{"text": "function res = le(A,B)\n%LE           Implements  A<=B  elementwise for long (refers only to midpoints)\n%\n\n% written  11/06/99     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%\n\n  C = A - B;\n  res = ( C.sign==-1 ) | all( C.mantissa==0 , 2);\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/long/@long/le.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.5999538518777853}}
{"text": "function list = shellSort(list)\n \n    N = numel(list);\n    increment = round(N/2);\n \n    while increment > 0  %loop until increment becomes 0\n \n        for i = (increment+1:N)\n            temp = list(i);\n            j = i;\n            while (j >= increment+1) && (list(j-increment) > temp)\n                list(j) = list(j-increment);\n                j = j - increment;\n            end\n \n            list(j) = temp;\n \n        end %for\n \n        if increment == 2 %This case causes shell sort to become insertion sort\n            increment = 1;\n        else\n            increment = round(increment/2.2);\n        end        \n    end %while\nend %shellSort\n", "meta": {"author": "TheAlgorithms", "repo": "MATLAB-Octave", "sha": "e150b77ad256de46c1ce3815c3d7945ac4fc28dc", "save_path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave", "path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave/MATLAB-Octave-e150b77ad256de46c1ce3815c3d7945ac4fc28dc/algorithms/sorting/shell_sort.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.5999538518777853}}
{"text": "%% im2patch\n% Below is a demonstration of the features of the |im2patch| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[F,V,C]=im2patch(M,IND,ptype);|\n\n%% Description\n% This function generates patch data for 3D images. The patch data is only\n% generated for the voxels specified by the indices (logic or linear\n% indices). The patch data is created according to the patch type desired\n% (e.g. voxel type of slice type).\n\n%% Examples\n\n%%\n% Plot settings\ncMap=parula(250);\nfaceAlpha1=1;\nfaceAlpha2=0.5;\nedgeColor1='none';\nedgeColor2='none';\nfontSize=15; \n\n%% Example: Introduction to using |im2patch| for voxel plotting\n% The voxel for which patch data is to be specified can be defined by\n% supplying linear indices or a logic array. \n\n% Simulating an image\nM=rand(3,5,7);\n% Example supplying linear indices, here all voxels\nindPatch=1:numel(M); \n\n%%\n% Creating patch data for voxel display\n[F,V,C]=im2patch(M,indPatch,'v'); \n\ncFigure;\ntitle('patch type: v');\nxlabel('J - columns');ylabel('I - rows'); zlabel('K - slices'); hold on;\ngpatch(F,V,C,'k',faceAlpha2);\ncolormap(cMap); caxis([min(M(:)) max(M(:))]); colorbar; \naxisGeom(gca,fontSize); camlight headlight;\ndrawnow;\n\n%%\n% Study the size of the face and vertex arrays to confirm that the patch\n% type |'v'| creates vertices and faces for each voxel. Shared vertices and\n% faces are not removed. This option requires the most memory. \ndisp(num2str(size(F)));\ndisp(num2str(size(V)));\n\n%%\n% Creating patch data for voxel display with shared vertices and faces\n% removed\n[F,V,C]=im2patch(M,indPatch,'vu'); \n\ncFigure;\ntitle('patch type: vu');\nxlabel('J - columns');ylabel('I - rows'); zlabel('K - slices'); hold on;\ngpatch(F,V,C,'k',faceAlpha2);\ncolormap(cMap); caxis([min(M(:)) max(M(:))]); colorbar; \naxisGeom(gca,fontSize); camlight headlight;\ndrawnow;\n\n%%\n% Study the size of the face and vertex arrays to confirm that the patch\n% type |'vu'| ensures that shared faces and vertices are not shared. Each\n% vertex and face is therefore unique. This saves memory with respect to\n% using the |'v'| patch type for voxel display. The figures look identical\n% except that shared faces may appear less dark when transparency is on\n% since now one one face is used. Color information is shared too\n% (averaged).\ndisp(num2str(size(F)));\ndisp(num2str(size(V)));\n\n%%\n% Creating patch data for voxel display with only non-shared faces and\n% vertices\n[F,V,C]=im2patch(M,indPatch,'vb'); \n\ncFigure;\ntitle('patch type: vb');\nxlabel('J - columns');ylabel('I - rows'); zlabel('K - slices'); hold on;\ngpatch(F,V,C,'k',faceAlpha2);\ncolormap(cMap); caxis([min(M(:)) max(M(:))]); colorbar; \naxisGeom(gca,fontSize); camlight headlight;\ndrawnow;\n\n%%\n% Study the size of the face and vertex arrays to confirm that the patch\n% type |'vb'| helps to plot only non-shared vertices and faces. \n% In the case of an enclosed shape filled with voxels thus only the\n% boundary faces are displayed. This path type appears no different than\n% the other is transparency is not on however it is much lighter on memory\n% than the above path types. \ndisp(num2str(size(F)));\ndisp(num2str(size(V)));\n\n%% Example: Introduction to using |im2patch| for slice plotting\n\ncFigure;\ntitle('patch type: si, sj, sk');\nxlabel('J - columns');ylabel('I - rows'); zlabel('K - slices'); hold on;\n\n%Setting up indices for I direction slices\nS=round(size(M,1)./2); %Selection of middle slice\nL_plot=false(size(M)); L_plot(S,:,:)=1;\nindPatch=find(L_plot);\n[F,V,C]=im2patch(M,indPatch,'si'); %Creating patch data for y mid-voxel slices\ngpatch(F,V,C);\n\n%Setting up indices for J direction slices\nS=round(size(M,2)./2); %Selection of middle slice\nL_plot=false(size(M)); L_plot(:,S,:)=1;\nindPatch=find(L_plot);\n[F,V,C]=im2patch(M,indPatch,'sj'); %Creating patch data for x mid-voxel slices\ngpatch(F,V,C);\n\n%Setting up indices for Z direction slices\nS=round(size(M,3)./2); %Selection of middle slice\nL_plot=false(size(M)); L_plot(:,:,S)=1;\nindPatch=find(L_plot);\n[F,V,C]=im2patch(M,indPatch,'sk'); %Creating patch data for z mid-voxel slices\ngpatch(F,V,C);\n\ncolormap(cMap); caxis([min(M(:)) max(M(:))]); colorbar; \naxisGeom(gca,fontSize); camlight headlight;\n\ndrawnow;\n\n%%\n% The path type s*u are simular to s* but use shared vertices\n\n%% Example: Comparison to standard MATLAB |imagesc| function and the patch type MATLAB functions |slice| and |pcolor|\n% The comparison is what motivates the choice of coordinate system for\n% im2patch i.e. that it is meant to aid in the visualization of image data\n% as is expected of image data. \n\ncFigure;\nsubplot(2,2,1);\ntitle('MATLAB imagesc function');\nxlabel('J - columns');ylabel('I - rows'); zlabel('K - slices'); hold on;\nimagesc(M(:,:,S));\ncolormap(cMap); caxis([min(M(:)) max(M(:))]);\naxisGeom(gca,fontSize); view(2);\n\nsubplot(2,2,2);\ntitle('MATLAB slice function');\nxlabel('J - columns');ylabel('I - rows'); zlabel('K - slices'); hold on;\nslice(M,[],[],S);\naxisGeom(gca,fontSize);\ncolormap(cMap); caxis([min(M(:)) max(M(:))]);\naxisGeom(gca,fontSize); view(2);\n\nsubplot(2,2,3);\ntitle('im2patch function');\nxlabel('J - columns');ylabel('I - rows'); zlabel('K - slices'); hold on;\ngpatch(F,V,C);\ncolormap(cMap); caxis([min(M(:)) max(M(:))]);\naxisGeom(gca,fontSize); view(2);\n\nsubplot(2,2,4);\ntitle('MATLAB pcolor function');\nxlabel('J - columns');ylabel('I - rows'); zlabel('K - slices'); hold on;\npcolor(M(:,:,S));\ncolormap(cMap); caxis([min(M(:)) max(M(:))]);\naxisGeom(gca,fontSize); view(2);\n\ndrawnow;\n\n%%\n% Note that the image size is wrong for the |slice| and |pcolor| commands.\n% This is because intensities appear to be defined on voxels vertices (and\n% are reinterpolated onto faces) for these functions instead of voxels\n% centres as should be the case for image data. \n\n%% Example: Creating and plotting combined voxel and slice patch data\n\n%%\n% Simulating 3D image\n[X,Y,Z]=meshgrid(linspace(-4.77,4.77,25));\nphi=(1+sqrt(5))/2;\nM=1/6*(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%%\n% Creating and plotting patch data. Last example illustrates the use of a\n% specific logic description (i.e. a mask) for the voxels of interest\n\ncFigure;\ntitle('Combined voxel and slice plotting');\nxlabel('J - columns');ylabel('I - rows'); zlabel('K - slices'); hold on;\n\n% Setting up indices for I direction slices\nS=round(size(M,1)./2); %Selection of middle slice\nL_plot=false(size(M)); L_plot(S,:,:)=1;\nindPatch=find(L_plot);\n[F,V,C]=im2patch(M,indPatch,'si'); %Creating patch data for y mid-voxel slices\ngpatch(F,V,C,'none',faceAlpha2);\n\n% Setting up indices for J direction slices\nS=round(size(M,2)./2); %Selection of middle slice\nL_plot=false(size(M)); L_plot(:,S,:)=1;\nindPatch=find(L_plot);\n[F,V,C]=im2patch(M,indPatch,'sj'); %Creating patch data for x mid-voxel slices\ngpatch(F,V,C,'none',faceAlpha2);\n\n% Setting up indices for K direction slices\nS=round(size(M,3)./2); %Selection of middle slice\nL_plot=false(size(M)); L_plot(:,:,S)=1;\nindPatch=find(L_plot);\n[F,V,C]=im2patch(M,indPatch,'sk'); %Creating patch data for z mid-voxel slices\ngpatch(F,V,C,'none',faceAlpha2);\n\n% Setting up indices for voxels to plot\nL_mask=M>-0.2 & M<0;\n[F,V,C]=im2patch(M,L_mask,'vb'); %Creating patch data for selection of high voxels\n\ngpatch(F,V,C);\ncolormap(cMap); colorbar; caxis([min(M(:)) max(M(:))]); \naxisGeom(gca,fontSize); camlight headlight;\ndrawnow;\n\n%% Example: Shrinking patch data through combination with |scalePatch| function\n\n% Using the function |scalePatch| patch data can be shrunk to aid\n% visualisation (can be a tool to avoid memory costly transparency for\n% instance).\n\n[Ev,Vv,Cv]=im2patch(M,L_mask,'h'); %This creates a hexahedral element for each voxel\n[Evs,Vvs]=scalePatch(Ev,Vv,0.5); %Apply voxel element scaling\n[Fvs,Cvs]=element2patch(Evs,Cv); %Convert to quad faces for plotting\n\n%%\n% Plotting the voxels\ncFigure;\ntitle('Scaled (shrunk) patch data');\nxlabel('J - columns');ylabel('I - rows'); zlabel('K - slices'); hold on;\ngpatch(Fvs,Vvs,Cvs);\ncolormap(cMap); colorbar; caxis([min(Cvs(:)) max(Cvs(:))]); \naxisGeom(gca,fontSize); camlight headlight;\ndrawnow;\n\n%% Example: Medical image data and coordinate manipulation due to voxel size\n\n% Get a 3D image\nload mri;\nM=squeeze(D); %example image data set\nv=2./[1,1,.4]; %example voxel size\n\n%%\n% The voxels to display can be specified as a list (vector) of voxels\n% numbers (linear indices) or using a mask (logic array).\n\n%Defining row, column and slice indicices for slice patching\nsliceIndexI=round(size(M,1)/2); %(close to) middle row\nsliceIndexJ=round(size(M,2)/2); %(close to) middle column\nsliceIndexK=round(size(M,3)/2); %(close to) middle slice\n\n%Defining \"masks\" i.e. logic arrays with ones for voxels of interest\nlogicSliceI=false(size(M)); \nlogicSliceI(sliceIndexI,:,:)=1;\nlogicSliceI=logicSliceI & M>0;\n\nlogicSliceJ=false(size(M)); \nlogicSliceJ(:,sliceIndexJ,:)=1;\nlogicSliceJ=logicSliceJ & M>0;\n\nlogicSliceK=false(size(M)); \nlogicSliceK(:,:,sliceIndexK)=1;\nlogicSliceK=logicSliceK & M>0;\n\n%Defining voxel indices for voxels of interest\nT_low=min(M(:))+((max(M(:))-min(M(:)))/10); %Threshold example\nlogicVoxels=(M>T_low);\nlogicVoxels(:,1:sliceIndexJ,:)=0;\n\n%%\n% Creating patch data\n% The patch data consists of a matrix array defining the faces, a matrix\n% array defining the vertices and a vector for the colour data. The\n% vertices are based on the image coordinates however they are formatted\n% as: [X(:) Y(:) Z(:)]. X relates to columns, Y to rows and Z to slices. \n% Use a function like |im2cart| , or |im2mrcart| to convert image to cartesian\n% coordinates. \n \n[Fv,Vv,Cv]=im2patch(M,logicVoxels,'vb'); \n[Fx,Vx,Cx]=im2patch(M,logicSliceJ,'sj');\n[Fy,Vy,Cy]=im2patch(M,logicSliceI,'si');\n[Fz,Vz,Cz]=im2patch(M,logicSliceK,'sk');\n\n% Convert image coordinates to cartesian coordinates\n[Vv(:,1),Vv(:,2),Vv(:,3)]=im2cart(Vv(:,2),Vv(:,1),Vv(:,3),v); \n[Vx(:,1),Vx(:,2),Vx(:,3)]=im2cart(Vx(:,2),Vx(:,1),Vx(:,3),v);\n[Vy(:,1),Vy(:,2),Vy(:,3)]=im2cart(Vy(:,2),Vy(:,1),Vy(:,3),v);\n[Vz(:,1),Vz(:,2),Vz(:,3)]=im2cart(Vz(:,2),Vz(:,1),Vz(:,3),v);\n\n%%\n% \ncFigure;\ntitle('MRI visualisation, slices and voxels in cartesian coordinates with aid of voxel size');\nxlabel('X (mm)');ylabel('Y (mm)'); zlabel('Z (mm)'); hold on;\ngpatch(Fv,Vv,Cv,edgeColor1,faceAlpha2);\ngpatch(Fx,Vx,Cx,edgeColor1,faceAlpha1);\ngpatch(Fy,Vy,Cy,edgeColor1,faceAlpha1);\ngpatch(Fz,Vz,Cz,edgeColor1,faceAlpha1);\ncolormap(gray(250)); colorbar; \naxisGeom(gca,fontSize); camlight headlight;\ndrawnow;\n\n%% Example: Combining colormap and RGB driven patch colours \n% N.B. The figure renderer might have to be set to OPENGL.\n\n%%\n% Convert voxels colouring to RGB type, here a simple conversion to a gray\n% scale description is used\nCv=(Cv*ones(1,3))./max(Cv(:)); \n\n%%\n% Plotting the voxels\n\ncFigure;\ntitle('MRI visualisation, slices and voxels, colormap and RGB driven respectively');\nxlabel('X (mm)');ylabel('Y (mm)'); zlabel('Z (mm)'); hold on;\n\n%RGB driven\ngpatch(Fv,Vv,Cv,edgeColor1,faceAlpha2);\n\n%Colormap driven\ngpatch(Fx,Vx,Cx,edgeColor1,faceAlpha1);\ngpatch(Fy,Vy,Cy,edgeColor1,faceAlpha1);\ngpatch(Fz,Vz,Cz,edgeColor1,faceAlpha1);\n\ncolormap(cMap); colorbar; \naxisGeom(gca,fontSize); camlight headlight;\ndrawnow;\n\n%% \n%\n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_im2patch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.5999538435237807}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% evalIFGT  Evaluate the density estimate using the \"improved\" Fast Gauss Transform\n%\n%   [e,b] = evalIFGT(X,Y,N [,Nc,rC]) -- eval likelihood (\"e\") of the points Y under\n%                       the density estimate X using N coefficients of the\n%                       \"improved\" Fast Gauss Transform; the value \"b\" is the bound\n%                       on the (absolute) error which could arise.\n%\n%  Optional arguments:\n%    Nc  -- # of clusters to use for \"X\", default is sqrt(Npoints) \n%    rC  -- Cutoff radius (in std deviations) to exclude contributions, default 3\n%\n% See: Yang, Duraiswami, Gumerov; \"Improved Fast Gauss Transform\", submitted to \n%         the Siam Journal of Scientific Computing, 2004\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [estimate,errbound] = evalIFGT(pp,q,Ncoeff,Nclusters,rCutoff)\n  p = kde(pp);\t% copy constructor to dodge later rescaling...\n  if (p.type ~= 0)  \n    error('Sorry -- FGT = fast Gauss transform; it needs Gaussian kernels');\n  end;\n  if (size(p.bandwidth,2)>2*p.N)\n    error('Sorry -- IFGT currently supports only uniform bandwidths');\n  end;\n  if (nargin<4) Nclusters = round(sqrt(getNpts(p))); end;\n  if (nargin<5) rCutoff = 3; end;  \n  if (isa(q,'kde')) qpts = getPoints(q); else qpts = q; end;\n  \n  BW = getBW(p,1); BWorig = BW;\n  if (any( BW - BW(1) ))   % CONVERT TO SINGLE, SCALAR BW:\n    p = rescale(p, 1./BW); %  if differ in dimensions, need to rescale\n    qpts = qpts .* repmat(1./BW,[1,size(qpts,2)]);\n    BW = 1;\n  else BW = BW(1);         % already scalar; can just drop other dim's\n  end;\n\n  [c,cPts,cWts,cWt,cRad] = fpClusterK(p,Nclusters);\n  %[c,cPts,cWts,cWt,cRad] = fpClusterR(p,sqrt(2)*BW);\n  coeff = findCoeff(c,cPts,cWts,cRad,BW,Ncoeff);\n  [estimate,errbound] = evalCoeff( qpts, c,coeff,Ncoeff,cWt,BW,cRad,rCutoff);\n\n  % Change norm. constant (due to rescaling operation)\n  scale = p.D*log(BW) - sum(log(BWorig));\n  estimate = estimate * exp(scale); errbound = errbound * exp(scale);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% fpCluster -- fast, \"farthest point\" clustering method\n%   cluster points of \"p\" into K clusters, described by \"centers\",\n%    \"clusters\" (cell array of pts to each cluster),\n%    cWeight (weight per cluster), and maximum radius of any cluster.\n%\nfunction [centers, clusters, weights, cWeight, radius] = fpClusterK(p, K)\n  points = getPoints(p); wts = getWeights(p);\n  [D,N] = size(points);\n  centers = zeros(D,K); clusters = cell(1,K); weights = cell(1,K);\n  assign = ones(1,N); dmin = zeros(1,N)+inf;\n  next = fix(rand(1)*N)+1;  % choose 1st center at random\n  for i=1:K\n    centers(:,i) = points(:, next);\n    d = points - repmat(centers(:,i),[1,N]);\n    d = sqrt(sum(d.^2,1));\n    F=find(d<dmin); dmin(F)=d(F); assign(F) = i;\n    [radius, next] = max(dmin); % next center is a farthest point\n  end;\n  cWeight = zeros(1,K);\n  for i=1:K\n    clusters{i}=points(:, find(assign == i) );\n    weights{i}=wts(:, find(assign == i) );\n    cWeight(i) = sum(weights{i}); %size(clusters{i},2) / N;\n  end;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Same thing but cluster until radius < rMax\nfunction [centers, clusters, weights, cWeight, radius] = fpClusterR(p, rMax)\n  points = getPoints(p); wts = getWeights(p);\n  [D,N] = size(points); K = N; centers = zeros(D,K);\n  assign = ones(1,N); dmin = zeros(1,N)+inf;\n  next = fix(rand(1)*N)+1;  % choose 1st center at random\n  i=0; radius = inf;\n  while (radius > rMax),\n    i=i+1; centers(:,i) = points(:, next);\n    d = points - repmat(centers(:,i),[1,N]);\n    d = sqrt(sum(d.^2,1));\n    F=find(d<dmin); dmin(F)=d(F); assign(F) = i;\n    [radius, next] = max(dmin); % next center is a farthest point\n  end;\n  K=i; centers = centers(:,1:K);\n  cWeight = zeros(1,K); clusters = cell(1,K); weights = cell(1,K);\n  for i=1:K\n    clusters{i}=points(:, find(assign == i) );\n    weights{i}=wts(:, find(assign == i) );\n    cWeight(i) = sum(weights{i}); %size(clusters{i},2) / N;\n  end;\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% findCoeff -- find the Taylor series coefficients of the Gaussian sum\n%   described by each cluster.\n%\nfunction coeff = findCoeff(centers, points, weights, radius, h, Nterms)\n  h = sqrt(2)*h;        % stupid transform...\n\n  Npart = length(points); coeff = cell(1,Npart); D = size(centers,1);\n  NptsTotal = 0;\n  Npts = zeros(1,Npart); for i=1:Npart, Npts(i) = size(points{i},2); end;\n  NptsTotal = sum(Npts);\n\n  for i=1:Npart\n    NptsI = Npts(i);\n    vals = ( points{i}-repmat(centers(:,i),[1,NptsI]) )/h;\n\n    Ncoeff = round(exp( sum(log(Nterms:Nterms+D-1))-sum(log(1:Nterms)) ));\n    coeffI = zeros(NptsI, Ncoeff);\n\n    start = 0; startNew = 1;\n    coeffI(:, start+1) = exp( -sum(vals.^2,1) )';\n    pos = ones(1,D); alpha = zeros(D,1);\n\n    for j=2:Nterms\n      Nprev = startNew - start;\n      Nadd = sum(Nprev-pos+1); alphaNew = zeros(D,Nadd);\n      m = 1; posNew(1) = m;\n      for k=1:D\n        for l=pos(k):Nprev\n          alphaNew(:,m) = alpha(:,l); alphaNew(k,m) = alphaNew(k,m)+1;\n          constFactor = 2  ./ prod(max(alphaNew(:,m),1));\n          coeffI(:,startNew+m) = vals(k,:)' .* coeffI(:,start+l) * constFactor;\n          m = m+1;\n        end;\n        if (k ~= D) posNew(k+1) = m; end;\n      end;\n      pos = posNew; alpha = alphaNew; start = startNew; startNew = start+Nadd;\n    end;\n    %coeffI = sum(coeffI,1)/NptsTotal;\n    coeffI = weights{i}*coeffI;\n    coeff{i} = coeffI;\n  end;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% evalCoeff -- evaluate the Taylor series at a number of new locations\n%   also returns an upper bound on the incurred error\n%\nfunction [est, err] = evalCoeff(locations,centers,coeff,Nterms,cWt,h,cRad,rCutoff)\n\n  h = sqrt(2)*h;\t% stupid transformation\n\n  Npts = size(locations,2); Npart = size(centers,2); D = size(locations,1);\n  est = zeros(1,Npts);\n  err = zeros(1,Npts);\n  for i=1:Npart  \n      coeffI = coeff{i};\n      vals = ( locations - repmat(centers(:,i),[1,Npts]) ) / h;\n      distance2 = sum(vals.^2,1);\n      PTS = find( distance2 < rCutoff^2);\n      PTSN = find( distance2 >= rCutoff^2);\n\n      start = 0; startNew = 1;\n      terms = zeros(length(PTS),size(coeffI,2));\n      terms(:,start+1) = exp( - distance2(PTS) )';\n      pos = ones(1,D); \n      for j=2:Nterms\n        Nprev = startNew - start;\n\tNadd = sum(Nprev-pos+1); \n\tm=1; posNew(1)=m;\n\tfor k=1:D\n\t  for l=pos(k):Nprev\n\t    terms(:,startNew+m) = vals(k,PTS)' .* terms(:,start+l);\n\t    m = m+1;\n\t  end;\n\t  if (k~=D) posNew(k+1) = m; end;\n\tend;\n\tpos = posNew; start = startNew; startNew = start+Nadd;\n      end;\n      est(PTS) = est(PTS) + (coeffI * terms');\n\n      % error bound addition for included points...  + Qin * 2^p/p! rhox^p rhoy^p\n      err(PTS)=err(PTS) + cWt(i)*exp( Nterms*log(2*rCutoff)- sum(log(1:Nterms)) + Nterms*log(cRad/h) );\n\n      % error bound addition for excluded points...  + Qin * exp(-rhoy^2+rhox^2)\n      err(PTSN)=err(PTSN) + cWt(i)*exp( - rCutoff^2 + (cRad/h)^2 );\n\n end; \n h = h / sqrt(2);\n \n est = est ./ (2*pi*h^2)^(D/2);\n err = err ./ (2*pi*h^2)^(D/2);\n\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/evalIFGT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5998993833664229}}
{"text": "classdef factorize\n%FACTORIZE an object-oriented method for solving linear systems\n% and least-squares problems, and for representing operations with the\n% inverse of a square matrix or the pseudo-inverse of a rectangular matrix.\n%\n% F = factorize(A) returns an object F that holds the factorization of a\n% non-singular matrix A.  x=F\\b then solves a linear system or a\n% least-squares problem.  S=inverse(F) or S=inverse(A) returns a factorized\n% representation of the inverse of A so that inverse(A)*b is mathematically\n% equivalent to inv(A)*b, but the former does not actually compute the\n% inverse of A.\n%\n% Example\n%\n%   F = factorize(A) ;      % LU, QR, or Cholesky factorization of A\n%   x = F\\b ;               % solve A*x=b; same as x=A\\b\n%   S = inverse (F) ;       % S represents the factorization of inv(A)\n%   x = S*b ;               % same as x = A\\b.\n%   S = A-B*inverse(D)*C    % efficiently computes the Schur complement\n%   S = A-B*inv(D)*C        % bad method for computing the Schur complement\n%   S = inverse(A) ; S(:,1) % compute just the first column of inv(A),\n%                           % without computing inv(A)\n%\n% If A is square, symmetric (Hermitian for the complex case), and has a\n% real positive diagonal, then use F=factorize(A,1).  If you know\n% otherwise, use F=factorize(A,0).  Using this option improves performance,\n% since otherwise this condition must be checked to choose between a\n% Cholesky or LU factorization.  The option is ignored if A is rectangular.\n%\n% For more details, type \"help factorize1\".\n% For a demo type \"fdemo\" or see the html/ directory.\n%\n% See also inverse, factorize1, mldivide, mrdivide, inv, pinv, linsolve\n\n% Copyright 2009, Timothy A. Davis, University of Florida\n\n    properties (SetAccess = protected)\n        % The factorize object holds a QR, LU, Cholesky factorization:\n        A = [ ] ;           % a copy of the input matrix\n        L = [ ] ;           % lower-triangular factor for LU and Cholesky\n        U = [ ] ;           % upper-triangular factor for LU\n        Q = [ ] ;           % Q factor for dense QR\n        R = [ ] ;           % R factor for QR\n        p = [ ] ;           % sparse row permutation matrix\n        q = [ ] ;           % sparse column permutation matrix\n        is_inverse = false ; % F represents the factorization of A or inv(A)\n        kind = 0 ;          % F is one of 8 kinds of factorizations\n    end\n\n    methods\n\n        function F = factorize (A,try_chol)\n\n            % factorize constructor: compute a factorization of A\n\n            if (ndims (A) > 2)\n                error ('Matrix must be 2D.') ;\n            end\n            [m n] = size (A) ;\n            F.A = A ;\n\n            if (m > n)\n\n                % QR factorization of A\n                if (issparse (A))\n                    % Q-less econonmy sparse QR: (A*q)'*(A*q) = R'*R\n                    q = sparse (colamd (A), 1:n, 1) ;\n                    R = qr (A*q, 0) ;\n                    F.q = q ;\n                    F.kind = 1 ;\n                else\n                    % dense economy QR factorization: A = Q*R\n                    [Q R] = qr (A,0) ;\n                    F.Q = Q ;\n                    F.kind = 2 ;\n                end\n                ok = (nnz (diag (R)) == n) ;\n                F.R = R ;\n\n            elseif (m < n)\n\n                % QR factorization of A'\n                if (issparse (A))\n                    % Q-less economy sparse QR: (p*A)*(p*A)' = R'*R\n                    C = A' ;\n                    p = sparse (1:m, colamd (C), 1) ;\n                    R = qr (C*p', 0) ;\n                    F.p = p ;\n                    F.kind = 3 ;\n                else\n                    % dense economy LQ factorization: A' = Q*R\n                    [Q R] = qr (A',0) ;\n                    F.Q = Q ;\n                    F.kind = 4 ;\n                end\n                ok = (nnz (diag (R)) == m) ;\n                F.R = R ;\n\n            else\n\n                % Cholesky or LU factorization of A\n                g = 1 ;\n                if (nargin == 1)\n                    % This is an expensive test, so skip it if the caller\n                    % already knows the matrix is a candidate for Cholesky.\n                    d = diag (A) ;\n                    try_chol = (all (d > 0) && nnz (imag (d)) == 0 && ...\n                        nnz (A-A') == 0) ;\n                end\n                if (try_chol)\n                    if (issparse (A))\n                        % sparse Cholesky factorization: q'*A*q = L*L'\n                        [L g q] = chol (A, 'lower') ;\n                    else\n                        % dense Cholesky factorization: A = R'*R\n                        [R g] = chol (A) ;\n                    end\n                end\n                % do an LU factorization if Cholesky failed or was skipped\n                ok = (g == 0) ;\n                if (ok)\n                    % Cholesky was successful\n                    if (issparse (A))\n                        F.L = L ;\n                        F.q = q ;\n                        F.kind = 5 ;\n                    else\n                        F.R = R ;\n                        F.kind = 6 ;\n                    end\n                else\n                    % need an LU factorization\n                    if (issparse (A))\n                        % sparse LU factorization: p*A*q = L*U\n                        [L U p q] = lu (A) ;\n                        F.q = q ;\n                        F.kind = 7 ;\n                    else\n                        % dense LU factorization: p*A = L*U\n                        [L U p] = lu (A, 'vector') ;\n                        p = sparse (1:n, p, 1) ;\n                        F.kind = 8 ;\n                    end\n                    F.L = L ;\n                    F.U = U ;\n                    F.p = p ;\n                    ok = (nnz (diag (U)) == n)  ;\n                end\n            end\n\n            if (~ok)\n                error ('Matrix is rank deficient.') ;\n            end\n        end\n    end\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/@factorize/factorize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5998993752469844}}
{"text": "function [textures] = getGLSZMtextures_temp(GLSZM)\n% -------------------------------------------------------------------------\n% function [textures] = getGLSZMtextures_temp(GLSZM)\n% -------------------------------------------------------------------------\n% DESCRIPTION:\n% This function computes texture features from an input Gray-Level Size\n% Zone Matrix (GLSZM).\n% -------------------------------------------------------------------------\n% REFERENCES:\n% [1] Galloway, M. M. (1975). Texture analysis using gray level run lengths. \n%     Computer Graphics and Image Processing, 4(2), 172\u2013179.\n% [2] Chu, A., Sehgal, C. M., & Greenleaf, J. F. (1990). Use of gray value \n%     distribution of run lengths for texture analysis. Pattern Recognition\n%     Letters, 11(6), 415-419.\n% [3] Dasarathy, B. V., & Holder, E. B. (1991). Image characterizations \n%     based on joint gray level-run length distributions. Pattern \n%     Recognition Letters, 12(8), 497-502.\n% [4] Thibault, G., Fertil, B., Navarro, C., Pereira, S., Cau, P., Levy, \n%     N., Mari, J.-L. (2009). Texture Indexes and Gray Level Size Zone \n%     Matrix. Application to Cell Nuclei Classification. In Pattern \n%     Recognition and Information Processing (PRIP) (pp. 140\u2013145).\n% -------------------------------------------------------------------------\n% INPUTS:\n% - GLSZM: Gray-Level Size Zone Matrix.\n%\n% ** 'GLSZM' should be the output from 'getGLSZM.m' **\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% - textures: Struture specifying the values of different GLSZM texture\n%             features as defined below.\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: January 2013\n% - Revision: May 2015\n% -------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015  Martin Vallieres\n%\n%    This package 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 package 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 package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\n\n% USEFUL MATRICES, VECTORS AND QUANTITIES\nsz = size(GLSZM); % Size of GLSZM\nnRuns = sum(GLSZM(:));\ncVect = 1:sz(2); rVect = 1:sz(1);% Row and column vectors\n[cMat,rMat] = meshgrid(cVect,rVect); % Column and row indicators for each entry of the GLSZM\npg = sum(GLSZM,2)'; % Gray-Level Run-Number Vector\npr = sum(GLSZM); % Run-Length Run-Number Vector\n\n\n% COMPUTATION OF TEXTURE FEATURES\n% 1. Small Zone Emphasis (SZE), Ref.[1,4]\ntextures.SZE = (pr*(cVect.^(-2))')/nRuns;\n\n% 2. Large Zone Emphasis (LZE), Ref.[1,4]\ntextures.LZE = (pr*(cVect.^2)')/nRuns;\n\n% 3. Gray-Level Nonuniformity (GLN), adapted from Ref.[1,4]\ntextures.GLN = sum(pg.^2)/nRuns;\n\n% 4. Zone-Size Nonuniformity (ZSN), adapted from Ref.[1,4]\ntextures.ZSN = sum(pr.^2)/nRuns;\n\n% 5. Zone Percentage (ZP), adapted from Ref.[1,4]\ntextures.ZP = nRuns/(pr*cVect');\n\n% 6. Low Gray-Level Zone Emphasis (LGZE), Ref.[2,4]\ntextures.LGZE = (pg*(rVect.^(-2))')/nRuns;\n\n% 7. High Gray-Level Zone Emphasis (HGZE), Ref.[2,4]\ntextures.HGZE = (pg*(rVect.^2)')/nRuns;\n\n% 8. Small Zone Low Gray-Level Emphasis (SZLGE), Ref.[3,4]\ntextures.SZLGE = sum(sum(GLSZM.*(rMat.^(-2)).*(cMat.^(-2))))/nRuns;\n\n% 9. Small Zone High Gray-Level Emphasis (SZHGE), Ref.[3,4]\ntextures.SZHGE = sum(sum(GLSZM.*(rMat.^2).*(cMat.^(-2))))/nRuns;\n\n% 10. Large Zone Low Gray-Level Emphasis (LZLGE), Ref.[3,4]\ntextures.LZLGE = sum(sum(GLSZM.*(rMat.^(-2)).*(cMat.^2)))/nRuns;\n\n% 11. Large Zone High Gray-Level Emphasis (LZHGE), Ref.[3,4]\ntextures.LZHGE = sum(sum(GLSZM.*(rMat.^2).*(cMat.^2)))/nRuns;\n\n\n% New features according to Ref.[4]\n% GLSZM = GLSZM./nRuns; % In the future, this operation will be applied at the beginning of the function\n% pg=sum(GLSZM,2)'; pr=sum(GLSZM);\nug = (pg*rVect')/(sz(1)*sz(2));\nur = (pr*cVect')/(sz(1)*sz(2));\n\n% 12. Gray-Level Variance (GLV), adapted from Ref.[4]\nGLV = 0;\nfor g = 1:sz(1)\n    for r = 1:sz(2)\n        GLV = GLV + (GLSZM(g,r)*g-ug)^2;\n    end\nend\ntextures.GLV = GLV/(sz(1)*sz(2));\n\n% 13. Zone-Size Variance (ZSV), adapted from Ref.[4]\nZSV = 0;\nfor g = 1:sz(1)\n    for r = 1:sz(2)\n        ZSV = ZSV + (GLSZM(g,r)*r-ur)^2;\n    end\nend\ntextures.ZSV = ZSV/(sz(1)*sz(2));\n\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/FEATURES_COMPUTATIONS/getGLSZMtextures_temp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5998993752469843}}
{"text": "function G=gauss2dmultislice(sizevec, m, s, a)\n% G=gauss2dmultislice(sizevec, m, s, a)\nlm=length(m);\nif length(s)<lm\n    s=repmat(s,lm); %all the sama sigma\nend\nif length(a)<lm\n    a=repmat(a,lm); %all the sama amplitude\nend\n\nG=zeros(sizevec);\nfor ii=1:sizevec(3)    \n    G(:,:,ii) = gauss2d(sizevec(1:2), m(ii,:), s(ii), a(ii));\nend", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/fitgauss/gauss2dmultislice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127455162774, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5998993594814777}}
{"text": "\nclear all; close all;\nI=imread('peppers.png');\nJ=rgb2gray(I);\nfigure;\nsubplot(121);\nimshow(J);\nsubplot(122);\nimcontour(J,3);", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/\u300aMATLAB\u56fe\u50cf\u5904\u7406\u300b\u6e90\u6587\u4ef6/\u672c\u4e66\u6e90\u6587\u4ef6/chap5/chap5_17.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5998969298721386}}
{"text": "% Description:\n%\n%     Create a design matrix for groups.\n%\n% Syntax:\n%\n%     [ X, terms ] = mG2X(groups, offset)\n%\n% Inputs:\n%\n%     groups  - [ N x G ] (int)  - columns of qualitative variables\n%     offset  - [ 1 x 1 ] (int)  - group offset index for terms\n%     options - [ 1 x P ] (cell) - see Details and Options\n%     columns - [ 1 x T ] (int)  - indices into columns of groups\n%\n% Outputs:\n%\n%     X     - [ N x M ] (double)\n%     terms - [ 1 x M ] (cell)\n%\n% Details:\n%\n%     By default, mG2X.m uses a canonical coding of the design matrix that \n%     includes the first level of each grouping variable in the intercept.\n%     This default coding may be replaced either by over-determined coding,\n%     which includes a column of ones and zeros for every level of every\n%     grouping variable, or by sigma-restricted coding, which estimates an\n%     overall mean and offsets from the overall mean for every level of every\n%     grouping variable, excluding the last level of each grouping variable.\n%\n% Options:\n%\n%     'over-determined'  - use over-determined coding for the design matrix\n%     'sigma-restricted' - use sigma-restricted coding for the design matrix\n%     'verbose'          - display extra information to the command window\n%\n% Examples:\n%\n% Notes:\n%\n% Author(s):\n%\n%     William Gruner (williamgruner@gmail.com)\n%\n% References:\n%\n% Acknowledgements:\n%\n%     Many thanks to Dr. Erik Erhardt and Dr. Elena Allen of the Mind Research\n%     Network (www.mrn.org) for their continued collaboration.\n%\n% Version:\n%\n%     $Author: williamgruner $\n%     $Date: 2010-04-12 07:14:07 -0600 (Mon, 12 Apr 2010) $\n%     $Revision: 494 $\n\nfunction [ X, terms ] = mG2X(groups, offset, options, columns)\n    \n    if ~exist('offset', 'var') || isempty(offset)\n        offset = 0;\n    end\n    \n    if ~exist('options', 'var')\n        options = cell(0);\n    end\n    \n    if ~exist('columns', 'var')\n        columns = 1 : size(groups, 2);\n    end\n    \n    terms = {};\n    X     = [];\n\n    if ~isempty(strmatch('verbose', options, 'exact'))\n        fprintf('\\n')\n    end\n\n    for i = columns\n        \n        [ B, I, J ] = unique(groups(:, i));\n        \n        if ~isempty(strmatch('verbose', options, 'exact'))\n            fprintf('Factor %d represents column %d of groups and has %d levels.\\n', ...\n                i + offset, i, length(B))\n        end\n        \n        if ~isempty(strmatch('over-determined', options, 'exact'))\n        \n            for j = 1 : length(B)\n                X(J ~= j, length(terms) + j) =  0;\n                X(J == j, length(terms) + j) =  1;\n            end\n        \n            for j = 1 : length(B)\n                terms{end + 1} = i + offset;\n            end            \n            \n        elseif ~isempty(strmatch('sigma-restricted', options, 'exact'))\n        \n            for j = 1 : length(B) - 1\n                X(J ~=         j, length(terms) + j) =  0;\n                X(J ==         j, length(terms) + j) =  1;\n                X(J == length(B), length(terms) + j) = -1;\n            end\n        \n            for j = 1 : length(B) - 1\n                terms{end + 1} = i + offset;\n            end            \n            \n        else\n            \n            for j = 2 : length(B) \n                X(J ~= j, length(terms) + j - 1) = 0;\n                X(J == j, length(terms) + j - 1) = 1;\n            end\n        \n            for j = 1 : length(B) - 1\n                terms{end + 1} = i + offset;\n            end            \n            \n        end\n        \n    end\n    \n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/27014-mancovan/mG2X.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5998969139874716}}
{"text": "function blas1_c_test05 ( )\n\n%*****************************************************************************80\n%\n%% TEST05 tests CDOTC.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 April 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 5;\n\n  x = [ ...\n     2.0 - 1.0 * i, ...\n    -4.0 - 2.0 * i, ...\n     3.0 + 1.0 * i, ...\n     2.0 + 2.0 * i, ...\n    -1.0 - 1.0 * i ];\n  y = [ ...\n    -1.0 + 0.0 * i, ...\n     0.0 - 3.0 * i, ...\n     4.0 + 0.0 * i, ...\n    -3.0 + 4.0 * i, ...\n    -2.0 + 0.0 * i ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST05\\n' );\n  fprintf ( 1, '  CDOTC computes the conjugated dot product of\\n' );\n  fprintf ( 1, '  two complex vectors.\\n' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  X =\\n' );\n  fprintf ( 1, '\\n' );\n  for j = 1 : n\n    fprintf ( 1, '  %6d  %10f  %10f\\n', j, real ( x(j) ), imag ( x(j) ) );\n  end\n\n  x_norm = cdotc ( n, x, 1, x, 1 );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The square of the norm of X, computed as\\n' );\n  fprintf ( 1, '  CDOTC(X,X) = %f  %f\\n', real ( x_norm ), imag ( x_norm ) );\n\n  xy_dot = cdotc ( n, x, 1, y, 1 );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Y = \\n' );\n  fprintf ( 1, '\\n' );\n  for j = 1 : n\n    fprintf ( 1, '  %6d  %10f  %10f\\n', j, real ( y(j) ), imag ( y(j) ) );\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The dot product X.Y* is %f  %f\\n', real ( xy_dot ), imag ( xy_dot ) );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/blas1_c/blas1_c_test05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.5998957040886659}}
{"text": "%% AKAZE local features matching\n%\n% In this demo, we will learn how to use AKAZE local features to detect and\n% match keypoints on two images. We will find keypoints on a pair of images\n% with given homography matrix, match them and count the number of inliers\n% (i.e. matches that fit in the given homography).\n%\n% Sources:\n%\n% * <https://docs.opencv.org/3.2.0/db/d70/tutorial_akaze_matching.html>\n% * <https://github.com/opencv/opencv/blob/3.2.0/samples/cpp/tutorial_code/features2D/AKAZE_match.cpp>\n% * <https://github.com/opencv/opencv/blob/3.2.0/samples/cpp/tutorial_code/xfeatures2D/LATCH_match.cpp>\n%\n\n%% Description\n%\n% You can find expanded version of this example\n% <https://github.com/pablofdezalc/test_kaze_akaze_opencv here>.\n%\n% We are going to use images 1 and 3 from _Graffity_ sequence of Oxford\n% dataset.\n%\n% <<https://docs.opencv.org/3.2.0/graf.png>>\n%\n% Homography is given by a 3-by-3 matrix shown below.\n%\n\n%% Code\n% Options\ninlier_threshold = 2.5;  % Distance threshold to identify inliers\nnn_match_ratio = 0.8;    % Nearest neighbor\n\n%%\n% Load grayscale images\nfnames = {\n    fullfile(mexopencv.root(), 'test', 'graf1.png')\n    fullfile(mexopencv.root(), 'test', 'graf3.png')\n};\nimgs = cell(size(fnames));\nfor i=1:numel(fnames)\n    % downloading if necessary\n    if exist(fnames{i}, 'file') ~= 2\n        disp('Downloading image...')\n        [~,name,ext] = fileparts(fnames{i});\n        baseURL = 'https://cdn.rawgit.com/opencv/opencv/3.2.0/samples/data/';\n        urlwrite([baseURL, name, ext], fnames{i});\n    end\n    % read image\n    imgs{i} = cv.imread(fnames{i}, 'Grayscale',true);\nend\n[img1, img2] = deal(imgs{:});\nwhos img1 img2\n\n%%\n% ground-truth homography\nH = [\n    7.6285898e-01  -2.9922929e-01   2.2567123e+02\n    3.3443473e-01   1.0143901e+00  -7.6999973e+01\n    3.4663091e-04  -1.4364524e-05   1.0000000e+00\n];\ndisplay(H)\n\n%%\n% Detect keypoints and compute descriptors using AKAZE\nif true\n    name = 'AKAZE';\n    akaze = cv.AKAZE();\n    [kpts1, desc1] = akaze.detectAndCompute(img1);\n    [kpts2, desc2] = akaze.detectAndCompute(img2);\nelse\n    % requires xfeatures2d from opencv_contrib\n    name = 'LATCH';\n    orb = cv.ORB('MaxFeatures',10000);\n    kpts1 = orb.detect(img1);\n    kpts2 = orb.detect(img2);\n    latch = cv.LATCH();\n    desc1 = latch.compute(img1, kpts1);\n    desc2 = latch.compute(img2, kpts2);\nend\nwhos kpts1 kpts2 desc1 desc2\n\n%%\n% Use brute-force matcher to find 2-nn matches.\n% We use Hamming distance, because AKAZE uses binary descriptor by default.\nmatcher = cv.DescriptorMatcher('BruteForce-Hamming');\nmatches = matcher.knnMatch(desc1, desc2, 2);\nwhos matches\n\n%%\n% Use 2-nn matches to find correct keypoint matches.\n% If the closest match is |ratio| closer than the second closest one, then the\n% match is correct.\nidx = cellfun(@(m) m(1).distance < nn_match_ratio * m(2).distance, matches);\nmatches = cellfun(@(m) m(1), matches(idx));\nkp1 = kpts1([matches.queryIdx] + 1);\nkp2 = kpts2([matches.trainIdx] + 1);\nwhos matches kp1 kp2\n\n%%\n% Check if our matches fit in the homography model.\n% If the distance from first keypoint's projection to the second keypoint\n% is less than threshold, then it it fits in the homography.\npts1 = cat(1, kp1.pt);\npts1(:,3) = 1;\npts1 = (H * pts1.').';\npts1 = bsxfun(@rdivide, pts1(:,1:2), pts1(:,3));\npts2 = cat(1, kp2.pt);\nd = sqrt(sum((pts1 - pts2).^2, 2));\nidx = d < inlier_threshold;\nwhos pts1 pts2\nfprintf('%d inliers\\n', nnz(idx));\n\n%%\n% We create a new set of matches for the inliers, because it is required\n% by the drawing function.\nkp1_good = kp1(idx);\nkp2_good = kp2(idx);\nmatches_good = matches(idx);\nfor i=1:numel(matches_good)\n    matches_good(i).queryIdx = i-1;\n    matches_good(i).trainIdx = i-1;\nend\nwhos kp1_good kp2_good matches_good\n\n%%\n% Show the result\nres = cv.drawMatches(img1, kp1_good, img2, kp2_good, matches_good);\nimshow(res), title(name)\n\n%%\n% Print some statistics\nfprintf('%s Matching Results:\\n', name);\nfprintf('Keypoints 1: %d\\n', numel(kpts1));\nfprintf('Keypoints 2: %d\\n', numel(kpts2));\nfprintf('Matches: %d\\n', numel(matches));\nfprintf('Inliers: %d\\n', numel(matches_good));\nfprintf('Inliers Ratio: %f\\n', numel(matches_good) / numel(matches));\n\n%% References\n%\n% * *(AKAZE)* Pablo F Alcantarilla, Jesus Nuevo, and Adrien Bartoli. \"Fast\n%   explicit diffusion for accelerated features in nonlinear scale spaces\".\n%   Trans. Pattern Anal. Machine Intell, 34(7):1281-1298, 2011.\n% * *(LATCH)* Gil Levi and Tal Hassner, \"LATCH: Learned Arrangements of\n%   Three Patch Codes\", arXiv preprint arXiv:1501.03719, 15 Jan. 2015\n%\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/akaze_match_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.5998771205125918}}
{"text": "function [max_min_diff, total_max_min_diff] = minimax(M)\n    max_rows = max(M');\n    min_rows = min(M');\n    max_min_diff = max_rows - min_rows;\n    total_max_min_diff = max(max_rows) - min(min_rows);\nend\n", "meta": {"author": "anishLearnsToCode", "repo": "introduction-to-programming-with-matlab", "sha": "4eb0dfab3f41b8a20d890e8d01a9e9b7463de410", "save_path": "github-repos/MATLAB/anishLearnsToCode-introduction-to-programming-with-matlab", "path": "github-repos/MATLAB/anishLearnsToCode-introduction-to-programming-with-matlab/introduction-to-programming-with-matlab-4eb0dfab3f41b8a20d890e8d01a9e9b7463de410/week-5/minimax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5998718532277759}}
{"text": "function [ftlb] = Btu2ftlb(Btu)\n% Convert energy or work from British thermal units to foot-pounds.\n% Chad A. Greene 2012\nftlb = Btu*778.16932495 ;", "meta": {"author": "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/Btu2ftlb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5998718432786629}}
{"text": "function Iout=scorfilt(I)\n% SPATIAL CORRELATION FILTER\n% \n% IN\n% I:        Image to filter, (RGB color or grayscale)\n% %\n% OUT\n% Iout:     Filtered image (double)\n%\n% EXAMPLE:\n%\n% %read image\n% imfile = fullfile(matlabroot,...\n%          'toolbox','images','imdemos','greens.jpg');\n% Io=im2double(imread(imfile));\n% %add noise\n% sigma_n=20; %noise std. dev.\n% randn('seed', 0);\n% I=Io+sigma_n/255*randn(size(Io));\n% figure('Name', 'input'), imshow(I);\n% %filter image\n% Iout = scorfilt(I);\n% figure('Name', 'output'), imshow(Iout);\n%\n% Author:   Carlos Estrada\n% Date:     May 25, 2012\n% Version   1.0\n%\n%% Configuration\nr_max=5;    %max. half-size window\nc=1/5;      %c 'neighborhood' constant default value\n\n%% labels\nI=im2double(I);\n[m n ch]=size(I);\n   \nif ch==1           %gray scale\n   maxI=max(I(:));\n   minI=min(I(:));\n   bins=255;   %quantization bins   \n   Ieq=uint8((bins-1)*histeq((I-minI)./(maxI-minI), bins))+1;\n\n   labels=zeros(m,n,'uint8');\n   N=0;\n   bin_mark=zeros(bins,1,'uint8');\n\n   for i=1:m   \n       for j=1:n       \n          id=Ieq(i,j);\n         if bin_mark(id)==0\n            N=N+1;\n            labels(i,j)=N;\n            bin_mark(id)=N;\n         else\n            labels(i,j)=bin_mark(id);\n         end\n       end\n   end\n\nelseif ch==3       %color\n%    maxI=max(I(:));\n%    minI=min(I(:));\n%    Ifit=(I-minI)/(maxI-minI);\n   bins=255;   %quantization bins\n   [labels, centers] = rgb2ind(I,bins,'nodither');\n   N=size(centers,1);\n   labels=labels+1;\nend\n\n%% adjacency matrix\nAcum=zeros(N,'uint32');\nfor i=1:m\n    for j=1:n\n       a=labels(i,j);\n       if i>1\n         e=labels(i-1,j);\n         Acum(a,e)=Acum(a,e)+1;\n       end\n       if j>1\n         e=labels(i,j-1);\n         Acum(a,e)=Acum(a,e)+1;\n       end\n    end\nend\nA=double(Acum+Acum');\n\nh4=sum(A,2);\nP=A./repmat(h4,1,N); %transition matrix\nQ=((P+P')./2)^2;\n%% neighborhood size\nteta=diag(P)'*h4./sum(h4);\nw=sqrt((1-teta)/teta);\nsigma_d=c*w;\nr=max(1,min(r_max,round(sigma_d*2.5)));\n%fprintf('\\tN: %d\\tw: %.4f\\tsigma_d: %.4f', N,w,sigma_d);\n%% compute Iout\nIout=zeros(m,n,ch);\n[x,y] = meshgrid(-r:r,-r:r);\nF=exp(-(x.^2 + y.^2)./(2*sigma_d^2));\n\nfor i=1:m   \n    iMin = max(i-r,1);\n    iMax = min(i+r,m);\n    di=iMin:iMax;\n    for j=1:n       \n       jMin = max(j-r,1);\n       jMax = min(j+r,n);\n       dj=jMin:jMax;\n       \n       a=labels(i,j);\n       l = labels(di,dj);\n       f=F(di-i+r+1,dj-j+r+1);\n       \n       w=Q(l(:),a).*f(:);\n       w=w./sum(w);\n       \n       y=I(di,dj,:);\n       \n       for cc=1:ch\n         yc=y(:,:,cc);\n         Iout(i,j,cc)=w'*yc(:);\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/39150-image-filter-by-spatial-correlation/scorfilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5998718312036518}}
{"text": "function d = fd04 ( p )\n\n%*****************************************************************************80\n%\n%% FD04 is a signed distance function for problem 4.\n%\n%  Modified:\n%\n%    11 September 2005\n%\n%  Parameters:\n%\n%    Input, real P(N,3), one or more points.\n%\n%    Output, real D(N), the signed distance of each point to the boundary of the region.\n%\n  d = sqrt ( sum ( p .^ 2, 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/distmesh_3d/fd04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5997981554943023}}
{"text": "function cfactor = SC_AmplitudeFactor(blk, page, edgewt, sccalib)\n% Amplitude Factor: ce_i with Edge Response Function (edgewt)\n% Reference: Improved scatter correction using adaptive scatter kernel superposition\n% Author: Yi Du (yi.du@hotmail.com)\n% Date: 2021-05-24\n\n%% group number\nngroup = length(sccalib.CalibrationResults.ObjectScatterModels.ObjectScatterModel);\n\n% Amplitude factor groups\ncfactor = [];\n\nfor ii=1:ngroup\n    tmp = sccalib.CalibrationResults.ObjectScatterModels.ObjectScatterModel{ii}.ObjectScatterFit;\n    % Amplitude Factor\n    % unit: mm - > cm\n    A = str2double(tmp.A.Text) / 10;\n    % unitless\n    alpha = str2double(tmp.alpha.Text);\n    beta = str2double(tmp.beta.Text);\n\n    % fill holes\n    term = (page + eps)./(blk + eps);\n    logterm = -log(term);\n    logterm(logterm<0) = NaN;\n    logterm = single(inpaint_nans(double(logterm), 2));\n    \n    % amplitude factor wi edge response function as well\n    cfactor(:,:,ii) = A .*edgewt .* (term).^(alpha) .* ( logterm ).^(beta);    \nend\n\nend\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/Utilities/IO/VarianCBCT/SC_AmplitudeFactor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5997981345726255}}
{"text": "%PARZENML Optimum smoothing parameter in Parzen density estimation.\n% \n%   H = PARZENML(A)\n% \n% INPUT\t\n%   A    Input dataset\n%\n% OUTPUT\n%   H    Scalar smoothing parameter (in case of crisp labels)\n%        Vector with smoothing parameters (in case of soft labels)\n%\n% DESCRIPTION\n% Maximum likelihood estimation for the smoothing parameter H in the \n% Parzen denstity estimation of the data in A. A leave-one out \n% maximum likelihood estimation is used. \n%\n% The dataset A can either be crisp or soft labeled. In case of crisp\n% labeling the class information is not used and a single smoothing \n% parameter is estimated. In case of soft labels a smoothing parameter\n% for every class is estimated and objects are weighted in relation to\n% their class weigthts (soft label value). \n% It may be profitable to scale the data before calling it. eg. \n% WS = SCALEM(A,'variance'); A = A*WS.\n% \n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% DATASETS, MAPPINGS, SCALEM, SELDAT, PARZENM, PARZENDC, PRPROGRESS\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: parzenml.m,v 1.11 2010/03/25 15:39:46 duin Exp $\n\nfunction h = parzenml(A,fid)\n\n\t\t\n\tif nargin < 2, fid = []; end\n\n\tif isdouble(A), A = prdataset(A); end\n\t\n\tA = testdatasize(A);\n\tA = testdatasize(A,'objects');\n\n\tif islabtype(A,'crisp')\n\t\th = parzenmlc(A,fid);\n\telseif islabtype(A,'soft')\n\t\th = parzenmls(A,fid);\n\telse\n\t\terror('Label type should be either ''crisp'' or ''soft''')\n\tend\n\t\n\treturn\n\t\nfunction h = parzenmlc(A,fid) %crisp version\n\n\t[m,k] = size(A);\n\tDD= distm(+A) + diag(1e70*ones(1,m));\n\tE = min(DD);\n\t\n\th1 = sqrt(max(E));    % initial estimate of h\n\tF1 = derlc(DD,E,h1,k); % derivative\n\n\tprprogress(fid,'parzenml:\\n');\n\tprprogress(fid,' %6.4f   %6.3e\\n',h1,F1);\n\tif abs(F1) < 1e-70 \n\t\th = h1;\n\t\tprwarning(4,'jump out\\n');\n\t\treturn;\n\tend\n\t\n\ta1 = (F1+m*k)*h1*h1;\n\th2 = sqrt(a1/(m*k));  % second guess\n\tF2 = derlc(DD,E,h2,k); % derivative\n\n\tprprogress(fid,' %6.4f   %6.3e\\n',h2,F2);\n\tif (abs(F2) < 1e-70) | (abs(1e0-h1/h2) < 1e-6) \n\t\th = h2;\n\t\tprwarning(4,'jump out\\n');\n\t\treturn\n\tend\n\t\n\t% find zero-point of derivative to optimize h^2\n\t% stop if improvement is small, or h does not change significantly\n\t\n\talf = 1;\n\tprwaitbar(100,'parzenml: Optimizing smoothing parameter',m > 100)\n\titer = 0;\n\twhile abs(1e0-F2/F1) > 1e-4 & abs(1e0-h2/h1) > 1e-3 & abs(F2) > 1e-70\n\t\titer = iter+1;\n\t\th3 = (h1*h1*h2*h2)*(F2-F1)/(F2*h2*h2-F1*h1*h1);\n\t\tif h3 < 0 % this should not happen\n\t\t\th3 = sqrt((F2+m*k)*h2*h2/(m*k));\n\t\telse\n\t\t\th3 = sqrt(h3);\n\t\tend\n\t\tprwaitbar(100,100-100*exp(-iter/10));\n\t\th3 = h2 +alf*(h3-h2);\n\t\tF3 = derlc(DD,E,h3,k);\n\t\tprprogress(fid,' %6.4f   %6.3e\\n',h3,F3);\n\t\tF1 = F2; F2 = F3;\n\t\th1 = h2; h2 = h3;\n\t\talf = alf*0.99; % decrease step size\n\tend\n\th = h2;\n\tprwaitbar(0);\n\nreturn\n\nfunction F = derlc(DD,E,h,k) % crisp version\n\t% computation of the likelihood derivative for Parzen density\n\t% given distances D and their object minima E (for increased accuracy)\n\tm = size(DD,1);\n\twarning off MATLAB:divideByZero;\n\t\tY = (DD-repmat(E,m,1))/(2*h*h); % correct for minimum distance to save accuracy\n\twarning on MATLAB:divideByZero;\n\tIY = find(Y<20);                % take small distance only, others don't contribute\n\tP = zeros(m,m);\n\tP(IY) = exp(-Y(IY));\n\tPP = sum(P,2)';\n\tFU = repmat(realmax,1,m);\n\tJ = find(PP~=0); \n\tFU(J) = 1./PP(J);\n\tFF = sum(DD.*P,2);\n\twarning off MATLAB:divideByZero;\n\t\tF = (FU*FF)./(h*h) - m*k;\n\twarning on MATLAB:divideByZero;\nreturn\n\nfunction h = parzenmls(A,fid) %soft version\n\n\tSS = gettargets(setlabtype(A,'soft'));\n\t[m,k,c] = getsize(A);\n\tDD= distm(+A) + diag(1e70*ones(1,m));\n\tE = min(DD);\n\th = zeros(c,1);\n\th0 = sqrt(max(E));    % initial estimate of h\n\t\n\t\n\ts = sprintf('parzenml: runover classes');\n\tprwaitbar(c,s,m > 100);\n\titer = 0;\n\t\n\tfor j=1:c\n\t\tprwaitbar(c,j)\n\t\tS = SS(:,j);\n\t\th1 = h0;\n\t\tF1 = derls(DD,E,h1,k,S); % derivative\n\n\t  prprogress(fid,'parzenml: class %i : \\n',j);\n\t\tprprogress(fid,' %6.4f   %6.3e\\n',h1,F1);\n\t\tif abs(F1) < 1e-70 \n\t\t\th(j) = h1;\n\t\t\tprwarning(4,'jump out\\n');\n\t\t\tbreak;\n\t\tend\n\t\n\t\ta1 = (F1+m*k)*h1*h1;\n\t\th2 = sqrt(a1/(m*k));  % second guess\n\t\tF2 = derls(DD,E,h2,k,S); % derivative\n\n\t\tprprogress(fid,' %6.4f   %6.3e\\n',h2,F2);\n\t\tif (abs(F2) < 1e-70) | (abs(1e0-h1/h2) < 1e-6) \n\t\t\th(j) = h2;\n\t\t\tprwarning(4,'jump out\\n');\n\t\t\tbreak;\n\t\tend\n\t\n\t\t% find zero-point of derivative to optimize h^2\n\t\t% stop if improvement is small, or h does not change significantly\n\t\n\t\t\n\t\tprwaitbar(100,'parzenml: Optimizing smoothing parameter',m > 100)\n\t\titer = 0;\n\t\talf = 1;\n\t\twhile abs(1e0-F2/F1) > 1e-4 & abs(1e0-h2/h1) > 1e-3 & abs(F2) > 1e-70\n\t\t\titer = iter+1;\n\t\t\tprwaitbar(100,100-100*exp(-iter/10));\n\t\t\th3 = (h1*h1*h2*h2)*(F2-F1)/(F2*h2*h2-F1*h1*h1);\n\t\t\tif h3 < 0 % this should not happen\n\t\t\t\th3 = sqrt((F2+m*k)*h2*h2/(m*k));\n\t\t\telse\n\t\t\t\th3 = sqrt(h3);\n\t\t\tend\n\t\t\th3 = h2 +alf*(h3-h2);\n\t\t\tF3 = derls(DD,E,h3,k,S);\n\t\t\tprprogress(fid,' %6.4f   %6.3e\\n',h3,F3);\n\t\t\tF1 = F2; F2 = F3;\n\t\t\th1 = h2; h2 = h3;\n\t\t\talf = alf*0.99; % decrease step size\n\t\tend\n\t\tprwaitbar(0)\n\t\th(j) = h2;\n\tend\n  prwaitbar(0)\nreturn\n\nfunction F = derls(DD,E,h,k,S) %soft version\n\t% computation of the likelihood derivative for Parzen density\n\t% given distances D and their object minima E (for increased accuracy)\n\t% S are the object weigths\n\tc = size(S,2);                  % number of classes\n\tm = size(DD,1);\n\tY = (DD-repmat(E,m,1))/(2*h*h); % correct for minimum distance to save accuracy\n\tIY = find(Y<20);                % take small distance only, others don't contribute\n\tF = 0;\n\tfor j=1:c\n\t\tP = zeros(m,m);\n\t\tP(IY) = exp(-Y(IY));\n\t\tPP = S(:,j)'*P';\n\t\tFU = repmat(realmax,1,m);\n\t\tJ = find(PP~=0);  \n\t\tFU(J) = S(J,j)'./PP(J);\n\t\tK = find(S(:,j)==0);\n\t\tFU(K) = zeros(1,length(K));\n\t\tFF = (DD.*P)*S(:,j);\n\t\tF = F + (FU*FF)./(h*h);\n\tend\n\tF = F - sum(S(:))*k;\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/parzenml.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5997981317391337}}
{"text": "function [cc] = oz2cc(oz)\n% Convert volume from US liquid ounces to cubic centimeters. \n% Chad Greene 2012\ncc = oz*29.573529563;", "meta": {"author": "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/oz2cc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424528443252, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5997893955503543}}
{"text": "function [ Q, sumQ] = OffpolicyQlearning150816( qldata3 , gamma, alpha, numtraces)\n% OFF POLICY Q LEARNING\n\n%initialisation of variables\nsumQ=zeros(numtraces,1);  %record sum of Q after each iteration\nnact=numel(unique(qldata3(:,3)))-1;   %nr of actions\nncl=numel(unique(qldata3(:,2)));\nQ=zeros (ncl, nact);  \nmaxavgQ=1;\nmodu=100;\nlisti=find(qldata3(:,1)==1);   %position of 1st step of each episodes in dataset\nnrepi=numel(listi);  %nr of episodes in the dataset\njj=1;\n\n for j=1:numtraces\n    \n    \n    i=listi(floor(rand()*(nrepi-2))+1);  %pick one episode randomly (not the last one!)\n    trace = [];\n    \n    while qldata3(i+1,1)~=1 \n    S1=qldata3(i+1,2);\n    a1=qldata3(i+1,3);\n    r1=qldata3(i+1,4);\n     step = [ r1, S1, a1 ];\n     trace = [trace ; step];\n    i=i+1;\n    end\n\n    tracelength = length(trace(:,1));\n    return_t = trace(tracelength,1); % get last reward as return for penultimate state and action.\n    \n    for t=tracelength-1:-1:1       %Step through time-steps in reverse order\n        s = trace(t,2); % get state index from trace at time t\n        a = trace(t,3); % get action index\n        Q(s,a) = (1-alpha)*Q(s,a) + alpha*return_t; % update Q.\n        return_t = return_t*gamma + trace(t,1); % return for time t-1 in terms of return and reward at t\n    end\n    \n     sumQ(jj,1)=sum(sum(Q));\n     jj=jj+1;\n     \n if mod(j,500*modu)==0  %check if can stop iterating (when no more improvement is seen)\n%      sumQ(jj,1)=sum(sum(Q));\n%      jj=jj+1;\n     s=mean(sumQ(j-49999:j));\n     d=(s-maxavgQ)/maxavgQ;\n     if abs(d)<0.001\n         break   %exit routine\n     end\n     maxavgQ=s;\n end\n \n\n end\n\n sumQ(jj:end)=[];\n \n \nend\n\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/OffpolicyQlearning150816.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5997893900427607}}
{"text": "% VL_TEST_IMWBACKWARDMX  Test: imwbackwardmx\n\nI = vl_test_pattern(102) ;\n\nfigure(1) ; clf ;\nimagesc(I) ;\ncolormap(gray(256)) ;\naxis equal ; axis off ;\n\n[M,N] = size(I) ;\nur    = linspace(-N/2, N/2, N) ;\nvr    = linspace(-M/2, M/2, M) ;\n[u,v] = meshgrid(ur,vr) ;\n\nfor s=.75*(1+cos(linspace(0,2*pi,100)))/2+.25\n  up = (cos(s-1)*u - sin(s-1)*v) / s ;\n  vp = (sin(s-1)*u + cos(s-1)*v) / s ;\n  J = vl_imwbackward(ur,vr,vl_imsmooth(I,1/s*.5),up,vp) ;\n  imagesc(J) ; drawnow ;\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/SIFTransac/vlfeat/toolbox/test/vl_test_imwbackwardmx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5997893799464035}}
{"text": "function wcoef = FWT_PO(x,L,qmf)\n% FWT_PO -- Forward Wavelet Transform (periodized, orthogonal)\n%  Usage\n%    wc = FWT_PO(x,L,qmf)\n%  Inputs\n%    x    1-d signal; length(x) = 2^J\n%    L    Coarsest Level of V_0;  L << J\n%    qmf  quadrature mirror filter (orthonormal)\n%  Outputs\n%    wc    1-d wavelet transform of x.\n%\n%  Description\n%    1. qmf filter may be obtained from MakeONFilter   \n%    2. usually, length(qmf) < 2^(L+1)\n%    3. To reconstruct use IWT_PO\n%\n%  See Also\n%    IWT_PO, MakeONFilter\n%\n  [n,J] = dyadlength(x) ;\n  wcoef = zeros(1,n) ;\n  beta = ShapeAsRow(x);  %take samples at finest scale as beta-coeffts\n  for j=J-1:-1:L\n       alfa = DownDyadHi(beta,qmf);\n       wcoef(dyad(j)) = alfa;\n       beta = DownDyadLo(beta,qmf) ;  \n  end\n  wcoef(1:(2^L)) = beta;\n  wcoef = ShapeLike(wcoef,x);\n\n%\n% Copyright (c) 1993. Iain M. Johnstone\n%     \n    \n    \n\n    \n \n \n%\n%  Part of Wavelab Version 850\n%  Built Tue Jan  3 13:20:40 EST 2006\n%  This is Copyrighted Material\n%  For Copying permissions see COPYING.m\n%  Comments? e-mail wavelab@stat.stanford.edu \n", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/FuncRegistry/UserFunctions/FWT_PO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5997893790275731}}
{"text": "function cond = condition_linpack ( n, a )\n\n%*****************************************************************************80\n%\n%% CONDITION_LINPACK estimates the L1 condition number of a 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%    For the system A * X = B, relative perturbations in A and B\n%    of size EPSILON may cause relative perturbations in X of size\n%    EPSILON*RCOND.\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%    Original FORTRAN77 version by Dongarra, Bunch, Moler, Stewart.\n%    MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Dongarra, Bunch, Moler, Stewart,\n%    LINPACK User's Guide,\n%    SIAM, 1979\n%\n%  Parameters:\n%\n%    Input, integer N, the order of the matrix A.\n%\n%    Input, real A(N,N), a matrix to be factored.\n%\n%    Output, real COND, an estimate of the condition number of A.\n%\n\n%\n%  Compute the L1 norm of A.\n%\n  anorm = norm ( a, 1 );\n%\n%  Compute the LU factorization.\n%\n  [ a_lu, pivot, info ] = r8ge_fa ( n, a );\n%\n%  COND = norm(A) * (estimate of norm(inverse(A))) \n%\n%  estimate of norm(inverse(A)) = norm(Z) / norm(Y)\n%\n%  where\n%    A * Z = Y\n%  and\n%    A' * Y = E\n%\n%  The components of E are chosen to cause maximum local growth in the\n%  elements of W, where U'*W = E.  The vectors are frequently rescaled\n%  to avoid overflow.\n%\n%  Solve U' * W = E.\n%\n  ek = 1.0;\n  z(1:n,1) = 0.0;\n\n  for k = 1 : n\n\n    if ( z(k,1) ~= 0.0 )\n      ek = - r8_sign ( z(k,1) ) * abs ( ek );\n    end\n\n    if ( abs ( a_lu(k,k) ) < abs ( ek - z(k,1) ) )\n      s = abs ( a_lu(k,k) ) / abs ( ek - z(k,1) );\n      z(1:n,1) = s * z(1:n,1);\n      ek = s * ek;\n    end\n\n    wk = ek - z(k,1);\n    wkm = -ek - z(k,1);\n    s = abs ( wk );\n    sm = abs ( wkm );\n\n    if ( a_lu(k,k) ~= 0.0 )\n      wk = wk / a_lu(k,k);\n      wkm = wkm / a_lu(k,k);\n    else\n      wk = 1.0;\n      wkm = 1.0;\n    end\n\n    if ( k + 1 <= n )\n\n      for j = k + 1 : n\n        sm = sm + abs ( z(j,1) + wkm * a_lu(k,j) );\n        z(j,1) = z(j,1) + wk * a_lu(k,j);\n        s = s + abs ( z(j,1) );\n      end\n\n      if ( s < sm )\n        t = wkm - wk;\n        wk = wkm;\n        z(k+1:n,1) = z(k+1:n,1) + t * a_lu(k,k+1:n)';\n      end\n\n    end\n\n    z(k,1) = wk;\n\n  end\n\n  t = sum ( abs ( z(1:n,1) ) );\n  z(1:n,1) = z(1:n,1) / t;\n%\n%  Solve L' * Y = W\n%\n  for k = n : -1 : 1\n\n    z(k,1) = z(k,1) + a_lu(k+1:n,k)' * z(k+1:n,1);\n\n    t = abs ( z(k,1) );\n\n    if ( 1.0 < t )\n      z(1:n,1) = z(1:n,1) / t;\n    end\n\n    l = pivot(k);\n\n    t = z(l,1);\n    z(l,1) = z(k,1);\n    z(k,1) = t;\n\n  end\n\n  z(1:n,1) = z(1:n,1) / sum ( abs ( z(1:n,1) ) );\n\n  ynorm = 1.0;\n%\n%  Solve L * V = Y.\n%\n  for k = 1 : n\n\n    l = pivot(k);\n\n    t = z(l,1);\n    z(l,1) = z(k,1);\n    z(k,1) = t;\n\n    z(k+1:n,1) = z(k+1:n,1) + t * a_lu(k+1:n,k);\n\n    if ( 1.0 < abs ( z(k,1) ) )\n      ynorm = ynorm / abs ( z(k,1) );\n      z(1:n) = z(1:n) / abs ( z(k,1) );\n    end\n\n  end\n\n  s = sum ( abs ( z(1:n,1) ) );\n  z(1:n,1) = z(1:n,1) / s;\n  ynorm = ynorm / s;\n%\n%  Solve U * Z = V.\n%\n  for k = n : -1 : 1\n\n    if ( abs ( a_lu(k,k) ) < abs ( z(k,1) ) )\n      s = abs ( a_lu(k,k) ) / abs ( z(k,1) );\n      z(1:n,1) = s * z(1:n,1);\n      ynorm = s * ynorm;\n    end\n\n    if ( a_lu(k,k) ~= 0.0 )\n      z(k,1) = z(k,1) / a_lu(k,k);\n    else\n      z(k,1) = 1.0;\n    end\n\n    z(1:k-1,1) = z(1:k-1,1) - a_lu(1:k-1,k) * z(k,1);\n\n  end\n%\n%  Normalize Z in the L1 norm.\n%\n  s = 1.0 / sum ( abs ( z(1:n,1) ) );\n  z(1:n,1) = s * z(1:n,1);\n  ynorm = s * ynorm;\n\n  cond = anorm / ynorm;\n\n  return\nend\n", "meta": {"author": "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_linpack.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5997893738262565}}
{"text": "%JSINGU Show the linearly dependent joints in a Jacobian matrix\n%\n% JSINGU(J) displays the linear dependency of joints in a Jacobian matrix.\n% This dependency indicates joint axes that are aligned and causes singularity.\n%\n% See also SerialLink.jacobn.\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\nfunction jsingu(J)\n\n    % convert to row-echelon form\n    [R, jb] = rref(J);\n\n    depcols = setdiff( 1:numcols(J), jb);\n\n    fprintf('%d linearly dependent joints:\\n', length(depcols));\n    for d=depcols\n        fprintf('  q%d depends on: ', d)\n        for k=find(R(:,d))\n            fprintf('q%d ', k);\n        end\n        fprintf('\\n');\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/jsingu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5997893686249397}}
{"text": "function pass = test_curl( pref ) \n\n% Grab some preferences\nif ( nargin == 0 )\n    pref = chebfunpref();\nend\ntol = 1e2*pref.techPrefs.chebfuneps;\n\n% Example 1 : (0,x,xy)\nVx = ballfun(@(x,y,z)0);\nVy = ballfun(@(r,lam,th)r.*sin(th).*cos(lam), 'spherical');\nVz = ballfun(@(r,lam,th)r.*sin(th).*cos(lam).*r.*sin(th).*sin(lam), 'spherical');\nV = ballfunv(Vx,Vy,Vz);\nW = curl(V);\nExactx = ballfun(@(r,lam,th)r.*sin(th).*cos(lam), 'spherical');\nExacty = ballfun(@(r,lam,th)-r.*sin(th).*sin(lam), 'spherical');\nExactz = ballfun(@(r,lam,th)1, 'spherical');\nExact = ballfunv(Exactx,Exacty,Exactz);\npass(1) = norm(W-Exact)<tol;\n\nif (nargout > 0)\n    pass = all(pass(:));\nend\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/ballfunv/test_curl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5997893634236229}}
{"text": "function [F,F_r,F_u] = odo3(F,u)\n\n% ODO3 3D Odometry evolution.\n%   F = ODO3(F,U) performs one step on the pose F of a vehicle, given\n%   odometry increments U=[DX;DV] in robot frame.\n%   - F is a frame structure (see FRAME).\n%   - Position increment DX is given in robot frame F.\n%   - Orientation increment DV is given as a Rotation Vector in robot frame F.\n%\n%   [F,F_r,F_u] = ODO3(F,U) gives the full Jacobians wrt state and odometry\n%   inputs.\n%\n%   See also FRAME, V2Q, QPROD, QUATERNION.\n\n%   Copyright 2005-2009 Joan Sola @ LAAS-CNRS.\n\ndv = u(4:6);\ndx = u(1:3);\n\nif nargout == 1\n\n    x = fromFrame(F,dx); % Position update\n\n    q  = F.x(4:end);\n    q2 = qProd(q,v2q(dv)); % quaternion update\n\n    F.x = [x;q2]; % frame update\n\n\nelse  % Jacobians\n\n    [x,X_r,X_dx] = fromFrame(F,dx); % Position update and jacobians\n\n    q               = F.x(4:end);\n    [dq,DQ_dv]      = v2q(dv);\n    [q2,Q2_q,Q2_dq] = qProd(q,dq); % quaternion update\n    Q2_dv           = Q2_dq*DQ_dv;\n\n    F.x = [x;q2]; % frame update\n\n    F_r  = [X_r;zeros(4,3) Q2_q];\n    F_u  = [X_dx zeros(3,3);zeros(4,3) Q2_dv];\nend\n\nF = updateFrame(F);\n\nreturn\n\n%% Jacobians\n\nsyms x y z a b c d real\nsyms dx dy dz dp dq dr real\nFi.x=[x;y;z;a;b;c;d];\nDx = [dx;dy;dz];\nDv = [dp;dq;dr];\nu  = [Dx;Dv];\n\nFi = updateFrame(Fi);\n\n[F,F_r,F_u] = odo3(Fi,u);\n\nF_rs = jacobian(F.x,Fi.x);\nF_us = jacobian(F.x,[Dx;Dv]);\n\nsimplify(F_r-F_rs)\nsimplify(F_u-F_us)\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 <http://www.gnu.org/licenses/>.\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/Kinematics/odo3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5997893634236229}}
{"text": "function pde = hyperIntf(am,ap,bm,bp,r,x0,y0,z0)\n%% USAGE: polynomial solution for Poisson equation\n%  Last Modified: 02/21/2020 by Xu Zhang\n\n%% PDE Structure\npde = struct('intf',@intf,...\n    'exactu1',@exactu1,'exactu2',@exactu2,'exactu3',@exactu3,...\n    'um1',@um1,'um2',@um2,'um3',@um3,'up1',@up1,'up2',@up2,'up3',@up3,...\n    'Dxu',@Dxu,'Dxum',@Dxum,'Dxup',@Dxup,'Dyu',@Dyu,...\n    'Dyum',@Dyum,'Dyup',@Dyup,'Dzu',@Dzu,'Dzum',@Dzum,'Dzup',@Dzup,...\n    'f1',@f1,'f2',@f2,'f3',@f3,...\n    'fm1',@fm1,'fm2',@fm2,'fm3',@fm3,...\n    'fp1',@fp1,'fp2',@fp2,'fp3',@fp3,...\n    'A',@A,'Am',@Am,'Ap',@Ap,'one',@one,...\n    'B',@B,'Bm',@Bm,'Bp',@Bp);\n\npde.am = am;\npde.ap = ap;\npde.bm = bm;\npde.bp = bp;\n%% interface function\n    function u = intf(x,y,z)\n        u = ((x-x0).^2 + (y-y0).^2 - (z-z0).^2)-r;\n    end\n\n%% exact solution\n    function u = exactu1(x,y,z)\n        u = um1(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = up1(x(id),y(id),z(id));\n    end\n    function u = exactu2(x,y,z)\n        u = um2(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = up2(x(id),y(id),z(id));\n    end\n    function u = exactu3(x,y,z)\n        u = um3(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = up3(x(id),y(id),z(id));\n    end\n    coef1 = 1; coef2 = 0; coef3 = 1;\n    function u = um1(x,y,z)\n        u = coef1*(z-z0) + coef3*(x-x0)/bm + coef2*intf(x,y,z).*(x-x0)/am;\n    end\n    function u = um2(x,y,z)\n        u =                coef3*(y-y0)/bm + coef2*intf(x,y,z).*(y-y0)/am;\n    end\n    function u = um3(x,y,z)\n        u = coef1*(x-x0) - coef3*(z-z0)/bm + coef2*intf(x,y,z).*(z-z0)/am;\n    end\n    function u = up1(x,y,z)\n        u = coef1*(z-z0) + coef3*(x-x0)/bp + coef2*intf(x,y,z).*(x-x0)/ap;\n    end\n    function u = up2(x,y,z)\n        u =                coef3*(y-y0)/bp + coef2*intf(x,y,z).*(y-y0)/ap;\n    end\n    function u = up3(x,y,z)\n        u = coef1*(x-x0) - coef3*(z-z0)/bp + coef2*intf(x,y,z).*(z-z0)/ap;\n    end\n%% Boundary Function\n    function u = gD1(x,y,z)\n        u = exactu1(x,y,z);\n    end\n    function u = gD2(x,y,z)\n        u = exactu2(x,y,z);\n    end\n    function u = gD3(x,y,z)\n        u = exactu3(x,y,z);\n    end\n%% Derivative of the exact solution\n    function u = Dxu(x,y,z)\n        u = Dxum(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Dxup(x(id),y(id),z(id));\n    end\n    function u = Dyu(x,y,z)\n        u = Dyum(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Dyup(x(id),y(id),z(id));\n    end\n    function u = Dzu(x,y,z)\n        u = Dzum(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Dzup(x(id),y(id),z(id));\n    end\n    function u = Dxum(x,y,z)\n        u = 4*(y-y0).*(z-z0)/am*coef2;\n    end\n    function u = Dyum(x,y,z)\n        u = -4*(x-x0).*(z-z0)/am*coef2;\n    end\n    function u = Dzum(x,y,z)\n        u = zeros(size(x));\n    end\n    function u = Dxup(x,y,z)\n        u = 4*(y-y0).*(z-z0)/ap*coef2;\n    end\n    function u = Dyup(x,y,z)\n        u = -4*(x-x0).*(z-z0)/ap*coef2;\n    end\n    function u = Dzup(x,y,z)\n        u = zeros(size(x));\n    end\n\n%% right hand side function\n    function u = f1(x,y,z)\n        u = fm1(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = fp1(x(id),y(id),z(id));\n    end\n    function u = f2(x,y,z)\n        u = fm2(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = fp2(x(id),y(id),z(id));\n    end\n    function u = f3(x,y,z)\n        u = fm3(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = fp3(x(id),y(id),z(id));\n    end\n\n    function u = fm1(x,y,z)\n        u = 4*(x-x0)*coef2 + bm*um1(x,y,z);\n    end\n    function u = fm2(x,y,z)\n        u = 4*(y-y0)*coef2 + bm*um2(x,y,z);\n    end\n    function u = fm3(x,y,z)\n        u = -8*(z-z0)*coef2 + bm*um3(x,y,z);\n    end\n    function u = fp1(x,y,z)\n        u = 4*(x-x0)*coef2 + bp*up1(x,y,z);\n    end\n    function u = fp2(x,y,z)\n        u = 4*(y-y0)*coef2 + bp*up2(x,y,z);\n    end\n    function u = fp3(x,y,z)\n        u = -8*(z-z0)*coef2 + bp*up3(x,y,z);\n    end\n\n%% Diffusion coefficient function\n    function u = A(x,y,z)\n        u = Am(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Ap(x(id),y(id),z(id));\n    end\n    function u = Am(x,y,z)\n        u = am*ones(size(x));\n    end\n    function u = Ap(x,y,z)\n        u = ap*ones(size(x));\n    end\n\n%% Mass coefficient function\n    function u = B(x,y,z)\n        u = Bm(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Bp(x(id),y(id),z(id));\n    end\n    function u = Bm(x,y,z)\n        u = bm*ones(size(x));\n    end\n    function u = Bp(x,y,z)\n        u = bp*ones(size(x));\n    end\n\n%% Other function\n    function u = one(x,y,z)\n        u = ones(size(x));\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/research/IVEM/hyperIntf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5997893606698259}}
{"text": "function loops=extractloops(edges)\n%\n% loops=extractloops(edges)\n%\n% extract individual loop or polyline segment from a collection of edges\n%\n% author: Qianqian Fang, <q.fang at neu.edu>\n% date: 2007/11/21\n%\n% input:   \n%    edges:  two column matrix recording the starting/ending \n%             points of all edge segments\n%\n% output:\n%    loops:  output, a single vector separated by NaN, each segment\n%             is a 3D polyline or loop consisted of node IDs\n%\n% example:\n%    edges=[1 2;2 3;1 4;3 4;7 3;1 9;5 6;6 7;10 9; 8 10;1 8;9 3;11 11;11 12];\n%    loops=extractloops(edges)\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nloops=[];\nedges(edges(:,1)==edges(:,2),:)=[]; % remove degenerated edges\nloops=[loops,edges(1,:)];\nloophead=edges(1,1);\nloopend=edges(1,end);\nedges(1,:)=[];\n\nwhile(~isempty(edges))\n    idx=[find(edges(:,1)==loopend)',find(edges(:,2)==loopend)'];\n    if(length(idx)>1) % when a node with multiple connection found\n        idx=idx(1);   % take the first connection and continue\n    end\n    if(isempty(idx)) % when an open-line segment gets to one end\n        % when both open ends are found\n        if(isempty([find(edges(:,1)==loophead)',find(edges(:,2)==loophead)']))\n            loops=[loops,nan];\n            loops=[loops,edges(1,:)];\n            loophead=edges(1,1);\n            loopend=edges(1,end);\n            edges(1,:)=[];\n        else % only the first open end is found, flip and trace the other\n            [loophead, loopend]=deal(loopend, loophead);\n            lp=fliplr(loops);\n            seg=find(isnan(lp),1);\n            if(isempty(seg))\n                loops=lp;\n            else\n                loops=[loops(1:end-seg(1)+1) lp(1:seg(1)-1)];\n            end\n        end\n        continue;    \n    end\n    if(length(idx)==1) % tracing along a single line thread\n        idx=idx(1);\n        ed=edges(idx,:);\n        ed(ed==loopend)=[];\n        newend=ed(1);\n        if(newend==loophead)  % when a loop is found\n            loops=[loops loophead nan];\n            edges(idx,:)=[];\n            if(size(edges,1)==0) break; end\n            loops=[loops,edges(1,:)];\n            loophead=edges(1,1);\n            loopend=edges(1,end);\n            edges(1,:)=[];\n            continue;\n        else\n            loops=[loops,newend];\n        end\n        loopend=newend;\n        edges(idx,:)=[];\n    end\nend\n    \n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/extractloops.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.5997881386319869}}
{"text": "function a_inverse = r8ge_inverse ( n, a_lu, pivot )\n\n%*****************************************************************************80\n%\n%% R8GE_INVERSE computes the inverse of a matrix factored by R8GE_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%    R8GE_INVERSE is a simplified standalone version of the LINPACK routine\n%    R8GEDI.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    20 March 2004\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the order of the matrix A.\n%\n%    Input, real A_LU(N,N), the factor information computed by R8GE_FA.\n%\n%    Input, integer PIVOT(N), the pivot vector from R8GE_FA.\n%\n%    Output, real A_INVERSE(N,N), the inverse matrix.\n%\n  a_inverse(1:n,1:n) = a_lu(1:n,1:n);\n%\n%  Compute Inverse(U).\n%\n  for k = 1 : n\n\n    a_inverse(k,k) = 1.0E+00 / a_inverse(k,k);\n    a_inverse(1:k-1,k) = -a_inverse(1:k-1,k) * a_inverse(k,k);\n\n    for j = k + 1 : n\n\n      temp = a_inverse(k,j);\n      a_inverse(k,j) = 0.0E+00;\n      a_inverse(1:k,j) = a_inverse(1:k,j) + a_inverse(1:k,k) * temp;\n\n    end\n\n  end\n%\n%  Form Inverse(U) * Inverse(L).\n%\n  for k = n - 1 : -1 : 1\n\n    work(k+1:n) = a_inverse(k+1:n,k);\n    a_inverse(k+1:n,k) = 0.0E+00;\n\n    for j = k + 1 : n\n      a_inverse(1:n,k) = a_inverse(1:n,k) + a_inverse(1:n,j) * work(j);\n    end\n\n    if ( pivot(k) ~= k )\n\n      for i = 1 : n\n        t                     = a_inverse(i,k);\n        a_inverse(i,k)        = a_inverse(i,pivot(k));\n        a_inverse(i,pivot(k)) = t;\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_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.5997881359282241}}
{"text": "function sphere_cubed_grid_points_display ( ns, xyz, filename )\n\n%*****************************************************************************80\n%\n%% SPHERE_CUBED_GRID_POINTS_DISPLAY displays the points on a cubed sphere grid.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    09 May 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer NS, the number of points.\n%\n%    Output, real XYZ(NS,3), distinct points on the unit sphere\n%    generated by a cubed sphere grid.\n%\n  figure ( )\n  clf\n  hold on\n  [ x, y, z ] = sphere ( 20 );\n  c = ones ( size ( z ) );\n  surf ( x, y, z, c );\n  plot3 ( xyz(:,1), xyz(:,2), xyz(:,3), 'b.', 'Markersize', 20 );\n  axis equal\n  grid on\n  view ( 3 )\n  xlabel ( '<--X-->' )\n  ylabel ( '<--Y-->' )\n  zlabel ( '<--Z-->' )\n  title_string = s_escape_tex ( filename )\n  title ( title_string, 'FontSize', 24 );\n  hold off\n\n  print ( '-dpng', filename );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Plot file saved to \"%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/sphere_cubed_grid/sphere_cubed_grid_points_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5997492861882086}}
{"text": "%% Machine Learning Online Class\n%  Exercise 6 | Support Vector Machines\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%     gaussianKernel.m\n%     dataset3Params.m\n%     processEmail.m\n%     emailFeatures.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\nfprintf('Loading and Visualizing Data ...\\n')\n\n% Load from ex6data1: \n% You will have X, y in your environment\nload('ex6data1.mat');\n\n% Plot training data\nplotData(X, y);\n\nfprintf('Program paused. Press enter to continue.\\n');\n%pause;\n\n%% ==================== Part 2: Training Linear SVM ====================\n%  The following code will train a linear SVM on the dataset and plot the\n%  decision boundary learned.\n%\n\n% Load from ex6data1: \n% You will have X, y in your environment\nload('ex6data1.mat');\n\nfprintf('\\nTraining Linear SVM ...\\n')\n\n% You should try to change the C value below and see how the decision\n% boundary varies (e.g., try C = 1000)\nC = 100;\nmodel = svmTrain(X, y, C, @linearKernel, 1e-3, 20);\nvisualizeBoundaryLinear(X, y, model);\n\nfprintf('Program paused. Press enter to continue.\\n');\n%pause;\n\n%% =============== Part 3: Implementing Gaussian Kernel ===============\n%  You will now implement the Gaussian kernel to use\n%  with the SVM. You should complete the code in gaussianKernel.m\n%\nfprintf('\\nEvaluating the Gaussian Kernel ...\\n')\n\nx1 = [1 2 1]; x2 = [0 4 -1]; sigma = 2;\nsim = gaussianKernel(x1, x2, sigma);\n\nfprintf(['Gaussian Kernel between x1 = [1; 2; 1], x2 = [0; 4; -1], sigma = 0.5 :' ...\n         '\\n\\t%f\\n(this value should be about 0.324652)\\n'], sim);\n\nfprintf('Program paused. Press enter to continue.\\n');\n%pause;\n\n%% =============== Part 4: Visualizing Dataset 2 ================\n%  The following code will load the next dataset into your environment and \n%  plot the data. \n%\n\nfprintf('Loading and Visualizing Data ...\\n')\n\n% Load from ex6data2: \n% You will have X, y in your environment\nload('ex6data2.mat');\n\n% Plot training data\nplotData(X, y);\n\nfprintf('Program paused. Press enter to continue.\\n');\n%pause;\n\n%% ========== Part 5: Training SVM with RBF Kernel (Dataset 2) ==========\n%  After you have implemented the kernel, we can now use it to train the \n%  SVM classifier.\n% \nfprintf('\\nTraining SVM with RBF Kernel (this may take 1 to 2 minutes) ...\\n');\n\n% Load from ex6data2: \n% You will have X, y in your environment\nload('ex6data2.mat');\n\n% SVM Parameters\nC = 1; sigma = 0.1;\n\n% We set the tolerance and max_passes lower here so that the code will run\n% faster. However, in practice, you will want to run the training to\n% convergence.\nmodel= svmTrain(X, y, C, @(x1, x2) gaussianKernel(x1, x2, sigma)); \nvisualizeBoundary(X, y, model);\n\nfprintf('Program paused. Press enter to continue.\\n');\n%pause;\n\n%% =============== Part 6: Visualizing Dataset 3 ================\n%  The following code will load the next dataset into your environment and \n%  plot the data. \n%\n\nfprintf('Loading and Visualizing Data ...\\n')\n\n% Load from ex6data3: \n% You will have X, y in your environment\nload('ex6data3.mat');\n\n% Plot training data\nplotData(X, y);\n\nfprintf('Program paused. Press enter to continue.\\n');\n%pause;\n\n%% ========== Part 7: Training SVM with RBF Kernel (Dataset 3) ==========\n\n%  This is a different dataset that you can use to experiment with. Try\n%  different values of C and sigma here.\n% \n\n% Load from ex6data3: \n% You will have X, y in your environment\nload('ex6data3.mat');\n\n% Try different SVM Parameters here\n[C, sigma] = dataset3Params(X, y, Xval, yval);\n\n% Train the SVM\nmodel= svmTrain(X, y, C, @(x1, x2) gaussianKernel(x1, x2, sigma));\nvisualizeBoundary(X, y, model);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\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-ex6/ex6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.599749285895633}}
{"text": "function f = randarb(x,y)\n% RANDARB generates a random observation from any arbitrary PDF defined by x,y\n% function f = hfarbrand(x,y) x and y are vectors of length N that describe a PDF\n% to some precision implicitly dictated by the size of N.  Fhe returned scalar f\n% is an observation from the set of x with a probability of (x/y(x))/sum(y)\n\n%% Sanity checks\nif nargin ~= 2\n    error('Two input vectors are required');\nend\nif length(x) ~= length(y)\n    error('x and y must be of the same length');\nend\nif length(x) < 30\n    warning('The size of x and y is very low');\nend\n\n%% Compute a uniform random number between 0 and sum(y)\nrandx = sum(y)*rand();\n\n%% Find where the number lies on a conceptual line comprised of \"segments\" of\n% length y\ni = 1;\nwhile sum(y(1:i)) < randx\n    i = i + 1;\nend\n\n%% Return the x value corresponding to the y value we \"landed on.\"\nf = x(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/6506-obs-from-arbitrary-pdf/randarb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5996953900808799}}
{"text": "% MATLAB computation of pulse transformer model - DS Method\n% File:  c:\\M_files\\shortcuts\\xfrmrds2.m\n% 9/19/02; 4/17/04; 2/15/07\n%   \ntic;clc;clear;\nK=1e3;pF=1e-12;mH=1e-3;uH=1e-6;ns=1e-9;ps=1e-12; % unit suffixes\n%\n% Components\n%\nR1=10;R2=1.5;R3=20*K;R4=1.5;R5=1*K;R6=0.5;R7=1;\nC1=20*pF;C2=5*pF;C3=20*pF;L1=1*uH;L2=2*mH;L3=1*uH;\n%\n% Get A, B, D, & E arrays; this function called only once.\n%\nNom=[R1 R2 R3 R4 R5 R6 R7 C1 C2 C3 L1 L2 L3];\n[A,B,D,E,I]=tfrmr2(Nom);\n%\n% * * * * * * * * * * * * Frequency response * * * * * * * * * * * *\n%\nEin=10; % Change Ein from 1V to 10V.\n%\nBF=2;ND=6;PD=50;NP=ND*PD+1;L=linspace(BF,BF+ND,NP);\n%\n% Since the output is vC3, we dont need the D and E arrays. \n% The cv output below is [vC1 vC2 vC3 iL1 iL2 iL3]'\n% (a column vector).  Hence we need vC3 or cv(3).\n%\nfor i=1:NP\n   F=10^L(i);s=2*pi*F*j;\n   cx=(s*I-A)\\B*Ein;\n%   cy=D*cx+E*Ein; % cy not used \n   Vo=abs(cx(3)); % vC3 = Vo\n   Vf(i)=20*log10(Vo); \nend\n%\n% * * * * * * * * * * * * * Transient response * * * * * * * * * * * \n%\nTx=1/max(max(abs(A)));\ndisp('Shortest circuit time constant');Tx\n%Per=input('Sweep time? (sec)');\n% set Sweep time to 200ns = 200e-9 to match Spice run.\nPer=200*ns;\nkmax=1e5; % kmax increased due to fast time constant Tx\ndt = 2*ps\nN=6;\n%dt=Per/kmax;N=6;\nt1=linspace(0,Per,kmax);IV=zeros(N,kmax);\n%\n% input ramp parameters\n%\np=Ein/(5*dt);b=6*dt;pw=5e4*dt;c=pw+6*dt;d=pw+11*dt;\nEa1=ramp1(p,t1(1),dt)-ramp1(p,t1(1),b)-ramp1(p,t1(1),c)+ramp1(p,t1(1),d);\n% initialize k = 1\nIV(:,1)=B*Ea1*dt;\n%\n% iterate for k = 2,3,...kmax\n%\nfor k=2:kmax\n   Eak=ramp1(p,t1(k),dt)-ramp1(p,t1(k),b)-ramp1(p,t1(k),c)+ramp1(p,t1(k),d);\n   IV(:,k)=A*IV(:,k-1)*dt+B*Eak*dt+IV(:,k-1);\nend\n%\n% Plot frequency response\n%\nsubplot(2,1,1)\nh=plot(L,Vf,'k');\nset(h,'LineWidth',2);\ngrid on;\naxis([BF BF+ND -40 30]);\nXT=linspace(BF,BF+ND,7);\nset(gca,'xtick',XT);\nylabel('dBV');title('AC Output Vc3');\nxlabel('Log Freq(Hz)');\n%\n% Plot time response\n%\nsubplot(2,1,2)\nh=plot(t1/ns,IV(1,:),'k',t1/ns,IV(3,:),'r');\nset(h,'LineWidth',2);\naxis auto\ngrid on;ylabel('Volts');title('Transient response, Vc1 & Vc3');\nxlabel('nsec');\nlegend('Vc1','Vc3');\n\nfigure(1) % display plot on screen.\n%\ndisp(' ');disp('Execution time in seconds');\nET=toc\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/2435-shortcut-state-space-circuit-analysis/Matlab_Files/xfrmrds2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5996953857188386}}
{"text": "function f = smiley(varargin)\n\nif nargin == 0 || ~isa(varargin{1},'vector3d')\n  if check_option(varargin,'exact')\n    f = S2FunHandle(@(v) S2Fun.smiley(v));\n  else\n    f = S2FunHarmonic.quadrature(@(v) S2Fun.smiley(v),varargin{:});\n  end\n  return;\nend\n\nv = varargin{1};\nv = v(:)';\n\n% Radial test function: quadratic spline\nf_r = @(z,h) (z>h).*(z-h).^2./(1-h).^2;\nif check_option(varargin,'even')\n  f_r = @(z,h) f_r(z,h)+f_r(-z,h); % f has to be even\nend\n\nx_0 = [pi/2,0; 0.6,-0.6; 0.6,0.6; -0.5,-1; -0.5,-0.5; -0.5,0; -0.5,0.5; -0.5,1];\nh_0 = [0.7; 0.96; 0.96; 0.93; 0.93; 0.93; 0.93; 0.93];\nc_0 = [0.5; -0.5; -0.5; 0.25; 0.25; 0.25; 0.25; 0.25];\n\ncenters = vector3d.byPolar(x_0(:, 1), x_0(:, 2));\nif strcmpi(getMTEXpref('xAxisDirection'),'east')\n  centers = rotate(centers,90*degree);\nend\n\n% TODO: upper line can be replaced by lower line with Matlab 2017\nfh = @(v) (sum(repmat(c_0,1,length(v)) .* f_r(dot(repmat(v,length(centers),1), repmat(centers,1,length(v))), repmat(h_0,1,length(v))), 1))';\n%fh = @(v) (sum(c_0.*f_r(dot(v, centers), h_0), 1))';\n\nf = fh(v);\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/S2Fun/@S2Fun/smiley.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5995947099508444}}
{"text": "function [W] = spm_Volt_W(u)\n% returns basis functions used for Volterra expansion\n% FORMAT [W] = spm_Volt_W(u);\n% u  - times {seconds}\n% W  - basis functions (mixture of Gammas)\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_Volt_W.m 1143 2008-02-07 19:33:33Z spm $\n\n\nu     = u(:);\nW     = [];\nfor i = 2:4\n    m   = (2^i);\n    s   = sqrt(m);\n    W   = [W spm_Gpdf(u,(m/s)^2,m/s^2)];\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_Volt_W.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5995947050024103}}
{"text": "N  = 24;                            % Prediction horizon (number of iterations)\nNu  = N;                            % Control horizon (number of iterations)           \nQ = [1 0 1 0 0];                    % State weights\nR = 0;                              % du weights\nRu = 1;                             % u weights\nLB = 0*ones(Nu,1);                  % Lower bound of control input\nUB = 1*ones(Nu,1);                  % Upper bound of control input\nLBdu = nan;                         % Lower bound of control input rate\nUBdu = nan;                         % Upper bound of control input rate\nLBo = 0;                            % Lower bound of output\nUBo = nan;                          % Upper bound of output\n", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/EX_HIV_THERAPY/getMPCparams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.599594699084812}}
{"text": "function out=tanh(x)\n\nout=sinh(x)./cosh(x);\n\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/tanh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5995946946209596}}
{"text": "%ADABOOSTC\n%\n% [W,V,ALF] =  ADABOOSTC(A,CLASSF,N,RULE,VERBOSE);\n%\n% INPUT\n%   A       Dataset\n%   CLASSF  Untrained weak classifier\n%   N       Number of classifiers to be trained\n%   RULE    Combining rule (default: weighted voting)\n%   VERBOSE Suppress progress report if 0 (default)\n%\n% OUTPUT\n%   W       Combined trained classifier\n%   V       Cell array of all classifiers\n%           Use VC = stacked(V) for combining\n%   ALF     Weights\n%\n% DESCRIPTION\n%\n% Computation of a combined classifier according to adaboost.\n%\n% In total N weighted versions of the training set A are generated\n% iteratevely and used for the training of the specified classifier.\n% Weights, to be used for the probabilities of the objects in the training\n% set to be selected, are updated according to the Adaboost rule.\n%\n% The entire set of generated classifiers is given in V.\n% The set of classifier weigths, according to Adaboost is returned in ALF\n%\n% Various aggregating possibilities can be given in \n% the final parameter rule:\n% []:      WVOTEC, weighted voting.\n% VOTEC    voting\n% MEANC    sum rule\n% AVERAGEC averaging of coeffients (for linear combiners)\n% PRODC    product rule\n% MAXC     maximum rule\n% MINC     minimum rule\n% MEDIANC  median rule\n%\n% REFERENCE\n% Ji Zhu, Saharon Rosset, Hui Zhou and Trevor Hastie, \n% Multiclass Adaboost. A multiclass generalization of the Adaboost \n% algorithm, based on a generalization of the exponential loss.\n% http://www-stat.stanford.edu/~hastie/Papers/samme.pdf\n%\n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% MAPPINGS, DATASETS\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% (Multiclass correction by Marcin Budka, Bournemouth Univ., UK)\n\n%function [W,V,alf] = adaboostc(a,clasf,n,rule,verbose)\nfunction [out,V,alf] = adaboostc(varargin)\n\n%% INITIALISATION\nargin = setdefaults(varargin,[],nmc,100,[],0);\nif mapping_task(argin,'definition')\n  \n  out = define_mapping(argin,'untrained','Adaboost');\n  \n%% TRAINING\nelseif mapping_task(argin,'training')\n  \n  [a,clasf,n,rule,verbose] = deal(argin{:});\n  [m,k,c] = getsize(a);\n  V = [];\n  laba = getlab(a);\n  u = ones(m,1)/m;\t\t\t% initialise object weights\n  alf = zeros(1,n);\t\t\t% space for classifier weights\n  isseparable = 0;          % check if we can make 0 error\n  if verbose && k == 2\n    figure(verbose);\n    scatterd(a);\n  end\n\n  %% generate n classifiers\n  for i = 1:n\n    b = gendatw(a,u,m);             % sample training set\n    b = setprior(b,getprior(a));\t% use original priors\n    w = b*clasf;                    % train weak classifier\n    ra = a*w;                       % test weak classifier\n\n    if verbose && k == 2\n      plotc(w,1); drawnow\n    end\n\t\n    labc = labeld(ra);\n    diff = sum(labc~=laba,2)~=0;\t% objects erroneously classified\n    erra = sum((diff).*u);          % weighted error on original dataset\n\n    if (erra==0)\n        isseparable = 1;\n        V = w;\n        break;\n    end\n    if (erra < (1-1/c))        % if classifier better then random guessing...\n      alf(i) = 0.5*(log((1-erra)/erra) + log(c-1));\n      correct = find(diff==0); % find correctly classified objects\n      wrong = find(diff==1);   % find incorrectly classified objects\n      u(correct) = u(correct)*exp(-alf(i));\t% give them the ...\n      u(wrong) = u(wrong)*exp(alf(i));\t  \t% proper weights\n      u = u./sum(u);                        % normalize weights\n    else\n      alf(i) = 0;\n    end\n\t\n    if verbose\n      disp([erra alf(i) sum(alf)])\n    end\n    V = [V w];                       % store all classifiers\n\n  end\n\n  %% combine and return\n  if isseparable\n      W = V;\n      W = setname(W,['Boosted ',getname(V)]);\n  else\n    if isempty(rule)\n        W = wvotec(V,alf);             % default is weighted combiner\n    else\n        W = traincc(a,V,rule);         % otherwise, use user supplied combiner\n    end\n  end\n\n  if verbose > 0 && k == 2\n    plotc(W,'r',3)\n    ee = a*W*testc;\n    title(['Error: ', num2str(ee)]);\n  end\n  \n  out = W;\n\nelse\n  error('Illegal call')\nend\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/adaboostc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5995946891879435}}
{"text": "% Calculate one-shot classification error rate\nfunction run_classification\n\n    classdir = 'model_refits';\n    load('items_classification','nrun','ntrain','ntest','cell_Y');\n\n    trainset = num2cell(vec(1:ntrain));\n    testset = num2cell(vec(1:ntest));\n\n    fprintf(1,'one-shot classification results\\n');\n    perror = zeros(nrun,1);\n    for r=1:nrun\n        Y = cell_Y{r};\n        fscore = @(itrain,itest) fclassify(itrain,itest,r,classdir);\n        perror(r) = myclassify(trainset,testset,fscore,Y,'score');\n        fprintf(1,' run %d (error %s%%)\\n',r,num2str(perror(r),3));\n    end\n    fprintf(1,'average error: %s%%\\n',num2str(mean(perror),3));\n\nend\n\n%\n% Bayesian classification score\n%\n%  log P(I_T|I_C) + log(I_C|I_T) - log(I_C)\n%   for training image I_C\n%   and test image I_T\n%\n% Input\n%  itrain: train index\n%  itest: test index\n%  irun: run index\n%  classdir: file directory for \"crossFit\" files\n%\n% Output\n%  log_score: [scalar] score\n%\nfunction log_score = fclassify(itrain,itest,irun,classdir)\n\n    srun = num2str(irun);\n    strain = num2str(itrain);\n    stest = num2str(itest);\n\n    fn_test_to_train = ['run',srun,'_fit_test' ,stest,'_to_image_train',strain];\n    fn_train_to_test = ['run',srun,'_fit_train',strain,'_to_image_test',stest];\n\n    % load file optimizing P(I_T|I_C)\n    if ~exist(fullfile(classdir,[fn_train_to_test,'.mat']),'file')\n       fprintf(1,'Please download pre-computed model results to use this feature. Program quiting...\\n');\n       assert false;\n    end\n    load(fullfile(classdir,fn_train_to_test),'fit_score','prior_score');\n    pair.fit_score = fit_score;\n    pair.prior_score = prior_score;\n    pair_fit_train_to_test = pair;\n    clear pair\n    \n    % load file optimizing P(I_C|I_T)\n    load(fullfile(classdir,fn_test_to_train),'fit_score','prior_score');\n    pair.fit_score = fit_score;\n    pair.prior_score = prior_score;\n    pair_fit_test_to_train = pair;\n    clear pair\n   \n    % compute score\n    [log_P_IT_given_IC,prior_scores] = log_post_pred(pair_fit_train_to_test);\n    log_P_IC_given_IT = log_post_pred(pair_fit_test_to_train);    \n    log_P_IC = logsumexp(prior_scores(:)); \n    log_score = log_P_IC_given_IT + log_P_IT_given_IC - log_P_IC;\n    \nend\n\n%\n% Log-posterior predictive score, log P(I_2 | I_1), using discrete approximation\n%\n% Input\n%  pair: structure\n%  \n% Output\n%  logscore: log conditional probability\n%  prior_scores:  [k x 1] log joint probability (unnormalized) weights for\n%       each parse of I_1\n%\nfunction [logscore,prior_scores] = log_post_pred(pair)\n\n    % extra info\n    logfit = pair.fit_score;\n    prior_scores = pair.prior_score;\n    \n    % normalize weights\n    logwt = prior_scores - logsumexp(prior_scores(:));\n    \n    % combine weights with fit term\n    logv = logfit(:) + logwt;\n    logscore = logsumexp(logv);\n    \nend", "meta": {"author": "brendenlake", "repo": "BPL", "sha": "2c7f679bb0055f29cbade7ef099897c3342bcb79", "save_path": "github-repos/MATLAB/brendenlake-BPL", "path": "github-repos/MATLAB/brendenlake-BPL/BPL-2c7f679bb0055f29cbade7ef099897c3342bcb79/classification/run_classification.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5995946887033615}}
{"text": "classdef MMAE < Metric\n    %MAE static class to calculate the minimum mean absolute error (MAE) per\n    %   class. Values range from 0 to J-1, where J is the number of classes.\n    %\n    %   MAE methods:\n    %      CALCULATEMETRIC            - Computes the evaluation metric\n    %      CALCULATECROSSVALMETRIC    - Computes the evaluation metric as an error\n    %\n    %   References:\n    %     [1] M. Cruz-Ram\u00edrez, C. Herv\u00e1s-Mart\u00ednez, J. S\u00e1nchez-Monedero and\n    %         P. A. Guti\u00e9rrez Metrics to guide a multi-objective evolutionary\n    %         algorithm for ordinal classification, Neurocomputing, Vol. 135, July, 2014, pp. 21-31.\n    %         https://doi.org/10.1016/j.neucom.2013.05.058\n    %\n    %   This file is part of ORCA: https://github.com/ayrna/orca\n    %   Original authors: Pedro Antonio Guti\u00e9rrez, Mar\u00eda P\u00e9rez Ortiz, Javier S\u00e1nchez Monedero\n    %   Citation: If you use this code, please cite the associated paper http://www.uco.es/grupos/ayrna/orreview\n    %   Copyright:\n    %       This software is released under the The GNU General Public License v3.0 licence\n    %       available at http://www.gnu.org/licenses/gpl-3.0.htmlml\n    methods\n        function obj = MMAE()\n            obj.name = 'Max Mean Absolute Error';\n        end\n    end\n    \n    methods(Static = true)\n        \n        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        %\n        % Function: calculateMetric (static)\n        % Description: Computes the evaluation metric\n        % Outputs: metric results\n        % Arguments:\n        %           argum1--> First argument (confusion matrix or predictions)\n        %\t    argum2--> Second argument (true labels)\n        % \t    If there is only one argument, the results are computed\n        %\t    using the confusion matrix. In other case, with the\n        %\t    predictions and true labels.\n        %\n        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        \n        function maxmae = calculateMetric(argum1,argum2)\n            %CALCULATEMETRIC Computes the evaluation metric\n            %   METRIC = CALCULATEMETRIC(CM) returns calculated metric from confussion\n            %   matrix CM\n            %   METRIC = CALCULATEMETRIC(actual, pred) returns calculated metric from\n            %   real labels (ACTUAL) labels and predicted labels (PRE\n            if nargin == 2\n                argum1 = confusionmat(argum1,argum2);\n            end\n            n=size(argum1,1);\n            cm = double(argum1);\n            cost = abs(repmat(1:n,n,1) - repmat((1:n)',1,n));\n            mae = zeros(n:1);\n            cmt = cm';\n            for i=0:n-1\n                mae(i+1) = sum(cost(1+(i*n):(i*n)+n).*cmt(1+(i*n):(i*n)+n)) / sum(cmt(1+(i*n):(i*n)+n));\n            end\n            maxmae = max(mae);\n        end\n        \n        function value = calculateCrossvalMetric(argum1,argum2)\n            %CALCULATECROSSVALMETRIC Computes the evaluation metric and returns\n            %it as an error.\n            %   METRIC = CALCULATECROSSVALMETRIC(CM) returns calculated metric from confussion\n            %   matrix CM\n            %   METRIC = CALCULATECROSSVALMETRIC(actual, pred) returns calculated metric from\n            %   real labels (ACTUAL) labels and predicted labels (PRED)\n            if nargin == 2\n                value = MMAE.calculateMetric(argum1,argum2);\n            else\n                value = MMAE.calculateMetric(argum1);\n            end\n        end\n        \n    end\n    \n    \nend\n", "meta": {"author": "ayrna", "repo": "orca", "sha": "eaa629e687d04d73628782e16e92d330acb43faf", "save_path": "github-repos/MATLAB/ayrna-orca", "path": "github-repos/MATLAB/ayrna-orca/orca-eaa629e687d04d73628782e16e92d330acb43faf/src/Measures/MMAE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.599594679291074}}
{"text": "function dist = getDistPCKh(pred,gt,refDist)\n\nassert(size(pred,1) == size(gt,1) && size(pred,2) == size(gt,2) && size(pred,3) == size(gt,3));\nassert(size(refDist,1) == size(gt,3));\n\ndist = nan(1,size(pred,2),size(pred,3));\n\nfor imgidx = 1:size(pred,3)\n    \n    % distance to gt joints\n    dist(1,:,imgidx) = sqrt(sum((pred(:,:,imgidx) - gt(:,:,imgidx)).^2,1))./refDist(imgidx);\n\nend", "meta": {"author": "Guanghan", "repo": "GNet-pose", "sha": "c70e0fc65b290e68a16ca3040a70300f9c2bee44", "save_path": "github-repos/MATLAB/Guanghan-GNet-pose", "path": "github-repos/MATLAB/Guanghan-GNet-pose/GNet-pose-c70e0fc65b290e68a16ca3040a70300f9c2bee44/testing/eval_MPII/getDistPCKh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5995928336483022}}
{"text": "function [U_final, V_final, nIter_final, objhistory_final] = GNMF(X, k, W, options, U, V)\n% Graph regularized Non-negative Matrix Factorization (GNMF)\n%\n% where\n%   X\n% Notation:\n% X ... (mFea x nSmp) data matrix \n%       mFea  ... number of words (vocabulary size)\n%       nSmp  ... number of documents\n% k ... number of hidden factors\n% W ... weight matrix of the affinity graph \n%\n% options ... Structure holding all settings\n%               options.alpha ... the regularization parameter. \n%                                 [default: 100]\n%                                 alpha = 0, GNMF boils down to the ordinary NMF. \n%                                 \n%\n% You only need to provide the above four inputs.\n%\n% X = U*V'\n%\n% References:\n% [1] Deng Cai, Xiaofei He, Xiaoyun Wu, and Jiawei Han. \"Non-negative\n% Matrix Factorization on Manifold\", Proc. 2008 Int. Conf. on Data Mining\n% (ICDM'08), Pisa, Italy, Dec. 2008. \n%\n% [2] Deng Cai, Xiaofei He, Jiawei Han, Thomas Huang. \"Graph Regularized\n% Non-negative Matrix Factorization for Data Representation\", IEEE\n% Transactions on Pattern Analysis and Machine Intelligence, , Vol. 33, No.\n% 8, pp. 1548-1560, 2011.  \n%\n%\n%   version 2.0 --April/2009 \n%   version 1.0 --April/2008 \n%\n%   Written by Deng Cai (dengcai AT gmail.com)\n%\n\nif min(min(X)) < 0\n    error('Input should be nonnegative!');\nend\n\nif ~isfield(options,'error')\n    options.error = 1e-5;\nend\nif ~isfield(options, 'maxIter')\n    options.maxIter = [];\nend\n\nif ~isfield(options,'nRepeat')\n    options.nRepeat = 10;\nend\n\nif ~isfield(options,'minIter')\n    options.minIter = 30;\nend\n\nif ~isfield(options,'meanFitRatio')\n    options.meanFitRatio = 0.1;\nend\n\nif ~isfield(options,'alpha')\n    options.alpha = 100;\nend\n\nnSmp = size(X,2);\n\nif isfield(options,'alpha_nSmp') && options.alpha_nSmp\n    options.alpha = options.alpha*nSmp;    \nend\n\nif isfield(options,'weight') && strcmpi(options.weight,'NCW')\n    feaSum = full(sum(X,2));\n    D_half = X'*feaSum;\n    X = X*spdiags(D_half.^-.5,0,nSmp,nSmp);\nend\n\nif ~isfield(options,'Optimization')\n    options.Optimization = 'Multiplicative';\nend\n\nif ~exist('U','var')\n    U = [];\n    V = [];\nend\n\nswitch lower(options.Optimization)\n    case {lower('Multiplicative')} \n        [U_final, V_final, nIter_final, objhistory_final] = GNMF_Multi(X, k, W, options, U, V);\n    otherwise\n        error('optimization method does not exist!');\nend\n\n\n    \n        ", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/MatrixFactorization/GNMF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5995753297744444}}
{"text": "function [mask, weight]=mesh2mask(node,face,xi,yi,hf)\n%\n% [mask weight]=mesh2mask(node,face,Nxy)\n%   or\n% [mask weight]=mesh2mask(node,face,[Nx,Ny])\n%   or\n% [mask weight]=mesh2mask(node,face,xi,yi,hf)\n%\n% fast rasterization of a 2D mesh to an image with triangle index labels\n% \n% author: Qianqian Fang <fangq at nmr.mgh.harvard.edu>\n% date for initial version: July 18,2013\n%\n% input:\n%      node: node coordinates, dimension N by 2 or N by 3 array\n%      face: a triangle surface, N by 3 or N by 4 array\n%      Nx,Ny,Nxy: output image in x/y dimensions, or both\n%      xi,yi: linear vectors for the output pixel center positions in x/y\n%      hf: (optional) the handle of a pre-created figure window, for faster \n%          rendering\n%\n% output:\n%      mask: a 2D image, the value of each pixel is the index of the\n%            enclosing triangle, if the pixel is outside of the mesh, NaN\n%      weight: (optional) a 3 by Nx by Ny array, where Nx/Ny are the dimensions for\n%            the mask\n%\n% note: This function only works in MATLAB when the DISPLAY is not \n%       disabled. The maximum size of the mask output is limited by the \n%       screen size.\n%\n% example:\n%\n%   [no,fc]=meshgrid6(0:5,0:5);\n%   [mask weight]=mesh2mask(no,fc,-1:0.1:5,0:0.1:5);\n%   imagesc(mask);\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nif(nargin==3 && length(xi)==1 && xi>0)\n    mn=min(node);\n    mx=max(node);\n    df=(mx(1:2)-mn(1:2))/xi;\nelseif(nargin==3 && length(xi)==2 && all(xi>0))\n    mn=min(node);\n    mx=max(node);\n    df=(mx(1:2)-mn(1:2))./xi;\nelseif(nargin==4 || nargin==5)\n    mx=[max(xi) max(yi)];\n    mn=[min(xi) min(yi)];\n    df=[min(diff(xi(:))) min(diff(yi(:)))];\nelse\n    error('you must give at least xi input');\nend\nif(size(node,2)<=1 || size(face,2)<=2)\n    error('node must have 2 or 3 columns; face can not have less than 2 columns');\nend\n\nif(nargin<5)\n    hf=figure('visible','on');\nelse\n    clf(hf);\nend\npatch('Vertices',node,'Faces',face,'linestyle','none','FaceColor','flat',...\n 'FaceVertexCData',(1:size(face,1))','CDataMapping', 'scaled');\nset(gca, 'Position', [0 0 1 1]);\ncm=jet(size(face,1));\ncolormap(cm);\naxis off\nset(gca,'xlim',[mn(1) mx(1)]);\nset(gca,'ylim',[mn(2) mx(2)]);\nset(gca,'clim',[1 size(face,1)]);\n\noutput_size = round((mx(1:2)-mn(1:2))./df); %Size in pixels\n\nif(isoctavemesh || isempty(getenv('DISPLAY')))\n    resolution = 300; %Resolution in DPI\n    set(gcf,'PaperPositionMode','manual')\n    set(gcf,'paperunits','inches','paperposition',[0 0 output_size/resolution]);\n    deletemeshfile(mwpath('post_mesh2mask.png'));\n    print(mwpath('post_mesh2mask.png'),'-dpng',['-r' num2str(resolution)]);\n    mask=imread(mwpath('post_mesh2mask.png'));\nelse\n    pos=get(hf,'position');\n    pos(3:4)=max(pos(3:4),output_size+20);\n    set(hf,'position',pos);\n    set(gca, 'Units','pixels','position',[1, 1, output_size(1), output_size(2)]);\n    mask=getframe(gca);\n    if(any(size(mask.cdata)<[output_size([2 1]) 3]))\n        error('the requested rasterization grid is larger than the screen resolution');\n    end\n    mask=mask.cdata(1:output_size(2),1:output_size(1),:);\nend\nif(nargin<5)\n    close(hf);\nend\nmask=int32(reshape(mask,[size(mask,1)*size(mask,2) size(mask,3)]));\n[isfound,locb]=ismember(mask,floor(cm*255),'rows');\nlocb(isfound==0)=nan;\n\nmask=rot90(reshape(locb,output_size([2 1]))');\n\nif(nargout>=2)\n    xi=mn(1)+df(1)/2:df(1):mx(1);\n    yi=mn(2)+df(2)/2:df(2):mx(2);\n    weight=barycentricgrid(node,face,xi,yi,mask);\n    if(size(face,2)>=4)\n        badidx=find(weight(1,:,:)<0 | weight(2,:,:)<0 | weight(3,:,:)<0);\n        badidx=badidx(face(mask(badidx),3)~=face(mask(badidx),4));\n        weight2=barycentricgrid(node,face(:,[1 3 4]),xi,yi,mask);\n        weight(:,badidx)=0;\n        weight([1 3 4],badidx)=weight2(:,badidx);\n    end\nend\n\nfunction weight=barycentricgrid(node,face,xi,yi,mask)\n[xx,yy]=meshgrid(xi,yi);\nidx=find(~isnan(mask));\neid=mask(idx);\nt1=node(face(:,1),:);\nt2=node(face(:,2),:);\nt3=node(face(:,3),:);\ntt=(t2(:,2)-t3(:,2)).*(t1(:,1)-t3(:,1))+(t3(:,1)-t2(:,1)).*(t1(:,2)-t3(:,2));\nw(:,1)=(t2(eid,2)-t3(eid,2)).*(xx(idx)-t3(eid,1))+(t3(eid,1)-t2(eid,1)).*(yy(idx)-t3(eid,2));\nw(:,2)=(t3(eid,2)-t1(eid,2)).*(xx(idx)-t3(eid,1))+(t1(eid,1)-t3(eid,1)).*(yy(idx)-t3(eid,2));\nw(:,1)=w(:,1)./tt(eid);\nw(:,2)=w(:,2)./tt(eid);\nw(:,3)=1-w(:,1)-w(:,2);\nweight=zeros(3,size(mask,1),size(mask,2));\nww=zeros(size(mask));\nww(idx)=w(:,1);\nweight(1,:,:)=ww;\nww(idx)=w(:,2);\nweight(2,:,:)=ww;\nww(idx)=w(:,3);\nweight(3,:,:)=ww;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/iso2mesh/mesh2mask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.599575324632397}}
{"text": "function [rq,rqSS,diagnostics] = realized_quantile_variance(price,time,timeType,samplingType,samplingInterval,quantiles,blockSize,symmetric,overlap,subsamples)\n% Computes the Quantile Realized Variance of Christensen, Oomen and Podolskij (2008), the MinRV and\n% MedRV estimator of Andersen, Dobrev and Shaumberg and the general symmetrized version suggested by\n% Sheppard in a discussion of COP \n%\n% USAGE:\n%   [RQ] = realized_quantile_variance(PRICE,TIME,TIMETYPE,SAMPLINGTYPE,SAMPLINGINTERVAL,QUANTILES,BLOCKSIZE)\n%   [RQ,RQSS,DIAGNOSTICS] = realized_quantile_variance(PRICE,TIME,TIMETYPE,SAMPLINGTYPE,SAMPLINGINTERVAL,QUANTILES,BLOCKSIZE,SYMMETRIC,OVERLAP,SUBSAMPLES)\n%\n% INPUTS:\n%   PRICE            - m by 1 vector of high frequency prices\n%   TIME             - m by 1 vector of times where TIME(i) corresponds to PRICE(i)\n%   TIMETYPE         - String describing the way times are measured\n%                       'wall'    24-hour clock of the form HHMMSS, e.g. 101543 or 153217\n%                       'seconds' Time measured in seconds past midnight on the first day.\n%                       'unit'  Unit normalized date format, e.g. .1, .234, .9\n%                         Unit normalized times are more general than the other types and can be\n%                         applied to data from more than one calendar day\n%   SAMPLINGTYPE     - String describing the type of sampling to use when\n%                        filtering PRICE\n%                        'CalendarTime' - Sample in calendar time using observations separated by\n%                          SAMPLINGINTERVAL seconds\n%                        'CalendarUniform' - Sample in calendar time using SAMPLINGINTERVAL\n%                          observations spread uniformly between TIME(1) and TIME(m)\n%                        'BusinessTime' - Sample in business (tick) time using observation separated\n%                          by SAMPLINGINTERVALticks\n%                        'BusinessUniform' - Sample in business (tick) time using observations\n%                          uniformly spaced in business time.\n%                        'Fixed' - Sample at specific points in time. When using fixed,\n%                          SAMPLINGINTERVAL must be a n by 1 vector of times with the same TIMETYPE\n%                          as TIME (i.e. seconds if TIME is in seconds)\n%   SAMPLINGINTERVAL - Scalar integer or n by 1 vector whose meaning depends on the selected SAMPLINGTYPE\n%   QUANTILES        - k by 1 vector of quantile values to use when computing RQ.\n%                        When SYMMETRIC = false, 0.5<QUANTILES<=1.\n%                        When SYMMETRIC = true, 0<QUANTILES<=1\n%                        In either case, QUANTILES * BLOCKSIZE must be an integer.\n%                        The simplest method to set the quantiles is to determine which of the\n%                        ordered returns should be used in the QRV, and then to set\n%                        QUANTILES = ORDER/BLOCKSIZE.  For example, when SYMETRIC = FALSE, and\n%                        BLOCKSIZE = 20, QUANTILES = [13 15 18]/20 will use the returns in position\n%                        13, 15 and 18 (as well as 8 6 and 3).  When SYMMETRIC = TRUE, QUANTILES =\n%                        [5 8 10 13 15 18]/20 will use the absolute value of returns in positions 5,\n%                        8, 10, 13, 15 and 18.  For a fixed block size, you should generally more\n%                        quantiles when SYMMETRIC = TRUE.\n%   BLOCKSIZE        - Number of returns to use in each block when computing the quantiles. NOTE: If\n%                        OVERLAP = FALSE, then the number of returns produced by filtering according\n%                        to SAMPLINGTYPE and SAMPLINGINTERVAL must be an integer multiple of\n%                        BLOCKSIZE. Otherwise there is no constraint.\n%   SYMMETRIC        - [OPTIONAL] Boolean indicating whether the base the estimator on the absolute value\n%                        of returns (symmetric) of on the non-adjusted returns. Default value is\n%                        FALSE (as used by COP).\n%   OVERLAP          - [OPTIONAL] Boolean indicating whether to use all overlapping blocks (TRUE),\n%                        or only non-overlapping blocks. Default value is TRUE.\n%   SUBSAMPLES       - [OPTIONAL] Scalar integer indicating the number of subsample realized\n%                        variance estimators to average with the original realized variance.\n%                        Subsample realized variances are based on prices uniformly spaced between\n%                        the times (Calendar sampling) or ticks (Business sampling).  SUBSAMPLES=1\n%                        will compute a subsample realized variance using the mid-point of the\n%                        price sample points, 2 will use 1/3 and 2/3, and so on. In general this\n%                        number should be small so the subsample estimators will be \"sparse\".\n%\n% OUTPUTS:\n%   RQ               - Quantile realized variance vector (k by 1) corresponding to the values in QUANTILES\n%   RQSS             - Subsample based version of RQ.  RQSS = RQ if SUBSAMPLES = 0 or omitted.\n%   DIAGNOSTICS      - Structure with fields:\n%                        RQINDIV   - k by 1 vector of RQ estimates\n%                        RQSSINDIV - k by 1 vector of subsample RQ estimates\n%                        RQWEIGHTS - Weights used in combining the individual RQ estimates.  RQ\n%                                      weights are computed from RQCOV as the minimum variance\n%                                      combination\n%                        RQCOV     - k by k non-scaled (integrated quarticity) covariance matrix.\n%\n% COMMENTS:\n%   The cases where SAMPLESPERBIN is in {4 5 6 10 13 15 18 20 25 26 30 36 39 50 60 65 72 75 100 144}\n%   (non-symmetric) or {2 3 4 5 6 8 9 10 12 13 15 18 20 24 25 26 30 36 39 40 50 60 65 72 75 100 144}\n%   (symmetric) the scales and non-scaled covariances have been pre-computed using Monte Carlo\n%   integration using 100,000,000 simulations. Choosing another number for SAMPLESPERBIN requires a\n%   run of realized_quantile_variance_scale which can be slow if SAMPLESPERBIN is large. If using\n%   another value, 1,000,000 simulations will be used in computing the weights. If repeatedly using\n%   another value, pre-computing the appropriate scales and non-scaled covariance using\n%   realzed_quantile_weight_simulation is recommended.  \n%\n% EXAMPLES:\n%   % Estimate the RQ from prices available from 9:30 to 16:00 using 1 minute returns, 30 samples per\n%   % bin and quantiles [18 22 27]/30 ([0.6 0.733 0.9])\n%   sampleTimes = seconds2wall(wall2seconds(93000):60:wall2seconds(160000))\n%   RQ=realized_quantile_variance(price,time,'wall','Fixed',sampleTimes,[18 22 27]/30,30);\n%\n%   % The same but using 4 subsamples\n%   RQ=realized_quantile_variance(price,time,'wall','Fixed',sampleTimes,[18 22 27]/30,30,[],[],4);\n%\n%   % Estimate the RQ from prices available from 9:30 to 16:00 using 1 minute returns, 30 samples per\n%   % bin, the symmetric verion and quantiles [5 10 15 18 22 27]/30 ([0.15 0.33 0.5 0.6 0.733 0.9])\n%   RQ=realized_quantile_variance(price,time,'wall','Fixed',sampleTimes,[5 10 15 18 22 27]/30,30,true);\n%\n%   % Estimate the MedRV of ABS\n%   RQ=realized_quantile_variance(price,time,'wall','Fixed',sampleTimes,2/3,3,true);\n%\n%   % Estimate the MinRV of ABS\n%   RQ=realized_quantile_variance(price,time,'wall','Fixed',sampleTimes,1/2,2,true);\n%\n%   % Estimate a MedRV-like RQV only using blocks of size 5\n%   RQ=realized_quantile_variance(price,time,'wall','Fixed',sampleTimes,3/5,5,true);\n%\n%  See also REALIZED_MIN_MED_VARIANCE, REALIZED_KERNEL, REALIZED_VARIANCE,\n%  REALIZED_BIPOWER_VARIATION, REALIZED_THRESHOLD_VARIANCE\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 5/1/2008\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% InputChecking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin<7 || nargin>10\n    error('Seven to ten inputs required.')\nend\nswitch nargin\n    case 7\n        symmetric = false;\n        overlap = true;\n        subsamples = 1;\n    case 8\n        overlap = true;\n        subsamples = 1;\n    case 9\n        subsamples = 1;\nend\n\n\nif size(price,2)>size(price,1)\n    price=price';\nend\nif size(price,2)>1\n    error('PRICE must be a m by 1 vector.')\nend\nif size(time,2)>size(time,1)\n    time=time';\nend\nif any(diff(time)<0)\n    error('TIME must be sorted and increasing')\nend\nif size(time,2)>1 || length(time)~=length(price)\n    error('TIME must be a m by 1 vector.')\nend\n% Inserted to protect against inputing integer times\ntime = double(time);\n\ntimeType=lower(timeType);\nif ~ismember(timeType,{'wall','seconds','unit'})\n    error('TIMETYPE must be one of ''wall'', ''seconds'' or ''unit''.');\nend\nsamplingType=lower(samplingType);\nif ~ismember(samplingType,{'calendartime','calendaruniform','businesstime','businessuniform','fixed'})\n    error('SAMPLINGTYPE must be one of ''CalendarTime'', ''CalendarUniform'', ''BusinessTime'', ''BusinessUniform'' or ''Fixed''.');\nend\n\nm=size(price,1);\nt0=time(1);\ntT=time(m);\nif ismember(samplingType,{'calendartime','calendaruniform','businesstime','businessuniform'})\n    % Must be a scalar integer\n    if ~isscalar(samplingInterval) || floor(samplingInterval)~=samplingInterval || samplingInterval<1\n        error('SAMPLINGINTERVAL must be a positive integer for the SAMPLINGTYPE selected.')\n    end\nelse\n    if size(samplingInterval,2)>size(samplingInterval,1)\n        samplingInterval=samplingInterval';\n    end\n    if ~(any(samplingInterval>=t0) && any(samplingInterval<=tT))\n        error('At least one sampling interval must be between min(TIME) and max(TIME) when using ''Fixed'' as SAMPLINGTYPE.')\n    end\n    if any(diff(samplingInterval)<=0)\n        error('When using ''Fixed'' as SAMPLINGTYPE the vector of sampling times in SAMPLINGINTERVAL must be sorted and strictly increasing.')\n    end\nend\n\n% SAMPLERPERBIN, positive integer >=2\nif blockSize<1 || floor(blockSize)~=blockSize\n    error('SAMPLESPERBIN must be a positive integer greater than or equal to 2 (and usually at least 20)')\nend\n\n% SYMMETRIC\nif isempty(symmetric)\n    symmetric = false;\nend\nif ~isscalar(symmetric)\n    error('SYMMETRIC must be a scalar logical value.')\nend\nsymmetric = logical(symmetric);\n\n% QUANTILES\nif symmetric\n    if any(quantiles<=0) || any(quantiles>1) || length(quantiles)>blockSize || length(unique(quantiles*blockSize)) ~= length(quantiles)\n        error('QUANTILES must be unique, greater than 0 and less than or equal to 1, and the number of quantiles must be smaller than SAMPLESPERBIN when SYMMETRIC = true.')\n    end\nelse\n    if any(quantiles<=0.5) || any(quantiles>1) || length(quantiles)>(blockSize/2) || length(unique(quantiles*blockSize)) ~= length(quantiles)\n        error('QUANTILES must be unique, greater than 0.5 and less than or equal to 1, and the number of quantiles must be smaller than 0.5*SAMPLESPERBIN when SYMMETRIC = false.')\n    end\nend\n\n% OVERLAP\nif isempty(overlap)\n    overlap = true;\nend\nif ~isscalar(overlap)\n    error('OVERLAP must be a scalar logical value.')\nend\noverlap = logical(overlap);\n\n% SUBSAMPLES\nif isempty(subsamples)\n    subsamples = 1;\nend\nif ~isscalar(subsamples) || subsamples<0 || floor(subsamples)~=subsamples\n    error('SUBSAMPLES must be a non-negative integer.')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% 1. Compute returns\nlogPrice = log(price);\nfilteredLogPrice = realized_price_filter(logPrice,time,timeType,samplingType,samplingInterval);\nreturns = diff(filteredLogPrice);\n% Check that the number of returns is compatible with SAMPLESPERBIN\nn=length(returns);\nif ~overlap\n    if floor(n/blockSize)~=(n/blockSize)\n        error(['The number of returns computed from the prices returned from realized_price_filter(PRICE,TIME,TIMETYPE,SAMPLINGTYPE,SAMPLINGINTERVAL) must be an integer multiple of SAMPLESPERBIN.  The number of return produced is ' num2str(n)]);\n    end\nend\n\nif overlap\n    binStart = 1:n-blockSize+1;\nelse\n    binStart = 1:blockSize:n;\nend\nreturns = returns * sqrt(n);\nif symmetric\n    returns = abs(returns);\nend\nq = length(quantiles);\nrqindiv = zeros(length(binStart),q);\n\n\n\n% Compute the indices to use\nif symmetric\n    indices = round(quantiles*blockSize);\nelse\n    upperIndices = round(quantiles*blockSize);\n    lowerIndices = round((1-quantiles)*blockSize+1);\nend\n% Loop over the bins\n\n\n\ncount = 1;\nfor j=binStart\n    binreturns = returns(j:j+blockSize-1);\n    binreturns = sort(binreturns)';\n    if symmetric\n        rqindiv(count,:)=binreturns(indices).^2;\n    else\n        rqindiv(count,:)=binreturns(lowerIndices).^2+binreturns(upperIndices).^2;\n    end\n    count = count + 1;\nend\nrqindiv = mean(rqindiv);\n\n[rq,rqindiv,rqcov,rqweights] = realized_quantile_variance_core(rqindiv,blockSize,quantiles,symmetric);\n\ndiagnostics.rqindiv = rqindiv;\ndiagnostics.rqcov = rqcov;\ndiagnostics.rqweights = rqweights;\n\n\nsubsampledLogPrice = realized_subsample(logPrice,time,timeType,samplingType,samplingInterval,subsamples);\nrqindiv = nan(subsamples * length(binStart),q);\ncount = 1;\nfor i=1:subsamples\n    filteredLogPrice = subsampledLogPrice{i};\n    returns = diff(filteredLogPrice);\n    n = length(returns);\n    returns = returns * sqrt(n);\n    if symmetric\n        returns = abs(returns);\n    end\n    binStart = 1:n-blockSize+1;\n    for j=binStart\n        binreturns = returns(j:j+blockSize-1);\n        binreturns = sort(binreturns)';\n         if symmetric\n            rqindiv(count,:)=binreturns(indices).^2;\n         else\n            rqindiv(count,:)=binreturns(lowerIndices).^2+binreturns(upperIndices).^2;\n        end\n        count = count + 1;\n    end\nend\nrqindiv = rqindiv(1:count-1,:);\nrqindiv = mean(rqindiv);\n\n[rqSS,rqindivSS] = realized_quantile_variance_core(rqindiv,blockSize,quantiles,symmetric);\ndiagnostics.rqindivSS = rqindivSS;\n\nend\n\n\nfunction [rq,rqindiv,rqcov,rqweights] = realized_quantile_variance_core(rqindiv,blockSize,quantiles,symmetric)\n\nscales = load('realized_quantile_scales');\nif symmetric\n    simulationBlockSize = scales.symmetricSimulationSamplerperbin;\n    simulationCovariance = scales.symmetricExpectedCovariance;\n    simulationExpectedQuantiles = scales.symmetricExpectedQuantiles;\n    simulationQuantile = scales.symmetricSimulationQuantile;\nelse\n    simulationBlockSize = scales.asymmetricSimulationSamplerperbin;\n    simulationCovariance = scales.asymmetricExpectedCovariance;\n    simulationExpectedQuantiles = scales.asymmetricExpectedQuantiles;\n    simulationQuantile = scales.asymmetricSimulationQuantile;\n    \nend\nsimulationBlockSize = cell2mat(simulationBlockSize);\nif ismember(blockSize,simulationBlockSize )\n    % If available load and use the pre-computed value\n    \n    \n    [~,pl]=ismember(blockSize,simulationBlockSize);\n    thisScale = simulationExpectedQuantiles{pl};\n    thisQuantile = simulationQuantile{pl};\n    thisCovariance = simulationCovariance{pl};\n    q = length(quantiles);\n    indicator = zeros(1,q);\n    for i = 1:q\n        [~,indicator(i)] = min(abs(thisQuantile-quantiles(i)));\n    end\n    rqExpectedSquaredQuantileValue = thisScale(indicator);\n    % Find index\n    rqcov     = thisCovariance(indicator,indicator);\n    rqCovInv = rqcov \\ eye(q);\n    rqweights = rqCovInv*ones(q,1)/(ones(1,q)*rqCovInv*ones(q,1));\nelse\n    % Need to simulate using 1,000,000 simulations\n    if blockSize>100\n        warning('oxfordRealized:realizedQuantileVariance','Computing the scales needed.  Since SAMPLESPERBIN is very large this may take a long time.  \\nConsider pre-computing this value, especially if using this value of SAMPLESPERBIN many times.')\n    else\n        warning('oxfordRealized:realizedQuantileVariance','Computing the scales needed.  \\nConsider pre-computing this value, especially if using this value of SAMPLESPERBIN many times.')\n    end\n    [rqExpectedSquaredQuantileValue,rqweights,rqcov]=realized_quantile_variance_scale(adjSamplesPerBin,quantiles,1000000);\nend\n\n\nrqindiv  = rqindiv ./ rqExpectedSquaredQuantileValue;\nrq = rqweights'*rqindiv';\nend", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/realized_quantile_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.599575320001054}}
{"text": "function pred_value = xval_simple_ols_featureselect(X, Y, pthreshold, holdout_method)\n% Check: a very simple leave-one-out cross-validated regression\n% pred_value = xval_simple_ols_loo(X, Y, p-value selection for univariate feature selection, holdout_method)\n%\n% pred_value: cross-validated predictions of outcome data\n% X: n x variables matrix of predictors\n% Y: n x 1 vector of outcomes\n%\n% Tor Wager, June 2010\n%\n% Go to any LASSO output directory and run this:\n% \n% maskInfo = iimg_read_img(fullfile(pwd, 'mask.img'), 2);\n% dat{1} =  iimg_get_data(maskInfo, anticimages);\n% pred_value = xval_simple_ols_loo(X, Y)\n\n\n[N, k] = size(X);\npred_value = zeros(N, 1);\n\nholdout_set = nested_select_holdout_set;\n \ncreate_figure('test', 1, 2);\n\nfprintf('Fold: %03d', 0);\nfor wh_fold = 1:length(holdout_set) \n    \n    fprintf('\\b\\b\\b%3.0f ', wh_fold);\n    \n    % select training data\n    Xi = X; \n    Yi = Y; \n    \n    Yi(holdout_set{wh_fold}) = [];\n    Xi(holdout_set{wh_fold}, :) = [];              % leave out the missing observation(s)\n\n    Xtest = X(holdout_set{wh_fold}, :);\n    Ytest = Y(holdout_set{wh_fold}, :);          % only used later when we test prediction\n\n    ntrain = size(Xi, 1);\n    nholdout = size(Xtest, 1);\n        \n    % select features based on univariate correlations\n    [r, p, Tstat] = correlation_fast_series(Xi, Yi);\n    wh_features = p <= pthreshold;\n    nfeatures(wh_fold) = sum(wh_features);\n    if nfeatures(wh_fold) == 0\n        disp('Warning: no features pass threshold');\n        wh_features = p <= prctile(p, 10);\n    end\n\n    Xi = Xi(:, wh_features);\n    \n    Xi = [ones(ntrain, 1) Xi]; % add intercept\n    \n    % Make prediction\n    b = pinv(Xi) * Yi;\n    pred_value(holdout_set{wh_fold}, 1) = [ones(nholdout, 1) Xtest(:, wh_features)] * b;\n \n    create_figure('test', 1, 2, 1); subplot(1, 2, 1); plot(Xi*b, Yi, 'ko'); \n    plot(pred_value(holdout_set{wh_fold}, 1), Ytest, 'ro', 'MarkerFaceColor', 'r');\n    subplot(1, 2, 2); \n   title('Black circles = training set; Red = holdout obs');\n    drawnow;\n    \nend\n\ncm = colormap(jet(N));\nfigure; hold on; \nfor i = 1:N\n    plot(pred_value(i), Y(i), 'ko', 'MarkerFaceColor', cm(i, :));\nend\nxlabel('Predicted outcome (xval)'); ylabel('Outcome');\ntitle('Color = order in data series');\n\n\n\n\nfunction holdout_set = nested_select_holdout_set\n        % purpose: return holdout_set variable\n\n        nobs_s = length(Y);\n\n        switch lower(holdout_method)\n            case 'loo'\n                holdout_set = cell(1, nobs_s);\n                for i = 1:nobs_s, holdout_set{i} = i; end\n\n            case 'l4o_covbalanced'\n                disp('Selecting holdout sets: Balancing on covariates and outcome, and also trying to ensure that each obs is selected equally often.');\n                holdout_proportion = 4 ./ nobs_s; % prop for leave-4-out\n                nfolds = 40;\n                if isempty(cov_val)\n                    wh_holdout = xval_select_holdout_set(Y, [], nfolds, holdout_proportion, verbose);\n                else\n                    wh_holdout = xval_select_holdout_set(Y, cov_val, nfolds, holdout_proportion, verbose);\n                end\n                holdout_set = cell(1, nfolds);\n                for k = 1:nfolds\n                    holdout_set{k} = wh_holdout(:, k);\n                end\n\n            case 'categorical_covs'\n                \n                holdout_set = xval_select_holdout_set_categoricalcovs(cov_val);\n                \n            case 'balanced4'\n                nfolds = 4;\n                holdout_set = cell(1, nfolds);\n                [ys, indx] = sort(Y);\n                for k = 1:nfolds\n\n                    holdout_set{k} = indx(k:nfolds:end);\n                    if isempty(holdout_set{k}), error('Holdout set construction error: Dataset too small?'); end\n\n                end\n\n            otherwise error('Unknown holdout method.  See help.');\n        end\nend\n    \nend % main function\n        \n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/Cross_validated_Regression/xval_simple_ols_featureselect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5995753143483024}}
{"text": "% RES = corrDn(IM, FILT, EDGES, STEP, START, STOP)\n%\n% Compute correlation of matrices IM with FILT, followed by\n% downsampling.  These arguments should be 1D or 2D matrices, and IM\n% must be larger (in both dimensions) than FILT.  The origin of filt\n% is assumed to be floor(size(filt)/2)+1.\n% \n% EDGES is a string determining boundary handling:\n%    'circular' - Circular convolution\n%    'reflect1' - Reflect about the edge pixels\n%    'reflect2' - Reflect, doubling the edge pixels\n%    'repeat'   - Repeat the edge pixels\n%    'zero'     - Assume values of zero outside image boundary\n%    'extend'   - Reflect and invert\n%    'dont-compute' - Zero output when filter overhangs input boundaries\n%\n% Downsampling factors are determined by STEP (optional, default=[1 1]), \n% which should be a 2-vector [y,x].\n% \n% The window over which the convolution occurs is specfied by START \n% (optional, default=[1,1], and STOP (optional, default=size(IM)).\n% \n% NOTE: this operation corresponds to multiplication of a signal\n% vector by a matrix whose rows contain copies of the FILT shifted by\n% multiples of STEP.  See upConv.m for the operation corresponding to\n% the transpose of this matrix.\n\n% Eero Simoncelli, 6/96, revised 2/97.\n\nfunction res = corrDn(im, filt, edges, step, start, stop)\n\n%% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD)\n\nfprintf(1,'Warning: You should compile the MEX code for \"corrDn\", found in the MEX subdirectory.  It is MUCH faster.\\n');\n\n%------------------------------------------------------------\n%% OPTIONAL ARGS:\n\nif (exist('edges') == 1) \n  if (strcmp(edges,'reflect1') ~= 1)\n    warning('Using REFLECT1 edge-handling (use MEX code for other options).');\n  end\nend\n\nif (exist('step') ~= 1)\n\tstep = [1,1];\nend\t\n\nif (exist('start') ~= 1)\n\tstart = [1,1];\nend\t\n\nif (exist('stop') ~= 1)\n\tstop = size(im);\nend\t\n\n%------------------------------------------------------------\n\n% Reverse order of taps in filt, to do correlation instead of convolution\nfilt = filt(size(filt,1):-1:1,size(filt,2):-1:1);\n\ntmp = rconv2(im,filt);\nres = tmp(start(1):step(1):stop(1),start(2):step(2):stop(2));\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/BLS-GSM/Simoncelli_PyrTools/corrDn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5995728098466225}}
{"text": "function [b0vector b0angle] = getB0direction(vw)\n% Return the direction of the b0 field from a scan as (1) a unit vector and\n% (2) an angle in degrees\n%\n%   [b0vector b0angle]  = getB0direction([vw])\n%\n% Examples: \n%   b0vector = getB0direction(vw)\n%   [b0vector b0angle] = getB0direction\n%\n% vw can be INPLANE, GRAY, or VOLUME\n\nmrGlobals\n\nif ~exist('vw', 'var'), vw = getCurView; end\n\n% get the scanner xform (image coords => mm coords)\nscannerXform = viewGet(vw, 'scannerXform');\n\n% Define a unit vector in the z-direction in scanner space. This is the B0\n% direction (by definition).\norigin = [0 0 0]; z = [0 0 1];\n\n% Transform the vector into INPLANE image space\nb0ip = scannerXform \\ [origin 1; z 1]';\nb0ip = b0ip(1:3,2) - b0ip(1:3,1);\n\n% Make it a unit vector\nb0ip = 1/norm(b0ip) * b0ip;\n\n% xform the b0 vector to the appropriate view type\nswitch lower(viewGet(vw, 'viewType'))\n    case 'inplane'\n        % done\n        b0vector = b0ip;\n    case {'gray' 'volume'}\n        xform = mrSESSION.alignment;\n        b0Vol = xform * [[0 0 0 1]' [b0ip; 1]];\n        % make it a vector of norm 1\n        b0vector = b0Vol(1:3,2) - b0Vol(1:3,1);\n        b0vector = 1/norm(b0vector) * b0vector;\n        % xform to xyz\n        b0vector = [-b0vector(3) b0vector(2) -b0vector(1)];\n    otherwise\n        error('Can''t get B0 direction in %s vw', viewGet(vw, 'viewType'))\nend\n\n% convert b0 vector into angle. This is the angle between z-vector in image\n% space and and z-vector in scanner space.\ncostheta    = dot(b0vector, z)/norm(b0vector)*norm(z);\ntheta       = acos(costheta);\nb0angle     = theta  / pi * 180;\n        ", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/View/getB0direction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5995728087080717}}
{"text": "%--------------------\nfunction [EbN, Es] = PQ_excitCB (X2)\n\npersistent W2 EIN\n\nNF = 2048;\nVersion = 'Basic';\nif (isempty (W2))\n    Fs = 48000;\n    f = linspace (0, Fs/2, NF/2+1);\n    W2 = PQWOME (f);\n    [Nc, fc] = PQCB (Version);\n    EIN = PQIntNoise (fc);\nend\n\n% Allocate storage\nXwN2 = zeros (1, NF/2+1);\n\n% Outer and middle ear filtering\nXw2(1,:) = W2 .* X2(1,1:NF/2+1);\nXw2(2,:) = W2 .* X2(2,1:NF/2+1);\n\n% Form the difference magnitude signal\nfor (k = 0:NF/2)\n    XwN2(k+1) = (Xw2(1,k+1) - 2 * sqrt (Xw2(1,k+1) * Xw2(2,k+1)) ...\n               + Xw2(2,k+1));\nend\n\n% Group into partial critical bands\nEb(1,:) = PQgroupCB (Xw2(1,:), Version);\nEb(2,:) = PQgroupCB (Xw2(2,:), Version);\nEbN     = PQgroupCB (XwN2, Version);\n\n% Add the internal noise term => \"Pitch patterns\"\nE(1,:) = Eb(1,:) + EIN;\nE(2,:) = Eb(2,:) + EIN;\n\n% Critical band spreading => \"Unsmeared excitation patterns\"\nEs(1,:) = PQspreadCB (E(1,:), Version);\nEs(2,:) = PQspreadCB (E(2,:), Version);", "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/CB/PQ_excitCB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253257, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5995728075965513}}
{"text": "%% Example: Random Category Registration problem and its semidefinite relaxations\n%% Heng Yang, July 06, 2021\n\nclc; clear; close all; restoredefaultpath\n\n%% paths to dependencies\nspotpath    = '../spotless';\nmosekpath   = '../../mosek';\nstridepath  = '../STRIDE';\nmanoptpath  = '../manopt';\nsdpnalpath  = '../../SDPNAL+v1.0';\npath.stridepath = stridepath;\npath.mosekpath  = mosekpath;\npath.manoptpath = manoptpath;\naddpath('../utils')\naddpath('./solvers')\n\n%% choose if run GNC for STRIDE\nrungnc      = true;\n\n%% generate random point cloud registration problem\ndatatype                 = 'car';\nproblem.outlierRatio     = 0.1;\nproblem.noiseSigma       = 0.01;\nproblem.translationBound = 10.0;\nswitch datatype\n    case 'random'\n        %%%%%%%%%%%%%% RANDOM data %%%%%%%%%%%%%%\n        problem.N                = 10;\n        problem.K                = 3;\n        problem                  = gen_category_registration(problem);\n    case 'car'\n        %%%%%%%%%%%%%% PASCAL Car %%%%%%%%%%%%%%\n        problem.path             = './data/car.mat';\n        problem                  = gen_catreg_pascal_car(problem);\nend\nlambda                   = 0.5;\n\n%% generate SDP relaxations\naddpath(genpath(spotpath))\nSDP     = relax_category_registration_v2(problem,'lambda',lambda,'checkMonomials',false);\nrmpath(genpath(spotpath))\n\n%% Solve using STRIDE\n% Primal initialization\nif rungnc\n    solution        = gnc_category_registration(problem,SDP,path,'lambda',lambda);\n    [R_est,t_est]   = invert_transformation(solution.R_est,solution.t_est);\n\n    v0       = lift_catreg_v2(R_est(:),...\n                              t_est(:),...\n                              solution.c_est(:),...\n                              solution.theta_est(:),...\n                              problem.cBound,...\n                              problem.translationBound);\n    X0          = rank_one_lift(v0);\n    gnc.R_err   = getAngularError(problem.R_gt,solution.R_est);\n    gnc.t_err   = getTranslationError(problem.t_gt,solution.t_est);\n    gnc.c_err   = getTranslationError(problem.c_gt,solution.c_est);\n    gnc.time    = solution.time;\n    gnc.info    = solution;\n\nelse\n    X0       = [];\nend\n\n% dual initialization\naddpath(genpath(spotpath))\nchordalSDP     = chordal_relax_category_registration_v2(problem,'lambda',lambda);\nrmpath(genpath(spotpath))\nprob = convert_sedumi2mosek(chordalSDP.sedumi.At,...\n                            chordalSDP.sedumi.b,...\n                            chordalSDP.sedumi.c,...\n                            chordalSDP.sedumi.K);\naddpath(genpath(mosekpath))\ntime0   = tic;\nparam.MSK_IPAR_INTPNT_MAX_ITERATIONS = 20; % set maximum iterations 20\n[~,res] = mosekopt('minimize info',prob,param);\ntime_dualInit = toc(time0);\n[Xchordal,ychordal,Schordal,~] = recover_mosek_sol_blk(res,chordalSDP.blk);\nS_assm             = catreg_dual_from_chordal_dual_v2(Schordal,problem.N,problem.K);\n\n\n% STRIDE main algorithm\naddpath(genpath(stridepath))\naddpath(genpath(manoptpath))\n\npgdopts.pgdStepSize     = 10;\npgdopts.SDPNALpath      = sdpnalpath;\npgdopts.maxiterPGD      = 5;\n% ADMM parameters\npgdopts.tolADMM         = 1e-10;\npgdopts.maxiterADMM     = 1e4;\npgdopts.stopoptionADMM  = 0;\n\npgdopts.rrOpt           = 1:3;\npgdopts.rrFunName       = 'local_search_catreg_v2';\nrrPar.blk = SDP.blk; rrPar.translationBound = problem.translationBound;\nrrPar.N = problem.N; rrPar.K = problem.K; rrPar.cBound = problem.cBound;\npgdopts.rrPar           = rrPar;\npgdopts.maxiterLBFGS    = 1000;\npgdopts.maxiterSGS      = 1000;\npgdopts.lbfgseps        = false;\npgdopts.S0              = S_assm;\n\n\n[outPGD,Xopt,yopt,Sopt]     = PGDSDP(SDP.blk, SDP.At, SDP.b, SDP.C, X0, pgdopts);\nrmpath(genpath(manoptpath))\n\ninfostride                  = get_performance_catreg_v2(Xopt,yopt,Sopt,SDP,problem,stridepath);\ninfostride.totaltime        = outPGD.totaltime + time_dualInit;\ninfostride.time             = [outPGD.totaltime,time_dualInit];\nif rungnc \n    infostride.gnc  = gnc; \n    infostride.totaltime = infostride.totaltime + gnc.time;\n    infostride.time      = [gnc.time,infostride.time];\nend\n\nfprintf('\\n\\n\\n\\n\\n')\n", "meta": {"author": "MIT-SPARK", "repo": "CertifiablyRobustPerception", "sha": "dd149d0c54093cfb72a8f912f4ae807635db6f3b", "save_path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception", "path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception/CertifiablyRobustPerception-dd149d0c54093cfb72a8f912f4ae807635db6f3b/CategoryRegistration/example_category_registration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5995728075965513}}
{"text": "classdef LossSmoothL1 < dagnn.Loss\n%LossSmoothL1  Smooth L1 loss\n%  `LossSmoothL1.forward({x, x0, w})` computes the smooth L1 distance \n%  between `x` and `x0`, weighting the elements by `w`.\n%\n%  Here the smooth L1 loss between two vectors is defined as:\n%\n%     Loss = sum_i f(x_i - x0_i) w_i.\n%\n%  where f is the function (following the Faster R-CNN definition):\n%\n%              { 0.5 * sigma^2 * delta^2,         if |delta| < 1 / sigma^2,\n%   f(delta) = {\n%              { |delta| - 0.5 / sigma^2,         otherwise.\n%\n%  In practice, `x` and `x0` can pack multiple instances as 1 x 1 x C\n%  x N arrays (or simply C x N arrays).\n\n  properties\n    sigma = 1.\n  end\n\n  methods\n    function outputs = forward(obj, inputs, params)\n      sigma2 = obj.sigma^2 ;\n      delta = inputs{1} - inputs{2} ;\n      absDelta = abs(delta) ;\n\n      linearRegion = (absDelta > 1. / sigma2) ;\n      absDelta(linearRegion) = absDelta(linearRegion) - 0.5/sigma2 ;\n      absDelta(~linearRegion) = 0.5 * sigma2 * absDelta(~linearRegion).^2 ;\n\n      % Mutliply by instance weights and sum.\n      outputs{1} = inputs{3}(:)' * absDelta(:) ;\n\n      % Accumulate loss statistics.\n      if obj.ignoreAverage, return; end;\n      n = obj.numAveraged ;\n      m = n + gather(sum(inputs{3}(:))) + 1e-9 ;\n      obj.average = (n * obj.average + gather(outputs{1})) / m ;\n      obj.numAveraged = m ;\n    end\n\n    function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)\n    % Function derivative:\n    %\n    %          { sigma^2 * x,             if |x| < 1 / sigma^2,\n    %  f'(x) = {\n    %          { sign(x),                 otherwise.\n\n      sigma2 = obj.sigma^2 ;\n      delta = inputs{1} - inputs{2} ;\n      absDelta = abs(delta) ;\n\n      linearRegion = (absDelta > 1. / sigma2) ;\n      delta(linearRegion) = sign(delta(linearRegion));\n      delta(~linearRegion) = sigma2 * delta(~linearRegion) ;\n\n      derInputs = {inputs{3} .* delta .* derOutputs{1}, [], []} ;\n      derParams = {} ;\n    end\n\n    function obj = LossSmoothL1(varargin)\n      obj.load(varargin) ;\n      obj.loss = 'smoothl1';\n    end\n  end\nend\n", "meta": {"author": "phoenix104104", "repo": "LapSRN", "sha": "95154bba82a3aab9bdaec8e0eedd4187babc5ed2", "save_path": "github-repos/MATLAB/phoenix104104-LapSRN", "path": "github-repos/MATLAB/phoenix104104-LapSRN/LapSRN-95154bba82a3aab9bdaec8e0eedd4187babc5ed2/matconvnet/examples/fast_rcnn/+dagnn/LossSmoothL1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.599572804207929}}
{"text": "function [ccg,ic] = chXcorr(hc_L,hc_R,fs,varargin)\n%CHXCORR Calculate cross-correlograms with a wide range of options.\n% \n%   CCG = IOSR.AUDITORY.CHXCORR(HC_L,HC_R,FS) cross-correlates the input\n%   2-D matrices HC_L and HC_R over 10ms frame with a maximum lag of 1ms.\n%   It is assumed that the number of frequency channels is min(size(HC_L))\n%   and hence HC_L and HC_R can be in either orientation. The\n%   cross-correlograms consist of cross-correlations for every frame and\n%   frequency channel. CCG has dimensions [lag,frequency,frame]. The\n%   function calculates running cross-correlations for every sample and\n%   integrates these cross-correlations over each frame. The number of\n%   frames frame_count is calculated thus:\n% \n%       frame_count = ...\n%           floor((max(size(hc_L))-maxlag-1)/frame_length);\n% \n%   The underlying cross-correlation algorithm is based on that proposed by\n%   Faller & Merimaa [1]. In this implmentation, the time constant of the\n%   backward infinite exponential window is given by tau (in samples).\n%   \n%   CCG = IOSR.AUDITORY.CHXCORR(HC_L,HC_R,FS,'PARAMETER',VALUE) allows a\n%   number of options to be specified. The options are:\n% \n%   ({} indicates the default value)\n% \n%   'frame_length'   : {round(0.01*fs)} | scalar\n%       The length of frames used to calculate for integrating\n%       cross-correlations.\n%   'noverlap'       : {1} | scalar\n%       The number of frames over which to integrate the\n%       cross-correlations. Note that the frame count is reduced\n%       accordingly.\n%   'maxlag'         : {round(0.001*fs)} | scalar\n%       The maximum lag of the cross-correlation.\n%   'tau'            : {round(0.01*fs)} | scalar\n%       The time constant of the exponential window used to calculate\n%       running cross-correlations. It is recommended that if norm_flag = 1\n%       then tau >> 1. As can be seen below, as tau -> 1 then \n%       [aL(m,i,n?1), aR(m,i,n?1)] -> 0, and hence c(m,i,n) -> 1.\n%   'inhib'          : {[]} | array\n%       Specificies an array with which to multiply the cross-correlations\n%       before they are integrated. The value defaults to an empty array,\n%       meaning that no inhibition will be applied.\n%   'ic_t'           : {0} | scalar\n%       Specifies the interaural coherence (IC) threshold. Only samples for\n%       which the IC exceeds this threshold will be used to integrate\n%       cross-correlations. The algorithm calculates Interaural Coherence\n%       (IC) according to [1]. The value should be in the range [0,1].\n%   'norm_flag'      : {0} | scalar\n%       Specifies whether the cross-correlograms are calculated using\n%       normalised cross-correlations. A non-zero value indicates that\n%       normalised cross-correlations are used.\n%   'inhib_mode'     : {'subtract'} | 'multiply'\n%       Specify how the inhibition is applied. The default 'subtract' will\n%       subtract inhib from the running cross-correlations (negative values\n%       are set to zero); 'multiply' will multiply inhib with the running\n%       cross-correlations.\n% \n%   [CCG,IC] = IOSR.AUDITORY.CHXCORR(...) returns the calculated IC to the\n%   matrix IC. Although the matrix returned is the same size as hc_L, IC is\n%   only calculated for samples 1:frame_count*frame_length, other values\n%   will be set to 0.\n% \n%   Algorithm\n% \n%   The running normalised cross-correlation is calculated as [1]:\n% \n%   C(m,i,n) = c(m,i,n) / sqrt( aL(m,i,n) * aR(m,i,n)\n% \n%   where\n% \n%   c(m,i,n) = (1/tau) * HC_L(i, max(n+m,n)) * HC_R(i, max(n-m,n)) + ...\n%       (1-1/tau) * c(m,i,n-1),\n% \n%   aL(m,i,n) = (1/tau) * (HC_L(i, max(n+m,n)))^2 + ...\n%       (1-1/tau) * aL(m,i,n-1),\n% \n%   aR(m,i,n) = (1/tau) * (HC_R(i, max(n+m,n)))^2 + ...\n%       (1-1/tau) * aR(m,i,n-1),\n% \n%   i is the frequency index, m is the lag index, and n is the sample\n%   index. The running (non-normalised) cross-correlation is calculated is\n%   simply c(m,i,n).\n% \n%   The interaural coherence is\n% \n%   IC(i,n) = max(C(m,i,n)) % (i.e. over m)\n% \n%   The cross-correlogram is calculated as the sum of cross- correlations\n%   in a given frame:\n% \n%   CCG(m,i,j) = sum(C(m,i,J),3)\n% \n%   where\n% \n%   J = (j-1) * frame_length + 1 : j * frame_length\n% \n%   References\n% \n%   [1] C. Faller and J. Merimaa, \"Source localization in complex listening\n%       situations: Selection of binaural cues based on interaural\n%       coherence\", The Journal of the Acoustical Society of America, vol.\n%       116, pp.3075-3089, Nov. 2004.\n% \n%   Further Reading\n%   \n%   C. Hummersone, R. Mason, and T. Brookes, \"A comparison of computational\n%       precedence models for source separation in reverberant\n%       environments\", The Journal of the Audio Engineering Society, vol.\n%       61(7/8), pp.508-520, July 2013.\n\n%   Copyright 2016 University of Surrey.\n\n    assert(nargin>=3, 'iosr:chXcorr:nargin', 'Number of input arguments must be greater than or equal to three.')\n\n    if isparameter(varargin,'inhib_mode') && ~isparameter(varargin,'inhib')\n        warning('iosr:instIld:inhibMode','''inhib_mode'' specified, but no inhibition array ''inhib''.');\n    end\n\n    % Check source file is compiled\n    iosr.general.checkMexCompiled('-largeArrayDims',fullfile(fileparts(mfilename('fullpath')),'chXcorr_c.c'))\n\n    options = struct(...\n        'frame_length',round(0.01*fs),...\n        'noverlap',1,...\n        'maxlag',round(0.001*fs),...\n        'tau',round(0.01*fs),...\n        'inhib',[],...\n        'ic_t',0,...\n        'norm_flag',0,...\n        'inhib_mode','subtract');\n\n    % read parameter/value inputs\n    if nargin > 3 % if parameters are specified\n        % read the acceptable names\n        optionNames = fieldnames(options);\n        % count arguments\n        nArgs = length(varargin);\n        if round(nArgs/2)~=nArgs/2\n           error('iosr:chXcorr:nameValuePair','CHXCORR needs propertyName/propertyValue pairs')\n        end\n        % overwrite defults\n        for pair = reshape(varargin,2,[]) % pair is {propName;propValue}\n           IX = strcmpi(pair{1},optionNames); % find match parameter names\n           if any(IX)\n              % do the overwrite\n              options.(optionNames{IX}) = pair{2};\n           else\n              error('iosr:chXcorr:unknownOption','%s is not a recognized parameter name',pair{1})\n           end\n        end\n    end\n\n    % assign options to variables\n    frame_length = options.frame_length;\n    noverlap = options.noverlap;\n    maxlag = options.maxlag;\n    tau = options.tau;\n    inhib_mode = options.inhib_mode;\n    norm_flag = options.norm_flag;\n    ic_t = options.ic_t;\n    inhib = options.inhib;\n\n    % check inputs\n    assert(all(size(hc_L)==size(hc_R)), 'iosr:chXcorr:invalidInput', '''hc_L'' and ''hc_R'' must be the same size')\n    assert(round(frame_length)==frame_length && isscalar(frame_length) && frame_length>0, 'iosr:chXcorr:invalidFrame', ...\n        '''frame_length'' must be an integer greater than zero')\n    assert(round(noverlap)==noverlap && isscalar(noverlap) && noverlap>0, 'iosr:chXcorr:invalidNoverlap', ...\n        '''noverlap'' must be an integer greater than zero')\n    assert(round(maxlag)==maxlag && isscalar(maxlag) && maxlag>0, 'iosr:chXcorr:invalidMaxlag', ...\n        '''maxlag'' must be an integer greater than zero')\n    assert(isscalar(tau) && tau>=1, 'iosr:chXcorr:invalidTau', '''tau'' must be a scalar greater than or equal to one')\n    assert(isscalar(norm_flag), 'iosr:chXcorr:invalidNorm', '''norm_flag'' must be a scalar')\n    assert(isscalar(ic_t) && ic_t>=0 && ic_t<=1, 'iosr:chXcorr:invalidIct', '''ic_t'' must be a scalar in the range [0,1]')\n    assert(ischar(inhib_mode), 'iosr:chXcorr:invalidInhibMode', '''inhib_mode'' must be a char array (string)')\n\n    % Calculate frame count\n    frame_count = floor(max(size(hc_L))/(frame_length));\n    frame_count = frame_count-noverlap+1;\n\n    % Calculate number of frequency channels\n    numchans = min(size(hc_L));\n    numsamples = max(size(hc_L));\n\n    % Check orientation of HC and inhib data (i.e. that frequency runs across the rows)\n    dims = size(hc_L);\n    hc_L = check_input(hc_L,2,numchans);\n    hc_R = check_input(hc_R,2,numchans);\n\n    % set a flag if data has been transposed in this way\n    if dims(1)~=size(hc_L,1)\n        rot = true;\n    else\n        rot = false;\n    end\n\n    % set inhibition mode ID\n    switch inhib_mode\n        case 'multiply'\n            inhib_mode_ID = 1;\n            if isempty(inhib)\n                inhib = ones(size(hc_L));\n            end\n        case 'subtract'\n            inhib_mode_ID = 2;\n            if isempty(inhib)\n                inhib = zeros(size(hc_L));\n            end\n        otherwise\n            error('iosr:chXcorr:unknownInhibMode','''inhib_mode'' must be set to ''multiply'' or ''subtract''')\n    end\n\n    inhib = check_input(inhib,2,numchans);\n\n    % Append HC and inhibition data with zeros for cross-correlation\n    hc_L = [hc_L; zeros(maxlag+1,numchans)];\n    hc_R = [hc_R; zeros(maxlag+1,numchans)];\n    inhib = [inhib; zeros(maxlag+1,numchans)];\n\n    assert(all(size(inhib)==size(hc_L)), 'iosr:chXcorr:invalidInhib', '''inhib'' must be a matrix the same size as ''hc_L'' or ''hc_R''')\n\n    % Calculate cross-correlograms\n    [ccg,ic] = iosr.auditory.chXcorr_c(hc_L,hc_R,frame_count,frame_length,noverlap,maxlag,tau,inhib,ic_t,norm_flag,inhib_mode_ID);\n\n    % Correct orientation of IC data, if data was transposed, and crop to remove appended zeros\n    ic = ic(1:numsamples,:);\n    if rot\n        ic = ic';\n    end\n\nend\n\nfunction output = check_input(input,dim,target)\n%CHECK_INPUT check input is correct orientation\n\n    if size(input,dim)~=target\n        output = input';\n        assert(size(output,dim)==target, 'iosr:chXcorr:invalidInputs', 'Input invalid')\n    else\n        output = input;\n    end\n\nend\n\nfunction set = isparameter(input,parameter)\n%ISPARAMETER check for input parameter\n\n    set = any(strcmpi(input(cellfun(@ischar,input)),parameter));\n\nend\n", "meta": {"author": "IoSR-Surrey", "repo": "MatlabToolbox", "sha": "4bff1bb2da7c95de0ce2713e7c710a0afa70c705", "save_path": "github-repos/MATLAB/IoSR-Surrey-MatlabToolbox", "path": "github-repos/MATLAB/IoSR-Surrey-MatlabToolbox/MatlabToolbox-4bff1bb2da7c95de0ce2713e7c710a0afa70c705/+iosr/+auditory/chXcorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.599572798596266}}
{"text": "function varargout = cosh(varargin)\n%COSH   Hyperbolic cosine of a DISKFUN.\n%   COSH(F) returns the hyperbolic cosine of F.\n% \n% See also DISKFUN/SINH, DISKFUN/COS.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n[varargout{1:nargout}] = cosh@separableApprox(varargin{:});\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/@diskfun/cosh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.599572792984603}}
{"text": "%% CS294A/CS294W Linear Decoder Exercise\n\n%  Instructions\n%  ------------\n%\n%  This file contains code that helps you get started on the\n%  linear decoder exericse. For this exercise, you will only need to modify\n%  the code in sparseAutoencoderLinearCost.m. You will not need to modify\n%  any code in this file.\n\naddpath '../library/'\naddpath '../library/minFunc/'\n\n%%======================================================================\n%% STEP 0: Initialization\n%  Here we initialize some parameters used for the exercise.\n\nimageChannels = 3;     % number of channels (rgb, so 3)\n\npatchDim = 8;          % patch dimension\nnumPatches = 100000;   % number of patches\n\nvisibleSize = patchDim * patchDim * imageChannels;  % number of input units\noutputSize = visibleSize;   % number of output units\nhiddenSize = 400;           % number of hidden units\n\nsparsityParam = 0.035; % desired average activation of the hidden units.\nlambda = 3e-3;         % weight decay parameter\nbeta = 5;              % weight of sparsity penalty term\n\nepsilon = 0.1;\t       % epsilon for ZCA whitening\n\n% %%======================================================================\n% %% STEP 1: Create and modify sparseAutoencoderLinearCost.m to use a linear decoder,\n% %          and check gradients\n% %  You should copy sparseAutoencoderCost.m from your earlier exercise\n% %  and rename it to sparseAutoencoderLinearCost.m.\n% %  Then you need to rename the function from sparseAutoencoderCost to\n% %  sparseAutoencoderLinearCost, and modify it so that the sparse autoencoder\n% %  uses a linear decoder instead. Once that is done, you should check\n% % your gradients to verify that they are correct.\n%\n% % NOTE: Modify sparseAutoencoderCost first!\n%\n% % To speed up gradient checking, we will use a reduced network and some\n% % dummy patches\n% hiddenSize = 5;\n% visibleSize = 8;\n% patches = rand([8 10]);\n% theta = initializeParameters(hiddenSize, visibleSize);\n%\n% [cost, grad] = sparseAutoencoderLinearCost(theta, visibleSize, hiddenSize, ...\n%                                            lambda, sparsityParam, beta, ...\n%                                            patches);\n%\n% % Check gradients\n% numGrad = computeNumericalGradient( @(x) sparseAutoencoderLinearCost(x, visibleSize, hiddenSize, ...\n%                                                   lambda, sparsityParam, beta, ...\n%                                                   patches), theta);\n%\n% % Use this to visually compare the gradients side by side\n% disp([numGrad grad]);\n%\n% diff = norm(numGrad-grad)/norm(numGrad+grad);\n% % Should be small. In our implementation, these values are usually less than 1e-9.\n% disp(diff);\n%\n% assert(diff < 1e-9, 'Difference too large. Check your gradient computation again');\n%\n% % NOTE: Once your gradients check out, you should run step 0 again to\n% %       reinitialize the parameters\n% %}\n\n%%======================================================================\n%% STEP 2: Learn features on small patches\n%  In this step, you will use your sparse autoencoder (which now uses a\n%  linear decoder) to learn features on small patches sampled from related\n%  images.\n\n%% STEP 2a: Load patches\n%  In this step, we load 100k patches sampled from the STL10 dataset and\n%  visualize them.\n\npatches = load('../data/STL10Patches100k.mat');\npatches = patches.patches;\n\ndisplayColorNetwork(patches(:, 1:100));\n\n\n%% STEP 2b: Apply preprocessing\n%  In this sub-step, we preprocess the sampled patches, in particular,\n%  ZCA whitening them.\n%\n%  In a later exercise on convolution and pooling, you will need to replicate\n%  exactly the preprocessing steps you apply to these patches before\n%  using the autoencoder to learn features on them. Hence, we will save the\n%  ZCA whitening and mean image matrices together with the learned features\n%  later on.\n\n% Scale data to range [0, 1]\npatches = patches / 255;\n\n% Subtract mean patch (hence zeroing the mean of the patches)\nmeanPatch = mean(patches, 2);\npatches = bsxfun(@minus, patches, meanPatch);\n\n% Apply ZCA whitening\nsigma = patches * patches' / numPatches;\n[u, s, v] = svd(sigma);\nZCAWhite = u * diag(1 ./ (diag(s) + epsilon)) * u';\npatches = ZCAWhite * patches;\n\ndisplayColorNetwork(patches(:, 1:100));\n\n%% STEP 2c: Learn features\n%  You will now use your sparse autoencoder (with linear decoder) to learn\n%  features on the preprocessed patches. This should take around 45 minutes.\n\ntheta = initializeParameters(hiddenSize, visibleSize);\n\n% Use minFunc to minimize the function\n\nclear('options');\noptions.Method = 'lbfgs';\noptions.maxIter = 400;\noptions.display = 'on';\n\n[optTheta, cost] = minFunc( @(p) sparseAutoencoderLinearCost(p, ...\n                                   visibleSize, hiddenSize, ...\n                                   lambda, sparsityParam, ...\n                                   beta, patches), ...\n                              theta, options);\n\n% Save the learned features and the preprocessing matrices for use in\n% the later exercise on convolution and pooling\nfprintf('Saving learned features and preprocessing matrices...\\n');\nsave('STL10Features.mat', 'optTheta', 'ZCAWhite', 'meanPatch');\nfprintf('Saved\\n');\n\n%% STEP 2d: Visualize learned features\n\nW = reshape(optTheta(1:visibleSize * hiddenSize), hiddenSize, visibleSize);\nb = optTheta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);\ndisplayColorNetwork(W');\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/linear_decoder_exercise/linearDecoderExercise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.5995703627863427}}
{"text": "function c = nancov(x,varargin)\n%NANCOV Covariance matrix, ignoring NaNs.\n%   C = NANCOV(X), if X is a vector, returns the sample variance of the\n%   values in X, treating NaNs as missing values.  For matrices, where\n%   each row is an observation and each column a variable, NANCOV(X) is\n%   the covariance matrix computing using rows of X that do not contain\n%   any NaN values.  NANCOV(X,Y), where X and Y are matrices with\n%   the same number of elements, is equivalent to NANCOV([X(:) Y(:)]). \n%   \n%   NANCOV(X) or NANCOV(X,Y) normalizes by (N-1) if N>1, where N is the\n%   number of observations after removing missing values.  This makes\n%   NANCOV(X) the best unbiased estimate of the covariance matrix if the\n%   observations are from a normal distribution. For N=1, COV normalizes\n%   by N.\n%\n%   NANCOV(X,1) or NANCOV(X,Y,1) normalizes by N and produces the second\n%   moment matrix of the observations about their mean.  NANCOV(X,Y,0) is\n%   the same as NANCOV(X,Y), and NANCOV(X,0) is the same as NANCOV(X).\n%\n%   C = NANCOV(...,'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 = NANCOV(...,'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%   The mean is removed from each column before calculating the\n%   result.\n%\n%   Example:  Generate random data having non-zero covariance between\n%             column 4 and the other columns.\n%       x = randn(30,4);       % uncorrelated data\n%       x(:,4) = sum(x,2);     % introduce correlation\n%       x(2,3) = NaN;          % introduce one missing value\n%       c = nancov(x)          % compute sample covariance\n%\n%   Class support for inputs X,Y:\n%      float: double, single\n%\n%   See also COV, VAR, NANVAR.\n\n%   Copyright 1984-2011 The MathWorks, Inc.\n%   $Revision: 1.1.8.3 $  $Date: 2011/02/09 19:35:29 $\n\nif nargin<1\n   error(message('stats:nancov:NotEnoughInputs'));\nend\n\n% Should we ignore NaNs by complete rows or pairwise?\ndopairwise = false;\nif numel(varargin)>0\n   temp = varargin{end};\n   if ischar(temp)\n      j = find(strncmpi(temp, {'pairwise' 'complete'},length(temp)));\n      if isempty(j)\n         error(message('stats:nancov:InvalidArg', temp));\n      end\n      dopairwise = (j==1);\n      varargin(end) = [];\n   end\nend\n\n% Should we use the mle (divide by N) or unbiased estimate (N-1)?\ndomle = false;\nif numel(varargin)>0\n   temp = varargin{end};\n   if isequal(temp,0) || isequal(temp,1)\n      domle = (temp==1);\n      varargin(end) = [];\n   end\nend\n\nif numel(varargin)>1\n   error(message('stats:nancov:TooManyArgs'));\nend\n\nscalarxy = false; % nancov(scalar,scalar) is an ambiguous case\nif numel(varargin)>0\n   y = varargin{1};\n\n   % Two inputs, convert to equivalent single input\n   x = x(:);\n   y = y(:);\n   if length(x)~=length(y)\n      error(message('stats:nancov:XYmismatch'));\n   end\n   scalarxy = isscalar(x) && isscalar(y);\n   x = [x y];\nelseif ndims(x)>2\n   error(message('stats:nancov:InputDim'));\nend\n\nif isvector(x) && ~scalarxy\n  x = x(:);\nend\n\nxnan = isnan(x);\n[m,n] = size(x);\n\nif isempty(x);\n  if (m==0 && n==0)\n      c = NaN(class(x));\n  else\n      c = NaN(n,class(x));\n  end\n  return;\nend\n\nif ~dopairwise || ~any(any(xnan))    % no need to do pairwise\n   nanrows = any(xnan,2);\n   if any(nanrows)\n       x = x(~nanrows,:);\n   end\n   c = localcov(x,domle);\nelse                                         % pairwise with some NaNs\n   % Compute variance using complete data separately by column\n   c = zeros(n,class(x));\n   x(xnan) = 0;\n   colsize = sum(~xnan,1);\n   xmean = sum(x,1) ./ max(1,colsize);\n   xmean(colsize==0) = NaN;\n   xc = x - repmat(xmean,m,1);\n   xc(xnan) = 0;\n   xvar = sum(xc.^2,1);\n   if domle\n      denom = colsize;\n   else\n      denom = max(0,colsize-1);\n   end\n   xvar(denom>1) = xvar(denom>1) ./ denom(denom>1);\n   xvar(denom==0) = NaN;\n   c(1:n+1:end) = xvar;\n\n   % Now compute off-diagonal entries\n   jk = 1:2;\n   for j = 2:n\n      jk(1) = j;\n      for k=1:j-1\n         jk(2) = k;\n         rowsjk = ~any(xnan(:,jk),2);\n         njk = sum(rowsjk);\n         if njk<=1\n            cjk = NaN;\n         else\n            cjk = localcov(x(rowsjk,jk),domle);\n            cjk = cjk(1,2);\n         end\n         c(j,k) = cjk;\n      end\n   end\n   c = c + tril(c,-1)';\nend\n\n% ------------------------------------------------\nfunction [c,n] = localcov(x,domle)\n%LOCALCOV Compute cov with no error checking and assuming NaNs are removed\n\n[m,n] = size(x);\nif domle\n   denom = m;\nelse\n   denom = max(0,m-1);\nend\n\nif m==1   % and doing mle, be sure to get exact 0\n   c = zeros(n,class(x));\nelseif denom==0\n   c = NaN(n,class(x));\nelse\n   xc = x - repmat(mean(x),m,1);\n   c = xc' * xc / denom;\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/nancov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.5995703508876661}}
{"text": "function varargout = calcTensor(odf,T,varargin)\n% compute the average tensor for an ODF\n%\n% Syntax\n%   [TVoigt, TReuss, THill] = calcTensor(odf,T)\n%   THill = calcTensor(odf,T,'Hill')\n%   TGeo = calcTensor(odf,T,'geometric')\n%\n% Input\n%  odf - @SO3Fun\n%  T   - @tensor\n%\n% Output\n%  T    - @tensor\n%\n% Options\n%  Voigt     - Boigt mean\n%  Reuss     - Reuss mean\n%  Hill      - Hill mean\n%  geometric - geometric mean\n%\n% See also\n% tensor/mean EBSD/calcTensor\n\n% decide between the quadrature based method and the harmonic method\nif ~check_option(varargin,'quadrature')\n\n  % the harmonic route is directly implemented into tensor/mean\n  [varargout{1:nargout}] = mean(T,odf,varargin{:});\n\nelse % quadrature based method\n\n  % define a grid\n  res = get_option(varargin,'resolution',2.5*degree);\n  S3G = equispacedSO3Grid(odf.CS,odf.SS,'resolution',res);\n\n  % evaluate the ODF\n  f = eval(odf,S3G,varargin{:});\n  f = f ./ sum(f(:));\n\n  % compute the means\n  [varargout{1:nargout}] = mean(S3G*T,'weights',f(:),varargin{:});\n\nend\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/SO3Fun/@SO3Fun/calcTensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5995414640888567}}
{"text": "function [nrm] = normals(pnt, tri, opt)\n\n% NORMALS compute the surface normals of a triangular mesh\n% for each triangle or for each vertex\n%\n% Use as\n%   [nrm] = normals(pnt, tri, opt)\n% where opt is either 'vertex' (default) or 'triangle'.\n%\n% See also PCNORMALS, PROJECTTRI\n\n% Copyright (C) 2002-2007, 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 <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nif nargin<3\n  opt='vertex';\nelseif (opt(1)=='v' || opt(1)=='V')\n  opt='vertex';\nelseif (opt(1)=='t' || opt(1)=='T')\n  opt='triangle';\nelse\n  ft_error('invalid optional argument');\nend\n\nnpnt = size(pnt,1);\nntri = size(tri,1);\n\n% shift to center\npnt(:,1) = pnt(:,1)-mean(pnt(:,1),1);\npnt(:,2) = pnt(:,2)-mean(pnt(:,2),1);\npnt(:,3) = pnt(:,3)-mean(pnt(:,3),1);\n\n% compute triangle normals\n% nrm_tri = zeros(ntri, 3);\n% for i=1:ntri\n%   v2 = pnt(tri(i,2),:) - pnt(tri(i,1),:);\n%   v3 = pnt(tri(i,3),:) - pnt(tri(i,1),:);\n%   nrm_tri(i,:) = cross(v2, v3);\n% end\n\n% vectorized version of the previous part\nv2 = pnt(tri(:,2),:) - pnt(tri(:,1),:);\nv3 = pnt(tri(:,3),:) - pnt(tri(:,1),:);\nnrm_tri = cross(v2, v3);\n\n\nif strcmp(opt, 'vertex')\n  % compute vertex normals\n  nrm_pnt = zeros(npnt, 3);\n  for i=1:ntri\n    nrm_pnt(tri(i,1),:) = nrm_pnt(tri(i,1),:) + nrm_tri(i,:);\n    nrm_pnt(tri(i,2),:) = nrm_pnt(tri(i,2),:) + nrm_tri(i,:);\n    nrm_pnt(tri(i,3),:) = nrm_pnt(tri(i,3),:) + nrm_tri(i,:);\n  end\n  % normalise the direction vectors to have length one\n  nrm = nrm_pnt ./ (sqrt(sum(nrm_pnt.^2, 2)) * ones(1,3));\nelse\n  % normalise the direction vectors to have length one\n  nrm = nrm_tri ./ (sqrt(sum(nrm_tri.^2, 2)) * ones(1,3));\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% fast cross product to replace the MATLAB standard version\nfunction [c] = cross(a,b)\nc = [a(:,2).*b(:,3)-a(:,3).*b(:,2) a(:,3).*b(:,1)-a(:,1).*b(:,3) a(:,1).*b(:,2)-a(:,2).*b(:,1)];\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/forward/private/normals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.599541462073459}}
{"text": "function fk_space = autoGen_fk_space(q1,q2,q3)\n%AUTOGEN_FK_SPACE\n%    FK_SPACE = AUTOGEN_FK_SPACE(Q1,Q2,Q3)\n\n%    This function was generated by the Symbolic Math Toolbox version 8.4.\n%    01-Jun-2020 11:59:03\n\nt2 = cos(q1);\nt3 = cos(q2);\nt4 = sin(q1);\nt5 = q2+q3;\nt6 = cos(t5);\nt7 = sin(t5);\nt8 = t3.*(4.0./2.5e+1);\nt9 = t6.*(5.7e+1./2.0e+2);\nt10 = t8+t9;\nfk_space = reshape([t2.*t6,t4.*t6,-t7,0.0,-t4,t2,0.0,0.0,t2.*t7,t4.*t7,t6,0.0,t2.*t10,t4.*t10,t7.*(-5.7e+1./2.0e+2)-sin(q2).*(4.0./2.5e+1),1.0],[4,4]);\n", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/autoGen_fk_space.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5995414580426636}}
{"text": "function [varargout, peval] = separcomp(dpix, peval, winit_pix, hinit)\n% separcomp(dpix, p_script, savethis, winit, hinit)\n% separate components\n% V ~ WH\n% V -> N_pix x N_t\n% W -> N_pix x N_comp - xth pixel of the ith components\n% H -> N_copm x N_t - contribution of the i-th component in the time t\n\n[peval.nx, peval.ny, peval.nt] = size(dpix);\npeval.numpix = peval.nx*peval.ny;\npeval.meandata = mean(dpix(:));\n\ndvec = reshape(dpix,peval.numpix, peval.nt);\ndpix_dip = dip_image(dpix);\n\n% background subtraction with empirical values:\npeval.bg_clip = 'no'; \npeval.bg_fs_var = 5; \npeval.bg_perc = 20; \npeval.bg_ob_dist = 8;\nif ~isfield(peval, 'bg')\n    [out_nobg, peval.bg, bg_im]=backgroundoffset(dpix_dip, peval.bg_clip, peval.bg_fs_var, peval.bg_perc, peval.bg_ob_dist);\nend\n\nif ~isfield(peval, 'ncomp')\n    peval.ncomp=estimate_ncpomp(dvec);\nend\n\n[winit, hinit] = initwh(winit_pix, hinit, peval); %initialization of w and h\n\n\n\nif ~isfield(peval, 'w_fixvec') peval.w_fixvec=[]; end\nif ~isfield(peval, 'h_fixvec') peval.h_fixvec=[]; end\n\nif isempty(peval.w_fixvec)\n    peval.w_fixvec = peval.ncomp + 1; %fixing background component\nelseif ~(peval.w_fixvec(end) == peval.ncomp + 1)\n    peval.w_fixvec = [peval.w_fixvec, peval.ncomp + 1];\nend\n\nif isempty(peval.h_fixvec)\n    peval.h_fixvec = peval.ncomp + 1; %fixing background component\nelseif ~(peval.h_fixvec(end) == peval.ncomp + 1)\n    peval.h_fixvec = [peval.h_fixvec, peval.ncomp + 1];\nend\n\nverbose = 1;\n% if strcmp (peval.method, 'nmf_classic') %classical nmf updates    \n%     [w,h,peval, dtrace, htrace]=nmf_classic(dvec,winit,hinit,peval,verbose);\n% elseif strcmp (peval.method, 'nmf_conjgrad_penalty') %classical nmf updates\n%     [w,h,peval, dtrace, htrace]=nmf_conjgrad_penalty(dvec,winit,hinit,peval,verbose);\n% end\neval (['[w,h,peval, dtrace, htrace]=' peval.method '(dvec,winit,hinit,peval,verbose);']);\n\nvarargout = struct('w',w,'h',h, 'dtrace', dtrace, 'htrace', htrace);", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/separ/separcomp_penalty.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5995414545175545}}
{"text": "%% INS\u60ef\u5bfc\u89e3\u7b97\nclear;\nclc;\nclose all;\n\n%% \nFs = 100;  %\u91c7\u6837\u9891\u7387\nN = 1000; %\u91c7\u6837\u6b21\u6570\n\ndt = 1 / Fs;\ngyr = [0.01, 0.02, 0.03]; %\u5355\u4f4drad\nacc = [0, 0, 9.8]; % \u5355\u4f4dm/s^(2)\n\n% \u6377\u8054\u60ef\u5bfc\u89e3\u7b97\np = zeros(3, 1);\nv = zeros(3, 1);\nq= [1 0 0 0]';\n\nfor i=1:N\n    [p ,v, q] = ch_nav_equ_local_tan(p, v, q, acc', gyr' , dt, [0, 0, -9.8]');\n    h_pos(i,:) = p;\n    h_vel(i,:) = v;\n    h_eul(i,:) = ch_q2eul(q);\nend\n\nfigure;\nsubplot(2,2,1);\nch_plot_pos3d(h_pos);\nsubplot(2,2,2);\nch_plot_pos2d(h_pos);\nsubplot(2,2,3);\nch_plot_att(h_eul);\n\nfprintf('\u7eaf\u79ef\u5206\u6d4b\u8bd5: \u9640\u87ba(rad/s):%.3f %.3f %.3f\\n', gyr(1), gyr(2), gyr(3));\nfprintf('\u7eaf\u79ef\u5206\u6d4b\u8bd5: \u52a0\u8ba1(m/s^(2)):%.3f %.3f %.3f\\n', acc(1), acc(2), acc(3));\n\nfprintf('\u89e3\u7b97:%d\u6b21 \u603b\u65f6\u95f4:%.3fs\\n', N, N /Fs);\nfprintf('\u6700\u7ec8\u8bef\u5dee(m): %.3f %.3f %.3f\\n', h_pos(end, 1),  h_pos(end, 2),  h_pos(end, 3));\n\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/ins_test/example_ins1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875225, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5995414444405663}}
{"text": "function d = Mtv(solver,I,i)\n% forward operator\n%\n% Input\n%  I - intensities\n%  alpha - scaling factors\n%\n% Output\n%  d - result\n%\n  \n% extend specimen symmetry\nlss = numProper(solver.SS);\nI_ext = repmat(I.',lss,1)./lss;\n\n% compute Fourier coefficients\nnfsftmex('set_f', solver.nfft_r(i), I_ext);\nnfsftmex('adjoint', solver.nfft_r(i));\nfhat = nfsftmex('get_f_hat_linear', solver.nfft_r(i));\n\n% convolution with kernel function\nfhat = 4*pi*fhat .* solver.A;\n\n% evaluate Fourier series at pole figure points g h_i\nnfsftmex('set_f_hat_linear', solver.nfft_gh(i), fhat);\nnfsftmex('trafo', solver.nfft_gh(i));\nd = real(nfsftmex('get_f', solver.nfft_gh(i)));\nd = reshape(d,length(solver.c),[]) * solver.refl{i}.';\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/PoleFigureAnalysis/@MLSSolver/Mtv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5994848673582418}}
{"text": "  function proj = ellipsoid_proj(cg, params, varargin)\n%|function proj = ellipsoid_proj(cg, params, varargin)\n%|\n%| Compute set of 2d line-integral projection views of ellipsoid(s).\n%| Works for both parallel-beam and cone-beam geometry.\n%|\n%| in\n%|\tcg\t\t\tct_geom()\n%|\tparams [ne 9]\t\tellipsoid parameters:\n%|\t\t\t[x_center y_center z_center  x_radius y_radius z_radius\n%|\t\t\t\txy_angle_degrees z_angle_degrees  amplitude]\n%| options\n%|\toversample\t\tover-sampling factor for emulating \"strips\"\n%|\t\t\t\t(to account for finite detector size)\n%|\n%| out\n%|\tproj\t[ns nt na]\tprojection views\n%|\n%| Copyright 2003-10-22, Patty Laskowsky, Nicole Caparanis, Taka Masuda,\n%| and Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(cg, 'test'), ellipsoid_proj_test, return, end\nif nargin < 2, ir_usage, end\n\narg.oversample = 1;\narg = vararg_pair(arg, varargin);\n\nproj = ellipsoid_proj_do(params, cg.s, cg.t, cg.ar, cg.source_zs, ...\n\t\tcg.dso, cg.dod, cg.dfs, arg.oversample);\n\nend % ellipsoid_proj()\n\n\n% ellipsoid_proj_do()\nfunction proj = ellipsoid_proj_do(params, ss, tt, ...\n\t\tbeta, ... % [radians]\n\t\tsource_zs, dso, dod, dfs, oversample)\n\nif size(params, 2) ~= 9, error '9 parameters per ellipsoid', end\n\nif oversample > 1\n\tds = ss(2) - ss(1);\n\tdt = tt(2) - tt(1);\n\tif any(abs(diff(ss) / ds - 1) > 1e-6) ...\n\t|| any(abs(diff(tt) / dt - 1) > 1e-6)\n\t\terror 'uniform spacing required for oversampling'\n\tend\n\tNo = oversample;\n\t% determine new finer sampling positions\n\tss = outer_sum([-(No-1):2:(No-1)]'/(2*No)*ds, ss(:)'); % [No ns]\n\ttt = outer_sum([-(No-1):2:(No-1)]'/(2*No)*dt, tt(:)'); % [No nt]\n\tproj = ellipsoid_proj_do(params, ss(:), tt(:), beta, source_zs, dso, dod, dfs, 1);\n\tproj = downsample3(proj, [No No 1]);\nreturn\nend\n\n\n% determine equivalent parallel-beam projection coordinates, at beta=0\nns = length(ss);\nnt = length(tt);\n[sss ttt] = ndgrid(ss, tt);\n\nif isinf(dso) % parallel beam\n\tuu = sss;\n\tvv = ttt;\n\tazim0 = 0;\n\tpolar = 0;\n\nelseif isinf(dfs) % cone-beam with flat detector\n\t[uu vv azim0 polar] = ir_coord_cb_flat_to_par(sss, ttt, dso, dod);\n\nelseif dfs == 0 % cone-beam with arc detector\n\t[uu vv azim0 polar] = ir_coord_cb_arc_to_par(sss, ttt, dso, dod);\n\nelse\n\tfail 'not done'\nend\n\nclear sss ttt\n\ncpolar = cos(polar);\nspolar = sin(polar);\nproj = zeros(ns, nt, numel(beta));\n\n% loop over ellipsoids\nfor ip = 1:size(params,1)\n\tpar = params(ip,:);\n\n\tcx = par(1);\trx = par(4);\n\tcy = par(2);\try = par(5);\n\tcz = par(3);\trz = par(6);\n\txang = deg2rad(par(7)); % xy-plane rotation\n\tzang = deg2rad(par(8)); % z-plane rotation\n\tif zang, error 'z rotation not done', end\n\tval = par(9);\n\n\tfor ib = 1:length(beta)\n%\t\taz = beta(ib) + azim0 - xang; % assume source rotate in xy plane\n\t\taz = beta(ib) + azim0; % correction due to Lei Zhu of Stanford\n\n\t\t% shift property of 3D transform:\n\t\tcz_eff = cz - source_zs(ib); % center relative to source\n\t\tushift = cx * cos(az) + cy * sin(az);\n\t\tvshift = (cx * sin(az) - cy * cos(az)) .* spolar + cz_eff * cpolar;\n\n\t\taz = az - xang; % correction due to Lei Zhu of Stanford\n\t\tp1 = (uu-ushift) .* cos(az) + (vv-vshift) .* sin(az) .* spolar;\n\t\tp2 = (uu-ushift) .* sin(az) - (vv-vshift) .* cos(az) .* spolar;\n\t\tp3 = (vv-vshift) .* cpolar;\n\n\t\te1 = -sin(az) .* cpolar;\n\t\te2 = cos(az) .* cpolar;\n\t\te3 = spolar;\n\n\t\tA = e1.^2 / rx^2 + e2.^2 / ry^2 + e3.^2 / rz^2;\n\t\tB = p1 .* e1 / rx^2 + p2 .* e2 / ry^2 + p3 .* e3 / rz^2;\n\t\tC = p1.^2 / rx^2 + p2.^2 / ry^2 + p3.^2 / rz^2 - 1;\n\n\t\tproj(:,:,ib) = proj(:,:,ib) + 2 * val * sqrt(B.^2 - A.*C) ./ A;\n\tend\nend\n\n% trick: anywhere proj of a single ellipsoid is imaginary, the real part is 0.\nproj = real(proj);\nend % ellipsoid_proj_do()\n\n\n% ellipsoid_proj_test()\nfunction ellipsoid_proj_test\n\nell = [20 0*50 -40 200 100 50 90 0 10;\n        0 50 100 80 80 20 0 0 10];\n\nfun_proj = @(cg) ellipsoid_proj(cg, ell, 'oversample', 2); % analytical\nfun_im = @(ig) ellipsoid_im(ig, ell, 'oversample', 2, 'checkfov', true);\n\nir_proj3_compare1(fun_proj, fun_im, 'chat', 1);\n\nend % ellipsoid_proj_test()\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/fbp/ellipsoid_proj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5993900615853215}}
{"text": "% Test file for bndfun/poly.m\n\nfunction pass = test_poly(pref)\n\n% Get preferences.\nif ( nargin < 1 )\n    pref = chebfunpref();\nend\n\n% Set the domain\ndom = [-2 7];\n\n%%\n% Check a few simple examples.\n\nf = bndfun(@(x) zeros(size(x)), struct('domain', dom), pref);\np = poly(f);\npass(1) = (norm(p, inf) <= get(f, 'vscale')*eps);\n\nf = bndfun(@(x) 3*ones(size(x)), struct('domain', dom), pref);\np = poly(f);\npass(2) = (norm(p - 3, inf) < get(f, 'vscale')*eps);\n\nf = bndfun(@(x) 6.4*x - 3i, struct('domain', dom), pref);\np = poly(f);\npass(3) = (norm(p - [6.4 (-3i)], inf) < get(f, 'vscale')*eps);\n\nf = bndfun(@(x) 2i*x.^5 - 3.2*x.^4 + 2*x.^2 - (1.2 + 3i), ...\n    struct('domain', dom), pref);\np = poly(f);\npass(4) = (norm(p - [2i (-3.2) 0 2 0 -(1.2 + 3i)], inf) ...\n    < get(f, 'vscale')*eps);\n\n%%\n% Verify operation for array-valued bndfun objects.\n\nf = bndfun(@(x) [3*ones(size(x)), (6.4*x - 3i), (4*x.^2 - 2i*x + 3.7)], ...\n    struct('domain', dom), pref);\np = poly(f);\np_exact = [0 0     3;\n           0 6.4   (-3i);\n           4 (-2i) 3.7];\npass(5) = (norm(p(:) - p_exact(:), inf) < ...\n    max(get(f, 'vscale')*eps));\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/bndfun/test_poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5993900600419815}}
{"text": "function [RET, REL, RETREL, ndx] = LMprecisionRecall(retrievedBoundingBox, annotation, objectname, mindetectablesize)\n% This function returns one point in the precision-recall curve.\n% Provided a set of detected bounding boxes, it indicates how may objects\n% have been detected (RETREL).\n%\n% The standard measures for IR are recall and precision. Assuming that:\n%\n%    * RET is the set of all items the system has retrieved for a specific inquiry;\n%    * REL is the set of relevant items for a specific inquiry;\n%    * RETREL is the set of the retrieved relevant items \n%\n% then precision and recall measures are obtained as follows:\n%\n%    precision = RETREL / RET\n%    recall = RETREL / REL \n\n\n% Search the target object in the annotation\nj = LMobjectindex(annotation, objectname);\n\n% Do not consider deleted objects:\nj = j(find(strcmp({annotation.object(j).deleted}, '0')));\n\nNinstances = length(j);\n\n% Extract the bounding boxes for each target present in the image\nBoundingBox = []; REL = 0;\nfor i = 1:Ninstances\n    [X,Y] = getLMpolygon(annotation.object(j(i)).polygon);\n    BoundingBox = [BoundingBox; min(X) max(X) min(Y) max(Y)];\n   \n    % If we detect an object that we thought was too small, we should not\n    % penalize performance for this. So, we will consider that the only\n    % relevant targets are the ones with a size larger than the minimal\n    % detectable size. \n    if max(Y)-min(Y)>mindetectablesize(1) & max(X)-min(X)>mindetectablesize(2) & max(Y)>0 & max(X)>0\n        REL = REL + 1;\n    end\nend\n\nRET = size(retrievedBoundingBox, 1);\n\nif REL == 0 \n    RETREL = 0;\n    return\nend\n\ncxO = mean(BoundingBox(:,1:2),2);\ncyO = mean(BoundingBox(:,3:4),2);\nDxO = diff(BoundingBox(:,1:2),1,2);\nDyO = diff(BoundingBox(:,3:4),1,2);\n\ncxR = mean(retrievedBoundingBox(:,1:2),2);\ncyR = mean(retrievedBoundingBox(:,3:4),2);\nDxR = diff(retrievedBoundingBox(:,1:2),1,2);\nDyR = diff(retrievedBoundingBox(:,3:4),1,2);\n\nndx = [];\nfor i = 1:RET\n    d = sqrt(((cxR(i) - cxO)./DxO).^2 + ((cyR(i) - cyO)./DyO).^2)<.5 ...\n        & max(DxO/DxR(i), DxR(i)./DxO)<1.5 ...\n        & max(DyO/DyR(i), DyR(i)./DyO)<1.5;\n    n = find(d);\n    if length(n)>0\n        ndx(i) = n(1);\n    else\n        ndx(i) = 0;\n    end\nend\nRETREL = sum(unique(ndx)>0); % each object can be detected only once\n\n% If we detect an object that we thought was too small, we should not\n% penalize performance for this. So, if we detected one object that was not\n% considered before within the relevan set, then we will move it into the\n% relevant set:\nREL = max(REL, RETREL);\n\n\n\n", "meta": {"author": "CSAILVision", "repo": "LabelMeToolbox", "sha": "b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2", "save_path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox", "path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox/LabelMeToolbox-b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2/objectdetection/LMprecisionRecall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5993900584115723}}
{"text": "%% rigidTransformationMatrixDirect\n% Below is a demonstration of the features of the |rigidTransformationMatrixDirect| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[M]=rigidTransformationMatrixDirect(V1,V2);|\n\n%% Description\n% This function computes the rigid transformation matrix (translation, and\n% rotation). For the two point matches input sets V1 and V2. \n\n%% Examples\n\n%%\n% Plot settings\nfontSize=15;\nfaceAlpha=1;\nedgeColor='k';\n\n%% Example: \n\n%% Determine the rigid transformation to overlay two surfaces\n% Below is a demonstration of the features of the |rigidTransformationMatrixDirect| function\n \n% Load example patch data\n[F,Vd]=parasaurolophus;\n \n%Translation\nOR=[-1 2 -3]; %Translations\nT  = [1 0 0 OR(1);...\n      0 1 0 OR(2);...\n      0 0 1 OR(3);...\n      0 0 0 1]; \n%Rotation\na=[-0.25*pi 0.75*pi 0.1*pi]; %Euler angles\nR  = eye(4,4); R(1:3,1:3)=euler2DCM(a);\n\n%Scaling  \nv=[2 3 1]; %Scaling factors\nS  = [v(1) 0    0    0;...\n      0    v(2) 0    0;...\n      0    0    v(3) 0;...\n      0    0    0    1];\n  \nM_true  = T * R; %The true transformation matrix\n\n%Point set 1\nV1=Vd+0.5;\n\n%Point set 2 \nV2=tform(M_true,V1);\n\n%%\n% Plotting input data\n\nhf=cFigure;\ntitle('The untransformed surfaces','FontSize',fontSize);\nxlabel('X','FontSize',fontSize); ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize);\n\nhp=patch('Faces',F,'Vertices',V1,'FaceColor','g','FaceAlpha',faceAlpha);\n\nhp=patch('Faces',F,'Vertices',V2,'FaceColor','r','FaceAlpha',faceAlpha,'edgeColor',edgeColor);\n\ncamlight headlight;\nset(gca,'FontSize',fontSize);\nview(3); axis tight;  axis equal; box on; \ndrawnow; \n\n%% \n% Get the transformation matrix for the point matched data using |rigidTransformationMatrixDirect|\n\n[M_fit]=rigidTransformationMatrixDirect(V1,V2);\n\nV1f=tform((M_fit),V1);\n\n%%\n% Plotting results\n\nhf=cFigure;\ntitle('The green surfaces transformed towards the red','FontSize',fontSize);\nxlabel('X','FontSize',fontSize); ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize);\n\nhp=patch('Faces',F,'Vertices',V2,'FaceColor','r','FaceAlpha',0.5,'edgeColor',edgeColor);\n\nhp=patch('Faces',F,'Vertices',V1f,'FaceColor','none','FaceAlpha',0.5,'edgeColor','g');\n% hp=patch('Faces',F,'Vertices',V2ff,'FaceColor','none','FaceAlpha',0.5*2,'edgeColor','b');\n\nset(gca,'FontSize',fontSize);\nview(3); axis tight;  axis equal; box on; \ndrawnow; \n\n%% \n%\n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_rigidTransformationMatrixDirect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.5993900407382771}}
{"text": "function sump=sum(p,dim)\n% sympoly/sum: sum a sympoly array along a given dimension\n% usage: sump=sum(p);\n% usage: sump=sum(p,dim);\n% \n% arguments:\n%    p - sympoly array object\n%  dim - (OPTIONAL) dimension to sum over\n%        DEFAULT ==1, unless sp is a row vector\n%\n%  sump - sympoly object containing the sum reduced array\n\ns = size(p);\nnp = length(s);\n\n% default for dim is 1, UNLESS p is a row vector.\nif (nargin<2) || isempty(dim)\n  if (s(1) == 1) && (np==2)\n    % a row vector\n    dim = 2;\n  else\n    % any other shape array\n    dim = 1;\n  end\nend\n\n% for dim == 1 or dim == 2, do the sum using a dot product\nif (dim == 1) && (np == 2)\n  % sum down rows\n  sump = ones(1,s(1))*p;\n  \nelseif (dim == 2) && (np == 2)\n  % sum across columns\n  sump = p*ones(s(2),1);\n\nelse\n  % its an n-d array\n  ss = s;\n  ss(dim) = 1;\n  \n  si = cell(1,np);\n  for i = 1:np\n    si{i} = 1:s(i);\n  end\n  \n  if any(ss~=1)\n    sump = repmat(sympoly(0),ss);\n  else\n    sump = sympoly(0);\n  end\n  for i = 1:s(dim)\n    si{dim} = i;\n    sump = sump + p(si{:});\n  end\n\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/9577-symbolic-polynomial-manipulation/SymbolicPolynomials/@sympoly/sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.599390040738277}}
{"text": "function [w, infos] = cd_lasso_elasticnet(problem, options)\n% Coordinate descent algorithm for LASSO problem.\n%\n% Inputs:\n%       problem     function (cost/grad/hess)\n%       options     options\n% Output:\n%       w           solution of w\n%       infos       information\n%\n% This file is part of GDLibrary and SGDLibrary.\n%\n% Created by H.Kasai on Apr. 18, 2017\n\n\n    % set dimensions and samples\n    d = problem.dim();\n    n = problem.samples();  \n    A = problem.A();\n\n    % extract options\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, 'tol_gnorm')\n        tol_gnorm = 1.0e-12;\n    else\n        tol_gnorm = options.tol_gnorm;\n    end    \n    \n    if ~isfield(options, 'max_iter')\n        max_iter = 100;\n    else\n        max_iter = options.max_iter;\n    end \n    \n    if ~isfield(options, 'verbose')\n        verbose = false;\n    else\n        verbose = options.verbose;\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        f_opt = -Inf;\n    else\n        f_opt = options.f_opt;\n    end    \n    \n    if ~isfield(options, 'store_w')\n        store_w = false;\n    else\n        store_w = options.store_w;\n    end \n    \n    if ~isfield(options, 'sub_mode')\n        sub_mode = 'lasso';\n    else\n        sub_mode = options.sub_mode;\n    end     \n    \n    % initialise\n    iter = 0;\n    if strcmp(sub_mode, 'lasso')\n        AtA = problem.AtA();\n        squred_norm_col = diag(AtA);\n    else\n        AtA_l2 = problem.AtA_l2();\n        squred_norm_col = diag(AtA_l2);\n    end\n    prox_th = ones(d, 1)./squred_norm_col;\n    \n    % store first infos\n    clear infos;\n    infos.iter = iter;\n    infos.time = 0;    \n    infos.grad_calc_count = 0;    \n    f_val = problem.cost(w);\n    infos.cost = f_val;     \n    optgap = f_val - f_opt;\n    infos.optgap = optgap;\n    grad = problem.full_grad(w);\n    gnorm = norm(grad);\n    infos.gnorm = gnorm;\n    if ismethod(problem, 'reg')\n        infos.reg = problem.reg(w);   \n    end    \n    if store_w\n        infos.w = w;       \n    end\n    \n    % set start time\n    start_time = tic();  \n    \n    % print info\n    if verbose\n        fprintf('CD (%s): Iter = %03d, cost = %.24e, gnorm = %.4e, optgap = %.4e\\n', sub_mode, iter, f_val, gnorm, optgap);\n    end      \n\n    % main loop\n    while (optgap > tol_optgap) && (gnorm > tol_gnorm) && (iter < max_iter)        \n\n        % update i-th coordinate\n        if strcmp(sub_mode, 'lasso')\n            for i = 1:d \n                w_except_i = w;\n                w_except_i(i) = 0;\n                residual = problem.residual(w_except_i);\n\n                snc = squred_norm_col(i);\n                w(i) = problem.prox(A(:, i)'*residual/snc, prox_th(i));\n            end\n        else\n            for i = 1:d \n                w_except_i = w;\n                w_except_i(i) = 0;\n                residual = problem.residual(w_except_i, i);\n\n                snc = squred_norm_col(i);\n                w(i) = problem.prox(residual/snc, prox_th(i));\n            end            \n            \n        end\n        \n        % calculate gradient\n        grad = problem.full_grad(w);\n\n        % update iter        \n        iter = iter + 1;\n        % calculate error\n        f_val = problem.cost(w);\n        optgap = f_val - f_opt;  \n        % calculate norm of gradient\n        gnorm = norm(grad);\n        \n        % measure elapsed time\n        elapsed_time = toc(start_time);        \n\n        % store infoa\n        infos.iter = [infos.iter iter];\n        infos.time = [infos.time elapsed_time];        \n        infos.grad_calc_count = [infos.grad_calc_count iter*n];      \n        infos.optgap = [infos.optgap optgap];        \n        infos.cost = [infos.cost f_val];\n        infos.gnorm = [infos.gnorm gnorm]; \n        if ismethod(problem, 'reg')\n            reg = problem.reg(w);\n            infos.reg = [infos.reg reg];\n        end        \n        if store_w\n            infos.w = [infos.w w];         \n        end        \n       \n        % print info\n        if verbose\n            fprintf('CD (%s): Iter = %03d, cost = %.24e, gnorm = %.4e, optgap = %.4e\\n', sub_mode, iter, f_val, gnorm, optgap);\n        end        \n    end\n    \n    if gnorm < tol_gnorm\n        fprintf('Gradient norm tolerance reached: tol_gnorm = %g\\n', tol_gnorm);\n    elseif optgap < tol_optgap\n        fprintf('Optimality gap tolerance reached: tol_optgap = %g\\n', tol_optgap);        \n    elseif iter == max_iter\n        fprintf('Max iter reached: max_iter = %g\\n', max_iter);\n    end    \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/gd_solver/cd_lasso_elasticnet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5993900343037084}}
{"text": "%UMFPACK_SIMPLE a simple demo\n%\n% Example:\n%   umfpack_simple\n%\n% Copyright 1995-2007 by Timothy A. Davis.\n%\n% UMFPACK License:\n%\n%     Your use or distribution of UMFPACK or any modified version of\n%     UMFPACK implies that you agree to this License.  UMFPACK is\n%     is free software; you can redistribute it and/or\n%     modify it under the terms of the GNU General Public\n%     License as published by the Free Software Foundation; either\n%     version 2 of the License, or (at your option) any later version.\n\n% Availability: http://www.cise.ufl.edu/research/sparse/umfpack\n%\n% See also: umfpack, umfpack2, umfpack_details\n\nhelp umfpack_simple\n\nformat short\n\nA = [\n 2  3  0  0  0\n 3  0  4  0  6\n 0 -1 -3  2  0\n 0  0  1  0  0\n 0  4  2  0  1\n] ;\nfprintf ('A = \\n') ; disp (A) ;\n\nA = sparse (A) ;\n\nb = [8 45 -3 3 19]' ;\nfprintf ('b = \\n') ; disp (b) ;\n\nfprintf ('Solution to Ax=b via UMFPACK:\\n') ;\nfprintf ('x1 = umfpack2 (A, ''\\\\'', b)\\n') ;\n\nx1 = umfpack2 (A, '\\', b) ;\nfprintf ('x1 = \\n') ; disp (x1) ;\n\nfprintf ('Solution to Ax=b via MATLAB:\\n') ;\nfprintf ('x2 = A\\\\b\\n') ;\n\nx2 = A\\b ;\nfprintf ('x2 = \\n') ; disp (x2) ;\n\nfprintf ('norm (x1-x2) should be small: %g\\n', norm (x1-x2)) ;\n\nfprintf ('Type ''umfpack_demo'' for a full demo of UMFPACK\\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/UMFPACK/MATLAB/umfpack_simple.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.5993403867809531}}
{"text": "% Chapter 14 - Poincare Maps and Nonautonomous Systems in the Plane.\n% Programs 14a - Solving an initial value problem.\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% Solve a differential equation (Example 1).\nr=dsolve('Dr=-r^2','r(0)=1');\n\n% List the first eight returns on the segment {y=0, 0<x<1}.\n% There may be small inaccuracies due to the numerical solution.\ndeq=inline('[-(r(1))^2]','t','r');\noptions=odeset('RelTol',1e-6,'AbsTol',1e-6);\n[t,returns]=ode45(deq,0:2*pi:16*pi,1);\nreturns\n\n% End of Programs 14a.", "meta": {"author": "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_14a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.5993403706547301}}
{"text": "function [csubl, csubd] = aerodyn(alpha)\n\n% aerodynamic properties\n\n% input\n\n%  alpha = angle-of-attack (radians)\n\n% output\n\n%  csubl = lift coefficient (non-dimensional)\n%  csubd = drag coefficient (non-dimensional)\n\n% STS aero - J. Betts model\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nrtd = 180.0 / pi;\n\ncl0 = -0.20704d0;\n\ncl1 = 0.029244d0;\n\ncd0 = 0.07854d0;\n\ncd1 = -6.1592d-3;\n\ncd2 = 6.21408d-4;\n\nalphad = rtd * alpha;\n\ncsubl = cl0 + cl1 * alphad;\n\ncsubd = cd0 + (cd1 + cd2 * alphad) * alphad;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39095-trajectory-modeling-in-the-flight-path-system/aerodyn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5993262203849536}}
{"text": "%\n% Bayesian Optimization of Combinatorial Structures\n%\n% Copyright (C) 2018 R. Baptista & M. Poloczek\n%\n% BOCS 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% BOCS 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 BOCS.  If not, see <http://www.gnu.org/licenses/>.\n%\n% Copyright (C) 2018 MIT & University of Arizona\n% Authors: Ricardo Baptista & Matthias Poloczek\n% E-mails: rsb@mit.edu & poloczek@email.arizona.edu\n%\n\nclear; close all; clc\naddpath(genpath('../algorithms'))\naddpath(genpath('../stat_model'))\naddpath(genpath('../test_problems/IsingModel'))\naddpath(genpath('../tools'))\n\n% Save inputs in struct\ninputs = struct;\ninputs.n_vars     = 12;\ninputs.evalBudget = 100;\ninputs.n_init     = 20;\ninputs.lambda     = 1e-4;\ninputs.estimator  = 'horseshoe';\n\n% Generate random 3x3 graphical model\nTheta   = rand_ising_grid(9);\nMoments = ising_model_moments(Theta);\n\n% Save objective function and regularization term\ninputs.model    = @(x) KL_divergence_ising(Theta, Moments, x);\ninputs.penalty  = @(x) inputs.lambda*sum(x,2);\n\n% Generate initial samples for statistical models\ninputs.x_vals   = sample_models(inputs.n_init, inputs.n_vars);\ninputs.y_vals   = inputs.model(inputs.x_vals);\n\n% Run BOCS-SDP and BOCS-SA (order 2)\nB_SA  = BOCS(inputs.model, inputs.penalty, inputs, 2, 'SA');\nB_SDP = BOCS(inputs.model, inputs.penalty, inputs, 2, 'sdp');\n\n% Plot results\nfigure\nhold on\nplot(1:length(B_SA.objVals),  cummin(B_SA.objVals), '-r');\nplot(1:length(B_SDP.objVals), cummin(B_SDP.objVals), '-.b');\nset(gca,'YScale','log')\nxlabel('$t$','interpreter','latex')\nylabel('Best $f(x)$','interpreter','latex')\nlegend({'BOCS - SA','BOCS - SDP'},'location','northeast')\nhold off\n", "meta": {"author": "baptistar", "repo": "BOCS", "sha": "fef0d4e34e376e8bb0dae9955d70c2155530b9eb", "save_path": "github-repos/MATLAB/baptistar-BOCS", "path": "github-repos/MATLAB/baptistar-BOCS/BOCS-fef0d4e34e376e8bb0dae9955d70c2155530b9eb/scripts/example_ising.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5993262119849828}}
{"text": "function [F] = mci_ramsay_fx (x,U,P,M)\n% State equation for Ramsay model\n% FORMAT [F] = mci_ramsay_fx (x,U,P,M)\n%\n% x     State vector\n%       x(1) Voltage variable\n%       x(2) Recovery variable\n% U     inputs\n% P     vector of model parameters - 2 params only\n% M     model\n%\n% F     dx/dt\n%\n% J Ramsay et al (2007) Parameter estimation for differential equations:\n% a generalised smoothing approach. J Roy Stat Soc B, 69(5):741-796.\n%\n% See also section 10 (page 26) and contribution by W.Penny on page 75 of: \n%\n% Girolami and Calderhead (2011) Riemann manifold Langevin and Hamiltonian\n% Monte Carlo methods. J Roy Stat Soc B,73(2):123-214.\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: mci_ramsay_fx.m 6548 2015-09-11 12:39:47Z will $\n\nc=3;\n\nP(1)=exp(P(1));\nP(2)=exp(P(2));\n\nF=zeros(2,1);\nF(1)=c*(x(1)-(1/3)*x(1)^3+x(2));\nF(2)=-(1/c)*(x(1)-P(1)+P(2)*x(2));\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/mci/models/ramsay/mci_ramsay_fx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5993262104546787}}
{"text": "function [mxc,mlat,OUT] = xc_stats(xc,xl,varargin)\n% [mxc,mlat,OUT] = xc_stats(xc,xl,varargin)\n% calculate t-statistic values for a k x k x n 3-D matrix of \n% correlation (xc) and latency (xl) values across n subjects.\n%\n% tor wager\n\n\nnames = [];\nif length(varargin) > 0, names = varargin{1};,end\n\n if isempty(xl), mlat = [];, end\n\n% ------------------------------------------------------------\n% stats on correlation values\n% ------------------------------------------------------------\n\nwarning off, clear stelatency, clear tlat, clear stecorr, clear tcorr\n% standard errors and t-values, element by element\n\n% only do this on the upper triangle, to be faster\n\nfor j = 1:size(xc,2)-1\n    for k = j + 1 : size(xc,2)\n        \n        if ~isempty(xl)\n            tmp = squeeze(xl(j,k,:));\n            z = tmp;     \n            [stelatency(j,k),tlat(j,k)] = ste(z);   % t-test on latencies; maybe should be poisson dist?\n        end\n        \n        tmp = squeeze(xc(j,k,:));\n        z = .5 * log( (1+tmp) ./ (1-tmp) );     % Fisher's r-to-z transform\n        [stecorr(j,k),tcorr(j,k)] = ste(z);     % correl in rand fx analysis across ss\n    end\nend\nwarning on\n\n\n% makes symmetric matrices from upper tri\n\nif ~isempty(xl), stelatency(end+1,:) = 0; ,end\nstecorr(end+1,:) = 0;\ntcorr(end+1,:) = 0; \nif ~isempty(xl), \n    tlat(end+1,:) = 0; \n    stelatency = stelatency + stelatency';\nend\n\nstecorr = stecorr + stecorr' + Inf * eye(size(stecorr,1));\ntcorr = tcorr + tcorr';     % t-scores for significance/reliability of cross-correlations across subjects\n\nif ~isempty(xl)\n    tlat = tlat + tlat';        % same for time lags across subjects\nend\n\n% group means\n\nif ~isempty(xl)\n    mlat = mean(xl,3);          % mean of latency data (cross-lag, group average)\nend\nmxc = mean(xc,3);           % mean cross-correlations among k regions, group average\n\n\n% ------------------------------------------------------------\n% print and save output\n% ------------------------------------------------------------\n\n\nOUT.desc1 = 'xl is latency mtx for each subject, xc is individual correlation mtx';\nif ~isempty(xl), OUT.xl = xl;, end\nOUT.xc = xc;\nOUT.desc2 = 'mlat and mxc: matrices of means across subjects for latency and correl'\nOUT.desc3 = 'tlat/tcorr are t-values across z-transformed correlations';\nOUT.mxc = mxc;\n\nif ~isempty(xl)\n    OUT.mlat = mlat;\n    OUT.tlat = tlat;\n    OUT.tcorr = tcorr;\nend\n\n% Output\nif ~isempty(xl)\n    fprintf(1,'Latency\\n');\n    str = correlation_to_text(mlat,Inf,names);\nend\n\nfprintf(1,'correlation T-values, p<.05 corrected, assuming normal distribution of latency diffs\\n');\n% Alpha correction - bonferroni.\nnumobs=(size(mxc,1)*(size(mxc,1)-1))/2;\ncorrp=1-(0.05/ (2 * (   numobs   )));       % 2-tailed corr p\ncrit_t = tinv_t(corrp,size(xc,1)-3);          % critical t-value for corrected significance\ncrit_tu = tinv_t(1-(.05/2),size(xc,1)-3);         % critical t-value for uncorrected significance\n\nif ~isempty(xl)\n    str = correlation_to_text(tlat,crit_t,names);\nend\n\nOUT.crit_t = crit_t;\nOUT.crit_tu = crit_tu;\nOUT.crit_tdesc = 'crit_t crit t value corrected, _tu uncorrected';\nOUT.corrp = corrp;\nOUT.corrpdesc = 'critical corrected p-value (bonferroni)';\n\n\nfprintf(1,'Average correlation across subjects\\n');\n[str, sigu] = correlation_to_text(mxc,Inf,names);\n\nfprintf(1,'Corr T-values, p<.05 uncorrected, 2-tailed, assuming independent samples over time\\n');\n[str, sigu] = correlation_to_text(tcorr,crit_tu,names);\nOUT.sigmat_uncorrected = sigu;\n\nfprintf(1,'Corr T-values, p<.05 corrected, 2-tailed, assuming independent samples over time\\n');\n[str, sigmat] = correlation_to_text(tcorr,crit_t,names);\n\nOUT.sigmat = sigmat;\n\n\n\n\nreturn", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/Support_functions/xc_stats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5993262083546861}}
{"text": "function t=getDCTTransform(im,N)\ns=dctmtx(N);\nt=s*im*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/41333-simulation-of-dct-walsh-hadamard-haar-and-slant-transform-using-variable-block-sizes/getDCTTransform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897442783526, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5993120447195888}}
{"text": "function gIX = KmeansSubdivide(numK2,gIX,M_0)\ngIX_old = gIX;\nU = unique(gIX);\n        for i = 1:length(U),\n            IX = find(gIX_old == U(i));\n            M_sub = M_0(IX,:);\n            \n            if numK2<length(IX),\n                [gIX_sub,C] = kmeans(M_sub,numK2,'distance','correlation');\n            else\n                [gIX_sub,C] = kmeans(M_sub,length(IX),'distance','correlation');\n            end\n            gIX(IX) = (i-1)*numK2+gIX_sub;\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/script functions/KmeansSubdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5992905353910775}}
{"text": "function dx = lorenz(t,x,Beta)\ndx = [\nBeta(1)*(x(2)-x(1));\nx(1)*(Beta(2)-x(3))-x(2);\nx(1)*x(2)-Beta(3)*x(3);\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/CH07/lorenz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5992905250873236}}
{"text": "function grad = compute_NN_grad(W, X, resp, hout, nonlinearity, nonzero_grad)\n\n% nonlinearity = 1 -- hyperbolic tangent\n% nonlinearity = 2 -- logistic sigmoid (subtract 0.5 from last layer's outputs)\n% nonlinearity = 3 -- logistic sigmoid + hyperbolic tangent (last layer)\n\nncases = size(resp{1},2);\nif isa(X, 'gsingle')\n  gputype = 'gsingle';\n  onesncases = gones(ncases,1,gputype);\nelseif isa(X, 'gdouble')\n  gputype = 'gsingle';\n  onesncases = gones(ncases,1,gputype);\nelse\n  onesncases = ones(ncases,1);\nend\n\nnlayer = numel(W);\n\nif (nonlinearity == 1)\n  \n  if (exist('nonzero_grad', 'var'))\n    snonzero_grad = sum(nonzero_grad);\n    if (snonzero_grad == 0)\n      for i=nlayer:-1:1\n\tgrad{i} = zeros(size(W{i}));\n      end\n      return;\n    end\n    \n    for i=nlayer:-1:1\n      if (i == nlayer)\n\ttmp = hout(:, nonzero_grad);\n      else\n\ttmp = (W{i+1}' * backward{i+1});\n      end\n      \n      if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n      end\n    \n      backward{i} = tmp .* (1 - resp{i}(:,nonzero_grad).^2);\n    \n      if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t  grad{i} = backward{i} * [resp{i-1}(:,nonzero_grad)' ones(snonzero_grad, 1)];\n\telse\n\t  grad{i} = backward{i} * resp{i-1}(:,nonzero_grad)';\n\tend    \n      else\n\tgrad{i} = backward{i} * X(:, nonzero_grad)';\n      end\n    end\n  else\n    for i=nlayer:-1:1\n      if (i == nlayer)\n\ttmp = hout;\n      else\n\ttmp = (W{i+1}' * backward{i+1});\n      end\n      \n      if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n      end\n      \n      backward{i} = tmp .* (1 - resp{i}.^2);\n      \n      if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t  grad{i} = backward{i} * [resp{i-1}' onesncases];\n\telse\n\t  grad{i} = backward{i} * resp{i-1}';\n\tend\n      else\n\tgrad{i} = backward{i} * X';\n      end\n    end\n  end\n  \nelseif (nonlinearity == 2)\n\n  if (exist('nonzero_grad', 'var'))\n    snonzero_grad = sum(nonzero_grad);\n    if (snonzero_grad == 0)\n      for i=nlayer:-1:1\n\tgrad{i} = zeros(size(W{i}));\n      end\n      return;\n    end\n    \n    for i=nlayer:-1:1\n      if (i == nlayer)\n\ttmp = hout(:, nonzero_grad);\n      else\n\ttmp = (W{i+1}' * backward{i+1});\n      end\n      \n      if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n      end\n      \n      backward{i} = tmp .* (1 - resp{i}(:,nonzero_grad)) .* resp{i}(:,nonzero_grad);\n      \n      if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t  grad{i} = backward{i} * [resp{i-1}(:,nonzero_grad)' gones(snonzero_grad,1,gputype)];\n\telse\n\t  grad{i} = backward{i} * resp{i-1}(:,nonzero_grad)';\n\tend\n      else\n\tgrad{i} = backward{i} * X(:, nonzero_grad)';\n      end\n    end\n  else\n    for i=nlayer:-1:1\n      if (i == nlayer)\n\ttmp = hout;\n      else\n\ttmp = (W{i+1}' * backward{i+1});\n      end\n      \n      if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n      end\n      \n      backward{i} = tmp .* (1 - resp{i}) .* resp{i};\n      \n      if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t  grad{i} = backward{i} * [resp{i-1}' onesncases];\n\telse\n\t  grad{i} = backward{i} * resp{i-1}';\n\tend\n      else\n\tgrad{i} = backward{i} * X';\n      end\n    end\n  end\n  \nelseif (nonlinearity == 3)\n  \n  if (exist('nonzero_grad', 'var'))\n    snonzero_grad = sum(nonzero_grad);\n    if (snonzero_grad == 0)\n      for i=nlayer:-1:1\n\tgrad{i} = zeros(size(W{i}));\n      end\n      return;\n    end\n  \n    for i=nlayer:-1:1\n      if (i == nlayer)\n\ttmp = hout(:, nonzero_grad);\n      else\n\ttmp = (W{i+1}' * backward{i+1});\n      end\n    \n      if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n      end\n      \n      if (i == nlayer)\n\tbackward{i} = tmp .* (1 - resp{i}(:,nonzero_grad)^2);\n      else\n\tbackward{i} = tmp .* (1 - resp{i}(:,nonzero_grad)) .* resp{i}(:,nonzero_grad);\n      end\n      \n      if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t  grad{i} = backward{i} * [resp{i-1}(:,nonzero_grad)' gones(snonzero_grad,1,gputype)];\n\telse\n\t  grad{i} = backward{i} * resp{i-1}(:,nonzero_grad)';\n\tend\n      else\n\tgrad{i} = backward{i} * X(:, nonzero_grad)';\n      end\n    end\n  else\n    for i=nlayer:-1:1\n      if (i == nlayer)\n\ttmp = hout;\n      else\n\ttmp = (W{i+1}' * backward{i+1});\n      end\n      \n      if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n      end\n    \n      if (i == nlayer)\n\tbackward{i} = tmp .* (1 - resp{i}.^2);\n      else\n\tbackward{i} = tmp .* (1 - resp{i}) .* resp{i};\n      end\n\n      if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t  grad{i} = backward{i} * [resp{i-1}' onesncases];\n\telse\n\t  grad{i} = backward{i} * resp{i-1}';\n\tend\n      else\n\tgrad{i} = backward{i} * X';\n      end\n    end\n  end\n\nend\n", "meta": {"author": "norouzi", "repo": "hdml", "sha": "78e01180fc2494db31f04a9f4653456a8bfb8ba0", "save_path": "github-repos/MATLAB/norouzi-hdml", "path": "github-repos/MATLAB/norouzi-hdml/hdml-78e01180fc2494db31f04a9f4653456a8bfb8ba0/compute_NN_grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5992905195978329}}
{"text": "function s=sprintsi(x,d,w)\n%SPRINTSI Print X with SI multiplier S=(X,D,W)\n% D is number of decimal places (+ve) or significant digits (-ve) [default=-3]\n% |W| is total width including multiplier\n% if W<=0 then trailing 0's will be eliminated\n%\n% Example: sprintsi(2345,-2) gives '2.3 k'\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: sprintsi.m 713 2011-10-16 14:45:43Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin<3 w=0; end;\nif nargin<2 d=-3; end;\nf='afpnum kMGT';\ne=max(-18,min(12,floor(log10(abs(x)))));\nk=floor(e/3);\ndp=max([0 d 3*k-d-e-1]);\nif w<=0 & dp\n   w=abs(w);\n   dp=max(find([1 mod(mod(round(x*10^(dp-3*k)),10^dp),10.^(dp:-1:1))]))-1;\nend\nif(k)\n   s=sprintf(sprintf('%%%d.%df %c',w-2,dp,f(k+7)),x*1e-3^k);\nelse\n   s=sprintf(sprintf('%%%d.%df ',w-1,dp),x*1e-3^k);\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/sprintsi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5992792851457613}}
{"text": "function pass = test_minus( pref ) \n% This tests the basic arithmetic operations on chebfun2 objects.\n\nif ( nargin < 1 ) \n    pref = chebfunpref; \nend \ntol = 1e5 * pref.cheb2Prefs.chebfun2eps;\nj = 1;\n\nD = [-1 1 -1 1; -2 2 -2 2; -1 pi 0 2*pi];\n\nfor r = 1 : size(D,1)\n    f = chebfun2(@(x,y) cos(x.*y), D(r,:));\n    g = chebfun2(@(x,y) x + y + x.*y, D(r,:));\n    \n    FminusG = chebfun2(@(x,y) cos(x.*y) - (x + y + x.*y), D(r,:) );\n    \n    tolr = norm(D(r,:),inf)*tol;\n    \n    pass(j) = ( norm( (f-g) - FminusG ) < 10*tolr ); j = j + 1;\n    \nend\n\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun2/test_minus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.5992792826490982}}
{"text": "% GP_COV_SUM - Covariance function as a sum of two covariance functions.\n%\n% Usage:\n%\n%   COVFUNC = GP_COV_SUM(COVFUNC1, COVFUNC2)\n%\n% The returned covariance function is called as\n%\n%   K = COVFUNC(THETA)\n%   [K, DK] = COVFUNC(THETA)\n%\n% where THETA is a vector of parameters. The parameters of COVFUNC1 and\n% COVFUNC2 are concatenated into a single parameter vector.\n%\n% If no arguments are given, dimensionality information is returned:\n%\n%   [N_THETA, N1, N2] = COVFUNC()\n%\n% N_THETA : Number of non-fixed parameters\n% N1      : Number of rows in the covariance matrix\n% N2      : Number of columns in the covariance matrix\n%\n% See also GP_COV, GP_COV_PRODUCT.\n\n% Last modified 2010-01-25\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)\n\nfunction func = gp_cov_sum(varargin)\n\nfunc = @get_covariance;\n\nif nargin < 2\n  error('Must give at least two covariance functions')\nend\n\ncovfuncs = varargin ;\n\n% Number of covariance functions\nn_funcs = nargin ;\n\n% Number of parameters for each covariance function\nn_theta = zeros(n_funcs,1) ;\n% Dimensionalities of each covariance function\nM = zeros(n_funcs,1) ;\nN = zeros(n_funcs,1) ;\n% Extract the values from the covariance functions\nfor i = 1:n_funcs\n  [n_theta(i), M(i), N(i)] = varargin{i}();\nend\n\n% Indices of the hyperparameters for each covariance function\nind_theta = cell(n_funcs,1);\nfor i = 1:n_funcs\n  ind_theta{i} = (1+sum(n_theta(1:(i-1)))):(sum(n_theta(1:i))) ;\nend\n\n%[n_theta1, M1, N1] = covfunc1();\n%[n_theta2, M2, N2] = covfunc2();\n\nif ~all(M == M(1)) || ~all(N == N(1))\n  error('Can''t sum covariance matrices with different dimensionalities');\nend\nM = M(1) ;\nN = N(1) ;\n\n  function varargout = get_covariance(theta)\n  \n  if nargout == 0\n    nout = 1 ;\n  else\n    nout = nargout ;\n  end\n  \n  varargout = cell(nout,1);\n\n  out = cell(nout,1);\n  varargout = cell(nout,1);\n  \n  % Return only dimension information if requested\n  if nargin == 0\n    if nout >= 1\n      varargout{1} = sum(n_theta); % number of parameters\n      if nout >= 2\n        varargout{2} = M; % dimensionalities\n        if nout >= 3\n          varargout{3} = N; % dimensionalities\n        end\n      end\n    end\n    return\n  end\n\n  varargout{1} = 0 ;\n  varargout{2} = cell(sum(n_theta),1) ;\n  \n  for i = 1:n_funcs\n    % Compute the covariance matrix\n    [out{:}] = covfuncs{i}(theta(ind_theta{i}));\n    varargout{1} = varargout{1} + out{1};\n  \n    % Compute the derivative\n    if nout >= 2\n      varargout{2}(ind_theta{i}) = out{2}(:);\n    end\n  end\n  \n  end\n\nend", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gp/gp_cov_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5992588175898862}}
{"text": "function [Xmat,idxisa] = workvolume(cam,room,imres,idxcams)\n\nSTEP = 0.1;\n\nif nargin < 4\n\tidxcams = [1:size(cam,2)];\nend\n\nif nargin < 3\n\timres = repmat([640 480],size(idxcams,2),1);\nend\nimres = imres(idxcams,:);\n\nif nargin < 2\n\t% room [x_min, x_max, y_min, y_max, z_min, z_max]\n\troom = [-3 3 -3 3 0 3];\nend\n\n% compose Pmat containing all P matrices\nPmat = [];\nfor i=idxcams,\n\tPmat = [Pmat; cam(i).P];\nend\n\n% create points\n\nzcoor = room(5):STEP:room(6);\nznum = size(zcoor,2);\nycoor = room(3):STEP:room(4);\nynum = size(ycoor,2);\nxcoor = room(1):STEP:room(2);\nxnum = size(xcoor,2);\n\n\nbuff  = repmat(ycoor,znum,1);\nyvec  = reshape(buff,prod(size(buff)),1);\nzvec  = repmat(zcoor',ynum,1);\n\nbuff = repmat(xcoor,znum*ynum,1);\nxvec = reshape(buff,prod(size(buff)),1);\n\nXmat = [xvec,repmat([yvec,zvec],xnum,1)];\nXmat = [Xmat,ones(size(Xmat(:,1)))];\n\nclear buff\n\nsize(Xmat)\numat = Pmat*Xmat';\n\n% normalize projected points in umat\nscalemat = [];\nfor i=1:size(idxcams,2),\n\tscalemat = [scalemat; repmat(umat(3*i,:),3,1)];\nend\numat = umat./scalemat;\nclear scalemat;\nmask = zeros(size(umat));\nmask(1:3:end,:) = umat(1:3:end,:)<repmat(imres(:,1),1,size(mask,2));\nmask(2:3:end,:) = umat(2:3:end,:)<repmat(imres(:,2),1,size(mask,2));\nmask(3:3:end,:) = 1;\nmask = mask.*(umat>0);\nidxisa = find(sum(mask)==size(mask,1));\n\nreturn;\n\n", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamValidation/CoreFunctions/workvolume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5992588175898861}}
{"text": "function [beta, t, pvals, convals, con_t, con_pvals, sigma, Phi, df, stebeta, conste, F] = fit_gls(y, X, c, p, varargin)\n% Fit a linear model using generalized least squares and an AR(p) model\n%\n% :Usage:\n% ::\n%\n%     [beta, t, pvals, convals, con_t, con_pvals, sigma, Phi, df, stebeta, conste, F] = fit_gls(y,X,c,p,[PX, equal to pinv(X), for speed], [Weights])\n%\n% This program uses the Cochrane-Orcutt algorithm to iteratively find the\n% GLS solution and estimate the noise parameters.\n%\n% Step 1: Find the OLS solution.\n%\n% Step 2: Use residuals from the previous fit to estimate the parameters in\n% the AR(p) noise model.\n%\n% Step 3: Find the GLS solution using the covariance matrix corresponding\n% to an AR(p) model with parameters estimated in Step 2 inserted.\n%\n% Step 4: Repeat steps 2-3 until convergence.\n%\n% :Inputs:\n%\n%   **y:**\n%        fMRI time course (T x 1 vector)\n%\n%   **X:**\n%        Design matrix (T x param matrix)\n%\n%   **c:**\n%        contrast vector(s) (param x # contrasts matrix)\n%\n%   **p:**\n%        order of AR model.\n%\n%   **PX:**\n%        pinv(X), for speeded, repeated calculations with different y vectors\n%\n%        Note: if using weights, px = inv(X' * W * X) * X' * W; \n%              where W = diag(Weights);\n%\n%   **Weights:**\n%        Optional, vector of weights for each observation\n%\n%        Empty or missing: Unweighted analysis.\n%\n% Note that setting p=0 implies a white noise model.\n%\n% :Output:\n%\n%   **t:**\n%        t-value for the contrast c'beta\n%\n%   **df:**\n%        degrees of freedom using Satterthwaite approximation\n%\n%   **beta:**\n%        beta vector\n%\n%   **Phi:**\n%        vector of coefficients in AR(p) model\n%\n%   **sigma:**\n%        standard deviation\n%\n%   **stebeta:**\n%        standard error of betas\n%\n% ..\n%    by Martin Lindquist\n%\n%    Last updated: 3/29/08, Tor Wager, added weighted least squares\n%                        verified that beta and t-values are identical to\n%                        glmfit.m in matlab7.5 with ar p = 0\n%                        ***AR(p) with weighted least squares needs to be\n%                        checked.  behaving reasonably.\n%               4/1/08,  Tor : output stats for boht betas and contrasts\n%                        Reorganized order of outputs\n%               5/15/08  Tor : Weird things happening with single inputs; particulaly with aryule; force\n%                         double\n% ..\n\ny = double(y);\nX = double(X);\n\nT = length(y);      % Length of time course\n\nk = size(X, 2);     % predictors\n\n\nif length(varargin) > 1\n    w = double(varargin{2});        % weights for weighted least squares\nelse\n    w = ones(T, 1);\nend\nW = diag(w);\nsqrtW = sqrt(W);     % for weighted residuals\n\nif ~isempty(varargin) && ~isempty(varargin{1})\n    px = double(varargin{1});\nelse\n    invxvx = inv(X' * W * X);   % we can re-use this later if p == 0\n    px = invxvx * X' * W; \nend\n\n\n% Step 1: Find the OLS solution \nbeta = px*y;                                      % Beta values; weighted, if weights are used\nresid = sqrtW * y - sqrtW * X * beta;             % Residuals (Weighted, if weights are used)\nsigma = sqrt((1 / (T - k)) * resid' * resid);     %sum(resid.^2)));  % Estimate of Sigma\n\n% Weighted residuals: Three equivalent ways\n% We pick one that is compatible with AR estimation\n% 1)\n% beta = px*y;                       % Beta values\n% resid = y - X*beta;                     % Residuals\n% sigma = sqrt((1 / (T - k)) * resid' * W * resid); %sum(resid.^2)));  % Estimate of Sigma\n\n% 2) \n%r2 = sqrt(W) * resid; sigma2 = sqrt((1 / (T - k)) * r2' *  r2)\n\n% 3)\n% r2 = sqrt(W) * y - sqrt(W) * X * beta;\n% sigma2 = sqrt((1 / (T - k)) * r2' *  r2)\n\n% Stuff needed for future iterations\niV = W;  % for ar p = 0 case\nA = W;   % for ar p = 0 case\nPhi = 0;\nbetaold = 0;\n\n% Steps 2-4: Find the GLS solution by iteration \n% If p=0, skip this step. Appropriate solution already calculated above.\n% Continue iteration until convergence or for at most 10 loops.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Note to Jack and Tor: Keith Worsley uses a similar algorithm when fitting\n% a GLM with an AR(p) noise model. However, he skips the iterative step\n% and only goes through the loop one time. He claims that this is enough. I\n% am not entirely convinced, therefore it is probably better to go through\n% a few times if needed.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ni=1;                % Set counter\n\nwhile i < 10 && p > 0 && (i == 1 || sum((beta - betaold).^2) > 0.001)\n    % Do up to 10 iterations, if arp > 0 and either first iteration or\n    % there's a difference from last iteration\n    \n    % resid = y - X*beta;             % Calculate residuals of current model fit\n\n    resid = sqrtW * y - sqrtW * X * beta;             % Residuals (Weighted, if weights are used)\n\n    % Estimate AR parameters using residuals\n    [a,e] = aryule(resid, p);\n    Phi =zeros(length(a)-1,1);\n    Phi(1:p) = -a(2:(p+1));\n\n    %sigma = sqrt(e); % swrtW*e??  % Moved later, because never used until\n    %after iteration loop\n\n    % Find the inverse of the covariance matrix\n    A = sqrtW; % ***should be sqrt(W)?\n\n    for j=1:p\n        %A = A + diag(-Phi(j)*ones((T-j),1),-j);\n\n        A = A + sqrtW * diag(-Phi(j)*ones((T-j),1),-j);\n    end;\n\n    %create_figure('A'); imagesc(A, [-.2 .2]); colorbar, drawnow, input(' ')\n\n    iV = A*A';                      %  New weights, with AR estimates, The inverse of the covariance matrix\n\n\n    betaold = beta;                 % Set old solution to be betaold\n    beta = inv(X'*iV*X)*X'*iV*y;    % Calculate new solution\n\n    i = i+1;                        % Add one to counter\n\n    %create_figure('COV'); imagesc(iV, [-.02 .02]); colorbar, drawnow, input(' ')\nend\n\nif p > 0 \n    % re-calc sigma\n    sigma = sqrt(e);\n\n    invxvx = inv(X'*iV*X);\n    \n    % Should we use the kind of thing below? Seems like sqrt(e) is unweighted,\n    % though it seems reasonable...\n    % sqrtiv = sqrt(iV);\n    % resid = sqrtiv * y - sqrtiv * X * beta;             % Residuals (Weighted, if weights are used)\n    % sigma = sqrt((1 / (T - k)) * resid' * resid)\nend\n\n\n\nR = (eye(T) - X * invxvx * X' * iV);        % Residual inducing matrix\n\nWd = R * A * inv(iV) * A';                  % inv(iV) = Covariance matrix\ndf = (trace(Wd).^2)./trace(Wd*Wd);       % Satterthwaite approximation for degrees of freedom\n\n\n% Should check on below: this creates difference in t-values from\n% glmfit...but why wouldn't we need to re-calculate a (larger) sigma if we have reduced df?\n% if df ~= (T - k)                    % Tor added 3/29, have to re-calculate sigma\n%     sigma = sqrt((1 / df) * resid' * iV * resid); %sum(resid.^2)));  % Estimate of Sigma\n% end\n\nvarbeta = sigma^2.* invxvx;            % Var(beta)\nstebeta = diag(varbeta).^.5;\nt = beta ./ stebeta;\n\nconvals = [];\nconste = [];\ncon_t = [];\ncon_pvals = [];\nF = [];\nif ~isempty(c)\n    % Contrast(s)\n    convals = (c' * beta);\n    conste = diag(c' * varbeta * c).^.5;                   % tor added as output\n    con_t = convals ./ conste;                            %sqrt(c'*varbeta*c);             % t-value\nend\n\n% get rid of nuisance regressors that aren't in any contrast\n% wh = stebeta > 0;\n% c = c(wh,wh); \n% beta = beta(wh);\n% stebeta = stebeta(wh);\n% \n% if ~isempty(c)\n%     beta = (c' * beta);\n%     %beta = beta(wh);\n%     t = beta ./ stebeta;   %sqrt(c'*varbeta*c);            % t-value\n% else\n%     t = beta(wh) ./ stebeta;\n% end\n\n%%%%%% Test H0: beta_1 = beta_2 = .... = beta_param = 0\nif nargout > 6\n    SSE = y'*y - beta'*X'*y;                 % Error sum of squares\n    mSSE = SSE/df;\n    J = ones(T);\n    SST=y'*y - (1/T).*y'*J*y;           % Total sum of squares\n    SSM=SST-SSE;                        % Model sum of squares\n\n    dfSSM=length(c) - 1;                % degrees of freedom for model (param - 1)\n    mSSM=SSM/dfSSM;\n\n    F=mSSM/mSSE;         % F-statistic - compare with F-distruibution with (param-1, df) degrees of freedom\nend\n\n% % get contrast values if we need those\n% if ~isempty(c)\n%     beta = (beta' * c)';\n% end\n\nif nargout > 2\n    pvals = 2 .* (1 - tcdf(abs(t), df)); % two-tailed\n    \n    \n    % make sure p-values for valid results are not zero...\n    pvals(pvals == 0 & beta ~= 0 & ~isnan(beta)) = 1000*eps;\n    \n    if ~isempty(c) && nargout > 5\n        con_pvals = 2 .* (1 - tcdf(abs(con_t), df)); % two-tailed\n        \n        con_pvals(con_pvals == 0 & convals ~= 0 & ~isnan(convals)) = 1000*eps;\n    end\n        \nend\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/Statistics_tools/fit_gls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.599258816313898}}
{"text": "function [ quasi, seed_new ] = sobol ( dim_num, seed )\n\n%% 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%  Modified:\n%\n%    30 March 2003\n%\n%  Reference:\n%\n%    Antonov and Saleev,\n%    USSR Computational Mathematics and Mathematical Physics,\n%    Volume 19, 1980, pages 252 - 256.\n%\n%    Paul Bratley and 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%    I Sobol,\n%    USSR Computational Mathematics and Mathematical Physics,\n%    Volume 16, pages 236-242, 1977.\n%\n%    I Sobol and 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 2 <= 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  global SOBOL_lastq;\n  global SOBOL_seed;\n\n  dim_max = 40;\n%\n%  Initialize (part of) V.\n%\n    v(1:40,1:30) = zeros(40,30);\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%  Check parameters.\n%\n    if ( dim_num < 2 | dim_max < dim_num )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'SOBOL - Fatal error!\\n' );\n      fprintf ( 1, '  The spatial dimension DIM_NUM should satisfy:\\n' );\n      fprintf ( 1, '    2 <= 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    atmost = 2^30 - 1;\n%\n%  Find the number of bits in ATMOST.\n%\n    maxcol = bit_hi1_base_2 ( atmost );\n%\n%  Initialize row 1 of V.\n%\n    v(1,1:maxcol) = 1;\n%\n%  Initialize the remaining rows of V.\n%\n    for ( i = 2 : dim_num )\n%\n%  The bit pattern of the integer POLY(I) gives the form\n%  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%  We 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\n        newv = v(i,j-m);\n        l = 1;\n\n        for ( k = 1 : m )\n\n          l = 2 * l;\n\n          if ( includ(k) )\n            newv = exor ( newv, l * v(i,j-k) );\n          end\n\n        end\n\n        v(i,j) = newv;\n\n      end\n\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.0E+00 / ( 2 * l );\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    SOBOL_lastq(1:dim_num) = 0;\n\n  elseif ( seed == SOBOL_seed + 1 )\n%\n%  Find the position of the right-hand zero in SEED.\n%\n    l = bit_lo0_base_2 ( seed );\n\n  elseif ( seed <= SOBOL_seed )\n\n    SOBOL_seed = 0;\n    l = 1;\n    SOBOL_lastq(1:dim_num) = 0;\n\n    for ( seed_temp = SOBOL_seed : seed-1 )\n\n      l = bit_lo0_base_2 ( seed_temp );\n\n      for ( i = 1 : dim_num )\n        SOBOL_lastq(i) = exor ( SOBOL_lastq(i), v(i,l) );\n      end\n\n    end\n\n    l = bit_lo0_base_2 ( seed );\n\n  elseif ( SOBOL_seed+1 < seed )\n\n    for ( seed_temp = SOBOL_seed+1 : seed-1 )\n\n      l = bit_lo0_base_2 ( seed_temp );\n\n      for ( i = 1 : dim_num )\n        SOBOL_lastq(i) = exor ( SOBOL_lastq(i), v(i,l) );\n      end\n\n    end\n\n    l = bit_lo0_base_2 ( 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, '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\n    quasi(i) = SOBOL_lastq(i) * recipd;\n\n    SOBOL_lastq(i) = exor ( SOBOL_lastq(i), v(i,l) );\n\n  end\n\n  SOBOL_seed = seed;\n  seed_new = seed + 1;\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/Sobol/sobol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5992588126762608}}
{"text": "function tests = test_ft_preproc_bandpassfilter\n\n% MEM 1gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_preproc_bandpassfilter\n\nif nargout\n  % assume that this is called by RUNTESTS\n  tests = functiontests(localfunctions);\nelse\n  % assume that this is called from the command line\n  fn = localfunctions;\n  for i=1:numel(fn)\n    feval(fn{i});\n  end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction testOptions(testCase)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nnchan   = 8;\nnsample = 1000;\n\ndat = randn(nchan, nsample) + 1;\nFs  = 1000;\nFbp = [1 35];\n\ninstabilityfix  = [];\ndf              = []; \nwintype         = []; \ndev             = []; \nplotfiltresp    = [];\nusefftfilt      = [];\n\nfilttypes = {'brickwall', 'firws' 'fir' 'firls' 'but'};\nfiltdirs  = {'onepass' 'onepass-reverse' 'twopass' 'twopass-reverse' 'twopass-average' 'onepass-zerophase' 'onepass-reverse-zerophase' 'onepass-minphase'};\nfiltorders = {[] 1 2 4 8};\n\nresult = {};\nopts   = {};\nfor i1 = 1:numel(filttypes)\n  if isequal(filttypes{i1}, 'brickwall')\n    opts{end+1}   =[filttypes{i1}]; \n    result{end+1} = ft_preproc_bandpassfilter(dat, Fs, Fbp, [], filttypes{i1}, [], instabilityfix, df, wintype, dev, plotfiltresp, usefftfilt);\n    continue;\n  elseif isequal(filttypes{i1}, 'but')\n    sel2 = 1:5;\n    sel3 = 2:4; % order 8 may become unstable, and thus requires an instabilityfix\n  elseif isequal(filttypes{i1}, 'firws')\n    sel2 = find(~contains(filtdirs, 'twopass')); % this leads to a filter that is not stable\n    sel3 = 1; % the low number orders do not make sense at all for the finite impulse filters.\n  else\n    sel2 = 1:numel(filtdirs);\n    sel3 = 1;\n  end\n  for i2 = sel2\n    for i3 = sel3\n      tmp = filtorders{i3};\n      if isempty(tmp)\n        tmp = 'defaultorder';\n      elseif isnumeric(tmp)\n        tmp = sprintf('order %d', tmp);\n      end\n      opts{end+1}   = sprintf('%s_%s_%s', filttypes{i1}, filtdirs{i2}, tmp); \n      result{end+1} = ft_preproc_bandpassfilter(dat, Fs, Fbp, filtorders{i3}, filttypes{i1}, filtdirs{i2}, instabilityfix, df, wintype, dev, plotfiltresp, usefftfilt);\n    end\n  end\nend\n\n% result{end+1} = ft_preproc_bandpassfilter(dat, Fs, Fbp, 8, 'but'      , 'onepass'                  , 'split', [], [], [], [], []); % this one is instable\n% result{end+1} = ft_preproc_bandpassfilter(dat, Fs, Fbp, 8, 'but'      , 'onepass-reverse'          , 'split', [], [], [], [], []);\n% result{end+1} = ft_preproc_bandpassfilter(dat, Fs, Fbp, 8, 'but'      , 'twopass'                  , 'split', [], [], [], [], []);\n% result{end+1} = ft_preproc_bandpassfilter(dat, Fs, Fbp, 8, 'but'      , 'twopass-reverse'          , 'split', [], [], [], [], []);\n% result{end+1} = ft_preproc_bandpassfilter(dat, Fs, Fbp, 8, 'but'      , 'twopass-average'          , 'split', [], [], [], [], []);\n\n% all iterations were done with (slightly) different options, hence the results should not be equal\nfor i=1:numel(result)\n  for j=(i+1):numel(result)\n    assert(~isequal(result{i}, result{j}), 'the results %d and %d should not be equal', i, j);\n  end\nend\n\nfor i=1:size(result{1},1)\n  for k=1:numel(result)\n    for m=(k+1):numel(result)\n      b(k,m) = result{k}(i,:)/result{m}(i,:);\n      b(m,k) = result{m}(i,:)/result{k}(i,:);\n    end\n    B(:,:,i) = b;\n  end\nend\nn = numel(result);\nfigure;imagesc((mean(B,3)+mean(B,3)')/2);\nset(gca, 'xtick', 1:n, 'ytick', 1:n, 'xticklabel', opts', 'yticklabel', opts', 'ticklabelinterpreter', 'none');\nset(gcf, 'position', [230 47 993 750]);\ncolorbar\naxis equal;axis tight\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_ft_preproc_bandpassfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5992588114002728}}
{"text": "function [h,t,dat,d,m1,m2,sterr] = tor_fill_steplot(dat,color,varargin)\n% :Usage:\n% ::\n%\n%    [h,t] = tor_fill_steplot(dat,color,[robust flag],[p-thresh],[x vector],[covs no interest])\n%\n% Plots a mean vector (mean of each column of dat)\n% surrounded by a fill with standard err bars\n%\n% If dat has 3 dimensions, then\n% the diff between dat(:,:,1) and dat(:,:,2) is\n% used as the difference for computing standard err\n% (as in repeated measures)\n%\n% if behavior is entered as optional argument, removes it before plotting\n% lines.  Also returns adjusted output in d, dat\n% \n% Optional: robust flag (1/0), robust IRLS\n%\n% :Examples:\n% ::\n%\n%    tor_fig;\n%    tor_fill_steplot(dat,{'b' 'r'},0,.05,secs);\n\ndorobust = 0; pthresh = 0; x = 1:size(dat,2);\nt = []; m1 = []; m2 = []; X = [];\n\nif length(varargin) > 0, dorobust = varargin{1};,end\nif length(varargin) > 1, pthresh = varargin{2};,end\nif length(varargin) > 2, x = varargin{3};,end   % small x, time\nif length(varargin) > 3, X = varargin{4};,end   % big X, model matrix of covs\n\nif isempty(x), x = 1:size(dat,2);, end\n\n\n\n\nif length(size(dat)) > 2\n    \n    % remove covariates of no interest, if any\n    % center covs and fit without intercept to preserve mean in data\n    if ~isempty(X)\n        disp('Adjusting for covariates.');\n        X = scale(X,1); % center\n        W = X * pinv(X);\n        y = squeeze(dat(:,:,1));\n        dat(:,:,1) = y - W * y;\n    \n        y = squeeze(dat(:,:,2));\n        dat(:,:,2) = y - W * y;\n    end\n    \n    d = dat(:,:,1) - dat(:,:,2);\n    \n    if dorobust\n        [m1] = robust_mean(dat(:,:,1));\n        [m2] = robust_mean(dat(:,:,2));\n        [dummy,t,p,sterr] = robust_mean(d);\n    else\n        \n        m1 = nanmean(dat(:,:,1));\n        m2 = nanmean(dat(:,:,2));\n        md = nanmean(d);\n        sterr = ste(d);\n        t = md ./ sterr;\n        [h,p,ci,stat] = ttest(d);\n    end\n    \n    if ~iscell(color), error('For two groups, color should be cell, e.g.,  {''r'' ''b''})');,end\n    \n    hold on; \n    h(1) = plot(x,m1,color{1},'LineWidth',2);\n    h(2) = plot(x,m2,color{2},'LineWidth',2);\n \n    drawnow\n    \n    fill_around_line(m1,sterr,color{1},x);\n    fill_around_line(m2,sterr,color{2},x);\n\n    drawnow\n    \n    if pthresh\n        % significance markers at top of plot.\n        yval = max([m1 m2]) + .04 * max([m1 m2]);\n        k = 1;\n        df = size(d,1) - k;\n        %tthr = tinv(1 - pthresh,df);\n        tsig = (p < pthresh) .* t;\n        \n        wh = yval * (tsig > 0);%double((t > tthr)); wh(wh==0) = NaN; wh(wh>0) = yval;\n        %plot(x,wh,color{1},'LineWidth',3);\n        for i = 1:length(wh)\n            if wh(i)\n                text(x(i),wh(i),'*','Color',color{1}(1),'FontSize',24);\n            end\n        end\n        \n        %wh = yval(find(tsig < 0)); % double((t < -tthr)); wh(wh==0) = NaN; wh(wh>0) = yval;\n        %plot(x,wh,color{2},'LineWidth',3);\n  \n        wh = yval * (tsig < 0);%double((t > tthr)); wh(wh==0) = NaN; wh(wh>0) = yval;\n        %plot(x,wh,color{1},'LineWidth',3);\n        for i = 1:length(wh)\n            if wh(i)\n                text(x(i),wh(i),'*','Color',color{2}(1),'FontSize',24);\n            end\n        end\n        \n        \n        text(x(5),yval+.04 * max([m1 m2]),'Significant','FontSize',16);\n    end\n    \n    drawnow\n\nelse\n    \n    if dorobust\n        [m1,t,p,sterr] = robust_mean(dat(:,:,1));\n    else\n        m1 = nanmean(dat(:,:,1), 1);\n        sterr = ste(dat);\n    end\n    \n    if ~iscell(color), tmp = color; color = []; color{1} = tmp; end\n    \n    hold on; \n    if ischar(color{1})\n        h = plot(x,m1,color{1},'LineWidth',2);\n    else\n        h = plot(x,m1,'o-', 'Color', color{1},'LineWidth',2);\n    end\n    \n    fill_around_line(m1,sterr,color{1},x);\n    \nend\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/tor_fill_steplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.599258808305466}}
{"text": "function w = dwt3D(x, J, af)\n\n% 3-D Discrete Wavelet Transform\n%\n% USAGE:\n%   w = dwt3D(x, stages, af)\n% INPUT:\n%   x - N1 by N2 by N3 matrix\n%       1) Ni all even\n%       2) min(Ni) >= 2^(J-1)*length(af)\n%   J - number of stages\n%   af  - analysis filters\n% OUTPUT:\n%   w - cell array of wavelet coefficients\n% EXAMPLE:\n%   [af, sf] = farras;\n%   x = rand(128,64,64);\n%   w = dwt3D(x,3,af);\n%   y = idwt3D(w,3,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\nfor k = 1:J\n    [x w{k}] = afb3D(x, af, af, af);\nend\nw{J+1} = 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/DTCWT/dwt3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5992588064866473}}
{"text": "function [nuisance_ratio, rsquare_design, rsquare_nuis] = scn_component_rsquare(V, nuisanceX, designX)\n% Print a table of r-square values (variance explained) for each of V data\n% vectors by nuisance (mvmt, physio) and task-related predictors\n%\n% Designed to work with components\n%\n% :Examples:\n% ::\n%\n%     % Typical operation\n%     scn_component_rsquare(compscore, movement_params(1:157, :), X(1:157, :));\n%\n%     % No design\n%     scn_component_rsquare(compscore, movement_params(1:157, :));\n%\n%     % Neither design nor nuisance, uses linear drift\n%     scn_component_rsquare(compscore, []);\n%\n% ..\n%    Tor Wager, Feb 2008\n% ..\n\n[t, m] = size(V);\n\nif nargin < 3, designX = []; end\n\nif isempty(nuisanceX) \n    disp('Looking for nuisance covariates, but none found. Using linear drift.');\n    nuisanceX = (1:t)'; \nend\n    \ndisp('Variance in each component explained:')\n\n% Nuisance\nrsquare_nuis = get_rsquare(V, nuisanceX)';\n\nif ~isempty(designX)\nrsquare_design = get_rsquare(V, designX)';\nelse\n    rsquare_design = .01 * ones(m, 1);\nend\n\nnuisance_ratio = rsquare_nuis ./ rsquare_design;\n\nnuis_related = find(nuisance_ratio > 2);\ntask_related = find(nuisance_ratio < 1);\n\n%rank_badness = sort(nuisance_ratio, 1, 'descend');\ndisp('All components');\nprint_matrix([(1:m)' rsquare_design rsquare_nuis nuisance_ratio], {'Comp.' 'R^2 Task' 'R^2 Nuisance' 'Ratio'});\nfprintf('\\n');\n\ndisp('Most task-related');\nif isempty(designX)\n    disp('NO DESIGN INFORMATION.');\nelse\nprint_matrix([task_related rsquare_design(task_related) rsquare_nuis(task_related) nuisance_ratio(task_related)], {'Comp.' 'R^2 Task' 'R^2 Nuisance' 'Ratio'});\nend\nfprintf('\\n');\n\ndisp('Most nuisance-related');\nprint_matrix([nuis_related rsquare_design(nuis_related) rsquare_nuis(nuis_related) nuisance_ratio(nuis_related)], {'Comp.' 'R^2 Task' 'R^2 Nuisance' 'Ratio'});\nfprintf('\\n');\n\n\n%fprintf('\\tComp %3.0f : %3.0f%%\\n', j, rsquare(j)*100);\nend\n\nfunction rsquare = get_rsquare(V, X)\n\n    [t, m] = size(V);\n    \n    for j = 1:m\n    % Center component to avoid counting intercept in r-square?\n    % Don't have to, doesn't matter because var operator is 2nd moment\n    y = V(:, j);  \n    b =  X \\ y;\n\n    fits = X * b;\n\n    rsquare(j) = var(fits) / var(y);\n    \n    end\n\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/diagnostics/scn_component_rsquare.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5992587966593964}}
{"text": "% plot_lognorm_scat2_1d: Plots the log normalized 2nd order scattering\n% coefficients for 1d signals.\n% Usage\n%    plot_lognorm_scat2_1d(S)\n% Input\n%    S: The log normalized scattering coefficients.\n% Output\n%    N/A\n% Description\n%   Plots the second order log normalized scattering coefficients as a\n%   function of j2-j1 (where 2^(-j1) is the first frequency, 2^(-j2) is the\n%   second frequency) for various values of j1.\n\nfunction plot_lognorm_scat2_1d(S)\n\n% Settings\n\n% The lower limit of j2-j1\nlowlimit = -2;\n\n% Stop plotting j2-j1 at the max-earlystop\nearlystop = 2;\n\n% The values of j1 go up to max-earlyend\nearlyend = 1;\n\n%% Initialize\n\n% Adjust settings as needed\nearlyend = max(earlyend,earlystop);\n\n% Second order coefficients\nS2 = S{3};\n\n% Number of frequencies minus one\nmaxj1 = max(S2.meta.j(1,:));\n\n% Colormap\nC = jet(maxj1-earlyend+1);\n\n% Legend\nleg = cell(maxj1-earlyend+1,1);\n\n%% Loop through values of j1 and plot in terms of j2-j1\n\nfigure,hold on;\nfor j1=0:(maxj1-earlyend)\n    indj1 = find(S2.meta.j(1,:)==j1);\n    j2 = S2.meta.j(2,indj1);\n    \n    S2j1j2 = S2.signal(indj1);\n    S2j1j2 = cat(2,S2j1j2{:});\n    S2j1j2 = S2j1j2(1,:);\n    \n    [j2,indj2] = sort(j2,'ascend');\n    S2j1j2 = S2j1j2(indj2);\n    \n    j2minj1 = j2-j1;\n    indj2j1 = j2minj1 >= lowlimit;\n    indj2j1((end-earlystop+1):end) = false;\n    \n    plot(j2minj1(indj2j1),S2j1j2(indj2j1),'Color',C(j1+1,:));\n    leg{j1+1} = sprintf('%d',j1);\nend\nlegend(leg);\nhold off;\n\nend", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/display/plot_lognorm_scat2_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5992587953834083}}
{"text": "%% load some data\nload leq\n%% plot it\nplot(yy);, grid on\ntitle('1-D signal')\n%% embed it into a 3-D space with a delay of 10\nN=10;\nA=[yy(1:end-(N-1)),yy(N/2:end-N/2),yy(N:end)];\n%% plot it again\nfigure\nplot3(A(:,1),A(:,2),A(:,3))\ngrid on, axis tight\ntitle('3-D signal')", "meta": {"author": "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/takens.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.599258784280169}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   Q = INVERSEKINEMATIC_SCARA(robot, T)\t\n%   Solves the inverse kinematic problem for the SCARA example robot\n%   where:\n%   robot stores the robot parameters.\n%   T is an homogeneous transform that specifies the position/orientation\n%   of the end effector.\n%\n%   A call to Q=INVERSEKINEMATIC_SCARA returns 2 possible solutions, thus,\n%   Q is a 4x4 matrix where each column stores 4 feasible joint values.\n%\n%   \n%   Example code:\n%\n%   robot=load_robot('example', 'scara');\n%   q = [0 0 0 0];\t\n%   T = directkinematic(robot, q);\n%   %Call the inversekinematic for this robot\n%   qinv = inversekinematic(robot, T);\n%   %check that all of them are feasible solutions!\n%   %and every Ti equals T\n%   for i=1:2,\n%        Ti = directkinematic(robot, qinv(:,i))\n%   end\n%\n%\tSee also DIRECTKINEMATIC.\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 <http://www.gnu.org/licenses/>.\nfunction q = inversekinematic_scara(robot, T)\n\nfprintf('\\nComputing inverse kinematics for the %s robot', robot.name);\n\n\n%initialize q\nq=zeros(4,2);\n\n%Evaluate the DH table to obtain geometric parameters\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\n\n%Store geometric parameters\nL1=abs(d(1));\nL2=abs(a(1));\nL3=abs(a(2));\n\n%T= [ nx ox ax Px;\n%     ny oy ay Py;\n%     nz oz az Pz];\nPx=T(1,4);\nPy=T(2,4);\nPz=T(3,4);\n\n\n%Distance of the point to the origin of S0\nR = sqrt(Px^2+Py^2);\n\n%Compute angles\ngamma = real(acos((L2^2+R^2-L3^2)/(2*R*L2)));\nbeta = atan2(Py,Px); \ndelta = real(acos((L2^2+L3^2-R^2)/(2*L2*L3)));\n\n%find the last rotation for the two possible configurations\nq4_1= find_last_rotation(robot,[beta+gamma delta-pi L1-Pz 0], T);\nq4_2= find_last_rotation(robot,[beta-gamma pi-delta L1-Pz 0], T);\n\n%Arrange all possible solutions\nq=[beta+gamma beta-gamma;\n    delta-pi pi-delta;\n    L1-Pz    L1-Pz;\n    q4_1 q4_2];\n\n\n% Compute the last rotation\nfunction q4 = find_last_rotation(robot, q, T)\n\nU = T(1:3,1);\n\n%Recompute the DH table according to q1, q2 and q3\ntheta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n%now compute the position/orientation of the system S3\nH=eye(4);\nfor i=1:3,\n    H=H*dh(theta(i), d(i), a(i), alpha(i));\nend\n\nX3=H(1:3,1);\nY3=H(1:3,2);\n\ncoseno=X3'*U;\nseno=U'*Y3;\n%compute the last rotation\nq4=atan2(seno,coseno);\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/scara/inversekinematic_scara.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5992534276334974}}
{"text": "function Gamma = simgamma_ltd(T,P,Pi,rate,L,refractory_period,grouping)\n%\n% Simulate state time courses with longer-than-order-1-markov time dependencies\n%\n% INPUTS:\n%\n% T                     Number of time points for each time series\n% P                     Transition probability matrix (K by K)\n% Pi                    Initial probabilities (K by 1)\n% rate                  The weights that model the contribution of the\n%                       latest L points are modelled by a Gamma\n%                       distribution, whose shape is 1 - and rate is\n%                       specified here\n% L                     The length of the history (in number of time points)\n%                       that influences the state at time t\n% refractory_period     to prevent bursts of quick changes, refractory_period\n%                       can be set so that, after a change, you cannot change again \n%                       after 'refractory_period' number of iterations\n%\n% OUTPUTS\n%\n% Gamma         simulated  p(state | data)\n%\n% Author: Diego Vidaurre, OHBA, University of Oxford\n\nN = length(T); K = length(Pi);\n\nif nargin<4, rate = 2; end\nif nargin<5, L = 10; end \nif nargin<6, refractory_period = 2; end \nif nargin<7, grouping = []; end\n\nGamma = zeros(sum(T),K);\nweights = gampdf(0:L-1,1,rate)'; \nweights = weights / sum(weights);\nweights = weights(end:-1:1);\n\nfor n = 1:N\n    if ~isempty(grouping)\n        i = grouping(n);\n        Pn = P(:,:,i); Pin = Pi(:,i)';\n    else\n        Pn = P; Pin = Pi;\n    end    \n    Gammai = zeros(T(n),K);\n    if any(Pin==1)\n        Gammai(1,Pin==1) = 1;\n    else\n        Gammai(1,:) = mnrnd(1,Pin);\n    end\n    last_ch = Inf; \n    for t = 2:L \n        if last_ch < refractory_period\n            Gammai(t,:) = Gammai(t-1,:); \n            last_ch = last_ch + 1;\n        else\n            if t==2\n                g = repmat(weights(end-t+2:end,1),1,K) .* Gammai(1:t-1,:);\n            else\n                g = sum(repmat(weights(end-t+2:end,1),1,K) .* Gammai(1:t-1,:));\n            end\n            g = g / sum(g);\n            Gammai(t,:) = mnrnd(1,g*Pn);\n            if any(Gammai(t,:)~=Gammai(t-1,:)), last_ch = 1; end\n            Gammai(t,:) = Gammai(t,:) / sum(Gammai(t,:));   \n        end\n    end\n    for t=L+1:T(n)\n        if last_ch < refractory_period\n            Gammai(t,:) = Gammai(t-1,:);\n            last_ch = last_ch + 1;\n        else\n            g = sum(repmat(weights,1,K) .* Gammai(t-L:t-1,:));\n            Gammai(t,:) = mnrnd(1,g*Pn);\n            if any(Gammai(t,:)~=Gammai(t-1,:)), last_ch = 1; end\n        end\n    end\n    t = (1:T(n)) + sum(T(1:n-1));\n    Gamma(t,:) = Gammai;\nend\n\nend\n\n", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/simulate/simgamma_ltd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5992534261981918}}
{"text": "function [Population,Fitness] = EnvironmentalSelection(Population,N)\n% The environmental selection of SPEA2+SDE\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    %% Calculate the fitness of each solution\n    Fitness = CalFitness(Population.objs);\n\n    %% Environmental selection\n    Next = Fitness < 1;\n    if sum(Next) < N\n        [~,Rank] = sort(Fitness);\n        Next(Rank(1:N)) = true;\n    elseif sum(Next) > N\n        Del  = Truncation(Population(Next).objs,sum(Next)-N);\n        Temp = find(Next);\n        Next(Temp(Del)) = false;\n    end\n    % Population for next generation\n    Population = Population(Next);\n    Fitness    = Fitness(Next);\nend\n\nfunction Del = Truncation(PopObj,K)\n% Select part of the solutions by truncation\n\n    N = size(PopObj,1);\n    \n    %% Calculate the shifted distance between each two solutions\n    Distance = inf(N);\n    for i = 1 : N\n        SPopObj = max(PopObj,repmat(PopObj(i,:),N,1));\n        for j = [1:i-1,i+1:N]\n            Distance(i,j) = norm(PopObj(i,:)-SPopObj(j,:));\n        end\n    end\n    \n    %% Truncation\n    Del = false(1,N);\n    while sum(Del) < K\n        Remain   = find(~Del);\n        Temp     = sort(Distance(Remain,Remain),2);\n        [~,Rank] = sortrows(Temp);\n        Del(Remain(Rank(1))) = true;\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/SPEA2+SDE/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5992534145983177}}
{"text": "function energy = computeEnergyBinaryPairwise( unaryTerms, pairwiseTerms, labels )\n%computeEnergyBinaryPairwise computes the value of the energy with unary and pairwise potentials\n\n%% check input\nnumLabels = 2;\n\nif ~isnumeric(unaryTerms) || ~ismatrix(unaryTerms) || size(unaryTerms, 2) ~= 2\n    error('Incorrect format for unaryTerms, has to be numNodes x 2')\nend\nnumNodes = size(unaryTerms, 1);\n\nif ~isnumeric(pairwiseTerms) || ~ismatrix(pairwiseTerms) || size(pairwiseTerms, 2) ~= 6\n    error('Incorrect format for pairwiseTerms, has to be numEdges x 6')\nend\nnumEdges = size(pairwiseTerms, 1);\n\nif ~isnumeric(labels) || ~isvector(labels) || length(labels) ~= numNodes\n    error('Incorrect format for labels, has to be numNodes x 1')\nend\nlabels = labels(:);\nif any(labels > numLabels) || any(labels < 1)\n    error('Incorrect values for labels, has to be an integer from 1 to numLabels')\nend\n\n%% computation\nenergy = sum( unaryTerms((1 : numNodes)' + numNodes * (labels - 1) ) );\n\nlabel1 = labels(pairwiseTerms(:, 1));\nlabel2 = labels(pairwiseTerms(:, 2));\nlabelMap = [ 3, 4; 5, 6];\njointLabelMap = labelMap( label1 + 2 * (label2 - 1) );\n\nenergy = energy + sum( pairwiseTerms( (1 : numEdges)' + numEdges * (jointLabelMap - 1) ) );\n\nend\n\n", "meta": {"author": "aosokin", "repo": "cnn_head_detection", "sha": "80624e7a25c62f7b504fa6f4d830136beb66eec8", "save_path": "github-repos/MATLAB/aosokin-cnn_head_detection", "path": "github-repos/MATLAB/aosokin-cnn_head_detection/cnn_head_detection-80624e7a25c62f7b504fa6f4d830136beb66eec8/pairwiseModel/energyMinimization/computeEnergyBinaryPairwise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.5992534051514037}}
{"text": "function rchy = realized_hayashi_yoshida(priceA,timeA,priceB,timeB,timeType,samplingType,samplingInterval,overlap)\n% Computed the Hayashi-Yoshida estimator of quadratic covariation, and allows for\n% the empirical-performance motivated K-lead-and-lag version similar to Drost and Nijman (1997).\n%\n% USAGE:\n%   [RCHY] = realized_hayashi_yoshida_(PRICEA,TIMEA,PRICEB,TIMEB,TIMETYPE,SAMPLINGTYPE,SAMPLINGINTERVAL,OVERLAP)\n%\n% INPUTS:\n%   PRICEA            - mA by 1 vector of high frequency prices\n%   TIMEA             - mA by 1 vector of times where TIMEB(i) corresponds to PRICEA(i)\n%   PRICEA            - mB by 1 vector of high frequency prices\n%   TIMEA             - mB by 1 vector of times where TIMEB(i) corresponds to PRICEB(i)\n%   TIMETYPE          - String describing the way times are measured\n%                        'wall'    24-hour clock of the form HHMMSS, e.g. 101543 or 153217\n%                        'seconds' Time measures in seconds past midnight.\n%                          TIME must satisfy 0<=TIME<86400\n%                        'unit'  Unit normalized date format, e.g. .1, .234, .9\n%                          Unit normalized times are more general than the\n%                          other types and can be applied to data from more\n%                          than one calendar day\n%   SAMPLINGTYPE      - String describing the type of sampling to use when\n%                         filtering PRICE\n%                         'CalendarTime' - Sample in calendar time using\n%                           observations separated by SAMPLINGINTERVAL\n%                           seconds. If TIMETYPE is 'unit',\n%                           SAMPLINGINTERVAL must be between 0 and 1 and\n%                           represents the fraction of the sample to skip\n%                           when sampling.\n%                         'CalendarUniform' - Sample in calendar time using\n%                           SAMPLINGINTERVAL observations spread uniformly\n%                           between TIME(1) and TIME(m)\n%                         'BusinessTime' - Sample in business (tick) time\n%                           using observation separated by SAMPLINGINTERVAL\n%                           ticks\n%                         'BusinessUniform' - Sample in business (tick)\n%                           time using observations uniformly spaced in\n%                           business time.\n%                         'Fixed' - Sample at specific points in time. When\n%                           using fixed, SAMPLINGINTERVAL must be a n by 1 vector\n%                           of times with the same TIMETYPE as TIME (i.e.\n%                           seconds if TIME is in seconds)\n%   SAMPLINGINTERVAL   - Scalar integer or n by 1 vector whose meaning depends on the\n%                          selected SAMPLINGTYPE\n%   OVERLAP            - Number of ticks to overlap when computing the HY estimator.  The original HY\n%                          estimator uses 0, which corresponds to the maximum likelihood estimator for\n%                          price processes whose observation times are driven by independent Poisson\n%                          processes.  Empirically this estimator performs poorly because prices are\n%                          not a vector semi-martingale and using a larger number of lags can alleviate\n%                          this problem.\n%\n% OUTPUTS:\n%   RCHY             - The K-lead-and-lag Hayashi-Yoshida covariance estimator\n%\n% COMMENTS:\n%   Filtering the price in calendar time allow the creation of a Hayashi-Yoshida corrected\n%   calendar-time sampled realized covariance.  The value in SAMPLINGTYPE is applied to price A and\n%   then the realized HY estimator is computed using the filtered price of A and the filtered times\n%   of A, and all observations of B.  Price filtering is done using realized_price_filter\n%\n% EXAMPLES:\n%   % Standard use with all prices with wall time prices\n%   RCHY = realized_hayashi_yoshida(PRICEA,TIMEA,PRICEB,TIMEB,'wall','BusinessTime',1,0)\n%\n%   % 10 lead and lag RCHY with all prices with wall time prices\n%   RCHY = realized_hayashi_yoshida(PRICEA,TIMEA,PRICEB,TIMEB,'wall','BusinessTime',1,10)\n%\n%   % 1-minute realized covariance with a HY correction\n%   RCHY = realized_hayashi_yoshida(PRICEA,TIMEA,PRICEB,TIMEB,'wall','CalendarTime',60,0)\n%\n%  See also REALIZED_MULTIVARIATE_KERNEL, REALIZED_COVARIANCE, REALIZED_KERNEL, REALIZED_VARIANCE,\n%  REALIZED_RANGE, REALIZED_QUANTILE_VARIANCE\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 5/1/2008\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin<7 || nargin>8\n    error('Seven or eight inputs required.')\nend\nif size(priceA,2)>size(priceA,1)\n    priceA=priceA';\nend\nif size(priceA,2)>1\n    error('PRICEA must be a m by 1 vector.')\nend\nif size(timeA,2)>size(timeA,1)\n    timeA=timeA';\nend\nif any(diff(timeA)<0)\n    error('TIMEA must be sorted and increasing')\nelseif any(diff(timeA)==0)\n    warning('oxfordRealized:realizedPriceFilter','TIMEA contains multiple entries with the same value. This creates an ambiguity and FILTEREDPRICE will contain the last price if TIMEA does not only unique elements.')\nend\nif size(timeA,2)>1 || length(timeA)~=length(priceA)\n    error('TIMEA must be a m by 1 vector.')\nend\n% Inserted to protect against inputing integer times\ntimeA = double(timeA);\nif size(priceB,2)>size(priceB,1)\n    priceB=priceB';\nend\nif size(priceB,2)>1\n    error('PRICEB must be a m by 1 vector.')\nend\nif size(timeB,2)>size(timeB,1)\n    timeB=timeB';\nend\nif any(diff(timeB)<0)\n    error('TIMEB must be sorted and increasing')\nelseif any(diff(timeB)==0)\n    warning('oxfordRealized:realizedPriceFilter','TIMEB contains multiple entries with the same value. This creates an ambiguity and FILTEREDPRICE will contain the last price if TIMEB does not only unique elements.')\nend\nif size(timeB,2)>1 || length(timeB)~=length(priceB)\n    error('TIMEB must be a m by 1 vector.')\nend\n% Inserted to protect against inputing integer times\ntimeB = double(timeB);\n\n% make sure the intersection is non-empty\nif ~(min(timeB)<max(timeA) || min(timeA)<max(timeB))\n    warning('oxfordRealized:realizedHayashiYoshida','The intersection of TIMESA and TIMESB is empty.  The RCHY will necessarily be 0.');\n    intersectionIsEmpty = true;\nelse\n    intersectionIsEmpty = false;\nend\n\n\ntimeType=lower(timeType);\nif ~ismember(timeType,{'wall','seconds','unit'})\n    error('TIMETYPE must be one of ''wall'', ''seconds'' or ''unit''.');\nend\n\nsamplingType=lower(samplingType);\nif ~ismember(samplingType,{'calendartime','calendaruniform','businesstime','businessuniform','fixed'})\n    error('SAMPLINGTYPE must be one of ''CalendarTime'', ''CalendarUniform'', ''BusinessTime'', ''BusinessUniform'' or ''Fixed''.');\nend\n\nm=size(priceA,1);\nt0Original=timeA(1);\ntTOriginal=timeA(m);\nif ismember(samplingType,{'calendartime','calendaruniform','businesstime','businessuniform'})\n    % Must be a scalar integer, unless using unit times\n    if (~isscalar(samplingInterval) || floor(samplingInterval)~=samplingInterval || samplingInterval<1) && ~strcmp(timeType,'unit')\n        error('SAMPLINGINTERVAL must be a positive integer for the SAMPLINGTYPE selected.')\n    end\nelse\n    if size(samplingInterval,2)>size(samplingInterval,1)\n        samplingInterval=samplingInterval';\n    end\n    if ~(any(samplingInterval>=t0Original) && any(samplingInterval<=tTOriginal))\n        error('At least one sampling interval must be between min(TIME) and max(TIME) when using ''Fixed'' as SAMPLINGTYPE.')\n    end\n    if any(diff(samplingInterval)<=0)\n        error('When using ''Fixed'' as SAMPLINGTYPE the vector of sampling times in SAMPLINGINTERVAL must be sorted and strictly increasing.')\n    end\nend\n\nif strcmp(timeType,'unit') && strcmp(samplingType,'calendartime')\n    % samplingInterval must be between 0 and 1\n    if samplingInterval>1\n        error('When TIMETYPE is ''unit'' and SAMPLINGTYPE is ''CalendarTime'', SAMPLINGINTERVAL must also be in ''unit'' terms, and so must be between 0 and 1')\n    end\nend\n\nif nargin==7\n    overlap = 0;\nelseif overlap<0 || floor(overlap)~=overlap || max(size(overlap))>1\n    error('OVERLAP must be a non-negative integer.')\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n% Price A is the base price, price B is the other price.  First sample priceA according to\n% samplingType and samplingInterval, then use the actual times of these to estimate the HY\n% respecting the value in overlap\n\nif ~intersectionIsEmpty\n    % First filter the price\n    [filteredPriceA,filteredTimeA,actualTimeA] = realized_price_filter(priceA,timeA,timeType,samplingType,samplingInterval);\n\n    % Then call the core routine\n    rchy = realized_hayashi_yoshida_core(filteredPriceA,actualTimeA,priceB,timeB,overlap);\nelse\n    rchy = 0;\nend\n\n\n\n\n\nfunction [rchy,times] = realized_hayashi_yoshida_core(priceA,timeA,priceB,timeB,overlap)\n% Core routine for computing the Hayashi-Yoshida estimator of quadratic covariation, and allows for\n% the empirical-performance motivated K-lead-and-lag version similar to Drost and Nijman (1997).\n%\n% USAGE:\n%   [RCHY,TIMES] = realized_hayashi_yoshida_core(PRICEA,TIMEA,PRICEB,TIMEB,OVERLAP)\n%\n% INPUTS:\n%   PRICEA           - mA by 1 vector of high frequency prices\n%   TIMEA            - mA by 1 vector of times where TIMEB(i) corresponds to PRICEA(i)\n%   PRICEA           - mB by 1 vector of high frequency prices\n%   TIMEA            - mB by 1 vector of times where TIMEB(i) corresponds to PRICEB(i)\n%   OVERLAP          - [OPTIONA] Number of ticks to overlap when computing the HY estimator.  The\n%                        original HY estimator uses 0, which corresponds to the maximum likelihood\n%                        estimator for price processes whose observation times are driven by\n%                        independent Poisson processes.  Empirically this estimator performs poorly\n%                        because prices are not a vector semi-martingale and using a larger number\n%                        of lags can alleviate this problem. If omitted OVERLAP = 0.\n%\n% OUTPUTS:\n%   RCHY             - The K-lead-and-lag Hayashi-Yoshida covariance estimator\n%   TIMES            - A mA by 1 matrix of time stamps contains the times where the prices were\n%                        sampled for computing the returns in the HY estimator.  This is mostly for\n%                        diagnostic purposes.\n%\n% COMMENTS:\n%   This is a helper function of realized_hayashi_yoshida and does no input checking.  In general\n%   it should not be directly called.\n%\n%  See also REALIZED_MULTIVARIATE_KERNEL, REALIZED_COVARIANCE, REALIZED_KERNEL, REALIZED_VARIANCE,\n%  REALIZED_RANGE, REALIZED_QUANTILE_VARIANCE\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 5/1/2008\n\npriceA = log(priceA);\npriceB = log(priceB);\ntimeA = double(timeA);\ntimeB = double(timeB);\n% Price A is the base price, price B is the one which will move\n\n% First find the first time that B is available before timeA(1).  If it is empty then find the first\n% timeA(1) which is weakly after the timeB(1)\nnA = size(priceA,1);\nnB = size(priceB,1);\n\nif timeA(1)<timeB(1)\n    % A starts before B, so the easy solution is to project backward the price of the first B to the\n    % time of the first A.  This will generate a 0 return but makes the algorithm easier.\n    timeB=[timeA(1);timeB];\n    priceB=[priceB(1);priceB];\n    nB = size(priceB,1);\nend\n\nif timeA(nA)>timeB(nB)\n    % A ends after B, so the easy solution is to project forward the last price B to the\n    % time of the last A.  This will generate a 0 return but makes the algorithm easier.\n    timeB=[timeB;timeA(nA)];\n    priceB=[priceB;priceB(nB)];\n    nB = size(priceB,1);\nend\n\n\n\n\n% Initialize the indices for A and B\nindexA = 1;\nindexB = find(timeB<=timeA(1), 1,'last');\nif overlap>0\n    indexB = max(indexB-overlap,1); % Make sure that indexB is >= 1\nend\n\n% Initialize rchy and the times\nrchy = 0;\ntimes = zeros(nA-1,4);\nwhile indexA<nA\n    % Get the two prices at indexA and indexA+1\n    pA1 = priceA(indexA);\n    pA2 = priceA(indexA+1);\n    % get the times\n    times(indexA-1,1) = timeA(indexA);\n    times(indexA-1,2) = timeA(indexA+1);\n    % Increment the index to A\n    indexA = indexA+1;\n\n    % Compute the index, including overlap if needed, make sure it doesn't end up before the first\n    % index\n    indexB_minus_overlap = max(indexB - overlap,1);\n    % Get the first price of B\n    pB1 = priceB(indexB_minus_overlap);\n    % Get the time\n    times(indexA-1,3) = timeB(indexB_minus_overlap);\n    while timeB(indexB)<timeA(indexA)\n        % The time stamp of B is strictly less than the time stamp of the second price in the return\n        % to asset A so increment the counter.  Since we do the pre- and post- pend trick above,\n        % there is no need to worry about uneven ending.\n        indexB = indexB + 1;\n    end\n    % Compute the index plus the overlap, make sure it doesn't go outsie the number of obs\n    indexB_plus_overlap = min(indexB + overlap,nB);\n    % Get the second price\n    pB2 = priceB(indexB_plus_overlap);\n    % Get the final time\n    times(indexA-1,4) = timeB(indexB_plus_overlap);\n    % Add to rchy\n    rchy = rchy + (pA2-pA1)*(pB2-pB1);\n\n    % Rewind indexB by 1 since it is now after A\n    if timeB(indexB)>timeA(indexA)\n        indexB = indexB - 1;\n    end\nend\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/realized/realized_hayashi_yoshida.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5992534044337503}}
{"text": "function [idx, frame] = registration_target(frames, useGPU)\n\n%% Parameters\n[ly, lx, nFrames] = size(frames);\ndata = single(frames);\n\nif nargin < 2\n  useGPU = false;\nend\n\n%% Prepare common arrays\n% Taper mask\n[ys, xs] = ndgrid(1:ly, 1:lx);\nys = abs(ys - mean(ys(:)));\nxs = abs(xs - mean(xs(:)));\nmY      = max(ys(:)) - 4;\nmX      = max(xs(:)) - 4;\nslope   = 1.2; % was 2\n\nmaskMul = single(1./(1 + exp((ys - mY)/slope)) ./(1 + exp((xs - mX)/slope)));\nmaskOffset = mean(data(:,:,1))*(1 - maskMul);\n% Smoothing filter in frequency domain\nsigma = 0.76; %.76 with mask\nhgx = exp(-(((0:lx-1) - fix(lx/2))/sigma).^2);\nhgy = exp(-(((0:ly-1) - fix(ly/2))/sigma).^2);\nhg = hgy'*hgx;\nfhg = real(fftn(ifftshift(single(hg/sum(hg(:))))));\n\neps0 = single(1e-20);\nif useGPU\n  data = gpuArray(data);\n%   peakCorrMatrix = zeros(nFrames, nFrames, 'single', 'gpuArray');\n% else\n%   peakCorrMatrix = zeros(nFrames, nFrames, 'single');\nend\n\ncorrRanges = zeros(nFrames, 3, 'single');\n\n[a, b] = ndgrid(1:nFrames, 1:nFrames);\ndata = fft2(bsxfun(@plus, maskOffset, bsxfun(@times, maskMul, data)));\ndata = data./(eps0 + abs(data));\ncdata = conj(data);\nfor fi = 1:nFrames\n  % compute correlation map of frame fi with every other frame\n  cmap = bsxfun(@times, data(:,:,a(:,fi)).*cdata(:,:,b(:,fi)), fhg);\n  cmap = real(ifft2(cmap));\n  % find peak of each correlation map\n  peaks = gather(max(reshape(cmap, ly*lx, nFrames), [], 1));\n  % compute first quartile of peak correlations, ignoring result\n  % from correlation of this frame with itself.\n  corrRanges(fi,:) = prctile(peaks((1:nFrames) ~= fi), [25 50 75]);\nend\n% find the frame with the best correlations with other frames\n[bestCorr, idx] = max(corrRanges(:,1));\n% plot(corrRanges)\nframe = frames(:,:,idx);\n% peakCorrMatrix = gather(peakCorrMatrix);\n% [mxi, idx] = max(prctile(peakCorrMatrix, 25, 1))\n% [mnx, mni] = min(prctile(peakCorrMatrix, 25, 2));\n% figure, imagesc(peakCorrMatrix);\n% figure, plot(1:nFrames, peakCorrMatrix(mxi,:), 1:nFrames, peakCorrMatrix(mni,:))\nend", "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/preRegistration/registration_target.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5992220305713043}}
{"text": "% Set system limits\nlims = mr.opts('MaxGrad',32,'GradUnit','mT/m',...\n    'MaxSlew',130,'SlewUnit','T/m/s',...\n    'rfRingdownTime', 30e-6, 'rfDeadtime', 100e-6);  \n\nseq=mr.Sequence(lims);          % Create a new sequence object\nfov=220e-3; Nx=256; Ny=256;     % Define FOV and resolution\n\nfoe=200e-3;             % Field of excitation\ntargetWidth=22.5e-3;    % Diameter of target excitation pattern\nn=8;                    % Number of spiral turns\nT=8e-3;                 % Pulse duration\n\n\n% Define spiral k-space trajectory\nkMax=(2*n)/foe/2;       % Units of 1/m (not rad/m)\ntk=0:seq.gradRasterTime:T-seq.gradRasterTime;\nkx=kMax*(1-tk/T).*cos(2*pi*n*tk/T);\nky=kMax*(1-tk/T).*sin(2*pi*n*tk/T);\n\n% Define RF pulse\ntr=0:seq.rfRasterTime:T-seq.rfRasterTime;\nkxRf=interp1(tk,kx,tr,'linear','extrap');\nkyRf=interp1(tk,ky,tr,'linear','extrap');\nbeta=2*pi*kMax*targetWidth/2/sqrt(2);  % Gaussian width in k-space\nsignal0 = exp(-beta.^2.*(1-tr/T).^2).*sqrt((2*pi*n*(1-tr/T)).^2+1);\nsignal = signal0.*(1 + exp(-1j.*2*pi*5e-2*(kxRf + kyRf)));\n\n% Add gradient ramps\n[kx,ky,signal]=mr.addRamps({kx,ky},'rf',signal);\n\nrf = mr.makeArbitraryRf(signal,20*pi/180,'system',lims);\ngxRf = mr.makeArbitraryGrad('x',mr.traj2grad(kx));\ngyRf = mr.makeArbitraryGrad('y',mr.traj2grad(ky));\n\n% Define other gradients and ADC events\ndeltak=1/fov;\ngx = mr.makeTrapezoid('x','FlatArea',Nx*deltak,'FlatTime',6.4e-3);\nadc = mr.makeAdc(Nx,'Duration',gx.flatTime,'Delay',gx.riseTime);\ngxPre = mr.makeTrapezoid('x','Area',-gx.area/2,'Duration',2e-3);\nphaseAreas = ((0:Ny-1)-Ny/2)*deltak;\n\n% Refocusing pulse and spoiling gradients\n%[rf180, gz] = mr.makeBlockPulse(pi,'Duration',1e-3,'SliceThickness',5e-3);\n[rf180, gz] = mr.makeSincPulse(pi,'system',lims,'Duration',3e-3,...\n    'SliceThickness',5e-3,'apodization',0.5,'timeBwProduct',4);\n\ngzSpoil = mr.makeTrapezoid('z','Area',gx.area,'Duration',2e-3);\n\n%%% Calculate timing (TE=20ms, TR=500ms)\ndelayTE1=ceil((20e-3/2 - mr.calcDuration(gzSpoil) - mr.calcDuration(rf180)/2)/seq.gradRasterTime)*seq.gradRasterTime;\ndelayTE2=delayTE1 - mr.calcDuration(gxPre) - mr.calcDuration(gx)/2;\ndelayTR=500e-3 - 20e-3 - mr.calcDuration(rf) - mr.calcDuration(gx)/2;\n\n%% Loop over phase encodes and define sequence blocks\nfor i=1:Ny\n    seq.addBlock(rf,gxRf,gyRf);\n    seq.addBlock(mr.makeDelay(delayTE1));\n    seq.addBlock(gzSpoil);\n    seq.addBlock(rf180,gz);\n    seq.addBlock(gzSpoil);\n    seq.addBlock(mr.makeDelay(delayTE2));\n    gyPre = mr.makeTrapezoid('y','Area',phaseAreas(i),'Duration',2e-3);\n    seq.addBlock(gxPre,gyPre);\n    seq.addBlock(gx,adc);\n    seq.addBlock(mr.makeDelay(delayTR));\nend\n\n%% check whether the timing of the sequence is correct\n[ok, error_report]=seq.checkTiming;\n\nif (ok)\n    fprintf('Timing check passed successfully\\n');\nelse\n    fprintf('Timing check failed! Error listing follows:\\n');\n    fprintf([error_report{:}]);\n    fprintf('\\n');\nend\n\n%%\nseq.setDefinition('Name', 'se_selRF');\n\nseq.write('selectiveRf.seq');   % Write to pulseq file\nseq.plot();\n\nreturn\n\n\n%% Write to file\n% The sequence is written to file in compressed form according to the file\n% format specification using the |write| method.\n%seq.setDefinition('Scan_ID',2068);\n%seq.setDefinition('Recon_Mode',1);\n%seq.write('external.seq')\n\n%seq.plot\n\n", "meta": {"author": "pulseq", "repo": "pulseq", "sha": "b4c8fee2a1ffa491d53bd6f507cba2029bf32835", "save_path": "github-repos/MATLAB/pulseq-pulseq", "path": "github-repos/MATLAB/pulseq-pulseq/pulseq-b4c8fee2a1ffa491d53bd6f507cba2029bf32835/matlab/demoSeq/writeSelectiveRf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5992220221736881}}
{"text": "function mags = gtmmag(net, latent_data)\n%GTMMAG\tMagnification factors for a GTM\n%\n%\tDescription\n%\t MAGS = GTMMAG(NET, LATENTDATA) takes a GTM structure NET, and\n%\tcomputes the magnification factors for each point the latent space\n%\tcontained in LATENTDATA.\n%\n%\tSee also\n%\tGTM, GTMPOST, GTMLMEAN\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\nerrstring = consist(net, 'gtm');\nif ~isempty(errstring)\n  error(errstring);\nend\n\nJacs = rbfjacob(net.rbfnet, latent_data);\nnlatent = size(latent_data, 1);\nmags = zeros(nlatent, 1);\ntemp = zeros(net.rbfnet.nin, net.rbfnet.nout);\nfor m = 1:nlatent\n  temp = squeeze(Jacs(m, :, :));  % Turn into a 2d matrix\n  mags(m) = sqrt(det(temp*temp'));\nend\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/gtmmag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5992117945492538}}
{"text": "function [ S, f, Serr ]= mtspectrumc_unequal_length_trials( data, movingwin, params, sMarkers )\n\n% This routine computes the multi-taper spectrum for a given set of unequal length segments. It is\n% based on modifications to the Chronux routines. The segments are continuously structured in the \n% data matrix, with the segment boundaries given by markers. Below,\n% movingwin is used in a non-overlaping way to partition each segment into\n% various windows. Th spectrum is evaluated for each window, and then the\n% window spectrum estimates averaged. Further averaging is conducted by\n% repeating the process for each segment. \n%\n% Inputs: \n%\n%   data = data( samples, channels )- here segments must be stacked\n%   as explained in the email \n%   movingwin = [window winstep] i.e length of moving\n%              window and step size. Note that units here have\n%              to be consistent with units of Fs. If Fs=1 (ie normalized)\n%              then [window winstep]should be in samples, or else if Fs is\n%              unnormalized then they should be in time (secs). \n%   sMarkers = N x 2 array of segment start & stop marks. sMarkers(n, 1) = start\n%           sample index; sMarkers(n,2) = stop sample index for the nth segment\n%   params = see Chronux help on mtspecgramc\n%\n% Output:\n%\n%       S       frequency x channels\n%       f       frequencies x 1\n%       Serr    (error bars) only for err(1)>=1\n%\n%\n\niwAvg = 1; % 0=no weighted average, 1=weighted average\ndebug = 0; % will display intermediate calcs. \n\nif nargin < 2; error('Unequal length trials:: Need data and window parameters'); end;\nif nargin < 3; params=[]; end;\nif isempty( sMarkers ), error( 'Unequal length trials:: Need Markers...' ); end\n[ tapers, pad, Fs, fpass, err, trialave, params ] = getparams( params );\nif nargout > 2 && err(1)==0; \n%   Cannot compute error bars with err(1)=0. change params and run again.\n    error('Unequal length trials:: When Serr is desired, err(1) has to be non-zero.');\nend;\n\n% Set moving window parameters to no-overlapping\nif abs(movingwin(2) - movingwin(1)) >= 1e-6, disp( 'avgSpectrum:: Warming: Window parameters for averaging should be non-overlapping. Set movingwin(2) = movingwin(1).' ); end\n\nwLength = round( Fs * movingwin(1) ); % number of samples in window\nwStep = round( movingwin(2) * Fs ); % number of samples to step through\n\n% Check whether window lengths satify segment length > NW/2\nif ( wLength < 2*tapers(1) ), error( 'avgSpectrum:: movingwin(1) > 2*tapers(1)' ); end\n\n% Left align segment markers for easier coding\nsM = ones( size( sMarkers, 1 ), 2 ); \nsM( :, 2 ) = sMarkers( :, 2 ) - sMarkers( :, 1 ) + 1;\n\n% min-max segments \nNmax = max( sM(:,2) ); Nmin = min( sM(:,2) );\nif ( Nmin < 2*tapers(1) ), error( 'avgSpectrum:: Smallest segment length > 2*tapers(1). Change taper settings' ); end\n\n% max time-sample length will be the window length. \nnfft = 2^( nextpow2( wLength ) + pad );\n[ f, findx ] = getfgrid( Fs, nfft, fpass); \n\n% Precompute all the tapers\nsTapers = tapers;\nsTapers = dpsschk( sTapers, wLength, Fs ); % compute tapers for window length\n\nnChannels = size( data, 2 ); \nnSegments = size( sMarkers, 1 );\n\nif debug\n    disp( ['Window Length = ' num2str(wLength)] );\n    disp( ['Window Step = ' num2str(wStep)] );\n    disp( ' ' );\nend\n\ns = zeros( length(f), nChannels );\nserr = zeros( 2, length(f), nChannels );\nS = zeros( length(f), nChannels );\nSerr = zeros( 2, length(f), nChannels );\nnWins = 0;\nfor sg = 1 : nSegments\n    % Window lengths & steps fixed above\n    % For the given segment, compute the positions & number of windows\n    N = sM(sg,2); \n    wStartPos = 1 : wStep : ( N - wLength + 1 );\n    nWindows = length( wStartPos );\n    if nWindows\n        nWins = nWins + nWindows; % for averaging purposes\n\n        w=zeros(nWindows,2);\n        for n = 1 : nWindows\n            w(n,:) = [ wStartPos(n), (wStartPos(n) + wLength - 1) ]; % nWindows x 2. just like segment end points\n        end\n\n        % Shift window limits back to original sample-stamps\n        w(:, 1) = w(:,1) + (sMarkers( sg, 1 ) - 1);\n        w(:, 2) = w(:,2) + (sMarkers( sg, 1 ) - 1);\n\n        if debug\n            disp( ['Segment Start/Stop = ' num2str( w(1,1) ) ' ' num2str( w(end,2) ) ] );\n            disp( ['Min / Max Window Positions = ' num2str( min(w(:,1)) ) ' ' num2str( max(w(:,1)) ) ] );\n            disp( ['Total Number of Windows = ' num2str(nWindows) ]);\n            disp( ' ' );\n        end\n\n        % Pile up window segments similar to segment pileup\n        wData = zeros( wLength, nChannels, nWindows ); %initialize to avoid fragmentation\n        for n = 1:nWindows\n            %wData( :, :, n ) = detrend( data( w(n,1):w(n,2), : ), 'constant' );\n            wData( :, :, n ) = detrend( data( w(n,1):w(n,2), : ) );\n        end\n\n        % J1 = frequency x taper x nWindows\n        % J2 = frequency x taper x nWindows x nChannels\n        J2 = zeros( length(f), tapers(2), nWindows, nChannels ); J2 = complex( J2, J2 );\n        for c = 1 : nChannels\n            J1 = mtfftc( squeeze(wData( :, c, : )), sTapers, nfft, Fs ); % FFT for the tapered data\n            J2( :, :, :, c ) = J1(findx,:,:);\n        end\n        % J2 = frequency x taper x nWindows x nChannels\n        % Inner mean = Average over tapers => frequency x nWindows x nChannels\n        % Outer mean = Average over windows => frequency x nChannels\n        dim1 = [length(f), nWindows, nChannels];\n        dim2 = [length(f), nChannels];\n        % s = frequency x nChannels\n        s = reshape( squeeze( mean( reshape( squeeze( mean( conj(J2).*J2, 2 ) ), dim1), 2 ) ), dim2 );\n\n        % Now treat the various \"windowed data\" as \"trials\"\n        % serr = 2 x frequency x channels. Output from specerr = 2 x frequency x 1\n        for c = 1 : nChannels\n            serr( :, :, c ) = specerr( squeeze( s(:, c ) ), squeeze( J2(:,:,:, c ) ), err, 1 );\n        end\n        \n        if iwAvg\n            % Segment Weighted error estimates.\n            S = S + nWindows*s;\n            Serr = Serr + nWindows*serr;\n        else\n            S = S + s;\n            Serr = Serr + serr;\n        end\n\n    else\n        if debug, disp(['avgSpectrum:: Zero windows for segment: ' num2str(sg) ]); end\n    end\nend\n\n% Segment Weighted error estimates.\n% Only over those that had non-zero windows\nif nWins && iwAvg\n    S=S/nWins; Serr=Serr/nWins;\nend\nif ~nWins\n    if debug, disp(['avgCoherence:: No segment long enough with movingwin parameters found. Reduce movingwin.' ]); end\nend\n\n\n\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/spectral_analysis/continuous/mtspectrumc_unequal_length_trials.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5992117865136527}}
{"text": "%IM_BDILATION Fixed mapping for binary dilation (DIP_Image)\n%\n%\tB = IM_BDILATION(A,N,CONNECTIVITY,EDGE_CONDITION)\n%\tB = A*IM_BDILATION([],N,CONNECTIVITY,EDGE_CONDITION)\n%\tB = A*IM_BDILATION(N,CONNECTIVITY,EDGE_CONDITION)\n%\n% INPUT\n%   A        Dataset with binary object images dataset (possibly multi-band)\n%   N        Number of iterations (default 1)\n%   CONNECTIVITY    See BDILATION\n%   EDGE_CONDITION  Value of edge, default 0\n%\n% OUTPUT\n%   B        Dataset with dilated images\n%\n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% DATASETS, DATAFILES, DIP_IMAGE, BDILATION\n\n% Copyright: R.P.W. Duin, duin@ph.tn.tudelft.nl\n% Faculty of Applied Physics, Delft University of Technology\n% P.O. Box 5046, 2600 GA Delft, The Netherlands\n\nfunction b = im_bdilation(varargin)\n\n\targin = shiftargin(varargin,'scalar');\n  argin = setdefaults(argin,[],1,-2,0);\n  if mapping_task(argin,'definition')\n    b = define_mapping(argin,'fixed');\n    b = setname(b,'Image dilation');\n  else\n    [a,n,connect,edgecon] = deal(argin{:});\n    if isa(a,'prdataset') % allows datafiles too\n      isobjim(a);\n      b = filtim(a,mfilename,{n,connect,edgecon});\n    elseif isa(a,'double') || isa(a,'dip_image') % here we have a single image\n      if checktoolbox('dipimage')\n        a = dip_image(a,'bin');\n        b = bdilation(a,n,connect,edgecon);\n      else\n        diplibwarn\n        b = bwmorph(a,'dilate',n);\n      end\n    else\n      error('Illegal input')\n    end\n\tend\n\t\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/im_bdilation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.599211780467842}}
{"text": "classdef LIRCMOP1 < PROBLEM\n% <multi> <real> <large/none> <constrained>\n% Constrained benchmark MOP with large infeasible regions\n\n%------------------------------- Reference --------------------------------\n% Z. Fan, W. Li, X. Cai, H. Huang, Y. Fang, Y. You, J. Mo, C. Wei, and E.\n% Goodman, An improved epsilon constraint-handling method in MOEA/D for\n% CMOPs with large infeasible regions, Soft Computing, 2019, 23:\n% 12491-12510.\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 Wenji Li\n    \n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values and constraint violations\n        function Population = Evaluation(obj,varargin)\n            X = varargin{1};\n            X = max(min(X,repmat(obj.upper,size(X,1),1)),repmat(obj.lower,size(X,1),1));\n            x_odd       = X(:,3:2:end);\n            x_even      = X(:,2:2:end);\n            g_1         = sum((x_odd - sin(0.5 * pi * X(:,1))).^2,2);\n            g_2         = sum((x_even - cos(0.5 * pi * X(:,1))).^2,2);\n            PopObj(:,1) = X(:,1) + g_1;\n            PopObj(:,2) = 1 - X(:,1) .^ 2 + g_2;\n            PopCon(:,1) = (0.5 - g_1).*(0.51 - g_1);\n            PopCon(:,2) = (0.5 - g_2).*(0.51 - g_2);\n            Population  = SOLUTION(X,PopObj,PopCon,varargin{2:end});\n            obj.FE      = obj.FE + length(Population);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - R(:,1).^2;\n            R      = R + 0.5;\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R = obj.GetOptimum(100);\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/LIR-CMOP/LIRCMOP1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042218, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5992117798300582}}
{"text": "function segment_length = p07_boundary_segment_length ( segment_index, h )\n\n%*****************************************************************************80\n%\n%% P07_BOUNDARY_SEGMENT_LENGTH returns boundary segment lengths in problem 07.\n%\n%  Discussion:\n%\n%    No attempt has been made here to accurately compute a value of N\n%    which would guarantee that the boundary would be divided into pieces\n%    of length no more than H.  The curve is a little too complicated\n%    to make this easy to do.\n%\n%    Moreover, the points that will be generated will only be equally\n%    spaced in their X argument, not in their arc length.\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 SEGMENT_INDEX, the index of one of the boundary segments.\n%\n%    Input, real H, the suggested spacing between points.\n%\n%    Output, integer SEGMENT_LENGTH, the number of points in the segment.\n%\n  if ( h <= 0.0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'P07_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n    fprintf ( 1, '  Nonpositive H = %f\\n', h );\n    error ( 'P07_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n  end\n\n  if ( segment_index == 1 )\n\n    n = round ( 10.0 * pi / h );\n    n = max ( n, 13 );\n    segment_length = n;\n\n  else\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'P07_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n    fprintf ( 1, '  Illegal SEGMENT_INDEX = %d\\n', segment_index );\n    error ( 'P07_BOUNDARY_SEGMENT_LENGTH - 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/test_triangulation/p07_boundary_segment_length.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.5992117651108622}}
{"text": "close all; clear all; clc;\nrng('default');\n\nA = [3 2; 2 6];\nX = [ 2 1 0 4; \n     -2 2 0 4];\nB = A * X;\n\nsolver = SPX_SteepestDescent(A, B);\nx = solver.solve();\nsolver.printResults();\n\n\n\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/examples/optimization/convex_optimization/steepest_descent/ex_steepest_descent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.599098699540795}}
{"text": "function [oa, pa, K, CM] = USFE_LPP(HSI, Tr, Te, dim, Trees)\n[nx,ny,nz]=size(HSI);\ndata=reshape(HSI,nx*ny,nz);\n[mappedX, mapping] = lpp(data, dim);\nFE_lpp=reshape(mappedX,nx,ny,dim);\n[acc_Mean,acc_std,CM]=RF_ntimes_overal(FE_lpp,Tr,Te,Trees);\npa=acc_Mean(1:dim,1);\noa=acc_Mean(dim+2,1);\nK=acc_Mean(dim+3,1);", "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/USFE_LPP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657177, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5990986902248625}}
{"text": "function [rc,fval,it] = ARjones(ti,xi,rcinit,p)\n\nnobs = length(xi);\n\nopties = optimset('Display','off','TolX',.001/sqrt(nobs),'TolFun',.0001);\n\n[rc_tan,fval,exitflag,output]= fminunc('Jonesfit',tan(.5*pi*rcinit),opties,ti,xi,p);\nrc = 2/pi*atan(rc_tan);\nit = output.iterations;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/18429-armasel-for-irregular-or-missing-data/ARjones.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5990986873432034}}
{"text": "% simple demo to convert a polygon mesh into a voxel representation\n\n% code is 99.99% based on\n% [1] http://www.mathworks.com/matlabcentral/fileexchange/24086-polygon2voxel\n% [2] http://www.mathworks.com/matlabcentral/fileexchange/21044-3d-voxelizer\n\n%   % Compile the c-coded function\n%   mex polygon2voxel_double.c -v\n\nload model;\n\nvertices = vertices - repmat(mean(vertices,1),size(vertices,1),1);\n\nFV.faces = faces;\nFV.vertices = vertices;\n\nVolume=polygon2voxel(FV,[20 20 20],'auto');\n\n%% visualization 1\nfigure\n[X,Y,Z]=ind2sub(size(Volume),find(Volume(:)));\nplot3(X,Y,Z,'.');\naxis equal;\nxlabel('x');\nylabel('y');\nzlabel('z');\n\n%% visualization 2\n% 3d pirnter style visualization to add layer by layer\n\ncareMask =  imdilate((Volume),ones(2,2,2));\nfigure,plot3D(careMask,1,'timed', 0.1)\nhold on;%plot3D(Volume,1,'b','*')\n saveas(gcf,sprintf('/Users/shurans/Dropbox/ModelNet/ECCV2014_sub/MaskVideo/%05d.png',21 ));\nviewA =33:5:176;\nfor i =1:length(viewA)\n    view(viewA(i),28);\n    saveas(gcf,sprintf('/Users/shurans/Dropbox/ModelNet/ECCV2014_sub/MaskVideo/%05d.png',21+i ));\nend\n%%\n%{\n%% visualization 3\nfigure\nfor i=1:size(Volume,1)\n    imagesc(squeeze(Volume(i,:,:)));\n    axis equal;\n    axis tight;\n    axis off\n    title(i);\n    pause(0.1);\nend\n\nfor i=1:size(Volume,2)\n    imagesc(squeeze(Volume(:,i,:)));\n    axis equal;\n    axis tight;\n    axis off\n    title(i);\n    pause(0.1);\nend\n\nfor i=1:size(Volume,3)\n    imagesc(squeeze(Volume(:,:,i)));\n    axis equal;\n    axis tight;\n    axis off\n    title(i);\n    pause(0.1);\nend\n%}", "meta": {"author": "zhirongw", "repo": "3DShapeNets", "sha": "6a6cc71a9231051866092c94486ae967ac533d34", "save_path": "github-repos/MATLAB/zhirongw-3DShapeNets", "path": "github-repos/MATLAB/zhirongw-3DShapeNets/3DShapeNets-6a6cc71a9231051866092c94486ae967ac533d34/voxelization/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5989426221057289}}
{"text": "here=pwd;\ncd /home/bernard/Data/ABC/apascal\nattrs=dlmread('all-perimage.attributes');\nclasses=dlmread('all.classid');\ncd (here);\nclasses=classes+1;\n\nnClasses=length(unique(classes));\n[nInstances, nAttrs]=size(attrs);\n\nclassesAttrs=zeros(nClasses*3,nAttrs);\nclassesCells=cell(1,nClasses);\n\nfor i=1:nInstances\n    class=classes(i);\n    signature=attrs(i,:);\n    classesCells{class}=[classesCells{class}; signature];\nend\ncounter=1;\nfor class=1:nClasses\n    classesAttrs(counter,:)=mean(classesCells{class});\n    classesAttrs(counter+1,:)=mean(classesCells{class})+0.5*std(classesCells{class});\n    classesAttrs(counter+2,:)=mean(classesCells{class})-0.5*std(classesCells{class});\n    counter=counter+3;\nend\n", "meta": {"author": "bernard24", "repo": "Embarrassingly-simple-ZSL", "sha": "700e92b1f7aebaf5a262c061803a789b082cca97", "save_path": "github-repos/MATLAB/bernard24-Embarrassingly-simple-ZSL", "path": "github-repos/MATLAB/bernard24-Embarrassingly-simple-ZSL/Embarrassingly-simple-ZSL-700e92b1f7aebaf5a262c061803a789b082cca97/stkernelaPY/getMinMaxAttributes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5989426133576303}}
{"text": "%% Author: epokh\n%% Website: www.epokh.org/drupy\n%% This software is under GPL\n\nclf\nclear\n%%Cartesian manipulator with an RPY wrist\npx=2.3;\npy=1.7;\npz=7.4;\n\nfia=32;\nfio=178;\nfin=4;\nTcartesian=Tras(px,py,pz);\nTorient=RPY(fia,fio,fin);\n\n%%The trasformation matrix is:\nTend=Tcartesian*Torient;\nfigure(1);\nplot3(0,0,0,'r');\nplotT(Tend);\ntitle('Cartesian manipulator example');\n%%Cylindrical manipulator with an Euler wrist\nTcyl=Tcyl(62,8.2,5.2)*Euler(32,15,17);\nfigure(2);\nplot3(0,0,0,'r');\nplotT(Tcyl);\ntitle('Cylindrical manipulator example');\n%%Spherical maninupaltor with an Euler an RPY wrist\nTsfer=Tsfer(40,50,10)*RPY(10,0,10);\nfigure(3);\nplot3(0,0,0,'r');\nplotT(Tsfer);\ntitle('Spherical manipulator example');\n\n%%Invert the Euler transformation\neuwrist=Euler(32,15,17);\n[fi1,fio,fi2]=invEuler(euwrist);\nfprintf('Invers euler angles %d %d %d \\n',fi1,fio,fi2);\nrpywrist=RPY(5,10,15);\n[fia,fio,fin]=invRPY(rpywrist);\nfprintf('Invers rpy angles %d %d %d \\n',fia,fio,fin);", "meta": {"author": "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/somExamples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5989426089835809}}
{"text": "% The original source code is from https://github.com/zhengliu6699/imageFusionMetrics/blob/master/metricChenBlum.m\n% The interface is modified by the authors of VIFB to integrate it into VIFB. \n\nfunction res=metricsQcb(img1,img2,fused)\n\n    fused = double(fused); \n    img1 = double(img1);\n    img2 = double(img2);\n    % Get the size of img \n    [m,n,b] = size(fused); \n    [m1,n1,b1] = size(img2);\n    \n    if b == 1\n        g = Qcb(img1,img2,fused);\n        res = g;\n    elseif b1 == 1\n        for k = 1 : b \n            g(k) = Qcb(img1(:,:,k),img2,fused(:,:,k)); \n        end \n        res = mean(g);         \n    else    \n        for k = 1 : b \n            g(k) = Qcb(img1(:,:,k),img2(:,:,k),fused(:,:,k)); \n        end \n        res = mean(g); \n    end\n\n\nend\n\nfunction output = Qcb(im1, im2, fused)\n\n    % function res=metricChenBlum(im1,im2,fused)\n    %\n    % This function implements Yin Chen's algorithm for fusion metric.\n    % im1, im2 -- input images;\n    % fused      -- fused image;\n    %\n    % IMPORTANT: The size of the images need to be 2X. \n    % See also: evalu_fusion.m\n    %\n    % Z. Liu [July 2009]    %\n\n    % Ref: A new automated quality assessment algorithm for image fusion, Image and Vision Computing, 27 (2009) 1421-1432 \n    % By Yin Chen et al.\n    % \n\n    im1 = im2double(im1);\n    im2 = im2double(im2);\n    fused = im2double(fused);\n\n    im1=normalize1(im1);\n    im2=normalize1(im2);\n    fused=normalize1(fused);\n\n    %% set up some constant values for experiment\n\n    f0=15.3870;\n    f1=1.3456;\n    a=0.7622;\n\n    % parameters for local constrast computation\n    k=1;\n    h=1;\n    p=3; %2.4;\n    %p=2.4;\n    q=2;\n    Z=0.0001;\n    sigma=2;\n    %% caculate the quality Q\n\n    [hang,lie]=size(im1);\n\n    %DoG filter\n    %DoG1\n    %HH=hang/2; LL=lie/2;\n    HH=hang/30; LL=lie/30;\n\n    %DoG2\n    %HH=hang/4; LL=lie/4;\n\n    %DoG3\n    %HH=hang/8; LL=lie/8;\n\n    [u,v]=freqspace([hang,lie],'meshgrid');\n    u=LL*u; v=HH*v;\n    r=sqrt(u.^2+v.^2);\n\n    Sd=exp(-(r/f0).^2)-a*exp(-(r/f1).^2);\n\n    % constrast sensitivity filtering\n    fused1=ifft2(ifftshift(fftshift(fft2(im1)).*Sd));\n    fused2=ifft2(ifftshift(fftshift(fft2(im2)).*Sd));\n    ffused=ifft2(ifftshift(fftshift(fft2(fused)).*Sd));\n\n    %--------------------\n    %fused1=normalize1(fused1);\n    %fused2=normalize1(fused2);\n    %ffused=normalize1(ffused);\n\n    % local contrast computation\n    % one level of contrast\n    G1=gaussian2d(hang,lie,2);\n    G2=gaussian2d(hang,lie,4);\n\n\n    % filtering in frequency domain\n    C1=contrast(G1,G2,fused1);\n    C1=abs(C1); % I add this. (see your notes)\n    C1P=(k*(C1.^p))./(h*(C1.^q)+Z);\n\n    C2=contrast(G1,G2,fused2);\n    C2=abs(C2); % I add this.\n    C2P=(k*(C2.^p))./(h*(C2.^q)+Z);\n\n    Cf=contrast(G1,G2,ffused);\n    Cf=abs(Cf); % I add this.\n    CfP=(k*(Cf.^p))./(h*(Cf.^q)+Z);\n\n    % contrast preservation calculation\n    mask=(C1P<CfP);\n    mask=double(mask);\n    Q1F=(C1P./CfP).*mask+(CfP./C1P).*(1-mask);\n\n    mask=(C2P<CfP);\n    mask=double(mask);\n    Q2F=(C2P./CfP).*mask+(CfP./C2P).*(1-mask);\n\n    % Saliency map generation\n    ramda1=(C1P.*C1P)./(C1P.*C1P+C2P.*C2P);\n    ramda2=(C2P.*C2P)./(C1P.*C1P+C2P.*C2P);\n\n    % global quality map\n\n    Q=ramda1.*Q1F+ramda2.*Q2F;\n\n    output=mean2(Q);\nend\n\n\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% sub-functions \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction res=gaussian2d(n1,n2,sigma)\n\n% creat a 2D Gaussian filter in spatial domain\n%\n\n% hang (H)-> y; lie (L) -> x\n\nH=floor((n1-1)/2);\nL=floor((n2-1)/2);\n\n\n[x,y]=meshgrid(-15:15,-15:15);\nG=exp(-(x.*x+y.*y)/(2*sigma*sigma))/(2*pi*sigma*sigma);\n\n%This is to normalize\n%G=G/sum(G(:));\nres=G;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction res=contrast(G1,G2,im)\n\n%[hang,lie]=size(im);\n\n%FG1=fft2(G1,hang,lie);\n%FG2=fft2(G2,hang,lie);\n%fused=fft2(im);\n\n%buff=real(ifft2(FG1.*fused));\n%buff1=real(ifft2(FG2.*fused));\n\nbuff=filter2(G1,im,'same');\nbuff1=filter2(G2,im,'same');\n\nres=buff./buff1-1;\nend\n\nfunction RES=normalize1(data)\n\n    % function RES=normalize1(data)\n    %\n    % This function is to NORMALIZE the data. \n    % The data will be in the interval 0-255 (gray level) and pixel value has\n    % been rounded to an integer.\n    % \n    % See also: normalize.m \n    %\n    % Z. Liu @NRCC (Aug 24, 2009)\n\n    data=double(data);\n    da=max(data(:));\n    xiao=min(data(:));\n    if (da==0 & xiao==0)\n        RES=data;\n    else\n        newdata=(data-xiao)/(da-xiao);\n        RES=round(newdata*255);\n    end\nend", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/metrics/metricsQcb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5989426042126131}}
{"text": "function sys = probability(c)\n% PROBABILITY Create basis for chance constraint\n%\n% EXAMPLE:\n% The following example computes the largest value t such that the\n% probability that a zero mean unit variance of a Gaussian variable is\n% larger than t, is larger than 0.9  \n%\n%  w = sdpvar(1,1);\n%  t = sdpvar(1);\n%  Model = [probability(a >= t) >= 0.9,uncertain(a,'normal',0,eye(1))];\n%  solvesdp(derandomize(Model),-t)\n\nif isa(c,'constraint') | isa(c,'lmi')\n    if ~is(c,'elementwise')\n        error('Probability constraints only applicable to single elementwise constraints');\n    else\n        sys.Constraint = c;\n        sys = class(sys,'probability');\n    end\nelse\n    error('Probability constraints only applicable to single elementwise constraints');\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/@probability/probability.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5989426033175598}}
{"text": "function [ftps2] = mGal2ftps2(mGal)\n% Convert acceleration from milligals to feet per second-squared\n% Chad A. Greene 2012\nftps2 = mGal*3.28083333e-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/35258-unit-converters/unit_converters/mGal2ftps2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5989425963595673}}
{"text": "function equalizedData = dfe_frac(data, trainingSymbols, nFTaps, nBTaps, SamplesPerSymbol, Constellation, channelDelay)\n\n\ninputBuffer = zeros(nFTaps,1);\ndecisionBuffer = zeros(nBTaps,1);\n\nforwardTaps = [1; zeros(nFTaps-1,1)];\nbackwardTaps = [zeros(nBTaps,1)];\n\nnumTrainingSymbols = length(trainingSymbols);\n\nind = 0;\nequalizedData = complex(zeros(length(data),1));\nmu = 0.001;\n\nfor s=1:SamplesPerSymbol:length(data)\n    ind = ind + 1;\n    \n    % Add data to buffer\n    inputBuffer = [data(s:s+SamplesPerSymbol-1); inputBuffer(1:end-SamplesPerSymbol)];\n    \n    % Fill equalizer\n    if s<=channelDelay\n        continue\n    end\n    \n    % Apply equalizer\n    eqOut = forwardTaps'*inputBuffer - backwardTaps'*decisionBuffer;\n    \n    % Make decision\n    [~,i] = min(abs(Constellation - eqOut));\n    d = Constellation(i);\n    \n    % Determine error\n    if s<=numTrainingSymbols\n        e = trainingSymbols(ind-channelDelay/SamplesPerSymbol) - eqOut;\n    else\n        e = d - eqOut;\n    end\n    e = conj(e);\n    \n    % Update taps\n    forwardTaps  = forwardTaps  + mu*e*inputBuffer;\n    %backwardTaps = backwardTaps - mu*e*decisionBuffer;\n    \n    % Update decision buffer\n    decisionBuffer = [d; decisionBuffer(1:end-1)];\n    \n    % Output\n    equalizedData(ind) = eqOut;\nend\n%s = channelDelay/SamplesPerSymbol+1;\n%[equalizedData(s:s+100-1), trainingSymbols(1:100), data(s:s+100-1)]\n\nend", "meta": {"author": "analogdevicesinc", "repo": "MathWorks_tools", "sha": "5f8df06d4fc2f4832ed9ec8b722fb750b2261f20", "save_path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools", "path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools/MathWorks_tools-5f8df06d4fc2f4832ed9ec8b722fb750b2261f20/targeting_models/modem-qpsk/FloatingPoint/private/dfe_frac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5988871871023361}}
{"text": "function g = gammaFun(j, k)\n%GAMMAFUN   Get a function handle to a gamma function.\n%   G = GAMMAFUN(J, K) returns a function handle to the gamma function (J, K).\n%\n% See also EXPINTEG/GAMMAEVAL.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Trivial case:\nif ( j == 0 )\n    g = @(z) (exp(k*z) - 1)./z;\n    \n% Compute them recursively using the recurrence formula:\nelse\n    g = @(z) 0*z;\n    for m = 1:j\n        gm = expinteg.gammaFun(j-m, k);\n        g = @(z) g(z) + (-1)^(m-1)/m*gm(z);\n    end\n    if ( j <= k )\n        g = @(z) (g(z) - nchoosek(k, j))./z;\n    else\n        g = @(z) g(z)./z;\n    end\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/@expinteg/gammaFun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5988871824199168}}
{"text": "function plot_Maps4(sFilename)\n%\n%\n%\nload(sFilename)\n\n%% plot results mean z values\ncmin=-4;cmax=4;\nfigure_w_normalized_uicontrolunits('Name','Z-Value','Position',[100 25 400 400]);\nmData=nan(size(median(params.mZ,1, 'omitnan')));\nmData=median(params.mZ,1, 'omitnan');\n% mData=params.mZ;\npcolor(params.vX,params.vY,...\n    reshape(mData,...\n    size(params.vY,1),size(params.vX,1)));\nh=colorbar;\n% set(h,'XAxisLocation','Top','XTick',0.5,'XTickLabel', 'median(z)')\ncolormap(jet);\nxlabel('longitude');\nylabel('latitude');\nshading interp;\nhold on;plot(params.mCatalog(:,1),params.mCatalog(:,2),'k.','MarkerSize',0.5);\nplot_WiemerWyss1994\nxlim([-117.1 -115.6]);\nylim([33 35.2]);\n\n% figure_w_normalized_uicontrolunits('Name','Std Z-Value');\n% mData=nan(size(mean(params.mZ,'omitnan')));\n% mData=std(params.mZ, 'omitnan');\n% pcolor(params.vX,params.vY,...\n%     reshape(mData,...\n%     size(params.vY,1),size(params.vX,1)));\n% h=colorbar;\n% % set(h,'XAxisLocation','Top','XTick',0.5,'XTickLabel', 'std(z)')\n% colormap(jet);\n% xlabel('longitude');\n% ylabel('latitude');\n% shading interp;\n% hold on;plot(params.mCatalog(:,1),params.mCatalog(:,2),'k.','MarkerSize',0.5);\n\n%\n% figure_w_normalized_uicontrolunits('Name','Z-probability by cross-comparison');\n% pcolor(params.vX,params.vY,...\n%     reshape(calc_ProbColorbar2Value(1-params.vPcrZ),...\n%     size(params.vY,1),size(params.vX,1)));\n% plot_ProbColorbar2(cmin, cmax);\n% % set(gca,'XAxisLocation','Top','XTick',0.5,'XTickLabel', 'P(z)')\n%\n% xlabel('longitude');\n% ylabel('latitude');\n% shading interp;\n% hold on;plot(params.mCatalog(:,1),params.mCatalog(:,2),'k.','MarkerSize',0.5);\n% % colorbar\n\n\nfigure_w_normalized_uicontrolunits('Name','Z-probability by overlap','Position',[100 25 400 400]);\npcolor(params.vX,params.vY,...\n    reshape(calc_ProbColorbar2Value(1-params.vPolZ),...\n    size(params.vY,1),size(params.vX,1)));\nxlabel('longitude');\nylabel('latitude');\nplot_ProbColorbar2(cmin, cmax);\n% set(gca,'XAxisLocation','Top','XTick',0.5,'XTickLabel', 'P(z)')\nshading interp;\nhold on;plot(params.mCatalog(:,1),params.mCatalog(:,2),'k.','MarkerSize',0.5);\nplot_WiemerWyss1994\nxlim([-117.1 -115.6]);\nylim([33 35.2]);\n\n%% plot results mean B-values\ncmin=-4;cmax=4;\n% figure_w_normalized_uicontrolunits('Name','Median Beta-Value');\n% mData=nan(size(median(-params.mB, 'omitnan')));\n% mData=median(params.mB, 'omitnan');\n% pcolor(params.vX,params.vY,...\n%     reshape(mData,...\n%     size(params.vY,1),size(params.vX,1)));\n% h=colorbar;\n% % set(h,'XAxisLocation','Top','XTick',0.5,'XTickLabel', 'median(1-B)')\n% colormap(jet);\n% xlabel('longitude');\n% ylabel('latitude');\n% shading interp;\n% hold on;plot(params.mCatalog(:,1),params.mCatalog(:,2),'k.','MarkerSize',0.5);\n%\n% figure_w_normalized_uicontrolunits('Name','Std Beta-Value');\n% mData=nan(size(std(params.mB, 'omitnan')));\n% mData=std(params.mB, 'omitnan');\n% pcolor(params.vX,params.vY,...\n%     reshape(mData,...\n%     size(params.vY,1),size(params.vX,1)));\n% h=colorbar;\n% % set(h,'XAxisLocation','Top','XTick',0.5,'XTickLabel', 'std(1-B)')\n% colormap(jet);\n% xlabel('longitude');\n% ylabel('latitude');\n% shading interp;\n% hold on;plot(params.mCatalog(:,1),params.mCatalog(:,2),'k.','MarkerSize',0.5);\n\n%\n% figure_w_normalized_uicontrolunits('Name','Beta-probability by cross-comparison');\n% pcolor(params.vX,params.vY,...\n%     reshape(calc_ProbColorbar2Value(params.vPcrB),...\n%     size(params.vY,1),size(params.vX,1)));\n% plot_ProbColorbar2(cmin, cmax);\n% % set(gca,'XAxisLocation','Top','XTick',0.5,'XTickLabel', 'P(B)')\n% xlabel('longitude');\n% ylabel('latitude');\n% shading interp;\n% hold on;plot(params.mCatalog(:,1),params.mCatalog(:,2),'k.','MarkerSize',0.5);\n% % colorbar\n\n\nfigure_w_normalized_uicontrolunits('Name','Beta-probability by overlap','Position',[100 25 400 400]);\npcolor(params.vX,params.vY,...\n    reshape(calc_ProbColorbar2Value(params.vPolB),...\n    size(params.vY,1),size(params.vX,1)));\nplot_ProbColorbar2(cmin, cmax);\n% set(gca,'XAxisLocation','Top','XTick',0.5,'XTickLabel', 'P(B)')\nxlabel('longitude');\nylabel('latitude');\nshading interp;\nhold on;plot(params.mCatalog(:,1),params.mCatalog(:,2),'k.','MarkerSize',0.5);\nplot_WiemerWyss1994\nxlim([-117.1 -115.6]);\nylim([33 35.2]);\n\nfigure_w_normalized_uicontrolunits('Name','Resolution','Position',[100 25 400 400]);\npcolor(params.vX,params.vY,...\n    reshape(params.mSamples_,...\n    size(params.vY,1),size(params.vX,1)));\nh=colorbar;\n% set(h,'XAxisLocation','Top','XTick',0.5,'XTickLabel', 'N')\nxlabel('longitude');\nylabel('latitude');\nshading interp;\nhold on;plot(params.mCatalog(:,1),params.mCatalog(:,2),'k.','MarkerSize',0.5);\nplot_WiemerWyss1994\nxlim([-117.1 -115.6]);\nylim([33 35.2]);\n\nend\n\nfunction plot_WiemerWyss1994\nmLatLon=[[-117.1 33];\n    [-115.6 33];\n    [-115.6 35.2];\n    [-117.1 35.2];\n    [-117.1 33]];\nhold on;plot(mLatLon(:,1),mLatLon(:,2),'k--');\nmLanders=[-116.4 34.3];\nhold on;plot(mLanders(1),mLanders(2),'ko','MarkerSize',20)\nend\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/thomas/plot/plot_Maps4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5988871824199167}}
{"text": "function judge = TestIfSO3(mat)\n% *** CHAPTER 3: RIGID-BODY MOTIONS ***\n% Takes mat: A 3x3 matrix.\n% Check if mat is close to or on the manifold SO(3).\n% Example Inputs:\n% \n% clear; clc;\n% mat = [1.0, 0.0,   0.0;\n%        0.0, 0.1, -0.95;\n%        0.0, 1.0,   0.1];\n% judge = TestIfSO3(mat)\n% \n% Output:\n% dudge =\n%     0\n\njudge = norm(DistanceToSO3(mat)) < 1e-3;\nend", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/mr/TestIfSO3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5988871815569917}}
{"text": "function [lat, lon, gam, k] = utm_inv(zone, northp, x, y)\n%UTM_INV  Forward transverse Mercator projection\n%\n%   [LAT, LON] = UTM_INV(ZONE, NORTHP, X, Y)\n%   [LAT, LON, GAM, K] = UTM_INV(ZONE, NORTHP, X, Y)\n%\n%   performs the inverse universal transverse Mercator projection of points\n%   (X,Y) to (LAT,LON) using ZONE and NORTHP.  X and Y can be scalars or\n%   arrays of equal size.  ZONE should be an integer in [1,60] and NORTHP\n%   is a logical indicating whether the transformation should use the false\n%   northing for the northern (NORTHP = true) or southern (NORTHP = false)\n%   hemisphere.  The forward projection is given by UTM_FWD.\n%\n%   GAM and K give metric properties of the projection at (LAT,LON); GAM is\n%   the meridian convergence at the point and K is the scale.\n%\n%   LAT, LON, GAM are in degrees.  The projected coordinates X, Y are in\n%   meters.  K is dimensionless.\n%\n%   This implementation for the UTM projection is based on the series\n%   method described in\n%\n%     C. F. F. Karney, Transverse Mercator with an accuracy of a few\n%     nanometers, J. Geodesy 85(8), 475-485 (Aug. 2011);\n%     Addenda: http://geographiclib.sf.net/tm-addenda.html\n%\n%   This extends the series given by Krueger (1912) to sixth order in the\n%   flattening.  This is a substantially better series than that used by\n%   the MATLAB mapping toolbox.  In particular the errors in the projection\n%   are less than 5 nanometers withing 3900 km of the central meridian (and\n%   less than 1 mm within 7600 km of the central meridian).  The mapping\n%   can be continued accurately over the poles to the opposite meridian.\n%\n%   This routine depends on the MATLAB File Exchange package \"Geodesics on\n%   an ellipsoid of revolution\":\n%\n%     http://www.mathworks.com/matlabcentral/fileexchange/39108\n%\n%   See also GEODPROJ, UTM_FWD, TRANMERC_INV.\n\n% Copyright (c) Charles Karney (2012) <charles@karney.com>.\n%\n% This file was distributed with GeographicLib 1.29.\n\n  if nargin < 4, error('Too few input arguments'), end\n  lon0 = -183 + 6 * zone; lat0 = 0;\n  fe = 500e3; fn = cvmgt(0, 10000e3, logical(northp)); k0 = 0.9996;\n  x = (x - fe) / k0; y = (y - fn) / k0;\n  [lat, lon, gam, k] = tranmerc_inv(lat0, lon0, x, y);\n  k = k * k0;\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/39366-geodesic-projections-for-an-ellipsoid/geographiclib-matlab/utm_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5988871768745724}}
{"text": "function D = driving_function_mono_nfchoa_ps(x0,xs,f,N,conf)\n%DRIVING_FUNCTION_MONO_NFCHOA_PS driving signal for a point source in NFC-HOA\n%\n%   Usage: D = driving_function_mono_nfchoa_ps(x0,xs,f,N,conf)\n%\n%   Input parameters:\n%       x0          - position of the secondary sources / m [nx3]\n%       xs          - position of virtual point source / m [nx3]\n%       f           - frequency of the monochromatic source / Hz\n%       N           - maximum order of spherical harmonics\n%       conf        - configuration struct (see SFS_config)\n%\n%   Output parameters:\n%       D           - driving function signal [nx1]\n%\n%   See also: driving_function_mono_nfchoa, driving_function_imp_nfchoa_ps\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 = 5;\nnargmax = 5;\nnarginchk(nargmin,nargmax);\nisargmatrix(x0,xs);\nisargpositivescalar(f,N);\nisargstruct(conf);\n\n\n%% ===== Configuration ==================================================\nxref = conf.xref;\nc = conf.c;\ndimension = conf.dimension;\ndriving_functions = conf.driving_functions;\nX0 = conf.secondary_sources.center;\n\n\n%% ===== Computation ====================================================\n\n% Secondary source positions\nx00 = bsxfun(@minus,x0,X0);\n[phi0,theta0,r0] = cart2sph(x00(:,1),x00(:,2),x00(:,3));\n\n% Point source\nxs0 = bsxfun(@minus,xs,X0);\n[phi,theta,r] = cart2sph(xs0(:,1),xs0(:,2),xs0(:,3));\n\n% Wavenumber\nomega = 2*pi*f;\n\n% modal window\nwin = modal_weighting(N,conf);\n\n% Initialize empty driving signal\nD = zeros(size(x0,1),1);\n\nif strcmp('2D',dimension)\n\n    % === 2-Dimensional ==================================================\n\n    switch driving_functions\n    case 'default'\n        % --- SFS Toolbox ------------------------------------------------\n        to_be_implemented;\n    otherwise\n        error(['%s: %s, this type of driving function is not implemented ', ...\n            'for a 2D point source.'],upper(mfilename),driving_functions);\n    end\n\n\nelseif strcmp('2.5D',dimension)\n\n    % === 2.5-Dimensional ================================================\n\n    % Reference point\n    xref = repmat(xref,[size(x0,1) 1]);\n\n    switch driving_functions\n    case 'default'\n        % --- SFS Toolbox ------------------------------------------------\n        % 2.5D point source\n        %\n        %                     _N_    (2)\n        %               1     \\     h|m|(w/c r)\n        % D(phi0,w) = ------  /__  ------------- e^(i m (phi0-phi))\n        %             2pi r0  m=-N   (2)\n        %                           h|m|(w/c r0)\n        %\n        % https://sfs.rtfd.io/en/3.2/d_nfchoa/#equation-fd-nfchoa-point-25d\n        for m=-N:N\n            D = D + 1 ./ (2.*pi.*r0) ...\n                .* win(abs(m)+1) ...\n                .* sphbesselh(abs(m),2,omega./c.*r) ...\n                ./ sphbesselh(abs(m),2,omega./c.*r0) ...\n                .* exp(1i.*m.*(phi0-phi));\n        end\n    otherwise\n        error(['%s: %s, this type of driving function is not implemented ', ...\n            'for a 2.5D point source.'],upper(mfilename),driving_functions);\n    end\n\n\nelseif strcmp('3D',dimension)\n\n    % === 3-Dimensional ==================================================\n\n    switch driving_functions\n    case 'default'\n        % --- SFS Toolbox ------------------------------------------------\n        % 3D point source\n        %\n        %                              _N_  _n_   (2)\n        %                       1      \\    \\    hn(w/c r)   -m\n        % D(theta0,phi0,w) = -------   /__  /__ ----------- Yn(theta,phi) ...\n        %                    2pi r0^2  n=0 m=-n   (2)\n        %                                        hn(w/c r0)\n        %                       m\n        %                    x Yn(theta0,phi0)\n        %\n        % https://sfs.rtfd.io/en/3.2/d_nfchoa/#equation-fd-nfchoa-point-3d\n        %\n        for n=0:N\n            for m=-n:n\n                D = D + 1 ./ (2.*pi.*r0.^2) ...\n                    .* win(n+1) ...\n                    .* sphbesselh(n,2,omega./c.*r) ...\n                    ./ sphbesselh(n,2,omega./c.*r0) ...\n                    .* sphharmonics(n,-m,theta,phi) ...\n                    .* sphharmonics(n,m,theta0,phi0);\n            end\n        end\n    otherwise\n        error(['%s: %s, this type of driving function is not implemented ', ...\n            'for a 3D point source.'],upper(mfilename),driving_functions);\n    end\n\nelse\n    error('%s: the dimension %s is unknown.',upper(mfilename),dimension);\nend\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_monochromatic/driving_functions_mono/driving_function_mono_nfchoa_ps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5988871753962872}}
{"text": "%\n% A variational approach to SPCP (Aravkin et al. 2014)\n%\n% RPCA | SPCP-sum-SPG | Stable PCP-sum solved by Spectral Projected Gradient (Aravkin et al. 2014)\n% process_video('RPCA', 'flip-SPCP-sum-SPG', 'dataset/demo.avi', 'output/demo_flip-SPCP-sum-SPG.avi');\n\nalg_path_aux = fullfile(lrs_conf.rpca_path,'SPGL1');\naddpath(genpath(alg_path_aux));\n\nnFrames     = size(M,2);\nlambda      = 1/sqrt(max(size(M,1),size(M,2)));\nL0          = repmat(median(M,2), 1, nFrames);\nS0          = M - L0;\nepsilon     = 5e-3*norm(M,'fro'); % tolerance for fidelity to data\n\n% Flip-Flop version of SPCP-sum solved by Spectral Projected Gradient\nopts = struct('sum',true,'L0',L0,'S0',S0,'max',false,...\n  'tau0',3e5,'SPGL1_tol',1e-1,'tol',1e-3);\n[L,S] = solver_RPCA_SPGL1(M,lambda,epsilon,[],opts);\n\nrmpath(genpath(alg_path_aux));", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/flip-SPCP-sum-SPG/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5988871619643888}}
{"text": "classdef CommunityDetection < PROBLEM\n% <single> <label> <large/none> <expensive/none>\n% The community detection problem with label based encoding\n% dataNo --- 1 --- Number of dataset\n\n%------------------------------- Reference --------------------------------\n% Y. Tian, S. Yang, and X. Zhang, An evolutionary multiobjective\n% optimization based fuzzy method for overlapping community detection, IEEE\n% Transactions on Fuzzy Systems, 2020, 28(11): 2841-2855.\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% The datasets are taken from\n% http://www-personal.umich.edu/~mejn/netdata/\n% No.   Name        Nodes   Edges\n% 1     Karate      34      78\n% 2     Dolphin     62      159\n% 3     Polbook     105     441\n% 4     Football    115     613\n\n    properties(Access = private)\n        Adj;    % Adjacency matrix of the network\n        G;      % The graph object\n    end\n    methods\n    \t%% Default settings of the problem\n        function Setting(obj)\n            % Load data\n            dataNo    = obj.ParameterSet(1);\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'Dataset_CD.mat'),'Dataset');\n            str     = {'Karate','Dolphin','Polbook','Football'};\n            obj.Adj = Dataset.(str{dataNo});\n            obj.G   = graph(obj.Adj);\n            % Parameter setting\n            obj.M = 1;\n            obj.D = size(obj.Adj,2);\n            obj.lower    = 1     + zeros(1,obj.D);\n            obj.upper    = obj.D + zeros(1,obj.D);\n            obj.encoding = 3     + zeros(1,obj.D);\n        end\n        %% Repair invalid solutions\n        function PopDec = CalDec(obj,PopDec)\n            for i = 1 : size(PopDec,1)\n                P = zeros(1,obj.D);\n                while ~all(P)\n                    x = find(~P,1);\n                    P(PopDec(i,:)==PopDec(i,x)) = max(P) + 1;\n                end\n                PopDec(i,:) = P;\n            end\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            PopObj = zeros(size(PopDec,1),1);\n            for i = 1 : size(PopObj,1)\n                PopObj(i) = 1 - Modularity(obj.Adj,Decoding(PopDec(i,:)));\n            end\n        end\n        %% Display a population in the decision space\n        function DrawDec(obj,Population)\n            [~,best] = min(Population.objs);\n            C = Decoding(Population(best).dec);\n            h = plot(Draw([]),obj.G,'MarkerSize',6,'EdgeColor',[.3 .3 .3]);\n            tempStream = RandStream('mlfg6331_64','Seed',2);\n            for i = 1 : length(C)\n                highlight(h,C{i},'NodeColor',rand(tempStream,1,3));\n            end\n        end\n    end\nend\n\nfunction Community = Decoding(Dec)\n    Community = {};\n    while any(Dec)\n        current      = find(Dec==Dec(find(Dec,1)));\n        Community    = [Community,current];\n        Dec(current) = 0;\n    end\nend\n\nfunction Q = Modularity(Adj,C)\n    Q = 0;\n    M = sum(sum(Adj))/2;\n    for i = 1 : length(C)\n        Q = Q + sum(sum(Adj(C{i},C{i})))/2/M - (sum(sum(Adj(C{i},:)))/2/M)^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/Problems/Single-objective optimization/Real-world SOPs/CommunityDetection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5988223923537238}}
{"text": "function [Population,Dec,Mask,FrontNo,CrowdDis] = SPEA2_EnvironmentalSelection(Population,Dec,Mask,N)\n% The environmental selection of MSKEA\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 Lei Chen\n\n    %% Delete duplicated solutions\n    [~,uni] = unique(Population.objs,'rows');\n    Population = Population(uni);\n    Dec        = Dec(uni,:);\n    Mask       = Mask(uni,:);\n    N          = min(N,length(Population));\n    %% Calculate the fitness of each solution\n    \n    [FrontNo,MaxFNo] = NDSort(Population.objs,N);\n    Next = false(1,length(FrontNo));\n    Next(FrontNo<MaxFNo) = true;\n    \n    PopObj = Population.objs;\n    fmax   = max(PopObj(FrontNo==1,:),[],1);\n    fmin   = min(PopObj(FrontNo==1,:),[],1);\n    PopObj = (PopObj-repmat(fmin,size(PopObj,1),1))./repmat(fmax-fmin,size(PopObj,1),1);\n\n    %% Environmental selection\n    Last = find(FrontNo==MaxFNo);\n    del  = Truncation(PopObj(Last,:),length(Last)-N+sum(Next));\n    Next(Last(~del)) = true;\n    % Population for next generation\n    Population = Population(Next);\n    Dec        = Dec(Next,:);\n    Mask       = Mask(Next,:);\n    FrontNo    = FrontNo(Next);\n    CrowdDis = CrowdingDistance(Population.objs,FrontNo);\nend\n\nfunction Del = Truncation(PopObj,K)\n% Select part of the solutions by truncation\n\n    %% Truncation\n    Distance = pdist2(PopObj,PopObj);\n    Distance(logical(eye(length(Distance)))) = inf;\n    Del = false(1,size(PopObj,1));\n    while sum(Del) < K\n        Remain   = find(~Del);\n        Temp     = sort(Distance(Remain,Remain),2);\n        [~,Rank] = sortrows(Temp);\n        Del(Remain(Rank(1))) = true;\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/MSKEA/SPEA2_EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5988223813825979}}
{"text": "clear, clc;\n\n% This is an example for running the function LogisticC\n%\n%  Problem:\n%\n%  min  f(x,c) = - weight_i * log (p_i) + 1/2 * rsL2 * ||x||_2^2\n%  s.t. \\|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% For detailed description of the function, please refer to the Manual.\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% [3]  Jun Liu, Jianhui Chen, and Jieping Ye, \n%      Large-Scale Sparse Logistic Regression, KDD, 2009.\n%\n%% ------------   History --------------------\n%\n% First version on August 10, 2009.\n%\n% September 5, 2009: adaptive line search is added\n%\n% For any problem, please contact Jun Liu (j.liu@asu.edu)\n\ncd ..\ncd ..\n\nroot=cd;\naddpath(genpath([root '/SLEP']));\n                     % add the functions in the folder SLEP to the path\n                   \n% change to the original folder\ncd Examples/L1;\n\nm=1000;  n=1000;    % The data matrix is of size m x n\n\nrandNum=1;          % a random number\n\n% ---------------------- generate random data ----------------------\nrandn('state',(randNum-1)*3+1);\nA=randn(m,n);         % the data matrix\n\ny=[ones(n/2,1);...\n    -ones(n/2, 1)];  % the response\n\nz=40;                % the radius of the L1 ball\n\n%----------------------- Set optional items -----------------------\nopts=[];\n\n% Starting point\nopts.init=2;        % starting from a zero point\n\n% Termination \nopts.tFlag=5;       % run .maxIter iterations\nopts.maxIter=40;    % maximum number of iterations\n\n% Normalization\nopts.nFlag=0;       % without normalization\n\n% Regularization\nopts.rsL2=0;        % the squared two norm term\n\n% Group Property\nopts.sWeight=[1,1]; % set the weight for positive and negative samples\n\n%----------------------- Run the code LogisticC -----------------------\nfprintf('\\n lFlag=0 \\n');\nopts.lFlag=0;       % Nemirovski's line search\ntic;\n[x1, c1,funVal1, ValueL1]= LogisticC(A, y, z, opts);\ntoc;\n\nfprintf('\\n lFlag=1 \\n');\nopts.lFlag=1;       % adaptive line search\nopts.tFlag=2; opts.tol= funVal1(end);\ntic;\n[x2, c2, funVal2, ValueL2]= LogisticC(A, y, z, opts);\ntoc;\n\nfigure;\nplot(funVal1,'-r');\nhold on;\nplot(funVal2,'--b');\nlegend('lFlag=0', 'lFlag=1');\nxlabel('Iteration (i)');\nylabel('The objective function value');\n\n% --------------------- compute the pathwise solutions ----------------\nopts.fName='LogisticC';      % set the function name to 'LogisticC'\nZ=[10, 20, 30, 40];          % set the parameters\n\n% run the function pathSolutionLogistic\nfprintf('\\n Compute the pathwise solutions, please wait...');\n[X,C]=pathSolutionLogistic(A, y, Z, opts);", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Toolbox/SLEP_package_4.1/Examples/L1/example_LogisticC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5988223763605497}}
{"text": "function [ev,ee,ebound,xyp] = q1p0grid(x,y,xy,mv,bound,mbound);\n%q1p0grid   Q1-P0 element grid generator\n%   [ev,ee,ebound,xyp] = q1p0grid(x,y,xy,mv,bound,mbound);\n%   input\n%          x          x coordinate vector\n%          y          y coordinate vector \n%          xy         nodal coordinate vector  \n%          mv         Q2 macroelement mapping matrix\n%          bound      boundary vertex vector\n%          mbound     macroelement boundary vertex vector\n%   output       \n%          ev         element vertex matrix\n%          ee         element edge connection matrix\n%          ebound     element boundary edge matrix   \n%          xyp        vertex coordinate vector\n%\n%   IFISS function: DJS; 28 February 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nxx=xy(:,1); yy=xy(:,2); nvtx=length(xx);\nadj=sparse(nvtx,nvtx);\nmel=length(mv(:,1)); nel=4*mel;\nev=zeros(nel,4);\n%\n%% loop over macroelements\nk=1:mel;\n% first element\nke=4*k-3;\nev(ke,1)=mv(k,1);\nev(ke,2)=mv(k,5);\nev(ke,3)=mv(k,9);\nev(ke,4)=mv(k,8);\n% second element\nke=4*k-2;\nev(ke,1)=mv(k,5);\nev(ke,2)=mv(k,2);\nev(ke,3)=mv(k,6);\nev(ke,4)=mv(k,9);\n% third element\nke=4*k-1;\nev(ke,1)=mv(k,9);\nev(ke,2)=mv(k,6);\nev(ke,3)=mv(k,3);\nev(ke,4)=mv(k,7);\n% fourth element\nke=4*k;\nev(ke,1)=mv(k,8);\nev(ke,2)=mv(k,9);\nev(ke,3)=mv(k,7);\nev(ke,4)=mv(k,4);\n%\n%% define element edges\nect=1;\n% bottom boundary edges\nk1=find(mbound(:,2)==1)';\nfor k=mbound(k1)\n   ebound(ect,1)=4*k-3; ebound(ect+1,1)=4*k-2; \n   ebound(ect,2)=1    ; ebound(ect+1,2)=1;\n   ect=ect+2;\nend\n% right boundary edges\nk2=find(mbound(:,2)==2)';\nfor k=mbound(k2)\n   ebound(ect,1)=4*k-2; ebound(ect+1,1)=4*k-1; \n   ebound(ect,2)=2    ; ebound(ect+1,2)=2;\n   ect=ect+2;\nend\n% top boundary edges\nk3=find(mbound(:,2)==3)';\nfor k=mbound(k3)\n   ebound(ect,1)=4*k-1; ebound(ect+1,1)=4*k; \n   ebound(ect,2)=3    ; ebound(ect+1,2)=3;\n   ect=ect+2;\nend\n% left boundary edges\nk4=find(mbound(:,2)==4)';\nfor k=mbound(k4)\n   ebound(ect,1)=4*k; ebound(ect+1,1)=4*k-3; \n   ebound(ect,2)=4    ; ebound(ect+1,2)=4;\n   ect=ect+2;\nend\n%%\n% centroid coordinates\nfor ielem=1:nel\nxc(ielem)=mean(xx(ev(ielem,:))); yc(ielem)=mean(yy(ev(ielem,:)));\nend\nxyp=[xc',yc'];\n%\n%% compute edge to edge connection array ee \n      np=nel;\n% initialise global matrices\n      adj = sparse(nvtx,nvtx); \n      ee = zeros(nel,4);\n%\n% evaluate element number on each edge in turn\n% and assemble into adjacency matrix \n%% nx= 0, ny=-1  \n\t\t adj=adj + sparse(ev(:,1),ev(:,2),1:np,nvtx,nvtx);  \n%% nx= 1, ny= 0\n\t\t adj=adj + sparse(ev(:,2),ev(:,3),1:np,nvtx,nvtx); \n%% nx= 0, ny= 1       \n\t\t adj=adj + sparse(ev(:,3),ev(:,4),1:np,nvtx,nvtx); \n%% nx=-1, ny= 0\n\t\t adj=adj + sparse(ev(:,4),ev(:,1),1:np,nvtx,nvtx); \n%\n       for el=1:nel\n\t\t   [ii,jj]=find(adj==el);\n           ee(el,:)=diag(adj(jj,ii))';\n\t\t   end\n           ee=ee(:,[2,4,3,1]);\n%\n% plotting of the grid \n%\n%if mel <=64,\n\tadj=sparse(nvtx,nvtx);\n    for i=1:nel\n\tadj(ev(i,1),ev(i,2)) =1;\n\tadj(ev(i,2),ev(i,3)) =1;\n\tadj(ev(i,3),ev(i,4)) =1;\n\tadj(ev(i,4),ev(i,1)) =1;\n    end\n    figure(30)\n    gplot(adj,xy,'b')\n    axis('square')\n    hold on\n    adj=sparse(nvtx,nvtx);\n    k1=find(ebound(:,2)==1);\n    for k=1:length(k1)\n    kk=ebound(k1(k));\n    adj(ev(kk,1),ev(kk,2))=1;\n    end\n    k2=find(ebound(:,2)==2);\n    for k=1:length(k2)\n    kk=ebound(k2(k));\n    adj(ev(kk,2),ev(kk,3))=1;\n    end\n    k3=find(ebound(:,2)==3);\n    for k=1:length(k3)\n    kk=ebound(k3(k));\n    adj(ev(kk,3),ev(kk,4))=1;\n    end\n    k4=find(ebound(:,2)==4);\n    for k=1:length(k4)\n    kk=ebound(k4(k));\n    adj(ev(kk,4),ev(kk,1))=1;\n    end\n%   gplot(adj,xy,'r')\n%   axis('off')\nplot(xy(:,1),xy(:,2),'ro')\nxybd=xy(bound,:);\nplot(xybd(:,1),xybd(:,2),'ko')\nplot(xyp(:,1),xyp(:,2),'k*')\nhold off\ndrawnow\ntitle('Q1-P0 finite element subdivision')\n%end\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/grids/q1p0grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5988223644623938}}
{"text": "function y = trace_inv( varargin )\n\n% TRACE_INV   Trace of the inverse of a PSD matrix.\n%     For square matrix X, TRACE_INV(X) is TRACE(INV(X)) if X is Hermitian\n%     or symmetric and positive definite; and +Inf otherwise. \n%\n%     An error results if X is not a square matrix.\n%\n%     Disciplined convex programming information:\n%         TRACE_INV is convex and nonmonotonic (at least with respect to\n%         elementwise comparison), so its argument must be affine.\n\npersistent P\nif isempty( P ),\n    P.nargs     = 1;\n    P.args      = [];\n    P.empty     = 0;\n    P.constant  = @trace_inv_diag;\n    P.diagonal  = @trace_inv_diag;\n    P.affine    = @trace_inv_aff;\n    P.structure = 'psdeig';\nend\ny = cvx_matrix_op( P, varargin );\n\nfunction z = trace_inv_diag( D )\nz = sum( 1.0 ./ D );\n\nfunction z = trace_inv_aff( X ) %#ok\ncvx_begin sdp\n    epigraph variable z nonnegative_\n    variable Y(size(X)) hermitian_if(X)\n    real(trace(Y)) <= z;\n    [Y,eye(size(X));eye(size(X)),X] >= 0; %#ok\ncvx_end\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/trace_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5988088760983319}}
{"text": "function [label, model, L] = vbgm(X, init, prior)\n% Perform variational Bayesian inference for Gaussian mixture.\n%   X: d x n data matrix\n%   init: k (1 x 1) or label (1 x n, 1<=label(i)<=k) or center (d x k)\n% Reference: Pattern Recognition and Machine Learning by Christopher M. Bishop (P.474)\n% Written by Michael Chen (sth4nth@gmail.com).\n\nfprintf('Variational Bayesian Gaussian mixture: running ... \\n');\n[d,n] = size(X);\nif nargin < 3\n    prior.alpha = 1;\n    prior.kappa = 1;\n    prior.m = mean(X,2);\n    prior.v = d+1;\n    prior.M = eye(d);   % M = inv(W)\nend\ntol = 1e-20;\nmaxiter = 2000;\nL = -inf(1,maxiter);\nconverged = false;\nt = 1;\n\nmodel.R = initialization(X,init);\nwhile  ~converged && t < maxiter\n    t = t+1;\n    model = vmax(X, model, prior);\n    model = vexp(X, model);\n    L(t) = vbound(X,model,prior)/n;\n    converged = abs(L(t)-L(t-1)) < tol*abs(L(t));\nend\nL = L(2:t);\nlabel = zeros(1,n);\n[~,label(:)] = max(model.R,[],2);\n[~,~,label] = unique(label);\nif converged\n    fprintf('Converged in %d steps.\\n',t-1);\nelse\n    fprintf('Not converged in %d steps.\\n',maxiter);\nend\n\nfunction R = initialization(X, init)\n[d,n] = size(X);\nif length(init) == 1  % random initialization\n    k = init;\n    idx = randsample(n,k);\n    m = X(:,idx);\n    [~,label] = max(bsxfun(@minus,m'*X,dot(m,m,1)'/2),[],1);\n    [u,~,label] = unique(label);\n    while k ~= length(u)\n        idx = randsample(n,k);\n        m = X(:,idx);\n        [~,label] = max(bsxfun(@minus,m'*X,dot(m,m,1)'/2),[],1);\n        [u,~,label] = unique(label);\n    end\n    R = full(sparse(1:n,label,1,n,k,n));\nelseif size(init,1) == 1 && size(init,2) == n  % initialize with labels\n    label = init;\n    k = max(label);\n    R = full(sparse(1:n,label,1,n,k,n));\nelseif size(init,1) == d  %initialize with only centers\n    k = size(init,2);\n    m = init;\n    [~,label] = max(bsxfun(@minus,m'*X,dot(m,m,1)'/2),[],1);\n    R = full(sparse(1:n,label,1,n,k,n));\nelse\n    error('ERROR: init is not valid.');\nend\n% Done\nfunction model = vmax(X, model, prior)\nalpha0 = prior.alpha;\nkappa0 = prior.kappa;\nm0 = prior.m;\nv0 = prior.v;\nM0 = prior.M;\nR = model.R;\n\nnk = sum(R,1); % 10.51\nalpha = alpha0+nk; % 10.58\nnxbar = X*R;\nkappa = kappa0+nk; % 10.60\nm = bsxfun(@times,bsxfun(@plus,kappa0*m0,nxbar),1./kappa); % 10.61\nv = v0+nk; % 10.63\n\n[d,k] = size(m);\nM = zeros(d,d,k); \nsqrtR = sqrt(R);\n\nxbar = bsxfun(@times,nxbar,1./nk); % 10.52\nxbarm0 = bsxfun(@minus,xbar,m0);\nw = (kappa0*nk./(kappa0+nk));\nfor i = 1:k\n    Xs = bsxfun(@times,bsxfun(@minus,X,xbar(:,i)),sqrtR(:,i)');\n    xbarm0i = xbarm0(:,i);\n    M(:,:,i) = M0+Xs*Xs'+w(i)*(xbarm0i*xbarm0i'); % 10.62\nend\n\nmodel.alpha = alpha;\nmodel.kappa = kappa;\nmodel.m = m;\nmodel.v = v;\nmodel.M = M; % Whishart: M = inv(W)\n% Done\nfunction model = vexp(X, model)\nalpha = model.alpha; % Dirichlet\nkappa = model.kappa;   % Gaussian\nm = model.m;         % Gasusian\nv = model.v;         % Whishart\nM = model.M;         % Whishart: inv(W) = V'*V\n\nn = size(X,2);\n[d,k] = size(m);\n\nlogW = zeros(1,k);\nEQ = zeros(n,k);\nfor i = 1:k\n    U = chol(M(:,:,i));\n    logW(i) = -2*sum(log(diag(U)));      \n    Q = (U'\\bsxfun(@minus,X,m(:,i)));\n    EQ(:,i) = d/kappa(i)+v(i)*dot(Q,Q,1);    % 10.64\nend\n\nElogLambda = sum(psi(0,bsxfun(@minus,v+1,(1:d)')/2),1)+d*log(2)+logW; % 10.65\nElogpi = psi(0,alpha)-psi(0,sum(alpha)); % 10.66\n\nlogRho = (bsxfun(@minus,EQ,2*Elogpi+ElogLambda-d*log(2*pi)))/(-2); % 10.46\nlogR = bsxfun(@minus,logRho,logsumexp(logRho,2)); % 10.49\nR = exp(logR);\n\nmodel.logR = logR;\nmodel.R = R;\n% Done\nfunction L = vbound(X, model, prior)\nalpha0 = prior.alpha;\nkappa0 = prior.kappa;\nm0 = prior.m;\nv0 = prior.v;\nM0 = prior.M;\n\nalpha = model.alpha; % Dirichlet\nkappa = model.kappa;   % Gaussian\nm = model.m;         % Gasusian\nv = model.v;         % Whishart\nM = model.M;         % Whishart: inv(W) = V'*V\nR = model.R;\nlogR = model.logR;\n\n\n[d,k] = size(m);\nnk = sum(R,1); % 10.51\n\nElogpi = psi(0,alpha)-psi(0,sum(alpha));\n\nEpz = dot(nk,Elogpi);\nEqz = dot(R(:),logR(:));\nlogCalpha0 = gammaln(k*alpha0)-k*gammaln(alpha0);\nEppi = logCalpha0+(alpha0-1)*sum(Elogpi);\nlogCalpha = gammaln(sum(alpha))-sum(gammaln(alpha));\nEqpi = dot(alpha-1,Elogpi)+logCalpha;\nL = Epz-Eqz+Eppi-Eqpi;\n\n\nU0 = chol(M0);\nsqrtR = sqrt(R);\nxbar = bsxfun(@times,X*R,1./nk); % 10.52\n\nlogW = zeros(1,k);\ntrSW = zeros(1,k);\ntrM0W = zeros(1,k);\nxbarmWxbarm = zeros(1,k);\nmm0Wmm0 = zeros(1,k);\nfor i = 1:k\n    U = chol(M(:,:,i));\n    logW(i) = -2*sum(log(diag(U)));      \n    \n    Xs = bsxfun(@times,bsxfun(@minus,X,xbar(:,i)),sqrtR(:,i)');\n    V = chol(Xs*Xs'/nk(i));\n    Q = V/U;\n    trSW(i) = dot(Q(:),Q(:));  % equivalent to tr(SW)=trace(S/M)\n    Q = U0/U;\n    trM0W(i) = dot(Q(:),Q(:));\n\n    q = U'\\(xbar(:,i)-m(:,i));\n    xbarmWxbarm(i) = dot(q,q);\n    q = U'\\(m(:,i)-m0);\n    mm0Wmm0(i) = dot(q,q);\nend\n\nElogLambda = sum(psi(0,bsxfun(@minus,v+1,(1:d)')/2),1)+d*log(2)+logW; % 10.65\nEpmu = sum(d*log(kappa0/(2*pi))+ElogLambda-d*kappa0./kappa-kappa0*(v.*mm0Wmm0))/2;\nlogB0 = v0*sum(log(diag(U0)))-0.5*v0*d*log(2)-logmvgamma(0.5*v0,d);\nEpLambda = k*logB0+0.5*(v0-d-1)*sum(ElogLambda)-0.5*dot(v,trM0W);\n\nEqmu = 0.5*sum(ElogLambda+d*log(kappa/(2*pi)))-0.5*d*k;\nlogB =  -v.*(logW+d*log(2))/2-logmvgamma(0.5*v,d);\nEqLambda = 0.5*sum((v-d-1).*ElogLambda-v*d)+sum(logB);\n\nEpX = 0.5*dot(nk,ElogLambda-d./kappa-v.*trSW-v.*xbarmWxbarm-d*log(2*pi));\n\nL = L+Epmu-Eqmu+EpLambda-EqLambda+EpX;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35362-variational-bayesian-inference-for-gaussian-mixture-model/vbgm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.5987275774691266}}
{"text": "function value = year_length_coptic ( y )\n\n%*****************************************************************************80\n%\n%% YEAR_LENGTH_COPTIC returns the number of days in a Coptic year.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    24 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, integer VALUE, the number of\n%    days in the year.\n%\n  if ( year_is_leap_coptic ( y ) )\n    value = 366;\n  else\n    value = 365;\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/calpak/year_length_coptic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.5987200730274667}}
{"text": "function pass = test_jacobian( pref ) \n% Test Jacobian\n\nif ( nargin == 0 ) \n    pref = chebfunpref; \nend\ntol = 100*pref.cheb2Prefs.chebfun2eps;\n\n\n% Check definition:\nF = chebfun2v(@(x,y) cos(x), @(x,y) sin(y));\nFx = diffx(F); \nFy = diffy(F); \njacF = Fx(1).*Fy(2) - Fx(2).*Fy(1); \n\npass(1) = ( norm(jacF - jacobian(F) ) < tol );\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun2v/test_jacobian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5987200695593136}}
{"text": "function [QAM_BER, QAM_SER] = QAM_Simulate(SNRs, varargin)\n\n% Run M_QAM_Model.mdl to generate Monte Carlo simulation results for\n% QAM signals over AWGN channels\n\nif nargin>1\n    simLines = varargin{1};\nend\n\nopen_system('M_QAM_Model')\nmaxNumBits = 1e7;\nmaxNumErrs = 100;\nTs = 1e-6;\n\n% SNRs = -4:28;\nQAM_BER = zeros(9,length(SNRs));\nQAM_SER = zeros(9,length(SNRs));\n\nS = simset('SrcWorkspace','current', 'DstWorkspace','current');\nk=1;\nfor M = [4, 8, 16, 32, 64, 128, 256, 512, 1024]\n    for EbNo = SNRs\n        % Don't try to simulate BER < 1e-5 (too long!)\n        tBER = berawgn(EbNo,'qam',M);\n        if (tBER>1e-4)\n            fprintf('Simulating %i-QAM, %idB, ', M, EbNo)\n            sim('M_QAM_Model',[], S)\n            QAM_BER(k,EbNo+5) = BER(1);\n            QAM_SER(k,EbNo+5) = SER(1);\n            fprintf('BER=%e, SER=%e\\n', BER(1), SER(1))\n            % Add the result to the plot if it exists\n            if nargin>1\n                set(simLines(k),'YData',QAM_BER(k,:))\n            end\n        end\n    end\n    drawnow\n    k=k+1;\nend\nclose_system('M_QAM_Model')", "meta": {"author": "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/QAM_Simulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143955, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.5987200648521342}}
{"text": "function e = rmModelSearchFit_twoGaussianDoGfixed(p,Y,Xv,Yv,stim,t,sigmaRatio,betaRatioAlpha)\n% rmModelSearchFit_twoGaussianDoGfixed - actual fit function of rmSearchFit\n%\n% error = rmModelSearchFit(_twoGaussianDoGfixed(p,Y,trends,Xgrid,YGrid,stimulusMatrix);\n%\n% Basic barebones fit of a single time-series. Error is returned in\n% percentage: 100% is RSS of unfitted time-series. This way we can quantify\n% the improvement of the fit independend of the variation in the raw\n% time-series.\n%\n% 2006/06 SOD: wrote it.\n% 2006/12 SOD: modifications for fmincon, this is litterally called >10000\n% times so we cut every corner possible. \n% 2009/12 SOD & WZ: adapted for dog fixed model\n\n% make RF (taken from rfGaussian2d)\nXv = Xv - p(1);   % positive x0 moves center right\nYv = Yv - p(2);   % positive y0 moves center up\nRF = exp( (Yv.*Yv + Xv.*Xv) ./ (-2.*(p(3).^2)) );\n\n% make surround\n%s2 = p(3).*sigmaRatio;\n[tmp eccentricity] = cart2pol(p(1), p(2));\ns2 = p(3).*sigmaRatio(1) + eccentricity.*sigmaRatio(2) + sigmaRatio(3);\nRF2 = exp( (Yv.*Yv + Xv.*Xv) ./ (-2.*(s2.^2)) );\n\n% full pRF\nbetaRatio = (p(3)./s2).^betaRatioAlpha;\nRF = RF - betaRatio.*RF2;\n\n% make prediction (taken from rfMakePrediction)\nX = [stim*RF t];\n\n% fit - inlining pinv\n%b = pinv(X)*Y; \n[U,S,V] = svd(X,0);\ns = diag(S); \ntol = numel(X) * eps(max(s));\nr = sum(s > tol);\nif (r == 0)\n    pinvX = zeros(size(X'));\nelse\n    s = diag(ones(r,1)./s(1:r));\n    pinvX = V(:,1:r)*s*U(:,1:r)';\nend\nb = pinvX*Y;\n\n% compute residual sum of squares (e)\n% e = norm(Y - X*abs(b));\nif b(1)>0,\n    e = norm(Y - X*b);\nelse\n    e = norm(Y).*(1+sum(abs(b(1))));\nend\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/rmModelSearchFit_twoGaussianDoGfixed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5985730454226468}}
{"text": "function [sm,pro]=oper(A,B) \n\n% This function computes the \n% sum and the product of 2 matrices\n\n\nsm=A+B;\n\npro=A*B;\n\n\n\n\n% book : Signals and Systems Laboratory with MATLAB  \n% authors : Alex Palamides & Anastasia Veloni\n", "meta": {"author": "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/1/oper.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.5985335029631995}}
{"text": "function [f,g] = hs71F(x)\n\nf = x(1)*x(4)*sum(x(1:3)) + x(3);\n\nif(nargout > 1)\n    g = [ 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)) ];\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/hs71F.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.598522466733965}}
{"text": "function newImg = dtiResliceVolume(img, xform, boundingBox, mmPerVoxOut)\n%\n% newImg = dtiResliceVolume(img, xform, boundingBox, mmPerVoxOut)\n%\n% HISTORY:\n%   2004.01.13 RFD (bob@white.stanford.edu) wrote it.\n\nif(~exist('mmPerVoxOut') | isempty(mmPerVoxOut))\n    mmPerVoxOut = [1 1 1];\nend\n\nif(~exist('boundingBox') | isempty(boundingBox))\n    % create a default bounding box for the resliced data.\n    % The following is the spm default bounding box. Note that the box is\n    % defined in Talairach space (units = mm).\n    boundingBox = [-78 -120 -60;\n                    78  80   85];\nend\n\n% myCinterp3 likes [rows,columns,slices], so we need a permute here\nimg = double(permute(img,[2,1,3]));\n\nx = (boundingBox(1,1):mmPerVoxOut(1):boundingBox(2,1));\ny = (boundingBox(1,2):mmPerVoxOut(2):boundingBox(2,2));\nz = (boundingBox(1,3):mmPerVoxOut(3):boundingBox(2,3));\n[X,Y,Z] = meshgrid(x, y, z);\nnewSize = size(X);\nclear x y z;\ntalCoords = [X(:) Y(:) Z(:)];\nnewSize = size(X);\nclear X Y Z;\n\nimgCoords = mrAnatXformCoords(xform, talCoords);\nnewImg = myCinterp3(img, [size(img,1) size(img,2)], size(img,3), imgCoords, 0.0);\nnewImg = squeeze(reshape(newImg,newSize));\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/dtiResliceVolume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5985224641177306}}
{"text": " function [kb, alpha, kb_m] = kaiser_bessel(x, J, alpha, kb_m, K_N)\n%function [kb, alpha, kb_m] = kaiser_bessel(x, J, alpha, kb_m)\n%function [kb, alpha, kb_m] = kaiser_bessel(x, J, 'best', 0, K_N)\n%\n% generalized Kaiser-Bessel function for x in support [-J/2,J/2]\n% shape parameter \"alpha\" (default 2.34 J)\n% order parameter \"kb_m\" (default 0)\n% see (A1) in lewitt:90:mdi, JOSA-A, Oct. 1990\n% in\n%\tx\t[M,1]\targuments\n% out\n%\tkb\t[M,1]\tKB function values, if x is numbers\n%\t\t\tor string for kernel(k,J), if x is 'string'\n%\t\t\tor inline function, if x is 'inline'\n%\talpha\n%\tkb_m\n%\n% Copyright 2001-3-30, Jeff Fessler, The University of Michigan\n\n% Modification 2002-10-29 by Samuel Matej\n% - for Negative & NonInteger kb_m the besseli() function has\n%\tsingular behavior at the boundaries - KB values shooting-up/down\n%\t(worse for small alpha) leading to unacceptable interpolators\n% - for real arguments and higher/reasonable values of alpha the\n%\tbesseli() gives similar values for positive and negative kb_m\n%\texcept close to boundaries - tested for kb_m=-2.35:0.05:2.35\n%\t(besseli() gives exactly same values for integer +- kb_m)\n%\t=> besseli(kb_m,...) approximated by besseli(abs(kb_m),...), which\n%\tbehaves well at the boundaries\n% WARNING: it is not clear how correct the FT formula (JOSA) is\n%\tfor this approximation (for NonInteger Negative kb_m)\n% NOTE: Even for the original KB formula, the JOSA FT formula\n%\tis derived only for m > -1 !\n\n% if no arguments, make example plots\nif nargin < 2\n\thelp(mfilename)\n\tJ = 8; alpha = 2.34 * J;\n\tx = linspace(-(J+1)/2, (J+1)/2, 1001)';\n%\tx = linspace(J/2-1/4, J/2+1/4, 1001)';\n\n\tmlist = [-4 0 2 7];\n\tleg = {};\n\tfor ii=1:length(mlist)\n\t\tkb_m = mlist(ii);\n\t\tyy(:,ii) = kaiser_bessel(x, J, alpha, kb_m);\n\t\tfunc = kaiser_bessel('inline', 0, alpha, kb_m);\n\t\tyf = func(x, J);\n\t\tif any(yf ~= yy(:,ii)),\n\t\t[yf yy(:,ii)]\n\t\terror 'bug', end\n\t\tleg{ii} = sprintf('m=%d', kb_m);\n\tend\n\tyb = kaiser_bessel(x, J, 'best', [], 2);\n\tplot(\tx, yy(:,1), 'c-', x, yy(:,2), 'y-', ...\n\t\tx, yy(:,3), 'm-', x, yy(:,4), 'g-', x, yb, 'r--')\n\tleg{end+1} = 'best';\n\taxis tight, legend(leg)\n%\taxisy(0, 0.01)\t% to see endpoints\n\txlabel \\kappa, ylabel F(\\kappa)\n\ttitle(sprintf('KB functions, J=%g \\\\alpha=%g', J, alpha) )\nreturn\nend\n\nif ~isvar('J'), J = 6; end\nif ~isvar('alpha') | isempty('alpha'), alpha = 2.34 * J; end\nif ~isvar('kb_m') | isempty('kb_m'), kb_m = 0; end\n\nif ischar(alpha)\n\t[alpha kb_m] = kaiser_bessel_params(alpha, J, K_N);\nend\n\nif ischar(x)\n\tif ischar(alpha)\n\t\tif ~isvar('K_N'), error 'K_N required', end\n\t\tkb = 'kaiser_bessel(k, J, ''%s'', [], %g)';\n\t\tkb = sprintf(kb, alpha, K_N);\n\telse\n\t\tkernel_string = 'kaiser_bessel(k, J, %g, %g)';\n\t\tkb = sprintf(kernel_string, alpha, kb_m);\n\tend\n\tif streq(x, 'inline')\n\t\tkb = inline(kb, 'k', 'J');\n\telseif ~streq(x, 'string')\n\t\terror '1st argument must be \"inline\" or \"string\"'\n\tend\nreturn\nend\n\n%\n% Warn about use of modified formula for negative kb_m\n%\nif (kb_m < 0) & ((abs(round(kb_m)-kb_m)) > eps)\n\tpersistent warned\n\tif isempty(warned)\t% only print this reminder the first time\n\t\tprintf('\\nWarning: Negative NonInt kb_m=%g in kaiser_bessel()', kb_m)\n\t\tprintf('\t- using modified definition of KB function\\n')\n\t\twarned = 1;\n\tend\nend\n\nkb_m_bi = abs(kb_m);\t\t% modified \"kb_m\" as described above\nii = abs(x) < J/2;\nf = sqrt(1 - (x(ii)/(J/2)).^2);\ndenom = besseli(kb_m_bi,alpha);\nif ~denom\n\tprintf('m=%g alpha=%g', kb_m, alpha)\nend\nkb = zeros(size(x));\nkb(ii) = f.^kb_m .* besseli(kb_m_bi, alpha*f) / denom;\nkb = reale(kb);\n\n\n%\n% optimized shape and order parameters\n%\nfunction [alpha, kb_m] = kaiser_bessel_params(alpha, J, K_N)\nif streq(alpha, 'best')\n\tif K_N ~= 2\n\t\twarning 'kaiser_bessel optimized only for K/N=2'\n\t\tprintf('using good defaults: m=0 and alpha = 2.34*J')\n\t\tkb_m = 0;\n\t\talpha = 2.34 * J;\n\telse\n\t\tkb_m = 0;\t% hardwired, because it was nearly the best!\n\t\ttry\n\t\t\ts = 'private/kaiser,m=0';\n\t\t\ts = load(s);\n\t\t\tii = find(J == s.Jlist);\n\t\t\tif isempty(ii)\n\t\t\t\tii = imin(abs(J - s.Jlist));\n\t\t\t\twarning(sprintf('J=%d not found, using %d', ...\n\t\t\t\t\tJ, s.Jlist(ii)))\n\t\t\tend\n\t\t\talpha = J * s.abest.zn(ii);\n\t\tcatch\n\t\t\twarning(['could not open file \"' s '\" so using default alpha = 2.34 J which should be fine.'])\n\t\t\talpha = 2.34 * J;\n\t\tend\n\tend\nelse\n\terror 'unknown alpha mode'\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/kaiser_bessel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5985224588116524}}
{"text": "function [x, mx, sx] = standardise(x, dim, lim)\n\n% STANDARDISE computes the zscore of a matrix along dimension dim\n% has similar functionality as the stats-toolbox's zscore function\n%\n% Use as\n%   x = standardise(x, dim)\n%\n% See also ZSCORE\n\n% Copyright (C) 2009, 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 <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nif nargin == 1,\n  dim = find(size(x)>1,1,'first');\nend\n\nif nargin == 3,\n  ft_error('third input argument is not used');\nend\n\nswitch dim\ncase 1\n  n  = size(x,dim);\n  mx = mean(x,dim);\n  x  = x-mx(ones(1,n),:,:,:,:,:,:,:);\n  sx = sqrt(sum(abs(x).^2,dim)./n);\n  x  = x./sx(ones(1,n),:,:,:,:,:,:,:);\ncase 2\n  n  = size(x,dim);\n  mx = mean(x,dim);\n  x  = x-mx(:,ones(1,n),:,:,:,:,:,:);\n  sx = sqrt(sum(abs(x).^2,dim)./n);\n  x  = x./sx(:,ones(1,n),:,:,:,:,:,:);\ncase 3\n  n  = size(x,dim);\n  mx = mean(x,dim);\n  x  = x-mx(:,:,ones(1,n),:,:,:,:,:);\n  sx = sqrt(sum(abs(x).^2,dim)./n);\n  x  = x./sx(:,:,ones(1,n),:,:,:,:,:);\ncase 4\n  n  = size(x,dim);\n  mx = mean(x,dim);\n  x  = x-mx(:,:,:,ones(1,n),:,:,:,:);\n  sx = sqrt(sum(abs(x).^2,dim)./n);\n  x  = x./sx(:,:,:,ones(1,n),:,:,:,:);\ncase 5\n  n  = size(x,dim);\n  mx = mean(x,dim);\n  x  = x-mx(:,:,:,:,ones(1,n),:,:,:);\n  sx = sqrt(sum(abs(x).^2,dim)./n);\n  x  = x./sx(:,:,:,:,ones(1,n),:,:,:);\ncase 6\n  n  = size(x,dim);\n  mx = mean(x,dim);\n  x  = x-mx(:,:,:,:,:,ones(1,n),:,:);\n  sx = sqrt(sum(abs(x).^2,dim)./n);\n  x  = x./sx(:,:,:,:,:,ones(1,n),:,:);\ncase 7\n  n  = size(x,dim);\n  mx = mean(x,dim);\n  x  = x-mx(:,:,:,:,:,:,ones(1,n),:);\n  sx = sqrt(sum(abs(x).^2,dim)./n);\n  x  = x./sx(:,:,:,:,:,:,ones(1,n),:);\ncase 8\n  n  = size(x,dim);\n  mx = mean(x,dim);\n  x  = x-mx(:,:,:,:,:,:,:,ones(1,n));\n  sx = sqrt(sum(abs(x).^2,dim)./n);\n  x  = x./sx(:,:,:,:,:,:,:,ones(1,n));\notherwise\n  ft_error('dim too large, standardise currently supports dimensionality up to 8');\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/connectivity/private/standardise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5985070070343845}}
{"text": " function [err, sn, T1] = nufft1_err_mm(om, N1, J1, K1, type, alpha, beta)\n%function [err, sn, T1] = nufft1_err_mm(om, N1, J1, K1, type, alpha, beta)\n% Compute worst-case error for each input frequency for min-max 1D NUFFT.\n% in:\n%\tom\t[M,1]\tdigital frequency omega in radians\n%\tN1\t\tsignal length\n%\tJ1\t\t# of neighbors used per frequency location\n%\tK1\t\tFFT size (should be > N1)\n%\ttype\t\t'sinc' 'diric' 'qr'\n%\talpha\t[L,1]\tFourier series coefficients of scaling factors\n%\t\t\ttrick: or, \"sn\" if length N1\n%\tbeta\t\tscale gamma=2pi/K by this in Fourier series\n%\t\t\ttypically is K/N (me) or 0.5 (Liu)\n% out:\n%\terr\t[M,1]\tworst-case error over unit-norm signals\n%\tsn\t[N,1]\tscaling factors corresponding to alpha,beta\n%\tT1\t[J,J]\tT matrix\n%\n% Copyright 2001-12-7, Jeff Fessler, The University of Michigan\n\n% if no arguments, give an example\nif nargin < 4\n\thelp(mfilename)\n\tN = 100; K = 2*N; gam = 2*pi/K;\n\tJ = 14;\n\tom = gam * linspace(0,1,101);\n\t[alpha, beta, ok] = nufft_best_alpha(J, 2, K/N);\n\tif ~ok, alpha = []; beta = 0.5; end\n\terrd = nufft1_err_mm(om, N, J, K, 'diric');\n\terrs = nufft1_err_mm(om, N, J, K, 'sinc');\n\terrq = nufft1_err_mm(om, N, J, K, 'qr');\n\tsemilogy(om/gam, errs, 'g-x', om/gam, errd, 'y-+', om/gam, errq, 'c-o')\n\txlabel '\\omega / \\gamma', ylabel 'E_{max}(\\omega)'\n\tlegend('Tr sinc', 'Tr diric', 'QR approach')\nreturn\nend\n\nif ~isvar('type') | isempty(type),\ttype = 'sinc'; end\nif ~isvar('alpha') | isempty(alpha)\n\talpha = [1];\t% default Fourier series coefficients of scaling factors\nend\nif ~isvar('beta') | isempty(beta)\n\tbeta = 0.5;\t% default is Liu version for now\nend\n\nuse_qr = logical(0);\nif streq(type, 'sinc')\n\tuse_true_diric = logical(0);\nelseif streq(type, 'diric')\n\tuse_true_diric = logical(1);\nelseif streq(type, 'qr')\n\tuse_qr = logical(1);\nelse\n\terror 'unknown type'\nend\n\n\n%\n% see if 'best' alpha is desired\n%\nif ischar(alpha)\n\tif streq(alpha, 'uniform')\n\t\talpha = [1];\n\t\tbeta = 0.5;\n\telse\n\t\tif streq(alpha, 'best')\n\t\t\tL = 0;\n\t\telseif streq(alpha, 'best,L=1')\n\t\t\tL = 1;\n\t\telseif streq(alpha, 'best,L=2')\n\t\t\tL = 2;\n\t\telse\n\t\t\terror 'unknown alpha argument'\n\t\tend\n\t\t[alpha, beta, ok] = nufft_best_alpha(J1, L, K1/N1);\n\t\tif ~ok\n\t\t\ttmp = 'optimal alpha unknown for J=%d, K/N=%g, L=%d';\n\t\t\twarning(sprintf(tmp, J1, K1/N1, L))\n\t\t\tsn = ones(N1,1);\n\t\t\terr = nan;\n\t\t\treturn\n\t\tend\n\tend\nend\n\n%\n% if requested, return corresponding scaling factors too\n%\nif length(alpha) == N1\t% trick: special way to give explicit sn's\n\tsn = alpha;\n\tif ~use_qr, error 'give sn only allowed for QR version', end\nelseif nargout > 1 | use_qr\n\tsn = nufft_scale(N1, K1, alpha, beta);\nend\n\n%\n% QR approach to error\n%\nif use_qr\n\tn = [0:N1-1]' - (N1-1)/2;\n\t[nn, jj] = ndgrid(n, 1:J1);\n\tgam1 = 2*pi/K1;\n\tC = exp(i * gam1 * nn .* jj) / sqrt(N1);\n\tS = spdiag(sn);\n\tA = S' * C;\n\t[Q,R] = qr(S' * C, 0);\t% [N,J] compact QR decomposition\n\n\tdo = col(om - gam1*nufft_offset(om, J1, K1));\n\tDb = exp(i * n * do') / sqrt(N1);\t% [N,M]\n\terr = Db - Q * (Q' * Db);\n\terr = sqrt(sum(abs(err).^2,1))';\t% [M]\nreturn\nend\n\ntol = 0;\nT1 = nufft_T(N1, J1, K1, tol, alpha, beta, use_true_diric);\t% [J,J]\nr1 = nufft_r(om, N1, J1, K1, alpha, beta, use_true_diric);\t% [J,M]\n\n%\n% worst-case error at each frequency\n%\nTr1 = T1 * r1;\t\t\t% [J,M]\nerr = sum(conj(r1) .* Tr1).';\t% [M,1]\nerr = min(real(err), 1);\nerr = sqrt(1 - err);\t\t% caution: this \"1 -\" may cause numerical error\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/nufft1_err_mm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5985070032811254}}
{"text": "function [out,Wc,Wo] = hankelsv(SYS)\n%HANKELSV Compute Hankel singular values and grammians.\n%\n% [OUT,Wc,Wo] = HANKELSV(SYS) computes controllability and observability\n%    grammians Wc, Wo, and the Hankel singular values OUT of an LTI \n%    model SYS (created with either TF, ZPK, SS, or FRD). The model\n%    SYS can be either continuous-time or discrete-time. However, only\n%    in continuous-time case that SYS is allowed to be unstable. \n%    The computed Hankel singular values are sorted in ascending order. \n%\n%    For unstable continuous-time system, state-space stable/anti-stable \n%    decomposition is used instead, and OUT=[OUT_stable;OUT_anti-stable].\n%    In addition, Wc={Wc_stable,Wc_anti-stable} and Wo is either. \n\n%    The former version of HKSV employs an obsolete fashion in using the \n%    Matlab function GRAM, i.e., instead of using GRAM(SYS,'c') and \n%    GRAM(SYS,'o'), it uses GRAM(A,B) and GRAM(A',C'), respectively.  \n%    This restricts the computation of gramians to continuous-time case,\n%    only, since GRAM(A,B) and GRAM(A',C') solve LYAP, not DLYAP. \n%   \n%    This improved version also correct some other bugs in the former  \n%    version, for example, HKSV does not return gramians when SYS is \n%    unstable, but not anti-stable. \n\n%    Developer: Wathanyoo Khaisongkram\n%    Date Developed: Oct 20, 2004\n%    Email: sunboom15@yahoo.com \n%    Improved version of HKSV by R. Y. Chiang & M. G. Safonov March, 1986\n% -----------------------------------------------------------------------\n\nSYS=ss(SYS);                            % convert to state-space model\n\n% Discrete-time LTI model\nif get(SYS,'Ts')~=0                     % discrete-time LTI model\n   if max(abs(pole(SYS))) > 1           % unstable discrete system\n      error('For discrete LTI model, system must be stable')\n   end\n   Wc = gram(SYS,'c');                  % controllability matrix\n   Wo = gram(SYS,'o');                  % observability matrix\n   out = sqrt(eig(Wc*Wo));              % Hankel singular values\n   [no_use,index] = sort(out);          % index for sorting \n   out = out(index);                    % sorted singular values\n   return                               % end function\nend   \n\n% Continuous-time LTI model \n[A,B,C,D]=ssdata(SYS);                  % extract the system matrices\n   mode = eig(A);                       % the eigen values of 'a'\n   nrow = size(A,1);                    % the number of rows in 'a'\n   nsta = length(find(real(mode) < 0)); % the number of unstable modes\nif isequal(nsta,nrow),                  % completely stable\n   Wc = gram(SYS,'c');                  % controllability matrix\n   Wo = gram(SYS,'o');                  % observability matrix\n   out = sqrt(eig(Wc*Wo));              % Hankel singular values\n   [no_use,index] = sort(out);          % index for sorting \n   out = out(index);                    % sorted singular values\nelseif isequal(nsta,0),                 % completely unstable\n   SYS=ss(-A,-B,C,D,SYS);               % change the dynamic and the input matrices to '-a' and '-b', \n                                        % respectively with all LTI properties inherited from \n                                        % original SYS, e.g., discrete or continuous domain.   \n   Wc = gram(SYS,'c');                  % controllability matrix\n   Wo = gram(SYS,'o');                  % observability matrix\n   out = sqrt(eig(Wc*Wo));              % Hankel singular values\n   [no_use,index] = sort(out);          % index for sorting \n   out = out(index);                    % sorted singular values\nelse, % 0 < nsta < nrow\n   [SYSs,SYSu] = stabproj(SYS);         % decompose stable/anti-stable parts\n   % Stable part \n   Wcs = gram(SYSs,'c');                % controllability matrix\n   Wos = gram(SYSs,'o');                % observability matrix\n   outl = sqrt(eig(Wcs*Wos));           % Hankel singular values1\n   [no_use,index] = sort(outl);         % index for sorting \n   outl = outl(index);                  % sorted singular values\n   % Anti-stable part \n   [Au,Bu,Cu,Du]=ssdata(SYSu);          % obtain the system matrices of SYSu\n   SYSu=ss(-Au,-Bu,Cu,Du,SYSu);         % change the dynamic and the input matrices to '-ar' and '-br'. \n   Wcu = gram(SYSu,'c');                % controllability matrix\n   Wou = gram(SYSu,'o');                % observability matrix\n   outr = sqrt(eig(Wcu*Wou));           % Hankel singular values\n   [no_use,index] = sort(outr);         % index for sorting \n   outr = outr(index);                  % sorted singular values\n   out = [outl;outr];                   % gather two cases\n   Wc={Wcs,Wcu};                        % controllability gramian\n   Wo={Wos,Wou};                        % observability gramian\nend\n\n% end of HKSV_MOD", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6082-hankelsv/hankelsv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5984829587982801}}
{"text": "%% (Internal) Design a filter to downsample signals prior printing to a report\n%   \n%   b = design_downsample_filter( downsample_factor )\n% \n% Arguments:\n% \n%      + downsample_factor: times to downsample signal\n% \n% Output:\n% \n%      + b: filter coefficients\n% \n% Example:\n% \n% Author: Mariano Llamedo Soria llamedom@electron.frba.utn.edu.ar\n% Version: 0.1 beta\n% Last update: 14/5/2014\n% Birthdate  : 21/4/2015\n% Copyright 2008-2015\n% \nfunction b = design_downsample_filter( downsample_factor )\n% MATLAB Code\n% Generated by MATLAB(R) 8.2 and the Signal Processing Toolbox 6.20.\n% Generated on: 23-Jun-2014 10:45:52\n\n% FIR least-squares Lowpass filter designed using the FIRLS function.\n\n% All frequency values are normalized to 1.\n\nN     = 60;   % Order\nFpass = 1/downsample_factor;  % Passband Frequency\nFstop = min(1, Fpass + 0.1);  % Stopband Frequency\nWpass = 1;    % Passband Weight\nWstop = 100;  % Stopband Weight\n\n% Calculate the coefficients using the FIRLS function.\nb  = firls(N, [0 Fpass Fstop 1], [1 1 0 0], [Wpass Wstop]);\n\n% [EOF]\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/design_downsample_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5984829586226027}}
{"text": "classdef ZXH_CF14 < PROBLEM\n% <multi/many> <real> <large/none> <constrained>\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    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            if isempty(obj.M); obj.M = 2; 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 (linear)\n            G      = [ones(N,1) cumprod(THETA,2)] .* [1-THETA ones(N,1)];\n            PopObj = G .* repmat((1+T),1,M);\n            % Step 6: Constraints\n            PopCon(:,1) = Sx(:,1) + h - 1; \n            PopCon(:,2) = -(Sx(:,1) + h - 1/4); \n            for i = 1 : obj.k\n                PopCon(:,i+2) = min(min(THETA(:,i)-1/10,4/5-THETA(:,i)),max(2/5-THETA(:,i),THETA(:,i)-7/10));\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            T = zeros(size(R));\n            for i = obj.M-1 : -1 : 1\n                T(:,i) = R(:,i+1)./R(:,i)./(1-T(:,i+1)+R(:,i+1)./R(:,i));\n            end\n            THETA = T(:,1:obj.k);\n            Valid = all(THETA<=1/10|THETA>=2/5&THETA<=7/10|THETA>=4/5,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,1,30)';\n                R = {a*a',a*(1-a'),(1-a)*ones(size(a'))};\n                T2 = R{3}./R{2}./(1+R{3}./R{2});\n                T1 = R{2}./(1-T2);\n                THETA = cat(3,T1,T2);\n                Valid = all(THETA<=1/10|THETA>=2/5&THETA<=7/10|THETA>=4/5,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_CF14.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.59848294270391}}
{"text": "function [ 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%    26 March 2012\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\n", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/init/private/i4_sobol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5984829374562382}}
{"text": "function [f,p,r] = compute_f(T,H)\n\n  if length(T) ~= length(H),\n    size(T)\n    size(H)\n  end;\n  \n  N = length(T);\n  numT = 0;\n  numH = 0;\n  numI = 0;\n  for n=1:N,\n    Tn = (T(n+1:end))==T(n);\n    Hn = (H(n+1:end))==H(n);\n    numT = numT + sum(Tn);\n    numH = numH + sum(Hn);\n    numI = numI + sum(Tn .* Hn);\n  end;\n  p = 1;\n  r = 1;\n  f = 1;\n  if numH > 0,\n    p = numI / numH;\n  end;\n  if numT > 0,\n    r = numI / numT;\n  end;\n  if (p+r) == 0,\n    f = 0;\n  else\n    f = 2 * p * r / (p + r);\n  end;\n  ", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/auxiliary/clustering_evaluator/compute_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5984829371048825}}
{"text": "\t\t% Se sterge spatiul de lucru\nclear;\n        % Stabilirea numarului de necunoscute\nN=1000;\n        % Se genereaza matricea coeficientilor (a)\na=rand(N);\n\t\t% Se incarca vectorul termenilor liberi b\nb=randn(N,1);\n        % Setarea cronometrului\nt0=cputime;\n        % Se rezolva sistemul de ecuatii liniare cu prima metoda prezentata\nx1=a\\b;\n        % Se calculeaza timpul de calcul necesar\nt1=cputime-t0;\n        % Setarea cronometrului\nt0=cputime;\n        % Se rezolva sistemul de ecuatii liniare cu a doua metoda prezentata\nx2=inv(a)*b;\n        % Se calculeaza timpul de calcul necesar\nt2=cputime-t0;\n        % Se afiseaza timpii de calcul\ndisp('Timp de calcul metoda 1:'); disp(t1');\ndisp('Timp de calcul metoda 2:'); disp(t2');\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/8416-widely-used-programming-environments-in-electrical-engineering-matlab/3/Ex_3_7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5984784070410487}}
{"text": "function val = m01Q1001(F10, F01)\n%------------------------------------------------------------------------------\n%\n% Integrates interpolated gridfunction {F10 U F01} times y,\n% interpolation is assumed piecewise constant.\n% The result corresponds to a first order moment.\n%\n% See also: m01\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw <Paul.de.Zeeuw@cwi.nl>  http://homepages.cwi.nl/~pauldz/\n% Last Revision: December 12, 2000.\n%  2000 Stichting CWI, Amsterdam\n%------------------------------------------------------------------------------\n[hx, hy] = Q1001gridfdims(F10, F01);\nQhxy = 2 * hx * hy;\n%\n[F10ycp, F01ycp] = Q1001ycpowp(F10, F01, 1, 0.0);\nval = sum(sum( F10ycp.*F10 ));\nclear F10ycp;\n%\nval = (val + sum(sum( F01ycp.*F01 ))) * Qhxy; \nclear F01ycp;        \n%------------------------------------------------------------------------------\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/m01Q1001.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.598478393771581}}
{"text": "function [beta_gibbs omega_gibbs F_gibbs L_gibbs phi_gibbs sigma_gibbs lambda_t_gibbs sigma_t_gibbs sbar]=tvbvar2gibbs(G,sigmahat,T,chi,psi,kappa,betahat,q,n,It,Bu,I_tau,I_om,H,Xbar,y,alpha0,yt,Xbart,upsilon0,f0,delta0,gamma,pick,pickf)\n\n\n\n\n\n% preliminary elements for the algorithm\n% compute the product G'*I_gamma*G (to speed up computations of deltabar)\nGIG=G'*I_om*G;\n% set tau as a large value\ntau=10000;\n% set omega as a large value\nom=5;\n% compute psibar\nchibar=(chi+T)/2;\n% compute alphabar\nkappabar=T+kappa;\n% compute alphabar\nalphabar=T+alpha0;\n\n\n% initiate the Gibbs sampler\n% initiate the counting of iterations\ncount=1;\npickcount=1;\n% initiate the record matrices and cells\nbeta_gibbs=[];\nomega_gibbs=[];\nF_gibbs=[];\nL_gibbs=[];\nphi_gibbs=[];\nsigma_gibbs=[];\nlambda_t_gibbs={};\nsigma_t_gibbs={};\n\n\n% step 1: determine initial values for the algorithm\n\n% initial value for B\nB=kron(ones(T,1),betahat);\n% initial value Omega\nomega=diag(diag(betahat*betahat'));\n% invert Omega\ninvomega=diag(1./diag(omega));\n% initial value for f_2,...,f_n\n% obtain the triangular factorisation of sigmahat\n[Fhat Lambdahat]=bear.triangf(sigmahat);\n% obtain the inverse of Fhat\n[invFhat]=bear.invltod(Fhat,n);\n% create the cell storing the different vectors of invF\nFinv=cell(n,1);\n% store the vectors\nfor ii=2:n\n    Finv{ii,1}=invFhat(ii,1:ii-1);\nend\n% initial values for L_1,...,L_n\nL=zeros(T,n);\n% initial values for phi_1,...,phi_n\nphi=ones(1,n);\n% initiate invsigmabar\ninvsigmabar=sparse(kron(eye(T),inv(sigmahat)));\n\n\n\n% step 2: determine the sbar values and Lambda\nsbar=diag(Lambdahat);\nLambda=sparse(diag(sbar));\n\n\n\n% step 3: recover the series of initial values for lambda_1,...,lambda_T and sigma_1,...,sigma_T\nlambda_t=repmat(diag(sbar),1,1,T);\nsigma_t=repmat(sigmahat,1,1,T);\n\nhbar = bear.parfor_progressbar(It,'Progress of the Gibbs sampler');  %create the progress bar\n\n% run the Gibbs sampler\nwhile count<=It\n    % count\n\n    hbar.iterate(1);   % update progress by one iteration\n\n\n    % step 4: draw B\n    invomegabar=H'*kron(I_tau,invomega)*H+Xbar'*invsigmabar*Xbar;\n    % compute the choleski of invomegabar\n    C=chol(bear.nspds(invomegabar),'Lower');\n    % compute temporary value\n    temp=Xbar'*invsigmabar*y;\n    % smoothing phase: solve by back substitution\n    temp1=C\\temp;\n    % smoothing phase: solve by forward substitution\n    Bbar=C'\\temp1;\n    % simulation phase:\n    B=Bbar+C'\\randn(q*T,1);\n    % reshape\n    Beta=reshape(B,q,T);\n\n\n\n    % step 5: draw omega from its posterior\n    % compute the summ\n    summ=(1/tau)*Beta(:,1)*Beta(:,1)';\n    for ii=2:T\n        summ=summ+(Beta(:,ii)-Beta(:,ii-1))*(Beta(:,ii)-Beta(:,ii-1))';\n    end\n    summ=diag(summ);\n    % obtain Qbar\n    psibar=summ+psi;\n    % draw omega\n    omega=diag(arrayfun(@bear.igrandn,kron(ones(q,1),chibar),psibar));\n    % invert it for next iteration\n    invomega=diag(1./diag(omega));\n\n\n\n    % step 6: draw the series f_2,...,f_n from their conditional posteriors\n    % recover first the residuals\n    for jj=1:T\n        epst(:,:,jj)=yt(:,:,jj)-Xbart{jj,1}*Beta(:,jj);\n    end\n    % then draw the vectors in turn\n    for jj=2:n\n        % first compute the summations required for upsilonbar and fbar\n        summ1=zeros(jj-1,jj-1);\n        summ2=zeros(jj-1,1);\n        % run the summation\n        for kk=1:T\n            prodt=epst(1:jj-1,1,kk)*exp(-L(kk,jj));\n            summ1=summ1+prodt*epst(1:jj-1,1,kk)';\n            summ2=summ2+prodt*epst(jj,1,kk)';\n        end\n        summ1=(1/sbar(jj,1))*summ1;\n        summ2=(-1/sbar(jj,1))*summ2;\n        % then obtain the inverse of upsilon0\n        invupsilon0=diag(1./diag(upsilon0{jj,1}));\n        % obtain upsilonbar\n        invupsilonbar=summ1+invupsilon0;\n        C=chol(bear.nspd(invupsilonbar));\n        invC=C\\speye(jj-1);\n        upsilonbar=full(invC*invC');\n        % recover fbar\n        fbar=upsilonbar*(summ2+invupsilon0*f0{jj,1});\n        % finally draw f_i^(-1)\n        Finv{jj,1}=fbar+chol(bear.nspd(upsilonbar),'lower')*randn(jj-1,1);\n    end\n    % recover the inverse of F\n    invF=eye(n);\n    for jj=2:n\n        invF(jj,1:jj-1)=Finv{jj,1};\n    end\n    % eventually recover F\n    F=bear.invltod(invF,n);\n    % then update sigma\n    sigma=F*Lambda*F';\n\n\n\n    % step 7: draw the series phi_1,...,phi_n from their conditional posteriors\n    % draw the parameters in turn\n    for jj=1:n\n        % estimate deltabar\n        deltabar=L(:,jj)'*GIG*L(:,jj)+delta0;\n        % draw the value phi_i\n        phi(1,jj)=bear.igrandn(alphabar/2,deltabar/2);\n    end\n\n\n\n\n    % step 8: draw the series lambda_i,t from their conditional posteriors, i=1,...,n and t=1,...,T\n    % consider variables in turn\n    for jj=1:n\n        % consider periods in turn\n        for kk=1:T\n            % a candidate value will be drawn from N(lambdabar,phibar)\n            % the definitions of lambdabar and phibar varies with the period, thus define them first\n            % if the period is the first period\n            if kk==1\n                lambdabar=(gamma*L(2,jj))/(1/om+gamma^2);\n                phibar=phi(1,jj)/(1/om+gamma^2);\n                % if the period is the final period\n            elseif kk==T\n                lambdabar=gamma*L(T-1,jj);\n                phibar=phi(1,jj);\n                % if the period is any period in-between\n            else\n                lambdabar=(gamma/(1+gamma^2))*(L(kk-1,jj)+L(kk+1,jj));\n                phibar=phi(1,jj)/(1+gamma^2);\n            end\n            % now draw the candidate\n            cand=lambdabar+phibar^0.5*randn;\n            % compute the acceptance probability\n            prob=bear.mhprob2(jj,cand,L(kk,jj),sbar(jj,1),epst(:,1,kk),Finv{jj,1});\n            % draw a uniform random number\n            draw=rand;\n            % keep the candidate if the draw value is lower than the prob\n            if draw<=prob\n                L(kk,jj)=cand;\n                % if not, just keep the former value\n            end\n        end\n    end\n    % then recover the series of matrices lambda_t and sigma_t\n    for jj=1:T\n        lambda_t(:,:,jj)=diag(sbar).*diag(exp(L(jj,:)));\n        sigma_t(:,:,jj)=F*lambda_t(:,:,jj)*F';\n    end\n\n\n\n\n\n\n\n    % record phase\n    % if the burn-in sample phase is not yet over\n    if count<=Bu\n        % simply add 1 to the iteration count\n        count=count+1;\n        % on the other hand, if the burn-in sample phase is over\n    elseif count>Bu\n        % adding one iteration to the count will depend on wether post-burn selection applies\n        % if there is no post burn selection\n        if pick==0\n            % record the results\n            beta_gibbs(:,count-Bu)=B;\n            omega_gibbs(:,count-Bu)=diag(omega);\n            F_gibbs(:,:,count-Bu)=F;\n            L_gibbs(:,:,count-Bu)=L;\n            phi_gibbs(count-Bu,:)=phi;\n            sigma_gibbs(:,count-Bu)=sigma(:);\n            for jj=1:T\n                lambda_t_gibbs{jj,1}(:,:,count-Bu)=lambda_t(:,:,jj);\n                sigma_t_gibbs{jj,1}(:,:,count-Bu)=sigma_t(:,:,jj);\n            end\n            % then add one to the count\n            count=count+1;\n            % if there is post burn selection, only one draw over 'fpick' draws will be retained\n        elseif pick==1\n            % if the iteration does not correspond to fpick, don't record the results, don't increase the regular count, but do increase pickcount by 1, and do record the acceptance rate of the Metropolis-Hastings step\n            if pickcount~=pickf\n                pickcount=pickcount+1;\n                % on the other hand, if the iteration does correspond to fpick\n            elseif pickcount==pickf\n                % do record the results\n                beta_gibbs(:,count-Bu)=B;\n                omega_gibbs(:,count-Bu)=diag(omega);\n                F_gibbs(:,:,count-Bu)=F;\n                L_gibbs(:,:,count-Bu)=L;\n                phi_gibbs(count-Bu,:)=phi;\n                sigma_gibbs(:,count-Bu)=sigma(:);\n                for jj=1:T\n                    lambda_t_gibbs{jj,1}(:,:,count-Bu)=lambda_t(:,:,jj);\n                    sigma_t_gibbs{jj,1}(:,:,count-Bu)=sigma_t(:,:,jj);\n                end\n                % then increase the regular count by 1 and re-initialise pickcount\n                count=count+1;\n                pickcount=1;\n            end\n        end\n    end\nend\nclose(hbar);   %close progress bar\n\n\n% turn beta_gibbs into cell\nbeta_gibbs=mat2cell(beta_gibbs,repmat(q,T,1),It-Bu);\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/tvbvar2gibbs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5984783900283854}}
{"text": "function   IM=subplane(Z)\n%SUBtract selected PLANE, or remove slope (detilt) from data matrix\n% \n%Call:\n%           IM=subplane(Z)\n%Input:\n%           Z = (double) data matrix \n%Output:\n%           IM = Z - plane     (the SUBtracted PLANE is defined by manually selected points)\n%\n%Vassili Pastushenko\tMarch\t2005\n%==============================\n%figure;\nimagesc(Z);\nshg\nset(gca,'fontsize',15)\n%select at least three (x,y) points which define a plane in 3D\ntitle('Click at least three coplanar points')\n[x,y]=getpts(gca);\n\nif numel(x)<3,\n    title('More points please');\n    [xx,yy]=getpts(gca);\n    x=[x;xx];y=[y;yy];\nend\n    \nx=round(x);\ny=round(y);\nPONT=numel(x);\nZIN=ones(PONT,1);\nM=[x y ZIN];\nfor i=1:PONT\nZIN(i)=Z(y(i),x(i));\nend\n\nV=M\\ZIN;\n[VY,VX]=size(Z);\n[X,Y]=meshgrid(1:VX,1:VY);\nBAS=V(1)*X+V(2)*Y+V(3);\nIM=Z-BAS;\nimagesc(IM);\ntitle('Detilted data')\nshg", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/7023-subplane/subplane.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.5984780941390027}}
{"text": "% File c:\\M_files\\shortcuts\\rtdbimod.m\n% mca of rtd circuit using pre-screened (bi-modal) inputs; \n% uses MATLAB function G2a.m\n% Revised and updated 3/10/04\n% Since this is a DC circuit, SS arrays A,B,D,E are not used.\nclc;clear\n% Component values\nR1=4.53;R2=34.8;R3=132;R4=9.09;R5=9.09;E1=5;\nR6=4.53;R7=27.4;R8=20;R9=20;RT=1.915;\nNom=[R1 R2 R3 R4 R5 R6 R7 R8 R9 RT E1];\nVo=G2a(Nom);\n%\n% \"Real world\" tolerances\n%\nTinit=0.001;Tlife=0.002;ppm=1e-6;\nTC1=50*ppm;TC2=25*ppm;\nThi=Tinit+Tlife+35*TC1;Tlo=-Tinit-Tlife-80*TC1;\nTrhi=8.1*1e-4;Trlo=-Trhi;Trefhi=0.02+35*TC2;\nTreflo=-0.02-80*TC2;\n%\np=1:9;T(1,p)=Tlo;T(2,p)=Thi;\nT(1,10)=Trlo;T(2,10)=Trhi;T(1,11)=Treflo;T(2,11)=Trefhi;\n%\nNk=10000; % Number of Monte Carlo samples\n%\nNc=length(Nom); % Number of components\nnb=30; % Number of bins in histograms\nNg=50; % Number of point in ideal Gaussian curve  \nrandn('state',sum(100*clock)); % randomize normal RNG seed\nYn=zeros(Nk,Nc);sp=0.5; % sp is 1/2 of gap width\nRn=zeros(Nk,Nc);\n% Get tolerance constants independent of samples k\np=1:Nc;tr1=(T(2,:)-T(1,:))/6;tr2=T(1,:)+1;\n%\nfor w=1:Nc\n\tk=0;\n\twhile k < Nk\n\t\tz=randn;\n\t\tif (z<-sp)|(z>sp) % accept only rv's outside of -sp to +sp gap\n\t\t\tk=k+1; % next rv\n\t\t\tYn(k,w)=z; % store in Yn array\n\t\tend\n\tend\nend\nfor k=1:Nk\n   Rn(k,:)=Nom.*(tr1.*(Yn(k,:)+3)+tr2);\n   Vm(k)=G2a(Rn(k,:));\nend\n%\n% get Nc input histograms\n%\nfor p=1:Nc\n\tVav(p)=mean(Yn(:,p));\n\tVsd(p)=3*std(Yn(:,p));\n\thin(p,:)=hist(Yn(:,p),nb)/Nk;\n\tVL1(p)=min(Yn(:,p));VH1(p)=max(Yn(:,p));\n\tintv1(p)=(VH1(p)-VL1(p))/nb;\n\tq=1:nb;bin1(p,q)=VL1(p)+intv1(p)*(q-1);\nend\n%\n% get output histogram\n%\nVs=std(Vm);Vavg=mean(Vm);\nhout=hist(Vm,nb)/Nk;VL2=min(Vm);VH2=max(Vm);\nintv2=(VH2-VL2)/nb;\nq=1:nb;bin2(q)=VL2+intv2*(q-1);\n% Ideal Gaussian curve\nintvn2=(VH2-VL2)/Ng;\nc1=intv2/(Vs*sqrt(2*pi));\nfor q=1:Ng\n   x1(q)=intvn2*(q-1)+VL2;\n   y1(q)=c1*exp((-(x1(q)-Vavg)^2/(2*Vs^2)));\nend\n%\nVhi2=Vavg+Vs;Vlo2=Vavg-Vs;\nVsr=sprintf('%2.3f\\n',3*Vs);Vavgr=sprintf('%2.3f\\n',Vavg);\n%\nsubplot(2,1,1)\nset(gca,'FontSize',8);\nbar(bin1(1,:),hin(1,:),1,'y');\n%stairs(bin1(1,:),hin(1,:),'k');\n%hold on\n%stairs(bin1(2,:),hin(2,:),'b');stairs(bin1(3,:),hin(3,:),'g');\n%stairs(bin1(4,:),hin(4,:),'k');stairs(bin1(5,:),hin(5,:),'k');\n%stairs(bin1(6,:),hin(6,:),'k');stairs(bin1(7,:),hin(7,:),'k');\n%stairs(bin1(8,:),hin(8,:),'k');hold off;\n%title('8 of 11 Pre-screened inputs');\ntitle('1 of 11 Pre-screened inputs');\ngrid off\nxlabel('Sigma');\naxis([-4 4 0 0.2]);\n%\nsubplot(2,1,2)\nbar(bin2,hout,1,'y');\nset(gca,'FontSize',[8]);\nhold on\nh=plot(x1-intv2/2,y1,'k');\nhold off\ntitle('RTD output');xlabel('Volts dc')\nxlabel('Volts DC');\naxis([4.0 4.6 0 0.15]);\ntext(4.1,0.1,['Vavg=',Vavgr],'FontSize',8); \ntext(4.1,0.08,['3s=',Vsr],'FontSize',8);\ntext(4.1,0.06,['Nk = ',num2str(Nk)],'FontSize',8);\n%\nfigure(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/2435-shortcut-state-space-circuit-analysis/Matlab_Files/rtdbimod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5984577087909051}}
{"text": "% test for dictionary learning with missing data\n% \n%   Copyright (c) 2007 Gabriel Peyre\n\npath(path, 'toolbox/');\nname = 'barb';\n\n% size of the image to inpaint\nn0 = 200;\n\nredun = 2;        % redundandy of the dictionary\novertraining = 30;   % over training factor\n        \nw = 8; n = w^2;\nm = round( n*redun );           % number of atoms\np = round( overtraining*m );    % number of samples\n% load random patches\nM0 = load_image(name);\nM0 = rescale( crop(M0,n0) );\n% destroy pixels\nMmask = rand(size(M0))>.3;\nM = M0.*Mmask;\n\n%% input exemplar for learning\nH = compute_all_patch(M,w);\nHmask = compute_all_patch(Mmask,w);\nH = reshape(H, n,size(H,4));\nHmask = reshape(Hmask, n,size(Hmask,4));\ns = std(H); [tmp,sel] = sort(s); sel = sel(end:-1:1);\nY = H(:,sel(1:4:end)); Y = Y(:,1:p);\nYmask = Hmask(:,sel(1:4:end)); Ymask = Ymask(:,1:p);\nY = Y ./ repmat( sqrt(sum(Y.^2,1)), n,1 );\n\n%% dictionary learning\noptions.K = m; % number of atoms\noptions.sparse_coder = 'omp';\noptions.sparse_coder = 'mp';\noptions.nbr_max_atoms = 4;\noptions.niter_grad = 60;\noptions.lambda_grad = .01; % gradient descent step\noptions.mask = Ymask;\noptions.niter_learning = 100;\noptions.use_bootstrapping = 1;\n[D,X,err] = perform_dictionary_learning(Y,options);\n\n%% display learned dictionary\nnb = [10 floor(m/10)]; ndim = 2;\nA = display_dictionnary(D, X, nb,ndim );\nclf;\nimageplot(A);\n\n%% perform inpainting\nniter_inpainting = 15;\noptions.sparse_coder = 'mp';\nM1 = M;\nfor i=1:40\n    M1 = perform_blurring(M1,1.2);\n    M1(Mmask) = M(Mmask);\nend\nfor i=1:niter_inpainting\n    progressbar(i,niter_inpainting);\n    Y1 = compute_all_patch(M1,w);\n    Y1 = reshape(Y1, n,size(Y1,4));\n    X1 = perform_omp(D,Y1,options);\n    Y1 = reshape(D*X1,[w w 1 size(Y1,2)]);\n    M1 = compute_all_patch(Y1,size(M1,1));\n    % impose boundary pixels\n    M1(Mmask) = M(Mmask);\nend\n\n%% display result\nrep = 'results/inpainting/';\nif not(exist(rep))\n    mkdir(rep);\nend\nMM = M; MM(Mmask==0) = 0;\nimageplot({M0,MM,A,M1}, {'Ground trust', 'Input','Dictionary','Inpainted'}, 2,2,1);\nsaveas(gcf, [rep name '-inpainted.png'], 'png');\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/tests/test_learning_missing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5984577038710047}}
{"text": "% DEMVOWELSFGPLVM3 Model the vowels data with a 2-D FGPLVM using RBF kernel and back constraints, but without PCA initialisation.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'vowels';\nexperimentNo = 3;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('fitc');\noptions.back = 'mlp';\noptions.backOptions = mlpOptions;\noptions.optimiseInitBack = 0;\noptions.numActive = 200;\nlatentDim = 2;\nd = size(Y, 2);\n\nmodel = fgplvmCreate(latentDim, d, Y, options);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\nmodelWriteResult(model, dataSetName, experimentNo);\n\nif exist('printDiagram') & printDiagram\n  lvmPrintPlot(model, lbls, dataSetName, experimentNo);\nend\n\n% Load the results and display dynamically.\nlvmResultsDynamic(dataSetName, experimentNo, 'vector')\n\nerrors = lvmNearestNeighbour(model, lbls);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demVowelsFgplvm3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6992544335934765, "lm_q1q2_score": 0.5984576987290908}}
{"text": "function [cst,cstJac] = autoGen_cst_footVel(q1p,q2p,q4p,q5p,q1m,q2m,q4m,q5m,dq1p,dq2p,dq4p,dq5p,dq1m,dq2m,dq4m,dq5m,l1,l2,l4,l5)\n%AUTOGEN_CST_FOOTVEL\n%    [CST,CSTJAC] = AUTOGEN_CST_FOOTVEL(Q1P,Q2P,Q4P,Q5P,Q1M,Q2M,Q4M,Q5M,DQ1P,DQ2P,DQ4P,DQ5P,DQ1M,DQ2M,DQ4M,DQ5M,L1,L2,L4,L5)\n\n%    This function was generated by the Symbolic Math Toolbox version 6.3.\n%    25-Oct-2015 18:36:52\n\nt2 = sin(q1p);\nt3 = sin(q2p);\nt4 = sin(q4p);\nt5 = sin(q5p);\nt6 = sin(q1m);\nt7 = sin(q2m);\nt8 = sin(q4m);\nt9 = sin(q5m);\ncst = [dq1p.*l1.*t2+dq2p.*l2.*t3-dq4p.*l4.*t4-dq5p.*l5.*t5;-dq1m.*l1.*t6-dq2m.*l2.*t7+dq4m.*l4.*t8+dq5m.*l5.*t9];\nif nargout > 1\n    cstJac = reshape([0.0,0.0,dq1p.*l1.*cos(q1p),0.0,dq2p.*l2.*cos(q2p),0.0,0.0,0.0,-dq4p.*l4.*cos(q4p),0.0,-dq5p.*l5.*cos(q5p),0.0,l1.*t2,0.0,l2.*t3,0.0,0.0,0.0,-l4.*t4,0.0,-l5.*t5,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-dq1m.*l1.*cos(q1m),0.0,-dq2m.*l2.*cos(q2m),0.0,0.0,0.0,dq4m.*l4.*cos(q4m),0.0,dq5m.*l5.*cos(q5m),0.0,-l1.*t6,0.0,-l2.*t7,0.0,0.0,0.0,l4.*t8,0.0,l5.*t9,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],[2,32]);\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/fiveLinkBiped/costOfTransport/autoGen_cst_footVel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5984576985070783}}
{"text": "% DEMOILFGPLVM1 Oil data with fully independent training conditional.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'oil';\nexperimentNo = 1;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('fitc');\noptions.optimiser = 'scg';\nlatentDim = 2;\nd = size(Y, 2);\n\nmodel = fgplvmCreate(latentDim, d, Y, options);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\nmodelWriteResult(model, dataSetName, experimentNo);\n\nif exist('printDiagram') & printDiagram\n  lvmPrintPlot(model, lbls, dataSetName, experimentNo);\nend\n\n% Load the results and display them.\nlvmScatterPlot(model, lbls);\n\n% compute the nearest neighbours errors in latent space.\nerrors = lvmNearestNeighbour(model, lbls);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demOilFgplvm1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5984576875572123}}
{"text": "function writeGrid(filename, grid_size, grid_spacing, pml_size, pml_alpha, Nt, dt, c_ref) \n%WRITEGRID    Write grid and PML properties to a k-Wave HDF5 file.\n%\n% DESCRIPTION:\n%       writeGrid creates and writes the wavenumber grids and PML variables\n%       required by the k-Wave C++ code to the HDF5 file specified by the\n%       user. \n%\n%       List of parameters that are written:\n%           Nx\n%           Ny\n%           Nz\n%           Nt\n%           dt\n%           dx\n%           dy\n%           dz\n%           c_ref\n%           ddx_k_shift_pos_r\n%           ddx_k_shift_neg_r\n%           ddy_k_shift_pos\n%           ddy_k_shift_neg\n%           ddz_k_shift_pos\n%           ddz_k_shift_neg\n%           x_shift_neg_r\n%           y_shift_neg_r\n%           z_shift_neg_r\n%           pml_x_sgx\n%           pml_y_sgy\n%           pml_z_sgz\n%           pml_x\n%           pml_y\n%           pml_z\n%           pml_x_alpha\n%           pml_y_alpha\n%           pml_z_alpha\n%           pml_x_size\n%           pml_y_size\n%           pml_z_size\n%\n% USAGE:\n%       writeGrid(filename, grid_size, grid_spacing, pml_size, pml_alpha, Nt, dt, c_ref) \n%\n% INPUTS:\n%       filename            - filename and location of the input HDF5 file\n%       grid_size           - [Nx, Ny, Nz]\n%       grid_spacing        - [dx, dy, dz]\n%       pml_size            - [pml_x_size, pml_y_size, pml_z_size]\n%       pml_alpha           - [pml_x_alpha, pml_y_alpha, pml_z_alpha]\n%       Nt                  - number of time points\n%       dt                  - time step\n%       c_ref               - scalar sound speed used in the k-space\n%                             operator and to define the pml variables\n%\n% ABOUT:\n%       author              - Bradley Treeby\n%       date                - 30th May 2013\n%       last update         - 21st August 2014\n%       \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n%\n% See also h5writeatt, writeAttributes, writeFlags, writeMatrix\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 <http://www.gnu.org/licenses/>. \n\n%#ok<*INUSL>\n%#ok<*NASGU>\n\n% get literals\ngetH5Literals;\n\n% unpack grid size inputs to make code easier to read\nNx          = grid_size(1);\nNy          = grid_size(2);\nNz          = grid_size(3);\ndx          = grid_spacing(1);\ndy          = grid_spacing(2);\ndz          = grid_spacing(3);\npml_x_size  = pml_size(1);\npml_y_size  = pml_size(2);\npml_z_size  = pml_size(3);\npml_x_alpha = pml_alpha(1);\npml_y_alpha = pml_alpha(2);\npml_z_alpha = pml_alpha(3);\n\n% =========================================================================\n% CREATE WAVENUMBER AND PML VECTORS\n% =========================================================================\n\n% create the wavenumber grids (assuming Nx, Ny and Nz are even)\nnx = ((-Nx/2:Nx/2-1)/Nx).';\nnx(floor(Nx/2) + 1) = 0;\nkx_vec = (2*pi/dx).*nx; \n\nny = ((-Ny/2:Ny/2-1)/Ny).';\nny(floor(Ny/2) + 1) = 0;\nky_vec = (2*pi/dy).*ny; \n\nnz = ((-Nz/2:Nz/2-1)/Nz).';\nnz(floor(Nz/2) + 1) = 0;\nkz_vec = (2*pi/dz).*nz; \n\n% force the vector operators be in the correct direction (Nx, 1, 1), (1, Ny, 1), (1, 1, Nz) \nky_vec = ky_vec.'; \nkz_vec = permute(kz_vec, [2 3 1]);\n\n% create vector derivative and shift variables\nddx_k_shift_pos = ifftshift( 1i*kx_vec .* exp( 1i*kx_vec*dx/2), 1);\nddx_k_shift_neg = ifftshift( 1i*kx_vec .* exp(-1i*kx_vec*dx/2), 1);\nddy_k_shift_pos = ifftshift( 1i*ky_vec .* exp( 1i*ky_vec*dy/2), 2); \nddy_k_shift_neg = ifftshift( 1i*ky_vec .* exp(-1i*ky_vec*dy/2), 2);\nddz_k_shift_pos = ifftshift( 1i*kz_vec .* exp( 1i*kz_vec*dz/2), 3);\nddz_k_shift_neg = ifftshift( 1i*kz_vec .* exp(-1i*kz_vec*dz/2), 3);\n    \n% create vector shift operators\nx_shift_neg = ifftshift( exp(-1i*kx_vec*dx/2), 1);\ny_shift_neg = ifftshift( exp(-1i*ky_vec*dy/2), 2);\nz_shift_neg = ifftshift( exp(-1i*kz_vec*dz/2), 3);\n\n% create reduced variables for use with real-to-complex FFT\nNx_r                    = floor(Nx/2) + 1;\nNy_r                    = floor(Ny/2) + 1;\nNz_r                    = floor(Nz/2) + 1;\nddx_k_shift_pos_r       = ddx_k_shift_pos(1:Nx_r);\nddx_k_shift_neg_r       = ddx_k_shift_neg(1:Nx_r);\nx_shift_neg_r           = x_shift_neg(1:Nx_r);\ny_shift_neg_r           = y_shift_neg(1:Ny_r);\nz_shift_neg_r           = z_shift_neg(1:Nz_r);\n\n% create vector PML variables\npml_x       = getPML(Nx, dx, dt, c_ref, pml_x_size, pml_x_alpha, false, 1);\npml_x_sgx   = getPML(Nx, dx, dt, c_ref, pml_x_size, pml_x_alpha, true,  1);\npml_y       = getPML(Ny, dy, dt, c_ref, pml_y_size, pml_y_alpha, false, 2);\npml_y_sgy   = getPML(Ny, dy, dt, c_ref, pml_y_size, pml_y_alpha, true,  2);\npml_z       = getPML(Nz, dz, dt, c_ref, pml_z_size, pml_z_alpha, false, 3);\npml_z_sgz   = getPML(Nz, dz, dt, c_ref, pml_z_size, pml_z_alpha, true,  3);\n\n% cleanup unused variables\nclear ddx_k_shift_pos ddx_k_shift_neg x_shift_neg y_shift_neg z_shift_neg;\n\n% =========================================================================\n% STORE FLOATS\n% =========================================================================\n\n% list of variables stored as floats\nvariable_names = {...\n    'dt', 'dx', 'dy', 'dz', ...\n    'ddx_k_shift_pos_r', 'ddx_k_shift_neg_r', 'x_shift_neg_r', ...\n    'ddy_k_shift_pos',   'ddy_k_shift_neg',   'y_shift_neg_r', ...\n    'ddz_k_shift_pos',   'ddz_k_shift_neg',   'z_shift_neg_r', ...\n    'pml_x_sgx',   'pml_y_sgy',   'pml_z_sgz', ...\n    'pml_x',       'pml_y',       'pml_z', ...\n    'pml_x_alpha', 'pml_y_alpha', 'pml_z_alpha', ...\n    'c_ref'};\n\n% change float variables to be in single precision (float in C++), then\n% add to HDF5 file\nfor index = 1:length(variable_names)\n\n    % cast matrix to single precision\n    eval([variable_names{index} ' = ' MATRIX_DATA_TYPE_MATLAB '(' variable_names{index} ');']);\n\n    % write to HDF5 file\n    writeMatrix(filename, eval(variable_names{index}), variable_names{index});\n\nend\n\n% =========================================================================\n% STORE INTEGERS\n% =========================================================================\n\n% integer variables\nvariable_names = {'Nx', 'Ny', 'Nz', 'Nt',...\n    'pml_x_size' , 'pml_y_size' , 'pml_z_size'};\n\n% change all the index variables to be in 64-bit unsigned integers (long in C++)\nfor index = 1:length(variable_names)\n\n    % cast matrix to 64-bit unsigned integer\n    eval([variable_names{index} ' = ' INTEGER_DATA_TYPE_MATLAB '(' variable_names{index} ');']);\n\n    % write to HDF5 file\n    writeMatrix(filename, eval(variable_names{index}), variable_names{index});\n\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/writeGrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5983862085148126}}
{"text": "function []=Rotor(be,th,ze)% be=[0 10 2];\n% th=[0 12 8];\n% ze=[0 0 0];\n\n\n\nload NACA632_615.txt;\nxy=NACA632_615;\n\nx=xy(:,1);\ny=xy(:,2);\n\nrR=10;\nR=100;\nSpar_Loc=[2*3.5;0;2*0.3];\n\nx=x/5-Spar_Loc(1);\ny=y/5-Spar_Loc(3);\nx=[x;x(1)];\ny=[y;y(1)];\n\ndeg=pi/180;\nb=be*deg;\nt=th*deg;\nz=ze*deg;\n\nbeta=inline('b1+b2*cos(psi)+b3*sin(psi)','b1','b2','b3','psi');\nzeta=inline('z1+z2*cos(psi)+z3*sin(psi)','z1','z2','z3','psi');\ntheta=inline('t1+t2*cos(psi)+t3*sin(psi)','t1','t2','t3','psi');\n\npsi=linspace(0,2*pi,50);\nn=10;\nr=linspace(0,100,n);\n\n[rr ssi]=meshgrid(r,psi);\n\nbbb=beta(b(1),b(2),b(3),ssi);\nzzz=zeta(z(1),z(2),z(3),ssi);\n\nxx=rr.*cos(bbb).*cos(ssi-zzz);\nyy=rr.*cos(bbb).*sin(ssi-zzz);\nzz=rr.*sin(bbb);\n\n\nzmin=-15;\nzmax=max(max(zz));\n\nRotor_Cone=surf(xx,yy,zz,repmat(7,size(zz)),'FaceAlpha',0);   % handle !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nset(Rotor_Cone,'Visible','off')\nhold on\nHP=fill( 100*cos(psi),100*sin(psi),'w' );                       % handle !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nset(HP,'FaceAlpha',0)\nset(HP,'Visible','off')\n\nTPP=fill3(xx(:,n),yy(:,n),zz(:,n),'g','FaceAlpha',0.5);         % handle !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nset(TPP,'Visible','off')\n\nNFP=fill3( 100*cos(psi),100*sin(psi),zeros(size(psi)),'m' ,'FaceAlpha',0.5); \nrotate(NFP,[1 0 0],th(2),[0 0 0])\nrotate(NFP,[0 1 0],th(3),[0 0 0])\nset(NFP,'Visible','off')\n\n\nHP_Cross(1)=plot3([-100 100],[0 0],[0 0]);\nHP_Cross(2)=plot3([0 0],[-100 100],[0 0]);\nset(HP_Cross,'Color','y','Linewidth',2)\nset(HP_Cross,'Visible','off')\n\n% ############################################## Plot limits ####################################################################\nxlim([-100 100])\nylim([-100 100])\nzlim([zmin zmax])\n\n\n[Rotor_Shaft(1) Rotor_Shaft(2) Rotor_Shaft(3)]=Cylinder( [0 0 0],2.5,zmin,'z',15,'closed' );\nset(Rotor_Shaft,'FaceColor','w')\nset(Rotor_Shaft,'Visible','off')\n\n\n[XAXIS(1) XAXIS(2) XAXIS(3)]=arrow3d( [0 0 0.5]',0.5,90,8,'x');\n[YAXIS(1) YAXIS(2) YAXIS(3)]=arrow3d( [0 0 0.5]',0.5,90,8,'y');\n[ZAXIS(1) ZAXIS(2) ZAXIS(3)]=arrow3d( [0 0 0.5]',0.5,40,4,'z');\n\nXAXIS(4)=text(110,0,0,'X','Color','r','FontSize',12);\nYAXIS(4)=text(0,110,0,'Y','Color','r','FontSize',12);\nZAXIS(4)=text(0,0,zmax+10,'Z','Color','r','FontSize',12);\n\n\n\nset(XAXIS(1),'FaceColor','k','EdgeAlpha',0)\nset(XAXIS(2),'FaceColor','r')\nset(XAXIS(3),'FaceColor','k')\n\nset(YAXIS(1),'FaceColor','k','EdgeAlpha',0)\nset(YAXIS(2),'FaceColor','r')\nset(YAXIS(3),'FaceColor','k')\n\nset(ZAXIS(1),'FaceColor','k','EdgeAlpha',0)\nset(ZAXIS(2),'FaceColor','r')\nset(ZAXIS(3),'FaceColor','k')\n\nset(XAXIS,'Visible','off')\nset(YAXIS,'Visible','off')\nset(ZAXIS,'Visible','off')\n\n\nPSI=0:10:360;\n\nTargetx=100*cos(PSI*pi/180);\nTargety=100*sin(PSI*pi/180);\nlooktarget=plot3(Targetx',zeros(size(Targetx')),Targety',Targetx',Targety',zeros(size(Targetx')),zeros(size(Targetx')),Targetx',Targety');\nset(looktarget,'Visible','off')\n\nBETA(1,:)=beta(b(1),b(2),b(3),PSI*deg);\nTHETA(1,:)=theta(t(1),t(2),t(3),PSI*deg);\nZETA(1,:)=zeta(z(1),z(2),z(3),PSI*deg);\n\ntr=[t(1) t(2)-b(3) b(2)+t(3)];\nbr=[b(1) 0 0];\nzr=z;\n            \nBETA(2,:)=beta(br(1),br(2),br(3),PSI*deg);\nTHETA(2,:)=theta(tr(1),tr(2),tr(3),PSI*deg);\nZETA(2,:)=zeta(zr(1),zr(2),zr(3),PSI*deg);\n\nbr=[b(1) b(2)+t(3) b(3)-t(2)];\ntr=[t(1) 0 0];\nzr=z;\n\nBETA(3,:)=beta(br(1),br(2),br(3),PSI*deg);\nTHETA(3,:)=theta(tr(1),tr(2),tr(3),PSI*deg);\nZETA(3,:)=zeta(zr(1),zr(2),zr(3),PSI*deg);\n\nfor i=1:37;\n    Blade_Disk(i,:)=Make_Blade(x,y,rR,R,PSI(i),THETA(1,i)/deg,BETA(1,i)/deg,ZETA(1,i)/deg);\n    set(Blade_Disk(i,:),'Visible','off')\n    \n    \n    a_HP(i,1)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0,['HP: \\psi = ' num2str(PSI(i)) ],'Color','k','FontSize',12);\n    a_HP(i,2)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0-10,['HP: \\beta = ' num2str(BETA(1,i)/deg) ],'Color','r','FontSize',12);\n    a_HP(i,3)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0+10,['HP: \\theta = ' num2str(THETA(1,i)/deg) ],'Color','m','FontSize',12);\n    a_HP(i,4)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0+20,['HP: \\zeta = ' num2str(ZETA(1,i)/deg) ],'Color','b','FontSize',12);\n    set(a_HP(i,:),'Visible','off')\n\n    \n    a_TPP(i,1)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0,['TPP: \\psi = ' num2str(PSI(i))],'Color','k','FontSize',12);\n    a_TPP(i,2)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0-10,['TPP: \\beta = ' num2str(BETA(2,i)/deg) ],'Color','r','FontSize',12);\n    a_TPP(i,3)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0+10,['TPP: \\theta = ' num2str(THETA(2,i)/deg) ],'Color','m','FontSize',12);\n    a_TPP(i,4)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0+20,['TPP: \\zeta = ' num2str(ZETA(2,i)/deg) ],'Color','b','FontSize',12); \n    set(a_TPP(i,:),'Visible','off')\n    \n    a_NFP(i,1)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0,['NFPP: \\psi = ' num2str(PSI(i)) ],'Color','k','FontSize',12);\n    a_NFP(i,2)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0-10,['NFPP: \\beta = ' num2str(BETA(3,i)/deg) ],'Color','r','FontSize',12);\n    a_NFP(i,3)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0+10,['NFPP: \\theta = ' num2str(THETA(3,i)/deg) ],'Color','m','FontSize',12);\n    a_NFP(i,4)=text(90*cos(PSI(i)*deg),90*sin(PSI(i)*deg),0+20,['NFPP: \\zeta = ' num2str(ZETA(3,i)/deg) ],'Color','b','FontSize',12); \n    set(a_NFP(i,:),'Visible','off')\nend\n    \n\naxis equal\naxis off\n\ndaspect([1 1 1])\ndaspect('manual')\ncamlookat(looktarget)\ncamzoom(1.5)\n\nsave para Rotor_Shaft HP TPP Rotor_Cone  HP_Cross XAXIS YAXIS ZAXIS Blade_Disk NFP a_HP a_TPP a_NFP\n\nsave looktargetfile looktarget", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/12502-helicopter-rotor-motion-simulator/CollectiveAndCyclic/Rotor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.598386190484296}}
{"text": "function [dVVectNTW] = getNTWdvVect(dVVect, rVect, vVect)\n%getNTWdvVect Summary of this function goes here\n%   Detailed explanation goes here\n    vVect = reshape(vVect, 3,1);\n    dVVect = reshape(dVVect, 3,1);\n    \n    tHat = vVect/norm(vVect);\n    wHat = cross(rVect,vVect)/norm(cross(rVect,vVect));\n    nHat = cross(tHat,wHat)/norm(cross(tHat,wHat));\n    ECI2TWNRotMat = [tHat,wHat,nHat];\n    dVVectNTW = ECI2TWNRotMat \\ dVVect;\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/astrodynamics/getNTWdvVect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5983619453873034}}
{"text": "function [ y, symm ] = cvx_s_symmetric_ut( m, n, symm )\n%CVX_S_SYMMETRIC_UT Symmetric matrices (upper triangle storage).\nif m ~= n,\n    error( 'Symmetric structure requires square matrices.' );\nend\nsymm = false;\nnsq = n * n;\nntr = 0.5 * ( nsq + n );\nc   = 0 : n - 1;\nc   = c( ones( 1, n ), : );\nr   = c';\nmn  = min( r, c );\nmx  = max( r, c );\ny   = mn + 0.5 * mx .* ( mx + 1 ) + 1;\ny   = sparse( y( : ), 1 : nsq, 1, ntr, nsq );\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/structures/cvx_s_symmetric_ut.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5983448956613228}}
{"text": "function Ar = sladd(A0, As, d)\n%SLADD Add a sub-array along some dimensions to an array\n%\n% $ Syntax $\n%   - Ar = sladd(A0, As)\n%   - Ar = sladd(A0, As, d)\n%\n% $ Arguments $\n%   - A0:           the original array\n%   - v:            the sub-array to be added to the array\n%   - Ar:           the resultant array\n%   - d:            the dimension along which the vector is added\n%\n% $ Description $\n%   - Ar = sladd(A0, As) adds the sub-array As to the array A0 along \n%     auto-selected dimensions. The dimensions are identified by the \n%     dimension of As with size larger than 1. If As is a scalar, then \n%     all elements of A0 will be added As.\n%   \n%   - Ar = sladd(A0, As, d) adds the sub-array As to the array A0 along\n%     the dimensions specified by d. \n%\n% $ Remarks $\n%   # An empty As is allowed. In such case, the original array A0 will\n%     be output, i.e. Ar = A0.\n%   # The sizes of dimensions along which the sub-array is added should\n%     match that of A0, otherwise, an error will be raised.\n%   # By specifying the dimensions through d, the speed can be accelerated.\n%\n% $ Examples $\n%   - Add a vector to a matrix.\n%     \\{\n%         A = [1 2 3; 4 5 6];\n%         v = [2; 5];\n%         Ar = sladd(A, v)\n%     \n%         Ar = \n%\n%             3     4     5         \n%             9    10    11\n%\n%     \\}\n%     It is equivalent to sladd(A, v, 1).\n%\n%  - Add a plane to a matrix\n%    \\{\n%        A1 = [1 2 3; 4 5 6];\n%        A2 = [7 8 9; 10 11 12];\n%        A = cat(3, A1, A2);\n%        v1 = [10; 20];\n%        v2 = [30; 40];\n%        As = cat(3, v1, v2)\n%\n%        Ar(:, :, 1) = \n%            \n%            11    12    13\n%            24    25    26\n%\n%        Ar(:, :, 2) = \n%\n%            37    38    39\n%            50    51    52\n%\n%    \\}\n%\n% $ History $\n%   - Created by Dahua Lin on Nov 18th, 2005\n%\n\n%% parse and verify input\nif nargin < 2\n    raise_lackinput('sladd', 2);\nend\nif isempty(As)\n    Ar = A0;\n    return;\nend\nif ndims(As) > ndims(A0)\n    error('sltoolbox:dimoverflow', ...\n        'The dimension of As should not be larger than that of A0');\nend\nif nargin < 3 || isempty(d)\n    % d is not specified, automatically determine d\n    d = find(size(As) > 1);\nend\nsiz_A0 = size(A0);\nsiz_As = size(As);\nif ~isequal(siz_A0(d), siz_As(d))\n    error('sltoolbox:dimmismatch', ...\n        'The dimensions of As does not match that of A0 in the dimensions to be added');\nend\n\n%% compute\nsiz_A0(d) = 1;\nAr = A0 + repmat(As, siz_A0);\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/core/sladd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.5983448938394036}}
{"text": "function [ kn, fn, wn ] = r4_nor_setup ( )\n\n%*****************************************************************************80\n%\n%% R4_NOR_SETUP sets data needed by R4_NOR.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 October 2013\n%\n%  Author:\n%\n%    Original C version by George Marsaglia, Wai Wan Tsang\n%    MATLAB version by John Burkardt\n%\n%  Reference:\n%\n%    George Marsaglia, Wai Wan Tsang,\n%    The Ziggurat Method for Generating Random Variables,\n%    Journal of Statistical Software,\n%    Volume 5, Number 8, October 2000, seven pages.\n%\n%  Parameters:\n%\n%    Output, uint32 KN(128), data needed by R4_NOR.\n%\n%    Output, real FN(128), WN(128), data needed by R4_NOR.\n%\n  kn = zeros ( 128, 'uint32' );\n  fn = zeros ( 128 );\n  wn = zeros ( 128 );\n\n  m1 = 2147483648.0;\n  vn = 9.91256303526217E-03;\n\n  dn = 3.442619855899;\n  tn = 3.442619855899;\n\n  q = vn / exp ( - 0.5 * dn * dn );\n  kn(1) = uint32 ( ( dn / q ) * m1 );\n  kn(2) = 0;\n\n  wn(1) = q / m1;\n  wn(128) = dn / m1;\n\n  fn(1) = 1.0;\n  fn(128) = exp ( - 0.5 * dn * dn );\n\n  for i = 127 : -1 : 2\n    dn = sqrt ( - 2.0 * log ( vn / dn + exp ( - 0.5 * dn * dn ) ) );\n    kn(i+1) = uint32 ( ( dn / tn ) * m1 );\n    tn = dn;\n    fn(i) = exp ( - 0.5 * dn * dn );\n    wn(i) = dn / m1;\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/ziggurat/r4_nor_setup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5983377853747127}}
{"text": "%   TTeMPS Toolbox. \n%   Michael Steinlechner, 2013-2016\n%   Questions and contact: michael.steinlechner@epfl.ch\n%   BSD 2-clause license, see LICENSE.txt\n\nfunction X = construct_initial_guess(L, F, r, n)\n% Basicially only the first micro-step of ALS\n\nX = TTeMPS_rand( r, n );\nX = 1/norm(X) * X;\n\n\nd = X.order;\nn = X.size;\n\n\nX = orthogonalize(X, 1);\nFi = contract( X, F, 1 );\nsz = [X.rank(1), X.size(1), X.rank(2)];\n\n[left, right] = Afun_prepare( L, X, 1 );\nB1 =  prepare_precond( L.A{1}, X, 1 );\n\nUi = pcg( @(y) Afun( L, y, 1, sz, left, right), ...\n         Fi(:), ...\n         1e-10, 1000, ...\n         @(y) apply_precond( L.A{1}, B1, y, sz ), [],...\n         X.U{1}(:) ); \n\nX.U{1} = reshape( Ui, sz );\n\nX = orth_at( X, 1, 'left', true );\n\n\nend\n\n\n\n\nfunction [left, right] = Afun_prepare( A, x, idx )\n    y = A.apply(x); \n    if idx == 1\n        right = innerprod( x, y, 'RL', idx+1 );\n        left = [];\n    elseif idx == x.order\n        left = innerprod( x, y, 'LR', idx-1 );\n        right = [];\n    else\n        left = innerprod( x, y, 'LR', idx-1 );\n        right = innerprod( x, y, 'RL', idx+1 ); \n    end\nend\n\nfunction res = Afun( A, U, idx, sz, left, right )\n\n    V = reshape( U, sz );\n    V = A.apply( V, idx );\n    \n    if idx == 1\n        tmp = tensorprod_ttemps( V, right, 3 );\n    elseif idx == A.order\n        tmp = tensorprod_ttemps( V, left, 1 );\n    else\n        tmp = tensorprod_ttemps( V, right, 3);\n        tmp = tensorprod_ttemps( tmp, left, 1);\n    end\n\n    res = tmp(:);\nend\n\n\nfunction B1 = prepare_precond( L0, X, idx )\n\n    if idx == 1\n        B1 = [];\n        return\n    end\n\n    n = size(L0, 1);\n    r = X.rank;\n\n    X1 = matricize( X.U{1}, 2);\n    Y = X;\n    Y.U{1} = tensorize( L0*X1, 2, [r(1), n(1), r(2)] );\n    B1 = innerprod( X, Y, 'LR', idx-1);\nend\n\nfunction res = apply_precond( L0, B1, rhs, sz )\n    \n    n = size(L0, 1);\n    rhs = reshape( rhs, sz );\n    if isempty(B1) %idx == 1\n        res = L0 \\ unfold( rhs, 'left' );\n        res = reshape( res, sz );\n    else\n        res = B1 \\ unfold(rhs, 'right');\n        res = reshape( res, sz );\n    end\n    res = res(:);\nend\n\n\n\n\n\n\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/algorithms/linearsystem/construct_initial_guess_rankOne.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5983377801859839}}
{"text": "function features = feature_extraction( x_flt, CSP, oldSMC, verbose )\n% x_flt: cell(2, numsamples) : 2-class\n%           x_flt{1, i} = [nChannels, nSamples, nTrials]\n\nif verbose == 1\n%     fprintf( '\\tFeature Extraction...\\n\\t\\t' );\nend\n\n[nclass, nparticles] = size( x_flt );\nfeatures = cell( nclass, nparticles );\n\nfor i=1:oldSMC.numBands\n    if verbose == 1\n        if mod(i, 5) == 0\n%             fprintf( '%d', i );\n        else\n%             fprintf( '.' );\n        end\n        if mod(i, 100) == 0\n%             fprintf( '\\n' );\n        end\n    end\n    \n    for k=1:nclass\n        [nc, ns, nt] = size( x_flt{k, i} );\n        temp = reshape( x_flt{k, i}, [nc, ns*nt] );\n        temp = CSP{i}.W' * temp;\n        temp = reshape( temp, [size(temp, 1), ns, nt] );\n        temp = permute( temp, [2 1 3] );\n        features{k, i} = squeeze( log(var(temp, 0, 1)) );\n    end\nend\n% fprintf( '\\n' );", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/GigaScience/function_MI/bssfo/original/feature_extraction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5983377798074329}}
{"text": "function [matrix_data] = Dvec2Dmat(vector_data,WIDTH,LENGTH,IND,nodata)\n% function which converts a vector to a matrix:\n% option 1: WIDTH only where it is assumed that the original grid was \n%                  made using vector = reshape(matrix,[],1);\n% option 2: WIDTH, LENGTH, IND where the IND has the same length as the vector_data\n%                  and where IND relates to the positon in a matrix. Note\n%                  that this method allows for a mask file to be included.\n%                  You can use the matlab function IND = sub2ind([WIDTH LENGTH], I, J)\n%                  to generate the IND variable\n% nodata argument is optional and us used to fill the nodata. By default\n% this is a NaN.\n%\n%     Copyright (C) 2016  Bekaert David \n%     davidbekaert.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 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 along\n%     with this program; if not, write to the Free Software Foundation, Inc.,\n%     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n%\n% Bekaert David  \n% modifications:\n% 8/10/2016     DB  Add nodata option\n\n\n%  checking of the input arguments\nmethod =1;          % this is the width method\nif nargin <2\n    error(['Expecting two inputs: vector_data and WIDTH'])\nend\nif nargin>2 && nargin<4\n    fprintf('WARNING: you need to specify 4 inputs when planning on using IND option, will fall back on width only \\n')\nend\nif length(WIDTH)~=1\n    error('WIDTH is given incorrect')\nend\nif nargin >=4\n   if isempty(LENGTH) || isempty(IND) \n       error('You need to specify LENGTH and IND') \n   end\n   if length(LENGTH)~=1\n       error('LENGTH is given incorrect')\n   end\n   if length(IND)~=length(vector_data)\n       error('Length of vector_data and IND needs to be consistent')\n   end\n   method = 2;      % change to the width, length and ind method\nend\nif nargin<5\n    nodata=NaN;\nend\n\n\n%% storing the data again\nif method ==1\n    matrix_data = reshape(vector_data,WIDTH,[]);\nelseif method ==2\n    if isnan(nodata)\n        matrix_data = NaN([WIDTH LENGTH]);\n    elseif nodata==0\n        matrix_data = zeros([WIDTH LENGTH]);\n    else\n        matrix_data = ones([WIDTH LENGTH]).*nodata;\n    end\n    matrix_data(IND)= vector_data;\nend\n\n", "meta": {"author": "dbekaert", "repo": "TRAIN", "sha": "6c93feb95ae95eaf4c8468e89ec0b8325eac946f", "save_path": "github-repos/MATLAB/dbekaert-TRAIN", "path": "github-repos/MATLAB/dbekaert-TRAIN/TRAIN-6c93feb95ae95eaf4c8468e89ec0b8325eac946f/matlab/Dvec2Dmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5983377798074329}}
{"text": "function rs = realifft(data, N)\n\n% inverse fft for fourier coefficents from real valued  original data\n% needs the length of the original time series from which the fft was computed\n% see also : realfft\n\ndata = data(:);\nif mod(N,2) \t% odd length\n\tdata = [data ; conj(data(end:-1:2))];  \nelse\t\t\t% even length\n\tdata = [data ; conj(data(end-1:-1:2))];  \nend \n\nrs = real(ifft(data)); % remove small imaginary components introduced by rounding errors\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/realifft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5983377794288814}}
{"text": "function prepare_data_gt(input_files, output_file_name, pca_dim)\n\n%load the hyperspectral data\nmat_load=load(input_files.data_file);\nfields=fieldnames(mat_load);\nfields=fields{1};\nim=getfield(mat_load,fields);\n\n%load the labels\ngt_load=load(input_files.gt_file);\nfields=fieldnames(gt_load);\nfields=fields{1};\nip_gt=getfield(gt_load,fields);\n\n%get statistics of the data\n[h,w,ch]=size(im)\nnum_pix=length(find(ip_gt>0));%h*w;\n\nim_cen=im;\n\n%pad the im_cen\nconv_size=5;\npad_no=(conv_size-1)/2;\n\n%padded image\nim_X=zeros(h+2*pad_no,w+2*pad_no,ch);\nfor i=1:ch\n    im_i=im_cen(:,:,i);\n    im_X(:,:,i)=padarray(im_i,[pad_no,pad_no],'symmetric');\nend\n\nip_gt_pad=padarray(ip_gt,[pad_no,pad_no],'symmetric');\n\ncnt=1;\nX=zeros(num_pix,ch,conv_size,conv_size);\nlabels=zeros(num_pix,1);\nverbose=false;\n\nfor y=1:h\n    fprintf('\\nRow num=%d of %d',y,h);\n    for x=1:w\n        if ip_gt(y,x)>0\n             X(cnt,:,:,:)=permute(im_X(y:y+conv_size-1,x:x+conv_size-1,:),...\n                [3,1,2]);\n            labels(cnt)=ip_gt(y,x);\n\n            if verbose\n                figure(1);\n                imagesc(ip_gt_pad);\n                rectangle('Position',[x y conv_size conv_size],...\n                    'EdgeColor','r','linewidth',2);\n                title(sprintf('Label=%d',labels(cnt)));\n            end\n            drawnow;\n            pause(0.01);\n            cnt=cnt+1;\n        end\n    end\nend\n\n\ncomp=pcExtract(permute(X,[2,1,3,4]),pca_dim);\nX_r=permute(comp,[2,1,3,4]);\n\n\nsave(output_file_name,'X_r','labels','ip_gt','im','-v7.3');\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u7c7b\u7b97\u6cd5/deephypercnn-master/Matlab-Sat-Data/prepare_data_gt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5983377742401528}}
{"text": "function [w, b] = Train_SVR(samples, labels)\n%Train_SVR creating a linear support vector regressor\n     \n    % liblinear training\n    addpath('C:\\liblinear\\matlab');\n      \n    % Remove redundant data\n    [samples, inds] = unique(samples, 'rows');\n    labels = labels(inds,:);\n    \n    cmd = ['-s 11 -B 1 -q'];\n    \n    svr_regressor = train(labels, sparse(double(samples)), cmd);\n\n    w = svr_regressor.w(1:end-1)';\n    b = svr_regressor.w(end);\n    \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/patch_experts/svr_training/Train_SVR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5982901597437614}}
{"text": "% =========================================================================\n% This code is part of the Matlab-based toolbox \n% LagLDDDM - A Lagrangian Gauss--Newton--Krylov Solver for Mass- and \n%                        Intensity-Preserving Diffeomorphic Image Registration\n% \n% For details and license info see \n% - https://github.com/C4IR/FAIR.m/tree/master/add-ons/LagLDDMM\n%\n% 2D Multilevel Mass-Preserving LDDMM Example using stationary velocity\n% field and diffusion regularizer as described in Sec. 4 of the paper:\n%\n% @article{MangRuthotto2017,\n%   Title = {A {L}agrangian {G}auss--{N}ewton--{K}rylov solver for mass- and intensity-preserving diffeomorphic image registration},\n%   Year = {2017},\n%   Journal = {SIAM Journal on Scientific Computing},\n%   Author = {A. Mang, L. Ruthotto},\n% }\n%\n% =========================================================================\nclose all; clc; clear all;\nsetup3DmouseData;\nalpha = [50 0];\nlvl = 4;\npad = 0;\nmV = @(m) m;\nnt = 0;\nN  = 2;\nminLevel = 4;\nmaxLevel = 6;\nimgModel('reset','imgModel','linearInterMex')\n% 1) setup grid for velocities (padded)\nomegaV = omega; omegaV(1:2:end) = omegaV(1:2:end)-pad;  omegaV(2:2:end) = omega(2:2:end)+pad;\n\n% 2) setup regularizer (and decide for stationary or nonstationary velocity)\nregularizer('reset','regularizer','mfDiffusionCC','alpha',alpha,'nt',nt,'HessianShift',1e-2); % nonstationary velocity\n\n%%\nplots = 1;\nNPIRpara    = optPara('NPIR-GN');\nNPIRpara.maxIter = 40;\nNPIRpara.scheme = @GaussNewtonLDDMM;\n\n[vc,~,wc,his] = MLLDDMM(ML,'minLevel',minLevel,'maxLevel',maxLevel,'omegaV',omegaV,...\n    'mV',mV,'N',N,'parametric',0,'plots',plots,'NPIRpara',NPIRpara,'NPIRobj',@MPLDDMMobjFctn);\nswitch regularizer\n    case {'mfDiffusionST','mfCurvatureST'}\n        yInv = getTrafoFromInstationaryVelocityRK4(vc,getNodalGrid(omega,m),'omega',omegaV,'m',m,'N',N,'nt',nt,'tspan',[1 0]);\n    case {'mfDiffusionCC','mfCurvatureCC'}\n        yInv = getTrafoFromVelocityRK4(vc,getNodalGrid(omega,m),'omega',omegaV,'m',m,'N',N,'tspan',[1 0]);\n        nt = 0;\nend\n\n%%\nyc = getTrafoFromVelocityRK4(vc,getNodalGrid(omega,m),'omega',omegaV,'m',m,'nt',nt,'tspan',[1,0],'N',N);\nJac = geometry(yInv,m,'Jac','omega',omega);\nTopt = linearInterMex(dataT,omega,center(yInv,m)) .* Jac;\nD0  = distance(dataT(:),dataR(:),omega,m);\nDOpt = distance(Topt(:),dataR(:),omega,m);\n\nfig = figure(); clf;\nfig.Name = sprintf('Results for %s',mfilename);\n\nsubplot(2,3,1);\nviewImage(dataR,omega,m);\ntitle('reference');\n\nsubplot(2,3,4);\nviewImage(dataT,omega,m);\ntitle('template');\n\nsubplot(2,3,2);\nviewImage(Topt,omega,m);\ntitle('T(yc)')\n\nsubplot(2,3,3);\nimgmontage(dataT(:)-dataR(:),omega,m);\ntitle('init. residual, SSD=100%');\n\nsubplot(2,3,5);\nimgmontage(Jac,omega,m);\ntitle(sprintf('Jac, min=%1.2f max=%1.2f',min(Jac(:)),max(Jac(:))));\n\nsubplot(2,3,6);\nimgmontage(Topt(:)-dataR(:),omega,m);\ntitle(sprintf('opt residual, SSD=%1.2f%%',100*DOpt/D0));", "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/add-ons/LagLDDMM/examples/EMPLDDMM_3Dmouse_mfDiffusionCC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5982901547392484}}
{"text": "function [PC,CC,DC,IC] = trim_with_spline(PA,CA,PB,CB,tol)\n  % TRIM_WITH_SPLINE Trim a given spline (PA,CA) with a \"solid\" spline (PB,CB)\n  %\n  % [PC,CC,DC,IC] = trim_with_spline(PA,CA,PB,CB,tol)\n  %\n  % Inputs:\n  %   PA  #PA by dim list of control point locations\n  %   CA  #CA by 4 list of indices into PA of cubic Bezier curves\n  %   PB  #PB by dim list of control point locations\n  %   CB  #CB by 4 list of indices into PB of cubic Bezier curves\n  %   tol  tolerance for intersection {1e-7}\n  % Outputs:\n  %   PC  #PC by dim list of control point locations\n  %   CC  #CC by 4 list of indices into PC of cubic Bezier curves\n  %   DC  #CC list of flags whether inside B\n  %   IC  #CC list of indices into CA\n  %\n\n  function [PA,CA,DA,IA] = trim_with_spline_helper(PA,CA,PB,CB)\n\n    [A1,A2] = box_each_element(PA,CA);\n    [B1,B2] = box_each_element(PB,CB);\n    I = box_intersect(A1,A2,B1,B2);\n    T = cell(size(CA,1),1);\n    % consider each intersection, gather splits\n    for ii = 1:size(I,1)\n      ca = I(ii,1);\n      cb = I(ii,2);\n      Tii = cubic_cubic_intersect(PA(CA(ca,:),:),PB(CB(cb,:),:),tol);\n      if ~isempty(Tii)\n        T{ca} = [T{ca};Tii(:,1)];\n      end\n    end\n    % conduct all splits\n    IA = (1:size(CA,1))';\n    for ca = 1:size(CA,1)\n      if ~isempty(T{ca})\n        Tca = sort(T{ca});\n        [PAa,CAa] = cubic_subdivide(PA(CA(ca,:),:),Tca);\n        CAa = reshape([CA(ca,1) CAa(2:end-1)+size(PA,1)-2 CA(ca,end)],size(CAa));\n        IA([ca size(CA,1)+(1:size(CAa,1)-1)],:) = IA(ca);\n        CA([ca size(CA,1)+(1:size(CAa,1)-1)],:) = CAa;\n        PA = [PA;PAa(3:end,:)];\n      end\n    end\n\n    %%fprintf('trim_with_spline...\\n');\n    %% loop order is imporant \n    %IA = (1:size(CA,1))';\n    %for cb = 1:size(CB,1)\n    %  %fprintf('  %04d/%04d:\\n',cb,size(CB,1));\n    %  for ca = 1:size(CA,1)\n    %    %progressbar(ca,size(CA,1));\n    %    T = cubic_cubic_intersect(PA(CA(ca,:),:),PB(CB(cb,:),:),tol);\n    %    if ~isempty(T)\n    %      [PAa,CAa] = cubic_subdivide(PA(CA(ca,:),:),T(:,1));\n    %      CAa = reshape([CA(ca,1) CAa(2:end-1)+size(PA,1)-2 CA(ca,end)],size(CAa));\n    %      IA([ca size(CA,1)+(1:size(CAa,1)-1)],:) = IA(ca);\n    %      CA([ca size(CA,1)+(1:size(CAa,1)-1)],:) = CAa;\n    %      PA = [PA;PAa(3:end,:)];\n    %    end\n    %  end\n    %end\n\n    % midpoints of each cubic\n    %fprintf('midpoints...\\n');\n    M = zeros(size(CA,1),2);\n    for ca = 1:size(CA,1)\n      M(ca,:) = cubic_eval(PA(CA(ca,:),:),0.5);\n    end\n    %fprintf('spline_winding_number...\\n');\n    DA = abs(spline_winding_number(PB,CB,M))>0.5;\n  end\n\n  m = size(CA,1);\n  embed = @(P,C) reshape(P(C,:),size(C,1),8);\n  CB8 = embed(PB,CB);\n  % In either direction\n  RB8 = embed(PB,fliplr(CB));\n  CA8 = embed(PA,CA);\n  % find perfect matches (only considering that every control point is exactly\n  % the same; not finding partial co-incidence )\n  [idx,dist] = rangesearch([CB8;RB8],CA8,0);\n  perfect = cellfun(@(i) ~isempty(i),idx);\n  JN = find(~perfect);\n  [PA,CN,DN,IN] = trim_with_spline_helper(PA,CA(JN,:),PB,CB);\n  CA = [CN;CA(perfect,:)];\n  JP = find(perfect);\n  IA = [JN(IN);JP];\n  DA = [DN;true(numel(JP),1)];\n  assert(size(CA,1) == numel(IA));\n  assert(max(IA) <= m);\n  assert(size(CA,1) == numel(DA));\n\n  % rename\n  PC = PA;\n  CC = CA;\n  DC = DA;\n  IC = IA;\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/trim_with_spline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5982901493180531}}
{"text": "function label = LSC(data,k,opts)\n% label = LSC(data,k,opts): Landmark-based Spectral Clustering\n% Input:\n%       - data: the data matrix of size nSmp x nFea, where each row is a sample\n%               point\n%       - k: the number of clusters\n%       opts: options for this algorithm\n%           - p: the number of landmarks picked (default 1000)\n%           - r: the number of nearest landmarks for representation (default 5)\n%           - numRep: the number of replicates for the final kmeans (default 10)\n%           - maxIter: the maximum number of iterations for final kmeans (default 100)\n%           - mode: landmark selection method, currently support\n%               - 'kmeans': use centers of clusters generated by kmeans (default)\n%               - 'random': use randomly sampled points from the original\n%                           data set \n%           The following parameters are effective ONLY in mode 'kmeans'\n%           - kmNumRep: the number of replicates for initial kmeans (default 1)\n%           - kmMaxIter: the maximum number of iterations for initial kmeans (default 5)\n% Output:\n%       - label: the cluster assignment for each point\n% Requre:\n%       litekmeans.m\n% Usage:\n%       data = rand([100,50]);\n%       label = LSC(data,10);\n%Reference:\n%\n%\t[1] Xinlei Chen, Deng Cai, \"Large Scale Spectral Clustering with\n%\tLandmark-Based Representation,\" AAAI 2011. \n%\n%   [2] Deng Cai, Xinlei Chen: Large Scale Spectral Clustering Via\n%   Landmark-Based Sparse Representation. IEEE Trans. Cybernetics 45(8):\n%   1669-1680 (2015)  \n%\n%   version 2.0 --Dec./2011 \n%   version 1.0 --Oct./2010 \n%\n%   Written by Xinlei Chen (endernewton AT gmail.com)\n%              Deng Cai (dengcai AT gmail.com)\n\n\n\n% Set and parse parameters\nif (~exist('opts','var'))\n   opts = [];\nend\n\n\np = 1000;\nif isfield(opts,'p')\n    p = opts.p;\nend\n\nr = 5;\nif isfield(opts,'r')\n    r = opts.r;\nend\n\nmaxIter = 100;\nif isfield(opts,'maxIter')\n    maxIter = opts.maxIter;\nend\n\nnumRep = 10;\nif isfield(opts,'numRep')\n    numRep = opts.numRep;\nend\n\nmode = 'kmeans';\nif isfield(opts,'mode')\n    mode = opts.mode;\nend\n\nnSmp=size(data,1);\n\n% Landmark selection\nif strcmp(mode,'kmeans')\n    kmMaxIter = 5;\n    if isfield(opts,'kmMaxIter')\n        kmMaxIter = opts.kmMaxIter;\n    end\n    kmNumRep = 1;\n    if isfield(opts,'kmNumRep')\n        kmNumRep = opts.kmNumRep;\n    end\n    [~,marks]=litekmeans(data,p,'MaxIter',kmMaxIter,'Replicates',kmNumRep);\n    clear kmMaxIter kmNumRep\nelseif strcmp(mode,'random')\n    indSmp = randperm(nSmp);\n    marks = data(indSmp(1:p),:);\n    clear indSmp\nelse\n    error('mode does not support!');\nend\n\n% Z construction\nD = EuDist2(data,marks);\n\nif isfield(opts,'sigma')\n    sigma = opts.sigma;\nelse\n    sigma = mean(mean(D));\nend\n\ndump = zeros(nSmp,r);\nidx = dump;\nfor i = 1:r\n    [dump(:,i),idx(:,i)] = min(D,[],2);\n    temp = (idx(:,i)-1)*nSmp+[1:nSmp]';\n    D(temp) = 1e100; \nend\n\ndump = exp(-dump/(2*sigma^2));\nsumD = sum(dump,2);\nGsdx = bsxfun(@rdivide,dump,sumD);\nGidx = repmat([1:nSmp]',1,r);\nGjdx = idx;\nZ=sparse(Gidx(:),Gjdx(:),Gsdx(:),nSmp,p);\n\n% Graph decomposition\nfeaSum = full(sqrt(sum(Z,1)));\nfeaSum = max(feaSum, 1e-12);\nZ = Z./feaSum(ones(size(Z,1),1),:);\nU = mySVD(Z,k+1);\nU(:,1) = [];\n\nU=U./repmat(sqrt(sum(U.^2,2)),1,k);\n\n% Final kmeans\nlabel=litekmeans(U,k,'MaxIter',maxIter,'Replicates',numRep);\n\n\n\n\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/Clustering/LSC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5982901493180531}}
{"text": "function [y1, y2] = vl_nnpdist(x, x0, p, varargin)\n%VL_NNPDIST CNN p-distance from target.\n%   VL_NNPDIST(X, X0, P) computes the P distance raised of each feature\n%   vector in X to the corresponding feature vector in X0:\n%\n%     Y(i,j,1) = (SUM_d (X(i,j,d) - X0(i,j,d))^P)^(1/P)\n%\n%   X0 should have the same size as X; the outoput Y has the same\n%   height and width as X, but depth equal to 1. Optionally, X0 can\n%   be a 1 x 1 x D x N array, in which case the same target feature\n%   vector in X0 is compared to all feature vectors in X. In that case,\n%   however, the DZDX0 are of size of X.\n%\n%   Setting the `noRoot` option to `true` does not take the 1/P power\n%   in the formula, computing instead\n%\n%     Y(i,j,1) = SUM_d (X(i,j,d) - X0(i,j,d))^P\n%\n%   For example, `vl_nnpdist(x, x0, 2, 'noRoot', true)` computes the\n%   squared L2 distance.\n%\n%   [DZDX, DZDX0] = VL_NNPDISTP(X, X0, P, DZDY) computes the derivative\n%   of the block inputs projected onto DZDY. DZDX, DZDX0 and DZDY have the\n%   same dimensions as X and Y, respectively.\n%\n%   VL_NNPDIST(___, 'OPT', VAL, ...) accepts the following options:\n%\n%   `NoRoot`:: `false`\n%      If set to true, compute the P-distance to the P-th power.\n%\n%   `Epsilon`:: 1e-6\n%      When computing derivatives, quantities that are divided in are\n%      lower boudned by this value. For example, the L2 distance is\n%      not smooth at the origin; this option prevents the\n%      derivative from diverging.\n%\n%   `Aggregate`:: false\n%      Instead of returning one scalar for each spatial location in\n%      the inputs, sum all of them into a single scalar.\n%\n%   `InstanceWeights``:: `[]`\n%      Optionally weight individual instances. This parameter can be\n%      eigther a scalar or a weight mask, one for each pixel in the\n%      input tensor.\n\n% Copyright (C) 2015  Karel Lenc and Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n% -------------------------------------------------------------------------\n%                                                             Parse options\n% -------------------------------------------------------------------------\n\nopts.noRoot = false ;\nopts.epsilon = 1e-6 ;\nopts.aggregate = false ;\nopts.instanceWeights = [] ;\nbackMode = numel(varargin) > 0 && ~ischar(varargin{1}) ;\nif backMode\n  dzdy = varargin{1} ;\n  opts = vl_argparse(opts, varargin(2:end), 'nonrecursive') ;\nelse\n  dzdy = [] ;\n  opts = vl_argparse(opts, varargin, 'nonrecursive') ;\nend\n\n% -------------------------------------------------------------------------\n%                                                             Parse options\n% -------------------------------------------------------------------------\n\nd = bsxfun(@minus, x, x0) ;\n\nif ~isempty(dzdy) && ~isempty(opts.instanceWeights)\n  dzdy = bsxfun(@times, opts.instanceWeights, dzdy) ;\nend\n\nif ~opts.noRoot\n  if isempty(dzdy)\n    if p == 1\n      y1 = sum(abs(d),3) ;\n    elseif p == 2\n      y1 = sqrt(sum(d.*d,3)) ;\n    else\n      y1 = sum(abs(d).^p,3).^(1/p) ;\n    end\n  else\n    if p == 1\n      y1 = bsxfun(@times, dzdy, sign(d)) ;\n    elseif p == 2\n      y1 = max(sum(d.*d,3), opts.epsilon).^(-0.5) ;\n      y1 = bsxfun(@times, bsxfun(@times, dzdy, y1),  d) ;\n    elseif p < 1\n      y1 = sum(abs(d).^p,3).^((1-p)/p) ;\n      y1 = bsxfun(@times, bsxfun(@times, dzdy, y1), max(abs(d), opts.epsilon).^(p-1) .* sign(d)) ;\n    else\n      y1 = max(sum(abs(d).^p,3), opts.epsilon).^((1-p)/p) ;\n      y1 = bsxfun(@times, bsxfun(@times, dzdy, y1), abs(d).^(p-1) .* sign(d)) ;\n    end\n  end\nelse\n  if isempty(dzdy)\n    if p == 1\n      y1 = sum(abs(d),3) ;\n    elseif p == 2\n      y1 = sum(d.*d,3) ;\n    else\n      y1 = sum(abs(d).^p,3) ;\n    end\n  else\n    if p == 1\n      y1 = bsxfun(@times, dzdy, sign(d)) ;\n    elseif p == 2\n      y1 = bsxfun(@times, 2 * dzdy, d) ;\n    elseif p < 1\n      y1 = bsxfun(@times, p * dzdy, max(abs(d), opts.epsilon).^(p-1) .* sign(d)) ;\n    else\n      y1 = bsxfun(@times, p * dzdy, abs(d).^(p-1) .* sign(d)) ;\n    end\n  end\nend\n\nif isempty(dzdy)\n  if ~isempty(opts.instanceWeights)\n    y1 = bsxfun(@times, opts.instanceWeights, y1) ;\n  end\n  if opts.aggregate\n    y1 = sum(sum(y1)) ;\n  end\nend\nif ~isempty(dzdy), y2 = -y1; end\n", "meta": {"author": "ybsong00", "repo": "CREST-Release", "sha": "e331e6763e6b683b1696e1d61420e902bfce4ef7", "save_path": "github-repos/MATLAB/ybsong00-CREST-Release", "path": "github-repos/MATLAB/ybsong00-CREST-Release/CREST-Release-e331e6763e6b683b1696e1d61420e902bfce4ef7/matconvnet/matlab/vl_nnpdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5982901393090266}}
{"text": "%PARZENC Optimisation of the Parzen classifier\n% \n%  [W,H] = PARZENC(A,H)\n%  [W,H] = A*PARZENC([],H)\n%  [W,H] = A*PARZENC(H)\n% \n% INPUT\n%  A    dataset\n%  H    smoothing parameter (may be scalar, vector of per-class\n%       parameters, or matrix with parameters for each class (rows) and\n%       dimension (columns))\n%\n% OUTPUT\n%  W    trained mapping\n%  H    estimated smoothing (scalar value)\n%\n% DESCRIPTION\n% Computation of the optimum smoothing parameter H for the Parzen \n% classifier between the classes in the dataset A. The leave-one-out \n% Lissack & Fu estimate is used for the classification error E. The \n% final classifier is stored as a mapping in W. It may be converted\n% into a classifier by W*CLASSC. PARZENC cannot be used for density\n% estimation.\n% \n% In case smoothing H is specified, no learning is performed, just the\n% discriminant W is produced for the given smoothing parameters H.\n% Smoothing parameters may be scalar, vector of per-class parameters, or \n% a matrix with individual smoothing for each class (rows) and feature\n% directions (columns)\n%\n% EXAMPLES\n% See PREX_DENSITY for densities and PREX_PARZEN for differences between\n% PARZENC, PARZENDC and PARZENM.\n%\n% REFERENCES\n% T. Lissack and K.S. Fu, Error estimation in pattern recognition via\n% L-distance between posterior density functions, IEEE Trans. Inform. \n% Theory, vol. 22, pp. 34-45, 1976.\n% \n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% DATASETS, MAPPINGS, PARZEN_MAP, PARZENML, PARZENDC, PARZENM, CLASSC, \n% PREX_PARZEN \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: parzenc.m,v 1.6 2008/07/03 09:11:44 duin Exp $\n\nfunction [W,h] = parzenc(varargin)\n  \n\tmapname = 'ParzenC';\n  argin = shiftargin(varargin,'scalar');\n  argin = setdefaults(argin,[],[]);\n  \n  if mapping_task(argin,'definition')\n    W = define_mapping(argin,'untrained',mapname);\n    \n  elseif mapping_task(argin,'training')\t\t\t% Train a mapping.\n  \n    [a,h] = deal(argin{:});\n    islabtype(a,'crisp','soft');\n    isvaldfile(a,2,2); % at least 2 objects per class, 2 classes\n    a = testdatasize(a);\n    a = testdatasize(a,'objects');\n\n    [m,k,c] = getsize(a);\n    nlab = getnlab(a);\n\n    if ~isempty(h)       % take user setting for smoothing parameter\n\n      if size(h,1) == 1, h = repmat(h,c,1); end\n      if size(h,2) == 1, h = repmat(h,1,k); end\n      if any(size(h) ~= [c,k])\n        error('Array with smoothing parameters has wrong size');\n      end\n      W = prmapping('parzen_map','trained',{a,h},getlablist(a),k,c);\n      W = setname(W,'Parzen Classifier');\n      return\n\n    end\n\n    % compute all object distances\n    % make diagonal inf to exclude objects own contribution\n    D = +distm(a) + diag(inf*ones(1,m));\n\n    % find object frequencies\n    if islabtype(a,'crisp')\n      csize = classsizes(a);\n      of = csize(nlab);\n    else\n      csize = sum(gettargets(a),1);\n    end\n\n    % find object weights q\n    p = getprior(a);\n    a = setprior(a,p);\n    q = p(nlab)./csize(nlab);\n\n    % initialise\n    h = max(std(a)); % for sure a too high value\n    L = -inf;\n    Ln = 0;\n    z = 0.1^(1/k); % initial step size\n\n    % iterate\n\n    iter = 0;\n    prwaitbar(100,'parzenc: Optimizing smoothing parameter',m > 100);\n    while abs(Ln-L) > 0.001 & z < 1\n\n      % In L we store the best performance estimate found so far.\n      % Ln is the actual performance (for the actual h)\n      % If Ln > L we improve the bound L, and so we rest it.\n\n      if Ln > L, L = Ln; end\n      iter = iter+1;\n      prwaitbar(100,100-100*exp(-iter/10));\n\n      r = -0.5/(h^2);\n      F = q(ones(1,m),:)'.*exp(D*r);           % density contributions\n      FS = sum(F)*((m-1)/m); IFS = find(FS>0); % joint density distribution\n      if islabtype(a,'crisp');\n        G = sum(F .* (nlab(:,ones(1,m)) == nlab(:,ones(1,m))'));\n        G = G.*(of-1)./of;                     % true-class densities\n      else\n        % here we are for soft labels (stored in targets)\n        G = zeros(1,m);\n        for j=1:c\n          G = G + sum(F .* (a.targets(:,j) * a.targets(:,j)'));\n          % to be corrected for bias?\n        end\n      end\n\n      % performance estimate\n      en = max(p)*ones(1,m);\n      en(IFS) = (G(IFS))./FS(IFS);\n      Ln = exp(sum(log(en))/m);\n\n      if Ln < L            % compute next estimate\n        z = sqrt(z);       % adjust stepsize up (recall: 0 < z < 1)\n        h = h / z;         % if we don't improve, increase h (approach h_opt from below)\n      else\n        h = h * z;         % if we improve, decrease h (approach h_opt from above)\n      end\n    end\n    prwaitbar(0);\n    W = prmapping('parzen_map','trained',{a,repmat(h,c,k);},getlablist(a),k,c);\n    W = setname(W,mapname);\n    W = setcost(W,a);\n    \n  end\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/parzenc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5982848466684932}}
{"text": "function out = gpuBlockSmallXtY(X, Y)\n\ng = gpuDevice;\nbytesGPU = g.AvailableMemory;\ninfoX = whos('X');\ninfoY = whos('Y');\n[hX, wX] = size(X);\n[hY, wY] = size(Y); % hY should be equal to hX\n% the dimensions of out will be wX-by-wY\nbytesPerRowX = infoX.bytes/hX;\nbytesPerRowY = infoY.bytes/hY;\n% theoretically, to keep the result and {X', X, and Y} in GPU memory\n% bytesRequired = bytesPerRowX*wY + batchSize*(2*bytesPerRowX+bytesPerRowY);\nbatchSize = floor((bytesGPU-bytesPerRowX*wY)/(2*bytesPerRowX+bytesPerRowY));\nbatchSize = floor(batchSize/8); % just to be on the safe side\n% also, interestingly with smaller batches the code runs slightly faster\nnBatches = ceil(hX/batchSize);\n\nstartIdx = 1:batchSize:hX;\nendIdx = startIdx + batchSize-1;\nendIdx = min(endIdx, hX);\n\nout = gpuArray(zeros([wX, wY], 'like', X));\nfor iBatch = 1:nBatches\n%     fprintf('Batch %d/%d\\n', iBatch, nBatches);\n    batchX = gpuArray(X(startIdx(iBatch):endIdx(iBatch), :));\n    batchY = gpuArray(Y(startIdx(iBatch):endIdx(iBatch), :));\n    out = out + batchX'*batchY;\n\n% MK - this is an annoying line of code, but it helps Matlab to do memory\n% management on the GPU properly. Otherwise I get OUT OF MEMORY errors\n% maybe it is just my GPU is a bit unstable\n    wait(gpuDevice);\nend\n\nout = gather(out);\n\nreturn\n", "meta": {"author": "cortex-lab", "repo": "Suite2P", "sha": "c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5", "save_path": "github-repos/MATLAB/cortex-lab-Suite2P", "path": "github-repos/MATLAB/cortex-lab-Suite2P/Suite2P-c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5/svd/gpuBlockXtY.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5982809705039667}}
{"text": "function hypersphere_integrals_test ( )\n\n%*****************************************************************************80\n%\n%% HYPERSPHERE_INTEGRALS_TEST tests the HYPERSPHERE_INTEGRALS library.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    07 January 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'HYPERSPHERE_INTEGRALS_TEST\\n' );\n  fprintf ( 1, '  MATLAB version\\n' );\n  fprintf ( 1, '  Test the HYPERSPHERE_INTEGRALS library.\\n' );\n\n  hypersphere_integrals_test01 ( );\n  hypersphere_integrals_test02 ( );\n%\n%  Terminate.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'HYPERSPHERE_INTEGRALS_TEST\\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/hypersphere_integrals/hypersphere_integrals_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.5982809579174815}}
{"text": "function [f_unk_1]=rlse(yk_1,hk_1,G_un,rk)           \n                                                                                \n% Estimate sk_1: A matrix with dimension rxr \nSk_1=inv(G_un'*inv(rk)*G_un);\n\n% Recusive solution for unknown excitation\nf_unk_1=Sk_1*G_un'*inv(rk)*(yk_1-hk_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/42621-extend-kalman-filter-for-damage-detection-in-large-scale-structure/global/1-5 floor/rlse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5982499356421007}}
{"text": "function final_score = aggregation_attention(score, attention, T)\n\nif size(score, 1)\n    score = cat(1, score, score);\n    attention = cat(1, attention, attention);\nend\n\nif size(score, 3) > 1\nscore = double(squeeze(mean(score, 2)));\nattention = double(squeeze(mean(attention, 2)));\nend\n\nattention = attention/T;\nsoftmax_attention = exp(attention);\nsoftmax_attention = bsxfun(@rdivide, softmax_attention, sum(softmax_attention));\n\nfinal_score = bsxfun(@times, score, softmax_attention);\nfinal_score = sum(final_score, 1);\n\nend", "meta": {"author": "wanglimin", "repo": "UntrimmedNet", "sha": "76ec6a332e6e2580b1b0e779d2bf3e419cf92f50", "save_path": "github-repos/MATLAB/wanglimin-UntrimmedNet", "path": "github-repos/MATLAB/wanglimin-UntrimmedNet/UntrimmedNet-76ec6a332e6e2580b1b0e779d2bf3e419cf92f50/matlab/aggregation_attention.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5982186121891774}}
{"text": "function [dP] = GradJacobiP(r, alpha, beta, N);\n\n% function [dP] = GradJacobiP(r, alpha, beta, N);\n% Purpose: Evaluate the derivative of the Jacobi polynomial of type (alpha,beta)>-1,\n%\t       at points r for order N and returns dP[1:length(r))]        \n\ndP = zeros(length(r), 1);\nif(N == 0)\n  dP(:,:) = 0.0; \nelse\n  dP = sqrt(N*(N+alpha+beta+1))*JacobiP(r(:),alpha+1,beta+1, N-1);\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/Codes1D/GradJacobiP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5982186121891774}}
{"text": "function res = immedian(img, filtre, varargin)\n%IMMEDIAN Compute median value in the neighboorhood of each pixel\n%\n%   RES = immedian(IMG, SE)\n%   Compute the median filter of image IMG, using structuring element SE.\n%   The goal of this function is to provide the same interface as for\n%   other image filters (imopen, imerode ...), and to allow the use of \n%   median filter with user-defined structuring element. \n%   This function can be used for directional filtering.\n%\n%\n%   RES = immedian(IMG, SE, PADOPT) also specify padding option. PADOPT can\n%   be either 'zeros' or 'SYMMETRIC', see medfilt2 or ordfilt2 for details.\n%\n%   See Also: IMMEAN, IMDIRFILTER, MEDFILT2, ORDFILT2\n%\n%\n%   ---------\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 16/02/2004.\n%\n\n%   HISTORY\n%   17/02/2004: add support for 'strel' objects.\n%   20/02/2004: add 'padopt' option, and documentation\n%   2011-11-05 deprecate\n\nwarning('imael:deprecatedFunction', ...\n    'function \"immedian\" has been deprecated and replaced by \"imMedianFilter\"');\n\n\n% transform STREL object into single array\nif strcmp(class(filtre), 'strel') %#ok<STISA>\n    filtre = getnhood(filtre);\nend\n\n% get padopt option.\npadopt = 'zeros'; % default for standard median filtering in matlab\nif ~isempty(varargin)\n    padopt = varargin{1};\nend\n\n% perform filtering\norder = ceil(sum(filtre(:))/2);\nres = ordfilt2(img, order, filtre, padopt);\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/immedian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5981106457499132}}
{"text": "% Hoer's code (P. O. Hoyer. Non-negative Matrix Factorization with sparseness constraints. \n% Journal of Machine Learning Research  5:1457-1469, 2004.) is modified \n\nfunction [W, H, objhistory, objhistory_v] = nmf( V, rdim, showflag, ttt )\n%% INPUT\n% V: data matrix\n% rdim : matrix factorization rank\n% showflag: if it is 1. than it plots the change of reconstruction error\n% for each iteration\n% ttt: maximum number of iterations allowed\n\n%% OUTPUT\n% W: Mixing matrix (V=WH)\n% H: Encoding matrix (V=WH)\n% objhistory: change of total reconstruction error\n% objhistory_v: reconstruction error for each individual sample\n\n\n\n\n% Check that we have non-negative data\nif min(V(:))<0, error('Negative values in data!'); end\n \n% Dimensions\nvdim = size(V,1);\nsamples = size(V,2);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% initialization %%%\nfname2=['initials/Initials' num2str(vdim) 'x' num2str(rdim) '.txt'];\nfid=fopen(fname2,'r');\nif (fid==-1)\n    ssbinitial(vdim,rdim);\nend\nfidW2 = fopen(fname2,'r');\nW = fscanf(fidW2,'%f', [vdim inf]);\nfclose(fidW2);\n\nclear fname2\n\nfname2=['initials/Initials' num2str(rdim) 'x' num2str(samples) '.txt'];\nfid=fopen(fname2,'r');\nif (fid==-1)\n    ssbinitial(rdim,samples);\nend\nfidW2 = fopen(fname2,'r');\nH = fscanf(fidW2,'%f', [rdim inf]);\nfclose(fidW2);\n\nclear fname2\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif (showflag==1)\n    objhistory = ((sum(sum((V-W*H).^2))))/(vdim*samples);\n    figure(2); clf;\n    drawnow;\nend\n\n\n% Start iteration\niter = 0;\nwhile 1,\n    \n    if (iter==ttt)\n        break\n    end\n    iter = iter+1;    \n    % Compute new W and H (Lee and Seung; NIPS*2000)\n    H = H.*(W'*V)./(W'*W*H + 1e-9);\n    W = W.*(V*H')./(W*H*H' + 1e-9);\n    \n%     norms = sqrt(sum(W.^2));\n%     H = H.*(norms'*ones(1,samples));\n%     W = W./(ones(vdim,1)*norms);\n\n    newobj = ((sum(sum((V-W*H).^2))))/(vdim*samples);\n    newobj_v = ((sum(sum((V(:,end)-W*H(:,end)).^2))))/(vdim);\n    if iter==1\n        objhistory = [newobj];\n        objhistory_v = [newobj_v];\n    else\n        objhistory = [objhistory newobj];\n        objhistory_v = [objhistory_v newobj_v];\n    end\n    \n    if(showflag==1)\n        if (iter>1)\n            plot(objhistory(2:end)); \n        end\n        drawnow;\n    end   \nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/nmf/iNMF/nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5981106457499131}}
{"text": "function nfigures = NumTotFigures(row,col,nvar)\n% =======================================================================\n% Determine the number of figures for a given number of subplots, rows \n% and columns\n% =======================================================================\n% nfigures = NumTotFigures(row,col,nvar)\n% -----------------------------------------------------------------------\n% INPUT\n%\t- row: number of rows of the subplot\n%\t- col: number of columns of the subplot\n%\t- nvar: number of variables\n% -----------------------------------------------------------------------\n% OUTPUT\n%\t- nfigures: number of charts per subplot\n% =======================================================================\n% VAR Toolbox 3.0\n% Ambrogio Cesa-Bianchi\n% ambrogiocesabianchi@gmail.com\n% March 2015. Updated November 2020\n% -----------------------------------------------------------------------\n\nNumGraphXPage = row*col;\n\np = floor(nvar./NumGraphXPage);\nq = (nvar./NumGraphXPage);\n\nif NumGraphXPage>=nvar\n    nfigures=1;\nelseif p==q\n    nfigures=p;\nelse\n    nfigures=p+1;\nend\nclear p q", "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/Figure/NumTotFigures.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5981106411184988}}
{"text": "function b = gray2bi( g )\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                                                                %\n%%   GRAY2BI converts Gray encoded sequence into the binary       %\n%%   sequence. It is assumed that the most significant bit is     %\n%%   the left hand side bit.                                      %\n%%                                                                %\n%%   Comments and suggestions to: batlles@gmail.com               %\n%%                                                                %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    % copy the msb:\n    b(:,1) = g(:,1);\n    \n    for i = 2:size(g,2),\n        b(:,i) = xor( b(:,i-1), g(:,i) ); \n    end\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/21494-a-802-16d-system-comments-on-english/gray2bi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.5981106394078896}}
{"text": "function [ n_data, n, x, fx ] = laguerre_polynomial_values ( n_data )\n\n%*****************************************************************************80\n%\n%% LAGUERRE_POLYNOMIAL_VALUES returns some values of the Laguerre polynomial.\n%\n%  Discussion:\n%\n%    In Mathematica, the function can be evaluated by:\n%\n%      LaguerreL[n,x]\n%\n%  Differential equation:\n%\n%    X * Y'' + (1-X) * Y' + N * Y = 0\n%\n%  First terms:\n%\n%      1\n%     -X   +  1\n%   (  X^2 -  4 X   +   2 ) / 2\n%   ( -X^3 +  9 X^2 -  18 X   +    6 ) / 6\n%   (  X^4 - 16 X^3 +  72 X^2 -   96 X +      24 ) / 24\n%   ( -X^5 + 25 X^4 - 200 X^3 +  600 X^2 -   600 X   +   120 ) / 120\n%   (  X^6 - 36 X^5 + 450 X^4 - 2400 X^3 +  5400 X^2 -  4320 X   +   720 ) / 720\n%   ( -X^7 + 49 X^6 - 882 X^5 + 7350 X^4 - 29400 X^3 + 52920 X^2 - 35280 X + 5040 ) / 5040\n%\n%  Recursion:\n%\n%    L(0)(X) = 1,\n%    L(1)(X) = 1-X,\n%    N * L(N)(X) = (2*N-1-X) * L(N-1)(X) - (N-1) * L(N-2)(X)\n%\n%  Orthogonality:\n%\n%    Integral ( 0 <= X < oo ) exp ( - X ) * L(N)(X) * L(M)(X) dX\n%    = 0 if N /= M\n%    = 1 if N == M\n%\n%  Special values:\n%\n%    L(N)(0) = 1.\n%\n%  Relations:\n%\n%    L(N)(X) = (-1)^N / N! * exp ( x ) * (d/dx)^n ( exp ( - x ) * X^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%    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 polynomial.\n%\n%    Output, real X, the point where the polynomial is evaluated.\n%\n%    Output, real FX, the value of the function.\n%\n  n_max = 17;\n\n  fx_vec = [ ...\n      0.1000000000000000E+01, ...\n      0.0000000000000000E+00, ...\n     -0.5000000000000000E+00, ...\n     -0.6666666666666667E+00, ...\n     -0.6250000000000000E+00, ...\n     -0.4666666666666667E+00, ...\n     -0.2569444444444444E+00, ...\n     -0.4047619047619048E-01, ...\n      0.1539930555555556E+00, ...\n      0.3097442680776014E+00, ...\n      0.4189459325396825E+00, ...\n      0.4801341790925124E+00, ...\n      0.4962122235082305E+00, ...\n     -0.4455729166666667E+00, ...\n      0.8500000000000000E+00, ...\n     -0.3166666666666667E+01, ...\n      0.3433333333333333E+02  ];\n\n  n_vec = [ ...\n     0,  1,  2, ...\n     3,  4,  5, ...\n     6,  7,  8, ...\n     9, 10, 11, ...\n    12,  5,  5, ...\n     5,  5 ];\n\n  x_vec = [ ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     0.5E+00, ...\n     3.0E+00, ...\n     5.0E+00, ...\n     1.0E+01 ];\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/test_values/laguerre_polynomial_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5981106389074764}}
{"text": "function [handles, key_points] = draw_pie_wedge(T1, T2, myradius, varargin)\n% Draws a pie wedge with color fill, for polar plots and circular charts\n%\n% :Usage:\n% ::\n%\n%     handles = draw_pie_wedge(T1, T2, myradius, ['linecolor'], [r g b], ['fillcolor'], [r g b])\n%\n% ..\n%     Dec 2017, Tor Wager\n%\n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n%\n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n%\n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n% ..\n%\n% :Inputs:\n%\n%   **T1:**\n%        Starting location, in radians. 0 = to the right on plot; 2*pi is\n%        full-circle, also to the right on plot.\n%\n%   **T2:**\n%        Ending location, in radians. 0 = to the right on plot; 2*pi is\n%        full-circle, also to the right on plot.\n%\n% :Optional Inputs:\n%   **'linecolor':**\n%        Followed by [r g b] triplet specifying line color, or 'none'\n%\n%   **'fillcolor:**\n%        Followed by [r g b] triplet specifying fill color, or 'none'\n%\n%   **'outside_radius_offset'**\n%        Followed by outside_radius_offset value. See below.\n% \n%   **'linewidth':**\n%       Followed by line width\n%\n%   **'stripes':**\n%       Turn on radial striping; can be followed by value true or false\n%\n%   **'stripedensity':**\n%       Number of stripes/lines to draw in wedge\n%\n% :Outputs:\n%\n%   **handles:**\n%        A structure of line and fill handles\n%\n%   **key_points:**\n%        x and y locations for the mid-point of the arc, inner mid-point of the\n%        wedge, and outer mid-point offset by a constant value. This is\n%        set by outside_radius_offset, and is useful for text labels\n%\n% :Examples:\n% ::\n%\n% myradius = 3;\n% T1 = 1; % start, in radians\n% T2 = 4; % end, in radians\n%\n% handles = draw_pie_wedge(1, 3, 2); % Draw wedge from radian=1 to 3, radius = 2\n%\n% Draw reference circle with radius = 2\n% handles = draw_pie_wedge(0, 2*pi, 2, 'linecolor', [0 0 0], 'fillcolor', 'none');\n%\n% Now draw a wedge on top of that:\n% handles = draw_pie_wedge(1, 1.5, 2.5, 'linecolor', [.7 .7 0], 'fillcolor', [.3 .7 .7]);\n%\n% Draw with dense striping pattern:\n% handles = draw_pie_wedge(1, 1.5, 2.5, 'linecolor', [.7 .7 0], 'fillcolor', [.3 .7 .7], 'stripes', 'stripedensity', 40);\n%\n% Draw a series of wedges in different colors:\n% n_categories = 7;\n% st = linspace(0, 2*pi, n_categories+1); % starting vals in radians\n% \n% en = st(2:end);\n% st = st(1:end-1);\n% \n% colors = seaborn_colors(n_categories + 1); % add one to make colors more diff\n% clear handles\n% \n% figure; hold on;\n% \n% for i = 1:n_categories\n%     \n%     handles(i) = draw_pie_wedge(st(i), en(i), i, 'linecolor', colors{i} ./ 2, 'fillcolor', colors{i});\n%     \n% end\n% \n% axis equal\n%\n% For another extended example with text labels, see tor_wedge_plot.m\n\n\n\nlinecolor = [1 0 0];\nfillcolor = [.7 .3 .7];\nlinewidth = 2;\noutside_radius_offset = .04; % Value to offset by when calculating outside-wedge midpoint for labels\ndostripes = false;\nstripedensity = 12;\n\nfor i = 1:length(varargin)\n    if ischar(varargin{i})\n        switch varargin{i}\n\n            case 'linecolor', linecolor = varargin{i+1}; varargin{i+1} = [];\n            case 'fillcolor', fillcolor = varargin{i+1}; varargin{i+1} = [];\n                \n            case 'linewidth', linewidth = varargin{i+1}; varargin{i+1} = [];\n                    \n            case 'stripes' \n                dostripes = true; \n                % Optional argument true or false following keyword\n                if length(varargin) > i && ~ischar(varargin{i+1}) % param value entered in next arg\n                    dostripes = varargin{i+1}; varargin{i+1} = [];\n                end\n                \n            case 'stripedensity', stripedensity = varargin{i+1}; varargin{i+1} = [];\n                \n            case 'outside_radius_offset', outside_radius_offset = varargin{i+1}; varargin{i+1} = [];\n            otherwise, warning(['Unknown input string option:' varargin{i}]);\n        end\n    end\nend\n\n% This would draw a reference circle\n%hold on\n%h0 = drawCircle(0, 0, myradius);\n%set(h0, 'Color', 'k');\n\n% Circle Arc\n% ------------------------------------------\n%h = drawCircleArc(0, 0, myradius, T1, T2);\n\n[h xt yt] = drawArc(T1, T2, myradius);\n\n% get midpoint of arc\n% ------------------------------------------\ntmid = (T1+T2)/2; \nxmid_arc = 0 + myradius*cos(tmid);\nymid_arc = 0 + myradius*sin(tmid);\n\n% Middle of pie\nxmid_pie = 0 + myradius/2*cos(tmid);\nymid_pie = 0 + myradius/2*sin(tmid);\n\n% outside arc\nrad2 = myradius + outside_radius_offset; %.1 * myradius;\nxmid_outside = 0 + rad2*cos(tmid);\nymid_outside = 0 + rad2*sin(tmid);\n\n% others\nradialangle = rad2deg(tmid); % radial angle in degrees\ntangentangle = rad2deg(tmid + (pi/2)); % angle of tangent, for text\n\nkey_points = struct('tmid_radians', tmid, 'radialangle', radialangle, 'tangentangle', tangentangle, ...\n    'xmid_arc', xmid_arc, 'ymid_arc', ymid_arc, 'xmid_outside', xmid_outside, ...\n    'ymid_outside', ymid_outside, 'xmid_pie', xmid_pie);\n\nset(h, 'Color', linecolor, 'LineWidth', linewidth)\n\n% Pie wedge\n% ------------------------------------------\nhold on\n[x1,y1] = pol2cart(T1, myradius);\nh(2) = plot([0 x1], [0 y1], 'Color', linecolor, 'LineWidth', linewidth);\n\n[x2,y2] = pol2cart(T2, myradius);\nh(3) = plot([0 x2], [0 y2], 'Color', linecolor, 'LineWidth', linewidth);\n\n% Fill\n% ------------------------------------------\n\nif ischar(fillcolor) && strcmp(fillcolor, 'none')\n    % skip it\n    hfill = [];\nelse\n    hfill = fill([xt 0], [yt 0], fillcolor, 'FaceAlpha', .65);\nend\n\nhandles = struct('line_han', h, 'fill_han', hfill);\n\n% Striping\n% ------------------------------------------\nif dostripes\n    \n    handles.stripe_han = drawStripes(T1, T2, myradius, stripedensity);\n    set(handles.stripe_han, 'Color', linecolor, 'LineWidth', linewidth)\n    \nelse\n    \n    handles.stripe_han = [];\n    \nend\n    \n\n\nend % main function\n\n\nfunction [h xt yt] = drawArc(T1, T2, myradius)\n\n% key bits\nt = T1:.01:T2;          % Arc\nxt = 0 + myradius*cos(t);\nyt = 0 + myradius*sin(t);\nxt = [xt 0+myradius*cos(T2)];\nyt = [yt 0+myradius*sin(T2)];\n\nh = line(xt, yt);\n\nend\n\n\nfunction h = drawStripes(T1, T2, myradius, stripedensity)\n\nr = linspace(0, myradius, stripedensity);\n\nfor i = 1:length(r)\n    \n    h(i) = drawArc(T1, T2, r(i));\n    \nend\n\nend\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Visualization_functions/draw_pie_wedge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.5981106296446477}}
{"text": "function uscita = deg2rad(ingresso)\nuscita = 2*pi*ingresso/360;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4239-fingerprint-recognition-system/rel51/deg2rad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087926320945, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5981042659795937}}
{"text": "[datapoints, numpoints] = px4_read_binary_file('e4_ekf_A.bin');\nroll_ekf = datapoints(1, :);\npitch_ekf = datapoints(2, :);\nroll_cf = datapoints(3, :);\npitch_cf = datapoints(4, :);\nroll_px4 = datapoints(5, :);\npitch_px4 = datapoints(6, :);\nt = datapoints(7, :);\nrad2deg = 180/pi;\nfigure(1)\nplot(t, roll_ekf*rad2deg, 'g', t, roll_cf*rad2deg, 'b', t, roll_px4*rad2deg, 'r')\nlegend('ekf', 'cf', 'px4');\nxlabel('time/s');\nylabel('roll/deg')\ntitle('roll-Filter effect comparison')\n", "meta": {"author": "RflySim", "repo": "RflyExpCode", "sha": "7dbec4d8796d6e23ee86c523e4ba5712203b1519", "save_path": "github-repos/MATLAB/RflySim-RflyExpCode", "path": "github-repos/MATLAB/RflySim-RflyExpCode/RflyExpCode-7dbec4d8796d6e23ee86c523e4ba5712203b1519/code/e4/e4.3/HardInloop/plot_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5980855516775625}}
{"text": "function X = slpcarecon(S, Y)\n%SLPCARECON Reconstructs the samples in original space\n%\n% $ Syntax $\n%   - Xr = slpcarecon(S, Y)\n%\n% $ Arguments $\n%   - S:        the PCA model struct\n%   - Y:        the principal component features\n%   - Xr:       the reconstructed samples\n%\n% $ Description $\n%   - Xr = slpcarecon(S, Y) reconstructs the original samples approximately\n%     using the principal components Y. If the dimension of Y is less than\n%     the subspace dimension, the leading space dimensions will be used.\n%\n% $ History $\n%   - Created by Dahua Lin, on Aug 17, 2006\n%   - Modified by Dahua Lin, on Sep 10, 2006\n%       - replace sladd by sladdvec to increase efficiency\n%\n\n%% parse and verify input\n\nif ~isstruct(S)\n    error('sltoolbox:invalidarg', ...\n        'S should be a PCA model struct');\nend\n\nif ~isnumeric(Y) || ndims(Y) ~= 2\n    error('sltoolbox:invalidarg', ...\n        'The features Y should be a 2D numeric matrix');\nend\n\ndy = size(Y, 1);\nif dy > S.feadim\n    error('sltoolbox:sizmismatch', ...\n        'The feature dimension of Y exceeds the subspace dimension preserved in model');\nend\n\n%% reconstruct\n\nif dy == S.feadim\n    X = S.P * Y;\nelse\n    X = S.P(:, 1:dy) * Y;\nend\n\nX = sladdvec(X, S.vmean, 1);\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/slpcarecon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.5980855477162942}}
{"text": "% Uncomment individual Example lines.\n\n%---- Example 1: E5 (nyquist frequency)\nfs = 120*1.023e6;\nn_E5_periods = 1;\n\n%---- Example 2: E5 (nyquist frequency, several periods)\n% fs = 120*1.023e6;\n% n_E5_periods = 8.2;\n\n%---- Example 3: E5 (sub-nyquist frequency, several periods)\n% fs = 10*1.023e6;\n% n_E5_periods = 2.2;\n\n%---- Example 4: E5 (higher frequency, several periods)\n% fs = 130*1.023e6;\n% n_E5_periods = 1.2;\n\n%---- Example 4: E5 (higher frequency non multiple, several periods)\n% fs = 130*1e6;\n% n_E5_periods = 1.2;\n\n%---- Example 4: E5 (lower frequency non multiple, several periods)\n% fs = 10*1e6;\n% n_E5_periods = 1.2;\n\ncoh_time = n_E5_periods*1e-3;\nfh = BOCgen;\n[sd1, sd2, sp1 sp2]  = fh.BOC_E5(coh_time,fs);\n\n%==========================================================================  \n%% Plots\n%==========================================================================  \nt_boc_chips = linspace(0,1.023e6*120*coh_time,length(sd1));\n\nfigure; \n        hold on;\n        stairs(t_boc_chips,sd1,'b');\n        stairs(t_boc_chips,sd2,'r');\n        grid on;\n        title('Data spread codes');\n        xlabel('BOC symbol period')\n        ylabel('amplitude');        \n        legend('Data spread code', 'Data spread code delayed');\n        \nfigure; hold on;        \n        stairs(t_boc_chips,sp1,'b');\n        stairs(t_boc_chips,sp2,'r');        \n        grid on;  \n        title('Pilot spread codes');\n        xlabel('BOC symbol period')\n        ylabel('amplitude'); \n        legend('Pilot spread code', 'Pilot spread code delayed');\n        \n% Next plots just shows that consecutive BOC symbols are identical              \nsub_period = round(fs/1.023e6*120);       \nn_periods = floor(length(sd1)/sub_period);  \nfigure, hold on;\nfor i=1:n_periods-1\n     plot(sd2(sub_period*(i-1)+1:sub_period*i)-sd2(sub_period*i+1:sub_period*(i+1)));    \nend    \n\nfigure, hold on;\nfor i=1:n_periods-1\n     plot(sd1(sub_period*(i-1)+1:sub_period*i)-sd1(sub_period*i+1:sub_period*(i+1)));    \nend    \n\nfigure, hold on;\nfor i=1:n_periods-1\n     plot(sp1(sub_period*(i-1)+1:sub_period*i)-sp1(sub_period*i+1:sub_period*(i+1)));    \nend    \n\nfigure, hold on;\nfor i=1:n_periods-1\n     plot(sp2(sub_period*(i-1)+1:sub_period*i)-sp2(sub_period*i+1:sub_period*(i+1)));    \nend    ", "meta": {"author": "danipascual", "repo": "GNSS-matlab", "sha": "0365dbc78b3e142266ef899440005dfcc1ee8155", "save_path": "github-repos/MATLAB/danipascual-GNSS-matlab", "path": "github-repos/MATLAB/danipascual-GNSS-matlab/GNSS-matlab-0365dbc78b3e142266ef899440005dfcc1ee8155/source/examples/BOCgen_example_E5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.5980855471322931}}
{"text": "function [u,v,I]=localcross(Y,tol)\n% Full-pivoted cross for truncating one ket TT block instead of SVD\n\nif (exist('localcross_mex','file')>0)&&(isreal(Y))\n    % Check for a faster mex\n    if (nargout>2)\n        [u,v,I]=localcross_mex(Y,tol);\n    else\n        [u,v]=localcross_mex(Y,tol);\n    end;\n    return;\nend;\n\n[n,m,b]=size(Y);\n\nminsz = min(n, m*b);\nu = zeros(n, minsz);\nv = zeros(minsz, m*b);\nres = reshape(Y, n, m*b);\n% Return also the indices\nI = zeros(1, minsz);\nval_max = max(abs(Y(:)));\nfor r=1:minsz\n    res = reshape(res, [], 1);\n    [val,piv]=max(abs(res));\n    piv = tt_ind2sub([n, m*b], piv);\n    if (val<=tol*val_max)\n        break;\n    end;\n    res = reshape(res, n, m*b);\n    u(:,r) = res(:, piv(2));\n    v(r,:) = res(piv(1), :)/res(piv(1),piv(2));\n    res = res - u(:,r)*v(r,:);\n    I(r)=piv(1);\nend;\n% Return indices\nr = find(I==0,1);\nif (isempty(r))\n    r=minsz;\nelse\n    r=r-1;\nend;\nI = I(1:r);\nu = u(:, 1:r);\nv = v(1:r, :);\nif (r==0)\n    u = zeros(n,1);\n    v = zeros(1,m);\n    I = 1;\nend;\n% qr u, in case we don't have enrichment\n[u,rv]=qr(u,0);\nv = rv*v;\nend\n\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/cross/localcross.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.598021287909861}}
{"text": "function Res = dfm(X,Spec,threshold)\n%DFM()    Runs the dynamic factor model\n%\n%  Syntax:\n%    Res = DFM(X,Par)\n%\n%  Description:\n%   DFM() inputs the organized and transformed data X and parameter structure Par.\n%   Then, the function outputs dynamic factor model structure Res and data\n%   summary statistics (mean and standard deviation).\n%\n%  Input arguments:\n%    X: Kalman-smoothed data where missing values are replaced by their expectation\n%    Par: A structure containing the following parameters:\n%      Par.blocks: Block loadings.\n%      Par.nQ: Number of quarterly series\n%      Par.p: Number of lags in transition matrix\n%      Par.r: Number of common factors for each block\n%\n% Output Arguments:\n%\n%   Res - structure of model results with the following fields\n%       . X_sm | Kalman-smoothed data where missing values are replaced by their expectation\n%       . Z | Smoothed states. Rows give time, and columns are organized according to Res.C.\n%       . C | Observation matrix. The rows correspond\n%          to each series, and the columns are organized as shown below:\n%         - 1-20: These columns give the factor loadings. For example, 1-5\n%              give loadings for the first block and are organized in\n%              reverse-chronological order (f^G_t, f^G_t-1, f^G_t-2, f^G_t-3,\n%              f^G_t-4). Columns 6-10, 11-15, and 16-20 give loadings for\n%              the second, third, and fourth blocks respectively.\n%       .R: Covariance for observation matrix residuals\n%       .A: Transition matrix. This is a square matrix that follows the\n%      same organization scheme as Res.C's columns. Identity matrices are\n%      used to account for matching terms on the left and righthand side.\n%      For example, we place an I4 matrix to account for matching\n%      (f_t-1; f_t-2; f_t-3; f_t-4) terms.\n%       .Q: Covariance for transition equation residuals.\n%       .Mx: Series mean\n%       .Wx: Series standard deviation\n%       .Z_0: Initial value of state\n%       .V_0: Initial value of covariance matrix\n%       .r: Number of common factors for each block\n%       .p: Number of lags in transition equation\n%\n% References:\n%\n%   Marta Banbura, Domenico Giannone and Lucrezia Reichlin\n%   Nowcasting (2010)\n%   Michael P. Clements and David F. Hendry, editors,\n%   Oxford Handbook on Economic Forecasting.\n\n%% Store model parameters ------------------------------------------------\n\n\n% DFM input specifications: See documentation for details\nPar.blocks = Spec.Blocks;                  % Block loading structure\nPar.nQ = sum(strcmp('q',Spec.Frequency));  % Number of quarterly series\nPar.p = 1;                                 % Number of lags in autoregressive of factor (same for all factors)\nPar.r = ones(1,size(Spec.Blocks,2));       % Number of common factors for each block\n%Par.r(1) =2;\n% Display blocks\ntry\n    fprintf('\\n\\n\\n');\n    disp('Table 3: Block Loading Structure')\n    disp(array2table(Spec.Blocks,...\n         'RowNames', strrep(Spec.SeriesName,' ','_'),...\n         'VariableNames',Spec.BlockNames));\n    fprintf('\\n\\n\\n');\ncatch\nend\n\nfprintf('Estimating the dynamic factor model (DFM) ... \\n\\n');\n\n[T,N] = size(X);\nr = Par.r;\np = Par.p;\nnQ = Par.nQ;\nblocks = Par.blocks;\n\ni_idio = logical([ones(N-nQ,1);zeros(nQ,1)]);\n\n%R*Lambda = q; Contraints on the loadings of the quartrly variables\n\nR_mat = [  2 -1  0  0  0;...\n           3  0 -1  0  0;...\n           2  0  0 -1  0;...\n           1  0  0  0 -1];\n\nq = zeros(4,1);\n\nif(nargin < 3)\n    threshold = 1e-5;  % EM loop threshold (default value)\nend\n\nmax_iter = 5000;  % EM loop maximum number of iterations\n\n%% Prepare data -----------------------------------------------------------\n\nMx = mean(X,'omitnan');\nWx = std(X,'omitnan');\nxNaN = (X-repmat(Mx,T,1))./repmat(Wx,T,1);  % Standardize series\n\n%% Initial Conditions -----------------------------------------------------\n\noptNaN.method = 2; % Remove leading and closing zeros\noptNaN.k = 3;      % Setting for filter(): See remNaN_spline\n\n[A, C, Q, R, Z_0, V_0] = InitCond(xNaN,r,p,blocks,optNaN,R_mat,q,nQ,i_idio);\n\n% Initialize EM loop values\nprevious_loglik = -inf;\nnum_iter = 0;\nLL = -inf;\nconverged = 0;\n\n% y for the estimation is WITH missing data\ny = xNaN';\n\n%% EM LOOP ----------------------------------------------------------------\n\n%The model can be written as\n%y = C*Z + e;\n%Z = A*Z(-1) + v\n%where y is NxT, Z is (pr)xT, etc\n\n% Remove the leading and ending nans\noptNaN.method = 3;\ny_est = remNaNs_spline(xNaN,optNaN)';\n\nwhile (num_iter < max_iter) & ~converged % Loop until converges or max iter.\n\n    [C_new, R_new, A_new, Q_new, Z_0, V_0, loglik] = ...  % Applying EM algorithm\n        EMstep(y_est, A, C, Q, R, Z_0, V_0, r,p,R_mat,q,nQ,i_idio,blocks);\n\n    C = C_new;\n    R = R_new;\n    A = A_new;\n    Q = Q_new;\n\n    if num_iter > 2  % Checking convergence\n        [converged, decrease(num_iter + 1)] = ...\n            em_converged(loglik, previous_loglik, threshold, 1);\n    end\n\n    if (mod(num_iter,10) == 0) && (num_iter > 0)  % Print updates to command window\n        disp(['Now running the ',num2str(num_iter),...\n              'th iteration of max ', num2str(max_iter)]);\n        disp(['  Loglik','   (% Change)'])\n        disp([num2str(loglik),'   (', sprintf('%6.2f',100*((loglik-previous_loglik)/previous_loglik)) '%)'])\n    end\n\n\n    LL = [LL loglik];\n    previous_loglik = loglik;\n    num_iter =  num_iter + 1;\n\nend\n\nif(num_iter < max_iter)\n    disp(['Successful: Convergence at ', num2str(num_iter), ' iterations'])\nelse\n   disp('Stopped because maximum iterations reached')\nend\n\n% Final run of the Kalman filter\nZsmooth = runKF(y, A, C, Q, R, Z_0, V_0)';\n\nx_sm = Zsmooth(2:end,:) * C';  % Get smoothed X\n\n\n%%  Loading the structure with the results --------------------------------\nRes.x_sm = x_sm;\nRes.X_sm = repmat(Wx,T,1) .* x_sm + repmat(Mx,T,1);  % Unstandardized, smoothed\nRes.Z = Zsmooth(2:end,:);\nRes.C = C;\nRes.R = R;\nRes.A = A;\nRes.Q = Q;\nRes.Mx = Mx;\nRes.Wx = Wx;\nRes.Z_0 = Z_0;\nRes.V_0 = V_0;\nRes.r = r;\nRes.p = p;\n\n%% Display output\n% Table with names and factor loadings\n\nnQ       = Par.nQ;                      % Number of quarterly series\nnM       = size(Spec.SeriesID,1) - nQ;  % Number monthly series\nnLags    = max(Par.p, 5);               % 5 comes from monthly-quarterly aggregation\nnFactors = sum(Par.r);\n\nfprintf('\\n\\n\\n');\n\ntry\ndisp('Table 4: Factor Loadings for Monthly Series');\ndisp(array2table(Res.C(1:nM, 1:5:nFactors*5),...  % Only select lag(0) terms\n     'RowNames', strrep(Spec.SeriesName(1:nM),' ','_'), ...\n     'VariableNames', Spec.BlockNames));\nfprintf('\\n\\n\\n');\ndisp('Table 5: Quarterly Loadings Sample (Global Factor)')\ndisp(array2table(Res.C(end-nQ+1:end, 1:5), ...  % Select only quarterly series\n     'RowNames', strrep(Spec.SeriesName(end-nQ+1:end),' ','_'), ...\n     'VariableNames', {'f1_lag0', 'f1_lag1', 'f1_lag2', 'f1_lag3', 'f1_lag4'}));\nfprintf('\\n\\n\\n');\ncatch\nend\n\n% Table with AR model on factors (factors with AR parameter and variance of residuals)\n\nA_terms = diag(Res.A);  % Transition equation terms\nQ_terms = diag(Res.Q);  % Covariance matrix terms\n\ntry\ndisp('Table 6: Autoregressive Coefficients on Factors')\ndisp(table(A_terms(1:5:nFactors*5), ...  % Only select lag(0) terms\n           Q_terms(1:5:nFactors*5), ...\n           'VariableNames', {'AR_Coefficient', 'Variance_Residual'}, ...\n           'RowNames',      strrep(Spec.BlockNames,' ','_')));\nfprintf('\\n\\n\\n');\ncatch\nend\n\n% Table with AR model idiosyncratic errors (factors with AR parameter and variance of residuals)\ntry\ndisp('Table 7: Autoregressive Coefficients on Idiosyncratic Component')\ndisp(table(A_terms([nFactors*5+1:nFactors*5+nM nFactors*5+nM+1:5:end]),...  % 21:50 give monthly, 51:5:61 give quarterly\n           Q_terms([nFactors*5+1:nFactors*5+nM nFactors*5+nM+1:5:end]), ...\n           'VariableNames', {'AR_Coefficient', 'Variance_Residual'}, ...\n           'RowNames', strrep(Spec.SeriesName,' ','_')));\ncatch\nend\n\nend\n\n\n\n%% PROCEDURES -------------------------------------------------------------\n% Note: Kalman filter (runKF()) is in the 'functions' folder\n\nfunction  [C_new, R_new, A_new, Q_new, Z_0, V_0, loglik] = EMstep(y, A, C, Q, R, Z_0, V_0, r,p,R_mat,q,nQ,i_idio,blocks)\n%EMstep    Applies EM algorithm for parameter reestimation\n%\n%  Syntax:\n%    [C_new, R_new, A_new, Q_new, Z_0, V_0, loglik]\n%    = EMstep(y, A, C, Q, R, Z_0, V_0, r, p, R_mat, q, nQ, i_idio, blocks)\n%\n%  Description:\n%    EMstep reestimates parameters based on the Estimation Maximization (EM)\n%    algorithm. This is a two-step procedure:\n%    (1) E-step: the expectation of the log-likelihood is calculated using\n%        previous parameter estimates.\n%    (2) M-step: Parameters are re-estimated through the maximisation of\n%        the log-likelihood (maximize result from (1)).\n%\n%    See \"Maximum likelihood estimation of factor models on data sets with\n%    arbitrary pattern of missing data\" for details about parameter\n%    derivation (Banbura & Modugno, 2010). This procedure is in much the\n%    same spirit.\n%\n%  Input:\n%    y:      Series data\n%    A:      Transition matrix\n%    C:      Observation matrix\n%    Q:      Covariance for transition equation residuals\n%    R:      Covariance for observation matrix residuals\n%    Z_0:    Initial values of factors\n%    V_0:    Initial value of factor covariance matrix\n%    r:      Number of common factors for each block (e.g. vector [1 1 1 1])\n%    p:      Number of lags in transition equation\n%    R_mat:  Estimation structure for quarterly variables (i.e. \"tent\")\n%    q:      Constraints on loadings\n%    nQ:     Number of quarterly series\n%    i_idio: Indices for monthly variables\n%    blocks: Block structure for each series (i.e. for a series, the structure\n%            [1 0 0 1] indicates loadings on the first and fourth factors)\n%\n%  Output:\n%    C_new: Updated observation matrix\n%    R_new: Updated covariance matrix for residuals of observation matrix\n%    A_new: Updated transition matrix\n%    Q_new: Updated covariance matrix for residuals for transition matrix\n%    Z_0:   Initial value of state\n%    V_0:   Initial value of covariance matrix\n%    loglik: Log likelihood\n%\n% References:\n%   \"Maximum likelihood estimation of factor models on data sets with\n%   arbitrary pattern of missing data\" by Banbura & Modugno (2010).\n%   Abbreviated as BM2010\n%\n%\n\n%% Initialize preliminary values\n\n% Store series/model values\n[n, T] = size(y);\nnM = n - nQ;  % Number of monthly series\npC = size(R_mat,2);\nppC = max(p,pC);\nnum_blocks = size(blocks,2);  % Number of blocks\n\n%% ESTIMATION STEP: Compute the (expected) sufficient statistics for a single\n%Kalman filter sequence\n\n% Running the Kalman filter and smoother with current parameters\n% Note that log-liklihood is NOT re-estimated after the runKF step: This\n% effectively gives the previous iteration's log-likelihood\n% For more information on output, see runKF\n[Zsmooth, Vsmooth, VVsmooth, loglik] = runKF(y, A, C, Q, R, Z_0, V_0);\n\n\n%% MAXIMIZATION STEP (TRANSITION EQUATION)\n% See (Banbura & Modugno, 2010) for details.\n\n% Initialize output\nA_new = A;\nQ_new = Q;\nV_0_new = V_0;\n\n%%% 2A. UPDATE FACTOR PARAMETERS INDIVIDUALLY ----------------------------\n\nfor i = 1:num_blocks  % Loop for each block: factors are uncorrelated\n\n    % SETUP INDEXING\n    r_i = r(i);  % r_i = 1 if block is loaded\n    rp = r_i*p;\n    rp1 = sum(r(1:i-1))*ppC;\n    b_subset = rp1+1:rp1+rp;  % Subset blocks: Helps for subsetting Zsmooth, Vsmooth\n    t_start = rp1+1;          % Transition matrix factor idx start\n    t_end = rp1+r_i*ppC;      % Transition matrix factor idx end\n\n\n\n    % ESTIMATE FACTOR PORTION OF Q, A\n    % Note: EZZ, EZZ_BB, EZZ_FB are parts of equations 6 and 8 in BM 2010\n\n    % E[f_t*f_t' | Omega_T]\n    EZZ = Zsmooth(b_subset, 2:end) * Zsmooth(b_subset, 2:end)'...\n        +sum(Vsmooth(b_subset, b_subset, 2:end) ,3);\n\n    % E[f_{t-1}*f_{t-1}' | Omega_T]\n    EZZ_BB = Zsmooth(b_subset, 1:end-1)*Zsmooth(b_subset, 1:end-1)'...\n            +sum(Vsmooth(b_subset, b_subset, 1:end-1), 3);\n\n    % E[f_t*f_{t-1}' | Omega_T]\n    EZZ_FB = Zsmooth(b_subset, 2:end)*Zsmooth(b_subset, 1:end-1)'...\n        +sum(VVsmooth(b_subset, b_subset, :), 3);\n\n    % Select transition matrix/covariance matrix for block i\n    A_i = A(t_start:t_end, t_start:t_end);\n    Q_i = Q(t_start:t_end, t_start:t_end);\n\n    % Equation 6: Estimate VAR(p) for factor\n    A_i(1:r_i,1:rp) = EZZ_FB(1:r_i,1:rp) * inv(EZZ_BB(1:rp,1:rp));\n\n    % Equation 8: Covariance matrix of residuals of VAR\n    Q_i(1:r_i,1:r_i) = (EZZ(1:r_i,1:r_i) - A_i(1:r_i,1:rp)* EZZ_FB(1:r_i,1:rp)') / T;\n\n    % Place updated results in output matrix\n    A_new(t_start:t_end, t_start:t_end) = A_i;\n    Q_new(t_start:t_end, t_start:t_end) = Q_i;\n    V_0_new(t_start:t_end, t_start:t_end) =...\n        Vsmooth(t_start:t_end, t_start:t_end,1);\nend\n\n%%% 2B. UPDATING PARAMETERS FOR IDIOSYNCRATIC COMPONENT ------------------\n\nrp1 = sum(r)*ppC;           % Col size of factor portion\nniM = sum(i_idio(1:nM));    % Number of monthly values\nt_start = rp1+1;            % Start of idiosyncratic component index\ni_subset = t_start:rp1+niM; % Gives indices for monthly idiosyncratic component values\n\n\n% Below 3 estimate the idiosyncratic component (for eqns 6, 8 BM 2010)\n\n% E[f_t*f_t' | \\Omega_T]\nEZZ = diag(diag(Zsmooth(t_start:end, 2:end) * Zsmooth(t_start:end, 2:end)'))...\n    + diag(diag(sum(Vsmooth(t_start:end, t_start:end, 2:end), 3)));\n\n% E[f_{t-1}*f_{t-1}' | \\Omega_T]\nEZZ_BB = diag(diag(Zsmooth(t_start:end, 1:end-1)* Zsmooth(t_start:end, 1:end-1)'))...\n       + diag(diag(sum(Vsmooth(t_start:end, t_start:end, 1:end-1), 3)));\n\n% E[f_t*f_{t-1}' | \\Omega_T]\nEZZ_FB = diag(diag(Zsmooth(t_start:end, 2:end)*Zsmooth(t_start:end, 1:end-1)'))...\n       + diag(diag(sum(VVsmooth(t_start:end, t_start:end, :), 3)));\n\nA_i = EZZ_FB * diag(1./diag((EZZ_BB)));  % Equation 6\nQ_i = (EZZ - A_i*EZZ_FB') / T;           % Equation 8\n\n% Place updated results in output matrix\nA_new(i_subset, i_subset) = A_i(1:niM,1:niM);\nQ_new(i_subset, i_subset) = Q_i(1:niM,1:niM);\nV_0_new(i_subset, i_subset) = diag(diag(Vsmooth(i_subset, i_subset, 1)));\n\n\n%% 3 MAXIMIZATION STEP (observation equation)\n\n%%% INITIALIZATION AND SETUP ----------------------------------------------\nZ_0 = Zsmooth(:,1); %zeros(size(Zsmooth,1),1); %\n\n% Set missing data series values to 0\nnanY = isnan(y);\ny(nanY) = 0;\n\n% LOADINGS\nC_new = C;\n\n% Blocks\nbl = unique(blocks,'rows');  % Gives unique loadings\nn_bl = size(bl,1);           % Number of unique loadings\n\n% Initialize indices: These later help with subsetting\nbl_idxM = [];  % Indicator for monthly factor loadings\nbl_idxQ = [];  % Indicator for quarterly factor loadings\nR_con = [];    % Block diagonal matrix giving monthly-quarterly aggreg scheme\nq_con = [];\n\n% Loop through each block\nfor i = 1:num_blocks\n    bl_idxQ = [bl_idxQ repmat(bl(:,i),1,r(i)*ppC)];\n    bl_idxM = [bl_idxM repmat(bl(:,i),1,r(i)) zeros(n_bl,r(i)*(ppC-1))];\n    R_con = blkdiag(R_con, kron(R_mat,eye(r(i))));\n    q_con = [q_con;zeros(r(i)*size(R_mat,1),1)];\nend\n\n% Indicator for monthly/quarterly blocks in observation matrix\nbl_idxM = logical(bl_idxM);\nbl_idxQ = logical(bl_idxQ);\n\ni_idio_M = i_idio(1:nM);            % Gives 1 for monthly series\nn_idio_M = length(find(i_idio_M));  % Number of monthly series\nc_i_idio = cumsum(i_idio);          % Cumulative number of monthly series\n\nfor i = 1:n_bl  % Loop through unique loadings (e.g. [1 0 0 0], [1 1 0 0])\n\n    bl_i = bl(i,:);\n    rs = sum(r(logical(bl_i)));                    % Total num of blocks loaded\n    idx_i = find(ismember(blocks, bl_i, 'rows'));  % Indices for bl_i\n    idx_iM = idx_i(idx_i<nM+1);                    % Only monthly\n    n_i = length(idx_iM);                          % Number of monthly series\n\n    % Initialize sums in equation 13 of BGR 2010\n    denom = zeros(n_i*rs,n_i*rs);\n    nom = zeros(n_i,rs);\n\n    % Stores monthly indicies. These are done for input robustness\n    i_idio_i = i_idio_M(idx_iM);\n    i_idio_ii = c_i_idio(idx_iM);\n    i_idio_ii = i_idio_ii(i_idio_i);\n\n    %%% UPDATE MONTHLY VARIABLES: Loop through each period ----------------\n    for t = 1:T\n        Wt = diag(~nanY(idx_iM, t));  % Gives selection matrix (1 for nonmissing values)\n\n        denom = denom +...  % E[f_t*t_t' | Omega_T]\n                kron(Zsmooth(bl_idxM(i, :), t+1) * Zsmooth(bl_idxM(i, :), t+1)' + ...\n                Vsmooth(bl_idxM(i, :), bl_idxM(i, :), t+1), Wt);\n\n        nom = nom + ...  E[y_t*f_t' | \\Omega_T]\n              y(idx_iM, t) * Zsmooth(bl_idxM(i, :), t+1)' - ...\n              Wt(:, i_idio_i) * (Zsmooth(rp1 + i_idio_ii, t+1) * ...\n              Zsmooth(bl_idxM(i, :), t+1)' + ...\n              Vsmooth(rp1 + i_idio_ii, bl_idxM(i, :), t+1));\n    end\n\n    vec_C = inv(denom)*nom(:);  % Eqn 13 BGR 2010\n\n    % Place updated monthly results in output matrix\n    C_new(idx_iM,bl_idxM(i,:)) = reshape(vec_C, n_i, rs);\n\n   %%% UPDATE QUARTERLY VARIABLES -----------------------------------------\n\n   idx_iQ = idx_i(idx_i > nM);  % Index for quarterly series\n   rps = rs * ppC;\n\n   % Monthly-quarterly aggregation scheme\n   R_con_i = R_con(:,bl_idxQ(i,:));\n   q_con_i = q_con;\n\n   no_c = ~(any(R_con_i,2));\n   R_con_i(no_c,:) = [];\n   q_con_i(no_c,:) = [];\n\n   % Loop through quarterly series in loading. This parallels monthly code\n   for j = idx_iQ'\n       % Initialization\n       denom = zeros(rps,rps);\n       nom = zeros(1,rps);\n\n       idx_jQ = j-nM;  % Ordinal position of quarterly variable\n       % Loc of factor structure corresponding to quarterly var residuals\n       i_idio_jQ = (rp1 + n_idio_M + 5*(idx_jQ-1)+1:rp1+ n_idio_M + 5*idx_jQ);\n\n       % Place quarterly values in output matrix\n       V_0_new(i_idio_jQ, i_idio_jQ) = Vsmooth(i_idio_jQ, i_idio_jQ,1);\n       A_new(i_idio_jQ(1), i_idio_jQ(1)) = A_i(i_idio_jQ(1)-rp1, i_idio_jQ(1)-rp1);\n       Q_new(i_idio_jQ(1), i_idio_jQ(1)) = Q_i(i_idio_jQ(1)-rp1, i_idio_jQ(1)-rp1);\n\n       for t=1:T\n           Wt = diag(~nanY(j,t));  % Selection matrix for quarterly values\n\n           % Intermediate steps in BGR equation 13\n           denom = denom + ...\n                   kron(Zsmooth(bl_idxQ(i,:), t+1) * Zsmooth(bl_idxQ(i,:), t+1)'...\n                 + Vsmooth(bl_idxQ(i,:), bl_idxQ(i,:), t+1), Wt);\n           nom = nom + y(j, t)*Zsmooth(bl_idxQ(i,:), t+1)';\n           nom = nom -...\n                Wt * ([1 2 3 2 1] * Zsmooth(i_idio_jQ,t+1) * ...\n                Zsmooth(bl_idxQ(i,:),t+1)'+...\n                [1 2 3 2 1]*Vsmooth(i_idio_jQ,bl_idxQ(i,:),t+1));\n       end\n\n        C_i = inv(denom) * nom';\n        C_i_constr = C_i - ...  % BGR equation 13\n                     inv(denom) * R_con_i'*inv(R_con_i*inv(denom)*R_con_i') * (R_con_i*C_i-q_con_i);\n\n        % Place updated values in output structure\n        C_new(j,bl_idxQ(i,:)) = C_i_constr;\n   end\nend\n\n%%% 3B. UPDATE COVARIANCE OF RESIDUALS FOR OBSERVATION EQUATION -----------\n% Initialize covariance of residuals of observation equation\nR_new = zeros(n,n);\nfor t=1:T\n    Wt = diag(~nanY(:,t));  % Selection matrix\n    R_new = R_new + (y(:,t) - ...  % BGR equation 15\n            Wt * C_new * Zsmooth(:, t+1)) * (y(:,t) - Wt*C_new*Zsmooth(:,t+1))'...\n           + Wt*C_new*Vsmooth(:,:,t+1)*C_new'*Wt + (eye(n)-Wt)*R*(eye(n)-Wt);\nend\n\n\nR_new = R_new/T;\nRR = diag(R_new); %RR(RR<1e-2) = 1e-2;\nRR(i_idio_M) = 1e-04;  % Ensure non-zero measurement error. See Doz, Giannone, Reichlin (2012) for reference.\nRR(nM+1:end) = 1e-04;\nR_new = diag(RR);\n\nend\n\n\n\n%--------------------------------------------------------------------------\n\nfunction [converged, decrease] = em_converged(loglik, previous_loglik, threshold, check_decreased)\n%em_converged    checks whether EM algorithm has converged\n%\n%  Syntax:\n%    [converged, decrease] = em_converged(loglik, previous_loglik, threshold, check_increased)\n%\n%  Description:\n%    em_converged() checks whether EM has converged. Convergence occurs if\n%    the slope of the log-likelihood function falls below 'threshold'(i.e.\n%    f(t) - f(t-1)| / avg < threshold) where avg = (|f(t)| + |f(t-1)|)/2\n%    and f(t) is log lik at iteration t. 'threshold' defaults to 1e-4.\n%\n%    This stopping criterion is from Numerical Recipes in C (pg. 423).\n%    With MAP estimation (using priors), the likelihood can decrease\n%    even if the mode of the posterior increases.\n%\n%  Input arguments:\n%    loglik: Log-likelihood from current EM iteration\n%    previous_loglik: Log-likelihood from previous EM iteration\n%    threshold: Convergence threshhold. The default is 1e-4.\n%    check_decreased: Returns text output if log-likelihood decreases.\n%\n%  Output:\n%    converged (numeric): Returns 1 if convergence criteria satisfied, and 0 otherwise.\n%    decrease (numeric): Returns 1 if loglikelihood decreased.\n\n%% Instantiate variables\n\n% Threshhold arguments: Checks default behavior\nif nargin < 3, threshold = 1e-4; end\nif nargin < 4, check_decreased = 1; end\n\n% Initialize output\nconverged = 0;\ndecrease = 0;\n\n%% Check if log-likelihood decreases (optional)\n\nif check_decreased\n    if loglik - previous_loglik < -1e-3 % allow for a little imprecision\n        fprintf(1, '******likelihood decreased from %6.4f to %6.4f!\\n', previous_loglik, loglik);\n        decrease = 1;\n    end\nend\n\n%% Check convergence criteria\n\ndelta_loglik = abs(loglik - previous_loglik);  % Difference in loglik\navg_loglik = (abs(loglik) + abs(previous_loglik) + eps)/2;\n\nif (delta_loglik / avg_loglik) < threshold,\n    converged = 1;  % Check convergence\nend\n\nend\n\n%--------------------------------------------------------------------------\n\n%InitCond()      Calculates initial conditions for parameter estimation\n%\n%  Description:\n%    Given standardized data and model information, InitCond() creates\n%    initial parameter estimates. These are intial inputs in the EM\n%    algorithm, which re-estimates these parameters using Kalman filtering\n%    techniques.\n%\n%Inputs:\n%  - x:      Standardized data\n%  - r:      Number of common factors for each block\n%  - p:      Number of lags in transition equation\n%  - blocks: Gives series loadings\n%  - optNaN: Option for missing values in spline. See remNaNs_spline() for details.\n%  - Rcon:   Incorporates estimation for quarterly series (i.e. \"tent structure\")\n%  - q:      Constraints on loadings for quarterly variables\n%  - NQ:     Number of quarterly variables\n%  - i_idio: Logical. Gives index for monthly variables (1) and quarterly (0)\n%\n%Output:\n%  - A:   Transition matrix\n%  - C:   Observation matrix\n%  - Q:   Covariance for transition equation residuals\n%  - R:   Covariance for observation equation residuals\n%  - Z_0: Initial value of state\n%  - V_0: Initial value of covariance matrix\n\nfunction [ A, C, Q, R, Z_0, V_0] = InitCond(x,r,p,blocks,optNaN,Rcon,q,nQ,i_idio)\n\npC = size(Rcon,2);  % Gives 'tent' structure size (quarterly to monthly)\nppC = max(p,pC);\nn_b = size(blocks,2);  % Number of blocks\n\nOPTS.disp=0;  % Turns off diagnostic information for eigenvalue computation\n[xBal,indNaN] = remNaNs_spline(x,optNaN);  % Spline without NaNs\n\n[T,N] = size(xBal);  % Time T series number N\nnM = N-nQ;           % Number of monthly series\n\nxNaN = xBal;\nxNaN(indNaN) = nan;  % Set missing values equal to NaNs\nres = xBal;          % Spline output equal to res: Later this is used for residuals\nresNaN = xNaN;       % Later used for residuals\n\n% Initialize model coefficient output\nC = [];\nA = [];\nQ = [];\nV_0 = [];\n\n% Set the first observations as NaNs: For quarterly-monthly aggreg. scheme\nindNaN(1:pC-1,:) = true;\n\nfor i = 1:n_b  % Loop for each block\n\n    r_i = r(i);  % r_i = 1 when block is loaded\n\n    %% Observation equation -----------------------------------------------\n\n    C_i = zeros(N,r_i*ppC);     % Initialize state variable matrix helper\n    idx_i = find(blocks(:,i));  % Returns series index loading block i\n    idx_iM = idx_i(idx_i<nM+1); % Monthly series indicies for loaded blocks\n    idx_iQ = idx_i(idx_i>nM);   % Quarterly series indicies for loaded blocks\n\n\n\n    % Returns eigenvector v w/largest eigenvalue d\n    [v, d] = eigs(cov(res(:,idx_iM)), r_i, 'lm');\n\n    % Flip sign for cleaner output. Gives equivalent results without this section\n    if(sum(v) < 0)\n        v = -v;\n    end\n\n    % For monthly series with loaded blocks (rows), replace with eigenvector\n    % This gives the loading\n    C_i(idx_iM,1:r_i) = v;\n    f = res(:,idx_iM)*v;  % Data projection for eigenvector direction\n    F = [];\n\n    % Lag matrix using loading. This is later used for quarterly series\n    for kk = 0:max(p+1,pC)-1\n        F = [F f(pC-kk:end-kk,:)];\n    end\n\n    Rcon_i = kron(Rcon,eye(r_i));  % Quarterly-monthly aggregation scheme\n    q_i = kron(q,zeros(r_i,1));\n\n    % Produces projected data with lag structure (so pC-1 fewer entries)\n    ff = F(:, 1:r_i*pC);\n\n    for j = idx_iQ'      % Loop for quarterly variables\n\n        % For series j, values are dropped to accommodate lag structure\n        xx_j = resNaN(pC:end,j);\n\n        if sum(~isnan(xx_j)) < size(ff,2)+2\n            xx_j = res(pC:end,j);  % Replaces xx_j with spline if too many NaNs\n\n        end\n\n        ff_j = ff(~isnan(xx_j),:);\n        xx_j = xx_j(~isnan(xx_j));\n\n        iff_j = inv(ff_j'*ff_j);\n        Cc = iff_j*ff_j'*xx_j;  % Least squares\n\n        % Spline data monthly to quarterly conversion\n        Cc = Cc - iff_j*Rcon_i'*inv(Rcon_i*iff_j*Rcon_i')*(Rcon_i*Cc-q_i);\n\n        C_i(j,1:pC*r_i)=Cc';  % Place in output matrix\n    end\n\n    ff = [zeros(pC-1,pC*r_i);ff];  % Zeros in first pC-1 entries (replace dropped from lag)\n\n    % Residual calculations\n    res = res - ff*C_i';\n    resNaN = res;\n    resNaN(indNaN) = nan;\n\n    C = [C C_i];  % Combine past loadings together\n\n\n    %% Transition equation ------------------------------------------------\n\n    z = F(:,1:r_i);            % Projected data (no lag)\n    Z = F(:,r_i+1:r_i*(p+1));  % Data with lag 1\n\n    A_i = zeros(r_i*ppC,r_i*ppC)';  % Initialize transition matrix\n\n    A_temp = inv(Z'*Z)*Z'*z;  % OLS: gives coefficient value AR(p) process\n    A_i(1:r_i,1:r_i*p) = A_temp';\n    A_i(r_i+1:end,1:r_i*(ppC-1)) = eye(r_i*(ppC-1));\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    Q_i = zeros(ppC*r_i,ppC*r_i);\n    e = z  - Z*A_temp;         % VAR residuals\n    Q_i(1:r_i,1:r_i) = cov(e); % VAR covariance matrix\n\n    initV_i = reshape(inv(eye((r_i*ppC)^2)-kron(A_i,A_i))*Q_i(:),r_i*ppC,r_i*ppC);\n\n    % Gives top left block for the transition matrix\n    A = blkdiag(A,A_i);\n    Q = blkdiag(Q,Q_i);\n    V_0 = blkdiag(V_0,initV_i);\nend\n\neyeN = eye(N);  % Used inside observation matrix\neyeN(:,~i_idio) = [];\n\nC=[C eyeN];\nC = [C [zeros(nM,5*nQ); kron(eye(nQ),[1 2 3 2 1])]];  % Monthly-quarterly agreggation scheme\nR = diag(var(resNaN,'omitnan'));  % Initialize covariance matrix for transition matrix\n\n\nii_idio = find(i_idio);    % Indicies for monthly variables\nn_idio = length(ii_idio);  % Number of monthly variables\nBM = zeros(n_idio);        % Initialize monthly transition matrix values\nSM = zeros(n_idio);        % Initialize monthly residual covariance matrix values\n\n\nfor i = 1:n_idio;  % Loop for monthly variables\n    % Set observation equation residual covariance matrix diagonal\n    R(ii_idio(i),ii_idio(i)) = 1e-04;\n\n    % Subsetting series residuals for series i\n    res_i = resNaN(:,ii_idio(i));\n\n    % Returns number of leading/ending zeros\n    leadZero = max( find( (1:T)' == cumsum(isnan(res_i)) ) );\n    endZero  = max( find( (1:T)' == cumsum(isnan(res_i(end:-1:1))) ) );\n\n    % Truncate leading and ending zeros\n    res_i = res(:,ii_idio(i));\n    res_i(end-endZero + 1:end) = [];\n    res_i(1:leadZero) = [];\n\n    % Linear regression: AR 1 process for monthly series residuals\n    BM(i,i) = inv(res_i(1:end-1)'*res_i(1:end-1))*res_i(1:end-1)'*res_i(2:end,:);\n    SM(i,i) = cov(res_i(2:end)-res_i(1:end-1)*BM(i,i));  % Residual covariance matrix\n\nend\n\nRdiag = diag(R);\nsig_e = Rdiag(nM+1:N)/19;\nRdiag(nM+1:N) = 1e-04;\nR = diag(Rdiag);  % Covariance for obs matrix residuals\n\n% For BQ, SQ\nrho0 = 0.1;\ntemp = zeros(5);\ntemp(1,1) = 1;\n\n% Blocks for covariance matrices\nSQ = kron(diag((1-rho0^2)*sig_e),temp);\nBQ = kron(eye(nQ),[[rho0 zeros(1,4)];[eye(4),zeros(4,1)]]);\ninitViQ = reshape(inv(eye((5*nQ)^2)-kron(BQ,BQ))*SQ(:),5*nQ,5*nQ);\ninitViM = diag(1./diag(eye(size(BM,1))-BM.^2)).*SM;\n\n% Output\nA = blkdiag(A, BM, BQ);                % Observation matrix\nQ = blkdiag(Q, SM, SQ);                % Residual covariance matrix (transition)\nZ_0 = zeros(size(A,1),1);              % States\nV_0 = blkdiag(V_0, initViM, initViQ);  % Covariance of states\n\nend\n\n\n\nfunction [zsmooth, Vsmooth, VVsmooth, loglik] = runKF(Y, A, C, Q, R, Z_0, V_0);\n%runKF()    Applies Kalman filter and fixed-interval smoother\n%\n%  Syntax:\n%    [zsmooth, Vsmooth, VVsmooth, loglik] = runKF(Y, A, C, Q, R, Z_0, V_0)\n%\n%  Description:\n%    runKF() applies a Kalman filter and fixed-interval smoother. The\n%    script uses the following model:\n%           Y_t = C_t Z_t + e_t for e_t ~ N(0, R)\n%           Z_t = A Z_{t-1} + mu_t for mu_t ~ N(0, Q)\n\n%  Throughout this file:\n%    'm' denotes the number of elements in the state vector Z_t.\n%    'k' denotes the number of elements (observed variables) in Y_t.\n%    'nobs' denotes the number of time periods for which data are observed.\n%\n%  Input parameters:\n%    Y: k-by-nobs matrix of input data\n%    A: m-by-m transition matrix \n%    C: k-by-m observation matrix\n%    Q: m-by-m covariance matrix for transition equation residuals (mu_t)\n%    R: k-by-k covariance for observation matrix residuals (e_t)\n%    Z_0: 1-by-m vector, initial value of state\n%    V_0: m-by-m matrix, initial value of state covariance matrix\n%\n%  Output parameters:\n%    zsmooth: k-by-(nobs+1) matrix, smoothed factor estimates\n%             (i.e. zsmooth(:,t+1) = Z_t|T)\n%    Vsmooth: k-by-k-by-(nobs+1) array, smoothed factor covariance matrices\n%             (i.e. Vsmooth(:,:,t+1) = Cov(Z_t|T))\n%    VVsmooth: k-by-k-by-nobs array, lag 1 factor covariance matrices\n%              (i.e. Cov(Z_t,Z_t-1|T))\n%    loglik: scalar, log-likelihood\n%\n%  References:\n%  - QuantEcon's \"A First Look at the Kalman Filter\"\n%  - Adapted from replication files for:\n%    \"Nowcasting\", 2010, (by Marta Banbura, Domenico Giannone and Lucrezia \n%    Reichlin), in Michael P. Clements and David F. Hendry, editors, Oxford \n%    Handbook on Economic Forecasting.\n%\n% The software can be freely used in applications. \n% Users are kindly requested to add acknowledgements to published work and \n% to cite the above reference in any resulting publications\n\nS = SKF(Y, A, C, Q, R, Z_0, V_0);  % Kalman filter\nS = FIS(A, S);                     % Fixed interval smoother\n\n% Organize output \nzsmooth = S.ZmT;\nVsmooth = S.VmT;\nVVsmooth = S.VmT_1;\nloglik = S.loglik;\n\nend\n\n%______________________________________________________________________\nfunction S = SKF(Y, A, C, Q, R, Z_0, V_0)\n%SKF    Applies Kalman filter\n%\n%  Syntax:\n%    S = SKF(Y, A, C, Q, R, Z_0, V_0)\n%\n%  Description:\n%    SKF() applies the Kalman filter\n\n%  Input parameters:\n%    Y: k-by-nobs matrix of input data\n%    A: m-by-m transition matrix \n%    C: k-by-m observation matrix\n%    Q: m-by-m covariance matrix for transition equation residuals (mu_t)\n%    R: k-by-k covariance for observation matrix residuals (e_t)\n%    Z_0: 1-by-m vector, initial value of state\n%    V_0: m-by-m matrix, initial value of state covariance matrix\n%\n%  Output parameters:\n%    S.Zm: m-by-nobs matrix, prior/predicted factor state vector\n%          (S.Zm(:,t) = Z_t|t-1)\n%    S.ZmU: m-by-(nobs+1) matrix, posterior/updated state vector\n%           (S.Zm(t+1) = Z_t|t)\n%    S.Vm: m-by-m-by-nobs array, prior/predicted covariance of factor\n%          state vector (S.Vm(:,:,t) = V_t|t-1)  \n%    S.VmU: m-by-m-by-(nobs+1) array, posterior/updated covariance of\n%           factor state vector (S.VmU(:,:,t+1) = V_t|t)\n%    S.loglik: scalar, value of likelihood function\n%    S.k_t: k-by-m Kalman gain\n  \n%% INITIALIZE OUTPUT VALUES ---------------------------------------------\n  % Output structure & dimensions of state space matrix\n  [~, m] = size(C);\n  \n  % Outputs time for data matrix. \"number of observations\"\n  nobs  = size(Y,2);\n  \n  % Instantiate output\n  S.Zm  = nan(m, nobs);       % Z_t | t-1 (prior)\n  S.Vm  = nan(m, m, nobs);    % V_t | t-1 (prior)\n  S.ZmU = nan(m, nobs+1);     % Z_t | t (posterior/updated)\n  S.VmU = nan(m, m, nobs+1);  % V_t | t (posterior/updated)\n  S.loglik = 0;\n\n%% SET INITIAL VALUES ----------------------------------------------------\n  Zu = Z_0;  % Z_0|0 (In below loop, Zu gives Z_t | t)\n  Vu = V_0;  % V_0|0 (In below loop, Vu guvse V_t | t)\n  \n  % Store initial values\n  S.ZmU(:,1)    = Zu;\n  S.VmU(:,:,1)  = Vu;\n\n%% KALMAN FILTER PROCEDURE ----------------------------------------------\n  for t = 1:nobs\n      %%% CALCULATING PRIOR DISTIBUTION----------------------------------\n      \n      % Use transition eqn to create prior estimate for factor\n      % i.e. Z = Z_t|t-1\n      Z   = A * Zu;\n      \n      % Prior covariance matrix of Z (i.e. V = V_t|t-1)\n      %   Var(Z) = Var(A*Z + u_t) = Var(A*Z) + Var(\\epsilon) = \n      %   A*Vu*A' + Q\n      V   = A * Vu* A' + Q; \n      V   =  0.5 * (V+V');  % Trick to make symmetric\n      \n      %%% CALCULATING POSTERIOR DISTRIBUTION ----------------------------\n       \n      % Removes missing series: These are removed from Y, C, and R\n      [Y_t, C_t, R_t, ~] = MissData(Y(:,t), C, R); \n\n      % Check if y_t contains no data. If so, replace Zu and Vu with prior.\n      if isempty(Y_t)\n          Zu = Z;\n          Vu = V;\n      else  \n          % Steps for variance and population regression coefficients:\n          % Var(c_t*Z_t + e_t) = c_t Var(A) c_t' + Var(u) = c_t*V *c_t' + R\n          VC  = V * C_t';  \n          iF  = inv(C_t * VC + R_t);\n          \n          % Matrix of population regression coefficients (QuantEcon eqn #4)\n          VCF = VC*iF;  \n\n          % Gives difference between actual and predicted observation\n          % matrix values\n          innov  = Y_t - C_t*Z;\n          \n          % Update estimate of factor values (posterior)\n          Zu  = Z  + VCF * innov;\n          \n          % Update covariance matrix (posterior) for time t\n          Vu  = V  - VCF * VC';\n          Vu   =  0.5 * (Vu+Vu'); % Approximation trick to make symmetric\n          \n          % Update log likelihood \n          S.loglik = S.loglik + 0.5*(log(det(iF))  - innov'*iF*innov);\n      end\n      \n      %%% STORE OUTPUT----------------------------------------------------\n      \n      % Store covariance and observation values for t-1 (priors)\n      S.Zm(:,t)   = Z;\n      S.Vm(:,:,t) = V;\n\n      % Store covariance and state values for t (posteriors)\n      % i.e. Zu = Z_t|t   & Vu = V_t|t\n      S.ZmU(:,t+1)    = Zu;\n      S.VmU(:,:,t+1)  = Vu;\n  end \n  \n  % Store Kalman gain k_t\n  if isempty(Y_t)\n      S.k_t = zeros(m,m);\n  else\n      S.k_t = VCF * C_t;\n  end\n  \nend\n\n\n%______________________________________________________________________\nfunction S = FIS(A, S)\n%FIS()    Applies fixed-interval smoother\n%\n%  Syntax:\n%    S = FIS(A, S)\n%\n%  Description:\n%    SKF() applies a fixed-interval smoother, and is used in conjunction \n%    with SKF(). See  page 154 of 'Forecasting, structural time series models \n%    and the Kalman filter' for more details (Harvey, 1990).\n%\n%  Input parameters:\n%    A: m-by-m transition matrix \n%    S: structure returned by SKF()\n%\n%  Output parameters:\n%    S: FIS() adds the following smoothed estimates to the S structure: \n%    - S.ZmT: m-by-(nobs+1) matrix, smoothed states\n%             (S.ZmT(:,t+1) = Z_t|T) \n%    - S.VmT: m-by-m-by-(nobs+1) array, smoothed factor covariance\n%             matrices (S.VmT(:,:,t+1) = V_t|T = Cov(Z_t|T))\n%    - S.VmT_1: m-by-m-by-nobs array, smoothed lag 1 factor covariance\n%               matrices (S.VmT_1(:,:,t) = Cov(Z_t Z_t-1|T))\n%\n%  Model:\n%   Y_t = C_t Z_t + e_t for e_t ~ N(0, R)\n%   Z_t = A Z_{t-1} + mu_t for mu_t ~ N(0, Q)\n\n%% ORGANIZE INPUT ---------------------------------------------------------\n\n% Initialize output matrices\n  [m, nobs] = size(S.Zm);\n  S.ZmT = zeros(m,nobs+1);\n  S.VmT = zeros(m,m,nobs+1);\n  \n  % Fill the final period of ZmT, VmT with SKF() posterior values\n  S.ZmT(:,nobs+1)   = squeeze(S.ZmU(:, nobs+1));\n  S.VmT(:,:,nobs+1) = squeeze(S.VmU(:,:, nobs+1));\n\n  % Initialize VmT_1 lag 1 covariance matrix for final period\n  S.VmT_1(:,:,nobs) = (eye(m)-S.k_t) *A*squeeze(S.VmU(:,:,nobs));\n  \n  % Used for recursion process. See companion file for details\n  J_2 = squeeze(S.VmU(:,:,nobs)) * A' * pinv(squeeze(S.Vm(:,:,nobs)));\n\n  %% RUN SMOOTHING ALGORITHM ----------------------------------------------\n  \n  % Loop through time reverse-chronologically (starting at final period nobs)\n    for t = nobs:-1:1\n                \n        % Store posterior and prior factor covariance values \n        VmU = squeeze(S.VmU(:,:,t));\n        Vm1 = squeeze(S.Vm(:,:,t));\n        \n        % Store previous period smoothed factor covariance and lag-1 covariance\n        V_T = squeeze(S.VmT(:,:,t+1));\n        V_T1 = squeeze(S.VmT_1(:,:,t));\n      \n        J_1 = J_2;\n                \n        % Update smoothed factor estimate\n        S.ZmT(:,t) = S.ZmU(:,t) + J_1 * (S.ZmT(:,t+1) - A * S.ZmU(:,t)) ; \n        \n        % Update smoothed factor covariance matrix\n        S.VmT(:,:,t) = VmU + J_1 * (V_T - Vm1) * J_1';   \n      \n        if t>1\n            % Update weight\n            J_2 = squeeze(S.VmU(:, :, t-1)) * A' * pinv(squeeze(S.Vm(:,:,t-1)));\n            \n            % Update lag 1 factor covariance matrix \n            S.VmT_1(:,:,t-1) = VmU * J_2'+J_1 * (V_T1 - A * VmU) * J_2';\n        end\n    end\n\nend\n\n    \nfunction [y,C,R,L]  = MissData(y,C,R)\n% Syntax:\n% Description:\n%   Eliminates the rows in y & matrices C, R that correspond to missing \n%   data (NaN) in y\n%\n% Input:\n%   y: Vector of observations at time t\n%   C: Observation matrix\n%   R: Covariance for observation matrix residuals\n%\n% Output:\n%   y: Vector of observations at time t (reduced)     \n%   C: Observation matrix (reduced)     \n%   R: Covariance for observation matrix residuals\n%   L: Used to restore standard dimensions(n x #) where # is the nr of \n%      available data in y\n  \n  % Returns 1 for nonmissing series\n  ix = ~isnan(y);\n  \n  % Index for columns with nonmissing variables\n  e  = eye(size(y,1));\n  L  = e(:,ix);\n\n  % Removes missing series\n  y  = y(ix);\n  \n  % Removes missing series from observation matrix\n  C  =  C(ix,:);  \n  \n  % Removes missing series from transition matrix\n  R  =  R(ix,ix);\n\nend\n\n", "meta": {"author": "FRBNY-TimeSeriesAnalysis", "repo": "Nowcasting", "sha": "19f365cab8269e3aac3faa11ad091d6e913c5c43", "save_path": "github-repos/MATLAB/FRBNY-TimeSeriesAnalysis-Nowcasting", "path": "github-repos/MATLAB/FRBNY-TimeSeriesAnalysis-Nowcasting/Nowcasting-19f365cab8269e3aac3faa11ad091d6e913c5c43/functions/dfm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.598021284866689}}
{"text": "function imgOut = pyrGaussGenAux(img)\n%\n%\n%        imgOut = pyrGaussGenAux(img)\n%\n%\n%        Input:\n%           -img: an image\n%\n%        Output:\n%           -imgOut: filtered img using 5x5 Gaussian filter \n%           -imgB: downsampled img at half the size\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 <http://www.gnu.org/licenses/>.\n%\n\n%5x5 Gaussian Kernel\nkernel = [1, 4, 6, 4, 1];\nmtx = kernel' * kernel;\nmtx = mtx / sum(mtx(:));\n\n%Convolution\nimgB = imfilter(img, mtx, 'replicate');\n\n%Downsampling\n[r, c] = size(img);\nimgOut = imgB(1:2:r, 1:2:c); %imresize(imgB, 0.5, 'bilinear');\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/LaplacianPyramids/pyrGaussGenAux.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5980212775626115}}
{"text": "close all\nclear all\nimage = im2double(imread('..\\2.tif'));\n\n%% proof that txt files and stage 4 size is not equal.\nprophoto2 = im2double(imread('..\\3.tif'));\n%center aligned\neucliudian_error1 = sqrt((image(:,:,1)-...\n    prophoto2(:,:,1)).^2 + ...\n    (image(:,:,2)-...\n    prophoto2(:,:,2)).^2 + ...\n    (image(:,:,3)-...\n    prophoto2(:,:,3)).^2);\nsum(eucliudian_error1(:))\nfigure,\nimagesc(eucliudian_error1, [0 0.01]);\n\n% abs()", "meta": {"author": "karaimer", "repo": "camera-pipeline-UI", "sha": "31cb1a9522242e3ed030faf89ece5aad6d732959", "save_path": "github-repos/MATLAB/karaimer-camera-pipeline-UI", "path": "github-repos/MATLAB/karaimer-camera-pipeline-UI/camera-pipeline-UI-31cb1a9522242e3ed030faf89ece5aad6d732959/image/compare_two_images.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5980212775626114}}
{"text": "function [grad, grad_W_raw] = B_weighted_average(prev_layers, curr_layer, future_layers)\n\n% raw_weights = prev_layers{1}.a;\ninput = prev_layers{2}.a;\n[dim, nFr] = size(input);\n\n% raw_weights2 = exp(raw_weights);\n% weights = raw_weights2 / sum(raw_weights2);\n\nweights = curr_layer.weights;\n\nfuture_grad = 0;\nfor i=1:length(future_layers)\n    future_grad = future_grad + future_layers{i}.grad;\nend\n\n% gradient of the input\n% grad_y = sum(future_grad,2);\ngrad_y = future_grad;\ngrad = grad_y * weights;\n\n% gradient of the weights\ngrad_W = input' * grad_y;\n\nif 1\n    grad_W_raw = weights .* grad_W' - weights * (weights * grad_W);\nelse\n    grad_W_raw = (diag(weights) - weights' * weights) * grad_W;\n    grad_W_raw = grad_W_raw';\nend\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/graph/B_weighted_average.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.598021272084747}}
{"text": "function output = FeaturePipe(input, processing, input2)\n\noutput = input;\nfor i=1:length(processing)\n    switch processing{i}.name\n        \n        % data manipulations\n\n        case 'CPU2GPU'\n            output = gpuArray(output);\n        case 'GPU2CPU'\n            output = gather(output);\n        case 'selectDim'\n            output = output(processing{i}.transform,:);\n        case {'splice', 'Splice'}\n            output = ExpandContext_v2(output, processing{i}.transform);\n        case 'stream2'  % extra input\n            output = [output; input2];\n        case 'segmentation'     % this is similar to enframe. It is usually used for high dimensional input, while enframe is usually for single/multichannel waveforms\n            seglen = processing{i}.transform(1);\n            segshift = processing{i}.transform(2);\n            % if input is 1D array, output is 2D matrix. If input is 2D matrix, output is 3D tensor.The last dimension is the number of segments\n            % Any remaining frames that is shorter than seglen is discarded.\n            output = DivideSent2Segments(output, seglen, segshift, 0);  \n        case 'transpose'\n            output = output';\n        case 'permute'\n            output = permute(output, processing{i}.transform);\n        case 'vectorize'\n            output = reshape(output,numel(output),1);\n            \n        case 'removeNonspeechFrame' % assume the input is something related to energy. Do energy based VAD first, then discard those frames classified as nonspeech\n            \n        case 'upsample'\n            \n        case 'downsample'\n\n            % signal processing\n            \n        case 'addNoise'\n            output = output + randn(size(output)) * processing{i}.transform;\n        case 'removeDC'\n            output = DC_remove(output,0.999);\n        case 'preemphasis'\n            output = filter([1 -0.97],1,output);\n        case 'enframe'\n            output = my_enframe(output, processing{i}.transform(1), processing{i}.transform(2));\n        case 'windowing'\n            switch processing{i}.transform\n                case 'hamming'\n                    window = hamming(frame_size);\n                case 'hanning'\n                    window = hanning(frame_size);\n                otherwise\n                    window = [];\n            end\n            if ~isempty(window)\n                output = bsxfun(@times, output, window);\n            end\n        case 'fft'\n            output = fft(output,processing{i}.transform);\n        case 'log'\n            if isfield(processing{i}, 'transform')\n                output = log(output+processing{i}.transform);\n            else\n                output = log(output+eps);\n            end\n        case 'power'\n            output = real(output .* conj(output));\n        case 'complex2realImag'\n            [D,nFr] = size(output);\n            output = output(1:D/2,:) + sqrt(-1)*output(D/2+1:end,:);\n        case 'realImag2complex'\n            output = [real(output); imag(output)];\n            \n            % language processing\n            \n        case 'seq2ngram'\n            output = seq2ngram(output, processing{i}.ngram, processing{i}.vocab);\n        case 'idx2vec'\n            output2 = sparse(processing{i}.outputDim, length(output));\n            for j=1:length(output)\n                output2(output(j),j)= 1;\n            end\n            output = output2;\n        case {'context_sum', 'Context_sum'}\n            context = processing{i}.transform;\n            output = SumContext(output, context);\n        case 'fulltify'\n            output = full(output);\n            \n            % temporal processing\n            \n        case 'delta'\n            output = comp_dynamic_feature(output', processing{i}.delta_order, processing{i}.delta_order)';\n        case 'dynamic'\n            D = genDeltaTransform(size(output,2), 2);\n            A = D*D;\n            output = [output; output*D'; output*A'];\n            \n            % neural networks steps\n            \n        case {'affinetransform','AffineTransform'};\n            output = processing{i}.transform * output;\n            if isfield(processing{i}, 'bias')\n                bias = processing{i}.bias;\n                output = bsxfun(@plus, output, bias(:));\n            end\n        case {'sigmoid','Sigmoid'}\n            output = sigmoid(output);\n        case {'softmax', 'Softmax'}\n            output = softmax(output);\n        case {'addshift', 'AddShift'}\n            output = bsxfun(@minus, output, processing{i}.transform');\n        case {'rescale', 'Rescale'}\n            if issparse(output)\n                visible_nonzero_idx = find(sum(abs(output),2)>0);\n                visible_nonzero = full(output(visible_nonzero_idx,:));\n                output(visible_nonzero_idx) = bsxfun(@times, visible_nonzero, processing{i}.transform(visible_nonzero_idx)');\n            else\n                output = bsxfun(@times, output, processing{i}.transform');\n            end\n        case 'linear'\n            % linear activation node, do nothings\n        case 'phoneID2posterior'\n            output = phoneID2posterior(output, length(processing{i}.classID), processing{i}.classID);\n        case 'phoneID2classID'\n            output = phoneID2classID(output, processing{i}.classID);\n \n            % normalization methods\n            \n        case 'MVN'\n            output = MVN(output')';\n        case 'CMN'\n            output = CMN(output')';\n        case 'length_norm'\n            scale = 1./sqrt(sum(output.^2,1));\n            output = bsxfun(@times, output, scale);\n\n        otherwise\n            fprintf('Error: unknown processing step: %s\\n', processing{i}.name);\n            break;\n    end\nend\nend", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/tools/FeaturePipe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5979892419986998}}
{"text": "function stroud_test2075 ( )\n\n%*****************************************************************************80\n%\n%% STROUD_TEST2075 tests the rules for EPN with GLG weight on monomials.\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  test_num = 5;\n\n  alpha_test = [ - 0.5, 0.0, 0.5, 1.0, 2.0 ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'STROUD_TEST2075\\n' );\n  fprintf ( 1, '  Demonstrate the use of quadrature rules for the region\\n' );\n  fprintf ( 1, '  EPN_GLG, that is, the positive half space [0,+oo)^N, with the\\n' );\n  fprintf ( 1, '  weight W(ALPHA;X) = product ( 1 <= I <= N ) X(I)^ALPHA exp ( -X(I) )\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  We use the formulas to integrate various monomials of\\n' );\n  fprintf ( 1, '  the form X(1)^E(1) * X(2)^E(2) * ... X(N)^E(N)\\n' );\n  fprintf ( 1, '  and compare to the exact integral.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The precision of each formula is known, and we only use\\n' );\n  fprintf ( 1, '  a formula if its precision indicates it should be able to\\n' );\n  fprintf ( 1, '  produce an exact result.\\n' );\n\n  for n = 1 : 6\n\n    expon = zeros ( n, 1 );\n    for test = 1 : test_num\n      alpha = alpha_test(test);\n      epn_glg_test ( n, expon, alpha );\n    end\n\n    expon = zeros ( n, 1 );\n    expon(n) = 1;\n    for test = 1 : test_num\n      alpha = alpha_test(test);\n      epn_glg_test ( n, expon, alpha );\n    end\n\n    if ( 2 <= n )\n      expon = zeros ( n, 1 );\n      expon(1) = 1;\n      expon(2) = 1;\n      for test = 1 : test_num\n        alpha = alpha_test(test);\n        epn_glg_test ( n, expon, alpha );\n      end\n    end\n\n    expon = zeros ( n, 1 );\n    expon(1) = 2;\n    for test = 1 : test_num\n      alpha = alpha_test(test);\n      epn_glg_test ( n, expon, alpha );\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/stroud/stroud_test2075.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.5979115106318221}}
{"text": "function b = ismonom(a)\n% function B = ismonom(A)\n%\n% DESCRIPTION\n%   Returns true for a monomial or a vector or matrix of monomials.\n%\n% INPUTS\n%   A: polynomial\n%\n% OUTPUTS\n%   B: 1 if A is a monomial or a vector or matrix of monomials.  Returns\n%      0 otherwise.\n%\n% SYNTAX\n%   B = ismonom(A);\n\n% 1/29/2008: PJS  Initial Coding\n\nif isa(a,'double') && a==1\n    b = true;\n    return;\nelseif ~isa(a,'polynomial')\n    b = false;\n    return;\nend\n\n% acoef will be Nterms-by-(Nrows*Ncols)\nacoef = a.coefficient;\n\nif all(nonzeros(acoef)==1) && all(sum(acoef,1)==1)\n    b = true;\nelse\n    b = false;\nend\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SOSTOOLS.300/SOSTOOLS.300/multipoly/ismonom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867585368344, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.5979114855553294}}
{"text": "function [symbol,labelx,labely] = sectionLabels(type)\n\n\nswitch lower(type)\n  \n  case 'alpha'\n    \n    symbol = '\\alpha';\n    labelx = '$\\gamma$';\n    labely = '$\\beta$';\n    \n  case 'gamma'\n    \n    symbol = '\\gamma';\n    labelx = '$\\alpha$';\n    labely = '$\\beta$';\n    \n    \n  case 'phi1'\n    \n    symbol = '\\varphi_1';\n    labelx = '$\\varphi_2$';\n    labely = '$\\Phi$';\n    \n  case 'phi2'\n    \n    symbol = '\\varphi_2';\n    labelx = '$\\varphi_1$';\n    labely = '$\\Phi$';\n    \n    \n  case 'sigma'\n    \n    symbol = '\\sigma';\n    labelx = '$\\sigma_2$';\n    labely = '$\\Phi$';   \n    \n  case 'omega'\n    \n    symbol = '\\omega';\n    labelx = '$\\theta$';\n    labely = '$\\rho$';\n    \n  case 'axisangle'\n    \n    symbol = '\\theta';\n    labelx = '$\\r$';\n    labely = '$\\Theta$';\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/plotting/plotting_tools/sectionLabels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5979110981714573}}
{"text": "function example4 ( )\n\n%*****************************************************************************80\n%\n%% EXAMPLE4 uses BVP4C to solve the EXAMPLE4 problem.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    07 September 2013\n%\n%  Author:\n%\n%    Original MATLAB version by Shampine, Kierzenka, Reichelt.\n%    This version by John Burkardt.\n%\n%  Reference:\n%\n%    Lawrence Shampine, Jacek Kierzenka, Mark Reichelt,\n%    Solving boundary value problems for ordinary differential equations\n%    in MATLAB with bvp4c.\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'EXAMPLE4:\\n' );\n  fprintf ( 1, '  MATLAB version\\n' );\n  fprintf ( 1, '  Use BVP4C to solve a boundary value problem with\\n' );\n  fprintf ( 1, '  a periodic solution of unknown period P.\\n' );\n  fprintf ( 1, '  We solve this on [0,1], with P an additional unknown.\\n' );\n  fprintf ( 1, '  y'' = 3 ( y + z - y^3/3 - 1.3\\n' );\n  fprintf ( 1, '  z'' = - ( y - 0.7 + 0.8 * z ) / 3\\n' );\n  fprintf ( 1, '  y(0) = y(P), z(0) = z(P)\\n' );\n  fprintf ( 1, '  Use initial guess y = sin ( 2 pi x ), z = cos ( 2 pi x ).\\n' );\n%\n%  Set SOLINIT, the structure defining the initial guess.\n%\n  x_init = linspace ( 0.0, 1.0, 5 );\n  p_init = 2.0 * pi;\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Initial estimate for P is %g\\n', p_init );\n  solinit = bvpinit ( x_init, @example4_init, p_init );\n%\n%  Have BVP4C solve the problem.\n%\n  sol = bvp4c ( @example4_ode, @example4_bc, solinit );\n%\n%  Retrieve the updated value of the period.\n%\n  p = sol.parameters;\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Period P = %g\\n', p );\n%\n%  Use DEVAL to evaluate the solution.\n%\n  x = linspace ( 0.0, 1.0, 101 );\n  px = p * x;\n  sol = deval ( sol, x );\n%\n%  Evaluate the initial guess on the initial grid [0,1].\n%\n  y_init = example4_init ( x );\n%\n%  Display a plot of Y versus initial guess.\n%\n  plot ( px, sol(1,:), 'r-', ...\n         px, y_init(1,:), 'g-', 'Linewidth', 2 );\n  xlabel ( '<--- X --->', 'Fontsize', 16 );\n  ylabel ( '<--- Y --->', 'Fontsize', 16 );\n  title ( 'EXAMPLE4: Y(red) versus initial guess (green)', 'Fontsize', 16 )\n  grid on\n  filename = 'example4.png';\n  print ( '-dpng', filename );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Saving plot file as \"%s\"\\n', filename );\n%\n%  Terminate.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'EXAMPLE4:\\n' );\n  fprintf ( 1, '  Normal end of execution.\\n' );\n  fprintf ( 1, '\\n' );\n  timestamp ( );\n\n  return\nend\nfunction y = example4_init ( x )\n\n%*****************************************************************************80\n%\n%% EXAMPLE4_INIT evaluates the initial guess for the solution.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    07 September 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X, the point at which the ODE is to be evaluated.\n%\n%    Output, real Y(M,1), the value of the initial guess.\n%\n  y(1,:) = sin ( 2.0 * pi * x );\n  y(2,:) = cos ( 2.0 * pi * x );\n\n  return\nend\nfunction dydx = example4_ode ( x, y, p )\n\n%*****************************************************************************80\n%\n%% EXAMPLE4_ODE evaluates the right hand side of the ODE.\n%\n%  Discussion:\n%\n%    We assume that the differential equation has been rewritten as a\n%    system of first order equations of the form\n%\n%      dydx = f(x,y)\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    07 September 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X, the point at which the ODE is to be evaluated.\n%\n%    Input, real Y(M), the value of the solution at X.\n%\n%    Input, real P, the estimate for the period.\n%\n%    Output, real DYDX(M), the value of the right hand side given X and Y.\n%\n  dydx(1,1) = p * 3.0 * ( y(1) + y(2) - ( y(1) )^3 / 3.0 - 1.3 );\n  dydx(2,1) =  - p * ( y(1) - 0.7 + 0.8 * y(2) ) / 3.0;\n\n  return\nend\nfunction bc = example4_bc ( ya, yb, p )\n\n%*****************************************************************************80\n%\n%% EXAMPLE4_BC evaluates the boundary conditions.\n%\n%  Discussion:\n%\n%    The third boundary condition applies the phase condition, and eliminates\n%    the spurious solution y'(x) = 0, and solutions with p = 0.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    05 September 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real YA(M), YB(M), the solution value at the left and right endpoints.\n%\n%    Input, real P, the estimate for the period.\n%\n%    Output, real BC(M), the value of the boundary conditions.\n%\n  bc(1,1) = ya(1) - yb(1);\n  bc(2,1) = ya(2) - yb(2);\n  bc(3,1) = p * ( ya(1) - 0.7 + 0.8 * ya(2) ) / 3.0 - 1.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/bvp4c/example4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.5978571566346172}}
{"text": "function [ x, seed ] = r8vec_uniform_01 ( n, seed )\n\n%*****************************************************************************80\n%\n%% R8VEC_UNIFORM_01 returns a unit pseudorandom R8VEC.\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 entries in the vector.\n%\n%    Input, integer SEED, a seed for the random number generator.\n%\n%    Output, real X(N,1), the vector of pseudorandom values.\n%\n%    Output, integer SEED, an updated seed for the random number generator.\n%\n  x = zeros ( n, 1 );\n\n  i4_huge = 2147483647;\n\n  if ( seed == 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8VEC_UNIFORM_01 - Fatal error!\\n' );\n    fprintf ( 1, '  Input SEED = 0!\\n' );\n    error ( 'R8VEC_UNIFORM_01 - Fatal error!' );\n  end\n\n  r = zeros ( n, 1 );\n\n  for i = 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    x(i) = seed * 4.656612875E-10;\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/normal/r8vec_uniform_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5978571526670677}}
{"text": "function [ x, seed ] = r4vec_uniform_ab ( n, a, b, seed )\n\n%*****************************************************************************80\n%\n%% R4VEC_UNIFORM_AB returns a scaled pseudorandom R4VEC.\n%\n%  Discussion:\n%\n%    Each dimension ranges from A to B.\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 N, the number of entries in the vector.\n%\n%    Input, real A, B, the range of the pseudorandom values.\n%\n%    Input, integer SEED, a seed for the random number generator.\n%\n%    Output, real X(N), the vector of pseudorandom values.\n%\n%    Output, integer SEED, an updated seed for the random number generator.\n%\n  x = zeros ( n, 1 );\n\n  if ( seed == 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R4VEC_UNIFORM_AB - Fatal error!\\n' );\n    fprintf ( 1, '  Input SEED = 0!\\n' );\n    error ( 'R4VEC_UNIFORM_AB - Fatal error!' );\n  end\n\n  for i = 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 + 2147483647;\n    end\n\n    x(i) = a + ( b - a ) * seed * 4.656612875E-10;\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/r4vec_uniform_ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.5978571445855144}}
{"text": "function [a, time_in, time_out, el] = test_resample(a_init, sfreq_out, sfreq_in)\n% TEST_RESAMPLE: Test all the methods available in Brainstorm for resamlping.\n% \n% USAGE:  test_resample(a_init, sfreq_out, sfreq_in)\n%         test_resample(a_init)\n%         test_resample()\n%         [a, time_in, time_out, el] = test_resample();\n%\n% INPUT: \n%     - a_init    : Signal to resample\n%                   Default: [cos(t);sin(t)], with t=-pi:.0001:pi\n%     - sfreq_out : Output sampling frequency\n%                   Default: 4217\n%     - sfreq_in  : Initial sampling frequency\n%                   Default: 5000\n%\n% OUTPUT:\n%     - a        : Cell-array oo the resampled signals for each method\n%     - time_in  : Input time vector (scalar)\n%     - time_out : Resampled time vector for each method \n%     - el       : Computation time for each method\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% Define input signal\nif (nargin < 1)\n    t = -pi:.0001:pi;\n    a_init = [cos(t);sin(t)];\nend\nif (nargin < 3)\n    sfreq_in  = 5000;\n    sfreq_out = 4217;\nend\ntime_in = (1:size(a_init,2)) / sfreq_in;\n\n% List of available methods\nlist_methods = {'resample', 'resample-rational', 'resample-cascade', 'interp-decimate-cascade', 'fft-spline'};\n\n% Intialize arrays\na        = cell(1,length(list_methods));\ntime_out = a;\nel       = a;\nisFigCreated = 0;\n% Loop on all the methods\nfor i = 1:length(list_methods)\n    % Method selection\n    method = list_methods{i};\n    % Resample\n    tic; \n    [a{i}, time_out{i}] = process_resample('Compute', a_init, time_in, sfreq_out, method); \n    el{i} = toc;\n    % Plot initial signal\n    if ~isFigCreated\n        isFigCreated = 1;\n        % Create figure: signal\n        hFigSignal = figure('Name', 'Resample: signal', 'NumberTitle', 'off', 'Toolbar', 'figure', 'Units', 'normalized', 'Position', [0 0 1 1]);\n        zoom on\n        % Plot signal\n        hAxesSignal(1) = PlotSignal(hFigSignal, 1, sprintf('Initial signal (%5.3fHz)', sfreq_in), time_in, a_init);\n        % Create figure: signal\n        hFigSpect(1) = figure('Name', 'Resample: |fft|', 'NumberTitle', 'off', 'Toolbar', 'figure', 'Units', 'normalized', 'Position', [0 0 1 1]);\n        zoom on\n        % Plot spectrum\n        hAxesSpect(1) = PlotSpectrum(hFigSpect, 1, sprintf('Initial signal (%5.3fHz)', sfreq_in), sfreq_in, a_init);\n    end\n    % Plot resampled signal\n    sfreq_out_effective = 1./diff(time_out{i}([1,2]));\n    axesTitle = sprintf('%s (%5.3fHz, %3.4fs)', method, sfreq_out_effective, el{i});\n    hAxesSignal(i+1) = PlotSignal(hFigSignal, i+1, axesTitle, time_out{i}, a{i});\n    % Plot resampled spectrum\n    hAxesSpect(i+1) = PlotSpectrum(hFigSpect, i+1, axesTitle, sfreq_out_effective, a{i});\nend\n% Link all axes\nlinkaxes(hAxesSignal);\nlinkaxes(hAxesSpect(2:end));\n\n\nfunction hAxes = PlotSignal(hFig, iPlot, axesTitle, t, x)\n    hAxes = subplot(2, 4, iPlot, 'Parent', hFig);\n    plot(hAxes, t, x);\n    title(hAxes, axesTitle);\n\nfunction hAxes1 = PlotSpectrum(hFig, iPlot, axesTitle, sfreq_in, x)\n    % Compute FFT\n    ntime = size(x,2);\n    nfft = 2^nextpow2(ntime);\n    Y = fft(x',nfft)' / ntime;\n    f = sfreq_in * linspace(0, 1, nfft);\n    % Plot |FFT|\n    hAxes1 = subplot(2, 4, iPlot, 'Parent', hFig(1));\n    plot(hAxes1, f, 2 * log(max(abs(Y'),1e-5))); \n    title(hAxes1, axesTitle);\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/script/test_resample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.5978571405691466}}
{"text": "function [widths, maxDepth, nodePositions] = treeGetWidths(tree)\n\n% TREEGETWIDTHS give width of each level of tree.\n% FORMAT\n% DESC gives the width of a tree at each level of the hierarchy and\n% the maximum depth of a tree as well as the node stored at a give\n% depth and breadth.\n% ARG tree : the tree for which the dimensions are required.\n% RETURN widths : stores the width at each depth level. \n% RETURN maxDepth : the maximum depth of the tree.\n% RETURN nodePositions : stores the nodeIndex present at depth i\n% and breadth j.\n%\n% COPYRIGHT : Andrew J. Moore, 2006\n% \n% SEEALSO : treeFindParents, treeFindChildren\n\n% NDLUTIL\n\nmaxDepth = 0;\n%widths stores the width at each depth level. Since the max depth isn't yet\n%known, allocate enough memory to widths for the worst case scenario where\n%each node has only 1 child and the depth is equal to the number of nodes.\nwidths = zeros(length(tree), 1);\n%nodePositions \nnodePositions = zeros(length(tree), length(tree));\nrootInd = treeFindRoots(tree);\nindAlreadySeen = [];\nfor i = 1:length(rootInd)\n  traverseTree(rootInd(i), 1);\nend\nwidths = widths(1:maxDepth, :); %trim off excess rows\n\n  function traverseTree(nodeIndex, depthLevel)\n    if ~any(indAlreadySeen == nodeIndex)\n      widths(depthLevel) = widths(depthLevel) + 1;\n    end\n    indAlreadySeen = [indAlreadySeen nodeIndex];\n\n    nodePositions(depthLevel, widths(depthLevel)) = nodeIndex;\n    if length(tree(nodeIndex).children) > 0\n      for i=1:length(tree(nodeIndex).children)\n        traverseTree(tree(nodeIndex).children(i), depthLevel + 1);\n      end\n    else\n      if depthLevel > maxDepth\n        maxDepth = depthLevel;\n      end\n    end\n  end\n\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/treeGetWidths.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.5978059737030382}}
{"text": "function a = daub10_inverse ( n )\n\n%*****************************************************************************80\n%\n%% DAUB10_INVERSE returns the inverse of the DAUB10 matrix.\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%  Parameters:\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Output, real A(N,N), the matrix.\n%\n  a = ( daub10 ( 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/daub10_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.5978059615072756}}
{"text": "function niederreiter2_test01 ( )\n\n%*****************************************************************************80\n%\n%% NIEDERREITER2_TEST01 tests SETFLD2.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    17 November 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'NIEDERREITER2_TEST01\\n' );\n  fprintf ( 1, '  SETFLD2 returns the addition, multiplication, and\\n' );\n  fprintf ( 1, '  subtraction tables for base 2.\\n' );\n\n  [ add, mul, sub ] = setfld2 ( 0 );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Addition table:\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '+  0  1\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '0  %d  %d\\n', add(1,1), add(1,2) );\n  fprintf ( 1, '1  %d  %d\\n', add(2,1), add(2,2) );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Multiplication table:\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '*  0  1\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '0  %d  %d\\n', mul(1,1), mul(1,2) );\n  fprintf ( 1, '1  %d  %d\\n', mul(2,1), mul(2,2) );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Subtraction table:\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '-  0  1\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '0  %d  %d\\n', sub(1,1), sub(1,2) );\n  fprintf ( 1, '1  %d  %d\\n', sub(2,1), sub(2,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/niederreiter2/niederreiter2_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.5978059572467667}}
{"text": "function x = mogSample(model, numSamples)\n  \n% MOGSAMPLE Sample from a mixture of Gaussians model.\n% FORMAT\n% DESC samples from a mixture of Gaussians.\n% ARG model  : the model that you want to sample from.\n% ARG numSamples : the number of samples required.\n% RETURN x : the samples from the model.\n% \n% COPYRIGHT : Neil D. Lawrence, 2008\n%\n% SEEALSO : mogCreate\n\n% MLTOOLS\n  \np = rand(numSamples, 1);\nbins = cumsum(model.prior);\ncompNo = sum(repmat(p, 1, model.m)<repmat(bins, numSamples, 1), 2);\nx = zeros(numSamples, model.d);\n\nfor i = 1:model.m\n  ind = find(compNo == i);\n  x(ind, :) = repmat(model.mean(i, :), length(ind), 1);\n  switch model.covtype\n   case 'ppca'\n    samps = randn(length(ind), model.q);\n    samps = samps*model.W{i}';\n    samps = samps + randn(length(ind), model.d)*sqrt(model.sigma2(i));\n    x(ind, :) = x(ind, :) + samps;\n   case 'spherical'\n    x(ind, :) = x(ind, :) + randn(length(ind), model.d)* ...\n        sqrt(model.sigma(i));\n  end\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/mogSample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5977892030939835}}
{"text": "function [c, s, active_set] = oasisAR1(y, g, lam, smin, active_set)\n%% Infer the most likely discretized spike train underlying an AR(1) fluorescence trace\n% Solves the sparse non-negative deconvolution problem\n%  min 1/2|c-y|^2 + lam |s|_1 subject to s_t = c_t-g c_{t-1} >=s_min or =0\n\n%% inputs:\n%   y:  T*1 vector, One dimensional array containing the fluorescence intensities\n%withone entry per time-bin.\n% OR %%\n% len_active_set*4 matrix, active set\n\n%   g:  scalar, Parameter of the AR(1) process that models the fluorescence ...\n%impulse response.\n%   lam:  scalar, sparsity penalty parameter lambda.\n%   smin: scalar, optional, default 0\n%miniumal non-zero activity within each bin (minimal 'spike size').\n%   active_set: npool x 4 matrix, warm stared active sets\n\n%% outputs\n%   c: T*1 vector, the inferred denoised fluorescence signal at each time-bin.\n%   s: T*1 vector, discetized deconvolved neural activity (spikes)\n%   active_set: npool x 4 matrix, active sets\n\n%% Authors: Pengcheng Zhou, Carnegie Mellon University, 2016\n% ported from the Python implementation from Johannes Friedrich\n\n%% References\n% Friedrich J et.al., NIPS 2016, Fast Active Set Method for Online Spike Inference from Calcium Imaging\n\n%% initialization\ny = reshape(y, [], 1);\nif isempty(y)\n    T = sum(active_set(:,4)); \nelse\nT = length(y);\nend\nif ~exist('g', 'var') || isempty(g)\n    g = estimate_time_constant(y);\nelseif length(g)>1\n    c = zeros(T,1); \n    s = zeros(T,1); \n    active_set = []; \n    return; \nend\nif ~exist('lam', 'var') || isempty(lam);   lam = 0; end\nif ~exist('smin', 'var') || isempty(smin);   smin = 0; end\nif ~exist('active_set', 'var') || isempty(active_set)\n    len_active_set = T;\n    active_set = [y-lam*(1-g),ones(T,1),(1:T)',ones(T,1),(1:T)'-1, (1:T)'+1]; % each row is one pool: (vi, wi, t, l)\n    active_set(end, :) = [y(end)-lam,1,T,1,T-1,nan] ;\n    active_set(1,5) = nan;\nelse\n    len_active_set = size(active_set,1);\n    active_set(:,5) = [nan; (1:len_active_set-1)']; \n    active_set(:,6) = [(2:len_active_set)';nan]; \nend\nidx = true(len_active_set,1);\n\n%% run OASIS\nii = 1;\nii_next = active_set(ii,6);\nwhile ~isnan(ii_next)\n    % find the active set\n    while (~isnan(ii_next)) && (active_set(ii_next,1)/active_set(ii_next,2)...\n            >=active_set(ii,1)/active_set(ii,2)*g^(active_set(ii,4))+smin)\n        active_set(ii_next,5) = ii;\n        ii = ii_next; \n        ii_next = active_set(ii,6);\n    end\n    \n    if isnan(ii_next); break; end\n    \n    %% merge pools\n    active_set(ii,1) = active_set(ii,1) + active_set(ii_next,1)* (g^(active_set(ii,4)));\n    active_set(ii,2) = active_set(ii,2) + active_set(ii_next,2)*(g^(2*active_set(ii,4)));\n    active_set(ii,4) = active_set(ii,4) + active_set(ii_next,4);\n    active_set(ii,6) = active_set(ii_next,6);\n    idx(ii_next) = false;\n    ii_next = active_set(ii,6);\n    ii_prev = active_set(ii, 5);\n\n    %% backtrack until violations fixed\n    while (~isnan(ii_prev)) && (active_set(ii,1)/active_set(ii,2)<...\n            max(0, active_set(ii_prev,1)/active_set(ii_prev,2)*g^(active_set(ii_prev,4)))+smin)\n        ii_next = ii;\n        ii = ii_prev;\n        active_set(ii,1) = active_set(ii,1) + active_set(ii_next,1)* (g^(active_set(ii,4)));\n        active_set(ii,2) = active_set(ii,2) + active_set(ii_next,2)*(g^(2*active_set(ii,4)));\n        active_set(ii,4) = active_set(ii,4) + active_set(ii_next,4);\n        active_set(ii,6) = active_set(ii_next,6);\n        idx(ii_next) = false;\n        \n        ii_prev = active_set(ii, 5);\n        ii_next = active_set(ii,6);\n    end\nend\nactive_set(~idx, :) = [];\nlen_active_set = size(active_set,1);\n\n%% construct solution for all t\nc = zeros(T, 1);\ns = c;\nfor ii=1:len_active_set\n    t0 = active_set(ii,3);\n    tau = active_set(ii, 4);\n    c(t0:(t0+tau-1)) = max(0,active_set(ii,1)/active_set(ii,2)) * (g.^(0:(tau-1)));\nend\n\ns(active_set(2:end,3)) = c(active_set(2:end,3)) - g*c(active_set(2:end,3)-1);\n", "meta": {"author": "zhoupc", "repo": "CNMF_E", "sha": "ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f", "save_path": "github-repos/MATLAB/zhoupc-CNMF_E", "path": "github-repos/MATLAB/zhoupc-CNMF_E/CNMF_E-ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f/OASIS_matlab/packages/oasis/oasisAR1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5977891962095994}}
{"text": "function P=mg_ns_prolong_step(nc,x,y,outbnd)\n%mg_ns_prolong_step  GMG prolongation operator for step domain (Navier-Stokes)\n%   P=mg_ns_prolong_step(nc,x,y,outbnd)\n%   input\n%          nc      grid parameter\n%          x       x coordinate vector for coarse grid\n%          y       y coordinate vector for coarse grid\n%          outbnd  location of outflow boundary\n%   output\n%          P       prolongation operator\n%\n%   IFISS function: HCE; 5 May 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage\n\nnelf=2^nc;nelc=nelf/2;nelcx=outbnd*nelc;\nnnf=(nelc+1)*((outbnd+1)*nelc+1)+nelc*(outbnd*nelc+1);\nnnc=(nelc/2+1)*(((outbnd+1)/2)*nelc+1)+(nelc/2)*(outbnd*nelc/2+1);\n\n% split coordinates \nx1=x(1:nelc+1); x2=x(nelc+1:end);\ny1=y(nelc+1:end); y2=y;\n\n% block size\nnnf1=nelc*(nelc+1);\nnnc1=nelc/2*(nelc/2+1);\n\nstart_col=(nelc/2+1)*(nelc/2+1);\n\n% Prolongation matrix has the form \n% P = [P_1, 0, P_2]\n%     [   0 ,  P_3]\n\n% nonzero components of upper block, for upper left of step and coupling\n[P_1,P_2]=mg_ellblock(nelc,nelc,x1,y1);\n% P(1:nnf1,1:nnc1)=P_1;                % upper block\n% P(1:nnf1,nnc-start_col+1:nnc)=P_2;   % coupling\n\n% nonzero component of lower block\nP_3=mg_prolong(nelcx,nelf,x2,y2);\n% P(nnf1+1:end,nnc1+1:end)=P_3;\n\nP = [[P_1,sparse(nnf1,nnc-start_col-nnc1),P_2];[sparse(nnf-nnf1,nnc1),P_3]];\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/solvers/mg_ns_prolong_step.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7154240079185318, "lm_q1q2_score": 0.5977249923870086}}
{"text": "function I = integral( f, varargin )\n%INTEGRAL   Complete definite integral of DISKFUN.\n%\n%   I = INTEGRAL(F), returns the definite integral of a DISKFUN integrated\n%   over its domain of definition.\n%\n%   I = INTEGRAL(F, g), returns the integral of F along the\n%   curve defined by the complex-valued CHEBFUN g.\n%\n%   I = INTEGRAL(F, 'unitcircle') returns the integral of F along the\n%   unit circle.\n% See also DISKFUN/SUM2, DISKFUN/INTEGRAL2.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n%check for empty\nif isempty(f)\n    I = 0;\n    return\nend\n\n\n% Another way to do sum2(f)\nif ( nargin == 1 )                         \n    I = integral2( f );\nelse\n    if ( ischar(varargin{1}) )\n        if ( strcmpi(varargin{1},'unitcircle') )\n            c = chebfun(@(t) exp(1i*t), [-pi, pi]);\n        else\n            error('CHEBFUN:DISKFUN:INTEGRAL:unrecognizedType',...\n                'Unrecognized line integral type.  Did you mean \"unitcircle\"');\n        end\n    else\n        c = varargin{1};\n    end\n    if ( ~isa( c, 'chebfun' ) )\n        I = integral2( f, varargin{ : } );\n    else                            % Line integral over a CHEBFUN\n        % Make complex:\n        c = c + realmin*1i;\n        % Line integral:\n        I = sum( feval(f, c ) .* abs( diff( c ) ) );\n    end    \nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@diskfun/integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5977249822483668}}
{"text": "function out = ij2xy(in, maxy)\n% out = xy2ij(in, maxy)\n%\n% Converts shapes from \"image\" coordinates to cartesian coordinates.\n% In cartesian coordinates, the origin is on the lower-left corner of\n% the image and y moves vertically while x moves horizontally.\n% Image coordinates follow a matrix notation where the origin is in\n% the upper left corner and the first coordinate 'i' moves vertically\n% (in the opposite direction of y), while the second 'j' coordinate\n% moves horizontally in the same direction as x.\n% \n%                         PARAMETERS\n%\n% in A Nx2xS matrix containing S shapes and N landmarks,\n%    in images coordinates: [i j]\n% maxy Number of rows of the image matrix, or height of the displayed image,\n%      in pixels.\n%\n%                          RETURNS\n% \n% out A Nx2xS matrix containing S shapes and N landmarks,\n%     in cartesian coordinates: [x y]\n%\n% Author: Luca Vezzaro (elvezzaro@gmail.com)\n\n\tout(:,1,:) = in(:,2,:);\n\tout(:,2,:) = repmat(maxy, [size(in, 1) 1 size(in,3)]) - in(:,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/32704-icaam-inverse-compositional-active-appearance-models/icaam/ij2xy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5977249771790457}}
{"text": "function [U,Out] = RecPF(m,n,aTV,aL1,picks,B,PsiT,Psi,opts,varargin)\n% [U,Out] = RecPF(m,n,aTV,aL1,picks,B,PsiT,Psi,opts,varargin)\n%\n% RecPF solves the TVL1-L2 model:\n%\n%   min aTV*TV(u) + aL1*|PsiT*U|_1 + 0.5|Fp*U - B|_2^2\n%\n% Inputs:\n%\n%  m, n     -- size of image\n%  aTV, aL1 -- regularization parameters in the model\n%  picks    -- sample positions in Fourier domain\n%  B        -- measurment vector\n%  PsiT     -- sparsifying basis, PsiT*U is the sparse representation of U\n%  Psi      -- inverse of PsiT, Psi*x = U reconstructs the image\n%  opts      --- contains parameters for algorithm\n%              * opts.mit_inn: maxium inner iteration number for each beta {default 30}\n%              * opts.mit_out: maxium outer iteration number {default 10} \n%              * opts.tol_inn: inner iteration error tolerance {1.e-3}\n%                (this option is effective only when \"opts.stc = 2\", see below)\n%              * opts.tol_rel_inn: tolerance of relative change in an inner iteration {5.e-2}\n%              * opts.tol_rel_out: tolerance of relative change in an outer iteration {1.e-2}\n%                (the above two options are effective only when \"opts.stc = 1\", see below)\n%              * opts.beta0:   initial penalty parameter {2^5}\n%              * opts.beta_max: final penalty parameter  {2^15}\n%              * opts.beta_rate: increase rate of beta\n%              * opts.idisp: 0 or nonzero, display inner iteration info or not\n%              * opts.recordf: 0 or 1, keep (or not) history of function values, TV and fidelity;\n%              * opts.U0: starting poing {default \"a least squares solution\"} \n%              * opts.wbarflag: 1 (on) or 0 (off), controls wait bar.\n%              * opts.stc: 1 (stopping criterion based on Relative Change) \n%                          or 2 (stopping criterion based on optimality conditions) {default 1}\n%              * opts.TVtype: 1 or 2, corresponding to anisotropic/isotropic TV {default 2}\n%  varargin{1}  -- a m x n matrix contains local weights of TV. Specifically, the local weigthed \n%                  TV is discretized as:\n%                     TV(u) = sum_i w_i ||D_i u||. \n%                  If all w_i == 1, then it is just the isotropic discritization of normal TV. \n%                  We require all w_i > 0.\n%  varargin{2}  -- true image (used to compute relative errors when it is present)\n%\n% Outputs:\n%     U   --- reconsctructed image\n%     Out --- a structrue contains\n%             * Out.iter: total iteration number\n%             * Out.Inner: inner iteration numbers for each beta\n%             * Out.ftrue: function values at each iteration \n%             * Out.Fvalvscpu: function values decrease with respect to CPU time \n%             * Out.TVhist: total variation changes with iteration \n%             * Out.FIDhist: fidelity history\n%              {the above four subfields are present only when opts.recordf = 1}\n%             * Out.ITvsERR: relative error vs. iteration number \n%             * Out.CPUvsERR: CPU time vs. relative error \n%              {the above two subfields are present only when the original image is present}\n\n%\n% Yin Zhang, 11-10-2007\n% CAAM, Rice University, Copyright (2007)\n%\n% Junfeng Yang, last modified on Feb. 2, 2009\n%\n\nglobal Ux Uy FU PsiTU\nglobal Wx Wy\nglobal Z PsiZ\nglobal beta\nglobal remain\n\nif aTV == 0 && aL1 == 0; error('No regularization' ); end\nif aTV <  0 || aL1 <  0; error('Regularization < 0'); end\nif ~exist('opts','var'); opts = []; end\n\n[mit_inn,mit_out,tol_inn,tol_rel_inn,tol_rel_out,beta0,beta_max, ...\n    beta_rate,TVtype,idisp,recordf,U0,wbarflag,stc] = setopts(opts);\n\n[Nomin1,Denom1,Denom2] = getC(picks,B,aTV,m,n);\n\nremain = setdiff(1:m*n,picks);\nif isempty(U0); U = zeros(m,n); else U = U0; clear U0; end\n\nif ~isempty(varargin)\n    Weights = varargin{1};\n    [mm,nn] = size(Weights);\n    if mm~=m || nn~= n\n        Weights = ones(m,n);\n    elseif find(Weights < 0,1)\n        error('negative weights are not allowed!');\n    end\nelse\n    Weights = ones(m,n);\nend\nif length(varargin) == 2\n    I = varargin{2};\n    nrmI = norm(I(:));  rer = norm(U(:)-I(:))/nrmI;\n    RER = zeros(500,2); RER(1,:) = [0,rer];\n    CPUvsRER = zeros(500,2); CPUvsRER(1,:) = [0,rer];\nend\n\nif aL1 > 0; PsiTU = PsiT(U); end\n\nif aTV > 0\n    Ux = [diff(U,1,2), U(:,1) - U(:,n)];\n    Uy = [diff(U,1,1); U(1,:) - U(m,:)];\nend\n\nif recordf\n    fval_true = funcval(U,aTV,aL1,B,picks);\n    FVAL = zeros(500,2);\n    FVAL(1,:) = [0,fval_true];\n    Fvalvscpu = zeros(500,2);\n    Fvalvscpu(1,:) = [0,fval_true];\n    TVhist = zeros(500,1);\n    FIDhist = zeros(500,1);\nend\n\n% initialization \nInn = zeros(100,1);\nbeta = beta0;\ntotalIter = 0;\nOutiter = 0;\nstopc = 0;\nt0 = cputime;\n\nif wbarflag == 1\n    wbar = waitbar(0, 'RecPF is running, please wait ...');\nend\n\n%% Main loop\nwhile ~stopc\n    Outiter = Outiter + 1;\n    if stc == 1; Uo = U; end\n    \n    Denom = Denom1;\n    if aTV > 0; Denom = Denom + (aTV*beta)*Denom2; end\n    if aL1 > 0; Denom = Denom + aL1*beta; end\n\n    stopci = 0; Inniter = 0; \n    while ~stopci\n\n        % ================================\n        %  Begin Alternating Minimization\n        % ----------------\n        %   W-subprolem\n        % ----------------\n        if aTV > 0;\n            switch TVtype\n                case 1;   % anisotropic TV\n                    Wx = sign(Ux).* max(abs(Ux)-Weights./beta,0);\n                    Wy = sign(Uy).* max(abs(Uy)-Weights./beta,0);\n                case 2;   % isotropic TV\n                    V = sqrt(Ux.^2 + Uy.^2);\n                    S = max(V - Weights./beta, 0);\n                    S = S ./ max(V,eps);\n                    Wx = S.*Ux; Wy = S.*Uy;\n                    clear V S\n                otherwise; error('TVtype must be 1 or 2');\n            end\n        end\n\n        % ----------------\n        %   Z-subprolem\n        % ----------------\n        if aL1 > 0;\n            Z = sign(PsiTU).*max(abs(PsiTU)-1/beta,0);\n            PsiZ = Psi(Z);\n        end\n\n        % ----------------\n        %   U-subprolem\n        % ----------------\n        if stc == 1; Ui = U; end\n        rhs = 0;\n        if aTV > 0\n            rhs = [Wx(:,end) - Wx(:, 1), -diff(Wx,1,2)];\n            rhs = rhs + [Wy(end,:) - Wy(1, :); -diff(Wy,1,1)];\n            rhs = (aTV*beta)*rhs;\n        end\n        if aL1 > 0\n            rhs = rhs + (aL1*beta)*PsiZ;\n        end\n\n        Nomin = Nomin1 + fft2(rhs);\n\n        FU = Nomin./Denom;\n        U = real(ifft2(FU));\n        Inniter = Inniter + 1;\n        totalIter = totalIter + 1;\n        %\n        %  End Alternating Minimization\n        % ================================\n\n        % -----------------------------------------\n        % check if inner stopping criterion is met\n        %\n        if stc == 1\n            if aTV > 0\n                Ux = [diff(U,1,2), U(:,1) - U(:,n)];\n                Uy = [diff(U,1,1); U(1,:) - U(m,:)];\n            end\n            if aL1 > 0; PsiTU = PsiT(U); end\n            chg_inn = norm(Ui(:) - U(:))/norm(U(:));\n            stopci = ((chg_inn < tol_rel_inn) || (Inniter >= mit_inn));\n        elseif stc == 2\n            [res_wn,res_wz,wzr,res_Zn,res_Zz,Zzr,res_u] = checkopt(U,aTV,aL1,PsiT,picks,B,0,Weights);\n            res = [res_wn,res_wz,res_Zn,res_Zz,res_u];\n            stopci = (max(res) < tol_inn || (Inniter >= mit_inn));\n        else\n            error('please specify a stopping criterion.');\n        end    \n        \n        if recordf && totalIter < 500\n            [fval_true,tvu,fidu] = funcval(U,aTV,aL1,B,picks);\n            TVhist(totalIter) = tvu;\n            FIDhist(totalIter) = fidu;\n            FVAL(totalIter+1,:) = [totalIter,fval_true];\n            Fvalvscpu(totalIter+1,:) = [cputime - t0, fval_true];\n        end\n        if exist('I','var') && totalIter < 500\n            rer = norm(U(:)-I(:))/nrmI;\n            RER(totalIter+1,:) = [totalIter,rer];\n            CPUvsRER(totalIter+1,:) = [cputime - t0, rer];\n        end\n        if idisp && stc == 2\n            fprintf('Iter: %d, res_ wn: %4.1e, wz: %4.1e, Zn: %4.1e, Zz: %4.1e, u: %4.1e, wzr %2.0f%%, Zzr %2.0f%%\\n', ...\n                totalIter, res_wn,res_wz,res_Zn,res_Zz,res_u,100*wzr,100*Zzr);\n        elseif idisp && stc == 1\n            fprintf('Iter: %d, chg_inn %4.2f\\n',totalIter,chg_inn);\n        end\n\n    end % inner\n    Inn(Outiter) = Inniter;\n\n    % ------------------------------------------\n    % check if outer stopping criterion is met\n    %\n    beta = beta_rate*beta;\n    if stc == 1\n        chg_out = norm(U(:)-Uo(:))/norm(U(:));\n        stopc = ((chg_out < tol_rel_out) || (Outiter >= mit_out));\n    elseif stc == 2\n        stopc = ((beta > beta_max) || (Outiter >= mit_out));\n    else\n        error('please specify a stopping criterion.');\n    end\n    if wbarflag == 1\n        waitbar(log2(beta)/(log2(beta_max)+1), wbar)\n    end\n    \nend % outer\nOut.iter = totalIter;\nOut.Inner = Inn(1:Outiter);\nif wbarflag == 1\n    close(wbar);\nend\nif recordf\n    Out.ftrue = FVAL(1:totalIter+1,:);\n    Out.Fvalvscpu = Fvalvscpu(1:totalIter+1,:);\n    Out.TVhist = TVhist(1:totalIter);\n    Out.FIDhist = FIDhist(1:totalIter);\nend\nif exist('I','var')\n    Out.ITvsRER  = RER(1:totalIter+1,:);\n    Out.CPUvsRER = CPUvsRER(1:totalIter+1,:);\nend\n\n%% ----------------- SUBFUNCTION ---------------------------\nfunction [res_wn,res_wz,wzr,res_Zn,res_Zz,Zzr,res_u] = ...\n    checkopt(U,aTV,aL1,PsiT,picks,f,flag,Weights)\n%\n% This function checks the optimality of\n%                   (              beta                 )\n% min   aTV * sum_i (||(W_i)||_2 + ---- ||D_iu - W_i||^2)\n%                   (               2                   )\n%\n%                   (         beta             )\n%     + aL1 *       ( |Z|_1 + ---- |Z-PsiT*u|^2 )\n%                   (           2              )\n%\n%     + .5 |F_p*u - f|^2\n%\n% where W_i = (Wx_i;Wy_i);\n%\n% U     --- current point\n% f     --- measurment vector\n% flag  --- 0 (do not check res_u), otherwise check res_u;\n%           Generally, res_u << 0, so setting flag = 0 is fine.\n% Weights -- local weights of TV\n%\n\n% Junfeng Yang, Aug. 08, 2008\n\nglobal Ux Uy FU PsiTU\nglobal Wx Wy\nglobal beta\nglobal remain\nglobal Z PsiZ\n\n[m,n] = size(U);\nmn = m*n;\n\n% res_wn, res_wz, wzr\nif aTV > 0\n    Ux = [diff(U,1,2), U(:,1) - U(:,n)];\n    Uy = [diff(U,1,1); U(1,:) - U(m,:)];\n\n    Dx = Wx - Ux;\n    Dy = Wy - Uy;\n\n    V = sqrt(Wx.^2 + Wy.^2);\n    Iz = find(V == 0);\n\n    if isempty(Iz)\n        In = 1:mn;\n    else\n        In = find(V ~= 0);\n        V(Iz) = 1;\n    end\n\n    V = V*beta;\n\n    RWx = Dx + Weights.*Wx./V;\n    RWy = Dy + Weights.*Wy./V;\n    S = sqrt(RWx.^2 + RWy.^2);\n\n    wzr = length(Iz)/mn;\n    if isempty(In)\n        res_wn = 0;\n    else\n        res_wn = max(S(In));\n    end\n\n    if isempty(Iz);\n        res_wz = -1;\n    else\n        res_wz = max(S(Iz) - Weights(Iz)/beta);\n    end\n\nelse\n    res_wn = 0;\n    res_wz = 0;\n    wzr = 0;\nend\n\n\n% res_Zn, res_Zz, Zzr\nif aL1 > 0\n    PsiTU = PsiT(U);\n    absPsiTU = abs(PsiTU);\n\n    ZIn = find(Z ~= 0);\n    if isempty(ZIn)\n        res_Zn = 0;\n    else\n        R3 = (1/beta)*sign(Z(ZIn)) + Z(ZIn) - PsiTU(ZIn);\n        res_Zn = max(abs(R3));\n    end\n\n    ZIz = find(Z == 0);\n    if isempty(ZIz)\n        res_Zz = -1;\n    else\n        R4 = absPsiTU(ZIz) - 1/beta;\n        res_Zz = max(R4);\n    end\n\n    Zzr = length(ZIz)/m/n;\n\nelse\n    PsiTU = 0;\n    res_Zn = 0;\n    res_Zz = -1;\n    Zzr = 0;\nend\n\n% res_u\nres_u = 0;\nif flag == 0\n    return;\nelse\n    % res_u\n    FU(picks) = -f + FU(picks);\n    FU(remain) = 0;\n    Ru = ifft2(FU);\n    Ru = real(Ru);\n\n    if aTV > 0\n        Dxx = [Dx(:,1) - Dx(:,n), diff(Dx,1,2)];\n        Dyy = [Dy(1,:) - Dy(m,:); diff(Dy,1,1)];\n        Ru = Ru + (beta*aTV)*(Dxx + Dyy);\n    end\n\n    if aL1 > 0\n        Ru = Ru + (aL1*beta)*(U - PsiZ);\n    end\n    res_u = max(abs(Ru(:)));\nend\n%% ------------- SUBFUNCTION ---------------\nfunction [Nomin1,Denom1,Denom2] = getC(picks,B,aTV,m,n)\n\n% compute fixed quantities\nNomin1 = zeros(m,n);\nNomin1(picks) = B;\nDenom1 = zeros(m,n);\nDenom1(picks) = 1;\nDenom2 = 0;\nif aTV > 0\n    Denom2 = abs(psf2otf([1,-1],[m,n])).^2 + abs(psf2otf([1;-1],[m,n])).^2;\nend\n%% ----------  SUBFUNCTION ---------------\nfunction [mit_inn,mit_out,tol_inn,tol_rel_inn,tol_rel_out,beta0,beta_max, ...\n    beta_rate,TVtype,idisp,recordf,U0,wbarflag,stc] = setopts(opts)\n\n% define default option fields\nmit_inn = 30;\nmit_out = 10;\ntol_inn  = 1.e-3;\ntol_rel_inn = 5.e-3;\ntol_rel_out = 1.e-2;\nbeta0 = 2^5;\nbeta_max = 2^15;\nbeta_rate = 2;\nTVtype = 2;\nidisp = 0;\nrecordf = 0;\nU0 = [];\nwbarflag = 0;\nstc = 1;\n\n% change to specified option fields if exist\nif ~isempty(opts);\n    if ~isa(opts,'struct'); error('L1pfi: opts not a struct'); end\n    if isfield(opts,'mit_inn'); mit_inn = opts.mit_inn; end\n    if isfield(opts,'mit_out'); mit_out = opts.mit_out; end\n    if isfield(opts,'tol_inn'); tol_inn = opts.tol_inn; end\n    if isfield(opts,'tol_rel_inn'); tol_rel_inn = opts.tol_rel_inn; end\n    if isfield(opts,'tol_rel_out'); tol_rel_out = opts.tol_rel_out; end\n    if isfield(opts,'beta0');   beta0 = opts.beta0; end\n    if isfield(opts,'beta_max'); beta_max = opts.beta_max; end\n    if isfield(opts,'beta_rate'); beta_rate = opts.beta_rate; end\n    if isfield(opts,'TVtype'); TVtype = opts.TVtype; end\n    if isfield(opts,'idisp'); idisp = opts.idisp; end\n    if isfield(opts,'recordf'); recordf = opts.recordf; end\n    if isfield(opts,'U0'); U0 = opts.U0; end\n    if isfield(opts,'wbarflag'); wbarflag = opts.wbarflag; end\n    if isfield(opts,'stc'); stc = opts.stc; 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/RecPF_v1.1/solver/RecPF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5977249705258505}}
{"text": "function d = cohens_d_2sample(input_values,binary_outcome)\n% d = cohens_d_2sample(input_values,binary_outcome)\n%\n% This is for the two-sample case\n% By Phil Kragel\n%\n% input_values: Continuous input values to test\n% binary_outcome: Logical vector of 1/0 values for group A/B assignment\n\nn1 = sum(~isnan(input_values(binary_outcome)) & ~isinf(input_values(binary_outcome)));\nn0 = sum(~isnan(input_values(~binary_outcome)) & ~isinf(input_values(~binary_outcome)));\n\nmeanpres = mean(input_values(binary_outcome));\nmeanabs = mean(input_values(~binary_outcome));\n\nv1 = var(input_values(binary_outcome));\nv0 = var(input_values(~binary_outcome));\n\npooledsd = sqrt((v1.*(n1-1) + v0.*(n0-1)) ./ (n1 + n0 - 2));\n\nd = (meanpres - meanabs) ./ pooledsd;\n\nend\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/cohens_d_2sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5977249697339129}}
{"text": "function [sos,g] = driving_function_imp_nfchoa_ls(N,R,r,conf)\n%DRIVING_FUNCTION_IMP_NFCHOA_LS second-order section representation for a\n%line source in NFC-HOA\n%\n%   Usage: sos = driving_function_imp_nfchoa_ls(N,R,r,conf)\n%\n%   Input parameters:\n%       N       - order of spherical Hankel function\n%       R       - radius of secondary source array / m\n%       r       - distance of line source from array center / m\n%       conf    - configuration struct (see SFS_config)\n%\n%   Output parameters:\n%       sos     - second-order section representation\n%       g       - scalar gain factor\n%\n%   See also: sound_field_imp, sound_field_imp_nfchoa,\n%       driving_function_imp_nfchoa\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 = 4;\nnargmax = 4;\nnarginchk(nargmin,nargmax);\nisargpositivescalar(N,R,r);\nisargstruct(conf);\n\n\n%% ===== Configuration ==================================================\n% Speed of sound\ndimension = conf.dimension;\ndriving_functions = conf.driving_functions;\n\n\n%% ===== Computation =====================================================\n% Find spherical Hankel function zeros\nz = sphbesselh_zeros(N);\n\n% Get the delay and weighting factors\nif strcmp('2D',dimension)\n\n    % === 2-Dimensional ==================================================\n\n    switch driving_functions\n    case 'default'\n        % --- SFS Toolbox ------------------------------------------------\n        to_be_implemented;\n    otherwise\n        error(['%s: %s, this type of driving function is not implemented', ...\n            'for a 2D line source.'],upper(mfilename),driving_functions);\n    end\n\n\nelseif strcmp('2.5D',dimension)\n\n    % === 2.5-Dimensional ================================================\n\n    switch driving_functions\n    case 'default'\n        % --- SFS Toolbox ------------------------------------------------\n        to_be_implemented;\n    otherwise\n        error(['%s: %s, this type of driving function is not implemented', ...\n            'for a 2.5D line source.'],upper(mfilename),driving_functions);\n    end\n\n\nelseif strcmp('3D',dimension)\n\n    % === 3-Dimensional ==================================================\n\n    switch driving_functions\n    case 'default'\n        % --- SFS Toolbox ------------------------------------------------\n        to_be_implemented;\n    otherwise\n        error(['%s: %s, this type of driving function is not implemented', ...\n            'for a 3D line source.'],upper(mfilename),driving_functions);\n    end\n\nelse\n    error('%s: the dimension %s is unknown.',upper(mfilename),dimension);\nend\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/driving_functions_imp/driving_function_imp_nfchoa_ls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.7154239957834734, "lm_q1q2_score": 0.5977249588033334}}
{"text": "function [germs, germPaths] = centroidalVoronoi2d(germs, poly, varargin)\n%CENTROIDALVORONOI2D Centroidal Voronoi tesselation within a polygon\n%\n%   PTS = centroidalVoronoi2d(NPTS, POLY)\n%   Generate points in a polygon based on centroidal voronoi tesselation.\n%   Centroidal germs can be computed by using the Llyod's algorithm:\n%   1) initial germs are chosen at random within polygon\n%   2) voronoi polygon of the germs is computed\n%   3) the centroids of each domain are computed, and used as germs of the\n%   next iteration\n%\n%   [PTS, PATHLIST] = centroidalVoronoi2d(NPTS, POLY)\n%   Also returns the path of each germs at each iteration. The result\n%   PATHLIST is a cell array with as many cells as the number of germs,\n%   containing in each cell the successive positions of the germ.\n%\n%   PTS = centroidalVoronoi2d(.., PARAM, VALUE)\n%   Specify one or several optional arguments. PARAM can be one of:\n%   * 'nIter'   specifies the number of iterations of the algorithm\n%       (default is 50)\n%   * 'verbose' display iteration number. Default is false.\n%\n%   Example\n%     poly = ellipseToPolygon([50 50 40 30 20], 200);\n%     nGerms = 100;\n%     germs = centroidalVoronoi2d(nGerms, poly);\n%     figure; hold on;\n%     drawPolygon(poly, 'k');\n%     drawPoint(germs, 'bo');\n%     axis equal; axis([0 100 10 90]);\n%     % extract regions of the CVD\n%     box = polygonBounds(poly);\n%     [n, e] = boundedVoronoi2d(box, germs);\n%     [n2, e2] = clipGraphPolygon(n, e, poly);\n%     drawGraphEdges(n2, e2, 'b');\n%\n%   See also\n%   graphs, boundedVoronoi2d, centroidalVoronoi2d_MC\n%\n%   Rewritten from programs found in\n%   http://people.scs.fsu.edu/~burkardt/m_src/cvt/cvt.html\n%\n%   Reference:\n%    Qiang Du, Vance Faber, and Max Gunzburger,\n%    Centroidal Voronoi Tessellations: Applications and Algorithms,\n%    SIAM Review, Volume 41, 1999, pages 637-676.\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2012-02-23,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n\n%% Parse input arguments\n\n% Number of germs\nif isscalar(germs)\n    nGerms = germs;\n    germs = [];\nelse\n    nGerms = size(germs, 1);\nend\n\n% Number of iterations\nnIter = 50;\n\nverbose = false;\n\nkeepPaths = nargout > 1;\n\nwhile length(varargin) > 1\n    paramName = varargin{1};\n    switch lower(paramName)\n        case 'verbose'\n            verbose = varargin{2};\n        case 'niter'\n            nIter = varargin{2};\n            \n        otherwise\n            error(['Unknown parameter name: ' paramName]);\n    end\n\n    varargin(1:2) = [];\nend\n\n\n%% Initialisations\n\n% bounding box of polygon\nbbox = polygonBounds(poly);\n\n% init germs if needed\nif isempty(germs)\n    germs = generatePointsInPoly(nGerms);\nend\ngermIters = cell(nIter, 1);\n\n\n%% Iteration of the Lloyd algorithm\n\nfor i = 1:nIter\n     if verbose\n        disp(sprintf('Iteration: %d/%d', i, nIter)); %#ok<DSPS>\n    end\n    \n    if keepPaths\n        germIters{i} = germs;\n    end\n    \n    % Compute Clipped Voronoi diagram of germs\n    if verbose\n        disp('  compute Voronoi Diagram');\n    end\n    [n, e, f] = boundedVoronoi2d(bbox, germs);\n    [n2, e2, f2] = clipMesh2dPolygon(n, e, f, poly); %#ok<ASGLU>\n\n    % update the position of each germ\n    if verbose\n        disp('  compute centroids');\n    end\n    for iGerm = 1:nGerms\n        polygon = n2(f2{iGerm}, :);\n        germs(iGerm,:) = polygonCentroid(polygon);\n    end\n    \nend\n\n\n%% Evenutally compute germs trajectories\n\nif nargout > 1\n    % init\n    germPaths = cell(nGerms, 1);\n    path = zeros(nIter+1, 2);\n    \n    % Iteration on germs\n    for i = 1:nGerms\n        \n        % create path corresponding to germ\n        for j = 1:nIter\n            pts = germIters{j};\n            path(j,:) = pts(i,:);\n        end\n        path(nIter+1, :) = germs(i,:);\n        \n        germPaths{i} = path;\n    end\nend\n\nfunction pts = generatePointsInPoly(nPts)\n    % extreme coordinates\n    xmin = bbox(1);  xmax = bbox(2);\n    ymin = bbox(3);  ymax = bbox(4);\n    \n    % compute size of box\n    dx = xmax - xmin;\n    dy = ymax - ymin;\n    \n    % allocate memory for result\n    pts = zeros(nPts, 2);\n\n    % iterate until all points have been sampled within the polygon\n    ind = (1:nPts)';\n    while ~isempty(ind)\n        NI = length(ind);\n        x = rand(NI, 1) * dx + xmin;\n        y = rand(NI, 1) * dy + ymin;\n        pts(ind, :) = [x y];\n        \n        ind = ind(~polygonContains(poly, pts(ind, :)));\n    end\nend\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/graphs/centroidalVoronoi2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.766293648423189, "lm_q1q2_score": 0.5977036052799041}}
{"text": "function [W,H] = nmf(X,K,alg,maxiter,speak)\n%\n% NMF wrapper function\n% function [W,H] = nmf(X,K,alg[,maxiter,speak])\n%\n% INPUT:\n%           'X'     Inputmatrix\n%           'K'     Number of components\n%           'alg'   Algorithm to use: \n%                   'mm'     multiplicative updates using euclidean\n%                            distance. Lee, D..D., and Seung, H.S., (2001)\n%                   'cjlin'  alternative non-negative least squares using \n%                            projected gradients, author: Chih-Jen Lin, \n%                            National Taiwan University.\n%                   'prob'   probabilistic NFM interpretating X as samples\n%                            from a multinomial, author: Lars Kai Hansen,\n%                            Technical University of Denmark\n%                   'als'    Alternating Least Squares. Set negative\n%                            elements to zero. \n%                   'alsobs' Alternating Least Squares. Set negative elements\n%                            to zero and adjusts the other elements acording\n%                            to Optimal Brain Surgeon. \n%           'maxiter'   Maximum number of iterations, default = 1000.\n%           'speak'     Print information to screen unless speak = 0,\n%                       default = 0\n%\n% OUTPUT:\n% W       : N x K matrix\n% H       : K x M matrix\n%\n% Kasper Winther Joergensen\n% Informatics and Mathematical Modelling\n% Technical University of Denmark\n% kwj@imm.dtu.dk\n% 2006/12/15\n\nswitch(nargin)\n    case {0,1,2}\n        error('Missing parameter. Type \"help nmf\" for usage.');\n        return\n    case 3\n        maxiter = 1000;\n        speak = 0;\n    case 4\n        speak = 0;\n    case 5\n        % empty\n    otherwise\n        error('Too many parameters. Type \"help nmf\" for usage.');\n        return\nend\n\n% find dimensionallity of X\n[D,N] = size(X);\n\n% switch algorithm \nswitch lower(alg)\n    case 'mm'\n        if speak, disp('Using mm algorithm'),end\n        [W,H]=nmf_mm(X,K,maxiter,speak);\n    case 'prob' \n        if speak, disp('Using prob algorithm'),end\n        [W,H]=nmf_prob(X,K,maxiter,speak);\n    case 'cjlin'\n        if speak, disp('Using cjlin algorithm'),end\n        [W,H]=nmf_cjlin(X,rand(D,K),rand(K,N),0.000001,10000,maxiter);\n    case 'als'\n        if speak, disp('Using als algorithm'),end\n        [W,H]=nmf_als(X,K,maxiter,speak);\n    case 'alsobs'\n        if speak, disp('Using alsobs algorithm'),end\n        [W,H]=nmf_alsobs(X,K,maxiter,speak);\n    otherwise\n        error('Unknown method. Type \"help nmf\" for usage.');\n        return\nend\n\n[W,H,nrgy] = order_comp(W,H);\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/NMF-DTU-Toolbox/nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.5977035974419505}}
{"text": "%PLOTSOM Plot the Self-Organizing Map in 2D\n%\n%    PRPLOTSOM(W)\n%\n% Plot the Self-Organizing Map W, trained by som.m. This is only\n% possible if the map is 2D.\n%\n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% SOM\n\n% Copyright: D.M.J. Tax, davidt@ph.tn.tudelft.nl\n% Faculty of Applied Physics, Delft University of Technology\n% P.O. Box 5046, 2600 GA Delft, The Netherlands\n\n% Maybe I should introduce the possibility to set the linewidth and\n% markersize... \n% \n% Changes:\n% DR1 - Dick de Ridder, 02-03-2006:\n%       If the mapped is trained on 3D data, plot it like this.\n\nfunction h = prplotsom(W)\n\nif ~ismapping(W)\n\terror('SOM mapping expected');\nend\nif ( ~strcmp(getmapping_file(W),'som') & ...\n\t ~strcmp(getmapping_file(W),'som_dd') )\n    error('I expect a SOM mapping!');\nend\nif size(W.data.neurons,2)~=2\n\terror('The SOM can only be plotted in 2D');\nend\n\n% Get the data:\nW = +W;  w=W.neurons; k=W.k;\n% Plot the bloody thing:\nhold on;\n\n% DR: Handle maps trained on 3D data.\n\nif (size(w,2) == 3)\n\t% The 'horizontal' lines:\n\tfor i=0:k(2)-1\n\t\t\th=plot3(w(i*k(1)+(1:k(1)),1),w(i*k(1)+(1:k(1)),2),w(i*k(1)+(1:k(1)),3),'o-');\n\t\t\tset(h,'linewidth',2,'markersize',8);\n\tend\n\tI = reshape(1:k(1)*k(2),k(1),k(2))';\n\t% The 'vertical' lines:\n\tfor i=0:k(1)-1\n\t\t\th=plot3(w(I(i*k(2)+(1:k(2))),1),w(I(i*k(2)+(1:k(2))),2),w(I(i*k(2)+(1:k(2))),3),'o-');\n\t\t\tset(h,'linewidth',2,'markersize',8);\n\tend\n\tview(3);\nelse\n\t% The 'horizontal' lines:\n\tfor i=0:k(2)-1\n\t\t\th=plot(w(i*k(1)+(1:k(1)),1),w(i*k(1)+(1:k(1)),2),'o-');\n\t\t\tset(h,'linewidth',2,'markersize',8);\n\tend\n\tI = reshape(1:k(1)*k(2),k(1),k(2))';\n\t% The 'vertical' lines:\n\tfor i=0:k(1)-1\n\t\t\th=plot(w(I(i*k(2)+(1:k(2))),1),w(I(i*k(2)+(1:k(2))),2),'o-');\n\t\t\tset(h,'linewidth',2,'markersize',8);\n\tend\nend;\n\n% Return the handle only when it is required\nif (nargout==0)\n\tclear h;\nend\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/prplotsom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.5977035932789497}}
{"text": "function y = tmat_mxp2 ( a, n, x )\n\n%*****************************************************************************80\n%\n%% TMAT_MXP2 multiplies a geometric transformation matrix times N points.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    23 May 2005\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Foley, van Dam, Feiner, Hughes,\n%    Computer Graphics, Principles and Practice,\n%    Addison Wesley, Second Edition, 1990.\n%\n%  Parameters:\n%\n%    Input, real A(4,4), the geometric transformation matrix.\n%\n%    Input, integer N, the number of points to be multiplied.\n%\n%    Input, real X(3,N), the points to be multiplied.\n%\n%    Output, real Y(3,N), the transformed points.  Each product is\n%    accumulated in a temporary vector, and then assigned to the\n%    result.  Therefore, it is legal for X and Y to share memory.\n%\n  for k = 1 : n\n    y(1:3,k) = a(1:3,4) + a(1:3,1:3) * x(1:3,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/geometry/tmat_mxp2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.5977035849529478}}
{"text": "function [model, B, elapse] = LSH_learn(A, maxbits)\n%   This is a function of LSH (Locality Sensitive Hashing) learning.\n%\n%\tUsage:\n%\t[model, B,elapse] = LSH_learn(A, maxbits)\n%\n%\t      A: Rows of vectors of data points. Each row is sample point\n%   maxbits: Code length\n%\n%     model: Used for encoding a test sample point.\n%\t      B: The binary code of the input data A. Each row is sample point\n%    elapse: The coding time (training time).\n%\n%\n%\n%   Reference:\n%\n%   Moses S. Charikar: Similarity estimation techniques from rounding\n%   algorithms. Proceedings of the thiry-fourth annual ACM symposium on\n%   Theory of computing, 2002.  \n%\n%\n%   version 2.0 --Nov/2016 \n%   version 1.0 --Jan/2010 \n%\n%   Written by  Yue Lin (linyue29@gmail.com)\n%               Deng Cai (dengcai AT gmail DOT com) \n%                                             \n\ntmp_T = tic;\n\n[~,Nfeatures] = size(A);\nk = maxbits;\n\nU = normrnd(0, 1, Nfeatures, k);\nZ = A * U;\n\nB = (Z > 0);\nmodel.U = U;\n\nelapse = toc(tmp_T);\nend\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/ANNS/Hashing/Unsupervised/LSH_learn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5976948474882556}}
{"text": "%% Misorientation Distribution Function\n% Explains how to compute and analyze misorientation distribution\n% functions. \n%\n%% TODO\n% Please help to redo the section\n%\n%% \n% When speaking about the misorientation distribution function (MDF) one\n% has to differentiate to cases\n%\n% # the boundary (correlated) misorientation distribution function\n% # the uncorelated misorientation distribution function\n%\n% While the first one considers only misorientations at grain boundaries\n% the second one considers misorietation between arbitrary crystal\n% orientations. To illustrate the difference lets consider the following\n% EBSD data set\n\n% Lets import some EBSD data and reconstruct the grains.\n\nmtexdata forsterite\ngrains = calcGrains(ebsd)\n\n\n%% The boundary misorientation distribution function\n%\n% In order to compute the boundary misorientation distribution function for\n% the phase transition from Forsterite to Enstatite we first extract the\n% misorientations along all Forsterite to Enstatite boundary segements\n\nmori_boundary = grains.boundary('Fo','En').misorientation\n\n%%\n% and second compute the corresponding density function using the command\n% <orientation.calcDensity.html calcDensity>\n\nmdf_boundary = calcDensity(mori_boundary,'halfwidth',5*degree)\n\n%%\n\nadf_boundary = mdf_boundary.calcAxisDistribution\n\nplot(adf_boundary)\n\n%%\n\n\n\n\n\n%%\n% The misorientation distribution function can be processed as any other\n% ODF. E.g. we can compute the prefered misorientation via\n\n[v,mori] = max(mdf_boundary)\n\n\n%%\n% or plot the pole figure corresponding to the crystal axis (1,0,0)\n\nplotPDF(mdf_boundary,Miller(1,0,0,ebsd('Fo').CS))\n\n\n\n\n\n%% The uncorrelated misorientation distribution function\n% \n% Alternatively the uncorrelated misorientation distribution function can be\n% computed by providing the option *uncorrelated*\n\nmori = calcMisorientation(ebsd('En'),ebsd('Fo'))\nmdf_uncor = calcDensity(mori)\n\n%%\n% Obviously it is different from the boundary misorientation distribution\n% function.\n\nplotPDF(mdf_uncor,Miller(1,0,0,ebsd('Fo').CS))\n\n%% Computing the uncorrelated misorientation function from two ODFs\n%\n% Let given two odfs\n\nodf_fo = calcDensity(ebsd('fo').orientations,'halfwidth',10*degree)\nodf_en = calcDensity(ebsd('en').orientations,'halfwidth',10*degree)\n\n%%\n% Then the uncorrelated misorientation function between these two ODFs can\n% be computed by\n\nmdf = calcMDF(odf_en,odf_fo)\n\n%%\n% This misorientation distribution function should be similar to the\n% uncorrelated misorientation function computed directly from the ebsd data\n\nplotPDF(mdf,Miller(1,0,0,ebsd('Fo').CS))\n\n%% Analyzing misorientation functions\n%\n% \n\n%% SUB: Angle distribution\n%\n% Let us first compare the actual angle distribution of the boundary\n% misorientations with the theoretical angle distribution of the\n% uncorrelated MDF.\n\nclose all\nplotAngleDistribution(grains.boundary('fo','en').misorientation)\n\nhold on\n\nplotAngleDistribution(mdf)\n\nhold off\n\n%%\n% For computing the exact values see the commands\n% <SO3Fun.calcAngleDistribution.html calcAngleDistribution(mdf)> and\n% <orientation.calcAngleDistribution.html calcAngleDistribution(ori)>.\n \n%% SUB: Axis distribution\n%\n% The same we can do with the axis distribution. First the actual angle distribution of the boundary\n% misorientations\n\nplotAxisDistribution(grains.boundary('fo','en').misorientation,'smooth')\n\n%%\n% Now the theoretical axis distribution of the\n% uncorrelated MDF.\n\nplotAxisDistribution(mdf)\n\n%%\n% For computing the exact values see the commands\n% <SO3Fun.calcAxisDistribution.html calcAxisDistribution(mdf)> and\n% <orientation.calcAxisDistribution.html calcAxisDistribution(grains)>.\n\naD = calcDensity(axis(grains.boundary('fo','en').misorientation))", "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/Misorientations/MDFAnalysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5976948296997245}}
{"text": "function h = complex(f, g)\n%COMPLEX   Construct complex CHEBFUN3 from real and imaginary parts.\n%   H = COMPLEX(F, G) returns the complex CHEBFUN3 F + i G, where F and G \n%   are real valued CHEBFUN3 objects with the same domain.\n%\n% See also CHEBFUN3/IMAG, CHEBFUN3/CONJ, CHEBFUN3/ABS and CHEBFUN3/REAL.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( ~isreal(f) || ~isreal(g) )\n    error('CHEBFUN:CHEBFUN3:complex:notReal1', ...\n        'Inputs must be real.');\nend\nh = f + 1i*g;\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/complex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5976948214923351}}
{"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 [value] = BinarySABR_3(f, k, t, a, b, r, n)\n% the value of a digital option within a SABR model\n    epsilon = 1e-004;\n    kp = k + epsilon;\n    km = k - epsilon;\n    sigmap = svol_2(a,b,r,n,f,kp,t);\n    sigmam = svol_2(a,b,r,n,f,km,t);\n    d1p = 1./(sigmap .* sqrt(t)).*(log(f./kp)+0.5*sigmap.^2*t);\n    d2p = 1./(sigmap .* sqrt(t)).*(log(f./kp)-0.5*sigmap.^2*t);\n    d1m = 1./(sigmam .* sqrt(t)).*(log(f./km)+0.5*sigmam.^2*t);\n    d2m = 1./(sigmam .* sqrt(t)).*(log(f./km)-0.5*sigmam.^2*t);\n    pp = f * normcdf(d1p) - kp .* normcdf(d2p);\n    pm = f * normcdf(d1m) - km.* normcdf(d2m);\n    value = (pm-pp) / (2*epsilon);\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/38322-the-sabr-model-densities-and-mc/Densities_Prices_MC/BinarySABR_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5976526349898673}}
{"text": "function  peri = perimeter(grains,varargin)\n% calculates the perimeter of a grain with or without inclusions\n%\n% Syntax\n%\n%   grains.perimeter\n%   perimter(grains)\n%   perimter(grains,'withInclusions')\n%\n% Input\n%  grains - @grain2d\n%\n% Output\n%  peri - perimeter (in measurement units)\n%\n% See also\n% grain2d/equivalentPerimeter\n\n\nif check_option(varargin,'withInclusion')\n  \n  bnd = grains.boundary;\n  grainId = bnd.grainId;\n  segLength = bnd.segLength;\n\n  isGrain1 = grainId(:,1)>0;\n  isGrain2 = grainId(:,2)>0;\n  peri = accumarray(grainId(isGrain1,1),segLength(isGrain1),[max(grainId(:)),1]) ...\n    + accumarray(grainId(isGrain2,2),segLength(isGrain2),[max(grainId(:)),1]);\n\n  peri = peri(grains.id);\n\nelse\n  \n  poly = grains.poly;\n\n  % remove inclusions\n  incl = grains.inclusionId;\n  for i = find(incl>0).'\n    poly{i} = poly{i}(1:end-incl(i));\n  end\n\n  V = grains.V;\n\n  peri =  cellfun(@(ind) sum(sqrt(sum(diff(V(ind,:)).^2,2))),poly);\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/EBSDAnalysis/@grain2d/perimeter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5976526294559543}}
{"text": "% Reeds Shepp path planner sample code\n%\n% based on python code from Python Robotics by Atsushi Sakai(@Atsushi_twi)\n%\n% Peter 3/18\n%\n% Finds the shortest path between 2 configurations:\n% - robot can move forward or backward\n% - the robot turns at zero or maximum curvature\n% - there are discontinuities in velocity and steering commands (cusps)\n% to see what it does run\n%\n% >> ReedsShepp.test\n%\n% References::\n% - Reeds, J. A.; Shepp, L. A.\n%   Optimal paths for a car that goes both forwards and backwards.\n%   Pacific J. Math. 145 (1990), no. 2, 367--393.\n%   https://projecteuclid.org/euclid.pjm/1102645450\n\n% each path is described by a 3-letter word.\n% the algorithm finds a bunch of possible paths, then chooses the shortest\n% one.  Each word is represented by a structure with fields:\n% - word      a 3-letter sequence drawn from the letters LRLS\n% - L         total path length\n% - lengths   a 3-vector of lengths, signed to indicate the direction of\n%             curvature\n% - traj      a cell array of 3xN matrices giving the path for each segment\n% - dir       the direction of travel: +1 or -1\n%\n% TODO: display all the solutions in one figure, as subplots\n\nclassdef ReedsShepp < handle\n    properties\n        best  % the best path\n        words\n        maxc\n    end\n    \n    methods\n        function obj = ReedsShepp(q0, qf, maxcurv, dl)\n            \n            obj.maxc = maxcurv;\n            \n            % return the word describing the shortest path\n            obj.words = generate_path(q0, qf, maxcurv);\n            \n            if isempty(obj.words)\n                error('no path');\n            end\n            \n            % find shortest path\n            [~,k] = min( [obj.words.L] );\n            \n            obj.best = obj.words(k);\n            \n            % add the trajectory\n            obj.best = generate_trajectories(obj.best, maxcurv, dl, q0);\n        end\n        \n        function p = path(obj)\n            p = [obj.best.traj{:}]';\n        end\n        \n        function show(obj)\n            for w=obj.words\n                fprintf('%s (%g): [%g %g %g]\\n', w.word, w.L, w.lengths);\n            end\n        end\n        \n        function plot(obj, varargin)\n            \n            opt.circles = [];\n            opt.join = [];\n            \n            opt = tb_optparse(opt, varargin);\n            \n            if ~ishold\n                clf\n            end\n            hold on\n            word = obj.best;\n            \n            for i=1:3\n                \n                if word.dir(i) > 0\n                    color = 'b';\n                else\n                    color = 'r';\n                end\n                if i == 1\n                    x = word.traj{i}(1,:);\n                    y = word.traj{i}(2,:);\n                else\n                    % ensure we join up the lines in the plot\n                    x = [x(end) word.traj{i}(1,:)];\n                    y = [y(end) word.traj{i}(2,:)];\n                end\n                \n                if ~isempty(opt.join) && i<3\n                    plot(x(end), y(end), opt.join{:});\n                end\n                if ~isempty(opt.circles)\n                    T = SE2(word.traj{i}(:,1));\n                    R = 1/obj.maxc;\n                    c = T*[0; word.dir(i)*R];\n                    \n                    plot_circle(c, R, opt.circles)\n                    plot_point(c, 'k+')\n                end\n                \n                plot(x, y, color, 'LineWidth', 2);\n            end\n            grid on; xlabel('X'); ylabel('Y')\n            hold off\n            axis equal\n            title('Reeds-Shepp path');\n        end\n        \n        function s = char(obj)\n            s = '';\n            s = strvcat(s, sprintf('Reeds-Shepp path:  %s, length %f', obj.best.word, obj.best.L));\n            s = strvcat(s, sprintf(' segment lengths:  %f %f %f', obj.best.lengths));\n        end\n        \n        function display(obj)\n            disp( char(obj) );\n        end\n    end\n    \n    methods(Static)\n        function test()\n            maxcurv = 1;\n            dl = 0.05;\n            q0 = [0 0 pi/4]'; qf = [0 0 pi]';\n            p = ReedsShepp(q0, qf, maxcurv, dl)\n            \n            p.plot('circles', 'k--', 'join', {'Marker', 'o', 'MarkerFaceColor', 'k'});\n        end\n    end\nend % class ReedsShepp\n\nfunction out = generate_trajectories(word, maxc, d, q0)\n    \n    % initialize the configuration\n    p0 = q0;\n    \n    % output struct is same as input struct, but we will add:\n    %  - a cell array of trajectories\n    %  - a vector of directions -1 or +1\n    out = word;\n    \n    for i=1:3\n        m = word.word(i);\n        l = word.lengths(i);\n        \n        x = [0:d:abs(l) abs(l)];\n        \n        p = pathseg(x, sign(l), m, maxc, p0);\n        \n        % add new fields to the struct\n        \n        if i == 1\n            out.traj{i} = p;\n        else\n            % for subsequent segments skip the first point, same as last\n            % point of previous segment\n            out.traj{i} = p(:,2:end);\n        end\n        out.dir(i) = sign(l);\n        \n        % initial state for next segment is last state of this segment\n        p0 = p(:,end);\n    end\nend\n\nfunction q = pathseg(l, dir, m, maxc, p0)\n    q0 = p0(:);\n    switch m\n        case 'S'\n            f = @(t,q) dir*[cos(q(3)), sin(q(3)), 0]';\n        case {'L', 'R'}\n            f = @(t,q) dir*[cos(q(3)), sin(q(3)), dir*maxc]';\n    end\n    [t,q] = ode45(f, l, q0);\n    q = q';  % points are column vectors\nend\n\n\nfunction words = generate_path(q0, q1, maxc)\n    % return a list of all possible words\n    q0 = q0(:); q1 = q1(:);\n    dq = q1 - q0;\n    dth = dq(3);\n    \n    xy = rot2(q0(3))' * dq(1:2) * maxc;\n    x = xy(1); y = xy(2);\n    \n    words = [];\n    words = SCS(x, y, dth, words);\n    words = CSC(x, y, dth, words);\n    words = CCC(x, y, dth, words);\n    \n    % account for non-unit curvature\n    for i=1:numel(words)\n        words(i).lengths = words(i).lengths / maxc;\n        words(i).L = words(i).L / maxc;\n    end\n    \nend\n\n%%\nfunction owords = SCS(x, y, phi, words)\n    \n    words = SLS([ x  y  phi], 1, 'SLS', words);\n    words = SLS([ x -y -phi], 1, 'SRS', words);\n    \n    owords = words;\nend\n\nfunction owords = CCC(x, y, phi, words)\n    \n    words = LRL([ x  y  phi],  1, 'LRL', words);\n    words = LRL([-x  y -phi], -1, 'LRL', words);\n    words = LRL([ x -y -phi],  1, 'RLR', words);\n    words = LRL([-x -y  phi], -1, 'RLR', words);\n    \n    % backwards\n    xb = x * cos(phi) + y * sin(phi);\n    yb = x * sin(phi) - y * cos(phi);\n    \n    flip = [0 1 0; 1 0 0; 0 0 1];  % flip u and v\n    \n    words = LRL([ xb  yb  phi],  flip, 'LRL', words);\n    words = LRL([-xb  yb -phi], -flip, 'LRL', words);\n    words = LRL([ xb -yb -phi],  flip, 'RLR', words);\n    words = LRL([-xb -yb  phi], -flip, 'RLR', words);\n    \n    owords = words;\nend\n\nfunction owords = CSC(x, y, phi, words)\n    \n    words = LSL([ x  y  phi],  1, 'LSL', words);\n    words = LSL([-x  y -phi], -1, 'LSL', words);\n    words = LSL([ x -y -phi],  1, 'RSR', words);\n    words = LSL([-x -y  phi], -1, 'RSR', words);\n    words = LSR([ x  y  phi],  1, 'LSR', words);\n    words = LSR([-x  y -phi], -1, 'LSR', words);\n    words = LSR([ x -y -phi],  1, 'RSL', words);\n    words = LSR([-x -y  phi], -1, 'RSL', words);\n    \n    owords = words;\nend\n\n% requires LSL, LSR, SLS, LRL\n\n%%\n\n\nfunction owords = SLS(q, sign, word, words)\n    x = q(1); y = q(2); phi = mod(q(3), 2*pi);\n    \n    if y > 0.0 && phi > 0.0 && phi < pi * 0.99\n        xd = - y / tan(phi) + x;\n        t = xd - tan(phi / 2.0);\n        u = phi;\n        v = norm( [(x - xd) y]) - tan(phi / 2.0);\n        owords = addpath(words, sign*[t, u, v], word);\n    elseif y < 0.0 && phi > 0.0 && phi < pi * 0.99\n        xd = - y / tan(phi) + x;\n        t = xd - tan(phi / 2.0);\n        u = phi;\n        v = -norm([(x - xd) y]) - tan(phi / 2.0);\n        owords = addpath(words, sign*[t, u, v], word);\n    else\n        owords = words;\n    end\nend\n\nfunction owords = LSL(q, sign, word, words)\n    x = q(1); y = q(2); phi = mod(q(3), 2*pi);\n    \n    [t,u] = cart2pol(x - sin(phi), y - 1.0 + cos(phi));\n    if t >= 0.0\n        v = angdiff(phi - t);\n        if v >= 0.0\n            owords = addpath(words, sign*[t, u, v], word);\n            return\n        end\n    end\n    \n    owords = words;\nend\n\nfunction owords = LRL(q, sign, word, words)\n    x = q(1); y = q(2); phi = mod(q(3), 2*pi);\n    \n    [t1,u1] = cart2pol(x - sin(phi), y - 1.0 + cos(phi));\n    \n    if u1 <= 4.0\n        u = -2.0 * asin(0.25 * u1);\n        t = angdiff(t1 + 0.5 * u + pi);\n        v = angdiff(phi - t + u);\n        \n        if t >= 0.0 && u <= 0.0\n            owords = addpath(words, [t, u, v]*sign, word);\n            return\n        end\n    end\n    \n    owords = words;\nend\n\nfunction owords = LSR(q, sign, word, words)\n    x = q(1); y = q(2); phi = mod(q(3), 2*pi);\n    \n    [t1,u1] = cart2pol(x + sin(phi), y - 1.0 - cos(phi));\n    u1 = u1^2;\n    if u1 >= 4.0\n        u = sqrt(u1 - 4.0);\n        theta = atan2(2.0, u);\n        t = angdiff(t1 + theta);\n        v = angdiff(t - phi);\n        \n        if t >= 0.0 && v >= 0.0\n            owords = addpath(words, sign*[t, u, v], word);\n            return\n        end\n    end\n    \n    owords = words;\nend\n\n\n%%\nfunction owords = addpath(words, lengths, ctypes)\n    \n    % create a struct to represent this segment\n    word.word = ctypes;\n    word.lengths = lengths;\n    \n    % check same path exist\n    for p = words\n        if strcmp(p.word, word.word)\n            if sum(p.lengths) - sum(word.lengths) <= 0.01\n                owords = words;\n                return %not insert path\n            end\n        end\n    end\n    \n    word.L = sum(abs(lengths));\n    \n    % long enough to add?\n    if word.L >= 0.01\n        owords = [words word];\n    end\nend\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/ReedsShepp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5976526239220412}}
{"text": "% DEMCMU35GPLVMVARGPLVMSIMPLE Run variational GPLVM with dynamics on a single\n% sequence of the CMU35 data.\n\n% VARGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\n% Define constants\nexperimentNo = 1000;\nlatentDim = 9; % this is Q, the number of latent dimensions\nindPoints = 100; % number of inducing points\n% dynamicKern = {'matern32', 'bias', 'white'};\ndynamicKern = {'rbf', 'bias', 'white'}; % kernel k_t for the GP for x(t)\ninitX ='ppca'; % initialize latent space with ppca\n\n% load data\ndataSetName = 'cmu35gplvm';\n[Ytmp, lbls, Y, lblstest] = lvmLoadData(dataSetName);\n\n% Set training and test sets\nindicesTraining = [1:40 61:size(Y,1)];\nindicesTest = setdiff(1:size(Y,1),indicesTraining);\nYtr = Y(indicesTraining,:);\nYtest = Y(indicesTest,:);\n\n% Corresponding timestamps (artificial and equally spaced for this demo)\nt = linspace(0, 2*pi, size(Y, 1)+1)';\nt = t(1:end-1, 1);\ntimeStampsTraining = t(indicesTraining);\ntimeStampsTest = t(indicesTest);\n\nY = Ytr; clear('Ytr','Ytmp');\n\n\n% Set up model\noptions = vargplvmOptions('dtcvar');\noptions.kern = {'rbfard2', 'bias', 'white'}; % Kernel k_x for the GP for f(x)\noptions.numActive = indPoints;\noptions.optimiser = 'scg';\n\nd = size(Y, 2);\nfprintf(1,'# Creating the model...\\n');\nmodel = vargplvmCreate(latentDim, d, Y, options);\nmodel = vargplvmParamInit(model, model.m, model.X);\nmodel.beta=1/(0.01*var(model.m(:)));\nmodel.vardist.covars = 0.5*ones(size(model.vardist.covars)) + 0.001*randn(size(model.vardist.covars));\n\n%-------- Add dynamics to the model -----\noptionsDyn.type = 'vargpTime';\noptionsDyn.t=timeStampsTraining;\noptionsDyn.inverseWidth=30;\noptionsDyn.initX = initX;\n\n% Dynamic kernel:\nkern = kernCreate(t, dynamicKern);\n% The following is related to the expected number of\n% zero-crossings.(larger inv.width numerator, rougher func)\nif ~strcmp(kern.comp{1}.type,'ou')\n    kern.comp{1}.inverseWidth = optionsDyn.inverseWidth./(((max(t)-min(t))).^2);\n    kern.comp{1}.variance = 1;\nend\noptionsDyn.kern = kern;\n\n% Fill in with default values whatever is not already set\noptionsDyn = vargplvmOptionsDyn(optionsDyn);\nmodel = vargplvmAddDynamics(model, 'vargpTime', optionsDyn, optionsDyn.t, 0, 0,optionsDyn.seq);\n\nfprintf(1,'# Further calibration of the initial parameters...\\n');\nmodel = vargplvmInitDynamics(model,optionsDyn);\nmodel.vardist.parallel=1;\n% do not learn beta for few iterations for intitilization\nmodel.learnBeta = 0;\ndisplay = 1;\nfprintf(1,'# Intitiliazing the model (fixed beta) %d iterations...\\n',100);\nmodel = vargplvmOptimise(model, display, 100);\ndisp('# Saving model after optimising beta...')\nmodelWriteResult(model, dataSetName, experimentNo);\n\n% Optimise the model.\nmodel.learnBeta = 1;\niters = 1000; % Default: 1000\nfprintf(1,'# Optimising the model for %d iterations...\\n',iters);\nmodel = vargplvmOptimise(model, display, iters);\n% Save the results.\nfprintf(1,'# Saving model after doing %d iterations\\n',iters)\nmodelWriteResult(model, dataSetName, experimentNo);\n\n% See the final lengthscales (see how some dimensions are switched-off).\n bar(model.kern.comp{1}.inputScales)\n\n%% ----------------- PREDICTIONS -----------------------------\nfprintf('# Only times prediction...\\n');\n% Prediction using the only information in the test time points\n[Testmeans2 Testcovars2] = vargplvmPredictPoint(model.dynamics, timeStampsTest);\nVarmu2 = vargplvmPosteriorMeanVar(model, Testmeans2, Testcovars2);\n\nerrorPredictions = mean(abs(Varmu2(:) - Ytest(:)));\nfprintf(1,'# Predictions Error:%d\\n', errorPredictions);\n\n\nplot(Varmu2(1,:),'r'),hold on, plot(Ytest(1,:),'g')\n\nskel = acclaimReadSkel('35.asf');\n[tmpchan, skel] = acclaimLoadChannels('35_01.amc', skel);\nchannels{1} = demCmu35VargplvmLoadChannels(Ytest,skel);\nchannels{2} = demCmu35VargplvmLoadChannels(Varmu2,skel);\nskelPlayData2(skel, channels,1/15,{'Ytest','Varmu2'});\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/demos/demCmuVargplvmSimple.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5976526239220411}}
{"text": "function Xform = inplane2VolXform(rot,trans,scaleFac)\n%\n% Xform = inplane2VolXform(rot,trans,scaleFac)\n%\n% Returns 4x4 homogeneous tranform that tranforms from inplane to\n% volume.\n%\n% djh/gmb, '97\n%\n% Modification:\n% - Flip first 2 rows and cols so that it deals with\n% (y,x,z) coords instead of (x,y,z).  DJH, 7/98.\n\nA=diag(scaleFac(2,:))*rot*diag(1./scaleFac(1,:));\nb = (scaleFac(2,:).*trans)';\n\nXform = zeros(4,4);\nXform(1:3,1:3)=A;\nXform(1:3,4)=b;\nXform(4,4)=1;\n\nXform([1 2],:) = Xform([2 1],:);\nXform(:,[1 2]) = Xform(:,[2 1]);\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/File/inplane2VolXform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5976526191854732}}
{"text": "%| denoise_threshold_test.m\n%| Test denoising based on l_1 type penalty, cf thresholding\n%| min_x 1/2 |y - x|^2 + \\beta pot(x)\n%|\n%| Copyright 2005-4-22, Jeff Fessler, University of Michigan\n\nyi = linspace(-10,10,101)';\nmask = true(size(yi));\nA = Gdiag(ones(size(mask))); % identity \"matrix\"\n\nif 1\n\tf.l2b_q = 1;\n%\tf.l2b_n = 5;\n\tf.l2b_n = 1;\n\tf.cut = 5; % cutoff point\n%\tf.delta = 0.2;\n\tf.delta = f.cut / (1 + 2^f.l2b_n); % for broken parabola\n\tf.tik = (1 + 2^f.l2b_n) * f.delta;\n\tf.niter = 40;\n%\tf.type = 'cauchy';\n\tf.type = 'broken';\n\n\tRq = Reg1(mask, 'type_denom', 'matlab', ...\n\t\t'offsets', 0, ... % trick for identity\n\t\t'beta', 2^f.l2b_q);\n%\t\t'pot_arg', {'quad'}, 'beta', 2^f.l2b_q);\n\n\txq = pwls_sps_os(0*yi(:), yi(:), [], A, Rq, ...\n\t\t\t2, [-inf inf], [], [], 1);\nend\n\nif 1\n\tRc = Reg1(mask, 'type_denom', 'matlab', ...\n\t\t'offsets', 0, ... % trick for identity\n\t\t'pot_arg', {f.type, f.delta}, 'beta', 2^f.l2b_n);\n\n\txc = pwls_sps_os(0*yi(:), yi(:), [], A, Rc, ...\n\t\tf.niter, [-inf inf], [], [], 1);\n\n\tRh = Reg1(mask, 'type_denom', 'matlab', ...\n\t\t'offsets', 0, ... % trick for identity\n\t\t'pot_arg', {'hyper3', f.delta}, 'beta', 2^f.l2b_n);\n\n\txh = pwls_sps_os(yi(:), yi(:), [], A, Rh, ...\n\t\tf.niter, [-inf inf], [], [], 1);\nend\n\nif im\n\tclf, plot(yi, yi, ':', ...\n\t\tyi, xh(:,end), '-', ...\n\t\tyi, xc(:,end), '-.', ...\n\t\tyi, xq(:,end), '--')\n%\taxis equal\n\taxis square\n\ttik = [min(yi), -f.tik 0 f.tik max(yi)];\n%%%%%%%%\txtick(tik), ytick(tik)\n\tgrid\n\tir_legend({'I', 'hyper', f.type, 'quad'})\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/denoise_threshold_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5976526152462496}}
{"text": "function [p] = integrateSubIntervals(x, cdf)\n\n[xLB, xUB] = subIntervals(x);\n\ncdfUB = cdf(xUB);\ncdfLB = cdf(xLB);\n\np = (cdfUB - cdfLB) ./ (xUB - xLB);\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/26478-fully-flexible-extreme-views/FullyFlexibleExtremeViews/integrateSubIntervals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5976279456225205}}
{"text": "function indx = r8row_sort_heap_index_a ( m, n, a )\n\n%*****************************************************************************80\n%\n%% R8ROW_SORT_HEAP_INDEX_A does an indexed heap ascending sort of an R8ROW.\n%\n%  Discussion:\n%\n%    An R8ROW is an M by N array of R8's, regarded as an array of M rows,\n%    each of length N.\n%\n%    The sorting is not actually carried out.  Rather an index array is\n%    created which defines the sorting.  This array may be used to sort\n%    or index the array, or to sort or index related arrays keyed on the\n%    original array.\n%\n%    A(I1,*) < A(I1,*) if the first nonzero entry of A(I1,*)-A(I2,*)\n%    is negative.\n%\n%    Once the index array is computed, the sorting can be carried out\n%    \"implicitly:\n%\n%      A(INDX(1:M),1:N) is sorted.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 May 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer M, the number of rows in each column of A.\n%\n%    Input, integer N, the number of columns in A.\n%\n%    Input, real A(M,N), the array.\n%\n%    Output, integer INDX(M), the sort index.  The I-th element of the sorted \n%    array is row INDX(I).\n%\n  indx(1:m) = 1 : m;\n\n  if ( m <= 1 )\n    return\n  end\n\n  l = floor ( m / 2 ) + 1;\n  ir = m;\n\n  while ( 1 )\n\n    if ( 1 < l )\n\n      l = l - 1;\n      indxt = indx(l);\n      row(1:n) = a(indxt,1:n);\n\n    else\n\n      indxt = indx(ir);\n      row(1:n) = a(indxt,1:n);\n      indx(ir) = indx(1);\n      ir = ir - 1;\n\n      if ( ir == 1 )\n        indx(1) = indxt;\n        break\n      end\n\n    end\n\n    i = l;\n    j = l + l;\n\n    while ( j <= ir )\n\n      if ( j < ir )\n\n        if ( r8row_compare ( m, n, a, indx(j), indx(j+1) ) < 0 )\n          j = j + 1;\n        end\n\n      end\n\n      if ( r8vec_compare ( n, row, a(indx(j),1:n) ) < 0 )\n        indx(i) = indx(j);\n        i = j;\n        j = j + j;\n      else\n        j = ir + 1;\n      end\n\n    end\n\n    indx(i) = indxt;\n\n  end\n\n  return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8row_sort_heap_index_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.5976279360325834}}
{"text": "function [ fm ] = gsp_modulate( G,f,k )\n%GSP_MODULATE Generalized modulation of the signal f to the frequency k\n%   Usage: fm = gsp_modulate( G,f,k );\n%\n%   Input parameters\n%       G   : Graph\n%       f   : Signal (column)\n%       k   : Indices of frequencies (int)\n%   Output parameters\n%       fm  : Modulated signal\n%\n%   This function modulate the column vector *f* onto the node i. If f is a\n%   matrix, the modulation will be applicated to each column.\n%\n\n% Author: Nathanael Perraudin\n% Date  : 09.12.2013\n\nnt = size(f,2);\n\nfm = sqrt(G.N)*repmat(f,1,nt).*repmat(G.U(:,k+1),1,nt);\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/operators/gsp_modulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5976279268637839}}
{"text": "function determ = smoke_determinant ( n )\n\n%*****************************************************************************80\n%\n%% SMOKE_DETERMINANT returns the determinant of the SMOKE 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 A.\n%\n%    Output, real DETERM, the determinant.\n%\n  if ( mod ( n, 2 ) == 0 )\n    determ =   2.0;\n  else\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/smoke_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.5975501034476631}}
{"text": "function yp = p25_fun ( neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P25_FUN evaluates the function for problem P25.\n%\n%  Discussion:\n%\n%    2 equations\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  yp(1) = y(2);\n  yp(2) = sqrt ( 1.0 + y(2).^2 ) / ( 25.0 - 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/test_ode/p25_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.5975501027645794}}
{"text": "function order = order_table ( rule )\n\n%*****************************************************************************80\n%\n%% ORDER_TABLE returns the order of a Lebedev rule.\n%\n%  Modified:\n%\n%    13 September 2010\n%\n%  Author:\n%\n%    John Burkardt\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%    Input, integer RULE, the index of the rule, between 1 and 65.\n%\n%    Output, integer ORDER, the order of the rule.\n%\n  rule_max = 65;\n\n  table = [ ...\n       6,   14,   26,   38,   50,   74,   86,  110,  146,  170, ...\n     194,  230,  266,  302,  350,  386,  434,  482,  530,  590, ...\n     650,  698,  770,  830,  890,  974, 1046, 1118, 1202, 1274, ...\n    1358, 1454, 1538, 1622, 1730, 1814, 1910, 2030, 2126, 2222, ...\n    2354, 2450, 2558, 2702, 2810, 2930, 3074, 3182, 3314, 3470, ...\n    3590, 3722, 3890, 4010, 4154, 4334, 4466, 4610, 4802, 4934, ...\n    5090, 5294, 5438, 5606, 5810 ]';\n\n  if ( rule < 1 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'ORDER_TABLE - Fatal error!\\n' );\n    fprintf ( 1, '  RULE < 1.\\n' );\n    error ( 'ORDER_TABLE - Fatal error!' );\n  elseif ( rule_max < rule )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'ORDER_TABLE - Fatal error!\\n' );\n    fprintf ( 1, '  RULE_MAX < RULE.\\n' );\n    error ( 'ORDER_TABLE - Fatal error!' );\n  end\n\n  order = table(rule);\n\n  return\nend\n", "meta": {"author": "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/order_table.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.5975500957068043}}
{"text": "function test_nearest\n\n% MEM 3gb\n% WALLTIME 00:10:00\n% DEPENDENCY nearest\n\n% Use as\n%   [indx] = nearest(array, val, insideflag, toleranceflag)\n\n% these are some normal cases\nassert(nearest([1 2 3], 1)==1)\nassert(nearest([1 2 3], 2)==2)\nassert(nearest([1 2 3], 3)==3)\nassert(nearest([1 2 3], -inf)==1)\nassert(nearest([1 2 3],  inf)==3)\n\n% unsorted arrays should be supported\nassert(nearest([1 3 2], -inf)==1)\nassert(nearest([3 1 2], -inf)==2)\nassert(nearest([3 1 2], 1)==2)\n\n% outside the range\ntry\n  nearest([1 2 3], 0, true);\n  error('this should have returned an error');\nend\ntry\n  nearest([1 2 3], 4, true);\n  error('this should have returned an error');\nend\n\n% just inside the tolerance range\nassert(nearest([1 2 3], 0.5, true, true)==1);\nassert(nearest([1 2 3], 3.5, true, true)==3);\n\n% just outside the tolerance range\ntry\n  nearest([1 2 3], 0.499, true, true);\n  error('this should have returned an error');\nend\ntry\n  nearest([1 2 3], 3.501, true, true);\n  error('this should have returned an error');\nend\n\n% new functionality of 'val' being a [minval maxval] input pair\n\nassert(all(nearest(.1:.1:1.0,[.1 .3])==[1 3]))\nassert(all(nearest(.1:.1:1.0,[.11 .3])==[2 3]))\nassert(all(nearest(.1:.1:1.0,[.1 .29])==[1 2]))\nassert(all(nearest(.1:.1:1.0,[0 .3])==[1 3]))\nassert(all(nearest(.1:.1:1.0,[.11 .29])==[2 2]))\nassert(all(nearest(.1:.1:1.0,[-inf 1])==[1 10]))\nassert(all(nearest(.1:.1:1.0,[.79 inf])==[8 10]))\nassert(all(nearest(.1:.1:1.0,[.8 10])==[8 10]))\nassert(all(nearest(.1:.1:1.0,[-2 8])==[1 10]))\nassert(all(nearest(.1:.1:1.0,[.79 .99])==[8 9]))\nassert(all(nearest(.001:.001:.01,[.002 .003])==[2 3]))\nassert(all(nearest(.001:.001:.1,[0 1])==[1 100]))\n\ntry\n  nearest(.1:.1:1.0,[3 8]);\ncatch me\n  if ~strcmp(me.message,'The limits you selected are outside the range available in the data')\n    error('wrong error message in nearest')\n  end\nend\n\n% create a large array and test\n\nx = 0:492:(492*(25*10^7));\ny = 8424306*492;\nindx = nearest(x,y);\nindx2 = find(x<=y, 1, 'last');\n\n% temporal comparison\n\ntic\nfor i=1:10\n  indx = nearest(x,y);\nend\nt1 = toc;\n\ntic\nfor i=1:10\n  x = sort(x);\n  indx2 = find(x<=y, 1, 'last');\n  indx3 = find(x>=y, 1, 'first');\n  if abs(x(indx2)-y) < abs(x(indx3)-y)\n    indx4 = indx2;\n  else\n    indx4 = indx3;\n  end\nend\nt2 = toc;\n\nfprintf('Time needed for nearest function: %.2s per 100 calls\\n', t1/100);\nfprintf('Time needed for find function: %.2s per 100 calls\\n', t2/100);\n\nif indx~=indx2, \n  error('nearest does not output the correct value');\n  fprintf('nearest is off by %d samples', indx2-indx);\nend\n% indx2 = 8424307\n\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/test/test_nearest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.5975500950237209}}
{"text": "function [ a, b ] = p01_ab ( m )\n\n%*****************************************************************************80\n%\n%% P01_AB returns bounds for problem 1.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 February 2012\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, integer M, the spatial dimension.\n%\n%    Output, real A(M,1), B(M,1), lower and upper bounds.\n%\n  a(1:m,1) = 0.0;\n  b(1:m,1) = 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_opt_con/p01_ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.5975500865997785}}
{"text": "function [C, sigma] = dataset3Params(X, y, Xval, yval)\n%DATASET3PARAMS returns your choice of C and sigma for Part 3 of the exercise\n%where you select the optimal (C, sigma) learning parameters to use for SVM\n%with RBF kernel\n%   [C, sigma] = DATASET3PARAMS(X, y, Xval, yval) returns your choice of C and \n%   sigma. You should complete this function to return the optimal C and \n%   sigma based on a cross-validation set.\n%\n\n% You need to return the following variables correctly.\nC = 1;\nsigma = 0.3;\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return the optimal C and sigma\n%               learning parameters found using the cross validation set.\n%               You can use svmPredict to predict the labels on the cross\n%               validation set. For example, \n%                   predictions = svmPredict(model, Xval);\n%               will return the predictions on the cross validation set.\n%\n%  Note: You can compute the prediction error using \n%        mean(double(predictions ~= yval))\n%\n\n% C_vec = [0.01,0.03,0.1,0.3,1,3,10,30];\n% sigma_vec = [0.01,0.03,0.1,0.3,1,3,10,30];\n% error = zeros(8,8);\n% \n% for i=1:8\n%     for j=1:8\n%         model= svmTrain(X, y, C_vec(i), @(x1, x2) gaussianKernel(x1, x2, sigma_vec(j)));\n%         predictions = svmPredict(model, Xval);\n%         error(i,j) = mean(double(predictions ~= yval));\n%     end\n% end\n% \n% temp= min(min(error));\n% \n% [row, colume ] = find(error == temp)\n\nC = 1;\nsigma = 0.1;\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-ex6/ex6/dataset3Params.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.5975500865997784}}
{"text": "function dt = EulerDT2D(Q, gamma)\n\n% function dt = EulerDT2D(Q, gamma)\n% purpose: compute the time step dt for the compressible Euler equations\n\nGlobals2D;\n\nrho = Q(:,:,1); rhou = Q(:,:,2); rhov = Q(:,:,3); Ener = Q(:,:,4);\nrho = rho(vmapM); rhou = rhou(vmapM); rhov = rhov(vmapM); Ener = Ener(vmapM);\n\nu = rhou./rho; v = rhov./rho;\np = (gamma-1.0)*(Ener - rho.*(u.^2+v.^2)/2); c = sqrt(abs(gamma*p./rho));\n\ndt = 1/max( ((N+1)^2)*.5*Fscale(:).*(sqrt ( u(:).^2 + v(:).^2 ) + c(:)));\n\nrhoprange = [min(min(rho)), max(max(rho)), min(min(p)), max(max(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/EulerDT2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5975496352025236}}
{"text": "function im_out = linear_stretch(im_in)\n% The top 0.00001 pixels of the image are clipped to 1, and the\n% image is linearly stretched.\nimg1 = max(im_in, [],3);   % maximum between RGB channels\nimg1 = img1(:);\nimg1 = sort(img1, 'descend');\nidx = round(0.00001*length(img1));\nscale = img1(idx);\nim_out = im_in./scale;\nim_out = min(im_out,1);", "meta": {"author": "danaberman", "repo": "underwater-hl", "sha": "c9c8c69287ce1e7dd1434a01f078809849a23ce2", "save_path": "github-repos/MATLAB/danaberman-underwater-hl", "path": "github-repos/MATLAB/danaberman-underwater-hl/underwater-hl-c9c8c69287ce1e7dd1434a01f078809849a23ce2/utils/linear_stretch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.597540721459616}}
{"text": "function [R,T,Xc,best_solution,opt]=efficient_pnp_gauss(x3d_h,x2d_h,A)\n\n% EFFICIENT_PNP_GAUSS Main Function to solve the PnP problem \n%       as 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%       Note: In this version of the software we perform a final\n%       optimization using Gauss-Newton,which is not described in the\n%       paper.\n%\n%       x3d_h: homogeneous coordinates of the points in world reference\n%       x2d_h: homogeneous position of the points in the image plane\n%       A: intrincic camera parameters\n%       R: Rotation of the camera system wrt world reference\n%       T: Translation of the camera system wrt world reference\n%       Xc: Position of the points in the camera reference\n%       best solution: dimension of the kernel for the best solution\n%                     (before applying Gauss Newton).\n%       opt: some parameters of the optimization process\n%\n% Copyright (C) <2007>  <Francesc Moreno-Noguer, Vincent Lepetit, Pascal Fua>\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 <http://www.gnu.org/licenses/>.\n%\n% Francesc Moreno-Noguer, CVLab-EPFL, October 2007.\n% fmorenoguer@gmail.com, http://cvlab.epfl.ch/~fmoreno/ \n\n\n\nXw=x3d_h(:,1:3);\nU=x2d_h(:,1:2);\n\nTHRESHOLD_REPROJECTION_ERROR=20;%error in degrees of the basis formed by the control points. \n%If we have a larger error, we will compute the solution using a larger\n%number of vectors in the kernel\n\n%define control points in a world coordinate system (centered on the 3d\n%points centroid)\nCw=define_control_points();\n\n%compute alphas (linear combination of the control points to represent the 3d\n%points)\nAlph=compute_alphas(Xw,Cw);\n\n%Compute M\nM=compute_M_ver2(U,Alph,A);\n\n%Compute kernel M\nKm=kernel_noise(M,4); %in matlab we have directly the funcion km=null(M);\n    \n\n\n%1.-Solve assuming dim(ker(M))=1. X=[Km_end];------------------------------\ndim_kerM=1;\nX1=Km(:,end);\n[Cc,Xc,sc]=compute_norm_sign_scaling_factor(X1,Cw,Alph,Xw);\n\n[R,T]=getrotT(Xw,Xc);  %solve exterior orientation\nerr(1)=reprojection_error_usingRT(Xw,U,R,T,A);\n\nsol(1).Xc=Xc;\nsol(1).Cc=Cc;\nsol(1).R=R;\nsol(1).T=T;\nsol(1).error=err(1);\nsol(1).betas=[1];\nsol(1).sc=sc;\nsol(1).Kernel=X1;\n\n\n%2.-Solve assuming dim(ker(M))=2------------------------------------------\nKm1=Km(:,end-1);\nKm2=Km(:,end);\n\n%control points distance constraint\nD=compute_constraint_distance_2param_6eq_3unk(Km1,Km2);\ndsq=define_distances_btw_control_points();\nbetas_=inv(D'*D)*D'*dsq;\nbeta1=sqrt(abs(betas_(1)));\nbeta2=sqrt(abs(betas_(3)))*sign(betas_(2))*sign(betas_(1));\nX2=beta1*Km1+beta2*Km2;\n\n[Cc,Xc,sc]=compute_norm_sign_scaling_factor(X2,Cw,Alph,Xw);\n\n[R,T]=getrotT(Xw,Xc);  %solve exterior orientation\nerr(2)=reprojection_error_usingRT(Xw,U,R,T,A);\n\nsol(2).Xc=Xc;\nsol(2).Cc=Cc;\nsol(2).R=R;\nsol(2).T=T;\nsol(2).error=err(2);\nsol(2).betas=[beta1,beta2];\nsol(2).sc=sc;\nsol(2).Kernel=[Km1,Km2];\n\n\n\n%3.-Solve assuming dim(ker(M))=3------------------------------------------\nif min(err)>THRESHOLD_REPROJECTION_ERROR %just compute if we do not have good solution in the previus cases\n\n    Km1=Km(:,end-2);\n    Km2=Km(:,end-1);\n    Km3=Km(:,end);\n\n    %control points distance constraint\n    D=compute_constraint_distance_3param_6eq_6unk(Km1,Km2,Km3);\n    dsq=define_distances_btw_control_points();\n    betas_=inv(D)*dsq;\n    beta1=sqrt(abs(betas_(1)));\n    beta2=sqrt(abs(betas_(4)))*sign(betas_(2))*sign(betas_(1));\n    beta3=sqrt(abs(betas_(6)))*sign(betas_(3))*sign(betas_(1));\n\n    X3=beta1*Km1+beta2*Km2+beta3*Km3;\n\n    [Cc,Xc,sc]=compute_norm_sign_scaling_factor(X3,Cw,Alph,Xw);\n  \n    [R,T]=getrotT(Xw,Xc);  %solve exterior orientation\n    err(3)=reprojection_error_usingRT(Xw,U,R,T,A);\n\n    sol(3).Xc=Xc;\n    sol(3).Cc=Cc;\n    sol(3).R=R;\n    sol(3).T=T;\n    sol(3).error=err(3);\n    sol(3).betas=[beta1,beta2,beta3];\n    sol(3).sc=sc;\n    sol(3).Kernel=[Km1,Km2,Km3];\n\nend\n\n\n\n%4.-Solve assuming dim(ker(M))=4------------------------------------------\nif min(err)>THRESHOLD_REPROJECTION_ERROR %just compute if we do not have good solution in the previus cases\n    Km1=Km(:,end-3);\n    Km2=Km(:,end-2);\n    Km3=Km(:,end-1);\n    Km4=Km(:,end);\n\n\n    D=compute_constraint_distance_orthog_4param_9eq_10unk(Km1,Km2,Km3,Km4);\n    dsq=define_distances_btw_control_points();\n    lastcolumn=[-dsq',0,0,0]';\n    D_=[D,lastcolumn];\n    Kd=null(D_);\n\n    P=compute_permutation_constraint4(Kd);\n    lambdas_=kernel_noise(P,1);\n    lambda(1)=sqrt(abs(lambdas_(1)));\n    lambda(2)=sqrt(abs(lambdas_(6)))*sign(lambdas_(2))*sign(lambdas_(1));\n    lambda(3)=sqrt(abs(lambdas_(10)))*sign(lambdas_(3))*sign(lambdas_(1));\n    lambda(4)=sqrt(abs(lambdas_(13)))*sign(lambdas_(4))*sign(lambdas_(1));\n    lambda(5)=sqrt(abs(lambdas_(15)))*sign(lambdas_(5))*sign(lambdas_(1));\n\n    betass_=lambda(1)*Kd(:,1)+lambda(2)*Kd(:,2)+lambda(3)*Kd(:,3)+lambda(4)*Kd(:,4)+lambda(5)*Kd(:,5);\n    beta1=sqrt(abs(betass_(1)));\n    beta2=sqrt(abs(betass_(5)))*sign(betass_(2));\n    beta3=sqrt(abs(betass_(8)))*sign(betass_(3));\n    beta4=sqrt(abs(betass_(10)))*sign(betass_(4));\n    X4=beta1*Km1+beta2*Km2+beta3*Km3+beta4*Km4;\n\n    [Cc,Xc,sc]=compute_norm_sign_scaling_factor(X4,Cw,Alph,Xw);\n    \n    [R,T]=getrotT(Xw,Xc);  %solve exterior orientation\n    err(4)=reprojection_error_usingRT(Xw,U,R,T,A);\n\n    sol(4).Xc=Xc;\n    sol(4).Cc=Cc;\n    sol(4).R=R;\n    sol(4).T=T;\n    sol(4).error=err(4);\n    sol(4).betas=[beta1,beta2,beta3,beta4];\n    sol(4).sc=sc;\n    sol(4).Kernel=[Km1,Km2,Km3,Km4];\nend\n\n\n%5.-Gauss Newton Optimization------------------------------------------------------ \n[min_err,best_solution]=min(err);\nXc=sol(best_solution).Xc;\nR=sol(best_solution).R;\nT=sol(best_solution).T;\nBetas=sol(best_solution).betas;\nsc=sol(best_solution).sc;\nKernel=sol(best_solution).Kernel;\n \nif best_solution==1\n    Betas=[0,0,0,Betas];\nelseif best_solution==2\n    Betas=[0,0,Betas];\nelseif best_solution==3\n    Betas=[0,Betas];\nend\n\nKm1=Km(:,end-3);\nKm2=Km(:,end-2);\nKm3=Km(:,end-1);\nKm4=Km(:,end);\nKernel=[Km1,Km2,Km3,Km4];\n\n\n%refine the solution iterating over the betas\nBeta0=Betas/sc;\n[Xc_opt,R_opt,T_opt,err_opt,iter]=optimize_betas_gauss_newton(Kernel,Cw,Beta0,Alph,Xw,U,A);\n\n%Just update R,T,Xc if Gauss Newton improves results (which is almost\n%always)\nif err_opt<min_err    \n    R=R_opt;\n    T=T_opt;\n    Xc=Xc_opt;\nend\n\nopt.Beta0=Beta0;\nopt.Kernel=Kernel;\nopt.iter=iter;\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [R, T]=getrotT(wpts,cpts)\n  \n% This routine solves the exterior orientation problem for a point cloud\n%  given in both camera and world coordinates. \n  \n% wpts = 3D points in arbitrary reference frame\n% cpts = 3D points in camera reference frame\n  \nn=size(wpts,1);\nM=zeros(3);\n\nccent=mean(cpts);\nwcent=mean(wpts);\n\nfor i=1:3\n  cpts(:,i)=cpts(:,i)-ccent(i)*ones(n,1);\n  wpts(:,i)=wpts(:,i)-wcent(i)*ones(n,1);\nend\nfor i=1:n\n   M=M+cpts(i,:)'*wpts(i,:);\nend\n[U S V]=svd(M);\nR=U*V';\nif det(R)<0\n  R=-R;\nend\nT=ccent'-R*wcent';\n% \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [err,Urep]=reprojection_error_usingRT(Xw,U,R,T,A)\n\n%clear all; close all; load reprojection_error_usingRT;\nn=size(Xw,1);\n\nP=A*[R,T];\nXw_h=[Xw,ones(n,1)];\nUrep_=(P*Xw_h')';\n\n%project reference points into the image plane\nUrep=zeros(n,2);\nUrep(:,1)=Urep_(:,1)./Urep_(:,3);\nUrep(:,2)=Urep_(:,2)./Urep_(:,3);\n\n\n%reprojection error\nerr_=sqrt((U(:,1)-Urep(:,1)).^2+(U(:,2)-Urep(:,2)).^2);\nerr=sum(err_)/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/EPnP/efficient_pnp_gauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5975407079161548}}
{"text": "%sim_evolve.m\n%Jamie Near, 2014.\n%\n% USAGE:\n% d_out = sim_evolve(d_in,H,t)\n% \n% DESCRIPTION:\n% This function simulates free evolution of the spin system under the \n% effects of chemical shift and scalar coupling.\n% \n% INPUTS:\n% d_in      = input density matrix structure.\n% H         = Hamiltonian operator structure.\n% t         = duration of evolution (s)\n%\n% OUTPUTS:\n% d_out     = output density matrix following free evolution.\n\nfunction d_out = sim_evolve(d_in,H,t)\n\nfor n=1:length(H) %JN - loop through the different parts of the spin-system\n    p=expm(1i*H(n).HAB*t);\n    d_out{n} = p' * d_in{n} * p;  %Faster than doing expm twice.  Suggested by Martin Froeling.\nend\n\nend\n\n\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/simulationTools/sim_evolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5975170378096469}}
{"text": "function varargout = norm_nuclear(varargin)\n% NORM_NUCLEAR Returns sum of singular values\n%\n% s = SUMK(X,k)\n%\n% For a vector X, NORM_NUCLEAR returns the sum of singular values\n%\n% For a matrix X, NORM_NUCLEAR returns the sum of absolute values.\n%\n% See also SUMABSK\n\nswitch class(varargin{1})\n    \n    case 'double' % What is the numerical value of this argument (needed for displays etc)\n        varargout{1} = sum(svd(varargin{1}));\n        \n    case 'sdpvar'\n        varargout{1} = yalmip('define',mfilename,varargin{:});\n        \n    case 'char' % YALMIP sends 'model' when it wants the epigraph or hypograph\n        if isequal(varargin{1},'graph')\n            t = varargin{2};\n            X = varargin{3};\n            [n,m] = size(X);\n            if is(X,'real')\n                U = sdpvar(m);\n                V = sdpvar(n);\n            else\n                U = sdpvar(m,m,'hermitian','complex');\n                V = sdpvar(n,n,'hermitian','complex');\n            end\n            F = [trace(U)+trace(V) <= 2*t, [U X';X V]>=0];\n            varargout{1} = F;\n            varargout{2} = struct('convexity','convex','monotonicity','none','definiteness','positive','model','graph');\n            varargout{3} = X;\n        else\n            varargout{1} = [];\n            varargout{2} = [];\n            varargout{3} = [];\n        end\n    otherwise\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/operators/norm_nuclear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5975170203172422}}
{"text": "classdef cubochoricPlot < axisAnglePlot\n  \n  methods\n    \n    function oP = cubochoricPlot(varargin)\n      % create a 3d plot of rotations in cubochoric coordinates\n      \n      oP = oP@axisAnglePlot(varargin{:});\n      \n     end\n        \n     function [x,y,z] = project(oP,ori,varargin)\n      \n      if ~check_option(varargin,'noBoundaryCheck')\n        switch oP.fRMode\n          case 'project2FundamentalRegion'\n            ori = project2FundamentalRegion(ori);\n          case 'restrict2FundamentalRegion'\n            ori(~oP.oR.checkInside) = NaN;\n        end\n      end\n     \n      [x,y,z] = double(cubochoric(ori));\n      \n    end\n    \n    function ori = iproject(oP,x,y,z,varargin)\n      ori = orientation.id;\n    end\n    \n    function ori = makeGrid(oP,varargin)\n      \n      [ori,S2G,omega] = makeGrid@axisAnglePlot(oP,varargin{:});\n      \n      [oP.plotGrid.x, oP.plotGrid.y, oP.plotGrid.z] = ...\n        double( S2G .* (3./4 * (omega - sin(omega))).^(1/3));\n      \n    end\n  end\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/plotting/orientationPlot/cubochoricPlot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.597517014420862}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   demo script for mesh generation from binarized volumetric image\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% preparation\n% user must add the path of iso2mesh to matlab path list\n% addpath('../');\n\n% user need to add the full path to .../iso2mesh/bin directory\n% to windows/Linux/Unix PATH environment variable\n\n%% load the sample data\nload rat_head.mat\n\n% volimage is a volumetric image such as an X-ray or MRI image\n% A,b are registration matrix and vector, respectively\n%% perform mesh generation\n\n%% use the alternative 'simplify' method: first create voxel-based\n% surface mesh, and then resample it to desired density.\n% this method does not guarantee to be free of self-intersecting\n% element, as 'cgalsurf' promises.\n\n[node,elem,face]=vol2mesh(volimage>0.05,1:size(volimage,1),1:size(volimage,2),...\n                          1:size(volimage,3),0.1,2,1,'simplify');\n\n%% visualize the resulting mesh\n\nplotmesh(node,face);\naxis equal;\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_vol2mesh_ex1b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5974511431647154}}
{"text": "function SIIval = SII(E,N,Mtype)\n\n% Implements  the ANSI S3.5-1997 standard: \n% \"Methods for calculation of the Speech Intelligibility Index\". \n%  \n%   INPUT:    \n%\n%     'E' Speech Spectrum Level (Section 3.6 in the standard)\n%         Level needs to be in dB SPL\n%     'N' Noise Spectrum Level (Section 3.15 in the standard)\n%         Level needs to be in dB SPL  \n%     'M' Speech material (needed to specify band-importance function) \n%         A scalar having a value of either 1, 2, 3, 4, 5, 6. The Band-importance functions associated with each scalar are\n%\t\t                1:\tvarious nonsense syllable tests where most English phonemes occur equally often (as specified in Table B.2)\n%\t\t                2:\tCID-22 (as specified in Table B.2)\n%\t\t                3:\tNU6 (as specified in Table B.2)\n%\t\t                3:\tDiagnostic Rhyme test (as specified in Table B.2)\n%\t\t                5:\tshort passages of easy reading material (as specified in Table B.2)\n%\t\t                6:\tSPIN (as specified in Table B.2)\n%\n%    OUTPUT:\n%       Returns the SII value (0 to 1)\n%\n%     Note that only the one-third-octave band procedure is implemented.\n%     Dimensions of 'E' and 'N' are 18x1, containing the speech and noise levels\n%     at 1/3-octave frequencies (see line 78 for 1/3-octave center frequencies)\n%\n% EXAMPLE\n% sp=[40 45 50 24 56 60 55 55 52 48 50 51 55 67 76 67 56 31];\n% ns=[30 50 60 20 60 50 70 45 80 40 60 20 60 22 55 50 67 40];\n% M= 5;\n% sv = SII (sp,ns, M);\n%\n% (c)2012 Philipos C. Loizou\n\n\nif length(E)~=18 | length(N)~=18\n    error('The target and masker spectra vectors have incorrect dimension - needs to be 18.');\nend\nif Mtype>6 | Mtype<1\n  error('Band-importance function type takes values between 1 and 6');\nend\n\n%================== DEFINE INPUT VARIABLES ==============================\n\nG=zeros(1,18);  % insertion gains - needed if used in the context of amplification devices (hearing aids)\nT=G;            % threshold levels in dB HL (for normal-hearing listeners, T=[0 0 ...0] )\nVocalEffort = 'normal';  % or \"raised\", \"loud\" and \"shout\"\n\n% Standard speech spectrum level for different vocal efforts (Table 3)\n%\nSpV=[32.41\t33.81\t35.29\t30.77;\n\t34.48\t33.92\t37.76\t36.65;\n\t34.75\t38.98\t41.55\t42.5;\n\t33.98\t38.57\t43.78\t46.51;\n\t34.59\t39.11\t43.3\t47.4;\n\t34.27\t40.15\t44.85\t49.24;\n\t32.06\t38.78\t45.55\t51.21;\n\t28.3\t36.37\t44.05\t51.44;\n\t25.01\t33.86\t42.16\t51.31;\n\t23\t\t31.89\t40.53\t49.63;\n\t20.15\t28.58\t37.7\t47.65;\n\t17.32\t25.32\t34.39\t44.32;\n\t13.18\t22.35\t30.98\t40.8;\n\t11.55\t20.15\t28.21\t38.13;\n\t9.33\t16.78\t25.41\t34.41;\n\t5.31\t11.47\t18.35\t28.24;\n\t2.59\t7.67\t13.87\t23.45;\n\t1.13\t5.07\t11.39\t20.72];\n\nswitch lower(VocalEffort)\n\tcase 'normal', EV = SpV(:,1)';\n\tcase 'raised', EV = SpV(:,2)';\n\tcase 'loud',   EV = SpV(:,3)';\n\tcase 'shout',  EV = SpV(:,4)';\n\totherwise, error('Unknown level of vocal effort')\nend;\n\n% Define band center frequencies for 1/3rd octave procedure (Table 3)\nf = [160 200 250 315 400 500 630 800 1000 1250 1600 2000, ...\n     2500 3150 4000 5000 6300 8000];\n\n\n% Define Internal Noise Spectrum Level (Table 3) \nX = [0.6 -1.7 -3.9 -6.1 -8.2 -9.7 -10.8 -11.9 -12.5 -13.5 -15.4 -17.7, ...\n\t-21.2 -24.2 -25.9 -23.6 -15.8 -7.1];\n\n\n% ----------------- start processing ----------------------\n%\n% Equivalent Speech Spectrum Level (5.1.3, Eq. 17)\t\nE = E + G;\n\n% Self-Speech Masking Spectrum (Sec 4.3.2.1, Eq. 5)\nV = E - 24;\n\n% 4.3.2.2\t\nB = max(V,N+G);\n\t\n% Calculate Equivalent Masking Spectrum Level (Sec 4.3.2.5, Eq. 9)\n%\nC = 0.6.*(B+10*log10(f)-6.353) - 80;  % slope parameter Ci (4.3.2.3 Eq. 7)\nZ(1) = B(1);\n\nfor i = 2:18\n\tZ(i) = 10*log10(10.^(0.1*N(i)) + ...\n\tsum(10.^(0.1*(B(1:(i-1))+3.32.*C(1:(i-1)).*log10(0.89*f(i)./f(1:(i-1)))))));\nend;\t\n\n\n% Equivalent Internal Noise Spectrum Level (Sec 4.4 Eq. 10)\nX = X + T;\n\t\n% Compute disturbance Spectrum Level (4.5)\nD = max(Z,X);\n\n% Level Distortion Factor (Sec 4.6, Eq. 11)\n%\nL = 1 - (E - EV - 10)./160;\nL = max(0,min(L,1)); \n\n\n% 4.7.1 Eq. 12\nK = (E-D+15)/30;\nK=max(0,min(K,1));\n\n% Band Audibility Function (7.7.2 Eq. 13)\n%\nA = L.*K;\n\n% Speech Intelligibility Index (4.8 Eq. 14)\n%\nSIIval = sum(BandImportance(Mtype).*A);\n\nreturn;\n\n\n%==================================================================\n\nfunction BIF = BandImportance(type)\n%\n% Band importance functions, taken from Table B.2:\n% type  = \n%\t\t1:\tNonsense syllable tests where most English\n%\t\t\tphonemes occur equally often\n%\t\t2:\tCID-22\n%\t\t3:\tNU6 (monosyllables)\n%\t\t4:\tDiagnostic Rhyme test (DRT)\n%\t\t5:\tshort passages of easy reading material\n%\t\t6:\tSPIN (monosyllables)\n\nif (nargin ~= 1) | (type>6) | (type<1)\n\terror('Incorrect argument to BandImportance');\nend;\n\nIFu   = [\t0\t\t0.0365\t0.0168\t0\t\t0.0114\t0\n\t\t\t0\t\t0.0279\t0.013\t0.024\t0.0153\t0.0255\n            0.0153  0.0405\t0.0211\t0.033\t0.0179\t0.0256\n\t\t\t0.0284\t0.0500\t0.0344\t0.039\t0.0558\t0.036\n\t\t\t0.0363\t0.0530\t0.0517\t0.0571\t0.0898\t0.0362\n\t\t\t0.0422\t0.0518\t0.0737\t0.0691\t0.0944\t0.0514\n\t\t\t0.0509\t0.0514\t0.0658\t0.0781\t0.0709\t0.0616\n\t\t\t0.0584\t0.0575\t0.0644\t0.0751\t0.066\t0.077\n\t\t\t0.0667\t0.0717\t0.0664\t0.0781\t0.0628\t0.0718\n\t\t\t0.0774\t0.0873\t0.0802\t0.0811\t0.0672\t0.0718\n\t\t\t0.0893\t0.0902\t0.0987\t0.0961\t0.0747\t0.1075\n\t\t\t0.1104\t0.0938\t0.1171\t0.0901\t0.0755\t0.0921\n\t\t\t0.112\t0.0928\t0.0932\t0.0781\t0.082\t0.1026\n\t\t\t0.0981\t0.0678\t0.0783\t0.0691\t0.0808\t0.0922\n\t\t\t0.0867\t0.0498\t0.0562\t0.048\t0.0483\t0.0719\n\t\t\t0.0728\t0.0312\t0.0337\t0.033\t0.0453\t0.0461\n\t\t\t0.0551\t0.0215\t0.0177\t0.027\t0.0274\t0.0306\n\t\t\t0\t\t0.0253\t0.0176\t0.024\t0.0145\t0];\n\nBIF = IFu(:,type)';\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/MATLAB_code/objective_measures/intelligibility/SII.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5974307165962724}}
{"text": "function x=ibm2num(b)\n% ibm2num : convert IBM 32 bit floating point format to doubles\n%    x=num2ibm(b)\n% b is a matrix of uint32\n% x is a corresponding matrix of doubles\n%\n%\n% See also num2ibm\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\n\n\nx=repmat(NaN,size(b));\n\nsign=bitget(b,32);                            % get sign from first bit\nsign=double(sign);\n\n% format hex\nexp=bitand(b,uint32(hex2dec('7f000000')));    % get exponent from first byte, last 7 bits\nexp=bitshift(exp,-24);\n%format long\n\nexp=double(exp)- 64;                          % remove bias from exponent \n\n%format hex\nfrac=bitand(b,uint32(hex2dec('00ffffff')));   % get mantissa from last 3 bytes\n%format long\nfrac=double(frac);\nfrac=frac/2^24;\n\n\nx=(1-2*sign).*16.^exp .* frac;\n\nerr = frac==0 & (exp~=-64 | sign~=0);         % bias removal is incorrect for zero\nif any(err)\n   % TMH 19/06/2003\n   disp(['WARNING : ',mfilename,' Invalid zero input --> Sure data are IBM FLOAT formatted ?'])\t\n   return;\t\t\t\t\t\t\t     \n   %warning('Invalid zero input in ibm2num for the following:')\n   % format hex; disp(b(err)); format\t\t\t\t\t\t\t      \nend\n\nerr = frac~=0 & (frac<1/16 | frac>=1);\nif any(err)\n   % TMH 19/06/2003\n   disp(['WARNING : ',mfilename,' Invalid mantissa input --> Sure data are IBM FLOAT formatted ?'])\t\n   return;\n   % warning('Invalid mantissa input in ibm2num for the following:')\n   % format hex; disp(b(err)); format\t\t\t\t\t\t\t      \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/ibm2num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5974275286915774}}
{"text": "function result = cartesianProduct(sets)\n    c = cell(1, numel(sets));\n    [c{:}] = ndgrid( sets{:} );\n    result = cell2mat( cellfun(@(v)v(:), c, 'UniformOutput',false) );\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/cartesianProduct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5974275267489744}}
{"text": "function [x, fx, exitFlag] = bisection(f,lb,ub,target,options)%#codegen\n    % BISECTION Fast and robust root-finding method that handles n-dim arrays.\n    %\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 <a href=\"http://en.wikipedia.org/wiki/Bisection_method\">bisection method</a> is very robust root-finding method. The absolute\n    %   error is halved at each step so the method converges linearly. However,\n    %   <a href=\"http://en.wikipedia.org/wiki/Brent%27s_method\">Brent's method</a> (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    \n    tolX    = 1e-6;\n    tolFun  = 0;\n    if 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\n    end\n    if nargin<4 || isempty(target); target=0; end\n    \n    \n    ub_in = ub; lb_in = lb;\n    f = @(x) f(x) - target;\n    \n    % --- Flip UB and LB if necessary. ---\n    isFlipped = lb>ub;\n    if any(isFlipped(:))\n        ub(isFlipped) = lb_in(isFlipped);\n        lb(isFlipped) = ub_in(isFlipped);\n        ub_in = ub; lb_in = lb;\n    end\n    \n    % --- Make sure everything is the same size for a non-scalar problem. ---\n    if 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\n    end\n    \n    % Check if lb and/or ub need to be made into arrays.\n    if isscalar(lb) && ~isscalar(ub)\n        lb = lb + zeros(size(ub));\n    elseif ~isscalar(lb) && isscalar(ub)\n        ub = ub + zeros(size(lb));\n    end\n    \n    x = zeros(size(lb));\n    [x, fx, outsideTolFun, outsideTolX, stillNotDone] = testconvergence(f, ub, lb, tolFun, tolX);\n    % --- Iterate ---\n    iterations = 0;\n    while any(stillNotDone(:))\n        bigger  = fx.*f(ub) > 0;\n        ub(bigger)= x(bigger);\n        lb(~bigger)= x(~bigger);\n        \n        [x, fx, outsideTolFun, outsideTolX, stillNotDone] = testconvergence(f, ub, lb, tolFun, tolX);\n        iterations = iterations + 1;\n        \n        if(iterations > 10000)\n            %         error('Too many iterations in bisection!');\n            break;\n        end\n    end\n    \n    % --- Check that f(x+tolX) and f(x-tolX) have opposite sign. ---\n    fu = f(min(x+tolX,ub_in));\n    fl = f(max(x-tolX,lb_in));\n    unboundedRoot = (fu.*fl) > 0;\n    \n    % Throw out unbounded results if not meeting TolFun convergence criteria.\n    \n    x(unboundedRoot & outsideTolFun) = NaN;\n    \n    % --- Catch NaN elements of UB, LB, target, or other funky stuff. ---\n    x(isnan(fx)) = NaN;\n    \n    % --- Characterize results. ---\n    fx = fx + target;\n    if nargout > 2\n        exitFlag                                    = +~outsideTolX;\n        exitFlag(~outsideTolFun)                    =  2;\n        exitFlag(~outsideTolFun & ~outsideTolX)     =  3;\n        exitFlag(isnan(x))                          = -1;\n    end\nend\n\nfunction [x, fx, outsideTolFun, outsideTolX, stillNotDone] = testconvergence(f, ub, lb, tolFun, tolX)\n    x=(ub+lb)/2;\n    fx=f(x);\n    outsideTolFun =  abs(fx)  > tolFun;\n    outsideTolX =   (ub - lb) > tolX;\n    stillNotDone = outsideTolX & outsideTolFun;\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.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5974275196517252}}
{"text": "function [vals, pos] = minandmax(f)\n%MINANDMAX   Global minimum and maximum of the SINGFUN F on [-1,1].\n%   VALS = MINANDMAX(F) returns a 2-vector VALS = [MIN(F); MAX(F)] with the\n%   global minimum and maximum of the SINGFUN F on [-1,1].\n%\n%   [VALS, POS] = MINANDMAX(F) returns also the 2-vector POS where the minimum\n%   and maximum of F occur.\n%\n% See also MIN, MAX.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\ntol = chebfunpref().blowupPrefs.exponentTol;\n\nif ( ~any(f.exponents) || all(abs(f.exponents) < tol) )\n  \n    % The function is actually smooth!\n    [vals, pos] = minandmax(f.smoothPart);\n    \nelse\n    \n    % Initialise:\n    minF = [];\n    maxF = [];\n    minLoc = [];\n    maxLoc = [];   \n    \n    % Look for blow up at the left:\n    if ( f.exponents(1) < -tol ) % Singularity at the left end.\n        fVal = feval(f, -1);\n        if ( fVal == inf )\n            maxF = inf;\n            maxLoc = -1;\n        elseif ( fVal == -inf )\n            minF = -inf;\n            minLoc = -1;\n        else\n            % NaNs may occur and then we can not conclude anything.\n            error('CHEBFUN:SINGFUN:minandmax:boundedness', ...\n            ['Function has a singularity but isn''t infinite at the left ' ...\n             'endpoint']);\n        end\n    end\n    \n    % Look for blow up at the right:\n    if ( f.exponents(2) < -tol ) % Singularity at the right end.\n        fVal = feval(f, 1);\n        if ( fVal == inf )\n            maxF = inf;\n            maxLoc = 1;\n        elseif ( fVal == -inf )\n            minF = -inf;\n            minLoc = 1;\n        else\n            % NaNs may occur and then we can not conclude anything.\n            error('CHEBFUN:SINGFUN:minandmax:boundedness', ...\n            ['Function has a singularity but isn''t infinite at the right ' ...\n             'endpoint']);\n        end\n    end\n    \n    % If min or max is empty, then we need to do more work:\n    if ( isempty(minF) || isempty(maxF) )       \n        % Find the roots of the derivative for local minima:\n        fp = diff(f);\n        r = roots(fp);\n        % Append the end points and remove duplicates:\n        r = unique([-1 ; r ; 1]);\n        if ( isempty(maxF) )\n            % Take the maximum of the local maxima:\n            [maxF, maxIndex] = max(feval(f, r));\n            maxLoc = r(maxIndex);\n        end\n        if ( isempty(minF) )\n            % Take the minimum of the local minima:\n            [minF, minIndex] = min(feval(f, r));\n            minLoc = r(minIndex);\n        end             \n    end    \n    vals = [ minF; maxF ];\n    pos = [ minLoc; maxLoc ];\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/@singfun/minandmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.5973454931272776}}
{"text": "%% Copyright (C) 2016 Abhinav Tripathi\n%% Copyright (C) 2016, 2018-2019, 2022 Colin B. Macdonald\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see <http://www.gnu.org/licenses/>.\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defmethod @@sym chebyshevU (@var{n}, @var{x})\n%% Find the nth symbolic Chebyshev polynomial of the second kind.\n%%\n%% If @var{n} is a vector then it returns a vector with Chebyshev polynomials\n%% of the second kind for each element of @var{n}.\n%%\n%% Examples:\n%% @example\n%% @group\n%% syms x\n%% chebyshevU(1, x)\n%%   @result{} (sym) 2\u22c5x\n%% chebyshevU(2, x)\n%%   @result{} (sym)\n%%          2\n%%       4\u22c5x  - 1\n%% syms n\n%% chebyshevU(n, x)\n%%   @result{} (sym) chebyshevu(n, x)\n%% @end group\n%% @end example\n%%\n%% The inputs can be vectors, for example:\n%% @example\n%% @group\n%% syms x\n%% chebyshevU([0 1 2], x)\n%%   @result{} (sym 1\u00d73 matrix)\n%%       \u23a1           2    \u23a4\n%%       \u23a31  2\u22c5x  4\u22c5x  - 1\u23a6\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/chebyshevT, @@double/chebyshevU}\n%% @end defmethod\n\n\nfunction y = chebyshevU(n, x)\n  if (nargin ~= 2)\n    print_usage ();\n  end\n  y = elementwise_op ('chebyshevu', sym(n), sym(x));\nend\n\n\n%!error chebyshevU (sym(1))\n%!error chebyshevU (sym(1), 2, 3)\n\n%!assert (isequaln (chebyshevU (2, sym(nan)), sym(nan)))\n\n%!shared x\n%! syms x\n\n%!assert(isequal(chebyshevU(0, x), sym(1)))\n%!assert(isequal(chebyshevU(1, x), 2*x))\n%!assert(isequal(chebyshevU(2, x), 4*x*x - 1))\n%!assert(isequal(chebyshevU([0 1 2], x), [sym(1) 2*x (4*x*x-1)]))\n\n%!test\n%! % round trip\n%! syms n z\n%! f = chebyshevU (n, z);\n%! h = function_handle (f, 'vars', [n z]);\n%! A = h (1.1, 2.2);\n%! B = chebyshevU (1.1, 2.2);\n%! assert (A, B)\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/chebyshevU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.5973454884273456}}
{"text": "\n%% ggremesh\n% Below is a demonstration of the features of the |ggremesh| function\n\n%% Syntax\n% |[Fn,Vn]=ggremesh(F,V,optionStruct)|\n\n%% Description \n% This function uses the external library Geogram to remesh the input\n% triangulation defined by the faces F and the vertices V. In particular\n% the code \"vorpalite\" is used. An additional option structure may be\n% provided where users can set particular parameters for Geogram. \n%\n% Below the options and defaults are provided: \n% optionStruct.nb_pts=size(V,1); %number of points\n% optionStruct.anisotropy=0; %Use anisotropy (~=0) to capture geometry or favour isotropic triangles (=0)\n% optionStruct.pre.max_hole_area=100; %Max hole area for pre-processing step\n% optionStruct.pre.max_hole_edges=0; %Max number of hole edges for pre-processing step\n% optionStruct.post.max_hole_area=100; %Max hole area for post-processing step\n% optionStruct.post.max_hole_edges=0; %Max number of hole edges for post-processing step\n% optionStruct.disp_on=1; %Turn on/off displaying of Geogram text\n%\n% Instead of nb_pts users can also specify a pointSpacing to be used\n% instead of nb_pts. This is not a Geogram feature but a GIBBON option\n% which is translated to the number of points for Geogram remeshing. This\n% is and example for a desired point spacing of 4:  \n% optionStruct.pointSpacing=4\n%\n% Geogram website:\n% http://alice.loria.fr/index.php/software/4-library/75-geogram.html \n% \n% Geogram license: \n% http://alice.loria.fr/software/geogram/doc/html/geogram_license.html\n%\n% L\u00e9vy B., Bonneel N. (2013) Variational Anisotropic Surface Meshing with\n% Voronoi Parallel Linear Enumeration. In: Jiao X., Weill JC. (eds)\n% Proceedings of the 21st International Meshing Roundtable. Springer,\n% Berlin, Heidelberg. https://doi.org/10.1007/978-3-642-33573-0_21 \n% \n% See also: \n% http://alice.loria.fr/publications/papers/2012/Vorpaline_IMR/vorpaline.pdf\n% https://www.ljll.math.upmc.fr/hecht/ftp/ff++days/2013/BrunoLevy.pdf\n\n%% Examples \n\n%%\nclear; close all; clc;\n\n%%\n% Plot settings\nfontSize=15;\nfaceColor='b';\nfaceAlpha=1;\nedgeColor='k';\nedgeWidth=0.5;\n\n%% Example 1: Remeshing a triangulated surface isotropically\n\n%% \n% Get example geometry\n[F,V]=graphicsModels(5); % Get surface\n\n%%\n% Remesh using ggremesh\n\n[Fn,Vn]=ggremesh(F,V);\n\n%%\n% Visualiza patch data\n\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Input mesh');\ngpatch(F,V,'w','k');\naxisGeom;\nview(-75,-36);\ncamlight headlight; axis off;\n\nsubplot(1,2,2); hold on;\ntitle('Geogram remeshed');\ngpatch(Fn,Vn,'gw','k',1,1);\naxisGeom;\nview(-75,-36);\ncamlight headlight; axis off;\n\ngdrawnow;\n\n%% Example 2: Remeshing a triangulated surface with desired number of points\n\n%% \n% Get example geometry\n[F,V]=graphicsModels(1); % Get surface\n\n%%\n% Remesh using ggremesh\n\noptionStruct1.nb_pts=500; %Set desired number of points\n[Fn,Vn]=ggremesh(F,V,optionStruct1);\n\n%%\n% Visualiza patch data\n\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Input mesh');\ngpatch(F,V,'w','k');\naxisGeom;\ncamlight headlight; axis off;\n\nsubplot(1,2,2); hold on;\ntitle('Geogram remeshed');\ngpatch(Fn,Vn,'gw','k',1,1);\naxisGeom;\ncamlight headlight; axis off;\n\ngdrawnow;\n\n%% Example 3: Remeshing a triangulated surface with desired point spacing\n\n%% \n% Get example geometry\n[F,V]=graphicsModels(11); % Get surface\n\n%%\n% Remesh using ggremesh\n\noptionStruct2.pointSpacing=4; %Set desired point spacing\noptionStruct2.disp_on=1; % Turn off command window text display\n[Fn,Vn]=ggremesh(F,V,optionStruct2);\n\n%%\n% Visualiza patch data\n\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Input mesh');\ngpatch(F,V,'w','k');\naxisGeom;\ncamlight headlight; \n\nsubplot(1,2,2); hold on;\ntitle('Geogram remeshed');\ngpatch(Fn,Vn,'gw','k',1,1);\naxisGeom;\ncamlight headlight; \n\ngdrawnow;\n\n%% Example 4: Setting pre- and prost-processing settings e.g. to close holes\n\n%% \n% Get example geometry\n\ninputStruct.cylRadius=1;\ninputStruct.numRadial=15;\ninputStruct.cylHeight=3;\ninputStruct.numHeight=11;\ninputStruct.meshType='tri';\n\n% Derive patch data for a cylinder\n[F,V]=patchcylinder(inputStruct); \n\n%% \n% Remesh using ggremesh\noptionStruct3.nb_pts=size(V,1); %Set desired number of points\noptionStruct3.disp_on=0; % Turn off command window text display\noptionStruct3.pre.max_hole_area=10; %Max hole area for pre-processing step\noptionStruct3.pre.max_hole_edges=20; %Max number of hole edges for pre-processing step\n% optionStruct3.post.max_hole_area=10; %Max hole area for post-processing step\n% optionStruct3.post.max_hole_edges=20; %Max number of hole edges for post-processing step\n\n[Fn,Vn]=ggremesh(F,V,optionStruct3);\n\n% Visualiza patch data\nEb=patchBoundary(F);\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Input mesh with holes');\ngpatch(F,V,'w','k');\ngpatch(Eb,V,'none','b',1,2);\naxisGeom;\ncamlight headlight; \n\nsubplot(1,2,2); hold on;\ntitle('Geogram remeshed and closed');\ngpatch(Fn,Vn,'gw','k',1,1);\naxisGeom;\ncamlight headlight; \n\ngdrawnow;\n\n%% Example 5: Setting pre- and prost-processing settings e.g. to avoid closure of holes\n\n%% \n% Get example geometry\n\ninputStruct.cylRadius=1;\ninputStruct.numRadial=15;\ninputStruct.cylHeight=3;\ninputStruct.numHeight=11;\ninputStruct.meshType='tri';\n\n% Derive patch data for a cylinder\n[F,V]=patchcylinder(inputStruct); \n\n%% \n% Remesh using ggremesh\noptionStruct3.nb_pts=size(V,1); %Set desired number of points\noptionStruct3.disp_on=1; % Turn off command window text display\noptionStruct3.pre.max_hole_area=100; %Max hole area for pre-processing step\noptionStruct3.pre.max_hole_edges=0; %Max number of hole edges for pre-processing step\n\n[Fn,Vn]=ggremesh(F,V,optionStruct3);\n\n% Visualiza patch data\nEb=patchBoundary(F);\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Input mesh with holes');\ngpatch(F,V,'w','k');\ngpatch(Eb,V,'none','b',1,2);\naxisGeom;\ncamlight headlight; \n\nsubplot(1,2,2); hold on;\ntitle('Geogram remeshed with holes');\ngpatch(Fn,Vn,'gw','k',1,1);\naxisGeom;\ncamlight headlight; \n\ngdrawnow;\n\n%% \n%\n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_ggremesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.5973454803443834}}
{"text": "function h = hesschek(net, x, t)\n%HESSCHEK Use central differences to confirm correct evaluation of Hessian matrix.\n%\n%\tDescription\n%\n%\tHESSCHEK(NET, X, T) takes a network data structure NET, together with\n%\tinput and target data matrices X and T, and compares the evaluation\n%\tof the Hessian matrix using the function NETHESS and using central\n%\tdifferences with the function NETERR.\n%\n%\tThe optional return value H is the Hessian computed using NETHESS.\n%\n%\tSee also\n%\tNETHESS, NETERR\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\nw0 = netpak(net);\nnwts = length(w0);\nh = nethess(w0, net, x, t);\n\nw = w0;\nhcent = zeros(nwts, nwts);\nh1 =  0.0; h2 =  0.0; h3 =  0.0; h4 = 0.0;\nepsilon = 1.0e-4;\nfprintf(1, 'Checking Hessian ...\\n\\n');\nfor k = 1:nwts;\n  for l = 1:nwts;\n    if(l == k)\n      w(k) = w0(k) + 2.0*epsilon;\n      h1 = neterr(w, net, x, t);\n      w(k) = w0(k) - 2.0*epsilon;\n      h2 = neterr(w, net, x, t);\n      w(k) = w0(k);\n      h3 = neterr(w, net, x, t);\n      hcent(k, k) = (h1 + h2 - 2.0*h3)/(4.0*epsilon^2);\n    else\n      w(k) = w0(k) + epsilon;\n      w(l) = w0(l) + epsilon;\n      h1 = neterr(w, net, x, t);\n      w(k) = w0(k) - epsilon;\n      w(l) = w0(l) - epsilon;\n      h2 = neterr(w, net, x, t);\n      w(k) = w0(k) + epsilon;\n      w(l) = w0(l) - epsilon;\n      h3 = neterr(w, net, x, t);\n      w(k) = w0(k) - epsilon;\n      w(l) = w0(l) + epsilon;\n      h4 = neterr(w, net, x, t);\n      hcent(k, l) = (h1 + h2 - h3 - h4)/(4.0*epsilon^2);\n      w(k) = w0(k);\n      w(l) = w0(l);\n    end\n  end\nend\n\nfprintf(1, '   analytical    numerical       delta\\n\\n');\ntemp = [h(:), hcent(:), (h(:) - hcent(:))];\nfprintf(1, '%12.6f  %12.6f  %12.6f\\n', temp');", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/hesschek.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.5973454684394239}}
{"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%\tlocal_group_invariance.m:\n%\n% Description:\n%\n%   Implements the Local Group Invariance algorithm.\n%   NOTE: the implementation considers the translation invariance solely.\n%\n% References:\n%\n%   Christian S. Pilz, S. Zaunseder, J. Krajewski, V. Blazek, \n%   Local Group Invariance for Heart Rate Estimation from Face Videos in the Wild, \n%   The IEEE Conference on Computer Vision and Pattern Recognition (CVPR) Workshops, \n%   pp.1254-1262, Salt Lake City, 2018\n%\n\nclassdef local_group_invariance\n    \n   properties\n \n   end\n   \n   methods\n       \n       function obj = local_group_invariance()\n          \n       end\n      \n       function [pulse, obj] = get(obj,skin_pixels)\n           \n           pulse=[];\n           frames=size(skin_pixels,2);\n           C=[];\n           \n           for f=1:frames\n               x=skin_pixels{f};\n               C(f,:)=[mean(x(:,1)); mean(x(:,2)); mean(x(:,3));];\n           end  \n           \n           [U,E,V]=svd(C');\n           \n           S=U(:,1)';\n           P=eye(3)-S'*S;%rank 1\n           \n           F(1:frames,3)=0;\n           for f=1:frames\n              F(f,:)=(P*C(f,:)')';   \n           end\n\n           pulse=double(F(:,2));\n       end\n   end\nend\n\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/features/local_group_invariance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5973359331904465}}
{"text": "function [vol,dist] = volume(psi,radius,dist)\n\nif nargin < 3\n  N = 60;\n  dist = zeros(numel(radius),N);\n  for i = 1:length(radius)\n        \n    if radius(i) + 5 * psi.halfwidth < pi\n      dist(i,1:N-9) = linspace(0,radius(i) + 5 * psi.halfwidth,N-9);\n      dist(i,N-9:end) = linspace(radius(i) + 5 * psi.halfwidth,pi,10);\n    else\n      dist(i,:) = linspace(0,pi,N);\n    end\n    \n  end\n\nend\n\n% make radius square as well\nradius = repmat(radius(:),1,size(dist,2));\n\n% weight function\nweight = @(rot_angle,quat_dist,volume_radius) (max(0,min(4*pi,2*pi*(1-(cos(volume_radius/2) - ...\n  cos(quat_dist/2) * cos(rot_angle/2))./...\n  (sin(quat_dist/2) * sin(rot_angle/2))))) ...\n  + max(0,min(4*pi,2*pi*(1-(cos(volume_radius/2) + ...\n  cos(quat_dist/2) * cos(rot_angle/2))./...\n  (sin(quat_dist/2) * sin(rot_angle/2))))))./pi./4;\n\n% integrant\nKV = @(rot_angle,quat_dist,volume_radius) weight(rot_angle,quat_dist,volume_radius) ...\n  .* sin(rot_angle ./2).^2 .* psi.eval(cos(rot_angle./2)) ./pi.*2 ;\n\n% perform quadrature\n%vol = zeros(size(dist));\n%for j = 1:length(dist)\n%  vol(j) = quad(@(rot_angle) KV(rot_angle,dist(j),radius),0,min(pi,5*k.hw),1e-6);\n%end\n\n%vol = quadv(@(rot_angle) KV(rot_angle,dist,radius),0,min(pi,5*psi.halfwidth),1e-7);\nvol = integral(@(rot_angle) KV(rot_angle,dist,radius),0,min(pi,5*psi.halfwidth),'AbsTol',1e-7,'ArrayValued',true);\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/SO3Fun/SO3KernelFunctions/@SO3Kernel/volume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443461, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5973359217704017}}
{"text": "function [ccf,pst] = spm_csd2ccf(csd,Hz,dt)\n% Converts cross spectral density to cross covariance function\n% FORMAT [ccf,pst] = spm_csd2ccf(csd,Hz,dt)\n%\n% csd  (n,:,:)          - cross spectral density (cf, mar.P)\n% Hz   (n x 1)          - vector of frequencies (Hz)\n% dt                    - samping interval (default = 1/(2*Hz(end)))\n%\n% ccf                   - cross covariance functions\n% pst  (N,1)            - vector of lags for evaluation (seconds)\n%\n% Note that because this scheme uses FFT one can only change dt.\n%\n% See also: \n%  spm_ccf2csd.m, spm_ccf2mar, spm_csd2ccf.m, spm_csd2mar.m, spm_mar2csd.m,\n%  spm_csd2coh.m, spm_Q.m, spm_mar.m and spm_mar_spectral.m\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_csd2ccf.m 6395 2015-03-26 15:05:04Z adeel $\n\n% Nyquist\n%--------------------------------------------------------------------------\nif nargin < 3, dt  = 1/(2*Hz(end)); end\n \n% unpack cells\n%--------------------------------------------------------------------------\nif iscell(csd)\n    for i = 1:length(csd)\n       [ccfi,pst] = spm_csd2ccf(csd{i},Hz,dt);\n       ccf{i}     = ccfi;\n    end\n    return\nend\n \n% unpack time bins (for time-frequency responses)\n%--------------------------------------------------------------------------\nif ndims(csd) == 4\n    for i = 1:size(csd,1)\n       [ccfi,pst]   = spm_csd2ccf(squeeze(csd(i,:,:,:)),Hz,dt);\n       ccf(i,:,:,:) = ccfi;\n    end\n    return\nend\n\n\n% indices for FFT\n%--------------------------------------------------------------------------\ndw    = Hz(2) - Hz(1);\nHz    = Hz/dw;\nns    = 1/dt;\nN     = ceil(ns/2/dw);\ngj    = find(Hz > 0 & Hz < (N + 1));\ngi    = gj + ceil(Hz(1)) - 1;\ng     = zeros(N,1);\n\n% Fourier transform cross-spectral density\n%==========================================================================\nfor i = 1:size(csd,2)\n    if ismatrix(csd)\n        g(gi)      = csd(gj,i);\n        f          = ifft([0; g; flipud(conj(g))]);\n        ccf(:,i)   = real(fftshift(f))*N*dw;\n    else\n        for j = 1:size(csd,3)\n            g(gi)      = csd(gj,i,j);\n            f          = ifft([0; g; flipud(conj(g))]);\n            ccf(:,i,j) = real(fftshift(f))*N*dw;\n        end\n    end\nend\n \n% Compute time bins\n%--------------------------------------------------------------------------\npst = dt*(-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/spectral/spm_csd2ccf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5972547396264021}}
{"text": "                    function rot\n% ***************************************************************\n%                   P r o g r a m   ROT\n% ***************************************************************\n%\n%  PURPOSE:\n%     Resolve numerically differential equation of rotational motion\n%     of a body\n%                      Jz*d2f/dt2 = Mz(t,f,w)\n%     and plots graphics of coordinate, velocity and phase plane.\n%     If possible, the program could solve the problem analytically.\n%\n%  INPUT DATA:\n%     Jz   - moment of inertia of the body ;\n%     Mz   - rotational moment  Mz = Mz(t,f,w);\n%     f0   - initial value of the coordinate ;\n%     w0   - initial value of the angular velocity ;\n%     Tend - upper bound of the integration ;\n%     eps  - precision of the integration ;\n%     np   - number of parameters .\n%     P{1}, P{2}, ..., P{np} - names of the parameters (array of cells);\n%\n%  NOTES:\n%   1. The coordinate is designed by the symbol 'f' and velocity by 'w';\n%   2. The physical names of the parameters are assigned to the\n%      cells of the array P like this: P{1}='Jz', P{2}='c',...;\n%   3. For analytical solution the values of Tend, eps, np and P are not\n%      needed. \n%   4. The parameters Jz, f0 and w0 have to be entered only as\n%      strings, even though they represent numbers!\n%   5. All the data can be input from file or in interactive mode.\n%\n%  EXAMPLE of DATA FILE:\n%   % Data File for problem ...\n%     Jz   = 'Jz'; ( or Jz = '0.15';)\n%     Mz   = '-k*w - c*f'; % k, c - parameters\n%     f0   = 'f0'; ( or f0 = '0.33';)\n%     w0   = 'w0'; ( or w0 = '7';)\n%     Tend = 20;\n%     eps  = 1.e-8;\n%     np   = 3;\n%     P{1} = 'Jz';\n%     P{2} = 'k';\n%     P{3} = 'c';\n\n% ---------------------------------------------------------\n%               DATA INPUT OF THE PROBLEM\n% =========================================================\n\n clear\n disp(' ');\n disp(' How will you input the data ?    ');\n disp('     1. From a data file;         ');\n disp('     2. In interactive mode.      ');\n ans = input(' Number of Your choice : '  );\n flag = 0;\n if ans == 1\n    while 1\n       disp(' ');\n       indat = input(' Input the name of the data file :', 's');\n       if exist([cd,'\\',indat]) % Search only in current directory\n          eval(indat);\n          flag = 1; break  % Successful\n        else               % Unsuccessful\n          disp(' ');\n          disp([' File ',indat,' not exist!'])\n          disp(' You have to:')\n          disp(' 1. Enter another DATA file name, or')\n          disp(' 2. Input the DATA interactively !')\n          ans2 = input(' Your choice, please: ');\n          if ans2 == 2, break , end\n       end\n    end\n end\nif flag == 0  \n    %Input of the data in-line mode\n    disp(' ');\n    Jz   = input(' Moment of inertia of the body Jz : ','s'      );\n    Mz   = input(' Expression of the rotational moment Mz : ','s');\n    f0   = input(' Initial coordinate f0 : '                     );\n    w0   = input(' Initial velocity w0 : '                       );\n    Tend = input(' Upper bound of the integration Tend : '       );\n    eps  = input(' Precision of the calculations eps : '         );\n    np   = input(' Number of parameters  np : '                  );\n    % Asigning names of the parameters\n    if np > 0\n       disp(' ');\n       disp(' Enter names of the parameters:')\n       for i = 1:np\n           ii = num2str(i);\n           P{i} = input([' Name of parameter P',ii,': '],'s');\n       end\n    end \n end\n \n% ---------------------------------------------------------\n%            Differential Equation of Motion\n% =========================================================\n\n                 syms f w D2f \n                 Mz = subs(Mz, 'w', 'Df');\n                 deq = Jz*D2f - Mz;\n\n% ---------------------------------------------------------\n%                  ANALYTICAL SOLUTION\n% =========================================================\n\n disp(' ');\n ans = input(' Would you like analytical solution? (Y/N): ','s');\n if ans =='Y' | ans == 'y'\n    if ~isstr(f0), f0 = num2str(f0); end % Repairing user\n    if ~isstr(w0), w0 = num2str(w0); end % input errors!\n    syms f\n    inicond = ['f(0)=',f0,',Df(0)=',w0];\n    f = dsolve(char(deq), inicond, 't');\n    if ~isempty(f)\n        disp(' ');\n        disp('   Low of Motion   ');\n        disp(' ***************** ');\n        disp(' ');\n        disp('f = '); pretty(f)\n        disp(' ');\n        fname = input(' Name of file to write solution: ','s');\n        save(fname, 'f');\n    end\n       disp(' ');\n       ans = input(' Would you like numerical solution? (Y/N): ','s');\n       if ans == 'N' | ans == 'n', return, end \n       f = 'f'; % Clear contents of f\n end\n\n% ---------------------------------------------------------\n%                  NUMERICAL SOLUTION\n% ========================================================= \n\n% Input the name of the file-function\ndisp(' ');\nfname = input(' Name of the File-function to be generated: ','s');\nflag1 = 'Y';\nif exist([cd,'\\',fname]) % Search only in current directory!\n    disp(' ');\n    disp([' A file-function with name ',fname,' already exist !'])\n    flag1 = input(' Overwrite it ? (Y/N): ', 's');\nend\n\n% ---------------------------------------------------------\n%              GENERATING THE FILE-FUNCTION\n% ---------------------------------------------------------\n\nif ( flag1 == 'Y' | flag1 == 'y' )\n   Mz = subs(Mz,{'f','Df'},{'y(1)','y(2)'});\n% Opening the file for writing file-function\n   [Fid,mes] = fopen([fname,'.m'],'wt');\n% Generating the string with physical parameters: Jz, c ...\n   strpar = '';\n   for j = 1:np\n      strpar = [strpar,',',P{j}];\n   end\n   titl = input(' Denomination of the Problem: ','s');\n%       Writing the headline of the File-function\n   fprintf(Fid,['function yt = ',fname,'(t,y',strpar,')\\n']);\n   fprintf(Fid,['%% ',titl]);\n%       Writing the first derivatives\n   fprintf(Fid,'\\n%% The first derivatives\\n');\n   fprintf(Fid, '  yt(1) = y(2); \\n');\n   fprintf(Fid,['  yt(2) = ',char(Mz/Jz),'; \\n']);\n   fprintf(Fid,'  yt = yt'';\\n');\n   fprintf(Fid,['%% *** End of File-function ',fname,' ***']);\n   fclose(Fid);\n   edit(fname)\nend\n\n% ---------------------------------------------------------\n%        INTEGRATION AND VISUALIZATION OF THE REZULTS\n% ---------------------------------------------------------\n\nflag2 = 0;\n% Initial entering values of the parameters and generating\n% the string with parameters 'P{1}, P{2}, ..., P{np}' to be\n% passed to the File-function as actual arguments \nif np > 0\n   PP = P; % Saving the physical names of the parameters in PP \n   parameters = ' ';\n   disp(' ');\n   disp(' Input the numerical values of the parameters: ')\n   for i = 1:np\n       i = num2str(i);\n       eval(['P{',i,'}=input([''   '',P{',i,'},'' = '']);']);\n       parameters = [parameters,',P{',i,'}'];\n   end \nelse\n    parameters = [];\nend\n% Check-up type of f0 and w0 and correct\n% it if needed\nif ischar(f0)\n    f0 = str2num(f0);\n    if isempty(f0), f0 = input(' f0 = '); end\nend\nif ischar(w0)\n    w0 = str2num(w0);\n    if isempty(w0), w0 = input(' w0 = '); end\nend\nwhile 1\n    if flag2 == 1\n        disp(' ');\n        eps  = input(' Precision of the computations eps: ');\n        Tend = input(' Upper bound of the integration Tend: ');\n        f0   = input(' Initial coordinate f0: ');\n        w0   = input(' Initial velocity w0: ');\n        if np > 0\n          P = PP; % Restoring the names of the parameters !\n          disp(' ');\n          disp(' Input the numerical values of the parameters: ')\n          for i = 1:np\n              i = num2str(i);\n              eval(['P{',i,'}=input([''   '',P{',i,'},'' = '']);']);\n          end \n        end\n    end\n    y0 = [f0 w0]; % initial conditions\n    options = odeset('AbsTol',eps,'RelTol',100*eps);\n    % Choosing of the Solver\n    disp('                                        ');\n    disp('      Choose the proper Solver:         ');\n    disp('  -------------------------------       ');\n    disp(' A. Non stiff differential equations    ');\n    disp('   1. ode45   - middle precision;       ');\n    disp('   2. ode23   - low precision;          ');\n    disp('   3. ode113  - from low to upper.      ');\n    disp('                                        ');\n    disp(' B. Stiff differential equations        ');\n    disp('   1. ode15s  - from low to upper;      ');\n    disp('   2. ode23s  - low precision;          ');\n    disp('   3. ode23t  - middle precision;       ');\n    disp('   4. ode23tb - low precision.          ');\n    disp('                                        ');\n    solver = input(' The name of the Solver: ','s');\n   \n    % Integration of the Differential Equations\n        \n    eval(['[t,y] = feval(solver,eval([''@'',fname]),',...\n                  '[0 Tend],y0,options',parameters,');']);\n    % Plotting graphs\n    \n    tmin  = min(t); \n    tmax  = max(t);\n    y1min = min(y(:,1)); \n    y1max = max(y(:,1));\n    y2min = min(y(:,2)); \n    y2max = max(y(:,2));\n    dy1   = y1max - y1min;\n    dy2   = y2max - y2min;\n    xmin  = y1min - 0.1*dy1;\n    xmax  = y1max + 0.1*dy1;\n    ymin  = y2min - 0.1*dy2;\n    ymax  = y2max + 0.1*dy2;\n    % Coordinate f = f(t)\n    figure % 1\n    comet(t,y(:,1))\n    plot(t,y(:,1),[tmin tmax],[0 0],'k'), grid on\n    axis([tmin, tmax, xmin, xmax]);\n    set(gca,'FontName','Arial Cyr','FontSize',12);\n    title('Low of motion {\\phi} = {\\phi}({\\itt})')\n    xlabel('{\\itt}'); ylabel('{\\phi}'); pause\n    % Angular velocity w = w(t)\n    figure % 2\n    comet(t,y(:,2))\n    plot(t,y(:,2),[tmin tmax],[0 0],'k'), grid on\n    axis([tmin, tmax, ymin, ymax]);\n    set(gca,'FontName','Arial','FontSize',12);\n    title('Angular velocity {\\omega} = {\\omega}({\\itt})')\n    xlabel('{\\itt}'); ylabel('{\\omega}'); pause\n    % Coordinate and Velocity\n    figure % 3\n    subplot(2,1,1), plot(t,y(:,1),[tmin tmax],[0 0],'k')\n    grid on, axis([tmin, tmax, xmin, xmax]);\n    set(gca,'FontName','Arial','FontSize',12);\n    title('Low of motion {\\phi} = {\\phi}(t)')\n    subplot(2,1,2), plot(t,y(:,2),[tmin tmax],[0 0],'k')\n    grid on, axis([tmin, tmax, ymin, ymax]);\n    set(gca,'FontName','Arial','FontSize',12);\n    title('Angular velocity {\\omega} = {\\omega}(t)')\n    pause\n    % Phase Plane\n    figure % 4 \n    subplot(1,1,1)\n    comet(y(:,1),y(:,2))\n    plot(y(:,1),y(:,2), [xmin,xmax],[0 0],'k',...\n                  [0 0],[ymin,ymax],'k'), grid on\n    axis([xmin, xmax, ymin, ymax]);         \n    set(gca,'FontName','Arial Cyr','FontSize',12);\n    title(' Phase Plane {\\omega} = {\\omega}({\\phi})')\n    xlabel('{\\phi}'), ylabel('{\\omega}'), pause\n    flag2 = 1;\n    % close all\n    disp(' ');\n    ans = input(' Would you like to continue? (Y/N): ','s');\n    if ans == 'n' | ans == 'N', break, end\nend\n\n%  ***************** End of Program ROT ********************\n", "meta": {"author": "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/SORCE Files/ROT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5972547386241382}}
{"text": "function r8vec_convolution_circ_test ( )\n\n%*****************************************************************************80\n%\n%% R8VEC_CONVOLUTION_CIRC_TEST tests R8VEC_CONVOLUTION_CIRC\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 = 4;\n\n  x = [ 1.0, 2.0, 3.0, 4.0 ];\n  y = [ 1.0, 2.0, 4.0, 8.0 ];\n  z_correct = [ 37.0, 44.0, 43.0, 26.0 ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8VEC_CONVOLUTION_CIRC_TEST\\n' );\n  fprintf ( 1, '  R8VEC_CONVOLUTION_CIRC computes the circular convolution\\n' );\n  fprintf ( 1, '  of two vectors.\\n' );\n\n  r8vec_print ( n, x, '  The factor X:' );\n  r8vec_print ( n, y, '  The factor Y:' );\n\n  z = r8vec_convolution_circ ( n, x, y );\n\n  r8vec_print ( n, z, '  The circular convolution z = xCCy:' );\n\n  r8vec_print ( n, z_correct, '  Correct answer:' );\n\n  return\nend\n", "meta": {"author": "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_convolution_circ_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.5972547351180284}}
{"text": "function [A B X E] = slr_iteration(D, labels, lambda, tau, eta, delta, epsilon, maxIter, maxOut)\n\n% Dec 2014\n%\n% by Jian Lai, jlai1@ntu.edu.sg\n% solve the equation (17) the supervised low rand decomposition in our PAMI paper\n% min ||A||_* + \\lambda ||B||_* + \\tau ||X||_F^2 + \\eta ||E||_1 s.t. D = A + BX + E.\n\n% input\n% D: training data, each column is a atom, with the size m*n\n% labels: the training labels of D, with the size n*1\n% lambda, tau and eta: the balancing parameters in equation (17)\n% delta: the balancing parameter of T in equation (20) and (23)\n% epsilon: the tolerance of the convergent checking\n% maxIter: max iteration within each subproblem\n% maxOut: max iteration of outer loop (defaul value is 4)\n\n% output\n% A: the class-specific dictionary\n% B: the nonclass-specific dictionary\n% X: the coefficient matrix of B\n% E: the error matrix\n\n\n\n\n% input checking\nif nargin < 6\n    error('Too few arguments') ;\nend\n\nif nargin < 7\n    epsilon = 1e-4;\nend\n\nif nargin < 8\n    maxIter = 1000;\nend\n\nif nargin < 9\n    maxIter = 4;\nend\n\n% initializate A_i as (19) in our PAMI paper\nunilabel = unique(labels);\nnumlabel = size(unilabel,2);\nfor classindex = 1:numlabel   \n    classid = unilabel(classindex);\n    Di = D(:,classid==labels);\n    [U S V] = svd(Di, 'econ');\n\tAi{classindex} = U(:, 1) * diag(S(1,1)) * V(:, 1)';    \nend\n\n% initialize of A\nA = [];\nfor classindex = 1:numlabel\n    A = [A Ai{classindex}];\nend\n\n% initialize X to an identity matrix\nX = eye(size(A,2));\n\n% initialize B to a zero matrix\nB = zeros(size(D));\n\nfor outiter = 1:maxOut\n    \n    fprintf('The %d iteration of SLR\\n', outiter);\n    \n    % solve the subproblem (20) in our PAMI paper\n    [B, T] = slr_BT_ialm(D, A, X, lambda, delta, epsilon, maxIter);\n    \n    % solve the subproblem (23) in our PAMI paper\n    [X, T] = slr_XT_ialm(D, A, B, tau, delta, epsilon, maxIter);\n        \n    % solve the subproblem (25) in our PAMI paper\n    [A, E] = slr_AE_ialm(D, B, X, eta, epsilon, maxIter); \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/SDR_SLR_PAMI2014/slr_iteration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5972547336152373}}
{"text": "function  [CQcc, LogP_absCQT, TimeVec, FreqVec, Ures_LogP_absCQT, Ures_FreqVec] = ...\n    cqcc(x, fs, B, fmax, fmin, d, cf, ZsdD)\n\n%   Constant Q cepstral coefficients\n%   Usage:  CQcc = cqcc(x, fs, B, fmax, fmin, d, cf, ZsdD)\n%\n%   Input parameters:\n%         x        : input signal\n%         fs       : sampling frequency\n%         B        : number of bins per octave [default = 96]\n%         fmax     : highest frequency to be analyzed [default = Nyquist frequency]\n%         fmin     : lowest frequency to be analyzed [default = ~20Hz to fullfill an integer number of octave]\n%         d        : number of uniform samples in the first octave [default 16]\n%         cf       : number of cepstral coefficients excluding 0'th coefficient [default 19]\n%         ZsdD     : any sensible combination of the following  [default ZsdD]:\n%                      'Z'  include 0'th order cepstral coefficient\n%                      's'  include static coefficients (c)\n%                      'd'  include delta coefficients (dc/dt)\n%                      'D'  include delta-delta coefficients (d^2c/dt^2)\n%\n%   Output parameters:\n%         CQcc              : constant Q cepstral coefficients (nCoeff x nFea)\n%         LogP_absCQT       : log power magnitude spectrum of constant Q trasform\n%         TimeVec           : time at the centre of each frame [sec]\n%         FreqVec           : center frequencies of analysis filters [Hz]\n%         Ures_LogP_absCQT  : uniform resampling of LogP_absCQT\n%         Ures_FreqVec      : uniform resampling of FreqVec [Hz]\n%\n%   See also:  cqt\n%\n%\n%   References:\n%     M. Todisco, H. Delgado, and N. Evans. A New Feature for Automatic\n%     Speaker Verification Anti-Spoofing: Constant Q Cepstral Coefficients.\n%     Proceedings of ODYSSEY - The Speaker and Language Recognition\n%     Workshop, 2016.\n%\n%     C. Sch\ufffdrkhuber, A. Klapuri, N. Holighaus, and M. D\ufffdfler. A Matlab\n%     Toolbox for Efficient Perfect Reconstruction log-f Time-Frequecy\n%     Transforms. Proceedings AES 53rd Conference on Semantic Audio, London,\n%     UK, Jan. 2014. http://www.cs.tut.fi/sgn/arg/CQT/\n%\n%     G. A. Velasco, N. Holighaus, M. D\ufffdfler, and T. Grill. Constructing an\n%     invertible constant-Q transform with non-stationary Gabor frames.\n%     Proceedings of DAFX11, Paris, 2011.\n%\n%     N. Holighaus, M. D\ufffdfler, G. Velasco, and T. Grill. A framework for\n%     invertible, real-time constant-q transforms. Audio, Speech, and\n%     Language Processing, IEEE Transactions on, 21(4):775-785, April 2013.\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright (C) 2016 EURECOM, France.\n%\n% This work is licensed under the Creative Commons\n% Attribution-NonCommercial-ShareAlike 4.0 International\n% License. To view a copy of this license, visit\n% http://creativecommons.org/licenses/by-nc-sa/4.0/\n% or send a letter to\n% Creative Commons, 444 Castro Street, Suite 900,\n% Mountain View, California, 94041, USA.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Authors: Massimiliano Todisco {todisco [at] eurecom [dot] fr}\n%          Hector Delgado {delgado [at] eurecom [dot] fr}\n%\n% Version: 1.0\n% Date: 22.01.16\n%\n% User are requested to cite the following paper in papers which report \n% results obtained with this software package.\t\n%\n%     M. Todisco, H. Delgado, and N. Evans. A New Feature for Automatic\n%     Speaker Verification Anti-Spoofing: Constant Q Cepstral Coefficients.\n%     Proceedings of ODYSSEY - The Speaker and Language Recognition\n%     Workshop, 2016.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%% CHECK INPUT PARAMETERS\nif nargin < 2\n    warning('Not enough input arguments.'), return\nend\n\n%%% DEFAULT INPUT PARAMETERS\nif nargin < 3; B = 96; end\nif nargin < 4; fmax = fs/2; end\nif nargin < 5; oct = ceil(log2(fmax/20)); fmin = fmax/2^oct; end\nif nargin < 6; d = 16; end\nif nargin < 7; cf = 19; end\nif nargin < 8; ZsdD = 'ZsdD'; end\ngamma = 228.7*(2^(1/B)-2^(-1/B));\n\n%%% CQT COMPUTING\nXcq = cqt(x, B, fs, fmin, fmax, 'rasterize', 'full', 'gamma', gamma);\n\n%%% LOG POWER SPECTRUM\nabsCQT = abs(Xcq.c);\nTimeVec = (1:size(absCQT,2))*Xcq.xlen/size(absCQT,2)/fs;\nFreqVec = fmin*(2.^((0:size(absCQT,1)-1)/B));\nLogP_absCQT = log(absCQT.^2 + eps);\n\n%%% UNIFORM RESAMPLING\nkl = (B*log2(1+1/d));\n[Ures_LogP_absCQT, Ures_FreqVec] = resample(LogP_absCQT,...\n    FreqVec,1/(fmin*(2^(kl/B)-1)),1,1,'spline');\n\n%%% DCT\nCQcepstrum = dct(Ures_LogP_absCQT);\n\n%%% DYNAMIC COEFFICIENTS\nif strfind(ZsdD, 'Z'); scoeff = 1; else scoeff = 2; end\nCQcepstrum_temp = CQcepstrum(scoeff:cf+1,:);\nf_d = 3; % delta window size\nif strcmp(strrep(ZsdD,'Z',''), 'sdD')\n    CQcc = [CQcepstrum_temp; Deltas(CQcepstrum_temp,f_d); ...\n        Deltas(Deltas(CQcepstrum_temp,f_d),f_d)];\nelseif strcmp(strrep(ZsdD,'Z',''), 'sd')\n    CQcc = [CQcepstrum_temp; Deltas(CQcepstrum_temp,f_d)];\nelseif strcmp(strrep(ZsdD,'Z',''), 'sD')\n    CQcc = [CQcepstrum_temp; Deltas(Deltas(CQcepstrum_temp,f_d),f_d)];\nelseif strcmp(strrep(ZsdD,'Z',''), 's')\n    CQcc = CQcepstrum_temp;\nelseif strcmp(strrep(ZsdD,'Z',''), 'd')\n    CQcc = Deltas(CQcepstrum_temp,f_d);\nelseif strcmp(strrep(ZsdD,'Z',''), 'D')\n    CQcc = Deltas(Deltas(CQcepstrum_temp,f_d),f_d);\nelseif strcmp(strrep(ZsdD,'Z',''), 'dD')\n    CQcc = [Deltas(CQcepstrum_temp,f_d); Deltas(Deltas(CQcepstrum_temp,f_d),f_d)];\nend\nend\n\nfunction D = Deltas(x,hlen)\n\n% Delta and acceleration coefficients\n%\n% Reference:\n%   Young S.J., Evermann G., Gales M.J.F., Kershaw D., Liu X., Moore G., Odell J., Ollason D.,\n%   Povey D., Valtchev V. and Woodland P., The HTK Book (for HTK Version 3.4) December 2006.\n\nwin = hlen:-1:-hlen;\nxx = [repmat(x(:,1),1,hlen),x,repmat(x(:,end),1,hlen)];\nD = filter(win, 1, xx, [], 2);\n% D = D(:,hlen+1:(end - hlen));\nD = D(:,hlen*2+1:end);\nD = D./(2*sum((1:hlen).^2));\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/CQCC_v1.0/cqcc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5972547336152373}}
{"text": "classdef SOP_F19 < PROBLEM\n% <single> <real> <expensive/none>\n% Hartman's family\n\n%------------------------------- Reference --------------------------------\n% X. Yao, Y. Liu, and G. Lin, Evolutionary programming made faster, IEEE\n% Transactions on Evolutionary Computation, 1999, 3(2): 82-102.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 1;\n            obj.D = 3;\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            a = [3 10 30;0.1 10 35;3 10 30;0.1 10 35];\n            c = [1;1.2;3;3.2];\n            p = [0.3689 0.1170 0.2673;0.4699 0.4387 0.7470;0.1091 0.8732 0.5547;0.03815 0.5743 0.8828];\n            PopObj = zeros(size(PopDec,1),1);\n            for i = 1 : size(PopDec,1)\n                PopObj(i) = -sum(c.*exp(-sum(a.*(repmat(PopDec(i,:),4,1)-p).^2,2)));\n            end\n        end\n        %% Generate the minimum objective value\n        function R = GetOptimum(obj,N)\n            R = -3.863;\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/Single-objective optimization/Simple SOPs/SOP_F19.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5972547316119186}}
{"text": "function[S] = adaptMedian_colfilt(I, w_max)\n%  \n%  \n\nif nargin < 2\n  w_max = 9;\nend\n\n[Nrows Ncols depth] = size(I);\nS = uint8(zeros(Nrows, Ncols, depth));\n\n\n\n\nfor d = 1:depth,\n\n% Get plane d\nIb = I(:,:,d);\n\n% Initialization\nw = 1;\np = 3;\ncond = uint8(1);    % zero --> noiseless pixel\n\n\nfor l = w+2:2:w_max\n\n\n  Imed = medfilt2(Ib, [p p]);\n  Imin = colfilt(Ib, [p p], 'sliding', @(x) min(x));\n  Imax = colfilt(Ib, [p p], 'sliding', @(x) max(x));\n\n\n  m1 = uint8( ((Imin < Imed) .* (Imed < Imax)) );\n  m2 = uint8( ((Imin < Ib) .* (Ib < Imax)) );\n\n  if(l == w)\n    S(:,:,d) =  m1.*(1-m2).*l;\n  else\n    S(:,:,d) = cond.*( m1.*(1-m2).*l ) + (1-cond).*S(:,:,d);\n  end\n\n  cond = cond.*(1-m1); % pixel that need further evaluation\n\n  p = p+2;\n\nend % _END_ FOR(l)\n\nS(:,:,d) = cond.*(w_max+2) + (1-cond).*S(:,:,d);\n\nend % _END_ FOR(d)\n\nS = double(S);\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/GTF/source/adaptMedian_colfilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5972547286063361}}
{"text": "%% Analyzing Investment Strategies with CVaR Portfolio Optimization in MATLAB\n%\n% Robert Taylor\n% The MathWorks, Inc.\n\n% Copyright (C) 2012 The MathWorks, Inc.\n\n%% Introduction\n\n% This script is a \"superscript\" that organizes the scripts for the webinar \"Analyzing Investment\n% Strategies with CVaR Portfolio Optimization in MATLAB.\" It describes what each script does and\n% shows the order in which the scripts should be examined.\n\n%% Instructions\n\n% The file structure for these scripts has a top-level folder that contains these scripts and should\n% have two folders 'data' and 'source' with data and analytics. To add these folders to the path,\n% start in the folder with the scripts and execute the commands\n\nsetlocalpaths\n\n% The script cvarwebinar_scenarios.m, which simulates scenarios, must be run before subsequent\n% scripts can be run because it generates a file BuyWriteScenarios.mat that is needed for these\n% scripts. The script to generate scenarios can take about one hour on a typical computer and\n% requires that the computer be a 64-bit machine. It creates a 12MB file in the ./data folder. Make\n% sure that the script to generate scenarios is run in the folder that contains this script so that\n% the scenarios file ends up in the correct data folder.\n\n%% Theory\n\n% This script illustrates basic features of covered-call strategies and provides a theoretical\n% analysis of issues regarding slippage due to assignment and re-investment.\n\ncvarwebinar_theory\n\n%% From Theory to Reality\n\n% This script illustrates an event-driven simulation of total returns for uncovered and covered\n% positions based on a single realization of an underlying stock. It moves from the simplicity of\n% theory to the messiness of reality as it models and simulates various contributions to slippage.\n\ncvarwebinar_reality\n\n%% Calibration\n\n% This script is the first of the sequence of scripts to illustrate a complete workflow to analyze a\n% covered-call strategy for a universe of 26 stocks. Given total return price data, this script\n% illustrates maximum likelihood calibration of the assumed geometric Brownian motion process for\n% the universe of stocks.\n\ncvarwebinar_calibration\n\n%% Scenario Generation\n\n% This script is the second of the sequence of scripts that generates scenarios for uncovered and\n% covered positions to be used for subsequent portfolio optimization and analysis. This is the\n% slowest script since it generates scenarios by simulation of investment actions during the course\n% of an investment period.\n\ncvarwebinar_scenarios\n\n%% Normality Tests\n\n% This script is the third of the sequence of scripts that examines the statistical properties of\n% the scenarios. As the probability of early exercise increases during an investment period, the\n% distribution of the log of covered-call returns becomes increasingly non-normal.\n\ncvarwebinar_normality\n\n%% Optimization\n\n% This script is the final of the sequence of scripts that performs several portfolio optimization\n% steps with both CVaR and mean-variance portfolio optimization. The difference in results between\n% the two types of optimization is examined to provide greater insights into the normative\n% implications of covered-call strategies.\n\ncvarwebinar_optimization\n\n%% References\n%\n% # P. Bernstein (1998), _Against the Gods: The Remarkable Story of Risk_, Wiley.\n% # F. Black (1975), \"Fact and Fantasy in the Use of Options,\" _Financial Analysts Journal_, Vol. 31,\n% No. 4, pp. 36-41 and 61-72.\n% # P. Glassermann (1991), _Monte Carlo Methods in Financial Engineering_, Springer.\n% # I. Karatzas and S. Shreve (1991), _Brownian Motion and Stochastic Calculus_, 2nd ed., Springer.\n% # H. Markowitz (1952), \"Portfolio Selection,\" _Journal of Finance_, Vol. 7, No. 1, pp. 77-91.\n% # R. Merton, M. Scholes, and M. Gladstein (1978), \"The Returns and Risk of Alternative Call Option \n% Portfolio Investment Strategies,\" _Journal of Business_, Vol. 51, No. 2, pp. 183-242.\n% # R. T. Rockafellar and S. Uryasev (2002). \"Conditional Value-at-Risk for General Loss\n% Distributions,\" _Journal of Banking and Finance_, Vol. 26, pp. 1443-1471.\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39449-analyzing-investment-strategies-with-cvar-portfolio-optimization/cvarwebinar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.597254727604072}}
{"text": "function G =  getGroupNonOverlapColor(row, col)\n\n\n   % N = (row-2)*(col-2);\n N =  row * col ;\n    g = sparse(zeros(N,1));\n    g = diag(g);\n    groupCount = 0;\n   \n    \n    %% build non-overlapping group\n    for i=2:3:col-1    \n        for j=2:3:row-1  \n            groupCount = groupCount+1;\n            \n            g(groupCount, (i-2)*row+j-1 ) = 1;\n            g(groupCount, (i-2)*row+j   ) = 1;\n            g(groupCount, (i-2)*row+j+1 ) = 1;\n            g(groupCount, (i-1)*row+j-1 ) = 1;\n            g(groupCount, (i-1)*row+j   ) = 1;\n            g(groupCount, (i-1)*row+j+1 ) = 1;             \n            g(groupCount, i*row+j-1 ) = 1;\n            g(groupCount, i*row+j   ) = 1;\n            g(groupCount, i*row+j+1 ) = 1;      \n\n        end\n    end\n   \n    g= g';\n   \n \n    g =g(:, 1:groupCount);\n    \n    G = sparse(3*N, 3*groupCount);\n\n    \n    G(1:N, 1:groupCount) = g;\n    G(N+1:2*N, groupCount+1:2*groupCount) =g;\n    G(2*N+1:3*N, 2*groupCount+1:3*groupCount) =g;\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/algorithms/st/GOSUS/getGroupNonOverlapColor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5971857254192061}}
{"text": "function [LE,J]=CylNeumanLePerp_PGSE(d, R, G, delta, smalldel, roots)\n% Substrate: Parallel, impermeable cylinders with one radius in an empty\n%            background.\n% Pulse sequence: Pulsed gradient spin echo\n% Signal approximation: Gaussian phase distribution.\n%\n% [LE,J] = CylNeumanLePerp_PGSE(d, R, G, delta, smalldel, roots)\n%\n% returns the log signal attenuation in perpendicular direction (LePerp) for\n% EACH RADIUS specified in R according to the Neuman model and the Jacobian J\n% of LePerp with respect to the parameters.\n%\n% The Jacobian DOES NOT include derivates with respect to the fibre direction.\n%\n% d is the diffusivity of the material inside the cylinders.\n%\n% R is the list of the radii of the cylinders. It has size [1 m] where m is the\n% number of radii.\n%\n% G, delta and smalldel are the gradient strength, pulse separation and\n% pulse length of each measurement in the protocol.  Each has\n% size [N 1].\n%\n% roots contains solutions to the Bessel function equation from function\n% BesselJ_RootsCyl.\n%\n% author: Daniel C Alexander (d.alexander@ucl.ac.uk)\n%         Gary Hui Zhang     (gary.zhang@ucl.ac.uk)\n%\n\n% When R=0, no need to do any calculation\nif (R == 0.00)\n    LE = zeros(size(G,1), size(R,2));\n    J = zeros([size(LE), 2]);\n\t J(:,:,:) = 0;\n    return;\nend\n\n% Check the roots array is correct\nif(abs(roots(1) - 1.8412)>0.0001)\n    error('Looks like the roots array is wrong.  First value should be 1.8412, but is %f', roots(1));\nend\n\n% Radial wavenumbers\nGAMMA = 2.675987E8;\n\n% number of gradient directions, i.e. number of measurements\nl_q=size(G,1);\nl_a=numel(R);\nk_max=numel(roots);\n\nR_mat=repmat(R,[l_q 1]);\nR_mat=R_mat(:);\nR_mat=repmat(R_mat,[1 1 k_max]);\nR_matSq=R_mat.^2;\n\nroot_m=reshape(roots,[1 1 k_max]);\nalpha_mat=repmat(root_m,[l_q*l_a 1 1])./R_mat;\namSq=alpha_mat.^2;\namP6=amSq.^3;\n\ndeltamx=repmat(delta,[1,l_a]);\ndeltamx_rep = deltamx(:);\ndeltamx_rep = repmat(deltamx_rep,[1 1 k_max]);\n\nsmalldelmx=repmat(smalldel,[1,l_a]);\nsmalldelmx_rep = smalldelmx(:);\nsmalldelmx_rep = repmat(smalldelmx_rep,[1 1 k_max]);\n\nGmx=repmat(G,[1,l_a]);\nGmxSq = Gmx.^2;\n\n% Perpendicular component (Neuman model)\nsda2 = smalldelmx_rep.*amSq;\nbda2 = deltamx_rep.*amSq;\nemdsda2 = exp(-d*sda2);\nemdbda2 = exp(-d*bda2);\nemdbdmsda2 = exp(-d*(bda2 - sda2));\nemdbdpsda2 = exp(-d*(bda2 + sda2));\n\nsumnum1 = 2*d*sda2;\n% the rest can be reused in dE/dR\nsumnum2 = - 2 + 2*emdsda2 + 2*emdbda2;\nsumnum2 = sumnum2 - emdbdmsda2 - emdbdpsda2;\nsumnum = sumnum1 + sumnum2;\n\nsumdenom = d^2*amP6.*(R_matSq.*amSq - 1);\n\n% Check for zeros on top and bottom\n%sumdenom(find(sumnum) == 0) = 1;\nsumterms = sumnum./sumdenom;\n\ntestinds = find(sumterms(:,:,end)>0);\ntest = sumterms(testinds,1)./sumterms(testinds,end);\nif(min(test)<1E4)\n    warning('Ratio of largest to smallest terms in Neuman model sum is <1E4.  May need more terms.');\nend\n\ns = sum(sumterms,3);\ns = reshape(s,[l_q,l_a]);\nif(min(s)<0)\n    warning('Negative sums found in Neuman sum.  Setting to zero.');\n    s(find(s<0))=0;\nend\n\nLE = -2*GAMMA^2*GmxSq.*s;\n\n% Compute the Jacobian matrix\nif(nargout>1)\n    \n    % dLE/dd\n    sumnumD = 2*sda2;\n    sumnumD = sumnumD - 2*sda2.*emdsda2;\n    sumnumD = sumnumD - 2*bda2.*emdbda2;\n    sumnumD = sumnumD + (bda2 - sda2).*emdbdmsda2;\n    sumnumD = sumnumD + (bda2 + sda2).*emdbdpsda2;\n    sumtermsD = sumnumD./sumdenom;\n\n    sD = sum(sumtermsD,3);\n    sD = reshape(sD,[l_q,l_a]);\n\n    dLEdd = -2*GAMMA^2*GmxSq.*(sD - 2*s/d);\n\n    % dLE/dR\n    sumtermsR = (6*sumterms - 2*d*sumtermsD)./R_mat;\n    \n    sR = sum(sumtermsR,3);\n    sR = reshape(sR,[l_q,l_a]);\n\n    dLEdr = -2*GAMMA^2*GmxSq.*sR;\n\n    % Construct the jacobian matrix.\n    J = zeros([size(LE), 2]);\n    J(:,:,1) = dLEdd;\n    J(:,:,2) = dLEdr;\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/CylNeumanLePerp_PGSE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5971857227795617}}
{"text": "function lp = wishpdfln(X,a,B,inverse)\n%WISHPDFLN    Logarithm of Wishart probability density function.\n%  See WISHPDF for argument description.\n\n% Written by Tom Minka\n% (c) Microsoft Corporation. All rights reserved.\n\nif nargin < 3\n  B = [];\nend\nif nargin < 4\n  inverse = 0;\nend\n\nif inverse\n  X = inv(X);\nend\nif isempty(B)\n  XB = X;\n  logDetB = 0;\nelse\n  XB = X*B;\n  logDetB = logdet(B);\nend\nd = rows(X);\nd2 = (d+1)/2;\nif inverse\n  d2 = -d2;\nend\nlogDetXB = (a-d2)*logdet(XB);\nlp = logDetXB - trace(XB) + d2*logDetB - gammaln(a,d);\n", "meta": {"author": "tminka", "repo": "lightspeed", "sha": "e65560c5aa3aae947a62dd662a6444cdfa96fc4f", "save_path": "github-repos/MATLAB/tminka-lightspeed", "path": "github-repos/MATLAB/tminka-lightspeed/lightspeed-e65560c5aa3aae947a62dd662a6444cdfa96fc4f/wishpdfln.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5971857227795616}}
{"text": "function pred = knnpred2(Xtest,X,class,class_exp,K,dist_type,pret_type)\n\n% prediction of new samples with calculated model\n%\n% pred = knnpred(Xtest,X,class,K,dist_type,pret_type)\n%\n% ------------ INPUT ---------------------------------------------------\n% Xtest:        dataset to be predicted [n_test x p] n objects, p variables\n% X:            training data matrix (n x p)\n% class:        training class vector (n x 1)\n% K:            number of neighbors\n% dist_type:    'euclidean' Euclidean distance\n%               'mahalanobis' Mahalanobis distance\n%               'cityblock' City Block metric\n%               'minkowski' Minkowski metric\n%               'sm' Sokal-Michener \n%               'jt' Jaccard Tanimoto\n%               'gle' Gleason-Dice\n%               'ct4' Consonni-Todeschini\n%               'ac' Austin-Colwell\n% pret_type:    'cent' cenering\n%               'scal' variance scaling\n%               'auto' for autoscaling (centering + variance scaling)\n%               'rang' range scaling (0-1)\n%               'fp'   fingerprints\n%\n% ------------ OUTPUT --------------------------------------------------\n% pred is a structure conyaining\n% class_pred    predicted class vector [n_test x 1]\n% neighbors     list of k neighbors for each predicted sample [n_test x k]\n% \n% version 1.0 - september 2009\n% Davide Ballabio\n% Milano Chemometrics and QSAR Research Group\n% www.disat.unimib.it/chm\n\n% version 2.0 - February 2012\n% Kamel Mansouri\n% Milano Chemometrics and QSAR Research Group\n% www.disat.unimib.it/chm\n\n% data check\nif length(class)~=size(X,1)\n    disp('the class input should be for the training set')\n    %class_tr=input('class tr');\n    %class=evalin(WS,);\n    %keyboard\nend\n\n[n,p] = size(Xtest);\n[X_scal_train,param] = data_pretreatment(X,pret_type);\nX_scal = test_pretreatment(Xtest,param);\nXd = [X_scal;X_scal_train];\n% D = pdist(Xd,model.set.dist_type);\n% D = squareform(D);\nD = knn_calc_dist(X_scal_train,X_scal,dist_type,pret_type);\nneighbors = zeros(n,K);\nw=zeros(n,K);\nclass_exp(find(isnan(class_exp)))=class(find(isnan(class_exp)));\nfor i=1:n\n    D_in = D(i,:);\n    [d_tmp,n_tmp] = sort(D_in);\n    neighbors(i,:) = n_tmp(1:K);\n    d_neighbors = d_tmp(1:K);\n    if d_neighbors(1)<1e-5 %&& d_neighbors(2)>d_neighbors(1)\n        d_neighbors(1)=0;\n    end\n    if d_neighbors(1)==0 %&& isnan(class_exp(neighbors(i,1)))%&& d_neighbors(2)~=0\n        class_calc(i) = knnclass2(class(neighbors(i,:)),d_neighbors,max(class),K);\n        class_calc_weighted(i)=class(neighbors(i,1));\n        w(i,1)=1;\n    else\n        %class(find(~isnan(class_exp)))=class_exp(find(~isnan(class_exp)));\n        class_calc(i) = knnclass2(class_exp(neighbors(i,:)),d_neighbors,max(class_exp),K);\n        [yc(i),class_calc_weighted(i),w(i,:)] = nnrcalcy2(class_exp(neighbors(i,:)),d_neighbors,K);\n        class_calc_weighted(i)=round(class_calc_weighted(i));\n    end\n    \n    dc(i,:)=d_neighbors;\nend\n\npred.neighbors  = neighbors;\npred.class_pred = class_calc';\npred.class_pred_w = class_calc_weighted';\npred.w=w;\npred.D=D;\npred.dc=dc;", "meta": {"author": "kmansouri", "repo": "OPERA", "sha": "fcbe8024c01f49cd9498187c0ff8c5c45d6dc833", "save_path": "github-repos/MATLAB/kmansouri-OPERA", "path": "github-repos/MATLAB/kmansouri-OPERA/OPERA-fcbe8024c01f49cd9498187c0ff8c5c45d6dc833/OPERA_Source_code/knnpred2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382004, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5971857198298844}}
{"text": "function A = hmf(A,n)\n\n%HMF Hybrid median filtering.\n%   B = HMF(A,N) performs hybrid median filtering of the matrix A using a\n%   NxN box. Hybrid median filtering preserves edges better than a NxN\n%   square kernel-based median filter because data from different spatial\n%   directions are ranked separately. Three median values are calculated in\n%   the NxN box: MR is the median of horizontal and vertical R pixels, and\n%   MD is the median of diagonal D pixels. The filtered value is the median\n%   of the two median values and the central pixel C: median([MR,MD,C]).\n%   For N = 5:\n%        |D  *  R  *  D|\n%        |*  D  R  D  *|\n%        |R  R  C  R  R|\n%        |*  D  R  D  *|\n%        |D  *  R  *  D|\n%\n%   B = HMF(A) uses N = 5 (default value).\n%\n%   A can be a 2-D array or an RGB image. If A is an RGB image, hybrid\n%   median filtering is performed in the HSV color space.\n%\n%   Notes\n%   -----\n%   1) N must be odd. If N is even then N is incremented by 1.\n%   2) The Image Processing Toolbox is required.\n%   3) If the function NANMEDIAN exists (Statistics Toolbox), NaN are\n%      treated as missing values and are ignored.\n%\n%   Examples\n%   --------\n%     % -- original grayscale image --\n%     I = imread('eight.tif');\n%     % noisy image\n%     J = imnoise(I,'salt & pepper',0.03);\n%     % hybrid median filtering\n%     K = hmf(J);\n%     % figures\n%     subplot(121),imshow(J),subplot(122),imshow(K)\n%     \n%     % -- original RGB image --\n%     [I,map] = imread('trees.tif');\n%     I = ind2rgb(I,map);\n%     % noisy image\n%     J = imnoise(I,'salt & pepper',0.02);\n%     % hybrid median filtering (using a 9x9 box)\n%     K = hmf(J,9);\n%     % figures\n%     subplot(121),imshow(J),subplot(122),imshow(K)\n% \n%   See also MEDFILT2, MEDFILT2RGB, MEDFILT3, COLFILT\n%\n%   -- Damien Garcia -- 2007/08, revised 2010/02 \n\nerror(nargchk(1,2,nargin));\nif nargin==1, n = 5; end\n\nif ~isscalar(n) || n<0, n = 5; end\n\n% --- n must be odd. If not then n = n+1\nn = round(n);\nif rem(n+1,2)~=0, n = n+1; end\n\n% --- Do we have an RGB image?\n% RGB images can be only be 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\n   if 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\n         isRGB = (min(A(:))>=0 && max(A(:))<=1);\n      end\n   end\nend\n% ---- end of isrgb ----\n\nassert(isRGB | ndims(A)==2,...\n    'The input must be a 2-D array or an RGB image.')\n\nclassA = class(A);\n\n% --- If the input is an RGB image, HMF is used in the HSV color space\nif isRGB\n    A = rgb2hsv(A);\n    for k = 1:3, A(:,:,k) = hmf(A(:,:,k),n); end\n    A = hsv2rgb(A);\n    % HSV2RGB returns a double: change the class if necessary\n    switch classA\n        case 'uint8'\n            A = uint8(A*255);\n        case 'uint16'\n            A = uint16(A*65535);\n        case 'single'\n            A = single(A);\n    end\n    return\nend\n\n% --- Plus & Cross masks\nPlus = false(n,n);\nPlus((n+1)/2,:) = true;\nPlus(:,(n+1)/2) = true;\nPlus = Plus(:);\nCross = false(n,n);\nCross((1:n)+n*(0:n-1)) = true;\nCross((1:n)+n*((n-1):-1:0)) = true;\nCross = Cross(:);\n\n\n%% --- Hybrid median filtering\n\n% Note: NANMEDIAN is used if this function exists (Statistics Toolbox)\nexistNaNmedian = exist('nanmedian','file');\n\n% --- the COLFILT function zero-pads! => replicate boundaries\nA = padarray(A,[(n-1)/2 (n-1)/2],'replicate');\n\nM1 = colfilt(A,[n n],'sliding',@CrossMedian);\nM2 = colfilt(A,[n n],'sliding',@PlusMedian);\nif existNaNmedian\n    A = nanmedian(cat(3,A,M1,M2),3);\nelse\n    A = median(cat(3,A,M1,M2),3);\nend\n\n% remove the borders that were added by PADARRAY\nA = A((n+1)/2:end-(n-1)/2,(n+1)/2:end-(n-1)/2);\n\nfunction CM = CrossMedian(X)\n    ncol = size(X,2);\n    I = repmat(Cross,[1 ncol]);\n    X = reshape(X(I),[2*n-1 ncol]);\n    if existNaNmedian\n        CM = nanmedian(X);\n    else\n        CM = median(X);\n    end\nend\n\nfunction PM = PlusMedian(X)\n    ncol = size(X,2);\n    I = repmat(Plus,[1 ncol]);\n    X = reshape(X(I),[2*n-1 ncol]);\n    if existNaNmedian\n        PM = nanmedian(X);\n    else\n        PM = median(X);\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/25825-hybrid-median-filtering/hmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5971303147922958}}
{"text": "function plot_circle(q,r,options)\n\n% plot_circle - display a collecion of circles\n%\n%   plot_circle(q,r,options);\n%\n%   Copyright (c) 2008 Gabriel Peyre\n\noptions.null = 0;\ndraw_centers = getoptions(options, 'draw_centers', 1);\ncenter_width = getoptions(options, 'center_width', 20);\nnpoints_circle = getoptions(options, 'npoints_circle', 60)+1;\ncolor_circle = getoptions(options, 'color_circle', 'b');\ncolor_center = getoptions(options, 'color_center', 'b');\n\nif draw_centers\nhh = plot(q(1,:), q(2,:), [color_center '.']);\nend\nset(hh, 'MarkerSize', center_width);\n% draw circles\nt = linspace(0,2*pi,npoints_circle);\nfor i=1:length(r)\n    plot( sin(t)*r(i)+q(1,i), cos(t)*r(i)+q(2,i), color_circle );\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_misc/plot_circle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5971303094064588}}
{"text": "function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu,ww)\n%function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)\n% This algorithm goes for accuracy without worrying about memory requirements.\n% ydata:   dependent variable data matrix\n% xdata:   exogenous variable data matrix\n% lags:    number of lags\n% breaks:  rows in ydata and xdata after which there is a break.  This allows for\n%          discontinuities in the data (e.g. war years) and for the possibility of\n%          adding dummy observations to implement a prior.  This must be a column vector.\n%          Note that a single dummy observation becomes lags+1 rows of the data matrix,\n%          with a break separating it from the rest of the data.  The function treats the \n%          first lags observations at the top and after each \"break\" in ydata and xdata as\n%          initial conditions. \n% lambda:  weight on \"co-persistence\" prior dummy observations.  This expresses\n%          belief that when data on *all* y's are stable at their initial levels, they will\n%          tend to persist at that level.  lambda=5 is a reasonable first try.  With lambda<0,\n%          constant term is not included in the dummy observation, so that stationary models\n%          with means equal to initial ybar do not fit the prior mean.  With lambda>0, the prior\n%          implies that large constants are unlikely if unit roots are present.\n% mu:      weight on \"own persistence\" prior dummy observation.  Expresses belief\n%          that when y_i has been stable at its initial level, it will tend to persist\n%          at that level, regardless of the values of other variables.  There is\n%          one of these for each variable.  A reasonable first guess is mu=2.\n%      The program assumes that the first lags rows of ydata and xdata are real data, not dummies.\n%      Dummy observations should go at the end, if any.  If pre-sample x's are not available,\n%      repeating the initial xdata(lags+1,:) row or copying xdata(lags+1:2*lags,:) into \n%      xdata(1:lags,:) are reasonable subsititutes.  These values are used in forming the\n%      persistence priors.\n\n% Original file downloaded from:\n% http://sims.princeton.edu/yftp/VARtools/matlab/rfvar3.m\n\nif nargin<7\n   scale_ = 0;\nelse\n    % correct for heteroskedasticity\n    scale_=1;\nend\n\n[T,nvar] = size(ydata);\nnox = isempty(xdata);\nif ~nox\n    [T2,nx] = size(xdata);\nelse\n    T2 = T;\n    nx = 0;\n    xdata = zeros(T2,0);\nend\n% note that x must be same length as y, even though first part of x will not be used.\n% This is so that the lags parameter can be changed without reshaping the xdata matrix.\nif T2 ~= T, error('Mismatch of x and y data lengths'),end\nif nargin < 4\n    nbreaks = 0;\n    breaks = [];\nelse\n    nbreaks = length(breaks);\nend\nbreaks = [0;breaks;T];\nsmpl = [];\nfor nb = 1:nbreaks+1\n    smpl = [smpl;[breaks(nb)+lags+1:breaks(nb+1)]'];\nend\nTsmpl = size(smpl,1);\nX = zeros(Tsmpl,nvar,lags);\nfor is = 1:length(smpl)\n    X(is,:,:) = ydata(smpl(is)-(1:lags),:)';\nend\nX = [X(:,:) xdata(smpl,:)];\ny = ydata(smpl,:);\n\n% rescale if heteroskedasticity corrected\nif scale_ ==1\n    ww = [ww; ones(length(y)-length(ww),1) ];\n    y = y./ repmat(ww,1,size(y,2)) ;\n    X = X ./ repmat(ww,1,size(X,2));    \nend\n% Everything now set up with input data for y=Xb+e \n\n% Add persistence dummies\nif lambda ~= 0 || mu > 0\n    ybar = mean(ydata(1:lags,:),1);\n    if ~nox\n        xbar = mean(xdata(1:lags,:),1);\n    else\n        xbar = [];\n    end\n    if lambda ~= 0\n        if lambda>0\n            xdum = lambda*[repmat(ybar,1,lags) xbar];\n        else\n            lambda = -lambda;\n            xdum = lambda*[repmat(ybar,1,lags) zeros(size(xbar))];\n        end\n        ydum = zeros(1,nvar);\n        ydum(1,:) = lambda*ybar;\n        y = [y;ydum];\n        X = [X;xdum];\n    end\n    if mu>0\n        xdum = [repmat(diag(ybar),1,lags) zeros(nvar,nx)]*mu;\n        ydum = mu*diag(ybar);\n        X = [X;xdum];\n        y = [y;ydum];\n    end\nend\n\n% Compute OLS regression and residuals\n[vl,d,vr] = svd(X,0);\ndi = 1./diag(d);\nB = (vr.*repmat(di',nvar*lags+nx,1))*vl'*y;\nu = y-X*B;\nxxi = vr.*repmat(di',nvar*lags+nx,1);\nxxi = xxi*xxi';\n\nvar.B = B;\nvar.u = u;\nvar.xxi = xxi;\nvar.y   = y;\nvar.X   = X;\n", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/bvartools/rfvar3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579722, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5971303067826159}}
{"text": "function [Nm] = ftlb2Nm(ftlb)\n% Convert energy or work from foot-pounds to newtons-meters.\n% Chad A. Greene 2012\nNm = ftlb*1.3558179;", "meta": {"author": "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/ftlb2Nm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5971302988189863}}
{"text": "function x_stdft = stdft(x, N, K, N_fft)\n\nframes      = 1:K:(length(x)-N);\nx_stdft     = zeros(length(frames), N_fft);\n\nw           = ml_hanning(N);\nx           = x(:);\n\nfor i = 1:length(frames)\n    ii              = frames(i):(frames(i)+N-1);\n\tx_stdft(i, :) \t= fft(x(ii).*w, N_fft);\nend\n", "meta": {"author": "mpariente", "repo": "pystoi", "sha": "9ff1cfa743d59b50f1bd35c21c2e8686de6ac026", "save_path": "github-repos/MATLAB/mpariente-pystoi", "path": "github-repos/MATLAB/mpariente-pystoi/pystoi-9ff1cfa743d59b50f1bd35c21c2e8686de6ac026/tests/octave/stdft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5971302935252498}}
{"text": "function [Dimg,D,X,err,Z] = perform_dictionary_signature_learning(Y, k, options)\n\n% perform_dictionary_signature_learning - compute an image signature\n%\n%   [Dimg,D,X,err,options.Z] = perform_dictionary_signature_learning(Y, k, w, options);\n%\n%   The algorithm is described in\n%       M. Aharon and M. Elad, \n%       \" Sparse and Redundant Modeling of Image Content Using an Image-Signature-Dictionary\", \n%       Submitted.\n%\n%   Y is a set of exemplar, each Y(:,i)=p(:) is a w*w vector where p should \n%       be some 2D patch of size (w,w) extracted from some image(s).\n%   k is the width of the dictionary signature.\n%\n%   The number of iterations is options.niter.\n%   The sparse coder used is set in options.sparse_coder to either 'omp' or\n%       'mp'.\n%\n%   Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\n\n% width of the patches\nww = size(Y,1);\nw = sqrt(ww);\n% number of exemplar\nm = size(Y,2);\nd = k;\ndd = d^2; % number of atoms in the dictionary\nkk = k^2;\n\nif m<2*dd\n    warning('You should increase the number of exemplars.');\nend\n\n% option for OMP\nif not(isfield(options, 'nbr_max_atoms'))\n    options.nbr_max_atoms = 4;\nend\nif not(isfield(options, 'use_mex'))\n    options.use_mex = 1;\nend\n\nDimg = getoptions(options, 'Dimg', randn(k));\nniter = getoptions(options, 'niter', 40);\nuse_cg = getoptions(options, 'use_cg', 1);\noptions.niter_max = getoptions(options, 'niter_cg', 10);\nsparse_coder = getoptions(options, 'sparse_coder', 'omp');\n\nDimg = Dimg/sqrt( sum(Dimg(:).^2) );\n\nif isfield(options, 'strict_sparsity')\n    options.nbr_atoms_max = options.strict_sparsity;\nend\n\n% remove mean\nmu = sum(Y);\nY = Y - repmat( mu/ww, [ww 1] );\n\n% compute the dictionary extraction sparse matrix\nif isfield(options, 'Z')\n    Z = options.Z;\nelse\n    Z = sparse(ww*dd,kk);\n    num = 0;\n    for x=1:d\n        for y=1:d\n            num = num+1;\n            selx = x:x+w-1;\n            sely = y:y+w-1;\n            selx = mod(selx-1,k)+1;\n            sely = mod(sely-1,k)+1;\n            [Ya,Xa] = meshgrid(sely,selx);\n            sel = Xa(:) + k*(Ya(:)-1);\n            Z( (1:ww)' + (num-1)*ww + (sel-1)*dd*ww ) = 1;\n        end\n    end\nend\nerr = []; Dimg = Dimg(:);\nfor i=1:niter\n    disp(['--> Iteration ' num2str(i) '/' num2str(niter) '.']);  \n    % extract dictionary and precompute the matrices\n    D = reshape( Z*Dimg, ww, dd);\n    % remove zero component and normalize\n    D = D - repmat( mean(D), [ww 1] );\n    D = D ./ repmat( sqrt( sum(D.^2) ), [ww 1] );\n    % sparse coding\n    disp('-> Sparse coding.');\n    if strcmp(sparse_coder, 'omp')\n        X = perform_omp(D,Y,options);\n    else\n        X = perform_mp(D,Y,options);\n    end\n    X = full(X);\n    err(end+1) = norm(Y-D*X, 'fro');\n    % update dictionary\n    if not(use_cg)\n        % pseudo inverion\n        D = Y * pinv(X);\n    else\n        options.x = D';\n        [D,err1] = perform_conjugate_gradient(X*X',X*Y',options);\n        D = D';\n    end\n    % reconstruct\n    Dimg = 1/ww * Z'*D(:);\nend\nDimg = reshape(Dimg,k,k);\nD = reshape( Z*Dimg(:), ww, dd);\nD = D - repmat( mean(D), [ww 1] );\nD = D ./ repmat( sqrt( sum(D.^2) ), [ww 1] );\n\n% add the low pass DC\nD = [ones(ww,1)/sqrt(ww) D];\nX = [mu/sqrt(ww); X];", "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_dictionary_signature_learning.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5971302935252498}}
{"text": "function cout=comp_irdgtiii(cin,a,M)\n%COMP_IRDGTIII  Compute inverse real DGT type III.\n% \n%   This is a computational routine. Do not call it\n%   directly.\n\n%   AUTHOR : Peter L. S\u00f8ndergaard\n\nN=size(cin,1)/M;\nW=size(cin,2);\nL=N*a;\n\ncin=reshape(cin,M,N,W);\n\nMhalf=floor(M/2);\n\ncout=zeros(M,N,W,assert_classname(cin));\n\nfor m=0:Mhalf-1\n  cout(m+1,:,:)=1/sqrt(2)*(cin(2*m+1,:,:)-i*cin(2*m+2,:,:));\n  cout(M-m,:,:)=1/sqrt(2)*(cin(2*m+1,:,:)+i*cin(2*m+2,:,:));\nend;\n\nif mod(M,2)==1\n  cout((M+1)/2,:,:)=cin(M,:,:);\nend;\n\n\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_irdgtiii.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5971022678524573}}
{"text": "%% Check rate of convergence for 3D H1 interface problem\n%     -div(A grad u)  = f,    x\\in \\Omega\n%      where A is a piecewise constant on Omega^+ and Omega^-.\n%\n% Domain: Rectangular domain: [xmin,xmax] X [ymin,ymax] X [zmin,zmax]\n% Mesh: Cartesian triangular mesh.\n% Method: VIFE\n\n\n%% Geometry and Boundary Conditions\n%clear\n%close all\n%clc\n\n%path(pathdef)\naddpath(genpath(pwd),'-begin');\nrmpath(genpath('./.git'));\nrmpath(genpath('./docs'));\nsavepath;\n\ndomain = [-1,1,-1,1,-1,1];\nbc = [1,1,1,1,1,1]; % Dirichelet BC\n\n%% Finite Element Type\nfemtype = 'P1';\ndisp(['FEM Type =  Conforming ', femtype]);\n\n%% Initial Partition\nnx0 = 10;\nny0 = nx0;\nnz0 = nx0;\n\n%% Task\nshowErr = 0;\nshowMesh = 0;\ncomputErr = 1;\n\n%% PDE\ntest = 5;\nswitch test\n    case 0\n        pde = poissonNonPoly3D;\n    case 1 % circular interface\n        %r = pi/5; bm = 1; bp = pi/(2*r^2);\n        r = sqrt(pi/2); bm = 1; bp = pi/(2*r^2);domain = [-2,2,-2,2,-2,2];\n        x0 = 0; y0 = 0; z0 = 0; rx = r; ry = r; rz = r;\n        pde = elli3DcircIntf(bm,bp,r,x0,y0,z0,rx,ry,rz);\n    case 2 % orthotorus interface\n        domain = [-1.2,1.2,-1.2,1.2,-1.2,1.2];\n        bm = 1; bp = 1;\n        rx = 1; ry = 0.075; rz = 3;\n        pde = elli3DorthocircIntf(bm,bp,rx,ry,rz);\n    case 3 % line interface\n        bm = 1; bp = 10;\n        rx = 1; ry = 0; rz = 0; cx = pi/10; cy = 0; cz = 0;\n        cm = 1; cp = 1; a = 1;\n        pde = elli3DlinIntf(bm,bp,cx,cy,cz,rx,ry,rz,a,cm,cp);\n    case 4 % line interface but with zero boundary conditions\n        bm = 1; bp = 10^(2); delta = pi/10; % delta can not be -1,1\n        pde = elli3DlinIntf2(bm,bp,delta);\n    case 5 % circular interface\n        r = pi/4; bm = 1; bp = 10; domain = [-1,1,-1,1,-1,1];\n        x0 = 0; y0 = 0; z0 = 0;\n        pde = elli3DcircIntf5(bm,bp,r,x0,y0,z0);\n    case 6 % circular interface\n        bm = 1; bp = 10; domain = [-1.3,1.3,-1.3,1.3,-1.3,1.3];\n        x1 = -0.3; y1 = 0; z1 = 0; r11 = pi/5; r12 = 0.2;\n        x2 =  0.3; y2 = 0; z2 = 0; r21 = pi/5; r22 = 0.2;\n        pde = elli3DtorusTwin(bm,bp,x1,y1,z1,r11,r12,x2,y2,z2,r21,r22);\nend\n\n%% Max Iteration\nmaxIt = 4;\ntime = zeros(9,maxIt);\nerror = zeros(maxIt,4);\nratio = zeros(maxIt,4);\n\nfor i = 1:maxIt\n    \n    %% 1. Generate Mesh\n    tic\n    nx = nx0 + 10*(i-1); h = (domain(2) - domain(1))/nx;\n    ny = ny0 + 10*(i-1);\n    nz = nz0 + 10*(i-1);\n    time(1,i) = nx;\n    disp(' ')\n    disp('**************************************************************************************')\n    disp(['Partition =  ',int2str(nx),' X ',int2str(ny),' X ',int2str(nz)]);\n    disp(' ')\n    \n    mesh = genMesh3D(domain, nx, ny, nz);\n    mesh = enrichMesh3D(mesh,1); % Mesh detail level = 2 (for PPIFE).\n    disp(['number of element =  ', int2str(length(mesh.t))]);    \n    mesh = genIntfMesh3D(mesh,pde.intf);\n    disp(['number of interface element =  ', int2str(-min(mesh.tLoc)),...\n        ', is ', num2str(100*-min(mesh.tLoc)/length(mesh.t)), '% of all elements']);\n    time(2,i) = toc;\n    \n    tic\n    fem = genFEM3D(mesh,femtype,bc);\n    disp(['number of DoF =  ', int2str(length(fem.p))]);\n    time(3,i) = toc;\n    \n    %% 2. Generate FEMI data including IFE functions and their matrices\n    tic\n    meshI = genIVmesh(mesh);\n    time(4,i) = toc;\n    length(unique(union(union(meshI.tface(:,1),meshI.tface(:,2)),meshI.tface(:,3))))\n    \n    tic\n    option.mass = 0; % generate mass matrix\n    option.rhs = 1;\n    femI = genP1VIFEM3D(meshI,mesh,pde,option);\n    time(5,i) = toc;\n    \n    %% 3. Assemble Matrix\n    tic\n    disp(' '); disp('Start Assembling Matrix');\n    option.mass = 0; % generate mass matrix\n    matrix = genMatVIFE3D(pde,mesh,fem,meshI,femI);\n    time(6,i) = toc;\n    \n    %% 4. Solve the linear system Au = f\n    tic\n    disp(' ')\n\n    disp('Start Solving Linear System: using PCG with ichol precond');\n    %L = ichol(matrix.A);\n    alpha = 10;\n    L = ichol(matrix.A,struct('type','ict','droptol',1e-3,'diagcomp',alpha));\n    [u,flag,relres,iter,resvec] = pcg(matrix.A,matrix.f,1e-8,1000,L,L');\n    \n    time(7,i) = toc;\n    tu = matrix.tu;\n    uh = tu; %uh(matrix.mapper) = u;\n    \n    %% 5. Postprocess: Calculating Errors\n    tic\n    errND = max(abs(uh - tu)); % Error on nodes\n    err.nd = errND; err.inf = 0; err.l2 = 0; err.h1 = 0;\n    if computErr == 1\n        disp(' ');  disp('Start computing error in Inf norm');\n        eNorm = 'inf';\n        errInfN = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);\n        eNorm = 'L2'; disp(['Start computing error in ',eNorm,'  norm']);\n        errL2 = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);\n        eNorm = 'H1x'; disp(['Start computing error in ',eNorm,' norm']);\n        errH1x = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);\n        eNorm = 'H1y'; disp(['Start computing error in ',eNorm,' norm']);\n        errH1y = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);\n        eNorm = 'H1z'; disp(['Start computing error in ',eNorm,' norm']);\n        errH1z = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);\n        \n        disp(' ')\n        err.inf = max([errND,errInfN]);\n        err.l2 = errL2;\n        err.h1 = sqrt(errH1x^2+errH1y^2+errH1z^2);\n    end\n    time(8,i) = toc;\n    time(9,i) = 1e6*sum(time(2:8,i))/length(mesh.t);\n    error(i,1) = errND; error(i,2) = err.inf;\n    error(i,3) = err.l2; error(i,4) = err.h1;\n    \n    %% 6: Display Output\n    disp(' ')\n    disp('Errors')\n    disp('Node        Inf norm    L2 norm     H1 norm')\n    formatSpec = '%6.4e  %6.4e  %6.4e  %6.4e\\n';\n    fprintf(formatSpec, err.nd, err.inf, err.l2, err.h1)\n    \n    if i > 1\n        format short\n        rNd = log(err0.nd/err.nd)./log(h0/h);\n        rInf = log(err0.inf/err.inf)./log(h0/h);\n        rL2 = log(err0.l2/err.l2)./log(h0/h);\n        rH1 = log(err0.h1/err.h1)./log(h0/h);\n        disp(' ')\n        disp('Convergence Rate')\n        disp('Node        Inf norm    L2 norm     H1 norm')\n        formatSpec = '%6.4f      %6.4f      %6.4f      %6.4f\\n';\n        fprintf(formatSpec, rNd, rInf, rL2, rH1)\n        ratio(i,:) = [rNd,rInf,rL2,rH1];\n    end\n    err0 = err; h0 = h;\n    \n    disp(' '); disp('CPU Time')\n    disp('   N     Mesh     FEM      MeshI    FemI    Matrix   Solve    Error    Time/1M cell')\n    formatSpec = '%4i  %7.2f  %7.2f  %7.2f  %7.2f  %7.2f  %7.2f  %7.2f   %7.2f\\n';\n    fprintf(formatSpec, time(:,1:i))\n    \n    %% 6. Plot Solution and Error\n    if showErr == 1\n    end\n   \nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/checkVIFEMrate3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5971022623481568}}
{"text": "function [rh,rg,h,g]=rh2rg(rh)\n\n%RH2RG    Calculates all the filters from the synthesis lowpass\n%\t  in the orthogonal case.\n%\n%\t  [RH,RG,H,G]=RH2RG(RH) begins with the synthesis lowpass\n%\t  filter (RH) and returns the synthesis highpass filter (RG),\n%\t  the analysis lowpass filter (H) and the analysis highpass\n%\t  filter (G).\n%\t\n%\t  It is an auxiliary function for orthogonal filters design.\n\n%--------------------------------------------------------\n% Copyright (C) 1994, 1995, 1996, by Universidad de Vigo \n%                                                      \n%                                                      \n% Uvi_Wave is free software; you can redistribute it and/or modify it      \n% under the terms of the GNU General Public License as published by the    \n% Free Software Foundation; either version 2, or (at your option) any      \n% later version.                                                           \n%                                                                          \n% Uvi_Wave is distributed in the hope that it will be useful, but WITHOUT  \n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or    \n% FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License    \n% for more details.                                                        \n%                                                                          \n% You should have received a copy of the GNU General Public License        \n% along with Uvi_Wave; see the file COPYING.  If not, write to the Free    \n% Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.             \n%                                                                          \n%       Author: Nuria Gonzalez Prelcic\n%       e-mail: Uvi_Wave@tsc.uvigo.es\n%--------------------------------------------------------\n\n% Calculate rg from rh.\n\nfor i=1:length(rh)        \n\trg(i) = -(-1)^i*rh(length(rh)-i+1);\nend  \n\n% Calculate h and g\n\nh=rh(length(rh):-1:1);\ng=rg(length(rg):-1:1);\n", "meta": {"author": "alexandrebarachant", "repo": "kaggle-seizure-prediction-challenge-2016", "sha": "00f937cc7710977dc812d9fc675864e2b8288658", "save_path": "github-repos/MATLAB/alexandrebarachant-kaggle-seizure-prediction-challenge-2016", "path": "github-repos/MATLAB/alexandrebarachant-kaggle-seizure-prediction-challenge-2016/kaggle-seizure-prediction-challenge-2016-00f937cc7710977dc812d9fc675864e2b8288658/Andriy/code/rh2rg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5971022623481568}}
{"text": "function [x_cplx,opt_val,lb_seq,ub_seq] = CE_similarity_ComRad( H,y,power,ee,x0,cle )\n% Branch and Bound Method for ComRad CEP\n%   Detailed explanation goes here\nN = length(x0);\namp = sqrt(power/N); % Amplitude of the Transmit Signal\ny_wave = sqrt(power*cle)*[real(y);imag(y)]; % Equivalent Real Desired Symbol\nH_wave = amp*[real(H),imag(H);-imag(H),real(H)]; % Equivalent Real Channel\nx0_wave = [real(x0);imag(x0)];\ndelta = acos(1-ee^2/2);\nfor ii = 1:N\n    l(ii,1) = angle(x0(ii))-delta;\n    u(ii,1) = angle(x0(ii))+delta;     %Initialized Upper and Lower Bound\nend           \n\nA = zeros(N,2*N);\nfor ii = 1:N\n    A(ii,ii) = cos((l(ii)+u(ii))/2)/cos(delta);\n    A(ii,ii+N) = sin((l(ii)+u(ii))/2)/cos(delta);\nend     \n\nmax_iternum = 200; %Maximum Iteration Number\nepsl = 1e-3; %Tolerence\nepsl1 = 1e-6;\n\n[x,LB] = QCQP_LB1( H_wave,y_wave,N,l,u);          %Initialized LB and x\n[x_nml1,UB1] = normalize_UB( H_wave,y_wave,x,N,l,u); %Initialized Normalization UB\n[x_nml2,UB2] = QCQP_UB( H_wave,y_wave,N,l,u,x_nml1); % fmincon UB\n[x_nml,UB] = QCQP_UB( H_wave,y_wave,N,l,u,x_nml2); % fmincon UB\nLB_start = LB;\nUB_start = UB;\n\nprob_list = zeros(max_iternum+100,4*N+1);          %Problem list initialization\nprob_list(1,:)=[x',l',u',LB];\nused = 1;\nlbest = LB;\nubest = UB;\nx_opt = x_nml;\n\nlb_seq = lbest;\nub_seq = ubest;\n\n% if (ubest-lbest)/abs(ubest)<epsl\n%     final_lb=lbest;\n%     final_ub=ubest;\n% end\n\niter = 2;\ncon = 1;\n\n\nwhile iter<=max_iternum\n    xc = prob_list(con,1:2*N)';                                   % Pick a problem having the smallest LB\n    lc = prob_list(con,(2*N+1):3*N )';\n    uc = prob_list(con,(3*N+1):4*N)';\n    x_cplx = x(1:N)+j*x(N+1:2*N);               \n    %     x_abs = abs(x_cplx);\n%     [x_abs_min,cd] = min(x_abs);\n    \n    [x_nml3,~] = normalize_UB( H_wave,y_wave,x,N,lc,uc);          % Calculate the UB of the problem\n    x_nml3_cplx = x_nml3(1:N)+j*x_nml3(N+1:2*N);\n    x_abs = abs(x_cplx - x_nml3_cplx);                            % Branching from the x(n) having the largest gap between x_u and x_l\n    [~,cd] = max(x_abs);\n    \n    xchild_left_lb=lc;                                            % Generate two sub-problems (left child and right child) at the chosen x(n)\n    xchild_left_ub=uc;\n    xchild_right_lb=lc;\n    xchild_right_ub=uc;\n    tr=(lc(cd)+uc(cd))/2;\n    xchild_left_ub(cd)=tr;\n    xchild_right_lb(cd)=tr;\n    \n    if con < used\n        prob_list(con,:) = prob_list(used,:);\n        used=used-1;\n    else\n        used=used-1;\n    end\n    [x,lb] = QCQP_LB1( H_wave,y_wave,N,xchild_left_lb,xchild_left_ub);        % Compute the LB and the associated solution of the left sub-problem\n\n    \n%     [xn_temp,ub_temp] = normalize_UB( H_wave,y_wave,x,N,xchild_left_lb,xchild_left_ub);\n%     [xn,ub] = QCQP_UB( H_wave,y_wave,N,xchild_left_lb,xchild_left_ub,xn_temp);\n    [xn,ub] = normalize_UB( H_wave,y_wave,x,N,xchild_left_lb,xchild_left_ub); % Compute the UB and the associated solution of the left sub-problem\n    \n    \n    \n    \n    if ub < ubest                                                   % If the UB is lower than the current ubest, replace ubest with UB\n       ubest=ub;\n       x_opt=xn;\n    end\n    prob_list(used+1,:)=[x',xchild_left_lb',xchild_left_ub',lb];              % Insert the associated LB and solutions into the problem list\n    used=used+1;\n    \n    [x,lb] = QCQP_LB1( H_wave,y_wave,N,xchild_right_lb,xchild_right_ub);                         % Compute the LB and the associated solution of the right sub-problem\n%     [xn_temp,ub_temp] = normalize_UB( H_wave,y_wave,x,N,xchild_right_lb,xchild_right_ub);\n%     [xn,ub] = QCQP_UB( H_wave,y_wave,N,xchild_right_lb,xchild_right_ub,xn_temp);\n    [xn,ub] = normalize_UB( H_wave,y_wave,x,N,xchild_right_lb,xchild_right_ub); % Compute the UB and the associated solution of the right sub-problem\n    if ub < ubest                    % If the UB is lower than the current ubest, replace ubest with UB\n       ubest=ub;\n       x_opt=xn;\n    end\n    prob_list(used+1,:)=[x',xchild_right_lb',xchild_right_ub',lb]; % Insert the associated LB and solutions into the problem list\n    used=used+1;\n    \n    \n    [lbest,con]=min(prob_list(1:used,4*N+1)); % Replace lbest with the smallest LB in the list, mark its index in the problem list as con\n\n    lb_seq(iter)=lbest;           %Generate LB and UB sequences\n    ub_seq(iter)=ubest;\n    iter=iter+1;\n    \n    if ((ubest-lbest)/abs(ubest)<epsl || (ubest-lbest)<epsl1)               %Convergence condition\n        final_lb=lbest;\n        final_ub=ubest;\n        break;\n    end\n%     clc\n%     disp(['Progress - ',num2str(iter),'/',num2str(max_iternum)]); \nend\nx_cplx = x_opt(1:N)+j*x_opt(N+1:2*N);          %Optimal x\n\nopt_val = objval_func(x_opt,H_wave,y_wave);  %Optimal objective function\n\n\n\nend\n\n", "meta": {"author": "yuanhao-cui", "repo": "Must-Reading-on-ISAC", "sha": "34cd6615c52ebca121428a979e756c608b195040", "save_path": "github-repos/MATLAB/yuanhao-cui-Must-Reading-on-ISAC", "path": "github-repos/MATLAB/yuanhao-cui-Must-Reading-on-ISAC/Must-Reading-on-ISAC-34cd6615c52ebca121428a979e756c608b195040/Codes/Fan2018TSP/Codes for DFRC Waveform Design/Constant Modulus/CE_similarity_ComRad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339907, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5971022597485292}}
{"text": "function [xAL,xBL,doesClip]=clipLine2ConvexPolygon(xAL,xBL,v)\n%%CLIPLINE2CONVEXPOLYGON Given the vertices of a convex polygon in 2D in\n%       either clockwise or counterclockwise order, clip one or more lines\n%       to the polygon. The lines are defined by two points on the lines,\n%       though they extend beyond the two points.\n%\n%INPUTS: xAL, xBL These are 2 2XnumLines matrices where xAL(:,k) and\n%                 xBL(:,k) are two points on the kth line.\n%               v A 2XnumVertices set of vertices defining the perimeter of\n%                 the convex polygon. The last vertex should not be a\n%                 repeat of the first vertex.\n%\n%OUTPUTS: xAL, xBL These are 2XnumLines set of the starting and ending\n%                  points of the lines clipped to the polygon. If the kth\n%                  line is complete outside the polygon, then xAL(:,k) and\n%                  xBL(:,k) will be NaNs.\n%         doesClip A numLinesX1 boolean vector indicating whether or not\n%                  each line is in or on the polygon at all.\n%\n%EXAMPLE:\n%Draw a polygon and a few line segments in black. The line segments\n%represent infinte lines. Clip the lines to the polygon and draw the\n%clipped lines in red. One of the lines does not clip, so a black segment\n%is drawn, but nothing is drawn in red.\n% numVertices=5;\n% v=zeros(2,numVertices);\n% v(:,1)=[1;1];\n% v(:,2)=[15;0];\n% v(:,3)=[10;10];\n% v(:,4)=[7;10];\n% v(:,5)=[0;8];\n% \n% %Two line segments.\n% xA=[[-3;10],[0;0],[4;6],[-2;1]];\n% xB=[[12;10],[16;8],[2;7],[-3;3]];\n% [xAT,xBT]=clipLine2ConvexPolygon(xA,xB,v);\n% \n% figure(1)\n% clf\n% hold on\n% plot([v(1,:),v(1,1)],[v(2,:),v(2,1)],'linewidth',2)\n% for k=1:size(xA,2)\n%     plot([xA(1,k),xB(1,k)],[xA(2,k),xB(2,k)],'-k','linewidth',4)\n%     \n%     if(~isnan(xAT(1,k)))\n%         plot([xAT(1,k),xBT(1,k)],[xAT(2,k),xBT(2,k)],'-r','linewidth',2)\n%     end\n% end\n%\n%REFERENCES:\n%[1] V. Skala, \"An efficient algorithm for line clipping by convex\n%    polygon,\" Computer and Graphics, vol. 17, no. 4, pp. 417-421, 1993.\n%\n%September 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nN=size(v,2);%N is the number of edges and vertices.\n\n%If many lines are clipped at once, precomputing this outside the loop can\n%be fastest.\nsiHat=zeros(2,N);\nfor k=1:(N-1)\n    siHat(:,k)=v(:,k+1)-v(:,k);\nend\nsiHat(:,N)=v(:,1)-v(:,N);\n\nnumPts=size(xAL,2);\ndoesClip=false(numPts,1);\n\nfor curPt=1:numPts\n    xA=xAL(:,curPt);\n    xB=xBL(:,curPt);\n\n    si=bsxfun(@minus,v,xA);\n    index=zeros(2,1);\n    prevSpecialIdx=-2;\n\n    k=0;\n    i=N-1;\n    j=0;\n    s=xB-xA;\n    xi=(si(2,i+1)*s(1)-si(1,i+1)*s(2));\n    while((j<N)&&(k<2))\n        eta=(si(2,j+1)*s(1)-si(1,j+1)*s(2));\n        if(xi*eta<0)%There is an intersection\n            index(k+1)=i+1;%The edge having the intersection.\n            k=k+1;\n            xi=eta;\n        elseif(xi*eta==0)%xi and/or eta=0\n            if(~(prevSpecialIdx==N-1&&i==0)&&~(prevSpecialIdx==i-1))        \n                if(eta==0)\n                    if(xi~=0)%If not special case m.\n                        index(k+1)=i+1;%The edge having the intersection.\n                        k=k+1;\n                        xi=eta;\n                        prevSpecialIdx=i;\n                    end\n                else%xi==0 and eta is not zero.\n                    index(k+1)=i+1;%The edge having the intersection.\n                    k=k+1;\n                    xi=eta;\n                    prevSpecialIdx=i;\n                end\n            end\n        end\n        i=j;\n        j=j+1;\n    end\n\n    if(k==0)\n        doesClip(curPt)=false;%There is no intersection.\n        xA=NaN;\n        xB=NaN;\n    else\n        doesClip(curPt)=true;%There is an intersection.\n        tMin=-Inf;\n        tMax=Inf;\n        i=index(1);\n        t1=det([si(:,i),-siHat(:,i)])/det([s,-siHat(:,i)]);\n        i=index(2);\n        t2=det([si(:,i),-siHat(:,i)])/det([s,-siHat(:,i)]);\n\n        if(t1<t2)\n           temp=t2;\n           t2=t1;\n           t1=temp;\n        end\n\n        if(t2<tMax)\n            xB=xA+s*t2;\n        end\n\n        if(t1>tMin)\n            xA=xA+s*t1;\n        end\n    end\n\n    xAL(:,curPt)=xA;\n    xBL(:,curPt)=xB;\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/Geometry/clipLine2ConvexPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5971022571489016}}
{"text": "\nfunction vbrfa2011_testbed_measure(model, Q)\n\nif nargin < 2 || isempty(Q)\n  % Load default results\n  disp('Loading default results..')\n  files = {'testbed_results_gaussian_D=30_20110617', ...\n           'testbed_results_multi-t_D=30_20110617', ...\n           'testbed_results_ind-t_D=30_20110617', ...\n           'testbed_results_laplace_D=30_20110617'};\n  Q = load(files{model}, 'W_struct', 'W', 'CovW', 'X', 'CovX', 'Tau_struct');\nend\n\n% Load test data\ndisp('Loading test data..')\ndata_test = load(['/share/climate/jluttine/testbed/' ...\n                  'testbed_vbrfa2011_testdata']);\n\n% Compute predictive log-likelihood\ndisp('Computing predictive log-likelihood..')\nsamples = 10;\n[M,N] = size(data_test.observations);\nYtest = data_test.observations;\nItest = ~isnan(Ytest);\nloglike = nan(samples,1);\nfor i=1:samples\n  \n  % Sample a noise level\n  tau = gamrnd(Q.W_struct.rho_struct.a_tau, 1/Q.W_struct.rho_struct.b_tau);\n\n  % Sample a reconstruction\n  for m=1:M\n    W(:,m) = gaussian_rand(Q.W(:,m), 1/tau * Q.CovW(:,:,m));\n  end\n  for n=1:N\n    X(:,n) = gaussian_rand(Q.X(:,n), Q.CovX(:,:,n));\n  end\n% $$$   W = mvnrnd(Q.W', 1/tau * Q.CovW)';\n% $$$   X = mvnrnd(Q.X', Q.CovX)';\n  F = W'*X;\n\n  % Log-likelihood\n  switch model\n   case 1 % GAUSSIAN\n    Z = Ytest(Itest) - F(Itest);\n    loglike(i) = gaussian_logpdf(tau*(Z'*Z), ...\n                                 0, ...\n                                 0, ...\n                                 -numel(Z)*log(tau), ...\n                                 numel(Z));\n    \n   case 2 % MULTIVARIATE T\n    alpha = Q.Tau_struct.a_u;\n    beta = Q.Tau_struct.b_u;\n    tau = tau * (alpha./beta);\n    nu = 2*alpha;\n    Z = Ytest - F;\n    Z(~Itest) = 0;\n    Z2 = tau .* dot(Z,Z,1);\n    Nmv = sum(Itest,1)>0;\n    loglike(i) = sum(t_logpdf(Z2(Nmv), ...\n                              -log(tau(Nmv)), ...\n                              nu(Nmv), ...\n                              sum(Itest(:,Nmv),1)));\n    \n   case 3 % INDEPENDENT T\n    [I,J] = find(Itest);\n    Z2 = tau * (Ytest(Itest) - F(Itest)).^2;\n    loglike(i) = sum(t_logpdf(Z2, ...\n                              -log(tau), ...\n                              Q.Tau_struct.nu(I), ...\n                              1));\n    \n   case 4 % LAPLACE\n    loglike(i) = sum(laplace_logpdf(Ytest(Itest), ...\n                                    F(Itest), ...\n                                    sqrt(tau)));\n  end\n\nend\n%loglike = loglike / samples;\nfprintf('Mean predictive log-density: %.4e\\n', mean(loglike));\nbias = max(loglike);\nfprintf('Log predictive density: %.4e\\n', log(mean(exp(loglike-bias))) + bias);\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/publications/vbrfa2011/vbrfa2011_testbed_measure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5971022571489016}}
{"text": "function [data,units] = compute_dangle_smallest_wing(trx,n)\n\nflies = trx.exp2flies{n};\nnflies = numel(flies);\ndata = cell(1,nflies);\nfor i = 1:nflies,\n  fly = flies(i);\n\n  danglel = diff(-trx(fly).wing_anglel);\n  dangler = diff(trx(fly).wing_angler);\n  data{i} = danglel;\n  idx = trx(fly).wing_arear_mm(1:end-1) <= trx(fly).wing_areal_mm(1:end-1);\n  data{i}(idx) = dangler(idx);\n  data{i} = data{i} ./ trx(fly).dt;\n    \nend\nunits = parseunits('rad/s');\n\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/compute_dangle_smallest_wing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5971022519496461}}
{"text": "function [km3] = cl2km3(cl)\n% Convert volume from centiliters to cubic kilometers. \n% Chad Greene 2012\nkm3 = cl*1e-14;", "meta": {"author": "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/cl2km3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5970977665436581}}
{"text": "% Dual RPCA (Lin et al. 2009)\n% process_video('RPCA', 'DUAL', 'dataset/demo.avi', 'output/demo_DUAL.avi');\nlambda = 1/sqrt(max(size(M))); % default lambda\n[L,S] = dual_rpca_2(M,lambda);\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/DUAL/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5970977536402313}}
{"text": "function [AP,TP,FN,FP,prec,rec,mdAll,levh]=averageprecision(coord_est,coord_true,radiustrue,intens)\n% Evaluates average precision for set of true and estimated points. See S407_report for details. \n% References: Everingham, M., Gool, L., Williams, C.K.I., Winn, J. & Zisserman, A. The Pascal Visual Object Classes (VOC) Challenge. International Journal of Computer Vision 88, 303-338 (2009).\n%\n% [AP,TP,FN,FP,prec,rec,mdAll]=averageprecision(coord_est,coord_true,radiustrue,intens)\n% input:  coord_est - Nx2 matrix of estimated coordinates\n%         coord_true- Nx2 matrix of true coordinates\n%         radiustrue - limit on distance between true and estimated coordinates. For smaller distance the estimated point is considered as a true positive (can be set to sigma/2, where sigma is the std of the gaussian approximation of hte PSF.)\n%         intens - Nx1 vector of intensity of the estimated source\n%         \n% output: AP - average precision\n%         TP - true positives\n%         FN - false negatives\n%         FP - false poitives\n%         prec - precision\n%         rec - recall \n%         mdAll - localisation precision at the lowest confidence level\n\n% levn = 100; % number of confidence levels for AP (see S407_report.pdf)\n\nlevh=sort(unique(sqrt(double(intens))));\nlevn=length(levh); % number of different intensities\n\nnT=size(coord_true,1);\nnE=size(coord_est,1);\nminh=min(levh);\nmaxh=max(levh);\n% levh=minh+(maxh-minh)/(levn-1)*[0:levn-1];\n\nTP=zeros(levn,1);\nFP=nE*ones(levn,1);\nFN=nT*ones(levn,1);\nT = coord_true;\nmdAll=mindistsep(T,coord_est);\nfor ii=1:levn\n    index = sqrt(intens)>=levh(ii); % above the limit brightness   \n    E = coord_est(index,:);\n    [md,mT,mE]=mindistsep(T,E); % mT and mE are indeces of points connected by a distance md.\n    TP(ii) = sum(md<=radiustrue); %true positives\n    setDiffE=setdiff(1:size(E,1),mE); % These estimated points have not been assighned to any true point.\n    setDiffT=setdiff(1:size(T,1),mT); % These true points have not been assighned to any estimated point.\n    FP(ii) = numel(setDiffE)+sum(md>radiustrue); %False positives: points futher from true then md, and estimated pints without any assigned true point\n    FN(ii) = numel(setDiffT)+sum(md>radiustrue); %False negatives: points futher from true then md, and true poitions without any assigned esitmated point\nend\n\nprec = TP./(TP+FP);\nrec = TP./(TP+FN);\n\nprecinterpol = zeros(11,1);\nfor ii=0:10;\n    recind=rec>=(.1*ii);\n    maxprec = max(prec(recind));\n    if ~isempty(maxprec)\n        precinterpol(ii+1)=maxprec;\n    end\nend\n\nAP=1/11*sum(precinterpol);", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/averagepreceval/averageprecision.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5970977479312485}}
{"text": "function [beta,betastar] = igls_orig(y, x, Vy, type)\n% function [betastar] = igls(y, x, Vy)\n%\n% Variance Component Estimation using IGLS/RIGLS\n%\n% y = d + cx + epsilon  where  epsilon ~ N(0,sigma*Vy)\n%\n% d ~ N(0, sigma_d) and c ~ N(0, sigma_c)\n%\n% Calculate d, c, sigma, sigma_d and sigma_c using Maximum Likelihood\n% methods (IGLS) and Restricted Maximum Likelihood methods (RIGLS).\n%\n% y - matrix T x subjects\n% x - matrix T x subjects\n% Vy - matrix T x T x subjects\n% type = 'i' IGLS\n% type = 'r' RIGLS\n%\n% By Martin Lindquist, April 2007\n%\n% Example:\n% \n% len = 200; sub =20;\n% x = zeros(len,sub);\n% x(11:20,:) = 2;\n% x = x+ normrnd(0,0.1,len,sub);\n% c = normrnd(0.5,0.1,sub,1);\n% d = normrnd(3,0.2,sub,1);\n% y=x;\n% for i=1:sub, y(:,i) = d(i) + c(i).*x(:,i) + normrnd(0,0.5,len,1); end;\n% Vy = zeros(len,len,sub);\n% for i=1:sub, Vy(:,:,i) = eye(len,len).*0.5; end;\n% \n% [beta, betastar] = igls(y, x, Vy,'i')\n%\nc1= clock;\n[T, sub] = size(y);             % Length of y vector and Number of subjects\n\none = zeros(T,1)+1;             % Vector of ones\nnull = zeros(T,1);              % Vector of zeros\n\nepsilon = 0.001;        \nnum_iter = 5;\n\nlen = sub*T;                                    % Total number of observations\nz = reshape(y,len,1);                           % Concatenated data\nD = [zeros(len,1)+1 reshape(x,len,1)];          % Design matrix\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Step 1: Find the OLS solution \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nbeta = pinv(D)*z;                           % Beta values\nresid = z - D*beta;                         % Residuals\n\nystar = [];\nif (type == 'i'),           % IGLS\n     for i=1:sub,\n         tmp = vech(resid(((i-1)*T+1):(i*T))*resid(((i-1)*T+1):(i*T))');                 % Find vech of estimated covariance\n         ystar = [ystar; tmp];\n     end;     \nelseif (type == 'r'),       % RIGLS\n    for i=1:sub,\n        Dtmp = D((((i-1)*T+1):(i*T)),:);\n        rtmp = resid(((i-1)*T+1):(i*T));\n        rig = rtmp*rtmp' + Dtmp*inv(Dtmp'*Dtmp)*Dtmp';\n        tmp = vech(rig);                              % Find vech of estimated covariance \n        ystar = [ystar; tmp];\n    end;\nend;\n    \nclear tmp rtmp rig Dtmp    \nG = Create_Design_Eq2(y, x, Vy);                      % Create design matrix for variance estimation\nbetastar = pinv(G)*ystar;                             % Estimate variance components\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Step 2: Iterate \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ncnt = 0;\nbetastar_old = betastar+10;\n\niSigma = zeros(len,len);    \n\nwhile(cnt < num_iter | sum((betastar-betastar_old).^2)> epsilon),\n\n    num = size(G,1)/sub;\n    \n    for i=1:sub,\n        iSigma(((i-1)*T+1):(i*T),((i-1)*T+1):(i*T)) = ivech(G(((i-1)*num+1):(i*num),:)*betastar);\n    end;\n    \n    beta = inv(D'*iSigma*D)*D'*iSigma*z;          % Beta values\n    resid = z - D*beta;                           % Residuals\n\n    ystar = [];\n\n    if (type == 'i'),           % IGLS   \n         for i=1:sub,\n             tmp = vech(resid(((i-1)*T+1):(i*T))*resid(((i-1)*T+1):(i*T))');                 % Find vech of estimated covariance\n             ystar = [ystar; tmp];\n         end;\n    elseif (type == 'r'),       % RIGLS\n         for i=1:sub,\n            Dtmp = D((((i-1)*T+1):(i*T)),:);\n            rtmp = resid(((i-1)*T+1):(i*T));\n            rig = rtmp*rtmp' + Dtmp*inv(Dtmp'*iSigma((((i-1)*T+1):(i*T)),(((i-1)*T+1):(i*T)))*Dtmp)*Dtmp';\n            tmp = vech(rig);                                                                 % Find vech of estimated covariance\n            ystar = [ystar; tmp];\n         end;      \n    end;\n\n    clear tmp rtmp rig Dtmp    \n\n    betastar_old = betastar;\n    betastar = pinv(G)*ystar;                                         % Estimate variance components\n\n    cnt = cnt+1\nend;\n\nc2 = clock;\nc2 - c1\nreturn;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Subfunctions\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [G] = Create_Design_Eq2(y, x, Vy)\n% function [G] = Create_Design(y, x, Vy)\n%\n% Create Design matrix for estimation of variance componets\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[T, sub] = size(x);\nlen = T*(T+1)/2;\nONE = zeros(len,1)+1;\n\nG = [];\nH = [];\n\nfor i=1:sub,\n \n    XX = x(:,i)*x(:,i)';\n\n    Gtmp = zeros(len,3);\n    Gtmp(:,1) = ONE;\n    Gtmp(:,2) = vech(XX);\n    Gtmp(:,3) = vech(Vy(:,:,i));    \n    G = [G; Gtmp];\n     \nend;\n\n\nreturn;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction V = vech(Mat)\n% function V = vech(Mat)\n%\n% Calculate vech for the matrix Mat\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nV = Mat(logical(tril(ones(size(Mat)))));\n\nreturn;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Mat = ivech(V)\n% function Mat = vech(V)\n%\n% Calculate the \"inverse\" of the vech function\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nlen = length(V);\ndim = -0.5 + sqrt(0.25 + 2*len);\nMat = zeros(dim,dim);\nind=1;\n\nfor i=1:dim\n    for j=i:dim\n        Mat(j,i)=V(ind);\n        ind=ind+1;\n    end\nend\n\nreturn;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/Iterative_Generalized_Least_Squares/igls_orig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5970977479312484}}
{"text": "function [ homos ] = NewWarping( pa_, pb_, H, W, qH, qW, lambda)\n% A warpped up wersion of as-similar-as-possible warping, with pre-warp. \n% set PREWARP to false if the output is badly distorted. \n    PREWARP = true;\n    nP = length(pa_);\n    if length(pb_) ~= nP\n        error('Points Numbers met Matching!');\n    end\n    if PREWARP\n        [preH, ~] = ransacfithomography(pa_', pb_', 0.001);\n        whilecount = 0;\n        while isnan(preH(1, 1)) && whilecount < 100\n            [preH, ~] = ransacfithomography(pa_', pb_', 0.001);\n            whilecount = whilecount + 1;\n        end\n        if whilecount == 100\n            error('?') ;\n        end\n    else\n        preH = eye(3);\n        pa = pa_;  \n    end\n    pbWarp = preH \\ [pb_' ; ones(1, nP)];\n    pbWarp(1, :) = pbWarp(1, :) ./ pbWarp(3, :);\n    pbWarp(2, :) = pbWarp(2, :) ./ pbWarp(3, :);\n    pbWarp = pbWarp(1:2, :)';    \n    \n    diff = sum((pa_ - pbWarp) .* (pa_ - pbWarp), 2) < 1000;    \n    valid = pbWarp(:, 1) > 0 & pbWarp(:, 1) < W & pbWarp(:, 2) > 0 & pbWarp(:, 2) < H;\n    pa = pa_(valid & diff, :);\n    pbWarp = pbWarp(valid & diff, :);\n    \n    asap = AsSimilarAsPossibleWarping(H, W, qW, qH, lambda);\n    asap.SetControlPts(pa, pbWarp);\n    asap.Solve();\n    \n% -----DEBUG-SCRIPT------\n% use it to check the warping result\n%     e = asap.CalcError();\n    \n%     grid = asap.Warp(ones(H, W, 3) * 255, 400);\n%     imshow(grid);\n    \n%     if e > 10\n%         disp('?') ;\n%     end\n\n    homos2 = asap.CalcHomos();\n    homos = homos2;\n    for row = 1:H/qH\n        for col = 1:W/qW\n            tempH = preH * squeeze(homos2(row, col, :, :));\n            homos(row, col, :, :) = tempH ./ tempH(3, 3);            \n        end\n    end\nend\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/stitch/NewWarping.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5970977422222653}}
{"text": "function SeamVector=removalMap(X,lines);\n% REMOVALMAP takes a given image and finds the ordered set of (vertical)\n% seams that are removed from an image and returns them in an array, where\n% the Nth column in the array corresponds to the Nth seam to be removed.\n%\n% Author: Danny Luong\n%         http://danluong.com\n%\n% Last updated: 12/20/07\n\n\n[rows cols dim]=size(X);\n\nE=findEnergy(X);    %Finds the gradient image\n\nfor i=1:min(lines,cols-1)\n\n    %find \"energy map\" image used for seam calculation given the gradient image\n    S=findSeamImg(E);\n\n    %find seam vector given input \"energy map\" seam calculation image\n    SeamVector(:,i)=findSeam(S);\n\n    %remove seam from image\n    X=SeamCut(X,SeamVector(:,i));\n    E=SeamCut(E,SeamVector(:,i));\n\n    %updates size of image\n    [rows cols dim]=size(X);\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/18089-seam-carving-for-content-aware-image-resizing-gui-implementation-demo/MATLAB_Seam_Carving/removalMap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5970898293198508}}
{"text": "function D = computeDistMatrix_AVFC (data,T,options)\n%\n% It uses KL-divergence to compute a subject-by-subject distance matrix\n% of average FC matrices (on fMRI). \n%\n% INPUT\n% data          observations; in this case it has to be a cell, each with\n%               the data for one subject\n% T             length of series, also a cell. \n% \n% OUTPUT\n% D             (N by N) distance matrix, with the distance between each\n%               pair of subjects in \"HMM space\"\n%\n% Author: Diego Vidaurre, OHBA, University of Oxford (2020)\n\nif ~iscell(data) || ~iscell(T), error('X and T must both be cells'); end \n\nif nargin<3, options = struct(); end\n\nN = length(data);\n\nfor n = 1:N\n    if ischar(data{n})\n        fsub = data{n};\n        loadfile_sub;\n    else\n        X = data{n};\n    end\n    X = preprocdata(X,T{n},options);\n    if n == 1\n        ndim = size(X,2);\n        V = zeros(ndim,ndim,N);\n    end\n    V(:,:,n) = X' * X;\nend\n\nD = NaN(N);\ntry\n    for n1 = 1:N-1\n        for n2 = n1+1:N\n            D(n1,n2) =  ( wishart_kl(V(:,:,n1),V(:,:,n2),sum(T{n1}),sum(T{n2})) + ...\n                wishart_kl(V(:,:,n2),V(:,:,n1),sum(T{n2}),sum(T{n1})) ) /2;\n            D(n2,n1) = D(n1,n2);\n        end\n    end\ncatch\n    for n = 1:N\n        V(:,:,n) = V(:,:,n) + 0.0001*eye(ndim);\n    end\n    for n1 = 1:N-1\n        for n2 = n1+1:N\n            D(n1,n2) =  ( wishart_kl(V(:,:,n1),V(:,:,n2),sum(T{n1}),sum(T{n2})) + ...\n                wishart_kl(V(:,:,n2),V(:,:,n1),sum(T{n2}),sum(T{n1})) ) /2;\n            D(n2,n1) = D(n1,n2);\n        end\n    end    \nend\n\nend\n\n\nfunction X = preprocdata(X,T,options)\n\n% Filtering\nif isfield(options,'filter') && ~isempty(options.filter)\n    X = filterX(X,T,options.Fs,options.filter);\nend\n% Detrend X\nif isfield(options,'detrend') && options.detrend\n    X = detrendX(X,T);\nend\n% Hilbert envelope\nif isfield(options,'onpower') && options.onpower\n    X = rawsignal2power(X,T);\nend\n% Embedding\nif isfield(options,'embeddedlags') && length(options.embeddedlags) > 1\n    X = embeddata(X,T,options.embeddedlags);\nend\nX = zscore(X);\n\nend", "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/prediction/computeDistMatrix_AVFC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5970535173819085}}
{"text": "function [u,w,AE,AI,isExteriorTElem,isExteriorSElem] = interfacefittedPoisson(node,telem,selem,pde,interfaceEdge,bdEdge,option)\n%% INTERFACEFITTEDPOISSON Poisson equation: P1 linear element.\n%\n%   u = INTERFACEPOISSON(node,telem,selem,pde,E) produces the linear finite element\n%   approximation of the interface Poisson equation\n% \n%   input:\n%       node, N*2 matrix, node(i,:) are the xy coordinates of i-th node;\n%       telem, NTT*3 matrix, telem(j,:) are the three  global indices of the\n%              vertices ofj-th triangle element;\n%       selem,NTS*4 matrix, selem(j,:) are the four global indices of the\n%             vertices of j-th quad element;\n%\n% \n\n[N,Dim] = size(node); \nNdof = N;\n\n%% Geometry structures of interface meshes\n\nNTS = size(selem,1);\nisExteriorSElem = false(NTS,1);\nc = (node(selem(:,1),:) + node(selem(:,2),:) + node(selem(:,3),:)+node(selem(:,4),:))/4;\nisExteriorSElem(pde.phi(c)>0) = true;\n\nNTT = size(telem,1);\nisExteriorTElem = false(NTT,1);\nc = (node(telem(:,1),:) + node(telem(:,2),:) + node(telem(:,3),:))/3;\nisExteriorTElem(pde.phi(c)>0) = true;\n\n[sAE,sbE] = getstiffmatrixandrhsonquad(node,selem(isExteriorSElem,:));\n[sAI,sbI] = getstiffmatrixandrhsonquad(node,selem(~isExteriorSElem,:));\n[tAE,tbE] = getstiffmatrixandrhsontri(node,telem(isExteriorTElem,:));\n[tAI,tbI] = getstiffmatrixandrhsontri(node,telem(~isExteriorTElem,:));\n\n\nA = sAE + sAI + tAE + tAI;\nb = sbE + sbI + tbE + tbI;\n\nAI = sAI + tAI;\nAE = sAE + tAE;\n\nflux = getfluxconditiononinterface(node,interfaceEdge);\nb = b - flux;\n\n\n\n%% Extend w to the whole domain\nisInterfaceNode = false(Ndof,1);\nisInterfaceNode(interfaceEdge(:)) = true;\ninterfaceNode = find(isInterfaceNode);\n\nisInNode = false(Ndof,1);\ninteriorSElem = selem(~isExteriorSElem,:);\ninteriorTElem = telem(~isExteriorTElem,:);\nisInNode([interiorSElem(:);interiorTElem(:)]) = true;\ninNode = find(isInNode & ~isInterfaceNode);\n\nw = zeros(Ndof,1);\nFI= zeros(Ndof,1);\nw(interfaceNode) = pde.exactw(node(interfaceNode,:));\nFI = FI - AI*w;\nextensionoption.printlevel = 0;\nw(inNode) = amg(AI(inNode, inNode),FI(inNode),extensionoption);\n\n%% Dirichlet boundary condition\nisBdNode = false(Ndof,1); \nisBdNode(bdEdge(:)) = true;\nbdNode = find(isBdNode);\n\nu = zeros(Ndof,1); \nu(bdNode) = pde.g_D(node(bdNode,:));\nb = b - A*u+AI*w;\nb(bdNode) = u(bdNode);\n\nfreeNode = find(~isBdNode);\nbdidx = zeros(Ndof,1); \nbdidx(bdNode) = 1;\nTbd = spdiags(bdidx,0,Ndof,Ndof);\nT = spdiags(1-bdidx,0,Ndof,Ndof);\nAD = T*A*T + Tbd;\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 <= 1e3  % 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 'amg'\n        option.solver = 'CG';\n        [u(freeNode),info] = amg(AD(freeNode,freeNode),b(freeNode),option);                 \nend\n\n%%\neqn = struct('A',AD,'b',b,'freeNode',freeNode);\n\n   %% Assemble stiffness matrix and rhs on quad mesh\n    function [A,b] = getstiffmatrixandrhsonquad(node,elem)\n        [NT,NV] = size(elem);\n        % generate sparse pattern\n        ii = zeros(10*NT,1); jj = zeros(10*NT,1);\n        index = 0;\n        for i = 1:4\n            for j = i:4\n                ii(index+1:index+NT) = double(elem(:,i));\n                jj(index+1:index+NT) = double(elem(:,j));\n                index = index + NT;\n            end\n        end\n        % quadrature points\n        if ~isfield(pde,'d'), pde.d = []; end\n        if ~isfield(option,'dquadorder')\n            option.dquadorder = 2;        % default order is exact for quadratic function\n        end\n        [pts, weight] = quadptsquad(option.dquadorder);\n        nQuad = size(pts,1);\n        % compute non-zeros\n        sA = zeros(10*NT,nQuad);\n        for p = 1:nQuad\n            % Dphi at quadrature points\n            [phi, Dphip, J] = quadbasis(node,elem,pts(p,:));\n            index = 0;\n            for i = 1:4\n                for j = i:4\n                    Aij = 0;\n                    if isempty(pde.d) || isnumeric(pde.d)\n                        Aij = Aij + weight(p)*dot(Dphip(:,:,i),Dphip(:,:,j),2);\n                    else\n                        pxy = zeros(NT, Dim);\n                        for ip = 1:Dim\n                            xi = node(:,ip);\n                            pxy(:,ip) = xi(elem)*phi;\n                        end\n                        Aij = Aij + weight(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.*J;\n                    sA(index+1:index+NT,p) = Aij;\n                    index = index + NT;\n                end\n            end\n        end\n        sA = sum(sA,2);\n        % assemble the matrix\n        diagIdx = (ii == jj);   upperIdx = ~diagIdx;\n        A = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Ndof,Ndof);\n        AU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Ndof,Ndof);\n        A = A + AU + AU';\n        clear Aij ii jj Dphip\n        \n        %% Assemble the right hand side\n        b = zeros(Ndof,1);\n        if ~isfield(option,'fquadorder')\n            option.fquadorder = 3;   % default order\n        end\n        if ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n            pde.f = [];\n        end\n        \n        if ~isempty(pde.f)\n            [pts, weight] = quadptsquad(option.fquadorder);\n            nQuad = size(pts,1);\n            bt = zeros(NT,NV);\n            for p = 1:nQuad\n                % quadrature points in the x-y coordinate\n                [phi, ~, J] = quadbasis(node,elem, pts(p,:));\n                pxy = zeros(NT, Dim);\n                for i = 1:Dim\n                    xi = node(:,i);\n                    pxy(:,i) = xi(elem)*phi; % ? questionable\n                end\n                fp = pde.f(pxy);\n                bt = bt + (weight(p)*fp.*J)*phi';\n            end\n            b = accumarray(elem(:),bt(:),[Ndof 1]);\n        end\n        \n    end\n\n    %% Assemble the stiffmatrix and right hand side on triangle mesh\n    function [A,b] = getstiffmatrixandrhsontri(node,elem)\n        NT = size(elem,1);\n        % quadrature points\n        center = (node(elem(:,1),:) + node(elem(:,2),:) + node(elem(:,3),:))/3;\n       % Diffusion coefficient\n        if isfield(pde,'d') && ~isempty(pde.d)\n            if isnumeric(pde.d)\n                K = pde.d;                   % d is an array\n            else                            % d is a function\n                K = pde.d(center);\n            end\n        else\n            K = [];\n        end\n        [Dphi,area] = gradbasis(node,elem);\n        A = sparse(Ndof,Ndof);\n        for i = 1:3\n            for j = i:3\n                Aij = (Dphi(:,1,i).*Dphi(:,1,j)+Dphi(:,2,i).*Dphi(:,2,j)).*area;\n                if ~isempty(K)\n                    Aij = K.*Aij;\n                end\n                if (j==i)\n                    A = A + sparse(elem(:,i),elem(:,j),Aij,Ndof,N);\n                else\n                    A = A + sparse([elem(:,i);elem(:,j)],[elem(:,j);elem(:,i)],[Aij; Aij],Ndof,Ndof);\n                end\n            end\n        end\n\n        b = zeros(Ndof,1);\n        if ~isfield(option,'fquadorder')\n            option.fquadorder = 3;   % default order\n        end\n        if ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n            pde.f = [];\n        end\n        if ~isempty(pde.f)\n            [lambda,weight] = quadpts(option.fquadorder);\n            nQuad = size(lambda,1);\n            ft = zeros(NT,3);\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                % function values at quadrature points\n                fp = pde.f(pxy);\n                % evaluate fp outside.\n                for j = 1:3\n                    ft(:,j) = ft(:,j) + lambda(p,j)*weight(p)*fp;\n                end\n            end\n            ft = ft.*[area,area,area];\n            b = accumarray(elem(:),ft(:),[Ndof 1]);\n        end  \n    end\n\n    %% Neumann boundary condition on interface edges\n    function b = getfluxconditiononinterface(node,interfaceEdge)\n        ve = node(interfaceEdge(:,1),:) - node(interfaceEdge(:,2),:);\n        ve = [-ve(:,2), ve(:,1)];\n        edgeLen = sqrt(sum(ve.^2,2));\n        if ~isfield(option,'gNquadorder')\n            option.gNquadorder = 5;   % default order\n        end\n        [lambda,weight] = quadpts1(option.gNquadorder);\n        nQuad = length(weight);\n        ge = zeros(size(interfaceEdge,1),2);\n        for i = 1:nQuad\n            pxy=lambda(i,1)*node(interfaceEdge(:,1),:)+lambda(i,2)*node(interfaceEdge(:,2),:);\n            leftpt = pxy - ve/2;\n            rightpt = pxy + ve/2;\n            pxy = findintersectbisect(pde.phi,leftpt,rightpt);\n            q = pde.exactq(pxy);\n            ge(:,1)=ge(:,1)+weight(i)*lambda(i,1)*q;\n            ge(:,2)=ge(:,2)+weight(i)*lambda(i,2)*q;\n        end\n        ge = ge.*[edgeLen,edgeLen];\n        b = accumarray(interfaceEdge(:), ge(:),[Ndof,1]);\n    end\n\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/interfacefittedPoisson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5970535016764943}}
{"text": "function [vfN, vfR, vrN, vrR, vnetN, vnetR, uL, uC, u0L, u0C, lnxL, lnxC] = projectOntoSubspace(A, vf, vr, vnet, u, u0, lnx,printLevel,rowBool,colBool)\n% Projects flux, net flux, potential and logarithmic concentration onto\n% their respective subspaces of A using projection matrices generated either \n% derived from SVD, or by using the Moore-Penrose pseudoinverse\n%\n% Optionally, a subset of the matrix A may be chosen by using A(rowBool,colBool)\n% but then only the true rows of u, u0, lnx, and true columns of vf,vr,vnet are\n% projected and the remaining rows and columns are not affected\n%\n% Let `M` denote the Moore-Penrose pseudoinverse of A and the subscripts are the following\n% `_R` row space,\n% `_N` nullspace,\n% `_C` column space,\n% `_L` left nullspace,\n%\n% Example for flux of net flux\n%\n% Let\n%\n% .. math::\n%      vf   &= vf_R + vf_N \\\\\n%      vf_R &= M A vf = PR vf \\\\\n%      vf_N &= (I - M A) vf = PN vf\n%\n% Example for potential or logarithmic concentration\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% USAGE:\n%\n%    [vfN, vfR, vrN, vrR, vnetN, vnetR, uL, uC, u0L, u0C, lnxL, lnxC] = projectOntoSubspace(modelT, vf, vr, vnet, u, u0, lnx)\n%\n% INPUTS:\n%    A          `m x n` matrix\n%    vf:        `n x 1` - forward flux\n%    vr:        `n x 1` - reverse flux\n%    vnet:      `n x 1` - net flux\n%    u:         `m x 1` - chemical potential\n%    u0:        `m x 1` - standard chemical potential\n%    lnx:       `m x 1` - logarithmic concentration\n% OPTIONAL INPUTS\n%    rowBool    `m x 1` - boolean indicating the subset of rows of A\n%    colBool    'n x 1' - boolean indicating the subset of cols of A\n%\n% OUTPUTS:\n%    vfN:       forward flux - nullspace\n%    vfR:       forward flux - row space\n%    vrN:       reverse flux - nullspace\n%    vrR:       reverse flux - row space\n%    vnetN:     net flux - nullspace\n%    vnetR:     net flux - row space\n%    uL:        chemical potential - left nullspace\n%    uC:        chemical potential - column space\n%    lnxL:      logarithmic concentration - left nullspace\n%    lnxC:      logarithmic concentration - column space\n\nif ~isempty(vf)\n    if any((vnet(colBool)- vf +vr)>1e-12) %sanity check\n    error('Net flux does not equal the difference between forward and reverse flux')\n    end\nend\n\nif ~isempty(lnx)\n    if any((u - u0 - lnx)>1e-12)\n        error('Chemical potential does not equal standard chemical potential plus logarithmic conc.')\n    end\nend\n\nif ~exist('printLevel','var')\n    printLevel=0;\nend\n\n[m,n]=size(A);\n\nif ~exist('rowBool','var')\n    rowBool=true(m,1);\nend\n\nif ~exist('colBool','var')\n    colBool=true(n,1);\nend\n\n%generate fake outputs, or populate with unprojected vectors, part of which\n%will be overwritten with the projected vectos further below.\nif ~exist('u','var')\n    uL=NaN*ones(m,1);\n    uC=NaN*ones(m,1);\nelse\n    uL=u;\n    uC=u;\nend\nif ~exist('u0','var')\n    u0L=NaN*ones(m,1);\n    u0C=NaN*ones(m,1);\nelse\n    u0L=u0;\n    u0C=u0;\nend\nif ~exist('lnx','var')\n    lnxL=NaN*ones(m,1);\n    lnxC=NaN*ones(m,1);\nelse\n    lnxL=lnx;\n    lnxC=lnx;\nend\nif ~exist('vf','var')\n    vfN=NaN*ones(n,1);\n    vfR=NaN*ones(n,1);\nelse\n    vfN=vf;\n    vfR=vf;\nend\nif ~exist('vr','var')\n    vrN=NaN*ones(n,1);\n    vrR=NaN*ones(n,1);\nelse\n    vrN=vr;\n    vrR=vr;\nend\nif ~exist('vnet','var')\n    vnetN=NaN*ones(n,1);\n    vnetR=NaN*ones(n,1);\nelse\n    vnetN=vnet;\n    vnetR=vnet;\nend\n\n%generate projection matrices\nsub_space='all';\n\n[PR,PN,PC,PL]=subspaceProjector(A(rowBool,colBool),printLevel,sub_space);\n\n%potential\nif ~isempty(u)\n    %concentration\n    uC(rowBool)=PC*u(rowBool);\n    uL(rowBool)=PL*u(rowBool);\nend\n\nif ~isempty(u0)\n    %standard potential\n    u0L(rowBool)=PL*u0(rowBool);\n    u0C(rowBool)=PC*u0(rowBool);\nend\n\nif ~isempty(lnx)\n    %concentration\n    lnxC(rowBool)=PC*lnx(rowBool);\n    lnxL(rowBool)=PL*lnx(rowBool);\nend\n\n%flux\nif ~isempty(vnet)\n    vnetN(colBool)=PN*vnet(colBool);\n    vnetR(colBool)=PR*vnet(colBool);\nend\nif ~isempty(vf)\n    vfN(colBool)=PN*vf(colBool);\n    vrR(colBool)=PR*vr(colBool);\nend\nif ~isempty(vr)\n    vrN(colBool)=PN*vr(colBool);\n    vrR(colBool)=PR*vr(colBool);\nend\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/subspaces/subspaceProjection/projectOntoSubspace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.597053501429161}}
{"text": "function pos2 = nutate (tjd, pos1)\n\n% this function nutates equatorial rectangular coordinates from\n% the mean dynamical equator and equinox of epoch to the true\n% equator and equinox of epoch. see explanatory supplement to the\n% astronomical almanac, pp. 114-115.\n\n% input\n\n%  tjd  = tdb julian date of epoch\n\n%  pos1 = position vector, geocentric equatorial rectangular\n%         coordinates, referred to mean dynamical equator and\n%         equinox of epoch\n\n% output\n\n%  pos2 = position vector, geocentric equatorial rectangular\n%         coordinates, referred to true equator and equinox of epoch\n\n% note:  if tjd is negative, inverse nutation (true to mean) is applied.\n\n% ported from NOVAS 3.0\n\n%%%%%%%%%%%%%%%%%%%%%%%\n\nseccon = 180.d0 * 3600.d0 / pi;\n\ntjd1 = abs(tjd);\n\n[oblm, oblt, eqeq, dpsi, deps] = etilt (tjd1);\n\noblm = oblm * 3600.d0 / seccon;\n\noblt = oblt * 3600.d0 / seccon;\n\ndpsi = dpsi / seccon;\n\ndeps = deps / seccon;\n\ncobm = cos(oblm);\n\nsobm = sin(oblm);\n\ncobt = cos(oblt);\n\nsobt = sin(oblt);\n\ncpsi = cos(dpsi);\n\nspsi = sin(dpsi);\n\n% compute elements of nutation rotation matrix\n\nxx =  cpsi;\nyx = -spsi * cobm;\nzx = -spsi * sobm;\n\nxy =  spsi * cobt;\nyy =  cpsi * cobm * cobt + sobm * sobt;\nzy =  cpsi * sobm * cobt - cobm * sobt;\n\nxz =  spsi * sobt;\nyz =  cpsi * cobm * sobt - sobm * cobt;\nzz =  cpsi * sobm * sobt + cobm * cobt;\n\nif (tjd < 0.0d0)\n\n    % perform rotation from true to mean\n\n    pos2(1) = xx * pos1(1) + xy * pos1(2) + xz * pos1(3);\n\n    pos2(2) = yx * pos1(1) + yy * pos1(2) + yz * pos1(3);\n\n    pos2(3) = zx * pos1(1) + zy * pos1(2) + zz * pos1(3);\n\nelse\n\n    % perform rotation from mean to true\n\n    pos2(1) = xx * pos1(1) + yx * pos1(2) + zx * pos1(3);\n\n    pos2(2) = xy * pos1(1) + yy * pos1(2) + zy * pos1(3);\n\n    pos2(3) = xz * pos1(1) + yz * pos1(2) + zz * pos1(3);\n\nend\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/nutate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5970019279970055}}
{"text": "% A Thin Plate Subjected to Uniform Traction\n% T3 Implementation\n% 2 elements\n% clear memory\nclear all; \nclc;\nclose all;\n% materials\nE  = 30e6;     poisson = 0.30;  thickness = 1;\n\n% matrix D\nD=E/(1-poisson^2)*[1 poisson 0;poisson 1 0;0 0 (1-poisson)/2];\n \n% trivial preprocessing\n% numberElements: number of elements\nnumberElements=2; \n% numberNodes: number of nodes\nnumberNodes=4;\n% coordinates and connectivities\nelementNodes=[1 3 2; 1 4 3];\nnodeCoordinates=[0, 0; 0, 10; 20, 10; 20, 0];\ndrawingMesh(nodeCoordinates,elementNodes,'T3','k-o');\n\n% GDof: global number of degrees of freedom\nGDof=2*numberNodes; \n\n% boundary conditions \nprescribedDof=[1 2 3 4]';\n% force vector \nforce=zeros(GDof,1);\nforce(5)=5000; force(7) =5000;\n\n% calculation of the system stiffness matrix\nstiffness=formStiffness2D(GDof,numberElements,...\n    elementNodes,numberNodes,nodeCoordinates,D,thickness);\n\n% solution\ndisplacements=solution(GDof,prescribedDof,stiffness,force);\n\n% output displacements\noutputDisplacements(displacements, numberNodes, GDof);\n\noutputStress(displacements,numberElements,...\n    elementNodes,nodeCoordinates,D)", "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/T3Simple_solution/Problem_1/problem2dTensileT3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5969934338619092}}
{"text": "% RES = pointOp(IM, LUT, ORIGIN, INCREMENT, WARNINGS)\n%\n% Apply a point operation, specified by lookup table LUT, to image IM.\n% LUT must be a row or column vector, and is assumed to contain\n% (equi-spaced) samples of the function.  ORIGIN specifies the\n% abscissa associated with the first sample, and INCREMENT specifies the\n% spacing between samples.  Between-sample values are estimated via\n% linear interpolation.  If WARNINGS is non-zero, the function prints\n% a warning whenever the lookup table is extrapolated.\n%\n% This function is much faster than MatLab's interp1, and allows\n% extrapolation beyond the lookup table domain.  The drawbacks are\n% that the lookup table must be equi-spaced, and the interpolation is\n% linear.\n\n% Eero Simoncelli, 8/96.\n\nfunction res = pointOp(im, lut, origin, increment, warnings)\n\n%% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD)\n\n% fprintf(1,'WARNING: You should compile the MEX code for \"pointOp\", found in the MEX subdirectory.  It is MUCH faster.\\n');\n\nX = origin + increment*[0:size(lut(:),1)-1];\nY = lut(:);\n\nres = reshape(interp1(X, Y, im(:), 'linear'),size(im));\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/pyrTools/pyrTools/pointOp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5969708593735846}}
{"text": "function area = polySgnArea(x,y)\n% area of an orientation with sign depending of orientation\n\narea = 0.5*sum((y(2:end)-y(1:end-1)) .* (x(2:end)+x(1:end-1)));\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/EBSDAnalysis/@grain2d/private/polySgnArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5969708485551023}}
{"text": "function Vi = spm_get_vc(I,factor)\n% Generate error covariance components for factorial designs\n% FORMAT Vi = spm_get_vc(I,factor)\n% I         - n x m matrix of factor level indicators\n%             I(n,i) is the level of factor i for observation n\n% factor(i) - structure array of sphericity assumptions for each factor\n% .variance - 1 for different variance among levels of factor i\n% .dept     - 1 for dependencies within levels of factor i\n%\n% Vi        - cell vector of covariance components\n%__________________________________________________________________________\n%\n% spm_get_vc generates variance components for a given design. For each\n% factor, the user specifies whether its levels have identical variances\n% and are independent. The individual components for each factor are\n% combined into covariance components by using the Kronecker tensor\n% product. If there are unequal number of observations at different levels,\n% the function specifies covariance components for a full factorial design\n% first and subsequently removes unwanted rows and columns from the\n% covariance matrices.\n%\n% The functionality of spm_get_vc is similar to that of spm_non_sphericity.\n% The difference is that spm_get_vc can accommodate any number of factors\n% and is more general, because it can cope with different number of\n% observations under different levels of a factor.\n%__________________________________________________________________________\n% Copyright (C) 2006 Freiburg Brain Imaging \n% Copyright (C) 2008-2013 Wellcome Trust Centre for Neuroimaging\n \n% Volkmar Glauche\n% $Id: spm_get_vc.m 5293 2013-03-01 16:41:46Z guillaume $\n \n\n%-Numbers of scans and factors\n%--------------------------------------------------------------------------\n[nscan,nfactor] = size(I);\n \n%-Make sure each row of Iin is unique\n%==========================================================================\n[Iu,Ii,Ij]  = unique(I,'rows');\nif size(Iu,1) < nscan\n    nfactor = nfactor + 1;\n    uf      = zeros(nscan, 1);\n    for k = 1:max(Ij)\n        uf(Ij==k) = 1:sum(Ij==k);\n    end\n    I       = [I uf];\nend\nnlevel      = max(I);\n \n%-Non-sphericity assumptions\n%--------------------------------------------------------------------------\n% First factor is replications, assume identical variance and independence.\n% Pad with zeroes in case there are less than nfactor factors specified.\nvariance    = [0 cat(2, factor.variance) zeros(1,nfactor)];\ndept        = [0 cat(2, factor.dept) zeros(1,nfactor)];\n\n% (i) generate generic index\n%==========================================================================\nIgen = zeros(prod(nlevel), nfactor);\nIgen(:,1) = kron(ones(1,prod(nlevel(2:end))),1:nlevel(1))';\nfor cf = 2:(nfactor-1)\n    Igen(:,cf) = kron(ones(1,prod(nlevel((cf+1):end))),kron(1:nlevel(cf),ones(1,prod(nlevel(1:(cf-1))))))';\nend        \nIgen(:,nfactor) = kron(1:nlevel(nfactor),ones(1,prod(nlevel(1:(nfactor-1)))))';\n        \n% (ii) generate error variance components\n%==========================================================================\nVi = {};\nfor f=1:nfactor\n    \n    % identical/non-identical variances\n    % for each factor, create a single variance component if variances are\n    % identical across levels, and level specific variance components if\n    % variances are non-identical\n    %----------------------------------------------------------------------\n    nVi = {};\n    if ~variance(f)\n        nVi{1} = speye(nlevel(f),nlevel(f));\n    else\n        for l1=1:nlevel(f)\n            nVi{l1} = sparse(l1,l1,1,nlevel(f),nlevel(f));\n        end\n    end\n    if dept(f)\n        for l1 = 1:nlevel(f)\n            for l2 = 1:(l1-1)\n                nVi{end+1} = sparse([l1 l2],[l2 l1],1,nlevel(f), ...\n                                         nlevel(f));\n            end\n        end\n    end\n    \n    % combine current factor components with previous ones, thus building\n    % up covariance components block by block\n    %----------------------------------------------------------------------\n    if isempty(Vi)\n        Vi = nVi;\n    else\n        oVi = Vi;\n        Vi = {};\n        for nv = 1:numel(nVi)\n            for ov = 1:numel(oVi)\n                Vi{end+1} = kron(nVi{nv}, oVi{ov});\n            end\n        end\n    end\nend\n \n% (iii) sort out rows/columns & remove all-zero variance components\n%==========================================================================\n[unused,ind] = ismember(I,Igen,'rows');\naz = false(size(Vi));\n \nfor cVi = 1:numel(Vi)\n    Vi{cVi} = Vi{cVi}(ind,ind);\n    az(cVi) = full(all(Vi{cVi}(:) == 0));\nend\nVi = Vi(~az);\n \ndupl = false(size(Vi));\nfor cVi = 1:numel(Vi)\n    if ~dupl(cVi)\n        for cVi1 = (cVi+1):numel(Vi)\n            dupl(cVi1) = dupl(cVi1)||full(all(Vi{cVi}(:) == Vi{cVi1}(:)));\n        end\n    end\nend\nVi = Vi(~dupl);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_get_vc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5969708380849319}}
{"text": "function res = imGeodesicPropagation(img, varargin)\n%IMGEODESICPROPAGATION Compute geodesic propagation for each foreground pixel\n%\n%   RES = imGeodesicPropagation(IMG);\n%   IMG is a binary image. For each foreground pixel, the geodesic\n%   progagation is defined as the maximum geodesic distance to another\n%   pixel of the foreground. If the foreground is not connected this\n%   distance equals infinity.\n%\n%   RES = imGeodesicPropagation(IMG, WEIGHTS);\n%   use different weights for the computation of distances. See\n%   imChamferDistance for further details.\n%\n%   Note:\n%   * As the algorithm propagates geodesic distances from each foreground\n%       pixel, the computation time may be expensive.\n%   * the function is defined for both 2D and 3D images\n%\n%\n%   Example \n%     % Compute geodesic propagation in a L-shape\n%     img = zeros(20, 20);\n%     img(4:16, 4:9) = 1;\n%     img(11:16, 4:16) = 1;\n%     prop = imGeodesicPropagation(img);\n%     imagesc(prop);\n%     colormap([1 1 1 ; jet]);\n%\n%     % Compute geodesic propagation in a set of particles\n%     prop = zeros(size(img));\n%     lbl = bwlabel(img);\n%     for i = 1:max(lbl(:))\n%         prop = max(prop, imGeodesicPropagation(lbl==i));\n%     end\n%     imagesc(prop);\n%     colormap([1 1 1 ; jet]);\n%\n%   See also\n%   imGeodesics, imGeodesicDistanceMap, imGeodesicRadius, imGeodesicExtremities\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2009-05-22,    using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009 INRA - Cepia Software Platform.\n\nimg = img > 0;\nres = zeros(size(img));\n\ndim = size(img);\nif length(dim) == 2\n    for i = 1:dim(1)\n        for j = 1:dim(2)\n            if ~img(i,j)\n                continue;\n            end\n            \n            marker = false(size(img));\n            marker(i, j) = true;\n            \n            dist = imGeodesicDistanceMap(img, marker, varargin{:});\n            res(i, j) = max(dist(img));\n        end\n    end\n    \nelseif length(dim) == 3\n    for k = 1:dim(3)\n        for j = 1:dim(2)\n            for i = 1:dim(1)\n                if ~img(i,j,k)\n                    continue;\n                end\n                \n                marker = false(size(img));\n                marker(i, j, k) = true;\n                \n                dist = imGeodesicDistanceMap3d(img, marker, varargin{:});\n                res(i, j, k) = max(dist(img));\n            end\n        end\n    end\n\nelse\n    error('Requires a 2D or a 3D image');\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/imGeodesics/imGeodesicPropagation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.5968930778108887}}
{"text": "% Gets the 3D coordinates of the corners of a 3D bounding box.\n%\n% Args:\n%   bb3d - 3D bounding box struct.\n%\n% Returns:\n%   corners - 8x3 matrix of 3D coordinates.\n%\n% See:\n%   create_bounding_box_3d.m\n%\n% Author: Nathan Silberman (silberman@cs.nyu.edu)\nfunction corners = get_corners_of_bb3d(bb3d)\n  corners = zeros(8, 3);\n  \n  % Order the bases.\n  [~, inds] = sort(abs(bb3d.basis(:,1)), 'descend');\n  basis = bb3d.basis(inds, :);\n  coeffs = bb3d.coeffs(inds);\n  \n  [~, inds] = sort(abs(basis(2:3,2)), 'descend');\n  if inds(1) == 2\n    basis(2:3,:) = flipdim(basis(2:3,:), 1);\n    coeffs(2:3) = flipdim(coeffs(2:3), 2);\n  end\n  \n  % Now, we know the basis vectors are orders X, Y, Z. Next, flip the basis\n  % vectors towards the viewer.\n  basis = flip_towards_viewer(basis, repmat(bb3d.centroid, [3 1]));\n  \n  coeffs = abs(coeffs);\n\n  corners(1,:) = -basis(1,:) * coeffs(1) + basis(2,:) * coeffs(2) + basis(3,:) * coeffs(3);\n  corners(2,:) = basis(1,:) * coeffs(1) + basis(2,:) * coeffs(2) + basis(3,:) * coeffs(3);\n  corners(3,:) = basis(1,:) * coeffs(1) + -basis(2,:) * coeffs(2) + basis(3,:) * coeffs(3);\n  corners(4,:) = -basis(1,:) * coeffs(1) + -basis(2,:) * coeffs(2) + basis(3,:) * coeffs(3);\n  \n  corners(5,:) = -basis(1,:) * coeffs(1) + basis(2,:) * coeffs(2) + -basis(3,:) * coeffs(3);\n  corners(6,:) = basis(1,:) * coeffs(1) + basis(2,:) * coeffs(2) + -basis(3,:) * coeffs(3);\n  corners(7,:) = basis(1,:) * coeffs(1) + -basis(2,:) * coeffs(2) + -basis(3,:) * coeffs(3);\n  corners(8,:) = -basis(1,:) * coeffs(1) + -basis(2,:) * coeffs(2) + -basis(3,:) * coeffs(3);\n  \n  corners = corners + repmat(bb3d.centroid, [8 1]);\nend\n\nfunction normals = flip_towards_viewer(normals, points)\n  points = points ./ repmat(sqrt(sum(points.^2, 2)), [1, 3]);\n  \n  proj = sum(points .* normals, 2);\n  \n  flip = proj > 0;\n  normals(flip, :) = -normals(flip, :);\nend\n", "meta": {"author": "thusiyuan", "repo": "cooperative_scene_parsing", "sha": "0689c8057757a9efec387c272ddae9074861b07a", "save_path": "github-repos/MATLAB/thusiyuan-cooperative_scene_parsing", "path": "github-repos/MATLAB/thusiyuan-cooperative_scene_parsing/cooperative_scene_parsing-0689c8057757a9efec387c272ddae9074861b07a/evaluation/vis/mBB/get_corners_of_bb3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.5968705076428882}}
{"text": "function [centers, mincenter, mindist, lower, computed] = anchors(firstcenter,k,data)\n% choose k centers by the furthest-first method\n% URL: http://cseweb.ucsd.edu/~elkan/fastkmeans.html\n\n[n,dim] = size(data);\ncenters = zeros(k,dim);\nlower = zeros(n,k);\nmindist = Inf*ones(n,1);\nmincenter = ones(n,1);\ncomputed = 0;\ncentdist = zeros(k,k);\n\nfor j = 1:k\n    if j == 1\n        newcenter = firstcenter;\n    else\n        [maxradius,i] = max(mindist);\n        newcenter = data(i,:);\n    end\n\n    centers(j,:) = newcenter;\n    centdist(1:j-1,j) = calcdist(centers(1:j-1,:),newcenter);\n    centdist(j,1:j-1) = centdist(1:j-1,j)';\n    computed = computed + j-1;\n    \n    inplay = find(mindist > centdist(mincenter,j)/2);\n    newdist = calcdist(data(inplay,:),newcenter);\n    computed = computed + size(inplay,1);\n    lower(inplay,j) = newdist;\n        \n    move = find(newdist < mindist(inplay));\n    shift = inplay(move);\n    mincenter(shift) = j;\n    mindist(shift) = newdist(move);\nend\n", "meta": {"author": "adikhosla", "repo": "feature-extraction", "sha": "290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8", "save_path": "github-repos/MATLAB/adikhosla-feature-extraction", "path": "github-repos/MATLAB/adikhosla-feature-extraction/feature-extraction-290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8/util/kmeansFast/anchors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5968704968396331}}
{"text": "function [X] = DCA(networks, dim, rsp, maxiter)\n\tQ = [];\n\tfor i = 1 : length(networks)\n\t\tfileID = char(strcat('../network/', networks(i), '.txt'));\n\t\tnet = load(fileID);\n\t\ttQ = diffusionRWR(net, maxiter, rsp);\n\t\tQ = [Q, tQ];\n\tend\n\n\tnnode = size(Q, 1);\n\talpha = 1 / nnode;\n\tQ = log(Q + alpha) - log(alpha);\n\n\tQ = Q * Q';\n\t[U, S] = svds(Q, dim);\t\n\tX = U * sqrt(sqrt(S));\nend\n", "meta": {"author": "luoyunan", "repo": "DTINet", "sha": "725c5d04db5cc342eb4d84bce2872db0cfd6da8c", "save_path": "github-repos/MATLAB/luoyunan-DTINet", "path": "github-repos/MATLAB/luoyunan-DTINet/DTINet-725c5d04db5cc342eb4d84bce2872db0cfd6da8c/src/DCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.596870496388387}}
{"text": "function nonlocalarr = blockmatch(patchmat,neighborindarr,neighbornumarr,selfindarr,para)\n%BLOCKMATCH Block matching of patches with non-local similarity.\n%   nonlocalarr=BLOCKMATCH(patchmat,neighborindarr,neighbornumarr,\n%   selfindarr,para) returns the indexes of the patches with non-local\n%   similarity.\n%   See slao WNNM_IMDENOISE.\ngridsize = length(neighbornumarr);\n\nnonlocalarr = zeros([para.patchnum,gridsize],'uint32');\nfor i = 1:gridsize\n    patch = patchmat(:,selfindarr(i)); % key patch\n    neighbors = patchmat(:,neighborindarr(1:neighbornumarr(i),i)); % all neighbors\n    distance = sum(bsxfun(@minus,neighbors,patch).^2); % ell_2 distance\n    [~,ascendind] = sort(distance); % sort distance in an ascending order\n    % indexes of the most similar (shortest distance) para.patchnum of neighbors\n    nonlocalarr(:,i) = neighborindarr(ascendind(1:para.patchnum),i);\nend\n\nend\n\n    ", "meta": {"author": "liuyang12", "repo": "DeSCI", "sha": "fc9fddddbe7a6d503301e79ead7eb599c2d5db39", "save_path": "github-repos/MATLAB/liuyang12-DeSCI", "path": "github-repos/MATLAB/liuyang12-DeSCI/DeSCI-fc9fddddbe7a6d503301e79ead7eb599c2d5db39/packages/denoiser/WNNM/wnnm_imdenoise/blockmatch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5968704907611359}}
{"text": "% Description:\n%\n%     Create a design matrix for group-covariate interactions.\n%\n% Syntax:\n%\n%     [ X, terms ] = mGC2X(groups, covariates, a, b)\n%\n% Inputs:\n%\n%     groups     - [ N x G ] (int)    - columns of qualitative variables\n%     covariates - [ N x C ] (double) - columns of quantitative variables\n%     a          - [ 1 x 1 ] (int)    - group offset index for terms\n%     b          - [ 1 x 1 ] (int)    - covariate offset index for terms\n%     options    - [ 1 x P ] (cell)   - see Options\n%     columns    - [ T x 2 ] (int)    - see Details\n%\n% Outputs:\n%\n%     X     - [ N x M ] (double)\n%     terms - [ 1 x M ] (cell)\n%\n% Details:\n%\n%     The first column of the columns input in this case is an index into the\n%     columns of groups.  The second column of the columns input is an index\n%     into the columns of covariates.  For example, [ 2 1 ] would refer to an\n%     interaction between column 2 of groups and column 1 of covariates.\n%\n% Options:\n%\n%     'over-determined'  - use over-determined coding for the design matrix\n%     'sigma-restricted' - use sigma-restricted coding for the design matrix\n%     'verbose'          - display extra information to the command window\n%\n% Examples:\n%\n% Notes:\n%\n% Author(s):\n%\n%     William Gruner (williamgruner@gmail.com)\n%\n% References:\n%\n% Acknowledgements:\n%\n%     Many thanks to Dr. Erik Erhardt and Dr. Elena Allen of the Mind Research\n%     Network (www.mrn.org) for their continued collaboration.\n%\n% Version:\n%\n%     $Author: williamgruner $\n%     $Date: 2010-04-12 07:14:07 -0600 (Mon, 12 Apr 2010) $\n%     $Revision: 494 $\n\nfunction [ X, terms ] = mGC2X(groups, covariates, a, b, options, columns)\n    \n    if ~exist('a', 'var') || isempty(a)\n        a = 0;\n    end\n    \n    if ~exist('b', 'var') || isempty(b)\n        b = 0;\n    end\n    \n    if ~exist('options', 'var')\n        options = {};\n    end\n    \n    if ~exist('columns', 'var')\n        \n        columns = [];\n\n        for i = 1 : size(groups, 2)\n            for j = 1 : size(covariates, 2)\n                columns(end + 1, :) = [ i j ];\n            end\n        end\n\n    end\n    \n    terms = {};\n    X     = [];\n    \n    [ G, g ] = mG2X(groups, 0, intersect(options, ...\n        { 'over-determined' 'sigma-restricted' }));\n\n    if ~isempty(strmatch('verbose', options, 'exact'))\n        fprintf('\\n')\n    end\n    \n    for i = 1 : size(columns, 1)\n        \n        if ~isempty(strmatch('verbose', options, 'exact'))\n            fprintf('Factor %d%d represents the interaction between column %d of groups and column %d of covariates.\\n', ...\n                columns(i, 1) + a, columns(i, 2) + b, columns(i, 1), columns(i, 2))\n        end\n\n        I = mFindTerms(columns(i, 1), g);\n        x = G(:, I) .* repmat(covariates(:, columns(i, 2)), 1, length(I));\n        X = cat(2, X, x);\n\n        for j = 1 : length(I)\n            terms{end + 1} = columns(i, :) + [ a b ];\n        end\n        \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/27014-mancovan/mGC2X.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5968704752331223}}
{"text": "function [cepstra,aspectrum,pspectrum] = melfcc(samples, sr, varargin)\n%[cepstra,aspectrum,pspectrum] = melfcc(samples, sr[, opts ...])\n%  Calculate Mel-frequency cepstral coefficients by:\n%   - take the absolute value of the STFT\n%   - warp to a Mel frequency scale\n%   - take the DCT of the log-Mel-spectrum\n%   - return the first <ncep> components\n%  This version allows a lot of options to be controlled, as optional \n%  'name', value pairs from the 3rd argument on: (defaults in parens)\n%    'wintime' (0.025): window length in sec\n%    'hoptime' (0.010): step between successive windows in sec\n%    'numcep'     (13): number of cepstra to return\n%    'lifterexp' (0.6): exponent for liftering; 0 = none; < 0 = HTK sin lifter\n%    'sumpower'    (1): 1 = sum abs(fft)^2; 0 = sum abs(fft)\n%    'preemph'  (0.97): apply pre-emphasis filter [1 -preemph] (0 = none)\n%    'dither'      (0): 1 = add offset to spectrum as if dither noise\n%    'minfreq'     (0): lowest band edge of mel filters (Hz)\n%    'maxfreq'  (4000): highest band edge of mel filters (Hz)\n%    'nbands'     (40): number of warped spectral bands to use\n%    'bwidth'    (1.0): width of aud spec filters relative to default\n%    'dcttype'     (2): type of DCT used - 1 or 2 (or 3 for HTK or 4 for feac)\n%    'fbtype'  ('mel'): frequency warp: 'mel','bark','htkmel','fcmel'\n%    'usecmp'      (0): apply equal-loudness weighting and cube-root compr.\n%    'modelorder'  (0): if > 0, fit a PLP model of this order\n%    'broaden'     (0): flag to retain the (useless?) first and last bands\n%    'useenergy'   (0): overwrite C0 with true log energy\n% The following non-default values nearly duplicate Malcolm Slaney's mfcc\n% (i.e. melfcc(d,16000,opts...) =~= log(10)*2*mfcc(d*(2^17),16000) )\n%       'wintime': 0.016\n%     'lifterexp': 0\n%       'minfreq': 133.33\n%       'maxfreq': 6855.6\n%      'sumpower': 0\n% The following non-default values nearly duplicate HTK's MFCC\n% (i.e. melfcc(d,16000,opts...) =~= 2*htkmelfcc(:,[13,[1:12]])'\n%  where HTK config has PREEMCOEF = 0.97, NUMCHANS = 20, CEPLIFTER = 22, \n%  NUMCEPS = 12, WINDOWSIZE = 250000.0, USEHAMMING = T, TARGETKIND = MFCC_0)\n%     'lifterexp': -22\n%        'nbands': 20\n%       'maxfreq': 8000\n%      'sumpower': 0\n%        'fbtype': 'htkmel'\n%       'dcttype': 3\n% For more detail on reproducing other programs' outputs, see\n% http://www.ee.columbia.edu/~dpwe/resources/matlab/rastamat/mfccs.html\n%\n% 2005-04-19 dpwe@ee.columbia.edu after rastaplp.m.  \n% Uses Mark Paskin's process_options.m from KPMtools\n% $Header: /Users/dpwe/matlab/rastamat/RCS/melfcc.m,v 1.3 2012/09/03 14:01:26 dpwe Exp dpwe $\n\nif nargin < 2;   sr = 16000;    end\n\n% Parse out the optional arguments\n[wintime, hoptime, numcep, lifterexp, sumpower, preemph, dither, ...\n minfreq, maxfreq, nbands, bwidth, dcttype, fbtype, usecmp, modelorder, ...\n broaden, useenergy] = ...\n    process_options(varargin, 'wintime', 0.025, 'hoptime', 0.010, ...\n          'numcep', 13, 'lifterexp', 0.6, 'sumpower', 1, 'preemph', 0.97, ...\n\t  'dither', 0, 'minfreq', 0, 'maxfreq', 4000, ...\n\t  'nbands', 40, 'bwidth', 1.0, 'dcttype', 2, ...\n\t  'fbtype', 'mel', 'usecmp', 0, 'modelorder', 0, ...\n          'broaden', 0, 'useenergy', 0);\n\nif preemph ~= 0\n  samples = filter([1 -preemph], 1, samples);\nend\n\n% Compute FFT power spectrum\n[pspectrum,logE] = powspec(samples, sr, wintime, hoptime, dither);\n\naspectrum = audspec(pspectrum, sr, nbands, fbtype, minfreq, maxfreq, sumpower, bwidth);\n\nif (usecmp)\n  % PLP-like weighting/compression\n  aspectrum = postaud(aspectrum, maxfreq, fbtype, broaden);\nend\n\nif modelorder > 0\n\n  if (dcttype ~= 1) \n    disp(['warning: plp cepstra are implicitly dcttype 1 (not ', num2str(dcttype), ')']);\n  end\n  \n  % LPC analysis \n  lpcas = dolpc(aspectrum, modelorder);\n\n  % convert lpc to cepstra\n  cepstra = lpc2cep(lpcas, numcep);\n\n  % Return the auditory spectrum corresponding to the cepstra?\n%  aspectrum = lpc2spec(lpcas, nbands);\n  % else return the aspectrum that the cepstra are based on, prior to PLP\n\nelse\n  \n  % Convert to cepstra via DCT\n  cepstra = spec2cep(aspectrum, numcep, dcttype);\n\nend\n\ncepstra = lifter(cepstra, lifterexp);\n\nif useenergy\n  cepstra(1,:) = logE;\nend\n  \n\n", "meta": {"author": "stephencwelch", "repo": "Perceptual-Coding-In-Python", "sha": "2993f57570663768c02745019185091a23f021fe", "save_path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python", "path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python/Perceptual-Coding-In-Python-2993f57570663768c02745019185091a23f021fe/matlabCode/bark_domain_exploration/rastamat/melfcc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.5968622208353669}}
{"text": "function [ m, p, t ] = naca4_mpt ( code )\n\n%*****************************************************************************80\n%\n%% NACA4_MPT returns the parameters stored in a NACA 4 digit airfoil code.\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%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer CODE, the NACA4 code.\n%    0 <= CODE <= 9999.\n%\n%    Output, real M, the maximum camber, as a percentage of the chord length.\n%    0 <= M <= 1.0.\n%\n%    Output, real P, the relative distance of the occurrence of the maximum \n%    camber from the beginning of the chord.\n%    0 <= P <= 1.0.\n%\n%    Output, real T, the maximum thickness relative to the chord length.\n%    0 <= T <= 1.0.\n%\n  if ( code < 0 || 9999 < code )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'NACA4_MPT - Fatal error!\\n' );\n    fprintf ( 1, '  CODE should be an integer between 0 and 9999.\\n' );\n    error ( 'NACA4_MPT - Fatal error!' );\n  end\n\n  m = floor ( code / 1000 );\n  code = code - m * 1000;\n  m = m / 100.0;\n\n  p = floor ( code / 100 );\n  code = code - p * 100;\n  p = p / 10.0;\n\n  t = code / 100.0;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/naca/naca4_mpt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303384097948, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.596783200039092}}
{"text": "function tests = test_VBA_random\n% Unit Tests for VBA_random\n\ntests = functiontests (localfunctions);\n\n% -------------------------------------------------------------------------   \nfunction test_arbitrary (testCase)\n    K = 3;\n    p = rand (K, 1);\n    p = p / sum (p);\n    vals_1 = 'abc';\n    vals_k = ['ab'; 'cd'; 'ef'];\n    M = size(vals_k, 2);\n    \n    % should fail on invalid parameters\n    shouldFail = @() VBA_random ('Arbitrary', [0.5; 0.5], vals_1);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    shouldFail = @() VBA_random ('Arbitrary', zeros (3, 1), vals_1);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    shouldFail = @() VBA_random ('Arbitrary', p, vals_k, 8, 8);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    \n    % should return one sample by default\n    actual = VBA_random ('Arbitrary', p, vals_1);\n    testCase.verifyNumElements (actual, 1);\n    actual = VBA_random ('Arbitrary', p, vals_k);\n    testCase.verifySize (actual, [M, 1]);\n    \n    % should return matrix on scalar N\n    N = 8;\n    actual = VBA_random ('Arbitrary', p, vals_1, N);\n    testCase.verifySize (actual, [N, N]);\n    actual = VBA_random ('Arbitrary', p, vals_k, N);\n    testCase.verifySize (actual, [M, N]);\n    \n    % should return matrix of asked dimension\n    N = num2cell (1 + randi (5, 1, 4));\n    actual = VBA_random ('Arbitrary', p, vals_1, N{:});\n    testCase.verifySize (actual, [N{:}]);\n    \n    % should return sample according to distribution\n    % + univariate\n    actual = VBA_random ('Arbitrary', p, vals_1, 1, 1e6);   \n    % - support\n    testCase.verifyEqual (unique (actual), vals_1);\n    % + density\n    for i = 1 : numel (p)\n        testCase.verifyEqual (mean (actual == vals_1(i)), p(i), 'AbsTol', 1e-2);\n    end \n    % + multivariate\n    actual = VBA_random ('Arbitrary', p, vals_k, 1e6);   \n    % - support\n    testCase.verifyEqual (unique (actual', 'rows'), vals_k);\n    % + density\n    for i = 1 : numel (p)\n        isEq = all(bsxfun(@eq, actual, vals_k(i,:)'));\n        testCase.verifyEqual (mean (isEq, 2), p(i), 'AbsTol', 1e-2);\n    end \n\n% -------------------------------------------------------------------------   \nfunction test_bernoulli (testCase)\n    p = rand ();\n\n    % should fail on invalid probability\n    shouldFail = @() VBA_random ('Bernoulli', -3);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    % should fail on invalid size\n    shouldFail = @() VBA_random ('Bernoulli', rand (3), 2);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n\n    % should return one sample by default\n    actual = VBA_random ('Bernoulli', p);\n    testCase.verifyNumElements (actual, 1);\n    \n    % should return matrix on scalar N\n    N = 3;\n    actual = VBA_random ('Bernoulli', p, N);\n    testCase.verifySize (actual, [N, N]);\n    \n    % should return matrix of asked dimension\n    N = num2cell (1 + randi (5, 1, 4));\n    actual = VBA_random ('Bernoulli', p,  N{:});\n    testCase.verifySize (actual, [N{:}]);\n    \n    % should return matrix on matrix p\n    actual = VBA_random ('Bernoulli', rand (N{:}));\n    testCase.verifySize (actual, [N{:}]);\n    \n    % should return sample according to distribution\n    actual = VBA_random ('Bernoulli', p, 1, 1e6);   \n    % + support\n    testCase.verifyEqual (unique (actual), [0 1]);\n    % + mean\n    testCase.verifyEqual (mean (actual), p, 'AbsTol', 1e-2);\n    \n    % should deal with nan\n    actual = VBA_random ('Bernoulli', [p NaN]);   \n    testCase.verifyTrue (~ isnan (actual(1)));\n    testCase.verifyTrue (isnan (actual(2)));\n    \n% -------------------------------------------------------------------------   \nfunction test_binomial (testCase)\n    n = 2;\n    p = rand ();\n\n    % should fail on invalid parameters\n    shouldFail = @() VBA_random ('Binomial',0, p);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    shouldFail = @() VBA_random ('Binomial',n, -3);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n\n    % should return one sample by default\n    actual = VBA_random ('Binomial', n, p);\n    testCase.verifyNumElements (actual, 1);\n    \n    % should return matrix on scalar N\n    N = 3;\n    actual = VBA_random ('Binomial', n, p, N);\n    testCase.verifySize (actual, [N, N]);\n     \n    % should return matrix of asked dimension\n    N = num2cell (1 + randi (5, 1, 4));\n    actual = VBA_random ('Binomial', n, p,  N{:});\n    testCase.verifySize (actual, [N{:}]);\n    \n    % should return sample according to distribution\n    actual = VBA_random ('Binomial', n, p, 1, 1e6);   \n    % + support\n    testCase.verifyEqual (unique (actual), 0 : n);\n\n    % + mean\n    testCase.verifyEqual (mean (actual), n * p, 'AbsTol', 1e-2);\n    % + variance\n    testCase.verifyEqual (var (actual), n * p * (1 - p), 'AbsTol', 1e-2);\n    % + density\n    for k = 0 : n\n        expected = nchoosek (n, k) * (p ^ k) * ((1 - p) ^ (n - k));\n        testCase.verifyEqual (mean (actual == k), expected, 'AbsTol', 1e-2);\n    end  \n    \n% -------------------------------------------------------------------------   \nfunction test_categorical (testCase)\n    K = 3;\n    p = rand (K, 1);\n    p = p / sum(p);\n\n    % should fail on invalid parameters\n    shouldFail = @() VBA_random ('Categorical', zeros (K, 1));\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    \n    % should return one sample by default\n    actual = VBA_random ('Categorical', p);\n    testCase.verifyNumElements (actual, 1);\n    \n    % should return matrix on scalar N\n    N = 3;\n    actual = VBA_random ('Categorical', p, N);\n    testCase.verifySize (actual, [N, N]);\n     \n    % should return matrix of asked dimension\n    N = num2cell (1 + randi (5, 1, 4));\n    actual = VBA_random ('Categorical', p,  N{:});\n    testCase.verifySize (actual, [N{:}]);\n    \n    % should return sample according to distribution\n    actual = VBA_random ('Categorical', p, 1, 1e6);   \n    % + support\n    testCase.verifyEqual (unique (actual), 1 : K);\n    % + mean\n    testCase.verifyEqual (mean (actual), (1 : K) * p, 'AbsTol', 1e-2);\n   % + density\n    for k = 1 : K\n        testCase.verifyEqual (mean (actual == k), p(k), 'AbsTol', 1e-2);\n    end\n\n    % -------------------------------------------------------------------------   \nfunction test_dirichlet (testCase)\n    K = 3;\n    alpha = 1 + randi (10, K, 1);\n\n    % should fail on invalid parameters\n    shouldFail = @() VBA_random ('Dirichlet', rand);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    shouldFail = @() VBA_random ('Dirichlet', alpha, 2, 3);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    \n    % should return one sample by default\n    actual = VBA_random ('Dirichlet', alpha);\n    testCase.verifySize (actual, [K, 1]);\n    \n    % should return N samples\n    N = 8;\n    actual = VBA_random ('Dirichlet', alpha, N);\n    testCase.verifySize (actual, [K, N]);\n    \n    % should return sample according to distribution\n    N = 1e6;\n    actual = VBA_random ('Dirichlet', alpha, N);   \n    % + support\n    testCase.verifyTrue (VBA_isInRange (actual, [0 1]));\n    testCase.verifyEqual (sum (actual), ones (1, N), 'AbsTol', 1e-13);\n    % + moments\n    [expected.m, expected.v] = VBA_dirichlet_moments(alpha);\n    testCase.verifyEqual (mean (actual, 2), expected.m , 'AbsTol', 1e-2);\n    testCase.verifyEqual (var (actual, [], 2), expected.v , 'AbsTol', 1e-2);\n\n\n% -------------------------------------------------------------------------   \nfunction test_gamma (testCase)\n    a = 10 * rand ();\n    b = 10 * rand ();\n\n    % should fail on invalid parameters\n    shouldFail = @() VBA_random ('Gamma', - 1, b);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    shouldFail = @() VBA_random ('Gamma', a, - 1);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    \n    % should return one sample by default\n    actual = VBA_random ('Gamma', a, b);\n    testCase.verifyNumElements (actual, 1);\n     \n    % should return matrix on scalar N\n    N = 3;\n    actual = VBA_random ('Gamma', a, b, N);\n    testCase.verifySize (actual, [N, N]);\n     \n    % should return matrix of asked dimension\n    N = num2cell (1 + randi (5, 1, 4));\n    actual = VBA_random ('Gamma', a, b,  N{:});\n    testCase.verifySize (actual, [N{:}]);\n    \n    % should return sample according to distribution\n    actual = VBA_random ('Gamma', a, b, 1, 1e6);   \n    % + support\n    testCase.verifyTrue (all (actual > 0));\n    % + mean\n    testCase.verifyEqual (mean (actual), a * b, 'RelTol', 1e-2);\n    % + variance\n    testCase.verifyEqual (var (actual), a * b ^ 2, 'RelTol', 1e-2);\n \n  % -------------------------------------------------------------------------   \nfunction test_gaussian (testCase)\n    \n    % + univariate\n    mu_1 = randn ();\n    Sigma_1 = rand () ^ 2;\n    % + multivariate\n    k = 2;\n    mu_k = randn (k, 1);\n    Sigma_k = rand (k);\n    Sigma_k = Sigma_k * Sigma_k';\n    \n     % should fail on invalid parameters\n    shouldFail = @() VBA_random ('Gaussian', mu_1, Sigma_k);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    shouldFail = @() VBA_random ('Gaussian', mu_k, Sigma_k, 2, 2);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    \n    % should return one sample by default\n    % + univariate\n    actual = VBA_random ('Gaussian', mu_1, Sigma_1);\n    testCase.verifyNumElements (actual, 1);\n    % + multivariate\n    actual = VBA_random ('Gaussian', mu_k, Sigma_k);\n    testCase.verifySize (actual, [k, 1]);\n\n    % should return matrix on scalar N\n    N = 5;\n    % + univariate\n    actual = VBA_random ('Gaussian', mu_1, Sigma_1, N);\n    testCase.verifySize (actual, [N, N]);\n    % + multivariate\n    actual = VBA_random ('Gaussian', mu_k, Sigma_k, N);\n    testCase.verifySize (actual, [k, N]);\n     \n    % should return matrix of asked dimension\n    N = num2cell (1 + randi (5, 1, 4));\n    actual = VBA_random ('Gaussian', mu_1, Sigma_1,  N{:});\n    testCase.verifySize (actual, [N{:}]);\n    \n    % should return sample according to distribution\n    % + univariate\n    actual = VBA_random ('Gaussian', mu_1, Sigma_1, 1, 1e6);   \n    % - mean\n    testCase.verifyEqual (mean (actual), mu_1, 'AbsTol', 1e-2);\n    % - variance\n    testCase.verifyEqual (var (actual), Sigma_1, 'AbsTol', 1e-2);\n    % + multivariate\n    actual = VBA_random ('Gaussian', mu_k, Sigma_k, 1e6);   \n    % - mean\n    testCase.verifyEqual (mean (actual, 2), mu_k, 'AbsTol', 1e-2);\n    % - variance\n    testCase.verifyEqual (cov (actual'), Sigma_k, 'AbsTol', 1e-2);\n  \n% -------------------------------------------------------------------------   \nfunction test_multinomial (testCase)\n    n = 2;\n    K = 3;\n    p = rand (K, 1);\n    p = p / sum(p);\n    \n    % should fail on invalid parameters\n    shouldFail = @() VBA_random ('Multinomial',0, p);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    shouldFail = @() VBA_random ('Multinomial',n, .5);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    shouldFail = @() VBA_random ('Multinomial',n, [1; 1]);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n    shouldFail = @() VBA_random ('Multinomial',n, p, 8, 8);\n    testCase.verifyError(shouldFail, 'VBA:invalidInput');\n\n    % should return one sample by default\n    actual = VBA_random ('Multinomial', n, p);\n    testCase.verifySize (actual, [K, 1]);\n    \n    % should return matrix on scalar N\n    N = 8;\n    actual = VBA_random ('Multinomial', n, p, N);\n    testCase.verifySize (actual, [K, N]);\n    \n    % should return sample according to distribution\n    N = 1e6;\n    actual = VBA_random ('Multinomial', n, p, N);   \n    % + support\n    testCase.verifyEqual (unique (actual)', 0 : n);\n    testCase.verifyEqual (sum (actual), n * ones (1, N), 'AbsTol', 1e-13);\n    % + density\n    for i = 1 : K\n        expected = n * p(i);\n        testCase.verifyEqual (mean (actual(i, :)), expected, 'AbsTol', 1e-2);\n        expected = n * p(i) * (1 - p(i));\n        testCase.verifyEqual (var (actual(i, :)), expected, 'AbsTol', 1e-2);\n    end  \n    \n    % should deal with nan\n    actual = VBA_random ('Multinomial', n, nan(K, 1));\n    testCase.verifySize (actual, [K, 1]);\n    testCase.verifyTrue (all (isnan (actual)));\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/tests/utils/test_VBA_random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.5967831764190483}}
{"text": "function eps = eps_RCUs( i_s, n, r )\neps = mean( exp( - max(0, i_s - log(2^(n*r)-1) ) ) ); % avg pr err \n% eps = mean( exp( - max(0, i_s - log(2^(n*r)-1)-log(2)) ) ); % max pr err\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/block-fading-PAT-SNN/eps_RCUs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5967481013902}}
{"text": "%% \n% \\documentclass[12pt]{article}\n%\n% \\title{ODEbox: A Toolbox for Ordinary Differential Equations\\\\\n% Sturm Liouville Example 2\\\\\n% The Mathieu Differential Equation}\n% \n% \\author{Matthew Harker and Paul O'Leary\\\\\n% Institute for Automation\\\\\n% University of Leoben\\\\\n% A-8700 Leoben,\n% Austria\\\\\n% URL: automation.unileoben.ac.at\\\\\n% \\\\\n% Original: January 9, 2013\\\\\n% $\\copyright$ 2013\\\\\n% \\\\\n% Last Modified: \\today}\n%%\n% \\section{The Mathieu Differential Equation}\n%\n% This example addresses the solution of the Mathieu differential equation.\n% This equation occurs in conjunction with the modelling of the vibration\n% of a ellptical membrane. The problem has no known analytical solution.\n% %\n% \\begin{equation}\n%    -\\ddot{y} + 2 \\,r \\, \\cos( 2 \\, x )= \\lambda \\, y\n%    \\hspace{5mm}\n%    \\text{with}\n%    \\hspace{5mm}\n%    y(0) = 0}\n%   \\hspace{5mm}\n%   \\text{and} \n%   \\hspace{5mm}\n%   \\dot{y}(\\pi) = 0\n% \\end{equation}\n% %\n% in the closed interval $0 \\leq x \\leq \\pi$.\n%\n%%\n% \\section{tidy up the Workspace}\n%\nclear all;\nclose all;\nsetUpGraphics;\n%%\n% \\section{Define the Nodes and Compute the Basis Functions}\n%\n% Define the number of nodes and the number of basis functions used.\n%\nnoPts = 1000;\nnoBfs = round( noPts/2);\n%%\n% Compute the Chebyshev points, but scaled to form a closed interval\n% $0 \\leq x \\leq \\pi$.\n%\nx = dopNodes( noPts, 'chebyends' );\nx = pi * (x + 1)/2;\n%%\n% Synthesize a complete set of basis functions\n%\nB = dop(x);\n%%\n% \\subsection{Generate the Differentiating Matrix}\n%\n% Synthesize the differentiating matrix with support length $l_s$\n%\nls = 13;\nD = dopDiffLocal( x, ls, ls );\n%%\n% \\subsection{Define the Constraints and Compute the Admissible Functions}\n%\n% Define the constraints\n%\nC = zeros( noPts, 2 );\nC(1,1) = 1;\nC(end,end) = 1;\n%%\n% Compute the set of constrained basis functions, i.e., admissible\n% functions.\n%\nBc = dopConstrain( C, B );\n%%\n% Trucate the basis functions\n%\nBc = Bc(:,1:noBfs);\n%\n%%\n% \\section{Setup the Sturm-Liouville Matrix Linear Differential Operator}\n%\n% Setup the Linear differential operator for the Mathieu differential\n% equation.\n%\nc1 = 0;\nc2 = -50;\ngx = diag(c1 + c2 * cos(2*x)) ;\nL = Bc' * (D * D - gx )* Bc;\n%\n%%\n% \\section{Solve the Eigenvector Problem}\n%\n% Solve the eigenvalue problem\n%\n[Vec, Val] = eig( L );\nvals = -diag( Val );\n%%\n% and sort the solutions.\n%\n[vals, inds] = sort(vals);\nVec = Vec(:,inds);\n%%\n% and compute the final eigenfunctions.\n%\nsols = Bc * Vec;\n%%\n% \\section{Close Pair of Eigenvalues}\n%\n% The Mathieu differential equation as paramatized here is known to produce\n% a close pair of eigenvalues. We now show this pair.\n%\nnoEVals = 2;\nfor k=1:noEVals\n    numStr = num2str(vals(k),'%2.10E') ;\n    str = ['\\lambda_{', int2str(k-1), '} = ', numStr]\nend;\n%noV = length(vals);\n%n = [1:noV]';\n%valsT = n.^2;\n%\n%%\n% \\section{Plot a Few Eigenfunctions}\n%\nsetUpGraphics(10)\nFigureSize=[1 1 10 6];\nset(0,'DefaultFigureUnits','centimeters');\nset(0,'DefaultFigurePosition',FigureSize);\nset(0,'DefaultFigurePaperUnits','centimeters');\nset(0,'DefaultFigurePaperPosition',FigureSize);\nMyAxesPosition=[0.18 0.17 0.8 0.8];\nset(0,'DefaultaxesPosition',MyAxesPosition);\n%\nfig1 = figure;\nplot( x, sols(:,1), 'r');\nhold on\nplot( x, sols(:,2), 'g');\nplot( x, sols(:,3), 'b');\nplot( x, sols(:,4), 'k');\ngrid on;\nxlabel('$$x$$');\nylabel('$$y8x)$$');\naxis([0,pi,-0.1,0.1]);\n%\n% \\caption{The first $4$ eigen functions of the Mathieu differential equation.}\n%%\n%\nsetUpGraphics(10)\nFigureSize=[1 1 10 10];\nset(0,'DefaultFigureUnits','centimeters');\nset(0,'DefaultFigurePosition',FigureSize);\nset(0,'DefaultFigurePaperUnits','centimeters');\nset(0,'DefaultFigurePaperPosition',FigureSize);\nMyAxesPosition=[0.16 0.17 0.8 0.8];\nset(0,'DefaultaxesPosition',MyAxesPosition);\n%\nfig2 = figure;\nP1 = [0.16 0.4 0.8 0.55] ;\nA = axes('position',P1);\nimagesc( log10(abs(Vec) ));\ncolorbar;\nylabel(['Basis function number $$m$$, $$n_b = ',int2str(noBfs),'$$']);\nP2 = [0.16 0.1 0.615 0.25] ;\nA = axes('position',P2);\nplot( vals(1:noBfs), 'k');\nrange = axis;\naxis([0,noBfs,-1000,900000]);\ngrid on;\nxlabel('Eigenvector number $$n$$');\nylabel('$$\\lambda$$');\n%\n% \\caption{The Rayleigh-Ritz Spectrum of the Eigenfunvtions with respect to \n% the admissible functions and the eigenvalues for the Mathieu differential \n% equation.}\n%%\n% \\section{Save the Figure to Disk.}\nfileType = 'eps';\nprintFigure( fig1, ['SLEx2EigFnsNb',int2str(noBfs)], fileType);\nprintFigure( fig2, ['SLEx2SpectrumNb',int2str(noBfs)], fileType);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41354-ordinary-differential-equation-toolbox-odebox-version-1-1/ODEBoxV1-1/SturmLiouville/SturmLiouvilleEx2/SturmLiouville2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.5967417852525643}}
{"text": "function [ n_data, mu, sigma, x, fx ] = cauchy_cdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% CAUCHY_CDF_VALUES returns some values of the Cauchy CDF.\n%\n%  Discussion:\n%\n%    In Mathematica, the function can be evaluated by:\n%\n%      Needs[\"Statistics`ContinuousDistributions`\"]\n%      dist = CauchyDistribution [ mu, sigma ]\n%      CDF [ dist, 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 MU, the mean of the distribution.\n%\n%    Output, real SIGMA, the standard deviation of the distribution.\n%\n%    Output, real X, the argument of the function.\n%\n%    Output, real FX, the value of the function.\n%\n  n_max = 12;\n\n  fx_vec = [ ...\n     0.5000000000000000E+00, ...\n     0.8524163823495667E+00, ...\n     0.9220208696226307E+00, ...\n     0.9474315432887466E+00, ...\n     0.6475836176504333E+00, ...\n     0.6024163823495667E+00, ...\n     0.5779791303773693E+00, ...\n     0.5628329581890012E+00, ...\n     0.6475836176504333E+00, ...\n     0.5000000000000000E+00, ...\n     0.3524163823495667E+00, ...\n     0.2500000000000000E+00 ];\n\n  mu_vec = [ ...\n     0.1000000000000000E+01, ...  \n     0.1000000000000000E+01, ...  \n     0.1000000000000000E+01, ...  \n     0.1000000000000000E+01, ...  \n     0.1000000000000000E+01, ...  \n     0.1000000000000000E+01, ...  \n     0.1000000000000000E+01, ...  \n     0.1000000000000000E+01, ...  \n     0.2000000000000000E+01, ...  \n     0.3000000000000000E+01, ...  \n     0.4000000000000000E+01, ...  \n     0.5000000000000000E+01 ]; \n\n  sigma_vec = [ ...\n     0.5000000000000000E+00, ...  \n     0.5000000000000000E+00, ...\n     0.5000000000000000E+00, ...\n     0.5000000000000000E+00, ...\n     0.2000000000000000E+01, ...\n     0.3000000000000000E+01, ...\n     0.4000000000000000E+01, ...\n     0.5000000000000000E+01, ...\n     0.2000000000000000E+01, ...\n     0.2000000000000000E+01, ...\n     0.2000000000000000E+01, ...\n     0.2000000000000000E+01 ];\n\n  x_vec = [ ...\n     0.1000000000000000E+01, ...  \n     0.2000000000000000E+01, ...  \n     0.3000000000000000E+01, ...  \n     0.4000000000000000E+01, ...  \n     0.2000000000000000E+01, ...  \n     0.2000000000000000E+01, ...  \n     0.2000000000000000E+01, ...  \n     0.2000000000000000E+01, ...  \n     0.3000000000000000E+01, ...  \n     0.3000000000000000E+01, ...  \n     0.3000000000000000E+01, ...  \n     0.3000000000000000E+01 ];\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    mu = 0.0;\n    sigma = 0.0;\n    x = 0.0;\n    fx = 0.0;\n  else\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/cauchy_cdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.5967417688759915}}
{"text": "function [S2G, W, M2] = quadratureS2Grid(bandwidth, varargin)\n%\n% Syntax\n%   [S2G, W, M2] = quadratureS2Grid(M) quadrature grid of type chebyshev\n%   [S2G, W, M2] = quadratureS2Grid(M, 'gauss') quadrature grid of type gauss\n%\n\n\npersistent S2G_p;\npersistent W_p;\npersistent M2_p;\n\nif check_option(varargin, 'gauss')\n  load(fullfile(mtexDataPath,'vector3d','quadratureS2Grid_gauss.mat'),'gridIndex');\nelse\n  load(fullfile(mtexDataPath,'vector3d','quadratureS2Grid_chebyshev.mat'),'gridIndex');\nend\nindex = find(gridIndex.bandwidth >= bandwidth, 1);\nif isempty(index)\n  index = size(gridIndex,1);\n  warning('M is too large, instead we are giving you the largest quadrature grid we got.');\nend\n\nM2 = gridIndex.bandwidth(index);\n\nif ~isempty(M2_p) && M2_p == M2\n  S2G = S2G_p;\n  W = W_p;\n  M2 = M2_p;\n  \nelse\n  name = cell2mat(gridIndex.name(index));\n  if check_option(varargin, 'gauss')\n    data = load(fullfile(mtexDataPath,'vector3d','quadratureS2Grid_gauss.mat'),name);\n  else\n    data = load(fullfile(mtexDataPath,'vector3d','quadratureS2Grid_chebyshev.mat'),name);\n  end\n\n  data = data.(name);\n  S2G = vector3d.byPolar(data(:, 1), data(:, 2));\n  \n  if check_option(varargin, 'gauss')\n    W = data(:,3);\n  else\n    W = 4*pi/size(data, 1) .* ones(size(S2G));\n  end  \n  \n  \n  % store the data\n  S2G_p = S2G;\n  W_p = W;\n  M2_p = M2;    \nend\n\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/geometry_tools/quadratureS2Grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5967417574914516}}
{"text": "function [omckk,Tckk,Rckk] = compute_extrinsic_init_fisheye(x_kk,X_kk,fc,cc,kc,alpha_c)\n\n%compute_extrinsic\n%\n%[omckk,Tckk,Rckk] = compute_extrinsic_init_fisheye(x_kk,X_kk,fc,cc,kc,alpha_c)\n%\n%Computes the extrinsic parameters attached to a 3D structure X_kk given its projection\n%on the image plane x_kk and the intrinsic camera parameters fc, cc and kc.\n%Works with planar and non-planar structures.\n%\n%INPUT: x_kk: Feature locations on the images\n%       X_kk: Corresponding grid coordinates\n%       fc: Camera focal length\n%       cc: Principal point coordinates\n%       kc: Distortion coefficients\n%       alpha_c: Skew coefficient\n%\n%OUTPUT: omckk: 3D rotation vector attached to the grid positions in space\n%        Tckk: 3D translation vector attached to the grid positions in space\n%        Rckk: 3D rotation matrices corresponding to the omc vectors\n%\n%Method: Computes the normalized point coordinates, then computes the 3D pose\n%\n%Important functions called within that program:\n%\n%normalize_pixel: Computes the normalize image point coordinates.\n%\n%pose3D: Computes the 3D pose of the structure given the normalized image projection.\n%\n%project_points.m: Computes the 2D image projections of a set of 3D points\n\n\n\nif nargin < 6,\n   alpha_c = 0;\n\tif nargin < 5,\n   \tkc = zeros(5,1);\n   \tif nargin < 4,\n      \tcc = zeros(2,1);\n      \tif nargin < 3,\n         \tfc = ones(2,1);\n         \tif nargin < 2,\n            \terror('Need 2D projections and 3D points (in compute_extrinsic.m)');\n            \treturn;\n         \tend;\n      \tend;\n   \tend;\n\tend;\nend;\n\n\n%keyboard;\n\n% Compute the normalized coordinates:\n\nxn = normalize_pixel_fisheye(x_kk,fc,cc,kc,alpha_c);\n\n\n\nNp = size(xn,2);\n\n%% Check for planarity of the structure:\n%keyboard;\n\nX_mean = mean(X_kk')';\n\nY = X_kk - (X_mean*ones(1,Np));\n\nYY = Y*Y';\n\n[U,S,V] = svd(YY);\n\nr = S(3,3)/S(2,2);\n\n%keyboard;\n\n\nif (r < 1e-3)|(Np < 5), %1e-3, %1e-4, %norm(X_kk(3,:)) < eps, % Test of planarity\n   \n   %fprintf(1,'Planar structure detected: r=%f\\n',r);\n\n   % Transform the plane to bring it in the Z=0 plane:\n   \n   R_transform = V';\n   \n   %norm(R_transform(1:2,3))\n   \n   if norm(R_transform(1:2,3)) < 1e-6,\n      R_transform = eye(3);\n   end;\n   \n   if det(R_transform) < 0, R_transform = -R_transform; end;\n   \n\tT_transform = -(R_transform)*X_mean;\n\n\tX_new = R_transform*X_kk + T_transform*ones(1,Np);\n   \n   \n   % Compute the planar homography:\n   \n   H = compute_homography(xn,X_new(1:2,:));\n   \n   % De-embed the motion parameters from the homography:\n   \n   sc = mean([norm(H(:,1));norm(H(:,2))]);\n   \n   H = H/sc;\n   \n   % Extra normalization for some reasons...\n   %H(:,1) = H(:,1)/norm(H(:,1));\n   %H(:,2) = H(:,2)/norm(H(:,2));\n   \n   if 0, %%% Some tests for myself... the opposite sign solution leads to negative depth!!!\n       \n       % Case#1: no opposite sign:\n       \n       omckk1 = rodrigues([H(:,1:2) cross(H(:,1),H(:,2))]);\n       Rckk1 = rodrigues(omckk1);\n       Tckk1 = H(:,3);\n       \n       Hs1 = [Rckk1(:,1:2) Tckk1];\n       xn1 = Hs1*[X_new(1:2,:);ones(1,Np)];\n       xn1 = [xn1(1,:)./xn1(3,:) ; xn1(2,:)./xn1(3,:)];\n       e1 = xn1 - xn;\n       \n       % Case#2: opposite sign:\n       \n       omckk2 = rodrigues([-H(:,1:2) cross(H(:,1),H(:,2))]);\n       Rckk2 = rodrigues(omckk2);\n       Tckk2 = -H(:,3);\n       \n       Hs2 = [Rckk2(:,1:2) Tckk2];\n       xn2 = Hs2*[X_new(1:2,:);ones(1,Np)];\n       xn2 = [xn2(1,:)./xn2(3,:) ; xn2(2,:)./xn2(3,:)];\n       e2 = xn2 - xn;\n       \n       if 1, %norm(e1) < norm(e2),\n           omckk = omckk1;\n           Tckk = Tckk1;\n           Rckk = Rckk1;\n       else\n           omckk = omckk2;\n           Tckk = Tckk2;\n           Rckk = Rckk2;\n       end;\n       \n   else\n       \n       u1 = H(:,1);\n       u1 = u1 / norm(u1);\n       u2 = H(:,2) - dot(u1,H(:,2)) * u1;\n       u2 = u2 / norm(u2);\n       u3 = cross(u1,u2);\n       RRR = [u1 u2 u3];\n       omckk = rodrigues(RRR);\n\n       %omckk = rodrigues([H(:,1:2) cross(H(:,1),H(:,2))]);\n       Rckk = rodrigues(omckk);\n       Tckk = H(:,3);\n       \n   end;\n   \n      \n   \n   %If Xc = Rckk * X_new + Tckk, then Xc = Rckk * R_transform * X_kk + Tckk + T_transform\n   \n   Tckk = Tckk + Rckk* T_transform;\n   Rckk = Rckk * R_transform;\n\n   omckk = rodrigues(Rckk);\n   Rckk = rodrigues(omckk);\n   \n   \nelse\n   \n   %fprintf(1,'Non planar structure detected: r=%f\\n',r);\n\n   % Computes an initial guess for extrinsic parameters (works for general 3d structure, not planar!!!):\n   % The DLT method is applied here!!\n   \n   J = zeros(2*Np,12);\n\t\n\txX = (ones(3,1)*xn(1,:)).*X_kk;\n\tyX = (ones(3,1)*xn(2,:)).*X_kk;\n\t\n\tJ(1:2:end,[1 4 7]) = -X_kk';\n\tJ(2:2:end,[2 5 8]) = X_kk';\n\tJ(1:2:end,[3 6 9]) = xX';\n\tJ(2:2:end,[3 6 9]) = -yX';\n\tJ(1:2:end,12) = xn(1,:)';\n\tJ(2:2:end,12) = -xn(2,:)';\n\tJ(1:2:end,10) = -ones(Np,1);\n\tJ(2:2:end,11) = ones(Np,1);\n\t\n\tJJ = J'*J;\n\t[U,S,V] = svd(JJ);\n   \n   RR = reshape(V(1:9,12),3,3);\n   \n   if det(RR) < 0,\n      V(:,12) = -V(:,12);\n      RR = -RR;\n   end;\n   \n   [Ur,Sr,Vr] = svd(RR);\n   \n   Rckk = Ur*Vr';\n   \n   sc = norm(V(1:9,12)) / norm(Rckk(:));\n   Tckk = V(10:12,12)/sc;\n   \n\tomckk = rodrigues(Rckk);\n   Rckk = rodrigues(omckk);\n   \nend;\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/compute_extrinsic_init_fisheye.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5967375547085817}}
{"text": "%-------------------------------------------------------------------------\n% Coupling Kinetic and Fluid System of Euler Equations\n% To solve Shock Tube Problem\n%\n% Kinetic equation use SBBGK and Hydrodynamic equation use Roe Euler\n%\n% Based on: \n%  [1] Pierre Degond, Giacomo Dimarco and Luc Mieussens\n%      A moving interface method for dynamic kinetic-fluid coupling\n%      Journal of Computation Physics 227(2007)1176-1208\n%\n% By Manuel Diaz and Yun-Da Tsai   \n% 007@IAM 25.01.2013\n%-------------------------------------------------------------------------\n\nclear all; clc; close all;\n\n%% Global Variables\nglobal CFL r_time theta dt dtdx nx\nglobal w k nv\nglobal gamma etpfix\n\n%% Controling Parameters\nname        ='SBBGK1d'; % Simulation Name\nCFL         = 0.05;     % CFL condition\nr_time      = 1/10000;  % Relaxation time\ntEnd        = 0.04;      % End time\ntheta       = 0;        % {-1} BE, {0} MB, {1} FD.\nquad        = 2;        % for NC = 1 , GH = 2\nmethod      = 1;        % for TVD = 1, WENO3 = 2, WENO5 = 3\nIC_case     = 1;        % IC: {1}Sod's, {2}LE, {3}RE, {4}DS, {5}SS, {6}Cavitation\nplot_figs   = 1;        % 0: no, 1: yes please!\nwrite_ans   = 0;        % 0: no, 1: yes please!\ngamma       = 2;      % Ratio of specific heats\nflxtype     = 2;        % {1} Roe, {2} LF, {3} LLF, {4} Upwind <-non-conservative!\netpfix      = 0.90;     % {#} Harten's sonic entropy fix value, {0} no entropy fix\n\n%% Space Discretization\nnx  = 100;                      % number of cells\nx   = linspace(0,1,nx);         % Physical domain -x\ndx  = max(x(2:end)-x(1:end-1)); % delta x\n\n%% Load Initial Condition\n[z0,ux0,t0,p0,rho0,E0] = SSBGK_IC1d(x,IC_case);\n\n%% Load Initial Cut Function\n xa = 0.5;   % buffer left boundary\n xb = 0.5125;   % buffer right boundary\n h0  = cutfunc(x,xa,xb);  % Physical Cut Function\n \n%  h0 = ones(size(x));\n%  h0 = zeros(size(x));\n\n%% Discretization of the Velocity Space\n% Microscopic Velocity Discretization (using Discrete Ordinate Method)\n% that is to make coincide discrete values of microscopic velocities with\n% values as the value points for using a quadrature method, so that we can\n% integrate the velocity probability distribution to recover our\n% macroscopics properties.\nswitch quad\n\n    case{1} % Newton Cotes Quadrature:\n    V  = [-20,20];  % range: a to b\n    nv = 200;       % nodes desired (may not the actual value)\n    [c,w,k] = cotes_xw(V(1),V(2),nv,5); % Using Netwon Cotes Degree 5\n        \n    case{2} % Gauss Hermite Quadrature:\n    nv = 100;          % nodes desired (the actual value)\n    [c,w] = GaussHermite(nv); % for integrating range: -inf to inf\n    k = 1;            % quadrature constant.\n    w = w.*exp(c.^2); % weighting function of the Gauss-Hermite quadrature\n    \n    otherwise\n        error('Order must be between 1 and 2');\nend\n\n%% Applying DOM\n% The actual nv value will be computed using 'lenght' vector function:\nnv = length(c); \n% Remap velocity points\n    c = repmat(c,1,nx);     w = repmat(w,1,nx);\n% Remap classical IC\n    [rho0,ux0,p0] = apply_DOM(rho0,ux0,p0,nv);\n% Remap Semiclassical IC\n    [z0,t0,E0] = apply_DOM(z0,t0,E0,nv);\n% Remap h coeficient\n  h0 = repmat(h0,nv,1);\n\n%% Semi0-classical Equilibrium Distribution Function\nM0 = f_equilibrium_1d(z0,ux0,c,t0,theta); \n\n%% Load initial Conditions and Spliting of information\nM = M0; rho = rho0; ux = ux0; t = t0; p = p0; z = z0; h = h0; E = E0;\n\n%% Split ICs in R and L\nrhor = h.*rho0;     rhol = (1-h).*rho0;\nuxr = h.*ux0;       uxl = (1-h).*ux0;\npr = h.*p0;         pl = (1-h).*p0;\n\n% [zr,~,tr,~] = macroproperties1d(rhor,rhor.*uxr,pr+0.5*rhor.*uxr.^2,nx,nv,theta);\n% [zl,~,tl,~] = macroproperties1d(rhol,rhol.*uxl,pl+0.5*rhol.*uxl.^2,nx,nv,theta);\n% Ml = f_equilibrium_1d(zl,uxl,c,tl,theta) ;\n% fr = f_equilibrium_1d(zr,uxr,c,tr,theta);\n fr=h.*M; \n Ml=(1-h).*M;\n%% Main Loop \n% Compute next time step\n dt = dx*CFL/max(c(:,1));\n \n \n% dt =1/20000;\ntime  = 0:dt:tEnd;\ndtdx = dt/dx;\n% Ml(isnan(Ml)) = 0;     fr(isnan(fr)) = 0;\nf = fr + Ml; % computed here for ploting purposes\n\ncount = 1; % iteration counter\ntic;\nfor tsteps = time\n\n    CFL=dtdx*max(c(:,1));\n% Plot IC\n   if plot_figs == 1; surf(f); end;\n    \n\n% Compute vector 'q'\n   q = [rhol(1,:) ; rhol(1,:).*uxl(1,:) ; pl(1,:)+0.5*rhol(1,:).*uxl(1,:).^2];\n    \n% Update Physical cut function 'h'\n     h_next = h; % this means: fixed buffer assumption\n\n%     Evaluate Modified Boltzmann BGK\n    [fr_next] = ModSBBGK(h,h_next,M,fr,Ml,c,flxtype);\n    \n\n% Evaluate Modificed Roe Euler Solver\n    [rhol,rhoul,El] = ModEuler(h,h_next,q,fr_next,c);\n    \n%     plot partial result\n%     if plot_figs == 1; \n%         subplot(1,3,1); plot(x,rhol,'o'); title('Density');\n%         subplot(1,3,2); plot(x,rhoul./rhol,'o'); title('Velocity');\n%         subplot(1,3,3); plot(x,El,'o'); title('Energy');\n%     end\n    \n%     macroscopic properties\n    [zl,uxl,tl,pl] = macroproperties1d(rhol,rhoul,El,nx,nv,gamma,theta);\n    \n    % Apply DOM\n    [tl,zl,uxl] = apply_DOM(tl,zl,uxl,nv);\n    \n    % Compute Ml_next\n     Ml_next = f_equilibrium_1d(zl,uxl,c,tl,theta) ;\n%  **************************************************** \n    \n    % New time step info: sum left and righ values with 'NaN' filter sum\n    % function. \n    Ml_next(isnan(Ml_next)) = 0;     fr_next(isnan(fr_next)) = 0;\n    % Total f\n     f  = fr_next + Ml_next;    \n         \n     % Update New macroquantity    \n   [rho,rhou,E] = macromoments1d(k,w,f,c);\n    \n    %Apply Neumann BC's in total variables\n    f(:,1)  = f(:,2);                 f(:,end)  = f(:,end-1);\n    rho(:,1)= rho(:,2);            rho(:,end)= rho(:,end-1);\n    rhou(:,1) = rhou(:,2);       rhou(:,end) = rhou(:,end-1);\n    E(:,1)  = E(:,2);                 E(:,end)  = E(:,end-1);\n    \n    [rho,rhou,E] = apply_DOM(rho,rhou,E,nv);\n     \n    % Recover Semiclassical Conditions for next time step\n     [z,ux,t,p] = macroproperties1d(rho,rhou,E,nx,nv,gamma,theta);   \n   \n     \n%  update New equilibrium\n     M=f_equilibrium_1d(z,ux,c,t,theta);   \n     fr=h.*M; \n    \n%  preparing new Ml\n     rhol = (1-h).*rho;\n     uxl = (1-h).*ux;\n     pl = (1-h).*p;\n     [zl,~,tl,~] = macroproperties1d(rhol,rhol.*uxl,pl+0.5*rhol.*uxl.^2,nx,nv,gamma,theta);\n% update New Ml     \n     Ml=   f_equilibrium_1d(zl,uxl,c,tl,theta) ;\n     Ml(isnan(Ml)) = 0;\n                      \n% update counter\n    count = count+1;\n    \n% update plot\n    drawnow\nend\ntoc;\n\n% write/plot final output\n%plot(x,r_total,'o');\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/Main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5967375492424762}}
{"text": "function results = poly_segmentation_3d(record)\nif nargin < 1\n  record = false;\nend\nimport iris.drawing.*;\n\nlb = [0;0;0];\nub = [10;10;10];\ndim = 3;\n\nn_obs = 20;\n% obstacles = iris.test.random_obstacles(dim, n_obs, lb, ub,3);\nobstacles = iris.test.random_cubic_obstacles(dim, n_obs, lb, ub);\n\nA_bounds = [-1,0,0;\n            0,-1,0;\n            0,0,-1;\n            1,0,0;\n            0,1,0;\n            0,0,1];\nb_bounds = [-lb;ub];\n\nstart = 0.5 * (ub + lb);\n\n\n% profile on\n[A,b,C,d,results] = iris.inflate_region(obstacles, A_bounds, b_bounds, start);\n% profile viewer\nif n_obs < 50\n  animate_results(results, record);\nend\n\nend\n", "meta": {"author": "rdeits", "repo": "iris-distro", "sha": "ff624610a82a858862d55732136dbc2cc9ab16fc", "save_path": "github-repos/MATLAB/rdeits-iris-distro", "path": "github-repos/MATLAB/rdeits-iris-distro/iris-distro-ff624610a82a858862d55732136dbc2cc9ab16fc/src/matlab/+iris/+test/test_poly_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5967375393927675}}
{"text": "%% This script is used to generate the Brain Network for user to perform further analysis by themselves.\n\n\nclear all\naddpath(genpath(pwd));\ninput_folder='./data/'; % this is the directory of the time course data for all subjects, each file for each subject, similar as you prepared for GUI\noutput_dir='./Generated_BrainNet/'; %this is the output directory;\nmeth_Net='aHOFC'; %Here you can set the brain network construction method;\n%[\"PC\",\"aHOFC\",\"tHOFC\",\"SR\",\"WSR\",\"SLR\",\"SGR\",\"WSGR\",\"GSR\",\"SSGSR\",\"dHOFC\"];\nswitch meth_Net\n    case {'SR','WSR','GSR'}\n        lambda=0.01:0.01:0.1; %User can change the parameter range by themselves;\n    case {'SLR','SGR','WSGR','SSGSR'}\n        lambda_1=0.01:0.01:0.1; %User can change the parameter range by themselves;\n        lambda_2=0.01:0.01:0.1;\n    case 'dHOFC'\n        C=100:100:800;\n        W=20:10:70;\n        s=1; %step size is usually set to 1 or 2;\n    case {'PC','tHOFC','aHOFC'}\n        \nend\n\n\n\n\ndirOutput=dir(fullfile(input_folder,'*.txt'));\nfileName={dirOutput.name}';\n%folder={dirOutput.folder}';\nfor i=1:length(fileName)\n    BOLD{i,1}=load([input_folder,'/',fileName{i}]);\nend\n%label=importdata(label_input);\n\n[~,nROI]=size(BOLD{1});\nnSubj=length(BOLD);\n\nfprintf('Begin network construction\\n');\n\nswitch meth_Net\n    case 'PC'       % Pearson's correlation\n        BrainNet{1}=PC(BOLD);\n    case 'tHOFC'    % Topographical high-order FC\n        BrainNet{1}=tHOFC(BOLD);\n    case 'aHOFC'    % Associated high-order FC\n        BrainNet{1}=aHOFC(BOLD);\n    case 'SR'       % Sparse representation\n        parfor i=1:length(lambda)\n            BrainNet{i}=SR(BOLD,lambda(i));\n        end\n             \n    case 'WSR'      % PC weighted SR\n        parfor i=1:length(lambda)\n            BrainNet{i}=WSR(BOLD,lambda(i));\n        end\n         \n    case 'SLR'      % Sparse low-rank representation\n        lambda1=lambda_1;\n        lambda2=lambda_2;\n        num_lambda1=length(lambda1);\n        num_lambda2=length(lambda2);\n        parfor i=1:num_lambda1\n            for j=1:num_lambda2\n                BrainNet{i,j}=SLR(BOLD,lambda1(i),lambda2(j));\n            end\n        end\n        BrainNet=reshape(BrainNet,1,num_lambda1*num_lambda2);\n        \n    case 'SGR'      % Sparse group representation\n        lambda1=lambda_1;\n        lambda2=lambda_2;\n        num_lambda1=length(lambda1);\n        num_lambda2=length(lambda2);\n        parfor i=1:num_lambda1\n            for j=1:num_lambda2\n                BrainNet{i,j}=SGR(BOLD,lambda1(i),lambda2(j));\n            end\n        end\n        \n        BrainNet=reshape(BrainNet,1,num_lambda1*num_lambda2);\n        \n    case 'WSGR'     % PC weighted SGR\n        lambda1=lambda_1; % parameter for sparsity\n        lambda2=lambda_2; % parameter for group sparsity\n        num_lambda1=length(lambda1);\n        num_lambda2=length(lambda2);\n        \n        parfor i=1:num_lambda1\n            for j=1:num_lambda2\n                BrainNet{i,j}=WSGR(BOLD,lambda1(i),lambda2(j));\n            end\n        end\n        BrainNet=reshape(BrainNet,1,num_lambda1*num_lambda2);\n        \n    case 'GSR'      % Group sparse representation\n        parfor i=1:length(lambda)\n            BrainNet{i}=GSR(BOLD,lambda(i));\n        end\n        \n    case 'SSGSR'    % Strength and Similarity guided GSR\n        %lambda1=lambda_1(1:6); % parameter for group sparsity\n        lambda1=lambda_1;\n        lambda2=lambda_2; % parameter for inter-subject LOFC-pattern similarity\n        num_lambda1=length(lambda1);\n        num_lambda2=length(lambda2);\n        parfor i=1:num_lambda1\n            for j=1:num_lambda2\n                BrainNet{i,j}=SSGSR(BOLD,lambda1(i),lambda2(j));\n            end\n        end\n        BrainNet=reshape(BrainNet,1,num_lambda1*num_lambda2);\n        \n    case 'dHOFC'    % Dynamic high-order FC\n        num_W=length(W);\n        num_C=length(C);\n        parfor i=1:num_W % number of clusters\n            for j=1:num_C\n                [BrainNet{i,j},IDX{i,j}]=dHOFC(BOLD,W(i),s,C(j));\n            end\n        end\n        BrainNet=reshape(BrainNet,1,num_W*num_C);\nend\nsave(char(strcat(output_dir,meth_Net,'.mat')),'BrainNet','-v7.3');\n% All the generated networks (and those resulted from different parameters) are saved as a cell array, nROIxnROIxnSubject in each cell, different cells for results with different combinations of parameters \nfprintf('Network construction finished\\n');\n", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/BatchExamples/save_BrainNet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5967375339266622}}
{"text": "function [ySqrtEst, PInvSqrtEst]=sqrtInfoBatchSmoother(ySqrtPred,PInvSqrtPred,z,u,H,F,SR,SQ,Gamma,kD)\n%%SQRTINFOBATCHSMOOTHER Run the square root information smoother for linear\n%                  dynamic and measurement models on a batch of\n%                  measurements. The smoothed result at one time step or\n%                  along the entire batch are available. The initial\n%                  predicted states can not be uninformative.\n%\n%INPUTS: ySqrtPred The xDimX1 predicted square root information state at\n%                 the time of the initial measurement in z. The predicted\n%                 information state is always PInvSqrtPred times the\n%                 predicted target state estimate.\n%    PInvSqrtPred The inverse square root information matrix associated\n%                 with the predicted information state at the time of the\n%                 initial measurement in z. If P is the covariance matrix\n%                 of a Gaussian state x, then P=PSqrt*PSqrt' and\n%                 PInvSqrtPred=inv(PSqrt). This can be either upper\n%                 triangular or lower triangular.\n%               z The zDim X N matrix of measurements for the whole batch.\n%               u The xDim X(N-1) matrix of control inputs for the whole\n%                 batch. If there are no control inputs, then set u=[];\n%               H The zDim X xDim X N hypermatrix of measurement matrices\n%                 such that H(:,:,k)*x+w is the measurement at time k, \n%                 where x is the state and w is zero-mean Gaussian noise \n%                 with covariance matrix R (:,:,k). Alternatively, if all\n%                 of the measurement matrices are the same, one can just\n%                 pass a single zDim X xDim matrix.\n%               F The xDim X xDim X (N-1) hypermatrix of state transition\n%                 matrices. The state at discrete-time k+1 is modeled as\n%                 F(:,:,k) times the state at time k plus zero-mean\n%                 Gaussian process noise with covariance matrix Q(:,:,k).\n%                 Alternatively, if all of the state transition matrices\n%                 are the same, one can just pass a single xDim X xDim\n%                 matrix.\n%              SR The zDim X zDim X N hypermatrix of lower-triangular\n%                 square-root of the measurement covariance matrices. The\n%                 matrices must be invertible. Alternatively, if all of the\n%                 measurement covariance matrices are the same, one can\n%                 just pass a single zDim X zDim matrix.\n%              SQ The xDim X xDim X (N-1) hypermatrix of lower-triangular\n%                 square-root of the process noise covariance matrices.\n%                 The matrices must be invertible. Alternatively, if all of\n%                 the measurement covariance matrices are the same, one can\n%                 just pass a single xDim X xDim matrix.\n%           Gamma An optional xDim X xDim X (N-1) hypermatrix of matrices\n%                 that transform the process noise to the state domain if\n%                 the process noise covariance matrix is singular.\n%                 Alternatively, if all of the transform matrices are the\n%                 same, one can just pass a single xDim X xDim matrix. If\n%                 this is omitted entirely, an identity matrix is used\n%                 (i.e. there is no Gamma).\n%              kD The discrete time-step at which the smoothed state\n%                 estimate is desired, where z(:,1) is at discrete\n%                 time-step 1 (not 0). If kD is omitted ot an empty matrix\n%                 is passed, then results along the entire batch are\n%                 obtained.\n%\n%OUTPUTS: ySqrtEst The xDimXN smoothed square root information state\n%                  estimates at all steps if kD is not provided or the\n%                  xDimX1 smoothed information state estimate at step kD if\n%                  kD is provided.\n%      PSqrtInvEst The inverse square root covariance matrices associated\n%                  with the smoothed information state estimates. This is\n%                  xDimXxDimXN for the whole batch if kD is not provided\n%                  and is xDimXxDim if kD is provided.\n%\n%The algorithm is that of the linear square root information filter and\n%smoother that is described in the book [1]. The forward pass steps can be\n%found in Chapter IV, and the backwards smoother in Chapter X.\n%\n%The algorithm works by running a square root information filter forward\n%in time and then smoothing backwards. The smoothing step depends on\n%information stored during the forward pass. The smoothing step here is\n%performed on a state residual rather than the state itself and applies the\n%smoothed output to the previous updated measurement. This was based off of\n%NASA's Orbit Determination Toolbox.\n%\n%z*(j+1)=PInvSqrt*(j+1)(x*(j+1)-xPred(j+1)\n%A=[Rw(j)+Rwx(j),   Rwx(j)F(j+1,j),         u(j)\n%   PInvSqrt*(j+1), PInvSqrt*(j+1)F(j+1,j), z*(j+1)]\n%qr(A)=[Rw*(j),   Rwx*(j),      u*(j)\n%       0,        PInvSqrt*(j), z*(j)]\n%x*(j)=xUpd(j)+PInvSqrt*(j)\\z*(j)\n%\n%where xPred is the forward predicted state, xUpd is the forward updated\n%state, Rw and Rwx are outputs from the forward prediction step, u is the\n%the control input (often zero), and x* and PInvSqrt* are the smoothed\n%states. x*(N)=xUpd(N) and PInvSqrt*(N)=PInvSqrtUpd(N)\n%\n%REFERENCES:\n%[1] G. J. Bierman, \"Factorization Methods for Discrete Sequential\n%    Estimation. Academic Press, New York, 1977.\n%\n%March 2015, David Karnick, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nxDim=size(H,2);\nN=size(z,2);\n\nif(nargin<9||isempty(Gamma))\n    Gamma=eye(xDim);\nend\nif(nargin<10||isempty(kD))\n    kD=[];\nend\nif(isempty(ySqrtPred))\n    ySqrtPred=zeros(xDim,1); \nend\nif(isempty(PInvSqrtPred))\n    PInvSqrtPred=zeros(xDim,xDim);\nend\nif(isempty(u))\n    u=zeros(xDim,N-1); \nend\nif(size(H,3)==1)\n    H=repmat(H,[1,1,N]);\nend\nif(size(F,3)==1)\n    F=repmat(F,[1,1,N-1]);\nend\nif(size(SR,3)==1)\n    SR=repmat(SR,[1,1,N]); \nend\nif(size(SQ,3)==1)\n    SQ=repmat(SQ,[1,1,N-1]);\nend\nif(size(Gamma,3)==1)\n    Gamma=repmat(Gamma,[1,1,N-1]);\nend\n\n%Run the SRIF forward until we have the predictions of step kD|kD-1 (going forwards).\nySqrtFwdPred=zeros(xDim,N);\nPInvSqrtFwdPred=zeros(xDim,xDim,N);\nySqrtFwdUpd=zeros(xDim,N);\nPInvSqrtFwdUpd=zeros(xDim,xDim,N);\nRw=zeros(xDim,xDim,N);\nRwx=zeros(xDim,xDim,N);\n\n%The first step uses the priors\nySqrtFwdPred(:,1)=ySqrtPred;\nPInvSqrtFwdPred(:,:,1)=PInvSqrtPred;\n\n%The rest of the steps\nfor curStep=1:(N-1)\n    [ySqrtFwdUpd(:,curStep),PInvSqrtFwdUpd(:,:,curStep)]=sqrtInfoFilterUpdate(ySqrtFwdPred(:,curStep),PInvSqrtFwdPred(:,:,curStep),z(:,curStep),SR(:,:,curStep),H(:,:,curStep));\n    [ySqrtFwdPred(:,curStep+1),PInvSqrtFwdPred(:,:,curStep+1),Rw(:,:,curStep+1),Rwx(:,:,curStep+1)]=sqrtInfoFilterDiscPred(ySqrtFwdUpd(:,curStep),PInvSqrtFwdUpd(:,:,curStep),F(:,:,curStep),SQ(:,:,curStep),u(:,curStep),Gamma(:,:,curStep));\nend\n\n%Run the SRIS backwards until we have the updated information state of\n%step kD|kD (going backwards).\nySqrtEst=zeros(xDim,N);\nPInvSqrtEst=zeros(xDim,xDim,N);\n\n%ODTBX method\n[ySqrtEst(:,end),PInvSqrtEst(:,:,end)]=sqrtInfoFilterUpdate(ySqrtFwdPred(:,N),PInvSqrtFwdPred(:,:,N),z(:,N),SR(:,:,N),H(:,:,N));\nfor curStep=(N-1):-1:1\n    xPred=PInvSqrtFwdPred(:,:,curStep+1)\\ySqrtFwdPred(:,curStep+1); %Forward predicted state_j+1\n    xStar=PInvSqrtEst(:,:,curStep+1)\\ySqrtEst(:,curStep+1); %Backward smoothed state_j+1\n    zStar=PInvSqrtEst(:,:,curStep+1)*(xStar-xPred);\n    \n    [zSmooth,PInvSqrtEst(:,:,curStep)]=sqrtInfoSmoothStep(zStar,PInvSqrtEst(:,:,curStep+1),F(:,:,curStep),Rw(:,:,curStep),Rwx(:,:,curStep),u(:,curStep),Gamma(:,:,curStep));\n    \n    xUpd=PInvSqrtFwdUpd(:,:,curStep)\\ySqrtFwdUpd(:,curStep); %Forward updated state_j\n    ySqrtEst(:,curStep)=PInvSqrtEst(:,:,curStep)*(xUpd+PInvSqrtEst(:,:,curStep)\\zSmooth);\nend\n\nif(~isempty(kD))\n    ySqrtEst=ySqrtEst(:,kD);\n    PInvSqrtEst=PInvSqrtEst(:,:,kD);\nend\nend\n\nfunction [ySqrtPred, PInvSqrtPred]=sqrtInfoSmoothStep(ySqrtPrev,PInvSqrtPrev,F,Ru,Rux,u,Gamma)\n%This is the basic Smoothing step shown in Bierman's book\nxDim=size(ySqrtPrev,1);\n\nA=[Ru+Rux*Gamma, Rux*F, u;\n    PInvSqrtPrev*Gamma,   PInvSqrtPrev*F,   ySqrtPrev];\n[~,T]=qr(A);\n\nySqrtPred=T((xDim+1):end,end);\nPInvSqrtPred=T((xDim+1):end,(end-xDim):(end-1));\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Estimation/Batch_and_Smoothing/sqrtInfoBatchSmoother.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.596737533385411}}
{"text": "function [TW] = Btuph2TW(Btuph)\n% Convert power from British thermal units per hour to terawatts.\n% Chad A. Greene 2012\nTW = Btuph*2.930710702e-13;\n", "meta": {"author": "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/Btuph2TW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5967375320054855}}
{"text": "function [post nlZ dnlZ] = infKL_sprox(hyp, mean, cov, lik, x, y)\n% PG-SVI\n\nif hyp.is_cached==1\n\tglobal cache_post;\n\tglobal cache_nlz;\n\tglobal cache_idx;\n\t\n\tpost=cache_post(cache_idx);\n\tnlZ=cache_nlz(cache_idx);\n\tif nargout>2\n\t\twarning('to be implemented\\n');\n\t\tdnlZ = NaN;\n\tend\n\treturn \nend\n\nsnu2=hyp.snu2;\nn=size(x,1);\n\n% GP prior\nK = feval(cov{:}, hyp.cov, x);                  % evaluate the covariance matrix\nm = feval(mean{:}, hyp.mean, x);                      % evaluate the mean vector\nK=snu2*eye(n)+K;\n\nlik_name = func2str(lik{1});\nmini_batch_size=hyp.mini_batch_size;\nassert (mini_batch_size>0)\nmini_batch_num=ceil(n/mini_batch_size);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%init value\npost_m=hyp.init_m;%k=0\ntW = zeros(n,1);%k=-1\npost_v=diag(hyp.init_V);%k=0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\niter = 0;%iteration\npass=0;%pass\nmax_pass=hyp.max_pass;\nbeta = hyp.learning_rate;\nr = 1/(beta+1);\nindex=1:n;\nwhile pass<max_pass\n\tif mini_batch_size<n\n\t\tindex=randperm(n);\n\tend\n\toffset=0;\n\tmini_batch_counter=0;\n\tpass=pass+1;\n\twhile mini_batch_counter<mini_batch_num\n\t\tmini_batch_counter=mini_batch_counter+1;\n\t\titer=iter+1;\n\t\t%mini batch\n\t\ttmp_idx = mini_batch_counter*mini_batch_size;\n\t\tidx=index( (tmp_idx-mini_batch_size+1):min(tmp_idx,n) );\n\n\t\tweight=double(n)/size(x(idx,:),1);\n\n\t\tif hyp.stochastic_approx==1\n\t\t\t[ll, gf, gv] = sampling_E(y(idx), post_m(idx), post_v(idx), lik, hyp.sample_size, hyp.lik);\n\t\telse\n\t\t\tswitch lik_name\n\t\t\tcase {'laplace','likLaplace','poisson','bernoulli_logit','likLogistic'}\n\t\t\t\t[ll, gf, gv] = E_log_p(lik_name, y(idx), post_m(idx), post_v(idx), hyp.lik);\n\t\t\totherwise\t \n\t\t\t\t[ll,gf,d2f,gv] = likKL(post_v(idx), lik, hyp.lik, y(idx), post_m(idx));\n\t\t\tend\n\t\tend\n\n\t\t% pseudo observation\n\t\tpseudo_y = m + K(:,idx)*(weight*gf) - post_m;\n\t\ttW = r.*tW;\n\t\ttW(idx) = tW(idx)+(1-r).*((-2*weight)*gv);%tW^{k}, where W=-2*gv\n\t\tsW = sqrt(abs(tW)) .* sign(tW);\n\t\tL = chol(eye(n)+sW*sW'.*K); %L = chol(sW*K*sW + eye(n)); \n\n\t\t%use this following line if we approximate r^{k} .* tW.^{k-1} by tW.{k}\n\t\tpost_m = post_m + (1-r).*(pseudo_y - K*(sW.*(L\\(L'\\(sW.*pseudo_y)))));%m^{k+1}\n\t\tT = L'\\(repmat(sW,1,n).*K); %T  = L'\\(sW*K);\n\t\tpost_v = diag(K) - sum(T.*T,1)'; % v = diag(inv(inv(K)+diag(W))); %v^{k+1}\n\n\t\tif isfield(hyp,'save_iter') && hyp.save_iter==1\n\t\t\tglobal cache_nlz_iter\n\t\t\tglobal cache_iter\n\n\t\t\talpha=K\\(post_m-m);\n\t\t\tnlZ2=compute_nlz(lik, hyp, sW, K, m, alpha, post_m, y);\n\t\t\tcache_iter=[cache_iter; iter];\n\t\t\tcache_nlz_iter=[cache_nlz_iter; nlZ2];\n\t\tend\n\n\tend\n\talpha=K\\(post_m-m);\n\tnlZ=compute_nlz(lik, hyp, sW, K, m, alpha, post_m, y);\n\n\tif isfield(hyp,'save_iter') && hyp.save_iter==1\n\t\tif pass==1\n\t\t\tglobal num_iters_at_pass;\n\t\t\tnum_iters_at_pass=iter;\n\t\tend\n\t\tfprintf('pass:%d) at %d iter %.4f %.4f\\n', pass, iter, nlZ, nlZ2);\n\telse\n\t\tfprintf('pass:%d) %.4f\\n', pass, nlZ);\n\tend\n\n\tif hyp.is_save==1\n\t\tglobal cache_post;\n\t\tglobal cache_nlz;\n\n\t\tpost.sW = sW;                                             % return argument\n\t\tpost.alpha = alpha;\n\t\tpost.L = L;      \n\n\t\tcache_post=[cache_post; post];\n\t\tcache_nlz=[cache_nlz; nlZ];\n\tend\nend\n\nalpha=K\\(post_m-m);\npost.sW = sW;                                             % return argument\npost.alpha = alpha;\npost.L = L;                                              % L'*L=B=eye(n)+sW*K*sW\n\nnlZ=compute_nlz(lik, hyp, sW, K, m, alpha, post_m, y);\nfprintf('final: %.4f\\n', nlZ);\n\nif nargout>2\n  warning('to be implemented\\n');\n  dnlZ = NaN;\nend\n", "meta": {"author": "emtiyaz", "repo": "vadam", "sha": "d8ea6bdc82ac8765b873578660e1d9ba95c701d4", "save_path": "github-repos/MATLAB/emtiyaz-vadam", "path": "github-repos/MATLAB/emtiyaz-vadam/vadam-d8ea6bdc82ac8765b873578660e1d9ba95c701d4/matlab/lib/supportPackages/gpml/inf/infKL_sprox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5967375295430581}}
{"text": "function [fb_sim] = acc_gen (ref, imu)\n% acc_gen: generates simulated accelerometers measurements from reference\n%  data and IMU error profile.\n%\n% INPUT\n%\tref: data structure with true trajectory.\n%\timu: data structure with IMU error profile.\n%\n% OUTPUT\n%\tfb_sim: Nx3 matrix with simulated accelerations in the\n%\t\tbody frame [X Y Z] (m/s^2, m/s^2, m/s^2).\n%\n%   Copyright (C) 2014, Rodrigo Gonz\u00e1lez, 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%   <http://www.gnu.org/licenses/>.\n%\n% References:\n%\n%\tR. Gonzalez, J. Giribet, and H. Pati\u00f1o. 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. Sec. 2.2.\n%\n%   Aggarwal, P. et al. MEMS-Based Integrated Navigation. Artech\n% House. 2010.\n%\n%   Thinking about accelerometers and gravity by Dave Redell\n% http://www.lunar.org/docs/LUNARclips/v5/v5n1/Accelerometers.html\n%\n% Version: 012\n% Date:    2022/08/22\n% Author:  Rodrigo Gonzalez <rodralez@frm.utn.edu.ar>\n% URL:     https://github.com/rodralez/navego\n\nN = max(size(ref.t));\nM = [N, 3];\n\n%% SIMULATION OF ACC\n\n% If true, accelerations are provided...\nif (isfield(ref, 'fb'))\n    \n    acc_b = ref.fb;\n    \n% If not, accelerations are obtained from velocity\nelseif (isfield(ref, 'vel'))\n    \n    acc_raw = (diff(ref.vel)) ./ [diff(ref.t) diff(ref.t) diff(ref.t)];\n    acc_raw = [ 0 0 0; acc_raw; ];\n    \n    % Noise introduced by derivatives should be smoothed\n    acc_ned = my_sgolayfilt(acc_raw);\n    acc_b = acc_nav2body(acc_ned, ref.DCMnb_m);\n    \n% If not, accelerations are obtained from position\nelse\n    \n    % Method: LLH > ECEF > NED\n    [~, acc_ned] = pllh2vned (ref);\n    acc_b = acc_nav2body(acc_ned, ref.DCMnb_m);\nend\n\n%% SIMULATION OF GRAVITY AND CORIOLIS\n\n% Gravity and Coriolis in nav-ref\ng_n = -gravity(ref.lat, ref.h);              % Accelerometer in Z axis senses an \n                                                % acceleration of 1.0 G straight up\ncor_n = coriolis(ref.lat, ref.vel, ref.h);\n\n% Gravity and Coriolis from nav-ref to body-ref\ng_b = zeros(M);\ncor_b = zeros(M);\nfor i = 1:N\n    dcmnb = reshape(ref.DCMnb_m(i,:), 3, 3);\n    gb = dcmnb * g_n(i,:)';\n    corb =  dcmnb * cor_n(i,:)';\n    g_b(i,:) = gb';\n    cor_b(i,:) = corb';\nend\n\n%% SIMULATION OF NOISES\n\n% -------------------------------------------------------------------------\n% Simulation of static bias as a constant random variable\n\nab_sta = noise_b_sta (imu.ab_sta, N);\n\n% -------------------------------------------------------------------------\n% Simulation of white noise\n\nwn = randn(M);\nacc_wn = zeros(M);\n\nfor i=1:3\n\n    acc_wn(:, i) = imu.a_std(i).* wn(:,i);\nend\n\n% -------------------------------------------------------------------------\n% Simulation of dynamic bias (bias instability) as a first-order Gauss-Markov model\n\ndt = 1/ref.freq; \nab_dyn = noise_b_dyn (imu.ab_corr, imu.ab_dyn, dt, M);\n\n% -------------------------------------------------------------------------\n% Simulation of rate random walk\n\nacc_rrw = noise_rrw (imu.vrrw, dt, M);\n\n% -------------------------------------------------------------------------\n\nfb_sim = acc_b + cor_b + g_b + acc_wn + ab_sta + ab_dyn + acc_rrw;\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/simulation/acc_gen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5967375180695965}}
{"text": "function [mh,mw]=tropmapf(time,pos,azel)\n\nif pos(3)<-1000||pos(3)>20000\n    mh=0; mw=0; return;\nend\n\n% hydro-ave-a,b,c, hydro-amp-a,b,c, wet-a,b,c at latitude 15,30,45,60,75\ncoef=[ 1.2769934E-3, 1.2683230E-3, 1.2465397E-3, 1.2196049E-3, 1.2045996E-3;...\n       2.9153695E-3, 2.9152299E-3, 2.9288445E-3, 2.9022565E-3, 2.9024912E-3;...\n       62.610505E-3, 62.837393E-3, 63.721774E-3, 63.824265E-3, 64.258455E-3;...\n    \n       0.0000000E-0, 1.2709626E-5, 2.6523662E-5, 3.4000452E-5, 4.1202191E-5;...\n       0.0000000E-0, 2.1414979E-5, 3.0160779E-5, 7.2562722E-5, 11.723375E-5;...\n       0.0000000E-0, 9.0128400E-5, 4.3497037E-5, 84.795348E-5, 170.37206E-5;...\n    \n       5.8021897E-4, 5.6794847E-4, 5.8118019E-4, 5.9727542E-4, 6.1641693E-4;...\n       1.4275268E-3, 1.5138625E-3, 1.4572752E-3, 1.5007428E-3, 1.7599082E-3;...\n       4.3472961E-2, 4.6729510E-2, 4.3908931E-2, 4.4626982E-2, 5.4736038E-2];\n\n% height correction\naht=[2.53E-5, 5.49E-3, 1.14E-3];\nah=zeros(3,1); aw=zeros(3,1);\n\nif azel(2)<=0,mh=0; mw=0; return;end\n    \nlat=pos(1)*180/pi;\nif lat<0,yy=0.5;else,yy=0;end\ny=(time2doy(time)-28.0)/365.25+yy;\ncosy=cos(2.0*pi*y);\nlat=abs(lat);\n\nfor i=1:3\n    ah(i)=interpc(coef(i,:),lat)-interpc(coef(i+3,:),lat)*cosy;\n    aw(i)=interpc(coef(i+6,:),lat);\n%     j=fix(lat/15);\n%     ah(i)=(coef(i,j)+(coef(i,j+1)-coef(i,j))*(lat/15-j))-...\n%           (coef(i+3,j)+(coef(i+3,j+1)-coef(i+3,j))*(lat/15-j))*cosy;\n%     aw(i)=(coef(i+6,j)+(coef(i+6,j+1)-coef(i+6,j))*(lat/15-j));\nend\n\nel=azel(2);\nsinel=sin(el);\n\nmh1=(1+ah(1)/(1+ah(2)/(1+ah(3))))/(sinel+(ah(1)/(sinel+ah(2)/(sinel+ah(3)))));\nmh2=(1+aht(1)/(1+aht(2)/(1+aht(3))))/(sinel+(aht(1)/(sinel+aht(2)/(sinel+aht(3)))));\nmh=mh1+(1/sinel-mh2)*pos(3)/1000;\n\nmw=(1+aw(1)/(1+aw(2)/(1+aw(3))))/(sinel+(aw(1)/(sinel+ah(2)/(sinel+aw(3)))));\n\nreturn\n\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/common/tropmapf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5967267984123402}}
{"text": "function result = TLDA_test_LR(traindata, testdata, trainlabel, testlabel)\n    %% use the model test the target domain data\n    tempTrainXY = scale_cols(traindata, trainlabel);\n    \n    % train the classifier\n    c00 = zeros(size(tempTrainXY,1),1);\n    lambdaLG = exp(linspace(-0.5,6,20));\n    wbest=c00;\n    f1max = -inf;\n    for j = 1 : length(lambdaLG)\n        c_0 = train_cg(tempTrainXY,c00,lambdaLG(j));\n        f1 = logProb(tempTrainXY,c_0);\n        if f1 > f1max\n            f1max = f1;\n            wbest = c_0;\n        end\n    end\n    C = wbest;\n\n    result = zeros(1,2);\n    % test the train data   \n    probability = 1./(1+1./(exp(C'*traindata)));\n    probability(probability >= 0.5) = 1;\n    probability(probability < 0.5) = -1;\n    result(1,1) = mean(probability(:) == trainlabel(:));\n    \n    % test the test data    \n    probability = 1./(1+1./(exp(C'*testdata)));\n    probability(probability >= 0.5) = 1;\n    probability(probability < 0.5) = -1;\n    result(1,2) = mean(probability(:) == testlabel(:));  ", "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/TLDA/TLDA_test_LR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5967267970137407}}
{"text": "function estimation_results = FEKF_SLAM(data)\n% FEJ-EKF SLAM\n% load pre-given data: odometry and observations\nif nargin < 1\n    load('./data.mat');\nend\n\ndata_matrix = data.state;\nodo_cov = data.odom_cov;   % constant variable\nobs_cov = data.obse_cov;   % constant variable\n\nodom_sigma = data.odom_sigma;\nobsv_sigma = data.obsv_sigma;\n\n%%%%%%%%%%%%%%%%%%%% Estimation_X is used to save the state in each step %%%%%%%%%%%%%%%%%%%%  \n%%%%%%%%%%%%%%%%%%%% In every step, all elements of Estimation_X will be changed %%%%%%%%%%%%\nestimation_x.orientation = data.poses.orientation(1:3,1:3);\nestimation_x.position    = data.poses.position(:,1);\nestimation_x.cov         = sparse(6,6);\nestimation_x.landmarks   = [];       % the landmarks observed until this step (included), 4*N format, the 4-th row is the index\nestimation_x0.IndexObservedNew=[];\nestimation_x0.IndexObservedAlreadyThis=[];\n%Estimation_X.IndexOfFeature=[];     % the names(indexes) of the landmarks observed until this step (included)\n%%%%%%%%%%%%%%%%%%%% Estimation_X is used to save the state in each step %%%%%%%%%%%%%%%%%%%%  \nFirstPosition=[]; % store  p_{n|n-1}\nFirstLandmarks=[]; % store f_{k0} \n\n\n% Initialize\nn_steps = max(data_matrix(:,4));  % step instead of pose,  hence, it does not include pose 0\nestimation_results = cell(1, n_steps+1);\nestimation_results{1} = estimation_x;\n\n\nfor i = 0:n_steps\n    IndexOfCurrentStepInDataMatrix = find(data_matrix(:,4) == i); \n    m = size(IndexOfCurrentStepInDataMatrix, 1);\n    if ( mod(i, 50) == 0 )\n        disp(['Processing pose ', int2str(i)]);\n    end\n    % det(Estimation_X.cov)\n    if i ~= n_steps\n        OdometryFromThis2Next = data_matrix(IndexOfCurrentStepInDataMatrix(m-5):IndexOfCurrentStepInDataMatrix(m),1);\n        if m > 6\n            CameraMeasurementThis = [ data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(m-6) , 1 ),...\n                                      data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(m-6) , 3 )];    \n            [estimation_x,FirstLandmarks] = FEKF_update(estimation_x, CameraMeasurementThis, obsv_sigma, FirstLandmarks );\n        end\n        \n        estimation_results{i+1} = estimation_x;\n        \n        [estimation_x, FirstPosition] = FEKF_propagate(estimation_x, OdometryFromThis2Next, odom_sigma, FirstPosition );\n\n    else\n        if m > 6\n            CameraMeasurementThis = [ data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(end) , 1 ) , data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(end) , 3 )];\n           [estimation_x,FirstLandmarks] = FEKF_update(estimation_x, CameraMeasurementThis, obsv_sigma, FirstLandmarks);\n        end\n        estimation_results{i+1} = estimation_x;\n    end\nend\n\nclearvars -except estimation_results;", "meta": {"author": "RomaTeng", "repo": "EKF-SLAM-on-Manifold", "sha": "12d7d8d88c84161baed173e38d49dedb4adb2b96", "save_path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold", "path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold/EKF-SLAM-on-Manifold-12d7d8d88c84161baed173e38d49dedb4adb2b96/f_ekf_3dTest/FEKF_SLAM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5966736320475535}}
{"text": "seed = 0;\nrand('state', seed);\nrandn('state', seed);\n\nnrows = 3;\nncols = 3;\nnpixels = nrows*ncols;\n\n% we number pixels in transposed raster scan order (top to bottom, left to right)\n\n% hidden var\nHV = reshape(1:npixels, nrows, ncols);\n% observed var\nOV = reshape(1:npixels, nrows, ncols) + length(HV(:));\n\n% observed factor\nOF = reshape(1:npixels, nrows, ncols);\n% vertical edge factor VEF(i,j) is the factor for edge HV(i,j) - HV(i+1,j)\nVEF = reshape((1:(nrows-1)*ncols), nrows-1, ncols) + length(OF(:));\n% horizontal edge factor HEF(i,j) is the factor for edge HV(i,j) - HV(i,j+1)\nHEF = reshape((1:nrows*(ncols-1)), nrows, ncols-1) + length(OF(:)) + length(VEF(:));\n\nnvars = length(HV(:))+length(OV(:));\nassert(nvars == 2*npixels);\nnfac = length(OF(:)) + length(VEF(:)) + length(HEF(:));\n\nK = 2; % number of discrete values for the hidden vars\n%O = 1; % each observed pixel is a scalar\nO = 2; % each observed pixel is binary\n\nfactors = cell(1,3);\n\n% hidden states generate observed 0 or 1 plus noise\n%factors{2} = cond_gauss1_kernel(K, O, 'mean', [0 1], 'cov', [0.1 0.1]);\npnoise = 0.2;\nfactors{1} = tabular_kernel([K O], [1-pnoise pnoise; pnoise 1-pnoise]);\nofactor = 1;\n\n% encourage compatibility between neighboring vertical pixels\nfactors{2} = tabular_kernel([K K], [0.8 0.2; 0.2 0.8]);\nvedge_factor = 2;\n\n%% no constraint between neighboring horizontal pixels\n%factors{3} = tabular_kernel([K K], [0.5 0.5; 0.5 0.5]);\n\nfactors{3} = tabular_kernel([K K], [0.8 0.2; 0.2 0.8]);\nhedge_factor = 3;\n\n\n\nfactor_ndx = zeros(1, 3);\nG = zeros(nvars, nfac);\nns = [K*ones(1,length(HV(:))) O*ones(1,length(OV(:)))];\n\nN = length(ns);\n%cnodes = OV(:);\ncnodes = [];\ndnodes = 1:N;\n\nfor i=1:nrows\n  for j=1:ncols\n    G([HV(i,j), OV(i,j)], OF(i,j)) = 1;\n    factor_ndx(OF(i,j)) = ofactor;\n\n    if i < nrows\n      G(HV(i:i+1,j), VEF(i,j)) = 1;\n      factor_ndx(VEF(i,j)) = vedge_factor;\n    end\n\n    if j < ncols\n      G(HV(i,j:j+1), HEF(i,j)) = 1;\n      factor_ndx(HEF(i,j)) = hedge_factor;\n    end\n\n  end\nend\n\n\nfg = mk_fgraph(G, ns, factors, 'discrete', dnodes, 'equiv_class', factor_ndx);\n\nif 1\n  % make image with vertical stripes\n  I = zeros(nrows, ncols);\n  for j=1:2:ncols\n    I(:,j) = 1;\n  end\nelse\n  % make image with square in middle\n  I = zeros(nrows, ncols);\n  I(3:6,3:6) = 1;\nend\n\n  \n% corrupt image\nO = mod(I + (rand(nrows,ncols)> (1-pnoise)), 2);\n\nmaximize = 1;\nengine = belprop_fg_inf_engine(fg, 'maximize', maximize, 'max_iter', npixels*5);\n\nevidence = cell(1, nvars);\nonodes = OV(:);\nevidence(onodes) = num2cell(O+1); % values must be in range {1,2}\n\nengine = enter_evidence(engine, evidence);\n\nfor i=1:nrows\n  for j=1:ncols\n    m = marginal_nodes(engine, HV(i,j));\n    Ihat(i,j) = argmax(m.T)-1;\n  end\nend\n\nIhat\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/fgraph/fg_mrf1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5966736320475535}}
{"text": "function [A_hat E_hat iter svp elapsed] = ialm_rpca(D, lambda, tol, maxIter, blk)\n\n% Oct 2009\n% This matlab code implements the inexact augmented Lagrange multiplier \n% method for 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% blk - indicate whether to use BLWS\n% \n% Initialize A,E,Y,u\n% while ~converged \n%   minimize (inexactly, update A and E only once)\n%     L(A,E,Y,u) = |A|_* + lambda * |E|_1 + <Y,D-A-E> + mu/2 * |D-A-E|_F^2;\n%   Y = Y + \\mu * (D - A - E);\n%   \\mu = \\rho * \\mu;\n% end\n\n%addpath PROPACK;\n\n%elapsed = tic;\n\n[m n] = size(D);\n\nif nargin < 2\n    lambda = 1 / sqrt(max(m,n));\nelseif lambda == -1\n    lambda = 1 / sqrt(max(m,n));\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\nif nargin < 5\n    blk = 0;\nelseif blk == -1\n    blk = 0;\nend\n    \n\n% initialize\nY = D;\nnorm_two = lansvd(Y, 1, 'L');\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);\nmu = 1.25/norm_two % this one can be tuned\nmu_bar = mu * 1e7\nrho = 1.2         % this one can be tuned\nd_norm = norm(D, 'fro');\n\niter = 0;\ntotal_svd = 0;\nconverged = false;\nstopCriterion = 1;\nsv = 10;\nd = min(m, n);\n\nmark = false;\nBlock_mark = false ;\n\nwhile ~converged       \n    iter = iter + 1;\n    \n    temp_T = D - A_hat + (1/mu)*Y;\n    E_hat = max(temp_T - lambda/mu, 0);\n    E_hat = E_hat+min(temp_T + lambda/mu, 0);\n    \n%     if Block_mark==true\n%         uv_temp=[U_temp; V_temp]/sqrt(2);\n%         [U S V]=BL_SVD(D - E_hat + (1/mu)*Y, U_temp, V_temp, 1);\n%     else  \n          [U S V] = lansvd(D - E_hat + (1/mu)*Y, sv, 'L');\n%     end\n    \n    if mark==true\n        U_temp = U;\n        V_temp = V;\n        Block_mark=true;\n    end\n\n    diagS = diag(S);\n    svp = length(find(diagS > 1/mu));\n    \n    len = length(diagS);\n    ratio = diagS(1:len-1) ./ diagS(2:len);\n%     ind = find(ratio > 2);\n%     if blk && length(ind) > 0\n%         svp = min(svp, ind(1));\n%         mark = true;\n%     end   \n\n    if svp < sv\n        sv = min(svp + 1, d);\n    else\n        sv = min(svp + round(0.05*d), d);\n    end\n    \n    A_hat = U(:, 1:svp) * diag(diagS(1:svp) - 1/mu) * V(:, 1:svp)';    \n\n    total_svd = total_svd + 1;\n    \n    Z = D - A_hat - E_hat;\n    \n    Y = Y + mu*Z;\n    mu = min(mu*rho, mu_bar);\n        \n    %% stop Criterion    \n    stopCriterion = norm(Z, 'fro') / d_norm;\n    if stopCriterion < tol\n        converged = true;\n    end    \n    \n    if mod( total_svd, 10) == 0\n        disp(['#svd ' num2str(total_svd) ' r(A) ' num2str(svp)...\n            ' |E|_0 ' num2str(length(find(abs(E_hat)>0)))...\n            ' stopCriterion ' num2str(stopCriterion)]);\n    end    \n    \n    if ~converged && iter >= maxIter\n        disp('Maximum iterations reached') ;\n        converged = 1 ;       \n    end\nend\n\n%elapsed = toc(elapsed);\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/L1F/ialm_rpca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706733, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5966736258846418}}
{"text": "%% This file is the ODE file used to simulate the Michaelis-Menten kinetics.\n% Date: 04/24/2019\n% Coded By: K\n\n% Here Vmax is rhe maximum rate of reaction time\n% Km is the concentration of half-maximal reaction rate\n% \n\n%% ODE functions\nfunction dx=MMK_ODE(t,x,jx,Vmax,Km)\ndx=jx-(Vmax*x(1,:)./(Km+x(1,:)));\n\n\n\n\n\n\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Comparison/NoiseSensitivity/Michaelis-Menten kinetics/Functions/MMK_ODE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7217432122827969, "lm_q1q2_score": 0.59667361972173}}
{"text": "function [ x, know ] = p05_sol ( m, know )\n\n%*****************************************************************************80\n%\n%% P05_SOL returns known solutions for problem 5.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 February 2012\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, integer M, the spatial dimension.\n%\n%    Input/output, integer KNOW.\n%    On input, KNOW is 0, or the index of the previously returned solution.\n%    On output, KNOW is 0 if there are no more solutions, or it is the\n%    index of the next solution.\n%\n%    Output, real X(M), the solution.\n%\n  if ( know == 0 )\n    know = 1;\n    x(1:m,1) = [ ...\n       3.0 / 11.0, ...\n       6.0 / 13.0, ...\n      12.0 / 23.0, ...\n       8.0 / 37.0 ]';\n  else\n    know = 0;\n    x = zeros ( m, 1 );\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_opt_con/p05_sol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5966736197217299}}
{"text": "function [AD,Rank] = UpdateDiversityArchive(AD,Population,ND,R,Z,Xre,sigma_niche,Problem)\n% Update the Diversity Archive\n\n%------------------------------- Copyright --------------------------------\n% Copyright 2017-2018 Yiping Liu\n% Please contact {yiping0liu@gmail.com} if you have any problem.\n%--------------------------------------------------------------------------\n\n    %% Non-dominated sorting\n    Population = [Population,AD];\n    [FrontNo,MaxFNo] = NDSort(Population.objs,ND);\n\n    %% Select the solutions in the last front\n    if length(find(FrontNo<=MaxFNo))== ND\n       Next = FrontNo<=MaxFNo;\n    else\n       Next = FrontNo < MaxFNo ;\n       NQ     = ND-sum(Next);\n       Last   = find(FrontNo==MaxFNo);\n       Choose = LastSelection(Population(Last).objs,Population(Last).decs,NQ,R,Z,Xre,sigma_niche,Problem); %Algorithm 4, lines 5-30\n       Next(Last(Choose)) = true;\n    end\n    \n    %% Population for next generation\n    AD = Population(Next);\n    Rank = FrontNo(Next);\nend\n\nfunction Choose = LastSelection(PopObj,PopDec,NQ,R,Z,Xre,sigma_niche,Problem)\n% Select solutions with good diversity in the last front    \n    N      = size(PopObj,1);\n    NR     = size(R,1);\n    \n    %% Normalize\n    PopObj = PopObj - repmat(Z,N,1);\n    PopDec = (PopDec - repmat(Problem.lower,N,1))./repmat(Problem.upper-Problem.lower,N,1);\n  \n    %% Calculate distance between every solution and reference point in the objective space\n    theta = pdist2(R,PopObj,'cosine');\n    \n    %% Calculate distance between every two solutions in the reminder decsion subspace\n    d = pdist2(PopDec(:,Xre),PopDec(:,Xre),'chebychev');   \n    \n    %% Cluster\n    [thmin,label] = min(theta,[],1);   \n    C1 = false(NR,N);\n    C2 = false(NR,N);\n    for j = 1:NR\n        member = find(label==j);\n        member1 = label==j;\n        [~,temp] = sort(thmin(member));\n        for i = temp\n           if any(d(member(i),and(C1(j,:),member1))<sigma_niche) \n               C2(j,member(i))=true;\n           else\n               C1(j,member(i))=true;\n           end\n        end        \n    end    \n    \n    %% Make selected solution == NQ\n    while sum(sum(C1))>NQ\n        cmax = max(sum(C1,2));\n        jmax = sum(C1,2)== cmax;\n        temp1 = find(sum(C1(jmax,:),1)>0);        \n        [~,xmax] = max(thmin(temp1));\n        xmax=temp1(xmax);\n        C1(label(xmax),xmax) = false;\n    end   \n    while sum(sum(C1))<NQ\n        c2 = sum(C2,2)>0;\n        cmin = min(sum(C1(c2,:),2));\n        jmin = and(sum(C1,2)==cmin,c2);\n        temp1 = find(sum(C2(jmin,:),1)>0);\n        [~,xmin] = min(thmin(temp1));\n        xmin=temp1(xmin);\n        C2(label(xmin),xmin) = false;\n        C1(label(xmin),xmin) = true;\n    end    \n    Choose = sum(C1)>0;  \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/TriMOEA-TA&R/UpdateDiversityArchive.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5966736197217298}}
{"text": "function pass = test_ultrapts(pref)\n\n% Choose a tolerance:\ntol = 1e-14;\n\n% Test a small n (using REC)\nn = 42;\nlambda = .3;\nx = ultrapts(n, lambda);\npass(1) = all(size(x) == [n, 1]);\n[x, w, v] = ultrapts(n, lambda);\npass(2) = all(size(x) == [n, 1]) && all(size(w) == [1, n]) && all(size(v) == [n, 1]);\npass(3) = abs(w*x) < tol && abs(w*x.^2 - 0.8843414686338345) < tol;\npass(4) = abs(x(37) - 9.131896381993957E-01) < tol;\npass(5) = abs(w(37) - 4.332670514309510E-02) < tol;\npass(6) = abs(v(37) - 3.115587460502451E-01) < tol;\n\n% Test on [0, 10]:\n[x, w, v] = ultrapts(n, lambda, [0, 10]);\npass(7) = abs(w*x - 30.1957169274024) < 31*tol && abs(w*x.^2 - 209.0472710358626) < 300*tol;\npass(8) = abs(x(38) - 9.704505777068543E+00) < tol;\npass(9) = abs(w(38) - 1.018229378664342E-01) < tol;\npass(10) = abs(v(38) + 2.449177929215358E-01) < tol;\n\n% Test a larger n\nlambda = .8;\nn = 251;\nx = ultrapts(n, lambda);\npass(11) = all(size(x) == [n, 1]);\n[x, w, v] = ultrapts(n, lambda);\npass(12) = all(size(x) == [n, 1]) && all(size(w) == [1, n]) && all(size(v) == [n, 1]);\npass(13) = abs(w*x) < tol && abs(w*x.^2 - 0.4744211549960596) < tol;\npass(14) = abs(x(37) + 8.958806879214126E-01) < tol;\npass(15) = abs(w(37) - 3.406945649865882E-03) < tol;\npass(16) = abs(v(37) - 2.321704534650446E-01) < tol;\n\n% Test on [0, 10]:\n[x, w, v] = ultrapts(n, lambda, [0, 10]);\npass(17) = abs(w*x - 112.1472319135050) < 100*tol && abs(w*x.^2 - 716.4962038918374) < 100*tol;\npass(18) = abs(x(38) - 5.486606034997460E-01 ) < tol;\npass(19) = abs(w(38) - 4.655102134393607E-02) < tol;\npass(20) = abs(v(38) + 2.427562206703888E-01 ) < tol;\n\n% Test a larger n with a larger lambda\nlambda = 7;\nn = 551;\nx = ultrapts(n, lambda,'asy');\npass(21) = all(size(x) == [n, 1]);\n[x, w, v] = ultrapts(n, lambda,'asy');\npass(22) = all(size(x) == [n, 1]) && all(size(w) == [1, n]) && all(size(v) == [n, 1]);\npass(23) = abs(w*x) < tol && abs(w*x.^2 - (429/32768)*pi) < tol;\npass(24) = abs(x(37) + 9.748144265829347E-01) < tol;\npass(25) = abs(w(37) - 4.244751593204416E-12) < tol;\npass(26) = abs(v(37) - 6.123401324799126E-06) < tol;\n\n% Test a larger n with a larger lambda\nlambda = 25.5;\nn = 5e3;\nx = ultrapts(n, lambda,'asy');\npass(27) = all(size(x) == [n, 1]);\n[x, w, v] = ultrapts(n, lambda,'asy');\npass(28) = all(size(x) == [n, 1]) && all(size(w) == [1, n]) && all(size(v) == [n, 1]);\npass(29) = abs(w*x) < tol && abs(w*x.^2 - 281474976710656/42710983650155457) < tol;\npass(30) = abs(sum(w) - 281474976710656/805867616040669 ) < tol;\n\n% Test n = 1: \nlambda = .6;\n[x, w] = ultrapts(1, lambda); \npass(31) = (x == 0); \npass(32) = abs(w - 1.887181162535959) < tol; \n[x, w] = ultrapts(1, lambda, [-10, 3]); \npass(33) = abs( (x + 10) + (x-3) ) < tol ; % midpoint \npass(34) = abs( w*x + 62.42774750787926 ) < 2*tol;  \n\n% Test n = 2: \n[x, w] = ultrapts(2, lambda); \npass(35) = all(abs(x - [-sqrt(5)/4; sqrt(5)/4]) < tol); \npass(36) = all(abs(w - [.5*gamma(lambda+.5)*sqrt(pi)/gamma(lambda+1),...\n    .5*gamma(lambda+.5)*sqrt(pi)/gamma(lambda+1)]) < tol); \n[x, w] = ultrapts(2, lambda, [-10, 3]); \npass(37) = abs(sum(w) - 17.83649928796550) < tol; \npass(38) = abs( w*x + 62.42774750787926 ) < 10*tol;            \npass(39) = abs( w*x.^2 - 453.9946459389969 ) < 100*tol;  \npass(40) = abs( w*x.^3 + 3237.463968416426 ) < 100*tol;   \nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/misc/test_ultrapts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5966736172034496}}
{"text": "% KATAMA_SSH\n% grab time series of water levels from Chen's GOM3 NECOFS forecast model archive\n% for points north and south of Katama Bay, using NCTOOLBOX\n%\n% Quick NCTOOLBOX Install:\n% 1. Grab and unzip: https://github.com/acrosby/nctoolbox_recent/zipball/master\n% 2. Run \"setup_nctoolbox\"\n\n% OPeNDAP URL for Chen's Archive of NECOFS GOM3 Forecast\nurl='http://www.smast.umassd.edu:8080/thredds/dodsC/fvcom/archives/necofs_gom3';\nnc=ncgeodataset(url);\nvar='zeta';\nzvar=nc.geovariable(var);\nstart=[2011 6 1 0 0 0];\nstop=[2011 9 15 0 0 0];\n\ntdat=zvar.timewindowij(start,stop);\n% picked these two spots (north, and south of Katama Bay)\nloni=[ -70.4893  -70.4873];\nlati=[  41.3973   41.3339];\ndisp(['Reading time series data from ' url '...'])\ndat=nj_tseries(nc,'zeta',loni,lati,'method','nearest',...\n      'itime',tdat.index,'ele',1);\n\nsave katama_ssh.mat dat\n% plot whole time series of water levels\nfigure(1);\nset(gcf,'pos',[40 100 900 400]);\nplot(dat.time,dat.vals);datetick\nlegend('north','south');\ntitle('Water levels from NECOFS GOM3')\ngrid;set(gcf,'color','white');\n\n% zoom into Irene\nfigure(2)\nset(gcf,'pos',[40 150 900 400]);\nii=date_index(dat.time,[2011 8 23 0 0 0],[2011 9 3 0 0 0]);\nplot(dat.time(ii),dat.vals(ii,:));datetick\nlegend('north','south');\ntitle('Water levels from NECOFS GOM3')\ngrid;set(gcf,'color','white');\n\n%% plot the model bathymetry and locations\nfigure(3);\nlon = nc.data(zvar.getlonname);\nlat = nc.data(zvar.getlatname);\ndepth=nc{'h'}(:);\ngvar=zvar.attribute('mesh'); % find mesh variable\ngrd=nc{gvar}(:); % get the mesh (connectivity array)\n[m,n]=size(grd);\nif m==3,grd=grd.';elseif n~=3;disp('Error:triangles only');return;end\n%zeta=nc{var}(tdat.index(1),:);\n%%\ntrisurf(grd,lon,lat,zeros(size(depth)),-depth);view(2);...\n  shading interp;colorbar;dasp(lat(1));\naxis([-70.55 -70.40 41.30  41.44]);\ncaxis([-20 0])\nline(loni,lati,'marker','x','linestyle','none','color','black','markersize',14)\ntitle('Katama Bay area bathymetry in NECOFS GOM3 forecast model (m)')\nset(gcf,'color','white');\nset(gca,'tickdir','out');\n", "meta": {"author": "nctoolbox", "repo": "nctoolbox", "sha": "af757acccfcac373e35fde89fc8ed7e64b67de82", "save_path": "github-repos/MATLAB/nctoolbox-nctoolbox", "path": "github-repos/MATLAB/nctoolbox-nctoolbox/nctoolbox-af757acccfcac373e35fde89fc8ed7e64b67de82/demos/contrib/katama_ssh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5966736135588179}}
{"text": "function [dSf_dV1, dSf_dV2, dSt_dV1, dSt_dV2, Sf, St] = dSbr_dV(branch, Yf, Yt, V, vcart)\n%DSBR_DV   Computes partial derivatives of branch power flows w.r.t. voltage.\n%\n%   The derivatives can be taken with respect to polar or cartesian coordinates\n%   of voltage, depending on the 5th argument.\n%\n%   [DSF_DVA, DSF_DVM, DST_DVA, DST_DVM, SF, ST] = DSBR_DV(BRANCH, YF, YT, V)\n%   [DSF_DVA, DSF_DVM, DST_DVA, DST_DVM, SF, ST] = DSBR_DV(BRANCH, YF, YT, V, 0)\n%\n%   Returns four matrices containing partial derivatives of the complex\n%   branch power flows at \"from\" and \"to\" ends of each branch w.r.t voltage\n%   magnitude and voltage angle, respectively (for all buses).\n%\n%   [DSF_DVR, DSF_DVI, DST_DVR, DST_DVI, SF, ST] = DSBR_DV(BRANCH, YF, YT, V, 1)\n%\n%   Returns four matrices containing partial derivatives of the complex\n%   branch power flows at \"from\" and \"to\" ends of each branch w.r.t real and\n%   imaginary parts of voltage, respectively (for all buses).\n%\n%   If YF is a sparse matrix, the partial derivative matrices will be as well.\n%   Optionally returns vectors containing the power flows themselves. The\n%   following explains the expressions used to form the matrices:\n%\n%   If = Yf * V;\n%   Sf = diag(Vf) * conj(If) = diag(conj(If)) * Vf\n%\n%   Polar coordinates:\n%     Partials of V, Vf & If w.r.t. voltage angles\n%       dV/dVa  = j * diag(V)\n%       dVf/dVa = sparse(1:nl, f, j * V(f)) = j * sparse(1:nl, f, V(f))\n%       dIf/dVa = Yf * dV/dVa = Yf * j * diag(V)\n%\n%     Partials of V, Vf & If w.r.t. voltage magnitudes\n%       dV/dVm  = diag(V./abs(V))\n%       dVf/dVm = sparse(1:nl, f, V(f)./abs(V(f))\n%       dIf/dVm = Yf * dV/dVm = Yf * diag(V./abs(V))\n%\n%     Partials of Sf w.r.t. voltage angles\n%       dSf/dVa = diag(Vf) * conj(dIf/dVa)\n%                       + diag(conj(If)) * dVf/dVa\n%               = diag(Vf) * conj(Yf * j * diag(V))\n%                       + conj(diag(If)) * j * sparse(1:nl, f, V(f))\n%               = -j * diag(Vf) * conj(Yf * diag(V))\n%                       + j * conj(diag(If)) * sparse(1:nl, f, V(f))\n%               = j * (conj(diag(If)) * sparse(1:nl, f, V(f))\n%                       - diag(Vf) * conj(Yf * diag(V)))\n%\n%     Partials of Sf w.r.t. voltage magnitudes\n%       dSf/dVm = diag(Vf) * conj(dIf/dVm)\n%                       + diag(conj(If)) * dVf/dVm\n%               = diag(Vf) * conj(Yf * diag(V./abs(V)))\n%                       + conj(diag(If)) * sparse(1:nl, f, V(f)./abs(V(f)))\n%\n%   Cartesian coordinates:\n%     Partials of V, Vf & If w.r.t. real part of complex voltage\n%       dV/dVr  = diag(ones(n,1))\n%       dVf/dVr = Cf\n%       dIf/dVr = Yf\n%     where Cf is the connection matrix for line & from buses\n%\n%     Partials of V, Vf & If w.r.t. imaginary part of complex voltage\n%       dV/dVi  = j * diag(ones(n,1))\n%       dVf/dVi = j * Cf\n%       dIf/dVi = j * Yf\n%\n%     Partials of Sf w.r.t. real part of complex voltage\n%       dSf/dVr = conj(diag(If)) * Cf + diag(Vf) * conj(Yf)\n%\n%     Partials of Sf w.r.t. imaginary part of complex voltage\n%       dSf/dVi = j * (conj(diag(If)) * Cf - diag(Vf) * conj(Yf))\n%\n%   Derivations for \"to\" bus are similar.\n%\n%   Examples:\n%       [Ybus, Yf, Yt] = makeYbus(baseMVA, bus, branch);\n%       [dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St] = ...\n%           dSbr_dV(branch, Yf, Yt, V);\n%       [dSf_dVr, dSf_dVi, dSt_dVr, dSt_dVi, Sf, St] = ...\n%           dSbr_dV(branch, Yf, Yt, V, 1);\n%\n%   For more details on the derivations behind the derivative code used\n%   in MATPOWER, see:\n%\n%   [TN2]  R. D. Zimmerman, \"AC Power Flows, Generalized OPF Costs and\n%          their Derivatives using Complex Matrix Notation\", MATPOWER\n%          Technical Note 2, February 2010. [Online]. Available:\n%          https://matpower.org/docs/TN2-OPF-Derivatives.pdf\n%          doi: 10.5281/zenodo.3237866\n%   [TN4]  B. Sereeter and R. D. Zimmerman, \"AC Power Flows and their\n%          Derivatives using Complex Matrix Notation and Cartesian\n%          Coordinate Voltages,\" MATPOWER Technical Note 4, April 2018.\n%          [Online]. Available: https://matpower.org/docs/TN4-OPF-Derivatives-Cartesian.pdf\n%          doi: 10.5281/zenodo.3237909\n\n%   MATPOWER\n%   Copyright (c) 1996-2019, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%   and Baljinnyam Sereeter, Delft University of Technology\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n%% define named indices into bus, gen, branch matrices\n[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...\n    TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...\n    ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;\n\n%% default input args\nif nargin < 5\n    vcart = 0;      %% default to polar coordinates\nend\n\n%% define\nf = branch(:, F_BUS);       %% list of \"from\" buses\nt = branch(:, T_BUS);       %% list of \"to\" buses\nnl = length(f);\nnb = length(V);\n\n%% compute intermediate values\nYfc = conj(Yf);\nYtc = conj(Yt);\nVc = conj(V);\nIfc = Yfc * Vc;     %% conjugate of \"from\" current\nItc = Ytc * Vc;     %% conjugate of \"to\" current\n\nif issparse(Yf)             %% sparse version (if Yf is sparse)\n    diagVf  = sparse(1:nl, 1:nl, V(f), nl, nl);\n    diagVt  = sparse(1:nl, 1:nl, V(t), nl, nl);\n    diagIfc = sparse(1:nl, 1:nl, Ifc, nl, nl);\n    diagItc = sparse(1:nl, 1:nl, Itc, nl, nl);\n    if ~vcart\n        Vnorm       = V ./ abs(V);\n        diagVc      = sparse(1:nb, 1:nb, Vc, nb, nb);\n        diagVnorm   = sparse(1:nb, 1:nb, Vnorm, nb, nb);\n        CVf  = sparse(1:nl, f, V(f), nl, nb);\n        CVnf = sparse(1:nl, f, Vnorm(f), nl, nb);\n        CVt  = sparse(1:nl, t, V(t), nl, nb);\n        CVnt = sparse(1:nl, t, Vnorm(t), nl, nb);\n    end\nelse                        %% dense version\n    diagVf  = diag(V(f));\n    diagVt  = diag(V(t));\n    diagIfc = diag(Ifc);\n    diagItc = diag(Itc);\n    if ~vcart\n        Vnorm       = V ./ abs(V);\n        diagVc      = diag(Vc);\n        diagVnorm   = diag(Vnorm);\n%         CVf        = zeros(nl, nb);    CVf(sub2ind([nl,nb], (1:nl)', f)) = V(f);\n%         CVnf       = zeros(nl, nb);    CVnf(sub2ind([nl,nb], (1:nl)', f)) = Vnorm(f);\n%         CVt        = zeros(nl, nb);    CVt(sub2ind([nl,nb], (1:nl)', t)) = V(t);\n%         CVnt       = zeros(nl, nb);    CVnt(sub2ind([nl,nb], (1:nl)', t)) = Vnorm(t);\n        CVf  = full(sparse(1:nl, f, V(f), nl, nb));\n        CVnf = full(sparse(1:nl, f, Vnorm(f), nl, nb));\n        CVt  = full(sparse(1:nl, t, V(t), nl, nb));\n        CVnt = full(sparse(1:nl, t, Vnorm(t), nl, nb));\n    end\nend\nif vcart\n    Cf = sparse(1:nl, f, ones(nl, 1), nl, nb);      %% connection matrix for line & from buses\n    Ct = sparse(1:nl, t, ones(nl, 1), nl, nb);      %% connection matrix for line & to buses\n    Af = diagIfc * Cf;\n    Bf = diagVf * Yfc;\n    At = diagItc * Ct;\n    Bt = diagVt * Ytc;\n\n    dSf_dV1 = Af + Bf;          %% dSf_dVr\n    dSf_dV2 = 1j * (Af - Bf);   %% dSf_dVi\n    dSt_dV1 = At + Bt;          %% dSt_dVr\n    dSt_dV2 = 1j * (At - Bt);   %% dSt_dVi\nelse\n    dSf_dV1 = 1j * (diagIfc * CVf - diagVf * Yfc * diagVc);     %% dSf_dVa\n    dSf_dV2 = diagVf * conj(Yf * diagVnorm) + diagIfc * CVnf;   %% dSf_dVm\n    dSt_dV1 = 1j * (diagItc * CVt - diagVt * Ytc * diagVc);     %% dSt_dVa\n    dSt_dV2 = diagVt * conj(Yt * diagVnorm) + diagItc * CVnt;   %% dSt_dVm\nend\n\nif nargout > 4\n    Sf = V(f) .* Ifc;\n    St = V(t) .* Itc;\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/dSbr_dV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5966736048776263}}
{"text": "classdef gnonomicProjection < sphericalProjection\n  % gnonomic projection\n  \n  methods \n        \n     function proj = gnonomicProjection(varargin)\n      proj = proj@sphericalProjection(varargin{:});\n    end\n    \n    function [x,y] = project(sP,v,varargin)\n      % compute polar angles\n  \n      [rho,theta] = project@sphericalProjection(sP,v,varargin{:});\n\n      % map to upper hemisphere\n      ind = find(theta > pi/2+10^(-10));\n      theta(ind)  = pi - theta(ind);\n\n      % turn around antipodal vectors\n      sP.sR.antipodal = false; v.antipodal = false;\n      ind = ~sP.sR.checkInside(v);\n      rho(ind) = rho(ind) + pi;\n      \n      % formula for stereographic projection\n      r =  tan(theta);\n            \n      % compute coordinates\n      x = reshape(cos(rho) .* r,size(v));\n      y = reshape(sin(rho) .* r,size(v));\n      \n    end\n    \n    function v = iproject(sP,x,y)\n      rho = atan2(y,x);\n      theta = atan(sqrt(x.^2 + y.^2));\n      v = vector3d('theta',theta,'rho',rho);\n    end\n    \n  end\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/plotting/sphericalProjections/gnonomicProjection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5966221592593594}}
{"text": "function [obj,objs] = dcc_inference_objective(parameters,data,dataAsym,m,l,n,univariate) %#ok<INUSL>\n% Objective function used by DCC, CCC and related multivariate volatility models to perform\n% inference.  It is not used (and cannot be used) to estimate parameters.\n%\n% USAGE:\n%  [OBJ,OBJS] = dcc_inference_objective(PARAMETERS,DATA,DATAASYM,M,L,N,UNIVARIAT)\n%\n% INPUTS:\n%   PARAMETERS   - Vector of ADCC parameters including possibly volatility and intercepts\n%   DATA         - A T by K matrix of zero mean residuals -OR-\n%                    K by K by T array of covariance estimators (e.g. realized covariance)\n%   DATAASYM     - [OPTIONAL] K by K by T array of asymmetric covariance estimators only needed if\n%                    DATA is 3-dimensional and O>0 or L>0\n%   M            - Order of symmetric innovations in DCC model\n%   L            - Order of asymmetric innovations in ADCC model\n%   N            - Order of lagged correlation in DCC model\n%   UNIVARIATE   - Cell array of structures containing information needed to compute volatilities.\n%\n% OUTPUTS:\n%   OBJ          - \"As if\" objective for estimating correlation intercept parameters\n%   OBJS         - T by 1 vector of \"as if\" objectives for estimating correlation intercept parameters\n%\n% COMMENTS:\n%\n% See also DCC, CCC_MVGARCH\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 4/13/2012\n\n\n[k,~,T] = size(data);\n% Parse parameters\ncount = 0;\nfor i=1:k\n    u = univariate{i};\n    count = count + u.p+u.o+u.q+1;\nend\ngarchParameters = parameters(1:count);\noffset = count;\n% R is next\ncount = k*(k-1)/2;\nR = corr_ivech(parameters(offset + (1:count)));\noffset = offset + count;\nif l>0\n    count = k*(k+1)/2;\n    N = ivech(parameters(offset+(1:count)));\nend\n\nH = dcc_reconstruct_variance(garchParameters,univariate);\nstdData = zeros(k,k,T);\nstdDataAsym = zeros(k,k,T);\nfor t=1:T\n    h = sqrt(H(t,:));\n    stdData(:,:,t) = data(:,:,t)./(h'*h);\n    stdDataAsym(:,:,t) = dataAsym(:,:,t)./(h'*h);\nend\n\nscales = diag(mean(stdData,3));\nobjs = zeros(T,1);\nfor j=1:k-1 % Cols\n    for i=j+1:k % Rows\n        scale = sqrt(scales(i)*scales(j));\n        errors = squeeze(stdData(i,j,:))/scale - R(i,j);\n        objs = objs + 0.5*(errors.^2);\n    end\nend\n\nif l>0\n    for j=1:k\n        for i= j:k\n            errors = squeeze(stdDataAsym(i,j,:)) - N(i,j);\n            objs = objs + 0.5*(errors.^2);\n        end\n    end\nend\n\nobj = sum(objs);\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/multivariate/dcc_inference_objective.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5965799069374341}}
{"text": "function [ value, ifault ] = xinbta ( p, q, beta, alpha )\n\n%*****************************************************************************80\n%\n%% XINBTA computes inverse of the incomplete Beta function.\n%\n%  Discussion:\n%\n%    The accuracy exponent SAE was loosened from -37 to -30, because\n%    the code would not otherwise accept the results of an iteration\n%    with p = 0.3, q = 3.0, alpha = 0.2.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 September 2014\n%\n%  Author:\n%\n%    Original FORTRAN77 version by GW Cran, KJ Martin, GE Thomas.\n%    MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    GW Cran, KJ Martin, GE Thomas,\n%    Remark AS R19 and Algorithm AS 109:\n%    A Remark on Algorithms AS 63: The Incomplete Beta Integral\n%    and AS 64: Inverse of the Incomplete Beta Integeral,\n%    Applied Statistics,\n%    Volume 26, Number 1, 1977, pages 111-114.\n%\n%  Parameters:\n%\n%    Input, real P, Q, the parameters of the incomplete\n%    Beta function.\n%\n%    Input, real BETA, the logarithm of the value of\n%    the complete Beta function.\n%\n%    Input, real ALPHA, the value of the incomplete Beta\n%    function.  0 <= ALPHA <= 1.\n%\n%    Output, real VALUE, the argument of the incomplete\n%    Beta function which produces the value ALPHA.\n%\n%    Output, integer IFAULT, error flag.\n%    0, no error occurred.\n%    nonzero, an error occurred.\n%\n%  Local Parameters:\n%\n%    Local, real SAE, requests an accuracy of about 10^SAE.\n%\n  sae = -30.0;\n\n  fpu = 10.0 ^ sae;\n\n  ifault = 0;\n  value = alpha;\n%\n%  Test for admissibility of parameters.\n%\n  if ( p <= 0.0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'XINBTA - Fatal error!\\n' );\n    fprintf ( 1, '  P <= 0.0\\n' );\n    ifault = 1;\n    error ( 'XINBTA - Fatal error!' );\n  end\n\n  if ( q <= 0.0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'XINBTA - Fatal error!\\n' );\n    fprintf ( 1, '  Q <= 0.0\\n' );\n    ifault = 1;\n    error ( 'XINBTA - Fatal error!' );\n  end\n\n  if ( alpha < 0.0 || 1.0 < alpha )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'XINBTA - Fatal error!\\n' );\n    fprintf ( 1, '  ALPHA not between 0 and 1.\\n' );\n    ifault = 2;\n    error ( 'XINBTA - Fatal error!' );\n  end\n%\n%  If the answer is easy to determine, return immediately.\n%\n  if ( alpha == 0.0 )\n    value = 0.0;\n    return\n  end\n\n  if ( alpha == 1.0 )\n    value = 1.0;\n    return\n  end\n%\n%  Change tail if necessary.\n%\n  if ( 0.5 < alpha )\n    a = 1.0 - alpha;\n    pp = q;\n    qq = p;\n    indx = 1;\n  else\n    a = alpha;\n    pp = p;\n    qq = q;\n    indx = 0;\n  end\n%\n%  Calculate the initial approximation.\n%\n  r = sqrt ( - log ( a * a ) );\n\n  y = r - ( 2.30753 + 0.27061 * r ) ...\n    / ( 1.0 + ( 0.99229 + 0.04481 * r ) * r );\n\n  if ( 1.0 < pp && 1.0 < qq )\n\n    r = ( y * y - 3.0 ) / 6.0;\n    s = 1.0 / ( pp + pp - 1.0 );\n    t = 1.0 / ( qq + qq - 1.0 );\n    h = 2.0 / ( s + t );\n    w = y * sqrt ( h + r ) / h - ( t - s ) ...\n      * ( r + 5.0 / 6.0 - 2.0 / ( 3.0 * h ) );\n    value = pp / ( pp + qq * exp ( w + w ) );\n\n  else\n\n    r = qq + qq;\n    t = 1.0 / ( 9.0 * qq );\n    t = r * ( 1.0 - t + y * sqrt ( t ) )^3;\n\n    if ( t <= 0.0 )\n      value = 1.0 - exp ( ( log ( ( 1.0 - a ) * qq ) + beta ) / qq );\n    else\n\n      t = ( 4.0 * pp + r - 2.0 ) / t;\n\n      if ( t <= 1.0 )\n        value = exp ( ( log ( a * pp ) + beta ) / pp );\n      else\n        value = 1.0 - 2.0 / ( t + 1.0 );\n      end\n\n    end\n\n  end\n%\n%  Solve for X by a modified Newton-Raphson method,\n%  using the function BETAIN.\n%\n  r = 1.0 - pp;\n  t = 1.0 - qq;\n  yprev = 0.0;\n  sq = 1.0;\n  prev = 1.0;\n\n  if ( value < 0.0001 )\n    value = 0.0001;\n  end\n\n  if ( 0.9999 < value )\n    value = 0.9999;\n  end\n\n  iex = max ( - 5.0 / pp / pp - 1.0 / a ^ 0.2 - 13.0, sae );\n\n  acu = 10.0 ^ iex;\n%\n%  Iteration loop.\n%\n  while ( 1 )\n\n    [ y, ifault ] = betain ( value, pp, qq, beta );\n\n    if ( ifault ~= 0 )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'XINBTA - Fatal error!\\n' );\n      fprintf ( 1, '  BETAIN returns IFAULT = %d\\n', ifault );\n      error ( 'XINBTA - Fatal error!' );\n      ifault = 3;\n      return\n    end\n\n    xin = value;\n    y = ( y - a ) * exp ( beta + r * log ( xin ) + t * log ( 1.0 - xin ) );\n\n    if ( y * yprev <= 0.0 )\n      prev = max ( sq, fpu );\n    end\n\n    g = 1.0;\n\n    while ( 1 )\n\n      while ( 1 )\n\n        adj = g * y;\n        sq = adj * adj;\n\n        if ( sq < prev )\n\n          tx = value - adj;\n\n          if ( 0.0 <= tx && tx <= 1.0 )\n            break\n          end\n\n        end\n\n        g = g / 3.0;\n\n      end\n%\n%  Check whether current estimate is acceptable.\n%  The change \"VALUE = TX\" was suggested by Ivan Ukhov.\n%\n      if ( prev <= acu && y * y <= acu )\n        value = tx;\n        if ( indx )\n          value = 1.0 - value;\n        end\n        return\n      end\n\n      if ( tx ~= 0.0 && tx ~= 1.0 )\n        break\n      end\n\n      g = g / 3.0;\n\n    end\n\n    if ( tx == value )\n      break\n    end\n\n    value = tx;\n    yprev = y;\n\n  end\n\n  if ( indx )\n    value = 1.0 - value;\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/asa109/xinbta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5965798967047176}}
{"text": "function [M] = spm_nwcov (M)\n% Get second moments of Normal-Wishart\n% FORMAT [M] = spm_nwcov (M)\n%\n% .mean_prior_cov    Prior covariance of mean\n% .sample_prior_cov  Prior covariance of samples\n% .mean_post_cov     Posterior covariance of mean\n% .sample_pred_cov   Predictive covariance of samples\n%\n% The latter quantity is also the covariance of the predictive density\n% The marginal distributions of the mean and of the samples \n% are multivariate-T, not Gaussian.\n%\n% See J. Bernardo and A. Smith (2000) \n% Bayesian Theory, Wiley (page 435)\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_nwcov.m 6548 2015-09-11 12:39:47Z will $\n\n% Get prior covariances\nM.mean_prior_cov=M.B0/(M.n0*(M.a0-1));\n\nalpha=2*M.a0-M.P+1;\nw_s=(1+1/M.n0)/(0.5*alpha-1);\nM.sample_prior_cov=w_s*M.B0;\n\n% Get posterior covariances\nM.mean_post_cov=M.BN/(M.nN*(M.aN-1));\n\nalpha=2*M.aN-M.P+1;\nw_s=(1+1/M.nN)/(0.5*alpha-1);\nM.sample_pred_cov=w_s*M.BN;", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/inference/spm_nwcov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.5965195618737015}}
{"text": "function [psfMatData, p] = constructMatrix_new( PSF, center, boundary, imsize )\n%\n%       psfMatData = constructMatrix_new( PSF, center, boundary, imsize );\n%\n%  Construct psfMatrix data.\n%\n%  Given a PSF and the locatio of the corresponding point source,\n%  this function sets up the data needed to do efficient matrix-vector\n%  multiplication.\n%\n%  This is meant only for spatially invariant PSFs.\n%\n%  Input:\n%         PSF  -  PSF image array\n%      center  -  location of point source\n%    boundary  -  desired boundary condition\n%      imsize  -  size of restored image\n%\n%  Output:\n%   psfMatData -  array containing the (complex) data needed to\n%                 do efficient matrix-vector multiplications.\n%\nswitch boundary\n    case 'periodic'\n        padSize = imsize - size(PSF);\n        PSF = padarray(PSF, padSize, 'post');\n        psfMatData = fft2(circshift(PSF, 1-center));\n        p = [];\n    otherwise\n        [U, S, V] = svd(PSF);\n        [m, n] = size(PSF);\n        imsize_pad = 2.^nextpow2(2*imsize);\n        minU = abs(min(min(U(:,1))));\n        maxU = max(max(abs(U(:,1))));\n       if minU == maxU\n           U = -U;\n           V = -V;\n       end\n       %\n       %  Find number of Kronecker terms to represent the matrix.\n       %\n       Rtol = 10*eps;\n       MaxTerms = sum(diag(S)/S(1,1) >= Rtol);\n       \n       %\n       %  Get quantities needed to multiply by the Toeplitz pieces:\n       %\n       bidx_top1 = 1:n-center(2)+1;\n       bidx_top2 = center(2):n;\n       bidx_bot1 = imsize_pad(2)-center(2)+2:imsize_pad(2);\n       bidx_bot2 = 1:center(2)-1;\n       cidx_top1 = 1:m-center(1)+1;\n       cidx_top2 = center(1):m;\n       cidx_bot1 = imsize_pad(1)-center(1)+2:imsize_pad(1);\n       cidx_bot2 = 1:center(1)-1;\n       \n              \n       BT = V(:,1:MaxTerms)*sqrt(S(1:MaxTerms,1:MaxTerms));\n       CT = U(:,1:MaxTerms)*sqrt(S(1:MaxTerms,1:MaxTerms));\n       \n       BT_hat = zeros(imsize_pad(2), MaxTerms);\n       CT_hat = zeros(imsize_pad(1), MaxTerms);\n       \n       BT_hat(bidx_top1,:) = BT(bidx_top2,:);\n       BT_hat(bidx_bot1,:) = BT(bidx_bot2,:);\n       CT_hat(cidx_top1,:) = CT(cidx_top2,:);\n       CT_hat(cidx_bot1,:) = CT(cidx_bot2,:);\n       lambdaT = fft(CT_hat);\n       deltaT = fft(BT_hat);\n       \n       %\n       %  Get quantities needed to multiply by the Hankel pieces:\n       %\n       bidx_top1 = 1:n-center(2);\n       bidx_top2 = center(2)+1:n;\n       bidx_bot1 = imsize_pad(2)-center(2)+1:imsize_pad(2)-1;\n       bidx_bot2 = 1:center(2)-1;\n       cidx_top1 = 1:m-center(1);\n       cidx_top2 = center(1)+1:m;\n       cidx_bot1 = imsize_pad(1)-center(1)+1:imsize_pad(1)-1;\n       cidx_bot2 = 1:center(1)-1;\n              \n       BH_hat = zeros(imsize_pad(2), MaxTerms);\n       CH_hat = zeros(imsize_pad(1), MaxTerms);\n       BH_hat(bidx_top1,:) = BT(bidx_top2,:);\n       BH_hat(bidx_bot1,:) = BT(bidx_bot2,:);\n       CH_hat(cidx_top1,:) = CT(cidx_top2,:);\n       CH_hat(cidx_bot1,:) = CT(cidx_bot2,:);\n       lambdaH = fft(CH_hat);\n       deltaH = fft(BH_hat);\n       \n       %\n       %  Need to permute these with a shift matrix:\n       %\n       pB = [1;(imsize_pad(2):-1:2)'];\n       pC = [1;(imsize_pad(1):-1:2)'];\n       \n       lambdaH = lambdaH(pC,:);\n       deltaH = deltaH(pB,:);\n       \n       psfMatData = zeros(imsize_pad(1), imsize_pad(2), 4);\n       psfMatData(:,:,1) = lambdaT*deltaT';\n       psfMatData(:,:,2) = lambdaT*deltaH';\n       psfMatData(:,:,3) = lambdaH*deltaT';\n       psfMatData(:,:,4) = lambdaH*deltaH';\n       p = [pB, pC];\n       \nend\n       \n       \n\n", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/Extra/prblur_tools/@psfMatrix/private/constructMatrix_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5965148178540813}}
{"text": "function Q = ForwardStepBC2D(xin, yin, nxin, nyin, mapI, mapO, mapW, mapC, Q, time);\n  \n%  function [Q] = ForwardStepBC2D(xin, yin, nxin, nyin, mapI, mapO, mapW, mapC, Q, time);\n% Purpose: Impose channel boundary conditions on 2D Euler equations on weak form\n\n% Example is Mach ** 0.3 ** flow in wind tunnel\ngamma = 1.4;\n\n% extract conserved variables\nrho = Q(:,:,1); rhou = Q(:,:,2); rhov = Q(:,:,3); Ener = Q(:,:,4);\n\n% Inflow conditions -- uniform inflow\nrhoin = gamma; uin = 3.0; vin = 0.0; pin = 1.0;\nEin = pin/(gamma-1.0) + 0.5*rhoin*(uin^2+vin^2);\n\nrho(mapI) = rhoin; rhou(mapI) = rhoin*uin; rhov(mapI) = rhoin*vin; Ener(mapI) = Ein;\n\n% Outflow conditions -- supersonic outflow ( do nothing )\n\n% Wall conditions -- reflective, isothermal, i.e., n.u=0, T=T(t=0)\nrhoW = rho(mapW); rhouW = rhou(mapW); rhovW = rhov(mapW); \nnxW = nxin(mapW);   nyW = nyin(mapW);\n\n% reverse flow in normal direction in ghost elements\nrhou(mapW) = rhouW - 2*nxW.*(nxW.*rhouW + nyW.*rhovW);\nrhov(mapW) = rhovW - 2*nyW.*(nxW.*rhouW + nyW.*rhovW);\n\n% pack modified conserved variables\nQ(:,:,1) = rho; Q(:,:,2) = rhou; Q(:,:,3) = rhov; Q(:,:,4) = Ener;\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/ForwardStepBC2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5965148081209276}}
{"text": "%\n%  Generate an equal ripple minimum phase filter starting with a linear\n%  phase filter.\n%  \n%  Called by dzmp.\n\n%  written by John Pauly, 1992\n%  (c) Board of Trustees, Leland Stanford Junior University\n\nfunction hmp = fmp(h)\n\nl = length(h);\nif rem(l,2) == 0,\n   disp('filter length must be odd');\n   return;\nend;\nlp = 8*exp(ceil(log(l)/log(2))*log(2));\nhp = [zeros(1,ceil((lp-l)/2)) h zeros(1,floor((lp-l)/2))];\nhpf = fftc(hp);\nhpfs = hpf-min(real(hpf))*1.000001;\nhpfmp = mag2mp(sqrt(abs(hpfs)));\nhpmp = ifft(fftshift(conj(hpfmp)));\nhmp = hpmp(1:(l+1)/2);\n\n", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/External/rf_tools/fmp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5965148004275995}}
{"text": "function W = nullspaceLUSOLapply2Modes(mode, m, n, V, nullS)\n% Computes the matrix vector product with the operator nullspace\n% function handle of the form `y = pdMat(mode, m, n, x)`\n%\n% USAGE:\n%\n%    W = nullspaceLUSOLapply2Modes(mode, m, n, V, nullS)\n%\n% INPUTS:\n%    mode:     :math:`mode = 1` returns :math:`W = Z V`, `mode = 2` returns :math:`W = Z^T V`\n%    m:        first dimension of the matrix\n%    n:        second dimension of the matrix\n%    V:        one of the components of the multiplication\n%    nullS:    structure `nullS` from the function `nullspaceLUSOLform(S)`;\n%              where `m x n` sparse matrix `S` (:math:`m < n`).\n%\n% OUTPUT:\n%    W:        Matrix vector product\n%\n% .. 16 May 2008: (MAS) First version of nullspaceLUSOLapply.m. See nullspaceLUSOLtest.m for testing.\n% .. 13 Mar 2009: (RF) Tried to add matrix vector product of the transpose for use with pdco\n\nif mode==1\n    %returns   W = Z*V (mode=1)\n\n    % Second, if V is an (n-m) x k sparse matrix (k >= 1),\n    %        W = nullspaceLUSOLapply(nullS,V);\n    % computes an n x k sparse matrix W from V such that S*W = 0.\n    %\n    % This is an operator form of finding an n x (n-m) matrix Z\n    % such that S*Z = 0 and then computing W = Z*V.\n    % The aim is to obtain W without forming Z explicitly.\n\n    % 16 May 2008: (MAS) First version of nullspaceLUSOLapply.m.\n    %              See nullspaceLUSOLtest.m for testing.\n\n    Cinv    = nullS.Cinv; % Column scales\n    L       = nullS.L;    % Strictly triangular L\n    p       = nullS.p;    % Column permutation for S\n    rankS   = nullS.rank; % rank(S)\n\n    [n ,n ] = size(L);\n    [mV,nV] = size(V);\n\n    B       = [sparse(rankS,nV)\n                V        ];\n    Z       = (L')\\B;\n    W       = Z;\n    W(p,:)  = Z;\n    W       = Cinv*W;\nelse\n    %returns  W = Z'*V (mode=2).\n\n    % This is an operator form of finding an n x (n-m) matrix Z\n    % such that S*Z = 0 and then computing W = Z'*V.\n    % The aim is to obtain W without forming Z explicitly.\n\n    % When S is scaled as S = R*A*C, we have Z = Cinv*P'*inv(L')[0;I]\n\n    % This was the maths I tried to follow -RF\n    %     W   =   A'*V\n    %         =   (Cinv*P'*inv(L')[0;I])'*V\n    %         =   [0,I]'*inv(L)*P*Cinv'*V\n\n\n    Cinv    = nullS.Cinv; % Column scales\n    L       = nullS.L;    % Strictly triangular L\n    p       = nullS.p;    % Column permutation for S\n    rankS   = nullS.rank; % rank(S)\n\n    [n ,n ] = size(L);\n\n    V = Cinv'*V;\n\n    % I am not sure how to use these permutations\n    % e.g. if P*A = B then is it B(p,:)=A or B=A(p,:)\n    V(p,:) = V;\n%     V(fliplr(p),:) = V;\n\n    W = L\\V;\n\n    W = W(rankS+1:n,:);\n\nend\n\nreturn\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/subspaces/nullspace/nullspaceLUSOLapply2Modes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5964957720134906}}
{"text": "function WtW = pairwise_dists(WU, WUinit)\n\nWU = reshape(WU, [], size(WU,3));\nWUinit = reshape(WUinit, [], size(WUinit,3));\nWtW = WU' * WUinit;\n\n\nmu = sum(WU.^2,1);\nmu = mu(:);\n\nmuinit = sum(WUinit.^2,1);\nmuinit = muinit(:);\n\nmu     = repmat(mu, 1, size(WUinit,2));\nmuinit = repmat(muinit', size(WU,2), 1);\n\nWtW = 1 - 2*WtW ./ (muinit + mu);", "meta": {"author": "cortex-lab", "repo": "KiloSort", "sha": "cd040da1963dd760da98b54c811b3fd441d54e79", "save_path": "github-repos/MATLAB/cortex-lab-KiloSort", "path": "github-repos/MATLAB/cortex-lab-KiloSort/KiloSort-cd040da1963dd760da98b54c811b3fd441d54e79/mergesplits/pairwise_dists.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5964038357341636}}
{"text": "function plot_3d_2( data1, data2, theta )\n\n    data1 = rotate(data1, theta);\n    x1 = data1(:, 1);\n    y1 = data1(:, 2);\n    z1 = data1(:, 3);\n\n    data2 = rotate(data2, theta);\n    x2 = data2(:, 1);\n    y2 = data2(:, 2);\n    z2 = data2(:, 3);\n    \n    figure();\n    scatter3(x1, y1, z1, 'b');\n    hold on;\n    scatter3(x2, y2, z2, 'r');\n    hold off;\n\nend", "meta": {"author": "XgTu", "repo": "2DASL", "sha": "95052f203e6d945bb6563f916cc539bba0815972", "save_path": "github-repos/MATLAB/XgTu-2DASL", "path": "github-repos/MATLAB/XgTu-2DASL/2DASL-95052f203e6d945bb6563f916cc539bba0815972/evaluation/3D_ICP-master/plot_3d_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276224, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5964038191671136}}
{"text": "function dt_stability_limit = checkStability(kgrid, medium)\n% CHECKSTABILITY   Compute maximum stable timestep for k-space models   \n%\n% DESCRIPTION:\n%       checkStability calculates the maximum time step for which the\n%       k-space propagation models kspaceFirstOrder1D, kspaceFirstOrder2D\n%       and kspaceFirstOrder3D are stable. These models are unconditionally\n%       stable when the reference sound speed is equal to or greater than\n%       the maximum sound speed in the medium and there is no absorption.\n%       However, when the reference sound speed is less than the maximum\n%       sound speed the model is only stable for sufficiently small time\n%       steps. The criterion is more stringent (the time step is smaller)\n%       in the absorbing case.        \n%\n%       The time steps given are accurate when the medium properties are\n%       homogeneous. For a heterogeneous media they give a useful, but not\n%       exact, estimate.  \n%\n%       The timesteps given are accurate when the medium properties are\n%       homogeneous. For a heterogeneous media they give a useful, but not\n%       exact, estimate.\n%\n% USAGE:\n%       dt_stability_limit = checkStability(kgrid, medium)\n%\n% INPUTS:\n%\n%       kgrid              - structure returned by makeGrid holding grid parameters\n%       medium             - structure holding the medium properties\n%\n% OUTPUTS:\n%   \n%       dt_stability_limit - maximum timestep for stability. (Set to Inf\n%                            when the model is unconditionally stable.) \n%\n% ABOUT:\n%       author             - Ben Cox\n%       date               - 12th August 2014\n%       last update        - 25th August 2014\n%       \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n%\n% See also kspaceFirstOrder1D, kspaceFirstOrder2D, kspaceFirstOrder3D,\n% makeGrid, makeTime\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 <http://www.gnu.org/licenses/>.\n\n% Find the maximum wavenumber\nkmax = max(kgrid.k(:));\n\n% calculate the reference sound speed for the fluid code, using the\n% maximum by default which ensures the model is unconditionally stable\nif isfield(medium, 'sound_speed_ref')\n    if isnumeric(medium.sound_speed_ref)\n        c_ref = medium.sound_speed_ref;\n    elseif strcmp(medium.sound_speed_ref, 'min')\n        c_ref = min(medium.sound_speed(:));\n    elseif strcmp(medium.sound_speed_ref, 'mean')\n        c_ref = mean(medium.sound_speed(:));\n    else strcmp(medium.sound_speed_ref, 'max')\n        c_ref = max(medium.sound_speed(:));        \n    end\nelse\n    c_ref = max(medium.sound_speed(:));\nend\n\n% calculate the timesteps required for stability\nif ~isfield(medium, 'alpha_coeff') || all(medium.alpha_coeff(:) == 0)\n\n    % =====================================================================\n    % NON-ABSORBING CASE\n    % =====================================================================\n    \n    if c_ref >= max(medium.sound_speed(:))\n        \n        % set the timestep to Inf when the model is unconditionally stable.\n        dt_stability_limit = Inf;\n        \n    else\n        \n        % set the timestep required for stability when c_ref~=max(medium.sound_speed(:))\n        dt_stability_limit = 2/(c_ref * kmax) * asin(c_ref/max(medium.sound_speed(:)));\n        \n    end\n    \nelse\n\n    % =====================================================================\n    % ABSORBING CASE\n    % =====================================================================\n\n    % convert the absorption coefficient to nepers.(rad/s)^-y.m^-1\n    medium.alpha_coeff = db2neper(medium.alpha_coeff, medium.alpha_power);\n\n    % calculate the absorption constant\n    if ~(isfield(medium, 'alpha_mode') && strcmp(medium.alpha_mode, 'no_absorption'))\n        absorb_tau = -2*medium.alpha_coeff.*medium.sound_speed.^(medium.alpha_power - 1);\n    else\n        absorb_tau = 0;\n    end\n\n    % calculate the dispersion constant\n    if ~(isfield(medium, 'alpha_mode') && strcmp(medium.alpha_mode, 'no_dispersion'))\n        absorb_eta = 2*medium.alpha_coeff.*medium.sound_speed.^(medium.alpha_power)*tan(pi*medium.alpha_power/2);\n    else\n        absorb_eta = 0;\n    end\n    \n    % Estimate the timestep required for stability in the absorbing case by\n    % assuming the k-space correction factor, kappa = 1;\n    % (Note that absorb_tau and absorb_eta are negative quantities.)\n    temp1 = max(medium.sound_speed(:)) * min(absorb_tau(:)) * kmax^(medium.alpha_power-1);\n    temp2 = 1 - min(absorb_eta(:)) * kmax^(medium.alpha_power-1);\n    dt_estimate = (temp1 + sqrt(temp1^2 + 4*temp2))/(temp2 * kmax * max(medium.sound_speed(:)));\n    \n    % Use a fixed point iteration to find the correct timestep, assuming\n    % now that kappa = kappa(dt), using the previous estimate as a starting\n    % point\n    \n    % First define the function to iterate\n    kappa = @(dt) sinc(c_ref*kmax*dt/2);\n    temp3 = @(dt) max(medium.sound_speed(:))*min(absorb_tau(:))*kappa(dt)*kmax^(medium.alpha_power-1);\n    func_to_solve = @(dt) (temp3(dt) + sqrt((temp3(dt))^2 + 4*temp2 ))/(temp2*kmax*kappa(dt)*max(medium.sound_speed(:)));\n\n    % run the fixed point iteration  \n    dt_stability_limit = dt_estimate;\n    dt_old = 0;\n    accuracy = 1e-12;\n    while abs(dt_stability_limit-dt_old)>accuracy\n        dt_old = dt_stability_limit;\n        dt_stability_limit = func_to_solve(dt_stability_limit);\n    end\n    \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/checkStability.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5964038095849671}}
{"text": "function [logp, yhat, res] = tapas_beta_obs(r, infStates, ptrans)\n% Calculates the log-probability of responses representing probabilities on the unit interval\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013-2016 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 <http://www.gnu.org/licenses/>.\n\n% Transform nu-prime to its native space\nnupr = exp(ptrans(1));\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% Predictions or posteriors?\nif strcmp(r.c_prc.model,'tapas_rw_binary')\n    mu = tapas_sgm(infStates(:,1), 1);\nelse\n    mu = infStates(:,1,1); % Default: predictions (ie, mu1hat)\n    if r.c_obs.predorpost == 2\n        mu = tapas_sgm(infStates(:,2,3), 1); % Alternative: posteriors (ie, sgm(mu2))\n    end\nend\n\n% Special cases\nif strcmp(r.c_prc.model,'hgf_whichworld')\n    mu = tapas_sgm(infStates(:,2,1,3), 1);\nend\nif strcmp(r.c_prc.model,'ph_binary')\n    mu = infStates(:,2);\nend\n\n% Weed irregular trials out from inferred states and responses\nmu(r.irr) = [];\ny = r.y(:,1);\ny(r.irr) = [];\n\n% y has to be in the *open* unit interval\n%y(y==0) = 1e-4;\n%y(y==1) = 1-1e-4;\ny = 0.95.*(y-0.5)+0.5; % Shrink all y values toward 1/2 by a factor of 0.95\n\n% Nu is nu-prime plus two (sometimes)\n%nu = nupr+2;\nnu = nupr;\n\n% Calculate alpha and beta from mu and nu\nal = mu.*nu;\nbe = nu - al;\n\n% Calculate log-probabilities for non-irregular trials\nreg = ~ismember(1:n,r.irr);\nlogp(reg) = log(betaDens(y,al,be));\nyhat(reg) = mu;\nres(reg) = y-mu;\n\nend\n\nfunction p = betaDens(x,alpha,beta)\n% Check whether x is in the unit interval\nif any(x(:)<0) || any(x(:)>1)\n    error('tapas:hgf:BetaObs:ArgNotInUnitIntrv', 'Error: first argument to betaDens must be in the unit interval.');\nend\n% Check whether alpha and beta are greater than 0\nif any(alpha(:)<0) || any(beta(:)<0)\n    error('tapas:hgf:BetaObs:AlphaOrBetaNeg', 'Error: alpha and beta have to be non-negative.');\nend\n% Calculate beta density\np = gamma(alpha+beta)./(gamma(alpha).*gamma(beta)).*x.^(alpha-1).*(1-x).^(beta-1);\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_beta_obs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6893056040203136, "lm_q1q2_score": 0.5964038088536905}}
{"text": "function [IPPEPoses,refinedPoses,HHat,U,Q] = featureBasedPlanePoseFromImage(planarTemplate,inputImage,K,kc,featureOpts,ransacOpts,IPPEOpts,plottingOpts)\n%featureBasedPlanePoseFromImage: An example of using IPPE to solve a plane's pose given a frontal 'template' image and a single input image. This follows the following pipeline:\n%\n%1. Detect features in the template and input image\n%2. Match features based on their descriptor similarity\n%3. Use the matched features to robustly estimate the homography between the template image and the input image.\n%4. From the inlier matches, use IPPE to estimate the camera's pose.\n%5. (Optionally) Refine the camera's pose with Levenberg\u2013Marquardt.\n%\n% The camera should be intrinsically calibrated a priori. We use a perspective camera model with lens distortion, which\n% is the standard model and used in OpenCV and Bouguet's Matlab camera calibration toolbox\n%(http://www.vision.caltech.edu/bouguetj/calib_doc/). This is parameterised by a 3x3 calibration matrix K and a 5x1 distortion vector\n%kc. You can determine K and kc by running Bouguet's calibration toolbox using a checkerboard calibration target.\n%\n%Inputs\n%\n%planarTemplate: a structure holding the planar object used to compute the\n%camera's pose. See makePlanarTemplate.m for a description of its fields.\n%\n%inputImage: a 2D unit8 input image (grayscale or rgb). This is an image of the plane viewed\n%from the camera. \n%\n%K: The input image's 3x3 intrinsic matrix (5x1 double).\n%\n%kc: The input image's distortion parameters (5x1 double)\n%\n%Note that when using ASIFT, it is best to use an undistorted image (i.e.\n%the effects of lens distortion are undone). This is because ASIFT does som\n%match filtering based on epipolar geometry, and does not handle lens\n%distortion. \n%\n%featureOpts: Options for feature detection and matching. See\n%detectAndMatchFeatures.m for details.\n%\n%ransacOpts: Options for ransac. See basicHomographyRansac.m for details.\n%detectAndMatchFeatures.m for details.\n%\n%IPPEOpts: Options for IPPE pose estimation. See perspectiveIPPE.m for details.\n%\n%plottingOpts: Options for plotting the fitted homography. This has two\n%fields:\n%    plottingOpts.doPlot (true or false): true if we want to visualise\n%    results, false otherwise\n%    plottingOpts.figId (positive integer): the figure number for plotting the results. \n%\n%Outputs:\n%IPPEPoses: structure containing the two pose solutions from IPPE. See\n%perspectiveIPPE.m for details.\n%\n%refinedPoses: structure containing the two refined pose solutions using\n%Levenberg\u2013Marquardt (same format as IPPEPoses). See\n%perspectiveIPPE.m for details. \n%\n%HHat is the homography matrix outputted from ransac (3x3 double). Note\n%that this is the mapping from the template's image to the input image's\n%normalised pixel coordinates. \n%\n%poseResults.U is the set of inlier correspondences detected in the template image (in mm) (2xN double)\n%\n%poseResults.Q is the set of inlier correspondences detected in the input image (in normalised pixels) (2xN double)\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This file is part of the IPPE package for fast plane-based pose\n% estimation from the paper \"Infinitesimal Plane-based Pose Estimation\" by Toby Collins and Adrien Bartoli,\n% published in the International Journal of Computer Vision, September\n% 2014. A copy of the author's pre-print version can be found here:\n%\n% http://isit.u-clermont1.fr/~ab/Publications/Collins_Bartoli_IJCV14.pdf\n%\n% This package is free and covered by the BSD licence without any warranty. We hope you find this code useful and please cite our paper in your work:\n% (c) Toby Collins 2015\n%\n%\n%\n%@article{\n%year={2014},\n%issn={0920-5691},\n%journal={International Journal of Computer Vision},\n%volume={109},\n%number={3},\n%doi={10.1007/s11263-014-0725-5},\n%title={Infinitesimal Plane-Based Pose Estimation},\n%url={http://dx.doi.org/10.1007/s11263-014-0725-5},\n%publisher={Springer US},\n%keywords={Plane; Pose; SfM; PnP; Homography},\n%author={Collins, Toby and Bartoli, Adrien},\n%pages={252-286},\n%language={English}\n%}\n%\n%\n%basic argument checking:\nassert(isa(inputImage,'uint8'));\nassert(size(K,1)==3);\nassert(size(K,2)==3);\nassert(size(kc,1) == 5);\nassert(size(kc,2) == 1);\n\n%first detect and match features:\n[p,q] = detectAndMatchFeatures(planarTemplate.rectifiedImage_g,planarTemplate.roi,...\n    inputImage,[],featureOpts);\nqNormalised = normaliseImagePoints(q,K,kc);\n\n%now estimate the homography with RANSAC:\n[HHat,inliers] = basicHomographyRansac(p,qNormalised,ransacOpts);\n\n%lets plot the results:\nif plottingOpts.doPlot\n    visualiseHomography(planarTemplate.rectifiedImage_g,planarTemplate.roi,inputImage,HHat,K,kc,p,q,inliers,plottingOpts.figId);   \nend\n\n%Now use IPPE to estimate the camera's pose.\n\n%First get the points on the template image into mm, and reject outliers:\nU = planarTemplate.templatImgPixelSize*p(:,inliers);\nQ = qNormalised(:,inliers);\n\n[IPPEPoses,refinedPoses] = perspectiveIPPE(U,Q,[],IPPEOpts);\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/featureBasedPlanePoseFromImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5964038071894304}}
{"text": "function [U_final, V_final, nIter_final, objhistory_final] = LCCF(X, k, W, options, U, V)\n% Locally Consistant Concept Factorization (LCCF)\n%\n% where\n%   X\n% Notation:\n% X ... (mFea x nSmp) data matrix \n%       mFea  ... number of words (vocabulary size)\n%       nSmp  ... number of documents\n% k ... number of hidden factors\n% W ... weight matrix of the affinity graph \n%\n% options ... Structure holding all settings\n%\n% You only need to provide the above four inputs.\n%\n% X = X*U*V'\n%\n% References:\n% [1] Deng Cai, Xiaofei He, Jiawei Han, \"Locally Consistent Concept\n%     Factorization for Document Clustering\", IEEE Transactions on Knowledge\n%     and Data Engineering, Vol. 23, No. 6, pp. 902-913, 2011.   \n%\n%\n%   version 2.0 --April/2010 \n%   version 1.0 --Dec./2008 \n%\n%   Written by Deng Cai (dengcai AT gmail.com)\n%\n\nnSmp=size(X,2);\n\nif ~isfield(options,'error')\n    options.error = 1e-5;\nend\nif ~isfield(options, 'maxIter')\n    options.maxIter = [];\nend\n\nif ~isfield(options,'nRepeat')\n    options.nRepeat = 10;\nend\n\nif ~isfield(options,'minIter')\n    options.minIter = 30;\nend\n\nif ~isfield(options,'meanFitRatio')\n    options.meanFitRatio = 0.1;\nend\n\nif ~isfield(options,'alpha')\n    options.alpha = 100;\nend\n\nif isfield(options,'alpha_nSmp') && options.alpha_nSmp\n    options.alpha = options.alpha*nSmp;    \nend\n\nif ~exist('U','var')\n    U = [];\n    V = [];\nend\n\nK = constructKernel(X',[],options);\n\nif isfield(options,'weight') && strcmpi(options.weight,'NCW')\n    D_mhalf = sum(K,2).^-.5;\n    D_mhalf = spdiags(D_mhalf,0,nSmp,nSmp);\n    K = D_mhalf*K*D_mhalf;\nend\n\nif ~isfield(options,'Optimization')\n    options.Optimization = 'Multiplicative';\nend\n\nswitch lower(options.Optimization)\n    case {lower('Multiplicative')} \n        [U_final, V_final, nIter_final,objhistory_final] = LCCF_Multi(K, k, W, options, U, V);\n    otherwise\n        error('optimization method does not exist!');\nend\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/MatrixFactorization/LCCF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5963135192815814}}
{"text": "% TEST_MAXWELL_CUBE_G_NMNN: data function for Neumann boundary condition.\n\nfunction g = test_maxwell_cube_g_nmnn (x, y, z, ind)\n\n  g = zeros ([3, size(x)]);\n  switch (ind)\n    case 1\n      g(2,:,:) = -(exp(x) .* cos(y) - z .* cos(y));\n      g(3,:,:) = sin(y) + exp(z) .* sin(x);\n    case 2\n      g(2,:,:) = exp(x) .* cos(y) - z .* cos(y);\n      g(3,:,:) = -(sin(y) + exp(z) .* sin(x));\n    case 3\n      g(1,:,:) = exp(x) .* cos(y) - z .* cos(y);\n    case 4\n      g(1,:,:) = -(exp(x) .* cos(y) - z .* cos(y));\n    case 5\n      g(1,:,:) = -(sin(y) + exp(z) .* sin(x));\n    case 6\n      g(1,:,:) = sin(y) + exp(z) .* sin(x);\n    otherwise\n      error ('g_nmnn: unknown reference number')\n  end\n\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/maxwell/data_files/test_maxwell_cube_g_nmnn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5963135151027087}}
{"text": "function [km2] = cm22km2(cm2)\n% Convert area from square centimeters to square kilometers.\n% Chad A. Greene 2012\nkm2 = cm2*1E-10;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/cm22km2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.5963135125071207}}
{"text": "%    The following is an implementation of \"the HMSD fusion based on the guided filter (HMSD-GF)\"\n%    (without visibility enhancement before the fusion).\n%    Ref: \"Fusion of infrared and visible images for night-vision context \n%    enhancement\", Applied Optics, 55(23), 2016\n%    \n%    The HMSD (Hybrid-MSD) fusion method was originally proposed in:\n%    Zhiqiang Zhou et al. \"Perceptual fusion of infrared and visible images through a hybrid \n%    multi-scale decomposition with Gaussian and bilateral filters\", Information Fusion, 30, 2016 \n%    \n%    Some of the test images were obtained at\n%      http://www.imagefusion.org\n%      http://www.ece.lehigh.edu/SPCRL/IF/image_fusion.htm\n%\n%    Zhiqiang Zhou, Beijing Institute of Technology\n%    Apr. 2016\n\nclear all;\n% close all;\nnLevel = 4;\n\n%  path_Vis = '.\\image\\b01_1.tif';      path_IR = '.\\image\\b01_2.tif';\n path_Vis = '.\\image\\Camp_Vis.jpg';      path_IR = '.\\image\\Camp_IR.jpg';\n% path_Vis = '.\\image\\Trees4906_Vis.jpg'; path_IR = '.\\image\\Trees4906_IR.jpg';\n% path_Vis = '.\\image\\Octec_Vis.jpg';     path_IR = '.\\image\\Octec_IR.jpg';\n% path_Vis = '.\\image\\Road_Vis.jpg';      path_IR = '.\\image\\Road_IR.jpg';\n% path_Vis = '.\\image\\Kayak_Vis.jpg';     path_IR = '.\\image\\Kayak_IR.jpg';\n% path_Vis = '.\\image\\Steamboat_Vis.jpg'; path_IR = '.\\image\\Steamboat_IR.jpg';\n% path_Vis = '.\\image\\Trees4917_Vis.jpg'; path_IR = '.\\image\\Trees4917_IR.jpg';\n% path_Vis = '.\\image\\Dune_Vis.jpg';      path_IR = '.\\image\\Dune_IR.jpg';\n\n[img1, img2, para.name] = PickName(path_Vis, path_IR);\nparaShow1.fig = 'Visible image';\nparaShow2.fig = 'Infrared image';\nShowImageGrad(img2, paraShow2);\nShowImageGrad(img1, paraShow1);\n\n% %% ---------- Visibility enhancement for visible image--------------\n% img1E = Ehn_GF(img1);\n% img1 = img1E;\n% %% ---------- Infrared image normalization--------------\n% mi = min(img2(:));\n% ma = max(img2(:));\n% img2 = (img2-mi)/(ma-mi)*255;\n\n%% ---------- Automatic parameter selection --------------\nRs = Relative_PS(img2, img1);\nif Rs<0.8\n    lambda = 100\nelse\n    if Rs>1.6\n        lambda = 2000\n    else\n        lambda = 2500*Rs - 1900\n    end\nend    \n\n%% ---------- Hybrid multiscale decomposition based on guided filter--------------\nsigma = 2;  k = 2;\nr0 = 2;     eps0 = 0.1;  \nl = 2;\n\nM1 = cell(1, nLevel+1);\nM1L = cell(1, nLevel+1);\nM1{1} = img1/255;\nM1L{1} = M1{1};\nM1D = cell(1, nLevel+1);\nM1E = cell(1, nLevel+1);\nsigma0 = sigma;\nr = r0;\neps = eps0;\nfor ii = 2:nLevel+1,\n    \n%     % ***using fast guided filter, which has the potential to achieve real-time performance when codes are fully optimized\n%     % ***NOTE: large subsampling ratio may cause problem for fusion of some source images.\n%     s = max(1, r/2); % subsampling ratio\n%     M1{ii} = fastguidedfilter_md(M1{ii-1}, M1{ii-1}, r, 100^2, s);  \n%     M1L{ii} = fastguidedfilter_md(M1L{ii-1}, M1L{ii-1}, r, eps^2, s);\n    \n    M1{ii} = guidedfilter(M1{ii-1}, M1{ii-1}, r, 100^2);  \n    M1L{ii} = guidedfilter(M1L{ii-1}, M1L{ii-1}, r, eps^2);    \n    \n    M1D{ii} = M1{ii-1} - M1L{ii};\n    M1E{ii} = M1L{ii} - M1{ii};\n    \n    sigma0 = k*sigma0;\n    r = k*r;\n    eps = eps/l;\nend\n\nM2 = cell(1, nLevel+1);\nM2L = cell(1, nLevel+1);\nM2{1} = img2/255;\nM2L{1} = M2{1};\nM2D = cell(1, nLevel+1);\nM2E = cell(1, nLevel+1);\nsigma0 = sigma;\nr = r0;\neps = eps0;\nfor ii = 2:nLevel+1,\n%     s = max(1, r/2);\n%     M2{ii} = fastguidedfilter_md(M2{ii-1}, M2{ii-1}, r, 100^2, s);\n%     M2L{ii} = fastguidedfilter_md(M2L{ii-1}, M2L{ii-1}, r, eps^2, s);\n    M2{ii} = guidedfilter(M2{ii-1}, M2{ii-1}, r, 100^2);\n    M2L{ii} = guidedfilter(M2L{ii-1}, M2L{ii-1}, r, eps^2);    \n \n    M2D{ii} = M2{ii-1} - M2L{ii};\n    M2E{ii} = M2L{ii} - M2{ii};\n\n    sigma0 = k*sigma0;\n    r = k*r;\n    eps = eps/l;\nend\n\n%% ---------- Fusion --------------\n\nfor j = nLevel+1:-1:3\nD2 = abs(M2E{j});\nD1 = abs(M1E{j});\nR = max(D2-D1, 0);\nRmax = max(R(:));\nP = R/Rmax;\n\nCj = atan(lambda*P)/atan(lambda);\n\nsigma_b = 2*sigma0;\nif j == nLevel+1\n    w = floor(3*sigma_b);\n    h = fspecial('gaussian', [2*w+1, 2*w+1], sigma_b);\n    lambda0 = lambda;\n    Cb = atan(lambda0*P)/atan(lambda0);\n    Cb = imfilter(Cb, h, 'symmetric');\n    MB = Cb.*M2{nLevel+1} + (1-Cb).*M1{nLevel+1};\nend\n\nsigma_c = 1;\nw = floor(3*sigma_c);\nh = fspecial('gaussian', [2*w+1, 2*w+1], sigma_c);   \nCj = imfilter(Cj, h, 'symmetric');\n\nmd = Cj.*M2E{j}+ (1-Cj).*M1E{j};\nMB = MB + md;\nmd = Cj.*M2D{j}+ (1-Cj).*M1D{j};\nMB = MB + md;\nend \n\nsigma_t = 1;\nw = floor(3*sigma_t);\nh = fspecial('gaussian', [2*w+1, 2*w+1], sigma_t);   \nC11 = double(abs(M1E{2}) < abs(M2E{2}));\nC11 = imfilter(C11, h, 'symmetric');\nmd = C11.*M2E{2}+ (1-C11).*M1E{2};\nMB = MB + md;  \nC10 = double(abs(M1D{2}) < abs(M2D{2}));\nmd = C10.*M2D{2}+ (1-C10).*M1D{2};\nMB = MB + md;\nFI = min(round(MB*275), 255);\nFI = max(FI, 0);\n\nparaShow.fig = 'Result';\nShowImageGrad(FI, paraShow);\n\n\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/Context-Enhance-via-Fusion-master/Context_Enhance_via_Fusion/HMSD_GF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5963135072511138}}
{"text": "function abram2_values_test ( )\n\n%*****************************************************************************80\n%\n%% ABRAM2_VALUES_TEST demonstrates the use of ABRAM2_VALUES.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    13 April 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'ABRAM2_VALUES_TEST:\\n' );\n  fprintf ( 1, '  ABRAM2_VALUES stores values of \\n' );\n  fprintf ( 1, '  the Abramowitz function of order 2.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '      X           FX\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x, fx ] = abram2_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/abram2_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.5963083059334868}}
{"text": "function [ r, z, rho, c, s ] = dchud ( r, ldr, p, x, z, ldz, nz, y, rho )\n\n%*****************************************************************************80\n%\n%% DCHUD updates an augmented Cholesky decomposition.\n%\n%  Discussion:\n%\n%    DCHUD can also update the triangular part of an augmented QR\n%    decomposition.\n%\n%    Specifically, given an upper triangular matrix R of order P, a row vector\n%    X, a column vector Z, and a scalar Y, DCHUD determines a unitary matrix\n%    U and a scalar ZETA such that\n%\n%           (R  Z)     (RR   ZZ )\n%      U  * (    )  =  (        ),\n%           (X  Y)     ( 0  ZETA)\n%\n%    where RR is upper triangular.\n%\n%    If R and Z have been obtained from the factorization of a least squares\n%    problem, then RR and ZZ are the factors corresponding to the problem\n%    with the observation (X,Y) appended.  In this case, if RHO is the\n%    norm of the residual vector, then the norm of the residual vector of\n%    the updated problem is sqrt ( RHO * RHO + ZETA * ZETA ).  DCHUD will\n%    simultaneously update several triplets (Z, Y, RHO).\n%\n%    For a less terse description of what DCHUD does and how\n%    it may be applied, see the LINPACK guide.\n%\n%    The matrix U is determined as the product U(P)*...*U(1),\n%    where U(I) is a rotation in the (I,P+1) plane of the form\n%\n%      (     C(I)      S(I) )\n%      (                    ).\n%      (    -S(I)      C(I) )\n%\n%    The rotations are chosen so that C(I) is real.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    18 June 2005\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, real R(LDR,P), the upper triangular matrix to be\n%    updated.  The part of R below the diagonal is not referenced.\n%\n%    Input, integer LDR, the leading dimension of the array R.\n%    LDR must be at least equal to P.\n%\n%    Input, integer P, the order of the matrix R.\n%\n%    Input, real X(P), the row to be added to R.\n%\n%    Input, real Z(LDZ,NZ), contains NZ P-vectors to be updated with R.\n%\n%    Input, integer LDZ, the leading dimension of the array Z.\n%    LDZ must be at least P.\n%\n%    Input, integer NZ, the number of vectors to be updated.  NZ may be\n%    zero, in which case Z, Y, and RHO are not referenced.\n%\n%    Input, real Y(NZ), the scalars for updating the vectors Z.\n%\n%    Input, real RHO(NZ), the norms of the residual vectors to be updated.  \n%    If RHO(J) is negative, it is left unaltered.\n%\n%    Output, real R(LDR,P), the updated matrix.\n%\n%    Output, real Z(LDZ,NZ), the updated vectors.\n%\n%    Output, real RHO(NZ), the updated norms of the residual vectors.\n%\n%    Output, real C(P), S(P), the cosines and sines of the\n%    transforming rotations.\n%\n\n%\n%  Update R.\n%\n  for j = 1: p\n\n    xj = x(j);\n%\n%  Apply the previous rotations.\n%\n    for i = 1 : j-1\n      t = c(i) * r(i,j) + s(i) * xj;\n      xj = c(i) * xj - s(i) * r(i,j);\n      r(i,j) = t;\n    end\n%\n%  Compute the next rotation.\n%\n    [ c(j), s(j), r(j,j), xj ] = drotg ( r(j,j), xj );\n\n  end\n%\n%  If required, update Z and RHO.\n%\n  for j = 1 : nz\n\n    zeta = y(j);\n\n    for i = 1 : p\n      t =    c(i) * z(i,j) + s(i) * zeta;\n      zeta = c(i) * zeta   - s(i) * z(i,j);\n      z(i,j) = t;\n    end\n\n    azeta = abs ( zeta );\n\n    if ( azeta ~= 0.0 & 0.0 <= rho(j) )\n      scale = azeta + rho(j);\n      rho(j) = scale * sqrt ( ( azeta / scale )^2 + ( rho(j) / scale )^2 );\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/linpack_d/dchud.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5961804075731609}}
{"text": "%% Calculate mean angular error between source and target images\n%\n% Copyright (c) 2018-present, Mahmoud Afifi\n% York University, Canada\n% mafifi@eecs.yorku.ca | m.3afifi@gmail.com\n%\n% This source code is licensed under the license found in the\n% LICENSE file in the root directory of this source tree.\n% All rights reserved.\n%\n% Please cite the following work if this program is used:\n% Mahmoud Afifi, Brian Price, Scott Cohen, and Michael S. Brown, \n% \"When color constancy goes wrong: Correcting improperly white-balanced \n% images\", CVPR 2019.\n%\n% Input:\n%   -source: image A\n%   -target: image B \n%   -color_chart_area: If there is a color chart in the image (that is\n%   masked out from both images, this variable represents the number of\n%   pixels of the color chart.\n%\n% Output:\n%   -f: the mean angular error between image A and image B.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% \nfunction f = calc_mae(source, target,color_chart_area)\n\nif size(source,1)<=color_chart_area\n    error('Color chart area should be less than the image area');\nend\nsource=double(source);\ntarget=double(target);\ntarget_norm = sqrt(sum(target.^2,2));\nsource_mapped_norm = sqrt(sum(source.^2,2));\nangles=dot(source,target,2)./(source_mapped_norm.*target_norm);\nangles(angles>1)=1;\nf=acosd(angles);\nf(isnan(f))=0;\nf=sum(f)/(size(source,1)-color_chart_area);\nend", "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/calc_mae.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5960812658157358}}
{"text": "% VOCLABELCOLORMAP Creates a label color map such that adjacent indices have different\n% colors.  Useful for reading and writing index images which contain large indices,\n% by encoding them as RGB images.\n%\n% CMAP = VOCLABELCOLORMAP(N) creates a label color map with N entries.\nfunction cmap = labelcolormap(N)\n\nif nargin==0\n    N=256\nend\ncmap = zeros(N,3);\nfor i=1:N\n    id = i-1; r=0;g=0;b=0;\n    for j=0:7\n        r = bitor(r, bitshift(bitget(id,1),7 - j));\n        g = bitor(g, bitshift(bitget(id,2),7 - j));\n        b = bitor(b, bitshift(bitget(id,3),7 - j));\n        id = bitshift(id,-3);\n    end\n    cmap(i,1)=r; cmap(i,2)=g; cmap(i,3)=b;\nend\ncmap = cmap / 255;\n", "meta": {"author": "peiyunh", "repo": "tiny", "sha": "37c44deacf53e0fbe23327ef3721b5fb5f22559f", "save_path": "github-repos/MATLAB/peiyunh-tiny", "path": "github-repos/MATLAB/peiyunh-tiny/tiny-37c44deacf53e0fbe23327ef3721b5fb5f22559f/toolbox/VOClabelcolormap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581097540518, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.596017311570906}}
{"text": "%% Interactive Perspective Transformation\n% This program demonstrates Perspective Transformation.\n%\n% In this sample you will learn how to use the following OpenCV functions:\n%\n% * <matlab:doc('cv.getPerspectiveTransform') cv.getPerspectiveTransform>\n% * <matlab:doc('cv.warpPerspective') cv.warpPerspective>\n% * <matlab:doc('cv.perspectiveTransform') cv.perspectiveTransform>\n%\n\nfunction varargout = perspective_transform_gui(im)\n    % load source image\n    if nargin < 1\n        img = imread(fullfile(mexopencv.root(),'test','fruits.jpg'));\n    elseif ischar(im)\n        img = imread(im);\n    else\n        img = im;\n    end\n\n    % create the UI\n    h = buildGUI(img);\n    if nargout > 0, varargout{1} = h; end\nend\n\nfunction onHelp(~,~)\n    %ONHELP  Display usage help dialog\n\n    helpdlg({\n        'This program demonstrates Perspective Transformation.'\n        ''\n        'Drag the image corners using the mouse: Move the pointer over a'\n        'vertex. The pointer changes to a circle. Click and drag the vertex'\n        'to its new position.'\n        ''\n        'You can also drag the image itself: move the pointer inside the'\n        'quadilateral. The pointer changes to a fleur shape. Click and drag'\n        'the mouse to move the image.'\n        ''\n        'Note: you must not add or remove points from the polygon.'\n        'The cv.getPerspectiveTransform function requires exactly'\n        '4 points to estimate the homography.'\n        'Also the function works best if no three points are collinear.'\n    });\nend\n\nfunction onDrag(newpos, handles)\n    %ONDRAG  Event handler for impoly\n\n    % compute the perspective transform matrix from matching corners\n    H = cv.getPerspectiveTransform(handles.pos, newpos);\n\n    % trigger redraw with the new homography\n    redraw(handles, H);\nend\n\nfunction redraw(handles, H)\n    %REDRAW  Warp and repaint image\n\n    % apply the perspective transformation on the source image\n    img2 = cv.warpPerspective(handles.img, H);\n\n    % display warped image and homography matrix\n    set(handles.hImg, 'CData',img2);\n    set(handles.hTxt, 'String',mat2str_latex(H));\n    drawnow limitrate;\nend\n\nfunction showModalDialog(~,~,handles)\n    %SHOWMODELDIALOG  Display dialog to edit matrix\n\n    % prompt for matrix using a model dialog\n    d = dialog('Position',[50 50 280 140], 'Resize','off', 'Name','Homography');\n    movegui(d, 'center');\n    uicontrol('Parent',d, 'Style','push', 'Position',[80 10 60 20], ...\n        'String','Ok', 'Callback',{@onDialogClose,true});\n    uicontrol('Parent',d, 'Style','push', 'Position',[140 10 60 20], ...\n        'String','Cancel', 'Callback',{@onDialogClose,false});\n    t = uitable(d, 'Position',[15 40 250 90], ...\n        'Data',eye(3), 'ColumnWidth',{70}, 'ColumnEditable',true, ...\n        'TooltipString','fill the 3x3 homography matrix');\n\n    % wait for dialog to close before returning\n    uiwait(d);\n\n    function onDialogClose(~,~,flag)\n        H = get(t, 'Data');  % get entered matrix\n        delete(gcf);         % close dialog\n        if flag && ~any(isnan(H(:)))\n            % update impoly position\n            newpos = cv.perspectiveTransform(handles.pos, H);\n            setPosition(handles.hPoly, newpos);\n            % transform image\n            redraw(handles, H);\n        end\n    end\nend\n\nfunction str = mat2str_latex(M)\n    %MAT2STR_LATEX  Convert numeric matrix to a latex table for display\n\n    %str = mat2str(M,3);\n    M = round(M, 9);  % nicely rounded numbers (for stuff like 1e-15)\n    str = ['$$H = \\left[\\begin{array}{ccc}' ...\n        sprintf('%.3g & %.3g & %.3g \\\\\\\\ ',M(1,:)) ...\n        sprintf('%.3g & %.3g & %.3g \\\\\\\\ ',M(2,:)) ...\n        sprintf('%.3g & %.3g & %.3g ',M(3,:)) ...\n        '\\end{array}\\right]$$'];\nend\n\nfunction img = print_instructions(img)\n    %PRINT_INSTRUCTIONS  Show help text on top of image\n\n    if nargin < 1, img = zeros([512 512 3], 'uint8'); end\n    opts = {'Color',[255 0 0], 'Thickness',3, 'FontScale',1.7};\n    img = cv.putText(img, 'Drag the image', [50 200], opts{:});\n    img = cv.putText(img, 'corners using', [50 300], opts{:});\n    img = cv.putText(img, 'the mouse.', [50 400], opts{:});\nend\n\nfunction handles = buildGUI(img)\n    %BUILDGUI  Creates the UI\n\n    handles = struct();\n    handles.img = print_instructions(img);\n\n    % initial quadilateral (image corners), from top-left in clockwise order\n    [h,w,~] = size(handles.img);\n    handles.pos = [1 1; w 1; w h; 1 h];\n\n    % display image and homography matrix\n    handles.hImg = imshow(handles.img);\n    handles.hTxt = text(10, 10, mat2str_latex(eye(3)), ...\n        'Interpreter','latex', 'FontSize',20, 'Color','y', ...\n        'HorizontalAlignment','left', 'VerticalAlignment','top');\n\n    % create draggable polygon\n    handles.hPoly = impoly(get(handles.hImg,'Parent'), handles.pos, 'Closed',true);\n    setColor(handles.hPoly, 'y');\n    if false\n        % restrict polygon inside image limits\n        setPositionConstraintFcn(hPoly, ...\n            makeConstrainToRectFcn('impozy',[1 w], [1 h]));\n    end\n\n    uicontrol('Style','pushbutton', 'Position',[20 20 60 20], 'String','Help', ...\n        'Callback',@onHelp);\n    uicontrol('Style','pushbutton', 'Position',[80 20 60 20], 'String','Reset', ...\n        'Callback',@(~,~) setPosition(handles.hPoly, handles.pos));\n    uicontrol('Style','pushbutton', 'Position',[140 20 60 20], 'String','Preset 1', ...\n        'Callback',@(~,~) setPosition(handles.hPoly, [100 100; w-100 100; w h; 1 h]));\n    uicontrol('Style','pushbutton', 'Position',[200 20 60 20], 'String','Preset 2', ...\n        'Callback',@(~,~) setPosition(handles.hPoly, [w+25 -25; 25 200; 175 h-10; w-100 h-50]));\n    uicontrol('Style','pushbutton', 'Position',[260 20 60 20], 'String','Manual', ...\n        'Callback',{@showModalDialog,handles});\n\n    % set callback when dragging points\n    addNewPositionCallback(handles.hPoly, @(p) onDrag(p, handles));\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/perspective_transform_gui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.5960173087684671}}
{"text": "classdef prtClassFld < prtClass\n %prtClassFld Fisher linear discriminant classifier\n % \n %    CLASSIFIER = prtClassFld returns a Fisher linear discriminant classifier\n %\n %    CLASSIFIER = prtClassFld(PROPERTY1, VALUE1, ...) constructs a\n %    prtClassFld object CLASSIFIER with properties as specified by\n %    PROPERTY/VALUE pairs.\n %\n %    A prtClassFld object inherits all properties from the abstract class\n %    prtClass. In addition is has the following properties:\n %\n %    w                  - regression weights, estimated during training\n %    plotBasis          - Flag indicating whether to plot the basis\n %                         functions when the PLOT function is called\n %    plotProjections    - Flag indicating whether to plot the projection\n %                         of points to the basis when the PLOT function is\n %                         called\n %\n %    For information on the Fisher Linear Discriminant algorithm, please\n %    refer to the following URL:\n %\n %    http://en.wikipedia.org/wiki/Linear_discriminant_analysis#Fisher.27s_linear_discriminant\n %\n %    A prtClassFld object inherits the TRAIN, RUN, CROSSVALIDATE and\n %    KFOLDS methods from prtAction. It also inherits the PLOT method from\n %    prtClass.\n %\n %    Example:\n %\n %    ds1 = prtDataGenUnimodal;       % Create some test and\n %    ds2 = prtDataGenUnimodal;   % training data\n %    classifier = prtClassFld;           % Create a classifier\n %    classifier = classifier.train(ds1);    % Train\n %    classified = run(classifier, ds2);         % Test\n %    subplot(2,1,1);\n %    classifier.plot;\n %    subplot(2,1,2);\n %    [pf,pd] = prtScoreRoc(classified);\n %    h = plot(pf,pd,'linewidth',3);\n %    title('ROC'); xlabel('Pf'); ylabel('Pd');\n %  \n %   See also prtClass, prtClassLogisticDiscriminant, prtClassBagging,\n %   prtClassMap, prtClassCap, prtClassBinaryToMaryOneVsAll, prtClassDlrt,\n %   prtClassPlsda, prtClassKnn, prtClassRvm, prtClassGlrt,  prtClassSvm,\n %   prtClassTreeBaggingCap, prtClassKmsd, prtClassKnn  \n\n\n\n\n% Copyright (c) 2013 New Folder Consulting \n%\n% Permission is hereby granted, free of charge, to any person obtaining a\n% copy of this software and associated documentation files (the\n% \"Software\"), to deal in the Software without restriction, including\n% without limitation the rights to use, copy, modify, merge, publish,\n% distribute, sublicense, and/or sell copies of the Software, and to permit\n% persons to whom the Software is furnished to do so, subject to the\n% following conditions:\n%\n% The above copyright notice and this permission notice shall be included\n% in all copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n% OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n% NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n% DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n% OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n% USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n \n\n    properties (SetAccess=private)\n        \n        name = 'Fisher Linear Discriminant' % Fisher Linear Discriminant\n        nameAbbreviation = 'FLD'            % FLD\n        isNativeMary = false;  % False\n    end\n    \n    properties (SetAccess = protected)\n        % w is a dataSet.nDimensions x 1 vector of projection weights\n        % learned during Fld.train(dataSet)\n        \n        w = []; % The vector of weights, learned during training\n        \n        % plotting options\n        plotBasis = false; % Flag indicating whether or not to plot the basis\n        plotProjections = false; % Flag indicating whether or not to plot the projections\n    end\n    \n    methods\n     \n               % Allow for string, value pairs\n        function self = prtClassFld(varargin)\n            self = prtUtilAssignStringValuePairs(self,varargin{:});\n        end\n        \n        function self = set.plotProjections(self,value)\n            if islogical(value) || (isnumeric(value) && (value == 1 || value == 0))\n                self.plotProjections = value;\n            else\n                error('prt:prtClassFld:plotProjections','plotProjections can only take true or false (boolean or 0/1) values; user speficied value %d',value);\n            end\n        end\n    end\n    \n    methods (Access=protected, Hidden = true)\n        \n        function self = trainAction(self,dataSet)\n            \n            n = dataSet.nObservations;\n            p = dataSet.nFeatures;\n            \n            if p > n\n                warning('prt:prtClassFld:train:illconditioned','dataSet has n (%d) < p (%d); prtClassFld may not be stable',n,p);\n            end\n            if ~dataSet.isBinary\n                error('prtClassFld:nonBinaryTraining','Input dataSet for prtClassFld.train must be binary');\n            end\n            \n            \n            dataH0 = dataSet.getObservationsByClassInd(1);\n            dataH1 = dataSet.getObservationsByClassInd(2);\n            \n            mean0 = mean(dataH0,1);\n            mean1 = mean(dataH1,1);\n            \n            cov0 = cov(dataH0);\n            cov1 = cov(dataH1);\n            covW = cov1 + cov0;\n            \n            self.w = covW\\(mean1-mean0)'; %w = covW^-1 * (mean1-mean0)'; But better\n            self.w = self.w./norm(self.w);\n            \n        end\n        \n        function dataSet = runAction(self,dataSet)\n            %dataSet = prtDataSetClass((self.w'*dataSet.getObservations()')');\n            dataSet.X = (self.w'*dataSet.getObservations()')';\n        end\n        \n        function imageHandle = plotGriddedEvaledClassifier(self, DS, linGrid, gridSize, cMap)\n            \n            % Call the original plot function\n            imageHandle = plotGriddedEvaledClassifier@prtClass(self, DS, linGrid, gridSize, cMap);\n            \n            W = self.w;\n            limits = axis;\n            nDims = length(W);\n            \n            if self.plotBasis\n                hold on\n                switch nDims\n                    case 1\n                        % Nothing\n                    case 2\n                        distances = zeros(4,1);\n                        distances(1) = sqrt(sum([limits(2); limits(4)].^2));\n                        distances(2) = sqrt(sum([limits(1); limits(3)].^2));\n                        distances(3) = sqrt(sum([limits(2); limits(3)].^2));\n                        distances(4) = sqrt(sum([limits(1); limits(4)].^2));\n                \n                        highPoint =  max(distances).*W;\n                        lowPoint =  -max(distances).*W;\n                \n                        h = plot([lowPoint(1),highPoint(1)],[lowPoint(2),highPoint(2)],'k');\n                        set(h,'linewidth',3);\n                    case 3\n                        distances = zeros(8,1);\n                        distances(1) = sqrt(sum([limits(1); limits(3); limits(5)].^2));\n                        distances(2) = sqrt(sum([limits(1); limits(3); limits(6)].^2));\n                        distances(3) = sqrt(sum([limits(1); limits(4); limits(5)].^2));\n                        distances(4) = sqrt(sum([limits(1); limits(4); limits(6)].^2));\n                        distances(5) = sqrt(sum([limits(2); limits(3); limits(5)].^2));\n                        distances(6) = sqrt(sum([limits(2); limits(3); limits(6)].^2));\n                        distances(7) = sqrt(sum([limits(2); limits(4); limits(5)].^2));\n                        distances(8) = sqrt(sum([limits(2); limits(4); limits(6)].^2));\n                \n                        highPoint =  max(distances).*W;\n                        lowPoint =  -max(distances).*W;\n                \n                        h = plot3([lowPoint(1),highPoint(1)],[lowPoint(2),highPoint(2)],[lowPoint(3), highPoint(3)],'k');\n                        set(h,'linewidth',3);\n                    otherwise\n                        error('prt:prtClassFld:tooManyDimensions','Too many dimensions for plotting.')\n                end\n            end\n\n            if self.plotProjections && ~isempty(self.dataSet)\n                OutputDataSet = run(self, self.dataSet);\n                hold on;\n                switch nDims\n                    case 2\n                        for i = 1:double(self.plotProjections):self.dataSet.nObservations\n                            cX = self.dataSet.X(i,:);\n                            cYout = OutputDataSet.X(i,:);\n                            plot([cX(1),cYout*W(1)],[cX(2),cYout*W(2)],'k');\n                        end\n                    case 3\n                        for i = 1:double(self.plotProjections):self.dataSet.nObservations\n                            cX = self.dataSet.X(i,:);\n                            cYout = OutputDataSet.X(i,:);\n                            plot3([cX(1),cYout*W(1)],[cX(2),cYout*W(2)],[cX(3),cYout*W(3)],'k');\n                        end\n                end\n                axis(limits);\n            end\n            hold off;\n        end\n        \n    end\n    \nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/class/prtClassFld.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.595982721035929}}
{"text": "function [B,Theta_diag,C_diag,Alpha_diag,Fit_diag,...\n    C_offdiag,Theta_offdiag,Alpha_offdiag,Fit_offdiag phi_t]=smooth_data(C,K,Q,nloop_diag,nloop_offdiag)\n\n%% This function is a wrapper for the smooth_mcmc function, which does the actual smoothing\n%% This was written to smoot the diagonal and off-diagonal conectivity time series separately\n%% and to save the coefficents and basis functions from each\n\n\nN=size(C,1);   \nM_i=zeros(N,1);\nfor i=1:N      \n    M_i(i)=size(C{i},1);\nend\n\n\n%% Get smoothed time-varying connectivity coefficients\n\n% smooth diagonal connectivities\nC_diag=cell(sum(M_i),1);\nind=0;\nfor i=1:N\n    for j=1:M_i(i)\n        ind=ind+1;\n        C_diag{ind}=squeeze(C{i}(j,j,:));\n    end\nend    \n[ALPHA ALPHA_BAR THETA FIT phi_t]=smooth_mcmc(C_diag,K,Q,nloop_diag);\nfirst=round(nloop_diag/2); last=nloop_diag+1;\nAlpha_diag=mean(ALPHA(:,:,first:last),3);\nTheta_diag=mean(THETA(:,:,first:last),3);\nFit_diag=phi_t'*Theta_diag*Alpha_diag;\n\nB=cell(N,1);\nind=0;\nfor i=1:N\n    B{i}=cell(M_i(i));\n    for j=1:M_i(i)\n        ind=ind+1;\n        B{i}{j,j}=Alpha_diag(:,ind)';\n    end\nend\n\n\n% smooth off-diagonal connectivities\nM_offdiag=M_i(1)^2-M_i(1);\nfor i=2:N\n    M_offdiag=M_offdiag+M_i(i)^2-M_i(i);\nend\n    \nC_offdiag=cell(M_offdiag,1);\nind=0;\nfor i=1:N\n    for j1=1:M_i(i)\n        for j2=1:M_i(i)\n            if(not(j1==j2))\n                ind=ind+1;\n                C_offdiag{ind}=squeeze(C{i}(j1,j2,:));\n            end\n        end\n    end\nend    \n[ALPHA ALPHA_BAR THETA FIT phi_t]=smooth_mcmc(C_offdiag,K,Q,nloop_offdiag);\nfirst=round(nloop_offdiag/2); last=nloop_offdiag+1;\nAlpha_offdiag=mean(ALPHA(:,:,first:last),3);\nTheta_offdiag=mean(THETA(:,:,first:last),3);\nFit_offdiag=phi_t'*Theta_offdiag*Alpha_offdiag;\n\nind=0;\nfor i=1:N\n    for j1=1:M_i(i)\n        for j2=1:M_i(i)\n            if not(j1==j2)\n                ind=ind+1;\n                B{i}{j1,j2}=Alpha_offdiag(:,ind)';\n            end\n        end\n    end\nend\n\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/grp/bayes/smooth_data_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5959827079088115}}
{"text": "function zernike_poly_coef_test ( )\n\n%*****************************************************************************80\n%\n%% ZERNIKE_POLY_COEF_TEST tests ZERNIKE_POLY_COEF.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    19 October 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 5;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'ZERNIKE_POLY_COEF_TEST\\n' );\n  fprintf ( 1, '  ZERNIKE_POLY_COEF determines the Zernike \\n' );\n  fprintf ( 1, '  polynomial coefficients.\\n' );\n\n  for m = 0 : n\n\n    c = zernike_poly_coef ( m, n );\n \n    r8poly_print ( n, c, '  Zernike polynomial' );\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/zernike_poly_coef_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.5959826999960047}}
{"text": "function AnalyzePersistence(Data,AggregationPersistence,LagsSamplAutCorr,Name)\n\nfor n=1:length(AggregationPersistence)\n    Series_Changes(n).Lag=AggregationPersistence(n);\n    SamplAutoCorrs=[];\n    \n    for s=1:AggregationPersistence(n)\n        \n        Sparse=Data(s:AggregationPersistence(n):end);\n        Changes=diff(Sparse);\n        SamplAutoCorrs = autocorr(Changes, LagsSamplAutCorr);\n        SamplAutoCorrs(1)=[];\n    end\n    Series_Changes(n).SampleAutocorrelation=mean(SamplAutoCorrs,2);\nend\n\nSampleAutocorrelations=[];\nfor n=1:length(AggregationPersistence)\n    SampleAutocorrelations=[SampleAutocorrelations Series_Changes(n).SampleAutocorrelation];\nend\n\nfigure\nbar3(SampleAutocorrelations,'detached')\nset(gca,'xlim',[AggregationPersistence(1) AggregationPersistence(end)],'ylim',[1 LagsSamplAutCorr],...\n    'zlim',[-.2 .4])\nxlabel('aggregation size (days)')\nylabel('lag')\nzlabel('autocorrelation')\ncolormap(.5*(1+gray));\nset(gcf,'Name',['        persistence properties of ' Name ' par swap rate'])\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23554-review-of-discrete-and-continuous-processes-in-finance/Matlab/03LongMemory/Empirical/AnalyzePersistence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5959826935782666}}
{"text": "function scatter3sph(X,Y,Z,varargin)\n%SCATTER3SPH (X,Y,Z) Plots a 3d scatter plot with 3D spheres\n%\tSCATTER3SPH is like scatter3 only drawing spheres with volume, instead\n%\tof flat circles, at coordinates specified by vectors X, Y, Z. All three\n%\tvectors have to be of the same length.\n%\tSCATTER3SPH(X,Y,Z) draws the spheres with the default size and color.\n%\tSCATTER3SPH(X,Y,Z,'size',S) draws the spheres with sizes S. If length(S)= 1\n%\tthe same size is used for all spheres.\n%\tSCATTER3SPH(X,Y,Z,'color',C) draws the spheres with colors speciffied in a\n%\tN-by-3 matrix C as RGB values.\n%\tParameter names can be abreviated to 3 letters. For example: 'siz' or \n%\t'col'. Case is irrelevant.\n%\n% Example\n% %Coordinates\n%  X= 100*rand(9,1); Y= 100*rand(9,1); Z= 100*rand(9,1);\n% \n% %Colors: 3 blue, 3 red and 3 green\n% C= ones(3,1)*[0 0 1];\n% C= [C;ones(3,1)*[1 0 0]];\n% C= [C;ones(3,1)*[0 1 0]];\n% \n% %Spheres sizes\n% S= 5+10*rand(9,1);\n% \n% figure(1);\n% scatter3sph(X,Y,Z,'size',S,'color',C);\n% axis equal\n% axis tight\n% view(125,20);\n% grid ON\n\n%-- Some checking...\nif nargin < 3 error('Need at least three arguments'); return; end\nif mean([length(X),length(Y),length(Z)]) ~= length(X) error ('Imput vectors X, Y, Z are of different lengths'); return; end\n\n%-- Defaults\nC= ones(length(X),1)*[0 0 1];\nS= 0.1*max([X;Y;Z])*ones(length(X),1);\n\n\n%-- Extract optional arguments\nfor j= 1:2:length(varargin)\n\tstring= lower(varargin{j});\n\tswitch string(1:min(3,length(string)))\n\t\tcase 'siz'\n\t\t\tS= varargin{j+1};\n\t\t\tif length(S) == 1\n\t\t\t\tS= ones(length(X),1)*S;\n\t\t\telseif length(S) < length(X)\n\t\t\t\terror('The vector of sizes must be of the same length as coordinate vectors (or 1)');\n\t\t\t\treturn\n\t\t\tend\n\n\t\tcase 'col'\n\t\t\tC= varargin{j+1};\n\t\t\tif size(C,2) < 3\terror('Colors matrix must have 3 columns'); return; end\n\t\t\tif size(C,1) == 1\n\t\t\t\tC= ones(length(X),1)*C(1:3);\n\t\t\telseif size(C,1) < length(X)\n\t\t\t\terror('Colors matrix must have the same number of rows as length of coordinate vectors (or 1)');\n\t\t\t\treturn\n\t\t\tend\n\n\t\totherwise\n\t\t\terror('Unknown parameter name. Allowed names: ''size'', ''color'' ');\n\tend\nend\n\n%-- Sphere facets\n[sx,sy,sz]= sphere(20);\n\n%-- Plot spheres\nhold on\nfor j= 1:length(X)\n\tsurf(sx*S(j)+X(j), sy*S(j)+Y(j), sz*S(j)+Z(j),...\n\t\t'LineStyle','none',...\n\t\t'AmbientStrength',0.4,...\n\t\t'FaceColor',C(j,:),...\n\t\t'SpecularStrength',0.8,...\n\t\t'DiffuseStrength',1,...\n\t\t'FaceAlpha',0.65,...\n\t\t'SpecularExponent',2);\nend\nlight('Position',[0 0 1],'Style','infinit','Color',[1 1 1]);\nlighting gouraud\nview(30,15)\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/27112-scatter3sph/scatter3sph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5959804557946178}}
{"text": "function [centres, options, post, errlog] = kmeans(centres, data, options)\n%KMEANS\tTrains a k means cluster model.\n%\n%\tDescription\n%\t CENTRES = KMEANS(CENTRES, DATA, OPTIONS) uses the batch K-means\n%\talgorithm to set the centres of a cluster model. The matrix DATA\n%\trepresents the data which is being clustered, with each row\n%\tcorresponding to a vector. The sum of squares error function is used.\n%\tThe point at which a local minimum is achieved is returned as\n%\tCENTRES.  The error value at that point is returned in OPTIONS(8).\n%\n%\t[CENTRES, OPTIONS, POST, ERRLOG] = KMEANS(CENTRES, DATA, OPTIONS)\n%\talso returns the cluster number (in a one-of-N encoding) for each\n%\tdata point in POST and a log of the error values after each cycle in\n%\tERRLOG.    The optional parameters have the following\n%\tinterpretations.\n%\n%\tOPTIONS(1) is set to 1 to display error values; also logs error\n%\tvalues in the return argument ERRLOG. If OPTIONS(1) is set to 0, then\n%\tonly warning messages are displayed.  If OPTIONS(1) is -1, then\n%\tnothing is displayed.\n%\n%\tOPTIONS(2) is a measure of the absolute precision required for the\n%\tvalue of CENTRES at the solution.  If the absolute difference between\n%\tthe values of CENTRES between two successive steps is less than\n%\tOPTIONS(2), then this condition is satisfied.\n%\n%\tOPTIONS(3) is a measure of the precision required of the error\n%\tfunction at the solution.  If the absolute difference between the\n%\terror functions between two successive steps is less than OPTIONS(3),\n%\tthen this condition is satisfied. Both this and the previous\n%\tcondition must be satisfied for termination.\n%\n%\tOPTIONS(14) is the maximum number of iterations; default 100.\n%\n%\tSee also\n%\tGMMINIT, GMMEM\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n[ndata, data_dim] = size(data);\n[ncentres, dim] = size(centres);\n\nif dim ~= data_dim\n  error('Data dimension does not match dimension of centres')\nend\n\nif (ncentres > ndata)\n  error('More centres than data')\nend\n\n% Sort out the options\nif (options(14))\n  niters = options(14);\nelse\n  niters = 100;\nend\n\nstore = 0;\nif (nargout > 3)\n  store = 1;\n  errlog = zeros(1, niters);\nend\n\n% Check if centres and posteriors need to be initialised from data\nif (options(5) == 1)\n  % Do the initialisation\n  perm = randperm(ndata);\n  perm = perm(1:ncentres);\n\n  % Assign first ncentres (permuted) data points as centres\n  centres = data(perm, :);\nend\n% Matrix to make unit vectors easy to construct\nid = eye(ncentres);\n\n% Main loop of algorithm\nfor n = 1:niters\n\n  % Save old centres to check for termination\n  old_centres = centres;\n  \n  % Calculate posteriors based on existing centres\n  d2 = dist2(data, centres);\n  % Assign each point to nearest centre\n  [minvals, index] = min(d2', [], 1);\n  post = id(index,:);\n\n  num_points = sum(post, 1);\n  % Adjust the centres based on new posteriors\n  for j = 1:ncentres\n    if (num_points(j) > 0)\n      centres(j,:) = sum(data(find(post(:,j)),:), 1)/num_points(j);\n    end\n  end\n\n  % Error value is total squared distance from cluster centres\n  e = sum(minvals);\n  if store\n    errlog(n) = e;\n  end\n  if options(1) > 0\n    fprintf(1, 'Cycle %4d  Error %11.6f\\n', n, e);\n  end\n\n  if n > 1\n    % Test for termination\n    if max(max(abs(centres - old_centres))) < options(2) & ...\n        abs(old_e - e) < options(3)\n      options(8) = e;\n      return;\n    end\n  end\n  old_e = e;\nend\n\n% If we get here, then we haven't terminated in the given number of \n% iterations.\noptions(8) = e;\nif (options(1) >= 0)\n  disp(maxitmess);\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/kmeansNetlab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5959712685543039}}
{"text": "function prob = survProbStdModel(t,b,time)\n% survProbStdModel: Computes survival probability using the standard model\n\nprob = ones(size(t));\ntime0 = [0;time];\ndtime = diff(time0);\n\nfor jdx=1:length(time)\n   if jdx < length(time)\n      tmpidx = t > time0(jdx) & t <= time0(jdx+1);\n   else\n      tmpidx = t > time0(jdx);\n   end\n   H = 0;\n   if (jdx>1)\n      H = dtime(1:jdx-1)'*b(1:jdx-1);\n   end\n   H = H + (t(tmpidx) - time0(jdx))*b(jdx);\n   prob(tmpidx) = exp(-H);\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/26905-fitting-survival-probability-models/survProbStdModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5959712629763494}}
{"text": "function classifier = train_boosted_dt_mc(features, cat_features, labels, ...\n    num_iterations, num_nodes, stopval, init_weights, varargin)\n% Train a classifier based on boosted decision trees.  Boosting done by the\n% logistic regression version of Adaboost (Adaboost.L - Collins, Schapire,\n% Singer 2002).  At each\n% iteration, a set of decision trees is created for each class, with\n% confidences equal to 1/2*ln(P+/P-) for that class, according to the\n% weighted distribution.  Final classification is based on the largest\n% confidence label (possibly incorporating a prior as h0(c) =\n% 1/2*ln(Pc/(1-Pc)).  Weights are assigned as\n% w(i,j) = 1 / (1+exp(sum{t in iterations}[yij*ht(xi, j)])).  \n\nif length(varargin) == 1  % class names supplied\n    gn = varargin{1};\n    gid = zeros(size(labels));\n    for c = 1:length(gn)\n        ind = find(strcmp(labels, gn{c}));\n        gid(ind) = c;\n        if ~isempty(init_weights)\n            disp([gn{c} ': ' num2str(sum(init_weights(ind)))]);\n        else\n            disp([gn{c} ': ' num2str(length(ind))]);\n        end\n    end\n    ind = find(gid==0);\n    gid(ind) = [];\n    labels(ind) = [];\n    features(ind, :) = [];\nelse    \n    [gid, gn] = grp2idx(labels);    \n    gn\nend\n\n\n\nclassifier.names = gn;\n\nnum_classes = length(gn);\nnum_data = length(gid);\n\nif ~exist('init_weights', 'var') || isempty(init_weights)\n    init_weights = ones(num_data, 1)/num_data;\nelse\n    init_weights = init_weights(:) / sum(init_weights);\nend\n\n% if no examples from a class are present, create one dummy example for\n% that class with very small weight\nfor c = 1:numel(gn)\n    if ~any(gid==c)\n        disp(['warning: no examples from class ' gn(c)])\n        gid(end+1) = c;\n        features(end+1, :) = zeros(size(features(end, 1)));\n        num_data = num_data + 1;\n        init_weights(end+1) = min(init_weights)/2;        \n    end\nend\n\nall_conf = zeros(num_data, num_classes);\nfor c = 1:num_classes\n\n    disp(['class: ' num2str(gn{c})]);    \n    y = (gid == c)*2-1;\n    cl = [-1 1];\n    nc = 2;\n    w = zeros(num_data, 1);\n    cw = zeros(num_classes, 1);  \n    for i = 1:2\n        indices = find(y==cl(i));\n        %count = sum(init_weights(indices));\n        %w(indices) = init_weights(indices) / count / 2;\n        w(indices) = init_weights(indices);\n        \n        if cl(i)==1\n            %classifier.h0(c) = log(count / (1-count));\n            classifier.h0(c) = 0;\n        end\n        \n    end\n        \n    data_confidences = zeros(num_data, 1);\n    aveconf = [];\n    \n    for t = 1:num_iterations\n        % learn decision tree based on weighted distribution\n        dt = treefitw(features, y, w, 1/num_data/2, 'catidx', cat_features, 'method', 'classification', 'maxnodes', num_nodes*4);\n        [tmp, level] = min(abs(dt.ntermnodes-num_nodes));\n        dt = treeprune(dt, 'level', level-1);\n\n        % assign partition confidences\n        pi = (strcmp(dt.classname{1},'1')) + (2*strcmp(dt.classname{2},'1'));\n        ni = (strcmp(dt.classname{1},'-1')) + (2*strcmp(dt.classname{2},'-1'));\n        classprob = dt.classprob;\n        confidences = 1/2*(log(classprob(:, pi)) - log(classprob(:, ni)));             \n\n        % assign weights\n        [class_indices, nodes, classes] = treeval(dt, features);        \n        data_confidences = data_confidences + confidences(nodes);\n        \n        w = 1 ./ (1+exp(y.*data_confidences));        \n        % was w = 1 ./ (1+exp(y.*data_confidences)); \n        w = w / sum(w);   \n                \n%         disp(['c: ' num2str(sum(init_weights ./ (1+exp(-y.*data_confidences)))) ...\n%             '  e: ' num2str(sum(init_weights .* (y.*data_confidences < 0))) ...\n%             '   w: ' num2str(max(w))]);  \n        \n        classifier.wcs(t, c).dt = dt;\n        classifier.wcs(t, c).confidences = confidences;       \n             \n        \n        %aveconf(t) = mean(1 ./ (1+exp(-y.*data_confidences)));\n        aveconf(t) = sum(1 ./ (1+exp(-y.*data_confidences)).*init_weights);\n        if t>10 && (aveconf(t)-aveconf(t-10) < stopval)\n            disp(num2str(aveconf))\n            disp(['Stopping after ' num2str(t) ' trees'])            \n            break;\n        end\n        \n    end\n\n    finalconf = 1 ./ (1+exp(-y.*data_confidences)) .* init_weights;\n    finalerr = (y.*data_confidences < 0);\n    disp(['confidence:: mean: ' num2str(sum(finalconf)) ...\n        '  pos: ' num2str(sum(finalconf(y==1))/sum(init_weights(y==1))) ...\n        '  neg: ' num2str(sum(finalconf(y~=1))/sum(init_weights(y~=1)))]);\n    disp(['training error:: mean: ' num2str(sum(init_weights.*finalerr)) ...\n        '  pos: ' num2str(sum(init_weights(y==1).*finalerr(y==1))/sum(init_weights(y==1))) ...\n        '  neg: ' num2str(sum(init_weights(y~=1).*finalerr(y~=1))/sum(init_weights(y~=1)))]);    \n    all_conf(:, c) = data_confidences+classifier.h0(c);\n  \nend\n\n% compute and display training error\n[tmp, assigned_label] = max(all_conf, [], 2);\nconf_matrix = zeros(num_classes, num_classes);\nfor c = 1:num_classes    \n    indices = find(gid==c);\n    for c2 = 1:num_classes\n        conf_matrix(c, c2) = sum(init_weights(indices).*(assigned_label(indices)==c2))/sum(init_weights(indices));\n    end\n    disp([gn{c} ' error: ' num2str(sum(init_weights(indices).*(assigned_label(indices)~=c))/sum(init_weights(indices)))]);\nend\ndisp('Confusion Matrix: ');\ndisp(num2str(conf_matrix));\ndisp(['total error: ' num2str(sum(init_weights.*(assigned_label~=gid)))]);\n\n\n        ", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/GeometricContext/boosting/train_boosted_dt_mc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5959712583167284}}
{"text": "function demo_RecPF\n\nclose all\nclear all\n\naddpath('utilities');\naddpath('solver');\naddpath('images');\n\n% load images\nIms = cell(6,1);\nfor k = 1:6\n    filename = ['ortho' int2str(k) '.jpg'];\n    I = single(imread(filename))/255;\n    if ndims(I) == 3\n        Ims{k} = rgb2gray(I);\n    end\nend\n\n% call tester\ntester(Ims);\n\nfunction tester(Ims)\n\n%\n% min aTV*TV(u) + aL1*||Phi*u||_1 + 0.5*||F_p*u - f_p||_2^2\n%\naTV = 1.e-6;\naL1 = 0.e-6;\n\nh = figure(1);\nset(h,'units','normalized','outerposition',[0 .4 .9 .6]);\n\nfor nimg = 1:length(Ims)\n    \n    % load an image\n    I = single(Ims{nimg});\n    [m n] = size(I);\n    N = m*n;\n    \n    % generate mask: two methods\n    mth = 1;\n    if mth == 1\n        acc = 3.6;\n        picks = selectPF(n/acc,n);\n        K = length(picks);\n    else\n        Ls = 45;\n        picks = fftshift(MRImask(n,Ls));\n        picks = union(find(picks~=0),1);\n        K = length(picks);\n    end\n    \n    % image information display\n    fprintf('Image %i: size %3i by %3i, N/M = %6.2f\\n',nimg,m,n,N/K);\n    snr(2*I,I);\n    subplot(2,6,nimg); imshow(I,[]);\n    title(['Original ' int2str(m) ' x ' int2str(n)]);\n    drawnow;\n    \n    % add noise\n    sigma = 0.01;\n    noise = sigma*(randn(K,1) + sqrt(-1)*randn(K,1));\n    \n    % DWT and IDWT\n    if exist('midwt','file')\n        wav = daubcqf(2);\n        Psi = @(x) midwt(x,wav);\n        PsiT = @(x) mdwt(x,wav);\n    elseif exist('wavedec2','file')\n        Psi = @(x) Wavedb1Phi(x,1);\n        PsiT = @(x) Wavedb1Phi(x,0);\n    else\n        Psi = @(x) x; PsiT = Psi;\n    end\n    \n    \n    % observation B\n    FI = fft2(I);\n    B = FI(picks) + noise;\n    \n    % run RecPF\n    opts = [];\n    t = cputime;\n    U = RecPF(m,n,aTV,aL1,picks,B,PsiT,Psi,opts);\n    t = cputime - t;\n    \n    % plot reconstructed images\n    subplot(2,6,6+nimg);\n    imshow(U,[]);\n    title(sprintf('%4.2fdB, %4.2fs',snr(U,I),t));\n    drawnow;\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/NESTA-1.1/RecPF_v1.1/demo_RecPF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5959712513272969}}
{"text": "\nclear all\nclose all\n\ndisp('Data from multiple subjects');\n\ndisp('Estimate mixed effects using Langevin Monte Carlo');\ndisp('Using LDS model with constrained connectivity');\n\nlds.model='forward';\n\n% Number of dynamical states e.g. brain areas\nd=4;\n\n% Observation noise\nlds.sd=0.1;\n\n% Prior over initial states\nlds.R.pE=linspace(3,1.5,d)';\nlds.R.pC=0.5^2*eye(d);\n\n% Number of subjects\nlds.Nsub=3;\n\n% Number of observations per subject\nlds.Nobs=5;\n\nlds.init_par='random';\nlds.flow_par='fixed';\n\n% Generate group data\n[lds.pinit,lds.pflow,lds.names,M,U,Y] = mci_lds_group_data (lds);\n\n% Assign init/flow as random/fixed effects\nassign.init_par='random';\nassign.flow_par='fixed';\nassign.out_par='known';\n\nMCI.assign=assign;\n\nMCI.fixed.pE=M{1}.pE;\nMCI.fixed.pC=M{1}.pC;\n\n% Initialisation\ni0=mci_interp_init(Y,M{1});\na0=[];\nif strcmp(assign.init_par,'random')\n    MCI.pinit0=i0;\nelse\n    MCI.pinit0=mean(i0,2);\nend\nif strcmp(assign.flow_par,'random')\n    MCI.pflow0=spm_vec(M{1}.pE)*ones(1,lds.Nsub);\n    if ~isempty(a0), MCI.pflow0(1:d,:)=a0; end\nelse\n    MCI.pflow0=spm_vec(M{1}.pE);\n    if ~isempty(a0), MCI.pflow0(1:d,:)=mean(a0,2); end\nend\nMCI.pout0=[];\n\n\nMCI.M=M; MCI.U=U; MCI.Y=Y;\nMCI.update_obs_noise=1;\nMCI.verbose=1;\nMCI.total_its=16;\nMCI.rinit=0.25;\n\ntic;\nMCI = spm_mci_mfx_dynamic (MCI);\ntoc\n\nrmse=mci_lds_plot_params (MCI,lds);\n\nfor n=1:lds.Nsub,\n    mci_lds_plot_fit (MCI,lds,n,1);\nend\n\ndisp('True dynamics:');\n[f,Atrue] = mci_lds_fx (lds.pinit(:,1),U{1},lds.pflow,M{1});\ndisp(Atrue);\n\ndisp('Estimated dynamics:');\n[f,Aest] = mci_lds_fx (MCI.pinit,U{1},MCI.pflow,M{1});\ndisp(Aest);\n\nmci_plot_noiseSD (MCI.Ce,MCI.post_ind);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/demo-group/mci_demo_mfx_lds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5959712480791528}}
{"text": "function r8mat_transpose_test ( )\n\n%*****************************************************************************80\n%\n%% R8MAT_TRANSPOSE_TEST tests R8MAT_TRANSPOSE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 March 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 5;\n  n = 4;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8MAT_TRANSPOSE_TEST\\n' );\n  fprintf ( 1, '  R8MAT_TRANSPOSE transposes an R8MAT.\\n'; );\n\n  a = r8mat_indicator ( m, n );\n  r8mat_print ( m, n, a, '  Matrix A:' );\n\n  at = r8mat_transpose ( m, n, a );\n  r8mat_print ( n, m, at, '  Transposed matrix At:' );\n\n  return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8mat_transpose_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.5959635376381524}}
{"text": "% function [B, Bb, Bw, pc_b, sc_b, pc_w, sc_w] = mlpcr2(X,Y,varargin)\n%\n% Multilevel PCR v3.0 designed for prediction on datasets with multiple \n% subjects and multiple observations per subject. Unlike version 2 this\n% supports full mixed effects modeling. See randSlope and randInt\n% arguments.\n%\n% Identifies within block (subject) eigenvectors with optional balancing \n% across subjects. Computes loadings of full dataset on these within \n% subject eigenvectors (so they can vary both within and between blocks). \n% Computes a separate PCA on the residual and obtains a second set of \n% orthogonal components and scores which only vary between blocks. Performs \n% regression of between and within loadings (jointly) on pain outcome, and \n% projects regression coefficients back to voxel space using within and \n% between eigenvectors.\n%\n% regression is OLS (default) or moore-penrose pseudoinverse (rank\n% deficient data), not some mixed effects thing. Within subject PCA is \n% rate limiting step.\n%\n% If the defaults are used then the result is identical to PCR, only you \n% get both within and between subject predictive models in addition to the \n% full model. Different results may be obtained with hyperparameter\n% optimization or concensus PCA enabled.\n%\n% Input ::\n%\n%   X           - n x p data matrix\n%\n%   Y           - n x 1 outcome vector\n%\n%   'subjIDs    - n x 1 vector (ideal) or cellstr (throws warning, but\n%                   fine) indicating group affilitations. Subjects must be\n%                   adjacent. Don't intermix blocks with one another. This\n%                   function was not designed for this scenario and will\n%                   break even with equivalently intermixed block labels.\n%\n% Optional Input ::\n%\n%   'numcomponents'\n%               - 1 x 2 numeric vector indicating number of PCA dimensions\n%                   to retain at the between and within levels\n%                   (respectively). Use Inf to autoselect based on\n%                   available degrees of freedom. default: [Inf, Inf]\n%                 Note 1: bayesopt from the Statistics and Machine Leraning\n%                   matlab toolbox provides an elegant way to optimize\n%                   these variables.\n%                 Note 2: More dimensions result in less biased solutions,\n%                   which is a good reason for using the default [Inf,Inf].\n%                   However task driven variance is going to be captured by \n%                   within components, so [0, Inf] is also a sensible\n%                   default if you wish to treat trait differences as\n%                   noise.\n%\n%   'cpca'      - followed by 0/1 to indicate whether or not concensus PCA\n%                   (Westerhuis, et al. 1998) should be used in place of \n%                   standard pca. If concensus PCA is enabled eigenvectors \n%                   will be selected such that variance is explained \n%                   equally across all blocks. Otherwise eigenvectors will \n%                   best represent blocks with the most observations.\n%                 Note 1: for optimization of dimension hyperparameters\n%                   specify a custom loss function that also balances the \n%                   weight of each block. fmri_data/predict won't do this\n%                   and will consequently fight against CPCA. A future \n%                   update may fix this, and if so this note should be \n%                   removed.\n%                 Note 2: In principle concensus PCA could be implemened\n%                   for traditional PCR too. It just hasn't been.\n%\n%   'randInt'   - Fit a random intercept model. Default=false\n%\n%   'randSlope' - Fit a random slope model (within effects only).\n%                   Default=false\n% \n%   'fitlmeOpts'\n%               - Cell array of options to passthrough to fitlme. Run with\n%               {'CovariancePattern','isotropic'} by default.\n%\n% Output ::\n%\n%   B           - B(1) is intercept, B(2:end) are regression weights in X \n%                   space.\n%\n%   Bb          - Bb(1) is intercept. Bb(2:end) are regression weights of\n%                   between block variance components in X space.\n%\n%   Bw          - Bw(1) is zero. Bb(2:end) are regression weights of within\n%                   block variance components in X space.\n%\n%   pc_b        - between eigenvectors\n%\n%   sc_b        - scores on between eigenvectors\n%\n%   pc_w        - within eigenvectors\n%\n%   sc_w        - scores on within eigenvectors\n%\n%\n% Version History ::\n%\n%   MLPCR was originally developed using mixed effects models (version 1,\n%   Petre, et al., 2019), however model fitting was prohibitively slow and\n%   consequently performance characteristics could not be fully evaluated. \n%   Version 2.0 substitutes (optionally weighted) OLS for much faster \n%   convergence, and minimaly different weight fitting. Version 1 is much \n%   more flexible than version 2, and is still available in CanlabPrivate \n%   for potential future development. It has been removed from CanlabCore.\n%   Version 3.0 reintroduces mixed effects modelling as a non-default\n%   option, but abides by better coding practices, following in the \n%   footsteps of version 2.0.\n%\n% References ::\n%\n%   Petre B, Woo W, Losin E, Eisenbarth H, Wager TD. (2019) Separate within\n%       -subject and individual-difference predictions with multilevel\n%       MVPA. Society for Neuroscience, San Diego, CA. (included with \n%       canlabCore mlpcr library as pdf).\n%\n%   Westerhuis J, Kourti T, MacGregor J. (1998) Analysis of Multiblock and \n%       Hierarchical PCA and PLS Methods. Journal of Chemometrics 12(5).\n%   \n%\n% Designed and writen by Bogdan, 5/4/2020\n%                   \n%\n%\n% ToDo:\n% - Enable between or within dimension retention priority for bootstrapping\n%   (allowing the user to force retention of one or the other even if\n%   eigenvalue rank doesn't justify it)\n% - passthrough options to higher level cv_mlpcr, cv_mlpcr_bt and\n%   cv_mlpcr_wi scripts. Concensus PCA should also use concensus cv_err,\n%   cv_mlpcr_wi and cv_mlpcr_bt should have within and between priority\n%   (respectively) by default.\n\nfunction [B, Bb, Bw, pc_b, sc_b, pc_w, sc_w, b] = mlpcr3(X,Y,varargin)\n    subjIDs = [];\n    wiDim = Inf;\n    btDim = Inf;\n    cpca = 0;\n    randInt = 0;\n    randSlope = 0;\n    fitlmeOpts = {};\n    for i = 1:length(varargin)\n        if ischar(varargin{i})\n            switch varargin{i}\n                case 'subjIDs'\n                    subjIDs = varargin{i+1}(:);\n                case 'numcomponents'\n                    nc = varargin{i+1};\n                    btDim = nc(1);\n                    wiDim = nc(2);\n                case 'cpca'\n                    cpca = varargin{i+1};\n                case 'randInt'\n                    randInt = varargin{i+1};\n                case 'randSlope'\n                    randSlope = varargin{i+1};\n                case 'fitlmeOpts'\n                    fitlmeOpts = varargin{i+1};\n            end\n        end\n    end\n    \n    if randInt || randSlope\n        if ~ismember('CovariancePattern',fitlmeOpts)\n            fitlmeOpts = [fitlmeOpts, {'CovariancePattern', 'isotropic'}];\n        end\n    end\n    \n    % check for intercept and remove if present\n    %{\n    intercept = ones(1,size(X,2))';\n    wh = cellfun(@(x) isequal(x,intercept),num2cell(X,1));\n    if ~isempty(wh)\n        warning('Your input X should not contain an intercept. Removing it. Model parameters will corespond to intercept free design')\n        X(:,wh) = [];\n    end\n    %}\n    \n    % we need adjacent subjIDs, so let's ensure that\n    [subjIDs, newOrder] = sortrows(subjIDs(:));\n    [~,origOrder] = sort(newOrder);\n    \n    X = X(newOrder,:);\n    Y = Y(newOrder);\n    \n    if isempty(subjIDs)\n        error('Cannot perform multilevel PCR without a subjIDs identifier');\n    end\n    \n    [~, grp_exemplar, subjIDs] = unique(subjIDs,'rows','stable');\n    uniq_grp = unique(subjIDs);\n    \n    % get centering and expansion matrices\n    n_grp = length(uniq_grp);\n    cmat = cell(1,n_grp);\n    emat = cell(1,n_grp);\n    sf = []; % scale factor for imbalanced datasets\n    for i = 1:n_grp\n        this_grp = uniq_grp(i);\n        this_n = sum(this_grp == subjIDs);\n        cmat{i} = eye(this_n) - 1/this_n;\n        emat{i} = ones(this_n,1);\n        sf = [sf(:); 1/sqrt(this_n)*ones(this_n,1)];\n    end\n    cmat = blkdiag(cmat{:});\n    emat = blkdiag(emat{:});\n    if ~cpca\n        sf = ones(size(sf));\n    end\n    \n    % compute preliminary within fractions\n    Xw = cmat*X;\n    \n    if wiDim > 0\n        % determine within dimension retention\n        if wiDim > length(subjIDs) - length(uniq_grp)\n            if wiDim < Inf % something user supplied was too big\n                warning('Max wiDim exceeds max df, reseting wiDim to %d',length(subjIDs) - length(uniq_grp));\n            end\n\n            wiDim = min(length(subjIDs) - length(uniq_grp), size(X,2));\n        end\n        \n        \n        % Get concensus PCA solution, which weighs each block equally\n        % requires Matlab 2016b or later perform operation across all\n        %   columns like this with sf\n        [pc_w,~,~] = svd((sf.*Xw)', 'econ');\n        pc_w = pc_w(:,1:wiDim);          \n        \n        sc_w = X*pc_w;\n        \n        % note: sc_w*pc_w' ~= Xw, it pulls scores from the entire dataset,\n        % \tSome of the between fraction may vary along the within\n        % \tcomponents, and we want to pull that into the within scores.\n        % \tsc_w*pc_w' is not necessarily mean zero within subject.\n        \n        % modified Xb, invariant with subject, but not exactly the subject\n        %   ean either due to the missing variance along pc_w\n        Xr = X - sc_w*pc_w';\n        Xb = Xr - cmat*Xr; % if we don't have full wiDim then there's residual within variance to remove\n        Xb = Xb(grp_exemplar,:);\n    else\n        [pc_w, sc_w] = deal([]);\n        \n        Xb = X - Xw;\n        Xb = Xb(grp_exemplar,:);\n    end\n    \n    if btDim > 0\n        % get between components from residual between fraction\n        if btDim > length(uniq_grp) - 1\n            if btDim < Inf % something user supplied was too big\n                warning('Max btDim exceeds max df, reseting btDim to %d',length(uniq_grp) - 1);\n            end\n\n            btDim = min(length(uniq_grp) - 1, size(Xb,2));\n        end\n        \n        [pc_b,~,~] = svd(scale(Xb,1)','econ');\n        pc_b = pc_b(:,1:btDim);\n        sc_b = Xb*pc_b;\n    else\n        [pc_b, sc_b] = deal([]);\n    end\n    \n    if ~isempty(sc_b) \n        sc_b = emat*sc_b; \n        bDim = 1:size(sc_b,2);\n        wDim = (1:size(sc_w,2)) + bDim(end);\n    else\n        bDim = [];\n        wDim = 1:size(sc_w,2);\n    end\n    sc = [sc_b, sc_w];\n    pc = [pc_b, pc_w];\n    \n    \n    % 3/8/13 TW solution from cv_pcr code to use numcomps, because sc is \n    %   not always full rank during bootstrapping. \n    % Modified by Bogdan for use in mlpcr to keep componens with the \n    %   highest ranking eigenvectors (not necessarily sequential in mlpcr \n    %   because of within/between stratification)\n    % ToDo: create a bootstrap priority option to allow the user to specify\n    %   whether they want to prefer between or within component retention\n    %   regardless of eigenvalue size.\n    if rank(sc) == size(sc,2)\n        numcomps = rank(sc); \n        retainComps = 1:numcomps;\n        \n        bDim(~ismember(bDim,retainComps)) = [];\n        wDim(~ismember(wDim,retainComps)) = [];\n    elseif rank(sc) < size(sc,2)\n        error('You will run into problems when reconstructing Bw at the end. Fix the wDim and bDim indexing');\n        numcomps = rank(sc)-1;\n        [~,compRank] = sort(var(sc),'descend');\n        retainComps = sort(compRank(1:numcomps));\n        \n        [bDimnew, wDimnew] = deal(zeros(length(compRank),1));\n        \n        bDim(~ismember(bDim,retainComps)) = [];\n        wDim(~ismember(wDim,retainComps)) = [];\n        \n        if ~any(ismember(bDim,retainComps)) && btDim > 0\n            warning('All between dimensions dropped due to rank deficiency'); \n        end\n        if ~any(ismember(wDim,retainComps)) && wiDim > 0\n            warning('All within dimensions dropped due to rank deficiency'); \n        end\n        \n        sc_w = sc(:,wDim);\n        sc_b = sc(:,bDim);\n        pc_w = pc(:,wDim);\n        pc_b = pc(:,bDim);\n        \n        bDimnew(bDim) = 1;\n        bDimnew = bDimnew(retainComps);\n        bDim = find(bDimnew);\n                \n        wDimnew(wDim) = 1;\n        wDimnew = wDimnew(retainComps);\n        wDim = find(wDimnew);\n    end\n    \n    xx = [ones(size(Y, 1), 1) sc(:, retainComps)];\n    \n    if ~randInt && ~randSlope % fit a LS or weighted LS model    \n        if rank(xx) <= size(sc, 2)\n            % compute (optional: weighted) pseudoinverse if not full rank\n            tol = max(size(xx))*eps(norm(xx));\n            [u,s,v] = svd(sf.*xx,'econ');\n            s = diag(s);\n            s(s>tol) = 1./s(s>tol);\n            s = diag(s);\n            pinv_xx = v*s*u';\n\n            b = pinv_xx * (sf.*Y);\n        else\n            b = inv(xx'*diag(sf.^2)*xx)*xx'*diag(sf.^2)*Y;\n        end\n    else % fit random effects model\n        if rank(xx) <= size(sc,2)\n            warning(['Rank deficient data found. This is not supported with mixed effects models.',...\n                'If you''re bootstrapping consider using the fixed effects approach instead']);\n        end\n        xxRE = [];\n        if randInt\n            xxRE = [xxRE, ones(size(Y,1),1)];\n        end\n        if randSlope\n            xxRE = [xxRE, sc_w];\n        end\n        \n        %m = fitlmematrix(double(sf.*xx), sf.*Y, double(sf.*xxRE), categorical(subjIDs), fitlmeOpts{:});\n        %try\n            m = fitlmematrix(double(xx), Y, double(xxRE), categorical(subjIDs), fitlmeOpts{:});\n        %catch\n        %    keyboard\n        %end\n        b = m.fixedEffects;\n    end\n\n    \n    if ~isempty(retainComps)\n        B = [b(1); pc(:,retainComps)*b(2:end)];\n    else\n        B = [b;  zeros(size(X,2),1)];\n    end\n    \n    if isempty(bDim)\n        Bb = [b(1); zeros(size(X,2),1)];\n    else\n        %Bb = [b(1); pc_b(:,bDim)*b(bDim + 1)];\n        Bb = [b(1); pc(:,bDim)*b(bDim + 1)];\n    end\n    \n    if isempty(wDim)\n        Bw = [0; zeros(size(X,2),1)];\n    else\n        %Bw = [0; pc_w(:,wDim)*b(wDim + 1)];\n        Bw = [0; pc(:,wDim)*b(wDim+1)];\n    end\n    \n    if ~isempty(sc_b), sc_b = sc_b(origOrder,:); end\n    if ~isempty(sc_w), sc_w = sc_w(origOrder,:); end\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/mlpcr/mlpcr3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5958932957729732}}
{"text": "% [threshx,cost,classorder] = onedim2kclass(x,idx,...)\n%\n% finds the k-1 thresholds that best separate the input one-dimensional\n% data vector x into k classes\n%\n% input:\n%\n% x: n x 1 is the n one-dimensional data points\n% idx: n x 1 is the integer labels for each data point\n% \n% optional:\n%\n% 'issorted': true/false, whether the list is sorted already\n% 'classorder': 1 x k vector where classorder(1) comes first and \n% classorder(k) comes last. otherwise, classorder is set based on means of each \n% class\n%\n% output:\n% threshx: k+1x1, class classorder(i) is >= threshx(i) and < thresh(i+1)\n% cost: number of misclassified samples\n% classorder: 1 x k\n% \nfunction [threshx,cost,classorder] = onedim2kclass(x,idx,varargin)\n\nx = x(:);\nidx = idx(:);\nn = length(x);\n\n\n[issorted,classorder] = myparse(varargin,'issorted',false,'classorder',nan);\n\n%k = max(idx); % right now, assuming labels are 1,...,k\n\n% make labels 1,...,k\noldidx = idx;\n[newidx2oldidx0,tmp,idx] = unique(idx);\n%[tmp,oldidx2newidx0] = sort(newidx2oldidx0);\nk = length(newidx2oldidx0);\nif ~any(isnan(classorder)),\n  classorder0 = classorder;\n  for i = 1:k,\n    classorder(classorder0==newidx2oldidx0(i)) = i;\n  end\nend\n\nif k == 1,\n  threshx = [min(x),max(x)+eps];\n  cost = 0;\n  if isnan(classorder),\n    classorder = newidx2oldidx0;\n  end\n  return;\nend\n\n%if k == 2,\n%  % use onedim2class\n%  % idx should be -1,1\n%  idx = 2*idx-3;\n%  [thresh,lower,cost] = onedim2class(x,idx);\n%  if lower == -1,\n%    order = [1,2];\n%  else\n%    order = [2,1];\n%  end\n%  classorder = order;\n%  %classorder = newidx2oldidx(order);\n%  return;\n%end\n\n% choose order for classes based on order of means\nif any(isnan(classorder)),\n  \n  mu = zeros(1,k);\n  for k1 = 1:k,\n    mu(k1) = mean(x(idx==k1));\n  end\n  [sortedmu,order] = sort(mu);\n  [tmp,oldidx2newidx] = sort(order);\n  classorder = newidx2oldidx0(order);\n  % relabel\n  idx0 = idx;\n  for k1 = 1:k,\n    idx(idx0==k1) = oldidx2newidx(k1);\n  end\n\nelse\n  [tmp,oldidx2newidx] = sort(classorder);\nend\n\n\nif ~issorted,\n  [x,xorder] = sort(x);\n  idx = idx(xorder);\n  [tmp,xreorder] = sort(xorder);\nend\n% deal with duplicates: cannot have a class start at i if x(i) == x(i-1)\n% isdup(i) = x(i) == x(i-1)\nisdup = [x(1:end-1) == x(2:end);false];\ndupidx = find(isdup);\n\n% costs(n1+1,k1) is the min cost of classifying samples 1:n1 as classes 1:k1\ncosts = inf(n+1,k-1);\n% prev(n1+1,k1)+1 is the start of class k1 when classifying samples 1:n1\nprev = zeros(n+1,k-1);\n\n% base cases\n\n% for i = 1,...,n\n% cost(i+1,1) is cost of classifying 1:i as 1 is \n% sum(idx(1:i)~=k) = c(i+1)\n% for i = 0, cost(i+1,1) = 0\ncosts(2:n+1,1) = cumsum(double(idx~=1));\n% cannot end at dupidx - 1\ncosts(dupidx+1) = inf;\n\n% for k1 = 1,...,k cost of classifying 1:0 as 1:k1 is 0\ncosts(1,:) = 0;\n\n% compute for increasing k, up to k-1\nfor k1 = 2:k-1,\n  \n  c = [0;cumsum(double(idx~=k1))];\n  \n  for n1 = 1:n,\n    if isdup(n1), continue; end\n    % compute one-class cost for i = 1:n1+1, end = n1\n    oneclasscost = c(n1+1)-c(1:n1+1);\n    % prev(n1+1,k1) is the start of the last class\n    [costs(n1+1,k1),prev(n1+1,k1)] = min( costs(1:n1+1,k1-1) + oneclasscost );\n  end\n  \nend\n\n% compute for n,k\nc = [0;cumsum(double(idx~=k))];\noneclasscost = c(n+1)-c(1:n+1);\n[cost,prevlast] = min( costs(1:n+1,k-1) + oneclasscost );\n\n% get thresholds\n% class k1 goes from thresh(k1) to thresh(k1+1)-1\nthresh = ones(k+1,1);\nthresh(end) = n+1;\nfor k1 = k:-1:1,\n  if prevlast < 1,\n    thresh(1:k1) = 1;\n    break;\n  end\n  thresh(k1) = prevlast;\n  if k1 > 1,\n    prevlast = prev(prevlast,k1-1);\n  end\nend\n\n% convert from indices to data points\nthreshx = zeros(k+1,1);\nthreshx(thresh<=1) = x(1);\nthreshx(thresh==n+1) = x(n)+1;\nother = thresh > 1 & thresh <= n;\nthreshx(other) = (x(thresh(other)-1)+x(thresh(other)))/2;\n%threshx(other) = x(thresh(other));\n\nif exist('classorder0','var')\n  classorder = classorder0;\nend\n\n% here is some code for testing\nif 0,\nn = 100;\nk = 3;\nntests = 100;\nsig = .1;\nfor test = 1:ntests,\n  %x = sort(rand(n,1));\n  idxtrue = randsample(k,n,true);\n  mutrue = sort(rand(k,1));\n  x = randn(n,1)*sig + mutrue(idxtrue);\n  [x,order] = sort(x);\n  idxtrue = idxtrue(order);\n  tic;\n  [mu,cost,idxdp,threshx] = onedimkmeans(x,k);\n  t = toc;\n  fprintf('DP score = %f, diff = %e, time = %f, centers = ',cost,cost-sum(sumD),t);\n  fprintf('%f, ',mu);\n  fprintf('\\n');\n  if cost > sum(sumD),\n    if all(idxkm==idxdp),\n      fprintf('Bigger cost, diff = %e, but all idx are the same\\n',cost-sum(sumD));\n      pause(1);\n    else\n      fprintf('*****Bigger cost, diff = %e, differing indices\\n',cost-sum(sumD));\n      fprintf('Differing indices: ');\n      fprintf('%d, ',find(idxkm~=idxdp));\n      fprintf('\\n');\n      break;\n    end\n  end\n  diffcost(test) = cost-sum(sumD);\n  fprintf('\\n');\nend\nend", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/onedim2kclass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5957423892072637}}
{"text": "function jac = p00_jac ( test, neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P00_JAC evaluates the jacobian for any problem.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    17 February 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer TEST, the problem number.\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  if ( test == 1 )\n    jac = p01_jac ( neqn, t, y );\n  elseif ( test == 2 )\n    jac = p02_jac ( neqn, t, y );\n  elseif ( test == 3 )\n    jac = p03_jac ( neqn, t, y );\n  elseif ( test == 4 )\n    jac = p04_jac ( neqn, t, y );\n  elseif ( test == 5 )\n    jac = p05_jac ( neqn, t, y );\n  elseif ( test == 6 )\n    jac = p06_jac ( neqn, t, y );\n  elseif ( test == 7 )\n    jac = p07_jac ( neqn, t, y );\n  elseif ( test == 8 )\n    jac = p08_jac ( neqn, t, y );\n  elseif ( test == 9 )\n    jac = p09_jac ( neqn, t, y );\n  elseif ( test == 10 )\n    jac = p10_jac ( neqn, t, y );\n  elseif ( test == 11 )\n    jac = p11_jac ( neqn, t, y );\n  elseif ( test == 12 )\n    jac = p12_jac ( neqn, t, y );\n  elseif ( test == 13 )\n    jac = p13_jac ( neqn, t, y );\n  elseif ( test == 14 )\n    jac = p14_jac ( neqn, t, y );\n  elseif ( test == 15 )\n    jac = p15_jac ( neqn, t, y );\n  elseif ( test == 16 )\n    jac = p16_jac ( neqn, t, y );\n  elseif ( test == 17 )\n    jac = p17_jac ( neqn, t, y );\n  elseif ( test == 18 )\n    jac = p18_jac ( neqn, t, y );\n  elseif ( test == 19 )\n    jac = p19_jac ( neqn, t, y );\n  elseif ( test == 20 )\n    jac = p20_jac ( neqn, t, y );\n  elseif ( test == 21 )\n    jac = p21_jac ( neqn, t, y );\n  elseif ( test == 22 )\n    jac = p22_jac ( neqn, t, y );\n  elseif ( test == 23 )\n    jac = p23_jac ( neqn, t, y );\n  elseif ( test == 24 )\n    jac = p24_jac ( neqn, t, y );\n  elseif ( test == 25 )\n    jac = p25_jac ( neqn, t, y );\n  elseif ( test == 26 )\n    jac = p26_jac ( neqn, t, y );\n  elseif ( test == 27 )\n    jac = p27_jac ( neqn, t, y );\n  elseif ( test == 28 )\n    jac = p28_jac ( neqn, t, y );\n  elseif ( test == 29 )\n    jac = p29_jac ( neqn, t, y );\n  elseif ( test == 30 )\n    jac = p30_jac ( neqn, t, y );\n  elseif ( test == 31 )\n    jac = p31_jac ( neqn, t, y );\n  elseif ( test == 32 )\n    jac = p32_jac ( neqn, t, y );\n  elseif ( test == 33 )\n    jac = p33_jac ( neqn, t, y );\n  elseif ( test == 34 )\n    jac = p34_jac ( neqn, t, y );\n  elseif ( test == 35 )\n    jac = p35_jac ( neqn, t, y );\n  elseif ( test == 36 )\n    jac = p36_jac ( neqn, t, y );\n  elseif ( test == 37 )\n    jac = p37_jac ( neqn, t, y );\n  elseif ( test == 38 )\n    jac = p38_jac ( neqn, t, y );\n  elseif ( test == 39 )\n    jac = p39_jac ( neqn, t, y );\n  elseif ( test == 40 )\n    jac = p40_jac ( neqn, t, y );\n  else\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'P00_JAC - Fatal error!\\n' );\n    fprintf ( 1, '  Unrecognized problem number = %d\\n', test );\n    error ( 'P00_JAC - 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/test_ode/p00_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.5957423811056515}}
{"text": "function power_method_test ( )\n\n%*****************************************************************************80\n%\n%% POWER_METHOD_TEST tests the POWER_METHOD library.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    25 May 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'POWER_METHOD_TEST\\n' );\n  fprintf ( 1, '  MATLAB version:\\n' );\n  fprintf ( 1, '  Test the POWER_METHOD library.\\n' );\n\n  power_method_test01 ( );\n  power_method_test02 ( );\n  power_method_test03 ( );\n%\n%  Terminate.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'POWER_METHOD_TEST:\\n' );\n  fprintf ( 1, '  Normal end of execution.\\n' );\n  fprintf ( 1, '\\n' );\n  timestamp ( );\n\n  return\nend\nfunction power_method_test01 ( )\n\n%*****************************************************************************80\n%\n%% POWER_METHOD_TEST01 uses POWER_METHOD on the Fibonacci2 matrix.\n%\n%  Discussion:\n%\n%    This matrix, despite having a single dominant eigenvalue, will generally\n%    converge only very slowly under the power method.  This has to do with\n%    the fact that the matrix has only 3 eigenvectors.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    20 July 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 50;\n\n  a = fibonacci2 ( n );\n\n  seed = 123456789;\n\n  [ x, seed ] = r8vec_uniform_01 ( n, seed );\n\n  it_max = 300;\n  tol = 0.000001;\n\n  phi = ( 1.0 + sqrt ( 5.0 ) ) / 2.0;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'POWER_METHOD_TEST01\\n' );\n  fprintf ( 1, '  Use the power method on the Fibonacci2 matrix.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Matrix order N       = %d\\n', n );\n  fprintf ( 1, '  Maximum iterations   = %d\\n', it_max );\n  fprintf ( 1, '  Error tolerance      = %g\\n', tol );\n\n  ctime1 = cputime;\n\n  [ x, lambda, it_num ] = power_method ( n, a, x, it_max, tol );\n\n  ctime2 = cputime;\n  ctime = ctime2 - ctime1;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of iterations = %d\\n', it_num );\n  fprintf ( 1, '  CPU time             = %f\\n', ctime );\n  fprintf ( 1, '  Estimated eigenvalue = %f\\n', lambda );\n  fprintf ( 1, '  Correct value        = %f\\n', phi );\n  fprintf ( 1, '  Error                = %e\\n', abs ( lambda - phi ) );\n%\n%  X2 is the exact eigenvector.\n%\n  x2(1:n,1) = phi.^(0:n-1);\n  x2 = x2 / norm ( x2 );\n%\n%  The sine of the angle between X and X2 is a measure of error.\n%\n  cos_x1x2 = x' * x2;\n  sin_x1x2 = sqrt ( ( 1.0 - cos_x1x2 ) * ( 1.0 + cos_x1x2 ) );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Sine of angle between true and estimated vectors = %e\\n', ...\n    sin_x1x2 );\n\n  return\nend\nfunction power_method_test02 ( )\n\n%*****************************************************************************80\n%\n%% POWER_METHOD_TEST02 uses POWER_METHOD2 on the Fibonacci2 matrix.\n%\n%  Discussion:\n%\n%    This matrix, despite having a single dominant eigenvalue, will generally\n%    converge only very slowly under the power method.  This has to do with\n%    the fact that the matrix has only 3 eigenvectors.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    20 July 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 50;\n\n  a = fibonacci2 ( n );\n\n  seed = 123456789;\n\n  [ x, seed ] = r8vec_uniform_01 ( n, seed );\n\n  it_max = 300;\n  tol = 0.000001;\n\n  phi = ( 1.0 + sqrt ( 5.0 ) ) / 2.0;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'POWER_METHOD_TEST02\\n' );\n  fprintf ( 1, '  Use the power method2 on the Fibonacci2 matrix.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Matrix order N       = %d\\n', n );\n  fprintf ( 1, '  Maximum iterations   = %d\\n', it_max );\n  fprintf ( 1, '  Error tolerance      = %g\\n', tol );\n\n  ctime1 = cputime;\n\n  [ lambda, v, it_num ] = power_method2 ( n, a, x, it_max, tol );\n\n  ctime2 = cputime;\n  ctime = ctime2 - ctime1;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of iterations = %d\\n', it_num );\n  fprintf ( 1, '  CPU time             = %f\\n', ctime );\n  fprintf ( 1, '  Estimated eigenvalue = %f  %f\\n', real ( lambda ), imag ( lambda ) );\n  fprintf ( 1, '  Correct value        = %f\\n', phi );\n  fprintf ( 1, '  Error                = %e\\n', abs ( lambda - phi ) );\n\n  return\nend\nfunction power_method_test03 ( )\n\n%*****************************************************************************80\n%\n%% POWER_METHOD_TEST03 uses POWER_METHOD2 on the TRIS matrix.\n%\n%  Discussion:\n%\n%    This matrix, despite having a single dominant eigenvalue, will generally\n%    converge only very slowly under the power method.  This has to do with\n%    the fact that the matrix has only 3 eigenvectors.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    20 July 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 50;\n\n  alpha = -1.0;\n  beta = 10.0;\n  gamma = 8.0;\n\n  a = tris ( n, n, alpha, beta, gamma );\n\n  seed = 123456789;\n\n  [ x, seed ] = r8vec_uniform_01 ( n, seed );\n\n  it_max = 4000;\n  tol = 0.000001;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'POWER_METHOD_TEST03\\n' );\n  fprintf ( 1, '  Use the power method2 on the TRIS matrix.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Matrix order N       = %d\\n', n );\n  fprintf ( 1, '  Maximum iterations   = %d\\n', it_max );\n  fprintf ( 1, '  Error tolerance      = %g\\n', tol );\n\n  ctime1 = cputime;\n\n  [ lambda, v, it_num ] = power_method2 ( n, a, x, it_max, tol );\n\n  ctime2 = cputime;\n  ctime = ctime2 - ctime1;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of iterations = %d\\n', it_num );\n  fprintf ( 1, '  CPU time             = %f\\n', ctime );\n  fprintf ( 1, '  Estimated eigenvalue = %f  %f\\n', ...\n    real ( lambda ), imag ( lambda ) );\n\n  lambda_vec = tris_eigenvalues ( n, alpha, beta, gamma );\n\n  lambda_max = lambda_vec(1);\n\n  for i = 2 : n\n    if ( abs ( lambda_max ) < abs ( lambda_vec(i) ) )\n      lambda_max = lambda_vec(i);\n    end\n  end\n\n  fprintf ( 1, '  Correct value        = %f  %f\\n', ...\n    real ( lambda_max ), imag ( lambda_max ) );\n  fprintf ( 1, '  Error                = %e\\n', abs ( lambda - lambda_max ) );\n\n  return\nend\nfunction a = fibonacci2 ( n )\n\n%*****************************************************************************80\n%\n%% FIBONACCI2 returns the Fibonacci2 matrix.\n%\n%  Example:\n%\n%    N = 5\n%\n%    0 1 0 0 0\n%    1 1 0 0 0\n%    0 1 1 0 0\n%    0 0 1 1 0\n%    0 0 0 1 1\n%\n%  Properties:\n%\n%    A is generally not symmetric: A' /= A.\n%\n%    A is tridiagonal.\n%\n%    Because A is tridiagonal, it has property A (bipartite).\n%\n%    A is banded, with bandwidth 3.\n%\n%    A is integral: int ( A ) = A.\n%\n%    A is a zero/one matrix.\n%\n%    If N = 1 then\n%      det ( A ) = 0\n%    else\n%      det ( A ) = (-1)**(N-1)\n%\n%    If 1 < N, then A is unimodular.\n%\n%    For 2 <= N, A has the eigenvalues:\n%\n%      PHI   (once),\n%      1     (N-2) times,\n%      1-PHI (once).\n%\n%    When applied to a Fibonacci1 matrix B, the Fibonacci2 matrix\n%    A produces the \"next\" Fibonacci1 matrix C = A*B.\n%\n%    Let PHI be the golden ratio (1+sqrt(5))/2.\n%\n%    For 2 <= N, the eigenvalues and eigenvectors are:\n%\n%    LAMBDA(1)     = PHI,     vector = (1,PHI,PHI^2,...PHI^(N-1));\n%    LAMBDA(2:N-1) = 1        vector = (0,0,0,...,0,1);\n%    LAMBDA(N)     = 1 - PHI. vector = ((-PHI)^(N-1),(-PHI)^(N-2),...,1)\n%\n%    Note that there is only one eigenvector corresponding to 1.\n%    Hence, for 3 < N, the matrix is defective.  This fact means, \n%    for instance, that the convergence of the eigenvector in the power \n%    method will be very slow.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    08 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  for i = 1 : n\n    for j = 1 : n\n\n      if ( i == 1 )\n\n        if ( j == 2 )\n          a(i,j) = 1.0;\n        else\n          a(i,j) = 0.0;\n        end\n\n      else\n\n        if ( j == i-1 | j == i )\n          a(i,j) = 1.0;\n        else\n          a(i,j) = 0.0;\n        end\n\n      end\n\n    end\n  end\n\n  return\nend\nfunction [ r, seed ] = r8vec_uniform_01 ( n, seed )\n\n%*****************************************************************************80\n%\n%% R8VEC_UNIFORM_01 returns a unit pseudorandom R8VEC.\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 entries in the vector.\n%\n%    Input, integer SEED, a seed for the random number generator.\n%\n%    Output, real R(N), the vector of pseudorandom values.\n%\n%    Output, integer SEED, an updated seed for the random number generator.\n%\n  i4_huge = 2147483647;\n\n  if ( seed == 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8VEC_UNIFORM_01 - Fatal error!\\n' );\n    fprintf ( 1, '  Input SEED = 0!\\n' );\n    error ( 'R8VEC_UNIFORM_01 - Fatal error!' );\n  end\n\n  for i = 1 : n\n\n    k = floor ( seed / 127773 );\n\n    seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n    if ( seed < 0 )\n      seed = seed + i4_huge;\n    end\n\n    r(i) = seed * 4.656612875E-10;\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 a = tris ( m, n, x, y, z )\n\n%*****************************************************************************80\n%\n%% TRIS returns the tridiagonal scalar matrix.\n%\n%  Formula:\n%\n%    if ( J = I-1 )\n%      A(I,J) = X\n%    elseif ( J = I )\n%      A(I,J) = Y\n%    elseif ( J = I + 1 )\n%      A(I,J) = Z\n%    else\n%      A(I,J) = 0\n%\n%  Example:\n%\n%    M = 5, N = 5, X = 1, Y = 2, Z = 3\n%\n%    2 3 0 0 0\n%    1 2 3 0 0\n%    0 1 2 3 0\n%    0 0 1 2 3\n%    0 0 0 1 2\n%\n%  Properties:\n%\n%    A is generally not symmetric: A' /= A.\n%\n%    A is tridiagonal.\n%\n%    Because A is tridiagonal, it has property A (bipartite).\n%\n%    A is banded, with bandwidth 3.\n%\n%    A is Toeplitz: constant along diagonals.\n%\n%    If Y is not zero, then for A to be singular, it must be the case that\n%\n%      0.5 * Y / sqrt ( X * Z ) < 1\n%\n%    and\n%\n%      cos (K*PI/(N+1)) = - 0.5 * Y / sqrt ( X * Z ) for some 1 <= K <= N.\n%\n%    If Y is zero, then A is singular when N is odd, or if X or Z is zero.\n%\n%    A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n%    A has eigenvalues\n%\n%      LAMBDA(I) = Y + 2 * sqrt(X*Z) * COS(I*PI/(N+1))\n%\n%    The eigenvalues will be complex if X * Z < 0.\n%\n%    If X = Z, the matrix is symmetric.\n%\n%    As long as X and Z are nonzero, the matrix is irreducible.\n%\n%    If X = Z = -1, and Y = 2, the matrix is a symmetric, positive\n%    definite M matrix, the negative of the second difference matrix.\n%\n%  Modified:\n%\n%    21 October 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    John Todd,\n%    Basic Numerical Mathematics,\n%    Volume 2: Numerical Algebra,\n%    Academic Press, 1978, page 155.\n%\n%  Parameters:\n%\n%    Input, integer M, N, the order of A.\n%\n%    Input, real X, Y, Z, the scalars that define A.\n%\n%    Output, real A(M,N), the matrix.\n%\n  for i = 1 : m\n    for j = 1 : n\n\n      if ( j == i - 1 )\n        a(i,j) = x;\n      elseif ( j == i )\n        a(i,j) = y;\n      elseif ( j == i + 1 )\n        a(i,j) = z;\n      else\n        a(i,j) = 0.0;\n      end\n\n    end\n  end\n\n  return\nend\nfunction lambda = tris_eigenvalues ( n, x, y, z )\n\n%*****************************************************************************80\n%\n%% TRIS_EIGENVALUES returns the eigenvalues of the tridiagonal scalar matrix.\n%\n%  Discussion:\n%\n%    The eigenvalues will be complex if X * Z < 0.\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 A.\n%\n%    Input, real X, Y, Z, the scalars that define A.\n%\n%    Output, complex LAMBDA(N), the eigenvalues.\n%\n  for i = 1 : n\n    angle = i * pi / ( n + 1 );\n    lambda(i) = y + 2.0 * sqrt ( x * z ) * 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/power_method/power_method_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434925908524, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.5957423770548452}}
{"text": "function [x,y,z] = doseCOM(doseStruct)\n%\"doseCOM\"\n%   Find [x,y,z] center of mass of dose contained in doseStruct.  Non\n%   uniform slice width is taken into consideration.\n%\n%   doseStruct is planC{indexS.dose}(doseNum) where doseNum is the number\n%   of the desired dose center of mass.\n%\n%JRA 3/12/04\n%\n%Usage:\n%   function [x,y,z] = doseCOM(doseStruct)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\n[xVals, yVals, zVals] = getDoseXYZVals(doseStruct);\n\ndA = getDoseArray(doseStruct);\n\n[xMesh, yMesh] = meshgrid(xVals, yVals);\n\nfor i=1:size(dA, 3);\n    slice = dA(:,:,i);\n    %Weighted mesh.\n    wX = xMesh .* slice;\n    wY = yMesh .* slice;        \n    sliceDose(i) = sum(slice(:));\n    if sliceDose(i) == 0\n        x(i) = 0;\n        y(i) = 0;\n    else\n        x(i) = sum(wX(:)) / sliceDose(i);\n        y(i) = sum(wY(:)) / sliceDose(i);\n    end\nend\n\n%Get voxel thickness at each slice.\nzDiff = diff(zVals);\ndividers = [zVals(1)-zDiff(1)/2 zDiff/2 + zVals(1:end-1) zVals(end)+zDiff(end)/2];\nvoxThickness = diff(dividers);\ntotalHeight = sum(voxThickness);\n\ntotalDose = sum(sliceDose);\n%Weight x,y,z values by dose on that slice/voxelThickness.\nx = sum(x     .* sliceDose / voxThickness) / totalDose * totalHeight;\ny = sum(y     .* sliceDose / voxThickness) / totalDose * totalHeight;\nz = sum(zVals .* sliceDose / voxThickness) / totalDose * totalHeight;", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/doseCOM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5957317607638577}}
{"text": "function peakIdxV = findFirstPeak(X)\n% AI  10/17/16\n% ========================================================================\n% X  : Input data matrix (nVox x nTimePts)\n% ========================================================================\n\nnVox = size(X,1);\n\n% Find pts of local maxima 't' where x(t)>x(t-1) & x(t)>x(t+1)\ntest1_M = [zeros(nVox,1) diff(X,1,2)];\ntest2_M = [-diff(X,1,2) zeros(nVox,1)];\ntest12_M = test1_M>=0 & test2_M>=0;\n% Retain local maxima that are at least 80% of the max. signal intensity\ntest3_M = bsxfun(@gt,X,.8*max(X,[],2));\nallPeaksM = test12_M & test3_M;\n% First peak\n[~,peakIdxV] = max(allPeaksM,[],2);   %Max returns the index corresponding to the\n                                      %first occurrence of maximum (here 1)\n                                      %If no peaks are found, returns first point)\n\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanAnalysis/DCE-MR analysis/TTHP analysis for DCE-MR/findFirstPeak.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5957317579702438}}
{"text": "function y = limiter(a,b,limtype)\n% Limiter function as defined in Sect. 4.8 and as used in Sect. 10.8\nif  b==0,  y=0; else\n  if limtype == 2          \t% van Albada\n    y = (a^2 + a*b)/(a^2 + b^2);\n  elseif limtype == 1\t\t% Minmod\n    y = max(0, min(a/b,1));\n  else\t\t\t\t% No limiting, no MUSCL\n    y = 0; \n  end   \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/cfdbook/chap10.8/limiter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5957228379624576}}
{"text": "function r=getRange(xCart,useHalfRange,zTx,zRx)\n%%GETRANGE Obtain the bistatic (or monostatic) range measurements of\n%          targets in the absence of refraction under non-relativistic\n%          mechanics, ignoring atmospheric effects. The transmitter and the\n%          target can be collocated.\n%\n%INPUTS: xCart The numDimXN set of N target positions. numDim is typically\n%              2 or 3.\n% useHalfRange A boolean value specifying whether the bistatic range value\n%             should be divided by two. This normally comes up when\n%             operating in monostatic mode, so that the range reported is\n%             a one-way range. The default if this parameter is not\n%             provided is false.\n%         zTx A numDimXN matrix of the positions of the transmitters . If\n%             this parameter is omitted or an empty matrix is passed, the\n%             transmitters are assumed to be at the origin. If only a\n%             single vector is passed, then the transmitter position is\n%             assumed the same for all of the target states being converted.\n%         zRx A numDimXN matrix of the positions of the receivers. If this\n%             parameter is omitted or an empty matrix is passed, the\n%             receivers are assumed to be at the origin. If only a single\n%             vector is passed, then the receiver position is assumed the\n%             same for all of the target states being converted.\n%\n%OUTPUTS: r The 1XN bistatic ranges of the targets.\n%\n%Bistatic range is discussed in [1].\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"Basic tracking using nonlinear 3D monostatic and\n%    bistatic measurements,\" IEEE Aerospace and Electronic Systems\n%    Magazine, vol. 29, no. 8, Part II, pp. 4-53, Aug. 2014.\n%\n%February 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nN=size(xCart,2);\nnumDim=size(xCart,1);\n\nif(nargin<4||isempty(zRx))\n    zRx=zeros(numDim,N);\nelseif(size(zRx,2)==1)\n    zRx=repmat(zRx,[1,N]);\nend\n\nif(nargin<3||isempty(zTx))\n    zTx=zeros(numDim,N);\nelseif(size(zTx,2)==1)\n    zTx=repmat(zTx,[1,N]);\nend\n\nif(nargin<2||isempty(useHalfRange))\n    useHalfRange=false;\nend\n\nr=sqrt(sum((xCart-zTx(1:numDim,:)).^2,1))+sqrt(sum((xCart-zRx(1:numDim,:)).^2,1));\n\nif(useHalfRange)\n   r=r/2; \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/Measurement_Components/getRange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198947, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5957228353803676}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% thermalLB.m: Rayleigh Benard Convection, using a LB method,\n%   based on [Z.Guo, e.a., http://dx.doi.org/10.1002/fld.337].\n%   Boussinesq approximation is used for the buoyancy term:\n%     - Fluid is approximated with incompressible Navier-Stokes\n%       equations including a body force term, and simulated\n%       with a BGK model\n%     - Temperature is approximated with advection-diffusion\n%       equation and simulated with a BGK model\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Lattice Boltzmann sample, written in matlab\n% Copyright (C) 2008 Andrea Parmigiani, Orestis Malaspinas, Jonas Latt\n% Address: Rue General Dufour 24,  1211 Geneva 4, Switzerland\n% E-mail: andrea.parmigiani@terre.unige.ch\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 (at your option) any later version.\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% You should have received a copy of the GNU General Public\n% License along with this program; if not, write to the Free\n% Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n% Boston, MA  02110-1301, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclear\n\n% GENERAL FLOW CONSTANTS\n\nly           = 51;\naspect_ratio = 2;\nlx           = aspect_ratio*ly;\ndelta_x      = 1./(ly-2);\nPr           = 1.;\nRa           = 20000.; % Rayleigh number\ngr           = 0.001;  % Gravity\nbuoyancy     = [0,gr];\n\nThot  = 1; % Heating on bottom wall\nTcold = 0; % Cooling on top wall\nT0 = (Thot+Tcold)/2;\n\ndelta_t = sqrt(gr*delta_x);\n% nu: kinematic viscosity in lattice units\nnu      = sqrt(Pr/Ra)*delta_t/(delta_x*delta_x);\n% k: thermal diffusivity\nk       = sqrt(1./(Pr*Ra))*delta_t/(delta_x*delta_x);\nomegaNS = 1./(3*nu+0.5); % Relaxation parameter for fluid\nomegaT  = 1./(3.*k+0.5); % Relaxation parameter for temperature\n\nmaxT   = 80000;    % total number of iterations\ntPlot  = 100;      % iterations between successive graphical outputs\ntStatistics = 10;  % iterations between successive file accesses\n\n% D2Q9 LATTICE CONSTANTS\ntNS   = [4/9, 1/9,1/9,1/9,1/9, 1/36,1/36,1/36,1/36];\ncxNS  = [  0,   1,  0, -1,  0,    1,  -1,  -1,   1];\ncyNS  = [  0,   0,  1,  0, -1,    1,   1,  -1,  -1];\noppNS = [  1,   4,  5,  2,  3,    8,   9,   6,   7];\n\n% D2Q5 LATTICE CONSTANTS\ntT   = [1/3, 1/6, 1/6, 1/6, 1/6];\ncxT  = [  0,   1,   0,  -1,   0];\ncyT  = [  0,   0,   1,   0,  -1];\noppT = [  1,   4,   5,   2,   3];\n\n[y,x] = meshgrid(1:ly,1:lx);\n\n% INITIAL CONDITION FOR FLUID: (rho=1, u=0) ==> fIn(i) = t(i)\nfIn = reshape( tNS' * ones(1,lx*ly), 9, lx, ly);\n\n% INITIAL CONDITION FOR TEMPERATURE: (T=0) ==> TIn(i) = t(i)\ntIn = reshape( tT' *Tcold *ones(1,lx*ly), 5, lx, ly);\n% Except for bottom wall, where T=1\ntIn(:,:,ly)=Thot*tT'*ones(1,lx);\n% We need a small trigger, to break symmetry\ntIn(:,lx/2,ly-1)= tT*(Thot + (Thot/10.));\n\n% Open file for statistics\nfid = fopen('thermal_statistics.dat','w');\nfprintf(fid,'Thermal Statistics: time-step --- uy[nx/2,ny/2] --- Nu\\n\\n\\n');\n\n% MAIN LOOP (TIME CYCLES)\nfor cycle = 1:maxT\n  % MACROSCOPIC VARIABLES\n   rho = sum(fIn);\n   T = sum(tIn); %temperature\n   ux  = reshape ( (cxNS * reshape(fIn,9,lx*ly)), 1,lx,ly) ./rho;\n   uy  = reshape ( (cyNS * reshape(fIn,9,lx*ly)), 1,lx,ly) ./rho;\n\n   % MACROSCOPIC BOUNDARY CONDITIONS\n   % NO-SLIP for fluid and CONSTANT at lower and upper\n   % boundary...  periodicity wrt. left-right\n   % COLLISION STEP FLUID\n   for i=1:9\n      cuNS         = 3*(cxNS(i)*ux+cyNS(i)*uy);\n      fEq(i,:,:)   = rho .* tNS(i) .* ...\n                       ( 1 + cuNS + 1/2*(cuNS.*cuNS) - 3/2*(ux.^2+uy.^2) );\n      force(i,:,:) = 3.*tNS(i) .*rho .* (T-T0) .* ...\n                       (cxNS(i)*buoyancy(1)+cyNS(i)*buoyancy(2))/(Thot-Tcold);\n      fOut(i,:,:)  = fIn(i,:,:) - omegaNS .* (fIn(i,:,:)-fEq(i,:,:)) + force(i,:,:);\n   end\n\n    % COLLISION STEP TEMPERATURE\n   for i=1:5\n      cu          = 3*(cxT(i)*ux+cyT(i)*uy);\n      tEq(i,:,:)  = T .* tT(i) .* ( 1 + cu );\n      tOut(i,:,:) = tIn(i,:,:) - omegaT .* (tIn(i,:,:)-tEq(i,:,:));\n   end\n\n   % MICROSCOPIC BOUNDARY CONDITIONS FOR FLUID\n   for i=1:9\n        fOut(i,:,1)  = fIn(oppNS(i),:,1);\n        fOut(i,:,ly) = fIn(oppNS(i),:,ly);\n   end\n\n   % STREAMING STEP FLUID\n   for i=1:9\n      fIn(i,:,:) = circshift(fOut(i,:,:), [0,cxNS(i),cyNS(i)]);\n   end\n\n   % STREAMING STEP FLUID\n   for i=1:5\n      tIn(i,:,:) = circshift(tOut(i,:,:), [0,cxT(i),cyT(i)]);\n   end\n\n   % MICROSCOPIC BOUNDARY CONDITIONS FOR TEMEPERATURE\n   %\n   tIn(5,:,ly) = Tcold-tIn(1,:,ly)-tIn(2,:,ly)-tIn(3,:,ly)-tIn(4,:,ly);\n   tIn(3,:,1)  = Thot-tIn(1,:,1)  -tIn(2,:,1) -tIn(4,:,1) -tIn(5,:,1);\n\n   % VISUALIZATION\n   if (mod(cycle,tStatistics)==0)\n       u     = reshape(sqrt(ux.^2+uy.^2),lx,ly);\n       uy_Nu = reshape(uy,lx,ly); % vertical velocity\n       T     = reshape(T,lx,ly);\n       Nu    = 1. + sum(sum(uy_Nu.*T))/(lx*k*(Thot-Tcold));\n       fprintf(fid,'%8.0f  %12.8f  %12.8f\\n',cycle,u(int8(lx/2),int8(ly/2))^2, Nu);\n       if(mod(cycle,tPlot)==0)\n           subplot(2,1,1);\n           imagesc(u(:,ly:-1:1)');\n           title('Fluid velocity');\n           axis off; drawnow\n           subplot(2,1,2);\n           imagesc(T(:,ly:-1:1)')\n           title(['Temperature (Nusselt number is ' num2str(Nu) ')']);\n           axis off; drawnow\n       end\n   end\nend\n\nfclose(fid);\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/LBM/rayleighbenard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5957228326811987}}
{"text": "function [Pfa_asv, Pmiss_asv, Pmiss_spoof_asv] = obtain_asv_error_rates(tar_asv, non_asv, spoof_asv, thresh_asv)\n\nNtar_asv    = length(tar_asv);\nNnon_asv    = length(non_asv);\nNspoof_asv  = length(spoof_asv);\n\n% Obtain ASV false alarm and miss rates\nPfa_asv     = sum(non_asv >= thresh_asv)./Nnon_asv;\nPmiss_asv   = sum(tar_asv <  thresh_asv)./Ntar_asv;\nif isempty(spoof_asv)\n    Pmiss_spoof_asv = [];\nelse\n    Pmiss_spoof_asv = sum(spoof_asv <  thresh_asv)./Nspoof_asv;\nend", "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/obtain_asv_error_rates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5957228326811986}}
{"text": "% Figures 6.8-6.10: Quadratic smoothing\n% Section 6.3.3\n% Boyd & Vandenberghe \"Convex Optimization\"\n% Original by Lieven Vandenberghe\n% Adapted for CVX Argyris Zymnis - 10/2005\n%\n% Suppose we have a signal x, which does not vary too rapidly\n% and that x is corrupted by some small, rapidly varying noise v,\n% ie. x_cor = x + v. Then if we want to reconstruct x from x_cor\n% we should solve (with x_hat as the parameter)\n%        minimize ||x_hat - x_cor||_2 + lambda*phi_quad(x_hat)\n%\n% where phi_quad(x) = sum(x_(i+1)-x_i)^2 , for i = 1 to n-1.\n% The parameter lambda controls the ''smoothness'' of x_hat.\n%\n% The first figure which is generated shows the original and\n% the corrupted signals. The second figure shows the tradeoff curve\n% obtained when varying lambda and the third figure shows three\n% reconstructed signals.\n%\n% NOTE: This is not a good problem to use CVX on. By exploiting\n% the sparsity in this case, we can solve this problem much more\n% efficiently using least squares.\n\n\nrandn('state',0);\n\nn = 4000;  t = (0:n-1)';\nexact = 0.5*sin((2*pi/n)*t).*sin(0.01*t);\ncorrupt = exact + 0.05*randn(size(exact));\n\nfigure(1)\nsubplot(211)\nplot(t,exact,'-');\naxis([0 n -0.6 0.6])\ntitle('original signal');\nylabel('ya');\n\nsubplot(212)\nplot(t,corrupt,'-');\naxis([0 n -0.6 0.6])\nxlabel('x');\nylabel('yb');\ntitle('corrupted signal');\n%print -deps smoothrec_signals.eps % figure 6.8, page 313\n\nA = sparse(n-1,n);\nA(:,1:n-1) = -speye(n-1,n-1);  A(:,2:n) = A(:,2:n)+speye(n-1,n-1);\n\n% tradeoff curve, figure 6.9, page 313\nnopts = 100;\nlambdas = logspace(-10,10,nopts);\n\nobj1 = [];  obj2 = [];\n\nfprintf('computing 100 points on tradeoff curve ... \\n');\n\nfor i=1:nopts\n\n  lambda = lambdas(i);\n  cvx_begin quiet\n    variable x(n)\n    minimize(norm(x-corrupt)+lambda*norm(x(2:n)-x(1:n-1)))\n  cvx_end\n  obj1 = [obj1, norm(full(A*x))];\n  obj2 = [obj2, norm(full(x-corrupt))];\n\n  fprintf('tradeoff point %d\\n',i);\nend;\n\nfigure(2)\nplot(obj2,obj1,'-');  hold on;\nplot(0,norm(A*corrupt),'o');\nplot(norm(corrupt),0,'o');  hold off;\nxlabel('x');\nylabel('y');\ntitle('||xhat-xcorr||_2 vs. ||D xhat||_2');\n%print -deps smoothrec_tradeoff.eps % figure 6.9, page 313\n\n%three smooth signals, figure 6.10, page 314\nnopts = 3;\nalphas = [8 3 1];\nxrecon = [];\n\nfor i=1:3\n   fprintf(1,'Reconstructed Signals: %d of 3 \\n',i)\n   alpha = alphas(i);\n   cvx_begin quiet\n    variable x(n)\n    minimize(norm(x(2:n)-x(1:n-1)))\n    subject to\n        norm(x-corrupt) <= alpha;\n   cvx_end\n   xrecon = [xrecon, x];\n\nend\n\nfigure(3)\nsubplot(311), plot(xrecon(:,1));\naxis([0 n -0.6 0.6])\nylabel('ya');\ntitle('||xhat-xcorr||_2=8');\nsubplot(312), plot(xrecon(:,2));\naxis([0 n -0.6 0.6])\nylabel('yb');\ntitle('||xhat-xcorr||_2=3');\nsubplot(313), plot(xrecon(:,3));\naxis([0 n -0.6 0.6])\nxlabel('x');\nylabel('yc');\ntitle('||xhat-xcorr||_2=1');\n%print -deps smoothrec_results.eps % figure 6.10, page 314\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/cvxbook/Ch06_approx_fitting/smoothrec_cvx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5957228273999399}}
{"text": "function [e E] = xyzankurError(X1,X2,type)\n\n% XYZANKURERROR Computes the error between two poses in xyz format \n% FORMAT\n% DESC Computes the error between two poses in xyz format \n% data. \n% ARG X1 : first set of poses\n% ARG X2 : second set of poses\n% RETURN E : mean error for the sequence\n%\n% SEEALSO : xyzankurDraw, xyzankurModify\n%\n% COPYRIGHT : Carl Henrik Ek, Andreas Damianou  and Neil Lawrence, 2011\n%\n  \n% MOCAP\n\nif(nargin<2)\n    error('Too few arguments');\nend\nif(size(X1)~=size(X2))\n    error('Dimensions mismatch');\nend\n\nE = zeros(size(X1,1),1);\nfor(i = 1:1:size(X1,1))\n    E(i) = mean(sqrt(sum((xyzankur2joint(X1(i,:)) - xyzankur2joint(X2(i,:))).^2,2)));\nend\ne = mean(E);\n\nreturn\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mocap/xyzankurError.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.595722827282861}}
{"text": "% Fig. 9.8  Feedback Control of Dynamic Systems, 5e \n%             Franklin, Powell, Emami\n n=[1 1];\n d = [1 0 0];\n rlocus(n,d)\n axis([-6 2 -3 3])\n hold on\n r=roots([1 1 1]);\n plot(r,'*')\n  z=0:.1:.9;\n wn= 1:6;\n sgrid(z, wn)\n hold 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/fig9_8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5957228218845229}}
{"text": "function x = line_adj_null_left ( m, n )\n\n%*****************************************************************************80\n%\n%% LINE_ADJ_NULL_LEFT returns a left null vector of the LINE_ADJ matrix.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 March 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer M, N, the order of the matrix.\n%\n%    Output, real X(M), a null vector\n%\n  if ( mod ( m, 2 ) == 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'LINE_ADJ_NULL_LEFT - Fatal error!\\n' );\n    fprintf ( 1, '  For M even, there is no null vector.\\n' );\n    error ( 'LINE_ADJ_NULL_LEFT - Fatal error!' );\n  end\n\n  x = zeros ( m, 1 );\n\n  x(1:4:m,1) =  1.0;\n  x(3:4:m,1) = -1.0;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/line_adj_null_left.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.5957167849259751}}
{"text": "function b = r8gd_to_r8ge ( n, ndiag, offset, a )\n\n%*****************************************************************************80\n%\n%% R8GD_TO_R8GE copies a R8GD matrix to a R8GE 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%    10 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 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%    Input, real A(N,NDIAG), the R8GD matrix.\n%\n%    Output, real B(N,N), the R8GE matrix.\n%\n  b(1:n,1:n) = 0.0E+00;\n\n  for i = 1 : n\n    for diag = 1 : ndiag\n      j = i + offset(diag);\n      if ( 1 <= j & j <= n )\n        b(i,j) = a(i,diag);\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_to_r8ge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.5957167606209383}}
{"text": "function triangulation_test23 ( )\n\n%*****************************************************************************80\n%\n%% TEST23 tests TRIANGULATION_ORDER6_BOUNDARY_EDGE_COUNT.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    24 August 2006\n%\n%  Author:\n%\n%    John Burkardt\n%  \n  dim_num = 2;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST23\\n' );\n  fprintf ( 1, '  TRIANGULATION_ORDER6_BOUNDARY_EDGE_COUNT counts the\\n' );\n  fprintf ( 1, '    boundary edges in an order 6 triangulation.\\n' );\n\n  [ node_num, triangle_num, hole_num ] = ...\n    triangulation_order6_example1_size ( );\n\n  [ node_xy, triangle_node, triangle_neighbor ] = ...\n    triangulation_order6_example1 ( node_num, triangle_num );\n\n  boundary_edge_num = triangulation_order6_boundary_edge_count ( ...\n    triangle_num, triangle_node );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of boundary edges = %d\\n', boundary_edge_num );\n  fprintf ( 1, '  Correct number =           %d\\n', 16 );\n\n  return\nend\n", "meta": {"author": "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_test23.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.5957167605232369}}
{"text": "function [h] = fscatter3(X,Y,Z,C,cmap);\n% [h] = fscatter3(X,Y,Z,C,cmap);\n% Plots point cloud data in cmap color classes and 3 Dimensions,\n% much faster and very little memory usage compared to scatter3 !\n% X,Y,Z,C are vectors of the same length\n% X,Y,Z,C might be put in as structure points.x,points.y,points.z,points.int  \n% with C being used as index into colormap (can be any values though)\n% cmap is optional colourmap to be used\n% h are handles to the line objects\n\n% Felix Morsdorf, Jan 2003 (last update Oct. 2010), Remote Sensing Laboratory Zuerich\n\n  if nargin == 1\n    if isfield(X,'int')\n      C = X.int;\n      Z = X.z;\n    else\n      C = X.z;\n      Z = C;\n    end\n    Y = X.y;\n    NX = X.x;\n    clear X;\n    X = NX;clear NX;\n    numclass = 256; % Number of color classes\n    cmap = myspecmap(256);\n    siz = 5;\n  elseif nargin == 4\n    numclass = 256; % Number of color classes\n    cmap = hsv(256);\n    siz = 5;\n  elseif nargin == 5\n    numclass = max(size(cmap));\n    siz = 5;\n    if numclass == 1\n      siz = cmap;\n      cmap = hsv(256);\n      numclass = 256;\n    end  \n  elseif nargin == 6\n    numclass = max(size(cmap));\n    if numclass == 1\n      siz = cmap;\n      cmap = hsv(256);\n      numclass = 256;\n    end  \n  end  \n  \n\n\n% avoid too many calculations\n\nmins = min(C);\nmaxs = max(C);\nminz = min(Z);\nmaxz = max(Z);\nminx = min(X);\nmaxx = max(X);\nminy = min(Y);\nmaxy = max(Y);\n\n% construct colormap :\n\ncol = cmap;\n\n% determine index into colormap\n\nii = floor( (C - mins ) * (numclass-1) / (maxs - mins) );\nii = ii + 1;\n\ncolormap(cmap);\n  \nhold on\nk = 0;o = k;\nfor j = 1:numclass\n  jj = (ii(:)== j);\n  if ~isempty(jj)\n    k = k + 1;\n    h = plot3(X(jj),Y(jj),Z(jj),'.','color',col(j,:),'markersize',siz);\n    if ~isempty(h)\n      o = o+1;\n        hp(o) = h;\n    end\n  end  \nend\ncaxis([min(C) max(C)])\naxis equal;rotate3d on;view(3);\nbox on\nhcb = colorbar('location','east');\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/2993-fscatter3-m/fscatter3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.595673353903675}}
{"text": "function x = gompertz_cdf_inv ( cdf, a, b )\n\n%*****************************************************************************80\n%\n%% GOMPERTZ_CDF_INV inverts the Gompertz 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%  Reference:\n%\n%    Johnson, Kotz, and Balakrishnan,\n%    Continuous Univariate Distributions, Volume 2, second edition,\n%    Wiley, 1994, pages 25-26.\n%\n%  Parameters:\n%\n%    Input, real CDF, the value of the CDF.\n%\n%    Input, real A, B, the parameters of the PDF.\n%    1 < A, 0 < B.\n%\n%    Output, real X, the corresponding argument.\n%\n  if ( cdf < 0.0 )\n    x = 0.0;\n  elseif ( cdf < 1.0 )\n    x = log ( 1.0 - log ( 1.0 - cdf ) * log ( a ) / b  ) / log ( a );\n  else\n    x = r8_huge ( );\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/gompertz_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5956733517552073}}
{"text": "function lambda = invol_eigenvalues ( n )\n\n%*****************************************************************************80\n%\n%% INVOL_LAMBDA returns the eigenvalues of the INVOL matrix.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    19 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 LAMBDA(N,1), the eigenvalues.\n%\n  lambda = zeros ( n, 1 );\n\n  k = floor ( n / 2 );\n\n  lambda(1:k,1) =   +1.0;\n  lambda(k+1:n,1) = -1.0;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/invol_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.5956733458303117}}
{"text": "function [X, y, XTest, yTest] = mappingLoadData(dataset, seedVal)\n\n% MAPPINGLOADDATA Load a regression or classification dataset.\n\n\nif nargin < 2\n  seedVal = 1e5;\nend\nrandn('seed', seedVal)\nrand('seed', seedVal)\nXTest = [];\nyTest = [];\nswitch dataset\n %/~\n case 'pumadynSeeger'\n  data = load('Dataset.data');\n  ind = randperm(size(data, 1));\n  indTr = ind(1:7168);\n  indTe = ind(7169:end);\n  X = data(indTr, 1:end-1);\n  y = data(indTr, end);\n  XTest = data(indTe, 1:end-1);\n  yTest = data(indTe, end);\n  Xscale = sqrt(var(X));\n  for j = 1:length(Xscale);\n    X(:, j) = X(:, j)/Xscale(j);\n    XTest(:, j) = XTest(:, j)/Xscale(j);\n  end\n  augX = [X ones(size(X, 1), 1)];\n  w = inv(augX'*augX)*augX'*y;\n  y = y -augX*w;\n  augTestX = [XTest ones(size(XTest, 1), 1)];\n  yTest = yTest - augTestX*w;\n  yscale = sqrt(var(y));\n  y = y/yscale;\n  yTest = yTest/yscale;\n case 'pumadyn'\n\n  % Data is variance 1, no need to normalise.\n  data = load('Dataset.data');\n  ind = randperm(size(data, 1));\n  indTr = ind(1:7168);\n  indTe = ind(7169:end);\n  X = data(indTr, 1:end-1);\n  y = data(indTr, end);\n  XTest = data(indTe, 1:end-1);\n  yTest = data(indTe, end);\n  %~/\n case 'usps'\n  load usps_train\n  X = ALL_DATA;\n  range =  min(ALL_T):max(ALL_T);\n  for i = 1:length(range)\n    y(:, i) = (ALL_T == range(i))*2 - 1;\n  end\n  if nargout > 2\n    load usps_test\n    XTest = ALL_DATA;\n    range =  min(ALL_T):max(ALL_T);\n    for i = 1:length(range)\n      yTest(:, i) = (ALL_T == range(i))*2 - 1;\n    end\n  end\n  \n case {'usps0', 'usps1', 'usps2', 'usps3', 'usps4', 'usps5', 'usps6', 'usps7', 'usps8', 'usps9'}\n  digitNo = str2num(dataset(end));\n  load usps_train\n  X = ALL_DATA;\n  range =  min(ALL_T):max(ALL_T);\n  for i = 1:length(range)\n    y(:, i) = (ALL_T == range(i))*2 - 1;\n  end\n  if nargout > 2\n    load usps_test\n    XTest = ALL_DATA;\n    range =  min(ALL_T):max(ALL_T);\n    for i = 1:length(range)\n      yTest(:, i) = (ALL_T == range(i))*2 - 1;\n    end\n  end\n  y = y(:, digitNo+1);\n  yTest = yTest(:, digitNo+1);\n  \n case 'regressionOne'\n  try\n    load regressionOneData.mat \n  catch\n    \n    [void, errid] = lasterr;\n    if strcmp(errid, 'MATLAB:load:couldNotReadFile')\n      numIn = 2;\n      N = 500;\n      X = zeros(N, numIn);\n      X(1:floor(N/2), :) = ...\n          randn(floor(N/2), numIn)*.5+1;\n      X(floor(N/2)+1:end, :) = ...\n          randn(ceil(N/2), numIn)*.5-1;\n      kern = kernCreate(X, 'rbfard');\n      kern.variance = 1;\n      kern.inverseWidth = 20;\n      kern.inputScales = [0 0.999];\n      \n      K = kernCompute(kern, X);\n      y = real(gaussSamp(K, 1)') + randn(N, 1)*0.01;\n\n      save('regressionOneData.mat', 'numIn', 'N', 'X', 'y')\n    else\n      error(lasterr);\n    end\n    \n  end\n  \n case 'regressionTwo'\n  try\n    load regressionTwoData.mat \n  catch\n    \n    [void, errid] = lasterr;\n    if strcmp(errid, 'MATLAB:load:couldNotReadFile')\n      numIn = 2;\n      N = 500;\n      X = zeros(N, numIn);\n      X(1:floor(N/2), :) = ...\n          randn(floor(N/2), numIn)*.5+1;\n      X(floor(N/2)+1:end, :) = ...\n          randn(ceil(N/2), numIn)*.5-1;\n      kern = kernCreate(X, 'rbfard');\n      kern.variance = 1;\n      kern.inverseWidth = 20;\n      kern.inputScales = [0.999 .2];\n      \n      K = kernCompute(kern, X);\n      y = real(gaussSamp(K, 1)') + randn(N, 1)*0.01;\n    \n      save('regressionTwoData.mat', 'numIn', 'N', 'X', 'y')\n    else\n      error(lasterr)\n    end\n        \n  end\n\n case 'regressionThree'\n  try\n    load regressionThreeData.mat \n  catch\n    \n    [void, errid] = lasterr;\n    if strcmp(errid, 'MATLAB:load:couldNotReadFile')\n      numIn = 2;\n      N = 500;\n      X = zeros(N, numIn);\n      X(1:floor(N/2), :) = ...\n          randn(floor(N/2), numIn)*.5+1;\n      X(floor(N/2)+1:end, :) = ...\n          randn(ceil(N/2), numIn)*.5-1;\n      kern = kernCreate(X, 'lin');\n      kern.variance = 1;\n      \n      K = kernCompute(kern, X);\n      y = real(gaussSamp(K, 1)') + randn(N, 1)*0.01;\n      save('regressionThreeData.mat', 'numIn', 'N', 'X', 'y')\n    else \n      error(lasterr);\n    end\n  end\n  \n case 'regressionFour'\n  try\n    load regressionFourData.mat \n  catch\n    \n    [void, errid] = lasterr;\n    if strcmp(errid, 'MATLAB:load:couldNotReadFile')\n      numIn = 2;\n      N = 500;\n      X = zeros(N, numIn);\n      X(1:floor(N/2), :) = ...\n          randn(floor(N/2), numIn)*.5+1;\n      X(floor(N/2)+1:end, :) = ...\n          randn(ceil(N/2), numIn)*.5-1;\n      kern = kernCreate(X, 'mlp');\n      kern.variance = 1;\n      kern.weightVariance = 1;\n      kern.biasVariance = 1;\n      K = kernCompute(kern, X);\n      y = real(gaussSamp(K, 1)') + randn(N, 1)*0.01;\n      save('regressionFourData.mat', 'numIn', 'N', 'X', 'y')\n    else \n      error(lasterr);\n    end\n  end\n case 'classificationOne'\n  try\n    load classificationOneData.mat\n  catch\n    [void, errid] = lasterr;\n    if strcmp(errid, 'MATLAB:load:couldNotReadFile')\n      X = [randn(100,2)-[zeros(100, 1) 6*ones(100, 1)]; randn(100,2)+[zeros(100, 1) 6*ones(100, 1)]; randn(100, 2)];\n      y = [ones(200, 1); -ones(100, 1)];\n      save('classificationOneData.mat', 'X', 'y')\n    else\n      error(lasterr);  \n    end\n  end\n case 'classificationTwo'\n   \n  try\n    load classificationTwoData.mat \n  catch\n    [void, errid] = lasterr;\n    if strcmp(errid, 'MATLAB:load:couldNotReadFile')\n      numIn = 2;\n      N = 500;\n      \n      X = zeros(N, numIn);\n      X = rand(N, numIn);\n      \n      kern = kernCreate(X, 'rbf');\n      kern.variance = 10;\n      kern.inverseWidth = 10;\n      \n      K = kernCompute(kern, X);\n      u = real(gaussSamp(K, 1)');\n      \n      p = cumGaussian(u);\n      y = 2*(rand(size(u))>p)-1;\n      save('classificationTwoData.mat', 'numIn', 'N', 'X', 'u', 'y')\n    else\n      error(lasterr);  \n    end\n    \n  end\n\n case 'classificationThree'\n   \n  try\n    load classificationThreeData.mat \n  catch\n    [void, errid] = lasterr;\n    if strcmp(errid, 'MATLAB:load:couldNotReadFile')\n      numIn = 2;\n      N = 500;\n      \n      X = zeros(N, numIn);\n      X = rand(N, numIn);\n      \n      kern = kernCreate(X, 'rbf');\n      kern.variance = 10;\n      kern.inverseWidth = 10;\n      \n      K = kernCompute(kern, X);\n      u = real(gaussSamp(K, 1)');\n      a = 3;\n      pMinus = cumGaussian(u-a/2);\n      pPlus = cumGaussian(-u-a/2);\n      p =rand(size(u));\n      indMinus = find(p<pMinus);\n      indPlus = find(p>pMinus & p<pMinus+pPlus);\n      indNone = find(p>pMinus+pPlus);\n      y = zeros(N, 1);\n      y(indPlus) = 1;\n      y(indMinus) = -1;\n      y(indNone, :) = [];\n      X(indNone, :) = [];\n      save('classificationThreeData.mat', 'numIn', 'N', 'X', 'u', 'y')\n    else\n      error(lasterr);  \n    end\n    \n  end\n\n case 'orderedOne'\n  dataPerCat = 30;\n  spacing = 3;\n  \n  % Generate a toy data-set of (linear) ordered categories.\n  X = [randn(dataPerCat,2)-[zeros(dataPerCat, 1) repmat(3*spacing, dataPerCat, 1)]; ...\n       randn(dataPerCat,2)-[zeros(dataPerCat, 1) repmat(2*spacing, dataPerCat, 1)]; ...\n       randn(dataPerCat,2)-[zeros(dataPerCat, 1) repmat(spacing, dataPerCat, 1)]; ...\n       randn(dataPerCat, 2); ...\n       randn(dataPerCat,2)+[zeros(dataPerCat, 1) repmat(spacing, dataPerCat, 1)]; ...\n       randn(dataPerCat,2)+[zeros(dataPerCat, 1) repmat(2*spacing, dataPerCat, 1)]; ...\n       randn(dataPerCat,2)+[zeros(dataPerCat, 1) repmat(3*spacing, dataPerCat, 1)]];\n  y = [zeros(dataPerCat, 1); ...\n       repmat(1, dataPerCat, 1); repmat(2, dataPerCat, 1); ...\n       repmat(3, dataPerCat, 1); repmat(4, dataPerCat, 1); ...\n       repmat(5, dataPerCat, 1); repmat(6, dataPerCat, 1)];\n\n case 'orderedTwo'\n  dataPerCat = 30;\n  spacing = 3;\n  \n  % Generate a toy data-set of (linear) ordered categories.\n  thetaR = [randn(dataPerCat,2)-[zeros(dataPerCat, 1) repmat(3*spacing, dataPerCat, 1)]; ...\n            randn(dataPerCat,2)-[zeros(dataPerCat, 1) repmat(2*spacing, dataPerCat, 1)]; ...\n            randn(dataPerCat,2)-[zeros(dataPerCat, 1) repmat(spacing, dataPerCat, 1)]; ...\n            randn(dataPerCat, 2); ...\n            randn(dataPerCat,2)+[zeros(dataPerCat, 1) repmat(spacing, dataPerCat, 1)]; ...\n            randn(dataPerCat,2)+[zeros(dataPerCat, 1) repmat(2*spacing, dataPerCat, 1)]; ...\n            randn(dataPerCat,2)+[zeros(dataPerCat, 1) repmat(3*spacing, dataPerCat, 1)]];\n  thetaR(:, 1) = thetaR(:, 1);\n  thetaR(:, 2) = thetaR(:, 2) + 15;\n  X = [sin(thetaR(:, 1)).*thetaR(:, 2) cos(thetaR(:, 1)).*thetaR(:, 2)];\n  y = [zeros(dataPerCat, 1); ...\n       repmat(1, dataPerCat, 1); repmat(2, dataPerCat, 1); ...\n       repmat(3, dataPerCat, 1); repmat(4, dataPerCat, 1); ...\n       repmat(5, dataPerCat, 1); repmat(6, dataPerCat, 1)];\n\n  \nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/datasets/mappingLoadData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.5956733424230348}}
{"text": "%% DEMO 17: Detector Rotation\n%\n%\n%\n%  Some systems have a slight rotation of the detector due to mechanicall\n%  inacuracies. \n%\n%  According to the article \"A geometric calibration method for cone beam\n%  CT systems\" (DOI: 10.1118/1.2198187), only Roll needs to be corrected\n%  for in the algorithmic part, as the other 2 can be easily ignored if\n%  \"sufficiently small\". In TIGRE we decided to leave that to the users\n%  discretion and implemented the 3 possible detector rotation, per angle\n%  if needed. \n%\n%  This demo shows how to use it. \n%  \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\n\nclear;\nclose all;\n%% Define Geometry\n% \n% VARIABLE                                   DESCRIPTION                    UNITS\n%-------------------------------------------------------------------------------------\ngeo.DSD = 1536;                             % Distance Source Detector      (mm)\ngeo.DSO = 1000;                             % Distance Source Origin        (mm)\n% Detector parameters\ngeo.nDetector=[512; 512];\t\t\t\t\t% number of pixels              (px)\ngeo.dDetector=[0.8; 0.8]; \t\t\t\t\t% size of each pixel            (mm)\ngeo.sDetector=geo.nDetector.*geo.dDetector; % total size of the detector    (mm)\n% Image parameters\ngeo.nVoxel=[128;128;128];                   % number of voxels              (vx)\n\n% a bit smaller than usual because the demo includes a very big detector\n% angle for showcase\ngeo.sVoxel=[256;256;256]/2;                 % total size of the image       (mm)\n\n\ngeo.dVoxel=geo.sVoxel./geo.nVoxel;          % size of each voxel            (mm)\n% Offsets\ngeo.offOrigin =[0;0;0];                     % Offset of image from origin   (mm)              \ngeo.offDetector=[0; 0];                     % Offset of Detector            (mm)\n\n\n% Auxiliary \ngeo.accuracy=0.5;                           % Accuracy of FWD proj          (vx/sample)\n\n%% Geometry has an additional field for the rotation.\n%\n%\nangles=linspace(0,2*pi,100);\n\n% lets define 3 angles, with big variability in each direction\n\nroll=angles;\npitch=0.7*linspace(0,1,size(angles,2));\nyaw=0.7*linspace(0,1,size(angles,2));\n\n% Fill rotDetector. It can also be a 3x1, if its not angle dependent. e.g.\n% geo.rotDetector=[pi/5; 0; pi/10];\n\ngeo.rotDetector=[roll;pitch;yaw];\n\n\n\n%% Load data and generate projections \n% define angles\n% Load thorax phatom data\nhead=headPhantom(geo.nVoxel);\n% generate projections\nprojections=Ax(head,geo,angles,'interpolated');\n\n%% Lets plot the projections with a rotated detector\nplotProj(projections,angles);\n\n%% lets reconstruct with and without detector rotation\n% \nimgRotDet=OS_SART(projections,geo,angles,50);\n\n% No rotation\ngeo.rotDetector=[0;0;0];\nprojections2=Ax(head,geo,angles,'interpolated');\n\n\nimgnoRot=OS_SART(projections2,geo,angles,50);\n\n% %% Plot to show that indeed the reconstruction is right\n% \n% \n% \nplotImg([imgRotDet imgnoRot] ,'dim',3)\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/d17_DetectorRotation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5956733377569484}}
{"text": "function estimation_results = se3EKF_SLAM(data, NumberOfSteps)\n% R-EKF SLAM \n\n% load pre-given data: odometry and observations\nif nargin < 1\n    load('./data.mat');\nend\n\ndata_matrix = data.state;\n\nodom_sigma = data.odom_sigma;\nobsv_sigma = data.obsv_sigma;\n\n% odoCov = data.odom_cov;   % constant variable\n% obsCov = data.obse_cov;   % constant variable\n\n%%%%%%%%%%%%%%%%%%%% Estimation_X is used to save the state in each step %%%%%%%%%%%%%%%%%%%%  \n%%%%%%%%%%%%%%%%%%%% In every step, all elements of Estimation_X will be changed %%%%%%%%%%%%\nEstimation_X.orientation = data.poses.orientation(1:3,1:3);\nEstimation_X.position    = data.poses.position(:,1);\nEstimation_X.cov         = sparse(6,6);\nEstimation_X.landmarks   = [];       % the landmarks observed until this step (included), 4*N format, the 4-th row is the index\nEstimation_X0.IndexObservedNew=[];\nEstimation_X0.IndexObservedAlreadyThis=[];\n%%%%%%%%%%%%%%%%%%%% Estimation_X is used to save the state in each step %%%%%%%%%%%%%%%%%%%%  \n\n\n% Initialize\nif nargin < 2\n    NumberOfSteps = max(data_matrix(:,4));  % step instead of pose,  hence, it does not include pose 0\nelseif NumberOfSteps > max(data_matrix(:,4))\n    NumberOfSteps = max(data_matrix(:,4));\nend\nestimation_results = cell(1, NumberOfSteps+1);\nestimation_results{1} = Estimation_X;\nrow_idx = (data_matrix(:, end) <= NumberOfSteps+1);\ndata_matrix = data_matrix(row_idx, :);\n\n\nfor i = 0:NumberOfSteps\n    IndexOfCurrentStepInDataMatrix = find(data_matrix(:,4) == i); \n    m = size(IndexOfCurrentStepInDataMatrix, 1);\n    if ( mod(i, 50) == 0 )\n        disp(['Processing pose ', int2str(i)]);\n    end\n    % det(Estimation_X.cov)\n    if i==NumberOfSteps-1\n    a=1;\n    end\n    \n    if i ~= NumberOfSteps\n        OdometryFromThis2Next = data_matrix(IndexOfCurrentStepInDataMatrix(m-5):IndexOfCurrentStepInDataMatrix(m),1);\n        if m > 6\n            CameraMeasurementThis = [ data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(m-6) , 1 ),...\n                                      data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(m-6) , 3 )];    \n           [Estimation_X] = se3EKF_update(Estimation_X, CameraMeasurementThis, obsv_sigma );\n        end\n        \n        estimation_results{i+1} = Estimation_X;\n        \n%        propagation using odometry info\n        [Estimation_X] = se3EKF_propagate(Estimation_X, OdometryFromThis2Next, odom_sigma );\n\n    else\n        a=2;\n        if m > 6\n            CameraMeasurementThis = [ data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(end) , 1 ) , ...\n                                      data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(end) , 3 )];\n            [Estimation_X] = se3EKF_update(Estimation_X, CameraMeasurementThis, obsv_sigma );\n        end\n        estimation_results{i+1} = Estimation_X;\n    end\nend\nclearvars -except estimation_results", "meta": {"author": "RomaTeng", "repo": "EKF-SLAM-on-Manifold", "sha": "12d7d8d88c84161baed173e38d49dedb4adb2b96", "save_path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold", "path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold/EKF-SLAM-on-Manifold-12d7d8d88c84161baed173e38d49dedb4adb2b96/se3_ekf_3d/se3EKF_SLAM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5956707844397541}}
{"text": "function [ point_coord, edge_point, face_order, face_point ] = ...\n  icos_shape ( point_num, edge_num, face_num, face_order_max )\n\n%*****************************************************************************80\n%\n%% ICOS_SHAPE describes an icosahedron.\n%\n%  Discussion:\n%\n%    The input data required for this routine can be retrieved from\n%    ICOS_SIZE.\n%\n%    The vertices lie on the unit sphere.\n%\n%    The dual of an icosahedron is a dodecahedron.\n%\n%    The data has been rearranged from a previous assignment.  \n%    The STRIPACK program refuses to triangulate data if the first\n%    three nodes are \"collinear\" on the sphere.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    21 July 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer POINT_NUM, the number of points (12).\n%\n%    Input, integer EDGE_NUM, the number of edges (30).\n%\n%    Input, integer FACE_NUM, the number of faces (20).\n%\n%    Input, integer FACE_ORDER_MAX, the maximum number of vertices per face (3).\n%\n%    Output, real POINT_COORD(3,POINT_NUM); the points.\n%\n%    Output, integer EDGE_POINT(2,EDGE_NUM), the points that make up each \n%    edge, listed in ascending order of their indexes.\n%\n%    Output, integer FACE_ORDER(FACE_NUM), the number of vertices per face.\n%\n%    Output, integer FACE_POINT(FACE_ORDER_MAX,FACE_NUM); FACE_POINT(I,J)\n%    is the index of the I-th point in the J-th face.  The points are listed \n%    in the counter-clockwise direction defined by the outward normal at the \n%    face.  The nodes of each face are ordered so that the lowest index \n%    occurs first.  The faces are then sorted by nodes.\n%\n  dim_num = 3;\n%\n%  Set point coordinates.\n%\n  phi = 0.5 * ( sqrt ( 5.0 ) + 1.0 );\n  b = 1.0 / sqrt ( 1.0 + phi * phi );\n  a = phi * b;\n  z = 0.0;\n%\n%  Set the points.\n%\n  point_coord(1:dim_num,1:point_num) = [ ...\n      a,  b,  z; ...\n      a, -b,  z; ...\n      b,  z,  a; ...\n      b,  z, -a; ...\n      z,  a,  b; ...\n      z,  a, -b; ...\n      z, -a,  b; ...\n      z, -a, -b; ...\n     -b,  z,  a; ...\n     -b,  z, -a; ...\n     -a,  b,  z; ...\n     -a, -b,  z ]';\n%\n%  Set the edges.\n%\n  edge_point(1:2,1:edge_num) = [ ...\n     1,  2; ...\n     1,  3; ...\n     1,  4; ...\n     1,  5; ...\n     1,  6; ...\n     2,  3; ...\n     2,  4; ...\n     2,  7; ...\n     2,  8; ...\n     3,  5; ...\n     3,  7; ...\n     3,  9; ...\n     4,  6; ...\n     4,  8; ...\n     4, 10; ...\n     5,  6; ...\n     5,  9; ...\n     5, 11; ...\n     6, 10; ...\n     6, 11; ...\n     7,  8; ...\n     7,  9; ...\n     7, 12; ...\n     8, 10; ...\n     8, 12; ...\n     9, 11; ...\n     9, 12; ...\n    10, 11; ...\n    10, 12; ...\n    11, 12 ]';\n%\n%  Set the face orders.\n%\n  face_order(1:face_num) = [ ...\n    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, ...\n    3, 3, 3, 3, 3, 3, 3, 3, 3, 3 ]';\n%\n%  Set the faces.\n%\n  face_point(1:face_order_max,1:face_num) = [ ...\n     1,  2,  4; ...\n     1,  3,  2; ...\n     1,  4,  6; ...\n     1,  5,  3; ...\n     1,  6,  5; ...\n     2,  3,  7; ...\n     2,  7,  8; ...\n     2,  8,  4; ...\n     3,  5,  9; ...\n     3,  9,  7; ...\n     4,  8, 10; ...\n     4, 10,  6; ...\n     5,  6, 11; ...\n     5, 11,  9; ...\n     6, 10, 11; ...\n     7,  9, 12; ...\n     7, 12,  8; ...\n     8, 12, 10; ...\n     9, 11, 12; ...\n    10, 12, 11 ]';\n\n  return\nend\n", "meta": {"author": "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_quad/icos_shape.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5956707744485197}}
{"text": "function [y,n] = audspacebw(fmin,fmax,varargin)\n%AUDSPACEBW  Auditory scale points specified by bandwidth\n%   Usage: y=audspacebw(fmin,fmax,bw,hitme);\n%          y=audspacebw(fmin,fmax,bw);\n%          y=audspacebw(fmin,fmax);\n%          [y,n]=audspacebw(...);\n%\n%   `audspacebw(fmin,fmax,bw,scale)` computes a vector containing values\n%   equistantly scaled between frequencies *fmin* and *fmax* on the\n%   selected auditory scale.  All frequencies are specified in Hz.The\n%   distance between two consecutive values is *bw* on the selected scale,\n%   and the points will be centered on the scale between *fmin* and *fmax*.\n%\n%   See the help on |freqtoaud| to get a list of the supported values of the\n%   *scale* parameter.\n%  \n%   `audspacebw(fmin,fmax,bw,hitme,scale)` will do as above, but one of\n%   the points is quaranteed to be the frequency *hitme*.\n%\n%   `[y,n]=audspacebw(...)` additionally returns the number of points *n* in\n%   the output vector *y*.\n%\n%   See also: freqtoaud, audspace, audfiltbw\n  \n%   AUTHOR : Peter L. S\u00f8ndergaard\n  \n% ------ Checking of input parameters ---------\n  \nif nargin<2\n  error('%s: Too few input parameters.',upper(mfilename));\nend;\n\nif ~isnumeric(fmin) || ~isscalar(fmin) || fmin<0\n  error('%s: fmin must be a non-negative scalar.',upper(mfilename));\nend;\n\nif ~isnumeric(fmax) || ~isscalar(fmax) || fmax<0\n  error('%s: fmax must be a non-negative scalar.',upper(mfilename));\nend;\n\nif fmin>fmax\n  error('%s: fmin must be less than or equal to fmax.',upper(mfilename));\nend;\n\ndefinput.import={'freqtoaud'};\ndefinput.keyvals.hitme=[];\ndefinput.keyvals.bw=1;\n\n[flags,kv,bw]=ltfatarghelper({'bw','hitme'},definput,varargin);\n\nif ~isnumeric(bw) || ~isscalar(bw) || bw<=0 \n  error('%s: bw must be a positive scalar.',upper(mfilename));\nend;\n\n  \n%% ------ Computation --------------------------\n\nif isempty(kv.hitme)\n  % Convert the frequency limits to auds.\n  audlimits = freqtoaud([fmin,fmax],flags.audscale);\n  audrange  = audlimits(2)-audlimits(1);\n\n  % Calculate number of points, excluding final point\n  n         = floor(audrange/bw);\n\n  % The remainder is calculated in order to center the points\n  % correctly between fmin and fmax.\n  remainder = audrange-n*bw;\n\n  audpoints = audlimits(1)+(0:n)*bw+remainder/2;\n  \n  % Add the final point\n  n=n+1;  \n  \nelse\n    \n  % Convert the frequency limits to auds.\n  audlimits    = freqtoaud([fmin,fmax,kv.hitme],flags.audscale);\n  audrangelow  = audlimits(3)-audlimits(1);\n  audrangehigh = audlimits(2)-audlimits(3);\n\n  % Calculate number of points, exluding final point.\n  nlow = floor(audrangelow/bw);\n  nhigh = floor(audrangehigh/bw);\n  \n  audpoints=(-nlow:nhigh)*bw+audlimits(3);\n  n=nlow+nhigh+1;\nend;\n\ny = audtofreq(audpoints,flags.audscale);\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/auditory/audspacebw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5956707623015514}}
{"text": "function [ r, seed ] = r8vec_uniform_01 ( n, seed )\n\n%*****************************************************************************80\n%\n%% R8VEC_UNIFORM_01 returns a unit pseudorandom R8VEC.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    07 May 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Paul Bratley, Bennett Fox, Linus Schrage,\n%    A Guide to Simulation,\n%    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 N, the number of entries in the vector.\n%\n%    Input, integer SEED, a seed for the random number generator.\n%\n%    Output, real R(N,1), the vector of pseudorandom values.\n%\n%    Output, integer SEED, an updated seed for the random number generator.\n%\n  i4_huge = 2147483647;\n\n  if ( seed == 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8VEC_UNIFORM_01 - Fatal error!\\n' );\n    fprintf ( 1, '  Input SEED = 0!\\n' );\n    error ( 'R8VEC_UNIFORM_01 - Fatal error!' );\n  end\n\n  r = zeros ( n, 1 );\n\n  for i = 1 : n\n\n    k = floor ( seed / 127773 );\n\n    seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n    if ( seed < 0 )\n      seed = seed + i4_huge;\n    end\n\n    r(i,1) = seed * 4.656612875E-10;\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_uniform_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.5956399463430161}}
{"text": "function B = cleanpoly(A,tol,deg)\n% function B = cleanpoly(A,tol,deg)\n%\n% DESCRIPTION\n%   Cleans up the input polynomial.  The output polynomial includes only\n%   terms whose coefficients have magnitude greater than or equal to TOL\n%   and whose monomial degree is specified by DEG.\n%\n% INPUTS\n%   A: polynomial\n%   tol: scalar double specifying the coefficient tolerance\n%   deg: vector of non-negative integers specifying the degrees of\n%        mononmials to retain. Alternatively deg can be an N-by-2\n%        cell array with deg{i,1} specifying a variable and\n%        deg{i,2} specifying a vector of non-negative integers.\n%        This will retain only monomials whose degree in variable\n%        deg{i,1} is specified in deg{i,2}.\n%\n% OUTPUTS\n%   B: polynomial which only contains the terms of A whose coefficients\n%      have magnitude greater than or equal to tol and whose monomial\n%      degree is listed in deg.\n%\n% SYNTAX\n%   B=cleanpoly(A,tol);\n%   B=cleanpoly(A,[],deg);\n%   B=cleanpoly(A,tol,deg);\n%\n% EXAMPLE\n%   pvar x1 x2 u;\n%   p = 9*u^3 + u*x1^2 + 1e-6*u^2*x1*x2 + 1e-5*u*x2^2 + 2*x1^3 ...\n%        - x1*x2 + 3*u + x1 + 2*x2;\n%\n%   % Remove terms whose coefficients has magnitude < tol\n%   tol = 1e-4;\n%   p1 = cleanpoly(p,tol)\n%\n%   % Retain linear and quadratic terms\n%   p2 = cleanpoly(p,[],1:2)\n%\n%   % Retain terms linear in u but of degree 0,1,2,3 in x1 and x2\n%   p3 = cleanpoly(p,[],{x1, 0:3; x2, 0:3; u 1})\n\n% 1/28/2008: PJS  Added option to grab terms of a specified degree\n% 4/22/2009: PJS  Added functionality to specify deg as a cell array\n\nif nargin<3\n    deg = [];\nend\n\nif ~isempty(tol)\n    if isa(tol,'double') && isscalar(tol) && tol>=0\n        Acoef = get(A,'Coefficient');\n        idx = find(abs(Acoef) < tol);\n        if ~isempty(idx)\n            Acoef(idx) = 0;\n            chkval = 0; % skip validity check\n            A=polynomial(Acoef,A.degmat,A.varname,size(A),chkval);\n        end\n    else\n        error('tol must be a non-negative double');\n    end\nend\n\nif ~isempty(deg)\n    \n    if isa(deg,'double') && ndims(deg)==2 && ...\n            all(floor(deg)==ceil(deg)) && all(deg>=0)\n        \n        % deg is a vector of non-negative integers\n        \n        Adeg = sum(A.degmat,2);\n        idx = [];\n        for i1=1:length(deg)\n            %idx=find(Adeg~=deg(i1));\n            idx=[idx; find(Adeg==deg(i1))];\n        end\n        idx = setdiff(1:length(Adeg),idx);\n        \n        Acoef = A.coefficient;\n        Acoef(idx,:) = 0;\n        chkval = 0; % skip validity check\n        A=polynomial(Acoef,A.degmat,A.varname,size(A),chkval);\n        \n    elseif iscell(deg) && ndims(deg)==2 && size(deg,2)==2\n        % deg is a cell array of pvars and vectors of non-neg integers\n        \n        Acoef = A.coefficient;\n        for i1=1:size(deg,1)\n            var = deg{i1,1};\n            if ispvar(var) && all(size(var)==[1 1])\n                var = char(var);\n            elseif ~ischar(var)\n                error('First column of cell array deg must contain strings or pvars');\n            end\n            vidx = find(strcmp(A.varname,var));\n            \n            if ~isempty(vidx)\n                degi = deg{i1,2};\n                if ~( isa(degi,'double') && ndims(degi)==2 && ...\n                        all(floor(degi)==ceil(degi)) && all(degi>=0) )\n                    error(['Second column of cell array deg must '...\n                        'contain a vector of non-negative integers.']);\n                end\n                \n                Adeg = A.degmat(:,vidx);\n                cidx = [];\n                for i2=1:length(degi)\n                    cidx=[cidx; find(Adeg==degi(i2))];\n                end\n                cidx = setdiff(1:length(Adeg),cidx);\n                Acoef(cidx,:) = 0;\n            end\n        end\n        A=polynomial(Acoef,A.degmat,A.varname,size(A));\n    else\n        error('deg must be a vector of non-negative integers or an Nx2 cell array');\n    end\n    \nend\n\n% Combine to remove terms\nB = combine(A);\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/multipoly/@polynomial/cleanpoly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.595639946343016}}
{"text": "%% Plotting Individual Orientations\n% Basics of the plot types for individual orientations data\n%\n%% \n% This section gives an overview over the possibilities that MTEX offers to\n% visualize orientation data. Let us first load a sample EBSD data set\n\nmtexdata forsterite\n\n%%\n% and select all individual orientations of the Iron phase\n\nebsd('Fo').orientations\n\n\n%% Scatter Pole Figure Plot\n% A pole figure showing scattered points of these data figure can be\n% produced by the command <orientation.plotPDF.html plotPDF>.\n\nplotPDF(ebsd('Fo').orientations,Miller(1,0,0,ebsd('Fo').CS))\n\n\n%% Scatter (Inverse) Pole Figure Plot\n% Accordingly, scatter points in inverse pole figures are produced by the\n% command  <orientation.plotIPDF.html plotIPDF>.\n\nplotIPDF(ebsd('Fo').orientations,xvector)\n\n\n%% Scatter Plot in ODF Sections\n% The plotting of scatter points in sections of the orientation space is carried out by the\n% command <orientation.plotSection.html plotSection>. In the above examples, the number\n% of plotted orientations was chosen automatically such that the\n% plots not to become too crowded with points. The number of randomly chosen orientations\n% can be specified by the option *points*.\n\nplotSection(ebsd('Fo').orientations,'points',1000,'sigma','sections',9)\n\n\n%% Scatter Plot in Axis Angle or Rodrigues Space\n% Another possibility is to plot the single orientations directly into the\n% orientation space, i.e., either in axis/angle parameterization or in Rodrigues\n% parameterization.\n\nscatter(ebsd('Fo').orientations)\n\n%%\n% Here, the optional option 'center' specifies the center of the unique\n% region in the orientation space.\n\n\n%% Orientation plots for EBSD and grains\n% Since EBSD and grain data involves single orientations, the above plotting\n% commands are also applicable for those objects.\n\n%%\n% Let us consider some grains <EBSD.calcGrains.html reconstructed> from the\n% EBSD data\n\ngrains = calcGrains(ebsd);\n\n%%\n% Then the scatter plot of the individual orientations of the Iron phase in\n% the inverse pole figure is achieved by\n\nplotIPDF(ebsd('Fo').orientations,xvector,'points',1000, 'MarkerSize',3);\n\n%%\n% In the same way, the mean orientations of grains can be visualized\n\nhold all\nplotIPDF(grains('Fo').meanOrientation,xvector,'points',500, 'MarkerSize',3);\nhold off\n\n%%\n% One can also use different colors on the scatter points\n\nh = [Miller(1,0,0,ebsd('Fo').CS),Miller(1,1,0,ebsd('Fo').CS)];\nplotPDF(ebsd('Fo').orientations,ebsd('Fo').mad,h,'antipodal','MarkerSize',4)\n\n%%\n% or some arbitrary data vector\n\nplotSection(grains('Fo').meanOrientation,log(grains('Fo').area),...\n  'sigma','sections',9,'MarkerSize',10);\n  \n%%\n% See also <PlotTypes_demo.html#5, Scatter plots> for more information\n% about scatter plot and <SphericalProjection_demo.html,spherical\n% projections>  for more information on spherical projections.\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/EBSDOrientationPlots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.5956399461476395}}
{"text": "%% Gabor Filter demo\n%\n% A GUI to interact with the 5 different Gabor filter parameters, while\n% visualizing the resulting filter.\n%\n\nfunction varargout = gabor_filter_gui(ksize)\n    % create the UI\n    if nargin < 1, ksize = [121 121]; end\n    h = buildGUI(ksize);\n    if nargout > 0, varargout{1} = h; end\nend\n\nfunction onChange(~,~,h)\n    %ONCHANGE  Event handler for UI controls\n\n    % retrieve current values from UI controls\n    sigma  = get(h.slid(5), 'Value') / 10;\n    theta  = get(h.slid(4), 'Value') * pi/180;\n    lambda = get(h.slid(3), 'Value');\n    gamma  = get(h.slid(2), 'Value') / 100;\n    psi    = get(h.slid(1), 'Value') * pi/180;\n\n    % create Gabor filter\n    kernel = cv.getGaborKernel('KSize',[h.ksize(2) h.ksize(1)], ...\n        'Sigma',sigma, 'Theta',theta, 'Lambda',lambda, ...\n        'Gamma',gamma, 'Psi',psi);\n\n    % normalize filter to [0,1] range and resize it\n    kernel = cv.normalize(kernel, 'NormType','MinMax');\n    kernel = cv.resize(kernel, [h.sz(2) h.sz(1)]);\n\n    % show result\n    set(h.img, 'CData',kernel)\n    set(h.txt(5), 'String',sprintf('Sigma  = %.2f',sigma))\n    set(h.txt(4), 'String',sprintf('Theta  = %.2f',theta))\n    set(h.txt(3), 'String',sprintf('Lambda = %.2f',lambda))\n    set(h.txt(2), 'String',sprintf('Gamma  = %.2f',gamma))\n    set(h.txt(1), 'String',sprintf('Psi    = %.2f',psi))\n    drawnow\nend\n\nfunction onType(~,e,h)\n    %ONTYPE  Event handler for key press on figure\n\n    % handle keys\n    switch e.Key\n        case {'q', 'escape'}\n            close(h.fig)\n            return\n        case 'h'\n            onHelp([],[]);\n        case 'r'\n            onReset([],[],h);\n    end\nend\n\nfunction onReset(~,~,h)\n    set(h.slid(5), 'Value',400);    % sigma\n    set(h.slid(4), 'Value',0);      % theta\n    set(h.slid(3), 'Value',11);     % lambda\n    set(h.slid(2), 'Value',100);    % gamma\n    set(h.slid(1), 'Value',90);     % psi\n    onChange([],[],h);\nend\n\nfunction onHelp(~,~)\n    %ONHELP  Display usage help dialog\n\n    helpdlg({\n        'This GUI allows to interact with the 5 different Gabor filter'\n        'parameters, while visualizing the resulting filter.'\n        ''\n        'Hot keys:'\n        'ESC, q - quit the program'\n        'r - reset parameters to original values'\n        'h - this help dialog'\n    });\nend\n\nfunction h = buildGUI(ksize)\n    %BUILDGUI  Creates the UI\n\n    % parameters\n    sigma = 400; sigma_max = 1000;\n    theta = 0;   theta_max = 180;\n    lambda = 11; lambda_max = 100;\n    gamma = 100; gamma_max = 200;\n    psi = 90;    psi_max = 180;\n    sz = [512 512];\n\n    % build the user interface (no resizing to keep it simple)\n    h = struct();\n    h.ksize = ksize;  % size of the filter\n    h.sz = sz;        % size of the image to show\n    h.fig = figure('Name','Gabor Filter Demo', ...\n        'NumberTitle','off', 'Menubar','none', 'Resize','off', ...\n        'Position',[200 200 sz(2) sz(1)+129]);\n    if ~mexopencv.isOctave()\n        %HACK: not implemented in Octave\n        movegui(h.fig, 'center');\n    end\n    h.ax = axes('Parent',h.fig, 'Units','pixels', 'Position',[1 130 sz(2) sz(1)]);\n    if ~mexopencv.isOctave()\n        h.img = imshow(zeros(sz), 'Parent',h.ax);\n    else\n        %HACK: https://savannah.gnu.org/bugs/index.php?45473\n        axes(h.ax);\n        h.img = imshow(zeros(sz));\n    end\n    text(5, 5, sprintf('KSize = %dx%d', ksize(2), ksize(1)), ...\n        'Color','y', 'VerticalAlignment','top');\n\n    props = {'Parent',h.fig, 'Style','text', 'String','', ...\n        'FontSize',11, 'HorizontalAlignment','left'};\n    h.txt(5) = uicontrol(props{:}, 'Position',[5   5 120 20]);\n    h.txt(4) = uicontrol(props{:}, 'Position',[5  30 120 20]);\n    h.txt(3) = uicontrol(props{:}, 'Position',[5  55 120 20]);\n    h.txt(2) = uicontrol(props{:}, 'Position',[5  80 120 20]);\n    h.txt(1) = uicontrol(props{:}, 'Position',[5 105 120 20]);\n\n    props = {'Parent',h.fig, 'Style','slider', 'Min',0};\n    h.slid(5) = uicontrol(props{:}, 'Position',[125   5 sz(2)-125-5 20], ...\n        'Value',sigma, 'Max',sigma_max, 'SliderStep',[10 100]./(sigma_max-0));\n    h.slid(4) = uicontrol(props{:}, 'Position',[125  30 sz(2)-125-5 20], ...\n        'Value',theta, 'Max',theta_max, 'SliderStep',[2 20]./(theta_max-0));\n    h.slid(3) = uicontrol(props{:}, 'Position',[125  55 sz(2)-125-5 20], ...\n        'Value',lambda, 'Max',lambda_max, 'SliderStep',[1 10]./(lambda_max-0));\n    h.slid(2) = uicontrol(props{:}, 'Position',[125  80 sz(2)-125-5 20], ...\n        'Value',gamma, 'Max',gamma_max, 'SliderStep',[2 20]./(gamma_max-0));\n    h.slid(1) = uicontrol(props{:}, 'Position',[125 105 sz(2)-125-5 20], ...\n        'Value',psi, 'Max',psi_max, 'SliderStep',[2 20]./(psi_max-0));\n\n    % hook event handlers, and trigger default start\n    opts = {'Interruptible','off', 'BusyAction','cancel'};\n    set(h.slid, 'Callback',{@onChange,h}, opts{:});\n    set(h.fig, 'WindowKeyPressFcn',{@onType,h}, opts{:});\n    onChange([],[],h);\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/gabor_filter_gui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.5956399423897647}}
{"text": "function box = intersectBoxes3d(box1, box2)\n%INTERSECTBOXES3D Intersection of two 3D bounding boxes\n%\n%   RES = intersectBoxes3d(BOX1, BOX2)\n%\n%   Example\n%   box1 = [5 20 5 30 10 50];\n%   box2 = [0 15 0 15 0 20];\n%   intersectBoxes3d(box1, box2)\n%   ans = \n%       5 15 5 15 10 20\n%\n%   See also\n%   boxes3d, drawBox3d, mergeBoxes3d\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-07-26,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% unify sizes of data\nif size(box1,1) == 1\n    box1 = repmat(box1, size(box2,1), 1);\nelseif size(box2, 1) == 1\n    box2 = repmat(box2, size(box1,1), 1);\nelseif size(box1,1) ~= size(box2,1)\n    error('Bad size for inputs');\nend\n\n% compute extreme coords\nmini = min(box1(:,2:2:end), box2(:,2:2:end));\nmaxi = max(box1(:,1:2:end), box2(:,1:2:end));\n\n% concatenate result into a new box structure\nbox = [maxi(:,1) mini(:,1) maxi(:,2) mini(:,2) maxi(:,3) mini(:,3)];\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/geom3d/intersectBoxes3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.5956399384365136}}
{"text": "function n = normalDirection(L)\n% normal direction\n\n[~,~,n] = svd(matrix(L));\n\nn = vector3d(n(:,1));", "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/@velocityGradientTensor/normalDirection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5956377442029175}}
{"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: Unified Solutions, \n%           Solvability/Observability Analysis and Uncertainty Description \n%           in A Globally Optimal Framework.\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\nfunction [XX, ff] = optimize_quat_cov2(q, F, cov_left, solver, verbose)\nif(~strcmp(solver, 'scs'))\n    X = sdpvar(4, 4);\n    f = q.' * X * q;\n    cons = [\n        X >= 0, ...\n        sym2vec3(F * X * F.') == sym2vec3(cov_left)\n        ];\n    options = sdpsettings('solver', solver, 'verbose', verbose);\n    if(strcmp(solver, 'sdpa_gmp'))\n        options.sdpa_gmp.epsilonDash = 1.0e-35;\n        options.sdpa_gmp.precision = 250;\n    end\n    optimize(cons, f, options);\n    XX = value(X);\n    ff = value(f);\nelse\n    cvx_solver scs\n    cvx_precision high\n    \n    cvx_begin sdp\n         variable X(4,4) symmetric semidefinite\n         dual variable Q\n         minimize(q.' * X * q)\n         X >= 0 * eye(4) : Q\n         subject to\n             sym2vec3(F * X * F.') == sym2vec3(cov_left)\n    cvx_end\n    XX = real(X);\n    ff = 0;\nend\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/utils/optimize_quat_cov2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5956377408177466}}
{"text": "function [x, infos] = kl_bmd_nmf(V, rank, in_options)\n% Block mirror descent method for KL-based non-negative matrix factorization (KL-BMD-NMF).\n%\n% The problem of interest is defined as\n%\n%           min f(V, W, H),\n%           where \n%           {V, W, H} >= 0.\n%\n% Given a non-negative matrix V, factorized non-negative matrices {W, H} are calculated.\n%\n%\n% Inputs:\n%       V           : (m x n) non-negative matrix to factorize\n%       rank        : rank\n%       in_options \n%\n% Output:\n%       x           : non-negative matrix solution, i.e., x.W: (m x rank), x.H: (rank x n)\n%       infos       : log information\n%           epoch   : iteration nuber\n%           cost    : objective function value\n%           optgap  : optimality gap\n%           time    : elapsed time\n%           grad_calc_count : number of sampled data elements (gradient calculations)\n%\n%\n% This file is part of NMFLibrary\n%\n% This file has been ported from \n% BMD.m at https://github.com/LeThiKhanhHien/KLNMF written originally by LTK Hien.\n%\n% Ported by H.Kasai on June 28, 2022\n%\n% Change log: \n%\n%       Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n    % set dimensions and samples\n    [m, n] = size(V);\n \n    % set local options\n    local_options = [];\n    local_options.metric.type   = 'kl-div';\n    local_options.myeps         = 1e-16;    \n    \n    % check input options\n    if ~exist('in_options', 'var') || isempty(in_options)\n        in_options = struct();\n    end      \n    % merge options\n    options = mergeOptions(get_nmf_default_options(), local_options);   \n    options = mergeOptions(options, in_options);        \n\n    % initialize factors\n    init_options = options;\n    [init_factors, ~] = generate_init_factors(V, rank, init_options);    \n    W = init_factors.W;\n    H = init_factors.H;      \n    \n    % initialize\n    method_name = 'KL-BMD';    \n    epoch = 0;    \n    grad_calc_count = 0;\n\n    if options.verbose > 0\n        fprintf('# %s: started ...\\n', method_name);           \n    end       \n\n    % initialize for this algorithm\n    lambdaH = (1./(sum(V))); % the row which is the sum of columns of X\n    lambdaH = repmat(lambdaH, rank, 1);\n    lambdaW = (1./(sum(V,2)))';\n    lambdaW = repmat(lambdaW, rank , 1);    \n    \n    % store initial info\n    clear infos;\n    [infos, f_val, optgap] = store_nmf_info(V, W, H, [], options, [], epoch, grad_calc_count, 0);\n    \n    if options.verbose > 1\n        fprintf('KL-BMD: Epoch = 0000, cost = %.16e, optgap = %.4e\\n', f_val, optgap); \n    end  \n\n    % set start time\n    start_time = tic();\n\n    % main loop\n    while true\n        \n        % check stop condition\n        [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n        if stop_flag\n            display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n            break;\n        end      \n\n        % update H\n        rj = sum(W)';\n        rjc = repmat(rj, 1, n);\n        bAv = V./(W*H+eps);\n        cj = W' * bAv; \n        H = H ./ (1 + (lambdaH .* H) .* (rjc - cj));\n        H = H + (H<options.myeps) .* options.myeps;        \n       \n        % update W\n        rj = sum(H, 2);\n        rjc = repmat(rj, 1, m);\n        bAv = V' ./ (H' * W' + eps);\n        cj = H * bAv; \n        Wt = W' ./ (1 + (lambdaW .* W') .* (rjc - cj));\n        W = Wt';\n        W = W + (W<options.myeps) .* options.myeps;         \n        \n        % measure elapsed time\n        elapsed_time = toc(start_time);        \n        \n        % measure gradient calc count\n        grad_calc_count = grad_calc_count + m*n;\n\n        % update epoch\n        epoch = epoch + 1;         \n        \n        % store info\n        infos = store_nmf_info(V, W, H, [], options, infos, epoch, grad_calc_count, elapsed_time);  \n        \n        % display info\n        display_info(method_name, epoch, infos, options);\n\n    end\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/divergence/kl_bmd_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.6959583250334527, "lm_q1q2_score": 0.5956367409566442}}
{"text": "function [cu, cv, cx, cz, footprint, feat] = poly2contacts(dt, u, v, imsize, v0, yc, f, minp, im)\n\nif ~exist('minp', 'var')\n    minp = 0.5;\nend\n\nimh = imsize(1);\nimw = imsize(2);\n\nif isempty(f)\n    f = 1.38; %S*max(size(im)) / imh;\nend\n\nu = u(:)'; \nv = v(:)';\nif exist('im', 'var')\n    figure(1), hold off, imshow(im), hold on    \n    plot([u(:) ; u(1)]', [v(:) ; v(1)]', '-b');\nend\n\n[tmp, ind] = min(u);\nu = [u(ind:end)  u(1:ind-1)];\nv = [v(ind:end)  v(1:ind-1)];\n\nu = (u - imw/2) ./ imh;\nv = 1 - (v ./ imh);\n\nif exist('im', 'var')\n    figure(1), plot(u*imh+imw/2, (1-v)*imh, '-g')\nend\ncind = convhull(u*imh+imw/2, (1-v)*imh);\nif exist('im', 'var')\n    figure(1), plot(u(cind)*imh+imw/2, (1-v(cind))*imh, '-y')\nend\n\n[v1, ind1] = min(v); % lowest point on object in image\n\n[footx, footz] = computeGroundPosition([min(u) max(u)], [v1 v1], v0, yc, f);\nfootz(2) = footz(1) + footx(2)-footx(1);\n\n[cx, cz] = computeGroundPosition(u, v, v0, yc, f);\n\ndata.u = (u*imh+imw/2)';\ndata.v = ((1-v)*imh)';\ndata.x3d = cx;\ndata.z3d = cz;\ndata.foot = [footx footz];\n\nfeat = contactdata2features(data);\n\n[b, nodes] = treeval(dt, feat);\n\nb = b - 1;\n\nind = dt.classprob(nodes, 2)>minp;%(b==1);\n\ncu = u(ind)*imh+imw/2;\ncv = (1-v(ind))*imh;\ncz = cz(ind);\ncx = cx(ind);\nfootprint = data.foot;\n\nif exist('im', 'var')\n    figure(1), plot(cu, cv, '*r')\n    figure(1), plot([1 1000], (1-v0)*imh*ones(1,2), '-b');\nend\n%keyboard\n% get how many points are in the footprint\n%figure(2), plot(cx, cz, '*'), axis equal\n\n\n%disp(num2str([cx ; cz]))\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [x, z] = computeGroundPosition(u, v, v0, yc, f)\n\nz = yc*f./max((v0-v), 0.001);\nx = u.*z./f;\n    ", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/iccv07Final/src/poly2contacts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5956367386772835}}
{"text": "% IndexToAssignment Convert index to variable assignment.\n%\n%   A = IndexToAssignment(I, D) converts an index, I, into the .val vector\n%   into an assignment over variables with cardinality D. If I is a vector, \n%   then the function produces a matrix of assignments, one assignment \n%   per row.\n%\n%   See also AssignmentToIndex.m and SampleFactors.m\n\nfunction A = IndexToAssignment(I, D)\n\nD = D(:)'; % ensure that D is a row vector\nA = mod(floor(repmat(I(:) - 1, 1, length(D)) ./ repmat(cumprod([1, D(1:end - 1)]), length(I), 1)), ...\n        repmat(D, length(I), 1)) + 1;\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/2.Bayesian Network for Genetic Inheritance/IndexToAssignment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5956367361184456}}
{"text": "function [g,dgdx,dgdp] = g_conv0(x,P,u,in)\n% this function evaluates a linear convolution of the inputs\n% function [gx,dgdx,dgdp] = g_conv0(x,P,u,in)\n% This function evaluates the following multiple convolution model:\n%   y(t) = cst + sum_k sum_tau w(k,tau)*u(k,t-tau)\n% where u can be of any dimension (k=1,...,K).\n% Note that the convolution (Volterra) kernels are constructed from the\n% parameters' vector P. The size of the parameters' vector P is determined\n% by the maximum lag (tau) considered.\n% IN:\n%   - x: [useless]\n%   - P: (K*maxLag+1)x1 vector of kernel parameters.\n%   - u: (K*nt)x1 vectorized input to the system\n%   - in: [useless]\n% OUT:\n%   - g: the predicted system's output\n%   - dgdx: [useless]\n%   - dgdp: the gradient of the system's output w.r.t. kernel parameters\n% SEE ALSO: g_convSig\nif ~ isfield (in, 'K')\n    in.K = 0;\nend\n\ntry\n    dgdp = in.dgdp;\ncatch\n    nt = size(u,1)/in.dim.nu;\n    dgdp = zeros(size(P,1),nt);\n    for i=1:in.dim.nu\n        ui = u((i-1)*nt+1:i*nt);\n        for j=1:nt\n            if j<=in.dim.n_t\n                dgdp((i-1)*in.dim.n_t+j,:) = circshift(ui',[0,j-1]);\n                dgdp((i-1)*in.dim.n_t+j,1:j-1) = 0;\n            end\n        end\n    end\n    dgdp(end,:) = 1;\nend\ng = dgdp'*P + in.K;\ndgdx = [];\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/g_conv0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5956367258830936}}
{"text": "function [xf,wftilda,wftilda2,wftilda3]=pfilterj(a,b,c,d,g,h,lambda,X0,y)\nT=length(y);\nn=length(X0);\nxf(:,1)=X0;\nwftilda(:,1)=1/n*ones(n,1);\nfor t=2:T\nxf(:,t)=gaussmix(mx(a,xf(:,t-1)),b,mx([a,g],xf(:,t-1)),sqrt(1+h)*b,lambda);\n%Compute and normalize filter weights\nwf(:,t)=normpdf(y(t),my(c,xf(:,t)),d);\n%Ensures a nonzero summation in denominator\n[n1,val]=zerotest(y(t),my(c,xf(:,t)),wf(:,t));\nwf(n1,t)=val;\nwftilda(:,t)=wf(:,t)/sum(wf(:,t));\nend\n\nfor i=1:n\nwf3(i,T)=wftilda(i,T)*weight(xf(i,T),xf(:,T),wftilda(i,T),wftilda(:,T),i,a,b,g,h,lambda);\nend\nwftilda3(:,T)=wf3(:,T)/sum(wf3(:,T));\n\nfor t=T-1:-1:1\n%Compute joint smoother weight p(x(t),x(t+1)|Y) and p(x(t),x(t)|Y)\nfor i=1:n\nwf2(i,t)=wftilda(i,t)*weight(xf(i,t+1),xf(:,t),wftilda(i,t+1),wftilda(:,t),i,a,b,g,h,lambda);\nwf3(i,t)=wftilda(i,t)*weight(xf(i,t),xf(:,t),wftilda(i,t),wftilda(:,t),i,a,b,g,h,lambda);\nend\n\n%Ensures a nonzero summation in denominator\nif sum(wf2(:,t))==0;\nwftilda2(:,t)=1/n*ones(n,1);\nelse\nwftilda2(:,t)=wf2(:,t)/sum(wf2(:,t));\nend\n\nif sum(wf3(:,t))==0;\nwftilda3(:,t)=1/n*ones(n,1);\nelse\nwftilda3(:,t)=wf3(:,t)/sum(wf3(:,t));\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/29723-particle-smoothing-expectation-maximization-procedure/GaussianMixtureModel-2/pfilterj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5956367253241406}}
{"text": "function A = meanDiscrete(s, hyp, x, i)\n\n% Mean function for discrete inputs x. Given a function defined on the\n% integers 1,2,3,..,s, the mean function is parametrized as:\n%\n% m(x) = mu_x,\n%\n% where mu is a fixed vector of length s.\n%\n% This implementation assumes that the inputs x are given as integers\n% between 1 and s, which simply index the provided vector.\n%\n% The hyperparameters are:\n%\n% hyp = [ mu_1\n%         mu_2\n%         ..\n%         mu_s ]\n%\n% Copyright (c) by Roman Garnett, 2014-08-14.\n%\n% See also COVDISCRETE.M, MEANFUNCTIONS.M.\n\nif nargin==0, error('s must be specified.'), end           % check for dimension\nif nargin<=2, A = num2str(s); return; end     % report number of hyperparameters\nmu = hyp(:);\nif nargin==3\n  A = mu(x(:));                                                  % evaluate mean\nelse\n  A = zeros(numel(x),1);                                            % derivative\n  A(x==i) = 1;\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/mean/meanDiscrete.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5956367150887886}}
{"text": "function demo_designOptimization ()\n% // VBA toolbox //////////////////////////////////////////////////////////\n%\n% [posterior, out] = demo_designOptimization ()\n% demo of off-line and online design optimisation\n%\n% This demo simulates a psychophysics paradigm similar to a signal\n% detection task, whereby the detection probability is a sigmoidal function\n% of the stimulus contrast (which is the design control variable).\n% Our goal is to estimate  the inflexion point (detection threshold) and the\n% sigmoid steepness (d prime) or the response function.\n% In order to provide the most efficient estimate of these model parameters,\n% we will show how to use offline (before the experiment) and online \n% (during the experiment) design optimization to decide given trial-by-trial \n% subjects' binary choice data (seen/unseen) which stimulus to show next.\n%\n% /////////////////////////////////////////////////////////////////////////\n\n%% Global values\n% =========================================================================\n\n% number of trials for the respective simulations\nN = 50; \n\n% true parameter values for the simulations \nphi = [- .5; 2.5]; % simulated parameters: [inflexion point, log-slope]\n\n% range of potential simuli\nuRange = linspace(- 1, 1, N);\n\n% prepare display\nVBA_figure('Name', 'demo_designOptimisation');\n\n%% Define the model\n% =========================================================================\n\n% observation function \n% -------------------------------------------------------------------------\nfunction [gx, dgdx, dgdp] = g_psychometric (~, phi, u, ~)\n    % tip: VBA_sigmoid returns derivatives wrt parameters in alphabetical\n    % order, ie. center -> slope.\n    [gx, ~, dgdp] = VBA_sigmoid (u,...\n    'center', phi(1), ...\n    'slope', exp (phi(2)) ...\n    );\n    dgdp(2,:) = dgdp(2,:) * exp (phi(2));\n    dgdx = [];\nend\n\n% dimensions\n% -------------------------------------------------------------------------\ndim.n_phi = 2;\ndim.n_t = 1;\ndim.p = N;\n\n% general options\n% -------------------------------------------------------------------------\n% binary observations  \noptions.sources.type = 1; \n\n% no display\noptions.DisplayWin = 0;\noptions.verbose = 0;\n\n%% 1) No optimisation\n% =========================================================================\n% here, we'll use the most naive approach, a full swipe of all possible \n% stimulus intensities\n\n% experimental design\n% -------------------------------------------------------------------------\nu = uRange';\n\n% simulate responses\n% -------------------------------------------------------------------------\ny = VBA_simulate (1,[],@g_psychometric,[],phi,u,[],[],options); \n\n% estimate parameters\n% -------------------------------------------------------------------------\nposterior_naive = VBA_NLStateSpaceModel (y,u,[],@g_psychometric,dim,options);\n\n% display results\n% -------------------------------------------------------------------------\nplot_design(1, 'no optimisation', u, y, posterior_naive);\n\n%% 2) Offline optimisation\n% =========================================================================\n% Here, we will try to find a better design before running the experiment\n\n% experimental design\n% -------------------------------------------------------------------------\n% number of designs to try\nnAttempts = 1e4;\n\n% initialization\nfprintf('Offline optimisation: optimizing (  0%%)');\nefficiency_offOpt = - Inf;\nefficiencyDesign = nan(1, nAttempts);\nkeepDesign = [1];\n\n% loop over designs\nfor attempt = 1 : nAttempts\n    \n    % draw random design\n    u_attempt = uRange(randi (numel (uRange), 1, N))';\n        \n    % estimate efficiency\n    efficiencyDesign(attempt) = VBA_designEfficiency([],@g_psychometric,dim,options,u_attempt,'parameters');\n\n    % if better, store and display\n    if efficiencyDesign(attempt) > efficiency_offOpt \n        efficiency_offOpt = efficiencyDesign(attempt);\n        u = sort(u_attempt);\n        keepDesign(end+1) = attempt;\n    end\n    \n    if efficiencyDesign(attempt) > efficiency_offOpt || mod(attempt, 50) == 0\n        plot_design(2, 'offline optimisation', u, y, [], [], efficiencyDesign(keepDesign));\n    end\n    \n    % progress bar\n    fprintf('\\b\\b\\b\\b\\b%3d%%)', round(100* attempt / nAttempts));\nend\n\n% simulate responses\n% -------------------------------------------------------------------------\ny = VBA_simulate (1,[],@g_psychometric,[],phi,u,[],[],options); \n\n% estimate parameters\n% -------------------------------------------------------------------------\nposterior_offline = VBA_NLStateSpaceModel (y,u,[],@g_psychometric,dim,options);\n\n% display results\n% -------------------------------------------------------------------------\nplot_design(2, 'offline optimisation', u, y, posterior_offline);\n\n%% 3) Online optimisation\n% =========================================================================\n% Here, we will optimize the design during the experiment by taking into\n% account trial-by-trial subject's responses to adaptively select the next\n% best stimulus to present\n\n% initialization\nopt = options;\nu = nan(N, 1);\nefficiencyInput = nan(1, length (uRange));\nefficiencyDesign = nan(1, length (uRange));\n\n% run experiment\nfor t = 1 : N\n    \n    % extend design\n    % ---------------------------------------------------------------------\n    % start from current posterior belief\n    try\n        opt.priors = posterior_online;\n    end\n        \n    % compute efficiency of potential stimuli\n    dim.p = 1;\n    for i = 1 : length (uRange)\n        efficiencyInput(i) = VBA_designEfficiency([],@g_psychometric,dim,opt,uRange(i),'parameters');\n    end\n    \n    % find best next stimulus to present\n    [efficiencyDesign(t), idxMaxEff] = max (efficiencyInput);\n    u(t) = uRange(idxMaxEff);\n\n    % simulate 1 responses\n    % ---------------------------------------------------------------------\n    y(t) = VBA_simulate (1,[],@g_psychometric,[],phi,u(t),Inf,[],options);\n    \n    % estimate parameters given data acquired so far\n    % ---------------------------------------------------------------------\n    dim.p = t;\n    posterior_online = VBA_NLStateSpaceModel(y(1:t),u(1:t),[],@g_psychometric,dim,options);\n\n    % display\n    % ---------------------------------------------------------------------\n    plot_design(3, 'online optimisation', u, y, posterior_online, efficiencyInput, efficiencyDesign);\n\nend\n\n% display\n% ---------------------------------------------------------------------  \nplot_design(3, 'online optimisation', u, y, posterior_online);\n\n%% show results\n% =========================================================================\n\nfprintf('\\nSimulation results:\\n');\n\ndisp (table ( ...\n    phi, ...\n    posterior_naive.muPhi, ...\n    posterior_offline.muPhi, ...\n    posterior_online.muPhi, ...\n    'RowNames', {'center','slope'}, ...\n    'VariableNames',{'true','naive','offline','online'}));\n\n%% ########################################################################\n%  display subfunction\n%  ########################################################################\n\nfunction plot_design(idx, titleTxt, u, y, posterior, uEfficiency, dEfficiency)\n        \n    % jitter for data display\n    persistent jitter;\n    if isempty(jitter)\n        jitter = 0.1 * (rand(N,1)-0.5);\n    end\n\n    % experimental design \n    subplot(4,3,idx)\n    \n    if nargin > 5 && ~ isempty (uEfficiency)% if efficiency given\n        \n        [ax,h1,h2] = plotyy(u,10,uRange,uEfficiency,@myHistogram,@myPlot);\n         xlim([uRange(1)-0.05, uRange(end)+0.05]);\n         set(get(ax(1), 'YLabel'), 'String', 'freq. of presentation')\n         set(get(ax(2), 'YLabel'), 'String', 'efficiency')\n         set(ax(1),'YLim', [0 0.4],'YTick',0:.2:.4)       \n         xlabel('stimulus intensity')\n         box off\n\n    else\n        \n     % show stimuli density\n     histogram(u, 10, 'EdgeColor','none','FaceColor',[.3 .3 .4],'Normalization','probability');\n     xlim([uRange(1)-0.05, uRange(end)+0.05])\n     ylim([0 0.4])\n     xlabel('stimulus intensity')\n     ylabel('freq. of presentation')\n     box off\n    end\n     % show type of optimisation\n     VBA_title(gca,titleTxt);\n       \n    if nargin > 6 % if efficiency given\n        subplot(4,3,3+idx)\n        plot(dEfficiency);\n        xlim([1 numel(dEfficiency)])\n        ylim([1.1*min(dEfficiency) 0])\n        switch idx\n            case 2\n                xlabel('selected design');\n            case 3\n                xlabel('trial');\n        end\n\n        ylabel('efficiency');\n        box off\n    end\n\n     % show results if any\n     if ~isempty(posterior)\n         \n        % + observations\n        \n        subplot(4,3,6+idx)\n        % predictions\n        opt_plot = options;\n        opt_plot.priors = posterior;\n        dim_opt = dim;\n        dim_opt.p = numel(uRange);\n        muy = VBA_getLaplace(uRange',[],@g_psychometric,dim_opt,opt_plot);\n        plot(uRange,muy,'r','LineWidth',2);\n        % true model\n        hold on\n        plot(uRange,g_psychometric([],phi,uRange),'Color',[0 .8 0],'LineWidth',2);\n        % data\n        plot(u,y+jitter(1:numel(y)),'.k');\n        \n        % options\n        ylim([-0.1 1.1])\n        xlim([uRange(1)-0.05, uRange(end)+0.05])\n        xlabel('stimulus intensity')\n        ylabel('prob. of detection')\n        hold off\n        box off\n        if idx == 1\n            text(.2,.6,'true model','Color',[0 .8 0]);\n            text(.2,.4,'observations','Color','k');\n            text(.2,.2,'predicted','Color','r');\n        end\n     \n        % + parameters\n\n        subplot(4,3,9+idx);\n        \n        % posterior estimates\n        plotUncertainTimeSeries(posterior.muPhi,sqrt(diag(posterior.SigmaPhi)),[],gca);\n        % true values\n        hold on\n        plot(phi,'o','MarkerFaceColor',[0 .8 0], 'MarkerEdgeColor',[0 .8 0]);\n        % options\n        set(gca,'XTickLabel',{'center','slope'})\n        ylim([-2 4])\n        xlabel('parameter')\n        ylabel('posterior estimate')\n        hold off\n        box off\n    end\n    \n    drawnow\nend\n\n    function h = myHistogram (x,y)\n        h = histogram(x,y,'EdgeColor','none','FaceColor',[.3 .3 .4],'Normalization','probability');\n    end\n\n    function h = myPlot (x,y)\n        h = plot(x,y);\n        hold on\n        [mE, iE] = max (y);\n        plot(uRange(iE),mE,'o','MarkerFaceColor',[.3 .3 .3],'MarkerEdgeColor',[.3 .3 .3])\n        hold off\n    end\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/demos/1_advanced/demo_designOptimization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.7057850340255387, "lm_q1q2_score": 0.5956085392123287}}
{"text": "% ------------------------------------------------------------------------ \n%  Copyright (C)\n%  Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain\n% \n%  Jordi Pont-Tuset <jordi.pont@upc.edu>\n%  June 2013\n% ------------------------------------------------------------------------ \n\n%% Dummy dummy\nlp = [ 1  1  1\n       2  3  2\n       2  2  2];\nms_matrix = [ 1  2  4\n              3  4  5];\n\n cands     = [1 2];\n[cands_hf] = hole_filling(lp, ms_matrix, cands);\nassert(isequal(cands_hf,[1 2 3]))\n\n\n%% Dummy\nlp = [ 1  2  3  4  5\n       6  7  8  9 10\n      11 12 13 14 15\n      16 17 18 19 20];\n  \n    % 21 21 21 21 24\n    % 22 25 25 21 24\n    % 22 26 26 23 24\n    % 23 23 23 23 24\nms_matrix = [ 1  2  3  4  9 21\n              6 11  0  0  0 22\n             16 17 18 19 14 23\n             10 15  5 20  0 24\n              7  8  0  0  0 25\n             12 13  0  0  0 26\n             22 23 24  0  0 27\n             26 27  0  0  0 28\n             21 25  0  0  0 29\n             28 29  0  0  0 30];\n\n cands     = [21 22 23];\n[cands_hf, cands_comp] = hole_filling(lp, ms_matrix, cands);\nassert(isequal(cands_hf  ,[21 22 23 25 26]))\nassert(isequal(cands_comp,24))\n\n\n cands2     = [21 22 23 24 25];\n[cands_hf, cands_comp] = hole_filling(lp, ms_matrix, cands2);\nassert(isequal(cands_hf  ,[21 22 23 24 25 26]))\nassert(isequal(cands_comp,30))\n\n cands3    = [1 2 3];\n[cands_hf, cands_comp] = hole_filling(lp, ms_matrix, cands3);\nassert(isequal(cands_hf  ,[1 2 3]))\nassert(isequal(cands_comp,[4 9 25 28]))\n\n%% Real test\nim_id = '2008_000009';\nload(fullfile(root_dir,'datasets','pascal2012','gPb_mUCM','multi', [im_id '.mat']));\n\ncurr_hier = ucm2hier(ucm2);\nths{1}.start_ths = curr_hier.start_ths';\nths{1}.end_ths = curr_hier.end_ths';\nms{1} = curr_hier.ms_matrix;\nlps = curr_hier.leaves_part;\n            \n[f_lp,f_ms,cands] = full_cands_from_hiers(lps,ms,ths,[500 500 500 500]');\n\ntic\n[cands_hf, cands_comp] = hole_filling(double(f_lp), double(f_ms), cands);\ntoc\n\ntic\n% Get masks\nmasks    = cands2masks(cands, f_lp, f_ms);\nmasks_hf2= false(size(masks));\n\n% Perform hole filling by morphology\nfor ii=1:size(masks,3)\n    masks_hf2(:,:,ii) = (imfill(masks(:,:,ii),'holes')>0);\nend\ntoc\n\n% Is equal?\nmasks_hf = cands2masks(cands_hf, f_lp, f_ms);\nassert(isequal(masks_hf,masks_hf2))\n\n% Was there any hole?\nassert(~isequal(masks_hf,masks))\n\n% Check complementaries\nn_regs = f_ms(end,end);\nmasks_comp = cands2masks(cands_comp, f_lp, f_ms);\nfor ii=1:size(masks,3)\n    if isequal(cands_comp(ii),n_regs)\n        assert(unique(masks_hf(:,:,ii))==1)\n    else\n        tmp = double(masks_comp(:,:,ii))+double(masks_hf(:,:,ii));\n        assert(unique(tmp)==1)\n    end\nend\n\n%% Show some results\n% id = 2000;\n% figure;\n% subplot(1,3,1);imshow(masks(:,:,id)>0)\n% subplot(1,3,2);imshow(masks_hf(:,:,id)>0)\n% subplot(1,3,3);imshow(masks_comp(:,:,id)>0)\n\n", "meta": {"author": "s-gupta", "repo": "rcnn-depth", "sha": "7a7baf7dcccc6fdf6be7c13d16828064d89dff4e", "save_path": "github-repos/MATLAB/s-gupta-rcnn-depth", "path": "github-repos/MATLAB/s-gupta-rcnn-depth/rcnn-depth-7a7baf7dcccc6fdf6be7c13d16828064d89dff4e/mcg/src/tests/test_hole_filling.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5956085287673925}}
{"text": "function [cellU, S, cellV] = separableFormat(A, xorder, yorder, domain)\n%SEPARATBLEFORMAT  Compute separable expression for a linear PDO.\n%\n% Calculate a separable representation of a partial differential \n% operator. These representations can then be using to derive a 2D spectral\n% method from 1D ideas.  The linear PDO can have variable coefficients. \n%\n% This uses the tensor-train decomposition and Proposition\n% 4.2 from [1].\n% \n% [1] A. Townsend and S. Olver, The automatic solution of partial differential\n% equations using a global spectral method, submitted, 2014. \n% \n% Author: Alex Townsend September 2014.\n\nif ( nargin == 1 )\n    N = A; \n    A = N.coeffs; \n    xorder = N.xorder; \n    yorder = N.yorder; \n    domain = N.domain; \nend\n\n% Loop over coefficients of A. Find coefficient of highest degree. We will \n% need this to recover the variable coefficients:  \nn = 10; \nfor jj = 1:size(A, 1) \n    for kk = 1:size(A, 2); \n        if ( isa(A{jj,kk}, 'chebfun2') )\n            [xdeg, ydeg] = length(A{jj,kk});    % get degrees \n            n = max([xdeg, ydeg, n]) + 1;       % take maximum degree we find\n        end\n    end\nend\n\n% Set up Chebyshev points that we need:  \nx = chebpts(xorder+1); \ns = chebpts(n, domain(1:2)); \ny = chebpts(yorder+1); \nt = chebpts(n, domain(3:4)); \n[xx, ss, yy, tt] = ndgrid(x, s, y, t); \n[newx, newy] = meshgrid(s, t); \n\n% We need to apply Proposition 4.2 from [1]. Use the linear operator \n% T motivated by umbral calculus. That is, convert \n% \n%       d^j/dx^j-> x^j \n%       d^j/dy^j-> y^j\n%         x     -> s\n%         y     -> t \n% We obtain a function of 4 variables, H(x,s,y,t). See [1]. \nH = @(x,s,y,t) 0*x;\nfor jj = 1:size(A, 1)\n    for kk = 1:size(A, 2)\n        if ( isa(A{jj,kk}, 'double') && ~(A{jj,kk} == 0) )\n            H = @(x,s,y,t) H(x,s,y,t) + A{jj,kk}*x.^(kk - 1).*y.^(jj - 1);\n        elseif ( isa(A{jj,kk}, 'chebfun2') )\n            v = zeros(1, n, 1, n);\n            v(1,:,1,:) = feval(A{jj,kk}, newx, newy).';\n            out = repmat(v, [xorder + 1, 1, yorder + 1, 1]);\n            H = @(x,s,y,t) H(x,s,y,t) + out.*x.^(kk-1).*y.^(jj-1);\n        end\n    end\nend\nH = H(xx, ss, yy, tt);\n\n% Using tensor-train ideas. Calculate the splitting rank of the function\n% H(x,s,y,t): \nA = reshape(H, n*(xorder+1), n*(yorder+1));\n[U, S, V] = svd(A); \nrk = find(abs(diag(S)/S(1,1)) > 1000*eps, 1, 'last' );  % splitting rank\n\n% Restrict to singular vectors of interest.  \nS = S(1:rk, 1:rk);\nU = U(:, 1:rk); \nV = V(:, 1:rk); \n\n% We have the splitting rank of the PDO, now we want the corresponding \n% separable representation. The following is tricky to get right... \ncellU = cell(yorder+1, rk);\ncellV = cell(xorder+1, rk); \nc1 = cell(xorder, 1); \nc2 = cell(yorder, 1); \n% Matrices to convert ChebT -> monomials: \nconverty = fliplr(poly(chebpoly(0:yorder))); \nconvertx = fliplr(poly(chebpoly(0:xorder)));\n\n% Figure out the separable representation: \nfor jj = 1:rk \n\n    % This is giving us the 1D ODEs that go on the right in the generalized\n    % Sylvester matrix equation: \n    f1 = chebfun2.vals2coeffs( reshape(U(:,jj), xorder+1, n) );  % @(x, s)\n    f1 = f1.' * convertx;\n    for kk = 1:xorder+1\n        c1{kk} = chebfun(f1(:,kk), domain(1:2), 'coeffs');\n        cellV(kk,jj) = c1(kk);\n    end\n\n    % This is giving us the 1D ODEs that go on the left in the generalized\n    % Sylvester matrix equation: \n    f2 = chebfun2.vals2coeffs( reshape(conj(V(:,jj)), yorder+1, n) );  % @(y, t) \n    f2 = f2.' * converty;\n    for kk = 1:yorder+1\n        c2{kk} = chebfun(f2(:,kk), domain(3:4), 'coeffs');\n        cellU(kk,jj) = c2(kk);\n    end  \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/@chebop2/separableFormat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.5956085259964498}}
{"text": "function [amp_map, ang_map] = detectChange(obj, t1, t2)\n% This method returns an amplitude map and a angle map as a byproduct.\n% When called in this form:\n%   change_map = detectChange(obj, t1, t2)\n% Only the amp_map will be caught and copied to change_map, while the\n% ang_map deserted.\n%\n% Unlike many counterparts, this implementation perfoms (t2 - t1)\n% insead of (t1 - t2) as I think the former one easier for\n% interpretation in vectors\ndiffMap = double(t2) - double(t1);\namp_map = sqrt(sum(diffMap.^2, 3));\nang_map = (diffMap ./ amp_map);\nend\n\n", "meta": {"author": "Bobholamovic", "repo": "ChangeDetectionToolbox", "sha": "167877b866665511d9d5e7e184f964bcda5f4016", "save_path": "github-repos/MATLAB/Bobholamovic-ChangeDetectionToolbox", "path": "github-repos/MATLAB/Bobholamovic-ChangeDetectionToolbox/ChangeDetectionToolbox-167877b866665511d9d5e7e184f964bcda5f4016/+Algorithms/@CVA/detectChange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5956085235449243}}
{"text": "% book : Signals and Systems Laboratory with MATLAB  \n% authors : Alex Palamides & Anastasia Veloni\n%\n% \n%\n% \tProblem 3- closed-loop discrete time Transfer Function \n\nK=2;\nTs=-1\n\nG=tf(0.1, [1 -0.5], Ts);\n\nH = tf(0.5, [1 -0.1], Ts);\n\nF = feedback(K*G, H)\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/11/c1115c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5956085229060898}}
{"text": "function [Y, R, E] = Isomap(D, n_fcn, n_size, options); \n\n% ISOMAP   Computes Isomap embedding using the algorithm of \n%             Tenenbaum, de Silva, and Langford (2000). \n%\n% [Y, R, E] = isomap(D, n_fcn, n_size, options); \n%\n% Input:\n%    D = N x N matrix of distances (where N is the number of data points)\n%    n_fcn = neighborhood function ('epsilon' or 'k') \n%    n_size = neighborhood size (value for epsilon or k) \n%\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%\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 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\n%%%%% Step 0: Initialization and Parameters %%%%%\n\nN = size(D,1); \nif ~(N==size(D,2))\n     error('D must be a square matrix'); \nend; \nif 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\nelseif n_fcn=='epsilon'\n     epsilon = n_size; \nelse \n     error('Neighborhood function must be either epsilon or k'); \nend\nif nargin < 3\n     error('Too few input arguments'); \nelseif nargin < 4\n     options = struct('dims',1:10,'overlay',1,'comp',1,'display',1,'verbose',1); \nend\nINF =  1000*max(max(D))*N;  %% effectively infinite distance\n\nif ~isfield(options,'dims')\n     options.dims = 1:10; \nend\nif ~isfield(options,'overlay')\n     options.overlay = 1; \nend\nif ~isfield(options,'comp')\n     options.comp = 1; \nend\nif ~isfield(options,'display')\n     options.display = 1; \nend\nif ~isfield(options,'verbose')\n     options.verbose = 1; \nend\ndims = options.dims; \ncomp = options.comp; \noverlay = options.overlay; \ndispl = options.display; \nverbose = options.verbose; \n\nY.coords = cell(length(dims),1); \nR = zeros(1,length(dims)); \n\n%%%%% Step 1: Construct neighborhood graph %%%%%\ndisp('Constructing neighborhood graph...'); \n\nif n_fcn == 'k'\n     [tmp, ind] = sort(D); \n     for i=1:N\n          D(i,ind((2+K):end,i)) = INF; \n     end\nelseif n_fcn == 'epsilon'\n     warning off    %% Next line causes an unnecessary warning, so turn it off\n     D =  D./(D<=epsilon); \n     D = min(D,INF); \n     warning on\nend\n\nD = min(D,D');    %% Make sure distance matrix is symmetric\n\nif (overlay == 1)\n     E = int8(1-(D==INF));  %%  Edge information for subsequent graph overlay\nend\n\n% Finite entries in D now correspond to distances between neighboring points. \n% Infinite entries (really, equal to INF) in D now correspond to \n%   non-neighoring points. \n\n%%%%% Step 2: Compute shortest paths %%%%%\ndisp('Computing shortest paths...'); \n\n% We use Floyd's algorithm, which produces the best performance in Matlab. \n% Dijkstra's algorithm is significantly more efficient for sparse graphs, \n% but requires for-loops that are very slow to run in Matlab.  A significantly \n% faster implementation of Isomap that calls a MEX file for Dijkstra's \n% algorithm can be found in isomap2.m (and the accompanying files\n% dijkstra.c and dijkstra.dll). \n\ntic; \nfor k=1:N\n     D = min(D,repmat(D(:,k),[1 N])+repmat(D(k,:),[N 1])); \n     if ((verbose == 1) & (rem(k,20) == 0)) \n          disp([' Iteration: ' num2str(k) '     Estimated time to completion: 'num2str((N-k)*toc/k/60) ' minutes']); \n     end\nend\n\n%%%%% Remove outliers from graph %%%%%\ndisp('Checking for outliers...'); \nn_connect = sum(~(D==INF));        %% number of points each point connects to\n[tmp, firsts] = min(D==INF);       %% first point each point connects to\n[comps, I, J] = unique(firsts);    %% represent each connected component once\nsize_comps = n_connect(comps);     %% size of each connected component\n[tmp, comp_order] = sort(size_comps);  %% sort connected components by size\ncomps = comps(comp_order(end:-1:1));    \nsize_comps = size_comps(comp_order(end:-1:1)); \nn_comps = length(comps);               %% number of connected components\nif (comp>n_comps)                \n     comp=1;                              %% default: use largest component\nend\ndisp(['  Number of connected components in graph: ' num2str(n_comps)]); \ndisp(['  Embedding component ' num2str(comp) ' with ' num2str(size_comps(comp)) ' points.']); \nY.index = find(firsts==comps(comp)); \n\nD = D(Y.index, Y.index); \nN = length(Y.index); \n\n%%%%% Step 3: Construct low-dimensional embeddings (Classical MDS) %%%%%\ndisp('Constructing low-dimensional embeddings (Classical MDS)...'); \n\nopt.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); \n\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^2,1); \nfor di = 1:length(dims)\n     if (dims(di)<=N)\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})),N^2,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\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", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/mrFlatMesh/mex/CSource/Isomap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5956085176836218}}
{"text": "function line = edgeToLine(edge)\n%EDGETOLINE Convert an edge to a straight line.\n%\n%   LINE = edgeToLine(EDGE);\n%   Returns the straight line containing the edge EDGE.\n%   EDGE is represented as [X1 Y1  X2 Y2]\n%   LINE is represented as [X0 Y0  DX DY]\n%\n%   Example\n%       edge = [2 3 4 5];\n%       line = edgeToLine(edge);\n%       figure(1); hold on; axis([0 10 0 10]);\n%       drawLine(line, 'color', 'g')\n%       drawEdge(edge, 'linewidth', 2)\n%   \n%   See also \n%   edges2d, lines2d, lineToEdge\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2009-07-23, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009-2022 INRA - Cepia Software Platform\n\nline = [edge(:, 1:2) edge(:, 3:4)-edge(:, 1:2)];\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom2d/edgeToLine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5955582830988849}}
{"text": "function [rsmooth,gsmooth,bsmooth,stdim] = flyproc(im)\n\n% This function contains the same algorithm as the demo script flyexdemo.m.\n% All graphical output steps have been removed, and the script has been\n% converted into a function which takes as input the filename of a\n% Drosophila image, and outputs the rotated and cropped image, along with\n% curves fit to the red, green and blue channels. It is used as a utility\n% function by localflyexdemo.m and dctflyexdemo.m.\n%\n% This function uses the Image Processing ans Curve Fitting Toolboxes.\n%\n% Sam Roberts\n\n%   Copyright 2006 The MathWorks, Inc.\n\nim = imread(im);\n\nRGBmax = max(im,[],3);\n\nmask = im2bw(RGBmax,20/255);\n\nmask = medfilt2(mask,[3,3]);\n\nmask = imclose(mask,strel('disk',5,0));\n\nL = bwlabel(mask);\n\nstats = regionprops(L,...\n    {'Orientation','MajorAxisLength','MinorAxisLength'});\n\nstdim = imrotate(im,-stats.Orientation);\nwarning off MATLAB:colon:nonIntegerIndex\nstdim = stdim(size(stdim,1)/2-stats.MinorAxisLength/2:size(stdim,1)/2+stats.MinorAxisLength/2,...\n    size(stdim,2)/2-stats.MajorAxisLength/2:size(stdim,2)/2+stats.MajorAxisLength/2,:);\nwarning on MATLAB:colon:nonIntegerIndex\n\nRGBmax = max(stdim,[],3);\n\nRGBequal = adapthisteq(RGBmax,'NumTiles',...\n    [ceil(size(RGBmax,1)/13),ceil(size(RGBmax,2)/13)]);\n\nRGBequal = medfilt2(RGBequal);\n\nbw=im2bw(RGBequal,105/255);\n[L,num] = bwlabel(bw,4);\n\nstats = regionprops(L,'Centroid','PixelIdxList');\n\nr = squeeze(stdim(:,:,1));\ng = squeeze(stdim(:,:,2));\nb = squeeze(stdim(:,:,3));\n[rows,columns,tmp]=size(stdim);\nfor i=1:num\n    data(i,1:2) = stats(i).Centroid./[columns,rows]*100;\n    data(i,3)=mean(r(stats(i).PixelIdxList));\n    data(i,4)=mean(g(stats(i).PixelIdxList));\n    data(i,5)=mean(b(stats(i).PixelIdxList));\nend\n\nmiddlestrip = (data(:,2)>40 & data(:,2)<60);\nmiddledata = data(middlestrip,:);\n\nopts = fitoptions('smoothingspline','SmoothingParam',0.01);\nfitresultr = fit(middledata(:,1),middledata(:,3),'smoothingspline',opts);\nfitresultg = fit(middledata(:,1),middledata(:,4),'smoothingspline',opts);\nfitresultb = fit(middledata(:,1),middledata(:,5),'smoothingspline',opts);\n\nrsmooth = feval(fitresultr,0:100);\ngsmooth = feval(fitresultg,0:100);\nbsmooth = feval(fitresultb,0: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/13684-quantitative-high-throughput-gene-expression-imaging/flyproc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5955582785931008}}
{"text": "function value = year_is_embolismic_greek ( y )\n\n%*****************************************************************************80\n%\n%% YEAR_IS_EMBOLISMIC_GREEK returns TRUE if the Greek year was embolismic.\n%\n%  Discussion:\n%\n%    Apparently, the Greek calendar was emended haphazardly.  This\n%    routine does not attempt to follow that historical pattern, and\n%    just uses the Hebrew calendar pattern for now.\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_greek.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.5955582624175589}}
{"text": "function showresult(node,elem,u,viewangle)\n%% SHOWRESULT display the mesh and the solution \n%\n%  showresult(node,elem,u,viewangle) displays the mesh and the solution in\n%  one figure. The left one is the mesh, the middle\n%  one is the contour of the solution, and the right one is the graph of\n%  the function. The last viewangle is used to adjust the view angle of the\n%  graph of the function.\n%\n%  Example:\n%     f = inline('sin(2*pi*x).*cos(2*pi*y)');\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%     u = f(node(:,1),node(:,2));\n%     showresult(node,elem,u,[-62,58]);\n%\n% See also showrate, showmesh, showsolution\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif (length(u) == size(elem,1)) || (length(u) == size(node,1))\n    % show mesh\n    set(gcf,'Units','normal'); \n    set(gcf,'Position',[0.25,0.25,0.6,0.25]);\n    if size(elem,1) < 6e4\n        subplot(1,3,1); \n        showmesh(node,elem); \n        pause(0.05)\n    else\n        subplot(1,3,1);\n        title('The mesh is too dense to display')\n    end\n    % show solution\n    subplot(1,3,2); \n    showsolution(node,elem,u,2);\n    colorbar;\n    pause(0.05)\n    subplot(1,3,3); \n    showsolution(node,elem,u);\n    if nargin>3\n        view(viewangle);\n    end\n    pause(0.05)\nelse\n    showmesh(node,elem);\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/tool/showresult.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.595511931236055}}
{"text": "function line_fekete_rule_bos_levenberg_test ( m )\n\n%*****************************************************************************80\n%\n%% LINE_FEKETE_RULE_BOS_LEVENBERG_TESTS: Bos Levenberg code for Fekete points.\n%\n%  Discussion:\n%\n%    I wanted to run the code in the Bos Levenberg paper for\n%    comparison with mine.\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%    Len Bos, Norm 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%    In the paper, M is 21.\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_BOS_LEVENBERG_TEST:\\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 polynomial space of dimension 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  A = chebvand ( m, x );\n  b = rand ( m, 1 );\n  y = A \\ b;\n  pp = ( y ~= 0.0 );\n  xf = x(pp);\n  nf = length ( xf );\n  r8vec_print ( nf, xf, '  Estimated Fekete points XF:' );\n\n  yf = ones ( nf, 1 );\n  plot ( xf, yf, '*' );\n  title ( 'Estimated Fekete point locations, Bos-Levenberg' );\n  grid on\n\n  filename = 'line_fekete_rule_bos_levenberg_test.png';\n  print ( '-dpng', filename );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Saved plot in file \"%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/line_fekete_rule/line_fekete_rule_bos_levenberg_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.5955119273314486}}
{"text": "%MIT IAP Radar Course 2011\n%Resource: Build a Small Radar System Capable of Sensing Range, Doppler, \n%and Synthetic Aperture Radar Imaging \n%\n%Gregory L. Charvat\n\n%SAR algorithm from:\n%Range Migration Algorithm from ch 10 of Spotlight Synthetic Aperture Radar\n%Signal Processing Algorithms, Carrara, Goodman, and Majewski\n\n%NOTE: set up-ramp sweep from 2-3.2V to stay within ISM band\n%change fstart and fstop bellow when in ISM band\n\n%-------------------------------------------%\n%Process raw data here\nclear all;\nclose all;\n\n%read the raw data .wave file here\n[Y,FS,NBITS] = wavread('towardswarehouse.wav');\n\n%constants\nc = 3E8; %(m/s) speed of light\n\n%radar parameters\nTp = 20E-3; %(s) pulse time\nTrp = 0.25; %(s) min range profile time duration\nN = Tp*FS; %# of samples per pulse\nfstart = 2260E6; %(Hz) LFM start frequency\nfstop = 2590E6; %(Hz) LFM stop frequency\n%fstart = 2402E6; %(Hz) LFM start frequency for ISM band\n%fstop = 2495E6; %(Hz) LFM stop frequency for ISM band\nBW = fstop-fstart; %(Hz) transmti bandwidth\nf = linspace(fstart, fstop, N/2); %instantaneous transmit frequency\n\n%the input appears to be inverted\ntrig = -1*Y(:,1);\ns = -1*Y(:,2);\nclear Y;\n\n%parse data here by position (silence between recorded data)\nrpstart = abs(trig)>mean(abs(trig));\ncount = 0;\nNrp = Trp*FS; %min # samples between range profiles\n\nfor ii = Nrp+1:size(rpstart,1)-Nrp\n    if rpstart(ii) == 1 & sum(rpstart(ii-Nrp:ii-1)) == 0\n        count = count + 1;\n        RP(count,:) = s(ii:ii+Nrp-1);\n        RPtrig(count,:) = trig(ii:ii+Nrp-1);\n    end\nend\n\n%parse data by pulse\ncount = 0;\nthresh = 0.08;\nclear ii;\nfor jj = 1:size(RP,1)\n    %clear SIF;\n    SIF = zeros(N,1);\n    start = (RPtrig(jj,:)> thresh);\n    count = 0;\n    jj\n    for ii = 12:(size(start,2)-2*N)\n        [Y I] =  max(RPtrig(jj,ii:ii+2*N));\n        if mean(start(ii-10:ii-2)) == 0 & I == 1\n            count = count + 1;\n            SIF = RP(jj,ii:ii+N-1)' + SIF;\n        end\n    end\n    %hilbert transform\n    q = ifft(SIF/count);\n    sif(jj,:) = fft(q(size(q,1)/2+1:size(q,1)));\nend\nsif(find(isnan(sif))) = 1E-30; %set all Nan values to 0\n\n%SAR data should be ready here\nclear s;\ns = sif;\nsave routsidewarehouse2 s; %for image data\n\n%-------------------------------------------%\n%load additional varaibles and setup constants for radar here\nclear all;\nc = 3E8; %(m/s) speed of light\n\n%load IQ converted data here\nload routsidewarehouse2 s; %load variable sif %for image data\n\nfor ii = 1:size(s,1)\n    s(ii,:) = s(ii,:) - mean(s,1);\nend\n\n%sif = s-sif_sub; %perform coherent background subtraction\n%sif = sif_sub; %image just the background\nsif = s; %image without background subtraction\nclear s;\nclear sif_sub;\n\n%***********************************************************************\n%radar parameters\nfc = (2590E6 - 2260E6)/2 + 2260E6; %(Hz) center radar frequency\nB = (2590E6 - 2260E6); %(hz) bandwidth\ncr = B/20E-3; %(Hz/sec) chirp rate\nTp = 20E-3; %(sec) pulse width\n%VERY IMPORTANT, change Rs to distance to cal target\n%Rs = (12+9/12)*.3048; %(m) y coordinate to scene center (down range), make this value equal to distance to cal target\nRs = 0;\nXa = 0; %(m) beginning of new aperture length\ndelta_x = 2*(1/12)*0.3048; %(m) 2 inch antenna spacing\nL = delta_x*(size(sif,1)); %(m) aperture length\nXa = linspace(-L/2, L/2, (L/delta_x)); %(m) cross range position of radar on aperture L\nZa = 0;\nYa = Rs; %THIS IS VERY IMPORTANT, SEE GEOMETRY FIGURE 10.6\nt = linspace(0, Tp, size(sif,2)); %(s) fast time, CHECK SAMPLE RATE\nKr = linspace(((4*pi/c)*(fc - B/2)), ((4*pi/c)*(fc + B/2)), (size(t,2)));\n\n%Save background subtracted and callibrated data\nsave sif sif delta_x Rs Kr Xa;\n%clear all;\n\n%run IFP\nSBAND_RMA_IFP;\n", "meta": {"author": "lukeweston", "repo": "SimpleFMCWRadar", "sha": "49a8f7b0813ed68c14357b601e6144cd0b3574b8", "save_path": "github-repos/MATLAB/lukeweston-SimpleFMCWRadar", "path": "github-repos/MATLAB/lukeweston-SimpleFMCWRadar/SimpleFMCWRadar-49a8f7b0813ed68c14357b601e6144cd0b3574b8/software/mit_matlab/SBAND_RMA_opendata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5955002396517864}}
{"text": "function [Population,Range] = EnvironmentalSelection(Problem,Population,Range,N)\n% The environmental selection of RSEA\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    %% Non-dominated sorting\n    [FrontNO,MaxFNO] = NDSort(Population.objs,N);\n    Next             = find(FrontNO<=MaxFNO);\n    \n    %% Environmental selection\n    if any(Range(1,:)==Range(2,:))\n        Choose = LastSelection(Problem,Population(Next).objs,ismember(Next,find(FrontNO<MaxFNO)),N,ceil(sqrt(N)));\n    else\n        Choose = LastSelection(Problem,(Population(Next).objs-repmat(Range(1,:),length(Next),1))./repmat(Range(2,:)-Range(1,:),length(Next),1),ismember(Next,find(FrontNO<MaxFNO)),N,ceil(sqrt(N))); \n    end\n    Population = Population(Next(Choose));\n\tRange(1,:) = min([Range(1,:);Population.objs],[],1);\n    Range(2,:) = max(Population(NDSort(Population.objs,1)==1).objs,[],1);\nend\n\nfunction Choose = LastSelection(Problem,PopObj,Choose,N,div)\n% Select part of the solutions based on the radar grid\n\n    %% Identify the extreme solutions\n    [~,Extreme] = min(repmat(sqrt(sum(PopObj.^2,2)),1,size(PopObj,2)).*sqrt(1-(1-pdist2(PopObj,eye(size(PopObj,2)),'cosine')).^2),[],1); %Calculate the extreme points based on PBI\n    Choose      = Choose | ismember(1:size(PopObj,1),Extreme);\n\n    %% Calculate the convergence of each solution\n\tCon = sum(PopObj.^2,2).^0.5;\n    Con = Con./max(Con);\n    \n    %% Calculate the radar grid of each solution\n    [Site,RLoc] = RadarGrid(PopObj,div);\n    RDis        = pdist2(RLoc,RLoc);\n    RDis(logical(eye(length(RDis)))) = inf;\n    CrowdG      = zeros(1,max(Site));\n    temp        = tabulate(Site(Choose));\n    CrowdG(temp(:,1)) = temp(:,2);\n\n    %% Select N solutions one by one\n    while sum(Choose) < N\n        remainS  = find(~Choose);\n        remainG  = unique(Site(remainS));\n        bestG    = CrowdG(remainG) == min(CrowdG(remainG));\n        current  = remainS(ismember(Site(remainS),remainG(bestG)));\n        r        = 1-(Problem.FE/Problem.maxFE)^2;\n        fitness  = Problem.M.*r.*Con(current) - min(RDis(current,Choose),[],2);\n        [~,best] = min(fitness);\n        Choose(current(best))       = true;\n        CrowdG(Site(current(best))) = CrowdG(Site(current(best))) + 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/Algorithms/Multi-objective optimization/RSEA/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5955002337753084}}
{"text": "function [h,p] = gppredcheck(gpstats,alpha)\n%GPPREDCHECK Check calibration of Gaussian process prediction.\n\nn = gpstats.last;\nidx = 1:n;\np = NaN;\n\n% No predictions available, test failed\nif n == 0; h = 1; return; end\n\nzscores = (gpstats.fval(idx) - gpstats.ymu(:,idx))./(gpstats.ys(:,idx));\n\n% A NaN means that some prediction went wrong\nif any(isnan(zscores)); h = 1; return ; end\n    \nzscores(isnan(zscores)) = [];\nn = numel(zscores);\n\nif n < 3\n    mychi2inv = @(x,v) 2*gammaincinv(x,v/2);\n    plo = mychi2inv(alpha/2,n);\n    phi = mychi2inv(1-alpha/2,n);                \n    t = sum(zscores.^2);\n    if t < plo || t > phi || any(isnan([plo,phi]))\n        h = 1; \n    else\n        h = 0;\n    end                \nelse\n    [h,p] = swtest(zscores, alpha);\nend", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/utils/gppredcheck.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5955002201109094}}
{"text": "function [Ystar,Xstar,Tstar]=doprior(Y,X,n,m,p,T,ar,arvar,lambda1,lambda3,lambda4,priorexo)\n\n\n% generate Yd, using (XXX)\n%Yd=[diag(ar(1:n,1).*arvar/lambda1);zeros(n*(p-1),n);zeros(m,n);diag(arvar)];\n\nYd=[diag(ar(1:n,1).*arvar/lambda1);zeros(n*(p-1),n);(priorexo./(lambda1.*lambda4))';diag(arvar)];\n\n\n% generate Xd, using (XXX)\nJp=diag([1:p].^lambda3);\nXd=[kron(Jp,diag(arvar/lambda1)) zeros(n*p,m);zeros(m,n*p) diag(1./(lambda1*lambda4(1,:)));zeros(n,n*p) zeros(n,m)]; % error if m is equal to zero\n% Compute Td, using (XXX)\nTd=n*(p+1)+m;\n\n\n% finally generate Ystar, Xstar and Tstar\nYstar=[Y;Yd];\nXstar=[X;Xd];\nTstar=T+Td;\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/doprior.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5955002181283918}}
{"text": "function Results = MTrick(TrainX,TrainY,TestX,TestY,alpha,beta,numK,numCircle)\n\nfor id = 1:length(TrainY)\n    if TrainY(id) == 2\n        TrainY(id) = -1;\n    end\nend\n\nfor id = 1:length(TestY)\n    if TestY(id) == 2\n        TestY(id) = -1;\n    end\nend\n\nG0 = [];\nfor i = 1:length(TrainY)\n    if TrainY(i) == 1\n        G0(i,1) = 1;\n        G0(i,2) = 0;\n    else\n        G0(i,1) = 0;\n        G0(i,2) = 1;\n    end\nend\n\nTrainXY = scale_cols(TrainX,TrainY);\nfprintf('......start to train logistic regression model1111.........\\n');\nw00 = zeros(size(TrainXY,1),1);\nlambda = exp(linspace(-0.5,6,20));\nwbest = [];\nf1max = -inf;\nfor i = 1:length(lambda)\n    w_0 = train_cg(TrainXY,w00,lambda(i));\n    f1 = logProb(TrainXY,w_0);\n    if f1 > f1max\n        f1max = f1;\n        wbest = w_0;\n        se_lambda = lambda(i);\n    end\nend\n% csvwrite(strcat('model_','test','.model'),wbest);\n% wbest = load(strcat('model_','test','.model'));\n\nptemp = 1./(1 + exp(-wbest'*TrainX));\noriA = getResult(ptemp,TrainY);\nfprintf('Test accuracy on source domain is :%g\\n',oriA);\nptemp = 1./(1 + exp(-wbest'*TestX));\noriA = getResult(ptemp,TestY);\nfprintf('Test accuracy on target domain is :%g\\n',oriA);\n\nfprintf('......start to learn PLSA model.........\\n');\nDataSetX = [TrainX TestX];\n% set some variables\nLearn.Verbosity = 1;\nLearn.Max_Iterations = 50;\nLearn.heldout = .1; % for tempered EM only, percentage of held out data\nLearn.Min_Likelihood_Change = 1;\nLearn.Folding_Iterations = 20; % for TEM only: number of fiolding\n% in iterations\nLearn.TEM = 0; %tempered or not tempered\n\n[Pw_z,Pz_d,Pd,Li,perp,eta] = pLSA(DataSetX,[],numK,Learn);\npz = Pz_d*Pd';\npw = Pw_z*pz;\nA = Pw_z;\nfor i = 1:size(Pw_z,1)\n    A(i,:) = A(i,:).*pz';\nend\n\nfor i = 1:size(Pw_z,2)\n    for j = 1:length(A(:,i))\n        if pw(j) > 0\n            A(j,i) = A(j,i)./pw(j);\n        else\n            A(j,i) = 1/size(Pw_z,2);\n        end\n    end\nend\npwz = A;\nclear A;\n% csvwrite(strcat('pwz_common.pwz'),pwz);\n% \n% pwz = load(strcat('pwz_common.pwz'));\n\nFs = pwz;\nFt = Fs;\n\nGs = G0;\nGt = [];\nfor i = 1:length(TestY)\n    Gt(i,1) = ptemp(i);\n    Gt(i,2) = 1 - ptemp(i);\nend\n\nXs = TrainX;\nXt = TestX;\nXs = Xs/sum(sum(Xs));\nXt = Xt/sum(sum(Xt));\n\nb = 1/(size(Gs,1));\n\nS = ones(size(Fs,2),size(Gs,2));\nfor i = 1:size(S,1)\n    S(i,:) = S(i,:)/sum(S(i,:));\nend\n\nfvalue = trace(Xs'*Xs-2*Xs'*Fs*S*Gs'+Gs*S'*Fs'*Fs*S*Gs')+alpha*b*trace(Gs*Gs'-2*Gs*G0'+G0*G0')+beta*trace(Xt'*Xt-2*Xt'*Ft*S*Gt'+Gt*S'*Ft'*Ft*S*Gt');\ntempf = 0;\nfor circleID = 1:numCircle\n    tempM = (Fs*S*Gs'*Gs*S');\n    tempM1 = Xs*Gs*S';\n    for i = 1:size(Fs,1)\n        for j = 1:size(Fs,2)\n            if tempM(i,j)~=0\n                Fs(i,j) = Fs(i,j)*(tempM1(i,j)/tempM(i,j))^(0.5);\n            else\n                Fs(i,j) = 0;\n            end\n        end\n    end\n    for i = 1:size(Fs,1)\n        if sum(Fs(i,:))~= 0\n            Fs(i,:) = Fs(i,:)/sum(Fs(i,:));\n        else\n            for j = 1:size(Fs,2)\n                Fs(i,j) = 1/(size(Fs,2));\n            end\n        end\n    end\n    tempM = (Gs*S'*Fs'*Fs*S+alpha*b*Gs);\n    tempM1 = Xs'*Fs*S + alpha*b*G0;\n    for i = 1:size(Gs,1)\n        for j = 1:size(Gs,2)\n            if tempM(i,j)~=0\n                Gs(i,j) = Gs(i,j)*(tempM1(i,j)/tempM(i,j))^(0.5);\n            else\n                Gs(i,j) = 0;\n            end\n        end\n    end\n    for i = 1:size(Gs,1)\n        if sum(Gs(i,:))~= 0\n            Gs(i,:) = Gs(i,:)/sum(Gs(i,:));\n        else\n            for j = 1:size(Gs,2)\n                Gs(i,j) = 1/(size(Gs,2));\n            end\n        end\n    end\n    \n    tempM = (Ft*S*Gt'*Gt*S');\n    tempM1 = Xt*Gt*S';\n    for i = 1:size(Ft,1)\n        for j = 1:size(Ft,2)\n            if tempM(i,j)~=0\n                Ft(i,j) = Ft(i,j)*(tempM1(i,j)/tempM(i,j))^(0.5);\n            else\n                Ft(i,j) =0;\n            end\n        end\n    end\n    for i = 1:size(Ft,1)\n        if sum(Ft(i,:))~= 0\n            Ft(i,:) = Ft(i,:)/sum(Ft(i,:));\n        else\n            for j = 1:size(Ft,2)\n                Ft(i,j) = 1/(size(Ft,2));\n            end\n        end\n    end\n    \n    tempM = (Gt*S'*Ft'*Ft*S);\n    tempM1 = Xt'*Ft*S;\n    for i = 1:size(Gt,1)\n        for j = 1:size(Gt,2)\n            if tempM(i,j)~=0\n                Gt(i,j) = Gt(i,j)*(tempM1(i,j)/tempM(i,j))^(0.5);\n            else\n                Gt(i,j) = 0;\n            end\n        end\n    end\n    for i = 1:size(Gt,1)\n        if sum(Gt(i,:))~= 0\n            Gt(i,:) = Gt(i,:)/sum(Gt(i,:));\n        else\n            for j = 1:size(Gt,2)\n                Gt(i,j) = 1/(size(Gt,2));\n            end\n        end\n    end\n    \n    \n    tempM = (Fs'*Fs*S*Gs'*Gs+beta*Ft'*Ft*S*Gt'*Gt);\n    tempM1 = Fs'*Xs*Gs+beta*Ft'*Xt*Gt;\n    for i = 1:size(S,1)\n        for j = 1:size(S,2)\n            if tempM(i,j)~=0\n                S(i,j) = S(i,j)*(tempM1(i,j)/tempM(i,j))^(0.5);\n            else\n                S(i,j) = 0;\n            end\n        end\n    end\n    \n    fvalue = trace(Xs'*Xs-2*Xs'*Fs*S*Gs'+Gs*S'*Fs'*Fs*S*Gs')+alpha*b*trace(Gs*Gs'-2*Gs*G0'+G0*G0')+beta*trace(Xt'*Xt-2*Xt'*Ft*S*Gt'+Gt*S'*Ft'*Ft*S*Gt');\n    \n    pp = [];\n    for i = 1:length(TestY)\n        if sum(Gt(i,:))~= 0\n            pp(1,i) = Gt(i,1)/sum(Gt(i,:));\n        else\n            pp(1,i) = 0.5;\n        end\n    end\n    Results(circleID) = getResult(pp,TestY);\n    fprintf('the %g iteration is %g,the value of objective is %g\\n',circleID,getResult(pp,TestY),fvalue);\n    \n    if circleID == 1\n        tempf = fvalue;\n    end\n    if circleID > 1\n        if abs(tempf - fvalue) < 10^(-11)\n            break;\n        end\n        tempf = fvalue;\n    end\nend", "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/MTrick/MTrick.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5954414041365214}}
{"text": "function [model, activation] = bp_forward(model, batch)\n% backprop feed forward used for discriminative finetuning\n\nglobal kConv_forward2;\nglobal kConv_forward_c;\n\nactivation = cell(model.numLayer, 1);\nfor l = 2 : model.numLayer\n    activation{l-1} = batch;\n    if l == 2\n        stride = model.layers{l}.stride;\n        hidden_presigmoid = myConvolve2(kConv_forward2, batch, model.layers{l}.w, stride, 'forward');\n        hidden_presigmoid = bsxfun(@plus, hidden_presigmoid, permute(model.layers{l}.c, [2,3,4,5,1]));\n        batch = 1 ./ (1 + exp(-hidden_presigmoid));\n    elseif strcmp(model.layers{l}.type, 'convolution')\n        stride = model.layers{l}.stride;\n        hidden_presigmoid = myConvolve(kConv_forward_c, batch, model.layers{l}.w, stride, 'forward');\n        hidden_presigmoid = bsxfun(@plus, hidden_presigmoid, permute(model.layers{l}.c, [2,3,4,5,1]));\n        batch = 1 ./ (1 + exp(-hidden_presigmoid));\n    elseif strcmp(model.layers{l}.type, 'fullconnected') && l < model.numLayer\n        batch_size = size(batch,1);\n        batch = reshape(batch, batch_size, []);\n        hidden_presigmoid = bsxfun(@plus, double(batch) * double(model.layers{l}.w), double(model.layers{l}.c));\n        batch = 1 ./ (1 + exp(-hidden_presigmoid));\n    else\n        batch_size = size(batch,1);\n        batch = reshape(batch, batch_size, []);\n        temp = bsxfun(@plus, batch * model.layers{l}.w, model.layers{l}.c);\n        energy = exp( bsxfun (@minus, temp, max(temp, [], 2)));\n        batch = bsxfun(@rdivide, energy, sum(energy,2));\n    end\nend\nactivation{end} = batch;\n", "meta": {"author": "zhirongw", "repo": "3DShapeNets", "sha": "6a6cc71a9231051866092c94486ae967ac533d34", "save_path": "github-repos/MATLAB/zhirongw-3DShapeNets", "path": "github-repos/MATLAB/zhirongw-3DShapeNets/3DShapeNets-6a6cc71a9231051866092c94486ae967ac533d34/bp/bp_forward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033682, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5954413961778344}}
{"text": "% DEMO_ZILOGGAUSSIAN  Regression problem demonstration for 2-input \n%                     function with zero-inflated log-Gaussian likelihood\n%\n%  Description\n%    The regression problem consist of a data with two input\n%    variables and one output variable with zero-inflated log-Gaussian\n%    likelihood. The inference is conducted with Laplace approximation for\n%    the conditional posterior of latent function and (Laplace approximate)\n%    MAP estimate for the hyperparameters.\n%\n% Copyright (c) 2016 Jarno Vanhatalo\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% 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% set zero observations and transfer the rest to exp scale\ny(y<0) = 0;\ny(y>0) = exp(y(y>0));\n\n% Construct the model\nlik = lik_ziloggaussian('sigma2_prior',prior_t('s2',0.1));\ncfc = gpcf_constant;\ngpcf = gpcf_sexp('lengthScale', [1.1 1.2], 'magnSigma2', 0.2^2)\ngp = gp_set('lik', lik, 'cf', {cfc gpcf cfc gpcf},'comp_cf', {1:2 3:4});\n\ndisp(' MAP estimate for the parameters')\n\n% Optimize with the scaled conjugate gradient method\nopt=optimset('TolFun',1e-3,'TolX',1e-3,'Display','iter');\ngp=gp_optim(gp,x,y,'opt',opt);\n\n% Make predictions of the underlying function on a dense grid and plot it.\n[xt1,xt2]=meshgrid(-1.8:0.1:1.8,-1.8:0.1:1.8);\nxt=[xt1(:) xt2(:)];\nnt = size(xt,1);\n[Eft_map, Varft_map, Lpy_map, Ey_map, Vary_map] = gp_pred(gp, x, y, xt, 'yt', zeros(size(xt,1),1));\n\n% Plot the prediction and data\nfigure(1)\nclf\nsubplot(1,2,1)\nmesh(xt1, xt2, reshape(1-exp(Lpy_map),37,37));\nhold on\nplot3(x(y>0,1), x(y>0,2), ones(sum(y>0),1), 'r*')\nplot3(x(y==0,1), x(y==0,2), zeros(sum(y==0)), 'k*')\naxis on;\ntitle('The probability of being greater than zero');\nsubplot(1,2,2)\nmesh(xt1, xt2, reshape(Ey_map,37,37));\nhold on\nplot3(x(:,1), x(:,2), y, '*')\naxis on;\ntitle('The posterior mean of y');\n\n\n% %% Test the likelihood function\n% % This block is a general purpose code for testing new likelihood\n% % functions\n% f = 2*randn(size(y,1)*2,1);\n% \n% lik.fh.ll(lik,y,f)\n% \n% % check llg with respect to latent\n% fe = @(x) lik.fh.ll(lik,y,x');\n% fg = @(x) lik.fh.llg(lik,y,x','latent')';\n% gradcheck(randn(size(f')),fe,fg);\n% \n% % check llg with respect to param\n% [w,s] = lik.fh.pak(lik)\n% w=randn(size(w));\n% fe = @(x) lik.fh.ll(lik.fh.unpak(lik,x),y,f);\n% fg = @(x) lik.fh.llg(lik.fh.unpak(lik,x),y,f,'param');\n% gradcheck(randn(size(w)),fe,fg);\n% \n% % check llg2 with respect to latent\n% ind = unique( ceil(length(y)*rand(20,1)));\n% h1 = lik.fh.llg2(lik,y(ind),f([ind ; ind+n]), 'latent');\n% ny=length(ind);\n% h1 = [diag(h1(1:ny,1)) diag(h1(ny+1:end,1)) ; diag(h1(1:ny,2)) diag(h1(ny+1:end,2))];\n% fe = @(x) lik.fh.ll(lik,y(ind),x);\n% h2 = hessian(fe,f([ind ; ind+n]));\n% [min(min(h1)) max(max(h1))]\n% [min(min(h2)) max(max(h2))]\n% [min(min(h1-h2)) max(max(h1-h2))]\n% \n% gpla_e(gp_pak(gp),gp,x,y)\n% gpla_g(gp_pak(gp),gp,x,y)\n% \n% gradcheck(randn(size(gp_pak(gp))),@gpla_e,@gpla_g,gp,x,y);", "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_ziloggaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5954392099628993}}
{"text": "function [h, compUpAV, compUpVP, compUp] =  lfmComputeH3AV(gamma1_p, gamma1_m, sigma2, t1, ...\n    t2, preFactor, mode)\n\n% LFMCOMPUTEH3AV Helper function for computing part of the LFMAV kernel.\n% FORMAT\n% DESC computes a portion of the LFMAV kernel.\n% ARG gamma1 : Gamma value for first system.\n% ARG gamma2 : Gamma value for second system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG preFactor : precomputed constants.\n% ARG mode: indicates the correct derivative.\n% RETURN h : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio Alvarez, 2010\n\n% KERN\n\n% Evaluation of h\n\nif nargout>1\n    [compUpAV{1}, compUpVP{1}, compUp{1}] = lfmavComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode);\n    [compUpAV{2}, compUpVP{2}, compUp{2}] = lfmavComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\n    h = preFactor(1)*compUpAV{1} + preFactor(2)*compUpAV{2};\nelse\n    h = preFactor(1)*lfmavComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode) ...\n        + preFactor(2)*lfmavComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\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/lfmComputeH3AV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5954391995280209}}
{"text": "function [C, d, volume] = maximal_ellipse(A,b)\n\n% poly = iris.Polyhedron(A, b).reduce();\n[Ad, ia] = unique(A,'rows');\nA = Ad;\nb = b(ia);\n\n[C, d] = iris.inner_ellipsoid.mosek_nofusion(A, b);\n% [C, d] = iris.inner_ellipsoid.mosek_ellipsoid(A, b);\n\n% If Mosek fails for you, you can use CVX with the free SDPT3 solver,\n% but it will be much (about 100X) slower. Just swap the above line for the\n% following:\n% [C, d] = iris.inner_ellipsoid.cvx_ellipsoid(A, b);\n\nvolume = det(C);\n\n", "meta": {"author": "rdeits", "repo": "iris-distro", "sha": "ff624610a82a858862d55732136dbc2cc9ab16fc", "save_path": "github-repos/MATLAB/rdeits-iris-distro", "path": "github-repos/MATLAB/rdeits-iris-distro/iris-distro-ff624610a82a858862d55732136dbc2cc9ab16fc/src/matlab/+iris/maximal_ellipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5954381171499935}}
{"text": "%performs knn classification\n%>\n%> @param TestFeatureVector: features for test observation (length iNumFeatures)\n%> @param TrainFeatureMatrix: features for all train observations (dimension iNumFeatures x iNumObservations)\n%> @param TrainClassIndices: audio signal (length iNumObservations)\n%> @param k: number of points taken into account (default = 3)\n%>\n%> @retval class index of the resulting class\n% ======================================================================\nfunction [class] = ToolSimpleKnn(TestFeatureVector, TrainFeatureMatrix, TrainClassIndices, k)\n \n    % set order to 3 if not set\n    if (nargin < 4)\n        k = 3;\n    end\n \n    % compute distances to all training observations\n    d = computeEucDist_I(TestFeatureVector, TrainFeatureMatrix);\n    \n    % sort the distances to find closest\n    [dummy,idx] = sort(d); \n    \n    % pick the majority of the k closest training observations\n    % note that for multi-class problems and even k, this needs to be\n    % refined\n    class = mode(TrainClassIndices(idx(1:k)));\nend\n\nfunction d = computeEucDist_I(A, B)\n    d = sqrt(sum(A.^2, 2)*ones(1,size(B,1)) - ...\n        2*A*B' + ...\n        ones(size(A,1),1)*sum(B.^2, 2)');\nend\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/ToolSimpleKnn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5954380979505626}}
{"text": "\n   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n   %   PULSED SPOTLIGHT SAR SIMULATION AND RECONSTRUCTION   %\n   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\ncolormap(gray(256))\ncj=sqrt(-1);\npi2=2*pi;\n%\nc=3e8;                   % propagation speed\nf0=50e6;                 % baseband bandwidth is 2*f0\nw0=pi2*f0;\nfc=200e6;                % carrier frequency\nwc=pi2*fc;\nlambda_min=c/(fc+f0);    % Wavelength at highest frequency\nlambda_max=c/(fc-f0);    % Wavelength at lowest frequency\nkc=(pi2*fc)/c;           % wavenumber at carrier frequency\nkmin=(pi2*(fc-f0))/c;    % wavenumber at lowest frequency\nkmax=(pi2*(fc+f0))/c;    % wavenumber at highest frequency\n%\nXc=1000;                 % Range distance to center of target area\nX0=20;                   % target area in range is within [Xc-X0,Xc+X0]\nYc=300;                  % Cross-range distance to center of target area\nY0=60;                  % target area in cross-range is within\n                         % [Yc-Y0,Yc+Y0]\n\n% Case 1: L < Y0; requires zero-padding of SAR signal in synthetic\n% aperture domain\n%\n  L=100;                 % synthetic aperture is 2*L\n\n% Case 2: L > Y0; slow-time Doppler subsampling of SAR signal spectrum\n% reduces computation\n%\n% L=400;                 % synthetic aperture is 2*L\n\ntheta_c=atan(Yc/Xc);     % Squint angle\nRc=sqrt(Xc^2+Yc^2);      % Squint radial range\nL_min=max(Y0,L);         % Zero-padded aperture is 2*L_min\n\n%\nXcc=Xc/(cos(theta_c)^2); % redefine Xc by Xcc for squint processing\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% u domain parameters and arrays for compressed SAR signal %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nduc=(Xcc*lambda_min)/(4*Y0);      % sample spacing in aperture domain\n                                  % for compressed SAR signal\nduc=duc/1.2;                      % 10 percent guard band; this guard band\n                                  % would not be sufficient for targets\n                                  % outside digital spotlight filter (use\n                                  % a larger guard band, i.e., PRF)\nmc=2*ceil(L_min/duc);             % number of samples on aperture\nuc=duc*(-mc/2:mc/2-1);            % synthetic aperture array\ndkuc=pi2/(mc*duc);                % sample spacing in ku domain\nkuc=dkuc*(-mc/2:mc/2-1);          % kuc array\n%\ndku=dkuc;                         % sample spacing in ku domain\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%    u domain parameters and arrays for SAR signal     %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nif Yc-Y0-L < 0,                            % minimum aspect angle\n theta_min=atan((Yc-Y0-L)/(Xc-X0));\nelse,\n theta_min=atan((Yc-Y0-L)/(Xc+X0));\nend;\ntheta_max=atan((Yc+Y0+L)/(Xc-X0));         % maximum aspect angle\n%\ndu=pi/(kmax*(sin(theta_max)- ...\n                     sin(theta_min))); % sample spacing in aperture\n                                       % domain for SAR signal\ndu=du/1.4;                        % 20 percent guard band\nm=2*ceil(pi/(du*dku));            % number of samples on aperture\ndu=pi2/(m*dku);                   % readjust du\nu=du*(-m/2:m/2-1);                % synthetic aperture array\nku=dku*(-m/2:m/2-1);              % ku array\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%       Fast-time domain parmeters and arrays          %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nTp=2.5e-7;                     % Chirp pulse duration\nalpha=w0/Tp;                   % Chirp rate\nwcm=wc-alpha*Tp;               % Modified chirp carrier\n%\nif Yc-Y0-L < 0,\n Rmin=Xc-X0;\nelse,\n Rmin=sqrt((Xc-X0)^2+(Yc-Y0-L)^2);\nend;\nTs=(2/c)*Rmin;                 % start time of sampling\nRmax=sqrt((Xc+X0)^2+(Yc+Y0+L)^2);\nTf=(2/c)*Rmax+Tp;              % end time of sampling\nT=Tf-Ts;                       % fast-time interval of measurement\nTs=Ts-.1*T;                    % start slightly earlier (10% guard band)\nTf=Tf+.1*T;                    % end slightly later (10% guard band)\nT=Tf-Ts;\nTmin=max(T,(4*X0)/(c*cos(theta_max)));  % Minimum required T\n%\ndt=1/(4*f0);                 % Time domain sampling (guard band factor 2)\nn=2*ceil((.5*Tmin)/dt);      % number of time samples\nt=Ts+(0:n-1)*dt;             % time array for data acquisition\ndw=pi2/(n*dt);               % Frequency domain sampling\nw=wc+dw*(-n/2:n/2-1);        % Frequency array (centered at carrier)\nk=w/c;                       % Wavenumber array\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Resolution for Broadside: (x,y) domain rotated by theta_c %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nDX=c/(4*f0);                      % range resolution (broadside)\nDY=(Xcc*lambda_max)/(4*L);         % cross-range resolution (broadside)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%           Parameters of Targets                 %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nntarget=9;                        % number of targets\n% Set ntarget=1 to see \"clean\" PSF of target at origin\n% Try this with other targets\n\n% xn: range;            yn= cross-range;    fn: reflectivity\n  xn=zeros(1,ntarget);  yn=xn;              fn=xn;\n\n% Targets within digital spotlight filter\n%\n  xn(1)=0;              yn(1)=0;            fn(1)=1;\n  xn(2)=.7*X0;          yn(2)=-.6*Y0;       fn(2)=1.4;\n  xn(3)=0;              yn(3)=-.85*Y0;      fn(3)=.8;\n  xn(4)=-.5*X0;         yn(4)=.75*Y0;       fn(4)=1.;\n  xn(5)=-.5*X0+DX;      yn(5)=.75*Y0+DY;    fn(5)=1.;\n\n% Targets outside digital spotlight filter\n% (Run the code with and without these targets)\n%  \n  xn(6)=-1.2*X0;        yn(6)=.75*Y0;       fn(6)=1.;\n  xn(7)=.5*X0;          yn(7)=1.25*Y0;      fn(7)=1.;\n  xn(8)=1.1*X0;         yn(8)=-1.1*Y0;      fn(8)=1.;\n  xn(9)=-1.2*X0;        yn(9)=-1.75*Y0;     fn(9)=1.;\n  \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                   SIMULATION                    %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\ns=zeros(n,mc);     % SAR signal array\n%\nfor i=1:ntarget;   % Loop for each target\n td=t(:)*ones(1,mc)-2*ones(n,1)*sqrt((Xc+xn(i)).^2+(Yc+yn(i)-uc).^2)/c;\n s=s+fn(i)*exp(cj*wcm*td+cj*alpha*(td.^2)).*(td >= 0 & td <= Tp & ...\n   ones(n,1)*abs(uc) <= L & t(:)*ones(1,mc) < Tf);\nend;\n%\ns=s.*exp(-cj*wc*t(:)*ones(1,mc));      % Fast-time baseband conversion\n\n% User may apply a slow-time domain window, e.g., power window, on\n% simulated SAR signal array \"s\" here.\n\nG=abs(s)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(t,uc,256-cg*(G-ng));\naxis('square');axis('xy')\nxlabel('Fast-time t, sec')\nylabel('Synthetic Aperture (Slow-time) U, meters')\ntitle('Measured Spotlight SAR Signal')\nprint P5.1.ps\npause(1)\n%\n\ntd0=t(:)-2*sqrt(Xc^2+Yc^2)/c;\ns0=exp(cj*wcm*td0+cj*alpha*(td0.^2)).*(td0 >= 0 & td0 <= Tp);\ns0=s0.*exp(-cj*wc*t(:));            % Baseband reference fast-time signal\n\ns=ftx(s).*(conj(ftx(s0))*ones(1,mc));  % Fast-time matched filtering\n%\nG=abs(iftx(s))';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\ntm=(2*Rc/c)+dt*(-n/2:n/2-1);    % fast-time array after matched filtering\nimage(tm,uc,256-cg*(G-ng));\naxis('square');axis('xy')\nxlabel('Fast-time t, sec')\nylabel('Synthetic Aperture (Slow-time) U, meters')\ntitle('SAR Signal after Fast-time Matched Filtering')\nprint P5.2.ps\npause(1)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%  Slow-time baseband conversion for squint %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nkus=2*kc*sin(theta_c)*ones(1,n);     % Doppler frequency shift in ku\n                                     % domain due to squint\n%\ns=s.*exp(-cj*kus(:)*uc);             % slow-time baseband conversion\nfs=fty(s);\n\n% Display aliased SAR spectrum\n%\nG=abs(fs)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(k*c/pi2,kuc,256-cg*(G-ng));\naxis('square');axis('xy')\nxlabel('Fast-time Frequency, Hertz')\nylabel('Synthetic Aperture (Slow-time) Frequency Ku, rad/m')\ntitle('Aliased Spotlight SAR Signal Spectrum')\nprint P5.3.ps\npause(1)\n\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%  Digital Spotlighting and Bandwidth Expansion in ku Domain  %%\n%%          via Slow-time Compression and Decompression        %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\ns=s.*exp(cj*kus(:)*uc);      % Original signal before baseband\n                             % conversion for squint\n\ncs=s.*exp(cj*2*(k(:)*ones(1,mc)).* ...      \n (ones(n,1)*sqrt(Xc^2+(Yc-uc).^2))-cj*2*k(:)*Rc*ones(1,mc));% compression\nfcs=fty(cs);            % F.T. of compressed signal w.r.t. u\n%\nG=abs(fcs)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(k*c/pi2,kuc,256-cg*(G-ng));\naxis('square');axis('xy')\nxlabel('Fast-time Frequency, Hertz')\nylabel('Synthetic Aperture (Slow-time) Frequency Ku, rad/m')\ntitle('Compressed Spotlight SAR Signal Spectrum')\nprint P5.4.ps\npause(1)\n%\nfp=iftx(fty(cs));      % Narrow-bandwidth Polar Format Processed\n                       % reconstruction\n%\nPH=asin(kuc/(2*kc));   % angular Doppler domain\nR=(c*tm)/2;            % range domain mapped from reference\n                       % fast-time domain\n%\n% Full Aperture Digital-Spotlight Filter\n%\nW_d=((abs(R(:)*cos(PH+theta_c)-Xc) < X0).* ...\n    (abs(R(:)*sin(PH+theta_c)-Yc) < Y0));\n%\nG=(abs(fp)/max(max(abs(fp)))+.1*W_d)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage((Rc/Xc)*(.5*c*tm-Rc),(kuc*Rc)/(2*kc),256-cg*(G-ng));\nxlabel('Range x, m')\nylabel('Cross-range y, m')\ntitle('Polar Format SAR Reconstruction with Digital Spotlight Filter')\naxis image; axis xy;\nprint P5.5.ps\npause(1)\n\nfd=fp.*W_d;                % Digital Spotlight Filtering\nfcs=ftx(fd);               % Transform to (omega,ku) domain\n\n% Zero-padding in ku domain for slow-time upsampling\n%\nmz=m-mc;        % number is zeros\nfcs=(m/mc)*[zeros(n,mz/2),fcs,zeros(n,mz/2)];\n%\ncs=ifty(fcs);              % Transform to (omega,u) domain\n\ns=cs.*exp(-cj*2*(k(:)*ones(1,m)).* ...      \n (ones(n,1)*sqrt(Xc^2+(Yc-u).^2))+cj*2*k(:)*Rc*ones(1,m));% decompression\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                           CAUTION                             %\n% For TDC or backprojection, do not subsample in Doppler domain %\n% and do not perform slow-time baseband conversion               %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\ns_ds=s;                    % Save s(omega,u) array for TDC and\n                           % backprojection algorithms\n\n%\ns=s.*exp(-cj*kus(:)*u);    % Slow-time baseband conversion for squint\nfs=fty(s);                 % Digitally-spotlighted SAR signal spectrum\n%\nG=abs(fs)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(k*c/pi2,ku,256-cg*(G-ng));\naxis('square');axis('xy')\nxlabel('Fast-time Frequency, Hertz')\nylabel('Synthetic Aperture (Slow-time) Frequency Ku, rad/m')\ntitle('Spotlight SAR Signal Spectrum after DS & Upsampling')\nprint P5.6.ps\npause(1)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%    SLOW-TIME DOPPLER SUBSAMPLING     %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nif Y0 < L,\n ny=2*ceil(1.2*Y0/du);      % Number of samples in y domain\n                            % 20 percent guard band\n ms=floor(m/ny);            % subsampling ratio\n tt=floor(m/(2*ms));\n I=m/2+1-tt*ms:ms:m/2+1+(tt-1)*ms; % subsampled index in ku domain\n [tt,ny]=size(I);           % number of subsamples\n fs=fs(:,I);                % subsampled SAR signal spectrum\n ky=ku(I);                  % subsampled ky array\n dky=dku*ms;                % ky domain sample spacing\nelse,\n dky=dku;\n ny=m;\n ky=ku;\nend;\n\ndy=pi2/(ny*dky);            % y domain sample spacing\ny=dy*(-ny/2:ny/2-1);        % cross-range array\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%             RECONSTRUCTION           %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nky=ones(n,1)*ky+kus(:)*ones(1,ny);       % ky array\nkx=(4*k(:).^2)*ones(1,ny)-ky.^2;\nkx=sqrt(kx.*(kx > 0));                  % kx array\n%\nplot(kx(1:20:n*ny),ky(1:20:n*ny),'.')\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('Spotlight SAR Spatial Frequency Data Coverage')\naxis image; axis xy\nprint P5.7.ps\npause(1)\n%\nkxmin=min(min(kx));\nkxmax=max(max(kx));\ndkx=pi/X0;        % Nyquist sample spacing in kx domain\nnx=2*ceil((.5*(kxmax-kxmin))/dkx); % Required number of\n                      % samples in kx domain;\n                      % This value will be increased slightly\n                      % to avoid negative array index\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%                                                         %%%\n%%%   FIRST TWO OPTIONS FOR RECONSTRUCTION:                 %%%\n%%%                                                         %%%\n%%%     1. 2D Fourier Matched Filtering and Interpolation   %%%\n%%%     2. Range Stacking                                   %%%\n%%%                                                         %%%\n%%%     Note: For \"Range Stacking,\" make sure that the      %%%\n%%%           arrays nx, x, and kx are defined.             %%%\n%%%                                                         %%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%    2D FOURIER MATCHED FILTERING AND INTERPOLATION    %%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Matched Filtering\n%\nfs0=(kx > 0).*exp(cj*kx*Xc+cj*ky*Yc+cj*.25*pi ...\n           -cj*2*k(:)*ones(1,ny)*Rc); % reference signal complex conjugate\nfsm=fs.*fs0;     % 2D Matched filtering\n\n% Interpolation\n%\nis=8;       % number of neighbors (sidelobes) used for sinc interpolator\nI=2*is+1;\nkxs=is*dkx; % plus/minus size of interpolation neighborhood in KX domain\n%\nnx=nx+2*is+4;  % increase number of samples to avoid negative\n               %  array index during interpolation in kx domain\nKX=kxmin+(-is-2:nx-is-3)*dkx;     % uniformly-spaced kx points where\n                                  % interpolation is done\nkxc=KX(nx/2+1);                   % carrier frequency in kx domain\nKX=KX(:)*ones(1,ny);\n%\nF=zeros(nx,ny);         % initialize F(kx,ky) array for interpolation\n\nfor i=1:n;                       % for each k loop\n  i                              % print i to show that it is running\n icKX=round((kx(i,:)-KX(1,1))/dkx)+1; % closest grid point in KX domain\n cKX=KX(1,1)+(icKX-1)*dkx;            % and its KX value\n ikx=ones(I,1)*icKX+[-is:is]'*ones(1,ny);\n ikx=ikx+nx*ones(I,1)*[0:ny-1];\n nKX=KX(ikx);\n SINC=sinc((nKX-ones(I,1)*kx(i,:))/dkx);             % interpolating sinc\n HAM=.54+.46*cos((pi/kxs)*(nKX-ones(I,1)*kx(i,:)));  % Hamming window\n         %%%%%   Sinc Convolution (interpolation) follows  %%%%%%%%\n F(ikx)=F(ikx)+(ones(I,1)*fsm(i,:)).*(SINC.*HAM);\nend\n%\n%  DISPLAY interpolated spatial frequency domain image F(kx,ky)\n\nKX=KX(:,1).';\nKY=ky(1,:);\n\nG=abs(F)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(KX,KY+kus(1),256-cg*(G-ng));\naxis image; axis xy\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('Wavefront Spotlight SAR Reconstruction Spectrum')\nprint P5.8.ps\npause(1)\n\n%\nf=iftx(ifty(F));     % Inverse 2D FFT for spatial domain image f(x,y)\n%\ndx=pi2/(nx*dkx);     % range sample spacing in reconstructed image\nx=dx*(-nx/2:nx/2-1); % range array\n%\n% Display SAR reconstructed image\n\nG=abs(f)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(Xc+x,Yc+y,256-cg*(G-ng));axis([Xc-X0 Xc+X0 Yc-Y0 Yc+Y0]);\naxis image; axis xy\nxlabel('Range X, meters')\nylabel('Cross-range Y, meters')\ntitle('Wavefront Spotlight SAR Reconstruction')\nprint P5.9.ps\npause(1)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%   SAR Image Compression (for Spotlight System)  %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%\nFc=ftx(fty(f.* ...\n  exp(cj*kxc*x(:)*ones(1,ny)+cj*ones(nx,1)*2*kc*sin(theta_c)*y ...\n -cj*2*kc*sqrt(((Xc+x(:)).^2)*ones(1,ny)+ones(nx,1)*((Yc+y).^2)))));\nG=abs(Fc)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(KX,KY+kus(1),256-cg*(G-ng));\naxis image; axis xy\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('Compressed Spotlight SAR Reconstruction Spectrum')\nprint P5.10.ps\npause(1)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%      RANGE STACK WAVEFRONT RECONSTRUCTION       %%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nf_stack=zeros(nx,ny); % Initialize reconstruction array in (x,y) domain\nfor i=1:nx; i        % Stack's loop for reconstruction at each range\n f_stack(i,:)=ifty(sum(fs.*exp(cj*kx*(Xc+x(i))+cj*ky*Yc ...\n  +cj*.25*pi-cj*2*k(:)*ones(1,ny)*Rc)));\nend;\n\n% Remove carrier in range domain\nf_stack=f_stack.*exp(-cj*x(:)*kxc*ones(1,ny));\n%\nf_stack=f_stack/nx; % Scale it for comparison with Fourier interpolation\n                    % Use \"f_stack-f\" to display difference of two\n                    % reconstructions\n           \nG=abs(f_stack)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(Xc+x,Yc+y,256-cg*(G-ng));axis([Xc-X0 Xc+X0 Yc-Y0 Yc+Y0]);\naxis image; axis xy\nxlabel('Range X, meters')\nylabel('Cross-range Y, meters')\ntitle('Range Stack Spotlight SAR Reconstruction')\nprint P5.11.ps\npause(1)\n                \nF_stack=ftx(fty(f_stack)); % Reconstruction array in spatial frequency\n                           % domain; Use \"F_stack-F\" to display\n                           %  difference of two reconstructions\n%\nG=abs(F_stack)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(KX,KY+kus(1),256-cg*(G-ng));\naxis image; axis xy\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('Range Stack Spotlight SAR Reconstruction Spectrum')\nprint P5.12.ps\npause(1)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%     TIME DOMAIN CORRELATION RECONSTRUCTION      %%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nf_tdc=zeros(nx,ny); % Initialize reconstruction array in (x,y) domain\n\nfor i=1:nx; i\n   for j=1:ny;\n      t_ij=(2*sqrt((x(i)+Xc)^2+(y(j)+Yc-u).^2))/c;\n      f_tdc(i,j)=sum(sum(s_ds.*exp(cj*w(:)*(t_ij-tm(n/2+1))).* ...\n         (ones(n,1)*(t_ij >= Ts & t_ij <= Tf))));\n   end;\nend;\n\n% Remove carrier in range domain\nf_tdc=f_tdc.*exp(-cj*x(:)*kxc*ones(1,ny));\n%\n\n% Remove carrier in cross-range domain (squint mode)\nf_tdc=f_tdc.*exp(-cj*ones(nx,1)*2*kc*sin(theta_c)*y);\n           \nG=abs(f_tdc)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(Xc+x,Yc+y,256-cg*(G-ng));axis([Xc-X0 Xc+X0 Yc-Y0 Yc+Y0]);\naxis image; axis xy\nxlabel('Range X, meters')\nylabel('Cross-range Y, meters')\ntitle('TDC Spotlight SAR Reconstruction')\nprint P5.13.ps\npause(1)\n                \nF_tdc=ftx(fty(f_tdc));     % Reconstruction array in spatial frequency\n%\nG=abs(F_tdc)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(KX,KY+kus(1),256-cg*(G-ng));\naxis image; axis xy\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('TDC Spotlight SAR Reconstruction Spectrum')\nprint P5.14.ps\npause(1)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%           BACKPROJECTION RECONSTRUCTION         %%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nf_back=zeros(nx,ny); % Initialize reconstruction array in (x,y) domain\nn_ratio=100;              % Upsampling ratio in fast-time domain\nnu=n_ratio*n;             % Size of upsampled s(t,u) array in t domain\nnz=nu-n;                  % Number of zeros\ndtu=(n/nu)*dt;            % Fast-time sample spacing of upsampled array\ntu=dtu*(-nu/2:nu/2-1);    % Upsampled reference fast-time array\nX=x(:)*ones(1,ny);\nY=ones(nx,1)*y;\n\nfor j=1:m; j\n   t_ij=(2*sqrt((X+Xc).^2+(Y+Yc-u(j)).^2))/c;\n   t_ij=round((t_ij-tm(n/2+1))/dtu)+nu/2+1;\n   it_ij=(t_ij > 0 & t_ij <= nu);\n   t_ij=t_ij.*it_ij+nu*(1-it_ij);\n   S=ifty([zeros(1,nz/2),s_ds(:,j).',zeros(1,nz/2)])...\n      .*exp(cj*wc*tu);\n   S(nu)=0;\n   f_back=f_back+S(t_ij);\nend;\n\nclear X Y\n\n% Remove carrier in range domain\nf_back=f_back.*exp(-cj*x(:)*kxc*ones(1,ny));\n%\n\n% Remove carrier in cross-range domain (squint mode)\nf_back=f_back.*exp(-cj*ones(nx,1)*2*kc*sin(theta_c)*y);\n  \nG=abs(f_back)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(Xc+x,Yc+y,256-cg*(G-ng));axis([Xc-X0 Xc+X0 Yc-Y0 Yc+Y0]);\naxis image; axis xy\nxlabel('Range X, meters')\nylabel('Cross-range Y, meters')\ntitle('Backprojection Spotlight SAR Reconstruction')\nprint P5.15.ps\npause(1)\n                \nF_back=ftx(fty(f_back));     % Reconstruction array in spatial frequency\n%\nG=abs(F_back)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(KX,KY+kus(1),256-cg*(G-ng));\naxis image; axis xy\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('Backprojection Spotlight SAR Reconstruction Spectrum')\nprint P5.16.ps\npause(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/2188-synthetic-aperture-radar-signal-processing-with-matlab-algorithms/soumekh/spotlight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5954328488713935}}
{"text": "function y = expcone(x)\n%EXPCONE Defines a low-level exponential cone constraint x(2)*exp(x(1)/x(2)) <= x(3)\n%\n% Input\n%    x       : Linear 3x1 SDPVAR object\n%\n% Example\n%\n% Standard  exponential cone constraint x(2)*exp(x(1)/x(2)) <= x(3)\n%    F = expcone(x)\n%\n% To quickly define several cones, the argument can be a matrix, and the\n% command is then short-hand for \n% for i = 1:size(x,2);F = [F,expcone(x(:,i))];end \n%\n% See also  @SDPVAR/CONE, @SDPVAR/PCONE\n\n\n[n,m] = size(x);\nif min([n m])==1\n    x = reshape(x,3,1);  \nend\n[n,m] = size(x);\nif n ~=3\n    error('x must be a vector or matrix of height 3')\nend\ny = x;\nif min([n m])>1\n\ty.typeflag = 22;\nelse\n\ty.typeflag = 21;\nend\ny = lmi(y);", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/expcone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5954023642007408}}
{"text": "function fibredir = GetFibreOrientation(modelname, fittedpars)\n%\n% function fibredir = GetFibreOrientation(modelname, fittedpars)\n%\n% Returns the fibre orientation as a unit vector from fitted parameters.\n%\n% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\ntheta = fittedpars(:, GetParameterIndex(modelname, 'theta'));\nphi = fittedpars(:, GetParameterIndex(modelname, 'phi'));\n\nfibredir = [cos(phi).*sin(theta) sin(phi).*sin(theta) cos(theta)]';\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/GetFibreOrientation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5954023470622912}}
{"text": "\nfunction a = map(hyper) \n\n%=======================================================================\n%  Mapping object\n%=======================================================================  \n% A=MAP(H) returns a map object initialized with hyperparameters H. \n%\n%  MAP is a general object for mapping data, it takes a supplied\n%  mapping function which can transform the given input data. The \n%  function can use four hyperparmeters p1,p2,p3,p4.\n%\n%  Hyperparameters, and their defaults\n% \n%   func='d.X=tanh((d.X+a.p1)*a.p2)' -- function we wish to use.\n%                                     This can be changed at will,\n%                                     it can access the object 'd' (data)\n%                                     and 'a' (mapping algorithm), e.g\n%                                     d.X, d.Y, a.p1, a.p2, etc. and \n%                                     usual matlab functions. It should \n%                                     store the new values in d.X. \n%                                      The default is a sigmoid mapping.\n%   p1=1,p2=0,p3=[],p4=[]          -- user parameters\n%=======================================================================\n% Reference : \n% Author    : \n% Link      : \n%=======================================================================\n    \n  a.func='x=tanh((d.X+a.p2)*a.p1)';        \n  a.p1=1; a.p2=0; a.p3=[]; a.p4=[];\n  \n  p=algorithm('map');\n  a= class(a,'map',p);\n  \n  if nargin==1\n    eval_hyper;\n  end  \n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/basic/@map/map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5953874560563887}}
{"text": "function [L_t, S_t, iters, frob_err] = ncrpca(M, true_r, EPS, MAX_ITER, EPS_S, incoh, TOL)\n\n% This matlab code implements Non-convex Robust PCA (NcRPCA)\n% Input:\n% M = given low rank+sparse matrix to be decomposed\n% true_r = maximum rank of the low rank rank component\n% EPS (optional) = convergence threshold for ||M-(L_t+S_t)||_F; default is 1e-3\n% MAX_ITER (optional) = maximum iterations for NcRPCA; default is 51\n% EPS_S (optional) = threshold for removing small entries in the sparse component; default is 1e-3\n% incoh (optional) = incoherence of the low rank component; default is 1\n% TOL (optional) = tolerance for relative error in ||M-(L_t+S_t)||_F in consecutive iterations; default is 1e-1\n% Output:\n% M_t = thresholded M at each iteration\n% L_t = rank-k approximation of M_t\n% S_t = sparse component, computed as M-M_t\n% iters = number of iteration of NcRPCA\n% frob_err = ||M-(L_t+S_t)||_F at each iteration\n\nif nargin < 7, TOL = 1e-1; end\nif nargin < 6, incoh = 1; end\nif nargin < 5, EPS_S = 1e-3; end\nif nargin < 4, MAX_ITER = 51; end\nif nargin < 3, EPS = 1e-3; end\n\n%addpath code_ncrpca/PROPACK;\n%addpath PROPACK;\nfrob_err(1) = inf;\n[~, n] = size(M);\nt = 1;\nidx = [];\nthresh_const = incoh; % threshold constant: can be tuned depending on incoherence\nthresh_red = 0.9; % parameter to reduce the threshold constant: can be tuned\nr_hat = 1; % initial rank for stagewise algorithm\nL_t = zeros(size(M));\nSig_t = lansvd(M,1,'L');\nD_t = M-L_t;\nthresh = thresh_const*Sig_t/sqrt(n);\nidx = unique([find(abs(D_t) > thresh); idx]);\nS_t = zeros(size(M));\nS_t(idx) = D_t(idx); % initial thresholding\nif max(idx(:))==0\n    idx = [];\nend\nwhile frob_err(t)/norm(M, 'fro')>=EPS && t<MAX_ITER % convergence check\n    if ~mod(t, 10)\n        %fprintf('Iter no. %d\\n', t);\n    end\n    t = t+1;\n    [U_t, Sig_t, V_t] = lansvd(M-S_t, r_hat+1, 'L');\n    %[U_t, Sig_t, V_t] = svds(M-S_t, r_hat+1); % use this if not using propack\n    L_t= U_t(:,1:r_hat)*Sig_t(1:r_hat,1:r_hat)*V_t(:,1:r_hat)';\n    D_t = M-L_t;\n    thresh = (thresh_const/sqrt(n))*Sig_t(r_hat+1, r_hat+1); % use n instead of sqrt(n) for thresholding less aggresively\n    idx = unique([find(abs(D_t) > thresh); idx]);\n    S_t(idx) = D_t(idx);\n    frob_err(t) = norm(M-(L_t+S_t), 'fro');\n    if ((frob_err(t-1)-frob_err(t))/frob_err(t-1) <= TOL) && r_hat<true_r\n%         r_hat = r_hat+1; % use this for incrementally updating rank by 1\n        sig_t = lansvd(M-S_t, true_r, 'L'); % svd function from propack\n        ratio_sig = sig_t(r_hat+1:end)./[sig_t(r_hat+2:end); sig_t(end)];\n        [~, mx_idx] = max(ratio_sig);\n        r_hat = r_hat+mx_idx; % update rank for the next stage\n    elseif ((frob_err(t-1)-frob_err(t))/frob_err(t-1) <= TOL) && r_hat==true_r\n        thresh_const = thresh_const*thresh_red; % tune threshold\n    end\nend\nS_t(abs(S_t)<EPS_S) = 0; % threshold to remove small errors and obtain sparse component\niters = length(frob_err)-1; % no. of iters. of ncrpca = length(frob_err)-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/st/MEDRoP/ncrpca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5953874503688905}}
{"text": "%% housekeeping\nclose all\nclear\nclc\n%% load the data\n\nload tut01_data\n\nload tut02_estimation\n\nload tut09_bootstrap\n\nload tut04_identification\n\nci=[30,50,68,90];\n\n%% pick a model\n\nmodel='ve_lr'; % ve\n\nendog=models.(model).endogenous;\n\n%% compute decompositions\n\n% choose identification scheme\nRfunc=[];\n\nhd=variance_decomposition(models.(model),params.(model),Rfunc,shock_names);\n\n%% plot decompositions\nshock_tex=shock_names;\n\nmyrange='1:50';\n\nfor iv=1:numel(endog)\n    \n    vname=tex.(endog{iv});\n    \n    titel=['Variance Decomposition (in %) of ',vname];\n    \n    figure('name',titel);\n    \n    d=hd.conditional.(endog{iv});\n    \n    d.varnames=shock_names;\n    \n    d=pages2struct(d);\n    \n    contributors=fieldnames(d); % = shock_names\n    \n    for ii=1:numel(contributors)\n    \n        subplot(3,2,ii)\n        \n        % note we are multiplying by 100, this just by pure convenience\n        %--------------------------------------------------------------\n        out=fanchart(100*d.(contributors{ii})(myrange),ci);\n        \n        plot_fanchart(out)\n        \n        title(contributors{ii})\n        \n        axis tight\n        \n    end\n    \n    [~,h]=sup_label(titel,'t');\n    \n    set(h,'fontsize',12)\n    \nend", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/HildeBjornland/tut10_variance_decomposition_distribution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.5953874457301009}}
{"text": "function sr_parameterstudy\n\n\ndisp('~/zmap/src/thomas/seismicrates/sr_parameterstudy.m')\n\n% reset random number generator\nrand('state',sum(100*clock));\n% set default sample size\nnN=[50];\n\n% create random number generator\n\nfor iCat=1:200\n    vRand=rand(nN(1),1);\n    iCat\n    % create different time intervals from 2 to 50 year\n    vYY=[5:5:40]';\n    for iYY=1:size(vYY,1)\n        fYr1=1980;\n        fYr2=1980+vYY(iYY);\n        fTw=(fYr2-fYr1)/2;\n\n        % create range of time bins\n        %     nTbin1=[1/10000 1/2000 1/1000 1/500 1/100 1/50 1/25 1/10];\n        %     nTbin1=1./([10 20 30 40 50 60 70 80 90 100 125 150 175 200 250 300 400 500 600 700 800 900 1000]);\n        nTbin1=1./([20 40 50 75 100 125 150 175 200 300 400 500]);\n\n        % round time bins\n        nTbin=ceil((fYr2-fYr1)*nTbin1*365)';\n\n        % set default catalog size\n        nCatSize=1000;\n        for j=1:size(nN)     % for each nN\n            %             mCat00=rand(nN(j),1)*(fYr2-fYr1)+fYr1;\n\n            mCat00=vRand*(fYr2-fYr1)+fYr1;\n            mCat=rand(nCatSize,1)*(fYr2-fYr1)+fYr1;\n            mCat20=mCat00(mCat00>(fYr2-fTw));\n            for i=1:size(nTbin)\n                [mLTA(i,iYY,iCat), mLTAprob(i,iYY,iCat)] =calc_zlta(mCat,mCat00,...\n                    mCat20,fYr1, fYr2,fTw,nTbin(i),nN(1));\n                [mBeta(i,iYY,iCat), mBetaprob(i,iYY,iCat)] =calc_beta(mCat,mCat00,...\n                    mCat20,fYr1, fYr2,fTw,nTbin(i),nN(1));\n            end\n        end\n        %         disp(n);\n        %     subplot(2,2,1)\n        %     hold on;plot(1./nTbin1,mLTA);\n        %     subplot(2,2,2)\n        %     hold on;plot(1./nTbin1,mLTAprob);\n        %     subplot(2,2,3)\n        %     hold on;plot(1./nTbin1,mBeta);\n        %     subplot(2,2,4)\n        %     hold on;plot(1./nTbin1,mBetaprob);\n\n    end\nend\n\nfor i=1:size(mLTA,1)\n    mLTA1(:,i)=reshape(mLTA(i,:,:),size(mLTA,2)*size(mLTA,3),1);\n    mLTAprob1(:,i)=reshape(mLTAprob(i,:,:),size(mLTAprob,2)*size(mLTAprob,3),1);\n    mBeta1(:,i)=reshape(mBeta(i,:,:),size(mBeta,2)*size(mBeta,3),1);\n    mBetaprob1(:,i)=reshape(mBetaprob(i,:,:),size(mBetaprob,2)*size(mBetaprob,3),1);\nend\n\nsave test.mat\nfigure;\nsubplot(2,1,1)\nerrorbar(1./nTbin1,mean(mLTA1),std(mLTA1),'b--x','LineWidth',3);\nhold on;\nerrorbar(1./nTbin1,mean(mBeta1),std(mBeta1),'r:o','LineWidth',2);\nxlabel('Bin Size [1/X]');\nylabel('Z and \\beta [ ]');\nlegend('z','\\beta');\nsubplot(2,1,2);\nerrorbar(1./nTbin1,mean(mLTAprob1),std(mLTAprob1),'b--x','LineWidth',3);\nYLim([0,1]);\nhold on;\nerrorbar(1./nTbin1,mean(mBetaprob1),std(mBetaprob1),'r:o','LineWidth',2);\nxlabel('Bin Size [1/X]');\nylabel('Probability of Z and \\beta [ ]');\nlegend('p(z)','p(\\beta)');\n\n\nsPrint=sprintf('print -dpng -r300 Tbin_N-%04.0f_Sim-%04.0f.png',nN,iCat);\neval(sPrint);\n disp(sPrint);\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/thomas/seismicrates/sr_parameterstudyTbin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5953874446813923}}
{"text": "clc;\nclear variables;\nimage=imread('lena_color.bmp');\n[r,c,d] = size(image);\nzoom = 1.5;\nzr=zoom*r;\nzc=zoom*c;\n\nfor i=1:1:zr\n     for j=1:1:zc\n         x=i/zoom;\n         mapi=round(x);\n         y=j/zoom;\n         mapj=round(y);\n          if mapi==0\n            mapi=1;\n         end\n         if mapj==0\n             mapj=1;\n         end\n         res(i,j)=image(mapi,mapj);\n     end\nend\nfigure\nimshow(image);\nfigure\nimshow(res);", "meta": {"author": "TheAlgorithms", "repo": "MATLAB-Octave", "sha": "e150b77ad256de46c1ce3815c3d7945ac4fc28dc", "save_path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave", "path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave/MATLAB-Octave-e150b77ad256de46c1ce3815c3d7945ac4fc28dc/algorithms/ImageProcessing/Nearest Neighbhor Interpolation/zoomimg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5953874389938939}}
{"text": "function padua_test04 ( )\n\n%*****************************************************************************80\n%\n%% PADUA_TEST04 tests PADUA_POINTS and PADUA_POINTS_SET.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    10 June 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'PADUA_TEST04\\n' );\n  fprintf ( 1, '  PADUA_POINTS computes the points of a Padua rule.\\n' );\n  fprintf ( 1, '  PADUA_POINTS_SET looks them up in a table.\\n' );\n \n  for l = 3 : 4\n    n = padua_order ( l );\n    xy1 = padua_points ( l );\n    [ x2, y2 ] = padua_points_set ( l );\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Level %d  Padua points\\n', l );\n    fprintf ( 1, '\\n' );\n    for j = 1 : n\n      fprintf ( 1, '  %4d  %14.6g  %14.6g\\n', j, xy1(1,j), xy1(2,j) );\n      fprintf ( 1, '        %14.6g  %14.6g\\n',    x2(j), y2(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/padua/padua_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.595332741646925}}
{"text": "%HOUGHPOINT2LINE  Calculates coordinates of line segment corresponded by point in Hough space\n%\n%     line = cv.HoughPoint2Line(houghPoint, srcImgInfo)\n%     line = cv.HoughPoint2Line(..., 'OptionName',optionValue, ...)\n%\n% ## Input\n% * __houghPoint__ Point in Hough space `[x,y]`.\n% * __srcImgInfo__ The source (input) image of Hough transform.\n%\n% ## Output\n% * __line__ Coordinates of line segment corresponded by point in Hough space,\n%   a 4-element integer vector `[vx,vy, ux,uy]`.\n%\n% ## Options\n% * __AngleRange__ The part of Hough space where point is situated. See\n%   cv.FastHoughTransform, default `ARO_315_135`.\n% * __MakeSkew__ Specifies to do or not to do image skewing. See\n%   cv.FastHoughTransform, default 'Deskew'.\n% * __Rules__ Specifies strictness of line segment calculating. This specifies\n%   the degree of rules validation. This can be used, for example, to choose\n%   a proper way of input arguments validation. Default 'IgnoreBorders':\n%   * __Strict__ Validate each rule in a proper way.\n%   * __IgnoreBorders__ Skip validations of image borders.\n%\n% The function calculates coordinates of line segment corresponded by point in\n% Hough space.\n%\n% ### Notes\n% - If `Rules` parameter set to 'Strict' then returned line cut along the\n%   border of source image.\n% - If `Rules` parameter set to 'IgnoreBorders' then in case of point, which\n%   belongs the incorrect part of Hough image, returned line will not\n%   intersect source image.\n%\n% See also: cv.FastHoughTransform, cv.HoughLines, hough, houghlines, houghpeaks\n%\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/+cv/HoughPoint2Line.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.595332733934791}}
{"text": "function hand_translation ( )\n\n%*****************************************************************************80\n%\n%% HAND_TRANSLATION applies a translation xy2 = xy + b to hand data.\n%\n%  Discussion:\n%\n%     This program assumes that the file 'HAND_NODES.TXT' is available.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    13 April 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Cleve Moler,\n%    Numerical Computing with MATLAB,\n%    SIAM, 2004,\n%    ISBN13: 978-0-898716-60-3,\n%    LC: QA297.M625. \n%\n\n%\n%  Read the data.\n%\n  xy = load ( 'hand_nodes.txt' );\n%\n%  Make XY an array of column vectors.\n%\n  xy = xy';\n%\n%  Repeat the first column at the end so the polygon closes.\n%\n  xy = [ xy, [ xy(:,1) ] ];\n%\n%  Define the transformation as xy2 = xy + b.\n%\n  b = repmat ( [ 1.0; -0.5 ], 1, 60 );\n%\n%  Transform the data.\n%\n  xy2 = xy + b;\n%\n%  Clear the graphics frame.\n%\n  clf\n%\n%  Plot the original data.\n%\n  plot ( xy(1,:), xy(2,:), 'Color', 'r', 'LineWidth', 2 );\n%\n%  Plot the transformed data.\n%\n  hold on\n  plot ( xy2(1,:), xy2(2,:), 'Color', 'b', 'LineWidth', 2 );\n%\n%  Annotate.\n%\n  axis equal\n  grid on\n  title ( 'Data (red), and data+[1.0;-0.5] (blue)' )\n\n  hold off\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hand_data/hand_translation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.5953327254415763}}
{"text": " function G = Gtomo2_strip(sg, ig, varargin)\n%function G = Gtomo2_strip(sg, ig, options)\n%\n% Generate a 2D system matrix for tomographic image reconstruction,\n% based on a square pixel basis and strip-integral detector model,\n% i.e., a rectangular detector response.\n% Works for parallel-beam, arc-fan, and flat-fan geometries.\n%\n% Closely matches Aspire \"system 13\" and \"system 14\".\n% The main limitation here is that it uses Matlab \"sparse\" data type,\n% so you will run out of memory for large image or sinogram sizes.\n%\n% in:\n%\tsg\t\tsino_geom()\n%\tig\t\timage_geom()\n%\n% options:\n%\t'strip_width'\tif 0, then line integrals (default: sg.d)\n%\t'single'\tif 1, then double(single()) the values, cf aspire\n%\t'gam_max'\tmax acceptance angle of detector [degrees] (def: 90)\n%\n% out:\n%\tG [nb*na,np]\tGsparse object, where np = sum(ig.mask(:))\n%\n% Copyright 2005-8-16, Jeff Fessler, The University of Michigan\n\nif nargin == 1 && streq(sg, 'test'), Gtomo2_strip_test, return, end\nif nargin < 2, help(mfilename), error(mfilename), end\n\n% defaults\narg.gam_max = 90; % degrees\narg.strip_width = [];\narg.single = false;\narg.chat = false;\narg.sse = false;\narg = vararg_pair(arg, varargin);\n\nif isempty(arg.strip_width), arg.strip_width = sg.d; end\n\nif streq(sg.type, 'par')\n  if (arg.sse)\n\n    nthread = 1;\n    mask = uint8(ig.mask);\n\n    [A B] = jmh_sse_mex('jmh,sse,matrix',int32(nthread), ...\n                        single(sg.orbit_start*pi/180), single(sg.orbit*pi/180), ...\n                        int32(sg.nb), single(sg.dr), single(sg.offset_r), ...\n                        single(arg.strip_width), int32(ig.nx), single(ig.dx), ...\n                        single(ig.offset_x), int32(ig.ny), single(ig.dy), ...\n                        single(ig.offset_y), mask,int32(sg.na));\n\n    M = ceil((ig.dx * sqrt(2) + arg.strip_width) / sg.dr);\n\n%     jj = [];\n    \n%     % Bad idea\n%     for y=1:ig.ny\n%       for x=1:ig.nx\n%         for a=1:sg.na\n%           for m=1:M\n%             jj = [jj,(y-1)*ig.nx + x];\n%           end\n%         end\n%       end\n%     end\n    jj = reshape(repmat(1:ig.nx*ig.ny,sg.na*M,1),[1,ig.nx*ig.ny*sg.na*M]);\n\n    G = sparse(double(B+1),double(jj'),double(A),sg.na*sg.nb,ig.nx*ig.ny,length(A));\n\n  else\n      G = Gtomo2_strip_par(sg.nb, sg.na, sg.dr, sg.offset_r, ...\n                           sg.orbit, sg.orbit_start, arg.strip_width, ...\n                           ig.nx, ig.ny, ig.dx, ig.dy, ig.offset_x, ig.offset_y, ...\n                           ig.mask, arg.single);\n  end\nelseif streq(sg.type, 'fan')\n\tG = Gtomo2_strip_fan(sg.nb, sg.na, sg.ds, sg.offset_s, ...\n\t\tsg.ar, arg.strip_width, ...\n\t\tdeg2rad(arg.gam_max), ...\n\t\tsg.dsd, sg.dso, sg.dfs, ... \n\t\tsg.source_offset, ...\n\t\tig.nx, ig.ny, ig.dx, ig.dy, ig.offset_x, ig.offset_y, ...\n\t\tig.mask, arg.single, arg.chat);\n\nelse\n\terror('unknown geometry: %s', sg.type)\nend\n\nG = Gsparse(G, 'mask', ig.mask, 'idim', [ig.nx ig.ny], 'odim', [sg.nb sg.na]);\n\n\n%\n% = Gtomo2_strip_par()\n%\nfunction G = Gtomo2_strip_par(nb, na, dr, offset_r, ...\n\torbit, orbit_start, strip_width, ...\n\tnx, ny, dx, dy, offset_x, offset_y, mask, is_single);\n\n% pixel centers\nwx = (nx-1)/2 + offset_x;\nwy = (ny-1)/2 + offset_y;\nwb = (nb-1)/2 + offset_r;\n\nx = dx * ([0:nx-1] - wx);\ny = dy * ([0:ny-1] - wy); % caution, may not match aspire if offset_y != 0\n[x y] = ndgrid(x, y);\nx = x(mask(:));\ny = y(mask(:));\nnp = length(x);\t\t% sum(mask(:)) - total # of support pixels\n\nangle = deg2rad(orbit_start + [0:na-1]'/na * orbit);\ncang = cos(angle);\nsang = sin(angle);\ntau = cang * x' + sang * y'; % [na,np] projected pixel center\ntau = tau / dr;\ntau = tau + wb;\n\nd_max = (abs(cang) + abs(sang)) / 2;\ntau_max = (dx * d_max + strip_width/2) / dr;\nib_min = 1 + floor(tau - repmat(tau_max, 1, np));\nM = ceil((dx * sqrt(2) + strip_width) / dr);\njj = find(mask(:))'; % all-column G\njj = repmat(jj, na, 1);\njj = col(jj); % so that na=1 case works\nlist.ii = [];\nlist.jj = [];\nlist.ss = [];\nfor mm=0:M-1\n\tticker(mfilename, mm+1, M)\n\tib = ib_min + mm;\n\tgood = (ib >= 0) & (ib < nb);\n\tgood = good(:);\n\tval = square_strip_int(dr * (ib - tau), ...\n\t\trepmat(angle, 1, np), 'dx', dx, 'sw', strip_width);\n\tval = val(:);\n\tii = col(ib + repmat([0:na-1]'*nb, 1, np)); % sinogram index\n\tlist.ii = [list.ii; 1+ii(good)];\n\tlist.jj = [list.jj; jj(good)];\n\tlist.ss = [list.ss; val(good)];\nend\nif is_single\n\tlist.ss = double(single(list.ss)); % stupid matlab insists on double\nend\nG = sparse(list.ii, list.jj, list.ss, nb*na, nx*ny, length(list.ss));\n\n\n%\n% = Gtomo2_strip_fan()\n%\nfunction G = Gtomo2_strip_fan(nb, na, ds, offset_s, ...\n\tbeta, strip_width, ...\n\tgam_max, ... % maximum angle gamma accepted by detector [radians]\n\tdsd, dso, dfs, roff, ...\n\tnx, ny, dx, dy, offset_x, offset_y, mask, is_single, chat);\n\n% pixel centers\nwx = (nx-1)/2 + offset_x;\nwy = (ny-1)/2 + offset_y;\nwb = (nb-1)/2 + offset_s;\n\nx = dx * ([0:nx-1] - wx);\ny = dy * ([0:ny-1] - wy); % caution, may not match aspire if offset_y != 0\n[x y] = ndgrid(x, y);\nx = x(mask(:)); % [np,1]\ny = y(mask(:));\nnp = length(x); % sum(mask(:)) - total # of support pixels\nna = length(beta);\n\ncbet = cos(beta);\nsbet = sin(beta);\n\n% s0 is \"s\" value for center of each pixel\ngam0 = atan2(cbet * x' + sbet * y' - roff, ...\n\tdso + sbet * x' - cbet * y'); % [na,np]\nclear cbet sbet\nif dfs == 0 % 3rd gen (arc)\n\ts0 = dsd * gam0;\nelseif isinf(dfs)\n\ts0 = dsd * tan(gam0);\nelse\n\terror 'unsupported dfs'\nend\n\nang0 = repmat(beta, [1 np]) + gam0;\nmag0 = dso * cos(gam0) - roff * sin(gam0) ...\n\t+ repmat(x', [na 1]) .* sin(ang0) - repmat(y', [na 1]) .* cos(ang0);\ngamgood = abs(gam0) < gam_max;\nif chat, printm('gam0: %g %g', rad2deg(minmax(gam0(gamgood)))), end\nclear gam0\nif dfs == 0 % 3rd gen (arc)\n\tmag0 = mag0 / dsd; \nelseif isinf(dfs)\n\tmag0 = mag0 / dsd ./ (1 + (s0 ./ dsd).^2);\nelse\n\terror 'dfs bug'\nend\nmag0min = min(mag0(gamgood));\nif isempty(mag0min)\n\tG = sparse([], [], [], nb*na, nx*ny, 0);\n\treturn\nend\n\ntau = s0 / ds + wb; % [na,np], unitless\n\nM = ceil((dx/mag0min * sqrt(2) + strip_width) / ds); % conservative!\nif chat, printm('M=%d, mag0min=%g', M, mag0min), end\nif M > 100\n\tprintm('Warn: M=%d too large? probably x-ray source is too oblique', M)\n\tprintm('type \"return\" and hope for the best, but it may be *slow*')\n\tprintm('recommend using \"gam_max\" to impose incidence angle constraint')\n\tkeyboard\nend\n\nib_min = 1 + floor(tau - M/2);\njj = find(mask(:))';\t% all-column G\njj = repmat(jj, na, 1); % [na,np]\njj = col(jj); % so that na=1 case works\nlist.ii = [];\nlist.jj = [];\nlist.ss = [];\nfor mm=0:M-1\n\tticker(mfilename, mm+1, M)\n\tib = ib_min + mm;\n\tval = mag0 .* square_strip_int(ds * (ib - tau), ...\n\t\tang0, 'dx', dx ./ mag0, ...\n\t\t'sw', strip_width);\n\tval = val(:); % for na=1 case\n%\tval = square_strip_int(ds * (ib - tau) .* mag0, ...\n%\t\tang0, 'dx', dx, 'sw', strip_width .* mag0); % same!\n\tii = col(ib + repmat([0:na-1]'*nb, 1, np)); % sinogram index\n%\tif chat, printm('%d of %d zeros', sum(val(:)==0), length(val(:))), end\n\tgood = (ib >= 0) & (ib < nb);\n\tgood = good & gamgood;\n\tgood = good(:);\n\tgood = good & (val > 0); % remove extra zeros due to conservative M\n\tlist.ii = [list.ii; 1+ii(good)];\n\tlist.jj = [list.jj; jj(good)];\n\tlist.ss = [list.ss; val(good)];\nend\nif is_single\n\tlist.ss = double(single(list.ss)); % stupid matlab insists on double\nend\nG = sparse(list.ii, list.jj, list.ss, nb*na, nx*ny, length(list.ss));\n\n\n%\n% test demo\n%\nfunction Gtomo2_strip_test\nig = image_geom('nx', 512, 'ny', 480', 'fov', 500, 'down', 8);\nig.mask = ig.circ > 0;\n% todo: 3 cases to test: parallel, arc-fan, flat-fan\nsg = sino_geom('par', 'nb', 600, 'na', 480, 'dr', 1.2, 'down', ig.down);\n% sg = sino_geom('fan', 'nb', 888, 'na', 984, 'ds', 1.0, 'down', ig.down, ...\n% \t'offset_s', 0*0.25, 'source_offset', 0*3.0, ...\n% \t'dsd', 949, 'dod', 408, 'dfs', 0);\n\nell = [20 50 150 150 0 1];\nell = [];\n[x ell] = ellipse_im(ig, ell, 'oversample', 2);\nya = ellipse_sino(sg, ell, 'oversample', 4);\n\nG = Gtomo2_strip(sg, ig, 'chat', 0);\n\nyd = G * x;\nsino = sg.zeros; sino(sg.nb/2, 10) = 1;\nb1 = G' * sino;\nbu = G' * sg.ones;\nmax_percent_diff(min(bu(ig.mask)), max(bu(ig.mask)), 'backproject ones')\n\nif im\n\tclf, im pl 2 2\n\tim(1, x, 'test image')\n\tim(2, ya, 'sinogram ya'), cbar\n\tim(4, yd, 'sinogram yd'), cbar\n\tim(3, yd-ya, 'yd-ya'), cbar\n\tif 0\n\t\tim(1, ig.mask, 'support mask')\n\t\tim(2, b1, 'backproject 1 ray'), cbar\n\t\tim(3, bu, 'backproject ones'), cbar\n\tend\nend\n\n% verify consistency with Gtomo2_wtmex (aspire)\nif 1 & has_aspire %& streq(sg.type, 'par')\nprompt\n\tGw = Gtomo2_wtmex(sg, ig, 'pairs', {'strip_width', sg.d});\n\tyw = Gw * x;\n\tys = G * x;\n\tmax_percent_diff(yw, ys, 'sino Gtomo2_wtmex vs Gtomo2_strip')\n\tif im\n\t\tim pl 2 3, im(1, x), cbar\n\t\tim(1, ya, 'ya'), cbar\n\t\tim(2, ys, 'ys'), cbar\n\t\tim(3, yw, 'yw'), cbar\n\t\tim(4, ys-yw, 'ys-yw'), cbar\n\t\txlabelf('%g%%', 100*nrms(ys(:), yw(:)))\n\t\tim(5, ys-ya, 'ys-ya'), cbar\n\t\txlabelf('%g%%', 100*nrms(ys(:), ya(:)))\n\t\tim(6, yw-ya, 'yw-ya'), cbar\n\t\txlabelf('%g%%', 100*nrms(yw(:), ya(:)))\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/contrib/sse_proj/irt/systems/Gtomo2_strip_sse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.6757646140788308, "lm_q1q2_score": 0.5952115017104916}}
{"text": "function [h, compUpAP, compUp] =  lfmComputeH3AP(gamma1_p, gamma1_m, sigma2, t1, ...\n    t2, preFactor, mode)\n\n% LFMCOMPUTEH3AP Helper function for computing part of the LFMAP kernel.\n% FORMAT\n% DESC computes a portion of the LFMAP kernel.\n% ARG gamma1 : Gamma value for first system.\n% ARG gamma2 : Gamma value for second system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG preFactor : precomputed constants.\n% ARG mode: indicates the correct derivative.\n% RETURN h : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio Alvarez, 2010\n\n% KERN\n\n% Evaluation of h\n\nif nargout>1    \n    [compUpAP{1}, compUp{1}] = lfmapComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode);\n    [compUpAP{2}, compUp{2}] = lfmapComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\n    h = preFactor(1)*compUpAP{1} + preFactor(2)*compUpAP{2};\nelse\n    h = preFactor(1)*lfmapComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode) ...\n        + preFactor(2)*lfmapComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\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/lfmComputeH3AP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5952114859784666}}
{"text": "%% Misorientation Distribution Function\n%\n%% TODO: Please help to extend this section\n% Let us consider the uncorrelated missorientation ODF corresponding to our\n% model ODF.\n\n\nmtexdata titanium\n\nodf = calcDensity(ebsd.orientations)\n\n%%\n\n\n% the uncorrelated \nmdf = calcMDF(odf)\n\n%%\n\nplotSection(mdf,'axisAngle')\n\n\n%% Axis / Angle Distribution\n% Then we can plot the distribution of the rotation axes of this\n% missorientation ODF\n\nplotAxisDistribution(mdf)\n\n%%\n% and the distribution of the missorientation angles and compare them to a\n% uniform ODF\n\nclose all\nplotAngleDistribution(mdf)\nhold all\nplotAngleDistribution(ebsd.CS,ebsd.CS)\nhold off\nlegend('model ODF','uniform ODF')\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/Misorientations/MisorientationDistributionFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5951741527927086}}
{"text": "function PlotAggregationVariance(AggregationVariance,SimulSecMoms,SecMom_Empirical,...\n    SecMom_Annualized,NumSimulations,b,s_2,Name)\nfigure\nfor n=1:NumSimulations\n    hold on\n    h=plot(AggregationVariance,SimulSecMoms(:,n),'.');\n    set(h,'color','k','markersize',1)\nend\nhold on\nh=plot(AggregationVariance,SecMom_Empirical);\nset(h,'color','r','linewidth',2);\nhold on\nh=plot(AggregationVariance,SecMom_Annualized);\nset(h,'color','k','linewidth',2);\nset(gca,'ytick',[],'xlim',[AggregationVariance(1) AggregationVariance(end)])\ngrid on\nxlabel('aggregation size (days)')\nylabel('aggregated variance')\nset(gcf,'Name',['               long memory of ' Name ' par swap rate'])\n\n\nfigure \nh2=plot(log(AggregationVariance),log(SecMom_Empirical),'.');\n%set(h,'color','k');\nhold on \n%h2=plot(log(AggregationVariance),b(1)+b(2)*log(AggregationVariance),'r');\nhold on \ny_norm=log(s_2)+log(AggregationVariance);\nh3=plot(log(AggregationVariance),y_norm,'k');\ngrid on\nlegend([h2 h3],['frac. B. m.: H=' num2str(b(2)/2)],'B. m.: H=0.5','location','northwest')\nxlabel('log-aggregation size (days)')\nylabel('log-aggregated variance')\nset(gcf,'Name',['               long memory of ' Name ' par swap rate'])\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23554-review-of-discrete-and-continuous-processes-in-finance/Matlab/03LongMemory/Empirical/PlotAggregationVariance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5951741479676536}}
{"text": "function lambda = orth_symm_eigenvalues ( n )\n\n%*****************************************************************************80\n%\n%% ORTH_SYMM_EIGENVALUES returns eigenvalues of the ORTH_SYMM matrix.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    17 October 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the order of A.\n%\n%    Output, real LAMBDA(N,1), the eigenvalues.\n%\n  lambda = zeros ( n, 1 );\n\n  m = floor ( ( n + 1 ) / 2 );\n  lambda(1:m,1)   = +1.0;\n  lambda(m+1:n,1) = -1.0;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/orth_symm_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.5951741463211372}}
{"text": "function i4row_sum_test ( )\n\n%*****************************************************************************80\n%\n%% I4ROW_SUM_TEST tests I4ROW_SUM;\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 3;\n  n = 4;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'I4ROW_SUM_TEST\\n' );\n  fprintf ( 1, '  I4ROW_SUM computes row sums;\\n' );\n\n  k = 0;\n  for i = 1 : m\n    for j = 1 : n\n      k = k + 1;\n      a(i,j) = k;\n    end\n  end\n\n  i4mat_print ( m, n, a, '  The matrix:' );\n\n  rowsum(1:m) = i4row_sum ( m, n, a );\n\n  mean(1:m) = i4row_mean ( m, n, a );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Sum, mean:\\n' );\n  fprintf ( 1, '\\n' );\n  for i = 1 : m\n    fprintf ( 1, '  %6d  %6d  %9f\\n', i, rowsum(i), mean(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/i4lib/i4row_sum_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.5951741447032441}}
{"text": "function F=makeRFSfilters\n% Returns the RFS filter bank of size 49x49x38 in F. The MR8, MR4 and\n% MRS4 sets are all derived from this filter bank. To convolve an\n% image I with the filter bank you can either use the matlab function\n% conv2, i.e. responses(:,:,i)=conv2(I,F(:,:,i),'valid'), or use the\n% Fourier transform.\n\n  SUP=49;                 % Support of the largest filter (must be odd)\n  SCALEX=[1,2,4];         % Sigma_{x} for the oriented filters\n  NORIENT=6;              % Number of orientations\n\n  NROTINV=2;\n  NBAR=length(SCALEX)*NORIENT;\n  NEDGE=length(SCALEX)*NORIENT;\n  NF=NBAR+NEDGE+NROTINV;\n  F=zeros(SUP,SUP,NF);\n  hsup=(SUP-1)/2;\n  [x,y]=meshgrid([-hsup:hsup],[hsup:-1:-hsup]);\n  orgpts=[x(:) y(:)]';\n\n  count=1;\n  for scale=1:length(SCALEX),\n    for orient=0:NORIENT-1,\n      angle=pi*orient/NORIENT;  % Not 2pi as filters have symmetry\n      c=cos(angle);s=sin(angle);\n      rotpts=[c -s;s c]*orgpts;\n      F(:,:,count)=makefilter(SCALEX(scale),0,1,rotpts,SUP);\n      F(:,:,count+NEDGE)=makefilter(SCALEX(scale),0,2,rotpts,SUP);\n      count=count+1;\n    end;\n  end;  \n  F(:,:,NBAR+NEDGE+1)=normalise(fspecial('gaussian',SUP,10));\n  F(:,:,NBAR+NEDGE+2)=normalise(fspecial('log',SUP,10));\nreturn\n\nfunction f=makefilter(scale,phasex,phasey,pts,sup)\n  gx=gauss1d(3*scale,0,pts(1,:),phasex);\n  gy=gauss1d(scale,0,pts(2,:),phasey);\n  f=normalise(reshape(gx.*gy,sup,sup));\nreturn\n\nfunction g=gauss1d(sigma,mean,x,ord)\n% Function to compute gaussian derivatives of order 0 <= ord < 3\n% evaluated at x.\n\n  x=x-mean;num=x.*x;\n  variance=sigma^2;\n  denom=2*variance; \n  g=exp(-num/denom)/sqrt(pi*denom);\n  switch ord,\n    case 1, g=-g.*(x/variance);\n    case 2, g=g.*((num-variance)/(variance^2));\n  end;\nreturn\n\nfunction f=normalise(f), f=f-mean(f(:)); f=f/sum(abs(f(:))); return", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/textons/makeRFSfilters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.817574471748733, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5951741430853513}}
{"text": "function Y = vl_nnsoftmaxloss(X,c,dzdy)\n% VL_NNSOFTMAXLOSS  CNN combined softmax and logistic loss\n%    Y = VL_NNSOFTMAX(X, C) applies the softmax operator followed by\n%    the logistic loss the data X. X has dimension H x W x D x N,\n%    packing N arrays of W x H D-dimensional vectors.\n%\n%    C contains the class labels, which should be integer in the range\n%    1 to D.  C can be an array with either N elements or with H x W x\n%    1 x N dimensions. In the fist case, a given class label is\n%    applied at all spatial locations; in the second case, different\n%    class labels can be specified for different locations.\n%\n%    D can be thought of as the number of possible classes and the\n%    function computes the softmax along the D dimension. Often W=H=1,\n%    but this is not a requirement, as the operator is applied\n%    convolutionally at all spatial locations.\n%\n%    DZDX = VL_NNSOFTMAXLOSS(X, C, DZDY) computes the derivative DZDX\n%    of the CNN with respect to the input X given the derivative DZDY\n%    with respect to the block output Y. DZDX has the same dimension\n%    as X.\n\n% Copyright (C) 2014 Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n%X = X + 1e-6 ;\nsz = [size(X,1) size(X,2) size(X,3) size(X,4)] ;\n\n% index from 0\nc = c - 1 ;\n\nif numel(c) == sz(4)\n  % one label per image\n  c = reshape(c, [1 1 1 sz(4)]) ;\n  c = repmat(c, [sz(1) sz(2)]) ;\nelse\n  % one label per spatial location\n  sz_ = [size(c,1) size(c,2) size(c,3) size(c,4)] ;\n  assert(isequal(sz_, [sz(1) sz(2) 1 sz(4)])) ;\nend\n\n% convert to indeces\nc_ = 0:numel(c)-1 ;\nc_ = 1 + ...\n  mod(c_, sz(1)*sz(2)) + ...\n  (sz(1)*sz(2)) * c(:)' + ...\n  (sz(1)*sz(2)*sz(3)) * floor(c_/(sz(1)*sz(2))) ;\n\n% compute softmaxloss\nXmax = max(X,[],3) ;\nex = exp(bsxfun(@minus, X, Xmax)) ;\n\nn = sz(1)*sz(2) ;\nif nargin <= 2\n  t = Xmax + log(sum(ex,3)) - reshape(X(c_), [sz(1:2) 1 sz(4)]) ;\n  Y = sum(t(:)) / n ;\nelse\n  Y = bsxfun(@rdivide, ex, sum(ex,3)) ;\n  Y(c_) = Y(c_) - 1;\n  Y = Y * (dzdy / n) ;\nend\n", "meta": {"author": "ybsong00", "repo": "Vital_release", "sha": "50de529396e2f452626aef41084972149cf4a7c7", "save_path": "github-repos/MATLAB/ybsong00-Vital_release", "path": "github-repos/MATLAB/ybsong00-Vital_release/Vital_release-50de529396e2f452626aef41084972149cf4a7c7/matconvnet/matlab/vl_nnsoftmaxloss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5951741414960822}}
{"text": "function [X,Y,vals,labI]=mp_conic(optn,varargin)\n% MP_CONIC  Conic projections\n%           This function should not be used directly; instead it is\n%           is accessed by various high-level functions named M_*.\n\n% Rich Pawlowicz (rich@ocgy.ubc.ca) 2/Apr/1997\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% Mathematical formulas for the projections and their inverses are taken from\n%\n%      Snyder, John P., Map Projections used by the US Geological Survey, \n%      Geol. Surv. Bull. 1532, 2nd Edition, USGPO, Washington D.C., 1983.\n%\n% These are  conic projections with two standard parallels, useful\n% for showing limited areas at mid-latitudes.\n%    Albers equal-area - has an equal-area property\n%    Lambert conformal - is conformal\n%\n%  7/6/99 - fixed tendency to re-define .ulongs if .clong set by user\n%  3/4/02 - added error if parallels are equidistant from equator (i.e. not conic projection really)\n%  24/10/08 - added ellipsoidal earth computations for lambert conformal conic projection\n%  16/10/09 - added ellipsoidal earth computations for albers conic projection\n%  06/03/17 - changed 'false_origin' to 'origin' as option name, also it\n%             didn't work correctly with the 'normal' spheroid so this was\n%             fixed, AND changed the default parallels so they were at 25%\n%             and 75% limits instead of being a single parallel at the\n%             center to prevent blowups with the albers ellipsoidal\n%             projection AND made it work with SPHERE ellipsoid.\n\nglobal MAP_PROJECTION MAP_VAR_LIST\n\nMAP_ELLIP=mc_ellips;\n\nname={'Albers Equal-Area Conic','Lambert Conformal Conic'};\n\npi180=pi/180;\n\nswitch optn\n\n  case 'name'\n\n     X=name;\n\n  case {'usage','set'}\n\n     m_names=fieldnames(MAP_ELLIP);\n\n     X=char({['     ''' varargin{1} ''''],...\n              '     <,''lon<gitude>'',[min max]>',...\n              '     <,''lat<itude>'',[min max]>',...\n              '     <,''clo<ngitude>'',value>',...\n              '     <,''par<allels>'',[lat1 lat2]>',...\n              '     <,''rec<tbox>'', ( ''on'' | ''off'' )>',...\n              '     <,''ell<ipsoid>'', one of',...\n    reshape(sprintf('         %6s',m_names{:}),15,length(m_names))',...\n        '                               >',...\n\t      '     <,''ori<gin>'', [long lat]>'});\n\n  case 'get'\n\n     X=char([' Projection: ' MAP_PROJECTION.name '  (function: ' MAP_PROJECTION.routine ')'],...\n            [' longitudes: ' num2str(MAP_VAR_LIST.ulongs) ' (centered at ' num2str(MAP_VAR_LIST.clong) ')'],...\n            [' latitudes: ' num2str(MAP_VAR_LIST.ulats) ],...\n            [' standard parallels: ' num2str(MAP_VAR_LIST.parallels) ],...\n            [' Rectangular border: ' MAP_VAR_LIST.rectbox ],...\n            [' ellipsoid: ' MAP_VAR_LIST.ellipsoid ],...\n            [' origin: ' num2str(MAP_VAR_LIST.origin) ]);\n\n  case 'initialize'\n\n    MAP_VAR_LIST=[];\n    MAP_PROJECTION.name=varargin{1};\n    MAP_VAR_LIST.ulongs=[-180 -50];\n    MAP_VAR_LIST.ulats=[10 85];\n    MAP_VAR_LIST.parallels=NaN;\n    MAP_VAR_LIST.clong=NaN;\n    MAP_VAR_LIST.origin=NaN;\n    MAP_VAR_LIST.rectbox='off';\n    MAP_VAR_LIST.ellipsoid = 'normal';\n    MAP_VAR_LIST.aussiemode=false;\n    k=2;longs_def=0;\n    while k<length(varargin)\n      switch varargin{k}(1:3)\n         case 'lon'\n           MAP_VAR_LIST.ulongs=varargin{k+1}(:)';longs_def=1;\n           if MAP_VAR_LIST.ulongs(1)>MAP_VAR_LIST.ulongs(2)\n              MAP_VAR_LIST.ulongs=MAP_VAR_LIST.ulongs([2 1]);\n           end\n         case 'clo'\n           MAP_VAR_LIST.clong=varargin{k+1};\n         case 'lat'\n           MAP_VAR_LIST.ulats=varargin{k+1}(:)';\n         case 'par'\n           MAP_VAR_LIST.parallels=varargin{k+1};\n         case 'rec'\n             switch lower(varargin{k+1}(1:2))\n                 case {'on','bo'}\n                    MAP_VAR_LIST.rectbox='on';\n                 case 'of'\n                    MAP_VAR_LIST.rectbox='on';\n                 otherwise\n                     error(['m_proj: Unrecognized box option: ' varargin{k+1}]);\n             end\n         case 'ell'\n           MAP_VAR_LIST.ellipsoid=varargin{k+1};\n         case 'ori'\n           MAP_VAR_LIST.origin=varargin{k+1};\n         case 'fal'\n           error(' FALSE_ORIGIN option has been renamed to ORIGIN - Change your m_proj call! ');\n\t case 'aus'  % aussiemode - my joke\n\t   if strcmp(varargin{k+1},'on')\n\t     MAP_VAR_LIST.aussiemode=true;\n\t   end   \n         otherwise\n           disp(['Unknown option: ' varargin{k}]);\n      end\n       k=k+2;\n    end\n    if isnan(MAP_VAR_LIST.clong)\n      if isnan(MAP_VAR_LIST.origin)\n         MAP_VAR_LIST.clong=mean(MAP_VAR_LIST.ulongs); \n      else\n         MAP_VAR_LIST.clong=MAP_VAR_LIST.origin(1);\n      end \t \n    elseif  ~longs_def\n        MAP_VAR_LIST.ulongs=MAP_VAR_LIST.clong+[-180 180];  \n    end\n    if isnan(MAP_VAR_LIST.parallels), MAP_VAR_LIST.parallels=mean(MAP_VAR_LIST.ulats)*[1 1]+diff(MAP_VAR_LIST.ulats)*[-1/6 1/6]; end % change default mar/2017\n    if isnan(MAP_VAR_LIST.origin), MAP_VAR_LIST.origin=[MAP_VAR_LIST.clong mean(MAP_VAR_LIST.parallels)]; end\n\n    MAP_VAR_LIST.rlongs=MAP_VAR_LIST.ulongs*pi180;\n    MAP_VAR_LIST.rlats=MAP_VAR_LIST.ulats*pi180;\n    MAP_VAR_LIST.rparallels=MAP_VAR_LIST.parallels*pi180;\n    MAP_VAR_LIST.rorigin=MAP_VAR_LIST.origin*pi180;\n\n    MAP_VAR_LIST.ellip=getfield(MAP_ELLIP,MAP_VAR_LIST.ellipsoid);\n    \n    % These are constants used by the projection formulas\n\n    switch MAP_PROJECTION.name\n      case name(1)\n        if MAP_VAR_LIST.ellip(2)==0 % spherical\n           MAP_VAR_LIST.n=sum(sin(MAP_VAR_LIST.rparallels))/2;\n           if MAP_VAR_LIST.n==0\n               error('Your parallels are equidistant from the equator - use a cylindrical projection!'); \n           end\n           MAP_VAR_LIST.C=cos(MAP_VAR_LIST.rparallels(1)).^2+2*MAP_VAR_LIST.n*sin(MAP_VAR_LIST.rparallels(1));\n           MAP_VAR_LIST.rho0=MAP_VAR_LIST.ellip(1)*sqrt(MAP_VAR_LIST.C-2*MAP_VAR_LIST.n*sin( MAP_VAR_LIST.rorigin(2)   ))/MAP_VAR_LIST.n;\n        else\n \t       e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n\t       m12=cos(MAP_VAR_LIST.rparallels)./sqrt(1-(e.*sin(MAP_VAR_LIST.rparallels)).^2);\n\t       q12=(1-e.^2)*(sin(MAP_VAR_LIST.rparallels)./(1-(e.*sin(MAP_VAR_LIST.rparallels)).^2) - ...\n\t            1./(2*e)*log((1-e.*sin(MAP_VAR_LIST.rparallels))./(1+e.*sin(MAP_VAR_LIST.rparallels))) );\n\t       q0= (1-e.^2)*(sin(MAP_VAR_LIST.rorigin(2))./(1-(e.*sin(MAP_VAR_LIST.rorigin(2))).^2) - ...\n\t            1./(2*e)*log((1-e.*sin(MAP_VAR_LIST.rorigin(2)))./(1+e.*sin(MAP_VAR_LIST.rorigin(2)))) );\n           if diff( MAP_VAR_LIST.rparallels )==0\n\t          MAP_VAR_LIST.n=sin(MAP_VAR_LIST.rparallels(1));\n           else\n\t          MAP_VAR_LIST.n=-diff(m12.^2)/diff(q12);\n           end\n\t       MAP_VAR_LIST.C=m12(1).^2 + MAP_VAR_LIST.n.*q12(1);\n\t       MAP_VAR_LIST.rho0=MAP_VAR_LIST.ellip(1)*sqrt(MAP_VAR_LIST.C-MAP_VAR_LIST.n*q0)/MAP_VAR_LIST.n;\t\n        end\n      case name(2)\n        if strcmp(MAP_VAR_LIST.ellipsoid,'normal')\n           if diff(MAP_VAR_LIST.parallels)==0\n             MAP_VAR_LIST.n=sin(MAP_VAR_LIST.rparallels(1));\n           else\n             MAP_VAR_LIST.n=-diff(log(cos(MAP_VAR_LIST.rparallels)))/diff(log(tan(MAP_VAR_LIST.rparallels/2+pi/4)));\n           end\n           MAP_VAR_LIST.F=cos(MAP_VAR_LIST.rparallels(1))/MAP_VAR_LIST.n* ...\n                \t  tan(pi/4+MAP_VAR_LIST.rparallels(1)/2).^MAP_VAR_LIST.n;\n           MAP_VAR_LIST.rho0=MAP_VAR_LIST.F/tan(pi/4+ MAP_VAR_LIST.rorigin(2)/2).^MAP_VAR_LIST.n;\n        else\n \t      e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n\t      m12=cos(MAP_VAR_LIST.rparallels)./sqrt(1-(e.*sin(MAP_VAR_LIST.rparallels)).^2);\n\t      t12=tan(pi/4-MAP_VAR_LIST.rparallels/2)./( (1-e*sin(MAP_VAR_LIST.rparallels))./(1+e*sin(MAP_VAR_LIST.rparallels)) ).^(e/2);\n\t      tF=tan(pi/4-MAP_VAR_LIST.rorigin(2)/2)./( (1-e*sin(MAP_VAR_LIST.rorigin(2)))./(1+e*sin(MAP_VAR_LIST.rorigin(2))) ).^(e/2);\n\t      if diff(MAP_VAR_LIST.rparallels)==0\n\t         MAP_VAR_LIST.n=sin(MAP_VAR_LIST.rparallels(1));\n          else   \n             MAP_VAR_LIST.n=diff(log(m12))/diff(log(t12));\n          end   \n\t      MAP_VAR_LIST.F=m12(1)/MAP_VAR_LIST.n/t12(1).^MAP_VAR_LIST.n;\n\t      MAP_VAR_LIST.rho0=MAP_VAR_LIST.ellip(1)*MAP_VAR_LIST.F*tF.^MAP_VAR_LIST.n;\n        end  \n    end\n\n    % check for a valid ellipsoid. if not, use the normalized sphere\n    \n    if ~isfield(MAP_ELLIP,MAP_VAR_LIST.ellipsoid)\n       MAP_VAR_LIST.ellipsoid = 'normal';\n    end\n\n    % Get X/Y and (if we are in a box) update the lat/long limits.\n\n    mu_util('xylimits');\n    if strcmp(MAP_VAR_LIST.rectbox,'on'),  mu_util('lllimits'); end\n\n\n  case 'll2xy'\n\n    long=varargin{1};\n    lat=varargin{2};\n    vals=zeros(size(long));\n    \n    % Clip out-of-range values (lat/long box)\n    \n    if ~strcmp(MAP_VAR_LIST.rectbox,'on') && ~strcmp(varargin{4},'off')\n        vals=vals | long<=MAP_VAR_LIST.longs(1)+eps*10 | long>=MAP_VAR_LIST.longs(2)-eps*10 | ...\n\t              lat<=MAP_VAR_LIST.lats(1)+eps*10 |   lat>=MAP_VAR_LIST.lats(2)-eps*10;\n        [long,lat]=mu_util('clip',varargin{4},long,MAP_VAR_LIST.longs(1),long<MAP_VAR_LIST.longs(1),lat);\n        [long,lat]=mu_util('clip',varargin{4},long,MAP_VAR_LIST.longs(2),long>MAP_VAR_LIST.longs(2),lat);\n        [lat,long]=mu_util('clip',varargin{4},lat,MAP_VAR_LIST.lats(1),lat<MAP_VAR_LIST.lats(1),long);\n        [lat,long]=mu_util('clip',varargin{4},lat,MAP_VAR_LIST.lats(2),lat>MAP_VAR_LIST.lats(2),long);\n    end\n\n    switch MAP_PROJECTION.name\n      case name(1)  \n        if MAP_VAR_LIST.ellip(2)==0   % spherical\n           rho=MAP_VAR_LIST.ellip(1)*sqrt(MAP_VAR_LIST.C-2*MAP_VAR_LIST.n*sin(lat*pi180))/MAP_VAR_LIST.n;\n        else\n\t       e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n\t       q= (1-e.^2)*(sin(lat*pi180)./(1-(e.*sin(lat*pi180)).^2) - ...\n\t            1./(2*e)*log((1-e.*sin(lat*pi180))./(1+e.*sin(lat*pi180))) );\n\t       rho=MAP_VAR_LIST.ellip(1)*sqrt(MAP_VAR_LIST.C-MAP_VAR_LIST.n*q)/MAP_VAR_LIST.n;\n        end  \n      case name(2)\n        if strcmp(MAP_VAR_LIST.ellipsoid,'normal')\n           lat(lat==-90)=-89.999; % Prevents /0 problems in next line\n           rho=MAP_VAR_LIST.F ./ tan(pi/4+lat*pi180/2).^MAP_VAR_LIST.n;\n        else\n\t       e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n\t       t=tan(pi/4-lat*pi180/2)./( (1-e*sin(lat*pi180))./(1+e*sin(lat*pi180)) ).^(e/2);\n\t       rho=MAP_VAR_LIST.ellip(1)*MAP_VAR_LIST.F*t.^MAP_VAR_LIST.n;\n        end \n    end\n    theta=MAP_VAR_LIST.n*(long-MAP_VAR_LIST.origin(1))*pi180;\n\n    X=real(rho.*sin(theta));    \n    Y=real(MAP_VAR_LIST.rho0-rho.*cos(theta));\n\n    % Clip out-of-range values (rectangular box)\n\n    if strcmp(MAP_VAR_LIST.rectbox,'on') && ~strcmp(varargin{4},'off')\n        vals= vals | X<=MAP_VAR_LIST.xlims(1)+eps*10 | X>=MAP_VAR_LIST.xlims(2)-eps*10 | ...\n                     Y<=MAP_VAR_LIST.ylims(1)+eps*10 | Y>=MAP_VAR_LIST.ylims(2)-eps*10;\n        [X,Y]=mu_util('clip',varargin{4},X,MAP_VAR_LIST.xlims(1),X<MAP_VAR_LIST.xlims(1),Y);\n        [X,Y]=mu_util('clip',varargin{4},X,MAP_VAR_LIST.xlims(2),X>MAP_VAR_LIST.xlims(2),Y);\n        [Y,X]=mu_util('clip',varargin{4},Y,MAP_VAR_LIST.ylims(1),Y<MAP_VAR_LIST.ylims(1),X);\n        [Y,X]=mu_util('clip',varargin{4},Y,MAP_VAR_LIST.ylims(2),Y>MAP_VAR_LIST.ylims(2),X);\n    end\n    if MAP_VAR_LIST.aussiemode, Y=-Y; X=-X; end\n\n\n  case 'xy2ll'\n\n    pi180=pi/180; \n    \n    if MAP_VAR_LIST.aussiemode, varargin{2}=-varargin{2}; varargin{1}=-varargin{1}; end\n    switch MAP_PROJECTION.name\n      case name(1)   \n        rho=sqrt(varargin{1}.^2+(MAP_VAR_LIST.rho0-varargin{2}).^2);\n        theta=atan(varargin{1}./(MAP_VAR_LIST.rho0-varargin{2}));\n        if  MAP_VAR_LIST.ellip(2)==0\n           Y=asin((MAP_VAR_LIST.C-(rho*MAP_VAR_LIST.n/MAP_VAR_LIST.ellip(1)).^2)/(2*MAP_VAR_LIST.n))/pi180;\n        else\n\t       e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n           q=(MAP_VAR_LIST.C - (rho.*MAP_VAR_LIST.n/MAP_VAR_LIST.ellip(1)).^2)./MAP_VAR_LIST.n;\t  \n\t       % Y is computed iteratively\n\t       Y=asin(q/2);\n\t       for k=1:4\n\t          Y=Y+(1-(e.*sin(Y)).^2).^2./(2*cos(Y)).*( q./(1-e.^2) - sin(Y)./(1-(e.*sin(Y)).^2) + ...\n\t             1./(2*e)*log( (1-e*sin(Y))./(1+e*sin(Y)) ) );\n           end\n\t       Y=Y/pi180; \n        end\n        % The pole is an arc in this projection, so for points inside that\n        % arc there is no inverse. If so, the math above can return complex\n        % values - instead set these to NaN\n        if ~isreal(Y)\n           Y(imag(Y)>1e-7)=NaN;\n           Y=real(Y); \n        end\n        \n      case name(2)\n        rho=sign(MAP_VAR_LIST.n)*sqrt(varargin{1}.^2+(MAP_VAR_LIST.rho0-varargin{2}).^2);\n        theta=atan(varargin{1}./(MAP_VAR_LIST.rho0-varargin{2}));\n\t    if strcmp(MAP_VAR_LIST.ellipsoid,'normal')\n           Y=(2*atan((MAP_VAR_LIST.F./rho).^(1/MAP_VAR_LIST.n))-pi/2)/pi180;\n        else\n\t       e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n\t       tp=(rho./MAP_VAR_LIST.ellip(1)/MAP_VAR_LIST.F).^(1./MAP_VAR_LIST.n);\n\t       % Y is computed iteratively\n\t       Y=pi/2 - 2*atan(tp);\n\t       for k=1:4\n\t         Y=pi/2 - 2*atan(tp.*((1-e*sin(Y))./(1+e*sin(Y))).^(e/2) );\n           end  \n\t       Y=Y/pi180;\n        end   \n    end\n    % Clip out-of-range values (lat/long box)\n    X=MAP_VAR_LIST.origin(1)+(theta/MAP_VAR_LIST.n)/pi180;\n\n  case 'xgrid'\n   \n    [X,Y,vals,labI]=mu_util('xgrid',MAP_VAR_LIST.longs,MAP_VAR_LIST.lats,varargin{1},3,varargin{2:3});\n\n  case 'ygrid'\n   \n    [X,Y,vals,labI]=mu_util('ygrid',MAP_VAR_LIST.lats,MAP_VAR_LIST.longs,varargin{1},31,varargin{2:3});\n\n  case 'box'\n\n    [X,Y]=mu_util('box',31);\n        \nend\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/private/mp_conic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.595148998205782}}
{"text": "function s = mean(f, dim)\n%MEAN   Average or mean value of a SPHEREFUN. \n%   MEAN(F) takes the mean in the latitude-direction (default), i.e., \n%          MEAN(F) = 1/pi sum(F).\n%\n%   MEAN(F, DIM) takes the mean along the direction DIM. If DIM = 1 it is the\n%   latitude-direction and if DIM = 2 then it is the longitude-direction.\n%\n% See also SPHEREFUN/MEAN2, SPHEREFUN/STD2.\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    s = chebfun;\n    return\nend \n\nif ( nargin == 1) \n    % Default to the y-direction:\n    dim = 1;    \nend\ndom = f.domain;\n\ns = sum( f, dim ); \nif ( dim == 1 )\n    s = s / pi; % Mean in the latitude direction (default)\nelseif ( dim == 2 )\n    s = s / (2*pi); % Mean in the longitude direction\nelse\n    error('CHEBFUN:SPHEREFUN:mean:dim', ...\n        'Mean not in longitude (LAMBDA) or latitude (THETA) direction.')\nend\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/@spherefun/mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633915959134572, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5951406875698041}}
{"text": "\n%%% Extraction of the final intrinsic and extrinsic paramaters:\n\ncheck_active_images;\n\nif ~exist('solution_error')\n   solution_error = zeros(6*n_ima + 15,1);\nend;\n\nfc = solution(1:2);%***\ncc = solution(3:4);%***\nalpha_c = solution(5);%***\nkc = solution(6:10);%***\n\nfc_error = solution_error(1:2);\ncc_error = solution_error(3:4);\nalpha_c_error = solution_error(5);\nkc_error = solution_error(6:10);\n\n% Calibration matrix:\n\t\nKK = [fc(1) fc(1)*alpha_c cc(1);0 fc(2) cc(2); 0 0 1];\ninv_KK = inv(KK);\n\n% Extract the extrinsic paramters, and recomputer the collineations\n\nfor kk = 1:n_ima,\n   \n   if active_images(kk),   \n      \n      omckk = solution(15+6*(kk-1) + 1:15+6*(kk-1) + 3);%***   \n      Tckk = solution(15+6*(kk-1) + 4:15+6*(kk-1) + 6);%*** \n      \n      omckk_error = solution_error(15+6*(kk-1) + 1:15+6*(kk-1) + 3); \n      Tckk_error = solution_error(15+6*(kk-1) + 4:15+6*(kk-1) + 6);\n      \n   \tRckk = rodrigues(omckk);\n   \n   \tHkk = KK * [Rckk(:,1) Rckk(:,2) Tckk];\n   \n   \tHkk = Hkk / Hkk(3,3);\n      \n   else\n      \n      omckk = NaN*ones(3,1);   \n      Tckk = NaN*ones(3,1);\n      Rckk = NaN*ones(3,3);\n      Hkk = NaN*ones(3,3);\n      omckk_error = NaN*ones(3,1);\n      Tckk_error = NaN*ones(3,1);\n      \n   end;\n   \n   eval(['omc_' num2str(kk) ' = omckk;']);\n   eval(['Rc_' num2str(kk) ' = Rckk;']);\n   eval(['Tc_' num2str(kk) ' = Tckk;']);\n   eval(['H_' num2str(kk) '= Hkk;']);\n   eval(['omc_error_' num2str(kk) ' = omckk_error;']);\n   eval(['Tc_error_' num2str(kk) ' = Tckk_error;']);\n   \nend;\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/extract_parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5951406758837721}}
{"text": "function GMST=TAI2GAST(Jul1,Jul2,version,deltaT)\n%%TAI2GAST Convert from international atomic time (TAI) to Greenwhich\n%          apparent sidereal time (GAST), which is a measure of the\n%          rotational direction of the Earth.\n%\n%INPUTS: Jul1,Jul2 Two parts of a pseudo-Julian date given in TAI. The\n%                  units of the date are days. The full date is the sum of\n%                  both terms. The date is broken into two parts to\n%                  provide more bits of precision. It does not matter how\n%                  the date is split.\n%          version An optional integer specifying the theory to use for\n%                  GMST. The theory chosen should be consistent with other\n%                  values used in astronomical routines. Possible values\n%                  are\n%                  1982 Compute GAST ion accordance with the International\n%                     Astronomical Union's (IAU's) 1982 model.\n%                  2000 Compute GMST in line with IAU 2000 resolutions\n%                     related to precession and nutation.\n%                  2006 (The default if omitted) Compute GMST in line with\n%                     IAU 2006 resolutions related to precession and\n%                     nutation.\n%           deltaT An optional parameter specifying the offset between TT\n%                  and UT1 in seconds. If this parameter is omitted, then\n%                  the value of the function getEOP will be used.\n%\n%OUTPUTS: GAST The Greenwhich apparent sideral time in radians. \n%\n%The function just calls TAI2TT and then TT2GAST.\n%\n%GAST is defined in Section 5.5.7 of [1].\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%April 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n[Jul1,Jul2]=TAI2TT(Jul1,Jul2);\n\nif(nargin==2)\n    GMST=TT2GAST(Jul1,Jul2);\nelseif(nargin==3)\n    GMST=TT2GAST(Jul1,Jul2,version);\nelse\n    GMST=TT2GAST(Jul1,Jul2,version,deltaT);\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/Time/TAI2GAST.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5951406710378421}}
{"text": "function M = euclideanfactory(m, n)\n% Returns a manifold struct to optimize over m-by-n matrices.\n%\n% function M = euclideanfactory(m, n)\n%\n% Returns M, a structure describing the Euclidean space of m-by-n matrices\n% equipped with the standard Frobenius distance and associated trace inner\n% product as a manifold for Manopt.\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%  July 5, 2013 (NB): added egred2rgrad, ehess2rhess, mat, vec, tangent.\n\n    \n    if ~exist('n', 'var') || isempty(n)\n        n = 1;\n    end\n\n    M.name = @() sprintf('Euclidean space R^(%dx%d)', m, n);\n    \n    M.dim = @() m*n;\n    \n    M.inner = @(x, d1, d2) d1(:).'*d2(:);\n    \n    M.norm = @(x, d) norm(d, 'fro');\n    \n    M.dist = @(x, y) norm(x-y, 'fro');\n    \n    M.typicaldist = @() sqrt(m*n);\n    \n    M.proj = @(x, d) d;\n    \n    M.egrad2rgrad = @(x, g) g;\n    \n    M.ehess2rhess = @(x, eg, eh, d) eh;\n    \n    M.tangent = M.proj;\n    \n    M.exp = @exp;\n    function y = exp(x, d, t)\n        if nargin == 3\n            y = x + t*d;\n        else\n            y = x + d;\n        end\n    end\n    \n    M.retr = M.exp;\n\t\n\tM.log = @(x, y) y-x;\n\n    M.hash = @(x) ['z' hashmd5(x(:))];\n    \n    M.rand = @() randn(m, n);\n    \n    M.randvec = @randvec;\n    function u = randvec(x) %#ok<INUSD>\n        u = randn(m, n);\n        u = u / norm(u, 'fro');\n    end\n    \n    M.lincomb = @lincomb;\n    function v = lincomb(x, a1, d1, a2, d2) %#ok<INUSL>\n        if nargin == 3\n            v = a1*d1;\n        elseif nargin == 5\n            v = a1*d1 + a2*d2;\n        else\n            error('Bad usage of euclidean.lincomb');\n        end\n    end\n    \n    M.zerovec = @(x) zeros(m, n);\n    \n    M.transp = @(x1, x2, d) d;\n    \n    M.pairmean = @(x1, x2) .5*(x1+x2);\n    \n    M.vec = @(x, u_mat) u_mat(:);\n    M.mat = @(x, u_vec) reshape(u_vec, [m, n]);\n    M.vecmatareisometries = @() true;\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/manopt/manopt/manifolds/euclidean/euclideanfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5951024223104188}}
{"text": "function results = vl_test_hog(varargin)\n% VL_TEST_HOG\nvl_test_init ;\n\nfunction s = setup()\ns.im = im2single(vl_impattern('roofs1')) ;\n[x,y]= meshgrid(linspace(-1,1,128)) ;\ns.round = single(x.^2+y.^2);\ns.imSmall = s.im(1:128,1:128,:) ;\ns.imSmall = s.im ;\ns.imSmallFlipped = s.imSmall(:,end:-1:1,:) ;\n\nfunction test_basic_call(s)\ncellSize = 8 ;\nhog = vl_hog(s.im, cellSize) ;\n\nfunction test_bilinear_orientations(s)\ncellSize = 8 ;\nvl_hog(s.im, cellSize, 'bilinearOrientations') ;\n\nfunction test_variants_and_flipping(s)\nvariants = {'uoctti', 'dalaltriggs'} ;\nnumOrientationsRange = 3:9 ;\ncellSize = 8 ;\n\nfor cellSize = [4 8 16]\n  for i=1:numel(variants)\n    for j=1:numel(numOrientationsRange)\n      args = {'bilinearOrientations', ...\n              'variant', variants{i}, ...\n              'numOrientations', numOrientationsRange(j)} ;\n      hog = vl_hog(s.imSmall, cellSize, args{:}) ;\n      perm = vl_hog('permutation', args{:}) ;\n      hog1 = vl_hog(s.imSmallFlipped, cellSize, args{:}) ;\n      hog2 = hog(:,end:-1:1,perm) ;\n      %norm(hog1(:)-hog2(:))\n      vl_assert_almost_equal(hog1,hog2,1e-3) ;\n    end\n  end\nend\n\nfunction test_polar(s)\ncellSize = 8 ;\nim = s.round ;\nfor b = [0 1]\n  if b\n    args = {'bilinearOrientations'} ;\n  else\n    args = {} ;\n  end\n  hog1 = vl_hog(im, cellSize, args{:}) ;\n  [ix,iy] = vl_grad(im) ;\n  m = sqrt(ix.^2 + iy.^2) ;\n  a = atan2(iy,ix) ;\n  m(:,[1 end]) = 0 ;\n  m([1 end],:) = 0 ;\n  hog2 = vl_hog(cat(3,m,a), cellSize, 'DirectedPolarField', args{:}) ;\n  vl_assert_almost_equal(hog1,hog2,norm(hog1(:))/1000) ;\nend\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/dependencies/vlfeat-0.9.16/toolbox/xtest/vl_test_hog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5951024223104188}}
{"text": "function jed = transition_to_jed_common ( )\n\n%*****************************************************************************80\n%\n%% TRANSITION_TO_JED_COMMON returns the Common calendar transition as a JED.\n%\n%  Discussion:\n%\n%    In the Common calendar, the last moment of the Julian calendar was\n%      11:59 pm, 4 October 1582 Julian/CE,\n%      11:59 pm, 14 October 1582 Gregorian.\n%    The first minute of the Gregorian calendar ended at\n%      12:01 am, 5 October 1582 Julian,\n%      12:01 am, 15 October 1582 Gregorian/CE.\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%  Parameters:\n%\n%    Output, real JED, the Julian Ephemeris Date of the date.\n%\n  jed = 2299160.5;\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/calpak/transition_to_jed_common.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.5951024180147967}}
{"text": "function [best,curSel] = findWeakRuleSamples(data,labels,dist,binVals,bins,params)\n\nnumDim = size(data,2);\n\nbest.dim = 1;\nbest.error = 0.5;\nbest.dir = 1;\nbest.tr = 0;\n\n% curBestErr = 0.5*ones(1,numDim);\n% binNo = ones(1,numDim);\n% bestDir = ones(1,numDim);\n\nnumS = params.numSample;\n\n% KB: only sample if it is helpful\ndosample = numS < numel(dist);\n\n% always helpful to normalize\ndist = dist / sum(dist);\n\n\n% fot testing\n% for dosample = [false,true],\n%   \n%   niters = 100;\n%   \n%   tic;\n%   for iter = 1:niters,\n\n\nif dosample,\n  \n  % KB: copied from randsample\n  edges = min([0 cumsum(dist')],1); % protect against accumulated round-off\n  edges(end) = 1; % get the upper edge exact\n  [~,curSel] = histc(rand(numS,1),edges);\n  \n  if any(curSel==0),\n    warning('Sanity check: some samples are not being chosen');\n    curSel(curSel==0) = size(data,1);\n  end\n  \n  curBins = bins(:,curSel);\n  curLabels = labels(curSel);\n\nelse\n  \n  curBins = bins;\n  curLabels = labels;\n  curSel = true(size(labels));\nend\n\n% KB: precompute these\nnumBins = size(binVals,1)+1;\n% indices with positive labels\nidxpos = curLabels > 0;\n\n% always normalize histograms by Z\nif dosample,\n  Z = size(curBins,2);\n  Zpos = nnz(idxpos);\nelse\n  Z = sum(dist);\n  Zpos = sum(dist(idxpos));\nend\nZneg = Z - Zpos;\n\nfracpos = Zpos/Z;\nfracneg = Zneg/Z;\n\nif dosample,\n  \n\n  posCount = accummatrix(curBins(:,idxpos)',ones(Zpos,1),numBins)'/Z;\n  negCount = accummatrix(curBins(:,~idxpos)',ones(Zneg,1),numBins)'/Z;\n  \n%   posCount = histc(curBins(:,idxpos),edges,2);\n%   posCount = posCount(:,1:end-1) / Z;\n%   negCount = histc(curBins(:,~idxpos),edges,2);\n%   negCount = negCount(:,1:end-1) / Z;\n\nelse\n\n  % weighted histogram, loop-free version\n\n  posCount = accummatrix(curBins(:,idxpos)',dist(idxpos),numBins)';\n  negCount = accummatrix(curBins(:,~idxpos)',dist(~idxpos),numBins)';\n  \n  \nend\n\nposLeft = cumsum(posCount,2);\nposRight = fracpos - posLeft;\nnegLeft = cumsum(negCount,2);\nnegRight = fracneg - negLeft;\n\nbinErr = posRight+negLeft-posLeft-negRight;\nnegErr = binErr<0;\nbinErr(negErr) = -binErr(negErr);\ndir = ones(numDim,numBins);\ndir(negErr) = -1;\nerr = 0.5-binErr/2;\n[curBestErr,binNo]= min(err(:,1:end-1),[],2);\ncurBestErr = curBestErr'; binNo = binNo';\nbestDir = dir(sub2ind([numDim,numBins],1:numDim,binNo));\n\n[minError minDim] = min(curBestErr); %#ok<UDIM>\nbest.error = minError;   best.dim = minDim; \nbest.dir = bestDir(minDim);   best.tr = binVals(binNo(minDim),minDim);\n\n%   end\n%   \n%   fprintf('dosample = %d, time = %f\\n',dosample,toc);\n%   \n% end\n\nend\n\n%{\nfunction [predError dir] = getError(data,label,tr, dist)\n\ndir = 1;\npredLabel = 2*(data>tr)-1;\npredError = sum(( (predLabel.*label) ~=1).*dist);\n\nif(predError>0.5); predError = 1-predError; dir = -1; end\nend\n%}\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/findWeakRuleSamples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.5950582652586623}}
{"text": "function f = testfcn1(x)\n\nif strcmpi(x,'init')\n    f.options.PopInitRange = [0, 0; 4, 4] ;\n    f.options.Vectorized = 'on' ;\n    f.options.HybridFcn = {} ;\n    f.options.Generations = 500 ;\n    f.options.ConstrBoundary = 'penalize' ;\n    f.LB = [0,0] ; f.UB = [] ;\n    f.Aeq = [] ; f.beq = [] ;\n    f.Aineq = [-1 0] ; f.bineq = [-0.01] ;\n%     f.Aineq = [] ; f.bineq = [] ;\n    f.nonlcon = [] ;\nelse\n    a = 1 ; b = 0.01 ;\n    f = (x(:,1).^b + x(:,2).^(1-b)).^a ;\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/psopt/testfcns/testfcn1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5950582652586622}}
{"text": "% design and visualize arrays\nclear(); close all;\n\nwavelength = 1; % normalized\nd = wavelength / 2;\ndesign_ula = design_array_1d('ula', 12, d);\ndesign_cp = design_array_1d('coprime', [4 5], d);\ndesign_nested = design_array_1d('nested', [5 7], d);\ndesign_mra = design_array_1d('mra', 12, d);\n\nvisualize_array(design_ula, 'VisualizeCoarray', true);\nvisualize_array(design_cp, 'VisualizeCoarray', true);\nvisualize_array(design_nested, 'VisualizeCoarray', true);\nvisualize_array(design_mra, 'VisualizeCoarray', true);", "meta": {"author": "morriswmz", "repo": "doa-tools", "sha": "76c1cb7f365615d719fbb050c7ea52b616a28c33", "save_path": "github-repos/MATLAB/morriswmz-doa-tools", "path": "github-repos/MATLAB/morriswmz-doa-tools/doa-tools-76c1cb7f365615d719fbb050c7ea52b616a28c33/examples/ex1_design_and_visualize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.595058264526862}}
{"text": "% File: RecognizeActions.m\n%\n% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n\nfunction [accuracy, predicted_labels] = RecognizeActions(datasetTrain, datasetTest, G, maxIter)\n\n% INPUTS\n% datasetTrain: dataset for training models, see PA for details\n% datasetTest: dataset for testing models, see PA for details\n% G: graph parameterization as explained in PA decription\n% maxIter: max number of iterations to run for EM\n\n% OUTPUTS\n% accuracy: recognition accuracy, defined as (#correctly classified examples / #total examples)\n% predicted_labels: N x 1 vector with the predicted labels for each of the instances in datasetTest, with N being the number of unknown test instances\n\n\n% Train a model for each action\n% Note that all actions share the same graph parameterization and number of max iterations\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% YOUR CODE HERE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n[P1 logli1 ClassProb1 PairProb1] = EM_HMM(datasetTrain(1).actionData, datasetTrain(1).poseData, G, datasetTrain(1).InitialClassProb, datasetTrain(1).InitialPairProb, maxIter);\n\n\n[P2 logli2 ClassProb2 PairProb2] = EM_HMM(datasetTrain(2).actionData, datasetTrain(2).poseData, G, datasetTrain(2).InitialClassProb, datasetTrain(2).InitialPairProb, maxIter);\n\n\n[P3 logli3 ClassProb3 PairProb3] = EM_HMM(datasetTrain(3).actionData, datasetTrain(3).poseData, G, datasetTrain(3).InitialClassProb, datasetTrain(3).InitialPairProb, maxIter);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% Classify each of the instances in datasetTest\n% Compute and return the predicted labels and accuracy\n% Accuracy is defined as (#correctly classified examples / #total examples)\n% Note that all actions share the same graph parameterization\n\naccuracy = 0;\npredicted_labels = [];\nP = [P1,P2,P3];\nN = size(datasetTest.poseData,1);\nI = size(datasetTest.labels,1);\nK = 3;\nloglikelihood = zeros(I,3);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% YOUR CODE HERE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfor iclass = 1:3\n  logEmissionProb = zeros(N,K);\n  \n  for i = 1:N\n\t  data = reshape(datasetTest.poseData(i,:,:),10,3);\n\t  for j = 1:10\n\t\t  if G(j,1) == 1\n\t\t\t  parent = data(G(j,2),:);\n\t\t\t  for k = 1:K\n\t\t\t\t  theta = P(iclass).clg(j).theta(k,:);\n\t\t\t\t  mu_y = sum(theta(1:4).*[1,parent]);\n\t\t\t\t  mu_x = sum(theta(5:8).*[1,parent]);\n\t\t\t\t  mu_a = sum(theta(9:12).*[1,parent]);\n\t\t\t\t  logEmissionProb(i,k) += lognormpdf(data(j,1),mu_y,P(iclass).clg(j).sigma_y(k));\n\t\t\t\t  logEmissionProb(i,k) += lognormpdf(data(j,2),mu_x,P(iclass).clg(j).sigma_x(k));\n\t\t\t\t  logEmissionProb(i,k) += lognormpdf(data(j,3),mu_a,P(iclass).clg(j).sigma_angle(k));\n\t\t\t  end\n\t\t  else\n\t\t\t  for k = 1:K\n\t\t\t\t  logEmissionProb(i,k) += lognormpdf(data(j,1),P(iclass).clg(j).mu_y(k),P(iclass).clg(j).sigma_y(k));\n\t\t\t\t  logEmissionProb(i,k) += lognormpdf(data(j,2),P(iclass).clg(j).mu_x(k),P(iclass).clg(j).sigma_x(k));\n\t\t\t\t  logEmissionProb(i,k) += lognormpdf(data(j,3),P(iclass).clg(j).mu_angle(k),P(iclass).clg(j).sigma_angle(k));\n\t\t\t  end\n\t\t  end\n\t  end\n  end\n\n  for i = 1:I\n\t  % construct all the three types of factors for each action and do inference to fill ClassProb and PairProb\n\t  m = length(datasetTest.actionData(i).marg_ind); % 1 to m represents S variables\n\t  F = repmat(struct('var',[],'card',[],'var',[]),1,2*m); % 1 is P(S1), 2 to m is P(Si/Si-1) and m+1 to 2m P(S/O)\n\t  F(1).var = 1; F(1).card = [K];F(1).val = log(P(iclass).c);\n\t  temp = log(reshape(P(iclass).transMatrix',1,9));\n\t  for j = 2:m\n\t\t  F(j).var = [j j-1]; F(j).card = [K K]; F(j).val = temp;\n\t  end\n\t  for j = 1:m\n\t\t  F(j+m).var = [j];F(j+m).card = [K];\n\t\t  F(j+m).val = logEmissionProb(datasetTest.actionData(i).marg_ind(j),:);\n\t  end\n\t  [M, PCalibrated] = ComputeExactMarginalsHMM(F);\n\t  loglikelihood(i,iclass) += logsumexp(PCalibrated.cliqueList(1).val);\n  end\nend\n[temp, predicted_labels] = max(loglikelihood,[],2);\naccuracy = sum(predicted_labels==datasetTest.labels)/I;\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/9.Learnign with Incomplete Data/RecognizeActions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5950582594235535}}
{"text": "% Test file for @deltafun/times.m.\n\nfunction pass = test_times(pref)\n\nif (nargin < 1)\n    pref = chebfunpref();\nend\n%%\n% Get the tolerance:\ndTol = pref.deltaPrefs.deltaTol;\n\nd = deltafun(bndfun(@sin), struct('deltaMag', 1, 'deltaLoc', 0));\npass(1) = isempty(deltafun() .* deltafun());\npass(2) = isempty(deltafun() .* d) && isempty(d .* deltafun());\n\nf = fun.constructor(@(x) exp(-x));\ng = bndfun(@sin);\ndf1 = deltafun(f, []);\ndf2 = deltafun(g, struct('deltaMag', [0; 0; 0; 0; 1], 'deltaLoc', 0));\ns = df1.*df2;\npass(3) = norm(s.deltaMag - [1, 4, 6, 4, 1].', inf) < dTol;\n\nf = fun.constructor(@(x) exp(x));\ng = bndfun(@sin);\ndf1 = deltafun(f, []);\ndf2 = deltafun(g, struct('deltaMag', [0; 0; 0; 1], 'deltaLoc', 0));\ns = df1.*df2;\npass(4) = norm(s.deltaMag - [-1, 3, -3, 1].', inf) < dTol;\n\na = -4;\nb = 4;\n\nf1 = fun.constructor(@(x) exp(sin(x)), struct('domain', [a, b]));\nd1 = .5*[0 1 0;\n         0 1 0;\n         1 0 1; ];\nl1 = sort(.9*(a + (b-a)/2*rand(1,3)));\n\nf2 = fun.constructor(@(x) exp(cos(x)), struct('domain', [a, b]));\n\ndf1 = deltafun(f1, struct('deltaMag', d1, 'deltaLoc', l1));\ndf2 = deltafun(f2, []);\n\ns = df1 .* df2;\npass(5) = iszero(s.funPart - f1.*f2);\npass(6) = norm(s.deltaLoc - sort(l1), inf) == 0;\n\nc1 = [ feval(diff(f2,2), l1(1));\n       -2*feval(diff(f2,1), l1(1));\n       feval(diff(f2,0), l1(1));    ];\n\nc2 = [ feval(diff(f2,0)-diff(f2,1), l1(2));\n       feval(diff(f2,0), l1(2));\n       0;                       ];\n       \nc3 = [feval(diff(f2,2), l1(3));\n      -2*feval(diff(f2,1), l1(3));\n      feval(diff(f2,0), l1(3))];\n\ndeltas1 = .5*[c1, c2, c3];\n\nerr = s.deltaMag - deltas1;\npass(7) = norm(err(:), inf) < dTol;\n    \n\nd2 = .8*[1 0 1;\n         0 1 0;\n         0 1 0; ];\nl2 =  .0010751808168034 + sort(.9*(b-a)/2*rand(1,3));\ndf2 = deltafun(f2, struct('deltaMag', d2, 'deltaLoc',l2));\n%%\ns = df1 .* df2;\npass(8) = iszero(s.funPart - f1.*f2);\npass(9) = norm(s.deltaLoc - sort(union(l1,l2)), inf) == 0;\n%%\nc1 = [ feval(diff(f1,0), l2(1));\n       0;\n       0; ];\nc2 = [ feval(diff(f1, 2)-diff(f1, 1), l2(2));\n       feval(diff(f1, 0)-2*diff(f1, 1), l2(2));\n       feval(diff(f1, 0), l2(2));  ];\n       \nc3 = [feval(diff(f1,0), l2(3));\n      0;\n      0; ];\n\ndeltas2 = .8*[c1, c2, c3];\n\nerr = [deltas1, deltas2] - s.deltaMag;\npass(10) = norm(err(:), inf) < dTol;\n%%\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/deltafun/test_times.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5950582594235535}}
{"text": "function [rp,nodenew,elemnew] = recoverP02P1(node,elem,p,recoverMethod)\n%% recoverP\n% Recover the pressure from barycenter to the node.\n% The recover methods\n% 1) 'LS': least square\n% 2) 'LA': solve the Laplacian problem, only this method\n%           the new node and new elem will be constructed.\n%\n% Created by Lin Zhong April, 2013. \n\nif ~exist('recoveryMethod','var')\n    recoverMethod = 'LA';\nend\nNT = size(elem,1);\nN = size(node,1);\nrp = zeros(N,1);\n% baycenter\nxnode = 1/3*(node(elem(:,1),:) + node(elem(:,2),:) + node(elem(:,3),:));\nNT2N = sparse(repmat(1:NT,1,3),[elem(:,1);elem(:,2);elem(:,3)],true,NT,N);\n \nif strcmp(recoverMethod,'LS') \n    % least square fit for every node\n    for i = 1:N\n        tempx = xnode(NT2N(:,i),:);\n        tempp = p(NT2N(:,i));\n        tempn = size(tempx,1);\n        if tempn == 1\n            rp(i) = tempp;\n        elseif tempn == 2\n            rp(i) = mean(tempp);\n        else\n            X = ones(tempn,3);\n            X(:,1:2) = tempx;\n            coefficient = (X'*X)\\(X'*tempp);\n            rp(i) = node(i,:)*coefficient(1:2) +coefficient(3);\n        end\n    end\nend\n\nif strcmp(recoverMethod,'LA')\n    T = auxstructure(elem);\n    edge = T.edge;\n    edge2elem = T.edge2elem;\n    %% find the boundary edge   \n    isbdEdge = (edge2elem(:,1) == edge2elem(:,2));\n    freeEdgeidx = find(~isbdEdge);\n    bdEdge = edge(isbdEdge,:);\n    freeEdge = edge(freeEdgeidx,:);\n\n    NE = size(edge,1);\n    NEbd = size(bdEdge,1);\n    NEin = NE - NEbd;\n    NTnew = 2*NEin;\n    elemnew = zeros(NTnew,3);\n    nodenew = [node; xnode];\n    %% find the corner point\n    acubdNode = accumarray([bdEdge(:,1);bdEdge(:,2)], 1, [N 1]);\n    bdNodeIdx = find(acubdNode);\n    freeNodeIdx = find(~acubdNode);\n    bdNode = node(bdNodeIdx);\n    NbdNode = size(bdNode,1);\n    \n    % new elems corresponding to the boundary edges\n%     elemnew(1:NEbd,:) = [bdEdge(:,1) bdEdge(:,2) N+edge2elem(isbdEdge,1)];   \n\n    % new elems corresponding to the interior edges\n    elemnew(1:NEin,:) = [freeEdge(:,1) N+edge2elem(freeEdgeidx,1) N+edge2elem(freeEdgeidx,2)];\n    elemnew(NEin+1:end,:) = [freeEdge(:,2) N+edge2elem(freeEdgeidx,1) N+edge2elem(freeEdgeidx,2)];\n    \n%   A = assemblematrix(nodenew,elemnew,1);\n    %------- construc stiffness matrix-------------\n    A11 = sparse(N,N);\n    A12 = sparse(N,NT);\n    [Dlambda,area] = gradbasis(nodenew,elemnew);\n    % the original node \n    ii = double(elemnew(:,1));\n    DiDi =area.*dot(Dlambda(:,:,1),Dlambda(:,:,1),2);\n    A11 = A11 +sparse(ii,ii,DiDi,N,N);\n    % the original node and the new nodes\n    for j = 2:3\n        jj = double(elemnew(:,j)-N);\n        DiDj =area.*dot(Dlambda(:,:,1),Dlambda(:,:,j),2);\n        A12 = A12 +sparse(ii,jj,DiDj,N,NT);\n    end\n    A = [A11 A12];\n    %------------------------------------------\n    rp(freeNodeIdx) = (-A(freeNodeIdx,N+1:end)*p)./diag(A(freeNodeIdx,freeNodeIdx));\n    \n    % use least square to recover the boundary nodes\n    for i = 1:NbdNode\n        ii = bdNodeIdx(i);\n        tempx = xnode(NT2N(:,ii),:);\n        tempp = p(NT2N(:,ii));\n        tempn = size(tempx,1);\n        if tempn == 1\n            rp(ii) = tempp;\n        elseif tempn == 2\n            rp(ii) = mean(tempp);\n        else\n            X = ones(tempn,3);\n            X(:,1:2) = tempx;\n            coefficient = (X'*X)\\(X'*tempp);\n            rp(ii) = node(ii,:)*coefficient(1:2) +coefficient(3);\n        end\n    end\nend  \nend\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/fem/recoverP02P1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5950582528566439}}
{"text": "function [Yl,Yh,Yscale] = dtwavexfm2(X,nlevels,biort,qshift);\n\n% Function to perform a n-level DTCWT-2D decompostion on a 2D matrix X\n%\n% [Yl,Yh,Yscale] = dtwavexfm2(X,nlevels,biort,qshift);\n%\n%     X -> 2D real matrix/Image\n%\n%     nlevels -> No. of levels of wavelet decomposition\n%\n%     biort ->  'antonini'   => Antonini 9,7 tap filters.\n%               'legall'     => LeGall 5,3 tap filters.\n%               'near_sym_a' => Near-Symmetric 5,7 tap filters.\n%               'near_sym_b' => Near-Symmetric 13,19 tap filters.\n%\n%     qshift -> 'qshift_06' => Quarter Sample Shift Orthogonal (Q-Shift) 10,10 tap filters, \n%                              (only 6,6 non-zero taps).\n%               'qshift_a' =>  Q-shift 10,10 tap filters,\n%                              (with 10,10 non-zero taps, unlike qshift_06).\n%               'qshift_b' => Q-Shift 14,14 tap filters.\n%               'qshift_c' => Q-Shift 16,16 tap filters.\n%               'qshift_d' => Q-Shift 18,18 tap filters.\n%               \n%\n%     Yl     -> The real lowpass image from the final level\n%     Yh     -> A cell array containing the 6 complex highpass subimages for each level.\n%     Yscale -> This is an OPTIONAL output argument, that is a cell array containing \n%               real lowpass coefficients for every scale.\n%\n% \n% Example: [Yl,Yh] = dtwavexfm2(X,3,'near_sym_b','qshift_b');\n% performs a 3-level transform on the real image X using the 13,19-tap filters \n% for level 1 and the Q-shift 14-tap filters for levels >= 2.\n%\n% Nick Kingsbury and Cian Shaffrey\n% Cambridge University, Sept 2001\n\n\nif isstr(biort) & isstr(qshift)\t\t%Check if the inputs are strings\n   biort_exist = exist([biort '.mat']);\n   qshift_exist = exist([qshift '.mat']);\n   if biort_exist == 2 & qshift_exist == 2;        \t\t%Check to see if the inputs exist as .mat files\n      load (biort);\n      load (qshift);\n   else\n      error('Please enter the correct names of the Biorthogonal or Q-Shift Filters, see help DTWAVEXFM2 for details.');\n   end\nelse\n   error('Please enter the names of the Biorthogonal or Q-Shift Filters as shown in help DTWAVEXFM2.');\nend \n\norginal_size = size(X);\n\nif ndims(X) >= 3;\n   error(sprintf('The entered image is %dx%dx%d, please enter each image slice separately.',orginal_size(1),orginal_size(2),orginal_size(3)));\nend\n\n% The next few lines of code check to see if the image is odd in size, if so an extra ...\n% row/column will be added to the bottom/right of the image\ninitial_row_extend = 0;  %initialise\ninitial_col_extend = 0;\nif any(rem(orginal_size(1),2)), %if sx(1) is not divisable by 2 then we need to extend X by adding a row at the bottom\n   X = [X; X(end,:)];           %Any further extension will be done in due course.\n   initial_row_extend = 1;\nend\nif any(rem(orginal_size(2),2)), \t%if sx(2) is not divisable by 2 then we need to extend X by adding a col to the left\n   X = [X X(:,end)];          %Any further extension will be done in due course.\n   initial_col_extend = 1;\nend\nextended_size = size(X);\n\nif nlevels == 0, return; end\n\n%initialise\nYh=cell(nlevels,1);\nif nargout == 3\n   Yscale=cell(nlevels,1);   %this is only required if the user specifies a third output component.\nend\n\nS = [];\nsx = size(X);\nif nlevels >= 1,\n   \n   % Do odd top-level filters on cols.\n   Lo = colfilter(X,h0o).';\n   Hi = colfilter(X,h1o).';\n   \n   % Do odd top-level filters on rows.\n   LoLo = colfilter(Lo,h0o).';\t\t\t% LoLo\n   Yh{1} = zeros([size(LoLo)/2  6]);\n   Yh{1}(:,:,[1 6]) = q2c(colfilter(Hi,h0o).');\t\t\t% Horizontal pair\n   Yh{1}(:,:,[3 4]) = q2c(colfilter(Lo,h1o).');\t\t\t% Vertical pair\n   Yh{1}(:,:,[2 5]) = q2c(colfilter(Hi,h1o).');\t      % Diagonal pair\n   S = [ size(LoLo) ;S];\n   if nargout == 3\n      Yscale{1} = LoLo;\n   end\nend\n\nif nlevels >= 2;\n   for level = 2:nlevels;\n      [row_size col_size] = size(LoLo);\n      if any(rem(row_size,4)),\t\t% Extend by 2 rows if no. of rows of LoLo are divisable by 4;\n         LoLo = [LoLo(1,:); LoLo; LoLo(end,:)];\n      end \n      if any(rem(col_size,4)),\t\t% Extend by 2 cols if no. of cols of LoLo are divisable by 4;\n         LoLo = [LoLo(:,1)  LoLo  LoLo(:,end)];\n      end \n      \n      % Do even Qshift filters on rows.\n      Lo = coldfilt(LoLo,h0b,h0a).';\n      Hi = coldfilt(LoLo,h1b,h1a).';\n      \n      % Do even Qshift filters on columns.\n      LoLo = coldfilt(Lo,h0b,h0a).';\t%LoLo\n      Yh{level} = zeros([size(LoLo)/2  6]);\n      Yh{level}(:,:,[1 6]) = q2c(coldfilt(Hi,h0b,h0a).');\t% Horizontal\n      Yh{level}(:,:,[3 4]) = q2c(coldfilt(Lo,h1b,h1a).');\t% Vertical\n      Yh{level}(:,:,[2 5]) = q2c(coldfilt(Hi,h1b,h1a).');\t% Diagonal   \n      S = [ size(LoLo) ;S];\n      if nargout == 3\n         Yscale{level} = LoLo;\n      end\n   end\nend\n\nYl = LoLo;\n\nif initial_row_extend == 1 & initial_col_extend == 1;\n   warning(sprintf(' \\r\\r The image entered is now a %dx%d NOT a %dx%d \\r The bottom row and rightmost column have been duplicated, prior to decomposition. \\r\\r ',...\n      extended_size(1),extended_size(2),orginal_size(1),orginal_size(2)));\nend\n\nif initial_row_extend == 1 ;\n   warning(sprintf(' \\r\\r The image entered is now a %dx%d NOT a %dx%d \\r Row number %d has been duplicated, and added to the bottom of the image, prior to decomposition. \\r\\r',...\n      extended_size(1),extended_size(2),orginal_size(1),orginal_size(2),orginal_size(1)));\nend\n\nif initial_col_extend == 1;\n   warning(sprintf(' \\r\\r The image entered is now a %dx%d NOT a %dx%d \\r Col number %d has been duplicated, and added to the right of the image, prior to decomposition. \\r\\r',...\n      extended_size(1),extended_size(2),orginal_size(1),orginal_size(2),orginal_size(2)));\nend\nreturn\n\n%==========================================================================================\n%\t\t\t\t\t\t**********  \tINTERNAL FUNCTION    **********\n%==========================================================================================\n\nfunction z = q2c(y)\n\n% function z = q2c(y)\n% Convert from quads in y to complex numbers in z.\n\nsy = size(y);\nt1 = 1:2:sy(1); t2 = 1:2:sy(2);\nj2 = sqrt([0.5 -0.5]);\n\n% Arrange pixels from the corners of the quads into\n% 2 subimages of alternate real and imag pixels.\n%  a----b\n%  |    |\n%  |    |\n%  c----d\n\n% Combine (a,b) and (d,c) to form two complex subimages. \np = y(t1,t2)*j2(1) + y(t1,t2+1)*j2(2);     % p = (a + jb) / sqrt(2)\nq = y(t1+1,t2+1)*j2(1) - y(t1+1,t2)*j2(2); % q = (d - jc) / sqrt(2)\n\n% Form the 2 subbands in z.\nz = cat(3,p-q,p+q);\n\nreturn\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/dtwavexfm2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5950497991478888}}
{"text": "function p = cycle_to_perm ( n, ncycle, t, index )\n\n%*****************************************************************************80\n%\n%% CYCLE_TO_PERM converts a permutation from cycle to array form.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    20 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 items permuted.\n%    N must be positive.\n%\n%    Input, integer NCYCLE, the number of cycles.\n%    1 <= NCYCLE <= N.\n%\n%    Input, integer T(N), INDEX(NCYCLE), describes the permutation\n%    as a collection of NCYCLE cycles.  The first cycle is\n%    T(1) -> T(2) -> ... -> T(INDEX(1)) -> T(1).\n%\n%    Output, integer P(N), describes the permutation using a\n%    single array.  For each index I, I -> P(I).\n%\n\n%\n%  Check.\n%\n  ierror = cycle_check ( n, ncycle, t, index );\n\n  if ( ierror ~= 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'CYCLE_TO_PERM - Fatal error!\\n' );\n    fprintf ( 1, '  The input array is illegal.\\n' );\n    fprintf ( 1, '  IERROR = %d\\n', ierror );\n    error ( 'CYCLE_TO_PERM - Fatal error!' );\n  end\n\n  jhi = 0;\n\n  for i = 1 : ncycle\n\n    jlo = jhi + 1;\n    jhi = jhi + index(i);\n\n    for j = jlo : jhi\n\n      if ( j < jhi )\n        p(t(j)) = t(j+1);\n      else\n        p(t(j)) = t(jlo);\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/combo/cycle_to_perm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.5950497905701199}}
{"text": "% show the eigenface images\n% examples are conducted in Yale face database\n[vectors,Training_matrix,Y]=train(20);  % 10 is the number of eigenvectors\n% the size of vectors is 77760*10\nfor k=1:20\n    col=vectors(:,k);  %pick up every column vector\n    im=reshape(col,243,320); % transform this vector into 2D-image\n    m_a=max(max(im));\n    n_b=min(min(im));\n    for i=1:243\n       for j=1:320\n       im(i,j)=(im(i,j)-n_b)/(m_a-n_b)*255;\n       end\n    end\n    subplot(4,5,k);\n    imshow(uint8(im));\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/\u7f8e\u8d5bB\u9898\u5e38\u89c1\u4ee3\u7801/\u79bb\u6563\u5c0f\u6ce2\u4e0e\u4e3b\u6210\u5206\u5206\u6790\u7684\u6570\u636e\u964d\u7ef4\u65b9\u6cd5/DWT_PCA/show_eigenface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5950497892787514}}
{"text": "function op = prox_dualize( dualProx, NEG )\n%PROX_DUALIZE   Define a proximity function by its dual\n%    OP = PROX_DUALIZE( dualOp ) returns an operator implementing the \n%    dual of the function dualProx. You can verify they are duals\n%    via test_proxPair( dualOp, OP ).\n%\n%    OP = PROX_DUALIZE( dualOp, 'neg' )\n%    OP = PROX_DUALIZE( dualOp, 'negative' )\n%       will return the scaled dual of dualOp; that is,\n%       dualOp(x) and OP(-x) are duals.\n%       The negative is useful because this is the version TFOCS\n%       expects for the SCD formulation.\n%       For 1-homogenous functions (e.g. norms), this has no effect,\n%       since ||x|| = ||-x||.\n%\n% Warning: if you can calculate the dual function explicitly,\n%   it is likely more computationally efficient to do so, rather\n%   than rely on this code. This code requires some tricks, some\n%   of which can sometimes be expensive; also, it will call dualOp\n%   so it is at least as slow as dualOp; and it may require high\n%   precision from dualOp. This code can break down if dualOp\n%   is not numerically stable.\n\nif nargin < 2, NEG = ''; end\nif strcmpi(NEG,'neg') || strcmpi(NEG,'negative')\n    op = @(varargin)dualize(dualProx,-1,varargin{:} );\nelse\n    op = @(varargin)dualize(dualProx,1,varargin{:} );\nend\n\nfunction [ v, x ] = dualize( dualProx, scale, x, t )\nvec     = @(x) x(:);\nmyDot   = @(x,y) x(:)'*y(:);\nif scale == -1\n    x   = -x;\nend\nswitch nargin,\n    case 3\n        if nargout == 2,\n            error( 'This function is not differentiable.'  );\n        else\n            % This case is a bit tricky...\n            %   If the function is non-differentiable, then standard exact\n            %   penalty function results tell us that for a sufficiently\n            %   small stepsize, we can remove the effect of smoothing.\n            %   In other cases, we don't have an exact value, but we hope this\n            %   is a reasonable approximation.\n            \n%             t       = 1e-15;\n%             [~,x2]  = dualProx( x/t, 1/t );\n%             v       = myDot(x,x2) - dualProx( x2 );\n            \n            % However, some functions break down when 1/t is huge\n            % So we will slowly decrease it\n            vOld    = Inf;\n            t       = 1e-5;\n            ok      = false;\n            iter    = 0;\n            while ~ok && t > eps\n                [~,x2]  = dualProx( x/t, 1/t );\n                v       = myDot(x,x2) - dualProx( x2 );\n                if abs(v-vOld)/max( 1e-10, abs(v) ) < 1e-4\n                    % due to exact penalty, we expect that\n                    %   for t < t_cutoff, v=vOld up to machine accuracy\n                    ok = true;\n                else\n                    t   = t/10;\n                    vOld = v;\n                    iter = iter + 1;\n                    %fprintf('%d and v is %.2e\\n', iter, v );\n                end\n            end\n            \n        end\n        \n    case 4\n        % This is exact.\n        [ignore,x2]  = dualProx( x/t, 1/t );\n        x1      = x - t*x2; % Moreau's identity, equation (8.1) in the user guide\n        v       = myDot(x1,x2) - dualProx( x2 );\n        \n        % If we think it is an indicator function, then round down to zero:\n        if abs(v) < 100*eps,\n            v  = 0;\n        end\n        x   = scale*x1;\n        \n    otherwise,\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/prox_dualize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519376, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.5950486796894701}}
{"text": "%%*************************************************************************\n%% mybicgstab\n%%\n%% [xx,resnrm,flag] = mybicgstab(A,b,M1,tol,maxit)\n%%\n%% iterate on  bb - (M1)*AA*x\n%%\n%% r = b-A*xtrue;\n%%\n%%*************************************************************************\n\nfunction [xx,resnrm,flag] = mybicgstab(A,b,M1,tol,maxit,printlevel)\n\nN = length(b);\nif (nargin < 6); printlevel = 1; end\nif (nargin < 5) || isempty(maxit); maxit = max(30,length(A.mat22)); end;\nif (nargin < 4) || isempty(tol); tol = 1e-10; end;\ntolb = min(1e-4,tol*norm(b));\nflag = 1;\n\nx = zeros(N,1);\nif (norm(x))\n    if isstruct(A); r = b-matvec(A,x); else r = b-mexMatvec(A,x); end;\nelse\n    r =b;\nend\nerr = norm(r); resnrm(1) = err;  minresnrm = err; xx = x;\n%%if (err < 1e-3*tolb); return; end\n\nomega  = 1.0;\nr_tld = r;\n%%\n%%\n%%\nbreakyes = 0;\nsmtol = 1e-40;\nfor iter = 1:maxit,\n    \n    rho   = (r_tld'*r);\n    if (abs(rho) < smtol)\n        flag = 2;\n        if (printlevel); fprintf('*'); end;\n        breakyes = 1;\n        break;\n    end\n    if (iter > 1)\n        beta  = (rho/rho_1)* (alp/omega);\n        p = r + beta*(p - omega*v);\n    else\n        p = r;\n    end\n    p_hat = precond(A,M1,p);\n    if isstruct(A); v = matvec(A,p_hat); else v = mexMatvec(A,p_hat); end;\n    alp = rho / (r_tld'*v);\n    s = r - alp*v;\n    %%\n    s_hat = precond(A,M1,s);\n    if isstruct(A); t = matvec(A,s_hat); else t = mexMatvec(A,s_hat); end;\n    omega = (t'*s) / (t'*t);\n    x = x + alp*p_hat + omega*s_hat;\n    r = s - omega*t;\n    rho_1 = rho;\n    %%\n    %% check convergence\n    %%\n    err = norm(r); resnrm(iter+1) = err; %#ok\n    if (err < minresnrm);\n        xx = x; minresnrm = err;\n    end\n    if (err < tolb)\n        break;\n    end\n    if (err > 10*minresnrm)\n        if (printlevel); fprintf('^'); end\n        breakyes = 2;\n        break;\n    end\n    if (abs(omega) < smtol)\n        flag = 2;\n        if (printlevel); fprintf('*'); end\n        breakyes = 1;\n        break;\n    end\nend\nif (~breakyes) && (printlevel >=3); fprintf(' '); end\n%%\n%%*************************************************************************\n%%*************************************************************************\n%% precond:\n%%*************************************************************************\n\nfunction Mx = precond(A,L,x)\n\nm = L.matdim; m2 = length(x)-m;\nMx = zeros(length(x),1);\n\nfor iter = 1\n    if norm(Mx); r = x - matvec(A,Mx); else r = x; end\n    if (m2 > 0)\n        r1 = full(r(1:m));\n    else\n        r1 = full(r);\n    end\n    if (m2 > 0)\n        r2 = r(m+1:m+m2);\n        w = linsysolvefun(L,r1);\n        z = mexMatvec(A.mat12,w,1) - r2;\n        z = L.Mu \\ (L.Ml \\ (L.Mp*z));\n        r1 = r1 - mexMatvec(A.mat12,z);\n    end\n    d = linsysolvefun(L,r1);\n    if (m2 > 0)\n        d = [d; z]; %#ok\n    end\n    Mx = Mx + d;\nend\n%%*************************************************************************\n%%*************************************************************************\n%% matvec: matrix-vector multiply.\n%% matrix = [A.mat11, A.mat12; A.mat12', A.mat22]\n%%*************************************************************************\n\nfunction Ax = matvec(A,x)\n\nm = length(A.mat11); m2 = length(x)-m;\nif issparse(x); x = full(x); end\nif (m2 > 0)\n    x1 = x(1:m);\nelse\n    x1 = x;\nend\nAx = mexMatvec(A.mat11,x1);\nif (m2 > 0)\n    x2 = x(m+1:m+m2);\n    Ax = Ax + mexMatvec(A.mat12,x2);\n    Ax2 = mexMatvec(A.mat12,x1,1) + mexMatvec(A.mat22,x2);\n    Ax = [full(Ax); full(Ax2)];\nend\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/Solver/mybicgstab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5950486736406014}}
{"text": "function h = hs71H(x,lambda)\n\nh = [ 2*x(4)             x(4)   x(4)   2*x(1)+x(2)+x(3);\n      x(4)               0      0   x(1);\n      x(4)               0      0   x(1);\n      2*x(1)+x(2)+x(3)  x(1)  x(1)  0 ];\n                          \nh = h + lambda.ineqnonlin*-[    0      x(3)*x(4) x(2)*x(4) x(2)*x(3);\n                            x(3)*x(4)     0     x(1)*x(4) x(1)*x(3);\n                            x(2)*x(4) x(1)*x(4)     0     x(1)*x(2);\n                            x(2)*x(3) x(1)*x(3) x(1)*x(2)     0  ];\n                     \nh = h + lambda.eqnonlin * diag([2 2 2 2]);", "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/hs71H.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5949898513677414}}
{"text": "%MDL_MICO Create model of Kinova Mico manipulator\n%\n% MDL_MICO is a script that creates the workspace variable mico which\n% describes the kinematic characteristics of a Kinova Mico manipulator\n% using standard DH conventions.\n%\n% Also define the workspace vectors:\n%   qz         zero joint angle configuration\n%   qr         vertical 'READY' configuration\n%\n% Reference::\n% - \"DH Parameters of Mico\" Version 1.0.1, August 05, 2013.\n%   Kinova\n%\n% Notes::\n% - SI units of metres are used.\n% - Unlike most other mdl_xxx scripts this one is actually a function that\n%   behaves like a script and writes to the global workspace.\n%\n% See also Revolute, mdl_jaco, mdl_puma560, mdl_twolink, SerialLink.\n\n% MODEL: Kinova, Mico, 6DOF, standard_DH\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\nfunction r = mdl_mico()\n    \n    deg = pi/180;\n    \n    % robot length values (metres)  page 4\n    D1 = 0.2755;\n    D2 = 0.2900;\n    D3 = 0.1233;\n    D4 = 0.0741;\n    D5 = 0.0741;\n    D6 = 0.1600;\n    e2 = 0.0070;\n    \n    % alternate parameters\n    aa = 30*deg;\n    ca = cos(aa);\n    sa = sin(aa);\n    c2a = cos(2*aa);\n    s2a = sin(2*aa);\n    d4b = D3 + sa/s2a*D4;\n    d5b = sa/s2a*D4 + sa/s2a*D5;\n    d6b = sa/s2a*D5 + D6;\n    \n    \n    % and build a serial link manipulator\n    \n    % offsets from the table on page 4, \"Mico\" angles are the passed joint\n    % angles.  \"DH Algo\" are the result after adding the joint angle offset.\n\n    robot = SerialLink([\n        Revolute('alpha', pi/2,  'a', 0,  'd', D1,   'flip')\n        Revolute('alpha', pi,    'a', D2, 'd', 0,    'offset', -pi/2)\n        Revolute('alpha', pi/2,  'a', 0,  'd', -e2,  'offset', pi/2)\n        Revolute('alpha', 2*aa,  'a', 0,  'd', -d4b)\n        Revolute('alpha', 2*aa,  'a', 0,  'd', -d5b, 'offset', -pi)\n        Revolute('alpha', pi,    'a', 0,  'd', -d6b, 'offset', pi/2)\n        ], ...\n        'name', 'Mico', 'manufacturer', 'Kinova');\n    \n    %{\n        % MDH version, no test  yet\n    robot = SerialLink([\n        Revolute('alpha', 0,     'a', 0,  'd', D1,   'modified', 'flip')\n        Revolute('alpha', -pi/2, 'a', 0,  'd', 0,    'modified', 'offset', -pi/2)\n        Revolute('alpha', 0,     'a', D2, 'd', e2,  'modified',  'offset', pi/2)\n        Revolute('alpha', -pi/2, 'a', 0,  'd', d4b, 'modified')\n        Revolute('alpha', 2*aa,  'a', 0,  'd', d5b, 'modified',  'offset', -pi)\n        Revolute('alpha', 2*aa,  'a', 0,  'd', d6b, 'modified',  'offset', pi/2)\n        ], ...\n        'name', 'Mico', 'manufacturer', 'Kinova');\n    %}\n    \n    % place the variables into the global workspace\n    if nargin == 1\n        r = robot;\n    elseif nargin == 0\n        assignin('caller', 'mico', robot);\n        assignin('caller', 'qz', [0 0 0 0 0 0]); % zero angles, arm up\n        assignin('caller', 'qr', [270 180 180 0 0 180]*deg); % vertical pose as per Fig 2\n    end\nend\n\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/models/mdl_mico.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5949884158672167}}
{"text": "function h = ref_lconv(f,g,ctype)\n%REF_LCONV  Reference linear convolution\n%   Usage:  h=ref_lconv(f,g)\n%\n%   PCONV(f,g) computes the linear convolution of f and g.\n\n% AUTHOR: Jordy van Velthoven\n\nLf = length(f);\nLg = length(g);\n\nLh = Lf+Lg-1;\n\nf = [f; zeros(Lh - Lf, 1)];\ng = [g; zeros(Lh - Lg, 1)];\n\nh = zeros(Lf+Lg-1, 1);\n\nswitch(lower(ctype))\n\tcase {'default'}\n    for ii = 0 : Lh-1\n      for jj = 0 : Lh-1\n        h(ii+1)=h(ii+1)+f(jj+1)*g(mod(ii-jj,Lh)+1);\n      end\n    end\n  case {'r'}\n    for ii=0:Lh-1\n      for jj=0:Lh-1\n\t      h(ii+1)=h(ii+1)+f(jj+1)*conj(g(mod(jj-ii, Lh)+1));\n      end;\n   \tend;\n  case {'rr'}\n    for ii=0:Lh-1\n      for jj=0:Lh-1\n\t      h(ii+1)=h(ii+1)+conj(f(mod(-jj, Lh)+1))*conj(g(mod(jj-ii,Lh)+1));\n      end;\n    end;\nend\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_lconv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5949883862744441}}
{"text": "% UNPAD_SIGNAL Remove de padding from PAD_SIGNAL\n%\n% Usage\n%    x = UNPAD_SIGNAL(y, resolution, target_sz, center)\n%\n% Input\n%    y (numeric): The signal to be unpadded.\n%    resolution (int): The resolution of the signal (as a power of 2), with\n%        respect to the original, unpadded version.\n%    target_sz (numeric): The size of the original, unpadded version. Combined\n%        with resolution, the size of the output y is given by\n%        target_sz.*2.*(-resolution).\n%    center (boolean, optional): If true, extracts the center part of y, oth-\n%        erwise extracts the (upper) left corner (default false).\n%\n% Output\n%    x (numeric): The extracted unpadded signal\n%\n% Description\n%    To handle boundary conditions, a signal is often padded using PAD_SIGNAL\n%    before being convolved with CONV_SUB_1D or CONV_SUB_2D. After this, the\n%    padding needs to be removed to recover a regular signal. This is achieved\n%    using UNPAD_SIGNAL, which takes the padded, convolved signal y as input,\n%    as well as its resolution relative to the original, unpadded version,\n%    and the size of this original version. Using this, it extracts the\n%    coefficients in y that correspond to the domain of the original signal.\n%    If the center flag was specified during PAD_SIGNAL, it is specified here\n%    again in order to extract the correct part.\n%\n% See Also\n%    PAD_SIGNAL\nfunction x = unpad_signal(x, res, target_sz, center)\n    if nargin < 4\n        center = 0;\n    end\n    \n    padded_sz = size(x);\n    \n    padded_sz = padded_sz(1:length(target_sz));\n    \n    offset = 0.*target_sz;\n    \n    if center\n        offset = (padded_sz.*2.^res-target_sz)/2;\n    end\n    \n    offset_ds = floor(offset./2.^res);\n    target_sz_ds = 1+floor((target_sz-1)./2.^res);\n    \n    switch length(target_sz)\n        case 1\n            x = x(offset_ds + (1:target_sz_ds),:,:);\n        case 2\n            x = x(offset_ds(1) + (1:target_sz_ds(1)), ...\n                offset_ds(2) + (1:target_sz_ds(2)), :);\n    end\nend\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/convolution/unpad_signal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.5948210769006185}}
{"text": "function variance = normal_01_variance ( )\n\n%*****************************************************************************80\n%\n%% NORMAL_01_VARIANCE returns the variance of the Normal 01 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%    Output, real VARIANCE, the variance of the PDF.\n%\n  variance = 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/truncated_normal/normal_01_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.5948210644519963}}
{"text": "function bessel_k0_int_values_test ( )\n\n%*****************************************************************************80\n%\n%% BESSEL_KO_INT_VALUES_TEST demonstrates the use of BESSEL_KO_INT_VALUES.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 February 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'BESSEL_KO_INT_VALUES_TEST:\\n' );\n  fprintf ( 1, '  BESSEL_K0_INT_VALUES stores values of \\n' );\n  fprintf ( 1, '  the integral of the Bessel function K0.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '      X           FX\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x, fx ] = bessel_k0_int_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fprintf ( 1, '  %12f  %24.16f\\n', x, fx );\n\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/bessel_k0_int_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.5948210644519963}}
{"text": "function [E,J]=SynthMeasWatsonSHCylSingleRadIsoV_GPD(x, protocol, fibredir, roots)\n% Substrate: Impermeable cylinders with one radius in a homogeneous background.\n% Orientation distribution: Watson's distribution with SH approximation\n% Signal approximation: Gaussian phase distribution.\n% Notes: This version includes an isotropic diffusion compartment with its own\n% diffusivity.\n%\n% [E,J]=SynthMeasWatsonSHCylSingleRadIsoV_GPD(x, protocol, fibredir, roots)\n% returns the measurements E according to the model and the Jacobian J of the\n% measurements with respect to the parameters.  The Jacobian does not\n% include derivates with respect to the fibre direction.\n%\n% x is the list of model parameters in SI units:\n% x(1) is the volume fraction of the intracellular space.\n% x(2) is the free diffusivity of the material inside and outside the cylinders.\n% x(3) is the hindered diffusivity outside the cylinders in perpendicular directions.\n% x(4) is the radius of the cylinders.\n% x(5) is the concentration parameter of the Watson's distribution.\n% x(6) is the volume fraction of the isotropic compartment.\n% x(7) is the diffusivity of the isotropic compartment.\n%\n% protocol is the object containing the acquisition protocol.\n%\n% fibredir is a unit vector along the symmetry axis of the Watson's\n% distribution.  It must be in Cartesian coordinates [x y z]' with size [3 1].\n%\n% roots contains solutions to the Bessel function equation from function\n% BesselJ_RootsCyl.\n%\n% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\nfiso = x(6);\ndIso = x(7);\n\n% Call the model with no isotropic component to get the anisotropic component.\nif(nargout == 1)\n    Eaniso=SynthMeasWatsonSHCylSingleRadGPD(x, protocol, fibredir, roots);\n    Eiso = SynthMeasIsoGPD(dIso, protocol);\nelse\n    [Eaniso,Janiso]=SynthMeasWatsonSHCylSingleRadGPD(x, protocol, fibredir, roots);\n    [Eiso, Jiso] = SynthMeasIsoGPD(dIso, protocol);\nend\n\nE = (1-fiso)*Eaniso + fiso*Eiso;\n\nif(nargout>1)\n    \n    % Update with anisotropic component.\n    J = Janiso*(1-fiso);\n    \n    % Add derivatives wrt isotropic fraction.\n    J(:,6) = Eiso - Eaniso;\n    \n    % Add entry for dIso\n    J(:,7) = fiso*Jiso;\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/watson/SynthMeasWatsonSHCylSingleRadIsoV_GPD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5948158710255265}}
{"text": "function output = callosqp(interfacedata)\n\noptions = interfacedata.options;\nmodel = yalmip2quadprog(interfacedata);\n\nif options.savedebug\n    save debugfile model\nend\n\nif options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end\n\n% Define QP\nn_var = length(model.c);\nP = model.Q;\nq = model.c;\neye_n = speye(n_var);\nA = [model.Aeq;model.A; eye_n];\nl = full([model.beq; -inf(length(model.b),1); model.lb]);\nu = full([model.beq; model.b; model.ub]);\n\n% Define verbose option\noptions.osqp.verbose = options.verbose;\n\n% Solve with OSQP\nOSQPSolver = osqp;\nOSQPSolver.setup(P, q, A, l, u, options.osqp);\nresults = OSQPSolver.solve();\n\nswitch results.info.status_val\n    case 1\n        problem = 0;\n    case 2\n        problem = 0;\n    case -2\n        problem = 3;\n    case -3\n        problem = 1;\n    case 3\n        problem = 1;\n    case -4\n        problem = 2;\n    case 4\n        problem = 2;\n    case -5\n        problem = 16;\n    case -10\n        problem = 11;\n    otherwise\n        problem = -10;\nend\n\n% Solver time\nsolvertime = results.info.run_time;\n\n% Standard interface\nPrimal      = results.x(:);\nDual        = results.y(1:end-n_var);\ninfostr     = yalmiperror(problem,interfacedata.solver.tag);\nif ~options.savesolverinput\n    solverinput = [];\nelse\n    solverinput = model;\nend\nif ~options.savesolveroutput\n    solveroutput = [];\nelse\n    solveroutput = results;\nend\n\n% Standard interface\noutput = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/callosqp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5947719757866115}}
{"text": "function [Mz_z,Mz_xy,F,ref_eff,Mx_xy,My_xy]=simRf(rf,rephase_factor,prephase_factor) \n%simRf Simulate an RF pulse with the given pulse shape.\n%   [Mz_z,Mz_xy,F,ref_eff,Mx_xy,My_xy]=simRf(pulse,prephase_factor,rephase_factor) \n%   Performs a rapid RF pulse simulation based on the rotation formalism.\n%   The algorithm is optimized by using quaternions to represent rotations. \n%   The compulsory parameter 'rf' is the Pulseq RF pulse. Optional\n%   parameter 'rephase_factor' is needed in several cases e.g. to correclty \n%   visualize the phase of the magnetization for slice-selective\n%   excitation. Another optional parameter 'prephase_factor' is an \n%   experimental parameter useful for simulating refocusing pulses or\n%   spoiling needed. \n%   Return values: \n%     Mz_z,Mz_xy:  z and xy comnponents of the magnetisation after the pulse\n%                  assuming the unit magnetization was aligned with z before\n%                  the pulse. Useful for assessing excitation RF pulses. \n%     F:           frequency axis in Hz \n%     ref_eff:     Refocusing efficiency of the pulse as a complex value.\n%                  Magnitude of ref_eff seems to closely follow Mz_z. Phase\n%                  of ref_eff is related to the effective phase of the RF\n%                  pulse, e.g. the axis of the planar flip.\n%     Mx_xy,My_xy: xy magnetizations after the RF pulse assuming the unit\n%                  magnetization was aligned with x or y axis prior to the\n%                  pulse, respectively. Useful for detailed analyses of\n%                  refocusing pulses.\n%\n%   The implementation was inspired by the example by Dr. Tony Stoecker\n%   (https://github.com/stoeckert/mr-simu-example-ismrm19)\n%   The algorithm was rewritten to quaternions and vectorized for \n%   performance by MZ \n%\n\nbw_mul=4;    % simulation bandwidth (multiplier of the pulse bandwidth)\ndf=1;        % spectral resolution [Hz]\ndt=10e-6;    % (re-)sampling interval\n\nif nargin < 2\n    if isfield(rf,'use') && strcmp(rf.use,'refocusing')\n        rephase_factor = 0;\n    else\n        rephase_factor = -(rf.shape_dur-mr.calcRfCenter(rf))/rf.shape_dur;\n    end\nend\n\nif nargin < 3\n    prephase_factor = 0;\nend\n        \n[bw,f0,spectrum,FF,rfs,tt]=mr.calcRfBandwidth(rf,0.5,df*10,dt);\n\nT     = (1:round(rf.shape_dur/dt))*dt-0.5*dt;                           % timesteps axis [s]\nF     = 2*pi*linspace(f0-bw_mul*bw/2,f0+bw_mul*bw/2,bw/df)';               % offset frequencies [rad/s] \n\nshapea = interp1(rf.t, 2*pi*rf.signal.*exp(1i*(rf.phaseOffset+2*pi*rf.freqOffset*rf.t)),T,'linear',0);\n\n% intialize result vectors\nM_ROT=zeros(size(F)); \nZ_ROT=zeros(size(F));\nsf=size(F);\nq=zeros(sf(1),4);\nq(:,1)=1; % init rotation quaternions\n\n% prephaser / left spoiler\nW = -F*dt*length(T)*prephase_factor;     % effective field rotation angle\nQ = [cos(W/2) zeros(sf) zeros(sf) sin(W/2)];\nq=quat_multiply(q,Q);\n\n% RF pulse simulation\nfor j=1:length(T)\n    W = -dt*sqrt(abs(shapea(j))^2+F.^2); % effective field rotation angles\n    n = dt * [real(shapea(j))*ones(sf) imag(shapea(j))*ones(sf) F]./abs(W); % effective field rotation axes\n    Q = [cos(W/2) sin(W/2).*n];\n    q=quat_multiply(q,Q);\nend\n\n% rephaser / right spoiler / refocusing pulse\nW = -F*dt*length(T)*rephase_factor;     % effective field rotation angle\nQ = [cos(W/2) zeros(sf) zeros(sf) sin(W/2)];\nq=quat_multiply(q,Q);\n\n% export results\nF=F/(2*pi);\nm=zeros(sf(1),4);\n\n% excitation: start with M0=M_z\nm(:,4)=1;\nm0rf=quat_multiply(quat_conj(q),quat_multiply(m,q));\nMz_z=m0rf(:,4);\nMz_xy=m0rf(:,2)+1i*m0rf(:,3);\n\n% refocusing: start both with M0=M_x and them M0=M_y\nm=zeros(sf(1),4);\nm(:,2)=1;\nMx_xy=quat_multiply(quat_conj(q),quat_multiply(m,q));\nMx_xy=Mx_xy(:,2)+1i*Mx_xy(:,3);\nm=zeros(sf(1),4);\nm(:,3)=1;\nMy_xy=quat_multiply(quat_conj(q),quat_multiply(m,q));\nMy_xy=My_xy(:,2)+1i*My_xy(:,3);\nref_eff=(Mx_xy+My_xy*1i)/2;\nend \n\nfunction qout = quat_multiply( q, r )\n%  quat_multiply: Calculate the product of two quaternions.\n\n% Calculate vector portion of quaternion product\n% vec = s1*v2 + s2*v1 + cross(v1,v2)\nvec = [q(:,1).*r(:,2) q(:,1).*r(:,3) q(:,1).*r(:,4)] + ...\n         [r(:,1).*q(:,2) r(:,1).*q(:,3) r(:,1).*q(:,4)]+...\n         [ q(:,3).*r(:,4)-q(:,4).*r(:,3) ...\n           q(:,4).*r(:,2)-q(:,2).*r(:,4) ...\n           q(:,2).*r(:,3)-q(:,3).*r(:,2)];\n\n% Calculate scalar portion of quaternion product\n% scalar = s1*s2 - dot(v1,v2)\nscalar = q(:,1).*r(:,1) - q(:,2).*r(:,2) - ...\n             q(:,3).*r(:,3) - q(:,4).*r(:,4);\n\nqout = [scalar  vec];\nend\n       \nfunction q = quat_conj( q ) \n%  quat_conj Calculate the conjugate of a quaternion.\nq(:,2:4) = -q(:,2:4);\nend\n", "meta": {"author": "pulseq", "repo": "pulseq", "sha": "b4c8fee2a1ffa491d53bd6f507cba2029bf32835", "save_path": "github-repos/MATLAB/pulseq-pulseq", "path": "github-repos/MATLAB/pulseq-pulseq/pulseq-b4c8fee2a1ffa491d53bd6f507cba2029bf32835/matlab/+mr/simRf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5947447199042883}}
{"text": "% %\n% Setup default values and run PK computation. Note that the kernel will\n% perform BETTER if you learn the parameters via cross validation instead of\n% using these defaults. \n% \n% Marion Neumann (m.neumann@wustl.edu)\n% % \n\n% propagation kernel parameter\nnum_iterations = 3;     % number of iterations (sth small 2 or 3)\n\n% hashing parameters\nw              = 1e-5;  % bin width\ndistance       = 'tv';  % distance to approximately preserve\n\n% load you dataset HERE\nload('mutag_mat');      \n\nnum_nodes   = size(A, 1);\nnum_classes = max(labels);\n\ninitial_label_distributions = accumarray([(1:num_nodes)', labels], 1, [num_nodes, num_classes]);\n\n% create a function handle to a feature transformation. Here we will\n% use label diffustion as we have fully labeled graphs.\ntransformation = @(features) label_diffusion(features, A);\n\n\n% calculate the graph kernel using the default (linear) base kernel\nK = propagation_kernel(initial_label_distributions, graph_ind, transformation, ...\n                       num_iterations, ...\n                       'distance', distance, ...\n                       'w',        w);\n\n\n% % If you want to set the BASE KERNEL to an RBF kernel instead of the default \n% % linear base kernel, use the following.\n% length_scale = 3;\n% base_kernel = @(counts) ...\n%               exp(-(squareform(pdist(counts)).^2 / (2 * length_scale^2)));\n% \n%           % calculate the graph kernel again using the new parameters\n% K = propagation_kernel(initial_label_distributions, graph_ind, transformation, ...\n%                        num_iterations, ...\n%                        'distance',    distance, ...\n%                        'w',           w, ...\n%                        'base_kernel', base_kernel);\n", "meta": {"author": "muhanzhang", "repo": "DGCNN", "sha": "7d3663b49561e57fe518f37af0023a364285eee1", "save_path": "github-repos/MATLAB/muhanzhang-DGCNN", "path": "github-repos/MATLAB/muhanzhang-DGCNN/DGCNN-7d3663b49561e57fe518f37af0023a364285eee1/software/propagation_kernels-master/demo/run_default_PK.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5947447164761116}}
{"text": "% Two examples to show how to solve an MILP and an LP with interior method\n\ndisp('-- Integer problem --');\ns=1;\nc=[-1,-1]';\na=[-2,5;2,-2];\nb=[5;1];\nctype=['U','U']';\nlb=[0;0]; ub=[];\nvartype=['B';'B'];\nparam.msglev=3;\n[xmin,fmin,status,extra]=glpk(c,a,b,lb,ub,ctype,vartype,s,param)\n% --- OBSOLETE ---\n% [xmin,fmin,status,extra]=glpkmex(s,c,a,b,ctype,lb,ub,vartype,param)\npause;\n\ndisp('3rd problem');\ns=1;\nc=[0 0 0 -1 -1]';\na=[-2 0 0 1 0;...\n    0 1 0 0 2;...\n    0 0 1 3 2];\nb=[4 12 18]';\nctype=['S','S','S']';\nlb=[0,0,0,0,0]'; ub=[];\nvartype=['C','C','C','C','C']';\nparam.lpsolver=2;\n[xmin,fmin,status,extra]=glpk(c,a,b,lb,ub,ctype,vartype,s,param)\n% --- OBSOLETE ---\n% [xmin,fmin,status,extra]=glpkmex(s,c,a,b,ctype,lb,ub,vartype)\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/solvers/glpkmex/glpktest2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5947427163359252}}
{"text": "clc;\nclear all;\nclose all;\n\nfile = 'data.csv'; % Dataset\n\n% Reading training file\ndata = dlmread(file);\nlabel = data(:,end);\n\n% Extracting positive data points\nidx = (label==1);\npos_data = data(idx,:); \nrow_pos = size(pos_data,1);\n\n% Extracting negative data points\nneg_data = data(~idx,:);\nrow_neg = size(neg_data,1);\n  \n% Random permuation of positive and negative data points\np = randperm(row_pos);\nn = randperm(row_neg);\n\n% 80-20 split for training and test\ntstpf = p(1:round(row_pos/5));\ntstnf = n(1:round(row_neg/5));\ntrpf = setdiff(p, tstpf);\ntrnf = setdiff(n, tstnf);\n\ntrain_data = [pos_data(trpf,:);neg_data(trnf,:)];\ntest_data = [pos_data(tstpf,:);neg_data(tstnf,:)];\n\n% Decision Tree\nprediction = SMOTEBoost(train_data,test_data,'tree',false);\ndisp ('    Label   Probability');\ndisp ('-----------------------------');\ndisp (prediction);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37311-smoteboost/SMOTEBoost/Test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5947427124753693}}
{"text": "% Version 1.000\n%\n% Code provided by Ruslan Salakhutdinov and Geoff Hinton\n%\n% Permission is granted for anyone to copy, use, modify, or distribute this\n% program and accompanying programs and documents for any purpose, provided\n% this copyright notice is retained and prominently displayed, along with\n% a note saying that the original programs are available from our\n% web page.\n% The programs and documents are distributed without any warranty, express or\n% implied.  As the programs were written for research purposes only, they have\n% not been tested to the degree that would be advisable in any important\n% application.  All use of these programs is entirely at the user's own risk.\n\nfunction [f, df] = CG_MNIST(VV,Dim,XX);\n\nl1 = Dim(1);\nl2 = Dim(2);\nl3 = Dim(3);\nl4= Dim(4);\nl5= Dim(5);\nl6= Dim(6);\nl7= Dim(7);\nl8= Dim(8);\nl9= Dim(9);\nN = size(XX,1);\n\n% Do decomversion.\n w1 = reshape(VV(1:(l1+1)*l2),l1+1,l2);\n xxx = (l1+1)*l2;\n w2 = reshape(VV(xxx+1:xxx+(l2+1)*l3),l2+1,l3);\n xxx = xxx+(l2+1)*l3;\n w3 = reshape(VV(xxx+1:xxx+(l3+1)*l4),l3+1,l4);\n xxx = xxx+(l3+1)*l4;\n w4 = reshape(VV(xxx+1:xxx+(l4+1)*l5),l4+1,l5);\n xxx = xxx+(l4+1)*l5;\n w5 = reshape(VV(xxx+1:xxx+(l5+1)*l6),l5+1,l6);\n xxx = xxx+(l5+1)*l6;\n w6 = reshape(VV(xxx+1:xxx+(l6+1)*l7),l6+1,l7);\n xxx = xxx+(l6+1)*l7;\n w7 = reshape(VV(xxx+1:xxx+(l7+1)*l8),l7+1,l8);\n xxx = xxx+(l7+1)*l8;\n w8 = reshape(VV(xxx+1:xxx+(l8+1)*l9),l8+1,l9);\n\n\n  XX = [XX ones(N,1)];\n  w1probs = 1./(1 + exp(-XX*w1)); w1probs = [w1probs  ones(N,1)];\n  w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)];\n  w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs  ones(N,1)];\n  w4probs = w3probs*w4; w4probs = [w4probs  ones(N,1)];\n  w5probs = 1./(1 + exp(-w4probs*w5)); w5probs = [w5probs  ones(N,1)];\n  w6probs = 1./(1 + exp(-w5probs*w6)); w6probs = [w6probs  ones(N,1)];\n  w7probs = 1./(1 + exp(-w6probs*w7)); w7probs = [w7probs  ones(N,1)];\n  XXout = 1./(1 + exp(-w7probs*w8));\n\nf = -1/N*sum(sum( XX(:,1:end-1).*log(XXout) + (1-XX(:,1:end-1)).*log(1-XXout)));\nIO = 1/N*(XXout-XX(:,1:end-1));\nIx8=IO; \ndw8 =  w7probs'*Ix8;\n\nIx7 = (Ix8*w8').*w7probs.*(1-w7probs); \nIx7 = Ix7(:,1:end-1);\ndw7 =  w6probs'*Ix7;\n\nIx6 = (Ix7*w7').*w6probs.*(1-w6probs); \nIx6 = Ix6(:,1:end-1);\ndw6 =  w5probs'*Ix6;\n\nIx5 = (Ix6*w6').*w5probs.*(1-w5probs); \nIx5 = Ix5(:,1:end-1);\ndw5 =  w4probs'*Ix5;\n\nIx4 = (Ix5*w5');\nIx4 = Ix4(:,1:end-1);\ndw4 =  w3probs'*Ix4;\n\nIx3 = (Ix4*w4').*w3probs.*(1-w3probs); \nIx3 = Ix3(:,1:end-1);\ndw3 =  w2probs'*Ix3;\n\nIx2 = (Ix3*w3').*w2probs.*(1-w2probs); \nIx2 = Ix2(:,1:end-1);\ndw2 =  w1probs'*Ix2;\n\nIx1 = (Ix2*w2').*w1probs.*(1-w1probs); \nIx1 = Ix1(:,1:end-1);\ndw1 =  XX'*Ix1;\n\ndf = [dw1(:)' dw2(:)' dw3(:)' dw4(:)' dw5(:)' dw6(:)'  dw7(:)'  dw8(:)'  ]'; \n\n\n", "meta": {"author": "qiuwch", "repo": "DeepLearning", "sha": "60508ffd8c39a085375eec82e576f446d1318bc9", "save_path": "github-repos/MATLAB/qiuwch-DeepLearning", "path": "github-repos/MATLAB/qiuwch-DeepLearning/DeepLearning-60508ffd8c39a085375eec82e576f446d1318bc9/CG_MNIST.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5947427116224192}}
{"text": "function P = getFamily(L,families)\n[K,n] = size(L);\nnf = length(families);\nC = zeros(K,nf);\nfor i=1:nf\n    indf = families{i};\n    C(indf,i) = 1;\nend\nf0 = C*sum(C,1)'.^-1/size(C,2);\nP = zeros(nf,n);\nfor i=1:n\n    logPm = L(:,i) + log(f0);\n    Pm = exp(logPm-max(logPm));\n    Pm = Pm./sum(Pm);\n    P(:,i) = C'*Pm;\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/legacy/trashbin/getFamily.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.594742710769469}}
{"text": "function [E,J]=SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD_B0(x, protocol, fibredir, roots)\n% Substrate: Impermeable cylinders with one radius in a homogeneous background.\n% Orientation distribution: Watson's distribution with SH approximation\n% Signal approximation: Gaussian phase distribution.\n% Notes: This version estimates the hindered diffusivity from the free diffusivity\n% and packing density using Szafer et al's tortuosity model for randomly\n% packed cylinders.\n% This version includes an isotropic diffusion compartment with its own\n% diffusivity.\n% This version includes a stationary water compartment.\n% Includes a free parameter for the measurement at b=0.\n%\n% [E,J]=SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD_B0(x, protocol, fibredir, roots)\n% returns the measurements E according to the model and the Jacobian J of the\n% measurements with respect to the parameters.  The Jacobian does not\n% include derivates with respect to the fibre direction.\n%\n% x is the list of model parameters in SI units:\n% x(1) is the volume fraction of the intracellular space.\n% x(2) is the free diffusivity of the material inside and outside the cylinders.\n% x(3) is the radius of the cylinders.\n% x(4) is the concentration parameter of the Watson's distribution.\n% x(5) is the volume fraction of the isotropic compartment.\n% x(6) is the diffusivity of the isotropic compartment.\n% x(7) is the volume fraction of the isotropic restriction.\n% x(8) is the measurement at b=0.\n%\n% protocol is the object containing the acquisition protocol.\n%\n% fibredir is a unit vector along the symmetry axis of the Watson's\n% distribution.  It must be in Cartesian coordinates [x y z]' with size [3 1].\n%\n% roots contains solutions to the Bessel function equation from function\n% BesselJ_RootsCyl.\n%\n% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\nS0 = x(8);\n\n% Call the other function to get normalized measurements.\nif(nargout == 1)\n    Enorm=SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD(x, protocol, fibredir, roots);\nelse\n   [Enorm,Jnorm]=SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD(x, protocol, fibredir, roots);\nend\n\nE = Enorm*S0;\n\nif(nargout>1)\n    J = Jnorm*S0;\n    J(:,8) = Enorm;\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/watson/SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD_B0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5947427077618629}}
{"text": "function op = prox_l1pos( q )\n%PROX_L1POS    L1 norm, restricted to x >= 0\n%    OP = PROX_L1( q ) implements the nonsmooth function\n%        OP(X) = norm(q.*X,1) + indicator_{ 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 (or must be same size as X).\n\n% New in v1.0d\n\nif nargin == 0,\n\tq = 1;\nelseif ~isnumeric( q ) || ~isreal( q ) ||  any( q(:) < 0 ) || all(q(:)==0) %|| numel( q ) ~= 1\n\terror( 'Argument must be positive.' );\nend\n\nop = tfocs_prox( @(x)f(x,q), @(x,t)prox_f(x,t,q), 'vector');\nend\n\nfunction v = f(x,q)\n    if any( x(:) < 0 )\n        v = Inf;\n    elseif isscalar(q)\n        v = q*sum( x(:) );\n    else\n        v = sum( q(:).*x(:) );\n    end\nend\n\n% The proximity operator is a simplified version of shrinkage:\nfunction x = prox_f(x,t,q)  \n    x   = max( 0, x - t*q );\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_l1pos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5947427013424571}}
{"text": "% Gnufft_test.m\n% Test the Gnufft object (vs exact Gdsft)\n\n%% create Gnufft class object\nif 1 || ~isvar('A'), printm 'setup Gnufft_test'\n\tim plc 3 3\n\tif 1 % 2d\n\t\tN = [32 30];\n\t\tJ = [6 7];\n\t%\tN = [32 1]; J = [5 1];\n\t\tomega = linspace(0, 10*2*pi, 201)'; % crude spiral:\n\t\tomega = pi*[cos(omega) sin(omega)].*omega(:,[1 1])/max(omega);\n\t\tif im, im subplot 1, plot(omega(:,1), omega(:,2), '.'), end\n\telse % 3d\n\t\tN = [16 12 14];\n\t\tJ = [6 7 5];\n\t\ttmp = linspace(0, 10*2*pi, 201)';\n\t\tomega = pi*[cos(tmp) sin(tmp)].*tmp(:,[1 1])/max(tmp);\n\t\tomega(:,3) = pi * tmp / max(tmp); % spiral cone\n\t\tif im, im subplot 1, plot3(omega(:,1), omega(:,2), omega(:,3), '.'), end\n\tend\n\n\tK = 2*N;\n\tif N(2) == 1\n\t\targs = {omega(:,1), N(1), J(1), K(1)}; omega(:,2) = 0;\n\telse\n\t\targs = {omega, N, J, K};\n\tend\n\n%\tmask = true(N); mask(1,1) = false;\n% todo: mask!\n\n\targs = {args{:}, 'table', 2^10, 'minmax:kb'}; % test with table\n\n\tA = Gnufft(args);\n\n\tAd = Gdsft(omega, N);\nend\n\n\n%% test save/load\nif 0\n\tsave('/tmp/A.mat', 'A')\nreturn\nend\n\n\n%% test data\nif 1 || ~isvar('x'), printm 'setup data'\n\tif length(N) == 2\n\t\tx = zeros(N);\n\t\tx(5:25,10:25) = 1;\n\t\tx(15:20,15:20) = 2;\n\t\tx(15,5) = 2;\n\t\tif N(2) == 1\n\t\t\tx = x(:,5,1);\n\t\tend\n\telse\n\t\trng(0)\n\t\tx = rand(N);\n\tend\n\tim(2, x, '\\x')\n\n\tyd = Ad * x;\n\n\tif length(N) == 2\n\t\tn1 = ([0:N(1)-1]/N(1) - 0.5)*2*pi;\n\t\tif N(2) == 1 % 1D case\n\t\t\tyd_g = interp1(omega(:,1), yd, n1);\n\t\telse\n\t\t\tn2 = ([0:N(2)-1]/N(2) - 0.5)*2*pi;\n\t\t\t[nn1 nn2] = ndgrid(n1, n2);\n\t\t\tyd_g = griddata(omega(:,1), omega(:,2), yd,  nn1, nn2);\n\t\t\tyd_g(isnan(yd_g)) = 0;\n\t\tend\n\t\tim(3, abs(yd_g), '$|\\y_d|$'), cbar\n\tend\nend\n\n\n%% build gram\nif 1, printm 'Gnufft gram'\n\twi = [1:size(omega,1)]';\n\tT = build_gram(A, wi);\n\ty2 = T * x(:);\n\ty1 = A' * (wi .* (A * x(:)));\n\tmax_percent_diff y1 y2\n%\tequivs(y1, y2)\nprompt\nend\n\n\n%% compare forward\nif 1, printm 'forward'\n\tyn = A * [x(:) x(:)]; % test with two\n\tyn = yn(:,1);\n\n\tif length(N) == 2\n\t\tif N(2) == 1 % 1D case\n\t\t\tyn_g = interp1(omega(:,1), yn, n1);\n\t\telse\n\t\t\tyn_g = griddata(omega(:,1), omega(:,2), yn,  nn1, nn2);\n\t\t\tyn_g(isnan(yn_g)) = 0;\n\t\tend\n\n\t\tim(4, abs(yn_g), '$|\\y_g|$'), cbar\n\t\tim(5, abs(yd_g - yn_g), '$|\\y_g - \\y_d|$'), cbar\n\tend\n\tmax_percent_diff yd yn\nend\n\n\n%% compare adjoint\nif 1, printm 'adjoint'\n\tyb = ones(size(omega,1), 1);\n\txd = Ad' * yb;\n\txd = iembed(Ad, xd);\n\txn = A' * [yb yb]; % test with two\n\txn = xn(:,1);\n\txn = iembed(A, xn);\n\n\tim(7, fftshift(abs(xd)), '|back dtft|'), cbar\n\tim(8, fftshift(abs(xn)), '|back nufft|'), cbar\n\tim(9, fftshift(abs(xn-xd)), '|back err|'), cbar\n\tmax_percent_diff xd xn\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/systems/tests/Gnufft_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.594742700489507}}
{"text": "function [soln,eqn,info] = StokesP2P0(node,elem,bdFlag,pde,option)\n%% STOKESP2P0 Stokes equation: P2-P0 elements.\n%\n%   [soln,eqn,info] = STOKESP2P0(node,elem,bdFlag,pde) use quadratic and piceswise\n%   constant elements to approximate velocity u and pressure p, repectively.\n% \n%       -div(mu*grad u) + grad p = f in \\Omega,\n%                        - div u = 0  in \\Omega,\n%   with \n%       Dirichlet boundary condition        u = g_D  on \\Gamma_D, \n%       Neumann boundary condition du/dn - np = g_N  on \\Gamma_N.\n%\n%   It is a choice of option.fem in Stokes. Please read Stokes for more\n%   information on the input and output.\n%\n% See also Stokes, Poisson, StokesP2P1\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n\nif ~exist('option','var'), option = []; end\n\n%% Construct Data Structure\n[elem2dof,edge,bdDof] = dofP2(elem);\nN = size(node,1);  NT = size(elem,1);  Nu = N+size(edge,1);   Np = NT;\n\nt = cputime;\n%% Compute geometric quantities and gradient of local basis\n[Dlambda,area] = gradbasis(node,elem);\n\n%% Assemble stiffness matrix for Laplace operator\n% generate sparse pattern\nii = zeros(21*NT,1); jj = 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,'nu'), pde.nu = []; end\nif ~isfield(option,'quadorder')\n    % constant viscosity\n    option.quadorder = 2;        % default order\n    if ~isempty(pde.nu) && isnumeric(pde.nu) % numerical viscosity\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(:,:,5) = 4*(lambda(p,3)*Dlambda(:,:,1)+lambda(p,1)*Dlambda(:,:,3));\n    Dphip(:,:,4) = 4*(lambda(p,2)*Dlambda(:,:,3)+lambda(p,3)*Dlambda(:,:,2));\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    index = 0;\n    for i = 1:6\n        for j = i:6\n            Aij = 0;\n            if isempty(pde.nu) || isnumeric(pde.nu)\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.nu) && (pde.nu~=1)\n                Aij = pde.nu*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);   upperIdx = ~diagIdx;\nA = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Nu,Nu);\nAU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Nu,Nu);\nA = A + AU + AU';\nA = blkdiag(A,A);\nclear Aij ii jj sA Dphip\n\n%% Assemble matrix for divergence operator\n% Since Dphi is linear, 1-pt quadrature is exact for the integral\n% int(div(phi)). We evaluate each basis at the barycenter.\nDphic(:,:,6) = 4/3*(Dlambda(:,:,1) + Dlambda(:,:,2));\nDphic(:,:,1) = 1/3*Dlambda(:,:,1); % (4*lambda(p,1)-1).*Dlambda(:,:,1);\nDphic(:,:,2) = 1/3*Dlambda(:,:,2);\nDphic(:,:,3) = 1/3*Dlambda(:,:,3);\nDphic(:,:,4) = 4/3*(Dlambda(:,:,2) + Dlambda(:,:,3));\nDphic(:,:,5) = 4/3*(Dlambda(:,:,3) + Dlambda(:,:,1));\nclear Dlambda\n% divergence matrix\nDx = sparse(Np,Nu);\nDy = sparse(Np,Nu);\nfor i = 1:6  \n    Dx = Dx + sparse(1:NT,double(elem2dof(:,i)),Dphic(:,1,i).*area,Np,Nu);\n    Dy = Dy + sparse(1:NT,double(elem2dof(:,i)),Dphic(:,2,i).*area,Np,Nu);\nend\nB = -[Dx Dy]; %#ok<*NASGU>\nclear Dphi Dx Dy\n\n%% Assemble right hand side\nf1 = zeros(Nu,1);\nf2 = zeros(Nu,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 ~isempty(pde.f) \n    % quadrature points in the barycentric coordinate\n    [lambda,weight] = quadpts(option.fquadorder);\n    % basis values at quadrature points\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    nQuad = size(lambda,1);\n    ft1 = zeros(NT,6);\n    ft2 = 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        % function values at quadrature points\n        fp = pde.f(pxy);\n        for j = 1:6\n            ft1(:,j) = ft1(:,j) + fp(:,1).*phi(p,j)*weight(p);\n            ft2(:,j) = ft2(:,j) + fp(:,2).*phi(p,j)*weight(p);\n        end\n    end\n    ft1 = ft1.*repmat(area,1,6);\n    ft2 = ft2.*repmat(area,1,6);\n    f1 = accumarray(elem2dof(:),ft1(:),[Nu 1]);\n    f2 = accumarray(elem2dof(:),ft2(:),[Nu 1]);\nend\n\n%% Boundary condition\n[AD,BD,f,g,u,p,ufreeDof,pDof] = getbdStokesP2P0;\n\n%% Record assembeling time\nassembleTime = cputime - t;\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(ufreeDof), return; end\nif isempty(option) || ~isfield(option,'solver')    % no option.solver\n    if length(f)+length(g) <= 1e3  % Direct solver for small size systems\n        option.solver = 'direct';\n    else          % Multigrid-type  solver for large size systems\n        option.solver = 'asmg';\n    end\nend\nsolver = option.solver;\n\n%% Solver\nswitch solver\n    case 'direct'\n        t = cputime;\n        bigA = [AD, BD'; ...\n                BD, sparse(Np,Np)];\n        bigF = [f; g];\n        bigu = [u; p];\n        bigFreeDof = [ufreeDof; 2*Nu+pDof];\n        bigu(bigFreeDof) = bigA(bigFreeDof,bigFreeDof)\\bigF(bigFreeDof);\n        u = bigu(1:2*Nu);\n        p = bigu(2*Nu+1:end);\n        residual = norm(bigF - bigA*bigu);\n        info = struct('solverTime',cputime - t,'itStep',0,'err',residual,'flag',2,'stopErr',residual);        \n    case 'mg'\n        option.solver  = 'WCYCLE';\n        [u(ufreeDof),p,info] = mgstokes(A(ufreeDof,ufreeDof),B(:,ufreeDof),f(ufreeDof),g,...\n                                        u(ufreeDof),p,elem,ufreeDof,option);         \n    case 'asmg'\n        [u(ufreeDof),p,info] = asmgstokes(A(ufreeDof,ufreeDof),B(:,ufreeDof),f(ufreeDof),g,...\n                                          u,p,node,elem,bdFlag,ufreeDof,option); \nend\n\n%% Post-process\nif length(pDof) ~= Np % p is unique up to a constant\n    % impose the condition int(p)=0\n    c = sum(p.*area)/sum(area);\n    p = p - c;\nend\n\n%% Output\nsoln = struct('u',u,'p',p);\neqn = struct('A',AD,'B',BD,'Lap',A,'f',f,'g',g,...\n             'edge',edge,'ufreeDof',ufreeDof,'pDof',pDof);\ninfo.assembleTime = assembleTime;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbdStokesP2P0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    function [AD,BD,f,g,u,p,ufreeDof,pDof] = getbdStokesP2P0\n    %% Boundary condition of Stokes equation: P2-P0 elements\n\n    %% Initial set up\n%     f = [f1; f2];    % set in Neumann boundary condition\n    g = zeros(Np,1);\n    u = zeros(2*Nu,1);    \n    p = zeros(Np,1);\n    ufreeDof = (1:Nu)';\n    pDof = (1:Np)';\n    \n    if ~exist('bdFlag','var'), bdFlag = []; end\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: Find Dirichlet dof and modify the matrix\n    % Find Dirichlet boundary dof: fixedDof and pDof\n    isFixedDof = false(Nu,1);     \n    if ~isempty(bdFlag)       % case: bdFlag is not empty \n        elem2edge = elem2dof(:,4:6)-N;\n        isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n        isFixedDof(edge(isDirichlet,:)) = true;   % nodes of all D-edges\n        isFixedDof(N + find(isDirichlet')) = true;% dof on D-edges\n        fixedDof = find(isFixedDof);\n        ufreeDof = 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        ufreeDof = find(~isFixedDof);    \n    end\n    if isempty(fixedDof) % pure Neumann boundary condition\n        % pde.g_N could be empty which is homogenous Neumann boundary condition\n        fixedDof = 1;\n        ufreeDof = 2:Nu;    % eliminate the kernel by enforcing u(1) = 0;\n    end\n\n    % Modify the matrix\n    % Build Dirichlet boundary condition into the matrix AD by enforcing\n    % AD(fixedDof,fixedDof)=I, AD(fixedDof,ufreeDof)=0, AD(ufreeDof,fixedDof)=0.\n    % BD(:,fixedDof) = 0 and thus BD'(fixedDof,:) = 0.\n    bdidx = zeros(2*Nu,1); \n    bdidx(fixedDof) = 1;\n    bdidx(Nu+fixedDof) = 1;\n    Tbd = spdiags(bdidx,0,2*Nu,2*Nu);\n    T = spdiags(1-bdidx,0,2*Nu,2*Nu);\n    AD = T*A*T + Tbd;\n    BD = B*T;\n\n    %% Part 2: Find boundary edges and modify the right hand side f and g\n    % Find boundary edges: Neumann and Robin\n    Neumann = []; Robin = []; %#ok<*NASGU>\n    if ~isempty(bdFlag)\n        isNeumann(elem2edge((bdFlag(:)==2)|(bdFlag(:) == 3))) = true;\n        isRobin(elem2edge(bdFlag(:)==3)) = true;\n        Neumannidx = find(isNeumann);        \n        Neumann   = edge(isNeumann,:);\n        Robin     = edge(isRobin,:);\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        Neumann = edge(bdDof>N,:);\n        if ~isempty(pde.g_R)\n            Robin = Neumann;\n        end\n    end\n\n    % Neumann boundary condition\n    if ~isempty(pde.g_N) && ~isempty(Neumann) && ~(isnumeric(pde.g_N) && (pde.g_N == 0))\n        [lambda,w] = quadpts1(3);\n        nQuad = size(lambda,1);\n        % quadratic bases (1---3---2)\n        bdphi(:,1) = (2*lambda(:,1)-1).*lambda(:,1);\n        bdphi(:,2) = (2*lambda(:,2)-1).*lambda(:,2);\n        bdphi(:,3) = 4*lambda(:,1).*lambda(:,2);\n        % length of edge\n        ve = node(Neumann(:,1),:) - node(Neumann(:,2),:);\n        edgeLength = sqrt(sum(ve.^2,2));\n        % update RHS\n        gex = zeros(size(Neumann,1),2);\n        gey = zeros(size(Neumann,1),2);\n        for pp = 1:nQuad\n            pxy = lambda(pp,1)*node(Neumann(:,1),:)+lambda(pp,2)*node(Neumann(:,2),:);\n            gp = pde.g_N(pxy);\n            gex(:,1) = gex(:,1) + w(pp)*edgeLength.*gp(:,1)*bdphi(pp,1);\n            gex(:,2) = gex(:,2) + w(pp)*edgeLength.*gp(:,1)*bdphi(pp,2);\n            gey(:,1) = gey(:,1) + w(pp)*edgeLength.*gp(:,2)*bdphi(pp,1);\n            gey(:,2) = gey(:,2) + w(pp)*edgeLength.*gp(:,2)*bdphi(pp,2);\n            f1(N+Neumannidx) = f1(N+Neumannidx) + w(pp)*edgeLength.*gp(:,1)*bdphi(pp,3); % interior bubble\n            f2(N+Neumannidx) = f2(N+Neumannidx) + w(pp)*edgeLength.*gp(:,2)*bdphi(pp,3); % interior bubble\n        end\n        f1(1:N) = f1(1:N) + accumarray(Neumann(:), gex(:),[N,1]);\n        f2(1:N) = f2(1:N) + accumarray(Neumann(:), gey(:),[N,1]);\n    end\n    f = [f1; f2];\n    % The case non-empty Neumann but g_N=[] corresponds to the zero flux\n    % boundary condition on Neumann edges and no modification is needed.\n\n    % Dirichlet boundary conditions\n    if ~isempty(fixedDof) && ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && (pde.g_D == 0))\n        u1 = zeros(Nu,1);\n        u2 = zeros(Nu,1);\n        idx = (fixedDof > N);              % index of edge dof\n        uD = pde.g_D(node(fixedDof(~idx),:));  % bd value at vertex dofs    \n        u1(fixedDof(~idx)) = uD(:,1);\n        u2(fixedDof(~idx)) = uD(:,2);\n        bdEdgeIdx = fixedDof(idx)-N;\n        bdEdgeMid = (node(edge(bdEdgeIdx,1),:)+node(edge(bdEdgeIdx,2),:))/2;\n        uD = pde.g_D(bdEdgeMid);         % bd values at middle points of edges\n        u1(fixedDof(idx)) = uD(:,1);\n        u2(fixedDof(idx)) = uD(:,2);\n        u = [u1; u2]; % Dirichlet bd condition is built into u\n        f = f - A*u;  % bring affect of nonhomgenous Dirichlet bd condition to\n        g = g - B*u;  % the right hand side\n        g = g - mean(g);\n        f(fixedDof) = u1(fixedDof);\n        f(fixedDof+Nu) = u2(fixedDof);\n    end\n    % The case non-empty Dirichlet but g_D=[] corresponds to the zero Dirichlet\n    % boundary condition and no modification is needed.\n    \n    % modfiy pressure dof for pure Dirichlet\n    if isempty(Neumann)\n        pDof = (1:Np-1)';\n    end\n    \n    ufreeDof = [ufreeDof; Nu+ufreeDof];        \n    end % end of function getbdStokesP2P0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nend\n% TODO: impose compatible condition int(pde.g_D*n)=0 numerically.\n% NOTE: the data should be compatible, which is not easy. One\n% special case is the enclose flow i.e. pde.g_D*n=0 everywhere.", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/StokesP2P0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949104, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5947426887057414}}
{"text": "function S2G = HEALPixS2Grid(varargin)\n% defines an equispaced spherical grid\n%\n% Syntax\n%   equispacedS2Grid('points',300)\n%   equispacedS2Grid('resolution',5*degree)\n%\n% Options\n%  points     - number of points to be generated\n%  resolution - resolution of the grid\n%  hemisphere - 'lower', 'uper', 'complete', 'sphere', 'identified'\n%  minRho     - starting rho angle (default 0)\n%  maxRho     - maximum rho angle (default 2*pi)\n%  minTheta   - starting theta angle (default 0)\n%  maxTheta   - maximum theta angle (default pi)\n%\n% Flags\n%  antipodal  - include <VectorsAxes.html antipodal symmetry>\n%  restrict2MinMax - restrict margins to min / max\n%  no_center  - ommit point at center\n%\n% See also\n% regularS2Grid plotS2Grid\n\n\n%  ind = rhoInside(rho,minrho,maxrho) & theta >= mintheta;\n%  theta = theta(ind);\n%  rho = rho(ind);\n%\n%  if isnumeric(maxtheta)\n%    ind = theta <= maxtheta;\n%  else\n%    ind = theta <= maxtheta(rho);\n%  end\n%  theta = theta(ind);\n%  rho = rho(ind);\n\nres = get_option(varargin,'resolution',2.5*degree);\n\nn = round(log(1/res)/log(2));\n\npolar = HealpixGenerateSampling(2^n,1);\n\n\nS2G = vector3d.byPolar(polar(:,1),polar(:,2));\n\n\nreturn\n\n% extract options\nbounds = getPolarRange(varargin{:});\n\n% get number of points\nif check_option(varargin,'points') % calculate resolution\n  ntheta = N2ntheta(fix(get_option(varargin,'points')),...\n    bounds.VR{2},bounds.VR{4}-bounds.VR{3});%Check this\n  res =  (bounds.VR{2}-bounds.VR{1}) / ntheta;\nelse\n  res = get_option(varargin,'resolution',2.5*degree);\n  res =  2* bounds.VR{2} / round(2 * bounds.VR{2} / res);\n  ntheta = fix(round(2 * (bounds.VR{2}-bounds.VR{1}) / res + ...\n    check_option(varargin,'no_center') )/2);\nend\n\n% define polar angle\nif check_option(varargin,'no_center')\n  theta =  (0.5:ntheta-0.5)*res;\nelse\n  theta = (0:ntheta)*res;\nend\ntheta = bounds.VR{1} + theta;\n\n% define azimuth angles\nidentified = check_option(varargin,'antipodal');\n\nrhGrid = repmat(S1Grid([],bounds.FR{3},bounds.FR{4} + pi,'periodic'),...\n  1,length(theta));\nfor j = 1:length(theta)\n\n  th = theta(j);\n  if isappr(th,pi/2) && isappr(bounds.drho,2*pi) && identified\n    rhGrid(j).max = bounds.FR{3} + pi;\n    rhGrid(j).points = bounds.VR{3} + res*(0.5*mod(j,2)+(0:2*ntheta-1));\n  else\n    steps = max(round(sin(th) * bounds.drho / bounds.dtheta * ntheta),1);\n    rhGrid(j).points = bounds.VR{3} + (0:steps-1 )* bounds.drho /steps + ...\n      mod(j,2) * bounds.drho/steps/2;\n  end\nend\n\ntheta = S1Grid(theta,bounds.FR{1},bounds.FR{2});\n\nif identified, opt = {'antipodal'}; else, opt = {}; end\nS2G = S2Grid(theta,rhGrid,opt{:});\nS2G = S2G.setOption('resolution',res);\n\n% restrict to spherical region if specified\nsR = getClass(varargin,'sphericalRegion');\nif ~isempty(sR), S2G = S2G.subGrid(sR.checkInside(S2G,'noAntipodal')); end\n\nend\n\n% ---------------------------------------------------------\nfunction ntheta = N2ntheta(N,maxtheta,maxrho)\nntheta = 1;\nwhile calcAnz(ntheta,0,maxtheta,maxrho) < N\n  ntheta = ntheta + 1;\nend\nif (calcAnz(ntheta,0,maxtheta,maxrho) - N) > (N-calcAnz(ntheta-1,0,maxtheta,maxrho))\n  ntheta = ntheta-1;\nend\n\nend\n\nfunction c = calcAnz(N,tmin,dt,dr)\nc = sum(round(sin(tmin+dt/N*(1:N)) * dr/dt * N));\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/geometry_tools/HEALPixS2Grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5946196904524212}}
{"text": "function lik = lik_qgp(varargin)\n%LIK_QGP  Create a Quantile Gaussian Process likelihood (utility) structure\n%\n%  Description\n%    LIK = LIK_QGP('PARAM1',VALUE1,'PARAM2,VALUE2,...) \n%    creates a quantile gp likelihood structure in which the named\n%    parameters have the specified values. Any unspecified\n%    parameters are set to default values.\n%\n%    LIK = LIK_QGP(LIK,'PARAM1',VALUE1,'PARAM2,VALUE2,...) \n%    modify a likelihood function structure with the named\n%    parameters altered with the specified values.\n%\n%    Parameters for QGP likelihood function [default]\n%      sigma2       - variance [0.1]\n%      sigma2_prior - prior for sigma2 [prior_logunif]\n%      quantile     - Quantile of interest [0.5]\n%\n%    Note! If the prior is 'prior_fixed' then the parameter in\n%    question is considered fixed and it is not handled in\n%    optimization, grid integration, MCMC etc. \n%\n%    The likelihood is defined as follows:\n%                            __ n\n%      p(y|f, sigma2, tau) = || i=1 tau*(1-tau)/sigma*exp(-(y-f)/sigma*\n%                                 (tau - I(t <= f)))\n%    \n%    where tau is the quantile of interest, sigma is the standard deviation\n%    of the distribution and I(t <= f) = 1 if t <= f, 0 otherwise.\n%\n%    Note that because the form of the likelihood, second order derivatives\n%    with respect to latent values are 0. Because this, EP should be used\n%    instead of Laplace approximation.    \n%\n%  See also\n%    GP_SET, PRIOR_*, LIK_*\n%\n%   Reference\n%     Boukouvalas et al. (2012). Direct Gaussian Process Quantile\n%     Regression Using Expectation Propagation. In Proceedings of the\n%     29th International Conference on Machine Learning, Edinburgh,\n%     Scotland, UK, 2012.\n%     \n%\n% Copyright (c) 2012 Ville Tolvanen\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  ip=inputParser;\n  ip.FunctionName = 'LIK_QGP';\n  ip.addOptional('lik', [], @isstruct);\n  ip.addParamValue('sigma2',0.1, @(x) isscalar(x) && x>0);\n  ip.addParamValue('sigma2_prior',prior_logunif(), @(x) isstruct(x) || isempty(x));\n  ip.addParamValue('quantile',0.5, @(x) isscalar(x) && x>0 && x<1);\n  ip.parse(varargin{:});\n  lik=ip.Results.lik;\n\n  if isempty(lik)\n    init=true;\n    lik.type = 'QGP';\n  else\n    if ~isfield(lik,'type') || ~isequal(lik.type,'QGP')\n      error('First argument does not seem to be a valid likelihood function structure')\n    end\n    init=false;\n  end\n  \n  % Initialize parameters\n  if init || ~ismember('sigma2',ip.UsingDefaults)\n    lik.sigma2 = ip.Results.sigma2;\n  end\n  if init || ~ismember('quantile',ip.UsingDefaults)\n    lik.quantile = ip.Results.quantile;\n  end\n  % Initialize prior structure\n  if init\n    lik.p=[];\n  end\n  if init || ~ismember('sigma2_prior',ip.UsingDefaults)\n    lik.p.sigma2=ip.Results.sigma2_prior;\n  end\n  if init\n    % Set the function handles to the subfunctions\n    lik.fh.pak = @lik_qgp_pak;\n    lik.fh.unpak = @lik_qgp_unpak;\n    lik.fh.lp = @lik_qgp_lp;\n    lik.fh.lpg = @lik_qgp_lpg;\n    lik.fh.ll = @lik_qgp_ll;\n    lik.fh.llg = @lik_qgp_llg;    \n    lik.fh.llg2 = @lik_qgp_llg2;\n    lik.fh.llg3 = @lik_qgp_llg3;\n    lik.fh.tiltedMoments = @lik_qgp_tiltedMoments;\n    lik.fh.siteDeriv = @lik_qgp_siteDeriv;\n    lik.fh.predy = @lik_qgp_predy;\n    lik.fh.invlink = @lik_qgp_invlink;\n    lik.fh.recappend = @lik_qgp_recappend;\n  end\n\nend\n\nfunction [w s h] = lik_qgp_pak(lik)\n%LIK_QGP_PAK  Combine likelihood parameters into one vector.\n%\n%  Description\n%    W = LIK_QGP_PAK(LIK) takes a likelihood structure LIK\n%    and combines the parameters into a single row vector W.\n%    This is a mandatory subfunction used for example in \n%    energy and gradient computations.\n%\n%       w = [ log(lik.sigma2)\n%             (hyperparameters of lik.magnSigma2)]'\n%     \n%  See also\n%    LIK_QGP_UNPAK\n\n  w = []; s = {}; h=[];\n  if ~isempty(lik.p.sigma2)\n    w = [w log(lik.sigma2)];\n    s = [s; 'log(qgp.sigma2)'];\n    h = [h 0];\n    % Hyperparameters of sigma2\n    [wh, sh, hh] = lik.p.sigma2.fh.pak(lik.p.sigma2);    \n    w = [w wh];\n    s = [s; sh];\n    h = [h hh];\n  end    \n\nend\n\nfunction [lik, w] = lik_qgp_unpak(lik, w)\n%LIK_QGP_UNPAK  Extract likelihood parameters from the vector.\n%\n%  Description\n%    W = LIK_QGP_UNPAK(W, LIK) takes a likelihood structure\n%    LIK and extracts the parameters from the vector W to the LIK\n%    structure. This is a mandatory subfunction used for example \n%    in energy and gradient computations.\n%\n%    Assignment is inverse of  \n%       w = [ log(lik.sigma2)\n%             (hyperparameters of lik.magnSigma2)]'\n%\n%  See also\n%    LIK_QGP_PAK\n  \n  if ~isempty(lik.p.sigma2)\n    lik.sigma2 = exp(w(1));\n    w = w(2:end);\n    \n    % Hyperparameters of sigma2\n    [p, w] = lik.p.sigma2.fh.unpak(lik.p.sigma2, w);\n    lik.p.sigma2 = p;\n  end\nend\n\nfunction lp = lik_qgp_lp(lik)\n%LIK_QGP_LP  Evaluate the log prior of likelihood parameters\n%\n%  Description\n%    LP = LIK_QGP_LP(LIK) takes a likelihood structure LIK and\n%    returns log(p(th)), where th collects the parameters. This\n%    subfunction is needed when there are likelihood parameters.\n%\n%  See also\n%    LIK_QGP_PAK, LIK_QGP_UNPAK, LIK_QGP_G, GP_E\n\n  lp = 0;\n\n  if ~isempty(lik.p.sigma2)\n    likp=lik.p;\n    lp = likp.sigma2.fh.lp(lik.sigma2, likp.sigma2) + log(lik.sigma2);\n  end\nend\n\nfunction lpg = lik_qgp_lpg(lik)\n%LIK_QGP_LPG  Evaluate gradient of the log prior with respect\n%                  to the parameters.\n%\n%  Description\n%    LPG = LIK_QGP_LPG(LIK) takes a QGP likelihood\n%    function structure LIK and returns LPG = d log (p(th))/dth,\n%    where th is the vector of parameters. This subfunction is \n%    needed when there are likelihood parameters.\n%\n%  See also\n%    LIK_QGP_PAK, LIK_QGP_UNPAK, LIK_QGP_E, GP_G\n\n  lpg = [];\n\n  if ~isempty(lik.p.sigma2)\n    likp=lik.p;\n    \n    lpgs = likp.sigma2.fh.lpg(lik.sigma2, likp.sigma2);\n    lpg = lpgs(1).*lik.sigma2 + 1;\n    if length(lpgs) > 1\n      lpg = [lpg lpgs(2:end)];\n    end            \n  end\nend\n\nfunction ll = lik_qgp_ll(lik, y, f, z)\n%LIK_QGP_LL  Log likelihood\n%\n%  Description\n%    LL = LIK_QGP_LL(LIK, Y, F, Z) takes a likelihood\n%    structure LIK, observations Y and latent values F. \n%    Returns the log likelihood, log p(y|f,z). This subfunction \n%    is needed when using Laplace approximation or MCMC for \n%    inference with non-Gaussian likelihoods. This subfunction \n%    is also used in information criteria (DIC, WAIC) computations.\n%\n%  See also\n%    LIK_QGP_LLG, LIK_QGP_LLG3, LIK_QGP_LLG2, GPLA_E\n  \n  tau=lik.quantile;\n  sigma=sqrt(lik.sigma2);\n  ll = sum(log(tau*(1-tau)/sigma) - (y-f)./sigma.*(tau-(y<=f)));\nend\n\nfunction llg = lik_qgp_llg(lik, y, f, param, z)\n%LIK_QGP_LLG  Gradient of the log likelihood\n%\n%  Description \n%    LLG = LIK_QGP_LLG(LIK, Y, F, PARAM) takes a likelihood\n%    structure LIK, observations Y and latent values F. Returns \n%    the gradient of the log likelihood with respect to PARAM. \n%    At the moment PARAM can be 'param' or 'latent'. This subfunction \n%    is needed when using Laplace approximation or MCMC for inference \n%    with non-Gaussian likelihoods.\n%\n%  See also\n%    LIK_QGP_LL, LIK_QGP_LLG2, LIK_QGP_LLG3, GPLA_E\n\n  \n  tau=lik.quantile;\n  sigma2=sqrt(lik.sigma2);\n  switch param\n    case 'param'      \n      llg = sum(-1/(2.*sigma2) + (y-f)./(2.*sigma2^(3/2)).*(tau-(y<=f)));\n      \n      % correction for the log transformation\n      llg = llg.*lik.sigma2;\n    case 'latent'\n      llg = (tau-(y<=f))/sqrt(sigma2);\n  end\nend\n\nfunction llg2 = lik_qgp_llg2(lik, y, f, param, z)\n%LIK_QGP_LLG2  Second gradients of the log likelihood\n%\n%  Description        \n%    LLG2 = LIK_QGP_LLG2(LIK, Y, F, PARAM) takes a likelihood\n%    structure LIK, observations Y and latent values F. Returns \n%    the Hessian of the log likelihood with respect to PARAM. \n%    At the moment PARAM can be 'param' or 'latent'. LLG2 is \n%    a vector with diagonal elements of the Hessian matrix \n%    (off diagonals are zero). This subfunction is needed \n%    when using Laplace approximation or EP for inference \n%    with non-Gaussian likelihoods.\n%\n%  See also\n%    LIK_QGP_LL, LIK_QGP_LLG, LIK_QGP_LLG3, GPLA_E\n\n  \n  tau=lik.quantile;\n  sigma2=lik.sigma2;\n  switch param\n    case 'param'\n      llg2 = sum(1/(2*sigma2^2) - 3.*(tau-(y<=f)).*(y-f)./(4.*sigma2^(5/2)));\n      \n      % correction due to the log transformation\n      llg2 = llg2.*lik.sigma2;\n    case 'latent'\n      llg2 = zeros(size(f));\n    case 'latent+param'\n      llg2 = -(tau-(y<=f))./(2*sigma2^(3/2));\n      \n      % correction due to the log transformation\n      llg2 = llg2.*lik.disper;\n  end\nend    \n\nfunction llg3 = lik_qgp_llg3(lik, y, f, param, z)\n%LIK_QGP_LLG3  Third gradients of the log likelihood\n%\n%  Description\n%    LLG3 = LIK_QGP_LLG3(LIK, Y, F, PARAM) takes a likelihood\n%    structure LIK, observations Y and latent values F and \n%    returns the third gradients of the log likelihood with \n%    respect to PARAM. At the moment PARAM can be 'param' or \n%    'latent'. LLG3 is a vector with third gradients. This \n%    subfunction is needed when using Laplace approximation for \n%    inference with non-Gaussian likelihoods.\n%\n%  See also\n%    LIK_QGP_LL, LIK_QGP_LLG, LIK_QGP_LLG2, GPLA_E, GPLA_G\n\n  tau=lik.quantile;\n  sigma2=lik.sigma2;\n  switch param\n    case 'param'\n      llg3 = sum(-1/sigma2^3 + 15.*(tau-(y<=f)).*(y-f)./(8.*sigma2^(7/2)));\n    case 'latent'\n      llg3 = 0;\n    case 'latent2+param'\n      llg3 = 0;\n      \n      % correction due to the log transformation\n      llg3 = llg3.*lik.sigma2;\n  end\nend\n\nfunction [logM_0, m_1, sigm2hati1] = lik_qgp_tiltedMoments(lik, y, i1, sigma2_i, myy_i, z)\n%LIK_QGP_TILTEDMOMENTS  Returns the marginal moments for EP algorithm\n%\n%  Description\n%    [M_0, M_1, M2] = LIK_QGP_TILTEDMOMENTS(LIK, Y, I, S2,\n%    MYY, Z) takes a likelihood structure LIK, observations\n%    Y, index I and cavity variance S2 and mean MYY. Returns \n%    the zeroth moment M_0, mean M_1 and variance M_2 of the \n%    posterior marginal (see Rasmussen and Williams (2006): \n%    Gaussian processes for Machine Learning, page 55). This \n%    subfunction is needed when using EP for inference with \n%    non-Gaussian likelihoods.\n%\n%  See also\n%    GPEP_E\n  \n  yy = y(i1);\n  sigma2 = lik.sigma2;\n  tau=lik.quantile;\n  logM_0=zeros(size(yy));\n  m_1=zeros(size(yy));\n  sigm2hati1=zeros(size(yy));\n  \n  for i=1:length(i1)\n    if isscalar(sigma2_i)\n      sigma2_ii = sigma2_i;\n    else\n      sigma2_ii = sigma2_i(i);\n    end\n    \n    % get a function handle of an unnormalized tilted distribution\n    % (likelihood * cavity = Quantile-GP * Gaussian)\n    % and useful integration limits\n    [tf,minf,maxf]=init_qgp_norm(yy(i),myy_i(i),sigma2_ii,sigma2,tau);\n    \n    % Integrate with quadrature\n    RTOL = 1.e-6;\n    ATOL = 1.e-10;\n    [m_0, m_1(i), m_2] = quad_moments(tf, minf, maxf, RTOL, ATOL);\n    if isnan(m_0)\n      logM_0=NaN;\n      return\n    end\n    sigm2hati1(i) = m_2 - m_1(i).^2;\n    \n    % If the second central moment is less than cavity variance\n    % integrate more precisely. Theoretically for log-concave\n    % likelihood should be sigm2hati1 < sigm2_i.\n    if sigm2hati1(i) >= sigma2_ii\n      ATOL = ATOL.^2;\n      RTOL = RTOL.^2;\n      [m_0, m_1(i), m_2] = quad_moments(tf, minf, maxf, RTOL, ATOL);\n      sigm2hati1(i) = m_2 - m_1(i).^2;\n      if sigm2hati1(i) >= sigma2_ii\n        error('lik_qgp_tilted_moments: sigm2hati1 >= sigm2_i');\n      end\n    end\n    logM_0(i) = log(m_0);\n  end\nend\n\nfunction [g_i] = lik_qgp_siteDeriv(lik, y, i1, sigm2_i, myy_i, z)\n%LIK_QGP_SITEDERIV  Evaluate the expectation of the gradient\n%                      of the log likelihood term with respect\n%                      to the likelihood parameters for EP \n%\n%  Description [M_0, M_1, M2] =\n%    LIK_QGP_SITEDERIV(LIK, Y, I, S2, MYY, Z) takes a\n%    likelihood structure LIK, observations Y, index I \n%    and cavity variance S2 and mean MYY. Returns E_f \n%    [d log p(y_i|f_i) /d a], where a is the likelihood \n%    parameter and the expectation is over the marginal posterior.\n%    This term is needed when evaluating the gradients of \n%    the marginal likelihood estimate Z_EP with respect to \n%    the likelihood parameters (see Seeger (2008):\n%    Expectation propagation for exponential families).This \n%    subfunction is needed when using EP for inference with \n%    non-Gaussian likelihoods and there are likelihood parameters.\n%\n%  See also\n%    GPEP_G\n\n\n  yy = y(i1);\n  sigma2=lik.sigma2;\n  tau=lik.quantile;\n  \n  % get a function handle of an unnormalized tilted distribution \n  % (likelihood * cavity = Quantile-GP * Gaussian)\n  % and useful integration limits\n  [tf,minf,maxf]=init_qgp_norm(yy,myy_i,sigm2_i,sigma2,tau);\n  % additionally get function handle for the derivative\n  td = @deriv;\n  \n  % Integrate with quadgk\n  [m_0, fhncnt] = quadgk(tf, minf, maxf);\n  [g_i, fhncnt] = quadgk(@(f) td(f).*tf(f)./m_0, minf, maxf);\n  g_i = g_i.*sigma2;\n\n  function g = deriv(f)\n\n    g = -1/(2.*sigma2) + (yy-f)./(2.*sigma2^(3/2)).*(tau-(yy<=f));\n    \n  end\nend\n\nfunction [lpy, Ey, Vary] = lik_qgp_predy(lik, Ef, Varf, yt, zt)\n%LIK_QGP_PREDY  Returns the predictive mean, variance and density of y\n%\n%  Description  \n%    LPY = LIK_QGP_PREDY(LIK, EF, VARF YT, ZT)\n%    Returns logarithm of the predictive density PY of YT, that is \n%        p(yt | zt) = \\int p(yt | f, zt) p(f|y) df.\n%    This subfunction is needed when computing posterior predictive \n%    distributions for future observations.\n%\n%    [LPY, EY, VARY] = LIK_QGP_PREDY(LIK, EF, VARF) takes a\n%    likelihood structure LIK, posterior mean EF and posterior\n%    Variance VARF of the latent variable and returns the\n%    posterior predictive mean EY and variance VARY of the\n%    observations related to the latent variables. This \n%    subfunction is needed when computing posterior predictive \n%    distributions for future observations.\n%        \n\n%\n%  See also\n%    GPLA_PRED, GPEP_PRED, GPMC_PRED\n\n\n  sigma2=lik.sigma2;\n  tau=lik.quantile;\n  \n  Ey=[];\n  Vary=[];\n  \n  % Evaluate the posterior predictive densities of the given observations\n  lpy = zeros(length(yt),1);\n  if (size(Ef,2) > 1) && (size(Ef,2) > 1) && size(yt,2) == 1\n    % Approximate integral with sum of grid points when using corrected\n    % marginal posterior\n    for i1=1:length(yt)\n      py = arrayfun(@(f) exp(lik.fh.ll(lik, yt(i1), f, [])), Ef(i1,:));\n      pf = Varf(i1,:)./sum(Varf(i1,:));\n      lpy(i1) = log(sum(py.*pf));\n    end\n  else\n    for i1=1:length(yt)\n      % get a function handle of the likelihood times posterior\n      % (likelihood * posterior = Quantile-GP * Gaussian)\n      % and useful integration limits\n      [pdf,minf,maxf]=init_qgp_norm(...\n        yt(i1),Ef(i1),Varf(i1),sigma2, tau);\n      % integrate over the f to get posterior predictive distribution\n      lpy(i1) = log(quadgk(pdf, minf, maxf));\n    end\n  end\nend\n\n\nfunction [df,minf,maxf] = init_qgp_norm(yy,myy_i,sigm2_i,sigma2,tau)\n%INIT_QGP_NORM\n%\n%  Description\n%    Return function handle to a function evaluating\n%    Quantile-GP * Gaussian which is used for evaluating\n%    (likelihood * cavity) or (likelihood * posterior) Return\n%    also useful limits for integration. This is private function\n%    for lik_qgp. This subfunction is needed by subfunctions\n%    tiltedMoments, siteDeriv and predy.\n%  \n%  See also\n%    LIK_QGP_TILTEDMOMENTS, LIK_QGP_SITEDERIV,\n%    LIK_QGP_PREDY\n  \n  sigma=sqrt(sigma2);\n% avoid repetitive evaluation of constant part\n  ldconst = log(tau*(1-tau)/sigma) ...\n            - log(sigm2_i)/2 - log(2*pi)/2;\n  % Create function handle for the function to be integrated\n  df = @qgp_norm;\n  % use log to avoid underflow, and derivates for faster search\n  ld = @log_qgp_norm;\n  ldg = @log_qgp_norm_g;\n%   ldg2 = @log_qgp_norm_g2;\n\n  % Set the limits for integration\n  % Quantile-GP likelihood is log-concave so the qgp_norm\n  % function is unimodal, which makes things easier\n  if yy==0\n    % with yy==0, the mode of the likelihood is not defined\n    % use the mode of the Gaussian (cavity or posterior) as a first guess\n    modef = myy_i;\n  else\n    % use precision weighted mean of the Gaussian approximation\n    % of the Quantile-GP likelihood and Gaussian\n    modef = (myy_i/sigm2_i + yy/sigma2)/(1/sigm2_i + 1/sigma2);\n  end\n  % find the mode of the integrand using Newton iterations\n  % few iterations is enough, since the first guess in the right direction\n  niter=8;       % number of Newton iterations \n  \n  minf=modef-6*sigm2_i;\n  while ldg(minf) < 0\n    minf=minf-2*sigm2_i;\n  end\n  maxf=modef+6*sigm2_i;\n  while ldg(maxf) > 0\n    maxf=maxf+2*sigm2_i;\n  end\n  for ni=1:niter\n%     h=ldg2(modef);\n    modef=0.5*(minf+maxf);\n    if ldg(modef) < 0\n      maxf=modef;\n    else\n      minf=modef;\n    end\n  end\n  % integrand limits based on Gaussian approximation at mode\n  minf=modef-6*sqrt(sigm2_i);\n  maxf=modef+6*sqrt(sigm2_i);\n  modeld=ld(modef);\n  iter=0;\n  % check that density at end points is low enough\n  lddiff=20; % min difference in log-density between mode and end-points\n  minld=ld(minf);\n  step=1;\n  while minld>(modeld-lddiff)\n    minf=minf-step*sqrt(sigm2_i);\n    minld=ld(minf);\n    iter=iter+1;\n    step=step*2;\n    if iter>100\n      error(['lik_qgp -> init_qgp_norm: ' ...\n             'integration interval minimun not found ' ...\n             'even after looking hard!'])\n    end\n  end\n  maxld=ld(maxf);\n  iter=0;\n  step=1;\n  while maxld>(modeld-lddiff)\n    maxf=maxf+step*sqrt(sigm2_i);\n    maxld=ld(maxf);\n    iter=iter+1;\n    step=step*2;\n    if iter>100\n      error(['lik_qgp -> init_qgp_norm: ' ...\n             'integration interval maximun not found ' ...\n             'even after looking hard!'])\n    end\n  end\n  \n  function integrand = qgp_norm(f)\n  % Quantile-GP * Gaussian\n    integrand = exp(ldconst ...\n                    -(yy-f)./sqrt(sigma2).*(tau-(yy<=f)) ...\n                    -0.5*(f-myy_i).^2./sigm2_i);\n  end\n  \n  function log_int = log_qgp_norm(f)\n  % log(Quantile-GP * Gaussian)\n  % log_qgp_norm is used to avoid underflow when searching\n  % integration interval\n    log_int = ldconst...\n              -(yy-f)./sqrt(sigma2).*(tau-(yy<=f)) ...\n              -0.5*(f-myy_i).^2./sigm2_i;\n  end\n  \n  function g = log_qgp_norm_g(f)\n  % d/df log(Quantile-GP * Gaussian)\n  % derivative of log_qgp_norm\n    g = (tau-(yy<=f))/sqrt(sigma2) ...\n        + (myy_i - f)./sigm2_i;\n  end\n  \n  \nend\n\nfunction mu = lik_qgp_invlink(lik, f, z)\n%LIK_QGP_INVLINK  Returns values of inverse link function\n%             \n%  Description \n%    MU = LIK_QGP_INVLINK(LIK, F) takes a likelihood structure LIK and\n%    latent values F and returns the values MU of inverse link function.\n%    This subfunction is needed when using function gp_predprctmu.\n%\n%     See also\n%     LIK_QGP_LL, LIK_QGP_PREDY\n  \n  mu = f;\nend\n\nfunction reclik = lik_qgp_recappend(reclik, ri, lik)\n%RECAPPEND  Append the parameters to the record\n%\n%  Description \n%    RECLIK = LIK_QGP_RECAPPEND(RECLIK, RI, LIK) takes a\n%    likelihood record structure RECLIK, record index RI and\n%    likelihood structure LIK with the current MCMC samples of\n%    the parameters. Returns RECLIK which contains all the old\n%    samples and the current samples from LIK.  This subfunction\n%    is needed when using MCMC sampling (gp_mc).\n% \n%  See also\n%    GP_MC\n\n  if nargin == 2\n    % Initialize the record\n    reclik.type = 'Quantile-GP';\n\n    % Initialize parameter\n    reclik.sigma2 = [];   \n\n    % Set the function handles\n    reclik.fh.pak = @lik_qgp_pak;\n    reclik.fh.unpak = @lik_qgp_unpak;\n    reclik.fh.lp = @lik_qgp_lp;\n    reclik.fh.lpg = @lik_qgp_lpg;\n    reclik.fh.ll = @lik_qgp_ll;\n    reclik.fh.llg = @lik_qgp_llg;    \n    reclik.fh.llg2 = @lik_qgp_llg2;\n    reclik.fh.llg3 = @lik_qgp_llg3;\n    reclik.fh.tiltedMoments = @lik_qgp_tiltedMoments;\n    reclik.fh.predy = @lik_qgp_predy;\n    reclik.fh.invlink = @lik_qgp_invlink;\n    reclik.fh.recappend = @lik_qgp_recappend;\n    reclik.p=[];\n    reclik.p.sigma2=[];\n    if ~isempty(ri.p.sigma2)\n      reclik.p.sigma2 = ri.p.sigma2;\n    end\n  else\n        \n    % Append to the record\n    reclik.sigma2(ri,:)=lik.sigma2;    \n    if ~isempty(lik.p.sigma2)\n      reclik.p.sigma2 = lik.p.sigma2.fh.recappend(reclik.p.sigma2, ri, lik.p.sigma2);\n    end\n    reclik.quantile = lik.quantile;\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/gp/lik_qgp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5946196753234667}}
{"text": "function [err_p,elerr_p] = diffpost_bc(aez,fez,elerror,xy,ev,ebound);\n%diffpost_bc postprocesses local Poisson error estimator \n%   [err_p,elerr_p] = diffpost_bc(aez,fez,elerror,xy,ev,ebound);\n%   input\n%          aez       elementwise Poisson problem matrices\n%          fez       elementwise rhs vectors\n%          elerror   elementwise error estimate (without BC imposition) \n%          xy        vertex coordinate vector  \n%          ev        element mapping matrix\n%          ebound    element edge boundary matrix \n%   output\n%          err_p     global error estimate \n%          elerr_p   elementwise error estimate\n%   IFISS function: DJS; 4 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n      x=xy(:,1); y=xy(:,2);\n      nel=length(ev(:,1));\n      lev=[ev,ev(:,1)]; elerr_p=elerror;\n%\n% recompute contributions from elements with Dirichlet boundaries\n      nbde=length(ebound(:,1));\n      ebdy = zeros(nel,1);\n      edge = zeros(nel,1);\n% isolate boundary elements\n      for el = 1:nbde\n      ee = ebound(el,1);\n      ebdy(ee) = ebdy(ee)+1; edge(ee)=ebound(el,2);\n      end  \n%\n% two edge elements\n      k2=find(ebdy==2);\n      nel2b=length(k2);\n% loop over two edge elements\n      for el = 1:nel2b\n      el2e=k2(el);\n      kk=find(ebound(:,1) == el2e);\n      edges=ebound(kk,2);\n% set up original matrix and RHS vector\n\t  ae=squeeze(aez(el2e,1:5,1:5)); \n      fe=fez(el2e,:)';\n% set up local coordinates and impose interpolated error as Dirichlet bc\n      xl=x(lev(el2e,:)); yl=y(lev(el2e,:)); \n      [bae,fe] = localbc_p(ae,fe,edges,xl,yl);\n% solve local problem\n      err=bae\\fe;\n      elerr_p(el2e,1) = err'*fe;\n      end\n% end of element loop\n%\n% one edge elements\n      k1=find(ebdy==1);\n      nel1b=length(k1);\n% loop over one edge elements\n      for el = 1:nel1b\n      el1e=k1(el);\n      kk=find(ebound(:,1) == el1e);\n      edges=ebound(kk,2);\n% set up original matrix and RHS vector \n      fe=fez(el1e,:)';\n\t  ae=squeeze(aez(el1e,1:5,1:5)); \n% set up local coordinates and impose interpolated error as Dirichlet bc\n      xl=x(lev(el1e,:)); yl=y(lev(el1e,:));\n      [bae,fe] = localbc_p(ae,fe,edges,xl,yl);\n% solve local problem\n      err=bae\\fe;\n      elerr_p(el1e,1) = err'*fe;\n      end\n% end of element loop\n%\n      err_p = sqrt(sum(elerr_p));\n      elerr_p = sqrt(elerr_p);\n      fprintf('done\\n')\n      fprintf('estimated global error (in energy):  %10.6e\\n',err_p)   \n return\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/diffusion/diffpost_bc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5946196642958376}}
{"text": "function p = randperm(n)\n%RANDPERM Random permutation.\n%\tRANDPERM(n) is a random permutation of 1:n.\n[ignore,p] = sort(rand(1,n));\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/utils/randperm2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.5944887307906762}}
{"text": "function [outerproduct] = outer(tensor1, tensor2, squeezedimensions)\n%C = OUTER(A, B, squeezedimensions) Computes the outer product\n%C(i[1],...,i[m],j[1],...,j[n]) = A(i[1],...,i[m]) * B(j[1],...j[n]).\n%Discards superfluous singleton dimensions if squeezedimensions ~= 0.\n%\n%Note: thanks to Emese Toth for suggesting the algorithm used here.\n%\n%Wynton Moore, January 2006\n\n\n%store initial dimensions\ndim1=size(tensor1);dim2=size(tensor2);\n\n\n%evaluate\nouterproduct=reshape(reshape(tensor1, [], 1)*reshape(tensor2, 1, []), [dim1 dim2]);\n\n\n%discard superfluous singleton dimensions\nif squeezedimensions\n    outerproduct=squeeze(outerproduct);\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/10062-multi-dimensional-matrix-product-outer-product-and-partial-trace/outer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5944886523249243}}
{"text": "function dawson_test ( )\n\n%*****************************************************************************80\n%\n%% DAWSON_TEST tests R4_DAWSON and R8_DAWSON.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 September 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n  addpath ( '../test_values' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'DAWSON_TEST:\\n' );\n  fprintf ( 1, '  Test DAWSON_VALUES, R4_DAWSON, R8_DAWSON.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '             X      DAWSON(X)\\n' );\n  fprintf ( 1, '                 R4_DAWSON(X)         Diff\\n' );\n  fprintf ( 1, '                 R8_DAWSON(X)         Diff\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x, fx1 ] = dawson_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fx2 = r4_dawson ( single ( x ) );\n    fx3 = r8_dawson ( x );\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  %14.4f  %14.6g\\n', x, fx1 );\n    fprintf ( 1, '                  %14.6g  %14.6g\\n', fx2, abs ( fx1 - fx2 ) );\n    fprintf ( 1, '                  %14.6g  %14.6g\\n', fx3, abs ( fx1 - fx3 ) );\n\n  end\n\n  rmpath ( '../test_values' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/dawson_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.5944886488377265}}
{"text": "% Driver script for solving the 1D Euler equations\nGlobals1D;\n\n% Polynomial order used for approximation \nN = 4;\n\n% Generate simple mesh\n[Nv, VX, K, EToV] = MeshGen1D(0, 2*pi, 80);\n\n% Initialize solver and construct grid and metric\nStartUp1D;\n\n% Set up initial conditions -- Sod's problem\nMassMatrix = inv(V')/V;\n%cx = ones(Np,1)*sum(MassMatrix*x,1)/2; \n\n%u = ones(Np,K).*( sin(2*pi*cx) );\nu0 = 0.5 + sin(x);\nFinalTime = 1.5;\n\n% Solve Problem\n[u] = iBurgers1D(u0,FinalTime);\nsnapnow;\n\n% Plot Figure\n%plotrange=[0,2*pi,min(min(u0))-0.2,max(max(u0))+0.2];\n%plot(x,u,x,u0,'-+'); axis(plotrange); ylabel('u(x)'); xlabel('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/JSHesthaven&TWarburton/CFD1D/iBurgersDriver1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5944732151229509}}
{"text": "function V = lumScotopic(imgXYZ)\n%\n%       V = lumScotopic(imgXYZ)\n%\n%       This function calculates the scotopic luminance\n%\n%       input:\n%           img: an image in the XYZ color space\n%\n%       output:\n%           V: scotopic luminance approximation by Larson, Rushmeier and Piatko 1997\n%\n%     Copyright (C) 2011-14  Francesco Banterle\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n%\n\ncheck3Color(imgXYZ);\n\neps = 1e-6;\nt = (imgXYZ(:,:,2) + imgXYZ(:,:,3)) ./ (imgXYZ(:,:,1) + eps);\nV = imgXYZ(:,:,2) .* (1.33 * (1.0 + t) - 1.68);\n\nend\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/ColorSpace/lumScotopic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5944732054072215}}
{"text": "function [M_c,C_c_nu_c,g_c,Jc_c,dJc_nu_c,nu_c] = fromFloatingToCentroidalDynamics(M, h, g, Jc, dJc_nu, nu, T, dT)\n%FROMFLOATINGTOCENTROIDALDYNAMICS  converts dynamic equation parameters to the\n%                       corresponding values in centroidal frame of reference.\n%\n% [M_c,C_c_nu_c,g_c,Jc_c,dJc_nu_c,nu_c] = FROMFLOATINGTOCENTROIDALDYNAMICS\n% (M, h, g, Jc, dJc_nu, nu, T, dT) takes as an input the robot dynamics.\n%  The output is the robot dynamics in centroidal frame of reference.\n%\n\n% ------------Initialization----------------\nndof   = size(g,1)-6;\ninvT   = eye(ndof+6)/T;\ninvTt  = eye(ndof+6)/(T');\n\n%% Control terms conversion\n% mass matrix\nM_c            = invTt*M*invT;\nM_c(1:6,7:end) = zeros(6,ndof);\nM_c(7:end,1:6) = zeros(ndof,6);\nM_c(1:3,1:3)   = M(1,1)*eye(3);\nM_c(1:3,4:6)   = zeros(3);\nM_c(4:6,1:3)   = zeros(3);\nMb             = M(1:6,1:6);\nMbj            = M(1:6,7:end);\n\nnu_c           = T*nu;\ngravAcc        = norm(invTt*g)/M(1,1);\ne3             = zeros(ndof+6,1);\ne3(3)          = 1;\ng_c            = M(1,1)*gravAcc*e3;\n\n%coriolis terms\nC_nu           = h - g;\nC_nu_j         = C_nu(7:end);\nC_nu_b         = C_nu(1:6);\nC_c_nu_c_dT    = invTt*C_nu - M_c*dT*nu;\nC_c_nu_c       = [ zeros(3,1);\n                  C_c_nu_c_dT(4:6);\n                  C_nu_j-(Mbj')*(Mb\\C_nu_b)];\n\n%new dT*nu computation for Jacobian\ndT_nu          = M_c\\(C_nu-C_c_nu_c); % M_c\\(inv(T)*C_nu-C_c_nu_c);\nJc_c           = Jc*invT;\ndJc_nu_c       = dJc_nu - Jc*invT*dT_nu;\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/simulink-library/MomentumVelocityControl/src/fromFloatingToCentroidalDynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5944175072363563}}
{"text": "function result = cross_entropy(head_embedding, tail_embedding, head, tail, weights, a, b, same_embedding)\n%CROSS_ENTROPY Given a distance for each 1-simplex in low-dimensional space\n% and the original weights of the 1-simplices in high-dimensional space,\n% compute the approximation to the cross-entropy between the two simplicial\n% complexes. This calculation uses the modified smooth formula Phi for\n% low-dimensional weight that is used in the stochastic gradient descent.\n%\n% result = cross_entropy(head_embedding, tail_embedding, head, tail, weights, a, b, same_embedding)\n%\n% Parameters\n% ----------\n% dists: array of size (n_1_simplices, 1)\n%     The current distance between the two endpoints of the 1-simplex in\n%     low-dimensional Euclidean space.\n%\n% weights: array of size (n_1_simplices, 1)\n%     The original weights assigned to the 1-simplices in high-dimensional\n%     space.\n%\n% a: double\n%     Parameter of differentiable approximation of right adjoint functor.\n% \n% b: double\n%     Parameter of differentiable approximation of right adjoint functor.\n% \n% Returns\n% -------\n% result: double\n%     The total approximated cross entropy between the two simplicial complexes.\n%\n% See also: NEG_SAMPLING_OBJECTIVE\n%\n%   AUTHORSHIP\n%   Math Lead & Primary Developer:  Connor Meehan <connor.gw.meehan@gmail.com>\n%   Secondary Developer: Stephen Meehan <swmeehan@stanford.edu>\n%   Bioinformatics Lead:  Wayne Moore <wmoore@stanford.edu>\n%   Provided by the Herzenberg Lab at Stanford University \n%   License: BSD 3 clause\n%\n    n1 = size(head_embedding, 1);\n    n2 = size(tail_embedding, 1);\n    \n    if n1*n2 > 1e8\n        error('HALTED: MATLAB usually freezes for embeddings this large.');\n    end\n\n    full_dists = pdist2(head_embedding, tail_embedding);\n    full_weights = full(sparse(head, tail, weights, n1, n2));\n    if same_embedding\n        full_weights = full_weights + eye(n1);\n    end\n    Phi = ones(size(full_weights))./(1 + a*(full_dists.^(2*b)));\n    fw0 = full_weights == 0;\n    fw1 = full_weights == 1;\n    other = ~fw0 & ~fw1;\n    Phi_summands = zeros(size(full_weights));\n    Phi_summands(fw0) = log(1-Phi(fw0));\n    Phi_summands(fw1) = log(Phi(fw1));\n    Phi_summands(other) = full_weights(other).*log(Phi(other)) + (1-full_weights(other)).*log(1-Phi(other));\n\n    result = -sum(sum(Phi_summands));\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/umap/umap/cross_entropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5943676348496788}}
{"text": "% input: rvqs0: r s in s0, v s in s0, q s0 2 s, note s0 is a fixed local\n% world frame, also called w-frame\n% rqs02e: rs0 in e, q s0 2 e, a, acceleration by IMU, w, angular rate by\n% gyro, dt, sample interval from the last measurement to the current\n% measurement.\n% gwomegaw, $g^w$, gravity in local world frame, 3-vector, and $w_{iw}^w$, 3-vector,\n% if all of them set 0, this amount to integration in inertial frame\n\nfunction rvqs0_new=strapdown_local_quat_bias(rvqs0, rqs02e, a, w, dt, gwomegaw)\nrvqs0_new=zeros(size(rvqs0));\ngs0=gwomegaw (1:3); % gravity in s0 frame\nwie2s0=gwomegaw (4:6);\n%Update attitude\n%% method (1) second order integration\nqe=rvec2quat_v000(wie2s0*dt);\nvr_a=quatmult_v000(rvqs0(7:10),qe);\nqb=rvec2quat_v000(-w*dt);\nrvqs0_new(7:10)=quatmult_v000(qb,vr_a);\n%% method (2) Runge-Kutta 4th order integration, empirically, this sometimes\n% gives worse result than second order integration\n% wie2s=quatrot_v000(rvqs0(7:10),wie2s0,0);\n% omega=zeros(4,2);\n% omega(1,2)=dt;\n% omega(2:4,1)=w-wie2s;\n% omega(2:4,2)=lastw-wie2s;\n% qs2s0=rotationRK4( omega, [rvqs0(7); -rvqs0(8:10)]);\n% rvqs0_new(7:10)=[qs2s0(1); -qs2s0(2:4)];\n\n%% better velocity and position integration than first order rectanglar rule\n%Update Velocity\nvel_inc1=(quatrot_v000(rvqs0(7:10),a*dt,1)+quatrot_v000(rvqs0_new(7:10),a*dt,1))/2;\nvel_inc2=(gs0+2*cross(rvqs0(4:6),wie2s0))*dt;\nrvqs0_new(4:6)=rvqs0(4:6)+vel_inc1+vel_inc2;\n%Update_pos\nrvqs0_new(1:3)=rvqs0(1:3)+(rvqs0(4:6)+rvqs0_new(4:6))*dt/2;\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/propagation/strapdown_local_quat_bias.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5943676344916203}}
{"text": "function imdb = getCifarImdb(opts)\n% -------------------------------------------------------------------------\n% Preapre the imdb structure, returns image data with mean image subtracted\nunpackPath = fullfile(opts.dataDir, 'cifar-10-batches-mat');\nfiles = [arrayfun(@(n) sprintf('data_batch_%d.mat', n), 1:5, 'UniformOutput', false) ...\n  {'test_batch.mat'}];\nfiles = cellfun(@(fn) fullfile(unpackPath, fn), files, 'UniformOutput', false);\nfile_set = uint8([ones(1, 5), 3]);\n\nif any(cellfun(@(fn) ~exist(fn, 'file'), files))\n  url = 'http://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz' ;\n  fprintf('downloading %s\\n', url) ;\n  untar(url, opts.dataDir) ;\nend\n\ndata = cell(1, numel(files));\nlabels = cell(1, numel(files));\nsets = cell(1, numel(files));\nfor fi = 1:numel(files)\n  fd = load(files{fi}) ;\n  data{fi} = permute(reshape(fd.data',32,32,3,[]),[2 1 3 4]) ;\n  labels{fi} = fd.labels' + 1; % Index from 1\n  sets{fi} = repmat(file_set(fi), size(labels{fi}));\nend\n\nset = cat(2, sets{:});\ndata = single(cat(4, data{:}));\n\n% remove mean in any case\ndataMean = mean(data(:,:,:,set == 1), 4);\ndata = bsxfun(@minus, data, dataMean);\n\n% normalize by image mean and std as suggested in `An Analysis of\n% Single-Layer Networks in Unsupervised Feature Learning` Adam\n% Coates, Honglak Lee, Andrew Y. Ng\n\nif isfield(opts,'contrastNormalization')&&opts.contrastNormalization\n  z = reshape(data,[],60000) ;\n  z = bsxfun(@minus, z, mean(z,1)) ;\n  n = std(z,0,1) ;\n  z = bsxfun(@times, z, mean(n) ./ max(n, 40)) ;\n  data = reshape(z, 32, 32, 3, []) ;\nend\n\nif isfield(opts,'whitenData') &&opts.whitenData\n  z = reshape(data,[],60000) ;\n  W = z(:,set == 1)*z(:,set == 1)'/60000 ;\n  [V,D] = eig(W) ;\n  % the scale is selected to approximately preserve the norm of W\n  d2 = diag(D) ;\n  en = sqrt(mean(d2)) ;\n  z = V*diag(en./max(sqrt(d2), 10))*V'*z ;\n  data = reshape(z, 32, 32, 3, []) ;\nend\n\nclNames = load(fullfile(unpackPath, 'batches.meta.mat'));\n\nimdb.images.data = data ;\nimdb.images.labels = single(cat(2, labels{:})) ;\nimdb.images.set = set;\nimdb.meta.sets = {'train', 'val', 'test'} ;\nimdb.meta.classes = clNames.label_names;", "meta": {"author": "yechengxi", "repo": "LightNet", "sha": "5dc29cefccf1ea6d9377aa90732581337408ce73", "save_path": "github-repos/MATLAB/yechengxi-LightNet", "path": "github-repos/MATLAB/yechengxi-LightNet/LightNet-5dc29cefccf1ea6d9377aa90732581337408ce73/CNN/getCifarImdb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5943461049963291}}
{"text": "function [x, resvec, lsvec] = dense_overdetermined_lsqr(A, b, R, tol, maxit)\n% x = dense_overdetermined_lsqr(A, b, R, tol, maxit)\n% [x, resvec, lsvec] = dense_overdetermined_lsqr(A, b, R, tol, maxit)\n%\n% LSQR on a dense overdetermined matrix with a dense preconditioner R.\n% Solves x = arg min (A*x - b)\n% Inputs:\n%   A, b\n%   R - Upper triangular preconditioner. kappa(A * inv(R)) governs\n%       the convergence.\n%   tol - tolerance. Stop when \n%      norm(inv(R') * A' * r) / (norm(A * inv(R), 'fro') * norm(r)) < tol\n%   maxit - Maximum number of iterations\n% \n% Outputs:\n%   x \n%   optional: resvec, lsvec - values of norm(A' * r) and norm(r).\n%\n% 6-December 2009, Version 1.3\n% Copyright (C) 2009, Haim Avron and Sivan Toledo.\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25241-blendenpik/blendenpik/dense_overdetermined_lsqr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5943460970361804}}
{"text": "function BandTrader(sys)\n%BANDTRADER - Band Trading Strategy\n%\n%  This MATLAB function implements a simple band trading strategy. A band \n%  consists of two lines that form the upper and lower boundaries of the band. \n%  The upper and lower boundaries are used to to enter and exit trades.\n%  For example, if prices fall below the lower boundary a buy signal is \n%  generated.\n% \n%  Requirements:\n%  - MATLAB 2012b\n%  - TA Developer Toolbox (http://www.tadeveloper.com)\n%\n%  Please refer to http://www.tadeveloper.com/docs/80-matlab-algo-trading\n%  for a full description of the strategy\n%\n\n% custom trading parameters\nif sys.TradingParameters.isKey('movingAverage'),\n    movingAverage = sys.TradingParameters('movingAverage');\nelse\n    movingAverage = 10; % default value if unset\nend;\nif sys.TradingParameters.isKey('bandWidth'),\n    bandWidth = sys.TradingParameters('bandWidth');\nelse\n    bandWidth = 2; % default value if unset\nend;\n  \n% Construct the center line\nAverage = (sys.High + sys.Low)/2;\nCenterLine = Ema(Average, movingAverage);\nPlotDataSeries(sys, CenterLine, 'blue', 'solid', 2, '');\n  \n% Construct the bands\nAverageTrueRange = Atr(sys.BarData, movingAverage);  \nUpperBand = CenterLine + bandWidth * AverageTrueRange;\nLowerBand = CenterLine - bandWidth * AverageTrueRange;\nPlotDataSeries(sys, UpperBand, 'magenta', 'solid', 2, '');\nPlotDataSeries(sys, LowerBand, 'magenta', 'solid', 2, '');\n  \n% Entry and Exit Signals\nLongSignal = sys.Close < LowerBand;\nShortSignal = sys.Close > UpperBand;\nAddLongSignal(sys, LongSignal);\nAddShortSignal(sys, ShortSignal);  \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/40152-band-trading-strategy/BandTrader.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.594319739521532}}
{"text": "function q=qrdivide(q1,q2)\n%QRDIVIDE divdes two real quaternions q=[q1,q2]\n%\n% Inputs:\n%\n%     q1(4,1), q2(4,1)  Two real quaternions in the form [r, i, j, k]' where i^2=j^2=k^2=ijk=-1\n%\n% Outputs: \n%\n%     q(4,1)   Quotient of q1/q2 such that q1=q*q2.\n%              Note that q*q2 ~= q2*q since quaternion multiplication does not commute.\n\n%      Copyright (C) Mike Brookes 2000-2008\n%      Version: $Id: qrdivide.m,v 1.1 2008/12/03 10:07:53 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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\npersistent a b c d\nif isempty(a)\n    a=[5 8 9 10 15 13];\n    b=[6 7 11 12 14 16];\n    c=[1 2 3 4 6 7 11 12 16 14];\n    d=[1 2 3 4 5 8 9 10 13 15];\nend\nif nargin<2\n    %    just take the inverse of the only input argument\n    q=q1/(q1'*q1);\n    q(2:4)=-q(2:4);\nelse\n    %    invert q2 and do a multiply\n    q=q2/(q2'*q2);\n    q(2:4)=-q(2:4);\n    t=q1*q.';\n    s=zeros(4,4);\n    s(a)=-t(b);\n    s(c)=t(d);\n    q=sum(s,2);\nend\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/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/qrdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5943163167262845}}
{"text": "function diff_vol = dtiSmoothAnisoPM(vol, num_iter, delta_t, kappa, option, voxel_spacing)\n%ANISODIFF2D Conventional anisotropic diffusion\n%   DIFF_VOL = ANISODIFF3D(VOL, NUM_ITER, DELTA_T, KAPPA, OPTION, VOXEL_SPACING) perfoms \n%   conventional anisotropic diffusion (Perona & Malik) upon a stack of gray scale images.\n%   A 3D network structure of 26 neighboring nodes is considered for diffusion conduction.\n% \n%       ARGUMENT DESCRIPTION:\n%               VOL      - gray scale volume data (MxNxP).\n%               NUM_ITER - number of iterations. \n%               DELTA_T  - integration constant (0 <= delta_t <= 3/44).\n%                          Usually, due to numerical stability this \n%                          parameter is set to its maximum value.\n%               KAPPA    - gradient modulus threshold that controls the conduction.\n%               OPTION   - conduction coefficient functions proposed by Perona & Malik:\n%                          1 - c(x,y,z,t) = exp(-(nablaI/kappa).^2),\n%                              privileges high-contrast edges over low-contrast ones. \n%                          2 - c(x,y,z,t) = 1./(1 + (nablaI/kappa).^2),\n%                              privileges wide regions over smaller ones.\n%          VOXEL_SPACING - 3x1 vector column with the x, y and z dimensions of\n%                          the voxel (milimeters). In particular, only cubic and \n%                          anisotropic voxels in the z-direction are considered. \n%                          When dealing with DICOM images, the voxel spacing \n%                          dimensions can be extracted using MATLAB's dicominfo(.).\n% \n%       OUTPUT DESCRIPTION:\n%               DIFF_VOL - (diffused) volume with the largest scale-space parameter.\n% \n%   Example\n%   -------------\n%   vol = randn(100,100,100);\n%   num_iter = 4;\n%   delta_t = 3/44;\n%   kappa = 70;\n%   option = 2;\n%   voxel_spacing = ones(3,1);\n%   diff_vol = anisodiff3D(vol, num_iter, delta_t, kappa, option, voxel_spacing);\n%   figure, subplot 121, imshow(vol(:,:,50),[]), subplot 122, imshow(diff_vol(:,:,50),[])\n% \n% See also anisodiff1D, anisodiff2D.\n\n% References: \n%   P. Perona and J. Malik. \n%   Scale-Space and Edge Detection Using Anisotropic Diffusion.\n%   IEEE Transactions on Pattern Analysis and Machine Intelligence, \n%   12(7):629-639, July 1990.\n% \n%   G. Grieg, O. Kubler, R. Kikinis, and F. A. Jolesz.\n%   Nonlinear Anisotropic Filtering of MRI Data.\n%   IEEE Transactions on Medical Imaging,\n%   11(2):221-232, June 1992.\n% \n%   MATLAB implementation based on Peter Kovesi's anisodiff(.):\n%   P. D. Kovesi. MATLAB and Octave Functions for Computer Vision and Image Processing.\n%   School of Computer Science & Software Engineering,\n%   The University of Western Australia. Available from:\n%   <http://www.csse.uwa.edu.au/~pk/research/matlabfns/>.\n% \n% Credits:\n% Daniel Simoes Lopes\n% ICIST\n% Instituto Superior Tecnico - Universidade Tecnica de Lisboa\n% danlopes (at) civil ist utl pt\n% http://www.civil.ist.utl.pt/~danlopes\n%\n% May 2007 original version.\n\n% Convert input volume to double.\nvol = double(vol);\n\n% Useful variables.\n[rows cols pags] = size(vol);\n\n% PDE (partial differential equation) initial condition.\ndiff_vol = vol;\nclear vol\n\n% Center voxel distances.\nx = voxel_spacing(1);\ny = voxel_spacing(2);\nz = voxel_spacing(3);\ndx = 1;\ndy = 1;\ndz = z/x;\ndd = sqrt(dx^2+dy^2);\ndh = sqrt(dx^2+dz^2);\ndc = sqrt(dd^2+dz^2);\n\n% 3D convolution masks - finite differences.\nh1 = zeros(3,3,3); h1(2,2,2) = -1; h1(2,2,1) = 1;\nh2 = zeros(3,3,3); h2(2,2,2) = -1; h2(2,2,3) = 1;\nh3 = zeros(3,3,3); h3(2,2,2) = -1; h3(2,1,2) = 1;\nh4 = zeros(3,3,3); h4(2,2,2) = -1; h4(2,3,2) = 1;\nh5 = zeros(3,3,3); h5(2,2,2) = -1; h5(3,2,2) = 1;\nh6 = zeros(3,3,3); h6(2,2,2) = -1; h6(1,2,2) = 1;\n\nh7 = zeros(3,3,3); h7(2,2,2) = -1; h7(3,1,1) = 1;\nh8 = zeros(3,3,3); h8(2,2,2) = -1; h8(2,1,1) = 1;\nh9 = zeros(3,3,3); h9(2,2,2) = -1; h9(1,1,1) = 1;\nh10 = zeros(3,3,3); h10(2,2,2) = -1; h10(3,2,1) = 1;\nh11 = zeros(3,3,3); h11(2,2,2) = -1; h11(1,2,1) = 1;\nh12 = zeros(3,3,3); h12(2,2,2) = -1; h12(3,3,1) = 1;\nh13 = zeros(3,3,3); h13(2,2,2) = -1; h13(2,3,1) = 1;\nh14 = zeros(3,3,3); h14(2,2,2) = -1; h14(1,3,1) = 1;\n\nh15 = zeros(3,3,3); h15(2,2,2) = -1; h15(3,1,2) = 1;\nh16 = zeros(3,3,3); h16(2,2,2) = -1; h16(1,1,2) = 1;\nh17 = zeros(3,3,3); h17(2,2,2) = -1; h17(3,3,2) = 1;\nh18 = zeros(3,3,3); h18(2,2,2) = -1; h18(1,3,2) = 1;\n\nh19 = zeros(3,3,3); h19(2,2,2) = -1; h19(3,1,3) = 1;\nh20 = zeros(3,3,3); h20(2,2,2) = -1; h20(2,1,3) = 1;\nh21 = zeros(3,3,3); h21(2,2,2) = -1; h21(1,1,3) = 1;\nh22 = zeros(3,3,3); h22(2,2,2) = -1; h22(3,2,3) = 1;\nh23 = zeros(3,3,3); h23(2,2,2) = -1; h23(1,2,3) = 1;\nh24 = zeros(3,3,3); h24(2,2,2) = -1; h24(3,3,3) = 1;\nh25 = zeros(3,3,3); h25(2,2,2) = -1; h25(2,3,3) = 1;\nh26 = zeros(3,3,3); h26(2,2,2) = -1; h26(1,3,3) = 1;\n\n% Anisotropic diffusion.\nfor t = 1:num_iter\n\n    % Finite differences. [imfilter(.,.,'conv') can be replaced by convn(.,.,'same')]\n    % Due to possible memory limitations, the diffusion\n    % will be calculated at each page/slice of the volume.\n    for p = 1:pags-2\n        diff3pp = diff_vol(:,:,p:p+2);\n        aux = imfilter(diff3pp,h1,'conv'); nabla1 = aux(:,:,2);\n        aux = imfilter(diff3pp,h2,'conv'); nabla2 = aux(:,:,2);\n        aux = imfilter(diff3pp,h3,'conv'); nabla3 = aux(:,:,2);\n        aux = imfilter(diff3pp,h4,'conv'); nabla4 = aux(:,:,2);\n        aux = imfilter(diff3pp,h5,'conv'); nabla5 = aux(:,:,2);\n        aux = imfilter(diff3pp,h6,'conv'); nabla6 = aux(:,:,2);\n        aux = imfilter(diff3pp,h7,'conv'); nabla7 = aux(:,:,2);\n        aux = imfilter(diff3pp,h8,'conv'); nabla8 = aux(:,:,2);\n        aux = imfilter(diff3pp,h9,'conv'); nabla9 = aux(:,:,2);\n        aux = imfilter(diff3pp,h10,'conv'); nabla10 = aux(:,:,2);\n        aux = imfilter(diff3pp,h11,'conv'); nabla11 = aux(:,:,2);\n        aux = imfilter(diff3pp,h12,'conv'); nabla12 = aux(:,:,2);\n        aux = imfilter(diff3pp,h13,'conv'); nabla13 = aux(:,:,2);\n        aux = imfilter(diff3pp,h14,'conv'); nabla14 = aux(:,:,2);\n        aux = imfilter(diff3pp,h15,'conv'); nabla15 = aux(:,:,2);\n        aux = imfilter(diff3pp,h16,'conv'); nabla16 = aux(:,:,2);\n        aux = imfilter(diff3pp,h17,'conv'); nabla17 = aux(:,:,2);\n        aux = imfilter(diff3pp,h18,'conv'); nabla18 = aux(:,:,2);\n        aux = imfilter(diff3pp,h19,'conv'); nabla19 = aux(:,:,2);\n        aux = imfilter(diff3pp,h20,'conv'); nabla20 = aux(:,:,2);\n        aux = imfilter(diff3pp,h21,'conv'); nabla21 = aux(:,:,2);\n        aux = imfilter(diff3pp,h22,'conv'); nabla22 = aux(:,:,2);\n        aux = imfilter(diff3pp,h23,'conv'); nabla23 = aux(:,:,2);\n        aux = imfilter(diff3pp,h24,'conv'); nabla24 = aux(:,:,2);\n        aux = imfilter(diff3pp,h25,'conv'); nabla25 = aux(:,:,2);\n        aux = imfilter(diff3pp,h26,'conv'); nabla26 = aux(:,:,2);\n        \n        % Diffusion function.\n        if option == 1\n            c1 = exp(-(nabla1/kappa).^2);\n            c2 = exp(-(nabla2/kappa).^2);\n            c3 = exp(-(nabla3/kappa).^2);\n            c4 = exp(-(nabla4/kappa).^2);\n            c5 = exp(-(nabla5/kappa).^2);\n            c6 = exp(-(nabla6/kappa).^2);\n            c7 = exp(-(nabla7/kappa).^2);\n            c8 = exp(-(nabla8/kappa).^2);\n            c9 = exp(-(nabla9/kappa).^2);\n            c10 = exp(-(nabla10/kappa).^2);\n            c11 = exp(-(nabla11/kappa).^2);\n            c12 = exp(-(nabla12/kappa).^2);\n            c13 = exp(-(nabla13/kappa).^2);\n            c14 = exp(-(nabla14/kappa).^2);\n            c15 = exp(-(nabla15/kappa).^2);\n            c16 = exp(-(nabla16/kappa).^2);\n            c17 = exp(-(nabla17/kappa).^2);\n            c18 = exp(-(nabla18/kappa).^2);\n            c19 = exp(-(nabla19/kappa).^2);\n            c20 = exp(-(nabla20/kappa).^2);\n            c21 = exp(-(nabla21/kappa).^2);\n            c22 = exp(-(nabla22/kappa).^2);\n            c23 = exp(-(nabla23/kappa).^2);\n            c24 = exp(-(nabla24/kappa).^2);\n            c25 = exp(-(nabla25/kappa).^2);\n            c26 = exp(-(nabla26/kappa).^2);            \n        elseif option == 2\n            c1 = 1./(1 + (nabla1/kappa).^2);\n            c2 = 1./(1 + (nabla2/kappa).^2);\n            c3 = 1./(1 + (nabla3/kappa).^2);\n            c4 = 1./(1 + (nabla4/kappa).^2);\n            c5 = 1./(1 + (nabla5/kappa).^2);\n            c6 = 1./(1 + (nabla6/kappa).^2);\n            c7 = 1./(1 + (nabla7/kappa).^2);\n            c8 = 1./(1 + (nabla8/kappa).^2);\n            c9 = 1./(1 + (nabla9/kappa).^2);\n            c10 = 1./(1 + (nabla10/kappa).^2);\n            c11 = 1./(1 + (nabla11/kappa).^2);\n            c12 = 1./(1 + (nabla12/kappa).^2); \n            c13 = 1./(1 + (nabla13/kappa).^2);\n            c14 = 1./(1 + (nabla14/kappa).^2);\n            c15 = 1./(1 + (nabla15/kappa).^2);\n            c16 = 1./(1 + (nabla16/kappa).^2);\n            c17 = 1./(1 + (nabla17/kappa).^2);\n            c18 = 1./(1 + (nabla18/kappa).^2); \n            c19 = 1./(1 + (nabla19/kappa).^2);\n            c20 = 1./(1 + (nabla20/kappa).^2);\n            c21 = 1./(1 + (nabla21/kappa).^2);\n            c22 = 1./(1 + (nabla22/kappa).^2);\n            c23 = 1./(1 + (nabla23/kappa).^2);\n            c24 = 1./(1 + (nabla24/kappa).^2);             \n            c25 = 1./(1 + (nabla25/kappa).^2);\n            c26 = 1./(1 + (nabla26/kappa).^2);             \n        end\n\n    % Discrete PDE solution.\n    diff_vol(:,:,p+1) = diff_vol(:,:,p+1) + ...\n                        delta_t*(...\n                        (1/(dz^2))*c1.*nabla1 + (1/(dz^2))*c2.*nabla2 + ...\n                        (1/(dx^2))*c3.*nabla3 + (1/(dx^2))*c4.*nabla4 + ...\n                        (1/(dy^2))*c5.*nabla5 + (1/(dy^2))*c6.*nabla6 + ...\n                        ...\n                        (1/(dc^2))*c7.*nabla7 + (1/(dh^2))*c8.*nabla8 + ...\n                        (1/(dc^2))*c9.*nabla9 + (1/(dh^2))*c10.*nabla10 + ...\n                        (1/(dh^2))*c11.*nabla11 + (1/(dc^2))*c12.*nabla12 + ...\n                        (1/(dh^2))*c13.*nabla13 + (1/(dc^2))*c14.*nabla14 + ...\n                        ...\n                        (1/(dd^2))*c15.*nabla15 + (1/(dd^2))*c16.*nabla16 + ...\n                        (1/(dd^2))*c17.*nabla17 + (1/(dd^2))*c18.*nabla18 + ...\n                        ...\n                        (1/(dc^2))*c19.*nabla19 + (1/(dh^2))*c20.*nabla20 + ...\n                        (1/(dc^2))*c21.*nabla21 + (1/(dh^2))*c22.*nabla22 + ...\n                        (1/(dh^2))*c23.*nabla23 + (1/(dc^2))*c24.*nabla24 + ...\n                        (1/(dh^2))*c25.*nabla25 + (1/(dc^2))*c26.*nabla26);\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/mrDiffusion/utils/dtiSmoothAnisoPM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5943163167262845}}
{"text": "function [u, s, U_p, U_k, U_d] = pinHole(p,k,d)\n\n% PINHOLE Pin-hole camera model, with optional radial distortion.\n%   U = PINHOLE(P) gives the projected pixel U of a point P in a canonical\n%   pin-hole camera, that is, with calibration parameters\n%     u0 = 0\n%     v0 = 0\n%     au = 1\n%     av = 1\n%   It uses reference frames {RDF,RD} (right-down-front for the 3D world\n%   points and right-down for the pixel), according to this scheme:\n%\n%         / z (forward)\n%        /\n%       +------- x                 +------- u\n%       |                          |\n%       |      3D : P=[x;y;z]      |     image : U=[u;v]\n%       | y                        | v\n%\n%   U = PINHOLE(P,K) allows the introduction of the camera's calibration\n%   parameters:\n%     K = [u0 v0 au av]'.\n%\n%   U = PINHOLE(P,K,D) allows the introduction of the camera's radial\n%   distortion parameters:\n%     D = [K2 K4 K6 ...]'\n%   so that the new pixel is distorted following the distortion equation:\n%     U_D = U * (1 + K2*R^2 + K4*R^4 + ...)\n%   with R^2 = sum(U.^2), being U the projected point in the image plane\n%   for a camera with unit focal length.\n%\n%   [U,S] = PINHOLE(...) returns the depth S from the camera center.\n%\n%   If P is a points matrix, PINHOLE(P,...) returns a pixel matrix U and a\n%   depths row-vector S. P, U and S are defined as\n%     P = [P1 ... Pn];   Pi = [xi;yi;zi]\n%     U = [U1 ... Un];   Ui = [ui;vi]\n%     S = [S1 ... Sn]\n%\n%   [U,S,U_p,U_k,U_d] returns the Jacobians of U wrt P, K and D. It only\n%   works for single points P=[x;y;z].\n%\n%   See also PERSP_PROJECT, DISTORT, PIXELLISE, INVPINHOLE, PINHOLEIDP, INVDISTORTION.\n\n%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n% Point's depth\ns = p(3,:);\n\nif nargout <= 2 % only pixel\n\n    switch nargin\n        case 1\n            u = persp_project(p);\n        case 2\n            u = pixellise(persp_project(p),k);\n        case 3\n            if ~isempty(d)\n                u = pixellise(distort(persp_project(p),d),k);\n            else\n                u = pixellise(persp_project(p),k);\n            end\n    end\n\n\nelse % Jacobians\n\n    if size(p,2) > 1\n        error('Jacobians not available for multiple points')\n    else\n\n        switch nargin\n            case 1\n                [u, U_p] = persp_project(p);\n\n            case 2\n                [u1, U1_p]     = persp_project(p);\n                [u, U_u1, U_k] = pixellise(u1,k);\n                U_p            = U_u1*U1_p;\n\n            case 3\n                if ~isempty(d)\n                    [u1, U1_p]        = persp_project(p);\n                    [u2, U2_u1, U2_d] = distort(u1,d);\n                    [u, U_u2, U_k]    = pixellise(u2,k);\n                    U_d               = U_u2*U2_d;\n                    U_p               = U_u2*U2_u1*U1_p;\n                else\n                    [u1, U1_p]     = persp_project(p);\n                    [u, U_u1, U_k] = pixellise(u1,k);\n                    U_p            = U_u1*U1_p;\n                    U_d            = zeros(2,0);\n                end\n\n        end\n\n    end\n\nend\n\nreturn\n\n%% jacobians\nsyms x y z u0 v0 au av d2 d4 d6 real\np = [x;y;z];\nk = [u0;v0;au;av];\nd = [d2;d4;d6];\n\n[u, s, U_p, U_k, U_d] = pinHole(p,k,d);\n\nsimplify(U_p - jacobian(u,p))\nsimplify(U_k - jacobian(u,k))\nsimplify(U_d - jacobian(u,d))\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 <http://www.gnu.org/licenses/>.\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/pinHole.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5943163137122824}}
{"text": "function out=acot(x)\n\nout=atan(1./x);\n\n\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/acot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5943000052184093}}
{"text": "classdef Anodal2gausComputer < handle\n\n    properties (Access = public)\n        A_nodal_2_gauss\n    end\n\n    properties (Access = private)\n        nnode\n        nelem\n        npnod\n        ngaus\n        connec\n        shape\n    end\n\n    methods (Access = public)\n        function obj = Anodal2gausComputer(cParams)\n            obj.init(cParams);\n        end\n\n        function compute(obj)\n            obj.computeA();\n        end\n\n        function intX = integrateP1FunctionWithShapeFunction(obj,cParams)\n            ndof = size(obj.A_nodal_2_gauss{1},2);\n            intX = zeros(ndof,1);\n            for igaus = 1:obj.ngaus\n                dVG  = cParams.dV(:,igaus);\n                xG   = cParams.x(:,igaus);\n                A    = obj.A_nodal_2_gauss{igaus};\n                intX = intX + A'*(xG.*dVG);\n            end\n        end\n    end\n\n    methods (Access = private)\n        function init(obj,cParams)\n            obj.nnode  = cParams.nnode;\n            obj.nelem  = cParams.nelem;\n            obj.npnod  = cParams.npnod;\n            obj.ngaus  = cParams.ngaus;\n            obj.connec = cParams.connec;\n            obj.shape  = cParams.shape;\n        end\n\n        function computeA(obj)\n            A0    = sparse(obj.nelem,obj.npnod);\n            A2g   = cell(obj.ngaus,1);\n            nodes = obj.connec;\n            for igaus = 1:obj.ngaus\n                A2g{igaus} = A0;\n                for inode = 1:obj.nnode\n                    node   = nodes(:,inode);\n                    shapeN = obj.shape(inode,igaus);\n                    Ni = ones(obj.nelem,1)*shapeN;\n                    A  = sparse(1:obj.nelem,node,Ni,obj.nelem,obj.npnod);\n                    A2g{igaus} = A2g{igaus} + A;\n                end\n            end\n            obj.A_nodal_2_gauss = A2g;\n        end\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/Filters/Anodal2gausComputer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5942999999497646}}
{"text": "function [model] = BCPF_MP(Y, varargin)\n% Bayesian CP Factorization using Gaussian Mixture Priors for Image Completion\n% Author : Qibin Zhao  2014\n%\n% -----------------------------------------------------------------------\n%  [model] = BCPF_MP(Y, 'PARAM1', val1, 'PARAM2', val2, ...)\n%\n%  INPUTS\n%     Y              - Input tensor\n%     'obs'          - Binary (0-1) tensor indicating missing entries\n%                      (0: missing; 1: observed)\n%     'init'         - Initialization method\n%                     - 'ml'  : SVD initilization (default)\n%                     - 'rand': Random matrices\n%     'maxRank'      - The initialization of rank (larger than true rank)\n%     'dimRed'       - 1: Remove unnecessary components automaticly (default)\n%                    - 0: Not remove\n%     'maxiters'     - max number of iterations (default: 100)\n%     'tol'          - lower band change tolerance for convergence dection\n%                      (default: 1e-5)\n%     'noise'        - whether noise is updated\n%                        - 'on': update noise parameter (default)\n%                        - 'off': fixed noise parameter (1e-5)\n%     'predVar'      - Predictive distribution\n%                         - 1:  compute and output\n%                         - 0:  doesnot compute  (default)\n%     'verbose'      - visualization of results\n%                       - 0: no\n%                       - 1: text (default)\n%                       - 2: online display image\n%                       - 3: show factors by image\n%                       - 4: show factors by hinton plot (very slow)\n%   OUTPUTS\n%      model         - Model parameters and hyperparameters\n% -----------------------------------------------------------------------\n%\n%   Example:\n%\n%     [model] = BCPF_MP(Y, 'obs', O, 'init', 'rand', 'maxRank', 10, 'dimRed', 1, 'maxiters', 100, ...\n%                                'tol', 1e-6, 'verbose', 3);\n%\n% < Bayesian CP Factorization of Incomplete Image using Gaussian Mixture Priors >\n% Copyright (C) 2014  Qibin Zhao\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 <http://www.gnu.org/licenses/>.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%\nwarning off; %#ok<WNOFF>\nrandn('state',1); rand('state',1); %#ok<RAND>\ndimY = size(Y);\nN = ndims(Y);\n\n%% Set parameters from input or by using defaults\nip = inputParser;\nip.addParamValue('obs', ones(dimY), @(x) (isnumeric(x) || islogical(x)) );\nip.addParamValue('init', 'rand', @(x) (ismember(x,{'ml','rand'})));\nip.addParamValue('maxRank', max(dimY), @isscalar);\nip.addParamValue('maxiters', 100, @isscalar);\nip.addParamValue('tol', 1e-5, @isscalar);\nip.addParamValue('verbose', 1, @isscalar);\nip.addParamValue('noise', 'on', @(x)ismember(x,{'on','off'}));\nip.addParamValue('dimRed', 1, @isscalar);\nip.addParamValue('predVar', 0, @isscalar);\nip.addParamValue('nd', 1, @isscalar);\nip.parse(varargin{:});\n\nO     = ip.Results.obs;\ninit  = ip.Results.init;\nR   = ip.Results.maxRank;\nmaxiters  = ip.Results.maxiters;\ntol   = ip.Results.tol;\nverbose  = ip.Results.verbose;\nDIMRED   = ip.Results.dimRed;\nnoise = ip.Results.noise;\npredVar = ip.Results.predVar;\nnd = ip.Results.nd;\n\n%% Initialization\nY = tensor(Y.*O);\nO = tensor(O);\nnObs = sum(O(:));\n\na_gamma0     = 1e-6;\nb_gamma0     = 1e-6;\nif  strcmp(noise,'on')\n    a_beta0      = 1e-6;\n    b_beta0      = 1e-6;\nelse\n    a_beta0      = 1e-1;\n    b_beta0      = 1e-6;\nend\ngammas = ones(R,1);\nbeta = 1e4;\ndscale =1;\n\nW = cell(N,1);\nW1 = cell(N,1);\noR = nObs/prod(dimY);\nfor n=1:N\n    W{n} = zeros(dimY(n),dimY(n));\n    for i=1:dimY(n)\n        for j=1:dimY(n)\n            W{n}(i,j) = exp(-2*oR*abs(i-j)^2);\n        end\n    end\n    W1{n} = W{n} - diag(diag(W{n}));\n    W1{n} = nd*5*bsxfun(@times, W1{n}, 1./sum(W1{n},2));\nend\n\nswitch init,\n    case 'ml'    % Maximum likelihood\n        Z = cell(N,1);\n        ZSigma = cell(N,1);\n        if ~isempty(find(O==0))\n            %   Y(find(O==0)) = sum(Y(:))/nObs;\n            Y1 = Y;\n            for n=1:N\n                Y1 = ttm(Y1, W{n}, n);\n            end\n            Y(find(O==0)) = Y1(find(O==0));\n        end\n        for n = 1:N\n            ZSigma{n} = (repmat(eye(R), [1 1 dimY(n)]));\n            [U, S, V] = svd(double(tenmat(Y,n)), 'econ');\n            if R <= size(U,2)\n                Z{n} = U(:,1:R)*(S(1:R,1:R)).^(0.5);\n            else\n                Z{n} = [U*(S.^(0.5)) randn(dimY(n), R-size(U,2))];\n            end\n        end\n        Y = Y.*O;\n    case 'rand'   % Random initialization\n        Z = cell(N,1);\n        ZSigma = cell(N,1);\n        for n = 1:N\n            Z{n} = rand(dimY(n),R);\n            ZSigma{n} = (repmat(eye(R), [1 1 dimY(n)]));\n            if n<3\n                %   Z{n} = cholcov(W{n})'*Z{n};\n                Z{n} = Z{n} +  W1{n}*Z{n};\n            end\n        end\nend\n\n% --------- E(aa') = cov(a,a) + E(a)E(a')----------------\nEZZT = cell(N,1);\nfor n=1:N\n    EZZT{n} = (reshape(ZSigma{n}, [R*R, dimY(n)]))';\nend\n\nFit =0;\nLB = 0;\nX = double(ktensor(Z));\n\n%% Create figures\nif verbose >2,\n    scrsz = get(0,'ScreenSize');\n    h1 = figure('Position',[scrsz(3)*0.2 scrsz(4)*0.3 scrsz(3)*0.6 scrsz(4)*0.4]);\n    figure(h1);\n    switch verbose,\n        case 4,\n            subplot(2,3,1); hintonDiagram(Z{1}); title('Mode-1'); ylabel('Length of #-mode');\n            subplot(2,3,2); hintonDiagram(Z{2}); title('Mode-2'); xlabel('Latent dimensions');\n            if N>=3, subplot(2,3,3); hintonDiagram(Z{3}); title('Mode-3'); end\n        case 3,\n            subplot(2,3,1); imagesc(Z{1}); title('Mode-1'); ylabel('Length of #-mode');\n            subplot(2,3,2); imagesc(Z{2}); title('Mode-2'); xlabel('Latent dimensions');\n            if N>=3, subplot(2,3,3); imagesc(Z{3}); title('Mode-3');end\n    end\n    subplot(2,3,4); bar(gammas); title('Posterior mean of \\lambda'); xlabel('Latent components'); ylabel(''); axis tight;\n    subplot(2,3,5); plot(LB, '-r.','LineWidth',1.5,'MarkerSize',10 ); title('Lower bound'); xlabel('Iteration');  grid on;\n    subplot(2,3,6); plotGamma(a_beta0, a_beta0); title('Posterior pdf'); xlabel('Noise precision \\tau');grid on;\n    set(findall(h1,'type','text'),'fontSize',12);\n    drawnow;\nend\nif verbose ==2;\n    h3 = figure;\n    temp = 255.*(X-min(X(:)))/(max(X(:))-min(X(:)));\n    imshow(uint8(temp));\n    title(['Iter.= '  num2str(0),',  Rank = ' num2str(R)],'FontSize', 13, 'color','b');\n    tic;\n    xlabel(['(BCPF-MP)  Time: ' num2str(round(toc)), ' seconds'],'FontSize', 13, 'color','b');\n    drawnow;\nend\n\n%% Model learning\nfor it=1:maxiters,\n    %% Update factor matrices\n    Aw = diag(gammas);\n    for n=1:N\n        % compute E(Z_{\\n}^{T} Z_{\\n})\n        ENZZT = reshape(khatrirao_fast(EZZT{[1:n-1, n+1:N]},'r')' * double(tenmat(O,n)'), [R,R,dimY(n)]);\n        % compute E(Z_{\\n})\n        FslashY = khatrirao_fast(Z{[1:n-1, n+1:N]},'r')' * tenmat(Y.*O, n)';\n        for i=1:dimY(n)\n            ZSigma{n}(:,:,i) = (beta * ENZZT(:,:,i) + Aw )^(-1);\n            Z{n}(i,:) = (beta * ZSigma{n}(:,:,i) * FslashY(:,i))';\n        end\n        if n<3\n            Z{n} = Z{n} + W1{n}*Z{n};\n        end\n        EZZT{n} = (reshape(ZSigma{n}, [R*R, dimY(n)]) + khatrirao_fast(Z{n}',Z{n}'))';\n    end\n    \n    %% Update latent tensor X\n    X = double(ktensor(Z));\n    \n    %% Update hyperparameters gamma\n    a_gammaN = (0.5*sum(dimY) + a_gamma0)*ones(R,1);\n    b_gammaN = 0;\n    for n=1:N\n        b_gammaN = b_gammaN + diag(Z{n}'*Z{n}) + diag(sum(ZSigma{n},3));\n    end\n    b_gammaN = b_gamma0 + 0.5.* b_gammaN;\n    gammas = a_gammaN./b_gammaN;\n    \n    %% update noise beta\n    %  The most time and space consuming part\n    if 0 % save time but large space needed\n        EX2 =  O(:)' * khatrirao_fast(EZZT,'r') * ones(R*R,1);\n    else  % save space but slow\n        temp1 = cell(N,1);\n        EX2 =0;\n        for i =1:R\n            for n=1:N\n                temp1{n} = EZZT{n}(:,(i-1)*R+1: i*R);\n            end\n            EX2 = EX2 + O(:)' * khatrirao_fast(temp1,'r')* ones(R,1);\n        end\n    end\n    err = Y(:)'*Y(:) - 2*Y(:)'*X(:) + EX2;\n    if  strcmp(noise,'on')\n        a_betaN = a_beta0 + 0.5*nObs;\n        b_betaN = b_beta0 + 0.5*err;\n    else\n        a_betaN = a_beta0;\n        b_betaN = b_beta0;\n    end\n    beta = a_betaN/b_betaN;\n    Fit = 1 - sqrt(sum(err(:)))/norm(Y(:));\n    \n    %% Lower bound\n    temp1 = -0.5*nObs*safelog(2*pi) + 0.5*nObs*(psi(a_betaN)-safelog(b_betaN)) - 0.5*(a_betaN/b_betaN)*err;\n    temp22 =0;\n    for n=1:N\n        temp22= temp22 + Z{n}'*Z{n} + sum(ZSigma{n},3);\n    end\n    temp2 = -0.5*R*sum(dimY)*safelog(2*pi) + 0.5*sum(dimY)*sum(psi(a_gammaN)-safelog(b_gammaN)) -0.5*trace(diag(gammas)* temp22);\n    temp3 = sum(-safelog(gamma(a_gamma0)) + a_gamma0*safelog(b_gamma0) -  b_gamma0.*(a_gammaN./b_gammaN) + (a_gamma0-1).*(psi(a_gammaN)-safelog(b_gammaN)));\n    temp4 = -safelog(gamma(a_beta0)) + a_beta0*safelog(b_beta0) + (a_beta0-1)*(psi(a_betaN)-safelog(b_betaN)) - b_beta0*(a_betaN/b_betaN);\n    temp5=0;\n    for n=1:N\n        for i=1:size(ZSigma{n},3)\n            temp5 = temp5 + 0.5*safelog(det(ZSigma{n}(:,:,i))) + 0.5*R*(1+safelog(2*pi));\n        end\n    end\n    temp6 = sum(safelog(gamma(a_gammaN)) - (a_gammaN-1).*psi(a_gammaN) -safelog(b_gammaN) + a_gammaN);\n    temp7 = safelog(gamma(a_betaN)) - (a_betaN-1)*psi(a_betaN) -safelog(b_betaN) + a_betaN;\n    LB(it) = temp1 + temp2 + temp3 + temp4 + temp5 + temp6 + temp7;\n    \n    %% Prune irrelevant dimensions?\n    Zall = cell2mat(Z);\n    comPower = diag(Zall' * Zall);\n    comTol = sum(dimY)*eps(norm(Zall,'fro'));\n    rankest = sum(comPower> comTol );\n    if max(rankest)==0\n        disp('Rank becomes 0 !!!');\n        break;\n    end\n    if DIMRED==1  && it >=2,\n        if R~= max(rankest)\n            indices = comPower > comTol;\n            gammas = gammas(indices);\n            temp = ones(R,R);\n            temp(indices,indices) = 0;\n            temp = temp(:);\n            for n=1:N\n                Z{n} = Z{n}(:,indices);\n                ZSigma{n} = ZSigma{n}(indices,indices,:);\n                EZZT{n} = EZZT{n}(:, temp == 0);\n            end\n            R = max(rankest);\n        end\n    end\n    \n    %% Display progress\n    if it>2\n        LBRelChan = abs(LB(it) - 2*LB(it-1) + LB(it-2))/-LB(2);\n    else\n        LBRelChan = NaN;\n    end\n    if verbose,\n        fprintf('Iter. %d: RelChan = %g, Fit = %g, R = %d \\n', it, LBRelChan, Fit, rankest);\n    end\n    \n    %% visualize online results\n    if verbose >2 ,\n        switch verbose,\n            case 4,\n                set(0,'CurrentFigure',h1);\n                subplot(2,3,1); hintonDiagram(Z{1}); title('Mode-1'); ylabel('Length of #-mode');\n                subplot(2,3,2); hintonDiagram(Z{2}); title('Mode-2'); xlabel('Latent dimensions');\n                if N>=3, subplot(2,3,3); hintonDiagram(Z{3}); title('Mode-3'); end\n            case 3,\n                set(0,'CurrentFigure',h1);\n                subplot(2,3,1); imagesc(Z{1}); title('Mode-1'); ylabel('Length of #-mode');\n                subplot(2,3,2); imagesc(Z{2}); title('Mode-2'); xlabel('Latent dimensions');\n                if N>=3, subplot(2,3,3); imagesc(Z{3}); title('Mode-3'); end\n        end\n        subplot(2,3,4); bar(gammas); title('Posterior mean of \\lambda'); xlabel('Latent components'); ylabel(''); axis tight;\n        subplot(2,3,5); plot(LB, '-r.','LineWidth',1.5,'MarkerSize',10 ); title('Lower bound'); xlabel('Iteration');  grid on;\n        subplot(2,3,6); plotGamma(a_betaN, b_betaN); title('Posterior pdf'); xlabel('Noise precision \\tau');grid on;\n        set(findall(h1,'type','text'),'fontSize',12);\n        drawnow;\n    end\n    if verbose==2\n        set(0,'CurrentFigure',h3);\n        figure(h3);\n        %        temp = (X-min(X(:)))/(max(X(:))-min(X(:)));\n        %        image(temp);\n        %        axis off;\n        imshow(uint8(X));\n        title(['Iter.= '  num2str(it),',  Rank = ' num2str(max(rankest))],'FontSize', 13, 'color','b');\n        xlabel(['(BCPF-MP)  Time: ' num2str(round(toc)), ' seconds'],'FontSize', 13, 'color','b');\n        drawnow;\n    end\n    \n    %% Convergence check\n    if it>5 && abs(LBRelChan) < tol\n        disp('\\\\\\======= Converged===========\\\\\\');\n        break;\n    end\nend\n\n%% Predictive distribution\nif predVar==1\n    Xvar =  tenzeros(size(Y));\n    for n=1:N\n        Xvar = tenmat(Xvar,n);\n        Fslash = khatrirao_fast(Z{[1:n-1, n+1:N]},'r');\n        if 1\n            temp1 = double(tenmat(tensor(ZSigma{n}),3));\n            temp2 = khatrirao_fast(Fslash', Fslash');\n            Xvar(:,:) = Xvar(:,:) + temp1*temp2;\n        else\n            % ---  slow computation ------\n            for i=1:size(Xvar,1)     %#ok\n                Xvar(i,:) = Xvar(i,:) + diag(Fslash * ZSigma{n}(:,:,i) *Fslash')';\n            end\n            % ---  slow computation ------\n        end\n        Xvar = tensor(Xvar);\n    end\n    Xvar = Xvar + beta^(-1);\n    Xvar = Xvar.*(2*a_betaN)/(2*a_betaN-2);\n    Xvar = Xvar.*(dscale^2);\nelse\n    Xvar =[];\nend\n\n%% Prepare the results\nSNR = 10*log10(var(X(:))*beta);\nX = ktensor(Z)*dscale;\nX = arrange(X);\n\n%% Output\nmodel.X = X;\nmodel.ZSigma = ZSigma;\nmodel.gammas = gammas;\nmodel.Fit = Fit;\nmodel.SNR = SNR;\nmodel.Xvar = double(Xvar);\nmodel.TrueRank = rankest;\nmodel.LowBound = max(LB);\n\n\nfunction y = safelog(x)\nx(x<1e-300)=1e-200;\nx(x>1e300)=1e300;\ny=log(x);\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/BCPF/Algorithms/BCPF_MP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5942999941154927}}
{"text": "% correct_mc() - compute an upper limit for the number of independant \n%                time-frequency estimate in a given time-frequency image. \n%                This number can be used to correct for multiple comparisons.\n%\n% Usage:\n%   [ncorrect array] = correct_mc( EEG, cycles, maxfreq, timesout);\n%\n% Inputs: \n%    EEG       - EEGLAB structure\n%    cycles    - [float] same as the cycle input to timef(). Default is [3 0.5].\n%    freqrange - [float] minimum and maximum frequency. Default is [2 50] Hz.\n%    timesout  - [integer] array of number of time points to test. \n%\n% Output:\n%    ncorrect - number of independant tf estimate in the time-freq image\n%    array    - array of size (freqs x timesout) containing pvalues.\n%\n% Method details:\n%\n% Dividing by the total number of time-frequency estimate in the 2-D \n% time-frequency image decomposition would be too conservative since \n% spectral estimates of neighboring time-frequency points are highly \n% correlated. One must thus estimate the number of independent \n% time-frequency points in the TF image. Here, I used geometrical wavelets \n% which are optimal in terms of image compression, so neighboring \n% frequencies can be assume to carry independent spectral estimates. \n% We thus had time-frequency decompositions at only X frequencies (e.g. 120, \n% 60, 30, 15, 7.5, 3.25, 1.625 Hz). For each frequency, I then found \n% the minimum number of time points for which there was a significant \n% correlation of the spectral estimates between neighboring time points \n% (for each frequency and number of time point, I computed the correlation \n% from 0 to 1 for all data channel to obtain an a probability distribution \n% of correlation; we then fitted this distribution using a 4th order curve \n% (Ramberg, J. S., E. J. Dudewicz, et al. (1979). \"A probability \n% distribution and its uses in fitting data.\" Technometrics 21(2)) and \n% assessed the probability of significance for the value 0 (no correlation) \n% to be within the distribution of estimated correlation). For instance, \n% using 28 time points at 120 Hz, there was no significant (p>0.05 taking \n% into account Bonferoni correction for multiple comparisons) correlation \n% between neighboring time-frequency power estimate, but there was a \n% significant correlation using 32 time points instead of 28 (p<0.05). \n% Applying the same approach for the X geometrical frequencies and summing \n% the minimum number of time points for observing a significant correlation \n% at all frequencies, ones obtain in general a number below 200 (with the \n% defaults above and 3-second data epochs) independent estimates. In all \n% the time-frequency plots, one has to used a significance mask at p<0.00025 \n% (0.05/200). An alternative method for correcting for multiple comparisons \n% is presented in Nichols & Holmes, Human Brain Mapping, 2001.\n%\n% Author: Arnaud Delorme, SCCN, Jan 17, 2004\n\n% Copyright (C) 2004 Arnaud Delorme, SCCN, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction [ncorrect, pval] = correct_mc( EEG, cycles, freqrange, timesout);\n\n    if nargin < 1\n        help correct_mc;\n        return;\n    end;\n    if nargin < 2\n        cycles  = [3 0.5];\n    end;\n    if nargin < 3\n        freqrange = [2 50];\n    end;\n    if nargin < 4\n        % possible number of time outputs\n        % -------------------------------\n        timesout = [5 6 7 8 9 10 12 14 16 18 20 24 28 32 36 40];\n    end;\n    nfreqs = ceil(log2(freqrange(2)));\n        \n    % scan times\n    % ----------\n    for ti = 1:length(timesout)\n        clear tmpf\n        \n        % scan data channels\n        % ------------------\n        for index = 1:EEG.nbchan\n            \n            clf; [ersp,itc,powbase,times,freqs,erspboot,itcboot] = newtimef(EEG.data(index,:),EEG.pnts, ...\n                             [EEG.xmin EEG.xmax]*1000,EEG.srate, cycles, 'timesout', timesout(ti), ...\n                             'freqscale', 'log', 'nfreqs', nfreqs, 'freqrange', freqrange, 'plotitc', 'off', 'plotersp', 'off');\n            \n            % compute correlation\n            % -------------------\n            for fi = 1:length(freqs)\n                tmp      = corrcoef(ersp(fi,1:end-1), ersp(fi,2:end));\n                tmpf(index,fi) = tmp(2,1);\n            end;\n            \n        end;\n        \n        % fit curve and determine if the result is significant\n        % ----------------------------------------------------\n        for fi = 1:length(freqs)\n            pval(fi, ti) = rsfit(tmpf(:,fi)', 0);\n            if pval(fi,ti) > 0.9999, pval(fi,ti) = NaN; end;\n        end;\n    end;\n\n    % find minimum number of points for each frequency\n    % ------------------------------------------------\n    ncorrect = 0;\n    threshold = 0.05 / prod(size(pval));\n    for fi = 1:size(pval,1)\n        ti = 1;\n        while ti <= size(pval,2)\n            if pval(fi,ti) < threshold\n                ncorrect = ncorrect +  timesout(ti);\n                ti = size(pval,2)+1;\n            end;\n            ti = ti+1;\n        end;\n    end;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/timefreqfunc/correct_mc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5942999917639842}}
{"text": "function e = strainRate(L)\n% strain rate \n\nif all(L.isSymmetric(:))\n  e = 0.5*max(eig(L));\nelse\n\n  for n = 1:length(L)\n    \n    e(n) = 0.5 * svds(L.M(:,:,n),1);\n\n  end\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/TensorAnalysis/@velocityGradientTensor/strainRate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5942999892239328}}
{"text": "function eclipVec=ICRS2Eliptic(vec,TT1,TT2,method)\n%%ICRS2ECLIPTIC Convert a location vector from the International\n%               Celestial Reference System (ICRS) to eliptic coordinates\n%               either using the IAU 2006 precession model or the Vondrak\n%               400 millennia precession model.\n%\n%INPUTS: x The NXnumVec collection of vectors in the ICRS to convert. N\n%          can be 2, or 3. If the vectors are 2D, then they are assumed to\n%          be azimuth and elevation in radians. 3D vectors are assumed to\n%          be Cartesian position.\n% Jul1, Jul2 Two parts of a Julian date given in terrestrial time (TT).\n%          The units of the date are days. The full date is the sum of\n%          both terms. The date is broken into two parts to provide more\n%          bits of precision. It does not matter how the date is split.\n%   method An optional parameter specifying which algorithm is to be used.\n%          Possible values are\n%          0 (The default if omitted or an empty matrix is passed) Use the\n%            IAU 2006 precession model.\n%          1 Use the long-term (Vondrak) precession model.\n%\n%OUTPUTS: xG The vectors rotated into the ecliptic coordinate system. If\n%            the input was 2D azimuth and elevation, the output will be\n%            the same. If the input was Cartesian, then the output will be\n%            Cartesian.\n%\n%This function is a Matlab interface for the relevant functions in the\n%International Astronomical Union's (IAU) Standard's of Fundamental\n%Astronomy library.\n%\n%The ecliptic is defined in the IERS Conventions [1] to be the \"the\n%plane perpendicular to the mean heliocentric orbital angular momentum\n%vector of the Earth-Moon barycentre in the BCRS\".\n%\n%The algorithm can be compiled for use in Matlab  using the\n%CompileCLibraries function.\n%\n%The algorithm is run in Matlab using the command format\n%eclipVec=ICRS2Eliptic(vec,TT1,TT2,method);\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%July 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nerror('This function is only implemented as a mexed C or C++ function. Please run CompileCLibraries.m to compile the function for use.')\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/Celestial_and_Terrestrial_Systems/ICRS2Eliptic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245618, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5942999810381523}}
{"text": "function S = mk_naive_struct(n,C)\n%\n% S = mk_naive_struct(Number_of_nodes, Class_node)\n%\nS = zeros(n);\nS(C,setdiff(1:n,C)) = 1;", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/learning/mk_naive_struct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5942876946539012}}
{"text": "% usage demo for\n\n% Masked k-order statistic filter for double data\n% -------------------------------------------------\n% by Fabio Bellavia (fbellavia@unipa.it),\n% refer to: F. Bellavia, D. Tegolo, C. Valenti,\n% \"Improving Harris corner selection strategy\",\n% IET Computer Vision 5(2), 2011.\n% Only for academic or other non-commercial purposes.\n\n% see kordstatfilt2.m for more details\n\n% compile the mex file\n% tested with Matlab R2012a x32 on Ubuntu 12.04  \nmex ordstatfilt2.c\n\n% input data\nim=double(rgb2gray(imread('donkey.jpg')));\nfigure;\nimshow(im,[]);\n\n% circular kernel\nker=fspecial('disk',15)>0;\n\n% median filter\nidx=sum(ker(:))/2+0.5;\nres=kordstatfilt2(im,ker,idx);\nfigure;\nimshow(res,[]);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/36686-masked-k-order-statistic-filters-for-2d-data/kordstatfilt2/kordstatfilt2/test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5942876946539012}}
{"text": "% load an image from uiuc texture database\nall_images = retrieve_uiuc(1,1);\nx = all_images{1}{1};\n\n% compute its 2d scattering \ntic;\noptions.feat = 'scatt2d_uiuc';\n[feat_f,outmeta,outprecomp] = gfeat(x,options);\ntoc; % about 20 seconds on a core i7 2.4Ghz\n\n% check number of coefficients : \n% there should be\n% 9 (scales) * 8 (orientations) coefficients of order 1\n% and\n% (7+5+3+1) (scales) * 8^2 (orientations) coefficients of order 2\ntheoritical_size = 9*8 + (7+5+3+1)*8^2;\n\nassert(numel(feat_f) == theoritical_size);", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/test/classification/test_gfeat_scatt2d_uiuc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5942876892689725}}
{"text": "function [I1,wl1,rgb1,g,H1,extra,s,G,S] = estimate_PSF_SRF(I,wl,bbl,rgb,s,extra,options)\n%ESTIMATE_PSF_SRF Estimate point spread function (PSF) and spectral \n%response function (SRF)\ndisp('Start estimating PSF and SRF');\nshow_fig = parse_param(options,'show_fig',0);\n\nI1 = I(:,:,bbl);\nwl1 = wl(bbl);\nrgb1 = rgb;\n\nY = reshape_hsi(I1);\nX = reshape(rgb1, [size(rgb1,1)*size(rgb1,2), size(rgb1,3)]);\n[N,B] = size(Y);\nb = size(X,2);\nR2 = s + extra*2;\nR = prod(R2);\n\nconvergence_t = 1e-3;\n\nSRF_range = parse_param(options,'SRF_range','color');\n% construct S\n[I_sel,bands_sel] = select_relevant_bands(I1,wl1,SRF_range);\nwl_sel = wl1(bands_sel)';\nS = zeros(B,length(wl_sel));\nfor i = 1:size(S,2)\n    S(bands_sel(i),i) = 1;\nend\n\n% construct C\nCs = construct_C(I1,rgb1,s,extra);\nC = cat(2,Cs{:});\n\nY1 = [ones(N,1),Y*S];\n\n% construct D\nD = zeros(N*b,R);\nfor i = 1:N\n    D((i-1)*b+1:i*b,:) = X'*Cs{i}';\nend\n\n% contruct options\noptions = [];\noptions.D = D;\noptions.Y1 = Y1;\noptions.D1D = D'*D;\noptions.D1YI = D'*kron(Y1,eye(b));\n\ng = (1/R) * ones(R,1);\nG = g2G(C,g,N);\n\n\ndelta_t0 = 1e-4;\ndelta_t_g = delta_t0;\n\nerrors = [];\nfor iter = 1:200\n    % Update H1\n    H1 = solve_for_H1(G*X, Y1, struct('lambda',1e-4));\n    options.H1 = H1;\n    \n    % Update G\n    der_g = calc_der_g(g, options);\n    options.der_g = der_g;\n    delta_t_g = calc_time_step_adaptive(@eval_obj_fun_g, @update_g, ...\n        g, options, delta_t_g, delta_t0);\n    g = update_g(g, options, delta_t_g);\n    options.g = g;\n    G = g2G(C,g,N);\n    \n    % Test convergence\n    errors(end+1) = eval_obj_fun(options);\n\n    if test_convergence(errors, convergence_t)\n        break;\n    end\n    \n    if mod(iter,100) == 0\n        disp(['Process iteration ',num2str(iter)]);\n    end\nend\n\nif show_fig\n    figure('name','PSF'), mesh(reshape(g,R2));\n    figure('name','SRF'), plot(H1);\nend\n\nfunction der_g = calc_der_g(g, options)\nvecH1 = (options.H1)';\nvecH1 = vecH1(:);\nder_g = options.D1D * g - options.D1YI * vecH1;\n\nfunction val = eval_obj_fun_g(g, options)\nvecYH = options.Y1 * options.H1;\nvecYH = vecYH';\nvecYH = vecYH(:);\nval = sum((options.D * g - vecYH).^2);\n\nfunction g_new = update_g(g, options, delta_t)\nder_g = options.der_g;\n\ng_new = g - delta_t * der_g;\ng_new = project_to_simplex(g_new');\ng_new = g_new';\n\nfunction val = eval_obj_fun(options)\ng = options.g;\nval = eval_obj_fun_g(g,options);\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/Fusion/estimate_PSF_SRF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5942876843044061}}
{"text": "% FUNCTION [idx,pnts] = kdtree_range(kdtree, range)\n%\n% AUTHOR:     Steven Michael\n%             (smichael@ll.mit.edu)\n%\n% DATE:       2/17/05\n%\n% DESCRIPTION:\n%\n%  This function simply returns all the points of a kdtree that\n%  are within an N-dimesional volume bounded by \"range\"\n%\n% INPUTS:\n%\n%   kdtree :    A KD Tree previously created with kdtree_create\n%\n%\n%   range  :    An array (ndim X 2) of points that specify the bounds\n%               of an \"ndim\" dimensional volume.  All the points of the\n%               kdtree within this volume will be returned.\n%               The range is boundary inclusive: [min,max]\n%\n%               Alternatively, range can be a (nsearches X ndim X 2)\n%               array of points that describes multiple range boxes\n%               -- the \"nsearches\" index references the range box.  The\n%               output in this case will be put into \"nsearches\"\n%               different cell arrays.\n% \n%\n% OUTPUTS:\n%\n%   idx    :    A (1 X N) array of points, where N is the number of\n%               points within the \"ndim\" dimensional volume. The value is\n%               the index to the releavant point in the array from which\n%               the tree was created.\n%\n%               If multiple range boxes are searches (a 3D array is input\n%               for range), then \"pnt\" will be a cell array, where the\n%               \"nth\" cell contains a (1XN) array of points ; N is the\n%               number of points within the \"ndim\" dimensional volume \n%               described by the \"nth\" index of the range input.\n%\n%\n%   pnts:  :    A (N X ndim) array the actual points. If the actual point\n%               instead of the index is desired, an optional second output\n%               will hold the points.  Multiple range boxes are handled\n%               as described above.\n%\n% Example: \n% \n%    % Create a list of 1000 random points in 3d space\n%    r = rand(1000,3);\n% \n%    % Create a tree from this list\n%    tree = kdtree(r);\n% \n%    % Find the point closest to the origin\n%    [pntidx,pntval] = kdtree_closestpoint(tree,[0 0 0]);\n%\n%    % Create a list \"r2\" of 100 random points in 3d space and\n%    % find the points in \"r\" that are closest to each point in \"r2\"\n%    [pntidx,pntval] = kdtree_closestpoint(tree,r2);\n%\n%    % Find all the points within the cube defined by \"rng\"\n%    rng = [ [.45 .55]; [.45 .55]; ; [.45 .55] ];\n%    pntidx = kdtree_range(tree,rng);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/7030-kd-tree-nearest-neighbor-and-range-search/kdtree/@kdtree/kdtree_range.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5942536098388499}}
{"text": "%GM_PHD_Construct_Update_Components\n%Last modified 12th September 2013\n%Matlab code by Bryan Clarke b.clarke@acfr.usyd.edu.au \n\n%This file creates the components needed for performing a Kalman filter update on the\n%targets using the measurement.\ns = sprintf('Step 3: Constructing update components for all targets, new and existing.');\ndisp(s);\n\n%We need to clear the data structures each iteration\neta = [];\nS = [];\nK = [];\nP_k_k = [];\n\nfor j = 1:numTargets_Jk_k_minus_1\n    m_j = mk_k_minus_1(:,j);\n    eta_j = H2 * m_j;%Observation model. Assume we see position AND velocity of the target.\n\n    P_range = calculateDataRange4(j); %4x4 array\n\n    PHt = Pk_k_minus_1(:,P_range) * H2'; %Taken from Tim Bailey's EKF code. 4x4 array\n\n    %Calculate K via Tim Bailey's method.\n    S_j = R2 + H2 * PHt;\n    %At this point, Tim Bailey's code makes S_j symmetric. In this case, it leads to the matrix being non-positive definite a lot of the time and chol() crashes.\n    %So we won't do that. \n    SChol= chol(S_j);\n\n    SCholInv= SChol \\ eye(size(SChol)); % triangular matrix, invert via left division\n    W1 = PHt * SCholInv;\n\n    K_j = W1 * SCholInv';\n\n    P_j = Pk_k_minus_1(:,P_range) - W1*W1';%4x4 array\n    %End Tim Bailey's code.\n    \n    eta = [eta, eta_j];\n    S = [S, S_j];\n    K = [K, K_j];\n    P_k_k = [P_k_k, P_j]; \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/42769-gaussian-mixture-probability-hypothesis-density-filter-gm-phd/GM_PHD_Filter_v104/GM_PHD_Filter/GM_PHD_Construct_Update_Components.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5942050553755988}}
{"text": "function [kernel, S] = dat2Kernel(data, kSize)\n% kernel = dat2Kernel(data, kSize,thresh)\n%\n% Function to perform k-space calibration step for ESPIRiT and create\n% k-space kernels. Only works for 2D multi-coil images for now.  \n% \n% Inputs: \n%       data - calibration data [kx,ky,coils]\n%       kSize - size of kernel (for example kSize=[6,6])\n%\n% Outputs: \n%       kernel - k-space kernels matrix (not cropped), which correspond to\n%                the basis vectors of overlapping blocks in k-space\n%       S      - (Optional parameter) The singular vectors of the\n%                 calibration matrix\n%\n%\n% See also:\n%           kernelEig\n%\n% (c) Michael Lustig 2013\n\n\n\n[sx,sy,nc] = size(data);\nimSize = [sx,sy] ;\n\ntmp = im2row(data,kSize); [tsx,tsy,tsz] = size(tmp);\nA = reshape(tmp,tsx,tsy*tsz);\n\n[U,S,V] = svd(A,'econ');\n    \nkernel = reshape(V,kSize(1),kSize(2),nc,size(V,2));\nS = diag(S);S = S(:);\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_ESPIRiT/dat2Kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5941939786879332}}
{"text": "function r = exp(a)\n%EXP          Taylor exponential  exp(a)\n%\n\n% written  05/21/09     S.M. Rump\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  e = 1e-30;\n  if 1+e==1-e                   % fast check for rounding to nearest\n    rndold = 0;\n  else\n    rndold = getround;\n    setround(0)\n  end\n\n  K1 = getappdata(0,'INTLAB_TAYLOR_ORDER') + 1;\n  \n  r = a;\n  N = size(a.t,2);\n  r.t(1,:) = exp(a.t(1,:));\n  for j=2:K1\n    r.t(j,:) = sum( repmat((1:j-1)',1,N).*r.t(j-1:-1:1,:).*a.t(2:j,:) , 1 ) ./ (j-1);\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/taylor/@taylor/exp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5941479382712797}}
{"text": "%\n% A variational approach to SPCP (Aravkin et al. 2014)\n%\n% RPCA | Lag-SPCP-SPG | Lagrangian SPCP solved by Spectral Projected Gradient (Aravkin et al. 2014)\n% process_video('RPCA', 'Lag-SPCP-SPG', 'dataset/demo.avi', 'output/demo_Lag-SPCP-SPG.avi');\n\nalg_path_aux = fullfile(lrs_conf.rpca_path,'SPGL1');\naddpath(genpath(alg_path_aux));\n\nnFrames     = size(M,2);\nlambda      = 1/sqrt(max(size(M,1),size(M,2)));\nL0          = repmat(median(M,2), 1, nFrames);\nS0          = M - L0;\nepsilon     = 5e-3*norm(M,'fro'); % tolerance for fidelity to data\n\n% Lagrangian SPCP solved by Spectral Projected Gradient\nopts    = struct('sum',false,'L0',L0,'S0',S0,'max',false,'tol',1e-3);\nlambdaL = 0.25; lambdaS = 0.01; % (Aravkin et al. 2014)\n[L,S] = solver_RPCA_Lagrangian(M,lambdaL,lambdaS,[],opts);\n\nrmpath(genpath(alg_path_aux));", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/Lag-SPCP-SPG/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5941479378793582}}
{"text": "function padua_test02 ( )\n\n%*****************************************************************************80\n%\n%% PADUA_TEST02 tests PADUA_POINTS.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    09 June 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'PADUA_TEST02\\n' );\n  fprintf ( 1, '  PADUA_POINTS returns the points of a Padua rule.\\n' );\n\n  for l = 0 : 10\n    n = padua_order ( l );\n    xy = padua_points ( l );\n    label = sprintf ( '  Level %d Padua points:', l );\n    r8mat_transpose_print ( 2, n, xy, label );\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/padua/padua_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.5941479364789625}}
{"text": "function Ath = threshold_components(A,options)\n\n% post processing of spatial components\n% for each component perform the following:\n%   (i)     perform median filtering \n%   (ii)    keep only pixels that contibute up to a level of total energy\n%   (iii)   perform morphological closing\n%   (iv)    extract largest connected component\n\n% Written by:\n% Eftychios A. Pnevmatikakis, Simons Foundation, 2015\n\n    defoptions.nrgthr = 0.9999;              % energy threshold\n    defoptions.clos_op = strel('square',3);  % morphological operator for closing\n    defoptions.medw = [3,3];                 % size of median filter\n    \n    if ~isfield(options,'nrgthr') || isempty(options.nrgthr); options.nrgthr = defoptions.nrgthr; end\n    if ~isfield(options,'clos_op') || isempty(options.clos_op); options.clos_op = defoptions.clos_op; end\n    if ~isfield(options,'medw') || isempty(options.medw); options.medw = defoptions.medw; end\n    if ~isfield(options,'d3') || isempty(options.d3); options.d3 = 1; end\n    \n    [d,nr] = size(A);\n    Ath = spalloc(d,nr,nnz(A));\n    Ath(:,nr-options.nb+1:nr) = A(:,nr-options.nb+1:nr);\n    indf = cell(nr,1);\n    valf = cell(nr,1);\n    parfor i = 1:nr-options.nb\n        A_temp = reshape(full(A(:,i)),options.d1,options.d2,options.d3);\n        for z = 1:options.d3\n            A_temp(:,:,z) = medfilt2(A_temp(:,:,z),options.medw);\n        end\n        A_temp = A_temp(:);\n        [temp,ind] = sort(A_temp(:).^2,'ascend'); \n        temp =  cumsum(temp);\n        ff = find(temp > (1-options.nrgthr)*temp(end),1,'first');\n        BW = zeros(options.d1,options.d2,options.d3);\n        BW(ind(ff:d)) = 1;\n        for z = 1:options.d3\n            BW(:,:,z) = imclose(BW(:,:,z),options.clos_op);\n        end\n        [L,NUM] = bwlabeln(BW,8*(options.d3==1) + 6*(options.d3~=1));\n        if NUM > 0\n            nrg = zeros(NUM,1);\n            for l = 1:NUM\n                ff = (L==l);\n                nrg(l) = sum(A_temp(ff).^2);\n            end\n            [~,indm] = max(nrg);\n            ff = find(L==indm);\n            %Ath(ff,i) = A(ff,i);\n            indf{i} = ff;\n            valf{i} = A_temp(ff);\n        else\n            valf{i} = 0;\n        end\n    end   \n    for i = 1:nr-options.nb\n        Ath(indf{i},i) = valf{i};\n    end\nend", "meta": {"author": "zhoupc", "repo": "CNMF_E", "sha": "ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f", "save_path": "github-repos/MATLAB/zhoupc-CNMF_E", "path": "github-repos/MATLAB/zhoupc-CNMF_E/CNMF_E-ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f/ca_source_extraction/utilities/threshold_components.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5941479322777752}}
{"text": "function test_failed = test_libltfat_rtdgtreal(varargin)\ntest_failed = 0;\nreturn;\nfprintf(' ===============  %s ================ \\n',upper(mfilename));\n\ndefinput.flags.complexity={'double','single'};\n[flags]=ltfatarghelper({},definput,varargin);\ndataPtr = [flags.complexity, 'Ptr'];\n\n[~,~,enuminfo]=libltfatprotofile;\nLTFAT_FIRWIN = enuminfo.LTFAT_FIRWIN;\nrdgt_phasetype = enuminfo.rtdgt_phasetype;\n\nglarr =     [500,  512, 1024, 90];\nMarr =      [1000, 512, 2048, 101];\naarr =      [100 , 256,  256, 40];\nWarr =      [10  ,   2,    1,  3];\n\nf = greasy;\n\na = 16;\ngl = 60;\ngdl = gl;\nM = 64;\nL = dgtlength(numel(f),a,M);\nM2 = floor(M/2) + 1;\ng = zeros(gl,1);\ngd = zeros(gdl,1);\ngPtr = libpointer(dataPtr,g);\ngdPtr = libpointer(dataPtr,gd);\nfunname = makelibraryname('firwin',flags.complexity,0);\ncalllib('libltfat',funname,LTFAT_FIRWIN.LTFAT_HANN,gl,gPtr);\n\nfunname = makelibraryname('gabdual_painless',flags.complexity,0);\nprd=calllib('libltfat',funname,gPtr,gl,a,M,gdPtr);\nif prd\n    warning('This is not painless frame');\n    g2Ptr = libpointer(dataPtr,fir2long(gPtr.Value,L));\n    gdPtr = libpointer(dataPtr,fir2long(gd,L));\n    funname = makelibraryname('gabdual_long',flags.complexity,0);\n    calllib('libltfat',funname,g2Ptr,L,1,a,M,gdPtr);\n    gdl = L;\nend\n\ncframes = signal2frames(f,gl,a,M);\n% cframes2 = bsxfun(@times,cframes,M*gPtr.Value.*gdPtr.Value);\n% f2 = frames2signal(cframes2,gl,a);\n% norm(f-postpad(f2,numel(f)))\nN = size(cframes,2);\n\n\n%ctrue = fftreal(ifftshift(bsxfun(@times,cframes,fftshift(gPtr.Value)),1));\nctrue = dgtreal(f,gPtr.Value,a,M,'timeinv');\np = libpointer();\npinv = libpointer();\n\nfunname = makelibraryname('rtdgtreal_init',flags.complexity,0);\ncalllib('libltfat',funname,gPtr,gl,M,rdgt_phasetype.LTFAT_RTDGTPHASE_ZERO,p);\nfunname = makelibraryname('rtidgtreal_init',flags.complexity,0);\ncalllib('libltfat',funname,gdPtr,gdl,M,rdgt_phasetype.LTFAT_RTDGTPHASE_ZERO,pinv);\n\nc = zeros(2*M2,N);\nf2 = zeros(gdl,N);\nfPtr = libpointer(dataPtr,cframes);\ncPtr = libpointer(dataPtr,c);\nf2Ptr = libpointer(dataPtr,f2);\n\ncalllib('libltfat','ltfat_rtdgtreal_execute_d',p,fPtr,N,cPtr);\nnorm(ctrue - interleaved2complex(cPtr.Value),'fro')\ncalllib('libltfat','ltfat_rtidgtreal_execute_d',pinv,cPtr,N,f2Ptr);\n\nfrec = frames2signal(f2Ptr.Value,gdl,a);\nfigure(1);plot([f-postpad(frec,numel(f))]);\n\nfprintf('Coef error. %d \\n', norm(ctrue-interleaved2complex(cPtr.Value),'fro'));\nfprintf('Rec error. %d \\n', norm(f-postpad(frec,numel(f))));\n\nfigure(2);plotdgtreal(abs(ctrue)-abs(interleaved2complex(cPtr.Value)),a,M,'linabs');\n%imagesc(abs(interleaved2complex(cPtr.Value))./abs(ctrue))\n\ncalllib('libltfat','ltfat_rtdgtreal_done_d',p);\ncalllib('libltfat','ltfat_rtidgtreal_done_d',pinv);\n\n%norm(long2fir(gdtrue,gl) - gdPtr.Value)\n\nfunction cframes = signal2frames(f,gl,a,M)\n\n[Ls,~] = size(f);\nL=dgtlength(Ls,a,M);\nN = L/a;\nf = postpad(f,L);\n\ncframes = zeros(gl,N,1);\n\nidxrange = -floor(gl/2):ceil(gl/2)-1;\n\nfor n=0:N-1\n    idx = mod(n*a + idxrange,L) + 1;\n    cframes(:,n+1) = f(idx);\nend\n\nfunction f = frames2signal(cframes,gl,a)\n\nN = size(cframes,2);\nL = N*a;\nf = zeros(L,1);\n\nidxrange = -floor(gl/2):ceil(gl/2)-1;\nfor n=0:N-1\n    idx = mod(n*a + idxrange,L) + 1;\n    f(idx) = f(idx) + cframes(:,n+1);\nend\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/libltfat/modules/libltfat/testing/mUnit/test_libltfat_rtdgtreal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.594147926676192}}
{"text": "function [ Z, H, dnorm] = cnmf ( X, k, y, varargin )\n% Matrix sizes\n% X: m x n\n% Z: m x num_of_components\n% H: num_of_components x num_of_components\n\n% Process optional arguments\npnames = {'z0' 'h0' 'bUpdateH' 'maxiter' 'nonlinearity_function', 'TolFun'};\n\n% Do SVD initialisation of the init components\n\nif 1\n    [z0, h0] = NNDSVD(abs(X), k, 0);\nelse\n    z0 = rand(size(X, 1), k);\n    h0 = rand(k, size(X,2));\nend\n\ndflts  = {z0, h0, 1, 300, @(x) x, 1e-5};\n\n[z0, h0, bUpdateH, max_iter, g, tolfun] = ...\n        internal.stats.parseArgs(pnames,dflts,varargin{:});\n\n\n% X =>  % p x n\nZ = z0; % p x k\n\nA = ind2vec([y; [length(y)+1:size(X, 2)]']')';\nH = max(abs(A' * pinv(h0)), eps); % c x k\n\nfor i = 1:max_iter\n    if bUpdateH\n        numer = A' * X' * Z;\n        H = H .* (numer ./ (((A' * A) * H * (Z' * Z)) + eps(numer)));\n    end\n   \n    numer = X * A * H;\n    Z = Z .* (numer ./  (Z * (H' * A') * (A * H) + eps(numer)));    \n    \n    if mod(i, 10) == 0 || mod(i+1, 10) == 0 \n        s = X - Z * H' * A';\n        dnorm = sqrt(sum(s(:).^2));\n        \n        if mod(i+1, 10) == 0\n            dnorm0 = dnorm;\n            continue\n        end\n\n%         if mod(i, 100) == 0\n            display(sprintf('...CNMF iteration #%d out of %d, error: %f\\n', i, max_iter, dnorm));\n%         end\n\n%         if exist('dnorm0')\n%             assert(dnorm <= dnorm0, sprintf('Rec. error increasing! From %f to %f. (%d)', dnorm0, dnorm, k));\n%         end\n\n        % Check for convergence\n        if exist('dnorm0') && dnorm0-dnorm <= tolfun*max(1,dnorm0)\n            display(sprintf('Stopped at %d: dnorm: %f, dnorm0: %f', i, dnorm, dnorm0));\n            break;\n        end\n     \n    end\nend\n\nH = A * H;\nH = H(length(y) +1 : end, :)';\n", "meta": {"author": "jwyang", "repo": "JULE.torch", "sha": "69bdfd82f9dfd431619a8ee25ac832da76a827e2", "save_path": "github-repos/MATLAB/jwyang-JULE.torch", "path": "github-repos/MATLAB/jwyang-JULE.torch/JULE.torch-69bdfd82f9dfd431619a8ee25ac832da76a827e2/matlab/approaches/nmf-deep/Deep-Semi-NMF-master/matlab/cnmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5941262121944413}}
{"text": "close all\nclear\n\n%% topology graph\nD = [1,-1,0,0,0,0,0,0,0,-1,0,1;\n    -1,0,0,0,0,0,1,-1,0,0,0,0;\n    0,1,-1,0,0,0,0,0,1,0,0,0;\n    0,0,0,0,0,1,-1,0,0,1,-1,0;\n    0,0,1,-1,0,0,0,0,0,0,1,-1;\n    0,0,0,0,1,-1,0,0,-1,0,0,0;\n    0,0,0,1,-1,0,0,1,0,0,0,0];\nL = D*D';\nH = D';\n\n%% dimensions\n[n,m] = size(D);\nd = 2;\n% r represents P(r)\nr = [2,0;\n    1,1;\n    1,-1;\n    0,1;\n    0,-1;\n    -1,1;\n    -1,-1];\n% P represents \\bar P(r)\nP = [r,ones(n,1)];\n% edge set\nedge = mod(reshape(find(D~=0),2,m),n);\nedge(edge==0) = n;\n\n%% target formation\nfigure\nfor i=1:m\n    plot(r(edge(:,i),1),r(edge(:,i),2),'k','linewidth',2); hold on\nend\nfor i=1:n\n    plot(r(i,1),r(i,2),'.','markersize',50);\nend\naxis([-2 2 -2 2]);\n\n%% trajectory\nfigure\nvia = [0,0;\n    5,0;\n    10,0;\n    10,-5;\n    10,-10;\n    5,-10;\n    0,-10];\nfor j=1:size(via,1)\n    if ~mod(j,2)\n        if j==4\n            T1 = diag([0.1,1]);\n        else\n            T1 = diag([1,0.1]);\n        end\n    else\n        T1 = eye(2);\n    end\n    T2 = rot2(-pi/2*floor((j-1)/2));\n    ra(:,:,j) = r*T2'*T1'+via(j,:);\n    qvia(j,:) = [vec(T1*T2)',via(j,:)];\n    for i=1:m\n        plot(ra(edge(:,i),1,j),ra(edge(:,i),2,j),'k','linewidth',2); hold on\n    end\nend\n[qr,dqr,ddqr,tr] = mstraj_(qvia,ones(1,6),0.1,0.2);\nA = reshape(qr(1,1:4)',[2,2]);\nb = qr(1,5:6)';\nxr = r*A'+b';\n% for j=1:length(tr)\n%     dA = reshape(dqr(j,1:4)',[2,2]);\n%     db = dqr(j,5:6)';\n%     dxr = r*dA'+db';\n%     xr = xr+dxr*0.1;\n%     plot(xr(1,1),xr(1,2),'bo');\n%     plot(xr(2,1),xr(2,2),'go');\n%     plot(xr(3,1),xr(3,2),'mo');\n%     drawnow\n% end\n\n\n%% calculate stress matrix\nE = [];\nfor i=1:n \n    E = [E;P'*H'*diag(H(:,i))];\nend\n[U,S,V] = svd(P);\n% the order in S: from big to small\nU1 = U(:,1:d+1);\nU2 = U(:,d+2:end);\n% in fact z is exactly the same as omega given in Fig. 3\nz = null(E);\n% check if all(svd(U2'*H'*diag(z)*H*U2)>0), then\nOmega = H'*diag(z)*H;\n\n%% initial position\nx = rand(n,d)*4-2; \ndx = zeros(size(x));\n% figure\nfor i=1:m\n    fig_edge(i) = plot(x(edge(:,i),1),x(edge(:,i),2),'k','linewidth',2); hold on\nend\nfor i=1:n\n    fig_node(i) = plot(x(i,1),x(i,2),'.','markersize',50);\nend\naxis([-2 12 -12 2]);\n\n%% simulation\ndt = 0.05;\nloop = 0;\nvideo_on = true;\nfor t=tr(1):dt:tr(end)\n    loop = loop+1;\n    dq = interp1(tr,dqr,t);\n    dA = reshape(dq(1:4)',[2,2]);\n    db = dq(5:6)';\n    dxr = r*dA'+db';\n    % test leader\n    alpha = 1;\n%     dx = dxr-alpha*(x-xr);\n    % followers apply control law (11)   \n    D = H';\n    gamma = diag(Omega);\n    for i=4:n\n        err_sum = [0,0];\n        edge_ind = find(D(i,:)~=0);\n        for k=edge_ind\n            node_ind = find(D(:,k)~=0);\n            j = node_ind(node_ind~=i);\n            err_sum = err_sum+z(k)*(x(i,:)-x(j,:)-dx(j,:));\n        end\n        dx(i,:) = -1/gamma(i)*err_sum;\n    end\n    % first 3 agents are leaders\n    dx(1:3,:) = dxr(1:3,:)-alpha*(x(1:3,:)-xr(1:3,:));\n    % update states\n    x = x+dt*dx;\n    xr = xr+dt*dxr;\n    pos_data(:,:,loop) = x;\n    % update figure\n    for i=1:m\n        set(fig_edge(i),'xdata',x(edge(:,i),1),'ydata',x(edge(:,i),2));\n    end\n    for i=1:n\n        set(fig_node(i),'xdata',x(i,1),'ydata',x(i,2));\n    end\n    % video\n    if video_on\n        frame(loop) = getframe(gcf);\n    end\n    drawnow\nend\n% write video\nif video_on \n    savevideo('affine_maneuver',frame);\nend\nfigure \nt_data = tr(1):dt:tr(end);\nxpos_data = squeeze(pos_data(:,1,:));\nypos_data = squeeze(pos_data(:,2,:));\nplot3(kron(ones(n,1),t_data)',xpos_data',ypos_data');\nxlabel('time/s');ylabel('x/m');zlabel('y/m');grid", "meta": {"author": "star2dust", "repo": "paper-simulation", "sha": "2d35e3beeccd2ce41f60c59e347b090f25960706", "save_path": "github-repos/MATLAB/star2dust-paper-simulation", "path": "github-repos/MATLAB/star2dust-paper-simulation/paper-simulation-2d35e3beeccd2ce41f60c59e347b090f25960706/Zhao2018Affine/affine_maneuver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5941262117890684}}
{"text": "% Author: Jai Juneja (adapted from SLAM course by Joan Sola)\n% Date: 12/02/2013\n%\n% For a point p_g in the global frame, determine the range-bearing\n% measurement y in the robot's local frame. This first requires a\n% transformation of the point p_g to the robot's local frame to give p_r.\n% This is then converted to a range and bearing vector with getMeasurement.\n%\n% Inputs:\n%   r = [x y alpha]'    :   Robot frame\n%   p_g = [pg_x pg_y]'  :   Point in global frame\n%\n% Outputs:\n%   y = [d a]           :   Range-bearing sensor measurement\n%   Optional:\n%   Y_r                 :   Jacobian of y wrt. r\n%   Y_pg                :   Jacobian of y wrt. p_g\n\nfunction [y, Y_r, Y_pg] = scanPoint(r, p_g)\n    \n    if nargout == 1\n        p_r = transToLocal(r, p_g);\n        y = getMeasurement(p_r);    % Obtain range-bearing measurement y of p_r\n    else\n        % Compute Jacobians:\n        [p_r, PR_r, PR_pg] = transToLocal(r, p_g);\n        [y, Y_pr] = getMeasurement(p_r);\n        \n        % From the chain rule, we deduce:\n        Y_r = Y_pr * PR_r;\n        Y_pg = Y_pr * PR_pg;\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/scanPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5941262063468826}}
{"text": "function [mopt, vopt, avals, mvals, vvals] = ...\n    scimat_optimal_intersecting_plane(scimat, m0, v0, params)\n% SCIMAT_OPTIMAL_INTERSECTING_PLANE  Optimise intersection plane for SCIMAT\n% segmentation mask.\n%\n% [MOPT, VOPT, AVALS, MVALS, VVALS] = ...\n%      scimat_optimal_intersecting_plane(SCIMAT, M0, V0, PARAMS)\n%\n%   This function computes the plane that intersects a SCIMAT segmentation\n%   mask in a way that minimizes the segmentation area intersected by the\n%   plane. That is, in some sense in finds the plane more orthogonal to the\n%   segmented volume.\n%\n%   (Note that the area is computed on the convex hull of the plane\n%   intersection with the volume.)\n%\n%   SCIMAT is the struct with the volume that we want to intersect (see\n%   \"help scimat\" for details).\n%\n%   M0 is the rotation centroid. This centroid will not change.\n%\n%   V0 is a 3-vector that describes the normal vector to the initial\n%   intersecting plane. By default, the initial plane is horizontal.\n%\n%   PARAMS is a struct with optimisation parameters:\n%\n%   * PARAMS.TYPE is a string. 'local' (default) means that the\n%   intersected area will be minimised using multidimensional unconstrained\n%   nonlinear minimization (Nelder-Mead, fminsearch). 'global' means that\n%   area values will be systematically computed over a range of plane\n%   inclination values.\n%\n%   * PARAMS.RAD can be a scalar or 2-vector:\n%\n%     scalar:   RAD is the radius of a 2D smoothing disk. The 2D image\n%               obtained from intersecting the 3D volume by the plane at\n%               each optimization iteration will be smoothed out using the\n%               disk before computing the area.\n%     2-vector: The smoothing element is a 3D ball. Instead of smoothing\n%               a 2D image at each iteration, the whole 3D image volume is\n%               smoothed with the ball at the beginning. RAD(1) is the ball\n%               radius in the XY-plane. RAD(2) is the ball height.\n%\n%   * PARAMS.RANGE (global optimisation only): Angular range. The azimuth\n%     of V0 will be changed RANGE(1) rad in any direction to compute\n%     area values. The elevation of V0 will be changed RANGE(2) rad.\n%     (Default RANGE(1) = RANGE(2) = 0.5236 rad = 30\u00ba).\n%     \n%   * PARAMS.N (global optimisation only): Number of azimuth (N(1)) or\n%   elevation (N(2)) samples. (Default N(1) = N(2) = 61).\n%\n%   MOPT is the centroid of the optimal intersection.\n%\n%   VOPT is the normal vector to the optimal plane.\n%\n%   Note that because M0 and MOPT are both contained in the optimal plane,\n%   the duples (M0, VOPT) and (MOPT, VOPT) define the same optimal plane.\n%\n%   AVALS is a vector with the record of area values from the optimization.\n%\n%   MVALS is a volume with the coordinates of M at the different tested\n%   values. If optimisation is 'local', then MVALS is a matrix where each\n%   column is the centroid at each iteration step. If optimisation is\n%   'global', then MVALS is a volume where MVALS(T,P,:) is the centroid for\n%   the normal vector VVALS(T,P,:).\n%\n%   VVALS is a volume like MVALS, only for the normal vectors.\n\n% Author(s): Ramon Casero <rcasero@gmail.com>, Vicente Grau\n% Copyright \u00a9 2010, 2014 University of Oxford\n% Version: 0.2.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 <http://www.gnu.org/licenses/>.\n\n%% Checks and initialization\n\n% check arguments\nnarginchk(2, 4) ;\nnargoutchk(0, 5) ;\n\n% defaults\nif (nargin < 3 || isempty(v0))\n    v0 = [0 0 1];\nend\nif (nargin < 4 || isempty(params))\n    params.type = 'local';\n    params.rad = [];\n    params.range = [30 30] / 180 * pi;\n    params.n = [61 61];\n    se = [];\nend\nif (~isfield(params, 'type'))\n    params.type = 'local';\nend\nif (~isfield(params, 'rad'))\n    params.rad = [];\n    se = [];\nend\nif (~isfield(params, 'range'))\n    params.range = [30 30] / 180 * pi;\nend\nif (~isfield(params, 'n'))\n    params.n = [61 61];\nend\n\n% prevent user entering rotation matrix instead of initial vector by\n% mistake\nif (size(v0, 2) ~= 1 || size(v0, 1) ~= 3)\n    error('V0 must be a column 3-vector')\nend\n\n% remove the dummy dimension and convert image data to double\nscimat = scimat_squeeze(scimat, true);\n\n% convert radius from real world size into number of pixels\nparams.rad = round(...\n    params.rad ./ [scimat.axis(1:length(params.rad)).spacing]);\n\n% create disk for dilation/erosion if we are going to smooth in 2D\nif (length(params.rad) == 1)\n    se = strel('disk', params.rad);\nend\n\n% 3D smoothing of the segmentation edges\nif (length(params.rad) == 2)\n    se = strel('ball', params.rad(1), params.rad(2));\n    scimat.data = imdilate(scimat.data, se);\n    scimat.data = imerode(scimat.data, se);\nend\n\n% generate 3D grid of coordinates\n[x, y, z] = scimat_ndgrid(scimat);\n\n% % DEBUG: compute intersection of SCIMAT volume with the initial plane\n% % (if you want to visualize the image as in Seg3D, you need to do 'axis\n% % xy')\n% im = scimat_intersect_plane(scimat, m0, v0, x, y, z);\n\n%% Optimisation of the intersection area\n\n% convert Cartesian coordinates into spherical coordinates (length has to\n% be one); note: we use phi for azimuth, and theta for elevation, contrary\n% to Matlab's naming convention\n[phi0, theta0] = cart2sph(v0(1), v0(2), v0(3));\n\n% group spherical coordinates into vector\nalpha0 = [phi0, theta0];\n\n% init variables to keep track of the evolution of area values in the\n% optimisation\navals = [];\nmvals = [];\nvvals = [];\n    \n% local or global optimisation\nif strcmp(params.type, 'local')\n\n    % run optimisation to find minimum area; note that v0 is the only\n    % variable optimised, but the rest (scimat, x, y, z, m, rad, se) are\n    % available to segmented_area_of_intersection() because the latter is a\n    % subfunction\n    alpha = fminsearch(@segmented_area_of_intersection, alpha0);\n    \n    % convert result from spherical to Carterian coordinates\n    [aux1 aux2 aux3] = sph2cart(alpha(1), alpha(2), 1.0);\n    vopt = [aux1 aux2 aux3];\n    \n    % final centroid of the intersecting plane\n    mopt = mvals(:, end);\n\nelseif strcmp(params.type, 'global')\n    \n    % interval of azimuth angle values, phi \\in [-180\u00ba, 180\u00ba] or \\in \n    % [0, 360\u00ba]\n    phimin = phi0 - abs(params.range(1));\n    phimax = phi0 + abs(params.range(1));\n    \n    % interval of elevation angle values, theta \\in [-90\u00ba, 90\u00ba]\n    thmin = max(theta0 - abs(params.range(2)), -pi/2);\n    thmax = min(theta0 + abs(params.range(2)), pi/2);\n    \n    % sample angle intervals\n    phivals = linspace(phimin, phimax, params.n(1));\n    thetavals = linspace(thmin, thmax, params.n(2));\n    \n    % create matrices to save outputs; note that for each area value we\n    % need to save a 3-vector with the rotation point, and a 3-vector with\n    % the normal plane\n    avals = zeros(length(thetavals), length(phivals));\n    mvals = zeros(length(thetavals), length(phivals), 3);\n    vvals = zeros(length(thetavals), length(phivals), 3);\n    \n    % compute area for each combination of elevation and azimuth angles\n    for T = 1:length(thetavals) % elevation\n        for P = 1:length(phivals) % azimuth\n            [a, mnew, v] = segmented_area_of_intersection(...\n                [phivals(P) thetavals(T)]);\n            \n            % put values in output matrices\n            avals(T, P) = a;\n            mvals(T, P, :) = mnew;\n            vvals(T, P, :) = v;\n            \n        end\n    end\n    \n    % find minimum area\n    [foo, idx] = min(avals(:));\n    \n    % convert linear index to multiple subscripts\n    [T, P] = ind2sub(size(avals), idx);\n    \n    % output optimal plane\n    mopt = squeeze(mvals(T, P, :));\n    vopt = squeeze(vvals(T, P, :));\n    \nelse\n    error(['Optimisation type not implemented: ' params.type])\nend\n\n    %% Objective function (the function we are trying to minimise)\n    \n    % rotate plane, intersect with image, and compute segmented area\n    function [a, mnew, v] = segmented_area_of_intersection(alpha)\n        \n        % convert spherical to Carterian coordinates\n        [aux1 aux2 aux3] = sph2cart(alpha(1), alpha(2), 1.0);\n        v = [aux1 aux2 aux3]';\n        \n        % vector cannot be zero\n        if (norm(v) == 0)\n            error('Normal vector to plane cannot be (0,0,0)')\n        end\n        \n        % this function cannot deal with vertical planes, because of a\n        % singularity\n        if (v(3) == 0)\n            error('Intersecting plane cannot be vertical')\n        end\n\n        % compute intersection of plane with volume\n        [im, zp, xp, yp] = scimat_intersect_plane(scimat, m0, v, x, y, z);\n        \n        % 2D smoothing of the segmentation edges\n        if (length(params.rad) == 1)\n            im = imdilate(im, se);\n            im = imerode(im, se);\n        end\n        \n%         % DEBUG: plot rotated plane\n%         hold off\n%         plot3(xp(:), yp(:), zp(:), '.r')\n        \n        % find segmented voxels in the 2D cut\n        idx = find(im);\n\n        % get coordinates of segmented voxels\n        xps = xp(idx);\n        yps = yp(idx);\n        zps = zp(idx);\n        \n%         % DEBUG: visualize intersection projected onto horizontal plane\n%         hold off\n%         imagesc(xp(:), yp(:), im > 0)\n%         hold on\n%         % DEBUG: compute and plot convex hull\n%         idx2 = convhull(xps, yps);\n%         vxs = xps(idx2);\n%         vys = yps(idx2);\n%         plot(vxs, vys, 'w')\n%         xlabel('x (m)')\n%         ylabel('y (m)')\n%         pause\n        \n        % compute a rotation matrix from the Cartesian system to the\n        % rotated plane\n        rotmat = vec2rotmat(v);\n  \n        % we are now seeing the rotated plane projected onto the horizontal\n        % plane, i.e. we see the segmentation mask in perspective.\n        % In order to see the true area of the segmentation mask, we need\n        % to change the system of coordinates so that the rotated plane\n        % becames the XY plane\n        \n        % first, move segmented points so that centroid is at (0,0,0)...\n        xps = xps - m0(1);\n        yps = yps - m0(2);\n        zps = zps - m0(3);\n        \n        % ...second, make the rotated plane horizontal, by inverting the\n        % rotation...\n        xyzps = [xps(:) yps(:) zps(:)] * rotmat;\n        xps = xyzps(:, 1);\n        yps = xyzps(:, 2);\n        zps = xyzps(:, 3);\n        \n        % if everything has gone alright, then the z-coordinate of xyzp\n        % should be zero (+numerical errors), because the rotated plane is\n        % now the XY plane\n        assert(abs(min(zps)) < 1e-10)\n        assert(abs(max(zps)) < 1e-10)\n        \n%         % DEBUG: visualize segmentation mask in real world coordinates\n%         hold off\n%         plot(xps + m0(1), yps + m0(2), 'r*')\n%         axis ij\n        \n        % compute convex hull (reuse idx2): note convex hull coordinates\n        % are on projected space\n        idx2 = convhull(xps, yps);\n        vxs = xps(idx2);\n        vys = yps(idx2);\n        \n        % compute x-,y-coordinates centroid and area of polygon\n        [mnew, a] = polycenter(vxs, vys);\n        mnew(3) = 0;\n        \n        % the centroid is now on projected coordinates, but we need to put\n        % it back on the real world coordinates\n        mnew = rotmat * mnew';\n        mnew = (mnew' + m0)';\n        \n        % for the global algorithm, values are recorded in a different way\n        if strcmp(params.type, 'local')\n            % kept track of optimisation evolution\n            avals = [avals a];\n            vvals = [vvals v];\n            mvals = [mvals mnew];\n        end\n        \n    end\nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/FiltersToolbox/scimat_optimal_intersecting_plane.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5941261958678842}}
{"text": "% LOGDET_KRON_LDLCHOL - Computes the log-determinant of a matrix using its\n% Cholesky factor from SuiteSparse.\n%\n% Y = LOGDET_LDLCHOL(LD1,LD2)\n%\n% Computes the log-determinant of the matrix X whose Cholesky factor is\n% the triangular matrix U. U can be lower or upper triangular.\n%\n% More generally, X could be a product of two instances of U and/or U'. For\n% instance, X=U'*U' or X=U'*U.\n\n% Last modified 2010-11-09\n% Copyright (c) Jaakko Luttinen\n\nfunction y = logdet_ldlchol(LD1,LD2)\n\nN1 = size(LD1,1);\nN2 = size(LD2,1);\n\ny = N2*logdet_tri(LD1) + N1*logdet_tri(LD2);", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/matrix_computations/logdet_kron_ldlchol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5941261904256985}}
{"text": "%% Machine Learning Online Class - Exercise 3 | Part 2: Neural Networks\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%     lrCostFunction.m (logistic regression cost function)\n%     oneVsAll.m\n%     predictOneVsAll.m\n%     predict.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%% Setup the parameters you will use for this exercise\ninput_layer_size  = 400;  % 20x20 Input Images of Digits\nhidden_layer_size = 25;   % 25 hidden units\nnum_labels = 10;          % 10 labels, from 1 to 10   \n                          % (note that we have mapped \"0\" to label 10)\n\n%% =========== Part 1: Loading and Visualizing Data =============\n%  We start the exercise by first loading and visualizing the dataset. \n%  You will be working with a dataset that contains handwritten digits.\n%\n\n% Load Training Data\nfprintf('Loading and Visualizing Data ...\\n')\n\nload('ex3data1.mat');\nm = size(X, 1);\n\n% Randomly select 100 data points to display\nsel = randperm(size(X, 1));\nsel = sel(1:100);\n\ndisplayData(X(sel, :));\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% ================ Part 2: Loading Pameters ================\n% In this part of the exercise, we load some pre-initialized \n% neural network parameters.\n\nfprintf('\\nLoading Saved Neural Network Parameters ...\\n')\n\n% Load the weights into variables Theta1 and Theta2\nload('ex3weights.mat');\n\n%% ================= Part 3: Implement Predict =================\n%  After training the neural network, we would like to use it to predict\n%  the labels. You will now implement the \"predict\" function to use the\n%  neural network to predict the labels of the training set. This lets\n%  you compute the training set accuracy.\n\npred = predict(Theta1, Theta2, X);\n\nfprintf('\\nTraining Set Accuracy: %f\\n', mean(double(pred == y)) * 100);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%  To give you an idea of the network's output, you can also run\n%  through the examples one at the a time to see what it is predicting.\n\n%  Randomly permute examples\nrp = randperm(m);\n\nfor i = 1:m\n    % Display \n    fprintf('\\nDisplaying Example Image\\n');\n    displayData(X(rp(i), :));\n\n    pred = predict(Theta1, Theta2, X(rp(i),:));\n    fprintf('\\nNeural Network Prediction: %d (digit %d)\\n', pred, mod(pred, 10));\n    \n    % Pause with quit option\n    s = input('Paused - press enter to continue, q to exit:','s');\n    if s == 'q'\n      break\n    end\nend\n\n", "meta": {"author": "Ayatans", "repo": "Machine-Learning-homework", "sha": "4550cfc0426c9da8072dff165130fff40d138c10", "save_path": "github-repos/MATLAB/Ayatans-Machine-Learning-homework", "path": "github-repos/MATLAB/Ayatans-Machine-Learning-homework/Machine-Learning-homework-4550cfc0426c9da8072dff165130fff40d138c10/machine-learning-ex3/ex3/ex3_nn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.5941055141288171}}
{"text": "classdef EIMEGO < ALGORITHM\n% <multi> <real/integer> <expensive>\n% Expected improvement matrix based efficient global optimization\n% InfillCriterionIndex --- 1 --- infill criterion index number\n\n%------------------------------- Reference --------------------------------\n% D. Zhan, Y. Cheng, and J. Liu, Expected improvement matrix-based infill\n% criteria for expensive multiobjective optimization, IEEE Transactions on\n% Evolutionary Computation, 2017, 21(6): 956-975.\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 Dawei Zhan\n\n    methods\n        function main(Algorithm,Problem)\n            %% Parameter setting\n            % 1 for Euclidean distance-based EIM criterion (default)\n            % 2 for Maximin distance-based EIM criterion\n            % 3 for Hypervolume-based EIM criterion\n            InfillCriterionIndex = Algorithm.ParameterSet(1);\n\n            %% Generate the initial design points\n            % number of design variables\n            D = Problem.D;\n            % number of objective functions\n            M = Problem.M;\n            % number of initial design points\n            N  = 11*D-1;\n            % generate initial design points using Latin Hypercube sampling\n            PopDec = repmat(Problem.upper-Problem.lower,N,1).*UniformPoint(N,D,'Latin')+repmat(Problem.lower,N,1);\n            % calculate initial design points\n            Population   = Problem.Evaluation(PopDec);\n\n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                % scale the objective values to 0 and 1\n                PopDec = Population.decs;\n                PopObj = Population.objs;\n                N  = size(PopDec,1);       \n                PopObjScaled = (PopObj-repmat(min(PopObj),N,1))./(repmat(max(PopObj),N,1)-repmat(min(PopObj),N,1));   \n                % bulid Kriging models for all the objective functions\n                KrigingModel = cell(1,M);\n                for i = 1 : M\n                    KrigingModel{i}= dacefit(PopDec,PopObjScaled(:,i),'regpoly0','corrgauss',1*ones(1,D),0.001*ones(1,D),1000*ones(1,D));\n                end       \n                % select one candidate with the maximum EIM value using GA\n                PopDec     = InfillSamplingEIM(Problem,KrigingModel,PopObjScaled,InfillCriterionIndex);\n                Population = [Population,Problem.Evaluation(PopDec)];\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/Algorithms/Multi-objective optimization/EIM-EGO/EIMEGO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.594096278883038}}
{"text": "function f = perform_mesh_smoothing(face,vertex,f,options)\n\n% perform_mesh_smoothing - smooth a function defined on a mesh by averaging\n%\n%   f = perform_mesh_smoothing(face,vertex,f,options);\n%\n%   Smooth a function f on a width of options.niter_averaging vertices.\n%\n%   Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\nnaver = getoptions(options, 'niter_averaging', 1);\ntype = getoptions(options, 'averaging_type', 'combinatorial');\n\nif nargin<3\n    f = [];\nend\nif isempty(f)\n    f = vertex;\nend\nif size(f,1)<size(f,2)\n    f = f';\nend\n[vertex,face] = check_face_vertex(vertex,face);\n\nif size(f,2)>1\n    for i=1:size(f,2)\n        f(:,i) = perform_mesh_smoothing(face,vertex,f(:,i),options);\n    end\n    return;\nend\n\nn = max(face(:));\n\n% compute normalized averaging matrix\nif strcmp(type, 'combinatorial')\n    %add diagonal\n    W = triangulation2adjacency(face) + speye(n);\n    D = spdiags(full(sum(W,2).^(-1)),0,n,n);\n    W = D*W;\nelse\n    options.normalize=1;\n    W = compute_mesh_weight(vertex,face,type,options);\nend\n\n% do averaging to smooth the field\nfor k=1:naver\n    f = W*f;\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_wavelet_meshes/toolbox/perform_mesh_smoothing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5940962717852071}}
{"text": "function obj=stat_bin2d(obj,varargin)\n% stat_bin2d() Makes 2D bins of X and Y data and displays count\n%\n% Parameters as 'name',value pairs:\n% - 'nbins': Array in the form of [nxbins nybins] to set the\n% number of bins in each dimension\n% - 'edges': Cell in the form of {[x__edges] [y_edges]} to set\n% custom bin edges for each dimension\n% - 'geom': Set how results are displayed. 'image' uses a\n% heatmap (default), 'contour' uses a contour plot. 'point'\n% uses circles of varying size.\n\np=inputParser;\nmy_addParameter(p,'nbins',[30 30]);\nmy_addParameter(p,'edges',{});\nmy_addParameter(p,'geom','image'); %contour\n\nparse(p,varargin{:});\n\nobj.geom=vertcat(obj.geom,{@(dobj,dd)my_bin2d(dobj,dd,p.Results)});\nobj.results.stat_bin2d={};\nend\n\n\nfunction hndl=my_bin2d(obj,draw_data,params)\n\nx=comb(draw_data.x);\ny=comb(draw_data.y);\n\nif isempty(params.edges)\n    [N,C] = hist3([shiftdim(x),shiftdim(y)],params.nbins);\nelse\n    [N,C] = hist3([shiftdim(x),shiftdim(y)],'Edges',params.edges);\n    \n    obj.plot_lim.minx(obj.current_row,obj.current_column)=params.edges{1}(1);\n    obj.plot_lim.maxx(obj.current_row,obj.current_column)=params.edges{1}(end);\n    obj.plot_lim.miny(obj.current_row,obj.current_column)=params.edges{2}(1);\n    obj.plot_lim.maxy(obj.current_row,obj.current_column)=params.edges{2}(end);\n    \n    %Put values on the upper edges as if they were in the last\n    %bin\n    N(:,end-1)=N(:,end-1)+N(:,end);\n    N(end-1,:)=N(end-1,:)+N(end,:);\n    \n    %Remove upper edge\n    N(:,end)=[];\n    N(end,:)=[];\n    \nend\n\nobj.results.stat_bin2d{obj.result_ind,1}.edges=C;\nobj.results.stat_bin2d{obj.result_ind,1}.counts=N;\n\nswitch params.geom\n    case 'contour'\n        \n        [~,hndl]=contour(C{1},C{2},N',5,'Color',draw_data.color);\n        \n    case 'image'\n        \n        if ~obj.continuous_color_options.active\n            obj.continuous_color_options.active = true;\n        end\n        \n        Nr=reshape(N',1,numel(N));\n        sel=Nr>0;\n        %sel=true(size(Nr));\n        \n        if isempty(params.edges)\n            %Get polygon half widths\n            wx=(C{1}(2)-C{1}(1))/2;\n            wy=(C{2}(2)-C{2}(1))/2;\n            \n            %Generate polygon edges\n            [X,Y] = meshgrid(C{1},C{2});\n            \n            X=reshape(X,1,numel(X));\n            Y=reshape(Y,1,numel(Y));\n            \n            \n            patchesx=[X(sel)-wx ; X(sel)-wx ; X(sel)+wx ; X(sel)+wx ];\n            patchesy=[Y(sel)-wy ; Y(sel)+wy ; Y(sel)+wy ; Y(sel)-wy ];\n            \n            \n        else\n            [Xs, Ys]=meshgrid(params.edges{1}(1:end-1),params.edges{2}(1:end-1));\n            [Xe, Ye]=meshgrid(params.edges{1}(2:end),params.edges{2}(2:end));\n            \n            Xs=reshape(Xs,1,numel(Xs));\n            Ys=reshape(Ys,1,numel(Ys));\n            Xe=reshape(Xe,1,numel(Xe));\n            Ye=reshape(Ye,1,numel(Ye));\n            \n            patchesx=[Xs(sel) ; Xs(sel) ; Xe(sel) ; Xe(sel)];\n            patchesy=[Ys(sel) ; Ye(sel) ; Ye(sel) ; Ys(sel)];\n            \n            %If we have varied-size patches (we use rounding to\n            %get away with numerical issues of unique\n            if length(unique(round(diff(params.edges{1})*1e10)))>1 || length(unique(round(diff(params.edges{2})*1e10)))>1\n                %Correct values by the area of each patch ?\n                Nr=Nr./((Xe-Xs).*(Ye-Ys));\n                obj.aes_names.color='Count/area';\n            else\n                obj.aes_names.color='Count';\n            end\n            \n        end\n        \n        \n        \n        \n        \n        %patchesz=[Nr(sel) ; Nr(sel) ; Nr(sel) ; Nr(sel) ];\n        \n        %p=patch(patchesx,patchesy,patchesz,Nr(sel));\n        hndl=patch(patchesx,patchesy,Nr(sel));\n        set(hndl,'edgeColor','none')\n        \n        %Store color values\n        obj.plot_lim.maxc(obj.current_row,obj.current_column)=max(Nr);\n        obj.plot_lim.minc(obj.current_row,obj.current_column)=min(Nr);\n        \n        \n    case 'point'\n        [X,Y] = meshgrid(C{1},C{2});\n        X=reshape(X,1,numel(X));\n        Y=reshape(Y,1,numel(Y));\n        Nr=reshape(N',1,numel(N));\n        sel=Nr>0;\n        %hndl=point_patch(X(sel),Y(sel),Nr(sel)*(C{1}(2)-C{1}(1))/30,draw_data.color,20,ratio);\n        hndl=scatter(X(sel),Y(sel),Nr(sel)*10,draw_data.marker,'MarkerEdgeColor',draw_data.color,'MarkerFaceColor','none');\nend\n\nobj.results.stat_bin2d{obj.result_ind,1}.handle=hndl;\n\nend", "meta": {"author": "piermorel", "repo": "gramm", "sha": "b0fc59245c17d6fbcd86a105d893aeb745fb51e2", "save_path": "github-repos/MATLAB/piermorel-gramm", "path": "github-repos/MATLAB/piermorel-gramm/gramm-b0fc59245c17d6fbcd86a105d893aeb745fb51e2/@gramm/stat_bin2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.594096260303741}}
{"text": "% [func, fx] = mcmc_init_hamiltonian(x_init, get_logpdf, get_dlogpdf, ...\n% epsilon, L, func_x)\n%\n% epsilon is the parameter to the exponential distribution for sampling\n% the momentum\n%\n% L is the number of simulation steps\nfunction [func, fx] = mcmc_init_hamiltonian(x_init, get_logpdf, get_dlogpdf, ...\n                                            epsilon, L, func_x)\n\nif nargin < 6\n  func_x = @func_x_default;\nend\n\nx_current = x_init;\n[fx_current, dfx_current] = func_x(x_current);\nlogpdf_current = get_logpdf(fx_current);\ndlogpdf_current = get_dlogpdf(dfx_current);\n\nfunc = @hamiltonian;\nfx = fx_current;\n\n  function [x, fx] = hamiltonian(varargin)\n  \n  x = x_current;\n  \n  p = normrnd(0,1,size(x_current));\n  p_current = p;\n  \n  lp_current = logpdf_current(varargin{:});\n  dlp_current = dlogpdf_current(varargin{:});\n  \n% $$$   mycheckgrad(@chkgrad, x, 1e-6)\n% $$$   \n% $$$     function [y,dy] = chkgrad(x)\n% $$$     [fx, dfx] = func_x(x);\n% $$$     f = get_logpdf(fx);\n% $$$     df = get_dlogpdf(dfx);\n% $$$     y = f(varargin{:});\n% $$$     dy = df(varargin{:});\n% $$$     end\n\n  % Random step size\n  e = exprnd(epsilon);\n  \n  % Make a half step for momentum at the beginning\n  p = p + 0.5*e*dlp_current;\n  \n  for l=1:L\n    x = x + e * p;\n    \n    if any(isnan(x))\n      break;\n    end\n    \n    [fx, dfx] = func_x(x);\n    dlogpdf = get_dlogpdf(dfx);\n    dlp = dlogpdf(varargin{:});\n    if l < L\n      p = p + e * dlp;\n    else\n      logpdf = get_logpdf(fx);\n      lp = logpdf(varargin{:});\n    end\n  end\n  \n  if all(~isnan(x))\n\n    % Make a half step for momentum at the end\n    p = p + 0.5*e*dlp;\n  \n    % Negate momentum to make the proposal symmetric\n    p = -p;\n  \n  \n    if log(rand()) < ( (lp - 0.5*(p'*p)) - ...\n                       (lp_current - 0.5*(p_current'*p_current)) )\n      % Accept\n      disp('Accept hamiltonian')\n      x_current = x;\n      fx_current = fx;\n      dfx_current = dfx;\n      logpdf_current = logpdf;\n      dlogpdf_current = dlogpdf;\n    else\n      disp('Reject hamiltonian')\n    end\n  \n  else\n      disp('Reject hamiltonian')\n  end\n  \n  x = x_current;\n  fx = fx_current;\n  end\n  \n  \nend\n\nfunction [fx, dfx] = func_x_default(x)\nfx = x;\ndfx = x;\nend\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/mcmc/mcmc_init_hamiltonian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5940962560242194}}
{"text": "%Normalizes homogenous coordinates such that the last coordinate is 1\n%You can use any dimension of the vectors\n%\n%Author:    Christian Wengert, \n%           Institute of Computer Vision\n%           Swiss Federale Institute of Technology, Zurich (ETHZ)\n%           wengert@vision.ee.ethz.ch\n%           www.vision.ee.ethz.ch/~cwengert/\n%\n%Input:     x       unnormalized homogenous coordinates\n%\n%Output     y       normalized homogenous coordinates\n%\n%Syntax:    y = normalizeHomogenousCoordinates(x)\n\nfunction y = normalizeHomogenousCoordinates(x)\n\n    %get dimension of array\n    ni = size(x,1);\n    nj = size(x,2);\n    %go through\n    for j=1:1:nj\n        y(:,j) = x(:,j)./x(ni,j);\n    end\n    y(ni,:) = ones(1,nj);\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/normalizeHomogenousCoordinates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5940704717634263}}
{"text": "%% test modulate for all oasis functions. \ncol = {[0 114 178],[0 158 115], [213 94 0],[230 159 0],...\n    [86 180 233], [204 121 167], [64 224 208], [240 228 66]}; % colors\nplot_cvx = false; \n\n%% example 7:  constrained-foopsi, AR1\ng = 0.95;         % AR coefficient \nnoise = .3; \nT = 3000; \nframerate = 30;     \nfirerate = 0.5; \nb = 0;              % baseline \nN = 1;              % number of trials \nseed = 13;          % seed for genrating random variables \n[y, true_c, true_s] = gen_data(g, noise, T, framerate, firerate, b, N, seed); \n\n% cvx solution \n[c_cvx, s_cvx] = constrained_foopsi(y, g, noise); \n% case 1: all parameters are known \n[c_oasis, s_oasis] = deconvolveCa(y, 'ar1', g, 'constrained', 'sn', noise);  %#ok<*ASGLU>\n\nfigure('name', 'constrained-FOOPSI, AR1, known: g, sn', 'papersize', [15, 4]);\nplot_cvx = true; \nshow_results; \nplot_cvx = false; \n\n% case 2: nothing is known, estimate g with auto-correlation method\n[c_oasis, s_oasis,options] = deconvolveCa(y, 'ar1', 'constrained'); \n\nfprintf('true gamma:        %.3f\\n', g); \nfprintf('estimated gamma:   %.3f\\n', options.pars); \n\nfigure('name', 'FOOPSI, AR1, estimated: g, sn', 'papersize', [15, 4]); \nshow_results; \n\n% case 3: nothing is know, estimate g with auto-correlation method first\n% and then update it to minimize the RSS\n[c_oasis, s_oasis, options] = deconvolveCa(y, 'ar1', 'constrained', ...\n    'optimize_pars'); \n\nfprintf('true gamma:        %.3f\\n', g); \nfprintf('estimated gamma:   %.3f\\n', options.pars); \n\nfigure('name', 'FOOPSI, AR1, estimated: g, sn, update:g', 'papersize', [15, 4]); \nshow_results; \n\n% case 4: nothing is know, estimate g with auto-correlation method first\n% and then update it to minimize the RSS, the baseline is also unknown\ntrue_b = 0.5; \n[c_oasis, s_oasis, options] = deconvolveCa(y+true_b, 'ar1', g,...\n    'constrained','optimize_b', 'sn', noise); \nfprintf('true gamma:        %.3f\\n', g); \nfprintf('estimated gamma:   %.3f\\n', options.pars); \nfprintf('true b:       %.3f\\n', true_b); \nfprintf('estimated b:       %.3f\\n', options.b); \nfprintf('tuning parameter:  %.3f\\n', options.lambda); \n\nfigure('name', 'FOOPSI, AR1, estimated: g, sn, lambda', 'papersize', [15, 4]); \nshow_results; \n\n% case 5: nothing is know, estimate g with auto-correlation method first\n% and then update it to minimize the RSS, the baseline is also unknown\ntrue_b = 0.5; \n[c_oasis, s_oasis, options] = deconvolveCa(y+true_b, 'ar1',...\n    'constrained','optimize_b', 'optimize_pars'); \nfprintf('true gamma:        %.3f\\n', g); \nfprintf('estimated gamma:   %.3f\\n', options.pars); \nfprintf('estimated b:       %.3f\\n', options.b); \nfprintf('tuning parameter:  %.3f\\n', options.lambda); \n\nfigure('name', 'FOOPSI, AR1, estimated: g, sn, lambda, update:g', 'papersize', [15, 4]); \nshow_results; \n\n%% ", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/deconvolution/examples/ar1_constrained_foopsi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5940704717634263}}
{"text": "function [L,E,EMAP] = crouzeix_raviart_cotmatrix(V,F)\n  % CROUZEIX_RAVIART_COTMATRIX Compute the Crouzeix-Raviart cotangent\n  % Laplacian matrix where we use test functions define at edge midpoints.\n  %\n  % See for example \"Discrete Quadratic Curvature Energies\" [Wardetzky, Bergou,\n  % Harmon, Zorin, Grinspun 2007]\n  %\n  % Inputs:\n  %   V  #V by dim list of vertex positions\n  %   F  #F by element-size list of triangle indices\n  % Outputs:\n  %   L  #E by #E edge-based sparse cotangent matrix\n  %   E  #E by 2 list of edges\n  %\n  % Examples:\n  %   % mesh in (V,F)\n  %   [Lcr,E,EMAP] = crouzeix_raviart_cotmatrix(V,F);\n  %   [Mcr,E,EMAP] = crouzeix_raviart_massmatrix(V,F);\n  %   [Ucr,~] = eigs(Lcr,Mcr,5,'sm');\n  %   % Convert between edge values and vertex values\n  %   E2V = sparse(E(:),repmat(1:size(E,1),1,2)',1,size(V,1),size(E,1));\n  %   E2V = bsxfun(@rdivide,E2V,sum(E2V,2));\n  %   V2E = sparse(E(:),repmat(1:size(E,1),1,2)',1,size(V,1),size(E,1))';\n  %   V2E = bsxfun(@rdivide,V2E,sum(V2E,2));\n  %   tsurf(F,[V(:,1:2) E2V*Ucr(:,end-1)])\n  %   \n  %   % Display discontinous solution\n  %   FF = reshape(1:numel(F),size(F));\n  %   VV = V(F,:);\n  %   EMAP = reshape(EMAP,size(F));\n  %   A = sparse( ...\n  %     [FF FF FF], ...\n  %     EMAP(:,[1 2 3 2 3 1 3 1 2]), ...\n  %     repmat(-[1 1 1 -1 -1 -1 -1 -1 -1],size(F,1),1), ...\n  %     size(VV,1), ...\n  %     size(E,1));\n  %   tsurf(FF,[VV(:,1:2) A*Ucr(:,end-1)])\n  %   \n  %\n  %\n  % See also: edge_laplacian, is_boundary_edge, crouzeix_raviart_massmatrix,\n  %   cotmatrix\n  %\n\n  %% check for non-manifold edges\n  %S = statistics(V,F,'Fast',true);\n  %if S.num_nonmanifold_edges > 0\n  %  error(sprintf('There are %d non-manifold edges',num_nonmanifold_edges));\n  %end\n\n  % number of vertices\n  n = size(V,1);\n  % number of elements\n  m = size(F,1);\n  % simplex size\n  ss = size(F,2);\n  switch ss\n  case 3\n    % Compute cotangents: seems to be 0.5*C\n    C = 2*cotangent(V,F);\n\n    allE = [F(:,[2 3]);F(:,[3 1]);F(:,[1 2])];\n    % Map each face-edge to a unique edge\n    F2E = reshape(1:3*m,m,3);\n    % Lij = -2 cot aij\n    %\n    % o\n    % |\\\n    % | \\\n    % |  \\\n    % |   \\\n    % i    \\\n    % |     \\\n    % |      \\\n    % |\u03b1ij    \\\n    % o----j---o\n    %\n    %\n    LI =  F2E(:, [1 2 3 2 3 1        1 2 3 2 3 1]);\n    LJ =  F2E(:, [2 3 1 1 2 3        1 2 3 2 3 1]);\n    LV = 2*[-C(:,[3 1 2 3 1 2]) C(:,[3 1 2 3 1 2])];\n\n    % Map duplicate edges to first instance\n    [E,~,EMAP] = unique(sort(allE,2),'rows');\n\n    assert(all(size(LI)==size(LJ)));\n    assert(all(size(LI)==size(LV)));\n    L = sparse(EMAP(LI),EMAP(LJ),LV,size(E,1),size(E,1));\n  case 4\n    % tets\n    T = F;\n    C = -2*cotangent(V,T);\n    allF = [ ...\n      T(:,2) T(:,4) T(:,3); ...\n      T(:,1) T(:,3) T(:,4); ...\n      T(:,1) T(:,4) T(:,2); ...\n      T(:,1) T(:,2) T(:,3); ...\n      ];\n    % Map each element-face to a unique face\n    T2F = reshape(1:4*m,m,4);\n    % Lij = -2 lij cot \u03b1ij\n    LI = T2F(:,[1 4 4 4 2 3 2 1 2 3 3 1        1 4 4 4 2 3 2 1 2 3 3 1]);\n    LJ = T2F(:,[2 1 2 3 3 1 1 4 4 4 2 3        1 4 4 4 2 3 2 1 2 3 3 1]); \n    LV = [-C(:,[3 4 5 6 1 2 3 4 5 6 1 2]) C(:,[3 4 5 6 1 2 3 4 5 6 1 2])];\n    % Map duplicate facets to first instance\n    [F,~,FMAP] = unique(sort(allF,2),'rows');\n\n    assert(all(size(LI)==size(LJ)));\n    assert(all(size(LI)==size(LV)));\n    L = sparse(FMAP(LI),FMAP(LJ),LV,size(F,1),size(F,1));\n    E = F;\n    EMAP = FMAP;\n\n  otherwise\n    error(['Simplex size ' num2str(ss) ' unsupported']);\n  end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/crouzeix_raviart_cotmatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5940704644735744}}
{"text": "%% Plotting Rotations\n%\n%%\n%\n% The function <quaternion.scatter.html scatter> allows you to visualize a\n% rotation in Rodriguez space.\n\n% define 100 random rotations\nrot = rotation.rand(100)\n\n% and plot the Rodriguez space\nscatter(rot)\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/Rotations/RotationPlotting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5940704644735743}}
{"text": "% StackExchange Signal Processing Q79314\n% https://dsp.stackexchange.com/questions/79314\n% Image Segmentation Using Deep Learning\n% References:\n%   1.  \n% Remarks:\n%   1.  B\n% TODO:\n% \t1.  C\n% Release Notes\n% - 1.0.000     27/11/2021\n%   *   First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 79;\n\nrun('InitScript.m');\n\nfigureIdx           = 0;\nfigureCounterSpec   = '%04d';\n\ngenerateFigures = ON;\n\n\n%% Simulation Constants\n\nSIG_TYPE_RAND       = 1;\nSIG_TYPE_GAUSSIAN   = 2;\n\n\n%% Simulation Parameters\n\n% Signal\nsignalType      = SIG_TYPE_GAUSSIAN;\nnumSamplesSig   = 201; %<! Make sure it is odd\ngaussianStd     = 2;\n\n% Support (Recieved Signal)\nnumSamples  = 300;\n\n% Noise\nminNoiseStd = 0;\nmaxNoiseStd = 1;\nnumNoisePts = 50;\nnumRealizations = 200; %<! Per noise level\n\n\n%% Generate Data\n\nsignalRadius = ceil(4 * gaussianStd);\nvSignalSupport = linspace(-signalRadius, signalRadius, numSamplesSig);\nvSignal = exp(-(vSignalSupport .^ 2) ./ (2 * gaussianStd));\nvSignal = single(vSignal(:));\n\nfigure(); plot(vSignalSupport, vSignal);\n\nvNoiseLevel = linspace(minNoiseStd, maxNoiseStd, numNoisePts);\nvNoiseLevel = single(vNoiseLevel);\n\nsignalRadius    = (numSamplesSig - 1) / 2;\nnumClasses      = numSamples - numSamplesSig + 1;\n\n\nmData   = zeros(numSamples, numClasses * numNoisePts * numRealizations, 'single');\nvLabels = zeros(numClasses * numNoisePts * numRealizations, 1);\n\nvNoise  = zeros(numSamples, 1, 'single');\nvX      = zeros(numSamples, 1, 'single');\nsigIdx = 1;\n\nfor ii = 1:numClasses\n    startIdx = ii;\n    endIdx = startIdx + numSamplesSig - 1;\n    vX(startIdx:endIdx) = vSignal;\n    for jj = 1:numNoisePts\n        noiseStd = vNoiseLevel(jj);\n        for kk = 1:numRealizations\n            vNoise(:) = noiseStd * randn(numSamples, 1, 'single');\n            mData(:, sigIdx) = vX + vNoise;\n            vLabels(sigIdx) = ii;\n            sigIdx = sigIdx + 1;\n        end\n    end\n    vX(startIdx:endIdx) = 0;\nend\n\n% ii = 20001; figure(); plot(mData(:, ii)); title(vLabels(ii));\n\n% Verify data by generating it without noise.\n% Then:\n% [vA, vB] = max(mData, [], 1);\n% vC = vB - signalRadius;\n% isequal(vC(:), vLabels)\n\n\n\n%% Save Data\n\nsave('Data', 'vSignal', 'mData', 'vLabels', 'subStreamNumber');\n\n\n%% Restore Defaults\n\n% set(0, 'DefaultFigureWindowStyle', 'normal');\n% set(0, 'DefaultAxesLooseInset', defaultLoosInset);\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/SignalProcessing/Q82711/GenerateData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.5940704556630101}}
{"text": "function fe2dx_r_fast_test ( )\n\n%*****************************************************************************80\n%\n%% FE2DX_R_FAST_TEST tests the FE2DX_R_FAST code.\n%\n%  Discussion:\n%\n%    This function sets all parameter values and initial condition information\n%    necessary to execute the \"fast\" version of the fe2dx_r algorithm.\n%\n%  Licensing:\n%\n%    Copyright (C) 2014 Marcus R. Garvie. \n%    See 'mycopyright.txt' for details.\n%\n%  Modified:\n%\n%    28 April 2014\n%\n%  Author:\n%\n%    Marcus R. Garvie. \n%\n%  Reference:\n%\n%    Marcus R Garvie, John Burkardt, Jeff Morgan,\n%    Simple Finite Element Methods for Approximating Predator-Prey Dynamics\n%    in Two Dimensions using MATLAB,\n%    Submitted to Bulletin of Mathematical Biology, 2014.\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'FE2DX_R_FAST_TEST:\\n' );\n  fprintf ( 1, '  Test the FE2DX_R_FAST function\\n' );\n  fprintf ( 1, '  which applies Robin boundary conditions as it\\n' );\n  fprintf ( 1, '  approximates a solution to a predator-prey system.\\n' );\n%\n%  Set the parameters.\n%\n  alpha = 0.4;\n  beta = 2.0;\n  gamma = 0.6;\n  delta = 1.0;\n%\n%  Use T=150.0 for normal run.\n%  Use T=0.50 for a \"quick\" run that might take 15 minutes of computing.\n%\n% T = 150.0;\n  T = 0.50;\n  delt = 1.0 / 384.0;\n  k1 = 0.01;\n  k2 = 0.01;\n\n  t = tic;\n  fe2dx_r_fast ( alpha, beta, gamma, delta, T, delt, @u0f, @v0f, k1, k2 );\n  t = toc ( t );\n\n  fprintf ( 1, '  Execution took %10.2g minutes \\n', t / 60.0 );\n%\n%  Terminate.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'FE2DX_R_FAST_TEST:\\n' );\n  fprintf ( 1, '  Normal end of execution.\\n' );\n  fprintf ( 1, '\\n' );\n  timestamp ( );\n\n  return\nend\n\nfunction value = u0f ( x, y )\n\n%*****************************************************************************80\n%\n%% U0F evaluates the initial condition for U.\n%\n%  Licensing:\n%\n%    Copyright (C) 2014 Marcus R. Garvie. \n%    See 'mycopyright.txt' for details.\n%\n%  Modified:\n%\n%    26 April 2014\n%\n%  Author:\n%\n%    Marcus R. Garvie. \n%\n%  Parameters:\n%\n%    Input, real X, Y, a location in the region.\n%\n%    Output, real VALUE, the initial condition for U at (X,Y).\n%\n  value = 6.0 / 35.0 - 2.0E-07 * ( x - 0.1 * y - 225.0 ) * ( x - 0.1 * y - 675.0 );\n\n  return\nend\n\nfunction value = v0f ( x, y )\n\n%*****************************************************************************80\n%\n%% V0F evaluates the initial condition for V.\n%\n%  Licensing:\n%\n%    Copyright (C) 2014 Marcus R. Garvie. \n%    See 'mycopyright.txt' for details.\n%\n%  Modified:\n%\n%    26 April 2014\n%\n%  Author:\n%\n%    Marcus R. Garvie. \n%\n%  Parameters:\n%\n%    Input, real X, Y, a location in the region.\n%\n%    Output, real VALUE, the initial condition for V at (X,Y).\n%\n  value = 116.0 / 245.0 - 3.0E-05 * ( x - 450.0 ) - 1.2E-04 * ( y - 150.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/fe2d_predator_prey_fast/fe2dx_r_fast_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.5940704556630101}}
{"text": "function im = fft2c(d)\n% Function performs a centered fft2\nim = fftshift(fft2(fftshift(d)));", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/fileFilters/rsvistafiles/ssfp/fft2c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5940014593081698}}
{"text": "function exact = p01_exact ( )\n\n%*****************************************************************************80\n%\n%% P01_EXACT returns the exact integral for problem 1.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    31 July 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Output, real EXACT, the value of the integral.\n%\n  omega = 1.0;\n\n  exact = sqrt ( pi ) * exp ( - omega * omega );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hermite_test_int/p01_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.8376199714402813, "lm_q1q2_score": 0.5938885865916829}}
{"text": "function d=disteusq(x,y,mode,w)\n%DISTEUSQ calculate euclidean, squared euclidean or mahanalobis distance D=(X,Y,MODE,W)\n%\n% Inputs: X,Y         Vector sets to be compared. Each row contains a data vector.\n%                     X and Y 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 X to every row of Y\n%                         'd'  Calculate only the distance between corresponding rows of X and Y\n%                              The default is 'd' if X and Y have the same number of rows otherwise 'x'.\n%                         's'  take the square-root of the result to give the euclidean distance.\n%\n%         W           Optional weighting matrix: the distance calculated is (x-y)*W*(x-y)'\n%                     If W is a vector, then the matrix diag(W) is used.\n%           \n% Output: D           If MODE='d' then D is a column vector with the same number of rows as the shorter of X and Y.\n%                     If MODE='x' then D is a matrix with the same number of rows as X and the same number of columns as Y'.\n%\n\n[nx,p]=size(x); ny=size(y,1);\nif nargin<3 | isempty(mode) mode='0'; end\nif any(mode=='d') | (mode~='x' & nx==ny)\n   nx=min(nx,ny);\n   z=x(1:nx,:)-y(1:nx,:);\n   if nargin<4\n      d=sum(z.*conj(z),2);\n   elseif min(size(w))==1\n      wv=w(:).';\n      d=sum(z.*wv(ones(size(z,1),1),:).*conj(z),2);\n   else\n      d=sum(z*w.*conj(z),2);\n   end\nelse\n   if p>1\n      if nargin<4\n         z=permute(x(:,:,ones(1,ny)),[1 3 2])-permute(y(:,:,ones(1,nx)),[3 1 2]);\n         d=sum(z.*conj(z),3);\n      else\n         nxy=nx*ny;\n         z=reshape(permute(x(:,:,ones(1,ny)),[1 3 2])-permute(y(:,:,ones(1,nx)),[3 1 2]),nxy,p);\n         if min(size(w))==1\n            wv=w(:).';\n            d=reshape(sum(z.*wv(ones(nxy,1),:).*conj(z),2),nx,ny);\n         else\n            d=reshape(sum(z*w.*conj(z),2),nx,ny);\n         end\n      end\n   else\n      z=x(:,ones(1,ny))-y(:,ones(1,nx)).';\n      if nargin<4\n         d=z.*conj(z);\n      else\n         d=w*z.*conj(z);\n      end\n   end\nend\nif any(mode=='s')\n   d=sqrt(d);\nend\n\n", "meta": {"author": "bastamon", "repo": "sound_signal_process-matlab-", "sha": "d621374ce1b3b2e3413e9ccc5ba9e6e925ea5f19", "save_path": "github-repos/MATLAB/bastamon-sound_signal_process-matlab-", "path": "github-repos/MATLAB/bastamon-sound_signal_process-matlab-/sound_signal_process-matlab--d621374ce1b3b2e3413e9ccc5ba9e6e925ea5f19/\u7b2c10\u7ae0 \u8bed\u97f3\u8bc6\u522b/10.2 \u57fa\u4e8e\u9690\u9a6c\u5c14\u53ef\u592b\u6a21\u578b\uff08HMM\uff09\u7684\u5b64\u7acb\u5b57\u8bed\u97f3\u8bc6\u522b\u5b9e\u9a8c/disteusq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.593888585993816}}
{"text": "function q = Qconj(p)\n\n% QCONJ   Quaternion conjugate\n%\n%   Q = QCONJ(P)returns the quaternion conjugate \n%    q = CONJQ(p) returns the quaternion conjugate of the quaternion P. P\n%    is a 4-vector representing a quaternion or an array 4*N (column i\n%    represents quaternion i) where N is the number of quaternions. If P =\n%    p0 + vecp, then P* = p0-vecp. Q has the same size as P.\n%\n% See also DQCONJ\n\nsp = size(p);\nif sp == [1 4], p = p'; sp = size(p); end\n\n% wrong size\nif sp(1) ~= 4 \n    error('DualQuaternion:Qconj:wrongsize',...\n        '%d rows in array p. It should be 4.',sp(1));\nend\n\nq = p;\nq(2:4,:) = - q(2: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/39288-dual-quaternion-toolbox/Dual quaternion toolbox v2/private/Qconj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5938885744977901}}
{"text": "%% Define Feedforward Convolutional Code\nSNR_dB = 3\nLM = 1600         % Mesg Length excluding pre-determined bits for starting & ending trellis at state 0\nTREL_TYPE = 'Feedback'  % {'Feedback', 'Feedforward'}\n\n%% Matlab Generator Polynomial convention\n% Build a binary number representation by placing a 1 in each spot where a connection line from the shift register feeds into the adder,\n% and a 0 elsewhere. The leftmost spot in the binary number represents the current input, while the rightmost spot represents the \n% oldest input that still remains in the shift register.\n\nif strcmp(TREL_TYPE, 'Feedback')    \n%     CL = 2\t\t% Rate 1/2 Feedback encoder with 2 states\n%     GenPoly0_1by2 = 3 % in octal\n%     GenPoly1_1by2 = 2\n%     FeedBackCoef = [1,1];  % For computing i/p bits needed to terminate trellis at state =0.\n%     TREL = poly2trellis(CL, [GenPoly0_1by2, GenPoly1_1by2], GenPoly0_1by2)\n\n%% Rate 1/2 Feedback encoder with 8-states used in 3GPP cellular 3G/4G standard\n    CL = 4  \n    GenPoly0_1by2 = 13 % in octal\n    GenPoly1_1by2 = 15\n    FeedBackCoef = [1,0,1,1];% For computing i/p bits needed to terminate trellis at state =0.\n    TREL = poly2trellis(CL, [GenPoly0_1by2, GenPoly1_1by2], GenPoly0_1by2)    \n    \nelse\n    %% Rate 1/3 Feedforward encoder with 4 states\n%     CL = 3; % constraint length\n%     GenPoly0_third = 4; % in octal\n%     GenPoly1_third = 5;\n%     GenPoly2_third = 7;\n%     TREL = poly2trellis( CL, [GenPoly0_third, GenPoly1_third, GenPoly2_third])    \n\n%     CL = 4 % constraint length\n%     GenPoly0_1by4 = 13 % in octal\n%     GenPoly1_1by4 = 15\n%     GenPoly2_1by4 = 15\n%     GenPoly3_1by4 = 17\n%     TREL = poly2trellis( CL, [GenPoly0_1by4, GenPoly1_1by4, GenPoly2_1by4, GenPoly3_1by4])\n\nend\nLM = LM + 2*(CL-1); % space for start & tail bits\n\n%% Verify trellis-structure is OK\n[isok, status] = istrellis(TREL) \n\nrandn('state', sum(100*clock)); % initialize to random state\n\n%% The encoder is assumed to have both started and ended at the all-zeros state\n%% Ensure msg is s.t. trellis starts at \"0\" state and ends at \"0\" state. \n%%  Generate Random binary stream & encode \nif strcmp(TREL_TYPE, 'Feedback')\n    msg1(1 : CL-1) = zeros(1, CL-1); % 1st (CL-1) bits must be 0\n    msg1(CL : LM -CL+1) = randint(LM -2*CL +2, 1, 2)' ; % Random data\n% \tmsg1(CL : LM -CL+1) = [0 1];\n\n    % Encode first part of msg, recording final state for later use.\n    [cenc_o1, final_state1] = convenc(msg1, TREL);\n\n    % Rest of msg depends on final_state1; it makes trellis terminate at final_state=0. \n    bvec_fs = bitget(final_state1, (CL-1) : -1 : 1); % All possible binary-vectors of length EncoderN\n    for idx = 1 : (CL-1)\n        msg2(idx) = rem( [0, bvec_fs]*FeedBackCoef', 2);\n        bvec_fs = [0, bvec_fs(1: (end-1))];\n    end\n%     msg2(1 : CL -1) = bvec_fs; % Last (CL-1) bits depend on state at time=(LM-CL+1)\n    [cenc_o2, final_state] = convenc(msg2, TREL, final_state1);\n    \n    msg = [msg1, msg2]; clear msg1 msg2\n    [cenc_o] = [cenc_o1, cenc_o2]; clear cenc_o1 cenc_o2\n    final_state    \nelse % Feedforward\n    msg(1 : CL-1) = zeros(1,CL-1); % 1st (CL-1) bits must be 0\n    msg(CL : LM -CL+1) = randint(LM -2*CL +2, 1, 2)' ; % Random data    \n    msg(LM -CL + 2 : LM) = zeros(CL-1, 1) % Last (CL-1) bits must be 0\n    [cenc_o, final_state] = convenc(msg, TREL);\nend\n\nif final_state ~= 0\n    disp('trellis not terminated properly: check last (CL-1) bits of mesg')\n    return\nend\n\n%%\tMap to BPSK constellation: bit0 -> 1, bit1 -> -1\nsignal_power = 1;\nchan_in = (1 - 2*cenc_o)*sqrt(signal_power);\n\n%%\tGenerate and add Gaussian-noise mean=0, variance= noise_power\nnoise_power = signal_power / 10^(SNR_dB/10);\nnoise = randn(size(chan_in))*sqrt(noise_power);\nchan_o = chan_in + noise;\n% chan_o = chan_in;\n\nEs = log2(TREL.numOutputSymbols)*signal_power;\nNo = noise_power;\nLc = 4*Es/No\n\n%%\tSoft-Decision decoding, map to decision values\nsoft_in = chan_o;\n% decodeds = vitdec_htm(TREL, soft_in');\n\n[LLR, Alpha, Beta] = LogMAPdecode_htm(TREL, chan_o, Lc);\n\ndecd_msg = (1 - sign(LLR))/2;\nerr_vec = abs(decd_msg - msg);\n\nsprintf('# of Bit-Errors = %d out of %d info-bits ', sum(abs(err_vec)), LM -CL -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/24848-log-map-decoder/test_LogMAPdec1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5938885699455118}}
{"text": "function B=unimodalcrossproducts(XtX,XtY,Bold)\n\n%UNIMODALCROSSPRODUCTS\n% Solves the problem min|Y-XB'| subject to the columns of \n% B are unimodal and nonnegative. The algorithm is iterative and\n% only one iteration is given, hence the solution is only improving \n% the current estimate\n%\n% I/O B=unimodalcrossproducts(XtX,XtY,Bold)\n% Modified from unimodal.m to handle crossproducts in input 1999\n% Reference\n% Bro and Sidiropoulos, \"Journal of Chemometrics\", 1998, 12, 223-247. \n\n\n% Copyright (C) 1995-2006  Rasmus Bro & Claus Andersson\n% Copenhagen University, DK-1958 Frederiksberg, Denmark, rb@life.ku.dk\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 2 of the License, or (at your option) any later 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 details.\n% You should have received a copy of the GNU General Public License along with \n% this program; if not, write to the Free Software Foundation, Inc., 51 Franklin \n% Street, Fifth Floor, Boston, MA  02110-1301, USA.\n\n\nB=Bold;\nF=size(B,2);\nfor f=1:F\n   xty = XtY(f,:)-XtX(f,[1:f-1 f+1:F])*B(:,[1:f-1 f+1:F])';\n   beta=pinv(XtX(f,f))*xty;\n   B(:,f)=ulsr(beta',1);\nend\n\n\nfunction [b,All,MaxML]=ulsr(x,NonNeg);\n\n% ------INPUT------\n%\n% x          is the vector to be approximated\n% NonNeg     If NonNeg is one, nonnegativity is imposed\n%\n%\n%\n% ------OUTPUT-----\n%\n% b \t     is the best ULSR vector\n% All \t     is containing in its i'th column the ULSRFIX solution for mode\n% \t     location at the i'th element. The ULSR solution given in All\n%            is found disregarding the i'th element and hence NOT optimal\n% MaxML      is the optimal (leftmost) mode location (i.e. position of maximum)\n%\n% ___________________________________________________________\n%\n%\n%               Copyright 1997\n%\n% Nikos Sidiroupolos\n% University of Maryland\n% Maryland, US\n%\n%       &\n%\n% Rasmus Bro\n% Royal Veterinary & Agricultural University\n% Denmark\n%\n% \n% ___________________________________________________________\n\n\n% This file uses MONREG.M\n\nx=x(:);\nI=length(x);\nxmin=min(x);\nif xmin<0\n  x=x-xmin;\nend\n\n\n% THE SUBSEQUENT \n% CALCULATES BEST BY TWO MONOTONIC REGRESSIONS\n\n% B1(1:i,i) contains the monontonic increasing regr. on x(1:i)\n[b1,out,B1]=monreg(x);\n\n% BI is the opposite of B1. Hence BI(i:I,i) holds the monotonic\n% decreasing regression on x(i:I)\n[bI,out,BI]=monreg(flipud(x));\nBI=flipud(fliplr(BI));\n\n% Together B1 and BI can be concatenated to give the solution to\n% problem ULSR for any modloc position AS long as we do not pay\n% attention to the element of x at this position\n\n\nAll=zeros(I,I+2);\nAll(1:I,3:I+2)=B1;\nAll(1:I,1:I)=All(1:I,1:I)+BI;\nAll=All(:,2:I+1);\nAllmin=All;\nAllmax=All;\n% All(:,i) holds the ULSR solution for modloc = i, disregarding x(i),\n\n\niii=find(x>=max(All)');\nb=All(:,iii(1));\nb(iii(1))=x(iii(1));\nBestfit=sum((b-x).^2);\nMaxML=iii(1);\nfor ii=2:length(iii)\n  this=All(:,iii(ii));\n  this(iii(ii))=x(iii(ii));\n  thisfit=sum((this-x).^2);\n  if thisfit<Bestfit\n    b=this;\n    Bestfit=thisfit;\n    MaxML=iii(ii);\n  end\nend\n\nif xmin<0\n  b=b+xmin;\nend\n\n\n% Impose nonnegativity\nif NonNeg==1\n  if any(b<0)\n    id=find(b<0);\n    % Note that changing the negative values to zero does not affect the\n    % solution with respect to nonnegative parameters and position of the\n    % maximum.\n    b(id)=zeros(size(id))+0;\n  end\nend\n\nfunction [b,B,AllBs]=monreg(x);\n\n% Monotonic regression according\n% to J. B. Kruskal 64\n%\n% b     = min|x-b| subject to monotonic increase\n% B     = b, but condensed\n% AllBs = All monotonic regressions, i.e. AllBs(1:i,i) is the \n%         monotonic regression of x(1:i)\n%\n%\n% Copyright 1997\n%\n% Rasmus Bro\n% Royal Veterinary & Agricultural University\n% Denmark\n% rb@kvl.dk\n%\n\n\nI=length(x);\nif size(x,2)==2\n   B=x;\nelse\n   B=[x(:) ones(I,1)];\nend\n\n   AllBs=zeros(I,I);\n   AllBs(1,1)=x(1);\n   i=1;\n   while i<size(B,1)\n      if B(i,1)>B(min(I,i+1),1)\n          summ=B(i,2)+B(i+1,2);\n          B=[B(1:i-1,:);[(B(i,1)*B(i,2)+B(i+1,1)*B(i+1,2))/(summ) summ];B(i+2:size(B,1),:)];\n          OK=1;\n          while OK\n             if B(i,1)<B(max(1,i-1),1)\n                summ=B(i,2)+B(i-1,2);\n                B=[B(1:i-2,:);[(B(i,1)*B(i,2)+B(i-1,1)*B(i-1,2))/(summ) summ];B(i+1:size(B,1),:)];\n                i=max(1,i-1);\n             else\n                OK=0;\n             end\n          end\n          bInterim=[];\n          for i2=1:i\n             bInterim=[bInterim;zeros(B(i2,2),1)+B(i2,1)];\n          end\n          No=sum(B(1:i,2));\n          AllBs(1:No,No)=bInterim;\n      else\n          i=i+1;\n          bInterim=[];\n          for i2=1:i\n             bInterim=[bInterim;zeros(B(i2,2),1)+B(i2,1)];\n          end\n          No=sum(B(1:i,2));\n          AllBs(1:No,No)=bInterim;\n      end\n  end\n\n  b=[];\n  for i=1:size(B,1)\n    b=[b;zeros(B(i,2),1)+B(i,1)];\n end\n", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/libs/nway331/unimodalcrossproducts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.59387835106416}}
{"text": "function [Zin,ip_it] = plain_foopsi(H,D,I_est,eps)\n\n% solves argmin ||X-H||^2 subject to D*X>=0 with an interior point method\n% using I_est as the initial value and eps as the initial barrier weight\n\n\nln = length(H);\nstep_back_frac = 0.5;\niter = 0;\nif nargin == 2\n    I_est = 1e-3*ones(ln,1);\n    eps = 1;\nend\nZin = I_est(:);\n\nif nargin == 3\n    eps = 1;\nend\nwhile eps>1e-5\n    n = D*Zin;\n    nnd = 10;\n    E = norm(Zin-H)^2 - eps*sum(log(D*Zin));\n    grad = 2*(Zin-H) - eps*D'*(n.^(-1));\n    Hs = 2*speye(ln) + eps*D'*spdiags(n.^(-2),0,ln,ln)*D;          \n    while nnd/2>1\n        iter = iter + 1;\n        Z_dir = -Hs\\grad;\n        hit = -n./(D*Z_dir);\n        if all(hit<0)\n            s = 1;\n        else\n            s = min(1,.9*min(hit(hit>=0)));\n        end\n        E_new = E; s = s/step_back_frac;\n        x_dg = grad'*Z_dir;\n        while E_new > E + 0.25*s*x_dg\n            s=s*step_back_frac; \n            Z_new = Zin + s*Z_dir;\n            n = D*Zin;\n            E_new = norm(Z_new-H)^2 - eps*sum(log(D*Z_new));\n        end\n        %E = E_new;\n        Zin = Zin + s*Z_dir;\n        nnd = -x_dg;\n        E = norm(Zin-H)^2 - eps*sum(log(D*Zin));\n        n = D*Zin;\n        grad = 2*(Zin-H) - eps*D'*(n.^(-1));\n        Hs = 2*speye(ln) + eps*D'*spdiags(n.^(-2),0,ln,ln)*D;\n        %disp(nnd)\n    end\n    eps = eps/10;\nend\n%fprintf('Interior point method converged after %i iterations \\n',iter);\nip_it = iter;\n", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/utilities/plain_foopsi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5938783326517069}}
{"text": "function 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 triples\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%    12 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, integer TRIANGLE_NODE(3,TRIANGLE_NUM), the nodes that make up the\n%    triangles.  These should be listed 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 = ( sortrows ( edge' ) )';\n%\n%  Records which appear twice are internal edges and can be ignored.\n%\n  node_boundary(1:node_num) = 0;\n\n  j = 0;\n\n  while ( j < 3 * triangle_num )\n\n    j = j + 1;\n\n    if ( j == 3 * triangle_num )\n      node_boundary(edge(1:m,j)) = 1;\n    elseif ( all ( edge(1:m,j) == edge(1:m,j+1) ) )\n      j = j + 1;\n    else\n      node_boundary(edge(1:m,j)) = 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/triangulation/triangulation_order3_boundary_node.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.5938783297197349}}
{"text": "%-fanDTasia ToolBox------------------------------------------------------------------\n% This Matlab script is part of the fanDTasia ToolBox: a Matlab library for Diffusion \n% Weighted MRI (DW-MRI) Processing, Diffusion Tensor (DTI) Estimation, High-order \n% Diffusion Tensor Analysis, Diffusion Kurtosis Imaging (DKI) Estimation,\n% Tensor ODF estimation, Visualization and more.\n%\n% A Matlab Tutorial on DW-MRI can be found in:\n% http://www.cise.ufl.edu/~abarmpou/lab/fanDTasia/tutorial.php\n%\n%-CITATION---------------------------------------------------------------------------\n% If you use this software please cite the following papers on 4th-order tensors:\n% 1) A. Barmpoutis et al. \"Diffusion Kurtosis Imaging: Robust Estimation from DW-MRI \n%    using Homogeneous Polynomials\", In the Proceedings of ISBI, 2011, pp. 262-265.\n% 2) A. Barmpoutis and B.C. Vemuri, \"A Unified Framework for Estimating Diffusion \n%    Tensors of any order with Symmetric Positive-Definite Constraints\", \n%    In the Proceedings of ISBI, 2010, pp. 1385-1388.\n%\n%-DESCRIPTION------------------------------------------------------------------------\n% This demo script shows how to compute the Diffusion Kurtosis Coefficients from a given \n% Diffusion-Weighted MRI dataset. The method guarantees that the estimated diffusivity as\n% well as the Diffusion Tensor are positive semi-definite, using the method\n% in Sec. 4.2 of the ISBI'11 paper. Here the given demo dataset consists of 5 voxels,\n% 30 gradient directions x 2 b-values from the real brain dataset used in the ISBI'11 paper.\n%\n%-USE--------------------------------------------------------------------------------\n% [D,W]=DEMO_DKI_Estimation_Method2_v2;\n%\n% D: is a vector with the computed Unique Coefficients of the 2nd-order Diffusion Tensor\n% W: is a vector with the computed Unique Coefficients of the 4th-order Kurtosis Tensor\n%\n%-DISCLAIMER-------------------------------------------------------------------------\n% You can use this source code for non commercial research and educational purposes \n% only without licensing fees and is provided without guarantee or warrantee expressed\n% or implied. You cannot repost this file without prior written permission from the \n% authors. If you use this software please cite the following papers:\n% 1) A. Barmpoutis et al. \"Diffusion Kurtosis Imaging: Robust Estimation from DW-MRI \n%    using Homogeneous Polynomials\", In the Proceedings of ISBI, 2011.\n% 2) A. Barmpoutis and B.C. Vemuri, \"A Unified Framework for Estimating Diffusion \n%    Tensors of any order with Symmetric Positive-Definite Constraints\", \n%    In the Proceedings of ISBI, 2010, pp. 1385-1388.\n%\n%-AUTHOR-----------------------------------------------------------------------------\n% Angelos Barmpoutis, PhD\n% Digital Worlds Institute\n% University of Florida, Gainesville, FL 32611, USA\n% angelbar at ufl dot edu\n%------------------------------------------------------------------------------------\nfunction [DKI_D,DKI_W]=DEMO_DKI_Estimation_Method2_v2\n\n%%% DATA OPENING %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%open data files\n[S,B]=openFDT('real_data_5voxels.fdt');\n\n%S0 signal, no diffusion weighting\nS0=S(:,:,:,1);\n\n%acquisition shell 1, 30 orientations\nS_1real=S(:,:,:,[2:31]);\nGradientOrientations_1=B([2:31],[1:3]);\nBValue_1=B(2,4);\n\n%acquisition shell 2, 30 orientations\nS_2real=S(:,:,:,[32:61]);\nGradientOrientations_2=B([32:61],[1:3]);\nBValue_2=B(32,4);\n\n\n\n%%% OPTIONAL: ADD RICIAN NOISE TO THE DATA FOR QUANTITATIVE EVALUATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nstdv=input('Do you want to add Rician noise to the data for validation? \\n If yes, then give the Std. Dev. (e.g: 0.1), otherwise type 0.\\n STD.DEV.:');\nS_1=S_1real;\nfor i=1:size(S_1real,4)\n    S_1(:,:,:,i)=sqrt((S_1real(:,:,:,i)+stdv*S0.*randn(size(S_1real,1),size(S_1real,2),size(S_1real,3))).^2+(stdv*S0.*randn(size(S_1real,1),size(S_1real,2),size(S_1real,3))).^2);\nend\nS_2=S_2real;\nfor i=1:size(S_2real,4)\n    S_2(:,:,:,i)=sqrt((S_2real(:,:,:,i)+stdv*S0.*randn(size(S_2real,1),size(S_2real,2),size(S_2real,3))).^2+(stdv*S0.*randn(size(S_2real,1),size(S_2real,2),size(S_2real,3))).^2);\nend\n%your data can have as many shells and bvalues you want\n\n\n\n%%% INITIALIZATION - COMPUTING AUXILIARY DATA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%Construct a constant set of polynomial coefficients C\nC_order2=constructSetOf81Polynomials(2)'; %computes C from section 5.1 (ISBI'10)\nC_order4=constructSetOf321Polynomials(4)'; %computes C from section 5.1 (ISBI'10)\nA_1=D4toDKImatrix(BValue_1);A_1=[A_1(:,[1:6])*C_order2 A_1(:,6+[1:15])];%Computes the matrix A from Table 1 (ISBI'11)\nA_2=D4toDKImatrix(BValue_2);A_2=[A_2(:,[1:6])*C_order2 A_2(:,6+[1:15])];%Computes the matrix A from Table 1 (ISBI'11)\n\n%shell 1\nG_1_order2=constructMatrixOfMonomials(GradientOrientations_1, 2); %computes G from section 5.1 (ISBI'10)\nG_1_order4=constructMatrixOfMonomials(GradientOrientations_1, 4); %computes G from section 5.1 (ISBI'10)\nGbig_1=[-BValue_1*G_1_order2 BValue_1*BValue_1/6*G_1_order4];  %all the monomials for orders 2 and 4.\n\n%shell 2\nG_2_order2=constructMatrixOfMonomials(GradientOrientations_2, 2); %computes G from section 5.1 (ISBI'10)\nG_2_order4=constructMatrixOfMonomials(GradientOrientations_2, 4); %computes G from section 5.1 (ISBI'10)\nGbig_2=[-BValue_2*G_2_order2 BValue_2*BValue_2/6*G_2_order4];  %all the monomials for orders 2 and 4.\n\n%your data can have as many shells and bvalues you want\nGbig=[Gbig_1; Gbig_2]; %all the monomials for orders 2 and 4 and bvalues b1 and b2.\n\n\n\n\n%%%%%% MAIN LOOP - METHOD: LINEAR FITTING - NO CONSTRAINTS %%%%%%%%%%%%%%%%%%%%%%%%%\nfor x=1:size(S,1)\n    for y=1:size(S,2)\n        for z=1:size(S,3)\n            \n            logS_1=log(squeeze(S_1(x,y,z,:))/S0(x,y,z));\n            logS_2=log(squeeze(S_2(x,y,z,:))/S0(x,y,z));\n                     \n            %The following 2 steps implement the method in Sec. 4.2 of the ISBI'11 paper.\n            %Step 1: Compute a positive-definite 4th-order tensor for each b-value\n            D4_1=C_order4*lsqnonneg(-G_1_order4*C_order4, logS_1);%computes a positive-definite tensor for b1\n            D4_2=C_order4*lsqnonneg(-G_2_order4*C_order4, logS_2);%computes a positive-definite tensor for b2\n\n            %Step 2: Compute DKI from the positive definite 4th-order tensors.\n            x1=zeros(size(C_order2,2),1); %the initialization is the zero vector\n            x2=zeros(15,1); %the initialization is the zero vector\n            for i=1:100 %we perform a kind of gradient descent for a number of iterations\n                x1=lsqnonneg([A_1(:,[1:size(C_order2,2)]);A_2(:,[1:size(C_order2,2)])],[D4_1;D4_2]-[A_1(:,[size(C_order2,2)+1:size(A_1,2)]);A_2(:,[size(C_order2,2)+1:size(A_1,2)])]*x2);\n                x2_new=pinv([A_1(:,[size(C_order2,2)+1:size(A_1,2)]);A_2(:,[size(C_order2,2)+1:size(A_1,2)])]) * ([D4_1;D4_2]-[A_1(:,[1:size(C_order2,2)]);A_2(:,[1:size(C_order2,2)])]*x1);\n                %sum(abs(x2-x2_new)) %I just put this here for convergence check\n                x2=x2_new;\n            end\n            dki=[C_order2*x1;x2];         \n\n            %Optional Validation if user adds noise to the data\n            if stdv>0\n                logS_1=log(squeeze(S_1real(x,y,z,:))/S0(x,y,z));\n                logS_2=log(squeeze(S_2real(x,y,z,:))/S0(x,y,z));\n                err(:,x,y,z)=abs(Gbig*dki-[logS_1; logS_2]);\n            end\n            \n            %Store the data\n            DKI_D(:,x,y,z)=dki([1:6]); %The 6 unique coefficients of the diffusion tensor D\n            %If you want you can put the result in the form of a 3x3 matrix\n            %D=[dki(6) dki(5)/2 dki(4)/2\n            %   dki(5)/2 dki(3) dki(2)/2\n            %   dki(4)/2 dki(2)/2 dki(1)];\n            \n            DKI_W(:,x,y,z)=dki([7:21]); %The 15 unique coefficients of the kurtosis tensor W\n            %You can see which coefficient is which you can use the function: printTensor(DKI_W(:,x,y,z),4)\n            % or if you want to plot a tensor or a tensor field as spherical functions\n            % you have to download the plotTensors.m function developed by Angelos Barmpoutis, Ph.D.\n            % and then uncomment the following lines.\n            % \n            % plotTensors(DKI_D(:,1,1,1),1,[321 1]); %3D ellipsoidal plot of D\n            % plotTensors(DKI_W(:,1,1,1),1,[321 1]); %3D ellipsoidal plot of W\n            \n            %Optional Calculation of Dapp and Kapp\n            Dapp(:,x,y,z) = G_1_order2*dki(1:6);\n            Kapp(:,x,y,z) = (G_1_order4*dki(7:21))./((G_1_order2*dki(1:6)).^2);\n            \n        end\n    end\nend\n\n\n%%%%%% OPTIONAL: PRINT RESULTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nall_err=[];\nall_Dapp=[];\nall_Kapp=[];\ncounter=0;\nmeanD=zeros(6,1);\nmeanW=zeros(15,1);\nfor x=1:size(S,1)\n    for y=1:size(S,2)\n        for z=1:size(S,3)\n            if stdv>0\n               all_err=[all_err; err(:,x,y,z)];\n            end\n            all_Dapp=[all_Dapp; Dapp(:,x,y,z)];\n            all_Kapp=[all_Kapp; Kapp(:,x,y,z)];\n            meanD=meanD+DKI_D(:,x,y,z);\n            meanW=meanW+DKI_W(:,x,y,z);\n            counter=counter+1;\n        end\n    end\nend\nmeanD=meanD/counter;\nmeanW=meanW/counter;\n\nfprintf(1,'\\n-----RESULTS:-----\\n\\n');\nfprintf('Number of fitted voxels: %d\\n',counter);\nif stdv>0\n    fprintf(1,'Fitting Error: %.4f (std. dev. %.4f)\\n',mean(all_err),std(all_err));\nend\nfprintf(1,'Mean Dapp: %.4f (std. dev. %.4f)\\n',mean(all_Dapp),std(all_Dapp));\nfprintf(1,'Mean Kapp: %.4f (std. dev. %.4f)\\n',mean(all_Kapp),std(all_Kapp));\nfprintf(1,'\\nMean Diffusion Tensor D:\\n');\nprintTensor(meanD,2);\nfprintf(1,'\\nMean Kurtosis Tensor W:\\n');\nprintTensor(meanW,4);\n\n% If you want to plot a Diffusion or Kurtosis tensor as spherical functions\n% you have to download the plotTensors.m function developed by Angelos Barmpoutis, Ph.D.\n% and then uncomment the following lines.\n%\n% subplot(1,2,1)\n% plotTensors(meanD,1,[321 1]);\n% title('Mean Diffusion Tensor');\n% subplot(1,2,2);\n% plotTensors(meanW,1,[321 1]);\n% title('Mean Kurtosis Tensor');\n\n\nfprintf(1,'\\nIf you use this software please cite the following papers on DKI and DTI estimation:\\n');\nfprintf(1,'1) A. Barmpoutis et al. \"Diffusion Kurtosis Imaging: Robust Estimation from DW-MRI\\n'); \nfprintf(1,'   using Homogeneous Polynomials\", In the Proceedings of ISBI, 2011, pp. 262-265.\\n');\nfprintf(1,'2) A. Barmpoutis and B.C. Vemuri, \"A Unified Framework for Estimating Diffusion Tensors\\n'); \nfprintf(1,'   of any order with Symmetric Positive-Definite Constraints\",\\n');\nfprintf(1,'   In the Proceedings of ISBI, 2010, pp. 1385-1388.\\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/31838-diffusion-kurtosis-tensor-estimation/DKI_Estimation/DEMO_DKI_Estimation_Method2_v2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5938631158384394}}
{"text": "% \n\nfunction [f, df] = sampleEijOpt(x)\n% optimization code\n\n% param\nvert = x(4:7);\nw_res = x(8);\n\n% box case (4 lines), three free parameters\nx0 = x(1); y0 = x(2); % camera center\nyc = x(3); % corner\n\n% assume vertical lines are fixed\na_aob = (vert(2) - vert (1))/w_res*2*pi;\na_boc = (vert(3) - vert (2))/w_res*2*pi;\na_cod = (vert(4) - vert (3))/w_res*2*pi;\na_doa = (vert(1) + w_res - vert (4))/w_res*2*pi;\n\n% energy\nv_ao  = [x0 y0]; v_bo = [x0-1 y0]; v_co = [x0-1 y0 - yc]; v_do = [x0 y0-yc];\nn_v_ao = norm(v_ao); n_v_bo = norm(v_bo); n_v_co = norm(v_co); n_v_do = norm(v_do);\nb_aob = acos(dot(v_ao, v_bo)/n_v_ao/n_v_bo);\nif det([v_ao;v_bo]) < 0\n    b_aob = 2*pi - b_aob;\nend\nb_boc = acos(dot(v_bo, v_co)/n_v_bo/n_v_co);\nif det([v_bo;v_co]) < 0\n    b_boc = 2*pi - b_boc;\nend\nb_cod = acos(dot(v_co, v_do)/n_v_co/n_v_do);\nif det([v_co;v_do]) < 0\n    b_cod = 2*pi - b_cod;\nend\nb_doa = acos(dot(v_do, v_ao)/n_v_do/n_v_ao);\nif det([v_do;v_ao]) < 0\n    b_doa = 2*pi - b_doa;\nend\n\nf = (b_aob - a_aob)^2 + (b_boc - a_boc)^2 + (b_cod - a_cod)^2 + (b_doa - a_doa)^2;\n\n% gradient\n% x0\nd_aob_x0 = (2*x0-1)*n_v_ao*n_v_bo + dot(v_ao, v_bo) * (x0*n_v_bo/n_v_ao + (x0-1)*n_v_ao/n_v_bo);\nd_aob_x0 = d_aob_x0 * (-1/(sqrt(1-cos(b_aob)*cos(b_aob))+eps))/n_v_ao/n_v_ao/n_v_bo/n_v_bo;\nif det([v_ao;v_bo]) < 0\n    d_aob_x0 = -d_aob_x0;\nend\nd_aob_x0 = 2*(b_aob - a_aob) * d_aob_x0;\n\nd_boc_x0 = 2*(x0-1)*n_v_bo*n_v_co + dot(v_bo, v_co) * ((x0-1)*n_v_co/n_v_bo + (x0-1)*n_v_bo/n_v_co);\nd_boc_x0 = d_boc_x0 * (-1/(sqrt(1-cos(b_boc)*cos(b_boc))+eps))/n_v_bo/n_v_bo/n_v_co/n_v_co;\nif det([v_bo;v_co]) < 0\n    d_boc_x0 = -d_boc_x0;\nend\nd_boc_x0 = 2*(b_boc - a_boc) * d_boc_x0;\n\nd_cod_x0 = (2*x0-1)*n_v_co*n_v_do + dot(v_co, v_do) * ((x0-1)*n_v_do/n_v_co + x0*n_v_co/n_v_do);\nd_cod_x0 = d_cod_x0 * (-1/(sqrt(1-cos(b_cod)*cos(b_cod))+eps))/n_v_co/n_v_co/n_v_do/n_v_do;\nif det([v_co;v_do]) < 0\n    d_cod_x0 = -d_cod_x0;\nend\nd_cod_x0 = 2*(b_cod - a_cod) * d_cod_x0;\n\nd_doa_x0 = 2*x0*n_v_do*n_v_ao +dot(v_do, v_ao) * (x0*n_v_ao/n_v_do + x0*n_v_do/n_v_ao);\nd_doa_x0 = d_doa_x0 * (-1/(sqrt(1-cos(b_doa)*cos(b_doa))+eps))/n_v_do/n_v_do/n_v_ao/n_v_ao;\nif det([v_do;v_ao]) < 0\n    d_doa_x0 = -d_doa_x0;\nend\nd_doa_x0 = 2*(b_doa - a_doa) * d_doa_x0;\n\n% y0\nd_aob_y0 = 2*y0*n_v_ao*n_v_bo + dot(v_ao, v_bo) * (y0*n_v_bo/n_v_ao + y0*n_v_ao/n_v_bo);\nd_aob_y0 = d_aob_y0 * (-1/(sqrt(1-cos(b_aob)*cos(b_aob))+eps))/n_v_ao/n_v_ao/n_v_bo/n_v_bo;\nif det([v_ao;v_bo]) < 0\n    d_aob_y0 = -d_aob_y0;\nend\nd_aob_y0 = 2*(b_aob - a_aob) * d_aob_y0;\n\nd_boc_y0 = (2*y0-yc)*n_v_bo*n_v_co + dot(v_bo, v_co) * (y0*n_v_co/n_v_bo + (y0-yc)*n_v_bo/n_v_co );\nd_boc_y0 = d_boc_y0/n_v_bo/n_v_bo/n_v_co/n_v_co;\nif det([v_bo;v_co]) < 0\n    d_boc_y0 = -d_boc_y0;\nend\nd_boc_y0 = 2*(b_boc - a_boc) * d_boc_y0;\n\nd_cod_y0 = 2*(y0-yc)*n_v_co*n_v_do + dot(v_co, v_do) * ((y0-yc)*n_v_do/n_v_co + (y0-yc)*n_v_co/n_v_do);\nd_cod_y0 = d_cod_y0 * (-1/(sqrt(1-cos(b_cod)*cos(b_cod))+eps))/n_v_co/n_v_co/n_v_do/n_v_do;\nif det([v_co;v_do]) < 0\n    d_cod_y0 = -d_cod_y0;\nend\nd_cod_y0 = 2*(b_cod - a_cod) * d_cod_y0;\n\nd_doa_y0 = (2*y0-yc)*n_v_do*n_v_ao + dot(v_do, v_ao) * ((y0-yc)*n_v_ao/n_v_do + y0*n_v_do/n_v_ao);\nd_doa_y0 = d_doa_y0 * (-1/(sqrt(1-cos(b_doa)*cos(b_doa))+eps))/n_v_do/n_v_do/n_v_ao/n_v_ao;\nif det([v_do;v_ao]) < 0\n    d_doa_y0 = -d_doa_y0;\nend\nd_doa_y0 = 2*(b_doa - a_doa) * d_doa_y0;\n\n% yc\nd_boc_yc = (-y0)*n_v_bo*n_v_co + dot(v_bo, v_co) * n_v_bo* (yc-y0)/n_v_co;\nd_boc_yc = d_boc_yc/n_v_bo/n_v_bo/n_v_co/n_v_co;\nif det([v_bo;v_co]) < 0\n    d_boc_yc = -d_boc_yc;\nend\nd_boc_yc = 2*(b_boc - a_boc) * d_boc_yc;\n\nd_cod_yc = 2*(yc-y0)*n_v_co*n_v_do + dot(v_co, v_do) * ((yc-y0)*n_v_do/n_v_co+(yc-y0)*n_v_co/n_v_do);\nd_cod_yc = d_cod_yc * (-1/(sqrt(1-cos(b_cod)*cos(b_cod))+eps))/n_v_co/n_v_co/n_v_do/n_v_do;\nif det([v_co;v_do]) < 0\n    d_cod_yc = -d_cod_yc;\nend\nd_cod_yc = 2*(b_cod - a_cod) * d_cod_yc;\n\nd_doa_yc = (-y0)*n_v_do*n_v_ao + dot(v_do, v_ao) * n_v_ao * (yc-y0)/n_v_do;\nd_doa_yc = d_doa_yc * (-1/(sqrt(1-cos(b_doa)*cos(b_doa))+eps))/n_v_do/n_v_do/n_v_ao/n_v_ao;\nif det([v_do;v_ao]) < 0\n    d_doa_yc = -d_doa_yc;\nend\nd_doa_yc = 2*(b_doa - a_doa) * d_doa_yc;\n\nd_x0 = d_aob_x0 + d_boc_x0 + d_cod_x0 + d_doa_x0;\nd_y0 = d_aob_y0 + d_boc_y0 + d_cod_y0 + d_doa_y0;\nd_yc = d_boc_yc + d_cod_yc + d_doa_yc;\n\ndf = [d_x0; d_y0; d_yc; 0; 0; 0; 0; 0];\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/sampleEijOpt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.593805099101812}}
{"text": "function Subs = som_ind2sub(msize,inds)\n\n%SOM_IND2SUB Map grid subscripts from linear index.\n%\n% Subs = som_ind2sub(msize,inds)\n%\n%  sub = som_ind2sub([10 15],44);\n%  sub = som_ind2sub(sMap,44);\n%  sub = som_ind2sub(sMap.msize,44);\n%  Subs = som_ind2sub([10 15],[44 13 91]');\n%\n%  Input and output arguments: \n%   msize  (struct) map or topology struct\n%          (vector) size 1 x m, specifies the map grid size\n%   inds   (vector) size n x 1, linear indeces of n map units\n% \n%   Subs   (matrix) size n x m, the subscripts\n%\n% See also SOM_SUB2IND.\n\n% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Vesanto\n% http://www.cis.hut.fi/projects/somtoolbox/\n\n% Version 2.0beta juuso 300798\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif isstruct(msize), \n  if strcmp(msize.type,'som_map'), msize = msize.topol.msize; \n  elseif strcmp(msize.type,'som_topol'), msize = msize.msize;\n  else error('Invalid first argument.'); end\nend\n\nn = length(msize); \nk = [1 cumprod(msize(1:end-1))]; \ninds = inds - 1;\nfor i = n:-1:1, \n  Subs(:,i) = floor(inds/k(i))+1; \n  inds = rem(inds,k(i)); \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"author": "ilarinieminen", "repo": "SOM-Toolbox", "sha": "f2597abc1ae33c2060e0443d49e854011ff21831", "save_path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox", "path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox/SOM-Toolbox-f2597abc1ae33c2060e0443d49e854011ff21831/som/som_ind2sub.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5936715408086392}}
{"text": "function [N,Z,M,A,XYZ] = spm_max(X,L)\n% Sizes, maxima and locations of local excursion sets\n% FORMAT [N Z M A XYZ] = spm_max(X,L)\n% X     - values of 3-D field\n% L     - locations [x y z]' {in voxels}\n%\n% N     - size of region {in voxels)\n% Z     - Z values of maxima\n% M     - location of maxima {in voxels}\n% A     - region number\n% XYZ   - cell array of voxel locations\n%__________________________________________________________________________\n%\n% spm_max characterizes a point list of voxel values (X) and their\n% locations (L) in terms of edge, face and vertex connected subsets,\n% returning a maxima- orientated list:  The value of the ith maximum is\n% Z(i) and its location is given by M(:,i). A(i) identifies the ith\n% maximum with a region. Region A(i) contains N(i) voxels, whose\n% coordinates are in a 3-by-N(i) array in XYZ{i}.\n%\n% See also: spm_bwlabel.m and spm_clusters.m\n%__________________________________________________________________________\n% Copyright (C) 2003-2011 Wellcome Trust Centre for Neuroimaging\n\n% Jesper Andersson\n% $Id: spm_max.m 4384 2011-07-06 17:00:20Z guillaume $\n\nif isempty(L)\n    N = []; Z = []; M = []; A = []; XYZ = [];\n    return;\nend\n\n%-Ensure that L contains exactly integers\n%--------------------------------------------------------------------------\nL          = round(L);\n\n%-Turn location list to binary 3D volume\n%--------------------------------------------------------------------------\ndim        = [max(L(1,:)) max(L(2,:)) max(L(3,:))];\nvol        = zeros(dim(1),dim(2),dim(3));\nindex      = sub2ind(dim,L(1,:)',L(2,:)',L(3,:)');\nvol(index) = 1;\n\n%-Label each cluster with its own label using an 18 connectivity criterion\n% cci = connected components image volume\n%--------------------------------------------------------------------------\n[cci,num]  = spm_bwlabel(vol,18);\n\n%-Get size (in no. of voxels) for each connected component\n% ccs = connected component size\n%--------------------------------------------------------------------------\nccs        = histc(cci(:),(0:num) + 0.5);\nccs        = ccs(1:end-1);\n\n%-Get indices into L for voxels that are indeed local maxima (using an 18 \n% neighbour criterion)\n%--------------------------------------------------------------------------\nvol(index) = X;\nLindex     = spm_get_lm(vol,L);\n\nM          = L(:,Lindex);\nZ          = X(Lindex);\nmindex     = sub2ind(dim,L(1,Lindex)',L(2,Lindex)',L(3,Lindex)');\nA          = cci(mindex);\nN          = ccs(A);\n\n%-Cell array of XYZ locations of voxels in each cluster\n%--------------------------------------------------------------------------\nif nargout > 4\n    xyz(:,index) = sparse(L);\n    cci   = sparse(cci(:));\n    XYZ = cell(1, max(A));\n    for i = 1:max(A)\n        XYZ{i} = full(xyz(:,cci == i));\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/spm_max.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.593671538069392}}
{"text": "function cspy(S,epsilon)\n  % cspy Visualize sparsity pattern. coloring positive and negative entries of S\n  % in red and blue respectively\n  %\n  % cspy(S)\n  % cspy(S,epsilon)\n  %\n  % Inputs:\n  %   S  m by n (sparse) matrix\n  %   epsilon  zero value {0}\n  %\n  % See also: spy\n  %\n\n  if nargin < 2\n    epsilon = 0;\n  end\n  spy(S>epsilon,'r');\n  hold on;\n  spy(S<-epsilon,'b');\n  hold off;\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/cspy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.5936715371932608}}
{"text": "function spec_plot2(varargin);\n%\n% Type: spec_plot2(S_m,freq,time,typ,f_min,f_max,c_min,c_max);\n% Type: spec_plot2(S_m,freq,time,typ,f_min,f_max,c_min);\n% Type: spec_plot2(S_m,freq,time,typ,f_min,f_max);\n% Type: spec_plot2(S_m,freq,time,typ,f_min);\n% Type: spec_plot2(S_m,freq,time,typ);\n% Type: spec_plot2(S_m,freq,time);\n%\n% Inputs:\n%\n% S_m    := Time frequency distribution matrix n x m matrix\n% freq   := Frequency vector n x 1 vector\n% time   := Time vector m x 1 vector\n% typ    := 'lin' or 'log' string for color scale of image plot\n% f_min  := Minimum frequency to show, scalar\n% f_max  := Maximum frequency to show, scalar\n% c_min  := value for low end of color spectrum (see caxis), scalar\n% c_max  := value for high end of color spectrum (see caxis), scalar\n%\n% This version uses pcolor and shading interp instead of imagesc\n\n% Scot McNeill, University of Houston, Fall 2007.\n%\nmsg=nargchk(3,8,nargin);\nif ~isempty(msg)\n   error(msg)\nend\n%\nS_m=varargin{1};\nfreq=varargin{2};\ntime=varargin{3};\n%\nif (length(varargin) >= 4 & ~isempty(varargin{4}))\n   typ=varargin{4};\nelse\n   typ='log';\nend\n%\nif (length(varargin) >= 5 & ~isempty(varargin{5}))\n   f_min=varargin{5};\nelse\n   f_min=min(freq);\nend\n%\nif (length(varargin) >=6 & ~isempty(varargin{6}))\n   f_max=varargin{6};\nelse\n   f_max=max(freq);\nend\n%\nif (length(varargin) >= 7 & ~isempty(varargin{7}))\n   c_min=varargin{7};\nelse\n   c_min=[];\nend\n%\nif (length(varargin) ==8 & ~isempty(varargin{8}))\n   c_max=varargin{8};\nelse\n   c_max=[];\nend\n%\n[nr,nc]=size(S_m);\nnt=length(time);\nnf=length(freq);\nif (nr ~= nf & nc ~= nt)\n   error('S_m must have dimensions length(freq) x length(time)')\nend\n%\n[i1]=find(freq>=f_min & freq<=f_max);\nfreq=freq(i1);\nS_m=S_m(i1,:);\n%\nnewplot;\nif strcmp(typ,'log');\n   %imagesc(time,freq,log10(abs(S_m)+eps));\n   pcolor(time,freq,log10(abs(S_m)+eps));shading interp;\n   axis xy;\n   colormap(jet);\n   xlabel('Time (seconds)');\n   ylabel('Frequency (Hz)');\n   title('Spectrogram');\n   axis([min(time),max(time),f_min,f_max]);\n   [c1,c2]=caxis;\n   if isempty(c_min);c_min=c1;end;\n   if isempty(c_max);c_max=c2;end;\n   caxis([c_min,c_max]);\n   h = colorbar;\n   set(get(h,'YLabel'),'String','Spectrogram, log_1_0([Units]^2/Hz)');\nelseif strcmp(typ,'lin');\n   %imagesc(time,freq,abs(S_m));\n   pcolor(time,freq,abs(S_m));shading interp;\n   axis xy;\n   colormap(jet);\n   xlabel('Time (seconds)');\n   ylabel('Frequency (Hz)');\n   title('Spectrogram');\n   axis([min(time),max(time),f_min,f_max]);\n   [c1,c2]=caxis;\n   if isempty(c_min);c_min=c1;end;\n   if isempty(c_max);c_max=c2;end;\n   caxis([c_min,c_max]);\n   h = colorbar;\n   set(get(h,'YLabel'),'String','Spectrogram, [Units]^2/Hz');\nelse\n   error(['typ must be ''lin'' or ''log''.']);\nend\nset(gca,'tickdir','out');\ndrawnow\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/32639-vold-kalman-order-tracking-code/vk_pkg/spec_plot2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5936715263471255}}
{"text": "function pass = test_contour3( pref )\n% Test contour3\n\nif ( nargin == 0 )\n    pref = chebfunpref;\nend\n\nf = diskfun(@(x,y) cos(cos(4*x).^2 + sin(5*y).^2));\nx = -pi:.1:pi;\ny = -1:.1:1;\n[xx, yy] = meshgrid(x,y);\n\npass = 1;\ntry\n   contour3(f)\n   contour3(f, 5)\n   contour3(f, [0.4 0.4])\n   contour3(f, 'numpts', 100)\n   contour3(f, 'pivots', 'r.-')\n   contour3(xx, yy, f)\ncatch ME\n    pass = 0;\nend\n\nclose all\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/diskfun/test_contour3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.5936715173641063}}
{"text": "function [u,p,info] = mgDarcy(M,B,f,g,elem,option,varargin)\n%% MGDARCY multigrid solvers for Darcy system discretized by RT0-P0 element\n%\n% [u,p,info] = mgDarcy(M,B,f,g,elem) solves saddle point problem\n% discretized from RT0-P0 mixed FEM for Darcy equation.\n%\n%      |M  B'| |u|  = |f|\n%      |B  0 | |p|  = |g|\n%\n%  A V-cycle multigrid using overlapping Schwarz smoother is implemented.\n%  In the first step, mgdivDarcy is called to find initial u satisfying Bu\n%  = g. Then at each vertex patch, a local problem with prescribed boundary\n%  flux is solved. Detailed description and convergence analysis can be\n%  found in the reference.\n%\n%  It is around 10 times slower than tripremixPoisson since a large for\n%  loop is not efficient in MATLAB. In operation count, this is superior.\n%  See the complexity analysis in page 18 of the reference.\n%\n% Reference: L. Chen. Multigrid Methods for Constrained Minimization\n% Problems and Application to Saddle Point Problems\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\ntime = cputime;\n%% Size of systems\nNu = length(f);                    \nNp = length(g);\nN = max(elem(:));                  % number of nodes\n% NT = size(elem,1);               % number of elements\n\n%% Options\n% Assign default values to unspecified parameters\nif ~exist('option','var'), \n    option = []; \nend\noption = mgoptions(option,Nu);    % parameters\nu0 = option.x0; \nN0 = option.N0; \ntol = option.tol;\nmaxIt = option.solvermaxit; \nmu = option.smoothingstep; \ncoarsegridsolver = option.coarsegridsolver; \nprintlevel = option.printlevel; \nfreeEdge = option.freeEdge;\n\n%% Hierarchical Structure of Mesh\nHB = zeros(N,3);\nlevel = 20;\nNL(level+1) = N; % now NL(1:level) = 0;\nelemi = cell(level,1);\nelemi{level} = elem;\nfreeEdgei = cell(level,1);\nfreeEdgei{level} = freeEdge;\nPro_u = cell(level,1);\nPro_p = cell(level,1);\nfor k = level: -1 : 2\n    switch option.refType \n        case 'red'\n            [elemi{k-1},newHB] = uniformcoarsenred(elemi{k}); % coasen red refinement\n            if ~isempty(newHB)\n                [Pro_u{k-1}, freeEdgei{k-1}] = transferedgered(elemi{k-1},elemi{k},freeEdgei{k}); % transfer operator of u\n                Pro_p{k-1} = repmat(speye(size(elemi{k-1},1)),4,1);   % transfer operator of p\n            end\n        case 'bisect'\n            % merge two coarsen of bisection grids s.t. the ratio is 1/4.\n            [tempelem,newHB1,tree] = uniformcoarsen(elemi{k}); % coarse bisection\n            if ~isempty(newHB1)            \n                % first coarsen\n                [tempPro_u,tempFreeEdge] = transferedgecoarsen(tempelem,elemi{k},tree,freeEdgei{k});\n                tempPro_p = transferelem(tempelem,elemi{k},tree);\n                % second coarsen\n                [elemi{k-1},newHB2,tree] = uniformcoarsen(tempelem); % coarse bisection\n                [Pro_u{k-1}, freeEdgei{k-1}] = transferedgecoarsen(elemi{k-1},tempelem,tree,tempFreeEdge);\n                Pro_u{k-1} = tempPro_u*Pro_u{k-1};\n                Pro_p{k-1} = transferelem(elemi{k-1},tempelem,tree);\n                Pro_p{k-1} = tempPro_p*Pro_p{k-1};\n                newHB = [newHB1; newHB2];\n            end\n    end    \n    if (isempty(newHB)) || (size(elemi{k},1)< 2*N0) \n        % no nodes are removed or it reaches the coarsest level\n        NL = NL(k:end);       \n        break; \n    end\n    NL(k) = NL(k+1) - size(newHB,1); % update NL(k)\n    HB(NL(k)+1:NL(k+1),1:3) = newHB(:,1:3);\nend\nlevel = length(NL)-1;    % actual level\nelemi = elemi(end-level+1: end);\nPro_u = Pro_u(end-level+1: end);\nPro_p = Pro_p(end-level+1: end);\nfreeEdgei = freeEdgei(end-level+1: end);\n% generate edge, elem2edge and freeNode etc\nedgei = cell(level,1);\nelem2edgei = cell(level,1);\nfor k = 1:level\n    [elem2edgei{k},edgei{k}] = dofedge(elemi{k});\nend\n\n%% Matrices in each level\noldf = f;\nMi = cell(level,1);\nBi = cell(level,1);\nif size(M,1) > length(freeEdge) % truncate to free edge only\n    Mi{level} = M(freeEdge,freeEdge);    \n    Bi{level} = B(:,freeEdge);\n    f  = f(freeEdge);\n    u0 = u0(freeEdge);\nelse\n    Mi{level} = M;    \n    Bi{level} = B;    \nend\nRes_u = cell(level,1);\nRes_p = cell(level,1);\nfor k = level:-1:2\n    Res_u{k} = transpose(Pro_u{k-1});\n    Res_p{k} = transpose(Pro_p{k-1});\n    Mi{k-1} = Res_u{k}*Mi{k}*Pro_u{k-1};           \n    Bi{k-1} = Res_p{k}*Bi{k}*Pro_u{k-1};\nend\n\n% %% Exact solver: for debug only\n% C = sparse(size(B,1),size(B,1));\n% A = [M B';B C];\n% F = [f; zeros(size(B,1),1)];\n% tempu = A\\F;\n% exactSigma = tempu(1:Ndof);\n\n%% MG cycles\n% initial set up\nk = 1; \nf0 = f - Mi{level}*u0;\ng0 = g - Bi{level}*u0;\n% find u satisfy Bu = g\nu = u0 + mgdivDarcy(f0,g0);\n% temp = abs(g-Bi{level}*u);\n% idx = temp<1e-14;\n% findelem(node,elem,idx,'noindex','FaceColor','c');  \nif printlevel >= 1\n    fprintf('Multigrid Vcycle Iteration \\n')\nend\nerr = zeros(maxIt,1);\nerr(1) = 1;\nr0 = f - Mi{level}*u;\nr = r0;\nwhile (max(err(k,:)) > tol) && (k <= maxIt)\n    k = k + 1;\n    % Step 2: Compute Br by one Vcylce MG\n    Br = vcycle(r);\n    % Step 3: Correct the solution\n    u = u + Br;\n    % Step 1: Form residual r\n    r = r - Mi{level}*Br;\n    err(k) = sqrt(abs(Br'*r/(u'*r0))); % approximate relative error in energy norm\n    if printlevel >= 2\n        fprintf('#dof: %8.0u,  #nnz: %8.0u, MG Vcycle iter: %2.0u, err = %8.4e\\n',...\n                 Nu+N, nnz(M)+nnz(B), k-1, err(k));\n    end            \nend\n\nerr = err(1:k,:);\nitStep = k-1;\n\n%% Find pressure\nAp = B*B';\nubar = zeros(Nu,1);\nubar(freeEdge) = u;\nb = B*(oldf-M*ubar);\np = zeros(Np,1);\nif option.isPureNeumannBC\n    freep = 1:Np-1;\nelse\n    freep = 1:Np;\nend\np(freep) = Ap(freep,freep)\\b(freep);\n\n%% Output\ntime = cputime - time;\nif k > maxIt\n    flag = 1;\nelse\n    flag = 0;\nend\nif printlevel >= 2\n    fprintf('#dof: %8.0u, level: %2.0u,   coarse grid %2.0u, #nnz: %8.0u\\n',...\n              Nu+N, level, size(Mi{1},1), nnz(Mi{1}))\nend\nif printlevel >= 1\n    fprintf('#dof: %8.0u,  #nnz: %8.0u, smoothing: %2.0u, iter: %2.0u,   err = %8.4e,   time = %4.2g s\\n',...\n                 Nu+Np, nnz(M)+2*nnz(B), mu, itStep, err(end), time)\nend\nif (flag == 1) && (printlevel>0)\n   fprintf('NOTE: the iterative method does not converge! \\n');    \nend\ninfo = struct('solverTime',time,'itStep',itStep,'error',err,'flag',flag,'stopErr',max(err(end,:)));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions vcycle\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Vcycle MG\n    function Br = vcycle(r,J)        % solve equations Ae = r in each level  \n    if nargin<=1\n        J = level;\n    end\n    ri = cell(J,1);            % record residual in each level\n    ei = cell(J,1);            % record err in each level\n    ri{J} = r;\n    for i = J:-1:2\n        ei{i} = zeros(size(Mi{i},1),1);\n        ei{i} = SchwarzsmootherDarcy(Mi{i},Bi{i},ri{i},zeros(size(Bi{i},1),1),...\n                ei{i},elemi{i},edgei{i},elem2edgei{i},freeEdgei{i},mu);\n        ri{i-1} = Res_u{i}*(ri{i} - Mi{i}*ei{i});\n    end\n    if strcmp(coarsegridsolver,'direct')\n        Ncoarse = size(Bi{1},1);\n        C1 = sparse(Ncoarse,Ncoarse);\n        A1 = [Mi{1} Bi{1}'; Bi{1} C1];\n        F1 = [ri{1}; zeros(Ncoarse,1)];\n        if option.isPureNeumannBC\n            bigu = A1(1:end-1,1:end-1)\\F1(1:end-1); % pure Neumann\n        else\n            bigu = A1\\F1;\n        end\n        ei{1} = bigu(1:size(Mi{1},1));\n    end\n    for i = 2:J\n        ei{i} = ei{i} + Pro_u{i-1}*ei{i-1};\n        ei{i} = SchwarzsmootherDarcy(Mi{i},Bi{i},ri{i},zeros(size(Bi{i},1),1),...\n                ei{i},elemi{i},edgei{i},elem2edgei{i},freeEdgei{i},-mu);\n    end\n    Br = ei{J};\n    end\n%% div Darcy\n% Use one V-cycle with post-smoothing only to find u s.t. div u = g\n\n    function u = mgdivDarcy(rf,rg)\n    J = level;\n    rfi = cell(J,1);\n    rgi = cell(J,1);\n    eui = cell(J,1);\n    rfi{J} = rf;\n    rgi{J} = rg;\n    % restrict the residual to the coarse level\n    for i = J:-1:2\n        rfi{i-1} = Res_u{i}*rfi{i};\n        rgi{i-1} = Res_p{i}*rgi{i};\n    end\n    % exact solve in the coarest mesh\n    Ncoarse = size(Bi{1},1);\n    C1 = sparse(Ncoarse,Ncoarse);\n    A1 = [Mi{1} Bi{1}'; Bi{1} C1];\n    F1 = [rfi{1}; rgi{1}];\n    if option.isPureNeumannBC\n        bigu = A1(1:end-1,1:end-1)\\F1(1:end-1); % pure Neumann\n    else\n        bigu = A1\\F1;\n    end\n    eui{1} = bigu(1:size(Mi{1},1));\n    % prolongate to the fine level and post-smoothing in each element\n    for i = 2:J\n        eui{i} = Pro_u{i-1}*eui{i-1};\n        eui{i} = SchwarzsmootherelemDarcy(Mi{i},Bi{i},rfi{i},rgi{i},...\n                eui{i},elemi{i},edgei{i},elem2edgei{i},freeEdgei{i},1);\n    end\n    u = eui{J};\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/solver/mgDarcy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5936546598216703}}
{"text": "clear\npatchSize = 8;\n\n% images courtesy of Stefan Roth\nI = double((imread('new.jpg')))/255;\nmask = double((imread('new_mask.png')))/255;\n\nif size(I,3)>1\n    I = rgb2ycbcr(I);\nend\n\n% find which patches are occluded for faster performance\nnoiseI = I;\nmask_inds = find(mask>0);\ntt = noiseI(:,:,1);\ntt(mask_inds)=NaN;\nttt = im2col(tt,[patchSize patchSize]);\nexcludeList = find(any(isnan(ttt)));\nclear ttt;\n\nnoiseI = I;\nfor i=1:size(I,3)\n    tt = I(:,:,i);\n    tt(mask_inds) = 0;\n    noiseI(:,:,i)=tt;\nend\n\n\n% load ICA model and initialize MAP estimator\nload ICAModel\nW = W*E;\ninvW = pinv(W);\nprior = @(Z,patchSize,noiseSD,imsize) PatchDCTGG(Z,patchSize,noiseSD,imsize,W,invW,excludeList);\n\n\n%%\ntic\n\n% inpainting\nlambda = 1000000*ones([size(I,1) size(I,2)]);\nlambda(mask_inds)=0;\ncleanI = zeros(size(I));\nfor i=1:size(I,3)\n    cleanI(:,:,i) = EPLLhalfQuadraticSplit(noiseI(:,:,i),lambda,patchSize,10*[1 2 16 128 512],20,prior,I(:,:,i));\nend\n\n%%\nif (size(I,3)>1)\n    cleanI = ycbcr2rgb(cleanI);\n    I = ycbcr2rgb(I);\n    noiseI = ycbcr2rgb(noiseI);\nend\ntoc\n\n%% output result\nfigure(1);\nimshow(I); title('Original');\nfigure(2);\nimshow(noiseI); title('Corrupted Image');\nfigure(3);\nimshow(cleanI); title('Restored Image');\nfprintf('PSNR is:%f\\n',20*log10(1/std2(cleanI-I)));\n\n", "meta": {"author": "lbasek", "repo": "image-denoising-benchmark", "sha": "9d753198d715b7628c8e7d9259dfa5c219d033ea", "save_path": "github-repos/MATLAB/lbasek-image-denoising-benchmark", "path": "github-repos/MATLAB/lbasek-image-denoising-benchmark/image-denoising-benchmark-9d753198d715b7628c8e7d9259dfa5c219d033ea/algoritms/matlab/EPLL/extra/demo_inpaint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5936546338820363}}
{"text": "function [c, d] = lpdec1(x, h, g, extmod)\n% LPDEC1   One-level Laplacian pyramid decomposition\n%\n%\t[c, d] = lpdec1(x, h, g)\n%\n% Input:\n%   x:      input signal\n%   h, g:   two biorthogonal 1-D lowpass filters\n%   extmod: [optional] extension mode (default is 'per')\n%\n% Output:\n%   c:      coarse signal at half size\n%   d:      detail signal at full size\n%\n% See also:\tLPREC1\n\nif ~exist('extmod', 'var')\n    extmod = 'per';\nend\n\nnd = ndims(x);\n\n% Computer the coarse signal by filter and downsample\nc = x;\nfor dim = 1:nd\n    c = filtdn(c, h, dim, extmod, 0);\nend\n    \n% Compute the detail signal by upsample, filter, and subtract\n% Even size filter needs to be adjusted to obtain perfect reconstruction\nadjust = mod(length(g) + 1, 2);\n\np = c;\nfor dim = 1:nd\n    p = upfilt(p, g, dim, extmod, adjust);\nend\n\nd = x - p;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9868-laplacian-pyramid-toolbox/lpdec1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5936546338820363}}
{"text": " function [C, rj] = penalty2_design(type, varargin)\n%|function [C, rj] = penalty2_design(type, ['leak'|'tight'], wang, ang, mask)\n%|\n%| Design the penalty matrix \"C\" (and penalty coefficients \"rj\")\n%| for a quadratic penalty R(x) = 1/2 x' C * C * x with:\n%| 1st-order differences and a 2nd-order neighborhood (8 neighbors).\n%| For 2D parallel-beam tomography with shift-invariant blur.\n%| Design based on Fourier method in fessler:03:aat (IEEE MIC, 2003).\n%|\n%| in\n%|\ttype\t\t\t'test' or 'quad,d1,n2' or 'quad,d1,n1'\n%|\t\t\t\t(n2 for usual 2nd order neighborhood)\n%|\twang\t[na nx ny]\tangular weights for each pixel\n%|\tang\t[na]\t\tangles\n%|\tmask\t[nx ny]\t\t(logical) reconstruction support\n%| out:\n%|\tC\t[4*nx*ny nx*ny] \"modified\" C containing sqrt{r_j} factors\n%|\trj\t[nx ny 4]\thoriz,vert,diag1,diag2 coefficients\n%|\n%| Copyright 2003-5-23, Jeff Fessler, University of Michigan\n\nif nargin < 1, ir_usage, end\n\n% run a self-test to compare my analytical solution\n% to the numerical solution computed using NNLS.\nif nargin == 1 && streq(type, 'test')\n\tpenalty2_design_test\nreturn\nend\n\n% analytical design of 1st-order difference, 2nd-order neighborhood\nif streq(type, 'quad,d1', 7)\n\tif length(varargin) < 1 || length(varargin) > 3, ir_usage, end\n\n\tif ischar(varargin{1})\n\t\tCtype = varargin{1};\n\t\tvarargin = varargin{2:end};\n\telse\n\t\tCtype = 'leak';\n\tend\n\n\twang = varargin{1};\n\t[na nx ny] = size(wang);\n\tnp = nx*ny;\n\twang = reshape(wang, [na np]);\n\n\tif length(varargin) >= 2\n\t\tang = col(varargin{2});\n\t\tif na ~= length(ang), error 'angle dim', end\n\telse\n\t\tang = [0:(na-1)]'/na * pi; % [0,pi)\n\tend\n\n\tif length(varargin) == 3\n\t\tmask = varargin{3};\n\t\tif any(size(mask) ~= [nx ny]), error 'mask dims', end\n\telse\n\t\tmask = true(nx,ny);\n\tend\n\n\t% dot product of each basis with wj\n\t% the \"mean\" takes care of normalization\n\tbasis = [ones(size(ang)) cos(2*ang) sin(2*ang)];\n\tdot_products = zeros(ncol(basis),np);\n\tfor ib=1:ncol(basis)\n\t\tb = basis(:,ib);\n\t\tb = repmat(basis(:,ib), 1, np);\n\t\tdot_products(ib,:) = mean(b .* wang, 1);\n\tend, clear ib b\n\n\tsptmp = @(tmp) spdiag(tmp, 'nowarn'); % for now\n\n\tif streq(type, 'quad,d1,n1') % 1st-order neighborhood\n\t\trj = penalty2_design_d1_n1(dot_products); % [2 np]\n\t\trj = permute(reshape(rj, [2 nx ny]), [2 3 1]); % [nx ny 2]\n\t\tC = C2sparse('leak', mask, 4, 0, 0);\n\t\ti1 = 1:(nx*ny);\n\t\tC = [\tsptmp(sqrt(col(rj(:,:,1)))) * C(0*nx*ny+i1,:);\n\t\t\tsptmp(sqrt(col(rj(:,:,2)))) * C(1*nx*ny+i1,:)];\n\n\telseif streq(type, 'quad,d1,n2') % 2nd-order neighborhood\n\t\trj = penalty2_design_d1_n2(dot_products); % [4 np]\n\t\trj = permute(reshape(rj, [4 nx ny]), [2 3 1]); % [nx ny 4]\n\t\t% fix: this must depend on flip_y !!\n\t\tprintf('Warn: penalty2_design.m may fail if flip_y = -1')\n\t\trj = rj(:,:,[1 2 4 3]); % re-order 45,135 (empirical)\n\n\t\tC = C2sparse('leak', mask, 8, 0, 0);\n\t\ti1 = 1:(nx*ny);\n\t\t% analysis assumes 1/sqrt(2) for diagonal 1st differences!\n\t\tC = [\tsptmp(sqrt(col(rj(:,:,1))))\t* C(0*nx*ny+i1,:);\n\t\t\tsptmp(sqrt(col(rj(:,:,2))))\t* C(1*nx*ny+i1,:);\n\t\t\tsptmp(sqrt(col(rj(:,:,3))/2))\t* C(2*nx*ny+i1,:);\n\t\t\tsptmp(sqrt(col(rj(:,:,4))/2))\t* C(3*nx*ny+i1,:)];\n\telse\n\t\terror 'bad type'\n\tend\n\nelse\n\terror(['unknown type: ' type])\nend\n\n\n%\n% in:\tiprod\t[3 np]\t\tinner products of angular weights with\n%\t\t\t\t\t[1 cos(2a) sin(2a)]\n% out:\trj\t[2 np]\t\thoriz,vert\n%\nfunction rj = penalty2_design_d1_n1(iprod)\n\nd1 = iprod(1,:);\nd2 = iprod(2,:);\n\nif any(d1 < 0), error 'bad inner products: d1<0', end\nif any(abs(d2) > d1), error 'bad inner products: d2>d1', end\n\nrj = [d1+2*d2; d1-2*d2];\n\nii = d2 > d1/2;\nr1 = 4/3 * (d1 + d2);\nrj(1,ii) = r1(ii);\nrj(2,ii) = 0;\n\nii = d2 < -d1/2;\nr2 = 4/3 * (d1 - d2);\nrj(1,ii) = 0;\nrj(2,ii) = r2(ii);\n\n\n\n%\n% in:\n%\tiprod\t[3 np]\t\tinner products of angular weights with\n%\t\t\t\t\t[1 cos(2a) sin(2a)]\n%\t\t\t\t\ttypically np = # of pixels\n% out:\n%\trj\t[4 np]\t\thoriz,vert,diag1,diag2 coefficients\n%\n% caution: diagonals coefficients are designed to be used with\n% diagonal differences that are normalized by 1/\\sqrt{2}.\n%\nfunction rj = penalty2_design_d1_n2(iprod)\n\nd1 = iprod(1,:);\ndp2 = iprod(2,:);\ndp3 = iprod(3,:);\nd2 = max(abs(dp2), abs(dp3)); % d2 >= d3\nd3 = min(abs(dp2), abs(dp3));\nif any(d1 < 0), error 'bad inner products: d1<0', end\nif any(d2 > d1), error 'bad inner products: d2>d1', end\n\nrj = zeros(4,length(d1));\n\nii = (d2 >= d1/2) & (d3 <= 2/3*d2 - d1/3); % case 1\nr1 = 4/3 * (d1 + d2);\nrj(1,ii) = r1(ii);\n\nii = (d3 >= 2/3*d2 - d1/3) & (d3 + d2 >= d1/2); % case 2\nr1 = 8/5 * (d1/2 + 3/2*d2 - d3);\nr3 = 12/5 * (d3 - 2/3*d2 + 1/3*d1);\nrj(1,ii) = r1(ii);\nrj(3,ii) = r3(ii);\n\nii = (d3 + d2 <= d1/2) & (d2 >= d1/4); % case 3\nrj(1,ii) = 4*d2(ii);\nr3 = d1 - 2*d2 + 2*d3;\nr4 = d1 - 2*d2 - 2*d3;\nrj(3,ii) = r3(ii);\nrj(4,ii) = r4(ii);\n\nii = (d2 <= d1/4); % case 4\nr1 = d1/2 + 2*d2;\nr2 = d1/2 - 2*d2;\nr3 = d1/2 + 2*d3;\nr4 = d1/2 - 2*d3;\nrj(1,ii) = r1(ii);\nrj(2,ii) = r2(ii);\nrj(3,ii) = r3(ii);\nrj(4,ii) = r4(ii);\n\n% symmetries\nii = abs(dp3) > abs(dp2);\nrj(:,ii) = rj([3 4 1 2],ii);\n\nii = dp3 < 0;\nrj([3 4],ii) = rj([4 3],ii);\n\nii = dp2 < 0;\nrj([1 2],ii) = rj([2 1],ii);\n\n\n%\n% brute-force NNLS approach\n% dot\t[3 np]\n% rj\t[4 np]\n%\nfunction rj = penalty2_design_nnls(Amat, dot)\n\nww = [dot(1,:); sqrt(2)*dot([2 3],:)];\nopt = optimset('lsqnonneg');\nopt = optimset(opt, 'tolx', 10*eps);\n\nrj = zeros(4, ncol(ww));\nfor jj=1:ncol(ww)\n\trj(:,jj) = lsqnonneg(Amat, ww(:,jj));\n\tif ~rem(jj,100), printf('%d of %d', jj, ncol(ww)), end\nend\n\n\n\n% penalty2_design_test()\nfunction penalty2_design_test\nAmat = 0.5 * [1 1 1 1;\n\t\t1/sqrt(2) -1/sqrt(2) 0 0 ;\n\t\t0 0 1/sqrt(2) -1/sqrt(2)];\nn2 = 41;\nn3 = 43;\nd2 = linspace(-1,1,n2);\nd3 = linspace(-1,1,n3);\ndot = zeros(3,n2*n3);\n[t2, t3] = ndgrid(d2, d3);\ndot(1,:) = 1;\ndot(2,:) = t2(:)';\ndot(3,:) = t3(:)';\n\nrj_anal = penalty2_design_d1_n2(dot);\nrj_nnls = penalty2_design_nnls(Amat, dot); % [4 n2*n3]\n\npenalty2_design_test_figure(Amat, dot, d2, d3, rj_anal, rj_nnls)\n\n\nfunction penalty2_design_test_figure(Amat, dot, d2, d3, ra, rn)\n\nn2 = length(d2);\nn3 = length(d3);\n\nww = [dot(1,:); sqrt(2)*dot([2 3],:)];\nerra = permute(reshape(Amat * ra - ww, [3 n2 n3]), [2 3 1]); % [n2 n3 3]\nerrn = permute(reshape(Amat * rn - ww, [3 n2 n3]), [2 3 1]);\n\nra = permute(reshape(ra, [4 n2 n3]), [2 3 1]); % [n2 n3 4]\nrn = permute(reshape(rn, [4 n2 n3]), [2 3 1]);\n\nif im\n\tclf, pl=440;\n\tfor ib=1:4\n\t\tim(pl+ib+0, d2, d3, ra(:,:,ib)), axis xy, cbar\n\t\ttitle(sprintf('Anal. ib=%d', ib))\n\t\tim(pl+ib+4, d2, d3, rn(:,:,ib)), axis xy, cbar\n\t\ttitle NNLS\n\tend\n\n\tsubplot(4,4,9)\n\tim(d2, d3, sum(ra > 0,3), 'Anal. sum(r > 0)'), axis xy, cbar\n\tsubplot(4,4,10)\n\tim(d2, d3, sum(rn > 0,3), 'NNLS sum(r > 0)'), axis xy, cbar\n\n\t% hold on, plot(d2, 2/3*(d2 - 1/sqrt(2)), 'c-'), hold off\n\t% hold on, plot(d2, sqrt(2)/3 - 2/3*d2, 'r-'), hold off\n\n\ttmp = sqrt(sum(erra.^2, 3));\n\tsubplot(4, 4, 11)\n\tim(d2, d3, tmp, 'Anal. |err|'), axis xy, cbar\n\tsubplot(4, 4, 15)\n\tim(d2, d3, tmp < 10*eps, 'Anal. |err|=0'), axis xy, cbar\n\n\ttmp = sqrt(sum(errn.^2, 3));\n\tsubplot(4, 4, 12)\n\tim(d2, d3, tmp, 'NNLS |err|'), axis xy, cbar\n\tsubplot(4, 4, 16)\n\tim(d2, d3, tmp < 10*eps, 'NNLS |err|=0'), axis xy, cbar\n\n\tsubplot(4, 4, 13)\n\t%im(d2, d3, sum(erra.^2, 3) < sum(errn.^2, 3)+10*eps, 'Anal<NNLS')\n\tim(d2, d3, sum(errn.^2, 3) - sum(erra.^2, 3), 'NNLS-Anal')\n\taxis xy, cbar\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/penalty/penalty2_design.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.593654629426313}}
{"text": "function jac = p27_jac ( neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P27_JAC evaluates the jacobian for problem p27.\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  if ( mod ( floor ( t ), 2 ) == 0 )\n    jac(1,1) = - 1.5;\n  else\n    jac(1,1) = - 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/test_ode/p27_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5936095843358795}}
{"text": "function value = c8_nint ( c1 )\n\n%*****************************************************************************80\n%\n%% C8_NINT returns the nearest complex integer of a C8.\n%\n%  Discussion:\n%\n%    A C8 is a complex ( kind = 8 ) value.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    02 March 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, complex C1, the value to be NINT'ed.\n%\n%    Output, complex VALUE, the NINT'ed value.\n%\n  xc = real ( c1 );\n  yc = imag ( c1 );\n%\n%  Lower left.\n%\n  x = floor ( real ( c1 ) );\n  y = floor ( imag ( c1 ) );\n  r = ( x - xc ) .^2 + ( y - yc ) .^2;\n  r_min = r;\n  x_min = x;\n  y_min = y;\n%\n%  Lower right.\n%\n  x = floor ( real ( c1 ) ) + 1.0;\n  y = floor ( imag ( c1 ) );\n  r = ( x - xc ) .^2 + ( y - yc ) .^2 ;\n  if ( r < r_min )\n    r_min = r;\n    x_min = x;\n    y_min = y;\n  end\n%\n%  Upper right.\n%\n  x = floor ( real ( c1 ) ) + 1.0;\n  y = floor ( imag ( c1 ) ) + 1.0;\n  r = ( x - xc ) .^2 + ( y - yc ) .^ 2;\n  if ( r < r_min )\n    r_min = r;\n    x_min = x;\n    y_min = y;\n  end\n%\n%  Upper left.\n%\n  x = floor ( real ( c1 ) );\n  y = floor ( imag ( c1 ) ) + 1.0;\n  r = ( x - xc ) .^ 2 + ( y - yc ) .^ 2;\n  if ( r < r_min )\n    r_min = r;\n    x_min = x;\n    y_min = y;\n  end\n\n  value = x_min + i * y_min;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/c8lib/c8_nint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.5936095722269676}}
{"text": "% Chapter 5: Duality\n%\n%  qcqp.m            - Section 5.2.4: Solves a simple QCQP\n%  matrix_games.m    - Section 5.2.5: Mixed strategies for matrix games\n%  matrix_games_LP.m - Section 5.2.5: Mixed strategies for matrix games (LP formulation)\n%  norm_approx.m     - Examples 5.6,5.8: An l_p norm approximation problem\n%  ex_5_19.m         - Exercise 5.19c: Markovitz portfolio optimization w/ diversification constraint\n%  ex_5_1.m          - Exercise 5.1d: Sensitivity analysis for a simple QCQP\n%  ex_5_33.m         - Exercise 5.33: Parametrized l1-norm approximation\n%  ex_5_39.m         - Exercise 5.39: SDP relaxations of the two-way partitioning problem\nhelp Contents\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/Ch05_duality/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.5936095722269676}}
{"text": "function varargout = hikmeans(varargin)\n% VL_HIKMEANS  Hierachical integer K-means\n%   [TREE,ASGN] = VL_HIKMEANS(DATA,K,NLEAVES) applies recursive integer\n%   K-menas to cluster the data DATA, returing a structure TREE\n%   representing the clusters and a vector ASGN with the data to\n%   cluster assignments. The depth of the recursive partition is\n%   computed so that at least NLEAVES are generated.\n%\n%   VL_HIKMEANS() is built on top of VL_IKMEANS() and requires the data to\n%   be of class UINT8.\n%\n%   TREE is a structure representing the hierarchical clusters.  Each\n%   node of the tree is also a structure with fields:\n%\n%   DEPTH::\n%     Depth of the tree (only at the root node)\n%\n%   CENTERS::\n%     K cluster centers\n%\n%   SUB::\n%     Array of K node structures representing subtrees\n%     (this field is missing at leaves).\n%\n%   ASGN is a matrix with one column per datum and height equal to the\n%   depth of the tree. Each column encodes the branch of the tree that\n%   correspond to each datum.\n%\n%   Example::\n%     ASGN(:,7) = [1 5 3] means that the tree as depth equal to 3 and\n%     that the datum X(:,7) corresponds to the branch\n%     ROOT->SUB(1)->SUB(5)->SUB(3).\n%\n%   See also: VL_HIKMEANSPUSH(), VL_HIKMEANSHIST(), VL_IKMEANS(), VL_HELP().\n[varargout{1:nargout}] = vl_hikmeans(varargin{:});\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/noprefix/hikmeans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5935206068793611}}
{"text": "function a = isTransform3d(trans, varargin)\n%ISTRANSFORM3D Check if input is a affine transformation matrix.\n%\n%   A = isTransform3d(TRANS) where TRANS should be a transformation matrix.\n%   The function accepts transformations given using the following formats:\n%   [a b c]   ,   [a b c j] , or  [a b c j]\n%   [d e f]       [d e f k]       [d e f k]\n%   [g h i]       [g h i l]       [g h i l]\n%                                 [0 0 0 1]\n%   \n%   If the transformation matrix should only contain rotation and\n%   translation without reflection, scaling, shearing, ... set 'rotation'\n%   to true. Default is false.\n%\n%   Example\n%     rot = ...\n%         createRotationOx(rand*2*pi)*...\n%         createRotationOy(rand*2*pi)*...\n%         createRotationOx(rand*2*pi);\n%     trans = rot*createTranslation3d(rand(1,3));\n%     isTransform3d(trans, 'rot', true)\n%\n%   See also \n%   composeTransforms3d, createBasisTransform3d, recenterTransform3d,\n%   transformPoint3d\n\n% ------\n% Author: oqilipo\n% E-mail: N/A\n% Created: 2018-07-08\n% Copyright 2018-2022\n\nnarginchk(1,5)\n\np = inputParser;\nlogParValidFunc = @(x) (islogical(x) || isequal(x,1) || isequal(x,0));\naddParameter(p,'rotation', 0, logParValidFunc);\nvalTol = @(x) validateattributes(x,{'numeric'},{'scalar', '>=',eps(class(trans)), '<=',1});\naddParameter(p,'tolerance', 1e-8, valTol);\nparse(p,varargin{:});\nrotation = p.Results.rotation;\ntolerance = p.Results.tolerance;\n\n% eventually add null translation\nif size(trans, 2) == 3\n    trans = [trans zeros(size(trans, 1), 1)];\nelseif size(trans, 2) < 3 || size(trans, 2) > 4\n    a=false;\n    return\nend\n\n% eventually add normalization\nif size(trans, 1) == 3\n    trans = [trans;0 0 0 1];\nelseif size(trans, 1) < 3 || size(trans, 1) > 4\n    a=false;\n    return\nend\n\na=true;\n\n% NaN is invalid\nif any(isnan(trans(:)))\n    a=false;\n    return\nend\n\n% Infinity is invalid\nif any(isinf(trans(:)))\n    a=false;\n    return\nend\n\n% trans(4,4) has to be a one\nif ~isequal(1, trans(4,4))\n    a = false;\n    return\nend\n\n% trans(4,1:3) have to be zeros\nif ~isequal(zeros(1,3), trans(4,1:3))\n    a = false;\n    return\nend\n\nif rotation\n    % transpose(trans(1:3,1:3)) * trans(1:3,1:3) has to be eye(3)\n    if any(abs(eye(3) - (trans(1:3,1:3)'*trans(1:3,1:3))) > tolerance)\n        a = false;\n        return;\n    end\n    \n    % determinant of trans(1:3) has to be one\n    if abs(1-det(trans)) > tolerance\n        a = false;\n        return\n    end\nend\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/geom3d/isTransform3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5935206025955253}}
{"text": "function [Z, H, dnorm] = seminmf( X, k, varargin )\n% Matrix sizes\n% X: m x n\n% Z: m x num_of_components\n% H: num_of_components x num_of_components\n\n% Process optional arguments\npnames = {'z0' 'h0' 'bUpdateH' 'maxiter' 'TolFun' 'bUpdateZ' 'verbose'};\n\n% Do SVD initialisation of the init components\n\n[z0, h0] = NNDSVD(abs(X), k, 0);\n\ndflts  = {z0, h0, 1, 300,  1e-5, 1, 1};\n\n[Z, H, bUpdateH, max_iter, tolfun, bUpdateZ, verbose] = ...\n        internal.stats.parseArgs(pnames,dflts,varargin{:});\n\nif exist(path, 'file') ~= 0\n    load(path);\n    return;\nend\n    \nfor i = 1:max_iter\n    \n    if bUpdateZ\n        Z = X * pinv(H);\n    end\n    \n    A = Z' * X;\n    Ap = (abs(A)+A)./2;\n    An = (abs(A)-A)./2;\n    \n    B = Z' * Z;\n    Bp = (abs(B)+B)./2;\n    Bn = (abs(B)-B)./2;\n    \n    if bUpdateH\n        H = H .* sqrt((Ap + Bn * H) ./ (An + Bp * H + eps));\n    end\n      \n    if mod(i, 10) == 0 || mod(i+1, 10) == 0 \n        \n        s = X - Z * H;\n        dnorm = sqrt(sum(s(:).^2));\n        % dnorm = norm(gX - Z * H, 'fro');\n        \n        if mod(i+1, 10) == 0\n            dnorm0 = dnorm;\n            continue\n        end\n\n        if mod(i, 100) == 0 && verbose\n            display(sprintf('...Semi-NMF iteration #%d out of %d, error: %f\\n', i, max_iter, dnorm));\n        end\n\n        if 1 && exist('dnorm0')\n            assert(dnorm <= dnorm0, sprintf('Rec. error increasing! From %f to %f. (%d)', dnorm0, dnorm, k));\n        end\n\n        % Check for convergence\n        if exist('dnorm0') && dnorm0-dnorm <= tolfun*max(1,dnorm0)\n            if verbose\n                display(sprintf('Stopped at %d: dnorm: %f, dnorm0: %f', i, dnorm, dnorm0));\n            end\n            break;\n        end\n     \n    end\nend\n", "meta": {"author": "jwyang", "repo": "JULE.torch", "sha": "69bdfd82f9dfd431619a8ee25ac832da76a827e2", "save_path": "github-repos/MATLAB/jwyang-JULE.torch", "path": "github-repos/MATLAB/jwyang-JULE.torch/JULE.torch-69bdfd82f9dfd431619a8ee25ac832da76a827e2/matlab/approaches/nmf-deep/seminmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.59352060178924}}
{"text": "function [VCV,A,B,scores,hess,gross_scores]=robustvcv(fun,theta,nw,varargin)\n% Compute Robust Variance Covariance matrix numerically, including\n% Newey-West style score covariance using 2-sided derivatives\n%\n% USAGE:\n%     [VCV,A,B,SCORES,HESS,GROSS_SCORES]=robustvcv(FUN,THETA,NW,VARARGIN)\n%\n% INPUTS:\n%     FUN           - Function name ('fun') or function handle (@fun) which will\n%                       return the sum of the log-likelihood (scalar) as the 1st output and the individual\n%                       log likelihoods (T by 1 vector) as the second output.\n%     THETA         - Parameter estimates at the optimum, usually from fmin*\n%     NW            - Number of lags to consider in Newey-West covariance.\n%                       Normally set to 0\n%     VARARGIN      - Other inputs to the log-likelihood function, such as data\n%\n% OUTPUTS:\n%     VCV           - Estimated robust covariance matrix (see White 1994)\n%     A             - A portion of robust covariance\n%     B             - B portion of robust covariance\n%     SCORES        - T x num_parameters matrix of scores\n%     HESS          - Estimated Hessian (Expectation of second derivative)\n%     GROSS_SCORES  - Numerical scores (1 by num_parameters) of the objective function, usually for diagnostics\n%\n% COMMENTS:\n%     This function simplifies calculating sandwich covariance estimators for (Q)MLE estimation\n\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 9/1/2005\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Argument Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif size(theta,1)<size(theta,2)\n    theta=theta';\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Argument Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nk=length(theta);\nh=max(abs(theta*eps^(1/3)),1e-8);\nh=diag(h);\n\n[~,like]=feval(fun,theta,varargin{:});\n\nt=length(like);\n\nLLFp=zeros(k,1);\nLLFm=zeros(k,1);\nlikep=zeros(t,k);\nlikem=zeros(t,k);\nfor i=1:k\n    thetaph=theta+h(:,i);\n    [LLFp(i),likep(:,i)]=feval(fun,thetaph,varargin{:});\n    thetamh=theta-h(:,i);\n    [LLFm(i),likem(:,i)]=feval(fun,thetamh,varargin{:});\nend\n\nscores=zeros(t,k);\ngross_scores=zeros(k,1);\nh=diag(h);\nfor i=1:k\n    scores(:,i)=(likep(:,i)-likem(:,i))./(2*h(i));\n    gross_scores(i)=(LLFp(i)-LLFm(i))./(2*h(i));\nend\n\nhess=hessian_2sided(fun,theta,varargin{:});\nA=hess/t;\nhess=A;\nAinv=A^(-1);\nif nw==0\n    % VCV=A^(-1)*B*A^(-1)/t;\n    B=cov(scores);\n    VCV=(Ainv*B*Ainv)/t;\nelse\n    B=covnw(scores,nw);\n    VCV=(Ainv*B*Ainv)/t;\nend", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/utility/robustvcv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5935205958928333}}
{"text": "function out = NL_TSTL_ReturnTime(y,NNR,maxT,past,Nref,embedParams)\n% NL_TSTL_ReturnTime    Analysis of the histogram of return times.\n%\n% Return times are the time taken for the time series to return to a similar\n% location in phase space for a given reference point.\n%\n% Strong peaks in the histogram are indicative of periodicities in the data.\n%\n%---INPUTS:\n%\n% y, scalar time series as a column vector\n% NNR, number of nearest neighbours\n% maxT, maximum return time to consider\n% past, Theiler window\n% Nref, number of reference indicies\n% embedParams, to feed into BF_Embed\n%\n%---OUTPUTS: include basic measures from the histogram, including the occurrence of\n% peaks, spread, proportion of zeros, and the distributional entropy.\n%\n% Uses the code, return_time, from TSTOOL.\n% TSTOOL: http://www.physik3.gwdg.de/tstool/\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,\n% <http://www.benfulcher.com>\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 <http://www.gnu.org/licenses/>.\n% ------------------------------------------------------------------------------\n\n% ------------------------------------------------------------------------------\n%% Check Inputs\n% ------------------------------------------------------------------------------\nN = length(y); % length of the input time series\n\n% Number of nearest neighbours, NNR\nif nargin < 2 || isempty(NNR)\n    NNR = 5;\nend\nif (NNR > 0) && (NNR < 1) % specify a proportion of time series length\n    NNR = floor(NNR*N); if NNR == 0, NNR = 1; end\nend\n\n% Maximum return time, maxT\nif nargin < 3 || isempty(maxT)\n    maxT = 0.1;\nend\nif (maxT > 0) && (maxT <= 1) % specify a proportion\n    maxT = floor(N*maxT);\n    if maxT == 0, maxT = 1; end\nend\n\n% Theiler window, past\nif nargin < 4 || isempty(past)\n    past = 10;\nend\nif (past > 0) && (past < 1) % specify a proportion\n    past = floor(N*past);\n    if past == 0, past = 1; end % round up from 0\nend\n\n% Number of reference points\nif nargin < 5 || isempty(Nref)\n    Nref = -1; % use all available points\nend\n\n% embed parameters\nif nargin < 6 || isempty(embedParams)\n    embedParams = {'ac','fnnmar'};\n    fprintf(1,'Using default embedding using autocorrelation and cao\\n');\nend\n\ndoPlot = false; % plot outputs to figures\n\n% ------------------------------------------------------------------------------\n%% Embed the signal\n% ------------------------------------------------------------------------------\ns = BF_Embed(y,embedParams{1},embedParams{2},1,true);\nif ~isa(s,'signal') && isnan(s); % embedding failed\n    warning('Embedding failed');\n    out = NaN; return\nend\nnumPoints = size(data(s),1);\nif numPoints < 10\n    % Set heuristic minimum (10) on the number of points needed to perform a meaningful analysis\n    warning('Time series not long enough for return time analysis')\n    out = NaN; return\nend\n\n% ------------------------------------------------------------------------------\n%% Run the code\n% ------------------------------------------------------------------------------\ntry\n    rs = return_time(s, NNR, maxT, past, Nref);\ncatch emsg\n    if strcmp(emsg.message,'Index exceeds matrix dimensions.')\n        fprintf(1,'Error evaluating return_time\\n');\n        out = NaN; return\n    else\n        error(emsg.message);\n    end\nend\n\nTrett = data(rs);\nNN = length(Trett);\n\n% ------------------------------------------------------------------------------\n%% Quantify structure in output\n% ------------------------------------------------------------------------------\nout.max = max(Trett);\nout.std = std(Trett);\nout.pzeros = sum(Trett == 0)/NN;\nout.pg05 = sum(Trett>max(Trett)*0.5)/NN;\nout.iqr = iqr(Trett);\n\n% recurrent peaks:\nicross05 = find((Trett(1:end-1)-0.5*max(Trett)).*(Trett(2:end)-0.5*max(Trett)) < 0);\nif ~isempty(icross05) && length(icross05) > 2\n    difficross05 = diff(icross05);\n    difficross05 = difficross05(difficross05 > 0.4*max(difficross05)); % remove small entries, crossing peaks\n\n    out.meanpeaksep = mean(difficross05)/NN;\n    out.maxpeaksep = max(difficross05)/NN;\n    out.minpeaksep = min(difficross05)/NN;\n    out.rangepeaksep = range(difficross05)/NN;\n    out.stdpeaksep = std(difficross05)/sqrt(NN);\nelse\n    out.meanpeaksep = NaN;\n    out.maxpeaksep = NaN;\n    out.minpeaksep = NaN;\n    out.rangepeaksep = NaN;\n    out.stdpeaksep = NaN;\nend\n\nout.statrtys = std(Trett(1:floor(end/2)))/std(Trett(floor(end/2)+1:end));\nout.statrtym = mean(Trett(1:floor(end/2)))/mean(Trett(floor(end/2)+1:end));\n\nout.hhist = -sum(Trett(Trett>0).*log(Trett(Trett>0)));\n\n% ------------------------------------------------------------------------------\n%% Coarse-grain to 20 bins\n% ------------------------------------------------------------------------------\nnumBins = 20;\ncglav = zeros(numBins,1);\ninds = round(linspace(0,NN,numBins+1));\nfor i = 1:numBins\n    cglav(i) = sum(Trett(inds(i)+1:inds(i+1)));\nend\nif doPlot\n    figure('color','w');\n    box('on');\n    plot(cglav,'k')\nend\nout.hcgdist = -sum(cglav(cglav > 0).*log(cglav(cglav > 0)));\nout.rangecgdist = range(cglav);\nout.pzeroscgdist = sum(cglav == 0)/numBins;\n\n% ------------------------------------------------------------------------------\n%% Get distribution of distribution of return times\n% ------------------------------------------------------------------------------\n[nhist, binEdges] = histcounts(Trett,'BinMethod','sqrt','Normalization','probability');\nif doPlot\n    binCenters = mean([binEdges(1:end-1); binEdges(2:end)]);\n    figure('color','w');\n    plot(binCenters,nhist,'o-k')\nend\nout.maxhisthist = max(nhist);\nout.phisthistmin = nhist(1); % this is the same as maxhisthist\nout.hhisthist = -sum(nhist(nhist > 0).*log(nhist(nhist > 0)));\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/NL_TSTL_ReturnTime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5935205958928333}}
{"text": "function pole_cplx = cplxpole(zta,wn,w,flag)\n%\n% Utility function: CPLXPOLE\n%\n% The purpose of this function is to compute the magnitude response of a\n% complex pole or zero.\n\n% Author: Craig Borghesani\n% Date: 8/8/94\n% Revised:\n% Copyright (c) 1999, Prentice-Hall\n\nif length(flag)==1,\n s = sqrt(-1)*w(:)';\n ht = s.^2 + 2*zta*wn*s + wn^2;\nelse\n T = flag(2);\n z = exp(sqrt(-1)*w(:)'*T);\n a = zta*wn; b = wn*sqrt(1-zta^2);\n ht = z - 2*exp(-a*T)*cos(b*T) + exp(-2*a*T)./z;\nend\nzero=find(abs(ht)==0);\nif length(zero), ht(zero)=ones(1,length(zero))*eps; end\npole_cplx = ht.^flag(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/38866-controls-tutor/contutor5/cplxpole.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5935205798161842}}
{"text": "%data   :3*length increment type equally spaced sensor output.\n%alg    :Type of the coning algorithm to be used   \nfunction [inc corr]=coning_minor(data, alg)\ninlen=size(data,2);\nswitch (alg)\n    case(0)\n        %ignagni(1990):Algorithm A (no correction - constant approximation)     \n        inc=data;\n        corr=zeros(size(data));\n    case(1)\n        %ignagni(1990):Algorithm D (quadratic approximation to 3 points)    \n        outlen=floor((inlen-3)/3)+1;\n        inc=zeros(3,outlen);\n        corr=zeros(3,outlen);\n        \n        ind=1;\n        for i=3:3:inlen\n            inc(:,ind)=sum(data(:,i-2:i),2);\n            corr(:,ind)=(33/80)*cross(data(:,i-2), data(:,i))+(57/80)*cross(data(:,i-1),data(:,i)-data(:,i-2));\n            ind=ind+1;\n        end\n    case(2)\n        %ignagni(1990):Algorithm E\n        outlen=floor((inlen-3)/3)+1;\n        inc=zeros(3,outlen);\n        corr=zeros(3,outlen);\n        \n        ind=1;\n        for i=3:3:inlen\n            inc(:,ind)=sum(data(:,i-2:i),2);\n            corr(:,ind)=(9/20)*cross(data(:,i-2), data(:,i))+(27/40)*cross(data(:,i-1),data(:,i)-data(:,i-2));\n            ind=ind+1;\n        end\n    case(3)\n        %ignagni(1996):Algorithm 1\n        outlen=floor((inlen-4)/2)+1;\n        inc=zeros(3,outlen);\n        corr=zeros(3,outlen);\n        \n        ind=1;\n        for i=4:2:inlen\n            vr_a=sum(data(:,i-1:i),2);\n            vr_b=sum(data(:,i-3:i-2),2);\n            inc(:,ind)=var_a;\n            corr(:,ind)=(32/45)*cross(data(:,i-1), data(:,i))+(-1/180)*cross(vr_b,vr_a);\n            ind=ind+1;\n        end\n    case(4)\n        %ignagni(1996):Algorithm 2\n        outlen=floor((inlen-3)/2)+1;\n        inc=zeros(3,outlen);\n        corr=zeros(3,outlen);\n\n        ind=1;\n        for i=3:2:inlen\n            inc(:,ind)=sum(data(:,i-1:i),2);\n            corr(:,ind)=cross(((-1/30)*data(:,i-2)+(11/15)*data(:,i-1)), data(:,i));\n            ind=ind+1;\n        end\n    case (5)\n        %ignagni(1996):Algorithm 3 - Ignagni (1990):Algorithm F\n        outlen=floor((inlen-3)/3)+1;\n        inc=zeros(3,outlen);\n        corr=zeros(3,outlen);\n\n        ind=1;\n        for i=3:3:inlen\n            inc(:,ind)=sum(data(:,i-2:i),2);\n            corr(:,ind)=cross(((9/20)*data(:,i-2)+(27/20)*data(:,i-1)), data(:,i));\n            ind=ind+1;\n        end\n    case (6)\n        %ignagni(1996):Algorithm 4\n        outlen=floor((inlen-6)/3)+1;\n        inc=zeros(3,outlen);\n        corr=zeros(3,outlen);\n\n        ind=1;\n        for i=6:3:inlen\n            vr_a=sum(data(:,i-2:i),2);\n            vr_b=sum(data(:,i-5:i-3),2);\n            inc(:,ind)=vr_a;\n            corr(:,ind)=cross(((243/560)*data(:,i-2)+(1539/1120)*data(:,i-1)), data(:,i))+(1/3360)*cross(vr_b,vr_a);\n            ind=ind+1;\n        end\n    case (7)\n        %ignagni(1996):Algorithm 5\n        outlen=floor((inlen-4)/3)+1;\n        inc=zeros(3,outlen);\n        corr=zeros(3,outlen);\n\n        ind=1;\n        for i=4:3:inlen\n            inc(:,ind)=sum(data(:,i-2:i),2);\n            corr(:,ind)=cross(((3/280)*data(:,i-3)+(57/140)*data(:,i-2)+(393/280)*data(:,i-1)), data(:,i));\n            ind=ind+1;\n        end\n    case (8)\n        %ignagni(1996):Algorithm 6\n        outlen=floor((inlen-5)/3)+1;\n        inc=zeros(3,outlen);\n        corr=zeros(3,outlen);\n\n        ind=1;\n        for i=5:3:inlen\n            inc(:,ind)=sum(data(:,i-2:i),2);\n            corr(:,ind)=cross(((-1/420)*data(:,i-4)+(1/40)*data(:,i-3)+(157/420)*data(:,i-2)+(1207/840)*data(:,i-1)), data(:,i));\n            ind=ind+1;\n        end   \n    case (9)\n        %ignagni(1996):Algorithm 7\n        outlen=floor((inlen-4)/4)+1;\n        inc=zeros(3,outlen);\n        corr=zeros(3,outlen);\n\n        ind=1;\n        for i=4:4:inlen\n            inc(:,ind)=sum(data(:,i-3:i),2);\n            corr(:,ind)=cross(((54/105)*data(:,i-3)+(92/105)*data(:,i-2)+(214/105)*data(:,i-1)), data(:,i));\n            ind=ind+1;\n        end\n    otherwise\n        disp('Undefined Algorithm (Perhaps, someone else adds it later)');\nend", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/conscull/coning_minor_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.593501333676524}}
{"text": "function smallpot = marginalize_pot(bigpot, keep, maximize, useC)\n% MARGINALIZE_POT Marginalize a mpot onto a smaller domain.\n% smallpot = marginalize_pot(bigpot, keep, maximize, useC)\n%\n% The maximize argument is ignored - maxing out a Gaussian is the same as summing it out,\n% since the mode and mean are equal.\n% The useC argument is ignored.\n\n\nnode_sizes = sparse(1, max(bigpot.domain));\nnode_sizes(bigpot.domain) = bigpot.sizes;\nsum_over = mysetdiff(bigpot.domain, keep);\n\n[logp, mu, Sigma] = marginalize_gaussian(bigpot.logp, bigpot.mu, bigpot.Sigma, ...\n\t\t\t\t\t keep, sum_over, node_sizes);\nsmallpot = mpot(keep, node_sizes(keep), logp, mu, Sigma);\n\n%%%%%%\n\nfunction [logpX, muX, SXX] = marginalize_gaussian(logp, mu, Sigma, X, Y, ns)\n% MARGINALIZE_GAUSSIAN Compute Pr(X) from Pr(X,Y) where X and Y are jointly Gaussian.\n% [logpX, muX, SXX] = marginalize_gaussian(logp, mu, Sigma, X, Y, ns)\n%\n% sizes(i) is the size of the i'th block in domain.\n \n[muX, muY, SXX, SXY, SYX, SYY] = partition_matrix_vec(mu, Sigma, X, Y, ns);\nlogpX = logp; % Lauritzen (1996) p161          \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/marginalize_pot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5934999958423841}}
{"text": "function out = convpower( in, uin, uout )\n%  CONVPOWER Convert from power units to desired power units.\n%   OUT = CONVPOWER( IN, UI, UO ) converts the input power IN (floating\n%   point array) from unit specified in UI (string) to unit specified in UO\n%   (string). If UO is not specified, IN is converted to the SI unit, which\n%   is Watts.\n%\n%   Allowable input/output strings (not case sensitive):\n%      'hp'          :horsepower     \n%      'W'           :watt\n%      'kW'          :kilowatt\n%      'lbf-ft/s'    :pound-feet/second (also 'lb-ft/s' or 'ft-lb/s')\n%\n%   Example:\n%\n%   Convert a matrix of power values from lbf-ft/s to hp:\n%       hp = convpower([2 3; 4 5], 'lbf-ft/s', 'hp')\n%\n%   See also in aerospace toolbox CONVACC, CONVANG, CONVANGACC, CONVANGVEL,\n%   CONVDENSITY, CONVFORCE, CONVLENGTH, CONVMASS, CONVPRES, CONVTEMP,\n%   CONVVEL.\n\n%   Author: Sky Sartorius\n%   http://www.mathworks.com/matlabcentral/fileexchange/authors/101715\n\nif ~isfloat( in )\n    error('Input is not floating point');\nend\nif nargin < 3\n    uout = 'w';\nend\nuin = lower(uin);\nuout = lower(uout);\n%conversion to watts\nif strcmp('hp',uin)\n    slope = 745.6998716; %W/hp\nelseif strcmp('kw',uin)\n    slope = 1000; %W/kW\nelseif strcmp('lbf-ft/s',uin) || strcmp('lb-ft/s',uin) || strcmp('ft-lb/s',uout)\n    slope = 1.355817948363637; %lb-ft/s/W\nelseif strcmp('w',uin)\n    slope = 1;\nelse\n    error('invalid input unit string')\nend\n\n%conversion from watts\nif strcmp('hp',uout)\n    slope = slope/745.6998716; %W/hp\nelseif strcmp('kw',uout)\n    slope = slope/1000; %W/kW\nelseif strcmp('lbf-ft/s',uout) || strcmp('lb-ft/s',uout) || strcmp('ft-lb/s',uout)\n    slope = slope/1.355817948363637; %lb-ft/s/W\nelseif strcmp('w',uout)\n%     slope = slope/1;\nelse\n    error('invalid output unit string')\nend\n\nout = in.*slope;", "meta": {"author": "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/utilities/convpower.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5934999879036861}}
{"text": "function [Lnew,Q] = bst_remove_silent(L)\n% bst_remove_silent: removes silent component of single sphere head model.\n%\n% USAGE:  [Lnew,Q]=bst_remove_silent(L)\n%\n% DESCRIPTION:\n%     Removes silent component of single sphere head model.\n%\n% INPUTS:\n%     - L : Forward field matrix for all the channels\n%\n% OUTPUTS:\n%     - Lnew : New forward field matrix for all the channels containg 2/3\n%     the number of dipole components. The radial dipole components have\n%     been removed, and only the gain vectors produced by the two\n%     tangential dipole components are included.\n%     - Q: A matrix containg the orientations of the two tangential dipole\n%     components per source point.\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% Copyright (C) 2010 - Rey Rene Ramirez\n% Authors:  Rey Rene Ramirez, Ph.D.   e-mail: rrramirez at mcw.edu\n\nszL = size(L);\nL = reshape(L,[szL(1) 3 szL(2)/3]);\nLnew = zeros(szL(1),szL(2)*(2/3));\nsp = 0;\nfor spoint = 1:2:szL(2)*(2/3)\n    sp = sp+1;\n    [uL,sL,vL] = svd(L(:,:,sp),'econ');\n    Lnew(:,spoint:spoint+1) = uL(:,1:2)*sL(1:2,1:2);\n    Q(:,spoint:spoint+1) = vL(:,1:2);\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/inverse/private/bst_remove_silent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5934999823488611}}
{"text": "function[]=makefigs_slidetrans\n%MAKEFIGS_SLIDETRANS  Makes a sample figure for SLIDETRANS.\n\nfigure\nM=3000;\nt=(0:M-1)';\nN=500;\nw=hermfun((-N:N)'./(N/4),0);\nw=w./sqrt(w'*w);\nfs=2*pi*(1:30)./1000;\nclear x\nx(1:M/2,1)=sin(2*pi*t(1:M/2)./70/3);\nx(M/2:M,1)=sin(2*pi*t(M/2:M)./70);\ny=slidetrans(x,w,fs,'zeros');\nh=wavespecplot(t,x,1./fs,abs(y),1/2);\nhlines(70*3/2/pi),hlines(70/2/pi)", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jfigures/makefigs_slidetrans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5934999775811151}}
{"text": "function [B,E,S,info] = DECOLOR(D,opt)\n% DEteting Contiguous Outliers in the LOw-rank Representation\n% http://arxiv.org/PS_cache/arxiv/pdf/1109/1109.0882v1.pdf\n% eexwzhou@ust.hk \n% Syntex: [B,S] = DECOLOR(D); or [B,S] = DECOLOR(D,opt);\n% Input:\n%   D -- 2D matrix\n%   opt -- options. Usually, default setting is good. No need to specify.\n%   opt.K: desired rank of the estimated low-rank component. \n%          Default: \\sqrt(min(size(D))) is good generally.\n%   opt.lambda: a constant controls the strength of smoothness regularize\n%               lambda ~ [1 5] is recommended. Default: 1\n%   opt.sigma: STD of noise in the image. If not specified, computed online\n%   opt.tol: convergence precision. Default: 1e-4\n% Output:\n%   B -- Low-rank component\n%   S -- Outlier support\n%   info -- other information\n\ndisp('^_^^_^^_^^_^^_^^_^ DECOLOR ^_^^_^^_^^_^^_^');\ntic;\n\n%% default parameter setting\nif ~exist('opt','var'); opt = []; end\nif ~isfield(opt,'tol'); opt.tol = 1e-4; end\nif ~isfield(opt,'K'); opt.K = floor(sqrt(min(size(D)))); end\nif ~isfield(opt,'lambda'); opt.lambda = 1; end % gamma = opt.lambda * beta;\nif ~isfield(opt,'sigma'); opt.sigma = []; end % sigma can be estimated online\n\n%% variable initialize\nD = double(D);\nB = D; % the low-rank matrix\nS = false(size(D)); % background support\nalpha = []; % Default setting by soft-impute\nbeta = 0.5*(std(D(:)))^2; % Start from a big value\nminbeta = 0.5*(3*std(D(:))/20)^2; % lower bound: suppose SNR <= 20\nsigma = opt.sigma; % if empty, will be estimated online\ncard = sum(S(:)); % record mumber of outliers\nminCard = numel(D)/1e4; % minimum number of outliers\nmaxOuterIts = 50; % max number of iteration\n\n% graph cuts initialization\n% GCO toolbox is called\nif opt.lambda > 0\n    hMRF = GCO_Create(numel(D),2);\n    GCO_SetSmoothCost( hMRF, [0 1;1 0] );\n    AdjMatrix = getAdj(size(D));\n    amplify = 10 * opt.lambda;\n    GCO_SetNeighbors( hMRF, amplify * AdjMatrix );\nend\n\n%% outer loop\nenergy_old = inf; % total energy\nfor outerIts = 1:maxOuterIts\n    disp(['---------------- Outer Loop:  ' num2str(outerIts) ' ----------------']);\n       \n    %% update B\n    disp('*** Estimate Low-rank Matrix *** ');\n    [B,Bnorm,alpha] = softImpute(D,B,~S,alpha,opt.K);\n    E = D - B;\n    \n    %% estimate sigma \n    if isempty(opt.sigma)\n        sigma_old = sigma;\n        sigma = std(E(~S(:)));\n        if abs(sigma_old-sigma)/abs(sigma_old) < 0.01\n            sigma = sigma_old; % if the change is not too large\n        end\n    end\n    % update beta\n    if card < minCard\n        beta = beta/2;\n    else\n        beta = min(max([beta/2,0.5*(3*sigma)^2 minbeta]),beta);\n    end\n    gamma = opt.lambda * beta;\n    \n    %% estimate S\n    disp('*** Estimate Outlier Support *** ');\n    disp(['$$$ beta = ' num2str(beta) '; gamma = ' num2str(gamma) '; sigma = ' num2str(sigma)]);\n    if opt.lambda > 0\n        % call GCO to run graph cuts\n        GCO_SetDataCost( hMRF, (amplify/gamma)*[ 0.5*(E(:)).^2, ones(numel(E),1)*beta]' );\n        GCO_Expansion(hMRF);\n        S = reshape(GCO_GetLabeling(hMRF)==2,size(S));\n        card = sum(S(:)==1);\n        energy_cut = (gamma/amplify)*double(GCO_ComputeEnergy(hMRF));\n    else\n        % direct hard thresholding if no smoothness\n        S = 0.5*E.^2 > beta;\n        card = sum(S(:));\n        energy_cut = 0.5*norm(D-B-E,2)^2 + beta*card;\n    end\n    \n    %% display energy\n    energy = energy_cut + alpha * Bnorm;\n    disp(['>>> the number of outliers is ' num2str(card)]);\n    disp(['>>> the objectvive energy is ' num2str(energy)]);\n    \n    %% check termination condition\n    if card > 0 && abs(energy_old-energy)/energy < opt.tol; break; end\n    energy_old = energy;\n    \nend\n\ninfo.opt = opt;\ninfo.time = toc;\ninfo.outerIts = outerIts;\ninfo.energy = energy;\ninfo.rank = rank(B);\ninfo.alpha = alpha;\ninfo.beta = beta;\ninfo.sigma = sigma;\n\nif opt.lambda > 0\n    GCO_Delete(hMRF);\nend\n\nend\n\n\n\n%% function to get the adjcent matirx of the graph\nfunction W = getAdj(sizeData)\nnumSites = prod(sizeData);\nid1 = [1:numSites, 1:numSites, 1:numSites];\nid2 = [ 1+1:numSites+1,...\n        1+sizeData(1):numSites+sizeData(1),...\n        1+sizeData(1)*sizeData(2):numSites+sizeData(1)*sizeData(2)];\nvalue = ones(1,3*numSites);\nW = sparse(id1,id2,value);\nW = W(1:numSites,1:numSites);\nend\n\n\n\n%% function for soft-impute\nfunction [Z,Znorm,alpha] = softImpute(X,Z,Omega,alpha0,maxRank)\n%\n% This program implements the soft-impute algorithm followed by\n% postprocessing in the Matrix completion paper Mazumder'10 IJML\n% min || Z - X ||_Omega + \\alpha || Z ||_Nulear\n% \\alpha is decrease from alpha0 to the minima value that makes rank(Z) <= maxRank\n\n% X is the incomplete matrix\n% maxRank is the desired rank in the constraint\n% Omega is the mask with value 1 for data and 0 for missing part\nif isempty(Z)\n    Z = X;\nend\nif isempty(Omega)\n    Omega = true(size(X));\nend\nif isempty(alpha0)\n    [dummy,D] = svd(X,'econ'); \n    alpha0 = D(2,2);\nend\nif isempty(maxRank)\n    maxRank = -1;\nend\n% parameters\neta = 0.707;\nepsilon = 1e-4;\nmaxInnerIts = 20;\n%% trivial\n% no rank constraint\nif maxRank >= min(size(X))\n    Z = X;\n    [dummy,D] = svd(Z,'econ');\n    Znorm = sum(diag(D));\n    alpha = 0;\n    return;\nend\n% no observation\nif sum(Omega(:)) == 0\n    % no data\n    Z = zeros(size(X));\n    Znorm = 0;\n    alpha = alpha0;\n    return;\nend\n%% soft-impute\n% 1. initialize\noutIts = 0;\nalpha = alpha0;\n% 2. Do for alpha = alpha0 > alpha_1 > alpha_2 > ... > alpha_maxRank\ndisp('begin soft-impute iterations');\nwhile 1\n    outIts = outIts + 1;\n    energy = inf;\n    for innerIts = 1:maxInnerIts\n        % (a)i\n        C = X.*Omega + Z.*(1-Omega);\n        [U,D,V] = svd(C,'econ');\n        VT = V';\n        % soft impute\n        d = diag(D);\n        idx = find(d > alpha);\n        Z = U(:,idx) * diag( d(idx) - alpha ) * VT(idx,:);\n        % (a)ii\n        Znorm = sum(d(idx)-alpha);\n        energy_old = energy;\n        energy = alpha*Znorm + norm(Z(Omega(:))-X(Omega(:)),'fro')/2;\n        if abs(energy - energy_old) / energy_old < epsilon\n            break\n        end\n    end\n    % check termination condition of alpha\n    k = length(idx); % rank of Z\n    disp(['alpha = ' num2str(alpha) ';    rank = ' num2str(k) ';  number of iteration: ' num2str(innerIts)]);\n    if k <= maxRank && alpha > 1e-3\n        alpha = alpha*eta;\n    else\n        break;      \n    end    \nend\nend\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/DECOLOR/DECOLOR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5934999767940362}}
{"text": "function timewindow = get_timewindow(utdnum_stop, numMins, utdnum_start) \n% GET_TIMEWINDOW\n%\n% Usage:  timewindow = get_timewindow([utdnum, [numMins, [utdnum_start]]])\n%\n% get_timewindow returns the Matlab datenumbers corresponding to the start and end of a time window\n% This time window is aligned such that if the numMins of data requested is 10, the start and end times\n% are aligned at 0, 10, 20, 30, 40 or 50 minutes past the hour, in such a way that the end time is the\n% most recent value that does not exceed dnum.\n%\n% If numMins is not given, it is set to 10.\n%\n% Example 1:\n% \t[timewindow.start,timewindow.stop]=gettartAndEndTimes(datenum(2007,04,23,17,13,13), 15)\n%\t\n%\tIn this case timewindow.start would be datenum(2007,04,23,16,45,00)\n%\tand timewindow.stop would be datenum(2007,04,23,17,00,00)\n%\n% Example 2:\n% \t[timewindow.start,timewindow.stop]=getStartAndEndTimes(datenum(2007,04,23,17,13,13), 10)\n%\t\n%\tIn this case timewindow.start would be datenum(2007,04,23,17,00,00)\n%\tand timewindow.stop would be datenum(2007,04,23,17,10,00)\n%\n% Glenn Thompson, 2007\n\nglobal PARAMS\n\n\nif nargin == 0\n\tutdnum_stop = utnow();\nend\n\nif nargin < 2\n\tnumMins = 10;\nend\n\n\nif nargin > 3\n\tdisp('get_timewindow([utdnum_stop [, numMins, [utdnum_start]]]')\n\treturn;\nend\n\ntimewindow.stop  = boundaryBeforeDnum(utdnum_stop, numMins);\ntimewindow.start = timewindow.stop - numMins/1440;\n\nif (nargin == 3)\n\tsnum = boundaryBeforeDnum(utdnum_start, numMins);\n\tsnum_array = snum: numMins/1440: timewindow.start;\n\tenum_array = snum_array + numMins/1440;\n\ttimewindow.start = snum_array;\n\ttimewindow.stop = enum_array;\nend\t\n\t\n\n%%%%%%%%%%%%%%%%%%%\nfunction dnum1=boundaryBeforeDnum(dnum, numMins)\ndayFraction\t\t=\trem(dnum,1); \nminutesIntoThisDay\t=\tdayFraction*1440;\ndnum1 \t\t\t= \tdnum - rem(minutesIntoThisDay, numMins)/1440;\n\nfunction dnum1=boundaryAfterDnum(dnum, numMins)\ndnum1 = boundaryBeforeDnum(dnum, numMins) + numMins/1440; \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/applications/+iceweb/get_timewindow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5934692343121704}}
{"text": "function determ = summation_determinant ( n )\n\n%*****************************************************************************80\n%\n%% SUMMATION_DETERMINANT returns the determinant of the SUMMATION 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 A.\n%\n%    Output, real DETERM, the determinant.\n%\n  determ = 1.0;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/summation_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.5934692326782011}}
{"text": "function [X, info] = IRmrnsd(A, b, varargin)\n%IRmrnsd Modified Residual Norm Steepest Descent method\n%\n% options  = IRmrnsd('defaults')\n% [X,info] = IRmrnsd(A,b)\n% [X,info] = IRmrnsd(A,b,K)\n% [X,info] = IRmrnsd(A,b,options)\n% [X,info] = IRmrnsd(A,b,K,options)\n%\n% This function implements the Modified Residual Norm Steepest Descent\n% method for computing a nonnegatiely constrained least squares solution.\n%\n% With 'defaults' as input returns the default options.  Otherwise outputs\n% the iterates specified in K, using max(K) as MaxIter, and using all other\n% default options.  With options as input: uses the user-specified options\n% and all the other default options.\n% \n% Inputs:\n%  A : either (a) a full or sparse matrix\n%             (b) a matrix object that performs the matrix*vector operation\n%             (c) user-defined function handle\n%  b : right-hand side vector\n%  K : (optional) integer vector that specifies which iterates are returned\n%      in X; the maximum number of iterations is assumed to be max(K)\n%      [ positive integer | vector of positive components ]\n%  options : structure with the following fields (optional)\n%      x0         - Initial guess for the iterations\n%                   [ array | {'none'} ]\n%      MaxIter    - maximum allowed number of cgls iterations\n%                   [ {100 } | positive integer ]\n%                   NOTE: K overrules MaxIter if both are assigned\n%      x_true     - true solution; allows us to returns error norms with\n%                   respect to x_true at each iteration\n%                   [ array | {'none'} ]\n%      NoiseLevel - norm of noise in rhs divided by norm of rhs \n%                   [ {'none'} | nonnegative scalar]\n%      eta        - safety factor for the discrepancy principle\n%                   [ {1.01} | scalar greater than (and close to) 1 ]\n%      NE_Rtol    - relative tolerance on the normal equation residual norm\n%                   [ {1e-12} | positive integer ]\n%      NoStop     - specifies whether the iterations should proceed\n%                   after a stopping criterion has been satisfied\n%                   [ 'on' | {'off'} ]\n%      IterBar    - shows the progress of the iterations\n%                   [ {'on'} | 'off' ]\n% Note: the options structure can be created using the function IRset.\n%\n% Outputs:\n%   X : computed solutions, stored column-wise (at the iterations listed in K)\n%   info: structure with the following fields:\n%      its      - number of the last computed iteration\n%      saved_iterations - iteration numbers of iterates stored in X \n%      StopFlag - string that describes the inner stopping condition:\n%                   * Residual tolerance satisfied (discrepancy principle)\n%                   * Normal equations residual tolerance satisfied\n%                   * Reached maximum number of iterations\n%      Rnrm     - relative residual norms at each iteration\n%      NE_Rnrm  - normal eqs relative residual norms at each iteration\n%      Xnrm     - solution norms at each iteration\n%      Enrm     - relative error norms (requires x_true) at each iteration\n%      StopReg  - struct containing information about the solution that\n%                 satisfies the stopping criterion.  Fields:\n%                   It   : iteration where the stopping criterion is satisfied\n%                   X    : solution satisfying the stopping criterion\n%                   Enrm : the corresponding relative error (requires x_true)\n%      BestReg  - struct containing information about the solution that\n%                 minimizes Enrm (requires x_true), with the fields:\n%                   It   : iteration where the minimum is attained\n%                   X    : best solution\n%                   Enrm : best relative error\n%\n% See also: IRconstr_ls, IRfista, IRnnfcgls, IRget, IRset\n\n% Silvia Gazzola, University of Bath\n% Per Christian Hansen, Technical University of Denmark\n% James G. Nagy, Emory University\n% April, 2018.\n\n% This file is part of the IR Tools package and is distributed under the \n% 3-Clause BSD License. A separate license file should be provided as part \n% of the package.\n\n% Set default values for options.\ndefaultopt = struct('x0','none', 'MaxIter',100, 'x_true','none', ...\n    'NoiseLevel','none', 'eta',1.01, 'NE_Rtol',1e-12, 'IterBar','on', ...\n    'NoStop', 'off');\n  \n% If input is 'defaults,' return the default options in X.\nif nargin==1 && nargout <= 1 && isequal(A,'defaults')\n    X = defaultopt;\n    return;\nend\n\ndefaultopt.verbosity = 'on';\n\n% Check for acceptable number of optional input arguments.\nswitch length(varargin)\n    case 0\n        K = []; options = [];\n    case 1\n        if isa(varargin{1}, 'double')\n            K = varargin{1}; options = [];\n        else\n            K = []; options = varargin{1};\n        end\n    case 2\n        if isa(varargin{1}, 'double')\n            K = varargin{1}; options = varargin{2};\n        else\n            K = varargin{2}; options = varargin{1};\n        end\n        if isfield(options, 'MaxIter') && ~isempty(options.MaxIter) && (~isempty(K) && options.MaxIter ~= max(K))\n            warning('The value of MaxIter is discarded; the maximum value in K is taken as MaxIter')\n        end\n    otherwise\n        error('Too many input parameters')\nend\n\nif isempty(options)\n    options = defaultopt;\nend\n\noptions = IRset(defaultopt, options);\n\nMaxIter    = IRget(options, 'MaxIter',    [], 'fast');\nx_true     = IRget(options, 'x_true',     [], 'fast');\nNoiseLevel = IRget(options, 'NoiseLevel', [], 'fast');\neta        = IRget(options, 'eta',        [], 'fast');\nNE_Rtol    = IRget(options, 'NE_Rtol',    [], 'fast');\nIterBar    = IRget(options, 'IterBar',    [], 'fast');\nNoStop     = IRget(options, 'NoStop',     [], 'fast');\nverbose    = IRget(options, 'verbosity',  [], 'fast');\n\nverbose = strcmp(verbose, 'on');\n\n% Setting K.\nif isempty(K)\n    K = MaxIter;\nend\n% Sorting the iterations (in case they are shuffled in input).\nK = K(:); K = sort(K,'ascend'); K = unique(K);\nif ~((isreal(K) && (all(K > 0)) && all(K == floor(K))))\n    error('K must be a vector of positive real integers')\nend\nif K(end) ~= MaxIter\n    MaxIter = K(end);  \nend\n\nStopIt = MaxIter;\n\nif isempty(NoiseLevel) || strcmp(NoiseLevel,'none')\n    Rtol = 0;\nelse\n    Rtol = eta*NoiseLevel;\nend\n\n% We need to find the number of columns in matrix A, but if A is not given \n% as a matrix, and no initial guess is given, then we can find it by \n% computing A'*b.  Since we need this anyway, it doesn't cost any \n% additional work.\ntrAb = Atransp_times_vec(A, b);\nn = length(trAb);\n\nnrmb = norm(b(:));\nnrmAtb = norm(trAb(:));\n\n% See if an initial guess is given.  If not, then use 0 as initial guess.  \nx = IRget(options, 'x0', [], 'fast');\n\nif strcmp(x,'none')\n    % the default initial guess for the iterations is defined as the\n    % minimizer of || b - A*(alpha*ones(n,1)) ||_2\n    coeffx0 = A_times_vec(A, ones(n,1)); alpha = (coeffx0'*b)/norm(coeffx0)^2;\n    if alpha <= 0\n        alpha = sqrt(eps);\n    end\n    x = alpha*ones(n,1);\nend\n\nif norm(x) == 0\n    error(['IRmrnsd cannot handle a zero initial guess. ',...\n    'Please consider assigning a different initial guess, or avoid specifying the initial guess in order to have a default value'])\nend\n\n% If initial guess has negative values, compensate.\nminx = min(x(:));\nif minx < 0\n     x = x - min(0,minx) + sqrt(eps);\nend\n\nnoIterBar = strcmp(IterBar,{'off'});\n\n% Declare matrices.\nX = zeros(n,length(K));\nXnrm    = zeros(MaxIter,1);\nRnrm    = zeros(MaxIter,1);\nNE_Rnrm = zeros(MaxIter,1);\nif strcmp(x_true,'none')\n    errornorms = false;\nelse\n    errornorms = true;\n    Enrm = zeros(MaxIter,1);\n    nrmtrue = norm(x_true(:));\n    BestReg.It = [];\n    BestReg.X = [];\n    BestReg.Enrm = [];\n    BestEnrm = 1e10;\n    BestReg.Xnrm = [];\n    BestReg.Rnrm = [];\n    BestReg.NE_Rnrm = [];\nend\n\nNoStop = strcmp(NoStop,'on');\nsaved_iterations = zeros(1, length(K));\n\n% Initializing some variables.\nr = b - A_times_vec(A,x);\ng = -Atransp_times_vec(A, r);\nxg = x .* g;\ngamma = g(:)' * xg(:);\n\nif ~noIterBar\n  h_wait = waitbar(0, 'Running iterations, please wait ...');\nend\n\nj = 0;\nfor k = 1:MaxIter\n    if ~noIterBar\n        waitbar(k/MaxIter, h_wait)\n    end\n  \n    s = - x .* g;\n\n    u = A_times_vec(A, s);\n  \n    theta = gamma / (u(:)'*u(:));\n    neg_ind = s < 0;\n  \n    alpha = min( theta, min( -x(neg_ind) ./ s(neg_ind) ) );\n    if isempty(alpha)\n        alpha = theta;\n    end\n  \n    x = x + alpha*s;\n    \n    r = r - alpha*u;\n    AlreadySaved = 0; \n    if any(K == k)\n        j = j+1;\n        X(:,j) = x;\n        saved_iterations(j) = k;\n        AlreadySaved = 1; \n    end\n    \n    z = Atransp_times_vec(A, u);\n\n    g = g + alpha*z;\n    xg = x .* g;\n    gamma = g(:)' * xg(:);\n\n    % Compute norms.\n    Xnrm(k)    = norm(x(:));\n    Rnrm(k)    = norm(r(:))/nrmb;\n    NE_Rnrm(k) = sqrt(gamma)/nrmAtb;\n    if errornorms\n        Enrm(k) = norm(x_true-x)/nrmtrue;\n        if Enrm(k)<BestEnrm\n            BestReg.It = k;\n            BestReg.X = x;\n            BestEnrm = Enrm(k);\n            BestReg.Enrm = BestEnrm;\n            BestReg.Xnrm = Xnrm(k);\n            BestReg.Rnrm = Rnrm(k);\n            BestReg.NE_Rnrm = NE_Rnrm(k);\n        end\n    end  \n    if (Rnrm(k) <= Rtol)  && (StopIt == MaxIter)\n        if verbose\n            disp('Residual tolerance satisfied')\n        end\n        StopFlag = 'Residual tolerance satisfied';\n        StopIt = k;\n        StopReg.It = k;\n        StopReg.X = x;\n        if errornorms, StopReg.Enrm = Enrm(k); end\n        if ~ NoStop\n            if ~AlreadySaved\n                j = j+1;\n                X(:,j) = x;\n                saved_iterations(j) = k;\n                AlreadySaved = 1;\n            end\n            Xnrm    = Xnrm(1:k);\n            Rnrm    = Rnrm(1:k);\n            NE_Rnrm = NE_Rnrm(1:k);\n            if errornorms, Enrm = Enrm(1:k); end\n            X = X(:,1:j);\n            saved_iterations = saved_iterations(1:j);\n            break\n        end\n    end\n    if NE_Rnrm(k) <= NE_Rtol\n        if verbose\n            disp('Normal equations residual tolerance satisfied')\n        end\n        StopFlag = 'Normal equations residual tolerance satisfied';\n        StopIt = k;\n        StopReg.It = k;\n        StopReg.X = x;\n        if errornorms, StopReg.Enrm = Enrm(k); end\n        if ~ NoStop\n            if ~AlreadySaved\n                j = j+1;\n                X(:,j) = x;\n                saved_iterations(j) = k;\n                AlreadySaved = 1;\n            end\n            Xnrm    = Xnrm(1:k);\n            Rnrm    = Rnrm(1:k);\n            NE_Rnrm = NE_Rnrm(1:k);\n            if errornorms, Enrm = Enrm(1:k); end\n            X = X(:,1:j);\n            saved_iterations = saved_iterations(1:j);\n            break\n        end \n    end\nend\nif k == MaxIter\n  if StopIt == MaxIter\n    % Stop because max number of iterations reached\n    if verbose\n        disp('Reached maximum number of iterations')\n    end\n    StopFlag = 'Reached maximum number of iterations';\n    StopReg.It = k;\n    StopReg.X = x;\n    if errornorms, StopReg.Enrm = Enrm(k); end\n    if ~AlreadySaved\n        j = j+1;\n        X(:,j) = x;\n        saved_iterations(j) = k;\n    end\n    Xnrm    = Xnrm(1:k);\n    Rnrm    = Rnrm(1:k);\n    NE_Rnrm = NE_Rnrm(1:k);\n    if errornorms, Enrm = Enrm(1:k); end\n    X = X(:,1:j);\n    saved_iterations = saved_iterations(1:j);\n  end \nend\nif ~noIterBar, close(h_wait), end\nif nargout==2\n  info.its = k;\n  info.saved_iterations = saved_iterations(1:j);\n  info.StopFlag = StopFlag;\n  info.StopReg = StopReg;\n  info.Rnrm = Rnrm(1:k);\n  info.NE_Rnrm = NE_Rnrm(1:k);\n  info.Xnrm = Xnrm(1:k);\n  if errornorms\n    info.Enrm = Enrm(1:k);\n    info.BestReg = BestReg;\n  end\nend", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/IRcodes/IRmrnsd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.5934558276029939}}
{"text": "clear;\nclc\nclose all;\naddpath('../../library/nav_lib');\n\n%% \u7528\u6237\u771f\u5b9e\u5750\u6807\u53ca\u63a5\u53d7\u673a\u949f\u5dee(m)\ntrue_user_states = [4245849, -2451342, 4113840, 1000000]';\n\n%% \u536b\u661f\u4f4d\u7f6e\nsat = zeros(3,5);\nsat(:,1) = [21630742.37 -7872946.37 13290000]';\nsat(:,2) = [9799722.428 -11678854.4 21773061.34]';\nsat(:,3) = [15014045.82 2647381.37 21773061.34]';\nsat(:,4) = [17020279.96 -20283979.8 2316599.642]';\nsat(:,5) = [26076581.77 4598004.93 2316599.642]';\npos = zeros(4,1);\ndp = 0;\n\n%% presduo range\npr = vecnorm(sat - true_user_states(1:3)) + true_user_states(4) ;\n[pos, dp, G] = ch_gpsls(pos, sat,  pr);\n\npos\ndp\n\n\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/study/Principles_of_GNSS_Inertial_and_Multi-Sensor_Integrated_Navigation_System_Second/example9_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5934541831391892}}
{"text": "function DEM_demo_Cornsweet\n% The Cornsweet effect: This demo illustrates the inference underlying the\n% Cornsweet effect or illusion. It exploits formal priors on the spatial\n% contiguity of the illuminant and reflectance; where the illuminant does not\n% have edges, but the reflectance can. This is implemented using a\n% discrete cosine set (DCT) as the spatial basis for the illuminant and a \n% (Haar) Discrete Wavelet transform (DWT) for the reflectance. Appropriate\n% shrinkage priors on the (implicit) transform coefficients ensure that the\n% explanation for visual input (reflectance times illuminant) assigns edges\n% to the reflectance; thereby producing the Cornsweet effect.\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: DEM_demo_Cornsweet.m 4851 2012-08-20 15:03:48Z karl $\n \n \n% Illustrate the Cornsweet effect\n%==========================================================================\nspm_figure('GetWin','Figure 1');\ncolormap((1:255)'*[1 1 1]/255)\n \n% basic profile\n%--------------------------------------------------------------------------\nnx    = 64;\nYX    = [zeros(1,nx*3/8) 1:(nx/8) -(nx/8):-1 zeros(1,nx*3/8)]*8/nx;\nYT    = ones(32,1);\n \n% present with different contrasts (C)\n%--------------------------------------------------------------------------\nC     = [1 4 32 64];\nnc    = length(C);\nfor i = 1:length(C)\n \n    subplot(nc,2,2*i - 1)\n    image(YT*YX*C(i) + 128)\n    title('Cornsweet effect','FontSize',16)\n    xlabel('eccentricity ','FontSize',12)\n    axis square\n \n    subplot(nc,2,2*i)\n    plot(YX*C(i))\n    title('Reflectance ','FontSize',16)\n    xlabel('eccentricity ','FontSize',12)\n    axis square, axis([1 nx -64 64]);\n    \nend\n \n \n% Simulations\n%==========================================================================\n \n \n% Basis functions of illuminant and reflectance\n%--------------------------------------------------------------------------\nnx      = 32;                               % number of pixels\nP.R     = spm_dwtmtx(nx,1,1);               % DWT for hidden causes\nP.I     = spm_dctmtx(nx,3);                 % DCT for hidden causes\nP.I     = P.I/diag(max(P.I));\nnr      = size(P.R,2);\nni      = size(P.I,2);\nW       = log2(nx./sum(P.R > 0))*4;         % scale of reflectance\nW(1)    = 16;\n \n \n% initial hidden states and causes\n%--------------------------------------------------------------------------\nx       = sparse(nr,1);\nv       = sparse(ni + nr,1);\nv(1)    = -1;\nii      = (1:ni);\nir      = (1:nr) + ni;\n \n% level 1\n%--------------------------------------------------------------------------\nM(1).f  = inline('(v(4:end) - x)/16','x','v','P');\nM(1).g  = inline('exp(P.R*x + P.I*v(1:3))','x','v','P');\nM(1).pE = P;                                % The prior expectation\nM(1).x  = x;                                % The prior expectation\nM(1).V  = exp(6);                           % error precision (data)\nM(1).W  = exp(10);                          % error precision (motion)\nM(1).xP = diag(exp(W));                     % error precision (motion)\n \n% level 2\n%--------------------------------------------------------------------------\nM(2).v  = v;                                % hidden causes \nM(2).V  = exp(0);                           % error precision (cause)\n \n% Create stimulus\n%==========================================================================\n \n% Create stimulus (with spatial and temporal envelopes YX and YT)\n%--------------------------------------------------------------------------\nM(1).E.n = 1;\nN        = 64;                             % length of sequence\nt        = ([1:N] - N/4)*8;                % time (ms)\nYX       = [zeros(1,nx*3/8) 1:(nx/8) -(nx/8):-1 zeros(1,nx*3/8)]*8/nx;\nYX       = YX'/4 + 1;\nYX       = exp(P.R*pinv(P.R)*log(YX));\nYT       = exp((tanh(([1:N] - N/3)/8) - 1)*4);\nYT       = exp(-([1:N] - N/2).^2/(2*(N/8)^2));\nY        = YX*YT;\n \n% invert\n%==========================================================================\nDEM.M    = M;\nDEM.Y    = Y;\nDEM      = spm_DEM(DEM);\n \n \n% render true and perceived stimuli\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 2'); clf\n \nsubplot(2,2,1)\nPI  = P.I*DEM.qU.v{2}(ii,:);\nimagesc(exp(PI))\ntitle('Perceived illunimant','FontSize',16)\nxlabel('time (bins)','FontSize',12)\nylabel('eccentricity ','FontSize',12)\naxis square\n \nsubplot(2,2,2)\nPR = P.R*DEM.qU.x{1};\nimagesc(exp(PR))\ntitle('Perceived reflectance','FontSize',16)\nxlabel('time (bins)','FontSize',12)\nylabel('eccentricity ','FontSize',12)\naxis square\n \nsubplot(2,2,3)\nimagesc(DEM.qU.v{1})\ntitle('Predicted stimulus','FontSize',16)\nxlabel('time (bins)','FontSize',12)\nylabel('eccentricity ','FontSize',12)\naxis square\n \n \n% first order effect: (R1) - Cornsweet\n%--------------------------------------------------------------------------\nC     = sparse(1,nx);\ni     = nx/2 - nx/4 - 1;\nC(i)  =  1;\ni     = nx/2 + nx/4 + 2;\nC(i)  = -1;\nR1    = C*P.R;\n \n% second order effect: (R2) - Mach bands\n%--------------------------------------------------------------------------\ni     = nx/2 - nx/8 - 1;\nC(i)  = -1;\ni     = nx/2 + nx/8 + 2;\nC(i)  =  1;\nR2    = C*P.R;\n \nD1    = R1*DEM.qU.x{1};\nD2    = R2*DEM.qU.x{1};\nfor i = 1:N\n    V1(i) = R1*DEM.qU.S{i}*R1';\n    V2(i) = R2*DEM.qU.S{i}*R2';\nend\n \n \nsubplot(2,2,4)\nspm_plot_ci(D1,V1,t), hold on\nspm_plot_ci(D2,V2,t), hold off\ntitle('Perceived reflectance','FontSize',16)\nxlabel('time (ms)','FontSize',12)\nylabel('eccentricity ','FontSize',12)\naxis square\nspm_axis tight\ndrawnow\n \n \n% Cycle over different levels of visual precision (cf contrast)\n%==========================================================================\nC   = -2:2:12;\nfor i = 1:length(C)\n    \n    % Change precision (contrast) and invert\n    %----------------------------------------------------------------------\n    SIM{i}        = DEM;\n    SIM{i}.M(1).V = exp(C(i));\n    SIM{i}        = spm_DEM(SIM{i});\n \n    % Record conditional peripheral reflectance difference\n    %----------------------------------------------------------------------\n    d1(i) = R1*SIM{i}.qU.x{1}(:,N/2);\n    v1(i) = R1*SIM{i}.qU.S{N/2}*R1';\n    d2(i) = R2*SIM{i}.qU.x{1}(:,N/2);\n    v2(i) = R2*SIM{i}.qU.S{N/2}*R2';\n \nend\n \n\n \n% show Cornsweet effect as a function of precision (contrast)\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 3'); clf\n \nsubplot(3,1,1)\nspm_plot_ci(d1,v1,C),                hold on\nplot(C,d1,'ob',C,C*0,'LineWidth',2), hold off\ntitle('Conditional difference (Cornsweet)','FontSize',16)\nxlabel('log-precision (contrast)','FontSize',12)\nylabel('reflectance difference','FontSize',12)\nspm_axis tight square\n \nsubplot(3,1,2)\nspm_plot_ci(d2,v2,C),                hold on\nplot(C,d2,'or',C,C*0,'LineWidth',2), hold off\ntitle('Conditional difference (Mach Band)','FontSize',16)\nxlabel('log-precision (contrast)','FontSize',12)\nylabel('reflectance difference','FontSize',12)\nspm_axis tight square\n \n% and associated percepts\n%--------------------------------------------------------------------------\ncolormap([1:255]'*[1 1 1]/255)\nj     = [1 5 7];\nnj    = length(j);\nfor i = 1:nj\n   \n    % predictions\n    %----------------------------------------------------------------------\n    PR    = P.R*SIM{j(i)}.qU.x{1};\n    PR    = PR*256 + 128;\n    \n    subplot(3,nj,i + 2*nj)\n    image(PR)\n    ylabel('eccentricity','FontSize',12)\n    axis square\n \nend\n \n% and associated prediction errors (cf ERPs)\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 4'); clf\nas    = 0;\nax    = 0;\nav    = 0;\nfor i = 1:nj\n    \n    \n    % predictions and errors\n    %----------------------------------------------------------------------\n    Ev = SIM{j(i)}.qU.z{2}(ir,:);\n    Es = SIM{j(i)}.qU.z{1};\n    av = max(max(abs(Ev(:))),av);\n    as = max(max(abs(Es(:))),as);\n    \n    subplot(3,nj,i)\n    plot(t,Es,'r')\n    title('Error (sensory)','FontSize',14)\n    xlabel('time (ms)','FontSize',12)\n    ylabel('error (state)','FontSize',12)\n \n    subplot(3,nj,i + nj)\n    plot(t,Ev,'r')\n    title('Error (hidden states)','FontSize',14)\n    xlabel('time (ms)','FontSize',12)\n    ylabel('error (state)','FontSize',12)\n    \n \nend\n \n \n% adjust axes\n%--------------------------------------------------------------------------\nfor i = 1:nj\n    \n    subplot(3,nj,i)\n    axis square, axis([t(1) t(end) -as*1.2 as*1.2])\n    \n    subplot(3,nj,i + nj)\n    axis square, axis([t(1) t(end) -av*1.2 av*1.2])\n \nend\n \n \n% redraw inference for effect\n%--------------------------------------------------------------------------\nspm_figure('GetWin','DEM');\nspm_DEM_qU(SIM{7}.qU)\n\n \n% Fitting behavioural data\n%==========================================================================\ntry, load cornsweet_data, catch, return, end\n\n% save simulation results\n%--------------------------------------------------------------------------\nsim.Con    = C;               % simulated contrast\nsim.Ecs    = d1;              % conditional expectation of Cornsweet effect\nsim.Emb    = d2;              % conditional expectation of mach band effect\nsim.Vcs    = v1;              % conditional dispersion of Cornsweet effect\nsim.Vmb    = v2;              % conditional dispersion of mach band effect\n \n% add emprical contrasts that were used\n%--------------------------------------------------------------------------\nsim.Con_cs = cornsweet.cornsweet;\nsim.Con_mb = mach.machContrast;\nG.sim      = sim;     % place in model\n \n% empirical responses\n%--------------------------------------------------------------------------\nY          = struct;\nY.y{1}     = cornsweet.stepMatch(:);\nY.y{2}     = mach.pSeeMach(:);\nY.Q        = spm_Ce([length(Y.y{1}) length(Y.y{2})]); % error precisions\n \n \n% model parameters\n%--------------------------------------------------------------------------\nB.thresh = -2;                % log-contrast threshold for Mach band\nB.sig    = 1;                 % parameter of contrast function\nB.off    = 2;                 % parameter of contrast function\nB.con    = 1/32;              % scaling of reported contrast\nB.sen    = 4;                 % parameter of response probability\nnb       = length(spm_vec(B));\n \n \n% setup model of empirical responses\n%--------------------------------------------------------------------------\nG.IS = 'spm_cornsweet';       % function name f(P,M,U) - generative model\nG.pE = B;                     % prior expectation of model parameters\nG.pC = speye(nb,nb)/8;        % prior covariance  of model parameters\nG.hE = [16; 8];               % prior expectation of log-precisions\nG.hC = exp(-4);               % prior covariance of log-precisions\n \n \n% invert model of empirical responses and plot\n%--------------------------------------------------------------------------\nEp   = spm_nlsi_GN(G,[],Y);\nspm_cornsweet(Ep,G,Y);\n\n\n\n\nreturn\n\n% plot behavioural results alone.\n%--------------------------------------------------------------------------\nsubplot(2,2,1)\nSE   = cornsweet.error;\nerrorbar(cornsweet.cornsweet,cornsweet.stepMatch,SE/2)\nxlabel('empirical contrast','Fontsize',12)\nylabel('reported contrast','Fontsize',12)\ntitle('Cornsweet','Fontsize',16)\nset(gca,'XLim',[0 .15]);\naxis square\n\nsubplot(2,2,2)\nSE   = mach.error;\nerrorbar(mach.machContrast,mach.pSeeMach,SE/2)\nxlabel('empirical contrast','Fontsize',12)\nylabel('report probability','Fontsize',12)\ntitle('Mach Bands','Fontsize',16)\nset(gca,'XLim',[0 .15]);\naxis square\n \n% Ancillary code for producing figures:\n%==========================================================================\nspm_figure('GetWin','paper'); clf\n \nn = 128;\na = 4;\ni = tanh(([1:n] - n/2)/(n/8))/a;\nr = kron([1 -1],ones(1,n/2))/a;\ns = exp(i + r);\nc = zeros(1,n);\n \nsubplot(5,1,1), plot(i),     spm_axis tight, title('illuminant')\nsubplot(5,1,2), plot(r),     spm_axis tight, title('reflectant')\nsubplot(5,1,3), plot(s),     spm_axis tight, title('stimulus')\nsubplot(5,1,4), plot(i + r), spm_axis tight, title('reflectant')\nsubplot(5,1,5), plot(c),     spm_axis tight, title('illuminant')\n \n \n% Illustrate the generative model (for 1D)\n%==========================================================================\nspm_figure('GetWin','paper'); clf\n \nDEM      = spm_DEM_generate(M,64,P,{16 0},{16});\n \nsubplot(3,2,1)\nPI  = P.I*DEM.pU.v{2}(ii,:);\nimagesc(exp(PI))\ntitle('Illunimant','FontSize',16)\nxlabel('time (bins)','FontSize',12)\nylabel('location ','FontSize',12)\naxis square\n \nsubplot(3,2,3)\nPR = P.R*DEM.pU.x{1};\nimagesc(exp(PR))\ntitle('Reflectant','FontSize',16)\nxlabel('time (bins)','FontSize',12)\nylabel('location ','FontSize',12)\naxis square\n \nsubplot(3,2,5)\nimagesc(DEM.pU.v{1})\ntitle('Stimulus','FontSize',16)\nxlabel('time (bins)','FontSize',12)\nylabel('location ','FontSize',12)\naxis square\n \n \nsubplot(3,2,2), imagesc(P.I), axis image off\nsubplot(3,2,4), imagesc(P.R), axis image off\n \n \n% Illustrate the generative model (for 2D)\n%==========================================================================\nnx    = 128;\nP.R   = spm_dwtmtx(nx,2);                 % DWT for hidden causes\nP.I   = spm_dctmtx(nx,3);                 % DCT for hidden causes\nI     = 0;\nR     = 0;\nfor i = 1:size(P.I,2)\n    for j = 1:size(P.I,2)\n        I = I + (P.I(:,i)*P.I(:,j)')*randn;\n    end\nend\nfor i = 1:size(P.R,2)\n    for j = 1:size(P.R,2)\n        v = sum(P.R(:,i) > 0)*sum(P.R(:,j) > 0);\n        R = R + (P.R(:,i)*P.R(:,j)')*randn*sqrt(v);\n    end\nend\n \nR   = R/std(R(:))/2;\nI   = I/std(I(:))/2;\n \n% Plot\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Paper');\n \nsubplot(2,2,1)\nimagesc(exp(I))\ntitle('Illuminant ','FontSize',16)\naxis square\n \nsubplot(2,2,2)\nimagesc(exp(R))\ntitle('Reflectance ','FontSize',16)\naxis square\n \nsubplot(2,1,2)\nimagesc(exp(I + R))\ntitle('Image','FontSize',16)\naxis square, drawnow\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_Cornsweet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5934541828448852}}
{"text": "function [ n_data, x, y, r, fxy ]  = bivariate_normal_cdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% BIVARIATE_NORMAL_CDF_VALUES returns some values of the bivariate normal CDF.\n%\n%  Discussion:\n%\n%    FXY is the probability that two variables A and B, which are\n%    related by a bivariate normal distribution with correlation R,\n%    respectively satisfy A <= X and B <= Y.\n%\n%    Mathematica can evaluate the bivariate normal CDF via the commands:\n%\n%      <<MultivariateStatistics`\n%      cdf = CDF[MultinormalDistribution[{0,0}{{1,r},{r,1}}],{x,y}]\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    23 November 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    National Bureau of Standards,\n%    Tables of the Bivariate Normal Distribution and Related Functions,\n%    NBS, Applied Mathematics Series, Number 50, 1959.\n%\n%  Parameters:\n%\n%    Input, integer N_DATA.  The user sets N_DATA to 0 before the\n%    first call.\n%\n%    Output, integer N_DATA, the routine increments the input value of N_DATA\n%    by 1, and returns the corresponding data; when there is no more data, the\n%    output value of N_DATA will be 0 again.\n%\n%    Output, real X, Y, the parameters of the function.\n%\n%    Output, real R, the correlation value.\n%\n%    Output, real FXY, the value of the function.\n%\n  n_max = 41;\n\n  fxy_vec(1:n_max) = [ ...\n  0.02260327218569867, ...\n  0.1548729518584100, ...\n  0.4687428083352184, ...\n  0.7452035868929476, ...\n  0.8318608306874188, ...\n  0.8410314261134202, ...\n  0.1377019384919464, ...\n  0.1621749501739030, ...\n  0.1827411243233119, ...\n  0.2010067421506235, ...\n  0.2177751155265290, ...\n  0.2335088436446962, ...\n  0.2485057781834286, ...\n  0.2629747825154868, ...\n  0.2770729823404738, ...\n  0.2909261168683812, ...\n  0.3046406378726738, ...\n  0.3183113449213638, ...\n  0.3320262544108028, ...\n  0.3458686754647614, ...\n  0.3599150462310668, ...\n  0.3742210899871168, ...\n  0.3887706405282320, ...\n  0.4032765198361344, ...\n  0.4162100291953678, ...\n  0.6508271498838664, ...\n  0.8318608306874188, ...\n  0.0000000000000000, ...\n  0.1666666666539970, ...\n  0.2500000000000000, ...\n  0.3333333333328906, ...\n  0.5000000000000000, ...\n  0.7452035868929476, ...\n  0.1548729518584100, ...\n  0.1548729518584100, ...\n  0.06251409470431653, ...\n  0.7452035868929476, ...\n  0.1548729518584100, ...\n  0.1548729518584100, ...\n  0.06251409470431653, ...\n  0.6337020457912916 ];\n  r_vec(1:n_max) = [ ...\n     0.500,  0.500,  0.500,  0.500,  0.500, ...\n     0.500, -0.900, -0.800, -0.700, -0.600, ...\n    -0.500, -0.400, -0.300, -0.200, -0.100, ...\n     0.000,  0.100,  0.200,  0.300,  0.400, ...\n     0.500,  0.600,  0.700,  0.800,  0.900, ...\n     0.673,  0.500, -1.000, -0.500,  0.000, ...\n     0.500,  1.000,  0.500,  0.500,  0.500, ...\n     0.500,  0.500,  0.500,  0.500,  0.500, ...\n     0.500 ];\n  x_vec(1:n_max) = [ ...\n    -2.0, -1.0,  0.0,  1.0,  2.0, ...\n     3.0, -0.2, -0.2, -0.2, -0.2, ...\n    -0.2, -0.2, -0.2, -0.2, -0.2, ...\n    -0.2, -0.2, -0.2, -0.2, -0.2, ...\n    -0.2, -0.2, -0.2, -0.2, -0.2, ...\n     1.0,  2.0,  0.0,  0.0,  0.0, ...\n     0.0,  0.0,  1.0,  1.0, -1.0, ...\n    -1.0,  1.0,  1.0, -1.0, -1.0, ...\n     0.7071067811865475  ];\n  y_vec(1:n_max) = [ ...\n     1.0,  1.0,  1.0,  1.0,  1.0, ...\n     1.0,  0.5,  0.5,  0.5,  0.5, ...\n     0.5,  0.5,  0.5,  0.5,  0.5, ...\n     0.5,  0.5,  0.5,  0.5,  0.5, ...\n     0.5,  0.5,  0.5,  0.5,  0.5, ...\n     0.5,  1.0,  0.0,  0.0,  0.0, ...\n     0.0,  0.0,  1.0, -1.0,  1.0, ...\n    -1.0,  1.0, -1.0,  1.0, -1.0, ...\n     0.7071067811865475 ];\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    r = 0.0;\n    x = 0.0;\n    y = 0.0;\n    fxy = 0.0;\n  else\n    r = r_vec(n_data);\n    x = x_vec(n_data);\n    y = y_vec(n_data);\n    fxy = fxy_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/bivariate_normal_cdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5934336298020371}}
{"text": "function out = convvel( in, uin, uout)\n%CONVVEL Convert from velocity units to desired velocity units.\n%Allowable UI and UO strings:\n% 'keas' Knots equivalent airspeed\n% 'm/s' metres per second\n% 'kt' knots\n\nif ~isfloat( in )\n    error('Input is not floating point');\nend\n\nif nargin < 3\n    uout = 'm/s';\nend \n    uin = lower(uin);\n    uout = lower(uout);\n    \n%conversion to m/s\nif strcmp('kts',uin)\n    slope = 0.514444444; %m/s/kts\nelseif strcmp('m/s',uin)\n    slope = 1;\nelseif strcmp('ft/min',uin)\n    slope = 5.08e-3;\nelse\n    error('invalid input unit string')\nend\n\n%conversion from m/s\nif strcmp('kts',uout)\n    slope = slope/0.514444444; %keas/m/s\nelseif strcmp('ft/min',uout)\n    slope = slope/5.08e-3;\n%else\n %  error('invalid output unit string')\nend\n\nout = in.*slope;", "meta": {"author": "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/utilities/convvel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5934336298020371}}
{"text": "function R = quantize_ucm_or(ucm, nori, angSpan)\nif nargin<2, nori = 8; end\nif nargin<3, angSpan = 1; end % in [1,...,8]. angSpan = 1: no overlap. angSpan = 3: overlap of nori/pi. angSpan = 8: todos los canales tienen full ucm.\n\n\nstrength = ucm.strength(3:2:end,3:2:end);\n[tx, ty] = size(strength);\nR = zeros(tx, ty, nori);\n\n\nfor o = 0 : nori-1,\n    \n    angMin = (2*o-angSpan)/nori/2*pi;\n    angMax = (2*o+angSpan)/nori/2*pi;\n    \n    if (angMin >= 0) && (angMax <= pi),\n        bw = (ucm.orient > angMin) & (ucm.orient <= angMax);\n    elseif (angMin < 0) && (angMax <= pi)\n        bw = (ucm.orient > (pi+angMin)) | (ucm.orient <= angMax);\n    elseif (angMin >= 0) && (angMax > pi)\n        bw = (ucm.orient > angMin) | (ucm.orient <= (angMax-pi) );\n    else\n        bw = (ucm.orient > (pi+angMin)) | (ucm.orient <= (angMax-pi) );\n    end\n\n    R(:, :, o+1) = strength .* ( bw & (ucm.orient~=0));\nend \n", "meta": {"author": "s-gupta", "repo": "rgbd", "sha": "e56ca4c37d7b0cf39fbfb757d9d58222284c315d", "save_path": "github-repos/MATLAB/s-gupta-rgbd", "path": "github-repos/MATLAB/s-gupta-rgbd/rgbd-e56ca4c37d7b0cf39fbfb757d9d58222284c315d/ucmGT/quantize_ucm_or.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5934205017027782}}
{"text": "%kckmeans2 'Performs K-Means clustering with more options '\n% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros ckmeans2.pane file\n%\n% Parameters: \n% InputFile: i1 'Input data object', required: 'input data object (to be clustered)'\n% InputFile: i2 'Cluster center input object', optional: 'cluster center input object'\n% Toggle: map 'Generate output map', default: 0: 'generate output map'\n% Toggle: spectrum 'SPECTRUM compatable map segment', default: 0: 'SPECTRUM compatable map segment'\n% Integer: n 'Max number of iterations', default: 50000: 'max number of iterations'\n% Integer: mergeifcount 'Cluster count is <', default: 1: 'merge with closest if the cluster has less than mergeifcount points'\n% Integer: maskifcount 'Mask points in clusters with counts < ', default: 1: 'mask if point is in cluster with less than maskifcount'\n% OutputFile: o1 'Cluster number output object', required: 'cluster number output object'\n% OutputFile: o2 'Cluster center output object', optional: 'cluster center output object'\n% OutputFile: o3 'Cluster variance output object', optional: 'cluster variance output object'\n% OutputFile: o4 'Cluster membership count output', optional: 'Cluster membership count output'\n% OutputFile: o5 'K-means statistics output (ASCII)', optional: 'K-means statistics output (ASCII)'\n% Integer: k 'Initial number of clusters', default: 2: 'initial number of clusters'\n%\n% Example: [o1, o2, o3, o4, o5] = kckmeans2({i1, i2}, {'i1','';'i2','';'map',0;'spectrum',0;'n',50000;'mergeifcount',1;'maskifcount',1;'o1','';'o2','';'o3','';'o4','';'o5','';'k',2})\n%\n% Khoros helpfile follows below:\n%\n%  PROGRAM\n% ckmeans2 - Performs K-Means clustering with more options\n%\n%  DESCRIPTION\n% \"ckmeans2\" is the implementation of a clustering algorithm that can be used for unsupervised classification of data. \\fIckmeans2\\fP has some enhancements over the \\fIkkmeans\\fP algorithm of the datamanip toolbox. These enhancements provides more variation of parameters for clustering but does not guarantee that better results could be obtained. \n% Main differences from \"kkmeans\" to \\fIckmeans2\\fP are:\n% 1 - \"ckmeans2\" consider mask data. Masked points will not be taken in account for clustering and/or calculation of means and variances.\n% 2 - If the user don't provide an initial cluster center object with the [-i2] parameter, \"ckmeans2\" will create the initial cluster centers from random sparse values - there is no guarantee that this will improve the convergence (in some cases may even slow down the clustering) but if you use the first N points from the data there is the risk that these points will be similar (e.g. with image data)\n% 3 - \"ckmeans2\" allows merging of clusters based on the number of points in the clusters - this allow clusters with few points  (specified with the parameter [-mergeifcount]) to be joined to the nearest cluster. Clusters can also be joined if their distances is smaller than a threshold ([-mergeifdistance]). Cluster distances are calculated with the Euclidean distance of their centers. Please note that the joining algorithm is not optimum - joining is perfomed after kmeans clustering to avoid conflicts while clustering (slowing convergence), and is not done recursively until a stable state is achieved.\n% 4 - \"ckmeans2\" allows the user to mask points belonging to clusters with few points (specified with the parameter [-maskifcount]). This has the effect of rejecting clusters with few points that can be considered as outliers on the data. A caveat is needed: the kmeans algorithm tries to create similar-sized, spherical-shaped clusters, but few points in a cluster does not necessarily means that this cluster is made of outliers.\n% This implementation of \"ckmeans2\" uses the same basic clustering procedure as the \\fIkkmeans\\fP implementation in Khoros - meaning that the code was copied partially, specially for creation of that complicated SPECTRUM compatibility thingie. Please refer to the \\fIkkmeans\\fP help for more information about \\fIkkmeans\\fP.\n% The input file is specified with the parameter [-i1], and optionally initial cluster centers can be passed with the [-i2] parameter. If passed, this data must have dimensions Cx1x1x1xE, where C is the number of classes and E is the number of elements in the [-i1] input data. \n% The number of clusters can be specified either with the [-k] parameter or by proportion [-divk] of the number of valid points on the data. The maximum number of iterations is specified with the [-n] parameter.\n% The output file [-o1] can have a map segment that will be the center of the cluster for each cluster, if the parameter [-map] is passed. Optionally a Spectrum-compatable map can be created by specifying [-spectrum]. \n% As with \"kkmeans\", this routine can create several output files: [-o1] will contain the cluster numbers for each input vector, [-o2] will contain the cluster centers, [-o3] will contain the cluster variances, [-o4] will contain the cluster counts and [-o5]\n% will contain information about the clustering (in ASCII). Please refer to the kman page for \"kkmeans\" for more details about these files.\n% This routine is a first step towards a more complete implementation of the Isodata algorithm, which uses the k-means clustering algorithm for clustering and heuristics for post-clustering merging and splitting of clusters.\n%\n%  \n%\n%  EXAMPLES\n% All examples for the Classify toolbox are listed on the Classify Toolbox Manual. For an example of this kroutine, please see the example workspace Classify:workspaces:kmeans\n%\n%  \"SEE ALSO\"\n% kkmeans (in the Datamanip toolbox), cfuzzycmeans\n%\n%  RESTRICTIONS \n% Complex data types are not supported. If there is mask, expect the mask to be consistent over vectors, i.e. for a vector's elements either all masks are TRUE or FALSE. \n% At this implementation the final result will contain the same number of clusters as specified by [-k] or [-divk], even if joining is performed. Future versions should delete the clusters with zero membership.\n%\n%  REFERENCES \n% All references for the Classify toolbox are listed on the Classify Toolbox Manual.\n%\n%  COPYRIGHT\n% Copyright (C) 1997 Rafael Santos. Khoros (C) Khoral Research, Inc.\n% \n\n\nfunction varargout = kckmeans2(varargin)\nif nargin ==0\n  Inputs={};arglist={'',''};\nelseif nargin ==1\n  Inputs=varargin{1};arglist={'',''};\nelseif nargin ==2\n  Inputs=varargin{1}; arglist=varargin{2};\nelse error('Usage: [out1,..] = kckmeans2(Inputs,arglist).');\nend\nif size(arglist,2)~=2\n  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')\n end\nnarglist={'i1', '__input';'i2', '__input';'map', 0;'spectrum', 0;'n', 50000;'mergeifcount', 1;'maskifcount', 1;'o1', '__output';'o2', '__output';'o3', '__output';'o4', '__output';'o5', '__output';'k', 2};\nmaxval={0,1,0,0,100000,2,2,0,1,1,1,1,2};\nminval={0,1,0,0,0,2,2,0,1,1,1,1,2};\nistoggle=[0,1,1,1,1,1,1,0,1,1,1,1,1];\nwas_set=istoggle * 0;\nparamtype={'InputFile','InputFile','Toggle','Toggle','Integer','Integer','Integer','OutputFile','OutputFile','OutputFile','OutputFile','OutputFile','Integer'};\n% identify the input arrays and assign them to the arguments as stated by the user\nif ~iscell(Inputs)\nInputs = {Inputs};\nend\nNumReqOutputs=1; nextinput=1; nextoutput=1;\n  for ii=1:size(arglist,1)\n  wasmatched=0;\n  for jj=1:size(narglist,1)\n   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments\n     wasmatched = 1;\n     was_set(jj) = 1;\n     if strcmp(narglist{jj,2}, '__input')\n      if (nextinput > length(Inputs)) \n        error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n      end\n      narglist{jj,2} = 'OK_in';\n      nextinput = nextinput + 1;\n     elseif strcmp(narglist{jj,2}, '__output')\n      if (nextoutput > nargout) \n        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n      end\n      if (isempty(arglist{ii,2}))\n        narglist{jj,2} = 'OK_out';\n      else\n        narglist{jj,2} = arglist{ii,2};\n      end\n\n      nextoutput = nextoutput + 1;\n      if (minval{jj} == 0)  \n         NumReqOutputs = NumReqOutputs - 1;\n      end\n     elseif isstr(arglist{ii,2})\n      narglist{jj,2} = arglist{ii,2};\n     else\n        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n        end\n        if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n          end\n        end\n     end\n     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in') \n       narglist{jj,2} = arglist{ii,2};\n     end\n   end\n   end\n   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n   end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n     if  strcmp(paramtype{jj}, 'Toggle')\n        if (narglist{jj,2} ==0)\n          narglist{jj,1} = ''; \n        end;\n        narglist{jj,2} = ''; \n     end;\n     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n          narglist{jj,1} = ''; \n          narglist{jj,2} = ''; \n     end;\n     if strcmp(narglist{jj,2}, '__input')\n      if (minval{jj} == 0)  % meaning this input is required\n        if (nextinput > size(Inputs)) \n           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n        else\n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        end\n      else  % this is an optional input\n        if (nextinput <= length(Inputs)) \n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end;\n     else \n     if strcmp(narglist{jj,2}, '__output')\n      if (minval{jj} == 0) % this is a required output\n        if (nextoutput > nargout & nargout > 1) \n           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n        else\n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n          NumReqOutputs = NumReqOutputs-1;\n        end\n      else % this is an optional output\n        if (nargout - nextoutput >= NumReqOutputs) \n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end\n     end\n  end\nend\nif nargout\n   varargout = cell(1,nargout);\nelse\n  varargout = cell(1,1);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n  w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\n[varargout{:}]=callKhoros([w 'ckmeans2\"  '],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kckmeans2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.593420486041433}}
{"text": "function M = getmassmatvec(elem2edge,area,Dlambda,elemType,K)\n%% GETMASSMATVEC Get the mass matrix of vector finite element space\n%\n% M = GETMASSMATVEC(elem2edge,area,Dlambda,elemType,K) get mass matrix of\n% the finite element space specified by elemType. The coefficient K is\n% piecewise constant.\n%\n% The elemType can be: \n%\n% - \"RT0\": The lowest order Raviart-Thomas element\n% - \"BDM1\": The lowest order Brezzi-Douglas-Michel element\n% - \"BDM1B\": The BDM element enriched by the curl of cubic bubble function\n% - \"ND0\": The lowest order Nedelec element\n% - \"RT1\": Linear-Quadratic Rvairart-Thomas element \n%\n% Note that RT0 and ND0 share the same mass matrix.\n%\n% RT0, BMD1 are created by Ming Wang at July, 2012. Improved by Long Chen.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('K','var'), K = []; end\nNE = double(max(elem2edge(:)));\nNT = size(elem2edge,1);\nDiDj = zeros(NT,3,3);\nfor i = 1:3\n    for j = i:3\n        if isempty(K)\n            DiDj(:,i,j) = dot(Dlambda(:,:,i),Dlambda(:,:,j),2);\n        else\n            switch size(K,2)\n                case 1 % scalar K\n                    DiDj(:,i,j) = dot(Dlambda(:,:,i),Dlambda(:,:,j),2)./K;\n                case 2 % diagonal matrix\n                    DiDj(:,i,j) =  Dlambda(:,1,i).*Dlambda(:,1,j)./K(:,1) ...\n                                 + Dlambda(:,2,i).*Dlambda(:,2,j)./K(:,2);\n                case 3 % K is 2 by 2 SPD matrix\n                    detK = K(:,1).*K(:,2) - K(:,3).^2;\n                    DiDj(:,i,j) = (Dlambda(:,1,i).*Dlambda(:,1,j).*K(:,2) ...\n                                 + Dlambda(:,2,i).*Dlambda(:,2,j).*K(:,1) ...\n                                 - Dlambda(:,1,i).*Dlambda(:,2,j).*K(:,3) ...\n                                 - Dlambda(:,2,i).*Dlambda(:,1,j).*K(:,3))./detK;\n                    \n            end\n        end\n        DiDj(:,j,i) = DiDj(:,i,j);\n    end\nend\nlocalEdge = [2 3; 1 3; 1 2]; % ascend ordering\n\n%% RT0 and ND0\nif strcmp(elemType,'RT0') || strcmp(elemType,'ND0')\n    M = sparse(NE,NE);\n    for i = 1:3\n        for j = i:3\n            % local to global index map and its sign\n            ii = double(elem2edge(:,i));\n            jj = double(elem2edge(:,j));\n            i1 = localEdge(i,1); i2 = localEdge(i,2); % [i1,i2] is the edge opposite to vertex i.\n            j1 = localEdge(j,1); j2 = localEdge(j,2);\n            % computation of mass matrix --- (phi_i, phi_j)\n            Mij = 1/12*area.*( (1+(i1==j1))*DiDj(:,i2,j2) ...\n                             - (1+(i1==j2))*DiDj(:,i2,j1) ...\n                             - (1+(i2==j1))*DiDj(:,i1,j2) ...\n                             + (1+(i2==j2))*DiDj(:,i1,j1));\n            if (j==i)\n                M = M + sparse(ii,jj,Mij,NE,NE);\n            else\n                M = M + sparse([ii;jj],[jj;ii],[Mij; Mij],NE,NE);\n            end\n        end\n    end\nend\n\n%% BDM1\nif strcmp(elemType,'BDM1') || strcmp(elemType,'BDM1B') || strcmp(elemType,'RT1')\n    M = sparse(2*NE,2*NE);\n    for i = 1:3\n        for j = i:3\n            % local to global index map and its sign\n            ii = double(elem2edge(:,i));\n            jj = double(elem2edge(:,j));\n            i1 = localEdge(i,1); i2 = localEdge(i,2); % [i1,i2] is the edge opposite to vertex i.\n            j1 = localEdge(j,1); j2 = localEdge(j,2);\n            % computation of mass matrix, note that (rot u, rot v) = (grad u, grad v)\n            % (phi_i, phi_j)\n            Mij = 1/12*area.*( (1+(i1==j1))*DiDj(:,i2,j2) ...\n                             - (1+(i1==j2))*DiDj(:,i2,j1) ...\n                             - (1+(i2==j1))*DiDj(:,i1,j2) ...\n                             + (1+(i2==j2))*DiDj(:,i1,j1));\n            if (j==i)\n                M = M + sparse(ii,jj,Mij,2*NE,2*NE);\n            else\n                M = M + sparse([ii;jj],[jj;ii],[Mij; Mij],2*NE,2*NE);\n            end\n            % (psi_i,psi_j)\n            Mij = 1/12*area.*( (1+(i1==j1))*DiDj(:,i2,j2) ...\n                             + (1+(i1==j2))*DiDj(:,i2,j1) ...\n                             + (1+(i2==j1))*DiDj(:,i1,j2) ...\n                             + (1+(i2==j2))*DiDj(:,i1,j1));\n            if (j==i)\n                M = M + sparse(ii+NE,jj+NE,Mij,2*NE,2*NE);\n            else\n                M = M + sparse([ii;jj]+NE,[jj;ii]+NE,[Mij; Mij],2*NE,2*NE);\n            end\n        end\n    end\n    for i = 1:3\n        for j = 1:3\n            % local to global index map and its sign\n            ii = double(elem2edge(:,i));\n            jj = double(elem2edge(:,j));\n            i1 = localEdge(i,1); i2 = localEdge(i,2);\n            j1 = localEdge(j,1); j2 = localEdge(j,2);\n            % (psi_i,phi_j)\n            Mij = 1/12*area.*( (1+(i1==j1))*DiDj(:,i2,j2) ...\n                             - (1+(i1==j2))*DiDj(:,i2,j1) ...\n                             + (1+(i2==j1))*DiDj(:,i1,j2) ...\n                             - (1+(i2==j2))*DiDj(:,i1,j1));\n            M = M + sparse([ii+NE;jj],[jj;ii+NE],[Mij; Mij],2*NE,2*NE);\n        end\n    end\nend\n\n%% BDM1B\nif strcmp(elemType,'BDM1B')\n    newM = sparse(2*NE+NT,2*NE+NT);\n    newM(1:2*NE,1:2*NE) = M;\n    M = newM;\n    % (phi_i, bubble)\n    for i = 1:3\n        ii = double(elem2edge(:,i)); \n        jj = double((1:NT)');\n        i1 = localEdge(i,1); i2 = localEdge(i,2); i3 = 6-i1-i2;\n        Mij = 9/10*area.*(DiDj(:,i2,i3)...\n                         +DiDj(:,i2,i2)...\n                         -DiDj(:,i1,i3)...\n                         -DiDj(:,i1,i1));\n        M = M + sparse([ii;jj+2*NE],[jj+2*NE;ii],[Mij;Mij],2*NE+NT,2*NE+NT);\n    end\n    clear ii jj i1 i2 i3 Mij;\n    % (psi_i, bubble)\n    for i = 1:3\n        ii = double(elem2edge(:,i)); \n        jj = double((1:NT)');\n        i1 = localEdge(i,1); i2 = localEdge(i,2); i3 = 6-i1-i2;\n        Mij = 9/10*area.*(DiDj(:,i2,i3)...\n                        + DiDj(:,i1,i3)...\n                        + DiDj(:,i2,i2)...\n                        + DiDj(:,i1,i1)...\n                        + DiDj(:,i1,i2));\n        M = M + sparse([ii+NE;jj+2*NE],[jj+2*NE;ii+NE],[Mij;Mij],2*NE+NT,2*NE+NT);\n    end\n    clear ii jj i1 i2 i3 Mij;\n    % (bubble, bubble)\n    ii = 1+2*NE:NT+2*NE;\n    Mij = 81/10*area.*(DiDj(:,1,1)...\n                    + DiDj(:,1,2)...\n                    + DiDj(:,1,3)...\n                    + DiDj(:,2,2)...\n                    + DiDj(:,2,3)...\n                    + DiDj(:,3,3));\n    if ~isempty(K)\n        Mij = Mij./K;\n    end        \n    M = M + sparse(ii,ii,Mij,2*NE+NT,2*NE+NT);\nend\n\n%% RT1\nelem2dof = [elem2edge elem2edge+NE (1:NT)'+2*NE (1:NT)'+2*NE+NT];\nlocBasesIdx = [1 2 0; 1 3 0; 2 3 0; ... % phi and psi\n               2 1 3; 3 1 2];           % chi\nif strcmp(elemType,'RT1')\n    newM = sparse(2*NE+2*NT,2*NE+2*NT);\n    newM(1:2*NE,1:2*NE) = M;\n    M = newM;\n    % (phi_i, chi_j)\n    for i = 1:3\n        for j = 1:2\n            ii = double(elem2dof(:,i));\n            jj = double(elem2dof(:,j+6));\n            i1 = locBasesIdx(i,1); i2 = locBasesIdx(i,2); %i3 = locBasesIdx(i,3);\n            j1 = locBasesIdx(j,1); j2 = locBasesIdx(j,2); j3 = locBasesIdx(j,3);\n            Mij = intlambda([j1,i1,j2],2)*DiDj(:,i2,j3) ...\n                 -intlambda([j1,i1,j3],2)*DiDj(:,i2,j2) ...\n                 -intlambda([j1,i2,j2],2)*DiDj(:,i1,j3) ...\n                 +intlambda([j1,i2,j3],2)*DiDj(:,i1,j2);                        \n            M = M + sparse([ii;jj],[jj;ii],[Mij;Mij],2*NE+2*NT,2*NE+2*NT);\n        end\n    end\n    clear ii jj i1 i2 i3 Mij;\n    % (psi_i, chi_j)\n    for i = 1:3\n        for j = 1:2\n            ii = double(elem2dof(:,i+3));\n            jj = double(elem2dof(:,j+6));\n            i1 = locBasesIdx(i,1); i2 = locBasesIdx(i,2); %i3 = locBasesIdx(i,3);\n            j1 = locBasesIdx(j,1); j2 = locBasesIdx(j,2); j3 = locBasesIdx(j,3);\n            Mij = intlambda([j1,i1,j2],2)*DiDj(:,i2,j3) ...\n                 -intlambda([j1,i1,j3],2)*DiDj(:,i2,j2) ...\n                 +intlambda([j1,i2,j2],2)*DiDj(:,i1,j3) ...\n                 -intlambda([j1,i2,j3],2)*DiDj(:,i1,j2);                        \n            M = M + sparse([ii;jj],[jj;ii],[Mij;Mij],2*NE+2*NT,2*NE+2*NT);\n        end\n    end\n    clear ii jj i1 i2 i3 Mij;\n    for i = 1:2\n        for j = 1:2\n            % (chi_j,chi_i)\n            ii = double(elem2dof(:,i+3));\n            jj = double(elem2dof(:,j+6));\n            i1 = locBasesIdx(i,1); i2 = locBasesIdx(i,2); i3 = locBasesIdx(i,3);\n            j1 = locBasesIdx(j,1); j2 = locBasesIdx(j,2); j3 = locBasesIdx(j,3);\n            Mij = intlambda([i1,j1,i2,j2],2)*DiDj(:,i3,j3) ...\n                 -intlambda([i1,j1,i2,j3],2)*DiDj(:,i3,j2) ...\n                 -intlambda([i1,j1,i3,j2],2)*DiDj(:,i2,j3) ...\n                 +intlambda([i1,j1,i3,j3],2)*DiDj(:,i2,j2);                        \n            M = M + sparse([ii;jj],[jj;ii],[Mij;Mij],2*NE+2*NT,2*NE+2*NT);\n        end\n    end\nend\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/getmassmatvec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642804, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5934204799468628}}
{"text": "% Local Regression and Likelihood, Figure 4.1.\n% Author: Catherine Loader\n%\n% Local Likelihood (Poisson Regression).\n\nload mine;\nfit = locfit(extrp,frac,'family','poisson','deg',1,'alpha',0.6);\nfigure('Name','fig4_1: Poisson Regression');\nlfplot(fit);\nlfband(fit);\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/fig4_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5934204703800878}}
{"text": "function [B,twom] = multiord_f(A,gamma,omega)\n%MULTIORD_F  returns multilayer Newman-Girvan modularity matrix for ordered undirected layers, function handle version\n% Only works for undirected networks\n%\n% Version: 2.2.0\n% Date: Thu 11 Jul 2019 12:25:42 CEST\n%\n%   Input: A: Cell array of NxN adjacency matrices for each layer of an\n%          ordered undirected multilayer network\n%          gamma: intralayer resolution parameter\n%          omega: interlayer coupling strength\n%\n%   Output: B: function handle where B(i) returns the ith column of\n%          [NxT]x[NxT] flattened modularity tensor for the\n%           multilayer network with uniform ordinal coupling (T is\n%           the number of layers of the network)\n%           twom: normalisation constant\n%\n%   Example of usage: [B,twom]=multiord_f(A,gamma,omega);\n%          [S,Q]= genlouvain(B); % see iterated_genlouvain.m and\n%          postprocess_ordinal_multilayer.m for how to improve output\n%          multilayer partition\n%          Q=Q/twom;\n%          S=reshape(S,N,T);\n%\n%   [B,twom] = MULTIORD_F(A,GAMMA, OMEGA) with A a cell array of square\n%   symmetric matrices of equal size each representing an undirected network\n%   \"layer\" computes the multilayer Newman-Girvan modularity matrix using\n%   the quality function described in Mucha et al. 2010, with intralayer\n%   resolution parameter GAMMA, and with interlayer coupling OMEGA connecting\n%   nearest-neighbor ordered layers.  The null model used for the quality\n%   function is the Newman-Girvan null model (see e.g. Bazzi et al. for other\n%   possible null models). Once the mulilayer modularity matrix is computed,\n%   optimization can be performed by the generalized Louvain code GENLOUVAIN\n%   or ITERATED_GENLOUVAIN. The output B can be used with other heuristics,\n%   provided the same mapping is used to go from the multilayer tensor to\n%   the multilayer flattened matrix. That is, the node-layer tuple (i,s)\n%   is mapped to i + (s-1)*N. [Note that we can define a mapping between a\n%   multilayer partition S_m stored as an N by T matrix and the corresponding\n%   flattened partition S stored as an NT by 1 vector. In particular\n%   S_m = reshape(S,N,T) and S = S_m(:).]\n%\n%\n%   See also\n%       genlouvain heuristics:      GENLOUVAIN, ITERATED_GENLOUVAIN\n%       multilayer wrappers:        MULTICAT, MULTICATF, MULTIORD\n%       other heuristics:           SPECTRAL23\n%       Kernighan-Lin improvement:  KLNB\n%\n%   Notes:\n%     The matrices in the cell array A are assumed to be square,\n%     symmetric, and of equal size.  These assumptions are not checked here.\n%\n%     For smaller systems, it is potentially more efficient (and easier) to\n%     directly use the sparse quality/modularity matrix B in MULTIORD. For\n%     large systems with directed layer networks, use MULTIORDDIR_F.\n%\n%     This code serves as a template and can be modified for situations\n%     with other wrinkles (e.g., different intralayer null models,\n%     different numbers of nodes from layer-to-layer, or systems which are\n%     both multiplex and longitudinal).  That is, this code is only a\n%     starting point; it is by no means exhaustive.\n%\n%     By using this code, the user implicitly acknowledges that the authors\n%     accept no liability associated with that use.  (What are you doing\n%     with it anyway that might cause there to be a potential liability?!?)\n%\n%   References:\n%     Blondel, Vincent D., Jean-Loup Guillaume, Renaud Lambiotte, and\n%     Etienne Lefebvre, \"Fast unfolding of communities in large networks,\"\n%     Journal of Statistical Mechanics: Theory and Experiment, P10008\n%     (2008).\n%\n%     Fortunato, Santo, \"Community detection in graphs,\" Physics Reports\n%     486, 75-174 (2010).\n%\n%     Good, Benjamin H., Yves-Alexandre de Montjoye, and Aaron Clauset,\n%     \"Performance of modularity maximization in practical contexts,\"\n%     Physical Review E 81, 046106 (2010).\n%\n%     Newman, Mark E. J. and Michelle Girvan. \"Finding and Evaluating\n%     Community Structure in Networks\", Physical Review E 69, 026113 (2004).\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%\n%     Porter, M. A., J. P. Onnela, and P. J. Mucha, \"Communities in\n%     networks,\" Notices of the American Mathematical Society 56, 1082-1097\n%     & 1164-1166 (2009).\n%\n%   Acknowledgments:\n%     Thank you to Dani Bassett, Jesse Blocher, Bruce Rogers, and Simi Wang\n%     for their collaborative help which led to significant cleaning up\n%     of earlier versions of our multilayer community detection codes.\n\n\nif nargin<2||isempty(gamma)\n    gamma=1;\nend\n\nif nargin<3\n    omega=1;\nend\n\nN=length(A{1});\nT=length(A);\n\nif length(gamma)==1\n    gamma=repmat(gamma,T,1);\nend\n\nii=[]; jj=[]; vv=[];\nki=[]; kj=[]; kv=[];\ntwom=0;\nfor s=1:T\n    indx=(1:N)'+(s-1)*N;\n    [i,j,v]=find(A{s});\n    ii=[ii;indx(i)]; jj=[jj;indx(j)]; vv=[vv;v];\n    k=sum(A{s});\n    mm=sum(k);\n    twom=twom+mm;\n    ki=[ki;indx];\n    kj=[kj;ones(N,1)*s];\n    kv=[kv;k(:)./mm];\nend\nAA = sparse(ii,jj,vv,N*T,N*T);\nK=sparse(ki,kj,kv,N*T,T);\nclear ii jj vv ki kj kv\nkvec = full(sum(AA));\nAA = AA + omega*spdiags(ones(N*T,2),[-N,N],N*T,N*T);\nB = @(i) AA(:,i) - gamma(ceil(i/(N+eps)))*K(:,ceil(i/(N+eps)))*kvec(i);\ntwom=twom+2*N*(T-1)*omega;\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/multiord_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891435927269, "lm_q2_score": 0.7217432122827967, "lm_q1q2_score": 0.5934094336006563}}
{"text": "function plotData(X, y)\n%PLOTDATA Plots the data points X and y into a new figure \n%   PLOTDATA(x,y) plots the data points with + for the positive examples\n%   and o for the negative examples. X is assumed to be a Mx2 matrix.\n\n% Create New Figure\nfigure; hold on;\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Plot the positive and negative examples on a\n%               2D plot, using the option 'k+' for the positive\n%               examples and 'ko' for the negative examples.\n%\n\n% Find Indices of Positive and Negative Examples\npos = find(y==1); neg = find(y==0);\n\n% Plot Examples\nplot(X(pos, 1), X(pos, 2), 'k+', 'LineWidth', 2, 'MarkerSize', 7);\nplot(X(neg, 1), X(neg, 2), 'ko', 'MarkerFaceColor', 'y', 'MarkerSize', 7);\n\n% =========================================================================\n\nhold off;\n\nend\n", "meta": {"author": "rmarquis", "repo": "coursera-machinelearning", "sha": "5b165935e6fecfab977b2af1b0e9c588c75ca8f4", "save_path": "github-repos/MATLAB/rmarquis-coursera-machinelearning", "path": "github-repos/MATLAB/rmarquis-coursera-machinelearning/coursera-machinelearning-5b165935e6fecfab977b2af1b0e9c588c75ca8f4/homework/mlclass-ex2/plotData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.5934094239628188}}
{"text": "function holdout_sets = xval_select_holdout_set_categoricalcovs(covs)\n    \nu = unique(covs, 'rows');\nnu = size(u, 1);  % number of unique cells; also size of holdout sets\n\n[N, k] = size(covs);\n\nonevec = ones(N, 1);\n\n% indices for each cell\nfor i = 1:nu\n    cell_indices{i} = all(covs - u(i * onevec, :) == 0, 2);\nend\n\nnobs_per_cell = sum(cat(2, cell_indices{:}));\nnfolds = max(nobs_per_cell);  % number of folds; max() leaves some unbalanced holdout sets; min keeps balance but does not test all obs\n\n% random selection of one obs per cell for each fold\nfor i = 1:nu\n    wh_obs{i} = find(cell_indices{i}); \n    wh_obs{i} = wh_obs{i}(randperm(nobs_per_cell(i)));\nend\n\n% deal observations into folds\nfor i = 1:nfolds\n    wh = [];\n    for j = 1:nu\n        if nobs_per_cell(j) >= i \n            wh = [wh wh_obs{j}(i)];\n        end\n    end\n    \n    holdout_sets{i} = logical(false * onevec);\n    holdout_sets{i}(wh) = true;\n    \nend\n\nend  % function\n\n% checking stuff\n% allsets = cat(2, holdout_set{:});\n% sum(allsets)\n% sum(allsets, 2)\n% covs(holdout_set{1}, :)\n% covs(holdout_set{2}, :)\n% covs(holdout_set{3}, :)\n% covs(holdout_set{4}, :)\n% covs(holdout_set{end}, :)", "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/Cross_validated_Regression/xval_select_holdout_set_categoricalcovs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.593409417877749}}
{"text": "function x = simuARMA(a,b,nobs)\n% x = simuARMA(a,b,nobs)\n% simulation of nobs observations of an ARMA process with parameters\n% a,b en standard deviation 1.\n%\n% No transients in finite signal\n% Paper:\n%\n%   Broersen, P.M.T. and S. de Waele\n% \tGenerating Data with Prescribed Power Spectral Density.\n%\tIEEE Trans. on Instrumentation and Measurement, vol. 52, no. 4, p 1061-1067, 2003.\n%\n%\n% uses randn( , )\n%\n\naro = length(a)-1;\nmao = length(b)-1;\n[cor,g]=arma2cor(a,b);\n[cor2,gar]=arma2cor(a,1);\n\nif ~aro,\n   v = randn(nobs+mao,1)/sqrt(g);   \nelse\n   z = randn(aro,1);\n   vs = zeros(aro,1);\n   [at rc] = ar2arset(a);\n   f = 1;\n   vs(1) = f*z(1);\n   al = [];\n   for i = 2:aro,\n   \tf = sqrt(1-rc(i)^2)*f;\n      al = [al 0] + rc(i)*[fliplr(al) 1];\n      vs(i) = f*z(i)-al*vs(i-1:-1:1);\n   end %for i = 2:aro,\n   vs = vs*sqrt(gar/g);\n   v = armafilter(randn(nobs+mao,1)/sqrt(g),a,1,vs,z);\nend %if ~aro,\nx = armafilter(v,1,b);\nx = x(mao+1:mao+nobs);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1330-armasa/ARMASA/fast/simuarma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5933279562725908}}
{"text": "#!/usr/bin/env octave\n%% Machine Learning Online Class\n%  Exercise 6 | Support Vector Machines\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%     gaussianKernel.m\n%     dataset3Params.m\n%     processEmail.m\n%     emailFeatures.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\nfprintf('Loading and Visualizing Data ...\\n')\n\n% Load from ex6data1: \n% You will have X, y in your environment\nload('ex6data1.mat');\n\n% Plot training data\nplotData(X, y);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% ==================== Part 2: Training Linear SVM ====================\n%  The following code will train a linear SVM on the dataset and plot the\n%  decision boundary learned.\n%\n\n% Load from ex6data1: \n% You will have X, y in your environment\nload('ex6data1.mat');\n\nfprintf('\\nTraining Linear SVM ...\\n')\n\n% You should try to change the C value below and see how the decision\n% boundary varies (e.g., try C = 1000)\nC = 1;\nmodel = svmTrain(X, y, C, @linearKernel, 1e-3, 20);\nvisualizeBoundaryLinear(X, y, model);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% =============== Part 3: Implementing Gaussian Kernel ===============\n%  You will now implement the Gaussian kernel to use\n%  with the SVM. You should complete the code in gaussianKernel.m\n%\nfprintf('\\nEvaluating the Gaussian Kernel ...\\n')\n\nx1 = [1 2 1]; x2 = [0 4 -1]; sigma = 2;\nsim = gaussianKernel(x1, x2, sigma);\n\nfprintf(['Gaussian Kernel between x1 = [1; 2; 1], x2 = [0; 4; -1], sigma = 0.5 :' ...\n         '\\n\\t%f\\n(this value should be about 0.324652)\\n'], sim);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% =============== Part 4: Visualizing Dataset 2 ================\n%  The following code will load the next dataset into your environment and \n%  plot the data. \n%\n\nfprintf('Loading and Visualizing Data ...\\n')\n\n% Load from ex6data2: \n% You will have X, y in your environment\nload('ex6data2.mat');\n\n% Plot training data\nplotData(X, y);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% ========== Part 5: Training SVM with RBF Kernel (Dataset 2) ==========\n%  After you have implemented the kernel, we can now use it to train the \n%  SVM classifier.\n% \nfprintf('\\nTraining SVM with RBF Kernel (this may take 1 to 2 minutes) ...\\n');\n\n% Load from ex6data2: \n% You will have X, y in your environment\nload('ex6data2.mat');\n\n% SVM Parameters\nC = 1; sigma = 0.1;\n\n% We set the tolerance and max_passes lower here so that the code will run\n% faster. However, in practice, you will want to run the training to\n% convergence.\nmodel= svmTrain(X, y, C, @(x1, x2) gaussianKernel(x1, x2, sigma)); \nvisualizeBoundary(X, y, model);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% =============== Part 6: Visualizing Dataset 3 ================\n%  The following code will load the next dataset into your environment and \n%  plot the data. \n%\n\nfprintf('Loading and Visualizing Data ...\\n')\n\n% Load from ex6data3: \n% You will have X, y in your environment\nload('ex6data3.mat');\n\n% Plot training data\nplotData(X, y);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% ========== Part 7: Training SVM with RBF Kernel (Dataset 3) ==========\n\n%  This is a different dataset that you can use to experiment with. Try\n%  different values of C and sigma here.\n% \n\n% Load from ex6data3: \n% You will have X, y in your environment\nload('ex6data3.mat');\n\n% Try different SVM Parameters here\n[C, sigma] = dataset3Params(X, y, Xval, yval);\n\n% Train the SVM\nmodel= svmTrain(X, y, C, @(x1, x2) gaussianKernel(x1, x2, sigma));\nvisualizeBoundary(X, y, model);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\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/ex6/ex6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.5933021125520547}}
{"text": "function [x,flag,relres,iter,resvec] = Pgmres_deflation(A,b,restart,tol,maxit,M1,M2,x,varargin)\n%GMRES   Generalized Minimum Residual Method.\n%   X = GMRES(A,B) attempts to solve the system of linear equations A*X = B\n%   for X.  The N-by-N coefficient matrix A must be square and the right\n%   hand side column vector B must have length N. This uses the unrestarted\n%   method with MIN(N,10) total iterations.\n%\n%   X = GMRES(AFUN,B) accepts a function handle AFUN instead of the matrix\n%   A. AFUN(X) accepts a vector input X and returns the matrix-vector\n%   product A*X. In all of the following syntaxes, you can replace A by\n%   AFUN.\n%\n%   X = GMRES(A,B,RESTART) restarts the method every RESTART iterations.\n%   If RESTART is N or [] then GMRES uses the unrestarted method as above.\n%\n%   X = GMRES(A,B,RESTART,TOL) specifies the tolerance of the method.  If\n%   TOL is [] then GMRES uses the default, 1e-6.\n%\n%   X = GMRES(A,B,RESTART,TOL,MAXIT) specifies the maximum number of outer\n%   iterations. Note: the total number of iterations is RESTART*MAXIT. If\n%   MAXIT is [] then GMRES uses the default, MIN(N/RESTART,10). If RESTART\n%   is N or [] then the total number of iterations is MAXIT.\n%\n%   X = GMRES(A,B,RESTART,TOL,MAXIT,M) and\n%   X = GMRES(A,B,RESTART,TOL,MAXIT,M1,M2) use preconditioner M or M=M1*M2\n%   and effectively solve the system inv(M)*A*X = inv(M)*B for X. If M is\n%   [] then a preconditioner is not applied.  M may be a function handle\n%   returning M\\X.\n%\n%   X = GMRES(A,B,RESTART,TOL,MAXIT,M1,M2,X0) specifies the first initial\n%   guess. If X0 is [] then GMRES uses the default, an all zero vector.\n%\n%   [X,FLAG] = GMRES(A,B,...) 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%    2 preconditioner M was ill-conditioned.\n%    3 GMRES stagnated (two consecutive iterates were the same).\n%\n%   [X,FLAG,RELRES] = GMRES(A,B,...) also returns the relative residual\n%   NORM(B-A*X)/NORM(B). If FLAG is 0, then RELRES <= TOL. Note with\n%   preconditioners M1,M2, the residual is NORM(M2\\(M1\\(B-A*X))).\n%\n%   [X,FLAG,RELRES,ITER] = GMRES(A,B,...) also returns both the outer and\n%   inner iteration numbers at which X was computed: 0 <= ITER(1) <= MAXIT\n%   and 0 <= ITER(2) <= RESTART.\n%\n%   [X,FLAG,RELRES,ITER,RESVEC] = GMRES(A,B,...) also returns a vector of\n%   the residual norms at each inner iteration, including NORM(B-A*X0).\n%   Note with preconditioners M1,M2, the residual is NORM(M2\\(M1\\(B-A*X))).\n%\n%   Example:\n%      n = 21; A = gallery('wilk',n);  b = sum(A,2);\n%      tol = 1e-12;  maxit = 15; M = diag([10:-1:1 1 1:10]);\n%      x = gmres(A,b,10,tol,maxit,M);\n%   Or, use this matrix-vector product function\n%      %-----------------------------------------------------------------%\n%      function y = afun(x,n)\n%      y = [0; x(1:n-1)] + [((n-1)/2:-1:0)'; (1:(n-1)/2)'].*x+[x(2:n); 0];\n%      %-----------------------------------------------------------------%\n%   and this preconditioner backsolve function\n%      %------------------------------------------%\n%      function y = mfun(r,n)\n%      y = r ./ [((n-1)/2:-1:1)'; 1; (1:(n-1)/2)'];\n%      %------------------------------------------%\n%   as inputs to GMRES:\n%      x1 = gmres(@(x)afun(x,n),b,10,tol,maxit,@(x)mfun(x,n));\n%\n%   Class support for inputs A,B,M1,M2,X0 and the output of AFUN:\n%      float: double\n%\n%   See also BICG, BICGSTAB, BICGSTABL, CGS, LSQR, MINRES, PCG, QMR, SYMMLQ,\n%   TFQMR, ILU, FUNCTION_HANDLE.\n\n%   References\n%   H.F. Walker, \"Implementation of the GMRES Method Using Householder\n%   Transformations\", SIAM J. Sci. Comp. Vol 9. No 1. January 1988.\n\n%   Copyright 1984-2011 The MathWorks, Inc.\n%   $Revision: 1.21.4.15 $ $Date: 2011/05/17 02:33:07 $\nglobal ZH AH\nif (nargin < 2)\n    error(message('MATLAB:gmres:NumInputs'));\nend\n\n% Determine whether A is a matrix or a function.\n[atype,afun,afcnstr] = iterchk(A);\nif strcmp(atype,'matrix')\n    % Check matrix and right hand side vector inputs have appropriate sizes\n    [m,n] = size(A);\n    if (m ~= n)\n        error(message('MATLAB:gmres:SquareMatrix'));\n    end\n    if ~isequal(size(b),[m,1])\n        error(message('MATLAB:gmres:VectorSize', m));\n    end\nelse\n    m = size(b,1);\n    n = m;\n    if ~iscolumn(b)\n        error(message('MATLAB:gmres:Vector'));\n    end\nend\n\n% Assign default values to unspecified parameters\nif (nargin < 3) || isempty(restart) || (restart == n)\n    restarted = false;\nelse\n    restarted = true;\nend\nif (nargin < 4) || isempty(tol)\n    tol = 1e-6;\nend\nwarned = 0;\nif tol < eps\n    warning(message('MATLAB:gmres:tooSmallTolerance'));\n    warned = 1;\n    tol = eps;\nelseif tol >= 1\n    warning(message('MATLAB:gmres:tooBigTolerance'));\n    warned = 1;\n    tol = 1-eps;\nend\nif (nargin < 5) || isempty(maxit)\n    if restarted\n        maxit = min(ceil(n/restart),10);\n    else\n        maxit = min(n,10);\n    end\nend\n\nif restarted\n    outer = maxit;\n    if restart > n\n        warning(message('MATLAB:gmres:tooManyInnerItsRestart',restart, n));\n        restart = n;\n    end\n    inner = restart;\nelse\n    outer = 1;\n    if maxit > n\n        warning(message('MATLAB:gmres:tooManyInnerItsMaxit',maxit, n));\n        maxit = n;\n    end\n    inner = maxit;\nend\n\n% Check for all zero right hand side vector => all zero solution\nn2b = norm(b);                   % Norm of rhs vector, b\nif (n2b == 0)                    % if    rhs vector is all zeros\n    x = zeros(n,1);              % then  solution is all zeros\n    flag = 0;                    % a valid solution has been obtained\n    relres = 0;                  % the relative residual is actually 0/0\n    iter = [0 0];                % no iterations need be performed\n    resvec = 0;                  % resvec(1) = norm(b-A*x) = norm(0)\n    if (nargout < 2)\n        itermsg('gmres',tol,maxit,0,flag,iter,NaN);\n    end\n    return\nend\n\nif ((nargin >= 6) && ~isempty(M1))\n    existM1 = 1;\n    [m1type,m1fun,m1fcnstr] = iterchk(M1);  %Check the size of Precondioner.\n    if strcmp(m1type,'matrix')\n        if ~isequal(size(M1),[m,m])\n            error(message('MATLAB:gmres:PreConditioner1Size', m));\n        end\n    end\nelse\n    existM1 = 0;\n    m1type = 'matrix';\nend\n\nif ((nargin >= 7) && ~isempty(M2))\n    existM2 = 1;\n    [m2type,m2fun,m2fcnstr] = iterchk(M2);\n    if strcmp(m2type,'matrix')\n        if ~isequal(size(M2),[m,m])\n            error(message('MATLAB:gmres:PreConditioner2Size', m));\n        end\n    end\nelse\n    existM2 = 0;\n    m2type = 'matrix';\nend\n\nif ((nargin >= 8) && ~isempty(x))\n    if ~isequal(size(x),[n,1])\n        error(message('MATLAB:gmres:XoSize', n));\n    end\nelse\n    x = zeros(n,1);\nend\n\nif ((nargin > 8) && strcmp(atype,'matrix') && ...\n        strcmp(m1type,'matrix') && strcmp(m2type,'matrix'))\n    error(message('MATLAB:gmres:TooManyInputs'));\nend\n\n% Set up for the method\nflag = 1;\nxmin = x;                        % Iterate which has minimal residual so far\nimin = 0;                        % \"Outer\" iteration at which xmin was computed\njmin = 0;                        % \"Inner\" iteration at which xmin was computed\ntolb = tol * n2b;                % Relative tolerance\nevalxm = 0;\nstag = 0;\nmoresteps = 0;\nmaxmsteps = min([floor(n/50),5,n-maxit]);\nmaxstagsteps = 3;\nminupdated = 0;\n\nx0iszero = (norm(x) == 0);\nr = b - iterapp('mtimes',afun,atype,afcnstr,x,varargin{:});\nnormr = norm(r);                 % Norm of initial residual\nif (normr <= tolb)               % Initial guess is a good enough solution\n    flag = 0;\n    relres = normr / n2b;\n    iter = [0 0];\n    resvec = normr;\n    if (nargout < 2)\n        itermsg('gmres',tol,maxit,[0 0],flag,iter,relres);\n    end\n    return\nend\nminv_b = b;\n\nif existM1\n    \n%    r = P*r;\n    r = r-A*(ZH*(AH\\(ZH'*r)));\n    r = iterapp('mldivide',m1fun,m1type,m1fcnstr,r,varargin{:});\n    if ~x0iszero\n        \n        b0 = b-A*(ZH*(AH\\(ZH'*b)));\n        minv_b = iterapp('mldivide',m1fun,m1type,m1fcnstr,b0,varargin{:});\n    else\n        minv_b = r;\n    end\n    if ~all(isfinite(r)) || ~all(isfinite(minv_b))\n        flag = 2;\n        x = xmin;\n        relres = normr / n2b;\n        iter = [0 0];\n        resvec = normr;\n        return\n    end\nend\n\nif existM2\n    r = iterapp('mldivide',m2fun,m2type,m2fcnstr,r,varargin{:});\n    if ~x0iszero\n        minv_b = iterapp('mldivide',m2fun,m2type,m2fcnstr,minv_b,varargin{:});\n    else\n        minv_b = r;\n    end\n    if ~all(isfinite(r)) || ~all(isfinite(minv_b))\n        flag = 2;\n        x = xmin;\n        relres = normr / n2b;\n        iter = [0 0];\n        resvec = normr;\n        return\n    end\nend\n\nnormr = norm(r);                 % norm of the preconditioned residual\nn2minv_b = norm(minv_b);         % norm of the preconditioned rhs\nclear minv_b;\ntolb = tol * n2minv_b;\nif (normr <= tolb)               % Initial guess is a good enough solution\n    flag = 0;\n    relres = normr / n2minv_b;\n    iter = [0 0];\n    resvec = n2minv_b;\n    if (nargout < 2)\n        itermsg('gmres',tol,maxit,[0 0],flag,iter,relres);\n    end\n    return\nend\n\nresvec = zeros(inner*outer+1,1);  % Preallocate vector for norm of residuals\nresvec(1) = normr;                % resvec(1) = norm(b-A*x0)\nnormrmin = normr;                 % Norm of residual from xmin\n\n%  Preallocate J to hold the Given's rotation constants.\nJ = sparse(2,inner);\n\nU = sparse(n,inner);\nR = sparse(inner,inner);\nw = sparse(inner+1,1);\n\nfor outiter = 1 : outer\n    %  Construct u for Householder reflector.\n    %  u = r + sign(r(1))*||r||*e1\n    u = r;\n    normr = norm(r);\n    beta = scalarsign(r(1))*normr;\n    u(1) = u(1) + beta;\n    u = u / norm(u);\n    \n    U(:,1) = u;\n    \n    %  Apply Householder projection to r.\n    %  w = r - 2*u*u'*r;\n    w(1) = -beta;\n    \n    for initer = 1 : inner\n        %  Form P1*P2*P3...Pj*ej.\n        %  v = Pj*ej = ej - 2*u*u'*ej\n        v = -2*(u(initer)')*u;\n        v(initer) = v(initer) + 1;\n        %  v = P1*P2*...Pjm1*(Pj*ej)\n        for k = (initer-1):-1:1\n            v = v - U(:,k)*(2*(U(:,k)'*v));\n        end\n        %  Explicitly normalize v to reduce the effects of round-off.\n        v = v/norm(v);\n        \n        %  Apply A to v.\n        v = iterapp('mtimes',afun,atype,afcnstr,v,varargin{:});\n        %  Apply Preconditioner.\n        if existM1\n            \n            v = v-A*(ZH*(AH\\(ZH'*v)));\n            v = iterapp('mldivide',m1fun,m1type,m1fcnstr,v,varargin{:});\n            %v = P*v;\n            if ~all(isfinite(v))\n                flag = 2;\n                break\n            end\n        end\n        \n        if existM2\n            v = iterapp('mldivide',m2fun,m2type,m2fcnstr,v,varargin{:});\n            if ~all(isfinite(v))\n                flag = 2;\n                break\n            end\n        end\n        %  Form Pj*Pj-1*...P1*Av.\n        for k = 1:initer\n            v = v - U(:,k)*(2*(U(:,k)'*v));\n        end\n        \n        %  Determine Pj+1.\n        if (initer ~= length(v))\n            %  Construct u for Householder reflector Pj+1.\n            u = [zeros(initer,1); v(initer+1:end)];\n            alpha = norm(u);\n            if (alpha ~= 0)\n                alpha = scalarsign(v(initer+1))*alpha;\n                %  u = v(initer+1:end) +\n                %        sign(v(initer+1))*||v(initer+1:end)||*e_{initer+1)\n                u(initer+1) = u(initer+1) + alpha;\n                u = u / norm(u);\n                U(:,initer+1) = u;\n                \n                %  Apply Pj+1 to v.\n                %  v = v - 2*u*(u'*v);\n                v(initer+2:end) = 0;\n                v(initer+1) = -alpha;\n            end\n        end\n        \n        %  Apply Given's rotations to the newly formed v.\n        for colJ = 1:initer-1\n            tmpv = v(colJ);\n            v(colJ)   = conj(J(1,colJ))*v(colJ) + conj(J(2,colJ))*v(colJ+1);\n            v(colJ+1) = -J(2,colJ)*tmpv + J(1,colJ)*v(colJ+1);\n        end\n        \n        %  Compute Given's rotation Jm.\n        if ~(initer==length(v))\n            rho = norm(v(initer:initer+1));\n            J(:,initer) = v(initer:initer+1)./rho;\n            w(initer+1) = -J(2,initer).*w(initer);\n            w(initer) = conj(J(1,initer)).*w(initer);\n            v(initer) = rho;\n            v(initer+1) = 0;\n        end\n        \n        R(:,initer) = v(1:inner);\n        \n        normr = abs(w(initer+1));\n        resvec((outiter-1)*inner+initer+1) = normr;\n        normr_act = normr;\n        \n        if (normr <= tolb || stag >= maxstagsteps || moresteps)\n            if evalxm == 0\n                ytmp = R(1:initer,1:initer) \\ w(1:initer);\n                additive = U(:,initer)*(-2*ytmp(initer)*conj(U(initer,initer)));\n                additive(initer) = additive(initer) + ytmp(initer);\n                for k = initer-1 : -1 : 1\n                    additive(k) = additive(k) + ytmp(k);\n                    additive = additive - U(:,k)*(2*(U(:,k)'*additive));\n                end\n                if norm(additive) < eps*norm(x)\n                    stag = stag + 1;\n                else\n                    stag = 0;\n                end\n                xm = x + additive;\n                evalxm = 1;\n            elseif evalxm == 1\n                addvc = [-(R(1:initer-1,1:initer-1)\\R(1:initer-1,initer))*...\n                    (w(initer)/R(initer,initer)); w(initer)/R(initer,initer)];\n                if norm(addvc) < eps*norm(xm)\n                    stag = stag + 1;\n                else\n                    stag = 0;\n                end\n                additive = U(:,initer)*(-2*addvc(initer)*conj(U(initer,initer)));\n                additive(initer) = additive(initer) + addvc(initer);\n                for k = initer-1 : -1 : 1\n                    additive(k) = additive(k) + addvc(k);\n                    additive = additive - U(:,k)*(2*(U(:,k)'*additive));\n                end\n                xm = xm + additive;\n            end\n            r = b - iterapp('mtimes',afun,atype,afcnstr,xm,varargin{:});\n            if norm(r) <= tol*n2b\n                x = xm;\n                flag = 0;\n                iter = [outiter, initer];\n                break\n            end\n            minv_r = r;\n            if existM1\n                \n                %minv_r = P*minv_r;\n                minv_r = r-A*(ZH*(AH\\(ZH'*r)));\n                minv_r = iterapp('mldivide',m1fun,m1type,m1fcnstr,minv_r,varargin{:});\n                if ~all(isfinite(minv_r))\n                    flag = 2;\n                    break\n                end\n            end\n            if existM2\n                minv_r = iterapp('mldivide',m2fun,m2type,m2fcnstr,minv_r,varargin{:});\n                if ~all(isfinite(minv_r))\n                    flag = 2;\n                    break\n                end\n            end\n            \n            normr_act = norm(minv_r);\n            resvec((outiter-1)*inner+initer+1) = normr_act;\n            \n            if normr_act <= normrmin\n                normrmin = normr_act;\n                imin = outiter;\n                jmin = initer;\n                xmin = xm;\n                minupdated = 1;\n            end\n            \n            if normr_act <= tolb\n                x = xm;\n                flag = 0;\n                iter = [outiter, initer];\n                break\n            else\n                if stag >= maxstagsteps && moresteps == 0\n                    stag = 0;\n                end\n                moresteps = moresteps + 1;\n                if moresteps >= maxmsteps\n                    if ~warned\n                        warning(message('MATLAB:gmres:tooSmallTolerance'));\n                    end\n                    flag = 3;\n                    iter = [outiter, initer];\n                    break;\n                end\n            end\n        end\n        \n        if normr_act <= normrmin\n            normrmin = normr_act;\n            imin = outiter;\n            jmin = initer;\n            minupdated = 1;\n        end\n        \n        if stag >= maxstagsteps\n            flag = 3;\n            break;\n        end\n    end         % ends inner loop\n    \n    evalxm = 0;\n    \n    if flag ~= 0\n        if minupdated\n            idx = jmin;\n        else\n            idx = initer;\n        end\n        y = R(1:idx,1:idx) \\ w(1:idx);\n        additive = U(:,idx)*(-2*y(idx)*conj(U(idx,idx)));\n        additive(idx) = additive(idx) + y(idx);\n        for k = idx-1 : -1 : 1\n            additive(k) = additive(k) + y(k);\n            additive = additive - U(:,k)*(2*(U(:,k)'*additive));\n        end\n        x = x + additive;\n        xmin = x;\n        r = b - iterapp('mtimes',afun,atype,afcnstr,x,varargin{:});\n        minv_r = r;\n        if existM1\n            \n\n            minv_r = r-A*(ZH*(AH\\(ZH'*r)));\n            minv_r = iterapp('mldivide',m1fun,m1type,m1fcnstr,minv_r,varargin{:});\n            if ~all(isfinite(minv_r))\n                flag = 2;\n                break\n            end\n        end\n        if existM2\n            minv_r = iterapp('mldivide',m2fun,m2type,m2fcnstr,minv_r,varargin{:});\n            if ~all(isfinite(minv_r))\n                flag = 2;\n                break\n            end\n        end\n        normr_act = norm(minv_r);\n        r = minv_r;\n    end\n    \n    if normr_act <= normrmin\n        xmin = x;\n        normrmin = normr_act;\n        imin = outiter;\n        jmin = initer;\n    end\n    \n    if flag == 3\n        break;\n    end\n    if normr_act <= tolb\n        flag = 0;\n        iter = [outiter, initer];\n        break;\n    end\n    minupdated = 0;\nend         % ends outer loop\n\n% returned solution is that with minimum residual\nif flag == 0\n    relres = normr_act / n2minv_b;\nelse\n    x = xmin;\n    iter = [imin jmin];\n    relres = normr_act / n2minv_b;\nend\n\n% truncate the zeros from resvec\nif flag <= 1 || flag == 3\n    resvec = resvec(1:(outiter-1)*inner+initer+1);\n    indices = resvec==0;\n    resvec = resvec(~indices);\nelse\n    if initer == 0\n        resvec = resvec(1:(outiter-1)*inner+1);\n    else\n        resvec = resvec(1:(outiter-1)*inner+initer);\n    end\nend\n\n% only display a message if the output flag is not used\n% if nargout < 2\n%     if restarted\n%         itermsg(sprintf('gmres(%d)',restart),tol,maxit,[outiter initer],flag,iter,relres);\n%     else\n%         itermsg(sprintf('gmres'),tol,maxit,initer,flag,iter(2),relres);\n%     end\n% end\n\nfunction sgn = scalarsign(d)\nsgn = sign(d);\nif (sgn == 0)\n    sgn = 1;\nend\n\nfunction y = iterapp(op,afun,atype,afcnstr,x,varargin)\n%ITERAPP   Apply matrix operator to vector and error gracefully.\n%   ITERAPP(OP,AFUN,ATYPE,AFCNSTR,X) applies matrix operator AFUN to vector\n%   X. If ATYPE is 'matrix, then AFUN is a matrix and the OP is applied\n%   directly. OP is either 'mtimes' or 'mldivide'.\n%   ATYPE and AFCNSTR are used in case of error.\n%   ITERAPP(OP,AFUN,ATYPE,AFCNSTR,X,P1,P2,...) allows extra arguments to\n%   AFUN(X,P1,P2,...) although this usage is now discouraged in favor of\n%   using anonymous functions.\n%   AFUN(X,P1,P2,...,PN,TFLAG) should accept a TFLAG as its final input if\n%   the calling function is BICG, LSQR or QMR. TFLAG is either 'transp' or\n%   'notransp' depending on whether A' OP X or A OP X is required.\n%   ITERAPP is designed for use by iterative methods like PCG which\n%   require matrix operators AFUN representing matrices A to operate on\n%   vectors X and return A*X and may also have operators MFUN representing\n%   preconditioning matrices M operate on vectors X and return M\\X.\n%\n%   See also BICG, BICGSTAB, CGS, GMRES, LSQR, MINRES, PCG, QMR, SYMMLQ.\n\n%   Copyright 1984-2011 The MathWorks, Inc.\n%   $Revision: 1.7.4.8 $ $Date: 2011/05/17 02:33:16 $\n\nif strcmp(atype,'matrix')\n    switch lower(op)\n        case 'mtimes'\n            if (nargin >= 6) && isequal(varargin{end},'transp')\n                y = afun' * x;\n            else\n                y = afun * x;\n            end\n        case 'mldivide'\n            if (nargin >= 6) && isequal(varargin{end},'transp')\n                y = afun' \\ x;\n            else\n                y = afun \\ x;\n            end\n        otherwise\n            error(message('MATLAB:iterapp:InvalidOp'))\n    end\nelse\n    try\n        if (nargin >= 6) && isequal(varargin{end},'notransp')\n            % A request for A*x coming from BICG, LSQR and QMR\n            try\n                % New syntax: we now request afun(x,P1,P2,...,PN,'notransp')\n                y = afun(x,varargin{:});\n            catch\n                % Old syntax: we used to accept afun(x,P1,P2,...,PN)\n                y = afun(x,varargin{1:end-1});\n            end\n        else\n            % A request for A*x\n            % coming from BICGSTAB, CGS, GMRES, MINRES, PCG or SYMMLQ\n            % with the call always afun(P1,P2,...,PN)\n            % or a request for A'*x coming from\n            % BICG, LSQR and QMR in the afun(x,P1,P2,...,PN,'transp') case\n            y = afun(x,varargin{:});\n        end\n    catch ME\n        error(message('MATLAB:iterapp:InvalidInput', atype,afcnstr, ME.message));\n    end\n\n    if ~iscolumn(y)\n        error(message('MATLAB:iterapp:MustReturnColumn', atype, afcnstr));\n    end\nend\n\n\nfunction [atype,afun,afcnstr] = iterchk(A)\n%ITERCHK  Checks arguments to iterative methods.\n%   [ATYPE,AFUN,AFCNSTR] = ITERCHK(A) returns the following:\n%   ATYPE is either 'matrix', 'function', 'expression' or 'inline object'.\n%   AFUN is the function name or inline object.\n%   AFUN is '' if ATYPE is 'matrix'.\n%   AFCNSTR is the function name if ATYPE is 'function'.\n%   AFCNSTR is the formula of the function if ATYPE is 'expression' or\n%   'inline object'.  AFCNSTR is '' if ATYPE is 'matrix'.\n%\n%   See also BICG, BICGSTAB, CGS, GMRES, LSQR, MINRES, PCG, QMR, SYMMLQ.\n\n%   Copyright 1984-2004 The MathWorks, Inc. \n%   $Revision: 1.8.4.3 $ $Date: 2010/08/23 23:12:57 $\n\n\n[afun,afunmsg] = fcnchk(A);\nif isempty(afunmsg)\n   if isa(afun,'inline')      \n      if isa(A,'inline')\n         atype = 'inline object';\n      else\n         atype = 'expression';\n      end\n      afcnstr = formula(afun);\n   else % both function_handles @fun and function names 'fun'\n      atype = 'function';\n      if isa(A,'function_handle')\n          afcnstr = func2str(A);\n      else\n          afcnstr = A;\n      end\n   end\nelseif isa(A,'float')\n   afun = A;\n   atype = 'matrix';\n   afcnstr = '';\nelse\n   error(message('MATLAB:iterchk:InvalidInput'));\nend\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\n\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/solver/Pgmres_deflation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.5933020963075747}}
{"text": "function [ PD ] = PD_Orthogonal( X,a,SNR )\n%UNTITLED2 Summary of this function goes here\n%   Detailed explanation goes here\n[N,L] = size(X);\nRs = X*X'/L;\nrou = SNR*abs(a'*Rs.'*a)^2;\nPfa = 1e-7;\nita = chi2inv(1-Pfa,2);\nPD = 1-ncx2cdf(ita,2,rou);\nend\n\n", "meta": {"author": "yuanhao-cui", "repo": "Must-Reading-on-ISAC", "sha": "34cd6615c52ebca121428a979e756c608b195040", "save_path": "github-repos/MATLAB/yuanhao-cui-Must-Reading-on-ISAC", "path": "github-repos/MATLAB/yuanhao-cui-Must-Reading-on-ISAC/Must-Reading-on-ISAC-34cd6615c52ebca121428a979e756c608b195040/Codes/Fan2018TSP/Codes for DFRC Waveform Design/Waveform Design With Given Radar Beampatterns/PD_Orthogonal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5932842409653725}}
{"text": "function y=rfft(x,n,d)\n%RFFT     Calculate the DFT of real data Y=(X,N,D)\n% Data is truncated/padded to length N if specified.\n%   N even:\t(N+2)/2 points are returned with\n% \t\t\tthe first and last being real\n%   N odd:\t(N+1)/2 points are returned with the\n% \t\t\tfirst being real\n% In all cases fix(1+N/2) points are returned\n% D is the dimension along which to do the DFT\n\n\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: rfft.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\ns=size(x);\nif prod(s)==1\n    y=x\nelse\n    if nargin <3 || isempty(d)\n        d=find(s>1,1);\n        if nargin<2\n            n=s(d);\n        end\n    end\n    if isempty(n) \n        n=s(d);\n    end\n    y=fft(x,n,d);\n    y=reshape(y,prod(s(1:d-1)),n,prod(s(d+1:end))); \n    s(d)=1+fix(n/2);\n    y(:,s(d)+1:end,:)=[];\n    y=reshape(y,s);\nend\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/rfft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5932842409653724}}
{"text": "function hc = binHistIndep(mu)\n% hc = binHistIndep(mu)\n% \tComputes expected histogram under independence assumption\n%   P(X)=PROD(P(x_i))\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\n\n% generate all possible binary patterns\nn = size(mu,1);\nc = 0:2^n-1;\npattern = zeros(n,size(c,2));\n\nfor i=n:-1:1\n    idx = c>=2^(i-1);\n    pattern(i,idx)=1;\n    c(idx) = c(idx) - 2^(i-1);    \nend\n\npattern = flipud(pattern);\n\n% transform to probabilities\nmu = mu/2+.5;\n\n% find relevant probabilities for independent model\npMat = (repmat(mu,1,size(pattern,2)).*pattern) + (repmat(1-mu,1,size(pattern,2)).* (~pattern));\n\n% calculate histogram\nhc = prod(pMat);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/20591-sampling-from-multivariate-correlated-binary-and-poisson-random-variables/lib/binHistIndep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5932842169052717}}
{"text": "function ret = nonlinear(chrom,sizepop)\n\nfor i=1:sizepop\n    x=fmincon(inline('-5*sin(x(1))*sin(x(2))*sin(x(3))*sin(x(4))*sin(x(5))-sin(5*x(1))*sin(5*x(2))*sin(5*x(3))*sin(5*x(4))*sin(5*x(5))'),chrom(i,:)',[],[],[],[],[0 0 0 0 0],[2.8274 2.8274 2.8274 2.8274 2.8274]);\n    ret(i,:)=x';\nend\n\n\n\n", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/MATLAB\u667a\u80fd\u7b97\u6cd530\u4e2a\u6848\u4f8b\u5206\u6790/chapter2 \u57fa\u4e8e\u9057\u4f20\u7b97\u6cd5\u548c\u975e\u7ebf\u6027\u89c4\u5212\u7684\u51fd\u6570\u5bfb\u4f18\u7b97\u6cd5/\u6848\u4f8b1\u975e\u7ebf\u6027/nonlinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5932492960349798}}
{"text": "function [cIX,gIX] = GrowClustersFromSeedsItr(thres_merge,thres_cap,thres_minsize,cIX,gIX,M_0)\n%disp('find ROIs')\n\n% Set params\n\n% may be determined by hist of distances between all cells (in a sample)\n% in correlation distance, i.e. 1 - corr.coeff\n% thres_merge = 0.4;\n% thres_cap = 0.5;\n\n% thres_minsize = 10; % cell number in final clusters\n\n%%\ngIX = SqueezeGroupIX(gIX);\nM = M_0(cIX,:);\nC = FindCentroid_Direct(gIX,M); % import functional supervoxels ('foxel')\nnFoxels = size(C,1);\n\n%% Calculate correlation distance between all cluster-centroids\ntemp = pdist(C,'correlation');\nDist = squareform(temp);\nfor i = 1:nFoxels,\n    Dist(i,i) = NaN;\nend\n\n%% ITERATION:\n% initialize\nROI = [];\nROI(nFoxels).fxlist = []; % not capping\nROI(nFoxels).numcell = [];\nROIcount = 0;\n\n% analogy ~ mask to store new ROI\nBW = zeros(nFoxels,1); \n\n%%\n\nwhile true, % loop through all qualified seeds           \n    % look for next seed\n    [~,ix] = min(Dist(:));\n    [I,J] = ind2sub(size(Dist),ix);\n    % and add seed position to mask\n    BW(I) = 1;\n    BW(J) = 1;\n    \n    if Dist(I,J)>(1-thres_merge),\n        break;\n    end\n    \n    while true % grow ROI: expand mask and examine next neighbors\n        IX_in = find(BW);\n        IX_out = find(BW==0);\n\n        % find next closest foxel\n        D = 1-corr(C(IX_in,:)',C(IX_out,:)'); % distance matrix between potential foxels to foxels already included in ROI\n        if isempty(D),\n            break;\n        end\n        D2 = min(D,[],1);\n        [a,ix] = min(D2);\n        ix_pretend = IX_out(ix);\n        \n        BW_pretend = BW;\n        BW_pretend(ix_pretend) = 1;\n        \n        % find correlation between potential foxel and new core\n        list = find(BW_pretend);\n        IX = [];\n        for i_gIX = 1:length(list),\n            IX = [IX;find(gIX==list(i_gIX))];\n        end\n        M_core = M(IX,:);\n        [~,newCore] = kmeans(M_core,1,'distance','correlation');                \n        coredist = 1-corr(C(ix_pretend,:)',newCore');\n        \n        if a<(1-thres_merge) && coredist<(1-thres_cap),\n            BW(ix_pretend) = 1;\n        else\n            break; % finished expanding this seed\n        end\n    end\n    \n    % save this ROI if bigger than thres\n    list = find(BW);\n    IX = [];\n    for i_gIX = 1:length(list),\n        IX = [IX;find(gIX==list(i_gIX))]; %#ok<AGROW>\n    end\n    numcell = length(IX);\n    if numcell >= thres_minsize,\n        ROIcount = ROIcount+1;\n        ROI(ROIcount).fxlist = find(BW);\n        ROI(ROIcount).numcell = numcell;\n    end\n    \n    % update/reset\n    Dist(list,:) = NaN;\n    Dist(:,list) = NaN;\n    C(list,:) = NaN;\n    BW = zeros(nFoxels,1);\n    \n    if isempty(find(isnan(Dist)==0)),\n        break;\n    end\nend\n\nROI(ROIcount+1:end) = [];\n\n%% Merge accordingly\nfor i = 1:ROIcount,\n    fxlist = ROI(i).fxlist;\n    for j = 2:length(fxlist),\n        gIX(gIX==fxlist(j)) = fxlist(1);\n    end\nend\n[gIX,numU] = SqueezeGroupIX(gIX);\n%disp(numU);\n\nend\n\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/old code/older versions/GrowClustersFromSeedsItr_mindist_dislike.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5932492923663855}}
{"text": "function calpak_test636 ( )\n\n%*****************************************************************************80\n%\n%% CALPAK_TEST636 tests YEAR_TO_SCALIGER_COMMON.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    13 April 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CALPAK_TEST636\\n' );\n  fprintf ( 1, '  For a Common year,\\n' );\n  fprintf ( 1, '  YEAR_TO_SCALIGER_COMMON determines the Scaliger indices.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Year  Julian / Metonic / Indiction\\n' );\n  fprintf ( 1, '\\n' );\n\n  for y = -4713 : -4675\n\n    y2 = y_astronomical_to_common ( y );\n    sy = y_to_s_common ( y2 );\n    [ c1, c2, c3, r1, r2, r3 ] = year_to_scaliger_common ( y2 );\n    fprintf ( 1, '  %10s  %3d  %3d    %3d  %3d    %3d  %3d\\n', ...\n    sy, c1, r1, c2, r2, c3, r3 );\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/calpak/calpak_test636.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5932179273033674}}
{"text": "function varargout = fastind2sub(siz,ndx)\n%\"fastind2sub\"\n%   FAST ind2sub is a faster version of ind2sub, based off the ind2sub that\n%   ships with matlab.  Only one line is changed, and the original doc for\n%   ind2sub is included below.\n%\n%   JRA 2/26/04\n%\n%IND2SUB Multiple subscripts from linear index.\n%\n%   IND2SUB is used to determine the equivalent subscript values\n%   corresponding to a given single index into an array.\n%\n%   [I,J] = IND2SUB(SIZ,IND) returns the arrays I and J containing the\n%   equivalent row and column subscripts corresponding to the index\n%   matrix IND for a matrix of size SIZ.  \n%   For matrices, [I,J] = IND2SUB(SIZE(A),FIND(A>5)) returns the same\n%   values as [I,J] = FIND(A>5).\n%\n%   [I1,I2,I3,...,In] = IND2SUB(SIZ,IND) returns N subscript arrays\n%   I1,I2,..,In containing the equivalent N-D array subscripts\n%   equivalent to IND for an array of size SIZ.\n%\n%   See also SUB2IND, FIND.\n \n%   Copyright 1984-2002 The MathWorks, Inc. \n%   $Revision: 1.3 $  $Date: 2008/10/08 21:38:59 $\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nnout = max(nargout,1);\nif length(siz)<=nout,\n  siz = [siz ones(1,nout-length(siz))];\nelse\n  siz = [siz(1:nout-1) prod(siz(nout:end))];\nend\nn = length(siz);\nk = [1 cumprod(siz(1:end-1))];\nndx = ndx - 1;\nfor i = n:-1:1,\n  varargout{i} = floor(ndx/k(i))+1;\n  ndx = ndx - (varargout{i}-1)*k(i);\n  \n%  This is the old method: slow because it\n%  recalculates the division after it has already been found above.  \n%  ndx = rem(ndx,k(i));\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/fastind2sub.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.5932179205169038}}
{"text": "function [ t, rank ] = ksubset_colex_successor ( k, n, t, rank )\n\n%*****************************************************************************80\n%\n%% KSUBSET_COLEX_SUCCESSOR computes the K subset colex successor.\n%\n%  Discussion:\n%\n%    In the original code, there is a last element with no successor.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    24 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 K, the number of elements each K subset must\n%    have.  1 <= K <= N.\n%\n%    Input, integer N, the number of elements in the master set.\n%    N must be positive.\n%\n%    Input/output, integer T(K), describes a K subset.  T(I) is the\n%    I-th element.  The elements must be listed in DESCENDING order.\n%    On input, T describes a K subset.\n%    On output, T describes the next K subset in the ordering.\n%    If the input T was the last in the ordering, then the output T\n%    will be the first.\n%\n%    Input/output, integer RANK, the rank.\n%    If RANK = -1 on input, then the routine understands that this is\n%    the first call, and that the user wishes the routine to supply\n%    the first element in the ordering, which has RANK = 0.\n%    In general, the input value of RANK is increased by 1 for output,\n%    unless the very last element of the ordering was input, in which\n%    case the output value of RANK is 0.\n%\n\n%\n%  Return the first element.\n%\n  if ( rank == -1 )\n    for i = 1 : k\n      t(i) = k + 1 - i;\n    end\n    rank = 0;\n    return\n  end\n%\n%  Check.\n%\n  ierror = ksubset_colex_check ( k, n, t );\n\n  if ( ierror ~= 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'KSUBSET_COLEX_SUCCESSOR - Fatal error!\\n' );\n    fprintf ( 1, '  The input array is illegal.\\n' );\n    fprintf ( 1, '  IERROR = %d\\n', ierror );\n    error ( 'KSUBSET_COLEX_SUCCESSOR - Fatal error!' );\n  end\n\n  for i = k - 1 : -1 : 1\n    if ( t(k+1-i) + 1 < t(k-i) )\n      t(k+1-i) = t(k+1-i) + 1;\n      rank = rank + 1;\n      return\n    end\n  end\n\n  if ( t(1) < n )\n    t(1) = t(1) + 1;\n    for i = 1 : k - 1\n      t(k+1-i) = i;\n    end\n    rank = rank + 1;\n    return\n  end\n%\n%  The last K subset was input.\n%  Return the first one.\n%\n  for i = 1 : k\n    t(i) = k + 1 - i;\n  end\n\n  rank = 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/combo/ksubset_colex_successor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.5932179137304397}}
{"text": "function [dpsi, deps] = nut2000a (date1, date2)\n\n% nutation based on iau 2000a theory\n\n% input\n\n%  date1, date2 = tt julian date\n%  (julian date = date1 + date2)\n\n% output\n\n%  dpsi = nutation in longitude in radians\n\n%  deps = nutation in obliquity in radians\n\n% reference\n\n%  Nutation Series Evaluation in NOVAS 3.0\n%  USNO Circular No. 181, December 15, 2009\n\n% ported from NOVAS 3.0 Fortran subroutine\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal jplephem_inutate nals napl icpl cls\n\nif (jplephem_inutate == 1)\n\n    % read data files\n\n    nals = csvread('nals.csv');\n\n    napl = csvread('napl.csv');\n\n    icpl = csvread('icpl.csv');\n\n    cls = csvread('cls.csv');\n\n    % transpose matrices\n\n    nals = nals';\n\n    napl = napl';\n\n    icpl = icpl';\n\n    cls = cls';\n\n    % reset flag\n\n    jplephem_inutate = 0;\n\nend\n\n% arc seconds to radians\n\ndas2r = 4.848136811095359935899141d-6;\n\n% arc seconds in a full circle\n\nturnas = 1296000.0d0;\n\n% 2 * pi\n\nd2pi = 6.283185307179586476925287d0;\n\n% units of 0.1 microarcsecond to radians\n\nu2r = das2r / 1.0d7;\n\n% reference epoch (j2000)\n\ndj0 = 2451545.0d0;\n\n% days per julian century\n\ndjc = 36525.0d0;\n\n% -------------------------\n% luni-solar nutation model\n% -------------------------\n\n%  ---------------\n%  planetary terms\n%  ---------------\n\n% interval between fundamental epoch j2000.0 and given date (jc)\n\nt = ((date1 - dj0) + date2) / djc;\n\n% -------------------\n% luni-solar nutation\n% -------------------\n\n% fundamental (delaunay) arguments from simon et al. (1994)\n\n% mean anomaly of the moon (radians)\n\nel = mod (485868.249036d0 + t * (1717915923.2178d0 ...\n    + t * (31.8792d0 + t * (0.051635d0 ...\n    + t * (-0.00024470d0)))), turnas) * das2r;\n\n% mean anomaly of the sun (radians)\n\nelp = mod (1287104.79305d0 + t * (129596581.0481d0 ...\n    + t * (-0.5532d0 + t * (0.000136d0 ...\n    + t * (-0.00001149d0)))), turnas) * das2r;\n\n% mean argument of the latitude of the moon (radians)\n\nf = mod (335779.526232d0 + t * (1739527262.8478d0 ...\n    + t * (-12.7512d0 + t * (-0.001037d0 ...\n    + t * (0.00000417d0)))), turnas) * das2r;\n\n% mean elongation of the moon from the sun (radians)\n\nd = mod (1072260.70369d0 + t * (1602961601.2090d0 ...\n    + t * (-6.3706d0 + t * (0.006593d0 ...\n    + t * (-0.00003169d0)))), turnas) * das2r;\n\n% mean longitude of the ascending node of the moon (radians)\n\nom = mod (450160.398036d0 + t * (-6962890.5431d0 ...\n    + t * (7.4722d0 + t * (0.007702d0 ...\n    + t * (-0.00005939d0)))), turnas) * das2r;\n\n% summation of luni-solar nutation series (in reverse order)\n\narg = mod ((nals(1, :)) * el  + (nals(2, :)) * elp + (nals(3, :)) * f ...\n    + (nals(4, :)) * d  + (nals(5, :)) * om, d2pi);\n\nsarg = sin(arg);\n\ncarg = cos(arg);\n\ndp = sum((cls(1,:) + cls(2,:) * t) .* sarg + cls(3,:) .* carg);\n\nde = sum((cls(4,:) + cls(5,:) * t) .* carg + cls(6,:) .* sarg);\n\n% convert from 0.1 microarcsec units to radians\n\ndpsils = dp * u2r;\n\ndepsls = de * u2r;\n\n% ------------------\n% planetary nutation\n% ------------------\n\n% mean anomaly of the moon (radians)\n\nal = mod (2.35555598d0 + 8328.6914269554d0 * t, d2pi);\n\n% mean anomaly of the sun (radians)\n\nalsu = mod (6.24006013d0 + 628.301955d0 * t, d2pi);\n\n% mean argument of the latitude of the moon (radians)\n\naf = mod (1.627905234d0 + 8433.466158131d0 * t, d2pi);\n\n% mean elongation of the moon from the sun (radians)\n\nad = mod (5.198466741d0 + 7771.3771468121d0 * t, d2pi);\n\n% mean longitude of the ascending node of the moon (radians)\n\naom = mod (2.18243920d0 - 33.757045d0 * t, d2pi);\n\n% general accumulated precession in longitude (radians)\n\napa = (0.02438175d0 + 0.00000538691d0 * t) * t;\n\n% planetary longitudes, mercury through neptune (souchay et al. 1999)\n\nalme = mod (4.402608842d0 + 2608.7903141574d0 * t, d2pi);\n\nalve = mod (3.176146697d0 + 1021.3285546211d0 * t, d2pi);\n\nalea = mod (1.753470314d0 +  628.3075849991d0 * t, d2pi);\n\nalma = mod (6.203480913d0 +  334.0612426700d0 * t, d2pi);\n\nalju = mod (0.599546497d0 +   52.9690962641d0 * t, d2pi);\n\nalsa = mod (0.874016757d0 +   21.3299104960d0 * t, d2pi);\n\nalur = mod (5.481293871d0 +    7.4781598567d0 * t, d2pi);\n\nalne = mod (5.321159000d0 +    3.8127774000d0 * t, d2pi);\n\n% summation of planetary nutation series (in reverse order)\n\narg = mod ((napl(1, :)) * al + (napl(2, :)) * alsu + (napl(3, :)) * af ...\n    + (napl(4, :)) * ad + (napl(5, :)) * aom  + (napl(6, :)) * alme ...\n    + (napl(7, :)) * alve + (napl(8, :)) * alea + (napl(9, :)) * alma ...\n    + (napl(10, :)) * alju + (napl(11, :)) * alsa + (napl(12, :)) * alur ...\n    + (napl(13, :)) * alne + (napl(14, :)) * apa, d2pi);\nsarg = sin(arg);\n\ncarg = cos(arg);\n\ndp = sum((icpl(1,:)) .* sarg + (icpl(2,:)) .* carg);\n\nde = sum((icpl(3,:)) .* sarg + (icpl(4,:)) .* carg);\n\n% convert from 0.1 microarcsec units to radians\n\ndpsipl = dp * u2r;\n\ndepspl = de * u2r;\n\n% add planetary and luni-solar components\n\ndpsi = dpsipl + dpsils;\n\ndeps = depspl + depsls;\n\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/sun_moon/novas/nut2000a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5931958221131355}}
{"text": "function test_example_glm_nirs\n\n% MEM 4gb\n% WALLTIME 00:10:00\n\n%% Using GLM to analyze NIRS timeseries data\n%\n% This is an example MATLAB script that demonstrates how to compute a simple GLM on the fingertapping NIRS data that is also used in the tutorial on [preprocessing and averaging of single-channel NIRS data](/tutorial/nirs_singlechannel). The data is available from our [FTP server](ftp://ftp.fieldtriptoolbox.org/pub/fieldtrip/tutorial/nirs_singlechannel/).\n%\n% We start with reading the NIRS data from disk.\n%\ncfg = [];\ncfg.dataset = dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/nirs_singlechannel/motor_cortex.oxy3');\ndata_nirs = ft_preprocessing(cfg);\n\n%% # Construct a number of additional channels with the task/stimulus details\n%\n% Then we read the events, which are represented as markers or triggers, indicating the samples in the data in which the fingertapping started or stopped. We use these to make some additional continuously represented channels that represent the onset, offset, and the motion. Furthermore, we can add two channels for a constant offset, and for a slope. These can be used to remove the baseline and a constant drift in the signal over time.\n%\nevent = ft_read_event(cfg.dataset);\n\ndata_stim = [];\ndata_stim.time = data_nirs.time;\ndata_stim.label = {\n  'onset'\n  'offset'\n  'motion'\n  'constant'\n  'slope'\n  };\ndata_stim.chantype = repmat({'stimulus'}, size(data_stim.label));  % Homer stires the experimental design as stimulus (s)\ndata_stim.chanunit = repmat({'unknown'}, size(data_stim.label));\n\nmove_onset  = [event(strcmp({event.value}, 'A')).sample]; % this indicates the beginning of the movement\nmove_offset = [event(strcmp({event.value}, 'B')).sample]; % this indicates the end of the movement\n\nnchans   = length(data_stim.label);\nnsamples = length(data_stim.time{1}); % it is a continous representation, hence one trial/segment\n\ndata_stim.trial{1} = zeros(nchans, nsamples);\ndata_stim.trial{1}(1,move_onset)  = 1;\ndata_stim.trial{1}(2,move_offset) = 1;\nfor i=1:numel(move_onset)\n  data_stim.trial{1}(3,move_onset(i):move_offset(i)) = 1;\nend\ndata_stim.trial{1}(4,:) = ones(1,nsamples);\ndata_stim.trial{1}(5,:) = linspace(0,1,nsamples);\n\n% show the experimental design as a matrix\nfigure\nimagesc(data_stim.trial{1})\n\n%\n% You actually have to zoom in a lot to see all details, since there are more samples than horizontal pixels on your screen\n%\n%% # Combine the NIRS data and the description of the task/stimulus details\n%\ncfg = [];\ndata_combined = ft_appenddata(cfg, data_nirs, data_stim);\n\n% also keep the optode structure, we need it further down for fieldtrip2homer and plotting\ndata_combined.opto = data_nirs.opto;\n\n%% # Perform a GLM analysis\n%\n% This is explained on http://mri-q.com/general-linear-model.html with an excelent introduction, and\n% on https://www.brainvoyager.com/bv/doc/UsersGuide/StatisticalAnalysis/TheGeneralLinearModel.html.\n%\nclose all\n\n% take the data from the FieldTrip data structures\ny = cat(2, data_nirs.trial{:})';\nx = cat(2, data_stim.trial{:})';\n\n% After further processing and artifact removal you could also take them from the `data_combined` structure, which would ensure that they keep nicely aligned - also when you discard artifact segments. But here we simply include all samples.\n%\n% use the default canonical haemodynamic response function (HRF) from SPM\nft_hastoolbox('spm12', 1);\nh = spm_hrf(1/data_nirs.fsample);\n\n% plot the original regressor\nfigure\nplot(x(:,3), 'b')\nhold on\ntitle('model')\n\n% convolve the design with the HRF\nxc = convn(x', h')';\nxc = xc(1:nsamples,:); % remove the trailing part\n% replace the first three columns of the design with the HRF convolved version\nx(:,1:3) = xc(:,1:3);\n\n% plot the HRF convolved regressor\nplot(x(:,3), 'r-')\n\n%\n% Remove the baseline, see also **[ft_preproc_baselinecorrect](https://github.com/fieldtrip/fieldtrip/blob/release/preproc/ft_preproc_baselinecorrect.m)** and **[ft_preproc_detrend](https://github.com/fieldtrip/fieldtrip/blob/release/preproc/ft_preproc_detrend.m)**. This is beneficial here, since the experimental regressors are not orthogonal to the confound regressors.\n%\ny = ft_preproc_polyremoval(y', 2)';\n\n% fit the general linear model (GLM)\n% y = x * b + e\nb     = x \\ y;\nmodel = x * b;\ne     = y - model;\n\nchan = find(strcmp(data_nirs.label, 'Rx4b-Tx5 [860nm]'));\n\nfigure\nhold on\nplot(y(:,chan), 'b')\nplot(e(:,chan), 'g')\nplot(model(:,chan), 'r', 'linewidth', 2)\n%set(h, 'LineWidth', 1)\nlegend({'data', 'noise', 'model'});\ntitle('fit to data')\n\n%\n%% # Convert the fitted model into statistical parameters\n%\n[n,p] = size(x);\nr2 = var(model)./var(y);\nf = r2*(n-p) ./ ((1-r2)*(p-1));\nc = [0 0 1 0 0]';\nt = (c' * b) ./ sqrt(var(e) * (c' * (x'*x) * c));\n\n% It would be possible to make topographic maps of these t-values.\n%\n%% # Doing the same using the Homer data representation\n%\n% We can also do this analysis using the Homer data representation. For that we can convert the data from FieldTrip to Homer\n%\nnirs = fieldtrip2homer(data_combined);\n\n% and then take the data matrix |y| and the experimental design matrix |x|\n%\ny = nirs.d;\nx = nirs.s;\n\n% Subsequently we could continue as above ...\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_example_nirs_glm20220113.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867825403177, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5931868816812914}}
{"text": "function [nautmi] = ft2nautmi(ft)\n% Convert length from feet to nautical miles.\n% Chad Greene 2012\nnautmi = ft*0.0001645788336933;", "meta": {"author": "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/ft2nautmi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5931868690328372}}
{"text": "function varargout = drawVector3d(pos, vect, varargin)\n%DRAWVECTOR3D Draw vector at a given position\n%\n%   drawVector3d(POS, VECT)\n%   Draws the vector VECT starting at the position POS. Both VECT and POS\n%   are N-by-3 arrays.\n%\n%   drawVector3d(..., PNAME, PVALUE)\n%   Specifies additional optional parameters that will be given to the\n%   quiver3 function.\n%\n%   Example\n%     figure; hold on;\n%     drawVector3d([2 3 4], [1 0 0]);\n%     drawVector3d([2 3 4], [0 1 0]);\n%     drawVector3d([2 3 4], [0 0 1]);\n%     view(3);\n%\n%   See also\n%   vectors3d, quiver3\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@nantes.inra.fr\n% Created: 2011-12-19,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\nh = quiver3(pos(:, 1), pos(:, 2), pos(:, 3), ...\n    vect(:, 1), vect(:, 2), vect(:, 3), 0, varargin{:});\n\n% format output\nif nargout > 0\n    varargout{1} = h;\nend\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom3d/drawVector3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5930972288415673}}
{"text": "function bvec_mul_test ( )\n\n%*****************************************************************************80\n%\n%% BVEC_MUL_TEST tests BVEC_MUL;\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 January 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 15;\n  seed = 123456789;\n  test_num = 10;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'BVEC_MUL_TEST\\n' );\n  fprintf ( 1, '  BVEC_MUL multiplies binary vectors \\n' );\n  fprintf ( 1, '  representing integers;\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '        I        J        I * J   BVEC_MUL\\n' );\n  fprintf ( 1, '\\n' );\n\n  for test = 1 : test_num\n    \n    [ i, seed ] = i4_uniform_ab ( -100, 100, seed );\n    [ j, seed ] = i4_uniform_ab ( -100, 100, seed );\n\n    k = i * j;\n\n    bvec1 = i4_to_bvec ( i, n );\n    bvec2 = i4_to_bvec ( j, n );\n    bvec3 = bvec_mul ( n, bvec1, bvec2 );\n    l = bvec_to_i4 ( n, bvec3 );\n\n    fprintf ( 1, '  %8d  %8d  %8d  %8d\\n', i, j, k, l );\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/bvec/bvec_mul_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5930972249999802}}
{"text": "function [s, m_v, zero_idx] = get_central_ula_size(diffs)\n%GET_CENTRAL_ULA_SIZE Obtains the size of the ULA centered at the origin\n%from the difference coarray.\n%Syntax:\n%   s = GET_CENTRAL_ULA_SIZE(diffs);\n%   [s, m_v, zero_idx] = GET_CENTRAL_ULA_SIZE(diffs);\n%Input:\n%   diffs - A vector of integer differences, or array design.\n%Outputs:\n%   s - Entire array size = 2*M_v - 1.\n%   m_v - The size of the ULA after trimming the negative part.\n%   zero_idx - Index of the zero element in diffs.\n\nif isstruct(diffs)\n    % convert array design to unique differences\n    diffs = unique_differences(diffs.element_indices);\nend\n\nw = 0;\nzero_idx = find(diffs == 0);\nn_diff = length(diffs);\nwhile zero_idx + w < n_diff && zero_idx - w > 1\n    w = w + 1;\n    if (diffs(zero_idx+w) - diffs(zero_idx+w-1) ~= 1) || (diffs(zero_idx-w+1) - diffs(zero_idx-w)) ~= 1\n        w = w - 1;\n        break;\n    end\nend\nm_v = w + 1;\ns = 2*m_v - 1;\n\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/array/get_central_ula_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.5930972134752182}}
{"text": "%% file example_rMTFL.m\n% this file shows the usage of Least_rMTFL.m function \n% and study how to detect outlier tasks. \n%\n%% OBJECTIVE\n%  argmin_W ||X(P+Q) - Y||_F^2 + lambda1*||P||_{1,2} + lambda2*||Q^T||_{1,2}\n%   s.t. W = P + Q\n%\n%% Copyright (C) 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 April 16, 2012.\n%\n%% Related papers\n%\n% [1] Gong, P. and Ye, J. and Zhang, C. Robust Multi-Task Feature Learning,\n% Submitted, 2012\n%\n\nclear;\nclc;\nclose all;\n\naddpath('../MALSAR/functions/rMTFL/'); % load function \naddpath('../MALSAR/utils/'); % load utilities\n\n%rng('default');     % reset random generator. Available from Matlab 2011.\n\n%generate synthetic data.\ndimension = 500;\nsample_size = 50;\ntask = 50;\nX = cell(task ,1);\nY = cell(task ,1);\nfor i = 1: task\n    X{i} = rand(sample_size, dimension);\n    Y{i} = rand(sample_size, 1);\nend\n\nopts.init = 0;      % guess start point from data. \nopts.tFlag = 1;     % terminate after relative objective value does not changes much.\nopts.tol = 10^-6;   % tolerance. \nopts.maxIter = 500; % maximum iteration number of optimization.\n\nrho_1 = 90;%   rho1: P\nrho_2 = 280; %   rho2: Q\n\n[W funcVal P Q] = Least_rMTFL(X, Y, rho_1, rho_2, opts);\n\n\n\n% draw figure\nclose;\nfigure();\nsubplot(3,1,1);\n%imshow(1- (abs(S')~=0), 'InitialMagnification', 'fit');\nimshow(P'==0, 'InitialMagnification', 'fit')\nylabel('P^T (feature)');\ntitle('Visualization of Robust Multi-Task Feature Learning Model');\nsubplot(3,1,2);\n%imshow(1- (zscore(L')), 'InitialMagnification', 'fit')\nimshow(Q'==0, 'InitialMagnification', 'fit')\nylabel('Q^T (outliers)');\nsubplot(3,1,3);\n%imshow(1- (zscore(W')), 'InitialMagnification', 'fit')\nimshow(W'==0, 'InitialMagnification', 'fit')\nylabel('W^T');\nxlabel('Dimension')\nprint('-dpdf', '-r600', 'LeastrMTFLExp');\n", "meta": {"author": "jiayuzhou", "repo": "MALSAR", "sha": "fb9751594983df020ddc4f7e4a40520ee7c37989", "save_path": "github-repos/MATLAB/jiayuzhou-MALSAR", "path": "github-repos/MATLAB/jiayuzhou-MALSAR/MALSAR-fb9751594983df020ddc4f7e4a40520ee7c37989/examples/example_rMTFL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5930427316322844}}
{"text": "function [assignment, cost] = assignmentoptimal(distMatrix)\n%ASSIGNMENTOPTIMAL    Compute optimal assignment by Munkres algorithm\n%\t\tASSIGNMENTOPTIMAL(DISTMATRIX) computes the optimal assignment for the\n%\t\tgiven rectangular distance (or weight) matrix, for example the assignment \n%\t\tof tracks (in rows) to observations (in columns). The result is a column \n%\t\tvector containing the assigned column number in each row (or 0 if no \n%\t\tassignment could be done).\n%\n%\t\t[ASSIGNMENT, COST] = ASSIGNMENTOPTIMAL(DISTMATRIX) returns the assignment\n%\t\tvector and the overall cost.\n%\n%\t\tThe distance matrix may contain infinite values (forbidden\n%\t\tassignments). Internally, the infinite values are set to a very large\n%\t\tfinite number, so that the Munkres algorithm itself works on finite-number\n%\t\tmatrices. Before returning the assignment, all assignments with infinite \n%\t\tdistance are deleted (i.e. set to zero).\n%\n%\t\tA description of Munkres algorithm (also called Hungarian algorithm) can\n%\t\teasily be found on the web.\n%\n%\t\tWritten by Markus Buehren, www.Lss.uni-stuttgart.de\n%\t\tLast modified 14.12.2004\n\n% save original distMatrix for cost computation\noriginalDistMatrix    = distMatrix;\n\n% check for negative elements\nif any(distMatrix(:) < 0)\n\terror('All matrix elements have to be non-negative.');\nend\n\n% get matrix dimensions\n[nOfRows, nOfColumns] = size(distMatrix);\n\n% check for infinite values\nfiniteIndex   = isfinite(distMatrix);\ninfiniteIndex = find(~finiteIndex);\nif ~isempty(infiniteIndex)\n\t% set infinite values to large finite value\n\tmaxFiniteValue = max(max(distMatrix(finiteIndex)));\n\tif maxFiniteValue > 0\n\t\tinfValue = abs(10 * maxFiniteValue * nOfRows * nOfColumns);\n\telse\n\t\tinfValue = 10;\n\tend\n\tif isempty(infValue)\n\t\t% all elements are infinite\n\t\tassignment = zeros(nOfRows, 1);\n\t\tcost       = 0;\n\t\treturn\n\tend\t\n\tdistMatrix(infiniteIndex) = infValue;\nend\n\n% memory allocation\ncoveredColumns = zeros(1,nOfColumns);\ncoveredRows    = zeros(nOfRows,1);\nstarMatrix     = zeros(nOfRows, nOfColumns);\nprimeMatrix    = zeros(nOfRows, nOfColumns);\n\n% preliminary steps\nif nOfRows <= nOfColumns\n\tminDim = nOfRows;\n\t\n\t% find the smallest element of each row\n\tminVector = min(distMatrix,[],2);\n\t\n\t% subtract the smallest element of each row from the row\n\tdistMatrix = distMatrix - repmat(minVector, 1, nOfColumns);\n\t\n\t% Steps 1 and 2\n\tfor row = 1:nOfRows\n\t\tfor col = find(distMatrix(row,:)==0)\n\t\t\tif ~coveredColumns(col)%~any(starMatrix(:,col))\n\t\t\t\tstarMatrix(row, col) = 1;\n\t\t\t\tcoveredColumns(col)  = 1;\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\tend\n\t\nelse % nOfRows > nOfColumns\n\tminDim = nOfColumns;\n\t\n\t% find the smallest element of each column\n\tminVector = min(distMatrix);\n\t\n\t% subtract the smallest element of each column from the column\n\tdistMatrix = distMatrix - repmat(minVector, nOfRows, 1);\n\t\n\t% Steps 1 and 2\n\tfor col = 1:nOfColumns\n\t\tfor row = find(distMatrix(:,col)==0)'\n\t\t\tif ~coveredRows(row)\n\t\t\t\tstarMatrix(row, col) = 1;\n\t\t\t\tcoveredColumns(col)  = 1;\n\t\t\t\tcoveredRows(row)     = 1;\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\tend\n\tcoveredRows(:) = 0; % was used auxiliary above\n\t\nend\n\nif sum(coveredColumns) == minDim\n\t% algorithm finished\n\tassignment = buildassignmentvector__(starMatrix);\nelse\n\t% move to step 3\n\t[assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step3__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim);\nend\n\n% compute cost and remove invalid assignments\n[assignment, cost] = computeassignmentcost__(assignment, originalDistMatrix, nOfRows);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction assignment = buildassignmentvector__(starMatrix)\n\n[maxValue, assignment] = max(starMatrix, [], 2);\nassignment(maxValue == 0) = 0;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [assignment, cost] = computeassignmentcost__(assignment, distMatrix, nOfRows)\n\nrowIndex   = find(assignment);\ncostVector = distMatrix(rowIndex + nOfRows * (assignment(rowIndex)-1));\nfiniteIndex = isfinite(costVector);\ncost = sum(costVector(finiteIndex));\nassignment(rowIndex(~finiteIndex)) = 0;\n\n% Step 2: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step2__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim)\n\n% cover every column containing a starred zero\nmaxValue = max(starMatrix);\ncoveredColumns(maxValue == 1) = 1;\n\nif sum(coveredColumns) == minDim\n\t% algorithm finished\n\tassignment = buildassignmentvector__(starMatrix);\nelse\n\t% move to step 3\n\t[assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step3__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim);\nend\n\n% Step 3: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step3__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim)\n\nzerosFound = 1;\nwhile zerosFound\n\t\n\tzerosFound = 0;\t\t\n\tfor col = find(~coveredColumns)\n\t\tfor row = find(~coveredRows')\n\t\t\tif distMatrix(row,col) == 0\n\t\t\t\t\n\t\t\t\tprimeMatrix(row, col) = 1;\n\t\t\t\tstarCol = find(starMatrix(row,:));\n\t\t\t\tif isempty(starCol)\n\t\t\t\t\t% move to step 4\n\t\t\t\t\t[assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step4__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, row, col, minDim);\n\t\t\t\t\treturn\n\t\t\t\telse\n\t\t\t\t\tcoveredRows(row)        = 1;\n\t\t\t\t\tcoveredColumns(starCol) = 0;\n\t\t\t\t\tzerosFound              = 1;\n\t\t\t\t\tbreak % go on in next column\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\nend\n\n% move to step 5\n[assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step5__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim);\n\n% Step 4: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step4__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, row, col, minDim)\n\nnewStarMatrix          = starMatrix;\nnewStarMatrix(row,col) = 1;\n\nstarCol = col;\nstarRow = find(starMatrix(:, starCol));\n\nwhile ~isempty(starRow)\n\n\t% unstar the starred zero\n\tnewStarMatrix(starRow, starCol) = 0;\n\t\n\t% find primed zero in row\n\tprimeRow = starRow;\n\tprimeCol = find(primeMatrix(primeRow, :));\n\t\n\t% star the primed zero\n\tnewStarMatrix(primeRow, primeCol) = 1;\n\t\n\t% find starred zero in column\n\tstarCol = primeCol;\n\tstarRow = find(starMatrix(:, starCol));\n\t\nend\nstarMatrix = newStarMatrix;\n\nprimeMatrix(:) = 0;\ncoveredRows(:) = 0;\n\n% move to step 2\n[assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step2__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim);\n\n\n% Step 5: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step5__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim)\n\n% find smallest uncovered element\nuncoveredRowsIndex    = find(~coveredRows');\nuncoveredColumnsIndex = find(~coveredColumns);\n[s, index1] = min(distMatrix(uncoveredRowsIndex,uncoveredColumnsIndex));\n[s, index2] = min(s);\nh = distMatrix(uncoveredRowsIndex(index1(index2)), uncoveredColumnsIndex(index2));\n\n% add h to each covered row\nindex = find(coveredRows);\ndistMatrix(index, :) = distMatrix(index, :) + h;\n\n% subtract h from each uncovered column\ndistMatrix(:, uncoveredColumnsIndex) = distMatrix(:, uncoveredColumnsIndex) - h;\n\n% move to step 3\n[assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step3__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim);\n\n\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/assignmentoptimal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5930427145092978}}
{"text": "function uvTformDataT = sr_src_domain_tform(uvPlaneID, modelPlane, uvTformAData, srcPos, trgPos)\n% SR_SRC_DOMAIN_TFORM\n%\n% The function estimates the source patch domain transformation based on\n% the source and target position, the plane parameters and apply the affine\n% transformation\n%\n% Input:\n%     - uvPlaneID:    [numUvPix] x [1], the plane label of uv pixels\n%     - modelPlane:   plane model\n%     - uvTformAData: [numUvPix] x 4, affine transformation\n%     - srcPos:       [numUvPix] x [2], the center position of source patch\n%     - trgPos:       [numUvPix] x [2], the center position of target patch\n% Output:\n%     - uvTformDataT: [numUvPix] X [9]\n%\n% The function of computing homography transformation induced by plane \n% is modified from the following paper:\n% \n% Jia-Bin Huang, Sing Bing Kang, Narendra Ahuja, and Johannes Kopf,\n% Image Completion using Planar Structure Guidance,\n% ACM Transactions on Graphics (Proceedings of SIGGRAPH 2014), 33(4), 2014\n% =========================================================================\n\n% TO-DO: Make sure that the predicted transformation can point it \n% the desired source patch position\n\n% =========================================================================\n% Compute homography transformation induced by plane\n% =========================================================================\n\nnumUvPix = size(srcPos, 1);\nuvTformDataH = zeros(numUvPix, 9, 'single');\nI = eye(3);\n\nfor indPlane = 1: modelPlane.numPlane\n    % The rectifying transformation for the plane\n    rectMat = modelPlane.rectMat{indPlane};\n    h7 = rectMat(3,1);\n    h8 = rectMat(3,2);\n    \n    % Retrieve the uv pixels that have the current plane label\n    uvPlaneIndCur = uvPlaneID == indPlane;\n    numPlanePixCur = sum(uvPlaneIndCur);\n    \n    if(numPlanePixCur)\n        % Target patch center position in the rectified domain\n        trgPosCur = trgPos(uvPlaneIndCur, :) - 1;\n        trgPosCurR = sr_apply_tform_H(trgPosCur, h7, h8);\n        \n        % Source patch center position in the rectified domain\n        srcPosCur = srcPos(uvPlaneIndCur, :) - 1;\n        srcPosCurR = sr_apply_tform_H(srcPosCur, h7, h8);\n        \n        % Displacement vector from target to source position\n        dRect = srcPosCurR - trgPosCurR;\n        \n        % Compute the transformation that maps from target to source\n        % (See Eqn 8 in the paper [Huang et al. TOG 2014])\n        uvTformCur = zeros(numPlanePixCur, 9, 'single');\n        uvTformCur(:,[1,4,7]) = bsxfun(@times, dRect(:,1), [h7, h8, 1]);\n        uvTformCur(:,[2,5,8]) = bsxfun(@times, dRect(:,2), [h7, h8, 1]);\n        \n        dTemp = dRect*[h7;h8]; % dTemp = dx*h7 + dy*h8\n        uvTformCur(:,[3,6,9]) = bsxfun(@times, dTemp, -[h7, h8, 1]);\n        uvTformCur = bsxfun(@plus, uvTformCur, I(:)');\n        \n        % Apply the offset to cancel out the dependency of the target position\n        % (See Eqn 9 in the paper [Huang et al. TOG 2014])\n        uvTformDataH(uvPlaneIndCur, :)   = sr_trans_tform(uvTformCur, trgPosCur);\n        uvTformDataH(uvPlaneIndCur, 7:8) = uvTformDataH(uvPlaneIndCur, 7:8) + 1;\n    end\nend\n\n% =========================================================================\n% Apply the similarity transformation\n% =========================================================================\n% The transformation T first map from original reference points to affine\n% transformation coordinate using A, and then map to the desired target\n% position using H\n% -> T = H * A\nuvTformDataT = uvTformDataH;\nuvTformDataT(:,1:3) = bsxfun(@times, uvTformDataH(:,1:3), uvTformAData(:,1)) + ...\n    bsxfun(@times, uvTformDataH(:,4:6), uvTformAData(:,2));\nuvTformDataT(:,4:6) = bsxfun(@times, uvTformDataH(:,4:6), uvTformAData(:,3)) + ...\n    bsxfun(@times, uvTformDataH(:,4:6), uvTformAData(:,4));\n\nuvTformDataT = bsxfun(@rdivide, uvTformDataT, uvTformDataT(:,9));\n\nend\n\n\nfunction x = sr_apply_tform_H(x, h7, h8)\n\n% Apply homography H with third row [h7, h8, 1] to 2D points x\n\ny = x(:,1)*h7 + x(:,2)*h8 + 1;\nx = bsxfun(@rdivide, x(:,1:2), y + eps);\n\n% numPix = size(x, 1);\n% x = cat(2, x, ones(numPix, 1, 'single'));\n% x = x*H';\n% x = bsxfun(@rdivide, x(:,1:2), x(:,3) + eps);\n\nend", "meta": {"author": "jbhuang0604", "repo": "SelfExSR", "sha": "8f6dd8c1d20cb7e8792a7177b4f6fd677633f598", "save_path": "github-repos/MATLAB/jbhuang0604-SelfExSR", "path": "github-repos/MATLAB/jbhuang0604-SelfExSR/SelfExSR-8f6dd8c1d20cb7e8792a7177b4f6fd677633f598/source/sr_src_domain_tform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5930427044500765}}
{"text": "% add the path of RBM code\naddpath('..');\n\n% load CBCL train\nload 'faces.train.mat';\nX = X_tra;\n\n% shuffle the training data\nperm_idx = randperm (size(X,1));\nX = X(perm_idx, :);\n\n% construct RBM and use default configurations\nR = default_rbm (size(X, 2), 300);\n\n% use continuous values\nR.data.binary = 0;\n\n% set grbm parameters\nR.grbm.do_vsample = 1;\nR.grbm.do_normalize = 0;\nR.grbm.do_normalize_std = 1;\nR.grbm.learn_sigmas = 1;\n\n% max. 100 epochs\nR.iteration.n_epochs = 100;\n\n% set the stopping criterion\nR.stop.criterion = 1;\nR.stop.recon_error.tolerate_count = 1000;\n\n% save the intermediate data after every epoch\nR.hook.per_epoch = {@save_intermediate, {'grbm_faces.mat'}};\n\n% print learining process\nR.verbose = 1;\n\n% display the progress\nR.debug.do_display = 0;\nR.debug.display_interval = 5;\nR.debug.display_fid = 1;\nR.debug.display_function = @visualize_grbm;\n\n% train RBM\nfprintf(1, 'Training GB-RBM\\n');\ntic;\nR = train_rbm (R, X);\nfprintf(1, 'Training is done after %f seconds\\n', toc);\n\n% grab some samples from RBM\nS = grbm_sample(normrnd(zeros(10,size(X,2)), ones(10,size(X,2))), R, 30, 1000);\n\nfigure;\nfor i=1:10\n    subplot(10, 1, i);\n    visualize_adv(squeeze(S(i,:,:)), 0, 1, 30, 0, 0);\nend\n\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/example/example_faces.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5930383484346508}}
{"text": "#computes the pose vector v from an homogeneous transform A\nfunction v=t2v(A)\n  v = [A(1:2,3); atan2(A(2,1),A(1,1))];\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/tools/t2v.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5930383362408418}}
{"text": "function [E,J]=SynthMeasWatsonSHCylSingleRadTortIsoV_GPD_B0(x, protocol, fibredir, roots)\n% Substrate: Impermeable cylinders with one radius in a homogeneous background.\n% Orientation distribution: Watson's distribution with SH approximation\n% Signal approximation: Gaussian phase distribution.\n% Notes: This version estimates the hindered diffusivity from the free diffusivity\n% and packing density using Szafer et al's tortuosity model for randomly\n% packed cylinders.\n% This version includes an isotropic diffusion compartment with its own\n% diffusivity.\n% Includes a free parameter for the measurement at b=0.\n%\n% [E,J]=SynthMeasWatsonSHCylSingleRadTortIsoV_GPD_B0(x, protocol, fibredir, roots)\n% returns the measurements E according to the model and the Jacobian J of the\n% measurements with respect to the parameters.  The Jacobian does not\n% include derivates with respect to the fibre direction.\n%\n% x is the list of model parameters in SI units:\n% x(1) is the volume fraction of the intracellular space.\n% x(2) is the free diffusivity of the material inside and outside the cylinders.\n% x(3) is the radius of the cylinders.\n% x(4) is the concentration parameter of the Watson's distribution.\n% x(5) is the volume fraction of the isotropic compartment.\n% x(6) is the diffusivity of the isotropic compartment.\n% x(7) is the measurement at b=0.\n%\n% protocol is the object containing the acquisition protocol.\n%\n% fibredir is a unit vector along the symmetry axis of the Watson's\n% distribution.  It must be in Cartesian coordinates [x y z]' with size [3 1].\n%\n% roots contains solutions to the Bessel function equation from function\n% BesselJ_RootsCyl.\n%\n% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\nS0 = x(7);\n\n% Call the other function to get normalized measurements.\nif(nargout == 1)\n    Enorm=SynthMeasWatsonSHCylSingleRadTortIsoV_GPD(x, protocol, fibredir, roots);\nelse\n    [Enorm,Jnorm]=SynthMeasWatsonSHCylSingleRadTortIsoV_GPD(x, protocol, fibredir, roots);\nend\n\nE = Enorm*S0;\n\nif(nargout>1)\n    J = Jnorm*S0;\n    [meas, params] = size(J);\n    J(:,params+1) = Enorm;\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/watson/SynthMeasWatsonSHCylSingleRadTortIsoV_GPD_B0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5930383352673648}}
{"text": "function [irf_record]=irf(beta_gibbs,It,Bu,IRFperiods,n,m,p,k)\n\n% function [irf_record]=irf(beta_gibbs,It,Bu,IRFperiods,n,m,p,k)\n% runs the gibbs sampler to obtain draws from the posterior distribution of IRFs\n% inputs:  - matrix 'beta_gibbs': record of the gibbs sampler draws for the beta vector\n%          - 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%          - integer 'IRFperiods': number of periods for IRFs\n%          - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)\n%          - integer 'm': number of exogenous variables in the BVAR model (defined p 7 of technical guide)\n%          - integer 'p': number of lags included in the model (defined p 7 of technical guide)\n%          - integer 'k': number of coefficients to estimate for each equation in the BVAR model (defined p 7 of technical guide)\n% outputs: -  cell 'irf_record': record of the gibbs sampler draws for the IRFs\n\n\n% this function implements algorithm 2.2.1\n\n% create the cell aray that will store the values from the simulations\nirf_record=cell(n,n);\n\nBgibbs=reshape(beta_gibbs,k,n,It-Bu);\n\n% deal with shocks in turn\nfor ii=1:n\n\n   % step 1: repeat the simulation process a number of times equal to the number of Gibbs iterations\n   for kk=1:It-Bu\n\n   % step 3: draw beta from its posterior distribution\n   B=squeeze(Bgibbs(:,:,kk));\n   % create a matrix of zeros of dimension p*n\n   Y=zeros(p,n);\n   %  step 2: set the value of the last row, column i, equal to 1\n   Y(p,ii)=1;\n\n% if prior~=61\n      % step 4: for each iteration kk, repeat the algorithm for periods T+1 to T+h\n      for jj=1:IRFperiods-1\n      % use the function lagx to obtain a matrix temp, containing the endogenous regressors\n      temp=bear.lagx(Y,p-1);\n      % define the vector X\n      X=[temp(end,:) zeros(1,m)];\n      % obtain the predicted value for T+jj\n      yp=X*B;\n      % concatenate yp at the top of Y\n      Y=[Y;yp];\n      % repeat until values are obtained for T+h\n      end\t  \n% elseif prior==61 %for prior=61 mean adjusted model\n% \t  % for each iteration kk, repeat the algorithm for periods T+1 to T+h\n%       for jj=1:IRFperiods\n%       % use the function lagx to obtain the matrix X\n%       X=bear.lagx(Y,p-1);\n%       X=X(end,:);\n%       % obtain predicted value for T+jj\n%       yp=X*B;\n%       % concatenate yp at the top of Y\n%       Y=[Y;yp];\n%       % repeat until values are obtained for T+h\n%       end\n% end\n\n   % step 5: record the results from current iteration in cell irf_record\n      % loop over variables\n      for jj=1:n\n      % consider column jj of matrix 'Y' and trim the (p-1) initial periods: what remains is the series of IRFs for period T to period T+h-1, for variable jj\n      temp=Y(p:end,jj);\n      % record these values in the corresponding matrix of irf_record\n      irf_record{jj,ii}(kk,:)=temp';\n      end\n\n   % then go for next iteration\n   end\n\n% conduct the same process with shocks in other variables\nend\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/irf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5929677525955546}}
{"text": "function f = fracInt(f, mu)\n%FRACINT  Fractional integral of a CHEBFUN. \n%   FRACINT(F, MU) gives the order MU fractional integral of a CHEBFUN object F.\n%\n%   Currently this only supports the situation where F is smooth (i.e., it has\n%   no breakpoints or endpoint singularities) and on a finite domain.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% No piecewise support yet:\nif ( numel(domain(f)) > 2 )\n    error('CHEBFUN:CHEBFUN:fracInt:breakpoints', ...\n        'FRACINT does not currently support piecewise functions.');\nend\n\n% Extract the fractional part of mu:\nmu_int = floor(mu);\nmu_frac = mu - mu_int;\n\n% Computer the integer CUMSUMs:\nif ( mu_int > 0 )\n    % Ensure mu is in [0, 1):\n    f = cumsum(f, mu_int);\n    f = fracInt(f, mu_frac);\n    return\nelseif ( mu_frac == 0 )\n    % Nothing more to do (non-fractional integral).\n    return\nend\n\n% Quasimatrix / Array-valued support:\n% TODO: This should be overhauled once SINGFUN supports array-valuedness.\nm = numColumns(f);\nif ( m > 1 )\n    % Convert to cell-array of scalar CHEBFUNs.\n    f = mat2cell(f);    \n    % Loop over columns:\n    for k = 1:m\n        f{k} = fracInt(f{k}, mu_frac);\n    end\n    % Convert from cell array to quasimatrix.\n    f = cat(2-f{1}.isTransposed, f{:});\n    return\nend\n\n% From here on f is scalar-valued:\n\n% Call BNDFUN/FRACINT():\nf.funs{1} = fracInt(f.funs{1}, mu_frac);\n\n% Update the pointValues:\nf.pointValues = chebfun.getValuesAtBreakpoints(f.funs);\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/fracInt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5929452093927954}}
{"text": "\n% Semantic Soft Segmentation\n% This function implements the soft segmentation approach described in\n% Yagiz Aksoy, Tae-Hyun Oh, Sylvain Paris, Marc Pollefeys, Wojciech Matusik\n% \"Semantic Soft Segmentation\", ACM TOG (Proc. SIGGRAPH) 2018\n\nfunction [softSegments, initSoftSegments, Laplacian, affinities, features, superpixels, eigenvectors, eigenvalues] = SemanticSoftSegmentation(image, features)\n    \n    disp('Semantic Soft Segmentation')\n    % Prepare the inputs and superpixels\n    image = im2double(image);\n    if size(features, 3) > 3 % If the features are raw, hyperdimensional, preprocess them\n        features = preprocessFeatures(features, image);\n    else\n        features = im2double(features);\n    end\n    superpixels = Superpixels(image);\n    [h, w, ~] = size(image);\n\n    disp('     Computing affinities')\n    % Compute the affinities and the Laplacian\n    affinities{1} = mattingAffinity(image);\n    affinities{2} = superpixels.neighborAffinities(features); % semantic affinity\n    affinities{3} = superpixels.nearbyAffinities(image); % non-local color affinity\n    Laplacian = affinityMatrixToLaplacian(affinities{1} + 0.01 * affinities{2} + 0.01 * affinities{3}); % Equation 6\n\n    disp('     Computing eigenvectors')\n    % Compute the eigendecomposition\n    eigCnt = 100; % We use 100 eigenvectors in the optimization\n    [eigenvectors, eigenvalues] = eigs(Laplacian, eigCnt, 'SM');\n    \n    disp('     Initial optimization')\n    % Compute initial soft segments\n    initialSegmCnt = 40;\n    sparsityParam = 0.8;\n    iterCnt = 40;\n    % feeding features to the function below triggers semantic intialization\n    initSoftSegments = softSegmentsFromEigs(eigenvectors, eigenvalues, Laplacian, ...\n                                            h, w, features, initialSegmCnt, iterCnt, sparsityParam, [], []);\n\n    % Group segments w.r.t. their mean semantic feature vectors\n    groupedSegments = groupSegments(initSoftSegments, features);\n\n    disp('     Final optimization')\n    % Do the final sparsification\n    softSegments = sparsifySegments(groupedSegments, Laplacian, imageGradient(image, false, 6));\n    \n    disp('     Done.')\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u5272\u7b97\u6cd5/SemanticSoftSegmentation-master/SemanticSoftSegmentation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461006, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5929452093927952}}
{"text": "%DEMO_SURVIVAL_COXPH  Survival model using Cox proportional model \n%\n%  Description \n%    Survival model using Cox proportional model with a piecewise\n%    log-constant baseline hazard. The hazard rate is \n%   \n%       h(t) = h_0(t)*exp(f),\n%\n%    where the baseline hazard is assumed to piecewise log-constant. \n%\n%    The inference is conducted via Laplace, where we find\n%    Gaussian approximation for p(f| th, data), where th is the\n%    maximum a posterior (MAP) estimate for the parameters.\n%    \n%    The censoring indicator ye is\n%    \n%      ye = 0 for uncensored event\n%      ye = 1 for right censored event.\n%\n%    If survival times y for n observation are given as nx2 matrix with\n%    entry times into follow-up in the first column and exit times from\n%    follow-up in the second column, left truncated right censored\n%    modelling is possible, for instance, in cases where age is wanted to\n%    be set as a baseline hazard.  \n%\n%    Example data set is leukemia survival data in Northwest England\n%    presented in (Henderson, R., Shimakura, S., and Gorst, D. (2002).\n%    Modeling spatial variation in leukemia survival data. Journal of the\n%    American Statistical Association, 97:965\u2013972). Data set was downloaded\n%    from http://www.math.ntnu.no/%7Ehrue/r-inla.org/examples/leukemia/leuk.dat\n%\n%  See also  DEMO_SURVIVAL_WEIBULL\n\n% Copyright (c) 2011 Jaakko Riihim\u00e4ki\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% First load data\nS = which('demo_survival_weibull');\nL = strrep(S,'demo_survival_weibull.m','demodata/leukemia.txt');\nleukemiadata=load(L);\n\n% leukemiadata consists of:\n% 'time', 'cens', 'xcoord', 'ycoord', 'age', 'sex', 'wbc', 'tpi', 'district'\n\n% survival times\ny=leukemiadata(:,1);\n% scale survival times\ny=y/max(y);\n\nye=1-leukemiadata(:,2); % event indicator, ye = 0 for uncensored event\n                  %                        ye = 1 for right censored event\n\n% choose (for example) 'age', 'sex', 'wbc', and 'tpi' covariates\nx0=leukemiadata(:,5:8);\nx=x0;\n% normalize continuous covariates \nx(:,[1 3:4])=bsxfun(@rdivide,bsxfun(@minus,x0(:,[1 3:4]),mean(x0(:,[1 3:4]),1)),std(x0(:,[1 3:4]),1));\n\n[n, nin]=size(x);\n\n% number of time intervals\nntime=50;\n% create finite partition of time axis\nS=linspace(0,max(y)+0.001,ntime+1);\n\n% Create the covariance functions\npl = prior_t('s2',1, 'nu', 4);\npm = prior_t('s2',1, 'nu', 4); \n\n% covariance for hazard function\ngpcfh = gpcf_sexp('lengthScale', 1, 'magnSigma2', 1.1, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\n% covariance for proportional part\ngpcf = gpcf_sexp('lengthScale', ones(1,size(x,2)), 'magnSigma2', 1.2, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\n\n% Create the likelihood structure\nlik = lik_coxph('S', S);\n\n% NOTE! if multiple covariance functions per latent is used, define\n% gp.comp_cf as follows:\n% gp = gp_set(..., 'comp_cf' {[1 2] [5 6]};\n% where [1 2] are for hazard function, and [5 6] for proportional part\ngp = gp_set('lik', lik, 'cf', {gpcfh gpcf}, 'jitterSigma2', 1e-6, 'comp_cf', {1 2});\n\n% Set the approximate inference method to Laplace\ngp = gp_set(gp, 'latent_method', 'Laplace');\n\nopt=optimset('TolFun',1e-2,'TolX',1e-2,'Display','iter');\ngp=gp_optim(gp,x,y,'z',ye,'opt',opt);\n\n% Make prediction\nxt1=zeros(200,nin); xt1(:,2)=1;\nxt2=zeros(200,nin); xt2(:,2)=-1;\n\nxt1(:,1)=linspace(min(x(:,1)), max(x(:,1)), 200);\nxt2(:,1)=linspace(min(x(:,1)), max(x(:,1)), 200);\nxt01(:,1)=linspace(min(x0(:,1)), max(x0(:,1)), 200);\nxt02(:,1)=linspace(min(x0(:,1)), max(x0(:,1)), 200);\n\n\n[Ef1, Covf1] = gp_pred(gp, x, y, xt1, 'z', ye);\n[Ef2, Covf2] = gp_pred(gp, x, y, xt2, 'z', ye);\nVarf1 = diag(Covf1);\nVarf2 = diag(Covf2);\n\n\nfigure, hold on, set(gcf, 'color', 'w'),\nplot(gp.lik.xtime, Ef1(1:ntime),'k', 'linewidth', 3)\nplot(gp.lik.xtime, Ef1(1:ntime)+1.96*sqrt(Varf1(1:ntime)),'--k', 'linewidth', 2)\nplot(gp.lik.xtime, Ef1(1:ntime)-1.96*sqrt(Varf1(1:ntime)),'--k', 'linewidth', 2)\ntitle('log-baseline hazard (follow-up time)')\nxlabel('time')\n\n% Compute posterior mean and 95% credible intervals of latent function as a\n% function of age and sex\ncol1=ones(1,3)*0.7;\ncol2=ones(1,3)*0.3;\nfigure, hold on, set(gcf, 'color', 'w'),\nplot(xt01(:,1), Ef1(ntime+1:end), 'color', col1, 'linewidth', 3)\nplot(xt01(:,1), Ef1(ntime+1:end)+1.96*sqrt(Varf1(ntime+1:end)), '--', 'color', col1, 'linewidth', 2)\nplot(xt01(:,1), Ef1(ntime+1:end)-1.96*sqrt(Varf1(ntime+1:end)), '--', 'color', col1, 'linewidth', 2)\n\nplot(xt02(:,1), Ef2(ntime+1:end), 'color', col2, 'linewidth', 3)\nplot(xt02(:,1), Ef2(ntime+1:end)+1.96*sqrt(Varf2(ntime+1:end)), '--', 'color', col2, 'linewidth', 2)\nplot(xt02(:,1), Ef2(ntime+1:end)-1.96*sqrt(Varf2(ntime+1:end)), '--', 'color', col2, 'linewidth', 2)\nxlabel('age')\ntitle('effect of age for both sexes')\n\n\n%- Age as baseline hazard\n\n% Age in the beginning and in the end of follow-up\ny=[x0(:,1) x0(:,1)+leukemiadata(:,1)/365];\ny2=y;\n% normalise ages\ny2=y2-min(y2(:)); y2=y2./max(y(:));\n\nx2=x;\nx2(:,1)=[];\n\n% covariance for proportional part\ngpcf = gpcf_sexp('lengthScale', ones(1,size(x2,2)), 'magnSigma2', .5, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\n\n% NOTE! if multiple covariance functions per latent is used, define\n% gp.comp_cf as follows:\n% gp = gp_set(..., 'comp_cf', {[1 2] [5 6]});\n% where [1 2] are for hazard function, and [5 6] for proportional part\ngp = gp_set('lik', lik, 'cf', {gpcfh gpcf}, 'jitterSigma2', 1e-6, 'comp_cf', {[1] [2]});\n\n% Set the approximate inference method to Laplace\ngp = gp_set(gp, 'latent_method', 'Laplace');\n\nopt=optimset('TolFun',1e-2,'TolX',1e-2,'Display','iter');\ngp=gp_optim(gp,x2,y2,'z',ye,'opt',opt);\n\n[Ef1, Covf1] = gp_pred(gp, x2, y2, x2, 'z', ye);\nVarf1 = diag(Covf1);\nxtmpl=linspace(min(y(:)),max(y(:)),50);\n\nfigure, hold on, set(gcf, 'color', 'w'),\nplot(xtmpl, Ef1(1:ntime),'k', 'linewidth', 3)\nplot(xtmpl, Ef1(1:ntime)+1.96*sqrt(Varf1(1:ntime)),'--k', 'linewidth', 2)\nplot(xtmpl, Ef1(1:ntime)-1.96*sqrt(Varf1(1:ntime)),'--k', 'linewidth', 2)\ntitle('log-baseline hazard (age)')\nxlabel('age')\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_survival_coxph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5929452039023306}}
{"text": "function [logp, yhat, res] = tapas_softmax_mu3(r, infStates, ptrans)\n% Calculates the log-probability of responses under the softmax model\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2017-2019 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or <http://www.gnu.org/licenses/>.\n\n% Predictions or posteriors?\npop = 1; % Default: predictions\nif r.c_obs.predorpost == 2\n    pop = 3; % Alternative: posteriors\nend\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% Assumed structure of infStates:\n% dim 1: time (ie, input sequence number)\n% dim 2: HGF level\n% dim 3: choice number\n% dim 4: 1: muhat, 2: sahat, 3: mu, 4: sa\n\n% Number of choices\nnc = size(infStates,3);\n\n% Belief trajectories at 1st level\nstates = squeeze(infStates(:,1,:,pop));\n\n% Log-volatility trajectory\nmu3 = squeeze(infStates(:,3,1,3));\n\n% Responses\ny = r.y(:,1);\n\n% Weed irregular trials out from inferred states and responses\nstates(r.irr,:) = [];\nmu3(r.irr) = [];\ny(r.irr) = [];\n\n% Inverse decision temperature\nbe = exp(-mu3);\nbe = repmat(be,1,nc);\n\n% Partition functions\nZ = sum(exp(be.*states),2);\nZ = repmat(Z,1,nc);\n\n% Softmax probabilities\nprob = exp(be.*states)./Z;\n\n% Extract probabilities of chosen options\nprobc = prob(sub2ind(size(prob), 1:length(y), y'));\n\n% Calculate log-probabilities for non-irregular trials\nreg = ~ismember(1:n,r.irr);\nlogp(reg) = log(probc);\nyhat(reg) = probc;\nres(reg) = -log(probc);\n\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_softmax_mu3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5929451932732938}}
{"text": "classdef PrincipalStressDirections < handle\n    \n    properties (GetAccess = public, SetAccess = private)\n        principalStressDir\n        principalStress\n    end\n    \n    properties (Access = private)\n        stress\n    end\n    \n    methods (Access = public)\n        \n        function obj = PrincipalStressDirections(cParams)\n            obj.init(cParams);\n        end\n        \n        function compute(obj)\n            obj.computeStressBase();\n            obj.normalizePrincipalDirection();\n            obj.transformBaseToElementalBase();\n        end\n    end\n    \n    methods (Access = private)\n        \n        function init(obj,cParams)\n            obj.stress = cParams.stress;\n        end\n        \n        function computeStressBase(obj)\n            s = obj.stress;\n            S = [s(1) s(3);s(3) s(2)];\n            [V,D] = eig(S);\n            obj.principalStressDir = V;\n            obj.principalStress = D;\n        end\n        \n    end\n    \n    methods (Access = private)\n        \n        function normalizePrincipalDirection(obj)\n            V = obj.principalStressDir;\n            V(:,1) = V(:,1)/norm(V(:,1));\n            V(:,2) = V(:,2)/norm(V(:,2));\n            obj.principalStressDir = V;\n        end\n        \n        function transformBaseToElementalBase(obj)\n            V = obj.principalStressDir;\n            V(:,2) = V(:,2)*det(V);\n            obj.principalStressDir = V;\n        end\n        \n    end\nend\n\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/MinimizingOrientation/PrincipalStressDirections.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5929245674417073}}
{"text": "function model = treeTrain(X, Y, opts)\n% Train a random tree\n% X is NxD, each D-dimensional row is a data point\n% Y is Nx1 discrete labels of classes\n% returned model is to be directly plugged into treeTest\n\nd= 5; % max depth of the tree\n\nif nargin < 3, opts= struct; end\nif isfield(opts, 'depth'), d= opts.depth; end\n\nu= unique(Y);\n[N, D]= size(X);\nnd= 2^d - 1;\nnumInternals = (nd+1)/2 - 1;\nnumLeafs= (nd+1)/2;\n\nweakModels= cell(1, numInternals); \n% if we can afford to store as non-sparse (100MB array, say), it is\n% slightly faster.\nif storage([N nd]) < 100 \n    dataix= zeros(N, nd); % boolean indicator of data at each node\nelse\n    dataix= sparse(N, nd); \nend\n    \nleafdist= zeros(numLeafs, length(u)); % leaf distribution\n\n% Propagate data down the tree while training weak classifiers at each node\nfor n = 1: numInternals\n    \n    % get relevant data at this node\n    if n==1 \n        reld = ones(N, 1)==1;\n        Xrel= X;\n        Yrel= Y;\n    else\n        reld = dataix(:, n)==1;\n        Xrel = X(reld, :);\n        Yrel = Y(reld);\n    end\n    \n    % train weak model\n    weakModels{n}= weakTrain(Xrel, Yrel, opts);\n    \n    % split data to child nodes\n    yhat= weakTest(weakModels{n}, Xrel, opts);\n    \n    dataix(reld, 2*n)= yhat;\n    dataix(reld, 2*n+1)= 1 - yhat; % since yhat is in {0,1} and double\nend\n\n% Go over leaf nodes and assign class statistics\nfor n= (nd+1)/2 : nd\n    reld= dataix(:, n);\n    hc = histc(Y(reld==1), u);\n    hc = hc + 1; % Dirichlet prior\n    leafdist(n - (nd+1)/2 + 1, :)= hc / sum(hc);\nend\n\nmodel.leafdist= leafdist;\nmodel.depth= d;\nmodel.classes= u;\nmodel.weakModels= weakModels;\nend\n", "meta": {"author": "karpathy", "repo": "Random-Forest-Matlab", "sha": "46aa3d5be31ba25364d087d3e71cdc9bd5f4de18", "save_path": "github-repos/MATLAB/karpathy-Random-Forest-Matlab", "path": "github-repos/MATLAB/karpathy-Random-Forest-Matlab/Random-Forest-Matlab-46aa3d5be31ba25364d087d3e71cdc9bd5f4de18/lib/treeTrain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5929236423089215}}
{"text": "function [err,elemErr] = getL2errorRT0(node,elem,exactSigma,sigmah,d)\n%% GETL2ERRORRT0 L2 norm of RT0 element.\n%\n%  The input exactSigma can be a function bundle or vector array. \n%  When exactSigma is a vector array, it should be size NT*2, and \n%  exactSigma = \\nabla u (or exactSigma= K\\nabla u), vector array of size\n%  NT by 2.\n% \n%  [err,elemErr] = getL2errorRT0(node,elem,exactSigma,sigmah).\n%  err gives the L2 norm between exact flux and approximate one from RT0, \n%  elemErr, an NT by 1 array, gives the square of L2 norm between exact \n%  flux and approximate one from RT0 on each element.\n%  \n%  [err,elemErr] = getL2errorRT0(node,elem,exactSigma,sigmah,d). \n%  If the coefficient 'd' is inlcuded, then the input should be in the way\n%  sigmah     = K\\nabla u_h  (including K), \n%  exactSigma =  \\nabla u    (function bundle, don't including K),    or \n%  exactSigma = K\\nabla u    (vector array, including K).\n%  err=||K exactSigma - sigma_h||_{K^(-1)} = |||u-u_h||| is the energy norm.\n%  elemErr, an NT by 1 array, gives the square of L2 norm between exact \n%  flux and approximate one from RT0 on each element\n%\n% Example\n%\n%     maxIt = 5;\n%     node = [1,0; 1,1; 0,1; -1,1; -1,0; -1,-1; 0,-1; 0,0]; % nodes\n%     elem = [1,2,8; 3,8,2; 8,3,5; 4,5,3; 7,8,6; 5,6,8];    % elements\n%     bdFlag = setboundary(node,elem,'Dirichlet');\n%     pde = mixBCdata;\n%     err = zeros(maxIt,1); \n%     h = zeros(maxIt,1);\n%     for k = 1:maxIt\n%         [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n%         [u,sigma] = PoissonRT0(node,elem,bdFlag,pde);\n%         err(k) = getL2errorRT0(node,elem,pde.Du,sigma);\n%         h(k) = 1./(sqrt(size(node,1))-1);\n%     end\n%     r1 = showrateh(h,err,2);\n%     legend('||\\sigma - \\sigma_h||',['h^{' num2str(r1) '}'],...\n%            'LOCATION','Best');\n% \n% See also getHdiverrorRT0, getL2error3RT0.\n%\n% Created by Ming Wang at Jan 17, 2011, M-lint modified at May 15, 2011.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details. \n\nif exist('d','var') && ~isempty(d)\n    if isreal(d)\n        K = d;                  % d is an array\n    else                        \n    center = (node(elem(:,1),:) + node(elem(:,2),:) + ...\n              node(elem(:,3),:))/3;\n    K = d(center);              % d is a function\n    end\nelse\n    K = [];\nend\n\n%% Construct Data Structure\n[elem2dof,~,elem2edgeSign] = dofedge(elem);\nNT = size(elem,1);% Ndof = max(elem2dof(:)); %N = size(node,1); \n[Dlambda,area] = gradbasis(node,elem);\nlocEdge = [2 3; 3 1; 1 2];\n\n%% Compute square of the L2 error element-wise\n[lambda,w] = quadpts(3); % quadrature order is 3\nnQuad = size(lambda,1);\nerr = zeros(NT,1);\nrotMat = [0 -1; 1 0]; % rotation matrix for computing rotLambda.\nfor p = 1:nQuad\n    pxy = lambda(p,1)*node(elem(:,1),:) ...\n        + lambda(p,2)*node(elem(:,2),:) ... \n        + lambda(p,3)*node(elem(:,3),:);\n    if ~isnumeric(exactSigma)\n        sigmap = exactSigma(pxy);\n        if(nargin >=5)&& ~isempty(K) % multiply coeff. if fun bundle flux.\n            sigmap = repmat(K,1,2).*sigmap;\n        end\n    else\n        sigmap = exactSigma;         %  K*\\nabla u_h.\n    end\n    sigmahp = zeros(NT,2);\n    for k = 1:3 % for each basis\n        i = locEdge(k,1); j = locEdge(k,2);\n        % phi_k = lambda_iRot_j - lambda_jRot_i;\n        sigmahp = sigmahp + repmat(elem2edgeSign(:,k).*sigmah(elem2dof(:,k)),1,2).*...\n                   (lambda(p,i)*Dlambda(:,:,j)*rotMat-lambda(p,j)*Dlambda(:,:,i)*rotMat);\n    end\n    err = err + w(p)*sum((sigmap - sigmahp).^2,2);\nend\nerr = err.*area;               % ||sigma - K\\nabla u_h||^2\nif(nargin >=5)&& ~isempty(K)   % ||sigma - K\\nabla u_h||^2_{K^(-1)}\n    err = err./K;\nend\nelemErr = err;           % ||sigma - K\\nabla u_h||^2_{K^(-1)}\n% modify the error\nerr(isnan(err)) = 0;\nerr = sqrt(sum(err));\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/getL2errorRT0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5928616806099354}}
{"text": "function dz = dynAcc(z, u, p)\n% dz = dynAcc(z, u, p)\n%\n% This function computes the dynamics of a simple planar quad-rotor\n% helicopter, including chain integrator for acceleration cost function.\n%\n% INPUTS:\n%   z = [9, n] = [X; V1; V2] = state matrix\n%   u = [5, n] = [U1; U2] = control matrix\n%   p = parameter struct:\n%       .g = acceleration due to gravity\n%       .d = half distance between rotors\n%       .m = mass of each rotor (half-mass of the quad-rotor)\n%\n% OUTPUTS:\n%   dz = derivative of state matrix\n%\n\n% Unpack the inputs\nX = z(1:3,:);   % configuration\nV1 = z(4:6,:);  % rates (dynamics)\n% V2 = z(7:9,:);  % rates (integrator)    %unused\nU1 = u(1:2,:);  % actuators\nU2 = u(3:5,:);  % kinematics\n\n% Call to the actual dynamics function\ndV1 = dynQuadRotor(X, U1, p);\n\n% Chain integrators\ndX = V1;\ndV2 = U2;\n\n% Pack up the outputs\ndz = [dX; dV1; dV2];\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/quadRotor2d/dynAcc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5928616800890691}}
{"text": "function dcenter = ComputeDistFlyCenter(obj,n,fly1)\n\nnflies = obj.nfliespermovie(n);\nflyidx1 = obj.getFlyIdx(n,fly1);\n\n% initialize\nx_mm1 = obj.GetPerFrameData('x_mm',n,fly1);\ny_mm1 = obj.GetPerFrameData('y_mm',n,fly1);\nnframes1 = obj.nframes(flyidx1);\nfirstframe1 = obj.firstframes(flyidx1);\nendframe1 = obj.endframes(flyidx1);\ndcenter = nan(nflies,nframes1);\n\nfor fly2 = 1:nflies,\n  if fly2 == fly1, continue; end\n  \n  flyidx2 = obj.getFlyIdx(n,fly2);\n  firstframe2 = obj.firstframes(flyidx2);\n  endframe2 = obj.endframes(flyidx2);\n  \n  % get start and end frames of overlap\n  t0 = max(firstframe1,firstframe2);\n  t1 = min(endframe1,endframe2);\n  \n  % no overlap\n  if t1 < t0, continue; end\n  \n  % indices for these frames\n  offi = firstframe1-1;\n  offj = firstframe2-1;\n  i0 = t0 - offi;\n  i1 = t1 - offi;\n  j0 = t0 - offj;\n  j1 = t1 - offj;\n  \n  x_mm2 = obj.GetPerFrameData('x_mm',n,fly2);\n  y_mm2 = obj.GetPerFrameData('y_mm',n,fly2);\n  \n  % centroid distance\n  dx = x_mm2(j0:j1)-x_mm1(i0:i1);\n  dy = y_mm2(j0:j1)-y_mm1(i0:i1);\n  z = sqrt(dx.^2 + dy.^2);\n  dcenter(fly2,i0:i1) = z;\n  \nend\n\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/@Trx/ComputeDistFlyCenter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5928616693168484}}
{"text": "%FREFINE refine estimate of fundamental matrix\n%\n% fr = frefine(F, uv1, uv2)\n%\n%  Return a refined estimate of fundamental matrix using non-linear\n% optimization and enforcing the rank-2 constraint.\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 <http://www.gnu.org/licenses/>.\n\nfunction fr = frefine(F, uv1, uv2)\n\n\tA = [];\n\tfor i=1:numrows(uv1),\n\t\ta = [\tuv1(i,1)*uv2(i,1)\n\t\t\tuv1(i,2)*uv2(i,1)\n\t\t\tuv2(i,1)\n\t\t\tuv1(i,1)*uv2(i,2)\n\t\t\tuv1(i,2)*uv2(i,2)\n\t\t\tuv2(i,2)\n\t\t\tuv1(i,1)\n\t\t\tuv1(i,2)\n\t\t\t1\n\t\t];\n\t\tA = [A; a'];\n\tend\n\tf = F';\n\tf = f(:);\n\tfprintf('Initial residual is %g\\n', norm(A * f));\n\tfprintf('Initial determinant is %g\\n', det(F));\n\n\toptions = optimset('MaxFunEvals', 10000, ...\n\t\t'LevenbergMarquardt', 'on', ...\n\t\t'TolFun', 1e-16, ...\n\t\t'TolCon', 1e-16, ...\n\t\t'LargeScale', 'off' ...\n\t\t);\n\tfr = fmincon(@fun, f, [], [], [], [], [], [], ...\n\t\t@nlfun, options, A);\n\tfprintf('Final residual is %g\\n', norm(A * fr));\n\tfr = reshape(fr, 3, 3)';\n\tdet(fr)\n\tfprintf('Final determinant is %g\\n', det(fr));\n\t\t\nfunction e = fun(x, A)\n\te = norm(A * x);\n\nfunction [c,ceq] = nlfun(x, A)\n\n\tceq = abs( det(reshape(x, 3, 3)) );\n\tc = [];\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/frefine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.592841228944446}}
{"text": "function triangle_points_plot ( file_name, node_xy, node_show, point_num, ...\n  point_xy, point_show )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_POINTS_PLOT plots a triangle and some points.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 October 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, string FILE_NAME, the name of the output file.\n%\n%    Input, real NODE_XY(2,3), the coordinates of the nodes\n%    of the triangle.\n%\n%    Input, integer NODE_SHOW,\n%   -1, do not show the triangle, or the nodes.\n%    0, show the triangle, do not show the nodes;\n%    1, show the triangle and the nodes;\n%    2, show the triangle, the nodes and number them.\n%\n%    Input, integer POINT_NUM, the number of points.\n%\n%    Input, real POINT_XY(2,POINT_NUM), the coordinates of the\n%    points.\n%\n%    Input, integer POINT_SHOW,\n%    0, do not show the points;\n%    1, show the points;\n%    2, show the points and number them.\n%\n  node_num = 3;\n  x_ps_max = 576;\n  x_ps_max_clip = 594;\n  x_ps_min = 36;\n  x_ps_min_clip = 18;\n  y_ps_max = 666;\n  y_ps_max_clip = 684;\n  y_ps_min = 126;\n  y_ps_min_clip = 108;\n%\n%  We need to do some figuring here, so that we can determine\n%  the range of the data, and hence the height and width\n%  of the piece of paper.\n%\n  x_max = max ( max ( node_xy(1,1:node_num) ), ...\n                max ( point_xy(1,1:point_num) ) );\n  x_min = min ( min ( node_xy(1,1:node_num) ), ...\n                min ( point_xy(1,1:point_num) ) );\n  x_scale = x_max - x_min;\n\n  x_max = x_max + 0.05 * x_scale;\n  x_min = x_min - 0.05 * x_scale;\n  x_scale = x_max - x_min;\n\n  y_max = max ( max ( node_xy(2,1:node_num) ), ...\n                max ( point_xy(2,1:point_num) ) );\n  y_min = min ( min ( node_xy(2,1:node_num) ), ...\n                min ( point_xy(2,1:point_num) ) );\n  y_scale = y_max - y_min;\n\n  y_max = y_max + 0.05 * y_scale;\n  y_min = y_min - 0.05 * y_scale;\n  y_scale = y_max - y_min;\n\n  if ( x_scale < y_scale )\n\n    delta = round ( ( x_ps_max - x_ps_min ) ...\n      * ( y_scale - x_scale ) / ( 2.0 * y_scale ) );\n\n    x_ps_max = x_ps_max - delta;\n    x_ps_min = x_ps_min + delta;\n\n    x_ps_max_clip = x_ps_max_clip - delta;\n    x_ps_min_clip = x_ps_min_clip + delta;\n\n    x_scale = y_scale;\n\n  elseif ( y_scale < x_scale )\n\n    delta = round ( ( y_ps_max - y_ps_min ) ...\n      * ( x_scale - y_scale ) / ( 2.0 * x_scale ) );\n\n    y_ps_max      = y_ps_max - delta;\n    y_ps_min      = y_ps_min + delta;\n\n    y_ps_max_clip = y_ps_max_clip - delta;\n    y_ps_min_clip = y_ps_min_clip + delta;\n\n    y_scale = x_scale;\n\n  end\n\n  file_unit = fopen ( file_name, 'wt' );\n\n  if ( file_unit < 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'TRIANGLE_POINTS_PLOT - Fatal error!\\n' );\n    fprintf ( 1, '  Can not open output file.\\n' );\n    return\n  end\n  \n  fprintf ( file_unit, '%!PS-Adobe-3.0 EPSF-3.0\\n' );\n  fprintf ( file_unit, '%%Creator: triangulation_order3_plot.f90\\n' );\n  fprintf ( file_unit, '%%Title: %s\\n', file_name );\n  fprintf ( file_unit, '%%Pages: 1\\n' );\n\n  fprintf ( file_unit, '%%BoundingBox:  %4d  %4d  %4d  %4d\\n', ...\n    x_ps_min, y_ps_min, x_ps_max, y_ps_max );\n  fprintf ( file_unit, '%%Document-Fonts: Times-Roman\\n' );\n  fprintf ( file_unit, '%%LanguageLevel: 1\\n' );\n  fprintf ( file_unit, '%%EndComments\\n' );\n  fprintf ( file_unit, '%%BeginProlog\\n' );\n  fprintf ( file_unit, '/inch {72 mul} def\\n' );\n  fprintf ( file_unit, '%%EndProlog\\n' );\n  fprintf ( file_unit, '%%Page: 1 1\\n' );\n  fprintf ( file_unit, 'save\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '%  Set the RGB line color to very light gray.\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '0.900  0.900  0.900 setrgbcolor\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '%  Draw a gray border around the page.\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, 'newpath\\n' );\n  fprintf ( file_unit, '  %4d  %4d  moveto\\n', x_ps_min, y_ps_min );\n  fprintf ( file_unit, '  %4d  %4d  lineto\\n', x_ps_max, y_ps_min );\n  fprintf ( file_unit, '  %4d  %4d  lineto\\n', x_ps_max, y_ps_max );\n  fprintf ( file_unit, '  %4d  %4d  lineto\\n', x_ps_min, y_ps_max );\n  fprintf ( file_unit, '  %4d  %4d  lineto\\n', x_ps_min, y_ps_min );\n  fprintf ( file_unit, 'stroke\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '%  Set the RGB color to black.\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '0.000  0.000  0.000 setrgbcolor\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '%  Set the font and its size.\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '/Times-Roman findfont\\n' );\n  fprintf ( file_unit, '0.50 inch scalefont\\n' );\n  fprintf ( file_unit, 'setfont\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '%  Print a title.\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '%  210  702  moveto\\n' );\n  fprintf ( file_unit, '%  (Triangulation)  show\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '%  Define a clipping polygon.\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, 'newpath\\n' );\n  fprintf ( file_unit, '  %4d  %4d  moveto\\n', x_ps_min_clip, y_ps_min_clip );\n  fprintf ( file_unit, '  %4d  %4d  lineto\\n', x_ps_max_clip, y_ps_min_clip );\n  fprintf ( file_unit, '  %4d  %4d  lineto\\n', x_ps_max_clip, y_ps_max_clip );\n  fprintf ( file_unit, '  %4d  %4d  lineto\\n', x_ps_min_clip, y_ps_max_clip );\n  fprintf ( file_unit, '  %4d  %4d  lineto\\n', x_ps_min_clip, y_ps_min_clip );\n  fprintf ( file_unit, 'clip newpath\\n' );\n%\n%  Draw the nodes.\n%\n  if ( 1 <= node_show )\n\n    circle_size = 5;\n\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '%  Draw filled dots at the nodes.\\n' );\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '%  Set the RGB color to blue.\\n' );\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '0.000  0.150  0.750 setrgbcolor\\n' );\n    fprintf ( file_unit, '%\\n' );\n\n    for node = 1 : 3\n\n      x_ps = round ( ...\n        ( ( x_max - node_xy(1,node)         ) * x_ps_min   ...\n        + (         node_xy(1,node) - x_min ) * x_ps_max ) ...\n        / ( x_max                   - x_min ) );\n\n      y_ps = round ( ...\n        ( ( y_max - node_xy(2,node)         ) * y_ps_min   ...\n        + (         node_xy(2,node) - y_min ) * y_ps_max ) ...\n        / ( y_max                   - y_min ) );\n\n      fprintf ( file_unit, 'newpath  %4d  %4d  %4d  0 360 arc closepath fill\\n',...\n        x_ps, y_ps, circle_size );\n\n    end\n\n  end\n%\n%  Label the nodes.\n%\n  if ( 2 <= node_show )\n\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '%  Label the nodes:\\n' );\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '%  Set the RGB color to darker blue.\\n' );\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '0.000  0.250  0.850 setrgbcolor\\n' );\n    fprintf ( file_unit, '/Times-Roman findfont\\n' );\n    fprintf ( file_unit, '0.20 inch scalefont\\n' );\n    fprintf ( file_unit, 'setfont\\n' );\n    fprintf ( file_unit, '%\\n' );\n\n    for node = 1 : node_num\n\n      x_ps = round ( ...\n        ( ( x_max - node_xy(1,node)         ) * x_ps_min   ...\n        + (       + node_xy(1,node) - x_min ) * x_ps_max ) ...\n        / ( x_max                   - x_min ) );\n\n      y_ps = round ( ...\n        ( ( y_max - node_xy(2,node)         ) * y_ps_min   ...\n        + (         node_xy(2,node) - y_min ) * y_ps_max ) ...\n        / ( y_max                   - y_min ) );\n\n      fprintf ( file_unit, '%4d  %4d  moveto ( %4d ) show\\n', x_ps, y_ps+5, node );\n\n    end\n\n  end\n%\n%  Draw the points.\n%\n  if ( point_num <= 200 )\n    circle_size = 5;\n  elseif ( point_num <= 500 )\n    circle_size = 4;\n  elseif ( point_num <= 1000 )\n    circle_size = 3;\n  elseif ( point_num <= 5000 )\n    circle_size = 2;\n  else\n    circle_size = 1;\n  end\n\n  if ( 1 <= point_show )\n\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '%  Draw filled dots at the points.\\n' );\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '%  Set the RGB color to green.\\n' );\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '0.150  0.750  0.000 setrgbcolor\\n' );\n    fprintf ( file_unit, '%\\n' );\n\n    for point = 1 : point_num\n\n      x_ps = round ( ...\n        ( ( x_max - point_xy(1,point)         ) * x_ps_min   ...\n        + (         point_xy(1,point) - x_min ) * x_ps_max ) ...\n        / ( x_max                     - x_min ) );\n\n      y_ps = round ( ...\n        ( ( y_max - point_xy(2,point)         ) * y_ps_min   ...\n        + (         point_xy(2,point) - y_min ) * y_ps_max ) ...\n        / ( y_max                     - y_min ) );\n\n      fprintf ( file_unit, 'newpath  %4d  %4d  %4d  0 360 arc closepath fill\\n', ...\n        x_ps, y_ps, circle_size );\n\n    end\n\n  end\n%\n%  Label the points.\n%\n  if ( 2 <= point_show )\n\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '%  Label the point:\\n' );\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '%  Set the RGB color to darker green.\\n' );\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '0.250  0.850  0.000 setrgbcolor\\n' );\n    fprintf ( file_unit, '/Times-Roman findfont\\n' );\n    fprintf ( file_unit, '0.20 inch scalefont\\n' );\n    fprintf ( file_unit, 'setfont\\n' );\n    fprintf ( file_unit, '%\\n' );\n\n    for point = 1 : point_num\n\n      x_ps = round ( ...\n        ( ( x_max - point_xy(1,point)         ) * x_ps_min   ...\n        + (       + point_xy(1,point) - x_min ) * x_ps_max ) ...\n        / ( x_max                     - x_min ) );\n\n      y_ps = round ( ...\n        ( ( y_max - point_xy(2,point)         ) * y_ps_min   ...\n        + (         point_xy(2,point) - y_min ) * y_ps_max ) ...\n        / ( y_max                     - y_min ) );\n\n      fprintf ( file_unit, '%4d  %4d  moveto ( %4d ) show\\n', x_ps, y_ps+5, point );\n\n    end\n\n  end\n%\n%  Draw the triangle.\n%\n  if ( 0 <= node_show )\n\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '%  Set the RGB color to red.\\n' );\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '0.900  0.200  0.100 setrgbcolor\\n' );\n    fprintf ( file_unit, '%\\n' );\n    fprintf ( file_unit, '%  Draw the triangle.\\n' );\n    fprintf ( file_unit, '%\\n' );\n\n    fprintf ( file_unit, 'newpath\\n' );\n\n    for i = 1 : 4\n\n      node = i4_wrap ( i, 1, 3 );\n\n      x_ps = round ( ...\n        ( ( x_max - node_xy(1,node)         ) * x_ps_min   ...\n        + (         node_xy(1,node) - x_min ) * x_ps_max ) ...\n        / ( x_max                   - x_min ) );\n\n      y_ps = round ( ...\n        ( ( y_max - node_xy(2,node)         ) * y_ps_min   ...\n        + (         node_xy(2,node) - y_min ) * y_ps_max ) ...\n        / ( y_max                   - y_min ) );\n\n      if ( i == 1 )\n        fprintf ( file_unit, '%3d  %3d  moveto\\n', x_ps, y_ps );\n      else\n        fprintf ( file_unit, '%3d  %3d  lineto\\n', x_ps, y_ps );\n      end\n\n    end\n\n    fprintf ( file_unit, 'stroke\\n' );\n\n  end\n\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, 'restore  showpage\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '%  End of page.\\n' );\n  fprintf ( file_unit, '%\\n' );\n  fprintf ( file_unit, '%%Trailer\\n' );\n  fprintf ( file_unit, '%%EOF\\n' );\n\n  fclose ( file_unit );\n\n  return\nend\n", "meta": {"author": "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_fekete_rule/triangle_points_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.5928412170279178}}
{"text": "% The COBRAToolbox: testConvertHypergraphToBipartiteGraph.m\n%\n% Purpose:\n%     - testconvertHypergraphToBipartiteGraph tests the convertHypergraphToBipartiteGraph\n%     function and its different methods\n%\n% Note:\n%      - test can be extended to test the performance of ConvertHypergraphToBipartiteGraph\n%        with B2 = hypergraph2bipartgraph(S~=0);\n%\n% Author:\n%     - original file: Marouen BEN GUEBILA - 10/02/2017\n%     - integration of test to CI: Laurent Heirendt - February 2017\n\nglobal CBTDIR\n\n% save the current path\ncurrentDir = pwd;\n\n% initialize the test\nfileDir = fileparts(which('testConvertHypergraph2BipartiteGraph'));\ncd(fileDir);\n\nfor flag = 1:2\n    if flag == 1\n        S = [-1  0  1 ;\n              1 -1  0 ;\n              0  1 -1 ];\n    elseif flag == 2\n        S = [-1; 1; 1; 0];\n    end\n\n    [A, B1] = convertHypergraphToBipartiteGraph(S);\n\n    fprintf('\\nB1\\n');\n    disp(full(B1));\n    fprintf('\\nA\\n');\n    disp(full(A));\n\n    %Compute the strongly connected components of a graph\n    [sci, sizes] = scomponents(A);\n\n    if flag == 1\n        assert(isequal(sci, [1; 1; 1; 1; 1; 1]));\n        assert(sizes == 6)\n    elseif flag == 2\n        assert(isequal(sci, [1; 1; 1; 2; 1;]));\n        assert(isequal(sizes, [4; 1]))\n    end\nend\n\n% test with ecoli_core_model\nload('testDataGraph2Hypergraph.mat');\nmodel = getDistributedModel('ecoli_core_model.mat');\n\nfor printLevel = 0:1\n    [A, B] = convertHypergraphToBipartiteGraph(model.S, printLevel);\n\n    % compare test data and results\n    assert(isequal(A, testA))\n    assert(isequal(B, testB))\nend\n\n% change the directory\ncd(currentDir)\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/verifiedTests/analysis/testTopology/testConvertHypergraphToBipartiteGraph/testConvertHypergraph2BipartiteGraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.5928412007812162}}
{"text": "function fem2d_bvp_serene_test03 ( )\n\n%*****************************************************************************80\n%\n%% FEM2D_BVP_SERENE_TEST03 carries out test case #3.\n%\n%  Discussion:\n%\n%    Use A3, C3, F3, EXACT3, EXACT_UX3, EXACT_UY3.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 June 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  nx = 5;\n  ny = 5;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'FEM2D_BVP_SERENE_TEST03\\n' );\n  fprintf ( 1, '  Solve - del ( A del U ) + C U = F \\n' );\n  fprintf ( 1, '  on the unit square with zero boundary conditions.\\n' );\n  fprintf ( 1, '  A1(X,Y) = 0.0\\n' );\n  fprintf ( 1, '  C1(X,Y) = 1.0\\n' );\n  fprintf ( 1, '  F1(X,Y) = X * ( 1 - X ) * Y * ( 1 - Y ).\\n' );\n  fprintf ( 1, '  U1(X,Y) = X * ( 1 - X ) * Y * ( 1 - Y )\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  This example is contrived so that the system matrix\\n' );\n  fprintf ( 1, '  is the WATHEN matrix.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The grid uses %d by %d nodes.\\n', nx, ny );\n  node_num = fem2d_bvp_serene_node_num ( nx, ny );\n  fprintf ( 1, '  The number of nodes is %d\\n', node_num );\n%\n%  Geometry definitions.\n%\n  x = linspace ( 0.0, 1.0, nx );\n  y = linspace ( 0.0, 1.0, ny );\n\n  show11 = 1;\n\n  u = fem2d_bvp_serene ( nx, ny, @a3, @c3, @f3, x, y, show11 );\n\n  if ( nx * ny <= 25 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '     I     J    X         Y         U         Uexact    Error\\n' );\n    fprintf ( 1, '\\n' );\n\n    k = 0;\n\n    for j = 1 : ny\n\n      if ( mod ( j, 2 ) == 1 )\n        inc = 1;\n      else\n        inc = 2;\n      end\n\n      for i = 1 : inc : nx\n        k = k + 1;\n        uexact = exact3 ( x(i), y(j) );\n        fprintf ( 1, '  %4d  %4d  %8f  %8f  %8f  %8f  %8e\\n', ...\n          i, j, x(i), y(j), u(k), uexact, abs ( u(k) - uexact ) );\n      end\n    end\n\n  end\n\n  e1 = fem2d_l1_error_serene ( nx, ny, x, y, u, @exact3 );\n  e2 = fem2d_l2_error_serene ( nx, ny, x, y, u, @exact3 );\n  h1s = fem2d_h1s_error_serene ( nx, ny, x, y, u, @exact_ux3, @exact_uy3 );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  l1 error   = %g\\n', e1 );\n  fprintf ( 1, '  L2 error   = %g\\n', e2 );\n  fprintf ( 1, '  H1S error  = %g\\n', h1s );\n%\n%  Pull out the Wathen matrix from MATLAB.\n%  It will have been multiplied by a random scale factor.\n%  While my numbering scheme is\n%    3  2  1\n%    4     8\n%    5  6  7\n%  the numbering scheme used here is \n%    1  2  3\n%    4     5\n%    6  7  8\n%    \n%\n  A = gallery ( 'wathen', 1, 1 );\n  A = full ( A );\n  s = 0.5 * A(1,3);\n  A = A / s;\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  WATHEN Matrix from \"gallery(''wathen'',1,1)\"\\n' );\n  fprintf ( 1, '\\n' );\n  i = [3,2,1,4,6,7,8,5];\n  A(i,i)\n\n  return\nend\nfunction value = a3 ( x, y )\n\n%*****************************************************************************80\n%\n%% A3 evaluates A function #3.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 June 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X, Y, the evaluation point.\n%\n%    Output, real VALUE, the value of A(X).\n%\n  value = 0.0;\n\n  return\nend\nfunction value = c3 ( x, y )\n\n%*****************************************************************************80\n%\n%% C3 evaluates C function #3.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 June 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X, Y, the evaluation point.\n%\n%    Output, real VALUE, the value of C(X).\n%\n  value = 1.0;\n\n  return\nend\nfunction value = exact3 ( x, y )\n\n%*****************************************************************************80\n%\n%% EXACT3 evaluates exact solution #3.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 June 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X, Y, the evaluation point.\n%\n%    Output, real VALUE, the value of the solution.\n%\n  value = x .* ( 1.0 - x ) .* y .* ( 1.0 - y );\n\n  return\nend\nfunction value = exact_ux3 ( x, y )\n\n%*****************************************************************************80\n%\n%% EXACT_UX3 evaluates the derivative dUdX of exact solution #3.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 June 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X, Y, the evaluation point.\n%\n%    Output, real VALUE, the value of dUdX.\n%\n  value = ( 1.0 - 2.0 * x ) .* ( y - y .* y );\n\n  return\nend\nfunction value = exact_uy3 ( x, y )\n\n%*****************************************************************************80\n%\n%% EXACT_UY3 evaluates the derivative dUdY of exact solution #3.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 June 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X, Y, the evaluation point.\n%\n%    Output, real VALUE, the value of dUdX.\n%\n  value = ( x - x .* x ) .* ( 1.0 - 2.0 * y );\n\n  return\nend\nfunction value = f3 ( x, y )\n\n%*****************************************************************************80\n%\n%% F3 evaluates right hand side function #3.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 June 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X, Y, the evaluation point.\n%\n%    Output, real VALUE, the value of the right hand side.\n%\n  value = x .* ( 1.0 - x ) .* y .* ( 1.0 - y );\n\n  return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_bvp_serene/fem2d_bvp_serene_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.592841200781216}}
{"text": "function [t1,pd] = relaxFitT1_lsq(data,flipAngles,tr,b1Map)\n%\n% [t1,pd] = relaxFitT1(data,flipAngles,tr,b1Map)\n% \n% Computes a linear fit of the the T1 estimate for all voxels. The data can\n% be passed as either a 4d array of X x Y x Z x nT1Measurements or an array of\n% size nVoxels x nT1Measurements. THe b1Map can be either be a scalar (to\n% correct for a constant bias across the whole image), or an image the same\n% size as one of the t1 measurments (ie. either X x Y x Z or nVoxels x 1).\n%\n% We allow multiple b1 maps to correct for different sets of measurements.\n% If there is more than 1 b1 map, then each row of the flip angle array\n% will be corrected by the corresponding b1 map. E.g., flipAngles(1,:) will\n% be corrected by b1Map(:,:,:,1), flipAngles(2,:) will be corrected by\n% b1Map(:,:,:,2), etc. The flip angle corresponding to each t1 should be\n% specified using the linear index. E.g., flipAngle(1) for t1(:,:,:,1),\n% flipAngle(2) for t1(:,:,:,2), etc.\n%\n% Returns:\n%   T1: T1 estimate (seconds)\n%   PD: a map that includes spin-density (M0), scanner scaling constant\n%       (G), and T2*: PD = M0 * G * exp(-TE / T2*).\n%\n% SEE ALSO:\n% \n% relaxMtFit.m to fit the f and k maps to the output of this function.\n%\n% HISTORY:\n% 2008.02.26 RFD: wrote it.\n\nif(~exist('b1Map','var')||isempty(b1Map))\n  b1Map = 1;\nend\n\ntheta = flipAngles*pi/180;\nszT1 = size(data);\nszB1 = size(b1Map);\nif(numel(szT1)>2)\n   nVox = prod(szT1(1:3));\n   nT1 = szT1(4);\n   data = reshape(data,nVox,nT1);\n   if(numel(b1Map)>1)\n       nB1 = szB1(4);\n       b1Map = reshape(b1Map,nVox,nB1);\n   else\n       nB1 = 1;\n   end\nelse\n   nVox = size(data,1);\n   nT1 = size(data,2);\n   nB1 = size(b1Map,2);\nend\nif(nB1>1)\n    if(size(theta,1)~=nB1)\n        error('The number of B1 maps must match the number of rows in the flip angle array.');\n    end\n    b1Inds = repmat([1:nB1]',1,size(theta,2));\nelse\n    b1Inds = repmat([1],1,numel(theta));\nend\ntheta = theta(:)';\nb1Inds = b1Inds(:)';\n   \n% The code below (esp ndfun) doesn't work when we have Inf or NaN, so:\nb1Map(~isfinite(b1Map)) = 1;\ndata(~isfinite(data)) = 0;\n\n%% NON-LINEAR T1 FIT\n%\n\n\n% Fit a line to the data in each voxel to estimate T1.\n% We'll use an eigenvector formulation since we already have a \n% vectorized eigenvector decompostion coded up.\n\n% Build a matrix M where M = [x1-x0 y1-y0; x2-x0 y2-y0; ... xn-x0 yn-y0]. \n% To make it work with ndfun, we need to reshape things a bit.\nM = zeros(nT1,2,nVox);\nfor(ii=1:nT1)\n  correctedFlip = theta(ii).*b1Map(:,b1Inds(ii));\n  M(ii,1,:) = abs(data(:,ii)./tan(correctedFlip));\n  M(ii,2,:) = abs(data(:,ii)./sin(correctedFlip));\nend\nM0 = mean(M,1);\nfor(ii=1:size(M,1))\n  M(ii,:,:) = M(ii,:,:) - M0;\nend\n% The best-fitting line is the eigenvector corresponding to\n% the largest eigenvalue of eig(M'*M):\n[vec,val] = ndfun('eig',ndfun('mult',permute(M,[2 1 3]),M));\n% The slope (m) of the line is simply the ratio of y to x and the\n% intercept (b) is y-m*x\n% Note that the eigenvalues from ndfun are sorted in descending\n% order, opposite from Matlab's 'eig'.\nm = vec(2,1,:)./vec(1,1,:);\n%b = M0(:,2,:)-m.*M0(:,1,:);\n\n% *** CHECK THIS\n%m(m<=0) = NaN;\nm = abs(squeeze(m));\nm(m<0.5) = 0.5;\n\nt1 = (-tr/1000)./log(m);\n% Clip to plausible values\nt1(isnan(t1)|t1<0.1) = 0.1;\nt1(t1>5) = 5;\n\n%pd = b./(1-m);\n%pd(pd>5e5) = 5e5;\n\npd = zeros(nVox,nT1);\n% We could use m here, but we've already clipped t1 to plausible values, so recomputing \n% the slope here provides a sane range of pd values.\nt1tr = exp(-tr/1000./t1);\nfor(ii=1:nT1)\n    correctedFlip = theta(ii).*b1Map(:,b1Inds(ii));\n    pd(:,ii) = data(:,ii)./sin(correctedFlip).*((1-cos(correctedFlip).*t1tr)./(1-t1tr));\nend\n% Could do least squares for better PDmap?\npd = mean(pd,2);\n\nif(numel(szT1)>ndims(data))\n   t1 = reshape(t1,szT1(1:3));\n   pd = reshape(pd,szT1(1:3));\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/mrQuant/relaxometry/relaxFitT1_lsq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5927984516568771}}
{"text": "function y = icplxdual2D(w, J, Fsf, sf)\n\n% Inverse Dual-Tree Complex 2D Discrete Wavelet Transform\n% \n% USAGE:\n%   y = icplxdual2D(w, J, Fsf, sf)\n% INPUT:\n%   w - wavelet coefficients\n%   J - number of stages\n%   Fsf - synthesis filters for final stage\n%   sf - synthesis filters for preceeding stages\n% OUTPUT:\n%   y - output array\n% See cplxdual2D\n%\n% WAVELET SOFTWARE AT POLYTECHNIC UNIVERSITY, BROOKLYN, NY\n% http://taco.poly.edu/WaveletSoftware/\n\nfor j = 1:J\n    for m = 1:3\n        [w{j}{1}{1}{m} w{j}{2}{2}{m}] = pm(w{j}{1}{1}{m},w{j}{2}{2}{m});\n        [w{j}{1}{2}{m} w{j}{2}{1}{m}] = pm(w{j}{1}{2}{m},w{j}{2}{1}{m});\n    end\nend\n\ny = zeros(size(w{1}{1}{1}{1})*2);\nfor m = 1:2\n    for n = 1:2\n        lo = w{J+1}{m}{n};\n        for j = J:-1:2\n            lo = sfb2D(lo, w{j}{m}{n}, sf{m}, sf{n});\n        end\n        lo = sfb2D(lo, w{1}{m}{n}, Fsf{m}, Fsf{n});\n        y = y + lo;\n    end\nend\n\n% normalization\ny = y/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_Proximal/Denoising/WaveletFunctions/icplxdual2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5927984458901192}}
{"text": "function [centroid, dimension_weight, class] = Entropy_Weighting_Subspace_Kmeans(data, iteration, K, beta, lambda, verbose)\n\n% Pre-allocate weights\ncentroid = zeros(K,size(data,2)); % centroid for each class\nclass = zeros(size(data,1),1); % classification result for each observation\ndimension_weight = ones(K,size(data,2)); % weights for each dimension in each class\n\n% Initialization\nn = size(data,1);\nJ = 0; % used to record objective function value\n\n% First round\ncentroid = data(unidrnd(n,K,1),:); % randomly choose K initial centroids \ndimension_weight = 1/size(data,2) * dimension_weight; % initialize weights for each dimension using uniform distribution\n\n% Partially optimization\nfor i = 1:iteration\n    \n    J0 = J;\n    \n    % body part\n    class = classify(centroid,dimension_weight,data);\n    centroid = centroid_update(centroid,data,class);\n    [dimension_weight,J] = dimension_weight_update(K,centroid,class,dimension_weight,data,beta,lambda);\n    \n    % whether display intermediate information\n    if(verbose == 1)\n        disp(['Objective Function(J) Value: ',num2str(J)]);\n    end\n    \n    % early stop condition\n    if(abs(J-J0)<1e-9)\n        fprintf('*** Clustering terminates after %i iterations ***\\n',i);\n        break;\n    end\nend\nend\n\n% Details on the scheme of updating dimension weights\nfunction [alpha,J] = dimension_weight_update(K,m,c,alpha,data,beta)\n\n  % Under writting...\n  \nend\n\nfunction [result] = classify(m,alpha,data)\nresult = zeros(size(data,1),1);\n% Construct temporary matrix for efficiently computing dimention-weighted distance\nmatrix = zeros(size(m,1),size(data,2));\nfor i = 1:size(result,1)\n    for j = 1:size(m,1)\n        matrix(j,:) = (m(j,:)-data(i,:)) .* (m(j,:)-data(i,:));\n    end\n    temp = sum(alpha .* matrix,2);\n    % To avoid more than one class having the minimum distance.\n    t_index = find(temp == min(temp));\n    result(i,1) = t_index(1,1);\nend\nend\n\nfunction [m] = centroid_update(m,data,c)\nfor i = 1:size(m,1)\n    if(~isempty(data(c==i,:)))\n        m(i,:) = mean(data(c==i,:),1);\n    else\n        continue;\n    end\nend\nend\n\n\n\n\n", "meta": {"author": "xuyxu", "repo": "Clustering", "sha": "f1a0d315c9ebd668dbd02d34497af034e51b62d2", "save_path": "github-repos/MATLAB/xuyxu-Clustering", "path": "github-repos/MATLAB/xuyxu-Clustering/Clustering-f1a0d315c9ebd668dbd02d34497af034e51b62d2/lib/Entropy_Weighting_Subspace_Kmeans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5927984404600956}}
{"text": "function model = ml_trainproximal(varargin)\n% Learn a linear probabilistic model proximal splitting methods.\n% Model = ml_trainproximal(Trials, Targets, Lambdas, Options...)\n%\n% This function allows to implement linear or logistic regression using a variety of regularization\n% terms and combinations thereof using proximal splitting [1].\n%\n% In:\n%   Trials       : training data matrix, as in ml_train\n%\n%   Targets      : 1d target variable vector, as in ml_train\n%\n%   LossType     : loss function to be used,\n%                  'logistic' for classification (default)\n%                  'squared' for regression\n%                  'hyperbolic-secant' special-purpose for super-Gaussian estimation\n%\n%   Regularizers : Definition of the regularization terms. Any combination of terms is permitted.\n%\n%\n%   Options  : optional name-value parameters to control the training details:\n%\n%               'regweights' : Weights of the regularizers. This is a vector of (relative) regularization\n%                              parameters. If [] set to 1/N for N regularizers. (default: [])\n%                              Can also be a cell array of (normalized) weight vectors; in this case \n%                              it it simultaneously optimized together with the lambdas.\n%\n%               'solverOptions' : cell array of name-value pairs to control how the outer ADMM solver\n%                                 behaves\n%\n%                    'abs_tol' : Absolute tolerance criterion. (default: 10e-4)\n%\n%                    'rel_tol' : Relative tolerance criterion. (default: 10e-3)\n%\n%                    'maxit' : Maximum number of iterations. (default: 1000)\n%\n%                    'rho' : Initial coupling parameter. For proximal algorithms this is the coupling strength\n%                            between the terms between updates. Increasing this can improve the convergence\n%                            speed but too strong values can prevent any convergence. (default: 1)\n%\n%                    'rho_update' : Update Rho. Whether to update rho dynamically according to 3.4.1 in [2].\n%                                   Note, this can sometimes cause r_norm, s_norm to \"blow up\". (default: true)\n%\n%                    'rho_cutoff' : Rho update threshold. (default: 10)\n%\n%                    'rho_incr' : Rho update increment factor. (default: 2)\n%\n%                    'rho_decr' : Rho update decrement factor. (default: 2)\n%\n%               'lbfgsOptions' : cell array of name-value pairs to control how the inner LFBGS solver\n%                                behaves\n%\n%                    'm' : LBFGS history length. The number of corrections to approximate the inverse\n%                          hessian matrix. (default: 6)\n%\n%                    'epsilon' : Tolerance criterion.  A minimization terminates when ||g|| < epsilon*max(1,||x||).\n%                                (default: 1e-3)\n%\n%                    'past' : Distance for delta-based convergence test. (default: 0)\n%\n%                    'delta' : Delta for convergence test. (default: 1e-5)\n%\n%                    'MaxIter' : Maximum number of iterations. (default: 10)\n%\n%                    'linesearch' : The line search algorithm. Can be any of the following:\n%                                   {'more_thuente','backtracking_armijo','backtracking_wolfe','backtracking_strong_wolfe'}\n%                                   (default: more_thuente)\n%\n%                    'max_linesearch' : Maximum number of trials for the line search. (default: 40)\n%\n%                    'min_step' : Minimum step of the line search. (default: 1e-20)\n%\n%                    'max_step': Maximum step of the line search routine. (default: 1e20)\n%\n%                    'ftol' : Line search tolerance F. A parameter to control the accuracy of the\n%                             line search routine. (default: 1e-4)\n%\n%                    'wolfe' : Coefficient for the Wolfe condition. (default: 0.9)\n%\n%                    'gtol' : Line search tolerance G. A parameter to control the accuracy of the\n%                             line search routine. (default: 0.9)\n%\n%                    'xtol' : Machine precision for floating-point values. (default: 1e-16)\n%\n%                    'DerivativeCheck' : Derivative check using finite differences. (default: 'off')\n%\n%                    'Display' : Options for displaying progress. (default: 'none')\n%\n%               'lambdaSearch' : cell array of name-value pairs governing the regularization path search\n%\n%                   'lambdas' : Regulariation parameters. Controls the sparsity/simplicity of the result.\n%                               Typically, this is an interval to scan. (default: 2.^(3:-0.25:-5))\n%\n%                   'nfolds' : Cross-validation folds. The cross-validation is used to determine the best\n%                              regularization parameter value (default: 5)\n%\n%                   'foldmargin' : Margin (in trials) between folds. This is the number of trials omitted\n%                                  between training and test sets. (default: 5)\n%\n%                   'cvmetric' : metric to use for parameter optimization; can be any of those supported by\n%                                ml_calcloss. In particular, 'auc' is a good idea if the classification\n%                                task is between highly imbalanced classes. (default: '' = auto-determine)\n%\n%                   'return_regpath' : Return the entire regularization path. If false, only the best model will\n%                                      be returned. (default: true)\n%\n%\n%               'scaling': pre-scaling of the data (see hlp_findscaling for options) (default: 'std')\n%\n%               'data_weights': dataset weights; optional vector of weights for each task in the\n%                               training data (one element per task in a multi-task learning setting) (default: [])\n%\n%               'includebias': whether to include a bias param (default: true)\n%\n%               'verbosity': verbosity level, 0-3 (0=no output)\n%\n% Out:\n%   Models   : a predictive model\n%\n% Examples:\n%\n% Notes:\n%   When linear operators and shapes are given as string expressions the variables a to h can be used as short-hands\n%   to refer to the number of array elements along respective dimension.\n%\n% See also:\n%   ml_predictproximal\n%\n% References:\n%  [1] Patrick L. Combettes & Jean-Christophe Pesquet, \"Proximal Splitting Methods in Signal Processing\",\n%      in Fixed-Point Algorithms for Inverse Problems in Science and Engineering, Springer Optimization and Its Applications\n%      pp. 185-212, 2011\n%\n%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n%                                2013-02-04\ndp;\n\n% definition of regularization terms\nregularizer_params = @(name) arg_subswitch({lower(name),name},{'none'},{ ...\n    'none', {}, ...\n    'l1', { ...\n    arg({'A','LinearOperator'},'@(x)x',[],'Linear transform. The norm applies to the linearly transformed feature vector. Either an expression that is evaluated in the workspace or a function handle. When defining the linear operator as an anonymous function, the variables a to h can be used to refer to the sizes of the first 8 dimensions of x.'), ...\n    arg({'weights','FeatureWeights'},[],[],'Weights on the features. Allows for a reweighted the norm (e.g., to impose certain types of priors).'), ...\n    }, ...\n    'l2', { ...\n    arg({'A','LinearOperator'},'@(x)x',[],'Linear transform. The norm applies to the linearly transformed feature vector. Either an expression that is evaluated in the workspace or a function handle. When defining the linear operator as an anonymous function, the variables a to h can be used to refer to the sizes of the first 8 dimensions of x.'), ...\n    arg({'nonorthogonal_transform','NonorthogonalTransform'},false,[],'Linear operator is non-orthogonal. In this case an iterative method will be used that is faster and numerically more robust than letting ADMM do it.'), ...\n    arg({'y','TargetValues'},[],[],'Recenter the norm around target values. This allows for regression problems as side assumptions.'), ...\n    arg({'weights','FeatureWeights'},[],[],'Weights on the features. Allows for a reweighted norm (e.g., to impose certain types of priors).'), ...\n    }, ...\n    'l1/l2', { ...\n    arg({'A','LinearOperator'},'@(x)x',[],'Linear transform. The norm applies to the linearly transformed feature vector. Either an expression that is evaluated in the workspace or a function handle. When defining the linear operator as an anonymous function, the variables a to h can be used to refer to the sizes of the first 8 dimensions of x.'), ...\n    arg({'g_d','GroupIndices'},uint32([]),[],'Feature group indices. This is a vector of indices that form the support of all groups; can also be a matrix. If empty, this defaults to columnwise sparsity.'), ...\n    arg({'g_t','GroupSizes'},uint32([]),[],'Feature group sizes. This is a vector of successive range lengths on the indices.'), ...\n    arg({'weights','FeatureWeights'},[],[],'Weights on the features. Allows for a reweighted norm (e.g., to impose certain types of priors).'), ...\n    arg({'weights1','GroupWeights'},[],[],'Weights on the groups. Allows for a reweighted the norm (e.g., to impose certain types of priors).') ...\n    }, ...\n    'l1/linf', { ...\n    arg({'A','LinearOperator'},'@(x)x',[],'Linear transform. The norm applies to the linearly transformed feature vector. Either an expression that is evaluated in the workspace or a function handle. When defining the linear operator as an anonymous function, the variables a to h can be used to refer to the sizes of the first 8 dimensions of x.'), ...\n    arg({'g_d','GroupIndices'},uint32([]),[],'Feature group indices. This is a vector of indices that form the support of all groups; can also be a matrix. If empty, this defaults to columnwise sparsity.'), ...\n    arg({'g_t','GroupSizes'},uint32([]),[],'Feature group sizes. This is a vector of successive range lengths on the indices.'), ...\n    arg({'weights','FeatureWeights'},[],[],'Weights on the features. Allows for a reweighted norm (e.g., to impose certain types of priors).'), ...\n    arg({'weights1','GroupWeights'},[],[],'Weights on the groups. Allows for a reweighted the norm (e.g., to impose certain types of priors).') ...\n    }, ...\n    'tv2d', { ...\n    arg({'A','LinearOperator'},'@(x)x',[],'Linear transform. The norm applies to the linearly transformed feature vector. Either an expression that is evaluated in the workspace or a function handle. When defining the linear operator as an anonymous function, the variables a to h can be used to refer to the sizes of the first 8 dimensions of x.'), ...\n    arg({'shape','Shape'},'',[],'Final feature shape. Allows to reshape the linearly transformed features into a matrix to apply matrix norms. If empty defaults to the shape of the original features.','shape','row'), ...\n    arg({'useGPU','UseGPU'},false,[],'Use GPU acceleration. This is experimental and requires that UnLocBox is started with GPU support enabled.'), ...\n    }, ...\n    'tv3d', { ...\n    arg({'A','LinearOperator'},'@(x)x',[],'Linear transform. The norm applies to the linearly transformed feature vector. Either an expression that is evaluated in the workspace or a function handle. When defining the linear operator as an anonymous function, the variables a to h can be used to refer to the sizes of the first 8 dimensions of x.'), ...\n    arg({'shape','Shape'},'',[],'Final feature shape. Allows to reshape the linearly transformed features into a matrix to apply matrix norms. If empty defaults to the shape of the original features.','shape','row'), ...\n    arg({'useGPU','UseGPU'},false,[],'Use GPU acceleration. This is experimental and requires that UnLocBox is started with GPU support enabled.'), ...\n    }, ...\n    'trace', { ...\n    arg({'A','LinearOperator'},'@(x)x',[],'Linear transform. The norm applies to the linearly transformed feature vector. Either an expression that is evaluated in the workspace or a function handle. When defining the linear operator as an anonymous function, the variables a to h can be used to refer to the sizes of the first 8 dimensions of x.'), ...\n    arg({'shape','Shape'},'',[],'Final feature shape. Allows to reshape the linearly transformed features into a matrix to apply matrix norms. If empty defaults to the shape of the original features.','shape','row'), ...\n    }}, 'Regularization term. Defines a term in the optimization problem; multiple types are supported and can be mixed freely.');\n\nexpose_handles(@solve_regularization_path,varargin{:});\n\narg_define([0 2],varargin, ...\n    arg_norep('trials'), ...\n    arg_norep('targets'), ...\n    arg({'loss','LossType'}, 'logistic', {'logistic','squared'}, 'Loss function to be used. The logistic loss is suited for classification problems, whereas the squared loss is suited for regression problems.'), ...\n    arg_sub({'regularizers','Regularizers'},{},{ ...\n        regularizer_params('Term1'), ...\n        regularizer_params('Term2'), ...\n        regularizer_params('Term3'), ...\n        regularizer_params('Term4'), ...\n        regularizer_params('Term5'), ...\n        regularizer_params('Term6'), ...\n        regularizer_params('Term7')}, 'Definition of the regularization terms. Any combination of terms is permitted.'), ...\n    arg({'regweights','TermWeights'},{[]},[],'Weights of the regularizers. This is a cell array of vectors of (relative) regularization parameters. Default is 1/N for N regularization terms. The cell array lists all possible assignments to search over.','type','expression','shape','row'), ...\n    arg_sub({'solverOptions','SolverOptions'},{},{ ...\n        arg({'maxit','MaxIterations'},2000,uint32([1 100 5000 10000]),'Maximum number of iterations.'), ...\n        arg({'rel_tol','RelativeTolerance'},1e-3,[0 1],'Relative tolerance criterion. If the relative difference between two successive iterates is lower than this value the algorithm terminates.'),...\n        arg({'abs_tol','AbsoluteTolerance'},0.000001,[0 Inf],'Absolute tolerance criterion. If the objective function value falls below this the algorithm terminates.'), ...\n        arg({'rho','CouplingParameter'},4,[0 1 30 Inf],'Initial coupling parameter. For proximal algorithms this is the coupling strength between the terms between updates. Increasing this can improve the convergence speed but too strong values can prevent any convergence.'), ...\n        arg({'rho_update','RhoUpdate'},true,[],'Update Rho. Whether to update rho dynamically according to 3.4.1 in [1]. Note, this can sometimes cause r_norm, s_norm to \"blow up\".'), ...\n        arg({'rho_cutoff','RhoUpdateThreshold'},10.0,[0 2 20 Inf],'Rho update threshold.','guru',true), ...\n        arg({'rho_incr','RhoUpdateIncr'},2.0,[1 1.5 3 Inf],'Rho update increment factor.','guru',true), ...\n        arg({'rho_decr','RhoUpdateDecr'},2.0,[1 1.5 3 Inf],'Rho update decrement factor.','guru',true), ...\n        arg({'warmstart','Warmstart'},true,[],'Warm-start through regularization path. Enabling this is more efficient but convergence issues can be harder to trace down.') ...\n    }, 'Controls the behavior of the ADMM optimization algorithm.'), ...\n    arg_sub({'lbfgsOptions','LBFGSOptions'},{},{ ...\n        arg({'MaxIter','MaxIterations'},10,uint32([1 1 20 1000]),'Maximum number of iterations.'), ...\n        arg({'m','HessianHistory'},6,uint32([1 4 10 20]),'LBFGS history length. The number of corrections to approximate the inverse hessian matrix.','guru',true), ...\n        arg({'epsilon','Epsilon'},1e-3,[],'Tolerance criterion.  A minimization terminates when ||g|| < epsilon*max(1,||x||).'), ...\n        arg({'past','DeltaDistance'},0,[],'Distance for delta-based convergence test.','guru',true), ...\n        arg({'delta','Delta'},1e-5,[],'Delta for convergence test.','guru',true), ...\n        arg({'linesearch','LineSearchAlgorithm'},'more_thuente',{'more_thuente','backtracking_armijo','backtracking_wolfe','backtracking_strong_wolfe'},'The line search algorithm.','guru',true), ...\n        arg({'max_linesearch','MaxLineSearch'},40,uint32([0 10 100 1000]),'Maximum number of trials for the line search.','guru',true), ...\n        arg({'min_step','MinStepsize'},1e-20,[],' Minimum step of the line search.','guru',true), ...\n        arg({'max_step','MaxStepsize'},1e20,[],' Maximum step of the line search routine.','guru',true), ...\n        arg({'ftol','FTolerance'},1e-4,[],'Line search tolerance F. A parameter to control the accuracy of the line search routine.','guru',true), ...\n        arg({'wolfe','WolfeCoefficient'}, 0.9,[],'Coefficient for the Wolfe condition.','guru',true), ...\n        arg({'gtol','GTolerance'},0.9,[],'Line search tolerance G. A parameter to control the accuracy of the line search routine.','guru',true), ...\n        arg({'xtol','XTolerance'},1e-16,[],'Machine precision for floating-point values.','guru',true), ...\n        arg({'useGPU','UseGPU'},true,[],'Run on the GPU if possible.'), ...\n        arg('DerivativeCheck','off',{'off','on'},' Derivative check using finite differences.','guru',true), ...\n        arg({'Display','Verbosity'},'none',{'none','on'},'Options for displaying progress.') ...\n    },'Options of the inner LBFGS solver. This is for the logistic objective function.'), ...\n    arg_sub({'lambdaSearch','LambdaSearch'},{},{ ...\n        arg({'lambdas','Lambdas'}, 2.^(3:-0.66:-8), [0 2^-8 2^15 Inf], 'Regulariation parameters. Controls the sparsity/simplicity of the result. Typically, this is an interval to scan, such as 2.^(10:-1:-15).'), ...\n        arg({'nfolds','NumFolds'},5,[],'Cross-validation folds. The cross-validation is used to determine the best regularization parameter. If in 0..1, k calulated as fraction of #trials, if in -1..0, taken as the p in p-holdout, if given as [low, high], taken as a fractional interval for interval holdout.','shape','row'),...\n        arg({'force_cv','ForceCV'},false,[],'Force cross-validation. This will perform a nested cross-validation even if there is only one lambda/regweight (i.e., a search wouldn''t be strictly necessary). Can be useful to simultaneously run multiple within-task/subject cross-validations given fixed reg parameters.','shape','row'),...\n        arg({'foldmargin','FoldMargin'},0,uint32([0 0 10 1000]),'Margin between folds. This is the number of trials omitted between training and test set.'), ...\n        arg({'cvmetric','ParameterMetric'},'',{'','kld','nll','mcr','mae','mse','max','rms','bias','medse','auc','cond_entropy','cross_entropy','f_measure'},'Metric for Parameter Optimization. By default auto-determined; can be any of the ml_calcloss-supported metrics. In particular, auc is a good idea if the classification task is between highly imbalanced classes.') ...\n        arg({'return_regpath','ReturnRegpath'}, true, [], 'Return the entire regularization path. This is for the best relative weighting of terms. If false, only the best model will be returned.'), ...\n        arg({'return_reggrid','ReturnReggrid'}, false, [], 'Return the entire regularization grid. This also returns regularization paths for all other relative weightings. Warning: this can require a lot of memory (depending on model size).'), ...\n        arg({'history_traces','HistoryTraces'}, false, [], 'Return history traces. If true, optimization history traces will be returned. Warning: this will require a very large amount of memory (depending on model size).'), ...\n    }, 'Controls the search for the optimal regularization parameter.'), ...\n    arg({'scaling','Scaling'}, 'std', {'none','center','std','minmax','whiten'}, 'Pre-scaling of the data. For the regulariation to work best, the features should either be naturally scaled well, or be artificially scaled.'), ...\n    arg_nogui({'shape','Shape'}, [], [], 'Reshaping for features. Allows to reshape (perhaps vectorized) features into a particular representation.','shape','row'), ...\n    arg({'data_weights','DataWeights'}, [], [], 'Dataset weights. Optional vector of weights for each task in the training data (one element per task in a multi-task learning setting).'), ...\n    arg({'verbosity','Verbosity'},1,uint32([1 5]),'Diagnostic output level. Zero is off, 1 only shows cross-validation diagnostics, 2 shows solver diagnostics, 3 shows iteration diagnostics.'), ...\n    arg({'continuous_targets','ContinuousTargets','Regression'}, false, [], 'Whether to use continuous targets. This allows to implement some kind of damped regression approach.'),...\n    arg({'votingScheme','VotingScheme'},'1v1',{'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    arg({'parallel_scope','ParallelScope'},[],[],'Optional parallel scope. If this is a cell array of name-value pairs, cluster resources will be acquired with these options for the duration of bci_train (and released thereafter) Options as in env_acquire_cluster.','type','expression'), ...\n    arg({'engine_cv','ParallelEngine','engine'},'global',{'global','local','BLS','Reference','ParallelComputingToolbox'}, 'Parallel engine to use. This can either be one of the supported parallel engines (BLS for BCILAB Scheduler, Reference for a local reference implementation, and ParallelComputingToolbox for a PCT-based implementation), or local to skip parallelization altogether, or global to select the currently globally selected setting (in the global tracking variable).'), ...\n    arg({'includebias','IncludeBias','bias'},true,[],'Include bias param. Also learns an unregularized bias param (strongly recommended for typical classification problems).'));\n\nif ~iscell(targets)\n    trials = {trials};\n    targets = {targets}; \nend\n\nfor t=1:length(trials)\n    trials{t} = real(trials{t}); end\n\n% find all target classes (if classification)\nnTasks = length(targets);\nclasses = unique(vertcat(targets{:}));\nif length(classes) > 2 && strcmp(loss,'logistic') && ~continuous_targets\n    % in the multi-class case we use the voter for now (TODO: use softmax loss instead)\n    model = ml_trainvote(trials, targets, votingScheme, @ml_trainproximal, @ml_predictproximal, varargin{:});\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        \n    if isscalar(lambdaSearch.nfolds)\n        % if nfolds is in [0..1], we take it as a function of #trials\n    if lambdaSearch.nfolds < 1 && lambdaSearch.nfolds > 0\n        lambdaSearch.nfolds = round(lambdaSearch.nfolds*mean(cellfun('length',targets))); end\n        % (if instead it's in [-1..0], we take it as the p in p-holdout)\n        % (else if an integer, we take it as the number of folds)\n    nFolds = ceil(abs(lambdaSearch.nfolds));\n    elseif isequal(size(lambdaSearch.nfolds), [1 2])\n        % if nfolds is of the form [low high], we treat these numbers as an interval specification,\n        % where low and high are taken as fractions of the number of trials\n        nFolds = 1;\n    else\n        error('NumFolds format is unsupported.');\n    end\n    \n    % sanitize some more inputs\n    solverOptions.verbose = max(0,verbosity-1);    \n    if isnumeric(regweights)\n        regweights = {regweights}; end\n    nRegweights = length(regweights);\n    \n    % lambdas need to be sorted in descending order for the warm-starting to work\n    nLambdas = length(lambdaSearch.lambdas);\n    lambdaSearch.lambdas = sort(lambdaSearch.lambdas,'ascend');\n    if strcmp(lambdaSearch.cvmetric,'mcr')\n        lambdaSearch.cvmetric = ''; end\n    \n    % determine featureshape and vectorize data if necessary \n    [featureshape,trials,vectorize_trials] = utl_determine_featureshape(trials,shape);\n    weightshape = [featureshape nTasks];\n    \n    % optionally scale the data\n    sc_info = hlp_findscaling(vertcat(trials{:}),scaling);\n    trials = cellfun(@(t)hlp_applyscaling(t,hlp_findscaling(t,scaling)),trials,'UniformOutput',false);\n    \n    % optionally remap target labels to -1,+1\n    if strcmp(loss,'logistic') && length(classes) == 2 && ~continuous_targets\n        for t=1:nTasks\n            targets{t}(targets{t}==classes(1)) = -1;\n            targets{t}(targets{t}==classes(2)) = +1;\n        end\n    end\n    \n    % ensure that data_weights exists and is scaled properly (we normalize data_weights to sum to\n    % nTasks, since the regularizers will usually also be scaled by nTasks)\n    if isempty(data_weights)\n        data_weights = ones(1,nTasks); end\n    data_weights = data_weights/sum(data_weights)*nTasks;\n        \n    % learn a sequence of models across the given lambda's, on all the data (i.e. the regularization path)\n    if verbosity\n        disp('Running optimization...'); end\n    \n    \n    % run a cross-validation to score the lambdas and regweights\n\n    % loss_means{regweight,task}(fold,lambda) is the average loss for a given task, regularization weight setting, cross-validation fold, and lambda setting\n    loss_means = cell(nRegweights,nTasks);    \n    % predictions{regweight,task}(trial,lambda) is the classifier prediction for a given task, regweight setting, trial, and lambda choice\n    predictions = repmat(cellfun(@(t)zeros(length(t),nLambdas),targets(:)','UniformOutput',false),nRegweights,1);\n    % foldid{task}(trial) is the fold in which a given trial is in the test set, for a given task\n    if isequal(size(lambdaSearch.nfolds), [1 2])\n        % interval form\n        p = lambdaSearch.nfolds;\n        foldids = cellfun(@(t)(0:length(t)-1)/length(t) > p(1) & (0:length(t)-1)/length(t) < p(2),targets,'UniformOutput',false);\n    elseif lambdaSearch.nfolds < 0 && lambdaSearch.nfolds > -1\n        p = abs(lambdaSearch.nfolds);\n        % negative fractional value encodes p-holdout (positive fractional value is already defined\n        % as the a fraction of the number of trials)\n        foldids = cellfun(@(t)(0:length(t)-1)/length(t)>(1-p),targets,'UniformOutput',false);\n    else\n        foldids = cellfun(@(t)1+floor((0:length(t)-1)/length(t)*nFolds),targets,'UniformOutput',false);\n    end\n    \n    if (nLambdas*nRegweights) > 1 || lambdaSearch.force_cv\n        % for each fold...\n        model_seq = cell(nFolds,nRegweights); % model_seq(fold,regweight}{lambda}{task} is the model for a given fold, regweight and lambda setting, and task\n        history_seq = cell(nFolds,nRegweights); % history_seq(fold,regweight}{lambda}( is a struct of optimization histories for a given fold, regweight and lambda setting, for all concurrent tasks\n        jobs = {}; % compute jobs\n        for f = 1:nFolds\n            % determine training and test set masks\n            % TODO: calc all this per fold and don't recalc below\n            testmask{f} = cellfun(@(foldid)foldid==f,foldids,'UniformOutput',false); % testmask{fold}{task}(trial) a bitmask of test-set trials for a given task\n            trainmask{f} = cellfun(@(x)~x,testmask{f},'UniformOutput',false);           % trainmask{fold}{task}(trial) is a bitmask of train-set trials\n            % cut train/test margins into trainmask\n            for t=1:nTasks\n                testpos = find(testmask{f}{t});\n                for j=1:lambdaSearch.foldmargin\n                    trainmask{f}{t}(max(1,testpos-j)) = false;\n                    trainmask{f}{t}(min(length(testmask{f}{t}),testpos+j)) = false;\n                end\n            end\n\n            % set up design matrices\n            [A{f},y{f},B{f},z{f}] = deal(cell(1,nTasks));\n            for t=1:nTasks\n                % training data\n                A{f}{t} = trials{t}(trainmask{f}{t},:);\n                y{f}{t} = targets{t}(trainmask{f}{t});\n                % test data\n                B{f}{t} = [trials{t}(testmask{f}{t},:) ones(nnz(testmask{f}{t}),double(includebias))];\n                z{f}{t} = targets{t}(testmask{f}{t});\n            end\n\n            % for each relative regularization term weighting...\n            for w = 1:nRegweights\n                jobs{end+1} = {@hlp_diskcache,'predictivemodels',@solve_regularization_path,A{f},y{f},lambdaSearch.lambdas,loss,includebias,verbosity,solverOptions,lbfgsOptions,regularizers,regweights{w},weightshape,data_weights}; end            \n        end\n        \n        % run the jobs\n        results = par_schedule(jobs, 'engine',engine_cv, 'scope',parallel_scope);\n\n        % evaluate results\n        predictions = repmat(cellfun(@(t)zeros(length(t),nLambdas),targets(:)','UniformOutput',false),nRegweights,1);\n        ji = 1;\n        for f = 1:nFolds\n            for w = 1:nRegweights\n                [model_seq{f,w},history_seq{f,w}] = deal(results{ji}.regpath,results{ji}.hist); ji = ji+1;\n                % for each task...\n                for t = 1:nTasks\n                    % calc test-set predictions for each model\n                    for m=nLambdas:-1:1\n                        predictions{w,t}(testmask{f}{t},m) = (B{f}{t}*model_seq{f,w}{m}{t}(:))'; end\n                    if strcmp(loss,'logistic')\n                        predictions{w,t}(testmask{f}{t},:) = 2*(1 ./ (1 + exp(-predictions{w,t}(testmask{f}{t},:))))-1; end\n\n                    % evaluate test-set losses\n                    if isempty(lambdaSearch.cvmetric)\n                        if strcmp(loss,'logistic')\n                            loss_means{w,t}(f,:) = mean(~bsxfun(@eq,z{f}{t},sign(predictions{w,t}(testmask{f}{t},:))));\n                        else\n                            loss_means{w,t}(f,:) = mean((bsxfun(@minus,z{f}{t},predictions{w,t}(testmask{f}{t},:))).^2);\n                        end\n                    else\n                        for m=1:nLambdas\n                            loss_means{w,t}(f,m) = ml_calcloss(lambdaSearch.cvmetric,z{f}{t},predictions{w,t}(testmask{f}{t},m)); end\n                    end\n                end\n            end\n        end\n    else\n        % we skip the nested cross-validation if there is only one lambda and one regweight\n        disp('Skipping nested cross-validation (only 1 lambda/regweight)...'); \n        model_seq = cell(nFolds,nRegweights); \n        history_seq = cell(nFolds,nRegweights);\n        loss_means = repmat({zeros(nFolds,nLambdas)},[nRegweights,nTasks]);\n        lambdaSearch.return_regpath = false;\n    end\n    \n    % pick best lambda and regweights across tasks (averaging over folds)\n    losses = zeros(nRegweights,nLambdas,nTasks);\n    for t=1:nTasks\n        for w=1:nRegweights\n            losses(w,:,t) = mean(loss_means{w,t}, 1); end        \n        joint_losses = mean(losses,3); % nRegweights x nLambdas\n        % find per-task best lambda/regweights\n        [best_regweight_indices,best_lambda_indices] = find(losses(:,:,t) == min(vec(losses(:,:,t))));\n        [dummy,idx] = max(best_lambda_indices); %#ok<ASGLU>\n        best_regweights{t} = regweights{best_regweight_indices(idx)}(:)';\n        best_lambda{t} = lambdaSearch.lambdas(best_lambda_indices(idx));\n    end\n    % find all optima in the loss surface and then pick the minimum at highest lambda (if multiple)\n    [best_regweight_indices,best_lambda_indices] = find(joint_losses == min(joint_losses(:)));\n    [dummy,idx] = max(best_lambda_indices); %#ok<ASGLU>\n    joint_best_regweights = regweights{best_regweight_indices(idx)}(:)';\n    joint_best_lambda = lambdaSearch.lambdas(best_lambda_indices(idx));\n\n    % pick the model at the minimum...\n    if lambdaSearch.return_regpath\n        % run the whole regularization path for the jointly best regweight combination\n        res = hlp_diskcache('predictivemodels',@solve_regularization_path,trials,targets,lambdaSearch.lambdas,loss,includebias,verbosity,solverOptions,lbfgsOptions,regularizers,joint_best_regweights,weightshape,data_weights);\n        [regpath,history] = deal(res.regpath, res.hist);\n        model.regularization_path = regpath;                                  % the model for a given {lambda}{task} at best regweights, for whole data\n        model.regularization_loss = permute(losses(best_regweight_indices(idx),:,:),[2,3,1]);   % the associated loss estimatses for a given (lambda,task)\n        model.ws = regpath{find(lambdaSearch.lambdas == joint_best_lambda,1)};% the best model for a given {task}\n    else\n        res = hlp_diskcache('predictivemodels',@solve_regularization_path,trials,targets,joint_best_lambda,loss,includebias,verbosity,solverOptions,lbfgsOptions,regularizers,joint_best_regweights,weightshape,data_weights);\n        [tmp,history] = deal(res.regpath, res.hist);\n        model.ws = tmp{1};  % optimal model for each {task}\n    end\n    \n    model.w = model.ws;\n    if length(model.w) == 1\n        model.w = model.w{1}; end                   % optimal model for each {task}, or the model if only one task given (without the enclosing cell array)\n    \n    if lambdaSearch.return_reggrid\n        model.regularization_grid = model_seq; end  % sequence of models for each {fold,regweight}{lambda}{task}\n    if lambdaSearch.history_traces\n        model.fold_history = history_seq;           % structure of regpath history for each {fold,regweight}{lambda} -- HUGE!\n        model.regularization_history = history;     % structure of regpath history at best lambda/regweights\n    end\n    model.loss_means = loss_means;                  % overall loss for each {regweight,task}(fold,lambda)\n    model.task_losses = losses;                     % average loss for each (reweight,task,lambda)\n    model.joint_losses = joint_losses;              % average loss for each (regweight,lambda)\n    model.best_regweights = best_regweights;        % best regweights for each {task}\n    model.best_lambda = best_lambda;                % best lambda for each {task}\n    model.joint_best_regweights = joint_best_regweights; % best regweights from all tasks\n    model.joint_best_lambda = joint_best_lambda;         % best lambda from all tasks\n    model.classes = classes;                        % set of class labels in training data\n    model.continuous_targets = continuous_targets;  \n    model.includebias = includebias;                % whether a bias is included in the model\n    model.vectorize_trials = vectorize_trials;      % whether trials need to be vectorized first\n    model.featureshape = featureshape;              % shape vector for features\n    model.sc_info = sc_info;                        % overall scaling info\n    model.loss = loss;                              % loss function name\nend\n\n\n\n% learn the regularization path\nfunction res = solve_regularization_path(A,y,lambdas,loss,includebias,verbosity,solverOptions,lbfgsOptions,regularizersArg,regweights,weightshape,data_weights)\n% solve_regularization_path_version<1.0.3>\nif ~includebias\n    error('This implementation currently requires that a bias is included.'); end\nnTasks = length(A);\n\n% m trials, n features, per task\nm = cellfun('size',A,1);\nn = cellfun('size',A,2);\nif length(unique(n)) > 1\n    error('Each task must have the same number of features.'); end\n\n% w is the concatenation of model weights for all tasks, followed by the unregularized biases for each task\nw = zeros(sum(n) + nTasks,1);\n\n% set up the design matrix A & label vector y\nA = cellfun(@(A)double(A),A,'UniformOutput',false);\ny = cellfun(@(y)double(y(:)),y,'UniformOutput',false);\n\n% set up the data-dependent loss function to use\nswitch loss\n    case 'logistic'\n        C = cellfun(@(A,y)[bsxfun(@times,-y,A) -y],A,y,'UniformOutput',false);\n        if lbfgsOptions.useGPU\n            try\n                C = cellfun(@gpuArray,C,'UniformOutput',false);\n            catch e\n                disp_once(['Could not enable GPU support: ' e.message]);\n            end\n        end\n        Cp = cellfun(@transpose,C,'UniformOutput',false);\n        lossfunc.prox = @(x,gamma,x0) prox_logistic_multitask(C,Cp,x,gamma,x0,m,n,hlp_struct2varargin(lbfgsOptions),data_weights);\n        lossfunc.eval = @(x,lambda) lambda*obj_logistic_multitask(C,x,m,n,data_weights);\n    case 'squared'\n        % append a bias to the design matrix\n        if length(A)>1\n            error('Squared loss with for multi-task case not yet fully implemented.'); end\n        Ao = cellfun(@(A)[A ones(size(A,1),1)],A,'UniformOutput',false);\n        mm = cellfun('size',Ao,1);\n        nn = cellfun('size',Ao,2);\n        % choose the right prox operator\n        if solverOptions.rho_update\n            lossfunc.prox = @(x,gamma,x0) prox_squared_iter(Ao{1},y{1},1/gamma,x,zeros(size(x)),mm,nn,x0);\n        else            \n            Atb = cellfun(@(Ao,y)Ao'*y,Ao,y,'UniformOutput',false);\n            [L,U] = deal(cell(1,nTasks));\n            for t=1:nTasks\n                [L{t},U{t}] = factor(Ao{t},solverOptions.rho/data_weights(t)); end\n            lossfunc.prox = @(x,gamma,x0) prox_squared_factored_multitask(Ao,Atb,L,U,solverOptions.rho,x,zeros(size(x)),mm,nn,data_weights);\n        end\n        lossfunc.eval = @(x,lambda) lambda*obj_squared_multitask(Ao,y,x,mm,nn,data_weights);\n    case 'hyperbolic-secant'\n        % lossfunc.prox = @(x,gamma,x0) prox_hs(y,x,gamma,x0,hlp_struct2varargin(lbfgsOptions));\n        % lossfunc.eval = @(x,lambda) lambda*obj_hs(x,b);\n        error('Hyperbolic-secant loss is not yet implemented.');\n    otherwise\n        error('Unsupported loss function.');\nend\nlossfunc.y0 = [];\nlossfunc = @(lambda)setfield(setfield(lossfunc,'prox',@(x,gamma,x0)lossfunc.prox(x,gamma*lambda,x0)),'eval',@(x)lossfunc.eval(x,lambda)); %#ok<SFLD>\n\n\n% ensure that regularizers is a cell array of structs\nregularizers = {};\nif isstruct(regularizersArg)\n    for k=1:length(fieldnames(regularizersArg))\n        if isfield(regularizersArg,['term' num2str(k)])\n            regularizers{end+1} = regularizersArg.(['term' num2str(k)]); end %#ok<AGROW>\n    end\nelse\n    regularizers = regularizersArg;\nend\n\n\n% set up the regularization functions one by one\nregfuncs = {};\nfor t = 1:length(regularizers)\n    param = regularizers{t};\n    if ~strcmp(param.arg_selection,'none')\n        regfunc = struct();\n        if isfield(param,'weights')\n            param.weights2 = param.weights; end\n        param.verbose = max(0,solverOptions.verbose-2);\n        \n        % rename & evaluate the linear operator expressions\n        if ischar(param.A)\n            try\n                [a,b,c,d,e,f,g,h] = size(reshape(w(1:sum(n)),weightshape)); %#ok<ASGLU>\n                param.A = eval(param.A);\n            catch e\n                env_handleerror(e);\n                disp(['This param does not evaluate correctly: '  param.A]);\n            end\n        end\n        \n        % if the linear operator happens to accept weights in the shape of the original features\n        % (and the numels are matching) then we reshape the weights to that shape before applying\n        % the linear operator\n        try\n            rA = param.A;\n            rA(reshape(w(1:sum(n)),weightshape));\n            param.A = @(x)rA(reshape(x(1:sum(n)),weightshape));\n        catch\n            try\n                param.A(w(1:sum(n)));\n                param.A = @(x)rA(x(1:sum(n)));\n            catch e\n                % sanity check: if this happens either your linear operator is incorrect or\n                % you need to specify NumberOfElements for this term\n                error(['The linear operator ' char(param.A) ' is not applicable to the weights w. Check for syntax errors and sizes.']);\n            end\n        end\n        shape_A_out = size(param.A(w));\n        \n        % if shape for the term is unspecified we assume that it is the output shape of the A\n        % operator\n        if isfield(param,'shape') && isempty(param.shape)\n            param.shape = shape_A_out; end\n        if isfield(param,'shape') && ischar(param.shape)\n            [a,b,c,d,e,f,g,h] = size(reshape(w(1:sum(n)),weightshape)); %#ok<ASGLU>\n            param.shape = eval(param.shape);\n        end\n        \n        % set the A matrix for future reference\n        if isfield(param,'A')\n            rA = param.A;\n        else\n            rA = @(x)x(1:sum(n));\n        end\n        \n        % move the A parameter into regfunc.L (handled by ADMM)\n        if isfield(param,'A') && ~(strcmp(param.arg_selection,'l2') && param.nonorthogonal_transform)\n            regfunc.L = param.A;\n            % remove fields from param\n            param = rmfield(param,'A');\n            if isfield(param,'At')\n                param = rmfield(param,'At'); end\n        else\n            regfunc.L = @(x)x(1:sum(n));\n        end\n        \n        % now turn .L into a matrix (since we actually need it in matrix form)\n        % the calculation is cached since it's quite slow for large parameter spaces\n        regfunc.L = operator_to_matrix(regfunc.L,numel(w));\n        \n        regfunc.param = param;\n        \n        vec = @(x)x(:);\n        if isfield(param,'weights')\n            if isempty(param.weights)\n                param.weights = ones(prod(shape_A_out),1); end\n            shaped_weights = reshape(param.weights,shape_A_out);\n        else\n            shaped_weights = ones(shape_A_out);\n        end\n        switch param.arg_selection\n            case 'l1'\n                if (isempty(param.weights) || all(param.weights(:)==1)) && ~isfield(param,'A')\n                    regfunc.prox = @(x,gamma,x0) prox_l1_simple(x,gamma);\n                    regfunc.eval = @(x,lambda) lambda*sum(abs(x));\n                else\n                    regfunc.prox = @(x,gamma,x0) prox_l1(x,gamma,param);\n                    regfunc.eval = @(x,lambda) lambda*norm(vec(shaped_weights.*rA(x)),1);\n                end\n            case 'l2'\n                if isempty(param.y)\n                    param.y = zeros(prod(shape_A_out),1); end\n                if isfield(param,'A')\n                    A = operator_to_matrix(param.A,sum(n));\n                    regfunc.prox = @(x,gamma,x0) prox_squared_iter(A,param.y,1/gamma,x,zeros(size(x)),sum(n),x0);\n                    regfunc.eval = @(x,lambda) lambda*obj_squared(A,param.y,x(1:sum(n)));\n                else                \n                    regfunc.prox = @(x,gamma,x0) prox_l2_simple(x,gamma);\n                    regfunc.eval = @(x,lambda) lambda*norm(shaped_weights(:).*(vec(rA(x)) - param.y(:)),2).^2;\n                end\n            case 'l1/l2'\n                if isfield(param,'A')\n                    error('The linear operator for the group sparsity prox operator is not implemented. You can however apply it by using the SDMM algorithm.'); end\n                if isempty(param.g_d) && isempty(param.g_t) && (isempty(param.weights2)||all(param.weights2(:)==1)) && (isempty(param.weights1)||all(param.weights1(:)==1))\n                    regfunc.prox = @(x,gamma,x0) prox_l12_simple(x,gamma,shape_A_out);\n                    regfunc.eval = @(x,lambda)lambda*norm_l12_simple(rA(x),shape_A_out);\n                else                    \n                    if isempty(param.g_d) && isempty(param.g_t)\n                        param.g_d = (1:prod(shape_A_out));\n                        param.g_t = shape_A_out(1)*ones(1,prod(shape_A_out(2:end)));\n                    end\n                    if isempty(param.weights1)\n                        param.weights1 = ones(numel(param.g_t),1); end\n                    if isempty(param.weights2)\n                        param.weights2 = ones(prod(shape_A_out),1); end\n                    regfunc.prox = @(x,gamma,x0) prox_l12(x,gamma,param);\n                    regfunc.eval = @(x,lambda) lambda*norm_l12(rA(x),param.g_d,param.g_t,param.weights2,param.weights1);\n                end\n            case 'l1/linf'\n                if isfield(param,'A')\n                    error('The linear operator for the group sparsity prox operator is not implemented. You can however apply it by using the SDMM algorithm.'); end\n                if isempty(param.g_d) && isempty(param.g_t) && (isempty(param.weights2)||all(param.weights2(:)==1)) && (isempty(param.weights1)||all(param.weights1(:)==1))\n                    regfunc.prox = @(x,gamma,x0) prox_l1inf_simple(x,gamma,shape_A_out);\n                    regfunc.eval = @(x,lambda)lambda*norm_l1inf_simple(rA(x),shape_A_out);\n                else                    \n                    if isempty(param.g_d) && isempty(param.g_t)\n                        param.g_d = (1:prod(shape_A_out));\n                        param.g_t = shape_A_out(1)*ones(1,prod(shape_A_out(2:end)));\n                    end\n                    if isempty(param.weights1)\n                        param.weights1 = ones(numel(param.g_t),1); end\n                    if isempty(param.weights2)\n                        param.weights2 = ones(prod(shape_A_out),1); end\n                    regfunc.prox = @(x,gamma,x0) prox_l1inf(x,gamma,param);\n                    regfunc.eval = @(x,lambda) lambda*norm_l1inf(rA(x),param.g_d,param.g_t,param.weights2,param.weights1);\n                end\n            case 'tv2d'\n                if isfield(param,'A')\n                    error('The linear operator for the total-variation prox operator is not implemented. You can however apply it by using the SDMM algorithm.'); end\n                regfunc.prox = @(x,gamma,x0) prox_tv(x,gamma,param);\n                regfunc.eval = @(x,lambda) lambda*tv_norm(rA(x),param.shape);\n            case 'tv3d'\n                if isfield(param,'A')\n                    error('The linear operator for the total-variation prox operator is not implemented. You can however apply it by using the SDMM algorithm.'); end\n                regfunc.prox = @(x,gamma,x0) prox_tv3d(x,gamma,param);\n                regfunc.eval = @(x,lambda) lambda*tv_norm3d(rA(x),param.shape);\n            case 'trace'\n                regfunc.prox = @(x,gamma,x0) prox_nuclear_simple(x,gamma,shape_A_out);\n                regfunc.eval = @(x,lambda) lambda*norm_nuclear_simple(rA(x),shape_A_out);\n            otherwise\n                error('Unrecognized regularization type requested.');\n        end\n        regfunc.y0 = [];\n        regfuncs{end+1} = @(lambda) setfield(setfield(regfunc,'prox',@(x,gamma,x0)regfunc.prox(x,gamma*lambda,x0)),'eval',@(x)regfunc.eval(x,lambda)); %#ok<AGROW,SFLD>\n    end\nend\n\nif iscell(regweights) && numel(regweights) == 1\n    regweights = regweights{1}; end\nif isempty(regweights)\n    regweights = ones(1,length(regfuncs)); end\nregweights = regweights/sum(regweights); \n\n% learn the regularization path\nif verbosity\n    disp('solving regularization path...'); end\ny0 = {};\nnLambdas = length(lambdas);\nregpath = cell(nLambdas,1);\nhist = cell(1,nLambdas);\nfor k =1:nLambdas\n    \n    % set up parameters\n    termweights = [1,lambdas(k)*regweights];\n    lossfunc = lossfunc(1);\n    lossfunc.L = [];\n    if ~isempty(y0)\n        lossfunc.y0 = y0{1}; end\n    lossfunc.param = struct();\n    for r = 1:length(regfuncs)\n        tmpregfuncs(r) = regfuncs{r}(termweights(1+r)); %#ok<AGROW>\n        if ~isempty(y0)\n            tmpregfuncs(r).y0 = y0{1+r}; end %#ok<AGROW>\n    end\n    \n    % we stash the termweights in the solverOptions because the hlp_diskcache below will by default\n    % not parse the tmpregfuncs anonymous function deep enough to discover the termweights, and thus \n    % cause cache collisions (this can be resolved by setting the serialize_anonymous_fully option\n    % to true, but since that is a global option it could cause unexpected behavior in the rest of\n    % BCILAB)\n    solverOptions.termweights = termweights;\n    \n    % solve\n    t0 = tic;\n    if verbosity\n        fprintf('  scanning lambda = %f (%i/%i)...',lambdas(k),k,nLambdas); end\n    if solverOptions.warmstart\n        [w,y0,rho,hist{k}] = hlp_diskcache('intermediate',@consensus_admm,w,[lossfunc tmpregfuncs],solverOptions); %#ok<ASGLU>\n    else\n        [w,y0dummy,rho,hist{k}] = hlp_diskcache('intermediate',@consensus_admm,zeros(size(w)),[lossfunc tmpregfuncs],solverOptions); %#ok<ASGLU>\n    end\n    if verbosity\n        fprintf(' %i iters; t = %.1fs\\n',length(hist{k}.objval),toc(t0)); end\n    \n    % assemble output weights for each task\n    if includebias && nTasks > 1\n        offsets = cumsum([1 n(1:end-1)]);\n        for t=1:nTasks\n            regpath{k}{t} = w([offsets(t)+(0:n(t)-1) end-length(m)+t]); end\n    else\n        regpath{k}{1} = w;\n    end\nend\n\n[res.regpath,res.hist] = deal(regpath,hist);\n\n\n% --- multi-task logistic loss code ---\n\nfunction [val,grad] = obj_proxlogistic_multitask(x,C,Cp,z,gamma,m,n,data_weights)\n% objective function for the multi-task logistic loss proximity operator (effectively l2-regularized logreg)\noffsets = cumsum([1 n(1:end-1)]);\nfor t=length(m):-1:1\n    % move bias from end to inline\n    xt = x([offsets(t)+(0:n(t)-1) end-length(m)+t]);\n    zt = z([offsets(t)+(0:n(t)-1) end-length(m)+t]);\n    ecx = exp(C{t}*xt);\n    scaling = (gamma*data_weights(t)/m(t));\n    val{t} = (1/2)*sum((xt-zt).^2) + scaling*gather(sum(log1p(ecx)));\n    if ~isfinite(val{t})\n        ecx(~isfinite(ecx(:))) = 2.^50;\n        val{t} = (1/2)*sum((xt-zt).^2) + scaling*gather(sum(log1p(ecx)));\n    end\n    grad{t} = (xt - zt) + scaling*gather(Cp{t}*(ecx./(1+ecx)));    \nend\nval = sum([val{:}]);\ngrad = vertcat(grad{:});\n% move biases back to end\ngrad = [grad;grad(cumsum(n+1))]; grad(cumsum(n+1)) = [];\n\nfunction x = prox_logistic_multitask(C,Cp,z,gamma,x0,m,n,args,data_weights)\nx = liblbfgs(@(w)obj_proxlogistic_multitask(w,C,Cp,z,gamma,m,n,data_weights),x0,args{:});\n\nfunction obj = obj_logistic_multitask(C,x,m,n,data_weights)\nobj = 0;\noffsets = cumsum([1 n(1:end-1)]);\nfor t=1:length(m)\n    xt = x([offsets(t)+(0:n(t)-1) end-length(m)+t]);\n    obj = obj + gather(sum(log1p(exp(C{t}*xt))))*(data_weights(t)/m(t)); \nend\n\n\n% --- multi-task square loss code  ---\n\nfunction x = prox_squared_factored_multitask(A,Atb,L,U,rho,z,u,m,n,data_weights)\n% this version can only be used if rho stays constant (TODO: confirm the use of data_weights as correct)\nscaling = rho/data_weights;\noffsets = cumsum([1 n(1:end-1)]);\nfor t=length(m):-1:1\n    q = Atb{t} + scaling(t)*(z([offsets(t)+(0:n(t)-1) end-length(m)+t]) - u([offsets(t)+(0:n(t)-1) end-length(m)+t]));\n    if(m(t) >= n(t))\n        x{t} = U{t}\\(L{t}\\q);\n    else\n        x{t} = q/scaling(t) - (A{t}'*(U{t}\\(L{t}\\(A{t}*q))))/scaling(t)^2;\n    end\nend\nx = vertcat(x{:});\nx = [x;x(cumsum(n+1))]; x(cumsum(n+1)) = [];\n    \nfunction obj = obj_squared_multitask(A,b,x,m,n,data_weights)\nobj = 0;\nfor t=length(m):-1:1\n    xt = x([offsets(t)+(0:n(t)-1) end-length(m)+t]); \n    obj = obj + data_weights(t)*0.5*norm(A*xt - b,2).^2;\nend\n\n\n% --- logistic loss code ---\n\nfunction [val,grad] = obj_proxlogistic(x,C,Cp,z,gamma,m)\n% objective function for the logistic loss proximity operator (effectively l2-regularized logreg)\necx = exp(C*x);\nscaling = (gamma/m);\nval = (1/2)*sum((x-z).^2) + scaling*gather(sum(log1p(ecx)));\nif ~isfinite(val)\n    ecx(~isfinite(ecx(:))) = 2.^50;\n    val = (1/2)*sum((x-z).^2) + scaling*gather(sum(log1p(ecx)));\nend\ngrad = (x - z) + scaling*gather(Cp*(ecx./(1+ecx)));\n\nfunction x = prox_logistic(C,Cp,z,gamma,x0,m,args)\nx = liblbfgs(@(w)obj_proxlogistic(w,C,Cp,z,gamma,m),x0,args{:});\n\nfunction obj = obj_logistic(C,x,m)\nobj = gather(sum(log1p(exp(C*x))))/m;\n\n           \n% --- square loss code  ---\n\nfunction x = prox_squared_factored(A,Atb,L,U,rho,z,u,m,n)\n% this version can only be used if rho stays constant\nq = Atb + rho*(z - u);\nif(m >= n)\n    x = U\\(L\\q);\nelse\n    x = q/rho - (A'*(U\\(L\\(A*q))))/rho^2;\nend\n\nfunction x = prox_squared_iter(A,b,rho,z,u,n,x0)\n[x, flag, relres, iters] = lsqr([A; sqrt(rho)*speye(n)], [b; sqrt(rho)*(z-u)], [], [], [], [], x0); %#ok<NASGU,ASGLU>\n\nfunction obj = obj_squared(A,b,x)\nobj = 0.5*norm(A*x - b,2).^2;\n\n\n% --- some useful prox operators & norms ---\n\nfunction x = prox_l1_simple(z, gamma)\n% for the l1 norm\nx = max(0,z-gamma) - max(0,-z-gamma);\n\nfunction x = prox_l12_simple(z, gamma, shape)\n% for the columnwise group l1/l2 norm\nz = reshape(z,shape);\nx = bsxfun(@times,max(0,1-gamma./sqrt(sum(z.^2))),z);\nx = x(:);\n\nfunction x = prox_l2_simple(z, gamma)\n% for the l2 norm\nx = bsxfun(@times,max(0,1-gamma./sqrt(sum(z.^2))),z);\n\nfunction x = prox_l1inf_simple(z, gamma, shape)\n% for the columnwise group l1/linf norm\nz = reshape(z,shape);\nx = bsxfun(@times,max(0,1-gamma/max(abs(z))),z);\nx = x(:);\n\nfunction x = prox_nuclear_simple(z, gamma, shape)\n% for the trace norm on first 2 dimensions\nz = reshape(z,shape);\nif ndims(z)>2\n    siz = size(z);\n    z = reshape(z,siz(1),siz(2),[]);\n    for k=1:size(z,3)\n        [U,S,V] = svd(z(:,:,k),'econ');\n        S = diag(max(0,diag(S)-gamma));\n        z(:,:,k) = U*S*V.';\n    end\n    x = reshape(z,siz);\nelse\n    [U,S,V] = svd(z,'econ');\n    S = diag(max(0,diag(S)-gamma));\n    x = U*S*V.';\nend\nx = x(:);\n\nfunction n = norm_l12_simple(z, shape)\n% for the columnwise group l1/l2 norm\nn = sqrt(sum(reshape(z.^2,shape)));\nn = sum(n(:));\n\nfunction n = norm_l1inf_simple(z, shape)\n% for the columnwise group l1/linf norm\nn = max(reshape(abs(z),shape));\nn = sum(n(:));\n\nfunction n = norm_nuclear_simple(z, shape)\n% for the trace norm on first 2 dimensions\nz = reshape(z,shape);\nif ndims(z)>2\n    siz = size(z);\n    z = reshape(z,siz(1),siz(2),[]);\n    n = 0;\n    for k=1:size(z,3)\n        n = n+sum(svd(z(:,:,k))); end\nelse\n    n = sum(svd(z));\nend\n\n\n% -- hyperbolic secant distribution loss code ---\n\nfunction [val,grad] = obj_proxhs(x,b,z,gamma)\n% objective function for the hyperbolic-secant loss proximity operator\nzz = x-b;\nmz = abs(zz);\nezzmz = exp(zz-mz);\nenzzmz = exp(-zz-mz);\nval = (1/2)*norm(x - z).^2 + gamma*sum(mz + log(ezzmz+enzzmz)-log(2/pi));\ngrad = (x - z) + gamma*(ezzmz-enzzmz)./(ezzmz+enzzmz);\n\nfunction x = prox_hs(b,z,gamma,x0,args)\nx = liblbfgs(@(w)obj_proxhs(w,b,z,gamma),x0,args{:});\n\nfunction obj = obj_hs(x,b)\nx = x-b;\nax = abs(x);\nobj = sum(mz + log(exp(x-ax)+exp(-x-ax))-log(2/pi));\n\n\n% --- helper functions ---\n\nfunction [L,U] = factor(A, rho)\n% note: rho is 1/gamma\n[m,n] = size(A);\nif (m >= n)\n    L = chol(A'*A + rho*speye(n),'lower');\nelse\n    L = chol(speye(m) + 1/rho*(A*A'),'lower');\nend\n% force matlab to recognize the upper / lower triangular structure\nL = sparse(L);\nU = sparse(L');\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/machine_learning/ml_trainproximal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5927984353668068}}
{"text": "classdef S2FunHandle < S2Fun\n% a class represeneting a function on the sphere\n  \nproperties\n  fun\n  antipodal = false\nend\n\n\nmethods\n  function S2F = S2FunHandle(fun)\n    S2F.fun = fun;\n  end\n  \n  function f = eval(S2F,v)\n    f = S2F.fun(v);\n  end\n  \nend\n\n\nmethods (Static = true)\n  \n  function S2F = Kachanov(lambda)\n    \n    S2F = S2FunHandle(@(v) fun(v,lambda));\n    \n    function values = fun(v,lambda)\n\n      phi = v.theta;\n      values =  ((lambda.^2 + 1) * exp(-lambda * phi) + ...\n        lambda*exp((-lambda*pi)/2))./(2*pi);\n      \n      values = values(:);\n      \n    end\n    \n  end\n    \n    \nend\n\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/S2Fun/@S2FunHandle/S2FunHandle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.5927984255169622}}
{"text": "function errors = test_gsp_remove_mean()\n\n\nX = rand(100,10);\n\nX1 = gsp_remove_mean(X);\n\nerrors = gsp_assert_test(0,sum(X1),eps(1000), 'remove mean dim 1');\n\nX2 = gsp_remove_mean(X,2);\n\nerrors = errors + gsp_assert_test(0,sum(X2,2),eps(1000), 'remove mean dim 2');\n\nX = rand(100,10,3);\n\nX3 = gsp_remove_mean(X,3);\n\nerrors = errors + gsp_assert_test(0,sum(X3,3),eps(1000), 'remove mean dim 3');\n\nend", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/test_gsptoolbox/test_gsp_remove_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.592798424843494}}
{"text": "% GET THE UNIT VECTOR\nfunction [v_unit] = unit(v)\n    v_unit = v/norm(v);\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/unit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5926716778042238}}
{"text": "function indx = r82vec_sort_heap_index_a ( n, a )\n\n%*****************************************************************************80\n%\n%% R82VEC_SORT_HEAP_INDEX_A does an indexed heap ascending sort of an R82VEC.\n%\n%  Discussion:\n%\n%    The sorting is not actually carried out.  Rather an index array is\n%    created which defines the sorting.  This array may be used to sort\n%    or index the array, or to sort or index related arrays keyed on the\n%    original array.\n%\n%    Once the index array is computed, the sorting can be carried out\n%    \"implicitly:\n%\n%      A(1:2,INDX(I)), I = 1 to N is sorted,\n%\n%    or explicitly, by the call\n%\n%      A = R82VEC_PERMUTE ( N, A, INDX )\n%\n%    after which A(1:2,I), I = 1 to N is sorted.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 February 2005\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(2,N), an array to be index-sorted.\n%\n%    Output, integer INDX(N), the sort index.  The\n%    I-th element of the sorted array is A(1:2,INDX(I)).\n%\n  if ( n < 1 )\n    return\n  end\n\n  if ( n == 1 )\n    indx(1) = 1;\n    return\n  end\n\n  indx = i4vec_indicator ( n );\n\n  l = floor ( n / 2 ) + 1;\n  ir = n;\n\n  while ( 1 )\n\n    if ( 1 < l )\n\n      l = l - 1;\n      indxt = indx(l);\n      aval(1:2) = a(1:2,indxt);\n\n    else\n\n      indxt = indx(ir);\n      aval(1:2) = a(1:2,indxt);\n      indx(ir) = indx(1);\n      ir = ir - 1;\n\n      if ( ir == 1 )\n        indx(1) = indxt;\n        break\n      end\n\n    end\n\n    i = l;\n    j = l + l;\n\n    while ( j <= ir )\n\n      if ( j < ir )\n        if (   a(1,indx(j)) <  a(1,indx(j+1)) | ...\n             ( a(1,indx(j)) == a(1,indx(j+1)) & ...\n               a(2,indx(j)) <  a(2,indx(j+1)) ) )\n          j = j + 1;\n        end\n      end\n\n      if (   aval(1) <  a(1,indx(j)) | ...\n           ( aval(1) == a(1,indx(j)) & ...\n             aval(2) <  a(2,indx(j)) ) )\n        indx(i) = indx(j);\n        i = j;\n        j = j + j;\n      else\n        j = ir + 1;\n      end\n\n    end\n\n    indx(i) = indxt;\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/r82vec_sort_heap_index_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.5926716631646242}}
{"text": "%ISHOMOG2 Test if SE(2) homogeneous transformation\n%\n% ISHOMOG2(T) is true (1) if the argument T is of dimension 3x3 or 3x3xN, else \n% false (0).\n%\n% ISHOMOG2(T, 'valid') as above, but also checks the validity of the rotation\n% sub-matrix.\n%\n% Notes::\n% - The first form is a fast, but incomplete, test for a transform in SE(3).\n% - Does not work for the SE(3) case.\n%\n% See also ISHOMOG, ISROT2, ISVEC.\n\n\n\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\nfunction h = ishomog2(tr, rtest)\n    d = size(tr);\n    if ndims(tr) >= 2\n        h =  all(d(1:2) == [3 3]);\n\n        if h && nargin > 1\n            h = abs(det(tr(1:2,1:2)) - 1) < eps;\n        end\n    else\n        h = false;\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/common/ishomog2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5926716617492354}}
{"text": "% \n% Author: Marius Drulea\n% http://www.cv.utcluj.ro/optical-flow.html\n% \n% References\n% M. Drulea and S. Nedevschi, \"Total variation regularization of \n% local-global optical flow,\" in Intelligent Transportation Systems (ITSC), \n% 2011 14th International IEEE Conference on, 2011, pp. 318-323.\n% \n% Copyright (C) 2011 Technical University of Cluj-Napoca\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 <http://www.gnu.org/licenses/>.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [u] = tv_min(u0, lambda)\n%   The output u approximately minimizes the Rudin-Osher-Fatemi (ROF)\n%   denoising model\n%\n%       Min  TV(u) + 1/(2*lambda)* || u - u0 ||^2_2,\n%        u\n\nu = zeros(size(u0));\n\n% initialization of the dual variable\np1 = zeros(size(u0));\np2 = zeros(size(u0));\n\ntau = 1/4;\nmax_iters = 100;\n\nder_mask = [0 -1 1];\nadjoint_der_mask = [-1 1 0];\n\nfor i=1:max_iters\n    \n    % the divergence\n    div_p = imfilter(p1, adjoint_der_mask, 'replicate') + ...\n        imfilter(p2, adjoint_der_mask', 'replicate');\n    \n    t = div_p - u0/lambda;\n    \n    % the derivatives\n    tx = imfilter(t, der_mask, 'replicate');\n    ty = imfilter(t, der_mask', 'replicate');\n    \n    denominator = 1 + tau * sqrt(tx.^2 + ty.^2);\n    \n    % update dual variable; gradient ascent and reprojection\n    p1 = (p1 + tau*tx)./denominator;\n    p2 = (p2 + tau*ty)./denominator;\n    \n    % update variable; gradient descent\n    u = u0 - lambda*div_p;\nend\n\nend", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/VSRnet/external_functions/CLG-TV-matlab/tv_min.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5926716570173568}}
{"text": "function [lin_fun, pp] = RAWCRF(image_raw, image_jpg, N, threshold_outliers)\n%\n%       [lin_fun, pp] = RAWCRF(image_raw, image_jpg, N, threshold_outliers)\n%\n%      \n%\n%        Input:\n%           -image_raw:\n%           -image_raw: \n%           -N:\n%           -threshold_outliers:\n%\n%        Output:\n%           -lin_fun:\n%           -pp: \n%\n\nif(isempty(image_raw))\n    error('RAWCRF: a stack cannot be empty!');\nend\n\nif(isempty(image_jpg))\n    error('RAWCRF: a stack_exposure cannot be empty!');\nend\n\nif(~exist('threshold', 'var'))\n    threshold_outliers = 0.05;\nend\n\nif(~exist('N', 'var'))\n    N = -1;\nend\n\nthreshold_outliers_inv = 1.0 - threshold_outliers;\n\ncol = size(image_raw, 3);\n\nlin_fun = zeros(256, col);\n\nerr = -1;\nN_max = 6;\nthr = [threshold_outliers, threshold_outliers_inv];\n\nif(N < 0)\n    for N_tmp=1:N_max\n        pp = RAWCRFn(image_raw, image_jpg, N_tmp, thr);\n\n        imgOut = RemoveCRF(image_jpg, 'poly', pp);\n\n        tmp_err = abs(imgOut - image_raw).^2;\n        tmp_err = mean(tmp_err(:));\n\n        if(err < 0)\n            err = tmp_err;\n            N = N_tmp;\n        else\n            if(tmp_err < err)\n                err = tmp_err;\n                N = N_tmp;\n            end\n        end\n\n    end\nelse\n    pp = RAWCRFn(image_raw, image_jpg, N, thr);\nend\n\nx_val = (0:255) / 255;\n\nfor i=1:col\n    lin_fun(:, i) = polyval(pp(:, i), x_val);\nend\n\nend\n\nfunction pp = RAWCRFn(image_raw, image_jpg, N, thr)\n    col = size(image_raw, 3);\n    \n    pp = zeros(N + 1, col);\n    \n    bFlag = 0;\n\n    %bDebug = 1;\n    \n    for i=1:col\n        slice_raw = image_raw(:,:,i);\n        slice_jpg = image_jpg(:,:,i);\n\n        indx = find(slice_jpg > thr(1) & slice_jpg < thr(2));\n\n        if(~isempty(indx))    \n            x = slice_jpg(indx);\n            y = slice_raw(indx);\n            \n%             \n%             if(bDebug)\n%                 figure(i);\n%                 c = zeros(256,256);\n%                 for k =1:length(x)\n%                     tx = ClampImg(round(x(k) * 255) + 1, 1, 256);\n%                     ty = ClampImg(round(y(k) * 255) + 1, 1, 256);\n%                     c(256 - ty + 1, tx) = c(256 - ty + 1, tx) + 1;\n%                 end\n%                 imshow(c);\n%             end\n            \n            pp(:, i) = polyfit(x, y, N);\n        else\n            bFlag = 1;\n            disp('RAWCRF: no enough data for estimating the CRF');\n        end\n    end\n    \n    if(bFlag)\n        pp = zeros(N + 1, col);\n    end\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/Generation/RAWCRF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5926716508909633}}
{"text": "function legendre_polynomial_test08 ( )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_POLYNOMIAL_TEST08 tests PMN_POLYNOMIAL_VALUE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    12 March 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n  mm = 1;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'LEGENDRE_POLYNOMIAL_TEST08:\\n' );\n  fprintf ( 1, '  PMN_POLYNOMIAL_VALUES stores values of\\n' );\n  fprintf ( 1, '  the Legendre polynomial Pmn(n,m,x).\\n' );\n  fprintf ( 1, '  PMN_POLYNOMIAL_VALUE evaluates the polynomial.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '                                Tabulated                 Computed\\n' );\n  fprintf ( 1, '     N     M        X           Pmn(N,M,X)                Pmn(N,M,X)             Error\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, n, m, x, fx1 ] = pmn_polynomial_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    v = pmn_polynomial_value ( mm, n, m, x );\n    fx2 = v(1,n+1);\n\n    e = fx1 - fx2;\n\n    fprintf ( 1, '  %4d  %4d  %12g  %24g  %24g  %8g\\n', n, m, x, fx1, fx2, 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/legendre_polynomial/legendre_polynomial_test08.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.5926516936012441}}
{"text": "function procNoiseParam=processNoiseSuggest(algorithm,maxVal,T,sigmaw2,manDur)\n%%PROCESSNOISESUGGEST Use one of a number methods for choosing the scaling\n%             parameter for the process noise covariance in a number of\n%             continuous-time and discrete-time dynamic models. This only\n%             provides the scaling parameter for one dimension of motion.\n%             In a multidimensional system, if the measurement noise\n%             variance varies between dimensions (such as tracking in range\n%             and angle with a range-angle state), then one might use\n%             different values in different dimensions. The method only\n%             considers scalar measurements in the respective dimensions\n%             and is thus only good for a rough approximation.\n%\n%INPUTS: algorithm A string specifying the algorithm and model used to\n%           estimate a good process noise parameter. Possible values are:\n%                  'PolyKal-ROT' Use a rule-of-thumb method for determining\n%                                the q0 term for the QPolyKal function, for\n%                                discrete-time models, and the DPoly\n%                                function, for continuous-time models. This\n%                                covers the continuous white noise\n%                                acceleration (CWNA) model (order=1), the \n%                                discretized continuous white noise\n%                                acceleration (DCWNA) model (order=1), the\n%                                continuous Wiener process acceleration\n%                                (CWPA) model  (order=2), and the \n%                                discretized continuous Wiener process\n%                                acceleration (DCWPA) model (order=2),\n%                                among others.\n%           'PolyKalDirectDisc-ROT' Use a rule-of-thumb method for\n%                                determining the sigmaV2 parameter for the\n%                                QPolyKalDirectDisc function. This covers\n%                                the discrete white noise acceleration\n%                                (DWNA) model (order=1), among others.\n%           'PolyKalDirectAlt-ROT' Use a rule-of-thumb method for\n%                                determining the sigmaV2 parameter for the\n%                                QPolyKalDirectAlt function. This covers\n%                                the discrete Wiener process acceleration\n%                                (DWPA) model (order=2), among others.\n%                 'CWNA-OptMMSE' Use the method of Blair for determining\n%                                the asymptotically optimal value of q0 in\n%                                terms of MSE for the CWNA and DCWNA\n%                                dynamic models for a maneuver having a\n%                                fixed maximum acceleration.\n%                 'DWNA-OptMMSE' Use the method of Blair for determining\n%                                the asymptotically optimal value of\n%                                sigmaV2 for the DWNA model for a maneuver\n%                                having a fixed maximum acceleration.\n%               'CWNA-ConstMeas' Use the method of Blair for determining\n%                                the asymptotically optimal value of q0\n%                                for the CWNA and DCWNA models such that\n%                                the MSE of a Kalman filter under a maximum\n%                                acceleration maneuver is not worse than\n%                                the measurement accuracy.\n%               'DWNA-ConstMeas' Use the method of Blair for determining\n%                                the asymptotically optimal value of\n%                                sigmaV2 for the DWNA model such that\n%                                the MSE of a Kalman filter under a maximum\n%                                acceleration maneuver is not worse than\n%                                the measurement accuracy.\n%    maxVal All of the methods require a maximum bound related to how the\n%           target can maneuver. For algorithms CWNA-OptMMSE,\n%           DWNA-OptMMSE, CWNA-ConstMeas, and DWNA-ConstMeas, maxVal is\n%           the maximum acceleration of the target. For PolyKal-ROT and\n%           PolyKalDirectDisc-ROT, and PolyKalDirectAlt-ROT maxVal is the\n%           maximum value of a moment one order higher than the maximum\n%           order of the dynamic model. For example, if order=1, then\n%           maxVal is a maximum acceleration.  If order=2, then maxVal is\n%           a maximum jerk.\n%         T For all of the algorithms except PolyKalDirectDisc-ROT, this\n%           parameter is required and is the typical time between\n%           measurements of the target.\n%   sigmaw2 For algorithms CWNA-OptMMSE, DWNA-OptMMSE, CWNA-ConstMeas, and\n%           DWNA-ConstMeas, this parameter is required and is the variance\n%           of the 1D measurement, which should be the lowest order moment\n%           of the state. In other words, position.\n%    manDur For algorithms CWNA-OptMMSE, DWNA-OptMMSE, CWNA-ConstMeas, and\n%           DWNA-ConstMeas, this parameter is required and is the\n%           maximum number of samples of duration T that a maximum\n%           acceleration maneuver is expected to take. This can take\n%           values, 3, 4, 5, 6 and infinity. The default if omitted or an\n%           empty matrix is passed is Inf.\n%\n%OUTPUTS: procNoiseParam The value of q0 or sigmaV2 for the specified\n%                        dynamic model, chosen according to the selected\n%                        ad-hoc parameter.\n%\n%The output of this function goes into functions like QPolyKal. It is meant\n%that one computes the process noise parameter once (for QPolyKal, this\n%would correspond to the q0 parameter), and then one calls the other\n%functions with different samples prediction intervals. This function\n%should not be called to change the process noise parameter as the sampling\n%period changes.\n%\n%All of the rule-of-thumb methods for choosing the process noise values are\n%from Chapter 6.2 and 6.3 of [1] and modified slightly, as described in the\n%comments for the implementation below.\n%\n%The solutions for the ConstMeas and MMSE methods are from [2], which is an\n%extension of the work in [3] and [4].\n%\n%The rule-of thumb parameters might be suitable for other dynamic models.\n%For example, when using the Singer model, given with aGaussMarkov and\n%DPoly in continuous-time and with FGaussMarkov and QGaussMarkov in\n%discrete-time, there does not appear to be a clear way to set the scaling\n%value for the process noise in the literature. However, if tau=infinity in\n%the model, then in continuous time, it reduces to the CWPA model. Thus,\n%methods for choosing the process noise parameter in the CWPA and the DCWPA\n%models might be good starting points for setting the process noise\n%parameter in the continuous and discrete Singer models.\n%\n%REFERENCES:\n%[1] Y. Bar-Shalom, X. R. Li, and T. Kirubarajan, Estimation with\n%    Applications to Tracking and Navigation. New York: John Wiley and\n%    Sons, Inc, 2001.\n%[2] W. D. Blair, \"Design of nearly constant velocity filters for radar\n%    tracking of maneuvering targets,\" in Proceedings of the IEEE Radar\n%    Conference, Atlanta, GA, 7-11 May 2012, pp. 1008-1013.\n%[3] W. D. Blair, \"Design of nearly constant velocity track filter for\n%    brief maneuvers,\" in Proceedings of the 14th International Conference\n%    on Information Fusion, Chicago, IL, 5-8 Jul. 2011.\n%[4] W. D. Blair, \"Design of nearly constant velocity track filters for\n%    tracking maneuvering targets,\" in Proceedings of the 11th\n%    International Conference on Information Fusion, Cologne, Germany, 30\n%    Jun. - 3 Jul. 2008.\n%\n%April 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<5||isempty(manDur))\n    manDur=Inf;\nend\n\nswitch(algorithm)\n    case 'PolyKal-ROT'\n        %The rule of thumb is generalized from the rules of thumb in\n        %Chapters 6.2.2 and 6.2.3 of Bar-Shalom's book, when considering\n        %the CWNA, DCWNA, CWPA and DCWPA. For the CWNA and DCWNA models, it\n        %is suggested that sqrt(q0*T) be on the order of the changes in\n        %velocity over a sampling interval. In other words, it is the\n        %average acceleration. It might be more useful to express things in\n        %terms of a maximum acceleration, though. In Chapter 6.3.2 for the\n        %DWNA model, it is suggested that  0.5*aMax<=sigmaV<=aMax. Using a\n        %similar logic, one might try  0.5*aMax<=sqrt(q0*T)<=aMax. Using\n        %the same logic for the CWPA and DCWPA models of Chapter 6.2.3, one\n        %might choose q0 such that  0.5*jerkMax<=sqrt(q0*T)<=jerkMax, where\n        %jerkMax is the maximum possible jerk (derivative of acceleration).\n        %This function generalizes the rule  to any order and chooses the\n        %point midway in that specified range.\n        \n        procNoiseParam=(0.75*maxVal)^2/T;\n        return;\n    case 'PolyKalDirectDisc-ROT'\n        %The rule-of-thumb is generalized from that given in Chapter 6.3.2\n        %of Bar-Shalom's book. In the book, it is suggested that\n        %0.5*aMax<=sigmaV<=aMax for the DWNA model (order=1). This function\n        %generalizes it to any order and chooses the point midway in that\n        %specified range.\n        \n        procNoiseParam=(0.75*maxVal)^2;\n        return;\n    case 'PolyKalDirectAlt-ROT'\n        %The rule-of-thumb is generalized from that given in Chapter 6.3.3\n        %of Bar-Shalom's book. In the book, it is suggested that\n        %0.5*deltaAMax<=sigmaV<=deltaAMax for the DWPA model (order=2),\n        %where deltaAMax is the maximum change in acceleration over an\n        %interval of duration T. This can be related to a maximum jerk as\n        %0.5*jerkMax*T<=sigmaV<=jerkMax*T. This function generalizes it to\n        %any order and chooses the point midway in that range.\n        \n        procNoiseParam=(0.5*maxVal*T)^2;\n        return;\n    case 'CWNA-OptMMSE'\n        optType=0;\n        isDiscrete=false;\n    case 'DWNA-OptMMSE'\n        optType=0;\n        isDiscrete=true;\n    case 'CWNA-ConstMeas'\n        optType=1;\n        isDiscrete=false;\n    case 'DWNA-ConstMeas'\n        optType=1;\n        isDiscrete=true;\n    otherwise\n        error('Unknown algorithm chosen')\nend\n\n%Equation 3, the deterministic maneuvering index.\nGammaD=maxVal*T^2/sqrt(sigmaw2);\n\nif(0.01>GammaD||GammaD>10)\n   warning('The deterministic maneuvering index is outside of the tabulated range of values. The process noise parameter might be inaccurate.')\nend\n%Blair's papers do not say the base, but if one uses base 10, one gets the\n%results in the plots. If one uses base e, the results do not match the\n%plots in the paper.\nlogVal=log10(GammaD);\n\n%optType=0 means MMSE (so use max)\n%optType=1 means limit the maximum error to the measurement noise (so use\n%          min)\nswitch(manDur)\n    case Inf\n        if(optType)\n            curRow=2;\n        else\n            curRow=1;\n        end\n    case 3\n        if(optType)\n            curRow=4;\n        else\n            curRow=3;\n        end\n    case 4\n        if(optType)\n            curRow=6;\n        else\n            curRow=5;\n        end\n    case 5\n    %If one wants a five-sample maneuver, then we will average the values\n    %from the length four and the length-six maneuvers.\n        if(optType)\n            curRow=[6;8];\n        else\n            curRow=[5;7];\n        end\n    case 6\n        if(optType)\n            curRow=8;\n        else\n            curRow=7;\n        end\n    otherwise\n        error('An untabulated value for the maximum maneuver duration has been given')\nend\n\n%Table I in Blair's paper\nk1CoeffTable=[1.677, -0.726,  0.230, -0.012, 0.005,  0.000;%k^{max}_{\\inf}\n              0.872, -0.102, -0.019,  0.010, 0.006,  0.001;%k^{min}_{\\inf}\n              1.539, -0.189, -0.651,  0.187, 0.284,  0.059;%k^{max}_{3}\n              0.707,  0.346, -0.318, -0.097, 0.088,  0.029;%k^{min}_{3}\n              1.630, -0.473, -0.403,  0.272, 0.173,  0.023;%k^{max}_{4}\n              0.803,  0.197, -0.385, -0.009, 0.138,  0.035;%k^{min}_{4}\n              1.671, -0.697,  0.025,  0.250,-0.0324,-0.028;%k^{max}_{6}\n              0.869,  0.008, -0.320,  0.088, 0.123,  0.023];%k^{min}_{6}\n\na0=k1CoeffTable(curRow,1);\na1=k1CoeffTable(curRow,2);\na2=k1CoeffTable(curRow,3);\na3=k1CoeffTable(curRow,4);\na4=k1CoeffTable(curRow,5);\na5=k1CoeffTable(curRow,6);\n\n%Equations 6 and 7. The mean command is for averaging if one wanted a\n%length 5 maneuver. Note that equation 6 has a repeated cubed term. That\n%appears to be a mistake.\nk1=mean(a0+logVal*(a1+logVal*(a2+logVal*(a3+logVal*(a4+a5*logVal)))));\n\nif(isDiscrete)%Discrete-time\n    procNoiseParam=(k1*maxVal)^2;\nelse%Continuous-time\n    procNoiseParam=T*(k1*maxVal)^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/Dynamic_Models/processNoiseSuggest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5926354443822262}}
{"text": "function [secUT] = convertYearDayHrMnSec2Sec(year, day, hour, min, sec)\n%convertYearDayHrMnSec2Sec Summary of this function goes here\n%   Detailed explanation goes here\n\n    [secInMin, secInHr, secInDay, secInYear] = getSecondsInVariousTimeUnits();\n    \n    secUT = (year-1)*secInYear;\n    secUT = secUT + (day-1)*secInDay;\n    secUT = secUT + hour*secInHr;\n    secUT = secUT + min*secInMin;\n    secUT = secUT + sec;    \nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/math/convertYearDayHrMnSec2Sec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5926354314942923}}
{"text": "%MIRT3D_MEXINTERP  Fast 3D linear interpolation \n%  \n% Output_image = mirt3D_mexinterp(Input_image, XI,YI,ZI) interpolates the 3D image 'Input_image' at\n%    the points with coordinates X,Y,Z. Input_image is assumed to  be defined at a regular grid 1:N, 1:M, 1:K, \n%    where [M,N,K]=size(Input_images). Points outside the boudary return NaNs. \n%    This is equivalent (but much faster) to Matlab's:\n%    Output_image = interp3(Input_image,XI,YI,ZI,'linear',NaN);\n%  \n% Output_images = mirt3D_mexinterp(Input_images, XI,YI,ZI). Input_images can be a stack of many 3D images (4D).\n%   The function interpolates each of the 3D images at X,Y,Z coordinates and return a stack of corresponding\n%   interpolated images. This is equivalent to Matlab's\n% \n%   Input_images(:,:,:,1)=Input_image1;\n%   Input_images(:,:,:,2)=Input_image2;\n%   Input_images(:,:,:,3)=Input_image3;\n%   Input_images(:,:,:,4)=Input_image4;\n%  \n%   Output_images(:,:,:,1) = interp3(Input_image1,XI,YI,ZI,'linear',NaN);\n%   Output_images(:,:,:,2) = interp3(Input_image2,XI,YI,ZI,'linear',NaN);\n%   Output_images(:,:,:,3) = interp3(Input_image3,XI,YI,ZI,'linear',NaN);\n%   Output_images(:,:,:,4) = interp3(Input_image4,XI,YI,ZI,'linear',NaN);\n% \n%  This is especially usefull fpr vector valued 3D images, RGB images, to interpolate the whole 3D video at the same coordinates\n%  or to interpolate image and its gradients at the same time (in image registration).\n%  The speed gain is also from the precomputation of nearest points for interpolation, which are the same for all images in a stack.\n%\n%  Andriy Myronenko, Feb 2008, email: myron@csee.ogi.edu, \n%  homepage: http://www.bme.ogi.edu/~myron/\n\n\n% The function below compiles the mirt3D_mexinterp.cpp file if you haven't done it yet.\n% It will be executed only once at the very first run.\nfunction Output_images = mirt3D_mexinterp(Input_images, XI,YI,ZI)\n\npathtofile=which('mirt3D_mexinterp.cpp');\npathstr = fileparts(pathtofile);\nmex(pathtofile,'-outdir',pathstr);\n\nOutput_images = mirt3D_mexinterp(Input_images, XI,YI,ZI);\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/Mirt3DMexinterpToolbox/mirt3D_mexinterp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.592635426634975}}
{"text": "function optimo = LocalSearch(Problem,pos,w)\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    MaxIter = 5;\n    Tol     = 1e-3;\n    step    = 1;\n    k       = 1;\n    error   = 10;\n    while error>Tol && k<MaxIter\n        grad(1,:)    = FiniteDifference(pos,w,Problem);\n        offspringdec = pos.dec - step*grad(1,:);\n        offspringdec = min(max(offspringdec,Problem.lower),Problem.upper);\n        offspring    = Problem.Evaluation(offspringdec);\n        grad(2,:)    = FiniteDifference(offspring,w,Problem);\n        step         = abs((offspring.dec-pos.dec)*(grad(2,:)-grad(1,:))')/norm(grad(2,:)-grad(1,:))^2;\n        error = norm(offspring.dec-pos.dec);\n        pos   = offspring;\n        k     = k + 1;\n    end\n    optimo = pos;\nend\n\nfunction df = FiniteDifference(X,W,Problem)\n    if any(X.con>0)\n        df = Problem.CalConGrad(X.dec)';\n        df = sum(df,2);\n    else\n        df = Problem.CalObjGrad(X.dec)';\n        df = df*W';\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/GPSO-M/LocalSearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5925710572601888}}
{"text": "function bcdof = BoundaryCondition(typeBC,coordinates)\n\n%--------------------------------------------------------------------------\n%   Purpose:\n%           To determine the boundary conditions degree of freedom\n%   Synopsis:\n%           bcdof = BoundaryCondition(typeBC,coordinates)\n%\n%   Variable Description:\n%           bcdof - boundary condition degree of freedom\n%                   dof's are (UZ,RX,RY)\n%           typeBC - string which gives the state of boundary condition\n%           coordinates - geometric coordinates of nodes\n%           \n%--------------------------------------------------------------------------\n\nL1 = find(coordinates(:,2)==min(coordinates(:,2))) ; % at y = 0 (along X-axes)\nL2 = find(coordinates(:,1)==max(coordinates(:,1))) ; % at x = a (along Y-axes)\nL3 = find(coordinates(:,2)==max(coordinates(:,2))) ; % at y = b (along X-axes)\nL4 = find(coordinates(:,1)==min(coordinates(:,1))) ; % at x = 0 (along Y-axes)\nn = length(L1) ;\n \nswitch typeBC\n    case 'ss-ss-ss-ss'\n        disp('plate is simply supported at all the edges')\n        dofL1 = zeros(1,2*n) ;\n        dofL2 = zeros(1,2*n) ;\n        dofL3 = zeros(1,2*n) ;\n        dofL4 = zeros(1,2*n) ;\n        for i = 1:n\n            i1 = 2*(i-1)+2 ;\n            i2 = i1-1 ;\n            dofL1(i1) = 3*L1(i);\n            dofL1(i2) = 3*L1(i)-2 ;\n            dofL3(i1) = 3*L3(i) ;\n            dofL3(i2) = 3*L3(i)-2 ;\n        end   \n        for i = 1:n\n            i1 = 2*(i-1)+2 ;\n            i2 = i1-1 ;\n            dofL2(i1) = 3*L2(i)-1 ;\n            dofL2(i2) = 3*L2(i)-2 ;\n            dofL4(i1) = 3*L4(i)-1 ;\n            dofL4(i2) = 3*L4(i)-2 ;\n        end\n        L1UL3 = union(dofL1,dofL3) ;\n        L2UL4 = union(dofL2,dofL4) ;\n        bcdof = union(L1UL3,L2UL4) ;\n        \n    case 'c-c-c-c'\n        disp('plate is clamped at all the edges')\n        dofL1 = zeros(1,2*n) ;\n        dofL2 = zeros(1,2*n) ;\n        dofL3 = zeros(1,2*n) ;\n        dofL4 = zeros(1,2*n) ;\n        for i = 1:n\n            i1 = 2*(i-1)+2 ;\n            i2 = i1-1 ;\n            dofL1(i1) = 3*L1(i)-1;\n            dofL1(i2) = 3*L1(i)-2 ;\n            dofL3(i1) = 3*L3(i)-1 ;\n            dofL3(i2) = 3*L3(i)-2 ;\n        end   \n        for i = 1:n\n            i1 = 2*(i-1)+2 ;\n            i2 = i1-1 ;\n            dofL2(i1) = 3*L2(i) ;\n            dofL2(i2) = 3*L2(i)-2 ;\n            dofL4(i1) = 3*L4(i) ;\n            dofL4(i2) = 3*L4(i)-2 ;\n        end\n        L1UL3 = union(dofL1,dofL3) ;\n        L2UL4 = union(dofL2,dofL4) ;\n        bcdof = union(L1UL3,L2UL4) ;\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/32029-plate-bending/Plate Bending/BoundaryCondition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5925710567300025}}
{"text": "function [y,deriv] = dotprod_of_functions(w,f,g)\n% This is an MV2DF (see MV2DF_API_DEFINITION.readme) which \n% represents the new function, \n%\n%    g(w) = f(w)'g(w) \n%\n% where f(w) and g(w) are column vectors of the same size.\n%\n% Here f,g are function handles to MV2DF's. \n\n\nif nargin==0\n    test_this();\n    return;\nend\n\n\nfunction A = extractA(w)\n    A = w(1:length(w)/2);\n    A = A(:).';\nend\n\n\nfunction B = extractB(w)\n    B = w(1+length(w)/2:end);\n    B = B(:)    ;\nend\n\n\n\nif isempty(w) \n\n    s = stack(w,f,g);\n    y = mm_special(s,@(w)extractA(w),@(w)extractB(w));\n    return;\nend\n\n\nif isa(w,'function_handle')\n    f = dotprod_of_functions([],f,g);\n    y = compose_mv(f,w,[]);\n    return;\nend\n\n\nf = dotprod_of_functions([],f,g);\nif nargout==1\n    y = f(w);\nelse\n    [y,deriv] = f(w);\nend\n\nend\n\nfunction test_this()\n\nm = 5;\nw = randn(2*m,1);\nf = subvec([],2*m,1,m);\ng = subvec([],2*m,m+1,m);\n\nh = dotprod_of_functions([],f,g);\ntest_MV2DF(h,w);\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_combination/dotprod_of_functions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5925710561998156}}
{"text": "%+========================================================================+\n%|                                                                        |\n%|            This script uses 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    \u00a0\u00a0\u00a0\u00a0         |\n%|                                                                        |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it.                                                      |\n%|________________________________________________________________________|\n%|   '&`   |                                                              |\n%|    #    |   FILE       : nrtHmxCompressorBox.m                         |\n%|    #    |   VERSION    : 0.40                                          |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |\n%|  ( # )  |   CREATION   : 14.03.2017                                    |\n%|  / 0 \\  |   LAST MODIF : 14.03.2018                                    |\n%| ( === ) |   SYNOPSIS   : Compare compressor for separated boxes        |\n%|  `---'  |                                                              |\n%+========================================================================+\n\nclear all\nclose all\nclc\n\n% Gypsilab path\nrun('../../addpathGypsilab.m')\n\n% Taille de la boite\nedg = 1;\n\n% Precision ou nombre de points de quadrature polynomiale\ntol = 1e-3;\n\n% Regular cube\nn       = 10;\nx       = 0:1/(n-1):1;\n[x,y,z] = meshgrid(x,x,x);\n\n% Recepteurs\nNx     = 1000;\n% X      = edg*rand(Nx,3);\nX      = edg*[x(:),y(:),z(:)];\n\n% Emmeteurs\nNy     = 1000;\n% Y      = edg*rand(Ny,3);\nY      = edg*[x(:),y(:),z(:)];\nY(:,1) = 2*edg + Y(:,1);\n\n% Potentiel aleatoire aux emmeteurs\nV  = (-1-1i) + (2+2i)*rand(Ny,1);\n\n% Representation graphique\nfigure(1)\nplot3(X(:,1),X(:,2),X(:,3),'*b',Y(:,1),Y(:,2),Y(:,3),'r*')\ngrid on\naxis equal\n\n% Noyau de green Helmholtz\nk     = 5;\nrxy   = @(X,Y) sqrt( (X(:,1)-Y(:,1)).^2 + (X(:,2)-Y(:,2)).^2 + (X(:,3)-Y(:,3)).^2 );\ngreen = @(X,Y) exp(1i*k*rxy(X,Y))./rxy(X,Y);\n\n% Gridding\n[I,J] = ndgrid(1:Nx,1:Ny);\n\n% Noyau de green\nGxy = green(X(I,:),Y(J,:));\nGxy = reshape(Gxy,Nx,Ny);\n% Gxy = [Gxy zeros(Nx,Ny) ; ...\n%     zeros(Nx,Ny) Gxy];\n% Gxy = [Gxy zeros(Nx,2*Ny) ; ...\n%     zeros(Nx,Ny) Gxy zeros(Nx,Ny) ; ...\n%     zeros(Nx,2*Ny) Gxy];\n% figure\n% imagesc(Gxy)\n\n% Calcul du rang\ntic\nrk = rank(Gxy,tol);\ntoc\nrk\n\n% Compression ACA, pivotage total\ntic\n[A,B] = hmxACA(Gxy,tol);\ntoc\nsize(A)\nnorm(A*B-Gxy,'fro')./norm(Gxy,'fro')\n\n% Compression ACA, pivotage partiel\ntic\n[A,B] = hmxACA(X,Y,@(X,Y) green(X,Y),tol);\ntoc\nsize(A)\nnorm(A*B-Gxy,'fro')./norm(Gxy,'fro')\n\n% % Recompression ACA, pivotage total\n% tic\n% [Ap,Bp] = hmxACA(A,B,tol);\n% toc\n% size(Ap)\n% norm(Ap*Bp-Gxy,'fro')./norm(Gxy,'fro')\n\n% Recompression RSVD\ntic\n[Ap,Bp,flag] = hmxRSVD(A,B,tol);\ntoc\nsize(Ap)\nnorm(Ap*Bp-Gxy,'fro')./norm(Gxy,'fro')\n\n% Recompression QRSVD\ntic\n[Ap,Bp] = hmxQRSVD(A,B,tol);\ntoc\nsize(Ap)\nnorm(Ap*Bp-Gxy,'fro')./norm(Gxy,'fro')\n\n\n\ndisp('~~> Michto gypsilab !')\n\n\n    \n\n\n    \n\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/gypsilabModified/nonRegressionTest/hierarchicalMatrix/nrtHmxCompressorsBox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5925710542516652}}
{"text": "%% Set Parameters\n% Preferences\nglobal ggamma rrho\nggamma = 2;        % coefficient of relative risk aversion\nrrho = 0.01;       % rate of time preference\n\n% Production function\nglobal ddelta aalpha\nddelta = .025;     % capital depreciation\naalpha = 1 / 3;    % capital share\n\n% Aggregate shock\nglobal ssigmaTFP rrhoTFP\nssigmaTFP = .007;  % standard deviation of TFP shock\nrrhoTFP = .95;     % quarterly autocorrelation of TFP shock\n\n% Idiosyncratic shocks\nglobal z\nzz1 = 0;           % unemployed\nzz2 = 1;           % employed\nz = [zz1,zz2];\n\n% Transition probabilities\nglobal lla\nllambda1 = 1 / 2;  % expected duration of unemployment is 2 quarters\nllambda2 = (llambda1 / (zz2 * .93 - zz1))*(zz2 - zz2 * .93); % unemployment rate 7%\nlla = [llambda1,llambda2];\n\n% Tax system\nglobal mmu ttau\nmmu = .15;        % UI replacement rate 15%\nttau = (mmu / zz2) * (lla(2) / lla(1));\t     % labor income tax\n\n% Labor supply\nglobal zAvg\nzAvg = (lla(1) * z(2) + lla(2) * z(1)) / (lla(1) + lla(2));\n\n%% Approximation Parameters\n% Wealth grid\nglobal I amin amax a da aa aaa\nI = 100;           % can't be too fine for some reason\namin = 0;\namax = 100;\na = linspace(amin,amax,I)';\nda = (amax - amin) / (I - 1);\naa = [a,a];\naaa = reshape(aa,2*I,1);\n\n% Labor productivity\nglobal zz zzz\nzz = ones(I,1) * z;\nzzz = reshape(zz,2*I,1);\n\n% Idiosyncratic shocks for income\nglobal Aswitch\nAswitch = [-speye(I) * lla(1),speye(I) * lla(1);speye(I) * lla(2),-speye(I) * lla(2)];\n\n% Steady state computations\nglobal rmin rmax r0 maxit crit Delta Ir crit_S\nrmin = .0001;       % lower bound for steady state interest rate\nrmax = rrho;        % upper bound for steady state interest rate\nr0 = .005;          % initial guess for steady state interest rate\nmaxit = 100;        % maximum iterations on steady state HJB\ncrit = 1e-6;        % error criterion for steady state value function convergence\nDelta = 1e4;        % update size for implicit scheme on steady state HJB\nIr = 100;           % maximum iterations on steady state interest rate\ncrit_S = 1e-5;      % error criterion for steady state interest rate\n\n% Number of variables in the system\nglobal nVars nEErrors n_v n_g n_p\nn_v = 2 * I;\nn_g = 2 * I-1 + 1;\nn_p = 6;\nnVars = n_v + n_g + n_p;\nnEErrors = 2 * I;\n\n% Spline parameters\nglobal n_splined\nn_knots = 12;\nc_power = 7;\nx = a';\nn_post = 2;\t        % This is from two income states\nn_prior = 1;\nn_splined = n_prior*n_knots*n_post;", "meta": {"author": "gregkaplan", "repo": "phact", "sha": "4cd7ff0c013b082db9c2ca070225feaff1056123", "save_path": "github-repos/MATLAB/gregkaplan-phact", "path": "github-repos/MATLAB/gregkaplan-phact/phact-4cd7ff0c013b082db9c2ca070225feaff1056123/examples/KrusellSmith/set_parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5925710507129547}}
{"text": "classdef CBFDT < handle\n    properties\n        systemParam\n        optType\n        optParam\n        xcurr\n        timecurr\n        solvertime\n        xdim\n        udim\n        tlog = []\n        xlog = []\n        ulog = []\n        omegalog = []\n    end\n    \n    methods\n        function self = CBFDT(system_param, x0, t0)\n            self.systemParam = system_param;\n            self.xcurr = x0;\n            self.timecurr = t0;\n            self.xdim = size(self.systemParam.A, 1);\n            self.udim = size(self.systemParam.B, 2);\n        end\n        \n        function setOpt(self, opt_type, opt_param)\n            self.optType = opt_type;\n            self.optParam = opt_param;\n        end\n        \n        function sim(self, total_time)\n            xk = self.xcurr;\n            while self.timecurr <= total_time\n                [feas, xopt, uopt, Jopt] = self.solve();\n                if feas ~= 1\n                    return;\n                end\n                uk = uopt(:,1);\n                xk = self.systemParam.A * xk + self.systemParam.B * uk;\n                self.xcurr = xk;\n                self.timecurr = self.timecurr + self.systemParam.timestep;\n                self.tlog = [self.tlog, self.timecurr];\n                self.xlog = [self.xlog, xk];\n                self.ulog = [self.ulog, uk];\n            end\n        end\n        \n        function [feas, xopt, uopt, Jopt] = solve(self)\n            if strcmp(self.optType,'dclfdcbf')\n                [feas, xopt, uopt, Jopt] = solveDCLFDCBF(self);\n            elseif strcmp(self.optType,'nmpcdclfdcbf')\n                [feas, xopt, uopt, Jopt] = solveNMPCDCLFDCBF(self);\n            elseif strcmp(self.optType,'mpcdcbf')\n                [feas, xopt, uopt, Jopt] = solveMPCDCBF(self);\n            elseif strcmp(self.optType,'mpcgcbf')\n                [feas, xopt, uopt, Jopt] = solveMPCGCBF(self);\n            elseif strcmp(self.optType,'nmpcdcbf')\n                [feas, xopt, uopt, Jopt] = solveNMPCDCBF(self);\n            else\n                disp('optimal control policy undefined');\n            end\n        end\n        \n        function [feas, xopt, uopt, Jopt] = solveDCLFDCBF(self)\n            x = sdpvar(self.xdim, 2);\n            u = sdpvar(self.udim, 1);\n            s = sdpvar(1,1);\n            cost = 0;\n            constraints = [];\n            % initial condition\n            constraints = [constraints; x(:,1) == self.xcurr];\n            % dynamics\n            constraints = [constraints; x(:,2) == self.systemParam.A * x(:,1) + self.systemParam.B * u(:,1)];\n            % DCLF constraint\n            v = x(:,1)' * self.optParam.P * x(:,1);\n            vnext = x(:,2)' * self.optParam.P * x(:,2);\n            constraints = [constraints; vnext - v + self.optParam.alpha * v <= s];\n            % DCBF constraint\n            r = 1;\n            b = x(:,1)' * x(:,1) - r^2;\n            bnext = x(:,2)' * x(:,2) - r^2;\n            constraints = [constraints; bnext - b + self.optParam.gamma * b >= 0];\n            % input constraint\n            constraints = [constraints; self.systemParam.ul <= u <= self.systemParam.uu];\n            % cost\n            cost = cost + u' * self.optParam.uWeight * u + s' * self.optParam.sWeight * s;\n            opt_settings = sdpsettings('solver','ipopt','verbose',0);\n            diagnostics = optimize(constraints, cost, opt_settings);\n            if diagnostics.problem == 0\n                feas = true;\n                xopt = value(x);\n                uopt = value(u);\n                Jopt = value(cost);\n            else\n                feas = false;\n                xopt= [];\n                uopt = [];\n                Jopt = value(cost);\n            end\n            self.solvertime = diagnostics.solvertime;\n            fprintf('solver time: %f\\n', diagnostics.solvertime);\n        end\n        \n        function [feas, xopt, uopt, Jopt] = solveNMPCDCLFDCBF(self)\n            x = sdpvar(self.xdim, self.optParam.horizon + 1);\n            u = sdpvar(self.udim, self.optParam.horizon);\n            s = sdpvar(1,self.optParam.horizonCLF);\n            omega = sdpvar(1,self.optParam.horizonCBF);\n            cost = 0;\n            constraints = [];\n            % initial condition\n            constraints = [constraints; x(:,1) == self.xcurr];\n            % MPC cost and constraints\n            for i = 1:self.optParam.horizon\n                constraints = [constraints;\n                    self.systemParam.ul <= u(:,i) <= self.systemParam.uu;\n                    x(:,i+1) == self.systemParam.A * x(:,i) + self.systemParam.B * u(:,i)];\n                cost = cost + x(:,i)'*self.optParam.xWeight*x(:,i);\n                cost = cost + u(:,i)'*self.optParam.uWeight*u(:,i);\n            end\n            cost = cost + x(:,self.optParam.horizon)' * self.optParam.P * x(:,self.optParam.horizon);\n            % CLF constraints\n            for i = 1:self.optParam.horizonCLF\n                v = x(:,1)' * self.optParam.P * x(:,1);\n                vnext = x(:,2)' * self.optParam.P * x(:,2);\n                constraints = [constraints; vnext - v + self.optParam.alpha * v <= s(i)];\n                cost = cost + s(i)' * self.optParam.sWeight * s(i);\n            end\n            % CBF constraints\n            for i = 1:self.optParam.horizonCBF\n                r = 1;\n                b = x(:,1)' * x(:,1) - r^2;\n                bnext = x(:,2)' * x(:,2) - r^2;\n                constraints = [constraints; bnext >= omega(i) * (1 - self.optParam.gamma) * b];\n                constraints = [constraints; omega(i) >= 0];\n                assign(omega(i), 1);\n                cost = cost + self.optParam.omegaWeight * (omega(i) - 1)^2;\n            end\n            opt_settings = sdpsettings('solver','ipopt','verbose',0);\n            diagnostics = optimize(constraints, cost, opt_settings);\n            if diagnostics.problem == 0\n                feas = true;\n                xopt = value(x);\n                uopt = value(u);\n                Jopt = value(cost);\n            else\n                feas = false;\n                xopt= [];\n                uopt = [];\n                Jopt = value(cost);\n            end\n            self.solvertime = diagnostics.solvertime;\n            fprintf('solver time: %f\\n', diagnostics.solvertime);\n        end\n        \n        function [feas, xopt, uopt, Jopt] = solveMPCDCBF(self)\n            x = sdpvar(self.xdim, self.optParam.horizon + 1);\n            u = sdpvar(self.udim, self.optParam.horizon);\n            cost = 0;\n            constraints = [];\n            % initial condition\n            constraints = [constraints; x(:,1) == self.xcurr];\n            % MPC cost and constraints\n            for i = 1:self.optParam.horizon\n                constraints = [constraints;\n                    self.systemParam.ul <= u(:,i) <= self.systemParam.uu;\n                    x(:,i+1) == self.systemParam.A * x(:,i) + self.systemParam.B * u(:,i)];\n                cost = cost + x(:,i)'*self.optParam.xWeight*x(:,i);\n                cost = cost + u(:,i)'*self.optParam.uWeight*u(:,i);\n            end\n            cost = cost + x(:,self.optParam.horizon)' * self.optParam.P * x(:,self.optParam.horizon);\n            % CBF constraints\n            for i = 1:self.optParam.horizon\n                r = 0;\n                b = r - x(1,i);\n                bnext = r - x(1,i+1);\n                constraints = [constraints; bnext - b + self.optParam.gamma * b >= 0];\n            end\n            opt_settings = sdpsettings('solver','ipopt','verbose',0);\n            diagnostics = optimize(constraints, cost, opt_settings);\n            if diagnostics.problem == 0\n                feas = true;\n                xopt = value(x);\n                uopt = value(u);\n                Jopt = value(cost);\n            else\n                feas = false;\n                xopt= [];\n                uopt = [];\n                Jopt = value(cost);\n            end\n            self.solvertime = diagnostics.solvertime;\n            fprintf('solver time: %f\\n', diagnostics.solvertime);\n        end\n        \n        function [feas, xopt, uopt, Jopt] = solveMPCGCBF(self)\n            x = sdpvar(self.xdim, self.optParam.horizon + 1);\n            u = sdpvar(self.udim, self.optParam.horizon);\n            cost = 0;\n            constraints = [];\n            % initial condition\n            constraints = [constraints; x(:,1) == self.xcurr];\n            % MPC cost and constraints\n            for i = 1:self.optParam.horizon\n                constraints = [constraints;\n                    self.systemParam.ul <= u(:,i) <= self.systemParam.uu;\n                    x(:,i+1) == self.systemParam.A * x(:,i) + self.systemParam.B * u(:,i)];\n                cost = cost + x(:,i)'*self.optParam.xWeight*x(:,i);\n                cost = cost + u(:,i)'*self.optParam.uWeight*u(:,i);\n            end\n            cost = cost + x(:,self.optParam.horizon)' * self.optParam.P * x(:,self.optParam.horizon);\n            % GCBF constraints\n            num_HO = 3;\n            r = 0;\n            b = r - x(1,1);\n            bnext = r - x(1,1+num_HO);\n            constraints = [constraints; bnext >= (1 - self.optParam.gamma)^num_HO * b];            \n            opt_settings = sdpsettings('solver','ipopt','verbose',0);\n            diagnostics = optimize(constraints, cost, opt_settings);\n            if diagnostics.problem == 0\n                feas = true;\n                xopt = value(x);\n                uopt = value(u);\n                Jopt = value(cost);\n            else\n                feas = false;\n                xopt= [];\n                uopt = [];\n                Jopt = value(cost);\n            end\n            self.solvertime = diagnostics.solvertime;\n            fprintf('solver time: %f\\n', diagnostics.solvertime);\n        end\n        \n        function [feas, xopt, uopt, Jopt] = solveNMPCDCBF(self)\n            x = sdpvar(self.xdim, self.optParam.horizon + 1);\n            u = sdpvar(self.udim, self.optParam.horizon);\n            omega = sdpvar(1,self.optParam.horizonCBF);\n            cost = 0;\n            constraints = [];\n            % initial condition\n            constraints = [constraints; x(:,1) == self.xcurr];\n            % MPC cost and constraints\n            for i = 1:self.optParam.horizon\n                constraints = [constraints;\n                    self.systemParam.ul <= u(:,i) <= self.systemParam.uu;\n                    x(:,i+1) == self.systemParam.A * x(:,i) + self.systemParam.B * u(:,i)];\n                cost = cost + x(:,i)'*self.optParam.xWeight*x(:,i);\n                cost = cost + u(:,i)'*self.optParam.uWeight*u(:,i);\n            end\n            cost = cost + x(:,self.optParam.horizon)' * self.optParam.P * x(:,self.optParam.horizon);\n            % CBF constraints\n            for i = 1:self.optParam.horizonCBF\n                r = 0;\n                b = r - x(1,i);\n                bnext = r - x(1,i+1);\n                constraints = [constraints; bnext >= omega(i) * (1 - self.optParam.gamma) * b];\n                constraints = [constraints; omega(i) >= 0];\n                assign(omega(i), 1);\n                cost = cost + self.optParam.omegaWeight * (omega(i) - 1)^2;\n            end\n            opt_settings = sdpsettings('solver','ipopt','verbose',0);\n            diagnostics = optimize(constraints, cost, opt_settings);\n            if diagnostics.problem == 0\n                feas = true;\n                xopt = value(x);\n                uopt = value(u);\n                Jopt = value(cost);\n            else\n                feas = false;\n                xopt= [];\n                uopt = [];\n                Jopt = value(cost);\n            end\n            self.solvertime = diagnostics.solvertime;\n            fprintf('solver time: %f\\n', diagnostics.solvertime);\n        end\n    end\nend\n\n", "meta": {"author": "HybridRobotics", "repo": "NMPC-DCLF-DCBF", "sha": "3f40c67578f49114301b02e744e5a86fa671a981", "save_path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF", "path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF/NMPC-DCLF-DCBF-3f40c67578f49114301b02e744e5a86fa671a981/matlab/cdc2021/CBFDT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5925710473468392}}
{"text": "function ar=lpcim2ar(im)\n%LPCIM2AR Convert impulse response to AR coefs AR=(IM)\n\n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: lpcim2ar.m 713 2011-10-16 14:45:43Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[nf,p1]=size(im);\nar=zeros(nf,p1);\nwz=[1 zeros(1,p1-1)];\nfor k=1:nf\n  ar(k,:)=wz/toeplitz(wz,im(k,:)/im(k,1));\nend\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/lpcim2ar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5925710462864673}}
{"text": "function [report_data] = report_convergence(report_data, state)\n% Report convergence of the algorithm\n\n% Copyright (C) 2004, 2005 DSS MATLAB package team (dss@cis.hut.fi).\n% Distributed by Laboratory of Computer and Information Science,\n% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.\n% $Id$\n\nif ~isfield(report_data, 'report_interval')\n  report_data.report_interval = 5;\n  dss_message(state, 2, sprintf('Setting default report interval to %d (report_data.report_interval)\\n', report_data.report_interval));\nend\n\n% deflation\nif state.iteration==1\n  % -- first iteration\n  if state.algorithm=='defl'\n    % deflation\n    report_data.change(state.component,1)=0;\n    report_data.deltaw_old=state.w;\n  else\n    % symmetric\n    report_data.change = zeros(size(state.W, 1),1);\n    report_data.dW_old = zeros(size(state.W));\n    report_data.W_old = state.W;\n  end\nelse\n  % -- iterations 2->\n  if (mod(state.iteration, report_data.report_interval)==0)\n    if state.algorithm=='defl'\n      % deflation\n      change = acos(state.w' * state.w_old/norm(state.w)/norm(state.w_old)) / pi * 180;\n    else \n      % symmetric\n      change = abs(angle(state.W, state.W_old)) / pi * 180;\n    end\n    message(state,1,sprintf('Change (angles): %d\\n', change));\n  end\nend\n\n% -----------------------------------\nfunction rad = angle(A, B)\n\nsum_cross = sum(A .* B, 2);\nsum_A = sum(A .* A, 2);\nsum_B = sum(B .* B, 2);\nrad = acos(sum_cross ./ sum_A.^(-1/2) ./ sum_B.^(-1/2));\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dss/report_convergence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5925710462864673}}
{"text": "function D = agreement_weighted(CI,Wts)\n%WEIGHTED_AGREEMENT     weights agreement matrix\n%\n%   D = AGREEMENT_WEIGHTED(CI,WTS) is identical to AGREEMENT, with the \n%   exception that each partitions contribution is weighted according to \n%   the corresponding scalar value stored in the vector WTS. As an example,\n%   suppose CI contained partitions obtained using some heuristic for \n%   maximizing modularity. A possible choice for WTS might be the Q metric\n%   (Newman's modularity score). Such a choice would add more weight to \n%   higher modularity partitions.\n%\n%   NOTE: Unlike AGREEMENT, this script does not have the input argument\n%   BUFFSZ.\n%\n%   Inputs:     CI,     set of partitions\n%               WTS,    relative weight of importance of each paritition\n%\n%   Outputs:    D,      weighted agreement matrix\n%\n%   Richard Betzel, Indiana University, 2013\n\nWts = Wts./sum(Wts);\n[N,M] = size(CI);\nD = zeros(N);\nfor i = 1:M\n    d = dummyvar(CI(:,i));\n    D = D + (d*d')*Wts(i);\nend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/agreement_weighted.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5925710418599786}}
{"text": "% \n% state = [x, y, yaw, delta]\n% input = [v_des, delta_des]\n% ref = [x_ref, y_ref, yaw_ref, v_ref]\n% \n% \n% \n\nclear variables;\nclose all;\n\n\nset(0, 'defaultAxesFontSize', 12);\nset(0, 'defaultTextFontSize', 20);\nset(0, 'DefaultAxesLineWidth', 1.0, 'DefaultLineLineWidth', 1.0);\n\n\naddpath ../path_design\n\ncontrol_mode_option = [\"pure_pursuit\", \"pid\", \"mpc\", \"mpc_no_constraints\"];\ncontrol_mode = control_mode_option(3);\n\nsave_video = 0; %1:save, 0:no\n\n%% preliminaries\nrad2deg = 180 / pi;\ndeg2rad = pi / 180;\nkmh2ms = 1000 / 3600;\n\nsimulation_time = 35;\nsimulation_rk4_time_step = 0.002; % simulation time step\n\nvel_ref = 30 * kmh2ms;\n\n% for dynamics model\nparam.tau = 0.27; % steering dynamics: 1d-approximated time constant\nparam.wheelbase = 2.69;\nparam.steer_lim = 30 * deg2rad;\nparam.vel_max = 10;\nparam.vel_min = -5;\n\nparam.input_delay = 0.24; % [s]\nparam.control_dt = 0.03; % [s]\nparam.measurement_noise_stddev = [0.1, 0.1, 1.0*deg2rad, 0.5*deg2rad]; % measurement noise\n% param.measurement_noise_stddev = [0,0,0,0]; % measurement noise\nparam.steering_steady_state_error_deg = 1;\n\n% for pure pursuit only\nparam.pure_pursuit_lookahead = 8.0; % [m]\n\n% for mpc only\nparam.mpc_dt = 0.1;\nparam.mpc_n = 30;\nparam.mpc_constraint_steering_deg = 30;\nparam.mpc_constraint_steer_rate_deg = 280;\nparam.mpc_model_dim = 3;\nparam.mpc_Q = diag([1,2]);\nparam.mpc_R = 0.5;\nparam.mpc_delay_comp_step = round(param.input_delay / param.control_dt);\n% param.mpc_delay_comp_step = 0.0;\n\n% use the input ahead of the delay time\nparam.mpc_sensor_delay = param.input_delay; \n\n% for mpc2\nparam.mpc2_dt = 0.2;\nparam.mpc2_n = 10;\nparam.mpc2_steering_lim_deg = 40;\nparam.mpc2_model_dim = 4;\nparam.mpc2_Q = diag([1,1,0]);\nparam.mpc2_R = 0.05;\n\n%% simulation parameters\n\n% initial position (x, y, yaw, delta)\nx0 = [0, 0.5, 0, 0];\n\nts = 0;\ndt = simulation_rk4_time_step;\ntf = simulation_time;\nt = ts:dt:tf;\n\n%% reference trajectory design\n\npath_design; % using spline\nload path; % x, y, yaw\n\nref = zeros(length(path), 6);\nIDX_X = 1;\nIDX_Y = 2;\nIDX_XY = 1:2;\nIDX_XYYAW = 1:3;\nIDX_YAW = 3;\nIDX_VEL = 4;\nIDX_CURVATURE = 5;\nIDX_TIME = 6;\n\nIDX_STEER = 4;\n\n\npath_size_scale = 15;\npath(:,IDX_XY) = path(:,IDX_XY) * path_size_scale;\nref(:,IDX_XYYAW) = path(:,IDX_XYYAW);\n\nref(:,IDX_VEL) = ones(length(path),1)*vel_ref;\n\n% insert curvature into path\nfor i = 2:length(ref)-1\n    p1_ = ref(i-1,IDX_XY);\n    p2_ = ref(i, IDX_XY);\n    p3_ = ref(i+1, IDX_XY);\n    A_ = ((p2_(1)-p1_(1))*(p3_(2)-p1_(2)) - (p2_(2)-p1_(2))*(p3_(1)-p1_(1))) / 2;\n    ref(i, IDX_CURVATURE) = 4 * A_ / (norm(p1_-p2_) * norm(p2_-p3_) * norm(p3_-p1_));\nend\n\n% insert relative time into path\nfor i = 2:length(ref)\n    v_ = ref(i,IDX_VEL);\n    d_ = norm(ref(i,IDX_XY)-ref(i-1,IDX_XY));\n    dt_ = d_ / v_;\n    ref(i, IDX_TIME) = ref(i-1, IDX_TIME) + dt_;\nend\n\n\n%% simulation\n\nif control_mode == \"pure_pursuit\"\n    [X, U, debug] = simulate_rk4(@kinematics_model, @pure_pursuit, x0, ref, ts, dt, tf, param);\n    lat_error_vec = debug(:,end);\nelseif control_mode == \"pid\"\n   [X, U, debug] = simulate_rk4(@kinematics_model, @pid_controller, x0, ref, ts, dt, tf, param);\n   lat_error_vec = debug(:,end);\nelseif control_mode == \"mpc\"\n    param.mpc_solve_without_constraint = false;\n    [X, U, debug] = simulate_rk4(@kinematics_model, @model_predictive_controller, x0, ref, ts, dt, tf, param);\n    lat_error_vec = debug(:,end);\nelseif control_mode == \"mpc_no_constraints\"\n    param.mpc_solve_without_constraint = true;\n    [X, U, debug] = simulate_rk4(@kinematics_model, @model_predictive_controller, x0, ref, ts, dt, tf, param);\n    lat_error_vec = debug(:,end);  \nelseif control_mode == \"mpc2\"\n    [X, U, debug] = simulate_rk4(@kinematics_model, @model_predictive_controller2, x0, ref, ts, dt, tf, param);\n    lat_error_vec = debug(:,end);\nend\nfprintf(\"lattitude error: mean square = %f, max = %f\", norm(lat_error_vec)/simulation_time, max(lat_error_vec));\n\n\n%% movie plot\n\nsp_num = 18;\nsubpl1 = 'subplot(sp_num,sp_num, sp_num+1:sp_num*12);';\nsubpl2 = 'subplot(sp_num,sp_num, sp_num*13+1:sp_num*15);';\nsubpl3 = 'subplot(sp_num,sp_num, sp_num*16+1:sp_num*18);';\n\n% tire2steer = 12.5;\n\nfig_trajectory_result = figure(1);\nset(fig_trajectory_result, 'Position', [716 735 1026 1146]);\neval(subpl1);\nplot(ref(:,1), ref(:,2),'k-.'); hold on; grid on;\n% plot(X(:,1), X(:,2));\n% legend('ref','tracked');\nxlabel('x [m]'); ylabel('y [m]');\n% img_orig = imread('handle.jpg');\n% img = imrotate(img_orig, 10);\n% handle_plt = image([150, 170],[110, 90], img);\n% handle_plt_point = [160, 100, 0];\n\n\neval(subpl2);\nplot(t, lat_error_vec, 'b'); grid on; hold on; \nxlabel('t [s]'); ylabel('latitude error [m]');\nulim = ceil(2*max(lat_error_vec))/2;\ndlim = floor(2*min(lat_error_vec))/2;\nylim([dlim, ulim]);\n\neval(subpl3);\np1 = plot(t, X(:,IDX_STEER)*rad2deg, 'b'); grid on; hold on; \np2 = plot(t, U(:,2)*rad2deg, 'Color', [0.7 0. 1]); hold on; \nlegend([p1,p2], {'measured','command'})\nxlabel('t [s]'); ylabel('steering angle [deg]');\nulim = round(2*max(X(:,IDX_STEER)*rad2deg))/2;\ndlim = round(2*min(X(:,IDX_STEER)*rad2deg))/2;\nylim([dlim, ulim]);\n\nz_axis = [0 0 1];\nsetpoint = []; rear_tire = []; front_tire = []; body = []; tracked = []; \nsetpoint_ideal = []; error_point = []; steer_point = []; time_bar_laterror = []; time_bar_steer = [];\nL = param.wheelbase;\nrear_length = 1;\nfront_length = 1;\nside_width = 0.9;\nfig_draw_i = 1:round(1/dt/20):length(t);\n\n% for movie\nclear frame_vec;\nframe_vec(length(fig_draw_i)) = struct('cdata', [], 'colormap',[]);\n\nj = 1;\nfig_trajectory_result; hold on;\nfor i = fig_draw_i\n    eval(subpl1);\n    disp(t(i))\n    rear_x = X(i,1);\n    rear_y = X(i,2);\n    yaw = X(i,3);\n    delta = X(i,IDX_STEER);\n    front_x = rear_x + L;\n    front_y = rear_y;\n    delete([setpoint, rear_tire, front_tire, body, tracked, setpoint_ideal, error_point, steer_point, time_bar_laterror, time_bar_steer]);\n    tracked = plot(X(1:i,1), X(1:i,2),'r');\n    title_draw = \"t = \"+num2str(t(i),'%5.1f') + \"[s], steer = \" + num2str(delta*rad2deg,'%+3.1f') + \"[deg], v = \" + ...\n        num2str(vel_ref*3600/1000,'%3.1f') + \"[km/h], lat error = \"+num2str(lat_error_vec(i),'%+2.2f') + \"[m]\";\n    title_draw = [title_draw; \"Simulation: solver = rk4, sensor-delay = \"  + num2str(param.input_delay*1000, '%d') + \"[ms], control freq=\" + ...\n        num2str(1/param.control_dt, '%d') + \"[hz]\"];\n    title_draw = [title_draw; \"noise-sigma = \" + num2str(param.measurement_noise_stddev(1),'%2.2f')+\"(pos), \"+ ...\n        num2str(param.measurement_noise_stddev(3),'%2.2f')+\"(yaw), \"+num2str(param.measurement_noise_stddev(4),'%2.2f')+\"(steer)\"];\n    if control_mode == \"mpc\" || control_mode == \"mpc_no_constraints\"\n        title_draw = [title_draw; \"MPC: dt = \" + num2str(param.mpc_dt, '%3.3f') + \"[s], horizon step = \" + num2str(param.mpc_n, '%d')];\n%         pred_states = debug(i, param.mpc_n+1:param.mpc_n*(4+1));\n%         pred_states = reshape(pred_states, param.mpc_n, length(pred_states)/param.mpc_n);\n%         setpoint = plot(pred_states(:,1), pred_states(:,2), 'bo'); % include linealize error\n        pred_error = debug(i, param.mpc_n*(4+1)+1:param.mpc_n*(2+4+1));\n        pred_error = reshape(pred_error, param.mpc_n, length(pred_error)/param.mpc_n);\n        setpoint_ideal = plot(pred_error(:,1), pred_error(:,2), 'mx'); % without linealize error\n    elseif control_mode == \"mpc2\"\n        title_draw = [title_draw; \"MPC2: dt = \" + num2str(param.mpc_dt, '%3.3f') + \"[s], horizon step = \" + num2str(param.mpc_n, '%d')];\n        pred_states = debug(i, param.mpc_n+1:param.mpc_n*(4+1));\n        pred_states = transpose(reshape(pred_states, length(pred_states)/param.mpc_n, param.mpc_n));\n        setpoint = plot(pred_states(:,1), pred_states(:,2), 'bo'); % include linealize error\n        pred_error = debug(i, param.mpc_n*(4+1)+1:param.mpc_n*(4+4+1));\n        pred_error = transpose(reshape(pred_error, length(pred_error)/param.mpc_n, param.mpc_n));\n        setpoint_ideal = plot(pred_error(:,1), pred_error(:,2), 'mx'); % without linealize error\n    elseif control_mode == \"pure_pursuit\"\n        title_draw = [title_draw; \"pure-pursuit: lookahead dist=\"+num2str(param.pure_pursuit_lookahead, '%1.1f')+\"[m]\"];\n        sp = debug(i,:);\n        setpoint = plot(sp(1), sp(2), 'ro');\n    elseif control_mode == \"pid\"\n        title_draw = [title_draw; \"PID: kp = \" + num2str(0.3, '%3.3f') + \", ki = \" + num2str(0, '%3.3f') + \", kd = \" + num2str(1.5, '%3.3f')];\n        sp = debug(i,:);\n        setpoint = plot(sp(1), sp(2), 'ro');\n    end\n    rear_tire = plot([rear_x-0.3, rear_x+0.3],[rear_y, rear_y], 'k', 'LineWidth', 2.0);\n    front_tire = plot([front_x-0.3, front_x+0.3],[front_y, front_y], 'k', 'LineWidth', 2.0);\n    body = plot([rear_x-rear_length, front_x+front_length, front_x+front_length, rear_x-rear_length, rear_x-rear_length], ...\n        [rear_y-side_width, front_y-side_width, front_y+side_width, rear_y+side_width, rear_y-side_width],'k');\n    rear_origin = [rear_x, rear_y, 0];\n    front_origin = [rear_x + L*cos(yaw), rear_y + L*sin(yaw), 0];\n    rotate(body, z_axis, yaw * rad2deg, rear_origin);\n    rotate(rear_tire, z_axis, yaw * rad2deg, rear_origin);\n    rotate(front_tire, z_axis, yaw * rad2deg, rear_origin);\n    rotate(front_tire, z_axis, delta * rad2deg, front_origin);\n%     rotate(handle_plt, [0,0,1], delta*tire2steer*rad2deg, handle_plt_point)\n    title(title_draw);\n    xlim([0 120]);\n     \n    % lat error\n    eval(subpl2);\n    error_point = plot(t(i), lat_error_vec(i), 'ko');\n    time_bar_laterror = plot([t(i), t(i)], [100, -100], 'k');\n    \n    % steering\n    eval(subpl3);\n    steer_point = plot(t(i), X(i, IDX_STEER)*rad2deg, 'ko');\n    time_bar_steer = plot([t(i), t(i)], [100, -100], 'k');\n    legend([p1,p2], {'measured','command'})\n    ylim([-40 40]);\n  \n    \n    drawnow;\n    frame_vec(j) = getframe(fig_trajectory_result);\n    \n    j = j + 1;\nend\n\n\n\n% for video save\nif (save_video == 1)\n    cd ./movie\n    frame_vec(1) = [];\n    vidObj = VideoWriter('result.avi');\n    vidObj.FrameRate = 25;\n    open(vidObj);\n    writeVideo(vidObj, frame_vec);\n    close(vidObj);\n    cd ../\nend\n\n\n\n% plot_pid;", "meta": {"author": "TakaHoribe", "repo": "trajectory_tracking_simulation", "sha": "ba86f63e0644d37580451184faf0dc4874a53ec7", "save_path": "github-repos/MATLAB/TakaHoribe-trajectory_tracking_simulation", "path": "github-repos/MATLAB/TakaHoribe-trajectory_tracking_simulation/trajectory_tracking_simulation-ba86f63e0644d37580451184faf0dc4874a53ec7/simulation/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5925710413297927}}
{"text": "function [accuracy,threshold] = Sys_accuracy(match, nonmatch)\n    [TAR,FAR,nonmatch_score] = rocplot(match, nonmatch);\n    %[length(TAR),length(FAR),length(match),length(nonmatch_score),length(nonmatch)]\n    accuracies=(TAR*length(match)+(1-FAR)*length(nonmatch))/(length(nonmatch)+length(match));\n    [~,idx]=sort(abs(TAR-(1-FAR)),1,'ascend');\n\n    [accuracy,a_idx]=max(accuracies(idx(1:100)));\n    threshold=nonmatch_score(idx(a_idx(1)));", "meta": {"author": "happynear", "repo": "FaceVerification", "sha": "c8c2b4d805abf7240d9d39d7b57151e04958f6bf", "save_path": "github-repos/MATLAB/happynear-FaceVerification", "path": "github-repos/MATLAB/happynear-FaceVerification/FaceVerification-c8c2b4d805abf7240d9d39d7b57151e04958f6bf/Sys_accuracy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5925710407996062}}
{"text": "function volume = cube01_volume ( )\n\n%*****************************************************************************80\n%\n%% CUBE01_VOLUME returns the volume of the unit cube in 3D.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    18 January 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Output, real VOLUME, the volume.\n%\n  volume = 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/cube_integrals/cube01_volume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.5925341807567658}}
{"text": "% [PYR, INDICES] = buildLpyr(IM, HEIGHT, FILT1, FILT2, EDGES)\n%\n% Construct a Laplacian pyramid on matrix (or vector) IM.\n%\n% HEIGHT (optional) specifies the number of pyramid levels to build. Default\n% is 1+maxPyrHt(size(IM),size(FILT));\n%\n% FILT1 (optional) can be a string naming a standard filter (see\n% namedFilter), or a vector which will be used for (separable)\n% convolution.  Default = 'binom5'.  FILT2 specifies the \"expansion\"\n% filter (default = filt1).  EDGES specifies edge-handling, and\n% defaults to 'reflect1' (see corrDn).\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.  This is compatible with the MatLab Wavelet toolbox.\n\n% Eero Simoncelli, 6/96.\n\nfunction [pyr,pind] = buildLpyr(im, ht, filt1, filt2, edges)\n\nif (nargin < 1)\n  error('First argument (IM) is required');\nend\n\nim_sz = size(im);\n\n%------------------------------------------------------------\n%% OPTIONAL ARGS:\n\nif (exist('filt1') ~= 1)\n  filt1 = 'binom5';\nend\n \nif isstr(filt1)\n  filt1 = namedFilter(filt1);\nend\n\nif ( (size(filt1,1) > 1) & (size(filt1,2) > 1) )\n  error('FILT1 should be a 1D filter (i.e., a vector)');\nelse\n  filt1 = filt1(:);\nend\n\nif (exist('filt2') ~= 1)\n  filt2 = filt1;\nend\n\nif isstr(filt2)\n  filt2 = namedFilter(filt2);\nend\n\nif ( (size(filt2,1) > 1) & (size(filt2,2) > 1) )\n  error('FILT2 should be a 1D filter (i.e., a vector)');\nelse\n  filt2 = filt2(:);\nend\n\nmax_ht = 1 + maxPyrHt(im_sz, max(size(filt1,1), size(filt2,1)));\nif (exist('ht') ~= 1)\n  ht = max_ht;\nelse\n  if (ht > max_ht)\n    error(sprintf('Cannot build pyramid higher than %d levels.',max_ht));\n  end\nend\n\nif (exist('edges') ~= 1)\n  edges= 'reflect1';\nend\n\n%------------------------------------------------------------\n\nif (ht <= 1)\n\n  pyr = im(:);\n  pind = im_sz;\n\nelse\n\n  if (im_sz(2) == 1)\n    lo2 = corrDn(im, filt1, edges, [2 1], [1 1]);\n  elseif (im_sz(1) == 1)\n    lo2 = corrDn(im, filt1', edges, [1 2], [1 1]);\n  else\n    lo = corrDn(im, filt1', edges, [1 2], [1 1]);\n    int_sz = size(lo);\n    lo2 = corrDn(lo, filt1, edges, [2 1], [1 1]);\n  end\n\n  [npyr,nind] = buildLpyr(lo2, ht-1, filt1, filt2, edges);\n\n  if (im_sz(1) == 1)\n    hi2 = upConv(lo2, filt2', edges, [1 2], [1 1], im_sz);\n  elseif (im_sz(2) == 1)\n    hi2 = upConv(lo2, filt2, edges, [2 1], [1 1], im_sz);\n  else\n    hi = upConv(lo2, filt2, edges, [2 1], [1 1], int_sz);\n    hi2 = upConv(hi, filt2', edges, [1 2], [1 1], im_sz);\n  end\n\n  hi2 = im - hi2;\n\n  pyr = [hi2(:); npyr];\n  pind = [im_sz; nind];\n\nend\n  \n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/pyrTools/pyrTools/buildLpyr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5925341694916647}}
{"text": "%  Computes the hessian by finite differences\n% \n%  ::\n% \n%     H = finite_differences(Objective,params)\n%     H = finite_differences(Objective,params,varargin)\n% \n%  Args:\n% \n%     - **Objective** [char|function handle]: function to differentiate\n%     - **params** [vector]: point at which the differentiation is taken\n%     - **varargin** : optional/further arguments of the objective function\n% \n%  Returns:\n%     :\n% \n%     - **H** [matrix]: Hessian matrix\n% \n%  See also:\n% \n%     - utils.hessian.outer_product\n% \n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/m/+utils/+hessian/finite_differences.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.5925341676496134}}
{"text": "function [ component_num, c ] = i4block_components ( l, m, n, a )\n\n%*****************************************************************************80\n%\n%% I4BLOCK_COMPONENTS assigns contiguous nonzero pixels to a common component.\n%\n%  Discussion:\n%\n%    On input, the A array contains values of 0 or 1.\n%\n%    The 0 pixels are to be ignored.  The 1 pixels are to be grouped\n%    into connected components.\n%\n%    The pixel A(I,J,K) is \"connected\" to the pixels:\n%\n%      A(I-1,J,  K  ),  A(I+1,J,  K  ),\n%      A(I,  J-1,K  ),  A(I,  J+1,K  ),\n%      A(I,  J,  K-1),  A(I,  J,  K+1),\n%\n%    so most pixels have 6 neighbors.\n%\n%    On output, COMPONENT_NUM reports the number of components of nonzero\n%    data, and the array C contains the component assignment for\n%    each nonzero pixel, and is 0 for zero pixels.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    28 February 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer L, M, N, the order of the array.\n%\n%    Input, integer A(L,M,N), the pixel array.\n%\n%    Output, integer COMPONENT_NUM, the number of components\n%    of nonzero data.\n%\n%    Output, integer C(L,M,N), the component array.\n%\n\n%\n%  Initialization.\n%\n  c = zeros ( l, m, n );\n  component_num = 0;\n%\n%  P is simply used to store the component labels.  The dimension used\n%  here is, of course, usually an absurd overestimate.\n%\n  p = 1 : l * m * n;\n%\n%  \"Read\" the array one pixel at a time.  If a (nonzero) pixel's north or\n%  west neighbor already has a label, the current pixel inherits it.\n%  In case the labels disagree, we need to adjust the P array so we can\n%  later deal with the fact that the two labels need to be merged.\n%\n  for i = 1 : l\n\n    for j = 1 : m\n\n      for k = 1 : n\n\n        if ( i == 1 )\n          north = 0;\n        else\n          north = c(i-1,j,k);\n        end\n\n        if ( j == 1 )\n          west = 0;\n        else\n          west = c(i,j-1,k);\n        end\n\n        if ( k == 1 )\n          up = 0;\n        else\n          up = c(i,j,k-1);\n        end\n\n        if ( a(i,j,k) ~= 0 )\n%\n%  New component?\n%\n          if ( north == 0 && west == 0 && up == 0 )\n            component_num = component_num + 1;\n            c(i,j,k) = component_num;\n%\n%  One predecessor is labeled.\n%\n          elseif ( north ~= 0 && west == 0 && up == 0 )\n            c(i,j,k) = north;\n          elseif ( north == 0 && west ~= 0 && up == 0 )\n            c(i,j,k) = west;\n          elseif ( north == 0 && west == 0 && up ~= 0 )\n            c(i,j,k) = up;\n%\n%  Two predecessors are labeled.\n%\n          elseif ( north == 0 && west ~= 0 && up ~= 0 )\n            c(i,j,k) = min ( west, up );\n            c1 = min ( p(west), p(up) );\n            p(west) = c1;\n            p(up) = c1;\n          elseif ( north ~= 0 && west == 0 && up ~= 0 )\n            c(i,j,k) = min ( north, up );\n            c1 = min ( p(north), p(up) );\n            p(north) = c1;\n            p(up) = c1;\n          elseif ( north ~= 0 && west ~= 0 && up == 0 )\n            c(i,j,k) = min ( north, west );\n            c1 = min ( p(north), p(west) );\n            p(north) = c1;\n            p(west) = c1;\n%\n%  Three predecessors are labeled.\n%\n          elseif ( north ~= 0 && west ~= 0 && up ~= 0 )\n            c(i,j,k) = min ( north, min ( west, up ) );\n            c1 = min ( p(north), min ( p(west), p(up) ) );\n            p(north) = c1;\n            p(west) = c1;\n            p(up) = c1;\n          end\n\n        end\n\n      end\n\n    end\n\n  end\n%\n%  When a component has multiple labels, have the higher labels\n%  point to the lowest one.\n%\n  for component = component_num : -1 : 1\n    b = component;\n    while ( p(b) ~= b )\n      b = p(b);\n    end\n    p(component) = b;\n  end\n%\n%  Locate the minimum label for each component.\n%  Assign these mininum labels new consecutive indices.\n%\n  q = zeros ( 1, component_num );\n  i = 0;\n  for component = 1 : component_num\n    if ( p(component) == component )\n      i = i + 1;\n      q(component) = i;\n    end\n  end\n\n  component_num = i;\n%\n%  Replace the labels by consecutive labels.\n%\n  i = find ( c ~= 0 );\n  c(i) = q ( p ( c(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/image_components/i4block_components.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.5925341663810476}}
{"text": "function deg=degree(p,y,e)\n%DEGREE Polynomial degree\n%\n% DEG = DEGREE(p,x,e)\n%\n% p : SDPVAR object.\n% x : Degree w.r.t linear SDPVAR objects, can be [].\n\n\n% e : If e=1, returns degree of each element in p\n%\n% Examples\n% x1 = sdpvar(1,1);x2 = sdpvar(1,1);\n% p = [x1;x1*x2+x2^2];\n%\n% degree(p) returns 2\n%\n% degree(p,x1) returns 1\n%\n% degree(p,[x1 x2]) returns [1 2]\n%\n% degree(p,[x1 x2],1) returns [1 0;1 2]\n%\n% degree(p,[],1) returns [1;3]\n\nif isa(p,'double')\n    if nargin==1\n        deg = 0;\n    else\n        deg = zeros(1,length(y));\n    end\n    return\nend\n\nif nargin<2\n    y = recover(depends(p));\nend\n\nif nargin<3 | (nargin==3 & e==0)\n    exponent_p = exponents(p,y);\n    switch nargin\n        case 1\n            deg = full(max(sum(exponent_p,2)));\n        case {2,3}\n            deg = full(max(exponent_p,[],1));\n        otherwise\n            error('Too many arguments. Wadda ya mean?')\n    end\nelse\n    p = p(:);\n    if isempty(y)\n        yy = recover(depends(p));\n    else\n        yy = y;\n    end\n    \n    for i = 1:length(p)\n        z.type = '()';\n        z.subs{1} = i;\n        exponent_p = exponents(subsref(p,z),yy);       \n        switch nargin\n            case 1\n                deg(i,:) = full(max(sum(exponent_p,2)));\n            case {2,3}\n                deg(i,:) = full(max(exponent_p,[],1));\n            otherwise\n               error('Too many arguments. Wadda ya mean?')\n        end\n    end\n    if isempty(y)\n        deg = sum(deg,2);\n    end\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/extras/@ncvar/degree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5925341663810475}}
{"text": "function [tf, tf_lambda, tf_U] = isequal(A,B)\n%ISEQUAL True if each component of two ktensor's is numerically equal.\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\ntf = false;\ntf_lambda = false;\ntf_U = false;\n\nif ~isa(B,'ktensor')\n    return;\nend    \n\ntf_lambda = isequal(A.lambda, B.lambda);\nif ncomponents(A) == ncomponents(B)\n    tf_U = cellfun(@isequal, A.u, B.u);\nend\ntf = tf_lambda & all(tf_U);\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/@ktensor/isequal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5925075704242834}}
{"text": "function v = newtonmonoms(p)\n% NEWTONMONOMS Computes all monoms inside half Newton polytope\n%\n% V = NEWTONMONOMS(P)\n%\n% Input\n%  P : Scalar SDPVAR object\n%\n% Output\n%  V : Vector with SDPVAR objects\n%\n% Example:\n%\n% sdpvar x y\n% sdisplay(newtonmonoms(1+x^4*y^2+x^2*y^4))\n%\n% See also NEWTONREDUCE, CONSISTENT, CONGRUENCEBLOCKS\n\nif isa(p,'double')\n    v = 1;\nelse\n    x = recover(depends(p));\n    v = monolist(x,degree(p)/2);\n    v = newtonreduce(v,p);\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/sos/newtonmonoms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5925075676194584}}
{"text": "function [newton_m2,N_unique,newton_m2_unique] = monomialproducts(N,n);\n%MONOMIALPRODUCTS  Internal function used for monomial reduction\n\n% Exponents in squared monomials\n\nN_unique = [];\nfor i = 1:size(N,1)\n    newton_m2{i} = [];\n    n = size(N{i},1);\n    for j = 1:n\n        newton_m2{i} = [newton_m2{i};[(1:n)' repmat(j,n,1) N{i}(1:n,:)+repmat(N{i}(j,:),n,1)]];\n    end\n    % Whoops, double copies of diagonal (we want double copies of non-diagonals though)\n    if isempty(newton_m2{i})\n        newton_m2_unique{i} = [];\n    else\n        [dummy,j,dummy2] = uniquesafe(newton_m2{i}(:,1:2),'rows');\n        newton_m2{i} = newton_m2{i}(j,:);\n        % Extract unique monomial products\n        [dummy,j,dummy2] = uniquesafe(newton_m2{i}(:,3:end),'rows');\n        newton_m2_unique{i} = newton_m2{i}(j,:);\n    end\n    N_unique = [N_unique;newton_m2_unique{i}];   \nend\nif ~isempty(N_unique)\n    [dummy,j,dummy2] = uniquesafe(N_unique(:,3:end),'rows');\n    N_unique = N_unique(j,:);\nend\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/sos/monomialproducts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5925075637311183}}
{"text": "function vscl = vscale(f) \n%VSCALE   Vertical scale of a SEPARABLEAPPROX.\n% \n% VSCL = VSCALE(F) returns the vertial scale of a SEPARABLEAPPROX as determined\n% by evaluating on a coarse tensor-product grid. \n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% TODO: Should this also be taking the maximum along the edges when we are\n% evaluating at 1st kind grids. \n\n% If f is an empty SEPARABLEAPPROX, VSCL = 0: \nif ( isempty( f ) ) \n    vscl = 0; \n    return\nend\n\n% Get the degree of the SEPARABLEAPPROX:\n[m, n] = length(f); \n\n% If F is of low degree, then oversample: \nm = min(max(m, 9),2000); \nn = min(max(n, 9),2000); % cannot afford to go over 2000x2000. \n\n% Calculate values on a tensor grid: \nvals = sample(f, m, n); \n\n% Take the absolute maximum: \nvscl = max(abs(vals(:))); \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/@separableApprox/vscale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5925075609262936}}
{"text": "function [ y, m, d ] = day_carry_roman ( y, m, d )\n\n%*****************************************************************************80\n%\n%% DAY_CARRY_ROMAN carries days to months in a Roman date.\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/output, integer Y, M, D, the YMD date.\n%    On output, D is between 1 and the number of days in M.\n%\n  days = month_length_roman ( y, m );\n\n  while ( days < d )\n\n    d = d - days;\n    m = m + 1;\n    days = month_length_roman ( y, m );\n%\n%  Make sure the month isn't too big.\n%\n    [ y, m ] = month_carry_roman ( y, m );\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/calpak/day_carry_roman.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.5925075539622494}}
{"text": "\nload 'sdae_mnist_vis.mat';\n\ncolors = colormap;\n\nfigure;\nhold on;\nfor c = 1:10\n    x = H(X_labels == (c-1), 1);\n    y = H(X_labels == (c-1), 2);\n    rndidx = randperm(length(x));\n    x = x(rndidx(1:500));\n    y = y(rndidx(1:500));\n\n    plot(x, y, 'x', 'Color', colors(ceil(c/10 * 64), :));\nend\nhold off;\n\n\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/example/vis_mnist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788903594355, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5925075455957926}}
{"text": "%  Figure 7.23      Feedback Control of Dynamic Systems, 6e\n%                        Franklin, Powell, Emami\n% script to generate Fig. 7.23\n% fig7_23.m\n% Nyquist for LQR\nclf;\nf=[0 1;0 0];\ng=[0;1];\nh=[1 0];\nj=0;\nr=1;\nrho=1;\nq=rho*h'*h;\n[k,s]=lqr(f,g,q,r);\nsys=ss(f,g,k,0);\n% circle of radius one\nplot(-1+sin(0:.1:2*pi),cos(0:.1:2*pi),'r--');\naxis equal;\ntext(-1,0,'x');\nhold on;\nw=logspace(0,2);\nnyquist(sys,w);\ntitle('Fig. 7.23: Nyquist diagram');\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig7_23.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5924797710006681}}
{"text": "function [Va, Mask] = reslice_vol(Vo, M, interp)\n% function [Va, Mask] = reslice_vol(Vo, M, interp)\n\n% Ripped out of SPM 8 and modified (2010, S.Klanke)\n\ndim = size(Vo);\nwrap = [1;1;0];\nd = [interp*[1;1;1] wrap];\n\n[x1,x2] = ndgrid(1:dim(1), 1:dim(2));\nC = spm_bsplinc(Vo, d);\nVa = zeros(dim);\nMask = zeros(dim);\n\nfor x3 = 1:dim(3)\n\t[msk_x3,y1,y2,y3] = getmask(M,x1,x2,x3,dim,wrap);\n\tMask(:,:,x3) = msk_x3;\n    Va(:,:,x3) = spm_bsplins(C, y1,y2,y3, d);\nend\nreturn;\n\nfunction [Mask,y1,y2,y3] = getmask(M,x1,x2,x3,dim,wrp)\ntiny = 5e-2; % From spm_vol_utils.c\ny1   = M(1,1)*x1+M(1,2)*x2+(M(1,3)*x3+M(1,4));\ny2   = M(2,1)*x1+M(2,2)*x2+(M(2,3)*x3+M(2,4));\ny3   = M(3,1)*x1+M(3,2)*x2+(M(3,3)*x3+M(3,4));\nMask = true(size(y1));\nif ~wrp(1), Mask = Mask & (y1 >= (1-tiny) & y1 <= (dim(1)+tiny)); end\nif ~wrp(2), Mask = Mask & (y2 >= (1-tiny) & y2 <= (dim(2)+tiny)); end\nif ~wrp(3), Mask = Mask & (y3 >= (1-tiny) & y3 <= (dim(3)+tiny)); end\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/realtime/online_mri/private/reslice_vol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782094, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5924797664926738}}
{"text": "function [x_mu, y_mu sig] = localizew(w,peval,localMaxRadius)\n% [x_mu, y_mu sig] = localizew(w,peval,localMaxRadius)\n% Localilzes w (#pixels x #components) from NMF model (V=WH)\n% peval : parameters (needed peval.nx, peval.ny)\n% localMaxDiameter : diameter in pixels to which confine a local maximum search. If set to 0 (default) no confinemend is done.  \nif ~exist('localMaxRadius', 'var')\n    localMaxRadius = 0; % Finding global max. \nend\nK=size(w,2);\nwr=reshape(w,peval.nx, peval.ny,K); %K can be different from peval.ncomp if background is takes as one component...\n[x,y] = meshgrid(1:peval.ny, 1:peval.nx); % nx and ny has to be swapped as in the image the first coordiante is number of rows\nif localMaxRadius\n    fprintf('Looking for local maximum %g only.\\n', localMaxRadius);\nend\n\nx_mu=inf(1,K);\ny_mu=inf(1,K);\nsig=inf(1,K);\ndiffer=inf(1,K);\nfor ii=1:K %background is not localized...\n    [x_mu(ii), y_mu(ii), sig(ii), differ(ii)] = fitgauss2d(wr(:,:,ii));\n    if localMaxRadius>0        \n        confinementMaskTmp=(x-x_mu(ii)).^2+(y-y_mu(ii)).^2<=localMaxRadius^2;\n        [ymtmp,xmtmp]=find(wr(:,:,ii)==max(max(wr(:,:,ii).*confinementMaskTmp)),1);\n        if isempty(xmtmp)&&isempty(ymtmp)\n            xmtmp=10*peval.nx;\n            ymtmp=xmtmp;\n            fprintf('Problem with maximum localisation.\\n');\n        end\n        confinementMask=(x-xmtmp).^2+(y-ymtmp).^2<=localMaxRadius^2; % mask centered on the local maximum\n        [x_mu(ii), y_mu(ii), sig(ii), differ(ii)] = fitgauss2d(wr(:,:,ii).*confinementMask);\n    end\n        \nend\n\nif sum(isinf([x_mu, y_mu,sig,differ]))\n    warning('Problem with localisation...')\nend", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/analyzingtool/localizew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5924797664926736}}
{"text": "% Fig. 6.13   Feedback Control of Dynamic Systems, 6e \n%             Franklin, Powell, Emami\n%\n\nclear all;\n%close all;\nclf\n\nnum=10;\nden=[1 1 0];\nw=logspace(-2,1,100);\n[m,p]=bode(num,den,w);\nwa=[.01 1.2];\nma=[1000 8.3333];\nloglog(w,m,w,10*ones(1,100),'--',wa,ma);\nxlabel('\\omega (rad/sec)');\nylabel('Magnitude');\ntitle('Fig. 6.13 Determination of Kv from the Bode plot');\nbodegrid;\n", "meta": {"author": "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_13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5924111784529218}}
{"text": "function [strshocks_record]=strshocks(beta_gibbs,D_record,Y,X,n,k,It,Bu,favar)\n\n% first create the call storing the results\nstrshocks_record=cell(n,1);\nBgibbs=reshape(beta_gibbs,k,n,It-Bu);\nDgibbs=reshape(D_record,n,n,It-Bu);\n\n% recall X and Y from the sampling process in this case\nif favar.FAVAR==1\n    if isfield(favar,'bvarXY')==1\n        bvarXY=1;\n        Xgibbs=reshape(favar.X_gibbs,size(X,1),size(X,2),It-Bu);\n        Ygibbs=reshape(favar.Y_gibbs,size(Y,1),size(Y,2),It-Bu);\n    else\n        bvarXY=0;\n    end\nelse\n    bvarXY=0;\nend\n\n% then loop over iterations\nfor ii=1:It-Bu\n    \n    % recover the VAR coefficients, reshaped for convenience\n    B=squeeze(Bgibbs(:,:,ii));\n    \n    if bvarXY==1\n        X=squeeze(Xgibbs(:,:,ii));\n        Y=squeeze(Ygibbs(:,:,ii));\n    end\n    \n    % obtain the residuals from (XXX)\n    EPS=Y-X*B;\n    \n    % then recover the structural marix D\n    D=squeeze(Dgibbs(:,:,ii));\n    \n    % obtain the structural disturbances from (XXX)\n    ETA=D\\EPS';\n    \n    % save in struct_shocks_record\n    for jj=1:n\n        strshocks_record{jj,1}(ii,:)=ETA(jj,:);\n    end\n    \nend\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/strshocks.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5923814206841724}}
{"text": "function [ber,rate] = Mrate_method()\n% traditional SVD algorithm for rate maximization\n\nglobal  H Ns V_ropt W_ropt;\n[U,~,V] = svd(H);\nV_ropt = V(:,1:Ns);\n%power constraint\nV_ropt = V_ropt / norm(V_ropt,'fro');\nW_ropt = U(:,1:Ns);\n\nber = get_ber(V_ropt,W_ropt);\nrate = get_rate(V_ropt,W_ropt);", "meta": {"author": "TianLin0509", "repo": "Hybrid-Beamforming-for-Millimeter-Wave-Systems-Using-the-MMSE-Criterion", "sha": "13764ff92998c4c8c82bea82f2077301af796283", "save_path": "github-repos/MATLAB/TianLin0509-Hybrid-Beamforming-for-Millimeter-Wave-Systems-Using-the-MMSE-Criterion", "path": "github-repos/MATLAB/TianLin0509-Hybrid-Beamforming-for-Millimeter-Wave-Systems-Using-the-MMSE-Criterion/Hybrid-Beamforming-for-Millimeter-Wave-Systems-Using-the-MMSE-Criterion-13764ff92998c4c8c82bea82f2077301af796283/shared_APIs/Algorithms/Mrate_method.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5923814206841723}}
{"text": "function Fs = fu2F7(u)\n\nZ = lin_fm(u);\n\nNullSp   = null(Z);\nif size(NullSp,2) > 2\n   Fs = [];\n   return; %degenerated sample\nend\n\nF1    = reshape(NullSp(:,1),3,3);\nF2    = reshape(NullSp(:,2),3,3);\np = fslcm(F1,F2);\naroots = rroots(p);\n\n%xr = o_fslcm(F1,F2)\n\n%aroots == xr\n\nfor i = 1:length(aroots)\n   l  = aroots(i);\n   Ft    = F1 * l + F2 * (1-l);\n%   Ft = Ft /norm(Ft,2);\n   Fs(:,:,i) = Ft;\nend\n\n\n\n", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamSelfCal/Ransac/fu2F7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5923814188766731}}
{"text": "clc\nclear all\naddpath(genpath('./'));\n\ntol = 5e-6; % optimality tolerance for stopping_type 1 \nDB=20; % SNR of the video\nframe_array=[35,100,125]; % frames that will be shown at the end \n\nseed = 602;\nrandn('state',seed); rand('state',seed);\nif exist('Hall_airport_1000_1496_497_144_176_gray.mat')==0\n    error('Video file cannot be found. Please download it from: http://www2.ie.psu.edu/aybat/Hall_airport_1000_1496_497_144_176_gray.mat')\nelse\n    load Hall_airport_1000_1496_497_144_176_gray.mat;\nend\nD = images(:,1:201);\nn1=144*176; n2=201;\nstdev = norm(D,'fro')/(sqrt(144*176*201)*10^(DB/20));\nD = D+stdev*randn(144*176,201);\n[X,S]=nsa(D,stdev,tol,1);\nfigure\nplot_data(frame_array,D,X,S,144,176)", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/NSA1/demo_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5923738305233645}}
{"text": "function cache = score_init_cache(N,L)\n% SCORE_INIT_CACHE generate an empty cache for local computation in structure learning\n% cache = score_init_cache(number_of_nodes,cache_size)\n%\n% For 2 nodes with cache of size 5 :\n%\n% cache =\n%   Nw  b        0      0      0 --> Nw=number of writings in cache (+1) and b==1 iff the cache is full\n%   0   0        1   -239.12   1 --> 1st familly in the cache (node 1 without parents) calculate with bic\n%   0   0        2   -318.98   1\n%   1   0        2   -189.23   2 --> 3rd familly in the cache (node 2 with 1 as parent) calculate with bayesian\n%   0   1        1   -251.09   1\n%   0   0        0      0      0 --> empty entry\n%   |   |        |      |      |\n%   |   |        |      |      |___> scoring function : 1 for 'bic', 2 for 'bayesian', ...\n%   |   |        |      |__________> local score of the familly\n%   |   |        |_________________> son node of the familly\n%   |   |__________________________> ==1 iff node 2 is parent of son node\n%   |______________________________> ==1 iff node 1 is parent of son node\n%\n%\n% V1.1 : 6 may 2003 (O. Francois - francois.olivier.c.h@gmail.com, Ph. Leray - philippe.leray@univ-nantes.fr)\n%\n%\n\ncache=zeros(L+1,N+3);\ncache(1,1)=2;\n\n% using a sparse matrix does not improve performances\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/scoring/score_init_cache.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5923738247145796}}
{"text": "%%%% EVALUATES CONSTRIANT ERROR\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\nfunction [Cerr]= CONSTRAINT_ERROR_1(th1,x2,y2,th2)\n\nglobal l1 lc1 l2 lc2\n\nCerr=[];\n\nfor i=1:length(th1)\n\n    c1=cos(th1(i));\n    c2=cos(th2(i));\n    s1=sin(th1(i));\n    s2=sin(th2(i));\n\n\n    C= [x2(i)-l1*c1-lc2*c2;\n        y2(i)-l1*s1-lc2*s2];\n    Cerr=[Cerr;abs(C')];\nend\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/24246-dynamic-control-of-two-link-manipulator-with-redundant-coordinates/2 Link Dynamic Control/Code/CONSTRAINT_ERROR_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5923738189057943}}
{"text": "function [qualMeas]=Measure_Quality(res_prev,res,QualMeasOpts)\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:           Manasavee Lohvithee\n%--------------------------------------------------------------------------\n\n%for loop over parameters to get the name \nfor ii=1:length(QualMeasOpts)\n    opt=QualMeasOpts{ii};\n   \n    switch opt\n        case 'RMSE'\n         q=RMSE(res_prev,res);\n         \n        case 'CC'\n         q=CC(res_prev,res); \n         \n        case 'MSSIM'\n         q=MSSIM(res_prev,res);\n         \n        case 'UQI'\n         q=UQI(res_prev,res);\n        case 'error_norm'\n         q=im3Dnorm(res_prev-res,'L2');\n        \n    end\n    \n    \n    qualMeas(ii)=q; \nend\n\n\n\nend", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Utilities/Quality_measures/Measure_Quality.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5923738189057943}}
{"text": "function W = upgrading_merge(W, miu)\nN = size(W, 2);%N is not a constant if merge is needed\nif N <= miu\n    return\nelse\n%         sum_before_merge = 0;\n%         for i = 1 : N/2\n%           sum_before_merge = sum_before_merge + norm(W(:, i) - W(end:-1:1, N - i + 1));\n%         end       \n%         sum_before_merge\n%         \n%         if sum_before_merge > 0.01\n%             sum(W(1, :))\n%              sum(W(2, :))\n%              W\n%         end\n% \n%         if sum_before_merge ~= 0\n%             sum_before_merge\n%             W\n%             sum(W(1, :))\n%             sum(W(2, :))\n%             LLR = log(W(1,:)) - log(W(2,:))\n%             [~, orderd] = sort(LLR, 'descend')\n%         end\n    \n    epsilon = 1e-3;\n    while(N > miu)\n\n        W_first_half = W(:, 1 : N/2);\n        LR = W_first_half(1, :)./W_first_half(2, :);\n        numerical_warning = 0;\n        \n        for i = 1 : N/2 - 1\n            ratio = LR(i)/LR(i + 1);\n            if ratio < 1 + epsilon\n                numerical_warning = 1;\n                break;\n            end\n        end\n        \n        if numerical_warning == 1\n\n            min_deltaI = realmax;\n            min_index = 0;\n            for i = 1 : N/2 - 1\n                a2 = W(1, i);\n                b2 = W(2, i);\n                a1 = W(1,i + 1);\n                b1 = W(2, i + 1);\n                deltaI = delta_capacity_lemma9(a1, a2, b1, b2);\n                if deltaI < min_deltaI %find minimum delta I\n                    min_deltaI = deltaI;\n                    min_index = i;\n                end\n            end\n\n            if min_index == 0\n                for k = 1 : N/2\n                    if sum(W(:, k)) < 1e-20\n                        min_index = k;\n                        W(:, min_index) = [];\n                        W(:, N - min_index) = [];\n                        N = size(W, 2);\n                        break;\n                    end\n                end\n                continue;\n            end\n\n            a2 = W(1, min_index);\n            b2 = W(2, min_index);\n            a1 = W(1, min_index + 1);\n            b1 = W(2, min_index + 1);\n\n           \n\n            \n            if a2/b2 < inf\n                lambda2 = a2/b2;\n                alpha2 = lambda2 * (a1 + b1)/(lambda2 + 1);\n                beta2 = (a1 + b1)/(lambda2 + 1);\n            else\n                alpha2 = a1 + b1;\n                beta2 = 0;\n            end\n\n            W(1, min_index) =  a2 + alpha2;\n            W(2, min_index) =  b2 + beta2;\n            W(1, N - min_index + 1) =  b2 + beta2;\n            W(2, N - min_index + 1) =  a2 + alpha2;\n            \n            W(:, min_index + 1) = [];\n            W(:, N - min_index - 1) = [];\n            N = size(W, 2);\n            \n        else\n\n            min_deltaI = realmax;\n            min_index = 0;\n\n            for i = 1 : N/2 - 2\n                a3 = W(1, i);\n                b3 = W(2, i);\n                a2 = W(1,i + 1);\n                b2 = W(2, i + 1);\n                a1 = W(1,i + 2);\n                b1 = W(2, i + 2);\n                \n                deltaI = delta_capacity_lemma11(a1, a2, a3, b1, b2, b3);\n\n                if deltaI < min_deltaI %find minimum delta I\n                    min_deltaI = deltaI;\n                    min_index = i;\n                end\n            end\n\n            if min_index == 0\n                for k = 1 : N/2\n                    if sum(W(:, k)) < 1e-20\n                        min_index = k;\n                        W(:, min_index) = [];\n                        W(:, N - min_index) = [];\n                        N = size(W, 2);\n                        break;\n                    end    \n                end\n                continue;\n            end\n            \n            a3 = W(1, min_index);\n            b3 = W(2, min_index);\n            a2 = W(1, min_index + 1);\n            b2 = W(2, min_index + 1);\n            a1 = W(1, min_index + 2);\n            b1 = W(2, min_index + 2);\n\n            lambda1 = a1/b1;\n            if a3/b3 < inf\n                lambda3 = a3/b3;\n                alpha1 = lambda1 * (lambda3 * b2 - a2) / (lambda3 - lambda1);\n                beta1 = (lambda3 * b2 - a2) / (lambda3 - lambda1);\n                alpha3 = lambda3 * (a2 - lambda1 * b2) / (lambda3 - lambda1);\n                beta3 = (a2 - lambda1 * b2) / (lambda3 - lambda1);\n            else\n                alpha1 = lambda1 * b2;\n                beta1 = b2;\n                alpha3 = a2 - lambda1 * b2;\n                beta3 = 0;\n            end\n            \n            W(1, min_index) =  a3 + alpha3;\n            W(2, min_index) =  b3 + beta3;\n            \n            W(1, min_index + 1) =  a1 + alpha1;\n            W(2, min_index + 1) =  b1 + beta1;\n            \n            W(1, N - min_index + 1) =  b3 + beta3;\n            W(2, N - min_index + 1) =  a3 + alpha3;\n            \n            W(1, N - min_index) =  b1 + beta1;\n            W(2, N - min_index) =  a1 + alpha1;\n            \n            W(:, min_index + 2) = [];\n            W(:, N - min_index - 2) = [];\n            N = size(W, 2);\n\n%             if N == miu\n%                 W\n%             end\n        end\n    end\n    \n    \n    \n%         sum_after_merge = 0;\n%         for i = 1 : N/2\n%             sum_after_merge = sum_after_merge + norm(W(:, i) - W(end:-1:1, N - i + 1));\n%         end\n%         sum_after_merge\n% W\nend\nend", "meta": {"author": "YuYongRun", "repo": "PolarCodeDecodersInMatlab", "sha": "f1b512d10bf057e83f18685ea012d242bdaaf6ac", "save_path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab", "path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab/PolarCodeDecodersInMatlab-f1b512d10bf057e83f18685ea012d242bdaaf6ac/PolarFastSCL/HowToConstructPolarCode/UpgradingConstruction/upgrading_merge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5922430146855564}}
{"text": "function im_o   =  Add_noise( im, v )\n\nseed  =  0;\nrandn( 'state', seed );\nnoise     =  randn( size(im) );\n% noise     =  noise/sqrt(mean2(noise.^2));\nim_o      =  double(im) + v*noise;", "meta": {"author": "lbasek", "repo": "image-denoising-benchmark", "sha": "9d753198d715b7628c8e7d9259dfa5c219d033ea", "save_path": "github-repos/MATLAB/lbasek-image-denoising-benchmark", "path": "github-repos/MATLAB/lbasek-image-denoising-benchmark/image-denoising-benchmark-9d753198d715b7628c8e7d9259dfa5c219d033ea/algoritms/matlab/NCSR/Utilities/Add_noise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5922430084217709}}
{"text": "nmpcdata=zeros(3,6);%Store data in matrix for nmpc and impc, first row: mean of computing time; second row: standard deviation of computing time; third row: infeasible rate\nimpcdata=zeros(3,6);\nfor ii = 1:6\ni=ii*4;\nfilenm1 = ['timecom' num2str(i) '.mat'];\nfilenm2 = ['feasibility' num2str(i) '.mat'];\nload(filenm1);\nload(filenm2);\ndistnmpc = fitdist(nmpcplot1','Normal');\ndistimpc = fitdist(impcplot1','Normal');\nmu1=distnmpc.mu;%Get mean of sample of computing time for NMPC-DCBF\nmu2=distimpc.mu;%Get mean of sample of computing time for iMPC-DCBF\nsigma1=distnmpc.sigma;%Get variance of sample of computing time for NMPC-DCBF\nsigma2=distimpc.sigma;%Get variance of sample of computing time for iMPC-DCBF\nnmpcdata(1,ii)=mu1; \nimpcdata(1,ii)=mu2;\nnmpcdata(2,ii)=sigma1;\nimpcdata(2,ii)=sigma2;\nnmpcdata(3,ii)=nmpcinf;\nimpcdata(3,ii)=impcinf;\nend", "meta": {"author": "HybridRobotics", "repo": "NMPC-DCLF-DCBF", "sha": "3f40c67578f49114301b02e744e5a86fa671a981", "save_path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF", "path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF/NMPC-DCLF-DCBF-3f40c67578f49114301b02e744e5a86fa671a981/matlab/acc2023/benchmark/gamma1_0p4/test_each_horizon/tabledata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5922430043201609}}
{"text": "% MAIN.m  --  Particle Swarm Optimization\n%\n% This script is used to run particle swarm optimization on several test\n% functions. \n%\n\nquadraticBowl = @(x)( sum(x.^2,1) );\nquadraticBowlSkew2d = @(x)( 0.3*x(1,:).^2 + 4.2*x(2,:).^2 );\nnoisyBowl = @(x)( sum(x.^2 + 0.1*randn(size(x)),1) );\n\nproblem.options.populationCount = 15;   % Number of particles in the search\nproblem.options.w = 0.3;  % Particle damping coefficient\nproblem.options.pg = 0.7;   % Global search coefficient\nproblem.options.pl = 0.5;   % Local search coefficient\nproblem.options.maxIter = 20;  % Number of iterations\n\nproblem.xLow = -ones(2,1);\nproblem.xUpp = ones(2,1);\n\nproblem.objFun = quadraticBowl;\n% problem.objFun = quadraticBowlSkew2d;\n% problem.objFun = noisyBowl;\n\nsoln = particleSwarmOptimization(problem);\n\n%%%% Plotting:\nfigure(1);\nfor i=1:problem.options.maxIter\n    plotIterData(soln,i);   %Only works for 2D objective function\n    pause(0.5);\nend\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/ParticleSwarmOptimization/MAIN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5922430043201607}}
{"text": "% RSADJUST - adjust l-values (Ramberg-Schmeiser distribution) \n%                with respect to signal mean and variance\n%\n% Usage: p = rsadjust(l3, l4, m, var, skew)\n%\n% Input:\n%   l3   - value lambda3 for Ramberg-Schmeiser distribution\n%   l4   - value lambda4 for Ramberg-Schmeiser distribution\n%   m    - mean of the signal distribution\n%   var  - variance of the signal distribution\n%   skew - skewness of the signal distribution (only the sign of\n%          this parameter is used).\n%\n% Output:\n%   l1  - value lambda3 for Ramberg-Schmeiser distribution\n%   l2  - value lambda4 for Ramberg-Schmeiser distribution\n%   l3  - value lambda3 for Ramberg-Schmeiser distribution (copy\n%         from input)\n%   l4  - value lambda4 for Ramberg-Schmeiser distribution (copy\n%         from input)\n%\n% Author: Arnaud Delorme, SCCN, 2003\n%\n% See also: RSFIT, RSGET\n%\n% Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F.\n%            A probability distribution and its uses in fitting data. \n%            Technimetrics, 1979, 21: 201-214.\n\n% Copyright (C) 2003 Arnaud Delorme, SCCN, 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 [l1,l2,l3,l4] = rsadjust( l3, l4, mu, sigma2, m3);\n    \n    % swap l3 and l4 for negative skewness\n    % ------------------------------------\n    if m3 < 0\n        ltmp = l4;\n        l4   = l3;\n        l3   = ltmp;\n    end\n    \n    A = 1/(1 + l3) - 1/(1 + l4);\n    B = 1/(1 + 2*l3) + 1/(1 + 2*l4) - 2*beta(1+l3, 1+l4);\n    C = 1/(1 + 3*l3) - 1/(1 + 3*l4) ...\n             - 3*beta(1+2*l3, 1+l4) + 3*beta(1+l3, 1+2*l4);\n\n    % compute l2 (and its sign)\n    % ------------------------\n    l2 = sqrt( (B-A^2)/sigma2 );    \n    if m3 == 0, m3 = -0.000000000000001; end\n    if (m3*(C - 2*A*B + 2*A^3)) < 0, l2 = -l2; end\n    %l22 = ((C - 2*A*B + 2*A^3)/m3)^(1/3) % also equal to l2\n       \n    % compute l1\n    % ----------\n    l1 = mu - A/l2;\n    \n    return;\n    \n    % fitting table 1 of \n    % ---------------\n    [l1 l2]  = pdffitsolv2(-.0187,-.0388, 0, 1, 1)\n    [l1 l2]  = pdffitsolv2(-.1359,-.1359, 0, 1, 0)\n\n    % sign problem\n    [l1 l2]  = pdffitsolv2(1.4501,1.4501, 0, 1)\n    \n    % numerical problem for l1\n    [l1 l2]  = pdffitsolv2(-.00000407,-.001076, 0, 1, 2)\n    [l1 l2]  = pdffitsolv2(0,-.000580, 0, 1, 2)\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/timefreqfunc/rsadjust.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5922429946754895}}
{"text": "function VectorFitting_Sparam ()\nclear; close all; FONTSIZE=20;\n\nfile='../DC_ringmod_type1_R=10,gap=180,Lc=0,wg=500,lambda=1550,mesh=2,angle=30.mat';\nload (file)\n\nc=3e8; wavelength=c./f*1e6;\nfSCALING = 1e14; f=f/fSCALING; s=1i*2*pi*f;  Np=length(f);\nhwait = waitbar(0,'Please wait...');\n\n% average the S parameters for the symmetric parameters that were simulated twice,\n% by considering amplitude and phase separately\nS1221 = (abs(S12)+abs(S21))/2 .* exp ( 1i * (unwrap(angle(S12)) + unwrap(angle(S21)) ) /2 );\nS12=S1221; S21 = S1221;\nS4132 = (abs(S41)+abs(S32))/2 .* exp ( 1i * (unwrap(angle(S41)) + unwrap(angle(S32)) ) /2 );\nS41=S4132; S32 = S4132;\nS13=S31; S23=S41; S33=S11; S43=S21; S14=S32; S24=S42; S34=S12; S44=S22;\n\n\nfor i=1:Np\n  Sparam = [ [ S11(i),S12(i),S13(i),S14(i)];\n    [ S21(i),S22(i),S23(i),S24(i)];\n    [ S31(i),S32(i),S33(i),S34(i)];\n    [ S41(i),S42(i),S43(i),S44(i)] ] ;\n  Test1(i) = norm(Sparam);\n  Sparam_w (:,:,i)=Sparam;\nend\n\n% Check if S-Parameters are already passive; if not, perform Vector Fit,\n% otherwise, export.\nif ~isempty(find(Test1>1))\n  \n  % rational fit, sweep number of parameters, N:\n  optsN=20:1:100; \n  opts.poletype='lincmplx'; opts.parametertype='S'; opts.stable=0; opts.Niter_out=10;\n  Npassive=[]; rms3passive=[];\n  for i=1:length(optsN)\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    opts.N=optsN(i);    % Vector Fit:\n    [SER,rmserr,Hfit,opts2]=VFdriver(Sparam_w,s,[],opts);\n    \n    %%%%%%%%%%%%%%%%%%%%%%  Enforce Passivity:\n    [SER,H_passive,opts3,wintervals]=RPdriver(SER,s,opts);\n    % Note: added output parameter wintervals to RPdriver.\n    \n    % Find rms error:\n    tell=0; Nc=length(SER.D);\n    for col=1:Nc\n      for row=col:Nc % makes assumption that S = S'\n        tell=tell+1; % make a single vector:\n        Sparam10(tell,:)= squeeze(Sparam_w(row,col,:)).';\n        fit10(tell,:)= squeeze(Hfit(row,col,:)).';\n        fitP(tell,:)= squeeze(H_passive(row,col,:)).';\n      end\n    end\n    rms2(i) = sqrt(sum(sum(abs((Sparam10-fit10).^2))))/sqrt(4*Np);\n    rms3(i) = sqrt(sum(sum(abs((Sparam10-fitP).^2))))/sqrt(4*Np);\n    \n    % Determine if the Passivity Enforcement was successful.\n    if (rms3(i) < 1) && isempty(wintervals)\n      Npassive=[Npassive optsN(i)]; rms3passive = [rms3passive rms3(i)];\n    end\n    \n    waitbar (i/length(optsN), hwait); \n    if (rms3(i) < 1e-4) && isempty(wintervals) ; break; end\n  end\n  close (hwait);\n  \n  % Plot error versus number of fitting parameters:\n  figure;\n  semilogy(optsN(1:i),rms2,'ro-', 'LineWidth',2, 'MarkerSize',7); hold all;\n  labels={}; labels{end+1} = 'Vector Fit, rms';\n  plot (Npassive, rms3passive, 'kx', 'MarkerSize',14, 'LineWidth',3);\n  labels{end+1} = 'Passivity-Enforced Fit, rms';\n  xlabel('Fitting order, N');   ylabel('rms error');\n  for ii=1:length(labels); labels{ii}=[labels{ii} ' ' char(31) ]; end;\n  legend (labels,'Location','NorthEast');\n  printfig(file,'convergence');\n  \n  % Plot residue values:\n  figure;\n  residues=sort(squeeze(prod(prod(abs(SER.R),1),2).^(1/4)), 1, 'descend');\n  semilogy(residues,'-s', 'LineWidth',3, 'MarkerSize',8); \n  xlabel('Residue index'); ylabel('Residue magnitude');\n  printfig(file,'residues');\n \n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % Plot S-Parameters + fit functions:\n  figure;\n  Nc=length(SER.D);\n  for row=1:Nc\n    for col= row:Nc\n      dum1=squeeze(Sparam_w(row,col,:));\n      dum2=squeeze(H_passive(row,col,:));\n      h1=semilogy(wavelength,abs(dum1),'b','LineWidth',3); hold on\n      h2=semilogy(wavelength,abs(dum2),'r-.','LineWidth',4);\n      h3=semilogy(wavelength,abs(dum2-dum1),'g--','LineWidth',3);\n    end\n  end\n  hold off\n  xlabel('Wavelength'); ylabel('Amplitude [S]');\n  axis tight; Yl =ylim; ylim ([Yl(1)*10 Yl(2)*2]);\n  labels={}; labels{end+1} = 'FDTD S-Parameters';\n  labels{end+1} = 'Passivity-enforced Fit'; labels{end+1}='Deviation';\n  for i=1:length(labels); labels{i}=[labels{i} ' ' char(31)]; end;\n  legend (labels,'Location','Best');\n  printfig(file,'VF2a');\n  \n  figure;\n  Nc=length(SER.D);\n  for row= 1:Nc  %1\n    for col= row:Nc  %3\n      dum1=squeeze(Sparam_w(row,col,:));\n      dum2=squeeze(H_passive(row,col,:));\n      h1=semilogy(wavelength,unwrap(angle(dum1)),'b','LineWidth',3); hold on\n      h2=plot(wavelength,unwrap(angle(dum2)),'r-.','LineWidth',4);\n      h3=plot(wavelength,abs(unwrap(angle(dum2))-unwrap(angle(dum1))),'g--','LineWidth',3);\n    end\n  end\n  hold off\n  xlabel('Wavelength'); ylabel('Phase [S]');\n  axis tight; Yl =ylim; ylim ([Yl(1)*10 Yl(2)*2]);\n  labels={}; labels{end+1} = 'FDTD S-Parameters';\n  labels{end+1} = 'Passivity-enforced Fit'; labels{end+1}='Deviation';\n  for i=1:length(labels); labels{i}=[labels{i} ' ' char(31)]; end;\n  legend (labels,'Location','Best');\n  printfig(file,'VF2p');\n  \n  \n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % Passivity test results:\n  for i=1:length(f)\n    Test0(i) = norm(Sparam_w(:,:,i));\n    Test1(i) = norm(Hfit(:,:,i));\n    Test2(i) = norm(H_passive(:,:,i));\n  end\n  figure;\n  plot (wavelength,Test0,'LineWidth',2); hold all;\n  plot (wavelength,Test1,'--','LineWidth',2)\n  plot (wavelength,Test2,'LineWidth',4)\n  plot(wavelength,ones(length(f),1),'--','LineWidth',3);\n  labels={}; labels{1} = 'FDTD S-Parameters'; labels{2} = 'Rational Fit'; labels{3} = 'Passivity-enforced Fit'; labels{4}='Passivity limit';\n  for i=1:length(labels); labels{i}=[labels{i} ' ' char(31)]; end; legend (labels,'Location','Best');\n  axis tight\n  xlabel ('Wavelength [\\mum]');\n  ylabel ('S-Parameter Passivity Test');\n  printfig(file,'passivitytest3');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% export S parameters to INTERCONNECT\nfid = fopen([file '.sparam'],'w');  Nc=4;\nfor row= 1:Nc\n  for col= 1:Nc\n    fprintf(fid,'%s\\n',[ '(''port ' num2str(col) ''',''TE'',1,''port ' num2str(row) ''',1,''transmission'')' ]  );\n    fprintf(fid,'%s\\n',[ '(' num2str(Np) ',3)' ]  );\n    dum2=squeeze(H_passive(row,col,:));\n    mag = abs(dum2);\n    phase = unwrap (angle(dum2)); % figure; plot (wavelength, phase);\n    for i=1:Np\n      fprintf(fid,'%g\t%g\t%g\\n', f(i)*1e14, mag(i), phase(i));\n    end\n  end\nend\nfclose(fid);\n\n\nfunction printfig (file, b)\nglobal PRINT_titles;\nPRINT_titles=0;\nFONTSIZE=20;\nset(get(gca,'xlabel'),'FontSize',FONTSIZE);\nset(get(gca,'ylabel'),'FontSize',FONTSIZE);\nset(get(gca,'title'),'FontSize',FONTSIZE-5);\nset(gca,'FontSize',FONTSIZE-2);\nif PRINT_titles==0\n  delete(get(gca,'title'))\nend\n%a=strfind(file,'.'); file(a)=',';\npdf = [file(1:end-4) '_' b '.pdf'];\nprint ('-dpdf','-r300', pdf);\nsystem([ 'pdfcrop ' pdf ' ' pdf ' &' ]);\n% system(['acroread ' pdf '.pdf &']);\n\n\n", "meta": {"author": "lukasc-ubc", "repo": "SiliconPhotonicsDesign", "sha": "44bdd03a5cd384555956e410689f9368361e11d4", "save_path": "github-repos/MATLAB/lukasc-ubc-SiliconPhotonicsDesign", "path": "github-repos/MATLAB/lukasc-ubc-SiliconPhotonicsDesign/SiliconPhotonicsDesign-44bdd03a5cd384555956e410689f9368361e11d4/siliconphotonicsdesign_book_scripts/ch9/Sparam_passivity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5922429915435972}}
{"text": "report_this_filefun(mfilename('fullpath'));\n\nm = [];\nm =0:0.1:max(newt2.Magnitude);\nm2 =min(newt2.Magnitude):0.1:max(newt2.Magnitude);\nm3 = 10.^(-(m2-min(newt2.Magnitude)));\nm3 = m3*newt2.Count;\n\nk = 0:0.1:min(newt2.Magnitude)-0.1;\nm4 = k*8+newt2.Count;\nm = [m4 m3];\nclf\n%plot(0:0.1:max(newt2.Magnitude),log10(m))\n%grid\n%hold on\nnewcat = newt2;\n\nlepo = length(m) -1;\nmm = [newt2.Count m(1:lepo) ];\nbval = mm-m;\nbvalfl = bval(length(bval):-1:1);\nmaxmag = max(newcat.Magnitude);\nmima = min(newcat.Magnitude);\nif mima > 0 ; mima = 0 ; end\n\n% number of mag units\nnmagu = (maxmag*10)+1;\n\nbvalsum = zeros(1,nmagu);\nbvalsum3 = zeros(1,nmagu);\n\nbvalsum = m;\nbvalsum3 = m(length(m):-1:1);\nxt3 = (maxmag:-0.1:mima);\n\n\nbackg_be = log10(bvalsum);\nbackg_ab = log10(bvalsum3);\norient tall\nrect = [0.2,  0.3, 0.70, 0.6];           % plot Freq-Mag curves\naxes('position',rect);\n\nsemilogy(xt3,bvalsum3,'-.m')\nhold on\nsemilogy(xt3,bvalsum3,'om')\ndifb = [0 diff(bvalsum3) ];\nsemilogy(xt3,difb,'xg')\nsemilogy(xt3,difb,'g')\ngrid\n\n% Marks the point of maximum curvature\n%\ni = find(difb == max(difb));\nte = semilogy(xt3(i),difb(i),'xk');\nset(te,'LineWidth',2,'MarkerSize',ms10)\nte = semilogy(xt3(i),bvalsum3(i),'xk');\nset(te,'LineWidth',2,'MarkerSize',ms10)\n\n% Estimate the b-value\n%\ni2 = round(i/3);\nte = semilogy(xt3(i2),difb(i2),'xk');\nset(te,'LineWidth',2,'MarkerSize',ms10)\nte = semilogy(xt3(i2),bvalsum3(i2),'xk');\nset(te,'LineWidth',2,'MarkerSize',ms10)\n\nxlabel('Magnitude','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\nylabel('Cumulative Number','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\nset(gca,'Color',[1 1 0.6])\nset(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...\n    'FontWeight','bold','LineWidth',1.5,...\n    'Box','on')\n\n\npar2 = 0.1 * max(bvalsum3);\npar3 = 0.12 * max(bvalsum3);\nM1b = [];\nM1b = [xt3(i) bvalsum3(i)];\ntt3=num2str(fix(100*M1b(1))/100);\ntext( M1b(1),M1b(2),['|: M1=',tt3] )\n\nM2b = [];\nM2b =  [xt3(i2) bvalsum3(i2)];\ntt4=num2str(fix(100*M2b(1))/100);\ntext( M2b(1),M2b(2),['|: M2=',tt4] )\n\nll = xt3 > M1b(1) & xt3 < M2b(1);\nx = xt3(ll);\n\nl = newcat.Magnitude > M1b(1) & newcat.Magnitude < M2b(1);\nme = 0.4343/(sum(bval.*xt3)/(sum(bval))-M1b(1));\nmer = 1.96*me/(sqrt(length(newcat(l,6))));\n\n\nso = log10(bval(10*M1b(1)+2)) - log10(bval(10*M2b(1)));\nme= so/( M2b(1)-0.2- M1b(1));\n\npause(0.1)\n\ny = backg_ab(ll);\n[p,s] = polyfit(x,y,1);                   % fit a line to background\nf = polyval(p,x);\nf = 10.^f;\nhold on\nttm= semilogy(x,f,'b');                         % plot linear fit to backg\nset(ttm,'LineWidth',2)\nr = corrcoef(x,y);\nr = r(1,2);\nstd_backg = std(y - polyval(p,x));      % standard deviation of fit\n\np=-p(1,1);\np=fix(100*p)/100;\nstd_backg=fix(100*std_backg)/100;\ntt2=num2str(std_backg);\ntt1=num2str(p);\n\nn = length(x)+3;\nl = b(:,6) > M1b(1) & b(:,6) <= M2b(1);\nles = (mean(b(l,6)) - (M1b(1)+0.05))/0.1;\n\nmysofu = @(x)sofu(x,n,les);\nso = fzero(mysofu,1.0);\nme2 = log(so)/(-2.3026*0.1)\n\n\nrect=[0 0 1 1];\nh2=axes('position',rect);\nset(h2,'visible','off');\n\ntxt1=text(.16, .18,['B-Value(L2): ',tt1,'  B(eff): ',num2str(me), '  B(mean2)= ',num2str(me2)]);\nset(txt1,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\ntxt1=text(.16, .1,['Standard Deviation: ',tt2]);\nset(txt1,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\nset(gcf,'visible','on');\nzmap_message_center.set_info('  ','Done')\ndone\n\n\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/makesyn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6859494421679928, "lm_q1q2_score": 0.5922429884117046}}
{"text": "function [G11, G12, G21, G22] = d2Sbus_dV2(Ybus, V, lam, vcart)\n%D2SBUS_DV2   Computes 2nd derivatives of power injection w.r.t. voltage.\n%\n%   The derivatives can be take with respect to polar or cartesian coordinates\n%   of voltage, depending on the 4th argument.\n%\n%   [GAA, GAV, GVA, GVV] = D2SBUS_DV2(YBUS, V, LAM)\n%   [GAA, GAV, GVA, GVV] = D2SBUS_DV2(YBUS, V, LAM, 0)\n%\n%   Returns 4 matrices containing the partial derivatives w.r.t. voltage angle\n%   and magnitude of the product of a vector LAM with the 1st partial\n%   derivatives of the complex bus power injections.\n%\n%   [GRR, GIR, GIR, GII] = D2SBUS_DV2(YBUS, V, LAM, 1)\n%\n%   Returns 4 matrices containing the partial derivatives w.r.t. real and\n%   imaginary parts of voltage of the product of a vector LAM with the 1st\n%   partial derivatives of the complex bus power injections.\n%\n%   Takes sparse bus admittance matrix YBUS, voltage vector V and nb x 1 vector\n%   of multipliers LAM. Output matrices are sparse.\n%\n%   Examples:\n%       [Ybus, Yf, Yt] = makeYbus(baseMVA, bus, branch);\n%       [Gaa, Gav, Gva, Gvv] = d2Sbus_dV2(Ybus, V, lam);\n%\n%       Here the output matrices correspond to:\n%           Gaa = d/dVa (dSbus_dVa.' * lam)\n%           Gav = d/dVm (dSbus_dVa.' * lam)\n%           Gva = d/dVa (dSbus_dVm.' * lam)\n%           Gvv = d/dVm (dSbus_dVm.' * lam)\n%\n%       [Grr, Gri, Gir, Gii] = d2Sbus_dV2(Ybus, V, lam, 1);\n%\n%       Here the output matrices correspond to:\n%           Grr = d/dVr (dSbus_dVr.' * lam)\n%           Gri = d/dVi (dSbus_dVr.' * lam)\n%           Gir = d/dVr (dSbus_dVi.' * lam)\n%           Gii = d/dVi (dSbus_dVi.' * lam)\n%\n%   For more details on the derivations behind the derivative code used\n%   in MATPOWER, see:\n%\n%   [TN2]  R. D. Zimmerman, \"AC Power Flows, Generalized OPF Costs and\n%          their Derivatives using Complex Matrix Notation\", MATPOWER\n%          Technical Note 2, February 2010. [Online]. Available:\n%          https://matpower.org/docs/TN2-OPF-Derivatives.pdf\n%          doi: 10.5281/zenodo.3237866\n%   [TN4]  B. Sereeter and R. D. Zimmerman, \"AC Power Flows and their\n%          Derivatives using Complex Matrix Notation and Cartesian\n%          Coordinate Voltages,\" MATPOWER Technical Note 4, April 2018.\n%          [Online]. Available: https://matpower.org/docs/TN4-OPF-Derivatives-Cartesian.pdf\n%          doi: 10.5281/zenodo.3237909\n\n%   MATPOWER\n%   Copyright (c) 2008-2019, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%   and Baljinnyam Sereeter, Delft University of Technology\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n%% default input args\nif nargin < 4\n    vcart = 0;      %% default to polar coordinates\nend\n\nn = length(V);\n\ndiaglam = sparse(1:n, 1:n, lam, n, n);\nif vcart\n    E = diaglam * conj(Ybus);\n    F = E + E.';\n    G = 1j * (E - E.');\n\n    G11 = F;        %% Grr\n    G21 = G;        %% Gir\n    G12 = G21.';    %% Gri\n    G22 = G11;      %% Gii\nelse\n    Ibus    = Ybus * V;\n    diagV   = sparse(1:n, 1:n, V, n, n);\n\n    A = sparse(1:n, 1:n, lam .* V, n, n);\n    B = Ybus * diagV;\n    C = A * conj(B);\n    D = Ybus' * diagV;\n    E = conj(diagV) * (D * diaglam - sparse(1:n, 1:n, D*lam, n, n));\n    F = C - A * sparse(1:n, 1:n, conj(Ibus), n, n);\n    G = sparse(1:n, 1:n, ones(n, 1)./abs(V), n, n);\n\n    G11 = E + F;\n    G21 = 1j * G * (E - F);\n    G12 = G21.';\n    G22 = G * (C + C.') * G;\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/d2Sbus_dV2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5921878002765424}}
{"text": " function proj = cuboid_proj(cg, params, varargin)\n%function proj = cuboid_proj(cg, params, varargin)\n%|\n%| Compute set of 2d line-integral projection views of cuboids.\n%| Works for both parallel-beam and cone-beam geometry.\n%|\n%| in\n%|\tcg\t\t\tct_geom()\n%|\tparams [ne 9]\t\tcuboid parameters:\n%|\t\t\t[x_center y_center z_center  x_radius y_radius z_radius\n%|\t\t\t\txy_angle_degrees z_angle_degrees  amplitude]\n%| options\n%|\toversample\t\tover-sampling factor for emulating \"strips\"\n%|\t\t\t\t(to account for finite detector size)\n%|\n%| out\n%|\tproj\t[ns nt na]\tprojection views\n%|\n%| Yong Long, 2008-08-28, University of Michigan, adapted from ellipsoid_proj()\n%| 2013-05-24 Jeff Fessler\n\nif nargin == 1 && streq(cg, 'test'), cuboid_proj_test, return, end\nif nargin < 2, ir_usage, end\n\narg.oversample = 1;\narg = vararg_pair(arg, varargin);\n\nproj = cuboid_proj_do(params, cg.s, cg.t, cg.dt, cg.ar, cg.source_zs, ...\n\t\tcg.dso, cg.dod, cg.dfs, arg.oversample);\n\nend % cuboid_proj()\n\n\n% cuboid_proj_line1()\nfunction [lxmin lxmax] = cuboid_proj_line1(rx, p1, e1)\ntmp = (e1 == 0);\ne1(tmp) = inf;\n% bounds of l corresponding to rect(x/rx)\nlxmin = (-rx/2 - p1) ./ e1;\nlxmax = ( rx/2 - p1) ./ e1;\n% re-arrange the bounds so that lxmin contains the minimum l values\n% and lxmax contains the maximum l values\ntemp = lxmin;\nlxmin = min(lxmin, lxmax);\nlxmax = max(temp, lxmax);\n% exclude points where e1=0 by setting lxmin = -Inf and lxmax = Inf\nlxmin(tmp) = -inf;\nlxmax(tmp) = inf;\nend % cuboid_proj_line1()\n\n\n% cuboid_proj_do()\nfunction proj = cuboid_proj_do(params, ss, tt, dt, ...\n\t\tbeta, ... % [radians]\n\t\tsource_zs, dso, dod, dfs, oversample)\n\nif size(params, 2) ~= 9, error '9 parameters per cuboid', end\n\nif oversample > 1\n\tds = ss(2) - ss(1);\n%\tdt = tt(2) - tt(1); % fails if nt=1 so pass dt instead\n\tif any(abs(diff(ss) / ds - 1) > 1e-6) ...\n\t|| any(abs(diff(tt) / dt - 1) > 1e-6)\n\t\tfail 'uniform spacing required for oversampling'\n\tend\n\tNo = oversample;\n\t% determine new finer sampling positions\n\tss = outer_sum([-(No-1):2:(No-1)]'/(2*No)*ds, ss(:)'); % [No ns]\n\ttt = outer_sum([-(No-1):2:(No-1)]'/(2*No)*dt, tt(:)'); % [No nt]\n\tproj = cuboid_proj_do(params, ss(:), tt(:), dt/No, ...\n\t\tbeta, source_zs, dso, dod, dfs, 1);\n\tproj = downsample3(proj, [No No 1]);\nreturn\nend\n\n\n% determine equivalent parallel-beam projection coordinates, at beta=0\nns = length(ss);\nnt = length(tt);\n[sss ttt] = ndgrid(ss, tt);\n\nif isinf(dso) % parallel beam\n\tuu = sss;\n\tvv = ttt;\n\tazim0 = zeros(size(sss));\n\tpolar = zeros(size(sss));\n\nelseif isinf(dfs) % cone-beam with flat detector\n\t[uu vv azim0 polar] = ir_coord_cb_flat_to_par(sss, ttt, dso, dod);\n\nelseif dfs == 0 % cone-beam with arc detector\n\t[uu vv azim0 polar] = ir_coord_cb_arc_to_par(sss, ttt, dso, dod);\n\nelse\n\tfail 'not done'\nend\n\nclear sss ttt\n\ncpolar = cos(polar);\nspolar = sin(polar);\nproj = zeros(ns, nt, numel(beta));\n\n% loop over cuboids\nfor ip = 1:size(params,1)\n\tpar = params(ip,:);\n\n\tcx = par(1);\trx = par(4);\n\tcy = par(2);\try = par(5);\n\tcz = par(3);\trz = par(6);\n\txang = deg2rad(par(7)); % xy-plane rotation\n\tzang = deg2rad(par(8)); % z-plane rotation\n\tif zang, error 'z rotation not done', end\n\tval = par(9);\n\n\tfor ib = 1:length(beta)\n\t\taz = beta(ib) + azim0;\n\n\t\t% shift property of 3D transform:\n\t\tcz_eff = cz - source_zs(ib); % center relative to source\n\t\tushift = cx * cos(az) + cy * sin(az);\n\t\tvshift = (cx * sin(az) - cy * cos(az)) .* spolar + cz_eff * cpolar;\n\n\t\taz = az - xang;\n\t\tus = uu - ushift;\n\t\tvs = vv - vshift;\n\t\tp1 = us .* cos(az) + vs .* sin(az) .* spolar;\n\t\tp2 = us .* sin(az) - vs .* cos(az) .* spolar;\n\t\tp3 = vs .* cpolar;\n\n\t\te1 = -sin(az) .* cpolar; % x = p1 + l*e1\n\t\te2 = cos(az) .* cpolar; % y = p2 + l*e2\n\t\te3 = spolar; % z = p3 + l*e3\n\n\t\t[lxmin lxmax] = cuboid_proj_line1(rx, p1, e1);\n%\t\tclear p1\n\t\t[lymin lymax] = cuboid_proj_line1(ry, p2, e2);\n%\t\tclear p2\n\t\t[lzmin lzmax] = cuboid_proj_line1(rz, p3, e3);\n%\t\tclear p3\n\n\t\tlmin = max(lxmin, lymin);\n\t\tlmin = max(lmin, lzmin); % lower bound for l\n\n\t\tlmax = min(lxmax, lymax);\n\t\tlmax = min(lmax, lzmax); % upper bound for l\n\n\t\tll = max(lmax - lmin, 0); % intersection only when lmax > lmin\n\n\t\t% cases where e(k) = 0 (rays along axes)\n\n\t\ttmp = e1 == 0; % sin(az) = 0\n\t\tzero_e = (-rx/2 <= us(tmp)) & (us(tmp) <= rx/2);\n\t\tll(tmp) = ll(tmp) .* zero_e;\n\n\t\ttmp = e2 == 0; % cos(az) = 0\n\t\tzero_e = (-ry/2 <= us(tmp)) & (us(tmp) <= ry/2);\n\t\tll(tmp) = ll(tmp) .* zero_e;\n\n\t\ttmp = e3 == 0; % sin(polar) = 0\n\t\tzero_e = (-rz/2 <= vs(tmp)) & (vs(tmp) <= rz/2);\n\t\tll(tmp) = ll(tmp) .* zero_e;\n\nif 0 % old way.  todo cut.  and verify e1 and e2 cases above\n\t\tif (e3 == 0) % sin(polar) = 0; so line along z\n\t\t\tzero_e = (-rz/2 <= vs) & (vs <= rz/2);\n\t\t\tll = ll .* zero_e;\n\t\tend\n\n\t\tif (e1 == 0) % sin(az) = 0;\n\t\t\tzero_e = (-rx/2 <= us) & (us <= rx/2);\n\t\t\tll = ll .* zero_e;\n\t\tend\n\n\t\tif (e2 == 0) % cos(az) = 0;\n\t\t\tzero_e = (-ry/2 <= us) & (us <= ry/2);\n\t\t\tll = ll .* zero_e;\n\t\tend\nend\n\n\t\tproj(:,:,ib) = proj(:,:,ib) + val * ll;\n\t\tclear proj_i\n\tend\nend\n\nend % cuboid_proj_do()\n\n\n% cuboid_proj_test()\n% internal test routine\nfunction cuboid_proj_test\n\nif 1\n\tparams = [30 20 5  200 100 20  45 0 10];\n\tfun_proj = @(cg) cuboid_proj(cg, params, 'oversample', 2); % analytical\n\tfun_im = @(ig) cuboid_im(ig, params, 'oversample', 2); %, 'checkfov', true);\n\n\tir_proj3_compare1(fun_proj, fun_im, 'chat', 1);\nreturn % todo\nend\n\ndown = 30;\ncg = ct_geom('fan', 'ns', round(888/down), 'nt', 64, ...\n\t'na', 18, ...\n\t'ds', 1.0*down, 'dt', 1.1, ...\n\t'down', 1, ... % only downsample s and beta\n\t'dsd', 949, 'dod', 408, 'dfs', 0, ... % 3rd gen CT\n\t'dsd', inf, ... % parallel-beam\n\t'pitch', 0.5, ...\n\t'offset_t', 0.0, ...\n\t'offset_s', 0.25); % quarter detector\n%\t'dsd', 949, 'dod', 408, 'dfs', inf, ... % flat detector\n\nig = image_geom('nx', 512/2^2, 'nz', 64, 'fov', 512, 'dz', 0.625);\n%cg.plot3(ig);\n\nparams = [30 20 5  200 100 20  45 0 10];\nx = cuboid_im(ig, params, 'oversample', 2);\n\nim plc 2 2\nim(1, x), cbar\n\nya = cuboid_proj(cg, params, 'oversample', 2);\nim(2, cg.s, cg.t, ya), cbar\ntitlef('analytical cone-beam projections, dfs=%g', cg.dfs)\nxlabel s, ylabel t\n\n%im clf, im(cg.s, cg.ad, permute(ya, [1 3 2])), cbar\n%xlabel s, ylabel '\\beta'\n\nA = Gcone(cg, ig);\nyd = A * x;\n\nim(3, cg.s, cg.t, yd, 'discrete projections'), cbar\n\nim(4, cg.s, cg.t, ya-yd), cbar\ntitlef('analytical - discrete')\n\nmax_percent_diff(ya, yd)\n\nend % cuboid_proj_test()\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/fbp/cuboid_proj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5921877908145484}}
{"text": "function [is_planar ksubgraph EI]=boyer_myrvold_planarity_test(A,varargin)\n% BOYER_MYRVOLD_PLANARITY_TEST Test a graph for planarity\n%\n% is_planar = boyer_myrvold_planaity_test(A) yields 1 if A is a planar\n% graph or 0 otherwise.  A planar graph can be drawn on the xy plane with\n% no edge crossings.\n%\n% [is_planar K] = ... identifies a Kuratowski subgraph of A when A is not\n% planar.\n% [is_planar K EI] = ... computes the planar embedding edge order in\n% EI.edge_order.  EI.vp gives the starting and ending entries in EI.edge_order\n% for the order of edges from each vertex.  (EI is the compressed\n% sparse row representation of the matrix A with the order of the column\n% indices permuted to the planar graph embedding order.)\n%\n% ... = boyer_myrvold_planaity_test(A,...) takes a set of\n% key-value pairs or an options structure.  See set_matlab_bgl_options\n% for the standard options. \n%   No additional options for this function\n%\n% Example:\n%   G = grid_graph(6,5);\n%   boyer_myrvold_planarity_test(G) % G is planar\n%   K5 = clique_graph(5);\n%   boyer_myrvold_planarity_test(K5) % K5 is not planar\n\n% David Gleich\n% Copyright, Stanford University, 2008\n\n%% History\n%  2007-10-06: Initial coding\n%%\n\n[trans check full2sparse] = get_matlab_bgl_options(varargin{:});\nif full2sparse && ~issparse(A), A = sparse(A); end\n\noptions = struct();\noptions = merge_options(options,varargin{:});\n\nif nargout <= 1\n    is_planar = planar_test_mex(A,0);\nelse \n    if nargout <= 2\n        [is_planar ki kj] = planar_test_mex(A,0);\n    else\n        [is_planar ki kj eip eie] = planar_test_mex(A,0);\n        EI = struct('vp',eip,'edge_order',eie);\n    end\n    if ~isempty(ki)\n        ksubgraph = sparse(ki,kj,1,size(A,1),size(A,2));\n    else\n        ksubgraph = sparse([]);\n    end\n    ksubgraph = ksubgraph|ksubgraph'; % placed here to get the type right    \nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/matlab_bgl/boyer_myrvold_planarity_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5921761562603346}}
{"text": "function [perc,n,which] = misclass(Y,Yest)\n% The rate of misclassifications.\n%\n% '[perc,n,which] = misclass(Y,Yest)'\n%\n%  'Y' contains the real class labels; \n%  'Yest' contains the estimated class labels;\n%  'perc' is the rate of misclassifications (between 0 and 1); \n%  'n' is the number of misclassifications;\n%  'which' contains the indices of the misclassificated instances\n%     (the first column gives the row, the second the column index)\n%\n%\n% see also:\n%    validate, mse, linf, medae, mae\n\n% Copyright (c) 2011,  KULeuven-ESAT-SCD, License & help @ http://www.esat.kuleuven.be/sista/lssvmlab\n\nn = sum(sum(Y~=Yest));\nperc = n/numel(Y);\n[I,J] = find(Y~=Yest);\nwhich = [J I];", "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/misclass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.5921761547577582}}
{"text": "% Author:  Javier Lopez-Calderon\n% 2009\n%\nfunction m = modeone(A)\nif iscell(A)        \n        while any(cellfun('isclass',A,'cell'))\n                A = cat(2,A{:});\n        end\n        \n        n = length(A);\n        h = cellfun(@isnumeric,A);\n        g = nnz(h);\n        \n        if g>0 && g~=n % mixed\n                error('Elements have to be of same class')\n        elseif g>0 && g==n  % only numbers\n                A = cell2mat(A);\n        end\nend\nu = unique_bc2(A);\n[tf, ind] = ismember_bc2(A, u);\nif ind>0\n        k = mode(ind);\n        m = u(k);\nelse\n        m = NaN;\nend\n", "meta": {"author": "ucdavis", "repo": "erplab", "sha": "e4f66f7a512c4dee2f7596982318e44bb1b72644", "save_path": "github-repos/MATLAB/ucdavis-erplab", "path": "github-repos/MATLAB/ucdavis-erplab/erplab-dd2f60aa41b01c866fcec342efafc48323523cc2/functions/modeone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7905303087996142, "lm_q1q2_score": 0.592176145901428}}
{"text": "function P = optimizer(self,x,u)\n%OPTIMIZER  Container for optimization problem\n%\n%   OPT = OPTIMIZER(Problem,x,u) exports an object that contains\n%   precompiled numerical data to be solved for varying arguments \n%   x, returning the optimal value of the expression u.\n%\n%   SEE OPTIMIZER for more info\n%\n%   Example\n%\n%    The following problem creates an LP with varying upper and lower\n%    bounds on the decision variable.\n%\n%    The optimizing argument is obtained by indexing (with {}) the optimizer \n%    object with the point of interest. The argument should be a column\n%    vector (if the argument has a width larger than 1, YALMIP assumes that\n%    the optimal solution should be computed in several points) \n%   \n%     A = randn(10,3);\n%     b = rand(10,1)*19;\n%     c = randn(3,1);\n%\n%     z = sdpvar(3,1);\n%     sdpvar UB LB\n%\n%     Constraints = [A*z < b, LB < z < UB];\n%     Objective = c'*z;\n%     P = optproblem(Constraints,Objective);\n%     % We want the optimal z as a function of [LB;UB]\n%     optZ = optimizer(P,[LB; UB],z);\n%     \n%     % Compute the optimal z when LB=1, UB = 3;\n%     zopt = optZ{[1; 3]}\n%\n%     % Compute two solutions, one for (LB,UB) [1;3] and one for (LB,UB) [2;6]\n%     zopt = optZ{[[1; 3], [2;6]]}\n%\n%     A second output argument can be used to catch infeasibility\n%     [zopt,infeasible] = optZ{[1; 3]}\n\n\nP = optimizer(self.Constraints,self.Objective,self.Options,x,u);", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/@optproblem/optimizer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5920661246317876}}
{"text": "function sub = ind2subv(siz,index)\n%IND2SUBV   Subscript vector from linear index.\n% IND2SUBV(SIZ,IND) returns a vector of the equivalent subscript values \n% corresponding to a single index into an array of size SIZ.\n% If IND is a vector, then the result is a matrix, with subscript vectors\n% as rows.\n\n% Written by Tom Minka\n% Part of Tom Minka's lightspeed package.\n% (c) Microsoft Corporation. All rights reserved.\n\nn = length(siz);\ncum_size = cumprod(siz(:)');\nprev_cum_size = [1 cum_size(1:end-1)];\nindex = index(:) - 1;\nsub = rem(repmat(index,1,n),repmat(cum_size,length(index),1));\nsub = floor(sub ./ repmat(prev_cum_size,length(index),1))+1;\n\n% slow way\n%for dim = n:-1:1\n%  sub(:,dim) = floor(index/cum_size(dim))+1;\n%  index = rem(index,cum_size(dim));\n%end\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/ind2subv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.5920661217304516}}
{"text": "function [goal]=Target_Allocation(goal,quad_init_x,quad_init_y,num,target_num,goal_series,temp_goal,mirror_dis)\nmirror_count=0;\nrow=0;\nline=0;\ntemp_sum_dis=0;\nsum_dis=[0;0;0;0];\nlimited_init_distance=0;%?????????\nquad_init=[quad_init_x quad_init_y];\n\ndistance=[sqrt((quad_init(1,1)-goal(1,1))^2+(quad_init(1,2)-goal(1,2))^2) sqrt((quad_init(1,1)-goal(2,1))^2+(quad_init(1,2)-goal(2,2))^2) sqrt((quad_init(1,1)-goal(3,1))^2+(quad_init(1,2)-goal(3,2))^2) sqrt((quad_init(1,1)-goal(4,1))^2+(quad_init(1,2)-goal(4,2))^2);\n          sqrt((quad_init(2,1)-goal(1,1))^2+(quad_init(2,2)-goal(1,2))^2) sqrt((quad_init(2,1)-goal(2,1))^2+(quad_init(2,2)-goal(2,2))^2) sqrt((quad_init(2,1)-goal(3,1))^2+(quad_init(2,2)-goal(3,2))^2) sqrt((quad_init(2,1)-goal(4,1))^2+(quad_init(2,2)-goal(4,2))^2);\n          sqrt((quad_init(3,1)-goal(1,1))^2+(quad_init(3,2)-goal(1,2))^2) sqrt((quad_init(3,1)-goal(2,1))^2+(quad_init(3,2)-goal(2,2))^2) sqrt((quad_init(3,1)-goal(3,1))^2+(quad_init(3,2)-goal(3,2))^2) sqrt((quad_init(3,1)-goal(4,1))^2+(quad_init(3,2)-goal(4,2))^2);\n          sqrt((quad_init(4,1)-goal(1,1))^2+(quad_init(4,2)-goal(1,2))^2) sqrt((quad_init(4,1)-goal(2,1))^2+(quad_init(4,2)-goal(2,2))^2) sqrt((quad_init(4,1)-goal(3,1))^2+(quad_init(4,2)-goal(3,2))^2) sqrt((quad_init(4,1)-goal(4,1))^2+(quad_init(4,2)-goal(4,2))^2)];\n      \ndistance_list=[sqrt((quad_init(1,1)-goal(1,1))^2+(quad_init(1,2)-goal(1,2))^2) sqrt((quad_init(1,1)-goal(2,1))^2+(quad_init(1,2)-goal(2,2))^2) sqrt((quad_init(1,1)-goal(3,1))^2+(quad_init(1,2)-goal(3,2))^2) sqrt((quad_init(1,1)-goal(4,1))^2+(quad_init(1,2)-goal(4,2))^2) ...,\n              sqrt((quad_init(2,1)-goal(1,1))^2+(quad_init(2,2)-goal(1,2))^2) sqrt((quad_init(2,1)-goal(2,1))^2+(quad_init(2,2)-goal(2,2))^2) sqrt((quad_init(2,1)-goal(3,1))^2+(quad_init(2,2)-goal(3,2))^2) sqrt((quad_init(2,1)-goal(4,1))^2+(quad_init(2,2)-goal(4,2))^2) ...,\n              sqrt((quad_init(3,1)-goal(1,1))^2+(quad_init(3,2)-goal(1,2))^2) sqrt((quad_init(3,1)-goal(2,1))^2+(quad_init(3,2)-goal(2,2))^2) sqrt((quad_init(3,1)-goal(3,1))^2+(quad_init(3,2)-goal(3,2))^2) sqrt((quad_init(3,1)-goal(4,1))^2+(quad_init(3,2)-goal(4,2))^2) ...,\n              sqrt((quad_init(4,1)-goal(1,1))^2+(quad_init(4,2)-goal(1,2))^2) sqrt((quad_init(4,1)-goal(2,1))^2+(quad_init(4,2)-goal(2,2))^2) sqrt((quad_init(4,1)-goal(3,1))^2+(quad_init(4,2)-goal(3,2))^2) sqrt((quad_init(4,1)-goal(4,1))^2+(quad_init(4,2)-goal(4,2))^2);\n              1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4;\n              1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4];\ndistance_sort=distance_list;\nfor k=1:(num*target_num)\n    for j=2:(num*target_num-k+1)\n        if distance_sort(1,j-1)>distance_sort(1,j)\n            Q=distance_sort(:,j-1);\n            distance_sort(:,j-1)=distance_sort(:,j);\n            distance_sort(:,j)=Q;\n        end\n    end\nend\nfor k=1:(num*target_num)\n    if (mirror_dis(distance_sort(2,k),distance_sort(3,k))~=2) && (mirror_count<3)\n        mirror_dis(distance_sort(2,k),:)=2;\n        mirror_dis(:,distance_sort(3,k))=2;\n        mirror_dis(distance_sort(2,k),distance_sort(3,k))=1;\n        mirror_count=mirror_count+1;\n    end\nend\nfor k=1:num\n    for j=1:target_num\n        if (mirror_dis(k,j)==1) || (mirror_dis(k,j)==0)\n            goal_series(k)=j;\n        end\n        if mirror_dis(k,j)==0\n            row=k;\n            line=j;\n        end\n    end\nend\nif distance(row,line)>limited_init_distance\n    for k=1:num%????????\n        sum_dis(k)=(distance(k,line)+distance(row,goal_series(k)))-(distance(k,goal_series(k))+distance(row,line));\n        if temp_sum_dis >= sum_dis(k)\n            temp_sum_dis=sum_dis(k);\n            second_row=k;\n        end\n    end\n    goal_series(row)=goal_series(second_row);\n    goal_series(second_row)=line;\nend\nfor k=1:target_num\n    temp_goal(k,:)=goal(goal_series(k),:);\nend\ngoal=temp_goal;\nend\n", "meta": {"author": "heartxuxuxu", "repo": "Formation_Flight_Sim", "sha": "71c30aacd9d507074f8217dab075d030a4c67feb", "save_path": "github-repos/MATLAB/heartxuxuxu-Formation_Flight_Sim", "path": "github-repos/MATLAB/heartxuxuxu-Formation_Flight_Sim/Formation_Flight_Sim-71c30aacd9d507074f8217dab075d030a4c67feb/Target_Allocation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.591997242804491}}
{"text": "function [MHz] = rpm2MHz(rpm)\n% Convert frequency from revolutions per minute to Megahertz.\n% Chad A. Greene 2012\nMHz = rpm/60/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/rpm2MHz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5919668334679404}}
{"text": "function demo_blockproc_slidingerblets(source,varargin) %RUNASSCRIPT\n%DEMO_BLOCKPROC_SLIDINGERBLETS Basic real-time rolling erblet-spectrogram visualization\n%   Usage: demo_blockproc_slidingerblets('gspi.wav')\n%\n%   For additional help call |demo_blockproc_slidingerblets| without arguments.\n%\n%   This demo shows a simple rolling erblet-spectrogram of whatever is specified in\n%   source. \n\nif demo_blockproc_header(mfilename,nargin)\n   return;\nend\n\n% Control pannel (Java object)\n% Each entry determines one parameter to be changed during the main loop\n% execution.\np = blockpanel({\n               {'GdB','Gain',-20,20,0,21},...\n               {'cMult','C mult',0,80,20,81}\n               });\n            \nfobj = blockfigure();\n\n% Setup blocktream\ntry\n    fs=block(source,varargin{:},'loadind',p);\ncatch\n    % Close the windows if initialization fails\n    blockdone(p,fobj);\n    err = lasterror;\n    error(err.message);\nend\n\n% Buffer length (30 ms)\nbufLen = floor(30e-3*fs);\nzpad = floor(bufLen/2);\n\n% Number of filters\nM = 200;\nF = frame('erbletfb',fs,2*bufLen+2*zpad,'fractionaluniform','M',M);\nFa = blockframeaccel(F,bufLen,'sliced','zpad',zpad);\n\nflag = 1;\ncola = [];\n%Loop until end of the stream (flag) and until panel is opened\nwhile flag && p.flag\n  % Get parameters \n  [gain,mult] = blockpanelget(p,'GdB','cMult');\n  gain = 10^(gain/20);\n  mult = 10^(mult/20);\n\n  % Read block of length bufLen\n  [f,flag] = blockread(bufLen);\n  f = f*gain;\n  % Apply analysis frame\n  c = blockana(Fa, f); \n  % Plot\n  cola = blockplot(fobj,Fa,mult*c(:,1),cola);\n  \n  blockplay(f);\nend\nblockdone(p,fobj,Fa);\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/demos/demo_blockproc_slidingerblets.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5919668325867918}}
{"text": "function sparse_grid_mixed_weight_test ( dim_num, level_max_min, ...\n  level_max_max, rule, alpha, beta, tol )\n\n%*****************************************************************************80\n%\n%% SPARSE_GRID_MIXED_WEIGHT_TEST checks the sum of the quadrature weights.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 March 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer DIM_NUM, the spatial dimension.\n%\n%    Input, integer LEVEL_MAX_MIN, LEVEL_MAX_MAX, the minimum and\n%    maximum values of LEVEL_MAX.\n%\n%    Input, integer RULE(DIM_NUM), the rule in each dimension.\n%     1, \"CC\",  Clenshaw Curtis, Closed Fully Nested rule.\n%     2, \"F2\",  Fejer Type 2, Open Fully Nested rule.\n%     3, \"GP\",  Gauss Patterson, Open Fully Nested rule.\n%     4, \"GL\",  Gauss Legendre, Open Weakly Nested rule.\n%     5, \"GH\",  Gauss Hermite, Open Weakly Nested rule.\n%     6, \"GGH\", Generalized Gauss Hermite, Open Weakly Nested rule.\n%     7, \"LG\",  Gauss Laguerre, Open Non Nested rule.\n%     8, \"GLG\", Generalized Gauss Laguerre, Open Non Nested rule.\n%     9, \"GJ\",  Gauss Jacobi, Open Non Nested rule.\n%    10, \"GW\",  Golub Welsch, (presumed) Open Non Nested rule.\n%    11, \"CC_SE\", Clenshaw Curtis Slow Exponential, Closed Fully Nested rule.\n%    12, \"F2_SE\", Fejer Type 2 Slow Exponential, Closed Fully Nested rule.\n%    13, \"GP_SE\", Gauss Patterson Slow Exponential, Closed Fully Nested rule.\n%    14, \"CC_ME\", Clenshaw Curtis Moderate Exponential, Closed Fully Nested rule.\n%    15, \"F2_ME\", Fejer Type 2 Moderate Exponential, Closed Fully Nested rule.\n%    16, \"GP_ME\", Gauss Patterson Moderate Exponential, Closed Fully Nested rule.\n%    17, \"CCN\", Clenshaw Curtis Nested, Linear, Closed Fully Nested rule.\n%\n%    Input, real ALPHA(DIM_NUM), BETA(DIM_NUM), parameters used for\n%    Generalized Gauss Hermite, Generalized Gauss Laguerre, and Gauss Jacobi rules.\n%\n%    Input, real TOL, the tolerance for point equality.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'SPARSE_GRID_MIXED_WEIGHT_TEST:\\n' );\n  fprintf ( 1, '  Compute the weights of a sparse grid.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Each sparse grid is of spatial dimension DIM_NUM,\\n' );\n  fprintf ( 1, '  and is made up of product grids of levels up to LEVEL_MAX.\\n' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ' Dimension      Rule     Alpha          Beta\\n' );\n  fprintf ( 1, '\\n' );\n\n  for dim = 1 : dim_num\n    fprintf ( 1, '  %8d  %8d', dim, rule(dim) );\n    if ( rule(dim) == 6 | rule(dim) == 8 | rule(dim) == 9 )\n      fprintf ( 1, '  %12e', alpha(dim) );\n    end\n    if ( rule(dim) == 9 )\n      fprintf ( 1, '  %12e', beta(dim) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n\n  weight_sum_exact = 1.0;\n\n  for dim = 1 : dim_num\n\n    if ( rule(dim) == 1 )\n      weight_sum_exact = weight_sum_exact * 2.0;\n    elseif ( rule(dim) == 2 )\n      weight_sum_exact = weight_sum_exact * 2.0;\n    elseif ( rule(dim) == 3 )\n      weight_sum_exact = weight_sum_exact * 2.0;\n    elseif ( rule(dim) == 4 )\n      weight_sum_exact = weight_sum_exact * 2.0;\n    elseif ( rule(dim) == 5 )\n      weight_sum_exact = weight_sum_exact * sqrt ( pi );\n    elseif ( rule(dim) == 6 )\n      weight_sum_exact = weight_sum_exact * gamma ( 0.5 * ( alpha(dim) + 1.0 ) );\n    elseif ( rule(dim) == 7 )\n      weight_sum_exact = weight_sum_exact * 1.0;\n    elseif ( rule(dim) == 8 )\n      weight_sum_exact = weight_sum_exact * gamma ( alpha(dim) + 1.0 );\n    elseif ( rule(dim) == 9 )\n      arg1 = - alpha(dim);\n      arg2 = 1.0;\n      arg3 = beta(dim) + 2.0;\n      arg4 = - 1.0;\n      value1 = r8_hyper_2f1 ( arg1, arg2, arg3, arg4 );\n      arg1 = - beta(dim);\n      arg2 = 1.0;\n      arg3 = alpha(dim) + 2.0;\n      arg4 = - 1.0;\n      value2 = r8_hyper_2f1 ( arg1, arg2, arg3, arg4 );\n      weight_sum_exact = weight_sum_exact * ( ...\n        value1 / ( beta(dim) + 1.0 ) + value2 / ( alpha(dim) + 1.0 ) );\n    elseif ( rule(dim) == 10 )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'SPARSE_GRID_MIXED_WEIGHT_TEST - Fatal error!\\n' );\n      fprintf ( 1, '  Do not know weight sum for rule 10.\\n' );\n      error ( 'SPARSE_GRID_MIXED_WEIGHT_TEST - Fatal error!' );\n    elseif ( rule(dim) == 11 )\n      weight_sum_exact = weight_sum_exact * 2.0;\n    elseif ( rule(dim) == 12 )\n      weight_sum_exact = weight_sum_exact * 2.0;\n    elseif ( rule(dim) == 13 )\n      weight_sum_exact = weight_sum_exact * 2.0;\n    elseif ( rule(dim) == 14 )\n      weight_sum_exact = weight_sum_exact * 2.0;\n    elseif ( rule(dim) == 15 )\n      weight_sum_exact = weight_sum_exact * 2.0;\n    elseif ( rule(dim) == 16 )\n      weight_sum_exact = weight_sum_exact * 2.0;\n    elseif ( rule(dim) == 17 )\n      weight_sum_exact = weight_sum_exact * 2.0;\n    else\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'SPARSE_GRID_MIXED_WEIGHT_TEST - Fatal error!\\n' );\n      fprintf ( 1, '  Unexpected value of RULE = %d\\n', rule(dim) );\n      error ( 'SPARSE_GRID_MIXED_WEIGHT_TEST - Fatal error!' );\n    end\n\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  As a simple test, sum these weights.\\n' );\n  fprintf ( 1, '  They should sum to exactly %f\\n', weight_sum_exact );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '     Level      Weight sum  Expected sum    Difference\\n' );\n  fprintf ( 1, '\\n' );\n\n  for level_max = level_max_min : level_max_max\n\n    point_total_num = sparse_grid_mixed_size_total ( dim_num, level_max, rule );\n\n    point_num  = sparse_grid_mixed_size ( dim_num, level_max, rule, alpha, beta, tol );\n\n    sparse_unique_index = sparse_grid_mixed_unique_index ( ...\n      dim_num, level_max, rule, alpha, beta, tol, point_num, point_total_num );\n\n    sparse_weight = sparse_grid_mixed_weight ( dim_num, level_max, rule, ...\n      alpha, beta, point_num, point_total_num, sparse_unique_index );\n\n    weight_sum = sum ( sparse_weight(1:point_num) );\n\n    weight_sum_error = abs ( weight_sum - weight_sum_exact );\n\n    fprintf ( 1, '  %8d  %14e  %14e  %14e\\n', ...\n      level_max, weight_sum, weight_sum_exact, weight_sum_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/sparse_grid_mixed/sparse_grid_mixed_weight_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5919668266288474}}
{"text": "function REP = REPSelection(PopObj,N,div)\n% Select one of the particles in REP as the global best position for each\n% particle\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    NoP = size(PopObj,1);\n    \n    %% Calculate the grid location of each solution\n    fmax = max(PopObj,[],1);\n    fmin = min(PopObj,[],1);\n    d    = (fmax-fmin)/div;\n    fmin = repmat(fmin,NoP,1);\n    d    = repmat(d,NoP,1);\n    GLoc = floor((PopObj-fmin)./d);\n    GLoc(GLoc>=div) = div - 1;\n    GLoc(isnan(GLoc)) = 0;\n    \n    %% Detect the grid of each solution belongs to\n    [~,~,Site] = unique(GLoc,'rows');\n\n    %% Calculate the crowd degree of each grid\n    CrowdG = hist(Site,1:max(Site));\n    \n    %% Roulette-wheel selection\n    TheGrid = RouletteWheelSelection(N,CrowdG);\n    REP     = zeros(1,N);\n    for i = 1 : length(REP)\n        InGrid = find(Site==TheGrid(i));\n        Temp   = randi(length(InGrid));\n        REP(i) = InGrid(Temp);\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/MOPSO/REPSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5919668233143488}}
{"text": "function ptch = showsurface( voxels )\n%SHOWSURFACE: draw a surface based on some voxels\n%\n%   SHOWSURFACE(VOXELS) tries to render the supplied voxel structure as a\n%   surface using MATLAB's ISOSURFACE command.\n%\n%   PTCH = SHOWSURFACE(VOXELS) also returns handles to the patches\n%   created.\n\n%   Copyright 2005-2009 The MathWorks, Inc.\n%  $Revision: 1.0 $    $Date: 2006/06/30 00:00:00 $\n\n% First grid the data\nux = unique(voxels.XData);\nuy = unique(voxels.YData);\nuz = unique(voxels.ZData);\n\n% Expand the model by one step in each direction\nux = [ux(1)-voxels.Resolution; ux; ux(end)+voxels.Resolution];\nuy = [uy(1)-voxels.Resolution; uy; uy(end)+voxels.Resolution];\nuz = [uz(1)-voxels.Resolution; uz; uz(end)+voxels.Resolution];\n\n% Convert to a grid\n[X,Y,Z] = meshgrid( ux, uy, uz );\n\n% Create an empty voxel grid, then fill only those elements in voxels\nV = zeros( size( X ) );\nN = numel( voxels.XData );\nfor ii=1:N\n    ix = (ux == voxels.XData(ii));\n    iy = (uy == voxels.YData(ii));\n    iz = (uz == voxels.ZData(ii));\n    V(iy,ix,iz) = voxels.Value(ii);\nend\n\n% Now draw it\nptch = patch( isosurface( X, Y, Z, V, 0.5 ) );\nisonormals( X, Y, Z, V, ptch )\nset( ptch, 'FaceColor', 'g', 'EdgeColor', 'none' );\n\nset(gca,'DataAspectRatio',[1 1 1]);\nxlabel('X');\nylabel('Y');\nzlabel('Z');\nview(-140,22)\nlighting( 'gouraud' )\ncamlight( 'right' )\naxis( 'tight' )\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26160-carving-a-dinosaur/SpaceCarving/+spacecarving/showsurface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5919668063216643}}
{"text": "%\n%   colour transfer algorithm based on linear Monge-Kantorovitch solution \n%\n%   IR = colour_transfer_MKL(I_original, I_target, nbiterations);\n%\n%  (c) F. Pitie 2007\n%\n%  see reference:\n%\n%\nfunction IR = colour_transfer_MKL(I0, I1)\n\nif (ndims(I0)~=3)\n    error('pictures must have 3 dimensions');\nend\n\nX0 = reshape(I0, [], size(I0,3));\nX1 = reshape(I1, [], size(I1,3));\n\nA = cov(X0);\nB = cov(X1);\n\nT = MKL(A, B);\n\nmX0 = repmat(mean(X0), [size(X0,1) 1]);\nmX1 = repmat(mean(X1), [size(X0,1) 1]);\n\nXR = (X0-mX0)*T + mX1;\n\nIR = reshape(XR, size(I0));\n\nfunction [T] = MKL(A, B)\nN = size(A,1);\n[Ua,Da2] = eig(A); \nDa2 = diag(Da2); \nDa2(Da2<0) = 0;\nDa = diag(sqrt(Da2 + eps));\nC = Da*Ua'*B*Ua*Da;\n[Uc,Dc2] = eig(C); \nDc2 = diag(Dc2);\nDc2(Dc2<0) = 0;\nDc = diag(sqrt(Dc2 + eps));\nDa_inv = diag(1./(diag(Da)));\nT = Ua*Da_inv*Uc*Dc*Uc'*Da_inv*Ua';\n\n\n\n\n", "meta": {"author": "xjqicuhk", "repo": "SIMS", "sha": "17e90439df06b29319f8bb1d4cce2ef18c5f6a5d", "save_path": "github-repos/MATLAB/xjqicuhk-SIMS", "path": "github-repos/MATLAB/xjqicuhk-SIMS/SIMS-17e90439df06b29319f8bb1d4cce2ef18c5f6a5d/matlab_code/colour-transfer-master/colour_transfer_MKL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5918326937370231}}
{"text": "function [cIX,gIX] = GrowClustersFromSeedsItr(thres_merge,thres_cap,thres_minsize,thres_reg,cIX,gIX,M_0)\ndisp('find ROIs')\n\n% Set params\n\n% may be determined by hist of distances between all cells (in a sample)\n% in correlation distance, i.e. 1 - corr.coeff\n% thres_merge = 0.4;\n% thres_cap = 0.5;\n\n% thres_minsize = 10; % cell number in final clusters\n\n%%\ngIX = SqueezeGroupIX(gIX);\nM = M_0(cIX,:);\nC = FindCentroid_Direct(gIX,M); % kmeans 20x20, 'supervoxels'\nnFoxels = size(C,1);\n\n%% Calculate correlation distance between all cluster-centroids\ntemp = pdist(C,'correlation');\nDist = squareform(temp);\nfor i = 1:nFoxels,\n    Dist(i,i) = NaN;\nend\n\n%% ITERATION:\n% initialize\nROI = [];\nROI(nFoxels).fxlist = []; % not capping\nROI(nFoxels).numcell = [];\nROIcount = 0;\n\n% analogy ~ mask to store new ROI\nBW = zeros(nFoxels,1); \n\n%%\ntic\nwhile true, % loop through all qualified seeds           \n    % look for next seed\n    [~,ix] = min(Dist(:));\n    [I,J] = ind2sub(size(Dist),ix);\n    % and add seed position to mask\n    BW(I) = 1;\n    BW(J) = 1;\n    \n    if Dist(I,J)>(1-thres_merge),\n        break;\n    end\n    \n    while true % grow ROI: expand mask and examine next neighbors\n        IX_in = find(BW);\n        IX_out = find(BW==0);\n\n        % find next closest cluster\n        D = 1-corr(C(IX_in,:)',C(IX_out,:)'); % distance matrix between new core and the original cluster means\n        D2 = min(D,[],1);\n        [a,ix] = min(D2);\n        ix_pretend = IX_out(ix);\n        \n        BW_pretend = BW;\n        BW_pretend(ix_pretend) = 1;\n        \n        % find correlation between potential cluster and new core\n        list = find(BW_pretend);\n        IX = [];\n        for i_gIX = 1:length(list),\n            IX = [IX;find(gIX==list(i_gIX))];\n        end\n        M_core = M(IX,:);\n        [~,newCore] = kmeans(M_core,1,'distance','correlation');                \n        coredist = 1-corr(C(ix_pretend,:)',newCore');\n        \n        if a<(1-thres_merge) && coredist<(1-thres_cap),\n            BW(ix_pretend) = 1;\n        else\n            break; % finished expanding this seed\n        end\n    end\n    \n    % save this ROI if bigger than thres\n    list = find(BW);\n    IX = [];\n    for i_gIX = 1:length(list),\n        IX = [IX;find(gIX==list(i_gIX))]; %#ok<AGROW>\n    end\n    numcell = length(IX);\n    if numcell >= thres_minsize,\n        ROIcount = ROIcount+1;\n        ROI(ROIcount).fxlist = find(BW);\n        ROI(ROIcount).numcell = numcell;\n    end\n    \n    % update/reset\n    Dist(list,:) = NaN;\n    Dist(:,list) = NaN;\n    C(list,:) = NaN;\n    BW = zeros(nFoxels,1);\nend\n\nROI(ROIcount+1:end) = [];\ntoc\n%% Merge accordingly\nfor i = 1:ROIcount,\n    fxlist = ROI(i).fxlist;\n    for j = 2:length(fxlist),\n        gIX(gIX==fxlist(j)) = fxlist(1);\n    end\nend\n[gIX,numU] = SqueezeGroupIX(gIX);\ndisp(numU);\n\n%% Regression with the centroid of each cluster, round 2\n% disp('auto-reg');\n% Reg = FindCentroid_Direct(gIX,M);\n% [cIX,gIX] = AllCentroidRegression_direct(M_0,thres_reg,Reg);\n\n%% size threshold\nU = unique(gIX);\nnumU = length(U);\nfor i=1:numU,\n    if length(find(gIX==U(i)))<thres_minsize,\n        cIX(gIX==U(i)) = [];\n        gIX(gIX==U(i)) = [];\n    end\nend\n[gIX,numU] = SqueezeGroupIX(gIX);\ndisp(numU);\nend\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/script functions/GrowClustersFromSeedsItr2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5918326840662443}}
{"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: Unified Solutions, \n%           Solvability/Observability Analysis and Uncertainty Description \n%           in A Globally Optimal Framework.\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\nfunction R = q2R(q)\nq0 = q(1); q1 = q(2); q2 = q(3); q3 = q(4);\nR = [\n        q0^2 + q1^2 - q2^2 - q3^2,         2*q0*q3 + 2*q1*q2,         2*q1*q3 - 2*q0*q2;\n                2*q1*q2 - 2*q0*q3, q0^2 - q1^2 + q2^2 - q3^2,         2*q0*q1 + 2*q2*q3;\n                2*q0*q2 + 2*q1*q3,         2*q2*q3 - 2*q0*q1, q0^2 - q1^2 - q2^2 + q3^2];\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/utils/q2R.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5918258628079193}}
{"text": "function [u,eqn,info] = fracLapP1P2(node,elem,pde,option)\n%% FRACLAPP1P2 solves fractional Laplacian equation using P1-P2 element\n%\n% [u,eqn,info] = fracLapP1P1(node,elem,pde,option) solves the fractional\n% Laplacian equation\n% \n%  (-\\Delta^^s u = f in \\Omega with u = 0 on \\partial \\Omega.\n\n\n%% Options\nif ~exist('option','var'), option = []; end\nif ~isfield(option,'plotflag'), option.plotflag = 0; end\n\n%% Parameters\nglobal s;\nalpha = 1-2*s;\nif s == 0.5\n    Gamma = 1;\nelse\n    Gamma = 5/(2*s)+0.01;  % a different grading factor\nend\n\n%% Mesh\nN = size(node,1); NT = size(elem,1);\n% My = round(sqrt(NT));\nL = 1+log10(NT)/3; % to control the truncated error, L should increase as logN\nMy = round(L*2*NT^(1/4)); % number of elements in y direction\n% My = round(pde.L*sqrt(sqrt(NT/2)));\ny = gradmap(0,L,Gamma,My);\nNy = length(y); % number of vertices in y-direction  \nNTy = Ny - 1;   % number of elements in y-direction\nNTtotal = NT*NTy;\nNxdof = N;      % dof in x direction is number of vertices\nNydof = (Ny + NTy); % dof in y direction is number of vertices plus elements\nNdof = Nxdof*Nydof;\n\ntic; % start the timing for the assembling\n%% Stiffness matrix and mass matrix in the extended direction\n% quantities in y direction\nhy = diff(y);\na = zeros(NTy,5);\nfor i = 1:5\n    a(:,i) = diff(y.^(alpha+i)/(alpha+i));\nend\ny1 = y(1:end-1);\ny2 = y(2:end);\ny12 = y1 + y2;\ny1y2 = y1.*y2;\nym = y12/2;\n% stiffness matrix in y direction\nAy = zeros(NTy,3,3);\nAy(:,1,1) = a(:,1)./hy.^2;\nAy(:,1,2) = -Ay(:,1,1);           \nAy(:,2,1) = -Ay(:,1,1);           \nAy(:,2,2) = Ay(:,1,1);         \nAy(:,1,3) = 8*(a(:,2) - ym.*a(:,1))./hy.^3;\nAy(:,3,1) = Ay(:,1,3);\nAy(:,2,3) = -Ay(:,1,3);\nAy(:,3,2) = Ay(:,2,3);\nAy(:,3,3) = 64*(a(:,3) - 2*ym.*a(:,2) + ym.^2.*a(:,1))./hy.^4;\n% mass matrix in y direction\nMy = zeros(NTy,3,3);\nMy(:,1,1) = (a(:,3) - 2*y1.*a(:,2) + y1.^2.*a(:,1))./hy.^2;\nMy(:,1,2) = (-a(:,3) + (y1+y2).*a(:,2) - y1.*y2.*a(:,1))./hy.^2;\nMy(:,2,1) = My(:,1,2);\nMy(:,2,2) = (a(:,3) - 2*y2.*a(:,2) + y2.^2.*a(:,1))./hy.^2;\nMy(:,1,3) = 4*(a(:,4) - (y12+y2).*a(:,3) + (y2.*y12 + y1y2).*a(:,2) ...\n             - y2.*y1y2.*a(:,1))./hy.^3;\nMy(:,3,1) = My(:,1,3);\nMy(:,2,3) = 4*(-a(:,4) + (y12+y1).*a(:,3) - (y1.*y12 + y1y2).*a(:,2) ...\n             + y1.*y1y2.*a(:,1))./hy.^3;\nMy(:,3,2) = My(:,2,3);\nMy(:,3,3) = 16*(a(:,5) - 2*y12.*a(:,4) + (y12.^2 + 2*y1y2).*a(:,3)...\n               -2*y12.*y1.*y2.*a(:,2) + y1y2.^2.*a(:,1))./hy.^4;\n\n%% Stiffness matrix and mass matrix in the original direction\n[Dphi,area] = gradbasis(node,elem); \n% Compute a piecewise constant diffusion coefficient\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\nif ~isempty(pde.d) % build the coefficients into the scaled area\n    areaK = K.*area;\nelse\n    areaK = area;\nend\nAt = zeros(NT,3,3);\nMt = zeros(NT,3,3);\nfor i = 1:3\n    for j = 1:3\n        At(:,i,j) = (Dphi(:,1,i).*Dphi(:,1,j) + Dphi(:,2,i).*Dphi(:,2,j)).*areaK;\n        Mt(:,i,j) = areaK*((i==j)+1)/12;\n    end\nend\n\n%% Assemble stiffness matrix\ndofMap = repmat(1:Nxdof,Nydof,1) + repmat((0:Nydof-1)'*Nxdof,1,Nxdof);\nii = zeros(9*9*NTtotal,1); \njj = zeros(9*9*NTtotal,1); \nsA = zeros(9*9*NTtotal,1);\nindex = 0;\nfor m = 1:3\n    for n = 1:3\n        for i = 1:3\n            for j = 1:3\n                if m < 3\n                    ii(index+1:index+NTtotal) = dofMap(m:Ny+m-2,elem(:,i));\n                else % m = 3: middle points of elements in y direction\n                    ii(index+1:index+NTtotal) = dofMap(Ny+1:Nydof,elem(:,i));\n                end\n                if n < 3\n                    jj(index+1:index+NTtotal) = dofMap(n:Ny+n-2,elem(:,j));\n                else % n = 3: middle points of elements in y direction\n                    jj(index+1:index+NTtotal) = dofMap(Ny+1:Nydof,elem(:,j));\n                end                    \n                sA(index+1:index+NTtotal) = kron(At(:,i,j),My(:,m,n)) + ...\n                                            kron(Mt(:,i,j),Ay(:,m,n));\n                index = index + NTtotal;\n            end\n        end\n    end\nend\nA = sparse(ii,jj,sA,Ndof,Ndof);\nclear ii jj sA At Mt Ay My\n\n%% Assemble the right hand side\nb = zeros(Ndof,1);\nu = zeros(Ndof,1);\n\n%% Set up boundary conditions\n% find Dirichlet boundary nodes\nbdNode = findboundary(elem);  % boundary vertices of mesh in x-direction\nlateralbd = dofMap(:,bdNode);\ntopbd = dofMap(Ny,:);\n\n% Modify the matrix to include the Dirichlet boundary condition\nbdidx = zeros(Ndof,1); \nbdidx(lateralbd) = 1;\nbdidx(topbd) = 1;\nTbd = spdiags(bdidx,0,Ndof,Ndof);\nT = spdiags(1-bdidx,0,Ndof,Ndof);\nA = T*A*T + Tbd;\n\n% Compute boundary integral over the original domain\nif ~isfield(option,'fquadorder')\n    option.fquadorder = 4;   \nend\nft = zeros(NT,3);\nds = 2^(1-2*s)*gamma(1-s)/gamma(s);\nif isfield(pde,'f') && ~ischar(pde.f)\n    [lambdaf,weightf] = quadpts(option.fquadorder);\n    phif = lambdaf;                 % linear bases\n    nQuadf = size(lambdaf,1);\n    for p = 1:nQuadf\n        % quadrature points in the x-y coordinate\n        pxy = lambdaf(p,1)*node(elem(:,1),:) ...\n            + lambdaf(p,2)*node(elem(:,2),:) ...\n            + lambdaf(p,3)*node(elem(:,3),:);\n        fp = pde.f(pxy);\n        for i = 1:3\n            ft(:,i) = ft(:,i) + weightf(p)*phif(p,i)*fp;\n        end\n    end\nelseif isfield(pde,'f') && ischar(pde.f)\n    if strcmp(pde.f,'intx') % f is a distribution \n        % compute (intx, d_x phi)\n        [lambdaf,weightf] = quadpts(option.fquadorder);\n        nQuad = size(lambdaf,1);\n        bt = zeros(NT,1);\n        for p = 1:nQuad\n            pxy = lambdaf(p,1)*node(elem(:,1),:) ...\n                + lambdaf(p,2)*node(elem(:,2),:) ...\n                + lambdaf(p,3)*node(elem(:,3),:);\n            bt = bt + weightf(p)*pde.intx(pxy);      \n        end\n%         [Dphi,area] = gradbasis(node,elem);\n        for i = 1:3\n            ft(:,i) = Dphi(:,1,i).*bt; % (intx, d_xphi)\n        end\n    end\nend\nft = ds*ft.*repmat(area,1,3);\nb = b + accumarray(elem(:),ft(:),[Ndof,1]); \n% Neumann edfts are considered as open set. So the corner points should be\n% set as Dirichlet boundary condition!\nb(bdNode) = 0;\nclear ft\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\nfreeDof = find(bdidx==0);\nif isempty(freeDof), 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(freeDof) = A(freeDof,freeDof)\\b(freeDof);\n        residual = norm(b - A*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 = 'VCYCLE';\n        option.freeDof = freeDof;\n        [u,info] = mgfracLapP1P2(A,b,elem,option); \n    case 'amg'\n        option.solver = 'CG';\n        [u(freeDof),info] = amg(A(freeDof,freeDof),b(freeDof),option);                 \nend\n\n%% Compute error using boundary integral\nif isfield(pde,'exactu')\n    err = zeros(NT,1);\n    [lambda,weight] = quadpts(8);\n    phi = lambda;                 % linear bases\n    nQuadf = size(lambda,1);\n    for p = 1:nQuadf\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        fp = pde.f(pxy);\n        uhp = u(elem(:,1))*phi(p,1) + u(elem(:,2))*phi(p,2) + u(elem(:,3))*phi(p,3);\n        up = pde.exactu(pxy);\n        err = err + weight(p)*fp.*(up - uhp);\n%         err = err + weight(p)*fp.*(up - 2*uhp);\n    end\n    err = ds*sum(err.*area);\n%     err = ds*sum(err.*area) + u'*(A*u);\n    err = sqrt(abs(err));\nelse\n    err = 0;\nend\ninfo.errH1 = err;\n\n%% Output information\neqn = struct('A',A,'b',b,'freeDof',freeDof);\ninfo.assembleTime = assembleTime;", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fracLaplacian/fracLapP1P2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5918258628079193}}
{"text": "function  SELVEparam = initSELVE(traindata, SELVEparam)\n            \nSELVEparam.s = 2;   %number of nearest anchors, please tune this parameter on different datasets\nSELVEparam.lambda = 0.1;\nSELVEparam.beta = 0.5;\nSELVEparam.RedDim = 300;  % the left dimensions of original data\nSELVEparam.m = 300;       % the number of landmark\nSELVEparam.sigma = 0;\n\nkmMaxIter = 10;\nkmNumRep = 1;\n[label,anchor] = litekmeans(traindata,SELVEparam.m,'MaxIter',kmMaxIter,'Replicates',kmNumRep);\nclear kmMaxIter kmNumRep;\n\ntemptraindata = zeros(size(traindata,1),size(traindata,2));\ntempanchor = zeros(SELVEparam.m,size(traindata,2));\ntotalnum = 0;\n\nfor i=1:length(unique(label))\n    tempnum = find(label == i);\n    temptraindata(totalnum +1: totalnum + length(tempnum),:) = traindata(tempnum,:);\n    tempanchor(totalnum +1:totalnum + length(tempnum),:) = repmat(anchor(i,:),length(tempnum),1);\n    totalnum = totalnum + length(tempnum);\nend\nGamma = temptraindata - tempanchor;  % ins * fea\nSELVEparam.GtG = Gamma'*Gamma;\nclear temptraindata tempanchor Gamma tempnum totalnum;\n\n%% searching for transformation matrix\nSELVEparam.XtX = traindata'*traindata;\nSELVEparam.anchor = anchor;\nSELVEparam.label = label;", "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/Method-SELVE/initSELVE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5918258557520154}}
{"text": "% [INPUT]\n% p = A vector of floats [0,Inf) of length t representing the prices.\n% r = A vector of floats (-Inf,Inf) of length t representing the logarithmic returns.\n% v = A vector of floats [0,Inf) of length t representing the trading volumes.\n% cp = A vector of floats [0,Inf) of length t representing the market capitalization.\n% bwl = An integer [90,252] representing the dimension of the long bandwidth.\n% bwm = An integer [21,90) representing the dimension of the medium bandwidth.\n% bws = An integer [5,21) representing the dimension of the short bandwidth.\n%\n% [OUTPUT]\n% hhlr = A column vector of floats [0,Inf) of length t representing the Hui-Heubel Liquidity Ratio.\n% tr = A column vector of floats [0,Inf) of length t representing the Turnover Ratio.\n% vr = A column vector of floats [0,Inf) of length t representing the Variance Ratio.\n\nfunction [hhlr,tr,vr] = liquidity_metrics(varargin)\n\n    persistent ip;\n\n    if (isempty(ip))\n        ip = inputParser();\n        ip.addRequired('p',@(x)validateattributes(x,{'double'},{'real' 'finite' 'nonnegative' 'vector' 'nonempty'}));\n        ip.addRequired('r',@(x)validateattributes(x,{'double'},{'real' 'finite' 'vector' 'nonempty'}));\n        ip.addRequired('v',@(x)validateattributes(x,{'double'},{'real' 'finite' 'nonnegative' 'vector' 'nonempty'}));\n        ip.addRequired('cp',@(x)validateattributes(x,{'double'},{'real' 'finite' 'nonnegative' 'vector' 'nonempty'}));\n        ip.addRequired('bwl',@(x)validateattributes(x,{'double'},{'real' 'finite' 'integer' '>=' 90 '<=' 252 'scalar'}));\n        ip.addRequired('bwm',@(x)validateattributes(x,{'double'},{'real' 'finite' 'integer' '>=' 21 '<' 90 'scalar'}));\n        ip.addRequired('bws',@(x)validateattributes(x,{'double'},{'real' 'finite' 'integer' '>=' 5 '<' 21 'scalar'}));\n    end\n\n    ip.parse(varargin{:});\n\n    ipr = ip.Results;\n    [p,r,v,cp,bwl,bwm,bws] = validate_input(ipr.p,ipr.r,ipr.v,ipr.cp,ipr.bwl,ipr.bwm,ipr.bws);\n\n    nargoutchk(3,3);\n\n    [hhlr,tr,vr] = liquidity_metrics_internal(p,r,v,cp,bwl,bwm,bws);\n\nend\n\nfunction [hhlr,tr,vr] = liquidity_metrics_internal(p,r,v,cp,bwl,bwm,bws)\n\n    hhlr = calculate_hhlr(p,v,cp,bwl,bws);\n    tr = calculate_tr(v,cp,bwl);\n    vr = calculate_vr(r,bwl,bwm);\n\nend\n\nfunction hhlr = calculate_hhlr(p,v,cp,bwl,bws)\n\n    tr = v ./ cp;\n    tr(~isfinite(tr)) = 0;\n\n    windows_p = extract_rolling_windows(p,bws);\n    dp = cellfun(@(x)(max(x) - min(x)) / min(x),windows_p);\n\n    alpha = 2 / (bwl + 1);\n\n    hhlr = dp ./ tr;\n    hhlr(~isfinite(hhlr)) = 0;\n    hhlr(1:bws) = mean(hhlr(bws+1:bws*2+1));\n    hhlr = [hhlr(1); filter(alpha,[1 (alpha - 1)],hhlr(2:end),(1 - alpha) * hhlr(1))];\n    hhlr = (hhlr - min(hhlr)) ./ (max(hhlr) - min(hhlr));\n\nend\n\nfunction tr = calculate_tr(v,cp,bwl)\n\n    alpha = 2 / (bwl + 1);\n\n    tr = v ./ cp;\n    tr(~isfinite(tr)) = 0;\n    tr = [tr(1); filter(alpha,[1 (alpha - 1)],tr(2:end),(1 - alpha) * tr(1))];\n    tr = (tr - min(tr)) ./ (max(tr) - min(tr));\n\nend\n\nfunction vr = calculate_vr(r,bwl,bwm)\n\n    alpha = 2 / (bwl + 1);\n    t = bwl / bwm;\n\n    windows_long = extract_rolling_windows(r,bwl);\n    var_long = cellfun(@var,windows_long);\n\n    windows_short = extract_rolling_windows(r,bwm);\n    var_short = cellfun(@var,windows_short);\n\n    vr = var_long ./ (t .* var_short);\n    vr(~isfinite(vr)) = 0;\n    vr(1:bwm) = mean(vr(bwm+1:bwm*2+1));\n    vr = [vr(1); filter(alpha,[1 (alpha - 1)],vr(2:end),(1 - alpha) * vr(1))];\n\nend\n\nfunction [p,r,v,cp,bwl,bwm,bws] = validate_input(p,r,v,cp,bwl,bwm,bws)\n\n    data = {p(:) r(:) v(:) cp(:)};\n\n    l = unique(cellfun(@numel,data));\n\n    if (numel(l) ~= 1)\n        error('The number of elements of ''p'', ''r'' and ''v'' must be equal.');\n    end\n\n    if (l < 5)\n        error('The value of ''p'', ''r'' and ''v'' is invalid. Expected inputs to be vectors containing at least 5 elements.');\n    end\n\n    [p,r,v,cp] = deal(data{:});\n\n    if (bwl < (bwm * 2))\n        error(['The long bandwidth (' num2str(bwl) ') must be at least twice the medium bandwidth (' num2str(bwm) ').']);\n    end\n\n    if (bwm < (bws * 2))\n        error(['The medium bandwidth (' num2str(bwm) ') must be at least twice the short bandwidth (' num2str(bws) ').']);\n    end\n\nend\n", "meta": {"author": "TommasoBelluzzo", "repo": "SystemicRisk", "sha": "f5e9b4823eabab2130974e535d13762c0cb3e4bf", "save_path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk", "path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk/SystemicRisk-f5e9b4823eabab2130974e535d13762c0cb3e4bf/ScriptsModels/liquidity_metrics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.591825848325756}}
{"text": "% \n%   Copyright (C) 2016  Starsky Wong <sununs11@gmail.com>\n% \n%   Note: The SIFT algorithm is patented in the United States and cannot be\n%   used in commercial products without a license from the University of\n%   British Columbia.  For more information, refer to the file LICENSE\n%   that accompanied this distribution.\n\nfunction [ descrs, locs ] = getFeatures( input_img )\n% Function: Get sift features and descriptors\nglobal gauss_pyr;\nglobal dog_pyr;\nglobal init_sigma;\nglobal octvs;\nglobal intvls;\nglobal ddata_array;\nglobal features;\nif(size(input_img,3)==3)\n    input_img = rgb2gray(input_img);\nend\ninput_img = im2double(input_img);\n\n%% Build DoG Pyramid\n% initial sigma\ninit_sigma = 1.6;\n% number of intervals per octave\nintvls = 3;\ns = intvls;\nk = 2^(1/s);\nsigma = ones(1,s+3);\nsigma(1) = init_sigma;\nsigma(2) = init_sigma*sqrt(k*k-1);\nfor i = 3:s+3\n    sigma(i) = sigma(i-1)*k;\nend\n% default cubic method\ninput_img = imresize(input_img,2);\n% assume the original image has a blur of sigma = 0.5\ninput_img = gaussian(input_img,sqrt(init_sigma^2-0.5^2*4));\n% smallest dimension of top level is about 8 pixels\noctvs = floor(log( min(size(input_img)) )/log(2) - 2);\n\n% gaussian pyramid\n[img_height,img_width] =  size(input_img);\ngauss_pyr = cell(octvs,1);\n% set image size\ngimg_size = zeros(octvs,2);\ngimg_size(1,:) = [img_height,img_width];\nfor i = 1:octvs\n    if (i~=1)\n        gimg_size(i,:) = [round(size(gauss_pyr{i-1},1)/2),round(size(gauss_pyr{i-1},2)/2)];\n    end\n    gauss_pyr{i} = zeros( gimg_size(i,1),gimg_size(i,2),s+3 );\nend\nfor i = 1:octvs\n    for j = 1:s+3\n        if (i==1 && j==1)\n            gauss_pyr{i}(:,:,j) = input_img;\n        % downsample for the first image in an octave, from the s+1 image\n        % in previous octave.\n        elseif (j==1)\n            gauss_pyr{i}(:,:,j) = imresize(gauss_pyr{i-1}(:,:,s+1),0.5);\n        else\n            gauss_pyr{i}(:,:,j) = gaussian(gauss_pyr{i}(:,:,j-1),sigma(j));\n        end\n    end\nend\n% dog pyramid\ndog_pyr = cell(octvs,1);\nfor i = 1:octvs\n    dog_pyr{i} = zeros(gimg_size(i,1),gimg_size(i,2),s+2);\n    for j = 1:s+2\n    dog_pyr{i}(:,:,j) = gauss_pyr{i}(:,:,j+1) - gauss_pyr{i}(:,:,j);\n    end\nend\n% for i = 1:size(dog_pyr,1)\n%     for j = 1:size(dog_pyr{i},3)\n%         imwrite(im2bw(im2uint8(dog_pyr{i}(:,:,j)),0),['dog_pyr\\dog_pyr_',num2str(i),num2str(j),'.png']);\n%     end\n% end\n\n%% Accurate Keypoint Localization\n% width of border in which to ignore keypoints\nimg_border = 5;\n% maximum steps of keypoint interpolation\nmax_interp_steps = 5;\n% low threshold on feature contrast\ncontr_thr = 0.04;\n% high threshold on feature ratio of principal curvatures\ncurv_thr = 10;\nprelim_contr_thr = 0.5*contr_thr/intvls;\nddata_array = struct('x',0,'y',0,'octv',0,'intvl',0,'x_hat',[0,0,0],'scl_octv',0);\nddata_index = 1;\nfor i = 1:octvs\n    [height, width] = size(dog_pyr{i}(:,:,1));\n    % find extrema in middle intvls\n    for j = 2:s+1\n        dog_imgs = dog_pyr{i};\n        dog_img = dog_imgs(:,:,j);\n        for x = img_border+1:height-img_border\n            for y = img_border+1:width-img_border\n                % preliminary check on contrast\n                if(abs(dog_img(x,y)) > prelim_contr_thr)\n                    % check 26 neighboring pixels\n                    if(isExtremum(j,x,y))\n                        ddata = interpLocation(dog_imgs,height,width,i,j,x,y,img_border,contr_thr,max_interp_steps);\n                        if(~isempty(ddata))\n                            if(~isEdgeLike(dog_img,ddata.x,ddata.y,curv_thr))\n                                 ddata_array(ddata_index) = ddata;\n                                 ddata_index = ddata_index + 1;\n                            end\n                        end\n                    end\n                end\n            end\n        end\n    end\nend\n\nfunction [ flag ] = isExtremum( intvl, x, y)\n% Function: Find Extrema in 26 neighboring pixels\n    value = dog_imgs(x,y,intvl);\n    block = dog_imgs(x-1:x+1,y-1:y+1,intvl-1:intvl+1);\n    if ( value > 0 && value == max(block(:)) )\n        flag = 1;\n    elseif ( value == min(block(:)) )\n        flag = 1;\n    else\n        flag = 0;\n    end\nend\n\n%% Orientation Assignment\n% number of detected points\nn = size(ddata_array,2);\n% determines gaussian sigma for orientation assignment\nori_sig_factr = 1.5;\n% number of bins in histogram\nori_hist_bins = 36;\n% orientation magnitude relative to max that results in new feature\nori_peak_ratio = 0.8;\n% array of feature\nfeatures = struct('ddata_index',0,'x',0,'y',0,'scl',0,'ori',0,'descr',[]);\nfeat_index = 1;\nfor i = 1:n\n    ddata = ddata_array(i);\n    ori_sigma = ori_sig_factr * ddata.scl_octv;\n    % generate a histogram for the gradient distribution around a keypoint\n    hist = oriHist(gauss_pyr{ddata.octv}(:,:,ddata.intvl),ddata.x,ddata.y,ori_hist_bins,round(3*ori_sigma),ori_sigma);\n    for j = 1:2\n        smoothOriHist(hist,ori_hist_bins);\n    end\n    % generate feature from ddata and orientation hist peak\n    % add orientations greater than or equal to 80% of the largest orientation magnitude\n    feat_index = addOriFeatures(i,feat_index,ddata,hist,ori_hist_bins,ori_peak_ratio);\nend\n\n%% Descriptor Generation\n% number of features\nn = size(features,2);\n% width of 2d array of orientation histograms\ndescr_hist_d = 4;\n% bins per orientation histogram\ndescr_hist_obins = 8;\n% threshold on magnitude of elements of descriptor vector\ndescr_mag_thr = 0.2;\ndescr_length = descr_hist_d*descr_hist_d*descr_hist_obins;\nlocal_features = features;\nlocal_ddata_array = ddata_array;\nlocal_gauss_pyr = gauss_pyr;\nclear features;\nclear ddata_array;\nclear gauss_pyr;\nclear dog_pyr;\nparfor feat_index = 1:n\n    feat = local_features(feat_index);\n    ddata = local_ddata_array(feat.ddata_index);\n    gauss_img = local_gauss_pyr{ddata.octv}(:,:,ddata.intvl);\n% computes the 2D array of orientation histograms that form the feature descriptor\n    hist_width = 3*ddata.scl_octv;\n    radius = round( hist_width * (descr_hist_d + 1) * sqrt(2) / 2 );\n    feat_ori = feat.ori;\n    ddata_x = ddata.x;\n    ddata_y = ddata.y;\n    hist = zeros(1,descr_length);\n    for i = -radius:radius\n        for j = -radius:radius\n            j_rot = j*cos(feat_ori) - i*sin(feat_ori);\n            i_rot = j*sin(feat_ori) + i*cos(feat_ori);\n            r_bin = i_rot/hist_width + descr_hist_d/2 - 0.5;\n            c_bin = j_rot/hist_width + descr_hist_d/2 - 0.5;\n            if (r_bin > -1 && r_bin < descr_hist_d && c_bin > -1 && c_bin < descr_hist_d)\n                mag_ori = calcGrad(gauss_img,ddata_x+i,ddata_y+j);\n                if (mag_ori(1) ~= -1)\n                    ori = mag_ori(2);\n                    ori = ori - feat_ori;\n                    while (ori < 0)\n                        ori = ori + 2*pi;\n                    end\n                    % i think it's theoretically impossible\n                    while (ori >= 2*pi)\n                        ori = ori - 2*pi;\n                        disp('###################what the fuck?###################');\n                    end\n                    o_bin = ori * descr_hist_obins / (2*pi);\n                    w = exp( -(j_rot*j_rot+i_rot*i_rot) / (2*(0.5*descr_hist_d*hist_width)^2) );\n                    hist = interpHistEntry(hist,r_bin,c_bin,o_bin,mag_ori(1)*w,descr_hist_d,descr_hist_obins);\n                end\n            end\n        end\n    end\n    local_features(feat_index) = hist2Descr(feat,hist,descr_mag_thr);\nend\n% sort the descriptors by descending scale order\nfeatures_scl = [local_features.scl];\n[~,features_order] = sort(features_scl,'descend');\n% return descriptors and locations\ndescrs = zeros(n,descr_length);\nlocs = zeros(n,2);\nfor i = 1:n\n    descrs(i,:) = local_features(features_order(i)).descr;\n    locs(i,1) = local_features(features_order(i)).x;\n    locs(i,2) = local_features(features_order(i)).y;\nend\n\nend", "meta": {"author": "sun11", "repo": "sw-sift", "sha": "3bfb1ac676ce95a8d1a74047637293b0bda19cc7", "save_path": "github-repos/MATLAB/sun11-sw-sift", "path": "github-repos/MATLAB/sun11-sw-sift/sw-sift-3bfb1ac676ce95a8d1a74047637293b0bda19cc7/getFeatures.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5918258426069619}}
{"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%==============================================================================\n% This function manages the solution of H * dy = - dJ' for various settings\n%\n%   'backslash',         simply solve dy = H\\rhs;\n%   'mbCG',               matrixBased, plain CG\n%   'mbPCG-SGS',         matrixBased, PCG with Symmetric Gauss Seidel preconditioner\n%   'mbPCG-ICHOL',     matrixBased, PCG with incomplete Cholesky preconditioner\n%   'mbPCG-Jacobi', matrixBased, PCG with Jacobi preconditioner\n%\n%   'MG-elastic',           matrixFree, PCG Multigrid for elastic regularizer\n%   'CG-elastic',       plain CG with H = A as in (1) below\n%   'CG-curvature',          plain CG with H = A as in (1) below\n%   'PCG-elastic',      Jacobi preconditioned with H = A as in (1,) below\n%   'PCG-curvature',      Jacobi preconditioned with H = A as in (1,) below\n%   'PCG-hyperElastic', ???\n%   'CG'                      plain CG with H full or as operator\n%\n% the operator H can be a\n%    - matrix (matrixBased)\n%    - function (coding the action ofH)\n%    - struct where H describes the pieces of a complex H\n%\n%  (1) action of H: distance + regularizer,\n%       H = P'*dr'*d2psi*dr*P + d2S\n%\n%      Hoperator = @(x) ...\n%       H.d2D.P((H.d2D.dr'*H.d2D.d2psi*H.d2D.dr)*H.d2D.P(x)) ...\n%       + H.d2S.d2S(x,H.omega,H.m);\n%\n%  (2) Jacobi (diagonal) preconditing\n%      Ddiag = diag(H.d2D.dr'*H.d2D.d2psi*H.d2D.dr);\n%      D = H.d2D.P(full(Ddiag))  +  H.d2S.diag(H.omega,H.m);\n%      PC = @(x) D.\\x; % Jacobi preconditioner\n%==============================================================================\n\nfunction [dy,solver] = solveLinearSystem(rhs,H,solver,varargin)\n\nif nargin == 0,\n  testSolver\n  help(mfilename);\n  runMinimalExample;\n  dy = 'endOfMinimalExample';\n  return;\nend;\n\nmaxIterCG = 500;\ntolCG     = 1e-1;\n\nfor k=1:2:length(varargin), % overwrites default parameter\n  eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend;\n\nif isempty(solver) && isnumeric(H),\n  warning('no solver specified, try backslash');\n  solver = 'backslash';\nend;\n\nif isa(solver,'function_handle')\n  dy     = solver(rhs,H,maxIterCG,tolCG);\n  return;\nend\n\nif isstruct(H), % matrixFree mode, configure operator\n  Hoperator = @(x) ...\n    H.d2D.P((H.d2D.dr'*H.d2D.d2psi*H.d2D.dr)*H.d2D.P(x)) ...\n    + H.d2S.d2S(x,H.omega,H.m);\nend;\n\n%------------------------------------------------------------------------------\nswitch solver\n  %------------------------------------------------------------------------------\n  \n  % ---------------------------------------------------------------------------\n  % matrix based\n  % ---------------------------------------------------------------------------\n  \n  case 'backslash',\n    dy = H\\rhs;\n    \n  case 'mbCG',\n    [dy,flag,relres,iter] = pcg(H,rhs,tolCG,maxIterCG);\n    \n  case 'mbPCG-SGS',\n    L   = tril(H); % Symmetric Gauss Seidel Preconditioning,\n    D   = diag(H); % L is lower, D is diagonal, U = L'\n    SGS = @(x) L\\(D.*(L'\\x));\n    [dy,flag,relres,iter] = pcg(H,rhs,tolCG,maxIterCG,SGS);\n    \n  case 'mbPCG-ICHOL',\n    %L1   = cholinc(sparse(H),'0');\n    L = ichol(H);\n    [dy,flag,relres,iter] = pcg(H,rhs,tolCG,maxIterCG,L,L');\n    \n  case 'mbPCG-Jacobi',\n    D   = diag(H); % D is diagonal\n    PC = @(x) D.\\x;\n    [dy,flag,relres,iter] = pcg(H,rhs,tolCG,maxIterCG,PC);\n    \n    \n    \n    % ---------------------------------------------------------------------------\n    % matrix free\n    % ---------------------------------------------------------------------------\n    \n    % In all matrix free solvers the approximates Hessian is supplied by function handle.\n    % Note, that the functionals have the common form\n    %\n    %   Jc = D + S (+ P) ==> d_2 Jc = d2D + d2S (+d2P)\n    %\n    % regularization and penalization (S,P) supply a struct stored in H.d2S or H.d2P\n    % which already has a function handle describing the operator.\n    % The  distance term (d2D) needs more care and the approximation to the Hessian\n    % depends on the solver as well. Therefore the objective function does NOT supply\n    % the function handle, but all variables needed to built such.\n    % For multi-grid (available for elastic and curvature), only the diagonal of the distance\n    % term is used\n    % whereas in conjugate gradient (CG, available for elastic, curvature and hyperelastic)\n    % methods we can model also the off-diagonals d2D(x) = (P'*dr'*d2psi*dr*P) * x\n    %\n    % The default solver for a chosen regularizer is parameterized by d2S.solver.\n    % However, one can overload this setting using\n    %    >> MLIR(..., 'solverNPIR','myFavoriteSolver', ... );\n    \n  case {'MG-elastic','MG'}, % multigrid for elastic regularizer\n    dy = MGsolver(rhs,H);\n    \n  case {'CG-elastic','CG-curvature'},\n    if isstruct(H)\n      %       A         = @(x) ...\n      %         H.d2D.P((H.d2D.dr'*H.d2D.d2psi*H.d2D.dr)*H.d2D.P(x)) ...\n      %         + H.d2S.d2S(x,H.omega,H.m);\n      [dy,flag,relres,iter] = pcg(Hoperator,rhs,tolCG,maxIterCG);\n    else\n      [dy,flag,relres,iter] = pcg(H,rhs,tolCG,maxIterCG);\n    end\n    \n  case {'PCG-elastic','PCG-curvature'}\n    \n    % operator\n    %     A         = @(x) ...\n    %       H.d2D.P((H.d2D.dr'*H.d2D.d2psi*H.d2D.dr)*H.d2D.P(x)) ...\n    %       + H.d2S.d2S(x,H.omega,H.m);\n    % preconditioner\n    Ddiag = diag(H.d2D.dr'*H.d2D.d2psi*H.d2D.dr);\n    D = H.d2D.P(full(Ddiag))  +  H.d2S.diag(H.omega,H.m);\n    PC = @(x) D.\\x; % Jacobi preconditioner\n    [dy,flag,relres,iter] = pcg(Hoperator,rhs,tolCG,maxIterCG,PC);\n    \n  case 'CG'\n    if isstruct(H)\n      [dy,flag,relres,iter] = pcg(H.operator,rhs,tolCG,maxIterCG);\n    else\n      [dy,flag,relres,iter] = pcg(H,rhs,tolCG,maxIterCG);\n    end\n    \n  case {'PCG-hyperElastic'}\n    M         = @(x) H.d2D.P((H.d2D.dr'*H.d2D.d2psi*H.d2D.dr)*H.d2D.P(x));\n    Hoperator = @(x) M(x) + H.d2S.d2S(x,H.omega,H.m,H.d2S.yc);\n    Ddiag     = diag(H.d2D.dr'*H.d2D.d2psi*H.d2D.dr);\n    D         = H.d2D.P(full(Ddiag))  +  H.d2S.diag(H.d2S.yc);\n    Preconditioner = @(x) D.\\x; % Jacobi preconditioner\n    [dy,flag,relres,iter] = pcg(Hoperator,rhs,tolCG,maxIterCG,Preconditioner);\n    \n  otherwise,\n    keyboard\n    error(1)\n    \n    %------------------------------------------------------------------------------\nend\n%------------------------------------------------------------------------------\n\nif exist('flag','var')\n  flags = {\n    sprintf('iter=%d>maxIter=%d but relres=%e>relResTol=%s',...\n    iter,maxIterCG,relres,tolCG)\n    'preconditioner is ill-conditioned'\n    'stagnation: x_k=x_{k+1}'\n    'scalars too small/large to continue computation'\n    };\n  switch flag\n    case {1,2,3,4}\n      fprintf('%s // PCG: %s\\n',flags{flag});\n    otherwise\n      fprintf('%s // PCG :iter = %d of %d, relRes= %1.2e, tolCG= %1.2e\\n',...\n        mfilename,iter,maxIterCG,relres,tolCG);\n  end\nend\n\n%------------------------------------------------------------------------------\n\nfunction runMinimalExample\n\n\n%% prepare 3D data\nsetup3DbrainData\nlevel = 4;\nomega = ML{level}.omega;\nm     = ML{level}.m;\n\nviewImage('reset','viewImage','viewImage2D','colormap',bone(256),'axis','off');\nimgModel('reset','imgModel','splineInterMex','regularizer','moments','theta',1e-2);\ndistance('reset','distance','SSD');\ntrafo('reset','trafo','affine3Dsparse');\n\n[T,R] = imgModel('coefficients',ML{level}.T,ML{level}.R,omega,'out',0);\nxc = getCellCenteredGrid(omega,m);\nRc = imgModel(R,omega,xc);\nw0   = trafo('w0');\nbeta = 0; M = []; wRef = [];\n[Jc,para,dJPIRsparse,HPIRsparse] = PIRobjFctn(T,Rc,omega,m,beta,M,wRef,xc,w0);\n\n\n%% prepare 2D data and approximations to Hessian\nsetup2DhandData\n\nviewImage('reset','viewImage','viewImage2D','colormap',bone(256),'axis','off');\nimgModel('reset','imgModel','splineInter','regularizer','moments','theta',1e-2);\ndistance('reset','distance','SSD');\n\nlevel = 4;\nomega = ML{level}.omega;\nm     = ML{level}.m;\n[T,R] = imgModel('coefficients',ML{level}.T,ML{level}.R,omega,'out',0);\n\n% initialize the image model, distance measure and regularizer\nxc    = getCellCenteredGrid(omega,m);\nRc    = imgModel(R,omega,xc);\n\n% setup PIR objective\nw0   = trafo('w0');\nbeta = 1e3;\nM    = diag([4,4,4,4,1,1]);\n\ntrafo('reset','trafo','affine2D');\nw0   = trafo('w0');\nwRef = w0;\n[Jc,para,dJPIR,HPIR] = PIRobjFctn(T,Rc,omega,m,beta,M,wRef,xc,w0);\n\n% setup NPIR objective\nyc   = getStaggeredGrid(omega,m);\nyRef = 0*yc;\n\nregularizer('reset','regularizer','mbElastic','alpha',1e4,'mu',1,'lambda',0);\n[Jc,para,dJmbElas,HmbElas] = NPIRobjFctn(T,Rc,omega,m,yRef,yc);\n\nregularizer('reset','regularizer','mfElastic','alpha',1e4,'mu',1,'lambda',0);\n[Jc,para,dJmfElas,HmfElas] = NPIRobjFctn(T,Rc,omega,m,yRef,yc);\n\nHxElas = @(x) HmfElas.d2D.P((HmfElas.d2D.dr'*HmfElas.d2D.d2psi*HmfElas.d2D.dr)*HmfElas.d2D.P(x)) ...\n  + HmfElas.d2S.d2S(x,HmfElas.omega,HmfElas.m);\n\nyc   = getCellCenteredGrid(omega,m);\nyRef = 0*yc;\n\nregularizer('reset','regularizer','mbCurvature','alpha',1e4);\n[Jc,para,dJmbCurv,HmbCurv] = NPIRobjFctn(T,Rc,omega,m,yRef,yc);\n\nregularizer('reset','regularizer','mfCurvature','alpha',1e4);\n[Jc,para,dJmfCurv,HmfCurv] = NPIRobjFctn(T,Rc,omega,m,yRef,yc);\nHxCurv = @(x) HmfCurv.d2D.P((HmfCurv.d2D.dr'*HmfCurv.d2D.d2psi*HmfCurv.d2D.dr)*HmfCurv.d2D.P(x)) ...\n  + HmfCurv.d2S.d2S(x,HmfCurv.omega,HmfCurv.m);\n\nproblems = {\n  'PIR-backslash'\n  'PIR-sparse'\n  'mbElastic-backslash'\n  'mbElastic-PCG-SGS'\n  'mbElastic-PCG-ICHOL'\n  'mbElastic-PCG-Jacobi'\n  'mbElastic-CG'\n  'mfElastic-MG'\n  'mfElastic-CG'\n  'mfElastic-PCG'\n  'mbCurvature-backslash'\n  'mbCurvature-PCG-SGS'\n  'mbCurvature-PCG-ICHOL'\n  'mbCurvature-PCG-Jacobi'\n  'mbCurvature-CG'\n  'mfCurvature-PCG'\n  'mfCurvature-CG'\n  }\n\nfor j = 1:length(problems)\n  \n  para = {};\n  \n  switch problems{j},\n    \n    case 'PIR-backslash',\n      solver = 'backslash';\n      H = HPIR; b = -dJPIR'; Hx = @(y) H*y;\n      \n    case 'PIR-sparse',\n      solver = 'backslash';\n      H = HPIRsparse; b = -dJPIRsparse'; Hx = @(y) H*y;\n      \n      %     case 2, % PRIR with conensed matrix\n      % % fprintf('test PIR with condensed matrix\\n');\n      % % trafo('reset','trafo','affine2Dsparse');\n      % % [Jc,para,dJ,H] = PIRobjFctn(T,Rc,omega,m,beta,M,wRef,xc,w0)\n      % % dy = solveLinearSystem(-dJ',H,'backslash');\n      % % test2 = norm(H*dy + dJ')\n      \n    case 'mbElastic-backslash'\n      solver = 'backslash';\n      H = HmbElas; b = -dJmbElas'; Hx = @(y) H*y;\n      \n    case 'mbElastic-PCG-SGS',\n      solver = 'mbPCG-SGS';\n      H = HmbElas; b = -dJmbElas'; Hx = @(y) H*y;\n      para = {'tolCG',1e-5};\n      \n    case 'mbElastic-PCG-ICHOL',\n      solver = 'mbPCG-ICHOL';\n      H = HmbElas; b = -dJmbElas'; Hx = @(y) H*y;\n      para = {'tolCG',1e-5};\n      \n    case 'mbElastic-PCG-Jacobi'\n      solver = 'mbPCG-Jacobi';\n      H = HmbElas; b = -dJmbElas'; Hx = @(y) H*y;\n      para = {'tolCG',1e-5};\n      \n    case 'mbElastic-CG'\n      solver = 'mbCG';\n      H = HmbElas; b = -dJmbElas'; Hx = @(y) H*y;\n      para = {'tolCG',1e-5};\n      \n    case 'mfElastic-MG'\n      solver = 'MG-elastic';\n      H = HmfElas; b = -dJmfElas'; Hx = HxElas;\n      \n    case 'mfElastic-CG'\n      solver = 'CG-elastic';\n      H = HmfElas; b = -dJmfElas'; Hx = HxElas;\n      \n    case 'mfElastic-PCG'\n      solver = 'PCG-elastic';\n      H = HmfElas; b = -dJmfElas'; Hx = HxElas;\n      \n    case 'mbCurvature-backslash'\n      solver = 'backslash';\n      H = HmbElas; b = -dJmbElas'; Hx = @(y) H*y;\n      \n    case 'mbCurvature-PCG-SGS',\n      solver = 'mbPCG-SGS';\n      H = HmbElas; b = -dJmbElas'; Hx = @(y) H*y;\n      para = {'tolCG',1e-5};\n      \n    case 'mbCurvature-PCG-ICHOL',\n      solver = 'mbPCG-ICHOL';\n      H = HmbElas; b = -dJmbElas'; Hx = @(y) H*y;\n      para = {'tolCG',1e-5};\n      \n    case 'mbCurvature-PCG-Jacobi'\n      solver = 'mbPCG-Jacobi';\n      H = HmbElas; b = -dJmbElas'; Hx = @(y) H*y;\n      para = {'tolCG',1e-5};\n      \n    case 'mbCurvature-CG'\n      solver = 'mbCG';\n      H = HmbElas; b = -dJmbElas'; Hx = @(y) H*y;\n      para = {'tolCG',1e-5};\n      \n      \n    case 'mfCurvature-PCG'\n      solver = 'PCG-curvature';\n      H = HmfElas; b = -dJmfElas'; Hx = HxElas;\n      \n    case 'mfCurvature-CG'\n      solver = 'CG-curvature';\n      H = HmfElas; b = -dJmfElas'; Hx = HxElas;\n      \n    case 'MG'\n      \n    otherwise,\n      error('1');\n  end;\n  \n  dy = solveLinearSystem(b,H,solver,para{:});\n  test = norm(Hx(dy)-b)/norm(b);\n  fprintf('%-2d of %2d: %-40s test = %s\\n',j,length(problems),...\n    sprintf('test <%s>:',problems{j}),num2str(test));\nend;\n\nreturn;\n%==============================================================================\n\n%   case 'mfCurvature',\n%     Afun     = @(dy) mfAy(dy,H);\n%     [dy,FLAG] = pcg(Afun,rhs,tolCG,maxIterCG);\n%     %\n\n%\n%   if isnumeric(H),\n%\n%   elseif isstruct(H),\n%     if isfield(H,'solver'),\n%       solver = H.solver;\n%     elseif isfield(H,'d2S') && isfield(H.d2S,'solver'),\n%       solver = H.d2S.solver;\n%     else\n%       error('solver has not been defined')\n%     end;\n%   else\n%     keyboard\n%   end;\n%   fprintf('[set solver to <%s> in %s]\\n',solver,mfilename);\n% end;\n% if isempty(solver)\n%   if isstruct(H),\n%   else % no regularizer initialized, assuming PIR\n%     dy = H\\rhs;\n%     return;\n%   end;\n% end;\n%\n% if isa(solver, 'function_handle')\n%     dy = feval(solver, rhs, H, maxIterCG, tolCG);\n%     return\n% end\n\n%\n%     %     case {'Joint-CG-hyperElastic'}\n%     %         Afctn = @(x) H.M(x) + H.d2S.d2S(x,H.omega,H.m,H.d2S.yc);\n%     %         [dy,flag,relres,iter] = pcg(Afctn,rhs,tolCG,maxIterCG);\n%     %     case {'CG-hyperElastic'}\n%     %         M =@(x) H.d2D.P((H.d2D.dr'*H.d2D.d2psi*H.d2D.dr)*H.d2D.P(x));\n%     %         Afctn = @(x) M(x) + H.d2S.d2S(x,H.omega,H.m,H.d2S.yc);\n%     %         [dy,flag,relres,iter] = pcg(Afctn,rhs,tolCG,maxIterCG);\n%     %     otherwise\n%     %         if isnumeric(H)\n%     %             % if H is a matrix, solve the linear system using MATLAB's backslash\n%     %             dy = H\\rhs;\n%     %         else\n%     %             error(solver)\n%     %         end\n%   otherwise,\n%     keyboard\n%     error(1)\n%     %\n%   case {'PCG-hyperElastic'}\n%     M =@(x) H.d2D.P((H.d2D.dr'*H.d2D.d2psi*H.d2D.dr)*H.d2D.P(x));\n%     Afctn = @(x) M(x) + H.d2S.d2S(x,H.omega,H.m,H.d2S.yc);\n%     Ddiag = diag(H.d2D.dr'*H.d2D.d2psi*H.d2D.dr);\n%     D = H.d2D.P(full(Ddiag))  +  H.d2S.diag(H.d2S.yc);\n%     PC = @(x) D.\\x; % Jacobi preconditioner\n%     [dy,flag,relres,iter] = pcg(Afctn,rhs,tolCG,maxIterCG,PC);\n%\n%     %   case {'PCG-elastic','PCG-curvature'}\n%     %     % operator\n%     %     A         = @(x) ...\n%     %       H.d2D.P((H.d2D.dr'*H.d2D.d2psi*H.d2D.dr)*H.d2D.P(x)) ...\n%     %       + H.d2S.d2S(x,H.omega,H.m);\n%     %     % preconditioner\n%     %     Ddiag = diag(H.d2D.dr'*H.d2D.d2psi*H.d2D.dr);\n%     %     D = H.d2D.P(full(Ddiag))  +  H.d2S.diag(H.omega,H.m);\n%     %     PC = @(x) D.\\x; % Jacobi preconditioner\n%     %     [dy,flag,relres,iter] = pcg(A,rhs,tolCG,maxIterCG,PC);\n%\n%\n%     %     case {'Joint-CG-hyperElastic'}\n%     %         Afctn = @(x) H.M(x) + H.d2S.d2S(x,H.omega,H.m,H.d2S.yc);\n%     %         [dy,flag,relres,iter] = pcg(Afctn,rhs,tolCG,maxIterCG);\n%     %     case {'CG-hyperElastic'}\n%     %         M =@(x) H.d2D.P((H.d2D.dr'*H.d2D.d2psi*H.d2D.dr)*H.d2D.P(x));\n%     %         Afctn = @(x) M(x) + H.d2S.d2S(x,H.omega,H.m,H.d2S.yc);\n%     %         [dy,flag,relres,iter] = pcg(Afctn,rhs,tolCG,maxIterCG);\n%     %     otherwise\n%     %         if isnumeric(H)\n%     %             % if H is a matrix, solve the linear system using MATLAB's backslash\n%     %             dy = H\\rhs;\n%     %         else\n%     %             error(solver)\n%     %         end\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/numerics/solveLinearSystem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.591815842035796}}
{"text": "% =========================================================================\n% This code is part of the Matlab-based toolbox \n% LagLDDDM - A Lagrangian Gauss--Newton--Krylov Solver for Mass- and \n%                        Intensity-Preserving Diffeomorphic Image Registration\n% \n% For details and license info see \n% - https://github.com/C4IR/FAIR.m/tree/master/add-ons/LagLDDMM\n%\n% Example illustrating the performance of different preconditioners for\n% the Gauss-Newton system in LDDMM. The example is described in detail in\n% Section 4.2 of the paper:\n%\n% @article{MangRuthotto2017,\n%   Title = {A {L}agrangian {G}auss--{N}ewton--{K}rylov solver for mass- and intensity-preserving diffeomorphic image registration},\n%   Year = {2017},\n%   Journal = {SIAM Journal on Scientific Computing},\n%   Author = {A. Mang, L. Ruthotto},\n% }\n%\n% =========================================================================\nclear all; clc;\nsetup2Ddisc2CData\n\n%% run affine pre-registration\nimgModel('reset','imgModel','splineInterMex','regularizer','moments','theta',.1);\n        trafo('set','trafo','affine2D');\n        distance('set','distance','SSD');\n\nalpha = [6e2 0];\nparametric = 0;\npad  = 0.5;\nnt = 0;\nN    = 3;\nmV     = @(m) ceil(1*m);\nminLevel = 5;\nmaxLevel = 5;\n\n%% run multilevel LDDMM registration\n\n% 1) setup grid for velocities (padded)\nomegaV = omega; omegaV(1:2:end) = omegaV(1:2:end)-pad;  omegaV(2:2:end) = omega(2:2:end)+pad;\n\n% 2) setup regularizer\nregularizer('reset','regularizer','mfDiffusionCC','alpha',alpha,'nt',nt,'HessianShift',1e-2); % stationary velocity\n\nNPIRpara    = optPara('NPIR-GN');\nNPIRpara.maxIter = 40;\nNPIRpara.scheme = @GaussNewtonLDDMM;\n[vc,~,wc,his] = MLLDDMM(ML,'minLevel',minLevel,'maxLevel',maxLevel,...\n    'omegaV',omegaV,'mV',mV,'N',N,'parametric',parametric,'NPIRpara',NPIRpara,'plots',1);\n\n\n%% generate plots to explore conditioning / sparsity\nxc = getNodalGrid(omega,ML{minLevel}.m);\n[T,R] = imgModel('coefficients',ML{minLevel}.T,ML{minLevel}.R,omega);\nRc    = imgModel(R,omega,center(xc,ML{minLevel}.m));\n  \nmV = ML{minLevel}.m;\nfctn = @(vc) LDDMMobjFctn(T,Rc,omega,ML{minLevel}.m,0*vc,center(xc,ML{minLevel}.m),omegaV,mV,N,vc);\n\nclose all\nregularizer('set','regularizer','mbDiffusionCC')\n[Sc,dS,d2Smb] = regularizer(vc,omegaV,mV);\n% get objective function\n[J0,p0,dJ0,Hmb0] = fctn(0*vc);\n[Jc,pc,dJc,Hmbc] = fctn(vc);\n\nregularizer('set','regularizer','mfDiffusionCC')\n[J0,p0,dJ0,Hmf0] = fctn(0*vc);\n[Jc,pc,dJc,Hmfc] = fctn(vc);\n\n%%\nfig = figure(); clf;\nfig.Name =sprintf('%s: Sparsity of Hessian',mfilename);\n\nsubplot(1,2,1)\nspy(Hmb0);\ntitle('H(v0)');\n\nsubplot(1,2,2);\nspy(Hmbc);\ntitle('H(vOpt');\n%% explore PCG convergence at first iteration\nhd = prod((omega(2:2:end)-omega(1:2:end))./ML{minLevel}.m);\nHmb0 = Hmb0 + hd* regularizer('get','HessianShift')* speye(size(Hmb0));\nD   = diag(Hmb0); % D is diagonal\nL   = tril(Hmb0); % Symmetric Gauss Seidel Preconditioning,\n\nPCjac = @(x) D.\\x;\nPCsgs = @(x) full(L\\(D.*(L'\\x)));\nPCnone = @(x) x;\n\n[~,iter0cg,relres0cg,resvec0cg] = spectralPrecondPCG(-dJ0(:), Hmf0, 250, 1e-10,'prec',PCnone);\n[~,iter0jac,relres0jac,resvec0jac] = spectralPrecondPCG(-dJ0(:), Hmf0, 250, 1e-10,'prec',PCjac);\n[~,iter0sgs,relres0sgs,resvec0sgs] = spectralPrecondPCG(-dJ0(:), Hmf0, 250, 1e-10,'prec',PCsgs);\n[~,iter0sp,relres0sp,resvec0sp] = spectralPrecondPCG(-dJ0(:), Hmf0, 250, 1e-10);\n\n%%\nfigConv = figure(); clf\nfigConv.Name = 'PCG convergence';\n\nsubplot(1,2,1);\nsemilogy(resvec0cg/resvec0cg(1));\nhold on;\nsemilogy(resvec0jac/resvec0jac(1));\nsemilogy(resvec0sgs/resvec0sgs(1));\nsemilogy(resvec0sp/resvec0sp(1));\ntitle('first GN iteration');\nax = [0 250 1e-10 10];\naxis(ax)\nlegend('CG','PCG-Jac','PCG-SGS','PCG-Spec','Location','SouthWest')\n\n\n%% explore PCG convergence at final iteration\nhd = prod((omega(2:2:end)-omega(1:2:end))./ML{minLevel}.m);\nHmb0 = Hmb0 + hd* regularizer('get','HessianShift')* speye(size(Hmb0));\nD   = diag(Hmbc); % D is diagonal\nL   = tril(Hmbc); % Symmetric Gauss Seidel Preconditioning,\n\nlinSol = @spectralPrecondPCG;\nPCjac = @(x) D.\\x;\nPCsgs = @(x) full(L\\(D.*(L'\\x)));\nPCnone = @(x) x;\n\n[~,itercg,relrescg,resveccg]    = linSol(-dJc(:), Hmfc, 250, 1e-10,'prec',PCnone);\n[~,iterjac,relresjac,resvecjac] = linSol(-dJc(:), Hmfc, 250, 1e-10,'prec',PCjac);\n[~,itersgs,relressgs,resvecsgs] = linSol(-dJc(:), Hmfc, 250, 1e-10,'prec',PCsgs);\n[~,itersp,relressp,resvecsp]    = linSol(-dJc(:), Hmfc, 250, 1e-10);\n\n%%\nfig = figure(figConv); \nsubplot(1,2,2);\nsemilogy(resveccg/resveccg(1));\nhold on;\nsemilogy(resvecjac/resvecjac(1));\nsemilogy(resvecsgs/resvecsgs(1));\nsemilogy(resvecsp/resvecsp(1));\ntitle('final iteration');\n\nlegend('CG','PCG-Jac','PCG-SGS','PCG-Spec','Location','SouthWest')\naxis(ax)\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/add-ons/LagLDDMM/examples/ELDDMM_Precond_diffusionCC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5918158411275044}}
{"text": "function k = rbfwhiteKernDiagCompute(kern, t)\n\n% RBFWHITEKERNDIAGCOMPUTE Compute diagonal of RBF-WHITE kernel.\n% FORMAT\n% DESC computes the diagonal of the kernel matrix for the RBF-WHITE kernel\n% given a column vector of inputs.\n% ARG kern : the kernel structure for which the kernel matrix is computed.\n% ARG t : input data in the form of a column vector.\n% RETURN k : a vector of the same size as t containing the diagonal of the\n% kernel matrix computed at the given points.\n%\n% SEEALSO : rbfwhiteKernParamInit, kernDiagCompute, kernCreate,\n% rbfwhiteKernCompute\n%\n% COPYRIGHT : David Luengo, 2009\n\n% KERN\n\n\nif size(t, 2) > 1\n  error('Input can only have one column');\nend\n\nif (kern.isStationary == false)\n    k = kern.variance/sqrt(8*pi) * erf(kern.inverseWidth*t/sqrt(2));\nelse\n    k = zeros(size(t));\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/rbfwhiteKernDiagCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5918158270565743}}
{"text": "function res = vect_isPointInMesh(point, v, f, varargin)\n%ISPOINTINMESH Check if a point is inside a 3D mesh.\n%\n%   B = isPointInMesh(PT, V, F)\n%   Check if the point PT (given as a 1-by-3 array) is inside the mesh\n%   defined by the vertices V and the face array F. The result is a\n%   boolean.\n%\n%   If PT is a N-by-3 point array, the result is a N-by-1 array of logical.\n%\n%   Example\n%     [v, f] = torusMesh([50 50 50 30 10 30 45]);\n%     [x, y, z] = meshgrid(5:5:100, 5:5:100, 5:5:100);\n%     res = false(size(x));\n%     res(:) = isPointInMesh([x(:) y(:) z(:)], v, f);\n%     figure; plot3(x(res), y(res), z(res), 'b.'); axis equal;\n%\n%   Algorithm:\n%   The method computes the intersection with a ray starting from the\n%   point(s) and with a random orientation. Some errors are possible if\n%   rays crosses the mesh between two or three faces.\n%\n%   See also\n%     meshes3d, intersectLineMesh3d\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2018-01-26,    using Matlab 9.3.0.713579 (R2017b)\n% Copyright 2018 INRA - Cepia Software Platform.\n\n% choose a random vector\nvect = rand(1, 3);\n\n% initialize array for result\nnp = size(point, 1);\nres = false(np, 1);\n\n% iterate over the various points\nlines = createLine3d(point, vect);\n[~, pos] = vect_intersectLineMesh3d(lines, v, f); \nfor i = 1:np   \n    res(i) = mod(sum(pos(:,:,i) > 0), 2) > 0;\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/meshes3d/vect_isPointInMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5917672830807923}}
{"text": "%% platonic_solid\n% Below is a demonstration of the features of the |platonic_solid| function\n\n%%\nclear; close all; clc;\n\n%%\n% Plot settings\nfontSize=15;\nfaceColor='b';\nfaceAlpha=1;\nedgeColor='k';\nedgeWidth=2;\nmarkerSize=5;\n\n%%\n\nhf=cFigure; % Open figure for plotting\npColor=gjet(5);\nfor q=1:1:5\n    %Defining the faces (F) and vertices (V) of a platonic solid\n    [V,F]=platonic_solid(q,1); %q indicates solid type, r is the radius\n    \n    subplot(2,3,q); hold on;\n    \n    hp=gpatch(F,V,pColor(q,:),'k',faceAlpha,3);\n    patchNormPlot(F,V);\n    \n    axisGeom(gca,fontSize);    \n    camlight('headlight'); lighting flat;\n    axis off;\nend\ndrawnow; \n\n%%\n%\n% <<gibbVerySmall.gif>>\n%\n% _*GIBBON*_\n% <www.gibboncode.org>\n%\n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_platonic_solid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.591767280260312}}
{"text": "function temp_obj_eval = my_compute_precision_recall_fmeasure(u, u0_GT, u0_SKL_GT)\n% 121227: Reza FARRAHI MOGHADDAM and Hossein ZIAEI NAFCHI\n% 090519: Reza FARRAHI MOGHADDAM\n% used in objective_evaluation_core.m\n\n%\n[xm ym] = size(u);\n% figure, imshow(u)\n\n%\nif (numel(u0_GT) == 0)\n    u0_GT = NaN * ones([xm ym]);\nend\n\n%\nif (nargin == 2)\n    % u0_SKL_GT = NaN * ones([xm ym]);\n\tu0_SKL_GT = ~bwmorph(~u0_GT, 'thin', 'inf');\nend\n\n    \n% TP pixels\ntemp_tp = [u == 0] & [u0_GT == 0];\n\n% FP pixels\ntemp_fp = [u == 0] & [u0_GT ~= 0];\n\n% FN pixels\ntemp_fn = [u ~= 0] & [u0_GT == 0];\n\n% TN pixels \ntemp_tn = [u ~= 0] & [u0_GT ~= 0];\n\n% SKL TP / FN pixels\ntemp_skl_tp = [u == 0] & [u0_SKL_GT == 0];\ntemp_skl_fp = [u == 0] & [u0_SKL_GT ~= 0];\ntemp_skl_fn = [u ~= 0] & [u0_SKL_GT == 0];\ntemp_skl_tn = [u ~= 0] & [u0_SKL_GT ~= 0];\n\n% counts\ncount_tp = sum(sum(temp_tp));\ncount_fp = sum(sum(temp_fp));\ncount_fn = sum(sum(temp_fn));\ncount_tn = sum(sum(temp_tn));\ncount_skl_tp = sum(sum(temp_skl_tp));\ncount_skl_fp = sum(sum(temp_skl_fp));\ncount_skl_fn = sum(sum(temp_skl_fn));\ncount_skl_tn = sum(sum(temp_skl_tn));\n\n% precision\ntemp_p = count_tp / (count_fp + count_tp);\n\n% recall\ntemp_r = count_tp / (count_fn + count_tp);\nif (temp_r == 0)\n    temp_r = NaN;\nend\n\n% p-recall\ntemp_pseudo_p = count_skl_tp / (count_skl_fp + count_skl_tp);\ntemp_pseudo_r = count_skl_tp / (count_skl_fn + count_skl_tp);\nif (temp_pseudo_r == 0)\n    temp_pseudo_r = NaN;\nend\n\n% f-measure\ntemp_f = 100 * 2 * (temp_p * temp_r) / (temp_p + temp_r);\n\n% p-f-measure\ntemp_pseudo_f = 100 * 2 * (temp_p * temp_pseudo_r) / (temp_p + temp_pseudo_r);\n\n% sensetivity\ntemp_sens = count_tp / (count_tp + count_fn);\nif (temp_sens == 0)\n    temp_sens = NaN;\nend\n\n% specificity\ntemp_spec = count_tn / (count_tn + count_fp);\nif (temp_spec == 0)\n    temp_spec = NaN;\nend\n\n% BCR: Balanced Classification Rate \ntemp_BCR = 0.5 * (temp_sens + temp_spec);\n\n% AUC: Area Under the Curve\ntemp_AUC = 0.5 * (temp_sens + temp_spec);\n\n% BER: Balanced Error Rate\ntemp_BER = 100 * (1 - temp_BCR);\n\n% S-F-measure: harmonic mean of sensetivity and specificity\ntemp_s_f_measure = 100 * 2 * (temp_sens * temp_spec) / (temp_sens + temp_spec);\n\n% Accuracy: mean of sensetivity and specificity\ntemp_accu = (count_tp + count_tn) / (count_tp + count_tn + count_fp + count_fn);\n\n% gAccuracy: Geometric mean of sensetivity and specificity\ntemp_g_accu = sqrt(temp_sens * temp_spec);\n\n% NRM (Negative Rate Metric) (*10^-2)\nNR_FN = count_fn / (count_fn + count_tp);\nNR_FP = count_fp / (count_fp + count_tn);\ntemp_NRM = (NR_FN + NR_FP) / 2;\n\n% PSNR\nerr=sum(sum(temp_fp | temp_fn)) / (xm * ym);\ntemp_PSNR = 10 * log10( 1 / err);\n\n% DRD: Distance Reciprocal Distortion Metric\nblkSize=8; % even number\nMaskSize=5; % odd number\nu0_GT1 = false(xm + 2, ym + 2);\nu0_GT1(2 : xm + 1, 2 : ym + 1) = u0_GT;\nintim = cumsum(cumsum(u0_GT1, 1), 2);\nNUBN = 0; blkSizeSQR = blkSize ^ 2;\nfor i= 2 : blkSize : (xm - blkSize + 1)\n    for j = 2 : blkSize : (ym - blkSize + 1)\n        blkSum=intim(i + blkSize - 1, j + blkSize - 1) - intim(i - 1, j + blkSize - 1) - intim(i + blkSize - 1, j - 1) + intim(i - 1, j - 1);\n        if blkSum == 0 || blkSum == blkSizeSQR\n        else\n            NUBN = NUBN + 1;\n        end\n    end\nend\n\nwm = zeros(MaskSize, MaskSize);\nic = (MaskSize + 1) / 2; jc = ic; % center coordinate\nfor i = 1 : MaskSize\n    for j = 1 : MaskSize\n        wm(i, j) = 1 / (sqrt((i - ic) .^ 2 + (j - jc) .^ 2));\n    end\nend\nwm(ic, jc) = 0;\nwnm = wm ./ (sum(wm(:))); % Normalized weight matrix\n\nu0_GT_Resized = zeros(xm + ic + 1, ym + jc + 1);\nu0_GT_Resized(ic : xm + ic - 1, jc : ym + jc - 1) = u0_GT;\nu_Resized = zeros(xm + ic + 1, ym + jc + 1);\nu_Resized(ic : xm + ic - 1, jc : ym + jc - 1) = u;\ntemp_fp_Resized = [u_Resized == 0] & [u0_GT_Resized ~= 0];\ntemp_fn_Resized = [u_Resized ~= 0] & [u0_GT_Resized == 0];\nDiff = temp_fp_Resized | temp_fn_Resized;\n[xm2 ym2] = size(Diff);\nSumDRDk = 0;\nfor i = ic : xm2 - ic + 1\n    for j = jc : ym2 - jc + 1\n        if Diff(i, j) == 1\n            Local_Diff = my_xor_infile(u0_GT_Resized(i - ic + 1 : i + ic -1 , j - ic + 1 : j + ic - 1), u_Resized(i, j));\n            DRDk = sum(sum(Local_Diff.* wnm));\n            SumDRDk = SumDRDk + DRDk;\n        end\n    end\nend\ntemp_DRD = SumDRDk / NUBN;\n\n% MPM: Misclassification penalty metric\nContour = bwmorph(~u0_GT, 'remove');\nDist = bwdist(Contour, 'Chessboard');\nD = sum(Dist(:));\nMP_FN = sum(Dist(temp_fn)) / D;\nMP_FP = sum(Dist(temp_fp)) / D;\ntemp_MPM = (MP_FN + MP_FP) / 2;\n\n% output\n%\ntemp_obj_eval.Precision = temp_p;\ntemp_obj_eval.Recall = temp_r;\ntemp_obj_eval.Fmeasure = temp_f;\ntemp_obj_eval.P_Precision = temp_pseudo_p;\ntemp_obj_eval.P_Recall = temp_pseudo_r;\ntemp_obj_eval.P_Fmeasure = temp_pseudo_f;\ntemp_obj_eval.Sensitivity = temp_sens;\ntemp_obj_eval.Specificity = temp_spec;\ntemp_obj_eval.BCR = temp_BCR;\ntemp_obj_eval.AUC = temp_AUC;\ntemp_obj_eval.BER = temp_BER;\ntemp_obj_eval.SFmeasure = temp_s_f_measure;\ntemp_obj_eval.Accuracy = temp_accu;\ntemp_obj_eval.GAccuracy = temp_g_accu;\ntemp_obj_eval.NRM = temp_NRM;\ntemp_obj_eval.PSNR = temp_PSNR;\ntemp_obj_eval.DRD = temp_DRD;\ntemp_obj_eval.MPM = temp_MPM;\n\nend\n\nfunction temp_xor_infile = my_xor_infile(u_infile, u0_GT_infile)\n% Reza\n\ntemp_fp_infile = [u_infile == 0] & [u0_GT_infile ~= 0];\ntemp_fn_infile = [u_infile ~= 0] & [u0_GT_infile == 0];\ntemp_xor_infile = temp_fp_infile | temp_fn_infile; \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/27652-objective-evaluation-of-binarization-methods-for-document-images/objective_evaluation/my_compute_precision_recall_fmeasure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.7217432122827969, "lm_q1q2_score": 0.5917524563440709}}
{"text": "function [V,E,I] = spline_to_poly(P,C,tol)\n  % SPLINE_TO_POLY Evaluate a cubic Bezier spline as a polyline where each\n  % segment corresponds to a locally flat segment of the curve up to given\n  % tolerance\n  % \n  % [V,E] = spline_to_poly(P,C,tol)\n  % \n  % Inputs:\n  %   P  #P by dim list of control point locations\n  %   C  #C by 4 list of indices into P of cubic Bezier curves\n  %   tol  tolerance \n  % Outputs:\n  %   V  #V by dim list of vertex locations\n  %   E  #E by dim list of edge indices into V\n  %   I  #E list of indices into 1:#C\n  %\n\n  % use transpose for amortized concatenation...\n  V = P';\n  E = [];\n  I = [];\n  % consider each cubic\n  for c = 1:size(C,1)\n    Pc = cubic_flat_eval(P(C(c,:),:),tol);\n    J = [C(c,1) size(V,2)+(1:size(Pc,1)-2) C(c,4)];\n    Ec = [J(1:end-1);J(2:end)]';\n    % use transpose for amortized concatenation...\n    E = [E,                    Ec'];\n    V = [V,         Pc(2:end-1,:)'];\n    I = [I;repmat(c,size(Ec,1),1)];\n  end\n  V = V';\n  E = E';\n  [V,~,~,E] = remove_unreferenced(V,E);\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/spline_to_poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5917524514368461}}
{"text": "function [hog2x2_arr, info] = dense_hog2x2(I, HOG2x2param)\n% Adapted from LabelMeToolbox\n% URL: http://labelme.csail.mit.edu/Release3.0/browserTools/php/matlab_toolbox.php\n\ngrid_spacing = HOG2x2param.grid_spacing;\npatch_size = HOG2x2param.patch_size;\nhalf_win = floor(patch_size/2);\n\nI = double(I);\nd = pixelwise_hog31(I,half_win);\nxmax = size(d,1); ymax = size(d,2);\n\ngrid_x = (1:grid_spacing:xmax-half_win);\ngrid_y = (1:grid_spacing:ymax-half_win);\n\nhog2x2_arr = zeros([length(grid_x),length(grid_y),124]);\n\nhog2x2_arr(:,:, 1: 31) = d(grid_x         ,grid_y         ,:);\nhog2x2_arr(:,:,32: 62) = d(grid_x+half_win,grid_y         ,:);\nhog2x2_arr(:,:,63: 93) = d(grid_x         ,grid_y+half_win,:);\nhog2x2_arr(:,:,94:124) = d(grid_x+half_win,grid_y+half_win,:);\n\n[x y] = meshgrid(grid_x, grid_y);\ninfo.y = x(:);\ninfo.x = y(:);\n", "meta": {"author": "adikhosla", "repo": "feature-extraction", "sha": "290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8", "save_path": "github-repos/MATLAB/adikhosla-feature-extraction", "path": "github-repos/MATLAB/adikhosla-feature-extraction/feature-extraction-290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8/features/hog2x2/dense_hog2x2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5917524479749731}}
{"text": "% Fig. 5.2   Feedback Control of Dynamic Systems, 5e \n%             Franklin, Powell, Emami\nclf\nhold off\nn2=1;\nd2=[1 1 0];\nrlocus(n2,d2)\naxis([-2 2 -1.5 1.5])\ntitle('Fig.5.2 Root locus of 1/s(s+1)')\ngrid on\n  z=0:.1:.9;\n wn=.5:.5:2;\n sgrid(z, wn)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig5_02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.591752445084269}}
{"text": "function smallT = marg_table(bigT, bigdom, bigsz, onto, maximize)\n% MARG_TABLE Marginalize a table\n% smallT = marg_table(bigT, bigdom, bigsz, onto, maximize)\n\nif nargin < 5, maximize = 0; end\n\n\nsmallT = myreshape(bigT, bigsz); % make sure it is a multi-dim array\nsum_over = mysetdiff(bigdom, onto);\nndx = find_equiv_posns(sum_over, bigdom);\nif maximize\n  for i=1:length(ndx)\n    smallT = max(smallT, [], ndx(i));\n  end\nelse\n  for i=1:length(ndx)\n    smallT = sum(smallT, ndx(i));\n  end\nend\n\n\nns = zeros(1, max(bigdom));\n%ns(bigdom) = mysize(bigT); % ignores trailing dimensions of size 1\nns(bigdom) = bigsz;\n\nsmallT = squeeze(smallT); % remove all dimensions of size 1\nsmallT = myreshape(smallT, ns(onto)); % put back relevant dims of size 1\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/KPMtools/marg_table.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.591752445084269}}
{"text": "function [x,g,xn,gg] = kmeanhar(d,k,l,e,x0)\n%KMEANS Vector quantisation using K-harmonic means algorithm [X,G,XN,GG]=(D,K,L,E,X0)\n%\n%  Inputs:\n%\n%    D(N,P)  contains N data vectors of dimension P\n%    K       is number of centres required\n%    L       integer portion is max loop count, fractional portion\n%            gives stopping threshold as fractional reduction in performance criterion\n%    E       is exponent in the cost function. Significantly faster if this is an even integer. [default 4]\n%    X0(K,P) are the initial centres (optional)\n%            Alternatively, X0 can be a character determining the initialization method:\n%                'f'    Initialize with K randomly selected data points [default]\n%                'p'    Initialize with centroids and variances of random partitions\n%\n%  Outputs:\n%\n%    X(K,P)  is output row vectors\n%    G       is the final performance criterion value (normalized by N)\n%    XN      nearest centre for each input point\n%    GG(L+1) value of performance criterion before each iteration and at end\n%\n% The k-harmonic means algorithm selects K cluster centres to minimize \n%                           sum_n(K/sum_k((d_n-x_k)^-e))\n% where sum_n is over the N inputs points d_n and sum_k is over the K cluster centres x_k.\n%\n% It is often a good idea to scale the input data so that it has equal variance in each\n% dimension before calling KMEANHAR so that approximately equal weight is given\n% to each dimension in the distance calculation.\n\n%  [1] Bin Zhang, \"Generalized K-Harmonic Means - Boosting in Unsupervised Learning\",\n%      Hewlett-Packartd Labs, Technical Report HPL-2000-137, 2000 [Zhang2000]\n%      http://www.hpl.hp.com/techreports/2000/HPL-2000-137.pdf\n\n%  Bugs:\n%      (1) Could use nested blocking to allow very large data arrays\n%      (2) Could then allow incremental calling with partial data arrays (but messy)\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: kmeanhar.m 713 2011-10-16 14:45:43Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% sort out the input arguments\n\nif nargin<5\n    x0='f';\n    if nargin<4\n        e=[];\n        if nargin<3\n            l=[];\n        end\n    end\nend\nif isempty(e)\n    e=4;  % default value\nend\nif isempty(l)\n    l=50+1e-3; % default value\nend\nsd=5;       % number of times we must be below threshold\n\n\n% split into chunks if there are lots of data points\n\nmemsize=voicebox('memsize');\n[n,p] = size(d);\nnb=min(n,max(1,floor(memsize/(8*p*k))));    % block size for testing data points\nnl=ceil(n/nb);                  % number of blocks\n\n% initialize if X0 argument is not supplied\n\nif ischar(x0)\n    if k<n\n        if any(x0=='p')                  % Initialize using a random partition\n            ix=ceil(rand(1,n)*k);       % allocate to random clusters\n            ix(rnsubset(k,n))=1:k;      % but force at least one point per cluster\n            x=zeros(k,p);\n            for i=1:k\n                x(i,:)=mean(d(ix==i,:),1);\n            end\n        else                                % Forgy initialization: choose k random points [default]\n            x=d(rnsubset(k,n),:);         % sample k centres without replacement\n        end\n    else\n        x=d(mod((1:k)-1,n)+1,:);    % just include all points several times\n    end\nelse\n    x=x0;\nend\neh=e/2;\nth=l-floor(l);\nl=floor(l)+(nargout>1);   % extra loop needed to calculate final performance value\nif l<=0\n    l=100;      % max number of iterations ever\nend\nif th==0\n    th=-1;      % prevent any stopping if l has no fractional part\nend\ngg=zeros(l+1,1);\nim=repmat(1:k,1,nb); im=im(:);\n\n% index arrays for replication\n\nwk=ones(k,1);\nwp=ones(1,p);\n% wn=ones(1,n);\n%\n% % Main calculation loop\n%\n% We have the following relationships to [1] where i and k index\n% the data values and cluster centres respectively:\n%\n%   This program     [Zhang2000]                            Equation  \n%\n%     d(i,:)            x_i                                 input data\n%     x(k,:)            m_k                                 cluster centres\n%     py(k,i)           (d_ik)^2\n%     dm(i)'            d_i,min^2\n%     pr(k,i)           (d_i,min/d_ik)^2\n%     pe(k,i)           (d_i,min/d_ik)^p                    (7.6) \n%     qik(k,i)          q_ik                                (7.2)\n%     qk(k)             q_k                                 (7.3)\n%     qik(k,i)./qk(k)   p_ik                                (7.4)\n%     se(i)'            d_i,min^p * sumk(d_ik^-p)\n%     xf(i)'            d_i,min^-2 / sumk(d_ik^-p)\n%     xg(i)'            d_i,min^-(p+2) / sumk(d_ik^-p)^2\n\n\nss=sd+1;        % one extra loop at the start\ng=0;                % dummy initial value of g\nxn=zeros(n,1);\nfor j=1:l\n\n    g1=g;                           % save old performance\n    x1=x;                           % save old centres\n    % first do partial chunk\n\n    jx=n-(nl-1)*nb;\n    ii=1:jx;\n    kx=repmat(ii,k,1);\n    km=repmat(1:k,1,jx);\n    py=reshape(sum((d(kx(:),:)-x(km(:),:)).^2,2),k,jx);\n    [dm,xn(ii)]=min(py,[],1);                 % min value in each column gives nearest centre\n    dmk=dm(wk,:);                   % expand into a matrix\n    dq=py>dmk;                      % update only these values\n    pr=ones(k,jx);                   % leaving others at 1\n    pr(dq)=dmk(dq)./py(dq);            % ratio of min(py)./py\n    pe=pr.^eh;\n    se=sum(pe,1);\n    xf=dm.^(eh-1)./se;\n    g=xf*dm.';                     % performance criterion (divided by k)\n    xg=xf./se;\n    qik=xg(wk,:).*pe.*pr;           % qik(k,i) is equal to q_ik in [Zhang2000]\n    qk=sum(qik,2);\n    xs=qik*d(ii,:);\n    ix=jx+1;\n    for il=2:nl\n        jx=jx+nb;        % increment upper limit\n        ii=ix:jx;\n        kx=ii(wk,:);\n        py=reshape(sum((d(kx(:),:)-x(im,:)).^2,2),k,nb);\n        [dm,xn(ii)]=min(py,[],1);                 % min value in each column gives nearest centre\n        dmk=dm(wk,:);                   % expand into a matrix\n        dq=py>dmk;                      % update only these values\n        pr=ones(k,nb);                   % leaving others at 1\n        pr(dq)=dmk(dq)./py(dq);            % ratio of min(py)./py\n        pe=pr.^eh;\n        se=sum(pe,1);\n        xf=dm.^(eh-1)./se;\n        g=g+xf*dm.';                     % performance criterion (divided by k)\n        xg=xf./se;\n        qik=xg(wk,:).*pe.*pr;           % qik(k,i) is equal to q_ik in [Zhang2000]\n        qk=qk+sum(qik,2);\n        xs=xs+qik*d(ii,:);\n        ix=jx+1;\n    end\n    gg(j)=g;\n    x=xs./qk(:,wp);\n    if g1-g<=th*g1\n        ss=ss-1;\n        if ~ss break; end  %  stop if improvement < threshold for sd consecutive iterations\n    else\n        ss=sd;\n    end\nend\ngg=gg(1:j)*k/n;                       % scale and trim the performance criterion vector\ng=g(end);\n% gg' % *** DEBUIG ***\nif nargout>1\n    x=x1;                               % go back to the previous x values if G and/or XN value is output\nend\n\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/kmeanhar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933403143929, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5917524433533327}}
{"text": "classdef SMD8 < PROBLEM\n% <multi> <real> <bilevel>\n% Bilevel optimization problems proposed by Sinha, Malo, and Deb\n% maxFElower --- 500 --- Maximum number of lower level function evaluations for each solution\n\n%------------------------------- Reference --------------------------------\n% A. Sinha, P. Malo, K. Deb, Test problem construction for single-objective \n% bilevel optimization, Evolutionary Computation, 2014, 22(3): 439-477.\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(SetAccess = private)\n        maxFElower; % Maximum number of lower level function evaluations for each solution\n        DU;         % Number of decision variables of the upper level\n        DL;         % Number of decision variables of the lower level\n        C;       \t% Number of upper constraints\n        p;          % The length of xu1\n        q;          % The length of xl1\n        r;          % The length of xu2 and xl2\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.maxFElower = obj.ParameterSet(500);\n            obj.M = 2;\n            obj.C = 0;\n            if isempty(obj.D); obj.D = 5; end\n            obj.DU = floor(obj.D/2);\n            obj.DL = obj.D - obj.DU;\n            obj.r  = floor(obj.DU/2);\n            obj.p  = obj.DU - obj.r;\n            obj.q  = obj.DL - obj.r;\n            obj.lower    = -5*ones(1,obj.D);\n            obj.upper    = 10*ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate upper level and lower level objective values\n        function PopObj = CalObj(obj,PopDec)\n            xu1   = PopDec(:,1:obj.p); \n            xu2   = PopDec(:,obj.p+1:obj.p+obj.r); \n            xl1   = PopDec(:,obj.p+obj.r+1:obj.p+obj.r+obj.q); \n            xl2   = PopDec(:,obj.p+obj.r+obj.q+1:end);\n            term2 = sum((xl1(:,2:end)-xl1(:,1:end-1).^2).^2+(xl1(:,1:end-1)-1).^2,2);\n            % Upper level function value\n            PopObj(:,1) = 20 + exp(1) - 20*exp(-0.2*sqrt(1/obj.p*sum(xu1.^2,2))) - exp(1/obj.p*sum(cos(2*pi*xu1),2)) - term2 + sum(xu2.^2,2) - sum((xu2-xl2.^3).^2,2);\n            % Lower level function value\n            PopObj(:,2) = sum(abs(xu1),2) + term2 + sum((xu2-xl2.^3).^2,2);\n        end\n        %% Calculate lower level objective values\n        function llPopulation = EvaluationLower(obj,varargin)\n            PopDec            = obj.CalDec(varargin{1});\n            PopObj            = obj.CalObj(PopDec);\n            PopObj(:,1)       = nan;\n            PopCon            = obj.CalCon(PopDec);\n            PopCon(:,1:obj.C) = nan;\n            llPopulation      = SOLUTION(PopDec,PopObj,PopCon,varargin{2: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/SMD/SMD8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5917524289172422}}
{"text": "function [ SimilarityMatrix ] = similarityNeighbor( x, n, ~)\n%similarityNeighbor Create a link for the n'th neighbour\n\n    sz = size(x,1);\n    SimilarityMatrix = eye(sz);\n\n    i = 1:sz-n;\n    SimilarityMatrix(sub2ind([sz, sz], i+n,i)) = 1;\n    SimilarityMatrix(sub2ind([sz, sz], i,i+n)) = 1;\n    \n    DiagMask = ones(size(x, 1)) - eye(size(x,1));\n    SimilarityMatrix = SimilarityMatrix .* DiagMask;\n    SimilarityMatrix = SimilarityMatrix + eye(size(x, 1));\n    \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/similarityNeighbor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.591747468601755}}
{"text": "function plot_continuous_samples(SAMPLES,Y)\n\n% plot results of MCMC sampler\n% The mean calcium sample, spike sampler raster plot and samples for\n% amplitude, number of spikes, discrete time constants, noise variance, \n% baseline and initial concentration are generated, together with their \n% autocorrelation functions. If the marginalized flag was used, then the \n% posterior pdfs of baseline and initial concentration are plotted.\n\n% Inputs:\n% SAMPLES:  structure with SAMPLES obtained from cont_ca_sampler.m\n% Y:        inpurt fluorescence trace\n\n% Author: Eftychios A. Pnevmatikakis, 2016, Simons Foundation\n\nT = length(Y);\nN = length(SAMPLES.ns);\nshow_gamma = 1;\nP = SAMPLES.params;\nP.f = 1;\ng = P.g(:);\np = min(length(g),2);\nDt = 1/P.f;                                     % length of time bin\nif ~isfield(SAMPLES,'g');\n    show_gamma = 0;\n    SAMPLES.g = ones(N,1)*g';\nend\n\nif p == 1\n    tau_1 = 0;\n    tau_2 = -Dt/log(g);                         % continuous time constant\n    G1 = speye(T);\n    G2 = spdiags(ones(T,1)*[-g,1],[-1:0],T,T);\n    ge = P.g.^((0:T-1)');     \nelseif p == 2\n    gr = roots([1,-g']);\n    p1_continuous = log(min(gr))/Dt; \n    p2_continuous = log(max(gr))/Dt;\n    tau_1 = -1/p1_continuous;                   %tau h - smaller (tau_d * tau_r)/(tau_d + tau_r)\n    tau_2 = -1/p2_continuous;                   %tau decay - larger\n    G1 = spdiags(ones(T,1)*[-min(gr),1],[-1:0],T,T);\n    G2 = spdiags(ones(T,1)*[-max(gr),1],[-1:0],T,T);\n    ge = G2\\[1;zeros(T-1,1)];\nelse\n    error('This order of the AR process is currently not supported');\nend\n\n\nif length(SAMPLES.Cb) == 2\n    marg = 1;       % marginalized sampler\nelse\n    marg = 0;       % full sampler\nend\n\nC_rec = zeros(N,T);\nfor rep = 1:N\n    %trunc_spikes = ceil(SAMPLES.ss{rep}/Dt);\n    tau = SAMPLES.g(rep,:);\n    gr = exp(-1./tau);    \n    ge = max(gr).^(0:T-1)';\n    s_1 =   sparse(ceil(SAMPLES.ss{rep}/Dt),1,exp((SAMPLES.ss{rep} - Dt*ceil(SAMPLES.ss{rep}/Dt))/tau(1)),T,1);  \n    s_2 =   sparse(ceil(SAMPLES.ss{rep}/Dt),1,exp((SAMPLES.ss{rep} - Dt*ceil(SAMPLES.ss{rep}/Dt))/tau(2)),T,1);  \n    if gr(1) == 0\n        G1 = sparse(1:T,1:T,Inf*ones(T,1)); G1sp = zeros(T,1);\n    else\n        G1 = spdiags(ones(T,1)*[-min(gr),1],[-1:0],T,T); G1sp = G1\\s_1(:);\n    end\n    G2 = spdiags(ones(T,1)*[-max(gr),1],[-1:0],T,T);\n    Gs = (-G1sp+ G2\\s_2(:))/diff(gr);\n    if marg\n        %C_rec(rep,:) = SAMPLES.Cb(1) + SAMPLES.Am(rep)*filter(1,[1,-SAMPLES.g(rep,:)],full(s_)+[SAMPLES.Cin(:,1)',zeros(1,T-p)]);\n        C_rec(rep,:) = SAMPLES.Cb(1) + SAMPLES.Am(rep)*Gs + (ge*SAMPLES.Cin(:,1));\n    else\n        %C_rec(rep,:) = SAMPLES.Cb(rep) + SAMPLES.Am(rep)*filter(1,[1,-SAMPLES.g(rep,:)],full(s_)+[SAMPLES.Cin(rep,:),zeros(1,T-p)]);\n        C_rec(rep,:) = SAMPLES.Cb(rep) + SAMPLES.Am(rep)*Gs + (ge*SAMPLES.Cin(rep,:)');\n    end\nend\nNc = 60;\n\nif marg\n    rows = 4;\nelse\n    rows = 5;\nend\n\nfigure;\n    set(gcf, 'PaperUnits', 'inches','Units', 'inches')           \n    set(gcf, 'PaperPositionMode', 'manual')\n    set(gcf, 'PaperPosition',[0,0, 14, 15])\n    set(gcf, 'Position',[2,2, 14, 15])\n    ha(1) = subplot(rows,4,[1:4]);plot(Dt*(1:T),Y); hold all; plot(Dt*(1:T),mean(C_rec,1),'linewidth',2); \n        title('Calcium traces','fontweight','bold','fontsize',14)\n        legend('Raw data','Mean sample');\n    ha(2) = subplot(rows,4,[5:8]); imagesc((1:T)*Dt,1:N,samples_cell2mat(SAMPLES.ss,T)); \n        title('Spike raster plot','fontweight','bold','fontsize',14)\n        linkaxes(ha,'x');\n    subplot(rows,4,4+5); plot(1:N,SAMPLES.ns); title('# of spikes','fontweight','bold','fontsize',14)\n    subplot(rows,4,4+6); plot(-Nc:Nc,xcov(SAMPLES.ns,Nc,'coeff')); set(gca,'XLim',[-Nc,Nc]);\n        title('Autocorrelation','fontweight','bold','fontsize',14)\n    \n    if ~show_gamma\n        subplot(rows,4,4+7); plot(1:N,SAMPLES.ld); title('Firing Rate','fontweight','bold','fontsize',14)\n        subplot(rows,4,4+8); plot(-Nc:Nc,xcov(SAMPLES.ld,Nc,'coeff')); set(gca,'XLim',[-Nc,Nc])\n        title('Autocorrelation','fontweight','bold','fontsize',14)\n    else\n        if gr(1) == 0\n            subplot(rows,4,4+7);  plot(1:N,exp(-1./SAMPLES.g(:,2))); title('Decay Time Constant','fontweight','bold','fontsize',14);\n            subplot(rows,4,4+8);  plot(-Nc:Nc,xcov(exp(-1./SAMPLES.g(:,2)),Nc,'coeff')); title('Autocorrelation','fontweight','bold','fontsize',14);\n            set(gca,'XLim',[-Nc,Nc])\n        else\n            subplot(rows,4,4+7);  plot(1:N,exp(-1./SAMPLES.g)); title('Decay Time Constants','fontweight','bold','fontsize',14);\n            g_cov = xcov(exp(-1./SAMPLES.g),Nc,'coeff');\n            subplot(rows,4,4+8);  plot(-Nc:Nc,g_cov(:,[1,4])); title('Autocorrelation','fontweight','bold','fontsize',14);\n            set(gca,'XLim',[-Nc,Nc])\n        end\n    end\n    \n    subplot(rows,4,4+9); plot(1:N,SAMPLES.Am); title('Spike Amplitude','fontweight','bold','fontsize',14)\n    subplot(rows,4,4+10); plot(-Nc:Nc,xcov(SAMPLES.Am,Nc,'coeff')); set(gca,'XLim',[-Nc,Nc])\n        title('Autocorrelation','fontweight','bold','fontsize',14)\n    if marg\n        xx = SAMPLES.Cb(1) + linspace(-4*SAMPLES.Cb(2),4*SAMPLES.Cb(2));\n        subplot(4,4,15); plot(xx,normpdf(xx,SAMPLES.Cb(1),SAMPLES.Cb(2)));\n            set(gca,'XLim',[xx(1),xx(end)])\n            title('Marg. post. of baseline','fontweight','bold','fontsize',14)\n\n        xx = SAMPLES.Cin(1) + linspace(-4*SAMPLES.Cin(2),4*SAMPLES.Cin(2));\n        subplot(4,4,16); plot(xx,normpdf(xx,SAMPLES.Cin(1),SAMPLES.Cin(2)));\n            set(gca,'XLim',[xx(1),xx(end)])\n            title('Marg. post. of initial con','fontweight','bold','fontsize',14)\n    else\n        subplot(5,4,4+11); plot(1:N,SAMPLES.Cb); title('Baseline','fontweight','bold','fontsize',14)\n        subplot(5,4,4+12); plot(-Nc:Nc,xcov(SAMPLES.Cb,Nc,'coeff')); set(gca,'XLim',[-Nc,Nc])\n            title('Autocorrelation','fontweight','bold','fontsize',14)\n        subplot(5,4,4+13); plot(1:N,SAMPLES.Cin); title('Initial Concentration','fontweight','bold','fontsize',14)\n        xcov_Cin = xcov(SAMPLES.Cin,Nc,'coeff');\n        subplot(5,4,4+14); plot(-Nc:Nc,xcov_Cin); set(gca,'XLim',[-Nc,Nc])\n            title('Autocorrelation','fontweight','bold','fontsize',14)\n        subplot(5,4,4+15); plot(1:N,SAMPLES.sn2); title('Noise variance','fontweight','bold','fontsize',14)\n        subplot(5,4,4+16); plot(-Nc:Nc,xcov(SAMPLES.sn2,Nc,'coeff')); set(gca,'XLim',[-Nc,Nc])\n            title('Autocorrelation','fontweight','bold','fontsize',14)\n    end\n    drawnow;", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/deconvolution/MCMC/plot_continuous_samples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.5917474601983551}}
{"text": "function [dS,f]=mtdspectrumc(data,phi,params)\n% Multi-taper frequency derivative of the spectrum - continuous process\n%\n% Usage:\n%\n% [dS,f]=mtdspectrumc(data,phi,params)\n% Input: \n%   Note that all times can be in arbitrary units. But the units have to be\n%   consistent. So, if E is in secs, win, t have to be in secs, and Fs has to\n%   be Hz. If E is in samples, so are win and t, and Fs=1. In case of spike\n%   times, the units have to be consistent with the units of data as well.\n%       data        (in form samples x channels/trials or a single vector) -- required\n%       phi         (angle for evaluation of derivative) -- required.\n%                       e.g. phi=[0,pi/2] gives the time and frequency derivatives\n%       params: structure with fields tapers, pad, Fs, fpass, trialave\n%       - optional\n%           tapers : precalculated tapers from dpss or in the one of the following\n%                    forms: \n%                   (1) A numeric vector [TW K] where TW is the\n%                       time-bandwidth product and K is the number of\n%                       tapers to be used (less than or equal to\n%                       2TW-1). \n%                   (2) A numeric vector [W T p] where W is the\n%                       bandwidth, T is the duration of the data and p \n%                       is an integer such that 2TW-p tapers are used. In\n%                       this form there is no default i.e. to specify\n%                       the bandwidth, you have to specify T and p as\n%                       well. Note that the units of W and T have to be\n%                       consistent: if W is in Hz, T must be in seconds\n%                       and vice versa. Note that these units must also\n%                       be consistent with the units of params.Fs: W can\n%                       be in Hz if and only if params.Fs is in Hz.\n%                       The default is to use form 1 with TW=3 and K=5\n%\n%\t        pad\t\t    (padding factor for the FFT) - optional (can take values -1,0,1,2...). \n%                    -1 corresponds to no padding, 0 corresponds to padding\n%                    to the next highest power of 2 etc.\n%\t\t\t      \t e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT\n%\t\t\t      \t to 512 points, if pad=1, we pad to 1024 points etc.\n%\t\t\t      \t Defaults to 0.\n%           Fs   (sampling frequency) - optional. Default 1.\n%           fpass    (frequency band to be used in the calculation in the form\n%                                   [fmin fmax])- optional. \n%                                   Default all frequencies between 0 and Fs/2\n%           trialave (average over trials/channels when 1, don't average when 0) - optional. Default 0\n% Output:\n%       dS       (spectral derivative in form phi x frequency x channels/trials if trialave=0 or \n%                in form phi x frequency if trialave=1)\n%       f        (frequencies)\n\nif nargin < 2; error('Need data and angle'); end;\nif nargin < 3; params=[]; end;\n[tapers,pad,Fs,fpass,err,trialave,params]=getparams(params);\nclear err params\ndata=change_row_to_column(data);\nN=size(data,1);\nnfft=max(2^(nextpow2(N)+pad),N);\n[f,findx]=getfgrid(Fs,nfft,fpass); \ntapers=dpsschk(tapers,N,Fs); % check tapers\nK=size(tapers,2);\nJ=mtfftc(data,tapers,nfft,Fs);\nJ=J(findx,:,:);\nA=sqrt(1:K-1);\nA=repmat(A,[size(J,1) 1]);\nA=repmat(A,[1 1 size(J,3)]);\nS=squeeze(mean(J(:,1:K-1,:).*A.*conj(J(:,2:K,:)),2));\nif trialave; S=squeeze(mean(S,2));end;\nnphi=length(phi);\nfor p=1:nphi;\n    dS(p,:,:)=real(exp(i*phi(p))*S);\nend;\ndS=squeeze(dS);\ndS=change_row_to_column(dS);\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/spectral_analysis/continuous/mtdspectrumc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5917474506038053}}
{"text": "function [F,V]=mesh2tri(X,Y,Z,tri_type)\n\n% function [F,V]=mesh2tri(X,Y,Z,tri_type)\n% ------------------------------------------------------------------------\n%\n% This function converts a regular mesh defined by X,Y and Z into a regular\n% triangulation. The output is patch data (triangles) in the faces \ufffdF\ufffd and\n% vertices \ufffdV\ufffd format. The quadrilateral mesh faces are converted to\n% triangles by splitting the faces into triangles according to the setting\n% tri_type:\n%   tri_type ='f' -> forward slash division of quadrilateral\n%   tri_type ='b' -> back slash division of quadrilateral\n%   tri_type ='x' -> Cross division of quadrilateral\n%\n% The output coordinates \"V\" are in the form of V=[X(:),Y(:),Z(:)];\n% For forward and back slash subdivision no extra coordinates are\n% introduced and therefore the original meshgrid formatted coordinates can\n% still be used for plotting, see examples below.\n% For cross division extra points are created at the centre of each\n% quadrilateral face using the mean of the input coordinates. The extra\n% coordinates are the last prod(size(X)-1) points (e.g.\n% V((numel(X)+1):end,:) )and can therefore be replaced by interpolated\n% coordinates if desired, see example.\n%\n%\n% %% EXAMPLE\n% clear all; close all; clc;\n%\n% [X,Y] = meshgrid(linspace(-10,10,25));\n% Z = sinc(sqrt((X/pi).^2+(Y/pi).^2));\n%\n% figure('units','normalized','Position',[0 0 1 1],'Color','w'); colordef('white');\n% subplot(2,2,1);\n% surf(X,Y,Z); hold on;\n% axis tight; axis square; grid on; axis off; view(3); view(-30,70);\n% title('Meshgrid','FontSize',20);\n%\n% [F,V]=mesh2tri(X,Y,Z,'f');\n% C=V(:,3); C=mean(C(F),2);\n% subplot(2,2,2);\n% patch('Faces',F,'Vertices',V,'FaceColor','flat','CData',C); hold on;\n% axis tight; axis square; grid on; axis off; view(3); view(-30,70);\n% title('Forward slash','FontSize',20);\n%\n% [F,V]=mesh2tri(X,Y,Z,'b');\n% C=V(:,3); C=mean(C(F),2);\n% subplot(2,2,3);\n% Example of using original meshgrid coordinates instead\n% trisurf(F,X,Y,Z);\n% axis tight; axis square; grid on; axis off; axis off; view(3); view(-30,70);\n% title('Back slash','FontSize',20);\n%\n% [F,V]=mesh2tri(X,Y,Z,'x');\n% Replace Z-coordinates of added points by interpolated values if desired\n% IND=(numel(X)+1):size(V,1);\n% ZI = interp2(X,Y,Z,V(IND,1),V(IND,2),'cubic');\n% V(IND,3)=ZI;\n%\n% C=V(:,3); C=mean(C(F),2);\n% subplot(2,2,4);\n% patch('Faces',F,'Vertices',V,'FaceColor','flat','CData',C); hold on;\n% axis tight; axis square; grid on; axis off; view(3); view(-30,70);\n% title('Crossed','FontSize',20);\n%\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n%\n% 15/07/2010\n%------------------------------------------------------------------------\n\n[J,I]=meshgrid(1:1:size(X,2)-1,1:1:size(X,1)-1);\n\nswitch tri_type\n    case 'f'%Forward slash\n        TRI_I=[I(:),I(:)+1,I(:)+1;  I(:),I(:),I(:)+1];\n        TRI_J=[J(:),J(:)+1,J(:);   J(:),J(:)+1,J(:)+1];\n        F = sub2ind(size(X),TRI_I,TRI_J);\n    case 'b'%Back slash\n        TRI_I=[I(:),I(:)+1,I(:);  I(:)+1,I(:)+1,I(:)];\n        TRI_J=[J(:)+1,J(:),J(:);   J(:)+1,J(:),J(:)+1];\n        F = sub2ind(size(X),TRI_I,TRI_J);\n    case 'x'%Cross\n        TRI_I=[I(:)+1,I(:);  I(:)+1,I(:)+1;  I(:),I(:)+1;    I(:),I(:)];\n        TRI_J=[J(:),J(:);    J(:)+1,J(:);    J(:)+1,J(:)+1;  J(:),J(:)+1];\n        IND=((numel(X)+1):numel(X)+prod(size(X)-1))';\n        F = sub2ind(size(X),TRI_I,TRI_J);\n        F(:,3)=repmat(IND,[4,1]);\n        Fe_I=[I(:),I(:)+1,I(:)+1,I(:)]; Fe_J=[J(:),J(:),J(:)+1,J(:)+1];\n        Fe = sub2ind(size(X),Fe_I,Fe_J);\n        Xe=mean(X(Fe),2); Ye=mean(Y(Fe),2);  Ze=mean(Z(Fe),2);\n        X=[X(:);Xe(:)]; Y=[Y(:);Ye(:)]; Z=[Z(:);Ze(:)];\nend\n\nV=[X(:),Y(:),Z(:)];\n\nend\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/mesh2tri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5917474488007426}}
{"text": "function [ objects] = room3DFromHyp( points, floor_height )\n%ROOM3DFROMHYP Popup room layout hypothesis to 3D\n%   points: room corner in sequence in room layout\n%   floor_height: assumed floor height, e.g. -160\n\n% uv = xyz2uvN(points);\n% high_height = floor_height * tan(uv(1:4,2))./tan(uv(5:8,2));\n% ceil_height = mean(high_height);\n% \n% point3D = zeros(8,3);\n% for i = 5:8\n%     point3D(i,:) = LineFaceIntersection([0 0 floor_height], [0 0 1], [0 0 0], points(i,:));\n% end\nCOUNTER_CLOCKWISE = true;\nFITTINGRULES;\n\n[pt I] = sortXYZ(points(1:4,:));\npd = points(5:8,:); pd = pd(I,:);\nsort_points = [pd;pt];\nann_points = sort_points(POINTMAPPING{3},:);\n\nobjects = struct('out_points_w',[],'name',[],'type',[],'points',[],'x_w',[]);\n[ out_point, x, fval, succ ] = initial_cuboid_3D( ann_points, 3, floor_height, 3, true );\n\nobjects.points = ann_points;\nobjects.type = 3;\nobjects.name = 'room';\nobjects.out_points_w = out_point;\nobjects.x_w = x;\n\nend\n\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/ObjectHypothesisGeneration/Rectangle2Hypothesis/room3DFromHyp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5915626086604749}}
{"text": "function out = echo_enc_mirror(signal, text, d0, d1, alpha, L)\n%ECHO_ENC_MIRRORED Echo Hiding with Mirrored Echo Kernels\n%\n%   INPUT VARIABLES\n%       signal : Cover signal\n%       text   : Message to hide\n%       d0     : Delay rate for bit0\n%       d1     : Delay rate for bit1\n%       alpha  : Echo amplitude\n%       L      : Length of frames\n%\n%   OUTPUT VARIABLES\n%       out    : Stego signal\n%\n%   Kadir Tekeli (kadir.tekeli@outlook.com)\n\nif nargin < 4\n\td0 = 150;     %Delay rate for bit0\n\td1 = 200;     %Delay rate for bit1\nend\n\nif nargin < 5\n\talpha = 0.5;  %Echo amplitude\nend\n\nif nargin < 6\n\tL = 8*1024;   %Length of frames\nend\n\n[s.len, s.ch] = size(signal);\nbit = getBits(text);\nnframe = floor(s.len/L);\nN = nframe - mod(nframe,8);      %Number of frames (for 8 bit)\n\nif (length(bit) > N)\n\twarning('Message is too long, being cropped!');\n\tbits = bit(1:N);\nelse\n\twarning('Message is being zero padded...');\n\tbits = [bit, num2str(zeros(N-length(bit), 1))'];\nend\n\n[echo_zro,echo_one] = mirror_echo(signal,d0,d1,alpha);  %Echo signals\nmix = mixer(L,bits,0,1,256)*ones(1, s.ch);              %Mixer signal\n\n%%%%%%%%%%%%%%%%%%%%%%% EMBEDDING MESSAGE... %%%%%%%%%%%%%%%%%%%%%%%\nout = signal(1:N*L, :) + echo_zro(1:N*L, :) .* abs(mix-1) ...\n                       + echo_one(1:N*L, :) .* mix;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nout = [out; signal(N*L+1:s.len, :)];   %Rest of the signal\nend\n", "meta": {"author": "ktekeli", "repo": "audio-steganography-algorithms", "sha": "695ae978cdec2537d64db771ed4a12887bda92f8", "save_path": "github-repos/MATLAB/ktekeli-audio-steganography-algorithms", "path": "github-repos/MATLAB/ktekeli-audio-steganography-algorithms/audio-steganography-algorithms-695ae978cdec2537d64db771ed4a12887bda92f8/02-Echo-Hiding/04-Echo-Hiding-Mirrored-Kernel/echo_enc_mirror.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5915445316771052}}
{"text": "% RSFIT - find p value for a given value in a given distribution\n%             using Ramberg-Schmeiser distribution\n%\n% Usage: >> p = rsfit(x, val)\n%        >> [p c l chi2] = rsfit(x, val, plot)\n%\n% Input:\n%   x    - [float array] accumulation values\n%   val  - [float] value to test\n%   plot - [0|1|2] plot fit. Using 2, the function avoids creating\n%          a new figure. Default: 0.\n%\n% Output:\n%   p    - p value\n%   c    - [mean var skewness kurtosis] distribution cumulants\n%   l    - [4x float vector] Ramberg-Schmeiser distribution best fit\n%          parameters.\n%   chi2 - [float] chi2 for goodness of fit (based on 12 bins). \n%          Fit is significantly different from data histogram if \n%          chi2 > 19 (5%) \n%\n% Author: Arnaud Delorme, SCCN, 2003\n%\n% See also: RSADJUST, RSGET, RSPDFSOLV, RSPFUNC\n%\n% Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F.\n%            A probability distribution and its uses in fitting data. \n%            Technimetrics, 1979, 21: 201-214.\n\n% Copyright (C) 2003 Arnaud Delorme, SCCN, 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 [p, c, l, res] = rsfit(x, val, plotflag)\n\n    if nargin < 2\n        help rsfit;\n        return;\n    end\n    if nargin < 3\n        plotflag  = 0;\n    end\n    \n    % moments\n    % -------\n    m1  = mean(x);\n    m2  = sum((x-m1).^2)/length(x);\n    m3  = sum((x-m1).^3)/length(x);\n    m4  = sum((x-m1).^4)/length(x);\n\n    xmean = m1;\n    xvar  = m2;\n    xskew = m3/(m2^1.5);\n    xkurt = m4/(m2^2);\n    c     = [ xmean xvar xskew xkurt ];\n    \n    if xkurt < 0\n        disp('rsfit error: Can not fit negative kurtosis');\n        save('/home/arno/temp/dattmp.mat', '-mat', 'x');\n        disp('data saved to disk in /home/arno/temp/dattmp.mat');        \n    end\n    \n    % find fit\n    % --------\n    try, \n        [sol tmp exitcode] = fminsearch('rspdfsolv', [0.1 0.1], optimset('TolX',1e-12, 'MaxFunEvals', 100000000), abs(xskew), xkurt);    \n    catch, exitcode = 0; % did not converge\n    end\n    if ~exitcode\n        try, [sol tmp exitcode] = fminsearch('rspdfsolv', -[0.1 0.1], optimset('TolX',1e-12, 'MaxFunEvals', 100000000), abs(xskew), xkurt);\n        catch, exitcode = 0; end\n    end\n    if ~exitcode,           error('No convergence'); end\n    if sol(2)*sol(1) == -1, error('Wrong sign for convergence'); end\n    %fprintf('          l-val:%f\\n', sol);\n    \n    res = rspdfsolv(sol, abs(xskew), xkurt);\n    l3 = sol(1);\n    l4 = sol(2);\n\n    %load res;\n    %[tmp indalpha3] = min( abs(rangealpha3 - xskew) );\n    %[tmp indalpha4] = min( abs(rangealpha4 - xkurt) );\n    %l3  = res(indalpha3,indalpha4,1);\n    %l4  = res(indalpha3,indalpha4,2);    \n    %res = res(indalpha3,indalpha4,3);\n    \n    % adjust fit\n    % ----------\n    [l1 l2 l3 l4] = rsadjust(l3, l4, xmean, xvar, xskew);\n    l = [l1 l2 l3 l4];\n    p = rsget(l, val);\n\n    % compute goodness of fit\n    % -----------------------\n    if nargout > 3 || plotflag\n\n        % histogram of value 12 bins\n        % --------------------------\n        [N X] = hist(x, 25);\n        interval = X(2)-X(1);\n        X = [X-interval/2 X(end)+interval/2]; % borders\n        \n        % regroup bin with less than 5 values\n        % -----------------------------------\n        indices2rm = [];\n        for index = 1:length(N)-1\n            if N(index) < 5\n                N(index+1) = N(index+1) + N(index);\n                indices2rm = [ indices2rm index];\n            end\n        end\n        N(indices2rm)   = [];\n        X(indices2rm+1) = [];\n        indices2rm = [];\n        for index = length(N):-1:2\n            if N(index) < 5\n                N(index-1) = N(index-1) + N(index);\n                indices2rm = [ indices2rm index];\n            end\n        end\n        N(indices2rm)   = [];\n        X(indices2rm)   = [];\n        \n        % compute expected values\n        % -----------------------        \n        for index = 1:length(X)-1\n            p1 = rsget( l, X(index+1));\n            p2 = rsget( l, X(index  ));\n            expect(index) = length(x)*(p1-p2); \n        end\n        \n        % value of X2\n        % -----------\n        res = sum(((expect - N).^2)./expect);\n        \n        % plot fit\n        % --------\n        if plotflag\n            if plotflag ~= 2, figure('paperpositionmode', 'auto'); end\n            hist(x, 10);\n            \n            % plot fit\n            % --------\n            xdiff = X(end)-X(1);\n            abscisia   = linspace(X(1)-0.2*xdiff, X(end)+0.2*xdiff, 100);\n            %abscisia  = (X(1:end-1)+X(2:end))/2;\n            expectplot = zeros(1,length(abscisia)-1);\n            for index = 2:length(abscisia); \n                p1 = rsget( l, abscisia(index-1));\n                p2 = rsget( l, abscisia(index  ));\n                expectplot(index-1) = length(x)*(p2-p1); \n                % have to do this subtraction since this a cumulate density distribution\n            end\n            abscisia = (abscisia(2:end)+abscisia(1:end-1))/2;\n            hold on; plot(abscisia, expectplot, 'r');\n        \n            % plot PDF\n            % ----------\n            pval = linspace(0,1, 102); pval(1) = []; pval(end) = [];\n            rp   = l(1) + (pval.^l(3) - (1-pval).^l(4))/l(2);\n            fp   = l(2)*1./(l(3).*(pval.^(l(3)-1)) + l(4).*((1-pval).^(l(4)-1)));\n            [maxval index]  = max(expect);\n            [tmp closestind] = min(abs(rp - abscisia(index)));\n            fp = fp./fp(closestind)*maxval;\n            plot(rp, fp, 'g');\n            legend('Chi2 fit (some bins have been grouped)', 'Pdf', 'Data histogram'  );\n            xlabel('Bins');\n            ylabel('# of data point per bin');            \n            title (sprintf('Fit of distribution using Ramberg-Schmeiser distribution (Chi2 = %2.4g)', res));            \n        end\n    end\n    return\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/timefreqfunc/rsfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711718571775, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5915445130924422}}
{"text": "function [N, eta, sigma_g] = scd_noise_fit_histo(data,varargin)\n% [N, eta, sigma_g] = scd_noise_fit_histo(data)\n% [N, eta, sigma_g] = scd_noise_fit_histo(__,Name,Value)\n\ndata=data(:);\np=inputParser;\naddRequired(p,'data',@isnumeric)\naddOptional(p,'nbins',max(15,sqrt(length(data))));\n[~, xmax] = range_outlier(data);\naddOptional(p,'maxval',xmax);\naddOptional(p,'maxy',0);\naddOptional(p,'color',[0 0 1],@isnumeric);\naddOptional(p,'fig',1,@isnumeric);\naddOptional(p,'plotfit',0,@isnumeric);\naddOptional(p,'distrib','Non-central Chi',@(x) any(validatestring(x,{'Non-central Chi','Rician'})));\n\nif logical(exist('OCTAVE_VERSION', 'builtin'))\n    in.fig = varargin{2};\n    in.distrib = varargin{4};\n    in.nbins = max(15,sqrt(length(data)));\n    [~, in.maxval] = range_outlier(data);\n    in.maxy = 0;\n    in.color = [0 0 1];\n    in.plotfit = 0;\nelse\n    parse(p,data,varargin{:});\n    in=p.Results;\nend\n\n%% PREPARE DATA\ndata(data==0)=[];\ndata(data>in.maxval)=[];\n\nif isinteger(data)\n    xout=double(unique(data(:)));\n    n=double(histc(data(:),xout));\nelse\n    [n,xout]=hist(data,in.nbins);\nend\nxout(n==0)=[]; n(n==0)=[];  n(xout==0)=0;\nn=n/trapz(xout,n);\n\nxout = xout(:); n = n(:);\nmaxnoise=cumtrapz(xout,n);\nmaxnoise=xout(find(maxnoise>0.999,1,'first'));\ndata(data>maxnoise)=[];\n\nif isinteger(data)\n    xout=double(unique(data(:)));\n    n=double(histc(data(:),xout));\nelse\n    [n,xout]=hist(data,in.nbins);\nend\n\nxout(n==0)=[]; n(n==0)=[];  n(xout==0)=0;\nn=n/trapz(xout,n);\nn(xout<0)=[];\nxout(xout<0)=[];\n\nxout = xout(:); n = n(:);\nxi=0:max(xout)/in.nbins:max(xout);\nyi = interp1(xout,n,xi);\nyi(isnan(yi))=0;\nyi=yi/trapz(xi,yi);\nxi=xout; yi=n;\n\n\n%% Fit: 'non-central chi'.\n%eta = sum(xi.*yi.*mean(diff(xi)));\n%    [N      eta     sigma]\nvar0=[1           eps            std(double(data))];\nlb = [1           0                  0.1        ]; \nub= [10    double(max(data)) std(double(data)*2)];\nswitch in.distrib\n    case 'Non-central Chi'\n        fx = [0 0 0];\n    case 'Rician'\n        fx = [1 1 0];\nend\n\noptions = optimset('Algorithm','trust-region-reflective','TolFun',1e-8,'Display','final','MaxIter',10,'Display','off');\ndisp('     N        eta      sigma_g')\n[varfit] = lsqnonlin(@(x1) noncentralchi_error(addfixparameters(var0,x1,fx),xi,yi,in.plotfit), var0(~fx), lb(~fx), ub(~fx),options);\nvarfit = addfixparameters(var0,varfit,fx);\ndisp(varfit)\nN=varfit(1); eta=varfit(2); sigma_g=varfit(3);\nfval = noncentralchi(xi, N,sigma_g,eta);\n\nif in.fig\n    figure(73)\n    set(73,'Name','Noise histogram','NumberTitle','off')\n    plot(xi,yi,'+','Color',in.color,'MarkerSize',10); hold on, plot(xi,fval,'Color',[1 0 0],'Linewidth',2);\n    xlim([0 in.maxval]);\n    if ~in.maxy, maxy=2*max(yi); else maxy=in.maxy; end\n    ylim([0 maxy])\n    title(['N = ' num2str(N) ', eta = ' num2str(eta) ', sigma = ' num2str(sigma_g)])\nend\n\nend\n\nfunction Error = noncentralchi_error(var,x,y,plotfit)\nN=var(1); eta=var(2); sigma_g=var(3);\nf= noncentralchi(x, N,sigma_g,eta);\nf(isnan(f))=0;\nf=f/trapz(x,f);\nif rand<plotfit\n    disp(num2str(var))\n    figure(4)\n    hold off, plot(x,y); hold on, plot(x,f,'r');\n    xlim([0 max(x)]);\n    ylim([0 2*max(y)])\n    pause(0.1)\nend\nError = abs(f-y);\nend\n\nfunction p= noncentralchi(x, N,sigma_g,eta)\np = abs(x).^N./(sigma_g^2*eta^(N-1)).*exp(-(x.^2+eta^2)/(2*sigma_g^2)).*besseli(N-1,x*eta/sigma_g^2);\nend\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/Noise/scd_noise_fit_histo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6959583124210895, "lm_q1q2_score": 0.5915445050172153}}
{"text": "function [f,relres,iter]=isgramreal(s,g,a,M,varargin)\n%ISGRAMREAL  Spectrogram inversion (real signal)\n%   Usage:  f=isgramreal(s,g,a,M);\n%           f=isgramreal(s,g,a,M,Ls);\n%           [f,relres,iter]=isgramreal(...);\n%\n%   Input parameters:\n%         c       : Array of coefficients.\n%         g       : Window function.\n%         a       : Length of time shift.\n%         M       : Number of channels.\n%         Ls      : length of signal.\n%   Output parameters:\n%         f       : Signal.\n%         relres  : Vector of residuals.\n%         iter    : Number of iterations done.\n%\n%   `isgramreal(s,g,a,M)` attempts to invert a spectrogram computed by ::\n%\n%     s = abs(dgtreal(f,g,a,M)).^2;\n%\n%   by an iterative method.\n%\n%   `isgramreal(s,g,a,M,Ls)` does as above but cuts or extends *f* to length *Ls*.\n%\n%   If the phase of the spectrogram is known, it is much better to use\n%   |dgtreal|\n%\n%   `f,relres,iter]=isgramreal(...)` additionally returns the residuals in a\n%   vector *relres* and the number of iteration steps done.\n%\n%   Generally, if the spectrogram has not been modified, the iterative\n%   algorithm will converge slowly to the correct result. If the\n%   spectrogram has been modified, the algorithm is not guaranteed to\n%   converge at all.  \n%\n%   `isgramreal` takes the following parameters at the end of the line of\n%   input arguments:\n%\n%     'lt',lt      Specify the lattice type. See the help on\n%                  |matrix2latticetype|. Only the rectangular or quinqux\n%                  lattices can be specified.\n%\n%     'zero'       Choose a starting phase of zero. This is the default\n%\n%     'rand'       Choose a random starting phase.\n%\n%     'int'        Construct a starting phase by integration. Only works\n%                  for Gaussian windows.\n%\n%     'griflim'    Use the Griffin-Lim iterative method, this is the\n%                  default.\n%\n%     'bfgs'       Use the limited-memory Broyden Fletcher Goldfarb\n%                  Shanno (BFGS) method.  \n%\n%     'tol',t      Stop if relative residual error is less than the specified tolerance.  \n%\n%     'maxit',n    Do at most n iterations.\n%\n%     'print'      Display the progress.\n%\n%     'quiet'      Don't print anything, this is the default.\n%\n%     'printstep',p\n%                  If 'print' is specified, then print every p'th\n%                  iteration. Default value is p=10.\n%\n%   The BFGS method makes use of the minFunc software. To use the BFGS method, \n%   please install the minFunc software from:\n%   `<http://www.cs.ubc.ca/~schmidtm/Software/minFunc.html>`_.\n%\n%   See also:  dgtreal, idgtreal\n%\n%   References: griffin1984sem decorsiere2011 liu1989limited\n  \n%   AUTHOR : Remi Decorsiere and Peter L. S\u00f8ndergaard.\n%   REFERENCE: OK\n\n% Check input paramameters.\n\n  if nargin<3\n    error('%s: Too few input parameters.',upper(mfilename));\n  end;\n  \n  if numel(g)==1\n    error('g must be a vector (you probably forgot to supply the window function as input parameter.)');\n  end;\n  \n  definput.keyvals.Ls=[];\n  definput.keyvals.lt=[0 1];\n  definput.keyvals.tol=1e-6;\n  definput.keyvals.maxit=100;\n  definput.keyvals.printstep=10;\n  definput.flags.method={'griflim','bfgs'};\n  definput.flags.print={'print','quiet'};\n  definput.flags.startphase={'zero','rand','int'};\n  \n  [flags,kv,Ls]=ltfatarghelper({'Ls','tol','maxit'},definput,varargin);\n\n  N=size(s,2);\n  W=size(s,3);\n  \n  % Make a dummy call to test the input parameters\n  Lsmallest=dgtlength(1,a,M,kv.lt);\n  \n  M2=floor(M/2)+1;\n  \n  if M2~=size(s,1)\n      error('Mismatch between the specified number of channels and the size of the input coefficients.');\n  end;\n  \n  L=N*a;\n  \n  if rem(L,Lsmallest)>0\n      error('%s: Invalid size of coefficient array.',upper(mfilename));\n  end;\n  \n  %% ----- step 3 : Determine the window \n  \n  [g,info]=gabwin(g,a,M,L,kv.lt,'callfun',upper(mfilename));\n  \n  if L<info.gl\n      error('%s: Window is too long.',upper(mfilename));\n  end;\n  \n  if ~isreal(g)\n      error('%s: Window must be real-valued.',upper(mfilename));\n  end;\n  \n  %% Actual computation\n  \n  sqrt_s=sqrt(s);\n  \n  if flags.do_zero\n    % Start with a phase of zero.\n    c=sqrt(s);\n  end;\n  \n  if flags.do_rand\n    c=sqrt_s.*exp(2*pi*1i*rand(size(s)));\n  end;\n  \n  if flags.do_int\n      if kv.lt(2)>1\n          error(['%s: The integration initilization is not implemented for ' ...\n                 'non-sep lattices.'],upper(mfilename));\n      end;\n\n      \n    s2=zeros(M,N);\n    s2(1:M2,:)=s;\n    if rem(M,2)==0\n      s2(M2+1:M,:)=flipud(s(2:end-1,:));\n    else\n      s2(M2+1:M,:)=flipud(s(2:end));\n    end;\n    c=constructphase(s2,g,a);\n    c=c(1:M2,:);\n  end;\n    \n  gd = gabdual(g,a,M);\n    \n  % For normalization purposes\n  norm_s=norm(s,'fro');\n  \n  relres=zeros(kv.maxit,1);\n  if flags.do_griflim\n    for iter=1:kv.maxit\n      f=comp_idgtreal(c,gd,a,M,kv.lt,0);\n      c=comp_dgtreal(f,g,a,M,kv.lt,0);\n      \n      relres(iter)=norm(abs(c).^2-s,'fro')/norm_s;\n      \n      c=sqrt_s.*exp(1i*angle(c));\n      \n      if flags.do_print\n        if mod(iter,kv.printstep)==0\n          fprintf('ISGRAMREAL: Iteration %i, residual = %f.\\n',iter,relres(iter));\n        end;    \n      end;\n      \n      if relres(iter)<kv.tol\n        relres=relres(1:iter);\n        break;\n      end;\n      \n    end;\n    \n  end;\n  \n  if flags.do_bfgs\n    if exist('minFunc')~=2\n      error(['To use the BFGS method in ISGRAMREAL, please install the minFunc ' ...\n             'software from http://www.cs.ubc.ca/~schmidtm/Software/minFunc.html.']);\n    end;\n    \n    % Setting up the options for minFunc\n    opts = struct;\n    opts.display = kv.printstep;\n    opts.maxiter = kv.maxit;\n    opts.usemex = 0;\n\n    % Don't limit the number of function evaluations, just the number of\n    % time-steps.\n    opts.MaxFunEvals = 1e9;\n    \n    f0 = comp_idgtreal(c,gd,a,M,kv.lt,0);\n    [f,fval,exitflag,output]=minFunc(@objfun,f0,opts,g,a,M,s,kv.lt);\n    % First entry of output.trace.fval is the objective function\n    % evaluated on the initial input. Skip it to be consistent.\n    relres = sqrt(output.trace.fval(2:end))/norm_s;\n    iter = output.iterations;\n  end;\n  \n  % Cut or extend f to the correct length, if desired.\n  if ~isempty(Ls)\n    f=postpad(f,Ls);\n  else\n    Ls=L;\n  end;\n  \n  f=comp_sigreshape_post(f,Ls,0,[0; W]);\n  \n%  Subfunction to compute the objective function for the BFGS method.\nfunction [f,df]=objfun(x,g,a,M,s,lt);\n  c=comp_dgtreal(x,g,a,M,lt,0);\n  \n  inner=abs(c).^2-s;\n  f=norm(inner,'fro')^2;\n  \n  df=4*real(conj(comp_idgtreal(inner.*c,g,a,M,lt,0)));\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/gabor/isgramreal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5915289973968136}}
{"text": "function [Yl,Yh,Yscale] = dtwavexfm(X,nlevels,biort,qshift);\n\n% Function to perform a n-level DTCWT decompostion on a 1-D column vector X\n% (or on the columns of a matrix X).\n%\n% [Yl,Yh,Yscale] = dtwavexfm(X,nlevels,biort,qshift);\n%\n%     X -> real 1-D signal column vector (or matrix of vectors)\n%\n%     nlevels -> No. of levels of wavelet decomposition\n%\n%     biort ->  'antonini'   => Antonini 9,7 tap filters.\n%               'legall'     => LeGall 5,3 tap filters.\n%               'near_sym_a' => Near-Symmetric 5,7 tap filters.\n%               'near_sym_b' => Near-Symmetric 13,19 tap filters.\n%\n%     qshift -> 'qshift_06' => Quarter Sample Shift Orthogonal (Q-Shift) 10,10 tap filters, \n%                              (only 6,6 non-zero taps).\n%               'qshift_a' =>  Q-shift 10,10 tap filters,\n%                              (with 10,10 non-zero taps, unlike qshift_06).\n%               'qshift_b' => Q-Shift 14,14 tap filters.\n%               'qshift_c' => Q-Shift 16,16 tap filters.\n%               'qshift_d' => Q-Shift 18,18 tap filters.\n%               \n%\n%     Yl     -> The real lowpass subband from the final level.\n%     Yh     -> A cell array containing the complex highpass subband for each level.\n%     Yscale -> This is an OPTIONAL output argument, that is a cell array containing \n%               the real lowpass coefficients at every scale.\n%\n% \n% Example: [Yl,Yh] = dtwavexfm(X,5,'near_sym_b','qshift_b');\n% performs a 5-level transform on the real image X using the 13,19-tap filters \n% for level 1 and the Q-shift 14-tap filters for levels >= 2.\n%\n% Nick Kingsbury and Cian Shaffrey\n% Cambridge University, May 2002\n\nif isstr(biort) & isstr(qshift)\t\t%Check if the inputs are strings\n   biort_exist = exist([biort '.mat']);\n   qshift_exist = exist([qshift '.mat']);\n   if biort_exist == 2 & qshift_exist == 2;  %Check to see if the filters exist as .mat files\n      load (biort);\n      load (qshift);\n   else\n      error('Please enter the correct names of the Biorthogonal or Q-Shift Filters, see help DTWAVEXFM for details.');\n   end\nelse\n   error('Please enter the names of the Biorthogonal or Q-Shift Filters as shown in help DTWAVEXFM.');\nend\n\nL = size(X);\n\nif any(rem(L(1),2)),\t % ensure that X is an even length, thus enabling it to be extended if needs be.\n   error('Size of X must be a multiple of 2');\nend\n\nif nlevels == 0, return; end\n\n%initialise\nYh=cell(nlevels,1);\nif nargout == 3\n   Yscale=cell(nlevels,1);   % This is only required if the user specifies a third output component.\nend\n\nj = sqrt(-1);\n\n% Level 1.\nHi = colfilter(X, h1o);   \nLo = colfilter(X, h0o);\nt = 1:2:size(Hi,1);\nYh{1} = Hi(t,:) + j*Hi(t+1,:); % Convert Hi to complex form.\nif nargout == 3\n   Yscale{1} = Lo;\nend\n\nif nlevels >= 2;  % Levels 2 and above.\n   for level = 2:nlevels;  \n      if rem(size(Lo,1),4),\t% Check to see if height of Lo is divisable by 4, if not extend.\n         Lo = [Lo(1,:); Lo; Lo(end,:)];\n      end     \n      Hi = coldfilt(Lo,h1b,h1a);\n      Lo = coldfilt(Lo,h0b,h0a); \n\t   t = 1:2:size(Hi,1);\n   \tYh{level} = Hi(t,:) + j*Hi(t+1,:); % Convert Hi to complex form.\n   \tif nargout == 3\n      \tYscale{level} = Lo;\n   \tend\n   end   \nend\n\nYl = Lo;\n\nreturn\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/dtwavexfm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5915289946809427}}
{"text": "function guv = evaluate_log_posterior_grad(this, uv)\n%EVALUATE_LOG_POSTERIOR computes the gradient of the log-posterior\n%   (negative energy) wrt the flow fields UV \n%   Actually only proportional to the log posterior since the variance of neither the\n%   spatial nor the data terms is considered\n%\n%   This is a member function of the class 'ba_optical_flow'. \n%\n%   Author: Deqing Sun, Department of Computer Science, Brown University\n%   Contact: dqsun@cs.brown.edu\n%   $Date: 2007-11-30 $\n%\n% Copyright 2007-2010, Brown University, Providence, RI. USA\n% \n%                          All Rights Reserved\n% \n% All commercial use of this software, whether direct or indirect, is\n% strictly prohibited including, without limitation, incorporation into in\n% a commercial product, use in a commercial service, or production of other\n% artifacts for commercial purposes.     \n%\n% Permission to use, copy, modify, and distribute this software and its\n% documentation for research purposes is hereby granted without fee,\n% provided that the above copyright notice appears in all copies and that\n% both that copyright notice and this permission notice appear in\n% supporting documentation, and that the name of the author and Brown\n% University not be used in advertising or publicity pertaining to\n% distribution of the software without specific, written prior permission.        \n%\n% For commercial uses contact the Technology Venture Office of Brown University\n% \n% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO\n% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n% FITNESS FOR ANY PARTICULAR PURPOSE.  IN NO EVENT SHALL THE AUTHOR OR\n% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n% THIS SOFTWARE.        \n\n% Spatial term\nS       = this.spatial_filters;\ngu1     = zeros(size(uv,1), size(uv,2));\ngv1     = gu1;\n\nfor i = 1:length(S)\n\n    u_ = conv2(uv(:,:,1), S{i}, 'valid');\n    v_ = conv2(uv(:,:,2), S{i}, 'valid');\n\n    Si = reshape(S{i}(end:-1:1), size(S{i}));\n    \n    if isa(this.rho_spatial_u{i}, 'robust_function')        \n        u_ = -reshape(deriv(this.rho_spatial_u{i}, u_(:)), size(u_));                \n        v_ = -reshape(deriv(this.rho_spatial_v{i}, v_(:)), size(v_));                        \n    elseif isa(this.rho_spatial_u{i}, 'gsm_density')\n        u_ = reshape(evaluate_log_grad(this.rho_spatial_u{i}, u_(:)'), size(u_));                \n        v_ = reshape(evaluate_log_grad(this.rho_spatial_v{i}, v_(:)'), size(v_));                        \n    else\n        error('evaluate_log_posterior: unknown rho function!');\n    end;\n    \n    gu1 = gu1+conv2(u_, Si, 'full');\n    gv1 = gv1+conv2(v_, Si, 'full');    \nend;\n\ngu2     = zeros(size(uv,1), size(uv,2));\ngv2     = gu2;\n\n% Data term  \n[It Ix Iy] = partial_deriv(this.images, uv, this.interpolation_method, this.deriv_filter, this.blend);\n\nif isa(this.rho_data, 'robust_function')\n    temp   = -reshape(deriv(this.rho_data, It(:)), size(It));\n    \nelseif isa(this.rho_data, 'gsm_density')    \n    temp   = reshape(evaluate_log_grad(this.rho_data, It(:)'), size(It));\nelse\n    error('evaluate_log_posterior: unknown rho function!');\nend;\n\ngu2     = temp.*Ix;\ngv2     = temp.*Iy;\n\nguv = cat(3, gu2+this.lambda*gu1, gv2+this.lambda*gv1);\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/spaceTime/optflow_deqing/@ba_optical_flow/evaluate_log_posterior_grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5915289783857153}}
{"text": "% DATA\n%\n% Files\n%   cubeafemdata     - Data of an example of AFEM in a cube\n%   eddycurrentdata1 - Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n%   elasticitydata   - data for elasticity problem\n%   fourorderdate    - data for four order problem\n%   jumpdata1        - data for interface problem\n%   jumpmgdata1      - Data of JUMPMG1\n%   jumpmgdata2      - Data of JUMPMG1\n%   Maxwelldata1     - positive definite and homogenous Neumann boundary condition\n%   Maxwelldata2     - non-homogenous Dirichlet/Neumann boundary condition\n%   Maxwelldata3     - polynomial data\n%   Maxwelldata4     - homogenous Dirichlet boundary condition\n%   Maxwelldata5     - linear polynomial data\n%   mixBCdata        - mix boundary condition data for Poisson equation\n%   mixBCdata3       - mix boundary condition data for Poisson equation in 3-D\n%   planewavedata    - plane wave solution of Maxwell equations: complex solution\n%   planewavedata1   - plane wave solution of Maxwell equations: real solution.\n%   planewavedataC   - plane wave solution of Maxwell equations: real solution and complex coefficients\n%   planewavedataH   - plane wave solution of Maxwell equations in terms of H\n%   polydata1        - polynomial data for Poisson equation\n%   polydata3        - polynomial data for Poisson equation in 3-D\n%   sincosdata       - trigonometric  data for Poisson equation\n%   sincosdata3      - trigonometric data for Poisson equation in 3-D\n%   tensordata1      - data for interface problem\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/data/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.5914844273350206}}
{"text": "%% axisLim\n% Below is a demonstration of the features of the |axisLim| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |axLim=axisLim(V);|\n\n%% Description \n% This function computes appropiate axis limits for the input vertices V.\n% The vertices may be an k x l x m array, where by by k is the number of\n% vertices, l is the number of dimensions (e.g. 2 or 3), and m is for\n% instance a time (or other) dimension. The function returs axLim which are\n% appropriate axis limits such that the coordinates in V can be displayed\n% appropriately (and in a tight fashion). \n\n%% Examples\n\n%% Example 1: setting axis limits tightly around a coordinate set in 2D\n\n%%\n% Create example data\nt=linspace(0,2*pi,250)'; \nr=5+2*sin(5*t);\nV=r.*[cos(t) sin(t)];\n\n%%\n% Compute appropriate limits\naxLim=axisLim(V) %Axis limits for vertices\n\n%%\n% Assign axis limits using |axisLim|\n\ncFigure; \nplot(V(:,1),V(:,2),'b-');\naxis equal; axis(axisLim(V));\ndrawnow; \n\n%% Example 2: setting axis limits tightly around a coordinate set in 3D\n\n%%\n% Create example data\n[F,V]=stanford_bunny; \n\n%%\n% Compute appropriate limits\naxLim=axisLim(V) %Axis limits for vertices\n\n%%\n% Assign axis limits using |axisLim|\n\ncFigure; \ngpatch(F,V);\naxisGeom; camlight headlight; \naxis(axisLim(V));\ngdrawnow; \n\n%% Example 3: setting axis limits tightly around multiple coordinate sets in 3D\n\n%%\n% Create example data\n[F1,V1]=graphicsModels(3); \n[F2,V2]=graphicsModels(4); \nV2=V2+1;\n%%\n% Compute appropriate limits\naxLim=axisLim(V1,V2) %Axis limits for vertices\n\n%%\n% Assign axis limits using |axisLim|\n\ncFigure; hold on; \ngpatch(F1,V1,'gw');\ngpatch(F2,V2,'rw');\naxisGeom; camlight headlight; \naxis(axisLim(V1,V2));\ngdrawnow; \n\n%% Example 3: setting axis limits tightly around multiple coordinate sets with varying dimensions\n\n%%\n% Create example data\nV1=r.*[cos(t) sin(t)];\n[F2,V2]=geoSphere(2,1); \n\n%%\n% Compute appropriate limits\naxLim=axisLim(V1,V2) %Axis limits for vertices\n\n%%\n% Assign axis limits using |axisLim|\n\ncFigure; hold on; \nplot(V1(:,1),V1(:,2),'b-');\ngpatch(F2,V2,'rw');\naxisGeom; camlight headlight; \naxis(axisLim(V1,V2));\ngdrawnow; \n\n%% Example 4: setting axis limits tightly for coordinates over time\n\n[F,V]=stanford_bunny; %Some graphics data\n\nnSteps=50;\nt=linspace(0,pi,nSteps)';\nU=[-100*t/pi zeros(nSteps,1) 50*sin(t)];\n\nV_DEF=zeros(size(V,1),3,nSteps);\nfor q=1:1:nSteps\n    V_DEF(:,:,q)=V+U(q*ones(size(V,1),1),:);\nend\n\n%%\n% Compute appropriate limits\naxLim=axisLim(V_DEF) %Axis limits for vertices\n\n%% \n% Assign axis limits using |axisLim|\n\nhf=cFigure; \nhp=gpatch(F,V,'gw');\naxisGeom; camlight headlight; \naxis(axisLim(V_DEF)); %Set limits to be suitable across time\ndrawnow; \n\n%%\n% Use |anim8| to animate the scene\n\nanimStruct.Time=linspace(0,1,nSteps); %Time vector\n\nfor q=1:1:nSteps    \n    %Set entries in animation structure\n    animStruct.Handles{q}=hp; %Handles of objects to animate\n    animStruct.Props{q}={'Vertices'}; %Properties of objects to animate\n    animStruct.Set{q}={V_DEF(:,:,q)}; %Property values for to set in order to animate\nend\n\n% Start |anim8| gui\nanim8(hf,animStruct);\n\n%%\n% \n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_axisLim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.5914844151233307}}
{"text": "function cc_grids_constrained_display ( )\n\n%*****************************************************************************80\n%\n%% CC_GRIDS_CONSTRAINED_DISPLAY displays grids generated by CC_GRIDS_CONSTRAINED.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    08 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_CONSTRAINED_DISPLAY:\\n' );\n  fprintf ( 1, '  MATLAB version\\n' );\n  fprintf ( 1, '  Display the 2D Clenshaw-Curtis grids\\n' );\n  fprintf ( 1, '  generated by CC_GRIDS_CONSTRAINED.\\n' );\n\n  dim_num = 2;\n \n  while ( 1 )\n%\n%  Get user input.\n%\n    q_max = input ( 'Enter Q_MAX or RETURN to exit;' );\n    \n    if ( isempty ( q_max ) )\n      break\n    end\n    \n    if ( q_max < dim_num )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, '  We require DIM_NUM <= Q_MAX!\\n' );\n      continue\n    end\n\n    alpha = input ( 'Enter [ ALPHA1, ALPHA2 ] or RETURN to exit;' );\n    \n    if ( isempty ( alpha ) )\n      break\n    end\n\n    order_min = input ( 'Enter [ ORDER_MIN1, ORDER_MIN2 ] or RETURN to exit;' );\n    \n    if ( isempty ( order_min ) )\n      break\n    end\n\n    order_max = input ( 'Enter [ ORDER_MAX1, ORDER_MAX2 ] or RETURN to exit;' );\n    \n    if ( isempty ( order_max ) )\n      break\n    end\n%\n%  Compute data.\n%\n    [ grid_num, point_num ] = cc_grids_constrained_size ( dim_num, ...\n      q_max, alpha, order_min, order_max );\n    \n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Number of grids is %d\\n', grid_num );\n    fprintf ( 1, '  Number of points is %d\\n', point_num );\n\n    [ grid_order, grid_point ] = cc_grids_constrained ( dim_num, ...\n      q_max, alpha, order_min, order_max, grid_num, point_num );\n\n    clf\n%\n%  We have to name the axes in order to control the grid.\n%\n    axes_handle = axes;\n%\n%  Plot the points.\n%\n    handle = scatter ( grid_point(1,:), grid_point(2,:), 'filled' );\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 ( '%d <= Q <= %d', q_min, q_max );\n    title ( s );\n    \n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CC_GRIDS_CONSTRAINED_DISPLAY:\\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_constrained_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.5914844069822042}}
{"text": "%% EXAMPLE 2: Plot SPOD spectrum and inspect SPOD modes.\n%  The large-eddy simulation data provided along with this example is a\n%  subset of the database of a Mach 0.9 turbulent jet described in [1] and \n%  was calculated using the unstructured flow solver Charles developed at \n%  Cascade Technologies. If you are using the database in your research or \n%  teaching, please include explicit mention of Br\u00e8s et al. [1]. The test \n%  database consists of 5000 snapshots of the symmetric component (m=0) of \n%  a round turbulent jet. A physical interpretaion of the SPOD results is \n%  given in [2], and a comprehensive discussion and derivation of SPOD and\n%  many of its properties can be found in [3].\n%\n%   References:\n%     [1] G. A. Br\u00e8s, P. Jordan, M. Le Rallic, V. Jaunet, A. V. G. \n%         Cavalieri, A. Towne, S. K. Lele, T. Colonius, O. T. Schmidt, \n%         Importance of the nozzle-exit boundary-layer state in subsonic \n%         turbulent jets, J. of Fluid Mech. 851, 83-124, 2018\n%     [2] Schmidt, O. T. and Towne, A. and Rigas, G. and Colonius, T. and \n%         Bres, G. A., Spectral analysis of jet turbulence, J. of Fluid Mech. 855, 953\u2013982, 2018\n%     [3] Towne, A. and Schmidt, O. T. and Colonius, T., Spectral proper \n%         orthogonal decomposition and its relationship to dynamic mode\n%         decomposition and resolvent analysis, J. of Fluid Mech. 847, 821\u2013867, 2018\n%\n% O. T. Schmidt (oschmidt@ucsd.edu), A. Towne, T. Colonius\n% Last revision: 5-Sep-2022 (OTS)\n\nclc, clear variables\naddpath('utils')\nload(fullfile('jet_data','jetLES.mat'),'p','x','r','dt');\n\n%% SPOD of the test database.\n%   Calculate the SPOD of the data matrix 'p' and use the timestep 'dt'\n%   between snapshots to obtain the physical frequency 'f'. 'L' is the\n%   matrix of modal energies, as before, and 'P' the data matrix of SPOD\n%   modes. We leave all other options empty for now.\n[L,P,f] = spod(p,[],[],[],dt);\n\n%   First, we plot the SPOD spectrum.\nfigure\nloglog(f,L)\nxlabel('frequency'), ylabel('SPOD mode energy')\n\n%   Second, we visualize the 1st and 2nd SPOD modes at three frequencies.\nfigure\ncount = 1;\nfor fi = [10 15 20]\n    for mi = [1 2]\n        subplot(3,2,count)\n        contourf(x,r,real(squeeze(P(fi,:,:,mi))),11,'edgecolor','none'), axis equal tight, caxis(max(abs(caxis))*[-1 1])\n        xlabel('x'), ylabel('r'), title(['f=' num2str(f(fi),'%.2f') ', mode ' num2str(mi) ', \\lambda=' num2str(L(fi,mi),'%.2g')])\n        xlim([0 10]); ylim([0 2])\n        count = count + 1;\n    end\nend\n\n%% Animate the same modes.\n%   Note how all wavepackets travel at approximately the same phase\n%   speed c_ph. The reason is that their streamwise wavenumber k_x changes \n%   with frequency such that c_ph = omega/k_x is approximately constant.\nfigure\nnt      = 30;\nT       = 1/f(10);              % period of the 10th frequency\ntime    = linspace(0,T,nt);     % animate over one period\ncount = 1;\nfor ti = 1:nt\n    for fi = [10 15 20]\n        for mi = [1 2]\n            subplot(3,2,count)\n            pcolor(x,r,real(squeeze(P(fi,:,:,mi)*exp(2i*pi*f(fi)*time(ti))))), shading interp, axis equal tight, caxis(max(abs(caxis))*[-1 1])\n            xlabel('x'), ylabel('r'), title(['f=' num2str(f(fi),'%.2f') ', mode ' num2str(mi) ', \\lambda=' num2str(L(fi,mi),'%.2g')])\n            xlim([0 10]); ylim([0 2])\n            count = count + 1;\n            hold on\n        end\n    end\n    drawnow\n    hold off\n    count = 1;\nend\n", "meta": {"author": "SpectralPOD", "repo": "spod_matlab", "sha": "12d6d7d098eb3247ef0d8a502e2ce9600968869c", "save_path": "github-repos/MATLAB/SpectralPOD-spod_matlab", "path": "github-repos/MATLAB/SpectralPOD-spod_matlab/spod_matlab-12d6d7d098eb3247ef0d8a502e2ce9600968869c/example_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.76908023177796, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.5914844029116408}}
{"text": "%% subtri\n% Below is a demonstration of the features of the |subtri| function\n\n%% Syntax\n% |[Fs,Vs]=subtri(F,V,n,uniqueOpt);|\n\n%% Description\n% The |subtri| function enables refinement of triangulated data\n\n%% Examples\n\nclear; close all; clc;\n\n%% \n% Plot Settings\nfontSize=15;\nfaceAlpha=1;\nedgeColor=0.2*ones(1,3);\nedgeWidth=1.5;\nmarkerSize=35; \nmarkerSize2=20; \n\n%% Refining a triangle\n\nV=[0 0 0; 1 0 0; 0.5 sqrt(3)/2 0];\nF=[1 2 3];\n\nn=0:1:3; %Number of added edge nodes\npColors=gjet(numel(n));\n\ncFigure; \nfor q=1:1:numel(n)\n    [Fs,Vs]=subtri(F,V,n(q)); \n    subplot(2,2,q); hold on;\n    title([num2str(n(q)),' added edge nodes'],'FontSize',fontSize);\n    gpatch(Fs,Vs,pColors(q,:),'k');\n    plotV(Vs,'k.','markerSize',markerSize2); \n    plotV(V,'k.','markerSize',markerSize);\n    \n    axis equal; axis tight; view(2);    \nend\ndrawnow; \n\n%% Refining a tetrahedron\n\n[V,F]=platonic_solid(1,1);\n\nn=0:1:3; %Number of added edge nodes\npColors=gjet(numel(n));\n\ncFigure; \nfor q=1:1:numel(n)\n    [Fs,Vs]=subtri(F,V,n(q)); \n    subplot(2,2,q); hold on;\n    title([num2str(n(q)),' added edge nodes'],'FontSize',fontSize);\n    gpatch(Fs,Vs,pColors(q,:),'k');\n    plotV(Vs,'k.','markerSize',markerSize2); \n    plotV(V,'k.','markerSize',markerSize);    \n    axisGeom(gca,fontSize);\n    camlight headlight;    \nend\ndrawnow; \n\n%% Refining triangulated surfaces in general\n\n[F,V]=geoSphere(1,1);\n\nn=[0 1 2 3]; %Number of added edge nodes\npColors=gjet(numel(n));\n\ncFigure; \nfor q=1:1:numel(n)\n    [Fs,Vs]=subtri(F,V,n(q)); \n    subplot(2,2,q); hold on;\n    title([num2str(n(q)),' added edge nodes'],'FontSize',fontSize);\n    gpatch(Fs,Vs,pColors(q,:),'k');    \n    axisGeom(gca,fontSize);\n    camlight headlight;     \nend\ndrawnow; \n\n%% \n%\n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_subtri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.5914844029116406}}
{"text": "function determ = neumann_determinant ( row_num, col_num )\n\n%*****************************************************************************80\n%\n%% NEUMANN_DETERMINANT returns the determinant of the NEUMANN matrix.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    17 October 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer ROW_NUM, COL_NUM, the number of rows and columns in the grid.\n%\n%    Output, real DETERM, the determinant.\n%\n  determ = 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_mat/neumann_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.5914587697751672}}
{"text": "% NANMAX Maximum value, ignoring NaNs.\n%    M = NANMAX(A) returns the maximum of A with NaNs treated as missing. \n%    For vectors, M is the largest non-NaN element in A.  For matrices, M is\n%    a row vector containing the maximum non-NaN element from each column.\n%    For N-D arrays, NANMAX operates along the first non-singleton\n%    dimension.\n% \n%    [M,NDX] = NANMAX(A) returns the indices of the maximum values in A.  If\n%    the values along the first non-singleton dimension contain more than\n%    one maximal element, the index of the first one is returned.\n%   \n%    M = NANMAX(A,B) returns an array the same size as A and B with the\n%    largest elements taken from A or B.  Either one can be a scalar.\n% \n%    [M,NDX] = NANMAX(A,[],DIM) operates along the dimension DIM.\n% \n%    See also MAX, NANMIN, NANMEAN, NANMEDIAN, NANMIN, NANVAR, NANSTD.\n%\n%    Reference page in Doc Center\n%       doc stats/nanmax\n%\n%    Other functions named nanmax\n%\n%       distributed/nanmax    fints/nanmax\n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/m/+utils/+stat/nanmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.5914587578079559}}
{"text": "function [ y, symm ] = cvx_s_upper_hankel( m, n, symm )\n\n% CVX_S_UPPER_HANKEL Upper Hankel matrices.\n\nc  = 0 : n - 1;\nc  = c( ones( 1, m ), : );\nr  = ( 0 : m - 1 )';\nr  = r( :, ones( 1, n ) );\nv  = abs( r + c ) + 1;\ntemp = v <= min( m, n );\ny = sparse( v( temp ), r( temp ) + m * c( temp ) + 1, 1, min( m, n ), m * n );\nsymm = false;\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/structures/cvx_s_upper_hankel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.591458757612303}}
{"text": "% most of the time. they both this and pcasvd takes about the same time\n% when smallest = 0, this should be faster but it's not always\n% when it's 1, due to null(U1'), it prob slows it down but not always\nfunction [U,d] = pcaeig(X,n,smallest)\n% X : nt x n, where nt examples of feature vecs of size n\n% n returns n dimensions\n% smallest = 1 when we want the n evecs assoc with the smallest\n% evals\n% U is evecs, d is diagonals\n% Copyright (c) 2013, Vipin Vijayan.\nif size(X,1) < size(X,2)\n    [U,D] = eig(X*X');\n    d = diag(D);\n    [~,ix] = sort(d,'descend');\n    U = U(:,ix);\n    d = d(ix);\nelse\n    [V,D1] = eig(X'*X);\n    d1 = diag(D1);\n    [~,ix] = sort(d1,'descend');\n    V = V(:,ix);\n    d1 = d1(ix);\n    U1 = X*V; % go from evecs of X'*X to evecs of X*X'\n    for ni = 1:size(U1,2), U1(:,ni) = U1(:,ni)./norm(U1(:,ni)); end\n    if ~smallest\n        U = U1;\n        d = d1;\n    else\n        U2 = null(U1'); % this runs svd on U1'\n        U = [U1 U2];\n        d = [d1 ; zeros(size(U2,2),1)];\n    end\nend\nif ~smallest,\n    tol = eps(class(X));\n    n = min(n, sum(d > tol));\n    U = U(:,1:n);\n    d = d(1:n);\nelse\n    n = min(n,size(U,2));\n    U = U(:,end:-1:end-n+1);\n    d = max(0,d);\n    d = d(end:-1:end-n+1);\nend\n% D = diag(d);\nend\n\n\n% very slow with large dimensions\nfunction [U,d] = pcaeigslow(X,n,smallest)\n[U,D] = eig(X*X');\nd = diag(D);\n[~,ix] = sort(d,'descend');\nU = U(:,ix);\nd = d(ix);\nif ~smallest,\n    tol = eps(class(X));\n    n = min(n, sum(diag(D) > tol));\n    U = U(:,1:n);\n    d = d(1:n);\nelse\n    n = min(n,size(U,2));\n    U = U(:,end:-1:end-n+1);\n    d = abs(diag(D));\n    d = d(end:-1:end-n+1);\nend\n% D = diag(d);\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/41379-direct-lda-and-pca+lda/directlda/pcaeig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5914558329286878}}
{"text": "function g = mlpderiv(net, x)\n%MLPDERIV Evaluate derivatives of network outputs with respect to weights.\n%\n%\tDescription\n%\tG = MLPDERIV(NET, X) takes a network data structure NET and a matrix\n%\tof input vectors X and returns a three-index matrix G whose I, J, K\n%\telement contains the derivative of network output K with respect to\n%\tweight or bias parameter J for input pattern I. The ordering of the\n%\tweight and bias parameters is defined by MLPUNPAK.\n%\n%\tSee also\n%\tMLP, MLPPAK, MLPGRAD, MLPBKP\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n% Check arguments for consistency\nerrstring = consist(net, 'mlp', x);\nif ~isempty(errstring);\n  error(errstring);\nend\n\n[y, z] = mlpfwd(net, x);\n\nndata = size(x, 1);\n\nif isfield(net, 'mask')\n  nwts = size(find(net.mask), 1);\n  temp = zeros(1, net.nwts);\nelse\n  nwts = net.nwts;\nend\n\ng = zeros(ndata, nwts, net.nout);\nfor k = 1 : net.nout\n  delta = zeros(1, net.nout);\n  delta(1, k) = 1;\n  for n = 1 : ndata\n    if isfield(net, 'mask')\n      temp = mlpbkp(net, x(n, :), z(n, :), delta);\n      g(n, :, k) = temp(logical(net.mask));\n    else\n      g(n, :, k) = mlpbkp(net, x(n, :), z(n, :),...\n\tdelta);\n    end\n  end\nend\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/mlpderiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5914558280462355}}
{"text": "classdef CF8 < PROBLEM\n% <multi> <real> <large/none> <constrained>\n% Constrained benchmark MOP\n\n%------------------------------- Reference --------------------------------\n% Q. Zhang, A. Zhou, S. Zhao, P. N. Suganthan, W. Liu, and S. Tiwari,\n% Multiobjective optimization test instances for the CEC 2009 special\n% session and competition, School of CS & EE, University of Essex, Working\n% Report CES-487, 2009.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 3;\n            if isempty(obj.D); obj.D = 10; end\n            obj.lower    = [0,0,zeros(1,obj.D-2)-4];\n            obj.upper    = [1,1,zeros(1,obj.D-2)+4];\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values and constraint violations\n        function Population = Evaluation(obj,varargin)\n            X  = varargin{1};\n            X  = max(min(X,repmat(obj.upper,size(X,1),1)),repmat(obj.lower,size(X,1),1));\n            D  = size(X,2);\n            J1 = 4 : 3 : D;\n            J2 = 5 : 3 : D;\n            J3 = 3 : 3 : D;\n            Y  = X - 2*repmat(X(:,2),1,D).*sin(2*pi*repmat(X(:,1),1,D)+repmat(1:D,size(X,1),1)*pi/D);\n            PopObj(:,1) = cos(0.5*X(:,1)*pi).*cos(0.5*X(:,2)*pi) + 2*mean(Y(:,J1).^2,2);\n            PopObj(:,2) = cos(0.5*X(:,1)*pi).*sin(0.5*X(:,2)*pi) + 2*mean(Y(:,J2).^2,2);\n            PopObj(:,3) = sin(0.5*X(:,1)*pi)                     + 2*mean(Y(:,J3).^2,2);\n            PopCon      = 1 - (PopObj(:,1).^2+PopObj(:,2).^2)./(1-PopObj(:,3).^2) + 4*abs(sin(2*pi*((PopObj(:,1).^2-PopObj(:,2).^2)./(1-PopObj(:,3).^2)+1)));\n            Population  = SOLUTION(X,PopObj,PopCon,varargin{2:end});\n            obj.FE      = obj.FE + length(Population);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            N      = ceil(N/5)*5;\n            R      = zeros(N,3);\n            R(:,3) = repmat(sin((0:1/(N/5-1):1).*pi/2)',5,1);\n            for i = 0 : 4\n                R(i*N/5+1:(i+1)*N/5,1) = sqrt(i/4*(1-R(i*N/5+1:(i+1)*N/5,3).^2));\n            end\n            R(:,2) = sqrt(max(1-R(:,1).^2-R(:,3).^2,0));\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/CF/CF8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5914558249359183}}
{"text": "%  INTERNAL FUNCTION: doubling_solve solves the linear equation X=A*X*B+C using doubling algorithm\n% \n%  ::\n% \n%     [P,retcode]=doubling(A,B,C);\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/classes/models/+vartools/doubling.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5914558174784216}}
{"text": "function [network, mappedX, reconX] = train_autoencoder(X, layers, noise, max_iter)\n%TRAIN_AUTOENCODER Trains an simple autoencoder\n%\n%   [network, mappedX, reconX] = train_encoder(X, layers, noise, max_iter)\n%\n% Trains up an autoencoder with the structure that is specified in layers. \n% The low-dimensional data is returned in mappedX, and the network in\n% network. The variable noise indicates how much of the input data should be\n% blacked out (default = 0).\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 nargin < 2\n        error('Not enough inputs.');\n    end\n    if isempty(layers)\n        error('There should be at least one hidden layer.');\n    end\n    if ~exist('noise', 'var') || isempty(noise)\n        noise = 0;\n    end\n    if ~exist('max_iter', 'var') || isempty(max_iter)\n        max_iter = 50;\n    end\n    \n    % Initialize the network\n    D = size(X, 2);\n    no_layers = length(layers) + 1;\n    network = cell(no_layers, 1);\n    network{1}.W = randn(D, layers(1)) * .0001;\n    network{1}.bias_upW = zeros(1, layers(1));\n    for i=2:no_layers - 1\n        network{i}.W = randn(layers(i - 1), layers(i)) * .0001;\n        network{i}.bias_upW = zeros(1, layers(i));\n    end\n    network{no_layers}.W = randn(layers(end), D) * .0001;\n    network{no_layers}.bias_upW = zeros(1, D);\n    reconX = run_data_through_autoenc(network, X);\n    disp(['Initial MSE of reconstructions: ' num2str(mean((X(:) - reconX(:)) .^ 2))]);    \n    \n    % Perform backpropagation to minimize reconstruction error\n    network = backprop(network, X, X, max_iter, noise);\n    \n    % Get representation from hidden layer\n    [reconX, mappedX] = run_data_through_autoenc(network, X);\n    disp(['Final MSE of reconstructions: ' num2str(mean((X(:) - reconX(:)) .^ 2))]);\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/train_autoencoder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5914494622771713}}
{"text": "\n%%\n% Auther : Gaul Swapnil Narhari,\n% Developed @ IIT Kharagpur, India.\n% In collaborationwith TaraNG, India.\n%%\n% for optimization see 'pso.m' file for fitness function defination see 'simple_fitness.m'\n%%\nclc;\nclear all;\nObjectiveFunction = @simple_fitness;\nnvars = 3;    % Number of variables\nLB = [0 0 0];   % Lower bound\nUB = [3 5 10];  % Upper bound\nPopln=20;\nGenrtn=50;\nWByn=1;\n[x,fvalue] = pso(ObjectiveFunction,'NumVar',nvars,'LowerBound',LB,'UpperBound',UB,'Population',Popln,'Genrations',Genrtn,'IncludeWB',WByn);\ndisp(x);\ndisp(fvalue);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/40609-optimization-using-particle-swarm/PSO_TaraNG/Main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5914494589986085}}
{"text": "function test11\n%TEST11 test cs_rowcnt\n%\n% Example:\n%   test11\n% See also: testall\n\n%   Copyright 2006-2007, Timothy A. Davis.\n%   http://www.cise.ufl.edu/research/sparse\n\nclear functions\nindex = UFget ;\n[ignore f] = sort (max (index.nrows, index.ncols)) ;\nf = f (1:200) ;\n\nfor i = f\n    Prob = UFget (i, index) ;\n    disp (Prob) ;\n    A = Prob.A ;\n    [m n] = size (A) ;\n    if (~isreal (A) | m ~= n)                                               %#ok\n        continue\n    end\n\n    A = spones (A) ;\n    A = A+A' + speye(n) ;\n\n    [cc h pa po R] = symbfact (A) ;\n    rc1 = full (sum (R)) ;\n    rc2 = cs_rowcnt (A, pa, po) ;\n    if (any (rc1 ~= rc2))\n        error ('!') ;\n    end\n\n    try\n        p = amd (A) ;\n    catch\n        p = symamd (A) ;\n    end\n    A = A (p,p) ;\n\n    [cc h pa po R] = symbfact (A) ;\n    rc1 = full (sum (R)) ;\n    rc2 = cs_rowcnt (A, pa, po) ;\n    if (any (rc1 ~= rc2))\n        error ('!') ;\n    end\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/CSparse/MATLAB/Test/test11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.5914494450431688}}
{"text": "function [coeff,RMSout]=FitLaw_GA(X,y,fh,Int,LB,UB)\n%\n% function [coeff,RMSout]=FitLaw_GA(X,y,fh,Int,LB,UB)\n%\n% The script fits a given general analytical law using Genetic Algorithms.\n% Such law can depend on several input variables and various parameters,\n% but it must have only one output, to be matched to the input variable y.\n% The optimum coefficients are derived using an optimization based on the\n% Genetic Algorithm.\n%\n% INPUT\n%   X = matrix containing the values of the indipendent variables of the\n%       function. Each column refers to a variable\n%   y = target values to be matched by the function (row vector)\n%   fh = handle of the function to be fitted to y and whose parameters have\n%        to be optimized\n%   Int = initial interval of the parameters to be optmized. Column i of\n%         the matrix refer to parameter i\n%   LB,UB = vectors defining the lower and upper bounds never to be\n%           exceeded by the parameters. Position i of the vectors refer to\n%           parameter i.\n%\n% OUTPUT\n%   coeff = parameters providing the best fitting\n%   RMSout = lowest RMS of the fitting error\n%\n% EXAMPLE OF USAGE\n%   Suppose one wants to fit to y the function p=x.*(1-exp(-a.*w+b.*z)),\n%   where (x,w,z) are the indipendent variables and (a,b) are the\n%   parameters to be determined. It is first necessary to define the handle\n%   to the function p before calling the optimization function. This is\n%   done as follows:\n%\n%      fh=@(X,par) X(:,1)'.*(1-exp(-par(1).*X(:,2)'+par(2).*X(:,3)'))\n%\n%   Afterwards, the callback of the function would be:\n%\n%   [coeff,RMSout]=FitLaw_GA([x' w' z'],y,fh,[-5 -5; 5 5],[-10 10],[10 10])\n%\n%   Note that since fh has been defined considering that each variable is\n%   assigned to each column of the matrix X, then X in the callback has to\n%   be in such form (as in the example). y is a row vector containing the\n%   target values of the function to be fitted. [-5 -5; 5 5] defines the\n%   initial intervals in which the parameters are sampled when the\n%   algorithm starts. Specifically, column i of the matrix Int contains the\n%   lower and upper limits for parameter i. However, as the algorithm\n%   proceeds, the parameters may exceed such intervals. That is why lower\n%   and upper bounds can be introduced to limit the acceptable values of\n%   the parameters (in this example, both paramaters are such that\n%   -10 < a,b < 10).\n%   \n%   To improve the fitting power, increase the variables PopSize and Iter\n%   defined below in the cell GENETIC ALGORITHM OPTIONS. Specifically,\n%   a high value of PopSize provides a higher probability to avoid local\n%   minima in the optimization procedure, while a high value of Iter\n%   permits a proper convergence of the algorithm.\n%   Obviously, high values of those variables imply longer calculation\n%   times.\n%\n% By: L.Luini\n\n%% GENETIC ALGORITHM OPTIONS\nPopSize=200;   % population size (default==200)\nIter=100;   % number of iterations of the algorithm (default==100)\nMigrInt=Iter/10;   % migration interval\nFig=1;   % if Fig==1, plot optimization results\n\n%% RUN THE GENETIC ALGORITHM\nnumPar=size(Int,2);\noptions=gaoptimset('PlotFcns',{@gaplotbestf,@gaplotbestindiv}, ...\n    'PopInitRange',Int, ...\n    'PopulationSize',PopSize,'MigrationInterval',MigrInt, ...\n    'StallGenLimit',Inf,'StallTimeLimit',Inf,'Generations',Iter);\ncoeff=ga(@FitFcn,numPar,[],[],[],[],LB,UB,[],options);\nest=fh(X,coeff);\nerror=100.*(est-y)./y;\nRMSout=sqrt(mean(error).^2+std(error).^2);\n\n% plot results if the function depends only on 1 variable\nif Fig==1&&numPar==1\n    figure\n    plot(X,y,'b','LineWidth',1.5)\n    hold on;grid on;\n    plot(X,est,'r','LineWidth',1.5)\n    legend('Input data','Fitting curve')\n    grid\nend\n\n    function fitness=FitFcn(param)\n\n        % Fitness function definition: RMS of the error        \n        est=fh(X,param);\n        error=100.*(est-y)./y;   % definition of the error\n        fitness=sqrt(mean(error).^2+std(error).^2);\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/19374-fitting-complex-analytic-laws-to-data-by-means-of-genetic-algorithms/FitLaw_GA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012105, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5914494419886925}}
{"text": "% Copyright (C) 2007 Peter Carbonetto. All Rights Reserved.\n% This code is published under the Eclipse Public License.\n%\n% Author: Peter Carbonetto\n%         Dept. of Computer Science\n%         University of British Columbia\n%         May 19, 2007\n\nfunction [dR, dS] = computeJGGradient (qR, qS, auxdata)\n  [K C f Rv Rf Sv Sf NS d] = deal(auxdata{:});\n  \n  nr = length(Rv);   % The number of large regions.\n  ns = length(Sv);   % The number of small regions.\n\n  % Reshape the input vectors.\n  qR = reshapemarginals(qR,Rv,K);\n  qS = reshapemarginals(qS,Sv,K);\n  \n  % Compute the gradient terms for the large regions. Repeat for each\n  % large region.\n  dR = cell(1,nr);\n  for r = 1:nr\n    is    = Rv{r};  % The variable nodes in the large region.\n    table = 1 ./ qR{r};\n    \n    % Multiply the table by all the factors in the large region.\n    for j = Rf{r}\n      table = multiplyfactors(table,is,f{j},C{j});\n    end\n    \n    dR{r} = -log(table) + 1;\n  end\n  \n  % Compute the gradient terms for the small regions. Repeat for each\n  % small region.\n  dS = cell(1,ns);\n  for s = 1:ns\n    is    = Sv{s};  % The variable nodes in the small region.\n    table = 1 ./ qS{s};\n\n    % Multiply the table by all the factors in the small region.\n    for j = Sf{s}\n      table = multiplyfactors(table,is,f{j},C{j});\n    end\n\n    dS{s} = (1 - d(s)) * (-log(table) + 1);\n  end\n  \n  % Convert the computed gradients into vectors.\n  dR = vectorize(dR);\n  dS = vectorize(dS);\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/Solvers/ipopt/distribution/examples/bayesnet/computeJGGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5914494389342162}}
{"text": "function  varargout = partitionData(Ndata, varargin)\n% PARTITIONDATA Partition a vector of indices into random sets\n% [a,b,c,...] = partitionData(N, 0.3, 0.2, 0.5, ...)\n%\n% Examples:\n% [a,b,c]=partitionData(105,0.3,0.2,0.5);\n% a= 1:30, b=32:52, c=52:105 (last bin gets all the left over)\n\nNpartitions = length(varargin);\nperm = randperm(Ndata);\n%perm = 1:Ndata;\nndx = 1;\nfor i=1:Npartitions\n  pc(i) = varargin{i};\n  Nbin(i) = fix(Ndata*pc(i));\n  low(i) = ndx;\n  if i==Npartitions\n    high(i) = Ndata;\n  else\n    high(i) = low(i)+Nbin(i)-1;\n  end\n  varargout{i} = perm(low(i):high(i));\n  ndx = ndx+Nbin(i);\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/KPMtools/partitionData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.805632207648114, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5914303445070005}}
{"text": "function value = year_is_leap_bahai ( y )\n\n%*****************************************************************************80\n%\n%% YEAR_IS_LEAP_BAHAI returns TRUE if the Bahai year was a leap year.\n%\n%  Discussion:\n%\n%    The leap year rules are the same as those used in the Gregorian\n%    calendar.\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 a leap year,\n%    FALSE otherwise.\n%\n  if ( y <= 0 )\n    value = 0;\n    return\n  end\n\n  if ( mod ( y, 400 ) == 0 )\n    value = 1;\n  elseif ( mod ( y, 100 ) == 0 )\n    value = 0;\n  elseif ( mod ( y, 4 ) == 0 )\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_leap_bahai.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.5914303180045515}}
{"text": "classdef Derivative < Algorithm\n    \n    properties (Access = public)    \n        order = 1;\n        delta = 1;\n        inPlaceComputation = true;\n    end\n    \n    methods (Access = public)\n        function obj = Derivative(order, delta)\n            if nargin > 0\n                obj.order = order;\n                if nargin > 1\n                    obj.delta = delta;\n                end\n            end\n            obj.name = 'derivative';\n            obj.inputPort = DataType.kSignal;\n            obj.outputPort = DataType.kSignal;\n        end\n        \n        function derivative = compute(obj, data)\n            if size(data,1) == 1\n                derivative = data;\n            else\n                if obj.order == 1\n                    derivative = obj.computeFirstOrderDerivative(data);\n                elseif obj.order == 2\n                    derivative = obj.computeSecondOrderDerivative(data);\n                else\n                    derivative = [];\n                end\n            end\n        end\n        \n        function derivative = computeFirstOrderDerivative(obj,data)\n            n = length(data);\n            derivative = zeros(n,1);\n            for i = 2 : n\n                derivative(i) = (data(i) - data(i-1)) / obj.delta;\n            end\n        end\n        \n        function derivative = computeSecondOrderDerivative(obj,data)\n            n = length(data);\n            derivative = zeros(n,1);\n            \n            derivative(1) = (data(2) - data(1)) / obj.delta;\n            derivative(n) = (data(n) - data(n-1)) / obj.delta;\n            \n            deltaSquared = obj.delta * obj.delta;\n            for i = 2 : n-1\n                derivative(i) = (data(i-1) - data(i) + data(i+1)) / deltaSquared;\n            end\n        end\n        \n        function str = toString(obj)\n            str = sprintf('%s_%d_%.2f',obj.name,obj.order,obj.delta);\n        end\n        \n        function editableProperties = getEditableProperties(obj)\n            property1 = Property('order',obj.order,1,2);\n            property2 = Property('delta',obj.delta);\n            editableProperties = [property1,property2];\n        end\n        \n        function metrics = computeMetrics(obj,input)\n            n = size(input,1);\n            flops = 6 * obj.order * size(input,1);\n            if obj.inPlaceComputation\n                memory = 1;\n            else\n                memory = n * Constants.kSensorDataBytes;\n            end\n            outputSize = n * Constants.kSensorDataBytes;\n            metrics = Metric(flops,memory,outputSize);\n        end\n    end\nend\n", "meta": {"author": "avenix", "repo": "WDK", "sha": "c525222b02bd390b4758d30f1cd8b19af043108e", "save_path": "github-repos/MATLAB/avenix-WDK", "path": "github-repos/MATLAB/avenix-WDK/WDK-c525222b02bd390b4758d30f1cd8b19af043108e/ARC/algorithm/2-preprocessing/Derivative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5914078258561493}}
{"text": "classdef Norm_DCF_Plot < handle\n% This class is for plotting normalized DCF curves from the \n% scores of a given detector, as a function of the effective target\n% prior. The DCF is parametrized by the prior and has unity cost\n% for both misses and false alarms. The algorithms to compute DCF\n% have been optimized to allow the use of large score sets, in\n% order to be able to obtain meaningful results at extreme\n% operating points.\n%\n% There are six curves that can be plotted: \n% (i) minimum DCF, where the evaluator chooses the optimal decision \n%     threshold at every operating point. (The operating point is defined \n%     by the effective target prior).\n% (ii) actual DCF, where the decision threshold is the \n%      minimum-probability-of-error Bayes decision threshold, assuming that\n%      the given detector scores are log-likelihood-ratios. This decision\n%      threshold is just -logit(Ptar). \n% (iii) actual misses, the component of actual DCF due to miss errors.\n% (iv) actual false alarms, the component of actual DCF due to false-alarm errors.\n% (v) minimum misses, the component of minimum DCF due to miss errors.\n% (vi) miniumu false alarms, the component of minimum DCF due to false-alarm errors.\n%\n% All curves are normalized by dividing by the DCF of the default system \n% that makes decisions based on the prior alone. The normalization is\n% min(Ptar,1-Ptar).\n%\n% The x-axis is logit(Ptar) = log(Ptar) - log(1-Ptar). The logit\n% transformation maps the effective target prior to the whole\n% extended real line from -inf to inf, but this plot is confined to\n% the given limits xmin and xmax.\n% \n% For more information on DCF, type:\n% > help fast_actDCF\n% > help fast_minDCF\n%\n% Use set_system with the target and non-target scores for a system\n% before calling the plotting functions.  The curves plotted will\n% all be for the current set system.  Curves for more than one\n% system can be plotted by calling set_system for the first system,\n% plotting all of its curves and points of interest, calling\n% set_system for the second system, plotting, etc.\n%\n% Inputs: \n%    plot_axes: [xmin,xmax,ymin,ymax]: the range for the x-axis and\n%      y-axis of this plot, where x = logit(Ptar).\n%\n%    plot_title: An optional title string for the plot.\n%\n\nproperties (Access = private)\n  fh\n  plot_axes\n  sys_name\n  plo\n  actDCF\n  actPmiss\n  actPfa\n  minDCF\n  minPmiss\n  minPfa\n  dr30Miss\n  dr30FA\n  Ptar_norm\n  Pnon_norm\n  handles_vec\n  legend_strings = {};\nend\n\nmethods (Access = public)\n  set_system(plot_obj,tar,non,sys_name)\n  set_system_from_scores(plot_obj,scores,key,sys_name)\n  plot_fa_rate_min(plot_obj,plot_args,legend_string)\n  plot_fa_rate_act(plot_obj,plot_args,legend_string)\n  plot_miss_rate_min(plot_obj,plot_args,legend_string)\n  plot_miss_rate_act(plot_obj,plot_args,legend_string)\n  plot_dcf_curve_min(plot_obj,plot_args,legend_string)\n  plot_dcf_curve_act(plot_obj,plot_args,legend_string)\n  plot_DR30_fa(plot_obj,plot_args,legend_string)\n  plot_DR30_miss(plot_obj,plot_args,legend_string)\n  plot_DR30_both(plot_obj,plot_args_fa,plot_args_miss)\n  plot_curves(plot_obj,mask,line_info)\n  plot_operating_point(plot_obj,value,plot_args,legend_string)\n  display_legend(plot_obj)\n  save_as_pdf(plot_obj,outfilename)\nend\n\nmethods (Access = public)\n  % plot_obj = Norm_DCF_Plot()\n  % plot_obj = Norm_DCF_Plot(plot_axes)\n  % plot_obj = Norm_DCF_Plot(plot_axes,plot_title)\n  function plot_obj = Norm_DCF_Plot(plot_axes,plot_title)\n  % constructor\n  if exist('plot_axes','var') && ~isempty(plot_axes)\n    assert(length(plot_axes)==4)\n    plot_obj.plot_axes = plot_axes;\n  else\n    plot_obj.plot_axes = [-10,0,0,1.2];\n  end\n  xmin = plot_obj.plot_axes(1);\n  xmax = plot_obj.plot_axes(2);\n  assert(xmin<xmax,'Illegal parameters xmin and xmax.')\n  step = (xmax-xmin)/1000;\n  plot_obj.plo = xmin:step:xmax;\n  Ptar = sigmoid(plot_obj.plo);\n  Pnon = sigmoid(-plot_obj.plo);\n  refPe = min(Ptar,Pnon);\n  plot_obj.Ptar_norm = Ptar ./ refPe;\n  plot_obj.Pnon_norm = Pnon ./ refPe;\n  plot_obj.actDCF = [];\n  plot_obj.handles_vec = [];\n  plot_obj.legend_strings = {};\n  \n  plot_obj.fh = figure();\n  hold on\n  ylabel('normalized DCF');\n  xlabel('logit P_{tar}');\n  grid\n  axis(plot_obj.plot_axes);\n  if exist('plot_title','var') && ~isempty(plot_title)\n    title(plot_title);\n  end    \n  end\nend\n\nmethods (Access = private)\n  add_legend_entry(plot_obj,lh,legend_string,append_name)\n  plot_miss_rate(plot_obj,Pmiss,plot_args,legend_string)\n  plot_fa_rate(plot_obj,Pfa,plot_args,legend_string)\n  plot_dcf_curve(plot_obj,dcf,plot_args,legend_string)\nend\n\nend\n", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/tDCF_v1/bosaris_toolkit.1.06/bosaris_toolkit/classes/@Norm_DCF_Plot/Norm_DCF_Plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5914078255234049}}
{"text": "function [col,bol,msz] = spm_MB_col(n)\n% FORMAT [col,bol,msz] = spm_MB_col(n)\n% Return colours and marker size for number of partitions\n% n  - number of partitions\n%__________________________________________________________________________\n% Copyright (C) 2019-2020 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_MB_col.m 7768 2020-01-07 11:37:19Z spm $\n\n% Marker colour and size\n%--------------------------------------------------------------------------\ns = rand('twister');\nrand('twister',1);\nmsz   = fix(16 + 64/n);\nfor k = 1:n\n    bol{k} = spm_softmax(log(rand(3,1))*2);\n    col{k} = bol{k}*(1 - 1/2) + ones(3,1)/2;\nend\nrand('twister',s);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_MB_col.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5914078153701393}}
{"text": "function [k, sk, n2] = rbfperiodic2KernCompute(kern, x, x2)\n\n% RBFPERIODIC2KERNCOMPUTE Compute the RBFPERIODIC2 kernel given the parameters and X.\n% FORMAT\n% DESC computes the kernel parameters for the RBF periodic covariance with variying period\n% kernel given inputs associated with rows and columns.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x : the input matrix associated with the rows of the kernel.\n% ARG x2 : the input matrix associated with the columns of the kernel.\n% RETURN k : the kernel matrix computed at the given points.\n%\n% FORMAT\n% DESC computes the kernel matrix for the RBF periodic covariance with variying period\n% kernel given a design matrix of inputs.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x : input data matrix in the form of a design matrix.\n% RETURN k : the kernel matrix computed at the given points.\n%\n% SEEALSO : rbfperiodic2KernParamInit, kernCompute, kernCreate, rbfperiodic2KernDiagCompute\n%\n% COPYRIGHT : Neil D. Lawrence, 2007, 2009\n%\n% MODIFICATIONS : Andreas C. Damianou, 2011\n%\n% MODIFICATIONS : Michalis K. Titsias, 2011\n\n% KERN\n\nfactor = kern.factor; % Default (if period is fixed: 2*pi/kern.period)\nif nargin < 3\n  n2 = sin(0.5*factor*(repmat(x, 1, size(x, 1)) - repmat(x', size(x, 1), 1)));\n  n2 = n2.*n2;\n  wi2 = (2 .* kern.inverseWidth);\n  sk = exp(-n2*wi2);\nelse\n  n2 = sin(0.5*factor*(repmat(x, 1, size(x2, 1)) - repmat(x2', size(x, 1), 1)));  \n  n2 = n2.*n2;\n  wi2 = (2 .* kern.inverseWidth);\n  sk = exp(-n2*wi2);\nend\nk = kern.variance*sk;\n% Test kernel with: kernTest('rbfperiodic2',1)\n\n  \n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/rbfperiodic2KernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5914078091289012}}
{"text": "function [X, R, S] = snapshot_gen_sym(design, doas, wavelength, stype, t, ncov, sp)\n%SNAPSHOT_GEN_SYM Generates snapshots from symbols.\n%Syntax:\n%   X = SNAPSHOT_GEN_SYM(design, doas, wavelength, stype[, t, ncov, sp]);\n%   [X, R] = SNAPSHOT_GEN_SYM(design, doas, wavelength, stype[, t, ncov, sp]);\n%   [X, R, S] = SNAPSHOT_GEN_SYM(design, doas, wavelength, stype[, t, ncov, sp]);\n%Inputs:\n%   design - Array design.\n%   doas - DOA vector. For 2D DOAs, each column represents a DOA pair.\n%   wavelength - Wavelength.\n%   stype - Symbol type.\n%   t - Number of snapshots.\n%   ncov - Covariance matrix of the additive complex circular-symmetric\n%          Gaussian noise. Can be a scalar, vector (for uncorrelated noise\n%          with different powers), or a matrix.\n%   sp - Sources powers. \n%Outputs:\n%   X - Snapshots, where each columns is a single snapshot.\n%   R - Sample covariance matrix (averaged by the number of snapshots).\n%   S - A source_count x snapshot_count matrix consists of source signal\n%       vectors.\nif nargin <= 6\n    sp = 1;\nend\nif nargin <= 5\n    ncov = 1;\nend\nif nargin <= 4\n    t = 1;\nend\nA = steering_matrix(design, wavelength, doas);\n[m, k] = size(A);\nS_internal = gen_symbols(k, t, stype, sp);\nX = A * S_internal + gen_ccsg(m, t, ncov);\nif nargout >= 2\n    R = (X*X')/t;\n    if nargout == 3\n        S = S_internal;\n    end\nend\nend\n\nfunction S = gen_symbols(m, n, stype, sp)\nswitch lower(stype)\n    case 'bpsk'\n        symbols = [-1 1];\n    case 'qpsk'\n        symbols = exp(1j*[1 3 5 7]/4*pi);\n    otherwise\n        error('Unsupported symbol type.')\nend\nS = symbols(randi([1 length(symbols)], m, n));\nif isscalar(sp)\n    S = sqrt(sp) * S;\nelse\n    S = bsxfun(@times, sqrt(sp(:)), S);\nend\nend\n\nfunction X = gen_ccsg(m, n, cov)\nX0 = randn(m, n) + 1j * randn(m, n);\nif isscalar(cov)\n    X = sqrt(cov/2) * X0;\nelseif isvector(cov)\n    X = bsxfun(@times, X0, cov(:));\nelse\n    C = sqrtm(cov/2);\n    X = C*X0;\nend\nend", "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/array/snapshot_gen_sym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.591407804218641}}
{"text": "function [u, erriter, i, timet] = CMF_Cut\n%\n%   Performing the continuous max-flow algorithm to solve the \n%   continuous min-cut problem in 2D\n%    \n%   Usage: [u, erriter, i, timet] = CMF_Cut;\n%\n%   Inputs: there is no input since all data and parameters can be\n%           adjusted within the program\n%\n%   Outputs: \n%       - u: the final results u(x) in [0,1]. As the following paper,\n%           the global binary result can be available by threshholding u\n%           by any constant alpha in (0,1):\n%\n%           Nikolova, M.; Esedoglu, S.; Chan, T. F. \n%           Algorithms for Finding Global Minimizers of Image Segmentation and Denoising Models \n%           SIAM J. App. Math., 2006, 66, 1632-1648\n%\n%       - erriter: it returns the error evaluation of each iteration,\n%           i.e. it shows the convergence rate. One can check the algorithm\n%           performance.\n%\n%       - i: gives the total number of iterations, when the algorithm converges.\n%\n%       - timet: gives the total computation time.\n%       \n%   Example:\n%       >> [u, erriter, i, timet] = CMF_Cut;\n%\n%       >> us = max(u, beta);  % where beta in (0,1)\n%\n%       >> imagesc(us), colormap gray, axis image, axis off;figure(gcf)\n%\n%       >> figure, loglog(erriter,'DisplayName','erriterN');figure(gcf)\n%\n%\n%           \n%   The original algorithm was proposed in the following papers:\n%\n%   [1] Yuan, J.; Bae, E.;  Tai, X.-C. \n%       A Study on Continuous Max-Flow and Min-Cut Approaches \n%       CVPR, 2010\n%\n%   [2] Yuan, J.; Bae, E.; Tai, X.-C.; Boycov, Y.\n%       A study on continuous max-flow and min-cut approaches. Part I: Binary labeling\n%       UCLA CAM, Technical Report 10-61, 2010\n%\n%   The mimetic finite-difference discretization method was proposed for \n%   the total-variation function in the paper:\n%\n%   [1] Yuan, J.; Schn{\\\"o}rr, C.; Steidl, G.\n%       Simultaneous Optical Flow Estimation and Decomposition\n%       SIAM J.~Scientific Computing, 2007, vol. 29, page 2283-2304, number 6\n%\n%   This software can be used only for research purposes, you should cite ALL of\n%   the aforementioned papers in any resulting publication.\n%\n%   Please email cn.yuanjing@gmail.com for any questions, suggestions and bug reports\n%\n%   The Software is provided \"as is\", without warranty of any kind.\n%\n%\n%                       Version 1.0\n%           https://sites.google.com/site/wwwjingyuan/       \n%\n%           Copyright 2011 Jing Yuan (cn.yuanjing@gmail.com)      \n%\n\nur = double(imread('cameraman.jpg'))/255;\n\n[rows, cols] = size(ur);\nimgSize = rows*cols;\n\n% define the required parameters:\n%\n%   - alpha: the penalty parameter to the total-variation term.\n%       For the case without incorporating image-edge weights, alpha is given\n%       by the constant everywhere. For the case with image-edge weights,\n%       alpha is given by the pixelwise weight function:\n%\n%       For example, alpha(x) = b/(1 + a*| nabla f(x)|) where b and a are positive\n%       constants and |nabla f(x)| gives the strength of the local gradient.\n%\n%   - cc: gives the step-size of the augmented Lagrangian method.\n%       The optimal range of cc is [0.3, 3].\n%\n%   - errbound: the error bound for convergence.\n%\n%   - numIter: the maximum iteration number.\n%\n%   - steps: the step-size for the graident-projection step to the\n%       total-variation function. The optimal range of steps is [0.1,\n%       0.17].\n%\n\nalpha = 0.5*ones(rows,cols); \ncc = 0.3;\nerrbound = 1e-4;\nnumIter = 300;\nsteps = 0.16;\n\n% build up the data terms\nulab(1) = 0.15;\nulab(2) = 0.6;\nCs = abs(ur - ulab(1));\nCt = abs(ur - ulab(2));\n\n% set the initial values\n%   - the initial value of u is set to be an initial cut, see below.\n%   - the initial values of two terminal flows ps and pt are set to be the\n%     specified legal flows.\n%   - the initial value of the spatial flow fiels p = (pp1, pp2) is set to\n%   be zero.\n\nu = double((Cs-Ct) >= 0);\nps = min(Cs, Ct);\npt = ps;\n\npp1 = zeros(rows, cols+1);\npp2 = zeros(rows+1, cols);\ndivp = pp1(:,2:cols+1)-pp1(:,1:cols)+pp2(2:rows+1,:)-pp2(1:rows,:);\n\nerriter = zeros(numIter,1);\n\ntic\nfor i = 1:numIter\n\n\t% update the spatial flow field p = (pp1, pp2):\n    %   the following steps are the gradient descent step with steps as the\n    %   step-size.\n    \n    pts = divp - (ps - pt  + u/cc);\n    pp1(:,2:cols) = pp1(:,2:cols) + steps*(pts(:,2:cols) - pts(:,1:cols-1)); \n    pp2(2:rows,:) = pp2(2:rows,:) + steps*(pts(2:rows,:) - pts(1:rows-1,:));\n    \n    % the following steps give the projection to make |p(x)| <= alpha(x)\n    \n    gk = sqrt((pp1(:,1:cols).^2 + pp1(:,2:cols+1).^2 + pp2(1:rows,:).^2 + pp2(2:rows+1,:).^2)*0.5);\n    gk = double(gk <= alpha) + double(~(gk <= alpha)).*(gk ./ alpha);\n    gk = 1 ./ gk;\n    \n    pp1(:,2:cols) = (0.5*(gk(:,2:cols) + gk(:,1:cols-1))).*pp1(:,2:cols); \n    pp2(2:rows,:) = (0.5*(gk(2:rows,:) + gk(1:rows-1,:))).*pp2(2:rows,:);\n    \n    divp = pp1(:,2:cols+1)-pp1(:,1:cols)+pp2(2:rows+1,:)-pp2(1:rows,:);\n    \n    % updata the source flow ps\n    \n    pts = divp + pt - u/cc + 1/cc;\n    ps = min(pts, Cs);\n    \n    % update the sink flow pt\n    \n    pts = - divp + ps + u/cc;\n    pt = min(pts, Ct);\n\n\t% update the multiplier u\n    \n\terru = cc*(divp + pt  - ps);\n\tu = u - erru;\n    \n    % evaluate the avarage error\n    \n    erriter(i) = sum(sum(abs(erru)))/imgSize; \n   \n    if (erriter(i) < errbound)\n        break;\n    end\nend\ntoc\ntimet = toc\n\nmsg = sprintf('number of iterations = %u. \\n', i);\ndisp(msg);\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/34126-fast-continuous-max-flow-algorithm-to-2d3d-image-segmentation/CMF v1.0/CMF_Cut.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.591389495187229}}
{"text": "function contourdemo\n\n% Demo function for tricontour\n%\n% Darren Engwirda - 2006\n\nclc, close all\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                        Driven Cavity\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nanswer = lower(input(['This is a demo function for tricontour. \\n'                                 ...\n                      '\\n'                                                                         ...\n                      'The following meshes were generated using my mesh generator, \"mesh2d.m\" \\n' ...\n                      'and the data comes from my CFD code \"Navier2d.m\" \\n'                        ...\n                      '\\n'                                                                         ...\n                      'Continue?? [y/n] \\n'],'s'));\n\nif ~strcmp(answer,'y')\n    return\nend\n\nload driven_cavity.mat\n\nnode  = old_data.node;\ncnect = old_data.cnect;\np     = old_data.p;\nt     = old_data.t;\nU     = old_data.U;\nV     = old_data.V;\nP     = old_data.P;\n\nfigure\n\nsubplot(1,2,1), trimesh(t,p(:,1),p(:,2),U), axis square, title('X velocity')\nsubplot(1,2,2), trimesh(t,p(:,1),p(:,2),V), axis square, title('Y velocity')\n\n\nfigure\n\nset(gcf,'Name','The xy velocity components for a box flow')\n\nsubplot(1,2,1), tricontour(p,t,U,15); axis equal, axis off, title('X velocity')\nsubplot(1,2,2), tricontour(p,t,V,15); axis equal, axis off, title('Y velocity')\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                          Tester\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nanswer = lower(input(['As well as making pretty pictures, the correct contouring interval is \\n'  ...\n                      'actually represented. \\n'                                                  ...\n                      '\\n'                                                                        ...\n                      'The following shows the contours of distance from a point at [0.5,0.5] \\n' ...\n                      'The function is correctly showing the contours at a distance of \\n'        ...\n                      '[0.1,0.2,0.3,0.4] \\n'                                                      ...\n                      '\\n'                                                                        ...\n                      'Continue?? [y/n] \\n'],'s'));\n\nif ~strcmp(answer,'y')\n    return\nend\n\nxc = 0.5;\nyc = 0.5;\nd  = sqrt( (p(:,1)-xc).^2+(p(:,2)-yc).^2 );\n\nfigure, trimesh(t,p(:,1),p(:,2),d)\nfigure, [c,h]=tricontour(p,t,d,[0.1,0.2,0.3,0.4]); clabel(c,h), axis equal, grid on, hold on, plot(0.5,0.5,'bx')\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                       Vortex Shedding\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nanswer = lower(input(['The domain can be complex. The following example is a domain with holes. \\n'             ...\n                      '\\n'                                                                                      ...\n                      'The complexity of the domain shouldn''t matter, you just need a valid triangulation. \\n' ...\n                      '\\n'                                                                                      ...\n                      'Continue?? [y/n] \\n'],'s'));\n\nif ~strcmp(answer,'y')\n    return\nend\n\nclose all\n\nload vortex_shedding.mat\n\nnode  = old_data.node;\ncnect = old_data.cnect;\np     = old_data.p;\nt     = old_data.t;\nU     = old_data.U;\nV     = old_data.V;\nP     = old_data.P;\nW     = old_data.W;\n\nfigure\n\ntrimesh(t,p(:,1),p(:,2),U), axis square, title('X velocity')\n\n\nfigure\n\nset(gcf,'Name','The x velocity for the flow over a cylinder')\n\n% Velocity contours\ntricontour(p,t,U,50), axis equal, axis off, title('X velocity')\n\n% Walls\npatch('faces',cnect,'vertices',node,'facecolor','none','edgecolor','k')\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                        Peaks\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nanswer = lower(input(['A standard contouring benchmark showing the operation of clabel. \\n' ...\n                      '\\n'                                                                  ...                                                                                    ...\n                      'Continue?? [y/n] \\n'],'s'));\n\nif ~strcmp(answer,'y')\n    return\nend\n\nclose all\n\n\n[xx,yy] = meshgrid(linspace(-3,3,64),linspace(-2.5,2.5,64));\nzz      = peaks(xx,yy);\nv       = -3:5;\nfigure(1)\n[c,h] = contour(xx,yy,zz,v);\nclabel(c,h)\ntitle('Contour')\n\n% Triangulate\np = [xx(:),yy(:)];\nt = delaunayn(p);\n\nfigure(2)\n[c,h] = tricontour(p,t,zz(:),v);\nclabel(c,h)\ntitle('Tricontour')\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/10408-contours-for-triangular-grids/contour_stuff/contourdemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.591381829383122}}
{"text": "function [ bootql ] = offpolicy_eval_tdlearning( qldata3, physpol, gamma, num_iter )\n% V value averaged over state population\n% hence the difference with mean(V) stored in recqvi(:,3)\n\nncl=size(physpol,1)-2;\nbootql=cell(num_iter,1);\np=unique(qldata3(:,8));\nprop=5000/numel(p); %5000 patients of the samples are used\nprop=min([prop 0.75]);  %max possible value is 0.75 (75% of the samples are used)\n\nii=qldata3(:,1)==1;\na=qldata3(ii,2);\nd=zeros(ncl,1);\n for i=1:ncl\n  d(i)=sum(a==i);    % intitial state disctribution\n end\n \nfprintf('Progress of Q-Learning:\\n');\nfprintf(['\\n' repmat('.',1,num_iter) '\\n\\n']);\n\nparfor i=1:num_iter\nfprintf('\\b|\\n');\n\nii=floor(rand(size(p,1),1)+prop);     % select a random sample of trajectories\nj=ismember(qldata3(:,8),p(ii==1));\nq=qldata3(j==1,1:4);\n\n[Qoff, ~]=OffpolicyQlearning150816( q , gamma, 0.1, 300000);\n\nV=zeros(750,25);\nfor k=1:750\n    for j=1:25\n        V(k,j)=physpol(k,j)*Qoff(k,j);\n    end\nend\n\nVs =sum(V')';\nbootql(i)={nansum(Vs(1:750).*d)/sum(d)};\n\n% Vs=nansum((physpol.*Qoff)')';\n% bootql(i)={sum(Vs(1:ncl).*d)/sum(d)};\nend\n\nbootql=cell2mat(bootql);\n\nend\n\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/offpolicy_eval_tdlearning.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5913164348747371}}
{"text": "function b= ImageDenoising(img, level)\n     distorted_img = imnoise(img,'gaussian',0,level);\n     \n     yRGB = im2double(distorted_img); \n     % Generate the same seed used in the experimental results of [1]\n     randn('seed', 0);\n     % Standard deviation of the noise --- corresponding to intensity \n     %  range [0,255], despite that the input was scaled in [0,1]\n     sigma = 25;\n     % Add the AWGN with zero mean and standard deviation 'sigma'\n     zRGB = yRGB + (sigma/255)*randn(size(yRGB));\n     % Denoise 'zRGB'. The denoised image is 'yRGB_est', and 'NA = 1'  \n     %  because the true image was not provided\n     [~, yRGB_est] = CBM3D(1, zRGB, sigma); \n     % Compute the putput PSNR\n%      PSNR = 10*log10(1/mean((yRGB(:)-yRGB_est(:)).^2))\n     % show the noisy image 'zRGB' and the denoised 'yRGB_est'\n%      figure; imshow(min(max(zRGB,0),1));   \n%      figure; imshow(min(max(yRGB_est,0),1));\n     b = uint8(yRGB_est*255);  \n\nend", "meta": {"author": "xialeiliu", "repo": "RankIQA", "sha": "22ca65cd0156b5b428cecd55ed939366fb64d2e5", "save_path": "github-repos/MATLAB/xialeiliu-RankIQA", "path": "github-repos/MATLAB/xialeiliu-RankIQA/RankIQA-22ca65cd0156b5b428cecd55ed939366fb64d2e5/data/rank_tid2013/ImageDenoising.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5913164307876777}}
{"text": "function uh = CurlCurl2dNd0(node,elem,bdFlag,pde)\n%% CURLCURL2DND0 curlcurl equation: lowest order edge element on triangular mesh\n% rot(\\mu^{-1} curl u) + \\kappa u = f in \\Omega\n% u\\times n = 0 on \\Gamma_D\n% \\mu^{-1} curl u = g_N on \\Gamma_N\n\n% Solve u_h in Nd0 \\cap {u \\times n = 0 on \\Gamma_D} = V_h\n% (\\mu^{-1} curl u_h, curl v_h) + (\\kappa u_h, v_h)\n% = (f, v_h) + <v_h \\cdot \\tau, g_N>_{\\Gamma_N} for any v_h \\in V_h\n\n% basis function associated with an edge |e|\n% \\phi_e = \\frac{|e|}{2|K|} (\\lamda_{i+1} n_{i-1} - \\lambda_{i+1} n_{i-1})\n% implented based on an older iFEM circa 2010.\n% \n% For 3D curl-curl problems\n% See also Maxwell, cubeMaxwell\n%\n% \n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n%%\nNT = size(elem,1);\nT = auxstructure(elem);\nelem2edge = T.elem2edge;\nedge = T.edge;\nelem2edgeSign = ones(NT,3);\ntotalEdge = uint32([elem(:,[2,3]); elem(:,[3,1]); elem(:,[1,2])]);\nidx = (totalEdge(:,1)>totalEdge(:,2));\nelem2edgeSign(idx) = -1;\n\nif ~isfield(pde,'mu'), pde.mu = 1; end\nif ~isfield(pde,'kappa'), pde.kappa = 1; end\nif ~isfield(pde,'g_D'), pde.g_D = []; end\nif ~isfield(pde,'g_N'), pde.g_N = []; end\n\nNE = size(edge,1);\nuh = zeros(NE,1);\ng_D = pde.g_D;\ng_N = pde.g_N;\nf_x = pde.f_x;\nf_y = pde.f_y;\nmu = pde.mu;\nkappa = pde.kappa;\n\n\n%% Boundary\nidxD = (bdFlag(:) == 1);     % all Dirichlet edges in bdFlag\nisFixedEdge = false(NE,1);\nisFixedEdge(elem2edge(idxD)) = true;  % index of fixed boundary edges\nfreeEdge = ~isFixedEdge;\n\nidxN = (bdFlag(:) == 2);     % all Neumann edges in bdFlag\nNeumann = edge(elem2edge(idxN),:);\n\n%% geometric quantities\n%edge vector which follows elem2edge counterclockwisely\nve(:,:,1) = node(elem(:,3),:)-node(elem(:,2),:);\nve(:,:,2) = node(elem(:,1),:)-node(elem(:,3),:);\nve(:,:,3) = node(elem(:,2),:)-node(elem(:,1),:);\narea = 0.5*abs(-ve(:,1,3).*ve(:,2,2)+ve(:,2,3).*ve(:,1,2));\n\n%length_ve(:,:,i) is the length of i^th edge\nlength_ve = sqrt(sum(ve.^2,2));\nlength_ve = reshape(length_ve,NT,3);\n\n%outer normal vector of each edge which follows the index of elem2edge\nne = [ve(:,2,:), -ve(:,1,:)];\n\n\n%%\n%M is the mass matrix M_{ij} = (\\kappa \\phi_i, \\phi_j)\n%B is the stiffness matrix B_{ij} = (\\mu^{-1} curl \\phi_i, curl \\phi_j)\nc = [3 1 2 3 1];\n%cyclic group of {1,2,3}: c(i)=i-1, c(i+2)=i+1\n\nM = sparse(NE,NE);\nB = sparse(NE,NE);\nmuinv = 1/mu;\n\nfor i = 1:3\n    for j = 1:3\n        sij = elem2edgeSign(:,i).*elem2edgeSign(:,j);\n        \n        if i==j\n            nini = length_ve(:,i).^2;\n            njnk = dot(ne(:,:,c(i)),ne(:,:,c(i+2)),2);\n            Mij = kappa.*length_ve(:,i).*(nini - 3*njnk)./(24*area);\n        else\n            ninj = dot(ne(:,:,i),ne(:,:,j),2);\n            ni2 = length_ve(:,i).^2;\n            nj2 = length_ve(:,j).^2;\n            Mij = -sij.*kappa.*length_ve(:,i).*length_ve(:,j).*(ni2 + nj2 + 3*ninj)./(24*area);\n        end\n        \n        \n        Bij = muinv.*sij.*length_ve(:,i).*length_ve(:,j)./area;\n        \n        M = M + sparse(elem2edge(:,i),elem2edge(:,j),Mij,NE,NE);\n        B = B + sparse(elem2edge(:,i),elem2edge(:,j),Bij,NE,NE);\n    end\nend\n\nA = M+B;\n\n%% rhs (old hard-coded implementation)\nFx = quadelem2node(node,elem,f_x);\nFy = quadelem2node(node,elem,f_y);\n\nbt1x = -0.5*elem2edgeSign(:,1).*length_ve(:,1)...\n    .*(Fx(:,2).*ne(:,1,3) - Fx(:,3).*ne(:,1,2))./area;\nbt2x = -0.5*elem2edgeSign(:,2).*length_ve(:,2)...\n    .*(Fx(:,3).*ne(:,1,1) - Fx(:,1).*ne(:,1,3))./area;\nbt3x = -0.5*elem2edgeSign(:,3).*length_ve(:,3)...\n    .*(Fx(:,1).*ne(:,1,2) - Fx(:,2).*ne(:,1,1))./area;\n\nbt1y = -0.5*elem2edgeSign(:,1).*length_ve(:,1)...\n    .*(Fy(:,2).*ne(:,2,3) - Fy(:,3).*ne(:,2,2))./area;\nbt2y = -0.5*elem2edgeSign(:,2).*length_ve(:,2)...\n    .*(Fy(:,3).*ne(:,2,1) - Fy(:,1).*ne(:,2,3))./area;\nbt3y = -0.5*elem2edgeSign(:,3).*length_ve(:,3)...\n    .*(Fy(:,1).*ne(:,2,2) - Fy(:,2).*ne(:,2,1))./area;\n\nbt1 = bt1x + bt1y;\nbt2 = bt2x + bt2y;\nbt3 = bt3x + bt3y;\n\nF = accumarray(elem2edge(:),[bt1;bt2;bt3],[NE 1]);\n\n%% Dirichlet Boundary\nif ~isempty(pde.g_D)\n    fixedEdge = edge(isFixedEdge,:);\n    signFixedEdge = elem2edgeSign(idxD);\n    Nve = node(fixedEdge(:,1),:) - node(fixedEdge(:,2),:);\n    NveLength = sqrt(sum(Nve.^2,2)); \n    GD = quadedge(node,fixedEdge,g_D).*signFixedEdge./NveLength;\n    uh(isFixedEdge) = GD;\nend\n\n%% Neumann Boundary\nif (~isempty(Neumann) && ~isempty(pde.g_N))\n    signNeumannEdge = elem2edgeSign(idxN);\n    GN = quadedge(node,Neumann,g_N).*signNeumannEdge;\n    F = F + accumarray(idxN(:),GN(:),[NE,1]); \nend\n\n%direct solver\nuh(freeEdge) = A(freeEdge,freeEdge)\\F(freeEdge);\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/curlcurl2d/CurlCurl2dNd0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5913164290395454}}
{"text": "function solution = CS_GWO(UAV, SearchAgents, Max_iter)\n%CS_GWO \u7070\u72fc-\u5e03\u8c37\u9e1f\u4f18\u5316\u7b97\u6cd5\n%Gray Wolf Cuckoo Optimization\n\n% \u8d85\u53c2\u6570\npa = 0.25;   % \u5e03\u8c37\u9e1f\u641c\u7d22\u53c2\u6570\n\n% \u7b97\u6cd5\u521d\u59cb\u5316\n[WolfPops, Tracks] = PopsInit(UAV, SearchAgents, false);   % \u968f\u673a\u751f\u6210 \u521d\u59cb\u72fc\u7fa4 \u548c \u8f68\u8ff9\u4eec\ndim = WolfPops.PosDim;                                                         % \u72b6\u6001\u53d8\u91cf\u7ef4\u5ea6\n\n% \u521d\u59cb\u5316\u89e3\nAlpha_pos = zeros(1, dim);   % \u03b1\u89e3\nAlpha_score = inf;                  % \u03b1\u89e3\u9002\u5e94\u5ea6\nAlpha_no = 1;                         % \u03b1\u89e3\u7f16\u53f7\n\nBeta_pos = zeros(1, dim);      % \u03b2\u89e3\nBeta_score = inf;                     % \u03b2\u89e3\u9002\u5e94\u5ea6\nBeta_no = 1;                             % \u03b2\u89e3\u7f16\u53f7\n\nDelta_pos = zeros(1, dim);     % \u03b4\u89e3\nDelta_score = inf;                    % \u03b4\u89e3\u9002\u5e94\u5ea6\nDelta_no = 1;                           % \u03b4\u89e3\u7f16\u53f7\n\nFitness_list = zeros(1, Max_iter);\n\n% \u8fed\u4ee3\u6c42\u89e3\ntic\nfprintf('>>CS_GWO \u4f18\u5316\u4e2d    00.00%%')\nfor iter = 1 : Max_iter\n\n    % \u2460  \u8ba1\u7b97\u6bcf\u53ea\u72fc\u7684\u9002\u5e94\u5ea6\uff0c\u66f4\u6539\u5176\u79cd\u7fa4\u7b49\u7ea7\n    ProbPoints = cell(SearchAgents, 1);   \n    for i = 1 : SearchAgents\n        % \u8ba1\u7b97\u76ee\u6807\u51fd\u6570\n        [fitness, ~, Data] = ObjFun(Tracks{i}, UAV);    % \u4e00\u4e2a\u667a\u80fd\u4f53\u7684\u76ee\u6807\u51fd\u6570\n        ProbPoints{i} = Data.ProbPoint;                       % \u6240\u6709\u667a\u80fd\u4f53\u4e0d\u7b26\u5408\u6761\u4ef6\u7684\u72b6\u6001\n\n        % \u66f4\u65b0 Alpha\u3001Beta \u548c Delta \u89e3\n        if fitness <= Alpha_score  % \u9002\u5e94\u80fd\u529b\u6700\u5f3a\uff08\u56e0\u4e3a\u6027\u80fd\u6307\u6807\u8d8a\u5c0f\u8d8a\u597d\uff0c\u56e0\u6b64\u4e3a\u5c0f\u4e8e\u53f7\uff09\n            Alpha_score = fitness;\n            Alpha_pos = WolfPops.Pos(i, :);\n            Alpha_no = i;\n        end \n        if fitness > Alpha_score && fitness <= Beta_score\n            Beta_score = fitness;\n            Beta_pos = WolfPops.Pos(i, :);\n            Beta_no = i;\n        end\n        if fitness > Alpha_score && fitness > Beta_score && fitness <= Delta_score\n            Delta_score = fitness;\n            Delta_pos = WolfPops.Pos(i, :);\n            Delta_no = i;\n        end\n    end\n\n    % \u2461  \u66f4\u65b0\u53c2\u6570a\n    a = 2 - iter * 2 / Max_iter;                  % \u7ebf\u6027\u9012\u51cf\n    %a = 2 * cos((iter / Max_iter) * pi/2);   % \u975e\u7ebf\u6027\u9012\u51cf\n\n    % \u2462  \u66f4\u65b0\u4f4d\u7f6e\uff08\u671d\u7740\u524d\u4e09\u53ea\u72fc\u4f4d\u7f6e\u524d\u8fdb\uff09\n    for i = 1 : SearchAgents\n        for j = 1 : dim\n\n            r1 = rand();\n            r2 = rand();\n            A1 = 2*a*r1 - a;\n            C1 = 2*r2;\n            D_alpha = abs(C1*Alpha_pos(j) - WolfPops.Pos(i, j));\n            X1(i, j) = Alpha_pos(j) - A1*D_alpha;\n\n            r1 = rand();\n            r2 = rand();            \n            A2 = 2*a*r1 - a;\n            C2 = 2*r2;\n            D_beta = abs(C2*Beta_pos(j) - WolfPops.Pos(i, j));\n            X2(i, j) = Beta_pos(j) - A2*D_beta;\n            \n            r1 = rand();\n            r2 = rand();\n            A3 = 2*a*r1 - a;\n            C3 = 2*r2;\n            D_delta = abs(C3*Delta_pos(j) - WolfPops.Pos(i, j));\n            X3(i, j) = Delta_pos(j) - A3*D_delta;\n            \n            %\u66f4\u65b0\n            %WolfPops.Pos(i, j) = (X1(i, j) + X2(i, j) + X3(i, j)) / 3;\n \n        end\n\n    end\n\n    % \u2463  Cuckoo \u641c\u7d22\n    fitness = nan(SearchAgents, 1);\n    for i = 1 : SearchAgents\n        [fitness(i), ~, ~] = ObjFun(Tracks{i}, UAV);\n    end\n    [~, index] = min(fitness);\n    best = WolfPops.Pos(index, :);\n    X1 = get_cuckoos(X1, best, WolfPops.lb, WolfPops.ub); \n    X2 = get_cuckoos(X2, best, WolfPops.lb, WolfPops.ub);\n    X3 = get_cuckoos(X3, best, WolfPops.lb, WolfPops.ub);\n    X1 = empty_nests(X1, WolfPops.lb, WolfPops.ub, pa);\n    X2 = empty_nests(X2, WolfPops.lb, WolfPops.ub, pa);\n    X3 = empty_nests(X3, WolfPops.lb, WolfPops.ub, pa);\n    WolfPops.Pos = (X1 + X2 + X3) / 3;\n\n    % \u2464  \u8c03\u6574\u4e0d\u7b26\u5408\u8981\u6c42\u7684\u72b6\u6001\u53d8\u91cf\n    [WolfPops, Tracks] = BoundAdjust(WolfPops, ProbPoints, UAV);\n\n    % \u2465  \u5b58\u50a8\u9002\u5e94\u5ea6\n    Fitness_list(iter) = Alpha_score;\n\n\n    if iter/Max_iter*100 < 10\n        fprintf('\\b\\b\\b\\b\\b%.2f%%', iter/Max_iter*100)\n    else\n        fprintf('\\b\\b\\b\\b\\b\\b%.2f%%', iter/Max_iter*100)\n    end\nend\nfprintf('\\n\\n>>\u8ba1\u7b97\u5b8c\u6210\uff01\\n\\n')\ntoc\n\n\n\n\n% \u8f93\u51fa\u503c\nsolution.method = 'GWO';                % \u7b97\u6cd5\nsolution.WolfPops = WolfPops;       % \u6240\u6709\u89e3\u79cd\u7fa4\u4fe1\u606f\nsolution.Tracks = Tracks;                  % \u6240\u6709\u89e3\u822a\u8ff9\u4fe1\u606f\nsolution.Fitness_list = Fitness_list;   % \u03b1\u89e3\u9002\u5e94\u5ea6\u66f2\u7ebf\nsolution.Alpha_Data = Data;            % \u03b1\u89e3\u7684\u5a01\u80c1\u4fe1\u606f\nsolution.Alpha_no = Alpha_no;        % \u03b1\u89e3\u7684\u4f4d\u7f6e\nsolution.Beta_no = Beta_no;             % \u03b2\u89e3\u7684\u4f4d\u7f6e\nsolution.Delta_no = Delta_no;          % \u03b4\u89e3\u7684\u4f4d\u7f6e\n\nend\n\n\n\n%%%%% \u5e03\u8c37\u9e1f\u641c\u7d22 %%%%%\nfunction nest = get_cuckoos(nest, best, Lb, Ub)\n    n = size(nest, 1);\n    beta = 3/2;\n    sigma = (gamma(1 + beta) * sin(pi*beta/2)/(gamma((1 + beta)/2)*beta*2^((beta - 1)/2)))^(1/beta);\n    for j = 1:n\n        s = nest(j, :);\n        u = randn(size(s))*sigma;\n        v = randn(size(s));\n        step = u./abs(v).^(1/beta);\n        stepsize = 0.01*step.*(s - best);\n        s = s + stepsize.*randn(size(s));\n        nest(j, :) = BoundClamp(s, Lb, Ub);\n    end\nend\nfunction new_nest = empty_nests(nest, Lb, Ub, pa)\n    n = size(nest, 1);\n    K = rand(size(nest)) > pa;\n    stepsize = rand*(nest(randperm(n), :) - nest(randperm(n), :));\n    new_nest = nest + stepsize.*K;\n    for j = 1:size(new_nest, 1)\n        s = new_nest(j, :);\n        new_nest(j, :) = BoundClamp(s, Lb, Ub);\n    end\nend\nfunction x = BoundClamp(x, lb, ub)\n    Flag4ub = x > ub;\n    Flag4lb = x < lb;\n    x = x .* ( ~(Flag4ub + Flag4lb) ) + ub .* Flag4ub + lb .* Flag4lb;\nend\n", "meta": {"author": "zhaohaojie1998", "repo": "Grey-Wolf-Optimizer-for-Path-Planning", "sha": "ff6d042c58ca6f2fbcb880124e5513ad7d5848a9", "save_path": "github-repos/MATLAB/zhaohaojie1998-Grey-Wolf-Optimizer-for-Path-Planning", "path": "github-repos/MATLAB/zhaohaojie1998-Grey-Wolf-Optimizer-for-Path-Planning/Grey-Wolf-Optimizer-for-Path-Planning-ff6d042c58ca6f2fbcb880124e5513ad7d5848a9/CS_GWO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5913164226135587}}
{"text": "clear, clc;\n\n% This is an example for running the function tree_LogisticR\n%\n%  Problem:\n%\n%  min  f(x,c) = - sum_i weight_i * log (p_i) + z * 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%  The tree structured 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%\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%  Note: \n%  1) If each element of x is a leaf node of the tree and the weight for\n%  this leaf node are the same, we provide an alternative \"efficient\" input\n%  for this kind of node, by creating a \"super node\" with \n%  opts.ind(1,1)=-1; opts.ind(2,1)=-1; and opts.ind(3,1)=the common weight.\n%\n%  2) If the features are well ordered in that, the features of the left\n%  tree is always less than those of the right tree, opts.ind(1,:) and\n%  opts.ind(2,:) contain the \"real\" starting and ending indices. That is to\n%  say, x( opts.ind(1,j):opts.ind(2,j) ) denotes x_{G_j}. In this case,\n%  the entries in opts.ind(1:2,:) are within 1 and n.\n%\n%\n%  If the features are not well ordered, please use the input opts.G for\n%  specifying the index so that  \n%   x( opts.G ( opts.ind(1,j):opts.ind(2,j) ) ) denotes x_{G_j}.\n%  In this case, the entries of opts.G are within 1 and n, and the entries of\n%  opts.ind(1:2,:) are within 1 and length(opts.G).\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%%\n\n\ncd ..\ncd ..\n\nroot=cd;\naddpath(genpath([root '/SLEP']));\n                     % add the functions in the folder SLEP to the path\n                   \n% change to the original folder\ncd Examples/tree;\n\nm=50;  n=100;       % The data matrix is of size m x n\n\n% ---------------------- generate random data ----------------------\n%randn('state',(randNum-1)*3+1);\nA=randn(m,n);        % the data matrix\n\ny=[-ones(25,1); ones(25,1)];      % the response\n\n\n%% In this example, the tree is set as:\n%\n% root, 1:100, with weight 0\n% its children nodes, 1:50, and 51:100\n%\n% For 1:50, its children are 1:20, 21:40, and 41:50\n%\n% For 51:100, its children are 51:70, and 71:100\n%\n% These nodes in addition have each individual features (they contain) as\n% children nodes.\n%\n%%\n\n%% One efficient way\n% We make use of the fact that the indices of the left nodes of the tree\n% are smaller than the right nodes.\n\n%----------------------- Set optional items -----------------------\nopts=[];\n\n% Starting point\nopts.init=2;        % starting from a zero point\n\n% Termination \nopts.tFlag=5;       % run .maxIter iterations\nopts.maxIter=100;   % maximum number of iterations\n\n% regularization\nopts.rFlag=1;       % use ratio\n\n% Normalization\nopts.nFlag=0;       % without normalization\n\n% Group Property\nopts.ind=[[-1, -1, 1]',... % leave nodes (each node contains one feature)\n    [1, 20, sqrt(20)]', [21, 40, sqrt(20)]',... % the layer above the leaf\n    [41, 50, sqrt(10)]', [51, 70, sqrt(20)]', [71,100, sqrt(30)]',...\n    [1, 50, sqrt(50)]', [51, 100, sqrt(50)]']; % the higher layer\n\n%----------------------- Run the code mc_cgLassoLeast -----------------------\nz=0.1;\ntic;\n[x, c, funVal, ValueL]= tree_LogisticR(A, y, z, opts);\ntoc;\n\n%% An alternative way\n% We make use of the fact that the indices of the left nodes of the tree\n% are smaller than the right nodes.\n%%\n\n%----------------------- Set optional items -----------------------\nopts=[];\n\n% Starting point\nopts.init=2;        % starting from a zero point\n\n% Termination \nopts.tFlag=5;       % run .maxIter iterations\nopts.maxIter=100;   % maximum number of iterations\n\n% regularization\nopts.rFlag=1;       % use ratio\n\n% Normalization\nopts.nFlag=0;       % without normalization\n\n% Group Property\nopts.ind=[[-1, -1, 1]',... % leave nodes (each node contains one feature)\n    [1, 20, sqrt(20)]', [21, 40, sqrt(20)]',... % the layer above the leaf\n    [41, 50, sqrt(10)]', [51, 70, sqrt(20)]', [71,100, sqrt(30)]',...\n    [101, 150, sqrt(50)]', [151, 200, sqrt(50)]']; % the higher layer\nopts.G=[1:100, 1:100];\n\n%----------------------- Run the code mc_cgLassoLeast -----------------------\nz=0.1;\ntic;\n[x2, c2, funVal2, Value2L]= tree_LogisticR(A, y, z, opts);\ntoc;\n\n", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Toolbox/SLEP_package_4.1/Examples/tree/example_tree_LogisticR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5913164191172945}}
{"text": "%% simple example of use of renorm_sibling_3d_same_scale\nclear; close all;\nx = uiuc_sample;\n%% compute roto-translation scattering of an image\noptions.Q = 1;\noptions.J = 5;\nWop = wavelet_factory_3d_pyramid(options, options, options);\nSx = scat(x, Wop);\n\n%% L1 renormalization\nop = @(x)(sum(x, 3));\nSx_renorm = renorm_sibling_3d_same_scale(Sx, op);\n\n%% L1 + smoothing renormalization\nop = renorm_factory_L1_smoothing(2);\n[Sx_renorm, siblings] = renorm_sibling_3d_same_scale(Sx, op);\n\n%%\nimage_scat(Sx, 0, 0);\n%%\nimage_scat(Sx_renorm, 0, 0);\n%%\nclose all;\nimagesc(min(image_scat_layer(Sx_renorm{3},0,0),0.2));\n\n%%\nimage_scat(Sx_renorm, 1, 1);\n%%\nimage_scat(Sx, 1, 1);\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/test/scatutils/test_renorm_sibling_3d_same_scale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5913164091950434}}
{"text": "function v=cart2curv(vcart,typeout,bcontr,bcovar)\n% v=cart2curv(vcart,typeout,bcontr,bcovar) converts\n% cartesian coordinate components to curvilinear\n% components.\n% vcart   - cartesian vector components\n% typeout - 1 for contravariant output or\n%           2 for covariant output\n% bcontr  - contravariant base vector components\n% bcovar  - covariant base vector components\n% v       - vector components in either contravariant\n%           or covariant form\n\nif typeout==1, v=bcontr.'*vcart(:);  \nelse v=bcovar.'*vcart(:); end\nv=simple(v);", "meta": {"author": "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/cart2curv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5913019213614522}}
{"text": "function [x, infos] = acc_online_mu_nmf(V, rank, in_options)\n% Accelerated online non-negative matrix factorization (ONMF) algorithm.\n%\n% Inputs:\n%       matrix      V\n%       rank        rank\n%       options     options\n% Output:\n%       w           solution of w\n%       infos       information\n%\n% References:\n%       S. S. Bucak, B. Gunsel,\n%       \"Incremental Subspace Learning via Non-negative Matrix Factorization,\"\n%       Pattern Recognition, 2009.\n%    \n%\n% This file is part of NMFLibrary.\n%\n% Created by H.Kasai and H.Sakai on Feb. 12, 2017\n%\n% Change log: \n%\n%       Feb. 12, 2017 (Hiroyuki Kasai): Fixed algorithm. \n%\n%       May. 20, 2019 (Hiroyuki Kasai): Added initialization module.\n%\n%       Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n    % set dimensions and samples\n    [m, n] = size(V);\n \n    % set local options\n    local_options = [];\n    local_options.rep_mode = 'fix';\n    local_options.w_repeat = 1;\n    local_options.h_repeat = 1;\n    local_options.alpha    = 2; \n    local_options.delta    = 0.1;    \n    \n    % check input options\n    if ~exist('in_options', 'var') || isempty(in_options)\n        in_options = struct();\n    end      \n    % merge options\n    options = mergeOptions(get_nmf_default_options(), local_options);   \n    options = mergeOptions(options, in_options);   \n    \n    % initialize factors\n    init_options = options;\n    [init_factors, ~] = generate_init_factors(V, rank, init_options);    \n    Wt = init_factors.W;\n    H = init_factors.H;  \n \n    % initialize\n    method_name = 'ACC-Online-NMF';\n    epoch = 0;\n    grad_calc_count = 0;\n\n    if options.verbose > 0\n        fprintf('# %s: started ...\\n', method_name);           \n    end      \n\n    %At = zeros(m, rank);\n    %Bt = zeros(rank, rank);  \n\n    % initialize for this algorithm\n    if strcmp(options.rep_mode, 'adaptive')\n        K = m*n;        \n        rhoh = 1+(K+m*rank)/(n*(rank+1));         \n    end    \n    \n    % store initial info\n    clear infos;\n    [infos, f_val, optgap] = store_nmf_info(V, Wt, H, [], options, [], epoch, grad_calc_count, 0);\n    \n    if options.verbose > 1\n        fprintf('%s: Epoch = 0000, cost = %.16e, optgap = %.4e\\n', method_name, f_val, optgap); \n    end     \n    \n    % set start time\n    start_time = tic();\n    \n    % main outer loop\n    while true\n        \n        % check stop condition\n        [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n        if stop_flag\n            display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n            break;\n        end      \n              \n        % Reset sufficient statistic\n        At = zeros(m, rank);\n        Bt = zeros(rank, rank);        \n\n        % main inner loop\n        for t = 1 : options.batch_size : n - 1\n\n            % retrieve vt and ht\n            vt = V(:, t:t+options.batch_size-1);\n            ht = H(:, t:t+options.batch_size-1);            \n\n%             % uddate ht\n%             Wtv = Wt.' * vt;\n%             WtW = Wt.' * Wt;\n%             for iii=1:h_repeat\n%                 ht = ht .* (Wtv) ./ (WtW * ht);\n%                 ht = ht + (ht<eps) .* eps;      \n%             end\n            \n            Wtv = Wt.' * vt;\n            WtW = Wt.' * Wt;\n            if strcmp(options.rep_mode, 'adaptive')\n                gamma = 1; \n                eps0 = 1; \n                j = 1;\n                rhoh_alpha = rhoh * options.alpha;\n\n                %while j <= floor(1+rhoh*alpha) &&  gamma >= delta*eps0\n                while j <= rhoh_alpha && gamma >= options.delta * eps0\n                    ht0 = ht;\n                    ht = ht .* (Wtv) ./ (WtW * ht);\n                    ht = ht + (ht<eps) .* eps;   \n                    if j == 1\n                        eps0 = norm(ht0 - ht); \n                    end\n                    gamma = norm(ht0 - ht);  \n                    j = j+1;\n                end           \n            else\n                for iii = 1 : options.h_repeat\n                    ht = ht .* (Wtv) ./ (WtW * ht);\n                    ht = ht + (ht<eps) .* eps;      \n                end                  \n            end \n            \n            \n            % update sufficient statistics\n            At = At + vt *  ht';\n            Bt = Bt + ht *  ht';              \n\n            % update W\n            for iii = 1 : options.w_repeat\n                Wt = Wt .* At ./ (Wt * Bt); \n                Wt = Wt + (Wt<eps) .* eps;\n            end\n\n            % store new h\n            H(:, t:t+options.batch_size-1) = ht;  \n\n            grad_calc_count = grad_calc_count + m * options.batch_size;            \n        end\n        \n        % measure elapsed time\n        elapsed_time = toc(start_time);        \n\n        % update epoch\n        epoch = epoch + 1;        \n        \n        % store info\n        infos = store_nmf_info(V, Wt, H, [], options, infos, epoch, grad_calc_count, elapsed_time);          \n        \n        % display info\n        display_info(method_name, epoch, infos, options);\n\n    end\n    \n    x.W = Wt;\n    x.H = H;\n    x.R = [];\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/online/acc_online_mu_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5912911350379665}}
{"text": "clear all\nclose all\npath(path,'..\\..\\FUZZCLUST')\ncolors={'r.' 'gx' 'b+' 'ys' 'md' 'cv' 'k.' 'r*' 'g*' 'b*' 'y*' 'm*' 'c*' 'k*' };\n\n%the data\ndata.X=nDexample(5,250,2,1);\n%normalization\ndata=clust_normalize(data,'range');\n\n%parameters\nparam.c=3;\nparam.m=2;\nparam.e=1e-3;\nparam.ro=ones(1,param.c);\nparam.val=1;\n\n%Gustafson Kessel-clustering\nresult = GKclust(data,param);\n\n%validation\nresult = validity(result,data,param);\nplot(data.X(:,1),data.X(:,2),'b.',result.cluster.v(:,1),result.cluster.v(:,2),'ro');\nhold on\nplot(result.cluster.v(:,1),result.cluster.v(:,2),'ro');\n\n%evaluation\nnew.X=data.X;\neval = clusteval(new,result,param);\nresult.validity", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/7486-clustering-toolbox/Demos/comparing/GKcall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6791786991753929, "lm_q1q2_score": 0.5912911157026101}}
{"text": "function nn = nnff(nn, x, y)\n%NNFF performs a feedforward pass\n% nn = nnff(nn, x, y) returns an neural network structure with updated\n% layer activations, error and loss (nn.a, nn.e and nn.L)\n\n    n = nn.n;\n    m = size(x, 1);\n\n    nn.a{1} = x;\n\n    %feedforward pass\n    for i = 2 : n-1\n        nn.a{i} = sigm(repmat(nn.b{i - 1}', m, 1) + nn.a{i - 1} * nn.W{i - 1}');\n        if(nn.dropoutFraction > 0)\n            if(nn.testing)\n                nn.a{i} = nn.a{i}.*(1 - nn.dropoutFraction);\n            else\n                nn.a{i} = nn.a{i}.*(rand(size(nn.a{i}))>nn.dropoutFraction);\n            end\n        end\n        %calculate running exponential activations for use with sparsity\n        if(nn.nonSparsityPenalty>0)\n            nn.p{i} = 0.99 * nn.p{i} + 0.01 * mean(nn.a{i}, 1);\n        end\n    end\n    switch nn.output \n        case 'sigm'\n            nn.a{n} = sigm(repmat(nn.b{n - 1}', m, 1) + nn.a{n - 1} * nn.W{n - 1}');\n        case 'linear'\n            nn.a{n} = repmat(nn.b{n - 1}', m, 1) + nn.a{n - 1} * nn.W{n - 1}';\n        case 'softmax'\n            nn.a{n} = repmat(nn.b{n - 1}', m, 1) + nn.a{n - 1} * nn.W{n - 1}';\n            nn.a{n} = exp(bsxfun(@minus, nn.a{n}, max(nn.a{n},[],2)));\n            nn.a{n} = bsxfun(@rdivide, nn.a{n}, sum(nn.a{n}, 2)); \n    end\n\n    %error and loss\n    nn.e = y - nn.a{n};\n    switch nn.output\n        case {'sigm','linear'}\n            nn.L = 1/2 * sum(sum(nn.e .^ 2)) / m; \n        case 'softmax'\n            nn.L = -sum(sum(y .* log(nn.a{n}))) / m;\n    end\nend\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/refVAD/vad-master/mfiles/nnff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5912911146097766}}
{"text": "%This is a more real-life example\n\nload DataTest; %load some simulation data for acoustic pressure coming from a focused device\n\nh1=figure;\nsubplot(1,2,1);\n\n [X,Y,Z]=meshgrid(Rx,Ry,Rz);\n pf = abs(uf); \n\n[Maxima,MaxPos,Minima,MinPos]=MinimaMaxima3D(pf,1,0,10,10); %We find the first 10 minima and maxima\n\nufa=20*log10(abs(uf)/max(abs(uf(:))));\n\nis=isosurface(X,Y,Z,ufa,-6); %we display the focused pressure at -6dB\npatch(is,'facecolor','red','edgecolor','none');\nview(24,28);\nlighting gouraud;\ncamlight;\ndaspect([1 1 1]);\ntitle(sprintf('(%3.1f,%3.1f,%3.1f) mm',CoordinatesToEval(nc,1)*1000, CoordinatesToEval(nc,2)*1000,CoordinatesToEval(nc,3)*1000));\nxlabel('x (mm)');\nylabel('y (mm)');\nzlabel('z (mm)');\nfor nm=1:5\n   %we display the location of the maxima, note that for my needs I\n   %switched X<->Y \n   posmax=[Rx(MaxPos(nm,2)),Ry(MaxPos(nm,1)),Rz(MaxPos(nm,3))];\n   line([posmax(1)-1 posmax(1)+1],[posmax(2) posmax(2)],[posmax(3) posmax(3)],'linewidth',1,'color','b');\n   line([posmax(1) posmax(1)],[posmax(2)-1 posmax(2)+1],[posmax(3) posmax(3)],'linewidth',1,'color','b');\n   line([posmax(1) posmax(1)],[posmax(2) posmax(2)],[posmax(3)-1 posmax(3)+1],'linewidth',1,'color','b');\n   TT=['\\bf \\leftarrow ' char(nm+96)];\n   Align='Cap';\n   FSize=12;\n   text(posmax(1),posmax(2),posmax(3),TT,'FontSize',FSize,'color','b','VerticalAlignment',Align,'Tag','IgnoreReFormatting','HorizontalAlignment','center');\nend\ngrid on;\nsubplot(1,2,2);\n\nxlim([0 10]);\nylim([0 10]);\ndaspect([1 1 1]);\n\nTT={};\nTT{1}='First 5 Maxima';\nfor nm=1:5\n    posmax=[Rx(MaxPos(nm,2)),Ry(MaxPos(nm,1)),Rz(MaxPos(nm,3))];\n    TT{nm+1}= [char(nm+96) sprintf(': %4.3f%',Maxima(nm)) ', X=' sprintf('%2.1f, ',posmax(1)) ', Y=' sprintf('%2.1f',posmax(2)) ', Z=' sprintf('%2.1f',posmax(3))]; \nend\nAlign='Cap';\nFSize=12;\n\nt1=text(-1.5,7,TT,'FontSize',FSize,'color','k','VerticalAlignment',Align,'BackgroundColor','w','Edgecolor','k','Margin',4);\nset(gca,'visible','off');\nset(t1,'visible','on');\n\n%at end, you should see three iosurfaces, where in each isosurface we can\n%see that global maxima is inside the -6dB region (as expected for my\n%needs) and we can see that the other 4 maxima are located oustide this\n%region (what for me is also expected).", "meta": {"author": "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/AMoreUsefulExample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5912911100491458}}
{"text": "function e = vgg_rms_rrror(M)\n% e = vgg_rms_rrror(M)\n%\n% Get RMS diff from zero of matrix or vector M\n\ne = sqrt(sum(sum(M.*M)) / prod(size(M)));\n", "meta": {"author": "jmmanley", "repo": "VGG-Multiple-View-Geometry", "sha": "f114712de03082bb97229eaf2a65981908b64127", "save_path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry", "path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry/VGG-Multiple-View-Geometry-f114712de03082bb97229eaf2a65981908b64127/vgg_multiview/vgg_rms_error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5912911054885148}}
{"text": "function [cl] = m32cl(m3)\n% Convert volume from cubic meters to centiliters. \n% Chad Greene 2012\ncl = m3*100000;", "meta": {"author": "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/m32cl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5912643881689502}}
{"text": "%% housekeeping\nclc\n%% RISE the model\nlinear=~true;\nif linear\n    m=rise('targets_lin');\nelse\n    m=rise('targets','steady_state_file','sstate_model');\nend\n%% get the parameters\nversion='a';\n% 'a' % model with an endogenous inflation target.\n% 'b' % model with an exogenous inflation target.\n% 'd' % model with backward-looking price setting.\nstart_at_mode=false;\n\n[p,priors]=create_parameters(version,linear,start_at_mode);\n\n%% push the parameters\nm=set(m,'parameters',p);\n\n%% create data\n[data]=create_data();\n\n%% estimate the model\nms=estimate(m,'data',data,'estim_priors',priors);\n\n%% Impulse responses\nmyirfs=irf(ms);\n\n%% plot responses\nmyvars={'Y','PAI','R','X'};\nlocs=locate_variables(myvars,ms.endogenous.name);\nmyvtex=ms.endogenous.tex_name(locs);\nsstate=get(ms,'sstate');\nssdev=false;\n\nshocks={'EPS_A','EPS_E','EPS_Z','EPS_V','EPS_PAI'};%m.exogenous.name;\nlocs=locate_variables(shocks,ms.exogenous.name);\nmyshtex=ms.exogenous.tex_name(locs);\nclose all\nfigure('name','Impulse reponses');\niter=0;\nss=1;\nfor ishock=1:numel(shocks)\n    shock=shocks{ishock};\n    for ivar=1:numel(myvars)\n        vname=myvars{ivar};\n        if ssdev\n            ss=sstate.(vname);\n        end\n        iter=iter+1;\n        subplot(5,4,iter)\n        plot('0:16',myirfs.(shock).(vname)/ss,'linewidth',2)\n        title([myvtex{ivar},' to ',myshtex{ishock}])\n    end\nend\n", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/PeterIreland/Targets_JMCB2007/master.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338727, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5912643772194265}}
{"text": "function [H,S,D]=sobi(X,n,p)\n% SOBI - Second Order Blind Identification (SOBI) by joint diagonalization of\n%          correlation  matrices. THIS CODE ASSUMES TEMPORALLY CORRELATED SIGNALS,\n%          and uses correlations across times in performing the signal separation.\n%          Thus, estimated time delayed covariance matrices must be nonsingular\n%          for at least some time delays.\n% Usage:\n%         >> winv = sobi(data);\n%         >> [winv,act] = sobi(data,n,p);\n% Inputs:\n%   data - data matrix of size [m,N] ELSE of size [m,N,t] where\n%                m is the number of sensors,\n%                N is the  number of samples,\n%                t is the  number of trials (avoid epoch boundaries)\n%         n - number of sources {Default: n=m}\n%         p - number of correlation matrices to be diagonalized\n%             {Default: min(100, N/3)} Note that for non-ideal data,\n%             the authors strongly recommend using at least 100 time delays.\n%\n% Outputs:\n%   winv - Matrix of size [m,n], an estimate of the *mixing* matrix. Its\n%          columns are the component scalp maps. NOTE: This is the inverse\n%          of the usual ICA unmixing weight matrix. Sphering (pre-whitening),\n%          used in the algorithm, is incorporated into winv. i.e.,\n%\n%             >> icaweights = pinv(winv); icasphere = eye(m);\n%\n%   act  - matrix of dimension [n,N] an estimate of the source activities\n%\n%             >> data            = winv            * act;\n%                [size m,N]        [size m,n]        [size n,N]\n%             >> act = pinv(winv) * data;\n%\n% Authors:  A. Belouchrani and A. Cichocki (references: See function body)\n% Note:     Adapted by Arnaud Delorme and Scott Makeig to process data epochs by\n%           computing covariances while respecting epoch boundaries.\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,  2003.\n\n% Authors note: For non-ideal data, use at least p=100 the time-delayed covariance matrices.\nDEFAULT_LAGS = 100;\n\n[m,N,ntrials]=size(X);\n\nif nargin<1 || nargin > 3\n    \n    help sobi\n    \nelseif nargin==1\n    \n    n=m; % Source detection (hum...)\n    p=min(DEFAULT_LAGS,ceil(N/3)); % Number of time delayed correlation matrices to be diagonalized\n    \nelseif nargin==2\n    \n    p=min(DEFAULT_LAGS,ceil(N/3)); % Default number of correlation matrices to be diagonalized\n    % Use < DEFAULT_LAGS delays if necessary for short data epochs\nend\n\n%\n% Make the data zero mean\n%\nX(:,:)=X(:,:)-kron(mean(X(:,:)')',ones(1,N*ntrials));\n\n%\n% Pre-whiten the data based directly on SVD\n%\n[UU,S,VV]=svd(X(:,:)',0);\nQ= pinv(S)*VV';\nX(:,:)=Q*X(:,:);\n\n% Alternate whitening code\n% Rx=(X*X')/T;\n% if m<n, % assumes white noise\n%   [U,D]=eig(Rx);\n%   [puiss,k]=sort(diag(D));\n%   ibl= sqrt(puiss(n-m+1:n)-mean(puiss(1:n-m)));\n%    bl = ones(m,1) ./ ibl ;\n%   BL=diag(bl)*U(1:n,k(n-m+1:n))';\n%   IBL=U(1:n,k(n-m+1:n))*diag(ibl);\n% else    % assumes no noise\n%    IBL=sqrtm(Rx);\n%    Q=inv(IBL);\n% end\n% X=Q*X;\n\n%\n% Estimate the correlation matrices\n%\nk=1;\npm=p*m; % for convenience\nfor u=1:m:pm\n    k=k+1;\n    for t = 1:ntrials\n        if t == 1\n            Rxp=X(:,k:N,t)*X(:,1:N-k+1,t)'/(N-k+1)/ntrials;\n        else\n            Rxp=Rxp+X(:,k:N,t)*X(:,1:N-k+1,t)'/(N-k+1)/ntrials;\n        end\n    end\n    M(:,u:u+m-1)=norm(Rxp,'fro')*Rxp;  % Frobenius norm =\nend                                    % sqrt(sum(diag(Rxp'*Rxp)))\n\n%\n% Perform joint diagonalization\n%\nepsil=1/sqrt(N)/100;\nencore=1;\nV=eye(m);\nstep_n=0;\nwhile encore\n    encore=0;\n    for p=1:m-1\n        for q=p+1:m\n            % Perform Givens rotation\n            g=[   M(p,p:m:pm)-M(q,q:m:pm)  ;\n                M(p,q:m:pm)+M(q,p:m:pm)  ;\n                i*(M(q,p:m:pm)-M(p,q:m:pm)) ];\n            [vcp,D] = eig(real(g*g'));\n            [la,K]=sort(diag(D));\n            angles=vcp(:,K(3));\n            angles=sign(angles(1))*angles;\n            c=sqrt(0.5+angles(1)/2);\n            sr=0.5*(angles(2)-j*angles(3))/c;\n            sc=conj(sr);\n            oui = abs(sr)>epsil ;\n            encore=encore | oui ;\n            if oui  % Update the M and V matrices\n                colp=M(:,p:m:pm);\n                colq=M(:,q:m:pm);\n                M(:,p:m:pm)=c*colp+sr*colq;\n                M(:,q:m:pm)=c*colq-sc*colp;\n                rowp=M(p,:);\n                rowq=M(q,:);\n                M(p,:)=c*rowp+sc*rowq;\n                M(q,:)=c*rowq-sr*rowp;\n                temp=V(:,p);\n                V(:,p)=c*V(:,p)+sr*V(:,q);\n                V(:,q)=c*V(:,q)-sc*temp;\n            end %% if\n        end %% q loop\n    end %% p loop\n    step_n=step_n+1;\n    fprintf('%d step\\n',step_n);\nend %% while\n\n%\n% Estimate the mixing matrix\n%\nH = pinv(Q)*V;\n\n%\n% Estimate the source activities\n%\nif nargout>1\n    S=V'*X(:,:); % estimated source activities\nend\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/sigprocfunc/sobi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5912643756375728}}
{"text": "function automobile_plot ( )\n\n%*****************************************************************************80\n%\n%% AUTOMOBILE_PLOT reads the automobile dataset and makes a scatterplot.\n%\n%  Discussion:\n%\n%    The hardest part of this exercise was reading the comma-separated data file,\n%    which contains integer, real and string data.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 April 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    A Frank, A Asuncion,\n%    UCI Machine Learning Repository,\n%    http://archive.ics.uci.edu/ml,\n%    School of Information and Computer Science,\n%    University of California, Irvine, California.\n%\n\n%\n%  Read the data from the file.\n%\n  auto_cell = automobile_read ( 'automobile.txt' );\n%\n%  Price and weight are specific columns of the cell array.\n%  Extract them, and convert them to numeric vectors.\n%\n  price = auto_cell(:,26);\n  price = cell2mat ( price );\n  weight = auto_cell(:,14);\n  weight = cell2mat ( weight );\n%\n%  Ignore missing data.\n%\n  index = ( ( price ~= -1 ) & ( weight ~= -1 ) );\n%\n%  Create a scatter plot.\n%\n  figure ( 1 )\n  clf\n\n  plot ( price(index), weight(index), 'bo', 'MarkerSize', 5 )\n  grid on\n  xlabel ( 'Price in 1985 Dollars' );\n  ylabel ( 'Curb weight in pounds' );\n  title ( 'Scatter plot of price versus weight.' );\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/graphics_examples/automobile_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.5912536467284945}}
{"text": "function [dist_matrix] = pos2dist(positions)\n% pos2dist - Compute the relative distances matrix from the positions \n%            matrix\n%\n% Inputs:\n%   positions - matrix of size (3,nb_agents)\n%\n% Ouputs:\n%   dist_matrix - symmetric matrix with pairwise distances\n%\n%\n    distances = pdist(positions');\n    dist_matrix = squareform(distances);\n\nend", "meta": {"author": "lis-epfl", "repo": "swarmlab", "sha": "3574deddd2e4fdcc5696d08f93d6e888f45c8ecc", "save_path": "github-repos/MATLAB/lis-epfl-swarmlab", "path": "github-repos/MATLAB/lis-epfl-swarmlab/swarmlab-3574deddd2e4fdcc5696d08f93d6e888f45c8ecc/math_tools/pos2dist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5911796509488773}}
{"text": "\n%%\n%nested cross validation for testing the logistic rMTFL model\n%The stratified cv are integrated into method to handle\n%\"not_enough_data_sample\" problems and privide more accurate estimator\n%Han Cao\n%24.02.2017\n%%\n\nclear;\nclc;\nclose;\n\naddpath('../MALSAR/functions/rMTFL/'); % load function\naddpath('../MALSAR/utils/'); % load utilities\naddpath('./train_and_test/'); \n\n\n% simulate the data\nn = 50;\nd = 300;\nT = 10;\n\nX = cell(T, 1);\nY = cell(T, 1);\nW = randn(d, T);\nW_mask = abs(randn(d, T))<1;\nW(W_mask) = 0;\nfor i = 1: T\n    X{i} = randn(n, d);\n    Y{i} = sign(X{i} * W(:, i) + rand(n, 1) * 0.01);\nend\n\n\n\n%optimization options\nopts.init = 2;  \nopts.tFlag = 1; \nopts.tol = 10^-5;\nopts.maxIter = 60000; \n\n% lambda range\nlambda1_range = [1:-0.01:0.01];\nlambda2_range = [2:-0.05:0.05];\n\n%container for holding the results\nr_acc=cell(1,3);\nr_inCvAcc=cell(1,3); %\nr_S=cell(1,3);\n\n\n%nested cross validation\nout_cv_fold=3;\nin_cv_fold=5;\nfor i = 1: out_cv_fold\n    Xtr = cell(T, 1);\n    Ytr = cell(T, 1);\n    Xte = cell(T, 1);\n    Yte = cell(T, 1);\n    \n    %stratified cross validation\n    for t = 1: T\n        task_sample_size = length(Y{t});\n        ct = find(Y{t}<0);\n        cs = find(Y{t}>0);\n        ct_idx = i : out_cv_fold : length(ct);\n        cs_idx = i : out_cv_fold : length(cs);\n        te_idx = [ct(ct_idx); cs(cs_idx)];\n        tr_idx = setdiff(1:task_sample_size, te_idx);\n        \n        Xtr{t} = X{t}(tr_idx, :);\n        Ytr{t} = Y{t}(tr_idx, :);\n        Xte{t} = X{t}(te_idx, :);\n        Yte{t} = Y{t}(te_idx, :);\n    end\n    \n    %inner cv\n    fprintf('inner CV started\\n')\n    [best_lambda1 best_lambda2 accuracy_mat] = CrossValidationDirty( Xtr, Ytr, ...\n        'Logistic_rMTFL', opts, lambda1_range,lambda2_range, in_cv_fold, ...\n        'eval_MTL_accuracy');\n    \n    %train\n    %warm start for one turn\n    [W C P Q L F] = Logistic_rMTFL(Xtr, Ytr, best_lambda1, best_lambda2, opts);\n    opts2=opts;\n    opts2.init=1;\n    opts2.C0=C;\n    opts2.P0=P;\n    opts2.Q0=Q;\n    opts2.tol = 10^-10;\n    [W2 C2 P2 Q2 L2 F2] = Logistic_rMTFL(Xtr, Ytr, best_lambda1, best_lambda2, opts2);\n    \n\n     %test\n    final_performance = eval_MTL_accuracy(Yte, Xte, W2, C2);\n    \n    %collect results\n    r_acc{i}=final_performance;\n    r_inCvAcc{i}=accuracy_mat;\n    r_S{i}=nnz((sum(P2,2)==0))/size(P2,1);\n  \nend\n\n fprintf('the average accuracy is \\n')\n disp(mean(cell2mat(r_acc)))\n \n %cv accuracy cross lambda\nfor i=1:out_cv_fold\n    surf(lambda1_range', lambda2_range,r_inCvAcc{i}' );\n    xlabel('Parameter for P');\n    ylabel('parameter for Q');\n    hold on; \nend\nhold off;\ntitle('cross validation accuracy over different lambda');\nset(gca,'FontSize',12);\nprint('-dpdf', '-r100', 'LogisticDirty');\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/examples/example_rMTFL_Classify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.59117963950529}}
{"text": "function plotData(X, y)\n%PLOTDATA Plots the data points X and y into a new figure \n%   PLOTDATA(x,y) plots the data points with + for the positive examples\n%   and o for the negative examples. X is assumed to be a Mx2 matrix.\n\n% Create New Figure\nfigure; hold on;\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Plot the positive and negative examples on a\n%               2D plot, using the option 'k+' for the positive\n%               examples and 'ko' for the negative examples.\n%\n\nids = find(y==0);\nXo = X(ids,:);\nplot(Xo(:,1), Xo(:,2), 'ko');\n\nids = find(y==1);\nXo = X(ids,:);\nplot(Xo(:,1), Xo(:,2), 'k+');\n\n\n\n\n\n\n% =========================================================================\n\n\n\nhold off;\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/plotData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.5911796334293671}}
{"text": "function Z=fftfilter(X, H)\nF=fft2(X, size(H,1), size(H, 2));\nZ=H.*F;\nZ=ifftshift(Z);\nZ=abs(ifft2(Z));\nZ=Z(1:size(X, 1), 1:size(X, 2));\nend\n", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/\u300aMATLAB\u56fe\u50cf\u5904\u7406\u300b\u6e90\u6587\u4ef6/\u672c\u4e66\u6e90\u6587\u4ef6/chap6/fftfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5911796182325938}}
{"text": "clear\nclc\nclose all\n\naddpath('data')\naddpath('src')\ndataset = {'1_mECS', '2_Kolod', '3_Pollen', '4_Usoskin'}\n\nfor i = 1:4\n    \n    % perform the analysis for the current dataset\n    load(['Test_' dataset{i}]);\n    C = max(true_labs); %%% number of clusters\n    rng(i,'twister'); %%% for reproducibility\n    [y, S, F, ydata,alpha] = SIMLR(in_X,C,10);\n    \n    % report NMI values\n    NMI_i = Cal_NMI(y,true_labs);\n    fprintf(['The NMI value for dataset ' dataset{i} ' is %f\\n'], NMI_i);\n    \n    % visualization\n    figure;\n    gscatter(ydata(:,1),ydata(:,2),true_labs);\n    \nend\n", "meta": {"author": "BatzoglouLabSU", "repo": "SIMLR", "sha": "bf44967cd40d9d4c789ecf866b3aae15ae6190f5", "save_path": "github-repos/MATLAB/BatzoglouLabSU-SIMLR", "path": "github-repos/MATLAB/BatzoglouLabSU-SIMLR/SIMLR-bf44967cd40d9d4c789ecf866b3aae15ae6190f5/MATLAB/Matlab_main_demo_SIMLR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5910782400276585}}
{"text": "% StackExchange Signal Processing Q62024\n% https://dsp.stackexchange.com/questions/62024\n% Proximal Gradient Method (PGM) for a Function Model with More than 2 Functions (Sum of Functions)\n% References:\n%   1.  aa\n% Remarks:\n%   1.  sa\n% TODO:\n% \t1.  ds\n% Release Notes\n% - 1.0.000     25/11/2019\n%   *   First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 79;\n\nrun('InitScript.m');\n\nfigureIdx           = 0; %<! Continue from Question 1\nfigureCounterSpec   = '%04d';\n\ngenerateFigures = OFF;\n\n\n%% Simulation Parameters\n\nnumElements = 40;\nparamLambda1 = 0.5; %<! L1 Norm\nparamLambda2 = 0.75; %<! TV Norm\n\nnumIterations = 1000; %<! For the ADMM\n\n\n%% Generate Data\n\nvY = 10 * randn(numElements, 1);\n\n% Generate the Diff Operator (1D Gradient) by Finite Differences\nmD = spdiags([-ones(numElements, 1), ones(numElements, 1)], [0, 1], numElements - 1, numElements);\n\nhSolveProxTv = @(vY, paramLambda) SolveProxTvAdmm(vY, mD, paramLambda, numIterations);\n\n% Objective Function\nhObjFun = @(vX) (0.5 * sum( (vX - vY) .^ 2)) + (paramLambda1 * sum(abs(vX))) + (paramLambda2 * sum(abs(mD * vX)));\n\n\n%% Solution by CVX\n\ncvx_begin('quiet')\n    cvx_precision('best');\n    variable vX(numElements);\n    minimize( (0.5 * pow_pos(norm(vX - vY, 2), 2)) + (paramLambda1 * norm(vX, 1)) + (paramLambda2 * norm(mD * vX, 1)));\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 Analytical Solution\n%{\nSolving $ \\arg \\min_x \\frac{1}{2} {\\left\\| x - y \\right\\|}_{2}^{2} +\n{\\lambda}_{1} {\\left\\| x \\right\\|}_{1} + {\\lambda}_{2} {\\left\\| D x \\right\\|}_{1} $\n%}\n\nvX = SolveProxL1(hSolveProxTv(vY, paramLambda2), paramLambda1);\n\ndisp([' ']);\ndisp(['Analytical Direct Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp([' ']);\n\n\n%% Solution by Analytical Solution\n%{\nSolving $ \\arg \\min_x \\frac{1}{2} {\\left\\| x - y \\right\\|}_{2}^{2} +\n{\\lambda}_{1} {\\left\\| x \\right\\|}_{1} + {\\lambda}_{2} {\\left\\| D x \\right\\|}_{1} $\n%}\n\nvX = hSolveProxTv(SolveProxL1(vY, paramLambda1), paramLambda2);\n\ndisp([' ']);\ndisp(['Analytical Direct Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\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/SignalProcessing/Q62024/AnalysisTvL1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.5910742294467443}}
{"text": "function y=gauss_res2(p)\nglobal grab;\nglobal xpix;\nglobal ypix;\nglobal psf_w02;\n\nyfit=p(3)*exp(-2*((xpix-p(1)).*(xpix-p(1))+(ypix-p(2)).*(ypix-p(2)))/psf_w02);\nydev=yfit-double(grab);\nydev2=ydev.*ydev;\ny=sum(sum(ydev2));\n%y=100*(p(2)-p(1)^2)^2+(1-p(1))^2;\nend\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/TGgui070708/gauss_res2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5910582808741879}}
{"text": "function [sol, infos] = gsp_ml_rls(xl, y, k, tau, A, At, param)\n%GSP_ML_RLS Manifold Learning regularized least square\n%   Usage: sol = gsp_ml_rls(xl, y, k, tau);\n%          sol = gsp_ml_rls(xl, y, k, tau, A, At);\n%          sol = gsp_ml_rls(xl, y, k, tau,  A, At, param);\n%          [sol, infos] = gsp_ml_rls(...)\n%   \n%   Input parameters:\n%       xl      : labeled points\n%       y       : labels\n%       k       : kernel\n%       tau     : regularization parameters\n%       A       : Operator\n%       At      : Adoint operator\n%       param   : Optional parameters\n%   Output parameters:\n%       sol     : solution of the problem (kernel coefficients)\n%       infos   : convergence info\n%       \n%   *param* is a structure of optional argument given to the solver\n%   gradient_descent. Please see the function gradient descent for more\n%   information. \n%\n%   In *param*, you also have to set an upperbound for the operator A as\n%   param.nu!\n%\n%   This function solves the following problem:\n%\n%   ..  argmin_alpha  || A (K alpha) - y ||_2^2 + tau *alpha^T K alpha\n%\n%   If tau is set to zero, then the following problem is solved\n%\n%   ..  argmin_alpha alpha^T K alpha s. t.  A (K alpha) = y\n%\n\n% Author: Nathanael Perraudin\n% Date  : 8 decembre 2014\n\n\nif nargin<5\n    A = @(x) x;\nend\n\n\nif nargin<6\n    At = A;\nend\n\nif nargin<7\n    param = struct;\nend\n\n\nif ~isfield(param, 'tol'), param.tol = 1e-6; end\nif ~isfield(param, 'nu'), param.nu = 1; end\nif ~isfield(param, 'verbose'), param.verbose = 1; end\n    \n    \n\n%N = size(xl,2);\n\n% Evaluate the kernel on the data points\nK = gsp_rkhs_evaluate(k,xl);\nnu = norm(K);\n\n[N,M] = size(y);\nNk = length(k);\nalpha_in = zeros(N*Nk,M);\n\nif tau >0\n    \n    fp.eval = @(x) tau * sum(norm_rkhs( K,x ));\n    fp.grad = @(x) tau * grad_rkhs( K,x);\n    fp.beta =   2*nu*tau;\n\n    ffid.eval = @(x) norm(A(K*x)-y,'fro')^2;\n    ffid.grad = @(x) 2*K'*At(A(K*x)-y);\n    ffid.beta = 2*nu^2*param.nu^2;\n\n\n    \n    \n%     paramfid.A = @(x) A(K*x);\n%     paramfid.At = @(x) K'*At(x);\n%     paramfid.nu = nu^2;\n%     paramfid.tight = 0;\n%     paramfid.y = y;\n%     paramfid.verbose = param.verbose -1;\n%     ffid.eval = @(x) norm(A(K*x)-y,'fro')^2;\n%     ffid.prox = @(x,T) prox_l2(x,T,paramfid);\n    \n    [sol,infos] = solvep(alpha_in, {fp,ffid}, param);\n\n%     param.gamma = 0.5/(tau*nu);\n%     [sol,infos] = forward_backward(alpha_in, ffid, fp, param);\nelse\n    \n    fp.eval = @(x) sum(norm_rkhs( K,x ));\n    fp.grad = @(x) grad_rkhs( K,x);\n    fp.beta =   2*nu;\n\n    \n    paramproj.A = @(x) A(K*x);\n    paramproj.At = @(x) K'*At(x);\n    paramproj.nu = nu^2*param.nu^2;\n    paramproj.tight = 0;\n    paramproj.verbose = param.verbose-1;\n    paramproj.y = y;\n    paramproj.maxit = 50;\n    ffid.eval = @(x) eps;\n    ffid.prox = @(x,T) proj_b2(x,T,paramproj);\n\n\n    [sol,infos] = forward_backward(alpha_in, ffid, fp, param);\n\nend\n\n\n\n\nend", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/graph_ml/gsp_ml_rls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5909716762902752}}
{"text": "function o = boxoverlap(a, b)\n% Compute the symmetric intersection over union overlap between a set of\n% bounding boxes in a and a single bounding box in b.\n%\n% a  a matrix where each row specifies a bounding box\n% b  a single bounding box\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2011-2012 Ross Girshick\n% Copyright (C) 2008, 2009, 2010 Pedro Felzenszwalb, Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\nx1 = max(a(:,1), b(1));\ny1 = max(a(:,2), b(2));\nx2 = min(a(:,3), b(3));\ny2 = min(a(:,4), b(4));\n\nw = x2-x1+1;\nh = y2-y1+1;\ninter = w.*h;\naarea = (a(:,3)-a(:,1)+1) .* (a(:,4)-a(:,2)+1);\nbarea = (b(3)-b(1)+1) * (b(4)-b(2)+1);\n% intersection over union overlap\no = inter ./ (aarea+barea-inter);\n% set invalid entries to 0 overlap\no(w <= 0) = 0;\no(h <= 0) = 0;", "meta": {"author": "liangzheng06", "repo": "PRW-baseline", "sha": "7dac8c62e4b2ec0c6e9a054b65bc438fccdb2356", "save_path": "github-repos/MATLAB/liangzheng06-PRW-baseline", "path": "github-repos/MATLAB/liangzheng06-PRW-baseline/PRW-baseline-7dac8c62e4b2ec0c6e9a054b65bc438fccdb2356/utils/boxoverlap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.590971669451329}}
{"text": "%IM_SELECT_BLOB Fixed mapping selecting largest blob in binary images (DIP_Image)\n%\n%       B = IM_SELECT_BLOB(A)\n%       B = A*IM_SELECT_BLOB\n%\n% Just the largest object in the image is returned.\n%\n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% DATASETS, DATAFILES, DIP_IMAGE\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 b = im_select_blob(a)\n\n\t\t\n  if nargin < 1 | isempty(a)\n    b = prmapping(mfilename,'fixed');\n    b = setname(b,'Select largest blob');\n\telseif isa(a,'prdataset') % allows datafiles too\n\t\tisobjim(a);\n    b = filtim(a,mfilename);\n\t\tb = setfeatsize(b,getfeatsize(a));\n  elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image\n    if ~isa(a,'dip_image')\n\t\t\ta = dip_image(a,'bin');\n\t\tend;\n\t\tlabim = label(a);\n\t\tsz = measure(labim,labim,{'size'});\n\t\t[cc,ind] = max(double(sz));\n\t\tI = double(measure(labim,labim,{'mean'}));\n\t\tb = a.*(labim==round(I(ind)));\n%\t\tc = measure(labim,labim,{'size','mean'});\n%\t\tc = double(c);\n%\t\t[cc,ind] = max(c(:,1));\n%\t\tb = a.*(labim==round(c(ind,2)));\n\tend\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/im_select_blob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5909716645740605}}
{"text": "classdef KnEA < ALGORITHM\n% <many> <real/integer/label/binary/permutation> <constrained/none>\n% Knee point driven evolutionary algorithm\n% rate --- 0.5 --- Rate of knee points in the population\n\n%------------------------------- Reference --------------------------------\n% X. Zhang, Y. Tian, and Y. Jin, A knee point-driven evolutionary algorithm\n% for many-objective optimization, IEEE Transactions on Evolutionary\n% Computation, 2015, 19(6): 761-776.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Parameter setting\n            rate = Algorithm.ParameterSet(0.5);\n\n            %% Generate random population\n            Population = Problem.Initialization();\n            FrontNo    = NDSort(Population.objs,Population.cons,inf);\n            KneePoints = zeros(1,Problem.N);     % Set of knee points\n            r          = -ones(1,2*Problem.N);\t% Ratio of size of neighorhood\n            t          = -ones(1,2*Problem.N);\t% Ratio of knee points\n\n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                MatingPool = MatingSelection(Population.objs,FrontNo,KneePoints);\n                Offspring  = OperatorGA(Problem,Population(MatingPool));\n                Population = [Population,Offspring];\n                [FrontNo,MaxFNo]                = NDSort(Population.objs,Population.cons,Problem.N);\n                [KneePoints,Distance,r,t]       = FindKneePoints(Population.objs,FrontNo,MaxFNo,r,t,rate);\n                [Population,FrontNo,KneePoints] = EnvironmentalSelection(Population,FrontNo,MaxFNo,KneePoints,Distance,Problem.N);      \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/Algorithms/Multi-objective optimization/KnEA/KnEA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5909716548195226}}
{"text": "function [yd3] = gal2yd3(gal)\n% Convert volume from US liquid gallons to cubic yards. \n% Chad Greene 2012\nyd3 = gal*0.0049511316873;", "meta": {"author": "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/gal2yd3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5909378078755048}}
{"text": "function rs = amutual2(s, len)\n\n%tstoolbox/@signal/amutual2\n%   Syntax:\n%     * amutual2(s, len)\n%\n%   Input arguments:\n%     * len - maximal lag\n%\n%   Auto mutual information (average) function for real scalar signals\n%   using 128 equidistant partitions.\n%\n% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt\nnarginchk(2,2);\n\n    if (ndim(s) > 1) | (~isreal(data(s)))\n\thelp(mfilename)\n\treturn\nend\n\nc = amutual2(s.core, len);\nrs = signal(c, s);\t% special constructor calling syntax for working routines\na = getaxis(s, 1); \ndl = delta(a);\na = setfirst(a, 0);\nrs = setaxis(rs, 1, a);\nrs = setyunit(rs, unit('Bit'));\t\t% acf values are scalars without unit\nrs = addhistory(rs, ['Auto mutual information of length ' num2str(len)]);\nrs = addcommandlines(rs, 's = amutual(s', len);\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/amutual2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.5909377866889061}}
{"text": "function set_theory_test ( )\n\n%*****************************************************************************80\n%\n%% SET_THEORY_TEST tests the SET_THEORY library.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 March 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'SET_THEORY_TEST:\\n' );\n  fprintf ( 1, '  MATLAB version\\n' );\n  fprintf ( 1, '  Test the SET_THEORY library.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Demonstrate some set theory operations that\\n' );\n  fprintf ( 1, '  can be implemented in MATLAB.\\n' );\n\n  set_theory_test01 ( );\n%\n%  Terminate.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'SET_THEORY_TEST:\\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/set_theory/set_theory_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.5908436311935518}}
{"text": "function linpack_z_test14 ( )\n\n%*****************************************************************************80\n%\n%% TEST14 tests ZHPCO.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 June 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 3;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST14\\n' );\n  fprintf ( 1, '  For a double precision complex (C)\\n' );\n  fprintf ( 1, '  Hermitian matrix using packed storage (HP),\\n' );\n  fprintf ( 1, '  ZHPCO factors the matrix and estimates\\n' );\n  fprintf ( 1, '  the reciprocal condition number.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The matrix order is N = %d\\n', n );\n%\n%  Set the values of the matrix A.\n%\n  k = 0;\n  seed = 123456789;\n\n  for j = 1 : n\n\n    for i = 1 : j-1\n      k = k + 1;\n      [ a(k), seed ] = c8_uniform_01 ( seed );\n      a_save(i,j) = a(k);\n      a_save(j,i) = conj ( a(k) );\n    end\n\n    k = k + 1;\n    [ a(k), seed ] = r8_uniform_01 ( seed );\n    a_save(j,j) = a(k);\n\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The matrix A:\\n' );\n  fprintf ( 1, '\\n' );\n\n  for i = 1 : n\n    for j = 1 : n\n      fprintf ( 1, '  (%8f  %8f)', real ( a_save(i,j) ), imag ( a_save(i,j) ) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n%\n%  Factor the matrix A.\n%\n  [ a, ipvt, rcond ] = zhpco ( a, n );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Estimated reciprocal condition RCOND = %f\\n', rcond );\n\n  return\nend\n", "meta": {"author": "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_z/linpack_z_test14.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5908436307049597}}
{"text": "function [distance,branch] = breadth(CIJ,source)\n%BREADTH        Auxiliary function for breadthdist.m\n%\n%   [distance,branch] = breadth(CIJ,source);\n%\n%   Implementation of breadth-first search.\n%\n%   Input:      CIJ,        binary (directed/undirected) connection matrix\n%               source,     source vertex\n%\n%   Outputs:    distance,   distance between 'source' and i'th vertex\n%                           (0 for source vertex)\n%               branch,     vertex that precedes i in the breadth-first search tree\n%                           (-1 for source vertex)\n%        \n%   Notes: Breadth-first search tree does not contain all paths (or all \n%   shortest paths), but allows the determination of at least one path with\n%   minimum distance. The entire graph is explored, starting from source \n%   vertex 'source'.\n%\n%\n%   Olaf Sporns, Indiana University, 2002/2007/2008\n\nN = size(CIJ,1);\n\n% colors: white, gray, black\nwhite = 0; \ngray = 1; \nblack = 2;\n\n% initialize colors\ncolor = zeros(1,N);\n% initialize distances\ndistance = inf*ones(1,N);\n% initialize branches\nbranch = zeros(1,N);\n\n% start on vertex 'source'\ncolor(source) = gray;\ndistance(source) = 0;\nbranch(source) = -1;\nQ = source;\n\n% keep going until the entire graph is explored\nwhile ~isempty(Q)\n   u = Q(1);\n   ns = find(CIJ(u,:));\n   for v=ns\n% this allows the 'source' distance to itself to be recorded\n      if (distance(v)==0)\n         distance(v) = distance(u)+1;\n      end;\n      if (color(v)==white)\n         color(v) = gray;\n         distance(v) = distance(u)+1;\n         branch(v) = u;\n         Q = [Q v];                                             %#ok<AGROW>\n      end;\n   end;\n   Q = Q(2:length(Q));\n   color(u) = black;\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/bct/breadth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5908436302163674}}
{"text": "function varargout = drawGrid3d(varargin)\n%DRAWGRID3D Draw a 3D grid on the current axis.\n%\n%   drawGrid3d\n%   draws a 3D square grid, with origin (0,0,0) and spacing 1 in each\n%   direction, with bounds corresponding to the bounds of current axis.\n%\n%   drawGrid3d(SPACING)\n%   where spacing is either a scalar or a [1x3] matrix, specifies the size\n%   of the unit cell.\n%\n%   drawGrid3d(ORIGIN, SPACING)\n%   Also specify origin of grid. ORIGIN is a [1x3] array.\n%\n%   drawGrid3d(..., EDGE)\n%   specifies whether function should draw edges touching edges of axis.\n%   EDGE is a characheter string, which can be :\n%   - 'OPEN' : each line start from one face of window to the opposite\n%   face. This results in a 'spiky' grid.\n%   - 'CLOSED' (default value) : each line stops at the last visible point\n%   of the grid for this line. The result looks like a box (no free spikes\n%   around the grid).\n%\n%   H = drawGrid3d(...);\n%   return a vector of handles for each LINE object which was crated.\n%\n\n%   ------\n%   Author: David Legland\n%   e-mail: david.legland@grignon.inra.fr\n%   Created: 2005-11-17\n%   Copyright 2005 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n%% initialize variables -----\n\n% default values\nclosed = true;\norigin = [0 0 0];\nspacing = [1 1 1];\n\n% check if grid is open or not\nstr = '';\nif ~isempty(varargin)\n    str = varargin{end};\nend\nif ischar(str)\n    if strncmpi(str, 'open', 4)\n        closed = false;\n    end\n    varargin = varargin(1:end-1);\nend\n\n% check origin and grid spacing\nif length(varargin)==1\n    spacing = varargin{1};\nelseif length(varargin)==2\n    origin = varargin{1};\n    spacing = varargin{2};\nend\n\n%% Compute internam data -----\n\n% get axis limits\nax = axis;\nx0 = ax(1); x1 = ax(2);\ny0 = ax(3); y1 = ax(4);\nz0 = ax(5); z1 = ax(6);\n\n% get first and last coordinates of the grid in each direction\ndx = spacing(1); dy = spacing(2); dz = spacing(3);\nxe = x0 + mod(origin(1) - x0, dx);\nxf = x1 - mod(x1 - origin(1), dx);\nye = y0 + mod(origin(2) - y0, dy);\nyf = y1 - mod(y1 - origin(2), dy);\nze = z0 + mod(origin(1) - z0, dz);\nzf = z1 - mod(z1 - origin(1), dz);\n\n% update first and last coordinate if grid is 'closed'\nif closed\n    x0 = xe; x1 = xf;\n    y0 = ye; y1 = yf;\n    z0 = ze; z1 = zf;\nend\n\n\n%% Draw the grid -----\n\nh = [];\n%TODO: rewrite code, avoiding loops\n\n% draw lines parallel to x axis\nfor y = ye:dy:yf\n    for z = ze:dz:zf\n        h = [h; drawEdge3d([x0 y z x1 y z])]; %#ok<AGROW>\n    end\nend\n\n% draw lines parallel to y axis\nfor x = xe:dx:xf\n    for z = ze:dz:zf\n        h = [h; drawEdge3d([x y0 z x y1 z])]; %#ok<AGROW>\n    end\nend\n\n% draw lines parallel to z axis\nfor x = xe:dx:xf\n    for y = ye:dy:yf\n        h = [h; drawEdge3d([x y z0 x y z1])]; %#ok<AGROW>\n    end\nend\n\n\n%% Check output arguments -----\n\nif nargout>0\n    varargout{1} = h;\nend\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/drawGrid3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.590843626389377}}
{"text": "function varargout = chebpolyval3(f, varargin)\n%CHEBPOLYVAL3   Values of a CHEBFUN3 object F on a tensor product grid.\n%   X = CHEBPOLYVAL3(F, M, N, P) returns an M x N x P tensor of values of a\n%   CHEBFUN3 object F on a tensor product grid.\n%\n%   X = CHEBPOLYVAL3(F) does the same but sets M, N, and P equal to the \n%   length of F.\n%\n%   [CORE, C, R, T] = CHEBPOLYVAL3(F) returns the low rank representation \n%   of the values of F on a tensor product grid, i.e.,\n%   X = CORE x_1 C x_2 R x_3 T.\n% \n%   Example: For an order-3 discrete tensor R, we should have \n%                                       R \\approx chebpolyval3(chebfun3(R)).\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    varargout = { [] }; \n    return\nend\n\nif ( nargin == 1 ) \n    % Get degrees:\n    [m, n, p] = length(f);\nelseif ( nargin ~= 4 ) \n    error('CHEBFUN:CHEBFUN3:chebpolyval3:inputs', 'Dimension not specified.'); \nelse\n    m = varargin{1}; \n    n = varargin{2}; \n    p = varargin{3}; \nend\n\n% Get low rank representation of f:\n[core, cols, rows, tubes] = tucker(f);\n\ntech = chebfunpref().tech(); \ncolVals = tech.coeffs2vals(chebcoeffs(cols, m));\nrowVals = tech.coeffs2vals(chebcoeffs(rows, n));\ntubeVals = tech.coeffs2vals(chebcoeffs(tubes, p));\n\n% Evaluate: \nif ( nargout <= 1 )\n    varargout = {chebfun3.txm(chebfun3.txm(chebfun3.txm(core, colVals, 1), ...\n        rowVals, 2), tubeVals, 3)};\nelse\n    varargout = {core, colVals, rowVals, tubeVals};\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/@chebfun3/chebpolyval3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5908430885997504}}
{"text": "function sparse_unique_index = sgmga_unique_index ( dim_num, level_weight, ...\n  level_max, rule, growth, np, p, tol, point_num, point_total_num )\n\n%*****************************************************************************80\n%\n%% SGMGA_UNIQUE_INDEX maps nonunique to unique points of an SGMGA grid.\n%\n%  Discussion:\n%\n%    The sparse grid usually contains many points that occur in more\n%    than one product grid.\n%\n%    When generating the point locations, it is easy to realize that a point\n%    has already been generated.\n%\n%    But when it's time to compute the weights of the sparse grids, it is\n%    necessary to handle situations in which weights corresponding to\n%    the same point generated in multiple grids must be collected together.\n%\n%    This routine generates ALL the points, including their multiplicities,\n%    and figures out a mapping from them to the collapsed set of unique points.\n%\n%    This mapping can then be used during the weight calculation so that\n%    a contribution to the weight gets to the right place.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 April 2011\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%    Fabio Nobile, Raul Tempone, Clayton Webster,\n%    An Anisotropic Sparse Grid Stochastic Collocation Method for Partial \n%    Differential Equations with Random Input Data,\n%    SIAM Journal on Numerical Analysis,\n%    Volume 46, Number 5, 2008, pages 2411-2442.\n%\n%  Parameters:\n%\n%    Input, integer DIM_NUM, the spatial dimension.\n%\n%    Input, real LEVEL_WEIGHT(DIM_NUM), the anisotropic weights.\n%\n%    Input, integer LEVEL_MAX, the maximum value of LEVEL.\n%\n%    Input, integer RULE(DIM_NUM), the rule in each dimension.\n%     1, \"CC\",  Clenshaw Curtis, Closed Fully Nested.\n%     2, \"F2\",  Fejer Type 2, Open Fully Nested.\n%     3, \"GP\",  Gauss Patterson, Open Fully Nested.\n%     4, \"GL\",  Gauss Legendre, Open Weakly Nested.\n%     5, \"GH\",  Gauss Hermite, Open Weakly Nested.\n%     6, \"GGH\", Generalized Gauss Hermite, Open Weakly Nested.\n%     7, \"LG\",  Gauss Laguerre, Open Non Nested.\n%     8, \"GLG\", Generalized Gauss Laguerre, Open Non Nested.\n%     9, \"GJ\",  Gauss Jacobi, Open Non Nested.\n%    10, \"HGK\", Hermite Genz-Keister, Open Fully Nested.\n%    11, \"UO\",  User supplied Open, presumably Non Nested.\n%    12, \"UC\",  User supplied Closed, presumably Non Nested.\n%\n%    Input, integer GROWTH(DIM_NUM), the growth in each dimension.\n%    0, \"DF\", default growth associated with this quadrature rule;\n%    1, \"SL\", slow linear, L+1;\n%    2  \"SO\", slow linear odd, O=1+2((L+1)/2)\n%    3, \"ML\", moderate linear, 2L+1;\n%    4, \"SE\", slow exponential;\n%    5, \"ME\", moderate exponential;\n%    6, \"FE\", full exponential.\n%\n%    Input, integer NP(DIM_NUM), the number of parameters used by each rule.\n%\n%    Input, real P(*), the parameters needed by each rule.\n%\n%    Input, real TOL, the tolerance for point equality.\n%\n%    Input, integer POINT_NUM, the number of unique points in\n%    the grid.\n%\n%    Input, integer POINT_TOTAL_NUM, the total number of points\n%    in the grid.\n%\n%    Output, integer SPARSE_UNIQUE_INDEX(POINT_TOTAL_NUM), lists,\n%    for each (nonunique) point, the corresponding index of the same point in\n%    the unique listing.\n%\n\n%\n%  Special cases.\n%\n  if ( level_max < 0 )\n    sparse_unique_index = [];\n    return\n  end\n\n  if ( level_max == 0 )\n    sparse_unique_index(1) = 1;\n    return\n  end\n%\n%  Generate SPARSE_TOTAL_ORDER and SPARSE_TOTAL_INDEX arrays\n%  for the TOTAL set of points.\n%\n  sparse_total_order = zeros(dim_num,point_total_num);\n  sparse_total_index = zeros(dim_num,point_total_num);\n\n  point_total_num2 = 0;\n%\n%  Initialization for SGMGA_VCN_ORDERED.\n%\n  level_weight_min_pos = r8vec_min_pos ( dim_num, level_weight );\n  q_min = level_max * level_weight_min_pos - sum ( level_weight(1:dim_num) );\n  q_max = level_max * level_weight_min_pos;\n  level_1d_max = zeros(dim_num,1);\n  for dim = 1 : dim_num\n    if ( 0.0 < level_weight(dim) )\n      level_1d_max(dim) = floor ( q_max / level_weight(dim) ) + 1;\n      if ( q_max <= ( level_1d_max(dim) - 1 ) * level_weight(dim) )\n        level_1d_max(dim) = level_1d_max(dim) - 1;\n      end\n    else\n      level_1d_max(dim) = 0;\n    end\n  end\n  more_grids = 0;\n  level_1d = [];\n%\n%  Seek all vectors LEVEL_1D which satisfy the constraint:\n%\n%    LEVEL_MAX * LEVEL_WEIGHT_MIN_POS - sum ( LEVEL_WEIGHT ) \n%      < sum ( 1 <= I <= DIM_NUM ) LEVEL_WEIGHT(I) * LEVEL_1D(I)\n%      <= LEVEL_MAX * LEVEL_WEIGHT_MIN_POS.\n%\n  while ( 1 )\n\n    [ level_1d, more_grids ] = sgmga_vcn_ordered ( dim_num, level_weight, ...\n      level_1d_max, level_1d, q_min, q_max, more_grids );\n\n    if ( ~more_grids )\n      break\n    end\n%\n%  Compute the combinatorial coefficient.\n%\n    coef = sgmga_vcn_coef ( dim_num, level_weight, level_1d, q_max );\n\n    if ( coef == 0.0 )\n      continue\n    end\n%\n%  Transform each 1D level to a corresponding 1D order.\n%\n    order_1d = level_growth_to_order ( dim_num, level_1d, rule, growth );\n%\n%  The inner loop generates a POINT of the GRID of the LEVEL.\n%\n    point_index = [];\n    more_points = 0;\n\n    while ( 1 )\n\n      [ point_index, more_points ] = vec_colex_next3 ( dim_num, order_1d, ...\n        point_index, more_points );\n\n      if ( ~more_points )\n        break;\n      end\n\n      point_total_num2 = point_total_num2 + 1;\n      sparse_total_order(1:dim_num,point_total_num2) = order_1d(1:dim_num);\n      sparse_total_index(1:dim_num,point_total_num2) = point_index(1:dim_num);\n\n    end\n\n  end\n%\n%  Now compute the coordinates of the TOTAL set of points.\n%\n  sparse_total_point = zeros(dim_num,point_total_num);\n  sparse_total_point(1:dim_num,1:point_total_num) = r8_huge ( );\n\n  level_weight_min_pos = r8vec_min_pos ( dim_num, level_weight );\n  q_max = level_max * level_weight_min_pos;\n\n  p_index = 1;\n\n  for dim = 1 : dim_num\n\n    if ( 0 < level_weight(dim) )\n      level_1d_max(dim) = floor ( q_max / level_weight(dim) ) + 1;\n      if ( q_max <= ( level_1d_max(dim) - 1 ) * level_weight(dim) )\n        level_1d_max(dim) = level_1d_max(dim) - 1;\n      end\n    else\n      level_1d_max(dim) = 0;\n    end\n\n    for level = 0 : level_1d_max(dim)\n\n      order = level_growth_to_order  ( 1, level, rule(dim), growth(dim) );\n\n      if ( rule(dim) == 1 )\n        points = clenshaw_curtis_compute_points ( order );\n      elseif ( rule(dim) == 2 )\n        points = fejer2_compute_points ( order );\n      elseif ( rule(dim) == 3 )\n        points = patterson_lookup_points ( order );\n      elseif ( rule(dim) == 4 )\n        points = legendre_compute_points ( order );\n      elseif ( rule(dim) == 5 )\n        points = hermite_compute_points ( order );\n      elseif ( rule(dim) == 6 )\n        alpha = p(p_index);\n        points = gen_hermite_compute_points ( order, alpha );\n      elseif ( rule(dim) == 7 )\n        points = laguerre_compute_points ( order );\n      elseif ( rule(dim) == 8 )\n        alpha = p(p_index);\n        points = gen_laguerre_compute_points ( order, alpha );\n      elseif ( rule(dim) == 9 )\n        alpha = p(p_index);\n        beta = p(p_index+1);\n        points = jacobi_compute_points ( order, alpha, beta );\n      elseif ( rule(dim) == 10 )\n        points = hermite_genz_keister_lookup_points ( order );\n      elseif ( rule(dim) == 11 )\n        fprintf ( 1, '\\n' );\n        fprintf ( 1, 'SGMGA_UNIQUE_INDEX - Fatal error!\\n' );\n        fprintf ( 1, '  Do not know how to assign points for rule 11.\\n' );\n        error ( 'SGMGA_UNIQUE_INDEX - Fatal error!' );\n      elseif ( rule(dim) == 12 )\n        fprintf ( 1, '\\n' );\n        fprintf ( 1, 'SGMGA_UNIQUE_INDEX - Fatal error!\\n' );\n        fprintf ( 1, '  Do not know how to assign points for rule 12.\\n' );\n        error ( 'SGMGA_UNIQUE_INDEX - Fatal error!' );\n      else\n        fprintf ( 1, '\\n' );\n        fprintf ( 1, 'SGMGA_UNIQUE_INDEX - Fatal error!\\n' );\n        fprintf ( 1,'  Unexpected value of RULE = %d\\n', rule(dim) );\n        error ( 'SGMGA_UNIQUE_INDEX - Fatal error!' );\n      end\n\n      index = find ( sparse_total_order(dim,1:point_total_num) == order );\n\n      sparse_total_point(dim,index) = points ( sparse_total_index(dim,index) );\n\n    end\n\n    p_index = p_index + np(dim);\n\n  end\n%\n%  Merge points that are too close.\n%\n  seed = 123456789;\n \n  [ point_num, undx, sparse_unique_index, seed ] = ...\n    point_radial_tol_unique_index ( dim_num, point_total_num, ...\n    sparse_total_point, tol, seed );\n\n  for point = 1 : point_total_num\n    rep = undx(sparse_unique_index(point));\n    if ( point ~= rep )\n      sparse_total_point(1:dim_num,point) = sparse_total_point(1:dim_num,rep);\n    end\n  end\n%\n%  Construct an index that indicates the \"rank\" of the unique points.\n%\n  [ undx, sparse_unique_index ] = point_unique_index ( dim_num, ...\n    point_total_num, sparse_total_point, 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/sgmga/sgmga_unique_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5908430776062088}}
{"text": "function [ res ] = bellman_residual(Qt,Qtmp)\n%BELLMAN_RESIDUAL Computes the Bellman residual\n%\n%   input -------------------------------------------------------\n%       \n%       o Q: Q-value function at time t\n%       \n%       o Qtmp: Q-value function at time t-1\n%\n\n\nvt   = compute_value_function(Qt);\nvtmp =  compute_value_function(Qtmp);\n\nres = (vt - vtmp).^2;\nres = sum(res(:)) / size(vt(:),1);\n\n\n\nend\n\n\nfunction v = compute_value_function(nfq_Q)\n\nu           = BuildActionList();\nnum_actions = 2;\nnbSamples   = 100;\nxs          = linspace(-1,1,nbSamples);\n[Xs,Ys]     = meshgrid(xs,xs);\ntest        = [Xs(:),Ys(:)];\nvs          = zeros(size(test,1),num_actions);\n\nM           = size(test,1);\n\nif iscell(nfq_Q)\n    for i=1:num_actions\n        vs(:,i) = nfq_Q{i}.f(test);\n    end\nelse\n    for i=1:num_actions\n        test_ui = [test,repmat(u(i),M,1)];\n        vs(:,i) = nfq_Q.f(test_ui);\n    end\nend\n\nv          = min(vs,[],2);\n\n\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/rl_common_functions/bellman_residual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5908430666126667}}
{"text": "function h=semiaudplot(x,y,varargin)\n%SEMIAUDPLOT  2D plot on auditory scale\n%   Usage: h=semiaudplot(x,y);\n%\n%   `semiaudplot(x,y)` plots the data $(x,y)$ on an auditory scale. By\n%   default the values of the x-axis will be shown on the Erb-scale.\n%\n%   `semiaudplot` takes the following parameters at the end of the line of input\n%   arguments:\n%\n%     'x'       Make the x-axis use the auditory scale. This is the default.\n%\n%     'y'       Make the y-axis use the auditory scale.\n%\n%     'opts',c  Pass options stored in a cell array onto the plot\n%               function.\n%\n%   In addition to these parameters, the auditory scale can be\n%   specified. All scales supported by |freqtoaud| are supported. The default\n%   is to use the erb-scale.     \n%\n%   See also: freqtoaud\n\nif nargin<2\n  error('%s: Too few input parameters.',upper(mfilename));\nend;\n\ndefinput.import       = {'ltfattranslate','freqtoaud'};\ndefinput.flags.plotdir= {'x','y'};\ndefinput.keyvals.tick = [0,100,250,500,1000,2000,4000,8000,16000];\ndefinput.keyvals.res  = 500;\ndefinput.keyvals.opts = {};\n\n[flags,kv]=ltfatarghelper({},definput,varargin);\n\nn=500;\ntickpos=freqtoaud(kv.tick,flags.audscale);\n    \nif flags.do_x\n  xmin=min(x);\n  xmax=max(x);\n  audminmax=freqtoaud([xmin,xmax],flags.audscale);\n  \n  plotval=spline(x,y,audspace(xmin,xmax,n,flags.audscale));\n  plot(linspace(audminmax(1),audminmax(2),n),plotval,kv.opts{:});\n  set(gca,'XTick',tickpos);\n  set(gca,'XTickLabel',num2str(kv.tick(:)));\n  xlabel(sprintf('%s (Hz)',kv.frequency));\n \nend;\n\nif flags.do_y\n  ymin=min(y);\n  ymax=max(y);\n  audminmax=freqtoaud([ymin,ymax],flags.audscale);\n  \n  plot(x,freqtoerb(y),kv.opts{:});\n  set(gca,'YTick',tickpos);\n  set(gca,'YTickLabel',num2str(tick(:)));\n  \n  ylabel(sprintf('%s (Hz)',kv.frequency));\nend;\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/auditory/semiaudplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5908430658665954}}
{"text": "function [A,B, S, err] = wls(x,y)\n    %WEIGHTED LINEAR LEAST SQUARES REGRESSION\n    %\t[A, B, S, err] = WLS(x,y) finds the A and B coefficients of A log cumalative frequency\n    %curve and the error.\n    %      A, B: a- and b- values of a weighted linear regression fit.\n    %    err: estimate of the std deviation of the error in predicting a future observation at X by A and B\n    %      S: contains fields for triangular factor(R) from QR decomp... see polyfit (used in polyval)\n    %    \n    %report_this_filefun();\n    %partially vectorized version\n    \n%    global S % output of POLYFIT used for error estimates\n    %mima = min(x);\n    \n    S=[];\n    err=inf;\n    \n    if any(size(x) ~= size(y))\n        error('X and Y vectors must be the same size.')\n    end\n    x = x(:);\n    y = y(:);\n    l = isinf(y); \n    y(l) = [];\n    x(l) = [];\n    % weight the values\n    teny= 10.^y;\n    wx = ones(1,ceil(sum(teny)));  \n    wy = wx; \n    fteny=floor(teny);\n    ks = cumsum([1; fteny]);\n    for i = 1:length(x)\n        wx(ks(i):ks(i+1)-1) = wx(ks(i):ks(i+1)-1) * x(i);\n        wy(ks(i):ks(i+1)-1) = wy(ks(i):ks(i+1)-1) * teny(i);\n    end\n    %x = wx;\n    %y = log10(wy);\n    \n    l = wx  > min(x);%mima;\n    \n    %[B, A,err ] = ma(x',y');\n    %b2 = -abs(B);\n    \n    if sum(l) <= 5\n        p = [NaN NaN] ; \n    elseif nargout > 2\n        [p,S] = polyfit(wx(l),log10(wy(l)),1);\n        if nargout==4 && S.df > 0\n            [~,err] = polyval(p,wx,S);\n            err = mean(err);\n        end\n    else\n        p = polyfit(wx(l),log10(wy(l)),1);\n    end\n    A = p(2);\n    B = p(1) ;\nend\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/wls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5908205050875059}}
{"text": "function [W V] = genhull(U, wtype)\n%GENHULL Generate \"hull\" matrices from orthonormal matrices\n%\tW = GENHULL(U)\n%\tW = GENHULL(U, wtype)\n%\t[W V] = GENHULL(U)\n%\t[W V] = GENHULL(U, wtype)\n%\t\n%\tU     - matrices in a cell with orthonormal column vectors (U{i}' * U{i} = I)\n%\twtype - weight function type for each matrix (default: 'snnn')\n%\t\n%\tW     - \"hull\" matrices (weight functions)\n%\tV     - vertex matrices (W{i}*V{i} = U{i})\n%\t\n%\twtype parameter controls the type of the column vectors in the resulting\n%\tW matrices.\n%\t\"hull\" matrix means that the row sums are 1 and each element is positive\n%\t\tie.: W{i}*ones == ones && all(all(W{i} >= 0)) &&\n%\t\t     exists V{i} such that W{i}*V{i} = U{i}\n%\n%\tpossible values of wtype:\n%\t\t'eye': return eye(size(U{i},1))\n%\t\t'ortho': keep as is: W{i} = U{i} (not hull matrix!)\n%\t\t'snnn': general non-negative sum-normalized (convex combination)\n%\t\t'cno': 'snnn' and each weight function comes close to 1 (tight hull)\n%\t\t'irno': 'snnn' and each weight function comes close to 0\n%\t\t'box': perform box_decomp\n%\t\n%\tSee also HOSVD, DECOMP.\n\nif nargin <= 1\n\t% TODO\n\twtype = 'close';\nend\n\n\nif ~iscell(U)\n\t% only one matrix\n\tif nargout < 2\n\t\tW = decomp(U, wtype);\n\telse\n\t\t[W V] = decomp(U, wtype);\n\tend\n\treturn\nend\n\nif ~iscell(wtype)\n\ttmp = wtype;\n\twtype = cell(1,length(U));\n\tfor i = 1:length(U)\n\t\twtype{i} = tmp;\n\tend\nend\n\n% TODO: allow skipping last few U?\n%assert(length(U) == length(wtype));\n\nW = cell(1,length(wtype));\nif nargout < 2\n\tfor i = 1:length(wtype)\n\t\tif isempty(U{i})\n\t\t\tW{i} = [];\n\t\telse\n\t\t\tW{i} = decomp(U{i}, wtype{i});\n\t\tend\n\tend\nelse\n\tV = cell(1,length(wtype));\n\tfor i = 1:length(wtype)\n\t\tif isempty(U{i})\n\t\t\tW{i} = [];\n\t\t\tV{i} = [];\n\t\telse\n\t\t\t[W{i} V{i}] = decomp(U{i}, wtype{i});\n\t\tend\n\tend\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/hull/genhull.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5908204876091165}}
{"text": "% MatrixUser, a multi-dimensional matrix analysis software package\n% https://sourceforge.net/projects/matrixuser/\n% \n% The MatrixUser is a matrix analysis software package developed under Matlab\n% Graphical User Interface Developing Environment (GUIDE). It features \n% functions that are designed and optimized for working with multi-dimensional\n% matrix under Matlab. These functions typically includes functions for \n% multi-dimensional matrix display, matrix (image stack) analysis and matrix \n% processing.\n%\n% Author:\n%   Fang Liu <leoliuf@gmail.com>\n%   University of Wisconsin-Madison\n%   Aug-30-2014\n\n\n\nfunction MU_funcSurfl(Temp,Event,handles)\nhandles = guidata(handles.MU_matrix_display);\n\nfigure;\nsurfl(double(handles.BMatrix));\nshading interp;\ncolormap(handles.V.Color_map);\n\n\nend", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/External/MatrixUser2.2/Src/FuncLib/MU_funcSurfl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.5907444780471187}}
{"text": "clear; close all; clc;\n \n% vector field\n \n[x,y]=meshgrid(-2:0.3:2,-2:.3:2);\n \nu=x.^2;\nv=y;\n \nquiver(x,y,u,v)\n \ngrid on;\nxlabel('x'); \nylabel('y');\nset(gca,'fontsize',15);\n ", "meta": {"author": "angeloyeo", "repo": "gongdols", "sha": "7be9fbd988dec6edab1dc881cb22d63e6f69398d", "save_path": "github-repos/MATLAB/angeloyeo-gongdols", "path": "github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/\ubbf8\uc801\ubd84\ud559/flux_vector_field.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5907444733122552}}
{"text": "function combo_test07 ( )\n\n%*****************************************************************************80\n%\n%% COMBO_TEST07 tests I4_FACTORIAL.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    23 January 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'COMBO_TEST07:\\n' );\n  fprintf ( 1, '  I4_FACTORIAL evaluates the factorial function.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '     X       Exact F       FACTORIAL(X)\\n' );\n  fprintf ( 1, '\\n' );\n\n  n = 0;\n\n  while ( 1 )\n\n    [ n, x, fx ] = i4_factorial_values ( n );\n\n    if ( n == 0 )\n      break\n    end\n\n    if ( x <= 0.0 )\n      continue\n    end\n\n    fx2 = i4_factorial ( x );\n\n    fprintf ( 1, '  %4d  %12d  %12d\\n', x, fx, fx2 );\n\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/combo/combo_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.590744472978493}}
{"text": "function anim = nrsfmXiaoKanade( W, nBasis )\n% Compute orthographic non-rigid structure from motion using Xiao-Kanade\n%\n% Just check the Xiao's CVPR04 paper\n%\n% USAGE\n%  anim = nrsfmXiaoKanade( W, nBasis )\n%\n% INPUTS\n%  W             - [ 2 x nPoint x nFrame ] set of 2D points\n%  nBasis        - {Computed } number of bases to use\n%\n% OUTPUTS\n%  anim          - Animation object (help Animation for details)\n%\n% EXAMPLE\n%\n% See also COMPUTESMFROMW\n%\n% Vincent's Structure From Motion Toolbox      Version 3.0\n% Copyright (C) 2008-2010 Vincent Rabaud.  [vrabaud-at-cs.ucsd.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the GPL [see external/gpl.txt]\n\nnFrame = size( W, 3 ); nPoint = size( W, 2 );\nanimBest=Animation; animBest.W = W;\n\nW = reshape( permute( W, [ 1 3 2 ] ), [], nPoint );\nanimBest.t = reshape( mean(W,2), 2, nFrame ); animBest.t(3,:) = 0;\nW = bsxfun(@minus,W,mean(W,2));\n\nif nargin<2 || isempty(nBasis)\n  [ U S V ] = svd(W,'econ'); S = diag(S); sumVal = S(1); Kd = 1;\n  while ( Kd<=length(S) ) && ( sumVal < 0.995*sum(abs(S)) )\n    if S(Kd)<0; break; end\n    Kd = Kd + 1; sumVal = sumVal + S(Kd);\n  end\n  W = U(:,1:Kd)*diag(S(1:Kd))*V(:,1:Kd)';\nelse\n  Kd = 3*nBasis;\n  % Check if Kd is not smaller (degenerate deformations)\n  [ U S V ] = svd(W,'econ');\n  S=cumsum(diag(S));\n  ind = find(S>=0.995*S(end));\n  Kd=min(Kd,ind(1));\nend\n\n%%%%%%%%%%%%%%%%%%%%%% Determine K3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nK3 = floor(Kd/3);\n% Basis constraints\nWTildeOri = [ W(1:2:end,:) W(2:2:end,:) ];\n\nwhile 1\n  % Perform random search for 5 seconds\n  t0 = clock; mini = Inf;\n  while etime( clock, t0 )<5\n    indWTmp = randSample(nFrame,K3);\n    tmp = cond( WTildeOri( indWTmp, : ) );\n    if tmp < mini; mini = tmp; indW = indWTmp; end\n  end\n  \n  if mini>1e2 && K3>0; K3=K3-1; else break; end\nend\n\n%%%%%%%%%%%%%%%%%%%%%% Deal with the K3 basis %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Compute initial variables\n[ MTilde S disc ] = svd( W );\nMTilde = MTilde( :, 1:Kd )*S(1:Kd,1:Kd); gj3=zeros(Kd,3,K3);\n\n% Rotation constraints\nQi = sdpvar( Kd, Kd );\nF = set( Qi >= 0 );\n% vect(AXB)=kron(B',A)*vect(X)\nkron1=zeros(nFrame,Kd^2); kron2=zeros(nFrame,Kd^2);\nfor i=1:nFrame\n  kron1(i,:)=kron(MTilde(2*i-1,:),MTilde(2*i-1,:)) - ...\n    kron(MTilde(2*i,:),MTilde(2*i,:));\n  kron2(i,:)=kron(MTilde(2*i,:),MTilde(2*i-1,:));\nend\nobjRotation=abs(kron1*Qi(:))+abs(kron2*Qi(:));\n\n% Solve for Qk using all the constraints\nkk = 1;\nfor i = indW\n  nc = 2*nFrame + 1;\n  objBasis = 0;\n  disp('Computing the basis constraints');\n  for m = indW\n    if m==i; interN = m; else interN = 1 : nFrame; end\n    for n = interN % could be sampled\n      if m==n && m==i\n        objBasis = objBasis +abs(MTilde(2*m-1,:)*Qi*MTilde(2*n-1,:)'-1) ...\n          + abs( MTilde(2*m,:)*Qi*MTilde(2*n,:)' - 1);\n      else\n        objBasis = objBasis +abs(MTilde(2*m-1,:)*Qi*MTilde(2*n-1,:)') ...\n          + abs( MTilde(2*m,:)*Qi*MTilde(2*n,:)' );\n      end\n      \n      objBasis = objBasis + abs( MTilde(2*m-1,:)*Qi*MTilde(2*n,:)' ) + ...\n        abs( MTilde(2*m,:)*Qi*MTilde(2*n-1,:)' );\n    end\n  end\n  \n  % Sample the constraints\n  disp('Solving the SDP');\n  diagno = solvesdp( F,objRotation+objBasis,sdpsettings('solver',...\n    'sdpa,csdp,sedumi,*','dualize',1,'verbose',0));\n  \n  QiTmp = double(Qi);\n  \n  [ U S disc ] = svd( QiTmp ); gj3(:,:,kk) = U(:,1:3)*sqrt(S(1:3,1:3));\n  kk = kk + 1;\nend\n\n%  [U S V]=svd(constr,'econ');\n%  rank(constr)\n%  size(null(constr(1:2*nFrame,:)))\n%  size(constr)\n%  tmp=diag(S)';\n%  tmp(end-3:end)\n%  size(null(constr),2)\n%  return\n%%%%%%%%%%%%%%%%%%%%%% Get K2 and K1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% The explanations given by Xiao04 seems wrong to determine K1 and K2\n%% So, let's do it the lazy way: let's try all possible combinations of K1\n%% and K2\nerrBest = Inf;\nfprintf('\\nSo far, Kd=%d, K3=%d\\n', Kd, K3 );\nfor K2 = floor((Kd-3*K3)/2) : -1 : 0\n  K1 = Kd - 3*K3 - 2*K2;\n  K = K3+K2+K1;\n  \n  fprintf('\\nTrying, Kd=%d, K1=%d, K2=%d, K3=%d\\n', Kd, K1, K2, K3 );\n  \n  %%%%%%%%%%%%%%%%%%%%%% Get the sets of rotations %%%%%%%%%%%%%%%%%%%%%%%%\n  G = reshape( gj3, Kd, [] );\n  M = MTilde*G; M = M/max(abs(M(:)))*K3; % Just for numerical stability\n  R = zeros( 2*nFrame, 3*K3 ); l = zeros( K, nFrame ); thres = 0.001;\n  rotIsBad = zeros( K3, nFrame );\n  for i = 1 : nFrame\n    for k = 1 : K3\n      tmp = M(2*i-1:2*i,3*k-2:3*k);\n      l(k,i) = norm(tmp);\n      \n      if abs( l(k,i) )>thres; R(2*i-1:2*i,3*k-2:3*k) = tmp/l(k,i);\n      else rotIsBad(k,i)=1;\n      end\n    end\n  end\n  \n  % Rectify R (not really mentioned by Xiao)\n  for k=2:K3\n    for i = 2:nFrame\n      goodFrame = find( sum( rotIsBad([1 k], 1:i), 1 )==0);\n      goodFrame = sort( [ 2*goodFrame 2*goodFrame-1 ] );\n      if length(goodFrame)<4; continue; end\n      R1 = R( goodFrame, 1:3 );\n      R2 = R( goodFrame, 3*k-2:3*k );\n      R3 = R2; R3(end-1:end,:) = -R3(end-1:end,:);\n      \n      if norm( R2*(R2\\R1)-R1, 'fro' )>norm( R3*(R3\\R1)-R1, 'fro' )\n        R( goodFrame(end-1:end), 3*k-2:3*k ) = ...\n          -R( goodFrame(end-1:end), 3*k-2:3*k );\n      end\n    end\n    \n    goodFrame = find( sum( rotIsBad([1 k], 1:nFrame), 1 )==0);\n    goodFrame = sort( [ 2*goodFrame 2*goodFrame-1 ] );\n    R1 = R( goodFrame, 1:3 );\n    R2 = R( goodFrame, 3*k-2:3*k );\n    tmp=R2\\R1;\n    \n    R( :, 3*k-2:3*k ) = R( :, 3*k-2:3*k )*tmp;\n    M( :, 3*k-2:3*k ) = M( :, 3*k-2:3*k )*tmp;\n  end\n  \n  % Get all the rotations and coefficients in K3 (if non-degenerate)\n  RTot = zeros(3,3,nFrame);\n  for i = 1 : nFrame\n    % Get the average rotation matrix\n    tmp=find(~rotIsBad(:,i)');\n    if isempty(tmp); continue; end\n    RTmp=zeros(3,3,length(tmp));\n    \n    qTot=cell(1,2);\n    for k=1:2\n      kk=1;\n      for j=tmp\n        RTmp(:,:,kk)=rotationMatrix( R(2*i-1:2*i,3*j-2:3*j)*(2*k-3) );\n        kk=kk+1;\n      end\n      \n      q=quaternion(RTmp);\n      for j=2:size(q,2)\n        if norm(-q(:,j)-q(:,1))<norm(q(:,j)-q(:,1)); q(:,j)=-q(:,j); end\n      end\n      qTot{k}=mean(q,2);\n    end\n    \n    q=qTot{1};\n    if i>=2\n      q0 = quaternion( RTot(:,:,i-1) );\n      if min( norm(qTot{2}-q0), norm(-qTot{2}-q0) )<...\n          min( norm(qTot{1}-q0), norm(-qTot{1}-q0) )\n        q=qTot{2};\n      end\n    end\n    \n    RTot(:,:,i) = quaternion(q);\n    \n    % Recover the coefficients\n    l(1:K3,i)=(reshape(RTot(1:2,:,i),[],1)\\reshape(M(2*i-1:2*i,1:3*K3),6,K3))';\n    \n    % Compute MTilde\n    MTilde(2*i-1:2*i,1:3*K3)=kron(l(1:K3,i)',RTot(1:2,:,i));\n  end\n  for k = 1 : K3\n    gj3(:,:,k) = 0; gj3(3*k-2:3*k,:,k) = eye(3);\n  end\n  R = RTot;\n  rotIsUnknown = sum(abs(l(1:K3,:))<thres,1)==K3;\n  if sum(~rotIsUnknown)==0\n    [disc indMax]=max(sum(l(1:K3,:).^2,1)); rotIsUnknown(indMax)=1;\n  end\n  goodFrame = find( ~rotIsUnknown );\n  tmp=sort([2*goodFrame,2*goodFrame-1]);\n  \n  % Get the MTilde where l(1:K3,i) is close to 0\n  M=MTilde(tmp,:); B=M\\W(tmp,:); M2=W/B;\n  for i=find(rotIsUnknown)\n    MTilde(2*i-1:2*i,:)=M2(2*i-1:2*i,:);\n  end\n  \n  %   find(rotIsUnknown)\n  %   plot(l')\n  %     B=MTilde\\W;\n  %   norm(MTilde*B-W,'fro')\n  %   pause\n  \n  % The first 3*K3 columns of MTilde and MHat are now identical\n  % We now need to deal with the last columns\n  \n  %%%%%%%%%%%%%%%%%%%%%% Find gj and rj %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % We here perform a full optimization and not the hacky alternate\n  % optimization from the paper\n  MNull = zeros( 2*K3, Kd );\n  for i = 1 : K3\n    MNull(2*i-1:2*i,:) = MTilde( 2*indW(i)-1:2*indW(i), : );\n  end\n  [ U S V ] = svd( MNull, 'econ' );\n  [ V disc ] =rq(V);\n  gj2 = reshape( V(:,end-(2*K2+K1)+1:end-K1), [], 2, K2);rj2=zeros(3,2,K2);\n  gj1 = V(:,end-K1+1:end); rj1=zeros(3,K1);\n  \n  % Perform iterations for K2 bases\n  opt = optimset( 'Display', 'on', 'GradObj', 'off', 'Hessian', 'off',...\n    'LargeScale', 'off' );\n  for j=1:K2\n    % Get the best rj2\n    ATmp=zeros(4*length(goodFrame),3);\n    for kk=1:2\n      n = 1;\n      for m=goodFrame\n        for k=1:2\n          ATmp(n,:)=gj2(:,k,j)'*MTilde(2*m-1,:)'*R(2,:,m) - ...\n            gj2(:,k,j)'*MTilde(2*m,:)'*R(1,:,m);\n          n = n + 1;\n        end\n      end\n      \n      % Force the rj2 to be independent\n      zeroStart=2+kk;\n      [ U S V ] = svd( ATmp(:,1:zeroStart-1), 'econ' );\n      rj2(1:zeroStart-1,kk,j) = V(:,end)/V(end,end);\n      rj2(zeroStart:end,kk,j) = 0;\n    end\n    \n    % Perform the full optimization\n    onePos=3*K3+1+2*(j-1);\n    x=[gj2(1:onePos-1,1,j); gj2(1:onePos,2,j); rj2(1:2,1,j); rj2(1:2,2,j)];\n    MTildeTmp= MTilde(:,1:onePos+1); MNullTmp=MNull(:,1:onePos+1);\n    x = fminunc( @(X)( optimizeGj2( X,goodFrame, MTildeTmp, ...\n      R, MNullTmp ) ), x,opt);\n    \n    % Save the best results\n    rj2(:,:,j)=[x(end-3:end-2) x(end-1:end); 0 1 ];\n    gj2(:,:,j)=0;\n    gj2(1:onePos,1,j) = [ x(1:onePos-1); 1 ];\n    gj2(1:onePos+1,2,j) = [ x(1:onePos); 1 ];\n  end\n  \n  % Perform iterations for K1 bases\n  for j=1:K1\n    % Get the best rj1\n    ATmp=zeros(length(goodFrame),3);\n    for m=goodFrame\n      ATmp(m,:) = gj1(:,j)'*( MTilde( 2*m-1 , : )'*R(2,:,m) - ...\n        MTilde( 2*m , : )'*R(1,:,m) );\n    end\n    \n    [ U S V ] = svd( ATmp, 'econ' );\n    rj1(:,j) = V(:,end);\n    \n    % Perform the full optimization\n    onePos=3*K3+2*K2+j;\n    x=[gj1(1:onePos-1,j); rj1(:,j) ];\n    MTildeTmp= MTilde(:,1:onePos); MNullTmp=MNull(:,1:onePos);\n    x = fminunc( @(X)( optimizeGj1( X,goodFrame, MTildeTmp, ...\n      R, MNullTmp ) ), x,opt);\n    \n    % Save the best results\n    rj1(:,j)=x(end-2:end);\n    gj1(:,j)=0; gj1(1:onePos,j) = [ x(1:onePos-1); 1 ];\n  end\n  \n  % % quality\n  % err=zeros(1,length(goodFrame));\n  % for j = 1:K2\n  %   for m=goodFrame\n  %     err(m)=err(m)+abs(gj2(:,1,j)'*( MTilde( 2*m-1 , : )'*R(2,:,m) - ...\n  %       MTilde( 2*m , : )'*R(1,:,m) )*rj2(:,1,j)) ...\n  %        + abs(gj2(:,2,j)'*( MTilde( 2*m-1 , : )'*R(2,:,m) - ...\n  %       MTilde( 2*m , : )'*R(1,:,m) )*rj2(:,2,j));\n  %   end\n  % end\n  %       norm(err)\n  % %       norm(MNull*gj1(:,j))\n  %       plot(err)\n  %\n  % pause\n  \n  %%%%%%%%%%%%%%%%%%%%%% Recover the coefficients for K2 K1 %%%%%%%%%%%%%%%\n  % Rectify the right columns of MTilde\n  for m=1:nFrame\n    for i = 1 : K2\n      MTilde(2*m-1:2*m,3*K3+2*i-1:3*K3+2*i)=MTilde(2*m-1:2*m,:)*gj2(:,:,i);\n    end\n    for i = 1 : K1\n      MTilde(2*m-1:2*m,3*K3+2*K2+i)=MTilde(2*m-1:2*m,:)*gj1(:,i);\n    end\n  end\n  %   l(K3+i,m)*R(1:2,:,m)*rj2(:,:,i)=\n  %                   MTilde(2*m-1:2*m,3*K3+2*i-1:3*K3+2*i)*RAmbiguityi\n  %   l(K3+i,m)*R(1:2,:,m)*rj1(:,i)=\n  %                   MTilde(2*m-1:2*m,3*K3+2*K2+i)\n  for m=goodFrame\n    for i = 1 : K2\n      tmp1=R(1:2,:,m)*rj2(:,:,i); tmp1=tmp1*tmp1';\n      tmp2=MTilde(2*m-1:2*m,3*K3+2*i-1:3*K3+2*i); tmp2=tmp2*tmp2';\n      l(K3+i,m) = sqrt( tmp1(:)\\tmp2(:) );\n    end\n    for i = 1 : K1\n      tmp1=R(1:2,:,m)*rj1(:,i);\n      tmp2=MTilde(2*m-1:2*m,3*K3+2*K2+i);\n      l(K3+K2+i,m) = tmp1\\tmp2;\n    end\n  end\n  \n  %   B=MTilde\\W;\n  %   norm(MTilde*B-W,'fro')\n  %   plot(l')\n  %   pause\n  \n  \n  % Change the signs of the coefficients\n  for i = 1 : K2\n    A=zeros(2*nFrame,2);\n    A(1:2,:)=l(K3+i,goodFrame(1))*R(1:2,:,goodFrame(1))*rj2(:,:,i);\n    \n    for j=2:length(goodFrame)\n      m=goodFrame(j); A(2*j-1:2*j,:)=l(K3+i,m)*R(1:2,:,m)*rj2(:,:,i);\n      tmp=goodFrame(1:j); tmp=sort( [ 2*tmp-1, 2*tmp ] );\n      MTildeLoc=MTilde(tmp,3*K3+2*i-1:3*K3+2*i);\n      \n      RAmb1=MTildeLoc\\A(1:2*j,:);\n      err1=norm(MTildeLoc*RAmb1-A(1:2*j,:),'fro');\n      \n      A(2*j-1:2*j,:)=-A(2*j-1:2*j,:);\n      RAmb2=MTildeLoc\\A(1:2*j,:);\n      err2=norm(MTildeLoc*RAmb2-A(1:2*j,:),'fro');\n      \n      if err2<err1; l(K3+i,m)=-l(K3+i,m);\n      else A(2*j-1:2*j,:)=-A(2*j-1:2*j,:);\n      end\n    end\n  end\n  \n  B=MTilde\\W;\n  %   norm(MTilde*B-W,'fro')\n  %   plot(l')\n  %   pause\n  \n  %%%%%%%%%%%%%%%%%%%%%% Recover the shape basis %%%%%%%%%%%%%%%%%%%%%%%%%%\n  M=zeros(2*length(goodFrame),3*K);\n  for i=1:length(goodFrame)\n    M(2*i-1:2*i,:)=kron(l(:,goodFrame(i))',R(1:2,:,goodFrame(i)));\n  end\n  \n  tmp=sort([2*goodFrame,2*goodFrame-1]);\n  B=M\\W(tmp,:);\n  %   norm(M*B-W(tmp,:),'fro')\n  %   tmp=sum((M*B-W(tmp,:)).^2,2);\n  %   plot( tmp(1:2:end)+tmp(2:2:end) )\n  %   'coiin'\n  %   pause\n  \n  % Recover the full basis\n  SBasis = zeros( 3, nPoint, K );\n  for i = 1 : K; SBasis(:,:,i) = B(3*i-2:3*i,:); end\n  \n  %%%%%%%%%%%%%%%%%%%%%% Recover the missing coefficients %%%%%%%%%%%%%%%%%\n  opt = optimset( 'Display', 'off', 'GradObj', 'off', 'Hessian', 'off',...\n    'LargeScale', 'off' );\n  \n  while 1\n    for m=1:nFrame\n      if rotIsUnknown(m)\n        if m==1 || rotIsUnknown(m-1)\n          if m==nFrame; continue\n          else if ~rotIsUnknown(m+1); iIni=m+1; else continue; end\n          end\n        else iIni=m-1;\n        end\n        \n        % Optimize over the shape coefficients/rotation\n        coeff=[ l(:,iIni); quaternion( R(:,:,iIni) ) ];\n        Wm=W(2*m-1:2*m,:);\n        \n        [ c res ] = fminunc( @(X)( optimRl( X, K,B,Wm ) ), coeff, opt );\n        \n        l(:,m)=c(1:K); R(:,:,m)=quaternion(c(K+1:end));\n        rotIsUnknown(m)=0;\n      else\n        if m>=2\n          %           plot(quaternion(R)')\n          %           pause\n          q0 = quaternion( R(:,:,m-1) );\n          q1 = quaternion( R(:,:,m) );\n          q2 = quaternion( rotationMatrix( -R(1:2,:,m) ) );\n          if min( norm(q2-q0), norm(-q2-q0) )<min(norm(q1-q0),norm(-q1-q0))\n            l(:,m)=-l(:,m); R(:,:,m)=rotationMatrix(-R(1:2,:,m));\n          end\n        end\n      end\n    end\n    if ~rotIsUnknown(1); break; end\n  end\n  \n  %%%%%%%%%%%%%%%%%%%%%% Finalize the anim object %%%%%%%%%%%%%%%%%%%%%%%%%\n  anim=Animation('SBasis', SBasis, 'l', l, 'R', R, 'isProj', false, ...\n    't', animBest.t, 'W', animBest.W );\n  err = anim.computeError(); err=err(1);\n  fprintf( 'Reprojection error: %f \\n', err );\n  \n  if err<errBest; errBest=err; animBest=anim; end\nend\nanim=animBest;\n\nfprintf( 'Best reprojection error: %f \\n', errBest );\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction res = optimRl(X,K,B,Wm)\nlm=X(1:K);\nRm=quaternion(X(K+1:end)/norm(X(K+1:end)));\nres = norm(kron(lm',Rm(1:2,:))*B-Wm,'fro')^2;\nend\n\nfunction val = optimizeGj2( x, goodFrame, MTilde, R, MNull )\n% gjk' MTilde_{2m-1}' R_m2 rjkk - gjk' MTilde_2m' R_m1 rjkk = 0,\n% k and kk in {1 2}\n% rj can be multiplied by any 2x2\nrj2=[x(end-3:end-2) x(end-1:end); 0 1 ]; rj2(:,1)=rj2(:,1)/norm(rj2(:,1));\nn=(length(x)-4-1)/2;\ngj2=[ [ x(1:n); 1; 0 ] [ x(n+1:2*n+1); 1 ] ];\nn=n+2;\n\nn=1;\nval=zeros(1,length(goodFrame));\nA=gj2'*MTilde';\nfor m=goodFrame\n  val(n)=norm( ( A(:,2*m-1,:)*R(2,:,m) - A(:,2*m)*R(1,:,m) )*rj2, 'fro' );\n  n=n+1;\nend\nval=norm([ val reshape(MNull*gj2,[],1)' ]);\nend\n\nfunction val = optimizeGj1( x, goodFrame, MTilde, R, MNull )\n% gj' ( MTilde_{2m-1} R_m2 - MTilde_2m R_m1 ) rj = 0\ngj1=[ x(1:end-3); 1 ];\nrj1=x(end-2:end); rj1=rj1/norm(rj1);\n\nn=1;\nA=gj1'*MTilde';\nB=zeros(length(goodFrame),3);\nfor m=goodFrame\n  B(n,:)=A(:,2*m-1)*R(2,:,m) - A(:,2*m)*R(1,:,m);\n  n=n+1;\nend\nval=norm([ (B*rj1); reshape(MNull*gj1,[],1) ]);\n\nend\n", "meta": {"author": "vrabaud", "repo": "sfm_toolbox", "sha": "7ce933b31b71292eddabb40bacfd619720fa221d", "save_path": "github-repos/MATLAB/vrabaud-sfm_toolbox", "path": "github-repos/MATLAB/vrabaud-sfm_toolbox/sfm_toolbox-7ce933b31b71292eddabb40bacfd619720fa221d/nrsfm/private/nrsfmXiaoKanade.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5906704553553231}}
{"text": "%% Experiment with the cnn_mnist_fc_bnorm\n\n[net_bn, info_bn] = cnn_mnist(...\n  'expDir', 'data/mnist-bnorm', 'useBnorm', true);\n\n[net_fc, info_fc] = cnn_mnist(...\n  'expDir', 'data/mnist-baseline', 'useBnorm', false);\n\nfigure(1) ; clf ;\nsubplot(1,2,1) ;\nsemilogy(info_fc.val.objective', 'o-') ; hold all ;\nsemilogy(info_bn.val.objective', '+--') ;\nxlabel('Training samples [x 10^3]'); ylabel('energy') ;\ngrid on ;\nh=legend('BSLN', 'BNORM') ;\nset(h,'color','none');\ntitle('objective') ;\nsubplot(1,2,2) ;\nplot(info_fc.val.error', 'o-') ; hold all ;\nplot(info_bn.val.error', '+--') ;\nh=legend('BSLN-val','BSLN-val-5','BNORM-val','BNORM-val-5') ;\ngrid on ;\nxlabel('Training samples [x 10^3]'); ylabel('error') ;\nset(h,'color','none') ;\ntitle('error') ;\ndrawnow ;", "meta": {"author": "willard-yuan", "repo": "cnn-for-image-retrieval", "sha": "2e3e8ab76e2c971314be55b5ae44e02884003261", "save_path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval/cnn-for-image-retrieval-2e3e8ab76e2c971314be55b5ae44e02884003261/matconvnet-1.0-beta18/examples/mnist/cnn_mnist_experiments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5906704528067145}}
{"text": "function W=RegCsp(EEGdata,gnd,genSs,genMs,beta,gamma)\n% RCSP: Regularized Common Spatial Pattern\n%\n% %[Prototype]%\n% function W=RegCsp(EEGdata,gnd,genSs,genMs,beta,gamma)\n%\n% %[Author Notes]%\n% Author: Haiping LU\n% Email : hplu@ieee.org   or   eehplu@gmail.com\n% Release date: March 20, 2012 (Version 1.0)\n% Please email me if you have any problem, question or suggestion\n%\n% %[Algorithm]%:\n% This function implements the Regularized Common Spatial Pattern\n% (R-CSP) algorithm presented in the follwing paper:\n%    Haiping Lu, How-Lung Eng, Cuntai Guan, K.N. Plataniotis, and A.N. Venetsanopoulos,\n%    \"Regularized Common Spatial Pattern With Aggregation for EEG Classification in Small-Sample Setting\",\n%    IEEE Trans. on Biomedical Engineering, Vol. 57, No. 12, Pages\n%    2936-2946, Dec. 2010.\n% Please reference this paper when reporting work done using this code.\n%\n% The following is an earlier conference version\n%    Haiping Lu, K.N. Plataniotis, and A.N. Venetsanopoulos,\n%    \"Regularized Common Spatial Patterns with Generic Learning for EEG Signal Classification\",\n%    in Proceedings of the 31st Annual International Conference of the \n%    IEEE Engineering in Medicine and Biology Society (EMBC), Sep., 2009.\n%\n% %[Syntax]%: W=RegCsp(EEGdata,gnd,genSs,genMs,beta,gamma)\n%\n% %[Inputs]%:\n%    EEGdata: the input EEG data for training, a 3D array with size [numT,numCh,nTrl]\n%       numT is the number of samples in each channle (T in the paper)\n%       numCh is the number of channels (N in the paper)\n%       nTrl is the number of trails for training (2*M in the paper)\n%\n%    gnd: the ground truth class labels for the nTrl trials, size nTrl x 1\n%\n%    genSs: size numCh x numCh x 2, the sum of generic covariance matrices \n%       from generic training trials for two classes, equation (6) in the paper\n%\n%    genMs: size 2 x 1, the number of generic training trials for two classes\n%   \n%    beta,gamma: the reguarlizatio parameters in the paper, setting both to\n%       zero gives the conventional CSP\n%\n% %[Outputs]%:\n%    W: \\hat{W} in the paper, the projection matrix, we often use only the \n%         first 6 columns from W\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %[Notes]%:\n% A. Developed using Matlab R2006a\n% B. Revision history:\n%       Version 1.0 released on March 20, 2012\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%\n[numT,numCh,nTrl] = size(EEGdata);%Input data, see documentation\nNs=zeros(2,1);\nSigma2=cell(2,1);%Two average spatial covariance matrices, one for each class\n%%%%%%%%%%%%%%%%%%%\nfor i=1:2%for each class\n    Idxs=find(gnd==i);\n    EEG=EEGdata(:,:,Idxs);\n    Ns(i)=length(Idxs);\n    C=zeros(numCh,numCh,Ns(i));%Sample covariance matrix, equation (1) in the paper\n    for trial=1:Ns(i)\n        E=EEG(:,:,trial)'; \n        tmpC = (E*E');        \n        C(:,:,trial) = tmpC./trace(tmpC);%normalization\n    end \n    Csum=sum(C,3);\n    %Reguarlization, see equations (3) and (4) in the paper\n    Sigma1=((1-beta)*Csum+beta*genSs(:,:,i))/((1-beta)*Ns(i)+beta*genMs(i));\n    Sigma2{i}=(1-gamma)*Sigma1+gamma*trace(Sigma1)*eye(numCh)/numCh;\nend\n\n%Equation (7) in the paper\nSigmaComps=Sigma2{1}+Sigma2{2}; \n[Ucomps,lmds] = eig(SigmaComps);\n[lmds,Idxs] = sort(diag(lmds),'descend');\nUcomps = Ucomps(:,Idxs);\n\n%Note equations (8) to (12) in the conference version is now condensed in\n%one equation (8) in the journal version\n%Equation (8) in the CONFERENCE paper\nP=sqrt(inv(diag(lmds)))*Ucomps';\n\n%Equation (9) in CONFERENCE the paper\nSgm1=P*Sigma2{1}*P';\n\n%Equation (11) in the CONFERENCE paper\n[B,D] = eig(Sgm1);\n[D,Idxs] = sort(diag(D),'descend'); \nB = B(:,Idxs);\n\n%Equation (12) in the CONFERENCE paper\n%Equation (8) in the JOURNAL paper\nW=(B'*P); \n%Normalize the projrection matrix\nfor i=1:length(Idxs), W(i,:)=W(i,:)./norm(W(i,:)); end\n\n%Sort columns, take first and last columns first, etc\nW0=W;\nW=zeros(size(W));\ni=0;\nfor d=1:numCh\n    if (mod(d,2)==0)\n        W(d,:)=W0(numCh-i,:);\n        i=i+1;\n    else\n        W(d,:)=W0(1+i,:);\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/35734-regularized-common-spatial-pattern-with-aggregation-r-csp-a-for-eeg-classi%EF%AC%81cation/RCSPCodes/RegCsp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5906704439400638}}
{"text": "function [A,B,C,D] = vibsHmxBlockOperator(omega,U,sigma,u,cL,cT,rhoS,c0,rho0,f,tol)\n%+========================================================================+\n%|                                                                        |\n%|                 OPENVIBS - LIBRARY FOR VIBRO-ACOUSTIC                  |\n%|           openVibs is part of the GYPSILAB toolbox for Matlab          |\n%|                                                                        |\n%| COPYRIGHT : Matthieu Aussal, Marc Bakry (c) 2017-2019.                 |\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%|             marc.bakry@polytechnique.edu                               |\n%| WEBSITE   : www.cmap.polytechnique.fr/~aussal/gypsilab    \u00a0\u00a0\u00a0\u00a0         |\n%|                                                                        |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it.                                                      |\n%|________________________________________________________________________|\n%|   '&`   |                                                              |\n%|    #    |   FILE       : vibsHmxBlockOperator.m                        |\n%|    #    |   VERSION    : 0.55                                          |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal & Marc Bakry                  |\n%|  ( # )  |   CREATION   : 14.03.2019                                    |\n%|  / 0 \\  |   LAST MODIF :                                               |\n%| ( === ) |   SYNOPSIS   :                                               |\n%|  `---'  |                                                              |\n%+========================================================================+\n\n% Constants\nmu     = rhoS*cT^2;\nlambda = rhoS*(cL^2 - 2*cT^2);\nw      = 2*pi*f;\nk      = w/c0;  \n\n% Dimension \nn = size(omega.msh.elt,2)-1;\n\n% Green kernel function\nif (n == 2)\n    Gxy         = @(X,Y) femGreenKernel(X,Y,'[H0(kr)]',k);\n    gradyGxy{1} = @(X,Y) femGreenKernel(X,Y,'grady[H0(kr)]1',k);\n    gradyGxy{2} = @(X,Y) femGreenKernel(X,Y,'grady[H0(kr)]2',k);\n    gradyGxy{3} = @(X,Y) femGreenKernel(X,Y,'grady[H0(kr)]3',k);\n    G0          = '[log(r)]';\n    gradyG0     = 'grady[log(r)]';    \n    cteGxy      = 1i/4;\n    cteG0       = -1/(2*pi);\n    \nelseif (n == 3)\n    Gxy         = @(X,Y) femGreenKernel(X,Y,'[exp(ikr)/r]',k);\n    gradyGxy{1} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]1',k);\n    gradyGxy{2} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]2',k);\n    gradyGxy{3} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]3',k);\n    G0          = '[1/r]';\n    gradyG0     = 'grady[1/r]';    \n    cteGxy      =  1/(4*pi);\n    cteG0       =  1/(4*pi);\n    \nelse\n    error('vibsNeumannBW.m : unavailable case.')\nend\n    \n% Coupling coeff for Brackage-Werner simulation\nbeta = 1i*k;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%% ELASTO-ELASTO (A11) %%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Initialization\nA = cell(n,n);\n\n% Static part\nGG = integral(omega,grad(U),grad(U));\nfor i = 1:n\n    for j = 1:n        \n        % Operator div(U):div(U)\n        DD = integral(omega,grad(U,i),grad(U,j));\n        \n        % Operator e(U):e(U)\n        EE = integral(omega,grad(U,j),grad(U,i));\n        if (i==j)\n            EE = EE + GG;\n        end\n        \n        % Summation\n        A{i,j} = lambda.*DD + mu.*EE;\n    end\nend\n\n% Dynamic part\nif (f ~= 0)\n    Id = integral(omega,U,U);\n    for i = 1:n\n       A{i,i} = A{i,i} - (rhoS*w^2) .* Id; \n    end\nend\n\n% Final form (sparse)\nA = cell2mat(A);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%% ELASTO-ACOUSTIC (A12) %%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Gaussian quadrature\n[Xqud,Wx] = sigma.qud;\nWx        = spdiags(Wx,0,length(Wx),length(Wx));\n\n% Collocation mass operator\nId = u.uqm(sigma);\n\n% Collocation boundary operator\nS = cteGxy .* integral(Xqud,sigma,Gxy,u,tol) + ...\n    cteG0  .* regularize(Xqud,sigma,G0,u);\n\n% Collocation boundary operator\nD = cteGxy .* integral(Xqud,sigma,gradyGxy,ntimes(u),tol) + ...\n    cteG0  .* regularize(Xqud,sigma,gradyG0,ntimes(u));\n\n% Final operator Brackage-Werner : [1i*k*beta*S - (Id/2 + D)]\nB.Mr = beta.*S - (0.5*Id + D);\n\n% Normal trace of the volumn element matrix\nnU   = ntimes(U);\nnPHI = nU.uqm(sigma);\n\n% Coupling to FEM\nB.Ml = cell(n,1);\nfor i = 1:n\n    B.Ml{i} = (nPHI{i}' * Wx);\nend\nB.Ml = cell2mat(B.Ml);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%% ELASTO-ACOUSTIC (A21) %%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Initialization\nC = cell(1,n);\n\n% Coupling FEM \nfor i = 1:n\n    C{i} = (rho0*w^2) .* integral(sigma,u,ntimes(U,i));\nend\n\n% Final format (sparse)\nC = cell2mat(C);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%% ACOUSTIC-ACOUSTIC (A22) %%%%%%%%%%%%%%%%%%%%%%%%\n\n% Finite element mass matrix\nId = integral(sigma,u,u);\n\n% Finite element boundary operator\nH  = cteGxy .* (k^2 * integral(sigma,sigma,ntimes(u),Gxy,ntimes(u),tol) ...\n    - integral(sigma,sigma,nxgrad(u),Gxy,nxgrad(u),tol));\nHr = cteG0  .* (k^2 * regularize(sigma,sigma,ntimes(u),G0,ntimes(u)) ...\n    - regularize(sigma,sigma,nxgrad(u),G0,nxgrad(u)));\n\n% Finite element boundary operator\nD  = cteGxy .* integral(sigma,sigma,u,gradyGxy,ntimes(u),tol);\nDr = cteG0  .* regularize(sigma,sigma,u,gradyG0,ntimes(u));\n\n% Final operator Brackage-Werner : - [1i*k*beta*(-Id/2 + Dt) - H]\nD = - (beta.*(-0.5*Id + (D+Dr).') - (H+Hr));\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/nonRegressionTest/vibroAcoustic/vibsHmxBlockOperator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5906631100542519}}
{"text": "function [tq,q,tu,u,t,p,Q,code]=hydrograph(uhname,rdname,method,...\n                                           K,D,R,Iar,A,CN,Tc,units)\n% SCS Unit Hydrograph Convolution (R11)\n%\n% [tq,q,tu,u,t,p,Q,code]=hydrograph(uhname,rdname,method,...\n%                                   K,D,R,Iar,A,CN,Tc,units)\n%\n% Input\n%   uhname  dimensionless unit hydrograph filename\n%   rdname  dimensionless rainfall distribution filename\n%   method  interpolation method\n%   K       peak factor\n%   D       storm duration (hr)\n%   R       rainfall depth (mm | in)\n%   Iar     initial abstraction ratio\n%   A       basin area (km^2 | ac)\n%   CN      curve number\n%   Tc      time of concentration (min)\n%   units   units code\n%             0 = imperial\n%             1 = metric\n%          \n% Output   \n%   tq      runoff hydrograph time (hr)\n%   q       runoff hydrograph flow rate (cms | cfs)\n%   tu      unit hydrograph time (hr)\n%   u       unit hydrograph flow rate (cms | cfs)\n%   t       rainfall-runoff time (hr)\n%   p       cumulative rainfall (mm | in)\n%   Q       cumulative runoff (mm | in)\n%   code    return code\n%             0 = fail\n%             1 = pass\n%\n% Example:\n%\n%  uhname='library\\gamma.duh'; rdname='library\\scsii-024.drd'; K=484;\n%  method='linear'; D=24; R=200; Iar=0.2; A=3; CN=75; Tc=90; units=1;\n%  [tq,q,tu,u,t,p,Q,code]=hydrograph(uhname,rdname,method,...\n%                                    K,D,R,Iar,A,CN,Tc,units)\n%\n% See also help\\hydographui.html.\n\n% Version 2.03 Copyright(c)2008\n% Tom Davis (tdavis@metzgerwillard.com)\n%\n% Last revision: 03/16/2008\n\nif units\n  R=R/25.4;                             % rainfall depth (in)\n  cm2cf=35.3146667214886;               % cubic meters to cubic feet\n  %    =1e6/(12^3*2.54^3);\n  sk2ac=247.105381467165;               % square kilometers to acres\n  %    =1e10/(43560*12^2*2.54^2);\n  A=A*sk2ac;                            % basin area (ac)\nend\nA =A/640;                               % basin area (mi^2)\nTc=Tc/60;                               % time of concentration (hr)\nd =Tc/7.5;                              % rain burst duration (hr)\nTp=5*d;                                 % time to peak (hr)\nmethod1=lower(method);\nmethod2=method1;\nuhname=lower(uhname);\ncode=1;\n\nif ~isempty(findstr('triangle',uhname))\n  uhname='triangle';\nelseif ~isempty(findstr('gamma',uhname))\n  uhname='gamma';\nend\n\nswitch uhname                           % dimensionless unit hydrograph\n  case 'triangle'\n    Tb=3872/(3*K);                      % time base\n    % =2(5280^2/60^2/12)/K\n    uh=[0,0;1,1;Tb,0];                  % triangular distribution\n    method1='linear';\n  case 'gamma'\n    f =K*3/1936;\n    % =K/(5280^2/60^2/12)\n    a0=0.045+0.5*f+5.6*f^2+0.3*f^3;     % cubic estimate\n    options=optimset('display','off','tolx',eps);\n    g =inline('gamma(a)*exp(a)/a^a-1/f','a','f');\n    a =fzero(g,a0,options,f);\n    tu=(0:0.2:round(2500/K))';\n    u =(tu.*exp(1-tu)).^a;              % gamma distribution\n    u(end)=0;                           % force zero ordinate\n  otherwise\n    uh=load(uhname);                    % tabular distribution\n    [m,n]=size(uh);\n    [umax,ndx]=max(uh(:,2));            %#ok umax not used\n    umin=min(min(uh));\n    if m<3 | n~=2 | umin<0 | uh(1,:)~=[0 0] | uh(ndx,:)~=[1 1] %#ok (R11)\n      msgbox('Unit Hydrograph is improperly formed.',...\n        'File Error','error','modal');\n      tq=[];q=[];tu=[];u=[];t=[];p=[];Q=[];code=0;\n      return\n    end\nend\n\nif ~strcmp(uhname,'gamma')\n  uh=[uh;uh(end,1)+0.2,0];              % force zero ordinate\n  Tu=uh(:,1);\n  U =uh(:,2);\n  % resample unit hydrograph\n  tu=(0:0.2:Tu(end))';\n  u =interp1(Tu,U,tu,method1);\nend\n\ntu=Tp*tu;                               % unit hydrograph time (hr)\nu =K*A*u/Tp;                            % unit hydrograph flow rate (cfs)\nu(u<0)=0;\n\nrd=load(rdname);                        % dimensionless rainfall distribution\n[m,n]=size(rd);\nrmax=max(max(rd));\nrmin=min(min(rd));\nif m<2 | n~=2 | rmin<0 | rmax>1 | rd(1,:)~=[0 0] | rd(end,:)~=[1 1] %#ok (R11)\n  msgbox('Rainfall Distribution is improperly formed.',...\n    'File Error','error','modal');\n  tq=[];q=[];tu=[];u=[];t=[];p=[];Q=[];code=0;\n  return\nend\n\nT =D*rd(:,1);\nP =R*rd(:,2);\n% resample rainfall distribution\nt =(0:d:T(end))';                       % rainfall time (hr)\np =interp1(T,P,t,method2);              % rainfall depth (in)\n\nQ =zeros(size(t));\ns =1000/CN-10;                          % retention (in)\ni =find(p>Iar*s);\nQ(i)=(p(i)-Iar*s).^2./(p(i)+(1-Iar)*s); % runoff depth (in)\ndQ=[diff(Q);0];                         % incremental runoff depth (in)\nq =conv(dQ,u);                          % runoff flow rate (cfs)\nq(q<0)=0;\ntq=(0:d:t(end)+tu(end))';               % runoff time (hr)\n\nif units\n  u=u/cm2cf; q=q/cm2cf;                 % cms\n  p=p*25.4; Q=Q*25.4;                   % mm\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/10420-scs-unit-hydrograph-convolution/hydrograph/hydrograph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5906631039793182}}
{"text": "function [V,D,bnd,j,work] = laneig(A,nin,k,sigma,options)\n\n%LANEIG  Compute a few eigenvalues and eigenvectors.\n%   LANEIG solves the eigenvalue problem A*v=lambda*v, when A is \n%   real and symmetric using the Lanczos algorithm with partial \n%   reorthogonalization (PRO). \n%\n%   [V,D] = LANEIG(A) \n%   [V,D] = LANEIG('Afun',N) \n%\n%   The first input argument is either a real symmetric matrix, or a \n%   string containing the name of an M-file which applies a linear \n%   operator to the columns of a given matrix.  In the latter case,\n%   the second input argument must be N, the order of the problem.\n%\n%   The full calling sequence is\n%\n%   [V,D,ERR] = LANEIG(A,K,SIGMA,OPTIONS)\n%   [V,D,ERR] = LANEIG('Afun',N,K,SIGMA,OPTIONS)\n%\n%   On exit ERR contains the computed error bounds.  K is the number of\n%   eigenvalues desired and SIGMA is numerical shift or a two letter string\n%   which specifies which part of the spectrum should be computed:\n%\n%   SIGMA            Specified eigenvalues\n%\n%   'AL'            Algebraically Largest \n%   'AS'            Algebraically Smallest\n%   'LM'            Largest Magnitude   (default)\n%   'SM'            Smallest Magnitude  (does not work when A is an m-file)\n%   'BE'            Both Ends.  Computes k/2 eigenvalues\n%                   from each end of the spectrum (one more\n%                   from the high end if k is odd.) \n%\n%   The OPTIONS structure specifies certain parameters in the algorithm.\n%\n%    Field name      Parameter                              Default\n%   \n%    OPTIONS.tol     Convergence tolerance                  16*eps\n%    OPTIONS.lanmax  Dimension of the Lanczos basis.\n%    OPTIONS.v0      Starting vector for the Lanczos        rand(n,1)-0.5\n%                    iteration.\n%    OPTIONS.delta   Level of orthogonality among the       sqrt(eps/K)\n%                    Lanczos vectors.\n%    OPTIONS.eta     Level of orthogonality after           10*eps^(3/4)\n%                    reorthogonalization. \n%    OPTIONS.cgs     reorthogonalization method used        0\n%                    '0' : iterated modified Gram-Schmidt \n%                    '1' : iterated classical Gram-Schmidt\n%    OPTIONS.elr     If equal to 1 then extended local      1\n%                    reorthogonalization is enforced. \n%\n%   See also LANPRO, EIGS, EIG.\n\n% References: \n% R.M. Larsen, Ph.D. Thesis, Aarhus University, 1998.\n%\n% B. N. Parlett, ``The Symmetric Eigenvalue Problem'', \n% Prentice-Hall, Englewood Cliffs, NJ, 1980.\n%\n% H. D. Simon, ``The Lanczos algorithm with partial reorthogonalization'',\n% Math. Comp. 42 (1984), no. 165, 115--142.\n\n% Rasmus Munk Larsen, DAIMI, 1998\n\n\n%%%%%%%%%%%%%%%%%%%%% Parse and check input arguments. %%%%%%%%%%%%%%%%%%%%%%\n\nif ~isstr(A)\n  if nargin<1\n    error('Not enough input arguments.');\n  end\n  [m n] = size(A);\n  Aisfunc = 0;\n  if m~=n | ~isequal(A,A') | ~isreal(A)\n    error('A must be real symmetric')\n  end  \n  if nargin < 4 | isempty(sigma)\n    options = [];\n  else  \n    options = sigma; \n  end\n  if nargin < 3 | isempty(k), sigma = 'LM'; else, sigma = k; end\n  if nargin < 2 | isempty(nin), k = min(n,5); else, k = nin; end\nelse\n  if nargin<2\n    error('Not enough input arguments.');\n  end\n  Aisfunc = 1;\n  n = nin;\n  if nargin < 5 | isempty(options)\n    options.tol = 16*eps;\n    options.lanmax = n;\n    options.v0 = rand(n,1)-0.5;\n  end\n  if nargin < 4 | isempty(sigma), sigma = 'LM'; end\n  if nargin < 3 | isempty(k), k = min(n,5);  end\nend\n\nif ~isnumeric(k) | real(abs(fix(k)))~=k | ~isnumeric(n) | real(abs(fix(n)))~=n\n  error('Input arguments N and K must be positive integers.')\nend\n\n% Quick return for n<2  or k<1\nif n < 1 | k<1\n  if nargout < 2\n    V = zeros(k,1);\n  else\n    V = eye(n,k);\n    D = zeros(k,k);\n    bnd =zeros(k,1);\n  end\n  return\nend\nif n == 1 \n  if ~Aisfunc\n    D = A;\n    V = 1;\n    bnd = 0;\n  else\n    D = feval(A,1);\n    V = 1;\n    dnb = 0;\n  end\n  if nargout<2\n    V=D;\n  end\n  return\nend\n\n% A is the matrix of all zeros (not detectable if A is a string)\nif ~Aisfunc \n  if nnz(A)==0\n    if nargout < 2\n      V = zeros(k,1);\n    else\n      V = eye(n,k);\n      D = zeros(k,k);\n      bnd =zeros(k,1);\n    end\n    return\n  end\nend\n\nlanmax = n;\ntol = 16*eps;\nr = rand(n,1)-0.5;\npart = sigma;\n% Parse options struct\nif ~isempty(options) & isstruct(options)\n  c = fieldnames(options);\n  for i=1:length(c)\n    if strmatch(c(i),'v0'), r = getfield(options,'v0'); r=r(:); end\n    if strmatch(c(i),'tol'), tol = getfield(options,'tol'); end\n    if strmatch(c(i),'lanmax'), lanmax = getfield(options,'lanmax'); end\n  end\nend\n\n% Protect against absurd arguments.\ntol = max(tol,eps);\nlanmax = min(lanmax,n);\nif size(r,1)~=n\n  error('v0 must be a vector of length n')\nend\n\nlanmax = min(lanmax,n);\nif k>lanmax\n  error('K must satisfy  K <= LANMAX <= N.');\nend\nksave = k;\n\nif strcmp(sigma,'SM') & ~isstr(A)\n  sigma = 0;\nend\n\n\n% Prepare for shift-and-invert if sigma is numeric.\nif  isnumeric(sigma)\n  part = 'LM';\n  if isstr(A) \n    error('Shift-and-invert works only when the matrix A is given explicitly.');\n  else\n    pmmd = symmmd(A);\n    A = A(pmmd,pmmd);\n    [S.L,S.U] = lu(A - sigma*speye(n));\n    condU = condest(S.U);\n    dsigma = n * full(max(max(abs(A)))) * eps;\n    if sigma < 0\n      sgnsig = -1;\n    else\n      sgnsig = 1;\n    end\n    sigitr = 1;\n    while condU > 1/eps & ((dsigma <= 1 & sigitr <= 10) | ~isfinite(condU))\n      disps1 = sprintf(['sigma = %10e is near an exact eigenvalue of A,\\n' ...\n\t\t\t'so we cannot use the LU factorization of (A-sigma*I): ' ...\n\t\t\t' condest(U) = %10e.\\n'],sigma,condU);\n      if abs(sigma) < 1\n\tsigma = sigma + sgnsig * dsigma;\n\tdisps2 = sprintf('We are trying sigma + %10e = %10e instead.\\n', ...\n\t\t\t sgnsig*dsigma,sigma);\n      else\n\tsigma = sigma * (1 + dsigma);\n\tdisps2 = sprintf('We are trying sigma * (1 + %10e) = %10e instead.\\n', ...\n\t\t\t dsigma,sigma);\n      end\n      %     if nargout < 3 & dispn ~= 0             \n      disp([disps1 disps2])\n      %     end   \n      [S.L,S.U] = lu(A - sigma*speye(n));\n      condU = condest(S.U);\n      dsigma = 10 * dsigma;\n      sigitr = sigitr + 1;\n    end\n  end\n  A = S;\nend\n\n\nneig = 0; nrestart=-1;\nif ~strcmp(part,'BE') \n  j = min(2*k+2,lanmax);\nelse\n  j = min(k+1,lanmax);\nend\n\n\n%%%%%%%%%%%%%%%%%%%%% Here begins the computation  %%%%%%%%%%%%%%%%%%%%%%\n\nV = []; T = []; anorm = []; work = zeros(1,2); rnorm=-1;\n\n\n\n\nwhile neig < k \n  %%%%%%%%%%%%%%%%%%%%% Compute Lanczos tridiagonalization %%%%%%%%%%%%%%%%%\n  j = min(lanmax,j+1-mod(j,2));\n  % \"Trick\" to avoid unwanted zero eigenvalues when laneig is used for\n  % SVD calculations. (Nothing to if lanmax is odd, though.)\n  \n  if  ~isstr(A)\n    [V,T,r,anorm,ierr,w] = lanpro(A,j,r,options,V,T,anorm);\n  else\n    [V,T,r,anorm,ierr,w] = lanpro(A,n,j,r,options,V,T,anorm);\n  end\n  work= work + w;\n\n  if ierr<0 % Invariant subspace of dimension -ierr found. \n    j = -ierr;\n  end\n\n  %%%%%%%%%%%%%%%%%% Compute eigenvalues and error bounds %%%%%%%%%%%%%%%%%%\n  % Analyze T\n  [D,top,bot,err] = tqlb([full(diag(T))],full([0;diag(T,1)]));\n  %  if err>0\n  %    printf(['TQLB failed. Eigenvalue no. %i did not converge in 30', ...\n  %\t  ' iterations'],err);\n  %  end\n  %  full(T)\n  %  [P,D] = eig(full(T));\n  %  D = diag(D);\n  %  bot = P(end,:)';\n  %  [P(1,:)' P(end,:)']\n  [D,I] = sort(D);\n  bot = bot(I);\n  \n  % Set simple error bounds\n  rnorm = norm(r);\n  bnd = rnorm*abs(bot);\n  \n  % Use Largest Ritz value to estimate ||A||_2. This might save some\n  % reorth. in case of restart.\n  anorm = max(abs(D));\n  \n  % Estimate gap structure and refine error bounds\n  bnd = refinebounds(D,bnd,n*eps*anorm);\n\n  %%%%%%%%%%%%%%%%%%% Check convergence criterion %%%%%%%%%%%%%%%%%%%%\n  % Reorder eigenvalues according to SIGMA\n  switch part\n   case 'AS'\n    IPART = 1:j;\n   case 'AL' \n    IPART = j:-1:1;\n   case 'LM'\n    [dummy,IPART] = sort(-abs(D));\n   case 'BE'\n    if j<k\n      IPART=1:j;\n    else\n      mid = floor(k/2);\n      par = rem(k,1);\n      IPART = [1:mid,(j-mid-par):j]';\n    end    \n   otherwise\n    error(['Illegal value for SIGMA: ',part]);\n  end\n  D = D(IPART);  bnd = bnd(IPART);\n  if isnumeric(sigma)\n    D = sigma + 1./D;\n  end\n  \n  % Check if enough have converged.\n  neig = 0;\n  for i=1:min(j,k)\n    if bnd(i) <= tol*abs(D(i))\n      neig = neig + 1;\n    end\n  end\n  \n  %%%%%%%%%%% Check whether to stop or to extend the Krylov basis? %%%%%%%%%%\n  if ierr<0 % Invariant subspace found\n    if j<k\n      warning(['Invariant subspace of dimension ',num2str(j-1),' found.'])\n    end\n    break;\n  end\n  if j>=lanmax % Maximal dimension of Krylov subspace reached => Bail out!\n    if neig<ksave\n      warning(['Maximum dimension of Krylov subspace exceeded prior',...\n\t       ' to convergence.']);\n    end\n    break;\n  end\n  \n  % Increase dimension of Krylov subspace and try again.\n  if neig>0\n    %    j = j + ceil(min(20,max(2,((j-1)*(k-neig+1))/(2*(neig+1)))));\n    j = j + min(100,max(2,0.5*(k-neig)*j/(neig+1)));\n  elseif neig<k\n    %    j = j + ceil(min(20,max(8,(k-neig)/2)));\n    j = max(1.5*j,j+10);\n  end\n  j = min(j+1,lanmax);\n  nrestart = nrestart + 1;\nend\n\n\n\n%%%%%%%%%%%%%%%% Lanczos converged (or failed). Prepare output %%%%%%%%%%%%%%%\nk = min(ksave,j);\n\nif nargout>1\n  j = size(T,1);\n  [Q,D] = eig(full(T)); D = diag(D);\n  [D,I] = sort(D);\n  % Compute and normalize Ritz vectors (overwrite V to save memory).\n  V = V*Q(:,I(IPART(1:k)));\n  for i=1:k\n    nq = norm(V(:,i));\n    if isfinite(nq) & nq~=0 & nq~=1\n      V(:,i) = V(:,i)/nq;\n    end\n  end\n  [D,I] = sort(D);\n  D = D(IPART(1:k));\n  if isnumeric(sigma)\n    D = sigma + 1./D;\n    V(pmmd,:) = V;\n  end\nend\n\n% Pick out desired part of the spectrum\nif length(D)~=k\n  D = D(1:k);\n  bnd = bnd(1:k);\nend\n\nif nargout<2\n  V = D;\nelse\n  D = diag(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/mc/SVP/private/laneig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5905792275611864}}
{"text": "function T = logm(q,varargin)\n% the logarithmic map that translates a rotation into a spin tensor\n%\n% Syntax\n%   T = logm(q) % spin tensor with reference to the identical rotation\n%   T = logm(q,q_ref) % spin tensor with reference q_ref\n%\n% Input\n%  q - @quaternion\n%  q_ref - @quaternion\n%\n% Output\n%  T - @spinTensor\n%\n% See also\n% spinTensor/exp \n\ntq = log(q,varargin{:});\n\nM = zeros([3,3,size(q)]);\n\nM(2,1,:) =  tq.z;\nM(3,1,:) = -tq.y;\nM(3,2,:) =  tq.x;\n\nM(1,2,:) = -tq.z;\nM(1,3,:) =  tq.y;\nM(2,3,:) = -tq.x;\n\n% make it a spinTensor\nT = spinTensor(M);\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@quaternion/logm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5905792219742831}}
{"text": "function incidence_matrix = gr_incidence_matrix ( node_num, ...\n  node_coordinates, edge_num, edge_nodes )\n\n%*****************************************************************************80\n%\n%% GR_INCIDENCE_MATRIX computes the incidence matrix.\n%\n%  Discussion:\n%\n%    The incidence matrix is of order EDGE_NUM by NODE_NUM.\n%\n%    A(I,J) = 1 if edge I uses node J.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    24 January 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_COORDINATES(2,NODE_NUM), the coordinates of the nodes.\n%\n%    Input, integer EDGE_NUM, the number of edges.\n%\n%    Input, integer EDGE_NODES(2,EDGE_NUM), the indices of the two nodes\n%    that form each edge.\n%\n%    Output, integer INCIDENCE_MATRIX(EDGE_NUM,NODE_NUM), the incidence\n%    matrix.\n%\n  incidence_matrix = zeros ( edge_num, node_num );\n\n  for e = 1 : edge_num\n    for i = 1 : 2\n      n = edge_nodes(i,e);\n      incidence_matrix(e,n) = incidence_matrix(e,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/graph_representation/gr_incidence_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.5905619358382722}}
{"text": "function matrix = rmAverageTime(matrix,nrep);\n% rmAverageTime - average non-unique epochs in time (1st) dimension\n%\n%  out = rmAverageTime(in,nrep);\n%\n% 2006/03 SOD: wrote it.\n\n% sanity check (<1 no averaging needed)\nif nrep <= 1,\n  return;\nelse,\n  matrixin = matrix;\nend;\n\n\n% get total size input\nsz  = size(matrixin);\n\n% get total size output\nlen      = sz(1)./nrep;\nszout    = sz; \nszout(1) = len;\n\n% initiate matrixout\nmatrix   = matrixin(1:len,:);\n\n% repeat (add) process \nstart = len;\nfor n=1:nrep-1,\n    matrix = matrix + matrixin(start+1:start+len,:);\n    start     = start + len;\nend;\n\n% mean\nmatrix = matrix ./ nrep;\n\n% reshape if necesary\nmatrix = reshape(matrix,szout);\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/rmAverageTime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5905619271090569}}
{"text": "function y = square_pos( x )\n\n%SQUARE_POS    Square of positive part.\n%   SQUARE_POS(X) is the square of the postive parts of the elements of X;\n%   i.e., SQUARE_POS(X)=MAX(X,0).^2. X must be real.\n%\n%   Disciplined convex programming information:\n%       SQUARE_POS(X) is convex and nondecreasing in X. Thus when used in\n%       CVX expressions, X must be convex (or affine).\n\nnarginchk(1,1);\nif ~isreal( x ), \n    error( 'Argument must be real.' ); \nend\n\ny = square( max( x, 0 ) );\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/square_pos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370421, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.5905619259370292}}
{"text": "function triangulation_test08 ( )\n\n%*****************************************************************************80\n%\n%% TEST08 tests R8TRIS2.\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  node_num = 9;\n  dim_num = 2;\n\n  node_xy = [ ...\n       0.0, 0.0; ...\n       0.0, 1.0; ...\n       0.2, 0.5; ...\n       0.3, 0.6; ...\n       0.4, 0.5; ...\n       0.6, 0.4; ...\n       0.6, 0.5; ...\n       1.0, 0.0; ...\n       1.0, 1.0 ]';\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST08\\n' );\n  fprintf ( 1, '  R8TRIS2 computes the Delaunay triangulation of\\n' );\n  fprintf ( 1, '    a set of nodes in 2D.\\n' );\n%\n%  Set up the Delaunay triangulation.\n%\n  [ triangle_num, triangle_node, triangle_neighbor ] = r8tris2 ( ...\n    node_num, node_xy );\n\n  triangulation_order3_print ( node_num, triangle_num, node_xy, ...\n    triangle_node, triangle_neighbor );\n\n  return\nend\n", "meta": {"author": "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_test08.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5905619239164762}}
{"text": "function [N,X,sp] = histogramDistributionPlot(varargin)\n% HISTOGRAM generates a histogram using the \"optimal\" number of bins\n%\n% If called with no output argument, histogram plots into the current axes\n%\n% SYNOPSIS [N,X,sp] = histogram(data,factor,normalize)\n%          [...] = histogram(data,'smooth')\n%          [...] = histogram(axesHandle,...)\n%\n% INPUT    data: vector of input data\n%          factor: (opt) factor by which the bin-widths are multiplied\n%                   if 'smooth' (or 's'), a smooth histogram will be formed.\n%                   (requires the spline toolbox). For an alternative\n%                   approach to a smooth histogram, see ksdensity.m\n%                   if 'discrete' (or 'd'), the data is assumed to be a discrete\n%                   collection of values. Note that if every data point is,\n%                   on average, repeated at least 3 times, histogram will\n%                   consider it a discrete distribution automatically.\n%                   if 'continuous' (or 'c'), histogram is not automatically\n%                   checking for discreteness.\n%          normalize : if 1 (default), integral of histogram equals number\n%                       data points. If 0, height of bins equals counts.\n%                       This option is exclusive to non-\"smooth\" histograms\n%          axesHandle: (opt) if given, histogram will be plotted into these\n%                       axes, even if output arguments are requested\n%\n% OUTPUT   N   : number of points per bin (value of spline)\n%          X   : center position of bins (sorted input data)\n%          sp  : definition of the smooth spline\n%\n% REMARKS: The smooth histogram is formed by calculating the cumulative\n%           histogram, fitting it with a smoothening spline and then taking\n%           the analytical derivative. If the number of data points is\n%           markedly above 1000, the spline is fitting the curve too\n%           locally, so that the derivative can have huge peaks. Therefore,\n%           only 1000-1999 points are used for estimation.\n%           Note that the integral of the spline is almost exactly the\n%           total number of data points. For a standard histogram, the sum\n%           of the hights of the bins (but not their integral) equals the\n%           total number of data points. Therefore, the counts might seem\n%           off.\n%\n%           WARNING: If there are multiples of the minimum value, the\n%           smooth histogram might get very steep at the beginning and\n%           produce an unwanted peak. In such a case, remove the\n%           multiple small values first (for example, using isApproxEqual)\n%\n%\n% c: 2/05 jonas\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% test input\nif nargin < 1\n    error('not enough input arguments for histogram')\nend\n\n% check for axes handle\nif length(varargin{1}) == 1 && ishandle(varargin{1});\n    axesHandle = varargin{1};\n    varargin(1) = [];\nelse\n    % ensure compatibility to when axesHandle was given as last input\n    if nargin == 3 && ishandle(varargin{end}) && varargin{end} ~= 0\n        axesHandle = varargin{end};\n        varargin(end) = [];\n    else\n        axesHandle = 0;\n    end\nend\n\n% assign data\nnumArgIn = length(varargin);\ndata = varargin{1};\ndata = data(:);\n\n% check for non-finite data points\ndata(~isfinite(data)) = [];\n\n% check for \"factor\"\nif numArgIn < 2 || isempty(varargin{2})\n    factor = 1;\nelse\n    factor = varargin{2};\nend\nif ischar(factor)\n    switch factor\n        case {'smooth','s'}\n        factor = -1;\n        case {'discrete','d'}\n            factor = -2;\n        case {'continuous','c'}\n            factor = -3;\n    otherwise\n        error('The only string inputs permitted for histogram.m are ''smooth'',''discrete'', or ''continuous''')\n    end\nelse\n    % check for normalize, but do so only if there is no \"smooth\". Note\n    % that numArgIn is not necessarily equal to nargin\n    if numArgIn < 3 || isempty(varargin{3})\n        normalize = true;\n    else\n        normalize = varargin{3};\n    end\nend\n\n% doPlot is set to 1 for now. We change it to 0 below if necessary.\ndoPlot = 1;\n\nnData = length(data);\n% check whether we do a standard or a smooth histogram\nif factor ~= -1\n    % check for discrete distribution\n    [xx,nn] = countEntries(data);\n    % consider the distribution discrete if there are, on average, 3\n    % entries per bin\n    nBins = length(xx);\n    if factor == -2 || (factor ~= -3 && nBins*3 < nData)\n        % discrete distribution.\n        nn = nn';\n        xx = xx';\n    else\n        % not a discrete distribution\n        if nData < 20\n            warning('HISTOGRAM:notEnoughDataPoints','Less than 20 data points!')\n            nBins = ceil(nData/4);\n        else\n\n            % create bins with the optimal bin width\n            % W = 2*(IQD)*N^(-1/3)\n            interQuartileDist = diff(prctile(data,[25,75]));\n            binLength = 2*interQuartileDist*length(data)^(-1/3)*factor;\n\n            % number of bins: divide data range by binLength\n            nBins = round((max(data)-min(data))/binLength);\n\n            if ~isfinite(nBins)\n                nBins = length(unique(data));\n            end\n\n        end\n\n\n\n        % histogram\n        [nn,xx] = hist(data,nBins);\n        % adjust the height of the histogram\n        if normalize\n            Z = trapz(xx,nn);\n            nn = nn * nData/Z;\n        end\n\n    end\n    if nargout > 0\n        N = nn;\n        X = xx;\n        doPlot = axesHandle;\n    end\n    if doPlot\n        if axesHandle\n            bar(axesHandle,xx,nn,1);\n        else\n            bar(xx,nn,1);\n        end\n    end\n\nelse\n    % make cdf, smooth with spline, then take the derivative of the spline\n\n    % cdf\n    xData = sort(data);\n    yData = 1:nData;\n\n    % when using too many data points, the spline fits very locally, and\n    % the derivatives can still be huge. Good results can be obtained with\n    % 500-1000 points. Use 1000 for now\n    step = max(floor(nData/1000),1);\n    xData2 = xData(1:step:end);\n    yData2 = yData(1:step:end);\n\n    % spline. Use strong smoothing\n    cdfSpline = csaps(xData2,yData2,1./(1+mean(diff(xData2))^3/0.0006));\n\n    % pdf is the derivative of the cdf\n    pdfSpline = fnder(cdfSpline);\n\n    % histogram\n    if nargout > 0\n        xDataU = unique(xData);\n        N = fnval(pdfSpline,xDataU);\n        X = xDataU;\n        % adjust the height of the histogram\n        Z = trapz(X,N);\n        N = N * nData/Z;\n        sp = pdfSpline;\n        % set doPlot. If there is an axesHandle, we will plot\n        doPlot = axesHandle;\n    end\n    % check if we have to plot. If we assigned an output, there will only\n    % be plotting if there is an axesHandle.\n    if doPlot\n        if axesHandle\n            plot(axesHandle,xData,fnval(pdfSpline,xData));\n        else\n            plot(xData,fnval(pdfSpline,xData));\n        end\n    end\nend", "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/distributionPlot/histogramDistributionPlot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.5905619183798414}}
{"text": "function symmetric_sparse_size_test ( )\n\n%*****************************************************************************80\n%\n%% SYMMETRIC_SPARSE_SIZE_TEST tests SYMMETRIC_SPARSE_SIZE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    04 September 2012\n%\n%  Author:\n%\n%    John Burkardt.\n%\n%  Local parameters:\n%\n%    Local, integer D, the spatial dimension.\n%\n%    Local, integer MAXK, the maximum level to check.\n%\n  test_num = 3;\n\n  dim_test = [ 5, 5, 3 ];\n  nodes1 = [ ...\n   0.0, 0.0, 0.0, 0.0, 0.0, 1.0;\n   0.0, 0.0, 0.0, 0.0, 1.0, 0.0;\n   0.0, 0.0, 0.0, 1.0, 0.0, 0.0;\n   0.0, 0.0, 1.0, 0.0, 0.0, 0.0;\n   0.0, 1.0, 0.0, 0.0, 0.0, 0.0 ]';\n  nodes2 = [ ...\n    0.0, 0.0, 0.0, 0.0, 0.0, ...\n    0.0, 0.0, 0.0, 0.0, 0.0, ...\n    0.0, 0.0, 0.0, 0.0, 0.0, ...\n    1.0, 1.0, 1.0, 1.0, 1.0, ...\n    1.73205; ...\n    0.0, 0.0, 0.0, 0.0, 0.0, ...\n    0.0, 0.0, 0.0, 0.0, 0.0, ...\n    1.0, 1.0, 1.0, 1.0, 1.73205, ...\n    0.0, 0.0, 0.0, 0.0, 1.0, ...\n    0.0; ...\n    0.0, 0.0, 0.0, 0.0, 0.0, ...\n    0.0, 1.0, 1.0, 1.0, 1.73205, ...\n    0.0, 0.0, 0.0, 1.0, 0.0, ...\n    0.0, 0.0, 0.0, 1.0, 0.0, ...\n    0.0; ...\n    0.0, 0.0, 0.0, 1.0, 1.0, ...\n    1.73205, 0.0, 0.0, 1.0, 0.0, ...\n    0.0, 0.0, 1.0, 0.0, 0.0, ...\n    0.0, 0.0, 1.0, 0.0, 0.0, ...\n    0.0; ...\n    0.0, 1.0, 1.73205, 0.0, 1.0, ...\n    0.0, 0.0, 1.0, 0.0, 0.0, ...\n    0.0, 1.0, 0.0, 0.0, 0.0, ...\n    0.0, 1.0, 0.0, 0.0, 0.0, ...\n    0.0 ]';\n  nodes3 = [ ...\n    0.0, 0.0, 0.0, 0.0, 0.0, ...\n    0.0, 0.0, 0.0, 0.0, 0.0, ...\n    0.0, 0.0, 0.741964, 1.0, 1.0, ...\n    1.0, 1.0, 1.0, 1.0, 1.73205, ...\n    1.73205, 1.73205, 2.33441; ...\n    0.0, 0.0, 0.0, 0.0, 0.0, ...\n    0.741964, 1.0, 1.0, 1.0, 1.73205, ...\n    1.73205, 2.33441, 0.0, 0.0, 0.0, ...\n    0.0, 1.0, 1.0, 1.73205, 0.0, ...\n    0.0, 1.0, 0.0; ...\n    0.0, 0.741964, 1.0, 1.73205, 2.33441, ...\n    0.0, 0.0, 1.0, 1.73205, 0.0, ...\n    1.0, 0.0, 0.0, 0.0, 1.0, ...\n    1.73205, 0.0, 1.0, 0.0, 0.0, ...\n    1.0, 0.0, 0.0 ]';\n  r_test = [ 6, 21, 23 ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'SYMMETRIC_SPARSE_SIZE_TEST\\n' );\n  fprintf ( 1, '  Given a symmetric sparse grid rule represented only by\\n' );\n  fprintf ( 1, '  the points with positive values, determine the total number\\n' );\n  fprintf ( 1, '  of points in the grid.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  For dimension DIM, we report\\n' );\n  fprintf ( 1, '  R, the number of points in the positive orthant, and\\n' );\n  fprintf ( 1, '  R2, the total number of points.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '       DIM         R        R2\\n' );\n  fprintf ( 1, '\\n' );\n\n  x0 = 0.0;\n\n  for test = 1 : test_num\n\n    r = r_test(test);\n    dim = dim_test(test);\n\n    if ( test == 1 )\n      r2 = symmetric_sparse_size ( r, dim, nodes1, x0 );\n    elseif ( test == 2 )\n      r2 = symmetric_sparse_size ( r, dim, nodes2, x0 );\n    elseif ( test == 3 )\n      r2 = symmetric_sparse_size ( r, dim, nodes3, x0 );\n    end\n\n    fprintf ( 1, '  %8d  %8d  %8d\\n', dim, r, r2 );\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/symmetric_sparse_size_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.5905619183798413}}
{"text": "%SUBTRACT  Calculates the per-element difference between two arrays or array and a scalar\n%\n%     dst = cv.subtract(src1, src2)\n%     dst = cv.subtract(src1, src2, 'OptionName',optionValue, ...)\n%\n% ## Input\n% * __src1__ first input array or a scalar.\n% * __src2__ second input array or a scalar.\n%\n% ## Output\n% * __dst__ output array of the same size and number of channels as the input\n%   array(s). The depth is defined by `DType` or that of `src1`/`src2`.\n%\n% ## Options\n% * __Mask__ optional operation mask; this is an 8-bit single channel array\n%   that specifies elements of the output array to be changed. Not set by\n%   default.\n% * __Dest__ Used to initialize the output `dst` when a mask is used. Not set\n%   by default.\n% * __DType__ optional depth of the output array: `uint8`, `int16`, `double`,\n%   etc. (see the discussion below). Must be specified if input arrays are of\n%   different types. default -1\n%\n% The function cv.subtract calculates:\n%\n% * Difference between two arrays, when both input arrays have the same size\n%   and the same number of channels:\n%\n%       dst(I) = saturate(src1(I) - src2(I)) if mask(I) != 0\n%\n% * Difference between an array and a scalar, when `src2` is constructed from\n%   Scalar or has the same number of elements as `size(src1,3)`:\n%\n%       dst(I) = saturate(src1(I) - src2) if mask(I) != 0\n%\n% * Difference between a scalar and an array, when `src1` is constructed from\n%   Scalar or has the same number of elements as `size(src2,3)`:\n%\n%       dst(I) = saturate(src1 - src2(I)) if mask(I) != 0\n%\n% * The reverse difference between a scalar and an array in the case of\n%   `SubRS`:\n%\n%       dst(I) = saturate(src2 - src1(I)) if mask(I) != 0\n%\n% where `I` is a multi-dimensional index of array elements. In case of\n% multi-channel arrays, each channel is processed independently.\n%\n% The first function in the list above can be replaced with matrix expressions:\n%\n%     dst = src1 - src2;\n%\n% The input arrays and the output array can all have the same or different\n% depths. For example, you can subtract to 8-bit unsigned arrays and store the\n% difference in a 16-bit signed array. Depth of the output array is determined\n% by `DType` parameter. In the second and third cases above, as well as in the\n% first case, when `class(src1) == class(src2)`, `DType` can be set to the\n% default -1. In this case the output array will have the same depth as the\n% input array, be it `src1`, `src2` or both.\n%\n% Note: Saturation is not applied when the output array has the depth `int32`.\n% You may even get result of an incorrect sign in the case of overflow.\n%\n% See also: cv.add, cv.addWeighted\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/subtract.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.5905619146012473}}
{"text": "function [Signal, Sigma] = MPdenoising(data, mask, kernel, sampling, centering)\n    %\n    % \"MPPCA\": 4d image denoising and noise map estimation by exploiting  data redundancy in the PCA domain using universal properties of the eigenspectrum of\n    % random covariance matrices, i.e. Marchenko Pastur distribution\n    %\n    %  [Signal, Sigma] = MPdenoising(data, mask, kernel, sampling)\n    %       output:\n    %           - Signal: [x, y, z, M] denoised data matrix\n    %           - Sigma: [x, y, z] noise map\n    %       input:\n    %           - data: [x, y, z, M] data matrix\n    %           - mask:   (optional)  region-of-interest [boolean]\n    %           - kernel: (optional)  window size, typically in order of [5 x 5 x 5]\n    %           - sampling: \n    %                    1. full: sliding window (default for noise map estimation, i.e. [Signal, Sigma] = MPdenoising(...) )\n    %                    2. fast: block processing (default for denoising, i.e. [Signal] = MPdenoising(...))\n    % \n    %  Authors: Jelle Veraart (jelle.veraart@nyumc.org)\n    % Copyright (c) 2016 New York Universit and University of Antwerp\n    %       \n    %      Permission is hereby granted, free of charge, to any non-commercial entity\n    %      ('Recipient') obtaining a copy of this software and associated\n    %      documentation files (the 'Software'), to the Software solely for\n    %      non-commercial research, including the rights to use, copy and modify the\n    %      Software, subject to the following conditions: \n    %       \n    %        1. The above copyright notice and this permission notice shall be\n    %      included by Recipient in all copies or substantial portions of the\n    %      Software. \n    %       \n    %        2. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n    %      EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIESOF\n    %      MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n    %      NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BELIABLE FOR ANY CLAIM,\n    %      DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n    %      OTHERWISE, ARISING FROM, OUT OF ORIN CONNECTION WITH THE SOFTWARE OR THE\n    %      USE OR OTHER DEALINGS IN THE SOFTWARE. \n    %       \n    %        3. In no event shall NYU be liable for direct, indirect, special,\n    %      incidental or consequential damages in connection with the Software.\n    %      Recipient will defend, indemnify and hold NYU harmless from any claims or\n    %      liability resulting from the use of the Software by recipient. \n    %       \n    %        4. Neither anything contained herein nor the delivery of the Software to\n    %      recipient shall be deemed to grant the Recipient any right or licenses\n    %      under any patents or patent application owned by NYU. \n    %       \n    %        5. The Software may only be used for non-commercial research and may not\n    %      be used for clinical care. \n    %       \n    %        6. Any publication by Recipient of research involving the Software shall\n    %      cite the references listed below.\n    % \n    % REFERENCES\n    %      Veraart, J.; Fieremans, E. & Novikov, D.S. Diffusion MRI noise mapping\n    %      using random matrix theory Magn. Res. Med., 2016, early view, doi:\n    %      10.1002/mrm.26059\n\n\n \n    if isa(data,'integer') \n        data = single(data);\n    end\n    [sx, sy, sz, M] = size(data);\n\n       \n    if ~exist('mask', 'var') || isempty(mask)\n        mask = true([sx, sy, sz]);\n    end\n    if ~isa(mask,'boolean') \n        mask = mask>0;\n    end\n  \n    if ~exist('kernel', 'var') || isempty(kernel)\n        kernel = [5 5 5];\n    end\n    \n    if isscalar(kernel)\n        kernel = [kernel, kernel, kernel];\n    end\n    kernel = kernel + (mod(kernel, 2)-1);   % needs to be odd.\n    k = (kernel-1)/2; kx = k(1); ky = k(2); kz = k(3);\n    N = prod(kernel);\n    \n    if ~exist('sampling', 'var') || isempty(sampling)\n        if nargout > 1\n            sampling = 'full';\n        else\n            sampling = 'fast';\n        end\n    end\n    \n    \n    % create mask\n    if ~exist('mask', 'var') || isempty(mask)\n        mask = true(sx, sy, sz);\n    end\n    \n    if ~exist('centering', 'var') || isempty(centering)\n        centering = false;\n    end\n    \n    if strcmp(sampling, 'fast')  \n        if nargout>1\n            warning('undersampled noise map will be returned')\n        end\n        % compute center points of patches\n        stats = regionprops(mask, 'BoundingBox');\n        n = ceil(stats.BoundingBox(4:6) ./ kernel);\n\n        x = linspace(ceil(stats.BoundingBox(1))+k(1), floor(stats.BoundingBox(1))-k(1) + stats.BoundingBox(4), n(1)); x = round(x);\n        y = linspace(ceil(stats.BoundingBox(2))+k(2), floor(stats.BoundingBox(2))-k(2) + stats.BoundingBox(5), n(2)); y = round(y);\n        z = linspace(ceil(stats.BoundingBox(3))+k(3), floor(stats.BoundingBox(3))-k(3) + stats.BoundingBox(6), n(3)); z = round(z);\n\n        [y, x, z] = meshgrid(x, y, z); x = x(:); y = y(:); z = z(:);\n    end\n    \n    if strcmp(sampling, 'full')\n        warning('image boundaries are not processed.')\n        mask(1:k(1), :, :) = 0;\n        mask(sx-k(1):sx, :, :) = 0;\n \n        mask(:, 1:k(2), :) = 0;\n        mask(:, sy-k(2):sy, :, :) = 0;           \n        mask(:,:,1:k(3)) = 0;\n        mask(:,:,sz-k(3)) = 0;\n             \n        x = []; y = []; z = []; \n        for i = k(3)+1:sz-k(3)\n            [x_, y_] = find(mask(:,:,i) == 1);\n            x = [x; x_]; y = [y; y_];  z = [z; i*ones(size(y_))];\n        end \n        x = x(:); y = y(:); z = z(:);\n    end\n\n    \n    % Declare variables:\n    if logical(exist('OCTAVE_VERSION', 'builtin')) % for Octave, zeros(..,'like',data) not implemented. replace with class(data).\n        zerosoption = {class(data)};\n    else\n        zerosoption = {'like', data};\n    end\n    sigma = zeros(1, numel(x), zerosoption{:});\n    npars = zeros(1, numel(x), zerosoption{:});\n    signal = zeros(M, prod(kernel), numel(x), zerosoption{:});\n\n    Sigma = zeros(sx, sy, sz, zerosoption{:});\n    Npars = zeros(sx, sy, sz, zerosoption{:});\n    Signal = zeros(sx, sy, sz, M, zerosoption{:});\n\n    \n    % compute scaling factor for in case N<M\n    R = min(M, N);\n    scaling = (max(M, N) - (0:R-centering-1)) / N;\n    scaling = scaling(:);\n\n    \n    % start denoising\n    for nn = 1:numel(x)\n        \n        % create data matrix \n        X = data(x(nn)-kx:x(nn)+kx, y(nn)-ky:y(nn)+ky, z(nn)-kz:z(nn)+kz, :);\n        X = reshape(X, N, M); X = X';\n\n        if centering\n            colmean = mean(X, 1);\n            X = X - repmat(colmean, [M, 1]);\n        end\n        % compute PCA eigenvalues \n        [u, vals, v] = svd(X, 'econ');\n        vals = diag(vals).^2 / N;   \n\n        \n        % First estimation of Sigma^2;  Eq 1 from ISMRM presentation \n        csum = cumsum(vals(R-centering:-1:1)); cmean = csum(R-centering:-1:1)./(R-centering:-1:1)'; sigmasq_1 = cmean./scaling;\n        \n        % Second estimation of Sigma^2; Eq 2 from ISMRM presentation \n        gamma = (M - (0:R-centering-1)) / N;\n        rangeMP = 4*sqrt(gamma(:));\n        rangeData = vals(1:R-centering) - vals(R-centering);\n        sigmasq_2 = rangeData./rangeMP;\n        \n        % sigmasq_2 > sigma_sq1 if signal-components are represented in the\n        % eigenvalues\n        \n        t = find(sigmasq_2 < sigmasq_1, 1);\n\n        if isempty(t)\n            sigma(nn) = NaN;\n            signal(:, :, nn) = X;  \n            t = R+1;\n        else\n            sigma(nn) = sqrt(sigmasq_1(t));\n            vals(t:R) = 0;\n            s = u*diag(sqrt(N*vals))*v';\n            if centering\n               s = s + repmat(colmean, [M, 1]);\n            end\n        \n            signal(:, :, nn) = s;\n        end\n        npars(nn) = t-1; \n    end\n\n    for nn = 1:numel(x)\n        Sigma(x(nn), y(nn), z(nn)) = sigma(nn);\n        Npars(x(nn), y(nn), z(nn)) = npars(nn);\n        if strcmp(sampling, 'fast')\n            Signal(x(nn)-k(1):x(nn)+k(1),y(nn)-k(2):y(nn)+k(2),z(nn)-k(3):z(nn)+k(3), :) = unpatch(signal(:,:,nn), k);\n        elseif strcmp(sampling, 'full')\n            Signal(x(nn), y(nn),z(nn), :) = signal(:,ceil(prod(kernel)/ 2),nn);\n        end\n    end\nend\n\nfunction data = unpatch(X, k)\n    kernel=k+k+1; \n    data = zeros([kernel, size(X, 1)]);\n    tmp = zeros(kernel);\n    for i = 1:size(X, 1);\n        tmp(:) = X(i, :);\n        data(:,:,:,i) = tmp;\n    end \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/mppca_denoise/MPdenoising.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5903969091342346}}
{"text": "function [f] = spm_fx_poly(x,v,P)\n% Normal (bilinear) form equation of motion\n% FORMAT [f] = spm_fx_poly(x,v,P)\n% x      - state vector\n% v      - exogenous cause\n% P      - free parameters \n%\n% f      - dx/dt\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_fx_poly.m 3878 2010-05-07 19:53:54Z karl $\n\n% compute Jacobian from blinear terms\n%--------------------------------------------------------------------------\nx     = spm_vec(x);\nJ     = P.A;\nfor i = 1:length(P.B)\n    J = J + P.B{i}*x(i);\nend\nfor i = 1:length(P.C)\n    J = J + P.C{i}*v(i);\nend\nf     = J*x;\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_fx_poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642945, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5903553103815933}}
{"text": "function s = dirichlet_initial_s(m, bar_p)\n\nK = length(m);\nm = m/sum(m);\ns = (K-1)/2/(-sum(m.*bar_p)+sum(m.*log(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/fastfit/dirichlet_initial_s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5903553103147929}}
{"text": "function [result, prediction] = svr_test_linear_shift(test_labels, test_samples, model)\n   \n    prediction = test_samples * model.w(1:end-1)' + model.w(end);\n%     prediction = predict(test_labels, test_samples, model);\n\n    prediction(~model.success) = 0;\n    \n    if(model.cutoff >= 0)\n        % perform shifting here per person\n        users = unique(model.vid_ids);\n\n        for i=1:numel(users)\n\n            preds_user = prediction(strcmp(model.vid_ids, users(i)));\n            sorted = sort(preds_user);\n\n            % alternative, move to histograms and pick the highest one\n\n            shift = sorted(round(end*model.cutoff)+1);\n\n            prediction(strcmp(model.vid_ids, users(i))) = preds_user - shift;\n\n        end\n    end\n    \n    % Cap the prediction as well\n    prediction(prediction<0)=0;\n    prediction(prediction>5)=5;\n    \n    % using the average of RMS errors\n%     result = mean(sqrt(mean((prediction - test_labels).^2)));  \n    if(~isfield(model, 'eval_ids'))\n        result = corr(test_labels, prediction);\n        [ ~, ~, ~, ccc, ~, ~ ] = evaluate_regression_results( prediction, test_labels ); \n        result = ccc;\n    else\n        eval_ids = unique(model.eval_ids)';\n        ccc = 0;\n        fprintf('CCC: ');\n        for i=eval_ids\n            [ ~, ~, ~, ccc_curr, ~, ~ ] = evaluate_regression_results( prediction(model.eval_ids == i), test_labels(model.eval_ids == i) ); \n            ccc = ccc + ccc_curr;\n            fprintf('%.3f ', ccc_curr);\n        end\n        ccc = ccc / numel(eval_ids);\n        fprintf('mean : %.3f\\n', ccc);\n        result = ccc;\n    end\n    \n    if(isnan(result))\n        result = 0;\n    end\n    \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/AU_training/experiments/training_code/svr_test_linear_shift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5903553023767216}}
{"text": "function p_ = ViewCurveSlope(X,p)\n\n[J,K]=size(X);\n\n% constrain probabilities to sum to one...\nAeq = ones(1,J);\nbeq=1;\n\n% ...constrain the expectation...\nV= X(:,14)-X(:,13);\nv=.0005;\n\nAeq=[Aeq\n    V'];\nbeq=[beq\n    v];\n\nA=[];\nb=[];\n\n% ...compute posterior probabilities\np_ = EntropyProg(p,A,b,Aeq ,beq);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21307-fully-flexible-views-and-stress-testing/EntropyPooling/ButterflyTrading/ViewCurveSlope.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5903552985412871}}
{"text": "function [RR_e_resamp,QRS_A_resamp] = clean_and_resample_intervals(onsets,QRS_A1,Fs)   \n\n% Use same pre-processing used for ECG in the paper ''\n% \n% \n\nIBI = diff(onsets)./Fs;\nt_IBI = onsets(2:end)./Fs;\n\nRR_e0 = IBI;     % no ectopic rejection\nQRS_A0 = QRS_A1;\n\n% reject ectopic beats\n% remove invalid R-R intervals if RR<0.3 or RR>2.0 & 20% outside of 41 points moving mean exclude  \n\nRR_mean_41 = meanfilt1(IBI,41);\nRR = [];    % RR interval in seconds\nRR_time=[]; % time of RR interval in seconds\nv_RR = ones(1,length(IBI))*-1;\nn_RR = 0;\nfor j=1:length(IBI)\n    if abs(IBI(j) - RR_mean_41(j)) < 0.2*RR_mean_41(j) &&  IBI(j)>= 0.3 && IBI(j) <= 2.0\n        n_RR = n_RR+1;\n        RR(n_RR) = IBI(j);\n        RR_time(n_RR) = onsets(j)/Fs;\n        v_RR(j)=1;\n    end\nend\nvalid_RR=find(v_RR==1);\n% remove invalid QRS peaks if 50% outside of 41 points moving mean\nQRS_A_mean_41=meanfilt1(QRS_A1,41);\nn_QRS=0;\nQRS=[];\nQRS_time=[];\nv_QRS=ones(1,length(QRS_A1))*-1;\nfor k=1:length(QRS_A1)\n    if abs(QRS_A1(k)-QRS_A_mean_41(k))<0.5*QRS_A_mean_41(k)\n        n_QRS=n_QRS+1;\n        QRS(n_QRS) = QRS_A1(k);\n        QRS_time(n_QRS) = tIBI(j);\n        v_QRS(k)=1;\n    end\nend\nvalid_QRS=find(v_QRS==1);\nvalid_RRQRS=intersect(valid_RR,valid_QRS);\nvalid_RR=valid_RRQRS;\n\nonsets = onsets(valid_RR);\nQRS_A1=QRS_A1(valid_RR);\n\nRR_e1 = IBI(valid_RR);\n\n% resample to 4Hz\nonsets = onsets./Fs;\nt2=round(onsets(end));\nFs_resamp=4;\nt1=(1/Fs_resamp):(1/Fs_resamp):t2; % 4Hz resample\n\n% linear interpolation\nQRS_A_resamp = interp1(onsets,QRS_A1,t1);%,'spline');\nRR_e_resamp = interp1(onsets,RR_e1,t1);%,'spline');\nQRS_A_resamp(find(isnan(QRS_A_resamp)))=nanmean(QRS_A_resamp);\nRR_e_resamp(find(isnan(RR_e_resamp)))=nanmean(RR_e_resamp);", "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/Sleep_PPG_transfer_learning/FeaturesExtraction/PreProcessing/clean_and_resample_intervals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5903101340520712}}
{"text": "function ret = filterBlock(in)\n    in = in + 1e-8;\n%     idx = [2 4 5 6 8];\n%     in = in(idx, :);\n    mid = in(5, :);\n%     ret = sum(abs(bsxfun(@minus, log(mid), log(in)))) / 8;\n    temp = abs(bsxfun(@minus, log(mid), log(in)));\n    ret = sum((temp)) / 8;\nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/MBRMF/Utilities/filterBlock.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5902385868972689}}
{"text": "function [Hx,Hy,Ez,time] = MaxwellPNonCon2D(pinfo, Hx, Hy, Ez, FinalTime)\n\n% function [Hx,Hy,Ez] = MaxwellPNonCon2D(pinfo, Hx, Hy, Ez, FinalTime)\n% Purpose  : Integrate TM-mode Maxwell's until FinalTime starting with initial conditions Hx,Hy,Ez       \n\nGlobals2D;\ntime = 0;\n\n% Runge-Kutta residual storage  \nresHx = zeros(size(Hx)); resHy = resHx; resEz = resHx;\n\n% compute time step size (taking into account variable polynomial order)\ndt = 100;\nfor N=1:length(pinfo)\n  dt = min(dt, 2./( N^2*max(pinfo(N).Fscale(:)/2)));\nend\n\n% outer time step loop \ntstep = 1;\nwhile (time<FinalTime)\n  \n   if(time+dt>FinalTime), dt = FinalTime-time; end\n\n   for INTRK = 1:5    \n      % compute right hand side of TM-mode Maxwell's equations\n      [rhsHx, rhsHy, rhsEz] = MaxwellPNonConRHS2D(pinfo, Hx,Hy,Ez);\n\n      % initiate and increment Runge-Kutta residuals\n      resHx = rk4a(INTRK)*resHx + dt*rhsHx;  \n      resHy = rk4a(INTRK)*resHy + dt*rhsHy; \n      resEz = rk4a(INTRK)*resEz + dt*rhsEz; \n      \n      % update fields\n      Hx = Hx+rk4b(INTRK)*resHx;  \n      Hy = Hy+rk4b(INTRK)*resHy;  \n      Ez = Ez+rk4b(INTRK)*resEz;        \n   end;\n\n   % Increment time\n   time = time+dt; tstep = tstep+1;\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/Codes2D/MaxwellPNonCon2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5902385868972689}}
{"text": "%% A Unit Test Class for mklJac\nclassdef mklJac_tests < matlab.unittest.TestCase\n\n    properties\n        absTol = 1e-8;\n    end\n    \n    % Unit Tests\n    methods (Test)\n\n        %-- Valid Operation --%\n        function scalarDiff(testCase)\n            testCase.verifyEqual(1, mklJac(@(x) sin(x), 0), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(1, mklJac(@(x) sin(x), 0, 1), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(-1, mklJac(@(x) sin(x), pi), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(0, mklJac(@(x) cos(x), pi), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(0, mklJac(@(x) cos(x), -pi), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(-1, mklJac(@(x) cos(x), pi/2), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(1, mklJac(@(x) cos(x), -pi/2), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(2, mklJac(@(x) 2*x, 0), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(2, mklJac(@(x) 2*x, 1), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(2, mklJac(@(x) 2*x, 2), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(-2, mklJac(@(x) -2*x, 0), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(-2, mklJac(@(x) -2*x, 1), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(-2, mklJac(@(x) -2*x, 2), 'AbsTol', testCase.absTol);\n        end\n        \n        function scalarDiffSweep(testCase)\n            fun = @(x) 3*cos(x^2) + 0.5*sin(x/2);\n            grad = @(x) cos(x/2)/4 - 6*x*sin(x^2);\n            x = linspace(-pi,pi);\n            for i = 1:length(x)\n                testCase.verifyEqual(grad(x(i)), mklJac(fun, x(i)), 'AbsTol', testCase.absTol);\n            end\n        end\n        \n        function vectorDiff(testCase)\n            testCase.verifyEqual(eye(3), mklJac(@(x) sin(x), zeros(3,1)), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(eye(6), mklJac(@(x) sin(x), zeros(6,1)), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(-eye(3), mklJac(@(x) sin(x), pi*ones(3,1)), 'AbsTol', testCase.absTol);\n            testCase.verifyEqual(zeros(3), mklJac(@(x) sin(x), pi/2*ones(3,1)), 'AbsTol', testCase.absTol);\n        end\n        \n        function vectorDiffSweep(testCase)\n            fun = @(x) 3*cos(x(1)^2)*sin(x(2)) + 0.5*sin(x(2)/2);\n            grad = @(x) [ -6*x(1)*sin(x(1)^2)*sin(x(2)), cos(x(2)/2)/4 + 3*cos(x(1)^2)*cos(x(2))];\n            x1 = linspace(-pi,pi);\n            x2 = linspace(pi,-pi);\n            for i = 1:length(x1)\n                testCase.verifyEqual(grad([x1(i);x2(i)]), mklJac(fun, [x1(i);x2(i)]), 'AbsTol', testCase.absTol);\n            end\n        end\n        \n        function vectorFunDiffSweep(testCase)\n            fun = @(x) [100*(x(2)-x(1)^2); 1 - x(1)];\n            grad = @(x) [-200*x(1) 100; -1 0];\n            x = linspace(-1,1,10);\n            for i = 1:length(x)\n                for j = 1:length(x)\n                    testCase.verifyEqual(grad([x(i);x(j)]), mklJac(fun, [x(i);x(j)]), 'AbsTol', testCase.absTol*10); %this is a hard one\n                end\n            end\n        end\n        \n        function autoSizeIdentify(testCase)\n            testCase.verifyEqual(1, numel(mklJac(@(x) sin(x), zeros(1,1))));\n            testCase.verifyEqual(4, numel(mklJac(@(x) sin(x), zeros(2,1))));\n            testCase.verifyEqual(9, numel(mklJac(@(x) sin(x), zeros(3,1))));\n            testCase.verifyEqual(16, numel(mklJac(@(x) sin(x), zeros(4,1))));\n        end    \n        \n        %-- Input Args --%\n        function inputArgs(testCase)\n            testCase.verifyError(@() mklJac(@(x) sin(x)), 'OPTIMex:InputError');   % not enough args\n            testCase.verifyError(@() mklJac(1, 1), 'OPTIMex:InputError');   % not fcn handle\n            testCase.verifyError(@() mklJac(@(x) sin(x), int16(1)), 'OPTIMex:InputError'); % wrong input type\n            testCase.verifyError(@() mklJac(@(x) sin(x), 1i), 'OPTIMex:InputError'); % wrong input type\n            testCase.verifyError(@() mklJac(@(x) sin(x), [1 1; 1 1]), 'OPTIMex:InputError'); % wrong input type\n            testCase.verifyError(@() mklJac(@(x) sin(x), 1, int16(1)), 'OPTIMex:InputError'); % wrong input type\n            testCase.verifyError(@() mklJac(@(x) sin(x), 1, [1;1]), 'OPTIMex:InputError'); % wrong input type\n            testCase.verifyError(@() mklJac(@(x) sin(x), 1, 0), 'OPTIMex:InputError'); % wrong val\n            testCase.verifyError(@() mklJac(@(x) sin(x), 1, 1e9), 'OPTIMex:InputError'); % wrong val\n            testCase.verifyError(@() mklJac(@(x) sin(x), 1, 1, int16(1)), 'OPTIMex:InputError'); % wrong input type\n            testCase.verifyError(@() mklJac(@(x) sin(x), 1, 1, [1;1]), 'OPTIMex:InputError'); % wrong input type\n            testCase.verifyError(@() mklJac(@(x) sin(x), 1, 1, 1e-18), 'OPTIMex:InputError'); % wrong val\n            testCase.verifyError(@() mklJac(@(x) sin(x), 1, 1, 1.1), 'OPTIMex:InputError'); % wrong val\n            testCase.verifyError(@() mklJac(@(x) sin(x), [1;1], 1), 'OPTIMex:DataError'); % wrong length\n            testCase.verifyError(@() mklJac(@(x) sin(x), [1;1], 3), 'OPTIMex:DataError'); % wrong length\n            testCase.verifyError(@() mklJac(@(x) sin(x), 1, 2), 'OPTIMex:DataError'); % wrong length (something odd about this ut)\n        end\n    end\n    \nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/math/opti/Utilities/UnitTests/mklJac_tests.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5902366450965356}}
{"text": "classdef RMMEDA_F4 < PROBLEM\n% <multi> <real> <large/none>\n% Benchmark MOP for testing RM-MEDA\n\n%------------------------------- Reference --------------------------------\n% Q. Zhang, A. Zhou, and Y. Jin, RM-MEDA: A regularity model-based\n% multiobjective estimation of distribution algorithm, IEEE Transactions on\n% Evolutionary Computation, 2008, 12(1): 41-63.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 3;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            g = sum((X(:,3:end)-repmat(X(:,1),1,size(X,2)-2)).^2,2);\n            PopObj(:,1) = cos(pi/2*X(:,1)).*cos(pi/2*X(:,2)).*(1+g);\n            PopObj(:,2) = cos(pi/2*X(:,1)).*sin(pi/2*X(:,2)).*(1+g);\n            PopObj(:,3) = sin(pi/2*X(:,1)).*(1+g);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R = UniformPoint(N,3);\n            R = R./repmat(sqrt(sum(R.^2,2)),1,3);\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            a = linspace(0,pi/2,10)';\n            R = {sin(a)*cos(a'),sin(a)*sin(a'),cos(a)*ones(size(a'))};\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/MOPs with variable linkages/RMMEDA_F4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5902366450965356}}
{"text": "function title = p14_title ( )\n\n%*****************************************************************************80\n%\n%% P14_TITLE returns the title for problem 14.\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%  Parameters:\n%\n%    Output, string TITLE, the title of the problem.\n%\n  title = 'sin ( exp(-x) + exp(-4x) )';\n\n  return\nend\n", "meta": {"author": "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/p14_title.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.5902366415906236}}
{"text": "function out = CO_Embed2_AngleTau(y,maxTau)\n% CO_Embed2_AngleTau Angle autocorrelation in a 2-dimensional embedding space\n%\n% Investigates how the autocorrelation of angles between successive points in\n% the two-dimensional time-series embedding change as tau varies from\n% tau = 1, 2, ..., maxTau.\n%\n%---INPUTS:\n% y, a column vector time series\n% maxTau, the maximum time lag to consider\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,\n% <http://www.benfulcher.com>\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 <http://www.gnu.org/licenses/>.\n% ------------------------------------------------------------------------------\n\ndoPlot = false;\ntauRange = (1:1:maxTau);\nnumTau = length(tauRange);\n\n% Ensure y is a column vector\nif size(y,2) > size(y,1);\n\ty = y';\nend\n\nstats_store = zeros(3,numTau);\n\nfor i = 1:numTau\n\ttau = tauRange(i);\n\n\tm = [y(1:end-tau), y(1+tau:end)];\n\n\ttheta = diff(m(:,2))./diff(m(:,1));\n\ttheta = atan(theta); % measured as deviation from the horizontal\n\n\tif isempty(theta)\n\t\terror('Time series (N=%u) too short for embedding',length(y));\n\tend\n\n\tstats_store(1,i) = CO_AutoCorr(theta,1,'Fourier');\n\tstats_store(2,i) = CO_AutoCorr(theta,2,'Fourier');\n\tstats_store(3,i) = CO_AutoCorr(theta,3,'Fourier');\nend\n\nif doPlot\n    figure('color','w'); box('on');\n    plot(stats_store');\nend\n\n% ------------------------------------------------------------------------------\n% Compute lots of outputs statistics:\n% ------------------------------------------------------------------------------\nout.ac1_thetaac1 = CO_AutoCorr(stats_store(1,:),1,'Fourier');\nout.ac1_thetaac2 = CO_AutoCorr(stats_store(2,:),1,'Fourier');\nout.ac1_thetaac3 = CO_AutoCorr(stats_store(3,:),1,'Fourier');\nout.mean_thetaac1 = mean(stats_store(1,:));\nout.max_thetaac1 = max(stats_store(1,:));\nout.min_thetaac1 = min(stats_store(1,:));\nout.mean_thetaac2 = mean(stats_store(2,:));\nout.max_thetaac2 = max(stats_store(2,:));\nout.min_thetaac2 = min(stats_store(2,:));\nout.mean_thetaac3 = mean(stats_store(3,:));\nout.max_thetaac3 = max(stats_store(3,:));\nout.min_thetaac3 = min(stats_store(3,:));\nout.meanrat_thetaac12 = out.mean_thetaac1/out.mean_thetaac2;\nout.diff_thetaac12 = sum(abs(stats_store(2,:)-stats_store(1,:)));\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_Embed2_AngleTau.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5902366404730364}}
{"text": "function lattice_print ( dim_num, m, z, title )\n\n%*****************************************************************************80\n%\n%% LATTICE_PRINT prints the points in a lattice rule.\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%    ISBN: 0198534728,\n%    LC: QA311.S56\n%\n%  Parameters:\n%\n%    Input, integer DIM_NUM, the spatial dimension.\n%\n%    Input, integer M, the number of points to use.\n%\n%    Input, integer Z(DIM_NUM), the generator vector.\n%\n%    Input, string TITLE, an optional title.\n%\n  if ( 0 < s_len_trim ( title ) )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '%s\\n', title );\n  end\n\n  fprintf ( 1, '\\n' );\n\n  for i = 0 : m - 1\n    y(1:dim_num) = mod ( i * z(1:dim_num), m );\n    fprintf ( 1, '%4d    ', i + 1 );\n    for dim = 1 : dim_num\n      fprintf ( 1, '%4d', y(dim) );\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/lattice_rule/lattice_print.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.5902366398376675}}
{"text": "function [ y, symm ] = cvx_s_symmetric( m, n, symm ) %#ok\n%CVX_S_SYMMETRIC Symmetric matrices (lower triangle storage).\nif m ~= n,\n    error( 'Symmetric structure requires square matrices.' );\nend\nsymm = false;\nnsq = n * n;\nntr = 0.5 * ( nsq + n );\nc  = 0 : n - 1;\nc  = c( ones( 1, n ), : );\nr  = c';\nmn = min( r, c );\nmx = max( r, c );\ny  = mx + mn .* ( n - 0.5 * ( mn + 1 ) ) + 1;\ny  = sparse( y( : ), 1 : nsq, 1, ntr, nsq );\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/structures/cvx_s_symmetric.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5902366334612125}}
{"text": "function i4_log_10_test ( )\n\n%*****************************************************************************80\n%\n%% I4_LOG_10_TEST tests I4_LOG_10.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 13;\n\n  x = [ 0, 1, 2, 3, 9, 10, 11, 99, 101, -1, -2, -3, -9 ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'I4_LOG_10_TEST\\n' );\n  fprintf ( 1, '  I4_LOG_10: whole part of log base 10,\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  X, I4_LOG_10\\n' );\n  fprintf ( 1, '\\n' );\n\n  for i = 1 : n\n\n    fprintf ( 1, '%6d  %12d\\n', x(i), i4_log_10 ( x(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/i4lib/i4_log_10_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.5902291890657902}}
{"text": "function [colChar]=xlsColNum2Str(colNum)\n%XLSCOLNUM2STR takes in an array of numbers and returns a cellular array\n%of the same size with cell of corresponding Excel column names.\n%\n%For example:\n%n=[1  10;\n%   53 256]\n%c=xlsColNum2Str(n);\n%c={'A' , 'J';\n%   'BA', 'IV'}\n%Note: up to Excel 2003 the number of columns was limited to 256, as of\n%Excel 2007 the number of columns has increased to 16,384 or 'XFD'\n%This function is designed to take accept any integer so proper handling \n%of the number of columns should be taken care of outside this function\n\n    colChar=cell(size(colNum)); %blank cell array\n    \n    % find max number of characters (AA n=2)\n    numOfChars=ceil(max(colNum)/26)-1;\n    n=1;\n    \n    while numOfChars>=1\n        numOfChars=ceil(numOfChars/26)-1;\n        n=n+1;\n    end    \n    \n    remainder=num2cell(colNum);\n    \n    for s=n:-1:1\n        if s>1\n            %find limits\n            % if n=2 then the columns go from AA to ZZ or 27 to 702\n            L=sum(26.^(1:s-1))+1; % lower limit\n            U=sum(26.^(1:s));   %upper limit\n            %place current character to right of previous\n            colChar(colNum>=L & colNum<=U) = ...\n                cellfun(@(x,y) ([x char(ceil((y-(L-1))/26^(s-1))+64)]),...\n                colChar(colNum>=L & colNum<=U),...      % x\n                remainder(colNum>=L & colNum<=U),...    % y\n                'UniformOutput',false);\n            %calculate the remaining string\n            %for example if last string was 'ABA' the 'A' was placed to the\n            %right of the previous string and now 'BA' is remaining\n            remainder(colNum>=L & colNum<=U)=...\n                cellfun(@(x,y) (y-26^(s-1)*(double(x(end))-64)),...\n                colChar(colNum>=L & colNum<=U),...\n                remainder(colNum>=L & colNum<=U),'UniformOutput',false);\n            colNum=cell2mat(remainder);\n        else\n             colChar=cellfun(@(x,y) ([x char(y+64)]),...\n                 colChar,remainder,'UniformOutput',false);\n        end\n    end    \nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_Data_Extraction/xlsColNum2Str.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.5902291790566848}}
{"text": "function [disp_row, disp_col] = resp_newton(response, responsef, iterations, ky, kx, use_sz)\n\n[max_resp_row, max_row] = max(response, [], 1);\n[init_max_response, max_col] = max(max_resp_row, [], 2);\nmax_row_perm = permute(max_row, [2 3 1]);\ncol = max_col(:)';\nrow = max_row_perm(sub2ind(size(max_row_perm), col, 1:size(response,3)));\n\ntrans_row = mod(row - 1 + floor((use_sz(1)-1)/2), use_sz(1)) - floor((use_sz(1)-1)/2);\ntrans_col = mod(col - 1 + floor((use_sz(2)-1)/2), use_sz(2)) - floor((use_sz(2)-1)/2);\ninit_pos_y = permute(2*pi * trans_row / use_sz(1), [1 3 2]);\ninit_pos_x = permute(2*pi * trans_col / use_sz(2), [1 3 2]);\nmax_pos_y = init_pos_y;\nmax_pos_x = init_pos_x;\n\n% pre-compute complex exponential\nexp_iky = exp(bsxfun(@times, 1i * ky, max_pos_y));\nexp_ikx = exp(bsxfun(@times, 1i * kx, max_pos_x));\n\n% gradient_step_size = gradient_step_size / prod(use_sz);\n\nky2 = ky.*ky;\nkx2 = kx.*kx;\n\niter = 1;\nwhile iter <= iterations\n    % Compute gradient\n    ky_exp_ky = bsxfun(@times, ky, exp_iky);\n    kx_exp_kx = bsxfun(@times, kx, exp_ikx);\n    y_resp = mtimesx(exp_iky, responsef, 'speed');\n    resp_x = mtimesx(responsef, exp_ikx, 'speed');\n    grad_y = -imag(mtimesx(ky_exp_ky, resp_x, 'speed'));\n    grad_x = -imag(mtimesx(y_resp, kx_exp_kx, 'speed'));\n    ival = 1i * mtimesx(exp_iky, resp_x, 'speed');\n    H_yy = real(-mtimesx(bsxfun(@times, ky2, exp_iky), resp_x, 'speed') + ival);\n    H_xx = real(-mtimesx(y_resp, bsxfun(@times, kx2, exp_ikx), 'speed') + ival);\n    H_xy = real(-mtimesx(ky_exp_ky, mtimesx(responsef, kx_exp_kx, 'speed'), 'speed'));\n    det_H = H_yy .* H_xx - H_xy .* H_xy;\n    \n    % Compute new position using newtons method\n    max_pos_y = max_pos_y - (H_xx .* grad_y - H_xy .* grad_x) ./ det_H;\n    max_pos_x = max_pos_x - (H_yy .* grad_x - H_xy .* grad_y) ./ det_H;\n    \n    % Evaluate maximum\n    exp_iky = exp(bsxfun(@times, 1i * ky, max_pos_y));\n    exp_ikx = exp(bsxfun(@times, 1i * kx, max_pos_x));\n    \n    iter = iter + 1;\nend\nmax_response = 1 / prod(use_sz) * real(mtimesx(mtimesx(exp_iky, responsef, 'speed'), exp_ikx, 'speed'));\n\n% check for scales that have not increased in score\nind = max_response < init_max_response;\nmax_pos_y(ind) = init_pos_y(ind);\nmax_pos_x(ind) = init_pos_x(ind);\ndisp_row = (mod(max_pos_y(1,1,1) + pi, 2*pi) - pi) / (2*pi) * use_sz(1);\ndisp_col = (mod(max_pos_x(1,1,1) + pi, 2*pi) - pi) / (2*pi) * use_sz(2);\nend", "meta": {"author": "vision4robotics", "repo": "AutoTrack", "sha": "e9b34ae09702f152407a7bf7cce5e3ed75bf2797", "save_path": "github-repos/MATLAB/vision4robotics-AutoTrack", "path": "github-repos/MATLAB/vision4robotics-AutoTrack/AutoTrack-e9b34ae09702f152407a7bf7cce5e3ed75bf2797/utils/resp_newton.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278533, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5901807949504422}}
{"text": "function SieveAnalysis5(Granulometria)\n% _____________________________________________________\n% See Contents.m\n%  With this routine you can get the sand sieve analysis. Routine\n% displays the computation of the particle-size distribution in different\n% windows. Add you can get the main parameters of statistics analysis:\n% percentiles, mean, standard deviation, kurtosis, etc.\n% Syntax:\n%              >> Granulometria[ %your data];\n%              >> SieveAnalysis5(Granulometria)\n% Update: 1. I've received a couples of emails, in which  some\n%                people had a lot of problems with how to give the inputs;\n%                for this reason, I decided to delete the GUI. Now, the\n%                user only has to do, it's to create a variable with the\n%                name \"Granulometria\" and inside this variable, you need to\n%                write your data. First column, the sieve mesh (in mm) and\n%                the second, the weights (in g). For example:\n%                Granulometria = [4.0 0.88; 2.0 1.08; 1.0 1.49; 0.50 3.58; 0.25 11.50;\n%                                                0.125 21.50; 0.0625 9.81; 0.0313 2.70];\n%                2. I deleted an enormous bugs.\n%\n% Last modification : 03/21/09\n% Author: PhD(c) Gabriel Ruiz \n% This routine is provided \"as is\" without warranty of any kind. \n% Please, you don't attribute it.\n% If you'll detect any mistake or bug, may you communicate to me,\n% please?\n% v1.1.5\n% Copyright 2006.\n% _____________________________________________________\n     clc;\n    \n    screen = get(0, 'screensize');\n    if screen(1,3) == 1152 && screen(1,4) == 864\n                 screen(1,3) = screen(1,3) - 128; screen(1,4) = screen(1,4) - 96;\n        elseif screen(1,3) == 1280 && screen(1,4) == 768\n                 screen(1,3) = screen(1,3) - 256; \n        elseif screen(1,3) == 1280 && screen(1,4) == 800\n                 screen(1,3) = screen(1,3) - 256; screen(1,4) = screen(1,4) - 32;         \n        elseif screen(1,3) == 1280 && screen(1,4) == 960\n                 screen(1,3) = screen(1,3) - 256; screen(1,4) = screen(1,4) - 192;\n        elseif screen(1,3) == 1280 && screen(1,4) == 1024\n                 screen(1,3) = screen(1,3) - 256; screen(1,4) = screen(1,4) - 256; \n        elseif screen(1,3) == 1400 && screen(1,4) == 1050\n                 screen(1,3) = screen(1,3) - 376; screen(1,4) = screen(1,4) - 282;\n        elseif screen(1,3) == 1600 && screen(1,4) == 900\n                 screen(1,3) = screen(1,3) - 576; screen(1,4) = screen(1,4) - 132;\n        elseif screen(1,3) == 1600 && screen(1,4) == 1200        \n                 screen(1,3) = screen(1,3) - 576; screen(1,4) = screen(1,4) - 432;\n    end\n    vpan = screen(1,4)-35; hpan = screen(1,3);    \n    colores = [1 1 0.85 ]; colortexto = [0.50 0.25 0.25];\n    WB = Granulometria(:,2);\n    milimeters = Granulometria(:,1);\n    r = length(milimeters);  \n\n        for i = 1 : r \n                Worksheet_sieve_data{1,1}(i) = WB(i);\n        end\n        Sum_Col_1 = sum( Worksheet_sieve_data{1,1} );\n        for i = 1: r \n                Worksheet_sieve_data{1,2}(i) = ( Worksheet_sieve_data{1,1}(i) / Sum_Col_1) * 100;\n                if i == 1 \n                        Worksheet_sieve_data{1,3}(i) = Worksheet_sieve_data{1,2}(i);\n                        Worksheet_sieve_data{1,4}(i) = 100;\n                else      \n                        Worksheet_sieve_data{1,3}(i) = Worksheet_sieve_data{1,2}(i) + Worksheet_sieve_data{1,3}(i-1);\n                        Worksheet_sieve_data{1,4}(i) = Worksheet_sieve_data{1,4}(1) - Worksheet_sieve_data{1,3}(i);\n                end\n        end\n\n        diamX = Worksheet_sieve_data{1,4} ;\n        diamX = diamX';\n        diamY = milimeters;\n        D_5 = interp1(diamX, diamY, 5, 'pchip');\n        D_10 = interp1(diamX, diamY, 10, 'pchip');\n        D_16 = interp1(diamX, diamY, 16, 'pchip');\n        D_25 = interp1(diamX, diamY, 25, 'pchip');\n        D_30 = interp1(diamX, diamY, 30, 'pchip');\n        D_50 = interp1(diamX, diamY, 50, 'pchip');  \n        D_60 = interp1(diamX, diamY, 60, 'pchip');\n        D_75 = interp1(diamX, diamY, 75, 'pchip');\n        D_84 = interp1(diamX, diamY, 84, 'pchip');\n        D_95 = interp1(diamX, diamY, 95, 'pchip');\n\n        resulchar.d_5 = num2str(D_5); \n        resulchar.d_10 = num2str(D_10); \n        resulchar.d_16 = num2str(D_16);\n        resulchar.d_25 = num2str(D_25); \n        resulchar.d_30 = num2str(D_30); \n        resulchar.d_50 = num2str(D_50);\n        resulchar.d_60 = num2str(D_60); \n        resulchar.d_75 = num2str(D_75); \n        resulchar.d_84 = num2str(D_84);\n        resulchar.d_95 = num2str(D_95); \n\n        D_5phi = -log(D_5) / log(2);      %Matlab has the function log2, but I prefer to use this form.\n        D_10phi = -log(D_10) / log(2);\n        D_16phi = -log(D_16) / log(2);\n        D_25phi = -log(D_25) / log(2);\n        D_30phi = -log(D_30) / log(2);\n        D_50phi = -log(D_50) / log(2);  \n        D_60phi = -log(D_60) / log(2);\n        D_75phi = -log(D_75) / log(2);\n        D_84phi = -log(D_84) / log(2);\n        D_95phi = -log(D_95) / log(2);\n\n        Mean_grain_size = ( D_16phi + D_50phi + D_84phi ) / 3;      \n        Mean_grain_size_mm = 2 ^ -(Mean_grain_size);\n        resulchar.MeanGS = num2str(Mean_grain_size_mm);\n        \n        if Mean_grain_size_mm <= 0.075\n                    resulchar.ASTM = 'Fine Soil';\n            elseif Mean_grain_size_mm >= 0.076 && Mean_grain_size_mm <= 0.425\n                    resulchar.ASTM = 'Fine sand';\n            elseif Mean_grain_size_mm >= 0.426 && Mean_grain_size_mm <= 2\n                    resulchar.ASTM = 'Medium sand';            \n            elseif Mean_grain_size_mm >= 2.1 && Mean_grain_size_mm <= 4.75\n                    resulchar.ASTM = 'Coarse sand';   \n            elseif Mean_grain_size_mm >= 4.76 && Mean_grain_size_mm <= 19\n                    resulchar.ASTM = 'Fine gravel'; \n            elseif Mean_grain_size_mm >= 19.1 && Mean_grain_size_mm <= 75\n                    resulchar.ASTM = 'Coarse gravel';  \n        end\n\n        if Mean_grain_size_mm >= 0.0625 && Mean_grain_size_mm <= 0.125\n                    resulchar.Wentworth = 'Very fine sand';\n            elseif Mean_grain_size_mm >= 0.126 && Mean_grain_size_mm <= 0.250\n                    resulchar.Wentworth = 'Fine sand';\n            elseif Mean_grain_size_mm >= 0.251 && Mean_grain_size_mm <= 0.50\n                    resulchar.Wentworth = 'Medium sand';            \n            elseif Mean_grain_size_mm >= 0.51 && Mean_grain_size_mm <= 1\n                    resulchar.Wentworth = 'Coarse sand';   \n            elseif Mean_grain_size_mm >= 1.01 && Mean_grain_size_mm <= 2\n                    resulchar.Wentworth = 'Very coarse sand'; \n            elseif Mean_grain_size_mm >= 2.01 && Mean_grain_size_mm <= 4.76\n                    resulchar.Wentworth = 'Granule';  \n            elseif Mean_grain_size_mm >= 4.77 && Mean_grain_size_mm <= 8\n                    resulchar.Wentworth = 'Small pebble';             \n            elseif Mean_grain_size_mm >= 8.01 && Mean_grain_size_mm <= 16\n                    resulchar.Wentworth = 'Medium pebble'; \n            elseif Mean_grain_size_mm >= 16.01 && Mean_grain_size_mm <= 19.03\n                    resulchar.Wentworth = 'Large pebble'; \n        end\n        \n        gravel = zeros(r,1);\n        for i = 1 : r  \n            if milimeters(i,1) <= 75 && milimeters(i,1) >= 4.75\n                gravel(i,1) = Worksheet_sieve_data{1,2}(i);\n            end\n        end\n        Gravel = sum(gravel(:,1));\n        resulchar.Grava = num2str(Gravel);\n \n        sand = zeros(r,1);\n        for i = 1 : r  \n            if milimeters(i,1) <= 4.74 && milimeters(i,1) >= 0.075\n                    sand(i,1) = Worksheet_sieve_data{1,2}(i);\n            end\n        end\n        Sand = sum(sand(:,1));\n        resulchar.arena = num2str(Sand);\n\n         fine = zeros(r,1);  \n        for i = 1 : r  \n            if milimeters(i,1) <= 0.074\n                    fine(i,1) = Worksheet_sieve_data{1,2}(i);\n            end\n        end\n        Fine = sum(fine(:,1));\n        resulchar.fino =num2str(Fine);\n        Muestrapor = [ Gravel Sand Fine ];\n\n        Standard_Deviation = ( ( D_84phi - D_16phi ) / 4 ) + ( ( D_95phi - D_5phi ) / 6 );   % E.3.\n        Standard_Deviation_mm = 2 ^ -(Standard_Deviation);\n        resulchar.SDe = num2str(Standard_Deviation_mm);\n        if Standard_Deviation < 0.34\n                    resulchar.SD = 'Very well sorted';\n            elseif Standard_Deviation >= 0.35 && Standard_Deviation <= 0.49\n                    resulchar.SD = 'Well sorted';\n            elseif Standard_Deviation >= 0.50 && Standard_Deviation <= 0.71\n                    resulchar.SD = 'Moderately well sorted';\n            elseif Standard_Deviation >= 0.72 && Standard_Deviation <= 0.99\n                    resulchar.SD = 'Moderately sorted';\n            elseif Standard_Deviation >= 1.00 && Standard_Deviation <= 1.99\n                    resulchar.SD = 'Poorly sorted';\n            elseif Standard_Deviation >= 2.00 && Standard_Deviation <= 3.99\n                    resulchar.SD = 'Very poorly sorted';\n            elseif Standard_Deviation >= 4.00 \n                    resulchar.SD = 'Extremely poorly sorted';\n        end\n        \n        Skewness =  ( ( D_84phi + D_16phi - ( 2 * D_50phi ) ) / ( 2 * ( D_84phi - D_16phi ) ) ) + ...     \n                              ( ( D_95phi + D_5phi - ( 2 * D_50phi ) ) / ( 2 * ( D_95phi - D_5phi ) ) );\n        Skewness_mm = 2 ^ -(Skewness);\n        resulchar.S_ke = num2str(Skewness_mm);\n        if Skewness < -0.29\n                    resulchar.Sk = 'Very coarse skewed';\n            elseif Skewness >= -0.30 && Skewness <= -0.09\n                    resulchar.Sk = 'Coarse skewed';\n            elseif Skewness >= -0.10 && Skewness <= 0.09\n                    resulchar.Sk = 'Near symmetrical';\n            elseif Skewness >= 0.10 && Skewness <= 0.29\n                    resulchar.Sk = 'Fine skewed';\n            elseif Skewness >= 0.30 \n                    resulchar.Sk = 'Very fine skewed';\n        end\n    \n        Kurtosis = ( D_95phi - D_5phi ) / ( 2.44 * ( D_75phi - D_25phi ) );     \n        Kurtosis_mm = 2 ^ -(Kurtosis);\n        resulchar.K_ur = num2str(Kurtosis_mm);\n         if Kurtosis < 0.64\n                    resulchar.kurt = 'Very platykurtic (flat)';\n            elseif Kurtosis >= 0.65 && Kurtosis <= 0.89\n                    resulchar.kurt = 'Platykurtic';\n            elseif Kurtosis >= 0.90 && Kurtosis <= 1.10\n                    resulchar.kurt = 'Mesokurtic ';\n            elseif Kurtosis >= 1.11 && Kurtosis <= 1.49\n                    resulchar.kurt = 'Leptokurtic (peaked)';\n            elseif Kurtosis >= 1.50 && Kurtosis <= 2.99\n                    resulchar.kurt = 'Very leptokurtic';\n            elseif Kurtosis >= 3.00 \n                    resulchar.kurt = 'Extremely leptokurtic';\n        end\n        \n        Cc_Dispersal = D_30 ^ 2 / ( D_10 * D_60 ) ;\n        resulchar.CC = num2str(Cc_Dispersal);\n        Cu_Hazen_uniformity = D_60 / D_10;\n        resulchar.Cu =num2str(Cu_Hazen_uniformity);\n        if Cu_Hazen_uniformity >= 6 && ( ( Cc_Dispersal >= 1 ) && ( Cc_Dispersal <= 3 ) )\n                    resulchar.SUCS = 'SW';\n        else\n                    resulchar.SUCS = 'SP';\n        end\n        \n        figure(3);\n        set(figure(3), 'Units' , 'Pixels' , 'NumberTitle' , 'Off' , 'Resize' , 'on' , ...\n                'Name' , '1.Sieve Analysis - Histogram' , 'Color' , [0.93 0.91 0.85] , ...\n                'Position' , [  hpan-880   vpan-440   hpan-664   vpan-464 ] );    \n        histo_h =bar(milimeters,Worksheet_sieve_data{1,2}, 'group');\n        colormap hsv;\n        xlabel('Grain Size in mm' , 'Fontsize' , 7); \n        ylabel('Percent Finer by Weight (%)' , 'Fontsize' , 7);\n        title('Histogram' , 'Color' , 'r' , 'FontWeight' , 'Bold' , 'Fontsize' , 8);\n        set(histo_h,  'FaceColor', 'r');\n        set(gca,  'Xgrid' , 'on' , 'Ygrid' , 'on' , 'Xcolor' , [0 0 0.37] , 'Ycolor' , [0 0 0.37] , 'Box' , 'off' , ...\n                   'FontWeight' , 'Bold' , 'FontSize' , 7 , 'FontAngle' , 'Oblique' , 'XMinorTick' , 'on' , 'YMinorTick' , 'on');\n          \n        figure(4);\n        set(figure(4), 'Units' , 'Pixels' , 'NumberTitle' , 'Off' , 'Resize' , 'on' , 'Color' , [0.93 0.91 0.85] , ...\n                'Position' , [  hpan-859   vpan-469  hpan-664  vpan-464 ] , ... \n                'name' , '2.Sieve Analysis - Frecuency Curve' );  \n        FCruve_h = plot(milimeters, Worksheet_sieve_data{1,2}, '-', 'Color' , 'b' , 'Linewidth' , 1.5);\n        xlabel('Grain Size in mm' , 'Fontsize' , 7); \n        ylabel('Percent Finer by Weight (%)' , 'Fontsize' , 7);\n        title('Frecuency Curve' , 'Color' , 'b' , 'FontWeight' , 'Bold' , 'Fontsize' , 8);\n        set(gca,  'Xgrid' , 'on' , 'Ygrid' , 'on' , 'Xcolor' , [0 0 0.37] , 'Ycolor' , [0 0 0.37] , 'Box' , 'off' , ...\n                   'FontWeight' , 'Bold' , 'FontSize' , 7 , 'FontAngle' , 'Oblique' , 'XMinorTick' , 'on' , 'YMinorTick' , 'on');\n\n        figure(5);\n        set(figure(5), 'Units' , 'Pixels' , 'NumberTitle' , 'Off' , 'Resize' , 'on' , 'Color' , [0.93 0.91 0.85] , ...\n                'Position' , [hpan-838  vpan-499  hpan-664  vpan-464] , ...\n                'name' , '3. Sieve Analysis - Cumulative Arithmetic Curve' );  \n        ACurve_h = plot(milimeters, Worksheet_sieve_data{1,3}, '-', 'Color' , [0 0.5 0] , 'Linewidth' , 1.5);\n        xlabel('Grain Size in mm' , 'Fontsize' , 7); \n        ylabel('Percent Finer by Weight (%)' , 'Fontsize' , 7);\n        title('Frecuency Cumulative  Curve' , 'Color' , [0 0.5 0] , 'FontWeight' , 'Bold' , 'Fontsize' , 8);\n        set(gca,  'Xgrid' , 'on' , 'Ygrid' , 'on' , 'Xcolor' , [0 0 0.37] , 'Ycolor' , [0 0 0.37] , 'Box' , 'off' , ...\n                   'FontWeight' , 'Bold' , 'FontSize' , 7 , 'FontAngle' , 'Oblique' , 'XMinorTick' , 'on' , 'YMinorTick' , 'on');\n\n        figure(6);\n        set(figure(6), 'Units' , 'Pixels' , 'NumberTitle' , 'Off' , 'Resize' , 'on' , 'Color' , [0.93 0.91 0.85] , ...\n                'Position' , [ hpan-816   vpan-529   hpan-664  vpan-464] , ...\n                'name' , '4. Sieve Analysis - Cumulative Probability Arithmetic Curve' );   \n        CCurve_h = plot(milimeters, Worksheet_sieve_data{1,4}, '-','Color' , [1 0.5 0] , 'Linewidth' , 1.5);\n        xlabel('Grain Size in mm', 'Fontsize' , 7); \n        ylabel('Probability Finer by Weight (%)' , 'Fontsize' , 7);\n        title('Cumulative Probability Curve ' , 'Color' , [1 0.5 0] , 'FontWeight' , 'Bold' , 'Fontsize' , 8);\n        set(gca,  'Xgrid' , 'on' , 'Ygrid' , 'on' , 'Xcolor' , [0 0 0.37] , 'Ycolor' , [0 0 0.37] , 'Box' , 'off' , ...\n                   'FontWeight' , 'Bold' , 'FontSize' , 7 , 'FontAngle' , 'Oblique' , 'XMinorTick' , 'on' , 'YMinorTick' , 'on');\n\n        figure(7);\n        set(figure(7), 'Units' , 'Pixels' , 'NumberTitle' , 'Off' , 'Resize' , 'on' , 'Color' , [0.93 0.91 0.85] , ...\n                'Position' , [   hpan-778   vpan-587    hpan-348    vpan-464  ] , ... \n                 'name' , '6. Sieve Analysis - Cumulative Probability Semi-Log Curve'  );  \n        CCurvesl_h = semilogx(milimeters, Worksheet_sieve_data{1,4}, '-o','Color' , [0 0 0.5] , ...\n                                      'Linewidth' , 2.5, 'MarkerFaceColor' , [ 0 0 0.5 ] , 'MarkerSize' , 2, ...\n                                      'MarkerEdgeColor' , [ 0 0.5 0.5] );\n        axis tight;\n        xlabel('Grain Size in mm', 'Fontsize' , 7); \n        ylabel('Probability Finer by Weight (%)' , 'Fontsize' , 7);\n        title('Cumulative Probability Curve ' , 'Color' , [0 0 0.5] , 'FontWeight' , 'Bold' , 'Fontsize' , 8);\n        set(gca,  'Xgrid' , 'on' , 'Ygrid' , 'on' , 'Xcolor' , [0 0 0.37] , 'Ycolor' , [0 0 0.37] , 'Box' , 'off' , 'XDir' , 'normal' , ...\n                   'FontWeight' , 'Bold' , 'FontSize' , 7 , 'FontAngle' , 'Oblique' , 'XMinorTick' , 'on' , 'YMinorTick' , 'on', ...\n                   'Xlim' , [0.01 10]  , 'XTickLabel', { '0.01' ; '0.1' ; '1' ;  '10' } ); \n        dimark = [0.074 4.76];\n        hold on;\n        escalY = get(gca,'YLim');\n        escalY = [ 0 escalY(1,2) ];\n        lenmark = length(dimark);\n        xmark = reshape([dimark;dimark;ones(1,lenmark)*nan;],lenmark*3,1);\n        ymark = repmat([escalY nan],1,lenmark);\n        plot(xmark,ymark, 'r', 'LineWidth', 2 );\n        punto07 = patch(D_50 , 50 , [1 0 0] );\n        punto08 = patch(0.01, 50 ,  [1 0 0] ); \n        punto09 = patch(D_50 , 0.01 , [1 0 0]); \n         l4 = line('Xdata' , [D_50 D_50] , 'Ydata' , [0 50] , 'Color' ,  [0.75 0.75 0.75] , ...\n                        'Linestyle' , '-' , 'Linewidth' , 2 ) ;\n         l5 = line('Xdata' , [0.01 D_50] , 'Ydata' , [50 50] , 'Color' ,  [0.75 0.75 0.75] , ...\n                        'Linestyle' , '-' , 'Linewidth' , 2 );\n        set(punto07, 'marker' , 'o' , 'MarkerEdgeColor', 'r' , 'MarkerFaceColor', 'r' , ...\n                 'MarkerSize' , 2);\n        set(punto08, 'marker' , 'o' , 'MarkerEdgeColor', 'r' , 'MarkerFaceColor', 'r' , ...\n                 'MarkerSize' , 2);\n        set(punto09, 'marker' , 'o' , 'MarkerEdgeColor', 'r' , 'MarkerFaceColor', 'r', ...\n                 'MarkerSize' , 2);\n        td50 = text(D_50+.005 , 3, num2str(D_50)); set(td50, 'FontSize' , 8 , ...\n                            'FontAngle' , 'Normal' , 'FontWeight' , 'Bold' );\n        tfinos = text(0.011 , 95, 'Fine'); set(tfinos, 'FontSize' , 8 , 'FontWeight' , 'Bold');\n        tsand = text(0.085 , 95, 'Sand'); set(tsand, 'FontSize' , 8 , 'FontWeight' , 'Bold' );\n        tgrav = text(5 , 95, 'Gravel'); set(tgrav, 'FontSize' , 8 , 'FontWeight' , 'Bold' );\n              \n        figure(8);\n        set(figure(8), 'Units' , 'Pixels' , 'NumberTitle' , 'Off' , 'Resize' , 'on' , 'Color' , [0.93 0.91 0.85] , ...\n                'Position' , [   hpan-796   vpan-558    hpan-664  vpan-464  ] , ... \n                'name' , '5. Sieve Analysis - Cumulative Probability Logarithmic Curve' );   \n        CCurvel_h = loglog(milimeters, Worksheet_sieve_data{1,4}, '-','Color' , [0.5 0 0.5] , 'Linewidth' , 1.5);\n        xlabel('Grain Size in mm' ,'Fontsize' , 7); \n        ylabel('Probability Finer by Weight (%)', 'Fontsize' , 7);\n        title('Cumulative Probability Curve ' , 'Color' , [0.5 0 0.5] , 'FontWeight' , 'Bold' , 'Fontsize' , 8);\n        set(gca,  'Xgrid' , 'on' , 'Ygrid' , 'on' , 'Xcolor' , [0 0 0.37] , 'Ycolor' , [0 0 0.37] , 'Box' , 'off' , ...\n                   'FontWeight' , 'Bold' , 'FontSize' , 7 , 'FontAngle' , 'Oblique' , 'XMinorTick' , 'on' , 'YMinorTick' , 'on'); clc;\n     \n        figure(9);\n        set(figure(9), 'Units' , 'Pixels' , 'NumberTitle' , 'Off' , 'Resize' , 'on' , 'Color' , [0.93 0.91 0.85] , ...\n                'Position' , [  hpan-757   vpan-616    hpan-664  vpan-464  ] , ... \n                'name' , '7. Sieve Analysis - % Percent of Sand'  );\n        if Muestrapor(1,1) == 0 && Muestrapor(1,2) ~= 0 && Muestrapor(1,3) ~= 0\n                    hotcake(1,1) =Muestrapor(1,2); \n                    hotcake(1,2) =Muestrapor(1,3); \n                    explode = [ 0 1 ];\n                    piecg = pie(hotcake, explode); \n                    hdlleg = legend('Sand', 'Fine', -1); \n                    set(piecg(1,2), 'FontUnits', 'pixels', 'FontSize' , 10);\n                    set(piecg(1,4), 'FontUnits', 'pixels', 'FontSize' , 10);\n         elseif Muestrapor(1,1) ~= 0 && Muestrapor(1,2) ~= 0 && Muestrapor(1,3) == 0\n                    hotcake(1,1) =Muestrapor(1,1); \n                    hotcake(1,2) =Muestrapor(1,2); \n                    explode = [ 0 1 ];\n                    piecg = pie(hotcake, explode); \n                    hdlleg = legend('Gravel' , 'Sand',  -1); \n                    set(piecg(1,2), 'FontUnits', 'pixels', 'FontSize' , 10);\n                    set(piecg(1,4), 'FontUnits', 'pixels', 'FontSize' , 10);\n        elseif Muestrapor(1,1) ~= 0 && Muestrapor(1,2) ~= 0 && Muestrapor(1,3) ~= 0\n                    explode = [ 0 1 0 ];\n                    piecg = pie(Muestrapor, explode);\n                    hdlleg = legend('Gravel' , 'Sand', 'Fine', -1);\n                    set(piecg(1,2), 'FontUnits', 'pixels', 'FontSize' , 10);\n                    set(piecg(1,4), 'FontUnits', 'pixels', 'FontSize' , 10);\n                    set(piecg(1,6), 'FontUnits', 'pixels', 'FontSize' , 10);\n        elseif Muestrapor(1,1) ~= 0 && Muestrapor(1,2) == 0 && Muestrapor(1,3) ~= 0\n                    hotcake(1,1) = Muestrapor(1,1); \n                    hotcake(1,2) = Muestrapor(1,3);\n                    explode = [ 0 1 ];\n                    piecg = pie(hotcake, explode); \n                    hdlleg = legend('Gravel' , 'Fine',  -1); \n                    set(piecg(1,2), 'FontUnits', 'pixels', 'FontSize' , 10);\n                    set(piecg(1,4), 'FontUnits', 'pixels', 'FontSize' , 10);\n        elseif Muestrapor(1,1) ~= 0 && Muestrapor(1,2) == 0 && Muestrapor(1,3) == 0\n                    hotcake = Muestrapor(1,1) ;\n                    piecg = pie(hotcake); \n                    hdlleg = legend('Gravel' , -1); \n                    set(piecg(1,2), 'FontUnits', 'pixels', 'FontSize' , 10);\n        elseif Muestrapor(1,1) == 0 && Muestrapor(1,2) ~= 0  && Muestrapor(1,3) == 0\n                    hotcake = Muestrapor(1,2) ;\n                    piecg = pie(hotcake); \n                    hdlleg = legend('Sand' , -1); \n                    set(piecg(1,2), 'FontUnits', 'pixels', 'FontSize' , 10);\n         elseif Muestrapor(1,1) == 0 && Muestrapor(1,2) == 0 && Muestrapor(1,3) ~= 0\n                    hotcake = Muestrapor(1,3) ;\n                    piecg = pie(hotcake); \n                    hdlleg = legend('Fine' , -1);  \n                    set(piecg(1,2), 'FontUnits', 'pixels', 'FontSize' , 10);\n        end\n        set(hdlleg, 'Color' , [ 0.93 0.91 0.85 ], 'Box', 'on'); clc;\n        \n        result = figure(11);\n        set(result, 'Units' , 'Pixels' , 'NumberTitle' , 'Off' , 'Resize' , 'on' , 'Color' , [0.93 0.91 0.85] , ...\n                'Position' , [   10+hpan/3+hpan-686  35   hpan-690 (vpan/3)*2-50] , ...\n                'name' , '8. Sieve Analysis - Results' ); \n         P4 = 12;                \n        uicontrol(result, 'Style' , 'Text' , 'String', 'The main results of sieve analysis were:' , 'Unit' , 'Pixels' , 'Position' , [0 418 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left' );\n        uicontrol(result, 'Style' , 'Text' , 'String', ['D_5 (mm) = ' , resulchar.d_5  ] , 'Unit' , 'Pixels' , 'Position' , [0 405 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left');                               \n        uicontrol(result, 'Style' , 'Text' , 'String', ['D_10 (mm) = ' , resulchar.d_10  ] , 'Unit' , 'Pixels' , 'Position' , [0 392 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left');   \n        uicontrol(result, 'Style' , 'Text' , 'String', ['D_16 (mm) = ' , resulchar.d_16  ] , 'Unit' , 'Pixels' , 'Position' , [0 379 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left');   \n        uicontrol(result, 'Style' , 'Text' , 'String', ['D_30 (mm) = ' , resulchar.d_30  ] , 'Unit' , 'Pixels' , 'Position' , [0 366 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left');                               \n        uicontrol(result, 'Style' , 'Text' , 'String', ['D_50 (mm) = ' , resulchar.d_50  ] , 'Unit' , 'Pixels' , 'Position' , [0 353 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'ForegroundColor' , [0.5 0 0 ] , 'HorizontalAlignment', 'left');   \n        uicontrol(result, 'Style' , 'Text' , 'String', ['D_60 (mm) = ' , resulchar.d_60  ] , 'Unit' , 'Pixels' , 'Position' , [0 340 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left'); \n        uicontrol(result, 'Style' , 'Text' , 'String', ['D_75 (mm) = ' , resulchar.d_75  ] , 'Unit' , 'Pixels' , 'Position' , [0 327 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left');                               \n        uicontrol(result, 'Style' , 'Text' , 'String', ['D_84 (mm) = ' , resulchar.d_84  ] , 'Unit' , 'Pixels' , 'Position' , [0 314 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85], 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left');   \n        uicontrol(result, 'Style' , 'Text' , 'String', ['D_95 (mm) = ' , resulchar.d_95  ] , 'Unit' , 'Pixels' , 'Position' , [0 301 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left'); \n        uicontrol(result, 'Style' , 'Text' , 'String', ['Mean Grain Size  (mm) = ' , resulchar.MeanGS  ] , 'Unit' , 'Pixels' , 'Position' , [0 288 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'ForegroundColor' , [0.5 0 0 ] , 'HorizontalAlignment', 'left');   \n        uicontrol(result, 'Style' , 'Text' , 'String', ['Standard Deviation ' , resulchar.SDe  ] , 'Unit' , 'Pixels' , 'Position' , [0 273 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left'); \n        uicontrol(result, 'Style' , 'Text' , 'String', ['Skewness = ' , resulchar.S_ke  ] , 'Unit' , 'Pixels' , 'Position' , [0 260 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left');                               \n        uicontrol(result, 'Style' , 'Text' , 'String', ['Kurtosis = ' , resulchar.K_ur  ] , 'Unit' , 'Pixels' , 'Position' , [0 247 200 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left');   \n        uicontrol(result, 'Style' , 'Text' , 'String', ['Coeficient of uniformity (Cc) = ' , resulchar.CC  ] , 'Unit' , 'Pixels' , 'Position' , [0 236 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left'); \n        uicontrol(result, 'Style' , 'Text' , 'String', ['Coeficient of curvature (Cu) = ' , resulchar.Cu  ] , 'Unit' , 'Pixels' , 'Position' , [0 223 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left');              \n        uicontrol(result, 'Style' , 'Text' , 'String', ['Standard Deviation Classification = ' , resulchar.SD  ] , 'Unit' , 'Pixels' , 'Position' , [0 210 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left');   \n        uicontrol(result, 'Style' , 'Text' , 'String', ['Skewness Classification = ' , resulchar.Sk  ] , 'Unit' , 'Pixels' , 'Position' , [0 197 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left');  \n        uicontrol(result, 'Style' , 'Text' , 'String', ['Kurtosis Classification = ' , resulchar.kurt  ] , 'Unit' , 'Pixels' , 'Position' , [0 184 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'HorizontalAlignment', 'left'); \n        uicontrol(result, 'Style' , 'Text' , 'String', ['ASTM Classification = ' , resulchar.ASTM  ] , 'Unit' , 'Pixels' , 'Position' , [0 169 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'ForegroundColor' , [0.5 0 0 ] , 'HorizontalAlignment', 'left'); \n        uicontrol(result, 'Style' , 'Text' , 'String', ['% of Gravel = ' , resulchar.Grava  ] , 'Unit' , 'Pixels' , 'Position' , [0 158 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'ForegroundColor' , [0.5 0 0 ] , 'HorizontalAlignment', 'left');  \n        uicontrol(result, 'Style' , 'Text' , 'String', ['% of Sand = ' , resulchar.arena  ] , 'Unit' , 'Pixels' , 'Position' , [0 145 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'ForegroundColor' , [0.5 0 0 ] , 'HorizontalAlignment', 'left');              \n        uicontrol(result, 'Style' , 'Text' , 'String', ['% of Fine = ' , resulchar.fino  ] , 'Unit' , 'Pixels' , 'Position' , [0 132 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'ForegroundColor' , [0.5 0 0 ] , 'HorizontalAlignment', 'left');                 \n        uicontrol(result, 'Style' , 'Text' , 'String', ['Wentworth classification = ' , resulchar.Wentworth  ] , 'Unit' , 'Pixels' , 'Position' , [0 117 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'ForegroundColor' , [0.5 0 0 ] , 'HorizontalAlignment', 'left');\n        uicontrol(result, 'Style' , 'Text' , 'String', ['USCS classification = ' , resulchar.SUCS  ] , 'Unit' , 'Pixels' , 'Position' , [0 103 300 P4] , ...\n                                   'BackGroundColor' , [0.93 0.91 0.85] , 'FontWeight' , 'Bold', 'ForegroundColor' , [0.5 0 0 ] , 'HorizontalAlignment', 'left');\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8158-sand-sieve-analysis/SieveAnalysis5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5901502421935589}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\nfunction [lower, upper] = UpperBound3(S, g, df, B, f, Nr, NSim, NSSim, ...\n    getpaths, payoff)\n% method from Broadie for computing upper bounds, see Chapter 8\n\niVec = 1:NSSim;\n\nv = g(:,end);   % start for backward induction\nc = zeros(NSim,Nr-1);   % continuation value\n\n% backward induction and regression from t_{Nr-1} up to t_1\nfor i = Nr-1:-1:1\n        index = find(g(:,i) > 0); % all ITM paths\n        s = S(index,i+1);         % values of S at given time point \n        v = v * df(i+1);          % option value at t_i\n\n        Acell = B(s);             % evaluate basis function in cell array B \n        A = cell2mat(Acell{:,:}); % convert to matrix\n    \n        c(index,i) = A*f(:,i);                  % continuation value\n\n        exercise = g(index,i) >= c(index,i);    % early exercise\n        v(index(exercise)) = g(index(exercise),i);\nend\n\nlower = mean(v * df(1));    % final option value\n\n% Computing the martingale numerically, martingale = pi\n\nL = zeros(NSim,1); %erster Teil von delta_i vgl. Formel (6.6)\nexpectation = zeros(NSim,Nr); %zweiter Teil von delta_i vgl. Formel (6.6)\nexpectation(:,1) = lower * ones(NSim,1);\n\nfor i=1:1:Nr-1\n    for j=1:NSim\n        expectation(j,i+1) = subsimulation(S(j,i+1), df, B, NSSim, Nr-i,...\n            f(:,i:end), iVec(1:NSSim), getpaths, payoff) * prod(df(1:i));\n    end      \nend\n\npi = zeros(NSim,Nr+1); % stores the values of the constructed martingale\n\n% first time step and last are different\ni_exercise = g(:,1) >= c(:,1) & c(:,1) > 0; % exercise in this case\n    \nL(i_exercise) = g(i_exercise, 1) * prod(df(1:1));\nL(~i_exercise) = expectation(~i_exercise,2);\n    \npi(:,2) = pi(:,1) + L - expectation(:,1);\n\nfor i=2:1:Nr-1\n    % exercise in this case if not already exercised\n    i_exercise = g(:,i) >= c(:,i) & c(:,i) > 0 & ~i_exercise; \n    \n    L(i_exercise) = g(i_exercise, i) * prod(df(1:i));\n    L(~i_exercise) = expectation(~i_exercise,i+1);\n    \n    pi(:,i+1) = pi(:,i) + L - expectation(:,i);\nend\n% finally exercise if in the money and not already exercised\ni_exercise = g(:,Nr) > 0 & ~i_exercise; \n\npi(i_exercise,Nr+1) = pi(i_exercise,Nr) + g(i_exercise,Nr)* prod(df(1:Nr));\npi(~i_exercise,Nr+1) = pi(~i_exercise,Nr);\n\n\n% upper bound using the martingale pi\n\nmaximum = zeros(NSim,1);\n\nfor j=1:1:NSim\n    maximum(j) = max(g(j,:) - pi(j,2:end)); %vgl. Formel (6.5)\nend\nupper = mean(maximum);\n\nend \n\nfunction y = subsimulation(S0, df, B, NSim, Nr, beta, iVec, gp,payoff)\n    S2 = gp(S0,NSim,Nr); S2 = S2(:,2:end);   % paths\n    g2 = payoff(S2);                         % payoff\n \n    exercise = Nr * ones(NSim,1);            % exercise per path\n    for i=1:1:Nr-1  \n        i_nexercised = exercise == Nr;\n        I_nexercise = iVec(i_nexercised);\n    \n        s = S2(i_nexercised,i);\n        Acell = B(s);\n        A = cell2mat(Acell{:,:});\n        c = A * beta(:,i);\n                \n        i_exercise = g2(i_nexercised,i) >= c & g2(i_nexercised,i) > 0;\n        exercise(I_nexercise(i_exercise)) = i;    \n    end\n    summe=0;\n    for j=1:1:NSim\n        summe = summe + g2(j,exercise(j)) * prod(df(1:exercise(j)));\n    end\n    y = summe / NSim;                         % MC value from subsimulation\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/37620-american-monte-carlo/AmericanMC/UpperBound3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.5901502368461206}}
{"text": "% NTF | NTD-HALS | Non-negative Tucker Decomposition solved by Hierarchical ALS  (Zhou et al. 2012)\n% process_video('NTF', 'NTD-HALS', 'dataset/demo.avi', 'output/demo_NTD-HALS.avi');\n\nalg_path_aux = fullfile(lrs_conf.ntf_path,'lraNTD');\naddpath(genpath(alg_path_aux));\n\nR = [size(T,1) size(T,2) 2];\nopts = struct('NumOfComp',R,'nlssolver','hals','maxiter',100,...\n  'maxiniter',20,'tdalgFile','call_tucker_als_opts.mat');\n\nT_hat = lraNTD_ANLS(T, opts);\n\nL = double(tensor(T_hat));\nS = double(T) - L;\n\nrmpath(genpath(alg_path_aux));\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/ntf/NTD-HALS/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.5901502261504417}}
{"text": "function anal = er_wtaClassifier(amps1,amps2,subtractDC,plotFlag,names);\n%\n% anal = er_wtaClassifier(amps1,amps2,[plotFlag],[names]);\n%\n% Apply a winner-take-all classifier to event-related\n% data.\n%\n% [more description forthcoming]\n%\n% Input args: amps1 and amps2 should be of shape voxels x conditions:\n% each column represents the pattern of response across voxels to a \n% given condition. (See mv_reliability for an example of how \n% to compute these.) \n%\n% plotFlag: 1 x 3 vector to flag each of the following\n% possible output plots:\n%   1) image the amplitudes for each subset\n%   2) summarize the reliability analysis\n%   3) 'omnibus' contrast: regress mean response, across conditions,\n%   from each subset\n%\n% subtractDC: option to subtract the baseline response\n% across conditions for \n% \n% ras 05/05. Based on exp5_haxby, by ras 03/05.\nif ieNotDefined('subtractDc')\n    subtractDC = 0;\nelse \n    subtractDC\nend\n\nif ieNotDefined('plotFlag')\n    plotFlag = [0 0 0];\nelse \n    plotFlag\nend\n\nif ieNotDefined('names')\n    for i = 1:size(amps1,2)\n        names{i} = num2str(i);\n    end\nend\n\nif size(amps1) ~= size(amps2)\n    error('amps1 and amps2 must be same size.')\nend\n\nnVoxels = size(amps1,1);\nnConds = size(amps1,2);\nfont = 'Arial';\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% omnibus test                    %\n% (always do this before zeroing, %\n% or you remove the effect)       %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nmu1 = mean(amps1,2);\nmu2 = mean(amps2,2);\n% ignore zeroed voxels\nnotzeroed = find(mu1~=0 & mu2~=0);\nmu1 = mu1(notzeroed);\nmu2 = mu2(notzeroed);\n[R P] = corrcoef(mu1(:),mu2(:));\nanal.omnibusR = R(1,2);\nanal.omnibusP = P(1,2);\nanal.mu1 = mu1;\nanal.mu2 = mu2;\n\n\nif subtractDC==1\n\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t% Normalize responses, in a manner similar   %\n\t% to Haxby et al 2001 -- subtract mean       %\n\t% response across conditions from each voxel %\n\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\tbsl1 = repmat(mean(amps1,2),1,size(amps1,2));\n\tusedAmps1 = amps1 - bsl1;\n\tbsl2 = repmat(mean(amps2,2),1,size(amps2,2));\n\tusedAmps2 = amps2 - bsl2;\nelse\n    % use the non-corrected amps\n    usedAmps1 = amps1;\n    usedAmps2 = amps2;\nend\n\n% assign amplitude fields to anal struct\nanal.amps1 = amps1;\nanal.amps2 = amps2;\nanal.usedAmps1 = usedAmps1;\nanal.usedAmps2 = usedAmps2;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% perform pairwise correlations between maps %\n% in the first and second data sets          %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfor i = 1:nConds \n    for j = 1:nConds \n        training = usedAmps1(:,i);\n        test = usedAmps2(:,j);\n        \n        % remove NaNs\n        ok = ~isnan(training) & ~isnan(test);\n        if sum(ok)==0\n            error('Too many NaNs in amplitudes.');\n        end\n        training = training(ok); test = test(ok);\n        \n        [R p] = corrcoef(training,test);\n        anal.corrRvals(i,j) = R(1,2);\n        anal.corrPvals(i,j) = p(1,2);        \n    end\nend\n\n% % 02/22/05: kalanit suggested thresholding\n% % the R vals, based on the p -- let's try it:\n% anal.corrRvals(anal.corrPvals>0.05) = 0;\n\n% as an ideal observer of activity patterns,\n% 'guess' the image shown in the 2nd data set\n% by looking at what provoked the most similar\n% (by correlation) response from the 1st data set\nfor i = 1:nConds \n    anal.guess(i,:) = zeros(1,nConds);\n    guess = find(anal.corrRvals(i,:)==max(anal.corrRvals(i,:)));\n    anal.guess(i,guess) = 1;\n    \n    % guesses along the diagonal are correct -- the\n    % highest-correlated pattern comes from the same image.\n    % other guesses are mistakes.\n    if isempty(guess), guess = 0; end\n    anal.correct(i) = (guess(1)==i);\nend\nanal.pctCorrect = 100 * sum(anal.correct)/length(anal.correct);\n\n% let's also compute the 'voxel reliability',the \n% correlation value for each voxel of the set of nConds\n% response amplitudes between the two subsets:\nfor v = 1:nVoxels\n    [R p] = corrcoef(anal.amps1(v,:),anal.amps2(v,:));\n    voxR(v) = R(1,2);\nend\nanal.voxR = voxR;\n\n% calculate mean correlations for same image,\n% diff image but same cat, diff cat:\nnImgs = nConds; %length(1:nConds);\ngroup = 3*ones(nImgs,nImgs); % diff cat \nfor i = 1:nImgs\n    for j = 1:nImgs\n        if ceil(j/4)==ceil(i/4)\n            group(i,j) = 2; % same cat\n        end\n    end\n    group(i,i) = 1;  % same img\nend\n\nanal.group = group;\nanal.meanR = [];\nanal.semR = [];\nfor j = 1:3\n    anal.meanR(j) = mean(anal.corrRvals(group==j));\n    nObs = sum(group(:)==j);\n    anal.semR(j) = std(anal.corrRvals(group==j))/sqrt(nObs-1);\n    try\n        [H p] = ttest2(anal.corrRvals(group==j),anal.corrRvals(group==3));\n    catch\n        H = 0; p = 1;\n    end\n    anal.sigDiffR(j) = H;\n    anal.pvalR(j) = p;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%\n% plot the results  %\n%%%%%%%%%%%%%%%%%%%%%\n% Amplitude plots\nif plotFlag(1)==1\n\tanal.h1 = figure('Name','Amplitudes From Each Half of Data',...\n                    'Units','Normalized','Position',[.7 .8 .3 .18],...\n                    'MenuBar','none',...\n                    'Color','w'); % [0 .4 .7 .4]\n\tcolormap jet\n\n    minVal = min([min(anal.amps1(:)) min(anal.amps2(:))]);\n\tmaxVal = max([max(anal.amps1(:)) max(anal.amps2(:))]);\n\n    subplot('Position',[.1 .15 .35 .75])\n\timagesc(anal.amps1,[minVal maxVal]); \n\tset(gca,'XTick',1:nConds,'XTickLabel',names);\n\tylabel('Voxels');\n    title('Subset 1 (Training)')\n    set(gca,'FontName',font,'FontSize',10);\n\n    subplot('Position',[.5 .15 .35 .75])\n\timagesc(anal.amps2,[minVal maxVal]);\n\tset(gca,'XTick',1:nConds,'XTickLabel',names,'YTick',[]);\n\tylabel('Voxels');\n    title('Subset 2 (Test)');\n    set(gca,'FontName',font,'FontSize',10);\n\n\t\n    hcb = subplot('Position',[.9 .2 .03 .6]);\n    colorbar(hcb);\n    ylabel('Response Amplitude, % Signal');\n    set(gca,'FontName',font,'FontSize',10);\nend\n\n% reliability summary\nif plotFlag(2)==1\n\tanal.h2 = figure('Name','Reliability Amps Results',...\n                'Color','w','MenuBar','none','Units','Normalized',...\n                'Position',[.7 .6 .3 .18]); % [.1 .2 .7 .7]\n\tsubplot(2,2,1);\n\timagesc(anal.corrRvals); % colorbar;\n\tset(gca,'XTick',1:nConds,'XTickLabel',names,...\n            'YTick',1:nConds,'YTickLabel',names);\n\tset(gca,'FontName',font,'FontSize',10);\n\txlabel('First Half');\n\tylabel('Second Half');\n\ttitle('Correlation Coefficient R');\n\t\n    subplot(2,2,2);\n\timagesc(anal.guess); % colorbar;\n\tset(gca,'XTick',1:nConds,'XTickLabel',names,...\n            'YTick',1:nConds,'YTickLabel',names);\n\tset(gca,'FontName',font,'FontSize',10);\n\txlabel('First Half');\n\tylabel('Second Half');\n\ttitle('Ideal Observer Best Guess');\n\t\n    subplot(2,2,3);\n\tstarbar(anal.meanR,anal.semR,anal.sigDiffR);\n\tgrps = {'Same Image' 'Same Category' 'Different Category'};\n\tset(gca,'XTickLabel',grps);\n\tset(gca,'FontName',font,'FontSize',10);\n\tylabel('Mean R Value');\n\n    subplot(2,2,4);\n\ttable = {'Percent Correct:'; num2str(anal.pctCorrect)};\n\tplotTable(table);\nend\n\n% 'omnibus' test\nif plotFlag(3)==1\n\tanal.h3 = figure('Color','w','MenuBar','none','Units','Normalized',...\n                     'Position',[.7 .4 .2 .18]);\n\tregressPlot(mu1,mu2);\n\tset(gca,'FontName',font,'FontSize',10);\n\taxis equal\n\taxis square\n\txlabel('Amplitude, Odd Runs','FontName','Helvetica','FontSize',nConds);\n\tylabel('Amplitude, Even Runs','FontName','Helvetica','FontSize',nConds);\n\tttltxt = sprintf('Amplitudes Across All Images');\n\ttitle(ttltxt,'FontName','Helvetica','FontSize',14);\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/EventRelated/er_wtaClassifier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5901502261504415}}
{"text": "function x = rsc_encode(G,m,termination)\n% Copyright 1998, Yufei Wu, MPRG lab, Virginia Tech. for academic use\n% encodes a binary data block m (0/1) with a RSC (recursive systematic \n% convolutional) code defined by generator matrix G, returns the output \n% in x (0/1), terminates the trellis with all-0 state if termination>0\nif nargin<3, termination = 0; end\n[N,L] = size(G); % Number of output bits, Constraint length\nM = L-1; % Dimension of the state\nlu = length(m)+(termination>0)*M; % Length of the input\nlm = lu-M; % Length of the message\nstate = zeros(1,M); % initialize the state vector\n% To generate the codeword\nx = [];\nfor i = 1:lu\n   if termination<=0 | (termination>0 & i<=length(m))\n     d_k = m(i);\n    elseif termination>0 & i>lm\n     d_k = rem(G(1,2:L)*state.',2); \n   end\n   a_k = rem(G(1,:)*[d_k state].',2);\n   xp = rem(G(2,:)*[a_k state].',2); % 2nd output (parity) bits\n   state = [a_k state(1:M-1)]; % Next sttate\n   x = [x [d_k; xp]]; % since systematic, first output is input bit\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/34878-example-turbo-coding-with-free-distance-exit-code-and-presentation/doc/resources/rsc_encode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5901208678881541}}
{"text": "% test_mecv2_reconstruction.m -\n% image reconstruction using mirror-extended curvelets\n\nif(1)\n  N = 512;\n  H = N/2;\n  [a,b] = ndgrid(0:N-1);\n  x = a+b-N;\n  x = (x-min(min(x)))/max(max(x-min(min(x))));\n  ns = ceil(log2(N) - 3);\n  nag = 16; \n  ci = 128;\n  \n  c = mefcv2(x,N,N,ns,nag);\n  \n  cfs = [];\n  for s=1:length(c);    for w=1:length(c{s});      cfs = [cfs; abs(c{s}{w}(:))];    end;  end\n  cfs = sort(abs(cfs)); cfs = cfs(end:-1:1);\n  val = cfs(ci);\n  d = c;\n  cnt = 0;\n  for s=1:length(c)\n    for w=1:length(c{s})\n      cnt = cnt + sum(sum(abs(c{s}{w})>=val+eps));\n      d{s}{w} = c{s}{w}.*(abs(c{s}{w})>=val+eps);\n    end\n  end\n  fprintf(1, 'number of coefficients used = %d\\n', cnt);\n  y = meicv2(d,N,N,ns,nag);\n  figure;  imagesc(real(y)); axis equal; axis tight; colormap gray; colorbar;\n  title('Partial reconstruction with mirror-extended curvelets');\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_TRAFO/CurveLab-2.1.3/mecv/test_mecv2_reconstruction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5901075968054645}}
{"text": "function err = sb_test_ori(pnt,elem)\nerr = 1;\nif(size(elem,2) == 4)\n    det = sum(cross(pnt(elem(:,2),:)-pnt(elem(:,1),:),pnt(elem(:,4),:)-pnt(elem(:,1),:),2).*(pnt(elem(:,3),:)-pnt(elem(:,1),:)),2);\n    if sum(det <= 0) > 0\n        err = 0;\n    end\nelseif(size(elem,2) == 8)\n    det1 = sum(cross(pnt(elem(:,6),:)-pnt(elem(:,1),:),pnt(elem(:,8),:)-pnt(elem(:,1),:),2).*(pnt(elem(:,5),:)-pnt(elem(:,1),:)),2);\n    det2 = sum(cross(pnt(elem(:,3),:)-pnt(elem(:,1),:),pnt(elem(:,6),:)-pnt(elem(:,1),:),2).*(pnt(elem(:,2),:)-pnt(elem(:,1),:)),2);\n    det3 = sum(cross(pnt(elem(:,8),:)-pnt(elem(:,1),:),pnt(elem(:,3),:)-pnt(elem(:,1),:),2).*(pnt(elem(:,4),:)-pnt(elem(:,1),:)),2);\n    det4 = sum(cross(pnt(elem(:,8),:)-pnt(elem(:,3),:),pnt(elem(:,6),:)-pnt(elem(:,3),:),2).*(pnt(elem(:,7),:)-pnt(elem(:,3),:)),2);\n    if sum(det1 <= 0) || sum(det2 <= 0) || sum(det3 <= 0) || sum(det4 <= 0)\n        err = 0;\n    end\nelse\n    error('Invalid number of nodes per element!');\nend\nend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/simbio/sb_test_ori.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5901075926227809}}
{"text": "%+========================================================================+\n%|                                                                        |\n%|            This script uses 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    \u00a0\u00a0\u00a0\u00a0         |\n%|                                                                        |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it.                                                      |\n%|________________________________________________________________________|\n%|   '&`   |                                                              |\n%|    #    |   FILE       : nrtStkRadiation.m                             |\n%|    #    |   VERSION    : 0.50                                          |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |\n%|  ( # )  |   CREATION   : 31.10.2018                                    |\n%|  / 0 \\  |   LAST MODIF : 25.11.2018                                    |\n%| ( === ) |   SYNOPSIS   : Stoke radiation of a unit sphere using BEM    |\n%|  `---'  |                with stokeslet G and stresslet T              |\n%+========================================================================+\n\n% Cleaning\nclear all\nclose all\nclc\n\n% Gypsilab path\nrun('../../addpathGypsilab.m')\n\n% Parameters\nN  = 300;\nn  = 100;\nx0 = [0.1 0.2 0.3];\n\n% Mesh unit sphere\nmesh = mshSphere(N,1);\n\n% Quadrature\ngamma = dom(mesh,3);\n\n% Finite element and unknowns\nphi = fem(mesh,'P1');\nunk = phi.unk;\n\n% Radiation particles\nmesh2 = mshSphere(n,2);\nX     = mesh2.vtx;\n\n% Graphical rep\nfigure\nplot(mesh)\nhold on\nplotNrm(mesh)\nplot(gamma)\nplot(phi,'*r')\nplot(msh(X))\nalpha(0.5)\naxis equal\n\n% Initalization of block matrix for each coordinate (x,y,z)\nG      = cell(3,3);\nT      = cell(3,3);\nmu     = cell(3,1);\nlambda = cell(3,1);\n\n% Loop for each coordinate\nfor i = 1:3\n    for j = 1:3\n        % Using r = x - y\n        % Single layer : G = \\int_gamma 1/(8pi) (\\delta_ij/r + r_i*r_j/|r|^3) \n        name   = ['[ij/r+rirj/r^3]',num2str(i),num2str(j)];\n        green  = @(X,Y) 1/(8*pi) .* femGreenKernel(X,Y,name,[]);\n        G{i,j} = integral(X,gamma,green,phi);\n        \n        % Double layer : T = \\int_gamma -6/(8pi) (r_i*r_j*(r.n)/|r|^5)\n        T{i,j} = 0;\n        for k = 1:3\n            name   = ['[rirjrk/r^5]',num2str(i),num2str(j),num2str(k)];\n            green  = @(X,Y) -6/(8*pi) .* femGreenKernel(X,Y,name,[]);\n            T{i,j} = T{i,j} + integral(X,gamma,green,ntimes(phi,k));\n        end\n    end\n    \n    % mu = [u] = u_int - u_ext = - Gi1 = - Gi1(x0,y)\n    name  = ['[ij/r+rirj/r^3]',num2str(i),num2str(1)];\n    mu{i} = -1/(8*pi) * femGreenKernel(x0,phi.unk,name,[]);\n    \n    % lambda = [sigma] = - Ti1, with nk = xk (because boundary is unit sphere)\n    lambda{i} = 0;\n    for k = 1:3\n        name      = ['[rirjrk/r^5]',num2str(i),num2str(1),num2str(k)];\n        lambda{i} = lambda{i} - (-6/(8*pi)) * femGreenKernel(x0,phi.unk,name,[]) .* unk(:,k);\n    end\nend\n\n% Convert cells to full matrix\nG      = cell2mat(G);\nT      = cell2mat(T);\nmu     = cell2mat(mu);\nlambda = cell2mat(lambda);\n\n% Stokes radiation in domain : ui(x) = - sum_j \\int_gamma Gij(x,y) lambda_j dy ...\n%              + sum_j \\int_gamma Tij(x,y).n(y) mu_j dy \nsol = -G*lambda + T*mu ; \n\n% Analytic solution : Gi1\nref = cell(3,1);\nfor i = 1:3\n    name   = ['[ij/r+rirj/r^3]',num2str(i),num2str(1)];\n    ref{i} = 1/(8*pi) * femGreenKernel(X,x0,name,[]);\nend\nref = cell2mat(ref);\n\n% Relative error L2 and inf\nnorm(ref-sol)/norm(ref)\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\n% Graphical representation of solution\nfigure(2)\nfor i = 1:3\n    subplot(1,3,i)\n    ind = (i-1)*n + (1:n);\n    plot(mesh2,sol(ind))\n    axis equal\n    colorbar\n    title(['Component ',num2str(i)])\nend\n\n\n\n\n\ndisp('~~> Michto gypsilab !')\n\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/gypsilabModified/nonRegressionTest/stokes/nrtStkRadiation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5901075816752815}}
{"text": "clear all;\nrandn('seed',0);\n% Data are generated\nX=randn(20000,100);\nX=X./repmat(sqrt(sum(X.^2)),[size(X,1) 1]);\n\n% parameter of the optimization procedure are chosen\nparam.numThreads=-1; % number of processors/cores to use; the default choice is -1\n                    % and uses all the cores of the machine\n\nparam.pos=0;                   \nparam.mode=1;       % projection on the l1 ball\nparam.thrs=2;\ntic\nX1=mexSparseProject(X,param);\nt=toc;\ntoc\nfprintf('%f signals of size %d projected per second\\n',size(X,2)/t,size(X,1));\nfprintf('Checking constraint: %f, %f\\n',min(sum(abs(X1))),max(sum(abs(X1))));\n\n\nparam.mode=2;       % projection on the Elastic-Net\nparam.lambda1=0.15;\n\ntic\nX1=mexSparseProject(X,param);\nt=toc;\ntoc\nfprintf('%f signals of size %d projected per second\\n',size(X,2)/t,size(X,1));\nconstraints=sum((X1.^2))+param.lambda1*sum(abs(X1));\nfprintf('Checking constraint: %f, %f\\n',min(constraints),max(constraints));\n\nparam.mode=6;       % projection on the FLSA\nparam.lambda1=0.7;\nparam.lambda2=0.7;\nparam.lambda3=1.0;\n\nX=rand(2000,100);\nX=X./repmat(sqrt(sum(X.^2)),[size(X,1) 1]);\n\ntic\nX1=mexSparseProject(X,param);\nt=toc;\ntoc\nfprintf('%f signals of size %d projected per second\\n',size(X,2)/t,size(X,1));\nconstraints=0.5*param.lambda3*sum(X1.^2)+param.lambda1*sum(abs(X1))+param.lambda2*sum(abs(X1(2:end,:)-X1(1:end-1,:)));\nfprintf('Checking constraint: %f, %f\\n',mean(constraints),max(constraints));\nfprintf('Projection is approximate (stops at a kink)\\n',mean(constraints),max(constraints));\n\nparam.mode=6;       % projection on the FLSA\nparam.lambda1=0.7;\nparam.lambda2=0.7;\nparam.lambda3=1.0;\n\nX=rand(2000,100);\nX=X./repmat(sqrt(sum(X.^2)),[size(X,1) 1]);\n\ntic\nX1=mexSparseProject(X,param);\nt=toc;\ntoc\nfprintf('%f signals of size %d projected per second\\n',size(X,2)/t,size(X,1));\nconstraints=0.5*param.lambda3*sum(X1.^2)+param.lambda1*sum(abs(X1))+param.lambda2*sum(abs(X1(2:end,:)-X1(1:end-1,:)));\nfprintf('Checking constraint: %f, %f\\n',mean(constraints),max(constraints));\nfprintf('Projection is approximate (stops at a kink)\\n',mean(constraints),max(constraints));\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/AMICO/SPAMS/test_release/test_SparseProject.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5900982941122248}}
{"text": "function Derive_Equations()\n%%%% Derive Equations - Five Link Biped Model %%%%\n%\n% This function derives the equations of motion, as well as some other useful\n% equations (kinematics, contact forces, ...) for the five-link biped\n% model.\n%\n% This version of the code includes a few more complicated features for\n% dealing with difficult cost functions. In particular, it adds 10 slack\n% variables to compute the abs(power) term in the cost function, and the\n% primary control is the derivative of torque, rather than torque itself.\n% This allows for regularization by the derivative of the input.\n%\n%\n% Nomenclature:\n%\n% - There are five links, which will be numbered starting with \"1\" for the\n% stance leg tibia, increasing as the links are father from the base joint,\n% and ending with \"5\" for the swing leg tibia.\n%   1 - stance leg tibia (lower leg)\n%   2 - stance leg femur  (upper leg)\n%   3 - torso\n%   4 - swing leg femur\n%   5 - swing leg tibia\n%\n% - This script uses absolute angles, which are represented with \"q\". All\n% angles use positive convention, with the zero angle corresponding to a\n% vertically aligned link configuration. [q] = [0] has the torso balanced\n% upright, with both legs fully extended straight below it.\n%\n% - Derivatives with respect to time are notated by prepending a \"d\". For\n% example the rate of change in an absolute angle is \"dq\" and angular\n% acceleration would be \"ddq\"\n%\n% - Joint positions are given with \"P\", center of mass positions are \"G\"\n%\n\nclc; clear;\ndisp('Creating variables and derivatives...')\n\n%%%% Absolute orientation (angle) of each link\nq1 = sym('q1', 'real');\nq2 = sym('q2','real');\nq3 = sym('q3','real');\nq4 = sym('q4','real');\nq5 = sym('q5','real');\n\n%%%% Absolute angular rate of each link\ndq1 = sym('dq1','real');\ndq2 = sym('dq2','real');\ndq3 = sym('dq3','real');\ndq4 = sym('dq4','real');\ndq5 = sym('dq5','real');\n\n%%%% Absolute angular acceleration of each linke\nddq1 = sym('ddq1','real');\nddq2 = sym('ddq2','real');\nddq3 = sym('ddq3','real');\nddq4 = sym('ddq4','real');\nddq5 = sym('ddq5','real');\n\n%%%% Torques at each joint\nu1 = sym('u1','real');  %Stance foot\nu2 = sym('u2','real');   %Stance knee\nu3 = sym('u3','real');   %Stance hip\nu4 = sym('u4','real');   %Swing hip\nu5 = sym('u5','real');   %Swing knee\n\n%%%% Torques rate at each joint\ndu1 = sym('du1','real');  %Stance foot\ndu2 = sym('du2','real');   %Stance knee\ndu3 = sym('du3','real');   %Stance hip\ndu4 = sym('du4','real');   %Swing hip\ndu5 = sym('du5','real');   %Swing knee\n\n%%%% Slack variables -- negative component of power\nsn1 = sym('sn1','real');  %Stance foot\nsn2 = sym('sn2','real');   %Stance knee\nsn3 = sym('sn3','real');   %Stance hip\nsn4 = sym('sn4','real');   %Swing hip\nsn5 = sym('sn5','real');   %Swing knee\n\n%%%% Slack variables -- positive component of power\nsp1 = sym('sp1','real');  %Stance foot\nsp2 = sym('sp2','real');   %Stance knee\nsp3 = sym('sp3','real');   %Stance hip\nsp4 = sym('sp4','real');   %Swing hip\nsp5 = sym('sp5','real');   %Swing knee\n\n%%%% Mass of each link\nm1 = sym('m1','real');\nm2 = sym('m2','real');\nm3 = sym('m3','real');\nm4 = sym('m4','real');\nm5 = sym('m5','real');\n\n%%%% Distance between parent joint and link center of mass\nc1 = sym('c1','real');\nc2 = sym('c2','real');\nc3 = sym('c3','real');\nc4 = sym('c4','real');\nc5 = sym('c5','real');\n\n%%%% Length of each link\nl1 = sym('l1','real');\nl2 = sym('l2','real');\nl3 = sym('l3','real');\nl4 = sym('l4','real');\nl5 = sym('l5','real');\n\n%%%% Moment of inertia of each link about its own center of mass\nI1 = sym('I1','real');\nI2 = sym('I2','real');\nI3 = sym('I3','real');\nI4 = sym('I4','real');\nI5 = sym('I5','real');\n\ng = sym('g','real'); % Gravity\nFx = sym('Fx','real');   %Horizontal contact force at stance foot\nFy = sym('Fy','real');   %Vertical contact force at stance foot\nempty = sym('empty','real');   %Used for vectorization, user should pass a vector of zeros\nt = sym('t','real');  %dummy continuous time\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                Set up coordinate system and unit vectors                %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\ni = sym([1;0]);   %Horizontal axis\nj = sym([0;1]);   %Vertical axis\n\ne1 = cos(q1)*(j) + sin(q1)*(-i);  %unit vector from P0 -> P1, (contact point to stance knee)\ne2 = cos(q2)*(j) + sin(q2)*(-i);  %unit vector from P1 -> P2, (stance knee to hip)\ne3 = cos(q3)*(j) + sin(q3)*(-i);  %unit vector from P2 -> P3, (hip to shoulders);\ne4 = -cos(q4)*(j) - sin(q4)*(-i);  %unit vector from P2 -> P4, (hip to swing knee);\ne5 = -cos(q5)*(j) - sin(q5)*(-i);  %unit vector from P4 -> P5, (swing knee to swing foot);\n\nP0 = 0*i + 0*j;   %stance foot = Contact point = origin\nP1 = P0 + l1*e1;  %stance knee\nP2 = P1 + l2*e2;  %hip\nP3 = P2 + l3*e3;  %shoulders\nP4 = P2 + l4*e4;  %swing knee\nP5 = P4 + l5*e5;  %swing foot\n\nG1 = P1 - c1*e1;  % CoM stance leg tibia\nG2 = P2 - c2*e2;  % CoM stance leg febur\nG3 = P3 - c3*e3;  % CoM torso\nG4 = P2 + c4*e4;  % CoM swing leg femur\nG5 = P4 + c5*e5;  % CoM swing leg tibia\nG = (m1*G1 + m2*G2 + m3*G3 + m4*G4 + m5*G5)/(m1+m2+m3+m4+m5);  %Center of mass for entire robot\n\n%%%% Define a function for doing '2d' cross product: dot(a x b, k)\ncross2d = @(a,b)(a(1)*b(2) - a(2)*b(1));\n\n%%%% Weight of each link:\nw1 = -m1*g*j;\nw2 = -m2*g*j;\nw3 = -m3*g*j;\nw4 = -m4*g*j;\nw5 = -m5*g*j;\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                             Derivatives                                 %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nq = [q1;q2;q3;q4;q5];\ndq = [dq1;dq2;dq3;dq4;dq5];\nddq = [ddq1;ddq2;ddq3;ddq4;ddq5];\nu = [u1;u2;u3;u4;u5];\ndu = [du1;du2;du3;du4;du5];\nsn = [sn1;sn2;sn3;sn4;sn5];\nsp = [sp1;sp2;sp3;sp4;sp5];\nz = [t;q;dq;u;du;sn;sp];   % time-varying vector of inputs\n\n% Neat trick to compute derivatives using the chain rule\nderivative = @(in)( jacobian(in,[q;dq;u])*[dq;ddq;du] );\n\n% Velocity of the swing foot (used for step constraints)\ndP5 = derivative(P5);\n\n% Compute derivatives for the CoM of each link:\ndG1 = derivative(G1);  ddG1 = derivative(dG1);\ndG2 = derivative(G2);  ddG2 = derivative(dG2);\ndG3 = derivative(G3);  ddG3 = derivative(dG3);\ndG4 = derivative(G4);  ddG4 = derivative(dG4);\ndG5 = derivative(G5);  ddG5 = derivative(dG5);\ndG = derivative(G);  ddG = derivative(dG);\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                             Calculations:                               %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nsingleStanceDynamics();\nobjectiveFunctions();\nheelStrikeDynamics();\n\nmechanicalEnergy();\ncontactForces();\nkinematics();\n\ndisp('Done!');\n\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                      Single-Stance Dynamics                             %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% I solve the dynamics here by carefully selecting angular momentum balance\n% equations about each joint, working my way out the kinematic tree from\n% the root.\n\n    function singleStanceDynamics()\n        disp('Deriving single stance dynamics...')\n        \n        %%%% AMB - entire system @ P0\n        eqnTorque0 = ...\n            cross2d(G1-P0,w1) + ...\n            cross2d(G2-P0,w2) + ...\n            cross2d(G3-P0,w3) + ...\n            cross2d(G4-P0,w4) + ...\n            cross2d(G5-P0,w5) + ...\n            u1;\n        \n        eqnInertia0 = ...\n            cross2d(G1-P0,m1*ddG1) + ddq1*I1 + ...\n            cross2d(G2-P0,m2*ddG2) + ddq2*I2 + ...\n            cross2d(G3-P0,m3*ddG3) + ddq3*I3 + ...\n            cross2d(G4-P0,m4*ddG4) + ddq4*I4 + ...\n            cross2d(G5-P0,m5*ddG5) + ddq5*I5;\n        \n        %%%% AMB - swing leg, torso, stance femer  @ stance knee\n        eqnTorque1 = ...\n            cross2d(G2-P1,w2) + ...\n            cross2d(G3-P1,w3) + ...\n            cross2d(G4-P1,w4) + ...\n            cross2d(G5-P1,w5) + ...\n            u2;\n        \n        eqnInertia1 = ...\n            cross2d(G2-P1,m2*ddG2) + ddq2*I2  + ...\n            cross2d(G3-P1,m3*ddG3) + ddq3*I3  + ...\n            cross2d(G4-P1,m4*ddG4) + ddq4*I4  + ...\n            cross2d(G5-P1,m5*ddG5) + ddq5*I5 ;\n        \n        %%%% AMB - swing leg, torso @ hip\n        eqnTorque2 = ...\n            cross2d(G3-P2,w3) + ...\n            cross2d(G4-P2,w4) + ...\n            cross2d(G5-P2,w5) + ...\n            u3;\n        \n        eqnInertia2 = ...\n            cross2d(G3-P2,m3*ddG3) + ddq3*I3  + ...\n            cross2d(G4-P2,m4*ddG4) + ddq4*I4  + ...\n            cross2d(G5-P2,m5*ddG5) + ddq5*I5 ;\n        \n        %%%% AMB - swing leg @ hip\n        eqnTorque3 = ...\n            cross2d(G4-P2,w4) + ...\n            cross2d(G5-P2,w5) + ...\n            u4;\n        \n        eqnInertia3 = ...\n            cross2d(G4-P2,m4*ddG4) + ddq4*I4  + ...\n            cross2d(G5-P2,m5*ddG5) + ddq5*I5 ;\n        \n        %%%% AMB - swing tibia % swing knee\n        eqnTorque4 = ...\n            cross2d(G5-P4,w5) + ...\n            u5;\n        \n        eqnInertia4 = ...\n            cross2d(G5-P4,m5*ddG5) + ddq5*I5 ;\n        \n        %%%% Collect and solve equations:\n        eqns = [...\n            eqnTorque0 - eqnInertia0;\n            eqnTorque1 - eqnInertia1;\n            eqnTorque2 - eqnInertia2;\n            eqnTorque3 - eqnInertia3;\n            eqnTorque4 - eqnInertia4];\n        \n        [MM, FF] = equationsToMatrix(eqns,ddq);  % ddq = MM\\ff;\n        \n        %%%% Compute gradients:\n        [m, mi, mz, mzi, mzd] = computeGradients(MM,z,empty);\n        [f, fi, fz, fzi, fzd] = computeGradients(FF,z,empty);\n        \n        % Write function file:\n        matlabFunction(m, mi, f, fi,...   %dynamics\n            mz, mzi, mzd, fz, fzi, fzd,...  %gradients\n            'file','autoGen_dynSs.m',...\n            'vars',{...\n            'q1','q2','q3','q4','q5',...\n            'dq1','dq2','dq3','dq4','dq5',...\n            'u1','u2','u3','u4','u5',...\n            'm1','m2','m3','m4','m5',...\n            'I1','I2','I3','I4','I5',...\n            'l1','l2','l3','l4',...\n            'c1','c2','c3','c4','c5',...\n            'g','empty'});\n        \n    end\n\n\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                        Objective Functions                              %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n    function objectiveFunctions()\n        \n        % Joint rates:\n        v1 = dq1;   % joint rate 1\n        v2 = dq2-dq1;   % joint rate 2\n        v3 = dq3-dq2; % joint rate 3\n        v4 = dq4-dq3;  % joint rate 4\n        v5 = dq5-dq4;  % joint rate 5\n        \n        % Compute the power used by each joint\n        pow1 = v1*u1;  %Power used by joint 1\n        pow2 = v2*u2;  %Power used by joint 2\n        pow3 = v3*u3;  %Power used by joint 3\n        pow4 = v4*u4;  %Power used by joint 4\n        pow5 = v5*u5;  %Power used by joint 5\n        \n        % Constraint on the slack variables:\n        slackCst = [...\n            pow1 - (sp1 - sn1);\n            pow2 - (sp2 - sn2);\n            pow3 - (sp3 - sn3);\n            pow4 - (sp4 - sn4);\n            pow5 - (sp5 - sn5)];\n        \n        % Gradients of the constraint on slack variables:\n        [c, ~, cz, czi, ~] = computeGradients(slackCst,z,empty);\n        \n        matlabFunction(c,cz,czi,...\n            'file','autoGen_cst_costOfTransport.m',...\n            'vars',{...\n            'dq1','dq2','dq3','dq4','dq5',...\n            'u1','u2','u3','u4','u5',...\n            'sn1','sn2','sn3','sn4','sn5',...\n            'sp1','sp2','sp3','sp4','sp5','empty'});\n        \n        % abs(power) using slack variables:\n        gammaNeg = sym('gammaNeg','real');  %Torque-squared smoothing parameter\n        gammaPos = sym('gammaPos','real');  %Torque-squared smoothing parameter\n        absPower = gammaNeg*(sn1 + sn2 + sn3 + sn4 + sn5) + ...\n            gammaPos*(sp1 + sp2 + sp3 + sp4 + sp5);\n        \n        % Cost of Transport:\n        weight = (m1+m2+m3+m4+m5)*g;\n        stepLength = sym('stepLength','real');\n        alpha = sym('alpha','real');  %Torque-squared smoothing parameter\n        beta = sym('beta','real');  %Torque-rate squared smoothing\n        F = absPower/(weight*stepLength) + ...\n            alpha*(u1^2 + u2^2 + u3^2 + u4^2 + u5^2) + ...\n            beta*(du1^2 + du2^2 + du3^2 + du4^2 + du5^2);\n        [f, ~, fz, fzi, ~]  = computeGradients(F,z,empty);\n        \n        matlabFunction(f,fz,fzi,...\n            'file','autoGen_obj_costOfTransport.m',...\n            'vars',{...\n            'm1','m2','m3','m4','m5',...\n            'u1','u2','u3','u4','u5',...\n            'du1','du2','du3','du4','du5',...\n            'sn1','sn2','sn3','sn4','sn5', ...\n            'sp1','sp2','sp3','sp4','sp5',...\n            'g','stepLength','gammaNeg','gammaPos','alpha','beta','empty'});\n        \n        % Swing foot height:\n        stepHeight = sym('stepHeight','real');\n        yFoot = P5(2);\n        xFoot = P5(1);\n        yMin = stepHeight*(1 - (xFoot/stepLength)^2);\n        yCst = yMin - yFoot;  %Must be negative\n        [y, ~, yz, yzi, ~]  = computeGradients(yCst,z,empty);\n        matlabFunction(y,yz,yzi,...\n                    'file','autoGen_cst_swingFootHeight.m',...\n            'vars',{...\n            'q1','q2','q4','q5',...\n            'l1','l2','l4','l5'...\n            'stepLength','stepHeight'});\n    end\n\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                        Heel-Strike Dynamics                             %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n    function heelStrikeDynamics()\n        disp('Deriving heel-strike dynamics...')\n        \n        %%%% Notes:\n        % xF - heelStrike(xI) --> constraint --> 0\n        % xF - collision(footSwap(xI));\n        %\n        \n        % Angles before heel-strike:\n        q1m = sym('q1m','real');\n        q2m = sym('q2m','real');\n        q3m = sym('q3m','real');\n        q4m = sym('q4m','real');\n        q5m = sym('q5m','real');\n        qm = [q1m;q2m;q3m;q4m;q5m];\n        \n        % Angles after heel-strike\n        q1p = sym('q1p','real');\n        q2p = sym('q2p','real');\n        q3p = sym('q3p','real');\n        q4p = sym('q4p','real');\n        q5p = sym('q5p','real');\n        qp = [q1p;q2p;q3p;q4p;q5p];\n        \n        % Angular rates before heel-strike:\n        dq1m = sym('dq1m','real');\n        dq2m = sym('dq2m','real');\n        dq3m = sym('dq3m','real');\n        dq4m = sym('dq4m','real');\n        dq5m = sym('dq5m','real');\n        dqm = [dq1m;dq2m;dq3m;dq4m;dq5m];\n        \n        % Angular rates after heel-strike\n        dq1p = sym('dq1p','real');\n        dq2p = sym('dq2p','real');\n        dq3p = sym('dq3p','real');\n        dq4p = sym('dq4p','real');\n        dq5p = sym('dq5p','real');\n        dqp = [dq1p;dq2p;dq3p;dq4p;dq5p];\n        \n        % torque before heel-strike:\n        u1m = sym('u1m','real');\n        u2m = sym('u2m','real');\n        u3m = sym('u3m','real');\n        u4m = sym('u4m','real');\n        u5m = sym('u5m','real');\n        um = [u1m;u2m;u3m;u4m;u5m];\n        \n        % torque after heel-strike\n        u1p = sym('u1p','real');\n        u2p = sym('u2p','real');\n        u3p = sym('u3p','real');\n        u4p = sym('u4p','real');\n        u5p = sym('u5p','real');\n        up = [u1p;u2p;u3p;u4p;u5p];\n        \n        % Compute kinematics before heel-strike:\n        inVars = {'q1','q2','q3','q4','q5','dq1','dq2','dq3','dq4','dq5'};\n        outVarsM = {'q1m','q2m','q3m','q4m','q5m','dq1m','dq2m','dq3m','dq4m','dq5m'};\n        %         P0m = subs(P0,inVars,outVarsM);\n        P1m = subs(P1,inVars,outVarsM);\n        P2m = subs(P2,inVars,outVarsM);\n        %         P3m = subs(P3,inVars,outVarsM);\n        P4m = subs(P4,inVars,outVarsM);\n        P5m = subs(P5,inVars,outVarsM);\n        dP5m = subs(dP5,inVars,outVarsM);\n        G1m = subs(G1,inVars,outVarsM);\n        G2m = subs(G2,inVars,outVarsM);\n        G3m = subs(G3,inVars,outVarsM);\n        G4m = subs(G4,inVars,outVarsM);\n        G5m = subs(G5,inVars,outVarsM);\n        dG1m = subs(dG1,inVars,outVarsM);\n        dG2m = subs(dG2,inVars,outVarsM);\n        dG3m = subs(dG3,inVars,outVarsM);\n        dG4m = subs(dG4,inVars,outVarsM);\n        dG5m = subs(dG5,inVars,outVarsM);\n        \n        % Compute kinematics after heel-strike:\n        outVarsP = {'q1p','q2p','q3p','q4p','q5p','dq1p','dq2p','dq3p','dq4p','dq5p'};\n        P0p = subs(P0,inVars,outVarsP);\n        P1p = subs(P1,inVars,outVarsP);\n        P2p = subs(P2,inVars,outVarsP);\n        %         P3p = subs(P3,inVars,outVarsP);\n        P4p = subs(P4,inVars,outVarsP);\n        %         P5p = subs(P5,inVars,outVarsP);\n        dP5p = subs(dP5,inVars,outVarsP);\n        G1p = subs(G1,inVars,outVarsP);\n        G2p = subs(G2,inVars,outVarsP);\n        G3p = subs(G3,inVars,outVarsP);\n        G4p = subs(G4,inVars,outVarsP);\n        G5p = subs(G5,inVars,outVarsP);\n        dG1p = subs(dG1,inVars,outVarsP);\n        dG2p = subs(dG2,inVars,outVarsP);\n        dG3p = subs(dG3,inVars,outVarsP);\n        dG4p = subs(dG4,inVars,outVarsP);\n        dG5p = subs(dG5,inVars,outVarsP);\n        \n        %%%% AMB - entire system @ New stance foot\n        eqnHs0m = ...   %Before collision\n            cross2d(G1m-P5m,m1*dG1m) + dq1m*I1 + ...\n            cross2d(G2m-P5m,m2*dG2m) + dq2m*I2 + ...\n            cross2d(G3m-P5m,m3*dG3m) + dq3m*I3 + ...\n            cross2d(G4m-P5m,m4*dG4m) + dq4m*I4 + ...\n            cross2d(G5m-P5m,m5*dG5m) + dq5m*I5;\n        eqnHs0 = ...   %After collision\n            cross2d(G1p-P0p,m1*dG1p) + dq1p*I1 + ...\n            cross2d(G2p-P0p,m2*dG2p) + dq2p*I2 + ...\n            cross2d(G3p-P0p,m3*dG3p) + dq3p*I3 + ...\n            cross2d(G4p-P0p,m4*dG4p) + dq4p*I4 + ...\n            cross2d(G5p-P0p,m5*dG5p) + dq5p*I5;\n        \n        \n        %%%% AMB - new swing leg, torso, stance femer  @  stance knee\n        eqnHs1m = ...   %Before collision\n            cross2d(G1m-P4m,m1*dG1m) + dq1m*I1 + ...\n            cross2d(G2m-P4m,m2*dG2m) + dq2m*I2 + ...\n            cross2d(G3m-P4m,m3*dG3m) + dq3m*I3 + ...\n            cross2d(G4m-P4m,m4*dG4m) + dq4m*I4;\n        eqnHs1 = ...   %After collision\n            cross2d(G2p-P1p,m2*dG2p) + dq2p*I2 + ...\n            cross2d(G3p-P1p,m3*dG3p) + dq3p*I3 + ...\n            cross2d(G4p-P1p,m4*dG4p) + dq4p*I4 + ...\n            cross2d(G5p-P1p,m5*dG5p) + dq5p*I5;\n        \n        \n        %%%% AMB - swing leg, torso  @ new hip\n        eqnHs2m = ...   %Before collision\n            cross2d(G3m-P2m,m3*dG3m) + dq3m*I3 + ...\n            cross2d(G2m-P2m,m2*dG2m) + dq2m*I2 + ...\n            cross2d(G1m-P2m,m1*dG1m) + dq1m*I1;\n        eqnHs2 = ...   %After collision\n            cross2d(G3p-P2p,m3*dG3p) + dq3p*I3 + ...\n            cross2d(G4p-P2p,m4*dG4p) + dq4p*I4 + ...\n            cross2d(G5p-P2p,m5*dG5p) + dq5p*I5;\n        \n        \n        %%%% AMB - swing leg @ new hip\n        eqnHs3m = ...   %Before collision\n            cross2d(G1m-P2m,m1*dG1m) + dq1m*I1 + ...\n            cross2d(G2m-P2m,m2*dG2m) + dq2m*I2;\n        eqnHs3 = ...   %After collision\n            cross2d(G4p-P2p,m4*dG4p) + dq4p*I4 + ...\n            cross2d(G5p-P2p,m5*dG5p) + dq5p*I5;\n        \n        %%%% AMB - swing tibia @ new swing knee\n        eqnHs4m = ...   %Before collision\n            cross2d(G1m-P1m,m1*dG1m) + dq1m*I1;\n        eqnHs4 = ...   %After collision\n            cross2d(G5p-P4p,m5*dG5p) + dq5p*I5;\n        \n        \n        %%%% Collect and solve equations:\n        eqnHs = [...\n            eqnHs0m - eqnHs0;\n            eqnHs1m - eqnHs1;\n            eqnHs2m - eqnHs2;\n            eqnHs3m - eqnHs3;\n            eqnHs4m - eqnHs4];\n        [MM, FF] = equationsToMatrix(eqnHs,dqp);\n        \n        %%%% Compute gradients:\n        tp = sym('tp','real');   %Initial trajectory time\n        tm = sym('tm','real');   %Final trajectory time\n        zBnd = [tp;qp;dqp;up;tm;qm;dqm;um];\n        [m, mi, mz, mzi, mzd] = computeGradients(MM,zBnd,empty);\n        [f, fi, fz, fzi, fzd] = computeGradients(FF,zBnd,empty);\n        \n        % Heel-strike\n        matlabFunction(m, mi, f, fi,...   %dynamics\n            mz, mzi, mzd, fz, fzi, fzd,...  %gradients\n            'file','autoGen_cst_heelStrike.m',...\n            'vars',{...\n            'q1p','q2p','q3p','q4p','q5p',...\n            'q1m','q2m','q3m','q4m','q5m',...\n            'dq1m','dq2m','dq3m','dq4m','dq5m',...\n            'm1','m2','m3','m4','m5',...\n            'I1','I2','I3','I4','I5',...\n            'l1','l2','l3','l4','l5',...\n            'c1','c2','c3','c4','c5','empty'});\n        \n        % Collision velocity of the swing foot:\n        cst = [-dP5p(2); dP5m(2)];  %Swing foot velocity before and after collision (negative sign is intentional, since output is constrained to be negative);\n        cstJac = jacobian(cst,zBnd);  %Gradient\n        matlabFunction(cst, cstJac,...\n            'file','autoGen_cst_footVel.m',...\n            'vars',{...\n            'q1p','q2p','q4p','q5p',...\n            'q1m','q2m','q4m','q5m',...\n            'dq1p','dq2p','dq4p','dq5p',...\n            'dq1m','dq2m','dq4m','dq5m',...\n            'l1','l2','l4','l5'});\n        \n        % Step length and height constraint:\n        stepLength = sym('stepLength','real');\n        ceq = [P5m(1)-stepLength; P5m(2)];\n        ceqJac = jacobian(ceq,zBnd);  %Gradient\n        matlabFunction(ceq, ceqJac,...\n            'file','autoGen_cst_steplength.m',...\n            'vars',{...\n            'q1m','q2m','q4m','q5m',...\n            'l1','l2','l4','l5','stepLength'});\n    end\n\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                         Mechanical Energy                               %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n    function mechanicalEnergy()\n        disp('Deriving mechanical energy...')\n        \n        %%%% Energy:\n        KineticEnergy = ...\n            0.5*m1*dot(dG1,dG1) + 0.5*I1*dq1^2 + ...\n            0.5*m2*dot(dG2,dG2) + 0.5*I2*dq2^2 + ...\n            0.5*m3*dot(dG3,dG3) + 0.5*I3*dq3^2 + ...\n            0.5*m4*dot(dG4,dG4) + 0.5*I4*dq4^2 + ...\n            0.5*m5*dot(dG5,dG5) + 0.5*I5*dq5^2;\n        PotentialEnergy = ...\n            m1*g*G1(2) + ...\n            m2*g*G2(2) + ...\n            m3*g*G3(2) + ...\n            m4*g*G4(2) + ...\n            m5*g*G5(2);\n        \n        \n        matlabFunction(KineticEnergy, PotentialEnergy,...\n            'file','autoGen_energy.m',...\n            'vars',{...\n            'q1','q2','q3','q4','q5',...\n            'dq1','dq2','dq3','dq4','dq5',...\n            'm1','m2','m3','m4','m5',...\n            'I1','I2','I3','I4','I5',...\n            'l1','l2','l3','l4',...\n            'c1','c2','c3','c4','c5',...\n            'g'},...\n            'outputs',{'KE','PE'});\n        \n    end\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                          Contact Forces                                 %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n\n    function contactForces()\n        \n        %%%% Contact Forces:\n        eqnForce5 = w1 + w2 + w3 + w4 + w5 + Fx*i + Fy*j;\n        eqnInertia5 = (m1+m2+m3+m4+m5)*ddG;\n        [AA,bb] = equationsToMatrix(eqnForce5-eqnInertia5,[Fx;Fy]);\n        ContactForces = AA\\bb;\n        \n        matlabFunction(ContactForces(1),ContactForces(2),...\n            'file','autoGen_contactForce.m',...\n            'vars',{...\n            'q1','q2','q3','q4','q5',...\n            'dq1','dq2','dq3','dq4','dq5',...\n            'ddq1','ddq2','ddq3','ddq4','ddq5',...\n            'm1','m2','m3','m4','m5',...\n            'l1','l2','l3','l4',...\n            'c1','c2','c3','c4','c5',...\n            'g'},...\n            'outputs',{'Fx','Fy'});\n        \n        \n    end\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                        Write Kinematics Files                           %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n    function kinematics()\n        disp('Writing kinematics files...')\n        \n        \n        P = [P1; P2; P3; P4; P5];\n        Gvec = [G1; G2; G3; G4; G5];\n        \n        % Used for plotting and animation\n        matlabFunction(P,Gvec,'file','autoGen_getPoints.m',...\n            'vars',{...\n            'q1','q2','q3','q4','q5',...\n            'l1','l2','l3','l4','l5',...\n            'c1','c2','c3','c4','c5'},...\n            'outputs',{'P','Gvec'});\n        \n    end\n\n\n\n\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                       Helper Functions                                  %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [m, mi, mz, mzi, dim] = computeGradients(M,z,empty)\n%\n% This function computes the gradients of a matrix M with respect the the\n% variables in z, and then returns both the matrix and its gradient as\n% column vectors of their non-zero elements, along with the linear indicies\n% to unpack them. It also simplifies m and mz.\n%\n% INPUTS:\n%   M = [na, nb] = symbolic matrix\n%   z = [nc, 1] = symbolic vector\n%\n% OUTPUTS:\n%   m = [nd, 1] = symbolic vector of non-zero elements in M\n%   mi = [nd, 1] = linear indicies to map m --> [na,nb] matrix\n%   mz = [ne, 1] = symbolic vector of non-zero elements in Mz\n%   mzi = [ne, 1] = linear indicies to map mz --> [na,nb,nc] array\n%   dim = [3,1] = [na,nb,nc] = dimensions of 3d version of mz\n%\n\n[na, nb] = size(M);\nnc = size(z,1);\nM = simplify(M);\n\nmz2 = jacobian(M(:),z);  %Compute jacobian of M, by first reshaping M to be a column vector\nmz3 = reshape(mz2,na,nb,nc); %Expand back out to a three-dimensional array\nmz3 = simplify(mz3);\n\n% Extract non-zero elements to a column vector:\nmi = find(M);\nm = M(mi);\nmzi = find(mz3);\nmz = mz3(mzi); mz = mz(:);  %Collapse to a column vector\ndim = [na,nb,nc];\n\n% Pad any constant terms with \"empty\" to permit vectorization:\nm = vectorizeHack(m, z, empty);\nmz = vectorizeHack(mz, z, empty);\n\nend\n\n\n\nfunction x = vectorizeHack(x, z, empty)\n%\n% This function searches for any elements of x that are not dependent on\n% any element of z. In this case, the automatically generated code will\n% fail to vectorize properly. One solution is to add an array of zeros\n% (empty) to the element.\n%\n% x = column vector of symbolic expressions\n% z = column vector of symbolic variables\n% z = symbolic variable, which the user will set equal to zero.\n%\n\n% Compute dependencies\ng = jacobian(x,z);\n\n% Check for rows of x with no dependence on z\n[n,m] = size(g);\nidxConst = true(n,1);\nfor i=1:n\n    for j=1:m\n        if ~isequal(sym(0),g(i,j))\n            idxConst(i) = false;\n            break;\n        end\n    end\nend\n\n% Add empty to those enteries\nx(idxConst) = x(idxConst) + empty;\n\nend\n\n\n\n\n\n", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/fiveLinkBiped/costOfTransport/Derive_Equations.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5900982728872357}}
{"text": "function centroids = kMeansInitCentroids(X, K)\n%KMEANSINITCENTROIDS This function initializes K centroids that are to be \n%used in K-Means on the dataset X\n%   centroids = KMEANSINITCENTROIDS(X, K) returns K initial centroids to be\n%   used with the K-Means on the dataset X\n%\n\n% You should return this values correctly\ncentroids = zeros(K, size(X, 2));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should set centroids to randomly chosen examples from\n%               the dataset X\n%\n% Initialize the centroids to be random examples\n% Randomly reorder the indices of examples\nrandidx = randperm(size(X, 1));\n% Take the first K examples as centroids\ncentroids = X(randidx(1:K), :);\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/kMeansInitCentroids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.5900982700855477}}
{"text": "% SCAT_ENERGY Calculate scattering energy\n%\n% Usage\n%    energy = scat_energy(S, U)\n%\n% Input\n%    S (cell): The scattering transform.\n%    U (cell): The wavelet modulus coefficients (optional).\n%\n% Output\n%    energy (numeric): The energy of the scattering transform (the sum of the \n%       squares of the coefficients). If both S and U are given, the energy of\n%       both are computed and summed.\n\nfunction energy = scat_energy(S, U)\n\tif nargin < 2\n\t\tU = [];\n\tend\n\t\n\tif ~isempty(U)\n\t\tenergy = scat_energy(S) + scat_energy(U);\n\telse\n\t\tif iscell(S)\n\t\t\tenergy = 0;\n\t\t\tfor m = 1:numel(S)\n\t\t\t\tenergy = energy + scat_energy(S{m});\n\t\t\tend\n\t\telse\n\t\t\tenergy = 0;\n\t\t\tfor p = 1:numel(S.signal)\n\t\t\t\tsig = S.signal{p};\n\t\t\t\t% TODO: fix so that multiple signals work!!\n\t\t\t\t%sz = size(sig);\n\t\t\t\t%sig = reshape(sig,[prod(sz(1:end-1)) sz(end)]);\n\t\t\t\tenergy = energy + sum(abs(sig(:)).^2,1);\n\t\t\tend\n\t\tend\n\tend\nend\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/scat_energy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5900973868617048}}
{"text": "function [B_detail, B_smooth] = train_choose_detail(training_path, unit, col)\n% choosing image patches which contain more detail\n\nfileFolder=fullfile(training_path);\ndirOutput=dir(fullfile(fileFolder,'*'));\nnum = length(dirOutput);\n% fileNames={dirOutput.name}'; % all names\nB = [];\nfor i = 3:num\n    img = imread([training_path,dirOutput(i).name]);\n    if size(img,3)>1\n        img = rgb2gray(img);\n    end\n\n    [t1,t2] = size(img);\n    img = img(1:floor(t1/unit)*unit, 1:floor(t2/unit)*unit);\n\n    img = im2double(img);\n    b = im2col(img, [unit, unit], 'distinct');\n    B = cat(2, B, b);\nend\n% calculating SD valuee of each column B\nB_mean = mean(B,1);\nB_mean = repmat(B_mean, unit*unit, 1);\nB_sd = sqrt(sum((B - B_mean).*(B - B_mean),1));\n% choose >0.5\nB_sd(find(B_sd<=0.5)) = 0;\nB_sd(find(B_sd>0.5)) = 1;\nB_mask = repmat(B_sd, unit*unit, 1);\nB_smooth = B.*(1-B_mask);\nB_detail = B.*B_mask;\nB_smooth(:,all(B_smooth==0,1))=[];\nB_detail(:,all(B_detail==0,1))=[];\n\n[m1,n1] = size(B_detail);\n[m2,n2] = size(B_smooth);\n\nend", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/mdlatlrr/learning_projection_matrix/train_choose_detail.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5900973866600919}}
{"text": "% \n% Usage:   [V [val_regularizer]]=mexProximalGraph(U,graph,param);\n%\n% Name: mexProximalGraph\n%\n% Description: mexProximalGraph computes a proximal operator. Depending\n%         on the value of param.regul, it computes \n%\n%         Given an input matrix U=[u^1,\\ldots,u^n], and a set of groups G,\n%         it computes a matrix V=[v^1,\\ldots,v^n] such that\n%\n%         if param.regul='graph'\n%         for every column u of U, it computes a column v of V solving\n%             argmin 0.5||u-v||_2^2 + lambda\\sum_{g \\in G} \\eta_g||v_g||_inf\n%\n%         if param.regul='graph+ridge'\n%         for every column u of U, it computes a column v of V solving\n%             argmin 0.5||u-v||_2^2 + lambda\\sum_{g \\in G} \\eta_g||v_g||_inf + lambda_2||v||_2^2\n%\n%\n%         if param.regul='multi-task-graph'\n%            V=argmin 0.5||U-V||_F^2 + lambda \\sum_{i=1}^n\\sum_{g \\in G} \\eta_g||v^i_g||_inf + ...\n%                                                lambda_2 \\sum_{g \\in G} \\eta_g max_{j in g}||V_j||_{inf}\n%         \n%         it can also be used with any regularization addressed by mexProximalFlat\n%\n%         for all these regularizations, it is possible to enforce non-negativity constraints\n%         with the option param.pos, and to prevent the last row of U to be regularized, with\n%         the option param.intercept\n%\n% Inputs: U:  double p x n matrix   (input signals)\n%               m is the signal size\n%         graph: struct\n%               with three fields, eta_g, groups, and groups_var\n%\n%               The first fields sets the weights for every group\n%                  graph.eta_g            double N vector \n%  \n%               The next field sets inclusion relations between groups \n%               (but not between groups and variables):\n%                  graph.groups           sparse (double or boolean) N x N matrix  \n%                  the (i,j) entry is non-zero if and only if i is different than j and \n%                  gi is included in gj.\n%               \n%               The next field sets inclusion relations between groups and variables\n%                  graph.groups_var       sparse (double or boolean) p x N matrix\n%                  the (i,j) entry is non-zero if and only if the variable i is included \n%                  in gj, but not in any children of gj.\n%\n%               examples are given in test_ProximalGraph.m\n%\n%         param: struct\n%               param.lambda  (regularization parameter)\n%               param.regul (choice of regularization, see above)\n%               param.lambda2  (optional, regularization parameter)\n%               param.lambda3  (optional, regularization parameter)\n%               param.verbose (optional, verbosity level, false by default)\n%               param.intercept (optional, last row of U is not regularized,\n%                 false by default)\n%               param.pos (optional, adds positivity constraints on the\n%                 coefficients, 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 p x n matrix (output coefficients)\n%         val_regularizer: double 1 x n vector (value of the regularization\n%         term at the optimum).\n%\n% Author: Julien Mairal, 2010\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/mexProximalGraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5900973760821047}}
{"text": "function [Y,W,SetupStruc] = Process_DSB(s,Transfer,SetupStruc)\nK = SetupStruc.DSB.K;\nhop = SetupStruc.DSB.hop;\nwin = hanning(K,'periodic');\nwin = win/sqrt(sum(win(1:hop:K).^2));\nSetupStruc.DSB.win = win;  % Preserve 'win' in 'SetupStruc'\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nN = size(s,2);\nfor i = 1:N\n    X(:,:,i) = fft(enframe(s(:,i),win,hop)');\nend\nframe_N = size(X,2);\nK_m = K/2+1;\nNum = size(Transfer,3);\nY = zeros((frame_N-1)*hop+K,Num);\nY_f = zeros(size(X,1),size(X,2),Num);\n%%%%%%%%%%%%%%%%%%%%%%%%%% Obtain processing matrix 'W'\nW = conj(permute(Transfer,[3 2 1]))/N;\nfor i = 2:K_m\n    X_f = permute(X(i,:,:),[3 2 1]);\n    W_f = permute(W(:,:,i),[1 2 3]);\n    Y_ = W_f*X_f;\n    Y_f(i,:,:) = Y_.';\n    if(i~=K_m)\n        Y_f(K+2-i,:,:) = Y_';\n    end\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Recover signals\nif(K/hop==2)\n    win = ones(K,1);\nend\nfor i = 1:Num\n    Y(:,i) = overlapadd(real(ifft(Y_f(:,:,i)))',win,hop);\nend\n\nreturn;", "meta": {"author": "KyleZhang1118", "repo": "Voice-Separation-and-Enhancement", "sha": "77d16c120356dbbca3ee768d293df5d743d343ad", "save_path": "github-repos/MATLAB/KyleZhang1118-Voice-Separation-and-Enhancement", "path": "github-repos/MATLAB/KyleZhang1118-Voice-Separation-and-Enhancement/Voice-Separation-and-Enhancement-77d16c120356dbbca3ee768d293df5d743d343ad/Process_DSB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.590088644307828}}
{"text": "function [Peg, Peh] = getPe(K, Ec, No, N, pulse);\n\n[mew, sigma] = get_mean_var_G(K, N, Ec, pulse.m1);\nIg = sqrt(N*No/2 + mew);\nTh = N*sqrt(Ec);       %Non- Coherent\nPeg = qfunc(Th/Ig);\n[mew, sigma] = get_mean_var_H(K, N, Ec, pulse.m1, pulse.m2, pulse.w1, pulse.w2);\nI1 = sqrt(No*N/2 + mew);\nI2 = sqrt(No*N/2 + (mew + sqrt(3) * sigma));\nI3 = sqrt(No*N/2 + (mew - sqrt(3) * sigma));\nPeh = 2/3*qfunc(Th/I1) + 1/6*qfunc(Th/I2) + 1/6*qfunc(Th/I3);\n\nfunction [mew_MAI, sigma_MAI] = get_mean_var_H(K, N, P, m1, m2, w1, w2)\nT =1;\nmew_MAI = (N*P * (K-1)*m1);\nsigma_MAI = (N*P) * ((K-1)*( (.375*w1 - m1^2) + ((N-1)/(N^2))*((1.5*w2) + (K-2)*(m2^2) )))^(.5);\n\nfunction [mew_MAI, sigma_MAI] = get_mean_var_G(K, N, P, m1)\nT =1;\nmew_MAI = (N*P * (K-1)*m1);\nsigma_MAI = 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/7409-bit-error-rate-in-bit-error-rates-with-pulse-shaping-consideration/getPe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5900839922641413}}
{"text": "function varargout = sample(f, varargin)\n%SAMPLE   Samples a DISKFUN object on a tensor product grid.\n%   X = SAMPLE(F) returns the matrix of values of F(theta, r) on a \n%   Fourier-Chebyshev tensor product grid. (theta, r) are polar coordinates, \n%   with -pi <= theta <= pi and 0 <= r <= 1. \n%\n%   [U, D, V] = SAMPLE(F) returns the low rank representation of the\n%   values of F on a tensor product grid where X = U * D * V'.\n%\n%   [U, D, V] = SAMPLE(F,M,N) returns the values of F on an M-by-N\n%   tensor product grid.\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    varargout = { [] };\n    return\nend\n\nif ( nargin == 1 ) \n    % Get degrees:\n    [m, n] = length(f);\n    \nelseif ( nargin == 2 ) \n    error('CHEBFUN:DISKFUN:sample:inputs', 'Dimension not specified.'); \n    \nelse\n    m = varargin{ 1 }; \n    n = varargin{ 2 }; \n    if ( (m <= 0) || (n <= 0) )\n        error('CHEBFUN:DISKFUN:sample:inputs', ['Number of sample ' ...\n             'points must be positive.']);\n    end\nend\n\n% Get the low rank representation for f. \n[cols, d, rows] = cdr(f);\n \nC = sample(cols, max(2*n-1, 1));\nC = C(n:end, :);\n\nR = real( sample(rows, m)); \n\n% Evaluate: \nif ( nargout <= 1 )\n    varargout = {C * d * R.'}; \nelse\n    varargout = {C , d, R}; \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/@diskfun/sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5900788400379393}}
{"text": "%TR2Q\tConvert homogeneous transform to a unit-quaternion\n%\n%\tQ = tr2q(T)\n%\n%\tReturn a unit quaternion corresponding to the rotational part of the\n%\thomogeneous transform T.\n%\n%\tSee also Q2TR\n\n%\tCopyright (C) 1993 Peter Corke\nfunction q = tr2q(t)\n\tq = zeros(1,4);\n\tq(1) = sqrt(trace(t))/2;\n\tkx = t(3,2) - t(2,3);\t% Oz - Ay\n\tky = t(1,3) - t(3,1);\t% Ax - Nz\n\tkz = t(2,1) - t(1,2);\t% Ny - Ox\n\n\tif (t(1,1) >= t(2,2)) & (t(1,1) >= t(3,3)) \n\t\tkx1 = t(1,1) - t(2,2) - t(3,3) + 1;\t% Nx - Oy - Az + 1\n\t\tky1 = t(2,1) + t(1,2);\t\t\t% Ny + Ox\n\t\tkz1 = t(3,1) + t(1,3);\t\t\t% Nz + Ax\n\t\tadd = (kx >= 0);\n\telseif (t(2,2) >= t(3,3))\n\t\tkx1 = t(2,1) + t(1,2);\t\t\t% Ny + Ox\n\t\tky1 = t(2,2) - t(1,1) - t(3,3) + 1;\t% Oy - Nx - Az + 1\n\t\tkz1 = t(3,2) + t(2,3);\t\t\t% Oz + Ay\n\t\tadd = (ky >= 0);\n\telse\n\t\tkx1 = t(3,1) + t(1,3);\t\t\t% Nz + Ax\n\t\tky1 = t(3,2) + t(2,3);\t\t\t% Oz + Ay\n\t\tkz1 = t(3,3) - t(1,1) - t(2,2) + 1;\t% Az - Nx - Oy + 1\n\t\tadd = (kz >= 0);\n\tend\n\n\tif add\n\t\tkx = kx + kx1;\n\t\tky = ky + ky1;\n\t\tkz = kz + kz1;\n\telse\n\t\tkx = kx - kx1;\n\t\tky = ky - ky1;\n\t\tkz = kz - kz1;\n\tend\n\tnm = norm([kx ky kz]);\n\tif nm == 0,\n\t\tq = [1 0 0 0];\n\telse\n\t\ts = sqrt(1 - q(1)^2) / nm;\n\t\tq(2:4) = s*[kx ky kz];\n\tend\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/EKF_monoSLAM_1pRANSAC/matlab_code/tr2q.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5900788287284253}}
{"text": "function dif_print ( ntab, xtab, diftab, title )\n\n%*****************************************************************************80\n%\n%% DIF_PRINT prints the polynomial represented by a divided difference table.\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 NTAB, the dimension of the arrays DIFTAB and XTAB.\n%\n%    Input, real XTAB(NTAB), the X values for the polynomial.\n%\n%    Input, real DIFTAB(NTAB), the divided difference table\n%    for the polynomial.\n%\n%    Input, string TITLE, a title.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '%s\\n', title );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  p(x) =                           %14f\\n', diftab(1) );\n\n  for i = 2 : ntab\n    fprintf ( 1, '       + ( x - %14f) * ( %14f\\n', xtab(i-1), diftab(i) );\n  end\n\n  fprintf ( 1, '  ' );\n  for i = 1 : ntab-1\n    fprintf ( 1, ')' );\n  end\n  fprintf ( 1, '\\n' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/divdif/dif_print.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.721743206297598, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.5900788286472056}}
{"text": "function [ ap, rcond, z, info ] = sppco ( ap, n )\n\n%*****************************************************************************80\n%\n%% SPPCO factors a real symmetric positive definite matrix in packed form.\n%\n%  Discussion:\n%\n%    SPPCO also estimates the condition of the matrix.\n%\n%    If RCOND is not needed, SPPFA is slightly faster.\n%\n%    To solve A*X = B, follow SPPCO by SPPSL.\n%\n%    To compute inverse(A)*C, follow SPPCO by SPPSL.\n%\n%    To compute determinant(A), follow SPPCO by SPPDI.\n%\n%    To compute inverse(A), follow SPPCO by SPPDI.\n%\n%  Packed storage:\n%\n%    The following program segment will pack the upper triangle of\n%    a symmetric matrix.\n%\n%      k = 0\n%      do j = 1, n\n%        do i = 1, j\n%          k = k + 1\n%          ap(k) = a(i,j)\n%        end\n%      end\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    09 November 2006\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, real AP(N*(N+1)/2), the packed form of a symmetric matrix A.  \n%    The columns of the upper triangle are stored sequentially in a \n%    one-dimensional array.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Output, real AP(N*(N+1)/2), an upper riangular matrix R, stored\n%    in packed form, so that A = R'*R.  If INFO /= 0, the factorization \n%    is not complete.\n%\n%    Output, real RCOND, an estimate of the reciprocal condition\n%    of A.  For the system A*X = B, relative perturbations in A and B of size\n%    EPSILON may cause relative perturbations in X of size EPSILON/RCOND.\n%    If RCOND is so small that the logical expression\n%      1.0 + RCOND == 1.0D+00\n%    is true, then A may be singular to working precision.  In particular,\n%    RCOND is zero if exact singularity is detected or the estimate underflows.\n%\n%    Output, real Z(N), a work vector whose contents are usually\n%    unimportant.  If A is singular to working precision, then Z is an\n%    approximate null vector in the sense that\n%      norm(A*Z) = RCOND * norm(A) * norm(Z).\n%    If INFO /= 0, Z is unchanged.\n%\n%    Output, integer INFO, error flag.\n%    0, for normal return.\n%    K, signals an error condition.  The leading minor of order K is\n%    not positive definite.\n%\n\n%\n%  Find the norm of A.\n%\n  j1 = 1;\n  for j = 1 : n\n    z(j) = sasum ( j, ap(j1:j1+j-1), 1 );\n    ij = j1;\n    j1 = j1 + j;\n    for i = 1 : j-1\n      z(i) = z(i) + abs ( ap(ij) );\n      ij = ij + 1;\n    end\n  end\n\n  anorm = max ( z(1:n) );\n%\n%  Factor.\n%\n  [ ap, info ] = sppfa ( ap, n );\n\n  if ( info ~= 0 )\n    return\n  end\n%\n%  RCOND = 1/(norm(A)*(estimate of norm(inverse(A)))).\n%\n%  Estimate = norm(Z)/norm(Y) where A * Z = Y and A * Y = E.\n%\n%  The components of E are chosen to cause maximum local\n%  growth in the elements of W where R'*W = E.\n%\n%  The vectors are frequently rescaled to avoid overflow.\n%\n%  Solve R' * W = E.\n%\n  ek = 1.0;\n  z(1:n) = 0.0;\n\n  kk = 0;\n\n  for k = 1 : n\n\n    kk = kk + k;\n\n    if ( z(k) ~= 0.0 )\n      ek = -abs ( ek ) * r4_sign ( z(k) );\n    end\n\n    if ( ap(kk) < abs ( ek - z(k) ) )\n      s = ap(kk) / abs ( ek - z(k) );\n      z(1:n) = s * z(1:n);\n      ek = s * ek;\n    end\n\n    wk = ek - z(k);\n    wkm = -ek - z(k);\n    s = abs ( wk );\n    sm = abs ( wkm );\n    wk = wk / ap(kk);\n    wkm = wkm / ap(kk);\n    kj = kk + k;\n\n    if ( k + 1 <= n )\n\n      for j = k + 1 : n\n        sm = sm + abs ( z(j) + wkm * ap(kj) );\n        z(j) = z(j) + wk * ap(kj);\n        s = s + abs ( z(j) );\n        kj = kj + j;\n      end\n\n      if ( s < sm )\n\n        t = wkm - wk;\n        wk = wkm;\n        kj = kk + k;\n\n        for j = k+1 : n\n          z(j) = z(j) + t * ap(kj);\n          kj = kj + j;\n        end\n\n      end\n\n    end\n\n    z(k) = wk;\n\n  end\n\n  z(1:n) = z(1:n) / sasum ( n, z(1:n), 1 );\n%\n%  Solve R * Y = W.\n%\n  for k = n : -1 : 1\n\n    if ( ap(kk) < abs ( z(k) ) );\n      s = ap(kk) / abs ( z(k) );\n      z(1:n) = s * z(1:n);\n    end\n\n    z(k) = z(k) / ap(kk);\n    kk = kk - k;\n    t = -z(k);\n    z(1:k-1) = saxpy ( k-1, t, ap(kk+1:kk+k-1), 1, z(1:k-1), 1 );\n\n  end\n\n  z(1:n) = z(1:n) / sasum ( n, z(1:n), 1 );\n\n  ynorm = 1.0;\n%\n%  Solve R' * V = Y.\n%\n  for k = 1 : n\n\n    z(k) = z(k) - sdot ( k-1, ap(kk+1:kk+k-1), 1, z(1:k-1), 1 );\n    kk = kk + k;\n\n    if ( ap(kk) < abs ( z(k) ) )\n      s = ap(kk) / abs ( z(k) );\n      z(1:n) = s * z(1:n);\n      ynorm = s * ynorm;\n    end\n\n    z(k) = z(k) / ap(kk);\n\n  end\n\n  s = 1.0 / sasum ( n, z(1:n), 1 );\n  z(1:n) = s * z(1:n);\n  ynorm = s * ynorm;\n%\n%  Solve R * Z = V.\n%\n  for k = n : -1 : 1\n\n    if ( ap(kk) < abs ( z(k) ) )\n      s = ap(kk) / abs ( z(k) );\n      z(1:n) = s * z(1:n);\n      ynorm = s * ynorm;\n    end\n\n    z(k) = z(k) / ap(kk);\n    kk = kk - k;\n    t = -z(k);\n    z(1:k-1) = saxpy ( k-1, t, ap(kk+1:kk+k-1), 1, z(1:k-1), 1 );\n\n  end\n%\n%  Make ZNORM = 1.0.\n%\n  s = 1.0 / sasum ( n, z(1:n), 1 );\n  z(1:n) = s * z(1:n);\n  ynorm = s * ynorm;\n\n  if ( anorm ~= 0.0 )\n    rcond = ynorm / anorm;\n  else\n    rcond = 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/linpack_s/sppco.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5900788204645556}}
{"text": "function RMC = fmri_mcorrestriction(RM,TR,nHEst,Delta,Tau)\n%\n% RMC = fmri_mcorrestriction(RM,TR,nHEst,Delta,Tau)\n%\n% Creates a restriction matrix for correlating with a\n% hemodynmic response function (HRF).  The HRF is\n% computed using a Gamma function with parameters \n% Delta and Tau over the estimation time window.\n%\n% RM is a restriction matrix created by CreateRM.\n%\n% See also: CreateRM(), HemoDyn()\n%\n% $Id: fmri_mcorrrestriction.m,v 1.1 2004/03/11 01:30:16 sayres Exp $\n\n\nt = TR*[0:nHEst-1]';\nhHDIR = fmri_hemodyn(t,Delta,Tau);\nnCond = size(RM,2)/nHEst; % excluding fix %\nq = repmat(hHDIR',size(RM,1),nCond);\nRMC = RM .* q;\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/fmri_mcorrrestriction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5900788125255654}}
{"text": "function [ tri_num, tri_vert, tri_nabe ] = r8tris2 ( point_num, p )\n\n%*****************************************************************************80\n%\n%% R8TRIS2 constructs a Delaunay triangulation of 2D vertices.\n%\n%  Discussion:\n%\n%    The routine constructs the Delaunay triangulation of a set of 2D vertices\n%    using an incremental approach and diagonal edge swaps.  Vertices are\n%    first sorted in lexicographically increasing (X,Y) order, and\n%    then are inserted one at a time from outside the convex hull.\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, integer POINT_NUM, the number of vertices.\n%\n%    Input, real P(2,POINT_NUM), the vertices.\n%\n%    Output, integer TRI_NUM, the number of triangles in the triangulation;\n%    TRI_NUM is equal to 2*POINT_NUM - NB - 2, where NB is the number\n%    of boundary vertices.\n%\n%    Output, integer TRI_VERT(3,TRI_NUM), the nodes that make up each triangle.\n%    The elements are indices of P.  The vertices of the triangles are\n%    in counter clockwise order.\n%\n%    Output, integer TRI_NABE(3,TRI_NUM), the triangle neighbor list.\n%    Positive elements are indices of TIL; negative elements are used for links\n%    of a counter clockwise linked list of boundary edges; LINK = -(3*I + J-1)\n%    where I, J = triangle, edge index; TRI_NABE(J,I) refers to\n%    the neighbor along edge from vertex J to J+1 (mod 3).\n%\n  tri_num = 0;\n  tri_vert = [];\n  tri_nabe = [];\n\n  tol = 100.0 * r8_epsilon ( );\n%\n%  Sort the vertices by increasing (x,y).\n%\n  indx = r82vec_sort_heap_index_a ( point_num, p );\n\n  p = r82vec_permute ( point_num, p, indx );\n%\n%  Make sure that the data points are \"reasonably\" distinct.\n%\n  m1 = 1;\n\n  for i = 2 : point_num\n\n    m = m1;\n    m1 = i;\n\n    k = 0;\n\n    for j = 1 : 2\n\n      cmax = max ( abs ( p(j,m) ), abs ( p(j,m1) ) );\n\n      if ( tol * ( cmax + 1.0 ) < abs ( p(j,m) - p(j,m1) ) )\n        k = j;\n        break\n      end\n\n    end\n\n    if ( k == 0 )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'R8TRIS2 - Fatal error!\\n' );\n      fprintf ( 1, '  Fails for point number I = %d\\n', i );\n      fprintf ( 1, '  M = %d\\n', m );\n      fprintf ( 1, '  M1 = %d\\n', m1 );\n      fprintf ( 1, '  X,Y(M)  = %f  %f\\n', p(1,m), p(2,m) );\n      fprintf ( 1, '  X,Y(M1) = %f  %f\\n', p(1,m1), p(2,m1) );\n      error ( 'R8TRIS2 - Fatal error!' )\n      return\n    end\n\n  end\n%\n%  Starting from points M1 and M2, search for a third point M that\n%  makes a \"healthy\" triangle (M1,M2,M)\n%\n  m1 = 1;\n  m2 = 2;\n  j = 3;\n\n  while ( 1 )\n\n    if ( point_num < j )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'R8TRIS2 - Fatal error!\\n' );\n      error ( 'R8TRIS2 - Fatal error!' )\n      return\n    end\n\n    m = j;\n\n    lr = lrline ( p(1,m), p(2,m), p(1,m1), p(2,m1), p(1,m2), p(2,m2), 0.0 );\n\n    if ( lr ~= 0 )\n      break\n    end\n\n    j = j + 1;\n\n  end\n%\n%  Set up the triangle information for (M1,M2,M), and for any other\n%  triangles you created because points were collinear with M1, M2.\n%\n  tri_num = j - 2;\n\n  if ( lr == -1 )\n\n    tri_vert(1,1) = m1;\n    tri_vert(2,1) = m2;\n    tri_vert(3,1) = m;\n    tri_nabe(3,1) = -3;\n\n    for i = 2 : tri_num\n\n      m1 = m2;\n      m2 = i+1;\n      tri_vert(1,i) = m1;\n      tri_vert(2,i) = m2;\n      tri_vert(3,i) = m;\n      tri_nabe(1,i-1) = -3 * i;\n      tri_nabe(2,i-1) = i;\n      tri_nabe(3,i) = i - 1;\n\n    end\n\n    tri_nabe(1,tri_num) = -3 * tri_num - 1;\n    tri_nabe(2,tri_num) = -5;\n    ledg = 2;\n    ltri = tri_num;\n\n  else\n\n    tri_vert(1,1) = m2;\n    tri_vert(2,1) = m1;\n    tri_vert(3,1) = m;\n    tri_nabe(1,1) = -4;\n\n    for i = 2 : tri_num\n      m1 = m2;\n      m2 = i+1;\n      tri_vert(1,i) = m2;\n      tri_vert(2,i) = m1;\n      tri_vert(3,i) = m;\n      tri_nabe(3,i-1) = i;\n      tri_nabe(1,i) = -3 * i - 3;\n      tri_nabe(2,i) = i - 1;\n    end\n\n    tri_nabe(3,tri_num) = -3 * tri_num;\n    tri_nabe(2,1) = -3 * tri_num - 2;\n    ledg = 2;\n    ltri = 1;\n\n  end\n%\n%  Insert the vertices one at a time from outside the convex hull,\n%  determine visible boundary edges, and apply diagonal edge swaps until\n%  Delaunay triangulation of vertices (so far) is obtained.\n%\n  top = 0;\n\n  for i = j+1 : point_num\n\n    m = i;\n    m1 = tri_vert(ledg,ltri);\n\n    if ( ledg <= 2 )\n      m2 = tri_vert(ledg+1,ltri);\n    else\n      m2 = tri_vert(1,ltri);\n    end\n\n    lr = lrline ( p(1,m), p(2,m), p(1,m1), p(2,m1), p(1,m2), p(2,m2), 0.0 );\n\n    if ( 0 < lr ) \n      rtri = ltri;\n      redg = ledg;\n      ltri = 0;\n    else\n      l = -tri_nabe(ledg,ltri);\n      rtri = floor ( l / 3 );\n      redg = mod(l,3) + 1;\n    end\n\n    [ ltri, ledg, rtri, redg ] = vbedg ( p(1,m), p(2,m), point_num, p, ...\n      tri_num, tri_vert, tri_nabe, ltri, ledg, rtri, redg );\n\n    n = tri_num + 1;\n    l = -tri_nabe(ledg,ltri);\n\n    while ( 1 )\n\n      t = floor ( l / 3 );\n      e = mod ( l, 3 ) + 1;\n      l = -tri_nabe(e,t);\n      m2 = tri_vert(e,t);\n\n      if ( e <= 2 )\n        m1 = tri_vert(e+1,t);\n      else\n        m1 = tri_vert(1,t);\n      end\n\n      tri_num = tri_num + 1;\n      tri_nabe(e,t) = tri_num;\n      tri_vert(1,tri_num) = m1;\n      tri_vert(2,tri_num) = m2;\n      tri_vert(3,tri_num) = m;\n      tri_nabe(1,tri_num) = t;\n      tri_nabe(2,tri_num) = tri_num - 1;\n      tri_nabe(3,tri_num) = tri_num + 1;\n      top = top + 1;\n\n      if ( point_num < top )\n        fprintf ( 1, '\\n' );\n        fprintf ( 1, 'R8TRIS2 - Fatal error!\\n' );\n        fprintf ( 1, '  Stack overflow.\\n' );\n        error ( 'R8TRIS2 - Fatal error!' )\n      end\n\n      work(top) = tri_num;\n\n      if ( t == rtri & e == redg )\n        break\n      end\n\n    end\n\n    tri_nabe(ledg,ltri) = -3 * n - 1;\n    tri_nabe(2,n) = -3 * tri_num - 2;\n    tri_nabe(3,tri_num) = -l;\n    ltri = n;\n    ledg = 2;\n\n    [ top, ltri, ledg, tri_vert, tri_nabe ] = swapec ( ...\n      m, top, ltri, ledg, point_num, p, tri_num, tri_vert, tri_nabe, work );\n\n  end\n%\n%  Now account for the sorting that we did.\n%\n  for i = 1 : 3\n    for j = 1 : tri_num\n      tri_vert(i,j) = indx ( tri_vert(i,j) );\n    end\n  end\n\n  indx = perm_inverse ( point_num, indx );\n\n  p = r82vec_permute ( point_num, p, indx );\n\n  return\nend\n", "meta": {"author": "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_scattered/r8tris2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5900788125255654}}
{"text": "% RecoverByGraInitial.m \n% RecoverByGra.m\n% -------------------------------------------------------------------\n% This function is just the joint of RecoverByGra and initial f0\n% Date:    17/03/2013\n% Last modified: 16/04/2015\n% -------------------------------------------------------------------\n\nfunction [imgRec, rms, gObj] = RecByGraInitial(img1, img2, ww1, ww2, dxdy, iter, res, alpha, iniMode)\n\n    % ------------ Check parameter --------------\n%     narginchk(9, 9);\n%     if size(img1, 3) ~=1 || size(img2, 3) ~=1,\n%         error('The image should be gray');\n%     end\n    % -------------------------------------------\n    switch lower(iniMode),\n        case 'avg',\n            f0 = (img1+img2)/2;\n        case 'weight',\n            f0 = ww1.*img1+ww2.*img2;\n        otherwise\n            error('There only two mode');\n    end\n    \n    [imgRec, rms, gObj] = RecoverByGra(f0, dxdy, iter, res, alpha);\n    \nend\n\n%%\nfunction [imgRec, rms, gObj] = RecoverByGra(imgOri, Obj, iter, res, alpha)\n\n    lp = [0 1 0;1 -4 1;0 1 0];\n    if isreal(Obj),\n%         disp('The original is the Laplace');\n        gObj = Obj;\n    else\n%         disp('The original is the Gradient');\n        gObj = LaplaceZ(Obj);\n    end\n    \n    rms = [];\n%     f0 = Boundary(imgOri, dxObj, dyObj);\n    f0 = imgOri;\n    for ii = 1:iter,\n%         f0 = Boundary(f0, dxObj, dyObj);\n        deltaF = imfilter(int16(f0), lp, 'replicate', 'corr');\n        deltaF = double(deltaF);\n        delta = alpha * (deltaF-gObj);\n\n        f1 = f0 + delta;\n\n        f1 = max(f1, 0);\n        f1 = min(f1, 255);\n\n\n        f0 = f1;  \n    end\n    \n    disp(['The ' num2str(ii) ' iteration is complete.']);\n    imgRec = f1;\nend\n\n%%\nfunction lap = LaplaceZ(IMGORGRA)\n\n    if isreal(IMGORGRA),\n%         disp('The input should be IMAGE')\n        lh=[0,  1, 0;...\n            1, -4, 1;...\n            0,  1, 0];\n        lap = imfilter(IMGORGRA, lh, 'replicate', 'corr');\n    else\n%         disp('The input should be GRADIENT');\n        fx=[0, 0, 0; 0, -1, 1; 0, 0, 0];\n        fy=[0, 0, 0;  0, -1, 0; 0, 1, 0];\n\n        dx = real(IMGORGRA);\n        dy = imag(IMGORGRA);\n\n        ddx = imfilter(dx, fx, 0, 'corr');\n        ddy = imfilter(dy, fy, 0, 'corr');\n\n        lap=ddx + ddy;\n    end\nend", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/MWGF_Image_Fusion_Codes/RecByGraInitial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.5900087635994009}}
{"text": "classdef ZXH_CF10 < PROBLEM\n% <multi/many> <real> <large/none> <constrained>\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    methods\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 Griewank function\n            h = 5*(sum((PopDec(:,M+1:end)-OptX).^2,2)-prod(cos(10*pi*(PopDec(:,M+1:end)-OptX)./repmat(sqrt(1:(D-M)),N,1)),2)+1);\n            % Step 4: Compute T_\n            T = (1 - Sx(:,1)).^2 + h;\n            % Step 5: Objectives (convex)\n            G      = 1-[ones(N,1) cumprod(sin(pi/2*THETA),2)] .* [cos(pi/2*THETA) ones(N,1)];\n            PopObj = G .* repmat((1+T),1,M);\n            % Step 6: Constraints\n            PopCon(:,1) = Sx(:,1) + h - 1; \n            PopCon(:,2) = -(Sx(:,1) + h - 1/4); \n            for i = 1 : obj.k\n                PopCon(:,i+2) = 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            T = zeros(size(R));\n            for i = obj.M-1 : -1 : 1\n                T(:,i) = atan((1-R(:,i+1))./(1-R(:,i))./cos(T(:,i+1)));\n            end\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                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_CF10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257655, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5900087588162218}}
{"text": "% SYNTAX:\n% data_dod = hmrR_MotionCorrectRLOESS(data_dod, span, turnon)\n%\n% UI NAME:\n% Motion_Correct_RLOESS\n%\n% DESCRIPTION:\n%\n% INPUTS:\n% data_dod: SNIRF data structure containing delta_OD\n% span:\n% turnon:   Optional argument to enable/disable this function in a processing stream chain\n%\n% OUTPUTS:\n% data_dod: SNIRF data structure containing delta_OD after motion correction,\n%           same size as dod (Channels that are not in the active ml remain unchanged)\n%\n% USAGE OPTIONS:\n% Motion_Correct_RLOESS: dod = hmrR_MotionCorrectRLOESS(dod, span, turnon)\n%\n% PARAMETERS:\n% span: 0.02\n% turnon: 1\n%\n% PREREQUISITES:\n% Intensity_to_Delta_OD: dod = hmrR_Intensity2OD( intensity )\n%\n% LOG:\n%\nfunction data_dod = hmrR_MotionCorrectRLOESS(data_dod, span, turnon)\n\n% span = 0.02 (default)\nif span<0\n    return\nend\n\n% Meryem Yucel, Oct, 2017\n% Added turn on/off option Meryem Nov 2017\nif ~exist('turnon','var')\n    turnon = 1;\nend\nif turnon==0\n    return;\nend\n\nfor iBlk=1:length(data_dod)\n    dod = data_dod(iBlk).GetDataTimeSeries();\n    t   = data_dod(iBlk).GetTime();\n    for i=1:size(dod,2)\n        dod(:,i) = smooth(t, dod(:,i), span, 'rloess');\n    end\n    data_dod(iBlk).SetDataTimeSeries(dod);    \nend", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/FuncRegistry/UserFunctions/hmrR_MotionCorrectRLOESS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5900087454863461}}
{"text": "function R = unidrndKPM(min, max, nr, nc)\n\nif nargin < 3\n  nr = 1; nc = 1;\nend\n\nR = unidrnd(max-min+1, nr, nc) + (min-1);\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/KPMstats/unidrndKPM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5900087359199875}}
{"text": "function jaccard = Jaccard_Index(SEG, GT)  \n    % SEG, GT are the binary segmentation and ground truth areas, respectively.  \n    % jaccard index  \n    jaccard = double(sum(uint8(SEG(:) & GT(:)))) / double(sum(uint8(SEG(:) | GT(:))));  \nend  ", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/benchmarks/Jaccard_Index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5899554738959587}}
{"text": "% Lifted matrices for MPC on horizon N\nfunction [Ab Bb] = createMPCmatrices(A,B,N,includex0)\n    if(~exist('includex0','var'))\n        includex0 = 0; %first block rows of Ab and Bb corresponding to x0 removed\n    end\n    \n    n = size(A,1);\n    Ab = zeros((N+1)*n, n);\n    Ab(1:n,:) = eye(n,n);\n    for i = 2:N+1\n        if( size(A,1) > 1000 )\n            i\n        end\n        %Ab((i-1)*n+1:i*n,:) = A^(i-1);\n        Ab((i-1)*n+1:i*n,:) = Ab((i-2)*n+1:(i-1)*n,:)*A;\n    end\n    if(includex0 == 0)\n        Ab = Ab(n+1:end,:); % Seems to take a lot of time if A is huge, possible to speedup\n    end\n    \n    for q = 1:length(B)\n        m = size(B{q},2);\n        Bb{q} = zeros((N+1)*n, N*m);\n        for i = 2:N+1\n            Bb{q}((i-1)*n+1:i*n,:) = A * Bb{q}((i-2)*n+1:(i-1)*n,:);\n            Bb{q}((i-1)*n+1:n*i,(i-2)*m+1:m*(i-1)) = B{q};\n        end\n        if(includex0 == 0)\n            Bb{q} = Bb{q}(n+1:end,:);\n        end\n    end\n\n\nend", "meta": {"author": "arbabiha", "repo": "KoopmanMPC_for_flowcontrol", "sha": "4581c284bed5420fee7a7e9a58590fe93a196c97", "save_path": "github-repos/MATLAB/arbabiha-KoopmanMPC_for_flowcontrol", "path": "github-repos/MATLAB/arbabiha-KoopmanMPC_for_flowcontrol/KoopmanMPC_for_flowcontrol-4581c284bed5420fee7a7e9a58590fe93a196c97/thehood/createMPCmatrices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5899430183368355}}
{"text": "% Fit a piece-wise linear regression model.\n% Here is the model\n%\n%  X \\\n%  | |\n%  Q |\n%  | /\n%  Y\n%\n% where all arcs point down.\n% We condition everything on X, so X is a root node. Q is a softmax, and Y is a linear Gaussian.\n% Q is hidden, X and Y are observed.\n\nX = 1;\nQ = 2;\nY = 3;\ndag = zeros(3,3);\ndag(X,[Q Y]) = 1;\ndag(Q,Y) = 1;\nns = [1 2 1]; % make X and Y scalars, and have 2 experts\ndnodes = [2];\nonodes = [1 3];\nbnet = mk_bnet(dag, ns, 'discrete', dnodes, 'observed', onodes);\n\nIRLS_iter = 10;\nclamped = 0;\n\nbnet.CPD{1} = root_CPD(bnet, 1);\n\n% start with good initial params\nw = [-5 5];  % w(:,i) is the normal vector to the i'th decisions boundary\nb = [0 0];  % b(i) is the offset (bias) to the i'th decisions boundary\n\nmu = [0 0];\nsigma = 1;\nSigma = repmat(sigma*eye(ns(Y)), [ns(Y) ns(Y) ns(Q)]);\nW = [-1 1];\nW2 = reshape(W, [ns(Y) ns(X) ns(Q)]);\n\nbnet.CPD{2} = softmax_CPD(bnet, 2, w, b,  clamped, IRLS_iter);\nbnet.CPD{3} = gaussian_CPD(bnet, 3, 'mean', mu, 'cov', Sigma, 'weights', W2);\n\n\nengine = jtree_inf_engine(bnet);\n\nevidence = cell(1,3);\nevidence{X} = 0.68;\n\nengine = enter_evidence(engine, evidence);\n\nm = marginal_nodes(engine, Y);\nm.mu\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/mixexp3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5899430074117822}}
{"text": "% qrtimax() -  perform Quartimax rotation of rows of a data matrix.\n%\n% Usage: >> [Q,B] = qrtimax(data);   \n%        >> [Q,B] = qrtimax(data,tol,'[no]reorder');\n%\n% Inputs:\n%        data      - input matrix\n%        tol       - the termination tolerance {default: 1e-4}\n%        noreorder - rotate without negation/reordering\n%\n% Outputs:\n%        B         - B=Q*A the Quartimax rotation of A\n%        Q         - the orthogonal rotation matrix\n%\n% Author: Sigurd Enghoff, CNL / Salk Institute, 6/18/98\n\n% Copyright (C) Sigurd Enghoff - CNL / Salk Institute, La Jolla 6/18/98\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% Reference: Jack O. Nehaus and Charles Wrigley (1954) \n% The Quartimax Method: an analytic approach to orthogonal \n% simple structure, Br J Stat Psychol, 7:81-91.\n\n% 01-25-02 reformated help & license -ad \n\nfunction [Q,B] = qrtimax(A,tol,reorder)\n\nif nargin < 1\n\thelp qrtimax\n\treturn\nend\n\nDEFAULT_TOL = 1e-4;\nMAX_ITERATIONS = 50;\n\nif nargin < 3\n\treorder = 1;\nelseif isempty(reorder) | reorder == 0\n\treorder = 1; % set default\nelse\n\treorder = strcmp('reorder',reorder);\nend\n\nif nargin < 2\n\teps1 = DEFAULT_TOL;\n\teps2 = DEFAULT_TOL;\nelse\n\teps1 = tol;\n\teps2 = tol;\nend\n\n% Do unto 'Q' what is done to A\n\nQ = eye(size(A,1));\n\n% Compute the cross-products of the rows of the squared loadings,\n% i.e. the cost function.\n%\n%  ---  ---\n%  \\    \\     2    2\n%  /    /    f    f\n%  ---  ---   ij   ik\n%   i   j<k\n%\n%  See reference, p. 85, line 3\n\nB = tril((A.^2)*(A.^2)');\ncrit = [sum(sum(B)) - trace(B) , 0];\n\n% Initialize variables\n\ninoim = 0;\niflip = 1;\nict = 0;\n\n% Main iterative loop: keep looping while no two consecutive trials \n% satisfy tolerance constraint AND less than MAX_ITERATIONS trials \n% AND one or more rotations were performed during last trial.\n\nwhile inoim < 2 & ict < MAX_ITERATIONS & iflip,\n\tiflip = 0;\n\n% Run through all combinations of j and k\n\n\tfor j = 1:size(A,1)-1,\n\t\tfor k = j+1:size(A,1),\n%\n%          ---                                   ---\n%          \\                2     2              \\       2     2  2      2   2\n% fnum = 4 /    [f   f    (f   - f  )]  , fden = /    [(f   - f  )  - 4 f   f  ]\n%          ---    ki  kj    ki    kj             ---     ki    kj        ki  kj\n%           k                                     k\n%\n%  See equation (5)\n\n\t\t\tu = A(j,:) .^ 2 - A(k,:) .^2;\n\t\t\tv = 2 * A(j,:) .* A(k,:);\n\t\t\tc = sum(u .^ 2 - v .^ 2);\n\t\t\td = sum(u .* v);\n\n\t\t\tfden = c;\n\t\t\tfnum = 2 * d;\n\n% Skip rotation if angle is too small\n\n\t\t\tif abs(fnum) > eps1 * abs(fden)\n\t\t\t\tiflip = 1;\n\t\t\t\tangl = atan2(fnum, fden);\n\n% Set angle of rotation according to Table I\n\n\t\t\t\tif fnum > 0\n\t\t\t\t\tif fden > 0\n\t\t\t\t\t\tangl = .25 * angl;\n\t\t\t\t\telse\n\t\t\t\t\t\tangl = .25 * (pi - angl);\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\tif fden > 0\n\t\t\t\t\t\tangl = .25 * (2 * pi - angl);\n\t\t\t\t\telse\n\t\t\t\t\t\tangl = .25 * (pi + angl);\n\t\t\t\t\tend\n\t\t\t\tend\n\n% Perform rotation\n\n\t\t\t\ttmp    =  cos(angl) * Q(j,:) + sin(angl) * Q(k,:);\n\t\t\t\tQ(k,:) = -sin(angl) * Q(j,:) + cos(angl) * Q(k,:);\n\t\t\t\tQ(j,:) = tmp;\n\n\t\t\t\ttmp    =  cos(angl) * A(j,:) + sin(angl) * A(k,:);\n\t\t\t\tA(k,:) = -sin(angl) * A(j,:) + cos(angl) * A(k,:);\n\t\t\t\tA(j,:) = tmp;\n\t\t\tend\n\t\tend\n\tend\n\n% Compute cost function.\n\n\tB = tril((A.^2)*(A.^2)');\n\tcrit = [sum(sum(B)) - trace(B) , crit(1)];\n\t\n\tinoim = inoim + 1;\n\tict = ict + 1;\n\n\tfprintf('#%d - crit = %g\\n',ict,(crit(1)-crit(2))/crit(1));\n\n% Check relative change of cost function (termination criterion).\n\n\tif (crit(1) - crit(2)) / crit(1) > eps2\n\t\tinoim = 0;\n\tend\nend\n\n% Reorder and negate if required. Determine new row order based on\n% row norms and reorder accordingly. Negate those rows in which the\n% accumulated sum is negative.\n\nif reorder\n\tfprintf('Reordering rows...');\n\t[fnorm index] = sort(sum(A'.^2));\n\tQ = Q .* ((2 * (sum(A') > 0) - 1)' * ones(1, size(Q,2)));\n\tA = A .* ((2 * (sum(A') > 0) - 1)' * ones(1, size(A,2)));\n\tQ = Q(fliplr(index),:);\n\tA = A(fliplr(index),:);\n\tfprintf('\\n');\nelse\n\tfprintf('Not reordering rows.\\n');\nend\n\nB=A;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/miscfunc/qrtimax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.589943005664947}}
{"text": "%  Figure 6.68      Feedback Control of Dynamic Systems, 6e\n%                   Franklin, Powell, Emami\n% \n\nclear all\n%close all;\nclf\n\nk=10;\nnum=k;\nden=[1 1 0];\nnum=conv(num,[10 1]);\nden=conv(den,[100 1]);\nnumcl=[1 0.1];\ndencl=[1 1.01 1.01 0.1];\nt=0:.2:50;\ny=step(numcl,dencl,t);\n%subplot(2,1,1)\nplot(t,y);\nxlabel('Time (sec)');\nylabel('y');\ntitle('Fig. 6.68 Step response of lag-compensation design.');\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_68.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5899383585463938}}
{"text": "% MHSWTRANS\n%\n%  MCMC Metropolis-Hastings transition function that\n%  utilizes the Swendsen-Wang proposal distribution.\n%  A - The current joint assignment.  This should be\n%      updated to be the next assignment\n%  G - The network\n%  F - List of all factors\n%  variant - a number (1 or 2) indicating the variant of Swendsen-Wang to use.  In variant 1,\n%            all the q_{i,j}'s are equal\n%\n% Copyright (C) Daphne Koller, Stanford University, 2012\n\nfunction A = MHSWTrans(A, G, F, variant)\n\n%%%%%%%%%%%%%% Get Proposal %%%%%%%%%%%%%%\n% Prune edges from q_list if the nodes don't have the same current value\nq_list = G.q_list;\nq_keep_indx = find(A(q_list(:, 1)) == A(q_list(:, 2)));\nq_list = q_list(q_keep_indx, :);\n% Select edges at random based on q_list\nselected_edges_q_list_indx = find(q_list(:, 3) > rand(size(q_list,1), 1));\nselected_edges = q_list(selected_edges_q_list_indx, 1:2);\n% Compute connected components over selected edges\nSelEdgeMat = sparse([selected_edges(:,1)'; selected_edges(:,2)'],...\n                    [selected_edges(:,2)'; selected_edges(:,1)'],...\n                    1, length(G.names), length(G.names));\n\n[var2comp, cc_sizes] = scomponents(SelEdgeMat);\nnum_cc = length(cc_sizes);\n\n\n% Select a connected component (the book calls this Y)\nselected_cc = ceil(rand() * num_cc);\nselected_vars = find(var2comp == selected_cc);\n% Check that the dimensions are all the same and they have the same current assignment\nassert(length(unique(G.card(selected_vars))) == 1);\nassert(length(unique(A(selected_vars))) == 1);\n\n% Pick a new label via sampling\nold_value = A(selected_vars(1));\nd = G.card(selected_vars(1));\nLogR = zeros(1, d);\nif variant == 1\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % YOUR CODE HERE\n    % Specify the log of the distribution (LogR) from \n    % which a new label for Y is selected for variant 1 \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    LogR = ones(1,d).*log(1/d);\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif variant == 2\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % YOUR CODE HERE\n    % Specify the log of the distribution (LogR) from \n    % which a new label for Y is selected for variant 2\n    %\n    % We suggest you read through the preceding code\n    % before implementing this, one of the generated\n    % data structures may be useful in implementing this section\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    LogR = BlockLogDistribution(selected_vars,G,F,A);\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelse\n    disp('WARNING: Unrecognized Swendsen-Wang Variant');\nend\n\n% Sample the new value from the distribution R\nnew_value = randsample(d, 1, true, exp(LogR));\nA_prop = A;\nA_prop(selected_vars) = new_value;\n\n% Get the log-ratio of the probability of picking the connected component Y given A_prop over A\nlog_QY_ratio = 0.0;\nfor i = 1:size(G.q_list, 1)  % Iterate through *all* edges, not just the ones we selected earlier\n    u = G.q_list(i, 1);\n    v = G.q_list(i, 2);\n    if length(intersect([u, v], selected_vars)) == 1  % the edge is from Y to outside-Y\n        if A(u) == old_value && A(v) == old_value\n            log_QY_ratio = log_QY_ratio - log(1 - G.q_list(i, 3));\n        end\n        if A_prop(u) == new_value && A_prop(v) == new_value\n            log_QY_ratio = log_QY_ratio + log(1 - G.q_list(i, 3));\n        end\n    end\nend\n\np_acceptance = 0.0;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% YOUR CODE HERE\n% Compute acceptance probability\n%\n% Read through the preceding code to understand\n% how to find the previous and proposed assignments\n% of variables, as well as some ratios used in computing\n% the acceptance probabilitiy.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nlnum = LogProbOfJointAssignment(F,A_prop);\nlden = LogProbOfJointAssignment(F,A);\n\n\np_acceptance = min(1,exp(lnum-lden+log_QY_ratio+LogR(old_value)-LogR(new_value)));\n%p_acceptance = min(1,exp(log_QY_ratio));\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Accept or reject proposal\nif rand() < p_acceptance\n    %disp('Accepted');\n    A = A_prop;\nend\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/5.Approximate Inference/MHSWTrans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5899383581409267}}
{"text": "classdef SMMOP2 < PROBLEM\n% <multi/many> <real> <large/none> <multimodal> <sparse/none>\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            \tg(:,i) =  sum(g1(X(:,M+(i-1)*S:M+i*S-1),pi/3),2)+sum(g3(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),X(:,1:M-1)],2)).*[ones(N,1),1-X(:,M-1:-1:1)];\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        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            if obj.M == 2\n                a = linspace(0,1,100)';\n                R = [a,1-a];\n            elseif obj.M == 3\n                a = linspace(0,1,10)';\n                R = {a*a',a*(1-a'),(1-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 = g1(x,t)\n    g = (x-t).^2;\nend\n\nfunction g = g3(x,t)\n    g = 4-(x-t)-4./exp(100*(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/SMMOP2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5899383557286714}}
{"text": "%randsample(V,n,true,distribution) returns a set of n values sampled\n% at random from the integers 1 through V with replacement using distribution\n% 'distribution'\n% \n% replacing true with false causes sampling w/out replacement\n% omitting the distribution causes a default to the uniform distribution\n%\n% Copyright (C) Daphne Koller, Stanford University, 2012\n\nfunction [v] = randsample(vals,numSamp,replace,weightIncrements)\n\n  vals = vals(:);\n  if(length(vals)==1)\n    maxval = vals;\n    vals = 1:maxval;\n  else\n    maxval = length(vals);\n  end\n\n  if(exist('replace','var')~=1)\n    replace = true;\n  end\n  if(exist('weightIncrements','var')~=1)\n    weightIncrements = (1/maxval)*ones(maxval,1);\n    weights = (1/maxval):(1/maxval):1;\n  else\n    weightIncrements = weightIncrements(:)/sum(weightIncrements(:));\n    weights = zeros(size(weightIncrements));\n    weights(1) = weightIncrements(1);\n    for i = 2:length(weightIncrements)\n      weights(i) = weightIncrements(i)+weights(i-1);\n    end\n  end\n  \n  weights = [0; weights(:)];\n  \n  %now do the sampling\n  v = [];\n  probs = rand(numSamp,1);\n  for i=1:numSamp\n    curInd = find((weights(1:end-1)<=probs(i))&(weights(2:end)>=probs(i)));\n    v(end+1)=vals(curInd);\n    if(replace~=true)\n      vals(curInd)=[];\n      weightIncrements(curInd)=[];\n      weightIncrements = weightIncrements(:)/sum(weightIncrements(:));\n      weights = zeros(size(weightIncrements));\n      for i = 2:length(weightIncrements)\n        weights(i) = weightIncrements(i)+weights(i-1);\n      end\n    end\n  end\n\n\nend\n", "meta": {"author": "anhncs", "repo": "Probabilistic-Graphical-Models", "sha": "7fd4ef255db59ecbfe1a134cadbc4be5ca839894", "save_path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models", "path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models/Probabilistic-Graphical-Models-7fd4ef255db59ecbfe1a134cadbc4be5ca839894/5.Approximate Inference/randsample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5899383525054819}}
{"text": "% test minq.m, minqdef.m, minqsep.m\n\ndisp('test of minq.m')\n\nn=7;\nm=10;\np=0.8;\t\t% approx. fraction of activities and equalities\nnewdata=1;\t% new data?\n\nif newdata,\n  % create random data satisfying the KKT conditions\n  A=rand(m,n);\n  c=rand(n,1);\n  d=rand(n,1);\n  ydes=rand(m,1)-p;\n  act=( ydes>p );\t\t% indices of nonactive inequalities\n  ydes(act)=0*ydes(act);\n  eq=( ydes<0 );\t\t% indices of equations\n  xdes=(A'*ydes-c)./d;\n  res=rand(m,1);\n  res(~act)=0*res(~act);\n  b=A*xdes-res;\n  save minq_data\n prt=0;\nelse\n  load minq_data\n  warning debug\n  prt=1;\nend;\n\n\nfor cas=1:2,\n  if cas==1, \n    disp('test of minqsep.m');\n    [x,y,ier]=minqsep(c,d,A,b,eq,prt);\n  else        \n    disp('test of minqdef.m');\n    [x,y,ier]=minqdef(c,diag(d),A,b,eq,prt);\n  end;\n\n  compldes=[ydes,A*xdes-b];\n  compl=[y,A*x-b];\n  act_eq=[act,eq]'\n  ydif=[ydes,y]\n  disp('usually two equal columns');\n  disp('but sometimes the dual is not unique')\n  xdif=[xdes,x]\n  disp('xdif should have two equal columns')\n  ier\n  if cas==2, break; end;\n  cont=input('enter return (next test) or 0 (quit)>');\n  if isempty(cont),\t% continue\n  elseif cont==0,      return; \n  end;\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/minq5/minq_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.589938352100014}}
{"text": "classdef CEC2013_F5 < PROBLEM\n% <single> <real> <large>\n% 7-nonseparable, 1-separable shifted and rotated Rastrigin's function\n\n%------------------------------- Reference --------------------------------\n% X. Li, K. Tang, M. N. Omidvar, Z. Yang, and K. Qin, Benchmark functions\n% for the CEC'2013 special session and competition on large-scale global\n% optimization, RMIT University, Australia, 2013.\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        Xopt;\t% Optimal decision vector\n        R25;    % Rotation matrices\n        R50;\n        R100;\n        p;      % Rank of decision variables\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2013.mat'),'Data');\n            obj.Xopt = Data{5}.xopt;\n            obj.R25  = Data{5}.R25;\n            obj.R50  = Data{5}.R50;\n            obj.R100 = Data{5}.R100;\n            obj.p    = Data{5}.p;\n            obj.M    = 1;\n            obj.D    = 1000;\n            obj.lower    = zeros(1,obj.D) - 5;\n            obj.upper    = zeros(1,obj.D) + 5;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            S = [50 25 25 100 50 25 25 700];\n            W = [1.81e-1 9.08e3 2.43e1 1.86e-6 1.77e4 2.82e-4 1.53e-2 1];\n            PopDec = PopDec - repmat(obj.Xopt,size(PopDec,1),1);\n            PopObj = zeros(size(PopDec,1),1);\n            for i = 1 : length(S)\n                loc = obj.p(sum(S(1:i-1))+1:sum(S(1:i)));\n                switch S(i)\n                    case 25\n                        PopDec(:,loc) = PopDec(:,loc)*obj.R25;\n                    case 50\n                        PopDec(:,loc) = PopDec(:,loc)*obj.R50;\n                    case 100\n                        PopDec(:,loc) = PopDec(:,loc)*obj.R100;\n                end\n                PopObj = PopObj + W(i)*Rastrigin(Tdiag(Tasy(Tosz(PopDec(:,loc)),0.2),10));\n            end\n        end\n    end\nend\n\nfunction F = Rastrigin(X)\n    F = sum(X.^2-10*cos(2*pi*X)+10,2);\nend\n\nfunction Z = Tosz(X)\n    X1 = zeros(size(X));\n    X1(X~=0) = log(abs(X(X~=0)));\n    C1 = zeros(size(X)) + 5.5;\n    C1(X>0) = 10;\n    C2 = zeros(size(X)) + 3.1;\n    C2(X>0) = 7.9;\n    Z = sign(X).*exp(X1+0.049*(sin(C1.*X1)+sin(C2.*X1)));\nend\n\nfunction Z = Tasy(X,beta)\n    Z = X.^(1+repmat(beta*linspace(0,1,size(X,2)),size(X,1),1).*sqrt(X));\n    Z(X<=0) = X(X<=0);\nend\n\nfunction Z = Tdiag(X,alpha)\n    Z = X.*repmat(sqrt(alpha).^linspace(0,1,size(X,2)),size(X,1),1);\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/Single-objective optimization/CEC 2013/CEC2013_F5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5899383468700367}}
{"text": "function [iCM, cCM, oCM, sm] = Itti_Saliency(img,varargin)\n\nverbose=0;\npictures=0;\n\n% Load image\nif verbose\n    fprintf('Loading %s\\n',filename);\nend\nimage=img;\nif pictures\n    ShowImage(1,image,'Image');\nend\nimage=double(image);\n\n% Extract luminance and color channels\nif verbose\n    fprintf('Extracting early channels\\n');\nend\n\nif length(size(image)) == 3 \n\t[iIm,rIm,gIm,bIm,yIm]=ExtractChannels(image);\n    \n   % if max(max(rIm))>0 && max(max(gIm))>0 && max(max(bIm))>0\n     if max(max(rIm))>0 && max(max(gIm))>0\n        % Create pyramids\n        if verbose\n            fprintf('Creating pyramids\\n');\n        end\n        iPyr=GaussianPyramid(iIm);\n        rPyr=GaussianPyramid(rIm);\n        gPyr=GaussianPyramid(gIm);\n        bPyr=GaussianPyramid(bIm);\n        yPyr=GaussianPyramid(yIm);\n        oPyr=OrientationPyramid(iPyr);\n\n        % Create feature maps\n        if verbose\n            fprintf('Creating feature maps\\n');\n        end\n        iFM=IntensityFeatureMap(iPyr);\n        [rgFM byFM]=ColorFeatureMap(rPyr,gPyr,bPyr,yPyr);\n        oFM=OrientationFeatureMap(oPyr);\n\n        % Create conspicuity maps\n        if verbose\n            fprintf('Conspicuity maps\\n');\n        end\n        [iCM cCM oCM]=ConspicuityMap(iFM,oFM, rgFM,byFM);\n        if pictures\n            ShowImage(2,iCM,'Intensity CM');\n            ShowImage(3,cCM,'Color CM');\n            ShowImage(4,oCM,'Orientation CM');\n        end\n\n        % Create saliency map\n        if verbose\n            fprintf('Saliency map\\n');\n        end\n        sm=SaliencyMap(iCM,oCM,cCM);\n\n   %     s=size(image);\n   %     s=s(1:2);\n   %    sm=imresize(sm,s,'bilinear');\n   %    sm=sm/max(max(sm))*255;\n        if pictures\n            ShowImage(5,sm,'Saliency');\n        end\n    else\n        iIm = rgb2hsv(image);\n        iIm = iIm(:,:,3);\n        iPyr=GaussianPyramid(iIm);\n        oPyr=OrientationPyramid(iPyr);\n        \n        if verbose\n            fprintf('Creating feature maps\\n');\n        end\n        iFM=IntensityFeatureMap(iPyr);\n        oFM=OrientationFeatureMap(oPyr);\n        \n        % Create conspicuity maps\n        if verbose\n            fprintf('Conspicuity maps\\n');\n        end\n        [iCM cCM oCM]=ConspicuityMap(iFM,oFM);\n        if pictures\n            ShowImage(2,iCM,'Intensity CM');\n            ShowImage(3,oCM,'Orientation CM');\n        end\n        if verbose\n            fprintf('Saliency map\\n');\n        end\n        sm=SaliencyMap(iCM,oCM);        \n        s=size(image);\n        s=s(1:2);\n        sm=imresize(sm,s,'bilinear');\n        if pictures\n            ShowImage(4,sm,'Saliency');\n        end\n    end\nelse\n        iIm = image;\n        iPyr=GaussianPyramid(iIm);\n        oPyr=OrientationPyramid(iPyr);\n        \n        if verbose\n            fprintf('Creating feature maps\\n');\n        end\n        iFM=IntensityFeatureMap(iPyr);\n        oFM=OrientationFeatureMap(oPyr);\n        \n        % Create conspicuity maps\n        if verbose\n            fprintf('Conspicuity maps\\n');\n        end\n        [iCM cCM oCM]=ConspicuityMap(iFM,oFM);\n        if pictures\n            ShowImage(2,iCM,'Intensity CM');\n            ShowImage(3,oCM,'Orientation CM');\n        end\n        if verbose\n            fprintf('Saliency map\\n');\n        end\n        sm=SaliencyMap(iCM,oCM);        \n        s=size(image);\n        s=s(1:2);\n        sm=imresize(sm,s,'bilinear');\n        if pictures\n            ShowImage(4,sm,'Saliency');\n        end\nend\n\n% ------------------------------------------------------------------------\n% ExtractChannels\n% ------------------------------------------------------------------------\n\nfunction [iIm,rIm,gIm,bIm,yIm]=ExtractChannels(image)\n\nr = image(:,:,1);\ng = image(:,:,2);\nb = image(:,:,3);\n\niIm = (r+g+b)/3;\n\n% iIm = rgb2hsv(image);\n% iIm = iIm(:,:,3);\n\n% Normalize (see Itti, Koch & Niebur, p. 1255)\nnormalizer = iIm;\nmaxIm = max(max(iIm));\n\nzeroentry = find(normalizer == 0);\nnormalizer(zeroentry) = 1e-10;\nt = iIm < maxIm/10;\nr = r ./ normalizer;\ng = g ./ normalizer;\nb = b ./ normalizer; \nr(t) = 0;\ng(t) = 0;\nb(t) = 0;\n\n% Channels R,G,B,Y\nrIm = r - (g + b)/2;\ngIm = g - (r + b)/2;\nbIm = b - (r + g)/2; % negtive \nyIm = (r + g)/2 - abs(r - g)/2 - b;\nrIm(rIm<0) = 0;\ngIm(gIm<0) = 0;\nbIm(bIm<0) = 0;\nyIm(yIm<0) = 0;\n\n% ------------------------------------------------------------------------\n% GaussianPyramid\n% ------------------------------------------------------------------------\n\nfunction pyramid = GaussianPyramid(image)\n\npyramid{1} = image;\n\nfor level=2:9\n    im = gausmooth(pyramid{level-1});\n    s=ceil(size(pyramid{level-1})/2.0);\n\tpyramid{level} = imresize(im,s);\nend\n\n% ------------------------------------------------------------------------\n% GaussianSmooth\n% ------------------------------------------------------------------------\nfunction im = gausmooth(im)\n\n[m,n] = size(im);\nGaussianDieOff = .0001;  \npw = 1:30; \nssq = 2;\nwidth = find(exp(-(pw.*pw)/(2*ssq))>GaussianDieOff,1,'last');\nif isempty(width)\n    width = 1;  % the user entered a really small sigma\nend\nt = (-width:width);\ngau = exp(-(t.*t)/(2*ssq))/sum(exp(-(t.*t)/(2*ssq)));     \n\nim = imfilter(im, gau,'conv','replicate');   % run the filter accross rows\nim = imfilter(im, gau','conv','replicate'); % and then accross columns\n% im = im/max(max(im));\n\n% ------------------------------------------------------------------------\n% OrientationPyramid\n% ------------------------------------------------------------------------\n\nfunction oPyr = OrientationPyramid(iPyr)\n\ngabor{1}=gabor_fn(1,0.5,0,2,0);\ngabor{2}=gabor_fn(1,0.5,0,2,pi/4);\ngabor{3}=gabor_fn(1,0.5,0,2,pi/2);\ngabor{4}=gabor_fn(1,0.5,0,2,pi*3/4);\n\n% gabor{1}=gabor_fn(1,1,0,2.333,0);\n% gabor{2}=gabor_fn(1,1,0,2.333,pi/4);\n% gabor{3}=gabor_fn(1,1,0,2.333,pi/2);\n% gabor{4}=gabor_fn(1,1,0,2.333,pi*3/4);\n\nfor l=3:9\n    for o=1:4\n        oPyr{l,o}=imfilter(iPyr{l},gabor{o},'symmetric');\n    end\nend\n\n% ------------------------------------------------------------------------\n% GaborFilterBank (with complex Gabors)\n% ------------------------------------------------------------------------\n\n\nfunction 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);\n%imshow(gb/2+0.5);\n\nfunction gabor = GaborFilterBank\n\n% low-pass filter for 5 x 5 kernels\nl=[1 3 8 3 1]/16.0;\nlpf = l'*l;\nssd = 1;\n\n%4 orientations\n% for o=1:4\n%     angle=(o-1)*pi/4;\n%     c=cos(angle);\n%     s=sin(angle);\n%     for x=1:5\n%         for y=1:5\n%             m=pi/2*(c*(x-3)+s*(y-3));\n%             kernel(y,x)=cos(m)+i*sin(m);\n%         end\n%     end\n%     gabor{o}=kernel .* lpf;\n% end\n\n\nfor o = 1:4\n    sz_x=fix(6*sqrt(ssd));\n    sz_y=fix(6*sqrt(ssd));\n\n    [x y]=meshgrid(-fix(sz_x/2):fix(sz_x/2),fix(-sz_y/2):fix(sz_y/2));\n\n    % Rotation \n    angle=(o-1)*pi/4;\n    x_theta=x*cos(angle)+y*sin(angle);\n    y_theta=-x*sin(angle)+y*cos(angle);\n\n    match = find(x_theta==0);\n    x_theta(match) = x_theta(match) + 1e-10;\n    gabor{o}=exp(-.5*(x_theta.^2/ssd+y_theta.^2/ssd)).*cos(2*pi./x_theta);\nend\n\n% ------------------------------------------------------------------------\n% IntensityFeatureMap\n% ------------------------------------------------------------------------\n\nfunction iFM = IntensityFeatureMap(iPyr)\n\nfor c=3:5\n    for delta = 3:4\n        s = c + delta;\n        iFM{c,s} = abs(Subtract(iPyr{c}, iPyr{s}));\n    end\nend\n\n% ------------------------------------------------------------------------\n% ColorFeatureMap\nfunction [rgFM, byFM] = ColorFeatureMap(rPyr, gPyr, bPyr, yPyr)\n\nfor c=3:5\n    for delta = 3:4\n        s = c + delta;\n        rgFM{c,s} = abs(Subtract(rPyr{c}-gPyr{c}, gPyr{s}-rPyr{s}));\n        byFM{c,s} = abs(Subtract(bPyr{c}-yPyr{c}, yPyr{s}-bPyr{s}));\n    end\nend\n\n% ------------------------------------------------------------------------\n% OrientationFeatureMap\n% ------------------------------------------------------------------------\n\nfunction oFM = OrientationFeatureMap(oPyr)\n\nfor c=3:5\n    for delta = 3:4\n        s = c + delta;\n        for o=1:4\n            oFM{c,s,o}=abs(Subtract(oPyr{c,o},oPyr{s,o}));\n        end\n    end\nend\n\n% ------------------------------------------------------------------------\n% ConspicuityMap\n% ------------------------------------------------------------------------\n\nfunction [iCM,cCM,oCM] = ConspicuityMap(varargin)\n\niFM = varargin{1};\noFM = varargin{2};\n\ndim=size(iFM{3,6});\niCM=zeros(dim);\nfor c=3:5\n    for delta = 3:4\n        s = c + delta;\n%         weight=s*c;\n        weight=1;\n        iCM = Add(iCM,weight*Normalize(iFM{c,s}));\n    end\nend\n\noCM=zeros(dim);\nfor c=3:5\n    for delta = 3:4\n        s = c + delta;\n%         weight=s*c;\n        weight=1;\n        for o=1:4\n            oCM=Add(oCM,weight*Normalize(oFM{c,s,o}));\n        end\n    end\nend\n\ncCM=zeros(dim);\nif length(varargin) == 4\n    rgFM = varargin{3};\n    byFM = varargin{4};    \n    for c=3:5\n        for delta = 3:4\n            s = c + delta;\n    %         weight=s*c;\n            weight=1;\n            cCM = Add(cCM,weight*Normalize(rgFM{c,s}));\n            cCM = Add(cCM,weight*Normalize(byFM{c,s}));\n        end\n    end\nend\n\n% ------------------------------------------------------------------------\n% Normalize\n% ------------------------------------------------------------------------\n\nfunction normalized = Normalize(map)\n\n% Normalize map to range [0..1]\nminValue = min(min(map));\nmap = map-minValue;\nmaxValue = max(max(map));\nif maxValue>0\n    map = map/maxValue;\nend\n\n% Position of local maxima\nlmax = LocalMaxima(map);\n\n% Position of global maximum\ngmax = (map==1.0);\n\n% Local maxima excluding global maximum\nlmax = lmax .* (gmax==0);\n\n% Average of local maxima excluding global maximum\nnmaxima=sum(sum(lmax));\nif nmaxima>0\n    m = sum(sum(map.*lmax))/nmaxima;\nelse\n    m = 0;\nend\nnormalized = map*(1.0-m)^2;\n\n% ------------------------------------------------------------------------\n% LocalMaxima\n% ------------------------------------------------------------------------\n\nfunction maxima = LocalMaxima(A)\n\nnRows=size(A,1);\nnCols=size(A,2);\n% compare with bottom, top, left, right\nmaxima =           (A > [A(2:nRows, :);   zeros(1, nCols)]);\nmaxima = maxima .* (A > [zeros(1, nCols); A(1:nRows-1, :)]);\nmaxima = maxima .* (A > [zeros(nRows, 1), A(:, 1:nCols-1)]);\nmaxima = maxima .* (A > [A(:, 2:nCols),   zeros(nRows, 1)]);\n\n% ------------------------------------------------------------------------\n% Subtract\n% ------------------------------------------------------------------------\n\nfunction result = Subtract(im1, im2)\n\nim2 = imresize(im2, size(im1), 'bilinear');\nresult = im1 - im2;\n\n% ------------------------------------------------------------------------\n% Add\n% ------------------------------------------------------------------------\n\nfunction result = Add(im1, im2)\n\nim2 = imresize(im2, size(im1), 'bilinear');\nresult = im1 + im2;\n\n% ------------------------------------------------------------------------\n% SaliencyMap\n% ------------------------------------------------------------------------\n\nfunction sm=SaliencyMap(varargin)\n\niCM = varargin{1};\noCM = varargin{2};\nif length(varargin) == 2\n    sm=(Normalize(iCM)+Normalize(oCM))/2;\nelse\n    cCM = varargin{3};\n    sm=(Normalize(iCM)+Normalize(cCM)+Normalize(oCM))/3;\nend\n\n% ------------------------------------------------------------------------\n% ShowImage\n% ------------------------------------------------------------------------\n\nfunction ShowImage(nFigure,image,fTitle)\n\n% figure(nFigure);\nfigure;\nimagesc(image);\nif (size(image, 3) == 1)\n    colormap('gray');\n    colorbar;\nend\naxis image;\ntitle(fTitle);\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/Saliency2013-master/Itti_Saliency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.589938341640059}}
{"text": "% Author: Ricardo Baptista and Matthias Poloczek\n% Date:   June 2018\n%\n% See LICENSE.md for copyright information\n%\n\nfunction out = contamination_prob(x, n_samples, seed)\n\n% Declare gamma factor (Lagrange constants)\ngamma = 1;\n\n% Find total number of input samples\nnum_inputs = size(x,1);\nout = zeros(num_inputs,1);\n\nfor i=1:num_inputs\n    \n    % Run contamination study\n    [cost, ~, ~, ~, constraint, ~, ~, ~] = Contamination(x(i,:)', n_samples, seed);\n\n    % Compute total output\n    out(i) = cost - sum(gamma*constraint);\n\nend\n", "meta": {"author": "baptistar", "repo": "BOCS", "sha": "fef0d4e34e376e8bb0dae9955d70c2155530b9eb", "save_path": "github-repos/MATLAB/baptistar-BOCS", "path": "github-repos/MATLAB/baptistar-BOCS/BOCS-fef0d4e34e376e8bb0dae9955d70c2155530b9eb/test_problems/ContStudy/contamination_prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289533, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5899383360046135}}
{"text": "function l_curr = gpu_forward_conv(l_prev, weights)\n    tic;\n    s = size(l_prev);\n    num_prev_row = s(1);\n    num_prev_col = s(2);\n    num_prev_ch = s(3);\n    \n    ss = size(weights);\n    num_curr_ch = ss(4);\n    \n    %disp('zero-pad the l_prev')\n    padded_l_prev = zeros(num_prev_row+2, num_prev_col+2, num_prev_ch);\n    padded_l_prev(2:num_prev_row+1, 2:num_prev_col+1, 1:num_prev_ch) = l_prev;\n    padded_gpu_l_prev = gpuArray(padded_l_prev);\n    %disp('start looping')\n    parfor ch = 1:num_curr_ch       \n        l_curr(:,:,ch) = convn(padded_gpu_l_prev, gpuArray(squeeze(weights(:,:,:,ch))),'valid');\n    end\n    l_curr = gather(l_curr);\n    %l_curr(l_curr<0) = 0; % this is the relu\n    toc\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u5272\u7b97\u6cd5/ImageSeg-master/gpu_forward_conv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.589938330774636}}
{"text": "function dt = CurvedCNSdt2D(Q, gamma, mu)\n\n% function dt = CurvedCNSdt2D(Q, gamma, mu)\n% Purpose: compute stable time step size for compressible Navier-Stokes solver\n\nGlobals2D;\n\n% extract field variables\nrho = Q(:,:,1); rhou = Q(:,:,2); rhov = Q(:,:,3); Ener = Q(:,:,4);\n\n% evaluate fields at surface nodes\nrho = rho(vmapM); rhou = rhou(vmapM); rhov = rhov(vmapM); Ener = Ener(vmapM);\n\n% compute primitive variables\nu = rhou./rho; v = rhov./rho;\np = (gamma-1.0)*(Ener - rho.*(u.^2+v.^2)/2);\nc = sqrt(abs(gamma*p./rho));\n\nh = 2./Fscale(:);\nlam = sqrt ( u(:).^2 + v(:).^2 ) + c(:);\ndt = 0.5*min(1./( (N+1)^2*lam./h + (N+1)^4*mu./(h.^2)))\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/JSHesthaven&TWarburton/CFD2D/CurvedCNSdt2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.589890886712275}}
{"text": "function [dfdz,dfdp,sym_dfdz,sym_dfdp] = symDynJac(ode,nstates,nparam)\n%SYMJAC  Returns Symbolically Differentiated Partial Derivatives of a Dynamic System\n%\n%   [dfdz,dfdp] = symDynJac(ode) uses the symbolic toolbox to automatically \n%   generate the sensitivity partial derivatives of the function handle ode. \n%   You should supply the function handle in the form @(t,z,p) z(1)^2 + p(1)\n%   noting t, z and p must be the only variables used, and are indexed in the \n%   equation (no vector operations).\n%\n%   [dfdz,dfdp] = symDynJac(ode,nstates) specifies the number of states in \n%   the equation, assuming consecutive ordering. Useful if a state is not\n%   specified in the original equation to pad DFDZ with zeros.\n%\n%   [dfdz,dfdp] = symDynJac(ode,nstates,nparam) specifies the number of \n%   parameters in the equation, assuming consecutive ordering. Useful if a \n%   parameter is not specified in the original equation to pad DFDP with \n%   zeros.\n\n%   Copyright (C) 2013 Jonathan Currie (I2C2)\n\nif(nargin < 3), nparam = 0; end\nif(nargin < 2), nstates = 0; end\n\nif(~optiCheckSymTBX())\n    dfdz = []; sym_dfdz = [];\n    dfdp = []; sym_dfdp = [];\n    return\nend\n\nif(~isa(ode,'function_handle') && ~isa(ode,'barvec'))\n    error('Fun should be a function handle!');\nend\nif(isa(ode,'function_handle') && nargin(ode) ~= 3)\n    error('ODE should only have three input arguments (t,z,p)');\nend\n\n%Convert ODE to a symbolic expression\nif(isa(ode,'function_handle'))\n    [symode,ind] = func2sym(ode,{'z','p','t'});\n    indz = ind{1}; indp = ind{2};\nelse\n    symode = sym(getEq(ode)); %convert from barvec to symbolic expression\n    v = char(symvar(symode));\n    indz = 1:length(strfind(v,'z'));\n    indp = 1:length(strfind(v,'p'));\nend\n\n%Create each symbolic partial derivative\nsym_dfdz = symPartialDer(symode,'z',nstates,indz);\nsym_dfdp = symPartialDer(symode,'p',nparam,indp);\n\n%Return to function handles (note order of args important and changed)\ndfdz = sym2func(sym_dfdz,{'t','z','p'});\ndfdp = sym2func(sym_dfdp,{'t','z','p'});\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/OptiToolbox/Utilities/Differentiation/Symbolic/symDynJac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5898455077594698}}
{"text": "function [v,y,w]=v_nearnonz(x,d)\n%V_NEARNONZ replace each zero element with the nearest non-zero element [V,Y,W]=v_nearnonz(X,D)\n%\n%  Inputs:  x         input vector, matrix or larger array\n%           d         dimension to apply filter along [default 1st non-singleton]\n%\n% Outputs:  v         v is the same size as x but with each zero entry replaced by\n%                     the nearest non-zero value along dimension d\n%                     elements equidistant from two non-zero entries will be taken\n%                     from the higher index\n%           y         y is the same size as x and gives the index along dimension d\n%                     from which the corresponding entry in v was taken\n%                     If there are no non-zero entries, then the corresponding\n%                     elements of y will be zero.\n%           w         w is the same size as x and gives the distance (+ or -) to the\n%                     nearest non-zero entry in x\n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: v_nearnonz.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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ne=size(x);\np=prod(e);\nif nargin<2             % if no dimension given, find the first non-singleton\n    d=find(e>1,1);\n    if ~numel(d)\n        d=1;\n    end\nend\nk=e(d);                 % size of active dimension\nq=p/k;                  % size of remainder\nif d==1\n    z=reshape(x,k,q);\nelse\n    z=shiftdim(x,d-1);\n    r=size(z);\n    z=reshape(z,k,q);\nend\nxx=z~=0;\ncx=cumsum(xx);\n[i,j]=find(z);\nqq=cx(xx);\npos=full(sparse(qq,j,i,k,q)); % list the positions of non-zero elements in each column\nmp=ceil((pos(1:end-1,:)+pos(2:end,:))*0.5); % find the mid point between consecutive non-zero elements\n[i2,j2]=find(pos(2:end,:)>0);\nzz=1+cumsum(full(sparse(mp(pos(2:end,:)>0),j2,1,k,q)));\ny=pos(zz+repmat((0:q-1)*k,k,1));\nv=z(max(y,1)+repmat((0:q-1)*k,k,1));\nw=y-repmat((1:k)',1,q);\nw(y==0)=0;\nif d==1\n    y=reshape(y,e);\n    v=reshape(v,e);\n    w=reshape(w,e);\nelse\n    y=shiftdim(reshape(y,r),length(e)+1-d);\n    v=shiftdim(reshape(v,r),length(e)+1-d);\n    w=shiftdim(reshape(w,r),length(e)+1-d);\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_nearnonz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.5898454914699067}}
{"text": "classdef MMF1 < PROBLEM\n% <multi> <real> <multimodal>\n% Multi-modal multi-objective test function\n\n%------------------------------- Reference --------------------------------\n% C. Yue, B. Qu, and J. Liang, A multi-objective particle swarm optimizer\n% using ring topology for solving multimodal multiobjective Problems, IEEE\n% Transactions on Evolutionary Computation, 2018, 22(5): 805-817.\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        POS;    % Pareto optimal set for IGDX calculation\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            obj.D = 2;\n            obj.lower    = [1,-1];\n            obj.upper    = [3,1];\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            PopObj(:,1) = abs(X(:,1)-2);\n            PopObj(:,2) = 1-sqrt(PopObj(:,1))+2*(X(:,2)-sin(6*pi*PopObj(:,1)+pi)).^2; \n        end\n        %% Generate Pareto optimal solutions\n        function R = GetOptimum(obj,N)\n            % Generate points in Pareto optimal set\n            obj.POS(:,1) = linspace(1,3,N)';\n            obj.POS(:,2) = sin(6*pi*abs(obj.POS(:,1)-2)+pi);\n            % Generate points on Pareto front\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - sqrt(R(:,1));\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R(:,1) = linspace(0,1,100)';\n            R(:,2) = 1 - sqrt(R(:,1));\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            temp   = PopDec(:,1)<=2;\n            Draw(Population(temp).objs,'o','MarkerSize',6,'Marker','o','Markerfacecolor',[1 .5 .5],'Markeredgecolor',[1 .2 .2],{'\\it f\\rm_1','\\it f\\rm_2',[]});\n            Draw(Population(~temp).objs+0.1,'o','MarkerSize',6,'Marker','o','Markerfacecolor',[.5 .5 1],'Markeredgecolor',[.2 .2 1]);\n            Draw(obj.PF,'-','LineWidth',1,'Color',[1 .2 .2]);\n            Draw(obj.PF+0.1,'-','LineWidth',1,'Color',[.2 .2 1]);\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/MMF/MMF1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.5898454885680329}}
{"text": "function f = flipud(f)\n%FLIPUD   Flip/reverse a TRIGTECH object.\n%   G = FLIPUD(F) returns G such that G(x) = F(-x) for all x in [-1,1].\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\n% Flip the values:\nf.values = [ f.values(1,:); flipud(f.values(2:end,:)) ];\n\n% Flip the coefficients taking into account where f is odd or even\nif mod(size(f.coeffs,1),2)\n    % Odd length is easy, just flip the coefficients\n    f.coeffs = flipud(f.coeffs);\nelse\n    % Even length requires keeping the first coefficient in place and \n    % flipping the remaining ones.  This follows since we interpret the \n    % first coefficient to correspond to the 1/2*cos(-N/2 x) mode.\n    f.coeffs(1) = conj(f.coeffs(1));\n    f.coeffs(2:end,:) = flipud(f.coeffs(2:end,:));\nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@trigtech/flipud.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.589839845739666}}
{"text": "function [ n_data, n, x, fx ] = h_polynomial_values ( n_data )\n\n%*****************************************************************************80\n%\n%% H_POLYNOMIAL_VALUES: tabulated values of H(i,x).\n%\n%  Discussion:\n%\n%    H(i,x) is the physicist's Hermite polynomial of degree I.\n%\n%    In Mathematica, the function can be evaluated by:\n%\n%      HermiteH[n,x]\n%\n%  Differential equation:\n%\n%    Y'' - 2 X Y' + 2 N Y = 0\n%\n%  First terms:\n%\n%      1\n%      2 X\n%      4 X^2     -  2\n%      8 X^3     - 12 X\n%     16 X^4     - 48 X^2     + 12\n%     32 X^5    - 160 X^3    + 120 X\n%     64 X^6    - 480 X^4    + 720 X^2    - 120\n%    128 X^7   - 1344 X^5   + 3360 X^3   - 1680 X\n%    256 X^8   - 3584 X^6  + 13440 X^4  - 13440 X^2   + 1680\n%    512 X^9   - 9216 X^7  + 48384 X^5  - 80640 X^3  + 30240 X\n%   1024 X^10 - 23040 X^8 + 161280 X^6 - 403200 X^4 + 302400 X^2 - 30240\n%\n%  Recursion:\n%\n%    H(0,X) = 1,\n%    H(1,X) = 2*X,\n%    H(N,X) = 2*X * H(N-1,X) - 2*(N-1) * H(N-2,X)\n%\n%  Norm:\n%\n%    Integral ( -oo < X < +oo ) exp ( - X^2 ) * H(N,X)^2 dX\n%    = sqrt ( PI ) * 2^N * N!\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    16 September 2004\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Milton Abramowitz and Irene Stegun,\n%    Handbook of Mathematical Functions,\n%    US Department of Commerce, 1964.\n%\n%    Stephen Wolfram,\n%    The Mathematica Book,\n%    Fourth Edition,\n%    Wolfram Media / Cambridge University Press, 1999.\n%\n%  Parameters:\n%\n%    Input/output, integer N_DATA.  The user sets N_DATA to 0 before the\n%    first call.  On each call, the routine increments N_DATA by 1, and\n%    returns the corresponding data; when there is no more data, the\n%    output value of N_DATA will be 0 again.\n%\n%    Output, integer N, the order of the polynomial.\n%\n%    Output, real X, the point where the polynomial is evaluated.\n%\n%    Output, real FX, the value of the function.\n%\n  n_max = 18;\n\n  fx_vec = [ ...\n      0.1000000000000000E+01, ...\n      0.1000000000000000E+02, ...\n      0.9800000000000000E+02, ... \n      0.9400000000000000E+03, ...\n      0.8812000000000000E+04, ...\n      0.8060000000000000E+05, ...\n      0.7178800000000000E+06, ...\n      0.6211600000000000E+07, ...\n      0.5206568000000000E+08, ...\n      0.4212712000000000E+09, ...\n      0.3275529760000000E+10, ...\n      0.2432987360000000E+11, ...\n      0.1712370812800000E+12, ...\n      0.0000000000000000E+00, ...\n      0.4100000000000000E+02, ...\n     -0.8000000000000000E+01, ...\n      0.3816000000000000E+04, ...\n      0.3041200000000000E+07 ];\n\n  n_vec = [ ...\n     0,  1,  2, ...\n     3,  4,  5, ...\n     6,  7,  8, ...\n     9, 10, 11, ...\n    12,  5,  5, ...\n     5,  5,  5 ];\n\n  x_vec = [ ...\n     5.0E+00, ...\n     5.0E+00, ...\n     5.0E+00, ...\n     5.0E+00, ...\n     5.0E+00, ...\n     5.0E+00, ...\n     5.0E+00, ...\n     5.0E+00, ...\n     5.0E+00, ...\n     5.0E+00, ...\n     5.0E+00, ...\n     5.0E+00, ...\n     5.0E+00, ...\n     0.0E+00, ...\n     0.5E+00, ...\n     1.0E+00, ...\n     3.0E+00, ...\n     1.0E+01 ];\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/hermite_polynomial/h_polynomial_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.5898398445706864}}
{"text": "function x = AngNormalize2(x)\n%ANGNORMALIZE2  Reduce any angle to range [-180, 180)\n%\n%   X = ANGNORMALIZE(X) reduces arbitrary angles to the range [-180, 180).\n%   X can be any shape.\n\n  x = AngNormalize(mod(x, 360));\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/AngNormalize2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5898398383992599}}
{"text": "function[mu,sigma]=GMM_parameter(image,segmentation,class_number)\n[n,d]=size(image);\nmu=zeros(class_number,d);\nsigma=zeros(d,d,class_number);\n   for i=1:class_number\n       Im_i=image(segmentation==i,:);\n       [sigma(:,:,i),mu(i,:)]=covmatrix(Im_i);\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/33592-image-segmentation-based-on-markov-random-fields/image segmentation/function/GMM_parameter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178928, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5897522042084772}}
{"text": "% Function to calculate Threshold for BayesShrink\n\nfunction threshold=bayes(X,sigmahat)\n\nlen=length(X);\nsigmay2=sum(X.^2)/len;\nsigmax=sqrt(max(sigmay2-sigmahat^2,0));\nif sigmax==0 threshold=max(abs(X));\nelse threshold=sigmahat^2/sigmax;\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/16386-image-denoising-using-bayes-thresholding-of-wavelet-coefficients/bayesthresholding/bayes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.589752197215329}}
{"text": "function [par, parb, Pf, Pb] = rc2parv(rc,rcb)\n\n%function [par, parb, Pf, Pb] = rc2parv(rc,rcb)\n%  Transforms forward and backward reflection matrices rc and rcb \n%  into parameters.\n\n%S. de Waele, March 2003.\n\ns = kingsize(rc);\norder = s(3)-1;\ndim = s(1); I = eye(dim);\n\npar = zeros(dim,dim,order+1);\nparb = zeros(dim,dim,order+1);\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   \nfor p = 2:order,\n   par(:,:,2:p) =  par_o(:,:,2:p) +fliptime(filterv(rc(:,:,p+1),1,parb_o(:,:,2:p)));\n   par(:,:,p+1)= rc(:,:,p+1);\n   parb(:,:,2:p) =  parb_o(:,:,2:p) +fliptime(filterv(rcb(:,:,p+1) ,1,par_o(:,:,2:p)));\n   parb(:,:,p+1)= rcb(:,:,p+1);\n   \n   par_o  = par;\n   parb_o = parb;\nend %for p = 2: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/conversions/rc2parv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5896859020559118}}
{"text": "function [bval] = function(fval,bounds,bits)\n% function [bval] = f2b(fval,bounds,bits)\n%\n% Return the binary representation of the float number fval.\n%\n% fval   - the float representation of the number\n% bval   - the binary representation of the number\n% bounds - the bounds on the variables\n% bits   - the number of bits to represent each variable\n\n% Binary and Real-Valued Simulation Evolution for Matlab \n% Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay \n%\n% C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function\n% optimization: A Matlab implementation. ACM Transactions on Mathmatical\n% Software, Submitted 1996.\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 1, or (at your option)\n% any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details. A copy of the GNU \n% General Public License can be obtained from the \n% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\nscale=(2.^bits-1)./ (bounds(:,2)-bounds(:,1))'; %The range of the variables\nnumV=size(bounds,1);\ncs=[0 cumsum(bits)];\nbval=[];\nfor i=1:numV\n  fval(i)=(fval(i)-bounds(i,1)) * scale(i);\n  bval=[bval rem(floor(fval(i)*pow2(1-bits(i):0)),2)];\nend", "meta": {"author": "Grootzz", "repo": "GA-BP", "sha": "81b82ce366a9325495a0f243bcb282ca074f8a91", "save_path": "github-repos/MATLAB/Grootzz-GA-BP", "path": "github-repos/MATLAB/Grootzz-GA-BP/GA-BP-81b82ce366a9325495a0f243bcb282ca074f8a91/src/GAOT/f2b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.589685886085117}}
{"text": "%\n% A variational approach to SPCP (Aravkin et al. 2014)\n%\n% RPCA | SPCP-max-QN  | Stable PCP-max solved by Quasi-Newton (Aravkin et al. 2014)\n% process_video('RPCA', 'flip-SPCP-max-QN', 'dataset/demo.avi', 'output/demo_flip-SPCP-max-QN.avi');\n\nalg_path_aux = fullfile(lrs_conf.rpca_path,'SPGL1');\naddpath(genpath(alg_path_aux));\n\nnFrames     = size(M,2);\nlambda      = 1/sqrt(max(size(M,1),size(M,2)));\nL0          = repmat(median(M,2), 1, nFrames);\nS0          = M - L0;\nepsilon     = 5e-3*norm(M,'fro'); % tolerance for fidelity to data\n\n% Flip-Flop version pf SPCP-max solved by Quasi-Newton\nopts = struct('sum',false,'L0',L0,'S0',S0,'max',true,...\n  'tau0',3e5,'SPGL1_tol',1e-1,'tol',1e-3);\n[L,S] = solver_RPCA_SPGL1(M,lambda,epsilon,[],opts);\n\nrmpath(genpath(alg_path_aux));", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/flip-SPCP-max-QN/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5896858799794032}}
{"text": "function [ bestThresh ] = ThresholdSelection(  trainDir, image, s, widthOfBins, thresh, p)\n% ThresholdSelection - This function is used for selecting the optimal \n% threshold by comparing the\n% fraction of the non-thresholded content which lies in the principal\n% component.  The variable \"p\" should represent the fraction of the image\n% inputed that contains the desired object... example: p=0.04.\n%--------------------------------------------------------------------------\n%   Params: trainDir - directory of training images.  Note there should be\n%               a subdirectory in trainDir which contains .jpg images\n%           s - the window size that each frame will be split up in to form\n%               histograms\n%           widthOfBins - the width of the bins for the RGB color\n%               histograms\n%           thresh - the cutoff distance threshold used to measure whether\n%               or not window histograms are close enough to the training\n%               histograms.\n%           p - proportion of pixels containing object of interest\n%\n%   Returns: bestThresh - a guess for threshold value to choose\n%--------------------------------------------------------------------------\n\n    display(strcat(datestr(now,'HH:MM:SS'),' [INFO] Processing training images...'));\n    trainingHistograms = BuildTrainingHistograms(trainDir, widthOfBins);\n    \n    display(strcat(datestr(now,'HH:MM:SS'),' [INFO] Reading image...'));\n    image = double(image);\n    bestThresh = 0;\n    bestRatio = 0;\n    for t = thresh\n        disp('-------------------------------------------------------------');\n        disp(strcat('Testing Threshold Value: ',num2str(t)))\n        scoreImage = ImageToScoreArray( image, trainingHistograms, s, widthOfBins, t );\n        pixels = prod(size(scoreImage)); %#ok<PSIZE>\n        [L,num] = bwlabeln(scoreImage);\n        max = 0;\n        total = 0;\n        for i = 1:num\n            temp = sum(sum(L==i));\n            total = total+temp;\n            if (temp>max)\n                max = temp;\n            end\n        end\n        display(strcat('Fraction of pixels above threshold:',num2str(total/pixels)));\n        display(strcat('Fraction of these pixels in principal component:',num2str(max/total)));\n        if (0.9>total/pixels)\n            if (total/pixels>p)\n                if (max/total>bestRatio)\n                    bestRatio = max/total;\n                    bestThresh = t;\n                end\n            end\n        end\n    end\n\nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/Surgery_DetectionTracking-master/classificationTracking/ThresholdSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5896717778860787}}
{"text": "function [V, policy, iter, cpu_time] = mdp_policy_iteration_modified(P, R, discount, epsilon, max_iter)\n\n\n% mdp_policy_iteration_modified    Resolution of discounted MDP  \n%                                  with modified policy iteration algorithm\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%              beware to check conditions of convergence for discount = 1.\n%   epsilon  = epsilon-optimal policy search, upper than 0,\n%              optional (default : 0.01)\n%   max_iter = maximum number of iteration to be done in the inner loop,\n%              upper than 0, optional (default: 10)\n% Evaluation -------------------------------------------------------------\n%   V(S)     = value function\n%   policy(S)= epsilon-optimal policy\n%   iter     = number of main iterations\n%   cpu_time = used CPU time\n%--------------------------------------------------------------------------\n% In verbose mode, at each iteration, displays the variation of V\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 <ORGANIZATION> 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\ncpu_time = cputime;\n\nglobal mdp_VERBOSE;\n\n% check of arguments\nif discount <= 0 || discount > 1\n    disp('--------------------------------------------------------')\n    disp('MDP Toolbox ERROR: Discount rate must be in ]0; 1]')\n    disp('--------------------------------------------------------')\nelseif nargin > 4 && epsilon <= 0\n    disp('--------------------------------------------------------')\n    disp('MDP Toolbox ERROR: epsilon must be upper than 0')\n    disp('--------------------------------------------------------')\nelseif nargin > 5 && max_iter <= 0\n    disp('--------------------------------------------------------')\n    disp('MDP Toolbox ERROR: The maximum number of iteration must be upper than 0')\n    disp('--------------------------------------------------------')\nelse\n\n    if discount == 1  \n        disp('-------------------------------------------------------')\n        disp('MDP Toolbox WARNING: check conditions of convergence.')\n        disp('With no discount, convergence is not always assumed.')\n        disp('--------------------------------------------------------')\n    end;\n    \n    if iscell(P); S = size(P{1},1); else S = size(P,1); end;\n    \n    PR = mdp_computePR(P,R);\n\n    % initialization of optional arguments\n    if nargin < 5; max_iter = 10; end;\n    if nargin < 4; epsilon = 0.01; end;\n\n    % computation of threshold of variation for V for an epsilon-optimal policy\n    if discount ~= 1\n        thresh = epsilon * (1-discount)/discount;\n    else \n        thresh = epsilon;\n    end;\n\n    if discount == 1\n        V = zeros(S,1);\n    else\n        V = 1/(1-discount)*min(min(PR))*ones(S,1);\n    end;     \n\n    if mdp_VERBOSE; disp('  Iteration  V_variation'); end;\n    \n    iter = 0;\n    is_done = false;\n    while ~is_done\n\n        iter = iter + 1;\n        \n        [Vnext, policy] = mdp_bellman_operator(P,PR,discount,V);\n        %[Ppolicy, PRpolicy] = mdp_computePpolicyPRpolicy(P, PR, policy);\n        \n        variation = mdp_span(Vnext - V);\n        if mdp_VERBOSE; \n             disp(['      ' num2str(iter,'%5i') '         ' num2str(variation)]); \n        end;\n   \n        V=Vnext;\n        if variation < thresh\n            is_done = true; \n        else\n\t    is_verbose = false;\n            if mdp_VERBOSE; mdp_VERBOSE = 0; is_verbose = true; end;\n            V = mdp_eval_policy_iterative(P, PR, discount, policy, V, epsilon, max_iter);\n            if is_verbose; mdp_VERBOSE = 1; end;\n        end;\n    end;\nend;\n\ncpu_time = cputime - cpu_time;\n", "meta": {"author": "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_policy_iteration_modified.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5896717760504498}}
{"text": "function [Y, bias, scale] = scaleData(Y, scaleMethod, scaleVal, bias)\n% SCALEDATA Scale and center data\n% VARGPLVM\n\nif nargin < 4, bias = []; end\nif nargin < 3, scaleVal = [];   end\nif nargin < 2, scaleMethod = []; end\n\nd = size(Y,2);\nif isempty(bias)\n    bias = mean(Y);\nend\n\n% Remove bias\nm = Y;\nfor i = 1:d\n  m(:, i) = m(:, i) - bias(i);\nend\n\n\n\nscale = ones(1, d);\n\nif ~isempty(scaleMethod) && scaleMethod ~= 0\n    if ~isempty(scaleVal) \n        warning('Both scale2var1 and scaleVal set for GP');\n    end\n    if(scaleMethod == 1) % Scale to variance 1\n        scale = std(Y);\n    elseif scaleMethod == 2 % Scale so that maximum is 1\n        scale = max(max(abs(m)));\n    else\n        error('Unknown scale option')\n    end\n    scale(find(scale==0)) = 1;\nend\n\nif isscalar(scaleVal)\n    if scaleVal\n        scale = repmat(scaleVal, 1, d);\n    end\nelseif ~isempty(scaleVal) && ~sum(scaleVal==0)\n    scale = scaleVal;\nend\n\n% Apply scale\nfor i = 1:d\n  if scale(i)\n    m(:, i) = m(:, i)/scale(i);\n  end\nend\n\nY = m;", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/utils/scaleData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.589671766321501}}
{"text": "N = 400;\nA = gallery('poisson', N);\n[L2,p,Ac] = achol(A); \n% [L2,p,Ac] = acholold(A); \n% save olddata L2 p Ac\ndisp(size(Ac,1));\n    b = ones(size(A,1),1);\n    tol = 1e-6; maxit = 100;    \n    tic;\n%     Ap = A(p,p);\n    [x2,fl2,rr2,it2,rv2] = pcg(A,b,tol,maxit,@(r)acholpre(r,A,L2,L2',p,Ac));\n    toc;\n    fprintf('#dof: %8.0u,  iter: %2.0u\\n',size(A,1), it2)\n    semilogy(0:it2,rv2./norm(b),'b.');\n    hold on", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/debug/acholdebug.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.589671766321501}}
{"text": "function hypervolume = hypervolume2D(F,ub)\n% Copyright (c) 2011, Johannes\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% Method for ND objective function values as described in:\n%\n% 'M. Fleischer. The measure of Pareto Optima Applications to \n%  Multi-objective Metaheuristics. EMO 2003, LNCSS 2632\n%  519-533, 2003.'\n%\n% Author: Johannes W. Kruisselbrink\n% Last modified: March 17, 2011\n%\n% Efficient method for 2D objective function values\n    F  = -F' + ones(size(F'));\n\tL  = sortrows(F',1)';\n\tl  = length(L(1,:)); ub = ub + ones(1,size(L,1));\n\thypervolume = 0;\n\tfor i = 1:l\n\t\thypervolume = hypervolume + ((L(1,i) - ub(1)) * (L(2,i) - ub(2)));\n        ub(2)       = L(2,i);\n    end\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/Mex_files/hypervolume/hypervolume2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.5896717657096244}}
{"text": "% [PYR, INDICES, STEERMTX, HARMONICS] = buildSpyr(IM, HEIGHT, FILTFILE, EDGES)\n%\n% Construct a steerable pyramid on matrix IM.\n%\n% HEIGHT (optional) specifies the number of pyramid levels to build. Default\n% is maxPyrHt(size(IM),size(FILT));\n%\n% FILTFILE (optional) should be a string referring to an m-file that\n% returns the rfilters.  (examples: 'sp0Filters', 'sp1Filters',\n% 'sp3Filters','sp5Filters'.  default = 'sp1Filters'). EDGES specifies\n% edge-handling, and defaults to 'reflect1' (see corrDn).\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.  This is compatible with the MatLab Wavelet toolbox.\n% See the function STEER for a description of STEERMTX and HARMONICS.\n\n% Eero Simoncelli, 6/96.\n\nfunction [pyr,pind,steermtx,harmonics] = buildSpyr(im, ht, filtfile, edges)\n\n%-----------------------------------------------------------------\n%% DEFAULTS:\n\nif (exist('filtfile') ~= 1)\n  filtfile = 'sp1Filters';\nend\n\nif (exist('edges') ~= 1)\n  edges= 'reflect1';\nend\n\nif (isstr(filtfile) & (exist(filtfile) == 2))\n   [lo0filt,hi0filt,lofilt,bfilts,steermtx,harmonics] = eval(filtfile);\nelse\n  fprintf(1,'\\nUse buildSFpyr for pyramids with arbitrary numbers of orientation bands.\\n');\n  error('FILTFILE argument must be the name of an M-file containing SPYR filters.');\nend\n\nmax_ht = maxPyrHt(size(im), size(lofilt,1));\nif (exist('ht') ~= 1)\n  ht = max_ht;\nelse\n  if (ht > max_ht)\n    error(sprintf('Cannot build pyramid higher than %d levels.',max_ht));\n  end\nend\n\n%-----------------------------------------------------------------\n\nhi0 = corrDn(im, hi0filt, edges);\nlo0 = corrDn(im, lo0filt, edges);\n\n[pyr,pind] = buildSpyrLevs(lo0, ht, lofilt, bfilts, edges);\n\npyr = [hi0(:) ; pyr];\npind = [size(hi0); pind];\n  \n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/pyrTools/pyrTools/buildSpyr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5896717547569222}}
{"text": "function fcv = Calculate_fcv(Population)\n% calculate normalized  constraints violation(CV) measuring feasibility\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    CV_Original = Population.cons;\n    CV_Original(CV_Original<=0) = 0;\n    CV = CV_Original./max(CV_Original);\n    CV(:,isnan(CV(1,:))) = 0;\n    fcv = sum(max(0,CV),2)./size(CV_Original,2);\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/TSTI/Calculate_fcv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.5896255789896034}}
{"text": "function lerch_values_test ( )\n\n%*****************************************************************************80\n%\n%% LERCH_VALUES_TEST demonstrates the use of LERCH_VALUES.\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  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'LERCH_VALUES_TEST:\\n' );\n  fprintf ( 1, '  LERCH_VALUES stores values of\\n' );\n  fprintf ( 1, '  the Lerch function.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '           Z        S             A            FX\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, z, s, a, fx ] = lerch_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fprintf ( 1, '  %12f  %4d  %12f  %24.16f\\n', z, s, a, 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/lerch_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.5896255725881598}}
{"text": "function [ft] = um2ft(um)\n% Convert length from micrometers (or microns) to feet.\n% Chad A. Greene 2012\nft = um*0.000003280839895013;", "meta": {"author": "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/um2ft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5896255674001526}}
{"text": "function X = arrange(X,foo)\n%ARRANGE Arranges the rank-1 components of a ktensor.\n%\n%   ARRANGE(X) normalizes the columns of the factor matrices and then sorts\n%   the ktensor components by magnitude, greatest to least.\n%\n%   ARRANGE(X,N) absorbs the weights into the Nth factor matrix instead of\n%   lambda. \n%\n%   ARRANGE(X,P) rearranges the components of X according to the\n%   permutation P. P should be a permutation of 1 to NCOMPOMENTS(X). \n%\n%   See also KTENSOR, NCOMPONENTS.\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\n\n%% Just rearrange and return if second argument is a permutation\nif exist('foo','var') && (length(foo) > 1)\n    X.lambda = X.lambda(foo);\n    for i = 1 : ndims(X)\n        X.u{i} = X.u{i}(:,foo);\n    end   \n    return;\nend\n\n%% Ensure that matrices are normalized\nX = normalize(X);\n\n%% Sort\n[X.lambda, idx] = sort(X.lambda, 1, 'descend');\nfor i = 1 : ndims(X)\n    X.u{i} = X.u{i}(:,idx);\nend\n\n%% Absorb the weight into one factor, if requested\nif exist('foo','var')\n    r = length(X.lambda);\n    X.u{end} = X.u{end} * spdiags(X.lambda,0,r,r);\n    X.lambda = ones(size(X.lambda));\nend\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/@ktensor/arrange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7341195210831261, "lm_q1q2_score": 0.5896255627280448}}
{"text": "function [tt]=round(tt,varargin)\n%Approximate QTT-Tucker with another one with specified accuracy\n%   [QTT]=ROUND(QTT,EPS) Approximate QTT-Tucker tensor with relative \n%   accuracy EPS\n%\n%   [QTT]=ROUND(QTT,EPS,RMAX) Approximate QTT-Tucker tensor with relative\n%   accuracy \n%   EPS and maximal rank RMAX. RMAX can be array of ranks or a number\n%\n% Please see @qtt_tucker/round2 for a more accurate version of the algorithm\n%\n% TT-Toolbox 2.2, 2009-2012\n%\n%This is TT Toolbox, written by Ivan Oseledets et al.\n%Institute of Numerical Mathematics, Moscow, Russia\n%webpage: http://spring.inm.ras.ru/osel\n%\n%For all questions, bugs and suggestions please mail\n%ivan.oseledets@gmail.com\n%---------------------------\nd=tt.dphys;\ncore=tt.core;\ntuck=tt.tuck;\neps=varargin{1};\ntolcorr = 0;\nfor i=1:d\n    tolcorr = tolcorr+tuck{i}.d;\nend;\nrmax = [];\nif (nargin==3)\n    rmax = varargin{2};\nend;\nismatrix = 0;\nif (isa(tuck{1}, 'tt_matrix'))\n    ismatrix = 1;\n    curn = cell(d,1);\n    curm = cell(d,1);\nend;\nfor i=1:d\n    if (ismatrix)\n        curn{i} = tuck{i}.n;\n        curm{i} = tuck{i}.m;\n        tuck{i} = tt_tensor(tuck{i});\n    end;\n   [tuck{i},rm]=qr(tuck{i},'lr');\n   core{i}=ten_conv(core{i},2,rm.');\nend\nif (isempty(rmax))\n    core=round(core,eps*sqrt(d)/sqrt(tolcorr)); \nelse\n    core=round(core,eps*sqrt(d)/sqrt(tolcorr),rmax); \nend;\n%Round the core --- we know the result comes\n%with rl orthogonality? -< No, we don't\n[core, nrm] = qr(core, 'lr');\ncore{d} = core{d}*nrm;\nrtt=rank(core); \nn=size(core);\nfor i=d:-1:1\n   cr=reshape(core{i},[rtt(i),n(i),rtt(i+1)]);\n   cr=permute(cr,[2,1,3]); cr=reshape(cr,n(i),rtt(i)*rtt(i+1));\n   [u,s,v]=svd(cr,'econ');\n   s=diag(s);\n   r=my_chop2(s,norm(s)*eps/sqrt(tolcorr));   \n   if (~isempty(rmax))\n       r = min(r,rmax);\n   end;\n   u=u(:,1:r); s=s(1:r); v=v(:,1:r);\n   tuck{i}=tuck{i}*(u*diag(s)); \n   if (isempty(rmax))\n       tuck{i}=round(tuck{i},eps*sqrt(tuck{i}.d)/sqrt(tolcorr));\n   else\n       tuck{i}=round(tuck{i},eps*sqrt(tuck{i}.d)/sqrt(tolcorr), rmax);\n   end;\n   [tuck{i},rm]=qr(tuck{i},'lr');\n   cr=rm*v';\n   cr=reshape(cr,[r,rtt(i),rtt(i+1)]);\n   % Shift QR to the next core block\n   if (i>1)\n       cr=permute(cr,[1,3,2]);\n       cr = reshape(cr, r*rtt(i+1), rtt(i));\n       [cr, rv] = qr(cr, 0);\n       cr2 = core{i-1};\n       rtuck2 = size(cr2, 2);\n       cr2 = reshape(cr2, rtt(i-1)*rtuck2, rtt(i));\n       cr2 = cr2*(rv.');\n       rtt(i) = size(cr, 2);\n       core{i-1} = reshape(cr2, rtt(i-1), rtuck2, rtt(i));\n       core{i} = reshape(cr.', rtt(i), r, rtt(i+1));\n   else\n       core{i}=permute(cr,[2,1,3]);\n   end;\nend\nif (ismatrix)\n    for i=1:d\n        tuck{i} = tt_matrix(tuck{i}, curn{i}, curm{i});\n    end;\nend;\ntt.core=core;\ntt.tuck=tuck;\nreturn\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/@qtt_tucker/round.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5895014959627684}}
{"text": "clear;\nclc;\nclose all;\n\nH = [-6 -6 -7 0 7 6 6 -3 -3 0 0 -6; -7 2 1 8 1 2 -7 -7 -2 -2 -7 -7];\n\n[R, ~] = ch_rotation_2d(H, deg2rad(-90));\nH = R*H;\n\nx = H(1,:)'; y = H(2,:)';\n\naxis('square');\naxis equal\nplot(x, y, 'o', x, y, '-');", "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/linear_transformation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5895014959627682}}
{"text": "function R = apprRot(Ra)\n%R = apprRot(Ra)\n\n% should not change due to introduction of c\n\ni1 = 0.5; i2 = 0.5;\nU = Ra(1,:);\nV = Ra(2,:);\nun = norm(U);\nvn = norm(V);\nUn = U/un;\nVn = V/vn;\n\nvp = Un*Vn';\nup = Vn*Un';\n\nVc = Vn-vp*Un;  Vc = Vc/norm(Vc);\nUc = Un-up*Vn;  Uc = Uc/norm(Uc);\n\nUa = i1*Un+i2*Uc; Ua = Ua/norm(Ua); \nVa = i1*Vn+i2*Vc; Va = Va/norm(Va);\n\n\n\nR = [Ua;Va;cross(Ua,Va)];\nif det(R)<0, R(3,:) = -R(3,:); end;\n\nend\n\n\n", "meta": {"author": "akar43", "repo": "CategoryShapes", "sha": "55c9dab2293bcaceaaa3bf5fea782fdbf930fadb", "save_path": "github-repos/MATLAB/akar43-CategoryShapes", "path": "github-repos/MATLAB/akar43-CategoryShapes/CategoryShapes-55c9dab2293bcaceaaa3bf5fea782fdbf930fadb/nrsfm/apprRot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5895014869921013}}
{"text": "%INTERSECTCONVEXCONVEX  Finds intersection of two convex polygons\n%\n%     [p12, area] = cv.intersectConvexConvex(p1, p2)\n%     [...] = cv.intersectConvexConvex(..., 'OptionName',optionValue, ...)\n%\n% ## Input\n% * __p1__ first polygon, stored in numeric array (Nx2/Nx1x2/1xNx2) or cell\n%   array of 2-element vectors (`{[x,y], ...}`).\n% * __p2__ second polygon, stored in numeric array (Nx2/Nx1x2/1xNx2) or cell\n%   array of 2-element vectors (`{[x,y], ...}`).\n%\n% ## Output\n% * __p12__ intersection polygon points, a cell array of 2-element vectors\n%   `{[x,y], ...}`\n% * __a__ area\n%\n% ## Options\n% * __HandleNested__ default true\n%\n% See also: cv.rotatedRectangleIntersection, cv.Rect.intersect, rectint\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/intersectConvexConvex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5894109686058022}}
{"text": "% Fig. 9.42   Feedback Control of Dynamic Systems, 5e \n%             Franklin, Powell, Emami\n%\n\n%script to plot the phase plane for a bang-bang example\nfigure(2)\nhold off\nclf\nN=-1;\nx = -100;\nfor k=7:11;\nxdot=2.02*k;\nsim('bang');\nplot(xbang(:,2),xdotbang(:,2),'b-',xbang(:,2),-xdotbang(:,2),'b-');\nxlabel('x_1');\nylabel('x_2');\ntext(-120,19,'u=-1');\nhold on;\nend;\nN=1;\nx = 100;\nfor k=7:11;\nxdot=-2.02*k;\nsim('bang')\nplot(xbang(:,2),xdotbang(:,2),'r-',xbang(:,2),-xdotbang(:,2),'r-');\nhold on;\nend\ntext(100,-17,'u=+1');\ntitle('Switching curves for 1/s^2 plant')\ngrid on\n", "meta": {"author": "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/fig9_42.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5894109613372771}}
{"text": "%Function to integrate to calculate the area of a figure\nfunction partieaire = functionviewfactorarea(t)\n\n\n%Global variables: pt1 to pt2 are the points that define the segment to integrate, normale is the unit normal vector.\nglobal pt1;\nglobal pt2;\nglobal normale;\n\n%Parametric equations of the segment that join pt1 to pt2\nx=pt1(1)+(pt2(1)-pt1(1)).*t;\ny=pt1(2)+(pt2(2)-pt1(2)).*t;\nz=pt1(3)+(pt2(3)-pt1(3)).*t;\n\n%Function to integrate to calculate the area of a figure\npartieaire=normale(2).*z.*(pt2(1)-pt1(1))+normale(3).*x.*(pt2(2)-pt1(2))+normale(1).*y.*(pt2(3)-pt1(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/5664-view-factors/functionviewfactorarea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.589399978583509}}
{"text": "function [ y, symm ] = cvx_s_upper_hankel( m, n, symm )\n\n% CVX_S_UPPER_HANKEL Upper Hankel matrices.\n\nc  = 0 : n - 1;\nc  = c( ones( 1, m ), : );\nr  = ( 0 : m - 1 )';\nr  = r( :, ones( 1, n ) );\nv  = abs( r + c ) + 1;\ntemp = v <= min( m, n );\ny = sparse( v( temp ), r( temp ) + m * c( temp ) + 1, 1, min( m, n ), m * n );\nsymm = false;\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/structures/cvx_s_upper_hankel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.5893413048019709}}
{"text": "function check = student_check ( a, b, c )\n\n%*****************************************************************************80\n%\n%% STUDENT_CHECK checks the parameter of the central Student T CDF.\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%  Parameters:\n%\n%    Input, real A, B, shape parameters of the PDF,\n%    used to transform the argument X to a shifted and scaled \n%    value Y = ( X - A ) / B.  It is required that B be nonzero.\n%    For the standard distribution, A = 0 and B = 1.\n%\n%    Input, 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, logical CHECK, is true if the parameters are legal.\n%\n  if ( b == 0.0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'STUDENT_CHECK - Fatal error!\\n' );\n    fprintf ( 1, '  B must be nonzero.\\n' );\n    check = 0;\n    return\n  end\n\n  if ( c <= 0.0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'STUDENT_CHECK - Fatal error!\\n' );\n    fprintf ( 1, '  C must be greater than 0.\\n' );\n    check = 0;\n    return\n  end\n\n  check = 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/prob/student_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.589341296690342}}
{"text": "function [kip] = kN2kip(kN)\n% Convert force from kilonewtons to kip. \n% Chad A. Greene 2012\nkip = kN* 0.22480894387;", "meta": {"author": "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/kN2kip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.589341296690342}}
{"text": "function order = IDX2order( IDX )\n% Converts class labels into an ordering.\n%\n% Creates an ordering order such that IDX(order)=[1 1...1 2...2 ... k...k].\n% All points within a class retain the ordering in which they originally\n% appeared.  Also, Xb = X(order,:) has cluster labels IDX(order), ie\n% adjacent elements in X typically belong to the same cluster.\n%\n% USAGE\n%  order = IDX2order( IDX )\n%\n% INPUTS\n%  IDX     - cluster membership [see kmeans2.m]\n%\n% OUTPUTS\n%  order   - n-by-1 vector containing a new ordering for the points.\n%\n% EXAMPLE\n%  order = IDX2order( [1 1 3 1 2 2] )  % should be: [1 2 4 5 6 3]\n%\n% See also DISTMATRIXSHOW\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\nk = max(IDX);  n = length(IDX);\norder = zeros(1,n);  count = 0;\nfor i=1:k\n  locs = (IDX==i); orderi = cumsum(locs);\n  order(locs) = orderi(locs) + count;\n  count = count+sum(locs);\nend\n[dis,order] = sort(order);\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SketchTokens-master/toolbox/classify/private/IDX2order.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.5893412926345273}}
{"text": "classdef IMMOEA_F10 < PROBLEM\n% <multi> <real> <large/none>\n% Benchmark MOP for testing IM-MOEA\n\n%------------------------------- Reference --------------------------------\n% R. Cheng, Y. Jin, K. Narukawa, and B. Sendhoff, A multiobjective\n% evolutionary algorithm using Gaussian process-based inverse modeling,\n% IEEE Transactions on Evolutionary Computation, 2015, 19(6): 838-856.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = [1,zeros(1,obj.D-1)+10];\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            t = X(:,2:obj.D).^(1./(1+3*repmat(2:obj.D,size(X,1),1)/obj.D)) - repmat(X(:,1),1,obj.D-1);\n            g = 1 + 10*(obj.D-1) + sum(t.^2-10*cos(2*pi*t),2);\n            PopObj(:,1) = X(:,1);\n            PopObj(:,2) = g.*(1-sqrt(PopObj(:,1)./g));\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - sqrt(R(:,1));\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R = obj.GetOptimum(100);\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/MOPs with variable linkages/IMMOEA_F10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.5893412884808267}}
{"text": "function [featvec] = MR8fast(im)\n%computes MR8 filterbank using recursive Gaussian filters\n%input: intensity image\n%output: MR8 feature vector\n\npersistent MR8filterNorm;\nobtainFilterNorm = 0;\n\n\n% problematic to do L1 normalization for recursive filters,\n% hence solve it this way...\nif (isempty(MR8filterNorm))\n    MR8filterNorm = 1;\n    obtainFilterNorm = 1;\n    a=zeros(256,256);\n    a(128,128)=1;\nend;\n\nin = double(im) - mean(mean(im));\nin = in ./ sqrt(mean(mean(in .^ 2)));\n\nims = cell(1, 8);\ni=1;\nn=1;\n\nsfac = 0.25;% 1.0;\nmulfac = 2.0;\n\ns1 = 3*sfac; s2 = 1*sfac;\nfor j=0:2,\n    for k=0:5,\n        phi = (k/6.0)*180.0;\n        \n        if (obtainFilterNorm)\n            % this should be done only once....\n            im1 = s2 .* anigauss(a, s1, s2, phi, 0, 1);\n            im2 = (s2*s2) .* anigauss(a, s1, s2, phi, 0, 2);\n            n1 = 1.0/sum(sum(abs(im1)));\n            n2 = 1.0/sum(sum(abs(im2)));\n            MR8filterNorm = [MR8filterNorm, n1, n2];\n        else\n            n1 = MR8filterNorm(n);\n            n = n+1;\n            n2 = MR8filterNorm(n);\n            n = n+1;\n        end;\n\n        im1 = n1 .* anigauss(in, s1, s2, phi, 0, 1);\n        im2 = n2 .* anigauss(in, s1, s2, phi, 0, 2);\n\n        % take max of abs response for first order derivative\n        % Varma&Zisserman also take abs max of second order...\n        im1 = abs(im1);\n        %im2 = abs(im2);\n        if (k==0)\n            maxim1 = im1;\n            maxim2 = im2;\n        else\n            maxim1 = max(maxim1, im1);\n            maxim2 = max(maxim2, im2);\n        end\n    end\n\n    ims{i} = maxim1; i=i+1;\n    ims{i} = maxim2; i=i+1;\n\n    % next octave\n    s1 = s1*mulfac; s2 = s2*mulfac;\nend\n\nsigma = 10.0*sfac;\n\nif (obtainFilterNorm)\n    im1 = anigauss(a, sigma, sigma, 0.0, 2, 0);\n    im2 = anigauss(a, sigma, sigma, 0.0, 0, 2);\n    im1 = (s2*s2) .* (im1+im2);\n    im2 = anigauss(a, sigma, sigma);\n    n1 = 1.0/sum(sum(abs(im1)));\n    n2 = 1.0/sum(sum(abs(im2))); % this one normally should be positive\n    MR8filterNorm = [MR8filterNorm, n1, n2];\nelse\n    n1 = MR8filterNorm(n);\n    n = n+1;\n    n2 = MR8filterNorm(n);\nend;\n\nim1 = anigauss(in, sigma, sigma, 0.0, 2, 0);\nim2 = anigauss(in, sigma, sigma, 0.0, 0, 2);\nims{i} = n1 .* (im1+im2);\ni=i+1;\nims{i} = n2 .* anigauss(in, sigma, sigma);\n\n% just throw away 25 pixel border...(half support of sigma=10 filter)\nif 0\n[R,C] = size(ims{1});\nfor j=1:i,\n    ims{j} = ims{j}(26:R-25,26:C-25);\nend\nend\n\nfeatvec = [ims{8}(:) ims{7}(:) ims{1}(:) ims{3}(:) ims{5}(:) ims{2}(:) ims{4}(:) ims{6}(:)]';\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/textons/MR8fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5893284410551427}}
{"text": "function K = lfmaXlfmKernCompute(lfmKern1, lfmKern2, t1, t2)\n\n% LFMAXLFMKERNCOMPUTE Acceleration and position LFM kernel  \n% FORMAT\n% DESC computes cross kernel terms between acceleration and position LFM\n% kernels.\n% ARG lfmKern1 : the kernel structure associated with the first LFM\n% kernel.\n% ARG lfmKern2 : the kernel structure associated with the second LFM\n% kernel.\n% ARG t : inputs for which kernel is to be computed.\n% RETURN K : block of values from kernel matrix.\n%\n% FORMAT\n% DESC computes cross kernel terms between two LFM kernels for\n% the multiple output kernel.\n% ARG lfmKern1 : the kernel structure associated with the first LFM\n% kernel.\n% ARG lfmKern2 : the kernel structure associated with the second LFM\n% kernel.\n% ARG t1 : row inputs for which kernel is to be computed.\n% ARG t2 : column inputs for which kernel is to be computed.\n% RETURN K : block of values from kernel matrix.\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\nif nargin < 4\n    t2 = t1;\nend\nif size(t1, 2) > 1 || size(t2, 2) > 1\n    error('Input can only have one column');\nend\n\nif lfmKern1.inverseWidth ~= lfmKern2.inverseWidth\n    error('Kernels cannot be cross combined if they have different inverse widths.')\nend\n\n% Get length scale out.\nsigma2 = 2/lfmKern1.inverseWidth;\nsigma = sqrt(sigma2);\n\n% Parameters of the kernel\nalpha(1) = lfmKern1.damper./(2*lfmKern1.mass);\nalpha(2) = lfmKern2.damper./(2*lfmKern2.mass);\nomega(1) = sqrt(lfmKern1.spring./lfmKern1.mass - alpha(1)*alpha(1));\nomega(2) = sqrt(lfmKern2.spring./lfmKern2.mass - alpha(2)*alpha(2));\n\n% Precomputations to increase the speed\npreExp1 = zeros(length(t1),2);\npreExp2 = zeros(length(t2),2);\ngamma1_p = alpha(1) + j*omega(1);\ngamma1_m = alpha(1) - j*omega(1);\ngamma2_p = alpha(2) + j*omega(2);\ngamma2_m = alpha(2) - j*omega(2);\npreGamma(1) = gamma1_p + gamma2_p;\npreGamma(2) = gamma1_p + gamma2_m;\npreGamma(3) = gamma1_m + gamma2_p;\npreGamma(4) = gamma1_m + gamma2_m;\npreConst = 1./preGamma;\npreFactors(1) = preConst(2) - preConst(1);\npreFactors(2) = preConst(3) - preConst(4);\npreFactors(3) = preConst(3) - preConst(1);\npreFactors(4) = preConst(2) - preConst(4);\npreExp1(:,1) = (gamma1_p^2).*exp(-gamma1_p*t1);\npreExp1(:,2) = (gamma1_m^2).*exp(-gamma1_m*t1);\npreExp2(:,1) = exp(-gamma2_p*t2);\npreExp2(:,2) = exp(-gamma2_m*t2);\n% Actual computation of the kernel\nsK = lfmComputeH3AP(gamma1_p, gamma1_m, sigma2, t1,t2,preFactors([1 2]), 0) + ...\n    lfmComputeH3AP(gamma2_p, gamma2_m, sigma2, t2,t1,preFactors([3 4]), 1).' + ...\n    lfmComputeH4AP(gamma1_p, gamma1_m, sigma2, t1, preGamma([1 2 4 3]), preExp2, 0 ) + ...\n    lfmComputeH4AP(gamma2_p, gamma2_m, sigma2, t2, preGamma([1 3 4 2]), preExp1, 1 ).';\n\nif lfmKern1.isNormalised\n    K0 =  lfmKern1.sensitivity*lfmKern2.sensitivity/(8*sqrt(2)*lfmKern1.mass*lfmKern2.mass*prod(omega));\nelse\n    K0 =  sigma*sqrt(pi)*lfmKern1.sensitivity*lfmKern2.sensitivity/(8*lfmKern1.mass*lfmKern2.mass*prod(omega));    \nend\n\nK = K0*sK;\n\n\n\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmaXlfmKernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5893284402786758}}
{"text": "\n% Detect if the expected matte is a highly-transparent one\n% This function implements the energy selection method described in\n% Yagiz Aksoy, Tunc Ozan Aydin, Marc Pollefeys, \"Designing Effective \n% Inter-Pixel Information Flow for Natural Image Matting\", CVPR, 2017.\n% This is a very simple histogram-based classifier.\n\nfunction ht = detectHighlyTransparent(image, trimap)\n\n    image = reshape(im2double(image), [size(image, 1) * size(image, 2), 3]);\n    trimap = im2double(trimap(:,:,1));\n\n    fg = trimap > 0.8;\n    bg = trimap < 0.2;\n    unk = ~(fg | bg);\n    fg = fg & imdilate(unk, ones(20));\n    bg = bg & imdilate(unk, ones(20));\n\n    fgi = image(fg, :);\n    bgi = image(bg, :);\n    uni = image(unk, :);\n\n    fgh = [imhist(fgi(:, 1), 10); imhist(fgi(:, 3), 10); imhist(fgi(:, 3), 10);] / sum(fg(:));\n    bgh = [imhist(bgi(:, 1), 10); imhist(bgi(:, 3), 10); imhist(bgi(:, 3), 10);] / sum(bg(:));\n    unh = [imhist(uni(:, 1), 10); imhist(uni(:, 3), 10); imhist(uni(:, 3), 10);] / sum(unk(:));\n\n    weights = ([fgh bgh]' * [fgh bgh]) \\ ([fgh bgh]' * unh);\n    recError = [fgh bgh] * weights - unh;\n    recError = sqrt(sum(recError(:) .* recError(:))) / size(recError(:), 1);\n\n    ht = recError > 0.0099;\n\nend", "meta": {"author": "yaksoy", "repo": "AffinityBasedMattingToolbox", "sha": "ab3951065321b67d3ad67333779cbb2078474939", "save_path": "github-repos/MATLAB/yaksoy-AffinityBasedMattingToolbox", "path": "github-repos/MATLAB/yaksoy-AffinityBasedMattingToolbox/AffinityBasedMattingToolbox-ab3951065321b67d3ad67333779cbb2078474939/common/detectHighlyTransparent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5893284306814686}}
{"text": "function [I,O] = tone2interval(T,key)\n% MUSIC.TONE2INTERVAL Returns the interval and octave of notes in a key.\n%    I = MUSIC.TONE2INTERVAL(T) returns the interval at which the tones in T are\n%    found in the key of 'C'. T is a vector of semitones defined relative to C4,\n%    where C4 corresponds to tone 0.\n%\n%    I = MUSIC.TONE2INTERVAL(T,KEY) uses the key of KEY. KEY may be an interval\n%    offset from 'C', or a character note (e.g., 'A', 'F#').\n%\n%    [I,O] = MUSIC.TONE2INTERVAL(...) also returns the octave number of each\n%    tone.\n%\n%    Examples\n%       I     = music.tone2interval([7 19])      % returns [7 7]\n%       [I,O] = music.tone2interval([7 19])      % returns [7 7], [4 5]\n%       [I,O] = music.tone2interval([7 19],'G')  % returns [0 0], [4 5]\n%\n%    See also music.tone2freq, music.tone2note,  music.interval2tone.\n\n%    Author: E. Johnson\n%    Copyright 2010 The MathWorks, Inc.\n\nif nargin < 2\n    key = 0;\nend\nif ischar(key)\n    key = music.note2interval(key);\nend\n\nI = mod(T,12) - key;\nI = mod(I,12);\n\nO = 4 + floor(T / 12);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26509-musical-notes/Pitch/+music/tone2interval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5893085418716334}}
{"text": "function [y_cp] = SpanLoading(l_s, l_t, CL, geo, panel)\n%Determine center of pressure and spanwise loading \n%due to bound vortices and trailing vortices.\n\nBV = [panel.BV];\nBV1 = [panel.BV1];\ns = [panel.s]';\n\ny_cp.alpha = sum([l_s.alpha].*BV(2,:)' + [l_t.alpha].*BV1(2,:)')/(0.5*CL.alpha*0.5*geo.b);  %Eqn 35 in NASA paper\ncl.alpha = ([l_s.alpha] + [l_t.alpha])*geo.S./(CL.alpha*2*s*cos(geo.dih)*geo.c_av);  %Eqn 37 in NASA paper\n\nif CL.c ~= 0  %Prevent divide by zero\ny_cp.c = sum([l_s.c].*BV(2,:)' + [l_t.c].*BV1(2,:)')/(0.5*CL.c*0.5*geo.b);  %Eqn 35 in NASA paper\ncl.c = ([l_s.c] + [l_t.c])*geo.S./(CL.c*2*s*cos(geo.dih)*geo.c_av);  %Eqn 37 in NASA paper\nelse\n    y_cp.c = 0;\n    cl.c = zeros(size(cl.alpha));\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/15442-wing-designer/SpanLoading.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5893061124232517}}
{"text": "% DIRECT JACOBIAN DEMO\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 <http://www.gnu.odrg/licenses/>.\n\nclose all;\n\nfprintf('\\nThe demo shows how to compute the end effectors speed as a function of the joint speeds')\n\nrobot =  load_robot('example','scara');\n\nT=1; %seconds. Tiempo que dura el movimiento\n\nq1=0:0.01:pi/2;\nq2=0:0.01:pi/2;\n\nq_v=pi/2/T; %rad/s\nV=zeros(3, length(q1));\nfor i=1:length(q1),\n   v = compute_end_velocity(robot, [q1(i) -q2(i) 0 0], [q_v q_v 0 0]);\n   V(:,i) = v(1:3);\nend\n\nfigure, hold\nplot(V(1, :), 'r')\nplot(V(2, :), 'g')\nplot(V(3, :), 'b')\nlegend('V_x', 'V_y', 'V_z')\ntitle('End effector speed (m/s)')\nxlabel('time (s)')\n\nfigure, hold\nplot(q1, 'r')\nplot(q2, 'g')\nlegend('q_1', 'q_2')\ntitle('Joint positions (rad)')\nxlabel('time (s)')\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/direct_jacobian_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5892963289543282}}
{"text": "function ber0_values_test ( )\n\n%*****************************************************************************80\n%\n%% BER0_VALUES_TEST demonstrates the use of BER0_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, 'BER0_VALUES_TEST:\\n' );\n  fprintf ( 1, '  BER0_VALUES stores values of \\n' );\n  fprintf ( 1, '  the Kelvin function BER of order 0.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '      X           FX\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x, fx ] = ber0_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/ber0_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.5892963223612395}}
{"text": "classdef ZXH_CF5 < PROBLEM\n% <multi/many> <real> <large/none> <constrained>\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    methods\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 Rosenbrock function\n            h = sum(100*((PopDec(:,M+1:end-1)-OptX).^2-(PopDec(:,M+2:end)-OptX)).^2+(PopDec(:,M+1:end-1)-OptX).^2,2);\n            % Step 4: Compute T_\n            T = (1 - Sx(:,1)).^2 + h;\n            % Step 5: Objectives (convex)\n            G      = 1-[ones(N,1) cumprod(sin(pi/2*THETA),2)] .* [cos(pi/2*THETA) ones(N,1)];\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) = max(1/4-THETA(:,i),THETA(:,i)-3/4);\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            T = zeros(size(R));\n            for i = obj.M-1 : -1 : 1\n                T(:,i) = atan((1-R(:,i+1))./(1-R(:,i))./cos(T(:,i+1)));\n            end\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                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_CF5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5892963187336839}}
{"text": "function demhint(nin, nhidden, nout)\n%DEMHINT Demonstration of Hinton diagram for 2-layer feed-forward network.\n%\n%\tDescription\n%\n%\tDEMHINT plots a Hinton diagram for a 2-layer feedforward network with\n%\t5 inputs, 4 hidden units and 3 outputs. The weight vector is chosen\n%\tfrom a Gaussian distribution as described under MLP.\n%\n%\tDEMHINT(NIN, NHIDDEN, NOUT) allows the user to specify the number of\n%\tinputs, hidden units and outputs.\n%\n%\tSee also\n%\tHINTON, HINTMAT, MLP, MLPPAK, MLPUNPAK\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\nif nargin < 1 nin = 5; end\nif nargin < 2 nhidden = 7; end\nif nargin < 3 nout = 3; end\n\n% Fix the seed for reproducible results\nrandn('state', 42);\nclc\ndisp('This demonstration illustrates the plotting of Hinton diagrams')\ndisp('for Multi-Layer Perceptron networks.')\ndisp(' ')\ndisp('Press any key to continue.')\npause\nnet = mlp(nin, nhidden, nout, 'linear');\n\n[h1, h2] = mlphint(net);\nclc\ndisp('The MLP has been created with')\ndisp(['    ' int2str(nin) ' inputs'])\ndisp(['    ' int2str(nhidden) ' hidden units'])\ndisp(['    ' int2str(nout) ' outputs'])\ndisp(' ')\ndisp('One figure is produced for each layer of weights.')\ndisp('For each layer the fan-in weights are arranged in rows for each unit.')\ndisp('The bias weight is separated from the rest by a red vertical line.')\ndisp('The area of each box is proportional to the weight value: positive')\ndisp('values are white, and negative are black.')\ndisp(' ')\ndisp('Press any key to exit.'); \npause; \ndelete(h1);\ndelete(h2);\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/demhint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.5892899866189507}}
{"text": "% Plot the curves extracted via curve_ext or curve_ext_multi\n%\n%  hc = plot_ext_curves(t, x, Tx, fs, Cs, Es, opt, clwin)\n%\n% Input:\n%  t, x, opt: same as input to synsq_cwt_fw/iw\n%  Tx, fs, clwin: same as input to curve_ext_multi\n%  Cs, Es: same as output of curve_ext_multi\n% Output:\n%  hc: Object handle for the resulting figure\n%\n%---------------------------------------------------------------------------------\n%    Synchrosqueezing Toolbox\n%    Authors: Eugene Brevdo (http://www.math.princeton.edu/~ebrevdo/)\n%---------------------------------------------------------------------------------\nfunction hc = plot_ext_curves(t, x, Tx, fs, Cs, Es, opt, clwin)\n\nif nargin<8, clwin = 4; end\nif nargin<7, opt = struct(); end\n\nif ~isfield(opt, 'markers')\n  opt.markers = {'+','o','*','x','s','d','^','v','>','<','p','h' };\nend\n\nNc = length(Es);\n[na, N] = size(Tx);\n\nassert(N == length(t));\nassert(N == length(x));\nNc = length(Es);\n\n% Reconstruct the curve signals\nxrs = curve_ext_recon(Tx, fs, Cs, opt, clwin);\n\nhca = gcf;\n\n% Plot everything\nif isfield(opt, 'hc'),\n    hc(1) = opt.hc(1);\n    subplot(hc(1));\nelse\n    hc(1) = subplot(2, 1, 1);\nend\n\n% Plot Tx\ntplot(Tx, t, fs, opt);\n% Set T-axis properly\naxis tight;\nxlabel('t');\nylabel('f');\ntitle('Extracted Contour(s)');\n\n% Plot the contours\nhold on;\ncpl=plot_markers(t, log2(fs(Cs)), opt.markers, '--k', 'LineWidth', 2);\nlegend(cpl, cellfun(@(j) {sprintf('k=%g', j)}, num2cell(1:Nc)));\n\nif isfield(opt, 'hc')\n    hc(2) = opt.hc(2);\n    subplot(hc(2));\nelse\n    hc(2) = subplot(2, 1, 2);\nend\n\n% % Plot both original signal and extracted contour\nlcs = plot(t, x, 'k'); hold on;\nlcs = [lcs plot_markers(t, xrs, opt.markers, '--k', 'LineWidth', 1)];\n\naxis tight;\nxlabel('t');\nylabel('x_c(t)');\ngrid on;\ntitle('Reconstruction of Extracted Contour');\nxcleg = arrayfun(@(j) {sprintf('x_%g(t)', j)}, 1:Nc);\nlegend(lcs, 'x(t)', xcleg{:});\n\nlinkaxes([hc(1) hc(2)], 'x');\nzec = zoom(hca);\nset(zec, 'RightClickAction', 'InverseZoom');\nsetAxesZoomMotion(zec, hc(1), 'vertical');\nsetAxesZoomMotion(zec, hc(2), 'horizontal');\nset(zec, 'Enable', 'on');\n\nend", "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/plot_ext_curves.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5892899826120184}}
{"text": "function k = findrows(A, b)\n%FINDROWS Find indices of a given row within a matrix.\n%\n%   FINDROWS(A, B) returns a column vector with the indices of the rows\n%   in the matrix A that are identical to the row vector B.  If no rows\n%   in A are identical to B, an empty vector is returned.\n%\n%   The methods uses a for-loop, but it uses less memory and is in many\n%   cases a lot faster than the vectorized methods\n%\n%      find( all( A == repmat(b, size(A, 1), 1), 2 ) )\n%      find( all( A == b(ones(size(A, 1), 1),:), 2 ) )\n%\n%   See also FIND, FINDCOLS.\n\n%   Author:      Peter J. Acklam\n%   Time-stamp:  2002-03-03 13:51:15 +0100\n%   E-mail:      pjacklam@online.no\n%   URL:         http://home.online.no/~pjacklam\n\n   k = find( A(:,1) == b(1) );\n   for j = 2:size(A, 2)\n      k = k( A(k,j) == b(j) );\n      if isempty(k)\n         return\n      end\n   end\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/lib/util/matutil/findrows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.5892899745981537}}
{"text": "function varargout = plotss(varargin)\n% VL_PLOTSS Plot scale space\n%   VL_PLOTSS(SS) plots the scale space SS. SS is a structure\n%   with the following members:\n%\n%   ss.firstOctave::\n%     The index of the first octave in the scale space.\n%\n%   ss.lastOctave::\n%     The index of the last octave in the scale space.\n%\n%   ss.octaveResolution::\n%     The octave resolution, i.e. the nubmer of subdivisions\n%     per octave.\n%\n%   ss.octaveFirstLevel::\n%     The index of the first level of subdivisions for each octave.\n%\n%   ss.octaveLastLevel::\n%     The iundex of last leve of subdivisions for each cotave.\n%\n%   ss.data::\n%     A cell array of 3D arrays representing the scale space data.\n%     The cell array has a length equal to the nubmer of octaves\n%     contained in the scale space. Each entry is a 3D array, the\n%     first two dimensions of which correspond to image rows and\n%     columns respectively, and the third to scale levels.\n%\n%   ss.sigma0::\n%     Base smoothing.\n%\n%   A scale space is a representation of a 2D signal (image) at\n%   multiple scales. In the simplest case, a scale SIGMA is defined as\n%   the input image I(x,y) convolved by a Gaussian kernel of isotropic\n%   standard deviation SIGMA:\n%\n%     I(x,y;sigma) = (g_sigma * I)(x,y)\n%\n%   where scales are sampled as follows:\n%\n%     sigma(o,s) = sigma0 2^{o + s / ss.octaveResolution),\n%     ss.firstOctave <= o <= ss.lastOctave,\n%     ss.octaveFirstLeve <= s <= ss.octaveLastLevel.\n%\n%   Moving from one octave to the next, the size of the kernel\n%   doubles. Hence the effective bandwith of the signal halves, and\n%   resolution can be reduced by half. Typically, for example, sigma0\n%   = 1.6, so at octave 0 the image can be effectively sampled with a\n%   step of 1, and the resolution of octave 0 is the same as the one\n%   at which the input image is presented. Then at octave o the\n%   sampling step is 2^o.\n%\n%   ss.octaveResolution is the number of scale subdivisions per\n%   octave. ss.firstOctave and ss.lastOctave give the additional\n%   flexibility of specifying a range for the level index s to exceed\n%   the standard setting [0, ss.octaveResolution-1]. In this manner\n%   the same scales can be represented twice, at two sampling\n%   rates. This is often convenient in feature computation (e.g. to\n%   find local maxima in scale of a function).\n%\n%   VL_PLOTSS(SS, 'Option', value) supports the following options:\n%\n%   Uniform:: false\n%     If TRUE then use a fixed gray scale for all the levels.\n[varargout{1:nargout}] = vl_plotss(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/plotss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.5892899745981537}}
{"text": "function y=agd(x)\n\n% Inverse Gudermannian function\ny=atanh(sin(x));\n\n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/agd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.589289966290658}}
{"text": "function [trop_delay,var]=trop_mops(time,pos,azel)\n\nk1=77.604;k2=382000;rd=287.054;gm=9.784;g=9.80665;\npersistent pos_ zh zw\nsinel=sin(azel(2)); h=pos(3);\n\nif isempty(pos_),pos_=zeros(3,1);end\nif isempty(zh),zh=0;end\nif isempty(zh),zh=0;end\n\nif pos(3)<-100||pos(3)>10000||azel(2)==0\n    trop_delay=0;\n    var=0;\n    return;\nend\n\nif zh==0||abs(pos(1)-pos_(1))>1e-7||abs(pos(2)-pos_(2))>1e-7||abs(pos(3)-pos_(3))>1\n    met=getmet(pos(1)*180/pi);\n    if pos(1)>=0\n        tmp=28;\n    else\n        tmp=211;\n    end\n    doy=time2doy(time);\n    c=cos(2*pi*(doy-tmp)/365.25);\n    for i=1:5\n        met(i)=met(i)-met(i+5)*c;\n    end\n    zh=1E-6*k1*rd*met(1)/gm;\n    zw=1E-6*k2*rd/(gm*(met(5)+1.0)-met(4)*rd)*met(3)/met(2);\n    zh=zh*(1.0-met(4)*h/met(2))^(g/(rd*met(4)));\n    zw=zw*(1.0-met(4)*h/met(2))^((met(5)+1.0)*g/(rd*met(4))-1.0);\n    for i=1:3\n        pos_(i)=pos(1);\n    end\nend\n\nm=1.001/sqrt(0.002001+sinel*sinel); %mapping function of GCAT model\ntrop_delay=(zh+zw)*m;\nvar=0.12*0.12*m*m;\n\nreturn\n    \n    ", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/common/trop_mops.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5892485407802402}}
{"text": "function value = smach ( job )\n\n%*****************************************************************************80\n%\n%% SMACH computes machine parameters of floating point arithmetic.\n%\n%  Discussion:\n%\n%    This routine is for testing only.  It is not required by LINPACK.\n%\n%    If there is trouble with the automatic computation of these quantities,\n%    they can be set by direct assignment statements.\n%    We assume the computer has\n%\n%      B = base of arithmetic\n%      T = number of base B digits\n%      L = smallest possible exponent\n%      u = largest possible exponent\n%\n%    then\n%\n%      EPS = B**(1-T)\n%      TINY = 100.0D+00 *B**(-L+T)\n%      HUGE = 0.01D+00 *B**(U-T)\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    08 June 2005\n%\n%  Author:\n%\n%    MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Jack Dongarra, Cleve Moler, Jim Bunch and Pete Stewart,\n%    LINPACK User's Guide,\n%    SIAM, 1979.\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 JOB:\n%    1: requests EPSILON;\n%    2: requests TINY;\n%    3: requests HUGE.\n%\n%    Output, real VALUE, the requested value.\n%\n  s = 1.0;\n\n  while ( 1 )\n\n    tiny = s;\n    s = s / 2.0;\n\n    if ( s * 1.0 == 0.0 | s == 0.0 )\n      break\n    end\n\n  end\n\n  tiny = ( tiny / eps ) * 100.0;\n  huge = 1.0 / tiny;\n\n  if ( job == 1 )\n    value = eps;\n  elseif ( job == 2 )\n    value = tiny;\n  elseif ( job == 3 )\n    value = huge;\n  else\n    xerbla ( 'SMACH', 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/blas0/smach.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5892233536943476}}
{"text": "classdef LIRCMOP4 < PROBLEM\n% <multi> <real> <large/none> <constrained>\n% Constrained benchmark MOP with large infeasible regions\n\n%------------------------------- Reference --------------------------------\n% Z. Fan, W. Li, X. Cai, H. Huang, Y. Fang, Y. You, J. Mo, C. Wei, and E.\n% Goodman, An improved epsilon constraint-handling method in MOEA/D for\n% CMOPs with large infeasible regions, Soft Computing, 2019, 23:\n% 12491-12510.\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 Wenji Li\n    \n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values and constraint violations\n        function Population = Evaluation(obj,varargin)\n            X = varargin{1};\n            X = max(min(X,repmat(obj.upper,size(X,1),1)),repmat(obj.lower,size(X,1),1));\n            x_odd       = X(:,3:2:end);\n            x_even      = X(:,2:2:end);\n            len_odd     = size(x_odd,2); \n            len_even    = size(x_even,2);\n            g_1         = sum((x_odd - repmat(X(:,1),1,len_odd)).^2,2);\n            g_2         = sum((x_even - repmat(X(:,1),1,len_even)).^2,2);  \n            PopObj(:,1) = X(:,1) + g_1;\n            PopObj(:,2) = 1 - sqrt(X(:,1)) + g_2;\n            PopCon(:,1) = (0.5 - g_1).*(0.51 - g_1);\n            PopCon(:,2) = (0.5 - g_2).*(0.51 - g_2);\n            PopCon(:,3) = 0.5 - sin(20 * pi * X(:,1));\n            Population  = SOLUTION(X,PopObj,PopCon,varargin{2:end});\n            obj.FE      = obj.FE + length(Population);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - sqrt(R(:,1));\n            R(sin(20*pi*R(:,1))<0.5,:) = [];\n            R      = R + 0.5;\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R(:,1) = linspace(0,1,100)';\n            R(:,2) = 1 - sqrt(R(:,1));\n            R(sin(20*pi*R(:,1))<0.5,:) = nan;\n            R      = R + 0.5;\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/LIR-CMOP/LIRCMOP4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5892233523446969}}
{"text": "function out = ctranspose3x3(in)\n\n% compute ctranspose of multiple 3x3 matrices, input is 3x3xN\n\nout = conj(in);\nout(1,2,:,:) = conj(in(2,1,:,:));\nout(2,1,:,:) = conj(in(1,2,:,:));\nout(1,3,:,:) = conj(in(3,1,:,:));\nout(3,1,:,:) = conj(in(1,3,:,:));\nout(2,3,:,:) = conj(in(3,2,:,:));\nout(3,2,:,:) = conj(in(2,3,:,:));\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/connectivity/private/ctranspose3x3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128672997041658, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5892233488630081}}
{"text": "function f=peven(f,dim)\n%PEVEN   Even part of periodic function\n%   Usage:  fe=peven(f);\n%           fe=peven(f,dim);\n%\n%   `peven(f)` returns the even part of the periodic sequence *f*.\n%\n%   `peven(f,dim)` does the same along dimension *dim*.\n%\n%   See also:  podd, dft, involute, pconv\n  \nif nargin==1\n  f=(f+involute(f))/2;\nelse\n  f=(f+involute(f,dim))/2;\nend;\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/fourier/peven.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.5891873606761561}}
{"text": "function asa266_test07 ( )\n\n%*****************************************************************************80\n%\n%% TEST07 tests PPCHI2.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    04 August 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n  nitest = 9;\n  njtest = 9;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST07\\n' );\n  fprintf ( 1, '  PPCHI2 computes the percentage points\\n' );\n  fprintf ( 1, '  of the chi squared distribution.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  CDF, PPCHI2(CDF)\\n' );\n  fprintf ( 1, '\\n' );\n\n  for j = 1 : njtest\n\n    v = j;\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  For Chi^2 parameter value %f\\n', v );\n    fprintf ( 1, '\\n' );\n\n    for i = 1 : nitest\n\n      cdf = i / ( nitest + 1 );\n      [ x1, ifault ] = ppchi2 ( cdf, v );\n\n      fprintf ( 1, '  %12f  %12f\\n', cdf, x1 );\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/asa266/asa266_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833945721305, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.5891873604315091}}
{"text": "function r=randSequence(maxN,N)\n% r=randSequence(maxN,N)\n% produces a random  increasing sequence \n% that includes N integers 1:maxN\n% (N<maxN)\n\nif N>=maxN, error('N is not less than maxN!!!'); end;\n\nfact=maxN/((maxN-N)*2);\nind=[];\n\nwhile length(ind)~=N,\n  ind=find(round(rand(1,maxN)*fact)>0);\nend;\nr=1:maxN;\nr=r(ind);", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/OptimizeDesign11/M-sequence/randSequence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5891707614022996}}
{"text": "% counting.m\n%\n%\n% \n% author: Young-Seok Kweon\n% created: 2020.11.12\n%% init\nclc; clear; close all;\n%% load\n\nlist=dir('Dataset\\*.mat');\n\n%% counting\n\nname=[];\nfor i=1:length(list)\n    temp=list(i).name;\n    temp=split(temp,'_');\n    name(i)=str2num(temp{1});\nend\n%%\ncount(max(name))=0;\nfor i=1:length(list)\n    count(name(i)) = count(name(i))+1;\nend\n\nfor i=unique(count)\n    if i==0\n        continue;\n    end\n    \n    n(i)=sum(count==i);\nend\n\n%%\ndir_='F:\\wsc\\datasets\\wsc-dataset-0.1.0.csv';\n\n[num, txt, raw]=xlsread(dir_);\n\n\nyear=count;\nc=count;\nyear(:)=0;\nc(:)=0;\nfor i=1:length(list)\n    if c(num(i,1))~=0\n        year(num(i,1))=year(num(i,1))+num(i,3)-c(num(i,1));\n        c(num(i,1))=num(i,3);\n    else\n        c(num(i,1))=num(i,3);\n    end\nend\nyear=year./count;\nfor i=unique(count)\n    if i==0\n        continue;\n    end\n    \n    n(i)=mean(year(count==i));\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_Consciousness/ysk/counting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7185943865443349, "lm_q1q2_score": 0.5891707614022996}}
{"text": "% Test file for Scaling Functions\n%\n% Copyright (c) 2018 Department of Computer Science,\n%                    University of Toronto, Canada,\n%                    Vector Institute, Canada\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%  Yingxue Wang <yingxue@cs.toronto.edu>\n%  Sean Robertson <sdrobert@cs.toronto.edu>\n%\n\nclassdef test_scales < matlab.unittest.TestCase\n    \n    properties\n        scaling_function\n    end \n    \n    methods(TestMethodSetup)\n        function setScalingFunction(testCase)\n            testCase.scaling_function = MelScaling();\n        end\n    end\n\n    methods (Test)\n        function test_scales_invertible(testCase)\n             for hertz = 200:100:2000\n                scale = testCase.scaling_function.hertz_to_scale(hertz);\n                testCase.verifyEqual(hertz, testCase.scaling_function.scale_to_hertz(scale),'relTol',sqrt(eps));\n             end\n        end\n    end\nend\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/feature_extraction/filterbanks/test/test_scales.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5891707572510267}}
{"text": "% Gianni Schena  July 2005, schena@units.it\n% Lattice Boltzmann LBE, geometry: D2Q9, model: BGK\n% Application to permeability in porous media (low porosity)\n\nRestart=false\nlogical(Restart);\n\nif Restart==false;\nclose all, clear all % start from scratch and clean ...\nRestart=false;\nPois_test=false, % for a test without obstacles\ntic\n%   IN\n% |vvvv|    + y\n% |vvvv|     ^\n% |vvvv|     | -> + x\n%  OUT\n\n% Pores in 2D : Wet and Dry locations (Wet ==1 , Dry ==0 )\nwXh_Dry=[3,1];wXh_Wet=[3,5];\n%wXh_Dry=[3,0];wXh_Wet=[3,5]; % test non obstacles !!!\nA=repmat([zeros(wXh_Dry),ones(wXh_Wet)],[1,3]);A=[A,zeros(wXh_Dry)]\nB=ones(size(A)); C=[A;B]  ;\nD=repmat(C,3,1);\nD=[B;B;D;B]; \nimshow(D,[]) ; % monitor the pore space\nChannel2D=D;\nLen_Channel_2D=size(Channel2D,1); % Length\nWidth=size(Channel2D,2); % should not be hod\nChannel_2D_half_Width=Width/2,\n\n% test without obstacles (i.e. 2D channel & no obstacles)\n\nif (Pois_test)\n%over-writes the definition of the pore space\nclear Channel2D\nLen_Channel_2D=18, \nChannel_2D_half_Width=4; Width=Channel_2D_half_Width*2;\nChannel2D=ones(Len_Channel_2D,Width); % define wet area\n%Channel2D(6:12,6:8)=0; % put fluid obstacle\nimshow(Channel2D,[]);\nend\n\n[Nr Mc]=size(Channel2D); % Number rows and Munber columns\n\n% FLUID PROPERTIES\n% physical properties\ncs2=1/3; % \ncP_visco=0.5; % [cP] 1 CP Dinamic water viscosity 20 C\ndensity=1.; % fluid density \nLky_visco=cP_visco/density; % lattice kinematic viscosity \nomega=(Lky_visco/cs2+0.5).^-1; %  omega: relaxation frequency\n%Lky_visco=cs2*(1/omega - 0.5) , % lattice kinematic viscosity\n%dPdL= Pressure / dL;% External pressure gradient [atm/cm]\n\nuy_fin_max=-0.2; \n%dPdL = abs( 2*Lky_visco*uy_fin_max/(Channel_2D_half_Width.^2) ); \ndPdL=-0.0125;\nuy_fin_max=dPdL*(Channel_2D_half_Width.^2)/(2*Lky_visco); % Poiseuille Gradient;\n% max poiseuille final  velocity on the flow profile\nuy0=-0.001; ux0=0.0001; %  linear vel .. inizialization\n\n% \n% uy_fin_max=-0.2; % max poiseuille final  velocity on the flow profile\n% omega=0.5, cs2=1/3; % omega: relaxation frequency\n% Lky_visco=cs2*(1/omega - 0.5) , % lattice kinematic viscosity\n% dPdL = abs( 2*Lky_visco*uy_fin_max/(Channel_2D_half_Width.^2) ); % Poiseuille Gradient;\n% \n\nuyf_av=uy_fin_max*(2/3);; % average fluid velocity on the profile\n\nx_profile=([-Channel_2D_half_Width:+Channel_2D_half_Width-1]+0.5);\nuy_analy_profile=uy_fin_max.*(1-  ( x_profile /Channel_2D_half_Width).^2 ); % analytical velocity profile\n\nav_vel_t=1.e+10; % inizialization (t=0)\n%PixelSize= 5; % [Microns]\n%dL=(Nr*PixelSize*1.0E-4); % sample hight [cm]\n\n\n%\n% EXPERIMENTAL SET-UP\n% inlet and outlet buffers\ninb=2, oub=2; % inlet and outlet buffers thickness\n% add fluid at the inlet (top) and outlet (down)\ninlet=ones(inb,Mc); outlet=ones(oub,Mc);\nChannel2D=[ [inlet]; Channel2D ;[outlet] ] ; % add flux in and down (E to W)\n[Nr Mc]=size(Channel2D); % update size\n% boundaries related to the experimental set up\nwb=2; % wall thickness\nChannel2D=[zeros(Nr,wb), Channel2D , zeros(Nr,wb)]; % add walls (no fluid leak)\n[Nr Mc]=size(Channel2D); % update size\nuy_analy_profile=[zeros(1,wb), uy_analy_profile, zeros(1,wb) ] ; % take into account walls\nx_pro_fig=[[x_profile(1)-[wb:-1:1]], [x_profile, [1:wb]+x_profile(end)] ];\n\n% Figure plots analytical parabolic profile\nfigure(20), plot(x_pro_fig,uy_analy_profile,'-'), grid on,\ntitle('Analytical parab. profile for Poiseuille planar flow in a channel')\n\n\n% VISUALIZE PORE SPACE & FLUID OSTACLES & MEDIAL AXIS\nfigure, imshow(Channel2D); title('Vassel geometry');\nChannel2D=logical(Channel2D);\n% obstacles for Bounce Back ( in front of the grain)\nObstacles=bwperim(Channel2D,8); % perimeter of the grains for bounce back Bound.Cond.\nObstacles([1:inb,Nr-oub:Nr],[wb+2:Mc-wb-1])=0;\n\nfigure, imshow(Obstacles); title(' Fluid obstacles (in the fluid)' );\n% \nMedial_axis=bwmorph(Channel2D,'thin',Inf); %\nfigure, imshow(Medial_axis); title('Medial axis');\n%figure(10) % used to visualize evolution of rho\n%figure(11) % used to visualize ux\n%figure(12) % used to visualize uy (i.e. top -> down)\n\n% porosity\nporosity=nnz(Channel2D==1)/(Nr*Mc)% porosity\nporosity=nnz(Channel2D( :,[(wb+1):(Mc-wb)] )==1)./(Nr*(Mc-2*wb))\n% exclude the wall from counting \n\n\n% INDICES\n% Wet locations etc.\n[iabw1 jabw1]=find(Channel2D==1); % indices i,j, of active lattice locations i.e. pore\nlena=length(iabw1); % number of active location i.e. of pore space lattice cells\nija= (jabw1-1)*Nr+iabw1; % equivalent single index (i,j)->> ija for active locations\n% absolute (single index) position of the obstacles in for bounce back in Channel2D\n% Obstacles \n[iobs jobs]=find(Obstacles);lenobs=length(iobs); ijobs= (jobs-1)*Nr+iobs; % as above\n% Medial axis of the pore space\n[ima jma]=find(Medial_axis); lenma=length(ima);  ijma= (jma-1)*Nr+ima; % as above\n% Internal wet locations : wet & ~obstables\n% (i.e. internal wet lattice location non in contact with dray locations)\n[iawint jawint]=find(( Channel2D==1 & ~Obstacles)); % indices i,j, of active lattice locations\nlenwint=length(iawint); % number of internal (i.e. not border) wet locations\nijaint= (jawint-1)*Nr+iawint; % equivalent singl\nNxM=Nr*Mc;\n\n\n% Look-up table for direct acess to the position of the ija in a wet only\n% array , i.e. from a i,j position in an array (full) to the index in an arry of wet\n% positions only, eg the position 5 is the 3 because 2 pixels are dry \n\n%ija =[2 3 5 9 13]; % wet positions \nLut(:,1)=[1:1:ija(end)]'; Lut(ija,2)=[1:1:length(ija)];\n% Lut use ijac=9 \n% from current ija (dry & wet ) to its position in an array of only wet\n% Lut(ijac,2) ... % alternative find(ija==ijac)\n\n\n% DIRECTIONS: E N W S NE NW SW SE ZERO (ZERO:Rest Particle)\n%    y^\n%  6 2 5           ^         NW  N  NE\n%  3 9 1 ... +x-> +y         W   RP  E\n%  7 4 8                     SW  S  SE\n%   -y\n% x & y components of velocities , +x is to est , +y is to nord\nEast=1; North=2; West=3; South=4; NE=5; NW=6; SW=7; SE=8; RP=9;\nN_c=9 ; % number of directions\n% versors D2Q9\nC_x=[1 0 -1  0 1 -1 -1  1 0]; \nC_y=[0 1  0 -1 1  1 -1 -1 0]; C=[C_x;C_y]\n\n% BOUNCE BACK SCHEME\n% after collision the fluid elements densities f are sent back to the\n% lattice node they come from with opposite direction\n% indices opposite to 1:8 for fast inversion after bounce\nic_op = [3 4 1 2 7 8 5 6]; %   i.e. 4 is opposite to 2 etc.\n\n% PERIODIC BOUNDARY CONDITIONS - reinjection rules\nyi2=[Nr , 1:Nr , 1]; % this definition allows implemening Period Bound Cond\n%yi2=[1, Nr , 2:Nr-1 , 1,Nr]; % re-inj the second last to as first\n% directional weights (density weights)\nw0=16/36. ; w1=4/36. ; w2=1/36.;\nW=[ w1 w1 w1 w1 w2 w2 w2 w2 w0];\n%c constants (sound speed related)\ncs2=1/3; cs2x2=2*cs2; cs4x2=2*cs2.^2;\nf1=1/cs2; f2=1/cs2x2; f3=1/cs4x2;\nf1=3.; f2=4.5; f3=1.5; % coef. of the f equil.\n\n% declarative statemets\nf=zeros(lena,N_c); % array of fluid density distribution\nfeq=zeros(lena,N_c); % f at equilibrium\nrho=ones(lena,1); % macro-scopic density\ntemp1=zeros(lena,1);\nux=zeros(lena,1);   uy=zeros(lena,1); uyout=zeros(lena,1);  % dimensionless velocities\nuxsq=zeros(lena,1); uysq=zeros(lena,1);   usq=zeros(lena,1);  % higher degree velocities\n% for normal 2d visualization\nuy1=zeros(Nr,Mc);  ux1=zeros(Nr,Mc); \n\n% initialization arrays : start values in the wet area\nfor ia=1:lena % stat values in the active cells only ; 0 outside\n    f(ia,:)=1/9; % uniform density distribution for a start\nend\nuy(:)=uy0; ux(:)=ux0; % initialize fluid velocities\nrho(:)=density;\n\n% EXTERNAL (Body) FORCES e.g. inlet pressure or inlet-outlet gradient\n% directions: E N W S NE NW SW SE ZERO\nforce = -dPdL*(1/6)*1*[0 -1 0 1 -1 -1 1  1  0]'; %;\n%...                   E  N E S NE NW SW SE RP ...\n% the pressure pushes the fluid down i.e. N to S\n\n% While .. MAIN TIME EVOLUTION LOOP\nStopFlag=false; % i.e. logical(0)\nMax_Iter=3000; % max allowed number of iteration\nCheck_Iter=1; Output_Every=8; % frequency of check & output\nCur_Iter=0; % current iteration counter inizialization\ntoler=1.0e-8; % tollerance to declare convegence\nCond_path=[]; % recording values of the convergence criterium\ndensity_path=[]; % recording aver. density values for convergence\nend % ends if restart\n\nif(Restart==true)\n StopFlag=false;  Max_Iter=Max_Iter+3000; toler=1.0e-12; \nend\n\n\nwhile(~StopFlag)\n    Cur_Iter=Cur_Iter+1 % iteration counter update\n\n    % density and moments\n    rho=sum(f,2); % density\n\n    if Cur_Iter >1 % use inizialization ux uy to start\n        % Moments ... Note:C_x(9)=C_y(9)=0\n       % ux=zeros(lena,1); uy=zeros(lena,1);\n        %for ic=1:N_c-1;\n         %   ux = ux + C_x(ic).*f(:,ic) ; uy = uy + C_y(ic).*f(:,ic)  ;\n       % end\n        \n        uy=f(:,2) +f(:,5)+f(:,6)-f(:,4)-f(:,7)-f(:,8); % in short !\n        ux=f(:,1) +f(:,5)+f(:,8)-f(:,3)-f(:,6)-f(:,7); % in short !  \n        \n    end\n   \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    ux(:)=ux(:)./rho(:); uy(:)=uy(:)./rho(:);\n    uxsq(:)=ux(:).^2; uysq(:)=uy(:).^2; usq(:)=uxsq(:)+uysq(:); %\n\n    % weighted densities : rest particle, principal axis, diagonals\n    rt0 = w0.*rho; rt1 = w1.*rho; rt2 = w2.*rho;\n    \n    % Equilibrium distribution\n    % main  directions ( + cross)\n    feq(:,1)= rt1(:) .*(1 +f1*ux(:) +f2*uxsq(:) -f3*usq(:));\n    feq(:,2)= rt1(:) .*(1 +f1*uy(:) +f2*uysq(:) -f3*usq(:));\n    feq(:,3)= rt1(:) .*(1 -f1*ux(:) +f2*uxsq(:) -f3*usq(:));\n    %feq(ija+NxM*(3)=f(ija)-2*rt1(ija)*f1.*ux(ija); % much faster... !!\n    feq(:,4)= rt1(:) .*(1 -f1*uy(:) +f2*uysq(:) -f3*usq(:));\n    \n    % diagonals (X diagonals) (ic-1)\n    feq(:,5)= rt2(:) .*(1 +f1*(+ux(:)+uy(:)) +f2*(+ux(:)+uy(:)).^2 -f3.*usq(:));\n    feq(:,6)= rt2(:) .*(1 +f1*(-ux(:)+uy(:)) +f2*(-ux(:)+uy(:)).^2 -f3.*usq(:));\n    feq(:,7)= rt2(:) .*(1 +f1*(-ux(:)-uy(:)) +f2*(-ux(:)-uy(:)).^2 -f3.*usq(:));\n    feq(:,8)= rt2(:) .*(1 +f1*(+ux(:)-uy(:)) +f2*(+ux(:)-uy(:)).^2 -f3.*usq(:));\n    % rest particle (.) ic=9\n    feq(:,9)= rt0(:) .*(1 - f3*usq(:));\n\n    %Collision (between fluid elements)omega=relaxation frequency\n    f=(1.-omega).*f + omega.*feq;\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %add external body force due to the pressure gradient prop. to dPdL\n    for ic=1:N_c;%-1\n       % for ia=1:lena\n           % i=iabw1(ia);  j=jabw1(ia);\n            % if Obstacles(i,j)==0 % the i,j is not aderent to the boundaries\n            f(:,ic)= f(:,ic) + force(ic);\n            % end\n       % end\n    end\n\n    % % STREAM\n    % Forward Propagation step & % Bounce Back (collision fluid with obstacles)\n    %f(:,9) = f(:,9); % Rest element do not move\n   \n    feq = f; % temp storage of f in feq\n        for ic=1:1:N_c-1, % select velocity layer\n        C_yic = C_y(ic); C_xic = C_x(ic);\n        ic2=ic_op(ic); % selects the layer of the velocity opposite to ic for BB\n        temp1=feq(:,ic); %\n\n        % from wet location that are NOT on the border to other wet locations\n        for ia=1:1:lenwint % number of internal (i.e. not border) wet locations\n            i=iawint(ia);  j=jawint(ia);  % so that we care for the wet space only !\n            i2 = i+C_yic; j2 = j+C_xic; % Expected final locations to move\n            i2=yi2(i2+1); % i2 corrected for PBC when necessary (flow out re-fed to inlet)\n            % i.e the new position (i2,j2)==ia2 is sure another wet location\n            % therefore normal propagation from (i,j)==ijaint to (i2,j2)==ia2 on layer ic\n            ia2=(j2-1)*Nr+i2; iarec2=Lut(ia2,2) ; % use lut (look up table)\n            iarec1=Lut(ijaint(ia),2) ;\n            f(iarec2,ic)=temp1(iarec1); % copy \n        end ; % i and j single loop\n\n        % from wet locations that ARE on the border of obstacles\n        for ia=1:1:lenobs % wet border locations\n            i=iobs(ia);  j=jobs(ia);  % so that we care for the wet space only !\n            i2 = i+C_yic; j2 = j+C_xic; % Expected final locations to move\n            i2=yi2(i2+1); % i2 corrected for PBC\n            iarec1=Lut(ijobs(ia),2) ;\n            if( Channel2D(i2,j2) ==0 ) % i.e the new position (i2,j2) is dry\n               f(iarec1,ic2) =temp1(iarec1); % invert direction: bounce-back in the opposite direction ic2\n            else % otherwise, normal propagation from (i,j) to (i2,j2) on layer ic\n               ia2=(j2-1)*Nr+i2; iarec2=Lut(ia2,2) ;\n               f(iarec2,ic)=temp1(iarec1); % \n            end ; % b.b. and propagations\n\n        end ; % i and j single loop\n        % special treatment for Corners\n        %   f(1,wb+1,ic)=temp1(Nr,Mc-wb);      f(1,Mc-wb,ic)=temp1(Nr,wb+1);\n        %   f(Nr,wb+1,ic)=temp1(1,Mc-wb);      f(Nr,Mc-wb,ic)=temp1(1,wb+1);\n\n    end ; %  for ic direction\n\n    % ends of Forward Propagation step &  Bounce Back Sections\n\n    % re-calculate  uy as uyout for convergence\n    rho=sum(f,2); % density\n    % check velocity\n%     uyout= zeros(lena,1);\n%     for ic=1:N_c-1;\n%         uyout= uyout + C_y(ic).*f(:,ic) ; % flow dim.less velocity out\n%     end\n%    % uyout(ija)=uyout(ija)./rho(ija); % from momentum to velocity\n\n    % Convergence check on velocity values\n    if (mod(Cur_Iter,Check_Iter)==0) ; % check for convergence every 'Check_Iter' iterations\n\n        % variables monitored\n        % mean density and\n        vect=rho(:); vect=vect(:); \n        cur_density=mean(vect);\n        % mean 'interstitial' velocity\n        % uy(ija)=uy(ija)/rho(ija); ?\n        vect=uy(:); av_vel_int= mean(vect)  ; % seepage velocity (in the wet area)\n        % on the whole cross-sectional area of flow (wet + dry)\n        av_vel_int=av_vel_int*porosity, % av. vel. on the wet + dry area\n        %av_vel_int=mean2(uy),\n        av_vel_tp1 = av_vel_int; \n        Condition=abs( abs(av_vel_t/av_vel_tp1 )-1), % should --> 0\n\n        Cond_path=[Cond_path, Condition]; % records the convergence path (value)\n        density_path=[density_path, cur_density];\n        %\n        av_vel_t=av_vel_tp1; % time t & t+1 \n\n        if (Condition < toler) | (Cur_Iter > Max_Iter)\n            StopFlag=true;\n            display( 'Stop iteration: Convergence met or iteration exeeding the max allowed' )\n            display( ['Current iteration: ',num2str(Cur_Iter),...\n                ' Max Number of iter: ',num2str(Max_Iter)] )\n            break % Terminate execution of WHILE .. exit the time evolution loop.\n\n        end    % if(Condition < toler\n\n    end\n\n    if (mod(Cur_Iter,Output_Every)==0) ;  % Output from loop every ...\n        %if (Cur_Iter>60) ;  % Output from loop every ...\n\n       % rho=sum(f,2); % density\n       % figure(10); imshow(rho,[0.1 0.9]); title(' rho'); % visualize density evolution\n        uy1(ija)=uy;  ux1(ija)=ux;\n        %figure(11); imshow(ux1,[ ]); title(' ux' ); % visualize fluid velocity horizontal\n        %figure(12); imshow(-uy1,[ ]); title(' uy' ); % visualize fluid velocity down\n        %figure(14), imshow(-uyout,[]), title('uyout'); % vis vel flow out\n        up=2; % linear section to visualize up from the lower row\n        figure(15), hold off, feather(ux1(Nr-up,:),uy1(Nr-up,:)),\n        figure(15), hold on , plot(uy_analy_profile,'r-')\n        title('Analytical (i.e. no obstacles) vs LB calculated (Blue), fluid velocity profile')\n        pause(1); % time given to visualize properly\n\n    end % every\n\n\n   % pause(1);\n\n    \nend %  End main time Evolution Loop\n\n% Output & Draw after the end of the time evolution\n\nfigure, plot(Cond_path(2:end)); title('convergence path')\n%figure, plot(density_path(2:end)); title('density convergence path')\nfigure, plot( [uy1(Nr-up,:)-uy_analy_profile] ); title('difference : LB - Analytical solution')\n\ntoc\n\n% Permeability K\n\nK_Darcy_Porous_Sys= (av_vel_int*porosity)/dPdL*Lky_visco ,\n\nK_Analy_2D_Channel=(Width^2)/12", "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/Porous2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126791, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.5891707554723536}}
{"text": "function [ft3] = l2ft3(l)\n% Convert volume from liters to cubic feet. \n% Chad Greene 2012\nft3 = l*0.035314666721;", "meta": {"author": "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/l2ft3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5891707523099224}}
{"text": "function err = getL2error3RT0(node,elem,sigma,sigmah,markedElem)\n%% GETL2ERROR3RT0  L2 norm of RT0 element in 3D.\n% \n%  err = getL2error3RT0(node,elem,sigma,sigmah,markedElem)\n%\n%  The input sigma can just be a function boundle. sigmah is the flux\n%  through faces. markedElem is used to compute the error in certain region\n%  only.\n%  \n%  Note that the ascend ordering of elem is used. \n%   \n% Example\n%   \n%   [node,elem] = cubemesh([-1,1,-1,1,-1,1],1);\n%   maxIt = 3;\n%   pde = mixBCdata3;\n%   err = zeros(maxIt,1); \n%   h = zeros(maxIt,1);\n%   for i = 1:maxIt\n%      [node,elem] = uniformrefine3(node,elem);\n%      uI = faceinterpolate3(pde.Du,node,elem);\n%      err(i) = getL2error3RT0(node,elem,pde.Du,uI);\n%      h(i) = 2^(-i);\n%   end\n%   figure;\n%   showrateh(h,err,2,'-+','|| u - u_I ||');\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details. \n\n%% Construct Data Structure\nelem = sortelem3(elem); \nelem2face = dof3face(elem); \n% [elem2face,dofSign] = dof3RT0(elem);\nNT = size(elem,1);% Ndof = max(elem2dof(:)); %N = size(node,1); \n[Dlambda,volume] = gradbasis3(node,elem);\nlocFace = [2 3 4; 1 3 4; 1 2 4; 1 2 3];\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    pxyz = 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    sigmap = sigma(pxyz);\n    sigmahp = zeros(NT,3);\n    for l = 1:4 % for each basis\n        i = locFace(l,1); j = locFace(l,2); k = locFace(l,3);\n        % phi_l = 2(lambda_i Dlambda_j x Dlambda_k + \n        %           lambda_j Dlambda_k x Dlambda_i + \n        %           lambda_k Dlambda_i x Dlambda_j)\n        sigmahp = sigmahp + repmat(2*sigmah(elem2face(:,l)),1,3).*...\n                   (lambda(p,i)*mycross(Dlambda(:,:,j),Dlambda(:,:,k)) + ...\n                    lambda(p,j)*mycross(Dlambda(:,:,k),Dlambda(:,:,i)) + ...    \n                    lambda(p,k)*mycross(Dlambda(:,:,i),Dlambda(:,:,j)));\n    end\n    err = err + w(p)*sum((sigmap - sigmahp).^2,2);\nend\nerr = err.*volume;\n% modify the error\nerr(isnan(err)) = 0;\nif (nargin == 5) && ~isempty(markedElem)\n    err = err(markedElem); % L2 err on some marked region\nend\nerr = sqrt(sum(err));", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/getL2error3RT0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5891707459850598}}
{"text": "function T = tprod1(S, U, n)\n%TPROD1 Tensor Product of a tensor and a matrix\n%\tT = TPROD1(S, U, n)\n%\t\n%\tS  - tensor (multidimensional array)\n%\tU  - matrix compatible with the nth size of S ie. size(S,n)==size(U,1)\n%\tn  - execute tprod in this dimension\n%\t\n%\tT  - result of the product\n%\n%\teg. tprod1(ones(2,3,4), [1 0 0; 0 1 0], 2)\n%\n%\tSee also TPROD.\n\n% TODO: n > dimensions of S -> ndim_expand\n\nsiz = size(S);\nsiz(n) = size(U,1);\nH = ndim_unfold(S, n);\nT = ndim_fold(U*H, n, siz);\n", "meta": {"author": "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/tprod1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.5891707438114713}}
{"text": "function [phw,stat]=model_phw(time,sat,type,opt,rs,rr,vs,phw0)\n\nstat=1; ds=zeros(1,3); dr=zeros(1,3);\nif opt==0,phw=phw0;stat=0;return;end\n\n%satellite yaw attitude model\n[exs,eys]=sat_yaw(time,sat,type,opt,rs,vs);\n\n%unit vector satellite to receiver\nr=rr-rs;\nek=r/norm(r);\n\n%unit vectors of receiver antenna\n[~,E]=xyz2blh(rr);\nexr(1)= E(2); exr(2)= E(5); exr(3)= E(8); %x = north\neyr(1)=-E(1); eyr(2)=-E(4); eyr(3)=-E(7); %y = west\n\n%phase windup effect\neks=cross(ek,eys);\nekr=cross(ek,eyr);\nfor i=1:3\n    ds(i)=exs(i)-ek(i)*dot(ek,exs')-eks(i);\n    dr(i)=exr(i)-ek(i)*dot(ek,exr')+ekr(i);\nend\ncosp=dot(ds,dr)/norm(ds)/norm(dr);\nif cosp<-1\n    cosp=-1;\nelseif cosp>1\n    cosp=1;\nend\n\nph=acos(cosp)/2/pi;\ndrs=cross(ds,dr);\ntmp=dot(ek,drs);\nif tmp<0\n    ph=-ph;\nend\nphw=ph+floor(phw0-ph+0.5);\n\nreturn\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/gnss/ppp/model_phw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5891477804797374}}
{"text": "% data1: sea-water Pc\n% Written by Ali A. Eftekhari\n% Last checked: June 2021\ndata{1}=[0.073 249\n0.085 45\n0.09 15\n0.131 8\n0.197 3.33\n0.23 2.22\n0.25 1.79\n0.328 0.6\n0.38 0\n0.5 -0.1\n0.6 -0.3\n0.7 -0.7\n0.8 -2.5\n0.831 -5.8\n0.84 -10\n0.856 -20\n0.863 -32.2\n0.867 -43\n0.869 -49.1\n0.87 -54.3\n0.882 -92.8\n0.893 -126.9\n0.895 -142.5\n0.899 -167.7\n0.901 -250];\n% zero sulphate Pc, table 3\ndata{2}=[0.056 200\n0.058 36.9\n0.073 9.3\n0.112 5.06\n0.137 3.56\n0.176 1.46\n0.232 0.5\n0.28 0\n0.503 -0.8\n0.606 -1.13\n0.698 -2\n0.768 -3\n0.793 -4\n0.81 -5\n0.827 -13\n0.84 -31.4\n0.857 -79.3];\n% 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(min(sw1),max(sw1),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\npc=@(sw, cwi, coi, awi, aoi, swc, sor)(cwi./((sw-swc)/(1-swc)).^awi+coi./((1-sw-sor)/(1-sor)).^aoi);\nswc0=0.0789;\nsor0=0.2529;\nlabda=2.4;\nf=@(x, sw)pc(sw, x(1), x(2), 1/labda, 1/labda, swc0, sor0);\nfw=@(x, sw)pc(sw, x(1), 0.0 , x(3), x(4), swc0, sor0);\nfo=@(x, sw)pc(sw, 0.0, x(2), x(3), x(4), swc0, sor0);\nx=lsqcurvefit(f, [1e3, -1e3],sw1, pc1)\nx=patternsearch(@(x)(sum(abs(f(x, sw1)-pc1))), x)\nplot(sw1, pc1, 'o', sw_plot, f(x, sw_plot))%, ...\n% sw_plot, fw(x, sw_plot), '--', ...\n% sw_plot, fo(x, sw_plot), '-.'); \ngrid;", "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_sw_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5891450364110582}}
{"text": "function [logp,logq1,logq2] = spm_mci_switch (Pr,M,U,Y,beta)\n% Return log probability of tempered model switch\n% FORMAT [logp,logq1,logq2] = spm_mci_switch (Pr,M,U,Y,beta)\n%\n% Pr        parameters (vectorised and in M.V subspace)\n% M,U,Y     as usual\n% beta      inverse temperature (set to 1 to get usual posterior)\n%\n% logp      log prob of model switch\n% logq1     log joint of model 1\n% logq2     log joint of model 2\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_mci_switch.m 6548 2015-09-11 12:39:47Z will $\n\nlogq1 = spm_mci_joint(Pr,M{1},U{1},Y);\n\n% Parameters in original space\nP = M{1}.V*Pr+M{1}.vpE;\n[L2,tmp,st] = feval(M{2}.L,P,M{2},U{2},Y);\ne = P-M{2}.vpE;\nL1 = - e'*M{2}.ipC*e/2 + M{2}.log_prior_t2;\nlogq2 = L1+L2;\n\nlogp=(1-beta)*logq1+beta*logq2;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/inference/spm_mci_switch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5891450262633972}}
{"text": "%  Figure 3.16      Feedback Control of Dynamic Systems, 6e\n%                        Franklin, Powell, Emami\n% script to generate Fig. 3.16\n%  fig3_14.m      \n%  Example 3.23    \nclf;\nnum=[2 1];\nden=[1 3 2];\nt=0:0.1:6;\ny=impulse(num,den,t);\nplot(t,y,'-')\ngrid\ntitle('Fig. 3.16  Example 3.23 system impulse response.')\nxlabel('Time (sec)')\nylabel('h(t)')\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_16.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.589033455338926}}
{"text": "function A = frand (n,nel,s)\n% A = frand (n,nel,s) creates an n-by-n sparse matrix consisting of nel finite\n% elements, each of which are of size s-by-s with random symmetric nonzero\n% pattern, plus the identity matrix.\n%\n% Example:\n%   A = frand (100, 100, 4) ; cspy (A)\n% See also: cs_demo\n\n%   Copyright 2006-2007, Timothy A. Davis.\n%   http://www.cise.ufl.edu/research/sparse\nss = s^2 ;\nnz = nel*ss ;\nii = zeros (nz,1) ;\njj = zeros (nz,1) ;\nxx = zeros (nz,1) ;\nk = 1 ;\nfor e = 1:nel\n    i = 1 + fix (n * rand (s,1)) ;\n    i = repmat (i, 1, s) ;\n    j = i' ;\n    x = rand (s,s) ;\n    ii (k:k+ss-1) = i (:) ; \n    jj (k:k+ss-1) = j (:) ; \n    xx (k:k+ss-1) = x (:) ;\n    k = k + ss ;\nend\nA = sparse (ii,jj,xx,n,n) + speye (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/MATLAB/Demo/private/frand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5889643319011875}}
{"text": "function [bar] = Torr2bar(Torr)\n% Convert pressure from torr (same as mmHg) to bar\n% Chad Greene 2012\nbar = Torr*0.00133322;", "meta": {"author": "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/Torr2bar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.588964325593123}}
{"text": "function r8col_sorted_tol_undex_test ( )\n\n%*****************************************************************************80\n%\n%% R8COL_SORTED_TOL_UNDEX_TEST tests R8COL_SORTED_TOL_UNDEX.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    17 July 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8COL_SORTED_TOL_UNDEX_TEST\\n' );\n  fprintf ( 1, '  R8COL_SORTED_TOL_UNDEX produces index vectors which \\n' );\n  fprintf ( 1, '  create a sorted list of the tolerably unique columns of \\n' );\n  fprintf ( 1, '  a sorted R8COL and a map from the original R8COL to the \\n' );\n  fprintf ( 1, '  (implicit) R8COL of sorted tolerably unique elements.\\n' );\n\n  m = 3;\n  n = 22;\n\n  a = [ ...\n    1.9,  0.0, 10.0; ...\n    2.0,  6.0, 10.0; ...\n    4.0,  8.0, 12.0; ...\n    1.0,  5.0,  9.0; ...\n    3.0,  7.0, 11.0; ...\n    2.0,  6.0,  0.0; ...\n    2.0,  0.0, 10.1; ...\n    2.0,  0.1, 10.0; ...\n    3.0,  4.0, 18.0; ...\n    1.9,  8.0, 10.0; ...\n    0.0,  0.0,  0.0; ...\n    0.0,  6.0, 10.0; ...\n    2.1,  0.0, 10.0; ...\n    2.0,  6.0, 10.0; ...\n    3.0,  7.0, 11.0; ...\n    2.0,  0.0, 10.0; ...\n    2.0,  0.0, 10.0; ...\n    2.0,  6.0, 10.0; ...\n    1.0,  5.0,  9.0; ...\n    2.0,  0.0, 10.1; ...\n    1.0,  5.0,  9.1; ...\n    1.0,  5.1,  9.0 ]';\n\n  r8mat_transpose_print ( m, n, a, '  The unsorted R8COL (transposed):' );\n\n  a = r8col_sort_heap_a ( m, n, a );\n\n  r8mat_transpose_print ( m, n, a, '  The sorted R8COL (transposed):' );\n\n  tol = 0.25;\n  n_unique = r8col_sorted_tol_unique_count ( m, n, a, tol );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Tolerance for equality is %e\\n', tol );\n  fprintf ( 1, '  Number of unique entries in X is %d\\n', n_unique );\n\n  [ undx, xdnu ] = r8col_sorted_tol_undex ( m, n, a, n_unique, tol );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  XDNU points to the representative for each item.\\n' );\n  fprintf ( 1, '  UNDX selects the representatives..\\n' );\n  fprintf ( 1, '\\n' );\n\n  for i = 1 : n_unique\n    fprintf ( 1, '  %4d  %4d  %4d\\n', i, xdnu(i), undx(i) );\n  end\n  for i = n_unique + 1 : n\n    fprintf ( 1, '  %4d  %4d\\n', i, xdnu(i) );\n  end\n\n  for j = 1 : n_unique\n    au(1:m,j) = a(1:m,undx(j));\n  end \n\n  r8mat_transpose_print ( m, n_unique, au, ...\n    '  The tolerably unique R8COL (transposed):' );\n\n  return\nend\n", "meta": {"author": "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/r8col_sorted_tol_undex_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.5889643186514876}}
{"text": "function b = r8gb_mxv ( m, n, ml, mu, a, x )\n\n%*****************************************************************************80\n%\n%% R8GB_MXV multiplies a R8GB matrix times a vector.\n%\n%  Discussion:\n%\n%    An M by N banded matrix A with lower bandwidth ML and upper bandwidth MU\n%    is assumed to be entirely zero, except for the main diagonal, and\n%    entries in the ML nearest subdiagonals, and MU nearest superdiagonals.\n%\n%    LINPACK and LAPACK \"R8GB\" storage for such a matrix generally includes\n%    room for ML extra superdiagonals, which may be required to store\n%    nonzero entries generated during Gaussian elimination.\n%\n%    The original M by N matrix is \"collapsed\" downward, so that diagonals\n%    become rows of the storage array, while columns are preserved.  The\n%    collapsed array is logically 2*ML+MU+1 by N.\n%\n%    LINPACK and LAPACK storage of general band matrices requires\n%    an extra ML upper diagonals for possible fill in entries during\n%    Gauss elimination.  This routine does not access any entries\n%    in the fill in diagonals, because it assumes that the matrix\n%    has NOT had Gauss elimination applied to it.  If the matrix\n%    has been Gauss eliminated, then the routine R8GB_MU must be\n%    used instead.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    18 November 2003\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Dongarra, Bunch, Moler, Stewart,\n%    LINPACK User's Guide,\n%    SIAM, 1979.\n%\n%  Parameters:\n%\n%    Input, integer M, the number of rows of the matrix.\n%    M must be positive.\n%\n%    Input, integer N, the number of columns of the matrix.\n%    N must be positive.\n%\n%    Input, integer ML, MU, the lower and upper bandwidths.\n%    ML and MU must be nonnegative, and no greater than min(M,N)-1.\n%\n%    Input, real A(2*ML+MU+1,N), the R8GB matrix.\n%\n%    Input, real X(N), the vector to be multiplied by A.\n%\n%    Output, real B(M), the product A * x.\n%\n  b(1:m) = 0.0;\n\n  for i = 1 : m\n    jlo = max ( 1, i - ml );\n    jhi = min ( n, i + mu );\n    for j = jlo : jhi\n      b(i) = b(i) + a(i-j+ml+mu+1,j) * 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/linplus/r8gb_mxv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478256, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5889643114313367}}
{"text": "function s = resampwor(p,m,n)\n%RESAMWOR Random resampling without replacement\n%\n%   Description:\n%   S = RESAMWOR(P) returns a new set of indices according to the\n%   probabilities P without replacemnt. P is array of probabilities,\n%   which are not necessarily normalized, though they must be\n%   non-negative, and not all zero. The size of S is the size of P.\n%\n%   S = RESAMWOR(P,M,N) returns M by N matrix.\n%\n%   S = RESAMWOR(P,M) returns M by M matrix.\n%\n%   See also RESAMPSIM, RESAMPRES, RESAMPSTR, RESAMPDET\n%\n% Copyright (c) 2003-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    [m,n] = size(p);\nelseif nargin==2\n    n = m;\nend\nif m*n>numel(p)\n  error('In resampling without replacment M*N has to be smaller than numel(P)')\nend\nr=rand([m,n]);\ns=zeros([m,n]);\nfor i=1:m*n\n  pc=cumsum(p(:));\n  pc=pc./pc(end);\n  s(i)=binsgeq(pc,r(i));\n  p(s(i))=0;\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/mc/resampwor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5889257357360045}}
{"text": "function A = linop_explicit( op )\n%LINOP_EXPLICIT Outputs the explicit matrix representation\n%   of a (implicitly defined) linear operator.\n%   Useful for checking correctness of code.\n% A = LINOP_EXPLICIT( OP ) \n%   returns the matrix A such that A*X = OP(X)\n%\n% Note: may not play well with linear operators defined on complex numbers\n%   (but should be OK if the output inclides complex numbers)\n\n% Introduced June 2016\n\nif nargin == 0,\n    error( 'Not enough input arguments.' );\nend\nsz = op([],0);\nif isnumeric(sz),\n    sz = { [sz(2),1], [sz(1),1] };\nend\n% convert [n1;n2] to [n1,n2] if necessary:\nfor kk = 1:2\n    sz{kk} = sz{kk}(:).';\nend\n% If inputs and outputs are not vectors, then we cannot represent\n%   with matrix multiplication\nif sz{1}(2) ~= 1 || sz{2}(2) ~= 1\n    error('Cannot represent this operator as matrix since input/output is not a vector');\nend\nm   = sz{2}(1);\nn   = sz{1}(1);\ne   = zeros(n,1);\nA   = zeros(m,n);\nfor i = 1:n\n    e(i) = 1;\n    A(:,i)  = op( e, 1 );\n    e(i) = 0;\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/linop_explicit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5889257357360045}}
{"text": "%DISP_HHS2  display Hilbert-Huang spectrum\n%\n% DISP_HHS2(im,t,inf,sub,color)\n% displays in a new figure the spectrum contained in matrix \"im\"\n% (amplitudes in dB).\n%\n% inputs:  - im: image matrix (e.g., output of \"toimage\")\n%          - t (optional): time instants (e.g., output of \"toimage\") \n%          - inf (optional): -dynamic range in dB (wrt max)\n%            default: inf = -20\n%          - fs: sampling frequency\n%          - sub: subset ratio\n%          - color: 0 = grayscale ; 1 = color (default)\n%\n% use:  disp_hhs(im) ; disp_hhs(im,t) ; disp_hhs(im,inf)\n%       disp_hhs(im,t,inf) ; disp_hhs(im,inf,fs) ; disp_hhs(im,[],fs)\n%       disp_hhs(im,t,[],fs) ; disp_hhs(im,t,inf,fs)\n%\n%\n% See also\n%  emd, hhspectrum, toimage\n%\n% Modification of G. Rilling code\n% gabriel.rilling@ens-lyon.fr\n\nfunction disp_hhs2(varargin)\n\nerror(nargchk(1,6,nargin));\nfs = 0;\ninf = -20;\nim = varargin{1};\nt = 1:size(im,2);\nsub = 1;\ncolor = 1;\nswitch nargin\n  case 1\n    %raf\n  case 2\n    if isscalar(varargin{2})\n      inf = varargin{2};\n    else\n      t = varargin{2};\n    end\n  case 3\n    if isvector(varargin{2})\n      t = varargin{2};\n      inf = varargin{3};\n    else\n      inf = varargin{2};\n      fs = varargin{3};\n    end\n  case 4\n    t = varargin{2};\n    inf = varargin{3};\n    fs = varargin{4};\n  case 5\n    if isscalar(varargin{5})\n      t = varargin{2};\n      inf = varargin{3};\n      fs = varargin{4};\n      sub = varargin{5};\n    end\n  case 6\n    if isscalar(varargin{6})\n      t = varargin{2};\n      inf = varargin{3};\n      fs = varargin{4};\n      sub = varargin{5};\n      color = varargin{6};\n    end\nend\n\nif isempty(inf)\n  inf = -20;\nend\n\nif inf > 0\n  inf = -inf;\nelseif inf == 0\n  error('inf must be nonzero')\nend\n\nif color~=0\n    color = 1;\nend\n\nM=max(max(im));\n\nwarning off\nim = 10*log10(im/M);\nwarning on\n\nfigure\nsubplot(6,1,[2:6]);   %AJOUT\nif fs == 0\n  imagesc(t,[0,pi/sub],im(1:floor(end/sub),:),[inf,0]);\n  ylabel('frequency (rad/s)')\nelse\n  imagesc(t,[0,0.5*fs],im,[inf,0]);\n  ylabel('frequency')\nend\nif color == 0\n    colormap(1.-gray);\nend\nset(gca,'YDir','normal')\nxlabel('time')\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/42141-empirical-wavelet-transforms/EWT/1D/disp_hhs2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5889257357360045}}
{"text": "function f=ftorque(tt)\nt1max=34;t2max=12;\nt1=tt(1,:);t2=tt(2,:);\nf=0;\nfor i=1:size(tt,2)\n    if abs(t1(i)) < t1max\n        tc1=0;\n    else\n        tc1=abs(t1(i))-t1max;\n    end\n    if abs(t2(i)) < t2max\n        tc2=0;\n    else\n        tc2=abs(t2(i))-t2max;\n    end\n    f=f+tc1+tc2;\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/23289-motion-planning-for-a-robot-arm-by-using-genetic-algorithm/robot motion planning/matlab code/ftorque.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5889257357360045}}
{"text": "function mr=v_rotqr2mr(qr)\n%V_ROTQR2MR converts a matrix of real quaternion vectors to quaternion matrices\n% Inputs:\n%\n%     QR(4m,n,...)   mxn matrix of real quaternion vectors (each 4x1)\n%\n% Outputs:\n%\n%     MR(4m,4n,...)   mxn matrix of real quaternion matrices (each 4x4)\n%\n% In matrix form, quaternions can be multiplied and added using normal matrix\n% arithmetic. Each element of an mxn matrix of quaternions is itself a 4x4 block\n% so the total dimension of MR is 4m x 4n.\n\n%\n%      Copyright (C) Mike Brookes 2000-2018\n%      Version: $Id: v_rotqr2mr.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\nif isempty(a)\n    a=[1 2 3 3 1 2];    % destination row of +ve entries (from 0)\n    b=[1 2 3 2 3 1];    % destination col of +ve entries (from 0)\n    c=[0 0 0 1 2 3];    % source row of +ve entries (from 0)\nend\ns=size(qr);\nm=s(1);\nmr=repmat(reshape(qr,s(1),[]),4,1);\nn=size(mr,2);\nmn=s(1)*n;\nj=repmat(4*m*(0:n-1),m/4,1);\ni=repmat((1:4:m)',n,1)+j(:);\nni=length(i);\ni6=repmat(i,1,6);\nmr(i6+repmat(a+m*b,ni,1))=mr(i6+repmat(c,ni,1));\nmr(i6+repmat(c+m*b,ni,1))=-mr(i6+repmat(a,ni,1));\ns(2)=4*s(2); % output array size\nmr=reshape(mr,s);\nif ~nargout\n    qr=qr(1:4);\n    v_rotqr2ro(qr(:)); % 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_rotqr2mr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5889257311757128}}
{"text": "function pass = test_chebpolyval(pref)\n\nif ( nargin == 0 )\n    pref = chebfunpref();\nend\n\n% NOTE: Since CHEBPOLYVAL() is basically a wrapper to CHEBTECH/FEVAL(), this is\n% just a simple test.\n\n% Init:\nseedRNG(42)\ntol = 10*pref.chebfuneps;\n\n% Use CHEBPOLYVAL():\nn = 10;\nc = rand(10, 2);\nx = rand(3);\nfx1 = chebpolyval(c, x);\n\n% Use CHEBPOLY():\nT = chebpoly(0:9);\nTc = T*flipud(c);\nfx2 = feval(Tc, x);\n\n% Error:\nerr = norm(fx1 - fx2, inf);\npass(1) = err < n*tol;\n\n%%\n\nx = chebfun('x');\nf = chebpolyval(c, x);\npass(2) = norm(f - Tc, inf) < n*tol;\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/misc/test_chebpolyval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5889257266154209}}
{"text": "function [params,names] = lmcKernExtractParam(kern)\n\n% LMCKERNEXTRACTPARAM Extract parameters from the LMC kernel struc.\n% FORMAT\n% DESC Extract parameters from the linear model of coregionalization kernel \n% structure into a vector of parameters for optimisation. \n% ARG kern : the kernel structure containing the parameters to be\n% extracted.\n% RETURN param : vector of parameters extracted from the\n% kernel. The vector of transforms is assumed to be empty here, any\n% transormation of parameters is assumed to be done in the\n% component kernels.\n%\n% FORMAT\n% DESC the same that before but also returns the names of the parameters.\n% ARG kern : the kernel structure containing the parameters to be\n% extracted.\n% RETURN param : vector of parameters extracted from the\n% kernel. The vector of transforms is assumed to be empty here, any\n% transormation of parameters is assumed to be done in the\n% component kernels.\n% RETURN names : cell array of strings containing parameter names.\n%\n% SEEALSO multiKernExtractParam\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\n% First extract the parameters of the basic kernel\n\nfhandle = str2func([kern.basicKernelType 'KernExtractParam']);\n\nif nargout > 1\n  [paramsTemp, namesTemp] = fhandle(kern);\n  namesB = cell(kern.nout, kern.rankCorregMatrix);\n  for i = 1:kern.nout\n      for j =1:kern.rankCorregMatrix\n          namesB{i,j} = ['A(' num2str(i) ',' num2str(j) ')'];\n      end\n  end\n  names = {namesTemp{1:kern.nParamsBK}, namesB{:}};\nelse\n  paramsTemp = fhandle(kern);\nend\n\n% Add the parameters of the corregionalization matrix \n\nparams = [paramsTemp(1:kern.nParamsBK)  kern.A(:)'];\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lmcKernExtractParam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.588925724667791}}
{"text": "function [z,dz,ymu,ys,fmu,fs,fpi] = acqNegSqEI(xi,target,gpstruct,optimState,grad_flag)\n%ACQNEGEI Acquisition function for (negative) expected squared improvement.\n\nif nargin < 5 || isempty(grad_flag); grad_flag = false; end\n\nn = size(xi,1);\n\nif grad_flag && n > 1\n    error('acqNegSqEI:gradient', ...\n        'Gradient of acquisition function is provided only at one test point XI (row vector).');\nend\n\nif grad_flag\n    [ymu,ys2,fmu,fs2,hypw,dymu,dys2,dfmu,dfs2] = gppred(xi,gpstruct,'central');\nelse\n    [ymu,ys2,fmu,fs2,hypw] = gppred(xi,gpstruct);\nend\nfs = sqrt(fs2);\nys = sqrt(ys2);\n\n% Probability of improvement\ngammaz = real((target - fmu)./fs);\nfpi = 0.5*erfc(-gammaz/sqrt(2));            \n\n% Expected squared improvement\nz = -fs.^2.*((gammaz.^2+1).*fpi + gammaz.*exp(-0.5*(gammaz.^2))/sqrt(2*pi));\n\ntry\n    z = sum(bsxfun(@times,hypw(~isnan(hypw)),z(~isnan(hypw),:)),1);\ncatch\n    z = Inf(1,n);\n    dz = NaN(n,size(xi,2));\n    return;\nend\n\nif grad_flag    \n    % Gradient of probability of improvement\n    dfs = 0.5*dfs2./fs;\n    dgammaz = -(dfmu.*fs + (target - fmu).*dfs)./fs2;\n    dfpi = -0.5*dgammaz/sqrt(2)*(-2*exp(-gammaz.^2/2)/sqrt(pi));\n    \n    % Gradient of expected improvement\n    %dz = -(dfs.*gammaz.*fpi + dgammaz.*fs.*fpi + dfpi.*gammaz.*fs) ...\n    %    + (fs.*gammaz.*dgammaz - dfs).*exp(-0.5*gammaz.^2)/sqrt(2*pi);\n    %dz = sum(bsxfun(@times,hypw,dz(~isnan(hypw),:)),1);    \nelse\n    dz = NaN(n,size(xi,2));     % Gradient not estimated\nend\n\nend", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/acq/acqNegSqEI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5888722204443424}}
{"text": "function [diff_data] = timeSeriesComparison(t1,data1,t2,data2,mode)\n% compare two time series the first one with lower spacing between epochs the second one with finer spacing\nif strcmp(mode,'aggregate')\n    edges = zeros(1,length(t2)+2+100);\n    j = 1;\n    rate = round(nan_mean(diff(t1))*86400)/86400;\n    empty_idx = [];\n    for i = 1:(length(t1) -1)\n        edges(j) = t1(i) - (rate/2);\n        j = j + 1;\n        if ((t1(i+1) - t1(i)) > 1.5*rate)\n            edges(j) = t1(i) + (rate/2);\n            j = j + 1;\n            empty_idx = [empty_idx; j];\n        end\n    end\n    edges(j) = t1(end) + (rate/2);\n    edges(j+1:end) = [];\n    \n    %edges = (data1.time.first.getMatlabTime-eps()) : 1:(data1.time.last.getMatlabTime+1);\n    Y = discretize(t2,edges,'IncludedEdge','right');\n    idx = false(size(Y));\n    for ei = empty_idx'\n        idx = idx | Y == ei;\n    end\n    idx = idx | isnan(Y);\n    Y(idx) = [];\n    ztds = zero2nan(data2(~idx));\n    avg_data = accumarray(Y,ztds,[],@nan_mean);\n    avg_data_time = edges(1:end-1) + (edges(2:end) - edges(1:end-1))/2;\n    if length(avg_data_time) > max(Y)\n    avg_data_time(max(Y)+1:end) = [];\n    end\n    avg_data_time = avg_data_time(avg_data~=0);\n    avg_data = avg_data(avg_data~=0);\n    [LIA,LocB] = ismembertol(avg_data_time, t1,1e-8);\n    diff_data = nan(size(data1));\n    diff_data(LocB(LocB~=0)) = zero2nan(avg_data(LIA)) - zero2nan(data1(LocB(LocB~=0)));\n    \nelseif strcmp(mode,'interpolate')\n    diff_data = data2 - interp1(t1,data1,t2,'linear');\nelseif strcmp(mode,'spline')\n     edges = zeros(1,length(t2)+2+100);\n    j = 1;\n    rate = round(nan_mean(diff(t1))*86400)/86400;\n    empty_idx = [];\n    for i = 1:(length(t1) -1)\n        edges(j) = t1(i) - (rate/2);\n        j = j + 1;\n        if ((t1(i+1) - t1(i)) > 1.5*rate)\n            edges(j) = t1(i) + (rate/2);\n            j = j + 1;\n            empty_idx = [empty_idx; j];\n        end\n    end\n    edges(j) = t1(end) + (rate/2);\n    edges(j+1:end) = [];\n    \n    %edges = (data1.time.first.getMatlabTime-eps()) : 1:(data1.time.last.getMatlabTime+1);\n    Y = discretize(t2,edges,'IncludedEdge','right');\n    idx = false(size(Y));\n    for ei = empty_idx'\n        idx = idx | Y == ei;\n    end\n    idx = idx | isnan(Y);\n    Y(idx) = [];\n    avg_data_time = edges(1:end-1) + (edges(2:end) - edges(1:end-1))/2;\n    if length(avg_data_time) > max(Y)\n    avg_data_time(max(Y)+1:end) = [];\n    end\n    avg_data_time = avg_data_time(unique(Y));\n    [LIA,LocB] = ismembertol(avg_data_time, t1,1e-7);\n    \n    [~,~,~, splined2] = splinerMat(t2, data2,rate,1e-5, avg_data_time);\n    diff_data = nan(size(data1));\n    diff_data(LocB(LocB~=0)) = zero2nan(splined2(LIA)) - zero2nan(data1(LocB(LocB~=0)));\n    \nend", "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/timeSeriesComparison.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5888722185176308}}
{"text": "function drawFace(p)\n%\n% head\n% eyes\n% nose\n% mouth\n% eyebrows\n% hair\n%\n% 1 - head width    0 1\n% 2 - head height   0 1\n% 3-5 head color    0 1\n%\n% 6     y eye level\n% 7     eye spacing\n% 8     eye line length\n% 9     left eye line width\n% 10    right eye line width\n%\n% 11    nose to eye dist\n% 12    nose length\n% 13    nose line width\n%\n% 14    mouth width\n% 15    smile scale factor\n% 16    smile displacement\n% 17    smile line width\n%\n% 18 x\n% 19 y\n\ncla\n\n% ------------------------------------------\n% * draw head\n% ------------------------------------------\n[X,Y,Z]=ellipsoid(p(18),p(19),0,p(1),p(2),1);\nsurf(X,Y,Z,'EdgeColor','None','FaceColor',[p(3) p(4) p(5)])\n%axis off; set(gcf,'Color','w');axis([-1 1 -1 1])\nhold on\n\n% ------------------------------------------\n% * draw eyes\n% ------------------------------------------\ny = p(6) * p(2) + p(19);\nx = p(18);\ns = (p(7) * p(1)) ./ 2;\nplot3(x+[-p(8) * p(1) - s -s] ,[y y],[2 2],'k','LineWidth',p(9)*8)\nplot3(x+[s (p(8)*p(1)+s)],[y y],[2 2],'k','LineWidth',p(10)*8)\n\n\n% ------------------------------------------\n% * draw nose\n% ------------------------------------------\nnosestart = y - .5*(p(11) * p(2));\nnoseend = max(y,p(12) * (p(2) - nosestart));\nplot3(x+[0 0],[nosestart noseend],[2 2],'k','LineWidth',p(13)*8)\n\n% ------------------------------------------\n% * draw mouth\n% ------------------------------------------\nx2 = x; % displacement\nwid = (p(14) * p(1)) ./ 2;\nx = -wid:.05.*p(1):wid;\nys = p(15) * 2 * (x) .^ 2;\nys = y+ ys - (p(16)*p(2));\nplot3(x+x2,ys,2*ones(size(x)),'k','LineWidth',p(17)*5)\n\ndrawnow\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/faceGA/drawFace2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5888298603397993}}
{"text": "function p = stat_fisher_pcomb(p)\n% Fisher's (1925) method for combination of independent p-values [1]\n% Code adapted from Bailey and Gribskov (1998) [2]\n%\n% [1] Fisher RA (1925). Statistical methods for research workers (13th edition). London: Oliver and Boyd.\n% [2] Bailey TL, Gribskov M (1998). Combining evidence using p-values: application to sequence homology searches. Bioinformatics, 14 (1) 48-54.\n%\n% Author: Peter Watson, http://imaging.mrc-cbu.cam.ac.uk/statswiki/FAQ/CombiningPvalues\n\nproduct=prod(p);\nn=length(p);\nif n<=0\n    error('pfast was passed an empty array of p-values')\nelseif n==1\n    p = product;\n    return\nelseif product == 0\n    p = 0;\n    return\nelse\n    x = -log(product);\n    t=product;\n    p=product;\n    for i = 1:n-1\n        t = t * x / i;\n        p = p + t;\n    end\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/stat/stat_fisher_pcomb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.588829842916837}}
{"text": "function W = gsp_vec2adj(A,x,type)\n%GSP_VEC2ADJ Create the matrix W with sparsity pattern A and entries x\n%\n%   Usage: W = gsp_vec2adj(A,x)\n%              gsp_vec2adj(A,x,type)\n%\n%   Input parameters:\n%       A       : Matrix of sparsity pattern (e.g. binary adjacency matrix)\n%       x       : Vector of entries\n%       type    : Type of matrix (string) (default 'sym' if A is symmetric)\n%                    *  sym: W will be symmetric (x must be of size nnz(A)/2)\n%                    * asym: W is asymmetric (x must be of size nnz(A))\n%   Output parameters\n%       W       : Weighted matrix\n%\n%   Create the matrix W with sparsity pattern A and entries x%\n%\n\n% Author: Francesco Grassi\n% Date   : July 2016\n\n\nif nargin<3\n    if issymmetric(full(double(A)))\n        type='sym';\n    else\n        type='asym';\n    end\nend\n\nif ~nnz(A)==length(x) && ~nnz(A)/2==length(x)\n    error('x must have the same size of nnz(A) or nnz(A)/2 if A is symmetric')\nend\n\n[N1,N2] = size(A);\n\nswitch type\n    case 'sym'\n        [i,j] = find(triu(A));\n        W = sparse(i,j,x,N1,N2)+sparse(i,j,x,N1,N2)';\n    case 'asym'\n        [i,j] = find(A);\n        W = sparse(i,j,x,N1,N2);\n    otherwise\n        error('Unknow type');\nend\n\n    \n\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_vec2adj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.5888283300521724}}
{"text": "%isivector - Test if parameter is a vector of integers satisfying an optional list of tests.\n%\n%  USAGE\n%\n%    test = isivector(x,test1,test2,...)\n%\n%    x              parameter to test\n%    test1...       optional list of additional tests (see examples below)\n%\n%  EXAMPLES\n%\n%    % Test if x is a vector of doubles\n%    isivector(x)\n%\n%    % Test if x is a vector of strictly positive doubles\n%    isivector(x,'>0')\n%\n%    % Test if x is a vector of doubles included in [2,3]\n%    isivector(x,'>=2','<=3')\n%\n%    % Special test: test if x is a vector of doubles of length 3\n%    isivector(x,'#3')\n%\n%    % Special test: test if x is a vector of strictly ordered doubles\n%    isivector(x,'>')\n%\n%  NOTE\n%\n%    The tests ignore NaNs, e.g. isivector([500 nan]), isivector([1 nan 3],'>0') and\n%    isivector([nan -7],'<=0') all return 1.\n%\n%  SEE ALSO\n%\n%    See also isdmatrix, isdvector, isdscalar, isimatrix, isiscalar, isstring,\n%    islscalar, islvector, islmatrix.\n%\n\n% Copyright (C) 2010 by Micha\u00ebl Zugaro\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\nfunction test = isivector(x,varargin)\n\n% Check number of parameters\nif nargin < 1,\n  error('Incorrect number of parameters (type ''help <a href=\"matlab:help isivector\">isivector</a>'' for details).');\nend\n\n% Test: double, vector\ntest = isa(x,'double') & isvector(x);\n\n% Ignore NaNs\nx = x(~isnan(x));\n\n% Test: integers?\ntest = test & all(round(x)==x);\n\n% Optional tests\nfor i = 1:length(varargin),\n\ttry\n\t\tif varargin{i}(1) == '#',\n\t\t\tif length(x) ~= str2num(varargin{i}(2:end)), test = false; return; end\n\t\telseif isstring(varargin{i},'>','>=','<','<='),\n\t\t\tdx = diff(x);\n\t\t\tif ~eval(['all(0' varargin{i} 'dx);']), test = false; return; end\n\t\telse\n\t\t\tif ~eval(['all(x' varargin{i} ');']), test = false; return; end\n\t\tend\n\tcatch err\n\t\terror(['Incorrect test ''' varargin{i} ''' (type ''help <a href=\"matlab:help isivector\">isivector</a>'' for details).']);\n\tend\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/isivector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5888283300521724}}
{"text": "function meshdemo_2d ( )\n\n%*****************************************************************************80\n%\n%% MESHDEMO_2D displays some 2D examples of the use of DISTMESH.\n%\n%  Licensing:\n%\n%    (C) 2004 Per-Olof Persson. \n%    See COPYRIGHT.TXT for details.\n%\n%  Modified:\n%\n%    27 October 2011\n%\n%  Reference:\n%\n%    Per-Olof Persson, Gilbert Strang,\n%    A Simple Mesh Generator in MATLAB,\n%    SIAM Review,\n%    Volume 46, Number 2, June 2004, pages 329-345.\n%\n%  Local parameters:\n%\n%    Local, integer ITERATION_MAX, the maximum number of iterations that \n%    DISTMESH should take.  (The program might take fewer iterations if it \n%    detects convergence.)\n%\n%    Local, real H, the desired initial spacing.  If a uniform mesh density is used,\n%    this is the approximate spacing throughout the region.\n%\n%    Local, pointer FH, an inline formula, or the name of an M file, which calculates\n%    the mesh density function.\n%\n  timestamp ( );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'MESHDEMO_2D\\n' );\n  fprintf ( 1, '  Demonstrations of the use of DISTMESH.\\n' );\n%\n%  Problem 1, the circle, with spacings H = 0.4, 0.2, 0.1.\n%\n  iteration_max = 200;\n  h = 0.40;\n  p01_demo ( iteration_max, h );\n  input ( 'Press RETURN' )\n\n  iteration_max = 200;\n  h = 0.20;\n  p01_demo ( iteration_max, h );\n  input ( 'Press RETURN' )\n\n  iteration_max = 200;\n  h = 0.10;\n  p01_demo ( iteration_max, h );\n  input ( 'Press RETURN' )\n%\n%  Problem 2, unit circle with a hole.\n%\n  iteration_max = 200;\n  h = 0.10;\n  p02_demo ( iteration_max, h )\n\n  input ( 'Press RETURN' )\n%\n%  Problem 3, square with a hole, uniform density.\n%\n  iteration_max = 200;\n  h = 0.15;\n  fh = @p03_fh;\n  p03_demo ( iteration_max, h, fh )\n\n  input ( 'Press RETURN' )\n%\n%  Problem 3, square with a hole, finer density near the hole.\n%\n  iteration_max = 300;\n  h = 0.05;\n  fh = inline ( 'min(4*sqrt(sum(p.^2,2))-1,2)', 'p' );\n  p03_demo ( iteration_max, h, fh )\n\n  input ( 'Press RETURN' )\n%\n%  Problem 4, hexagon with a hexagonal hole.\n%\n  iteration_max = 200;\n  h = 0.1;\n  p04_demo ( iteration_max, h );\n\n  input ( 'Press RETURN' )\n%\n%  Problem 5, the horn.\n%\n  iteration_max = 200;\n  h = 0.020;\n  p05_demo ( iteration_max, h );\n\n  input ( 'Press RETURN' )\n%\n%  Problem 6, the superellipse.\n%  Needs MAPLE to run...\n%\n  if ( 0 )\n    iteration_max = 200;\n    h = 0.08;\n    p06_demo ( iteration_max, h );\n    input ( 'Press RETURN' )\n  else\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Skipping problem 6, the superellipse.\\n' );\n  end\n%\n%  Problem 7, the bicycle seat.\n%  Needs MAPLE to run...\n%\n  if ( 0 )\n    iteration_max = 200;\n    h = 0.75;\n    p07_demo ( iteration_max, h );\n    input ( 'Press RETURN' )\n  else\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Skipping problem 7, the bicycle seat.\\n' );\n  end\n%\n%  Problem 8, the holey pie slice, uniform density.\n%\n  iteration_max = 200;\n  h = 0.025;\n  fh = @huniform;\n  p08_demo ( iteration_max, h, fh );\n  input ( 'Press RETURN' )\n%\n%  Problem 8, the holey pie slice, variable density.\n%\n  iteration_max = 200;\n  h = 0.005;\n  fh = @p08_fh;\n  p08_demo ( iteration_max, h, fh );\n  input ( 'Press RETURN' )\n%\n%  Problem 9, Jeff Borggaard's square with two hexagonal holes.\n%\n  iteration_max = 200;\n  h = 0.08;\n  p09_demo ( iteration_max, h );\n  input ( 'Press RETURN' )\n%\n%  Problem 10, a simple square.\n%\n  iteration_max = 200;\n  h = 0.10;\n  p10_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 11, the L-shaped region.\n%\n  iteration_max = 200;\n  h = 0.10;\n  p11_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 12, John Shadid's H-shaped region.\n%\n  iteration_max = 200;\n  h = 0.05;\n  p12_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 13, the Sandia Fork.\n%\n  iteration_max = 200;\n  h = 0.025;\n  p13_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 14, Marcus Garvie's Lake Alpha with Beta island.\n%\n  if ( 0 )\n    iteration_max = 50;\n    h = 20.0;\n    fh = @huniform;\n    p14_demo ( iteration_max, h, fh )\n    input ( 'Press RETURN' )\n  else\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Skipping problem 14.\\n' );\n  end\n%\n%  Problem 14, Marcus Garvie's Lake Alpha with Beta island.\n%  You may get endless warnings from DELAUNAYN about duplicate points.\n%  Shut off this annoying drivel with \"warning off\".\n%\n  if ( 0 )\n    warning off\n    iteration_max = 50;\n    h = 10.0;\n    fh = @p14_fh;\n    p14_demo ( iteration_max, h, fh )\n    input ( 'Press RETURN' )\n  else\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Skipping problem 14.\\n' );\n  end\n%\n%  Problem 15, Sangbum Kim's forward step problem.\n%\n  iteration_max = 50;\n  h = 0.2;\n  p15_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 16, Kevin Pond's elbow.\n%\n  iteration_max = 50;\n  h = 0.05;\n  p16_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 17, Reuleaux triangle problem.\n%\n  iteration_max = 50;\n  h = 0.05;\n  p17_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 18, Dumbbell problem.\n%\n  iteration_max = 50;\n  h = 0.100;\n  p18_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 19, Dumbbell problem.\n%\n  iteration_max = 200;\n  h = 0.025;\n  p19_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 20, ICAM Wright House problem.\n%\n  iteration_max = 2;\n  h = 2.0;\n  p20_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 21, Zhu Wang's quarter round problem.\n%\n  iteration_max = 200;\n  h = 0.100;\n  p21_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 22, Hans-Werner van Wyk's Big C.\n%\n  iteration_max = 200;\n  h = 0.100;\n  p22_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Problem 23, Mike Schneier's nonuniform square.\n%\n  iteration_max = 200;\n  h = 0.025;\n  p23_demo ( iteration_max, h )\n  input ( 'Press RETURN' )\n%\n%  Terminate.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'MESHDEMO_2D\\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/distmesh/meshdemo_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.5888283223306043}}
{"text": "function dUpsilon = lfmvpGradientUpsilonVector(gamma, sigma2, t, upsilon)\n\n% LFMVPGRADIENTUPSILONVECTOR Gradient upsilon vector vel. pos.\n% FORMAT\n% DESC computes the gradient of 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 upsilon : precomputation of the upsilon matrix.\n% ARG mode : operation mode, according to the derivative (mode 0,\n% derivative wrt t1, mode 1 derivative wrt t2)\n% RETURN upsilon : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n%\n% SEEALSO : lfmvpComputeUpsilonMatrix.m\n\n% KERN\n\nif nargin<4\n    upsilon = lfmComputeUpsilonVector(gamma, sigma2, t);\nend\n\ndUpsilon = -upsilon - gamma*lfmGradientUpsilonVector(gamma, sigma2, t);\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/lfmvpGradientUpsilonVector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5888193706826137}}
{"text": "function [ output_maps ] = max_pooling2( input_maps, kernel_size, stride)\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 = round((orig_rows - kernel_size)/stride) + 1;\n    pooled_cols = round((orig_cols - kernel_size)/stride) + 1;   \n     \n    if(exist('vl_nnpool', 'file') == 3)\n        % Caffe and MatConvNet do pooling slightly differently, so need to\n        % counter for that\n\n        pooled_cols_vl = floor((orig_cols - kernel_size)/stride) + 1;\n        pooled_rows_vl = floor((orig_rows - kernel_size)/stride) + 1;\n\n        if(pooled_rows_vl == pooled_rows && pooled_cols_vl == pooled_cols)\n            output_maps = vl_nnpool(input_maps, [kernel_size, kernel_size], 'stride', stride);\n        else\n            % Else need to pad right and bottom with infinities \n            for x=1:kernel_size\n                pooled_cols_vl = floor((orig_cols + x - kernel_size)/stride) + 1;\n                if(pooled_cols_vl == pooled_cols)\n                    break;\n                end\n            end\n            for y=1:kernel_size\n                pooled_rows_vl = floor((orig_rows +y - kernel_size)/stride) + 1;\n                if(pooled_rows_vl == pooled_rows)\n                    break;\n                end\n            end\n\n            input_maps_new = -inf * ones(size(input_maps,1)+y, size(input_maps,2)+x, size(input_maps,3), size(input_maps,4));\n            input_maps_new(1:size(input_maps,1),1:size(input_maps,2),:,:) = input_maps;\n            output_maps = vl_nnpool(input_maps_new, [kernel_size, kernel_size], 'stride', stride);\n        end\n    else\n    \n        up_to_rows_out = floor((orig_rows - kernel_size)/stride) + 1;\n        up_to_cols_out = floor((orig_cols - kernel_size)/stride) + 1;\n\n        % How many full max-pooling steps are there\n        up_to_cols = kernel_size + (up_to_cols_out-1) * stride;\n        up_to_rows = kernel_size + (up_to_rows_out-1) * stride;\n\n        output_maps = zeros(pooled_rows, pooled_cols, size(input_maps,3), size(input_maps,4));\n\n        % Pick only the striding elements\n        [y, x] = meshgrid(1:up_to_cols-kernel_size+1, 1:up_to_rows-kernel_size+1);\n        to_keep_map = mod(y, stride) == 1 & mod(x, stride) == 1;\n        to_keep = find(to_keep_map);\n\n        inds_pooling = im2col_inds(input_maps(1:up_to_rows,1:up_to_cols,1,1), [kernel_size, kernel_size]);\n        inds_pooling = inds_pooling(:, to_keep);\n        for m=1:size(input_maps,4)\n            for i=1:size(input_maps,3)\n    %             temp = im2col(input_maps(1:up_to_rows,1:up_to_cols,i,m), [kernel_size, kernel_size], 'sliding');     \n    %             temp = im2col_mine(input_maps(1:up_to_rows,1:up_to_cols,i,m), [kernel_size, kernel_size]);        \n    %             temp = temp(:,to_keep);\n\n                temp = input_maps(1:up_to_rows,1:up_to_cols,i,m);\n                temp = temp(inds_pooling);\n\n                max_val = max(temp);\n                output_maps(1:up_to_rows_out,1:up_to_cols_out,i,m) = reshape(max_val, up_to_rows_out, up_to_cols_out);     \n            end\n        end\n        % A bit of a hack for non-even number of rows or columns\n        if(orig_cols ~= up_to_cols)\n            span = orig_cols - (up_to_cols - kernel_size + stride);\n            inds_pooling = im2col_inds(input_maps(1:up_to_rows,end-span+1:end,i,m), [kernel_size, span]);\n            inds_pooling = inds_pooling(:, 1:stride:end);\n            for m=1:size(input_maps,4)\n                for i=1:size(input_maps,3)\n    %                 temp = im2col(input_maps(1:up_to_rows,end-span+1:end,i,m), [kernel_size, span], 'sliding');\n    %                 temp = im2col_mine(input_maps(1:up_to_rows,end-span+1:end,i,m), [kernel_size, span]);\n    %                 max_val = max(temp(:,1:stride:end));\n\n                    temp = input_maps(1:up_to_rows,end-span+1:end,i,m);\n                    max_val = max(temp(inds_pooling));\n                    output_maps(1:up_to_rows_out,end,i,m) = max_val;     \n                end        \n            end\n        end\n\n        if(orig_rows ~= up_to_rows)\n            span = orig_rows - (up_to_rows - kernel_size + stride);\n            inds_pooling = im2col_inds(input_maps(end-span+1:end, 1:up_to_cols,i,m), [span, kernel_size]);\n            inds_pooling = inds_pooling(:, 1:stride:end);\n\n            for m=1:size(input_maps,4)\n                for i=1:size(input_maps,3)\n    %                 temp = im2col(input_maps(end-span+1:end, 1:up_to_cols,i,m), [span, kernel_size], 'sliding');\n    %                 temp = im2col_mine(input_maps(end-span+1:end, 1:up_to_cols,i,m), [span, kernel_size]);\n    %                 max_val = max(temp(:,1:stride:end));\n                    temp = input_maps(end-span+1:end, 1:up_to_cols,i,m);\n                    max_val = max(temp(inds_pooling));\n\n                    output_maps(end, 1:up_to_cols_out,i,m) = max_val;     \n                end   \n            end\n        end\n\n        if(orig_cols ~= up_to_cols && orig_rows ~= up_to_rows)\n            for m=1:size(input_maps,4)\n                for i=1:size(input_maps,3)\n                    tmp = input_maps(up_to_rows- kernel_size + stride + 1:end,up_to_cols - kernel_size + stride+1:end,i,m);            \n                    output_maps(end,end,i,m) = max(tmp(:));\n                end\n            end\n        end\n    \n    end\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_pooling2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5888193677137464}}
{"text": "function [E,J]=SynthMeasWatsonSHCylNeuman_PGSE(x, grad_dirs, G, delta, smalldel, fibredir, roots)\n% Substrate: Impermeable cylinders with one radius in an empty background.\n% Orientation distribution: Watson's distribution with SH approximation\n% Pulse sequence: Pulsed gradient spin echo\n% Signal approximation: Gaussian phase distribution.\n%\n% [E,J]=SynthMeasWatsonSHCylNeuman_PGSE(x, grad_dirs, G, delta, smalldel, fibredir, roots)\n% returns the measurements E according to the model and the Jacobian J of the\n% measurements with respect to the parameters.  The Jacobian does not\n% include derivates with respect to the fibre direction.\n%\n% x is the list of model parameters in SI units:\n% x(1) is the diffusivity of the material inside the cylinders.\n% x(2) is the radius of the cylinders.\n% x(3) is the concentration parameter of the Watson's distribution\n%\n% grad_dirs is the gradient direction for each measurement.  It has size [N\n% 3] where N is the number of measurements.\n%\n% G, delta and smalldel are the gradient strength, pulse separation and\n% pulse length of each measurement in the protocol.  Each has\n% size [N 1].\n%\n% fibredir is a unit vector along the symmetry axis of the Watson's\n% distribution.  It must be in Cartesian coordinates [x y z]' with size [3 1].\n%\n% roots contains solutions to the Bessel function equation from function\n% BesselJ_RootsCyl.\n%\n% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\nif length(x) ~= 3\n    error('the first argument should have exactly three parameters');\nend\n\nd=x(1);\nR=x(2);\nkappa=x(3);\n\nl_q = size(grad_dirs,1);\n\n% Parallel component\nif nargout > 1\n    [LePar, J_LePar] = CylNeumanLePar_PGSE(d, G, delta, smalldel);\nelse\n    LePar = CylNeumanLePar_PGSE(d, G, delta, smalldel);\nend\n\n% Perpendicular component\nif nargout > 1\n    [LePerp, J_LePerp] = CylNeumanLePerp_PGSE(d, R, G, delta, smalldel, roots);\nelse\n    LePerp = CylNeumanLePerp_PGSE(d, R, G, delta, smalldel, roots);\nend\nePerp = exp(LePerp);\n\n% Compute the Legendre weighted signal\nLpmp = LePerp - LePar;\nif nargout > 1\n    [lgi, J_lgi] = LegendreGaussianIntegral(Lpmp, 6);\nelse\n    lgi = LegendreGaussianIntegral(Lpmp, 6);\nend\n\n% Compute the spherical harmonic coefficients of the Watson's distribution\nif nargout > 1\n    [coeff, J_coeff] = WatsonSHCoeff(kappa);\nelse\n    coeff = WatsonSHCoeff(kappa);\nend\ncoeffMatrix = repmat(coeff, [l_q, 1]);\n\n% Compute the dot product between the symmetry axis of the Watson's distribution\n% and the gradient direction\n%\n% For numerical reasons, cosTheta might not always be between -1 and 1\n% Due to round off errors, individual gradient vectors in grad_dirs and the\n% fibredir are never exactly normal.  When a gradient vector and fibredir are\n% essentially parallel, their dot product can fall outside of -1 and 1.\n%\n% BUT we need make sure it does, otherwise the legendre function call below\n% will FAIL and abort the calculation!!!\n%\ncosTheta = grad_dirs*fibredir;\nbadCosTheta = find(abs(cosTheta)>1);\ncosTheta(badCosTheta) = cosTheta(badCosTheta)./abs(cosTheta(badCosTheta));\n\n% Compute the SH values at cosTheta\nsh = zeros(size(coeff));\nshMatrix = repmat(sh, [l_q, 1]);\nfor i = 1:7\n    shMatrix(:,i) = sqrt((i - .75)/pi);\n    % legendre function returns coefficients of all m from 0 to l\n    % we only need the coefficient corresponding to m = 0\n    % WARNING: make sure to input ROW vector as variables!!!\n    % cosTheta is expected to be a COLUMN vector.\n    tmp = legendre(2*i - 2, cosTheta');\n    tmp = tmp';\n    shMatrix(:,i) = shMatrix(:,i) .* tmp(:,1);\nend\n\nE = sum(lgi.*coeffMatrix.*shMatrix, 2);\n% with the SH approximation, there will be no guarantee that E will be positive\n% but we need to make sure it does!!! replace the negative values with 10% of\n% the smallest positive values\nE(find(E<=0)) = min(E(find(E>0)))*0.1;\nE = 0.5*E.*ePerp;\n\n% Compute the Jacobian matrix\nif(nargout>1)\n    % dePerp/dd\n    dePerpdd = E.*J_LePerp(1);\n    % dePar/dd\n    dElgi = sum(J_lgi.*coeffMatrix.*shMatrix, 2);\n    dePardd = 0.5*dElgi.*(J_LePerp(:,:,1) - J_LePar).*ePerp;\n    % dE/dd\n    dEdd = dePardd + dePerpdd;\n    \n\t% dePerp/dR\n    dePerpdR = E.*J_LePerp(2);\n    % dePar/dR\n    dePardR = 0.5*dElgi.*J_LePerp(:,:,2).*ePerp;\n    % dE/dR\n    dEdR = dePardR + dePerpdR;\n    \n    % dE/dK\n    J_coeffMatrix = repmat(J_coeff, [l_q, 1]);\n    dEdk = sum(lgi.*J_coeffMatrix.*shMatrix,2);\n    dEdk = 0.5*dEdk.*ePerp;\n    \n    % Construct the jacobian matrix.\n    J = zeros(length(E), 3);\n    J(:,1) = dEdd;\n    J(:,2) = dEdR;\n    J(:,3) = dEdk;\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/watson/SynthMeasWatsonSHCylNeuman_PGSE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5888193562137792}}
{"text": "% Demonstration of generative model functions.\n%\n% See GENERATIVE_MODEL and EVALUATE_GENERATIVE_MODEL for further details\n% and interpretation.\n\nclear\nclose all\nclc\n\ndata = load('demo_generative_models_data');\nA     = data.A;\nAseed = data.Aseed;\nD     = data.D;\n\n% get cardinality of network\nn = length(A);\n\n% set model type\nmodeltype = 'matching';\n\n% set whether the model is based on powerlaw or exponentials\nmodelvar = [{'powerlaw'},{'powerlaw'}];\n\n% choose some model parameters\nnparams = 100;\nparams = [unifrnd(-10,0,nparams,1), unifrnd(-1,1,nparams,1)];\n\n% generate synthetic networks and energy for the neighbors model;\n[B,E,K] = evaluate_generative_model(Aseed,A,D,modeltype,modelvar,params);\nX = [E,K];\n\n% show scatterplot of parameter values versus energy and KS statistics\nnames = [...\n    {'energy'},...\n    {'degree'},...\n    {'clustering'},...\n    {'betweenness'},...\n    {'edge length'}];\n\nf = figure(...\n    'units','inches',...\n    'position',[2,2,4,4]);\nfor i = 1:size(X,2)\n    subplot(3,2,i);\n    scatter(params(:,1),params(:,2),100,X(:,i),'filled');\n    set(gca,...\n        'clim',[0,1]);\n    colormap(jet);\n    xlabel('geometric parameter, \\eta');\n    ylabel('topological parameter, \\gamma');\n    title(names{i});\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/2019_03_03_BCT/data_and_demos/demo_generative_models_neighbors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5888193518543536}}
{"text": "function [hp] = Btuph2hp(Btuph)\n% Convert power from British thermal units per hour to mechanical horsepower.\n% Chad A. Greene 2012\nhp = Btuph*0.000393015;\n", "meta": {"author": "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/Btuph2hp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5888107468270541}}
{"text": "function plotData(X, y)\n%PLOTDATA Plots the data points X and y into a new figure\n%   PLOTDATA(x,y) plots the data points with + for the positive examples\n%   and o for the negative examples. X is assumed to be a Mx2 matrix.\n\n% Create New Figure\nfigure; hold on;\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Plot the positive and negative examples on a\n%               2D plot, using the option 'k+' for the positive\n%               examples and 'ko' for the negative examples.\n%\n\n% Find Indices of Positive and Negative Examples\npos = find(y==1); neg = find(y == 0);\n\n% Plot Examples\nplot(X(pos, 1), X(pos, 2), 'k+', 'LineWidth', 2, 'MarkerSize', 7);\nplot(X(neg, 1), X(neg, 2), 'ko', 'MarkerFaceColor', 'y', 'MarkerSize', 7);\n\n% =========================================================================\n\n\n\nhold off;\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-ex2/ex2/plotData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.5888107422657808}}
{"text": "function MatingPool = MatingSelection(PopObj,Range,N)\n% The mating selection of RSEA\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\t%% Calculate the convergence of each solution\n    PopObj = (PopObj-repmat(Range(1,:),size(PopObj,1),1))./repmat(Range(2,:)-Range(1,:),size(PopObj,1),1);\n    Con = sum(PopObj.^2,2).^0.5;\n\n    %% Calculate the radar grid of each solution\n    [Site,~] = RadarGrid(PopObj,ceil(sqrt(size(PopObj,1)))); \n    temp     = tabulate(Site);\n    CrowdG   = temp(:,2);\n    \n    %% Binary tournament selection\n    MatingPool = zeros(1,ceil(N/2)*2);\n    grids      = TournamentSelection(2,length(MatingPool),CrowdG);\n    for i = 1 : length(MatingPool)\n        current = find(Site==grids(i));\n        if isempty(current)\n             MatingPool(i) = randi(size(PopObj,1),1);\n        else\n            parents       = current(randi(length(current),1,2));\n            [~,best]      = min(Con(parents));\n            MatingPool(i) = parents(best);\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/Algorithms/Multi-objective optimization/RSEA/MatingSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5887406978908934}}
{"text": "function [data, w] = normalize_data(data, K, scale, w)\n[m,n] = size(data.A);\n\nMIN_SCALE = 1e-3;\nMAX_SCALE = 1e3;\nminRowScale = MIN_SCALE * sqrt(n);\nmaxRowScale = MAX_SCALE * sqrt(n);\nminColScale = MIN_SCALE * sqrt(m);\nmaxColScale = MAX_SCALE * sqrt(m);\n\nD = ones(m,1);\nE = ones(n,1);\nNN = 1; % NN = 1, other choices bad\nfor j=1:NN\n    %% D scale:\n    Dt = twonorms(data.A(1:K.f,:)')';\n    idx = K.f;\n    Dt = [Dt;twonorms(data.A(idx+1:idx+K.l,:)')'];\n    idx = idx + K.l;\n    for i=1:length(K.q)\n        if (K.q(i) > 0)\n            nmA = mean(twonorms(data.A(idx+1:idx+K.q(i),:)'));\n            Dt = [Dt;nmA*ones(K.q(i),1)];\n            idx = idx + K.q(i);\n        end\n    end\n    for i=1:length(K.s)\n        if (K.s(i) > 0)\n            nmA = mean(twonorms(data.A(idx+1:idx+get_sd_cone_size(K.s(i)),:)'));\n            Dt = [Dt;nmA*ones(get_sd_cone_size(K.s(i)),1)];\n            idx = idx + get_sd_cone_size(K.s(i));\n        end\n    end\n    for i=1:K.ep\n        nmA = mean(twonorms(data.A(idx+1:idx+3,:)'));\n        Dt = [Dt;nmA*ones(3,1)];\n        idx = idx + 3;\n    end\n    for i=1:K.ed\n        nmA = mean(twonorms(data.A(idx+1:idx+3,:)'));\n        Dt = [Dt;nmA*ones(3,1)];\n        idx = idx + 3;\n    end\n    for i=1:length(K.p)\n        nmA = mean(twonorms(data.A(idx+1:idx+3,:)'));\n        Dt = [Dt;nmA*ones(3,1)];\n        idx = idx + 3;\n    end\n    \n    Dt(Dt < minRowScale) = 1;\n    Dt(Dt > maxRowScale) = maxRowScale;\n    data.A = sparse(diag(1./Dt))*data.A;\n    \n    %% E Scale\n    Et = twonorms(data.A)';\n    Et(Et < minColScale) = 1;\n    Et(Et > maxColScale) = maxColScale;\n    data.A = data.A*sparse(diag(1./Et));\n    \n    %%\n    D = D.*Dt;\n    E = E.*Et;\nend\n\nnmrowA = mean(twonorms(data.A'));\nnmcolA = mean(twonorms(data.A));\n\ndata.A = data.A*scale;\n\ndata.b = data.b./D;\nsc_b = nmcolA/ max(norm(data.b), MIN_SCALE);\ndata.b = data.b * sc_b * scale;\n\ndata.c = data.c./E;\nsc_c = nmrowA/max(norm(data.c), MIN_SCALE);\ndata.c = data.c * sc_c * scale;\n\nw.D = D;\nw.E = E;\nw.sc_b = sc_b;\nw.sc_c = sc_c;\n\n    function twoNorms = twonorms(A)\n        twoNorms = sqrt(sum(A.^2,1));\n    end\n\nend", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/3rd_Party_Libraries/scs-matlab-master/examples/scs_matlab/normalize_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5887406924847552}}
{"text": "function [ns] = min2ns(min)\n% Convert time from minutes to nanoseconds. \n% Chad Greene 2012\nns = min*60000000000;", "meta": {"author": "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/min2ns.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5887406871500888}}
{"text": " function X = dtft(x, omega, varargin)\n%function X = dtft(x, omega [,options])\n%|\n%| Compute d-dimensional DTFT of signal x at frequency locations omega\n%|\n%| in\n%|\tx\t[(Nd) L]\tsignal values\n%|\tomega\t[M dd]\t\tfrequency locations (radians), dd = numel(Nd)\n%|\n%| option\n%|\t'n_shift' [dd 1]\tuse [0:N-1]-n_shift (default [0 .. 0])\n%|\t'how'\t\t\t'outer' (default) big outer product\n%|\t\t\t\t'loop' reduce memory use (slower)\n%|\t\t\t\t'arrayfun' uses arrayfun()\n%|\n%| out\n%|\tX\t[M L]\t\tDTFT values\n%|\n%| Requires enough memory to store M * prod(Nd) size matrices (for testing)\n%|\n%| Copyright 2001-9-17, Jeff Fessler, University of Michigan\n%| 2013-03-22, Daniel Weller added arrayfun version and other improvements\n%| 2013-03-27, JF converted to vararg\n\nif nargin == 1 && streq(x, 'test'), dtft_test(0), return, end\nif nargin == 1 && streq(x, 'time'), dtft_test(1), return, end\nif nargin < 2, ir_usage(), end\n\narg.n_shift = 0;\narg.how = 'outer';\narg = vararg_pair(arg, varargin);\n\ndd = size(omega, 2);\nNd = size(x);\n\nif numel(arg.n_shift) == 1\n\targ.n_shift = repmat(arg.n_shift, dd);\nend\nn_shift = arg.n_shift;\nif numel(n_shift) ~= dd\n\tfail 'n_shift size bad')\nend\n\nif dd == 1 && numel(Nd) == 2 && Nd(2) == 1 % 1D\n\tNd = Nd(1);\nend\n\nif length(Nd) == dd % just one image\n\tx = x(:);\nelseif length(Nd) == dd+1 % multiple images\n\tNd = Nd(1:(end-1));\n\tx = reshapee(x, prod(Nd), []); % [*Nd L]\nelse\n\terror 'bad input signal size'\nend\n\n% dsw alternative to the loop:\n% nn = arrayfun(@(nd,nshift) (0:(nd-1))-nshift, Nd, n_shift, 'UniformOutput', false);\nfor id=1:dd\n\tnn{id} = [0:(Nd(id)-1)] - n_shift(id);\nend\n\n% nn = ndgrid_jf('cell', nn);\nif dd > 1\n\t[nn{:}] = ndgrid(nn{:});\nend\n\nswitch arg.how\ncase 'outer'\n\tX = dtft_outer(x, omega, nn);\ncase 'loop'\n\tX = dtft_loop(x, omega, Nd, nn);\ncase 'arrayfun'\n\tX = dtft_arrayfun(x, omega, nn);\notherwise\n\tfail('unknown how \"%s\"', arg.how)\nend\n\n\n% dtft_outer()\nfunction X = dtft_outer(x, omega, nn);\nX = 0;\ndd = ncol(omega);\nfor id=1:dd % add up phases\n\tX = X + omega(:,id) * col(nn{id})'; % [M *Nd]\nend\nX = exp(-1i*X) * x;\n\n\n% dtft_loop()\n% loop way: slower but less memory\nfunction X = dtft_loop(x, omega, Nd, nn);\nM = nrow(omega);\nX = zeros(numel(x)/prod(Nd),M); % [L M]\n%t1 = col(nn{1})';\nif ncol(omega) > 3\n\tfail 'only up to 3d done'\nend\nif ncol(omega) < 3\n\tfor dd = (ncol(omega)+1) : 3\n\t\tnn{dd} = 0; % dummy 0's\n\tend\n\tomega(1,3) = 0; % trick: make '3d'\nend\nt1 = nn{1}(:)';\nt2 = col(nn{2})';\nt3 = col(nn{3})';\nfor mm=1:M\n\ttmp = omega(mm,1)*t1 + omega(mm,2)*t2 + omega(mm,3)*t3;\n\tX(:,mm) = exp(-1i * tmp) * x;\nend\nX = X.'; % [M L]\n\n\n% dtft_arrayfun()\n% by Dan Weller, 2013-03-27\nfunction X = dtft_arrayfun(x, omega, nn);\nnn = cellfun(@(x) col(x).',nn,'UniformOutput',false); % make row vectors\nnn = cat(1,nn{:}); % [dd *Nd]\n\nM = nrow(omega);\nX = arrayfun(@(m) exp((-1i*omega(m,:)) * nn) * x, 1:M, 'UniformOutput', false); % each cell is [1 L]\nX = cat(1,X{:}); % [M L]\n\n% X = exp(-1i*(omega * nn)) * x; % [M L]\n\n\n% dtft_test\n% simple test\nfunction dtft_test(do_time)\nNd = [4 6 5] * 2^(1+do_time);\nn_shift = [1 3 2];\nrng(0), x = randn(Nd); % test signal\no1 = 2*pi*[0:(Nd(1)-1)]'/Nd(1); % test with uniform frequency locations\no2 = 2*pi*[0:(Nd(2)-1)]'/Nd(2);\no3 = 2*pi*[0:(Nd(3)-1)]'/Nd(3);\n[o1 o2 o3] = ndgrid(o1, o2, o3);\nom = [o1(:) o2(:) o3(:)];\ncpu etic\nXd = dtft(x, om, 'n_shift', n_shift);\ncpu etoc outer\ncpu etic\nXl = dtft(x, om, 'n_shift', n_shift, 'how', 'loop');\ncpu etoc loop\ncpu etic\nXa = dtft(x, om, 'n_shift', n_shift, 'how', 'arrayfun');\ncpu etoc arrayfun\nprintm('loop max %% difference = %g', max_percent_diff(Xl,Xd))\nprintm('afun max %% difference = %g', max_percent_diff(Xa,Xd))\nXf = fftn(x);\nXf = Xf(:) .* exp(1i * (om * n_shift(:))); % phase shift\nprintm('fftn 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/dtft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5887406870071443}}
{"text": "function y = norms( varargin )\n\n%NORMS   Computation of multiple vector norms.\n%   NORMS( X ) provides a means to compute the norms of multiple vectors\n%   packed into a matrix or N-D array. This is useful for performing\n%   max-of-norms or sum-of-norms calculations.\n%\n%   All of the vector norms, including the false \"-inf\" norm, supported\n%   by NORM() have been implemented in the NORMS() command.\n%     NORMS(X,P)           = sum(abs(X).^P).^(1/P)\n%     NORMS(X)             = NORMS(X,2).\n%     NORMS(X,inf)         = max(abs(X)).\n%     NORMS(X,-inf)        = min(abs(X)).\n%   If X is a vector, these computations are completely identical to\n%   their NORM equivalents. If X is a matrix, a row vector is returned\n%   of the norms of each column of X. If X is an N-D matrix, the norms\n%   are computed along the first non-singleton dimension.\n%\n%   NORMS( X, [], DIM ) or NORMS( X, 2, DIM ) computes Euclidean norms\n%   along the dimension DIM. NORMS( X, P, DIM ) computes its norms\n%   along the dimension DIM.\n%\n%   Disciplined convex programming information:\n%       NORMS is convex, except when P<1, so an error will result if these\n%       non-convex \"norms\" are used within CVX expressions. NORMS is\n%       nonmonotonic, so its input must be affine.\n\npersistent P\nif isempty( P ),\n    P.map = cvx_remap( { 'constant' ; 'l_convex' ; ...\n        { 'p_convex', 'n_concave', 'affine' } } );\n    P.funcs = { @norms_1, @norms_1, @norms_2 };\n    P.zero = 0;\n    P.reduce = true;\n    P.reverse = false;\n    P.constant = 1;\n    P.fname = 'norms';\n    P.dimarg = 3;\nend\n[ sx, x, p, dim ] = cvx_get_dimension( varargin, 3 );\nif nargin < 2 || isempty(p),\n    p = 2;\nelseif ~( isnumeric(p) && numel(p)==1 && isreal(p) && p >= 1 ),\n    cvx_throw( 'Second argument must be a scalar between 1 and +Inf, inclusive.' );\nend\nif sx(dim) == 0,\n    sx(dim) = 1;\n    y = zeros( sx, 1 );\n    if isa( x, 'cvx' ), y = cvx( y ); end\nelseif sx(dim) == 1,\n    y = abs( x );\nelseif p == 1,\n    y = sum( abs( x ), dim );\nelseif p == Inf,\n    y = max( abs( x ), [], dim );\nelse\n    y = cvx_reduce_op( P, x, p, dim );\nend\n\nfunction y = norms_1( x, p )\ny = sum( abs( x ) .^ p, 1 ) .^ ( 1 / p );\n\nfunction y = norms_2( x, p ) %#ok\n[nx,nv] = size(x);\nif p == 2,\n    cvx_begin\n        epigraph variable y( 1, nv ) nonnegative_\n        { linearize(x), y } == lorentz( [ nx, nv ], 1, ~isreal( x ) ); %#ok\n    cvx_end\nelse\n    cvx_begin\n        variable z( nx, nv )\n        epigraph variable y( 1, nv ) nonnegative_\n        if isreal(x), cmode = 'abs'; else cmode = 'cabs'; end\n        { cat( 3, z, repmat(y,[nx,1]) ), linearize(x) } ...\n            == geo_mean_cone( [nx,nv,2], 3, [1/p,1-1/p], cmode ); %#ok\n        sum( z ) == y; %#ok\n    cvx_end\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/norms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.588740676266339}}
{"text": "function model = createToyModelForLooplessFVA()\n% Create a toy model that has a loop and will give different solutions when\n% minimizing the 0-, 1- and 2-norms respectively\n%\n%    <=> B    10  10   10  10\n%         \\    <===> F <===>\n% <=> A ----> D -----------> E <=>\n%      2 2/\n%       2/\n%   <=> C\n\nmodel = createModel();\nReactions = {'R1', 'A + B -> D'; ...\n             'R2', '2 A + 2 C -> 2 D';...\n             'R3', 'D -> E';...\n             'R4', '10 D <=> 10 F';...\n             'R5', '10 F <=> 10 E';...\n             'Ex_A', 'A <=>'; ...\n             'Ex_B', 'B <=>'; ...\n             'Ex_C', 'C <=>'; ...\n             'Ex_E', 'E <=>'};\n         \n%Add Reactions\nfor i = 1:size(Reactions,1)\n    %All reactions are irreversible\n    model = addReaction(model, Reactions{i,1}, 'reactionFormula', Reactions{i,2}, 'printLevel', -1);\nend\n\n% uptake bound for A = 1\nmodel = changeRxnBounds(model, 'Ex_A', -1, 'l');\n% objective: max production of E\nmodel = changeObjective(model, 'Ex_E', 1);\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/verifiedTests/analysis/testFVA/createToyModelForLooplessFVA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5886503272528602}}
{"text": "function [ bic ] = BIC_f(loglik,k,nbParamK,N)\n%BIC\n\nbic = -2*loglik + k*nbParamK*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/GMMfunctions/plotGaussians/BIC_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5886503167008128}}
{"text": "function rule_num = triangle_nco_rule_num ( )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_NCO_RULE_NUM returns the number of NCO rules available.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 January 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Peter Silvester,\n%    Symmetric Quadrature Formulae for Simplexes,\n%    Mathematics of Computation,\n%    Volume 24, Number 109, January 1970, pages 95-100.\n%\n%  Parameters:\n%\n%    Output, integer RULE_NUM, the number of rules available.\n%\n  rule_num = 9;\n\n  return\nend\n", "meta": {"author": "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_nco_rule/triangle_nco_rule_num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.5886503111510615}}
{"text": "function [h, hdata] = mlphess_weighted(net, x, t, eso_w, hdata)\n%MLPHESS Evaluate the Hessian matrix for a multi-layer perceptron network.\n%\n%\tDescription\n%\tH = MLPHESS(NET, X, T) takes an MLP network data structure NET, a\n%\tmatrix X of input values, and a matrix T of target values and returns\n%\tthe full Hessian matrix H corresponding to the second derivatives of\n%\tthe negative log posterior distribution, evaluated for the current\n%\tweight and bias values as defined by NET.\n%\n%\t[H, HDATA] = MLPHESS(NET, X, T) returns both the Hessian matrix H and\n%\tthe contribution HDATA arising from the data dependent term in the\n%\tHessian.\n%\n%\tH = MLPHESS(NET, X, T, HDATA) takes a network data structure NET, a\n%\tmatrix X of input values, and a matrix T of  target values, together\n%\twith the contribution HDATA arising from the data dependent term in\n%\tthe Hessian, and returns the full Hessian matrix H corresponding to\n%\tthe second derivatives of the negative log posterior distribution.\n%\tThis version saves computation time if HDATA has already been\n%\tevaluated for the current weight and bias values.\n%\n%\tSee also\n%\tMLP, HESSCHEK, MLPHDOTV, EVIDENCE\n%\n\n%\tCopyright (c) Ian T Nabney (1996-9)\n\n% Check arguments for consistency\nerrstring = consist(net, 'mlp', x, t);\nif ~isempty(errstring);\n  error(errstring);\nend\n\nif nargin == 4\n  % Data term in Hessian needs to be computed\n  hdata = datahess(net, x, t, eso_w);\nend\n\n[h, hdata] = hbayes(net, hdata);\n\n% Sub-function to compute data part of Hessian\nfunction hdata = datahess(net, x, t, eso_w)\n\nhdata = zeros(net.nwts, net.nwts);\n\nfor v = eye(net.nwts);\n  hdata(find(v),:) = mlphdotv_weighted(net, x, t, eso_w, v);\nend\n\nreturn\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlabKPM/mlphess_weighted.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5886503003252863}}
{"text": "% For all clusters, correlation with nearest neighbor\nC = FindCentroid(hfig);\ncoeffs = corr(C');\n\nA = zeros(1,length(coeffs));\nfor i = 1:length(coeffs),\n   coeffs(i,i) = nan;\n   A(i) = max(coeffs(i,:));\nend\n\nfigure; hist(A)\n\n%% Distribution of within-cluster correlations\nU = unique(gIX);\nnumU = length(U);\nB = zeros(numU,3);\nfor i=1:numU,\n    i\n    IX = find(gIX == U(i));\n    coeffs = corr(M(IX,:)');\n    m = coeffs(:);\n    B(i,1) = min(m);\n    B(i,2) = mean(m);\n    B(i,3) = median(m);\nend\n\nfigure;hist(B)\n%%\nfigure;\nhist(B(:,2))\nh = findobj(gca,'Type','patch');\nh.FaceColor = [0.5 0.5 0.5];\nh.EdgeColor = 'w';\nxlim([0,1])\nxlabel('average corr. within cluster')\nylabel('count')\n\n%% Distribution of cluster sizes\nU = unique(gIX);\nnumU = length(U);\nC = zeros(numU,1);\nfor i=1:numU,\n    i\n    IX = find(gIX == U(i));    \n    C(i) = length(IX);\nend\n[N,edges] = histcounts(C,10:10:2100);\n%%\nfigure;\nh = bar(edges,[0,N])%+1)\nset(gca,'XScale','log')\nset(gca,'YScale','log')\n% h = findobj(gca,'Type','patch');\nh.FaceColor = [0.5 0.5 0.5];\nh.EdgeColor = 'w';\nxlim([5,1000])\nylim([-10,100])\nxlabel('cluster size')\nylabel('number of clusters (+1 to differentiate 0 from 1)')\n%%\nfigure;hold on;\nfor i = 1:length(N),\n    plot([edges(i),edges(i)],[0,N(i)],'color',[1,0.5,0.5],'linewidth',6)\nend\nset(gca,'XScale','log')\n% set(gca,'YScale','log')\nxlim([5,1000])\nylim([0,85])\nxlabel('cluster size')\nylabel('count')\n\n%%\nset(gca,'XScale','log')\nset(gca,'YScale','log')\n% h = findobj(gca,'Type','patch');\nh.FaceColor = [0.5 0.5 0.5];\nh.EdgeColor = 'w';\nxlim([5,1000])\nylim([-10,100])\nxlabel('cluster size')\nylabel('number of clusters (+1 to differentiate 0 from 1)')\n\n%% Plot Foxel Characterization\n\nfigure;\n% after second kmeans\ncounts = hist(gIX,1:max(gIX));\nhist(counts,1:1:200);\ntitle('Fish8: cluster sizes after 2nd kmeans');\ntext(20,300,'mean=10;median=4;mode=1;31 clusters>200')", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/old code/CheckClustersStats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5886503003252863}}
{"text": "function [x, f, eflag, output, lambda] = miqps_cplex(H, c, A, l, u, xmin, xmax, x0, vtype, opt)\n%MIQPS_CPLEX  Mixed Integer Quadratic Program Solver based on CPLEX.\n%   [X, F, EXITFLAG, OUTPUT, LAMBDA] = ...\n%       MIQPS_CPLEX(H, C, A, L, U, XMIN, XMAX, X0, VTYPE, OPT)\n%   [X, F, EXITFLAG, OUTPUT, LAMBDA] = MIQPS_CPLEX(PROBLEM)\n%   A wrapper function providing a standardized interface for using\n%   CPLEXQP or CPLEXLP to solve the following QP (quadratic programming)\n%   problem:\n%\n%       min 1/2 X'*H*X + C'*X\n%        X\n%\n%   subject to\n%\n%       L <= A*X <= U       (linear constraints)\n%       XMIN <= X <= XMAX   (variable bounds)\n%\n%   Inputs (all optional except H, C, A and L):\n%       H : matrix (possibly sparse) of quadratic cost coefficients\n%       C : vector of linear cost coefficients\n%       A, L, U : define the optional linear constraints. Default\n%           values for the elements of L and U are -Inf and Inf,\n%           respectively.\n%       XMIN, XMAX : optional lower and upper bounds on the\n%           X variables, defaults are -Inf and Inf, respectively.\n%       X0 : optional starting value of optimization vector X\n%       VTYPE : character string of length NX (number of elements in X),\n%               or 1 (value applies to all variables in x),\n%               allowed values are 'C' (continuous), 'B' (binary),\n%               'I' (integer), 'S' (semi-continuous), or 'N' (semi-integer).\n%       OPT : optional options structure with the following fields,\n%           all of which are also optional (default values shown in\n%           parentheses)\n%           verbose (0) - controls level of progress output displayed\n%               0 = no progress output\n%               1 = some progress output\n%               2 = verbose progress output\n%           skip_prices (0) - flag that specifies whether or not to\n%               skip the price computation stage, in which the problem\n%               is re-solved for only the continuous variables, with all\n%               others being constrained to their solved values\n%           price_stage_warn_tol (1e-7) - tolerance on the objective fcn\n%               value and primal variable relative match required to avoid\n%               mis-match warning message\n%           cplex_opt - options struct for CPLEX, value in verbose\n%                   overrides these options\n%       PROBLEM : The inputs can alternatively be supplied in a single\n%           PROBLEM struct with fields corresponding to the input arguments\n%           described above: H, c, A, l, u, xmin, xmax, x0, vtype, opt\n%\n%   Outputs:\n%       X : solution vector\n%       F : final objective function value\n%       EXITFLAG : CPLEXQP/CPLEXLP exit flag\n%           (see CPLEXQP and CPLEXLP documentation for details)\n%       OUTPUT : CPLEXQP/CPLEXLP output struct\n%           (see CPLEXQP and CPLEXLP documentation for details)\n%       LAMBDA : struct containing the Langrange and Kuhn-Tucker\n%           multipliers on the constraints, with fields:\n%           mu_l - lower (left-hand) limit on linear constraints\n%           mu_u - upper (right-hand) limit on linear constraints\n%           lower - lower bound on optimization variables\n%           upper - upper bound on optimization variables\n%\n%   Note the calling syntax is almost identical to that of QUADPROG\n%   from MathWorks' Optimization Toolbox. The main difference is that\n%   the linear constraints are specified with A, L, U instead of\n%   A, B, Aeq, Beq.\n%\n%   Calling syntax options:\n%       [x, f, exitflag, output, lambda] = ...\n%           miqps_cplex(H, c, A, l, u, xmin, xmax, x0, vtype, opt)\n%\n%       x = miqps_cplex(H, c, A, l, u)\n%       x = miqps_cplex(H, c, A, l, u, xmin, xmax)\n%       x = miqps_cplex(H, c, A, l, u, xmin, xmax, x0)\n%       x = miqps_cplex(H, c, A, l, u, xmin, xmax, x0, vtype)\n%       x = miqps_cplex(H, c, A, l, u, xmin, xmax, x0, vtype, opt)\n%       x = miqps_cplex(problem), where problem is a struct with fields:\n%                       H, c, A, l, u, xmin, xmax, x0, vtype, opt\n%                       all fields except 'c', 'A' and 'l' or 'u' are optional\n%       x = miqps_cplex(...)\n%       [x, f] = miqps_cplex(...)\n%       [x, f, exitflag] = miqps_cplex(...)\n%       [x, f, exitflag, output] = miqps_cplex(...)\n%       [x, f, exitflag, output, lambda] = miqps_cplex(...)\n%\n%\n%   Example: (problem from from https://v8doc.sas.com/sashtml/iml/chap8/sect12.htm)\n%       H = [   1003.1  4.3     6.3     5.9;\n%               4.3     2.2     2.1     3.9;\n%               6.3     2.1     3.5     4.8;\n%               5.9     3.9     4.8     10  ];\n%       c = zeros(4,1);\n%       A = [   1       1       1       1;\n%               0.17    0.11    0.10    0.18    ];\n%       l = [1; 0.10];\n%       u = [1; Inf];\n%       xmin = zeros(4,1);\n%       x0 = [1; 0; 0; 1];\n%       opt = struct('verbose', 2);\n%       [x, f, s, out, lambda] = miqps_cplex(H, c, A, l, u, xmin, [], x0, vtype, opt);\n%\n%   See also MIQPS_MASTER, CPLEXMIQP, CPLEXMILP, CPLEXQP, CPLEXLP,\n%   CPLEX_OPTIONS.\n\n%   MP-Opt-Model\n%   Copyright (c) 2010-2020, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MP-Opt-Model.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://github.com/MATPOWER/mp-opt-model for more info.\n\n%% check for CPLEX\n% if ~have_feature('cplexqp')\n%     error('miqps_cplex: requires the MATLAB interface for CPLEX');\n% end\n\n%%----- input argument handling  -----\n%% gather inputs\nif nargin == 1 && isstruct(H)       %% problem struct\n    p = H;\n    if isfield(p, 'opt'),   opt = p.opt;    else,   opt = [];   end\n    if isfield(p, 'vtype'), vtype = p.vtype;else,   vtype = []; end\n    if isfield(p, 'x0'),    x0 = p.x0;      else,   x0 = [];    end\n    if isfield(p, 'xmax'),  xmax = p.xmax;  else,   xmax = [];  end\n    if isfield(p, 'xmin'),  xmin = p.xmin;  else,   xmin = [];  end\n    if isfield(p, 'u'),     u = p.u;        else,   u = [];     end\n    if isfield(p, 'l'),     l = p.l;        else,   l = [];     end\n    if isfield(p, 'A'),     A = p.A;        else,   A = [];     end\n    if isfield(p, 'c'),     c = p.c;        else,   c = [];     end\n    if isfield(p, 'H'),     H = p.H;        else,   H = [];     end\nelse                                %% individual args\n    if nargin < 10\n        opt = [];\n        if nargin < 9\n            vtype = [];\n            if nargin < 8\n                x0 = [];\n                if nargin < 7\n                    xmax = [];\n                    if nargin < 6\n                        xmin = [];\n                    end\n                end\n            end\n        end\n    end\nend\n\n%% define nx, set default values for missing optional inputs\nif isempty(H) || ~any(any(H))\n    if isempty(A) && isempty(xmin) && isempty(xmax)\n        error('miqps_cplex: LP problem must include constraints or variable bounds');\n    else\n        if ~isempty(A)\n            nx = size(A, 2);\n        elseif ~isempty(xmin)\n            nx = length(xmin);\n        else    % if ~isempty(xmax)\n            nx = length(xmax);\n        end\n    end\nelse\n    nx = size(H, 1);\nend\nif isempty(c)\n    c = zeros(nx, 1);\nend\nif isempty(A) || (~isempty(A) && (isempty(l) || all(l == -Inf)) && ...\n                                 (isempty(u) || all(u == Inf)))\n    A = sparse(0,nx);           %% no limits => no linear constraints\nend\nnA = size(A, 1);                %% number of original linear constraints\nif isempty(u)                   %% By default, linear inequalities are ...\n    u = Inf(nA, 1);             %% ... unbounded above and ...\nend\nif isempty(l)\n    l = -Inf(nA, 1);            %% ... unbounded below.\nend\nif isempty(xmin)                %% By default, optimization variables are ...\n    xmin = -Inf(nx, 1);         %% ... unbounded below and ...\nend\nif isempty(xmax)\n    xmax = Inf(nx, 1);          %% ... unbounded above.\nend\nif isempty(x0)\n    x0 = zeros(nx, 1);\nend\n\n%% default options\nif ~isempty(opt) && isfield(opt, 'verbose') && ~isempty(opt.verbose)\n    verbose = opt.verbose;\nelse\n    verbose = 0;\nend\n\n%% split up linear constraints\nieq = find( abs(u-l) <= eps );          %% equality\nigt = find( u >=  1e10 & l > -1e10 );   %% greater than, unbounded above\nilt = find( l <= -1e10 & u <  1e10 );   %% less than, unbounded below\nibx = find( (abs(u-l) > eps) & (u < 1e10) & (l > -1e10) );\nAe = A(ieq, :);\nbe = u(ieq);\nAi  = [ A(ilt, :); -A(igt, :); A(ibx, :); -A(ibx, :) ];\nbi  = [ u(ilt);    -l(igt);    u(ibx);    -l(ibx)];\n\n%% grab some dimensions\nnlt = length(ilt);      %% number of upper bounded linear inequalities\nngt = length(igt);      %% number of lower bounded linear inequalities\nnbx = length(ibx);      %% number of doubly bounded linear inequalities\n\n%% set up options struct for CPLEX\nif ~isempty(opt) && isfield(opt, 'cplex_opt') && ~isempty(opt.cplex_opt)\n    cplex_opt = cplex_options(opt.cplex_opt);\nelse\n    cplex_opt = cplex_options;\nend\n\nvstr = have_feature('cplex', 'vstr');\nvnum = have_feature('cplex', 'vnum');\nvrb = max([0 verbose-1]);\nif vrb && vnum > 12.002 && vnum < 12.007\n    cplex_opt.diagnostics   = 'on';\nend\nif verbose > 2\n    cplex_opt.display = 'iter';\nelseif verbose > 1\n    cplex_opt.display = 'on';\nelseif verbose > 0\n    cplex_opt.display = 'off';\nend\n\nif isempty(Ai) && isempty(Ae)\n    unconstrained = 1;\n    Ae = sparse(1, nx);\n    be = 0;\nelse\n    unconstrained = 0;\nend\n\n%% call the solver\nif verbose\n    alg_names = {\n        'default',\n        'primal simplex',\n        'dual simplex',\n        'network simplex',\n        'barrier',\n        'sifting',\n        'concurrent'\n    };\nend\nif isempty(vtype) || isempty(find(vtype == 'B' | vtype == 'I' | ...\n        vtype == 'S' | vtype == 'N'))\n    mi = 0;\nelse\n    mi = 1;\n    %% expand vtype to nx elements if necessary\n    if length(vtype) == 1 && nx > 1\n        vtype = char(vtype * ones(1,nx));\n    end\nend\n\nif mi\n    if isempty(H) || ~any(any(H))\n        if verbose\n            fprintf('CPLEX Version %s -- %s MILP solver\\n', ...\n                vstr, alg_names{cplex_opt.lpmethod+1});\n        end\n        [x, f, eflag, output] = ...\n            cplexmilp(c, Ai, bi, Ae, be, [], [], [], xmin, xmax, vtype, x0, cplex_opt);\n        lam = [];\n    else\n        if verbose\n            fprintf('CPLEX Version %s --  %s MIQP solver\\n', ...\n                vstr, alg_names{cplex_opt.qpmethod+1});\n        end\n        %% ensure H is numerically symmetric\n        if ~isequal(H, H')\n            H = (H + H')/2;\n        end\n        [x, f, eflag, output] = ...\n            cplexmiqp(H, c, Ai, bi, Ae, be, [], [], [], xmin, xmax, vtype, x0, cplex_opt);\n    end\n    lam = [];\nelse\n    if isempty(H) || ~any(any(H))\n        if verbose\n            fprintf('CPLEX Version %s -- %s LP solver\\n', ...\n                vstr, alg_names{cplex_opt.lpmethod+1});\n        end\n        [x, f, eflag, output, lam] = ...\n            cplexlp(c, Ai, bi, Ae, be, xmin, xmax, x0, cplex_opt);\n    else\n        if verbose\n            fprintf('CPLEX Version %s --  %s QP solver\\n', ...\n                vstr, alg_names{cplex_opt.qpmethod+1});\n        end\n        %% ensure H is numerically symmetric\n        if ~isequal(H, H')\n            H = (H + H')/2;\n        end\n        [x, f, eflag, output, lam] = ...\n            cplexqp(H, c, Ai, bi, Ae, be, xmin, xmax, x0, cplex_opt);\n    end\nend\n\n%% workaround for eflag == 5 (which we have seen return infeasible results)\n%%          cplexstatus: 6\n%%    cplexstatusstring: 'non-optimal'\n%%              message: 'Solution with numerical issues'\nif eflag > 1\n    warning('qps_cplex: Undocumented ''exitflag'' value (%d)\\n          cplexstatus: %d\\n    cplexstatusstring: ''%s''\\n              message: ''%s''', eflag, output.cplexstatus, output.cplexstatusstring, output.message);\n    if eflag == 5 && mi\n        eflag = 1;      %% give it a try for the MI phase\n    else\n        eflag = -100 - eflag;\n    end\nend\n\n%% check for empty results (in case optimization failed)\nif isempty(x)\n    x = NaN(nx, 1);\nend\nif isempty(f)\n    f = NaN;\nend\nif isempty(lam)\n    lam.ineqlin = NaN(length(bi), 1);\n    lam.eqlin   = NaN(length(be), 1);\n    lam.lower   = NaN(nx, 1);\n    lam.upper   = NaN(nx, 1);\n    mu_l        = NaN(nA, 1);\n    mu_u        = NaN(nA, 1);\nelse\n    mu_l        = zeros(nA, 1);\n    mu_u        = zeros(nA, 1);\nend\nif unconstrained\n    lam.eqlin = [];\nend\n\n%% negate prices depending on version\nif vnum < 12.003\n    lam.eqlin   = -lam.eqlin;\n    lam.ineqlin = -lam.ineqlin;\nend\n\n%% repackage lambdas\nkl = find(lam.eqlin < 0);   %% lower bound binding\nku = find(lam.eqlin > 0);   %% upper bound binding\n\nmu_l(ieq(kl)) = -lam.eqlin(kl);\nmu_l(igt) = lam.ineqlin(nlt+(1:ngt));\nmu_l(ibx) = lam.ineqlin(nlt+ngt+nbx+(1:nbx));\n\nmu_u(ieq(ku)) = lam.eqlin(ku);\nmu_u(ilt) = lam.ineqlin(1:nlt);\nmu_u(ibx) = lam.ineqlin(nlt+ngt+(1:nbx));\n\nlambda = struct( ...\n    'mu_l', mu_l, ...\n    'mu_u', mu_u, ...\n    'lower', lam.lower, ...\n    'upper', lam.upper ...\n);\n\nif mi && eflag == 1 && (~isfield(opt, 'skip_prices') || ~opt.skip_prices)\n    if verbose\n        fprintf('--- Integer stage complete, starting price computation stage ---\\n');\n    end\n    if isfield(opt, 'price_stage_warn_tol') && ~isempty(opt.price_stage_warn_tol)\n        tol = opt.price_stage_warn_tol;\n    else\n        tol = 1e-7;\n    end\n    k = find(vtype == 'I' | vtype == 'B' | vtype == 'N' | ...\n            (vtype == 'S' & x' == 0));\n    x(k) = round(x(k));\n    xmin(k) = x(k);\n    xmax(k) = x(k);\n    x0 = x;\n    opt.cplex_opt.lpmethod = 1;     %% primal simplex\n    opt.cplex_opt.qpmethod = 1;     %% primal simplex\n    \n    [x_, f_, eflag_, output_, lambda] = qps_cplex(H, c, A, l, u, xmin, xmax, x0, opt);\n    if eflag ~= eflag_\n        error('miqps_cplex: EXITFLAG from price computation stage = %d', eflag_);\n    end\n    if abs(f - f_)/max(abs(f), 1) > tol\n        warning('miqps_cplex: relative mismatch in objective function value from price computation stage = %g', abs(f - f_)/max(abs(f), 1));\n    end\n    xn = x;\n    xn(abs(xn)<1) = 1;\n    [mx, k] = max(abs(x - x_) ./ xn);\n    if mx > tol\n        warning('miqps_cplex: max relative mismatch in x from price computation stage = %g (%g)', mx, x(k));\n    end\n    output.price_stage = output_;\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/mp-opt-model/lib/miqps_cplex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5886503000515584}}
{"text": "function [P] = spm_mci_update_cov (P)\n% Update covariance matrix of proposal density using Robbins-Monro\n% FORMAT [P] = spm_mci_update_cov (P)\n%\n% See e.g.\n% H. Haario, E. Saksman, and J. Tamminen. An adaptive Metropolis algorithm. \n% Bernoulli, 7(2):223-242, 2001.\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_mci_update_cov.m 7679 2019-10-24 15:54:07Z spm $\n\nNp=size(P.theta,1);\ngamma=1/P.adapt_its;\n\nx=P.theta(:,end);\ndx=x-P.mu;\n\nP.mu=P.mu+gamma*dx;\nP.Ct=P.Ct+gamma*(dx*dx'-P.Ct);\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/mci/inference/spm_mci_update_cov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5886068623044873}}
{"text": "function d = bpdhe(im)\n\nim = im2uint8(im);\n\nhsv = rgb2hsv(im);\nh = hsv(:,:,1);\ns = hsv(:,:,2);\ni = uint8(hsv(:,:,3).*255);\n% i = uint8(20+rand(512).*(200));\nma = double(max(i(:)));\nmi = double(min(i(:)));\nbins = (ma-mi)+1;\nhist_i = hist(double(i(:)),bins);\ngausFilter = fspecial('gaussian',[1 9],1.0762);\nblur_hist = (imfilter(hist_i,gausFilter,'replicate'));\nderivFilter = [-1 1];\nderiv_hist = imfilter(blur_hist,derivFilter,'replicate');\nsign_hist = sign(deriv_hist);\nmeanFilter = [1/3 1/3 1/3];\nsmooth_sign_hist = sign(imfilter(sign_hist,meanFilter,'replicate'));\ncmpFilter = [1 1 1  -1 -1 -1 -1 -1];\nindex = zeros([1,3]);\nindex(1) = 0;\np = 2;\nfor n = 1:bins-7\n    C = smooth_sign_hist(n:n+7) == cmpFilter;\n    if sum(C) ==8\n        index(p) = n+3;\n        p = p+1;\n    end \nend\nindex(p) = bins;\nfactor = zeros([length(index)-1,1]);\nspan = factor;\nM = factor;\nrange = factor;\nstart = factor;\nendd = factor;\nsub_hist = cell([length(index)-1,1]);\nfor m = 1:length(index)-1;\n    sub_hist{m} = hist_i(index(m)+1:index(m+1));\n    M(m) = sum(sub_hist{m});\n    low = mi + index(m);\n    high = mi + index(m+1)-1; \n    span(m) = high-low+1;\n    factor(m) = span(m)*log10(M(m));\nend\nfactor_sum = sum(factor);\nfor m = 1:length(index)-1;\n    range(m) = round((256-mi)*factor(m)/factor_sum);\nend\nstart(1) = mi;\nendd(1) = mi+range(1)-1;\nfor m = 2:length(index)-1;\n    start(m) = start(m-1)+range(m-1);\n    endd(m) = endd(m-1)+range(m);\nend\ny = cell([length(index)-1,1]);\ns_r = zeros([1,mi]);\nfor m = 1:length(index)-1;\n    hist_cum = cumsum(sub_hist{m});\n    c = hist_cum./M(m);\n    y{m} = round(start(m)+(endd(m)-start(m)).*c);\n    s_r = [s_r,y{m}];\nend\ni_s = zeros(size(i));\nfor n = mi:ma\n    lc = i == n;\n    i_s(lc) = double(s_r(n+1))/255;\nend\n% hist_is = hist(double(i_s(:)),bins);\nhsi_o = cat(3,h,s,i_s);\nd = uint8(hsv2rgb(hsi_o).*255);\n", "meta": {"author": "dawnlh", "repo": "awesome-low-light-image-enhancement", "sha": "673e7ef10c2d1d29887ff5bc54474d441f53c2ff", "save_path": "github-repos/MATLAB/dawnlh-awesome-low-light-image-enhancement", "path": "github-repos/MATLAB/dawnlh-awesome-low-light-image-enhancement/awesome-low-light-image-enhancement-673e7ef10c2d1d29887ff5bc54474d441f53c2ff/codes/bpdhe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5886068459540232}}
{"text": "function combo_test21 ( )\n\n%*****************************************************************************80\n%\n%% COMBO_TEST21 tests NPART_TABLE and PART_TABLE.\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  maxn = 10;\n  maxpart = 5;\n\n  fprintf ( 1, ' \\n' );\n  fprintf ( 1, 'COMBO_TEST21\\n' );\n  fprintf ( 1, '  NPART_TABLE tabulates partitions\\n' );\n  fprintf ( 1, '  of N with NPART parts;\\n' );\n  fprintf ( 1, '  PART_TABLE tabulates partitions of N.\\n' );\n\n  offset = 1;\n\n  p = npart_table ( maxn, maxpart );\n\n  p2 = part_table ( maxn );\n\n  fprintf ( 1, ' \\n' );\n  fprintf ( 1, '    I P(I)  P(I,0) P(I,1) P(I,2) P(I,3) P(I,4) P(I,5)\\n' );\n  fprintf ( 1, ' \\n' );\n\n  for i = 0 : maxn\n    fprintf ( 1, '%5d%5d', i, p2(i+offset) );\n    for j = 0 : maxpart\n      fprintf ( 1, '%5d', p(i+offset,j+offset) );\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/combo/combo_test21.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.5885720338824239}}
{"text": "close all;\nclear all;\nclc;\npng_export = true;\npdf_export = false;\n\nload('bin/rand_dict_bp_omp_success_with_k_figure_1.mat');\n\nmf = spx.graphics.Figures();\n\nmf.new_figure('Recovery probability with K');\nhold all;\nplot(Ks, bp_success_with_k);\nplot(Ks, omp_success_with_k);\nxlabel('Sparsity level');\nylabel('probability of successful recovery');\nlegend('BP', 'OMP');\ngrid on;\n\n\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/examples/pursuit/joint_recovery/chen2006theoretical/print_fig_1_a_rand_dict_omp_bp_with_k.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.5885720338824237}}
{"text": "function b = cptsl ( n, d, e, b )\n\n%*****************************************************************************80\n%\n%% CPTSL solves a Hermitian positive definite tridiagonal linear system.\n%\n%  Discussion;\n%\n%    The system does not have to be factored first.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    07 May 2007\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, complex D(N), the diagonal of the matrix.\n%\n%    Input, complex E(N), the superdiagonal of the matrix in E(1:N-1).  \n%\n%    Input, complex B(N), the right hand side.\n%\n%    Output, complex B(N), the solution.\n%\n\n%\n%  Check for 1 x 1 case.\n%\n  if ( n == 1 )\n    b(1) = b(1) / d(1);\n    return\n  end\n\n  nm1 = n - 1;\n  nm1d2 = floor ( ( n - 1 ) / 2 );\n\n  if ( n ~= 2 )\n\n    kbm1 = n - 1;\n%\n%  Zero top half of subdiagonal and bottom half of superdiagonal.\n%\n    for k = 1 : nm1d2\n      t1 = conj ( e(k) ) / d(k);\n      d(k+1) = d(k+1) - t1 * e(k);\n      b(k+1) = b(k+1) - t1 * b(k);\n      t2 = e(kbm1) / d(kbm1+1);\n      d(kbm1) = d(kbm1) - t2 * conj ( e(kbm1) );\n      b(kbm1) = b(kbm1) - t2 * b(kbm1+1);\n      kbm1 = kbm1 - 1;\n    end\n\n  end\n\n  kp1 = nm1d2 + 1;\n%\n%  Clean up for possible 2 x 2 block at center.\n%\n  if ( mod ( n, 2 ) == 0 )\n    t1 = conj ( e(kp1) ) / d(kp1);\n    d(kp1+1) = d(kp1+1) - t1 * e(kp1);\n    b(kp1+1) = b(kp1+1) - t1 * b(kp1);\n    kp1 = kp1 + 1;\n  end\n%\n%  Back solve starting at the center, going towards the top and bottom.\n%\n  b(kp1) = b(kp1) / d(kp1);\n\n  if ( n ~= 2 )\n\n    k = kp1 - 1;\n    ke = kp1 + nm1d2 - 1;\n\n    for kf = kp1 : ke\n      b(k) = ( b(k) - e(k) * b(k+1) ) / d(k);\n      b(kf+1) = ( b(kf+1) - conj ( e(kf) ) * b(kf) ) / d(kf+1);\n      k = k - 1;\n    end\n\n  end\n\n  if ( mod ( n, 2 ) == 0 )\n    b(1) = ( b(1) - e(1) * b(2) ) / d(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/linpack_c/cptsl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.58857202625787}}
{"text": "%FindInInterval - Find values that fall in a given interval.\n%\n%  The equivalent Matlab code is trivial\n%\n%      i = find(values(:,1)>=interval(1)&values(:,1)<=interval(2));\n%      indices = [i(1),i(end)];\n%\n%  but becomes extremely slow when dealing with very large lists.\n%  This function can dramatically speed up things whenever one needs\n%  to repeatedly find values in a long list of intervals.\n%\n%  USAGE\n%\n%    indices = FindInInterval(values,interval,from)\n%\n%    values         values to test, sorted in ascending order\n%    interval       [start,stop] pair\n%    from           optional initial index (see example below)\n%\n%  OUTPUT\n%\n%    indices        indices of the first and last values that fall\n%                   in the interval\n%\n%  EXAMPLE\n%\n%    This code assumes that the variable 'interval' contains a list\n%    of non-overlapping intervals sorted in ascending order,\n%    i.e. interval(i+1,1) >= interval(i,2).\n%\n%    previous = 1;\n%    for i = 1:n,\n%       % Find values within this window\n%       j = FindInInterval(values,interval(i,:),previous);\n%       previous = j(1);\n%       % ... do whatever computations here ...\n%    end\n%\n%  SEE\n%\n%    See also ConsolidateIntervals, SubtractIntervals, ExcludeIntervals,\n%    InIntervals, Restrict, CountInIntervals, PlotIntervals.\n\n% Copyright (C) 2004-2010 by Micha\u00ebl Zugaro\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/FMAToolbox/General/FindInInterval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.5885720164828192}}
{"text": "function boxOut = bbox_scale2(boxIn,scale,szOut)\n% Copyright (C) 2016 Hakan Bilen.\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 isempty(boxIn), boxOut = []; return; end\n\nboxOut = scale * (boxIn-1) + 1;\n\nboxOut = [max(1,round(boxOut(:,1))),...\n  max(1,round(boxOut(:,2))),...\n  min(szOut(1),round(boxOut(:,3))),...\n  min(szOut(2),round(boxOut(:,4)))];\n", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/libs/matconvnet/examples/fast_rcnn/bbox_functions/bbox_scale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5884532113495278}}
{"text": "function c = tapas_hgf_jget_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the Hierarchical Gaussian Filter (HGF) model for the jumping\n% Gaussian estimation task (JGET).\n%\n% The HGF is the model introduced in \n%\n% Mathys C, Daunizeau J, Friston, KJ, and Stephan KE. (2011). A Bayesian foundation\n% for individual learning under uncertainty. Frontiers in Human Neuroscience, 5:39.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% The HGF configuration consists of the priors of parameters and initial values. All priors are\n% Gaussian in the space where the quantity they refer to is estimated. They are specified by their\n% sufficient statistics: mean and variance (NOT standard deviation).\n% \n% Quantities are estimated in their native space if they are unbounded (e.g., the omegas). They are\n% estimated in log-space if they have a natural lower bound at zero (e.g., the sigmas).\n% \n% Parameters can be fixed (i.e., set to a fixed value) by setting the variance of their prior to\n% zero. Aside from being useful for model comparison, the need for this arises whenever the scale\n% and origin at the j-th level are arbitrary. This is the case if the observation model does not\n% contain the representations mu_j and sigma_j. A choice of scale and origin is then implied by\n% fixing the initial value mu_j_0 of mu_j and either kappa_j-1 or omega_j-1.\n%\n% Fitted trajectories can be plotted by using the command\n%\n% >> tapas_hgf_jget_plotTraj(est)\n% \n% where est is the stucture returned by fitModel. This structure contains the estimated\n% perceptual parameters in est.p_prc and the estimated trajectories of the agent's\n% representations (cf. Mathys et al., 2011). Their meanings are:\n%              \n%         est.p_prc.mux_0      row vector of initial values of mu_x (in ascending order of levels)\n%         est.p_prc.sax_0      row vector of initial values of sigma_x (in ascending order of levels)\n%         est.p_prc.mua_0      row vector of initial values of mu_alpha (in ascending order of levels)\n%         est.p_prc.saa_0      row vector of initial values of sigma_alpha (in ascending order of levels)\n%         est.p_prc.kau        kappa_u\n%         est.p_prc.omu        omega_u\n%         est.p_prc.kax        row vector of kappa_x (in ascending order of levels)\n%         est.p_prc.omx        row vector of omega_x (in ascending order of levels)\n%         est.p_prc.kaa        row vector of kappa_alpha (in ascending order of levels)\n%         est.p_prc.oma        row vector of omega_alpha (in ascending order of levels)\n%\n%         est.traj.mux         mux (rows: trials, columns: levels)\n%         est.traj.sax         sigma_x (rows: trials, columns: levels)\n%         est.traj.muxhat      prediction of mu_x (rows: trials, columns: levels)\n%         est.traj.saxhat      precisions of predictions of x (rows: trials, columns: levels)\n%         est.traj.wx          weighting factors for x (rows: trials, columns: levels)\n%         est.traj.dax         volatility prediction errors in x (rows: trials, columns: levels)\n%         est.traj.mua         mu_alpha (rows: trials, columns: levels)\n%         est.traj.saa         sigma_alpha (rows: trials, columns: levels)\n%         est.traj.muahat      prediction of mu_alpha (rows: trials, columns: levels)\n%         est.traj.saahat      precisions of predictions of alpha (rows: trials, columns: levels)\n%         est.traj.wa          weighting factors for alpha (rows: trials, columns: levels)\n%         est.traj.daa         volatility prediction errors in alpha (rows: trials, columns: levels)\n%         est.traj.dau         input prediction error\n%\n%\n%\n% Tips:\n% - If you get an error saying that the prior means are in a region where model assumptions are\n%   violated, lower the prior means of the omegas, starting with the highest level and proceeding\n%   downwards.\n%\n% - Alternatives are lowering the prior means of the kappas, if they are not fixed, or adjusting\n%   the values of the kappas or omegas, if any of them are fixed.\n%\n% - If the log-model evidence cannot be calculated because the Hessian poses problems, look at\n%   est.optim.H and fix the parameters that lead to NaNs.\n%\n% - Your guide to all these adjustments is the log-model evidence (LME). Whenever the LME increases\n%   by at least 3 across datasets, the adjustment was a good idea and can be justified by just this:\n%   the LME increased, so you had a better model.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013-2014 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or <http://www.gnu.org/licenses/>.\n\n\n% Config structure\nc = struct;\n\n% Model name\nc.model = 'hgf_jget';\n\n% Number of levels (minimum: 2)\nc.n_levels = 2;\n\n% Sufficient statistics of Gaussian parameter priors\n\n% PLACEHOLDER VALUES\n% It is often convenient to set some priors to values\n% derived from the inputs. This can be achieved by\n% using placeholder values. The available placeholders\n% are:\n%\n% 99991   Value of the first input\n%         Usually a good choice for mux_0mu(1)\n% 99992   Variance of the first 20 inputs\n%         Usually a good choice for mux_0sa(1)\n% 99993   Log-variance of the first 20 inputs\n%         Usually a good choice for logsax_0mu(1) and mua_0mu(1)\n% 99994   Log-variance of the first 20 inputs minus two\n%         Usually a good choice for omxmu(1)\n\n% Initial mus and sigmas\n% Format: row vectors of length n_levels\n% For all but the first level, this is usually best\n% kept fixed to 1 (determines origin on x_i-scale).\nc.mux_0mu = [99991, 1];\nc.mux_0sa = [    0, 0];\n\nc.logsax_0mu = [log(3), log(0.1)];\nc.logsax_0sa = [      0,       0];\n\nc.mua_0mu = [log(1), 1];\nc.mua_0sa = [   0.1, 0];\n\nc.logsaa_0mu = [log(3), log(0.1)];\nc.logsaa_0sa = [      0,       0];\n\n% Kappas\n% Format: row vector of length n_levels-1 (except kappa_u: scalar)\n% This should be fixed (preferably to 1) if the observation model\n% does not use mu_i+1 (kappa then determines the scaling of x_i+1).\nc.logkaumu = log(1);\nc.logkausa = 0;\n\nc.logkaxmu = [log(1)];\nc.logkaxsa = [     0];\n\nc.logkaamu = [log(1)];\nc.logkaasa = [     0];\n\n% Omegas\n% Format: row vector of length n_levels (except omega_u: scalar)\nc.omumu = 0;\nc.omusa = 0;\n\nc.omxmu = [  0,  -7];\nc.omxsa = [5^2,   1];\n\nc.omamu = [  0,  -7];\nc.omasa = [5^2,   1];\n\n% Gather prior settings in vectors\nc.priormus = [\n    c.mux_0mu,...\n    c.logsax_0mu,...\n    c.mua_0mu,...\n    c.logsaa_0mu,...\n    c.logkaumu,...\n    c.logkaxmu,...\n    c.logkaamu,...\n    c.omumu,...\n    c.omxmu,...\n    c.omamu,...\n         ];\n\nc.priorsas = [\n    c.mux_0sa,...\n    c.logsax_0sa,...\n    c.mua_0sa,...\n    c.logsaa_0sa,...\n    c.logkausa,...\n    c.logkaxsa,...\n    c.logkaasa,...\n    c.omusa,...\n    c.omxsa,...\n    c.omasa,...\n         ];\n\n% Check whether we have the right number of priors\nexpectedLength = 8*c.n_levels;\nif length([c.priormus, c.priorsas]) ~= 2*expectedLength;\n    error('tapas:hgf:PriorDefNotMatchingLevels', 'Prior definition does not match number of levels.')\nend\n\n% Model function handle\nc.prc_fun = @tapas_hgf_jget;\n\n% Handle to function that transforms perceptual parameters to their native space\n% from the space they are estimated in\nc.transp_prc_fun = @tapas_hgf_jget_transp;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_jget_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5884532066113111}}
{"text": "function [ bboxes ] = scale_bboxes( bboxes, scale_factor )\n% scale_bboxes: it scales the set bounding boxes bboxes by the scale_factor\n% factor.\n%\n% INPUT:\n% 1) bboxes: a N x 4 array with the input bounding box coordinates in the \n% form of [x0,y0,x1,y1] (where (x0,y0) is the top-left corner and (x1,y1)  \n% the bottom left corner)\n% 2) scale_factor: a 1 x 1 or 2 x 1 array with the scaling factor of the\n% bounding boxes. If scale_factor is a 1 x 1 array then the same scaling\n% factor will be applied on both the x and y axis. If scale_factor is a\n% 2 x 1 (or 1 x 2) array then the bounding boxes will be scaled across the\n% y dimension by scale_factor(1) and across the x dimension by\n% scale_factor(2).\n% \n% OUTPUT:\n% 1) bboxes: a N x 4 array with the output bounding box coordinates in the \n% form of [x0,y0,x1,y1] (where (x0,y0) is the top-left corner and (x1,y1)  \n% the bottom left corners.\n%\n% This file is part of the code that implements the following paper:\n% Title      : \"LocNet: Improving Localization Accuracy for Object Detection\"\n% Authors    : Spyros Gidaris, Nikos Komodakis\n% Institution: Universite Paris Est, Ecole des Ponts ParisTech\n% ArXiv link : http://arxiv.org/abs/1511.07763\n% code       : https://github.com/gidariss/LocNet\n%\n% AUTORIGHTS\n% --------------------------------------------------------\n% Copyright (c) 2016 Spyros Gidaris\n% \n% Title     : \"LocNet: Improving Localization Accuracy for Object Detection\"\n% ArXiv link: http://arxiv.org/abs/1511.07763\n% Licensed under The MIT License [see LICENSE for details]\n% ---------------------------------------------------------\n\nif numel(scale_factor) == 1, scale_factor(2) = scale_factor(1); end\nassert(numel(scale_factor) == 2);\nscale_factor = single(scale_factor);\n\n\nbboxes_center      = [(bboxes(:,1)+bboxes(:,3)), (bboxes(:,2)+bboxes(:,4))]/2;\nbboxes_width_half  = (bboxes(:,3) - bboxes(:,1))/2;\nbboxes_width_half  = bboxes_width_half * scale_factor(2);\n\nbboxes_height_half = (bboxes(:,4) - bboxes(:,2))/2;\nbboxes_height_half = bboxes_height_half * scale_factor(1);\n\nbboxes = round([bboxes_center(:,1) - bboxes_width_half, ...\n                bboxes_center(:,2) - bboxes_height_half, ...\n                bboxes_center(:,1) + bboxes_width_half, ...\n                bboxes_center(:,2) + bboxes_height_half]);\nend", "meta": {"author": "gidariss", "repo": "LocNet", "sha": "a4678b87d9e63dcea07d9afd978d1223174d8be3", "save_path": "github-repos/MATLAB/gidariss-LocNet", "path": "github-repos/MATLAB/gidariss-LocNet/LocNet-a4678b87d9e63dcea07d9afd978d1223174d8be3/code/utils/scale_bboxes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5884532061327167}}
{"text": "function m_demo(index)\n% M_DEMO  Demonstration program showing various maps in M_Map package\n%         Dig into this to look for examples of things you want to do.\n%\n%         M_DEMO runs all the demos.\n%         M_DEMO(NUM) runs examples NUM (1<=NUM<=10), pausing between examples.\n%\n%         Some demos may require you to install GSHHS or TerrainBase datafiles\n%         (see documentation)\n\n% Rich Pawlowicz (rich@ocgy.ubc.ca) 7/May/1997\n% (thanks to Art Newhall for putting these examples into an m-file,\n% and the Chuck Denham for enhancing the interface)\n%\n% 27/July/98 - more examples.\n% 17/Aug/98     \"\n% 15/Nov/98  - another example, better interface.\n% 23/Dec/98  - another example.\n\n%\n% This software is provided \"as is\" without warranty of any kind. But\n% it's mine, so you can't sell it.\n\n\nN_EXAMPLES=11;\n\nif nargin==0\n index=1:N_EXAMPLES;\nend\n\nfor i=index\n\nclf;\nswitch i\n\n  case 1\n\n    m_proj('ortho','lat',48','long',-123');\n    m_coast('patch','r');\n    m_grid('linest','-','xticklabels',[],'yticklabels',[],'ytick',[-80:40:80]);\n    xlabel('Orthographic Projection','visible','on');\n\n  case 2\n\n    m_proj('lambert','long',[-160 -40],'lat',[30 80]);\n    m_coast('patch',[1 .85 .7]);\n    m_elev('contourf',[500:500:6000]);\n    m_grid('box','fancy','tickdir','in');\n    colormap(flipud(copper));\n    xlabel('Conic Projection of North America with elevations','visible','on');\n\n  case 3\n\n    m_proj('stereographic','lat',90,'long',30,'radius',25);\n    m_elev('contour',[-3500:1000:-500],'edgecolor','b');\n    m_grid('xtick',12,'tickdir','out','ytick',[70 80],'linest','-');\n    m_coast('patch',[.7 .7 .7],'edgecolor','r');\n    xlabel('Polar Stereographic Projection with bathymetry','visible','on');\n\n  case 4\n\n    subplot(211);\n    Slongs=[-100 0;-75 25;-5 45; 25 145;45 100;145 295;100 290];\n    Slats= [  8 80;-80  8; 8 80;-80   8; 8  80;-80   0;  0  80];\n    for l=1:7\n     m_proj('sinusoidal','long',Slongs(l,:),'lat',Slats(l,:));\n     m_grid('fontsize',6,'xticklabels',[],'xtick',[-180:30:360],...\n            'ytick',[-80:20:80],'yticklabels',[],'linest','-','color',[.9 .9 .9]);\n     m_coast('patch','g');\n    end\n    xlabel('Interrupted Sinusoidal Projection of World Oceans');\n    % In order to see all the maps we must undo the axis limits set by m_grid calls:\n    set(gca,'xlimmode','auto','ylimmode','auto');\n\n    subplot(212);\n    Slongs=[-100 43;-75 20; 20 145;43 100;145 295;100 295];\n    Slats= [  0  90;-90  0;-90   0; 0  90;-90   0;  0  90];\n    for l=1:6\n     m_proj('mollweide','long',Slongs(l,:),'lat',Slats(l,:));\n     m_grid('fontsize',6,'xticklabels',[],'xtick',[-180:30:360],...\n            'ytick',[-80:20:80],'yticklabels',[],'linest','-','color','k');\n     m_coast('patch',[.6 .6 .6]);\n    end\n    xlabel('Interrupted Mollweide Projection of World Oceans');\n    set(gca,'xlimmode','auto','ylimmode','auto');\n\n  case 5\n\n    %% Nice looking data\n    [lon,lat]=meshgrid([-136:2:-114],[36:2:54]);\n    u=sin(lat/6);\n    v=sin(lon/6);\n\n    m_proj('oblique','lat',[56 30],'lon',[-132 -120],'aspect',.8);\n\n    subplot(121);\n    m_coast('patch',[.9 .9 .9],'edgecolor','none');\n    m_grid('tickdir','out','yaxislocation','right',...\n\t   'xaxislocation','top','xlabeldir','end','ticklen',.02);\n    hold on;\n    m_quiver(lon,lat,u,v);\n    xlabel('Simulated surface winds');\n\n    subplot(122);\n    m_coast('patch',[.9 .9 .9],'edgecolor','none');\n    m_grid('tickdir','out','yticklabels',[],...\n\t   'xticklabels',[],'linestyle','none','ticklen',.02);\n    hold on;\n    [cs,h]=m_contour(lon,lat,sqrt(u.*u+v.*v));\n    clabel(cs,h,'fontsize',8);\n    xlabel('Simulated something else');\n\n  case 6\n\n    % Plot a circular orbit\n    lon=[-180:180];\n    lat=atan(tan(60*pi/180)*cos((lon-30)*pi/180))*180/pi;\n\n    m_proj('miller','lat',82);\n    m_coast('color',[0 .6 0]);\n    m_line(lon,lat,'linewi',3,'color','r');\n    m_grid('linest','none','box','fancy','tickdir','out');\n\n\n  case 7\n\n    m_proj('lambert','lon',[-10 20],'lat',[33 48]);\n    m_tbase('contourf');\n    m_grid('linestyle','none','tickdir','out','linewidth',3);\n    colormap(jet);\n\n  case 8\n\n    m_vec;\n\n  case 9\n\n    % Example showing the default coastline and all of the GSHHS coastlines.\n\n    axes('position',[.35 .6 .37 .37]);\n    m_proj('albers equal-area','lat',[40 60],'long',[-90 -50],'rect','on');\n    m_coast('patch',[0 1 0]);\n    m_grid('linest','none','linewidth',2,'tickdir','out','xaxisloc','top','yaxisloc','right');\n    m_text(-69,41,'Standard coastline','color','r','fontweight','bold');\n\n    axes('position',[.09 .5 .37 .37]);\n    m_proj('albers equal-area','lat',[40 54],'long',[-80 -55],'rect','on');\n    m_gshhs_c('patch',[.2 .8 .2]);\n    m_grid('linest','none','linewidth',2,'tickdir','out','xaxisloc','top');\n    m_text(-80,52.5,'GSHHS\\_C (crude)','color','m','fontweight','bold','fontsize',14);\n\n    axes('position',[.13 .2 .37 .37]);\n    m_proj('albers equal-area','lat',[43 48],'long',[-67 -59],'rect','on');\n    m_gshhs_l('patch',[.4 .6 .4]);\n    m_grid('linest','none','linewidth',2,'tickdir','out');\n    m_text(-66.5,43.5,'GSHHS\\_L (low)','color','m','fontweight','bold','fontsize',14);\n\n    axes('position',[.35 .05 .37 .37]);\n    m_proj('albers equal-area','lat',[45.8 47.2],'long',[-64.5 -62],'rect','on');\n    m_gshhs_i('patch',[.5 .6 .5]);\n    m_grid('linest','none','linewidth',2,'tickdir','out','yaxisloc','right');\n    m_text(-64.4,45.9,'GSHHS\\_I (intermediate)','color','m','fontweight','bold','fontsize',14);\n\n    axes('position',[.55 .23 .37 .37]);\n    m_proj('albers equal-area','lat',[46.375 46.6],'long',[-64.2 -63.7],'rect','on');\n    m_gshhs_h('patch',[.6 .6 .6]);\n    m_grid('linest','none','linewidth',2,'tickdir','out','xaxisloc','top','yaxisloc','right');\n    m_text(-64.18,46.58,'GSHHS\\_H (high)','color','m','fontweight','bold','fontsize',14);\n\n  case 10\n\n    % Example showing a trackline plot\n\n    clf\n    m_proj('UTM','long',[-72 -68],'lat',[40 44]);\n    m_gshhs_i('color','k');\n    m_grid('box','fancy','tickdir','in');\n\n    % fake up a trackline\n    lons=[-71:.1:-67];\n    lats=60*cos((lons+115)*pi/180);\n    dates=datenum(1997,10,23,15,1:41,zeros(1,41));\n\n    m_track(lons,lats,dates,'ticks',0,'times',4,'dates',8,...\n           'clip','off','color','r','orient','upright');\n\n  case 11\n\n    % example showing range rings\n\n    clf\n    m_proj('hammer','clong',170);\n    m_grid('xtick',[],'ytick',[],'linestyle','-');\n    m_coast('patch','g');\n    m_line(100.5,13.5,'marker','square','color','r');\n    m_range_ring(100.5,13.5,[1000:1000:15000],'color','b','linewi',2);\n    xlabel('1000km range rings from Bangkok');\n\n  end\n\n if i<length(index)\n   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n   disp('  hit return to continue');\n   pause\n   disp('        ...drawing');\n   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n end\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/zmap_deprecated/orphaned/m_map/m_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5884532018730935}}
{"text": "function plotMicArray(mic_dirs_deg, R)\n% PLOTMICARRAY plots the arrangement of the microphones in a spherical array\n%\n%   mic_dirs:   the directions of the microphones in [azi1 elev1; ...]\n%       convention\n%   R:          radius of the array\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% PLOTMICARRAY.M - 11/7/2013\n% Archontis Politis, archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nmic_dirs_rad = mic_dirs_deg*pi/180;\nNmic = size(mic_dirs_deg,1);\n\nhold on\n% set up unit sphere information\nnumSphereFaces = 20;\n[unitSphereX, unitSphereY, unitSphereZ] = sphere(numSphereFaces);\n% radius of each sphere\nspheresRadius = ones(Nmic,1)*0.05*R;\n%plot 3d axes\nline([0 2*R],[0 0], [0 0],'color','r');\ntext(2*R,0,0,'x','Color','r','FontSize',24);\nline([0 0],[0 2*R], [0 0],'color','g');\ntext(0,2*R,0,'y','Color','g','FontSize',24);\nline([0 0],[0 0], [0 2*R],'color','b');\ntext(0,0,2*R,'z','Color','b','FontSize',24);\n\nspheresX = R*cos(mic_dirs_rad(:,1)).*cos(mic_dirs_rad(:,2));\nspheresY = R*sin(mic_dirs_rad(:,1)).*cos(mic_dirs_rad(:,2));\nspheresZ = R*sin(mic_dirs_rad(:,2));\n% for each given sphere, shift the scaled unit sphere by the\n% location of the sphere and plot\nfor i=1:Nmic\n    sphereX = spheresX(i) + unitSphereX*spheresRadius(i);\n    sphereY = spheresY(i) + unitSphereY*spheresRadius(i);\n    sphereZ = spheresZ(i) + unitSphereZ*spheresRadius(i);\n    h = surf(sphereX, sphereY, sphereZ);\n    set(h, 'FaceColor','b', 'FaceLighting', 'gouraud')\n    \n    text(1.1*spheresX(i),1.1*spheresY(i),1.1*spheresZ(i), num2str(i),'color','w','FontSize',24)    \nend\nsphereX = unitSphereX*R;\nsphereY = unitSphereY*R;\nsphereZ = unitSphereZ*R;\nh = surf(sphereX, sphereY, sphereZ);\nset(h, 'FaceColor','c', 'FaceLighting', 'gouraud')\nlight('Position',[0 0 1],'Style','infinite');\nmaterial shiny\nhold off\naxis equal\ngrid on\nview(-30,15)\nset(gca,'visible','off')\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/plotMicArray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5884532004373108}}
{"text": "classdef testHomogenizationLaminateForAnisotropicTensors < ...\n         testShowingError\n    \n     \n     properties (Access = protected)\n         testName = 'HomogenizationLaminateForAnisotropicTensors';\n         tol = 1e-6;\n     end\n     \n     properties (Access = private)\n         stiffTensor\n         weakTensor\n         ChForIso\n         ChForAni\n         laminateDirection\n         theta\n     end\n     \n     methods (Access = public)\n         \n         function obj = testHomogenizationLaminateForAnisotropicTensors()\n             obj.init()\n             obj.computeHomogenizerForIsotropicMaterials()\n             obj.computeHomogenizerForAnisotropicMaterials()\n         end\n         \n     end\n     \n     \n     methods (Access = protected)\n         \n         function init(obj)\n             obj.createTensors()\n             obj.createLaminateDirection()\n             obj.theta = 0.8;\n         end\n         \n        function createLaminateDirection(obj)\n            d = [0 1 0];            \n            dir = Vector3D;\n            dir.setValue(d);\n            dir.normalize()\n            obj.laminateDirection = dir;\n        end\n         \n         function createTensors(obj)\n            E1 = 1;\n            E0 = 1e-3;\n            nu1 = 1/3;\n            nu0 = 1/3;\n            obj.stiffTensor = IsotropicConstitutiveTensor(E1,nu1);\n            obj.weakTensor  = IsotropicConstitutiveTensor(E0,nu0);\n         end\n         \n         function computeHomogenizerForIsotropicMaterials(obj)\n            C0 = obj.weakTensor;\n            C1 = obj.stiffTensor;\n            dir{1} = obj.laminateDirection;\n            m1 = 1;\n            SeqHomog = VoigtPlaneStressHomogHomogenizer(C0,C1,dir,m1,obj.theta);\n            obj.ChForIso  = SeqHomog.getPlaneStressHomogenizedTensor();\n         end\n         \n         function computeHomogenizerForAnisotropicMaterials(obj)\n            C0 = obj.weakTensor;\n            C1 = obj.stiffTensor;\n            dir = obj.laminateDirection;\n            Lam = AnisotropicLaminateHomogenizer(C0,C1,dir,obj.theta); \n            obj.ChForAni = Lam.getHomogenizedTensor();\n         end\n         \n         \n         function computeError(obj)\n             Ch4Iso = obj.ChForIso.getValue();\n             Ch4Ani = obj.ChForAni.getValue();\n             obj.error = norm(Ch4Iso - Ch4Ani);\n         end\n         \n     end\n     \nend\n\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/tests/Source/AmplificatorTests/testHomogenizationLaminateForAnisotropicTensors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5884531999587157}}
{"text": "function plot_histogram (samples, pd, x_label, x_title)\n% plot_histogram: plots histogram from samples (empirical PDF)  and \n% compares to inferred probability density function (reference PDF). It \n% also plots mean and median.\n%\n% INPUT\n%   samples: Nx1 samples.\n%   pd: probality distribution object from ProbabilityDistribution class.\n%   x_label: label for X axis (string).\n%   x_title: title for the figure (string).\n%\n% OUTPUT\n%   figure with histogram, reference PDF, mean and median.\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%   <http://www.gnu.org/licenses/>.\n%\n% Reference:\n%\n%\n% Version: 004\n% Date:    2021/03/02\n% Author:  Rodrigo Gonzalez <rodralez@frm.utn.edu.ar>\n% URL:     https://github.com/rodralez/navego`\n\nN = length(samples);\n\n%% REFERENCE PDF\n\nx = linspace(min(samples), max(samples), N );\nref_pdf = pdf(pd, x);\n\n%% STATISTIC ANALYSIS\n\nmu = mean(samples);\nmed = median(samples);\n\ni = -5;\nidx1 = [];\nidx2 = [];\n\nwhile (isempty(idx1) || isempty(idx2))\n    \n    EPS = 10^i;\n    idx1 = find( x >= mu - EPS   & x < mu + EPS );\n    idx2 = find( x >= med - EPS & x < med + EPS );\n    i = i + 1;    \nend\n\nif ( isempty(idx1) || isempty(idx2) )\n    error('plot_histogram: no match for mean or median')\nend\n\n% Middlepoints \nidx1 = idx1( ceil(end/2) );\nidx2 = idx2( ceil(end/2) );\n\n%% PLOT\n\nbins = 100;\nblue_new = [0 0.4470 0.7410];\norange_new = [0.8500 0.3250 0.0980];\n\nfigure\n\n% Plot histogram from dataquiq\nhistogram(samples, bins, 'Normalization', 'pdf', 'FaceColor', [.9 .9 .9]);\nhold on\n\n% Plot the reference pdf\np0 = plot(x, ref_pdf, '-',  'LineWidth', 2);\n\n% Plot lines\ny = ref_pdf (idx1);\nl1 = line( [mu, mu] , [0, y], 'Color', blue_new, 'LineWidth', 2, 'LineStyle','-.');\n\ny = ref_pdf (idx2);\nl2 = line( [med, med] , [0, y], 'Color', orange_new, 'LineWidth', 2, 'LineStyle','-.' );\n\nlegend([p0, l1, l2], 'Reference PDF', 'Mean', 'Median')\n\nxlabel(x_label);\n% ylabel('Probability density function (PDF)');\ntitle(x_title)\n\ngrid on\nhold off\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/plot/plot_histogram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5883899031220813}}
{"text": "classdef LSMOP8 < PROBLEM\n% <multi/many> <real> <large/none>\n% Large-scale benchmark MOP\n% nk --- 5 --- Number of subcomponents in each variable group\n\n%------------------------------- Reference --------------------------------\n% R. Cheng, Y. Jin, and M. Olhofer, Test problems for large-scale\n% multiobjective and many-objective optimization, IEEE Transactions on\n% Cybernetics, 2017, 47(12): 4108-4121.\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        nk = 5; % Number of subcomponents in each variable group\n        sublen;\t% Number of variables in each subcomponent\n        len;    % Cumulative sum of lengths of variable groups\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            % Parameter setting\n            obj.nk = obj.ParameterSet(5);\n            if isempty(obj.M); obj.M = 3; end\n            if isempty(obj.D); obj.D = 100*obj.M; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = [ones(1,obj.M-1),10.*ones(1,obj.D-obj.M+1)];\n            obj.encoding = ones(1,obj.D);\n            % Calculate the number of variables in each subcomponent\n            c = 3.8*0.1*(1-0.1);\n            for i = 1 : obj.M-1\n                c = [c,3.8.*c(end).*(1-c(end))];\n            end\n            obj.sublen = floor(c./sum(c).*(obj.D-obj.M+1)/obj.nk);\n            obj.len    = [0,cumsum(obj.sublen*obj.nk)];\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            [N,D] = size(PopDec);\n            M     = obj.M;\n            PopDec(:,M:D) = (1+repmat(cos((M:D)./D*pi/2),N,1)).*PopDec(:,M:D) - repmat(PopDec(:,1)*10,1,D-M+1);\n            G = zeros(N,M);\n            for i = 1 : 2 : M\n                for j = 1 : obj.nk\n                    G(:,i) = G(:,i) + Griewank(PopDec(:,obj.len(i)+M-1+(j-1)*obj.sublen(i)+1:obj.len(i)+M-1+j*obj.sublen(i)));\n                end\n            end\n            for i = 2 : 2 : M\n                for j = 1 : obj.nk\n                    G(:,i) = G(:,i) + Sphere(PopDec(:,obj.len(i)+M-1+(j-1)*obj.sublen(i)+1:obj.len(i)+M-1+j*obj.sublen(i)));\n                end\n            end\n            G      = G./repmat(obj.sublen,N,1)./obj.nk;\n            PopObj = (1+G+[G(:,2:end),zeros(N,1)]).*fliplr(cumprod([ones(N,1),cos(PopDec(:,1:M-1)*pi/2)],2)).*[ones(N,1),sin(PopDec(:,M-1:-1:1)*pi/2)];\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R = UniformPoint(N,obj.M);\n            R = R./repmat(sqrt(sum(R.^2,2)),1,obj.M);\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,10)';\n                R = {sin(a)*cos(a'),sin(a)*sin(a'),cos(a)*ones(size(a'))};\n            else\n                R = [];\n            end\n        end\n    end\nend\n\nfunction f = Griewank(x)\n    f = sum(x.^2,2)./4000 - prod(cos(x./repmat(sqrt(1:size(x,2)),size(x,1),1)),2) + 1;\nend\n\nfunction f = Sphere(x)\n    f = sum(x.^2,2);\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/LSMOP/LSMOP8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867825403176, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5883898974428879}}
{"text": "function e = trimSegment(s,imSize,mrg)\n\n% TRIMSEGMENT  Trim segment at image borders\n%   TRIMSEGMENT(S,IMSIZE) trims the segment S at the image borders\n%   specified by IMSIZE. S is a 4-vector containing the two segment's\n%   endpoints. IMSIZE is a 2-vector with the image dimensions in pixels,\n%   IMSIZE = [HSIZE,VSIZE]. The output segment has the same orientation as\n%   the input one.\n%\n%   TRIMSEGMENT(...,MRG) restricts the image size to be smaller in MRG\n%   pixels at its four borders.\n%\n%   See also PINHOLESEGMENT.\n\n%   (c) 2008-2009 Joan Sola @ LAAS-CNRS\n\n% input segment's endpoints\na = s(1:2);\nb = s(3:4);\n\n% image witdh and height\n[w,h] = split(imSize);\n\nif nargin < 3\n    insq = inSquare([a b],[0 w 0 h]);\nelse\n    insq = inSquare([a b],[0 w 0 h],mrg);\nend\n\nif all(insq) % both endpoints are in the image\n\n    e = s; % return the segment unchanged\n\nelse % at least one endpoint is out of the image\n\n    H = pp2hmgLin(a,b); % homogeneous line\n    L = [1; 0; 0];  % left image border\n    R = [1; 0;-w];  % right\n    T = [0; 1; 0];  % top\n    B = [0; 1;-h];  % bottom\n\n    % intersections of infinite line with infinite borders\n    HL = intersectHmgLin(H,L,1);\n    HR = intersectHmgLin(H,R,1);\n    HT = intersectHmgLin(H,T,1);\n    HB = intersectHmgLin(H,B,1);\n\n    % bring to image borders\n    i = 1;\n    if inInterval(HL(2),[0,h])\n        e(i:i+1,1) = HL;\n        i = 3;\n    end\n    if inInterval(HR(2),[0,h])\n        e(i:i+1,1) = HR;\n        i = 3;\n    end\n    if inInterval(HT(1),[0,w])\n        e(i:i+1,1) = HT;\n        i = 3;\n    end\n    if inInterval(HB(1),[0,w])\n        e(i:i+1,1) = HB;\n    end\n\n    if insq(1) % endpoint a is in the image\n\n        p = e(1:2);\n        q = e(3:4);\n\n        u = b - a;\n        v = p - a;\n        if any(u./v > 0)\n            e(1:2) = a;\n            e(3:4) = p;\n        else\n            e(1:2) = a;\n            e(3:4) = q;\n        end\n\n    elseif insq(2) % endpoint b is in the image\n\n        p = e(1:2);\n        q = e(3:4);\n\n        u = a - b;\n        v = p - b;\n        if any(u./v > 0)\n            e(1:2) = p;\n            e(3:4) = b;\n        else\n            e(1:2) = q;\n            e(3:4) = b;\n        end\n\n    else % no endpoint is inside the image\n\n        if i == 1 % no intersection with image borders\n            % Segment is not visible\n            e = [];\n\n        else\n            p = e(1:2);\n            q = e(3:4);\n\n            if i==3 && any((p-a)./(b-p) > 0)  % segment is visible\n                % check orientations\n\n                u = b - a;\n                v = q - p;\n                if any(u./v < 0)\n                    e = e([3 4 1 2]); % match orientations\n                end\n            else % segment is not visible\n                e = [];\n            end\n        end\n\n    end\nend\n\nreturn\n\n%% test\nimsize = [10 10];\ns{1}  = [1 2 3 4]';\ns{2}  = [-1 2 3 4]';\ns{3}  = [1 -2 3 4]';\ns{4}  = [1 2 -3 4]';\ns{5}  = [1 2 3 -4]';\ns{6}  = [1 2 3 11]';\ns{7}  = [1 2 11 4]';\ns{8}  = [1 11 3 4]';\ns{9}  = [11 2 3 4]';\ns{10} = [-1 -2 13 14]';\ns{11} = [13 14 -1 -2]';\n\nfor i=1:numel(s)\n    s{i}'\n    (trimSegment(s{i},imsize))'\nend\n\n%% test\nlmin = 10;\nmrg = 0;\nimSize = [640;480];\ncla\nlh = line('color','c','linewidth',3);\nyh = line('color','r','linestyle','--')\n\n%%\ns = randn(4,1)*600\n\nset(lh,'xdata',s([1,3]),'ydata',s([2,4]))\n\nsv = trimSegment(s,imSize)\n\nif isempty(sv)\n    set(yh,'xdata',[],'ydata',[])\nelse\n    set(yh,'xdata',sv([1,3]),'ydata',sv([2,4]))\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 <http://www.gnu.org/licenses/>.\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/trimSegment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5883898960443358}}
{"text": "function [y,nz] = ompdenoise1(params,msgdelta)\n%OMPDENOISE1 OMP denoising of 1-D signals.\n%  OMPDENOISE1 denoises a 1-dimensional signal using OMP denoising. The\n%  function syntax is identical to OMPDENOISE, but it runs significantly\n%  faster on 1-D signals. OMPDENOISE1 requires somewhat more memory than\n%  OMPDENOISE (approximately the size of the input signal), so if memory is\n%  limited, OMPDENOISE can be used instead.\n%\n%  See also OMPDENOISE.\n\n\n%  Ron Rubinstein\n%  Computer Science Department\n%  Technion, Haifa 32000 Israel\n%  ronrubin@cs\n%\n%  August 2009\n\n\n% parse input arguments %\n\nx = params.x(:);\nD = params.dict;\nblocksize = params.blocksize;\n\n\n% maxval %\nif (isfield(params,'maxval'))\n  maxval = params.maxval;\nelse\n  maxval = 1;\nend\n\n\n% gain %\nif (isfield(params,'gain'))\n  gain = params.gain;\nelse\n  gain = 1.15;\nend\n\n\n% maxatoms %\nif (isfield(params,'maxatoms'))\n  maxatoms = params.maxatoms;\nelse\n  maxatoms = floor(blocksize/2);\nend\n\n\n% stepsize %\nif (isfield(params,'stepsize'))\n  stepsize = params.stepsize;\nelse\n  stepsize = 1;\nend\nif (any(stepsize<1))\n  error('Invalid step size.');\nend\n\n\n% noise mode %\nif (isfield(params,'noisemode'))\n  switch lower(params.noisemode)\n    case 'psnr'\n      sigma = maxval / 10^(params.psnr/20);\n    case 'sigma'\n      sigma = params.sigma;\n    otherwise\n      error('Invalid noise mode specified');\n  end\nelseif (isfield(params,'sigma'))\n  sigma = params.sigma;\nelseif (isfield(params,'psnr'))\n  sigma = maxval / 10^(params.psnr/20);\nelse\n  error('Noise strength not specified');\nend\n\n\n% lambda %\nif (isfield(params,'lambda'))\n  lambda = params.lambda;\nelse\n  lambda = maxval/(10*sigma);\nend\n\n\n% msgdelta %\nif (nargin <2)\n  msgdelta = 5;\nend\nif (msgdelta<=0)\n  msgdelta = -1;\nend\n\n\nepsilon = sqrt(blocksize) * sigma * gain;   % target error for omp\n\n\nMEM_LOW = 1;\nMEM_NORMAL = 2;\nMEM_HIGH = 3;\n\nif (isfield(params,'memusage'))\n  switch lower(params.memusage)\n    case 'low'\n      memusage = MEM_LOW;\n    case 'normal'\n      memusage = MEM_NORMAL;\n    case 'high'\n      memusage = MEM_HIGH;\n    otherwise\n      error('Invalid memory usage mode');\n  end\nelse\n  memusage = MEM_NORMAL;\nend\n\n\n% compute G %\n\nG = [];\nif (memusage >= MEM_NORMAL)\n  G = D'*D;\nend\n\n\n% verify dictionary normalization %\n\nif (isempty(G))\n  atomnorms = sum(D.*D);\nelse\n  atomnorms = diag(G);\nend\nif (any(abs(atomnorms-1) > 1e-2))\n  error('Dictionary columns must be normalized to unit length');\nend\n\n\n% denoise the signal %\n\n\n% process the signal in batches to conserve memory\n% choose batchsize so im2colstep returns a matrix of approximately the same\n% size as the signal\nbatchsize = ceil(length(x)*stepsize/blocksize + blocksize);\n\ny = zeros(size(x));\nids = 1:min(batchsize,length(x));\nnz = 0;\n\nblocknum = floor((length(x)-blocksize)/stepsize) + 1;\nprocessedblocks = 0;\ntid = timerinit('ompdenoise', blocknum);\nwhile (length(ids)>=blocksize)\n\n  % extract the signal blocks\n  blocks = im2colstep(x(ids),[blocksize 1],[stepsize 1]);\n\n  % remove DC\n  [blocks, dc] = remove_dc(blocks,'columns');\n\n  % denoise the blocks\n  if (memusage == MEM_LOW)\n    gamma = omp2(D,blocks,[],epsilon,'maxatoms',maxatoms,'checkdict','off');\n  else\n    gamma = omp2(D'*blocks,sum(blocks.*blocks),G,epsilon,'maxatoms',maxatoms,'checkdict','off');\n  end\n  nz = nz + nnz(gamma);\n  cleanblocks = add_dc(D*gamma, dc, 'columns');\n\n  y(ids) = y(ids) + col2imstep(cleanblocks, [length(ids) 1], [blocksize 1], [stepsize 1]);\n  ids = ids + floor((batchsize-blocksize)/stepsize)*stepsize + stepsize;\n  if (ids(end)>length(x))\n    ids = ids(ids<=length(x));\n  end\n  \n  % display status\n  if (msgdelta>0)\n    processedblocks = processedblocks + size(blocks,2);\n    timereta(tid, processedblocks, msgdelta);\n  end\n\nend\n\nif (msgdelta>0)\n  timereta(tid, blocknum);\nend\n\n\ncnt = countcover(size(x),[blocksize 1],[stepsize 1]);\ny = (y+lambda*x)./(cnt + lambda);\ny = reshape(y,size(params.x));\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/ompdenoise1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7217432182679957, "lm_q1q2_score": 0.588388520501542}}
{"text": "function y = solveLinearSystem(mode,A,b,para);\n\nswitch mode,\n  case {'matlab','MATLAB'},\n    y = A\\b;\n%     file = createFileName('prefix','JL');\n%     save(file,'A','b');\n    \n  case 'MG', \n    para.MGlevel      = log2(para.m(1))+1;\n    para.MGcycle      = 1;\n    para.MGomega      = 0.5;   %% !!! 0.5 should be better\n    para.MGsmoother   = 'mfJacobi';\n    para.MGpresmooth  = 3;\n    para.MGpostsmooth = 1;\n    para.dim = length(para.Omega);\n    u = zeros(size(b));\n    [y,res,r] = mfvcycle(para,u,b,1e-12,para.MGlevel,(max(para.m)>32));\nend;\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/RetinotopyModelFit/Version10/solvers/solveLinearSystem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.588385579624619}}
{"text": "function [p] = eeg_linfit(p)\n\n% eeg_linfit - returns slope/intercept of linear fit\n%\n% USEAGE: [p] = eeg_linfit(p)\n%\n% p is the eeg_toolbox struct.  For this function, the fields\n% required are:\n%\n%   p.volt.data - voltage data matrix (Npoints,Nelec)\n%   p.volt.timeArray - voltage sample points (msec)\n%\n% Returns slope and intercept matrices (Npoints,Nelec)\n% for linear fit of each electrode into fields of p:\n%\n%   p.volt.fitslope\n%   p.volt.fitintercept\n%\n% The column vectors of slope/intercept hold constant \n% values.  So, the linear fit data can be generated by:\n% \n% y = p.volt.fitslope .* p.volt.timeArray + p.volt.fitintercept;\n% \n% Where necessary, the p.volt.timeArray is replicated\n% across columns for each electrode to enable this calculation\n% \n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:52 $\n\n% Licence:  GNU GPL, no implied or express warranties\n% History:  07/00, Darren.Weber_at_radiology.ucsf.edu\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% volt.timeArray is essentially a column vector, but\n% operations in the eeg_toolbox may replicate across N columns\ntime = p.volt.timeArray(:,1);\n\nslope = zeros(1,size(p.volt.data,2));\nintercept = slope;\n\nfor elec = 1:size(p.volt.data,2),\n    \n    y = polyfit(time,p.volt.data(:,elec),1);\n    slope(1,elec) = y(1);\n    intercept(1,elec) = y(2);\nend\n\n% make sure that volt.timeArray is same size as volt.data\nif ~isequal(size(p.volt.timeArray),size(p.volt.data)),\n    p.volt.timeArray = repmat(p.volt.timeArray(:,1),1,size(p.volt.data,2));\nend\n\np.volt.fitslope = repmat(slope,size(p.volt.data,1),1);\np.volt.fitintercept = repmat(intercept,size(p.volt.data,1),1);\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/eeg_linfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5883855646601829}}
{"text": "function [varargout]=patchPointDist(V,F,Vp,dL)\n\nmethodOpt='near-norm';\n\nswitch methodOpt\n    case 'near-norm'\n        \n        [Nn,Vn]=patchNormal(F,V); %Get face normals and normal vector origins\n        [Dn,indMin]=minDist(Vp,Vn); %Get distances to origins and find closest faces\n        \n        %Attempt to find orthogonal projection to closest face\n        N=Nn(indMin,:); %Order the normals\n        W=Vp-Vn(indMin,:);\n        Dm=(dot(N,W,2));\n        D=abs(Dm);        \n        Dp=Dm(:,ones(1,3)).*N;\n        Vpd=Vp-Dp;\n        \n        %Test if projection is valid\n        TR = triangulation(F,V);\n        B = cartesianToBarycentric(TR,indMin,Vpd);        \n        logicOutside=any(B<-dL,2);\n        \n        %Replace invalid projections with face centre points\n        D(logicOutside)=Dn(logicOutside); %Replace distances        \n        Dp(logicOutside,:)=Vp(logicOutside,:)-Vn(indMin(logicOutside),:); %Replace difference vectors         \n        \n    otherwise\n        error('Wrong method option chosen');\nend\n\nswitch nargout\n    case 1\n        varargout{1}=D;\n    case 2\n        varargout{1}=D;\n        varargout{2}=Dp;    \n    case 3\n        varargout{1}=D;\n        varargout{2}=Dp;\n        varargout{3}=logicOutside;\nend\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/patchPointDist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5883855566591534}}
{"text": "classdef prtClassMatchedSubspace < prtClass\n\n\n\n\n\n\n\n    properties (SetAccess=private)\n       \n        name = 'Matched Subspace'   \n        nameAbbreviation = 'MatchedSubspace'\n        isNativeMary = true;\n        \n    end\n    \n    properties\n        inferH1subspace = true;\n        inferH0subspace = false;\n        \n        nH1components = 2;\n        nH0components = 2;\n        \n        proj1\n        proj0\n    end\n    \n    methods\n        function self = prtClassKnn(varargin)\n            self = prtUtilAssignStringValuePairs(self,varargin{:});\n            self.verboseStorage = true;\n        end\n    end\n    \n    methods (Access=protected, Hidden = true)\n\n        function self = trainAction(self,ds)\n            \n            if self.inferH1subspace\n                ds1 = ds.retainClassesByInd(2);\n                x = ds1.X;\n                [u,s] = svds(x',self.nH1components);\n                p = u*(u'*u)^(-1/2)*u';\n            else\n                p = eye(ds.nFeatures);\n            end\n            self.proj1 = p;\n            \n            if self.inferH0subspace\n                ds0 = ds.retainClassesByInd(1);\n                x = ds0.X;\n                [u,s] = svds(x,self.nH0components);\n                p = u*(u'*u)^(-1/2)*u';\n            else\n                p = eye(ds.nFeatures);\n            end\n            self.proj0 = p;\n            \n        end\n        \n        function yOut = runAction(self,ds)\n            \n            x = ds.X;\n            h1 = diag(x*self.proj1*x');\n            h0 = diag(x*self.proj0*x');\n            yOut = ds;\n            %             yOut.X = log(h1)-log(h0);\n            h1 = abs(h1);\n            h0 = abs(h0);\n            yOut.X = h1./h0;\n            \n        end\n    end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/class/prtClassMatchedSubspace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5883855486581236}}
{"text": "function [out_im,status ] = open_bitfield_bmp( filename )\n% OPEN_BITFIELD_BMP open a bitfield compressed bitmap image.\n%\n%   IM = OPEN_BITFIELD_BMP( FILENAME ) opens a 16-bit bitmapped compressed file \n%   named FILENAME. The output is formatted as three planes of Red, Green \n%   and Blue data. \n% \n%   See also imread, imfinfo\n\n% Get information about the image\ninfo = imfinfo(filename);\n\n% if we have a bitfield compressed R-G-B bitmap image\nif ( strcmp(info.Format , 'bmp') && ...\n     strcmp(info.CompressionType , 'bitfields') &&  ...\n     (info.BitDepth == 16 || info.BitDepth == 32) )\n\n    % indicate the input bmp file is not of 8-bit\n    status = 0;\n \n    % Open the file for reading\n    fid = fopen(filename, 'r');\n        \n    % Extract relevvant image info \n    data_offset = info.ImageDataOffset;\n    width = info.Width;\n    height = info.Height;\n    \n    % Create space for output image\n    out_im = zeros(height, width, 3);\n    \n    % Seek to where the image data begins (i.e. skip the file header\n    fseek(fid, data_offset, 'bof');\n    \n    % Read in the image data and format it into a matrix\n    if (info.BitDepth == 16)\n        % compressed_image = (fread(fid, [width + 1, height] , 'uint16'))';\n        compressed_image = (fread(fid, [width, height] , 'uint16'))';\n    else\n        compressed_image = (fread(fid, [width, height] , 'uint32'))';\n    end\n\n    % Eliminate last column of junk data (scanline row terminators) in 16\n    % bit mode\n    if (info.BitDepth == 16)\n        compressed_image = compressed_image(:, 1:(width));\n    end;\n        \n    % Invert Row Order since it is flipped\n    new_image = flipud(compressed_image);\n    \n    % Extract color bitmasks to decompress\n    red_mask = info.RedMask;\n    blue_mask = info.BlueMask;\n    green_mask = info.GreenMask;\n \n    \n    % Extract color components and form output image\n    out_im(:,:,1) = (bitand(new_image, red_mask) / red_mask * 255);\n    out_im(:,:,2) = (bitand(new_image, green_mask) / green_mask * 255);\n    out_im(:,:,3) = (bitand(new_image, blue_mask) / blue_mask * 255);\n\n    % typecast\n    out_im = uint8(out_im);\n\n    % display image\n    %imshow(out_im);\n    \nelse\n\n    % indicate the input bmp file is 8-bit\n    status = 1;\n    \n    % general imread for all other cases\n    out_im = imread(filename);\n    %imshow(out_im);\n    \nend\n\n", "meta": {"author": "xialeiliu", "repo": "RankIQA", "sha": "22ca65cd0156b5b428cecd55ed939366fb64d2e5", "save_path": "github-repos/MATLAB/xialeiliu-RankIQA", "path": "github-repos/MATLAB/xialeiliu-RankIQA/RankIQA-22ca65cd0156b5b428cecd55ed939366fb64d2e5/data/rank_tid2013/open_bitfield_bmp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5883188304945648}}
{"text": "function Whitener = bst_whitener(NoiseCov, ChannelFile, DataTypes, ChannelFlag)\n% BST_WHITENER: Compute a whitener from a NoiseCov matrix\n%\n% USAGE:  Whitener = bst_whitener(NoiseCov);\n%         Whitener = bst_whitener(NoiseCov, ChannelFile, DataTypes, ChannelFlag);\n%         Whitener = bst_whitener(NoiseCov,     Channel, DataTypes, ChannelFlag);\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, 2009-2010\n\n% If channels definition is not provided\nif (nargin < 4)\n    % Use all channels\n    iChan = 1:length(NoiseCov);\nelse\n    % If channel file provided: load ChannelFile\n    if ischar(ChannelFile)\n        ChannelMat = in_bst_channel(ChannelFile, 'Channel');\n        Channel = ChannelMat.Channel;\n    % If Channel structure provided\n    elseif isstruct(ChannelFile)\n        Channel = ChannelFile;\n    end\n    % Get good channels\n    iChan = good_channel(Channel, ChannelFlag, DataTypes);\nend\n\n% Detect the rows with only zero values\niZeroRow = find(sum(NoiseCov .^ 2) == 0);\n% Remove those channels from list of valid channels\niChan = setdiff(iChan, iZeroRow);\n\n% Initialize output matrix\nWhitener = zeros(size(NoiseCov));\n% Decomposition\n[U,S] = svd(NoiseCov(iChan,iChan));\n% Check matrix rank\nm = length(iChan);\nr = sum(diag(S) > m * S(1) * eps('double'));\nif (r < m)\n    error(['You have deficient data. Please:' 10 10 ...\n           '1) Look for bad channels in your recordings' 10 ...\n           '2) Tag them bad channels in all your recordings' 10 ...\n           '3) Try automatic detection of flat channels: Right click > Good/bad channels > ...' 10 ...\n           '4) Recompute the noise covariance matrix' 10, ...\n           '5) Restart this proces']);\nend\n% Create whitener\nWhitener(iChan,iChan) = pinv(U * sqrt(S));\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/inverse/bst_whitener.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.588318814587048}}
{"text": "function [m] = pm2m(pm)\n% Convert length from picometers to meters.\n% Chad A. Greene 2012\nm = pm*1e-12;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/pm2m.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5883187998267316}}
{"text": "function sysmodel = SparseRegression(Y,Yp,U,dt, options_method, lambda)\n\nNstates = size(Y,1);\nNinputs = size(U,1);\n\n% Sparse regression\nswitch options_method.sparsify\n    case 'LASSO'\n        % using the l1 norm to promote sparsity\n        G = zeros(Nstates+Ninputs,Nstates);\n        for i = 1:Nstates\n            [G(:,i), FitInfo] = lasso([Y;U]',Yp(i,:)','Lambda',lambda); %,'Lambda',0.00000001\n            %     lassoPlot(G{i},FitInfo);\n        end\n    case 'ILSTH'\n        G = sparsifyDynamics([Y;U]',Yp',lambda,Nstates);\nend\n\nG = G';\nA = G(1:Nstates,1:Nstates);\nB = G(1:Nstates,Nstates+1:Nstates+Ninputs);\nC = eye(Nstates,Nstates);\nD = zeros(Nstates,1);\nsysmodel = ss(A,B,C,D,dt);\nend", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/utils/SparseRegression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5882897705981943}}
{"text": "clear all, close all\nn1=10; n2=5;                       % number of data points from each class n1/n2\nsc=1;                                  % change the scale of the initial problem\n\n% 1) draw data from two Gaussians\nS1 = eye(2); S2 = [1 0.95; 0.95 1];\nm1 = [0.75;  0]; m2 = [-0.75; 0];\nrandn('seed',17); rand('seed',17)\n% coordinates\nx1 = chol(S1)'*randn(2,n1)+repmat(m1,1,n1);\nx2 = chol(S2)'*randn(2,n2)+repmat(m2,1,n2);\nx1(:,5) = x1(:,2); x1(:,1) = x1(:,4); x2(:,1) = x2(:,2);  % rank deficiency in K\nxtr = [x1 x2]';\n% class labels\nytr = [repmat(-1,[1,n1]) repmat(1,[1,n2])]';\ntt = (-5:.3:5)*sc; [t1 t2] = meshgrid(tt,tt);\nx1 = x1*sc; x2=x2*sc; xtr=xtr*sc; m1=m1*sc; m2=m2*sc;\nt  = [t1(:) t2(:)];\nz1 = exp(-sum((t-repmat(m1',length(t),1))*inv(S1).*(t-repmat(m1',length(t),1)),2)/2);\nz2 = exp(-sum((t-repmat(m2',length(t),1))*inv(S2).*(t-repmat(m2',length(t),1)),2)/2);\nxte = t; clear t\nxtr(end,:)=[2.9,2.3]; ytr(end)=-1;                                       % modif\n\n% 2) set GP parameters\ncov = {@covSum,{@covSEiso,@covNoise}}; hyp.cov = [0; 2; -Inf];       % ell,sf,sn\nlik =  {'likLogistic'};  hyp.lik  = [];                  % likLogistic or likErf\nmn  = {'meanZero'};      hyp.mean = [];\ninf = 'infEP';\n\n% 3) predict using approximated inference\n[nlZ,dnlZ,post] = gp(hyp, inf, mn, cov, lik, xtr, ytr);\n[ymu,ys2,fmu,fs2,junk,post] = gp(hyp,inf,mn,cov,lik,xtr,post,xte);\n\n% 4) prediction using MCMC sampling\n% set MCMC parameters, see some more details in inf/infMCMC.m\n% We have two samplers implemented, namely\n%  hmc - Hybrid Monte Carlo, and\n%  ess - Elliptical Slice Sampling.\n% par.sampler = 'hmc'; par.Nsample = 20;\npar.sampler = 'ess'; par.Nais = 5; par.Nsample = 20; par.Nburnin = 20; par.Nskip = 2;\n\nhyp = gpminimize(hyp,@gp,-200,0,inf,mn,cov,lik,xtr,ytr);\ntic\n[posts,nlZs,dnlZs] = infMCMC(hyp,mn,cov,lik,xtr,ytr,par);\nposts\ntoc\n[ymus,ys2s,fmus,fs2s,junk,posts] = gp(hyp,@infMCMC,mn,cov,lik,xtr,posts,xte);\n\n% 5a) echo results\nfprintf('nlZ-EP=%f, nlZ-AIS=%f\\n', nlZ, nlZs)\nfprintf('acceptance rate (MCMC) = %1.2f%%\\n',100*posts.acceptance_rate_MCMC)\nfor r=1:length(posts.acceptance_rate_AIS)\n  fprintf('acceptance rate (AIS) = %1.2f%%\\n',100*posts.acceptance_rate_AIS(r))\nend\n% 5b) print results\nfigure\nsubplot(221)\n  plot([-12,12],[-12,12],'r'), hold on, plot(fmus,fmu,'k.'), title('\\mu_f')\n  xlabel('MCMC'), ylabel(inf)\nsubplot(222)\n  plot([0,10],[0,10],'r'), hold on, plot(sqrt(fs2s),sqrt(fs2),'k.')\n  title('\\sigma_f')\n  xlabel('MCMC'), ylabel(inf)\nsubplot(223)\n  plot([-1,1],[-1,1],'r'), hold on, plot(ymus,ymu,'k.'), title('\\mu_y')\n  xlabel('MCMC'), ylabel(inf)\nsubplot(224)\n  plot([0,1],[0,1],'r'), hold on, plot(sqrt(ys2s),sqrt(ys2),'k.')\n  title('\\sigma_y')\n  xlabel('MCMC'), ylabel(inf)", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/gpml-matlab-v3.6-2015-07-07/doc/usageSampling.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5882897647472176}}
{"text": "function blas2_test01 ( )\n\n%*****************************************************************************80\n%\n%% BLAS2_TEST01 tests DGEMV.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    11 February 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'BLAS2_TEST01\\n' );\n  fprintf ( 1, '  For a general matrix A,\\n' );\n  fprintf ( 1, '  DGEMV computes y := alpha * A * x + beta * y\\n' );\n  fprintf ( 1, '  or             y := alpha * A'' * x + beta * y.\\n' );\n%\n%  y = alpha * A * x + beta * y\n%\n  trans = 'N';\n  m = 5;\n  n = 4;\n  alpha = 2.0;\n  lda = m;\n  a = r8mat_test ( trans, lda, m, n );\n  x = zeros ( n, 1 );\n  for i = 1 : n\n    x(i) = i;\n  end\n  incx = 1;\n  beta = 3.0;\n  y = zeros ( m, 1 );\n  for i = 1 : m\n    y(i) = 10 * i;\n  end\n  incy = 1;\n\n  r8mat_print ( m, n, a, '  Matrix A:' );\n  r8vec_print ( n, x, '  Vector X:' );\n  r8vec_print ( m, y, '  Vector Y:' );\n\n  y = dgemv ( trans, m, n, alpha, a, lda, x, incx, beta, y, incy );\n\n  r8vec_print ( m, y, '  Result Y = alpha * A  * x + beta * y' );\n%\n%  y = alpha * A' * x + beta * y\n%\n  trans = 'T';\n  m = 5;\n  n = 4;\n  alpha = 2.0;\n  lda = m;\n  a = r8mat_test ( trans, lda, n, m );\n  x = zeros ( m, 1 );\n  for i = 1 : m\n    x(i) = i;\n  end\n  incx = 1;\n  beta = 3.0;\n  y = zeros ( n, 1 );\n  for i = 1 : n\n    y(i) = 10 * i;\n  end\n  incy = 1;\n\n  r8mat_print ( m, n, a, '  Matrix A:' );\n  r8vec_print ( m, x, '  Vector X:' );\n  r8vec_print ( n, y, '  Vector Y:' );\n\n  y = dgemv ( trans, m, n, alpha, a, lda, x, incx, beta, y, incy );\n\n  r8vec_print ( n, y, '  Result Y = alpha * A'' * x + beta * y' );\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/blas2/blas2_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.5882646200561874}}
{"text": "function T = sptoeplitz(col, row)\n%SPTOEPLITZ   Sparse Toeplitz matrix.\n%   SPTOEPLITZ(C, R) produces a sparse nonsymmetric Toeplitz matrix having\n%   C as its first column and R as its first row. Neither C nor R needs to\n%   be sparse. No full-size dense matrices are formed.\n%\n%   SPTOEPLITZ(R) is a sparse symmetric/Hermitian Toeplitz matrix.\n%\n%   Examples:\n%     sptoeplitz( real( (1i).^(0:8) ) )   % 9x9, 41 nonzeros\n%     sptoeplitz( [-2 1 zeros(1,9998)] ); % classic 2nd difference\n%\n% See also TOEPLITZ, SPDIAGS.\n\n% Based on SPTOEPLITZ.M on the Mathworks File Exchange, \n% Copyright (c) 2006 by Tobin Driscoll (tobin.driscoll@gmail.com).\n\n% Developer note: This is needed by multiplication operators.\n\n% This part is borrowed from built-in Toeplitz.\nif ( nargin < 2 ) % Symmetric case\n  col(1) = conj(col(1)); \n  row = col; \n  col = conj(col); \nelse\n  if ( col(1) ~= row(1) )\n    warning('MATLAB:sptoeplitz:DiagonalConflict',['First element of ' ...\n      'input column does not match first element of input row. ' ...\n      '\\n         Column wins diagonal conflict.'])\n  end\nend\n\n% Size of result.\nm = length(col(:));\nn = length(row(:));\n\n% Only use toeplitz if you have too... fairly slow. \nif ( (m < 2e3) && (n < 2e3) )\n    % Note: nnz(col) -- Number of nonzero elements in col\n    if ( nnz(col) == 1 && nnz(row) == 1 )\n        Ic = find(col);\n        Ir = find(row);\n        if ( Ic == 1 )\n            T = spdiags(col(Ic)*ones(m, 1), 0, m, n);\n        else\n            T = spdiags([col(Ic)*ones(m, 1) row(Ir)*ones(n , 1)], ...\n                [-Ic + 1, Ir - 1], m, n);\n        end\n    else\n        T = toeplitz(col, row);\n        T = sparse(T); \n    end\nelse\n    % Locate the nonzero diagonals.\n    [ic, jc, sc] = find(col(:));\n    row(1) = 0;  % not used\n    [ir, jr, sr] = find(row(:));\n\n    % Use spdiags for construction.\n    d = [ ir - 1; 1 - ic ];\n    B = repmat( [ sr; sc ].', min(m, n), 1 );\n    T = spdiags(B, d, m, 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/@coeffsDiscretization/sptoeplitz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.5882646162922923}}
{"text": "function bk = r4_besks ( xnu, x, nin )\n\n%*****************************************************************************80\n%\n%% R4_BESKS evaluates a sequence of K Bessel functions at X.\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 XNU, the order of the first function.\n%    |XNU| < 1.\n%\n%    Input, real X, the argument.\n%\n%    Input, integer NIN, the absolute value of NIN indicates\n%    the number of terms to compute.\n%    If NIN < 0, successive values of NU count DOWN from XNU.\n%    If NIN > 0, successive values of NU count UP from XNU.\n%\n%    Output, real BK(abs(NIN)), the K Bessel functions.\n%\n  persistent xmax\n\n  if ( isempty ( xmax ) )\n    xmax = - log ( r4_mach ( 1 ) );\n    xmax = xmax + 0.5 * log ( 3.14 * 0.5 / xmax );\n  end\n\n  bk = r4_beskes ( xnu, x, nin );\n\n  expxi = exp ( - x );\n  n = abs ( nin );\n\n  bk(1:n) = expxi * bk(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/fn/r4_besks.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.588264607494461}}
{"text": "function chebyshev_discrete_test ( )\n\n%*****************************************************************************80\n%\n%% CHEBYSHEV_DISCRETE_TEST tests CHEBYSHEV_DISCRETE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    18 March 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  OFFSET = 1;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CHEBYSHEV_DISCRETE_TEST:\\n' );\n  fprintf ( 1, '  CHEBYSHEV_DISCRETE evaluates discrete Chebyshev polynomials.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '       N      M         X        T(N,M,X)\\n' );\n\n  n = 5;\n  m = 5;\n\n  for j = 0 : 5\n\n    x = j / 2.0;\n\n    value = chebyshev_discrete ( n, m, x );\n\n    fprintf ( 1, '\\n' );\n\n    for i = 0 : n\n\n      fprintf ( 1, '  %8d  %8d  %8f  %14f\\n', i, m, x, value(i+OFFSET) );\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/polpak/chebyshev_discrete_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.5882530987053347}}
{"text": "function M = legendreMass(k)\n% Compute the mass matrix using legendre polinomials of order 'k' as a base\n% for our expansion.\n\nM = diag(2./(2*(0:k)+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/Legendre/legendreMass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5882490882181195}}
{"text": "%PRINCSE Compute principal stresses and strains.\n%\n%   [ SE_P ] = PRINCSE( SE_X, SE_Y, SE_Z, SE_XY, SE_YZ, SE_XZ, ICOMP ) Computes\n%   principal stresses and strains (for the ICOMP component, default 1). In two\n%   dimensions only inputs SE_X, SE_Y, SE_Z, SE_XY, and ICOMP are required.\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/post/princse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5882138455159495}}
{"text": "function c=comp_nonsepdgtreal_quinqux(f,g,a,M)\n%COMP_NONSEPDGTREAL_QUINQUX  Compute Non-separable Discrete Gabor transform\n%   Usage:  c=comp_nonsepdgtreal_quinqux(f,g,a,M);\n%\n%   This is a computational subroutine, do not call it directly.\n\n%   AUTHOR : Nicki Holighaus and Peter L. S\u00f8ndergaard\n%   TESTING: TEST_NONSEPDGT\n%   REFERENCE: REF_NONSEPDGT\n\nlt=[1 2];\n\nL=size(f,1);\nW=size(f,2);\nN=L/a;\nM2=floor(M/2)+1;\n\n% ----- algorithm starts here, split into sub-lattices ---------------\n\nc=zeros(M,N,W,assert_classname(f,g));\n\nmwin=comp_nonsepwin2multi(g,a,M,[1 2],L);\n\n% simple algorithm: split into sublattices\n\nfor ii=0:1\n    c(:,ii+1:2:end,:)=comp_dgt(f,mwin(:,ii+1),2*a,M,[0 1],0,0,0);\nend;\n\n% Phase factor correction \nE = zeros(1,N,assert_classname(f,g));\nfor win=0:1\n    for n=0:N/2-1\n        E(win+n*2+1) = exp(-2*pi*i*a*n*rem(win,2)/M);\n    end;\nend;\n\nc=bsxfun(@times,c(1:M2,:,:),E);\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_nonsepdgtreal_quinqux.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.833324611869563, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5881480395426782}}
{"text": "function [kPa] = ftH2O2kPa(ftH2O)\n% Convert pressure from feet of water column at 4 degrees to kilopascals\n% Chad Greene 2012\nkPa = ftH2O*2.98907;", "meta": {"author": "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/ftH2O2kPa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5881480395426781}}
{"text": "function overlayPlot(varargin)\n%IMAGEOVERLAY  Overlay two images\n%\n% DESCRIPTION:\n%       overlayPlot overlays two 2D images. The background is displayed\n%       using a grayscale map. The foreground is log compressed and\n%       thresholded to a particular dynamic range, and overlayed using an\n%       alpha value of 0.5.\n%\n%       Example:\n%           x = rand(128);\n%           y = peaks(128);\n%           overlayPlot(x, y, 30);\n%\n% USAGE:\n%       overlayPlot(bg, fg)\n%       overlayPlot(bg, fg, fg_dnr)\n%       overlayPlot(x, y, bg, fg, fg_dnr)\n%\n% INPUTS:\n%       x, y        - vectors describing the position of the pixels in the\n%                     image equivalent to image(x, y, c)\n%       bg          - background image\n%       fg          - foreground image\n%       fg_dbr      - dynamic range in dB of foreground image\n%\n% ABOUT:\n%       author      - Bradley Treeby\n%       date        - 17th October 2012\n%       last update - 4th June 2013\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 <http://www.gnu.org/licenses/>.\n\n% set the literals\nnum_colors = 128;\ntransparency = 0.5;\nfg_dnr = 30;\n\n% extract the inputs\nif nargin == 2 || nargin == 3\n    bg = varargin{1};\n    fg = varargin{2};\n    if nargin == 3\n        fg_dnr = varargin{3};\n    end\nelseif nargin == 5\n    x_vec = varargin{1};\n    y_vec = varargin{2};\n    bg = varargin{3};\n    fg = varargin{4};\n    fg_dnr = varargin{5};\nelse\n    error('incorrect number of inputs');\nend\n\n% scale the background image from 0 to num_colors\nbg = bg - min(bg(:));\nbg = round(num_colors*bg/max(bg(:)));\n\n% convert the background image to true color\nbg = ind2rgb(bg, gray(num_colors));\n\n% plot the background image\nif nargin == 5\n    image(x_vec, y_vec, bg);\nelse\n    image(bg);\nend\n\n% if a value for the dynamic range is given, log compress and threshold\nif fg_dnr\n    fg(fg <= 0) = 0;\n    fg = 20*log10(fg./max(fg(:)));\n    fg = fg + fg_dnr;\n    fg(fg <= 0) = 0;\nend\n\n% scale the background image from 0 to num_colors\nfg = fg - min(fg(:));\nfg = round(num_colors*fg/max(fg(:)));\n\n% compute the alpha channel\nalpha = transparency*ones(size(fg));\nalpha(fg == 0) = 0;\n\n% convert the background image to true color\nfg = ind2rgb(fg, jet(num_colors));\n\n% plot the foreground image and set the alpha channel\nhold on;\nif nargin == 5\n    fg_im = image(x_vec, y_vec, fg);\nelse\n    fg_im = image(fg);\nend\nset(fg_im, 'AlphaData', alpha);", "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/overlayPlot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.833324611869563, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.588148034385626}}
{"text": "% test for level set on meshes\n\npath(path, '../toolbox_graph_data/off/');\nif not(exist('name'))\nname = 'elephant-50kv';\nname = 'bunny';\nname = 'david50kf';\nname = 'hand';\nend\n\noptions.name = name;\n[vertex,face] = read_off([name '.off']);\n\nfunc = 'xaxis';\nfunc = 'eigen';\n\nswitch func\n    case 'xaxis'\n        F = rescale(vertex(1,:))';\n        tau = linspace(0.05,.95, 10);\n    case 'eigen'\n        options.symmetrize = 1;\n        options.normalize = 1;\n        disp('--> Computing Laplacian');\n        L = compute_mesh_laplacian(vertex,face,'conformal',options);\n        opts.disp = 0;\n        p = 150;\n        disp('--> Extracting Eigenvectors');\n        [U,D] = eigs(L,p, 'SM', opts);\n        D = diag(abs(D)); [D,I] = sort(D); U = U(:,I);\n        nb = 10; sel = round(linspace(10,p,nb));\n        F = U(:, sel);\n        tau = 0;\nend\n\nrep = 'results/levelsets-meshes/';\nif not(exist(rep))\n    mkdir(rep);\nend\n\ndisp('--> Displaying');\nfor it=1:size(F,2)\n    progressbar(it,size(F,2));\n    f = F(:,it);\n    options.niter_averaging = 3;\n    f = perform_mesh_smoothing(face, vertex, f, options);\n    % extract level set\n    [v1,v2] = compute_levelset_mesh(vertex,face,f,tau,options);\n\n    % display\n    lw = 3;\n    fw = perform_histogram_matching(f, linspace(0,1,length(f)));\n    options.face_vertex_color = fw;\n    clf;\n    hold on;\n    plot_mesh(vertex,face,options);\n    for i=1:size(v1,2)\n        h = plot3( [v1(1,i) v2(1,i)], [v1(2,i) v2(2,i)], [v1(3,i) v2(3,i)], 'k' );\n        set(h, 'LineWidth', lw);\n    end\n    hold off;\n    colormap jet(256);\n    saveas(gcf, [rep name '-' func '-' num2string_fixeddigit(it,2), '.png'], 'png');\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_graph/tests/test_levelset_mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5881480278566146}}
{"text": "function [Acc]=parameter_sensitivity_test_loocv(All_Feat,nSubj,label,meth_Net,lambda_lasso)\n% This function performs parameter sensitivity test using all the subject data with LOOCV, and\n% it is run across all the combination of parameters.\n% Input:\n%       All_Feat: the constructed brain network using one combination of parameter;\n%       nSubj: number of subjects;\n%       label: the label for each subject; e.g., -1 for normal controls and 1 for patients;\n%       lambda_lasso: lambda in the lasso feature selection;\n%         \n% Written by Zhen Zhou, zzstefan@email.unc.edu\n% IDEA lab, https://www.med.unc.edu/bric/ideagroup\n% Department of Radiology and BRIC, University of North Carolina at Chapel Hill\n\n\ne = 1:nSubj;\ncpred = zeros(nSubj,1);\nscore = zeros(nSubj,1);\n\n% LOOCV for testing\nfor i=1:nSubj\n    Tst_ind = i;\n    telabel = label(i);\n    Trn_ind = e;\n    Trn_ind(i) = [];\n    trlabel = label;\n    trlabel(i) = [];\n    \n\n    Feat = All_Feat;\n    trFe = Feat(Trn_ind,:);\n    teFe = Feat(Tst_ind,:);\n    \n    % Feature selection ag\n    if ~strcmpi(meth_Net,'dHOFC')\n        pval=0.05;  % generally use pval<0.05 as a threshold for feature selection\n        [~,p]=ttest2(trFe(trlabel==-1,:),trFe(trlabel==1,:));\n        trFe=trFe(:,p<pval);\n        teFe=teFe(:,p<pval);\n        \n        midw=lasso(trFe,trlabel,'Lambda',lambda_lasso);  % parameter lambda for sparsity\n        trFe=trFe(:,midw~=0);\n        teFe=teFe(:,midw~=0);\n    else\n        midw=lasso(trFe,trlabel,'Lambda',lambda_lasso);  % parameter lambda for sparsity\n        trFe=trFe(:,midw~=0);\n        teFe=teFe(:,midw~=0);\n    end\n    \n    % Feature normalization ag\n    Mtr=mean(trFe);\n    Str=std(trFe);\n    trFe=trFe-repmat(Mtr,size(trFe,1),1);\n    trFe=trFe./repmat(Str,size(trFe,1),1);\n    teFe=teFe-Mtr;\n    teFe=teFe./Str;\n    \n    % train SVM model ag\n    classmodel=svmtrain(trlabel,trFe,'-t 0 -c 1 -q'); % linear SVM (require LIBSVM toolbox)\n    % classify ag\n    [cpred(i),~,score(i)]=svmpredict(telabel,teFe,classmodel,'-q');\nend\n\nAcc=100*sum(cpred==label)/nSubj;\n%[AUC,SEN,SPE,F1]=perfeval(label,cpred,score);\n\n", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Function/AddedFuntions/parameter_sensitivity_test_loocv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.5881480226995625}}
{"text": "\nfunction vbrfa2011_artificial_experiment(seed)\n\nif nargin < 1\n  seed = 10;\nend\nrand('state', seed);\nrandn('state', seed);\n\n% Observations:\n% \n% - When increasing M, Laplace -> independent t\n%\n% - Variance of corruption makes no big difference between Laplace and\n% independent t\n\n% From Bishop, standard deviations 5,4,3,2,1,1,1,1,... :\n\nM = 10;\nN = 100;\nD = 4;\n\n% Covariance matrix singular values: \n\nR = orth(randn(M));\neig = ([D:-1:1,zeros(1,M-D)]).^2;\nCov = R*diag(eig)*R';\n% $$$ eig = (1+[D:-1:1,zeros(1,M-D)]).^2;\n% $$$ Cov = R*diag(eig-1)*R';\n\nmu = randn(M,1);\n\n% Noiseless data\nY = mvnrnd(mu, Cov, N)';\n\n% Noisy data\nYn = Y + 1*randn(M,N);\n\n% Corrupted data\nI = rand(M,N) < 0.02;\nYno = Yn + I.*unifrnd(-30,30,M,N);\n\n%\n% Construct the model\n%\n\nDh = M-1;\n\n% $$$ tsplot(Yno, 'k')\n% $$$ addtsplot(Y, 'b');\n% $$$ return\n\nfor model=1:4\n  \n  % It seems that (at least in some cases) it would be better to combine the\n  % isotropic noise with X instead W for better and more stable results..?\n\n  noise_iso = noise_module_isotropic(M, 1, ...\n                                     'init', struct('a_tau',1, ...\n                                                    'b_tau',1));\n\n  % ARD for W\n  W_module = factor_module_ard(Dh+1, M, ...\n                               'update_alpha', 1, ...\n                               'noise_module', noise_iso);\n\n  % IID for X\n  mu = [1; zeros(Dh,1)];\n  Cov = diag([1e-6; ones(Dh,1)]);\n  X_module = factor_module_iid(Dh+1, N, ...\n                               'prior', struct('mu', mu, ...\n                                               'CovX', Cov), ...\n                               'noise_module', []);\n                               \n\n  switch model\n\n   case 1 % GAUSSIAN\n    noise = noise_module_fixed(M, N, 1);\n    id = 'gaussian';\n\n   case 2 % MULTIVARIATE T\n    noise = noise_module_multivariate_t(M, N, ...\n                                        'update_nu', [1], ...\n                                        'init', struct('nu', 0.1));\n    id = 'multi-t';\n\n   case 3 % INDEPENDENT T\n    noise = noise_module_independent_t(M, N, ...\n                                       'update_nu', [1], ...\n                                       'nu', 'pooled', ...\n                                       'init', struct('nu', 0.1));\n    id = 'ind-t';\n\n   case 4 % LAPLACE\n    noise = noise_module_laplace(M, N);\n    id = 'laplace';\n    \n   otherwise\n    error('Unknown model requested')\n    \n  end\n\n  %\n  % Run the method\n  %\n\n  % General function call for running the method\n  Q = vbfa(Dh+1, ...\n           Yno, ...\n           W_module, ...\n           X_module, ...\n           noise, ...\n           'maxiter', 50, ...\n           'rotate', [1:10, 10:5:100], ...\n           'rotation_maxiter', 20, ...\n           'update_x', 1, ...\n           'update_w', 1, ...\n           'update_noise', 1);\n\n  Yh = Q.W'*Q.X;\n\n  rmse1_train(model) = rmse(Yh, Yno)\n  rmse2_test(model) = rmse(Yh(~I), Y(~I))\n  rmse3_outliers(model) = rmse(Yh(I), Y(I))\n\n% $$$   tsplot(Yno(1:10,:), 'k')\n% $$$   addtsplot(Y(1:10,:), 'b');\n% $$$   addtsplot(Yh(1:10,:), 'r');\nend\n\n\nrmse1_train\nrmse2_test\nrmse3_outliers\n\n%Q.W*diag(Q.rhow)*Q.W' + sum(Q.CovW,3)\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/publications/vbrfa2011/vbrfa2011_artificial_experiment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5880633626567822}}
{"text": "% A script for visualizing the orientations in the menpo data, allows to\n% see the distributions of the data\nclear\nload('../menpo_68_pts.mat');\naddpath('../../PDM_helpers');\n\nxs = all_pts(1:end/2,:);\nys = all_pts(end/2+1:end,:);\nnum_imgs = size(xs, 1);\n\nrots = zeros(3, num_imgs);\nerrs = zeros(1,num_imgs);\n\npdmLoc = ['../pdm_68_aligned_menpo.mat'];\n\nload(pdmLoc);\n\npdm = struct;\npdm.M = double(M);\npdm.E = double(E);\npdm.V = double(V);\nerrs_poss = [];\nfor i=1:num_imgs\n    \n    labels_curr = cat(2, xs(i,:)', ys(i,:)');\n    labels_curr(labels_curr==-1) = 0;\n\n    [ a, R, T, ~, l_params, err, shapeOrtho] = fit_PDM_ortho_proj_to_2D(pdm.M, pdm.E, pdm.V, labels_curr);\n    errs(i) = err/a;\n    rots(:,i) = Rot2Euler(R);\n    \nend\n\nhist(rots', 100);", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/model_training/pdm_generation/menpo_pdm/helpers/Analyze_orient_distribution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5880439287949263}}
{"text": "function pde = TorusTime(mum,mup,sigm,sigp,epsm,epsp,omega,x0,y0,z0,r1,r2)\n%% USAGE: polynomial solution for Poisson equation\n%  Last Modified: 02/21/2020 by Xu Zhang\n\n%% PDE Structure\npde = struct('intf',@intf,...\n    'f1',@f1,'f2',@f2,'f3',@f3,...\n    'fm1',@fm1,'fm2',@fm2,'fm3',@fm3,...\n    'fp1',@fp1,'fp2',@fp2,'fp3',@fp3,...\n    'Mu',@Mu,'Mum',@Mum,'Mup',@Mup,'one',@one,...\n    'Epslon',@Epslon,'Epslonm',@Epslonm,'Epslonp',@Epslonp,...\n    'Sig',@Sig,'Sigm',@Sigm,'Sigp',@Sigp);\n\npde.mum = mum;\npde.mup = mup;\npde.sigm = sigm;\npde.sigp = sigp;\npde.epsm = epsm;\npde.epsp = epsp;\n%% interface function\n    function u = intf(x,y,z)\n        u = (sqrt((x-x0).^2+(y-y0).^2)-r2).^2 + (z-z0).^2 - r1^2;\n    end\n\n%% exact solution\n\n%% right hand side function\n    function u = f1(x,y,z,t)\n        u = fm1(x,y,z,t);\n        id = intf(x,y,z) > 0;\n        u(id) = fp1(x(id),y(id),z(id),t);\n    end\n    function u = f2(x,y,z,t)\n        u = fm2(x,y,z,t);\n        id = intf(x,y,z) > 0;\n        u(id) = fp2(x(id),y(id),z(id),t);\n    end\n    function u = f3(x,y,z,t)\n        u = fm3(x,y,z,t);\n        id = intf(x,y,z) > 0;\n        u(id) = fp3(x(id),y(id),z(id),t);\n    end\n\n    function u = fm1(x,y,z,t)\n        u = -2*pi*omega*sin(myacos(x,y))*cos(2*pi*omega*t);\n    end\n    function u = fm2(x,y,z,t)\n        u = 2*pi*omega*cos(myacos(x,y))*cos(2*pi*omega*t);\n    end\n    function u = fm3(x,y,z,t)\n        u = zeros(size(x));\n    end\n    function u = fp1(x,y,z,t)\n        u = zeros(size(x));\n    end\n    function u = fp2(x,y,z,t)\n        u = zeros(size(x));\n    end\n    function u = fp3(x,y,z,t)\n        u = zeros(size(x));\n    end\n    function theta = myacos(x,y)        \n        theta = (2*pi*(1-sign(y))/2 + sign(y).*acos(x./sqrt(x.^2+y.^2))).*abs(sign(y))+...\n            (1-abs(sign(y))).*((1-x)/2*pi);       \n    end\n\n%% Diffusion coefficient function\n    function u = Mu(x,y,z)\n        u = Mum(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Mup(x(id),y(id),z(id));\n    end\n    function u = Mum(x,y,z)\n        u = mum^(-1)*ones(size(x));\n    end\n    function u = Mup(x,y,z)\n        u = mup^(-1)*ones(size(x));\n    end\n\n%% Mass coefficient function\n    function u = Epslon(x,y,z)\n        u = Epslonm(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Epslonp(x(id),y(id),z(id));\n    end\n    function u = Epslonm(x,y,z)\n        u = epsm*ones(size(x));\n    end\n    function u = Epslonp(x,y,z)\n        u = epsp*ones(size(x));\n    end\n    \n    function u = Sig(x,y,z)\n        u = Sigm(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Sigp(x(id),y(id),z(id));\n    end\n    function u = Sigm(x,y,z)\n        u = sigm*ones(size(x));\n    end\n    function u = Sigp(x,y,z)\n        u = sigp*ones(size(x));\n    end\n\n%% Other function\n    function u = one(x,y,z)\n        u = ones(size(x));\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/research/IVEM/ExampleFun/TorusTime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5880439171891301}}
{"text": "function rs = acf(s, len)\n\n%tstoolbox/@signal/acf\n%   Syntax:\n%     * acf(s, len)\n%\n%   Input arguments:\n%     * len -length of the fft (optional)\n%\n%   Autocorrelation function for real scalar signals, using fft (of length\n%   len). If len is ommited a default value is calculated. The maximum of\n%   the calculated length is 128.\n%\n% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt\n\nnarginchk(1,2);\n     \nif (ndim(s) > 1) | (~isreal(data(s)))\n\thelp(mfilename)\n\treturn\nend\n\nif (nargin < 2) \n\tif dlens(s,1) > 256\n\t\tlen = 128;\n\telse\n\t\tlen = nextpow2(dlens(s,1)/4);\n\tend\nend\n\nc = acf(s.core, len);\nrs = signal(c, s);\t% special constructor calling syntax for working routines\na = getaxis(s, 1); \ndl = delta(a);\na = setfirst(a, 0);\nrs = setaxis(rs, 1, a);\nrs = setyunit(rs, unit);\t\t% acf values are scalars without unit\nrs = addhistory(rs, 'Autocorrelation function');\nrs = setlabel(rs, 'Autocorrelation function');\nrs = addcommandlines(rs, 's = acf(s', len);\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/acf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5879061859110937}}
{"text": "function A = projection_precon_mnls(X, B, A)\n    \n    s = svd(B'*B);\n    L = max(s);\n    %eigen_values = eig(B'*B);\n    %L = max(eigen_values);\n    \n    grad = - X * B + A*(B' * B);\n    A = A - 1/L * grad / (B'*B);\n    A = max(A, 0); \nend\n\n\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/online/online_auxiliary/projection_precon_mnls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5878959343497664}}
{"text": "function params = get_params_value()\n% constant parameters\nparams.c = physconst('LightSpeed');% Speed of light in air (m/s)\nparams.fc = 77e9; % Center frequency (Hz)\nparams.lambda = params.c/params.fc;\nparams.Rx = 4;\nparams.Tx = 2;\n\n% configuration parameters\nparams.Fs = 4*10^6;\nparams.sweepSlope = 21.0017e12;\nparams.samples = 128;\nparams.loop = 255;\n\nparams.Tc = 120e-6; % us\nparams.fft_Rang = 134; % 134=>128\nparams.fft_Vel = 256;\nparams.fft_Ang = 128;\nparams.num_crop = 3;\nparams.max_value = 1e+04; % data WITH 1843\n\n% Creat grid table\nfreq_res = params.Fs/params.fft_Rang; % range_grid\nfreq_grid = (0:params.fft_Rang-1).'*freq_res;\nparams.rng_grid = freq_grid*params.c/params.sweepSlope/2; % d=frediff_grid*c/sweepSlope/2;\n\nw = linspace(-1,1,params.fft_Ang); % angle_grid\nparams.agl_grid = asin(w)*180/pi; % [-1,1]->[-pi/2,pi/2]\n\n% velocity_grid\ndop_grid = fftshiftfreqgrid(params.fft_Vel,1/params.Tc); % now fs is equal to 1/Tc\nparams.vel_grid = dop_grid*params.lambda/2;   % unit: m/s, v = lamda/4*[-fs,fs], dopgrid = [-fs/2,fs/2]\n\nend", "meta": {"author": "Xiangyu-Gao", "repo": "mmWave-radar-signal-processing-and-microDoppler-classification", "sha": "3d59968ed7059e96a8a5befe32ecb34e49f291bd", "save_path": "github-repos/MATLAB/Xiangyu-Gao-mmWave-radar-signal-processing-and-microDoppler-classification", "path": "github-repos/MATLAB/Xiangyu-Gao-mmWave-radar-signal-processing-and-microDoppler-classification/mmWave-radar-signal-processing-and-microDoppler-classification-3d59968ed7059e96a8a5befe32ecb34e49f291bd/config/get_params_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.587895928303293}}
{"text": "function max_pr = trace_fit_extreme(C,fr,t_int,fac)\n\nif nargin < 4 || isempty(fac); fac = 1; end\nif nargin < 3 || isempty(t_int); t_int = 0.25; end\nif nargin < 2 || isempty(fr); fr = 30; end\n\nNp = round(t_int*fr);\n[K,T] = size(C);\nbas = zeros(K,1);\nsn = zeros(K,1);\nfor i = 1:K\n    [~,density,xmesh] = kde(C(i,:));\n    [~,ind] = max(density); \n    bas(i) = xmesh(ind);\n    sn(i) = std(C(i,C(i,:)<bas(i)))/sqrt(1-2/pi);\nend\n\nmu = norminv(1-1/T);\nsig = norminv(1-exp(-1)/T) - mu;\n\nz = bsxfun(@times, 1./(fac*sn(:)), bsxfun(@minus, C, bas));  % normalized z scores\nz_pr = exp(-exp(-(z-mu)/sig));\n\nfilt_z = filter(ones(1,Np),1,log(z_pr),[],2)/sqrt(Np);\nmax_pr = exp(max(filt_z,[],2));", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/utilities/trace_fit_extreme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5878959186719273}}
{"text": "function [P,T] = cubic_flat_eval(C,tol)\n  % CUBIC_FLAT_EVAL Recursively subdivide a cubic Bezier curve until each\n  % segment spans a region of the curve that is locally flat up to a given\n  % tolerance (i.e., this computes an adaptive refinement).\n  %\n  % [P,T] = cubic_flat_eval(C,tol)\n  %\n  % Inputs:\n  %   C  4 by dim list of control points\n  % Outputs:\n  %   P  #P by dim list of evaluated points\n  %   T  #T list of corresponding parameter values\n  % \n  % See also: cubic_eval, cubic_is_flat, cubic_split\n  %\n  if cubic_is_flat(C,tol)\n    P = C([1 4],:);\n    T = [0 1];\n  else\n    [C1,C2] = cubic_split(C,0.5);\n    [P1,T1] = cubic_flat_eval(C1,tol);\n    [P2,T2] = cubic_flat_eval(C2,tol);\n    P = [P1;P2(2:end,:)];\n    T = [T1*0.5;0.5+T2(2:end,:)];\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/cubic_flat_eval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5878036360966916}}
{"text": "function X = cs_qleft (V, Beta, p, Y)\n%CS_QLEFT apply Householder vectors on the left.\n%   X = cs_qleft(V,Beta,p,Y) computes X = Hn*...*H2*H1*P*Y = Q'*Y where Q is\n%   represented by the Householder vectors V, coefficients Beta, and\n%   permutation p.  p can be [], which denotes the identity permutation.\n%\n%   Example:\n%       Prob = UFget ('HB/well1033') ; A = Prob.A ; [m n] = size (A) ;\n%       b = rand (m,1) ;\n%       [V,beta,p,R] = cs_qr (A) ; % QR factorization of A(p,:)\n%       b1 = cs_qleft (V, beta, p, b) ;\n%       x1 = R (1:n,1:n) \\ b1 (1:n) ;\n%       x2 = A\\b ;\n%       norm (x1-x2)\n%      \n%   See also CS_QR, CS_QRIGHT.\n\n%   Copyright 2006-2007, Timothy A. Davis.\n%   http://www.cise.ufl.edu/research/sparse\n\n[m2 n] = size (V) ;\n[m ny] = size (Y) ;\nX = Y ;\nif (m2 > m)\n    if (issparse (Y))\n        X = [X ; sparse(m2-m,ny)] ;\n    else\n        X = [X ; zeros(m2-m,ny)] ;\n    end\nend\nif (~isempty (p))\n    X = X (p,:) ;\nend\nfor k = 1:n\n    X = X - V (:,k) * (Beta (k) * (V (:,k)' * X)) ;\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/CSparse/cs_qleft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5877334869262215}}
{"text": "function partition=new_partitions(zones,sigma,r,N,x)\n%sigma=1;\n%r=8.4;\nT=r/2/sigma;\nkappa=size(zones);\nkappa=kappa(1);\n%width=sigma*(2*N/r-1);\n%x=-width:1/200:width;\n\npartition=zeros(kappa,length(x));\n\nif kappa==1\n  k=kappa;\n  for j=1:length(x)\n      if x(j)<=(zones(k,1)-1)/T+sigma\n        partition(k,j)=0;\n      elseif (zones(k,1)-1)/T+sigma<x(j) & x(j)<-sigma\n        partition(k,j)=rho((-x(j)-sigma)/(-2*sigma-(zones(k,1)-1)/T));\n      elseif -sigma<=x(j) & x(j)<=sigma\n        partition(k,j)=1;\n      elseif sigma<x(j) & x(j)<(zones(k,2)+1)/T-sigma\n        partition(k,j)=rho((x(j)-sigma)/((zones(k,2)+1)/T-2*sigma)); \n      else\n        partition(k,j)=0; \n      end\n  end\nelse\nfor k=1:kappa\n  if k==1\n    for j=1:length(x)\n      if x(j)<=(zones(k,1)-1)/T+sigma\n        partition(k,j)=0;\n      elseif (zones(k,1)-1)/T+sigma<x(j) & x(j)<-sigma\n        partition(k,j)=rho((-x(j)-sigma)/(-2*sigma-(zones(k,1)-1)/T));\n      elseif -sigma<=x(j) & x(j)<=(zones(k+1,1)-1)/T+sigma\n        partition(k,j)=1;\n      elseif (zones(k+1,1)-1)/T+sigma<x(j) & x(j)<(zones(k,2)+1)/T-sigma\n\tpartition(k,j)=rho((x(j)-((zones(k+1,1)-1)/T+sigma))/((zones(k,2)-zones(k+1,1)+2)/T-2*sigma));\n%      elseif (1-N)/T+sigma<x(j) & x(j)<(1-N/2)/T\n%        partition(k,j)=1-rho((-x(j)+(1-N/2)/T)/(N/T/2-sigma))/2;\n%      elseif x(j)==(1-N/2)/T\n%        partition(k,j)=1/2;\n%      elseif (1-N/2)/T<x(j) & x(j)<1/T-sigma\n%        partition(k,j)=rho((x(j)-(1-N/2)/T)/(N/T/2-sigma))/2;\n      else\n        partition(k,j)=0;\n      end\n    end\n  elseif k==kappa\n    for j=1:length(x)\n      if x(j)<=(zones(k,1)-1)/T+sigma\n        partition(k,j)=0; \n      elseif (zones(k,1)-1)/T+sigma<x(j) & x(j)<(zones(k-1,2)+1)/T-sigma\n        partition(k,j)=1-rho((x(j)-((zones(k,1)-1)/T+sigma))/((zones(k-1,2)-zones(k,1)+2)/T-2*sigma));\n%      elseif sigma-1/T<x(j) & x(j)<(N/2-1)/T\n%        partition(k,j)=rho((-x(j)+(N/2-1)/T)/(N/T/2-sigma))/2; \n%      elseif x(j)==(N/2-1)/T\n%        partition(k,j)=1/2; \n%      elseif (N/2-1)/T<x(j) & x(j)<(N-1)/T-sigma\n%        partition(k,j)=1-rho((x(j)-(N/2-1)/T)/(N/T/2-sigma))/2;  \n      elseif (zones(k-1,2)+1)/T-sigma<=x(j) & x(j)<=sigma\n        partition(k,j)=1; \n      elseif sigma<x(j) & x(j)<(zones(k,2)+1)/T-sigma\n        partition(k,j)=rho((x(j)-sigma)/((zones(k,2)+1)/T-2*sigma)); \n      else\n        partition(k,j)=0; \n      end\n    end\n  else\n    for j=1:length(x)\n      if x(j)<=(zones(k,1)-1)/T+sigma\n        partition(k,j)=0;\n      elseif (zones(k,1)-1)/T+sigma<x(j) & x(j)<(zones(k-1,2)+1)/T-sigma\n        partition(k,j)=1-rho((x(j)-((zones(k,1)-1)/T+sigma))/((zones(k-1,2)-zones(k,1)+2)/T-2*sigma));\n%      elseif (-N+k-1)/T+sigma<x(j) & x(j)<(k-1-N/2)/T\n%        partition(k,j)=rho((-x(j)+(k-1-N/2)/T)/(N/T/2-sigma))/2;\n%      elseif x(j)==(k-1-N/2)/T\n%        partition(k,j)=1/2;\n%      elseif (k-1-N/2)/T<x(j) & x(j)<(k-1)/T-sigma\n%        partition(k,j)=1-rho((x(j)-(k-1-N/2)/T)/(N/T/2-sigma))/2;\n      elseif (zones(k-1,2)+1)/T-sigma<=x(j) & x(j)<=(zones(k+1,1)-1)/T+sigma\n        partition(k,j)=1;\n      elseif (zones(k+1,1)-1)/T+sigma<x(j) & x(j)<(zones(k,2)+1)/T-sigma\n        partition(k,j)=rho((x(j)-((zones(k+1,1)-1)/T+sigma))/((zones(k,2)-zones(k+1,1)+2)/T-2*sigma));\n%      elseif (-N+k)/T+sigma<x(j) & x(j)<(k-N/2)/T\n%        partition(k,j)=1-rho((-x(j)+(k-N/2)/T)/(N/T/2-sigma))/2;\n%      elseif x(j)==(k-N/2)/T\n%        partition(k,j)=1/2;\n%      elseif (k-N/2)/T<x(j) & x(j)<k/T-sigma\n%        partition(k,j)=rho((x(j)-(k-N/2)/T)/(N/T/2-sigma))/2;\n      else\n        partition(k,j)=0;\n      end\n    end\n  end\n%  plot(x,partition(k,:))\n%  axis([min(x) max(x) 0 1])\n%  [k kappa]\n%  zones(k,:)\n%  pause\nend\nend\n%plot(x,partition'); %'\n%pause\n\n%total=zeros(size(x));\n%for j=1:N\n%total=total+partition(j,:);\n%end\n%spy(1-total);\n\n\n\n\n", "meta": {"author": "yueyuzhao", "repo": "gyrophone", "sha": "aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e", "save_path": "github-repos/MATLAB/yueyuzhao-gyrophone", "path": "github-repos/MATLAB/yueyuzhao-gyrophone/gyrophone-aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e/strohmer_tanner_code/over_partitions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5877334767326831}}
{"text": "classdef NSGAIIARSBX < ALGORITHM\n% <multi> <real/integer> <constrained/none>\n% NSGA-II with adaptive rotation based simulated binary crossover\n\n%------------------------------- Reference --------------------------------\n% L. Pan, W. Xu, L. Li, C. He, and R. Cheng, Adaptive simulated binary\n% crossover for rotated multi-objective optimization, Swarm and\n% Evolutionary Computation, 2021, 60: 100759.\n%--------------------------------------------------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB Platform\n% for Evolutionary Multi-Objective Optimization [Educational Forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Generate random population\n            Population = Problem.Initialization();\n            [~,FrontNo,CrowdDis] = EnvironmentalSelection(Population,Problem.N);\n            B  = eye(Problem.D);\n            m  = 0.5*(Problem.upper - Problem.lower);\n            ps = 0.5;\n            \n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                MatingPool = TournamentSelection(2,Problem.N,FrontNo,-CrowdDis);\n                Offspring  = ARSBX(Problem,Population(MatingPool),{B,m,ps});\n                [Population,FrontNo,CrowdDis] = EnvironmentalSelection([Population,Offspring],Problem.N);\n                [B,m,ps,Population] = UpdateParameter(Problem,Population);\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/Algorithms/Multi-objective optimization/NSGA-II+ARSBX/NSGAIIARSBX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5876698486206484}}
{"text": "function A = affineBuild(trans, rot, scale, skew)\n%\n% A = affineBuild(trans, rot, scale, skew)\n%\n% Builds an affine (orthogonal linear) transformation matrix from the four\n% componets: translations, rotations scales and skews.\n%\n% trans, rot, scale, skew should all be 1x3 vectors specifying x,y,z.\n% Rotations are in radians, and can be described as pitch (x-rotation),\n% roll (y-rotation) and yaw (z-rotation).\n%\n% The transformations are applied in the following order:\n%\n% 1) translations\n% 2) rotations\n% 3) scaling\n% 4) skews\n%\n% The form of the transform assumes a PRE-multiplication format:\n% Y = A*X where X and Y are 4 x n arrays of n coordinates.\n%\n% HISTORY:\n%   2004.03.12 RFD (bob@white.stanford.edu) shamelessly copied the core\n%   algorithm from spm99's spm_matrix.m.\n%   2005.07.08 ras (sayres at stanford edu) imported into mrVista 2.0\n%   2005.07.28 ras enorces double class for inputs\nif ~exist('skew','var') | isempty(skew), skew = [0 0 0];    end\nif ~exist('scale','var') | isempty(scale), scale = [1 1 1]; end\nif ~exist('rot','var') | isempty(rot), rot = [0 0 0];       end\nif ~exist('trans','var') | isempty(trans), trans = [0 0 0]; end\nif ~isa(trans,'double'), trans = double(trans);             end\nif ~isa(rot,'double'), rot = double(rot);                   end\nif ~isa(scale,'double'), scale = double(scale);             end\nif ~isa(skew,'double'), skew = double(skew);                end\n\nA  = eye(4);\n\nA  = A*[1 \t0 \t0  trans(1);\n        0 \t1 \t0  trans(2);\n        0 \t0 \t1  trans(3);\n        0 \t0 \t0  1];\n\nA  = A*[1   0            0            0;\n        0   cos(rot(1))  sin(rot(1))  0;\n        0  -sin(rot(1))  cos(rot(1))  0;\n        0   0    \t      0           1];\n\nA  = A*[cos(rot(2))  0  sin(rot(2))  0;\n        0    \t     1  0            0;\n       -sin(rot(2))  0  cos(rot(2))  0;\n        0            0  0            1];\n\nA  = A*[cos(rot(3))  sin(rot(3))  0  0;\n       -sin(rot(3))  cos(rot(3))  0  0;\n        0            0            1  0;\n        0     \t     0    \t      0  1];\n\nA  = A*[scale(1) 0         0         0;\n        0        scale(2)  0         0;\n        0        0         scale(3)  0;\n        0        0         0         1];\n\nA  = A*[1  skew(1)  skew(2)  0;\n        0  1        skew(3)  0;\n        0  0        1        0;\n        0  0        0        1];\n    \nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/RSVista/mrMethods/coords/affineBuild.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5876698314043733}}
{"text": "function dX = Motor2D(X,K,isForceField)\n\n% Parameters\nm   = 2;%1;  % mass \nb   = 10; % viscosity\nc1  = 0.15/2;\nc2  = 0.05/2;\ndt  = 0.005;\ntau = 0.05;\nA = [ 0 0    1    0;\n      0 0    0    1;\n      0 0 -b/m    0;\n      0 0    0 -b/m];\nB = [0   0;\n     0   0;\n     1/m 0;\n     0 1/m];\nB1 = [1/tau 0;\n     0  1/tau];\n\nx = X(1:6);\nz = X(7:8);\n\ndx = x;\nx = x(:);\nu = -K*x;\n\nw = randn(2,1)*sqrt(dt);\nM = [c1*u(1) c2*u(2); -c2*u(1) c1*u(2)];\n\nVF=[-10.1 -11.2; -11.2 11.1];\n\nv = M*w; % control dependent noise\nf = z;\n\ndx(1:4) = A * x(1:4)+B*(x(5:6)+f);\ndx(5:6) = B1 * (-x(5:6)+u+v./dt);\n\nif isForceField\n\tdz = -1/0.01*(z-VF*[x(3);x(4)]);\nelse\n\tdz=[0;0];\nend\n\ndX=[dx;dz];\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/Chapter7_Example2/Motor2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5876569783160257}}
{"text": "classdef SomeOptimalSuperEllipseExponentVsStress < handle\n    \n    properties (Access = private)\n        samplePoints\n        qOpt\n        phiMin\n        phiMax\n        nPhi\n        rhoV\n        xiV\n        rho\n        xi\n        outputPath\n        phiDV\n        phiV\n        iIn\n        iOut\n        qMin\n        qMax\n        qMean\n    end\n    \n    methods (Access = public)\n        \n        function obj = SomeOptimalSuperEllipseExponentVsStress()\n            obj.init();\n            for iTest = 1:length(obj.xiV)\n                obj.rho   = obj.rhoV(iTest);\n                obj.xi   = obj.xiV(iTest);\n                obj.phiV  = obj.createPhi();\n                obj.phiDV = obj.createPhiInInterval();       \n                obj.createSamplePoints();\n                obj.computeOptimalSuperEllipseExponent();\n                obj.computeMeanSuperEllipseExponent();            \n                obj.plotQoptAndGaussianVsPhi(iTest);                \n            end\n        end\n        \n    end    \n    \n    methods (Access = private)\n        \n        function init(obj)\n            obj.outputPath = '/home/alex/Dropbox/PaperStress/';\n            obj.phiMin = 0;\n            obj.phiMax = pi;\n            obj.nPhi = 3;%50;               \n            obj.rhoV  = [0.9,0.9,0.5,0.5];\n            obj.xiV  = pi/2 - [0.1083,0.557,0.88974,1.0984];            \n        end        \n        \n        function itIs = isInInterval(obj,phi)\n            itIs = phi>= obj.phiMin & phi <= obj.phiMax;\n        end\n        \n        function phiD = createPhiInInterval(obj)\n            phi = obj.phiV;            \n            iI  = obj.isInInterval(phi);\n            iO  = ~iI;\n            phiD(iI) = phi(iI);\n            phiD(iO) = sign(phi(iO)).*(phi(iO)-pi/2);            \n        end\n        \n        function phi = createPhi(obj)\n            phi = linspace(obj.phiMin,obj.phiMax,obj.nPhi);\n        end\n         \n        function createSamplePoints(obj)\n            s.type = 'FromFixedRhoAndTxi';\n            s.rho0 = obj.rho;\n            s.txi  = obj.xi;\n            s.phi  = obj.phiV;\n            sample = SamplePointsCreatorForOptimalExponentComputer.create(s);\n            sample.compute();\n            obj.samplePoints = sample;\n        end\n        \n        function computeOptimalSuperEllipseExponent(obj)\n            s.samplePoints = obj.samplePoints;\n            rhoT = strrep(num2str(obj.rho),'.','_');\n            txiT = strrep(num2str(round(obj.xi,3)),'.','_');\n            fN = ['AveragingSuperEllipseRho',rhoT,'Txi',txiT];\n            s.fileName = fN;\n            exponentComputer = OptimalExponentComputer(s);\n            exponentComputer.compute();\n            obj.qOpt = exponentComputer.qOpt;\n            obj.qMax = exponentComputer.qMax;\n            obj.qMin = exponentComputer.qMin;\n        end\n        \n        function computeMeanSuperEllipseExponent(obj)\n            s.phiV = obj.phiV;\n            qMeanC    = SuperEllipseMeanAndDesvExponentComputer(s);\n            obj.qMean = qMeanC.computeMean(obj.qOpt,obj.xi);\n        end        \n        \n        function plotQoptAndGaussianVsPhi(obj,itxi)\n            s.phiV = obj.phiV;\n            s.phiMin = obj.phiMin;\n            s.phiMax = obj.phiMax;\n            s.qOpt = obj.qOpt;\n            s.qMin = obj.qMin;\n            s.qMax = obj.qMax;\n            s.qMean = obj.qMean;\n            s.xi = obj.xi;\n            s.rho = obj.rho;\n            p = OptimalSuperEllipseExponentVsGaussianPlotter(s);\n            p.plot(itxi);\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/Homogenization/Sources/VadamecumCalculator/SomeOptimalSuperEllipseExponentVsStress.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5876417828577285}}
{"text": "function morph_profile=GetMP(img,SEs)\n% Extract Morphological Profiles of the input image with the given SEs\n%2016-10-20, jlfeng\n[nr,nc]=size(img);\nnumSE=length(SEs);\nmorph_profile=zeros(nr,nc,numSE*8);\n%%\n% Opening and Closing\nmp1=zeros(nr, nc,numSE);mp2=zeros(nr, nc,numSE);\nfor kk=1:numSE\n    mp1(:,:,kk)=imclose(img,SEs{kk});\n    mp2(:,:,kk)=imopen(img,SEs{numSE+1-kk});\nend\ndmp=diff(cat(3,mp1,img,mp2),[],3);\nmorph_profile(:,:,1:numSE*4)=cat(3,mp1,mp2,dmp);\n% OpenRec and CloseRec\nfor kk=1:numSE\n    marker=imerode(img,SEs{numSE+1-kk});\n    mp1(:,:,kk)=imreconstruct(marker,img);\n    marker=imdilate(img,SEs{kk});\n    mp2(:,:,kk)=imreconstruct(imcomplement(marker),imcomplement(img));\nend\ndmp=diff(cat(3,mp1,img,mp2),[],3);\nmorph_profile(:,:,(numSE*4+1):numSE*8)=cat(3, mp1,mp2,dmp);\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u7c7b\u7b97\u6cd5/HSI-Classification-master/img_process/GetMP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.5876417781370431}}
{"text": "classdef LHSintegrator_StiffnessColumn < LHSintegrator\n    \n    properties (Access = public)\n        geometry\n        stiffnessMatrix\n    end\n    \n    properties (Access = private)\n        freeNodes\n    end\n    \n    methods (Access = public)\n        \n        function obj = LHSintegrator_StiffnessColumn(cParams)\n            obj.init(cParams) \n            obj.initStiffnessColumn(cParams);\n            obj.createQuadrature();\n            obj.createInterpolation();\n            obj.createGeometry();\n        end\n\n        function LHS = compute(obj)\n            lhs = obj.computeElementalLHS();\n            LHS = obj.assembleMatrix(lhs);\n            obj.stiffnessMatrix = LHS;\n        end\n\n        function [Kfree,free] = provideFreeStiffnessMatrix(obj)\n            free = obj.freeNodes;\n            K = obj.stiffnessMatrix;\n            Kfree  = K(free,free);\n        end\n\n    end\n\n    methods (Access = protected)\n\n        function lhs = computeElementalLHS(obj)\n            d = obj.dim;\n            nElem = obj.mesh.nelem; \n            Edof = d.ndofPerElement;\n            Ke = zeros(Edof,Edof,nElem);\n            l = obj.computeLength();\n            [c1,c2,c3,c4,c5] = obj.coeffsStiffness(l);\n            Ke(1,1,:) = c1.*c2;\n            Ke(1,2,:) = c1.*c3;\n            Ke(1,3,:) = -c1.*c2;\n            Ke(1,4,:) = c1.*c3;\n            Ke(2,1,:) = c1.*c3;\n            Ke(2,2,:) = c1.*c4;\n            Ke(2,3,:) = -c1.*c3;\n            Ke(2,4,:) = -c1.*c5;\n            Ke(3,1,:) = -c1.*c2;\n            Ke(3,2,:) = -c1.*c3;\n            Ke(3,3,:) = c1.*c2;\n            Ke(3,4,:) = -c1.*c3;\n            Ke(4,1,:) = c1.*c3;\n            Ke(4,2,:) = -c1.*c5;\n            Ke(4,3,:) = -c1.*c3;\n            Ke(4,4,:) = c1.*c4;\n            lhs = Ke;\n        end\n\n    end\n    \n    methods (Access = private)\n\n        function initStiffnessColumn(obj,cParams)\n            obj.freeNodes = cParams.freeNodes;\n        end\n\n        function createGeometry(obj)\n            q   = obj.quadrature;\n            int = obj.interpolation;\n            int.computeShapeDeriv(q.posgp);\n            s.mesh = obj.mesh;\n            g = Geometry.create(s);\n            g.computeGeometry(q,int);\n            obj.geometry = g;\n        end\n\n        function l = computeLength(obj)\n            g = obj.geometry;\n            l = sum(g.dvolu,2);\n        end\n\n        function [c1,c2,c3,c4,c5] = coeffsStiffness(obj,l)\n            c1 = (1./(30*l))';\n            c2 = 36*ones(1,length(l));\n            c3 = (3*l)';\n            c4 = (4*l.^2)';\n            c5 = (l.^2)';\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/Integrator/LHSintegrator_StiffnessColumn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5876417781370431}}
{"text": "% FUNCTION kdtree = kdtree_create(points)\n%\n% AUTHOR:     Steven Michael\n%             (smichael@ll.mit.edu)\n%\n% DATE:       2/17/05\n%\n% DESCRIPTION:\n%\n%  This function creates a KD Tree from the given points\n%  and outputs it in the abstract object \"kdtree\"\n%  The \"kdtree\" object can then be used for range finding\n%  and nearest neighbor searching.\n%\n% INPUTS:\n%\n%   points   :     A (npoints X ndim) array of points, where \"npoints\"\n%                  is the number of points and \"ndim\" is the number\n%                  of dimensions.  Note that the points, even if they\n%                  are double precision, will be converted to single\n%                  precision when the tree is populated.  This is for \n%                  speed -- most kdtree search applications don't\n%                  necessitate double precision data.\n%\n% OUTPUTS:\n%\n%   kdtree   :     The abstract KD Tree object.\n%\n%\n% Example: \n% \n%    % Create a list of 1000 random points in 3d space\n%    r = rand(1000,3);\n% \n%    % Create a tree from this list\n%    tree = kdtree(r);\n% \n%    % Find the point closest to the origin\n%    [pntidx,pntval] = kdtree_closestpoint(tree,[0 0 0]);\n%\n%    % Create a list \"r2\" of 100 random points in 3d space and\n%    % find the points in \"r\" that are closest to each point in \"r2\"\n%    [pntidx,pntval] = kdtree_closestpoint(tree,r2);\n%\n%    % Find all the points within the cube defined by \"rng\"\n%    rng = [ [.45 .55]; [.45 .55]; ; [.45 .55] ];\n%    pntidx = kdtree_range(tree,rng);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/7030-kd-tree-nearest-neighbor-and-range-search/kdtree/@kdtree/kdtree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5875044518052882}}
{"text": "function check_WC_params(par)\n\nif isfield(par,'features') && strcmp('features','wav')\n\n    if isfield(par,'scales')&&  isfield(par,'par.w_post') &&  isfield(par,'par.w_pre')\n         L = wmaxlev(par.w_pre+par.w_post,'haar');\n         if L<scale\n             error('[par.scale] exceeds maximum wavelet decomposition level for a waveform of length [par.w_pre+par.w_post]')\n         end\n    end\n    if isfield(par,'par.w_post') &&  isfield(par,'par.w_pre')\n        x = log2(par.w_pre+par.w_post);\n        if floor(x)~=x\n            error('The length [par.w_pre+par.w_post] should be a power of 2')\n        end\n    end\nend\nend", "meta": {"author": "csn-le", "repo": "wave_clus", "sha": "3cbc9e7a747353dde2b97984eef48bbbd7991928", "save_path": "github-repos/MATLAB/csn-le-wave_clus", "path": "github-repos/MATLAB/csn-le-wave_clus/wave_clus-3cbc9e7a747353dde2b97984eef48bbbd7991928/Batch_files/check_WC_params.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.587504439028937}}
{"text": "clf\nset(gcf, 'Position', [90   410   651   545]);\ngoal = [4 8];\nstart = [7 2];\nopt.metric = 'euclidean'\nopt.show = 1\nopt.movie = [];%'dxform2.mp4'\n\n% make a simple map\noccgrid = zeros(10,10);\noccgrid(4:6,3:7) = 1;\n%occgrid(7:8,7) = 1;  % extra bit\n\n\ncost0 = occgrid;\ncost0(cost0==1) = NaN;\n\ncost = cost0;\ncost(cost0==0) = Inf;\ncost(goal(2), goal(1)) = 0;\n\nif ~isempty(opt.movie)\n    anim = Animate(opt.movie);\nend\n\nshowpixels(cost, 'contrast', 6, 'fmt', '%.2g', 'cscale', [0 12], 'fontsize', 20, 'infsymbol', 'nancolor', 'nohidenan', 'nohideinf', 'infcolor')\n\nif ~isempty(opt.movie)\n    anim.add();\nend\n\n\nswitch opt.metric\n    case 'cityblock'\n        m = [inf 1 inf\n              1  0  1\n             inf 1 inf];\n    case 'euclidean'\n        r2 = sqrt(2);\n        m = [r2 1 r2\n              1 0  1\n             r2 1 r2];\n    otherwise\n        error('unknown distance metric');\nend\n\ncount = 0;\nninf = 0;\n\nwhile 1\n    \n    cost = imorph(cost, m, 'plusmin');\n    count = count+1;\n    if opt.show\n        % transfer over the finite values\n%         k = ~isinf(cost0);\n%         cost(k) = cost0(k);\n        \n        showpixels(cost, 'contrast', 6, 'fmt', '%.2g', 'cscale', [0 14], 'fontsize', 20, 'nancolor', 'nohideinf', 'infsymbol', 'nohidenan', 'infcolor', 'here')\n        xlabel('x', 'FontSize', 20); ylabel('y', 'FontSize', 20)\n        %         cmap = [1 0 0; gray(count)];\n        %         colormap(cmap)\n        %         image(occgrid+1, 'CDataMapping', 'direct');\n        %         set(gca, 'Ydir', 'normal');\n        %         xlabel('x');\n        %         ylabel('y');\n        if ~isempty(opt.movie)\n            anim.add();\n        end\n        pause(opt.show);\n    end\n    \n    ninfnow = sum( isinf(cost(:)) ); % current number of Infs\n    if ninfnow == ninf\n        % stop if the number of Infs left in the map had stopped reducing\n        % it may never get to zero if there are unreachable cells in the map\n        break;\n    end\n    ninf = ninfnow;\nend\ncount\nif ~isempty(opt.movie)\n    anim.close();\nend", "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/dxdemo2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.587504439028937}}
{"text": "function cmap = cmapExtendedHSV(numGrays,numColors,range)\n%\n% cmap = cmapExtendedHSV([numGrays=128],[numColors=96],[range=query user])\n% \n%The map created here are hsv maps where all of the colors\n% can be placed in a subsection of the full color map.  In this way, the\n% full range of colors spans less than 2pi, like in the double color map.\n% Rather than compressing by a complete factor of 2, like the double color\n% map, the compression factor can be a bit smaller.\n%\n%   There are numGrays gray scale entries.  They occupy the first part of the cmap, 1:numGrays\n%   There are numColors hsv colors.  They fill the map entries following the gray, \n%   from (numGrays+1):numGrays+numColors\n%   When the range is 1, the hsv map is hsv(numColors) and we insert it\n%   into the cmap.\n%   When the range is 1.5, we compute tmp = hsv(numColors/1.5) and we\n%   create [tmp,tmp(1:needed)] to fill up numColors entries.\n%\n% Examples:\n%   cmap = cmapExtendedHSV(128,96,1.1);\n%   cmap = cmapExtendedHSV(128,96);    -- 128 gray levels, 96 color levels,\n%          query use for compression\n%   cmap = cmapExtendedHSV;\n%   cmap = cmapExtendedHSV(128,96,2);  -- Same as hsvDoubleCmap\n%\n\n\nfunction vw = cmapExtended(vw,range)\n%\n%   vw = cmapExtended(vw,range)\n%\n% Author: AAB, BW\n% Purpose:\n%   Compress the current color map to smaller range and add gray at the end.\n%\n%  vw = FLAT{1};\n\nnumGrays = viewGet(vw,'cmapcurnumgrays');\nnumColors = viewGet(vw,'cmapcurnumcolors');\nmpColors = viewGet(vw,'cmapcurrent');\n\nif ieNotDefined('vw'),  error('Must pass in the view.'); end\nif ieNotDefined('range'), range = 1.2; end\n\nif (range < 1) | (range > 2),  error('Range must be betweem 1 and 2.'); end\n\ndesiredColors = round(numColors/range);\nextraColors = numColors - desiredColors;\nnewMap = [round(interp1(mpColors',(1:range:numColors)')')];\nnewMap = [newMap,ones(3,extraColors)*128];\n\nvw = viewSet(vw,'cmapcurrent',newMap);\n\n% cmap = zeros(numGrays+numColors,3);\n% \n% % If you want the map symmetric at the boundary, you should do this.\n% % We could trap range == 2 and do it then ... which would be backwards\n% % compatible?\n% % cmap = [gray(numGrays); hsvMap; flipud(hsvMap(1:hsvColorsExtra,:))];\n% cmap = [hsvMap; hsvMap(1:hsvColorsExtra,:)];\n% shiftSize = round(hsvColorsExtra/2);\n% hsvMap = circshift(cmap,shiftSize);\n% \n% cmap = [gray(numGrays); cmap];\n\nreturn;\n\n%----------------------------------------\nfunction range = readRange\n\nprompt={'Enter compression range for the hsv map (2 = double color map)'};\ndef={'1.2'};\ndlgTitle='Color map compression factor';\nlineNo=1;\nrange=inputdlg(prompt,dlgTitle,lineNo,def);\nrange = str2num(range{1});\n\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/Colormap/cmapExtendedHSV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5874968500086453}}
{"text": "function c8_sqrt_test ( )\n\n%*****************************************************************************80\n%\n%% C8_SQRT_TEST tests C8_SQRT.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 March 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  test_num = 10;\n  seed = 123456678;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'C8_SQRT_TEST\\n' );\n  fprintf ( 1, '  C8_SQRT computes the principal square root of a C8.\\n' );\n \n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ...\n    '            C1=random            C2=C8_SQRT(C1)         C3=C2*C2\\n' );\n  fprintf ( 1, '\\n' );\n\n  for test = 1 : test_num\n \n    [ c1, seed ] = c8_uniform_01 ( seed );\n    c2 = c8_sqrt ( c1 );\n    c3 = c1 * c1;\n\n    fprintf ( 1, '  %10f  %10f    %10f  %10f    %10f  %10f\\n', ...\n      real ( c1 ), imag ( c1 ), ...\n      real ( c2 ), imag ( c2 ), ...\n      real ( c3 ), imag ( c3 ) );\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_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.5874968426735324}}
{"text": "clear all; close all; clc\n\naddpath('apm')\n\ns = 'http://byu.apmonitor.com';\nb = 'mhe';\n\n% Connect to Arduino\ntclab;\n\n% Run time in minutes\nrun_time = 10.0;\n\n% Number of cycles (1 cycle per 3 seconds)\nloops = round(20*run_time);\n\n% milli-volts input\nQ1 = zeros(1,loops);\nQ2 = zeros(1,loops);\nQ1(3:end) = 100.0;\nQ1(50:end) = 0.0;\nQ1(100:end) = 80.0;\n\nQ2(25:end) = 60.0;\nQ2(75:end) = 100.0;\nQ2(125:end) = 25.0;\n\nfor i = 130:180\n    if mod(i,10)==0\n        Q1(i:i+10) = rand(1) * 100;\n    end\n    if mod(i+5,10)==0\n        Q2(i:i+10) = rand(1) * 100;\n    end        \nend\n\n% Temperature (degC)\nT1 = ones(1,loops) * T1C(); % measured T\nT2 = ones(1,loops) * T2C(); % measured T\nT1mhe = ones(1,loops) * T1C(); % measured T\nT2mhe = ones(1,loops) * T2C(); % measured T\nUmhe = ones(1,loops) * 10.0;\ntaumhe = ones(1,loops) * 5.0;\namhe1 = ones(1,loops) * 0.01;\namhe2 = ones(1,loops) * 0.0075;\ntime = zeros(1,loops);\n\n% time\ntm = zeros(1,loops);\n\n% moving horizon estimation\nmhe_init();\n\nstart_time = clock;\nprev_time = start_time;\n\n% dynamic plot (note: subplots needs to be declared here first)\nfigure(1)\nsubplot(3,1,1)\nhold on, grid on\nanexp1 = animatedline('LineStyle','-', 'Color', 'k', 'LineWidth', 2);\nanpred1 = animatedline('LineStyle','--','Color', 'r','LineWidth', 2);\nanexp2 = animatedline('LineStyle','-', 'Color', 'b', 'LineWidth', 2);\nanpred2 = animatedline('LineStyle','--','Color', 'g','LineWidth', 2);\nylabel('Temperature \\circC')\nlegend('T_1 Measured', 'T_1 Predicted', ...\n    'T_2 Measured', 'T_2 Predicted', ...\n    'Location', 'northwest')\ntitle('Temperature Estimation')\nsubplot(3,1,2)\nhold on, grid on\nanQ1 = animatedline('LineStyle','-', 'Color', 'k', 'LineWidth', 2);\nanQ2 = animatedline('LineStyle','--', 'Color', 'b', 'LineWidth', 2);\nylabel('Power Level Q (%)')\nlegend('Q_1', 'Q_2', 'Location', 'northwest')\nsubplot(3,1,3)\nhold on, grid on\nanU = animatedline('LineStyle','-', 'Color', 'r', 'LineWidth', 2);\nantau = animatedline('LineStyle','--', 'Color', 'b', 'LineWidth', 2);\nana1 = animatedline('LineStyle','-', 'Color', 'g', 'LineWidth', 2);\nana2 = animatedline('LineStyle','-', 'Color', 'k', 'LineWidth', 2);\nylabel('Parameters')\nlegend('U', 'tau', 'a1 x 1000', 'a2 x 1000', 'Location', 'northwest')\nxlabel('Time (sec)')\n\nfor ii = 1:loops\n    % adjust power level\n    h1(Q1(ii));\n    h2(Q2(ii));\n    \n    % Pause Sleep time\n    pause_max = 3.0;\n    pause_time = pause_max - etime(clock,prev_time);\n    if pause_time >= 0.0\n        pause(pause_time - 0.01)\n    else\n        pause(0.01)\n    end\n    \n    % Record time and change in time\n    t = clock;\n    dt = etime(t,prev_time);\n    if ii>=2\n        time(ii) = time(ii-1) + dt;\n    end\n    prev_time = t;\n\n    % read and record from temperature controller\n    T1(ii) = T1C();\n    T2(ii) = T2C();\n    \n    % Start estimating parameters after 10 cycles (30 sec)\n    if ii==10\n       apm_option(s,b,'U.STATUS',1);\n       apm_option(s,b,'tau.STATUS',1);\n       apm_option(s,b,'a1.STATUS',1);\n       apm_option(s,b,'a2.STATUS',1);\n    end\n    \n    % non-linear energy balance\n    jj = ii+1;\n    params = mhe(T1(ii),T2(ii),Q1(ii),Q2(ii));\n    Umhe(jj) = params(1);\n    taumhe(jj) = params(2);\n    a1(jj) = params(3);\n    a2(jj) = params(4);\n    T1mhe(jj) = params(5);        \n    T2mhe(jj) = params(6);        \n        \n    % plot\n    addpoints(anexp1,time(ii),T1(ii))\n    addpoints(anpred1,time(ii),T1mhe(ii))\n    addpoints(anexp2,time(ii),T2(ii))\n    addpoints(anpred2,time(ii),T2mhe(ii))\n    addpoints(anQ1,time(ii),Q1(ii))\n    addpoints(anQ2,time(ii),Q2(ii))\n    addpoints(anU,time(ii),Umhe(ii))\n    addpoints(antau,time(ii),taumhe(ii))\n    addpoints(ana1,time(ii),1000*a1(ii))\n    addpoints(ana2,time(ii),1000*a2(ii))\n    drawnow    \n    \n    % open web-interface\n    if ii==20\n        apm_web(s,b);\n    end\nend\n\nh1(0);\nh2(0);\ndisp('Heaters off')\n% turn off heater but keep LED on if T > 50\nif (T1C() || T2C()) > 50\n    led(1)\n    disp(['Warning, heater temperature 1 =', num2str(T1C())])\n    disp(['Warning, heater temperature 2 =', num2str(T2C())])\nelse\n    led(0)\nend\n\n% save txt file with data\ndata = [time',Q1',Q2',T1',T2'];\ncsvwrite('data.txt',data);", "meta": {"author": "APMonitor", "repo": "arduino", "sha": "f36e65a70dd7122d1829883899e40e56bf6c4279", "save_path": "github-repos/MATLAB/APMonitor-arduino", "path": "github-repos/MATLAB/APMonitor-arduino/arduino-f36e65a70dd7122d1829883899e40e56bf6c4279/5_Moving_Horizon_Estimation/2nd_order_nonlinear/MATLAB/main_mhe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5874968336799075}}
{"text": "function [crack_img] = seg2cracks(seg)\n%\n% [crack_img] = seg2cracks(seg)\n% \n%  Converts a segmentation image into a crack-coded image.\n%\n\n% Bits:\n%       |\n%       | 1\n% 4 ----+---- 2\n%       | \n%       | 3\n\n% Values:\n% tic\nUP    = 1;\nRIGHT = 2;\nDOWN  = 3;\nLEFT  = 4;\n\nJUNCTION = 5;\n\n% dx = uint8(seg ~= image_right(seg));\n% dy = uint8(seg ~= image_down(seg) );\n% crack_img = dx + bitshift(dy,LEFT-1) + ...\n%     bitshift(image_right(dy),RIGHT-1) + bitshift(image_down(dx),DOWN-1);\n\n% Removed dependency on image_down and image_right, to make this more\n% easily packaged:\ndx = uint8(seg ~= seg(:,[2:end end]));\ndy = uint8(seg ~= seg([2:end end],:));\ncrack_img = dx + bitshift(dy,LEFT-1) + ...\n    bitshift(dy(:,[2:end end]),RIGHT-1) + bitshift(dx([2:end end],:),DOWN-1);\n\n% Find interior junctions:\njunction_map = (crack_img==11 | crack_img==7 | crack_img==14 | ...\n    crack_img==13 | crack_img==15);\n\n% Find the junctions along the borders:\njunction_map([1 end],:) = junction_map([1 end],:) | bitget(crack_img([1 end],:),UP);\njunction_map(:,[1 end]) = junction_map(:,[1 end]) | bitget(crack_img(:,[1 end]),LEFT);\n\n% set the junction bit for all these junctions in the crack_img\ncrack_img(junction_map) = bitset(crack_img(junction_map), JUNCTION);\n   \n\n% % Also set all borders of the image to be seen as junctions (all bits set\n% % == a value of 15) so that we will know to stop in the fragment chaining \n% % process later\n% crack_img(:,[1 end]) = 15;\n% crack_img([1 end],:) = 15;\n\n% fprintf('New method: %.3f seconds\\n', toc);\n% \n% %% Old Method %%\n% tic\n% [nrows, ncols ] = size(seg);\n% crack_img2 = zeros(nrows, ncols, 'uint8');\n% % Bits:\n% UP    = 1;\n% RIGHT = 2;\n% DOWN  = 3;\n% LEFT  = 4;\n% \n% index = find(seg ~= image_right(seg));\n% crack_img2(index) = bitset(crack_img2(index), UP);\n% \n% index = find(image_right(seg) ~= image_downright(seg));\n% crack_img2(index) = bitset(crack_img2(index), RIGHT);\n% \n% index = find(image_down(seg) ~= image_downright(seg));\n% crack_img2(index) = bitset(crack_img2(index), DOWN);\n% \n% index = find(seg ~= image_down(seg));\n% crack_img2(index) = bitset(crack_img2(index), LEFT);\n% \n% fprintf('Old method: %.3f seconds\\n', toc);\n% \n% if(all(crack_img(:)==crack_img2(:)))\n%     disp('Results agree.')\n% end\n% \n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/iccv07Final/src/andrew/seg2cracks.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7248702880639792, "lm_q1q2_score": 0.5874920799976361}}
{"text": "% PLOT2DKM - For a 2-D binary classification problem, plot2dkm plots the data, \n%            the margin and error vectors and contours of constant margin\n%            for the SVM classifier in memory.\n%\n% Syntax: plot2dkm\n%\n% Version 3.22e -- Comments to diehl@alumni.cmu.edu\n%\n\nfunction plot2dkm\n\n% flags for example state\nMARGIN    = 1;\nERROR     = 2;\nRESERVE   = 3;\nUNLEARNED = 4;\n\n% define global variables \nglobal ind;   % cell array containing indices of margin, error, reserve and unlearned vectors\nglobal X;     % matrix of margin, error, reserve and unlearned vectors stored columnwise\nglobal y;     % column vector of class labels (-1/+1) for margin, error, reserve and unlearned vectors\n\n% plot examples with label -1\nfigure;\nindn1 = find(y == -1);\nscatter(X(1,indn1),X(2,indn1),40,'b','filled');\nhold on;\n\n% plot examples with label +1\nind1 = find(y == 1);\nscatter(X(1,ind1),X(2,ind1),40,'r');\n\n% plot margin vectors\nscatter(X(1,ind{MARGIN}),X(2,ind{MARGIN}),120,'k');\nscatter(X(1,ind{MARGIN}),X(2,ind{MARGIN}),150,'k');\nscatter(X(1,ind{MARGIN}),X(2,ind{MARGIN}),200,'k');\n\n% plot error vectors\nscatter(X(1,ind{ERROR}),X(2,ind{ERROR}),120,'k');\nscatter(X(1,ind{ERROR}),X(2,ind{ERROR}),150,'k');\nscatter(X(1,ind{ERROR}),X(2,ind{ERROR}),200,'k');\nscatter(X(1,ind{ERROR}),X(2,ind{ERROR}),120,'k','x');\nscatter(X(1,ind{ERROR}),X(2,ind{ERROR}),150,'k','x');\nscatter(X(1,ind{ERROR}),X(2,ind{ERROR}),200,'k','x');\n\n% draw margin band\nxl = xlim;\nyl = ylim;\npd = min(xl(2)-xl(1),yl(2)-yl(1))/100;\nx_range = xl(1):pd:xl(2);\ny_range = yl(1):pd:yl(2);\nf = zeros(length(y_range),length(x_range));\ni = 1;\nfor xp = x_range\n   j = 1;\n   for yp = y_range\n      f(j,i) = svmeval([xp ; yp]);\n      j = j + 1;\n   end;\n   i = i + 1;\nend;\ncontour(x_range,y_range,f,[-1 1]);\n\n\n\n\n\n", "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/CLIA/iSVM/plot2dkm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5874920607290601}}
{"text": "% Copyright (C) 2013 Quan Wang <wangq10@rpi.edu>,\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% this is a demo showing the use of our dynamic time warping package \n% we provide both Matlab version and C/MEX version\n% the C/MEX version is much faster and highly recommended\n\nclear;clc;close all;\n\nmex dtw_c.c;\n\na=rand(500,3);\nb=rand(520,3);\nw=50;\n\ntic;\nd1=DTWComputer.mddtw(a,b);\nt1=toc;\n\ntic;\nd2=dtw_c(a,b,w);\nt2=toc;\n\nfprintf('Using Max version: distance=%f, running time=%f\\n',d1,t1);\nfprintf('Using C/MEX version: distance=%f, running time=%f\\n',d2,t2);\n\n", "meta": {"author": "avenix", "repo": "WDK", "sha": "c525222b02bd390b4758d30f1cd8b19af043108e", "save_path": "github-repos/MATLAB/avenix-WDK", "path": "github-repos/MATLAB/avenix-WDK/WDK-c525222b02bd390b4758d30f1cd8b19af043108e/libraries/dynamic_time_warping_v2.1/demo_dtw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5874920540925515}}
{"text": "% RPCA | MoG-RPCA | Mixture of Gaussians RPCA (Zhao et al. 2014)\n% process_video('RPCA', 'MoG-RPCA', 'dataset/demo.avi', 'output/demo_MoG-RPCA.avi');\n\n%{\nclear, clc;\nload('dataset/trafficdb/traffic_patches.mat');\nV = im2double(imgdb{100});\n[M,m,n,p] = convert_video3d_to_2d(V);\n%}\n\nr = 1;\nparam.mog_k = 3;\nparam.lr_init = 'SVD';\nparam.maxiter = 100;\nparam.initial_rank = 2*r;\nparam.tol = 1e-3;\n\nlr_prior.a0 = 1e-6;\nlr_prior.b0 = 1e-6;\n\nmog_prior.mu0 = 0;\nmog_prior.c0 = 1e-3;\nmog_prior.d0 = 1e-3;\nmog_prior.alpha0 = 1e-3;\nmog_prior.beta0 = 1e-3;\n\n[lr_model, mog_model, r] = mog_rpca(M, param, lr_prior, mog_prior);\n\nL = lr_model.U*lr_model.V';\nS = M - L;\n\n%{\nshow_2dvideo(M,m,n);\nshow_2dvideo(L,m,n);\nshow_2dvideo(S,m,n);\nshow_2dvideo(hard_threshold(S),m,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/MoG-RPCA/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5873380858795034}}
{"text": "function MatingPool = MatingSelection(PopObj,div)\n% The mating selection of GrEA\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    N = size(PopObj,1);\n\n    %% Calculate the grid location of each solution\n    fmax = max(PopObj,[],1);\n    fmin = min(PopObj,[],1);\n    lb   = fmin-(fmax-fmin)/2/div;\n    ub   = fmax+(fmax-fmin)/2/div;\n    d    = (ub-lb)/div;\n    lb   = repmat(lb,N,1);\n    d    = repmat(d,N,1);\n    GLoc = floor((PopObj-lb)./d); \n    GLoc(isnan(GLoc)) = 0;\n    \n    %% Calculate the GD value of each solution\n    GD = zeros(N)+inf;\n    for i = 1 : N-1\n        for j = i+1 : N\n            GD(i,j) = sum(abs(GLoc(i,:)-GLoc(j,:)));\n            GD(j,i) = GD(i,j);\n        end\n    end\n    \n    %% Calculate the GCD value of each solution\n    GD  = max(size(PopObj,2)-GD,0);\n    GCD = sum(GD,2);\n    \n    %% Binary tournament selection\n    Parents1   = randi(N,1,N);\n    Parents2   = randi(N,1,N);\n    Dominate   = any(PopObj(Parents1,:)<PopObj(Parents2,:),2) - any(PopObj(Parents1,:)>PopObj(Parents2,:),2);\n    GDominate  = any(GLoc(Parents1,:)<GLoc(Parents2,:),2) - any(GLoc(Parents1,:)>GLoc(Parents2,:),2);\n    MatingPool = [Parents1(Dominate==1 | GDominate==1),...\n                  Parents2(Dominate==-1 | GDominate==-1),...\n                  Parents1(Dominate==0 & GDominate==0 & GCD(Parents1)<=GCD(Parents2)),...\n                  Parents2(Dominate==0 & GDominate==0 & GCD(Parents1)>GCD(Parents2))];\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/GrEA/MatingSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5873380697971339}}
{"text": "function [ W, W1,S, index_mat,IDX_vote,S_tan,Data_PCA ] = createAffMatrix( feats,params,affinity_type )\n%% W1 affinity matrix using Euclidean distances and RBF.\n\nswitch affinity_type\n    case 'local_PCA'\n       % [W1,index_mat, S] = RBF_affnity(feats,params);\n        [W1,index_mat, S,IDX_vote,S_tan] = RBF_affnity_knn_fast(feats,params);\n        %% W2 affinity using local tangent space with local PCA\n        [Data_PCA,W2,theta] = locPCA_affnity_fast(feats, IDX_vote, params);\n        %index_mat=IDX_vote;\n        %% Connecting all the points\n        Wc = W1.*W2;\n        W = Wc.*Wc';\n        \n        %W_large=W_large.*W2;\n        %W_large=W_large.*W_large;\n        \n    case 'Hillinger_affinity'\n        %params.affinity_type='cosine';\n      %  [W1, index_mat, S] = affinity.RBF_affnity(feats,params);\n        [W1,index_mat, S,IDX_vote,S_tan] = RBF_affnity_knn(feats,params);\n        params.affinity_type= 'Hillinger_affinity';\n        \n        [W2, W_l]= Hillinger_affinity( feats, IDX_vote,params); \n        Wc = W1.*W2;\n        W = Wc.*Wc';       \n    case 'sqeuclidean'  \n       % [W1,index_mat, S] = affinity.RBF_affnity(feats,params);\n      %  [W1,index_mat, S,IDX_vote,S_tan] = affinity.RBF_affnity_knn(feats,params);\n        [W1,index_mat, S,IDX_vote,S_tan] = RBF_affnity_knn_fast(feats,params);\n        W=W1;\n        case 'outliers'  \n        [W1,index_mat, S,IDX_vote,S_tan] = RBF_affnity_knn_fast(feats,params);\n         W=W1;\n        \n    case 'cosine'\n       % [W1,index_mat, S] = affinity.RBF_affnity(feats,params);\n      % [W1,index_mat, S,IDX_vote,S_tan] = affinity.RBF_affnity_knn(feats,params);\n       [W1,index_mat, S,IDX_vote,S_tan] = RBF_affnity_knn_fast(feats,params);\n        \n        \n        W = W1;\n    case 'Tensor_Voting'\n        %[W1,index_mat, S] = affinity.RBF_affnity(feats,params);\n        [W1,index_mat, S,IDX_vote,S_tan] = RBF_affnity_knn(feats,params);\n        %% W2 affinity using the Tensor Voting Graph\n        [Normal_Space,W2,theta] = TVG_affinity_knn(feats, IDX_vote, params,S_tan);\n        %% Connecting all the points\n        Wc = W1.*W2;\n        %W=(Wc + Wc')./2;\n        W = Wc.*Wc';\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u53bb\u566a\u7b97\u6cd5/Robust-Manifold-Denoising--master/createAffMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.587338069681833}}
{"text": "function [err,PatchHandles] = ShowPlane (EqPlane,Opt)\n%\n%   [err,PatchHandles] = ShowPlane (EqPlane,Opt)\n%\n%Purpose:\n%   This function displays a plane with equation ax + by + cz +d = 0\n%   The plane is defined by one sqaure patch\n%   The planes span the current axis limits of the figure.\n%\n%Input Parameters:\n%   EqPlane is a Nx4 matrix containing the equation of the plane containing each\n%       triplet in  Triplets. The plane passing by triplet i is speicifed in\n%       EqPlane(i,:) the plane would be\n%       EqPlane(i,1)x + EqPlane(i,2)y + EqPlane(i,3)z + EqPlane(i,4) = 0\n%   Opt is the options structure\n%     .Fig is a handle to the figure you want the planes displayed in,\n%         default is the current figure.\n%     .WriteIV if this string is not empty, the planes that are displayed\n%         on the graph are written to an inventor format file\n%     .units 'mm' or 'tesscon'. default is tesscon\n%       if you specify mm, then the xyz coordinates are transformed to tesscon\n%       before writing them out. (*319.7). The idea is to write all inventor\n%       files in tesscon units. This option will only be used if WriteIV is not empty.\n%     .OvrWrite (0/1) default is 0, flag for overwriting existing .iv file\n%\n%Output Parameters:\n%   err : 0 No Problem\n%       : 1 Mucho Problems\n%\n%   PatchHandles : the handle to the patches displayed on the figure\n%\n%More Info :\n%   see Plane_Equation\n%\n%\n%\n%     Author : Ziad Saad\n%     Date : Thu Oct 22 20:19:36 CDT 1998\n\n\n%Define the function name for easy referencing\nFuncName = 'ShowPlane';\n\n%initailize return variables\nerr = 1;\n\n\n%check on the size of input data\nif (nargin == 1),\t\n\tOpt.Fig = [];\t\n\tOpt.OvrWrite = 0;\n\tOpt.WriteIV = '';\nend\n\nif (~isfield(Opt,'OvrWrite') | isempty(Opt.OvrWrite)), Opt.OvrWrite = 0; end\n\nif (size(EqPlane,2) ~= 4),\terr = ErrEval(FuncName,'Err_Bad size for EqPlane');\treturn;\tend\n\nNplanes = size(EqPlane,1);\nNnodes = 4.* Nplanes;\n\n%pop up a figure\nif (~isfield(Opt,'Fig') | isempty(Opt.Fig)),\n\tOpt.Fig = gcf;\nend\n\nfigure(Opt.Fig);\n\n%get the axis roperties of the figure\nXlim = get(gca,'Xlim');\nYlim = get(gca,'ylim');\nZlim = get(gca,'Zlim');\n\ninode = 0;\nNode = zeros(Nnodes,3);\nPat = zeros(Nplanes,4);\nztmp = zeros(1,4);\n\nfor (i=1:1:Nplanes),\n\t%using the XY limits, find the corrspondign z values\n\tif (EqPlane(i,3) ~= 0),\n\t\tztmp(1) = (-EqPlane(i,4) - EqPlane(i,1).*Xlim(1) - EqPlane(i,2).*Ylim(1)) ./ EqPlane(i,3);\n\t\tztmp(2) = (-EqPlane(i,4) - EqPlane(i,1).*Xlim(2) - EqPlane(i,2).*Ylim(1)) ./ EqPlane(i,3);\n\t\tztmp(3) = (-EqPlane(i,4) - EqPlane(i,1).*Xlim(2) - EqPlane(i,2).*Ylim(2)) ./ EqPlane(i,3);\n\t\tztmp(4) = (-EqPlane(i,4) - EqPlane(i,1).*Xlim(1) - EqPlane(i,2).*Ylim(2)) ./ EqPlane(i,3);\n\t\t%form the four points on the plane\n\t\tNode(inode+1,:) = [Xlim(1) Ylim(1) ztmp(1)];\n\t\tNode(inode+2,:) = [Xlim(2) Ylim(1) ztmp(2)];\n\t\tNode(inode+3,:) = [Xlim(2) Ylim(2) ztmp(3)];\n\t\tNode(inode+4,:) = [Xlim(1) Ylim(2) ztmp(4)];\n\t\t\n\telseif (EqPlane(i,2) ~= 0),\n\t\tytmp(1) = (-EqPlane(i,4) - EqPlane(i,1).*Xlim(1) - EqPlane(i,3).*Zlim(1)) ./ EqPlane(i,2);\n\t\tytmp(2) = (-EqPlane(i,4) - EqPlane(i,1).*Xlim(2) - EqPlane(i,3).*Zlim(1)) ./ EqPlane(i,2);\n\t\tytmp(3) = (-EqPlane(i,4) - EqPlane(i,1).*Xlim(2) - EqPlane(i,3).*Zlim(2)) ./ EqPlane(i,2);\n\t\tytmp(4) = (-EqPlane(i,4) - EqPlane(i,1).*Xlim(1) - EqPlane(i,3).*Zlim(2)) ./ EqPlane(i,2);\n\t\t%form the four points on the plane\n\t\tNode(inode+1,:) = [Xlim(1) ytmp(1) Zlim(1)];\n\t\tNode(inode+2,:) = [Xlim(2) ytmp(2) Zlim(1)];\n\t\tNode(inode+3,:) = [Xlim(2) ytmp(3) Zlim(2)];\n\t\tNode(inode+4,:) = [Xlim(1) ytmp(4) Zlim(2)];\n\telseif (EqPlane(i,1) ~= 0),\n\t\txtmp(1) = (-EqPlane(i,4) - EqPlane(i,2).*Ylim(1) - EqPlane(i,3).*Zlim(1)) ./ EqPlane(i,1);\n\t\txtmp(2) = (-EqPlane(i,4) - EqPlane(i,2).*Ylim(2) - EqPlane(i,3).*Zlim(1)) ./ EqPlane(i,1);\n\t\txtmp(3) = (-EqPlane(i,4) - EqPlane(i,2).*Ylim(2) - EqPlane(i,3).*Zlim(2)) ./ EqPlane(i,1);\n\t\txtmp(4) = (-EqPlane(i,4) - EqPlane(i,2).*Ylim(1) - EqPlane(i,3).*Zlim(2)) ./ EqPlane(i,1);\n\t\t%form the four points on the plane\n\t\tNode(inode+1,:) = [xtmp(1) Ylim(1) Zlim(1)];\n\t\tNode(inode+2,:) = [xtmp(2) Ylim(2) Zlim(1)];\n\t\tNode(inode+3,:) = [xtmp(3) Ylim(2) Zlim(2)];\n\t\tNode(inode+4,:) = [xtmp(4) Ylim(1) Zlim(2)];\n\tend\t\n\n\t%verify that all points are on plane for debugging only\n\t%sum(EqPlane.*[Node(inode+1,:) 1])\n\t%sum(EqPlane.*[Node(inode+2,:) 1])\n\t%sum(EqPlane.*[Node(inode+3,:) 1])\n\t%sum(EqPlane.*[Node(inode+4,:) 1])\n\t\n\t%form the faceset connection, for the patch\n\tPat(i,:) = [inode+1 inode+2 inode+3 inode+4];\n\n\tinode = inode + 4;\n\t\nend\n\n%Now display those patches\nvc = 0:1./Nnodes:(1-1./Nnodes);\ntcolor = [vc' (1-vc)' vc'];\n\nPatchHandles = patch('vertices',Node,'faces',Pat,...\n          'FaceVertexCData',tcolor,'FaceColor','flat');\n\n%write to file ?\nif (isfield(Opt,'WriteIV') & ~isempty(Opt.WriteIV)),\n\tfprintf (1,'Saving patches to iv file %s ...\\n',Opt.WriteIV);\n   Opt.OptIV.BaseCol = tcolor;\n   if (~isfield(Opt,'units') | isempty(Opt.units)),\tOpt.units = 'tesscon'; end\n\tOpt.OptIV.units = Opt.units;\n\tOpt.OptIV.OvrWrite = Opt.OvrWrite;\n\tOpt.OptIV.verbose = 0;\n   [err] = WriteInv21Surf(Opt.WriteIV,Node,Pat,Opt.OptIV);  %exclude redundant last node\nend\n\nerr = 0;\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/afni/ShowPlane.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5873158222207626}}
{"text": "function fismat = genfis4(Xin, Xout, fistype, sig_par, varargin)\n\n%GENFIS4 Generates a FIS using CART\n%\n%   Given separate sets of input and output data, GENFIS4 generates a fuzzy\n%   inference system (FIS) using CART algorithm. GENFIS4 accomplishes this\n%   by extracting a set of rules that models the data behavior. The rule\n%   extraction method first uses TREEINFO to determine the number\n%   of rules and membership functions for the antecedents and consequents.\n%\n%   FIS = GENFIS4(XIN, XOUT) returns a Sugeno-type FIS given input data XIN\n%   and output data XOUT. The matrices XIN and XOUT have one column per FIS \n%   input and output, respectively.\n%\n%   FIS = GENFIS4(XIN, XOUT, TYPE) returns FIS of type specified by the\n%   argument TYPE. It can take one of two values: 'mamdani' or 'sugeno'.\n%\n%   FIS = GENFIS4(XIN, XOUT, TYPE, SIGM_PAR) allows you to specify the\n%   sigmoid parameters in the argument SIGM_PAR. The parameter is used to\n%   form input membership function. The larger SIGM_PAR the closer\n%   behaviour of fuzzy CART to behaviour of \"crisp\" CART. It should be\n%   positive scalar or vector. The latter should have size equal to number\n%   of FIS inputs. This argument also takes the value 'auto' in which case\n%   GENFIS4 uses additional information containing in data set to calculate\n%   SIGM_PAR. \n% \n%   FIS = GENFIS4(XIN, XOUT, TYPE, SIGM_PAR, VARARGIN) allows you to\n%   specify options for the CART algorithm. Type HELP CLASSREGTREE and \n%   HELP TEST for a list of options that can be specified for the CART\n%   algorithm.\n%\n%   Examples:\n% \n%       Xin1 = 7 * rand(50, 1);\n%       Xin2 = 20 * rand(50, 1) - 10;\n%       Xin = [Xin1 Xin2];\n%       Xout = 5 * rand(50, 1);\n%       fis = genfis4(Xin, Xout);\n%\n%       fis = genfis4(Xin, Xout, 'mamdani', [10, 1]);\n%       specifies the type of FIS and the sigmoid parameters desired.\n%\n%       fis = genfis4(Xin, Xout, 'mamdani', 'auto', {'minparent', 15}); \n%       specifies the type of FIS, the sigmoid parameters desired and CART \n%       options.\n%\n%   See also CLASSREGTREE, TEST, TREEINFO, GENFIS3, ANFISX\n\n%   Per Konstantin A. Sidelnikov, 2009.\n\n%%%%%%%%%%%%%%%%%%%%\n% Some constants\n%%%%%%%%%%%%%%%%%%%%\n\n% Number of standard deviations (can be changed)\nNSTD = 1;\n% Area under the gauss curve in the \n% [mu - NSTD * sigma, mu + NSTD * sigma]\nAREA = erf(NSTD / sqrt(2));\n% Scaling factor \nSCALE = log((1 + AREA) / (1 - AREA)) / NSTD;\n\n%%%%%%%%%%%%%%%%%%%%\n% Number of input arguments checking\n%%%%%%%%%%%%%%%%%%%%\n\nif nargin < 2\n    error('FuzzyLogic:missingparams', ...\n        'genfis4 requires input and output data to build a FIS.');\nend\n\nif nargin < 3\n    fistype = 'sugeno';\nend\n\nif nargin < 4\n    sig_par = 'auto';\nend\n\n% hardcoded for now\nin_mftype = 'sigmf';\nout_mftype = 'gaussmf';\n\n%%%%%%%%%%%%%%%%%%%%%%%%%\n% IO checking\n%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Check Xin, Xout\n[numData, numInp] = size(Xin);\n[numData2, numOutp] = size(Xout);\n\nif numData ~= numData2\n    % There's a mismatch in the input and output data matrix dimensions\n    if numData == numOutp\n        % The output data matrix should have been transposed, we'll fix it\n        Xout = Xout';\n        numOutp = numData2;\n    else\n        error('FuzzyLogic:dimensionmismatch', ...\n            'Mismatched input and output data matrices.');\n    end\nend\n\nif numOutp > 1\n    error('FuzzyLogic:outputmismatch', ...\n        'Output data must be a vector.');\nend\n\n%%%%%%%%%%%%%%%%%%%%\n% Checking sig_par\n%%%%%%%%%%%%%%%%%%%%\n\n% Convert sig_par (if necessary) to numeric array\narrayNaN = NaN(1, numInp);\nif ~isnumeric(sig_par)\n    if ~isequal(sig_par, 'auto')\n        error('FuzzyLogic:sigmoid', ...\n            'Set sigmoid parameter to ''auto'' or a value greater than 0');\n    end\n    sig_par = arrayNaN;\nelseif ~isscalar(sig_par)\n    tmp = arrayNaN;\n    tmp(1 : length(sig_par)) = sig_par;\n    sig_par = tmp;\nelse\n    sig_par = repmat(sig_par, 1, numInp);\nend \n% Avoid negative sig_par\nsig_par = abs(sig_par);\n% Length of sig_par must be the same as number of inputs\nif length(sig_par) ~= numInp\n    error('FuzzyLogic:sigmoid', ...\n        ['Set number of sigmoid parameters to ', ...\n        '1 or %d (number of inputs)'], numInp);\nend\n\n%%%%%%%%%%%%%%%%%%%%\n% Creating tree\n%%%%%%%%%%%%%%%%%%%%\nti = treeinfo(Xin, Xout, varargin{:});\n\nn_node = numel(ti.node);\nn_leaf = numel(ti.leaf);\n\nin_mf = zeros(1, n_node);\n\n%%%%%%%%%%%%%%%%%%%%%%\n% Building FIS\n%%%%%%%%%%%%%%%%%%%%%\n\n% Initialize a FIS\nstr = sprintf('%s%g%g', fistype, numInp, numOutp);\nfismat = newfis(str, fistype);\n\n% Loop through and add inputs\nfor ind = 1 : numInp    \n    fismat = addvar(fismat, ...\n        'input', ['in' num2str(ind)], minmax(Xin(:, ind)'));\nend\n\n% Loop through and add mf's\nfor ind = 1 : n_node       \n    var = ti.node(ind).variable;\n    cut = ti.node(ind).cutpoint;\n    s = ti.node(ind).sample;        \n    mfparams = computemfparams(in_mftype, Xin(s, var), ...\n        cut, sig_par(var), SCALE);\n    \n    fismat = addmf(fismat, 'input', var, ...\n        ['larger', num2str(ind)], in_mftype, mfparams);\n    \n    in_mf(ind) = length(fismat.input(var).mf);\nend\n\n% Add output\nfismat = addvar(fismat, 'output', 'out', minmax(Xout'));\n\nswitch fistype  \n    case 'sugeno'\n        % Loop through and add mf's        \n        for ind = 1 : n_leaf         \n            s = ti.leaf(ind).sample;\n            mfparams = computemfparams('linear', Xin(s, :), Xout(s));\n            \n            fismat = addmf(fismat, 'output', 1, ...\n                ['class', num2str(ind)], 'linear', mfparams);           \n        end\n    case 'mamdani'        \n        % Loop through and add mf's\n        for ind = 1 : n_leaf  \n            s = ti.leaf(ind).sample;\n            mfparams = computemfparams(out_mftype, [], Xout(s));\n            \n            fismat = addmf(fismat, 'output', 1, ...\n                ['class', num2str(ind)], out_mftype, mfparams);\n        end\n    otherwise\n        error('FuzzyLogic:unknownfistype', ...\n            'Unknown fistype specified');    \nend\n\n% Create rules\nrulelist = cell(n_leaf, 4);\nfor ind = 1 : n_leaf   \n    n = ti.branch(ind).nodes;\n    e = ti.branch(ind).ineqs;\n    \n    var = [ti.node(n).variable];\n        \n    rulelist{ind, 1} = [var; in_mf(n) .* e];\n    rulelist{ind, 2} = ind;\n    rulelist{ind, 3} = 1;\n    rulelist{ind, 4} = 1;\nend\n\nfismat = addrulex(fismat, rulelist);\n\nfunction mfparams = computemfparams(mf, X, y, sig_par, scale)\n%   This subfunction computes parameters of input and \n%   output membership functions dependeding on mf's value.\n\nswitch mf\n    case 'sigmf'\n        % NaN's value of sig_par means its automatic calculation\n        if isnan(sig_par)\n            sigma = std(X);\n            sig_par = scale / sigma;\n        end\n        mfparams = [sig_par, y];\n    case 'gaussmf'\n        sigma = std(y);\n        % Check if y is a scalar or consists of identical elements\n        if sigma == 0\n            sigma = sqrt(eps);\n        end\n        c = mean(y);\n        mfparams = [sigma, c];\n    case 'linear'\n        numData = size(X, 1);\n        A = [X, ones(numData, 1)];\n        % Using pinv instead of ldivide avoids\n        % warning if A is close to singular\n        mfparams = (pinv(A) * y)';\n    otherwise\n        error('FuzzyLogic:invalidmftype', ...\n            'Unknown type of membership function specified.');\nend\n\nfunction pr = minmax(p)\n%MINMAX Ranges of matrix rows.\n%\n%  Syntax\n%\n%    pr = minmax(p)\n%\n%  Description\n%\n%    MINMAX(P) takes one argument,\n%      P - RxQ matrix.\n%    and returns the Rx2 matrix PR of minimum and maximum values\n%    for each row of P.\n%\n%    Alternately, P can be an MxN cell array of matrices.  Each matrix\n%    P{i,j} should have Ri rows and Q columns.  In this case, MINMAX returns\n%    an Mx1 cell array where the mth matrix is an Rix2 matrix of the\n%    minimum and maximum values of elements for the matrics on the\n%    ith row of P.\n%\n%  Examples\n%\n%    p = [0 1 2; -1 -2 -0.5]\n%    pr = minmax(p)\n%\n%    p = {[0 1; -1 -2] [2 3 -2; 8 0 2]; [1 -2] [9 7 3]};\n%    pr = minmax(p)\n\nif iscell(p)\n    m = size(p, 1);\n    pr = cell(m, 1);\n    for i = 1 : m\n        pr{i} = minmax([p{i, :}]);\n    end\nelseif isa(p, 'double')\n    pr = [min(p, [], 2), max(p, [], 2)];\nelse\n    error('Argument has illegal type.');\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/28393-fuzzy-cart/fcart/genfis4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5873158166130678}}
{"text": "function [data, Ht] = rarch_simulate(T,C,parameters,p,q,type)\n% Simulation of RARCH(p,q) multivariate volatility model of Noureldin, Shephard and Sheppard\n%\n% USAGE:\n%  [DATA,HT] = rarch_simulate(T,C,PARAMETERS,P,Q,TYPE)\n%\n% INPUTS:\n%   T          - Either a scalar containing the length of the series to simulate, or a T by K matrix \n%                  of simulated random variables.  The default is to use standard normal random \n%                  variables.  Providing a T by K matrix allows other distributions to be used.\n%   C          - Unconditional covariance of the data\n%   PARAMETERS - Vector of parameters governing the dynamics.  The form of the parameters depends on the TYPE.  \n%                  'Scalar':\n%                  [a(1) ... a(p) b(1) ... b(q)]'  (all scalars)\n%                  'CP' :\n%                  [diag(A(:,:,1))' ... diag(A(:,:,p))' theta]' (theta is the scalar persistence)\n%                  'Diagonal' \n%                  [diag(A(:,:,1))' ... diag(A(:,:,p))' diag(B(:,:,1))' ... diag(B(:,:,p))']'\n%   P          - Positive, scalar integer representing the number of symmetric innovations\n%   Q          - Non-negative, scalar integer representing the number of conditional covariance\n%                  lags.  When using 'CP' model, 0<=q<=1\n%   TYPE       - String, one of :\n%                  'Scalar' (Default) \n%                  'CP' (Common Persistence) \n%                  'Diagonal'\n%\n% OUTPUTS:\n%   DATA   - A T by K matrix of simulated data\n%   HT     - A [K K T] dimension matrix of conditional covariances\n%\n% COMMENTS:\n%   The dynamics of a RARCH model are identical to that of a BEKK, except\n%   that the model evolves in the rotated space.\n%   \n%   G(:,:,t) = (eye(K) - sum(A.^2,3) - sum(B.^2,3)) +\n%       A(:,:,1)*OP(:,:,t-1)*A(:,:,1) + ... A(:,:,p)*OP(:,:,t-1)*A(:,:,p) +\n%       B(:,:,1)*G(:,:,t-1)*B(:,:,1) + ... B(:,:,p)*OP(:,:,t-1)*B(:,:,p)\n%\n%   where in the scalar model A(:,:,i) = a(i)*eye(K), B(:,:,j)=b(j)*eye(K)\n%   and in the CP model, B(:,:,j) = theta - sum(A.^2,3).  OP is the outer product of the\n%   unconditionally standardized data.\n%\n% EXAMPLES:\n%   % Scalar with A.^2=.05 and B.^2=.93\n%   [data,Ht] = rarch_simulate(1000,eye(2)+1,sqrt([.05,.93]),1,1,'Scalar')\n%   % Diagonal \n%   [data,Ht] = rarch_simulate(1000,eye(2)+1,sqrt([.05 .07 .93 .88]),1,1,'Diagonal')\n%   % Common Persistence, note uses theta (sqrt(A.^2+B.^2) not B)\n%   [data,Ht] = rarch_simulate(1000,eye(2)+1,sqrt([.05 .07 .99]),1,1,'CP')\n%\n% See also RARCH\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 3/27/2012\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nk = size(C,1);\nif isscalar(T)\n    e = randn(2*T,k);\nelse\n    e = T;\n    if size(e,2)~=k\n        error('T must have K columns when providing simulated random numbers.')\n    end\n    T = size(e,1);\n    e = [e(ceil(rand(T,1)*T),:);e];\nend\n\nif strcmpi(type,'Scalar')\n    type = 1;\nelseif strcmpi(type,'CP')\n    type = 2;\nelseif strcmpi(type,'Diagonal')\n    type = 3;\nelse\n    error('TYPE must be ''Scalar'', ''CP'' or  ''Diagonal''.')\nend\n\nif type==2 && q>1\n    error('Q must be either 0 or 1 for the ''CP'' model.')\nend\n\nswitch type\n    case 1\n        count = p+q;\n    case 2\n        count = p*k+q;\n    case 3\n        count = (p+q)*k;\nend\nif length(parameters)~=count\n    error('PARAMETERS does not have the expected number of elements.')\nend\n[C,A,B] = rarch_parameter_transform(parameters,p,q,k,C,type,false);\nif max(diag(sum(A.^2,3)+sum(B.^2,3)))>=1\n    warning('MFE:nonstationary','The parameters do not correspond to the stationary region.')\nend\nif type==2 && q==1 && min(B(:))<0\n    error('When using ''CP'', the common persistence parameter Theta must satisfy Theta^2>=sum(A.^2,3)')\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nGt = repmat(eye(k),[1 1 2*T]);\nintercept = eye(k) - sum(A.^2,3) - sum(B.^2,3);\nbackCast = eye(k);\nfor i=1:(2*T)\n    Gt(:,:,i) = intercept;\n    for j=1:p\n        if (i-j)<=0\n            Gt(:,:,i) = Gt(:,:,i) + A(:,:,j)*backCast*A(:,:,j);\n        else\n            Gt(:,:,i) = Gt(:,:,i) + A(:,:,j)*(e(i-j,:)'*e(i-j,:))*A(:,:,j);\n        end\n    end\n    for j=1:q\n        if (i-j)<=0\n            Gt(:,:,i) = Gt(:,:,i) + B(:,:,j)*backCast*B(:,:,j);\n        else\n            Gt(:,:,i) = Gt(:,:,i) + B(:,:,j)*Gt(:,:,i-j)*B(:,:,j);\n        end\n    end\n    Gt12 = Gt(:,:,i)^(0.5);\n    e(i,:) = e(i,:)*Gt12;\nend\n\ndata = zeros(size(e));\nHt = zeros(k,k,T);\nC12 = C^(0.5);\nfor i=1:length(e)\n    data(i,:) = e(i,:)*C12;\n    Ht(:,:,i) = C12*Gt(:,:,i)*C12;\nend\n\ndata = data(T+1:2*T,:);\nHt = Ht(:,:,T+1:2*T);", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/multivariate/rarch_simulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5873158059695566}}
{"text": "%DEMO_SVI_REGRESSION  A toy data regression example for sparse SVI GP\n%\n%  Description\n%    Demonstration of sochastic variational inference GP model regression.\n%    The problem is similar as in the Hensman et. al (2013). The dataset is\n%    made synthetically in two dimensions using sinusoidal functions.\n%\n%  See also\n%    DEMO_SVI_CLASSIFIC\n%\n%  References:\n%    Hensman, J., Fusi, N. and Lawrence, N. D. (2013). Gaussian processes\n%    for big data. arXiv preprint arXiv:1309.6835.\n\n% Copyright (c) 2014 Tuomas Sivula\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% Generate toy data\nn = 2000;\ns2 = 0.01;\n% Training samples\nx = rand(n,2)*2*pi - pi;\ny = sin(x(:,1)).*sin(x(:,2)) + sqrt(s2).*randn(n,1);\n% Test samples\nnt = 100;\nxt = rand(nt,2)*2*pi - pi;\nyt = sin(xt(:,1)).*sin(xt(:,2));\n\n% Prediction grid\n[X1,X2] = meshgrid(-4:0.2:4, -4:0.2:4);\ngrid = [X1(:), X2(:)];\n\n% Build gp structure\ngp = gp_set('lik',lik_gaussian, 'cf', gpcf_sexp, 'latent_method', 'SVI');\n% Optimise\nnu = 50;    % The number of inducing inputs\nmaxi = 150; % The maximum number of iteration rounds\n[gp, diagnosis] = svigp(gp,x,y,'xt',xt,'yt',yt,'nu',nu,'maxiter',maxi);\n% Predict\nEft = gpsvi_pred(gp,x,y,grid);\n\n% ------- Plot --------\n% Prediction\nfigure()\ncontour(X1, X2, reshape(Eft, size(X1)), 16)\nhold on\nscatter(x(:,1), x(:,2), 20, y, 'filled')\nscatter(gp.X_u(:,1), gp.X_u(:,2), 30)\nlegend('Eft', 'data', 'Z')\n% Convergence analysis\nfigure()\nsubplot(3,1,1)\nplot(mean(diagnosis.e,2))\ntitle('energy')\nsubplot(3,1,2)\nplot(diagnosis.mlpd)\ntitle('mean log predictive density')\nsubplot(3,1,3)\nplot(diagnosis.rmse)\ntitle('root mean square error')\nxlabel('iteration')\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_svi_regression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.587315800504831}}
{"text": "function varargout = warpvars_vbmc(varargin)\n%WARPVARS Linear and nonlinear transformation of variables.\n%\n%  TRINFO = PDFTRANS(NVARS,LB,UB) returns the transformation structure \n%  TRINFO for a problem with NVARS dimensions and lower/upper bounds\n%  respectively LB and UB. LB and UB are either scalars or row arrays that \n%  can contain real numbers and Inf's\n%  The ordering LB <= UB needs to hold coordinate-wise.\n%\n%  Variables with lower or upper bounds are transformed via a log transform.\n%  Variables with both lower and upper bounds are transformed via a logit\n%  transform. \n%\n%  Y = TRANSVARS(X,'dir',TRINFO) performs direct transform of constrained \n%  variables X into unconstrained variables Y according to transformation \n%  encoded in structure TRINFO. X must be a N x NVARS array, where N is the \n%  number of input data and NVARS is the number of dimensions.\n%\n%  X = TRANSVARS(Y,'inv',TRINFO) performs inverse transform of unconstrained \n%  variables Y into constrained variables X.\n%\n%  P = TRANSVARS(Y,'prob',TRINFO) returns probability multiplier for the \n%  original pdf evaluated at f^{-1}(Y), that is | df^{-1}(y) / dy |.\n%\n%  LP = TRANSVARS(Y,'logprob',TRINFO) returns log probability term for the \n%  original log pdf evaluated at f^{-1}(Y).\n\n%  Author: Luigi Acerbi\n%  e-mail: luigi.acerbi@gmail.com\n\nif nargin < 3\n    error('TRANSVARS requires a minimum of three input arguments.');\nend\n\n%% Transform variables\nif nargin == 3 && (isstruct(varargin{3}) || ischar(varargin{2}))\n    \n    Tol = sqrt(eps);    % Small number\n    \n    action = varargin{2};\n    trinfo = varargin{3};\n\n    if isempty(action)\n        error('The transformation direction cannot be empty. Allowed values are direct (''dir'' or ''d'') and inverse (''inv'' or ''i'').');\n    end\n\n    if isempty(trinfo)\n        % Empty TRINFO - consider as identity transformation\n\n        x = varargin{1};\n        \n        switch lower(action(1))\n            case {'d','i'}\n                varargout{1} = x;\n            case 'p'\n                varargout{1} = ones(size(x,1),1);\n            case 'l'\n                varargout{1} = zeros(size(x,1),1);\n            case {'m','f','g'}\n                error('TRINFO is empty.');\n            otherwise\n                error(['Unkwnown transformation direction ''' action '''. Allowed values are direct (''dir'' or ''d'') and inverse (''inv'' or ''i'').']);\n        end\n    else\n                \n        scale = [];\n        if isfield(trinfo,'scale') && ~isempty(trinfo.scale) && any(trinfo.scale ~= 1)\n            scale = trinfo.scale;\n        end\n\n        if ~isfield(trinfo,'R_mat'); trinfo.R_mat = []; end\n        \n        nvars = numel(trinfo.lb_orig);  % Number of variables\n        \n        switch lower(action(1))\n        %% DIRECT TRANSFORM\n            case 'd'    % Direct transform\n                x = varargin{1};            \n                y = x;\n                a = trinfo.lb_orig;\n                b = trinfo.ub_orig;\n                mu = trinfo.mu;\n                delta = trinfo.delta;\n                \n                % Unbounded scalars (possibly center and rescale)\n                idx = trinfo.type == 0;\n                if any(idx)\n                    y(:,idx) = bsxfun(@rdivide,bsxfun(@minus,x(:,idx),mu(idx)),delta(idx));\n                end\n\n                % Lower bounded scalars\n                idx = trinfo.type == 1;\n                if any(idx)\n                    y(:,idx) = log(bsxfun(@minus, x(:,idx), a(idx)));\n                end\n\n                % Upper bounded scalars\n                idx = trinfo.type == 2;\n                if any(idx)\n                    y(:,idx) = log(bsxfun(@minus, b(idx), x(:,idx)));\n                end\n\n                % Lower and upper bounded scalars\n                idx = trinfo.type == 3;\n                if any(idx)\n                    z = bsxfun(@rdivide, bsxfun(@minus, x(:,idx), a(idx)), ...\n                        b(idx) - a(idx)); \n                    y(:,idx) = log(z./(1-z));\n                    y(:,idx) = bsxfun(@rdivide,bsxfun(@minus,y(:,idx),mu(idx)),delta(idx));\n                end\n                \n                % Lower and upper bounded scalars with Beta CDF transform\n                idx = trinfo.type == 4;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;\n                    for ii = find(idx)\n                        % z = betacdf((x(:,ii) - a(ii)) / (b(ii) - a(ii)),alpha(ii),beta(ii));\n                        z = min(max(eps,betacdf((x(:,ii) - a(ii)) / (b(ii) - a(ii)),alpha(ii),beta(ii))),1-eps);\n                        y(:,ii) = log(z./(1-z));\n                    end\n                end\n\n                % Lower and upper bounded scalars with Kumaraswamy CDF transform\n                idx = trinfo.type == 5;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;\n                    for ii = find(idx)\n                        % z = kumarcdf((x(:,ii) - a(ii)) / (b(ii) - a(ii)),alpha(ii),beta(ii));\n                        % p = min(max(eps,kumarcdf(z,alpha(ii),beta(ii))),1-eps);\n                        % y(:,ii) = log(p./(1-p));\n                        z = (x(:,ii) - a(ii)) / (b(ii) - a(ii));\n                        % p = 1 - (1 - z.^alpha(ii)).^beta(ii);\n                        y(:,ii) = log1p(-(1 - z.^alpha(ii)).^beta(ii)) - beta(ii)*log1p(-z.^alpha(ii));\n                    end\n                     y(:,idx) = bsxfun(@rdivide,bsxfun(@minus,y(:,idx),mu(idx)),delta(idx));\n                end\n\n                % Lower and upper bounded scalars with Kumaraswamy-logistic-power transform\n                idx = trinfo.type == 6;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;\n                    mu = trinfo.mu;\n                    gamma = trinfo.gamma;\n                    for ii = find(idx)\n                        z = (x(:,ii) - a(ii)) / (b(ii) - a(ii));\n                        y(:,ii) = log1p(-(1 - z.^alpha(ii)).^beta(ii)) - beta(ii)*log1p(-z.^alpha(ii)) - mu(ii);\n                        y(:,ii) = sign(y(:,ii)).*abs(y(:,ii)).^gamma(ii);\n                    end\n                end\n                \n                % Lower and upper bounded scalars with nonparametric CDF transform\n                idx = trinfo.type == 7;\n                if any(idx)\n                    xspace = trinfo.xspace;\n                    pspace = trinfo.pspace;\n                    for ii = find(idx)\n                        y(:,ii) = norminv(interp1(xspace(ii,:),pspace(ii,:),x(:,ii)));\n                    end\n                end\n\n                % Lower and upper bounded scalars with GMM CDF transform\n                idx = trinfo.type == 8;\n                if any(idx)\n                    for ii = find(idx)\n                        gmm = trinfo.gmm{ii};\n                        z = (x(:,ii) - a(ii)) / (b(ii) - a(ii));\n                        z = gmm.lambda*z + (1-gmm.lambda)*(gmm1cdf(z,gmm.w,gmm.Mu,gmm.Sigma)-gmm.Min)./gmm.Norm;\n                        y(:,ii) = norminv(z);\n                        % y(:,ii) = logiinv(z);\n                    end\n                end\n                \n                % Lower and upper bounded scalars with Kumaraswamy-logit transform\n                idx = trinfo.type == 9;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;\n                    for ii = find(idx)\n                        z = (x(:,ii) - a(ii)) / (b(ii) - a(ii));\n                        u = z.^(alpha(ii));\n                        \n                        % Small u (close to zero)\n                        uzero = u < sqrt(eps);\n                        y(uzero,ii) = log(beta(ii)) + alpha(ii)*log(z(uzero)) + 0.5*u(uzero)*(beta(ii)+1) + 0.5*((beta(ii)-1)^2/4-beta(ii))*u(uzero).^2;\n                        \n                        % Large u (close to 1)\n                        uone = u > (1 - sqrt(eps));\n                        y(uone,ii) = log(1./(1 - u(uone)).^beta(ii) - 1);\n                        \n                        % Other values\n                        y(~uzero & ~uone,ii) = log1p(-(1 - z(~uzero & ~uone).^alpha(ii)).^beta(ii)) - beta(ii)*log1p(-z(~uzero & ~uone).^alpha(ii));\n                    end\n                end\n                \n                % Unbounded with logistic-Kumaraswamy-logit transform\n                idx = trinfo.type == 10;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;\n                    for ii = find(idx)\n                        z = (x(:,ii)-mu(:,ii)) ./ delta(:,ii);\n                        %z = exp(z)./(exp(z)+1);\n                        %y(:,ii) = log1p(-(1 - z.^alpha(:,ii)).^beta(:,ii)) - beta(:,ii).*log1p(-z.^alpha(:,ii));\n                        s = 1./(1+exp(-z));\n                        u = s.^alpha(ii);\n                        \n                        % Small u (near zero)\n                        uzero = u < Tol;\n                        %y(uzero,ii) = log(beta(ii)) + alpha(ii)*log(s(uzero)) + beta(ii)*u(uzero);\n                        y(uzero,ii) = log(beta(ii)) + alpha(ii)*z(uzero) + beta(ii)*u(uzero);\n                        \n                        % Large u (near one)\n                        uone = u > (1 - Tol);\n                        w = 1./(1 + exp(z(uone)));\n                        y(uone,ii) = -log(alpha(ii)) + beta(ii)*z(uone) - (alpha(ii)*w).^beta(ii);\n                        \n                        % All other cases\n                        urest = ~uzero & ~uone;\n                        y(urest,ii) = log1p(-(1 - s(urest).^alpha(ii)).^beta(ii)) - beta(ii).*log1p(-s(urest).^alpha(ii));\n                    end\n                end\n                \n                % Lower and upper bounded scalars with Kumaraswamy-logit inverse CDF transform\n                idx = trinfo.type == 11;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;\n                    for ii = find(idx)\n                        % z = kumarinv((x(:,ii) - a(ii)) / (b(ii) - a(ii)),alpha(ii),beta(ii));\n                        % p = min(max(eps,kumarcdf(z,alpha(ii),beta(ii))),1-eps);\n                        % y(:,ii) = log(p./(1-p));\n                        z = (x(:,ii) - a(ii)) / (b(ii) - a(ii));\n                        % p = 1 - (1 - z.^alpha(ii)).^beta(ii);\n                        % y(:,ii) = 1./alpha(ii).*log1p(-(1 - z).^(1./beta(ii))) - log1p(-(1-(1-z).^(1./beta(ii))).^(1./alpha(ii)));\n                        u = (1./beta(ii)).*log1p(-z);\n                        \n                        uidx = u < log(eps)/2;\n                        % u(uidx) = 1 - 1./alpha(ii).*exp(u(uidx));\n                        y(uidx,ii) = -1./alpha(ii).*exp(u(uidx)) + log(alpha(ii)) - u(uidx);\n                        % u(~uidx) = (1 - exp(u(~uidx))).^(1/alpha(ii));\n                        y(~uidx,ii) = (1/alpha(ii)).*log1p(-exp(u(~uidx))) - log1p(-(1 - exp(u(~uidx))).^(1/alpha(ii)));\n                        usmall = abs(u) < sqrt(eps);\n                        y(usmall,ii) = (1/alpha(ii)).*log(-u(usmall)) - log1p(-u(usmall)/alpha(ii));                        \n                        \n                        % y(:,ii) = log(expm1(-1./alpha(ii).*log1p(-(1-z).^(1./beta(ii)))));\n                        y(:,ii) = bsxfun(@rdivide,bsxfun(@minus,y(:,ii),mu(ii)),delta(ii));\n                    end\n                end\n                \n                % Lower and upper bounded scalars (cumulative normal)\n                idx = trinfo.type == 12;\n                if any(idx)\n                    z = bsxfun(@rdivide, bsxfun(@minus, x(:,idx), a(idx)), ...\n                        b(idx) - a(idx));                    \n                    y(:,idx) = -sqrt(2).*erfcinv(2*z);                    \n                    y(:,idx) = bsxfun(@rdivide,bsxfun(@minus,y(:,idx),mu(idx)),delta(idx));\n                end\n\n                % Lower and upper bounded scalars (Student-t, nu = 4)\n                idx = trinfo.type == 13;\n                if any(idx)\n                    z = bsxfun(@rdivide, bsxfun(@minus, x(:,idx), a(idx)), ...\n                        b(idx) - a(idx));                    \n                    aa = sqrt(4*z.*(1-z));\n                    q = cos(acos(aa)/3)./aa;                    \n                    y(:,idx) = sign(z - 0.5).*(2.*sqrt(q-1));\n                    y(:,idx) = bsxfun(@rdivide,bsxfun(@minus,y(:,idx),mu(idx)),delta(idx));\n                end\n                \n                % Rotate output\n                if ~isempty(trinfo.R_mat); y = y*trinfo.R_mat; end\n                \n                % Rescale output\n                if ~isempty(scale); y = bsxfun(@rdivide,y,scale); end\n                \n                varargout{1} = y;\n                \n            %% INVERSE TRANSFORM\n            case 'i'    % Inverse transform\n                y = varargin{1};                \n                % Rescale input\n                if ~isempty(scale); y = bsxfun(@times,y,scale); end\n                \n                % Rotate input\n                if ~isempty(trinfo.R_mat); y = y*trinfo.R_mat'; end        \n                                \n                x = y;\n                a = trinfo.lb_orig;\n                b = trinfo.ub_orig;\n                mu = trinfo.mu;\n                delta = trinfo.delta;                \n\n                % Unbounded scalars (possibly unscale and uncenter)\n                idx = trinfo.type == 0;\n                if any(idx)\n                    x(:,idx) = bsxfun(@plus,bsxfun(@times,y(:,idx),delta(idx)),mu(idx));\n                end\n                \n                % Lower bounded scalars\n                idx = trinfo.type == 1;\n                if any(idx)\n                    x(:,idx) = bsxfun(@plus, exp(y(:,idx)), a(idx));\n                end\n\n                % Upper bounded scalars\n                idx = trinfo.type == 2;\n                if any(idx)\n                    x(:,idx) = bsxfun(@minus, b(idx), exp(y(:,idx)));\n                end\n\n                % Lower and upper bounded scalars\n                idx = trinfo.type == 3;\n                if any(idx)\n                    x(:,idx) = bsxfun(@plus,bsxfun(@times,y(:,idx),delta(idx)),mu(idx));\n                    x(:,idx) = bsxfun(@plus, a(:,idx), bsxfun(@times, ...\n                        b(idx)-a(idx), 1./(1+exp(-x(:,idx)))));\n                end\n                \n                % Lower and upper bounded scalars with Beta CDF transform\n                idx = trinfo.type == 4;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;\n                    for ii = find(idx)\n                        z = 1./(1+exp(-y(:,ii)));\n                        x(:,ii) = a(ii) + (b(ii)-a(ii))*betainv(z,alpha(ii),beta(ii));\n                    end\n                end                \n\n                % Lower and upper bounded scalars with Kumaraswamy CDF transform\n                idx = trinfo.type == 5;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;\n                    y(:,idx) = bsxfun(@plus,bsxfun(@times,y(:,idx),delta(idx)),mu(idx));\n                    for ii = find(idx)\n                        % z = 1./(1+exp(-y(:,ii)));\n                        % x(:,ii) = a(ii) + (b(ii)-a(ii))*kumarinv(z,alpha(ii),beta(ii));\n                        z = exp(-y(:,ii))./(1+exp(-y(:,ii)));\n                        x(:,ii) = a(ii) + (b(ii)-a(ii))*(1-z.^(1/beta(ii))).^(1/alpha(ii));\n                    end\n                end\n                \n                % Lower and upper bounded scalars with Kumaraswamy-logistic-power transform\n                idx = trinfo.type == 6;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;\n                    mu = trinfo.mu;\n                    gamma = trinfo.gamma;                    \n                    for ii = find(idx)\n                        z = sign(y(:,ii)).*abs(y(:,ii)).^(1/gamma(ii)) + mu(ii);\n                        z = exp(-z)./(1+exp(-z));\n                        x(:,ii) = a(ii) + (b(ii)-a(ii))*(1-z.^(1/beta(ii))).^(1/alpha(ii));\n                    end\n                end\n                \n                % Lower and upper bounded scalars with nonparametric CDF transform\n                idx = trinfo.type == 7;\n                if any(idx)\n                    xspace = trinfo.xspace;\n                    pspace = trinfo.pspace;\n                    for ii = find(idx)\n                        x(:,ii) = interp1(pspace(ii,:),xspace(ii,:),normcdf(y(:,ii)));\n                    end\n                end\n\n                % Lower and upper bounded scalars with GMM CDF transform\n                idx = trinfo.type == 8;\n                if any(idx)                    \n                    for ii = find(idx)\n                        gmm = trinfo.gmm{ii};\n                        z = normcdf(y(:,ii));\n                        % z = logicdf(y(:,ii));\n                        for j = 1:size(z,1)\n                            z(j) = tgmminv(z(j),gmm);\n                        end\n                        x(:,ii) = a(ii) + (b(ii)-a(ii)).*z;\n                    end\n                end\n                \n                % Lower and upper bounded scalars with Kumaraswamy-logit transform\n                idx = trinfo.type == 9;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;\n                    for ii = find(idx)\n                        z = exp(-y(:,ii))./(1+exp(-y(:,ii)));   % 1 - logistic(z)\n                        x(:,ii) = a(ii) + (b(ii)-a(ii))*(1-z.^(1/beta(ii))).^(1/alpha(ii));\n                    end\n                end\n                \n                % Unbounded scalars with logistic-Kumaraswamy-logit transform\n                idx = trinfo.type == 10;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;                                        \n                    for ii = find(idx)\n                        % z = exp(-y(:,ii))./(1+exp(-y(:,ii)));   % 1 - logistic(z)\n                        % % z = (1-z.^(1/beta(ii))).^(1/alpha(ii));\n                        % z = 1./alpha(:,ii).*log1p(-z.^(1./beta(:,ii))) - log1p(-(1-z.^(1./beta(:,ii))).^(1./alpha(:,ii)));\n                        \n                        % Small u (~ zero)\n                        uzero = y(:,ii) < log(Tol);                        \n                        u = 1./(1 + exp(-y(uzero,ii)));\n                        %x(uzero,ii) = 1/alpha(ii)*(-log1p(exp(-y(uzero,ii)))-log(beta(ii))) - log1p(-(u/beta(ii)).^(1/alpha(ii)));\n                        x(uzero,ii) = 1/alpha(ii)*(y(uzero,ii)-log(beta(ii))) - log1p(-(u/beta(ii)).^(1/alpha(ii)));\n                        \n                        % Large u (~ one)\n                        uone = y(:,ii) > -log(Tol);\n                        w = 1./(1 + exp(y(uone,ii))).^(1/beta(ii));\n                        x(uone,ii) = 1/alpha(ii)*log1p(-w) + 1/beta(ii)*y(uone,ii) + log(alpha(ii));\n                        \n                        % All other cases\n                        urest = ~uzero & ~uone;\n                        z = 1./(1+exp(y(urest,ii)));\n                        x(urest,ii) = 1./alpha(:,ii).*log1p(-z.^(1./beta(:,ii))) - log1p(-(1-z.^(1./beta(:,ii))).^(1./alpha(:,ii)));\n                        \n                        x(:,ii) = x(:,ii).*delta(:,ii) + mu(:,ii);\n                    end\n                end\n                \n                % Lower and upper bounded scalars with Kumaraswamy inverse CDF transform\n                idx = trinfo.type == 11;\n                if any(idx)\n                    alpha = trinfo.alpha;\n                    beta = trinfo.beta;\n                    y(:,idx) = bsxfun(@plus,bsxfun(@times,y(:,idx),delta(idx)),mu(idx));\n                    for ii = find(idx)\n                        z = 1./(1+exp(-y(:,ii)));\n                        x(:,ii) = a(ii) + (b(ii)-a(ii))*(1 - (1-z.^(alpha(ii))).^beta(ii));\n                    end\n                end\n                                \n                % Lower and upper bounded scalars (cumulative normal)\n                idx = trinfo.type == 12;\n                if any(idx)\n                    x(:,idx) = bsxfun(@plus,bsxfun(@times,y(:,idx),delta(idx)),mu(idx));\n                    x(:,idx) = bsxfun(@plus, a(:,idx), bsxfun(@times, ...\n                        b(idx)-a(idx), 0.5 * erfc(-x(:,idx) ./ sqrt(2))));\n                end\n                  \n                % Lower and upper bounded scalars (Student-t, nu = 4)\n                idx = trinfo.type == 13;\n                if any(idx)\n                    x(:,idx) = bsxfun(@plus,bsxfun(@times,y(:,idx),delta(idx)),mu(idx));\n                    t2 = x(:,idx).^2;\n                    f = 0.5 + 3/8*x(:,idx)./sqrt(1 + t2/4).*(1 - t2./(1 + t2/4)/12);\n                    x(:,idx) = bsxfun(@plus, a(:,idx), bsxfun(@times, ...\n                        b(idx)-a(idx), f));\n                end\n                \n                % Force to stay within bounds\n                a(isfinite(a)) = a(isfinite(a)) + eps(a(isfinite(a)));\n                b(isfinite(b)) = b(isfinite(b)) - eps(b(isfinite(b)));\n                x = bsxfun(@min,bsxfun(@max,x,a),b);\n                varargout{1} = x;\n                \n            %% PDF (OR LOG PDF) CORRECTION           \n            case {'p','l','g'}  % pdf (or log pdf) correction\n                y = varargin{1};\n                % Rescale input\n                if ~isempty(scale); y = bsxfun(@times,y,scale); end\n\n                % Rotate input\n                if ~isempty(trinfo.R_mat); y = y*trinfo.R_mat'; end        \n                \n                logpdf_flag = strcmpi(action(1),'l');\n                if logpdf_flag\n                    p = zeros(size(y,1),nvars);\n                else\n                    p = ones(size(y,1),nvars);\n                end\n                grad_flag = strcmpi(action(1),'g');\n                \n                a = trinfo.lb_orig;\n                b = trinfo.ub_orig;\n                mu = trinfo.mu;\n                delta = trinfo.delta;                \n                \n                % Unbounded scalars\n                idx = trinfo.type == 0;\n                if any(idx)\n                    p(:,idx) = repmat(log(delta(idx)),[size(p,1),1]);\n                end\n                                \n                % Lower or upper bounded scalars\n                idx = trinfo.type == 1 | trinfo.type == 2;\n                if any(idx)\n                    p(:,idx) = y(:,idx);\n                end\n\n                % Lower and upper bounded scalars\n                idx = trinfo.type == 3;\n                if any(idx)\n                    y(:,idx) = bsxfun(@plus,bsxfun(@times,y(:,idx),delta(idx)),mu(idx));\n                    z = -log1p(exp(-y(:,idx)));\n                    p(:,idx) = bsxfun(@plus, log(b(idx)-a(idx)), -y(:,idx) + 2*z);\n                    p(:,idx) = bsxfun(@plus, p(:,idx), log(delta(idx)));\n                end\n                \n                % Lower and upper bounded scalars with Beta CDF transform\n                idx = trinfo.type == 4;\n                if any(idx)\n                    for ii = find(idx)\n                        alpha = trinfo.alpha;\n                        beta = trinfo.beta;\n\n                        z = -log1p(exp(-y(:,ii)));\n                        x = min(max(eps,betainv(1./(1+exp(-y(:,ii))),alpha(ii),beta(ii))),1-eps);\n                        logbeta = (alpha(ii)-1)*log(x) + (beta(ii)-1)*log1p(-x) ...\n                            + gammaln(alpha(ii)+beta(ii)) - gammaln(alpha(ii)) - gammaln(beta(ii));\n                        p(:,ii) = log(b(ii)-a(ii)) -logbeta -y(:,ii) + 2*z;\n\n                        if any(~isfinite(p))\n                            fprintf('aaaa!');\n                        end\n                    end\n                end\n                \n                % Lower and upper bounded scalars with Kumaraswamy CDF transform\n                idx = trinfo.type == 5;\n                if any(idx)\n                    for ii = find(idx)\n                        alpha = trinfo.alpha;\n                        beta = trinfo.beta;\n\n                        y(:,ii) = bsxfun(@plus,bsxfun(@times,y(:,ii),delta(ii)),mu(ii));\n                        \n                        z = -log1p(exp(-y(:,ii)));\n                        % x = kumarinv(1./(1+exp(-y(:,ii))),alpha(ii),beta(ii));\n\n                        %p = 1./(1+exp(-y(:,ii)));\n                        %x = (-((-(p-1)).^(1/beta(ii))-1)).^(1/alpha(ii));\n                        %log(-(p-1)) = -y(,::) - log1p(exp(-y(:,ii)))); \n\n\n                        %(1/beta(ii)).*log(-(p-1))\n\n                        % x = min(max(eps,kumarinv(1./(1+exp(-y(:,ii))),alpha(ii),beta(ii))),1-eps);\n                        u = 1./(1 + exp(-y(:,ii)));\n                        logf = (1-1/alpha(ii))*log1p(-(1-u).^(1/beta(ii))) + (1-1/beta(ii))*(-y(:,ii)+z) ...\n                            + log(alpha(ii)) + log(beta(ii));\n\n                        % Special case for very small u\n                        %idx_small = u < 1e12;\n                        %logf(idx_small) = (1-1/alpha(ii))*(-y(idx_small,ii) + z - log(beta(ii))) + (1-1/beta(ii))*(-y(idx_small,ii)+z(idx_small)) ...\n                        %    + log(alpha(ii)) + log(beta(ii));\n\n                        %logf = (alpha(ii)-1)*log(x) + (beta(ii)-1)*log1p(-x.^alpha(ii)) ...\n                        %    + log(alpha(ii)) + log(beta(ii));\n                        p(:,ii) = log(b(ii)-a(ii)) -logf -y(:,ii) + 2*z;\n                        p(:,ii) = bsxfun(@plus, p(:,ii), log(delta(ii)));\n\n                        if any(~isfinite(p))\n                            p(~isfinite(p)) = -Inf;\n                            fprintf('aaaa!');\n                        end\n                    end\n                end\n                \n                % Lower and upper bounded scalars with Kumaraswamy-logistic-power transform\n                idx = trinfo.type == 6;\n                if any(idx)\n                    for ii = find(idx)\n                        alpha = trinfo.alpha;\n                        beta = trinfo.beta;\n                        mu = trinfo.mu;\n                        gamma = trinfo.gamma;                        \n                        \n                        yl = sign(y(:,ii)).*abs(y(:,ii)).^(1/gamma(ii)) + mu(ii);\n\n                        z = -log1p(exp(-yl));\n                        u = 1./(1 + exp(-yl));\n                        logf = (1-1/alpha(ii))*log1p(-(1-u).^(1/beta(ii))) + (1-1/beta(ii))*(-yl+z) ...\n                            + log(alpha(ii)) + log(beta(ii));\n                        logf = logf + log(gamma(ii)) + (gamma(ii)-1)*log(abs(yl-mu(ii)));\n                        p(:,ii) = log(b(ii)-a(ii)) -logf -yl + 2*z;\n                    end\n                end\n                \n                % Lower and upper bounded scalars with nonparametric CDF transform\n                idx = trinfo.type == 7;\n                if any(idx)\n                    xspace = trinfo.xspace;\n                    pspace = trinfo.pspace;\n                    for ii = find(idx)\n                        z = -0.5*log(2*pi) -0.5*y(:,ii).^2;\n\n                        yinv = normcdf(y(:,ii));\n                        [~,pos] = histc(yinv,pspace(ii,:));\n                        dx = [-log(diff(xspace(ii,:))),Inf];                            \n                        logf = dx(pos);\n\n                        p(:,ii) = log(b(ii)-a(ii)) -logf(:) + z;\n                    end\n                end\n                \n                % Lower and upper bounded scalars with GMM CDF transform\n                idx = trinfo.type == 8;\n                if any(idx)\n                    for ii = find(idx)\n                        gmm = trinfo.gmm{ii};\n\n                        z = -0.5*log(2*pi) -0.5*y(:,ii).^2;\n                        % z = -y(:,ii) - 2*log1p(exp(-y(:,ii)));\n\n                        yinv = normcdf(y(:,ii));\n                        for j = 1:size(yinv,1); yinv(j) = tgmminv(yinv(j),gmm); end\n\n                        logf = log(gmm.lambda + (1-gmm.lambda)*gmm1pdf(yinv,gmm.w,gmm.Mu,gmm.Sigma)./gmm.Norm);\n\n                        p(ii) = log(b(ii)-a(ii)) - logf + z;\n\n                        if any(~isfinite(p))\n                            p(~isfinite(p)) = -Inf;\n                            fprintf('aaaa!');\n                        end\n                    end\n                end\n                \n                % Lower and upper bounded scalars with Kumaraswamy-logit transform\n                idx = trinfo.type == 9;\n                if any(idx)\n                    for ii = find(idx)\n                        alpha = trinfo.alpha;\n                        beta = trinfo.beta;                        \n                        nf = (b(ii)-a(ii))/alpha(ii)/beta(ii);\n                        k = 1./(1+exp(-y(:,ii)));\n                        \n                        logk = -log1p(exp(-y(:,ii)));\n                        log1mk = logk - y(:,ii);\n                        logz = 1/alpha(ii)*log1p(-(1-k).^(1/beta(ii)));\n                        \n                        % k small (close to zero)\n                        kzero = k < sqrt(eps);\n                        log1mk(kzero) = log1p(-k(kzero));\n                        logz(kzero) = 1/alpha(ii) * (logk(kzero)-log(beta(ii))) + 1/alpha(ii)*log1p(0.5*(1-1/beta(ii)*k(kzero)));\n                        \n                        %z = (1-(1-k).^(1/beta(ii))).^(1/alpha(ii));\n                        % 1 - z^alpha = (1-k).^(1/beta(ii))\n                        p(:,ii) = log(nf) + (1/beta(ii)-1) * log1mk + (1-alpha(ii))*logz -y(:,ii)+2*logk;\n                    end\n                end\n                \n                % Unbounded scalars with logistic-Kumaraswamy-logit transform\n                idx = trinfo.type == 10;\n                if any(idx)\n                    for ii = find(idx)\n                        alpha = trinfo.alpha;\n                        beta = trinfo.beta;\n\n                        lnf = log(delta(:,ii)./alpha(:,ii)./beta(:,ii));\n                        \n                        if 0\n                        \n\n                            u = 1./(1+exp(y(:,ii)));\n                            logu = -log1p(exp(y(:,ii)));\n                            z = (1-u.^(1./beta(:,ii))).^(1./alpha(:,ii));                        \n                            p(:,ii) = lnf + y(:,ii) + (1+1./beta(:,ii)).*logu - log1p(-u.^(1./beta(:,ii))) - log1p(-z);\n                            \n                        else\n\n                            p(:,ii) = lnf -y(:,ii) - 2*log1p(exp(-y(:,ii)));\n                            \n                            % Small u (~ zero)\n                            uzero = y(:,ii) < log(Tol);\n                            u = 1./(1 + exp(-y(uzero,ii)));\n                            % p(uzero,ii) = p(uzero,ii) - log(u/beta(ii)) + (1/beta(ii)-1)*log1p(-u);                            \n                            p(uzero,ii) = p(uzero,ii) - y(uzero,ii) + log(beta(ii)) + (1/beta(ii)-1)*log1p(-u);\n                            t = (1 - (1-u).^(1/beta(ii))).^(1/alpha(ii));                            \n                            p(uzero,ii) = p(uzero,ii) - log1p(-t);\n                            \n                            % Large u (~ one)\n                            uone = y(:,ii) > -log(Tol);\n                            w = 1./(1 + exp(y(uone,ii)));                            \n                            p(uone,ii) = p(uone,ii) - log1p(-w.^(1/beta(ii))) + y(uone,ii) + log(alpha(ii));\n                            \n                            % All other cases\n                            urest = ~uzero & ~uone;\n                            u = 1./(1 + exp(-y(urest,ii)));\n                            p(urest,ii) = p(urest,ii) - log1p(-(1-u).^(1/beta(ii))) + (1/beta(ii)-1)*log1p(-u);\n                            t = (1 - (1-u).^(1/beta(ii))).^(1/alpha(ii));\n                            p(urest,ii) = p(urest,ii) - log1p(-t);\n                            \n                            \n                        end\n                            \n                            \n                    end\n                end\n                \n                % Lower and upper bounded scalars with inverse Kumaraswamy logit CDF transform\n                idx = trinfo.type == 11;\n                if any(idx)\n                    for ii = find(idx)\n                        alpha = trinfo.alpha;\n                        beta = trinfo.beta;\n\n                        y(:,ii) = bsxfun(@plus,bsxfun(@times,y(:,ii),delta(ii)),mu(ii));\n                        \n                        y_large = y(:,ii) > -log(eps)/2;\n                        \n                        z = 1./(1+exp(-y(:,ii)));\n                        u = 1 - (1-z.^(alpha(ii))).^beta(ii);\n                        \n                        u(y_large) = 1 - alpha(ii)*exp(-beta(ii)*y(y_large,ii))./(1+alpha(ii)*beta(ii)*exp(-y(y_large,ii)));\n                        \n                        \n%                        z = -log1p(exp(-y(:,ii)));\n                        %u = 1./(1 + exp(-y(:,ii)));\n                        %u = a(ii) + (b(ii)-a(ii))*(1 - (1-u.^(alpha(ii))).^beta(ii));\n%                        logf = log(alpha(ii)) + log(beta(ii)) + (alpha(ii)-1).*log(u) + (beta(ii)-1) .* log1p(-u.^alpha(ii));\n                         logf = (1-1/alpha(ii))*log1p(-(1-u).^(1/beta(ii))) + (1-1/beta(ii))*log1p(-u) ...\n                             + log(alpha(ii)) + log(beta(ii));\n                         logf(y_large) = (1-1/alpha(ii))*log1p(-alpha(ii)*exp(-y(y_large,ii))./(1+alpha(ii)*exp(-y(y_large,ii)))) ...\n                             + (1-1/beta(ii))*log(alpha(ii)*exp(-beta(ii)*y(y_large,ii))./(1+alpha(ii)*beta(ii)*exp(-y(y_large,ii)))) ...\n                             + log(alpha(ii)) + log(beta(ii));\n                         \n%                         logf = (1-1/alpha(ii))*log1p(-(1-u).^(1/beta(ii))) + (1-1/beta(ii))*(-y(:,ii)+z) ...\n%                             + log(alpha(ii)) + log(beta(ii));\n\n                        w = log1p(-z);\n                        w(y_large) = -y(y_large,ii) - log1p(exp(-y(y_large,ii)));\n                        \n                        p(:,ii) = log(b(ii)-a(ii)) + logf + log(z) + w; %-y(:,ii) + 2*z;\n                        p(:,ii) = bsxfun(@plus, p(:,ii), log(delta(ii)));\n\n                        if any(~isfinite(p))\n                            p(~isfinite(p)) = -Inf;\n                            fprintf('aaaa!');\n                        end\n                    end\n                end\n\n                % Lower and upper bounded scalars (cumulative normal)\n                idx = trinfo.type == 12;\n                if any(idx)\n                    y(:,idx) = bsxfun(@plus,bsxfun(@times,y(:,idx),delta(idx)),mu(idx));\n                    z = -0.5*log(2*pi) - 0.5*y(:,idx).^2;\n                    p(:,idx) = bsxfun(@plus, log(b(idx)-a(idx)), z);\n                    p(:,idx) = bsxfun(@plus, p(:,idx), log(delta(idx)));\n                end\n\n                % Lower and upper bounded scalars (Student-t, nu = 4)\n                idx = trinfo.type == 13;\n                if any(idx)\n                    y(:,idx) = bsxfun(@plus,bsxfun(@times,y(:,idx),delta(idx)),mu(idx));\n                    z = log(3/8) - 5/2*log1p(y(:,idx).^2/4);\n                    p(:,idx) = bsxfun(@plus, log(b(idx)-a(idx)), z);\n                    p(:,idx) = bsxfun(@plus, p(:,idx), log(delta(idx)));\n                end\n                \n                %if ~isempty(trinfo.R_mat) && lower(action(1)) == 'g'\n                %    p = p*(trinfo.R_mat*diag();\n                %end\n                \n                % Scale transform\n                if ~isempty(scale) && ~grad_flag\n                    p = bsxfun(@plus,p,log(scale));\n                end\n                \n                if ~grad_flag; p = sum(p,2); end\n                if ~logpdf_flag; p = exp(p); end\n                \n                varargout{1} = p;\n                \n            %% FIRST DERIVATIVE WRT TRANSFORMATION PARAMETERS (ignores final rotation and scaling)\n            case {'f'} \n                y = varargin{1};\n                nvars = numel(trinfo.lb_orig);\n                \n                % Rescale input\n                if ~isempty(scale); y = bsxfun(@times,y,scale); end\n\n                % Rotate input\n                if ~isempty(trinfo.R_mat); y = y*trinfo.R_mat'; end        \n                \n                a = trinfo.lb_orig;\n                b = trinfo.ub_orig;\n                delta = trinfo.delta;                \n\n                % Lower and upper bounded scalars with Kumaraswamy-logit transform\n                % and unbounded scalars with logistic-Kumaraswamy-logit transform\n                idx = (trinfo.type == 9 | trinfo.type == 10);\n                if any(idx)\n                    for ii = find(idx)\n                        alpha = trinfo.alpha;\n                        beta = trinfo.beta;                        \n\n                        k = 1./(1+exp(-y(:,ii)));                        \n                        talpha = 1 - (1-k).^(1/beta(ii));                        \n                        logt = 1/alpha(ii) .* log1p(-(1-k).^(1/beta(ii)));\n                                                \n                        p(:,ii) = talpha.*beta(ii).*logt./(1-talpha)./k;\n                        p(:,ii+nvars) = -log1p(-talpha)./k;\n                    end\n                end\n                \n                varargout{1} = p;\n                \n            %% MIXED DERIVATIVE WRT TRANSFORMATION PARAMETERS of FIRST DERIVATIVE\n            % (ignores final rotation and scaling)          \n            case {'m'}\n                y = varargin{1};\n                nvars = numel(trinfo.lb_orig);\n                \n                % Rescale input\n                if ~isempty(scale); y = bsxfun(@times,y,scale); end\n\n                % Rotate input\n                if ~isempty(trinfo.R_mat); y = y*trinfo.R_mat'; end        \n                \n                a = trinfo.lb_orig;\n                b = trinfo.ub_orig;\n                delta = trinfo.delta;                \n\n                % Lower and upper bounded scalars with Kumaraswamy-logit transform\n                % and unbounded scalars with logistic-Kumaraswamy-logit transform\n                idx = (trinfo.type == 9 | trinfo.type == 10);\n                if any(idx)\n                    for ii = find(idx)\n                        alpha = trinfo.alpha;\n                        beta = trinfo.beta;                        \n\n                        k = 1./(1+exp(-y(:,ii)));                        \n                        talpha = 1 - (1-k).^(1/beta(ii));                        \n                        logt = 1/alpha(ii) .* log1p(-(1-k).^(1/beta(ii)));\n                        t = talpha.^(1/alpha(ii));\n                        \n                        if trinfo.type(ii) == 9\n                            nf = - 1./(b(ii) - a(ii)) ./ t;\n                        else\n                            nf = (t-1)./delta(ii);                       \n                        end                        \n                        den = 1 ./ k.^2 ./ (talpha-1) .* nf;                                                \n                        p(:,ii) = talpha.*beta(ii).*((-k.*(1+alpha(ii).*logt)) + talpha.*(1 + (1-k).*(-1+alpha(ii).*beta(ii).*logt))) ...\n                            .* den ./ (talpha - 1);\n                        p(:,ii+nvars) = talpha .* alpha(ii) .* (1 + (1-k).*(-1 - y(:,ii) - log1p(exp(-y(:,ii))))) ...\n                            .* den;\n                    end\n                end\n                \n                varargout{1} = p;\n                \n            otherwise\n                error(['Unkwnown transformation direction ''' action '''. Allowed values are direct (''dir'' or ''d'') and inverse (''inv'' or ''i'').']);\n        end\n    end\n    \nelse\n%% Create transform\n\n    nvars = varargin{1};\n    lb = varargin{2}(:)';\n    ub = varargin{3}(:)';\n    if nargin > 3\n        plb = varargin{4}(:)';\n        pub = varargin{5}(:)';\n    else\n        plb = []; pub = [];\n    end\n    if nargin > 5\n        bounded_type = varargin{6};\n    else\n        % Default bounded type is logit\n        bounded_type = 3;\n    end\n            \n    % Empty LB and UB are Infs\n    if isempty(lb); lb = -Inf; end\n    if isempty(ub); ub = Inf; end\n\n    % Empty plausible bounds equal hard bounds\n    if isempty(plb); plb = lb; end\n    if isempty(pub); pub = ub; end\n    \n    % Convert scalar inputs to row vectors\n    if isscalar(lb); lb = lb*ones(1,nvars); end\n    if isscalar(ub); ub = ub*ones(1,nvars); end\n    if isscalar(plb); plb = plb*ones(1,nvars); end\n    if isscalar(pub); pub = pub*ones(1,nvars); end\n    \n    % Check that the order of bounds is respected\n    assert(all(lb <= plb & plb < pub & pub <= ub), ...\n        'Variable bounds should be LB <= PLB < PUB <= UB for all variables.');\n    \n    % Transform to log coordinates\n    trinfo.lb_orig = lb;\n    trinfo.ub_orig = ub;\n    \n    trinfo.type = zeros(1,nvars);    \n    for i = 1:nvars\n        if isfinite(lb(i)) && isinf(ub(i)); trinfo.type(i) = 1; end\n        if isinf(lb(i)) && isfinite(ub(i)); trinfo.type(i) = 2; end\n        if isfinite(lb(i)) && isfinite(ub(i)) && lb(i) < ub(i); trinfo.type(i) = bounded_type; end\n    end\n    \n    % Centering (at the end of the transform)\n    trinfo.mu = zeros(1,nvars);\n    trinfo.delta = ones(1,nvars);\n    \n    % Get transformed PLB and PUB\n    plb = warpvars_vbmc(plb,'d',trinfo);\n    pub = warpvars_vbmc(pub,'d',trinfo);\n    \n    % Center in transformed space\n    for i = 1:nvars\n        if isfinite(plb(i)) && isfinite(pub(i))\n            trinfo.mu(i) = 0.5*(plb(i)+pub(i));\n            trinfo.delta(i) = (pub(i)-plb(i));\n        end\n    end\n        \n    varargout{1} = trinfo;\n    \nend\n\nend\n\n%--------------------------------------------------------------------------\nfunction y = tgmminv(p,gmm)\n    if p <= 0; p = eps; elseif p >= 1; p = 1 - eps; end    % Correct bounds\n    fun = @(z) tgmmfzero(z,p,gmm.w,gmm.Mu,gmm.Sigma,gmm.Min,gmm.iMax,gmm.Norm,gmm.lambda);\n    y = qfzero(fun,[-eps,1+eps]);\n    if y <= 0; y = eps; elseif y >= 1; y = 1 - eps; end    % Correct bounds\nend", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/shared/warpvars_vbmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818987, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5872610319226625}}
{"text": "function [kappa,k,theta0,P,b,ebuf,Zf,Zw] = celpana(x,L,M,c,cb,Pidx,bbuf,ebuf,Zf,Zw)\n%  celpana --> CELP analyzer (coder).\n%\n%    [kappa,k,theta0,P,b,ebuf,Zf,Zw] = celpana(x,L,M,c,cb,Pidx,bbuf,ebuf,Zf,Zw)\n%\n%    The function implements a CELP coder using the following steps:\n%\n%    (1) Find the reflection coefficients, kappa, using M'th order\n%    LP analysis on the signal frame x of length N.\n%\n%    (2) Find the coefficients of the filter function A(z/c) used in\n%    the perceptual weighting filter.\n%\n%    (3) Determine the excitation parameters k, theta0, P, and b, used\n%    to generate the excitation sequence, e(n). The parameters will be\n%    estimated in blocks of length L, so N/L values are obtained for\n%    the single input frame. Other inputs used here, are the Gaussian\n%    codebook given by the L-by-K matrix cb, the pitch search range\n%    Pidx(1) < P < Pidx(2), the last estimated b in bbuf, Pidx(2) previous\n%    excitation samples buffered in the vector ebuf, and Zf and Zw which\n%    are the memory hangover in the filters 1/A(z/c) and W(z) = A(z/c)/A(z),\n%    respectively.\n\nN = length(x);                          % Frame length.\nJ = N/L;                                % Number of sub-blocks.\n\nk      = zeros(J,1);\ntheta0 = zeros(J,1);\nP      = zeros(J,1);\nb      = zeros(J,1);\n\n[ar,xi,kappa,ehat] = lpcana(x,M);       % LP analysis of frame.\nac = lpcweight(ar,c);                   % Coefficients of filter A(z/c).\n\nfor (j=1:J)                             % Excitation sequence in blocks.\n  n = (j-1)*L+1:j*L;\n  [k(j),theta0(j),P(j),b(j),ebuf,Zf,Zw] = celpexcit(x(n),cb,Pidx,ar,ac,...\n                                                              bbuf,ebuf,Zf,Zw);\n  bbuf = b(j);                          % Last estimated 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/39038-celp-codec/CELP_done/celpana.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5872610299485463}}
{"text": "%  Figure 10.24      Feedback Control of Dynamic Systems, 6e\n%                        Franklin, Powell, Emami\n%\n%   fig10_24.m is a script to generate Fig. 10.24,   \n%   the transient response of the LQR symmetric rootlocus compensator \n%   of the satellite position control, non-colocated case WITH ESTIMATOR\n\n% parameter values\nm=[1, 0.1]; k=[0, 0.091] ; d=[0, 0.0036]; k1=[0, 0.4];\n% call function\n[f,g,h,j] = twomass(m,k,d);\ns=[f, g;h, 0];r=[0*g;1]; n=s\\r;nx=n(1:4);nu=n(5);\n% call function\n[f1,g,h,j] = twomass(m,k1,d);\n\n% form G(s)G(-s) model\na=[f, 0*f;\n-h'*h, -f'];\nb=[g;0*g];\nd=[0];\nc=[0*h, g'];\nhold off; clf\nP=eig(a-b*c*0.1621);\npc=P(real(P<0)==1);\nK=place(f,g,pc);\nnbar=nu+K*nx;\n% eig(f-g*K)\nP=eig(a-b*c*3.056e7);\npe=P(real(P<0)==1);\nL=place(f',h',pe)';\nac=f-g*K-L*h ;bc=L;cc=K;dc=0;\n[Aol,Bol,Col,Dol]=series(ac,bc,cc,dc,f,g,h,j);\n[acl,bcl,ccl,dcl]=feedback(f,g,h,j,ac,bc,cc,dc);\n[acl1,bcl,ccl,dcl]=feedback(f1,g,h,j,ac,bc,cc,dc);\nbcl= nbar*[g;g];\nt=0:.25:30;\nsyscl=ss(acl,bcl,ccl,dcl);\nstep(syscl,t); \nhold on; \ngtext('nominal case')\nsyscl1=ss(acl1,bcl,ccl,dcl);\nstep(syscl1,t) ;\ngtext('stiff-spring case');\ntitle('Fig. 10.24 Closed-loop step response for the SRL design with an estimator')\n%grid\nnicegrid\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig10_24.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.587261016140553}}
{"text": "function [err_N, sG] = ptv_nuclear_metric(volfix, voldef, pix_resolution, mask, singular_coefs, norm_type)\n    volsz = [size(voldef, 1), size(voldef, 2), size(voldef, 3)]; \n    npix = prod(volsz);\n    Nimgs = size(voldef, 5);\n    \n%     nuc_G = zeros(size(voldef), 'like', voldef);\n    err_N = 0;\n    \n%     imagesc([voldef(:,:, round(end/2), 1, 1), volfix(:,:, round(end/2), 1, 1)]); pause(0.02);\n%     imagesc([ mean(voldef(:,:, round(end/2), 1, :), 5)]); pause(0.02);\n    \n    if isempty(singular_coefs)\n        singular_coefs = fl(sqrt(1:Nimgs));\n        singular_coefs(1) = 0;\n    end\n    \n    if isempty(volfix)\n        X = reshape(voldef, [npix, Nimgs]);\n    else\n        X = reshape(cat(5, volfix, voldef), [npix, Nimgs+1]);\n        if numel(singular_coefs > 1)\n%             singular_coefs = [0, 1, singular_coefs(2:end)];\n%             singular_coefs = [fl(singular_coefs(1:end)); singular_coefs(end)];\n%             singular_coefs = fl(sqrt(1:(Nimgs+1)));\n%             singular_coefs\n        end\n    end\n    if ~isempty(mask)\n        mask = logical(mask > 0.5);\n        X = X(mask, :);\n    end\n    singular_coefs = singular_coefs(1 : min(numel(singular_coefs), size(X, 1)));\n    [sU, sS, sV] = svdecon(X);\n%     sS\n    diagS = diag(sS);\n    if false\n        sGt = sU * ( (diag(singular_coefs)) * sV');\n        err_N = sum(diagS(:) .* singular_coefs(:));\n    else\n        eps = 1e-4;\n%         eps=0.1;\n        G_sS = diagS ./ sqrt(diagS.^2 + eps);\n        sGt = sU * ( (diag(singular_coefs(:) .* G_sS(:))) * sV');\n        err_N = sum( sqrt(diagS.^2 + eps) .* singular_coefs(:));\n    end\n    \n%     if true\n%         sk1 = sqrt(1 : size(singular_coefs, 1));\n%         sk2 = sk1;\n%         sk2(1) = 0;\n%         \n%         sk3 = ones(size(singular_coefs, 1), 1);\n%         sk4 = sk3;\n%         sk4(1) = 0;\n%         \n%         size(sk1)\n%         subplot(221);\n%         itmp = reshape(sU * (diag(sk1) * sV'), [volsz, Nimgs]);\n%         imagesc(itmp(:,:, 70)); colorbar;\n%         \n%         subplot(222);\n%         itmp = reshape(sU * (diag(sk2) * sV'), [volsz, Nimgs]);\n%         imagesc(itmp(:,:, 70)); colorbar;\n%         \n%         subplot(223);\n%         itmp = reshape(sU * (diag(sk3) * sV'), [volsz, Nimgs]);\n%         imagesc(itmp(:,:, 70)); colorbar;\n%         \n%         subplot(224);\n%         itmp = reshape(sU * (diag(sk4) * sV'), [volsz, Nimgs]);\n%         imagesc(itmp(:,:, 70)); colorbar;\n%         \n%         pause(0.05);\n%         pause();\n%     end\n    \n    if isempty(volfix)\n        if ~isempty(mask)\n            sG = zeros([npix, Nimgs], 'like', voldef);\n            sG(mask, :) = reshape(sGt, [nnz(mask), Nimgs]);\n            sG = reshape(sG, [volsz, Nimgs]);\n        else\n            sG = reshape(sGt, [volsz, Nimgs]);\n        end\n    else\n        if ~isempty(mask)\n            sG = zeros([npix, Nimgs+1], 'like', voldef);\n            sG(mask, :) = reshape(sGt, [nnz(mask), Nimgs+1]);\n            sG = reshape(sG, [volsz, Nimgs+1]);\n        else\n            sG = reshape(sGt, [volsz, Nimgs+1]);\n        end\n        sG = sG(:,:,:, 2:end);\n    end\n    \n\nend", "meta": {"author": "visva89", "repo": "pTVreg", "sha": "c359620e3c8435392db02354274d6c74d682d437", "save_path": "github-repos/MATLAB/visva89-pTVreg", "path": "github-repos/MATLAB/visva89-pTVreg/pTVreg-c359620e3c8435392db02354274d6c74d682d437/ptv/ptv_nuclear_metric.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5872610121923207}}
{"text": "function d = mg_q1cd_supg(xy,ev,expe,eph,epw)\n%mg_q1cd_supg  streamline diffusion matrix generator for GMG \n%   d = mg_q1cd_supg(xy,ev,expe,eph,epw)\n%   input\n%           xy         vertex coordinate vector  \n%           ev         element mapping matrix\n%           expe       element peclet numbers        \n%           eph        flow specific element lengths \n%           epw        centroid evaluated wind \n%   output \n%           d          discrete streamline diffusion operator\n%\n%   IFISS function: DJS; 26 February 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage\n\n%   Analogous to femq1_cd_supg.m\nx=xy(:,1); y=xy(:,2);\nnvtx=length(x);\nnel=length(ev(:,1));\n%\n% find the elements where streamline diffusion is active\nacte = find(isfinite(expe)); nacte=length(acte);\n%\n% initialise global matrices\n      d = sparse(nvtx,nvtx);\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% loop over active and inactive elements    \n%      for iact = 1:nacte\n% ielem = acte(iact);\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\tend\n        de = zeros(nel,4,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         [flowx,flowy] = gauss_transprt(sigpt,tigpt,xl_v,yl_v);\n\t\t for j = 1:4\n               for i = 1:4\n    de(:,i,j) = de(:,i,j) + flowx(:).*dphidx(:,i).*flowx(:).*dphidx(:,j).*invjac(:);\n    de(:,i,j) = de(:,i,j) + flowy(:).*dphidy(:,i).*flowx(:).*dphidx(:,j).*invjac(:);\n    de(:,i,j) = de(:,i,j) + flowx(:).*dphidx(:,i).*flowy(:).*dphidy(:,j).*invjac(:);\n    de(:,i,j) = de(:,i,j) + flowy(:).*dphidy(:,i).*flowy(:).*dphidy(:,j).*invjac(:);\n               end\n\t    end\n% end of Gauss point loop\n         end\n%\n% scale with the appropriate parameter\n      acte = find(isfinite(expe));\n      factor = expe(acte); flow_h=eph(acte); flow_l2=epw(acte);\n\t  lpe =zeros(nel,1); lpe(acte)= factor.*(flow_h./flow_l2);\n\t\t for j = 1:4\n               for i = 1:4\n               de(:,i,j) = lpe(:) .* de(:,i,j);\n\t\t   end\n\t   end\n%   \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          d = d + sparse(nrow,ncol,de(:,krow,kcol),nvtx,nvtx);\n          end\n      end\n%\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_q1cd_supg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5872558625081454}}
{"text": "function [aVals,aJacob,aHess,papt]=aSpiralSimp(xPoints,numRetDims)\n%%ASPIRALSIMP The drift function for a non-ballistic spiraling target\n%         motion model in 3 dimensions, formulated in a manner such that it\n%         is simple to make a spiraling target follow a nominal trajectory.\n%         This model is probably bad to design into a target tracking\n%         algorithm, but might be good for designing spiraling trajectories\n%         to use to test target tracking algorithms.\n%\n%INPUTS: xPoints The target state at time t. It consists of position \n%                (3 elements), instantaneous velocity (3 elements), the\n%                velocity vector (3 elements) of the overall direction of\n%                motion of the spiraling model (ground speed) and the\n%                spiral rate of the target. Thus xDim=10. If x is an\n%                xDim X numStates matrix, then the spiraling model is\n%                evaluated for all of the state vectors. The last 4\n%                elements in xPoints are taken to be constants and thus\n%                aVal entries will be 0 for them. If only aVals is\n%                requested on the output, then xPoints can be a matrix of\n%                points.\n%     numRetDims If numRetDims=6, then the last 4 elements in xPoints (the\n%                velocity vector of the overall spiraling model and the\n%                spiral rate) are taken to be constants and the returned\n%                aVals Vec is 6X1. Otherwise, numRetDims can be 10 and\n%                aVals is 10X1. The default if omitted or an empty matrix\n%                is passed is 6.\n%\n%OUTPUTS: aVals The 6X1 (or 10X1 depending on numRetDims) flat-Earth time-\n%               derivative of the state. If xPoints was a matrix of N\n%               points, then this will be 6XN (or 10XN).\n%        aJacob The 6X6 (or 10X10) matrix of partial derivatives of aVals\n%               such that aJacob(:,k) is the partial derivative of\n%               aVals(:,k) with respect to\n%               xPoints(k). xPoints can't be a matrix if this output is\n%               requested.\n%         aHess The 6X6X6 (or 10X10X10) matrix of second derivatives of\n%               aVals such that aHess(:,k1,k2) is the second partial\n%               derivative of aVals with respect to xPoints(k1) and\n%               xPoints(k2).\n%          papt The 6X1 or 10X1 derivative with resect to time of aVals.\n%               This is all zeros, because the model is time invariant.\n%\n%A derivation of the simplified flat-Earth spiraling dynamic model is given\n%in [1].\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%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n    if(nargin<3||isempty(numRetDims))\n        numRetDims=6;\n    end\n\n    if(numRetDims<6||numRetDims>10)\n       error('numRetDims must be between 6 and 10.')\n    end\n\n    numPoints=size(xPoints,2);\n    aVals=zeros(numRetDims,numPoints);\n    \n    vl=xPoints(7:9,:);\n    omega=xPoints(10,:);\n    \n    vlMag2=sum(vl.*vl,1);\n    vlMag=sqrt(vlMag2);\n    \n    aVals(1:3,:)=xPoints(4:6,:);\n    vs=xPoints(4:6,:)-vl;\n    ul=bsxfun(@rdivide,vl,vlMag);\n    vsDot=omega.*bsxfun(@cross,ul,vs);\n    aVals(4:6,:)=vsDot;\n    \n    if(nargout>1)\n        rdotx=xPoints(4);\n        rdoty=xPoints(5);\n        rdotz=xPoints(6);\n\n        vlx=vl(1);\n        vly=vl(2);\n        vlz=vl(3);\n        \n        vlx2=vlx*vlx;\n        vly2=vly*vly;\n        vlz2=vlz*vlz;\n\n        vlMag2=vlMag*vlMag;\n        vlMag3=vlMag2*vlMag;\n        \n        pXrdy=-(omega*vlz)/vlMag;\n        pXrdz=(omega*vly)/vlMag;\n\n        pYrdx=(omega*vlz)/vlMag;\n        pYrdz=-((omega*vlx)/vlMag);\n\n        pZrdx=-((omega*vly)/vlMag);\n        pZrdy=(omega*vlx)/vlMag;\n\n        if(numRetDims==6)\n            aJacob=[0,0,0,1,        0,      0;\n                    0,0,0,0,        1,      0;\n                    0,0,0,0,        0,      1;\n                    0,0,0,0,        pXrdy,  pXrdz;\n                    0,0,0,pYrdx,    0,      pYrdz;\n                    0,0,0,pZrdx,    pZrdy,  0];\n        else\n            pXvx=(omega*vlx*(-rdotz*vly+rdoty*vlz))/vlMag3;\n            pXvy=(omega*(rdoty*vly*vlz+rdotz*(vlx2+vlz2)))/vlMag3;\n            pXvz=-((omega*(rdoty*(vlx2+vly2)+rdotz*vly*vlz))/vlMag3);\n\n            pXomega=(rdotz*vly-rdoty*vlz)/vlMag;\n\n            pYvx=-((omega*(rdotx*vlx*vlz+rdotz*(vly2+vlz2)))/vlMag3);\n            pYvy=(omega*vly*(rdotz*vlx-rdotx*vlz))/vlMag3;\n            pYvz=(omega*(rdotx*(vlx2+vly2)+rdotz*vlx*vlz))/vlMag3;\n            pYomega=(-rdotz*vlx+rdotx*vlz)/vlMag;\n            \n            pZvx=(omega*(rdotx*vlx*vly+rdoty*(vly2+vlz2)))/vlMag3;\n            pZvy=-((omega*(rdoty*vlx*vly+rdotx*(vlx2+vlz2)))/vlMag3);\n            pZvz=(omega*(-rdoty*vlx+rdotx*vly)*vlz)/vlMag3;\n            pZomega=(rdoty*vlx-rdotx*vly)/vlMag;\n\n            aJacob=[0,0,0,1,        0,      0,      0,      0,      0,      0;\n                    0,0,0,0,        1,      0,      0,      0,      0,      0;\n                    0,0,0,0,        0,      1,      0,      0,      0,      0;\n                    0,0,0,0,        pXrdy,  pXrdz,  pXvx,   pXvy,   pXvz,   pXomega;\n                    0,0,0,pYrdx,    0,      pYrdz,  pYvx,   pYvy,   pYvz,   pYomega;\n                    0,0,0,pZrdx,    pZrdy,  0,      pZvx,   pZvy,   pZvz,   pZomega;\n                    zeros(4,10)];\n        end\n\n        if(nargout>2)\n            aHess=zeros(numRetDims,numRetDims,numRetDims);\n \n            vlMag5=vlMag3*vlMag2;\n            \n            %Second deriavtives are all 0 if only \n            if(numRetDims>6)\n                pXrdyvx=(omega*vlx*vlz)/vlMag3;\n                pXrdyvy=(omega*vly*vlz)/vlMag3;\n                pXrdyvz=-((omega*(vlx2+vly2))/vlMag3);\n                pXrdyOmega=-(vlz/vlMag);\n\n                pXrdzvx=-((omega*vlx*vly)/vlMag3);\n                pXrdzvy=(omega*(vlx2+vlz2))/vlMag3;\n                pXrdzvz=-((omega*vly*vlz)/vlMag3);\n                pXrdzOmega=vly/vlMag;\n                \n                pXvxrdx=0;\n                pXvxrdy=pXrdyvx;\n                pXvxrdz=pXrdzvx;\n                pXvxvx=-((omega*(rdotz*vly-rdoty*vlz)*(-2*vlx2+vly2+vlz2))/vlMag5);\n                pXvxvy=-((omega*vlx*(3*rdoty*vly*vlz+rdotz*(vlx2-2*vly2+vlz2)))/vlMag5);\n                pXvxvz=(omega*vlx*(3*rdotz*vly*vlz+rdoty*(vlx2+vly2-2*vlz2)))/vlMag5;\n                pXvxOmega=(-rdotz*vlx*vly+rdoty*vlx*vlz)/vlMag3;\n\n                pXvyrdx=0;\n                pXvyrdy=pXrdyvy;\n                pXvyrdz=pXrdzvy;\n                pXvyvx=pXvxvy;\n                pXvyvy=(omega*(-3*rdotz*vly*(vlx2+vlz2)+rdoty*vlz*(vlx2-2*vly2+vlz2)))/vlMag5;\n                pXvyvz=(omega*(rdoty*vly*(vlx2+vly2-2*vlz2)-rdotz*vlz*(vlx2-2*vly2+vlz2)))/vlMag5;\n                pXvyOmega=(rdoty*vly*vlz+rdotz*(vlx2+vlz2))/vlMag3;\n\n                pXvzrdx=0;\n                pXvzrdy=pXrdyvz;\n                pXvzrdz=pXrdzvz;\n                pXvzvx=pXvxvz;\n                pXvzvy=pXvyvz;\n                pXvzvz=(omega*(3*rdoty*(vlx2+vly2)*vlz-rdotz*vly*(vlx2+vly2-2*vlz2)))/vlMag5;\n                pXvzOmega=(-rdoty*(vlx2+vly2)-rdotz*vly*vlz)/vlMag3;\n\n                pXOmegardx=0;\n                pXOmegardy=pXrdyOmega;\n                pXOmegardz=pXrdzOmega;\n                pXOmegavx=pXvxOmega;\n                pXOmegavy=pXvyOmega;\n                pXOmegavz=pXvzOmega;\n                pXOmegaOmega=0;\n\n                pYrdxvx=-((omega*vlx*vlz)/vlMag3);\n                pYrdxvy=-((omega*vly*vlz)/vlMag3);\n                pYrdxvz=(omega*(vlx2+vly2))/vlMag3;\n                pYrdxOmega=vlz/vlMag;\n\n                pYrdzvx=-((omega*(vly2+vlz2))/vlMag3);\n                pYrdzvy=(omega*vlx*vly)/vlMag3;\n                pYrdzvz=(omega*vlx*vlz)/vlMag3;\n                pYrdzOmega=-(vlx/vlMag);\n                                \n                pYvxrdx=pYrdxvx;\n                pYvxrdy=0;\n                pYvxrdz=pYrdzvx;\n                pYvxvx=(omega*(3*rdotz*vlx*(vly2+vlz2)-rdotx*vlz*(-2*vlx2+vly2+vlz2)))/vlMag5;\n                pYvxvy=(omega*vly*(3*rdotx*vlx*vlz+rdotz*(-2*vlx2+vly2+vlz2)))/vlMag5;\n                pYvxvz=(omega*(-rdotx*vlx*(vlx2+vly2-2*vlz2)+rdotz*vlz*(-2*vlx2+vly2+vlz2)))/vlMag5;\n                pYvxOmega=(-rdotx*vlx*vlz-rdotz*(vly2+vlz2))/vlMag3;\n\n                pYvyrdx=pYrdxvy;\n                pYvyrdy=0;\n                pYvyrdz=pYrdzvy;\n                pYvyvx=pYvxvy;\n                pYvyvy=(omega*(rdotz*vlx-rdotx*vlz)*(vlx2-2*vly2+vlz2))/vlMag5;\n                pYvyvz=-((omega*vly*(3*rdotz*vlx*vlz+rdotx*(vlx2+vly2-2*vlz2)))/vlMag5);\n                pYvyOmega=(vly*(rdotz*vlx-rdotx*vlz))/vlMag3;\n\n                pYvzrdx=pYrdxvz;\n                pYvzrdy=0;\n                pYvzrdz=pYrdzvz;\n                pYvzvx=pYvxvz;\n                pYvzvy=pYvyvz;\n                pYvzvz=(omega*(-3*rdotx*(vlx2+vly2)*vlz+rdotz*vlx*(vlx2+vly2-2*vlz2)))/vlMag5;\n                pYvzOmega=(rdotx*(vlx2+vly2)+rdotz*vlx*vlz)/vlMag3;\n            \n                pYOmegardx=pYrdxOmega;\n                pYOmegardy=0;\n                pYOmegardz=pYrdzOmega;\n                pYOmegavx=pYvxOmega;\n                pYOmegavy=pYvyOmega;\n                pYOmegavz=pYvzOmega;\n                pYOmegaOmega=0;\n                \n                pZrdxvx=(omega*vlx*vly)/vlMag3;\n                pZrdxvy=-((omega*(vlx2+vlz2))/vlMag3);\n                pZrdxvz=(omega*vly*vlz)/vlMag3;\n                pZrdxOmega=-(vly/vlMag);\n                                \n                pZrdyvx=(omega*(vly2+vlz2))/vlMag3;\n                pZrdyvy=-((omega*vlx*vly)/vlMag3);\n                pZrdyvz=-((omega*vlx*vlz)/vlMag3);\n                pZrdyOmega=vlx/vlMag;\n\n                pZvxrdx=pZrdxvx;\n                pZvxrdy=pZrdyvx;\n                pZvxrdz=0;\n                pZvxvx=(omega*(-3*rdoty*vlx*(vly2+vlz2)+rdotx*vly*(-2*vlx2+vly2+vlz2)))/vlMag5;\n                pZvxvy=(omega*(rdotx*vlx*(vlx2-2*vly2+vlz2)-rdoty*vly*(-2*vlx2+vly2+vlz2)))/vlMag5;\n                pZvxvz=-((omega*vlz*(3*rdotx*vlx*vly+rdoty*(-2*vlx2+vly2+vlz2)))/vlMag5);\n                pZvxOmega=(rdotx*vlx*vly+rdoty*(vly2+vlz2))/vlMag3;\n\n                pZvyrdx=pZrdxvy;\n                pZvyrdy=pZrdyvy;\n                pZvyrdz=0;\n                pZvyvx=pZvxvy;\n                pZvyvy=(omega*(3*rdotx*vly*(vlx2+vlz2)-rdoty*vlx*(vlx2-2*vly2+vlz2)))/vlMag5;\n                pZvyvz=(omega*vlz*(3*rdoty*vlx*vly+rdotx*(vlx2-2*vly2+vlz2)))/vlMag5;\n                pZvyOmega=(-rdoty*vlx*vly-rdotx*(vlx2+vlz2))/vlMag3;\n                \n                pZvzrdx=pZrdxvz;\n                pZvzrdy=pZrdyvz;\n                pZvzrdz=0;\n                pZvzvx=pZvxvz;\n                pZvzvy=pZvyvz;\n                pZvzvz=-((omega*(rdoty*vlx-rdotx*vly)*(vlx2+vly2-2*vlz2))/vlMag5);\n                pZvzOmega=(-rdoty*vlx*vlz+rdotx*vly*vlz)/vlMag3;\n\n                pZOmegardx=pZrdxOmega;\n                pZOmegardy=pZrdyOmega;\n                pZOmegardz=0;\n                pZOmegavx=pZvxOmega;\n                pZOmegavy=pZvyOmega;\n                pZOmegavz=pZvzOmega;\n                pZOmegaOmega=0;\n\n                aHess(:,:,4)=[zeros(3,10);\n                              0,0,0,0,0,0,  pXvxrdx,   pXvyrdx,   pXvzrdx,   pXOmegardx;\n                              0,0,0,0,0,0,  pYvxrdx,   pYvyrdx,   pYvzrdx,   pYOmegardx;\n                              0,0,0,0,0,0,  pZvxrdx,   pZvyrdx,   pZvzrdx,   pZOmegardx;\n                              zeros(4,10)];\n                aHess(:,:,5)=[zeros(3,10);\n                              0,0,0,0,0,0,  pXvxrdy,   pXvyrdy,   pXvzrdy,   pXOmegardy;\n                              0,0,0,0,0,0,  pYvxrdy,   pYvyrdy,   pYvzrdy,   pYOmegardy;\n                              0,0,0,0,0,0,  pZvxrdy,   pZvyrdy,   pZvzrdy,   pZOmegardy;\n                              zeros(4,10)];\n                aHess(:,:,6)=[zeros(3,10);\n                              0,0,0,0,0,0,  pXvxrdz,   pXvyrdz,   pXvzrdz,   pXOmegardz;\n                              0,0,0,0,0,0,  pYvxrdz,   pYvyrdz,   pYvzrdz,   pYOmegardz;\n                              0,0,0,0,0,0,  pZvxrdz,   pZvyrdz,   pZvzrdz,   pZOmegardz;\n                              zeros(4,10)];     \n                aHess(:,:,7)=[zeros(3,10);\n                              0,0,0,0,          pXrdyvx,  pXrdzvx,  pXvxvx,   pXvyvx,   pXvzvx,   pXOmegavx;\n                              0,0,0,pYrdxvx,    0,        pYrdzvx,  pYvxvx,   pYvyvx,   pYvzvx,   pYOmegavx;\n                              0,0,0,pZrdxvx,    pZrdyvx,  0,        pZvxvx,   pZvyvx,   pZvzvx,   pZOmegavx;\n                              zeros(4,10)];\n                aHess(:,:,8)=[zeros(3,10);\n                              0,0,0,0,          pXrdyvy,  pXrdzvy,  pXvxvy,   pXvyvy,   pXvzvy,   pXOmegavy;\n                              0,0,0,pYrdxvy,    0,        pYrdzvy,  pYvxvy,   pYvyvy,   pYvzvy,   pYOmegavy;\n                              0,0,0,pZrdxvy,    pZrdyvy,  0,        pZvxvy,   pZvyvy,   pZvzvy,   pZOmegavy;\n                              zeros(4,10)];\n                aHess(:,:,9)=[zeros(3,10);\n                              0,0,0,0,          pXrdyvz,  pXrdzvz,  pXvxvz,   pXvyvz,   pXvzvz,   pXOmegavz;\n                              0,0,0,pYrdxvz,    0,        pYrdzvz,  pYvxvz,   pYvyvz,   pYvzvz,   pYOmegavz;\n                              0,0,0,pZrdxvz,    pZrdyvz,  0,        pZvxvz,   pZvyvz,   pZvzvz,   pZOmegavz;\n                              zeros(4,10)];\n               aHess(:,:,10)=[zeros(3,10);\n                              0,0,0,0,             pXrdyOmega,  pXrdzOmega,  pXvxOmega,   pXvyOmega,   pXvzOmega,   pXOmegaOmega;\n                              0,0,0,pYrdxOmega,    0,           pYrdzOmega,  pYvxOmega,   pYvyOmega,   pYvzOmega,   pYOmegaOmega;\n                              0,0,0,pZrdxOmega,    pZrdyOmega,  0,           pZvxOmega,   pZvyOmega,   pZvzOmega,   pZOmegaOmega;\n                              zeros(4,10)];\n            end\n            if(nargout>3)\n                papt=zeros(10,1);\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/Dynamic_Models/Continuous_Time/aSpiralSimp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.587255851888378}}
{"text": "% test for front propagation on 3D meshes\n%\n%   Copyright (c) 2007 Gabriel Peyre\n\npath(path, 'toolbox/');\npath(path, '../toolbox_graph_data/');\npath(path, '../toolbox_graph_data/off/');\n\n\nrep = ['results/geodesic-mesh/'];\nif not(exist(rep))\n    mkdir(rep);\nend\n\n\ndisp('Loading mesh.');\nif not(exist('name'))\n    name = 'bunny';\n    name = 'elephant-50kv';\n    name = 'david50kf';\n    name = 'david_head';\n    name = 'hand';\nend\noptions.name = name;\n[vertex,faces] = read_mesh(name);\nclf;\nplot_mesh(vertex, faces,options);\nsaveas(gcf, [rep name '-mesh.png'], 'png');\n\nnverts = max(size(vertex));\nif not(exist('nstart'))\n    nstart = 1;\nend\nstart_points = [1 round(nverts/2)];\nstart_points = floor(rand(nstart,1)*nverts)+1;\nstart_points = start_points(:);\noptions.end_points = [];\n% enforce a nice starting position for the first point\nswitch name\n    case 'bunny'\n        start_points(1) = 8900;\n    case 'elephant-50kv'\n        start_points(1) = 24575;\n    case 'david50kf'\n        start_points(1) = 20361;\n    case 'david_head'\n        start_points(1) = 18080;\n    case 'hand'\n        start_points(1) = 29719;\nend\n\ndisp('Performing propagation.');\n[D,S,Q] = perform_fast_marching_mesh(vertex, faces, start_points, options);\n\n\n% compute geodesics\nnpaths = max(20,4*nstart);\n% npaths = 1;\n[tmp,I] = sort( D(:) ); I = I(end:-1:1); I = I(1:round(nverts*1));\nend_points = floor( rand(npaths,1)*(length(I)-1) )+1;\nend_points = I(end_points);\n% [tmp,I] = sort( D(:) ); end_points(1) = I(end);\n\noptions.v2v = compute_vertex_ring(faces);\noptions.e2f = compute_edge_face_ring(faces);\n\ndisp('Extracting geodesics');\noptions.method = 'discrete';\noptions.method = 'continuous';\npaths = compute_geodesic_mesh(D,vertex,faces, end_points, options);\n    \noptions.colorfx = 'equalize';\nplot_fast_marching_mesh(vertex,faces, D, paths, options);\nsaveas(gcf, [rep name '-geodesics-' num2str(nstart) '.png'], 'png');\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_propagation_mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5872558467062554}}
{"text": "samplen=1000;%Total number of initial states\nInitialMat=zeros(4,samplen);%Store initialized x, y, theta, v into each row by sequence\nfor i=1:samplen\nrr=0;\nwhile rr<=1\nxini1=(-10+rand(1)*(20));%-10~10\nyini1=(-10+rand(1)*(20));%-10~10\nrr = (xini1)^2+(yini1)^2;%Initialize location states which are inside safe region\nend\nthetaini1=(-10+rand(1)*(20));%-10~10\nvini1=(-10+rand(1)*(20));%-10~10\nInitialMat(1,i)=xini1;\nInitialMat(2,i)=yini1;\nInitialMat(3,i)=thetaini1;\nInitialMat(4,i)=vini1;\nend\nsave('InitialStateData','InitialMat');", "meta": {"author": "HybridRobotics", "repo": "NMPC-DCLF-DCBF", "sha": "3f40c67578f49114301b02e744e5a86fa671a981", "save_path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF", "path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF/NMPC-DCLF-DCBF-3f40c67578f49114301b02e744e5a86fa671a981/matlab/acc2023/benchmark/InitialState.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.587255846450733}}
{"text": "function y = sinh(x)\n%SINH         Implements  sinh(x)  for intervals\n%\n%   y = sinh(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 11/20/05     S.M. Rump  fast check for rounding to nearest\n% modified 12/04/05     S.M. Rump  extreme values for approximate part\n% modified 09/06/07     S.M. Rump  approximate std fcts removed\n% modified 08/26/12     S.M. Rump  global variables removed\n% modified 10/13/12     S.M. Rump  INTLAB_INTVAL_STDFCTS\n%\n\n  if issparse(x)\n    [ix,jx,sx] = find(x);\n    [m,n] = size(x);\n    y = sparse(ix,jx,sinh(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 = ( exp(x) - exp(-x) ) / 2;  \n    setround(rndold)\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  len2 = sum(IndexSupNeg);\n\n  Y = sinhpos( [ xinf(IndexInfPos) ; -xsup(IndexSupNeg) ] , -1 );\n  y.inf(IndexInfPos) = Y(1:len1);\n  y.sup(IndexSupNeg) = -Y( len1+1 : end );\n\n  IndexInfNeg = ~IndexInfPos;\n  len1 = sum(IndexInfNeg);\n  IndexSupPos = ~IndexSupNeg;\n  len2 = sum(IndexSupPos);\n\n  Y = sinhpos( [ -xinf(IndexInfNeg) ; xsup(IndexSupPos) ] , 1 );\n  y.inf(IndexInfNeg) = -Y(1:len1);\n  y.sup(IndexSupPos) = Y( len1+1 : len1+len2 );\n  \n  setround(rndold)\n\n\nfunction y = sinhpos(x,rnd)\n% rigorous sinh(x) for nonnegative double vector x with\n% rounding corresponding to rnd\n\n  INTLAB_STDFCTS_SINH = getappdata(0,'INTLAB_STDFCTS_SINH');\n\n  y = x;\n\n  % small input\n  index = ( x<8 );\n  if any(index)\n    setround(0)\n    xx = x(index);\n    [f,e] = log2(xx);\n    bits = 14 + min(e,0);\n    xs = pow2( floor(f.*2.^bits) , e-bits );  % max. 14 bits of mantissa,\n                                              % no bit below 2^-14\n    d = xx - xs;                              % 0 <= d < 2^-14*x < 2^-11\n    sinhxs = sinh(xs);                        % round to nearest\n\n    % bounds for exp(xs)\n    INTLAB_STDFCTS_EXP = getappdata(0,'INTLAB_STDFCTS_EXP');\n    setround(-1)\n    expinf = exp(xs)*(1-INTLAB_STDFCTS_EXP.EPS);\n    setround(1)\n    expsup = exp(xs)*(1+INTLAB_STDFCTS_EXP.EPS);\n    expinf(xs==0) = 1;                    % gives accuracy for small x\n    expsup(xs==0) = 1;\n\n    % use sinh(xx) = sinh(xs+d) = sinh(xs)*cosh(d) + cosh(xs)*sinh(d)\n    setround(rnd)\n    corr = INTLAB_STDFCTS_SINH.EPS;\n    if rnd==-1\n      % coshxs <= cosh(xs)\n      coshxs = 0.5*( expinf + 1./expsup );  % rounded downwards\n      dd = d.*d;\n      % 0 <= err(sinhd) <= sinh(d)*d^4/4! < 6e-8*d^3/6\n      % 0 <= err(coshd) <= sinh(d)*d^5/5! < 4.8e-8*d^4/24\n      y(index) = sinhxs + ...\n          ( ( sinhxs .* ( -corr + (1-corr)*dd/2.*( 1 + dd/12 ) ) + ...\n              coshxs.*d.*dd/6 ) + ...\n            coshxs.*d ...\n          );\n    else\n      % coshxs >= cosh(xs)\n      coshxs = 0.5*( expsup + 1./expinf );  % correctly rounded according to rnd\n      dd = d.*d;\n      y(index) = sinhxs + ...\n          ( ( sinhxs .* ( corr + (1+corr)*dd/2.*( 1 + dd/12.*( 1+4.8e-8 ) ) ) + ...\n              coshxs.*d.*dd/6.*( 1+6e-8 ) ) + ...\n            coshxs.*d ...\n          );\n    end\n  end\n\n  % medium input\n  index = ( ~index ) & ( x<709 );         % 8 <= x < 709\n  if any(index)\n    xx = x(index);\n    exprnd = exp_rnd(xx,rnd);\n    setround(rnd)\n    y(index) = 0.5 * ( exprnd + (-1)./exprnd );\n  end\n\n  % large input\n  index = ( x>=709 );\n  if any(index)\n    INTLAB_STDFCTS_E = getappdata(0,'INTLAB_STDFCTS_E');\n    exprnd = exp_rnd( x(index)-1 , rnd )/2;\n    setround(rnd)\n    if rnd==-1\n      y(index) = exprnd .* INTLAB_STDFCTS_E.INF;\n    else\n      y(index) = exprnd .* INTLAB_STDFCTS_E.SUP;\n    end\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/sinh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5872558433486258}}
{"text": "function [M_mean,n]=meanfilt3(M,IND,k,v)\n\n%Creating spherical mask environment with radius k\n[kI,kJ,kK]=cart2im(k,k,k,v);\nkI=round(kI); kJ=round(kJ); kK=round(kK);\n[MASK_J,MASK_I,MASK_K]=meshgrid(-kJ:kJ,-kI:kI,-kK:kK);\n% [MASK_X,MASK_Y,MASK_Z]=im2cart(MASK_I,MASK_J,MASK_K,v);\nMASK_X=MASK_J.*v(2); MASK_Y=MASK_I.*v(1); MASK_Z=MASK_K.*v(3);\n\nR=sqrt(MASK_X.^2 + MASK_Y.^2 + MASK_Z.^2);\n\nLv=R<=k;\nMASK_I=MASK_I(Lv); MASK_J=MASK_J(Lv); MASK_K=MASK_K(Lv);\n\n%Getting mask indices\n[IND_mask]=maskfind(M,IND(:),MASK_I(:),MASK_J(:),MASK_K(:));\nL_valid=IND_mask>0;\nINT_valid=M(IND_mask(L_valid));\nINT_mask=nan(size(IND_mask));\nINT_mask(L_valid)=INT_valid;\n\n%Calculating median, ignoring NaN's\nM_mean=gnanmean(INT_mask,2);\n\n%Calculating number of elements used in median calculation\nn=sum(~isnan(INT_mask),2);\n\n%         %Creating spherical mask environment\n%         k=k+iseven(k);\n%         k_offset=round(k/2)-1;\n%         [MASK_J,MASK_I,MASK_K]=meshgrid(-k_offset:k_offset);\n%         R=sqrt(MASK_J.^2 + MASK_I.^2 + MASK_K.^2);\n%         Lv=R<=k_offset;\n%         MASK_I=MASK_I(Lv); MASK_J=MASK_J(Lv); MASK_K=MASK_K(Lv);\n%\n%         %Getting mask indices\n%         [IND_mask]=maskfind(M,IND(:),MASK_I(:),MASK_J(:),MASK_K(:));\n%         L_valid=IND_mask>0;\n%         INT_valid=M(IND_mask(L_valid));\n%         INT_mask=nan(size(IND_mask));\n%         INT_mask(L_valid)=INT_valid;\n%\n%         %Calculating median, ignoring NaN's\n%         M_median=nanmedian(INT_mask,2);\n%\n%         %Calculating number of elements used in median calculation\n%         n=sum(~isnan(INT_mask),2);\nend\n\n\n\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/meanfilt3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5872558412686104}}
{"text": "function [Q,c,f,x,info] = quaddecomp(p,z)\n%QUADDECOMP Internal function to decompose quadratic expression\n\n[n,m]=size(p);\ninfo = 0;\n\n% Is it a scalar\nif (n*m==1)\n    % Involved in polynomial expression\n    [mt,variabletype] = yalmip('monomtable');\n    x_lin = getvariables(p);\n    x_var = find(any(mt(x_lin,:),1));\n    if nargin==2\n        x_var = union(x_var,depends(z));\n    end\n    x = recover(x_var);\n    if all(variabletype(x_lin) ==0)% is(p,'linear')\n        n = length(x);\n        Q = spalloc(n,n,0);\n        fc = getbase(p);\n        f = fc(1);\n        if nargin==2\n            vars = getvariables(p);\n            c = zeros(length(x),1);\n            for i = 1:length(vars)\n                c(find(vars(i)==x_var)) = fc(1+i);\n            end\n        else\n            c = fc(2:end);c=c(:);\n        end\n        return\n    end\n    variabletype = variabletype(x_lin);\n    if all(variabletype<=2)\n\n        base = getbase(p);\n        if nnz(base(1))==0\n            f = 0;\n            base = base(2:end);\n        else\n            f = base(1);\n            base = base(2:end);\n        end\n        mt = mt(x_lin,x_var);     \n        quads   = find (variabletype == 2);\n        bilins  = find (variabletype == 1);\n        linears  = find (variabletype == 0);\n        [varsC,aux1,aux2] = find(mt(linears,:)');\n        [varsQ,aux1,aux2] = find(mt(quads,:)');\n        [varsB,aux1,aux2] = find(mt(bilins,:)');\n        if isempty(varsQ)\n            varsQ = [];\n        end\n        if isempty(varsB)\n            varsB = [];\n        end\n        if isempty(varsC)\n            varsC = [];\n        end\n        c = sparse(varsC,1,base(linears),length(x),1);\n        ii = [varsQ ; varsB(1:2:end) ; varsB(2:2:end)];\n        jj = [varsQ ; varsB(2:2:end) ; varsB(1:2:end)];\n        kk = [base(quads)  base(bilins)/2  base(bilins)/2];\n        Q = sparse(ii,jj,kk,length(x),length(x));\n    else\n        if nargout==5\n            info = 1;\n            Q = [];\n            c = [];\n            f = [];\n            x = [];\n        else\n            error('Function is not quadratic');\n        end\n    end\n\nelse\n    if nargout==5\n        info = 1;\n        Q = [];\n        c = [];\n        f = [];\n        x = [];\n    else\n        error('Function is not scalar');\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/@sdpvar/quaddecomp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5872083348608997}}
{"text": "function [h]=arrows(x,y,w,fac,color)\n% function [h]=arrows(x,y,w,fac,color)\n%    Draws arrows with their tails at each point corresponding\n%\tto identical indices in the matrices x,y.  The matrices u\n%\tand v are the components of the vector to be represented.\n%\tfac is the scaling factor \n%\n%  Geometry of arrowheads (choosing HEADA and HEADL):\n%    If the arrow is defined by the points A B C B D where A is the base of \n%  the arrow, B is the head, and C and D are the corners of the arrowhead, then\n%  HEADA is the angle BAC (or BAD), and HEADL is the ratio of distances AC/AB.\n%\n\n% revision 3/20/97 to use nans for line breaks\n% much more efficient and returns only a single handle\n  \nHEADA=10*pi/180; HEADL=.75;\nz=x(:)+i*y(:);\n\nif nargin < 5,color='red';end\nif nargin < 4,help arrows,end\nw=w(:)*fac;\nr=w*HEADL; wr1=r*exp(+i*HEADA); wr2=r*exp(-i*HEADA);\nwplot=ones(length(z),6); \nwplot(:,1)=z; \nwplot(:,[2,4])=(z+w)*ones(1,2);\nwplot(:,3)=z+wr1; wplot(:,5)=z+wr2;\nwplot(:,6)=z*nan;\nwplot=wplot.';\nwplot=wplot(:);\n%z=eps*ones(size(wplot));\n%h=line(real(wplot),imag(wplot),z,'color',color);\nh=line(real(wplot),imag(wplot),'color',color);\nset(h(1),'userdata',fac);\n", "meta": {"author": "nctoolbox", "repo": "nctoolbox", "sha": "af757acccfcac373e35fde89fc8ed7e64b67de82", "save_path": "github-repos/MATLAB/nctoolbox-nctoolbox", "path": "github-repos/MATLAB/nctoolbox-nctoolbox/nctoolbox-af757acccfcac373e35fde89fc8ed7e64b67de82/cdm/utilities/graphics/arrows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5872083208608472}}
{"text": "function [mg] = kg2mg(kg)\n% Convert mass from kilograms to milligrams. \n% Chad Greene 2012\nmg = kg*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/kg2mg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5872083024291694}}
{"text": "function month_cal_gregorian ( y, m )\n\n%*****************************************************************************80\n%\n%% MONTH_CAL_GREGORIAN prints a Gregorian month calendar.\n%\n%  Format:\n%\n%    GREGORIAN CALENDAR\n%        APRIL 1997 AD\n%\n%    Su  M Tu  W Th  F Sa\n%           1  2  3  4  5\n%     6  7  8  9 10 11 12\n%    13 14 15 16 17 18 19\n%    20 21 22 23 24 25 26\n%    27 28 29 30\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%  Parameters:\n%\n%    Input, integer  Y, M, the YM date.\n%\n\n%\n%  Make local copies of the input.\n%\n  m2 = m;\n  y2 = y;\n%\n%  Check the month and year.  After this call, month is\n%  guaranteed to be between 1 and 12.\n%\n  [ y2, m2, ierror ] = ym_check_gregorian ( y2, m2 );\n\n  if ( ierror ~= 0 )\n    return\n  end\n%\n%  Find the day of the week for Y M 1.\n%\n  d = 1;\n  f = 0.0;\n\n  w = ymdf_to_weekday_gregorian ( y2, m2, d, f );\n%\n%  Find the appropriate label for the first box in the calendar.\n%\n  iday = 2 - w;\n%\n%  Print out a heading.\n%\n  s1 = month_to_month_name_common ( m2 );\n  s2 = y_to_s_gregorian ( y2 );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'Gregorian Calendar\\n' );\n  fprintf ( 1, '%s %s\\n', s1, s2 );\n  fprintf ( 1, '\\n' );\n%\n%  Get the days of the week.\n%\n  fprintf ( 1, ' ' );\n  for w = 1 : 7\n    lab = weekday_to_name_common2 ( w );\n    fprintf ( 1, '%3s', lab );\n  end\n  fprintf ( 1, '\\n' );\n%\n%  Print out a line of day numbers.\n%\n  while ( iday <= month_length_gregorian ( y2, m2 ) )\n\n    fprintf ( 1, ' ' );\n\n    for w = 1 : 7\n\n      if ( iday < 1 )\n        fprintf ( 1, '   ' );\n      elseif ( month_length_gregorian ( y2, m2 ) < iday )\n        fprintf ( 1, '   ' );\n      else\n        fprintf ( 1, ' %2d', iday );\n      end\n\n      iday = iday + 1;\n\n    end\n\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/calpak/month_cal_gregorian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.5872059515238368}}
{"text": "%FIGURE_sliding_distance\n\n%%%% EXPERIMENT %%%%\n%\n% For a slendar rod toppling from rest, plot how the slip distance varies\n% as a function of coefficient of friction.\n%\n%\n\nclc; clear;\n\nsetup.Tspan = [0,10];  %only used for timeout of the simulation\nsetup.tol = 1e-12;   %Accuracy of the intergation method\nsetup.dataFreq = 750;   %How much data to return?\nsetup.solver = @ode45;   %Tell the simulation to use a still solver.\n\n%%%% HACK %%%%\n% If the perturbation is too small, then numerical errors start to creep\n% into the results. If perturbation is larger than the critical angle of\n% the smallest non-zero coefficient of friction, then it will cause a\n% direct error by violating the initial phase assumption.\nsetup.perturbation = 1e-2;\n%%%% DONE %%%%\n\nMoI = logspace(-3,0,250);\nMu = [0,0.05,0.1,0.5,1,5,10,inf];\nP.m = 1;\nP.g = 1;\nP.L = 1;\n\n%%%% Run big experiment %%%%\nData = runSlipExperiment(setup,MoI,Mu);\n\n%%%% Plotting %%%%\nN_mu = length(Data);\nxBnd = [min(Data(1).moi), max(Data(1).moi)];\nMu = zeros(N_mu,1);\nstyle = {'k--','b--','r--','m--','g--',...\n    'k-','b-','r-','m-','g-'...\n    'k:','b:','r:','m:','g:'};\nLINEWIDTH = 3;\nFontSize.Title = 16;\nFontSize.label = 12;\nnames = cell(1,N_mu);\nfor i=1:N_mu\n    Mu(i) = Data(i).mu;\n    names{i} = num2str(['u = ' num2str(Mu(i))]);\nend\n\n%%%% Distance %%%%\nH_dist = figure(100); clf; hold on;\nset(H_dist,'Name','SlipDist','NumberTitle','off')\nIDX = false(2,length(Mu));\nfor i=1:length(Data)\n    sty = style{mod(i-1,length(style))+1};\n    subplot(2,1,1); hold on;\n    idx = Data(i).pos~=0;  IDX(1,i) = sum(idx)~=0;\n    semilogx(Data(i).moi(idx),Data(i).pos(idx),sty,'LineWidth',LINEWIDTH);\n    title('Backwards Slip (falling forward)','FontSize',FontSize.Title)\n    xlabel('Moment of Inertia','FontSize',FontSize.label)\n    ylabel('Slip Distance','FontSize',FontSize.label)\n    set(gca,'Xscale','log')\n    subplot(2,1,2); hold on;\n    idx = Data(i).neg~=0;  IDX(2,i) = sum(idx)~=0;\n    semilogx(Data(i).moi(idx),Data(i).neg(idx),sty,'LineWidth',LINEWIDTH);\n    title('Forwards Slip (falling forward)','FontSize',FontSize.Title)\n    xlabel('Moment of Inertia','FontSize',FontSize.label)\n    ylabel('Slip Distance','FontSize',FontSize.label)\n    set(gca,'Xscale','log')\nend\n%subplot(2,1,1); legend(names(IDX(1,:)),'Location','NorthEast');\n% extents = [xBnd,-1,0];  axis(extents);\nsubplot(2,1,2); legend(names(IDX(2,:)),'Location','SouthWest');\n% extents = [xBnd,0,0.14];\n\n%%%% Critical Angle %%%%\nH_angle = figure(101); clf; hold on;\nset(H_angle,'Name','CriticalAngle','NumberTitle','off')\nIDX = false(2,length(Mu));\nfor i=1:length(Data)\n    sty = style{mod(i-1,length(style))+1};\n    \n    idx1 = Data(i).pos~=0;  IDX(1,i) = sum(idx1)~=0;\n    subplot(2,1,1); hold on\n    semilogx(Data(i).moi(idx1),-Data(i).angle(idx1)*180/pi,sty,'LineWidth',LINEWIDTH);\n    title('Backwards Slip (falling forward)','FontSize',FontSize.Title)\n    xlabel('Moment of Inertia','FontSize',FontSize.label)\n    ylabel('Critical Angle (deg)','FontSize',FontSize.label)\n    set(gca,'Xscale','log')\n    \n    idx2 = Data(i).neg~=0; IDX(2,i) = sum(idx2)~=0;\n    idx2a = idx2 & idx1;   %In these special cases, it slips backwards and then forwards. Only plot the FIRST critical angle.\n    idx2b = idx2 & ~idx1;\n    subplot(2,1,2); hold on;\n%     semilogx(Data(i).moi(idx2a),-Data(i).angle(idx2a)*180/pi,sty,'LineWidth',LINEWIDTH);\n    semilogx(Data(i).moi(idx2b),-Data(i).angle(idx2b)*180/pi,sty,'LineWidth',LINEWIDTH);\n    title('Forwards Slip (falling forward)','FontSize',FontSize.Title)\n    xlabel('Moment of Inertia','FontSize',FontSize.label)\n    ylabel('Critical Angle (deg)','FontSize',FontSize.label)\n    set(gca,'Xscale','log')\nend\n\nsubplot(2,1,1); legend(names(IDX(1,:)),'Location','NorthEast');\n% extents = [xBnd,0,45];  axis(extents);\nsubplot(2,1,2); legend(names(IDX(2,:)),'Location','NorthWest');\n% extents = [xBnd,30,60];\n\n%%%% SAVE %%%%\nsave('DATA_Slip_vs_Mu.mat','Data');\nsave2pdf('../WriteUp/Figures/Slip_vs_Mu__Distance.pdf',H_dist,600);\nsave2pdf('../WriteUp/Figures/Slip_vs_Mu__Angle.pdf',H_angle,600);", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/toppling_stick/FIGURE_sliding_distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.5872059310744127}}
{"text": "% Fig. 9.8  Feedback Control of Dynamic Systems, 6e \n%             Franklin, Powell, Emami\n n=[1 1];\n d = [1 0 0];\n rlocus(n,d)\n axis([-6 2 -3 3])\n hold on\n r=roots([1 1 1]);\n plot(r,'*')\n  z=0:.1:.9;\n wn= 1:6;\n sgrid(z, wn)\n hold 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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig9_08.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5871877002801092}}
{"text": "function [X, info] = IRhybrid_flsqr(A, b, varargin)\n%IRhybrid_flsqr Hybrid version of FLSQR algorithm [...]\n%\n% options  = IRhybrid_flsqr('defaults')\n% [X,info] = IRhybrid_flsqr(A,b)\n% [X,info] = IRhybrid_flsqr(A,b,K)\n% [X,info] = IRhybrid_flsqr(A,b,options)\n% [X,info] = IRhybrid_flsqr(A,b,K,options)\n%\n% IRhybrid_flsqr is a hybrid iterative regularization method used for \n% solving large-scale, ill-posed inverse problems of the form:\n%               b = A*x + noise .\n% The method combines FLSQR iteration (iterative regularization method) \n% with a Tikhonov regularization method to stabilize the semiconvergence\n% behavior that is characteristic of many iterative solvers applied to\n% ill-posed problems.\n%\n% With 'defaults' as input returns the default options.  Otherwise outputs\n% the iterates specified in K, using max(K) as MaxIter, and using all other\n% default options.  With options as input: uses the user-specified options\n% and all the other default options.\n%\n%   \n% Inputs:\n%  A : either (a) a full or sparse matrix\n%             (b) a matrix object that performs the matrix*vector operation\n%             (c) user-defined function handle\n%  b : right-hand side vector\n%  K : (optional) integer vector that specifies which iterates are returned\n%      in X; the maximum number of iterations is assumed to be max(K)\n%      [ positive integer | vector of positive components ]\n%  options : structure with the following fields (optional)\n%      x0         - initial guess for the iterations; default = zero vector\n%                   [ array | {'none'} ]\n%      x_true     - true solution; allows us to returns error norms with\n%                   respect to x_true at each iteration\n%                   [ array | {'none'} ]\n%      RegParam   - a value or a method to find the regularization\n%                   parameter for the projected problems: \n%                   [  non-neg. scalar | {'wgcv'} | 'gcv' | 'modgcv' |...\n%                     'discrep' | 'discrepit' | 'optimal']\n%                   This also determines which stopping rule is used\n%                   If 'gcv', 'wgcv' or 'modgcv' is chosen, the iteration is\n%                     stopped when the GCV function minimum stabilizes or\n%                     increases within a certain window of iterations (see\n%                     'stopGCV', 'FlatTol' and 'MinTol').\n%                   If 'discrep' is chosen, and NoiseLevel is provided,\n%                     then the discrepancy principle is used as stopping\n%                     (see 'NoiseLevel' and 'eta').\n%                   If 'discrepit' is chosen, and NoiseLevel is provided,\n%                     then the discrepancy principle is used to set the \n%                     parameter at each iteration, and the stabilization of \n%                     successive parameters is used as stopping criterion\n%                     (see 'NoiseLevel', 'eta' and 'regPflatTol').\n%                   If 'optimal' is chosen, and x_true is provided,\n%                     no stopping criterion is considered\n%      stopGCV    - stopping criterion for the iterations when GCV is used\n%                   [ 'GCVvalues' | {'resflat'} ]\n%      resflatTol - tolerace for the stabilization of the residual\n%                   (to be used if stopGCV is 'resflat')\n%                   [ {0.05} | non-negative scalar ]\n%      regPflatTol- tolerance for the stabilization of \n%                   successive regularization parameters \n%                   (to be used as stopping criterion)\n%                   [ {0.9} | non-negative scalar ]\n%      GCVflatTol - tolerance for detecting flatness (stabilization)\n%                   in the GCV function as a stopping criterion\n%                   [ {10^-6} | non-negative scalar ]\n%      GCVminTol  - window of iterations - if the GCV minimum continues\n%                   to increase over this window, then the iterations are\n%                   stopped:\n%                   [ {3} | positive integer ]\n%      GCVweight  - weight to be used if RegParam is 'wgcv'\n%                   [ 'adapt' | non-negative scalar ]\n%      NoiseLevel - norm of noise in rhs divided by norm of rhs (must be\n%                   assigned if RegParam is 'discrep')\n%                   [ {'none'} | nonnegative scalar ]\n%      eta        - safety factor for the discrepancy principle\n%                   [ {1.01} | scalar greater than (and close to) 1 ]\n%      RegParam0  - regularization parameter used in the first  projected\n%                   problem (needed if RegParam is 'discrep')\n%                   [ {1} | positive scalar ]\n%      MaxIter    - maximum number of iterations\n%                   [ {'none'} | positive integer ]\n%      DecompOut  - returns the Golub-Kahan decomposition to the user\n%                   [ 'on' | {'off'} ]\n%      IterBar    - shows the progress of the iterations\n%                   [ {'on'} | 'off' ]\n%      NoStop     - specifies whether the iterations should proceed\n%                   after a stopping criterion is satisfied\n%                   [ 'on' | {'off'} ]\n%   SparsityTrans - sparsity transform for the solution\n%                   [ {'none'} | 'dwt' ]\n%      wname      - discrete wavelet transform name (meaningful if \n%                   SpartistyTrans is 'dwt')\n%                   [ {'db1'} ]\n%      wlevels    - discrete wavelet transform level (meaningful if \n%                   SpartistyTrans is 'dwt')\n%                   [ {2} | positive integer]\n%   hybridvariant - kind of hybrid method to be implemented\n%                   [ {'I'} | 'R' ]\n%            tolX - tolerance for the weights (the modulus of the weights \n%                   cannot be below this threshold\n%                   [ {10^-10} | non-negative scalar ]\n% Note: the options structure can be created using the function IRset. \n%\n% Outputs:\n%   X : computed solutions, stored column-wise (at the iterations listed in K)\n%   info: structure with the following fields:\n%      its      - number of the last computed iteration\n%      saved_iterations - iteration numbers of iterates stored in X \n%      StopFlag - string that describes the output/stopping condition:\n%                   * Flat GCV curve \n%                   * Minimum of GCV function (within window of MinTol its)\n%                   * Performed max number of iterations\n%                   * Discrepancy principle satisfied\n%                   * Breakdown of the Golub-Kahan bidiagonalization algorithm\n%      StopReg  - structure with the following fields:\n%                   * X: solution satisfying the stopping criterion\n%                   * It: iteration satisfying the stopping criterion\n%                   * RegP: regularization parameter at the iteration satisfying \n%                     the stopping crierion\n%                   * Xnrm: norm of the solution satisfying satisfying the\n%                     stopping criterion \n%                   * Rnrm: relative residual norm at the iteration\n%                     satisfying the stopping criterion\n%                   * Enrm: relative error norm at the iteration\n%                     satisfying the stopping criterion (requires x_true)\n%      Xnrm     - solution norms at each iteration\n%      Rnrm     - relative residual norms at each iteration\n%      Enrm     - relative error norms at each iteration (requires x_true)\n%      RegP     - sequence of the regularization parameters\n%      GCValues - GCV function evaluated at minimum point at each\n%                 iteration (if RegParam is 'gcv', 'wgcv', 'modgcv')\n%      V        - Golub-Kahan bidiagonalization basis vectors for the solution\n%      U        - Golub-Kahan bidiagonalization basis vectors\n%      B        - lower bidiagonal matrix computed by Golub-Kahan bidiagonalization\n%\n% See also: IRcgls, IRhybrid_fgmres, IRhybrid_gmres, IRhybrid_flsqr, IRget, IRset\n\n% Julianne Chung, Virginia Tech\n% Silvia Gazzola, University of Bath\n% June, 2018.\n\n\n% Initialization\ndefaultopt = struct('x0', 'none', 'MaxIter', 100 ,...\n    'x_true', 'none', 'NoStop','off', 'IterBar', 'on',...\n    'RegParam','wgcv',...\n    'SparsityTrans', 'none', 'wname', 'db1', 'wlevels', 2,...\n    'qnorm', 1, 'weight0', 'none',...\n    'hybridvariant', 'I', 'tolX', 10^-10,...\n    'GCVweight', 'adapt',...\n    'GCVflatTol', 10^-6, 'GCVminTol', 3,...\n    'stopGCV', 'GCVvalues', 'resflatTol', 0.05, 'regPflatTol', 0.9,...\n    'NoiseLevel', 'none', 'eta', 1.01, 'RegParam0', 1, 'DecompOut', 'off');\n\nif nargin == 0\n    error('Not enough input arguments')\nelseif nargin == 1 \n    % If input is 'defaults,' return the default options in X\n    if nargout <= 1 && isequal(A,'defaults')\n        X = defaultopt;\n        return;\n    else\n        error('Not enough input arguments')\n    end\nend\n\ndefaultopt.restart = 'off';\ndefaultopt.verbosity = 'on';\n\n% Check for acceptable number of optional input arguments\nswitch length(varargin)\n    case 0 \n        K = []; options = [];\n    case 1\n        if isa(varargin{1}, 'double')\n            K = varargin{1}; options = [];\n        else\n            % no matter the order of appearance\n            K = []; options = varargin{1};\n        end\n    case 2\n        if isa(varargin{1}, 'double')\n            K = varargin{1}; options = varargin{2};\n        else\n            % again, no matter the order of appearance\n            K = varargin{2}; options = varargin{1};\n        end\n        if isfield(options, 'MaxIter') && ~isempty(options.MaxIter) && (~isempty(K) && options.MaxIter ~= max(K))\n            warning('The value of MaxIter is discarded; the maximum value in K is taken as MaxIter')\n        end \n    otherwise\n        error('Too many input parameters')\nend\n\nif isempty(options)\n    options = defaultopt;\nend\n\noptions = IRset(defaultopt, options);\n\nMaxIter    = IRget(options, 'MaxIter',    [], 'fast');\nRegParam   = IRget(options, 'RegParam',   [], 'fast');\nx_true     = IRget(options, 'x_true',     [], 'fast');\nNoStop     = IRget(options, 'NoStop',     [], 'fast');\nIterBar    = IRget(options, 'IterBar',    [], 'fast');\nomega      = IRget(options, 'GCVweight',  [], 'fast');\nstopGCV    = IRget(options, 'stopGCV',    [], 'fast');\nresdegflat = IRget(options, 'resflatTol', [], 'fast');\ndegflat    = IRget(options, 'GCVflatTol', [], 'fast');\nregPflat   = IRget(options, 'regPflatTol', [], 'fast');\nmintol     = IRget(options, 'GCVminTol',  [], 'fast');\nNoiseLevel = IRget(options, 'NoiseLevel', [], 'fast');\neta        = IRget(options, 'eta',        [], 'fast');\nRegParamk  = IRget(options, 'RegParam0',  [], 'fast');\nrestart    = IRget(options, 'restart',    [], 'fast');\nverbose    = IRget(options, 'verbosity',  [], 'fast');\nDecompOut  = IRget(options, 'DecompOut', [], 'fast');\ntolX       = IRget(options, 'tolX',      [], 'fast');\nq          = IRget(options, 'qnorm', [], 'fast');\nSparsityTrans = IRget(options, 'SparsityTrans', [], 'fast');\nhybridvariant = IRget(options, 'hybridvariant', [], 'fast');\n\nverbose = strcmp(verbose, 'on');\n\nadaptWGCV = strcmp(RegParam, {'wgcv'}) && strcmp(omega, {'adapt'});\n\n% setting K\nif isempty(K)\n    K = MaxIter;\nend\n% sorting the iterations (in case they are shuffled in input)\nK = K(:); K = sort(K,'ascend'); K = unique(K);\nif ~((isreal(K) && (all(K > 0)) && all(K == floor(K))))\n    error('K must be a vector of positive real integers')\nend\nif K(end) ~= MaxIter\n    MaxIter = K(end);    \nend\n% note that there is no control on K, as it does not go through IRset\n\nif (strcmp(RegParam,'discrep') || strcmp(RegParam,'discrepit')) && ischar(NoiseLevel)\n    error('The noise level (NoiseLevel) must be assigned')\nend\n\nif strcmp(RegParam,'optimal') && ischar(x_true)\n    error('The true solution (x_true) must be assigned')\nend\n\nStopIt = MaxIter;\n\nrestart = strcmp(restart, 'on');\nif restart\n    ktotcount  = IRget(options, 'ktotcount', [],'fast');\n    TotIterMax = IRget(options, 'TotIterMax',[],'fast');\n    if strcmp(TotIterMax, 'none') || TotIterMax < MaxIter\n        TotIterMax = MaxIter;\n    end\n    if strcmp(ktotcount, 'none')\n        error('the total iteration counter must be assigned')\n    end\n    Ktot = IRget(options, 'Ktot', [], 'fast');\n    % no checks on Ktot, it should be given from IRrestart\nend\n\nd = Atransp_times_vec(A, b);\nn = length(d);\nm = length(b);\n\n\nif strcmp(SparsityTrans, 'none')\n    Trans = speye(n);\nelseif strcmp(SparsityTrans, 'dwt')\n    wname   = IRget(options, 'wname',   [], 'fast');\n    wlevels = IRget(options, 'wlevels', [], 'fast'); \n    if wlevels > 1/2*(log2(n))\n        error('The assigned wavelet levels are too high. Make sure that wlevels <= 1/2*(log2(n))')\n    end\n    Trans = FreqMatrix('dwt', [sqrt(n) sqrt(n)], wname, wlevels);\nend\n\n% setting x0\n\nx0 = IRget(options, 'x0', [], 'fast');\n\nif strcmp(x0, 'none')\n    x0 = zeros(n,1);\n    r = b(:); \n    precX = ones(n,1); \nelse\n    try\n        x0 = Trans*x0;\n    catch\n        error('Check the length of x0')\n    end    \n    if max(abs(x0(:))) == 0\n        r = b;\n        x0 = zeros(n,1);\n        precX = ones(n,1);\n    else\n        x0 = Trans'*x0;\n        Ax0 = A_times_vec(A, x0);\n        r = b(:) - Ax0;\n        precX = x0;\n        precX(abs(precX) < tolX) = eps;\n        precX = (precX).^((2-q)/2); \n    end\nend\n\nx = x0; % useful in case we have an immediate breakdown of the algorithm\nbeta = norm(r(:)); \nnrmb = norm(b(:));\n\n% means no true solution\nnotrue = strcmp(x_true,'none');\n% means we do not want to stop when the stopping criterion is satisfied\nNoStop = strcmp(NoStop,'on');\n\n% assessing if we want inner Tikhonov regularization\nif strcmp(RegParam,'off')\n    RegParam = 0;\nend\n\nRfactor = strcmpi(hybridvariant, 'R');\n\n% Declare matrices.\nX                = zeros(n,length(K));\nXnrm             = zeros(max(K),1);\nRnrm             = zeros(max(K),1);\nRegParamVect     = zeros(max(K),1);\nM = zeros(max(K)+1,max(K));\nT = zeros(max(K)+1); \nZ = zeros(n, max(K));\nV = zeros(n, max(K)+1);\nU = zeros(m, max(K)+1);\nrhs              = zeros(max(K)+1,1); % projected right-hand side\nif restart\n    saved_iterations = zeros(1, length(Ktot));\nelse\n    saved_iterations = zeros(1, length(K));\nend\nGCV   = zeros(max(K),1);\nOmega = zeros(max(K), 1);\nwarningGCV          = 0;\nif notrue\n    errornorms = false;\nelse\n    errornorms = true;\n    Enrm       = zeros(max(K),1);\n    nrmtrue = norm(x_true(:));\n    BestReg.RegP = [];\n    BestReg.It = [];\n    BestReg.X =[];\n    BestReg.Enrm = [];\n    BestReg.Xnrm = [];\n    BestReg.Rnrm = [];\n    BestEnrm = 1e10;\nend\n% Main Code Begins Here\nu = r;\nU(:,1) = u/beta; % no matter the preconditioning (because it's on the right)\nrhs(1) = beta;\n% Iterate\nnoIterBar = strcmp(IterBar,{'off'});\nif ~noIterBar\n  h_wait = waitbar(0, 'Running iterations, please wait ...');\nend\nj = 0;\nfor k=1:MaxIter\n    if ~noIterBar\n        waitbar(k/MaxIter, h_wait)\n    end\n    if restart, ktotcount = ktotcount + 1; end\n    v = Atransp_times_vec(A, U(:,k)); v = v(:);\n    v = Trans*v;\n    for i = 1:k-1\n        T(i,k)=V(:,i)'*v;\n        v = v - T(i,k)*V(:,i);\n    end\n    T(k,k) = norm(v);\n    v = v / T(k,k);\n    %\n    z = precX.*v;\n    u = Trans'*z;          \n    u = A_times_vec(A, u); u = u(:);  %%%%\n    for i = 1:k\n        M(i,k) = U(:,i)'*u;\n        u = u - M(i,k)*U(:,i);\n    end\n    M(k+1,k) = norm(u);\n    u = u / M(k+1,k);\n    U(:,k+1) = u;\n    V(:,k) = v;\n    Z(:,k) = z;\n    \n    rhsk = rhs(1:k+1); % current projected rhs\n    \n    \n    if abs(T(k,k)) <= eps || abs(M(k+1,k)) <= eps\n        if verbose\n            disp('Flexible Golub-Kahan algorithm breaks down')\n        end\n        M = M(1:k+1,1:k);\n        T = T(1:k,1:k);\n        Z = Z(:,1:k);\n        V = V(:,1:k);\n        U = U(:,1:k+1);\n        X(:,j+1) = x;\n        X = X(:,1:j+1);\n        if restart\n            saved_iterations(j+1) = ktotcount-1;\n        else\n            saved_iterations(j+1) = k-1;\n        end\n        saved_iterations = saved_iterations(1:j+1);\n        if k>1\n            Xnrm    = Xnrm(1:k-1);\n            Rnrm    = Rnrm(1:k-1);\n            RegParamVect    = RegParamVect(1:k-1);\n            if errornorms, Enrm = Enrm(1:k-1); end\n        end\n        % stop because the bidiagonal matrix is (numerically) singular\n        % No chioce: even if NoStop is 'on'...we simpy cannot compute the solution, anymore\n        if StopIt == MaxIter\n            StopFlag = 'Breakdown of the Golub-Kahan algorithm';\n            StopReg.X = x; \n            StopReg.It = k-1;\n            StopReg.RegP = RegParamk;\n            StopReg.Xnrm = Xnrm(k-1);\n            StopReg.Rnrm = Rnrm(k-1);\n            if errornorms, StopReg.Enrm = Enrm(k-1); end\n        end\n        break\n    end\n    Mk = M(1:k+1,1:k);\n    [Uk, Sk, Vk] = svd(Mk);\n    if k==1\n        Sk = Sk(1,1);\n    else\n        Sk = diag(Sk);\n    end\n    rhskhat = Uk'*rhsk;\n    flsqr_res = abs(rhskhat(k+1))/nrmb;\n\n    if Rfactor\n        % update the Householder-QR factorization of Lk\n        if k == 1\n            [ZUk, ZRk] = householderQR(Z(:,1:k));\n        else\n            [ZUk, ZRk] = upd_householderQR(Z(:,1:k-1),...\n            Z(:,k), ZUk, ZRk);\n        end\n        ZRksq = ZRk(1:k,1:k);\n        [Uk, Vk, ~, Ck, Sk] = gsvd(Mk, ZRksq);\n        rhskhat = Uk'*rhsk;\n        if k==1\n            gammak = Ck(1)/Sk(1);\n        else\n            gammak = sqrt(diag(Ck'*Ck)./diag(Sk'*Sk));\n        end\n    else\n        ZRksq = eye(k);\n    end\n    \n    % if tik\n        if isscalar(RegParam)\n            RegParamk = RegParam;\n            RegParamVect(k) = RegParamk;\n        elseif strcmp(RegParam,'discrep')\n            if k==1 \n                RegParamVect(k) = RegParamk;\n            end\n        elseif strcmp(RegParam, 'discrepit')\n            if flsqr_res > eta*NoiseLevel\n                RegParamk = 0;\n                RegParamVect(k) = RegParamk; \n            else\n                RegParamk = fzero(@(l)discrfcn(l, Mk, ZRksq, rhsk, nrmb, eta*NoiseLevel), [0, 1e10]);\n                RegParamVect(k) = RegParamk; \n            end\n        elseif strcmp(RegParam, 'optimal')\n            optfun = @(l)TikOptParam(l, Mk, ZRksq, rhsk, x0, Z(:,1:k), Trans, x_true);\n            RegParamk = fmincon(optfun,0,[],[],[],[],0,.1);\n            RegParamVect(k) = RegParamk; \n        elseif strcmp(RegParam,'wgcv')\n            if k>1\n            if ~Rfactor\n                if adaptWGCV \n                    %Use the adaptive, weighted GCV method\n                    Omega(k) = min(1, findomega(rhskhat, Sk));\n                    omega = mean(Omega(1:k));\n                end\n                RegParamk = fminbnd('TikGCV', 0, Sk(1), [], rhskhat, Sk, omega);\n                GCValk = GCVstopfun(RegParamk, Uk(1,:)', Sk, nrmb, m, n);\n            else\n                if adaptWGCV \n                    %Use the adaptive, weighted GCV method\n                    Omega(k) = min(1, findomega(rhskhat, gammak));\n                    omega = mean(Omega(1:k));\n                end\n                RegParamk = fminbnd('TikGCV', 0, gammak(k), [], rhskhat, gammak, omega);\n                GCValk = GCVstopfun(RegParamk, Uk(1,:)', gammak, nrmb, m, n);\n            end\n            RegParamVect(k) = RegParamk;\n            GCV(k) = GCValk;\n            else\n            RegParamk = 0; GCValk = 0;\n            RegParamVect(k) = RegParamk; GCV(k) = GCValk;\n            end\n        elseif strcmp(RegParam,'gcv')\n            if ~Rfactor\n                RegParamk = fminbnd('TikGCV', 0, Sk(1), [], rhskhat, Sk);\n                GCValk = GCVstopfun(RegParamk, Uk(1,:)', Sk, nrmb, m, n);\n            else\n                RegParamk = fminbnd('TikGCV', 0, gammak(k), [], rhskhat, gammak);\n                GCValk = GCVstopfun(RegParamk, Uk(1,:)', gammak, nrmb, m, n);\n            end\n            RegParamVect(k) = RegParamk;\n            GCV(k) = GCValk;\n        elseif strcmp(RegParam,'modgcv')\n            if ~Rfactor\n                RegParamk = fminbnd('TikGCV', 0, Sk(1), [], rhskhat, Sk, m);\n                GCValk = GCVstopfun(RegParamk, Uk(1,:)', Sk, nrmb, m, n);\n            else\n                RegParamk = fminbnd('TikGCV', 0, gammak(k), [], rhskhat, gammak, m);\n                GCValk = GCVstopfun(RegParamk, Uk(1,:)', gammak, nrmb, m, n);\n            end\n            RegParamVect(k) = RegParamk;\n            GCV(k) = GCValk;\n        else\n            error('Invalid parameter choice method')\n        end\n        if ~Rfactor\n            Dk = Sk.^2 + RegParamk^2;\n            % Dk = Sk.^2 + RegParamk;\n            rhskhat = Sk .* rhskhat(1:k);\n            yhat = rhskhat(1:k)./Dk;\n            y = Vk * yhat;\n%             MZk = [Mk; RegParamk*eye(k)];\n%             rhsZk = [rhsk; zeros(k,1)];\n%             y = MZk\\rhsZk;\n        else\n            MZk = [Mk; RegParamk*ZRksq(1:k,:)];\n            % MZk = [Mk; sqrt(RegParamk)*ZRksq(1:k,:)];\n            rhsZk = [rhsk; zeros(k,1)];\n            y = MZk\\rhsZk;\n        end\n        Rnrm(k) = norm(rhsk - Mk*y)/nrmb;\n        d = Z(:,1:k)*y;\n        x = x0 + d;\n        precX = abs(x);\n        precX(precX < tolX) = eps;\n        precX = precX.^((2-q)/2);\n        x = Trans'*x;\n        % Compute norms\n        Xnrm(k) = norm(x(:));\n        if errornorms\n            Enrm(k) = norm(x_true(:) - x(:))/nrmtrue;\n            if Enrm(k)<BestEnrm\n                BestReg.RegP = RegParamk;\n                BestReg.It = k;\n                BestReg.X = x;\n                BestEnrm = Enrm(k);\n                BestReg.Enrm = BestEnrm;\n                BestReg.Xnrm = Xnrm(k);\n                BestReg.Rnrm = Rnrm(k);\n            end\n        end \n        AlreadySaved = 0;\n        if any(k==K)\n            j = j+1;\n            X(:,j) = x;  \n            saved_iterations(j) = k;\n            % this is used to save the last iteration, in the case \n            % K = MaxIterIn\n            % (when performing restarts, and the inner stopping criterion is not satisfied)\n            if restart, saved_iterations(j) = ktotcount; end\n            AlreadySaved = 1;              \n        end\n        if restart\n            if any(ktotcount == Ktot) && ~ AlreadySaved\n                j = j+1;\n                X(:,j) = x;\n                saved_iterations(j) = ktotcount;\n                AlreadySaved = 1;                \n            end\n            if ktotcount == TotIterMax\n                if ~ AlreadySaved\n                    j = j+1;\n                    saved_iterations(j) = ktotcount;\n                    X(:,j) = x; \n                end\n                StopIt = k;\n                StopReg.X = x;\n                StopReg.It = k;\n                StopReg.RegP = RegParamk;  \n                StopReg.Xnrm = Xnrm(k);\n                StopReg.Rnrm = Rnrm(k);\n                if errornorms\n                    Enrm = Enrm(1:k);\n                    StopReg.Enrm = Enrm(k);\n                end\n                Xnrm    = Xnrm(1:k);\n                Rnrm    = Rnrm(1:k);\n                RegParamVect    = RegParamVect(1:k);\n                M = M(1:k+1,1:k);\n                T = T(1:k,1:k);\n                Z = Z(:,1:k);\n                V = V(:,1:k);\n                U = U(:,1:k+1);\n                X = X(:,1:j);\n                saved_iterations = saved_iterations(1:j);\n                if verbose\n                    disp('reached maximum number of iterations')\n                end\n                StopFlag = 'reached maximum number of iterations';\n                break\n            end\n        end       \n        % update parameters, check stopping criteria\n        if isscalar(RegParam)\n        % Purely iterative method case.\n        if strcmp(NoiseLevel, 'none')\n            if k>1\n            if abs((Rnrm(k)-Rnrm(k-1)))/Rnrm(k-1) < resdegflat && ...\n                Rnrm(k) == min(Rnrm(1:k)) && StopIt == MaxIter\n                if verbose\n                    disp('The stopping criterion for flsqr is satisfied')\n                end\n                % Stop because the residual stabilizes.\n                StopFlag = 'The residual norm stabilizes';\n                if ~AlreadySaved && ~NoStop\n                    j = j+1;\n                    X(:,j) = x;\n                    if restart\n                        saved_iterations(j) = ktotcount;\n                    else\n                        saved_iterations(j) = k;\n                    end\n                    AlreadySaved = 1;\n                end\n                StopIt = k;\n                StopReg.RegP = RegParamk;\n                StopReg.It = k;\n                StopReg.X = x;\n                if errornorms, StopReg.Enrm = Enrm(k); end\n                if ~ NoStop\n                    Xnrm    = Xnrm(1:k);\n                    Rnrm    = Rnrm(1:k);\n                    RegParamVect = RegParamVect(1:k);\n                    M = M(1:k+1,1:k);\n                    T = T(1:k,1:k);\n                    Z = Z(:,1:k);\n                    V = V(:,1:k);\n                    U = U(:,1:k+1);\n                    if errornorms, Enrm = Enrm(1:k); end\n                    X = X(:,1:j);\n                    saved_iterations = saved_iterations(1:j);\n                    break\n                end\n            end\n            end\n        else\n            if Rnrm(k) < eta*NoiseLevel\n            % Stopping criterion.\n            if StopIt == MaxIter\n                if verbose\n                    disp('The discrepancy principle is satisfied')\n                end\n                StopFlag = 'The discrepancy principle satisfied';\n                if ~AlreadySaved && ~NoStop\n                    j = j+1;\n                    X(:,j) = x;\n                    if restart\n                        saved_iterations(j) = ktotcount;\n                    else\n                        saved_iterations(j) = k;\n                    end\n                    AlreadySaved = 1;\n                end\n                StopIt = k;\n                StopReg.RegP = RegParamk;\n                StopReg.It = k;\n                StopReg.X = x;\n                if errornorms, StopReg.Enrm = Enrm(k); end\n                if ~ NoStop\n                    Xnrm    = Xnrm(1:k);\n                    Rnrm    = Rnrm(1:k);\n                    RegParamVect    = RegParamVect(1:k);\n                    M = M(1:k+1,1:k);\n                    T = T(1:k,1:k);\n                    Z = Z(:,1:k);\n                    V = V(:,1:k);\n                    U = U(:,1:k+1);\n                    if errornorms, Enrm = Enrm(1:k); end\n                    X = X(:,1:j);\n                    saved_iterations = saved_iterations(1:j);\n                    % Stop because the discrepancy principle is satisfied.\n                    break\n                end\n            end\n            end\n        end\n        elseif strcmp(RegParam,'discrep')\n            if Rnrm(k) < eta*NoiseLevel\n                % stopping criterion\n                if StopIt == MaxIter % the method has not stopped, yet\n                    if verbose\n                        disp('The discrepancy principle is satisfied')\n                    end\n                    StopFlag = 'discrepancy principle (secant update method) satisfied';\n                    if ~AlreadySaved && ~NoStop\n                        j = j+1;\n                        X(:,j) = x;\n                        if restart\n                            saved_iterations(j) = ktotcount;\n                        else\n                            saved_iterations(j) = k;\n                        end\n                        AlreadySaved = 1;\n                    end\n                    StopIt = k;\n                    StopReg.X = x;\n                    StopReg.It = k;\n                    StopReg.RegP = RegParamk;\n                    StopReg.Xnrm = Xnrm(k);\n                    StopReg.Rnrm = Rnrm(k);\n                    if errornorms, StopReg.Enrm = Enrm(k); end\n                    if ~ NoStop\n                        Xnrm    = Xnrm(1:k);\n                        Rnrm    = Rnrm(1:k);\n                        RegParamVect    = RegParamVect(1:k);\n                        M = M(1:k+1,1:k);\n                        T = T(1:k,1:k);\n                        Z = Z(:,1:k);\n                        V = V(:,1:k);\n                        U = U(:,1:k+1);\n                        if errornorms, Enrm = Enrm(1:k); end\n                        X = X(:,1:j);\n                        saved_iterations = saved_iterations(1:j);\n                        % stop because the discrepancy principle is satisfied\n                        break\n                    else\n                        RegParamk = abs((eta*NoiseLevel - flsqr_res)/(Rnrm(k) - flsqr_res))*(RegParamk^2);\n                        % RegParamk = RegParamk^2; \n                        % RegParamk = abs((eta*NoiseLevel - flsqr_res)/(Rnrm(k) - flsqr_res))^2*RegParamk;\n                        % RegParamk = abs((eta*NoiseLevel - flsqr_res)/(Rnrm(k) - flsqr_res))*RegParamk;\n                        RegParamk = sqrt(RegParamk);\n                        if k~=MaxIter, RegParamVect(k+1) = RegParamk; end\n                    end\n                else\n                    RegParamk = abs((eta*NoiseLevel - flsqr_res)/(Rnrm(k) - flsqr_res))*(RegParamk^2);\n                    % RegParamk = RegParamk^2; \n                    % RegParamk = abs((eta*NoiseLevel - flsqr_res)/(Rnrm(k) - flsqr_res))*RegParamk;\n                    RegParamk = sqrt(RegParamk);\n                    if k~=MaxIter, RegParamVect(k+1) = RegParamk; end\n                end\n            else\n                RegParamk = abs((eta*NoiseLevel - flsqr_res)/(Rnrm(k) - flsqr_res))*(RegParamk^2);\n                % RegParamk = RegParamk^2; \n                % RegParamk = abs((eta*NoiseLevel - flsqr_res)/(Rnrm(k) - flsqr_res))*RegParamk;\n                RegParamk = sqrt(RegParamk);\n                if k~=MaxIter, RegParamVect(k+1) = RegParamk; end\n            end\n        elseif strcmp(RegParam,'discrepit')\n            if k>2\n                % stopping criterion\n                if StopIt == MaxIter % the method has not stopped, yet\n                    if abs(RegParamVect(k)-RegParamVect(k-1))/RegParamVect(k-1) < regPflat && abs(RegParamVect(k-1)-RegParamVect(k-2))/RegParamVect(k-2)<regPflat\n                        if verbose\n                            disp('The stopping criterion for the discrepancy principle is satisfied')\n                        end\n                        StopFlag = 'discrepancy principle (stopping criterion) satisfied';\n                        if ~AlreadySaved && ~NoStop\n                            j = j+1;\n                            X(:,j) = x;\n                            if restart\n                                saved_iterations(j) = ktotcount;\n                            else\n                                saved_iterations(j) = k;\n                            end\n                            AlreadySaved = 1;\n                        end\n                        StopIt = k;\n                        StopReg.X = x;\n                        StopReg.It = k;\n                        StopReg.RegP = RegParamk;\n                        StopReg.Xnrm = Xnrm(k);\n                        StopReg.Rnrm = Rnrm(k);\n                        if errornorms, StopReg.Enrm = Enrm(k); end\n                        if ~ NoStop\n                            Xnrm    = Xnrm(1:k);\n                            Rnrm    = Rnrm(1:k);\n                            RegParamVect    = RegParamVect(1:k);\n                            M = M(1:k+1,1:k);\n                            T = T(1:k,1:k);\n                            Z = Z(:,1:k);\n                            V = V(:,1:k);\n                            U = U(:,1:k+1);\n                            if errornorms, Enrm = Enrm(1:k); end\n                            X = X(:,1:j);\n                            saved_iterations = saved_iterations(1:j);\n                            % stop because the discrepancy principle is satisfied\n                            break\n                        end\n                    end\n                end\n            end\n        elseif strcmp(RegParam,'wgcv') || strcmp(RegParam,'gcv') || strcmp(RegParam,'modgcv')\n            % check the stopping criterion (all the possibilities)\n            if k > 1\n            if strcmpi(stopGCV, 'GCVvalues')\n                if StopIt == MaxIter % the method has not stopped, yet\n                if abs((GCV(k)-GCV(k-1)))/GCV(2) < degflat && StopIt == MaxIter\n                % the method has not stopped, yet\n                        if verbose\n                            disp('The stopping criterion for GCV principle is satisfied')\n                        end\n                        % stop because the GCV curve is too flat\n                        StopFlag = 'GCV curve too flat';\n                        if ~AlreadySaved && ~ NoStop\n                            j = j+1;\n                            X(:,j) = x;\n                            if restart\n                                saved_iterations(j) = ktotcount;\n                            else\n                                saved_iterations(j) = k;\n                            end\n                            AlreadySaved = 1;\n                        end\n                        StopIt = k;\n                        StopReg.X = x;\n                        StopReg.It = k;\n                        StopReg.RegP = RegParamk;\n                        StopReg.Xnrm = Xnrm(k);\n                        StopReg.Rnrm = Rnrm(k);\n                        if errornorms, StopReg.Enrm = Enrm(k); end\n                        if ~ NoStop\n                            Xnrm    = Xnrm(1:k);\n                            Rnrm    = Rnrm(1:k);\n                            RegParamVect    = RegParamVect(1:k);\n                            M = M(1:k+1,1:k);\n                            T = T(1:k,1:k);\n                            Z = Z(:,1:k);\n                            V = V(:,1:k);\n                            U = U(:,1:k+1);\n                            if errornorms, Enrm = Enrm(1:k); end\n                            X = X(:,1:j);\n                            saved_iterations = saved_iterations(1:j);\n                            % stop because the GCV stopping criterion is satisfied\n                            break\n                        end\n                elseif GCV(k-1) < GCV(k) && ~ warningGCV && StopIt == MaxIter % Potential minimum reached. \n                    warningGCV = 1;\n                    % Save data just in case.\n                    x_save = x;\n                    k_save = k; % for computing the GCV stopping criterion\n                    j_save = j;\n                    AlreadySaved_save = AlreadySaved;\n                    RegParamk_save = RegParamk;\n                    if restart, ktotcount_save = ktotcount; end\n                elseif warningGCV && k > min(k_save + mintol, MaxIter) && StopIt == MaxIter % Passed window\n                    if GCV(k_save) < GCV(k_save+1:min(k_save + mintol, MaxIter))\n                        if verbose\n                            disp('The stopping criterion for GCV principle is satisfied')\n                        end\n                        StopFlag = 'increasing GCV minima';\n                        StopIt = k_save;\n                        StopReg.It = k_save;\n                        StopReg.X = x_save;\n                        StopReg.RegP = RegParamk_save;\n                        StopReg.Xnrm = Xnrm(k_save);\n                        StopReg.Rnrm = Rnrm(k_save);\n                        if errornorms\n                            StopReg.Enrm = Enrm(k_save);\n                        end\n                        if ~ NoStop\n                            j = j_save;\n                            saved_iterations = saved_iterations(1:j);\n                            X = X(:,1:j);\n                            if ~AlreadySaved_save\n                                j = j+1;\n                                X(:,j) = x_save;\n                                if restart\n                                    saved_iterations(j) = ktotcount_save;\n                                else\n                                    saved_iterations(j) = k_save;\n                                end\n                            end\n                            Xnrm    = Xnrm(1:k_save);\n                            Rnrm    = Rnrm(1:k_save);\n                            RegParamVect    = RegParamVect(1:k_save);\n                            M = M(1:k_save+1,1:k_save);\n                            T = T(1:k_save,1:k_save);\n                            Z = Z(:,1:k_save);\n                            V = V(:,1:k_save);\n                            U = U(:,1:k_save+1);\n                            if errornorms\n                                Enrm = Enrm(1:k_save);\n                                if BestReg.It > k_save\n                                    [BestReg.Enrm, BestReg.It] = min(Enrm);\n                                    BestReg.RegP = RegParamVect(BestReg.It);\n                                    BestReg.Xnrm = Xnrm(BestReg.It);\n                                    BestReg.Rnrm = Rnrm(BestReg.It);\n                                    % recompute the best solution again\n                                    ktemp = BestReg.It;\n                                    Mtemp = M(1:ktemp+1,1:ktemp);\n                                    Ztemp = Z(:,1:ktemp);\n                                    rhsk = rhs(1:ktemp+1);\n                                    [Uk, Sk, Vk] = svd(Mtemp);\n                                    if ktemp==1\n                                        Sk = Sk(1,1);\n                                    else\n                                        Sk = diag(Sk);\n                                    end\n                                    rhskhat = Uk'*rhsk;\n                                    if Rfactor\n                                        [~, ZRksq] = qr(Ztemp,0);\n                                    end\n                                    if ~Rfactor\n                                        Dk = Sk.^2 + RegParamk^2;\n                                        rhskhat = Sk .* rhskhat(1:ktemp);\n                                        yhat = rhskhat(1:ktemp)./Dk;\n                                        y = Vk * yhat;\n                                    else\n                                        MLk = [Mtemp; RegParamk*ZRksq];\n                                        rhsLk = [rhsk; zeros(ktemp,1)];\n                                        y = MLk\\rhsLk;\n                                    end\n                                    dtemp = Ztemp*y;\n%                                     if precond, dtemp = P_solve(L, dtemp); end\n                                    xtemp = x0 + dtemp;\n                                    BestReg.X = xtemp;\n                                end\n                            end\n                            X = X(:,1:j);\n                            saved_iterations = saved_iterations(1:j);\n                            if restart, ktotcount = ktotcount_save; end\n                            % stop because the GCV stopping criterion is satisfied\n                            break\n                        end\n                    else\n                        warningGCV = 0;\n                    end\n                end\n            elseif strcmpi(stopGCV, 'resflat')\n                if abs((Rnrm(k)-Rnrm(k-1)))/Rnrm(k-1) < resdegflat && ...\n                    Rnrm(k) == min(Rnrm(1:k)) && StopIt == MaxIter\n                    if verbose\n                        disp('The stopping criterion for GCV principle is satisfied')\n                    end\n                    % stop because discrepancy (i.e., residual for the\n                    % regularized problem) stabilizes\n                    StopFlag = 'the residual norm stabilizes';\n                    if ~AlreadySaved && ~NoStop\n                        j = j+1;\n                        X(:,j) = x;\n                        if restart\n                            saved_iterations(j) = ktotcount;\n                        else\n                            saved_iterations(j) = k;\n                        end\n                        AlreadySaved = 1;\n                    end\n                    StopIt = k;\n                    StopReg.X = x;\n                    StopReg.It = k;\n                    StopReg.RegP = RegParamk;\n                    StopReg.Xnrm = Xnrm(k);\n                    StopReg.Rnrm = Rnrm(k);\n                    if errornorms, StopReg.Enrm = Enrm(k); end\n                    if ~ NoStop\n                        Xnrm    = Xnrm(1:k);\n                        Rnrm    = Rnrm(1:k);\n                        RegParamVect    = RegParamVect(1:k);\n                        M = M(1:k+1,1:k);\n                        T = T(1:k,1:k);\n                        Z = Z(:,1:k);\n                        V = V(:,1:k);\n                        U = U(:,1:k+1);\n                        if errornorms, Enrm = Enrm(1:k); end\n                        X = X(:,1:j);\n                        saved_iterations = saved_iterations(1:j);\n                        break\n                    end\n                end\n                end\n            end\n            end\n        end\nend\nif k == MaxIter \n    if StopIt == MaxIter\n        % Stop because max number of iterations reached\n        if verbose\n            disp('Reached maximum number of iterations')\n        end\n        StopFlag = 'reached maximum number of iterations';\n        if ~AlreadySaved\n            j = j+1;\n            X(:,j) = x;\n            if restart\n                saved_iterations(j) = ktotcount;\n            else\n                saved_iterations(j) = k;\n            end\n        end\n        StopReg.X = x;\n        StopReg.It = k;\n        StopReg.RegP = RegParamk;\n        StopReg.Xnrm = Xnrm(k);\n        StopReg.Rnrm = Rnrm(k);\n        if errornorms, StopReg.Enrm = Enrm(k); end\n        Xnrm    = Xnrm(1:k);\n        Rnrm    = Rnrm(1:k);\n        RegParamVect    = RegParamVect(1:k);\n        M = M(1:k+1,1:k);\n        T = T(1:k,1:k);\n        Z = Z(:,1:k);\n        V = V(:,1:k);\n        U = U(:,1:k+1);\n        if errornorms, Enrm = Enrm(1:k); end\n        X = X(:,1:j);\n        saved_iterations = saved_iterations(1:j);\n    end \nend\nif ~noIterBar, close(h_wait), end\nif nargout==2\n  if NoStop\n      info.its = k;\n  else\n      info.its = StopIt;\n  end\n  info.saved_iterations = saved_iterations(1:j);\n  info.StopReg = StopReg;\n  info.StopFlag = StopFlag;\n  if errornorms\n    info.Enrm = Enrm;\n    info.BestReg = BestReg;\n  end\n  info.Xnrm = Xnrm;\n  info.Rnrm = Rnrm;\n  info.RegP = RegParamVect;\n  if strcmp(RegParam,'wgcv') || strcmp(RegParam,'gcv') || strcmp(RegParam,'modgcv')\n    info.GCValues = GCV(1:k);\n  end\n  if strcmp(DecompOut,'on')\n      info.V = V(:,1:k);\n      info.U = U(:,1:k+1);\n      info.Z = Z(:,1:k);\n      info.T = T(1:k,1:k);\n      info.M = M(1:k+1,1:k);\n  end\n  if restart\n      info.ktotcount = ktotcount;\n  end\nend\n\n%% ---------------SUBFUNCTIONS ---------------------------------------\nfunction [U,R] = householderQR(L)\n%   \n%  [U,R] = householderQR(L)\n%  This function computes the Householder-QR factorization of L\n%  (a \"projected\" regularization matrix), that will be used to define a\n%  \"projected\" regularization matrix R to employ within the LSQR iterates.\n%\n\n[m, n] = size(L);\nR = L;\nU = zeros(m, n);\nfor k = 1:n\n    x = L(k:m,k);\n    e = zeros(length(x),1); e(1) = 1;\n    u = sign(x(1))*norm(x(:))*e + x;\n    u = u./norm(u(:));\n    R(k:m, k:n) = R(k:m, k:n) -2*u*(u'*R(k:m, k:n));\n    U(k:m,k) = u;\nend\n\nfunction [U,R] = upd_householderQR(L,ll,U,R)\n%   \n% [U,R] = upd_householderQR(L, ll, U, R)\n% This function updates the Householder-QR factorization of [L, ll].\n%\n% Input:\n%   L  - matrix whose QR factorization is defined by U and R\n%   ll - column appended to L, i.e., [L, ll]\n%    U - matrix defining the orthogonal matrix Q, such that L = QR\n%    R - upper triangular factor of L = QR\n%\n\n[m,n] = size(L);\nUnew = zeros(m, n+1);\nUnew(:,1:n) = U;\nw = ll;\nfor i = 1:n\n    u = U(i:m,i);\n    w(i:m) = w(i:m) - 2*u*(u'*w(i:m));\nend\nv = w(1:n); x = w(n+1:m);\ne = zeros(length(x),1); e(1) = 1;\nu = sign(x(1))*norm(x(:))*e + x;\nu = u./norm(u(:));\nx = x -2*u*(u'*x);\nUnew(n+1:m,n+1)=u;\nU = Unew;\nrr = [v; x];\nR = [R, rr];\n\nfunction omega = findomega(bhat, s)\n%\n%   omega = findomega(bhat, s)\n%\n%  This function computes a value for the omega parameter used in wGCV.\n%\n%  The method: Assume the 'optimal' regularization parameter to be the\n%  smallest singular value.  Then we take the derivative of the GCV\n%  function with respect to alpha, evaluate it at alpha_opt, set the \n%  derivative equal to zero and then solve for omega.\n%  \n%  Input:   bhat -  vector U'*b, where U = left singular vectors\n%              s -  vector containing the singular values\n%\n%  Output:     omega - computed value for the omega parameter.\n\n%\n%   First assume the 'optimal' regularization parameter to be the smallest\n%   singular value.\n%\n\n%\n% Compute the needed elements for the function.\n%\nm = length(bhat);\nn = length(s);\n\nt0 = sum(abs(bhat(n+1:m)).^2);\nalpha = s(end);\ns2 = abs(s) .^ 2;\nalpha2 = alpha^2;\n\ntt = 1 ./ (s2 + alpha2);\n\nt1 = sum(s2 .* tt);\nt2 = abs(bhat(1:n).*alpha.*s) .^2;\nt3 = sum(t2 .* abs((tt.^3)));\n\nt4 = sum((s.*tt) .^2);\nt5 = sum((abs(alpha2*bhat(1:n).*tt)).^2);\n\nv1 = abs(bhat(1:n).*s).^2;\nv2 = sum(v1.* abs((tt.^3)));\n\n%\n% Now compute omega.\n%\nomega = (m*alpha2*v2)/(t1*t3 + t4*(t5 + t0));\n", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/IRcodes/IRhybrid_flsqr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5871877002801091}}
{"text": "%% \n% \\documentclass[12pt]{article}\n%\n% \\title{ODEbox: A Toolbox for Ordinary Differential Equations\\\\\n% Example 1}\n% \n% \\author{Matthew Harker and Paul O'Leary\\\\\n% Institute for Automation\\\\\n% University of Leoben\\\\\n% A-8700 Leoben,\n% Austria\\\\\n% URL: automation.unileoben.ac.at\\\\\n% \\\\\n% Original: January 9, 2013\\\\\n% $\\copyright$ 2013\\\\\n% \\\\\n% Last Modified: \\today}\n%%\n%\\section{Initial Value Problem}\n%\n% This file demonstrated the solution of initial value problems using the\n% DOPBox and ODEBox toolbaxes. The example being considered here is:\n%\n% \\begin{equation}\n%    \\ddot{y} + 6\\,\\dot{y} + 9 y = 0\n%    \\hspace{5mm}\n%    \\text{with}\n%    \\hspace{5mm}\n%    y(0) = 10\n%   \\hspace{5mm}\n%   \\text{and} \n%   \\hspace{5mm}\n%   \\dot{y}(0) = -75\n% \\end{equation}\n%\n% The analytical solution to this problem is:\n%\n% \\begin{equation}\n%   y(x) = 10 \\, e^{-3\\,x} - 45 \\,x {e^{-3\\,x}}.\n% \\end{equation}\n%\n% This example has been taken from~\\cite{adams}. \n%\n% This M-file demonstrated the new approach to solving this problem and\n% compared the result with a classical runga-kutta solution as provided by\n% MATLAB.\n%\n%%\n% \\section{Prepare the workspace}\n%\nclose all;\nclear all;\nsetUpGraphics(12) ;\n%%\n% Define the equation and solution as a strings for documentation\n%\nEq = '$$\\ddot{y} - 6\\,\\dot{y} - 9 y = 0$$, with, $$y(0) = 10$$ and $$\\dot{y}(1) = -75$$' ;\nSol = '$$y(x) = 10 \\, e^{-3\\,x} - 45 \\,x {e^{-3\\,x}}$$';\n%\n%------------------------------------------------------------------\n%%\n% \\section{Define the Matrix Linear Differential Operator}\n%\n% Define the number of points used in the solution\n%\nnoPts = 85 ;\n%\n% Define the interval in which the problem is to be solved\n%\nxMin = 0 ;\nxMax = 3 ;\n%\n% Use a nonlinear node placement. This ensures a higher density of nodes\n% where the solution has a highed derivative.\n%\nx = linspace(0,1,noPts)';\nx = 5 * x.^2;\n%\n% Setup the differentiating matrix, with support length 13.\n%\nls = 13;\nD = dopDiffLocal( x, ls, ls );\n%\n% Define the matrix C of constraints, i.e. the initial conditions\n%\nC = zeros(noPts,2) ;\n%\nC(1,1) = 1 ;\nC(:,2) = D(1,:)' ;\n%\nd = [ 10 ; -75]  ;\n%\n% Compute the linear differential operator.\n%\nL = D*D + 6*D + 9*eye(noPts) ;\n%%\n%\\section{Compute the Solutions}\n%\n% Solve the algebraic system of equations as a least squares problem. This\n% is the actual computation of the solution of the differential equation.\n%\ny = odeLSE( L, [] , C, d );\n%%\n% For comparison solve using the MATLAB ode45 method.\n% Runge-Kutta Solution:\n%\n[xm,Y] = ode45(@eulerODE01,[xMin xMax],d');\n%\nym = Y(:,1);\n%%\n% Compute the Analytic Solution as an inline to compare the results\n%\nf = inline('10*exp(-3*t) - 45*t.*exp(-3*t)') ;\n%\nya = f(x);\n%%\n% \\section{Plot the Results}\n%\n% for plot purposes solve beyond the ends\n%\nxp = linspace(xMin-1/4,xMax+1/4,1000) ;\nyp = f(xp);\n%\n% Present the solutions\n%\nsetUpGraphics(12)\nFigureSize=[1 1 10 6];\nset(0,'DefaultFigureUnits','centimeters');\nset(0,'DefaultFigurePosition',FigureSize);\nset(0,'DefaultFigurePaperUnits','centimeters');\nset(0,'DefaultFigurePaperPosition',FigureSize);\nMyAxesPosition=[0.13 0.15 0.86 0.82];\nset(0,'DefaultaxesPosition',MyAxesPosition);\n%\nfig1 = figure;\nplot( xp, yp, 'k' ) ;\nhold on\nplot( x, y, 'ko', 'MarkerFaceColor', 'w' ) ;\n%\nplot( xm, ym,'kv');\nlegend('Analytical','New','Runge-Kutta','Location','NorthEast');\nxlabel('$$x$$');\nylabel('$$y$$');\ngrid on;\nrange = axis;\nplot( range(1:2), [0,0],'k');\naxis([-0.5,3.5,-5,15]);\nplot( x, -4.5*ones(size(x)), 'k.');\n%\n%\\caption{Comparison of the analytical solution, the new numberical \n% method and the Runga-Kutta solution.}\n%%\n%\nsetUpGraphics(12)\nFigureSize=[1 1 10 6];\nset(0,'DefaultFigureUnits','centimeters');\nset(0,'DefaultFigurePosition',FigureSize);\nset(0,'DefaultFigurePaperUnits','centimeters');\nset(0,'DefaultFigurePaperPosition',FigureSize);\nMyAxesPosition=[0.13 0.13 0.86 0.82];\nset(0,'DefaultaxesPosition',MyAxesPosition);\n%\nfig2 = figure;\nsubplot(2,1,1)\nplot( x, y - ya, 'k', 'MarkerFaceColor', 'w' ) ;\nhold on\nplot( x, y - ya, 'k.', 'MarkerFaceColor', 'w' ) ;\nrange = axis;\nplot( range(1:2), [0,0],'k');\nylabel('$$e_{L}$$');\ngrid on;\n%title(Sol);\n%\nsubplot(2,1,2)\nplot( xm, ym - f(xm), 'k', 'MarkerFaceColor', 'w' ) ;\nhold on\nplot( xm, ym - f(xm), 'k.', 'MarkerFaceColor', 'w' ) ;\nhold on;\nrange = axis;\nplot( range(1:2), [0,0],'k');\nxlabel('$$x$$');\nylabel('$$e_{RK}$$');\ngrid on;\n%\n% \\caption{Comparison the residual error for the new method (top)  (Bottom)and \n% for the Runga-Kutta method. Note the residual is orders of magnitude smaller for the new method.}\n%\n%%\n%\\section{Save the figures to disk.}\n%\nfileType = 'eps';\nprintFigure( fig1, 'ivpExp3Sol', fileType);\nprintFigure( fig2, 'ivpExp3Err', fileType);\n%\n%% Define the Bibliography\n%\n% \\bibliographystyle{IEEETran}\n% \\bibliography{odebib}\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41354-ordinary-differential-equation-toolbox-odebox-version-1-1/ODEBoxV1-1/IVPExamples/IVPEx1/IVP1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.5871876852011491}}
{"text": "function [price, opt, L] = PROJ_GMDB_DCA_Fast(proj_params, S_0, gmdb_params, r, q, modelInput)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% About: Pricing Function for DCA-Style Garuanteed Minimum Withdraw Benefit (GMWB) using PROJ method\n%        This version is based on a dollar cost average style investment account (see reference below)\n%\n% Terminal Payoff:  Payoff(tau) = L*exp(g*tau) + (Gam(tau) - L*exp(g*tau))^+\n%                      Gam(tau) = S_M * sum_{m=0}^M(alpha*gamma / S_m)\n%                          tau  = time of death (discrete periods)\n%                            M  = number of periods until time of death (each period length dt)\n%\n% Models Supported: Levy Processes, including jump diffusions and Black-Scholes model\n% Returns: price of contract\n%\n% Author: Justin Lars Kirkby\n% References: 1) Equity-Linked  Guaranteed Minimum Death Benefits with Dollar Cost Averaging, J.L.Kirkby & D.Nguyen, 2021\n%\n% ----------------------\n% Contract/Model Params \n% ----------------------\n% S_0 = initial stock price (e.g. 100)\n% r   = interest rate (e.g. 0.05)\n% q   = dividend yield (e.g. 0.05)\n% M   = number of subintervals of [0,T] (total of M+1 monitoring points in time grid, including S_0)\n% gmdb_params = container of GMDB contract params, see below\n% modelInput =  model inputs, see below\n%\n% ----------------------\n% Numerical (PROJ) Params \n% ----------------------\n% proj_params = numerical params\n%   proj_params.N = number of basis elements, e.g. N = 2^10\n%   proj_params.L1 = gridwidth param, e.g. L1 = 8\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% ------------------\n% GMDB Contract Params\n% ------------------\nL = gmdb_params.L;   % Guarantee Level: Set L = -1 to use ATMF value for L\nalpha = gmdb_params.alpha;  % Period premium payment, paid every dt time units\ngamma = gmdb_params.gamma;  % Proportion of investment retained by policyholder (fee is 1-gamma)\ncontract_type = gmdb_params.contract_type;  % Contract type: 1 = GMDB, 2 = GMDB-RS (Ratchet strike)\np = gmdb_params.death_prob;  % death probability distribution, must be consistent with dt\ng = gmdb_params.g;\n\n% ------------------\n% Model Inputs\n% ------------------\ndt = modelInput.dt;  % Time increment, premiums paid / underlying S is monitored every dt\nphiR = modelInput.rnCHF;  % Risk neutral CHF for time period dt\n\n\ncall = 1;\nER = 0;\n  \nZ = gen_func(-r, dt, p);\nif g == 0\n    Zrg = Z;\nelse\n    Zrg = gen_func(-(r-g), dt, p);\nend\n\nif L == -1\n    MF = gen_func(r - q - g, dt, p);\n    Zg = gen_func(-g, dt, p);\n    L = alpha * gamma * (exp((r-q)*dt)*MF - Zg) / (exp((r-q)*dt) - 1);\nend\n\nMmax = length(p); Tmax = Mmax*dt;\npr_alpha = getTruncationAlpha(Tmax, proj_params.L1, modelInput, modelInput.model);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nN = proj_params.N;\ndx = 2*pr_alpha/(N-1); a = 1/dx;\nA    = 32*a^4;\nC_aN = A/N;\n\n\n\n%%% SHIFTS\nx1    = zeros(1,Mmax);\n\nif contract_type == 1\n    strikes = S_0*L*exp(g*dt*(1:Mmax)) ./ (alpha*gamma*(2:Mmax + 1));\nelse\n    strikes = S_0*ones(1,Mmax);\nend\n\n\nfor m=1:Mmax\n    if m == 1\n        x1(m) = ER;\n    else\n        x1(m) = ER + log(1+exp(x1(m-1)));  %%BENHAMOU SHIFT\n    end\n    %x1(m) = log(m) + .5*(m+1)*ER;    %% LOWER BOUND SHIFT derived in APROJ paper\nend\n\nNm   = floor(a*(x1-ER));\nx1   = ER + (1-N/2)*dx + Nm*dx;\nNNM  = N + Nm(Mmax-1);   %Number of columns of PSI\n\n%%% Now check that we wont fall off the grid later\nfor m=1:Mmax\n    ystar = log((m+1)*strikes(m)/S_0 -1);\n    nbar  = floor((ystar-x1(m))*a+1);\n    % fprintf('%.0f\\n', nbar);\n    if nbar + 1 > N  \n        proj_params.L1 = proj_params.L1*1.25;\n        [price, opt, L] = PROJ_GMDB_DCA_Fast(proj_params, S_0, gmdb_params, r, q, modelInput);\n        return;\n    end\nend\n\ndxi   = 2*pi*a/N;\nxi    = dxi*(1:(N-1))';\nPhiR = [1; phiR(xi)];\n\nb0    = 1208/2520; b1 = 1191/2520; b2 = 120/2520; b3 = 1/2520;\nzeta  = (sin(xi/(2*a))./xi).^4./(b0 + b1*cos(xi/a) +b2*cos(2*xi/a) +b3*cos(3*xi/a));\nAA = 1/A;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% PSI Matrix: 5-Point GAUSSIAN\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nPSI = make_PSI(N,NNM,x1(1),dx,dxi);\n\n%%%%%%%%%%%%%%\n% STEP 1) Value the European!!!\n%%%%%%%%%%%%%%\nbeta  = [AA; zeta.*PhiR(2:N).*exp(-1i*x1(1)*xi)];   %grand(end)=.5*grand(end);\nbeta  = real(fft(beta));\n\ns = european_price(zeta,PhiR,xi,dx, r, q, dt, strikes(1), S_0, ER, N, a, call);\ns = p(1) * 2 * s;\n\n%%%%%%%%%%%%%%\n% STEP 2) Value the rest\n%%%%%%%%%%%%%%\n\nPhiR  = C_aN*PhiR;\nbeta  = PSI(:,1:N)*beta.*PhiR;  %Nm(1)=0\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%% Loop to find PSI_M\nfor n=2:Mmax\n    opt_v = intermediate_asian_price(N, dx, dt, xi, zeta, beta, x1(n), n, r, q, strikes(n), S_0);\n    % fprintf('%.12f \\n',opt_v);\n    \n    beta(2:N) = zeta.*beta(2:N).*exp(-1i*x1(n)*xi); beta(1) = AA;\n    beta      = real(fft(beta));\n    if n < Mmax\n        beta      = PSI(:,Nm(n)+1:Nm(n)+N)*beta.*PhiR;\n    end\n    \n    s = s + p(n) * (n + 1) * opt_v; \nend\n\n\nopt = s * alpha * gamma / S_0;\nprice = L*Zrg - alpha * (exp(r*dt) - Z) / (exp(r*dt) - 1) + opt;\n\nend\n\n\nfunction PSI = make_PSI(N,NNM,x_1,dx,dxi)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% PSI Matrix: 5-Point GAUSSIAN\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nPSI     = zeros(N,NNM);    %The first row will remain ones\nPSI(1,:) = ones(1,NNM);\n\n%%%% Sample\nNeta  = 5*(NNM) + 15;   %sample size\nNeta5 = (NNM) + 3;\ng2    = sqrt(5-2*sqrt(10/7))/6;\ng3    = sqrt(5+2*sqrt(10/7))/6;\nv1    = .5*128/225; \nv2    = .5*(322+13*sqrt(70))/900; \nv3    = .5*(322 - 13*sqrt(70))/900;\n\n\nthet                 = zeros(1,Neta);   %sample initialized\nthet(5*(1:Neta5)-2)  = x_1 -1.5*dx + dx*(0:Neta5-1);\nthet(5*(1:Neta5)-4)  = x_1 -1.5*dx + dx*(0:Neta5-1) - dx*g3;\nthet(5*(1:Neta5)-3)  = x_1 -1.5*dx + dx*(0:Neta5-1) - dx*g2;\nthet(5*(1:Neta5)-1)  = x_1 -1.5*dx + dx*(0:Neta5-1) + dx*g2;\nthet(5*(1:Neta5))    = x_1 -1.5*dx + dx*(0:Neta5-1) + dx*g3;\n\n\n%%%% Weights\nsig      = [-1.5-g3, -1.5-g2, -1.5, -1.5+g2, -1.5+g3, -.5-g3, -.5-g2, -.5, -.5+g2, -.5+g3,];\nsig(1:5) = (sig(1:5) + 2).^3/6;\nsig(6:10) = 2/3 - .5*(sig(6:10)).^3 - (sig(6:10)).^2;\n\nsig([1 5 6 10]) = v3*sig([1 5 6 10]); \nsig([2 4 7 9]) = v2*sig([2 4 7 9]); \nsig([3 8]) = v1*sig([3 8]);\n\n%%%% Fill Matrix\nzz  = exp(1i*dxi*log(1+exp(thet)));\nthet   = zz; \n\n\nfor j=2:N-1\n    PSI(j,:) =  sig(1)*(thet(1:5:Neta-19) + thet(20:5:Neta)) ...\n              + sig(2)*(thet(2:5:Neta-18) + thet(19:5:Neta-1)) ...\n              + sig(3)*(thet(3:5:Neta-17)  + thet(18:5:Neta-2)) ...\n              + sig(4)*(thet(4:5:Neta-16)  + thet( 17:5:Neta-3)) ...\n              + sig(5)*(thet(5:5:Neta-15)  + thet( 16:5:Neta-4)) ...\n              + sig(6)*(thet(6:5:Neta-14)  + thet( 15:5:Neta-5)) ...\n              + sig(7)*(thet(7:5:Neta-13)  + thet( 14:5:Neta-6)) ...\n              + sig(8)*(thet(8:5:Neta-12)  + thet( 13:5:Neta-7)) ...\n              + sig(9)*(thet(9:5:Neta-11)  + thet( 12:5:Neta-8)) ...\n              + sig(10)*(thet(10:5:Neta-10)  + thet( 11:5:Neta-9));\n\n    thet = thet.*zz;\nend\nend\n\nfunction Val = intermediate_asian_price(N, dx, dt, xi, zeta, chf, x_1, M, r, q, W, S_0)\ncall = 1;\na = 1/dx;\nA    = 32*a^4;\nAA = 1/A;\nC_aN = A/N;\nT = M*dt;\n\n%%%%% FINAL VALUE\nystar = log((M+1)*W/S_0 -1);\nnbar  = floor((ystar-x_1)*a+1);\nC     = S_0/(M+1);\nD     = W - C;\nx_1   = ystar- (nbar-1)*dx;\n\nbeta(2:N) = zeta.*chf(2:N).*exp(-1i*x_1*xi); beta(1)=AA;\nbeta      = real(fft(beta)).';\n\n\n\nCc1 = C*( exp(-7/4*dx)/54 + exp(-1.5*dx)/18 + exp(-1.25*dx)/2 + 7*exp(-dx)/27 )/20;\n\nCc2 = C*.05*(28/27 + exp(-7/4*dx)/54 + exp(-1.5*dx)/18 + exp(-1.25*dx)/2 + 14*exp(-dx)/27 ...\n              + 121/54*exp(-.75*dx) + 23/18*exp(-.5*dx) + 235/54*exp(-.25*dx));\n          \nCc3 = C*( (28 + 7*exp(-dx))/3 ...\n              + ( 14*exp(dx) + exp(-7/4*dx) + 242*cosh(.75*dx) + 470*cosh(.25*dx))/12 ...\n              +.25*(exp(-1.5*dx) + 9*exp(-1.25*dx) + 46*cosh(.5*dx)))/90;\n          \nCc4 = C*( 14/3*(2+cosh(dx)) ...\n              + .5*(cosh(1.5*dx) + 9*cosh(1.25*dx) +23*cosh(.5*dx))...\n              +  1/6*(cosh(7/4*dx) + 121*cosh(.75*dx) +235*cosh(.25*dx)))/90;\n\nG           = zeros(nbar+1,1);\nE           = exp(ystar-(nbar-1)*dx+dx*(0:nbar));\n\nG(nbar+1)   = D/24    - Cc1*E(nbar+1);\nG(nbar)     = .5*D    - Cc2*E(nbar);\nG(nbar-1)   = 23*D/24 - Cc3*E(nbar-1);\nG(1:nbar-2) = D       - Cc4*E(1:nbar-2); \n\nVal = C_aN*exp(-r*T)*sum(beta(1:nbar+1).*G);\nif call==1  %Call Option, use Put-Call-Parity\n    if r - q == 0\n        mult = M + 1;\n    else\n        mult = (exp((r-q)*T*(1+1/M))-1)/(exp((r-q)*dt)-1);\n    end\n    Val = Val + C*exp(-r*T)*mult - W*exp(-r*T);\nend\nVal = max(0, Val);\n\nend\n\n\nfunction price = european_price(zeta,PhiR,xi,dx, r, q, T, W, S_0, c1, N, a, call)\n\nW = 2*W - S_0;  % we shift the strike then divide by 2 at the end, this is asian with M=2\n\nlws = log(W/S_0);\nlam = c1 -(N/2 -1)*dx;\nnbar = floor(a*(lws-lam)+1);\nif nbar>=N\n    nbar = N-1;\nend\nxmin = lws - (nbar-1)*dx;\n\n\nCons = 32*a^4;\n\nbeta  = [1/Cons; zeta.*PhiR(2:N).*exp(-1i*xmin*xi)];   %grand(end)=.5*grand(end);\nbeta  = real(fft(beta)).';\n\nG = zeros(1,nbar +1); \nG(nbar +1) = W*(1/24 - 1/20*exp(dx)*(exp(-7/4*dx)/54 + exp(-1.5*dx)/18 + exp(-1.25*dx)/2 + 7*exp(-dx)/27));\n\nG(nbar )   =  W*(.5 -.05*(28/27 + exp(-7/4*dx)/54 + exp(-1.5*dx)/18 + exp(-1.25*dx)/2 + 14*exp(-dx)/27 ...\n            + 121/54*exp(-.75*dx) + 23/18*exp(-.5*dx) + 235/54*exp(-.25*dx)));\n\nG(nbar -1) = W*( 23/24 - exp(-dx)/90*( (28 + 7*exp(-dx))/3 ...\n            + ( 14*exp(dx) + exp(-7/4*dx) + 242*cosh(.75*dx) + 470*cosh(.25*dx))/12 ...\n            +.25*(exp(-1.5*dx) + 9*exp(-1.25*dx) + 46*cosh(.5*dx))) );\n\nG(1: nbar -2) = W - S_0*exp(xmin +dx*(0:nbar-3))/90*( 14/3*(2+cosh(dx)) ...\n                + .5*(cosh(1.5*dx) + 9*cosh(1.25*dx) +23*cosh(.5*dx))...\n                +  1/6*(cosh(7/4*dx) + 121*cosh(.75*dx) +235*cosh(.25*dx)));\n            \nif call == 1  % Use put-call parity\n    price = Cons*exp(-r*T)/N*G*(beta(1:length(G))') + S_0*exp(-q*T) - W*exp(-r*T);\nelse\n    price = Cons*exp(-r*T)/N*G*(beta(1:length(G))');\nend\n\nprice = 0.5*max(price, 0);  % Protect against deep out of money case\n\nend\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/GMDB_DCA/PROJ_GMDB_DCA_Fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.587187681340527}}
{"text": "function [T, DISTR, df, Ybar, S] = symNormalTest2(TEST_TYPE, Ybar1, S1, n1, Ybar2, S2, n2, COV_TYPE, COV_DIFF)\n\n% Two-sample tests for symmetric matrices.\n%\n%   [T, DISTR, df, Ybar, S] = symNormalTest2(TEST_TYPE, Ybar1, S1, n1, Ybar2, [S2], [n2], [COV_TYPE], [COV_DIFF])\n%\n% Input:\n%   TEST_TYPE   Controls the type of test (assuming equal variances\n%               between the two groups):\n%                   'full': H0: both groups have the same mean tensors.\n%                   'val' : H0: both groups have the same eigenvalues,\n%                           with possibly different unknown eigenvectors.\n%                   'vec' : H0: both groups have the same eigenvectors,\n%                           with common unknown eigenvalues.\n%   Ybar1, Ybar2  pxpx[sz] arrays of mean matrices for each group\n%   S1, S2        qxqx[sz] arrays of covariance matrices for each group, q=p(p+1)/2\n%                      (default S2 = 0)\n%   n1, n2        Number of subjects in each group (default n2 = 1).\n%   COV_TYPE      Type of covariance: 'spherical', 'orth-inv' or 'full' (default).\n%   COV_DIFF      Assume different covariances: 1 (yes - default) or 0 (no)\n% Output:\n%   T           [sz] array of test statistics\n%   DISTR       'f' or 'gamma'\n%   df          2x1 degrees of freedom of F, or 2x[sz] parameters of Gamma (nu/2, 2a)\n%   Ybar        pxpx[sz] array of pooled mean matrices\n%   S           qxqx[sz] array of pooled covariance matrices\n%\n% E.g.:\n%   [Ybar1, S1, n1] = symNormalStats(Y(:,:,g1));\n%   [Ybar2, S2, n2] = symNormalStats(Y(:,:,g2));\n%   [T, DISTR, df] = symNormalTest2('vec', Ybar1, S1, n1, Ybar2, S2, n2);\n%\n% Copyright by Armin Schwartzman, 2009\n\n% HISTORY:\n%   2008.12.30 ASH (armins@hsph.harvard.edu) wrote it.\n%\n\n% Check inputs\nif ~exist('S2'),\n    S2 = 0;\nend\nif ~exist('n2'),\n    n2 = 1;\nend\nif (size(Ybar1,1) ~= size(Ybar1,2) | size(S1,1) ~= size(S1,2) | ...\n    size(Ybar2,1) ~= size(Ybar2,2) | size(S2,1) ~= size(S2,2)),\n    error('Wrong input format');\nend\nif (size(Ybar1,1) ~= size(Ybar2,1) | size(S1,1) ~= size(S2,1)),\n    error('Wrong input format');\nend\nif ~exist('COV_TYPE'), COV_TYPE = 'full'; end\nif (~strmatch(COV_TYPE,'spherical') & ~strmatch(COV_TYPE,'rot-inv') & ~strmatch(COV_TYPE,'full')),\n    error('Only spherical, rot-inv and full covariance types supported.')\nend\nif ~exist('COV_DIFF'), COV_DIFF = 1; end\n\n% Constants\nn = n1 + n2;\np = size(Ybar1, 1);\nq = size(S1, 1);\nif (q ~= p*(p+1)/2),\n    error('Wrong input format');\nend\n\n% Pooled mean and covariance\nYbar = (n1*Ybar1 + n2*Ybar2)/n;\nS = ((n1-1)*S1 + (n2-1)*S2)/(n-2);\n\n% Test type\nswitch TEST_TYPE,\n    case 'full',\n        d = permute(vecd(Ybar1 - Ybar2), [1 ndims(Ybar1)+1 2:ndims(Ybar1)]);\n        switch COV_TYPE,\n        case 'spherical',\n            T = n1*n2/n * ndfun('mult', permute(d, [2 1 3:ndims(d)]), d);\n            DISTR = 'f';\n            if COV_DIFF,\n                error('Full test, different spherical cov., not implemented.')\n            end\n            s2 = S(1,1,:);\n            df = [q; q*(n-2)];\n            T = df(2)/df(1) * T./(q*(n-2)*s2);\n        case 'orth-inv',\n            error('Full test, orth-inv cov., not implemented.')\n        case 'full',\n            if COV_DIFF,\n                S = S1/n1 + S2/n2;\n                Sinv = ndfun('inv', S);\n                T = ndfun('mult', permute(d, [2 1 3:ndims(d)]), ndfun('mult', Sinv, d));\n                Sinv1 = ndfun('mult', Sinv, ndfun('mult', S1/n1, Sinv));\n                T1 = ndfun('mult', permute(d, [2 1 3:ndims(d)]), ndfun('mult', Sinv1, d));\n                Sinv2 = ndfun('mult', Sinv, ndfun('mult', S2/n2, Sinv));\n                T2 = ndfun('mult', permute(d, [2 1 3:ndims(d)]), ndfun('mult', Sinv2, d));\n                m = 1./((T1./T).^2/(n1-1) + (T2./T).^2/(n2-1));\n                df(2,:) = m-q+1; df(1,:) = q;\n                DISTR = 'f';\n                T = (m-q+1)./(q*m) .* T;\n                df = shiftdim(df);\n            else\n                Sinv = ndfun('inv', S);\n                T = n1*n2/n * ndfun('mult', permute(d, [2 1 3:ndims(d)]), ndfun('mult', Sinv, d));\n                df = [q; n-q-1];\n                DISTR = 'f';\n                T = df(2)./df(1) .* T./(n-2);\n            end\n        end\n        \n    case 'val',\n        [V1,L1] = ndSymEig(Ybar1); % [V1,L1] = ndfunm('eig', Ybar1);\n        [V2,L2] = ndSymEig(Ybar2); % [V2,L2] = ndfunm('eig', Ybar2);\n        T = n1*n2/n * sum(sum((L1 - L2).^2, 1), 2);\n        switch COV_TYPE,\n        case 'spherical',\n            DISTR = 'f';\n            if COV_DIFF,\n                error('Eigval test, different spherical cov., not implemented.')\n            end\n            s2 = S(1,1,:);\n            df = [p; q*(n-2)];\n            T = df(2)/df(1) * T./(q*(n-2)*s2);\n        case 'orth-inv',\n            error('Full test, orth-inv cov., not implemented.')\n        case 'full',\n            Omega = 0;\n            for i=1:p,\n                W = cat(1, v(i,i,V1), -v(i,i,V2));\n                Omega = Omega + ndfun('mult', W, permute(W, [2 1 3:ndims(W)]));\n            end\n            Omega = (n1*n2)/n * Omega;\n            SS = zeros(size(Omega));  % (2q)x(2q)x[]\n            if COV_DIFF,\n                SS(1:q,1:q,:) = S1(1:q,1:q,:)/n1; SS(q+1:2*q,q+1:2*q,:) = S2(1:q,1:q,:)/n2;\n            else\n                SS(1:q,1:q,:) = S(1:q,1:q,:)/n1; SS(q+1:2*q,q+1:2*q,:) = S(1:q,1:q,:)/n2;\n            end\n            [a,nu] = chi2approx(SS, Omega);\n            DISTR = 'gamma';\n            df = cat(1, nu/2, 2*a);  % shape parameter, scale parameter\n        end\n\n    case 'vec',\n        [V1,L1] = ndSymEig(Ybar1); % [V1,L1] = ndfunm('eig', Ybar1);\n        [V2,L2] = ndSymEig(Ybar2); % [V2,L2] = ndfunm('eig', Ybar2);\n        T = 2*n1*n2/n * (sum(sum(L1.*L2, 1), 2) - sum(sum(Ybar1.*Ybar2, 1), 2));\n        switch COV_TYPE,\n        case 'spherical',\n            DISTR = 'f';\n            if COV_DIFF,\n                error('Eigvec test, different spherical cov., not implemented.')\n            end\n            s2 = S(1,1,:);\n            df = [q-p; q*(n-2)];\n            T = df(2)/df(1) * T./(q*(n-2)*s2);\n        case 'orth-inv',\n            error('Eigvec test, orth-inv cov., not implemented.')\n        case 'full',\n            Omega = 0;\n            for i=1:p,\n                for j=1:p,\n                    W = omega(i,j,n1,n2,V1,V2);\n                    Omega = Omega + ndfun('mult', W, permute(W, [2 1 3:ndims(W)]));\n                end\n            end\n            Omega = (n1*n2)/n * Omega;\n            SS = zeros(size(Omega));  % (2q)x(2q)x[]\n            if COV_DIFF,\n                SS(1:q,1:q,:) = S1(1:q,1:q,:)/n1; SS(q+1:2*q,q+1:2*q,:) = S2(1:q,1:q,:)/n2;\n            else\n                SS(1:q,1:q,:) = S(1:q,1:q,:)/n1; SS(q+1:2*q,q+1:2*q,:) = S(1:q,1:q,:)/n2;\n            end\n            [a,nu] = chi2approx(SS, Omega);\n            DISTR = 'gamma';\n            df = cat(1, nu/2, 2*a);  % shape parameter, scale parameter\n        end\nend\n\n% Adjust output\nT = shiftdim(T, 2);\n\nend\n\n\n%------------------------------------------------------------------------\n% Auxiliary functions\n\nfunction v = v(i,j,U)\n    Ui = zeros(size(U));\n    Ui(:,1,:) = U(:,i,:);\n    Uj = zeros(size(U));\n    Uj(1,:,:) = U(:,j,:);\n    v = ndfun('mult', Ui, Uj);\n    v = vecd((v + permute(v, [2 1 3:ndims(v)]))/2);\n    v = permute(v, [1 ndims(v)+1 2:ndims(v)]);\nend\n\nfunction W = omega(i,j,n1,n2,U1,U2)\n    sz = size(U1);\n    p = sz(1);\n    v1 = v(j, i, permute(U1, [2 1 3:ndims(U1)]))/2;\n    v2 = v(j, i, permute(U2, [2 1 3:ndims(U1)]))/2;\n    b = zeros([p 1 sz(3:end)]);\n    b(1:p,:) = (n1*v2(1:p,:) + n2*v1(1:p,:))/(n1+n2);\n    Eji = zeros(size(U1)); Eji(j,i,:) = 1/2;  Eji(i,j,:) = 1/2;\n    Eji = permute(vecd(Eji), [1 ndims(Eji)+1 2:ndims(Eji)]);\n    w1 = Eji - ndfun('mult', B(U1), b);\n    w2 = Eji - ndfun('mult', B(U2), b);\n    W = cat(1, w1, -w2);\nend\n\nfunction B = B(U)\n    sz = size(U);\n    p = sz(1);\n    q = p*(p+1)/2;\n    B = zeros([q p sz(3:end)]);\n    for i=1:p,\n        vv = v(i,i,U);\n        B(:,i,:) = vv(1:q,1,:);\n    end\nend\n\nfunction [a,nu] = chi2approx(S,Q)\n    SQ = ndfun('mult',S,Q);\n    k1 = ndfunm('trace',SQ);\n    k2 = ndfunm('trace',ndfun('mult',SQ,SQ));\n    a = k2./k1; nu = k1.^2./k2;\nend\n\n\n%------------------------------------------------------------------------\n% Debugging\n% M = zeros(3);\n% S = eye(6);\n% Y = symNormalRnd(M, S, [100 4]);\n% [Ybar1, S1, n1] = symNormalStats(Y(:,:,1:40,:), 'full');\n% [Ybar2, S2, n2] = symNormalStats(Y(:,:,41:100,:), 'full');\n% [T, DISTR, df, Ybar, S] = symNormalTest2('val', Ybar1, S1, n1, Ybar2, S2, n2)\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/statistics/symNormalTest2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.5871840133587996}}
{"text": "function [f] = elec_fit_sphere_optim(r, X, Y, Z, xo, yo, zo)\n\n% elec_fit_sphere_optim - Optimization for elec_fit_sphere.m\n%\n% Called from elec_fit_sphere.m\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:55 $\n\n% Licence:  GNU GPL, no implied or express warranties\n% History:  02/2002, Darren.Weber_at_radiology.ucsf.edu\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% with center (Xo,Yo,Zo) and radius r, the equation of a sphere is:\n%\n% r^2 = (x-xo)^2  +  (y-yo)^2  +  (z-zo)^2\n%\n% This function below creates a scalar value to\n% return to the fminsearch function in elec_fit_sphere.\n\nS = (X-xo).^2  +  (Y-yo).^2  +  (Z-zo).^2  -  r^2;\n\nf = sum( S.^2 );\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_fit_sphere_optim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5871839954262852}}
{"text": "function owens_test01 ( )\n\n%*****************************************************************************80\n%\n%% TEST01 demonstrates the use of T.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    05 February 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST01:\\n' );\n  fprintf ( 1, '  T evaluates Owen''s T function.\\n' );\n  fprintf ( 1, '  Compare to tabulated values.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '          H            A        ' );\n  fprintf ( 1, 'T                         T\\n' );\n  fprintf ( 1, '                                ' );\n  fprintf ( 1, '(Tabulated)               (T)                     DIFF\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, h, a, t1 ] = owen_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    t2 = t ( h, a );\n\n    fprintf ( 1, '  %12.8f  %12.8f  %24.16e  %24.16e  %10.4e\\n', ...\n    h, a, t1, t2, abs ( t1 - t2 ) );\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/owens/owens_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.5871802779149293}}
{"text": "function p = pscale(p,alpha,var)\n%PSCALE       scale of argument by alpha\n%\n%For a polynomial p and scalar alpha, scaling with repect to \"var\".\n%\n%  call:     q = pscale(p,alpha,var) \n%  result:   q{x} = p{alpha*x}    for x denoting the dependent variable (or var).\n%\n%For univariate polynomial p the parameter \"var\" is optional (default: dependent variable).\n%\n%If p does not depend on var, function is executed, possibly with warning, or an error message\n%  is given depending on setting of 'AccessVariable', see polynominit\n%\n%Execution with error bounds in case p or alpha of type intval\n%\n\n% written  07/17/02     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 09/28/08     S.M. Rump  check for rounding to nearest improved\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  e = 1e-30;\n  if 1+e==1-e                           % fast check for rounding to nearest\n    rndold = 0;\n  else\n    rndold = getround;\n    setround(0)\n  end\n\n  if size(p.e,2)<=1                               % univariate polynomial\n    if ( nargin==3 ) & ~isequal(var,p.v)          % polynomial not depending on specified variable\n      INTLAB_POLYNOM_ACCESS_VARIABLE = getappdata(0,'INTLAB_POLYNOM_ACCESS_VARIABLE');\n      switch INTLAB_POLYNOM_ACCESS_VARIABLE\n        case 1, warning('polynomial does not depend on specified variable')\n        case 2, error('polynomial does not depend on specified variable')\n      end\n      if rndold\n        setround(rndold)\n      end\n      return\n    end\n    n = p.e;                                      % degree of polynomial\n    p.c = ( alpha.^(n:-1:0) ) .* p.c ;\n  else                                            % multivariate polynomial\n    if ~ischar(var)                               % dependent variable must be string\n      error('dependent variable must be string')\n    end\n    index = find(strcmp(p.v,var));                % index of dependent variable\n    if isempty(index)                             % polynomial not depending on specified variable\n      INTLAB_POLYNOM_ACCESS_VARIABLE = getappdata(0,'INTLAB_POLYNOM_ACCESS_VARIABLE');\n      switch INTLAB_POLYNOM_ACCESS_VARIABLE\n        case 1, warning('polynomial does not depend on specified variable')\n        case 2, error('polynomial does not depend on specified variable')\n      end  \n      if rndold\n        setround(rndold)\n      end\n      return\n    end\n    p.c = ( alpha.^p.e(:,index) ) .* p.c;\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/polynom/@polynom/pscale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.587180273873987}}
{"text": "function tec_write ( tec_file_name, dim_num, node_num, element_num, ...\n  element_order, node_data_num, node_coord, element_node, node_data )\n\n%*****************************************************************************80\n%\n%% TEC_WRITE writes finite element data to a TEC file.\n%\n%  Discussion:\n%\n%    This program writes the node, element and data files that define\n%    a finite element geometry and data based on that geometry:\n%    * a set of nodes, \n%    * a set of elements based on those nodes, \n%    * a set of data values associated with each node.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    11 March 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, string TEC_FILE_NAME, the name of the TEC file.\n%\n%    Input, integer DIM_NUM, the spatial dimension.\n%\n%    Input, integer NODE_NUM, the number of nodes.\n%\n%    Input, integer ELEMENT_NUM, the number of elements.\n%\n%    Input, integer ELEMENT_ORDER, the order of the elements.\n%\n%    Input, integer NODE_DATA_NUM, the number of data items per node.\n%\n%    Input, real NODE_COORD(DIM_NUM,NODE_NUM), the coordinates of nodes.\n%\n%    Input, integer ELEMENT_NODE(ELEMENT_ORDER,ELEMENT_NUM); \n%    the global index of local node I in element J.\n%\n%    Input, real NODE_DATA(NODE_DATA_NUM,NODE_NUM), the data values associated\n%    with each node.\n%\n  tec_file_unit = fopen ( tec_file_name, 'wt' );\n%\n%  Write the title.\n%\n  fprintf ( tec_file_unit, 'TITLE = \"%s\"\\n', tec_file_name );\n%\n%  Write the variable names.\n%\n  fprintf ( tec_file_unit, 'VARIABLES = ' );\n\n  name = 'X';\n  for dim = 1 : dim_num\n    if ( dim == 1 ) \n      fprintf ( tec_file_unit, '\"%s\"', name );\n    else\n      fprintf ( tec_file_unit, ', \"%s\"', name );\n    end\n    name = s_inc ( name );\n  end\n\n  name = 'data_001';\n  for dim = 1 : node_data_num\n    fprintf ( tec_file_unit, ', \"%s\"', name );\n    name = file_name_inc ( name );\n  end\n\n  fprintf ( tec_file_unit, '\\n' );\n%\n%  Write the ZONE record.\n%\n  if ( dim_num == 2 & element_order == 3 )\n    zonetype = 'FETRIANGLE';\n  elseif ( dim_num == 2 & element_order == 4 )\n    zonetype = 'FEQUADRILATERAL';\n  elseif ( dim_num == 3 & element_order == 4 )\n    zonetype = 'FETETRAHEDRON';\n  elseif ( dim_num == 3 & element_order == 8 )\n    zonetype = 'FEBRICK';\n  else\n    zonetype = 'FEUNKNOWN';\n  end\n\n  fprintf ( tec_file_unit, 'ZONE N = %d, E = %d, ', node_num, element_num );\n  fprintf ( tec_file_unit, 'DATAPACKING = POINT, ZONETYPE = %s\\n', ...\n    zonetype );\n%\n%  Write the node coordinates and node data.\n%\n  for node = 1 : node_num\n    for dim = 1 : dim_num\n      fprintf ( tec_file_unit, '  %10f', node_coord(dim,node) );\n    end\n    for data = 1 : node_data_num\n      fprintf ( tec_file_unit, '  %10f', node_data(data,node) );\n    end\n    fprintf ( tec_file_unit, '\\n' );\n  end\n%\n%  Write the element-node connectivity.\n%\n  for element = 1 : element_num\n    for order = 1 : element_order\n      fprintf ( tec_file_unit, '  %6d', element_node(order,element) );\n    end\n    fprintf ( tec_file_unit, '\\n' );\n  end\n\n  fclose ( tec_file_unit );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEC_WRITE wrote all data to \"%s\".\\n', ...\n    tec_file_name );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/tec_io/tec_write.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.587180273873987}}
{"text": "function testFMinSearchNew\n% Test function to show two things:\n%\n% - how the newly-modified fminsearchbnd works\n% - how to use output functions and plot functions in fminsearch or fminsearchbnd (or other Matlab\n% optimization routines) - heretofore documentation and examples for these have been sparse.\n%\n% note: use the fminsearchbnd that was modified 2007-Nov-29 by Ken Purchase, which handles plot and\n% output functions properly.\n%\n\n\n    % set up the function that returns a sim structure (the simulation function)\n    optFn = @(x, varargin) 100*(x(2)-x(1)^2)^2 + (1-x(1))^2;\n    \n    x0 = [-1.2 1];\n    mins = [-2 0]; %[2 -inf];\n    maxs = [Inf Inf]; %[inf 3];\n\n    % I'm going to pass in a useless extra parameter, just to show that fminsearchbnd and fminsearch\n    % pass this back thru to your optimization function.  Your function could make use if this if\n    % you watned.\n    extraParams = 1;\n    \n    \n    % Set up optimization options - you can leave any of these blank and fminsearch will use\n    % defaults.\n    searchOptions = struct(...\n        'Display','none',...\n        'MaxIter','200*numberOfVariables',...\n        'MaxFunEvals','200*numberOfVariables',...\n        'TolX',1e-6,...\n        'TolFun',1e-6, ...\n        'FunValCheck','off',...\n        'OutputFcn', @firstOutputFunction,...  \n        'PlotFcns',@firstPlotFunction);\n    % NOTE: you could add several output or plot functions by incluing a cell array of function\n    % handles, such as {@firstOutputFunction, @secondOutputFunction}\n    \n      \n    % Run the optimization:\n    [outX,fval,exitflag,output] = fminsearchbnd(optFn, x0, mins, maxs, searchOptions, extraParams);\n    \n\n    % Finally, re-run the best case thru the simulation function and display result:\n    outX\n    finalValue = optFn(outX, extraParams)\n    \n    \n    \n    \n    % Define output and print functions.  These functions are nexted WITHIN the overall routine so they \n    % have access to variables in the above code if needed.\n    %\n\n    function stop = firstOutputFunction(xOutputfcn, optimValues, state, varargin)\n        % create an output function for the fMinSearch\n        %\n        % inputs:\n        % 1) xOutputfcn = the current x values\n        % 2) optimValues - structure having:\n        %         optimValues.iteration = iter;  % iteration number\n        %         optimValues.funccount = numf;  % number of function eval's so far\n        %         optimValues.fval = f;          % value of the function at current iter.\n        %         optimValues.procedure = how;   % how is fminsearch current method (expand, contract, etc)\n        % 3) State = 'iter','init' or 'done'     % where we are in the fminsearch algorithm.\n        % 4) varargin is passed thru fminsearch to the user function and can be anything.\n        %\n\n        stop = false;\n\n        % NOTE: this makes a bit of a messy display, but shows what you can do with an output\n        % function.  You can get much of the same information using the fminsearch input option\n        % 'Display', 'iter'\n        disp(sprintf('Iteration: %d,  Evals: %d,  Current Min Value: %d', ...\n            optimValues.iteration, optimValues.funccount, optimValues.fval));\n        disp(['Best x so far: [' sprintf('%g ', xOutputfcn) ']']);\n        \n        % you could place plotting code here if you didn't want the automatic figure handling of the\n        % plot functions.\n        \n        % you can also modify the value of 'stop' here to true if you want fminseach to terminate\n        % based on any criteria you'd put here.\n    end\n        \n\n\n    function stop = firstPlotFunction(xOutputfcn, optimValues, state, varargin)\n        % create an print function for the fMinSearch\n        %\n        % NOTE: The plot functions do their own management of the plot and axes - if you want to\n        % plot on your own figure or axes, just do the plotting in the output function, and leave\n        % the plot function blank.  \n        %\n        % One thing the plot function DOES have it that it installs STOP and PAUSE buttons on the\n        % plot that allow you to interrupt the optimization to go in and see what's going on, and \n        % then resume, or stop the iteration and still have it exit normally (and report output \n        % values, etc).  \n        %\n        % inputs:\n        % 1) xOutputfcn = the current x values\n        % 2) optimValues - structure having:\n        %         optimValues.iteration = iter;  % iteration number\n        %         optimValues.funccount = numf;  % number of function eval's so far\n        %         optimValues.fval = f;          % value of the function at current iter.\n        %         optimValues.procedure = how;   % how is fminsearch current method (expand, contract, etc)\n        % 3) State = 'iter','init' or 'done'     % where we are in the fminsearch algorithm.\n        % 4) varargin is passed thru fminsearch to the user function and can be anything.\n        %\n        \n        stop = false;\n        \n        hold on; \n        % this is fun - it simply plots the optimization variable (inverse figure of merit) as it \n        % goes along, so you can see it improving, or stop the iterations if it stagnates.\n        rectangle('Position', ...\n            [(optimValues.iteration - 0.45) optimValues.fval, 0.9, 0.5*optimValues.fval]);\n        set(gca, 'YScale', 'log');\n        \n        % when you run this, try pressing the 'stop' or 'pause' buttons on the plot.\n        \n        % you can add any code here that you desire.\n        \n    end\n        \n    \n    \n    \n    \nend % end of test code\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/HRF_Est_Toolbox3/New_fminsearchbnd/testFMinSearchNew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.5871802697351098}}
{"text": "function suborder_num = tetrahedron_nco_suborder_num ( rule )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_NCO_SUBORDER_NUM returns the number of suborders for an NCO rule.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    31 January 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Peter Silvester,\n%    Symmetric Quadrature Formulae for Simplexes,\n%    Mathematics of Computation,\n%    Volume 24, Number 109, January 1970, pages 95-100.\n%\n%  Parameters:\n%\n%    Input, integer RULE, the index of the rule.\n%\n%    Output, integer SUBORDER_NUM, the number of suborders of the rule.\n%\n  if ( rule == 1 )\n    suborder_num = 1;\n  elseif ( rule == 2 )\n    suborder_num = 1;\n  elseif ( rule == 3 )\n    suborder_num = 2;\n  elseif ( rule == 4 )\n    suborder_num = 3;\n  elseif ( rule == 5 )\n    suborder_num = 5;\n  elseif ( rule == 6 )\n    suborder_num = 6;\n  elseif ( rule == 7 )\n    suborder_num = 9;\n\n  else\n\n    suborder_num = -1;\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'TETRAHEDRON_NCO_SUBORDER_NUM - Fatal error!\\n' );\n    fprintf ( 1, '  Illegal RULE = %d\\n', rule );\n    error ( 'TETRAHEDRON_NCO_SUBORDER_NUM - 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/tetrahedron_nco_rule/tetrahedron_nco_suborder_num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.5871802657921019}}
{"text": "function spline_test23 ( )\n\n%*****************************************************************************80\n%\n%% TEST23 tests SPLINE_OVERHAUSER_VAL.\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  ndata = 4;\n  ndim = 2;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST23\\n' );\n  fprintf ( 1, '  SPLINE_OVERHAUSER_VAL evaluates the\\n' );\n  fprintf ( 1, '    Overhauser spline.\\n' );\n%\n%  Set the data.\n%\n  tdata(1) = 1.0;\n  ydata(1,1) =   0.0;\n  ydata(2,1) =   0.0;\n\n  tdata(2) = 2.0;\n  ydata(1,2) =   1.0;\n  ydata(2,2) =   1.0;\n\n  tdata(3) = 3.0;\n  ydata(1,3) =   2.0;\n  ydata(2,3) = - 1.0;\n\n  tdata(4) = 4.0;\n  ydata(1,4) =   3.0;\n  ydata(2,4) =   0.0;\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', ndata );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '       T             Y\\n' );\n  fprintf ( 1, '\\n' );\n\n  for i = 1 : ndata\n    fprintf ( 1, '%14f  ', tdata(i) );\n    for j = 1 : ndim\n      fprintf ( 1, '%14f  ',  ydata(j,i) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n%\n%  Now evaluate the spline all over the place.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  T, Spline value\\n' );\n  fprintf ( 1, '\\n' );\n\n  for i = 0 : 6 * ndata + 3\n\n    tval = ( i ) / 6.0;\n    yval = spline_overhauser_val ( ndim, ndata, tdata, ydata, tval );\n\n    fprintf ( 1, '%14f  ', tval );\n    for j = 1 : ndim\n      fprintf ( 1, '%14f  ',  yval(j) );\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/spline/spline_test23.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.5871802657921019}}
{"text": "function F  = obj_find_valve_param_table_3way(x,Q_r)\n% Objective function to find out the required area vs. spool displacement\n% relationship for 3-way valve.\n% Copyright 2010 MathWorks, Inc.\n\n% x - vector of variable parameters. It is constructed of ten area values\n% a_1 ... a_max - cross-sectional area of the valve at 10 successive \n% spool position s_1 ... s_10. The positions are set by shifting the spool\n% from zero to its maximum opening at constant speed.\n\n% Q_r - required flow rate expressed in percentage with respect to its\n% maximum flow and maximum displacement\n\n% Q_max - maximum flow rate\n\nassignin('base','a_1', x(1));\nassignin('base','a_2', x(2));\nassignin('base','a_3', x(3));\nassignin('base','a_4', x(4));\nassignin('base','a_5', x(5));\nassignin('base','a_6', x(6));\nassignin('base','a_7', x(7));\nassignin('base','a_8', x(8));\nassignin('base','a_9', x(9));\nassignin('base','a_10', x(10));\n\nmodel = 'valve_testrig_flow_char_3way';\nload_system(model);\nsim(model);\n\nk = [1 1 1 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2]; % Weight multipliers\n\n% Computing objective function\nF = 0;\nfor j = 1:11\n    F = F + k(j) * (yout(j) - Q_r(j))^2;\nend\nend\n\n% EOF", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/27260-hydraulic-valve-parameters-from-data-sheets-and-experimental-data/Valve_Params_SH/Ex3_3_Way_Valve/obj_find_valve_param_table_3way.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5871768296411446}}
{"text": "function [delay,maxBitRate,energy] = dtiNeuronBitRate(radius, length, meanFiringRate, myelinated)\n%\n% [delay,maxBitRate,energy] = dtiNeuronBitRate(radius, length, meanFiringRate, [myelinated=true])\n%\n% Returns neural conduction delay in msec, the maximum bit-rate, and the energy consumption\n% given the outer radius (in micrometers), the length (in millimeters), and the mean firing\n% rate (in spikes/sec).\n%\n% Energy requirements are specified in amol glucose / action potential.\n%\n% See:\n%   Brenner et. al. (2000). Synergy in a neural code. Neural Comput.\n%   Wang et. al. (2008). Functional Trade-Offs in White Matter Axonal Scaling. J. Neurosci.\n%   (The main reference that works out the bit-rate.)\n%\n% Also see:\n%   Timing jitter vs. radius: Swadlow (2000). Time and the brain (R. Miller, ed.)\n%   (We assume that timing jitter is +/-10% or the total conduction delay.)\n%\n% 2009.02.06 RFD wrote it.\n\nif(~exist('myelinated','var') || isempty(myelinated))\n    myelinated = true;\nend\n\n[speed,energyPerMm] = dtiNeuralConductionSpeed(radius, myelinated);\n\ndelay = 1 ./ (speed ./ length);\n% delay is in ms- we need seconds, thus the 1000\nenergy = energyPerMm.*length;\nmaxBitRate = log2(1./(meanFiringRate.*0.2.*(delay./1000)));\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/models/dtiNeuronBitRate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5871768255263006}}
{"text": "function specGlobal = doa_music(x,Param,nsrc)\nif(size(x,2)<2)\n    error('ERROR[MUSIC]:\u4fe1\u53f7\u901a\u9053\u6570\u5fc5\u987b\u5927\u4e8e\u7b49\u4e8e2');\nend\n%% STFT\nX = ssl_stft(x.',Param.window,Param.noverlap,Param.nfft,Param.fs);%nbin,nfram,nchan\nX = X(2:end,:,:);\nX = X(Param.freqBins,:,:);\n[nbin,~,nmic] = size(X);\n%% MUSIC\n% linspace\u5305\u542b\u7aef\u70b9\uff0c\u4fdd\u8bc1\u63d2\u503c\u65f6\u4e0d\u4f1a\u51fa\u73b0NaN\naziGrid = linspace(Param.azimuth(1),Param.azimuth(end),round((Param.azimuth(end)-Param.azimuth(1))/Param.alphaRes)+1);\neleGrid = linspace(Param.elevation(1),Param.elevation(end),round((Param.elevation(end)-Param.elevation(1))/Param.alphaRes)+1);\npower = zeros(nbin, length(aziGrid), length(eleGrid));\n\nfor ibin = 1:nbin % \u5bf9\u4e8e\u6bcf\u4e2a\u9891\u70b9 \n    Rxx = (transpose(squeeze(X(ibin,:,:)))*conj(squeeze(X(ibin,:,:))));% \u81ea\u76f8\u5173\u77e9\u9635\n    [U,~,~] = svd(Rxx);    % SVD\u5206\u89e3   Rxx = U * S * U^H\n    En = U(:,nsrc+1:end);  % \u566a\u58f0\u5b50\u7a7a\u95f4\n    fprintf('%d\\n',ibin)\n    for iaz = 1 :length(aziGrid)\n        for iel = 1 :length(eleGrid)\n            v = [cosd(eleGrid(iel))*cosd(aziGrid(iaz));cosd(eleGrid(iel))*sind(aziGrid(iaz));sind(eleGrid(iel))];% 3 x 1\n            tau = v'*(Param.micPos-repmat(Param.micPos(:,1),[1,nmic]))./Param.c; % 1 * nmic  \u53c2\u8003\u9ea6\u514b\u4e3a1\uff1aParam.micPos(:,1)         \n            a = exp(1i*2*pi*Param.f(ibin).*transpose(tau));%nmic x 1     SV = exp(-2*1i*pi*tau*Param.f.');  % nmic x nbin\n            power(ibin,iaz,iel) = 1./(sum(abs( ctranspose(a) * En * ctranspose(En) * a )));\n        end\n    end\nend\n\n% \u5bf9\u6240\u6709\u9891\u7387\u7684\u7a7a\u95f4\u8c31\u52a0\u5728\u4e00\u8d77:\nspec = squeeze(sum(power,1)); %nAzi x nEle\n[az,el]=meshgrid(aziGrid,eleGrid);\n[azi,eli]=meshgrid(Param.azimuth,Param.elevation);\n\nspecInterp = interp2(az,el,spec.',azi,eli);\n% specInterp = interp2(azOri,elOri,spec.',azInterp,elInterp);\nspecGlobal = reshape(specInterp.',1,[]);\nend\n\nfunction X=ssl_stft(x,window,noverlap,nfft,fs)\n\n% Inputs:x: nchan x nsampl  window = blackman(wlen);\n% Output:X: nbin x nfram x nchan matrix \n\n[nchan,~]=size(x);\n[Xtemp,F,T,~] = spectrogram(x(1,:),window,noverlap,nfft,fs);%S nbinxnframe\nnbin = length(F);\nnframe = length(T);\nX = zeros(nbin,nframe,nchan);\nX(:,:,1) = Xtemp;\nfor ichan = 2:nchan\n    X(:,:,ichan) = spectrogram(x(ichan,:),window,noverlap,nfft,fs); \nend\n\nend\n", "meta": {"author": "WenzheLiu-Speech", "repo": "sound-source-localization-algorithm_DOA_estimation", "sha": "9f7e91bce217d69a110441af939cf041c8f26cd9", "save_path": "github-repos/MATLAB/WenzheLiu-Speech-sound-source-localization-algorithm_DOA_estimation", "path": "github-repos/MATLAB/WenzheLiu-Speech-sound-source-localization-algorithm_DOA_estimation/sound-source-localization-algorithm_DOA_estimation-9f7e91bce217d69a110441af939cf041c8f26cd9/ssl_tools/doa_music.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5871768179310275}}
{"text": "function cvx_optval = norm_nuc( X ) %#ok\n\n%NORM_NUC   Internal cvx version.\n\nerror( nargchk( 1, 1, nargin ) );\nif ndims( X ) > 2,\n    error( 'norm_nuc is not defined for N-D arrays.' );\nelseif ~cvx_isaffine( X ),\n    error( 'Input must be affine.' );\nend\n\n%\n% Construct problem\n% \n\n[ m, n ] = size( X ); %#ok\ncvx_begin sdp\n    variable W1(m,m) symmetric\n    variable W2(n,n) symmetric\n    minimize(0.5*(trace(W1)+trace(W2)));\n    [W1,X;X',W2] >= 0; %#ok\ncvx_end\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/@cvx/norm_nuc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5871223843896978}}
{"text": "function [rvts,rvtsSS,rvtsD,rvtsSSD,diagnostics] = realized_twoscale_variance(price,time,timeType,samplingType,samplingInterval,subsamples,options)\n% Estimated quadratic variation using the Two-Scale estimator of Ait-Sahalia, Mykland and Zhang\n%\n% USAGE:\n%   RVTS = realized_twoscale_variance(PRICE)\n%   [RVTS,RVTSSS,RVTSD,RVTSSSD,DIAGNOSTICS] = realized_twoscale_variance(PRICE,TIME,TIMETYPE,SAMPLINGTYPE,SAMPLINGINTERVAL,SUBSAMPLES,OPTIONS)\n%\n% INPUTS:\n%   PRICE            - m by 1 vector of high frequency prices\n%   TIME             - [OPTIONAL] m by 1 vector of times where TIME(i) corresponds to PRICE(i).\n%   TIMETYPE         - [OPTIONAL] String describing the way times are measured\n%                       'wall'    24-hour clock of the form HHMMSS.mmm, e.g. 101543 or 153217\n%                       'seconds' Time measured in seconds past midnight\n%                       'unit'  Unit normalized date format, e.g. .1, .234, .9\n%                         Unit normalized times are more general than the other types and can be\n%                         applied to data from more than one calendar day\n%   SAMPLINGTYPE     - [OPTIONAL] String describing the type of sampling to use when\n%                        filtering PRICE for estimating the fast scale estimator.\n%                        'CalendarTime' - Sample in calendar time using observations separated by\n%                          SAMPLINGINTERVAL seconds\n%                        'CalendarUniform' - Sample in calendar time using SAMPLINGINTERVAL\n%                          observations spread uniformly between TIME(1) and TIME(m)\n%                        'BusinessTime' - Sample in business (tick) time using observation separated\n%                          by SAMPLINGINTERVAL ticks\n%                        'BusinessUniform' - Sample in business (tick) time using observations\n%                          uniformly spaced in business time.\n%                        'Fixed' - Sample at specific points in time. When using fixed,\n%                          SAMPLINGINTERVAL must be a n by 1 vector of times with the same TIMETYPE\n%                          as TIME (i.e. seconds if TIME is in seconds)\n%   SAMPLINGINTERVAL  - [OPTIONAL] Scalar integer or n by 1 vector whose meaning depends on the\n%                         selected SAMPLINGTYPE\n%   OPTIONS           - [OPTIONAL] Realized Two-Scale option structure initialized by calling\n%                         realized_options('Multiscale'). See help realized_options for a description of\n%                         available options.\n%\n% OUTPUTS:\n%   RVTS        - Realized two-scale variance estimate\n%   RVTSSS      - Realized two-scale variance estimate constructed by averaging RVTS across multiple\n%                 initial observations.  If SAMPLINGTYPE is 'BusinessTime' and SAMPLINGINTERAL is 1\n%                 then subsampling is not possible.\n%   RVTSD       - Debiased version of realized two-scale variance estimate\n%   RVTSSSD     - Debiased version of realized two-scale variance estimate constructed by averaging RVTS across multiple\n%                 initial observations.  \n%   DIAGNOSTICS - Structure of useful diagnostic information.  Fields are\n%                   BANDWIDTH             - Ratio of slow scale to fast scale where the fast scale\n%                                           sampling is determined by SAMPLINGTYPE and SAMPLINGINTERVAL.\n%                   NOISEVARIANCE         - Bandi-Russell noise variance estimate. Empty if user\n%                                           supplies bandwidth.\n%                   DEBIASEDNOISEVARIANCE - Bias adjusted estimate of the noise variance.\n%                   IQESTIMATE            - Estimate of IQ used. Empty if not needed. Empty if user\n%                                           supplies bandwidth.\n%\n% COMMENTS:\n%   For best results:\n%     - Use prices sampled close to the highest frequency available, if not using 'BusinessTime' and\n%     - If using calendar time sampling, sample close to the limit of the data availability (e.g. 5-15\n%       seconds for a stock that trades a few thousand times per day)\n%     - When sampling less frequently (e.g. 5 - 30 minutes) standard realized variance is\n%       probably more appropriate\n%     - The debiased version should be preferred to the standard version\n%\n% EXAMPLE:\n%  % Default usage with 'BusinessTime' sampling with interval 1 and automatic bandwidth selection\n%  [RVTS,RVTSSS,RVTSD,RVTSSSD] = realized_twoscale_variance(PRICE)\n%\n%  % 5-tick two-scale variance with automatic bandwidth selection\n%  [RVTS,RVTSSS,RVTSD,RVTSSSD] = realized_twoscale_variance(PRICE,TIME,'wall','BusinessTime',5)\n%\n%  % Two scale variance with a bandwidth of 30 sampling at every tick\n%  options = realized_options('Twoscale');\n%  options.bandwidth = 30;\n%  [RVTS,RVTSSS,RVTSD,RVTSSSD] = realized_twoscale_variance(PRICE,TIME,'wall','BusinessTime',1,0,options)\n%\n%  % 5-tick two-scale variance with automatic bandwidth selection and dense subsampling\n%  [RVTS,RVTSSS,RVTSD,RVTSSSD] = realized_twoscale_variance(PRICE,TIME,'wall','BusinessTime',5,4)\n%\n%  See also REALIZED_OPTIONS, REALIZED_NOISE_ESTIMATE, REALIZED_VARIANCE,\n%  REALIZED_VARIANCE_OPTIMAL_SAMPLING, REALIZED_RANGE, REALIZED_QUANTILE_VARIANCE\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 5/1/2008\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch nargin\n    case 1\n        m = length(price);\n        time = linspace(9.5*3600,16*3600,m)';\n        timeType = 'seconds';\n        samplingType = 'businesstime';\n        samplingInterval = 1;\n        subsamples = 1;\n        options = realized_options('twoscale');\n    case 5\n        subsamples = 1;\n        options = realized_options('twoscale');\n    case 6\n        options = realized_options('twoscale');\n    case 7\n        % Nothing\n    otherwise\n        error('One, five, six or seven inputs required.')\nend\nsamplingType=lower(samplingType);\ntimeType=lower(timeType);\n[errorMessage, options] = realized_twoscale_variance_parameter_check(price,time,timeType,samplingType,samplingInterval,subsamples,options);\n\nif ~isempty(errorMessage )\n    error(errorMessage)\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nlogPrice = log(price);\nfilteredLogPrice = realized_price_filter(logPrice,time,timeType,samplingType,samplingInterval);\n%options.bandwidth= 60;\nif isempty(options.bandwidth)\n    % Estimate the optimal bandwidth if not provided\n    [noiseVariance, debiasedNoiseVariance, IQEstimate] = realized_noise_estimate(price, time, timeType, options);\n    diagnostics.noiseVariance=noiseVariance;\n    diagnostics.debiasedNoiseVariance=debiasedNoiseVariance;\n    diagnostics.IQEstimate=IQEstimate;\n    % Select the correct noise variance estimate\n    if options.useDebiasedNoise\n        selectedNoiseVariance = debiasedNoiseVariance;\n    else\n        selectedNoiseVariance = noiseVariance;\n    end\n    % Compute the bandwidth\n    n = length(filteredLogPrice) - 1;\n    cOpt = ((12 * selectedNoiseVariance^2) / IQEstimate)^(1/3);\n    options.bandwidth = ceil(cOpt * n^(2/3));\nend\n\nbandwidth = ceil(options.bandwidth);\nif bandwidth<2\n    warning('oxfordRealized:smallBandwidth','The selected bandwidth is less then 2, and RTVS is not well defined in this case.  Setting bandwidth to 2 and proceeding.')\n    bandwidth = 2;\nend\ndiagnostics.bandwidth = bandwidth;\n\n\nn = length(filteredLogPrice) - 1;\nK = bandwidth;\nnbar = (n - K + 1) / K;\n[RV,count,naturalCount] = overlap_realized_variance(filteredLogPrice,K);\noverlapScale = count / naturalCount;\nRVq = RV / overlapScale;\nRV1 = overlap_realized_variance(filteredLogPrice,1);\n% Eq. 55\nrvts = RVq - nbar/n * RV1;\n% Eq. 64\nrvtsD = (1-nbar/n)^(-1)*rvts;\n\n% Subsampled RVq and RV1\nsubsampledLogPrices = realized_subsample(logPrice,time,timeType,samplingType,samplingInterval,subsamples);\nrvqs = zeros(subsamples,1);\nrv1s = zeros(subsamples,1);\ntotalCount  = 0;\ntotalCount0 = 0;\nfor i=1:subsamples\n    filteredLogPrice =  subsampledLogPrices{i};\n    [RV,count] = overlap_realized_variance(filteredLogPrice,K);\n    rvqs(i) = RV;\n    totalCount = totalCount + count;\n    if i==1\n        baseCount = count;\n    end\n    [rv1s(i),count] = overlap_realized_variance(filteredLogPrice,1);\n    totalCount0 = totalCount0 + count;\n    if i==1\n        baseCount0 = count;\n    end\nend\nRVqSS = sum(rvqs) * (baseCount / totalCount);\n% RVq is now based on all overlapping blcoks, so need to normalize to the\n% non-overlapping case\nRVqSS = RVqSS / overlapScale;\nRV1SS = sum(rv1s) * (baseCount0 / totalCount0);\nrvtsSS = RVqSS - nbar/n * RV1SS;\nrvtsSSD = (1-nbar/n)^(-1)*rvtsSS;\nend\n\n\nfunction [rv,count,naturalCount] = overlap_realized_variance(price,skip)\n\nnaturalCount = (length(price)-1)/skip;\nm = length(price);\nreturns = price(1+skip:m) - price(1:m-skip);\ncount = length(returns);\nrv = returns' * returns;\n\nend\n\n\nfunction [errorMessage,options] = realized_twoscale_variance_parameter_check(price,time,timeType,samplingType,samplingInterval,subsamples,options)\n% Support function for realized_twoscale_variance that does input validation\n%\n% USAGE:\n%   [ERRORMESSAGE,OPTIONS] = realized_variance_optimal_sampling_parameter_check(PRICE,TIME,TIMETYPE,SAMPLINGTYPE,SAMPLINGINVERVAL,OPTIONS)\n%\n% INPUTS:\n%   See realized_variance_optimal_sampling\n%\n% OUTPUT:\n%   ERRORMESSAGE - String containing a description of the error if one is detected.  Empty if no error.\n%\n% COMMENTS:\n%   See realized_options for a description of the other fields in OPTIONS\n%\n%  See also REALIZED_VARIANCE_OPTIMAL_SAMPLING\n\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 5/1/2008\nerrorMessage = [];\n\nif size(price,2)>size(price,1)\n    price=price';\nend\nif size(price,2)>1\n    errorMessage = 'PRICE must be a m by 1 vector.';\n    return\nend\nif size(time,2)>size(time,1)\n    time=time';\nend\nif any(diff(time)<0)\n    errorMessage = 'TIME must be sorted and increasing';\n    return\nend\nif size(time,2)>1 || length(time)~=length(price)\n    errorMessage = 'TIME must be a m by 1 vector.';\n    return\nend\n\ntimeType=lower(timeType);\nif ~ismember(timeType,{'wall','seconds','unit'})\n    errorMessage = 'TIMETYPE must be one of ''wall'', ''seconds'' or ''unit''.';\n    return;\nend\n\n\nsamplingType=lower(samplingType);\nif ismember(samplingType,{'calendartime','calendaruniform','businesstime','businessuniform'})\n    % Must be a scalar integer\n    if ~isscalar(samplingInterval) || floor(samplingInterval)~=samplingInterval || samplingInterval<1\n        errorMessage = 'SAMPLINGINTERVAL must be a positive integer for the SAMPLINGTYPE selected.';\n        return\n    end\nelse\n    if size(samplingInterval,2)>size(samplingInterval,1)\n        samplingInterval=samplingInterval';\n    end\n    if ~(any(samplingInterval>=t0) && any(samplingInterval<=tT))\n        errorMessage = 'At least one sampling interval must be between min(TIME) and max(TIME) when using ''Fixed'' as SAMPLINGTYPE.';\n        return\n    end\n    if any(diff(samplingInterval)<=0)\n        errorMessage = 'When using ''Fixed'' as SAMPLINGTYPE the vector of sampling times in SAMPLINGINTERVAL must be sorted and strictly increasing.';\n        return\n    end\nend\n\n% Options\n\n\n% List of flat top kernels\nflatTopKernelList = {'bartlett','twoscale','2ndorder','epanechnikov',...\n    'cubic','multiscale','5thorder','6thorder','7thorder','8thorder','parzen',...\n    'th1','th2','th5','th16'};\n\n% List of non flat top kernels\nnonFlatTopKernelList = {'nonflatparzen','qs','fejer','thinf','bnhls'};\n\n% Combined kernel list\nkernelList = [flatTopKernelList nonFlatTopKernelList];\n\n% Check fields for valid values\noptionsFieldNames = fieldnames(options);\n% Insert any missing fiedls\ndefaultOptions = realized_options('Optimal Sampling');\ndefaultFieldNames = fieldnames(defaultOptions);\nmissingFields = setdiff(defaultFieldNames,optionsFieldNames);\nif ~isempty(missingFields)\n    for i = 1:length(missingFields)\n        options.(missingFields{i}) = defaultOptions.(missingFields{i});\n    end\nend\n\nfor i=1:length(optionsFieldNames)\n    fieldName = optionsFieldNames{i};\n    fieldValue = options.(fieldName);\n    if ischar(fieldValue)\n        fieldValue = lower(fieldValue);\n        options.(fieldName) = fieldValue;\n    end\n    \n    switch fieldName\n        case {'medFrequencyKernel'}\n            % Member of kernelList\n            if ~ismember(fieldValue,kernelList)\n                errorMessage = ['OPTIONS.' fieldName ' must be one of the listed types.'];\n                return\n            end\n        case {'medFrequencyBandwidth'}\n            % Non-negative scalar\n            if ~isempty(fieldValue) && ~isnonnegativescalar(fieldValue)\n                errorMessage = ['OPTIONS.' fieldName ' must a non-negative scalar.'];\n                return\n            end\n        case {'useDebiasedNoise','useAdjustedNoiseCount'}\n            % Logical or scalar\n            if ~islogical(fieldValue) && ~ismember(fieldValue,[0 1])\n                errorMessage = 'OPTIONS.useDebiasedNoise must be a logical value.';\n                return\n            end\n        case {'IQEstimationSamplingType','medFrequencySamplingType','noiseVarianceSamplingType'}\n            % One of the sampling types\n            if ~ismember(fieldValue,{'calendartime','calendaruniform','businesstime','businessuniform','fixed'})\n                errorMessage = ['OPTIONS.' fieldName ' must be one of ''CalendarTime'', ''CalendarUniform'', ''BusinessTime'', ''BusinessUniform'' or ''Fixed''.'];\n                return\n            end\n        case {'medFrequencySamplingInterval','noiseVarianceSamplingInterval','IQEstimationSamplingInterval'}\n            % Non-negative scalar, less that 1 if timeType is unit\n            if isempty(fieldValue) || ~isnonnegativescalar(fieldValue)\n                errorMessage = ['OPTIONS.' fieldName ' must be a non-negative scalar between 0 and 1.'];\n                return\n            end\n            if strcmp(timeType,'unit') && fieldValue>1\n                errorMessage = ['OPTIONS.' fieldName ' must be less than 1 if TIMETYPE when ''unit''.'];\n                return\n            end\n    end\nend\n\nif ~isempty(subsamples)\n    if ~isscalar(subsamples) || subsamples<0 || floor(subsamples)~=subsamples\n        errorMessage = 'SUBSAMPLES must be a non-negative scalar.';\n    end\nend\nend\n\nfunction condition = isnonnegativescalar(x)\n% Function that returns logical true if that input is a non-empty scalar >=0\ncondition = ~isempty(x) && isscalar(x) && x>=0;\nend", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/realized_twoscale_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5871223833067885}}
{"text": "function f = spm_fx_mountaincar(x,v,a,P)\n% state equations for mountain car problem\n% FORMAT f = spm_fx_mountaincar(x,v,P)\n% FORMAT f = spm_fx_mountaincar(x,v,a,P)\n% FORMAT f = spm_fx_mountaincar(x,v,P,M)\n% x    - [x, x']\n% v    - exogenous force\n% a    - action\n%\n% P.a  - 0th order coefficients of force\n% P.b  - 1st order coefficients of force\n% P.c  - 2nd order coefficients of force\n% P.d  - action coefficient\n%\n% M    - model structure\n%\n% f    - flow dx/dt\n%\n% see:\n% Gaussian Processes in Reinforcement Learning\n% Carl Edward Rasmussen and Malte Kuss\n% Max Planck Institute for Biological Cybernetics\n% Spemannstra\u00dfe 38, 72076 T\u00a8ubingen, Germany\n% {carl,malte.kuss}@tuebingen.mpg.de\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_fx_mountaincar.m 7679 2019-10-24 15:54:07Z spm $\n \n \n% determine controlled forces (a)\n%==========================================================================\n \n% spm_fx_mountaincar(x,v,P) - recognition model (no action)\n%--------------------------------------------------------------------------\nglobal eta\nif isempty(eta), eta = 8; end\nif nargin == 3\n    \n    P    = a;\n    a    = 0;\n  \nelseif all(isfield(P,{'f','g'}))\n    \n    % spm_fx_mountaincar(x,v,P,M) - generative model (no action)\n    %----------------------------------------------------------------------\n    P.f;\n    P.g;\n    M    = P;\n    P    = a;\n    a    = 0;\n\nend\n\n\n% default parameters\n%--------------------------------------------------------------------------\nif isempty(P)\n    P.a  = 0;\n    P.b  = [0 0];\n    P.c  = [0 0 0 0];\n    P.d  = 1;\nend\n \n% acceleration = force:\n%--------------------------------------------------------------------------\nx     = x(1:2);\na     = tanh((P.d*a + P.a + P.b*x + P.c*kron(x,x))/2);\n \n% f(x)\n%--------------------------------------------------------------------------\ndt    = 1/4;\nif x(1) < 0                                  % gravity\n    dHdx = 2*x(1) + 1;\nelse\n    xx   = x(1)^2;\n    dHdx = (5*xx + 1).^(-3/2) + (x(1)/2).^4;\nend\nf     = [x(2); a + v - dHdx - x(2)/eta]*dt;\n \n\nreturn\n\n \n% NOTES: Plots for figure\n%--------------------------------------------------------------------------\ndx    = 1/64;\nx     = linspace(-2,2,1/dx);\nxx    = x.^2;\ndHdx  = (x < 0).*(2*x + 1);\ndHdx  = (x > 0).*((5*xx + 1).^(-3/2) + (x/2).^4) + dHdx;\nH     = cumsum(dHdx)*dx;\nH     = H - min(H);\n \nsubplot(2,2,1)\nplot(x,H,x.^0,H,':')\nxlabel('position','FontSize',12)\nylabel('height','FontSize',12)\ntitle('mountain car problem','FontSize',16)\naxis square\n \nsubplot(2,2,2)\nplot(x,-dHdx,x,x*0,'-.',x,-x.^0,'--')\nxlabel('position','FontSize',12)\nylabel('force','FontSize',12)\ntitle('forces','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/spm_fx_mountaincar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6757646010190477, "lm_q1q2_score": 0.5871223797992621}}
{"text": "function [v,faces] = generateUnitCells(xy,unitCell,varargin)\n% generate a list of patches according to spatial coordinates and the unitCell\n%\n% Input\n%  xy       - midpoints of the cells\n%  unitCell - spatial coordinates of the unit cell\n%\n% Ouput\n%  v     - list of vertices\n%  faces - list of faces\n\n% compute the vertices\nx = reshape(bsxfun(@plus,xy(:,1),unitCell(:,1).'),[],1);\ny = reshape(bsxfun(@plus,xy(:,2),unitCell(:,2).'),[],1);\n\n% remove equal points\n% in general every measurment point generates 4 or 6 vertex points\n% some of them apear multiple times \n% lets try to reduce them\n\nif ~check_option(varargin,'noStripes')\n  eps = abs(diff(unitCell));\n  eps = eps(eps > max(eps(:))/10);\n  eps = min(eps) / 12;\n  [~,m,n] = unique(round([x-min(x) y-min(y)]./eps),'rows');\nelse\n  [~,m,n] = uniquetol([x-min(x) y-min(y)],0.01/sqrt(size(xy,1)),'ByRows',true );\nend\n\nv = [x(m) y(m)];\n\n% set faces\nfaces = reshape(n, [], size(unitCell,1));\n\n% tic\n% [~,m,n] = unique(round([x-min(x) y-min(y)]./eps),'rows');\n% toc\n\n%%\n% tic\n% [~,m,n] = uniquetol([x-min(x) y-min(y)],0.01/sqrt(size(xy,1)),'ByRows',true );\n% toc\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/EBSDAnalysis/@EBSD/private/generateUnitCells.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.587122379799262}}
{"text": "function [f] = elec_fit_ellipse_optim(r, X, Y, Z, xo, yo, zo)\n\n% elec_fit_ellipse_optim - Optimization for elec_fit_ellipse.m\n%\n% Called from elec_fit_ellipse.m\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:55 $\n\n% Licence:  GNU GPL, no implied or express warranties\n% History:  02/2002, Darren.Weber_at_radiology.ucsf.edu\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% r is a 3x1 vector of radius values for each x,y,z axis component of ellipse\n%\n% equation of ellipsoid with center (xo,yo,zo) and radius for each axis (x,y,z) = (a,b,c):\n% (( x - xo )^2 / a^2) + (( y - yo )^2 / b^2) + (( z - zo )^2 / c^2) = 1\n%\n% This function below creates a scalar value to\n% return to the fminsearch function in elec_fit_sphere.\n\nE = ( (X-xo).^2 )/r(1).^2 + ((Y-yo).^2)/r(2).^2 + ((Z-zo).^2)/r(3).^2  - 1;\n\nf = sum( E .* E );  % sum of squares returned\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_fit_ellipse_optim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.587122364945045}}
{"text": "function cvt_1d_sampling ( n, it_num, s_num )\n\n%*****************************************************************************80\n%\n%% CVT_1D_SAMPLING carries out the Lloyd algorithm.\n%\n%  Discussion:\n%\n%    This program is a variation of the CVT_1D_LLOYD method.\n%    Instead of using an exact technique to determine the Voronoi\n%    regions, it uses sampling.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    09 September 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the number of generators.\n%\n%    Input, integer IT_NUM, the number of CVT iterations.\n%\n%    Input, integer S_NUM, the number of samples in [0,1] to use\n%    when estimating the Voronoi regions.\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CVT_1D_SAMPLING\\n' );\n  fprintf ( 1, '  MATLAB version\\n' );\n  fprintf ( 1, '  Use sampling to implement an approximation of Lloyd''s algorithm\\n' );\n  fprintf ( 1, '  in the 1D unit interval [0,1].\\n' );\n\n  if ( nargin < 1 )\n    n = input ( '  Enter number of generators: ' );\n  elseif ( ischar ( n ) )\n    n = str2num ( n );\n  end\n\n  if ( nargin < 2 ) \n    it_num = input ( '  Enter number of iterations: ' );\n  elseif ( ischar ( it_num ) )\n    it_num = str2num ( it_num );\n  end\n\n  if ( nargin < 3 ) \n    s_num = input ( '  Enter number of sample points: ' );\n  elseif ( ischar ( s_num ) )\n    s_num = str2num ( s_num );\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of generators is %d\\n', n );\n  fprintf ( 1, '  Number of iterations is %d\\n', it_num );\n  fprintf ( 1, '  Number of samples is %d\\n', s_num );\n%\n%  For convenience, add a 0.0 and 1.0 point.\n%  Also, sort the array.\n%\n  g = zeros ( n + 2, 1 );\n  g_new = zeros ( n + 2, 1 );\n\n  g(1,1) = 0.0;\n  if ( 0 )\n    g(2:n+1,1) = rand ( n, 1 );\n  else\n    g(2:n+1,1) = linspace ( 0.01, 0.02, n );\n  end\n  g(n+2,1) = 1.0;\n\n  g = sort ( g );\n%\n%  Print the initial generators.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Initial generators:\\n' );\n  fprintf ( 1, '\\n' );\n  for k = 2 : n + 1\n    fprintf ( 1, '  %4d  %f\\n', k - 1, g(k,1) );\n  end\n%\n%  Initialize the plotting arrays.\n%\n  g_plot = zeros ( n+2, it_num + 1 );\n\n  step = 1 : it_num;\n  e = nan ( it_num, 1 );\n  gm = nan ( it_num, 1 );\n\n  for it = 1 : it_num\n\n    g_plot ( 1:n+2, it ) = g(1:n+2,1);\n\n    s = rand ( s_num, 1 );\n%\n%  We need to \"assign\" each entry of S to the nearest X, then\n%  replace X by the average of the values assigned to it.\n%\n%  There's a faster way for this 1D case.\n%  1) Sort the S values.\n%  2) Determine the values XM that delimit the Voronoi intervals.\n%  3) For each XM, find the index LEFT in S such that S(LEFT) <= XM < S(LEFT+1).\n%  4) Replace X(I) by the average of the S values that you have determined\n%     are within its Voronoi interval.\n%\n    s = sort ( s );\n\n    xm = zeros ( n - 1, 1 );\n    for j = 1 : n - 1\n      xm(j) = 0.5 * ( g(j+1) + g(j+2) );\n    end\n\n    left = r8vec_bracket4 ( s_num, s, n - 1, xm );\n%\n%  Compute the new generators.\n%\n    e(it,1) = 0.0;\n\n    j = 1;\n    g_new(j) = 0.0;\n\n    k2 = 0;\n    for j = 1 : n - 1\n      k1 = k2;\n      k2 = left(j);\n      g_new(j+1) = sum ( s(k1+1:k2) ) / ( k2 - k1 );\n      for k = k1 + 1 : k2\n        e(it,1) = e(it,1) + ( s(k) - g(j+1) ).^2;\n      end\n    end\n\n    k1 = k2;\n    k2 = s_num;\n    j = n + 1;\n    g_new(j) = sum ( s(k1+1:k2) ) / ( k2 - k1 );\n    for k = k1 + 1 : k2\n      e(it,1) = e(it,1) + ( s(k) - g(j) ).^2;\n    end\n\n    j = n + 2;\n    g_new(j) = 1.0;\n\n    e(it,1) = e(it,1) / s_num;\n%\n%  Display the energy.\n%\n    figure ( 1 )\n    plot ( step, log ( e ), 'm-*' )\n    title ( 'Log (Energy)' )\n    xlabel ( 'Step' )\n    ylabel ( 'Energy' )\n    grid\n%\n%  Compute the generator motion.\n%\n    gm(it,1) = sum ( ( g_new(:) - g(:) ).^2 ) / n;\n%\n%  Display the generator motion.\n%\n    figure ( 2 )\n    plot ( step, log ( gm ), 'm-*' )\n    title ( 'Log (Average generator motion)' )\n    xlabel ( 'Step' )\n    ylabel ( 'Motion' )\n    grid\n%\n%  Update the generators.\n%\n    g = g_new;\n\n  end\n\n  g_plot(1:n+2,it_num+1) = g(1:n+2,1);\n\n%\n%  Print the current generators.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Current generators:\\n' );\n  fprintf ( 1, '\\n' );\n  for k = 2 : n + 1\n    fprintf ( 1, '  %4d  %f\\n', k - 1, g(k,1) );\n  end\n%\n%  Plot the evolution of the locations of the generators.\n%\n  figure ( 3 )\n  y = ( 0 : it_num );\n  for k = 1 : n + 2\n    plot ( g_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%  Terminate.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CVT_1D_SAMPLING\\n' );\n  fprintf ( 1, '  Normal end of execution.\\n' );\n  fprintf ( 1, '\\n' );\n  timestamp ( );\n\n  return\nend\nfunction left = r8vec_bracket4 ( nt, t, ns, s )\n\n%*****************************************************************************80\n%\n%% R8VEC_BRACKET4 finds the interval to each of a vector of values.\n%\n%  Discussion:\n%\n%    An R8VEC is a vector of R8's.\n%\n%    The routine always returns the index LEFT of the sorted array\n%    T with the property that either\n%    *  T is contained in the interval [ T(LEFT), T(LEFT+1) ], or\n%    *  T < T(LEFT) = T(1), or\n%    *  T > T(LEFT+1) = T(N).\n%\n%    The routine is useful for interpolation problems, where\n%    the abscissa must be located within an interval of data\n%    abscissas for interpolation, or the \"nearest\" interval\n%    to the (extreme) abscissa must be found so that extrapolation\n%    can be carried out.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    30 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer NT, length of the input array.\n%\n%    Input, real T(NT), an array that has been sorted\n%    into ascending order.\n%\n%    Input, integer NS, the number of points to be bracketed.\n%\n%    Input, real S(NS), values to be bracketed by entries of T.\n%\n%    Output, integer LEFT(NS).\n%    LEFT(I) is set so that the interval [ T(LEFT(I)), T(LEFT(I)+1) ]\n%    is the closest to S(I); it either contains S(I), or else S(I)\n%    lies outside the interval [ T(1), T(NT) ].\n%\n\n%\n%  Check the input data.\n%\n  if ( nt < 2 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8VEC_BRACKET4 - Fatal error!\\n' );\n    fprintf ( 1, '  NT must be at least 2.\\n' );\n    error ( 'R8VEC_BRACKET4 - Fatal error!' );\n  end\n\n  for i = 1 : ns\n\n    left(i) = floor ( ( nt + 1 ) / 2 );\n%\n%  CASE 1: S < T(LEFT):\n%  Search for S in [T(I), T(I+1)] for intervals I = 1 to LEFT-1.\n%\n    if ( s(i) < t(left(i)) )\n\n      if ( left(i) == 1 )\n        continue\n      elseif ( left(i) == 2 )\n        left(i) = 1;\n        continue\n      elseif ( t(left(i)-1) <= s(i) )\n        left(i) = left(i) - 1;\n        continue\n      elseif ( s(i) <= t(2) )\n        left(i) = 1;\n        continue\n      end\n%\n%  ...Binary search for S in [T(I), T(I+1)] for intervals I = 2 to LEFT-2.\n%\n      low = 2;\n      high = left(i) - 2;\n\n      while ( 1 )\n  \n        if ( low == high )\n          left(i) = low;\n          break\n        end\n\n        mid = floor ( ( low + high + 1 ) / 2 );\n\n        if ( t(mid) <= s(i) )\n          low = mid;\n        else\n          high = mid - 1;\n        end\n\n      end\n%\n%  CASE2: T(LEFT+1) < S:\n%  Search for S in [T(I),T(I+1)] for intervals I = LEFT+1 to N-1.\n%\n    elseif ( t(left(i)+1) < s(i) )\n\n      if ( left(i) == nt - 1 )\n        continue\n      elseif ( left(i) == nt - 2 )\n        left(i) = left(i) + 1;\n        continue\n      elseif ( s(i) <= t(left(i)+2) )\n        left(i) = left(i) + 1;\n        continue\n      elseif ( t(nt-1) <= s(i) )\n        left(i) = nt - 1;\n        continue\n      end\n%\n%  ...Binary search for S in [T(I), T(I+1)] for intervals I = LEFT+2 to NT-2.\n%\n      low = left(i) + 2;\n      high = nt - 2;\n\n      while ( 1 )\n\n        if ( low == high )\n          left(i) = low;\n          break\n        end\n\n        mid = floor ( ( low + high + 1 ) / 2 );\n\n        if ( t(mid) <= s(i) )\n          low = mid;\n        else\n          high = mid - 1;\n        end\n\n      end\n%\n%  CASE3: T(LEFT) <= S <= T(LEFT+1):\n%  S is in [T(LEFT), T(LEFT+1)].\n%\n    else\n\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/cvt_1d_sampling/cvt_1d_sampling.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.5871032520202026}}
{"text": "function [p_, KLdiv, exitflag] = optimizeEntropy(p, A, b, Aeq, beq, options)\n\n% number of inequality constraints\nK_ = size(A, 1);\n% number of equality constraints\nK  = size(Aeq, 1);\nA_ = A';\n%b_ = b';\nAeq_ = Aeq';\nbeq_ = beq';\nx0   = zeros(K_ + K, 1);\nInqMat = -eye(K_ + K); \nInqMat(K_ + 1:end, :) = [];\nInqVec = zeros(K_, 1);\n\nlnp = log(p);\n\n% uses analytic gradient and Hessian during optimization\nif nargin < 6\n    options = optimset(... \n        'Display', 'iter', ... \n        'GradObj', 'on', ... \n        'Hessian', 'on', ...\n        'TolFun', 1e-10, ... \n        'TolX', 1e-10, ... \n        'TolCon', 1e-10, ... \n        'MaxFunEvals', 5000, ... \n        'MaxIter', 5000);\nend\n    \n% minimize negative Lagrange function (i.e. maximize Lagrange function)\nif ~K_\n    % equality constraints only\n    [v, dummy, exitflag] = fminunc(@nestedfunU, x0, options);\n    if exitflag > 0\n        lnp_ = lnp - 1 - Aeq_ * v;\n    else\n        lnp_ = lnp;\n    end\nelse\n    % inequality (and equality) constraints\n    [lv, dummy, exitflag] = fmincon(@nestedfunC, x0, InqMat, InqVec, [], [], [], [], [], options);\n    if exitflag > 0\n        % inequality Lagrange multipliers\n        l = lv(1:K_);\n        % equality Lagrange multipliers\n        v = lv(K_ + 1:end);\n        lnp_ = lnp - 1 - A_ * l - Aeq_ * v;\n    else\n        lnp_ = lnp;\n    end\nend\n\np_ = exp(lnp_);\n\nif nargout > 1\n    if exitflag > 0\n        KLdiv = p_' * (lnp_ - lnp);\n    else\n        KLdiv = NaN;\n    end\nend\n\n    % sub-function -- equality case\n    function [mL, g, H] = nestedfunU(v)\n        lnx = lnp - 1 - Aeq_ * v;\n        % robustificaton\n        lnx = max(lnx, -150.0); \n        x = exp(lnx);   \n        % Lagrange dual function\n        L = x' * (lnx - lnp + Aeq_ * v) - beq_ * v; \n        % take neg values since we want to maximize\n        mL = -L;\n        \n        % gradient and Hessian\n        g = beq - Aeq * x;    \n        H = Aeq * ((x * ones(1, K)) .* Aeq_);\n    end\n\n    % sub-function -- inequality case\n    function [mL, g, H] = nestedfunC(lv)\n        % inequality Lagrange multiplier\n        l = lv(1:K_); \n        % equality Lagrange multiplier\n        v = lv(K_ + 1:end); \n        lnx = lnp - 1 - A_ * l - Aeq_ * v;\n        % robustification\n        lnx = max(lnx, -150.0); \n        x = exp(lnx);\n        % Lagrange dual function\n        L = x' * (lnx - lnp) + l' * (A * x - b) + v' * (Aeq * x - beq);\n        % take neg values since we want to maximize\n        mL = -L; \n    \n        % gradient and Hessian\n        g = [b - A * x; beq - Aeq * x];    \n        H = [A * ((x * ones(1, K_)) .* A_), A * ((x * ones(1, K)) .* Aeq_);...\n            Aeq * ((x * ones(1, K_)) .* A_), Aeq * ((x * ones(1, K)) .* Aeq_)];  \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/26478-fully-flexible-extreme-views/FullyFlexibleExtremeViews/optimizeEntropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5870706438637037}}
{"text": "function pyramid_num_test ( )\n\n%*****************************************************************************80\n%\n%% PYRAMID_NUM_TEST tests PYRAMID_NUM.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    04 December 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'PYRAMID_NUM_TEST\\n' );\n  fprintf ( 1, '  PYRAMID_NUM computes the pyramidal numbers.\\n' );\n  fprintf ( 1, '\\n' );\n \n  for n = 1 : 10\n    fprintf ( 1, '  %2d  %6d\\n', n, pyramid_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/polpak/pyramid_num_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.5870706227862517}}
{"text": "function [fx,dF_dX,dF_dTheta] = f_lin1D(Xt,Theta,ut,inF)\n% dummy 2D linear evolution function\n\ndeltat = inF.delta_t;\n\ntry\n    a = inF.a.^-1;\ncatch\n    a = 1;\nend\ntry\n    [uu,dudtheta] = feval(inF.u_fname,Theta(2:end),ut(2:end),inF);\ncatch\n    uu = 0;\n    if size(Theta,1) > 1\n        dudtheta = zeros(size(Theta,1)-1,1);\n    else\n        dudtheta = [];\n    end\nend\n\nA = -a.*exp(Theta(1));\nfx = Xt + deltat.*(A*Xt + ut(1) + uu);\ndF_dX = 1 + deltat.*A;\ndF_dTheta = deltat.*([Xt*A;zeros(size(Theta,1)-1,1)] + [0;dudtheta]);\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_lin1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5870706122475254}}
{"text": "function c = block_fwt( f, w, J)\n%BLOCK_FWT FWT func. wrapper for a block processing\n%   Usage: c = block_fwt( f, w, J);\n%\n%   Input parameters:\n%         f     : Input data.\n%         w     : Analysis Wavelet Filterbank. \n%         J     : Number of filterbank iterations.\n%\n%   Output parameters:\n%         c      : Coefficient vector.\n%\n%   `c = block_fwt(f,w,J)` accepts suitably extended block of data *f*\n%   and produces correct coefficients using the SegDWT algorithm (based on\n%   overlap-save block convolution) with wavelet filters defined by *w* \n%   and *J* levels. *f* is expected to be a column vector or a matrix and \n%   the processing is done column-wise.\n%\n%   Do not call this function directly. The function is called from \n%   |blockana| when used with frame type 'fwt' and 'segola' block transform\n%   handling see |blockframeaccel|.\n%\n%   Function should be independent of block_interface.\n%\n%   See also: block, block_ifwt\n%\n%   References: ltfatnote026\n\nif nargin<3\n  error('%s: Too few input parameters.',upper(mfilename));\nend;\n\n% Initialize the wavelet filters structure\n%h = fwtinit(h,'ana');\n\nif any(w.a~=w.a(1))\n   error('%s: Non-equal subsampling factors are not supported.',upper(mfilename));\nend\n\nw = fwtinit(w);\n% Extended block length \nLs = size(f,1);\n% Low-pass filter length\nm = numel(w.h{1}.h);\n% Low-pass subsampling factor\na = w.a(1);\n% Extension length\nrred = (a^J-1)/(a-1)*(m-a);\n% Block boundaries\nblocksize=w.a(1)^J;\n% Input signal samples to be processed\n\n% This is effectivelly the \"negative\" right extension described in chapter\n% 4.1.4 in the reference.\nL=rred+floor((Ls-rred)/blocksize)*blocksize;\n\nlevelLen = L;\nfiltNo = length(w.h);\nsubbNo = (filtNo-1)*J+1;\nLc = zeros(subbNo,1);\nrunPtr = 0; \nfor jj=1:J\n   for ff=filtNo:-1:2\n      Lc(end-runPtr) = floor((levelLen-m-1)/w.a(ff));\n      runPtr = runPtr + 1;\n   end\n   levelLen = floor((levelLen-m-1)/w.a(1));\nend\nLc(1)=levelLen; \n\n% \n%[Lc, L] = fwtclength(Ls,h,J,'valid');\n\n% Crop to the right length\nif(Ls>L)\n   f=postpad(f,L); \nend\n\nif Ls<rred+a^J\n   error('%s: Insufficient input signal length for the %s flag. Minimum is %i.',upper(mfilename),'''valid''',rred+a^J);\nend\n\nc = comp_fwt(f,w.h,w.a,J,'valid');\n\n% Do the cropping \nrunPtr = 0; \nfor jj=1:J-1\n   for ff=filtNo:-1:2\n      cstart = (a^(J-jj)-1)/(a-1)*(m-a);\n      c{end-runPtr} = c{end-runPtr}(cstart+1:end,:);\n      runPtr = runPtr + 1;\n   end\nend\n\n% To the pack format\nc = cell2mat(c);\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/blockproc/private/block_fwt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.685949442167993, "lm_q1q2_score": 0.5870706067528757}}
{"text": "function c8_tan_test ( )\n\n%*****************************************************************************80\n%\n%% C8_TAN_TEST tests C8_TAN.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    12 February 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  seed = 123456678;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'C8_TAN_TEST\\n' );\n  fprintf ( 1, '  C8_TAN computes the tangent of a C8.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ...\n    '       C1=C8_UNIFORM_01          C2 = C8_TAN(C1)           C3 = C8_ATAN(C1)\\n' );\n  fprintf ( 1, '     ---------------------     ---------------------     ---------------------\\n' );\n  fprintf ( 1, '\\n' );\n\n  for test = 1 : 10\n \n    [ c1, seed ] = c8_uniform_01 ( seed );\n    c2 = c8_tan ( c1 );\n    c3 = c8_atan ( c2);\n\n    fprintf ( 1, '  (%12f  %12f)  (%12f  %12f)  (%12f  %12f)\\n', ...\n      real ( c1 ), imag ( c1 ), real ( c2 ), imag ( c2 ), real ( c3 ), imag ( c3 ) );\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_tan_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.587036707777622}}
{"text": "function tests = test_lansvd\n  tests = functiontests(localfunctions);\nend\n\nfunction A = mat_simple1_1(n)\n    m = 200;\n    if nargin < 1\n        n = 50;\n    end\n    U0 = orth(randn(m));\n    V0 = orth(randn(n));\n    S0 = zeros(m, n);\n    for i=1:n\n        S0(i,i) = m / (i);\n    end\n    A = U0*S0*V0';\nend\n\nfunction verify_lansvd(A, k, testCase)\n    S1 = svds(A, k);\n    options.verbosity = 0;\n    options.tolerance = 16 * eps;\n    options.k = k;\n    S2 = spx.fast.lansvd(A, options);\n    verifyEqual(testCase, S1, S2, 'RelTol', 1e-9);\n\n    [U1, S1, V1] = svds(A, k);\n    S1 = diag(S1);\n    [U2, S2, V2] = spx.fast.lansvd(A, options);\n    verifyEqual(testCase, S1, S2, 'RelTol', 1e-9);\n    verifyEqual(testCase, spx.la.nonorthogonality(U2), 0, 'AbsTol', 1e-9);\n    verifyEqual(testCase, spx.la.nonorthogonality(V2), 0, 'AbsTol', 1e-9);\n    % TODO this tolerance is very high\n    verifyEqual(testCase, abs(U1), abs(U2), 'AbsTol', 1e-5);\n    % verifyEqual(testCase, abs(V1), abs(V2), 'AbsTol', 1e-12);\nend\n\nfunction verify_lansvd_func_handle(A, k, testCase)\n    S.A = @(x)  A *x;\n    S.At = @(x)  (x' * A)';\n    [M, N] = size(A);\n    S.M = M;\n    S.N = N;\n\n    S1 = svds(A, k);\n    options.verbosity = 0;\n    options.tolerance = 16 * eps;\n    options.k = k;\n    S2 = spx.fast.lansvd(S, options);\n    verifyEqual(testCase, S1, S2, 'RelTol', 1e-9);\n\n    [U1, S1, V1] = svds(A, k);\n    [U2, S2, V2] = spx.fast.lansvd(S, options);\n    verifyEqual(testCase, S1, S2, 'RelTol', 1e-9);\n    verifyEqual(testCase, spx.la.nonorthogonality(U2), 0, 'AbsTol', 1e-10);\n    verifyEqual(testCase, spx.la.nonorthogonality(V2), 0, 'AbsTol', 1e-10);\n    verifyEqual(testCase, abs(U1), abs(U2), 'AbsTol', 1e-12);\n    verifyEqual(testCase, abs(V1), abs(V2), 'AbsTol', 1e-12);\nend\n\nfunction verify_lansvd_svt(A, lambda, testCase)\n    options.verbosity = 0;\n    options.tolerance = 16 * eps;\n    options.lambda = lambda;\n    S2 = spx.fast.lansvd(A, options);\n    k = numel(S2);\n    S1 = svds(A, k+1);\n    % verify that the singular value after k-th one is smaller than the threshold\n    verifyTrue(testCase, S1(k+1) <= lambda);\n    verifyEqual(testCase, S1(1:k), S2, 'RelTol', 1e-9);\nend\n\n\nfunction test_simple_cases(testCase)\n    A = [];\n    verify_lansvd(A, 1, testCase);\n    A = [2.4];\n    verify_lansvd(A, 1, testCase);\nend\n\nfunction test_single_row(testCase)\n    A = [1 2 3];\n    verify_lansvd(A, 1, testCase);\n    verify_lansvd_func_handle(A, 1, testCase);\nend\n\nfunction test_single_col(testCase)\n    A = [1 2 3]';\n    verify_lansvd(A, 1, testCase);\nend\n\nfunction test_1(testCase)\n    verify_lansvd(spx.data.mtx_mkt.abb313, 4, testCase);\n    verify_lansvd(spx.data.mtx_mkt.abb313, 10, testCase);\nend\n\nfunction test_2(testCase)\n    verify_lansvd(spx.data.mtx_mkt.illc1850, 4, testCase);\n    verify_lansvd(spx.data.mtx_mkt.illc1850, 10, testCase);\nend\n\nfunction test_3(testCase)\n    verify_lansvd(mat_simple1_1(20), 4, testCase);\nend\n\nfunction test_4(testCase)\n    verify_lansvd(mat_simple1_1(50), 10, testCase);\nend\n\nfunction test_cryg10000(testCase)\n    verify_lansvd(spx.data.mtx_mkt.cryg10000, 4, testCase);\n    verify_lansvd(spx.data.mtx_mkt.cryg10000, 10, testCase);\nend\n\nfunction test_abb313_svt(testCase)\n    verify_lansvd_svt(spx.data.mtx_mkt.abb313, 7.51, testCase);\nend\n\nfunction test_illc1850_svt(testCase)\n    %TODO . The test should pass at much lower thresholds\n    verify_lansvd_svt(spx.data.mtx_mkt.illc1850, 1.5, testCase);\nend\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/library/tests/la/svd/test_lansvd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.587036686901383}}
{"text": "function [U,B_k,V] = lanc_b(A,p,k,reorth)\n%LANC_B Lanczos bidiagonalization.\n%\n% B_k = lanc_b(A,p,k,reorth)\n% [U,B_k,V] = lanc_b(A,p,k,reorth)\n%\n% Performs k steps of the Lanczos bidiagonalization process with\n% starting vector p, producing a lower bidiagonal matrix\n%           [b_11               ]\n%           [b_21 b_22          ]\n%     B_k = [     b_32 .        ]\n%           [          . b_kk   ]\n%           [            b_k+1,k]\n% such that\n%     A*V = U*B_k ,\n% where U and V consist of the left and right Lanczos vectors.\n%\n% Reorthogonalization is controlled by means of reorth:\n%    reorth = 0 : no reorthogonalization,\n%    reorth = 1 : reorthogonalization by means of MGS,\n%    reorth = 2 : Householder-reorthogonalization.\n% No reorthogonalization is assumed if reorth is not specified.\n\n% Reference: G. H. Golub & C. F. Van Loan, \"Matrix Computations\",\n% 3. Ed., Johns Hopkins, 1996.  Section 9.3.4.\n% Referred to as \"bidiag1\" by Paige and Saunders.\n\n% Per Christian Hansen, IMM, April 8, 2001.\n\n% Initialization.\nif (k<1), error('Number of steps k must be positive'), end\nif (nargin < 4), reorth = 0; end\nif (reorth < 0 | reorth > 2), error('Illegal reorth'), end\nif (nargout==2), error('Not enough output arguments'), end\n[m,n] = size(A);\nB_k = sparse(k+1,k);\nif (nargout>1 | reorth==1)\n  U = zeros(m,k); V = zeros(n,k); UV = 1;\nelse\n  UV = 0;\nend\nif (reorth==2)\n  if (k>=n), error('No. of iterations must satisfy k < n'), end\n  HHU = zeros(m,k); HHV = zeros(n,k);\n  HHalpha = zeros(1,k); HHbeta = HHalpha;\nend\n\n% Prepare for Lanczos iteration.\nv = zeros(n,1);\nbeta = norm(p);\nif (beta==0), error('Starting vector must be nonzero'), end\nif (reorth==2)\n  [beta,HHbeta(1),HHU(:,1)] = gen_hh(p);\nend\nu = p/beta;\nif (UV), U(:,1) = u; end\n\n% Perform Lanczos bidiagonalization with/without reorthogonalization.\nfor i=1:k\n\n  r = A'*u - beta*v;\n  if (reorth==0)\n    alpha = norm(r); v = r/alpha;\n  elseif (reorth==1)\n    for j=1:i-1, r = r - (V(:,j)'*r)*V(:,j); end\n    alpha = norm(r); v = r/alpha;\n  else\n    for j=1:i-1\n      r(j:n) = app_hh(r(j:n),HHalpha(j),HHV(j:n,j));\n    end\n    [alpha,HHalpha(i),HHV(i:n,i)] = gen_hh(r(i:n));\n    v = zeros(n,1); v(i) = 1;\n    for j=i:-1:1\n      v(j:n) = app_hh(v(j:n),HHalpha(j),HHV(j:n,j));\n    end\n  end\n  B_k(i,i) = alpha; if (UV), V(:,i) = v; end\n\n  p = A*v - alpha*u;\n  if (reorth==0)\n    beta = norm(p); u = p/beta;\n  elseif (reorth==1)\n    for j=1:i, p = p - (U(:,j)'*p)*U(:,j); end\n    beta = norm(p); u = p/beta;\n  else\n    for j=1:i\n      p(j:m) = app_hh(p(j:m),HHbeta(j),HHU(j:m,j));\n    end\n    [beta,HHbeta(i+1),HHU(i+1:m,i+1)] = gen_hh(p(i+1:m));\n    u = zeros(m,1); u(i+1) = 1;\n    for j=i+1:-1:1\n      u(j:m) = app_hh(u(j:m),HHbeta(j),HHU(j:m,j));\n    end\n  end\n  B_k(i+1,i) = beta; if (UV), U(:,i+1) = u; end\n\nend\n\nif (nargout==1), U = B_k; 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/external/regu/regu/lanc_b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5870366869013829}}
{"text": "function [no,fc]=gridsurf(x,y,z, varargin)\n%\n% [no,fc]=gridsurf(x,y,z)\n%    or\n% [no,fc]=gridsurf(x,y,z, opt)\n% [no,fc]=gridsurf(x,y,z, 'param1', value1, 'param2', value2, ...)\n%\n% convert a grid-shaped surface (used as input for surf) to a quad or triangular mesh\n%\n% author: Qianqian Fang, <q.fang at neu.edu>\n%\n% input:\n%   x,y,z: parameter used as the input for surf()/mesh()\n%   : a surface mesh triangle list (ne x 3)\n%   opt: a list of optional parameters, currently surfacenorm supports:\n%        'Type': [3|4|int] if set to 3 (default), output triangular mesh; if set to 4,\n%                output a quad mesh where fc is an Nx4 array; otherwise,\n%                output a quad mesh where fc is a cell array\n%        'Nodup': [0|1] if set to 0 (default), no duplicated nodes in x/y/z are removed;\n%                if set to 1, duplicated nodes are removed\n%\n% output:\n%   no: output surface node coordinates\n%   fc: output surface connections - if 'type' set to 3 or 4, fc is a numerical array,\n%       otherwise, fc is a cell array with each element containing 4 integers\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nopt=varargin2struct(varargin{:});\n\ns=size(x);\nif(~all(s==size(y) & s==size(z)))\n    error('x/y/z must be a 2D array of the same size');\nend\n\nno=[x(:),y(:),z(:)];\nnodelen=size(no,1);\nfc=zeros((s(1)-1)*s(2),4);\nrow=[(1:s(1)-1)', (2:s(1))', (s(1)+2:2*s(1))', (s(1)+1:2*s(1)-1)'];\n\nfor i=0:s(2)-1\n    fc(i*(s(1)-1)+1:(i+1)*(s(1)-1),:)=row+i*s(1);\nend\n\nfc(fc>nodelen)=fc(fc>nodelen)-nodelen;\n\nif(jsonopt('nodup',0,opt))\n    [no,fc]=removedupnodes(no,fc);\nend\n\noutputtype=jsonopt('type',3,opt);\nif(outputtype==3)\n    fc=[fc(:,[1 2 3]); fc(:,[1 3 4])];\nelseif(outputtype==4)\n    fc=num2cell(fc,2);\nend\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/gridsurf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.5869749331336904}}
{"text": "function linpack_z_test04 ( )\n\n%*****************************************************************************80\n%\n%% TEST04 tests ZGBCO.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 June 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  ml = 1;\n  mu = 1;\n  n = 3;\n  lda = 2*ml+mu+1;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST04\\n' );\n  fprintf ( 1, '  For a complex general band storage matrix:\\n' );\n  fprintf ( 1, '  ZGBCO factors the matrix and estimates the\\n' );\n  fprintf ( 1, '  reciprocal condition number.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The matrix order is N = %d\\n', n );\n  fprintf ( 1, '  The lower band is ML =  %d\\n', ml );\n  fprintf ( 1, '  The upper band is MU =  %d\\n', mu );\n%\n%  Set the values of the matrix A.\n%\n  a_save(1:n,1:n) = 0.0;\n\n  m = ml + mu + 1;\n\n  seed = 123456789;\n\n  for j = 1 : n\n    i1 = max ( 1, j - mu );\n    i2 = min ( n, j + ml );\n    for i = i1 : i2\n      k = i - j + m;\n      [ a(k,j), seed ] = c8_uniform_01 ( seed );\n      a_save(i,j) = a(k,j);\n    end\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The matrix A:\\n' );\n  fprintf ( 1, '\\n' );\n\n  for i = 1 : n\n    for j = 1 : n\n      fprintf ( 1, '  (%8f  %8f)', real ( a_save(i,j) ), imag ( a_save(i,j) ) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n%\n%  Factor the matrix A.\n%\n  [ a, ipvt, rcond ] = zgbco ( a, lda, n, ml, mu );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Estimated reciprocal condition RCOND = %f\\n', rcond );\n\n  return\nend\n", "meta": {"author": "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_z/linpack_z_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5869749328399968}}
{"text": "function [ptbifu, ptroot] = points_init(bw)\n\n% This function initializes the feature points from the binary image\n\n[M, N]= size(bw);\nimdim = M*N + 1;\n\nNeighbor = [-M, 1, M, -1, -1-M, 1-M,  1+M, -1+M];\nLen = prod(size(Neighbor));\n\nseeds = find(bw == 1);\nnpix = prod(size(seeds));\ncountmap = zeros(size(bw));\n\nfor k =1:npix\n    localidx = seeds(k);\n    neighidx = localidx + Neighbor;\n    for i=1:Len\n        idx = neighidx(i);\n        if (idx>0) & (idx<imdim) & (bw(idx) ==1)\n            countmap(localidx) = countmap(localidx)+1;\n        end\n    end\nend\n\n% The bifurcation candidates may connect, but only the central is true\n% bifurcation point\nbw1 = (countmap>=3);\n[labelmap, numlabel] = bwlabel(bw1, 8);\nfor i=1:numlabel\n    candidates = find(labelmap==i);\n    ptbifu(i) = candidates(fix((end+1)/2));\nend\n\nptroot = find(countmap == 1);\n\nptbifu = ptbifu(:);\nptroot = ptroot(:);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23015-feature-based-retinal-image-registration/Registration/code/points_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5869523139887759}}
{"text": "function [Gs]=gsp_graph_multiresolution_old(G,num_levels,varargin)\n%GSP_GRAPH_MULTIRESOLUTION  Compute a multiresolution of graphs\n%   Usage:  [Gs]=gsp_graph_multiresolution(G,num_levels);\n%           [Gs]=gsp_graph_multiresolution(G,num_levels,param);\n%\n%   Input parameters:\n%         G                          : Graph structure.\n%         num_levels                 : Number of times to downsample and coarsen the graph.\n%   Output parameters:\n%         Gs                         : Cell array, with each element containing a graph structure represent a reduced graph.\n%   Additional parameters:\n%         param.downsampling_method  : The graph downsampling method (default='largest_eigenvector')\n%         param.reduction_method     : The graph reduction method (default='Kron')\n%         param.sparsify             : To perform a spectral sparsification step immediately after the graph reduction (default=1)\n%         param.sparsify_epsilon     : Parameter epsilon used in the spectral sparsification (default=min(10/sqrt(G.N),.3))\n%         param.compute_full_eigen   : To also compute the graph Laplacian eigenvalues and eigenvectors for every graph in the multiresolution sequence (default=0)\n%         \n%   'gsp_graph_multiresolution(G,num_levels)' computes a multiresolution of \n%   graph by repeatedly downsampling and performing graph reduction. The\n%   default downsampling method is the largest eigenvector method based on \n%   the polarity of the components of the eigenvector associated with the \n%   largest graph Laplacian eigenvalue. The default graph reduction method\n%   is Kron reduction followed by a graph sparsification step.\n%\n%   See also:  \n%\n%   Demos:  \n% \n%   References: \n%\n%   AUTHORS : David I Shuman, Elle Weeks, Andre Archer, Stefan Faridani, Yan Jin.\n%   TESTING: \n%   REFERENCE:\n\nif nargin>2\n    param=varargin{1};\nelse\n    param=0;\nend\n\nif ~isfield(param,'reduction_method')\n    reduction_method='kron'; \nelse\n    reduction_method=param.reduction_method;\nend\n\nif ~isfield(param,'downsampling_method')\n    downsampling_method='largest_eigenvector';\nelse\n    downsampling_method=param.downsampling_method;\nend\n\nif ~isfield(param,'sparsify')\n    sparsify=1; \nelse\n    sparsify=param.sparsify;\nend\n\n\nif ~isfield(param,'sparsify_epsilon')\n    sparsify_epsilon=min(10/sqrt(G.N),.3);\nelse\n    sparsify_epsilon=param.sparsify_epsilon;\nend\n\nif ~isfield(param,'compute_full_eigen')\n    compute_full_eigen=0; \nelse\n    compute_full_eigen=param.compute_full_eigen;\nend\n\n\n%set up cell for multiresolutions of graphs\nGs=cell(num_levels+1,1);\nGs{1}=G;\nif compute_full_eigen\n    if (~isfield(Gs{1},'U') || ~isfield(Gs{1},'e') )\n        Gs{1}=gsp_compute_fourier_basis(Gs{1});\n    end\nelse\n    if ~isfield(Gs{1},'lmax')\n        Gs{1}=gsp_estimate_lmax(Gs{1});\n    end\nend\nGs{1}.idx=(1:Gs{1}.N)';\nGs{1}.orig_idx=Gs{1}.idx;\n\n\nfor lev=1:num_levels\n    \n    % Graph downsamping: get indices to keep for the new lower resolution graph\n    switch downsampling_method\n        case 'largest_eigenvector'\n            if compute_full_eigen\n                largest_eigenvector = Gs{lev}.U(:,Gs{lev}.N);\n            else\n                [largest_eigenvector,~]=eigs(Gs{lev}.L,1); \n            end\n             largest_eigenvector = largest_eigenvector * sign(largest_eigenvector(1));\n            \n            nonnegative_logicals=(largest_eigenvector >= 0);\n            if sum(nonnegative_logicals) == 0\n                error('Too many pyramid levels. Try fewer.');\n            end\n            keep_inds=find(nonnegative_logicals==1);\n            \n        % we can add other downsampling methods here\n        \n        otherwise\n            error('Unknown graph downsampling method');\n    end\n    \n   \n    % Graph reduction: rewire the new lower resolution graph to form weighted adjacency and Laplacian matrices\n    switch reduction_method\n        case 'kron'\n            % Kron reduction\n            Gs{lev+1}.L=gsp_kron_reduce_old(Gs{lev}.L,keep_inds);\n          \n        % we can add other graph reduction methods here\n        \n        otherwise\n            error('Unknown graph reduction method');\n    end\n    \n    % Spectral sparsification\n    if sparsify\n        N=size(Gs{lev+1}.L,1);\n        sparsify_epsilon=max(sparsify_epsilon,2/sqrt(N));\n    %    gsp_reset_seed();\n        [Gs{lev+1}.L,~,~] = gsp_graph_sparsify_old(Gs{lev+1}.L,sparsify_epsilon);\n    end\n    \n    % Create the new graph from the reduced weighted adjacency matrix \n    new_W=diag(diag(Gs{lev+1}.L))-Gs{lev+1}.L;\n    Gs{lev+1}=gsp_graph(new_W);\n    Gs{lev+1}=gsp_copy_graph_attributes(Gs{lev},'unknown',Gs{lev+1});\n\n    % Copy the coordinates of the subsampled vertices\n    Gs{lev+1}.coords = Gs{lev}.coords(keep_inds,:);\n    \n    % Update indexing\n    Gs{lev+1}.idx=keep_inds;\n    Gs{lev+1}.orig_idx=Gs{lev}.orig_idx(keep_inds);\n    \n    % Compute full eigendecomposition of new graph, if desired\n    if compute_full_eigen\n        Gs{lev+1}=gsp_compute_fourier_basis(Gs{lev+1});\n    else\n        Gs{lev+1}=gsp_estimate_lmax(Gs{lev+1});\n    end\n     \nend\n\n\nend\n\n\n\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/gsp_graph_multiresolution_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.586952303581765}}
{"text": "% RPCA (De la Torre and Black, 2001)\n% process_video('RPCA', 'RPCA', 'dataset/demo.avi', 'output/demo_RPCA.avi');\nsizeim = [params.rows params.cols];\n[L,S] = RPCA(M,sizeim);\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/RPCA/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5869522909662871}}
{"text": "echo on\n%--------------------------------------------------\n% ToUTM\n%   Example conversion from Geodetic to UTM\n%   coordinates.  Creates UTM coordinate listing\n%   in GeoLab 2.0 NE format.\n% 05 Feb 2010\n%\n% M-files:  dms2rad, refell, ell2utm\n%--------------------------------------------------\n%clear all\n\n%---------- Define names and geodetic lat,lon of\n%---------- points to convert\n\n% PLO      07KC005ECC   N 58 54  12.11752 W111 35  21.20267      104.084\n% PLO      07NA001ECC   N 58 59  47.66810 W111 23  32.15643      106.236\n% PLO      100A         N 58 50  16.59244 W111 41  23.36311      106.060\n% PLO      102A         N 58 52  23.70694 W111 46   9.27700      107.385\n% NE       07KC005ECC       6529232.4191      466051.9575            UTM 12\n% NE       07NA001ECC       6539528.0046      477460.4120            UTM 12\n% NE       100A             6522003.1191      460180.9293            UTM 12\n% NE       102A             6525984.6308      455641.7913            UTM 12\n\nname=[\n'07KC005ECC   '\n'07NA001ECC   '\n'100A         '\n'102A         '\n];\nplo=[\n58 54  12.11752  111 35  21.20267      104.084\n58 59  47.66810  111 23  32.15643      106.236\n58 50  16.59244  111 41  23.36311      106.060\n58 52  23.70694  111 46   9.27700      107.385\n];\n\n%---------- Convert to UTM\n\nlatdms=plo(:,1:3);\nlondms=plo(:,4:6);\nlat=dms2rad(latdms);\nlon=-dms2rad(londms);\nn=length(lat);\n[a,b,e2,finv]=refell('NAD27');\n[N,E,Zone]=ell2utm(lat,lon,a,e2);\n\n\n%---------- List results\n\n%[N E Zone]\necho off\n\ndisp(' ');\ns=['          STATION NAME         N (m)',...\n   '            E (m)                 Zone'];\ndisp(s);\ns=['------------------------------------',...\n   '---------------------------------------'];\ndisp(s);\nfor i=1:n\n  s=[' NE       ',name(i,:),'%16.4f %16.4f',...\n     '            UTM %3.0f\\n'];\n  fprintf(s,N(i),E(i),Zone(i));\nend\nfprintf('\\n');\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15285-geodetic-toolbox/geodetic/ToUTM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143777, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5869522886405931}}
{"text": "function [struct_irf_record,D_record,gamma_record,favar]=irfchol(sigma_gibbs,irf_record,It,Bu,IRFperiods,n,favar)\n\n\n\n% function [struct_irf_record D_record gamma_record]=irfchol(sigma_gibbs,irf_record,It,Bu,IRFperiods,n)\n% runs the gibbs sampler to obtain draws from the posterior distribution of IRFs, orthogonalised with a Choleski decomposition\n% inputs:  - matrix'sigma_gibbs': record of the gibbs sampler draws for the sigma matrix (vectorised)\n%          - cell 'irf_record': record of the gibbs sampler draws for the IRFs\n%          - 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%          - integer 'IRFperiods': number of periods for IRFs\n%          - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)\n% outputs: - cell 'struct_irf_record': record of the gibbs sampler draws for the orthogonalised IRFs\n%          - matrix 'D_record': record of the gibbs sampler draws for the structural matrix D\n%          - matrix 'gamma_record': record of the gibbs sampler draws for the structural disturbances variance-covariance matrix gamma\n\n\n\n% this function implements algorithm 2.4.1\n\n\n\n% preallocation: create the matrices and cell arrays that will store the results from the simulations\nstruct_irf_record=cell(n,n);\nD_record=zeros(n^2,It-Bu);\ngamma_record=zeros(n^2,It-Bu);\n% gamma is just identity\ngamma=reshape(eye(n),n^2,1);\npsi=zeros(n,n);\nsigma_gibbs=reshape(sigma_gibbs,n,n,It-Bu);\n% recall L from the sampling process in this case, analogue to beta and sigma\nif favar.FAVAR==1 && favar.npltX>0\n    FAVAR=1;\n    npltX=favar.npltX;\n    favar_struct_irf_record=cell(favar.npltX,n);\n    Lgibbs=reshape(favar.L_gibbs,size(favar.L,1),size(favar.L,2),It-Bu);\n    %relevant loadings of restricted information variables\n    Lgibbs=Lgibbs(favar.plotX_index,:,:);\nelse\n    FAVAR=0;\n    npltX=0;\nend\n\n% step 1: repeat simulations a number of times equal to the number of simulations retained from Gibbs sampling\nfor ii=1:It-Bu\n    \n    % step 2: recover sigma\n    sigma=squeeze(sigma_gibbs(:,:,ii));\n    % step 3: Obtain the Choleski factor of sigma\n    D=chol(bear.nspd(sigma),'lower');\n    \n    \n    % step 4: obtain orthogonalised IRFs\n    % loop over periods\n    for jj=1:IRFperiods\n        \n        % loop over vertical and horizontal dimensions to recover the responses of all the variables to all the shocks\n        for kk=1:n\n            for ll=1:n\n                % recover the IRF matrix psi, representing the response of variable kk to shock ll at time horizon jj, for Gibbs iteration ii\n                psi(kk,ll)=irf_record{kk,ll}(ii,jj);\n            end\n        end\n        \n        % compute the orthonalised irf matrix psitilde, as defined in (2.3.10)\n        psitilde=psi*D;\n        \n        % record the results in the cell; here again, loop over vertical and horizontal dimensions\n        for kk=1:n\n            for ll=1:n\n                struct_irf_record{kk,ll}(ii,jj)=psitilde(kk,ll);\n            end\n        end\n        \n        % compute IRFs for FAVAR plotX variables\n        if FAVAR==1 && npltX>0\n            for oo=1:npltX\n                L=squeeze(Lgibbs(oo,:,ii));\n                for ll=1:n\n                    favar_struct_irf_record{oo,ll}(ii,jj)=L*psitilde(:,ll);\n                end\n            end\n        end\n        \n        %go for next period\n    end\n    \n    % step 5: record values for D and gamma\n    D_record(:,ii)=D(:);\n    % gamma is just identity\n    gamma_record(:,ii)=gamma;\n    \n    % go for next iteration\nend\n\n% save\nif FAVAR==1 && npltX>0\n    favar.IRF.favar_irf_record=favar_struct_irf_record;\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/irfchol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5869522811113937}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%DENSE LUCAS KANADE PYRAMIDAL + ITERATIVE REFINMENT \n%J.MARZAT - ENSEM / INRIA Rocquencourt (France) julien.marzat@gmail.com\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Data acquisition\nim1=single((imread('yos_img_10.pgm')));\nim2=single((imread('yos_img_11.pgm')));\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%parameters : levels number, window size, iterations number, regularization\nnumLevels=3;\nwindow=9;\niterations=1;\nalpha = 0.001;\n\nhw = floor(window/2);\nt0=clock;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%pyramids creation\npyramid1 = im1;\npyramid2 = im2;\n%init\nfor i=2:numLevels\n    im1 = impyramid(im1, 'reduce');\n    im2 = impyramid(im2, 'reduce');\n    pyramid1(1:size(im1,1), 1:size(im1,2), i) = im1;\n    pyramid2(1:size(im2,1), 1:size(im2,2), i) = im2;\nend;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Processing all levels\nfor p = 1:numLevels\n   \n    %current pyramid\n    im1 = pyramid1(1:(size(pyramid1,1)/(2^(numLevels - p))), 1:(size(pyramid1,2)/(2^(numLevels - p))), (numLevels - p)+1);\n    im2 = pyramid2(1:(size(pyramid2,1)/(2^(numLevels - p))), 1:(size(pyramid2,2)/(2^(numLevels - p))), (numLevels - p)+1);\n       \n    %init\n    if p==1\n    u=zeros(size(im1));\n    v=zeros(size(im1));\n    else  \n    %resizing\n    u = 2 * imresize(u,size(u)*2,'bilinear');   \n    v = 2 * imresize(v,size(v)*2,'bilinear');\n    end\n    \n    %refinment loop\n    for r = 1:iterations\n   \n    u=round(u);\n    v=round(v);\n    \n    %every pixel loop\n        for i = 1+hw:size(im1,1)-hw\n            for j = 1+hw:size(im2,2)-hw\n            patch1 = im1(i-hw:i+hw, j-hw:j+hw);\n      \n            %moved patch \n            lr = i-hw+v(i,j);\n            hr = i+hw+v(i,j);\n            lc = j-hw+u(i,j);\n            hc = j+hw+u(i,j);\n           \n                  if (lr < 1)||(hr > size(im1,1))||(lc < 1)||(hc > size(im1,2))  \n                  %Regularized least square processing\n                  else\n                  patch2 = im2(lr:hr, lc:hc);\n      \n                  fx = conv2(patch1, 0.25* [-1 1; -1 1]) + conv2(patch2, 0.25*[-1 1; -1 1]);\n                  fy = conv2(patch1, 0.25* [-1 -1; 1 1]) + conv2(patch2, 0.25*[-1 -1; 1 1]);\n                  ft = conv2(patch1, 0.25*ones(2)) + conv2(patch2, -0.25*ones(2));\n\n      \n                  Fx = fx(2:window-1,2:window-1)';\n                  Fy = fy(2:window-1,2:window-1)';\n                  Ft = ft(2:window-1,2:window-1)';\n\n                  A = [Fx(:) Fy(:)];      \n                  G=A'*A;\n              \n                  G(1,1)=G(1,1)+alpha; G(2,2)=G(2,2)+alpha;\n                  U=1/(G(1,1)*G(2,2)-G(1,2)*G(2,1))*[G(2,2) -G(1,2);-G(2,1) G(1,1)]*A'*-Ft(:);\n                  u(i,j)=u(i,j)+U(1); v(i,j)=v(i,j)+U(2);\n                  end\n            end\n        end\n    end\n    etime(clock,t0)\nend\n\n%resizing\nu=u(window:size(u,1)-window+1,window:size(u,2)-window+1);\nv=v(window:size(v,1)-window+1,window:size(v,2)-window+1);\n\n%colormap display\nfigure(1)\nRGB1=showmap3(u,v,5);\nimshow(RGB1);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22950-lucas-kanade-pyramidal-refined-optical-flow-implementation/LKPR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.586950301976798}}
{"text": "% 3D Example for Multilevel Mass-Preserving Image Registration using VAMPIRE\n% \n% (c) Fabian Gigengack and Lars Ruthotto 2011/02/04, see FAIR.2 and FAIRcopyright.m.\n% http://www.uni-muenster.de/EIMI/\n% http://www.mic.uni-luebeck.de/\n%\n%   - data                 Cardiac gated PET images of a mouse heart.\n%                          (level 4:6, full resolution: 40x40x40)\n%                          Images show the heart in systole and diastole.\n%   - viewer               viewImage3D\n%   - interpolation        splineInterMex (regularizer='moments', theta=0.01)\n%   - distance             SSD\n%   - pre-registration     none\n%   - regularizer          mfHyperElastic\n%   - optimizer            Gauss-Newton with ArmijoBacktrack linesearch\n%\n% Acknowledgement:\n% ----------------\n% Thanks to the European Institute for Molecular Imaging (EIMI) and SFB 656, \n% University of Muenster, Germany for supplying this interesting data.\n\nsetup3DmouseData\n\n% prepare the plot\nFAIRplots('clear')\nDshow = @(T,R,omega,m) viewIP(abs(T-R),omega,m,'colormap',gray(256));\nFAIRplots('set','Dshow',Dshow);\n\n% set the regularizer\nalpha       = 1;\nalphaLength = 1;\nalphaArea   = 0.1;\nalphaVolume = 2;\nregularizer('reset', 'regularizer', 'mfHyperElastic', 'alpha', alpha, ...\n    'alphaLength', alphaLength, ...\n    'alphaArea',   alphaArea, ...\n    'alphaVolume', alphaVolume);\n\n% finally: run the MultiLevel Non-Parametric Image Registration\nNPIRpara            = optPara('NPIR-GN');\nNPIRpara.lineSearch = @ArmijoDiffeomorphic;\nNPIRpara.solver     = @VAMPIREsolveGN_PCG;\n\n[yc,wc,his] = MLIR(ML, 'NPIRobj', @VAMPIRENPIRobjFctn, ...\n    'parametric', false, 'NPIRpara', NPIRpara);\n\n%% Plot results\n% Compute resulting image: dataT(yc) * det(D(yc))\nTopt = reshape(linearInter(dataT,omega,center(yc,m)) .* geometry(yc,m,'Jac','omega',omega), m);\n\nfigure(1); clf;\nsubplot(2,2,1)\nviewSlices(dataT,omega,m);\ntitle('dataT, template');\n\nsubplot(2,2,2)\nviewSlices(dataR,omega,m);\ntitle('dataR, reference');\n\nsubplot(2,2,3)\nviewSlices(Topt,omega,m);\ntitle('dataT(y).*detDy');\n\nsubplot(2,2,4)\nviewSlices((Topt-dataR),omega,m);\ntitle('final residual');\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/add-ons/VAMPIRE/examples/EV_3Dmouse_VAMPIRE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5869268962884946}}
{"text": "function C = multiTimes( A, B, type )\n% Matrix multiply each submatrix of two 3D arrays without looping.\n%\n% type controls the matrix multiplication to perform (for each i):\n%  1    - C(:,:,i) = A(:,:,i)*B(:,:)\n%  1.1  - C(i,:,:) = A(:,:,i)*B(:,:)\n%  1.2  - C(:,:,i) = A(:,:)*B(:,:,i)\n%  2    - C(:,:,i) = A(:,:,i)*B(:,:,i)\n%  2.1  - C(:,:,i) = A(:,:,i)'*B(:,:,i)\n%  2.2  - C(:,:,i) = A(:,:,i)*B(:,:,i)'\n%  3    - C(:,i) = A(:,:,i)*B(:,i)\n%  3.1  - C(:,i) = A(:,:,i)'*B(:,i)\n%  3.2  - C(:,i) = A(:,i)'*B(:,:,i)\n%  4.1  - C(i) = trace(A(:,:,i)'*B(:,:,i))\n% Corresponding dimensions of A and B must match appropriately.\n%\n% USAGE\n%  C = multiTimes( A, B, type )\n%\n% INPUTS\n%  A         - [ma x na x oa] matrix\n%  B         - [mb x nb x ob] matrix\n%  type      - multiplication type (see above)\n%\n% OUTPUTS\n%  C         - result of the multiplication\n%\n% EXAMPLE\n%  n=10000; A=randn(2,2,n); B=randn(2);\n%  tic, C1=multiTimes(A,B,1); toc\n%  tic, C2=zeros(size(A)); for i=1:n, C2(:,:,i)=A(:,:,i)*B; end; toc\n%\n% See also BSXFUN, MTIMES\n%\n% Piotr's Computer Vision Matlab Toolbox      Version 2.52\n% Copyright 2014 Piotr Dollar.  [pdollar-at-gmail.com]\n% Licensed under the Simplified BSD License [see external/bsd.txt]\n\nma = size(A,1); na = size(A,2); oa = size(A,3);\nmb = size(B,1); nb = size(B,2); ob = size(B,3);\n\n% just to simplify the reading\n%if( ma==mb ); m = ma; end\n%if( na==nb ); n = na; end\nif( oa==ob ); o = oa; end\n\nswitch type\n  case 1    % C(:,:,i) = A(:,:,i)*B(:,:)\n    C = permute(reshape(reshape(permute(A,[1 3 2]),ma*oa,na)*B,...\n      ma,oa,nb),[1 3 2]);\n  case 1.1  % C(i,:,:) = A(:,:,i)*B(:,:)\n    C = reshape(reshape(permute(A,[3 1 2]),ma*oa,na)*B,oa,ma,nb);\n  case 1.2  % C(:,:,i) = A(:,:)*B(:,:,i)\n    C = reshape(A*reshape(B,mb,nb*ob),ma,nb,ob);\n  case 2    % C(:,:,i) = A(:,:,i)*B(:,:,i)\n    C = reshape(sum(bsxfun(@times,reshape(A,...\n      [ma na 1 o]),reshape(B,[1 mb nb o])),2),[ma nb o]);\n  case 2.1  % C(:,:,i) = A(:,:,i)'*B(:,:,i)\n    C = reshape(sum(bsxfun(@times,reshape(permute(A,[2,1,3]),...\n      [na ma 1 o]),reshape(B,[1 mb nb o])),2),[na nb o]);\n  case 2.2  % C(:,:,i) = A(:,:,i)*B(:,:,i)'\n    C = reshape(sum(bsxfun(@times,reshape(A,...\n      [ma na 1 o]),reshape(permute(B,[2,1,3]),[1 nb mb o])),2),[ma mb o]);\n  case 3    % C(:,i) = A(:,:,i)*B(:,i)\n    C = reshape(sum(bsxfun(@times, A, reshape(B,[1 mb nb ])),2),ma,nb);\n  case 3.1  % C(:,i) = A(:,:,i)'*B(:,i)\n    C = reshape(sum(bsxfun(@times, permute(A,[2,1,3]), ...\n      reshape(B,[1 mb nb ])),2),na,nb);\n  case 3.2  % C(:,i) = A(:,i)'*B(:,:,i)\n    C = reshape(sum(bsxfun(@times, reshape(A,ma,1,na), B),1), nb,na);\n  case 4.1  % C(i) = tr(A(:,:,i)'*B(:,:,i))\n    C = reshape(sum(sum(A.*B,1),2),1,o);\n  otherwise\n    error('unknown type: %f',type);\nend\n", "meta": {"author": "pdollar", "repo": "toolbox", "sha": "e87332637bbe8e8b92dd487c87567d9628404523", "save_path": "github-repos/MATLAB/pdollar-toolbox", "path": "github-repos/MATLAB/pdollar-toolbox/toolbox-e87332637bbe8e8b92dd487c87567d9628404523/matlab/multiTimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5869268920021952}}
{"text": "function hd = DirectionCalulate(X1,Y1,X2,Y2)\n    hd=rem(atan2d(Y2-Y1,X2-X1)+360, 360);\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/DirectionCalulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.586898591127137}}
{"text": "function k = findcols(A, b)\n%FINDCOLS Find indices of a given column within a matrix.\n%\n%   FINDCOLS(A, B) returns a row vector with the indices of the columns\n%   in the matrix A that are identical to the column vector B.  If no\n%   columns in A are identical to B, an empty vector is returned.\n%\n%   The methods uses a for-loop, but it uses less memory and is in many\n%   cases a lot faster than the vectorized methods\n%\n%      find( all( A == repmat(b, 1, size(A, 2)), 1 ) )\n%      find( all( A == b(:,ones(size(A, 2), 1)), 1 ) )\n%\n%   See also FIND, FINDROWS.\n\n%   Author:      Peter J. Acklam\n%   Time-stamp:  2002-03-03 13:51:19 +0100\n%   E-mail:      pjacklam@online.no\n%   URL:         http://home.online.no/~pjacklam\n\n   k = find( A(1,:) == b(1) );\n   for j = 2:size(A, 1)\n      k = k( A(j,k) == b(j) );\n      if isempty(k)\n         return\n      end\n   end\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/lib/util/matutil/findcols.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.5867953308520265}}
{"text": "function h = plot_tensor_field(H, M, options)\n\n% plot_tensor_field - display a tensor field\n%\n%   h = plot_tensor_field(H, M, options);\n%\n%   options.sub controls sub-sampling\n%   options.color controls color\n%\n%   Copyright (c) 2006 Gabriel Peyre\n\nif nargin<3\n    options.null = 0;\nend\nif not( isstruct(options) )\n    sub = options;\n    clear options;\n    options.sub = sub;\nend\n\n% sub = getoptions(options, 'sub', 1);\nsub = getoptions(options, 'sub', round(size(H,1)/30) );\ncolor = getoptions(options, 'color', 'r');\n\nif nargin<2\n    M = [];\nend\n\nif not(isempty(M)) && size(M,3)==1\n    M = repmat(M, [1 1 3]); % ensure B&W image\nend\n\nif size(H,3)==3 && size(H,4)==1\n    H = cat(3, H(:,:,1), H(:,:,3), H(:,:,3), H(:,:,2) );\n    H = reshape(H, size(H,1), size(H,2), 2, 2);\n    if 0\n    % flip the main eigen-axes\n    [e1,e2,l1,l2] = perform_tensor_decomp(H);\n    H = perform_tensor_recomp(e2,e1,l1,l2);\n    end\n    h = plot_tensor_field(H, M, sub);\n    return;\nend\n\n% swap X and Y axis\n%%% TODO\na = H(:,:,2,2);\nH(:,:,2,2) = H(:,:,1,1);\nH(:,:,1,1) = a;\n\nhold on;\nif ~isempty(M)\n    imagesc(rescale(M)); drawnow;\nend\nh = fn_tensordisplay(H(:,:,1,1),H(:,:,1,2), H(:,:,2,2), 'sub', sub, 'color', color);\naxis image; axis off;\ncolormap jet(256);\n% hold off;\n\n\nfunction h = fn_tensordisplay(varargin)\n\n% function h = fn_tensordisplay([X,Y,]Txx,Txy,Tyy[,'sigma',sigma][,'sub',sub][,color][,patch options...]])\n% function h = fn_tensordisplay([X,Y,]e[,'sigma',sigma][,'sub',sub][,color][,patch options...]])\n\n% X,Y,Txx,Txy,Tyy\nif isstruct(varargin{1}) || isstruct(varargin{3})\n    if isstruct(varargin{1}), nextarg=1; else nextarg=3; end\n    e = varargin{nextarg};\n    Txx = e.ytyt;\n    Txy = -e.ytyx;\n    Tyy = e.yxyx;\n    if nextarg==1\n        [nj ni] = size(Txx);\n        [X Y] = meshgrid(1:ni,1:nj);\n    else\n        [X Y] = deal(varargin{1:2});\n    end\n    nextarg = nextarg+1;\nelse\n    [nj ni] = size(varargin{3});\n    if nargin<5 || ischar(varargin{4}) || ischar(varargin{5}) || any(size(varargin{5})~=[nj ni])\n        [X Y] = meshgrid(1:ni,1:nj);\n        nextarg = 1;\n    else\n        [X Y] = deal(varargin{1:2});\n        nextarg = 3;\n    end\n    [Txx Txy Tyy] = deal(varargin{nextarg:nextarg+2});\n    nextarg = nextarg+3;\nend\nif any(size(X)==1), [X Y] = meshgrid(X,Y); end\n[nj,ni] = size(X);\nif any(size(Y)~=[nj ni]) || ...\n        any(size(Txx)~=[nj ni]) || any(size(Txy)~=[nj ni]) || any(size(Tyy)~=[nj ni])\n    error('Matrices must be same size')\nend\n% sigma, sub, color\ncolor = 'r';\nwhile nextarg<=nargin\n    flag = varargin{nextarg};\n    nextarg=nextarg+1;\n    if ~ischar(flag), color = flag; continue, end\n    switch lower(flag)\n        case 'sigma'\n            sigma = varargin{nextarg};\n            nextarg = nextarg+1;\n            switch length(sigma)\n                case 1\n                    sigmax = sigma;\n                    sigmay = sigma;\n                case 2\n                    sigmax = sigma(1);\n                    sigmay = sigma(2);\n                otherwise\n                    error('sigma definition should entail two values');\n            end\n            h = fspecial('gaussian',[ceil(2*sigmay) 1],sigmay)*fspecial('gaussian',[1 ceil(2*sigmax)],sigmax);\n            Txx = imfilter(Txx,h,'replicate');\n            Txy = imfilter(Txy,h,'replicate');\n            Tyy = imfilter(Tyy,h,'replicate');\n        case 'sub'\n            sub = varargin{nextarg};\n            nextarg = nextarg+1;\n            switch length(sub)\n                case 1\n                    [x y] = meshgrid(1:sub:ni,1:sub:nj);\n                    sub = y+nj*(x-1);\n                case 2\n                    [x y] = meshgrid(1:sub(1):ni,1:sub(2):nj);\n                    sub = y+nj*(x-1);\n            end\n            X = X(sub); Y = Y(sub);\n            Txx = Txx(sub); Txy = Txy(sub); Tyy = Tyy(sub);\n            [nj ni] = size(sub);\n        case 'color'            \n            color = varargin{nextarg};\n            nextarg = nextarg+1;\n        otherwise\n            break\n    end\nend\n% options\noptions = {varargin{nextarg:end}};\n\n\nnpoints = 50;\ntheta = (0:npoints-1)*(2*pi/npoints);\ncircle = [cos(theta) ; sin(theta)];\nTensor = cat(3,Txx,Txy,Txy,Tyy);        % jdisplay x idisplay x tensor\nTensor = reshape(Tensor,2*nj*ni,2);     % (display x 1tensor) x 2tensor\nEllipse = Tensor * circle;              % (display x uv) x npoints\nEllipse = reshape(Ellipse,nj*ni,2,npoints);         % display x uv x npoints\nXX = repmat(X(:),1,npoints);                        % display x npoints\nYY = repmat(Y(:),1,npoints);                        % display x npoints\nU  = reshape(Ellipse(:,1,:),nj*ni,npoints);         % display x npoints\nV  = reshape(Ellipse(:,2,:),nj*ni,npoints);         % display x npoints\numax = max(U')'; vmax = max(V')';\numax(umax==0)=1; vmax(vmax==0)=1;\nif ni==1, dx=1; else dx = X(1,2)-X(1,1); end\nif nj==1, dy=1; else dy = Y(2,1)-Y(1,1); end\nfact = min(dx./umax,dy./vmax)*.35;\nfact = repmat(fact,1,npoints);\nU = XX + fact.*U;\nV = YY + fact.*V;\n\n%-----------\nMM = mmax(Txx+Tyy);\nmm = mmin(Txx+Tyy);\n[S1, S2] = size(U);\nColormap = zeros(S2, S1, 3);\nMap = colormap(jet(256));\nfor k =1:npoints\n    Colormap(k,:,1) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 1);\n    Colormap(k,:,2) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 2);\n    Colormap(k,:,3) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 3);\nend\n%-----------\n%h = fill(U',V',color,'EdgeColor',color,options{:});\nh = fill(U',V',Colormap,'EdgeColor', 'interp');\n\naxis ij;\n\nif nargout==0, clear h, end\n\n\nfunction a=mmax(a)\na = max(a(:));\nfunction a=mmin(a)\na = min(a(:));\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_diffc/plot_tensor_field.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5867953187769144}}
{"text": "function plotFunc()\n  colors = ['r'; 'b';'m';'g'];\n  lineWidth=2;\n  markerSize=20;\n  sigmas = [2.5, 5, 10];\n\n  hold on;\n  legendStrs = {};\n  x=-20:0.2:20;\n  for ii=1:length(sigmas)\n    sigma = sigmas(ii);\n    y = exp(-0.5*(x/sigma).^2);\n    plot(x, y, colors(ii), 'MarkerSize', markerSize, 'linewidth', lineWidth);\n    legendStrs{end+1} = ['\\sigma=' num2str(sigma)];\n  end\n\n  % legend\n  fontsize = 12;\n  legendLocation = 'Best'; % 'NorthWest'; % \n  legend(legendStrs,'FontSize', fontsize, 'Location', legendLocation);\nend\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/print/plotDistFunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7549149923816046, "lm_q1q2_score": 0.586795310987815}}
{"text": "%% OPT13_RUN\n%\n%  Modified:\n%\n%    12 February 2008\n%\n   %---------------------------------------------------------------------\n   %  Use NEWTON method.\n   %---------------------------------------------------------------------\n   fprintf('---------------------------------------------------------\\n')\n   fprintf('Test case 13 as a standard minimization problem.\\n' );\n   fprintf('Use Newton''s method.\\n' );\n   fprintf('The function is badly scaled.\\n' );\n   fprintf('There is a local minimizer at X=(0.285,0.279), F(X)=5.92\\n' );\n   fprintf('There is a global minimizere at X=-21.02,36.76), F(X)=0.0\\n' );\n   fprintf('---------------------------------------------------------\\n')\n\n   fname = 'opt13_fgh';\n   options = [];\n   options.max_iterations     = 30;\n   options.method             = 'newton';\n   \n   fprintf('Newton:\\n')\n\n   x0 = [ 1; 1 ];\n   x = entrust(fname, x0, options);\n\n   fprintf('Newton''s method produced  (%10.7e,%10.7e)\\n\\n',x(1),x(2))\n   f = opt13_fgh ( x, 'f' );\n   fprintf('Value of F(X) = %f\\n', f );\n\n   %---------------------------------------------------------------------\n   %  Use GAUSS-NEWTON method on least squares problem.\n   %---------------------------------------------------------------------\n   fprintf('---------------------------------------------------------\\n')\n   fprintf('Running testcase_13 as least squares problem: \\n')\n   fprintf('---------------------------------------------------------\\n')\n   fname = 'opt13_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     = 10000;\n   options.max_fevals         = 10000;\n\n   x0 = [ 1; 1 ];\n   x = entrust(fname, x0, options);\n   fprintf('Gauss-Newton produced  (%10.7e, %10.7e)\\n\\n',x(1),x(2))\n   [ res, jac ] = opt13_rj ( x, 'f' );\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/opt13_run.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5867953102048881}}
{"text": "function stroud_test335 ( )\n\n%*****************************************************************************80\n%\n%% TEST335 tests SPHERE_SHELL_03_ND.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    06 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  global FUNC_ND_INDEX;\n\n  n_max = 3;\n\n  num = function_nd_num ( );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST335\\n' );\n  fprintf ( 1, '  For integrals inside a spherical shell in ND:\\n' );\n  fprintf ( 1, '  SPHERE_SHELL_03_ND approximates the integral.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  We compare these results with those computed by\\n' );\n  fprintf ( 1, '  from the difference of two ball integrals:\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  BALL_F1_ND approximates the integral;\\n' );\n  fprintf ( 1, '  BALL_F3_ND approximates the integral.\\n' );\n  fprintf ( 1, '\\n' );\n\n  for j = 1 : 2\n\n    if ( j == 1 )\n      r1 = 0.0;\n      r2 = 1.0;\n      xc(1:n_max) = 0.0;\n    else\n      r1 = 2.0;\n      r2 = 3.0;\n      xc(1:n_max) = [ 1.0, -1.0, 2.0 ];\n    end\n\n    for n = 2 : n_max\n\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, '  Spatial dimension N = %d\\n', n );\n      fprintf ( 1, '  Sphere center:\\n' );\n      for i = 1 : n\n        fprintf ( 1, '  %12f', xc(i) );\n      end\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, '  Inner sphere radius = %f\\n', r1 );\n      fprintf ( 1, '  Outer sphere radius = %f\\n', r2 );\n      fprintf ( 1, '  Spherical shell volume = %f\\n', ...\n        sphere_shell_volume_nd ( n, r1, r2 ) );\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, '    Rule:      #3       F1(R2)-F1(R1)  F3(R2)-F3(R1)\\n' );\n      fprintf ( 1, '    F(X)\\n' );\n      fprintf ( 1, '\\n' );\n\n      for i = 1 : num\n\n        FUNC_ND_INDEX = i;\n\n        result1 = sphere_shell_03_nd ( 'function_nd', n, xc, r1, r2 );\n\n        result3 = ball_f1_nd ( 'function_nd', n, xc, r1 );\n        result4 = ball_f1_nd ( 'function_nd', n, xc, r2 );\n      \n        result5 = ball_f3_nd ( 'function_nd', n, xc, r1 );\n        result6 = ball_f3_nd ( 'function_nd', n, xc, r2 );\n\n        fname = function_nd_name ( i );\n\n        fprintf ( 1, '  %s  %12f  %12f  %12f\\n', ...\n          fname, result1, result4-result3, result6-result5 );\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/stroud/stroud_test335.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.5867953059188749}}
{"text": "% add the path of RBM code\naddpath('..');\naddpath('~/work/Algorithms/liblinear-1.7/matlab');\n\n% load MNIST\nload 'mnist_14x14.mat';\n\n% shuffle the training data\nperm_idx = randperm (size(X,1));\n\nn_all = size(X, 1);\nn_train = ceil(n_all * 3 / 4);\nn_valid = floor(n_all /4);\n\nX_valid = X(perm_idx(n_train+1:end), :);\nX_valid_labels = X_labels(perm_idx(n_train+1:end));\nX = X(perm_idx(1:n_train), :);\nX_labels = X_labels(perm_idx(1:n_train));\n\nlayers = [size(X,2), 200, 100, 50, 2];\nn_layers = length(layers);\nblayers = [1, 1, 1, 1, 0];\n\nuse_tanh = 0;\ndo_pretrain = 1;\n\nif do_pretrain\n    Ds = cell(n_layers - 1, 1);\n    H = X;\n    H_valid = X_valid;\n\n    for l = 1:n_layers-1\n        % construct DAE and use default configurations\n        D = default_dae (layers(l), layers(l+1));\n\n        D.data.binary = blayers(l);\n        D.hidden.binary = blayers(l+1);\n\n        if use_tanh \n            if l > 1\n                D.visible.use_tanh = 1;\n            end\n            D.hidden.use_tanh = 1;\n        else\n            if D.data.binary\n                mH = mean(H, 1)';\n                D.vbias = min(max(log(mH./(1 - mH)), -4), 4);\n            else\n                D.vbias = mean(H, 1)';\n            end\n        end\n\n        D.learning.lrate = 1e-1;\n        D.learning.lrate0 = 5000;\n        D.learning.weight_decay = 0.0001;\n        D.learning.minibatch_sz = 128;\n\n        D.valid_min_epochs = 10;\n\n        D.noise.drop = 0.2;\n        D.noise.level = 0;\n\n        %D.adagrad.use = 1;\n        %D.adagrad.epsilon = 1e-8;\n        D.adagrad.use = 0;\n        D.adadelta.use = 1;\n        D.adadelta.epsilon = 1e-8;\n        D.adadelta.momentum = 0.99;\n\n        D.iteration.n_epochs = 500;\n\n        % save the intermediate data after every epoch\n        D.hook.per_epoch = {@save_intermediate, {sprintf('dae_mnist_%d.mat', l)}};\n\n        % print learining process\n        D.verbose = 0;\n        % display the progress\n        D.debug.do_display = 0;\n\n        % train RBM\n        fprintf(1, 'Training DAE (%d)\\n', l);\n        tic;\n        D = dae (D, H, H_valid, 0.1);\n        fprintf(1, 'Training is done after %f seconds\\n', toc);\n\n        H = dae_get_hidden(H, D);\n        H_valid = dae_get_hidden(H_valid, D);\n\n        Ds{l} = D;\n    end\nend\n\nS = default_sdae (layers);\n\nS.data.binary = blayers(1);\nS.bottleneck.binary = blayers(end);\nS.hidden.use_tanh = use_tanh;\n\nS.hook.per_epoch = {@save_intermediate, {'sdae_mnist.mat'}};\n\nS.learning.lrate = 1e-1;\nS.learning.lrate0 = 5000;\n%S.learning.momentum = 0.9;\nS.learning.weight_decay = 0.0001;\nS.learning.minibatch_sz = 128;\n\n%S.noise.drop = 0.2;\n%S.noise.level = 0;\nS.adadelta.use = 1;\nS.adadelta.epsilon = 1e-8;\nS.adadelta.momentum = 0.99;\n\n%S.adagrad.use = 1;\n%S.adagrad.epsilon = 1e-8;\nS.valid_min_epochs = 10;\n\nS.iteration.n_epochs = 100;\n\nif do_pretrain\n    for l = 1:n_layers-1\n        S.biases{l+1} = Ds{l}.hbias;\n        S.W{l} = Ds{l}.W;\n    end\nelse\n    if S.data.binary\n        mH = mean(X, 1)';\n        S.biases{1} = min(max(log(mH./(1 - mH)), -4), 4);\n    else\n        S.biases{1} = mean(X, 1)';\n    end\nend\n\nfprintf(1, 'Training sDAE\\n');\ntic;\nS = sdae (S, X, X_valid, 0.1);\nfprintf(1, 'Training is done after %f seconds\\n', toc);\n\nH = sdae_get_hidden (X, S);\nsave 'sdae_mnist_vis.mat' H X_labels;\n\nvis_mnist;\n\n\n\n\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/example/example_mnist_sdae.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5867839069837241}}
{"text": "% TEST_THICL_LSHAPED_MP_G_NMNN: data function for Neumann boundary condition.\n\nfunction g = test_thick_Lshaped_mp_g_nmnn(x, y, z, ind)\n  switch (ind)\n   case {1, 4}\n     g = cos(z) .* exp(x) .* (sin(x.*y) + y .* cos(x.*y));\n   case {2, 3}\n     g = -x .* exp(x) .* cos(x.*y) .* cos(z);\n   case {5}\n     g = -cos(z) .* exp(x) .* (sin(x.*y) + y .* cos(x.*y));\n   case {6}\n     g = x .* exp(x) .* cos(x.*y) .* cos(z);\n   case {7}\n     g = exp(x) .* sin(x.*y) .* sin(z);\n   case {8}\n     g = - exp(x) .* sin(x.*y) .* sin(z);\n   otherwise\n    error('g_nmnn: error in the reference number for the boundary')\n  end\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/base/data_files/test_thick_Lshaped_mp_g_nmnn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5867838978099225}}
{"text": "%PRTESTC Test routine for the PRTOOLS classifier\n%\n% This script tests a given, untrained classifier w, defined in the\n% workspace, e.g. w = my_classifier. The goal is to find out whether \n% w fulfills all the requirements of a PRTools classifier. \n% \n\nif exist('w') ~= 1 | ~ismapping(w) | ~isuntrained(w)\n\terror('No untrained classifier w found')\nend\n\nm = 50;\na = gendath([m,m]);\na = setprior(a,0);\n[b,c] = gendat(a,0.5);\nname = getname(w);\nif (isempty(name))\n\terror('No name found for the untrained classifier.')\nend\n\ndisp('')\ndisp(['     Testing Classifier ' name])\ndisp(['     ------------------ '])\nv = b*w;\nnewfig(1,3);\nscatterd(b);\nplotc(v);\nif (isempty(getname(v)))\n\tdisp('No name found for the classifier.')\nend\ndisp('Classification error for the Higleyman data: ')\ndisp(c*v*testc)\n\ndisp('Direct output: ')\ndisp(c(1:5,:)*v)\n\ndisp('Classifier output: ')\ndisp(c(1:5,:)*v*classc)\n\ndisp('Soft labels, classification error: ')\na = gendath([m,m],'soft');\na = setprior(a,0);\n[b,c] = gendat(a,0.5);\ndisp(c*(b*w)*testc);\n\nnewfig(2,3);\nlearnsizes = [3,5,7,10,15];\ne = cleval(w,b,learnsizes,2,c);\nplote(e)\na = gendatm(repmat(20,1,8));\na = setprior(a,0);\n[b,c] = gendat(a,0.5);\nnewfig(3,3)\nscatterd(b)\nu = b*w;\nplotc(u)\ndisp('Classification error for a multi-class problem: ')\ndisp(c*u*testc)\n\nif (isaffine(v))\n\tload nist16_38\n\ta = prdataset(a);\n\tv = a*w;\n\tnewfig(6,3);\n\tshow(v);\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/prtestc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.586783895881726}}
{"text": "function [forecast_record]=maforecast(data_endo_a,data_exo_a,data_exo_p,It,Bu,beta_gibbs,sigma_gibbs,delta_gibbs,Fperiods,n,m,p,k1,k3)\n\n\n\n\n% function [forecast_record]=maforecast(data_endo_a,data_exo_a,data_exo_p,It,Bu,beta_gibbs,sigma_gibbs,delta_gibbs,Fperiods,n,m,p,k1,k3)\n% computes draws from the posterior predictive distribution, that is, from the posterior distribution of forecasts\n% inputs:  - matrix 'data_endo_a': the matrix storing the pre-forecast endogenous data\n%          - matrix 'data_exo_a': the matrix storing the pre-forecast exogenous data\n%          - matrix 'data_exo_p': the matrix storing the predicted exogenous data\n%          - integer 'It': the total number of iterations run by the Gibbs sampler\n%          - integer 'Bu': the number of initial iterations discared as burn-in sample\n%          - matrix 'beta_gibbs': the matrix recording the post-burn draws of beta\n%          - matrix 'sigma_gibbs': the matrix recording the post-burn draws of sigma\n%          - matrix 'delta_gibbs': the matrix recording the post-burn draws of delta\n%          - integer 'Fperiods': the number of periods for which forecasts have to be produced\n%          - integer 'n': the number of endogenous variables in the model\n%          - integer 'm': the number of exogenous variables in the model\n%          - integer 'p': the number of lags in the model\n%          - integer 'k1': the number of coefficients related to the endogenous variables for each equation in the model\n%          - integer 'k3': the number of coefficients related to the exogenous variables for each equation, in the reformulated model (3.5.5)\n% outputs: - cell 'forecast_record': the cell array containing records of simulated  forecasts\n\n\n% this function implements algorithm 2.1.1, adapted for the mean-adjusted BVAR model\n\n\n% create first the cell storing the results\nforecast_record=cell(n,1);\n\n\n% generate the matrix of predicted exogenous variables \n% augment the matrices of exogenous with a column of ones to account for the exogenous\ndata_exo_a=[ones(size(data_endo_a,1),1) data_exo_a];\ndata_exo_p=[ones(Fperiods,1) data_exo_p];\n\n\n% then start simulations\n% repeat the process a number of times equal to the number of simulations retained from Gibbs sampling\nfor ii=1:It-Bu\n\n\n% compute the matrix temp1 \ntemp1=data_endo_a(end-p+1:end,:);\n\n\n% compute the matrix temp2\ntemp2=[data_exo_a(end-p+1:end,:)];\n\n\n% step 2: draw beta and sigma\n% draw beta from its posterior distribution\nbeta=beta_gibbs(:,ii);\n% reshape\nB=reshape(beta,k1,n);\n\n\n% draw delta from its posterior distribution\ndelta=delta_gibbs(:,ii);\n% reshape\nDelta=reshape(delta,k3,n);\n\n% draw sigma from its posterior distribution\nsigma=sigma_gibbs(:,ii);\n% reshape sigma to recover its original square form\nsigma=reshape(sigma,n,n);\n\n\n   % step 4: generate forecasts recursively\n   % repeat the process for periods T+1 to T+h\n   for jj=1:Fperiods\n\n   % concatenate the predicted exogenous to the top of temp2 (the actual exogenous)\n   temp2=[temp2;data_exo_p(jj,:)];\n\n   % use the function lagx on temp1 to obtain the matrix Y; retain only the last row\n   X=bear.lagx(temp1,p-1);\n   X=X(end,:);\n\n   % use the function lagx on temp2 to obtain the matrix Z; retain only the last row\n   Z=bear.lagx(temp2,p);\n   Z(:,m+1:end)=-Z(:,m+1:end);\n   Z=Z(end,:);\n\n   % draw the residuals from N(0,sigma)\n   res=bear.trns(chol(bear.nspd(sigma),'Lower')*randn(n,1));\n   \n   % obtain predicted value for T+jj by using (3.5.9)   \n   yp=X*B+Z*Delta+res;\n\n   % concatenate the transpose of yp to the top of temp1\n   temp1=[temp1;yp];\n\n   % repeat until values are obtained for T+h\n   end\n\n% step 5: record the results from current iteration in the cell forecast_record\n   % loop over variables\n   for kk=1:n\n   % consider column kk of matrix temp1 and select the last h rows: these are the predicted values for the period T+1 to T+h, for variable kk\n   temp3=temp1(end-Fperiods+1:end,kk);\n   % record these values in the corresponding matrix of forecast_record\n   forecast_record{kk,1}(ii,:)=temp3';\n   end\n\n% then go for next iteration\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/unreachableCode_ToRemove/maforecast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.586783895881726}}
{"text": "function lspec = lyapspec(ts, dim, delay, NNR, eps, Nref)\n\nts = ts(:);\nN = length(ts) - dim*delay;\nref = 1:delay:min(N,(1+(Nref-1)*delay));\n\n[nn, dists, points] = emb_nn_search(ts(1:(end-delay)), [dim delay], ref, NNR+1, -1);\n\nQ = diag(ones(dim,1));\t\nlspec = [];zeros(dim, 1);\n\nfor i=1:length(ref)\n\tX = points(nn(i,:), :);\n\tX0 = mean(X);\t\t% center of gravity\t\n\tY = X - repmat(X0, NNR+1, 1);\n\t[U,W,V] = svd(Y);\n\tw = diag(W) / sum(diag(W));\n\tk = max(find(w >= eps));\n\tV = V(:,1:k);\n\tZ = Y * V;\n\t\n\timages = ts(dim*delay+nn(i,:));\n\t%all(points(nn(i,:)+delay,1) == images);\n\t\n\t\n\ta = [Z ones(NNR+1,1)] \\ images;\n\t\n\tb = a(end);\n\ta = a(1:end-1);\n\tc = V * a;\n\n\t%mean(abs(images-(X * c + ( b - X0 * c))) ./ abs(images))\n\t\n\tJAC = sparse([ones(1,dim) 2:dim], [1:dim 1:dim-1], [c' ones(1, dim-1)]);\n\t%full(JAC);\n\t\n\tA =  JAC * Q;\n\t[Q,R,E] = qr(A);\n\n\tlspec = [lspec; diag(R)'];\nend\n\nlspec = mean(log(abs(lspec(min(length(ref)/10,500):end,:))));\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/mex-dev/Lyapunov/lyapspec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5867838909734593}}
{"text": "function distance = word_distance(word1, word2, model)\n% Shows the L2 distance between word1 and word2 in the word_embedding_weights.\n% Inputs:\n%   word1: The first word as a string.\n%   word2: The second word as a string.\n%   model: Model returned by the training script.\n% Example usage:\n%   word_distance('school', 'university', model);\n\nword_embedding_weights = model.word_embedding_weights;\nvocab = model.vocab;\nid1 = strmatch(word1, vocab, 'exact');\nid2 = strmatch(word2, vocab, 'exact');\nif ~any(id1)\n  fprintf(1, 'Word ''%s\\'' not in vocabulary.\\n', word1);\n  return;\nend\nif ~any(id2)\n  fprintf(1, 'Word ''%s\\'' not in vocabulary.\\n', word2);\n  return;\nend\nword_rep1 = word_embedding_weights(id1, :);\nword_rep2 = word_embedding_weights(id2, :);\ndiff = word_rep1 - word_rep2;\ndistance = sqrt(sum(diff .* diff));\n", "meta": {"author": "khanhnamle1994", "repo": "neural-nets", "sha": "7558937c68e3a51ad86e193f464008d44f8ddde5", "save_path": "github-repos/MATLAB/khanhnamle1994-neural-nets", "path": "github-repos/MATLAB/khanhnamle1994-neural-nets/neural-nets-7558937c68e3a51ad86e193f464008d44f8ddde5/Assignment2/word_distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5867838867079245}}
{"text": "% SPINV_LDLCHOL - Evaluate the sparse inverse matrix given the LDL\n%                 decomposition.\n%\n% For a sparse symmetric positive definite matrix C,\n%\n%   Z = SPINV(LD)\n%\n% where LD = LDLCHOL(C) and [Z]_ij = [inv(C)]_ij for such ij that [C]_ij\n% is non-zero.\n%\n% See Vanhatalo and Vehtari (2008) for details. \n\n% Copyright (c) 2008      Jarno Vanhatalo\n\n% This software is distributed under the GNU General Public\n% License (version 2 or later); please refer to the file\n% License.txt, included with the software, for details.\n\nfunction Z = spinv_ldlchol(LD)\n\nZ = spinv(LD, 1);\nreturn\n\n    \n    n = size(LD,1);\n\n\n    % The mex-file was not available, so evaluate the sparse inverse here\n    \n    % TODO:\n    % For now, just evaluate the matrix A and then run..\n    %[L,D] = ldlsplit(LD);\n    %A = L*D*L';\n    \n    if nargin < 2\n      q = 1:n;\n    end\n\n    %[LD, p, q] = ldlchol(A);\n    \n    [I,J,ld] = find(LD);\n    temp = [I(:) J(:) ; J(:) I(:)];\n    temp = sortrows(unique(temp,'rows'),2);\n    Iz = temp(:,1); Jz = temp(:,2); \n    \n    % Find the column starting points\n    a1=zeros(n,1);\n    a2 = cumsum(histc(J,1:n));\n    a1(1) = 1; a1(2:end) = a2(1:end-1) + 1;\n    az1=zeros(n,1);\n    az2 = cumsum(histc(Jz,1:n));\n    az1(1) = 1; az1(2:end) = az2(1:end-1) + 1;\n    \n    for j=1:n\n        indaz{j} = az1(j):az2(j);\n        indIz{j} = Iz(indaz{j})';\n    end\n\n    % Evaluate the sparse inverse\n    z = zeros(size(Iz));\n    z(end) = 1./ld(end);\n    % Allocate memory\n    cindit=zeros(n,1);\n    for jj = n-1:-1:1\n        fil = ld(a1(jj)+1:a1(jj+1)-1);\n        fi = I(a1(jj)+1:a1(jj+1)-1);\n        lfi = length(fi);\n        Zt = zeros(lfi,lfi);\n        indz = cumsum(histc(indIz{jj},[0 ; fi]));\n        indz = az1(jj) + indz(1:end-1);\n        \n        i4=0;            \n        for i1 = 1:lfi\n            cind1=indaz{fi(i1)};\n            Icind1=indIz{fi(i1)};\n            indfi = lfi;\n            i2=length(Icind1);\n            go = true;\n            while go\n                if Icind1(i2)==jj  % Find the indeces for the jj'th rows in fi columns\n                    i4=i4+1;\n                    cindit(i4)=cind1(i2);\n                    go = false;\n                end\n                if indfi >= 1 && fi(indfi) == Icind1(i2) % Find the indeces for the fi'th rows in i2'nd columns\n                    Zt(indfi,i1) = z(cind1(i2));\n                    indfi = indfi-1;\n                end\n                i2 = i2-1;\n            end\n        end\n        % remove extras\n        cindi=cindit(1:i4);\n\n        zij = -fil'*Zt;\n        z(cindi) = zij;\n        z(indz) = zij;\n        zij = 1./ld(a1(jj)) - fil'*z(indz);\n        z(az1(jj)-1+find(indIz{jj}==jj,1)) = zij;\n    end\n    \n    Z = sparse(Iz,Jz,z);\n    r(q) = 1:n;\n    Z = Z(r,r);\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/matrix_computations/spinv_ldlchol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5866814740009639}}
{"text": "function [x,g,xn,gg] = kmeanhar(d,k,l,e,x0)\n%KMEANS Vector quantisation using K-harmonic means algorithm [X,G,XN,GG]=(D,K,L,E,X0)\n%\n%  Inputs:\n%\n%    D(N,P)  contains N data vectors of dimension P\n%    K       is number of centres required\n%    L       integer portion is max loop count, fractional portion\n%            gives stopping threshold as fractional reduction in performance criterion\n%    E       is exponent in the cost function. Significantly faster if this is an even integer. [default 4]\n%    X0(K,P) are the initial centres (optional)\n%            Alternatively, X0 can be a character determining the initialization method:\n%                'f'    Initialize with K randomly selected data points [default]\n%                'p'    Initialize with centroids and variances of random partitions\n%\n%  Outputs:\n%\n%    X(K,P)  is output row vectors\n%    G       is the final performance criterion value (normalized by N)\n%    XN      nearest centre for each input point\n%    GG(L+1) value of performance criterion before each iteration and at end\n%\n% The k-harmonic means algorithm selects K cluster centres to minimize \n%                           sum_n(K/sum_k((d_n-x_k)^-e))\n% where sum_n is over the N inputs points d_n and sum_k is over the K cluster centres x_k.\n%\n% It is often a good idea to scale the input data so that it has equal variance in each\n% dimension before calling KMEANHAR so that approximately equal weight is given\n% to each dimension in the distance calculation.\n\n%  [1] Bin Zhang, \"Generalized K-Harmonic Means - Boosting in Unsupervised Learning\",\n%      Hewlett-Packartd Labs, Technical Report HPL-2000-137, 2000 [Zhang2000]\n%      http://www.hpl.hp.com/techreports/2000/HPL-2000-137.pdf\n\n%  Bugs:\n%      (1) Could use nested blocking to allow very large data arrays\n%      (2) Could then allow incremental calling with partial data arrays (but messy)\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: kmeanhar.m,v 1.6 2008/06/02 07:20:52 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% sort out the input arguments\n\nif nargin<5\n    x0='f';\n    if nargin<4\n        e=[];\n        if nargin<3\n            l=[];\n        end\n    end\nend\nif isempty(e)\n    e=4;  % default value\nend\nif isempty(l)\n    l=50+1e-3; % default value\nend\nsd=5;       % number of times we must be below threshold\n\n\n% split into chunks if there are lots of data points\n\nmemsize=voicebox('memsize');\n[n,p] = size(d);\nnb=min(n,max(1,floor(memsize/(8*p*k))));    % block size for testing data points\nnl=ceil(n/nb);                  % number of blocks\n\n% initialize if X0 argument is not supplied\n\nif ischar(x0)\n    if k<n\n        if any(x0=='p')                  % Initialize using a random partition\n            ix=ceil(rand(1,n)*k);       % allocate to random clusters\n            ix(rnsubset(k,n))=1:k;      % but force at least one point per cluster\n            x=zeros(k,p);\n            for i=1:k\n                x(i,:)=mean(d(ix==i,:),1);\n            end\n        else                                % Forgy initialization: choose k random points [default]\n            x=d(rnsubset(k,n),:);         % sample k centres without replacement\n        end\n    else\n        x=d(mod((1:k)-1,n)+1,:);    % just include all points several times\n    end\nelse\n    x=x0;\nend\neh=e/2;\nth=l-floor(l);\nl=floor(l)+(nargout>1);   % extra loop needed to calculate final performance value\nif l<=0\n    l=100;      % max number of iterations ever\nend\nif th==0\n    th=-1;      % prevent any stopping if l has no fractional part\nend\ngg=zeros(l+1,1);\nim=repmat(1:k,1,nb); im=im(:);\n\n% index arrays for replication\n\nwk=ones(k,1);\nwp=ones(1,p);\n% wn=ones(1,n);\n%\n% % Main calculation loop\n%\n% We have the following relationships to [1] where i and k index\n% the data values and cluster centres respectively:\n%\n%   This program     [Zhang2000]                            Equation  \n%\n%     d(i,:)            x_i                                 input data\n%     x(k,:)            m_k                                 cluster centres\n%     py(k,i)           (d_ik)^2\n%     dm(i)'            d_i,min^2\n%     pr(k,i)           (d_i,min/d_ik)^2\n%     pe(k,i)           (d_i,min/d_ik)^p                    (7.6) \n%     qik(k,i)          q_ik                                (7.2)\n%     qk(k)             q_k                                 (7.3)\n%     qik(k,i)./qk(k)   p_ik                                (7.4)\n%     se(i)'            d_i,min^p * sumk(d_ik^-p)\n%     xf(i)'            d_i,min^-2 / sumk(d_ik^-p)\n%     xg(i)'            d_i,min^-(p+2) / sumk(d_ik^-p)^2\n\n\nss=sd+1;        % one extra loop at the start\ng=0;                % dummy initial value of g\nxn=zeros(n,1);\nfor j=1:l\n\n    g1=g;                           % save old performance\n    x1=x;                           % save old centres\n    % first do partial chunk\n\n    jx=n-(nl-1)*nb;\n    ii=1:jx;\n    kx=repmat(ii,k,1);\n    km=repmat(1:k,1,jx);\n    py=reshape(sum((d(kx(:),:)-x(km(:),:)).^2,2),k,jx);\n    [dm,xn(ii)]=min(py,[],1);                 % min value in each column gives nearest centre\n    dmk=dm(wk,:);                   % expand into a matrix\n    dq=py>dmk;                      % update only these values\n    pr=ones(k,jx);                   % leaving others at 1\n    pr(dq)=dmk(dq)./py(dq);            % ratio of min(py)./py\n    pe=pr.^eh;\n    se=sum(pe,1);\n    xf=dm.^(eh-1)./se;\n    g=xf*dm.';                     % performance criterion (divided by k)\n    xg=xf./se;\n    qik=xg(wk,:).*pe.*pr;           % qik(k,i) is equal to q_ik in [Zhang2000]\n    qk=sum(qik,2);\n    xs=qik*d(ii,:);\n    ix=jx+1;\n    for il=2:nl\n        jx=jx+nb;        % increment upper limit\n        ii=ix:jx;\n        kx=ii(wk,:);\n        py=reshape(sum((d(kx(:),:)-x(im,:)).^2,2),k,nb);\n        [dm,xn(ii)]=min(py,[],1);                 % min value in each column gives nearest centre\n        dmk=dm(wk,:);                   % expand into a matrix\n        dq=py>dmk;                      % update only these values\n        pr=ones(k,nb);                   % leaving others at 1\n        pr(dq)=dmk(dq)./py(dq);            % ratio of min(py)./py\n        pe=pr.^eh;\n        se=sum(pe,1);\n        xf=dm.^(eh-1)./se;\n        g=g+xf*dm.';                     % performance criterion (divided by k)\n        xg=xf./se;\n        qik=xg(wk,:).*pe.*pr;           % qik(k,i) is equal to q_ik in [Zhang2000]\n        qk=qk+sum(qik,2);\n        xs=xs+qik*d(ii,:);\n        ix=jx+1;\n    end\n    gg(j)=g;\n    x=xs./qk(:,wp);\n    if g1-g<=th*g1\n        ss=ss-1;\n        if ~ss break; end  %  stop if improvement < threshold for sd consecutive iterations\n    else\n        ss=sd;\n    end\nend\ngg=gg(1:j)*k/n;                       % scale and trim the performance criterion vector\ng=g(end);\n% gg' % *** DEBUIG ***\nif nargout>1\n    x=x1;                               % go back to the previous x values if G and/or XN value is output\nend\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/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/kmeanhar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673223709252, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5866814724077073}}
{"text": "function lengths = meshEdgeLength(vertices, edges, faces) %#ok<INUSD>\n%MESHEDGELENGTH Lengths of edges of a polygonal or polyhedral mesh\n%\n%   output = meshEdgeLength(V, E, F)\n%\n%   Example\n%   meshEdgeLength\n%\n%   See also\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-10-04,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% extract vertices\np1 = vertices(edges(:, 1), :);\np2 = vertices(edges(:, 2), :);\n\n% compute euclidean distance betwenn the two vertices\nlengths = sqrt(sum((p2-p1).^2, 2));\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/meshes3d/meshEdgeLength.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5866814659492777}}
{"text": "function plotSDCon(sdcone,data)\n%PLOTSDCON Plot Semidefinite Constraints on the current figure\n%   plotSDCon(sdcone)\n\n%   Copyright (C) 2013 Jonathan Currie (I2C2)\n\nxl = xlim; yl = ylim;\nhold on;\n\n%Colour\ndkr = [179/255 0.0 70/255];\n\n%Determine number of quad constraints\nif(iscell(sdcone))\n    no = length(sdcone);\nelse\n    no = 1;\nend\n%Generate Constraint Surface Points\n[x1,x2] = meshgrid(linspace(xl(1),xl(2),data.npts),linspace(yl(1),yl(2),data.npts));\n\n%For each semidefinite constraint, plot\nfor i = 1:no\n    %Get Constraint Variables & Form Constraint Function\n    if(iscell(sdcone))\n        m = sqrt(size(sdcone{i},1));\n        C = reshape(sdcone{i}(:,1),m,m); A0 = reshape(sdcone{i}(:,2),m,m); \n        switch(data.ndec)\n            case 1\n                con = @(x) min(eig(A0*x(1) - C));\n            case 2\n                A1 = reshape(sdcone{i}(:,3),m,m);\n                con = @(x) min(eig(A0*x(1) + A1*x(2) - C));\n            case 3\n                A1 = reshape(sdcone{i}(:,3),m,m); A2 = reshape(sdcone{i}(:,4),m,m);\n                con = @(x) min(eig(A0*x(1) + A1*x(2) + A2*x(3) - C));\n            case 4\n                A1 = reshape(sdcone{i}(:,3),m,m); A2 = reshape(sdcone{i}(:,4),m,m); \n                A3 = reshape(sdcone{i}(:,5),m,m);\n                con = @(x) min(eig(A0*x(1) + A1*x(2) + A2*x(3) + A3*x(4) - C));\n            case 5\n                A1 = reshape(sdcone{i}(:,3),m,m); A2 = reshape(sdcone{i}(:,4),m,m); \n                A3 = reshape(sdcone{i}(:,5),m,m); A4 = reshape(sdcone{i}(:,6),m,m);\n                con = @(x) min(eig(A0*x(1) + A1*x(2) + A2*x(3) + A3*x(4) + A4*x(5) - C));\n            otherwise\n                error('Plotting Semidefinite constraints up to 5D is only supported');\n        end\n    else\n        m = sqrt(size(sdcone,1));\n        C = reshape(sdcone(:,1),m,m); \n        A0 = reshape(sdcone(:,2),m,m);\n        switch(data.ndec)\n            case 1\n                con = @(x) min(eig(A0*x(1) - C));\n            case 2\n                A1 = reshape(sdcone(:,3),m,m);\n                con = @(x) min(eig(A0*x(1) + A1*x(2) - C));\n            case 3\n                A1 = reshape(sdcone(:,3),m,m);\n                A2 = reshape(sdcone(:,4),m,m);\n                con = @(x) min(eig(A0*x(1) + A1*x(2) + A2*x(3) - C));\n            case 4\n                A1 = reshape(sdcone(:,3),m,m);\n                A2 = reshape(sdcone(:,4),m,m);\n                A3 = reshape(sdcone(:,5),m,m);\n                con = @(x) min(eig(A0*x(1) + A1*x(2) + A2*x(3) + A3*x(4) - C));\n            case 5\n                A1 = reshape(sdcone(:,3),m,m);\n                A2 = reshape(sdcone(:,4),m,m);\n                A3 = reshape(sdcone(:,5),m,m);\n                A4 = reshape(sdcone(:,6),m,m);\n                con = @(x) min(eig(A0*x(1) + A1*x(2) + A2*x(3) + A3*x(4) + A4*x(5) - C));\n            otherwise\n                error('Plotting Semidefinite constraints up to 5D is only supported');\n        end      \n    end  \n    %Plot Each Quad Con as General Nonlinear Constraint\n    plotNLCon(con,[],1e-6,Inf,x1,x2,dkr,data);    \nend\nhold off;\n\n\n\n\n% OLD CODE \n% %Plot Semidefinite Constraints (Inefficient.. ideas appreciated!)\n% [x1,x2] = meshgrid(linspace(xl(1),xl(2),npts),linspace(yl(1),yl(2),npts));\n% nox = size(x1);\n% noy = size(x2);\n% obj = zeros(nox(1),noy(2));\n% if(iscell(sdcone))\n%     no = length(sdcone);\n% else\n%     no = 1;\n% end\n% for i = 1:no\n%     %get vars\n%     if(iscell(sdcone))\n%         C = sdcone{i}(:,1); A0 = sdcone{i}(:,2); A1 = sdcone{i}(:,3);\n%     else\n%         m = sqrt(size(sdcone,1));\n%         C = reshape(sdcone(:,1),m,m); \n%         A0 = reshape(sdcone(:,2),m,m); \n%         A1 = reshape(sdcone(:,3),m,m);\n%     end           \n%     % create surface\n%     for n = 1:nox(1)\n%         for m = 1:noy(2)      \n%             obj(n,m) = min(eig(A0*x1(n,m) + A1*x2(n,m) - C));\n%         end\n%     end\n%     c = contour(x1,x2,obj,'color',dkr,'levellist',0);\n%     %Plot Hatch\n%     if(~isempty(c))\n%         %See if we have multiple contours (non-convex or sd)\n%         len = size(c,2)-1;\n%         if(c(2,1) ~= len)\n%             %Build contour array\n%             cstrt = 2; cend = []; n = 2; ind = 1;\n%             while(ind <= len)\n%                 ind = ind + c(2,ind) + 1;\n%                 cend(n-1) = ind-1; %#ok<AGROW>\n%                 cstrt(n) = ind+1;  %#ok<AGROW>\n%                 n = n + 1;\n%             end\n%         else\n%             cstrt = 2;\n%             cend = len;\n%         end\n%         %Plot each contour hatch\n%         for n = 1:length(cend)\n%             %Get contour vectors\n%             vecx = diff(c(1,cstrt(n):cend(n)));\n%             vecy = diff(c(2,cstrt(n):cend(n)));\n%             if(isempty(vecx) || isempty(vecy))\n%                 continue;\n%             end\n%             %Rotate hatch lines based on infeasible region\n%             xt = [c(1,cstrt(n))+vecy(1) c(2,cstrt(n))-vecx(1)]'; %check rotated -90\n%             fval = all(eig(A0*xt(1) + A1*xt(2) - C) >= 1e-6);      \n%             if(fval) %rotate 90\n%                 hvecx = -vecy;\n%                 hvecy = vecx;\n%             else %rotate -90\n%                 hvecx = vecy;\n%                 hvecy = -vecx;\n%             end\n%             %Normalize \n%             av = mean(sqrt(hvecx.^2 + hvecy.^2));\n%             dirs = atan2(hvecy,hvecx);    \n%             hvecx = av*cos(dirs);\n%             hvecy = av*sin(dirs);\n%             %Shift origin\n%             hvecx = c(1,cstrt(n):cend(n)-1) + hvecx;\n%             hvecy = c(2,cstrt(n):cend(n)-1) + hvecy;\n%             %Plot\n%             line([c(1,cstrt(n):cend(n)-1)' hvecx']',[c(2,cstrt(n):cend(n)-1)' hvecy']','Color',dkr)\n%         end                \n%     else\n%         optiwarn('opti:plot','Cannot plot semidefinite constraint as contour data is empty!');\n%     end\n% end\n% \n% hold off;\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/Utilities/Plots/plotSDCon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.586608330977245}}
{"text": "function [mps] = mach2mps(mach)\n% Convert speed from mach (at standard temperature and pressure!) to \n% meters per second. \n% Chad A. Greene 2012\nmps = mach*343;", "meta": {"author": "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/mach2mps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5866083302167844}}
{"text": "function f = createConvexHullMethod(p,xL,xU)\n\nif ~isa(p.properties.derivative,'function_handle')\n    f = [];\n    return\nend\n\nif isa(p.properties.convexity,'char') && ~(isequal(p.properties.convexity,'none'))\n    vexity = p.properties.convexity;\nelseif isa(p.properties.convexity,'function_handle')\n    % User-supplied method to derive convexity in region\n    vexity = p.properties.convexity(xL,xU);\nelseif ~isempty(p.properties.inflection)\n    % Derive convexity by information about inflection\n    vexity = DeriveVexityFromInflection(p.properties,xL,xU);   \nelse\n    vexity = 'none';\nend\n\nif isequal(vexity,'convex')\n    if strcmpi(p.fcn,'blackbox')\n        f0 = @(x)real(blackbox(x,p.arg{2}));\n    else\n        f0 = @(x)real(eval([p.fcn '(x)']));\n    end\n    f = @(xL,xU)createConvexHullMethodConvex(xL,xU,f0,p.properties.derivative);\nelseif isequal(vexity,'concave')\n    f0 = @(x)real(eval([p.fcn '(x)']));\n    f = @(xL,xU)createConvexHullMethodConcave(xL,xU,f0,p.properties.derivative);\nelse\n    f = [];\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/createConvexHullMethod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5866083294563235}}
{"text": "function [ mapX, mapY ] = WarpRegion( xmin, ymin, mask, triX, coeffs )\n%WARPREGION Summary of this function goes here\n%   Detailed explanation goes here\n\n    %%\n    [h, w] = size(mask);\n    mapX = zeros(size(mask));\n    mapY = zeros(size(mask));\n \n    ys = [1:h]' * ones(1, w) + ymin - 1;\n    xs = ([1:w]' * ones(1, h))' + xmin - 1;\n    \n    for t=0:size(coeffs,1)-1\n       \n        trimap = triX == t;\n        \n        a = coeffs(t+1,:); \n                \n        xo = a(1) + a(2) * xs + a(3) * ys;       \n        \n        mapX(trimap) = xo(trimap);\n\n        yo = a(4) + a(5) * xs + a(6) * ys;\n        mapY(trimap) = yo(trimap);\n        \n    end\n    \n    mapX(~mask) = -1;\n    mapY(~mask) = -1;\n     \n    %%\n%     [h, w] = size(mask);\n%     mapX_2 = zeros(size(mask));\n%     mapY_2 = zeros(size(mask));\n%  \n%     ys = [1:h]' * ones(1, w) + ymin - 1;\n%     xs = ([1:w]' * ones(1, h))' + xmin - 1;\n%     \n%     ys = ys(:);\n%     xs = xs(:);\n%     \n%     xos = coeffs(1,:) + bsxfun(@times, coeffs(2,:), xs) + bsxfun(@times, coeffs(3,:), ys);    \n%     yos = coeffs(4,:) + bsxfun(@times, coeffs(5,:), xs) + bsxfun(@times, coeffs(6,:), ys);\n%     \n%     maps = repmat(trimap(:),1, size(coeffs,1));\n%     maps = repmat\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_validation/paw_helpers/WarpRegion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583167, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5866083243127719}}
{"text": "function G =  getGroupOverlapColor(row, col)\n\n\n    N = row*col;\n\n    g = sparse(zeros(N,1));\n    g = diag(g);\n \n \n    \n    %% build overlapping group\n    \n    % top let corner group\n     \n    g(1, 1 ) = 1;\n    g(1, 2 ) = 1;\n    g(1, 1+row ) = 1;\n    g(1, 2+row ) = 1;\n    \n     % bottom let corner group \n  \n    g(row, row-1 ) = 1;\n    g(row, row ) = 1;\n    g(row, row-1+row ) = 1;\n    g(row, row+row ) = 1;\n    \n    % top right corner group\n   \n    g((col-1)*row+1, (col-1)*row+1 ) = 1;\n    g((col-1)*row+1, (col-2)*row+1 ) = 1;\n    g((col-1)*row+1, (col-1)*row+2 ) = 1;\n    g((col-1)*row+1, (col-2)*row+2 ) = 1;\n    \n    % bottom right corner group\n    \n    g((col-1)*row+row , (col-1)*row+row-1 ) = 1;\n    g((col-1)*row+row , (col-2)*row+row-1 ) = 1;\n    g((col-1)*row+row , (col-1)*row+row ) = 1;\n    g((col-1)*row+row , (col-2)*row+row ) = 1;\n            \n            \n    \n    \n    % boundary group\n    \n    for i=2:col-1\n        % top row rgoup\n \n        j = 1;    \n  \n        g( (i-1)*row+j  , (i-2)*row+j   ) = 1;\n        g( (i-1)*row+j  , (i-2)*row+j+1 ) = 1;\n         \n        g( (i-1)*row+j  , (i-1)*row+j   ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j+1 ) = 1;             \n        \n        g( (i-1)*row+j  , i*row+j   ) = 1;\n        g( (i-1)*row+j  , i*row+j+1 ) = 1;\n\n        % bottom row group\n    \n        j = row;\n        \n        g( (i-1)*row+j  , (i-2)*row+j-1 ) = 1;\n        g( (i-1)*row+j  , (i-2)*row+j   ) = 1;\n      \n        g( (i-1)*row+j  , (i-1)*row+j-1 ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j   ) = 1;\n                \n        g( (i-1)*row+j  , i*row+j-1 ) = 1;\n        g( (i-1)*row+j  , i*row+j   ) = 1;\n         \n        \n        \n    end\n    \n    for j=2:row-1\n          % left column rgoup\n    \n            \n        i=1;\n        \n        g( (i-1)*row+j  , (i-1)*row+j-1 ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j   ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j+1 ) = 1;             \n        g( (i-1)*row+j  , i*row+j-1 ) = 1;\n        g( (i-1)*row+j  , i*row+j   ) = 1;\n        g( (i-1)*row+j  , i*row+j+1 ) = 1;\n\n        % right  column group\n \n\n        i=col;\n        \n        \n        g( (i-1)*row+j  , (i-2)*row+j-1 ) = 1;\n        g( (i-1)*row+j  , (i-2)*row+j   ) = 1;\n        g( (i-1)*row+j  , (i-2)*row+j+1 ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j-1 ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j   ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j+1 ) = 1;             \n        \n    end\n    \n    for i=2:col-1    \n        for j=2:row-1  \n            \n            \n            g( (i-1)*row+j  , (i-2)*row+j-1 ) = 1;\n            g( (i-1)*row+j  , (i-2)*row+j   ) = 1;\n            g( (i-1)*row+j  , (i-2)*row+j+1 ) = 1;\n            g( (i-1)*row+j  , (i-1)*row+j-1 ) = 1;\n            g( (i-1)*row+j  , (i-1)*row+j   ) = 1;\n            g( (i-1)*row+j  , (i-1)*row+j+1 ) = 1;             \n            g( (i-1)*row+j  , i*row+j-1 ) = 1;\n            g( (i-1)*row+j  , i*row+j   ) = 1;\n            g( (i-1)*row+j  , i*row+j+1 ) = 1;      \n\n        end\n    end\n   \n\n    \n    G = sparse(3*N, 3*N);\n    \n    G(1:N, 1:N) = g;\n    G(N+1:2*N, N+1:2*N) =g;\n    G(2*N+1:3*N, 2*N+1:3*N) =g;\n    \n    % G =[g; g; g];\n    \n\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/GOSUS/getGroupOverlapColor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.5866083191692205}}
{"text": "function res = chowlin_co_W(Y,x,ta,sc,opC)\n% PURPOSE: Temporal disaggregation using the Chow-Lin method\n%         (quarterly rho derived from Cochrane-Orcutt annual rho)\n%          Without pretesting for intercept\n% ------------------------------------------------------------\n% SYNTAX: res = chowlin_co_W(Y,x,ta,sc,opC);\n% ------------------------------------------------------------\n% OUTPUT: res: a structure\n%           res.meth    ='Chow-Lin';\n%           res.ta      = type of disaggregation\n%           res.type    = method of estimation\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.beta    = estimated model parameters\n%           res.beta_sd = estimated model parameters: standard deviation\n%           res.beta_t  = estimated model parameters: t ratios\n%           res.rho     = innovational parameter\n%           res.aic     = Information criterion: AIC\n%           res.bic     = Information criterion: BIC\n%           res.co      = Cochrane-Orcutt regression (see LeSage\n%           Econometric Toolbox)\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%        sc: number of high frequency data points for each low frequency data points \n%            sc= 3 ---> quarterly to monthly\n%            sc= 4 ---> annual to quarterly \n%        opC: 1x1 option related to intercept\n%            opc = 0 : no intercept in hf model\n%            opc = 1 : intercept in hf model\n% ------------------------------------------------------------\n% LIBRARY: aggreg, olsc\n% ------------------------------------------------------------\n% SEE ALSO: chowlin, litterman, fernandez, td_plot, td_print\n% ------------------------------------------------------------\n% REFERENCE: Chow, G. and Lin, A.L. (1971) \"Best linear unbiased \n% distribution and extrapolation of economic time series by related \n% series\", Review of Economic and Statistics, vol. 53, n. 4, p. 372-375.\n% Bournay, J. y Laroque, G. (1979) \"Reflexions sur la methode d'elaboration \n% des comptes trimestriels\", Annales de l'INSEE, n. 36, p. 3-30.\n\n% written by:\n%  Enrique M. Quilis\n%  Macroeconomic Research Department\n%  Ministry of Economy and Competitiveness\n%  <enrique.quilis@mineco.es>\n\n% Version 1.1 [August 2006]\n\nt0=clock;\n\n% ------------------------------------------------------------\n% Checks\n\nif ((sc ~= 3) & (sc ~= 4))\n    error ('*** THE FREQUENCY CONVERSION SHOULD BE 3 OR 4 ***');\n end\n \nif ((ta == 3) | (ta == 4))\n    error ('*** THIS RELEASE DOES NOT PERFORM INTERPOLATION ***');\nend\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% 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% Computing annual rho by means of Cochrane-Orcutt\n\nrex = olsc(Y,X); %Econometric Toolbox (LeSage, 1999)\n\nRa=rex.rho; %Getting annual rho\n\nif (Ra < 0)\n    error ('*** ANNUAL RHO IS NEGATIVE. END OF PROGRAM ***');\nend\n\nif (Ra >= 1)\n   Ra = 0.99;\nend\n\nr = 0:0.01:0.99; nr = length(r); R=ones(nr,1);\nswitch sc\ncase 3 %Quarterly to monthly\n   for i=1:nr\n      R(i) = (r(i)^5+2*r(i)^4+3*r(i)^3+2*r(i)^2+r(i)) / (2*r(i)^2+4*r(i)+3);\n   end\ncase 4 %Annual to quarterly\n   % ------------------------------------------------------------\n   % Evaluating the function that relates annual and quarterly rho\n   for i=1:nr\n      R(i) = (r(i)*(r(i)+1)*(r(i)^2+1)^2) / (2*(r(i)^2+r(i)+2));\n   end\nend\n   \n% -----------------------------------------------------------\n% Determination of optimal rho \n\n[aux,h] = min(abs(Ra-R));\nrho = r(h);\n\n% -----------------------------------------------------------\n% Final estimation with optimal rho\n\nI=eye(n); w=I;\nLL = diag(-ones(n-1,1),-1);\n\nAux=I+rho*LL;\nAux(1,1)=sqrt(1-rho^2);\nw=inv(Aux'*Aux);           % High frequency VCV matrix (without sigma_a)\nW=C*w*C';                  % Low frequency VCV matrix (without sigma_a)\nWi=inv(W);\nbeta=(X'*Wi*X)\\(X'*Wi*Y);  % beta estimator\nU=Y-X*beta;                % Low frequency residuals\nscp=U'*Wi*U;               % Weighted least squares\nsigma_a=scp/(N-p);         % sigma_a estimator\nL=w*C'*Wi;                 % Filtering matrix\nu=L*U;                     % High frequency residuals\n\n% -----------------------------------------------------------\n% Temporally disaggregated time series\n\ny = x*beta + u;\n\n% -----------------------------------------------------------\n% Information criteria\n% Note: p is expanded to include the innovational parameter\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_beta=sigma_a*inv(X'*Wi*X);\n\nVCV_y=sigma_a*(eye(n)-L*C)*w+(x-L*X)*sigma_beta*(x-L*X)';\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='Chow-Lin';\n\n% -----------------------------------------------------------\n% Basic parameters \n\nres.ta        = ta;\nres.N         = N;\nres.n         = n;\nres.pred      = pred;\nres.sc        = sc;\nres.p         = p;\nres.type      = 3;  % For output convenience\nres.opC       = opC;\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.beta      = beta;\nres.beta_sd   = sqrt(diag(sigma_beta));\nres.beta_t    = beta./sqrt(diag(sigma_beta));\nres.rho       = rho;\n\n% -----------------------------------------------------------\n% Information criteria\n\nres.aic       = aic;\nres.bic       = bic;\n\n% -----------------------------------------------------------\n% Cochrane-Orcutt results\n\nres.co       = rex;\n\n% -----------------------------------------------------------\n% Objective function\n\nres.val       = R;\nres.r         = r;\nres.valA      = Ra * ones(nr,1);\nres.ropt      = rho * ones(nr,1);\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/chowlin_co_W.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5866083147861297}}
{"text": "function plotData(X, y)\n%PLOTDATA Plots the data points X and y into a new figure \n%   PLOTDATA(x,y) plots the data points with + for the positive examples\n%   and o for the negative examples. X is assumed to be a Mx2 matrix.\n\n% Create New Figure\nfigure; hold on;\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Plot the positive and negative examples on a\n%               2D plot, using the option 'k+' for the positive\n%               examples and 'ko' for the negative examples.\n%\n\n% Find Indices of Positive and Negative Examples\npos = find(y==1); neg = find(y == 0);\n% Plot Examples\nplot(X(pos, 1), X(pos, 2), 'k+', 'LineWidth', 2, 'MarkerSize', 7);\nplot(X(neg, 1), X(neg, 2), 'ko', 'MarkerFaceColor', 'y', 'MarkerSize', 7);\n\n% =========================================================================\n\n\n\nhold off;\n\nend\n", "meta": {"author": "JY-112553", "repo": "machine-learning", "sha": "db9c6e5a5175739821acd97787453472b8f46cac", "save_path": "github-repos/MATLAB/JY-112553-machine-learning", "path": "github-repos/MATLAB/JY-112553-machine-learning/machine-learning-db9c6e5a5175739821acd97787453472b8f46cac/machine-learning-ex2/ex2/plotData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.5865713712182213}}
{"text": "function [z,Z,iZ,MD2,Z_e,Z_y] = innovation(y,R,e,E,f)\n\n% INNOVATION  Innovation of an observation.\n%   [z,Z] = INNOVATION(y,R,e,E) computes innovation z and innovation's\n%   covariances matrix Z from a measurement N{y,R} to the expectation N{e,E}\n%   as\n%\n%     z = y - e\n%     Z = R + E\n%\n%   [z,Z] = INNOVATION(y,R,e,E,@Finn) uses the innovation function Finn to\n%   compute the innovation:\n%\n%       z = Finn(y,e)\n%\n%   and uses its Jacobians F_e and F_y to compute Z:\n%\n%       Z = F_e*E*F_e' + F_y*R*F_y'\n%\n%   [z,Z,iZ,MD2] = INNOVATION(...) returns also the inverse of the\n%   innovation covariance iZ and the squared Mahalanobis distance MD2.\n%\n%   [z,Z,iZ,MD2,F_e,F_y] INNOVATION(...) returns the Jacobians wrt the\n%   expectation e and the measurement y.\n%\n%   EXAMPLES:\n%   innovation(seg,SEG,hmLin,HMLIN,@hms2hh) is the innovation of a segment\n%   measurement seg = [x1;y1;x2;y2] with respect to a homogeneous line\n%   hmLin = [a;b;c], defined as the two orthogonal distances from [xi;yi]\n%   to hmLin.\n%\n%   See also HMS2HH, MAHALANOBIS.\n\n%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nif nargin == 4  % Use plain Euclidean innovation\n    z   = y - e;\n    Z   = R + E;\n    Z_e = -1;\n    Z_y = 1;\nelse            % Use given function\n    [z,Z_e,Z_y] = f(e,y);\n    Z = Z_e*E*Z_e' + Z_y*R*Z_y';\nend\n\n% compute extra outputs\nif nargout >= 3\n    iZ = eye(size(Z,1))/Z;  % better than inv(Z) -- ask Matlab!\n    if nargout >= 4\n        MD2 = z'*iZ*z;\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 <http://www.gnu.org/licenses/>.\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/EKF/innovation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933403143929, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5865713646692551}}
{"text": "% DeJong_f4.m\n% De Jong's f4 function, ND, no noise\n%\n% described by Clerc in ...\n% http://clerc.maurice.free.fr/pso/Semi-continuous_challenge/Semi-continuous_challenge.htm\n%\n% used to test optimization/global minimization problems \n% in Clerc's \"Semi-continuous challenge\"\n%\n% f(x) = sum( [1:N].*(in.^4), 2)\n%\n% x = N element row vector containing [ x0, x1,..., xN ]\n%   each row is processed independently,\n%   you can feed in matrices of timeXN no prob\n%\n% example: cost = DeJong_f4([1,2;3,4;5,6])\n% note minimum =0 @ x= all zeros\n\n% Brian Birge\n% Rev 1.0\n% 9/12/04\nfunction [out]=DeJong_f4(in)\n persistent D tlen d\n\n% this speeds routine up a lot, if called from PSO these won't change from\n% call to call (repmat is a cpu hog)\n Dx=length(in(1,:));\n tlenx=length(in(:,1));\n if isempty(D) | D~=Dx | tlen~=tlenx\n   D=Dx; % dimension of prob\n   tlen=tlenx; % how many separate states\n   d=repmat([1:D],tlen,1); % needed to vectorize this\n end\n out = sum( d.*(in.^4), 2);", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/MATLAB\u667a\u80fd\u7b97\u6cd530\u4e2a\u6848\u4f8b\u5206\u6790/chapter17 \u57fa\u4e8ePSO\u5de5\u5177\u7bb1\u7684\u51fd\u6570\u5bfb\u4f18\u7b97\u6cd5/testfunctions/DeJong_f4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.5865713628430066}}
{"text": "function [c,Ls] = unsdgtreal(f,g,a,M)\n%UNSDGTREAL  Uniform non-stationary Discrete Gabor transform\n%   Usage:  c=unsdgtreal(f,g,a,M);\n%           [c,Ls]=unsdgtreal(f,g,a,M);\n%\n%   Input parameters:\n%         f     : Input signal.\n%         g     : Cell array of window functions.\n%         a     : Vector of time positions of windows.\n%         M     : Vector of numbers of frequency channels.\n%   Output parameters:\n%         c     : Cell array of coefficients.\n%         Ls    : Length of input signal.\n%\n%   `unsdgtreal(f,g,a,M)` computes the non-stationary Gabor coefficients of the\n%   input signal *f*. The signal *f* can be a multichannel signal, given in\n%   the form of a 2D matrix of size $Ls \\times W$, with *Ls* the signal\n%   length and *W* the number of signal channels.\n%\n%   As opposed to |nsdgt| only the coefficients of the positive frequencies\n%   of the output are returned. `unsdgtreal` will refuse to work for complex\n%   valued input signals.\n%\n%   The non-stationary Gabor theory extends standard Gabor theory by\n%   enabling the evolution of the window over time. It is therefore\n%   necessary to specify a set of windows instead of a single window.  This\n%   is done by using a cell array for *g*. In this cell array, the n'th\n%   element `g{n}` is a row vector specifying the n'th window. The\n%   uniformity means that the number of channels is not allowed to vary over\n%   time.\n%\n%   The resulting coefficients is stored as a $M/2+1 \\times N \\times W$\n%   array. `c(m,n,l)` is thus the value of the coefficient for time index *n*,\n%   frequency index *m* and signal channel *l*.\n%\n%   The variable *a* contains the distance in samples between two\n%   consecutive blocks of coefficients. The variable *M* contains the\n%   number of channels for each block of coefficients. Both *a* and *M* are\n%   vectors of integers.\n%\n%   The variables *g*, *a* and *M* must have the same length, and the result *c*\n%   will also have the same length.\n%   \n%   The time positions of the coefficients blocks can be obtained by the\n%   following code. A value of 0 correspond to the first sample of the\n%   signal::\n%\n%     timepos = cumsum(a)-a(1);\n%\n%   `[c,Ls]=unsdgtreal(f,g,a,M)` additionally returns the length *Ls* of the input \n%   signal *f*. This is handy for reconstruction::\n%\n%     [c,Ls]=unsdgtreal(f,g,a,M);\n%     fr=insdgtreal(c,gd,a,Ls);\n%\n%   will reconstruct the signal *f* no matter what the length of *f* is, \n%   provided that *gd* are dual windows of *g*.\n%\n%   Notes:\n%   ------\n%\n%   `unsdgtreal` uses circular border conditions, that is to say that the signal is\n%   considered as periodic for windows overlapping the beginning or the \n%   end of the signal.\n%\n%   The phaselocking convention used in `unsdgtreal` is different from the\n%   convention used in the |dgt| function. `unsdgtreal` results are phaselocked (a\n%   phase reference moving with the window is used), whereas |dgt| results are\n%   not phaselocked (a fixed phase reference corresponding to time 0 of the\n%   signal is used). See the help on |phaselock| for more details on\n%   phaselocking conventions.\n%\n%   See also:  nsdgt, insdgtreal, nsgabdual, nsgabtight, phaselock\n%\n%   Demos:  demo_nsdgt\n%\n%   References: ltfatnote018\n  \n%   AUTHOR : Florent Jaillet\n%   TESTING: TEST_NSDGTREAL\n%   REFERENCE: \n\nif ~isnumeric(a)\n  error('%s: a must be numeric.',upper(mfilename));\nend;\n\nif ~isnumeric(M)\n  error('%s: M must be numeric.',upper(mfilename));\nend;\n\nL=sum(a);\n\n[f,Ls,W,wasrow,remembershape]=comp_sigreshape_pre(f,'UNSDGTREAL',0);\nf=postpad(f,L);\n\n[g,info]=nsgabwin(g,a,M);\n\nif ~info.isuniform\n    error('%s: M must be a scalar or a constant vector.',upper(mfilename));    \nend;\nM=M(1);\n\ntimepos=cumsum(a)-a(1);\n  \nN=length(a); % Number of time positions\n\nM2=floor(M/2)+1;\nc=zeros(M2,N,W,assert_classname(f,g{1})); % Initialisation of the result\n\nfor ii=1:N\n  shift=floor(length(g{ii})/2);\n  temp=zeros(M,W,assert_classname(f,g{1}));\n  \n  % Windowing of the signal.\n  % Possible improvements: The following could be computed faster by \n  % explicitely computing the indexes instead of using modulo and the \n  % repmat is not needed if the number of signal channels W=1 (but the time \n  % difference when removing it whould be really small)\n  temp(1:length(g{ii}))=f(mod((1:length(g{ii}))+timepos(ii)-shift-1,L)+1,:).*...\n    repmat(conj(circshift(g{ii},shift)),1,W);\n  \n  temp=circshift(temp,-shift);\n  if M<length(g{ii}) \n    % Fft size is smaller than window length, some aliasing is needed\n    x=floor(length(g{ii})/M);\n    y=length(g{ii})-x*M;\n    % Possible improvements: the following could probably be computed \n    % faster using matrix manipulation (reshape, sum...)\n    temp1=temp;\n    temp=zeros(M,size(temp,2),assert_classname(f,g{1}));\n    for jj=0:x-1\n      temp=temp+temp1(jj*M+(1:M),:);\n    end\n    temp(1:y,:)=temp(1:y,:)+temp1(x*M+(1:y),:);\n  end\n  \n  % FFT of the windowed signal\n  c(:,ii,:) = reshape(fftreal(temp),M2,1,W); \nend\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/nonstatgab/unsdgtreal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5865713615207765}}
{"text": "function value = csign2 ( z1, z2 )\n\n%*****************************************************************************80\n%\n%% CSIGN2 is a complex transfer-of-sign function.\n%\n%  Discussion:\n%\n%    The L2 norm is used.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 April 2006\n%\n%  Author:\n%\n%    MATLAB version by John Burkardt\n%\n%  Parameters:\n%\n%    Input, complex Z1, Z2, the arguments.\n%\n%    Output, complex VALUE,  a complex value, with the magnitude of\n%    Z1, and the argument of Z2.\n%\n  if ( cabs2 ( z2 ) == 0.0 )\n    value = 0.0;\n  else\n    value = cabs2 ( z1 ) * ( z2 / cabs2 ( z2 ) );\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/blas0/csign2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5865644727695237}}
{"text": "function hz=spc2hz(i,fs,n)\nhz = i/((n-1)/(fs/2));", "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/spc2hz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5865644691538903}}
{"text": "function [cmap] = buildcmap(colors)\n% [cmap]=buildcmap(colors)\n%\n% This function can be used to build your own custom colormaps. Imagine if\n% you want to display rainfall distribution map. You want a colormap which\n% ideally brings rainfall in mind, which is not achiveved by colormaps such\n% as winter, cool or jet and such. A gradient of white to blue will do the\n% task, but you might also use a more complex gradient (such as\n% white+blue+red or colors='wbr'). This function can be use to build any\n% colormap using main colors rgbcmyk. In image processing, w (white) can be\n% used as the first color so that in the output, the background (usually\n% with 0 values) appears white. In the example of rainfall map, 'wb' will\n% produce a rainfall density map where the background (if its DN values are\n% 0) will appear as white.\n%\n% Inputs:\n%  colors: string (char) of color codes, any sequence of rgbcmywk\n%  representing different colors (such as 'b' for blue) is acceptable. If a\n%  gradient of white to blue is needed, colors would be 'wb'; a rainbow of\n%  white+blue+red+green would be 'wbrg'.\n%\n% Example:\n%  [cmap]=buildcmap('wygbr');\n% %try the output cmap:\n% im=imread('cameraman.tif');\n% imshow(im), colorbar\n% colormap(cmap) %will use the output colormap\n%\n% First version: 14 Feb. 2013\n% sohrabinia.m@gmail.com\n%--------------------------------------------------------------------------\n\nif nargin<1\n    colors='wrgbcmyk';\nend\n\nif ~ischar(colors)\n    error(['Error! colors must be a variable of type char with '...\n        'color-names, such as ''r'', ''g'', etc., '...\n        'type ''help buildcmap'' for more info']);\nend\n\nncolors=length(colors)-1;\n\n\nbins=round(255/ncolors);\n% diff1=255-bins*ncolors;\n\nvec=zeros(300,3);\n\nswitch colors(1)\n    case 'w'\n        vec(1,:)=1;\n    case 'r'\n        vec(1,:)=[1 0 0];\n    case 'g'\n        vec(1,:)=[0 1 0];\n    case 'b'\n        vec(1,:)=[0 0 1];\n    case 'c'\n        vec(1,:)=[0 1 1];\n    case 'm'\n        vec(1,:)=[1 0 1];\n    case 'y'\n        vec(1,:)=[1 1 0];\n    case 'k'\n        vec(1,:)=[0 0 0];\nend\n\n\nfor i=1:ncolors\n beG=(i-1)*bins+1;\n enD=i*bins+1; %beG,enD\n switch colors(i+1)\n     case 'w'\n         vec(beG:enD,1)=linspace(vec(beG,1),1,bins+1)';\n         vec(beG:enD,2)=linspace(vec(beG,2),1,bins+1)';\n         vec(beG:enD,3)=linspace(vec(beG,3),1,bins+1)';%colors(i+1),beG,enD,\n     case 'r'\n         vec(beG:enD,1)=linspace(vec(beG,1),1,bins+1)';\n         vec(beG:enD,2)=linspace(vec(beG,2),0,bins+1)';\n         vec(beG:enD,3)=linspace(vec(beG,3),0,bins+1)';%colors(i+1),beG,enD\n     case 'g'\n         vec(beG:enD,1)=linspace(vec(beG,1),0,bins+1)';\n         vec(beG:enD,2)=linspace(vec(beG,2),1,bins+1)';\n         vec(beG:enD,3)=linspace(vec(beG,3),0,bins+1)';%colors(i+1),beG,enD\n     case 'b'         \n         vec(beG:enD,1)=linspace(vec(beG,1),0,bins+1)';\n         vec(beG:enD,2)=linspace(vec(beG,2),0,bins+1)';\n         vec(beG:enD,3)=linspace(vec(beG,3),1,bins+1)';%colors(i+1),beG,enD\n     case 'c'\n         vec(beG:enD,1)=linspace(vec(beG,1),0,bins+1)';\n         vec(beG:enD,2)=linspace(vec(beG,2),1,bins+1)';\n         vec(beG:enD,3)=linspace(vec(beG,3),1,bins+1)';%colors(i+1),beG,enD\n     case 'm'\n         vec(beG:enD,1)=linspace(vec(beG,1),1,bins+1)';\n         vec(beG:enD,2)=linspace(vec(beG,2),0,bins+1)';\n         vec(beG:enD,3)=linspace(vec(beG,3),1,bins+1)';\n     case 'y'\n         vec(beG:enD,1)=linspace(vec(beG,1),1,bins+1)';\n         vec(beG:enD,2)=linspace(vec(beG,2),1,bins+1)';\n         vec(beG:enD,3)=linspace(vec(beG,3),0,bins+1)';\n     case 'k'\n         vec(beG:enD,1)=linspace(vec(beG,1),0,bins+1)';\n         vec(beG:enD,2)=linspace(vec(beG,2),0,bins+1)';\n         vec(beG:enD,3)=linspace(vec(beG,3),0,bins+1)';\n end\nend\ncmap=vec(1:bins*ncolors,:);\nend %end of buildcmap\n", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/3D/buildcmap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5865644684344596}}
{"text": "function [logww] = free_energy(vv,beta_k1,beta_k0,visbiases_base,visbiases,hidbias,vishid)\n\n [numcases,numdims] = size(vv); \n temp_base = vv*visbiases_base'; \n temp_bias = vv*visbiases'; \n tempvWh = hidbias + (vv*vishid);  \n\n aa = beta_k1; \n p_star_k1  = (1-aa)*temp_base  + aa*temp_bias + sum(log(1+exp(aa*tempvWh)),2);\n\n aa = beta_k0;\n p_star_k0  =  (1-aa)*temp_base + aa*temp_bias + sum(log(1+exp(aa*tempvWh)),2);\n\n logww = (p_star_k1 - p_star_k0);\n\n\n\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/free_energy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.6513548578981939, "lm_q1q2_score": 0.5865644543475852}}
{"text": "%This Matlab script can be used to reproduce Figure 3.8 in the monograph:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.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%Empty workspace and close figures\nclose all;\nclear;\n\n\n%Define number of UEs per cell\nK = 10;\n\n%Define the range of BS antennas\nMrange = 10:10:100;\n\n%Define the pilot length\ntau_p = K;\n\n%Complexity of MMSE channel estimation, based on Table 3.1\ncomplexity_MMSE = Mrange*tau_p + Mrange.^2;\n\n%Complexity of EW-MMSE channel estimation, based on Table 3.1\ncomplexity_EW_MMSE = Mrange*(tau_p + 1);\n\n%Complexity of LS channel estimation, based on Table 3.1\ncomplexity_LS = Mrange*tau_p;\n\n\n%% Plot the simulation results\nfigure;\nhold on; box on;\n\nplot(Mrange,complexity_MMSE,'r--','LineWidth',1);\nplot(Mrange,complexity_EW_MMSE,'k-','LineWidth',1);\nplot(Mrange,complexity_LS,'b-.','LineWidth',1);\n\nxlabel('Number of antennas (M)');\nylabel('Number of complex multiplications');\nset(gca,'YScale','log');\n\nlegend('MMSE','EW-MMSE','LS','Location','NorthWest');\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/section3_figure8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.5865258702669082}}
{"text": "function element_node = grid_t10_element ( nelemx, nelemy )\n\n%*****************************************************************************80\n%\n%% GRID_T10_ELEMENT produces a grid of pairs of 10 node triangles.\n%\n%  Example:\n%\n%    Input:\n%\n%      NELEMX = 2, NELEMY = 2\n%\n%    Output:\n%\n%      ELEMENT_NODE =\n%         1,  2,  3,  4, 10, 16, 22, 15,  8,  9;\n%        25, 24, 23, 22, 16, 10,  4, 11, 18, 17;\n%         4,  5,  6,  7, 13, 19, 25, 18, 11, 12;\n%        28, 27, 26, 25, 19, 13,  7, 14, 21, 20;\n%        22, 23, 24, 25, 31, 37, 43, 36, 29, 30;\n%        46, 45, 44, 43, 37, 31, 25, 32, 39, 38;\n%        25, 26, 27, 28, 34, 40, 46, 39, 31, 33;\n%        49, 48, 47, 46, 40, 34, 28, 35, 42, 41.\n%\n%  Grid:\n%\n%   43-44-45-46-47-48-49\n%    |\\     6 |\\     8 |\n%    | \\      | \\      |\n%   36 37 38 39 40 41 42\n%    |   \\    |   \\    |\n%    |    \\   |    \\   |\n%   29 30 31 32 33 34 35\n%    |      \\ |      \\ |\n%    | 5     \\| 7     \\|\n%   22-23-24-25-26-27-28\n%    |\\     2 |\\     4 |\n%    | \\      | \\      |\n%   15 16 17 18 19 20 21\n%    |   \\    |   \\    |\n%    |    \\   |    \\   |\n%    8  9 10 11 12 13 14\n%    |      \\ |      \\ |\n%    | 1     \\| 3     \\|\n%    1--2--3--4--5--6--7\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, 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(10,2*NELEMX*NELEMY), the nodes that form\n%    each element.\n%\n  element = 0;\n\n  for j = 1 : nelemy\n    for i = 1 : nelemx\n\n      base = ( j - 1 ) * 3 * ( 3 * nelemx + 1 ) + 3 * i - 2;\n\n      element = element + 1;\n\n      element_node( 1,element) = base;\n      element_node( 2,element) = base                          + 1;\n      element_node( 3,element) = base                          + 2;\n      element_node( 4,element) = base                          + 3;\n      element_node( 5,element) = base +     ( 3 * nelemx + 1 ) + 2;\n      element_node( 6,element) = base + 2 * ( 3 * nelemx + 1 ) + 1;\n      element_node( 7,element) = base + 3 * ( 3 * nelemx + 1 );\n      element_node( 8,element) = base + 2 * ( 3 * nelemx + 1 );\n      element_node( 9,element) = base +     ( 2 * nelemx + 1 ) + 2;\n      element_node(10,element) = base +     ( 2 * nelemx + 1 ) + 3;\n\n      element = element + 1;\n\n      element_node( 1,element) = base + 3 * ( 3 * nelemx + 1 ) + 3;\n      element_node( 2,element) = base + 3 * ( 3 * nelemx + 1 ) + 2;\n      element_node( 3,element) = base + 3 * ( 3 * nelemx + 1 ) + 1;\n      element_node( 4,element) = base + 3 * ( 3 * nelemx + 1 );\n      element_node( 5,element) = base + 2 * ( 3 * nelemx + 1 ) + 1;\n      element_node( 6,element) = base +     ( 3 * nelemx + 1 ) + 2;\n      element_node( 7,element) = base                          + 3;\n      element_node( 8,element) = base +     ( 3 * nelemx + 1 ) + 3;\n      element_node( 9,element) = base + 2 * ( 3 * nelemx + 1 ) + 3;\n      element_node(10,element) = base + 2 * ( 3 * nelemx + 1 ) + 2;\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_t10_element.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5865258585287524}}
{"text": "function [on,rt,ac] = spm_ADEM_cue_rt(DEM)\n% returns reaction times and accuracy for ADEM_cued_response demo\n% FORMAT [on,rt,ac] = spm_ADEM_cue_rt(DEM)\n%\n% DEM - DEM structure from ADEM_cued_response.m\n%\n% on  - cue onset\n% ac  - accuracy\n% rt  - reaction time\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_ADEM_set_rt.m 4231 2011-03-07 21:00:02Z karl $\n \n% distance from target and cue contrast\n%--------------------------------------------------------------------------\nP   = DEM.pP.P{1};                            % location of targets\nL   = DEM.pU.v{1}((1:2) + 2,:);               % location of finger\nn   = length(P);                              % number of targets\nN   = length(L);                              % number of time bins\nD   = sparse(n,N);\nfor j = 1:N\n    for i = 1:n\n        D(i,j) = D(i,j) + sum((L(:,j) - P(:,i)).^2);\n    end\nend\nD   = sqrt(D);                                % distance from targets\nC   = DEM.pU.v{1}((1:n) + 4,:);               % contrast of targets\n \nr   = 1/32;                                   % radius of proximity\nc   = diff(C > 1/2,1,2) > 0;                  % target onset\non  = {};                                     % cue onset\nac  = {};                                     % accuracy\nrt  = {};                                     % reaction time\n \n% get performance\n%--------------------------------------------------------------------------\nfor i = 1:n\n    \n    on{i} = find(c(i,:));\n    for j = 1:length(on{i})\n        try\n            \n            % minimum distance\n            %--------------------------------------------------------------\n            d        = D(i,(1:8) + on{i}(j))';\n            ac{i}(j) = sqrt(min(d));\n            \n            % estimated reaction time\n            %--------------------------------------------------------------\n            X        = (1:length(d))' - 1;\n            B        = pinv([X.^0 X.^1])*log(d);\n            rt{i}(j) = (log(r) - B(1))/B(2);\n            \n        catch\n            ac{i}(j) = NaN;\n            rt{i}(j) = NaN;\n        end\n    end\nend\n \n% sort trials (over all targets\n%--------------------------------------------------------------------------\non = spm_vec(on); [i j] = sort(on,1,'ascend'); on = on(j);\nac = spm_vec(ac); ac = ac(j);\nrt = spm_vec(rt); rt = rt(j);\n \n% remove first trial\n%--------------------------------------------------------------------------\non(1) = [];\nrt(1) = [];\nac(1) = [];\n \n% convert spatial error to accuracy\n%--------------------------------------------------------------------------\nac    = 1./ac;\n \n% convert reaction time to ms\n%--------------------------------------------------------------------------\ndt    = 64/1000;\nrt    = rt*1000*dt;\non    = on*dt;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_ADEM_set_rt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5864804591813102}}
{"text": "\n% Shared Matting Matte Refinement\n% This function implements the matte refinement approach described in\n% Eduardo S. L. Gastal, Manuel M. Oliveira, \"Shared Sampling for \n% Real-Time Alpha Matting\", Computer Graphics Forum, 2010.\n% 'alphaHat' and 'confidences' parameters are typically obtained by a\n% sampling-based natural matting algorithm. 'confidences' is filled by\n% ones if not provided. Optional input parameter 'params' can be \n% customized by editing the default values in the struct returned \n% by 'getMattingParams('SharedMatting').\n% - loc_*** define the parameters for the matting Laplacian.\n% - refinement_mult determines how much trust is given to the initial\n%   alpha estimation\n\nfunction alpha = sharedMattingMatteRefinement(image, trimap, alphaHat, confidences, params, suppressMessages)\n    abmtSetup\n    tic;\n    if ~exist('confidences', 'var') || isempty(confidences)\n        confidences = ones(size(alphaHat(:,:,1)));\n    end\n    if ~exist('params', 'var') || isempty(params)\n        params = getMattingParams('SharedMatting');\n    end\n    if ~exist('suppressMessages', 'var') || isempty(suppressMessages)\n        suppressMessages = false;\n    end\n    if(~suppressMessages) display('Matte refinement via Shared Matting...'); end\n\n    image = im2double(image);\n    trimap = im2double(trimap(:,:,1));\n    alphaHat = im2double(alphaHat(:,:,1));\n\n    % Compute matting Laplacian\n    unk = trimap < 0.8 & trimap > 0.2;\n    dilUnk = imdilate(unk, ones(3, 3));\n    if(~suppressMessages) display('     Computing matting Laplacian...'); end\n    Lap = affinityMatrixToLaplacian(mattingAffinity(image, dilUnk, params.loc_win, params.loc_eps));\n    \n    if(~suppressMessages) display('     Solving for alphas...'); end\n    alpha = solveForAlphas(Lap, trimap, params.lambda, params.usePCGtoSolve, alphaHat, confidences, params.refinement_mult);\n\n    alpha = reshape(alpha, [size(image, 1), size(image, 2)]);\n    \n    dur = toc;\n    if(~suppressMessages) display(['Done. It took ' num2str(dur) ' seconds.']); end\nend\n", "meta": {"author": "yaksoy", "repo": "AffinityBasedMattingToolbox", "sha": "ab3951065321b67d3ad67333779cbb2078474939", "save_path": "github-repos/MATLAB/yaksoy-AffinityBasedMattingToolbox", "path": "github-repos/MATLAB/yaksoy-AffinityBasedMattingToolbox/AffinityBasedMattingToolbox-ab3951065321b67d3ad67333779cbb2078474939/sharedMattingMatteRefinement.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.5864804381230758}}
{"text": "function [y, b] = remove_baseline(y, sn)\n% estiamte baseline of the calcium traces and subtract it \nif ~exist('sn', 'var') || isempty(sn)\n    sn = get_noise_fft(reshape(y, 1, [])); \nend\nsz = size(y); \ny = reshape(y, 1, []); \ny_diff = [-1, diff(y)]; \nb = median(y(and(y_diff>=0, y_diff<sn))); \ny = reshape(y-b, sz); ", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/endoscope/remove_baseline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.586397196147613}}
{"text": "% Test file for SPINSPHERE:\n\nfunction pass = test_spinsphere()\n\ntol = 1e-2;\n\n%% AC:\n\n% Solve with DT and DT/2:\nS = spinopsphere('AC'); S.tspan = S.tspan/10;\nN = 128; dt = 1e-1;\nu = spinsphere(S, N, dt, 'plot', 'off');\nv = spinsphere(S, N, dt/2, 'plot', 'off');\n\n% Compare:\ndom = S.domain;\n[xx, yy] = meshgrid(linspace(dom(1), dom(2), 50));\nscale = max(max(abs(v(xx,yy))));\npass(1) = max(max(abs(u(xx,yy) - v(xx,yy))))/scale < tol;\n\n%% GL:\n\n% Solve with DT and DT/2:\nS = spinopsphere('GL'); S.tspan = S.tspan/10; \nS.init =  spherefun(@(x,y,z) cos(cosh(x.*z)-y));\nN = 128; dt = 1e-1;\nu = spinsphere(S, N, dt, 'plot', 'off');\nv = spinsphere(S, N, dt/2, 'plot', 'off');\n\n% Compare:\ndom = S.domain;\n[xx, yy] = meshgrid(linspace(dom(1), dom(2), 50));\nscale = max(max(abs(v(xx,yy))));\npass(2) = max(max(abs(u(xx,yy) - v(xx,yy))))/scale < tol;\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/spinopsphere/test_spinsphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5863971857662045}}
{"text": "function [datsmooth] = ft_preproc_smooth(dat, n, tol)\n\n% FT_PREPROC_SMOOTH performs boxcar smoothing with specified length.\n% Edge behavior is improved by implicit padding with the mean over\n% half the boxcar length at the edges of the data segment.\n%\n% Use as\n%   [dat] = ft_preproc_smooth(dat, n)\n%\n% Where dat is an Nchan x Ntime data matrix, and n is the length\n% of the boxcar smoothing kernel\n%\n% If the data contains NaNs, these are ignored for the computation, but\n% retained in the output.\n%\n% See also PREPROC\n\n% Undocumented options:\n%  n can also be a vector containing a custom smoothing kernel\n%  n can also be 'regsmooth', using a regularised estimate of the first temporal derivative \n%\n% Copyright (C) 2010, Stefan Klanke\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 <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% preprocessing fails on channels that contain NaN\nif any(isnan(dat(:)))\n  ft_warning('FieldTrip:dataContainsNaN', 'data contains NaN values');\nend\n\n% create smoothing kernel\nregflag = false;\nif isequal(n, 'regsmooth')\n  regflag = true;\n  n = 0;\nelseif isscalar(n)\n  krn = ones(1,n)/n;\nelse\n  krn = n(:)'./sum(n(:));\n  n   = numel(krn);\nend\n\n% deal with padding\ndat = ft_preproc_padding(dat, 'localmean', ceil(n/2));\n\n% do the smoothing\nif regflag\n  if nargin<3\n    tol = 1e-9;\n  end\n  datsmooth = smooth_regularised(dat, tol);\nelseif n<100\n  % heuristic: for large kernel the convolution is faster when done along\n  % the columns, weighing against the costs of doing the transposition.\n  % the threshold of 100 is a bit ad hoc.\n  datsmooth = convn(dat,   krn,   'same');\nelse\n  datsmooth = convn(dat.', krn.', 'same').';\nend\n\n% cut the eges\ndatsmooth = ft_preproc_padding(datsmooth, 'remove', ceil(n/2));\n\nfunction out = smooth_regularised(dat, tol)\n\ntol = tol.*std(dat(:));\nn   = size(dat, 2);\nB    = eye(n);\n\n% create Toeplitz matrix F\nr = [1 zeros(1,n-1)];\nd = [1 zeros(1,n-1)];\nm = 2;\nfor k=1:m\n d = filter([1 -1],1,d);\nend\nF = toeplitz(d,r);\n\n% create Toeplitz matrix G\nc = ones(n,1);\nG = toeplitz(c,r);\n\n% compute gamma parameter\n\n% SVD\nH       = B*(G/F);\n[U,D,V] = svd(H);\ndiagD2  = diag(D).^2;\ndiagD   = diag(D);\nepsi    = U'*B*dat.';\n\ngammarange = 10.^(-10:0.2:10);\nngamma     = numel(gammarange);\nonevec_n   = ones(n,1);\nonevec_ngamma = ones(1,ngamma);\n\nnchan = size(dat,1);\nro    = zeros(n,ngamma,nchan);\nfor k = 1:nchan\n  ro(:,:,k) = (gammarange(onevec_n,:).*epsi(:,k.*onevec_ngamma))./(diagD2(:,onevec_ngamma) + gammarange(onevec_n,:));\nend\nwrss = squeeze(sum(ro.^2));\n\ngamma = zeros(nchan,1);\nni = zeros(n,nchan);\nfor k = 1:nchan\n  gamma(k,1) = gammarange(find(wrss(:,k)<tol,1,'last'));\n  ni(:,k) = (diagD.*epsi(:,k))./(diagD2 + gamma(k));\nend\n\nddata_smooth = transpose(F\\V*ni);\nout          = ddata_smooth*G';\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/preproc/ft_preproc_smooth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5863971849342681}}
{"text": "classdef DTLZ7 < PROBLEM\n% <multi/many> <real> <large/none> <expensive/none>\n% Benchmark MOP proposed by Deb, Thiele, Laumanns, and Zitzler\n\n%------------------------------- Reference --------------------------------\n% K. Deb, L. Thiele, M. Laumanns, and E. Zitzler, Scalable test problems\n% for evolutionary multiobjective optimization, Evolutionary multiobjective\n% Optimization. Theoretical Advances and Applications, 2005, 105-145.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            if isempty(obj.M); obj.M = 3; end\n            if isempty(obj.D); obj.D = obj.M+19; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            PopObj = zeros(size(PopDec,1),obj.M);\n            g      = 1+9*mean(PopDec(:,obj.M:end),2);\n            PopObj(:,1:obj.M-1) = PopDec(:,1:obj.M-1);\n            PopObj(:,obj.M)     = (1+g).*(obj.M-sum(PopObj(:,1:obj.M-1)./(1+repmat(g,1,obj.M-1)).*(1+sin(3*pi.*PopObj(:,1:obj.M-1))),2));\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            interval     = [0,0.251412,0.631627,0.859401];\n            median       = (interval(2)-interval(1))/(interval(4)-interval(3)+interval(2)-interval(1));\n            X            = UniformPoint(N,obj.M-1,'grid');\n            X(X<=median) = X(X<=median)*(interval(2)-interval(1))/median+interval(1);\n            X(X>median)  = (X(X>median)-median)*(interval(4)-interval(3))/(1-median)+interval(3);\n            R            = [X,2*(obj.M-sum(X/2.*(1+sin(3*pi.*X)),2))];\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            if obj.M == 2\n                x      = linspace(0,1,100)';\n                y      = 2*(2-x/2.*(1+sin(3*pi*x)));\n                nd     = NDSort([x,y],1)==1;\n                x(~nd) = nan;\n                R      = [x,y];\n            elseif obj.M == 3\n                [x,y]  = meshgrid(linspace(0,1,20));\n                z      = 2*(3-x/2.*(1+sin(3*pi*x))-y/2.*(1+sin(3*pi*y)));\n                nd     = reshape(NDSort([x(:),y(:),z(:)],1)==1,size(z));\n                z(~nd) = nan;\n                R      = {x,y,z};\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/DTLZ/DTLZ7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5863971809914683}}
{"text": "function [result_edgesize,result_pertg,nvell_num] = Riverflux_distribution(obj)     \n% [result_edgesize,result_pertg\uff0cnvell_num] = Riverflux_distribution(obj) \n% \n% Input a msh class object to get the representative edge width and flux \n% percentage for each node on the riverine flow boundary.\n% \n% This function is used to distribute a total flux of a cross-section where \n% the riverine boundary located to each node of the riverine boundary. \n%\n% result_edgesize and result_pertgis are the result of the representative \n% edge width and flux percentage for each node, respectively. nvell_num \n% represents the number of nodes for each riverine boundary.\n%\n% Each column of result_edgesize and result_pertg represents the result of \n% each riverine boundary. \n%\n% Nodal representative edge width equals to the sum of half the width of\n% each of the two edges it is connected to.\n%\n% Nodeal flow percentage on the riverine boundary equals to the flow area\n% of this node divided by the total flow area of the cross-section.\n% \n% Nodal flow area is calculated via a trapezoidal rule using its representative\n% edge width and the bathymetric depths of this node and its neighboring nodes.\n%\n% Note that the calculation of representative edge width and flow percentage \n% for the nodes at either end of the boundary is a little bit of different. \n% \n% User need to specify river flow boundaries (ibtype=22) before using it.\n%\n% Author:      Jiangchao Qiu                                \n% Created:     January 7 2021                                      \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nbd_dat = obj.bd;\np_dat = obj.p;\nb_dat = obj.b;\nriver_num = find(bd_dat.ibtype == 22);\nN = length(river_num);% total number of river boundarys\nnvell_num = bd_dat.nvell(river_num);% number of nodes for each river boundary\n\n% Consider the riverine boundaries may have different number of nodes, the \n% number of rows for result_edgesize and result_pertg is set to max(nvell_num)\nresult_edgesize = NaN(max(nvell_num),N); % the final result of edgesize\nresult_pertg = NaN(max(nvell_num),N);% the final result of percentage\n\nif isempty(river_num)\n    error('No riverine boundary information to distribute total flow')\nend\n\nfor i=1:N\n    node_num = bd_dat.nbvv(:,river_num(i));\n    node_num(node_num==0)=[];\n    bathy = b_dat(node_num);\n    location = p_dat(node_num,:); \n    J = length(node_num);% total number of nodes for the current river boundary\n    flowarea = zeros(J,1);\n    edgesize = zeros(J,1);\n    %% calculate the projected distance for each edge on the boundary\n    proj = 'Mercator';\n    m_proj(proj,'lon',[ min(obj.p(:,1))-0.25 max(obj.p(:,1))+0.25 ],...\n                'lat',[ min(obj.p(:,2))-0.25 max(obj.p(:,2))+0.25])\n    proj_location = zeros(J,2);\n    for j=1:J\n        [proj_location(j,1),proj_location(j,2)] = m_ll2xy(location(j,1),location(j,2));\n    end\n    node_distance = 1000*m_xydist(proj_location(:,1),proj_location(:,2));     \n    %% calculate the respresentive width for each node\n    % note: if the current boundary has J nodes, there are J-1 edges\t\n    for j=1:J\n\t\tif j==1      % the first edge (the number is J) \n            edgesize(j) = 0.5*node_distance(j);\n        elseif j==J  % the last edge (the number is J-1)\n            edgesize(j) = 0.5*node_distance(j-1);\n        else         % the other edges \n            edgesize(j) = 0.5*node_distance(j-1)+0.5*node_distance(j);\n        end\n        result_edgesize(1:J,i) = edgesize;\n    end\n    %% calculate flow area for each node on the boundary\n    for j=1:J\n        if j==1      % the first node\n            local_z1 = (bathy(j)+bathy(j+1))*0.5;\n            flowarea(j) = 0.5*(bathy(j)+local_z1)*(0.5*node_distance(j));\n        elseif j==J  % the last node \n            local_z1 = (bathy(j-1)+bathy(j))*0.5;\n            flowarea(j) = 0.5*(bathy(j)+local_z1)*(0.5*node_distance(j-1));\n        else         % the other nodes\n            local_z1 = (bathy(j-1)+bathy(j))*0.5;\n            local_z2 = (bathy(j)+bathy(j+1))*0.5;\n            flowarea(j) = 0.5*(bathy(j)+local_z1)*(0.5*node_distance(j-1))+...\n                          0.5*(bathy(j)+local_z2)*(0.5*node_distance(j));\n        end\n        percent = flowarea/sum(flowarea);  % the flux distribution percentage for each node\n        result_pertg(1:J,i) =  percent;\n    end\nend\n\n\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/Riverflux_distribution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5863971745528596}}
{"text": "function pass = test_complex(pref) \n% Test complex\n\nif ( nargin == 0) \n    pref = chebfunpref; \nend\ntol = 1000*pref.cheb3Prefs.chebfun3eps;\n\nf = chebfun3(@(x,y,z) sin(x.*y.*z));\ng = chebfun3(@(x,y,z) cos(x.*y.*z));\nh = chebfun3(@(x,y,z) sin(x.*y.*z) + 1i*cos(x.*y.*z));\npass = norm(h - complex(f, g)) < tol;\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun3/test_complex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.5862824551683202}}
{"text": "function  [Ypred, ps] = evaluateHist(model, X)\n\ngrids = model.grids;\nntypes = size(model.hist,3);\n\nlogps = zeros(size(X,1), ntypes);\nfor j = 1:size(model.grids,2)\n    xp = X(:, j+1);\n    xp(xp<grids(1,j))   = grids(1,j);\n    xp(xp>grids(end,j)) = grids(end,j);\n    \n    [~, ~, ibin]    = histcounts(xp, grids(:,j));\n    \n    logps           = logps + log(sq(model.hist(ibin, j, :)));\nend\n\nps = ones(1,ntypes)/ntypes; \nfor j = 1:10\n    L    = bsxfun(@plus, logps, log(ps));\n    L    = bsxfun(@minus, L, max(L, [], 2));\n    rs   = exp(L) + 1e-5;\n    rs   = bsxfun(@rdivide, rs, sum(rs,2));\n    ps   = mean(rs,1);\nend\n\nYpred = rs(:,1);    \n", "meta": {"author": "cortex-lab", "repo": "Suite2P", "sha": "c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5", "save_path": "github-repos/MATLAB/cortex-lab-Suite2P", "path": "github-repos/MATLAB/cortex-lab-Suite2P/Suite2P-c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5/gui2P/evaluateHist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5862197479020964}}
{"text": "function [betas,stats] = weighted_glmfit(Y,varargin)\n% Calculate weighted average using weighted linear least squares\n% See examples below for usage\n%\n% Model:\n% Y_i = 1*Ypop + noise\n%\n% :Inputs:\n%\n%   **Y:**\n%        data matrix (nsub x T)\n%\n%   **w:**\n%        weights\n%\n%   **varY:**\n%        variance of data at each time point (nsub x T) + var between\n%\n% :Outputs:\n%\n%   **Ymean:**\n%        weighted mean of each column of Y\n%\n%   **dfe:**\n%        error degrees of freedom, adjusted for inequality of variance\n%        (Sattherwaite) and pooled across data columns\n%\n% :Extended output in stats structure:\n%\n%   **stats.t:**\n%        t-values for weighted t-test\n%\n%   **stats.p:**\n%        2-tailed p-values for weighted t-test\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%          - sqrt(v) is the standard error of the mean (or grp difference)\n%\n%\n%   **stats.fits:**\n%        fits  for each group (Ymean by group), low contrast weight group then high\n%\n% Fastest if no stats are asked for.\n%\n% :Computation time:\n% For FULL stats report\n%   - Triples from 500 -> 1000 columns of Y, continues to increase\n%\n% For mean/dfe only, fast for full dataset (many columns of Y)\n%\n% :Examples:\n%\n% Basic multivariate stats for 1000 columns of dat, no weighting\n% Multivariate covariances are meaningful if cols of Y are organized, e.g.,\n% timeseries\n% ::\n%\n%    [means,stats] = weighted_glmfit(dat(:,1:1000));\n%\n% The same, but return univariate stats only (good for large Y)\n% ::\n%\n%    [means,stats] = weighted_glmfit(dat,'uni');\n%\n% A weighted version, where we put in the weights, and with a design matrix too:\n% ::\n%\n%    [means,stats] = weighted_glmfit(X,dat,'uni','w',weights);\n%\n% A weighted version, where weights are determined from w/i subject variances:\n% ::\n%\n%    [means,stats] = weighted_glmfit(X,dat,'uni','vary',variances);\n%\n% ..\n%    NOTE: TOR CHANGED INPUT TO ASSUME THAT WE SHOULD ENTER VARWI + VARBETWEEN\n% ..\n\nif nargin == 0, error('Must at least enter data as 1st argument.'); end\n\n% --------------------------------------\n% * Set up arguments\n% --------------------------------------\n\ndomultivariate = 0;     % multivariate covariance est for Y\n\nzpdiff = []; w = []; varY = []; X = [];\n\nfor i = 1:length(varargin)\n    arg = varargin{i};\n    if ischar(arg)\n        switch lower(arg)\n            case 'w', w = varargin{i+1};\n            case 'vary', varY = varargin{i+1};\n            case 'uni', domultivariate = 0;\n            case 'multi', domultivariate = 1;\n                \n            case {'X','x'}, X = varargin{i+1};\n        end\n    end\nend\n\n% fill in missing inputs with default values\n\nif ~is_entered(w), w = ones(m,1);  end\nif ~is_entered(varY), varY = ones(m,1); end\nif ~is_entered(X), X = ones(m,1);  end\n\n% Get rid of missing values\nnancols = find(any(isnan(Y) | Y==0,1));\nY(:,nancols) = [];\n\n[m,n] = size(Y);\n\n% --------------------------------------\n% * Means and contrast\n% --------------------------------------\n\n% pool weights across all voxels\n[betas,invxwx,bform,fits] = get_betas_singleweight(X,Y,w);\n\nif nargout == 1, return, end\n\n% --------------------------------------\n% * Residuals\n% --------------------------------------\n\ne = Y - fits;         % residuals\n\n\n% --------------------------------------\n% * Degrees of freedom\n% --------------------------------------\n\n[dfe,dfediff] = get_dfe(m,n,X,bform,varY,0);\n\n\n\nif ~domultivariate\n    % ======================================\n    %\n    %\n    % Univariate stats: MSE, t, and p-values\n    %\n    %\n    % ======================================\n\n    % --------------------------------------\n    % * Mean squared error\n    % --------------------------------------\n\n    W = diag(w);                    % Weight matrix\n    % Loop version of MSE: avoids out of memory errors for large voxel sets\n    MSE = zeros(1,n); for i=1:n, MSE(i) = e(:,i)'*W*e(:,i); end, MSE = MSE/dfe;\n\n    k = size(betas,1);\n    v = repmat(diag(invxwx),1,n) .* repmat(MSE,k,1);\n    %v = invxwx * MSE;       % variances for mean\n\n    % output\n    stats.descrip1 = 'Univariate stats for test against zero:';\n    stats.v = v;\n    stats.v_descrip = 'V = ste^2; variance of mean estimate';\n    stats.t = betas ./ sqrt(v);\n    stats.p = 2 * ( 1 - tcdf(abs(stats.t),dfe) );\n    stats.dfe = dfe;\n\n\n\nelse\n    % ======================================\n    %\n    %\n    % Multivariate stats: MSE, cov(Y), r(Y)\n    % Useful for simulating t-values under dependence\n    %\n    % ======================================\n\n    % --------------------------------------\n    % * Mean squared error\n    % --------------------------------------\n\n    % additional output: covariance matrix for betas and zdiff across time\n    % (columns)\n    % and correlation matrix for betas and zdiff\n    % used in Monte Carlo simulations for controlling false positives\n    % across columns\n\n    MSE = (e'*W*e)/dfe;             % Mean square error\n\n    if dobtwn\n        MSEdiff = (ediff'*W*ediff)/dfediff;\n    end\n\n\n    % --------------------------------------\n    % * Estimated covariance and correlation\n    %   Estimated between-subjects variance (v)\n    % --------------------------------------\n\n    xy = invxwx * MSE;           % Covariance matrix for betas;\n\n    xy = 0.5*(xy+xy');              % Remove rounding error\n\n    if dobtwn\n        xydiff = inv(bcon'*W*bcon)*MSEdiff;           % Covariance matrix for betas;\n        xydiff = 0.5*(xydiff+xydiff');\n    end\n\n    v = diag(xy);                   % Variance for betas\n\n    if dobtwn\n        vdiff = diag(xydiff);\n    end\n\n    r = xy./sqrt(v*v');             % Correlation matrix for betas\n\n    if dobtwn\n        rdiff = xydiff./sqrt(vdiff*vdiff');         % Correlation matrix for betas\n    end\n\n    stats.descrip1 = 'Multivariate stats for test against zero:';\n    stats.r = r;\n    stats.v = v;\n    stats.xy = xy;\n\n    stats.t = betas ./ sqrt(v');\n    stats.p = 2 * ( 1 - tcdf(abs(stats.t),dfe) );\n\nend\n\n\nreturn\n\n\n\n\n\n\n\n\nfunction [dfe,dfediff] = get_dfe(m,n,X,bform,varY,dobtwn,hatdiff,bcon)\n\ndfediff = [];\n\n% Set up residual-forming matrix\n% --------------------------------------\ndfe_v = zeros(n,1);\nR = eye(m) - X*bform;    % residual inducing matrix\n\n% contrast, if entered\nif dobtwn\n    dfe_vdiff = zeros(n,1);\n    Rdiff = eye(m) - bcon * hatdiff;\nend\n\n% Calculate effective degrees of freedom\n% --------------------------------------\n\nhave_unique_vars = size(varY,2) == n;\n\nif ~have_unique_vars\n\n    % Only one (pooled?) vector of variance estimates\n    % --------------------------------------\n    V = diag(varY(:,1));\n    dfe = (trace(R*V)^2)/trace(R*V*R*V);       % Satherwaite approximation\n    if dobtwn, dfediff = (trace(Rdiff*V)^2)/trace(Rdiff*V*Rdiff*V); end\nelse\n    % Variance estimates for each data vector\n    % --------------------------------------\n    for i=1:n,\n\n        % make diagonal matrix of variances\n        V = diag(varY(:,i));\n\n        dfe_v(i) = (trace(R*V)^2)/trace(R*V*R*V);       % Satherwaite approximation\n\n        if dobtwn\n            dfe_vdiff(i) = (trace(Rdiff*V)^2)/trace(Rdiff*V*Rdiff*V);\n        end\n\n    end\n\n    dfe = mean(dfe_v);               % Calculate average df over all columns (pool over data vectors)\n    if dobtwn\n        dfediff = mean(dfe_vdiff);\n    end\n\nend\n\nreturn\n\n\n\n\n\nfunction bool = is_entered(x)\n\nbool = exist('x','var') && ~isempty(x);\n\nreturn\n\n\n%\n%\n% Duplicated in robust_reg_pooled\n%\n%\n\nfunction [betas,invxwx,bform,fits] = get_betas_singleweight(X,Y,w)\n\nW = diag(w);                    % Weight matrix\n\n%X = repmat(1,m,1);              % Design matrix - 1 column of all ones to calculate average\n% and, separately, use bcon if that's entered\n\ninvxwx = inv(X'*W*X);\nbform = invxwx * X'* W;         % beta-forming matrix.  hat = X * bform\n\n% rows are columns of design (X), cols are Y variables\nbetas = bform*Y;\n\nif nargout > 3\n    fits = X * betas;\nend\n\nreturn\n\n\n\nfunction w = bisquare_weight(r,radjust,xrank)\n% r is residuals\n% radjust is adjustment factor: DuMouchel & O'Brien\n% xrank is rank of weighted X matrix (design)\n% w is weights from bisquare function\n% n is number of Y variables to replicate weights over\ntuneconst = 4.685;\n\nr = r .* radjust;\ns = mad_sigma_pooled(r,xrank);\nr = r ./ (s*tuneconst);\nw = (abs(r)<1) .* (1 - r.^2).^2;\nreturn\n\n\nfunction s = mad_sigma_pooled(r,xrank)\n%    Compute std estimate using MAD of residuals from 0\nrsort = sort(abs(r));\nrsort = rsort(xrank:end,:); % eliminate smallest; like reducing df\ns = median(rsort(:)) / 0.6745;\nreturn\n\nfunction str = display_string(str)\nstr = sprintf(str); fprintf(1,'%s',str);\nreturn\n\n\nfunction erase_string(str)\n\nlen = length(str);\nstr2 = repmat('\\b',1,len);\n\nfprintf(1,str2);\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/Statistics_tools/weighted_glmfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5862197380873011}}
{"text": "function [RNew, phi, psi, alphaNew, gammaOld, gammaNew] = ...\n        computeGammaMultipleSinus(...\n        ROld, iOrder, crossCorrelationVectors, a, phi, psi, gammaOld, ...\n        gammaNew, alphaOld, hankelMatrixIsAdded, dcIsIncluded)\n\n    nPitches = length(a);\n    RNew = computeRowsOfToeplitzHankelMatrix(iOrder, iOrder, ...\n        crossCorrelationVectors, hankelMatrixIsAdded, dcIsIncluded);\n    lambda = a-sum(ROld.*phi,1);\n    mu = -sum(ROld.*psi,1);\n    phi = [phi;zeros(1,nPitches)]+(ones(iOrder-1,1)*lambda).*gammaNew;\n    psi = [psi;zeros(1,nPitches)]+(ones(iOrder-1,1)*mu).*gammaNew;\n    alphaNew = sum(RNew(1:end-1,:).*gammaNew,1);\n    b = (ones(iOrder-1,1)*(alphaOld-alphaNew)).*gammaNew+...\n        [zeros(1,nPitches);gammaNew(1:iOrder-2,:)]+...\n        [gammaNew(2:end,:);zeros(1,nPitches)]-...\n        [gammaOld(1:iOrder-2,:);zeros(1,nPitches)]+...\n        (ones(iOrder-1,1)*psi(end,:)).*phi-...\n        (ones(iOrder-1,1)*phi(end,:)).*psi;\n    nu = sum(RNew(1:end-1,:).*b)./gammaNew(end,:);\n    gammaOld = gammaNew;\n    gammaNew = nan(iOrder,nPitches);\n    gammaNew(iOrder,:) = 1./(nu+RNew(iOrder,:));\n    gammaNew(1:iOrder-1,:) = (ones(iOrder-1,1)*...\n        (gammaNew(iOrder,:)./gammaOld(end,:))).*b;\n\nend\n", "meta": {"author": "LimingShi", "repo": "Bayesian-Pitch-Tracking-Using-Harmonic-model", "sha": "ad9a3fcfe60d2e97a635a92c2076ff1978ae3697", "save_path": "github-repos/MATLAB/LimingShi-Bayesian-Pitch-Tracking-Using-Harmonic-model", "path": "github-repos/MATLAB/LimingShi-Bayesian-Pitch-Tracking-Using-Harmonic-model/Bayesian-Pitch-Tracking-Using-Harmonic-model-ad9a3fcfe60d2e97a635a92c2076ff1978ae3697/BF0NLS_MATLAB/private/computeGammaMultipleSinus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5862197301827549}}
{"text": "function varargout = spm_diffeo(varargin)\n% Mex function called for image registration stuff\n%\n%_______________________________________________________________________\n%\n% FORMAT u = spm_diffeo('vel2mom', v, param)\n% v     - velocity (flow) field n1*n2*n3*3.\n% param - 8 parameters (settings)\n%         - [1][2][3] Voxel sizes\n%         - [4][5][6][7][8] Regularisation parameters\n%           - [4] Absolute displacements need to be penalised by a tiny\n%                 amount.  The first element encodes the amount of\n%                 penalty on these.  Ideally, absolute displacements\n%                 should not be penalised, but it is usually necessary\n%                 for technical reasons.\n%           - [5] The `membrane energy' of the deformation is penalised,\n%                 usually by a relatively small amount. This penalises\n%                 the sum of squares of the derivatives of the velocity\n%                 field (ie the sum of squares of the elements of the\n%                 Jacobian tensors).\n%           - [6] The `bending energy' is penalised (3rd element). This\n%                 penalises the sum of squares of the 2nd derivatives of\n%                 the velocity.\n%           - [7][8] Linear elasticity regularisation is also included.\n%                    The first parameter (mu) is similar to that for\n%                    linear elasticity, except it penalises the sum of\n%                    squares of the Jacobian tensors after they have been\n%                    made symmetric (by averaging with the transpose).\n%                    This term essentially penalises length changes,\n%                    without penalising rotations.\n%                    The final term also relates to linear elasticity,\n%                    and is the weight that denotes how much to penalise\n%                    changes to the divergence of the velocities (lambda).\n%                    This divergence is a measure of the rate of volumetric\n%                    expansion or contraction.\n% u       - `momentum' field n1*n2*n3*3.\n%\n% Convert a velocity field to a momentum field by u = A*v, where\n% A is the large sparse matrix encoding some form of regularisation.\n% v and m are single precision floating point.\n%\n%_______________________________________________________________________\n%\n% FORMAT v = spm_diffeo('mom2vel',g, param)\n% v     - the solution n1*n2*n3*3\n% g     - parameterisation of first derivatives\n% param - 10 parameters (settings)\n%         - [1][2][3] Voxel sizes\n%         - [4][5][6][7][8] Regularisation settings (see vel2mom).\n%         - [9] Number of Full Multigrid cycles.\n%         - [10] Number of relaxation iterations per cycle.\n%\n% Solve equations using a Full Multigrid method.  See Press et al\n% for more information.\n% v = inv(A)*g\n% g and v are both single precision floating point.\n%\n%_______________________________________________________________________\n%\n% FORMAT v = spm_diffeo('fmg',H, g, param)\n% v     - the solution n1*n2*n3*3\n% H     - parameterisation of 2nd derivatives \n% g     - parameterisation of first derivatives\n% param - 10 parameters (settings)\n%         - [1][2][3] Voxel sizes\n%         - [4][5][6][7][8] Regularisation settings (see vel2mom).\n%         - [9] Number of Full Multigrid cycles.\n%         - [10] Number of relaxation iterations per cycle.\n%\n% Solve equations using a Full Multigrid method, but using Hessian of\n% the matching term.  See Press et al for more information.\n% v = inv(A+H)*g\n% H, g and v are all single precision floating point.\n%\n%_______________________________________________________________________\n%\n% FORMAT v = spm_diffeo('cgs',H, g, param)\n% v     - the solution\n% H     - parameterisation of 2nd derivatives\n% g     - parameterisation of first derivatives\n% param - 10 parameters (settings)\n%         - [1][2][3] Voxel sizes\n%         - [4][5][6][7][8] Regularisation settings (see vel2mom).\n%         - [9] Tolerance.  Indicates required degree of accuracy.\n%         - [10] Maximum number of iterations.\n%\n% This is for solving a set of equations using a conjugate gradient\n% solver. This method is less efficient than the Full Multigrid, and\n% is included for illustrative purposes.\n% v = inv(A+H)*g\n% H, g and v are all single precision floating point.\n%\n%_______________________________________________________________________\n%\n% FORMAT F = spm_diffeo('kernel',d,prm)\n% d   - image dimensions\n% prm - 8 parameters (settings).\n%       These are described above (for 'vel2mom').\n% F   - The differential operator encoded as an image (or images).\n%       Convolving a velocity field by this will give the momentum.\n%\n%_______________________________________________________________________\n%\n% FORMAT y3 = spm_diffeo('comp',y1,y2)\n% y1, y2 - deformation fields n1*n2*n3*3.\n% y3     - deformation field field n1*n2*n3*3.\n%\n% Composition of two deformations y3 = y1(y2)\n% y1, y2 and y3 are single precision floating point.\n%\n%\n% FORMAT [y3,J3] = spm_diffeo('comp', y1, y2, J1, J2)\n% y1, y2 - deformation fields n1*n2*n3*3.\n% y3     - deformation field n1*n2*n3*3.\n% J1, J2 - Jacobian tensor fields n1*n2*n3*3*3.\n% J3     - Jacobian tensor field n1*n2*n3*3*3.\n%\n% Composition of two deformations, with their Jacobian fields.\n% All fields are single precision floating point.\n%\n%_______________________________________________________________________\n%\n% FORMAT iy = spm_diffeo('invdef',y,d,M1,M2);\n%\n% iy - inverted deformation field of size d(1)*d(2)*d(3)*3.\n% y  - original deformation field.\n% M1 - An affine mapping from mm to voxels in the co-ordinate\n%      system of the inverse deformation field.\n% M2 - An affine mapping from voxels to mm in the co-ordinate\n%      system of the forward deformation field.\n%\n% Inversion of a deformation field.\n%\n% The field is assumed to consist of a piecewise affine transformations,\n% whereby each cube jointing 8 neighbouring voxels contains eight\n% tetrahedra.  The mapping within each tetrahedron is assumed to be\n% affine.\n%\n%  Reference:\n%    J. Ashburner, J. Andersson and K. J. Friston (2000).\n%    \"Image Registration using a Symmetric Prior - in Three-Dimensions\".\n%    Human Brain Mapping 9(4):212-225 (appendix).\n%_______________________________________________________________________\n%\n% FORMAT [f,dfx,dfy,dfz] = spm_diffeo('bsplins', c, y,d)\n% c          - input image(s) of B-spline coefficients n1*n2*n3*n4\n%              - see 'bsplinc'\n% y          - points to sample n1*n2*n3*3\n% d(1:3)     - degree of B-spline (from 0 to 7) along different dimensions\n%              - these must be same as used by 'bsplinc'\n% d(4:6)     - 1/0 to indicate wrapping along the dimensions\n%\n% f           - output image n1*n2*n3*n4\n% dfx,dfy,dfz - sampled first derivatives\n%\n% c, f and y are single precision floating point.\n%\n% This function takes B-spline basis coefficients from spm_bsplinc,\n% and re-convolves them with B-splines centred at the new sample points.\n% \n% Note that nearest neighbour interpolation is used instead of 0th\n% degree B-splines, and the derivatives of trilinear interpolation are\n% returned insted of those of 1st degree B-splines.  The difference is\n% extremely subtle.\n%\n% c, f and y are single precision floating point.\n% \n%  References:\n%    M. Unser, A. Aldroubi and M. Eden.\n%    \"B-Spline Signal Processing: Part I-Theory,\"\n%    IEEE Transactions on Signal Processing 41(2):821-832 (1993).\n% \n%    M. Unser, A. Aldroubi and M. Eden.\n%    \"B-Spline Signal Processing: Part II-Efficient Design and\n%    Applications,\"\n%    IEEE Transactions on Signal Processing 41(2):834-848 (1993).\n% \n%    M. Unser.\n%    \"Splines: A Perfect Fit for Signal and Image Processing,\"\n%    IEEE Signal Processing Magazine, 16(6):22-38 (1999)\n% \n%    P. Thevenaz and T. Blu and M. Unser.\n%    \"Interpolation Revisited\"\n%    IEEE Transactions on Medical Imaging 19(7):739-758 (2000).\n%\n%_______________________________________________________________________\n%\n% FORMAT c = spm_diffeo('bsplinc',f,d)\n%   f - an image\n%   d(1:3) - degree of B-spline (from 0 to 7) along different dimensions\n%       d(4:6) - 1/0 to indicate wrapping along the dimensions\n%   c - returned volume of B-spline coefficients\n%\n% This function deconvolves B-splines from f, returning\n% coefficients, c.  These coefficients are then passed to 'bsplins'\n% in order to sample the data using B-spline interpolation.\n%\n%_______________________________________________________________________\n%\n% FORMAT f2 = spm_diffeo('samp', f1, y)\n% f1 - input image(s) n1*n2*n3*n4\n% y  - points to sample n1*n2*n3*3\n% f2 - output image n1*n2*n3*n4\n%\n% Sample a function according to a deformation using trilinear interp.\n% f2 = f1(y)\n% f1, f2 and y are single precision floating point.\n%\n%_______________________________________________________________________\n%\n% FORMAT f2 = spm_diffeo('push', f1, y)\n% f1 - input image(s) n1*n2*n3*n4\n% y  - points to sample n1*n2*n3*3\n% f2 - output image n1*n2*n3*n4\n%\n% Push values of a function according to a deformation.  Note that the\n% deformation should be the inverse of the one used with 'samp' or 'bsplins'.\n% f1, f2 and y are single precision floating point.\n%\n%_______________________________________________________________________\n%\n% FORMAT f2 = spm_diffeo('pushc', f1, y)\n% f1 - input image(s) n1*n2*n3*n4\n% y  - points to sample n1*n2*n3*3\n% f2 - output image n1*n2*n3*n4\n%\n% Push values of a function according to a deformation, but using\n% circulant boundary conditions.  Data wraps around.\n% f1, f2 and y are single precision floating point.\n%\n%_______________________________________________________________________\n%\n% FORMAT ut = spm_diffeo('pushg', u0, y)\n% u0 - input momentum n1*n2*n3*3\n% y  - points to sample n1*n2*n3*3\n% ut - output momentum n1*n2*n3*3\n%\n% FORMAT ut = spm_diffeo('pushg', u0, y)\n% u0 - input momentum n1*n2*n3*3\n% y  - points to sample n1*n2*n3*3\n% J  - Jacobian tensor field of y n1*n2*n3*3*3\n% ut - output momentum n1*n2*n3*3\n%\n% Push values of a momentum field according to a deformation using\n% circulant boundary conditions.  This essentially computes\n% (Ad_y)^* u = |det dy| (dy)^T u(y), which is a key to the\n% EPdiff equations used for geodesic shooting.\n% u0, ut and y are single precision floating point.\n%\n%_______________________________________________________________________\n%\n% FORMAT f2 = spm_diffeo('resize', f1, dim)\n% f1  - input fields n1*n2*n3*n4\n% f2  - output field dim1*dim2*dim3*n4\n% dim - output dimensions\n%\n% Resize a field according to dimensions dim.  This is a component of\n% the multigrid approach, and is used for prolongation.\n%\n%_______________________________________________________________________\n%\n% FORMAT v2 = spm_diffeo('restrict', v1)\n% v1  - input fields n1*n2*n3*n4\n% v2  - output field dim1*dim2*dim3*n4\n%\n% Restricts a field such that its dimensions are approximately half\n% their original.  This is a component of the multigrid approach.\n%\n%_______________________________________________________________________\n%\n% FORMAT J = spm_diffeo('def2jac',y)\n% y - Deformation field\n% J - Jacobian tensor field of y\n%\n% Compute Jacobian tensors from a deformation.\n%\n%_______________________________________________________________________\n%\n% FORMAT J = spm_diffeo('def2det',y)\n% y - Deformation field\n% j - Jacobian determinant field of y\n%\n% Compute Jacobian determinants from a deformation.\n%\n%_______________________________________________________________________\n%\n% FORMAT j = spm_diffeo('det',J)\n% J - Jacobian tensor field\n% j - Jacobian determinant field\n%\n% Compute determinants of Jacobian tensors.\n%\n%_______________________________________________________________________\n%\n% FORMAT dv = spm_diffeo('div',v)\n% v  - velocity field\n% dv - divergences of velocity field\n%\n% Computes divergence from velocity field.  This is indicative of rates\n% of volumetric expansion/contraction.\n%\n%_______________________________________________________________________\n%\n% FORMAT [y,J] = spm_diffeo('smalldef',v,s)\n% v - velocity field\n% s - scaling factor\n% y - small deformation\n% J - approximate Jacobian tensors of small deformation (computed via\n%     a matrix exponsntial of the Jacobians of the velocity field).\n%\n% This function is used for each time step of geodesic shooting.  It may\n% change in future to use some form of Pade approximation of the\n% small deformation.\n%\n%_______________________________________________________________________\n%\n% FORMAT v3 = spm_diffeo('brc', v1, v2)\n% v1, v2, v3 - flow fields n1*n2*n3*3\n%\n% Lie Bracket.  Useful for many things\n% e.g. Baker-Campbell-Haussdorf series expansion.\n% The Lie bracket is denoted by\n% v3 = [v1,v2]\n% and on scalar fields, is computed by\n% v3 = J1*v2 - J2*v1, where J1 and J2 are the Jacobian\n% tensor fields. For matrices, the Lie bracket is simply\n% [A,B] = A*B-B*A\n%\n%_______________________________________________________________________\n%\n% FORMAT v = spm_diffeo('dartel',v,g,f,param)\n% v     - flow field n1*n2*n3*3 (single precision float)\n% g     - first image n1*n2*n3*n4 (single precision float)\n% f     - second image n1*n2*n3*n4 (single precision float)\n% param - 9 parameters (settings)\n%         - [1] Regularisation type, can take values of\n%           - 0 Linear elasticity\n%           - 1 Membrane energy\n%           - 2 Bending energy\n%         - [2][3][4] Regularisation parameters\n%           - For \"membrane energy\", the parameters are\n%             lambda, unused and id.\n%           - For \"linear elasticity\", the parameters are\n%             mu, lambda, and id\n%           - For \"bending energy\", the parameters are\n%             lambda, id1 and id2, such that regularisation is by\n%             (-lambda*\\grad^2 + id1)^2 + id2\n%         - [5] Levenberg-Marquardt regularisation\n%         - [6] Number of Full Multigrid cycles\n%         - [7] Number of relaxation iterations per cycle\n%         - [8] K, such that 2^K time points are used to\n%               generate the deformations.  A value of zero\n%               indicates a small deformation model.\n%         - [9] code of 0, 1 or 2.\n%               0 - asymmetric sums of squares objective function.\n%               1 -  symmetric sums of squares objective function.\n%               2 - assumes multinomial distribution, where template\n%                   encodes the means and interpolation of template\n%                   done using logs and softmax function.\n%\n% This is for performing a single iteration of the Dartel optimisation.\n% All velocity fields and images are represented by single precision floating\n% point values. Images can be scalar fields, in which case the objective\n% function is the sum of squares difference.  Alternatively, images can be\n% vector fields, in which case the objective function is the sum of squares\n% difference between each scalar field + the sum of squares difference\n% between one minus the sum of the scalar fields.\n%\n%_______________________________________________________________________\n%\n% FORMAT [y,J] = spm_diffeo('Exp', v, param)\n% v - flow field\n% J - Jacobian. Usually a tensor field of Jacobian matrices, but can\n%     be a field of Jacobian determinants.\n% param - 2 (or 3) parameters.\n%         [1] K, the number of recursions (squaring steps), such\n%             that exponentiation is done using an Euler-like\n%             integration with 2^K time steps.\n%         [2] a scaling parameter.\n%         If there is a third parameter, and it is set to 1, then\n%         the J will be the Jacobian determinants.\n%\n% A flow field is \"exponentiated\" to generate a deformation field\n% using a scaling and squaring approach.  See the work of Arsigny\n% et al, or Cleve Moler's \"19 Dubious Ways\" papers.\n%\n%_______________________________________________________________________\n%\n% Note that the boundary conditions are circulant throughout.\n% Interpolation is trilinear, except for the resize function\n% which uses a 2nd degree B-spline (without first deconvolving).\n%\n%_______________________________________________________________________\n% Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_diffeo.m 4890 2012-09-03 15:19:46Z guillaume $\n\n\n%-This is merely the help file for the compiled routine\nerror('spm_diffeo.c not compiled - see Makefile')\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/spm12/spm_diffeo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5862197221903577}}
{"text": "function res = spm_eeg_specest_morlet(S, data, time)\n% Plugin for spm_eeg_tf implementing Morlet wavelet transform\n% FORMAT res = spm_eeg_specest_morlet(S, data, time)\n%\n% S                     - input structure\n% fields of S:\n%    S.subsample   - factor by which to subsample the time axis (default - 1)\n%  either\n%    S.ncycles     - Morlet wavelet factor (default - 7)\n%  or\n%    S.timeres     - Fixed time window length in ms\n%\n%    S.frequencies - vector of frequencies (default - 0-48) at optimal frequency bins\n%                            \n% Output:\n%  res - \n%   If no input is provided the plugin returns a cfg branch for itself\n%\n%   If input is provided:\n%      res.fourier - the complex output of wavelet transform\n%      res.time    - time axis\n%      res.freq    - frequency axis\n%__________________________________________________________________________\n% Copyright (C) 2010-2017 Wellcome Trust Centre for Neuroimaging\n\n% Vladimir Litvak\n% $Id: spm_eeg_specest_morlet.m 7129 2017-07-04 16:24:53Z guillaume $\n\n\n%-This part if for creating a config branch that plugs into spm_cfg_eeg_tf\n% Any parameters can be specified and they are then passed to the plugin\n% when it's called.\n%--------------------------------------------------------------------------\nif nargin == 0\n    subsample         = cfg_entry;\n    subsample.tag     = 'subsample';\n    subsample.name    = 'Subsample';\n    subsample.strtype = 'n';\n    subsample.num     = [1 1];\n    subsample.val     = {1};\n    subsample.help    = {'Set to N to subsample the time axis to every Nth sample (to reduce the dataset size).'};\n    \n    ncycles         = cfg_entry;\n    ncycles.tag     = 'ncycles';\n    ncycles.name    = 'Number of wavelet cycles';\n    ncycles.strtype = 'n';\n    ncycles.num     = [1 1];\n    ncycles.val     = {7};\n    ncycles.help    = {'Number of wavelet cycles (a.k.a. Morlet wavelet factor).',...\n        'This parameter controls the time-frequency trade-off',...\n        'Increasing it increases the frequency resolution at the expense of time resolution.'};\n    \n    timeres         = cfg_entry;\n    timeres.tag     = 'timeres';\n    timeres.name    = 'Fixed time window length';\n    timeres.strtype = 'r';\n    timeres.num     = [1 1];\n    timeres.val     = {0};\n    timeres.help    = {'Fixed time window for all frequencies.',...\n        'Specify time window length in ms.',...\n        'Default valued of 0 specifies variable time window length.'};\n    \n    morlet      = cfg_branch;\n    morlet.tag  = 'morlet';\n    morlet.name = 'Morlet wavelet transform';\n    morlet.val  = {ncycles, timeres, subsample};\n    \n    res = morlet;\n    \n    return;\nend\n\n%-Defaults\n%--------------------------------------------------------------------------\ntry, S.subsample; catch, S.subsample = 1; end\ntry, S.ncycles;   catch, S.ncycles = 7;   end\n\ndt = time(end) - time(1);\nif ~isfield(S, 'frequencies') || isempty(S.frequencies)\n    S.frequencies = (1/dt):max(1/dt, floor(dt)/dt):48;\nend\n\n%-Generate wavelets\n%--------------------------------------------------------------------------\nif ~isfield(S, 'timeres') || S.timeres == 0\n    M = spm_eeg_morlet(S.ncycles, 1000*diff(time(1:2)), S.frequencies);\nelse\n    M = spm_eeg_morlet(S.ncycles, 1000*diff(time(1:2)), S.frequencies, 1000./S.timeres);\nend\n\n%-Data dimensions\n%--------------------------------------------------------------------------\nNchannels    = size(data, 1);\nNsamples     = size(data, 2);\nNfrequencies = numel(M);\n\n%-Initialize output struct\n%--------------------------------------------------------------------------\nres.freq    = S.frequencies;\nres.time    = time(1:S.subsample:end);\nres.fourier = zeros(Nchannels, Nfrequencies, length(res.time));\n\n%-Compute wavelet transform\n%--------------------------------------------------------------------------\nfor j = 1:Nchannels\n    for i = 1:Nfrequencies\n        tmp = conv(data(j, :), M{i});\n        \n        % time shift to remove delay\n        tmp = tmp([1:Nsamples] + (length(M{i})-1)/2);\n        \n        tmp = tmp(1:S.subsample:end);\n        \n        res.fourier(j, i, :) = tmp;\n    end\nend\n\n%% The following is often faster but requires more memory\n%for i = 1:Nfrequencies\n%    H = spm_convmtx(M{i}',Nsamples); % faster than conv for large Nchannels\n%    tmp = data * H';\n%    % subsample and time shift to remove delay\n%    tmp = tmp(:,(1:S.subsample:Nsamples) + (length(M{i})-1)/2);\n%    res.fourier(:,i,:) = tmp;\n%end\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_eeg_specest_morlet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5862197182820098}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Reconstruction of N-th order nonuniformly sampled bandlimited signals\n% using digital filter banks\n% Authors: S. K. Sindhi, K. M. M. Prabhu\n%%%%%%%%%%%%%%%%%%%%%%%  with Knab window   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% LF=13;w_c=0.85; BETA=4 Proposed/Prendergast and BETA=3 ITAMI gives best %\n%%%%%%%%%%%%%%%%%%%%%%%  with kaiser_mine1  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% LF=13;w_c=0.85; BETA=3 Proposed/Prendergast and BETA=3 ITAMI gives best %\n\n% clear all;\n% close all;\n% clc;\n\ndisplay('Nth (2) order Reconstruction');\n\nN = 2;                  % Nth order nonuniform sampling\nTQ = 1;Fs = 1/TQ;                 % Nyquist Period    \n\nT = [1.5*TQ 3*TQ];      % Decimation Periods\nK = 0.5*lcm(2*T(1), 2*T(2))/TQ; % number of samples in recurrent period\ncapT = K*TQ; % the full sampling period - of all samplers\nM = capT./T;\nML = 400; % number of slices\nw_c = 0.85;\nNS = 100;  % Number of Sinusoids\n\nLF = lcm(M(1),M(2))*2*K+1;      % length of LF should be Multiple of LCM{M(p)}*2*K\nn = -(LF-1)/2:1:(LF-1)/2;\nHd = firpm(LF-1,[0 w_c],[0 w_c*pi],'differentiator');\ndelayV = (LF-1)/2;\n\nk = -(K-1):1:(K-1);\nm = (0:1:(2*K-1))';\nF = exp(1i*(pi/K).*kron(m,k));\nstd = [1e-6 1e-5 1e-4 1e-3 1e-2 1e-1];%5*1e-1];\n\nserP = zeros(size(std));\nserE = zeros(size(std));\nserI = zeros(size(std));\nserV = zeros(size(std));\nserPr = zeros(size(std));\nserJ = zeros(size(std));\nserNO = zeros(size(std));\n\nMCruns = 25;\nMCruns1 = 25;\n\nfor tt = 1:length(std)\naa = 0;\ndisplay(tt);\nfor rrr = 1:MCruns1\ntaus = [0 1+std(tt)*randn]*TQ;    \nif or(taus(2)==1.5*TQ,taus(1)==taus(2))\n    aa = aa+1;\n    continue;\nend\ntausI = sort([taus(1) taus(2) T(1)+taus(1)]);\ntauI = zeros(K,ML);\nfor p = 1:K\n    tauI(p,:) = tausI(p)+(0:ML-1)*capT;\nend;\na = zeros(1,K);\nfor p = 1:K\n    a(p) = 1;\n    for q = 1:K\n        if q ~= p\n                a(p) = a(p)/sin(pi*(tausI(p)-tausI(q))/capT);\n        end;\n    end;\nend;\n% c = sin(pi*(tausI(0+1))/capT);\n% s = cos(pi*(tausI(0+1))/capT);\n% b(1,1) = 0.5*(c+1i*s);\n% c = sin(pi*(tausI(1+1))/capT);\n% s = cos(pi*(tausI(1+1))/capT);\n% b(1,2) = 0.5*(c+1i*s);\n% b(3,:) = conj(b(1,:));\n% b(2,:) = 0;\n\nb = zeros(2*K-1,K);\nc = -0.5*cos(pi*(tausI(1+1)+tausI(2+1))/capT);\ns = -0.5*sin(pi*(tausI(1+1)+tausI(2+1))/capT);\nb(1,1) = 0.5*(c+1i*s);\nc = -0.5*cos(pi*(tausI(0+1)+tausI(2+1))/capT);\ns = -0.5*sin(pi*(tausI(0+1)+tausI(2+1))/capT);\nb(1,2) = 0.5*(c+1i*s);\nc = -0.5*cos(pi*(tausI(0+1)+tausI(1+1))/capT);\ns = -0.5*sin(pi*(tausI(0+1)+tausI(1+1))/capT);\nb(1,3) = 0.5*(c+1i*s);\nb(5,:) = conj(b(1,:));\nb(2,:) = 0;\nb(4,:) = conj(b(2,:));\nc = 0.5*cos(pi*(tausI(2+1)-tausI(1+1))/capT);\nb(3,1) = c;\nc = 0.5*cos(pi*(tausI(2+1)-tausI(0+1))/capT);\nb(3,2) = c;\nc = 0.5*cos(pi*(tausI(1+1)-tausI(0+1))/capT);\nb(3,3) = c;\n\nr = tausI-TQ*(0:K-1);\nrr = r(mod((0:ML*K-1),K)+1);\n\ntauPr = zeros(K,ML);\nfor p = 1:K\n    tauPr(p,:) = -tausI(p)+(0:ML-1)*capT;\nend;\nH = zeros(K,LF);\nfor i=1:K\n%     H(i,:) = sinc(n-tausI(i)).*conv(sinc(n-tausI(i)),kaiser(LF,10).','same');\n%     H(i,:) = sinc(n-tausI(i)).*knab(LF,3,-tausI(i)).';\n    H(i,:) = sinc(n-tausI(i)).*kaiser_mine1(LF,3,-tausI(i));\nend;\nH = H(:,1:end-1);\nEP = reshape(H.',K,length(H(1,:))/K,K);\ncapE = [];\nfor k=1:K\n    temp = [];\n    for i=1:K\n        temp=[temp,toeplitz([EP(i,1,k),zeros(1,(length(H(1,:))/K)-1)],[EP(i,:,k),zeros(1,(length(H(1,:))/K)-1)])];\n    end\n    capE = [capE;temp];\nend\nd = ceil(size(capE,2)/(2*K));\nP = kron(eye(K),[zeros(1,d),1,zeros(1,(size(capE,2)/K)-d-1)]);\nR = P/capE;\n% size(capE) \n% size(zeros(LF-1,2*LF-2-K))\n% size(R)\n% size(zeros(K,LF-1))\n% size(P)\n% size(zeros(K,2*LF-2-K))\nR = upsample(R.',K).';\nrt = size(R,2)/K;\nFR = zeros(K,rt);\nfor j=1:K\n    for i=1:K\n        temp = filter([zeros(1,K-i),1],1,R(i,(j-1)*rt+1:j*rt));\n        FR(j,:) = FR(j,:)+temp;\n    end\nend\n\nr = r.';\nw_o = w_c*pi*TQ;\nhJ = zeros(K,LF);\nC = zeros(1,LF);\nNt = (LF-1)/2;\nfor i = 1:K\n    C = -2*sin(w_o*(n-r(1+(mod(i-1-n,K)))'))./(pi*(n-r(1+(mod(i-1-n,K)))'));\n    C(isnan(C)==1)=-2*w_o/pi;\n    C = C.';\n    S = zeros(LF,LF);\n    for k = 1:LF\n        S(k,:) = sin(w_o*(-Nt+k-1-r(1+(mod(i-1-(-Nt+k-1),K)))-(n-r(1+(mod(i-1-n,K)))')))./(pi*(-Nt+k-1-r(1+(mod(i-1-(-Nt+k-1),K)))-(n-r(1+(mod(i-1-n,K)))')));\n    end;\n    S(isnan(S)==1)=w_o/pi;\n    hJ(i,:) = -0.5*S\\C;\nend;\n\nfor pp = 1:MCruns;\nFrq = rand(1,NS)*w_c/2;\nAmp = rand(1,NS)/(sqrt(NS)*2);\nPhi = rand(1,NS)*2*pi;\ninput = zeros(1,ML*K);\nfor k = 1:NS\n  input = input + Amp(k)*sin(2*pi*Frq(k)*(0:ML*K-1)*TQ+Phi(k));\nend;\nxp = zeros(N,ML*K);\nfor p = 1:N\n    tau = taus(p)+(0:ML*M(p)-1)*T(p);\n    x1 = zeros(1,ML*M(p));\n    for k = 1:NS\n        x1 = x1 + Amp(k)*sin(2*pi*Frq(k)*tau+Phi(k));\n    end;\n    \n    m = (0:1:M(p)-1)'; lemda = 0:1:M(p)-1;\n    W = exp(1i*(2*pi/M(p)).*kron(m,lemda)); % m*lemda\n    \n    bb = zeros(2*(K-M(p))+1,M(p));\n    aaa = ones(1,M(p));\n    for l = 1:M(p)\n        for q = 1:N\n            if q ~= p\n                    aaa(l) = aaa(l)/sin(pi*M(q)*(taus(p)-taus(q)+(l-1)*T(p))/capT);\n                    c = sin(pi*M(q)*(-taus(q)+(l-1)*T(p))/capT);\n                    s = cos(pi*M(q)*(taus(q)-(l-1)*T(p))/capT);\n                    bb(2*M(q)+1,l) = 0.5*(c-1i*s);\n                    bb(1,l) = conj(bb(2*M(q)+1,l));                        \n            end;\n        end;\n    end;\n    A = diag(aaa); % display(A);\n    B = bb; % display(B);\n\n    y1 = upsample(x1,K);\n    y1 = reshape(y1,M(p),length(y1)/M(p));\n\n    if M(p)>1\n        y1(2:end,:) = flipud(y1(2:end,:));\n        for i = 1:M(p)-1\n            y1(i+1,:) = filter([0,1],1,y1(i+1,:));\n        end;\n    end;\n\n    dim = K-M(p); w = -dim:1:dim;\n\n    xlemda = zeros(M(p),size(y1,2));\n    for lemda = 0:M(p)-1\n\n        rP = (lemda/M(p))+(0:1:(2*K-1))';\n        Fshift = exp(1i*(pi/K).*kron(rP,w));   % r*w\n\n%         h = sinc((n*TQ/T(p))+(lemda/K)-(taus(p)/T(p))).*conv(sinc((lemda/M(p))-(taus(p)/TQ)), kaiser(LF,3),'same');\n        h = sinc((n*TQ/T(p))+(lemda/K)-(taus(p)/T(p))).*kaiser_mine1(LF,3,(lemda/M(p))-(taus(p)/TQ));\n%        h = sinc((n*TQ/T(p))+(lemda/K)-(taus(p)/T(p))).*knab(LF,3,(lemda/M(p))-(taus(p)/TQ)).';\n        y2 = Fshift*B*A*W*W(:,lemda+1)*y1(lemda+1,:);\n        for i=1:2*K\n            h1 = upsample(downsample(h,2*K,i-1),2*K);\n            y2(i,:) = filter(h1,1,y2(i,:));\n            y2(i,:) = filter([zeros(1,i-1),1],1,y2(i,:));%,zeros(1,2*K-i)\n        end;\n        xlemda(lemda+1,:) = sum(y2,1);\n    end;\n    xp(p,:) = sum(xlemda,1)/M(p);\n    clear bb;\nend;\ny = real(sum(xp,1));\ndelayP = (length(h)-1)/2;\ny = y(1+delayP:end);\nx = input(1:end-delayP);\ny = y(160:end-60);\nx = x(160:end-60);\nserP(tt) = serP(tt)+20*log10(norm(x,2)/norm(y-x,2));\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% % Filterbank Reconstruction of Bandlimited Signals from Nonuniform and\n% % Generalized Samples \n% % Authors: Y C Eldar and A V Oppenheim\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ny = zeros(N,ML*K);\nfor p = 1:N\n    tau = taus(p)+(0:ML*M(p)-1)*T(p);\n    x1 = zeros(1,ML*M(p));\n    for k = 1:NS\n        x1 = x1 + Amp(k)*sin(2*pi*Frq(k)*tau+Phi(k));\n    end;\n    y1 = upsample(x1,K);\n    \n    LFE = M(p)*lcm(M(1),M(2))*2*K+1;      % length of LF should be Multiple of LCM{M(p)}*2*K\n    nE = -(LFE-1)/2:1:(LFE-1)/2;\n    h = sinc((nE/K)-(taus(p)/T(p))).*kaiser_mine1(LFE,3,-K*(taus(p)/T(p)));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Implementation 1 %%%%%%%%%%%%%%%%%%%%%%%%%%%\n%     bb = zeros(2*(K-M(p))+1,M(p));\n%     aaa = ones(1,M(p));\n%     for l = 1:M(p)\n%         for q = 1:N\n%             if q ~= p\n%                 aaa(l) = aaa(l)/sin(pi*(taus(p)-taus(q)+(l-1)*T(p))/T(q));\n%                 c = sin(pi*M(q)*(-taus(q)+(l-1)*T(p))/capT);\n%                 s = cos(pi*M(q)*(taus(q)-(l-1)*T(p))/capT);\n%                 bb(2*M(q)+1,l) = 0.5*(c-1i*s);\n%                 bb(1,l) = conj(bb(2*M(q)+1,l));\n%             end;\n%         end;\n%     end;\n%     AE = diag(aaa);\n%     BE = bb.';\n%     \n%     dim = K-M(p); w = -dim:1:dim;\n%     FE = exp(1i*(pi/(K*M(p))).*kron(nE,w'));\n% \n%     E1E = exp(1i*(2*pi/M(p)).*kron((0:M(p)-1),(0:M(p)-1)'))/M(p);\n% \n%     E2E = exp(1i*(2*pi/M(p)).*kron(nE,(0:M(p)-1)'));\n% \n%     temp = E1E*AE*BE*FE;\n%     bbn = h.*sum(E2E.*temp,1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Implementation 2 %%%%%%%%%%%%%%%%%%%%%%%%%%%\n%     bb = zeros(2*(K-M(p))+1,M(p));\n%     aaa = ones(1,M(p));\n%     bbvl = zeros(M(p),LFE);\n%     for l = 1:M(p)\n%         for q = 1:N\n%             if q ~= p\n%                 aaa(l) = aaa(l)*sin(pi*(taus(p)-taus(q)+(l-1)*T(p))/T(q));\n%                 c = sin(pi*M(q)*(-taus(q)+(l-1)*T(p))/capT);\n%                 s = cos(pi*M(q)*(taus(q)-(l-1)*T(p))/capT);\n%                 bb(2*M(q)+1,l) = 0.5*(c-1i*s);\n%                 bb(1,l) = conj(bb(2*M(q)+1,l));\n%             end;\n%         end;\n%         bbv = zeros(2*(K-M(p))+1,LFE);\n%         for v = -(K-M(p)):K-M(p)\n%             bbv(K-M(p)+1+v,:) = bb(K-M(p)+1+v,l)*exp(1i*(pi/(K*M(p)))*v*nE);\n%         end;\n%         bbvl(l,:) = sum(bbv,1)/aaa(l);\n%     end;\n% \n%     bbb = zeros(M(p),LFE);\n%     bbn = zeros(M(p),LFE);\n%     for m = 1:M(p)\n%         for l = 1:M(p)\n%             bbb(l,:) = bbvl(l,:)*exp(1i*(2*pi/M(p))*(m-1)*(l-1));\n%         end\n%         bbb = sum(bbb,1);\n%         bbn(m,:) = bbb.*exp(1i*(2*pi/M(p))*(m-1)*nE);\n%     end;\n%     bbn = sum(bbn,1);\n%     bbn = bbn.*h/M(p);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Implementation 3 %%%%%%%%%%%%%%%%%%%%%%%%%%%\n    aaa = ones(1,M(p));\n    bb = ones(M(p),LFE);\n    for l = 1:M(p)\n        for q = 1:N\n            if q ~= p\n                aaa(l) = aaa(l)*sin(pi*(taus(p)-taus(q)+(l-1)*T(p))/T(q));\n                bb(l,:) = bb(l,:).*sin(pi*((nE*TQ/M(p))-taus(q)+(l-1)*T(p))/T(q));\n            end;\n        end;\n        bb(l,:) = bb(l,:)/aaa(l);\n    end;\n\n    bbb = zeros(M(p),LFE);\n    bbn = zeros(M(p),LFE);\n    for m = 1:M(p)\n        for l = 1:M(p)\n            bbb(l,:) = bb(l,:)*exp(1i*(2*pi/M(p))*(m-1)*(l-1));\n        end\n        bbb = sum(bbb,1);\n        bbn(m,:) = bbb.*exp(1i*(2*pi/M(p))*(m-1)*nE);\n    end;\n    bbn = sum(bbn,1);\n    bbn = bbn.*h/M(p);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    y1 = conv(y1,bbn);\n    delay = (length(h)-1)/2;\n    y(p,:) = y1(1+delay:M(p):end-delay);\nend;\ny = sum(real(y),1);\nx = input;\ny = y(160:end-60);\nx = x(160:end-60);\nserE(tt) = serE(tt)+20*log10(norm(x,2)/norm(y-x,2));\n\n% % figure();\n% subplot(2,1,1);\n% plot(([x' y']));\n% title('input / output signals');\n% xlabel('sample');\n% ylabel('signal value');\n% grid on;\n% subplot(2,1,2);\n% plot((x'-y'));\n% xlabel('time (sample)');\n% ylabel('error value');\n% grid on;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% A realization of Digital Filter Banks for Reconstruction of Uniformly\n% sampled signals from nonuniform samples\n% Authors: Itami, Watanabe, Nishihara\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nx11 = zeros(K,ML);\nfor k = 1:NS\n    x11 = x11 + Amp(k)*sin(2*pi*Frq(k)*tauI+Phi(k));\nend;\ny1=upsample(x11.',K).';\n\ny = zeros(K,size(y1,2));\nfor r = 1:K\n    y2 = F*b(:,r)*a(r)*y1(r,:);\n%     h = sinc((n/K)-tausI(r)/capT).*conv(sinc(-tausI(r)/TQ), kaiser(LF,3),'same');\n    h = sinc((n/K)-tausI(r)/capT).*kaiser_mine1(LF,3,-tausI(r)/TQ);\n%     h = sinc((n/K)-tausI(r)/capT).*knab(LF,3,-tausI(r)/TQ).';\n    for i=1:2*K\n            h1 = upsample(downsample(h,2*K,i-1),2*K);\n            y2(i,:) = filter(h1,1,y2(i,:));\n            y2(i,:) = filter([zeros(1,i-1),1],1,y2(i,:));%,zeros(1,2*K-i)\n    end;\n    y(r,:) = sum(y2,1);\nend;\ny = (sum(y,1));\ndelayI = (length(n)-1)/2;\nx=input(1:end-delayI);\ny=y(1+delayI:end);\ny = y(160:end-60);\nx = x(160:end-60);\nserI(tt) = serI(tt)+20*log10(norm(x,2)/norm(y-x,2));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Without any reconstruction, the SNR value calculation\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwo_reconst = reshape(x11,1,[]);\nserNO(tt) = serNO(tt)+20*log10(norm(input(160:end-60),2)/...\n            norm(wo_reconst(160:end-60)-input(160:end-60),2));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Reconstruction of Nonuniformly Sampled Band-Limited Signals\n% Using a Differentiator-Multiplier Cascade\n% Authors: Stefan Tertinek and Christian Vogel\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nx1 = reshape(x11,1,K*size(x1,2));\n% x1 = x11;% LF = (0:11); Fs = 1;\n% Differentiator Design\n% figure();\n% NFFT = 2^nextpow2(length(Hd)); % Next power of 2 from length of Hd\n% HD = fftshift(fft(Hd,NFFT))/length(Hd);\n% f = Fs*linspace(-1,1,NFFT);\n% % Plot double-sided amplitude spectrum.\n% plot(f,2*abs(HD(1:NFFT))) \n% title('Double-Sided Amplitude Spectrum of Hd(n)')\n% xlabel('Frequency (Hz)')\n% ylabel('|HD(f)|')\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ny1 = filter(Hd,1,x1);\nx1 = filter([zeros(1,delayV),1],1,x1);\nr2 = filter([zeros(1,delayV),1],1,rr);\ne = y1.*r2;\ny1 = x1-e;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ny2 = filter(Hd,1,y1);\ntemp = filter([zeros(1,delayV),1],1,y2);\nx1 = filter([zeros(1,2*delayV),1],1,x1);\nr2 = filter([zeros(1,2*delayV),1],1,r2);\ne1 = temp.*r2;\ny2 = filter(Hd,1,y2);\ne2 = 0.5*y2.*r2.^2;\ny2 = x1-e1-e2;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ny3 = filter(Hd,1,y2);\ntemp = filter([zeros(1,2*delayV),1],1,y3);\nx1 = filter([zeros(1,3*delayV),1],1,x1);\nr2 = filter([zeros(1,3*delayV),1],1,r2);\ne1 = temp.*r2;\ny3 = filter(Hd,1,y3);\ntemp = filter([zeros(1,delayV),1],1,y3);\ne2 = 0.5*temp.*r2.^2;\ny3 = filter(Hd,1,y3);\ne3 = (y3.*r2.^3)/6;\ny3 = x1-e1-e2-e3;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ny = real(y3(1+6*delayV:end));\nx = input(1:end-6*delayV);\ny = y(160:end-60);\nx = x(160:end-60);\nserV(tt) = serV(tt)+20*log10(norm(x,2)/norm(y-x,2));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Reconstruction of Band-Limited Periodic Nonuniformly Sampled Signals \n% Through Multirate Filter Banks\n% Ryan S Prendergast, Bernard C Levy, Paul J Hurst\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nx1 = zeros(K,ML);\nfor k = 1:NS\n    x1 = x1 + Amp(k)*sin(2*pi*Frq(k)*tauPr+Phi(k));\nend;\n\nyb = upsample(x1.',K).';\nfor i = 1:K\n    yb(i,:) = filter(FR(i,:),1,yb(i,:));\nend;\ny = sum(yb,1);\ndelayPr = (size(FR,2))/2+K-1;\nx=input(1:end-delayPr);\ny=y(1+delayPr:end);\ny = y(160:end-60);\nx = x(160:end-60);\nserPr(tt) = serPr(tt)+20*log10(norm(x,2)/norm(y-x,2));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Reconstruction of Periodically Nonuniformly Sampled Bandlimited Signals\n% Using Time-Varying FIR Filters\n% Authors: H. Johansson and Per Lowenborg\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nx1 = reshape(x11,1,size(x11,2)*K);\ny1 = zeros(K,length(x1));\nfor j=1:K\n    y1(j,:) = filter(hJ(j,:),1,x1);\n    y1(j,:) = upsample(downsample(y1(j,:),K,j-1),K)/K;\n    y1(j,:) = filter([zeros(1,j-1),1],1,y1(j,:));\nend;\ny = K*0.25*sum(y1,1);\ndelayJ = (size(hJ,2)-1)/2;\ny = real(y(1+delayJ:end));\nx = input(1:end-delayJ);\ny = y(160:end-60);\nx = x(160:end-60);\nserJ(tt) = serJ(tt)+20*log10(norm(x,2)/norm(y-x,2));\nend\nend\nend\nserP = serP/(MCruns*(MCruns1-aa));\nserE = serE/(MCruns*(MCruns1-aa));\nserI = serI/(MCruns*(MCruns1-aa));\nserV = serV/(MCruns*(MCruns1-aa));\nserPr = serPr/(MCruns*(MCruns1-aa));\nserJ = serJ/(MCruns*(MCruns1-aa));\nserNO = serNO/(MCruns*(MCruns1-aa));\n\nfigure();hold all;\n% plot(std,serJ,'kp-','LineWidth',2);\n% plot(std,serPr,'ko-','LineWidth',2);\n% plot(std,serV,'ks-','LineWidth',2);\n% plot(std,serP,'kd-','LineWidth',2);\n% plot(std,serI,'k>-','LineWidth',2);\n% plot(std,serE,'k+-','LineWidth',2);\n% plot(std,serNO,'k+-','LineWidth',2);\nplot(std,serJ);\nplot(std,serPr);\nplot(std,serV);\nplot(std,serP);\nplot(std,serI);\nplot(std,serE);\nplot(std,serNO);\n% legend('Johansson','Prendergast','Tertinek','Proposed','Itami','Eldar');\nlegend('Johansson','Prendergast','Tertinek','Proposed','Itami','Eldar', 'W/O Reconst');\nxlabel('Standard Deviation (\\sigma)','fontsize',14,'fontweight','b');\nylabel('SNR in dB','fontsize',14,'fontweight','b');\ngrid on;box on;\nset(gca,'fontsize',14,'fontweight','b')\n\n% display('Proposed Method');\n% display(sprintf('Delay imposed due to reconstruction system = %d', delayP));\n% display(sprintf('Length of prototype filter = %d\\n', length(n)));\n% \n% display('Itami Method');\n% display(sprintf('Delay imposed due to reconstruction system = %d', delayI));\n% display(sprintf('Length of prototype filter = %d', length(n)));\n% display(sprintf('Length of fractional delay filter = %d\\n', length(n)));\n% \n% display('Vogel Method');\n% display(sprintf('Delay imposed due to reconstruction system = %d', 6*delayV));\n% display(sprintf('Length of differentiator = %d\\n', LF));\n% \n% display('Prendergast Method');\n% display(sprintf('Delay imposed due to reconstruction system = %d', delayPr));\n% display(sprintf('Length of prototype filter = %d', size(FR,2)));\n% display(sprintf('Length of fractional delay filter = %d\\n', length(n)));\n% \n% display('Johansson Method');\n% display(sprintf('Delay imposed due to reconstruction system = %d', delayJ));\n% display(sprintf('Length of prototype filter = %d\\n', size(h,2)));\n\n% figure();\n% subplot(2,1,1);\n% plot(([x' y']));\n% title('input / output signals');\n% xlabel('sample');\n% ylabel('signal value');\n% grid on;\n% subplot(2,1,2);\n% plot((x'-y'));\n% xlabel('time (sample)');\n% ylabel('error value');\n% grid on;", "meta": {"author": "yueyuzhao", "repo": "gyrophone", "sha": "aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e", "save_path": "github-repos/MATLAB/yueyuzhao-gyrophone", "path": "github-repos/MATLAB/yueyuzhao-gyrophone/gyrophone-aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e/SindhiPrabhu/N2_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5861853029608144}}
{"text": "function [BCMatrix, BCRHS] = boundaryConditionCylindrical3D(BC)\n% It creates the matrix of coefficient based on the BC structureprovided\n% by the user. It also generates the right hand side vector of the linear\n% system of equations\n%\n% SYNOPSIS:\n%       [BCMatrix, BCRHS] = boundaryConditionCylindrical3D(BC)\n%\n% PARAMETERS:\n%\n%\n% RETURNS:\n%\n%\n% EXAMPLE:\n%\n% SEE ALSO:\n%\n\n% Note: I use a for loop here fr more readability of the code!\n\n% extract data from the mesh structure\nNxyz = BC.domain.dims;\nNx = Nxyz(1); Ntetta = Nxyz(2); Nz = Nxyz(3);\nG=reshape(1:(Nx+2)*(Ntetta+2)*(Nz+2), Nx+2, Ntetta+2, Nz+2);\ndx_1 = BC.domain.cellsize.x(1);\ndx_end = BC.domain.cellsize.x(end);\ndtetta_1 = BC.domain.cellsize.y(1);\ndtetta_end = BC.domain.cellsize.y(end);\ndz_1 = BC.domain.cellsize.z(1);\ndz_end = BC.domain.cellsize.z(end);\nrp = repmat(BC.domain.cellcenters.x, 1, Nz);\n\n% number of boundary nodes (axact number is 2[(m+1)(n+1)*(n+1)*(p+1)+(m+1)*p+1]:\nnb = 8*((Nx+1)*(Ntetta+1)+(Nx+1)*(Nz+1)+(Ntetta+1)*(Nz+1));\n\n% define the vectors to be used for the creation of the sparse matrix\nii = zeros(nb,1);\njj = zeros(nb,1);\ns = zeros(nb,1);\n\n% define the RHS column vector\nBCRHS = zeros((Nx+2)*(Ntetta+2)*(Nz+2), 1);\n\n% assign value to the corner nodes (useless cells)\nq = 1:8;\nii(q) = BC.domain.corners; jj(q) = BC.domain.corners;\ns(q) = 1; BCRHS(BC.domain.corners) = 0;\n\n% assign values to the edges (useless cells)\nq = q(end)+(1:length(BC.domain.edges));\nii(q) = BC.domain.edges; jj(q) = BC.domain.edges;\ns(q) = 1; BCRHS(BC.domain.edges) = 0;\n\n% Assign values to the boundary condition matrix and the RHS vector based\n% on the BC structure\nif (BC.top.periodic ==0) && (BC.bottom.periodic == 0)\n    % top boundary\n    j=Ntetta+2;\n    i=2:Nx+1;\n    k=2:Nz+1;\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k);  s(q) = BC.top.b/2 + BC.top.a./(dtetta_end*rp);\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j-1,k); s(q) = BC.top.b/2 - BC.top.a./(dtetta_end*rp);\n    BCRHS(G(i,j,k)) = BC.top.c;\n\n    % Bottom boundary\n    j=1;\n    i=2:Nx+1;\n    k=2:Nz+1;\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j+1,k);  s(q) = -(BC.bottom.b/2 + BC.bottom.a./(dtetta_1*rp)); % consider the reverse direction of normal\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k); s(q) = -(BC.bottom.b/2 - BC.bottom.a./(dtetta_1*rp)); % consider the reverse direction of normal\n    BCRHS(G(i,j,k)) = -(BC.bottom.c);\nelseif (BC.top.periodic ==1) || (BC.bottom.periodic == 1) % periodic\n    % top boundary\n    j=Ntetta+2;\n    i=2:Nx+1;\n    k=2:Nz+1;\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k);  s(q) = 1;\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j-1,k);  s(q) = -1;\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,1,k); s(q) = dtetta_end/dtetta_1;\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,2,k); s(q) = -dtetta_end/dtetta_1;\n    BCRHS(G(i,j,k)) = 0;\n\n    % Bottom boundary\n    j=1;\n    i=2:Nx+1;\n    k=2:Nz+1;\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k);  s(q) = 1;\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j+1,k);  s(q) = 1;\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,Ntetta+1,k); s(q) = -1;\n    q = q(end)+(1:Nx*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,Ntetta+2,k); s(q) = -1;\n    BCRHS(G(i,j,k)) = 0;\nend\n\nif (BC.right.periodic == 0) && (BC.left.periodic == 0)\n    % Right boundary\n    i=Nx+2;\n    j=2:Ntetta+1;\n    k=2:Nz+1;\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k);  s(q) = BC.right.b/2 + BC.right.a/dx_end;\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i-1,j,k); s(q) = BC.right.b/2 - BC.right.a/dx_end;\n    BCRHS(G(i,j,k)) = BC.right.c;\n\n    % Left boundary\n    i = 1;\n    j=2:Ntetta+1;\n    k=2:Nz+1;\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i+1,j,k);  s(q) = -(BC.left.b/2 + BC.left.a/dx_1); % consider the reverse direction of normal\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k); s(q) = -(BC.left.b/2 - BC.left.a/dx_1); % consider the reverse direction of normal\n    BCRHS(G(i,j,k)) = -(BC.left.c);\nelseif (BC.right.periodic == 1) || (BC.left.periodic == 1) % periodic\n    % Right boundary\n    i=Nx+2;\n    j=2:Ntetta+1;\n    k=2:Nz+1;\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k);  s(q) = 1;\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i-1,j,k);  s(q) = -1;\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(1,j,k); s(q) = dx_end/dx_1;\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(2,j,k); s(q) = -dx_end/dx_1;\n    BCRHS(G(i,j,k)) = 0;\n\n    % Left boundary\n    i = 1;\n    j=2:Ntetta+1;\n    k=2:Nz+1;\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k);  s(q) = 1;\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(i+1,j,k);  s(q) = 1;\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(Nx+1,j,k); s(q) = -1;\n    q = q(end)+(1:Ntetta*Nz);\n    ii(q) = G(i,j,k);  jj(q) = G(Nx+2,j,k); s(q) = -1;\n    BCRHS(G(i,j,k)) = 0;\nend\n\nif (BC.front.periodic == 0) && (BC.back.periodic == 0)\n    % Front boundary\n    k=Nz+2;\n    i = 2:Nx+1;\n    j=2:Ntetta+1;\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k);  s(q) = BC.front.b/2 + BC.front.a/dz_end;\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k-1); s(q) = BC.front.b/2 - BC.front.a/dz_end;\n    BCRHS(G(i,j,k)) = BC.front.c;\n\n    % Back boundary\n    k=1;\n    i = 2:Nx+1;\n    j=2:Ntetta+1;\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k+1);  s(q) = -(BC.back.b/2 + BC.back.a/dz_1); % consider the reverse direction of normal\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k); s(q) = -(BC.back.b/2 - BC.back.a/dz_1); % consider the reverse direction of normal\n    BCRHS(G(i,j,k)) = -(BC.back.c);\nelseif (BC.front.periodic == 1) || (BC.back.periodic == 1) % periodic\n    % Front boundary\n    k=Nz+2;\n    i = 2:Nx+1;\n    j=2:Ntetta+1;\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k);  s(q) = 1;\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k-1);  s(q) = -1;\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,1); s(q) = dz_end/dz_1;\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,2); s(q) = -dz_end/dz_1;\n    BCRHS(G(i,j,k)) = 0;\n\n    % Back boundary\n    k=1;\n    i = 2:Nx+1;\n    j=2:Ntetta+1;\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k);  s(q) = 1;\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,k+1);  s(q) = 1;\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,Nz+1); s(q) = -1;\n    q = q(end)+(1:Nx*Ntetta);\n    ii(q) = G(i,j,k);  jj(q) = G(i,j,Nz+2); s(q) = -1;\n    BCRHS(G(i,j,k)) = 0;\nend\n\n% Build the sparse matrix of the boundary conditions\nBCMatrix = sparse(ii(1:q(end)), jj(1:q(end)), s(1:q(end)), ...\n    (Nx+2)*(Ntetta+2)*(Nz+2), (Nx+2)*(Ntetta+2)*(Nz+2));\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Boundary/boundaryConditionCylindrical3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5861849487142019}}
{"text": "function D = spm_mrdivide(A, B)\n% Regularised variant of mrdivide(A, B) or A / B, similar to B * spm_inv(A)\n% FORMAT D = spm_mrdivide(A, B)\n%\n% D = B * inv(A), or if A is near singular D = B * inv(A + TOL*eye(size(A))\n% \n% where TOL is adaptively increased if necessary.\n%\n% This function should be preferable to B * spm_inv(A) if A is large and\n% sparse or if B has few rows, since the inverse need not be explicitly\n% computed (the linear system can be solved with the backslash operator).\n%\n% See also: spm_mldivide\n%__________________________________________________________________________\n% Copyright (C) 2011 Wellcome Trust Centre for Neuroimaging\n \n% Ged Ridgway\n% $Id: spm_mrdivide.m 4360 2011-06-14 16:46:37Z ged $\n\nD = spm_mldivide(B', 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_mrdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970904940925, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5860916782840041}}
{"text": "function coeffS = computeMcoeffs(coeffS,symmetric)\n% function coeffS = computeMcoeffs(coeffS,symmetric)\n%\n% APA, 6/11/2018\n\nif ~exist('symmetric','var')\n    symmetric = true;\nend\n\n%% ComputeRemainingCoefficients(bool symmetric)\n\nif symmetric\n    \n    coeffS.M1 = coeffS.N1 - coeffS.D1 * coeffS.N0;\n    coeffS.M2 = coeffS.N2 - coeffS.D2 * coeffS.N0;\n    coeffS.M3 = coeffS.N3 - coeffS.D3 * coeffS.N0;\n    coeffS.M4 = -coeffS.D4 * coeffS.N0;\n        \nelse\n    \n   coeffS.M1 = -( coeffS.N1 - coeffS.D1 * coeffS.N0 );\n   coeffS.M2 = -( coeffS.N2 - coeffS.D2 * coeffS.N0 );\n   coeffS.M3 = -( coeffS.N3 - coeffS.D3 * coeffS.N0 );\n   coeffS.M4 = coeffS.D4 * coeffS.N0;\nend\n    \n% Compute coefficients to be used at the boundaries ...\n% in order to simulate edge extension boundary conditions.\ncoeffS.SN = coeffS.N0 + coeffS.N1 + coeffS.N2 + coeffS.N3;\ncoeffS.SM = coeffS.M1 + coeffS.M2 + coeffS.M3 + coeffS.M4;\ncoeffS.SD = 1.0 + coeffS.D1 + coeffS.D2 + coeffS.D3 + coeffS.D4;\n    \ncoeffS.BN1 = coeffS.D1 * coeffS.SN / coeffS.SD;\ncoeffS.BN2 = coeffS.D2 * coeffS.SN / coeffS.SD;\ncoeffS.BN3 = coeffS.D3 * coeffS.SN / coeffS.SD;\ncoeffS.BN4 = coeffS.D4 * coeffS.SN / coeffS.SD;\n    \ncoeffS.BM1 = coeffS.D1 * coeffS.SM / coeffS.SD;\ncoeffS.BM2 = coeffS.D2 * coeffS.SM / coeffS.SD;\ncoeffS.BM3 = coeffS.D3 * coeffS.SM / coeffS.SD;\ncoeffS.BM4 = coeffS.D4 * coeffS.SM / coeffS.SD;\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/recursiveFilters/computeMcoeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5860916699555858}}
{"text": "function f = harmean(g,m,n)\n% Implemets a harmonic mean filter.\ninclass = class(g);\ng = im2double(g);\nf = m * n ./ imfilter(1./(g + eps),ones(m,n),'replicate');\nf = changeclass(inclass,f);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28986-adding-noise-and-image-restoration/harmean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5859929146546583}}
{"text": "function y=H_obj(x)\n\ny=[8-2*x(2) -2*x(1);-2*x(1) 2];", "meta": {"author": "QiangLong2017", "repo": "Optimization-Theory-and-Algorithm", "sha": "13becd67be377356c221367ffbc7c90a1aabd917", "save_path": "github-repos/MATLAB/QiangLong2017-Optimization-Theory-and-Algorithm", "path": "github-repos/MATLAB/QiangLong2017-Optimization-Theory-and-Algorithm/Optimization-Theory-and-Algorithm-13becd67be377356c221367ffbc7c90a1aabd917/code/10_2NewtonMethod/H_obj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5859928947365637}}
{"text": "function [Simil2]=fuzzysimil2(A,B)\n\nPA=sqrt((A(1)-A(2))^2+A(5)^2)+sqrt((A(3)-A(4))^2+A(5)^2)+(A(3)-A(2))+(A(4)-A(1));\nPB=sqrt((B(1)-B(2))^2+B(5)^2)+sqrt((B(3)-B(4))^2+B(5)^2)+(B(3)-B(2))+(B(4)-B(1));\naA=1/2*(A(5)*(A(3)-A(2)+A(4)-A(1)));\naB=1/2*(B(5)*(B(3)-B(2)+B(4)-B(1)));\ntemp=(min(PA,PB)/max(PA,PB))*(min(aA,aB) + min(A(5),B(5)))/(max(aA,aB) + max(A(5),B(5)));\n\nSimil2=(1-(sum(abs(A(1:4)-B(1:4))))/4)*temp;\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/36323-stopsis/Stopsis1.2/fsimil2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.5859789744869279}}
{"text": "% demonstrate usage of classification\n%\n% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2013-10-16.\nclear all, close all\n\n%% SAY WHICH CODE WE WISH TO EXERCISE\nid = [1,1]; % use Gauss/Exact\nid = [1,2; 2,2; 3,2]; % compare Laplace\nid = [1,3; 2,3; 3,3]; % study EP\nid = [1,5; 2,5]; % look into KL (takes quite a while)\nid = [1,4; 2,4; 3,4]; % deal with VB\n\nseed = 943; randn('seed',seed), rand('seed',seed)\n\nntr = 50; nte = 1e4;                        % number of training and test points\nxtr = 10*sort(rand(ntr,1));                                     % sample dataset\np = @(x) 1./(1+exp(-5*sin(x)));                  % \"true\" underlying probability\nytr = 2*(p(xtr)>rand(ntr,1))-1;                              % draw labels +1/-1\ni = randperm(ntr); nout = 3;                                      % add outliers\nytr(i(1:nout)) = -ytr(i(1:nout)); \nxte = linspace(0,10,1e4)';                    % support, we test our function on\ncov = {@covSEiso}; sf = 1; ell = 0.7;                             % setup the GP\nhyp0.cov  = log([ell;sf]);\nmean = {@meanZero};                                                   % m(x) = 0\nhyp0.mean = [];\nlik_list = {'likGauss','likErf','likLogistic'};          % allowable likelihoods\ninf_list = {'infExact','infLaplace','infEP','infVB','infKL'};   % inference algs\n\nNcg = 50;                                   % number of conjugate gradient steps\nsdscale = 0.5;                  % how many sd wide should the error bars become?\ncol = {'k',[.8,0,0],[0,.5,0],'b',[0,.75,.75],[.7,0,.5]};                % colors\nymu{1} = 2*p(xte)-1; ys2{1} = 0;\nfor i=1:size(id,1)\n  lik = lik_list(id(i,1));                                % setup the likelihood\n  if strcmp(lik,'likGauss')\n    sn = .2; hyp0.lik = log(sn);\n  else\n    hyp0.lik = [];\n  end\n  inf = inf_list{id(i,2)};\n  fprintf('OPT: %s/%s\\n',lik_list{id(i,1)},inf_list{id(i,2)})\n  hyp = minimize(hyp0,'gp', -Ncg, inf, mean, cov, lik, xtr, ytr);   % opt hypers\n  [ymu{i+1}, ys2{i+1}] = gp(hyp, inf, mean, cov, lik, xtr, ytr, xte);  % predict\n  [nlZ(i+1)] = gp(hyp, inf, mean, cov, lik, xtr, ytr);\nend\n\nfigure, hold on\nfor i=1:size(id,1)+1\n  plot(xte,ymu{i},'Color',col{i},'LineWidth',2)\n  if i==1\n    leg = {'function'};\n  else\n    leg{end+1} = sprintf('%s/%s -lZ=%1.2f',...\n                                lik_list{id(i-1,1)},inf_list{id(i-1,2)},nlZ(i));\n  end\nend\nfor i=1:size(id,1)+1\n  ysd = sdscale*sqrt(ys2{i});\n  fill([xte;flipud(xte)],[ymu{i}+ysd;flipud(ymu{i}-ysd)],...\n       col{i},'EdgeColor',col{i},'FaceAlpha',0.1,'EdgeAlpha',0.3);\nend\nfor i=1:size(id,1)+1, plot(xte,ymu{i},'Color',col{i},'LineWidth',2), end\nplot(xtr,ytr,'k+'), plot(xtr,ytr,'ko'), legend(leg)\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/gpml/doc/usageClassification.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5859645042952903}}
{"text": "function Show_EWT2D_Filters(fil)\n\n%===========================================================\n%\n% function Show_EWT2D_Filters(fil)\n%\n% This function permits to plot the Fourier magnitude of all \n% 2D EWT Littlewood-Paley filters.\n%\n% Input:\n%   - fil: cell containing all the filters\n%\n% Author: J.Gilles\n% Institution: UCLA - Department of Mathematics\n% email: jegilles@math.ucla.edu\n% Date: March, 1st, 2013\n%\n%===========================================================\np=ceil(length(fil)/2);\n\nfigure;\nfor n=1:length(fil)\n    subplot(2,p,n);imshow(fftshift(abs(fil{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/42141-empirical-wavelet-transforms/EWT/2D/Show_EWT2D_Filters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.58596449724672}}
{"text": "function Jnst = newtonbc(J,xy,bound)\n%newtonbc imposes Dirichlet bc on Jacobian\n%   Jnst = newtonbc(J,xy,bound);\n%   input\n%          J          Jacobian velocity matrix\n%          xy         vertex coordinate vector  \n%          bound      boundary vertex vector\n%   output\n%          Jnst       Jacobian velocity matrix\n%\n%   IFISS function: DJS, HCE; 30 August 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n\nnvtx = length(xy(:,1));\nnu = nvtx*2; nbd=length(bound);\nnull_col=sparse(nu,nbd); %null_row=sparse(nbd,nu);\nJnst=J;\n\n%% set boundary condition\nxbd=xy(bound,1); ybd=xy(bound,2);\n%% impose boundary condition\ndA=zeros(nvtx,1); dA(bound)=ones(nbd,1); \n\n%Procedure is equivalent to the two commented lines below\n%It is more efficient because only columns are referenced\n%Jnst(:,bound)=null_col;  Jnst(bound,:)=null_row;\n%Jnst(:,nvtx+bound)=null_col;  Jnst(nvtx+bound,:)=null_row;\n\nJt = Jnst';\nJt(:,bound) = null_col;\nJt(:,nvtx+bound) = null_col;\nJnst = Jt';\nJnst(:,bound) = null_col;\nJnst(:,nvtx+bound) = null_col;\n\nJnst = Jnst + [spdiags(dA,0,nvtx,nvtx),sparse(nvtx,nvtx); ...\n               sparse(nvtx,nvtx),spdiags(dA,0,nvtx,nvtx)];\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/navier_flow/newtonbc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867585368343, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5859644809119535}}
{"text": "function bin_pos = createIndexVector(keypts, match_binsize, x_bin_num, y_bin_num)\n%CREATEINDEXVECTOR Find the bin position to which each keypoint belongs to\n%\n% INPUT:\n%   - keypts(1, N): input feature keypoints\n%   - match_binsize: matching bin width/height\n%   - x_bin_num: number of bins along x-direction\n%   - y_bin_num: number of bins along y-direction\n%\n% OUTPUT:\n%   - bin_pos(x_bin_num, y_bin_num, 4): cell containing indices of keypoint\n\n% allocate memory\nnum = size(keypts, 2);\n% number of classes\nclasses_num = 4; \n\n% create a array for bin positions/class\nbin_pos = cell(x_bin_num, y_bin_num, classes_num);\n\n% iterate over all keypoints\nfor i = 1:num\n    % coordinate of keypoint\n    x = keypts(i).location(1);\n    y = keypts(i).location(2);\n    c = keypts(i).class;\n    % find bin position\n    bin_x = min(ceil(x/match_binsize), x_bin_num);\n    bin_y = min(ceil(y/match_binsize), y_bin_num);\n    % add keypoint index to corresponding bin_pos\n    bin_pos{bin_x, bin_y, c} = horzcat(bin_pos{bin_x, bin_y, c}, i);\nend\n\nend\n", "meta": {"author": "Mayankm96", "repo": "Stereo-Odometry-SOFT", "sha": "22580a44a8859ecd0720bae5279d0acadd8e86dc", "save_path": "github-repos/MATLAB/Mayankm96-Stereo-Odometry-SOFT", "path": "github-repos/MATLAB/Mayankm96-Stereo-Odometry-SOFT/Stereo-Odometry-SOFT-22580a44a8859ecd0720bae5279d0acadd8e86dc/code/functions/featureMatching/createIndexVector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5859493568270763}}
{"text": "function res = penalized_coefficients(lasso_object, indices, alignment)\n% -------------------------------------------------------------------------\n% function res = penalized_coefficients(penalized_object, indices, alignment)\n% -------------------------------------------------------------------------\n% PURPOSE: This function returns the LASSO coefficients for which the \n%          chosen index equals those listed in indices.\n%          The alignment index can be chosen to be:\n%          lambdas, normalized L1 norms and L1 norms;\n% -------------------------------------------------------------------------\n% INPUTS:\n% lasso_object: a structure as the one returned by the lasso routine:\n% indices:      index of the points at which interpolation is wanted\n% alignment:    one string of ('normalized_l1', 'l1'm 'lambdas')\n%               indicating which index to use for alignment\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% res:          a structure containing  the coefficients and the \n%               regularization parameter at the interpolated points\n%               intercept:\n%               nbeta:\n%               beta:\n%               lambda:\n% -------------------------------------------------------------------------\n% Author: Guilherme V. Rocha\n%         Department of Statistics\n%         University of California, Berkeley\n%         gvrocha@stat.berkeley.edu, gvrocha@gmail.com\n% 2006/09\n% -------------------------------------------------------------------------\n% See also: LASSO, BLASSOL2\n\n% 0. Checking input parameters:\n%==========================================================================\nif nargin < 3\n  alignment = 'normalized_penalty';\nend;\n\n% 1. Interpolates according to the chosen L1 norm (normalized x non normalized)\n%==========================================================================\nswitch(lower(alignment))\n  case{'normalized_penalty'}\n    sizes = lasso_object.npenalty;\n  case{'penalty'}\n    sizes = lasso_object.penalty;\n  case{'lambda'}\n    sizes = lasso_object.lambda;\n  otherwise\n    error('Unrecognized alignment string');\nend;\n\n% Takes care of the case when there are entries with repeated L1s:\n[unique_sizes, I, J]   = unique(sizes);\n\n% If one of the points to be calculated is beyond the end of the path, use\n% the end of path coeffcients for it:\nindices       = min(indices, max(sizes));\nindices       = reshape(indices, prod(size(indices)), 1);\nres.intercept = interp1(unique_sizes, lasso_object.intercept(I), indices);\nres.beta      = interp1(unique_sizes, lasso_object.beta(I,:), indices);\nres.nbeta     = interp1(unique_sizes, lasso_object.nbeta(I,:), indices);\nif(~isempty(lasso_object.lambda))\n  res.lambda    = interp1(unique_sizes, lasso_object.lambda(I,:), indices);\nend;\nres.indices   = indices';\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/lasso/penalized_coefficients.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.585949353762}}
{"text": "Fs=44100; % sampling frequency\ndt=1/Fs;\nT0=2; % period, sec\n\nclose all;\n\nr = audiorecorder(Fs, 16, 1);\nclc;disp('recording started...');\nrecordblocking(r,T0); % record next data\ndisp('recorded');\ns00 = getaudiodata(r); % get data\n\n\nL0=length(s00);\n\ns=s00-mean(s00);\n\n %load('bp.mat'); % bandpass 50-4000 Hz\n load('lp.mat'); % lowpass 0-10000Hz\n \n s = filter(Num,1,s);\n \n s=s/max(abs(s)); % normalize to maximum\n\n[op ismax]=find_all_optimums(s);\n% op - optimums positions\n\n%[z isrise]=find_zeros(s);\n%op=decimate_optimums(z,op,s(op));\n\nt=(0:L0-1)'*dt;\nplot(t,s,'b-');\nhold on;\nplot(t(op),s(op),'rx');\n\n% sw0=interp1(t(op),s(op),t,'nearest');\n% sw1=interp1(t(op),s(op),t,'linear');\n% al=0;\n\n\ndop=diff(op);\n\n% quntitize dop to [0 255]:\ndop(dop>255)=255;\ndop=round(dop); % not necessary\n\n\nopv=s(op); % values in optimums\n\n% quntitize opv to -128 127\nopv=128*opv;\nopv(opv>127)=127;\nopv(opv<-128)=-128;\nopv=round(opv);\n\n\n% compression ratio:\nszo=2*length(s); % original size as 2 byts per sample \nszc=1*length(dop)+1*length(opv); % compressed size one byte for dop element, one byte for opv element\ncr=szo/szc; % compression ratio\n\n\n% reconstruction\nopr=[0; cumsum(dop)];\ntr=opr*dt;\n\nopvr=opv/128;\n\ntra=0:dt:max(tr); % time for interpolation\n\nsw=interp1(tr,opvr,t,'pchip');\n\nsoundsc(sw,Fs);\n\nplot(t,sw,'g-');\n\n\ntitle(['compressed in ' num2str(cr) ' times']);\nlegend('original','optimums','reconstructed');\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/33674-sound-compression-by-optimums/test1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5859352581559563}}
{"text": "function x = prox_sum_square(v, lambda)\n% PROX_SUM_SQUARE    Proximal operator of sum-of-squares.\n%\n%   prox_sum_square(v,lambda) is the proximal operator of\n%   (1/2)||.||_2^2 with parameter lambda.\n\n    x = (1/(1 + lambda))*v;\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/prox_sum_square.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5859352474084223}}
{"text": "function [MW] = hpb2MW(hpb)\n% Convert power from boiler horsepower to megawatts.\n% Chad A. Greene 2012\nMW = hpb*9809.5e-6;\n", "meta": {"author": "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/hpb2MW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424334245617, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5859352393378561}}
{"text": "function [aw,tt1, tt2, tmc, mag_zone]=bvalue(this, mcType, method)\n    %BVALUE evaluate b-value, a-value and magnitude of completeness\n    % of an earthquake catalog stored in a Catalog object.\n    %\n    % BVALUE(COBJ, MCTYPE) produces a Gutenberg-Richter type plot \n    %    with the best fit line and display of b-,a-values and Mc \n    %    for the catalog object COBJ. MCTYPE is a number from 1-5 \n    %    to select the algorithm used for calculation of the \n    %    magnitude of completeness. Options are:\n    %\n    %    1: Maximum curvature\n    %    2: Fixed Mc = minimum magnitude (Mmin)\n    %    3: Mc90 (90% probability)\n    %    4: Mc95 (95% probability)\n    %    5: Best combination (Mc95 - Mc90 - maximum curvature)\n\n    % Liberally adapted from original code in ZMAP.\n    % Author: Silvio De Angelis, 27/07/2012 00:00:00\n    % Modified and included in Catalog by Glenn Thompson,\n    % 14/06/2014\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 cobj.magas 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 Pucobj.magblic License\n    % along with this program; if not, write to the\n    % Free Software Foundation, Inc.,\n    % 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n    if nargin < 2\n        disp('--------------------------------------------------------')\n        disp('ERROR: Usage is: bvalue(cobj, mcType). mcType not specified')\n        disp('--------------------------------------------------------')\n        disp('mcType can be:')\n        disp('1: Maximum curvature')\n        disp('2: Fixed Mc = minimum magnitude (Mmin)')\n        disp('3: Mc90 (90% probability)')\n        disp('4: Mc95 (95% probability)')\n        disp('5: Best combination (Mc95 - Mc90 - maximum curvature)')\n        return\n    end\n\n    % form magnitude vector - removing any NaN values with find\n    good_magnitude_indices = find(this.data > 0.0);\n    if strcmp(method, 'power')\n        mag = log10(this.data(good_magnitude_indices));\n    elseif strcmp(method, 'exponential')\n        mag = this.data(good_magnitude_indices);\n    end   \n\n    %MIN AND MAX MAGNITUDE IN CATALOG\n    minimum_mag = min(mag);\n    maximum_mag = max(mag);\n\n    %COUNT EVENTS IN EACH MAGNITUDE BIN\n    if strcmp(method, 'power')\n        magrange = minimum_mag:0.1:maximum_mag;\n    elseif strcmp(method, 'exponential')\n        magrange = 10.^(log10(minimum_mag):0.1:log10(maximum_mag));\n    end  \n    [bval, xt2] = hist(mag, magrange);\n\n    %CUMULATIVE NUMBER OF EVENTS IN EACH MAGNITUDE BIN\n    bvalsum = cumsum(bval);\n\n    %NUMBER OF EVENTS IN EACH BIN IN REVERSE ORDER\n    bval2 = bval(length(bval):-1:1);\n\n    %NUMBER OF EVENTS IN EACH MAGNITUDE BIN IN REVERSE ORDER\n    bvalsum3 = cumsum(bval(length(bval):-1:1));\n\n    %BINS IN REVERSE ORDER\n    xt3 = fliplr(magrange);\n    backg_ab = log10(bvalsum3);\n\n    %CREATE FIGURE WINDOW AND MAKE FREQUENCY-MAGNITUDE PLOT\n    figure('Color','w','Position',[0 0 600 600])\n\n    pl = semilogy(xt3,bvalsum3,'sb'); \n\n    set(pl, 'LineWidth', [1.0],'MarkerSize', [10],'MarkerFaceColor','r','MarkerEdgeColor','k');\n    axis square\n    hold on\n\n    %pl1 = semilogy(xt3,bval2,'^b');\n    %set(pl1, 'LineWidth',[1.0],'MarkerSize',[10],'MarkerFaceColor','w','MarkerEdgeColor','k');\n    if strcmp(method, 'power')\n        %xlabel('Log_1_0(Amplitude)','Fontsize', 12)\n        xlabel('Magnitude','Fontsize', 12)\n    elseif strcmp(method, 'exponential')\n        xlabel('Amplitude','Fontsize', 12)\n    end             \n\n    ylabel('Cumulative Minutes','Fontsize',12)\n    set(gca,'visible','on','FontSize',12,'FontWeight','normal',...\n        'FontWeight','bold','LineWidth',[1.0],'TickDir','in','Ticklength',[0.01 0.01],...\n        'Box','on','Tag','cufi','color','w')\n\n    %ESTIMATE B-VALUE (MAX LIKELIHOOD ESTIMATE)\n    Nmin = 10;\n    fMccorr = 0;\n    fBinning = 0.1;\n\n    if length(mag) >= Nmin\n\n        %GOODNESS-OF-FIT TO POWER LAW\n        %%%%%%%%%%%%%%%%%% mcperc_ca3.m start %%%%%%%%%%%%%%%%%%%%\n        % This is a completeness determination test\n\n\n        if strcmp(method, 'power')\n            [bval,xt2] = hist(mag,-2:0.1:6);\n        elseif strcmp(method, 'exponential')\n            [bval,xt2] = hist(log10(mag),-2:0.1:6);\n        end  \n        l = max(find(bval == max(bval)));\n        magco0 =  xt2(l)\n\n        dat = [];\n\n        %for i = magco0-0.6:0.1:magco0+0.2\n        for i = magco0-0.5:0.1:magco0+0.7\n            if strcmp(method, 'power')\n                l = mag >= i - 0.0499;\n            elseif strcmp(method, 'exponential')\n                l = mag >= 10^(i - 0.0499);\n            end\n            nu = length(mag(l));\n            if length(mag(l)) >= 25;\n                %[bv magco stan av] =  bvalca3(catZmap(l,:),2,2);\n                if strcmp(method, 'power')\n                    [mw bv2 stan2 av] =  bvalue_lib.bmemag(mag(l));\n                elseif strcmp(method, 'exponential')\n                    [mw bv2 stan2 av] =  bvalue_lib.bmemag(log10(mag(l)));\n                end\n                bvalue_lib.synthb_aut;\n                dat = [ dat ; i res2];\n            else\n                dat = [ dat ; i nan];\n            end\n\n        end\n\n        j =  min(find(dat(:,2) < 10 ));\n        if isempty(j) == 1; Mc90 = nan ;\n        else;\n            Mc90 = dat(j,1);\n        end\n\n        j =  min(find(dat(:,2) < 5 ));\n        if isempty(j) == 1; Mc95 = nan ;\n        else;\n            Mc95 = dat(j,1);\n        end\n\n        j =  min(find(dat(:,2) < 10 ));\n        if isempty(j) == 1; j =  min(find(dat(:,2) < 15 )); end\n        if isempty(j) == 1; j =  min(find(dat(:,2) < 20 )); end\n        if isempty(j) == 1; j =  min(find(dat(:,2) < 25 )); end\n        j2 =  min(find(dat(:,2) == min(dat(:,2)) ));\n        %j = min([j j2]);\n\n        Mc = dat(j,1);\n        magco = Mc;\n        prf = 100 - dat(j2,2);\n        if isempty(magco) == 1; magco = nan; prf = 100 -min(dat(:,2)); end\n        %display(['Completeness Mc: ' num2str(Mc) ]);\n        %%%%%%%%%%%%%%%%%% mcperc_ca3.m end %%%%%%%%%%%%%%%%%%%%%%\n\n        %CALCULATE MC\n        [fMc] = bvalue_lib.calc_Mc(mag, mcType, fBinning, fMccorr);\n        l = mag >= fMc-(fBinning/2);\n        if length(mag(l)) >= Nmin\n            [fMeanMag, fBValue, fStd_B, fAValue] =  bvalue_lib.calc_bmemag(mag(l), fBinning);\n        else\n            [fMc, fBValue, fStd_B, fAValue] = deal(NaN);\n        end\n\n        %STANDARD DEV OF a-value SET TO NAN;\n        [fStd_A, fStd_Mc] = deal(NaN);\n\n    else\n        [fMc, fStd_Mc, fBValue, fStd_B, fAValue, fStd_A, ...\n            fStdDevB, fStdDevMc] = deal(NaN);\n    end\n\n    magco = fMc; % magnitude of completeness?\n    index_low=find(xt3 < magco+.05 & xt3 > magco-.05);\n    mag_hi = xt3(1);\n    index_hi = 1;\n    mz = xt3 <= mag_hi & xt3 >= magco-.0001;\n    mag_zone=xt3(mz);\n    y = backg_ab(mz);\n\n    %PLOT MC IN FIGURE\n    Mc = semilogy(xt3(index_low),bvalsum3(index_low)*1.5,'vk');\n    set(Mc,'LineWidth',[1.0],'MarkerSize',7)\n    Mc = text(xt3(index_low)+0.2,bvalsum3(index_low)*1.5,'Mc');\n    set(Mc,'FontWeight','normal','FontSize',12,'Color','k')\n\n    %CREATE AND PLOT FIT LINE\n    sol_type = 'Maximum Likelihood Solution';\n    bw=fBValue;\n    aw=fAValue;\n    ew=fStd_B;\n    p = [ -1*bw aw];\n    f = polyval(p,mag_zone);\n    f = 10.^f;\n\n    hold on\n    ttm= semilogy(mag_zone,f,'k');\n    set(ttm,'LineWidth',[2.0])\n    std_backg = ew;\n\n    %ERROR CALCULATIONS\n    %b = mag;\n    bv = [];\n    si = [];\n\n    set(gca,'XLim',[min(mag)-0.5  max(mag+0.5)])\n    %set(gca,'YLim',[0.9 length(mag+30)*2.5]);\n\n    p=-p(1,1);\n    p=fix(100*p)/100;\n    tt1=num2str(bw,3);\n    tt2=num2str(std_backg,1);\n    tt4=num2str(bv,3);\n    tt5=num2str(si,2);\n    tmc=num2str(magco,2);\n    rect=[0 0 1 1];\n    h2=axes('position',rect);\n    set(h2,'visible','off');\n    a0 = aw-log10((max(this.dnum)-min(this.dnum))/365);\n\n    text(.53,.88, ['b-value = ',tt1,' +/- ',tt2,',  a value = ',num2str(aw,3)],'FontSize',12);\n    %text(.53,.85,sol_type,'FontSize',12 );\n    text(.53,.82,['Magnitude of Completeness = ',tmc],'FontSize',12);\n\n\n    % Glenn 20150111 add R^2 value\n    thiscorr = corrcoef(mag_zone, f)\n    r2 = thiscorr(1,2);\n    thiscorr2 = corrcoef(mag_zone, log10(f))\n    r22 = thiscorr2(1,2);\n    %text(.53,.76,['R^2 = ',num2str(r2)],'FontSize',12);\n    %text(.53,.70,['R^2 = ',num2str(r22)],'FontSize',12);\n\nend         ", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@rsam/extensions/bvalue.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5859352366608882}}
{"text": "% Script demonstrating usage of the cbpdndlmd function.\n%\n% Author: Brendt Wohlberg <brendt@lanl.gov>  Modified: 2017-04-29\n%\n% This file is part of the SPORCO library. Details of the copyright\n% and user license can be found in the 'Copyright' and 'License' files\n% distributed with the library.\n\n\n% Training images\nS0 = zeros(512, 512, 2, 'single');\nS0(:,:,1) = single(stdimage('lena.grey')) / 255;\nS0(:,:,2) = single(stdimage('barbara.grey')) / 255;\n\n\n%Reduce images size to speed up demo script\ntmp = zeros(128, 128, 2, 'single');\nfor k = 1:size(S0,3),\n  tmp(:,:,k) = imresize(S0(:,:,k), 0.25);\nend\nS0 = tmp;\n\n\n% Filter input images and compute highpass images\nnpd = 16;\nfltlmbd = 5;\n[Sl, Sh] = lowpass(S0, fltlmbd, npd);\n\n\n% Construct weight matrix and padded test image set\nShp = padarray(Sh, [7 7], 'post');\nt = 0.5;\nW = randn(size(Sh));\nW(abs(W) > t) = 1;\nW(abs(W) < t) = 0;\nW = padarray(W, [7 7], 'post');\nShW = W .* Shp;\n\n\n% Construct initial dictionary\nD0 = zeros(8,8,32, 'single');\nD0(3:6,3:6,:) = single(randn(4,4,32));\n\n\n% Set up cbpdndl parameters\nlambda = 0.05;\nopt = [];\nopt.Verbose = 1;\nopt.MaxMainIter = 500;\nopt.rho = 50*lambda + 0.5;\nopt.sigma = size(Sh,3);\nopt.AutoRho = 1;\nopt.AutoRhoPeriod = 10;\nopt.AutoSigma = 1;\nopt.AutoSigmaPeriod = 10;\nopt.XRelaxParam = 1.8;\nopt.DRelaxParam = 1.8;\n\n\n% Do standard dictionary learning and reconstruct\n[D1, X1, optinf1] = cbpdndl(D0, ShW, lambda, opt);\nDX1 = ifft2(bsxfun(@times, fft2(D1, size(X1,1), size(X1,2)), fft2(X1)), ...\n           'symmetric');\nSr1 = squeeze(sum(DX1,3)) + padarray(Sl, [7 7], 'post');\n\n% Do dictionary learning with mask decoupling and reconstruct\nopt.W = W;\n[D2, X2, optinf2] = cbpdndlmd(D0, ShW, lambda, opt);\nDX2 = ifft2(bsxfun(@times, fft2(D2, size(X2,1), size(X2,2)), fft2(X2)), ...\n           'symmetric');\nSr2 = squeeze(sum(DX2,3)) + padarray(Sl, [7 7], 'post');\n\n\n% Display dictionaries\nfigure;\nsubplot(1,2,1);\nimdisp(tiledict(D1));\ntitle('Standard DL');\nsubplot(1,2,2);\nimdisp(tiledict(D2));\ntitle('DL with mask decoupling');\n\n\n% Display reconstructions\nfigure;\nsubplot(2,2,1);\nimdisp(Sr1(:,:,1));\ntitle('Standard DL');\nsubplot(2,2,2);\nimdisp(Sr2(:,:,1));\ntitle('DL with mask decoupling');\nsubplot(2,2,3);\nimdisp(Sr1(:,:,2));\ntitle('Standard DL');\nsubplot(2,2,4);\nimdisp(Sr2(:,:,2));\ntitle('DL with mask decoupling');\n\n\n% Plot functional value evolution\nfigure;\nsubplot(1,2,1);\nsemilogx(optinf1.itstat(:,2), 'LineWidth', 2);\nylim([15, 45]);\nxlabel('Iterations');\nylabel('Functional value');\ntitle('Standard DL');\nsubplot(1,2,2);\nsemilogx(optinf2.itstat(:,2), 'LineWidth', 2);\nylim([15, 45]);\nxlabel('Iterations');\nylabel('Functional value');\ntitle('DL with mask decoupling');\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/ConvSR_Image_Fusion_Codes/sporco/Demo/demo_cbpdndlmd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5859352366344462}}
{"text": "function h = conv(f, g)\n%CONV   Convolution of BNDFUN objects.\n%   H = CONV(F, G) produces the convolution of BNDFUN objects F and G:\n%                     - \n%                    /\n%           H(x) =   |    F(t) G(x-t) dt,  x in [a + c, b + d]\n%                    /\n%                   -\n%   where domain(F) is [a, b] and domain(G) is [c, d]. The integral is taken\n%   over all t for which the integrand is defined: max(a, x - d) <= t <= min(b,\n%   x - c).  The breakpoints of H are all pairwise sums of the breakpoints of F\n%   and G.\n%\n%   Note that CONV only supports piecewise-smooth functions on bounded domains.\n%\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n%\n% Nick Hale and Alex Townsend, 2014\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DEVELOPER NOTE:\n%\n% For further details, see Hale and Townsend, \"An algorithm for the convolution\n% of Legendre series\", SIAM Journal on Scientific Computing, Vol. 36, No. 3,\n% pages A1207-A1220, 2014.\n% \n% In the following, it is assumed that the length of the domain of g is greater\n% than the length of the domain of f. If this is not the case, then simply\n% compute h = conv(g, f), which is equivalent. We assume f and g are polynomials\n% of degree M and N, resepectively. If f and g are piecewise-defined, one can\n% use the bilinearity of convolution and convolve each each the FUNs\n% individually.\n%\n% The general convolution domain (for smooth functions) is as follows:\n%           .___________________________\n%          /|                  |      /\n%        /  |                  |    /\n%      /    |                  |  /\n%    /______|__________________|/\n%  a+c     b+c                a+d     b+d \n%\n% The triangular pieces at end are dealt with using a convolution theorem for\n% Legendre polynomials, which leads to a convenient recurrence relation. The\n% cost of this is O(m*n) and results in a polynomial of degree m+n. See\n% EASYCONV() for details.\n%\n% Similarly one can show the interior rectangle results in a polynomial of\n% degree n. This can be computed by patching with R = floor[(d-c) / (b-a)]\n% parallelograms (although triangle Z is not used). Each parallelogram requires\n% restricting g to a suitable subdomain, which costs O(n^2) operations. Total\n% complexity ratio*(m*n + n*n)\n%            ___________________________\n%          /       /       /:     /   /\n%        /       /       /  : Z /   /          <-- R patches\n%      /       /       /    : /   /           \n%    /_______/_______/______/__ /\n%  a+c     b+c             fl  a+d     b+d\n%\n% The final piece is computed via further parallelogram subdivision starting\n% from the right (B), and a smaller subdivision in both f and g (C).\n% Contributions from D and E are discarded, as they have already been counted\n% above. Complexity O(m^2 + n^2)\n%   ________________\n%   : /E|C/:      / \n%   :   /  :    /\n%   : /D|B :  /\n%   /___|__:/\n%  a+c fl a+d     b+d\n%\n% Rather than make a BNDFUN corresponding to the each of the patches, we\n% instead evaluate directly on a corresonding Chebyshev grid of appropriate\n% size, which turns out to be far more efficient. \n%\n% Total complexity: O( R*(m*n + n*n) + m*m )\n%\n% However, in the case when R is too big we revert to a Clenshaw-Curtis\n% quadrature-based approach to compute the convolution in the inner rectangle.\n% This approach has a complexity O( (m + n)^3 ). We naively compare this with\n% the big-O term above to determine which approach to use.\n\n% [TODO]: It's possible this should be pushed further to the chebtech level.\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Return empty for an empty input:\nif ( isempty(f) || isempty(g) )\n    h = bndfun();\n    return\nend\n\n% Extract the domain:\ndomF = f.domain;\na = domF(1);\nb = domF(2);\n\ndomG = g.domain;\nc = domG(1);\nd = domG(2);\n\n% Ensure that g is the signal (i.e., on the larger domain) and f is the filter:\nif ( (b - a) > (d - c) )\n    h = conv(g, f);\n    return\nend\n    \n% Useful things:\nM = length(f);                               % Length of F\nN = length(g);                               % Length of g\nnumPatches = floor((d - c) / (b - a));       % Number of patches required\nx = chebpts(N, [b+c, a+d], 1);               % Chebyshev grid for interior piece\ny = 0*x;                                     % Initialise values in interior\nmap = @(x, a, b) (x-a)/(b-a) - (b-x)/(b-a);  % Map from [a, b] --> [-1, 1]\n\n% If there are too many patches then the HT approach is too slow. In such a case\n% we resort to the standard quadrature-based approach (but still use the HT\n% approach for the two triangular domains at the ends).\ncoeffsConvCost = numPatches*((M+N)*N);\nquadConvCost = (M+N)^3;\nif ( numPatches > 1 && coeffsConvCost > quadConvCost )\n    h_left = conv(f, restrict(g, c+[0, b-a]));     % Left triangle\n    h_right = conv(f, restrict(g, d-[(b-a) 0]));   % Right tirangle\n    % Middle:\n    [t, w] = legpts((M+N+5)/2, [a,b]);             % Legendre grid\n    [tt, xx] = meshgrid(t,x);                      % Cheb/Leg grid to evaluate g\n    ft = feval(f,t);                               % Evaluate f\n    gxmt = feval(g, xx-tt);                        %    and g (expensive)\n    y = gxmt*(w'.*ft);                             % Compute integral\n    y = chebtech1.vals2coeffs(y);                  % Convert values to coeffs \n    % Trim small coefficients:\n    ay = abs(y); my = max(ay); loc = max(find(ay > 10*eps*my, 1, 'last'),1);\n    if ( isempty(loc) ), loc = 1; end              % Deal with case when y = 0\n    y = y(1:loc);\n    data.domain = [b+c, a+d];\n    h_mid = bndfun({[],y}, data);                  % Make h_mid from coeffs\n    h = {h_left{1}, h_mid, h_right{end}};          % Combine three pieces\n    h = fixMaps(h);                                % Ensure domain ends match\n    return\nend\n\n% Trim small coefficients in f:\nf_cheb = get(f, 'coeffs'); af = abs(f_cheb); mf = max(af); \nloc = find(af > 10*eps*mf, 1, 'last'); if ( isempty(loc) ), loc = 1; end\nf_cheb = f_cheb(1:loc);\nf_leg = cheb2leg(f_cheb);                   % Legendre coefficients of f\n\n% Restrict g:\ndoms = c + (b - a)*(0:numPatches);\ng_restricted = restrict(g, doms);\ndoms = c + (b - a)*(0:numPatches);           % Subdomains\nif ( ~iscell(g_restricted) )\n    % If doms happened to be domain(g), restrict would return a cell.\n    g_restricted = {g_restricted};\nend\n\n% Loop over the patches:\nfor k = 1:numPatches      \n                          %         _____\n    dk = doms([k, k+1]);  %       /|    /\n    dk_left  = a + dk(1); %     /  |  /\n    dk_mid   = a + dk(2); %   /____|/\n    dk_right = b + dk(2); %  dkl  dkm   dkr\n    gk = g_restricted{k};                          % g on this subdomain\n    gk = simplify(gk);                             % Simplify for efficiency\n    gk_leg = cheb2leg(get(gk, 'coeffs'));          % Legendre coefficients\n    [hLegL, hLegR] = easyConv(f_leg, gk_leg);      % Convolution on this domain\n        \n    % The left triangle for the kth patch:\n    ind = (dk_left <= x) & (x < dk_mid); % Locate the grid values in [dkl, dkr]:\n    if ( k == 1 ) % First piece:\n        hLegL = leg2cheb(hLegL);                   % Cheb. coeffs of left tri.\n        data.domain = [dk_left, dk_mid];\n        h_left = bndfun({[], hLegL}, data);        % Make BNDFUN from coeffs\n    else          % Subsequent left pieces\n        z = map(x(ind), dk_left, dk_mid);          % Map grid points to [-1, 1]\n        tmp = clenshawLegendre(z, hLegL);          % Evaluate via recurrence\n        y(ind) = y(ind) + tmp;                     % Append\n    end\n    \n    % The right triangle for the kth patch:\n    if ( k < numPatches )                          % Not needed for final patch!\n        % Locate the grid values in [dkl, dkr]:\n        ind = (dk_mid <= x) & (x < dk_right);\n        z = map(x(ind), dk_mid, dk_right);\n        tmp = clenshawLegendre(z, hLegR);\n        y(ind) = y(ind) + tmp;\n    end\n    \nend\n\nif ( abs((b-a)-(d-c)) < 10*eps(norm([a b c d], inf)) )\n    % If there's only one patch, then we already have all the information reqd.\n    hLegR = leg2cheb(hLegR);                        % Cheb coeffs of right tri.\n    data.domain = d + [a b];\n    h_right = bndfun({[], hLegR}, data);            % Make BNDFUN from coeffs\n    h_mid = bndfun();\n    \nelse  \n    % Final right right triangle:\n    %  ________________\n    %  : /E|C/:      / \n    %  :   /  : A  /\n    %  : /D|B :  /\n    %  /___|__:/\n    %     fl a+d     b+d\n\n    finishLocation = a + c + numPatches*(b - a);    % Where patches got to. (fl) \n    gk = restrict(g, d-[(b-a) 0]);                  % g on appropriate domain   \n    gk = simplify(gk);                              % Simplify for efficiency\n    gk_leg = cheb2leg(get(gk, 'coeffs'));           % Legendre coeffs\n    [hLegL, hLegR] = easyConv(f_leg, gk_leg);       % Conv on A and B\n    hLegR = leg2cheb(hLegR);                        % Cheb coeffs on A\n    data.domain = [d+a, d+b];\n    h_right = bndfun({[], hLegR}, data);            % Make BNDFUN from coeffs\n\n    % Remainder piece: (between fl and a+d)\n    remainderWidth = d + a - finishLocation; % b+d-fl-(b-a)\n    if ( remainderWidth > 0 )\n        ind = finishLocation <= x;           % Discard D and E\n\n        % B: (Coeffs were computed above)\n        z = map(x(ind), d - b + 2*a, d + a); % Map grid to [-1, 1]\n        tmp = clenshawLegendre(z, hLegL);    % Evaluate via recurrence\n        y(ind) = tmp;                        % Store\n\n        % C: \n        domfk = b + [-remainderWidth, 0];               % Domain of fk\n        domfk(1) = max(domfk(1), f.domain(1));          % Ensure domfk is a\n        domfk(end) = min(domfk(end), f.domain(end));    %  valid subdomain\n        fk = restrict(f, domfk);                        % Restrict f\n        fk = simplify(fk);                              % Simplify f\n        fk_leg = cheb2leg(get(fk, 'coeffs'));           % Legendre coeffs\n        domgk = [finishLocation, d + a] - b;            % Domain of gk\n        domgk(1) = max(domgk(1), g.domain(1));          % Ensure domgk is a\n        domgk(end) = min(domgk(end), g.domain(end));    %  valid subdomain\n        gk = restrict(g, domgk);                        % Restrict g\n        gk = simplify(gk);                              % Simplify g\n        gk_leg = cheb2leg(get(gk, 'coeffs'));           % Legendre coeffs\n        [~, hLegR] = easyConv(fk_leg, gk_leg);          % Conv \n        z = map(x(ind), finishLocation, d + a);         % Map to [-1, 1]\n        tmp = clenshawLegendre(z, hLegR);               % Eval via recurrence\n        y(ind) = y(ind) + tmp*remainderWidth/(b - a);   % Scale and append\n    end\n    % Convert values to coeffs (we don't want to construct a chebtech1)\n    y = chebtech1.vals2coeffs(y);\n\n    % Construct BNDFUN of the interior (rectangle) using coefficients:\n    data.domain = [b+c, a+d];\n    h_mid = bndfun({[], y}, data);\n    \nend\n\n% h_mid can be empty so return the three or two pieces as a cell array:\nif ( isempty(h_mid) )\n    h = {h_left*(b-a)/2, h_right*(b-a)/2};\nelse    \n    h = {h_left*(b-a)/2, h_mid*(b-a)/2, h_right*(b-a)/2};\nend\nh = fixMaps(h);\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction h = fixMaps(h)\n% Ensure endpoints of BNDFUNs for adjacent subintervals match exactly. NB: This\n% is a bit inefficient if consecutive endpoints get adjusted, as some BNDFUNs\n% may have their maps changed twice, but the map-change operation is fast enough\n% that this shouldn't matter.\nfor n = 2:1:numel(h)\n    end_left = h{n-1}.domain(end);\n    end_right = h{n}.domain(1);\n    if ( end_left ~= end_right )\n        hs_left = norm(h{n-1}.domain, Inf);  % hscale for left piece.\n        hs_right = norm(h{n}.domain, Inf);   % hscale for right piece.\n\n        % If there's a mismatch, it should be small because the BNDFUNs should\n        % come out in order corresponding to consecutive adjacent subintervals.\n        if ( abs(end_left - end_right) < 2*eps*max(hs_left, hs_right) )\n            new_end = (end_left + end_right)/2;\n            h{n-1} = changeMap(h{n-1}, [h{n-1}.domain(1) new_end]);\n            h{n} = changeMap(h{n}, [new_end h{n}.domain(end)]);\n        else\n            % We should only get here if a programmer error made elsewhere\n            % causes the BNDFUNs to get out of order.\n            error('CHEBFUN:BNDFUN:conv:nonConsecutive', ...\n                'Pieces do not belong to consecutive subintervals.');\n        end\n    end\nend\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [gammaL, gammaR] = easyConv(alpha, beta)\n% Convolution using Legendre expansions and the analoguous convolution theorem.\n% See Hale and Townsend, \"An algorithm for the convolution of Legendre series\",\n% SIAM Journal on Scientific Computing, Vol. 36, No. 3, pages A1207-A1220, 2014.\n\n% Better computational efficiency is achieved when g has the lower degree:\nif ( length(beta) > length(alpha) )\n    tmp = alpha;\n    alpha = beta;\n    beta = tmp;\nend\n\n% Maximum degree of result:\nMN = length(alpha) + length(beta);\n\n% Pad to make length n + 1.\nalpha = [ alpha ; zeros(MN - length(alpha), 1) ];\n\n% S represents multiplication by 1/z in spherical Bessel space:\ne = [[1 ; 1./(2*(1:(MN-1)).'+1)], [1 ; zeros(MN-1, 1)], -1./(2*(0:MN-1).'+1)];\nS = spdiags(e, -1:1, MN, MN);\n\ngammaL = rec(S, alpha, beta, -1); % Chebyshev coeffs for the left piece\nS(1,1) = -1;                      % Update S\ngammaR = rec(S, -alpha, beta, 1); % Chebyshev coeffs for the right piece\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%% MATRIX FREE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    function gamma = rec(S, alpha, beta, sgn)\n        % Compute the Legendre coefficients of the convolution on L/R piece.\n        % See Theorem 4.1 of paper.\n        \n        % Initialise scl:\n        N = length(beta);\n        scl = 1./(2*(1:N).'-1);\n        scl(2:2:end) = -scl(2:2:end);\n        \n        % First column of B:\n        vNew = S*alpha;\n        v = vNew;\n        gamma = beta(1)*vNew;\n        beta_scl = scl.*beta;\n        beta_scl(1) = 0;\n        gamma(1) = gamma(1) + vNew(1:N).'*beta_scl;\n        \n        % The scalar case is trivial:\n        if ( length(beta) == 1 )\n            return\n        end\n        \n        % Second column of B:\n        vNew = S*v + sgn*v;\n        vOld = v;\n        v = vNew;\n        vNew(1) = 0;\n\n        gamma = gamma + beta(2)*vNew;\n        beta_scl = -beta_scl*((2 - 0.5)/(2 - 1.5));\n        beta_scl(2) = 0;\n        gamma(2) = gamma(2) + vNew(1:N).'*beta_scl;\n        \n        % Loop over remaining columns using recurrence:\n        for n = 3:N\n            vNew = (2*n-3) * (S * v) + vOld; % Recurrence\n            vNew(1:n-1) = 0;                 % Zero terms \n            gamma = gamma + vNew*beta(n);    % Append to g\n            \n            % Recurrence is unstable for j < k. Correct for upper-tri part:\n            beta_scl = -beta_scl*((n-.5)/(n-1.5));\n            beta_scl(n) = 0;\n            gamma(n) = gamma(n) + vNew(1:N).'*beta_scl;\n            \n            vOld = v;\n            v = vNew;\n            \n        end\n        \n        ag = abs(gamma);\n        mg = max(ag);\n        loc = find(ag > eps*mg, 1, 'last');\n        gamma = gamma(1:loc);\n\n    end\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = clenshawLegendre(x, alpha) \n% Evaluate a Legendre expansion with coefficient alpha at x. \n\nn = length(alpha); \nb_old = 0; \nb_cur = 0; \nfor k = (n-1):-1:1\n  b_new = alpha(k+1) + (2*k + 1)/(k + 1)*x.*b_cur - (k + 1)/(k + 2)*b_old;\n  b_old = b_cur; \n  b_cur = b_new; \nend\nval = alpha(1) + x.*b_cur - .5*b_old; \n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@bndfun/conv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5859352259001328}}
{"text": "% This is the main extended Kalman filter SLAM loop. This script calls all the required\n% functions in the correct order.\n%\n% You can disable the plotting or change the number of steps the filter\n% runs for to ease the debugging. You should however not change the order\n% or calls of any of the other lines, as it might break the framework.\n%\n% If you are unsure about the input and return values of functions you\n% should read their documentation which tells you the expected dimensions.\n\n% Turn off pagination:\nmore off;\n\n% clear all variables and close all windows\nclear all;\nclose all;\n\n% Make tools available\naddpath('tools');\n\n% Read world data, i.e. landmarks. The true landmark positions are not given to the robot\nlandmarks = read_world('../data/world.dat');\n% load landmarks;\n% Read sensor readings, i.e. odometry and range-bearing sensor\ndata = read_data('../data/sensor_data.dat');\n%load data;\n\nINF = 1000;\n% Get the number of landmarks in the map\nN = size(landmarks,2);\n\n% observedLandmarks is a vector that keeps track of which landmarks have been observed so far.\n% observedLandmarks(i) will be true if the landmark with id = i has been observed at some point by the robot\nobservedLandmarks = repmat(false,1,N);\n\n% Initialize belief:\n% mu: 2N+3x1 vector representing the mean of the normal distribution\n% The first 3 components of mu correspond to the pose of the robot,\n% and the landmark poses (xi, yi) are stacked in ascending id order.\n% sigma: (2N+3)x(2N+3) covariance matrix of the normal distribution\nmu = repmat([0.0], (2*N+3), 1);\nrobSigma = zeros(3);\nrobMapSigma = zeros(3,2*N);\nmapSigma = INF*eye(2*N);\nsigma = [[robSigma robMapSigma];[robMapSigma' mapSigma]];\n\n% toogle the visualization type\n%showGui = true;  % show a window while the algorithm runs\nshowGui = false; % plot to files instead\n\n% Perform filter update for each odometry-observation pair read from the\n% data file.\nfor t = 1:size(data.timestep, 2)\n%for t = 1:80\n\n    % Perform the prediction step of the EKF\n    [mu, sigma] = prediction_step(mu, sigma, data.timestep(t).odometry);\n\n    % Perform the correction step of the EKF\n    [mu, sigma, observedLandmarks] = correction_step(mu, sigma, data.timestep(t).sensor, observedLandmarks);\n\n    %Generate visualization plots of the current state of the filter\n    plot_state(mu, sigma, landmarks, t, observedLandmarks, data.timestep(t).sensor, showGui);\n    disp(\"Current state vector:\")\n    disp(\"mu = \"), disp(mu)\nendfor\n\ndisp(\"Final system covariance matrix:\"), disp(sigma)\n% Display the final state estimate\ndisp(\"Final robot pose:\")\ndisp(\"mu_robot = \"), disp(mu(1:3)), disp(\"sigma_robot = \"), disp(sigma(1:3,1:3))\n", "meta": {"author": "kiran-mohan", "repo": "SLAM-Algorithms-Octave", "sha": "e0254ad38cfca2170b2af68c96c183df77c76252", "save_path": "github-repos/MATLAB/kiran-mohan-SLAM-Algorithms-Octave", "path": "github-repos/MATLAB/kiran-mohan-SLAM-Algorithms-Octave/SLAM-Algorithms-Octave-e0254ad38cfca2170b2af68c96c183df77c76252/1_EKF_SLAM/octave/ekf_slam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094302, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5859120925805409}}
{"text": "function [Population,RankSolution] = EnvironmentalSelection(Population,N,alpha)\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 Mengjun Ming\n\n    %% Parameter\n    popSize    = length(Population);\n    NumSeq     = (1:popSize)';\n    RankConvg  = zeros(popSize,1);\n    RankDivs   = zeros(popSize,1);\n    \n    %% Modify the infeasible solutions\n    PopObj = Population.objs;\n    PopCon = Population.cons;\n    z      = min(PopObj,[],1);\n    n      = max(PopObj,[],1);\n    M      = length(z);\n    [W,~]  = UniformPoint(N,M);\n    [~,Region]     = min(pdist2(PopObj-z,W,'cosine'),[],2);  \n    PopObj_2       = PopObj;\n    Infeasible_all = any(PopCon>0,2);\n    if sum(Infeasible_all) ~= 0\n        [~,Region_Fmax] = min(pdist2(n-z,W,'cosine'),[],2); \n        PopObj_2(Infeasible_all,:) = repmat(n,sum(Infeasible_all),1)+sum(max(0,PopCon(Infeasible_all,:)),2)*W(Region_Fmax,:)/norm(W(Region_Fmax,:));\n    end\n    \n    %% Non-dominated sorting\n    CV       = sum(max(0,PopCon),2);\n    Dominate = false(popSize);\n    for i = 1 : popSize-1\n        for j = i+1 : popSize\n            if CV(i) < CV(j)\n                Dominate(i,j) = true;\n            elseif CV(i) > CV(j)\n                Dominate(j,i) = true;\n            else\n                k = any(PopObj(i,:)<PopObj(j,:)) - any(PopObj(i,:)>PopObj(j,:));\n                if k == 1\n                    Dominate(i,j) = true;\n                elseif k == -1\n                    Dominate(j,i) = true;\n                end\n            end\n        end\n    end\n    \n    %% Calculate S(i)\n    S = sum(Dominate,2);\n    \n    %% Calculate R(i)\n    R = zeros(1,popSize);\n    for i = 1 : popSize\n        R(i) = sum(S(Dominate(:,i)));\n    end\n    FrontNo = R + 1;\n    \n    %% Calculate the crowding distance of each solution\n    PopObj   = Population.objs;\n    Distance = pdist2(PopObj,PopObj);\n    Distance(logical(eye(length(Distance)))) = inf;\n    Distance = sort(Distance,2);\n    CrowdDis = Distance(:,floor(sqrt(popSize)));\n    \n    %% Add a middle column\n    MiddleLevel = zeros(popSize,1);\n    \n    %% Environmental selection -- convergence\n    Next = FrontNo == 1;\n    if sum(Next) <= N\n        [~,indx_Convg] = sortrows([FrontNo',-CrowdDis]);\n    elseif sum(Next) > N\n        Del  = Truncation(Population(Next).objs,sum(Next)-N);\n        Temp = find(Next);\n        Next(Temp(Del)) = false;\n        MiddleLevel(Temp(Del)) = 1;\n        [~,indx_Convg] = sortrows([FrontNo',MiddleLevel,-CrowdDis]);        \n    end\n    RankConvg(indx_Convg) = NumSeq;\n    \n    %% Environmental selection -- diversity\n    FrontNo_D = ones(popSize,1);\n    for i = 1:size(W,1)\n        index = find(Region==i);\n        if (~isempty(index))\n            Objs_temp = PopObj_2(index,:);        \n            g_temp = sum((Objs_temp-z).*W(i,:),2);\n            [~,index_FrontNo_D] = sort(g_temp);\n            FrontNo_D(index(index_FrontNo_D)) = (1:length(g_temp))';\n        end\n    end\n    FrontNo_D           = FrontNo_D+Infeasible_all*popSize;\n    [~,indx_divs]       = sortrows([FrontNo_D,-CrowdDis]);\n    RankDivs(indx_divs) = NumSeq;\n    \n    %% Population for next generation\n    RankSolution = alpha*RankConvg+(1-alpha)*RankDivs;\n    [~,Rank]     = sort(RankSolution);\n    Population   = Population(Rank(1:N));\n    RankSolution = 1 : N;\nend\nfunction Del = Truncation(PopObj,K)\n% Select part of the solutions by truncation\n\n    %% Truncation\n    Distance = pdist2(PopObj,PopObj);\n    Distance(logical(eye(length(Distance)))) = inf;\n    Del = false(1,size(PopObj,1));\n    while sum(Del) < K\n        Remain   = find(~Del);\n        Temp     = sort(Distance(Remain,Remain),2);\n        [~,Rank] = sortrows(Temp);\n        Del(Remain(Rank(1))) = true;\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/c-DPEA/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5859120856152596}}
{"text": "%-------------------------------------------------------------------------\n% This is a simulation demo to show multiple trackpaths for tracking the \n% blood cell motion. In this demo, the diameter of the blood cell is 16\n% pixels, so we use 9 trackpaths(in row 23) and the distance between each\n% trackpath is 8 pixels(in row 25).\n% Written by Yuan Chen,Nanjing university of aeronautic and astronautic(2010)\n%-------------------------------------------------------------------------\nclear all; \n%% read the avi file, and calculate the mean image;\ndisplay('Reading and processing demo3.avi file...')\nvideo=aviread('demo3.avi');             % read the avi file;\nvideo = {video.cdata};                  % exracte the avi data(matrix);\nz = 0;\nfor i=1:length(video);                  % change 'color' video to gray;\n    video{i}=rgb2gray(video{i});\n    z = z + double(video{i});    \nend\nz = z/length(video);                    % the mean image;\n[mz,nz] = size(z);\n[mu1,mu2,v1x,v1y,v2x,v2y] = eigfunction(z,7,5);  % calculate the eigen values and eigen vectors of the mean image;\n\n%% the trackpaths generation;\nN = 9;                                  % THE number of trackpath can be set within [5,65];NOTE that,larger N will consume\n                                        % much more processing times,we suggrest that N = 9, and no larger than 16;\nt = 64/(N-1);                           % the distance between each trakcpath;\nT = 64:t:128;                           % T are the radius of the trackpaths(the center(148,150)in the mean image z);\nfor k = 1:length(T)\n    tmp = zeros(size(z));\n    for i = 1:138\n        for j = 1:300            \n            if sqrt((148-i)^2 + (150-j)^2 ) < T(k)+1 && sqrt((148-i)^2 + (150-j)^2 ) >= T(k);\n               tmp(i,j) = 255;\n            end\n        end      \n    end\n    tmp = im2bw(tmp);\n    tmp = bwmorph(tmp,'thin',inf);\n    trackpath{k} = tmp;\nend\ndisplay([num2str(N),' trackpaths are selected to generate ',num2str(N),' ST images...Processing them may take several minutes'])\n%% ST image generation, processing and traces extraction;\nfor i=1:size(trackpath,2)                                   % the number of the generated trackpath;\n    map = [];\n    [xx,yy] = startpoint(trackpath{i});                     % finding the starting point of a trackpath;\n    ind_trackpath = ord_line_indx(trackpath{i},xx,yy);      % order the trackpath points;\n    for j = 1:size(video,2)                                 % ST image generation;\n        line = video{j}(ind_trackpath);\n        map = [map;line];\n    end\n    map = map';\n    Map{i} = map;                                           % store the ST image;\n    display(['processing ST image',int2str(i)])\n    [F,Theta,angle] = J4(map,2.5);                          % raw ST image enhanced by Jacob filter;\n    R = nsf(F);                                             % applying noise supression function;\n    K = angfilter(R,Theta,angle,20);                        % applying orientation filter function;\n    th = graythresh(K);                                     % threshold for cell tracked trackpath;\n    if th <= 0.01;                                          % threshold for none cell tracked trackpath;\n        th = 0.01;\n    end\n    bw = im2bw(K,th);\n    thin = bwmorph(bw,'thin',inf);                          % thinning extracted traces;\n    trace{i} = bwareaopen(thin,10);                         % remove noise trace if its length smaller than 10 pixels;   \nend\n\n%% calculate the trackpaths coordinate and grayscale;\nh = fspecial('gaussian',7);\nfor i = 1:length(trackpath)                                 % denoise;\n    Map_denoise{i} = conv2(Map{i},h,'same');\n    Map_denoise{i} = conv2(Map_denoise{i},h,'same');\nend\n% -------find out the coordinate(X_trackpath,Y_trackpath) and grayscale of the trackpaths;\nfor i = 1:length(trackpath)\n    [xx,yy] = startpoint(trackpath{i});                     % find the start coordinate of a trackpath;\n    ind_trackpath = ord_line_indx(trackpath{i},xx,yy);      % search the trackpath's point from the start point orderly;\n    for j = 1:length(ind_trackpath)             \n        [X_trackpath(j),Y_trackpath(j)] = ind2sub([mz,nz],ind_trackpath(j)); % change the index to (X,Y) coordinate;\n    end    \n    Trackpath_value{i}(:,1) = X_trackpath';     \n    Trackpath_value{i}(:,2) = Y_trackpath';    \n    Trackpath_value{i}(:,3) = 0;\n    [Y_trace,X_trace] = find(trace{i}==1);                  % find extracted trace coordinate;\n    for k = 1:length(Y_trace)                               % store the grayscale of the trace;\n        Trackpath_value{i}(Y_trace(k),3) = Map_denoise{i}(Y_trace(k),X_trace(k));                        \n    end\n    clear X_trackpath;clear Y_trackpath;\nend\n% -------backward mapping the extracted traces to the trackpaths;\nfor i = 1:length(Trackpath_value)\n    for j = 1:size(Trackpath_value{i},1)\n        z(Trackpath_value{i}(j,1),Trackpath_value{i}(j,2)) = Trackpath_value{i}(j,3);\n    end\nend\n% figure,imshow(z,[]),title('The tracking state of trackpaths')\n\n%% trackpaths alignment\nk = round(length(T)/2);                                     % the centerline trackpath;\n% -------turn all trackpaths and all ST images to the same length(or size) as the centreline trackpath and centreline ST image\n% according to the eigen victor v1x,v1y;\nfor i = 1:length(T)\n    p = findpoints(trackpath{k},trackpath{i},v1x,v1y);      % the corresponding relationship between the k and the i trackpaths.\n    P{i} = round(smooth(p));\n    if i~=k                                                    \n        for j = 1:length(P{i})\n            trace_aligned{i}(j,:) = trace{i}(P{i}(j),:); \n            Points_aligned{i}(j,:) = Trackpath_value{i}(P{i}(j),:);\n        end\n    else\n        trace_aligned{i} = trace{i};\n        Points_aligned{i} = Trackpath_value{i};\n    end\nend\n\n% -------base trace generation;\nB_trace = 0;\nfor i = 1:length(trace_aligned)\n    B_trace = B_trace + trace_aligned{i};\nend\n% figure,imshow(B_trace),title('the result of traces mapping')\nB_trace = im2bw(B_trace);\nB_trace = bwmorph(B_trace,'dilate');\nB_trace = bwmorph(B_trace,'thin',inf);\n% figure,imshow(B_trace),title('Base-trace')\n\n%%  fusion of aligned points in trackpaths to calculate the trajectory;\nl = 1;\nfor j = 1:size(Points_aligned{1},1)             % the number of the aligned points in the trackpath;\n    Fusion_points = [];\n    for i = 1:size(Points_aligned,2)            % the number of the trackpaths;\n        if Points_aligned{i}(j,3) > 0           % >0 means the cell is tracked;\n            X = Points_aligned{i}(j,1);         % X coordinate;\n            Y = Points_aligned{i}(j,2);         % Y coordinate;\n            V = Points_aligned{i}(j,3);         % grayvalue of (X,Y);\n            Fusion_points = [Fusion_points,[X;Y;V]];\n        end\n    end\n    if size(Fusion_points,2) > 2                % the cell is tracked by three or more than three trackpths;\n        X_fused(l,1) = mean(Fusion_points(1,:));% the fused position is the center among the aligned points;\n        Y_fused(l,1) = mean(Fusion_points(2,:)); \n        l = l+1;\n    elseif size(Fusion_points,2) == 2           % the cell is tracked by two trackpaths(Eq.(15)in the paper);\n        x1 = Fusion_points(1,1); x2 = Fusion_points(1,2);\n        y1 = Fusion_points(2,1); y2 = Fusion_points(2,2);\n        v1 = Fusion_points(3,1); v2 = Fusion_points(3,2);\n        [X_fused(l,1),Y_fused(l,1)] = fusion2p(x1,y1,x2,y2,v1,v2,0.4); % the fused position calculation;\n        l = l+1;\n    elseif size(Fusion_points,2) ==1            % the cell is tracked by only one trackpath;\n        X_fused(l,1) = Fusion_points(1,1);      % no fusion is needed;\n        Y_fused(l,1) = Fusion_points(2,1);\n        l = l+1;\n    end\nend\n   \n   X_trajectory = round(X_fused);               % calculated trajectory;\n   Y_trajectory = round(Y_fused);\n   X_smooth = round(smooth(X_fused,10));        % smooth process to prevent jagged trajectory;\n   Y_smooth = round(smooth(Y_fused,10));\nfor i = 1:length(X_fused)\n    z(X_trajectory(i),Y_trajectory(i)) = 255;\nend\nfigure,imshow(z,[]);title(['Blood cell tracking by ',num2str(N), ' trackpaths(black line)'])\nhold on;plot(Y_smooth,X_smooth,'r')\n\n% -------the real trajectory of the cell;\nx = 76:228;\ny = 124*sin(pi/162*x+80.32);\ny = round(-y+151);           \nhold on,plot(x,y);\nh = legend('Tracked trajectory','Real trajectory',2);\n\n%% calculating the error and variance;\nfor i = 1:length(X_trajectory)                  % by finding the closest points in the real trajectory to calculate the error;\n    for j = 1:length(x)                         \n        dis(j) = sqrt((X_trajectory(i) - y(j))^2 + (Y_trajectory(i) - x(j))^2);\n        Error(i) = min(dis);\n    end\nend\nES = [mean(Error),std2(Error)];                 % mean error and standard deviation;\ndisplay(['The Error and Variance of the tracked tracjectory by using ',num2str(N),' trackpaths are'])\ndisplay([num2str(ES(1)) ' pixels and ' num2str(ES(2)),' pixels'])", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/30253-blood-cells-tracking-and-measurement-by-using-spatiotemporal-images-analysis/BloodCellsTracking/demo3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5859120835790022}}
{"text": "x = uiuc_sample;\nx = x(1:256, 1:256);\n\nWop = wavelet_factory_2d(size(x));\n%%\n[Sx, Ux] = scat(x, Wop);\n\n%%\nplot_meta(Sx);", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/test/display/test_plot_meta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5859120755955922}}
{"text": "function log_evidence = ldae_is_variants(words, topics, topic_prior, num_samples, variant, variant_iters)\n%LDAE_IS_VARIANTS approximate evidence of LDA model, importance sampling with choice of q-distributions\n%\n% log_evidence = ldae_is_variants(words, topics, topic_prior[, num_samples=1000[, variant=3[, variant_iters=1]]]);\n%\n% Inputs:\n%             words 1xNd\n%            topics TxV each row is a distribution over a vocabulary of size V \n%       topic_prior 1xT parameters of Dirichlet from which document topic vector is drawn\n%       num_samples 1x1 default 1000\n%           variant 1x1 1: prior, 2: q(z) = \\prod p(z_n|w_n), 3: q(z) = \\prod(z_n|w_n,hacky_pseudo_counts)\n%                       Default is 3, as that seems to work best.\n%     variant_iters 1x1 If variant needs iterative updates, use this number\n%\n% Outputs:\n%     log_evidence  1x1 \n\n% Iain Murray, January 2009\n\n[T, V] = size(topics);\nNd = length(words);\n\nif ~exist('num_samples', 'var')\n    num_samples = 1000;\nend\nif ~exist('variant', 'var')\n    variant = 3;\nend\nif ~exist('variant_iters', 'var')\n    variant_iters = 1;\nend\n\ntopic_prior = topic_prior(:)';\ntopic_alpha = sum(topic_prior);\n%topic_mean = topic_prior / topic_alpha;\n\nif variant == 1\n    % Importance sample from prior\n    qstar = repmat(topic_prior', 1, Nd); % T x Nd\n    qq = bsxfun(@rdivide, qstar, sum(qstar, 1));\nelse\n    % Take w_n into account when picking z_n\n    qstar = bsxfun(@times, topic_prior', topics(:, words)); % T x Nd\n    qq = bsxfun(@rdivide, qstar, sum(qstar, 1));\n\n    if variant == 3\n        for i = 1:variant_iters\n            % Now create pseudo-counts from qq and recompute qq using them\n            pseudo_counts = bsxfun(@minus, topic_prior' + sum(qq, 2), qq);\n            qstar = bsxfun(@times, pseudo_counts, topics(:, words)); % T x Nd\n            qq = bsxfun(@rdivide, qstar, sum(qstar, 1));\n        end\n    end\nend\n\n% Draw samples from the q-distribution\nsamples = zeros(Nd, num_samples);\nfor n = 1:Nd\n    samples(n, :) = discreternd(num_samples, qq(:, n))'; % Nd x num_samples\nend\n\n% Evaluate P(z, v) at samples and compare to q-distribution\nNk = histc(samples, 1:T, 1); % T x num_samples\nlog_pz = sum(gammaln(bsxfun(@plus, Nk, topic_prior')), 1) ...\n        + gammaln(topic_alpha) - sum(gammaln(topic_prior)) ...\n        - gammaln(Nd + topic_alpha); % 1 x num_samples\nlog_w_given_z = zeros(1, num_samples);\nfor n = 1:Nd\n    log_w_given_z = log_w_given_z + log(topics(samples(n,:), words(n)))';\nend\nlog_joint = log_pz + log_w_given_z;\n%\nlog_qq = zeros(1, num_samples);\nfor n = 1:Nd\n    log_qq = log_qq + log(qq(samples(n,:), n))';\nend\nlog_weights = log_joint - log_qq;\nlog_evidence = logsumexp(log_weights(:)) - log(length(log_weights));\n\n", "meta": {"author": "jacobeisenstein", "repo": "SAGE", "sha": "5776655f6c09f2c24a96485a0985660e64664415", "save_path": "github-repos/MATLAB/jacobeisenstein-SAGE", "path": "github-repos/MATLAB/jacobeisenstein-SAGE/SAGE-5776655f6c09f2c24a96485a0985660e64664415/3rd-party/lda-eval/ldae_is_variants.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.585912075310089}}
{"text": "classdef TSLDirectionKey < directionColorKey\n  % converts directions to rgb values\n    \n  methods\n    \n    function dM = TSLDirectionKey(varargin)\n      dM@directionColorKey(varargin{:});\n      dM.sym = dM.sym.Laue;\n      dM.sR = dM.sym.fundamentalSector;\n      \n      if ismember(dM.sym.id,[2,5,8,11,18,21,24,27,35,42])\n        warning('Not a topological correct colormap! Green to blue colorjumps possible');\n      end\n    end\n  \n    function rgb = direction2color(dM,h,varargin)      \n      % in TSL all fundamental sectors are colorized with white in the center\n  \n      % project to fundamental region\n      h = h.project2FundamentalRegion(dM.sym);\n      \n      % this should become white if not stated differently\n      center = dM.sR.center;\n\n      % compute angle of the points \"sh\" relative to the center point \"center\"\n      % this should be between 0 and 1\n      v = dM.sR.vertices;\n      if ~isempty(v)\n        v = v(1);\n      else\n        v  = dM.sym.aAxisRec;\n      end\n      [radius,rho] = polarCoordinates(dM.sR,h,center,v);\n      \n      % white center\n      radius = 0.5+radius./2;\n\n      % compute the color vector on the sphere\n      v = vector3d('rho',rho,'theta',radius.*pi);\n\n      % post processing of the color vector\n      % by default we have white at the z, black at the -z, red\n      % at x and green and blue at 120 and 240 degree accordingly\n      % post rotate the color\n      v = dM.colorPostRotation * v;\n\n      % compute rgb values\n      rgb = ar2rgb(mod(v.rho./ 2 ./ pi,1),v.theta./pi,get_option(varargin,'grayValue',1),'noHueCorrection');      \n      \n    end\n  end\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/plotting/directionColorKeys/TSLDirectionKey.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5859120732738319}}
{"text": "function [x_pred, y_pred]= convert_trans_and_scale(pred_point_raw, mid_point, scale)\n   % 1. The input heatmap is 248 by 248, which is rescaled from a crop, introducing\n   %    a scale\n   % 2. The crop comes from the original image, and introduce a translation\n   % Summary: This script is to do the backwards mapping, back to the original position.\n   % (1) First, find the position in the cropped image\n   % (2) Second, find the position in the original image\n\n   % Use (scale) for the scale. [180, 280] is current value.\n   % Consult [gen_cropped_test_images.m]. Make sure use same scale.\n   % Officially, scale is w.r.t. 200 px height\n   human_bbox_wid = 180 * scale;\n   human_bbox_ht = 280 * scale;\n   \n   % Prepare [x_min, y_min] for translation\n   x_min = mid_point(1) - human_bbox_wid/2.0;\n   y_min = mid_point(2) - human_bbox_ht/2.0;\n\n   % Based on translation, scale, and output, find input\n   [x_pred, y_pred] = find_pos_for_org_image(pred_point_raw, human_bbox_wid, human_bbox_ht, x_min, y_min);\nend\n\n\nfunction [x0, y0] = find_pos_for_org_image(pos_248, human_bbox_wid, human_bbox_ht, x_min, y_min)\n    [x1, y1] = find_pos_for_cropped_image(pos_248, human_bbox_wid, human_bbox_ht);\n    \n    x0 = x1 + x_min;\n    y0 = y1 + y_min;\n    \n    pos_org = [x0, y0];\nend\n\n\nfunction [x1, y1] = find_pos_for_cropped_image(pos_248, human_bbox_wid, human_bbox_ht)\n   x2 = pos_248(1);\n   y2 = pos_248(2);\n   \n   x1 = int64((x2 * human_bbox_wid)/248.0);\n   y1 = int64((y2 * human_bbox_ht)/248.0);\n   \n   pos_cropped = [x1, y1];\nend\n\n", "meta": {"author": "Guanghan", "repo": "GNet-pose", "sha": "c70e0fc65b290e68a16ca3040a70300f9c2bee44", "save_path": "github-repos/MATLAB/Guanghan-GNet-pose", "path": "github-repos/MATLAB/Guanghan-GNet-pose/GNet-pose-c70e0fc65b290e68a16ca3040a70300f9c2bee44/testing/utils_eval_mpii/convert_trans_and_scale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5859120732738318}}
{"text": "function b_im = Blur_IM( im, H )\n\n[h w ch]  =  size(im);\n\nif ch==3\n    m1  = im(:,:,1);\n    m2  = im(:,:,2);\n    m3  = im(:,:,3);    \n    b_im(:,:,1)  =  reshape( H*m1(:), h, w );\n    b_im(:,:,2)  =  reshape( H*m2(:), h, w );\n    b_im(:,:,3)  =  reshape( H*m3(:), h, w );\nelse\n    b_im  =  reshape( H*im(:), h, w );\nend", "meta": {"author": "lbasek", "repo": "image-denoising-benchmark", "sha": "9d753198d715b7628c8e7d9259dfa5c219d033ea", "save_path": "github-repos/MATLAB/lbasek-image-denoising-benchmark", "path": "github-repos/MATLAB/lbasek-image-denoising-benchmark/image-denoising-benchmark-9d753198d715b7628c8e7d9259dfa5c219d033ea/algoritms/matlab/NCSR/Utilities/Blur_IM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5859120629686615}}
{"text": "classdef H0Kernel < Kernel\n    properties\n        k; \n        C; % Such that G(r) = C*besselh(0,1,k*r)\n        % Hankel function of the first kind. \n    end\n    methods\n        function[this] = H0Kernel(kk,CC)\n            if nargin == 0\n                kk = 1;\n            end\n            if nargin <= 1\n                CC = 1;                                \n            end\n            this.k = kk;\n            this.C = CC;\n            Jk = J0Kernel(kk);\n            Yk = Y0Kernel(kk);\n            modelKern = this.C*(Jk + 1i*Yk);\n            this.func = modelKern.func;\n            this.der = modelKern.der;\n            this.scalFunc = modelKern.scalFunc;\n            this.lim0 = this.C*(Jk.lim0 + 1i*Yk.lim0);\n        end\n        function[out] = dilatation(this,lambda)\n            lim0keep = this.lim0;\n            out = H0Kernel(this.k*lambda,this.C);\n            out.lim0 = lim0keep;\n        end\n        function[out] = mtimes(this,mu)\n            if isa(this,'Kernel')\n                assert(and(isa(mu,'double'),isscalar(mu)));\n                out = H0Kernel(this.k,this.C*mu);\n            else\n                out = mtimes(mu,this);\n            end\n        end\n        function[rq] = radialQuadKernel(this,a,tol,varargin)\n            modelKern = J0Kernel(this.k) + 1i*Y0Kernel(this.k);\n            rqTemp = modelKern.radialQuadKernel(a,tol/abs(this.C),varargin{:});\n            rq = this.C*rqTemp;\n        end\n    end\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/openEbd/Kernels/H0Kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5859120629686614}}
{"text": "function N = mtimes(K, M)\n% N = mtimes(K, M)\n%\n%  kronMatrix multiplication;\n%     multiply a kronMatrix by a matrix, a vector, or by\n%     another kronMatrix (if possible),\n%     \n%     \n\n% 9/2002 L. Perrone \n% written for new kronMatrix class\n\n% 6/2003 J. Nagy\n% some minor modifications to incorporate new subsref.m capabilities\n\nif (isa(K, 'kronMatrix'))\n   if isa(M, 'double')\n      N = left_mtimes(K, M);\n   elseif isa(M,'kronMatrix')\n      if length(M) == 1\n         sizeMa = size(M.a{1});\n         sizeMb = size(M.b{1});\n         l = length(K);\n         Anew = cell(l,1);\n         Bnew = cell(l,1);\n         for i = 1:l\n           sizeKa = size(K.a{i});\n           sizeKb = size(K.b{i});\n           if sizeKa(2)==sizeMa(1) & sizeKb(2)==sizeMb(1)\n             Anew{i} = K.a{i} * M.a{1};\n             Bnew{i} = K.b{i} * M.b{1};\n           else\n             error('Kron factors must be of compatible sizes for multiplication')\n           end\n         end % end the for i=1:l loop\n         N = kronMatrix(Anew,Bnew);\n      elseif length(K) == 1\n         sizeKa = size(K.a{1});\n         sizeKb = size(K.b{1});\n         l = length(M);\n         Anew = cell(l,1);\n         Bnew = cell(l,1);\n         for i = 1:l\n           sizeMa = size(M.a{i});\n           sizeMb = size(M.b{i});\n           if sizeKa(2)==sizeMa(1) & sizeKb(2)==sizeMb(1)\n             Anew{i} = K.a{1} * M.a{i};\n             Bnew{i} = K.b{1} * M.b{i};\n           else\n             error('Kron factors must be of compatible sizes for multiplication')\n           end\n         end % end the for i=1:l loop\n         N = kronMatrix(Anew,Bnew);\n      else \n         error('This currently only works if one of the kronMatrix objects has one term in it''s sum.')\n      end\n   else % M isn't a 'double' or a 'kronMatrix'\n      error('Wrong input arguments')\n   end % end the case when K is a 'kronMatrix'\n\nelseif isa(K,'double') & isa(M,'kronMatrix')\n   N = right_mtimes(K, M);\nelse\n   error('Wrong input arguments')\nend\n\n", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/Extra/prblur_tools/@kronMatrix/mtimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5858899079204036}}
{"text": "% Script demonstrating usage of the bpdndl function.\n%\n% Author: Brendt Wohlberg <brendt@lanl.gov>  Modified: 2015-07-30\n%\n% This file is part of the SPORCO library. Details of the copyright\n% and user license can be found in the 'Copyright' and 'License' files\n% distributed with the library.\n\n\n% Training images\nS0 = zeros(512, 512, 5);\nS0(:,:,1) = single(stdimage('lena.grey')) / 255;\nS0(:,:,2) = single(stdimage('barbara.grey')) / 255;\nS0(:,:,3) = single(stdimage('kiel.grey')) / 255;\nS0(:,:,4) = single(rgb2gray(stdimage('mandrill'))) / 255;\ntmp = single(stdimage('man.grey')) / 255;\nS0(:,:,5) = tmp(101:612, 101:612);\n\n\n%Reduce images size to speed up demo script\ntmp = zeros(256, 256, 5);\nfor k = 1:size(S0,3),\n  tmp(:,:,k) = imresize(S0(:,:,k), 0.5);\nend\nS0 = tmp;\n\n\n% Extract all 8x8 image blocks, reshape, and subtract block means\nSB = imageblocks(S0, [8 8]);\nSB = reshape(SB, size(SB,1)*size(SB,2), size(SB,3));\nS = bsxfun(@minus, SB, mean(SB, 1));\n\n\n% Construct initial dictionary\nD0 = randn(size(S,1), 64);\n\n\n% Set up bpdndl parameters\nlambda = 0.2;\nopt = [];\nopt.Verbose = 1;\nopt.MaxMainIter = 1000;\nopt.rho = 50*lambda + 0.5;\nopt.sigma = size(S,2)/200;\nopt.AutoRho = 1;\nopt.AutoRhoPeriod = 10;\nopt.RhoRsdlRatio = 2;\nopt.RhoScaling = 5;\nopt.AutoRhoScaling = 1;\nopt.AutoSigma = 1;\nopt.AutoSigmaPeriod = 10;\nopt.XRelaxParam = 1.8;\nopt.DRelaxParam = 1.8;\n\n% Do dictionary learning\n[D, X, optinf] = bpdndl(D0, S, lambda, opt);\n\n\n% Display learned dictionary\nfigure;\nimdisp(tiledict(D, [8 8]));\n\n% Plot functional value evolution\nfigure;\nplot(optinf.itstat(:,2));\nxlabel('Iterations');\nylabel('Functional value');\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/ConvSR_Image_Fusion_Codes/sporco/Demo/demo_bpdndl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5858899056722219}}
{"text": "function [coef, res, wres, ymoco] = robust_ar_fit( y, Pmax )\n    [~, res] = ar_fit(y, Pmax);\n    \n    w = wfun(res);\n    [coef, ~] = ar_fit(w.*y, Pmax);\n    \n    res     = filter([1; -coef(2:end)], 1, y-coef(1));\n    wres    = filter([1; -coef(2:end)], 1, w.*y-coef(1));\n    \n    ymoco   = filter(1, [1; -coef(2:end)], w.*res);\nend\n\nfunction w = wfun(r)\n    s = mad(r, 0) / 0.6745;\n    r = r/s/4.685;\n    \n    w = (1 - r.^2) .* (r < 1 & r > -1);\nend", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/FuncRegistry/UserFunctions/iWLS/robust_ar_fit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.585889900432951}}
{"text": "function [Gx,Gy] = gradient2( I )\n% Compute numerical gradients along x and y directions.\n%\n% For 2D arrays identical to Matlab's gradient() with a spacing value of\n% h=1 but ~10-20x faster (due to mexed implementation). Like gradient(),\n% computes centered derivatives in interior of image and uncentered\n% derivatives along boundaries. For 3D arrays computes x and y gradient\n% separately for each channel and concatenates the results.\n%\n% This code requires SSE2 to compile and run (most modern Intel and AMD\n% processors support SSE2). Please see: http://en.wikipedia.org/wiki/SSE2.\n%\n% USAGE\n%  [Gx,Gy] = gradient2( I )\n%\n% INPUTS\n%  I      - [hxwxk] input k channel single image\n%\n% OUTPUTS\n%  Gx     - [hxwxk] x-gradient (horizontal)\n%  Gy     - [hxwxk] y-gradient (vertical)\n%\n% EXAMPLE\n%  I=single(imread('peppers.png'))/255;\n%  tic, [Gx1,Gy1]=gradient(I,1); toc\n%  tic, [Gx2,Gy2]=gradient2(I); toc\n%  isequal(Gx1,Gx2), isequal(Gy1,Gy2)\n%\n% See also gradient, gradientMag\n%\n% Piotr's Image&Video Toolbox      Version 3.00\n% Copyright 2012 Piotr Dollar & Ron Appel.  [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\n[Gx,Gy]=gradientMex('gradient2',I);\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/channels/gradient2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5858898895829566}}
{"text": "function [ind,ind2,stats] = Gaussian_mix(x,niter,basepts,verbose,doplot, doplot2)\n% Two-Gaussian mixture model\n%\n% :Usage:\n% ::\n%\n%     [ind,ind2,stats] = Gaussian_mix(x,niter,basepts,verbose,doplot, doplot2)\n%\n% :Inputs:\n%\n%   **x:**\n%        data\n%\n%   **iter:**\n%        number of iterations\n%\n%   **basepts:**\n%        number of baseline pts at start of run. The modal class in the\n%        baseline period is defined as the 0-class\n%\n% :Outputs:\n%\n%   **ind:**\n%        indicator function of class belonging\n%\n%   **ind2:**\n%        indicator function of class belonging where 3 consecutive points\n%        are needed to switch states\n%\n%   **mu:**\n%        mean vector\n%\n%   **sigma:**\n%        standard deviation\n%\n%   **p:**\n%        probability that latent class random variable (delta) is equal\n%        to [0,1]\n%\n% :Examples:\n% ::\n%\n%    [ind,ind2,stats] = Gaussian_mix(linear_detrending(dat),20);\n%    % dat is n subjects by t time points\n%    % plotting is on\n%\n%    % Simulated data\n%    r = normrnd(1, 1, 200, 1); r(1:50) = r(1:50) + normrnd(3, 1, 50, 1);\n%    [ind, ind2, stats] = Gaussian_mix(r, 50, [], 0, 1);\n% \n% We recommend 50 iterations\n\n% ..\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %\n    % Set up inputs\n    %\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% ..\n\n    if ~(exist('doplot')==1) || isempty(doplot), doplot = 1; end\n    if ~(exist('doplot2')==1) || isempty(doplot2), doplot2 = 1; end\n    if ~(exist('verbose')==1) || isempty(verbose), verbose = 1; end\n    if ~(exist('basepts')==1) || isempty(basepts), basepts = 1:length(x); end\n\n    % make sure it's a column vector or vectors\n    if size(x,1) ~= length(x), x = x'; end\n\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %\n    % Iterative mode\n    %\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    if size(x,2) > 1\n        % multiple data vectors, run this function iteratively\n\n        IND = []; IND2 = [];\n        verbose = 0;\n        if doplot, nrows = ceil(sqrt(size(x,2))); tor_fig(nrows,nrows); end\n\n        for datavec = 1:size(x,2)\n            if doplot, subplot(nrows,nrows,datavec);  end\n\n            [IND(:,datavec),IND2(:,datavec),stats(datavec)] = Gaussian_mix(x(:,datavec),niter,basepts,verbose,doplot);\n        end\n\n        % save group stats/output\n\n        ind = IND; ind2 = IND2;\n        S.cp = cat(1,stats.cp);\n        S.cnt = cat(1,stats.cnt);\n        S.tot = cat(1,stats.tot);\n        S.longest = cat(1,stats.longest);\n        S.firstlen = cat(1,stats.firstlen);\n        S.totaldur = cat(1,stats.totaldur);\n        S.mu = cat(2,stats.mu);\n        S.sigma = cat(2,stats.sigma);\n        S.p = cat(1,stats.p);\n        S.ind2 = IND2;\n        S.ind = ind;\n\n        S.cpmean = nanmean(S.cp);\n        S.meancnt = mean(S.cnt);\n        S.meantot = mean(S.tot);\n        S.meantotaldur =  mean(S.totaldur);\n        S.meanlongest = mean(S.longest);\n        S.meanfirst = mean(S.firstlen);\n\n        ind = mean(IND2')';     % group prob. of activation state\n        stats = S;\n\n        if doplot\n            % group plot\n            tor_fig; plot(ind,'k','LineWidth',2);\n            hold on; plot(S.cpmean,ind(round(S.cpmean)),'ko','MarkerSize',12,'MarkerFaceColor',[.5 .5 .5]);\n            xlabel('Time (images)'); ylabel('Probability of active state.');\n        end\n\n\n        return\n    end\n\n\n\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    %\n\n    % Initial values for EM-algorithm\n\n    %\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n    n = length(x);\n\n\n\n    gam =zeros(n,2);\n\n    p = [0.5 0.5];                      % probability that delta is [0,1]\n\n    %mu = normrnd(0,1,1,2);              % means of Gaussian\n\n    mu = zeros(1,2);\n    mu(1) = min(x);\n    mu(2) =max(x);\n\n    sigma = zeros(1,1,2);               % covariance matrices\n\n    for i=1:2,\n\n        sigma(:,:,i) = std(x);\n\n    end\n\n\n\n\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    %\n\n    % EM -algorithm - repeat niter times\n\n    %\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    if verbose,  fprintf(1,'iteration %03d',0); end\n\n    for t=1:niter,\n\n\n\n        if verbose, fprintf(1,'\\b\\b\\b%03d',t); end\n\n\n\n        % E-step\n\n\n\n        for i=1:2,\n\n            gam(:,i) = p(i)*det(sigma(:,:,i))^(-0.5)*exp(-0.5*sum((x'-repmat(mu(:,i),1,n))'*inv(sigma(:,:,i)).*(x'-repmat(mu(:,i),1,n))',2));\n\n        end\n\n\n\n        gam = gam./repmat(sum(gam,2),1,2);            % Normalize\n\n\n\n\n\n        % M-step\n\n\n\n        for i=1:2,\n\n            mu(:,i) = (x'*gam(:,i))./sum(gam(:,i));                                                               % Update mean\n\n            ind = (gam>0.5);\n            dev = x-repmat(mu(:,i),n,1);\n\n            sigma(:,:,i) = dev' *(gam(:,i).* dev) ./ sum(gam(:,i));           % Update covariance\n\n            p(i) = mean(gam(:,i));                                                                                % Update probability\n\n        end\n\n        pooleds = sigma(:,:,1).*p(1) + sigma(:,:,2).*p(2);\n        sigma(:,:,1:2) = pooleds;\n\n    end\n\n\n\n\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    %\n\n    % Classify points\n\n    %\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n    ind = (gam>0.5);\n\n    [a,b]=max(mu);\n\n\n\n    % Classify points using 3 consecutive alternate states in order to\n\n    % switch states\n\n\n\n    ind2 = zeros(n,1);\n\n    state = 0;\n\n    len = 3;\n\n    for i=1:(length(ind(:,b))-(len-1)),\n\n        if (state == 0),\n\n            if(sum(ind(i:(i+(len-1)),b)) == len),\n\n                state = 1;\n\n            end;\n\n        elseif (state == 1),\n\n            if(sum(ind(i:(i+(len-1)),b)) == 0),\n\n                state = 0;\n\n            end;\n\n        end;\n\n        ind2(i) = state;\n\n    end;\n\n    ind2((length(ind(:,b))-(len-1)):end) = state;\n\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %\n    % re-format output and do baseline pts.\n    %\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n    ind = ind(:,1) - ind(:,2);\n    %ind2 = ind2(:,1) - ind2(:,2);\n\n    % wh is the class number (0 = class #1, 1 = class #2) of the most frequent\n    % baseline class\n    classes = [0 1];\n    wh = [sum(ind2(1:basepts) == 0) sum(ind2(1:basepts) == 1)]; wh = find(wh==max(wh)); wh = wh(1);\n    baseclass = classes(wh);    % 0 or 1\n\n    whbase = find(ind2 == baseclass);\n    whactive = find(ind2 ~= baseclass);\n\n    % define so that base class is 0, active class is 1\n    ind2(whbase) = 0; ind2(whactive) = 1;\n\n\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %\n    % output stats and stats on runs\n    %\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    stats.cp = find(ind2);  % first point in active state -- CP estimate\n    if isempty(stats.cp), stats.cp = NaN;\n    else\n        stats.cp = stats.cp(1);\n    end\n\n    [stats.cnt,stats.tot,lenmat] = cnt_runs(ind2);\n    stats.longest = max(lenmat); stats.firstlen = lenmat(1);\n    stats.totaldur = find(ind2);\n    if isempty(stats.totaldur) || length(stats.totaldur) < 2, stats.totaldur = 0;\n    else\n        stats.totaldur = stats.totaldur(end) - stats.totaldur(1);\n    end\n    stats.mu = mu'; stats.sigma = squeeze(sigma); stats.p = p; stats.gam = gam;\n\n\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    %\n\n    % Plot results\n\n    %\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n    if doplot\n\n        xx = 1:length(x);\n\n\n        hold off;\n        plot(xx,x,'k','LineWidth',1);\n        hold on;\n\n        wh = find(~ind2); xtmp = x; xtmp(wh) = NaN;\n        plot(xx,xtmp,'b','LineWidth',2);\n\n\n        wh = find(ind2);xtmp = x; xtmp(wh) = NaN;\n        plot(xx,xtmp,'g','LineWidth',2);\n\n        %plot(ind2,'r','LineWidth',2);\n\n        %axis([0 length(ind) -0.1 1.1])\n\n\n    end\n\n    if doplot2\n\n        [h, x] = hist(x, ceil(length(x) ./ 5));\n        h1 = normpdf(x, stats.mu(1), stats.sigma(1));\n        h2 = normpdf(x, stats.mu(2), stats.sigma(2));\n\n\n        stats.cnt1 = sum(ind > 0);\n        stats.cnt2 = sum(ind < 0);\n\n        try\n            h1 = moving_average('gaussian', h1', 8)';\n            h2 = moving_average('gaussian', h2', 8)';\n        catch\n            disp('problem with moving average')\n        end\n        \n        h1 = stats.cnt1 .* h1 ./ sum(h1);\n        h2 = stats.cnt2 .* h2 ./ sum(h2);\n\n        create_figure('Gaussian mixture plot');\n        plot(x, h, 'k', 'LineWidth', 2);\n        hold on;\n        plot(x, h1, 'r', 'LineWidth', 2);\n        plot(x, h2, 'b', 'LineWidth', 2);\n\n    end\n\n    return\n\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/hewma_utility/Gaussian_mix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5858755593609025}}
{"text": "function pass = test_syntax( pref )\n% Check the Chebfun2v constructor for different syntax.\n% Alex Townsend, March 2013.\n\nif ( nargin < 1 )\n    pref = chebfunpref;\nend\ntol = 1e5 * pref.cheb2Prefs.chebfun2eps;\n\nfor jj = 1 : 2\n    \n    f = @(x,y) jj*sin(x.*y);  % simple function.\n    g = @(x,y ) jj*cos(x.*y);\n    \n    fd = diskfun(f);\n    gd = diskfun(g);\n\n    F1 = diskfunv( f, g);\n    F2 = diskfunv( fd, gd);\n    F3 =  [ fd; gd]; \n    \n    pass(1, jj) = ( norm(F1 - F2) < tol ); \n    pass(2, jj) = ( norm(F2 - F3) < tol );\n    \nend\npass = pass(:)';\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/diskfunv/test_syntax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5858215004029431}}
{"text": "function start_points = perform_lloyd_mesh(vertex,faces, start_points, options)\n\n% perform_lloyd_mesh - perform lloyd relaxation to sample point on a mesh\n%\n%   start_points = perform_lloyd_mesh(vertex,faces, start_points, options);\n%\n%   Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\n\nif size(vertex,1)>size(vertex,2)\n    vertex = vertex';\nend\nif size(faces,1)>size(faces,2)\n    faces = faces';\nend\n\nniter_lloyd = getoptions(options, 'niter_lloyd', 1);\nif niter_lloyd>1\n    for i=1:niter_lloyd\n        start_points = perform_lloyd_mesh(vertex,faces, start_points, options)\n        options.lambda = []; % enfore recomputing\n    end\n    return;\nend\n\nlambda = getoptions(options, 'lambda', []);\nedges_id = getoptions(options, 'edges_id', []);\nQ = getoptions(options, 'Q', []);\nif isempty(lambda) || isempty(edges_id) || isempty(Q)\n    % update voronoi\n    [Q,DQ, ve, edges_id, lambda] = compute_voronoi_mesh(vertex,faces, start_points, options);\nend\n\n% compute distances for start\nne = length(lambda);\nn = size(vertex,2);\n% compute edge length\nd = diff( reshape(vertex(:,edges_id'), [3 ne 2]), 1, 3 );\nd = sqrt( sum(d.^2,1) );\nd1 = (1-lambda).*d;\nd2 = lambda.*d;\n% compute initial values for FM\nvalues = zeros(n,1); cnt = zeros(n,1);\nfor i=1:ne\n    values(edges_id(1,i)) = values(edges_id(1,i)) + d1(i);\n    cnt(edges_id(1,i)) = cnt(edges_id(1,i)) + 1;\n    values(edges_id(2,i)) = values(edges_id(2,i)) + d1(i);\n    cnt(edges_id(2,i)) = cnt(edges_id(2,i)) + 1;\nend\nvalues = values./cnt;\n% perform FM from edge points\npts = unique( edges_id(:) );\noptions.values = values(pts);\noptions.values = [];\nD = perform_fast_marching_mesh(vertex, faces, pts, options);\n\n% seed new locations\nnstart = length(start_points);\nfor i=1:nstart\n    I = find(Q(:,1)==i);\n    [v,k] = max(D(I));\n    start_points(i) = I(k);\nend\nstart_points = start_points(:);", "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/perform_lloyd_mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5858215004029431}}
{"text": "% Extract critical features (junctions and endpoints).\n%\n% Rougly follows procedure of Liu et al. \"Identification of Fork Points...\" IEEE\n% TAPMI\n%\n% For a circular stroke, there are no \"features\" by this definition.\n% Thus, for any partition of the pixels into regions, there should\n% be at least one feature for the tracing algorithm to find.\n%\n% Input\n%  T: [n x n boolean] thinned image.\n%    images are binary, where true means \"black\"\n%\n% Output\n%  SN: [n x n boolean] extracted features.\nfunction SN = extract_junctions(T)\n\n    SE = bwmorph(T,'endpoints');\n    SB = T; % black pixels\n    sz = size(T,1);\n    \n    lutS3 = makelut( @(P)fS3(P) , 3);\n    S3 = applylut(T,lutS3);\n\n    % final criteria\n    SN = SE | (SB & S3);\n    \n    % Check to see that each connected component has a feature.\n    % This is necessary to process circles in the image.\n    CC = bwconncomp(T,8);\n    nCC = CC.NumObjects;\n    for c=1:nCC\n       \n       pid = CC.PixelIdxList{c};       \n       \n       % We have a circle. Circles are generally drawn from the\n       % top, we choose the top pixel here\n       if sum(SN(pid))==0\n          [irow,icol] = ind2sub(sz,pid);\n          sel = argmin(irow);\n          SN(pid(sel)) = true;           \n       end\n       \n    end\n       \nend\n\n% See Liu et al.\nfunction Y=fS3(P)\n    sz = size(P);\n    assert(isequal(sz,[3 3]));\n    \n    % Get cross number\n    NC = fNC(P);\n    \n    % Count black pixels\n    PM = P;\n    PM(2,2) = false;\n    NB = sum(PM(:));\n    \n    % Criteria\n    Y = (NC >= 3-eps) || (NB >= 4-eps);\nend\n\n% See Liu et al.\nfunction Y=fNC(P)       \n    sum = 0;\n    for i=0:7\n        sum = sum + abs( P(fIP(i+1)) - P(fIP(i)) );\n    end\n    Y = sum./2;\nend\n\n% See Liu et al.\nfunction newlindx = fIP(lindx)\n    switch lindx\n        case {0,8}\n            i=1; j=2;\n        case 1\n            i=1; j=3;\n        case 2\n            i=2; j=3;\n        case 3\n            i=3; j=3;\n        case 4\n            i=3; j=2;\n        case 5\n            i=3; j=1;\n        case 6\n            i=2; j=1;\n        case 7\n            i=1; j=1;\n    end\n    newlindx = sub2ind([3 3],i,j);\nend", "meta": {"author": "brendenlake", "repo": "BPL", "sha": "2c7f679bb0055f29cbade7ef099897c3342bcb79", "save_path": "github-repos/MATLAB/brendenlake-BPL", "path": "github-repos/MATLAB/brendenlake-BPL/BPL-2c7f679bb0055f29cbade7ef099897c3342bcb79/bottomup/skeleton/extract_junctions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.5858214856638957}}
{"text": "classdef prtPreProcFilter < prtPreProc\n    % prtPreProcFilter   Data filtering\n    %   Apply the filter specified in the propertes a and b to the rows of\n    %   the data in dataSet.X:\n    %\n    % ds = prtDataGenCylinderBellFunnel;\n    % b = fir1(21,.5);\n    % pp = prtPreProcFilter('b',b,'a',1);\n    % pp = pp.train(ds);\n    % dsLpf = pp.run(ds);\n    % subplot(1,2,1); imagesc(ds);\n    % subplot(1,2,2); imagesc(dsLpf);\n\n\n\n\n\n    properties (SetAccess=private)\n        name = 'Filter'  % Zero Mean Unit Variance\n        nameAbbreviation = 'Filt'  % ZMUV\n    end\n    \n    properties\n        b = [];\n        a = 1;\n        filtfilt = true;\n    end\n    \n    methods\n        function Obj = prtPreProcFilter(varargin)\n            Obj = prtUtilAssignStringValuePairs(Obj,varargin{:});\n        end\n    end\n    \n    methods (Access=protected,Hidden=true)\n        \n        function self = trainAction(self,ds)\n            % nothing to do\n        end\n        \n        \n        function ds = runAction(self,ds)\n            % Remove the means and normalize the variance\n            X = ds.X;\n            if self.filtfilt\n                X = filtfilt(self.b,self.a,X')';\n            else\n                X = filter(self.b,self.a,X')';\n            end\n            ds.X = X;\n        end\n        \n        function xOut = runActionFast(self,xIn,ds) %#ok<INUSD>\n           if self.filtfilt\n                xOut = filtfilt(self.b,self.a,xIn')';\n            else\n                xOut = filter(self.b,self.a,xIn')';\n            end\n        end\n    end\n    \n    methods (Hidden)\n        \n        function str = exportSimpleText(self) %#ok<MANU>\n            error('Not implemented');\n            %             titleText = sprintf('%% prtPreProcZmuv\\n');\n            %             zmuvMeansText = prtUtilMatrixToText(self.means,'varName','means');\n            %             zmuvVarsText = prtUtilMatrixToText(self.stds,'varName','std');\n            %             str = sprintf('%s%s%s',titleText,zmuvMeansText,zmuvVarsText);\n        end\n    end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/preProc/prtPreProcFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5858214825866206}}
{"text": "% Weighted Prediction Error for dereverberation\n% reference: Nakatani, Tomohiro, et al. \"Speech dereverberation based on\n% variance-normalized delayed linear prediction.\" IEEE TASLP 18.7 (2010)\n% ZitengWANG@201903\n\n\nclear all\naddpath('..\\STFT\\')\naddpath('..\\Simulation\\')\naddpath('..\\Simulation\\RIR-Generator\\')\n\n%% simulation start\nflatStart = 1;\nprefix = '';   % for saving file\n\nspeechDir = '..\\Simulation\\Data\\';\nspeechFile = 'fajw0_sa1.wav';\nsaveDir = 'GeneratedData\\';\nif ~exist(saveDir)\n    mkdir(saveDir)\nend\nspeech = audioread([speechDir speechFile]);\n\n% configuration\ncfg = [];\ncfg.fs = 16000;                     % sampling rate\ncfg.room = [6 5 3];                 % room dimension (m)\ncfg.T60 = 0;                      % reverberation time (s)\n\ncfg.Nch = 6;\ncfg.micCenter = [2 3 1.5];          % array center (m)\ncfg.micCoordinate =[0.0425,0.0,0.0;\n        0.02125,0.03680608,0.0;\n        -0.02125,0.03680608,0.0;\n        -0.0425,0.0,0.0;\n        -0.02125,-0.03680608,0.0;\n        0.02125,-0.03680608,0.0;];  % microphone array coordinates\n    \ncfg.az = 180;\ncfg.el = 0;\ncfg.dist = 3;\n\ncfg.SNR = 20;\nif cfg.SNR ~= inf               % inf means no noise\n    cfg.noiseType = 'white';    % choice {'white' 'diffuse' 'recorded'}\n    if strcmp(cfg.noiseType, 'recorded')\n        % check first the noise is longer than speech!\n        cfg.noiseFile = '';     \n    end\nend\n\ncfg.SIR = inf;\n\n% setup room and collect data\nsetup_room\nsetup_noise\n\n\n%% offline processing start\n% the following parts are specific to the algorithm\nNfft = 512;\n\nY = stft_multi_2(y, Nfft);\n[Nframe, Nbin, Nch] = size(Y);\n\niterMax = 5;\nwpe.delay = 3;\nwpe.taps = 10;\nXeEst = Y;\nfor bin = 1:Nbin\n    % get audio context first\n    YbarFrm = cell(Nframe, 1);\n    for frm = (wpe.taps + wpe.delay):Nframe\n        Ybar = squeeze(Y(frm - wpe.delay,bin,:));\n        for tap=1:wpe.taps-1\n            Ybar = [Ybar; squeeze(Y(frm - wpe.delay - tap,bin ,:))];\n        end\n        YbarFrm{frm} = Ybar;\n    end\n    \n    % iterate\n    X = squeeze(Y(:,bin,:));\n    for iter = 1:iterMax\n        % calculate mean signal power\n        Xpow = mean(abs(X).^2, 2);\n        XpowMax = max(Xpow);\n        % calculate correlation matrix and correlation vector\n        R = 0;\n        P = 0;\n        for frm = (wpe.taps + wpe.delay):Nframe\n            Ybar = YbarFrm{frm};\n            YbarTmp = Ybar / max(Xpow(frm), 1e-10*XpowMax);\n            R = R + YbarTmp * Ybar' ;\n            P = P + YbarTmp * squeeze(Y(frm,bin,:))';\n        end\n        hWPE = R \\ P;\n        \n        % apply the filter\n        for frm = (wpe.taps + wpe.delay):Nframe\n            X(frm, :) = squeeze(Y(frm,bin,:)) - hWPE'*YbarFrm{frm};\n        end\n    end\n    XeEst(:,bin,:) = permute(X,[1,3,2]);\nend\n\nxeEst = istft_multi_2(XeEst, length(speech));\naudiowrite([saveDir prefix 'WPE' postfix '.wav'], xeEst, fs);\n\n\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/WPE/WPE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5857966403959406}}
{"text": "% predicting numerical values using Linear Regression\nclear all;\nformat long\ndisp('===== Linear Regression ====');\ndisp('Reading featur vector');\n\n\n\nfor feat = 1:3\n    featurs = csvread('data\\forWeka_featuresonly.csv');\n    num_data = size(featurs,1); %5000;\n    disp(sprintf('Number of datapoints %d',num_data))\n    \n    possiblefeaturizations =  {'bernouli', 'tfidf','multinomial'};\n    %featurization = 'bernouli'%'tfidf'%'tfidf'%'multinomial'%'tfidf' %'multinomial'; % 'bernouli', 'tfidf'\n    featurization  = possiblefeaturizations{feat}\n    \n    \n    featurs = featurs(:,2:size(featurs,2));\n    if strcmp(featurization,'multinomial')\n        %just pass\n    elseif strcmp(featurization,'bernouli')\n        featurs = bernoulli(featurs);\n    elseif strcmp(featurization,'tfidf')\n        featurs = tfidf(featurs);\n    end\n    \n    \n    size_training = floor(.8*num_data);\n    \n    \n    trainingset = featurs(1:size_training,:);\n    testset = featurs((size_training+1):num_data,:);\n    \n    \n    disp('Splitting up data into training/test sets');\n    [num,txt,raw] = xlsread('data\\final104.xls');\n    \n    % reading the description of each shoe\n    descriptions = raw(2:size(raw,1),2);\n    style_ratings = num(1:size(num,1),1);\n    comfort_ratings = num(1:size(num,1),4);\n    overal_ratings = num(1:size(num,1),5);\n    \n    % only take m data points\n    m=num_data;\n    descriptions = descriptions(1:m);\n    style_ratings = style_ratings(1:m);\n    comfort_ratings = comfort_ratings(1:m);\n    overal_ratings = overal_ratings(1:m);\n    \n    responsevals = [style_ratings, comfort_ratings, overal_ratings];\n    \n    responsevals_training = responsevals(1:size_training,:);\n    responsevals_test = responsevals((size_training+1):num_data,:);\n    \n    disp('Discreminate Analsys');\n    % \n    \n    tic;\n    \n    predictions = [];\n    actual = [];\n    for i =1:3\n        a = responsevals_training(:,i);\n        b = responsevals_test(:,i)';\n        %regresscoeff = regress(a, trainingset);\n        %C2 = (regresscoeff'*(testset'));\n        class = classify(testset,trainingset,a)\n        predictions = [predictions, class];\n        actual = [actual, b'];\n    end\n    \n    \n    MSE = mean(sum(((predictions-actual).^2)'))\n    toc;\n    \nend\n", "meta": {"author": "faridani", "repo": "MatlabNLP", "sha": "e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f", "save_path": "github-repos/MATLAB/faridani-MatlabNLP", "path": "github-repos/MATLAB/faridani-MatlabNLP/MatlabNLP-e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f/sandboxes/siamak sandbox/multivariate6D/DiscreminateAnalysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5857966252222992}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\nfunction [S, u, d, df, p] = createbintree(S0, T, n, r, sigma)\n% creates a simple binomial tree using repmat\n    dt = T / n;                  % length of one period\n    u = exp(sigma * sqrt(dt));   % up move\n    d = 1 / u;                   % down move\n    df = exp(-r * dt);           % discount\n    p = (1/df - d) / (u - d);    % probability up\n\n    S = zeros(2^n, n+1);\n    S(:,1) = S0*ones(2^n,1);\n\n    for i=1:1:n\n        a = [u * ones(2^(n-i),1); d * ones(2^(n-i),1)];\n        S(:,i+1) = S(:,i).*repmat(a, 2^(i-1),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/37620-american-monte-carlo/AmericanMC/createbintree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5857966223289279}}
{"text": "function desc = sift( patches )\npsz = [size(patches, 1), size(patches, 2)];\nfrm = [(psz(1) ./ 2 + 0.5) * ones(2, 1) ; psz(1) ./ 2; 0];\ndesc = [];\nfor pi = 1:size(patches, 3)\n  I = single(patches(:, :, pi));\n  [Ix, Iy] = vl_grad(I) ;\n  mod      = sqrt(Ix.^2 + Iy.^2) ;\n  ang      = atan2(Iy, Ix) ;\n  grd      = shiftdim(cat(3, mod, ang), 2) ;\n  d        = vl_siftdescriptor(grd, frm, 'magnif', 0.5) ;\n  if isempty(desc)\n    desc = zeros(numel(d), size(patches, 3), 'single');\n  end\n  desc(:, pi) = d;\nend\n\nend\n\n", "meta": {"author": "hpatches", "repo": "hpatches-benchmark", "sha": "d5bde9d4520a037e8efc839bd1b6fc70edca82ed", "save_path": "github-repos/MATLAB/hpatches-hpatches-benchmark", "path": "github-repos/MATLAB/hpatches-hpatches-benchmark/hpatches-benchmark-d5bde9d4520a037e8efc839bd1b6fc70edca82ed/matlab/+desc/+feats/sift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.585743917659349}}
{"text": "function s = resampdet(p,m,n);\n%RESAMPDET Deterministic resampling\n%\n%   Description\n%   S = RESAMPDET(P) returns a new set of indices according to the\n%   probabilities P. P is array of probabilities, which are not\n%   necessarily normalized, though they must be non-negative, and\n%   not all zero. The size of S is the size of P. \n%\n%   S = RESAMPDET(P,M,N) returns M by N matrix.\n%\n%   S = RESAMPDET(P,M) returns M by M matrix.\n%\n%   Default is to use no-sort resampling. For sorted resampling use\n%    [PS,PI]=SORT(P);\n%    S=PI(RESAMPDET(PS));\n%   Sorted re-sampling is slower but has smaller variance. Note\n%   that deterministic resampling is not unbiased. Stratified\n%   resampling (RESAMPSTR) is unbiased, almost as fast as\n%   deterministic resampling, and has only slightly larger\n%   variance.\n%\n%   In deterministic resampling indices are sampled using\n%   deterministic numbers u_j~(j-a)/n, for fixed a in [0,1) and\n%   n is length of P. Compare this to simple random resampling\n%   where u_j~U[0,n]. See, Kitagawa, G., Monte Carlo Filter and\n%   Smoother for Non-Gaussian Nonlinear State Space Models,\n%   Journal of Computational and Graphical Statistics, 5(1):1-25,\n%   1996. \n%\n%   See also RESAMPSIM, RESAMPRES, RESAMPSTR\n\n% Copyright (c) 2003-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    [m,n]=size(p);\nelseif nargin==2\n    n=m;\nend\nmn=m.*n;\npn=p./sum(p(:)).*mn;\nfpn=floor(pn);\ns=zeros(m,n);\nk=0;\nc=0.5;\nfor i=1:numel(p)\n  if pn(i)>=1\n    a=fpn(i);\n    pn(i)=pn(i)-a;\n    s(k+[1:a])=i;\n    k=k+a;\n  end\n  c=c+pn(i);\n  if c>=1\n    k=k+1;\n    s(k)=i;\n    c=c-1;\n  end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/mc/resampdet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5857439090602387}}
{"text": "function denoised_im = denoise_foe(im, basis, W, a, sigma)\n%DENOISE_FOE Denoise image using Field of Experts prior model\n%\n%   denoised_im = denoise_foe(im, basis, W, a, sigma)\n%\n% Denoises the image im, using a Gaussian noise model with variance sigma, \n% and a Field of Experts image prior specified by basis, W, and a.\n%\n%\n% (C) Laurens van der Maaten, 2009\n% Delft University of Technology\n\n    \n    % Initialize some variables\n    eta = 10;\n    max_iter = 275; %275 je bilo originalno\n    im = double(im);\n    dI = zeros(size(im));\n    \n    % Convert to YCbCr color space if input is RGB\n    if size(im, 3) == 3\n        im = 255 .* rgb2ycbcr(im ./ 255);\n    end\n    denoised_im = im;\n\n    minEnergy = realmax;\n    minEnergyImg = denoised_im;\n    % Perform gradient iterations\n    for iter=1:max_iter\n        \n        % Compute gradient of posterior log-likelihood\n        for c=1:size(denoised_im, 3)\n            dI(:,:,c) = reshape(foe_energy_grad_x(denoised_im(:,:,c), basis, W, a), [size(im, 1) size(im, 2)]);\n        end\n        dI = dI + (1 / sigma ^ 2) * (im - denoised_im);\n        \n        % Perform gradient update\n        denoised_im = denoised_im - eta * dI;\n        \n        % Print progress\n        if ~rem(iter, 10) || iter == max_iter\n            \n            % Compute energy of posterior\n            E = foe_energy(denoised_im, basis, W, a, size(denoised_im)) + (1 ./ (sigma ^ 2)) * sum(((im(:) - denoised_im(:)) ./ 255) .^ 2);\n            \n            if E < minEnergy\n                minEnergy = E;\n                minEnergyImg = denoised_im;\n                disp(['Iteration ' num2str(iter) ': energy is ' num2str(E)]);\n            else\n                disp('Finished because of energy increase.');\n                denoised_im = minEnergyImg;\n                break;\n            end\n            \n            \n            \n            % Show intermediate result\n            if size(im, 3) == 3\n                tmp1 = uint8(round(255 .* ycbcr2rgb(im ./ 255)));\n                tmp2 = uint8(round(255 .* ycbcr2rgb(denoised_im ./ 255)));\n            else\n                tmp1 = uint8(round(im));\n                tmp2 = uint8(round(denoised_im));\n            end            \n        end\n    end\n    \n    subplot(1, 2, 1); imshow(tmp1); colormap(gray); title('Noisy image');\n    subplot(1, 2, 2); imshow(tmp2); colormap(gray); title(['Denoised image (iteration ' num2str(iter) ')']);\n    drawnow;\n    \n    % Convert back to RGB if necessary\n    if size(denoised_im, 3) == 3\n        denoised_im = 255 .* ycbcr2rgb(denoised_im ./ 255);\n    end \n    denoised_im = uint8(round(denoised_im));\n    ", "meta": {"author": "lbasek", "repo": "image-denoising-benchmark", "sha": "9d753198d715b7628c8e7d9259dfa5c219d033ea", "save_path": "github-repos/MATLAB/lbasek-image-denoising-benchmark", "path": "github-repos/MATLAB/lbasek-image-denoising-benchmark/image-denoising-benchmark-9d753198d715b7628c8e7d9259dfa5c219d033ea/algoritms/matlab/FOE/foe/denoise_foe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5857439090602387}}
{"text": "function angles3d(varargin)\n%ANGLES3D Conventions for manipulating angles in 3D.\n%\n%   The library uses both radians and degrees angles;\n%   Results of angle computation between shapes usually returns angles in\n%   radians.\n%   Representation of 3D shapes use angles in degrees (easier to manipulate\n%   and to save). \n%\n%   Contrary to the plane, there are no oriented angles in 3D. Angles\n%   between lines or between planes are comprised between 0 and PI.\n%\n%   Spherical angles\n%   Spherical angles are defined by 2 angles:\n%   * THETA, the colatitude, representing angle with Oz axis (between 0 and\n%       PI)\n%   * PHI, the azimut, representing angle with Ox axis of horizontal\n%       projection of the direction (between 0 and 2*PI)\n%\n%   Spherical coordinates can be represented by THETA, PHI, and the\n%   distance RHO to the origin.\n%\n%   Euler angles\n%   Some functions for creating rotations use Euler angles. They follow the\n%   ZYX convention in the global reference system, that is eqivalent to the\n%   XYZ convention ine a local reference system. \n%   Euler angles are given by a triplet of angles [PHI THETA PSI] that\n%   represents the succession of 3 rotations: \n%   * rotation around X by angle PSI    (\"roll\")\n%   * rotation around Y by angle THETA  (\"pitch\")\n%   * rotation around Z by angle PHI    (\"yaw\")\n%\n%   In this library, euler angles are given in degrees. The functions that\n%   use euler angles use the keyword 'Euler' in their name.\n%\n%\n%   See also\n%   cart2sph2, sph2cart2, cart2sph2d, sph2cart2d\n%   anglePoints3d, angleSort3d, sphericalAngle, randomAngle3d\n%   dihedralAngle, polygon3dNormalAngle, eulerAnglesToRotation3d\n%   rotation3dAxisAndAngle, rotation3dToEulerAngles\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2008-10-13,    using Matlab 7.4.0.287 (R2007a)\n% Copyright 2008 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\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/angles3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672089305841, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5857438961041387}}
{"text": "function [resp] = responseCox(X,coeff)\n% -------------------------------------------------------------------------\n% function [resp] = responseLR(X,coeff)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes the multivariable response of an input set of\n% features from a given set of logistic regression coefficients.\n% -------------------------------------------------------------------------\n% INPUTS:                             \n% - X: Matrix of size [nInst X nFeat], specifying the numerical data of the\n%      features of the input training data, where 'nInst' refers to the \n%      number of instances in X, and 'nFeat' to the number of features in \n%      X. Each column is a different feature.\n% - coeff: Column vector of size [nFeat+1 X 1] representing the set of \n%          logistic regression coefficients computed from\n%          drxlr_apply_logistic_regression.m. One coefficient is present\n%          for each feature in 'X', in addition to one offset coefficient.\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% - resp: Multivariable response vector of size [nInst X 1].\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: May 2015\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015  Martin Vallieres\n%\n%    This package 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 package 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 package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\nnInst = size(X,1);\nnFeat = size(X,2);\nresp = zeros(nInst,1);\nfor j = 1:nFeat\n    resp(:) = resp(:) + X(:,j).*coeff(j);\nend\n\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/MULTIVARIABLE_MODELING/responseCox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5857438956583172}}
{"text": "function [G, Y, optinf] = bpdndl(D0, S, lambda, opt)\n\n% bpdndl -- BPDN Dictionary Learning\n%\n%         argmin_{D,X} (1/2)||D X - S||_2^2 + lambda ||X||_1\n%\n%         Dictionary learning consists of interleaved alternation of\n%         the ADMM (see boyd-2010-distributed) steps for the BPDN (see\n%         chen-1998-atomic) and MOD (see engan-1999-method) problems.\n%\n% Usage:\n%       [D, X, optinf] = bpdndl(D0, S, lambda, opt)\n%\n% Input:\n%       D0          Initial dictionary\n%       S           Input image\n%       lambda      Regularization parameter\n%       opt         Options/algorithm parameters structure (see below)\n%\n% Output:\n%       D           Dictionary\n%       X           Coefficients\n%       optinf      Details of optimisation\n%\n%\n% Options structure fields:\n%   Verbose          Flag determining whether iteration status is displayed.\n%                    Fields are iteration number, functional value,\n%                    data fidelity term, l1 regularisation term, and\n%                    primal and dual residuals (see Sec. 3.3 of\n%                    boyd-2010-distributed). The values of rho and sigma\n%                    are also displayed if options request that they are\n%                    automatically adjusted.\n%   MaxMainIter      Maximum main iterations\n%   AbsStopTol       Absolute convergence tolerance (see Sec. 3.3.1 of\n%                    boyd-2010-distributed)\n%   RelStopTol       Relative convergence tolerance (see Sec. 3.3.1 of\n%                    boyd-2010-distributed)\n%   L1Weight         Weight matrix for L1 norm\n%   Y0               Initial value for Y\n%   U0               Initial value for U\n%   G0               Initial value for G (overrides D0 if specified)\n%   H0               Initial value for H\n%   rho              Augmented Lagrangian penalty parameter\n%   AutoRho          Flag determining whether rho is automatically updated\n%                    (see Sec. 3.4.1 of boyd-2010-distributed)\n%   AutoRhoPeriod    Iteration period on which rho is updated\n%   RhoRsdlRatio     Primal/dual residual ratio in rho update test\n%   RhoScaling       Multiplier applied to rho when updated\n%   AutoRhoScaling   Flag determining whether RhoScaling value is\n%                    adaptively determined (see wohlberg-2015-adaptive). If\n%                    enabled, RhoScaling specifies a maximum allowed\n%                    multiplier instead of a fixed multiplier\n%   sigma            Augmented Lagrangian penalty parameter\n%   AutoSigma        Flag determining whether sigma is automatically\n%                    updated (see Sec. 3.4.1 of boyd-2010-distributed)\n%   AutoSigmaPeriod  Iteration period on which sigma is updated\n%   SigmaRsdlRatio   Primal/dual residual ratio in sigma update test\n%   SigmaScaling     Multiplier applied to sigma when updated\n%   AutoSigmaScaling Flag determining whether SigmaScaling value is\n%                    adaptively determined (see wohlberg-2015-adaptive). If\n%                    enabled, SigmaScaling specifies a maximum allowed\n%                    multiplier instead of a fixed multiplier.\n%   StdResiduals     Flag determining whether standard residual definitions\n%                    (see Sec 3.3 of boyd-2010-distributed) are used instead\n%                    of normalised residuals (see wohlberg-2015-adaptive)\n%   XRelaxParam      Relaxation parameter (see Sec. 3.4.3 of\n%                    boyd-2010-distributed) for X update\n%   DRelaxParam      Relaxation parameter (see Sec. 3.4.3 of\n%                    boyd-2010-distributed) for D update\n%   NonNegCoef       Flag indicating whether solution should be forced to\n%                    be non-negative\n%   AuxVarObj        Flag determining whether objective function is computed\n%                    using the auxiliary (split) variable\n%   ZeroMean         Force learned dictionary entries to be zero-mean\n%\n%\n% Author: Brendt Wohlberg <brendt@lanl.gov>  Modified: 2015-07-30\n%\n% This file is part of the SPORCO library. Details of the copyright\n% and user license can be found in the 'License' file distributed with\n% the library.\n\n\nif nargin < 4,\n  opt = [];\nend\ncheckopt(opt, defaultopts([]));\nopt = defaultopts(opt);\nNx = size(D0,2)*size(S,2);\nNd = prod(size(D0));\n\n% Set up status display for verbose operation\nhstr = ['Itn   Fnc       DFid      l1        Cnstr     '...\n        'r(X)      s(X)      r(D)      s(D) '];\nsfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';\nnsep = 84;\nif opt.AutoRho,\n  hstr = [hstr '     rho  '];\n  sfms = [sfms ' %9.2e'];\n  nsep = nsep + 10;\nend\nif opt.AutoSigma,\n  hstr = [hstr '     sigma  '];\n  sfms = [sfms ' %9.2e'];\n  nsep = nsep + 10;\nend\nif opt.Verbose && opt.MaxMainIter > 0,\n  disp(hstr);\n  disp(char('-' * ones(1,nsep)));\nend\n\n% Mean removal and normalisation projections\nPzmn = @(x) bsxfun(@minus, x, mean(x,1));\nPnrm = @(x) normalise(x);\n\n% Projection of dictionary filters onto constraint set\nif opt.ZeroMean,\n  Pcn = @(x) Pnrm(Pzmn(x));\nelse\n  Pcn = @(x) Pnrm(x);\nend\n\n% Start timer\ntstart = tic;\n\n% Project initial dictionary onto constraint set\nD = Pnrm(D0);\n\n% Set up algorithm parameters and initialise variables\nrho = opt.rho;\nif isempty(rho), rho = 50*lambda+1; end;\nsigma = opt.sigma;\nif isempty(sigma), sigma = size(S,2)/200; end;\noptinf = struct('itstat', [], 'opt', opt);\nrx = Inf;\nsx = Inf;\nrd = Inf;\nsd = Inf;\neprix = 0;\neduax = 0;\neprid = 0;\neduad = 0;\n\n% Initialise main working variables\nX = [];\nif isempty(opt.Y0),\n  Y = zeros(size(D,2), size(S,2));\nelse\n  Y = opt.Y0;\nend\nYprv = Y;\nif isempty(opt.U0),\n  if isempty(opt.Y0),\n    U = zeros(size(D,2), size(S,2), class(S));\n  else\n    U = (lambda/rho)*sign(Y);\n  end\nelse\n  U = opt.U0;\nend\nif isempty(opt.G0),\n  G = D;\nelse\n  G = opt.G0;\nend\nGprv = G;\nif isempty(opt.H0),\n  if isempty(opt.G0),\n    H = zeros(size(G), class(S));\n  else\n    H = G;\n  end\nelse\n  H = opt.H0;\nend\nGS = G'*S;\n\n\n% Main loop\nk = 1;\nwhile k <= opt.MaxMainIter && (rx > eprix|sx > eduax|rd > eprid|sd >eduad),\n\n  % Solve X subproblem, using G as the dictionary for improved stability\n  [luLx, luUx] = factorise(G, rho);\n  X = linsolveX(G, rho, luLx, luUx, GS + rho*(Y - U));\n\n  % See pg. 21 of boyd-2010-distributed\n  if opt.XRelaxParam == 1,\n    Xr = X;\n  else\n    Xr = opt.XRelaxParam*X + (1-opt.XRelaxParam)*Y;\n  end\n\n  % Solve Y subproblem\n  Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);\n  if opt.NonNegCoef,\n    Y(Y < 0) = 0;\n  end\n  SY = S*Y';\n\n  % Update dual variable corresponding to X, Y\n  U = U + Xr - Y;\n\n  % Compute primal and dual residuals and stopping thresholds for X update\n  nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));\n  if opt.StdResiduals,\n    % See pp. 19-20 of boyd-2010-distributed\n    rx = norm(vec(X - Y));\n    sx = norm(vec(rho*(Yprv - Y)));\n    eprix = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;\n    eduax = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;\n  else\n    % See wohlberg-2015-adaptive\n    rx = norm(vec(X - Y))/max(nX,nY);\n    sx = norm(vec(Yprv - Y))/nU;\n    eprix = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;\n    eduax = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;\n  end\n\n  % Solve D subproblem, using Y as the coefficients for improved stability\n  [luLd, luUd] = factorise(Y, sigma);\n  D = linsolveD(Y, sigma, luLd, luUd, SY + sigma*(G - H));\n\n  % See pg. 21 of boyd-2010-distributed\n  if opt.DRelaxParam == 1,\n    Dr = D;\n  else\n    Dr = opt.DRelaxParam*D + (1-opt.DRelaxParam)*G;\n  end\n\n  % Solve G subproblem\n  G = Pcn(Dr + H);\n  GS = G'*S;\n\n  % Update dual variable corresponding to D, G\n  H = H + Dr - G;\n\n  % Compute primal and dual residuals and stopping thresholds for D update\n  nD = norm(D(:)); nG = norm(G(:)); nH = norm(H(:));\n  if opt.StdResiduals,\n    % See pp. 19-20 of boyd-2010-distributed\n    rd = norm(vec(D - G));\n    sd = norm(vec(sigma*(Gprv - G)));\n    eprid = sqrt(Nd)*opt.AbsStopTol+max(nD,nG)*opt.RelStopTol;\n    eduad = sqrt(Nd)*opt.AbsStopTol+sigma*nH*opt.RelStopTol;\n  else\n    % See wohlberg-2015-adaptive\n    rd = norm(vec(D - G))/max(nD,nG);\n    sd = norm(vec(Gprv - G))/nH;\n    eprid = sqrt(Nd)*opt.AbsStopTol/max(nD,nG)+opt.RelStopTol;\n    eduad = sqrt(Nd)*opt.AbsStopTol/(sigma*nH)+opt.RelStopTol;\n  end\n\n  % Objective function\n  if opt.AuxVarObj,\n    Jdf = sum(vec(abs(G*Y - S).^2))/2;\n    Jl1 = sum(abs(vec(opt.L1Weight .* Y)));\n  else\n    Jdf = sum(vec(abs(D*X - S).^2))/2;\n    Jl1 = sum(abs(vec(opt.L1Weight .* X)));\n  end\n  Jfn = Jdf + lambda*Jl1;\n  Jcn = norm(vec(Pcn(D) - D));\n\n\n  % Record and display iteration details\n  tk = toc(tstart);\n  optinf.itstat = [optinf.itstat; ...\n        [k Jfn Jdf Jl1 rx sx rd sd eprix eduax eprid eduad rho sigma tk]];\n  if opt.Verbose,\n    dvc = [k Jfn Jdf Jl1 Jcn rx sx rd sd];\n    if opt.AutoRho,\n      dvc = [dvc rho];\n    end\n    if opt.AutoSigma,\n      dvc = [dvc sigma];\n    end\n    disp(sprintf(sfms, dvc));\n  end\n\n  % See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed\n  if opt.AutoRho,\n    if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,\n      if opt.AutoRhoScaling,\n        rhomlt = sqrt(rx/sx);\n        if rhomlt < 1, rhomlt = 1/rhomlt; end\n        if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end\n      else\n        rhomlt = opt.RhoScaling;\n      end\n      rsf = 1;\n      if rx > opt.RhoRsdlRatio*sx, rsf = rhomlt; end\n      if sx > opt.RhoRsdlRatio*rx, rsf = 1/rhomlt; end\n      rho = rsf*rho;\n      U = U/rsf;\n    end\n  end\n  if opt.AutoSigma,\n    if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,\n      if opt.AutoSigmaScaling,\n        sigmlt = sqrt(rd/sd);\n        if sigmlt < 1, sigmlt = 1/sigmlt; end\n        if sigmlt > opt.SigmaScaling, sigmlt = opt.SigmaScaling; end\n      else\n        sigmlt = opt.SigmaScaling;\n      end\n      ssf = 1;\n      if rd > opt.SigmaRsdlRatio*sd, ssf = sigmlt; end\n      if sd > opt.SigmaRsdlRatio*rd, ssf = 1/sigmlt; end\n      sigma = ssf*sigma;\n      H = H/ssf;\n    end\n  end\n\n\n  Yprv = Y;\n  Gprv = G;\n  k = k + 1;\n\nend\n\n% Record run time and working variables\noptinf.runtime = toc(tstart);\noptinf.X = X;\noptinf.Y = Y;\noptinf.U = U;\noptinf.D = D;\noptinf.G = G;\noptinf.H = H;\noptinf.lambda = lambda;\noptinf.rho = rho;\noptinf.sigma = sigma;\n\nif opt.Verbose && opt.MaxMainIter > 0,\n  disp(char('-' * ones(1,nsep)));\nend\n\nreturn\n\n\nfunction u = vec(v)\n\n  u = v(:);\n\nreturn\n\n\nfunction u = shrink(v, lambda)\n\n  u = sign(v).*max(0, abs(v) - lambda);\n\nreturn\n\n\nfunction u = normalise(v)\n\n  vn = sqrt(sum(v.^2, 1));\n  vn(vn == 0) = 1;\n  u = bsxfun(@rdivide, v, vn);\n\nreturn\n\n\nfunction [L,U] = factorise(A, c)\n\n  [N,M] = size(A);\n  % If N < M it is cheaper to factorise A*A' + cI and then use the\n  % matrix inversion lemma to compute the inverse of A'*A + cI\n  if N >= M,\n    [L,U] = lu(A'*A + c*eye(M,M));\n  else\n    [L,U] = lu(A*A' + c*eye(N,N));\n  end\n\nreturn\n\n\nfunction x = linsolveX(A, c, L, U, b)\n\n  [N,M] = size(A);\n  if N >= M,\n    x = U \\ (L \\ b);\n  else\n    x = (b - A'*(U \\ (L \\ (A*b))))/c;\n  end\n\nreturn\n\n\nfunction x = linsolveD(A, c, L, U, b)\n\n  [N,M] = size(A);\n  if N >= M,\n    x = (b - (((b*A) / U) / L)*A')/c;\n  else\n    x = (b / U) / L;\n  end\n\nreturn\n\n\nfunction opt = defaultopts(opt)\n\n  if ~isfield(opt,'Verbose'),\n    opt.Verbose = 0;\n  end\n  if ~isfield(opt,'MaxMainIter'),\n    opt.MaxMainIter = 1000;\n  end\n  if ~isfield(opt,'AbsStopTol'),\n    opt.AbsStopTol = 1e-6;\n  end\n  if ~isfield(opt,'RelStopTol'),\n    opt.RelStopTol = 1e-4;\n  end\n  if ~isfield(opt,'L1Weight'),\n    opt.L1Weight = 1;\n  end\n  if ~isfield(opt,'Y0'),\n    opt.Y0 = [];\n  end\n  if ~isfield(opt,'U0'),\n    opt.U0 = [];\n  end\n  if ~isfield(opt,'G0'),\n    opt.G0 = [];\n  end\n  if ~isfield(opt,'H0'),\n    opt.H0 = [];\n  end\n  if ~isfield(opt,'rho'),\n    opt.rho = [];\n  end\n  if ~isfield(opt,'AutoRho'),\n    opt.AutoRho = 0;\n  end\n  if ~isfield(opt,'AutoRhoPeriod'),\n    opt.AutoRhoPeriod = 10;\n  end\n  if ~isfield(opt,'RhoRsdlRatio'),\n    opt.RhoRsdlRatio = 10;\n  end\n  if ~isfield(opt,'RhoScaling'),\n    opt.RhoScaling = 2;\n  end\n  if ~isfield(opt,'AutoRhoScaling'),\n    opt.AutoRhoScaling = 0;\n  end\n  if ~isfield(opt,'sigma'),\n    opt.sigma = [];\n  end\n  if ~isfield(opt,'AutoSigma'),\n    opt.AutoSigma = 0;\n  end\n  if ~isfield(opt,'AutoSigmaPeriod'),\n    opt.AutoSigmaPeriod = 10;\n  end\n  if ~isfield(opt,'SigmaRsdlRatio'),\n    opt.SigmaRsdlRatio = 10;\n  end\n  if ~isfield(opt,'SigmaScaling'),\n    opt.SigmaScaling = 2;\n  end\n  if ~isfield(opt,'AutoSigmaScaling'),\n    opt.AutoSigmaScaling = 0;\n  end\n  if ~isfield(opt,'StdResiduals'),\n    opt.StdResiduals = 0;\n  end\n  if ~isfield(opt,'XRelaxParam'),\n    opt.XRelaxParam = 1;\n  end\n  if ~isfield(opt,'DRelaxParam'),\n    opt.DRelaxParam = 1;\n  end\n  if ~isfield(opt,'NonNegCoef'),\n    opt.NonNegCoef = 0;\n  end\n  if ~isfield(opt,'AuxVarObj'),\n    opt.AuxVarObj = 1;\n  end\n  if ~isfield(opt,'ZeroMean'),\n    opt.ZeroMean = 0;\n  end\n\nreturn\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/ConvSR_Image_Fusion_Codes/sporco/DictLearn/bpdndl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.585740992993972}}
{"text": "% op_zeropad.m\n% Jamie Near, McGill University 2014.\n% \n% USAGE:\n% out=op_zeropad(in,zpFactor);\n% \n% DESCRIPTION:\n% Apply zeropadding (a.k.a. zero-filling) to MRS data.\n% \n% INPUTS:\n% in         = input data in matlab structure format.\n% zpFactor   = the factor by which the number of points in the fid will be\n%             increased.  ie.  if zpFactor =2, then the number of zeros \n%             added to the end of the fid will be equal to the number of \n%             points in the original spectrum.\n%\n% OUTPUTS:\n% out        = Output dataset following zeropadding.\n\nfunction out=op_zeropad(in,zpFactor);\n\nif in.flags.zeropadded\n    cont=input('WARNING:  Zero padding has already been performed!  Continue anyway?  (y or n)','s');\n    if cont=='y'\n        %continue;\n    else\n        error('STOPPING');\n    end\nend\n\n\n%calculate how many zeros to add\nzp=ceil((in.sz(1)*zpFactor)-in.sz(1));\n\n%Add zeros using MATLAB array zeropadding function;\nfids=padarray(in.fids,zp,'post');\n\n%Calculate Specs using fft\nspecs=fftshift(ifft(fids,[],in.dims.t),in.dims.t);\n\n%recalculate the sz vector\nsz=size(fids);\n\n\n%Now re-calculate t and ppm arrays using the calculated parameters:\nf=[(-in.spectralwidth/2)+(in.spectralwidth/(2*sz(1))):...\n    in.spectralwidth/(sz(1)):...\n    (in.spectralwidth/2)-(in.spectralwidth/(2*sz(1)))];\n\nppm=-f/(in.Bo*42.577);\nppm=ppm+4.65;\n\nt=[0:in.dwelltime:(sz(1)-1)*in.dwelltime];\n\n\n%FILLING IN DATA STRUCTURE\nout=in;\nout.fids=fids;\nout.specs=specs;\nout.sz=sz;\nout.ppm=ppm;  \nout.t=t;   \nout.n=sz(1);\n\n%FILLING IN THE FLAGS\nout.flags=in.flags;\nout.flags.writtentostruct=1;\nout.flags.zeropadded=1;\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/processingTools/op_zeropad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5857409929939719}}
{"text": "% Least Mean Squares algorithm\n%\n% From A. H. Sayed, \"Fundamentals of adaptive filtering}\", Wiley-IEEE\n% Press, 2003, Chapter 5.\n%\n% This file is part of the Kernel Adaptive Filtering Toolbox for Matlab.\n% https://github.com/steven2358/kafbox/\n\nclassdef lms < linear_filter\n    \n    properties (GetAccess = 'public', SetAccess = 'private')\n        mu = 0.001; % learning rate\n    end\n    \n    properties (GetAccess = 'public', SetAccess = 'private')\n        w = []; % filter coefficients\n    end\n    \n    methods\n        function obj = lms(parameters) % constructor\n            if (nargin > 0) % copy valid parameters\n                for fn = fieldnames(parameters)'\n                    if ismember(fn,fieldnames(obj))\n                        obj.(fn{1}) = parameters.(fn{1});\n                    end\n                end\n            end\n        end\n        \n        function y_est = evaluate(obj,x) % evaluate the algorithm\n            if numel(obj.w)>0\n                y_est = x*obj.w;\n            else\n                y_est = zeros(size(x,1),1);\n            end\n        end\n        \n        function train(obj,x,y) % train the algorithm\n            if numel(obj.w)==0 % initialize\n                obj.w = zeros(length(x),1);\n            end\n            \n            % Algorithm 5.2.1 in reference\n            err = y - x*obj.w; % instantaneous error\n            obj.w = obj.w + obj.mu*x'*err; % update filter coefficients\n        end\n        \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/lms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5857094681967278}}
{"text": "function [TW] = hpb2TW(hpb)\n% Convert power from boiler horsepower to terawatts.\n% Chad A. Greene 2012\nTW = hpb*9809.5e-12;\n", "meta": {"author": "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/hpb2TW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5857094616895068}}
{"text": "function [ know, x ] = p11_sol ( )\n\n%*****************************************************************************80\n%\n%% P11_SOL returns the solution for problem 11.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 February 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Output, integer KNOW.\n%    If KNOW is 0, then the solution is not known.\n%    If KNOW is positive, then the solution is known, and is returned in X.\n%\n%    Output, real X, the solution, if known.\n%\n  know = 1;\n\n  x = 1.0 / 3.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/p11_sol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.5857094562801847}}
{"text": "clc\nclear all\nseed = 601;\nrandn('state',seed); rand('state',seed);\ntol = 5e-6; % optimality tolerance for stopping_type 1 \nDB=20; % SNR of the video\nframe_array=[35,100,125]; % frames that will be shown at the end \n\nglobal D X S\nseed = 602;\nrandn('state',seed); rand('state',seed);\nload Hall_airport_1000_1496_497_144_176_gray.mat;\nD = images(:,1:201);\nn1=144*176; n2=201;\nstdev = norm(D,'fro')/(sqrt(144*176*201)*10^(DB/20))\nD = D+stdev*randn(144*176,201);\n[X,S]=nsa_v1(D,stdev,tol);\nfigure\nplot_data(frame_array,D,X,S,144,176)", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/NSA2/demo_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5856470951802758}}
{"text": "function [cpulse, verbose] = tapas_physio_findpeaks_template_xcorr(...\n    c, pulseCleanedTemplate, cpulseSecondGuess, averageHeartRateInSamples, ...\n    verbose, varargin)\n% Finds peaks of a time series via pre-determined template via maxima of\n% matlab cross correlations (xcorr) via going backward from search starting \n% point in time series, and afterwards forward again\n%\n%   [cpulse, verbose] = tapas_physio_findpeaks_template_correlation(...\n%       c, pulseCleanedTemplate, cpulseSecondGuess, ...\n%           averageHeartRateInSamples, verbose)\n%\n% IN\n%   varargin    property name/value pairs for additional options\n%\n%\n% OUT\n%\n% EXAMPLE\n%   tapas_physio_findpeaks_template_correlation\n%\n%   See also\n\n% Author: Steffen Bollmann, cleanup, xcorr: Lars Kasper\n% Created: 2014-08-05\n% Copyright (C) 2014 TNU, Institute for Biomedical Engineering, \n%                         University of Zurich and ETH Zurich.\n%\n% This file is part of the TAPAS PhysIO 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 <http://www.gnu.org/licenses/>.\n\n\n\n% Determine starting peak for the search:\n%   search for a representative R-peak a range of peaks\n\n\nnSamples = size(c,1);\n\ndebug = verbose.level >= 4;\n\nidxStartPeakSearch = [0 20];\n\nhalfTemplateWidthInSamples = floor(numel(pulseCleanedTemplate)/2);\n\n[~,zTransformedTemplate] = tapas_physio_corrcoef12(pulseCleanedTemplate,...\n    pulseCleanedTemplate);\nisZTransformed = [0 1];\n\n% start and end point of search for representative start cycle\ncentreSampleStart = round(2*halfTemplateWidthInSamples+1);\n\nif idxStartPeakSearch(1) > 0\n    centreSampleStart = centreSampleStart + ...\n        cpulseSecondGuess(idxStartPeakSearch(1));\nend\ncentreSampleEnd = cpulseSecondGuess(idxStartPeakSearch(2));\n\niSignalStart = centreSampleStart - halfTemplateWidthInSamples;\niSignalEnd = centreSampleEnd + halfTemplateWidthInSamples;\nsignalPart = c(iSignalStart:iSignalEnd);\n\nsimilarityToTemplate = xcorr(zTransformedTemplate, flipud(signalPart));\n\n% not needed, since only zero-filled\n% similarityToTemplate = similarityToTemplate(1:centreSampleEnd);\n\n\n[C_bestMatch, I_bestMatch] = max(similarityToTemplate);\n\n\n\n%% now compute backwards to the beginning:\n% go average heartbeat by heartbeat back and look (with\n% decreasing weighting for higher distance) for highest\n% correlation with template heartbeat\n\nn = I_bestMatch;\nbestPosition = n; % to capture case where 1st R-peak is best\n\npeakNumber = 1;\n\nsimilarityToTemplate = zeros(nSamples,1);\n\nsearchStepsTotal    = round(0.5*averageHeartRateInSamples);\nsearchPositionArray = -searchStepsTotal:searchStepsTotal;\nnSamplesSignalPart  = 2*searchStepsTotal+1;\nlocationWeight      = ones(nSamplesSignalPart,1);\n\nwhile n > 1+searchStepsTotal+halfTemplateWidthInSamples\n    \n \n    % Nested function, needs c, zTransformedTemplate, n, halfTemplateWidthInSamples,\n    % searchStepsTotal, locationWeight\n    similarityToTemplate(n+searchPositionArray) = ...\n        get_similarity_to_template();\n    \n    %find biggest correlation-peak from the last search\n    indexSearchStart    = n-searchStepsTotal;\n    indexSearchEnd      = n+searchStepsTotal;\n    \n    indexSearchRange    = indexSearchStart:indexSearchEnd;\n    searchRangeValues   = similarityToTemplate(indexSearchRange);\n    [C_bestMatch,I_bestMatch] = max(searchRangeValues);\n    bestPosition = indexSearchRange(I_bestMatch);\n    \n    cpulse(peakNumber) = bestPosition;\n    peakNumber = peakNumber+1;\n    \n    \n    n=bestPosition-averageHeartRateInSamples;\nend % END: going backwards to beginning of time course\n\n%% Now go forward through the whole time series\nn           = bestPosition; % 1st R-peak\npeakNumber  = 1;\nclear cpulse;\n\n% Now correlate template with PPU signal at the positions\n% where we would expect a peak based on the average heartrate and\n% search in the neighborhood for the best peak, but weight the peaks\n% deviating from the initial starting point by a gaussian\nsearchStepsTotal = round(0.5*averageHeartRateInSamples);\n\n% for weighted searching of max correlation\nlocationWeight = tapas_physio_gausswin(nSamplesSignalPart);\n\nn = max(n, searchStepsTotal + halfTemplateWidthInSamples + 1);\n\n% zero-pad c at end to allow for detection of last peak by\n% template-matching up to the last sample of c\nc = [c; zeros(searchStepsTotal + halfTemplateWidthInSamples + 1, 1)];\n\nwhile n < nSamples % -searchStepsTotal - halfTemplateWidthInSamples\n    \n     similarityToTemplate(n+searchPositionArray) = ...\n         get_similarity_to_template();\n    \n    %find biggest correlation-peak from the last search\n    indexSearchStart    = n - searchStepsTotal;\n    indexSearchEnd      = n + searchStepsTotal;\n    \n    indexSearchRange    = indexSearchStart:indexSearchEnd;\n    searchRangeValues   = similarityToTemplate(indexSearchRange);\n    [C_bestMatch,I_bestMatch] = max(searchRangeValues);\n    bestPosition        = indexSearchRange(I_bestMatch);\n    \n    cpulse(peakNumber) = bestPosition;\n    peakNumber = peakNumber+1;\n    \n    %only take the last 20 cpulses to compute the current HeartRate\n    foundCpulses = size(cpulse,2);\n    \n    if  foundCpulses < 3\n        currentHeartRateInSamples=averageHeartRateInSamples;\n    end\n    \n    if (foundCpulses < 21) && (foundCpulses >= 3)\n        currentHeartRateInSamples = round(mean(diff(cpulse)));\n    end\n    \n    if foundCpulses >= 21\n        currentCpulses = cpulse (foundCpulses-20:foundCpulses);\n        currentHeartRateInSamples = round(mean(diff(currentCpulses)));\n    end\n    \n    \n    %check currentHeartRate\n    checkSmaller    = currentHeartRateInSamples > 0.5*averageHeartRateInSamples;\n    checkLarger     = currentHeartRateInSamples < 1.5*averageHeartRateInSamples;\n    \n    %jumpToNextPeakSearchArea\n    if (checkSmaller && checkLarger)\n        n = bestPosition + currentHeartRateInSamples;\n    else\n        n = bestPosition + averageHeartRateInSamples;\n    end\nend\n\n\n%% Nested function, \n% computes point-wise similarity (cross-correlation) of time course snippet \n% to given peak template (z-transformed)\n% nested function to improve performance\n%\n% needs c, zTransformedTemplate, n, halfTemplateWidthInSamples,\n% searchStepsTotal, searchPositionArray, locationWeight\n    function similarityToTemplateTmp = get_similarity_to_template()\n        % (c, zTransformedTemplate, n, halfTemplateWidthInSamples, searchStepsTotal, locationWeight);\n        iSignalStart    = n - halfTemplateWidthInSamples - searchStepsTotal;\n        iSignalEnd      = n + halfTemplateWidthInSamples + searchStepsTotal;\n        \n        signalPart = c(iSignalStart:iSignalEnd);\n        similarityToTemplateTmp = ...\n            xcorr(zTransformedTemplate, flipud(signalPart));\n        similarityToTemplateTmp = similarityToTemplateTmp(1:nSamplesSignalPart);\n        % crop beginning and end\n        %similarityToTemplateTmp(1:halfTemplateWidthInSamples) = [];\n        %similarityToTemplateTmp(end-halfTemplateWidthInSamples+1:end) = [];\n        \n        % reweight correlations with distance from expected heart beat\n        amplitudeWeight = abs(c((n+1)-searchPositionArray));\n        similarityToTemplateTmp =  locationWeight.*amplitudeWeight .* ...\n            similarityToTemplateTmp;\n        \n    end\n\nend", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/PhysIO/code/utils/tapas_physio_findpeaks_template_xcorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.585647090052818}}
{"text": "function n = exploration_noise(t, params)\nn = params.noiseLevel * sin(1*t) + ...\n    params.noiseLevel * sin(7*t)  + ...\n    params.noiseLevel * sin(3*t);\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/Extra_Examples/truck_trailer/exploration_noise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5856470865314193}}
{"text": "function A = slgda(K, nums, sol)\n%SLGDA Performs Baudat's Generalized Discriminant Analysis\n%\n% $ Syntax $\n%   - A = slgda(K, nums)\n%   - A = slgda(K, nums, sol)\n%\n% $ Arguments $\n%   - K:        the kernel gram matrix\n%   - nums:     the numbers of samples in each classes\n%   - sol:      the cell containing the parameter for generalized eigen\n%               decomposition\n%   - A:        the resulting projection coefficient matrix\n%\n% $ Description $\n%   - A = slgda(K, nums) performs Generalized Discriminant Analysis(GDA),\n%     an representative work in using kernel method to extend LDA, \n%     proposed by Baudat et al. The generalized eigen-problem is\n%     solved in a default way by slsymgeig.\n%\n%   - A = slgda(K, nums, sol) in the function, slsymgeig will be invoked \n%     to solve the generalized eigen-decomposition problem. sol is \n%     a cell containing the parameters for slsymgeig. \n%\n% $ Remarks $\n%   - The function follows the instructions given in the original paper\n%     on GDA.\n%\n%   - The projection is learned after the kernel gram matrix is\n%     centralized.\n%\n%   - The aim of the function is to give an exact implementation of \n%     of representative work GDA, so it does not offer other facilities\n%     such as weighting and other ways of scatter computation. For higher\n%     flexibility, please use the function slkfd.\n%\n% $ History $ \n%   - Created by Dahua Lin on May 3rd, 2005\n%\n\n%% parse and verify input arguments\n\nif nargin < 2\n    raise_lackinput('slkernelscatter', 2);\nend\n\nif ndims(K) ~= 2 || size(K, 1) ~= size(K, 2)\n    error('sltoolbox:invaliddims', ...\n        'The gram matrix K should be a square matrix');\nend\n\nM = size(K, 1);         % number of samples\nN = length(nums);       % number of classes\nif ~isequal(size(nums), [1, N])\n    error('sltoolbox:invaliddims', ...\n        'The nums should be a 1 x N row vector');\nend\nif sum(nums) ~= M\n    error('sltoolbox:sizmismatch', ...\n        'The total number in nums is inconsistent with that in K');\nend\n\nif nargin < 3\n    sol = {};\nend\n\n%% Compute\n\n%% Centralize\n\nK = slcenkernel(K);\n\n%% Construct the eigen-problem\n\n[sp, ep] = slnums2bounds(nums);\nW = zeros(M, M);\nfor i = 1 : N\n    ni = nums(i);\n    spi = sp(i); epi = ep(i);\n    W(spi:epi, spi:epi) = 1 / ni;    \nend\nclear sp ep;\n\nB = K * W * K;\nclear W;\n\nV = K * K;\n\n%% Resolve the eigen-problem\n\n[evs, A] = slsymgeig(B, V, sol{:});\nd = sldim_by_eigval(evs);\nA = A(:, 1:d);\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/kernel/slgda.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5855895703333761}}
{"text": "% K-nearest Neighbor (9/12/2020)\n\nfunction Acc = jknn(feat,label,opts)\n% Default of k-value\nk = 5;\n\nif isfield(opts,'k'), k = opts.k; end\nif isfield(opts,'Model'), Model = opts.Model; end\n\n% Define training & validation sets\ntrainIdx = Model.training;    testIdx = Model.test;\nxtrain   = feat(trainIdx,:);  ytrain  = label(trainIdx);\nxvalid   = feat(testIdx,:);   yvalid  = label(testIdx);\n% Training model\nMy_Model = fitcknn(xtrain,ytrain,'NumNeighbors',k); \n% Prediction\npred     = predict(My_Model,xvalid);\n% Accuracy\nAcc      = sum(pred == yvalid) / length(yvalid);\n\nfprintf('\\n Accuracy: %g %%',100 * Acc);\nend\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/jknn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5855895664954545}}
{"text": "classdef CEC2008_F5 < PROBLEM\n% <single> <real> <large/none> <expensive/none>\n% Shifted Griewank's function\n\n%------------------------------- Reference --------------------------------\n% K. Tang, X. Yao, P. N. Suganthan, C. MacNish, Y.-P. Chen, C.-M. Chen, and\n% Z. Yang, Benchmark functions for the CEC'2008 special session and\n% competition on large scale global optimization, Nature Inspired\n% Computation and Applications Laboratory, USTC, China, 2007.\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        O;  % Optimal decision vector\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2008.mat'),'Data');\n            obj.O = Data{5};\n            obj.M = 1;\n            if isempty(obj.D); obj.D = 100; end\n            obj.D = min(obj.D,length(obj.O));\n            obj.lower    = zeros(1,obj.D) - 600;\n            obj.upper    = zeros(1,obj.D) + 600;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopObj = 1/4000*sum(Z.^2,2) - prod(cos(Z./sqrt(repmat(1:size(Z,2),size(Z,1),1))),2) + 1;\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/Single-objective optimization/CEC 2008/CEC2008_F5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5855895540828839}}
{"text": "function y = modulate2(x, type, center)\n% MODULATE2\t2D modulation\n%\n%\ty = modulate2(x, type, [center])\n%\n% With TYPE = {'r', 'c' or 'b'} for modulate along the row, or column or\n% both directions.\n%\n% CENTER secify the origin of modulation as floor(size(x)/2)+1+center\n% (default is [0, 0])\n\nif ~exist('center', 'var')\n    center = [0, 0];\nend\n\n% Size and origin\ns = size(x);\no = floor(s / 2) + 1 + center;\n\nn1 = [1:s(1)] - o(1);\nn2 = [1:s(2)] - o(2);\n\nswitch lower(type(1))\n    case 'r'\n\tm1 = (-1) .^ n1;\n\ty = x .* repmat(m1', [1, s(2)]);\n\t\n    case 'c'\n\tm2 = (-1) .^ n2;\n\ty = x .* repmat(m2, [s(1), 1]);\n\t\n    case 'b'\n\tm1 = (-1) .^ n1;\n\tm2 = (-1) .^ n2;\n\tm = m1' * m2;\n\ty = x .* m;\n\t\n    otherwise\n\terror('Invalid input type');\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/nsct_toolbox/modulate2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5855895478765982}}
{"text": "function stroud_test35 ( )\n\n%*****************************************************************************80\n%\n%% TEST35 tests SQUARE_UNIT_SET, RECTANGLE_SUB_2D.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    06 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  global FUNC_2D_INDEX;\n\n  num = function_2d_num ( );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST35\\n' );\n  fprintf ( 1, '  SQUARE_UNIT_SET sets up a quadrature rule\\n' );\n  fprintf ( 1, '    on a unit square.\\n' );\n  fprintf ( 1, '  RECTANGLE_SUB_2D applies it to subrectangles of an\\n' );\n  fprintf ( 1, '    arbitrary rectangle.\\n' );\n  fprintf ( 1, '\\n' );\n%\n%  Set the location of the square.\n%\n  xval(1) = 1.0;\n  yval(1) = 2.0;\n\n  xval(2) = 3.0;\n  yval(2) = 3.0;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The corners of the rectangle are:\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  %12f  %12f\\n', xval(1), yval(1) );\n  fprintf ( 1, '  %12f  %12f\\n', xval(2), yval(2) );\n%\n%  Get the quadrature abscissas and weights for a unit square.\n%\n  rule = 2;\n\n  order = square_unit_set ( rule );\n\n  [ xtab, ytab, weight ] = square_unit_set ( rule, order );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Using unit square integration rule number %d\\n', rule );\n%\n%  Set the function.\n%\n  for i = 1 : num\n\n    FUNC_2D_INDEX = i;\n%\n%  Try an increasing number of subdivisions.\n%\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '    Function  Subdivisions  Integral\\n' );\n    fprintf ( 1, '\\n' );\n\n    for j = 1 : 5\n\n      nsub(1) = j;\n      nsub(2) = 2 * j;\n\n      result = rectangle_sub_2d ( 'function_2d', xval, yval, nsub, order, xtab, ...\n        ytab, weight );\n\n      fname = function_2d_name ( i );\n\n      fprintf ( 1, '  %s  %2d  %2d  %14f\\n', fname, nsub(1), nsub(2), result );\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/stroud/stroud_test35.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5855652694733211}}
{"text": "function uknt = kntunclamp (knt, deg, k, dim)\n% KNTUNCLAMP: Compute the unclamped knot vector starting from an open one.\n%\n% Calling Sequence:\n% \n%   uknt = kntunclamp (knt, deg, k)\n%   uknt = kntunclamp (knt, deg, k, dim)\n% \n% INPUT:\n% \n%   knt\t: open knot vector: see kntrefine\n%   deg : polynomial degree of the spline space\n%   k   : continuity for the unclamping (from 0 up to p-1)\n%   dim : dimensions in which to unclamp (all by default).\n%\n% OUTPUT:\n% \n%   uknt: unclamped knot vector, see nrbmak\n% \n% Description:\n% \n%     Unclamps directly the open knot vector. See nrbunclamp\n%    for further information.\n% \n%    Copyright (C) 2013, 2014 Rafael Vazquez\n%    Copyright (C) 2020, Bernard Kapidani\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 <http://www.gnu.org/licenses/>.\n\n  knt_is_cell = true;\n  if (~iscell (knt))\n    knt = {knt};\n    knt_is_cell = false;\n  end\n  uknt = knt;\n  \n  ndim = numel (knt);\n  if (nargin < 4)\n    dim = 1:ndim;\n  end\n  \n\n% if (iscell (knt))\n  if (numel(k) < ndim)\n    k = [k(:).', k(end) * ones(1, ndim-numel(k))];\n  end\n  \n  assert (numel(deg) == ndim, 'degrees and knots must have the same size');\n  for idim = dim\n      \n    U  = knt{idim};\n    \n    p  = deg(idim);\n    n  = numel(U) - p - 1;\n    m  = n + p + 1;\n    kk = k(idim);\n\n    if (kk >= p)\n      warning ('Taking the maximum k allowed, degree - 1')\n      kk = p - 1;\n    end\n\n  % Unclamp at left end\n    for ii=0:kk\n      U(kk-ii+1) = U(kk-ii+2) - (U(n+1-ii) - U(n-ii));\n    end\n\n  % Unclamp at right end\n    for ii=0:kk\n      U(m-kk+ii) = U(m-kk+ii-1) + U(p+ii+1+1) - U(p+ii+1);\n    end\n    \n    uknt{idim} = U;\n\n  end\n  \n  if (~knt_is_cell)\n    uknt = uknt{1};\n  end\n  \nend\n\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/utils/kntunclamp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.5855652612904374}}
{"text": "function Line=findlyap(MainHandles)\n%FINDLYAP  determines the Lyapunov exponents and dimension\n%\n%    The alogrithm employed in this toolbox for determining Lyapunov\n%    exponents is according to the algorithms proposed in\n%\n%    [1] 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%    [2] J. P. Eckmann and D. Ruelle, \"Ergodic Theory of Chaos and Strange\n%        Attractors,\" Rev. Mod. Phys., Vol. 57, pp. 617-656, 1985.\n%\n%    The algorithm given in [1] is used for first-order systems while\n%    the QR-based algorithm proposed in [2] is applied for higher order\n%    systems.\n\n%   by Steve W. K. SIU, July 5, 1998.\n\n\n%Print the results to the file every iteration\nPrintStep=10;\n%Display the results on the screen every iteration\nDisplayStep=1;\n\n%Clear the current axis objects\ncla;\nv=axis;\nxc=(v(2)+v(1))/2;\t%Center of the axis box [xc,y]\ny=(v(4)+v(3))/2;\naW=v(2)-v(1);\t\t%Axis width\nx=xc-1/4*aW;\n\n%Display the text \"Loading... Please wait!\"\nth=text(x,y,'Loading... Please wait!','Color','r','FontSize',15,...\n   \t'FontAngle','italic');\ndrawnow;\n%Clear the bottom text if any\nset(MainHandles(1),'String','');\n\n%Get the data stored in 'UserData' of the setting button\nDATA=get(MainHandles(4),'UserData');\n%Restore the data input by the user\noutput=DATA(1);\t\t%Output checkbox: \"on\"=1; \"off\"=0\nLEout=DATA(2);\t\t\t%Output Lyapunov exponents to file: \"yes\"=1; \"no\"=0\nLEprec=DATA(3);      %Precision of the output Lyapunov exponents\nLDout=DATA(4);\t\t\t%Output Lyapunov dimension to file: \"yes\"=1; \"no\"=0\nLDprec=DATA(5);      %Precision of the Lyapunov dimension\nIntMethod=DATA(6);\t%Integration method: 1=Discrete map, 2=ODE45, 3=ODE23\n\t\t\t\t\t\t\t% 4=ODE113, 5=ODE23S, 6=ODE15S\nInitialTime=DATA(7);\t%Initial time\nFinalTime=DATA(8);\t%Final time\nTimeStep=DATA(9);\t\t%Time step\nRelTol=DATA(10);\t\t%Relative tolerance\nAbsTol=DATA(11);\t\t%Absolute tolerance\nplot1=DATA(12);\t\t%Plot imediately: 1=\"checked\", 0=\"unchecked\"\nplot2=DATA(13);\t\t%Plot according to specified iterations\nItrNum=DATA(14);\t\t%No. of iteration for updating the plot\nColor=DATA(15);\t\t%Line Color option\n\t\t\t\t\t\t\t%Line color: 1=\"blue\", 2=\"balck\", 3=\"green\", 4=\"red\",\n                     %5=\"yellow\", 6=\"magenta\", 7=\"cyan\"\nDiscardItr=DATA(16);\t%Iterations to be discarded\nUpdateStepNum=DATA(17);\t%Lyapunov exponents updating steps\nlinODEnum=DATA(18);\t%No. of linearized ODEs\nic=DATA(19:length(DATA));\t%Initial conditions\n\n%Get the output file and ODE function names stored in\n%'UserData' of the \"Start\" button.\n%Handles(2) is the handle of \"Start\" button\nNAMES=get(MainHandles(2),'UserData');\nOutputFile=rmspace(NAMES(1,:));\nodefun=rmspace(NAMES(2,:));\n\n%Construct a look-up table for the line colors\nCOLORS='bkgrymc';\n%Map the \"Line color\" pop-up menu position to the look-up table\nLineColor=COLORS(Color);\t\n\n%Construct a look-up table for integration methods\nMethods=char('Discrete map', 'ode45','ode23','ode113','ode23s','ode15s');\nODEsolver=strcat(Methods(IntMethod,:));\n\n%Dimension of the linearized system (total: d x d ODEs)\nd=sqrt(linODEnum);\n%Initial conditions for the linearized ODEs\nQ0=eye(d);\nIC=[ic(:);Q0(:)];\nICnum=length(IC);\t\t%Total no. of initial coniditions\n%One iteration: Duration for updating the LEs\nIteration=UpdateStepNum*TimeStep;\t\nDiscardTime=DiscardItr*Iteration+InitialTime;\n\n%MATLAB's ODE functions will give the intermediate solutions if \n%the duration between the initial time and the final time is only\n%one time step, this will slow down the whole iteration process. \n%To avoid this, reduce the time step by half.\nif (UpdateStepNum==1 & IntMethod~=3)\n   TimeStep=TimeStep/2;\nend\n\nT1=InitialTime;\nT2=T1+Iteration;\nTSpan=[T1:TimeStep:T2];\n%Absolute tolerance of each components is set to the same value\noptions=odeset('RelTol',RelTol,'AbsTol',ones(1,ICnum)*AbsTol);\n\n%Initialize variables\nn=0;\t\t\t%Iteration counter\nk=0;\t\t\t%Effective iteration counter\n\t\t\t\t% (discarded iterations are not counted)\nh=1;\t\t\t%No. of line handles sets (1 set = d line handles)\ndelLine=0;  %Indicator for deleting the drawn lines            \nSum=zeros(1,d);\nxData=[];\nyData=[];\nLine=[];\nbufferSize=10000; %Max. no. of data can be stored in the buffer before creating a new line.\nif ( output & (LEout | LDout) )\n   %If the output file cannot be opened, warn the user\n   msg=['Unable to open \"' sprintf(OutputFile) '\".'];\n   Warn='errordlg(msg,''ERROR'',''replace''); problem=1;';\n   eval('fid=fopen(OutputFile,''wt''); problem=0;',Warn)\n   %Construct a look-up table for precision format\n   Prec=char('%.4f','%.6f','%.8f','%.10f','%.12f');\n   %Map the pop-up menu position to its corresponding format\n   LEprecision=strcat(Prec(LEprec,:));\n   LDprecision=strcat(Prec(LDprec,:));\n   if ~problem\n      fprintf(fid,'Time');\n      if LEout\n         for i=1:d\n            Str1=['\\tLE%d'];\n            fprintf(fid,Str1,i);\n         end\n      end\n      if LDout\n         Str2=['\\tLD'];\n         fprintf(fid,Str2); \n      end\n      fprintf(fid,'\\n');\n   end\nelse\n   problem=0;\nend\n\n%Start the stop watch\ntic;\n%Get the state of the \"Stop\" button\nstop=get(MainHandles(3),'UserData');\nif DiscardTime>0\n   %Display the text \"Discarding transient steps...\"\n   set(MainHandles(1),'String','Discarding transient steps...');\nend\n\nA=[];\n\n%String that contains the integration command\nIntegrationStr=['[t,X]=',ODEsolver,'(odefun,TSpan,IC,options);'];\n%Main loop\nwhile (~stop & ~problem)\n   n=n+1;\n   %Integration\n   if IntMethod>1\n      eval(IntegrationStr);\n   else\t%If it is a discrete map\n      for i=1:UpdateStepNum\n         X(i,:)=(feval(odefun,IC))';\n      end\n   end\n   [rX,cX]=size(X);\n   L=cX-linODEnum;      %No. of initial conditions for \n                        %the original system\n   for i=1:d\n      m1=L+1+(i-1)*d;\n      m2=m1+d-1;\n      A(:,i)=(X(rX,m1:m2))';\n   end\n   %QR decomposition\n   if d>1\n      %The algorithm for 1st-order system doesn't require\n      %QR decomposition\n      [Q,R]=qr(A);\n      if T2>DiscardTime\n         Q0=Q;\n      else\n         Q0=eye(d);\n      end\n   else\n      R=A;\n   end\n      \n   \n   %Delete the text \"Loading...Please wait!\" \n   %before the first iteration\n   if n==1\n      delete(th);\n      drawnow;\n      %Display the final time\n      set(MainHandles(11),'String',FinalTime);\n   end\n   \n  %Any zero diagonal element will cause overflow\n  %in the following calculation, so discard this step.\n   permission=1;\n   for i=1:d\n      if R(i,i)==0\n         permission=0;\n         break;\n      end\n   end\n  %To determine the Lyapunov exponents\n   if (T2>DiscardTime & permission)\n      k=k+1;\n      T=k*Iteration;\n      TT=n*Iteration+InitialTime;\n      %There are d Lyapunov exponents\n      Sum=Sum+log(abs(diag(R))');\n      lambda=Sum/T;\n      \n      %Sort the Lyapunov exponents in descenting order\n      Lambda=fliplr(sort(lambda));\n      %To calculate the Lyapunov dimension (or Kaplan-Yorke dimension)\n      LESum=Lambda(1);\t\t\t\n      LD=0;\n      if (d>1 & Lambda(1)>0)\n         for N=1:d-1\n            if Lambda(N+1)~=0\n               LD=N+LESum/abs(Lambda(N+1));\n               LESum=LESum+Lambda(N+1);\n               if LESum<0\n                  break;\n               end\n            end\n         end\n      end\n      %Store the [x,y] data for plotting\n      [rxD,cxD]=size(xData);\n      [ryD,cyD]=size(yData);\n      if rxD<=bufferSize\n         xData=[xData;TT];\n         yData=[yData;lambda];\n      else\n         %When the buffers are full, refresh them\n         %Max. size of buffers = 10000 data\n         xData=[xData(rxD);TT];\n         yData=[yData(ryD,:);lambda];\n         h=h+1;\t\t%add one set of line handles\n         delLine=0;\t%After refreshing the buffers, the\n                     % previous drawn lines must not be deleted\n      end\n      \n      if ( output & ~problem & (LEout | LDout) & rem(k,PrintStep)==0)\n         fprintf(fid,'%.2f',TT);\n         if LEout\n            for i=1:d\n               Str1=['\\t',LEprecision];\n               fprintf(fid,Str1,Lambda(i));\n            end\n         end\n         if LDout\n            Str2=['\\t',LDprecision];\n            fprintf(fid,Str2,LD);\n         end\n         fprintf(fid,'\\n');\n      end\n\n      %Draw lines immediately if \"update the plot immediately\" was chosen.\n      if (plot1==1 | plot2==1 & rem(k,ItrNum)==0)\n         if delLine\n            %Clear the previous drawn line if any\n            delete(Line(h,:));\n         end\n      \t%Draw d lines      \n         for i=1:d\n            %Set \"Erase Mode\" to \"none\" for increasing speed (less refresh)\n            Line(h,i)=line('EraseMode','none','Color',LineColor,...\n                      'xData',xData,'yData',yData(:,i));\n            %Force MATLAB to draw immediately\n            drawnow;\n         end\n         delLine=1;\t%Set a flag to indicate that the lines now can be deleted\n      end\n      %Display the calculated Lyapunov exponents\n      if rem(k,DisplayStep)==0\n         set(MainHandles(1),'String',[num2str(Lambda),blanks(3),'( ',num2str(LD),' )']);\n      end\n   end\n   \n\n   %To see whether \"Stop\" is pressed\n   stop=get(MainHandles(3),'UserData');\n   \n   %Display current time, and time used\n   set(MainHandles(10),'String',num2str(round(T2)));\t\t%Current time\n   set(MainHandles(12),'String',num2str(round(toc)));\t\t%Used time\n   drawnow;\n   \n   %If calculation is finished or \"stop\" button is pressed, exit the loop.\n   if (stop | T2>=FinalTime)\n      %Reset the \"Erase mode\" to normal\n      set(Line,'EraseMode','normal');\n      %Show the final results (for making sure the final results being shown if DisplayStep>1)\n      if (T2>DiscardTime & permission)\n         set(MainHandles(1),'String',[num2str(Lambda),blanks(3),'( ',num2str(LD),' )']);\n      end\n      break;\n   end\n   %Update the initial conditions and time span for the next iteration\n   if IntMethod>1\n      ic=X(rX,1:L);\n      T1=T1+Iteration;\n      T2=T2+Iteration;\n      TSpan=[T1:TimeStep:T2];\n   else %For discrete map\n      ic=X(UpdateStepNum,1:L);\n      T2=T2+Iteration;\n   end\n   IC=[ic(:);Q0(:)];\nend\t\t%End of main loop\n\nif T2>=FinalTime\n   set(MainHandles([2,4,13,15]),'Enable','On');\n   set(MainHandles(3),'Enable','Off');\nend\nif (output & ~problem)\n   fclose(fid);\nend\n\n%----------------Subroutine-----------------------------------\nfunction outStr=rmspace(inStr)\n%RMSPACE\t\tFunction for removing the beginning and ending\n%\t\t\t\tspaces of a string\n\n%Remove spaces at the end of the string\noutStr=strcat(inStr);\n%Delete spaces at the beginning of the string\nif ~isempty(outStr)\n   while isspace(outStr(1))\n   \toutStr=outStr(2:length(outStr));\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/233-let/LET/findlyap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.5855652575895814}}
{"text": "function [ n_data, x, cbi ] = airy_cbi_values ( n_data )\n\n%*****************************************************************************80\n%\n%% AIRY_CBI_VALUES returns some values of the Airy Bi(x) with complex argument.\n%\n%  Discussion:\n%\n%    The Airy functions Ai(X) and Bi(X) are a pair of linearly independent\n%    solutions of the differential equation:\n%\n%      W'' - X * W = 0\n%\n%    In Mathematica, the function can be evaluated by:\n%\n%      AiryBi[x]\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    13 April 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, complex X, the argument of the function.\n%\n%    Output, complex CBI, the value of the Airy BI function.\n%\n  n_max = 10;\n\n  cbi_vec = [ ...\n    1.207423594952871  + 0.0000000000000000 * i, ...\n    0.9127160108293936 + 0.3800456133135556 * i, ...\n    0.6824453575635721 + 0.3343047153635002 * i, ...\n    0.5726265660086474 + 0.3988641086982559 * i, ...\n    0.2511841251049547 + 0.3401447690712719 * i, ...\n    0.1039973894969446 + 0.0000000000000000 * i, ...\n    0.2511841251049547 - 0.3401447690712719 * i, ...\n    0.5726265660086474 - 0.3988641086982559 * i, ...\n    0.6824453575635721 - 0.3343047153635002 * i, ...\n    0.9127160108293936 - 0.3800456133135556 * i ];\n\n  x_vec = [ ...\n     1.0000000000000000 + 0.0000000000000000 * i, ...\n     0.8090169943749474 + 0.5877852522924731 * i, ...\n     0.3090169943749474 + 0.9510565162951536 * i, ...\n    -0.3090169943749474 + 0.9510565162951536 * i, ...\n    -0.8090169943749474 + 0.5877852522924731 * i, ...\n    -1.0000000000000000 + 0.0000000000000000 * i, ...\n    -0.8090169943749474 - 0.5877852522924731 * i, ...\n    -0.3090169943749474 - 0.9510565162951536 * i, ...\n     0.3090169943749474 - 0.9510565162951536 * i, ...\n     0.8090169943749474 - 0.5877852522924731 * i ];\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    cbi = 0.0;\n  else\n    x = x_vec(n_data);\n    cbi = cbi_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/airy_cbi_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5855652546698965}}
{"text": "function z=fun00(x)\nz=0;\nfor i=1:length(x)\n    z=z+x(i)*sin(abs(x(i)));\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/11317-genetic-algorithm-performance/Genetic Algorithm/fun00.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5855652531075537}}
{"text": "function u = acsc(a)\n%ACSC         Slope inverse cosecant acsc(a)\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 09/28/08     S.M. Rump  check for rounding to nearest improved\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  e = 1e-30;\n  if 1+e==1-e                           % fast check for rounding to nearest\n    rndold = 0;\n  else\n    rndold = getround;\n    setround(0)\n  end\n\n  INTLAB_SLOPE = getappdata(0,'INTLAB_SLOPE');\n\n  u = a;\n\n  u.r = acsc(a.r);\n  indexc = 1:INTLAB_SLOPE.NUMVAR;\n  indexr = 2:INTLAB_SLOPE.NUMVAR+1;\n  Xxs = hull(a.r(:,indexc),a.r(:,indexr));\n  Index = 1:size(a.r.inf,1);\n\n  index = all( a.r.sup<=0 , 2);\n  if any(index)\n    aindex.r = a.r(index,:);\n    aindex.s = a.s(index,:);\n    u.s(index,:) = ...\n      slopeconvexconcave('acsc','-1./(abs(%).*sqrt(sqr(%)-1))',aindex,0);\n    Index(index) = 0;\n  end\n\n  index = all( a.r.inf>=0 , 2);\n  if any(index)\n    aindex.r = a.r(index,:);\n    aindex.s = a.s(index,:);\n    u.s(index,:) = ...\n      slopeconvexconcave('acsc','-1./(abs(%).*sqrt(sqr(%)-1))',aindex,1);\n    Index(index) = 0;\n  end\n\n  if any(Index)\n    Index( Index==0 ) = [];\n    Xxs = Xxs(Index);\n    u.s(Index,:) = - a.s(Index,:) ./ ( abs(Xxs) .* sqrt( sqr(Xxs)-1 ) );\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/slope/@slope/acsc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5854899897603946}}
{"text": "function varargout = nifti_stats(varargin)\n% Conversion among various statistics\n% FORMAT P = nifti_stats(VAL,CODE,OPT,PARAM)\n%   CODE can be one of\n%     'CORREL'      'TTEST'       'FTEST'       'ZSCORE'\n%     'CHISQ'       'BETA'        'BINOM'       'GAMMA'\n%     'POISSON'     'NORMAL'      'FTEST_NONC'  'CHISQ_NONC'\n%     'LOGISTIC'    'LAPLACE'     'UNIFORM'     'TTEST_NONC'\n%     'WEIBULL'     'CHI'         'INVGAUSS'    'EXTVAL'\n%     'PVAL'\n%   With only one input argument, CODE defaults to 'ZSCORE'\n%\n%   OPT can be one of\n%     '-p' ==> output P = Prob(statistic < VAL).\n%     '-q' ==> output is 1-p.\n%     '-d' ==> output is probability density.\n%     '-1' ==> output is X such that Prob(statistic < x) = VAL.\n%     '-z' ==> output is Z such that Normal cdf(Z) = p(VAL).\n%     '-h' ==> output is Z such that 1/2-Normal cdf(Z) = p(VAL).\n%   With less than three input arguments, OPT defaults to '-p'.\n%\n%   PARAM are up to three distribution parameters.\n%   These default to zero if unspecified.\n%\n%   P is an array with the same dimensions as VAL.\n%\n%__________________________________________________________________________\n% 99.99% of the work by RW Cox - SSCC/NIMH/NIH/DHHS/USA/EARTH - March 2004\n%  0.01% of the work (the mex wrapper) by John Ashburner - FIL/ION/UCL\n% Copyright (C) 2005-2017 Wellcome Trust Centre for Neuroimaging\n\n%\n% $Id: nifti_stats.m 7147 2017-08-03 14:07:01Z spm $\n\n\nfprintf('******************************************\\n');\nfprintf('Compile the nifti_stats function with\\n');\nfprintf('    mex nifti_stats.c nifti_stats_mex.c -O\\n');\nfprintf('******************************************\\n');\n\nerror('nifti_stats is not compiled.');\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/@nifti/private/nifti_stats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5854899811646763}}
{"text": "function val = m00Q0011(F00, F11)\n%------------------------------------------------------------------------------\n%\n% Integrates interpolated gridfunction F on quincunx grid (F00 united with F11)\n% where interpolation is assumed piecewise constant.\n%\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw <Paul.de.Zeeuw@cwi.nl>  http://homepages.cwi.nl/~pauldz/\n% Last Revision: February 1, 2001.\n%  2001 Stichting CWI, Amsterdam\n%------------------------------------------------------------------------------\n[hx, hy] = Q0011gridfdims(F00, F11);\nQhxy = 2 * hx * hy;\nval = ( sum(sum(F00)) + sum(sum(F11)) ) * Qhxy;\n%------------------------------------------------------------------------------\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/m00Q0011.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5854899786828777}}
{"text": "function nfmi = fmi(ima, imb, imf, feature, w)\n\n% FMI calculates the Feature Mutual Information (FMI), the non-reference \n% performance metric for fusion algorithms, proposed in:\n% \n% M.B.A. Haghighat, A. Aghagolzadeh, H. Seyedarabi, \"A Non-Reference Image \n% Fusion Metric Based on Mutual Information of Image Features,\" Computers \n% and Electrical Engineering, vol. 37, no. 5, pp. 744-756, Sept. 2011.\n% http://dx.doi.org/10.1016/j.compeleceng.2011.07.012\n% \n% \n% This code is the implementation of FAST-FMI, presented in:\n% \n% M. Haghighat, M.A. Razian, \"Fast-FMI: non-reference image fusion metric,\"\n% 8th International Conference on Application of Information and \n% Communication Technologies (AICT), pp. 1-3, 2014.\n% \n% \n% Inputs:\n% \t\tima \t: \tFirst source image\n% \t\timb \t: \tSecond source image\n% \t\timf \t: \tFused image\n% \t\tfeature : \tFeature extraction method: gradient, edge, dct, wavelet, none (raw pixels) (default: image with no feature extraction)\n% \t\tw       : \tSliding window size w by w (default: 3)\n% \n% Output:\n% \t\tnfmi \t: \tNormalized Feature Mutual Information\n% \n% \n% Sample use:\n% nfmi = fmi(ima,imb,imf,'none',3);\n% % Or simply:\n% nfmi = fmi(ima,imb,imf);\n% \n% \n% (C)\tMohammad Haghighat, University of Miami\n%       haghighat@ieee.org\n%       IF YOU USE THIS CODE IN YOUR WORK, PLEASE CITE THE ABOVE PAPERS.\n\n\n\nif nargin < 3               % Check correct number of arguments\n    error('There should be three input images (2 source images and 1 fused image)!');\nend\n\nif size(ima) ~= size(imb)\t% Check if the source images are of the same size\n    error('Size of the source images must be the same!');\nend\n\nif size(ima) ~= size(imf)\t% Check if the source images are of the same size\n    error('Size of the source and fused images must be the same!');\nend\n\nif ~exist('feature', 'var')\n    feature = 'edge';       % Default feature extraction\nend\n\nif ~exist('w', 'var')\n    w = 3;                  % Default window size\nend\n\nima = double(ima);\nimb = double(imb);\nimf = double(imf);\n\n\n% Feature Extraction\n\nswitch feature\n    \n\tcase 'none'         % Raw pixels (no feature extraction)              \n        aFeature = ima;\n        bFeature = imb;\n        fFeature = imf;\n        \n    case 'gradient'     % Gradient\n        aFeature = gradient(ima);\n        bFeature = gradient(imb);\n        fFeature = gradient(imf);\n        \n    case 'edge'         % Edge\n        aFeature = edge(ima);\n        bFeature = edge(imb);\n        fFeature = edge(imf);\n        \n    case 'dct'          % DCT\n        aFeature = dct2(ima);\n        bFeature = dct2(imb);\n        fFeature = dct2(imf);\n        \n    case 'wavelet'      % Discrete Meyer wavelet\n        [cA,cH,cV,cD] = dwt2(ima,'dmey');\n        aFeature = rerange([cA,cH;cV,cD]);\n        [cA,cH,cV,cD] = dwt2(imb,'dmey');\n        bFeature = rerange([cA,cH;cV,cD]);\n        [cA,cH,cV,cD] = dwt2(imf,'dmey');\n        fFeature = rerange([cA,cH;cV,cD]);\n       \n    otherwise\n        error('Please specify a feature extraction method among ''gradient'', ''edge'', ''dct'', ''wavelet'', or ''none'' (raw pixels)!');\n        \nend\n\n\n% Sliding window\n\n[m,n] = size(aFeature);\nw = floor(w/2);\nfmi_map = ones(m-2*w, n-2*w);\n\nfor p = w+1:m-w\n    for q = w+1:n-w\n        \n        aSub = aFeature(p-w:p+w, q-w:q+w);\n        bSub = bFeature(p-w:p+w, q-w:q+w);\n        fSub = fFeature(p-w:p+w, q-w:q+w);\n        \n        l = round((2*w+1).^2);\n        \n        if aSub == fSub\n            fmi_af = 1;\n        else\n            aMax = max(aSub(:));\n            aMin = min(aSub(:));\n            if aMax == aMin\n                aSub = ones(2*w+1);\n            else\n                aSub = (aSub - aMin)/(aMax - aMin);\n            end\n            \n            fMax = max(fSub(:));\n            fMin = min(fSub(:));\n            if fMax == fMin\n                fSub = ones(2*w+1);\n            else\n                fSub = (fSub - fMin)/(fMax - fMin);\n            end\n            \n            % Normalize the feature images to get the marginal PDFs\n            aPdf = aSub(:)./(sum(sum(aSub)));\n            fPdf = fSub(:)./(sum(sum(fSub)));\n            \n            % PDF to CDF tranformation\n            aCdf = zeros(size(aPdf));\n            fCdf = zeros(size(fPdf));\n            aCdf(1) = aPdf(1);\n            fCdf(1) = fPdf(1);\n            for i = 2:l\n                aCdf(i) = aPdf(i)+aCdf(i-1);\n                fCdf(i) = fPdf(i)+fCdf(i-1);\n            end\n            \n            % Pearson correlation between marginal PDFs\n            aTemp = aPdf - mean(aPdf);\n            fTemp = fPdf - mean(fPdf);\n            if sum(aTemp.*fTemp) == 0\n                c = 0;\n            else\n                c = sum(aTemp.*fTemp)/sqrt(sum(aTemp.*aTemp)*sum(fTemp.*fTemp));\n            end\n            \n            % Population standard deviations\n            e_aPdf = 0; e2_aPdf = 0; e_fPdf = 0; e2_fPdf = 0; \n            for i = 1:l\n                e_aPdf  = e_aPdf  + i.*aPdf(i);         % Expected value of aPdf\n                e2_aPdf = e2_aPdf + (i.^2).*aPdf(i);    % 2nd-order moment of aPdf\n                e_fPdf  = e_fPdf  + i.*fPdf(i);         % Expected value of fPdf\n                e2_fPdf = e2_fPdf + (i.^2).*fPdf(i);\t% 2nd-order moment of fPdf\n            end\n            aSd = sqrt(e2_aPdf - e_aPdf.^2);\t% Population standard deviation of aPdf\n            fSd = sqrt(e2_fPdf - e_fPdf.^2);\t% Population standard deviation of fPdf\n            \n            \n            jointEntropy = 0;\n            % Joint PDF calculation using simplified Nelsen method with joint entropy calculation\n            if c >= 0\n                \n                if c == 0 || aSd == 0 || fSd == 0\n                    phi = 0;   \n                else        \n                    covUp = 0;\n                    for i = 1:l\n                        for j = 1:l\n                            % Frechet's upper bound bivariate distributions between f & a\n                            covUp = covUp + 0.5*(fCdf(i)+aCdf(j)-abs(fCdf(i)-aCdf(j))) - fCdf(i).*aCdf(j);\n                        end\n                    end\n                    corrUp = covUp/(fSd*aSd); % Upper correlation between f & a\n                    phi = c/corrUp;\n                end\n                \n                jpdfUp = 0.5*(fCdf(1)+aCdf(1)-abs(fCdf(1)-aCdf(1)));\n                jpdf = phi.*jpdfUp + (1-phi).*fPdf(1).*aPdf(1);\n                if jpdf~=0\n                    jointEntropy = real(-jpdf.*log2(jpdf)); % Joint entropy\n                end\n                \n                % 1-D boundaries\n                for i=2:l\n                    jpdfUp = 0.5*(fCdf(i)+aCdf(1)-abs(fCdf(i)-aCdf(1))) - ...\n                        0.5*(fCdf(i-1)+aCdf(1)-abs(fCdf(i-1)-aCdf(1)));\n                    jpdf = phi.*jpdfUp + (1-phi).*fPdf(i).*aPdf(1);\n                    if jpdf~=0\n                        jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                    end\n                end\n                for j=2:l\n                    jpdfUp = 0.5*(fCdf(1)+aCdf(j)-abs(fCdf(1)-aCdf(j))) - ...\n                        0.5*(fCdf(1)+aCdf(j-1)-abs(fCdf(1)-aCdf(j-1)));\n                    jpdf = phi.*jpdfUp + (1-phi).*fPdf(1).*aPdf(j);\n                    if jpdf~=0\n                        jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                    end\n                end\n                % 2-D walls\n                for i=2:l\n                    for j=2:l\n                        jpdfUp = 0.5*(fCdf(i)+aCdf(j)-abs(fCdf(i)-aCdf(j))) - ...\n                            0.5*(fCdf(i-1)+aCdf(j)-abs(fCdf(i-1)-aCdf(j))) - ...\n                            0.5*(fCdf(i)+aCdf(j-1)-abs(fCdf(i)-aCdf(j-1))) + ...\n                            0.5*(fCdf(i-1)+aCdf(j-1)-abs(fCdf(i-1)-aCdf(j-1)));\n                        jpdf = phi.*jpdfUp + (1-phi).*fPdf(i).*aPdf(j);\n                        if jpdf~=0\n                            jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                        end\n                    end\n                end\n                \n            end\n\n            if c < 0\n                \n                if aSd == 0 || fSd == 0\n                    theta = 0;\n                else\n                    covLo = 0;\n                    for i = 1:l\n                        for j = 1:l\n                            % Frechet's lower bound bivariate distributions between f & a\n                            covLo = covLo + 0.5*(fCdf(i)+aCdf(j)-1+abs(fCdf(i)+aCdf(j)-1)) - fCdf(i).*aCdf(j);\n                        end\n                    end\n                    corrLo = covLo/(fSd*aSd); % Lower correlation between f & a\n                    theta = c/corrLo;\n                end\n                \n                jpdfLo = 0.5*(fCdf(1)+aCdf(1)-1+abs(fCdf(1)+aCdf(1)-1));\n                jpdf = theta.*jpdfLo + (1-theta).*fPdf(1).*aPdf(1);\n                if jpdf~=0\n                    jointEntropy = real(-jpdf.*log2(jpdf)); % Joint entropy\n                end\n                \n                % 1-D boundaries\n                for i=2:l\n                    jpdfLo = 0.5*(fCdf(i)+aCdf(1)-1+abs(fCdf(i)+aCdf(1)-1)) - ...\n                        0.5*(fCdf(i-1)+aCdf(1)-1+abs(fCdf(i-1)+aCdf(1)-1));\n                    jpdf = theta.*jpdfLo + (1-theta).*fPdf(i).*aPdf(1);\n                    if jpdf~=0\n                        jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                    end\n                end\n                for j=2:l\n                    jpdfLo = 0.5*(fCdf(1)+aCdf(j)-1+abs(fCdf(1)+aCdf(j)-1)) - ...\n                        0.5*(fCdf(1)+aCdf(j-1)-1+abs(fCdf(1)+aCdf(j-1)-1));\n                    jpdf = theta.*jpdfLo + (1-theta).*fPdf(1).*aPdf(j);\n                    if jpdf~=0\n                        jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                    end\n                end\n                % 2-D walls\n                for i=2:l\n                    for j=2:l\n                        jpdfLo = 0.5*(fCdf(i)+aCdf(j)-1+abs(fCdf(i)+aCdf(j)-1)) - ...\n                            0.5*(fCdf(i-1)+aCdf(j)-1+abs(fCdf(i-1)+aCdf(j)-1)) - ...\n                            0.5*(fCdf(i)+aCdf(j-1)-1+abs(fCdf(i)+aCdf(j-1)-1)) + ...\n                            0.5*(fCdf(i-1)+aCdf(j-1)-1+abs(fCdf(i-1)+aCdf(j-1)-1));\n                        jpdf = theta.*jpdfLo + (1-theta).*fPdf(i).*aPdf(j);\n                        if jpdf~=0\n                            jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                        end\n                    end\n                end\n                \n            end\n            \n            % Marginal entropies\n            index = find(aPdf~=0);\n            aEntropy = sum(-aPdf(index).*log2(aPdf(index)));\n            index = find(fPdf~=0);\n            fEntropy = sum(-fPdf(index).*log2(fPdf(index)));\n            \n            % Mutual information between a & f\n            mi = aEntropy + fEntropy - jointEntropy;  \n            \n            % Overall normalized mutual information\n            if mi == 0\n                fmi_af = 0;\n            else\n                fmi_af = 2.*mi./(aEntropy+fEntropy);\n            end\n            \n        end\n        \n        if bSub == fSub\n            fmi_bf = 1;\n        else\n            bMax = max(bSub(:));\n            bMin = min(bSub(:));\n            if bMax == bMin\n                bSub = ones(2*w+1);\n            else\n                bSub = (bSub - bMin)/(bMax - bMin);\n            end\n\n            fMax = max(fSub(:));\n            fMin = min(fSub(:));\n            if fMax == fMin\n                fSub = ones(2*w+1);\n            else\n                fSub = (fSub - fMin)/(fMax - fMin);\n            end\n\n            % PDF of the gradients of the images\n            bPdf = bSub(:)./(sum(sum(bSub)));\n            fPdf = fSub(:)./(sum(sum(fSub)));\n\n            l = length(bPdf);\n\n            % PDF to CDF tranformation\n            bCdf = zeros(size(bPdf));\n            fCdf = zeros(size(fPdf));\n            bCdf(1) = bPdf(1);\n            fCdf(1) = fPdf(1);\n            for i=2:l\n                bCdf(i) = bPdf(i)+bCdf(i-1);\n                fCdf(i) = fPdf(i)+fCdf(i-1);\n            end\n\n            % Pearson correlation between marginal PDFs\n            bTemp = bPdf - mean(bPdf);\n            fTemp = fPdf - mean(fPdf);\n            if sum(bTemp.*fTemp) == 0\n                c = 0;\n            else\n                c = sum(bTemp.*fTemp)/sqrt(sum(bTemp.*bTemp)*sum(fTemp.*fTemp));\n            end\n\n            % Population standard deviations\n            e_bPdf = 0; e2_bPdf = 0; e_fPdf = 0; e2_fPdf = 0; \n            for i = 1:l\n                e_bPdf  = e_bPdf  + i.*bPdf(i);         % Expected value of the aPdf\n                e2_bPdf = e2_bPdf + (i.^2).*bPdf(i);\t% 2nd-order moment of the aPdf\n                e_fPdf  = e_fPdf  + i.*fPdf(i);         % Expected value of the bPdf\n                e2_fPdf = e2_fPdf + (i.^2).*fPdf(i);\t% 2nd-order moment of the bPdf\n            end\n            bSd = sqrt(e2_bPdf - e_bPdf.^2);\t% Population standard deviation of the intensity\n            fSd = sqrt(e2_fPdf - e_fPdf.^2);\t% Population standard deviation of the intensity\n\n\n            jointEntropy = 0;\n            % JPDF calculation using simplified Nelsen method with joint entropy calculation\n            if c >= 0\n\n                if c == 0 || bSd == 0 || fSd == 0\n                    phi = 0;   \n                else        \n                    covUp = 0;\n                    for i = 1:l\n                        for j = 1:l\n                            % Frechet's upper bound bivariate distributions between f & b\n                            covUp = covUp + 0.5*(fCdf(i)+bCdf(j)-abs(fCdf(i)-bCdf(j))) - fCdf(i).*bCdf(j);\n                        end\n                    end\n                    corrUp = covUp/(fSd*bSd); % Upper correlation between f & b\n                    phi = c/corrUp;\n                end\n\n                jpdfUp = 0.5*(fCdf(1)+bCdf(1)-abs(fCdf(1)-bCdf(1)));\n                jpdf = phi.*jpdfUp + (1-phi).*fPdf(1).*bPdf(1);\n                if jpdf~=0\n                    jointEntropy = real(-jpdf.*log2(jpdf)); % Joint entropy\n                end\n\n                % 1-D boundaries\n                for i=2:l\n                    jpdfUp = 0.5*(fCdf(i)+bCdf(1)-abs(fCdf(i)-bCdf(1))) - ...\n                        0.5*(fCdf(i-1)+bCdf(1)-abs(fCdf(i-1)-bCdf(1)));\n                    jpdf = phi.*jpdfUp + (1-phi).*fPdf(i).*bPdf(1);\n                    if jpdf~=0\n                        jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                    end\n                end\n                for j=2:l\n                    jpdfUp = 0.5*(fCdf(1)+bCdf(j)-abs(fCdf(1)-bCdf(j))) - ...\n                        0.5*(fCdf(1)+bCdf(j-1)-abs(fCdf(1)-bCdf(j-1)));\n                    jpdf = phi.*jpdfUp + (1-phi).*fPdf(1).*bPdf(j);\n                    if jpdf~=0\n                        jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                    end\n                end\n                % 2-D walls\n                for i=2:l\n                    for j=2:l\n                        jpdfUp = 0.5*(fCdf(i)+bCdf(j)-abs(fCdf(i)-bCdf(j))) - ...\n                            0.5*(fCdf(i-1)+bCdf(j)-abs(fCdf(i-1)-bCdf(j))) - ...\n                            0.5*(fCdf(i)+bCdf(j-1)-abs(fCdf(i)-bCdf(j-1))) + ...\n                            0.5*(fCdf(i-1)+bCdf(j-1)-abs(fCdf(i-1)-bCdf(j-1)));\n                        jpdf = phi.*jpdfUp + (1-phi).*fPdf(i).*bPdf(j);\n                        if jpdf~=0\n                            jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                        end\n                    end\n                end\n\n            end\n\n            if c < 0\n\n                if bSd == 0 || fSd == 0\n                    theta = 0;\n                else\n                    covLo = 0;\n                    for i = 1:l\n                        for j = 1:l\n                            % Frechet's lower bound bivariate distributions between f & b\n                            covLo = covLo + 0.5*(fCdf(i)+bCdf(j)-1+abs(fCdf(i)+bCdf(j)-1)) - fCdf(i).*bCdf(j);\n                        end\n                    end\n                    corrLo = covLo/(fSd*bSd); % Lower correlation between f & b\n                    theta = c/corrLo;\n                end\n\n                jpdfLo = 0.5*(fCdf(1)+bCdf(1)-1+abs(fCdf(1)+bCdf(1)-1));\n                jpdf = theta.*jpdfLo + (1-theta).*fPdf(1).*bPdf(1);\n                if jpdf~=0\n                    jointEntropy = real(-jpdf.*log2(jpdf)); % Joint entropy\n                end\n\n                % 1-D boundaries\n                for i=2:l\n                    jpdfLo = 0.5*(fCdf(i)+bCdf(1)-1+abs(fCdf(i)+bCdf(1)-1)) - ...\n                        0.5*(fCdf(i-1)+bCdf(1)-1+abs(fCdf(i-1)+bCdf(1)-1));\n                    jpdf = theta.*jpdfLo + (1-theta).*fPdf(i).*bPdf(1);\n                    if jpdf~=0\n                        jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                    end\n                end\n                for j=2:l\n                    jpdfLo = 0.5*(fCdf(1)+bCdf(j)-1+abs(fCdf(1)+bCdf(j)-1)) - ...\n                        0.5*(fCdf(1)+bCdf(j-1)-1+abs(fCdf(1)+bCdf(j-1)-1));\n                    jpdf = theta.*jpdfLo + (1-theta).*fPdf(1).*bPdf(j);\n                    if jpdf~=0\n                        jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                    end\n                end\n                % 2-D walls\n                for i=2:l\n                    for j=2:l\n                        jpdfLo = 0.5*(fCdf(i)+bCdf(j)-1+abs(fCdf(i)+bCdf(j)-1)) - ...\n                            0.5*(fCdf(i-1)+bCdf(j)-1+abs(fCdf(i-1)+bCdf(j)-1)) - ...\n                            0.5*(fCdf(i)+bCdf(j-1)-1+abs(fCdf(i)+bCdf(j-1)-1)) + ...\n                            0.5*(fCdf(i-1)+bCdf(j-1)-1+abs(fCdf(i-1)+bCdf(j-1)-1));\n                        jpdf = theta.*jpdfLo + (1-theta).*fPdf(i).*bPdf(j);\n                        if jpdf~=0\n                            jointEntropy = jointEntropy + real(-jpdf.*log2(jpdf)); % Joint entropy\n                        end\n                    end\n                end\n\n            end\n\n\n            % Marginal entropies\n            index = find(bPdf~=0);\n            bEntropy = sum(-bPdf(index).*log2(bPdf(index)));\n            index = find(fPdf~=0);\n            fEntropy = sum(-fPdf(index).*log2(fPdf(index)));\n\n            % Mutual information between b & f\n            mi = bEntropy + fEntropy - jointEntropy;  \n\n            % Overall normalized mutual information\n            if mi == 0\n                fmi_bf = 0;\n            else\n                fmi_bf = 2.*mi./(bEntropy+fEntropy);\n            end\n\n        end\n        \n        fmi_map(p-w,q-w) = (fmi_af + fmi_bf)./2;\n        \n    end\nend\n\nnfmi = mean2(fmi_map);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction imNorm = rerange(im)\n\n% RERANGE changes the range of images into interval [0,1]\n\nim = double(im);\n\n[m,n] = size(im);\n\nimMax = max(im(:));\nimMin = min(im(:));\n\nif imMax == imMin\n    imNorm = ones(m,n);\nelse\n    imNorm = (im - imMin)/(imMax - imMin);\nend\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/GTF/Fusion evaluation/fmi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5854355874055612}}
{"text": "\nfunction test_solve_kron\nwarning('This function is deprecated')\n\n\nN1 = 150;\nx1 = 1:N1;\nK1 = gp_cov_pp(log(10), x1, x1);\nI1 = speye(N1);\n\nN2 = 100;\nx2 = 1:N2;\nK2 = gp_cov_pp(log(10), x2, x2);\nI2 = speye(N2);\n\n% Full matrix approach\n%K = kron(K1, K2);\n%K_noise = kron(K1+I1, K2+I2);\n%K_posterior = K - K * (K_noise \\ K);\n\n%\n% Solve: kron(K1+I1,K2+I2) \\ kron(K1,K2)\n%\n\n%K = kron(K2,K1);\n%X_full = K * (kron(K2+I2,K1+I1) \\ K);\n\n% Kronecker approach\ntic\nC1 = K1 * ((K1 + I1) \\ K1);\nC2 = K2 * ((K2 + I2) \\ K2);\nX_kron = diag(C1) * diag(C2)';\n%X_kron = dot(K1,C1,1)' * dot(K2,C2,1);\ntoc\n\n% Conjugate gradient approach\n%\n% Computing the variances is veeery expensive...\ntic\nafun = @(x) reshape(kronprod(K1+I1,K2+I2,reshape(x,N1,N2)), N1*N2, 1);\nX_cg = zeros(N1,N2);\nfor n1=1:N1\n  for n2=1:N2\n    fprintf('Progress: %d %%\\n', floor(100*n1/N1));\n    x = pcg(afun, kron(K2(:,n2),K1(:,n1)), [], 2);\n    X_cg(n1,n2) = K1(n1,:) * reshape(x,N1,N2) * K2(:,n2);\n  end\nend\ntoc\n\nfull([X_kron(:), X_cg(:)])\n%full([X_kron(:), X_cg(:), diag(X_full)])\n\nfunction Y = kronprod(A, B, X)\n% kron(B', A)\nY = A*X*B;", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/deprecated/test_solve_kron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5854355867795359}}
{"text": "function y = tapas_condhalluc_obs_sim(r, infStates, p)\n% Simulates responses according to the condhalluc_obs model\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.\n\n% Inverse decision temparature beta is the only parameter\nbe = p;\n\n% Prediction trajectory\nmu1hat = infStates(:,1,1);\n\n% Get true-positive rate corresponding to stimuli\ntp = r.u(:,2);\n\n% Calculate belief x using Bayes' theorem\nx = tp.*mu1hat./(tp.*mu1hat + (1-mu1hat).^2);\n\n% Belief is mu1hat in trials where there is no tone\nx(find(tp==0)) = mu1hat(find(tp==0));\n\n% Apply the logistic sigmoid to the inferred beliefs\nprob = tapas_sgm(be.*(2.*x-1),1);\n\n% Initialize random number generator\nif isnan(r.c_sim.seed)\n    rng('shuffle');\nelse\n    rng(r.c_sim.seed);\nend\n\n% Simulate\ny = binornd(1, prob);\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_condhalluc_obs_sim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5854355641412219}}
{"text": "% Fig. 8.8   Feedback Control of Dynamic Systems, 6e \n%             Franklin, Powell, Emami\n\n%    (requires fig8_08c.mdl)\n\nclear all;\n%close all;\n\n% response comparison of continuous and digital control.\n\nclear\nclf\n[tout,yout]=sim('fig8_08c');\nr=[1 1];   %reference input\nt=[0 2];\nfigure(1)\nsubplot(2,1,1)\nplot(t,r,'r')\nhold on\nplot(ycd(:,1),ycd(:,2))\nplot(ycd(:,1),ycd(:,3),'m')\ntitle('Figure 8.8 Step Responses of Digital and Continuous Controllers')\nylabel('Position, y')\nxlabel('Time (sec)')\ntext(.33,.9, '\\leftarrow continuous  controller')\ntext(.7,1.3, 'digital  controller')\nnicegrid\nhold off\nsubplot(2,1,2)\nplot(ycd(:,1),ycd(:,4))\nhold on\nplot(ycd(:,1),ycd(:,5),'m')\nylabel('Control, u')\nxlabel('Time (sec)')\ntext(.55,10, ' continuous  controller')\ntext(.08,29, '\\leftarrow digital  controller')\nnicegrid\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig8_08.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5853527663559782}}
{"text": "function gmsh_io_test02 ( )\n\n%*****************************************************************************80\n%\n%% GMSH_IO_TEST02 reads the example data from a file.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    23 October 2014\n%\n%  Author:\n%\n%   John Burkardt\n%\n  gmsh_filename = 'example_2d.msh';\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'GMSH_IO_TEST02:\\n' );\n  fprintf ( 1, '  Read data from a file.\\n' );\n%\n%  Get the data size.\n%\n  [ node_num, m, element_num, element_order ] = ...\n    gmsh_size_read ( gmsh_filename );\n%\n%  Print the sizes.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Node data read from file \"%s\"\\n', gmsh_filename );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of nodes = %d\\n', node_num );\n  fprintf ( 1, '  Spatial dimension = %d\\n', m );\n  fprintf ( 1, '  Number of elements = %d\\n', element_num );\n  fprintf ( 1, '  Element order = %d\\n', element_order );\n%\n%  Get the data.\n%\n  [ node_x, element_node ] = gmsh_data_read ( gmsh_filename, m, node_num, ...\n    element_order, element_num );\n%\n%  Print some of the data.\n%\n  r8mat_transpose_print_some ( m, node_num, node_x, ...\n    1, 1, m, 10, '  Coordinates for first 10 nodes:' );\n\n  i4mat_transpose_print_some ( element_order, element_num, element_node, ...\n    1, 1, element_order, 10, '  Connectivity for first 10 elements:' );\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/gmsh_io/gmsh_io_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.5853527594021731}}
{"text": "function [ c_vec1, c_vec2 ] = real_cross( p_vec1, p_vec2, pcross_real,...\n                                            eta_c, min_realvar, max_realvar)\n%   Applies SBX over two vectors of double.\n\nnreal = length(p_vec1);\n\nepsilon = 1.0e-14 ;\n% ncross = 0 ;\n\nc_vec1 = zeros(1,nreal);\nc_vec2 = zeros(1,nreal);\n\nif(rand(1) <= pcross_real) \n% if(randomperc() <= pcross_real) % SLOW !!!\n    % ncross = ncross + 1 ;\n    if(nreal < 10)                \n        [c_vec1, c_vec2] = sbx_looped(p_vec1, p_vec2, ...\n                                    c_vec1, c_vec2, ...\n                                    epsilon, eta_c, ...\n                                    min_realvar, max_realvar);\n    else        \n        [c_vec1, c_vec2] = sbx_vectorized(p_vec1, p_vec2, ...\n                                    c_vec1, c_vec2, ...\n                                    epsilon, eta_c, ...\n                                    min_realvar, max_realvar);\n    end\nelse\n    c_vec1 = p_vec1 ;\n    c_vec2 = p_vec2 ;    \nend\nend\n\nfunction [c_vec1, c_vec2] = sbx_looped(p_vec1, p_vec2, ...\n                                            c_vec1, c_vec2, ...\n                                            epsilon, eta_c, ...\n                                            min_realvar, max_realvar)\n% This is the original implementation\nnreal = length(p_vec1);\nfor i = 1:nreal\n   if (rand(1) <= 0.5)\n   % if (randomperc() <= 0.5) % SLOW !!!\n       if (abs(p_vec1(i) - p_vec2(i)) > epsilon)\n            if (p_vec1(i) < p_vec2(i))\n                y1 = p_vec1(i) ;\n                y2 = p_vec2(i) ;\n            else\n                y1 = p_vec2(i) ;\n                y2 = p_vec1(i) ;\n            end\n            yl = min_realvar(i);\n            yu = max_realvar(i);\n            r = rand(1) ;\n            % r = randomperc() ; % SLOW !!!\n            beta_ = 1.0 + (2.0 * (y1 - yl) / (y2 - y1));\n            alpha_ = 2.0 - (beta_ ^ (-1.0 * (eta_c + 1.0)));            \n            if (r <= (1.0 / alpha_))\n                    betaq = (r * alpha_) ^ (1.0/(eta_c + 1.0));\n            else\n                    betaq = (1.0 / (2.0 - r * alpha_)) ^ (1.0 / (eta_c + 1.0));\n            end\n            c1 = 0.5 * ((y1 + y2) - (betaq * (y2 - y1)));\n            beta_ = 1.0 + (2.0 * (yu - y2)/(y2 - y1));\n            alpha_ = 2.0 - (beta_ ^ (-1.0 * (eta_c + 1.0)));\n            if (r <= (1.0 / alpha_))\n                    betaq = (r * alpha_) ^ (1.0 / (eta_c + 1.0));\n            else\n                    betaq = (1.0 / (2.0 - r * alpha_)) ^ (1.0 / (eta_c + 1.0));\n            end\n            c2 = 0.5 * ((y1 + y2) + betaq * (y2 - y1));\n            if (c1 < yl)\n                c1 = yl;\n            end\n            if (c2 < yl)\n                c2 = yl;\n            end\t\t\t\t\n            if (c1 > yu)\n                c1 = yu;\n            end\t\t\t\t\n            if (c2 > yu)\n                c2 = yu;\n            end\t\t\t\t\n            if (rand(1) <= 0.5)\n            % if (randomperc() <= 0.5) % SLOW !!!\n                c_vec1(i) = c2;\n                c_vec2(i) = c1;\n            else\n                c_vec1(i) = c1;\n                c_vec2(i) = c2;\n            end\n        else\n            c_vec1(i) = p_vec1(i) ;\n            c_vec2(i) = p_vec2(i) ;\n        end\n    else\n        c_vec1(i) = p_vec1(i) ;\n        c_vec2(i) = p_vec2(i) ;\n    end\nend\n%\nend\n\nfunction [c_vec1, c_vec2] = sbx_vectorized(p_vec1, p_vec2, ... \n                                            c_vec1, c_vec2, ...\n                                            epsilon, eta_c, ...\n                                            min_realvar, max_realvar)\n% This is the vectorized version of the above code, this will generally \n% give you 2-times speed up than the above code, especially you will \n% observe even more speed up when the length of the variable gets larger.\n% However, short variable length may make it slower (like in Osyczka's \n% problems)\nnreal = length(p_vec1);\nrandv1lthalf = rand(1,nreal) <  0.5 ;    \n% randv1lthalf = randompercv(1,nreal) <  0.5 ; % SLOW !!!\nabsdiffgteps = abs(p_vec1 - p_vec2) > (zeros(1,nreal) * epsilon) ;    \nxover_index = randv1lthalf & absdiffgteps ;\nabs_xover_index = (1:length(xover_index));\nabs_xover_index = abs_xover_index(xover_index);\np1 = p_vec1(xover_index);\np2 = p_vec2(xover_index);\nlen = length(p1);\nif(len > 0)\n    eta_cv = ones(1, len) * eta_c ;\n    rv = rand(1,len);       \n    % rv = randompercv(1,len); % SLOW !!!\n    randv2lthalf = rand(1,len) < 0.5 ;\n    % randv2lthalf = randompercv(1,len) < 0.5 ; % SLOW !!!\n    %\n    pveclt = p1 < p2 ;\n    y1v = p1 .* pveclt + p2 .* (~pveclt);\n    y2v = p1 .* (~pveclt) + p2 .* pveclt;\n    ylv = min_realvar(xover_index).' ;\n    yuv = max_realvar(xover_index).' ;\n    %\n    beta_v = 1.0 + (2.0 .* (y1v - ylv) ./ (y2v - y1v));\n    alpha_v = 2.0 - (beta_v .^ (-1.0 .* (eta_cv + 1.0)));\n    rltalpha = rv <= (1.0 ./ alpha_v);\n    % bsxfun here ?\n    betaqv = ((rv .* alpha_v) .^ (1.0 ./ (eta_cv + 1.0))) .* ... \n                rltalpha + ((1.0 ./ (2.0 - rv .* alpha_v)) .^ ...\n                    (1.0 ./ (eta_cv + 1.0))) .* (~rltalpha);\n    c1v = 0.5 .* ((y1v + y2v) - (betaqv .* (y2v - y1v)));\n    %\n    beta_v = 1.0 + (2.0 .* (yuv - y2v) ./ (y2v - y1v));\n    alpha_v = 2.0 - (beta_v .^ (-1.0 .* (eta_cv + 1.0)));\n    rltalpha = rv <= (1.0 ./ alpha_v);\n    % bsxfun here ?\n    betaqv = ((rv .* alpha_v) .^ (1.0 ./ (eta_cv + 1.0))) .* ... \n                rltalpha + ((1.0 ./ (2.0 - rv .* alpha_v)) .^ ...\n                    (1.0 ./ (eta_cv + 1.0))) .* (~rltalpha);\n    c2v = 0.5 .* ((y1v + y2v) + betaqv .* (y2v - y1v));\n    %\n    c1ltyl = c1v < ylv ;\n    c1gtyu = c1v > yuv ;\n    c1v = (c1ltyl .* ylv) + (c1v .* (~c1ltyl));\n    c1v = (c1gtyu .* yuv) + (c1v .* (~c1gtyu));        \n    c2ltyl = c2v < ylv ;\n    c2gtyu = c2v > yuv ;\n    c2v = (c2ltyl .* ylv) + (c2v .* (~c2ltyl));\n    c2v = (c2gtyu .* yuv) + (c2v .* (~c2gtyu));        \n    %        \n    p1 = c2v .* randv2lthalf + c1v .* (~randv2lthalf);\n    p2 = c1v .* randv2lthalf + c2v .* (~randv2lthalf);       \nend\n%\nc_vec1 = c_vec1' ;\nc_vec1(abs_xover_index.',1) = p1' ;\nc_vec1((~xover_index).',1) = p_vec1(~xover_index).' ;\nc_vec1 = c_vec1';\n%\nc_vec2 = c_vec2' ;\nc_vec2(abs_xover_index.',1) = p2' ;\nc_vec2((~xover_index).',1) = p_vec2(~xover_index).' ;\nc_vec2 = c_vec2' ;\n%\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/real_cross.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5853527547105247}}
{"text": "% calculate non-negative leaset squares\nfunction H = calc_nls_nmf(X, W, lambda)\n    R = size(W,2);\n    %H = inv(W'*W + lambda * eye(R)) * W'* X;\n    H = (W'*W + lambda * eye(R)) \\ W'* X;\n    H = max(H, 1e-16);\nend\n\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/online/online_auxiliary/calc_nls_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5853339436360079}}
{"text": "% hierarchical bayesian mixture model\nfunction [MCMC_State] = grp_hbmm_mcmc(varargin)\n\n% inputs:\n%   B: {subj}(M_i x M_i x Q) matrix of (possibly time-varying)  (obtain from EEG(i).CAT.Conn)\n%      connectivities or basis coefficients\n%   S: {subj}(M_i x 3) matrix of dipole locations (obtain from EEG(i).dipfit)\n%   M_i: [N x 1] vector of number of sources for each subject\n%   M:  number of clusters required\n% automatically determined:\n%   N:  number of subjects (length(B))\n%   Q:  number of basis coefficients (size(B{1},3))\n%   k:  clustering mode (1 = kmeans, 2=gmm)\n\narg_define([0 3], varargin, ...\n    arg_norep({'B','Connectivity'},mandatory,[],'Connectivity matrices. B{i} is an (M_i x M_i x Q) matrix of (possibly time-varying) connectivity values or basis coefficients for the ith subject. M_i is the number of components for the ith subject.'), ...\n    arg_norep({'S','DipoleLocations'},mandatory,[],'Dipole locations. S{i} is an (M_i x 3) matrix of [X Y Z] dipole locations for the ith subject. M_i is the number of components for the ith subject.'), ...\n    arg_norep({'MCMC_InitState'},struct([]),[],sprintf('Initial state of MCMC sampler. This can be computed from grp_hbmm_initMCMC or can be the output of a previous call to grp_hmbb_mcmc (i.e. the last state of the MCMC iterator). This structure must contain the following fields:\\nZ\\t: Mi x M matrices of group indicators\\nS_BAR\\t: cluster centroid locations\\nSIGMA_S\\t: cluster centroid variances\\nB_BAR\\t: group level connectivities\\nSIGMA_B\\t: variances of connectivities\\nN_k\\t: number of components that belong to each cluster\\nN_k1k2\\t: pairwise counts of group level clusters'),'type','struct'), ...\n    arg_sub({'hyperparams','Hyperparameters'},[],...\n    {...\n        arg({'c','ConnMeanPriorVar'},10000,[eps Inf],'Between-cluster mean connectivity prior variance. Variance of gaussian prior for between-cluster mean connectivity. Larger --> more uncertainty'), ...\n        arg({'eta','DipoleLocVarPriorShape'},[],[],'Within-cluster dipole location prior variance D.O.F. Degrees of freedom for inverse-wishart prior distribution for within-cluster dipole location covariance matrices. Leave empty to compute from initial clustering.'), ...\n        arg({'SS','DipoleLocVarPriorScale'},[],[],'Within-cluster dipole location prior variance scale. Scale matrix of inverse-wishart prior distribution for within-cluster dipole location covariance matrices. Leave empty to compute from initial clustering.'), ...\n        arg({'p1','ConnVarPriorShape','a'},1,[],'Between-cluster mean connectivity variance shape.'), ...\n        arg({'p2','ConnVarPriorScale','b'},1,[],'Between-cluster mean connectivity variance scale.'), ...\n    },'MCMC hyperparameters'), ...\n    arg({'nMCMCiters','NumMCMCIters','niter','niters'},1000, [1 Inf], 'Number of MCMC iterations for spline fitting'), ...\n    arg({'burnInFraction','BurnInFractionForMCMC'},0.5,[0 0.99],'Fraction of initial MCMC samples to discard (burn in period). The number of MCMC samples is taken to be the smaller of MCMCitersOffDiag and MCMCitersDiag.'), ...\n    arg({'thinFactor','ThinningFactor'},1,[1 Inf],'Thinning factor for MCMC. We keep every kth MCMC sample, where k=ThinningFactor. This is useful when we have limited available memory to store MCMC results since successive MCMC estimates are more likely to be correlated.'), ...\n    arg({'normlog','NormalizeAndLogTransform'},true,[],'Transform data before smoothinFactorg. Normalize across last dim (time), add 1 and take logarithm. Inverse transform is applied after smoothinFactorg'), ...\n    arg({'verb','VerbosityLevel'},2,{int32(0) int32(1) int32(2)},'Verbosity level. 0 = no output, 1 = text, 2 = graphical'), ...\n    arg({'appendLastState','AppendLastState'},false,[],'Append new state to initial MCMC state') ... \n    );\n\n%     arg({'basisCoeffVarPrior'},1000,[eps Inf],'Variance of basis coefficient gaussian prior. Larger --> more wiggling allowed'), ...\n%     arg({'noiseVarPriorShape'},0.01,[eps Inf],'Shape (D.O.F) of noise variance prior. This is the \"alpha\" parameter of the inverse gamma prior distribution. Increasing noiseVarPriorShape --> decreased variance of noise variance distribution.'), ...\n%     arg({'noiseVarPriorScale'},0.01,[eps Inf],'Scale parameter of noise variance prior. This is the \"theta\" (1/beta) parameter of inverse gamma prior distribution. Increasing noiseVarPriorScale --> right-shift of distribution --> (increase in expected noise variance). In general MEAN(noiseVariance) = noiseVarPriorScale/noiseVarPriorShape and MODE(noiseVariance) = noiseVarPriorScale/(noiseVarPriorShape-1) for noiseVarPriorShape>=1.'), ...\n%     arg({'initNoiseVariance'},0.1,[eps Inf],'Initial noise variance'), ...\n    \n\n% set up initial state of MCMC\nif isempty(MCMC_InitState)\n    error('You must provide an initial state for the MCMC iterator (MCMC_InitState)');\nend\n\n% initialize vars based on last state of MCMC_InitState\n% this will initialize the following variables:\n% 'Z','S_BAR','SIGMA_S','B_BAR','SIGMA_B','N_k','N_k1k2'\nvarnames = setdiff_bc(fieldnames(MCMC_InitState),'initstate');\nif MCMC_InitState.initstate\n    % initialize to initial state of MCMC iterator\n    for i = 1:length(varnames)\n        eval(sprintf('%s=MCMC_InitState.(''%s'');',varnames{i},varnames{i})); \n    end\nelse\n    % initialize to last state of MCMC iterator\n    for i = 1:length(varnames)\n        eval(sprintf('%s=MCMC_InitState.(''%s''){end};',varnames{i},varnames{i})); \n    end\nend\nif ~appendLastState\n    clear MCMC_InitState; \nend\n\n% define some vars\nM   = length(N_k);                      % number of clusters\nN   = length(B);                        % number of subjects\nM_i = cellfun(@(B_i) size(B_i,1),B);    % number of sources for each subject\nQ   = size(B{1},3);                     % connectivity time-series dimension\n\n% initialize prior probabilities of cluster membership\nif ~exist('MU','var')\n    MU  = ones(M,1)/M; end\n% initialize hyperparams\nif isempty(hyperparams.eta)\n    hyperparams.eta=median(N_k); end\nif isempty(hyperparams.SS)\n    hyperparams.SS = hyperparams.eta*mean(SIGMA_S,3); end\n\n% compute number of burn-in samples\nnumBurnInSamples = floor(burnInFraction*nMCMCiters);\nniterToKeep      = round((nMCMCiters-numBurnInSamples)/thinFactor);\nif verb,\n    fprintf(['I will discard %d burn-in samples.\\n' ...\n             'I will thin the distribution by a factor of %d samples\\n', ...\n             'The distribution of the estimator will have %d samples\\n'], ...\n            numBurnInSamples,thinFactor,niterToKeep);\nend\n\n%% initialize arrays of posterior draws\nZ_array         = cell(niterToKeep,1);\nS_BAR_array     = cell(niterToKeep,1);\nSIGMA_S_array   = cell(niterToKeep,1);\nB_BAR_array     = cell(niterToKeep,1);\nSIGMA_B_array   = cell(niterToKeep,1);\nMU_array        = cell(niterToKeep,1);\nN_k_array       = cell(niterToKeep,1);\nN_k1k2_array    = cell(niterToKeep,1);\niter_array      = 0;\n\n\n%% run MCMC \nfor iter=1:nMCMCiters\n\n    % Draw S_BAR (group centroid locations)\n    SSinv = double(inverse(hyperparams.SS));\n    for k=1:M\n        mu_s_bar_k=zeros(3,1);\n        Sigma_s_bar_k=double(inverse(N_k(k)*double(inverse(SIGMA_S(:,:,k)))+SSinv));\n        for i=1:N\n            if max(Z{i}(:,k))==1\n                j_k=find(Z{i}(:,k)==1);\n                for j=1:length(j_k)\n                    mu_s_bar_k=mu_s_bar_k+S{i}(j_k(j),:)';\n                end\n            end\n        end\n        mu_s_bar_k=Sigma_s_bar_k/SIGMA_S(:,:,k)*mu_s_bar_k;\n        S_BAR(k,:)=mvnrnd(mu_s_bar_k,Sigma_s_bar_k);\n    end\n\n    \n    % Draw SIGMA_S (group centroid covariance matrices)\n    for k=1:M\n        eta_k=hyperparams.eta+.5*N_k(k);\n        SS_k=hyperparams.SS;\n        for i=1:N\n            if max(Z{i}(:,k))==1\n                j_k=find(Z{i}(:,k)==1);\n                for j=1:length(j_k)\n                    SS_k=SS_k+.5*(S{i}(j_k(j),:)-S_BAR(k,:))'*(S{i}(j_k(j),:)-S_BAR(k,:));\n                end\n            end\n        end\n        SS_k=.5*(SS_k+SS_k');\n        inv_SS_k=double(inverse(SS_k));\n        inv_SS_k=.5*(inv_SS_k+inv_SS_k');\n        SIGMA_S(:,:,k)=double(inverse(wishrnd(inv_SS_k,eta_k)));\n    end  \n    \n    \n    % Draw B_BAR (group mean connectivites)\n    for k1=1:M\n        for k2=1:M\n            mu_b_bar_k1k2=zeros(Q,1);\n            Sigma_sq_b_k1k2=1/(1/hyperparams.c+N_k1k2(k1,k2)/SIGMA_B(k1,k2))*eye(Q);\n            for i=1:N\n                n_k1=sum(Z{i}(:,k1));\n                n_k2=sum(Z{i}(:,k2));\n                if(and(n_k1>=1,n_k2>=1))\n                    j_k1=find(Z{i}(:,k1)==1);\n                    j_k2=find(Z{i}(:,k2)==1);\n                    for j1=1:n_k1\n                        for j2=1:n_k2\n                            mu_b_bar_k1k2=mu_b_bar_k1k2+squish(B{i}(j_k1(j1),j_k2(j2),:));\n                        end\n                    end\n                end\n            end\n            mu_b_bar_k1k2=Sigma_sq_b_k1k2*mu_b_bar_k1k2/SIGMA_B(k1,k2);\n            B_BAR(k1,k2,:)=mvnrnd(mu_b_bar_k1k2,Sigma_sq_b_k1k2);\n        end\n    end\n    \n    % Draw SIGMA_B (group connectivity variances)\n    for k1=1:M\n        for k2=1:M\n            p1_k1k2=hyperparams.p1+.5*Q*N_k1k2(k1,k2);\n            p2_k1k2=hyperparams.p2;\n            for i=1:N\n                n_k1=sum(Z{i}(:,k1));\n                n_k2=sum(Z{i}(:,k2));\n                if(and(n_k1>=1,n_k2>=1))\n                    j_k1=find(Z{i}(:,k1)==1);\n                    j_k2=find(Z{i}(:,k2)==1);\n                    for j1=1:n_k1\n                        for j2=1:n_k2\n                            p2_k1k2=p2_k1k2+.5*sum((B{i}(j_k1(j1),j_k2(j2),:)-B_BAR(k1,k2,:)).^2);\n                        end\n                    end\n                end\n            end\n            SIGMA_B(k1,k2)=1/gamrnd(p1_k1k2,1/p2_k1k2);\n        end\n    end\n\n\n    % Draw Z (indicators of group membership)   \n    ind=randperm(N);\n    for i=ind\n        ind_i=randperm(M_i(i));\n        for j=ind_i\n            Log_p_ij=zeros(M,1);\n            for k=1:M\n                Sigma_s_ijk=SIGMA_S(:,:,k);\n                s_ijk=S{i}(j,:)-S_BAR(k,:);\n                log_p_s_ijk=-.5*log(det(Sigma_s_ijk))-.5*s_ijk/Sigma_s_ijk*s_ijk';\n                log_p_b_ijk=0;\n                for j1=1:M_i(i)\n                    if j==j1\n                        log_p_b_ijk=log_p_b_ijk-.5*Q*log(det(SIGMA_B(k,k)))...\n                        -.5*sum((B{i}(j,j,:)-B_BAR(k,k,:)).^2)/SIGMA_B(k,k);\n                    end\n                    if and(not(j==j1),find(Z{i}(j1,:)==1)==k)\n                        log_p_b_ijk=log_p_b_ijk-.5*Q*log(det(SIGMA_B(k,k)))...\n                        -.5*sum((B{i}(j1,j1,:)-B_BAR(Z{i}(j1,:)==1,Z{i}(j1,:)==1,:)).^2)/...\n                            SIGMA_B(Z{i}(j,:)==1,Z{i}(j,:)==1);                    \n                    end\n                    if not(find(Z{i}(j,:)==1)==find(Z{i}(j1,:)==1))\n                        log_p_b_ijk=log_p_b_ijk-.5*Q*log(det(SIGMA_B(k,Z{i}(j1,:)==1)))...\n                        -.5*sum((B{i}(j,j1,:)-B_BAR(k,Z{i}(j1,:)==1,:)).^2)/...\n                              SIGMA_B(k,Z{i}(j1,:)==1);\n                    end\n                end\n                for j2=1:M_i(i)\n                    if not(find(Z{i}(j2,:)==1)==find(Z{i}(j,:)==1))\n                        log_p_b_ijk=log_p_b_ijk-.5*Q*log(det(SIGMA_B(Z{i}(j2,:)==1,k)))...\n                        -.5*sum((B{i}(j2,j,:)-B_BAR(Z{i}(j2,:)==1,k,:)).^2)/...\n                                SIGMA_B(Z{i}(j2,:)==1,k);\n                    end\n                end\n                Log_p_ij(k)=MU(k)+log_p_s_ijk+log_p_b_ijk;\n            end\n            Log_p_ij=Log_p_ij-max(Log_p_ij);\n            P_ij=exp(Log_p_ij)/sum(exp(Log_p_ij));\n            v=rand;\n            Z{i}(j,:)=0*Z{i}(j,:);\n            if v<=P_ij(1)\n                   Z{i}(j,1)=1;\n                   log_p_ij=Log_p_ij(1);\n            end\n            for k=1:(M-1)\n               if(and(v>sum(P_ij(1:k)),v<=sum(P_ij(1:(k+1)))))\n                   Z{i}(j,k+1)=1;\n                   log_p_ij=Log_p_ij(k);\n               end\n            end\n        end\n    end\n\n    % Draw MU (probabilities of clusters)   \n    N_k1k2=zeros(M);\n    for k1=1:M\n        for k2=1:M\n            for i=1:N\n                n_k1=sum(Z{i}(:,k1));\n                n_k2=sum(Z{i}(:,k2));\n                if(and(n_k1>=1,n_k2>=1))\n                    if not(k1==k2)\n                        N_k1k2(k1,k2)=N_k1k2(k1,k2)+n_k1*n_k2;\n                    end                \n                    if k1==k2\n                        N_k1k2(k1,k2)=N_k1k2(k1,k2)+n_k1;\n                    end\n                end\n            end\n        end\n    end\n    N_k=diag(N_k1k2);\n    MU=drchrnd(1/M*ones(1,M)+N_k',1);\n\n    \n    % Posterior Draw arrays    \n    if and(iter>=numBurnInSamples,thinFactor*round(iter/thinFactor)==iter)\n        iter_array=iter_array+1;\n        Z_array{iter_array}=Z;\n        S_BAR_array{iter_array}=S_BAR;\n        SIGMA_S_array{iter_array}=SIGMA_S;\n        B_BAR_array{iter_array}=B_BAR;\n        SIGMA_B_array{iter_array}=SIGMA_B;\n        N_k_array{iter_array}=N_k;\n        N_k1k2_array{iter_array}= N_k1k2;\n        MU_array{iter_array}=MU;\n\n        \n        if verb\n            disp(['iter: ' num2str(iter)]);\n%             % compute and print out intermediate estimates of source locations\n%             S_BAR_mean=S_BAR_array{1};\n%             for j=2:iter_array\n%                 S_BAR_mean=S_BAR_mean+S_BAR_array{j};\n%             end\n%             S_BAR_mean=S_BAR_mean/iter_array;\n%             disp([S_BAR zeros(M,1) S_BAR_mean])\n        end\n        \n        %[sqrt(sum(min(pdist2(S_BAR_true,S_BAR_st)').^2))/M sqrt(sum(min(pdist2(S_BAR_true,S_BAR_mean)').^2))/M]\n      \n        \n        if verb\n%             %compute and print intermediate indicator probs for random subject\n%             i=discretesample(ones(N,1)/N,1);\n%             Z_i_mean=Z_array{1}{i};\n%             for j=2:iter_array\n%                Z_i_mean=Z_i_mean+Z_array{j}{i};\n%             end\n%             Z_i_mean=Z_i_mean/iter_array;\n% %         Z_st{i}\n%            disp(Z_i_mean);\n        end\n    end\nend\n\n\n% return MCMC state\nvarnames = {'Z_array','S_BAR_array','SIGMA_S_array','B_BAR_array','SIGMA_B_array','MU_array','N_k1k2_array','N_k_array'};\nfor i = 1:length(varnames)\n    % state fieldnames have trailing '_array' stripped\n    fname = strrep(varnames{i},'_array','');\n    vname = varnames{i};\n    if appendLastState\n        % append current state estimates to last state estimate\n        MCMC_State.(fname) = [MCMC_State.(fname); eval(vname)];\n    else\n        % replace last state estimate with current state estimates \n        MCMC_State.(fname) = eval(vname); \n    end\nend\nMCMC_State.initstate = false;\n\n\nfunction r = drchrnd(a,n)\n    p = length(a);\n    r = gamrnd(repmat(a,n,1),1,n,p);\n    r = r ./ repmat(sum(r,2),1,p);\n\n    ", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/grp/bayes/grp_hbmm_mcmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5853301532577292}}
{"text": "function u = log10(a)\n%LOG10        slope base 10 logarithm  log10(a)\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 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  u = a;\n\n  u.r = log10(a.r);\n  u.s = slopeconvexconcave('log10','1./(log(intval(10))*(%))',a,0);\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/slope/@slope/log10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5853301431723515}}
{"text": "function rrd = jpleph_mice (et, ntarg, ncent)\n\n% reads the jpl planetary ephemeris and gives the position and velocity\n% of the point 'ntarg' with respect to point 'ncent' using MICE routines\n\n% input\n\n%   et    = TDB julian date at which interpolation is wanted\n\n%   ntarg = integer number of 'target' point\n\n%   ncent = integer number of center point\n\n%   the numbering convention for 'ntarg' and 'ncent' is:\n\n%        1 = mercury           8 = neptune\n%        2 = venus             9 = pluto\n%        3 = earth            10 = moon\n%        4 = mars             11 = sun\n%        5 = jupiter\n%        6 = saturn\n%        7 = uranus\n\n% output\n\n%   rrd = output 6-word array containing position and velocity\n%         of point 'ntarg' relative to 'ncent'. the units are\n%         determined by the value of km passed via global.\n\n% global\n\n%   iephem  = initialization flag (1 = initialize)\n%   ephname = name of ephemeris binary data file (de436.bsp, etc.)\n%   km      = state vector units flag (1 = km & km/sec, 0 = au & au/day)\n%   au      = numerical value of astronomical unit (kilometers)\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal iephem ephname km au\n\nif (iephem == 1)\n\n    % load binary ephemeris data file\n\n    go_dir = Core.getGlobalConfig().getLocalStorageDir();\n    cspice_furnsh(fullfile(go_dir, ephname));\n\n    % reset initialization flag\n\n    iephem = 0;\n\nend\n\n% set name of target body\n\nswitch ntarg\n\n    case (1)\n\n        targ = 'mercury';\n\n    case (2)\n\n        targ = 'venus';\n\n    case (3)\n\n        targ = 'earth';\n\n    case (4)\n\n        targ = 'mars';\n\n    case(5)\n\n        targ = 'jupiter';\n\n    case (6)\n\n        targ = 'saturn';\n\n    case (7)\n\n        targ = 'neptune';\n\n    case (8)\n\n        targ = 'uranus';\n\n    case (9)\n\n        targ = 'pluto';\n\n    case (10)\n\n        targ = 'moon';\n\n    case (11)\n\n        targ = 'sun';\n\nend\n\n% set name of central body\n\nswitch ncent\n\n    case (1)\n\n        obs = 'mercury';\n\n    case (2)\n\n        obs = 'venus';\n\n    case (3)\n\n        obs = 'earth';\n\n    case (4)\n\n        obs = 'mars';\n\n    case (5)\n\n        obs = 'jupiter';\n\n    case (6)\n\n        obs = 'saturn';\n\n    case (7)\n\n        obs = 'neptune';\n\n    case (8)\n\n        obs = 'uranus';\n\n    case (9)\n\n        obs = 'pluto';\n\n    case (10)\n\n        obs = 'moon';\n\n    case (11)\n\n        obs = 'sun';\n\nend\n\n% compute time, expressed as TDB seconds past J2000 TDB (2451545.0)\n\netime = 86400.0d0 * (et - 2451545.0d0);\n\n% compute position and velocity vectors in eme2000 system (no corrections)\n\nstarg = mice_spkezr(targ, etime, 'J2000', 'NONE', obs);\n\n% provide output in user-requested units\n\nif (km == 1)\n\n    % state is kilometers and kilometers/second\n\n    rrd = starg.state;\n\nelse\n\n    % state is au's and au's/day\n\n    rrd(1:3) = starg.state(1:3) / au;\n\n    rrd(4:6) = 86400.0 * starg.state(4:6) / au;\n\n    rrd = rrd';\n\nend\n\n\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/sun_moon/jpl_ephem/jpleph_mice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.585330141971095}}
{"text": "%\n% BEZIER\n%\n% ger en bezierkurza mellan p1 och p2, med styrpunkter b och c. n stycken\n% punkter, inkluderar p1, men inte p2.\n\nfunction r=bezier(p1,b,c,p2,n)\n\nt=(0:1/n:1-(1/n)/2)';\nr=(1-t).^3*p1+3*t.*(1-t).^2*b+3*t.^2.*(1-t)*c+t.^3*p2;\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/705-a-viking-ship/bezier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5853301407698382}}
{"text": "function [x, infos] = deep_bidirectional_nmf(X, rank_layers, in_options)\n% Deep Bidir-Semi-NMF.\n%\n% The problem of interest is defined as\n%\n%           min || X - Z_1 * Z_2 * ... * Z_n * H_n ||_F^2,\n%           where \n%           {H_n} >= 0.\n%\n% Given a matrix X, factor matrices {Z_1, Z_2, ..., Z_n, H_n} are calculated.\n%\n%\n% Inputs:\n%       X           : (m x n) matrix to factorize\n%       rank_layers : ranks in each layer\n%       in_options \n%\n%\n% Output:\n%       x           : non-negative matrix solution, i.e., x.Z (cell), x.H (cell)\n%       infos       : log information\n%           epoch   : iteration nuber\n%           cost    : objective function value\n%           optgap  : optimality gap\n%           time    : elapsed time\n%           grad_calc_count : number of sampled data elements (gradient calculations)\n%\n% References\n%           G. Trigeorgis, K. Bousmalis, S. Zafeiriou and B. Schuller,\n%           \"A deep semi-NMF model for learning hidden representations\",\n%           ICML2014, 2014.\n%\n%           G. Trigeorgis, K. Bousmalis, S. Zafeiriou and B. Schuller\n%           \"A deep matrix factorization method for learning attribute representations,\"\n%           IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol.39, no.3, pp.417-429, 2017\n%   \n%\n% This file is part of NMFLibrary\n%\n% Originally created by G.Trigeorgis.\n%\n% Change log: \n%\n%       Jul. 26, 2018 (Hiroyuki Kasai): Modified code structures.\n%\n%       Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n    % set dimensions and samples\n    [m, n] = size(X);\n\n    % set the number of rank_layers\n    num_of_layers = numel(rank_layers);\n\n    % set local options\n    local_options.bUpdateZ  = true;\n    local_options.bUpdateH  = true;\n    local_options.bUpdateLastH = true;\n    local_options.deepZ     = true;\n    local_options.deepH     = true;\n    local_options.updateH_alg = 'mu';  % 'mu' or 'apg'\n    local_options.eval_clustering_acc = 0;\n    local_options.classnum      = 0;    \n    \n    % check input options\n    if ~exist('in_options', 'var') || isempty(in_options)\n        in_options = struct();\n    end     \n    % merge options\n    options = mergeOptions(get_nmf_default_options(), local_options);   \n    options = mergeOptions(options, in_options); \n\n    % initialize\n    method_name = 'Deep-Bidir-SemiNMF';       \n    epoch = 0;    \n    grad_calc_count = 0;\n\n    if options.verbose > 0\n        fprintf('# %s: started ...\\n', method_name);           \n    end     \n    \n    if ~isempty(options.gnd) && options.classnum > 1\n        options.eval_clustering_acc = 1;\n    end    \n    \n    % initialize Z and H\n    Z = cell(1, num_of_layers);\n    H = cell(1, num_of_layers); \n    P = cell(1, num_of_layers);\n    Q = cell(1, num_of_layers);     \n    %A = cell(1, num_of_layers+1); \n    %B = cell(1, num_of_layers);\n    if ~isfield(options, 'x_init')\n        \n        if options.deepH        \n            for i_layer = 1:num_of_layers\n\n                if options.verbose > 1\n                    fprintf('### Initializing by %s for layer %d ... ', method_name, i_layer);\n                end\n\n                if i_layer == 1\n                    % For the first layer we go linear from X to Z*H, so we use id\n                    V = X;\n                else \n                    V = H{i_layer-1};\n                end\n\n                % For the later rank_layers we use nonlinearities as we go from\n                % g(H_{k-1}) to Z*H_k              \n                semi_nmf_options.max_iter  = options.max_epoch;\n                semi_nmf_options.bUpdateH  = options.bUpdateH;\n                semi_nmf_options.bUpdateZ  = options.bUpdateZ;\n                semi_nmf_options.verbose   = 0;\n\n                [semi_nmf_x, ~] = semi_mu_nmf(V, rank_layers(i_layer), semi_nmf_options);\n                Z{i_layer} = semi_nmf_x.W;\n                H{i_layer} = semi_nmf_x.H;\n\n                %fprintf('V: %5.5f, Zi: %5.5f, Hi: %5.5f\\n', norm(V), norm(Z{i_layer}), norm(H{i_layer}));              \n                if options.verbose > 1\n                    fprintf('done\\n');\n                end            \n            end\n        end\n        \n        \n        if options.deepZ \n            XT = X';\n            for i_layer = 1:num_of_layers\n\n                if options.verbose > 1\n                    fprintf('### Initializing by %s for layer %d ... ', method_name, i_layer);\n                end\n\n                if i_layer == 1\n                    % For the first layer we go linear from X to Z*H, so we use id\n                    V = XT;\n                else \n                    V = Q{i_layer-1};\n                end\n\n                % For the later rank_layers we use nonlinearities as we go from\n                % g(H_{k-1}) to Z*H_k              \n                semi_nmf_options.max_iter  = options.max_epoch;\n                semi_nmf_options.bUpdateH  = options.bUpdateH;\n                semi_nmf_options.bUpdateZ  = options.bUpdateZ;\n                semi_nmf_options.verbose   = 0;\n\n                [semi_nmf_x, ~] = semi_mu_nmf(V, rank_layers(i_layer), semi_nmf_options);\n                P{i_layer} = semi_nmf_x.W;\n                Q{i_layer} = semi_nmf_x.H;\n\n                %fprintf('V: %5.5f, Zi: %5.5f, Hi: %5.5f\\n', norm(V), norm(Z{i_layer}), norm(H{i_layer}));              \n                if options.verbose > 1\n                    fprintf('done\\n');\n                end            \n            end\n        end        \n\n    else\n        Z = options.Z;\n        H = options.H;\n    end\n    \n    Hm = H{num_of_layers};\n    Qm = Q{num_of_layers};\n    \n    \n    % select disp_freq \n    disp_freq = set_disp_frequency(options);      \n    \n   \n    % store initial info\n    clear infos;\n    Z_rec = reconst_Z(Z, num_of_layers);  \n    \n  \n   % Concatinated_H = B{1};\n    %Concatinated_Q = Z{1}';\n    \n    \n    if options.deepH\n        B{num_of_layers} = Hm;\n        for i_layer = num_of_layers-1:-1:1\n            B{i_layer} = Z{i_layer+1} * B{i_layer+1};\n        end\n        H_rec = B{1};\n        Z_rec = Z{1}; \n        Concatinated_Q = Z{1}';\n    elseif options.deepZ\n        B{num_of_layers} = Qm;\n        for i_layer = num_of_layers-1:-1:1\n            B{i_layer} = P{i_layer+1} * B{i_layer+1};\n        end\n        H_rec = P{1}';\n        Z_rec = B{1}';\n    elseif options.deepH && options.deepZ\n        \n    end\n\n    \n    %[infos, f_val, optgap] = store_nmf_info(X, Z_rec, Hm, [], options, [], epoch, grad_calc_count, 0);\n    [infos, f_val, optgap] = store_nmf_info(X, Z_rec, H_rec, [], options, [], epoch, grad_calc_count, 0);\n    \n    % evaluate clustering accuracy\n    if ~isempty(options.gnd) && options.classnum > 1\n        [infos] = store_clustering_accuracy(Hm, options.gnd, options.classnum, infos, options.eval_clustering_num, 0);\n    end     \n\n    if options.verbose > 1\n        fprintf('%s: Epoch = 0000, cost = %.16e, optgap = %.4e\\n', method_name, f_val, optgap); \n    end  \n\n    % set start time\n    start_time = tic();   \n    \n\n    % main loop\n    while true\n        \n        % check stop condition\n        [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n        if stop_flag\n            display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n            break;\n        end\n        \n        % update Z and deep H\n        if options.deepH\n            Z{1} = Concatinated_Q';\n            [Z, Hm, Concatinated_H] = calc_deep_matrices(X, Z, Hm, num_of_layers, options, 1);\n        else\n            Concatinated_H = P{1}';\n        end\n        \n        \n%         [infos, f_val, optgap] = store_nmf_info(X, Z{1}, Concatinated_H, [], options, infos, epoch, grad_calc_count, 0);          \n%         % display infos\n%         if options.verbose > 1\n%             if ~mod(epoch, disp_freq)\n%                 fprintf('Deep-SemiNMF (B): Epoch = %04d, cost = %.16e, optgap = %.4e\\n', epoch, f_val, optgap);\n%             end\n%         end          \n%         \n        if options.deepZ\n            % update H and deep Z\n            P{1} = Concatinated_H';\n            [P, Qm, Concatinated_Q] = calc_deep_matrices(XT, P, Qm, num_of_layers, options, 0);\n        else\n            Concatinated_Q = Z{1}';\n        end\n        \n        %fprintf('%e\\n', norm(XT-P{1}*Concatinated_Q, 'fro')^2 / 2 );\n        \n   \n       \n        \n\n        % measure elapsed time\n        elapsed_time = toc(start_time);        \n        \n        % measure gradient calc count\n        grad_calc_count = grad_calc_count + m*n;\n\n        % update epoch\n        epoch = epoch + 1;         \n        \n        % store info\n        %Z_rec = reconst_Z(Z, num_of_layers);\n        %[infos, f_val, optgap] = store_nmf_info(X, Z_rec, Hm, [], options, infos, epoch, grad_calc_count, elapsed_time);  \n        [infos, f_val, optgap] = store_nmf_info(X, Concatinated_Q', P{1}', [], options, infos, epoch, grad_calc_count, elapsed_time);          \n        \n        \n%         % display infos\n%         if options.verbose > 1\n%             if ~mod(epoch, disp_freq)\n%                 fprintf('Deep-SemiNMF: Epoch = %04d, cost = %.16e, optgap = %.4e\\n', epoch, f_val, optgap);\n%             end\n%         end        \n\n        % evaluate clustering accuracy\n        if options.eval_clustering_acc\n            [infos] = store_clustering_accuracy(Hm, options.gnd, options.classnum, infos, options.eval_clustering_num, epoch);\n        end\n        \n        % display infos\n        if options.verbose > 1\n            if ~mod(epoch, disp_freq)\n\n                if ~options.eval_clustering_acc\n                    fprintf('%s: Epoch = %04d, cost = %.16e, optgap = %.4e\\n', method_name, epoch, f_val, optgap);\n                else\n                    fprintf('%s: Epoch = %04d, cost = %.16e, optgap = %.4e, acc = %.4f, nmi = %.4f, purity = %.4f, f = %.4f\\n', ...\n                        method_name, epoch, f_val, optgap, infos.clustering_acc(end).acc, infos.clustering_acc(end).nmi, infos.clustering_acc(end).purity, infos.clustering_acc(end).f_val);\n                end\n\n            end\n\n            \n        elseif options.verbose == 1\n            textwaitbar(epoch, options.max_epoch, '  progress');\n        end   \n\n    end\n    \n    H{num_of_layers} = Hm;    \n    x.Z = Z;\n    x.H = H;\n    \nend\n\n\nfunction [Z, Hm, Concatinated_H] = calc_deep_matrices(X, Z, Hm, num_of_layers, options, Hm_nonnegative)\n\n    A = cell(1, num_of_layers+1); \n    B = cell(1, num_of_layers);\n    \n    m = size(Z, 1);\n    \n    % B{1} = Z{2} * Z{3} * ... * Z{num_of_layers} * Hm\n    % B{2} = Z{3} * ... * Z{num_of_layers} * Hm\n    % B{3} = ....\n    % ....\n    % B{num_of_layers} = Hm\n    B{num_of_layers} = Hm;\n    for i_layer = num_of_layers-1:-1:1\n        B{i_layer} = Z{i_layer+1} * B{i_layer+1};\n    end\n\n    %% update Z\n    % where Z = Z{1} = X * (B{1})^{-1} due to Z{1} B{1} = X.\n    Z{1} = X  * pinv(B{1});    \n\n    A{1} = eye(m);\n    % update Z{2}, ... , Z{num_of_layers} \n    for i = 2 : num_of_layers\n\n        % A{1} = \n        % A{2} = Z{1}\n        % A{3} = Z{1} * Z{2}\n        % A{4} = Z{1} * Z{2} * Z{3}\n        % ....\n        % A{num_of_layers} = Z{1} * Z{2} * ... * Z{num_of_layers-1}\n        if i == 2\n            A{i} = Z{i-1};\n        else\n            A{i} = A{i-1} * Z{i-1};\n        end\n\n        Z{i} = pinv(A{i}) * X * pinv(B{i});\n\n    end\n\n    % update Hm\n    A{num_of_layers+1} = A{num_of_layers} * Z{num_of_layers};\n    if Hm_nonnegative\n        if strcmp(options.updateH_alg, 'mu')\n            P = A{num_of_layers+1}' * X;\n            Pp = (abs(P)+P)./2;\n            Pn = (abs(P)-P)./2;\n\n            Q = A{num_of_layers+1}' * A{num_of_layers+1};\n\n            Qp = (abs(Q)+Q)./2;\n            Qn = (abs(Q)-Q)./2;\n\n            Hm = Hm .* sqrt((Pp + Qn * Hm) ./ max(Pn + Qp * Hm, 1e-16));        \n        else\n            % min_H 1/2 | X - A{num_of_layers+1}*H |^2_F \n            % --> min_H 1/2 | X' - H' * A{num_of_layers+1}' |^2_F \n            % ----> min_A 1/2 | X - A * B' |^2_F in \"nesterov_mnls(X, B, A,..)\"\n            [tmpH, ~, ~] = nesterov_mnls(X', A{num_of_layers+1}, Hm', 1, options.apg_maxiter, 'basic');\n            Hm = tmpH';\n        end \n    else\n        Hm = pinv(A{num_of_layers+1}) * X;\n    end\n    \n    %\n    B{num_of_layers} = Hm;\n    for i_layer = num_of_layers-1:-1:1\n        B{i_layer} = Z{i_layer+1} * B{i_layer+1};\n    end    \n    Concatinated_H = B{1};\n    \n%     % B{1} = Z{2} * Z{3} * ... * Z{num_of_layers} * H{num_of_layers}\n%     % B{2} = Z{3} * ... * Z{num_of_layers} * H{num_of_layers}\n%     % B{3} = ....\n%     % ....\n%     % B{num_of_layers} = H{num_of_layers}\n%     B{num_of_layers} = H{num_of_layers};\n%     for i_layer = num_of_layers-1:-1:1\n%         B{i_layer} = Z{i_layer+1} * B{i_layer+1};\n%     end\n% \n%     %% update Z\n%     % where Z = Z{1} = X * (B{1})^{-1} due to Z{1} B{1} = X.\n%     Z{1} = X  * pinv(B{1});    \n% \n%     A{1} = eye(m);\n%     % update Z{2}, ... , Z{num_of_layers} \n%     for i = 2 : num_of_layers\n% \n%         % A{1} = \n%         % A{2} = Z{1}\n%         % A{3} = Z{1} * Z{2}\n%         % A{4} = Z{1} * Z{2} * Z{3}\n%         % ....\n%         % A{num_of_layers} = Z{1} * Z{2} * ... * Z{num_of_layers-1}\n%         if i == 2\n%             A{i} = Z{i-1};\n%         else\n%             A{i} = A{i-1} * Z{i-1};\n%         end\n% \n%         Z{i} = pinv(A{i}) * X * pinv(B{i});\n% \n%     end\n% \n%     % update H\n%     A{num_of_layers+1} = A{num_of_layers} * Z{num_of_layers};\n%     if strcmp(options.updateH_alg, 'mu')\n%         P = A{num_of_layers+1}' * X;\n%         Pp = (abs(P)+P)./2;\n%         Pn = (abs(P)-P)./2;\n% \n%         Q = A{num_of_layers+1}' * A{num_of_layers+1};\n% \n%         Qp = (abs(Q)+Q)./2;\n%         Qn = (abs(Q)-Q)./2;\n% \n% \n%         H{num_of_layers} = H{num_of_layers} .* sqrt((Pp + Qn * H{num_of_layers}) ./ max(Pn + Qp * H{num_of_layers}, 1e-10));        \n%     else\n%         % min_H 1/2 | X - A{num_of_layers+1}*H |^2_F \n%         % --> min_H 1/2 | X' - H' * A{num_of_layers+1}' |^2_F \n%         % ----> min_A 1/2 | X - A * B' |^2_F in \"nesterov_mnls(X, B, A,..)\"\n%         [tmpH, ~, ~] = nesterov_mnls(X', A{num_of_layers+1}, H{num_of_layers}', 1, 100, 'basic');\n%         H{num_of_layers} = tmpH';\n%     end\n\n\nend\n\n\n% calculate Z = Z_1 * Z_2 * ... * Z_n\nfunction Z_rec = reconst_Z(Z, num_of_layers)\n\n    Z_rec = Z{num_of_layers};\n    \n    for k = num_of_layers-1 : -1 : 1\n        Z_rec =  Z{k} * Z_rec;\n    end\n\nend\n", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/solver/deep/deep_bidirectional_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5853301350539277}}
{"text": "function logPr = calcJointLogPr_BPHMMState( Psi, data )\n%  OUTPUT\n%     logPr : struct with fields\n%                .F     : log p( F | hypers)\n%                .obs   : log p( obs_ii | F_ii, z_ii )  sum over all ii\n%                .z     : log p( z_ii | F_ii, hypers )  sum over all ii\n%                .all   : log p( obs, F, z | hypers )\n\nF = Psi.F > 0;\ngamma = Psi.bpM.gamma;\nc     = Psi.bpM.c;\nTransM = Psi.TransM;\nThetaM = Psi.ThetaM;\nstateSeq = Psi.stateSeq;\n\n% -----------------------------   Compute prob. of binary feature mat F\nlogPr.F = calcLogPrFeatureMatrix( F, gamma, c );\n\nlogPr.z = TransM.calcMargPrStateSeq( F, stateSeq );\n\n% Remember, no arguments means use stored suff stats\nif ~exist( 'data', 'var' ) \n    logPr.obs = ThetaM.calcMargPrData( ); \nelse\n    logPr.obs = ThetaM.calcMargPrData( data, stateSeq );\nend\n\n% ============== combine all logPr into joint prob of chain state\nlogPrFields = fieldnames( logPr );\nlogPr.all = 0;\nfor ff = 1:length( logPrFields )\n    logPr.all = logPr.all + logPr.( logPrFields{ff} );\nend\n", "meta": {"author": "michaelchughes", "repo": "NPBayesHMM", "sha": "22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd", "save_path": "github-repos/MATLAB/michaelchughes-NPBayesHMM", "path": "github-repos/MATLAB/michaelchughes-NPBayesHMM/NPBayesHMM-22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd/code/BPHMM/BPutil/calcJointLogPr_BPHMMState.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5851743335764796}}
{"text": "function Population = EnvironmentalSelection(Population,V,theta)\n% The environmental selection of RVEA*\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    %% Select only the non-dominated solutions\n    Population = Population(NDSort(Population.objs,1)==1);\n    PopObj = Population.objs;\n    [N,M]  = size(PopObj);\n    NV     = size(V,1);\n    \n    %% Translate the population\n    PopObj = PopObj - repmat(min(PopObj,[],1),N,1);\n    \n    %% Calculate the degree of violation of each solution\n    CV = sum(max(0,Population.cons),2);\n    \n    %% Calculate the smallest angle value between each vector and others\n    cosine = 1 - pdist2(V,V,'cosine');\n    cosine(logical(eye(length(cosine)))) = 0;\n    gamma  = min(acos(cosine),[],2);\n\n    %% Associate each solution to a reference vector\n    Angle = acos(1-pdist2(PopObj,V,'cosine'));\n    [~,associate] = min(Angle,[],2);\n\n    %% Select one solution for each reference vector\n    Next = zeros(1,NV);\n    for i = unique(associate)'\n        current1 = find(associate==i & CV==0);\n        current2 = find(associate==i & CV~=0);\n        if ~isempty(current1)\n            % Calculate the APD value of each solution\n            APD = (1+M*theta*Angle(current1,i)/gamma(i)).*sqrt(sum(PopObj(current1,:).^2,2));\n            % Select the one with the minimum APD value\n            [~,best] = min(APD);\n            Next(i)  = current1(best);\n        elseif ~isempty(current2)\n            % Select the one with the minimum CV value\n            [~,best] = min(CV(current2));\n            Next(i)  = current2(best);\n        end\n    end\n    % Population for next generation\n    Population = Population(Next(Next~=0));\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/RVEAa/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.58517432955943}}
{"text": "function Kss=cp_SSgain(A,Q,H,R,P, mtd)\nnum_st=size(A,1);\n    \nif (mtd==0)     %method to use when dare fails to reach a solution\n    % [Beq, yy]=chol(Q,'lower');\n    Beq=Q^0.5;\n   \n    %basis for observable space\n    Ob=obsv(A,H);\n    [u,s,v]=svd(Ob'*Ob);\n    num_null_obs=length(find(diag(s)<1e-6));\n    num_range_obs=num_st-num_null_obs;\n    base_null_obs=v(:,(num_range_obs+1):num_st);\n    base_range_obs=u(:,1:num_range_obs);\n    Wo=[base_null_obs base_range_obs];   %x=Wz\n    \n    %basis for controllable and uncontrollable spaces\n    Co=ctrb(A,Beq);\n    [u,s,v]=svd(Co*Co');\n    num_null_ctr=length(find(diag(s)<1e-12));\n    num_range_ctr=size(A,1)-num_null_ctr;\n    base_null_ctr=v(:,(num_range_ctr+1):size(A,1));\n    base_range_ctr=u(:,1:num_range_ctr);\n    Wc=[base_null_ctr base_range_ctr];   %x=Wz\n    \n    %%%compute the intersection of observable space with cont/uncont spaces\n    %obs+ctr space (min real)\n    if (num_null_ctr>0)\n        mx_a=[base_range_obs base_range_ctr];\n        [mx_b,pvt] = rref(mx_a);\n        ind=setdiff(1:(num_range_obs+num_range_ctr),pvt);\n        if (~isempty(ind))\n            Woc=base_range_obs*mx_b(1:num_range_obs,ind);\n            Woc*diag(diag(Woc'*Woc).^-0.5); %normalize\n            num_base_oc=size(Woc,2);\n        else\n            Woc=[];\n            num_base_oc=0;\n        end\n        %obs+unctr space\n        mx_a=[base_range_obs base_null_ctr];\n        [mx_b,pvt] = rref(mx_a);\n        ind=setdiff(1:(num_range_obs+num_null_ctr),pvt);\n        if (~isempty(ind))\n            Wou=base_range_obs*mx_b(1:num_range_obs,ind);\n            Wou=diag(diag(Wou'*Wou).^-0.5); %normalize\n            num_base_ou=size(Wou,2);\n        else\n            Wou=[];\n            num_base_ou=0;\n        end\n        \n        %%%overall transformation matrix\n        W=[base_null_obs Wou Woc];\n    else    %no uncontrollable subspace\n        W=[base_null_obs base_range_obs];\n        num_base_ou=0;\n        num_base_oc=base_range_obs;\n    end\n    \n    %transform the system\n    W_inv=inv(W);\n    A_t=W_inv*A*W;\n    Beq_t=W_inv*Beq;\n    Qeq_t=Beq_t*Beq_t';\n    H_t=H*W;\n    \n    %partitions\n    in1=num_null_obs;\n    in2=num_null_obs+num_base_ou;\n    in3=num_null_obs+num_base_ou+num_base_oc;\n    \n    Au=A_t(1:in1,1:in1);   %unobservable part\n    Au_cross=A_t(1:in1,in1+1:end);   %cross effects of observable part on unobservable part\n    Aou=A_t(in1+1:in2,in1+1:in2);   %observable but unctrollable part\n    Aoc=A_t(in2+1:end,in2+1:end);   %observable and controllable\n    Aoc_cross=A_t(in2+1:end,in1+1:in2); %cross effects of ou part on oc part (not used)\n    Ao=A_t(in1+1:end,in1+1:end);   %observable part\n    \n    Qu=Qeq_t(1:in1,1:in1);\n    Qu_cross=Qeq_t(1:in1,in1+1:end);    %cross disturbance between o and uno parts\n    Qoc=Qeq_t(in2+1:end,in2+1:end);\n    Qo=Qeq_t(in1+1:end,in1+1:end);\n    \n    Hou=H_t(:,in1+1:in2);\n    Hoc=H_t(:,in2+1:end);\n    Ho=H_t(:,in1+1:end);    %observable\n    \n    %steady state solution for ubsorvable and controllable parts (including\n    %uncont. parts except the unit circle)\n    [Poc,clp,Koc]=dare(Aoc',Hoc', Qoc, R);\n    Koc=Poc*Hoc'*inv(Hoc*Poc*Hoc'+R);\n    \n    %Add SS gain values for the unit circle uncontrollable parts but observable\n    %parts\n    Ko=[zeros(num_base_ou,size(Koc,2));Koc];\n    Po=diag_mat(Poc,1,zeros(num_base_ou));\n    \n    % %%Steady state solution for observable part\n    % [Po,clp,Ko]=dare(A3',H2', Q3, R);\n    % Ko=Po*H2'*inv(H2*Po*H2'+R);\n    \n    %%%%Compute the cross gain\n    mx_a=Au;\n    mx_b=(eye(num_range_obs)-Ho'*inv(Ho*Po*Ho'+R)*Ho*Po)*Ao';\n    mx_c=Au_cross*(Po-Ko*Ho*Po)'*Ao'+Qu_cross;\n    %%check the multiplication of eigenvalues\n    if (isempty(mx_a)) %no unobservable space\n        eig_mul=0;\n    else\n        lef=eig(mx_a);\n        rig=eig(mx_b);\n        eig_mul=lef*rig';\n    end\n    \n    if (isempty(find(eig_mul==1,1,'first')))\n        Pu_cross = dlyap(mx_a,mx_b,mx_c);\n        Ku_cross=Pu_cross*Ho'*inv(Ho*Po*Ho'+R);\n        %%overall gain\n        Kss=W*[Ku_cross;Ko];\n    else %in this case stein equation has no unique solution (solution depends initial P value)\n        %Perform standard KF iteration to find a K\n        disp('comp_ss_gain: NO SS!!');\n        K_pre=zeros(num_st,size(H,1));\n        K=P*H'*inv(H*P*H'+R);\n        while (max(abs(K(:)-K_pre(:))>1e-7))\n            K_pre=K;\n            P=(eye(size(A))-K*H)*P;\n            P=A*P*A'+Beq*Beq';\n            K=P*H'*inv(H*P*H'+R);\n        end\n        Kss=K;\n    end\nelseif (mtd==1) %iterations\n    K_pre=zeros(num_st,size(H,1));\n    K=P*H'*inv(H*P*H'+R);\n    in=0;\n    while (max(abs(K(:)-K_pre(:))>1e-7))\n        K_pre=K;\n        P=(eye(size(A))-K*H)*P;\n        P=A*P*A'+Q;\n        K=P*H'*inv(H*P*H'+R);\n        in=in+1;\n    end\n    disp(['cpSSgain 145: SS iteration =' num2str(in)]);\n    Kss=K;\nend", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/Common/cp_SSgain_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5851658298045188}}
{"text": "%JSINGU Show the linearly dependent joints in a Jacobian matrix\n%\n% JSINGU(J) displays the linear dependency of joints in a Jacobian matrix.\n% This dependency indicates joint axes that are aligned and causes singularity.\n%\n% See also SerialLink.jacobn.\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\nfunction jsingu(J)\n\n    % convert to row-echelon form\n    [R, jb] = rref(J);\n    R(abs(R) < 100*eps) = 0;\n\n    depcols = setdiff( 1:numcols(J), jb);\n\n    fprintf('%d linearly dependent joints:\\n', length(depcols));\n    for d=depcols\n        fprintf('  q%d depends on: ', d)\n        for k=find(R(:,d))\n            fprintf('q%d ', k);\n        end\n        fprintf('\\n');\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/jsingu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5851384052003952}}
{"text": "function gdout=filterbankdual(g,a,varargin)\n%FILTERBANKDUAL  Dual filters\n%   Usage:  gd=filterbankdual(g,a,L);\n%           gd=filterbankdual(g,a);\n%           \n%\n%   `filterbankdual(g,a,L)` computes the canonical dual filters of *g* for a\n%   channel subsampling rate of *a* (hop-size) and system length *L*.\n%   *L* must be compatible with subsampling rate *a* as \n%   `L==filterbanklength(L,a)`. This will create a dual frame valid for \n%   signals of length *L*. \n%\n%   `filterabankrealdual(g,a)` does the same, but the filters must be FIR\n%   filters, as the transform length is unspecified. *L* will be set to \n%   next suitable length equal or bigger than the longest impulse response\n%   such that `L=filterbanklength(gl_longest,a)`.\n%\n%   The input and output format of the filters *g* are described in the\n%   help of |filterbank|.\n%\n%   In addition, the funtion recognizes a 'forcepainless' flag which\n%   forces treating the filterbank *g* and *a* as a painless case\n%   filterbank.  \n%\n%   To actually invert the output of a filterbank, use the dual filters\n%   together with the |ifilterbank| function.\n%\n%   REMARK: In general, perfect reconstruction can be obtained for signals \n%   of length *L*. In some cases, using dual system calculated for shorter\n%   *L* might work but check the reconstruction error.\n%\n%   See also: filterbank, ufilterbank, ifilterbank\n\ncomplainif_notenoughargs(nargin,2,'FILTERBANKDUAL');\n\ndefinput.import={'filterbankdual'};\ndefinput.flags.outformat = {'fir','full','econ','asfreqfilter'};\ndefinput.keyvals.efsuppthr = 10^(-5);\n\n[flags,kv,L]=ltfatarghelper({'L'},definput,varargin);\n\n[g,asan,info]=filterbankwin(g,a,L,'normal');\nif isempty(L) \n    if info.isfir\n        % Pick shortest possible length for FIR filterbank\n        L = filterbanklength(info.longestfilter,asan);\n    else\n        % Just thow an error, nothing reasonable can be done without L\n        error(['%s: L must be specified when not working with FIR ',...'\n               'filterbanks.'], upper(mfilename));\n    end\nend\nM=info.M;\n\n% Force usage of the painless algorithm \nif flags.do_forcepainless\n    info.ispainless = 1;\nend\n\n% Check user defined L\nif L~=filterbanklength(L,a)\n     error(['%s: Specified length L is incompatible with the length of ' ...\n            'the time shifts.'],upper(mfilename));\nend;\n\n% Prioritize painless over uniform algorithm if both are suitable\nif info.isuniform && info.ispainless\n    info.isuniform = 0;\nend\n\n% Factorization of frame operator to block-diagonal matrix\nif info.isuniform\n  % Uniform filterbank, use polyphase representation\n  a=a(1);\n  \n  % Transfer functions of individual filters as cols\n  G = filterbankfreqz(g,a,L);\n  \n  N=L/a;\n  \n  gd=zeros(M,N,class(G));\n  \n  for w=0:N-1\n    idx = mod(w-(0:a-1)*N,L)+1;\n    H = G(idx,:);\n    \n    H=pinv(H)';\n    \n    gd(:,idx)=H.';\n  end;\n  % gd was created transposed because the indexing gd(:,idx_a)\n  % is much faster than gd(idx_a,:)\n  gd =  gd.';\n  thisclass = class(G);\n\nswitch flags.outformat\n    case 'fir'\n        gd=ifft(gd)*a;\n        % Matrix cols to cell elements + cast\n        gdout = cellfun(@(gdEl) cast(gdEl,thisclass), num2cell(gd,1),...\n                  'UniformOutput',0);\n\n  %      All filters in gdout will be treated as FIR of length L. Convert them\n  %      to a struct with .h and .offset format.\n        gdout = filterbankwin(gdout,a);      \n    case 'full'\n\n        gdout = gd*a;\n    case 'econ'\n        Shorten filters to essential support\n        gd = gd*a;\n        gdout=economize_filters(gd,'efsuppthr',kv.efsuppthr);\n\n    case 'asfreqfilter'\n        gd = gd*a;\n%        All filters in gdout will be treated as (numeric) freqfilter format. \n%        Manually convert them to a struct with .H and .foff.\n        template = struct('H',[],'foff',0,'realonly',0,'delay',0,'L',L);\n        gdout = cell(1,M);\n        gdout(:) = {template};\n\n        [H,foff,~]=economize_filters(gd,'efsuppthr',kv.efsuppthr);\n        for kk = 1:M\n            gdout{kk} = setfield(gdout{kk},'H',H{kk});\n            gdout{kk} = setfield(gdout{kk},'foff',foff(kk));\n        end      \n    otherwise\n        error('%s: Unknown filter format.', upper(mfilename)); \nend \n\nelseif info.ispainless\n   % Factorized frame operator is diagonal.\n   gdout = comp_painlessfilterbank(g,asan,L,'dual',0);\nelse\n        error(['%s: The canonical dual frame of this system is not a ' ...\n               'filterbank. You must either call an iterative ' ...\n               'method to perform the desired inverstion or transform ',...\n               'or transform the filterbank to uniform one. Please see ' ...\n               'FRANAITER or FRSYNITER for the former and ',...\n               'NONU2UFILTERBANK for the latter case.'],upper(mfilename));        \n\n    \nend;\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/filterbank/filterbankdual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.585138400371268}}
{"text": "function clrIX = MapXto1Dcolormap(X,Xrange,numC)\n% note: Xrange only saturates high and low values, does not remove data\n% points in X. \n\nif nargin < 2\n    Xrange = [min(X),max(X)];    \nend\nif nargin < 3\n    numC = 64;\nend\n\nX(X<Xrange(1)) = Xrange(1);\nX(X>Xrange(2)) = Xrange(2);\n\nclrIX = round((X-Xrange(1))/(Xrange(2)-Xrange(1))*(numC-1))+1;\nif size(clrIX,1)<size(clrIX,2)\n    clrIX = clrIX';\nend\nend", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/script functions/MapXto1Dcolormap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5850526118367501}}
{"text": "function h = gaussianNoise3dPlot(noise, plotType, CX, CY, CZ, CZVar, varargin)\n\n% GAUSSIANNOISE3DPLOT Draws a 3D or contour plot for the GAUSSIAN noise model.\n% FORMAT\n% DESC draws a 3D or contour plot for the Gaussian noise model.\n% ARG noise : the noise structure for which the plot is required.\n% ARG plotType : string containing the name of the plotting function (for example mesh, contour).\n% ARG X : the input X data in the form of a 'mesh' matrix.\n% ARG Y : the input Y data in the form of a 'mesh' matrix.\n% ARG mu : the input mean in the form of a 'mesh' matrix.\n% ARG varSigma : the input variance in the form of a 'mesh' matrix. \n% ARG P1, P2, P3 ... : optional additional arguments for the given plot type.\n% RETURN h : the gradients of the diagonal with respect to each element\n% of X. The returned matrix has the same dimensions as X.\n%\n% SEEALSO : gaussianNoiseParamInit, noise3dPlot, \n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005\n\n% NOISE\n\n\nCZ = (CZ+noise.bias);\nfhandle = str2func(plotType);\nh = fhandle(CX, CY, CZ, varargin{:});\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/noise/gaussianNoise3dPlot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5850526050362197}}
{"text": "function [ y ] = ill_si( t, x, lambda)\n%ILL_SIR Summary of this function goes here\n%   \u8f93\u5165\u53c2\u6570 x \u5305\u542b\u4e00\u4e2a\u5206\u91cf\uff0c\u4e3a\uff1aInfective \u7684\u6bd4\u4f8b\n% lambda   \u65e5\u63a5\u89e6\u7387\n\ny = [lambda * x(1) * (1 - x(1))]';\n\nend\n\n", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/NovelCoronaVirus/ill_si.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5850525939410886}}
{"text": "function h = PlotSpectrogram (x, varargin)\n% Plot a gray-level spectrogram. The spectrogram is plotted as an image\n% with the intensities encoding the levels. The spectrogram has time on the\n% abscissa and frequency on the ordinate axis. The spectrogram consists of\n% vertical slices displaying the spectral response as intensities in dB.\n% The slices are calculated as the DFT of windowed samples. The time window\n% for each slice is centred at the corresponding abscissa point. The length\n% of the time window determines the time-frequency resolution trade-off.\n% The default window length (190 samples) gives relatively good frequency\n% resolution.\n%\n% The intensity values in the plot is calibrated in terms of the decibel\n% value relative to a full scale (dBov, see ITU-T G.100.1). A full scale\n% sine wave with frequency at one of the DFT values appears  at -6 dBov.\n% The default mapping makes the maximum value appear as the darkest value\n% and -80 dB below that correspond to the lightest value.\n%\n%   h = PlotSpectrogram (x, [ts, tf], Fs, Options)\n% Simplified forms\n%   h = PlotSpectrogram (x, Fs)\n%   h = PlotSPectrogram (x)\n% Options can appear as the last arguments in any of these forms. Options\n% take the form of pairs of arguments, the first being a keyword, the\n% second being a value.\n%\n% h    - handle to the image\n% x    - data vector. The data is considered to be extended with zeros at\n%        each end in case the windows extend into those regions.\n% [ts, tf] - Specifies the start and stop times. The first spectrogram\n%        slice is centred at ts and the last spectrogram slice is centred\n%        at tf. The default is to create slices spanning the entire data\n%        vector, i.e., ts=0, tf=(N-1)/Fs, where N is the number of samples\n%        in the data vector.\n% Fs   - sampling frequency, default 1.\n%\n% Options\n%  Data window\n%    The data window used for each spectrum slice can be specified with\n%    the keywords 'Win', 'Lwin' or 'BW'.\n%  'Win': the data window vector is explicitly specified.\n%  'LWin': the length of the data window (in samples) is specified.\n%    A Hamming window of that length is used.\n%  'BW': the 3 dB bandwidth (in Hz) of the Hamming window to be used\n%    is specified. The length of the Hamming window is chosen using the\n%    formula, LWin = 1.18523 * Fs / BW. The default bandwidth is Fs/160.\n%    The bandwidth can also be specified with the character strings\n%    'NB' (narrowband spectrogram - good frequency resolution, but poor\n%    time resolution, same as Fs/160), or 'WB' (wideband spectrogram - poor\n%    frequency resolution, but good time resolution, same as 6/160 Fs).\n% 'NSlice'\n%   The number of spectrogram slices, default 500.\n% 'Nfft'\n%   The number of rows in the spectrogram is determined by the DFT size,\n%   Nfft. The Nfft/2+1 rows correspond to frequencies from 0 to Fs/2. The\n%   frequency resolution of the DFT is Fs/Nfft. If not specified, Nfft is\n%   chosen to be 1024 or 2048, with the larger value chosen if the window\n%   length is greater than 0.9*1024 (0.9 is the Kell factor).\n% 'PLimdB'\n%   Minimum and maximum levels for the spectrogram on dB. The spectrogram\n%   levels are clipped outside of these values. The value for 'PLimdB' can\n%   be a two element vector giving the minimum and maximum values. The\n%   'PLimdB' value can also be a single value giving the dynamic range in\n%   dB. In that case, the maximum is determined automatically and the\n%   minimum is set according to the specified dynamic range. The default is\n%   to determine the maximum automatically and apply a dynamic range of 80\n%   dB.\n% 'Amax'\n%   The data is expected to take on values between -Amax to +Amax. The\n%   default is 1 is suitable for data acquired from sound files. This value\n%   affects the scaling of the intensities.\n% 'FLim'\n%   This parameter is of the form [Fs, Ff] specifying the frequency range\n%   of the spectrogram to be plotted. The spectrogram is always calculated\n%   over the whole frequency range. This parameter can be used to select\n%   a subrange of frequencies for plotting. The default is [0, Fs/2].\n% 'preF'\n%   The frequency response values can be pre-emphasized to better show\n%   lower amplitude high-frequency components. The pre-emphasis response is\n%   that of a first order difference filter with parameter preF. The\n%   default value of preF is 0. A suitable value for pre-emphasis might be\n%   0.97.\n%\n% Notes:\n% - To get a colour spectrogram with a colorbar legend:\n%       PlotSpectrogram(...);\n%       colormap(SpecColorMap);\n%       colorbar;\n% - To get an intensity scale in dB SPL (sound pressure level):\n%   - Assume that a full scale sine results in PmaxdBSPL (often chosen to\n%     be 92 dB SPL).\n%   - Then to convert dBov to dB SPL,\n%       PmaxdBSPL = 92;  % Max level in dB SPL\n%       Amax = 1;        % Assume normalized scaling from a sound file\n%       PoffsdB = PmaxdBSPL + 20*log10(2);\n%       g = 10^(PoffsdB/20);\n%       AmaxN = Amax/g;\n%       PlotSpectrogram(..., 'Amax', AmaxN);\n%   - This conversion brings the peak sine wave response in the display\n%     to be PmaxdBSPL.\n\n% $Id: PlotSpectrogram.m,v 1.10 2009/06/01 18:38:22 pkabal Exp $\n\n% Process arguments\n[TLim, Fs, Options] = DecodeArgs(varargin{:});\n\n% Process options\n[NSlice, Win, Nfft, FLim, PLimdB, Amax, preF] = ...\n                                            PSDecodeOptions(Options, Fs);\n% Fill in the default time limits\n% Set the times of the slices\nif (isempty(TLim))\n  TLim = [0 (length(x)-1)/Fs];\nend\nt = linspace(TLim(1), TLim(2), NSlice);\n\n% Get spectrum in dB\n[PdB, f] = SpecSlices(t, x, Fs, Win, Nfft);\n\n% Select a subset of frequencies\nI = find(f >= FLim(1) & f <= FLim(2));\nf = f(I);\nPdB = PdB(I,:);\n\n% Convert to dBov\nPdBov = SpecCalib(PdB, Amax, Win);\n\n% Pre-emphasis\npre = (1 + preF^2) - 2 * preF * cos(2 * pi * f / Fs);\npredB = 10 * log10(pre');\nfor (i = 1:NSlice)\n  PdBov(:,i) = PdBov(:,i) + predB;\nend\n\n% Automatic scaling\nif (length(PLimdB) == 1)\n  PmaxdB = max(max(PdBov));\n  PLimdB = [PmaxdB-PLimdB PmaxdB];\nend\n\n% Plot the image\nh = imagesc(t, f, PdBov, PLimdB);\naxis('xy');\n\n% Grayscale map (dark is more intense)\ncolormap(flipud(gray));\n\nxlabel('Time (s)');\nylabel('Frequency (Hz)');\n\nreturn\n\n% ===============================\nfunction PdBov = SpecCalib (PdB, Amax, Win)\n% Calibration of a spectrum, The input spectrum in dB is gain modified so\n% that a sine wave of maximum amplitude Amax gives a total energy level of\n% -3 dBov. This mean that each of the two peaks (one at -fc and the other\n% at +fc) will have a level of -6 dBov. A dc level of Amax will give a\n% 0 dBov level at zero frequency.\n% - Amax, maximum level of the sinusoid (typically 1 for scaled data from\n%   sound files). With the true maximum level, the scaling gives an\n%   output in dBov. However, Amax can be artificially changed to affect a\n%   change in scaling. For instance halving Amax, increases the levels by\n%   6 dB.\n\n% Calibration\n% - Input:\n%   - dc peak amplitude Amax gives 0 dBov\n%      - DFT gives sum(Win) at dc\n%   - sine peak amplitude Amax give -6dBov at fc and -fc\n%     - Assumes sine frequency is coincident with a DFT bin, i.e. fc is of\n%       the form m * Fs/Nfft\n%     - The peak amplitude of the DFT of the windowed response (assuming no\n%       overlap of the components due to the sine at -fc and +fc) is\n%       Apeak = abs (Amax / 2 * Wpeak)\nApeak = abs (Amax * sum(Win));\nGLdB = -20 * log10(Apeak); \n\nPdBov = PdB + GLdB;\n\nreturn\n\n% ===============================\nfunction [TLim, Fs, Options] = DecodeArgs(varargin)\n% Decode [ts, tf], Fs, Options\n% These are distinguished by being a 2 element vector, a scalar, and\n% a character string (marking the start of the options)\n\nOptions = [];\nFs = 1;\nTLim = [];\n\n% Find the first argument with a character string\n% Store it and the following arguments in Options\nNarg = length(varargin);\nfor (i = 1:Narg)\n  if (ischar(varargin{i}))\n    Options = varargin(i:end);\n    if (mod(length(Options), 2) ~= 0)\n      error('PlotSpectrogram: Invalid Options format');\n    end\n    varargin(i:end) = [];\n    break;\n  end\nend\n\n% Check for a TLim argument\nif (length(varargin) > 1 && length(varargin{1}) == 2)\n  TLim = varargin{1};\n  varargin(1) = [];\nend\n\n% Pick off Fs\nif (~ isempty(varargin) && length(varargin{1}) == 1)\n  Fs = varargin{1};\n  varargin(1) = [];\nend\n\nif (~ isempty(varargin))\n  error('PlotSpectrogram: Too many input arguments');\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/24321-plotspectrogram/Spectrogram/PlotSpectrogram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954683, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5850525917937883}}
{"text": "function [X,Zf] = moving_average(N,X,Zi,dim)\n% Like filter() for the special case of moving-average kernels.\n% [X,Zf] = moving_average(N,X,Zi,Dim)\n%\n% This is an overall very fast implementation whose running time does now grow with N (beyond\n% N=100). The algorithm does not run into numerical problems for large data sizes unlike the usual\n% cumsum-based implementations.\n%\n% In:\n%   N : filter length in samples\n%\n%   X : data matrix\n%\n%   Zi : initial filter conditions (default: [])\n%\n%   Dim : dimension along which to filter (default: first non-singleton dimension)\n%\n% Out:\n%   X : the filtered data\n%\n%   Zf : final filter conditions\n%\n% See also:\n%   filter\n%\n%                           Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n%                           2012-01-10\n\n% Copyright (C) Christian Kothe, SCCN, 2012, christian@sccn.ucsd.edu\n%\n% This program is free software; you can redistribute it and/or modify it under the terms of the GNU\n% General Public License as published by the Free Software Foundation; either version 2 of the\n% License, or (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\n% even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n% General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License along with this program; if not,\n% write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307\n% USA\n\n% determine the dimension along which to filter\nif nargin <= 3\n    if isscalar(X)\n        dim = 1;\n    else\n        dim = find(size(X)~=1,1); \n    end\nend\n\n% empty initial state\nif nargin <= 2\n    Zi = []; end\n\nlenx = size(X,dim);\nif lenx == 0\n    % empty X\n    Zf = Zi;\nelse\n    if N < 100\n        % small N: use filter\n        [X,Zf] = filter(ones(N,1)/N,1,X,Zi,dim);\n    else\n        % we try to avoid permuting dimensions below as this would increase the running time by ~3x\n        if ndims(X) == 2\n            if dim == 1\n                % --- process along 1st dimension ---\n                if isempty(Zi)\n                    % zero initial state\n                    Zi = zeros(N,size(X,2));\n                elseif size(Zi,1) == N-1\n                    % reverse engineer filter's initial state (assuming a moving average)\n                    tmp = diff(Zi(end:-1:1,:),1,1);\n                    Zi = [tmp(end:-1:1,:); Zi(end,:)]*N;\n                    Zi = [-sum(Zi,1); Zi];\n                elseif ~isequal(size(Zi),[N,size(X,2)])\n                    error('These initial conditions do not have the correct format.');\n                end\n                \n                % pre-pend initial state & get dimensions\n                Y = [Zi; X]; M = size(Y,1);\n                % get alternating index vector (for additions & subtractions)\n                I = [1:M-N; 1+N:M];\n                % get sign vector (also alternating, and includes the scaling)\n                S = [-ones(1,M-N); ones(1,M-N)]/N;\n                % run moving average\n                X = cumsum(bsxfun(@times,Y(I(:),:),S(:)),1);\n                % read out result\n                X = X(2:2:end,:);\n                \n                % construct final state\n                if nargout > 1\n                    Zf = [-(X(end,:)*N-Y(end-N+1,:)); Y(end-N+2:end,:)]; end\n            else\n                % --- process along 2nd dimension ---\n                if isempty(Zi)\n                    % zero initial state\n                    Zi = zeros(N,size(X,1));\n                elseif size(Zi,1) == N-1\n                    % reverse engineer filter's initial state (assuming a moving average)\n                    tmp = diff(Zi(end:-1:1,:),1,1);\n                    Zi = [tmp(end:-1:1,:); Zi(end,:)]*N;\n                    Zi = [-sum(Zi,1); Zi];\n                elseif ~isequal(size(Zi),[N,size(X,1)])\n                    error('These initial conditions do not have the correct format.');\n                end\n                \n                % pre-pend initial state & get dimensions\n                Y = [Zi' X]; M = size(Y,2);\n                % get alternating index vector (for additions & subtractions)\n                I = [1:M-N; 1+N:M];\n                % get sign vector (also alternating, and includes the scaling)\n                S = [-ones(1,M-N); ones(1,M-N)]/N;\n                % run moving average\n                X = cumsum(bsxfun(@times,Y(:,I(:)),S(:)'),2);\n                % read out result\n                X = X(:,2:2:end);\n                \n                % construct final state\n                if nargout > 1\n                    Zf = [-(X(:,end)*N-Y(:,end-N+1)) Y(:,end-N+2:end)]'; end\n            end\n        else\n            % --- ND array ---\n            [X,nshifts] = shiftdim(X,dim-1);\n            shape = size(X); X = reshape(X,size(X,1),[]);\n            \n            if isempty(Zi)\n                % zero initial state\n                Zi = zeros(N,size(X,2));\n            elseif size(Zi,1) == N-1\n                % reverse engineer filter's initial state (assuming a moving average)\n                tmp = diff(Zi(end:-1:1,:),1,1);\n                Zi = [tmp(end:-1:1,:); Zi(end,:)]*N;\n                Zi = [-sum(Zi,1); Zi];\n            elseif ~isequal(size(Zi),[N,size(X,2)])\n                error('These initial conditions do not have the correct format.');\n            end\n            \n            % pre-pend initial state & get dimensions\n            Y = [Zi; X]; M = size(Y,1);\n            % get alternating index vector (for additions & subtractions)\n            I = [1:M-N; 1+N:M];\n            % get sign vector (also alternating, and includes the scaling)\n            S = [-ones(1,M-N); ones(1,M-N)]/N;\n            % run moving average\n            X = cumsum(bsxfun(@times,Y(I(:),:),S(:)),1);\n            % read out result\n            X = X(2:2:end,:);\n            \n            % construct final state\n            if nargout > 1\n                Zf = [-(X(end,:)*N-Y(end-N+1,:)); Y(end-N+2:end,:)]; end\n            \n            X = reshape(X,shape);\n            X = shiftdim(X,ndims(X)-nshifts);\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/code/misc/moving_average.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.828938799869521, "lm_q2_score": 0.7057850216484839, "lm_q1q2_score": 0.5850525888111782}}
{"text": "function G = approxfcn(F,range)\n%APPROXFCN Approximation function.\n%   G = APPROXFCN(F,RANGE) returns a function handle, G, that\n%   approximates the function handle F by using a lookup table. RANGE is\n%   an M-by-2 matrix specifying the input range for each of the M inputs\n%   to 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\nnum_inputs = size(range,1);\nmax_table_elements = 10000;\nmax_table_dim = 100;\ntable_dim = min(floor(max_table_elements^(1/num_inputs)), ...\n   max_table_dim);\n\n% Compute the input grid values.\ninputs = cell(1,num_inputs);\ngrid = cell(1,num_inputs);\nfor k = 1:num_inputs\n   grid{k} = linspace(range(k,1),range(k,2),table_dim);\nend\n\nif num_inputs > 1\n   [inputs{:}] = ndgrid(grid{:});\nelse\n   inputs = grid;\nend\n\n% Initialize the lookup table.\ntable = zeros(size(inputs{1}));\n\n% Initialize the waitbar.\nbar = waitbar(0,'Working...');\n\n% Initialize the cell array used to pass inputs to F.\nZk = cell(1,num_inputs);\nL = numel(inputs{1});\n% Update the progress bar at 2% intervals.\nwaitbar_update_interval = ceil(0.02 * L);\n\nfor p = 1:L\n   for k = 1:num_inputs\n      Zk{k} = inputs{k}(p);\n   end\n   table(p) = F(Zk{:});\n   if (rem(p,waitbar_update_interval) == 0)\n      % Update the progress bar.\n      waitbar(p/L);\n   end\nend\nclose(bar)\n\nG = @tableLookupFcn;\n\n   %-------------------------------------------------------------------%\n   function out = tableLookupFcn(varargin)\n      if num_inputs > 1\n         out = interpn(grid{:},table,varargin{:});\n      else\n         out = interp1(grid{1},table,varargin{1});\n      end\n   end\n\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/fuzzyFunctions/approxfcn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.5850013884619653}}
{"text": "function [elem,HB] = uniformcoarsenquadred(elem)\n%% UNIFORMCOARSEQUADNRED uniform coarsening of red refinement\n%\n% [elem,HB] = uniformcoarsenred(elem) remove grid points added by uniform\n% refinement. See the illustration below:\n%\n% 4  - 7 -  3\n% | t4 | t3 |\n% 8 -  9 -  6\n% | t1 | t2 |\n% 1 -  5 -  2\n%\n% It is mainly used to get multilevel decomposition in multigrid methods.\n% The input matrix elem stands for the fine mesh and the output one for the\n% coarse mesh. The HB records the hierarchical structure of added points\n% going from the coarse to the fine mesh such that HB(:,2:3) are two parent\n% nodes of HB(:,1).\n%\n%   See also: uniformcoarsen, coarsen, bisect, uniformcoarsen3, mg\n% \n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nHB = [];\nNT = size(elem,1);\nif mod(NT,4)==0\n    NTc = NT/4; % number of triangles in the coarse grid\nelse\n%     display('Not from red refinement');\n    return\nend\n\n%% Find points\nt1 = 1:NTc; t2 = t1+NTc; t3 = t2+NTc; t4 = t3+NTc;\nif any(elem(t1,2)~=elem(t2,1)) || any(elem(t1,3)~=elem(t3,1)) || ...\n   any(elem(t4,1)~=elem(t1,4)) || any(elem(t4,2)~=elem(t3,1))\n%     display('Not from red refinement');\n    return\nend\np1 = elem(t1,1);\np2 = elem(t2,2);\np3 = elem(t3,3);\np4 = elem(t4,4);\np5 = elem(t1,2);\np6 = elem(t2,3);\np7 = elem(t3,4);\np8 = elem(t4,1);\np9 = elem(t1,3);\n\n%% Remove quad\nelem(t1,:) = [p1 p2 p3 p4];\nelem = elem(t1,:);\n\n%% Record HB\nHB(p9,:) = [p9 p1 p3];\nHB(p5,:) = [p5 p1 p2];\nHB(p6,:) = [p6 p2 p3];\nHB(p7,:) = [p7 p4 p3];\nHB(p8,:) = [p8 p1 p4];\nNc = max(elem(:));\nHB = HB(Nc+1:end,:);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/solver/uniformcoarsenquadred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.5850013883150006}}
{"text": "% Gnufft_test0.m\n% Basic tests of small Gnufft object\n\nif ~isvar('A') % create Gnufft class object\n\tomega = linspace(0, 10*2*pi, 101)'; % crude spiral:\n\tomega = pi*[cos(omega) sin(omega)].*omega(:,[1 1])/max(omega);\n\tif 1 % 2d\n\t\tN = [16 14];\n\t\tJ = [8 6];\n\t\ttestadj = @(sys) test_adjoint(sys, 'complex', 1);\n\telse % 3d\n\t\tN = [16 14 10];\n\t\tJ = [8 6 4];\n\t\tomega(:,3) = linspace(-pi, pi, size(omega,1));\n\t\ttestadj = @(sys) test_adjoint(sys, 'big', 1, 'complex', 1);\n\tend\n\tK = 2*N;\n\tmask = true(N);\n\tmask(:,end) = false;\n\tcl = 'Fatrix';\n\tcl = 'fatrix2';\n\tA = Gnufft(cl, mask, {omega, N, J, K});\n\n\tif 1\n\t\tfatrix2_tests(A, 'complex', 1, 'tol_gram', 7e-5)\n\t\ttestadj(A);\n\tend\nend\n\n\nif ~isvar('W')\n\twi = [1:size(omega,1)]';\n\tW = Gdiag(wi);\nend\n\n\nif 1, printm 'Gnufft gram'\n\tT = build_gram(A, wi);\n\tif isa(A, 'Fatrix')\n\t\tFatrix_test_basic(T, mask, 'complex', 1)\n\telse\n\t\tfatrix2_tests(T, 'complex', 1)\n\tend\n\tif length(N) == 3\n\t\ttestadj(T);\n\telse\n\t\t[t0 t1] = test_adjoint(T, 'complex', 1);\n\t\tim plc 1 3, im(1, t0), im(2, t1), im(3, t0 - t1')\n\tend\nprompt\nend\n\nif length(N) == 2, printm 'T vs A''WA' % slow in 3D\n\tT2 = T(:,:);\n\tAf = A(:,:);\n\tT1 = Af' * diag(wi) * Af;\n\tmax_percent_diff T1 T2\n\tim plc 1 3, im(1, T1), im(2, T2), im(3, T1 - T2)\n%\tequivs(y1, y2)\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/systems/tests/Gnufft_test0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5849935471346207}}
{"text": "function C = inv(S)\n% compliance to stiffness tensor\n%\n% Input\n%  S - @complianceTensor\n%\n% Output\n%  C - @stiffnessTensor\n%\n\nC = stiffnessTensor(inv@tensor(S));\n\nend\n\n% this can be done more explicitely by\nfunction test\n\nM = matrix(S,'voigt');\n\nD = M(1,1,:) .* M(2,2,:) .* M(3,3,:) ...\n  - M(1,1,:) .* M(2,3,:).^2 ...\n  - M(2,2,:) .* M(1,3,:) .* M(1,3,:) ...\n  - M(3,3,:) .* M(1,2,:).^2 ...\n  + 2 * M(1,2,:) .* M(2,3,:) .* M(1,3,:);\n\nC11 = (M(2,2,:) .* M(3,3,:)-M(2,3,:) .* M(2,3,:))/D;\nC12 = (M(1,3,:) .* M(2,3,:)-M(1,2,:) .* M(3,3,:))/D;\nC13 = (M(1,2,:) .* M(2,3,:)-M(1,3,:) .* M(2,2,:))/D;\nC22 = (M(1,1,:) .* M(3,3,:)-M(1,3,:) .* M(1,3,:))/D;\nC23 = (M(1,2,:) .* M(1,3,:)-M(2,3,:) .* M(1,1,:))/D;\nC33 = (M(1,1,:) .* M(2,2,:)-M(1,2,:) .* M(1,2,:))/D;\n\n% Enter tensor as 6 by 6 matrix,M line by line.\nM = [[  C11   C12   C13    0     0     0];...\n    [   C12   C22   C23    0     0     0];...\n    [   C13   C23   C33    0     0     0];...\n    [   0      0      0   1./M(4,4,:)    0     0];...\n    [   0      0      0    0    1./M(5,5,:)    0];...\n    [   0      0      0    0     0   1./M(6,6,:)]];\n% \nC = reshape(stiffnessTensor(M,cs_tensor,'density',rho),size(S));\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/TensorAnalysis/@complianceTensor/inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.584993540169634}}
{"text": "function KLdiv = KL_divergence2(bnetP, bnetQ)\n% KL_DIVERGENCE2 computes the Kullback-Leibler divergence between two BNET distributions\n% KLdiv = KL_divergence2(bnetP, bnetQ)\n%\n% Output :\n%   div = sum_x  P(x).log(P(x)/Q(x))\n%\n% Rem : \n%   This version is optimized for memory use, but quite slow !!!\n%     ==> if you have no memory problem, use kl_divergence instead\n%\n%   ONLY FOR TABULAR NODES\n%   Make sure that you have done the params learning.\n%\n%   V1.1 : 8 oct 2004 (Ph. Leray - philippe.leray@univ-nantes.fr)\n\nN = size(bnetP.dag,1);\nN2 = size(bnetQ.dag,1);\nns= bnetP.node_sizes;\nns2= bnetQ.node_sizes;\nif N~=N2, error('size of dags must be the same'), end\nif ns~=ns2, error('node sizes of dags must be the same'), end\ntiny = exp(-700);\nKLdiv=0;\n\nfor i=1:prod(ns),\n  inst = ind2subv(ns, i); % i'th instantiation\n  Px=1; Qx=1;\n  for i=1:N,\n    ps = parents(bnetP.dag, i);\n    e = bnetP.equiv_class(i);\n    [tmp Pxi] = prob_node(bnetP.CPD{e}, inst(i), inst(ps)');\n    Px=Px*Pxi;\n    ps = parents(bnetQ.dag, i);\n    e = bnetQ.equiv_class(i);\n    [tmp Qxi] = prob_node(bnetQ.CPD{e}, inst(i), inst(ps)');\n    Qx=Qx*Qxi;\n  end\n    Px = Px + (Px==0)*tiny; % replace 0s by tiny\n    Qx = Qx + (Qx==0)*tiny; % replace 0s by tiny\n  KLdiv = KLdiv + Px*log(Px/Qx);\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/SLP/scoring/kl_divergence2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5849935343363459}}
{"text": "function M=find_motif34(m,n)\n%FIND_MOTIF34       Motif legend\n%\n%   Motif_matrices = find_motif34(Motif_id,Motif_class);\n%   Motif_id = find_motif34(Motif_matrix);\n%\n%   This function returns all motif isomorphs for a given motif id and \n%   class (3 or 4). The function also returns the motif id for a given\n%   motif matrix\n%\n%   1. Input:       Motif_id,           e.g. 1 to 13, if class is 3\n%                   Motif_class,        number of nodes, 3 or 4.\n%\n%      Output:      Motif_matrices,     all isomorphs for the given motif\n%\n%   2. Input:       Motif_matrix        e.g. [0 1 0; 0 0 1; 1 0 0]\n%\n%      Output       Motif_id            e.g. 1 to 13, if class is 3\n%\n%\n%Mika Rubinov, UNSW, 2007-2008\n\npersistent M3 ID3 M4 ID4\n\nif isscalar(m)\n    if n==3\n        if isempty(ID3);\n            load motif34lib M3 ID3;\n        end\n        ind=find(ID3==m).';\n        M=zeros(3,3,length(ind));\n        for i=1:length(ind)\n            M(:,:,i)=reshape([0 M3(ind(i),1:3) 0 ...\n                M3(ind(i),4:6) 0],3,3);\n        end\n    elseif n==4\n        if isempty(ID4);\n            load motif34lib M4 ID4;\n        end\n        ind=find(ID4==m).';\n        M=zeros(4,4,length(ind));\n        for i=1:length(ind)\n            M(:,:,i)=reshape([0 M4(ind(i),1:4) 0 ...\n                M4(ind(i),5:8) 0 M4(ind(i),9:12) 0],4,4);\n        end\n    end\nelse\n    n=size(m,1);\n    M=eval(['find(motif' int2str(n) 'struct_bin(m))']);\nend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/find_motif34.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7217432122827969, "lm_q1q2_score": 0.584957651031174}}
{"text": "function line_num = sphere_llq_line_num ( lat_num, long_num )\n\n%*****************************************************************************80\n%\n%% SPHERE_LLQ_LINE_NUM counts lines for a latitude/longitude quadrilateral grid.\n%\n%  Discussion:\n%\n%    The number returned is the number of pairs of points to be connected.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    08 October 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer LAT_NUM, LONG_NUM, the number of latitude and\n%    longitude lines to draw.  The latitudes do not include the North and South\n%    poles, which will be included automatically, so LAT_NUM = 5, for instance,\n%    will result in points along 7 lines of latitude.\n%\n%    Output, integer LINE_NUM, the number of grid lines.\n%\n  line_num = long_num * ( lat_num + 1 ) ...\n           + lat_num * long_num;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_grid/sphere_llq_line_num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.5849576395724175}}
{"text": "function p = rad(p);\n%RAD          Radius of (interval) polynomial (same as p.rad)\n%\n%   r = rad(p)\n%\n\n% written  10/04/02     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%\n\n  p.c = rad(p.c);\n  p = normalize(p);\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/polynom/@polynom/rad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5849576364785415}}
{"text": "function boolVal=pointIsInUBeam(points,uBounds,boundType)\n%%POINTISINUBEAM A region in a single direction cosine in 2D space is\n%      defined either in terms of a central direction and a half beamwidth\n%      (the beamwidth being the distance between the bounds of the region)\n%      or in terms of a starting direction cosine and an ending direction\n%      cosine, determine whether provided points are within that span.\n%      Because beams and points that go past the -1 to 1 region alias back\n%      into that region, one cannot simply compare the values in the points\n%      to those of the bounds. \n%\n%INPUTS: points A vector or matrix of direction cosines values to test\n%               whether or not they are in the beam. nonaliased values are\n%               between -1 and 1.\n%       uBounds A 2X1 vector defining the bounds of the beam. If\n%               boundType=0, then uBounds(1) is the direction of the\n%               center of the beam and uBounds(2) is the half\n%               beamwidth of the beam. If boundType=1, then uBounds(1) is\n%               the lower bound and azBounds(2) is the upper bound --where\n%               the values are taken in increasing (aliased) order. If\n%               bounds go outside of the beam span, then they are assumed\n%               to alias back into the valid span (a beam split between two\n%               directions 180 degrees apart).\n%     boundType This is either 0 or 1 and affects the format of uBounds,\n%               as described above. The default if omitted or an empty\n%               matrix is passed is 0. \n%\n%OUTPUTS: boolVal This has the same size as the input and the entries are\n%                 true if the corresponding entry in the input is in the\n%                 beam and false if it is not in the beam. \n%\n%EXAMPLE:\n%This plots a beam that is aliased across the -1,1 boundary. Then, points\n%uniformly spaced across the -1 to 1 u span are tested for being in the\n%beam. Those in the beam are plotted in red and all the other points are\n%plotted in blue. One can see that the function correctly handles aliasing\n%around the -1,1 discontinuity.\n% range=[0;1];\n% beamHalfwidth=0.1;\n% closeEnds=true;\n% figure(1)\n% clf\n% hold on\n% uCenter=0.95;\n% drawUBeam(uCenter,beamHalfwidth,range,[],[],closeEnds,'-k','linewidth',2)\n% \n% numPoints=1000;\n% uPoints=linspace(-1,1,numPoints);\n% boundType=0;\n% uBounds=[uCenter;beamHalfwidth];\n% boolVal=pointIsInUBeam(uPoints,uBounds,boundType);\n% \n% %Plot all the points at unit range in blue.\n% points=[ones(1,numPoints);uPoints];\n% useHalfRange=true;\n% xyPts=ru2Cart2D(points,useHalfRange);\n% scatter(xyPts(1,:),xyPts(2,:),100,'.b')\n% %Plot the points that gate in red.\n% points=points(:,boolVal);\n% xyPts=ru2Cart2D(points,useHalfRange);\n% scatter(xyPts(1,:),xyPts(2,:),200,'.r')\n% axis([-1,1,-0.5,1])\n%\n%January 2023 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(boundType))\n    boundType=0;\nend\n\nif(boundType==0)\n    %If defined in terms of a beam center and a beamwidth....\n    beamCenter=uBounds(1);\n    beamHalfwidth=uBounds(2);\n\n    if(beamHalfwidth>=1)\n        boolVal=true(size(points));\n        return;\n    end\n\n    u1=beamCenter-beamHalfwidth;\n    u2=beamCenter+beamHalfwidth;\nelse\n    %If the bounds are directly given.\n    u1=uBounds(1);\n    u2=uBounds(2);\nend\n%Alias everything so that u1=0. Everything is considered in terms of\n%increasing u from 0.\nu2=wrapRange(u2-u1,0,2);\npoints=wrapRange(points-u1,0,2);\n\n%Test whether the direction cosines are in or on the edge of the beam.\nboolVal=(points<=u2);\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/Beams/pointIsInUBeam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5849124099296852}}
{"text": "function [h,g,a,info] = wfilt_oddevena(N)\n%WFILT_ODDEVENA  Kingsbury's symmetric even filters\n%\n%   Usage: [h,g,a] = wfilt_oddevena(N);\n%\n%   `[h,g,a]=wfilt_oddevena(N)` with $N \\in {1}$ returns Kingsbury's\n%   even filters.\n%\n%   Examples:\n%   ---------\n%   :::\n%     figure(1);\n%     wfiltinfo('ana:oddevena1');\n%\n%     figure(2);\n%     wfiltinfo('syn:oddevena1');\n% \n%   References: king02\n\n% AUTHOR: Zdenek Prusa\n\ninfo.istight = 0;\n\na = [2;2];\n\nswitch(N)\n case 1\n    % Example 1. from the reference. Symmetric near-orthogonal\n    garr = [\n             0           0           \n             0           0           \n             0          -0.0004645   \n             0           0.0013349  \n            -0.0058109   0.0022006  \n             0.0166977  -0.0130127  \n            -0.0000641   0.0015360  \n            -0.0834914   0.0869008  \n             0.0919537   0.0833552  \n             0.4807151  -0.4885957  \n             0.4807151   0.4885957     \n             0.0919537  -0.0833552 \n            -0.0834914  -0.0869008  \n            -0.0000641  -0.0015360  \n             0.0166977   0.0130127  \n            -0.0058109  -0.0022006  \n             0          -0.0013349  \n             0           0.0004645  \n             0           0         \n             0           0          \n    ];\n\n    % This scaling is not in the reference paper, but it is here to be\n    % consistent\n    garr = garr*sqrt(2);\n    %garr = setnorm(garr,'energy');\n    \n    offset = -10;\n\n  otherwise\n        error('%s: No such filters.',upper(mfilename)); \nend\n\n    %garr = [garr(:,3:4),garr(:,1:2)];\n    modrange = (-1).^((0:size(garr,1)-1) + offset+1).';\n    modrange2 = (-1).^((0:size(garr,1)-1) + offset).';\n    \n    harr =       [garr(:,2).*modrange2,...\n                  garr(:,1).*modrange,...\n                  ];\n            \n   \n% In the biorthogonal case, the filters do not get time reversed\ngarr = flipud(garr);\n  \nhtmp=mat2cell(harr,size(harr,1),ones(1,size(harr,2)));\nh = cellfun(@(hEl)struct('h',hEl,'offset',offset),htmp(1:2),...\n                   'UniformOutput',0);\n\n\ngtmp=mat2cell(garr,size(garr,1),ones(1,size(garr,2)));\n\ng = cellfun(@(gEl)struct('h',gEl,'offset',offset),gtmp(1:2),...\n                   'UniformOutput',0);\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/wavelets/wfilt_oddevena.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5849124021703592}}
{"text": "clc;\nload('detector1.mat');\n\nI1=imread('C:\\Shivanshu laptop data\\Desktop data\\Ortho_HOG\\video\\frame\\frame205.jpg');\n\nI=rgb2gray(I1);\nJ=edge(I,'Canny',[0.15 0.3]);\ns=size(J);\nu=s(1,1);\nv=s(1,2);\ny=[2*u/5 u u 2*u/5];%h\nx=[v/2 v/4 3*v/4 v/2];%w\nmask=poly2mask(x,y,u,v);\nf=J.*mask;\ny1=[0 u u 0];%h\nx1=[0 0 v/2 v/2];%w\nmask1=poly2mask(x1,y1,u,v);\nf1=f.*mask1;\n[H,T,R]=hough(f1);\ny2=[0 u u 0];%h\nx2=[v/2 v/2 v v];%w\nmask2=poly2mask(x2,y2,u,v);\nf2=f.*mask2;\n[H,T,R]=hough(f1,'RhoResolution',2,'ThetaResolution',5);\nP=houghpeaks(H,5,'threshold',ceil(0.5*max(H(:))));\nlines1=houghlines(f1,T,R,P,'FillGap',15,'MinLength',7);\n\n[H2,T2,R2]=hough(f2,'RhoResolution',2,'ThetaResolution',5);\nP2=houghpeaks(H2,5,'threshold',ceil(0.5*max(H2(:))));\nlines2=houghlines(f2,T2,R2,P2,'FillGap',15,'MinLength',7);\n\nfigure(6)\nimshow(I);\ntitle('0.6');\n\nmax_len1=0;\nmax_len2=0;\n%AA1=zeros(1,length(lines1));\n%AA2=zeros(1,length(lines2));\nfor k=1:length(lines1)\nlen1=norm(lines1(k).point1-lines1(k).point2);\nxy1=[lines1(k).point1;lines1(k).point2];\nif(len1>max_len1)\n    max_len1=len1;\n    xy_long=xy1;\nend\nend\n\nfor k=1:length(lines2)\nlen2=norm(lines2(k).point1-lines2(k).point2);\nxy2=[lines2(k).point1;lines2(k).point2];\nif(len2>max_len2)\n    max_len2=len2;\n    xy_2=xy2;\nend\nend\n\n%for k=1:length(lines1)\n %   disp(k);\n  %  xy=[lines1(k).point1;lines1(k).point2];\n   % len=norm(lines(k).point1-lines(k).point2);\n    %disp(xy(1,2));\n    %if(xy(1,2)<=(v/2))\n     %       AA1(1,k)=len;\n    %else\n     %   AA2(1,k)=len;\n    %end\n%end\n%[max_len1,idx]=max(AA1);\n%for k=1:length(lines)\n%if(AA1(1,k)==max_len1)\n %       xy_long=[lines(k).point1;lines(k).point2];\n  %      end\n%end\n%[max_len2,idx]=max(AA2);\n%for k=1:length(lines)\n%if(AA2(1,k)==max_len2)\n %       xy2=[lines(k).point1;lines(k).point2];\n  %      end\n%end\n\n    %[ee,ff]=max(AA);\n    %xy2=[lines(ff).point1;lines(ff).point2];\n     %plot(xy_long(:,1),xy_long(:,2)+[20; 150],'LineWidth',2,'Color','green');%\n     %plot(xy_2(:,1),xy_2(:,2)+[-10; -20],'LineWidth',2,'Color','green');\n     \n     \n     \n     \nh1=imread('C:\\Shivanshu laptop data\\Desktop data\\Ortho_HOG\\video\\frame\\frame739.jpg');\nI1=imread('C:\\Shivanshu laptop data\\Desktop data\\Ortho_HOG\\video\\frame\\frame194.jpg');\nI=rgb2hsv(I1);\nh=rgb2hsv(h1);\n%figure(1)\n%imshow(I1);\nII=I(:,:,3);\nHH=h(:,:,3);\nfor i=1:360\n    for j=1:450\n        if((II(i,j)<=1) && (II(i,j)>0.85))\n            II(i,j)=II(i,j);\n        else\n           II(i,j)=0;\n        end\n    end\nend\n\nfor i=1:360\n    for j=1:450\n        if((HH(i,j)<=1) && (HH(i,j)>0.12))\n            HH(i,j)=HH(i,j);\n        else\n           HH(i,j)=0;\n        end\n    end\nend\n%figure(2)\n%imshow(II);\n\ns=size(II);\nu=s(1,1);\nv=s(1,2);\ny=[2*u/5 u u 1*u/3 2*u/5];%h\nx=[v/2 v/3 v v v/2];%w\nmask=poly2mask(x,y,u,v);\nf=II.*mask;\n%figure(2);\n%imshow(mask);\nhh=HH.*mask;\nhh=1-hh;\n\nfor i=1:360\n  for  j=1:450\nif(hh(i,j)<1)\n    hh(i,j)=0;\nend\nend\nend\nf=f.*hh;\n\n[bbox, score, label] = detect(detector1,f)\n%Display detection results.\n%detectedImg = insertObjectAnnotation(I1,'Rectangle',bbox);\n%detectedImg = insertShape(I1,'Rectangle',bbox);\n%figure(3)\n%imshow(detectedImg)\n\n% Display detection results\nlabel_str = cell(1,1);\n%conf_val = [score];\nconf_lab = [label];\n%for ii=1:3\n    label_str =[sprintf('%s',conf_lab)];\n%end\nposition = [bbox];\noutputImage = insertObjectAnnotation(I1,'rectangle',position,label_str,...\n    'TextBoxOpacity',0.9,'FontSize',10);\nfigure(4)\nimshow(outputImage)\nhold on\nplot(xy_long(:,1),xy_long(:,2)+[20; 150],'LineWidth',2,'Color','green');%\n     plot(xy_2(:,1),xy_2(:,2)+[-10; -20],'LineWidth',2,'Color','green');\n", "meta": {"author": "Aarchishya", "repo": "Human-detection-and-tracking-on-Railway-tracks", "sha": "a99db3e80b71255dc318e7f669395f927302bcf9", "save_path": "github-repos/MATLAB/Aarchishya-Human-detection-and-tracking-on-Railway-tracks", "path": "github-repos/MATLAB/Aarchishya-Human-detection-and-tracking-on-Railway-tracks/Human-detection-and-tracking-on-Railway-tracks-a99db3e80b71255dc318e7f669395f927302bcf9/code/codefnl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5849123922490451}}
{"text": "function pass = test_addBreaksAtRoots(pref)\n\nif ( nargin == 0 )\n    pref = chebfunpref();\nend\n\n%% \n% Test that pointValues are exactly zero at the new roots.\n\n% Scalar:\nf = chebfun(@(x) sin(x)-.5, pref);\ng = addBreaksAtRoots(f);\npass(1) = g.pointValues(2) == 0;\n\n% Array-valued:\nf = chebfun(@(x) [sin(x), sin(x)-.5], pref);\ng = addBreaksAtRoots(f);\npass(2) = g.pointValues(2,1) == 0 && g.pointValues(3,2) == 0;\n\n%% piecewise smooth chebfun: smoothfun + singfun & splitting off.\n\n% define the domain:\ndom = [-2 7];\ndomCheck = [dom(1)+0.1 dom(2)-0.1];\n\npow1 = -0.5;\npow2 = -1.2;\nop = @(x) cos(40*x).*((x-dom(1)).^pow1).*((x-dom(2)).^pow2);\nf = chebfun(op, dom, 'exps', [pow1 pow2], 'splitting', 'off');\ng = addBreaksAtRoots(f);\n\n% check values:\n\n% Generate a few random points to use as test values:\nx = diff(domCheck) * rand(100, 1) + domCheck(1);\n\nvals_g = feval(g, x);\nvals_check = feval(op, x);\nerr = vals_g - vals_check;\n\nr_exact = (((-25:88)+1/2)*pi/40).';\n\npass(3) = ( norm(err, inf) < 1e4*eps*norm(vals_check, inf) ) && ...\n    ( norm( [dom(1); r_exact; dom(2)] - g.domain.', inf) < ...\n    1e4*eps*norm(r_exact, inf) );\n\n\n%% Tests for functions defined on unbounded domain:\n\n% Functions on [-inf inf]:\n\n% Set the domain:\ndom = [-Inf Inf];\ndomCheck = [-1e2 1e2];\n\n% Generate a few random points to use as test values:\nx = diff(domCheck) * rand(100, 1) + domCheck(1);\n\nop = @(x) (1-exp(-x.^2))./x;\nf = chebfun(op, dom);\ng = addBreaksAtRoots(f);\nrExact = 0;\n\nvals_g = feval(g, x);\nvals_check = feval(op, x);\nerr = vals_g - vals_check;\npass(4) = ( norm(err, inf) < 1e2*eps*vscale(f) ) && ...\n    ( norm( rExact - g.domain(2:end-1).', inf) < 1e2*eps*vscale(f) );\n    \n\n% Blow-up function:\nop = @(x) x.^2.*(1-exp(-x.^2))-2;\nf = chebfun(op, dom, 'exps', [2 2]);\ng = addBreaksAtRoots(f);\nrExact = [-1.4962104914103104707 ; 1.4962104914103104707];\n\nvals_g = feval(g, x);\nvals_check = feval(op, x);\nerr = vals_g - vals_check;\npass(5) = ( norm(err, inf) < 1e7*eps*vscale(f) ) && ...\n    ( norm( rExact - g.domain(2:end-1).', inf) < 1e5*eps*vscale(f) );\n\n\n% Functions on [a inf]:\ndom = [0 Inf];\ndomCheck = [0 100];\n\n% Generate a few random points to use as test values:\nx = diff(domCheck) * rand(100, 1) + domCheck(1);\n\nop = @(x) 0.15+sin(10*x)./exp(x);\nf = chebfun(op, dom);\ng = addBreaksAtRoots(f);\nrExact = [0.33529141416564289113; \n          0.60061694515161002799;\n          0.98375750309184861332;\n          1.2042605667187311146;\n          1.6619482204330474390;\n          1.7760894757659030239];\n      \nvals_g = feval(g, x);\nvals_check = feval(op, x);\nerr1 = norm(vals_g - vals_check, inf);\ntol1 = 1e2*eps*vscale(f);\nerr2 = norm( rExact - g.domain(2:end-1).', inf);\ntol2 = 1e2*eps*vscale(f);\npass(6) = ( err1 < tol1 ) && ( err2 < tol2 );\n\n\n% TODO: Add more tests.\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun/test_addBreaksAtRoots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.5848986666113174}}
{"text": "function stroud_test052 ( )\n\n%*****************************************************************************80\n%\n%% TEST052 tests BALL_VOLUME_3D.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    06 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 3;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST052\\n' );\n  fprintf ( 1, '  In 3 dimensions:\\n' );\n  fprintf ( 1, '  BALL_VOLUME_3D computes the volume of a unit ball.\\n' );\n  fprintf ( 1, '  BALL_VOLUME_ND will be called for comparison.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  N    R      Volume    Method\\n' );\n  fprintf ( 1, '\\n' );\n\n  r = 1.0;\n\n  for i = 1 : 3\n\n    fprintf ( 1, '  %1d  %12f  %12f  %s\\n', ...\n      n, r, ball_volume_3d ( r ), 'BALL_VOLUME_3D' );\n\n    fprintf ( 1, '  %1d  %12f  %12f  %s\\n', ...\n      n, r, ball_volume_nd ( n, r ), 'BALL_VOLUME_ND' );\n\n    r = r * 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/stroud/stroud_test052.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5848986623893493}}
{"text": "function d = dunion ( d1, d2 )\n\n%*****************************************************************************80\n%\n%% DUNION returns the signed distance to a union of two regions.\n%\n%  Copyright:\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 distance of one or more points\n%    to two regions.\n%\n%    Output, real D, the signed distance of one or more points to\n%    the region formed by the union of the two regions.\n%\n  d = min ( d1, d2 );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/dist_plot/dunion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5848986544352026}}
{"text": "%% geoSphere\n% Below is a demonstration of the features of the |geoSphere| function\n\n%% Syntax\n% |[F,V,Vs]=geoSphere(n,r,solidType);|\n\n%% Description\n% Use |geoSphere| to generate triangulated spheres with nearly geodesic\n% triangle distributions. The density of the triangulation can be\n% controlled through a particular choice of n (number of mesh refinement\n% steps).\n\n%% Examples\n\nclear; close all; clc;\n\n%%\n% Plot Settings\nfontSize=15;\nfaceAlpha=1;\nedgeColor=0.2*ones(1,3);\nedgeWidth=1.5;\n\n%% Building a geodesic dome based on the icosahedron\n% The function inputs are n and r which define the mesh refinement and\n% radius respectively. The mesh refinement number n defines the number of\n% subtriangulation (see function |subTri|) iterations performed on an\n% icosahedron.\n\nr=1; %sphere radius\nn=2; %Refinements\n[F,V,~]=geoSphere(n,r);\n[Fi,Vi,~]=geoSphere(0,r);\n%%\n% Visualize sphere\n\ncFigure; hold on;\nsubplot(1,2,1); hold on;\ngpatch(Fi,Vi,'rw','r',0.8,2);\nplotV(Vi,'r.','MarkerSize',50);\ncamlight headlight;\naxisGeom(gca,fontSize);\n\nsubplot(1,2,2); hold on;\ngpatch(F,V,'bw','k',1,2);\nplotV(Vi,'r.','MarkerSize',50);\ncamlight headlight;\naxisGeom(gca,fontSize);\ndrawnow;\n\n%%\n% Below is a visualisation for n=0:1:3. The function outputs the geodesic\n% dome faces (F) and vertices (V) and also the spherical coordinates of the\n% vertices (Vs) (this output is suppressed in the example below).\n\ncFigure; % Open figure for plotting\n\n%Defining triangulated geodesic domes with different densities\nr=1; %sphere radius\nn=0:1:3; %Refinements\npColors=gjet(numel(n));\nfor q=1:1:numel(n)\n    [F,V,~]=geoSphere(n(q),r);\n    subplot(2,2,q); hold on;\n    title([num2str(n(q)),' refinement iterations'],'FontSize',fontSize);\n    gpatch(F,V,pColors(q,:));\n    % patchNormPlot(F,V);\n    camlight headlight;\n    axisGeom(gca,fontSize);\nend\ndrawnow;\n\n%% Using other solid types\n% Other platonic solids can also be used as a starting tesselation. However\n% these may not be as geodesic as the result for the icosahedron and\n% dodecahedron.\n\n%e.g. using a cube\nsolidTypes=1:5;\n\ncFigure; % Open figure for plotting\ntitleCell={'tetrahedron','cube','octahedron','icosahedron','dodecahedron'};\npColors=gjet(numel(solidTypes));\nfor q=solidTypes\n    [F,V,~]=geoSphere(0,r,q);\n    subplot(2,3,q); hold on;\n    title(['Based on: ',titleCell{q}],'FontSize',fontSize);\n    gpatch(F,V,pColors(q,:));\n    % patchNormPlot(F,V);\n    camlight headlight;\n    axisGeom(gca,fontSize);\nend\ndrawnow;\n\n%%\n%\n% <<gibbVerySmall.gif>>\n%\n% _*GIBBON*_\n% <www.gibboncode.org>\n%\n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n\n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_geoSphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5847446131413028}}
{"text": "function [ps,ix] = dpsimplify(p,tol)\n\n% Recursive Douglas-Peucker Polyline Simplification, Simplify\n%\n% [ps,ix] = dpsimplify(p,tol)\n%\n% dpsimplify uses the recursive Douglas-Peucker line simplification \n% algorithm to reduce the number of vertices in a piecewise linear curve \n% according to a specified tolerance. The algorithm is also know as\n% Iterative Endpoint Fit. It works also for polylines and polygons\n% in higher dimensions.\n%\n% In case of nans (missing vertex coordinates) dpsimplify assumes that \n% nans separate polylines. As such, dpsimplify treats each line\n% separately.\n%\n% For additional information on the algorithm follow this link\n% http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm\n%\n% Input arguments\n%\n%     p     polyline n*d matrix with n vertices in d \n%           dimensions.\n%     tol   tolerance (maximal euclidean distance allowed \n%           between the new line and a vertex)\n%\n% Output arguments\n%\n%     ps    simplified line\n%     ix    linear index of the vertices retained in p (ps = p(ix))\n%\n% Examples\n%\n% 1. Simplify line \n%\n%     tol    = 1;\n%     x      = 1:0.1:8*pi;\n%     y      = sin(x) + randn(size(x))*0.1;\n%     p      = [x' y'];\n%     ps     = dpsimplify(p,tol);\n%\n%     plot(p(:,1),p(:,2),'k')\n%     hold on\n%     plot(ps(:,1),ps(:,2),'r','LineWidth',2);\n%     legend('original polyline','simplified')\n%\n% 2. Reduce polyline so that only knickpoints remain by \n%    choosing a very low tolerance\n%\n%     p = [(1:10)' [1 2 3 2 4 6 7 8 5 2]'];\n%     p2 = dpsimplify(p,eps);\n%     plot(p(:,1),p(:,2),'k+--')\n%     hold on\n%     plot(p2(:,1),p2(:,2),'ro','MarkerSize',10);\n%     legend('original line','knickpoints')\n%\n% 3. Simplify a 3d-curve\n% \n%     x = sin(1:0.01:20)'; \n%     y = cos(1:0.01:20)'; \n%     z = x.*y.*(1:0.01:20)';\n%     ps = dpsimplify([x y z],0.1);\n%     plot3(x,y,z);\n%     hold on\n%     plot3(ps(:,1),ps(:,2),ps(:,3),'k*-');\n%\n%\n%\n% Author: Wolfgang Schwanghart, 13. July, 2010.\n% w.schwanghart[at]unibas.ch\n\n\nif nargin == 0\n    help dpsimplify\n    return\nend\n\nerror(nargchk(2, 2, nargin))\n\n% error checking\nif ~isscalar(tol) || tol<0;\n    error('tol must be a positive scalar')\nend\n\n\n% nr of dimensions\nnrvertices    = size(p,1); \ndims    = size(p,2);\n\n% anonymous function for starting point and end point comparision\n% using a relative tolerance test\ncompare = @(a,b) abs(a-b)/max(abs(a),abs(b)) <= eps;\n\n% what happens, when there are NaNs?\n% NaNs divide polylines.\nInan      = any(isnan(p),2);\n% any NaN at all?\nInanp     = any(Inan);\n\n% if there is only one vertex\nif nrvertices == 1 || isempty(p);\n    ps = p;\n    ix = 1;\n\n% if there are two \nelseif nrvertices == 2 && ~Inanp;\n    % when the line has no vertices (except end and start point of the\n    % line) check if the distance between both is less than the tolerance.\n    % If so, return the center.\n    if dims == 2;\n        d    = hypot(p(1,1)-p(2,1),p(1,2)-p(2,2));\n    else\n        d    = sqrt(sum((p(1,:)-p(2,:)).^2));\n    end\n    \n    if d <= tol;\n        ps = sum(p,1)/2;\n        ix = 1;\n    else\n        ps = p;\n        ix = [1;2];\n    end\n    \nelseif Inanp;\n    \n    % case: there are nans in the p array\n    % --> find start and end indices of contiguous non-nan data\n    Inan = ~Inan;\n    sIX = strfind(Inan',[0 1])' + 1; \n    eIX = strfind(Inan',[1 0])'; \n \n    if Inan(end)==true;\n        eIX = [eIX;nrvertices];\n    end\n    \n    if Inan(1);\n        sIX = [1;sIX];\n    end\n    \n    % calculate length of non-nan components\n    lIX = eIX-sIX+1;   \n    % put each component into a single cell\n    c   = mat2cell(p(Inan,:),lIX,dims);\n    \n    % now call dpsimplify again inside cellfun. \n    if nargout == 2;\n        [ps,ix]   = cellfun(@(x) dpsimplify(x,tol),c,'uniformoutput',false);\n        ix        = cellfun(@(x,six) x+six-1,ix,num2cell(sIX),'uniformoutput',false);\n    else\n        ps   = cellfun(@(x) dpsimplify(x,tol),c,'uniformoutput',false);\n    end\n    \n    % write the data from a cell array back to a matrix\n    ps = cellfun(@(x) [x;nan(1,dims)],ps,'uniformoutput',false);    \n    ps = cell2mat(ps);\n    ps(end,:) = [];\n    \n    % ix wanted? write ix to a matrix, too.\n    if nargout == 2;\n        ix = cell2mat(ix);\n    end\n    \n       \nelse\n    \n\n% if there are no nans than start the recursive algorithm\nixe     = size(p,1);\nixs     = 1;\n\n% logical vector for the vertices to be retained\nI   = true(ixe,1);\n\n% call recursive function\np   = simplifyrec(p,tol,ixs,ixe);\nps  = p(I,:);\n\n% if desired return the index of retained vertices\nif nargout == 2;\n    ix  = find(I);\nend\n\nend\n\n% _________________________________________________________\nfunction p  = simplifyrec(p,tol,ixs,ixe)\n    \n    % check if startpoint and endpoint are the same \n    % better comparison needed which included a tolerance eps\n    \n    c1 = num2cell(p(ixs,:));\n    c2 = num2cell(p(ixe,:));   \n    \n    % same start and endpoint with tolerance\n    sameSE = all(cell2mat(cellfun(compare,c1(:),c2(:),'UniformOutput',false)));\n\n    \n    if sameSE; \n        % calculate the shortest distance of all vertices between ixs and\n        % ixe to ixs only\n        if dims == 2;\n            d    = hypot(p(ixs,1)-p(ixs+1:ixe-1,1),p(ixs,2)-p(ixs+1:ixe-1,2));\n        else\n            d    = sqrt(sum(bsxfun(@minus,p(ixs,:),p(ixs+1:ixe-1,:)).^2,2));\n        end\n    else    \n        % calculate shortest distance of all points to the line from ixs to ixe\n        % subtract starting point from other locations\n        pt = bsxfun(@minus,p(ixs+1:ixe,:),p(ixs,:));\n\n        % end point\n        a = pt(end,:)';\n\n        beta = (a' * pt')./(a'*a);\n        b    = pt-bsxfun(@times,beta,a)';\n        if dims == 2;\n            % if line in 2D use the numerical more robust hypot function\n            d    = hypot(b(:,1),b(:,2));\n        else\n            d    = sqrt(sum(b.^2,2));\n        end\n    end\n    \n    % identify maximum distance and get the linear index of its location\n    [dmax,ixc] = max(d);\n    ixc  = ixs + ixc; \n    \n    % if the maximum distance is smaller than the tolerance remove vertices\n    % between ixs and ixe\n    if dmax <= tol;\n        if ixs ~= ixe-1;\n            I(ixs+1:ixe-1) = false;\n        end\n    % if not, call simplifyrec for the segments between ixs and ixc (ixc\n    % and ixe)\n    else   \n        p   = simplifyrec(p,tol,ixs,ixc);\n        p   = simplifyrec(p,tol,ixc,ixe);\n\n    end\n\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/21132-line-simplification/dpsimplify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5847446052847461}}
{"text": "function z = crossp(x,y)\n\n% crossp - compute cross product\n%\n%   z = crossp(x,y);\n%\n% x and y are (m,3) dimensional\n%\n%   Copyright (c) 2007 Gabriel Peyre\n\nz = x;\nz(:,1) = x(:,2).*y(:,3) - x(:,3).*y(:,2);\nz(:,2) = x(:,3).*y(:,1) - x(:,1).*y(:,3);\nz(:,3) = x(:,1).*y(:,2) - x(:,2).*y(:,1);", "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/crossp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5847446016992237}}
{"text": "function varargout = svmtrain(varargin)\n% VL_SVMTRAIN   Train a Support Vector Machine\n%   [W B] = VL_SVMTRAIN(X, Y, LAMBDA) trains a linear Support Vector\n%   Machine (SVM) from the data vectors X and the labels Y. X is a D\n%   by N matrix, with one column per example and D feature dimensions\n%   (SINGLE or DOUBLE). Y is a DOUBLE vector with N elements with a\n%   binary (-1 or +1) label for each training point. To a first order\n%   approximation, the function computes a weight vector W and offset\n%   B such that the score W'*X(:,i)+B has the same sign of LABELS(i)\n%   for all i.\n%\n%   VL_SVMTRAIN(DATASET, LABELS, LAMBDA) takes as input a DATASET\n%   structure, which allows more sophisticated input formats to be\n%   supported (see VL_SVMDATASET()).\n%\n%   [W, B, INFO] = VL_SVMTRAIN(...) additionally returns a structure\n%   INFO with the following fields:\n%\n%   iteration::\n%     Number of iterations performed.\n%\n%   epoch::\n%     Number of iterations over number of training data points.\n%\n%   elapsedTime::\n%     Time elapsed since the start of training.\n%\n%   objective::\n%     SVM objective value.\n%\n%   regularizer::\n%     Regularizer value.\n%\n%   loss::\n%     Loss value.\n%\n%   scoreVariation:: [SGD only]\n%     Mean square root of the difference between the last two\n%     values of the SVM scores for each point.\n%\n%   dualObjective:: [SDCA only]\n%     Dual objective value.\n%\n%   dualLoss:: [SDCA only]\n%     Dual loss value::\n%\n%   dualityGap:: [SDCA only]\n%     Difference between the objective and the dual objective.\n%\n%   [W, B, INFO, SCORES] = VL_SVMTRAIN(X, Y, LABMDA) returns a row\n%   vector of the SVM score for each training point. This can be used\n%   in combination with the options SOLVER, MODEL, and BIAS to\n%   evaluate an existing SVM on new data points. Furthermore INFO will\n%   contain the corresponding SVM loss, regularizer, and objective\n%   function value. If this information is not of interest, it is\n%   possible to pass a null vector Y instead of the actual labels as\n%   well as a null regularizer.\n%\n%   VL_SVMTRAIN() accepts the following options:\n%\n%   Verbose::\n%     Specify one or multiple times to increase the verbosity level.\n%     Given only once, produces messages at the beginning and end of\n%     the learning. Verbosity of at least 2 prints information at\n%     every diagnostic step.\n%\n%   Epsilon:: 1e-3\n%     Tolerance for the stopping criterion.\n%\n%   MaxNumIterations:: 10/LAMBDA\n%     Maximum number of iterations.\n%\n%   BiasMultiplier:: 1\n%     Value of the constant B0 used as bias term (see below).\n%\n%   BiasLearningRate:: 0.5\n%     Learning rate for the bias (SGD solver only).\n%\n%   DiagnosticFunction:: []\n%     Diagnostic function callback. The callback takes the INFO\n%     structure as only argument. To trace energies and plot graphs,\n%     the callback can update a global variable or, preferably, be\n%     defined as a nested function and update a local variable in the\n%     parent function.\n%\n%   DiagnosticFrequency:: Number of data points\n%     After how many iteration the diagnostic is run. This step check\n%     for convergence, and is done rarely, typically after each epoch\n%     (pass over the data). It also calls the DiangosticFunction,\n%     if any is specified.\n%\n%   Loss:: HINGE\n%     Loss function. One of HINGE, HINGE2, L1, L2, LOGISTIC.\n%\n%   Solver:: SDCA\n%     One of SGD (stochastic gradient descent [1]), SDCA (stochastic\n%     dual coordinate ascent [2,3]), or NONE (no training). The\n%     last option can be used in combination with the options MODEL\n%     and BIAS to evaluate an existing SVM.\n%\n%   Model:: null vector\n%     Specifies the initial value for the weight vector W (SGD only).\n%\n%   Bias:: 0\n%     Specifies the initial value of the bias term (SGD only).\n%\n%   Weights:: []\n%     Specifies a weight vector to assign a different non-negative\n%     weight to each data point. An application is to rebalance\n%     unbalanced datasets.\n%\n%   FORMULATION\n%\n%   VL_SVMTRAIN() minimizes the objective function of the form:\n%\n%     LAMBDA/2 |W|^2 + 1/N SUM_i LOSS(W' X(:,i), Y(i))\n%\n%   where LOSS(W' Xi,Yi) is the loss (hinge by default) for i-th\n%   data point. The bias is incorporated by extending each data\n%   point X with a feature of constant value B0, such that the\n%   objective becomes\n%\n%    LAMBDA/2 (|W|^2 + WB^2) 1/N SUM_i LOSS(W' X(:,i) + WB B0, Y(i))\n%\n%   Note that this causes the learned bias B = WB B0 to shrink\n%   towards the origin.\n%\n%   Example::\n%     Learn a linear SVM from data X and labels Y using 0.1\n%     as regularization coefficient:\n%\n%       [w, b] = vl_svmtrain(x, y, 0.1) ;\n%\n%     The SVM can be evaluated on new data XTEST with:\n%\n%       scores = w'*xtest + b ;\n%\n%     Alternatively, VL_SVMTRAIN() can be used for evaluation too:\n%\n%       [~,~,~, scores] = vl_svmtrain(xtest, y, 0, 'model', w, 'bias', b, 'solver', 'none') ;\n%\n%     The latter form is particularly useful when X is a DATASET structure.\n%\n%   See also: <a href=\"matlab:vl_help('svm')\">SVM fundamentals</a>,\n%   VL_SVMDATASET(), VL_HELP().\n[varargout{1:nargout}] = vl_svmtrain(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/svmtrain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5847446010137115}}
{"text": "function idx = scimat_world2index(x, scimat, CHOP)\n% SCIMAT_WORLD2INDEX  Convert real world coordinates to image indices for\n% the SCIMAT image struct that we use in Gerardus.\n% \n%   Function SCIMAT_WORLD2INDEX() converts the coordinates of a voxel given\n%   as real world coordinates [x, y, z, t] into index coordinates \n%   [row, column, slice, frame].\n%\n%      [x, y, z, t] -> [r, c, s, f]\n%\n%   This agrees with Matlab's convention that images are expected to be\n%   (r, c, s) <-> (y, x, z), but point coordinates are given in the\n%   (x, y, z)-order.\n%\n%   This function can also be applied to images that are not 4D, and in\n%   that case, index and real world coordinates will have the same number\n%   of elements as dimensions the image has.\n%\n%   The relation between indices IDX and real world coordinates X is\n%\n%     X = s.*(IDX-1)*R + t\n%\n%   where s is the voxel size, R the rotation matrix, and t the\n%   image offset.\n%\n%   For points that are not within the data volume, the returned\n%   indices are \"NaN\".\n%\n%   Note also that the indices are not rounded, to allow for sub-pixel\n%   accuracy. If integer indices are required, then just use round(idx).\n%\n% IDX = SCIMAT_WORLD2INDEX(X, SCIMAT)\n%\n%   X is a 3-column matrix where each row contains the real world\n%   (x,y,z)-coordinates of a point.\n%\n%   IDX has the same size as X, and the voxel indices in \n%   (row, column, slice)-order, that corresponds to (y, x, z)-order.\n%\n%   SCIMAT is a struct with the image space metadata, i.e. spacing, offset\n%   and orientation (see \"help scimat\" for details). SCIMAT.data (the fild\n%   that contains the image itself) is not used by the function, and thus\n%   can be present or absent. Note that Matlab will pass SCIMAT.data by\n%   reference, so passing the whole image does not require more memory or\n%   slow the function down.\n%\n% IDX = SCIMAT_WORLD2INDEX(..., CHOP)\n%\n%   CHOP is a flag to convert points outside the image volume to NaNs. By\n%   default, CHOP=true.\n%\n%\n% Example:\n%\n% >> idx = scimat_world2index([.01, .011, .02], scimat)\n%\n% idx =\n%\n%     55   189   780\n%\n% See also: scimat, scimat_index2world, scimat_load, scimat_im2scimat.\n    \n% Authors: Ramon Casero <rcasero@gmail.com>, \n% Benjamin Villard <b.016434@gmail.com>,\n% Christopher Kelly  <christopher.kelly28@googlemail.com>\n% Copyright \u00a9 2009-2015 University of Oxford\n% Version: 0.5.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 <http://www.gnu.org/licenses/>.\n\n% check arguments\nnarginchk(2, 3);\nnargoutchk(0, 1);\n\n% defaults\nif (nargin < 3 || isempty(CHOP))\n    CHOP = true;\nend\nif (~isfield(scimat, 'rotmat'))\n    scimat.rotmat = [];\nend\n\n% extract parameters\nxmin = [scimat.axis.min];\ndx = [scimat.axis.spacing];\nn = [scimat.axis.size];\norig = xmin + dx/2;\nR = scimat.rotmat;\n\n% number of dimensions\nD = length(scimat.axis);\n\n%% convert real world coordinates to indices\n\n% remove offset\nidx = x - repmat(orig([2 1 3:end]), size(x, 1), 1);\n\n% apply inverse rotation only to the spatial coordinates\nif (~isempty(R))\n    idx(:, 1:size(R, 1)) = idx(:, 1:size(R, 1)) * R';\nend\n\n% (x, y) => (y, x)\nidx = idx(:, [2 1 3:end]);\n\n% i = x / dx + 1\nidx = idx ./ repmat(dx, size(idx, 1), 1) + 1;\n\n% find which coordinates are outside the volume\nif CHOP\n    for I = 1:D\n        idx(idx(:, I) < 0.5 | idx(:, I) > n(I)+0.5, I) = NaN;\n    end\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/FileFormatToolbox/scimat_world2index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5846908118118832}}
{"text": "function clenshaw_curtis_rule ( n, a, b, filename )\n\n%*****************************************************************************80\n%\n%% CLENSHAW_CURTIS_RULE generates a Clenshaw Curtis rule.\n%\n%  Discussion:\n%\n%    This program computes a standard Clenshaw Curtis quadrature rule\n%    and writes it to a file.\n%\n%    The user specifies:\n%    * N, the number of points in the rule;\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%    06 February 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CLENSHAW_CURTIS_RULE\\n' );\n  fprintf ( 1, '  MATLAB version\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Compute a Clenshaw Curtis rule for approximating\\n' );\n  fprintf ( 1, '    Integral ( A <= x <= B ) f(x) dx\\n' );\n  fprintf ( 1, '  of order N.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The user specifies N, A, B, and FILENAME.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  N is the number of points:\\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, '\\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 N.\n%\n  if ( nargin < 1 )\n    n = input ( '  Enter the rule order N:  ' );\n  elseif ( ischar ( n ) )\n    n = str2num ( n );\n  end\n%\n%  Get A.\n%\n  if ( nargin < 2 )\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 < 3 )\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 < 4 )\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, '  N = %d\\n', n );\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 and output it.\n%\n  r = [ a; b ];\n  [ x, w ] = clenshaw_curtis_compute ( n );\n%\n%  Rescale the rule.\n%\n  [ x, w ] = rescale ( a, b, x, w );\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,  'CLENSHAW_CURTIS_RULE:\\n' );\n  fprintf ( 1,  '  Normal end of execution.\\n' );\n  fprintf ( 1,  '\\n' );\n  timestamp ( );\n\n  return\nend\nfunction [ x, w ] = clenshaw_curtis_compute ( n )\n\n%*****************************************************************************80\n%\n%% CLENSHAW_CURTIS_COMPUTE computes a Clenshaw Curtis quadrature rule.\n%\n%  Discussion:\n%\n%    Our convention is that the abscissas are numbered from left to right.\n%\n%    The rule is defined on [-1,1].\n%\n%    The integral to approximate:\n%\n%      Integral ( -1 <= X <= 1 ) F(X) dX\n%\n%    The quadrature rule:\n%\n%      Sum ( 1 <= I <= N ) W(I) * F ( X(I) )\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 February 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the order of the rule.\n%    1 <= N.\n%\n%    Output, real X(N), the abscissas.\n%\n%    Output, real W(N), the weights.\n%\n  if ( n < 1 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'CLENSHAW_CURTIS_COMPUTE - Fatal error!\\n' );\n    fprintf ( 1, '  Illegal value of N = %d\\n', n );\n    error ( 'CLENSHAW_CURTIS_COMPUTE - Fatal error!' );\n  end\n\n  w = zeros ( n, 1 );\n  x = zeros ( n, 1 );\n\n  if ( n == 1 )\n    x(1) = 0.0;\n    w(1) = 2.0;\n    return\n  end\n\n  for i = 1 : n\n    x(i) = cos ( ( n - i ) * pi / ( n - 1 ) );\n  end\n\n  x(1) = -1.0;\n  if ( mod ( n, 2 ) == 1 )\n    x((n+1)/2) = 0.0;\n  end\n  x(n) = +1.0;\n\n  w(1:n) = 1.0;\n\n  for i = 1 : n\n\n    theta = ( i - 1 ) * pi / ( n - 1 );\n\n    for j = 1 : ( n - 1 ) / 2\n\n      if ( 2 * j == ( n - 1 ) )\n        b = 1.0;\n      else\n        b = 2.0;\n      end\n\n      w(i) = w(i) - b * cos ( 2.0 * j * theta ) / ( 4 * j * j - 1 );\n\n    end\n\n  end\n\n  w(1)     =       w(1)     / ( n - 1 );\n  w(2:n-1) = 2.0 * w(2:n-1) / ( n - 1 );\n  w(n)     =       w(n)     / ( n - 1 );\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 [ x, w ] = rescale ( a, b, x, w )\n\n%*****************************************************************************80\n%\n%% RESCALE rescales a Legendre quadrature rule from [-1,+1] to [A,B].\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    21 October 2009\n%\n%  Author:\n%\n%    John Burkardt.\n%\n%  Parameters:\n%\n%    Input, real A, B, the endpoints of the new interval.\n%\n%    Input, integer N, the order.\n%\n%    Input, real X(N), the abscissas for [-1,+1].\n%\n%    Input, real W(N), the weights for [-1,+1].\n%\n%    Output, real X(N), the abscissas for [A,B].\n%\n%    Output, real W(N), the weights for [A,B].\n%\n  x = 0.5 * ( ( x + 1.0 ) * b - ( x - 1.0 ) * a );\n\n  w = 0.5 * ( b - a ) * w;\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 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/clenshaw_curtis_rule/clenshaw_curtis_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.5846908032375712}}
{"text": "function [volumePVC] = PVEcorrect(volume,nIter,waveletName)\n% -------------------------------------------------------------------------\n% function [volumePVC] = PVEcorrect(volume,nIter,waveletName)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% Apply partial-volume effect (PVE) correction of an input PET volume\n% using the methodology developed in ref. [1].\n% -------------------------------------------------------------------------\n% REFERENCE:\n% [1] Boussion, N. et al. (2009). Incorporation of wavelet-based denoising\n%     in iterative deconvolution for partial volume correction in \n%     whole-body PET imaging. Eur J Nucl Med Mol Imaging, 36(7), 1064-1075.\n% -------------------------------------------------------------------------\n% INPUTS:\n% - volume: 3D array representing the input PET volume to correct for PVE.\n% - nIter: Number of iterations in the deconvolution process of the PVE \n%          correction (see ref. [1]). If set to a string 'compute', the \n%          algorithm will determine the optimal number of iterations in \n%          terms of residuals up to a maximum of 10.\n% - waveletName: (optional). MATLAB name of the type of wavelet used in the \n%                denoising part of the PVE correction (see ref. [1]). \n%                Default is 'bior3.5'.\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% - volumePVC: 3D array representing the input PET volume corrected for\n%              partial volume effects.\n% -------------------------------------------------------------------------\n% AUTHOR(S): \n% - Andre Diamant <adboustead@gmail.com>\n% - Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: January 2016\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015  Martin Vallieres\n%\n%    This package 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 package 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 package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\n% INTIALIZATION\nvolumePVC = zeros(size(volume));\npsf = nonIsotropicGaussianPSF(1,4);\n\nif nargin == 3\n    global wavelet_name\n    wavelet_name = waveletName;\nend\n\n% PVE CORRECTION\nif strcmp(nIter,'compute')\n    [~,residuals] = deconvlucydenoiseNew(volume,psf,10);\n    [~,nIter] = min(abs(residuals));\n    fprintf('*** FOUND NUMBER OF ITERATIONS TO BE %.0f ***\\n',nIter)\nend\n[volumePVC,~] = deconvlucydenoiseNew(volume,psf,nIter);\n\nif nargin == 3\n    clear global wavelet_name\nend\n\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/PRE-PROCESSING/PVEcorrection/PVEcorrect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5846907980929835}}
{"text": "% DEMO_VALIDATION_CSP - The demo exemplifies how to use the crossvalidation\n%  function to validate CSP-based classification. The important issue here\n%  is that the CSP analysis has to be performed WITHIN the cross-validation\n%  on each training set. The matrix of spatial filters that is obtained from\n%  the training set needs to be transfered to the test set. If you would like\n%  to know more about such valiation issues, see [Lemm et al, Neuroimage\n%  2011]. \n%  In the function crossvalidation, there is the possibility to specify\n%  processing chains separately for training and test set. Variables obtained\n%  from training data may be transfered to the test data. Each step in the\n%  processing chain is an application of a 'proc_*' function that transforms\n%  the features.\n\n\nfile= fullfile(BTB.DataDir, 'demoMat', 'VPkg_08_08_07', ...\n               'calibration_motorimageryVPkg');\n[cnt, mrk]= file_loadMatlab(file);\nmrk= mrk_selectClasses(mrk, [1 2]);\n\n[filt_b,filt_a]= butter(5, [9 13]/cnt.fs*2);\ncnt= proc_filt(cnt, filt_b, filt_a);\nfv= proc_segmentation(cnt, mrk, [750 3750]);\n\nproc.train= {{'CSPW', @proc_cspAuto, 3}\n             @proc_variance\n             @proc_logarithm\n            };\nproc.apply= {{@proc_linearDerivation, '$CSPW'}\n             @proc_variance\n             @proc_logarithm\n            };\n\ncrossvalidation(fv, {@train_RLDAshrink, 'Gamma',0}, ...\n                'SampleFcn', {@sample_chronKFold, 8}, ...\n                'Proc', proc)\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/demos/demo_validation_csp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5846878276482965}}
{"text": "function maxzlta() \n    % maxzlta calculates the maximum z value for the LTA function. \n    % The parameter step (window) can be defined by the user.\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    report_this_filefun();\n    \n    winlen_days = ZG.compare_window_dur_v3 / ZG.bin_dur;\n    \n    [len, ncu] = size(cumuall);       % redefine ncu\n    len = len -2;\n    lta = 1:1:ncu-2;\n    var1 = zeros(1,ncu);\n    var2 = zeros(1,ncu);\n    lta = zeros(1,ncu);\n    maxlta = zeros(1,ncu);\n    maxlta = maxlta -5;\n    cu = [cumuall(1:ti-1,:) ; cumuall(ti+winlen_days+1:len,:)];\n    mean1 = mean(cu(:,:));\n    wai = waitbar(0,'Please wait...')\n    set(wai,'Color',[0.8 0.8 0.8],'NumberTitle','off','Name','Percent done');\n    for i = 1:ncu\n        var1(i) = cov(cu(:,i));\n    end     % for i\n    \n    for it = 1:step: len - winlen_days\n        \n        waitbar(it/len)\n        \n        mean2 = mean(cumuall(it:it+winlen_days,:));\n        for i = 1:ncu\n            var2(i) = cov(cumuall(it:it+winlen_days,i));\n        end     % for i\n        lta = (mean1 - mean2)./(sqrt(var1/it+var2/(len-it)));\n        maxlta2 = [maxlta ;  lta ];\n        maxlta = max(maxlta2);\n        \n    end    % for it\n    \n    \n    valueMap = reshape(maxlta,length(gy),length(gx));\n    \n    close(wai)\n    \n    stri = [  'Maximum z  Map of   '  file1];\n    stri2 = ['winlen_days = ' char(days(winlen)) ];\n    in = 'lta';\n    view_max(valueMap,gx,gy,stri,'');\n    \n    \nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/maxzlta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276224, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5846878229513415}}
{"text": "function [y,a]=plane_project2(x,E)\n    [N,M]=size(x);\n    p=size(E,2);\n    a=zeros(p,M);\n    ct=E(:,1);\n    Ep=E(:,2:p)-ct*ones(1,p-1);\n    a(2:p,:)=Ep\\(x-ct*ones(1,M));\n    a(1,:)=ones(1,M)-sum(a(2:p,:),1);\n    y=E*a;\nend", "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/AAM/plane_project2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5846530174177694}}
{"text": "function [z, mu, s] = zscore(x, varargin)\n\n% [Z, MU, S] = ZSCORE(X, NORMALIZEFLAG, DIM, FLAG) computes the zscore, across all cells in x along \n% the dimension dim, normalising by the total number of samples \n% \n% X should be an linear cell-array of matrices for which the size in at \n% least one of the dimensions should be the same for all cells. If flag==1, the mean will\n% be subtracted first (default behavior, but to save time on already demeaned data, it\n% can be set to 0). MU and S are vectors containing the mean and standard deviations used\n% for zscoring\n\nif numel(varargin)==0, varargin{1} = []; end\nif numel(varargin)==1, varargin{2} = []; end\nif numel(varargin)==2, varargin{3} = 1;  end\n\nif varargin{3}\n  mu = nanmean(x, varargin{2});\n  x  = cellvecadd(x, -mu);\nend\ns = nanstd(x, varargin{1:end});\nz = cellvecmult(x, 1./s);\n\nif ~varargin{3}\n  mu = zeros(size(s))+nan;\nend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/cellfunction/@cell/zscore.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5846530072601726}}
{"text": "function data = funInterp2(x_pred, y_pred, x_obs, y_obs, data_obs, fun)\n%\n% SINTAX:\n%   data = funInterp2(x_pred, y_pred, x_obs, y_obs, data_obs, fun)\n%\n% INPUT:\n%   x_pred , y_pred     coordinates of the prediction point (arrays [n x 1])\n%   x_obs, y_obs        coordinates of the observation (array [n x 1], sparse points)\n%   data_obs            data observation array [n x n_epochs]\n%   fun                 virtual function f(dist) as function of the distance\n%\n% OUTPUT:\n%   data                interpolated data in the point of interest [n x n_epochs]\n%\n% DEFAULT VALUES:\n%   generic interpolator using as correlation function fun\n%   <default: fun = @(dist) exp(-dist)>\n%\n% EXAMPLE:\n%   fun = @(dist) 0.2 * exp(-(dist/1e4)) + exp(-(dist/6e3).^2);\n%   temp = funInterp2(ep(:), np(:), e_obs(:), n_obs(:), td_obs(:,:), fun);\n%\n\n%--- * --. --- --. .--. ... * ---------------------------------------------\n%               ___ ___ ___\n%     __ _ ___ / __| _ | __|\n%    / _` / _ \\ (_ |  _|__ \\\n%    \\__, \\___/\\___|_| |___/\n%    |___/                    v 1.0RC1\n%\n%--------------------------------------------------------------------------\n%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n%  Written by:       Andrea Gatti\n%  Contributors:     Andrea Gatti ...\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 <http://www.gnu.org/licenses/>.\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n    narginchk(5, 6);\n\n    if nargin < 6\n        % Correlation function\n        fun = @(dist) exp(-dist);\n    end\n\n    % Init out data\n    data = nan(size(data_obs, 2), numel(x_pred));\n\n    [x_mesh, y_mesh] = meshgrid(x_obs, y_obs);\n    d_obs = sqrt(abs(x_mesh - x_mesh').^2 + abs(y_mesh - y_mesh').^2);\n    q_fun_obs = fun(d_obs);\n    %q_fun_obs = exp(-d_obs/0.4e4);\n    [xv, ~, xi] = unique(x_pred);\n    [yv, ~, yi] = unique(y_pred);\n    x2 = (repmat(x_obs, 1, numel(xv)) - repmat(xv', numel(x_obs), 1)).^2;\n    y2 = (repmat(y_obs, 1, numel(yv)) - repmat(yv', numel(y_obs), 1)).^2;\n    for i = 1 : numel(x_pred)\n        d_pred = sqrt(x2(:,xi(i)) + y2(:,yi(i)));\n        c_mat = q_fun_obs .* repmat(fun(d_pred)', size(q_fun_obs,1),1);\n        %c_mat = bsxfun(@times, q_fun_obs, fun(d_pred)');\n        c_mat = triu(c_mat) + triu(c_mat, 1)';\n\n        trans = sum(c_mat);\n        w = trans / sum(trans);\n        data(:, i) = (w * data_obs)';\n    end\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/funInterp2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5846529962897703}}
{"text": "function [ ap, prec_k, recall_k ] = evaluate( actual, prediction, cutoff )\n% Codes for evaluate average precision (AP), precision@k and recall@k\n% given actual ranking and predicted ranking\n% \n% ARGS:\n% actual       : the given actual ranking\n% prediction   : the given predicted ranking\n% cutoff       : cutoff k for precision@k and recall@k\n%\n% RETURN:\n% ap           : the average precision (not MAP)\n% prec_k       : the precision@k\n% recall_k     : the recall@k\n\nap = ap_k(actual, prediction);\nprks = pr_k(actual, prediction, cutoff);\nprec_k = prks(1,:);\nrecall_k = prks(2,:);\n\n\nfunction scores = ap_k(actual, prediction, k)\nif nargin<3\n    k=inf;\nend\n\nif length(prediction)>k\n    prediction = prediction(1:k);\nend\nscore = 0;\nnum_hits = 0;\nfor i=1:min(length(prediction), k)\n    if sum(actual==prediction(i))>0 && ...\n            sum(prediction(1:i-1)==prediction(i))==0\n        num_hits = num_hits + 1;\n        score = score + num_hits / i;\n    end\nend\nscores = score / min(length(actual), k);\n\n\nfunction scores = pr_k(actual, prediction, ks)\nscores = zeros(2, length(ks));\nfor i=1:length(ks)\n    k = ks(i);\n    if length(prediction) > k\n        pred = prediction(1:k);\n    else\n        pred = prediction;\n    end\n    num_hit = length(intersect(actual, pred));\n    scores(1, i) = num_hit / length(pred); % precision\n    scores(2, i) = num_hit / length(actual); % recall\nend", "meta": {"author": "graytowne", "repo": "caser", "sha": "a981663a608bc3f393fee3bf9f7d8098676dd0f2", "save_path": "github-repos/MATLAB/graytowne-caser", "path": "github-repos/MATLAB/graytowne-caser/caser-a981663a608bc3f393fee3bf9f7d8098676dd0f2/evaluation/evaluate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5846445303244484}}
{"text": "function test_libltfat_gabframediag\n[~,~,enuminfo]=libltfatprotofile;\nLTFAT_FIRWIN = enuminfo.LTFAT_FIRWIN;\n\na = 14;\ngl = 34;\nM = 64;\ng = zeros(gl,1);\nd = zeros(a,1);\ngPtr = libpointer('doublePtr',g);\ndPtr = libpointer('doublePtr',d);\n\ncalllib('libltfat','ltfat_firwin_d',LTFAT_FIRWIN.LTFAT_HANN,gl,gPtr);\n\n\ncalllib('libltfat','ltfat_gabframediag_d',gPtr,gl,a,M,a,dPtr);\n\n\nd =gabframediag(gPtr.Value,a,M,lcm(a,M));\nd(1:a)-dPtr.Value\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/libltfat/modules/libltfat/testing/mUnit/test_gabframediag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5846445257447542}}
{"text": "%% A Unit Test Class for the OPTI Object\nclassdef opti_tests < matlab.unittest.TestCase\n\n    properties\n\n    end\n    \n    % Unit Tests\n    methods (Test)\n\n        %-- Single Precision: Nonlinear --%\n        function singleNonlinear(testCase)\n            \n            optiObj = opti_tests.makeHS71();\n            defaultOpts = optiset(optiObj.opts, 'warnings', 'none', 'derivCheck', 'on');\n            \n            testCase.verifyError(@() opti(optiObj, 'fun', @(x) single(opti_tests.hs71_obj(x))), 'OPTI:NotDouble');\n            testCase.verifyError(@() opti(optiObj, 'nlcon', @(x) single(opti_tests.hs71_con(x))), 'OPTI:NotDouble');           \n            testCase.verifyError(@() opti(optiObj, 'grad', @(x) single(opti_tests.hs71_grad(x)), 'opts', defaultOpts), 'OPTI:NotDouble');         \n            testCase.verifyError(@() opti(optiObj, 'nljac', @(x) single(opti_tests.hs71_jac(x)), 'opts', defaultOpts), 'OPTI:NotDouble');\n            testCase.verifyError(@() opti(optiObj, 'hess', @(x,s,l) single(opti_tests.hs71_hess(x,s,l)), 'opts', defaultOpts), 'OPTI:NotDouble');\n        end\n    end\n    \n    methods (Static)\n        %-- Hock & Schittkowski #71 --%\n        function optiObj = makeHS71()            \n            cl = [25;40];\n            cu = [Inf;40];\n            lb = ones(4,1);\n            ub = 5*ones(4,1);        \n            x0 = [1 5 5 1]';               \n            opts = optiset('warnings', 'none');\n            optiObj = opti('fun',@opti_tests.hs71_obj,'grad',@opti_tests.hs71_grad,'hess',@opti_tests.hs71_hess,...\n                            'nl',@opti_tests.hs71_con,cl,cu,'nljac',@opti_tests.hs71_jac,'nljacstr',@opti_tests.hs71_jacStr,...\n                            'hessstr',@opti_tests.hs71_hessStr,'bounds',lb,ub, 'x0', x0, 'opts', opts);\n        end\n            \n        function obj = hs71_obj(x)\n            obj = x(1)*x(4)*sum(x(1:3)) + x(3);\n        end\n        \n        function grad = hs71_grad(x)\n            grad = [ 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        end\n        \n        function con = hs71_con(x)\n            con = [ prod(x); sum(x.^2) ];\n        end\n        \n        function jac = hs71_jac(x)\n            jac = [ prod(x)./x'; 2*x' ];\n        end\n        \n        function jacStr = hs71_jacStr()\n            jacStr = sparse(ones(2,4));\n        end\n        \n        function hess = hs71_hess(x, sigma, lambda)\n            hess = sigma*[ 2*x(4)             0      0   0;\n                              x(4)               0      0   0;\n                              x(4)               0      0   0;\n                              2*x(1)+x(2)+x(3)  x(1)  x(1)  0 ] + ...\n                   lambda(1)*[   0          0         0         0;\n                              x(3)*x(4)     0         0         0;\n                              x(2)*x(4) x(1)*x(4)     0         0;\n                              x(2)*x(3) x(1)*x(3) x(1)*x(2)     0  ] + ...\n         \t\t   lambda(2)*diag([2 2 2 2]);\n        end\n            \n        function hessStr = hs71_hessStr()\n            hessStr = sparse(tril(ones(4)));\n        end\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/opti/Utilities/UnitTests/opti_tests.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5845592819252386}}
{"text": "function [hfun] = limhfn2(vert,tria,hfun,dhdx)\n%LIMHFN2 impose gradient limits on a discrete mesh-size fun-\n%ction defined over a 2-simplex triangulation.\n%   [HFUN] = LIMHFN2(VERT,TRIA,HFUN,DHDX) returns a \"gradie-\n%   nt-limited\" function HFUN, defined over a triangulation\n%   {VERT,TRIA}. HFUN is a T-by-1 vector of function values,\n%   VERT is a V-by-2 array of XY coordinates and TRIA is a\n%   T-by-3 array of triangles. Each row of TRIA\n%   defines a triangle, such that VERT(TRIA(II,1),:), VERT(\n%   TRIA(II,2),:) and VERT(TRIA(II,3),:) are the coordinates\n%   of the II-TH triangle. DHDX is a scalar gradient-limit.\n%   HFUN is \"limited\" to control variation over the elements\n%   in the triangulation, such that (HFUN(V2)-HFUN(V1))/LL<=\n%   DHDX, where {V1,V2} are the vertices of a given triangle\n%   edge and LL is the edge-length. Limits are enforced exh-\n%   austively over all edges.\n%\n%   See also TRIHFN2, LFSHFN2\n\n%   This function is based on a very simplified version of:\n%   Persson, P.O. \"Mesh size functions for implicit geometr-\n%   ies and PDE-based gradient limiting.\" Engineering with\n%   Computers 22 (2006): 95-109.\n\n%   Darren Engwirda : 2017 --\n%   Email           : de2363@columbia.edu\n%   Last updated    : 18/04/2017\n\n%---------------------------------------------- basic checks\n    if ( ~isnumeric(vert) || ...\n         ~isnumeric(tria) || ...\n         ~isnumeric(hfun) || ...\n         ~isnumeric(dhdx) )\n        error('limhfn2:incorrectInputClass' , ...\n            'Incorrect input class.') ;\n    end\n\n%---------------------------------------------- basic checks\n    if (ndims(vert) ~= +2 || ...\n        ndims(tria) ~= +2 || ...\n        ndims(hfun) ~= +2 || ...\n        numel(dhdx) ~= +1 )\n        error('limhfn2:incorrectDimensions' , ...\n            'Incorrect input dimensions.');\n    end\n    if (size(vert,2)~= +2 || ...\n        size(tria,2) < +3 || ...\n        size(hfun,2)~= +1 || ...\n        size(vert,1)~= size(hfun,1) )\n        error('limhfn2:incorrectDimensions' , ...\n            'Incorrect input dimensions.');\n    end\n\n    nvrt = size(vert,1) ;\n\n%---------------------------------------------- basic checks\n    if (min(min(tria(:,1:3))) < +1 || ...\n            max(max(tria(:,1:3))) > nvrt )\n        error('limhfn2:invalidInputArgument', ...\n            'Invalid TRIA input array.') ;\n    end\n\n%-------------------- impose gradient limits over mesh edges\n   [edge,tria] = tricon2(tria);\n\n    evec = vert(edge(:,2),:) - ...\n           vert(edge(:,1),:) ;\n    elen = sqrt(sum(evec.^2,2)) ;\n\n%-------------------- impose gradient limits over edge-graph\n   [hfun] = limgrad( ...\n         edge,elen,hfun,dhdx,sqrt(nvrt)) ;\n\nend\n\n\n\n", "meta": {"author": "dengwirda", "repo": "mesh2d", "sha": "749a81073facc8b5db02e4f7bb0b10c9783cebd3", "save_path": "github-repos/MATLAB/dengwirda-mesh2d", "path": "github-repos/MATLAB/dengwirda-mesh2d/mesh2d-749a81073facc8b5db02e4f7bb0b10c9783cebd3/hfun-util/limhfn2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5845592808783056}}
{"text": "function out = normalize_rows(in)\n    out = scale_rows(in,1./row_sum(in));\n% rowSums = sum(x,2);\n% [I,J] = size(x);\n% p = zeros(I,J);\n% for i=1:I\n%     p(i,:) = x(i,:) / rowSums(i);\n% end\n% \nend\n", "meta": {"author": "jacobeisenstein", "repo": "SAGE", "sha": "5776655f6c09f2c24a96485a0985660e64664415", "save_path": "github-repos/MATLAB/jacobeisenstein-SAGE", "path": "github-repos/MATLAB/jacobeisenstein-SAGE/SAGE-5776655f6c09f2c24a96485a0985660e64664415/utils/normalize_rows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5845592758090626}}
{"text": "function [j, dist] = LMhistintersectionquery(Query, h)\n%\n% Assumes histograms are normalized and sum = 1\n\nN = size(h,1);\n\ndist = 1-sum(min(h, repmat(Query, [N 1])),2); % histogram intersection\n[dist, j] = sort(dist);\n\n", "meta": {"author": "CSAILVision", "repo": "LabelMeToolbox", "sha": "b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2", "save_path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox", "path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox/LabelMeToolbox-b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2/features/LMhistintersectionquery.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5845592758090624}}
{"text": "%+========================================================================+\n%|                                                                        |\n%|            This script uses 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    \u00a0\u00a0\u00a0\u00a0         |\n%|                                                                        |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it.                                                      |\n%|________________________________________________________________________|\n%|   '&`   |                                                              |\n%|    #    |   FILE       : nrtMshSegment.m                               |\n%|    #    |   VERSION    : 0.50                                          |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |\n%|  ( # )  |   CREATION   : 14.03.2017                                    |\n%|  / 0 \\  |   LAST MODIF : 25.11.2018                                    |\n%| ( === ) |   SYNOPSIS   : Edge mesh of a segment                        |\n%|  `---'  |                                                              |\n%+========================================================================+\n\n% Cleaning\nclear all\nclose all\nclc\n\n% Gypsilab path\nrun('../../addpathGypsilab.m')\n\n% Create mesh\nNvtx = 21;\nL    = 4;\nmesh = mshSegment(Nvtx,L);\n\n% Colours\nctr = 1/2 .* (...\n        mesh.vtx(mesh.elt(:,1),:) + ...\n        mesh.vtx(mesh.elt(:,2),:) ) ;\nmesh.col(ctr(:,1)<0)               = 1;    \nmesh.col(ctr(:,1)>=0 & ctr(:,1)<1) = 2;\nmesh.col(ctr(:,1)>=1)              = 3;\n\n% Graphical representation\nfigure\nplot(mesh)\ncolorbar\n\n% Sub-meshing\nmesh1 = mesh.sub(mesh.col==1);\nmesh2 = mesh.sub(mesh.col==2);\nmesh3 = mesh.sub(mesh.col==3);\nnorm(mesh1.col-1,'inf')\nnorm(mesh2.col-2,'inf')\nnorm(mesh3.col-3,'inf')\n\n% Graphical representation\nfigure\nplot(mesh1)\nhold on\nplot(mesh2)\nplot(mesh3)\ncolorbar\n\n% Center\nXctr = mesh.ctr;\nhold on\nplot3(Xctr(:,1),Xctr(:,2),Xctr(:,3),'*y')\n\n% Normals\nplotNrm(mesh,'r')\n\n% Volume\nV = mesh.ndv;\nnorm(sum(V)-L)/L\n\n% Length\nl = mesh.stp;\n\n% Edges\nfigure\nplot(mesh.edg)\ncolorbar\n\n% Particles\nfigure\nplot(mesh.prt)\ncolorbar\n\n% Unicity\ntmp     = mesh;\ntmp.vtx = [tmp.vtx ; tmp.vtx];\ntmp.elt = [tmp.elt ; tmp.elt + size(mesh.vtx,1)];\ntmp.col = [tmp.col ; tmp.col];\n[~,I]   = unique(tmp);\nnorm(I-(1:size(mesh.elt,1))','inf')\n\n% Intersection\n[~,I] = intersect(mesh1,mesh);\nnorm(I-(1:size(mesh1.elt,1))','inf')\n\n% Union\n[tmp,I] = union(mesh,mesh1);\nnorm(I-(1:size(mesh.elt,1))','inf')\n\n% Difference\n[mesh4,~] = setdiff(mesh,mesh1);\nfigure\nplot(mesh4)\ncolorbar\n\n% Reconstruction\nmesh5 = union(mesh1,mesh2);\nmesh5 = union(mesh5,mesh3);\nsetdiff(mesh,mesh5)\n\n% Boundary\nbound = mesh5.bnd;\nfigure\nplot(bound)\ncolorbar\n\n% Clean degenerated mesh\nmesh6 = mesh;\nind   = (mesh6.vtx(:,1)>0);\nmesh6.vtx(ind,1) = 0;\nmesh6 = clean(mesh6,1e-6);\nsetdiff(mesh6,mesh1)\n\n% Clean degenerated particle mesh\nvtx = mesh.vtx;\nvtx(vtx(:,1)>0,1) = 0;\nmesh7 = msh(vtx);\nmesh7 = clean(mesh7,1e-6);\nsetdiff(mesh7,msh(mesh1.vtx))\n\n\n\ndisp('~~> Michto gypsilab !')\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/nonRegressionTest/meshManagement/nrtMshSegment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634457, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5845592727509745}}
{"text": "function mono_total_next_grlex_test ( )\n\n%*****************************************************************************80\n%\n%% MONO_TOTAL_NEXT_GRLEX_TEST tests MONO_TOTAL_NEXT_GRLEX.\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_TOTAL_NEXT_GRLEX_TEST\\n' );\n  fprintf ( 1, '  MONO_TOTAL_NEXT_GRLEX can list the monomials\\n' );\n  fprintf ( 1, '  in M variables, of total degree N,\\n' );\n  fprintf ( 1, '  one at a time, in graded lexicographic order.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  We start the process with (0,0,...,0,N).\\n' );\n  fprintf ( 1, '  The process ends with (N,0,...,0,0)\\n' );\n\n  n = 3;\n  m = 3;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Let M = %d\\n', m );\n  fprintf ( 1, '      N = %d\\n', n );\n  fprintf ( 1, '\\n' );\n\n  x = [ 0, 0, n ];\n  i = 1;\n\n  while ( 1 )\n\n    fprintf ( 1, '  %2d:', i );\n    for j = 1 : m\n      fprintf ( 1, '  %1d', x(j) );\n    end\n    fprintf ( 1, '\\n' );\n\n    if ( x(1) == n )\n      break\n    end\n\n    x = mono_total_next_grlex ( m, n, x );\n    i = i + 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/monomial/mono_total_next_grlex_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.5845392691851126}}
{"text": "function cost = perm_cost(p,c)\n\ncost = 0;\nfor q=1:length(p)\n    cost = cost + c(q,p(q));\nend\n\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/linprog/perm_cost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998405389917, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5845392493467105}}
{"text": "function [ dist ] = euclidean_dist( X_gallery, X_probe, model_para )\n    dist=pdist2(X_probe,X_gallery,'euclidean');\nend\n\n", "meta": {"author": "wuancong", "repo": "SYSU-MM01", "sha": "b1f8f3691f59da47bd481b9343aeaf6a03675dfe", "save_path": "github-repos/MATLAB/wuancong-SYSU-MM01", "path": "github-repos/MATLAB/wuancong-SYSU-MM01/SYSU-MM01-b1f8f3691f59da47bd481b9343aeaf6a03675dfe/evaluation/euclidean_dist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5845171829142722}}
{"text": "function ov = regionOverlap(region1, region2, area)\n% compute intersection over union of two regions\n% ov = regionOverlap(region1, region2, area)\n\narea = area(:);\nr1 = false(numel(area), 1);\nr2 = false(numel(area), 1);\nr1(region1) = true;\nr2(region2) = true;\nov = sum(area(r1 & r2)) / sum(area(r1 | r2));\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/iccv07Final/src/occlusion/regionOverlap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545425, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5845171773910698}}
{"text": "function [data_out]=ofdmsymbol_fft_cp(data_in,G,TxRx)\n\n% We can make Nfft as a parameter as well\n Nfft = 256;\n\n if TxRx==10\n      data=data_in'; %this makes the input column vector to a array\n\n% %% making odfm symbol and taking IFFT\n% function  symbol_ofdm = createsymbol (pilots,data)\n\n%% now first generate the pilot\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nA=complex(-1,0);\nB=complex(1,0);\npilots = [A B A B B B A A];  %%% here we direct making the pilot,detail procedure given below\n\n% n_symbol = 1;  % At the time of generating the pilots, I need to know what symbol i am simulating \n%                % because the seed to do it depends on it.\n% % The values of the pilots are to be modulated are defined in the standard as such(pp 443) :\n% % Before beginning, it is necessary to consider that the value to calculate depends on 2 factors : \n% % the number of symbols and whether we are in the uplink or dwnlink. We will consider that we are in\n% % the downlink and we are transmitting the symbol \"1\". \n% % If we want to consider the other uplink connection, the seed would be \"10101010101\".\n% % \n% seed = [1 1 1 1 1 1 1 1 1 1 1];\n% for i=1:n_symbol+2                         \n%     wk(i) = seed (11);                 \n%     next = xor(seed(9),seed(11));\n%     seed = [next seed(1,1:10)];\n% end\n% \n% % Once the value of wk is found(that depends on the number of symbol with wihich it is working),\n% % the values of the subcarriers must be found and of the mapping of them with BPSK constellation.\n% \n% wk = wk(n_symbol+2)\n% A = 1 - 2*wk                           % Values defined in the standard.\n% B = 1 - 2*(~wk)\n% value_carrier = [A B A B B B A A]\n% \n% % For uplink, the values should be [A B A B A A A A]\n% \n% pilot_mapping = 2*mapping(value_carrier,1,Tx);      \n% \n% % The factor of \"2\" is due to the fact that the pilots are transmitted to a\n% % double power of the information bits.\n\n% NOW The guard bands are prepared.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nguard1 = complex (0,0) * ones (1,28);\nDC = complex (0,0);\nguard2 = complex (0,0) * ones (1,27);\n\n% The pilot and guard subcarriers are placed according to the standard.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nsymbol_ofdm = [guard1 data(1:12) pilots(1) data(13:36)...\n    pilots(2) data(37:60) pilots(3) data(61:84) pilots(4)...\n    data(85:96) DC data(97:108) pilots(5) data(109:132) pilots(6)...\n    data(133:156) pilots(7) data(157:180) pilots(8) data(181:192) guard2];\n\n% here the ofdm symbol is completed\n%Now taking IFFT\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n symbol_ofdm = sqrt(Nfft).*ifft(symbol_ofdm,Nfft);\n\n %Now adding cyclic prefix%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% we generate the cyclic prefix so that the multipaths do not affect our data so much.\nmargin = length(symbol_ofdm)*G;\ndata_tx = [symbol_ofdm((end-margin+1):end) symbol_ofdm];\ndata_out=data_tx;      \n\n   % At receiving end\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelseif TxRx==01\n       \ndata_rx=data_in;\n% First, we must remove the CP.\nmargin = length(data_rx)*G;\nmargin = margin/(1+G);\nsymbol_ofdm_rx= data_rx(margin+1:end);\n   \n% After removing the CP, we have to inverse the IFFT, logcally by FFT. \n\n symbol_rx = fft(symbol_ofdm_rx,Nfft) ./ sqrt(Nfft);\n  \n % Here the pilots are indicated, since i need to know where they are.\n % now we will be able to estimate the channel.\n\n pilots = [symbol_rx(41) symbol_rx(66) symbol_rx(91) symbol_rx(116) symbol_rx(142) symbol_rx(167) symbol_rx(192) symbol_rx(217)];\n      \n% After getting the received symbol, the channel is to be estimated using\n% the pilot carriers. This is bypassed for an AWGN channel.\n \n% Next, the values of the data and pilot carriers are extracted\n data_total = [symbol_rx(29:40) symbol_rx(42:65) symbol_rx(67:90) symbol_rx(92:115) symbol_rx(117:128)...\n           symbol_rx(130:141) symbol_rx(143:166) symbol_rx(168:191) symbol_rx(193:216) symbol_rx(218:229)];\n data_out=data_total'; %this makes it a column vector \nelse\n      disp('error in ofdmsymbol_fft_cp.m function');\nend\n        \n  \n\n       \n \n\n  \n\n \n \n \n \n \n \n \n ", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24369-wimax-physical-layer-simulation/wimax phy layer simulation code/ofdmsymbol_fft_cp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5845133140370401}}
{"text": "% MAP_PROJECTION - Set the projection\n%\n% 'GLOBAL-ELLIPSE'\n% 'GLOBAL-RECT'\n% 'TESTBED'\n\nfunction map_projection(projection)\n\nif nargin < 1\n  projection = 'global-ellipse';\nend\n\nswitch lower(projection)\n case 'global-ellipse'\n  m_proj('mollweide', 'clongitude', 0); % straight latitudes (equal area)\n  %m_proj('hammer-aitoff', 'clon', 0); % curved latitudes (equal area)\n case 'global-rect'\n  m_proj('miller');\n case 'testbed'\n  m_proj('Mercator', 'lon',[22.5,26.8], 'lat',[59.74,61.0])\n otherwise\n  error('Unknown projection')\nend\n\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/plotting/map_projection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5845089438840271}}
{"text": "function [PV,DV] = VariableClustering(Problem,Population,nSel,nPer)\n% Detect the kind of each decision variable\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    [N,D] = size(Population.decs);\n    ND    = NDSort(Population.objs,1) == 1;\n    fmin  = min(Population(ND).objs,[],1);\n    fmax  = max(Population(ND).objs,[],1);\n    if any(fmax==fmin)\n        fmax = ones(size(fmax));\n        fmin = zeros(size(fmin));\n    end\n    \n    %% Calculate the proper values of each decision variable\n    Angle  = zeros(D,nSel);\n    RMSE   = zeros(D,nSel);\n    Sample = randi(N,1,nSel);\n    for i = 1 : D\n        drawnow('limitrate');\n        % Generate several random solutions by perturbing the i-th dimension\n        Decs      = repmat(Population(Sample).decs,nPer,1);\n        Decs(:,i) = unifrnd(Problem.lower(i),Problem.upper(i),size(Decs,1),1);\n        newPopu   = Problem.Evaluation(Decs);\n        for j = 1 : nSel\n            % Normalize the objective values of the current perturbed solutions\n            Points = newPopu(j:nSel:end).objs;\n            Points = (Points-repmat(fmin,size(Points,1),1))./repmat(fmax-fmin,size(Points,1),1);\n            Points = Points - repmat(mean(Points,1),nPer,1);\n            % Calculate the direction vector of the determining line\n            [~,~,V] = svd(Points);\n            Vector  = V(:,1)'./norm(V(:,1)');\n            % Calculate the root mean square error\n            error = zeros(1,nPer);\n            for k = 1 : nPer\n                error(k) = norm(Points(k,:)-sum(Points(k,:).*Vector)*Vector);\n            end\n            RMSE(i,j) = sqrt(sum(error.^2));\n            % Calculate the angle between the line and the hyperplane\n            normal     = ones(1,size(Vector,2));\n            sine       = abs(sum(Vector.*normal,2))./norm(Vector)./norm(normal);\n            Angle(i,j) = real(asin(sine)/pi*180);\n        end\n    end\n    \n    %% Detect the kind of each decision variable\n    VariableKind = (mean(RMSE,2)<1e-2)';\n    result       = kmeans(Angle,2)';\n    if any(result(VariableKind)==1) && any(result(VariableKind)==2)\n        if mean(mean(Angle(result==1&VariableKind,:))) > mean(mean(Angle(result==2&VariableKind,:)))\n            VariableKind = VariableKind & result==1;\n        else\n            VariableKind = VariableKind & result==2;\n        end\n    end\n    PV = find(~VariableKind);\n    DV = find(VariableKind);\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/LMEA/VariableClustering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5845089334060798}}
{"text": "function [distance_matrix, gram_matrix]= update_distance_matrix(distance_matrix, gram_matrix, gram_vector, new_sample_norm, id1, id2, w1, w2)\n% Updates the distance matrix\n\n% Normalise the weights so that they sum to one\nalpha1 = w1/(w1+w2);\nalpha2 = 1 - alpha1;\n\n\nif id2 < 0\n    norm_id1 = gram_matrix(id1, id1);\n    \n    % Update the gram matrix\n    if alpha1 == 0\n        % The new sample replaces an existing sample.\n        gram_matrix(:,id1) = gram_vector;\n        gram_matrix(id1,:) = gram_matrix(:,id1);\n        gram_matrix(id1, id1) = new_sample_norm;\n    elseif alpha2 == 0\n        % The new sample is discared \n    else\n        % The new sample is merge with an existing sample\n        gram_matrix(:,id1) = alpha1*gram_matrix(:,id1) + alpha2*gram_vector;\n        gram_matrix(id1,:) = gram_matrix(:,id1);\n        gram_matrix(id1, id1) = alpha1^2*norm_id1 + alpha2^2*new_sample_norm + 2*alpha1*alpha2*gram_vector(id1);\n    end\n    \n    % Update distance matrix\n    distance_matrix(:,id1) = max(gram_matrix(id1, id1) + diag(gram_matrix) - 2*gram_matrix(:,id1),0);\n    distance_matrix(id1,:) = distance_matrix(:,id1) ;\n    distance_matrix(id1,id1) = inf;\nelse\n    if alpha1 == 0 || alpha2 == 0\n        error('Error!');\n    end\n    \n    % Two existing samples are merged and the new sample fills the empty\n    % slot\n    norm_id1 = gram_matrix(id1, id1);\n    norm_id2 = gram_matrix(id2, id2);\n    ip_id1_id2 = gram_matrix(id1,id2);\n    \n    % Handle the merge of existing samples\n    gram_matrix(:,id1) = alpha1*gram_matrix(:,id1) + alpha2*gram_matrix(:,id2);\n    gram_matrix(id1,:) = gram_matrix(:,id1);\n    gram_matrix(id1, id1) = alpha1^2*norm_id1 + alpha2^2*norm_id2 + 2*alpha1*alpha2*ip_id1_id2;\n    \n    gram_vector(id1) = alpha1*gram_vector(id1) + alpha2*gram_vector(id2);\n    \n    % Handle the new sample\n    gram_matrix(:,id2) = gram_vector;\n    gram_matrix(id2,:) = gram_matrix(:,id2);\n    gram_matrix(id2, id2) = new_sample_norm;\n    \n    % Update the distance matrix\n    distance_matrix(:,id1) = max(gram_matrix(id1, id1) + diag(gram_matrix) - 2*gram_matrix(:,id1),0);\n    distance_matrix(id1,:) = distance_matrix(:,id1) ;\n    distance_matrix(id1,id1) = inf;\n    \n    distance_matrix(:,id2) = max(gram_matrix(id2, id2) + diag(gram_matrix) - 2*gram_matrix(:,id2),0);\n    distance_matrix(id2,:) = distance_matrix(:,id2) ;\n    distance_matrix(id2,id2) = inf;\nend\n\n\n", "meta": {"author": "martin-danelljan", "repo": "ECO", "sha": "27e8ae565cd63ec14bafcaad8b5b993bec8f3e69", "save_path": "github-repos/MATLAB/martin-danelljan-ECO", "path": "github-repos/MATLAB/martin-danelljan-ECO/ECO-27e8ae565cd63ec14bafcaad8b5b993bec8f3e69/implementation/sample_space_model/update_distance_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5844198673713542}}
{"text": "function figure_num = cube3d_grid_plot ( x1, x2, x3, filename, figure_num )\n\n%*****************************************************************************80\n%\n%% CUBE3D_GRID_PLOT plots hypersphere gridpoints onto the surface of a 3D cube. \n%\n%  Discussion:\n%\n%    The X1, X2, X3 data has, presumably, been computed by CUBE_GRID for\n%    a 3D cube.\n%\n%    This function plots the surface, and then the surface plus the \n%    projected grid points.\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, real X1(2*N+1,N+1), X2(2*N+1,N+1), X3(2*N+1,N+1), the coordinates \n%    of points on the cube surface, projected from the hypersphere.\n%\n%    Input, string FILENAME, the \"first name\" of the two files to be created:\n%    filename_surface.png and filename_points.png.\n%\n%    Input/output, int FIGURE_NUM, the current figure index.\n%\n  if ( nargin < 4 )\n    filename = 'cube';\n  end\n%\n%  Draw the surface.\n%\n  figure_num = figure_num + 1;\n  figure ( figure_num )\n  mesh ( x3, x2, x1, 'FaceColor', 'interp' );\n  axis equal\n  grid on\n  xlabel ( '<---X--->', 'FontSize', 16 );\n  ylabel ( '<---Y--->', 'FontSize', 16 );\n  zlabel ( '<---Z--->', 'FontSize', 16 );\n  title ( 'Cube transition surface', 'FontSize', 24 )\n  hold off\n  filename1 = sprintf ( '%s_surface.png', filename );\n  print ( '-dpng', filename1 );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Created plotfile \"%s\".\\n', filename1 );\n%\n%  Draw the surface and points.\n%\n%  Listing the points in the order X1, X2, X3, rational as it may seem,\n%  is apparently NOT the way to go here.\n%\n  figure_num = figure_num + 1;\n  figure ( figure_num )\n  hold on\n  mesh ( x3, x2, x1, 'FaceColor', 'interp' );\n  plot3 ( x3, x2, x1, 'k.', 'MarkerSize', 5 );\n  axis equal\n  grid on\n  xlabel ( '<---X--->', 'FontSize', 16 );\n  ylabel ( '<---Y--->', 'FontSize', 16 );\n  zlabel ( '<---Z--->', 'FontSize', 16 );\n  title ( 'Grid points on transition surface', 'FontSize', 24 )\n  hold off\n  filename2 = sprintf ( '%s_points.png', filename );\n  print ( '-dpng', filename2 );\n  fprintf ( 1, '  Created plotfile \"%s\".\\n', filename2 );\n\n  return\nend\n", "meta": {"author": "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/cube3d_grid_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.8397339616560073, "lm_q1q2_score": 0.5844198308367908}}
{"text": "function [F,feasible] = filter_norm_2(all_f,all_c_w,all_c_x,all_Q_xw,x,Zmodel,allw,X,Q_xx,VariableType)\n\nfeasible = 1;\n% As a first step, we figure out the radius\nr = Zmodel.r;\ncenter = Zmodel.center;\nF = ([]);\nci_basis = all_c_w';\nlastBici = [];\nlastusedrows = [];\n% (bi' + (Bi*w)')*x + (ci'*w + di).\nfor i = 1:length(all_f)\n    Bi = 2*all_Q_xw(:,length(x)*(i-1)+1:length(x)*i)';\n    bi = all_c_x(length(x)*(i-1)+1:length(x)*i);\n    if (nnz(ci_basis(:,i))==0) & nnz(Bi)==0\n        F = F + (X(i)>=0);\n        % This constraint row is constant\n    else\n        ci = ci_basis(:,i);\n        di = all_f(i);\n        used = find(full(any([full(Bi') ci],2)));\n        %        ci = ci(used);\n        %        Bi = Bi(:,used);\n        % Shift |w-center|, wtilde = w-center i.e. w=wtilde+center\n        di = di + ci'*center;\n        bi = bi + Bi*center;\n        if isequal(abs(lastBici),abs([Bi' ci]))            \n             F = F + (x'*Q_xx{i}*x+bi'*x + di - r*s >= 0);            \n      %       F = F + (x'*Q_xx{i}*x+bi'*x + di - r*norm(full(Bi(used_rows,used)))*s >= 0);            \n        else\n            s = sdpvar(1,1);\n            if length(used)==1\n                if nnz(Bi(:,used))==0\n                    s = norm(full(ci(used)));\n                    F = F + (x'*Q_xx{i}*x+bi'*x + di - r*s >= 0);\n                else\n                    F = F + (x'*Q_xx{i}*x+bi'*x + di - r*s >= 0) + (-s<=Bi(:,used)'*x+ci(used)<=s);                   \n                end\n                used_rows = 1:size(Bi,1);\n                lastBici = [Bi' ci];\n            else\n                used_rows = find(any(full(Bi(:,used)')));\n                if length(used_rows)==1 & nnz(ci(used))==0\n                    % Special case norm(double vector*scalar)\n                    if isequal(used_rows,lastusedrows)\n                        F = F + (x'*Q_xx{i}*x+bi'*x + di - r*norm(full(Bi(used_rows,used)))*lasts >= 0)  ;\n                    else\n                        F = F + (x'*Q_xx{i}*x+bi'*x + di - r*norm(full(Bi(used_rows,used)))*s >= 0) + (-s <= x(used_rows)<=s);\n                        lastBici = [Bi' ci];\n                        lastusedrows = used_rows;\n                        lasts = s;\n                    end\n                else\n                    if nnz(Bi)==0\n                        s = norm(full(ci(used)));\n                        F = F + (x'*Q_xx{i}*x+bi'*x + di - r*s >= 0) ;\n                    else\n                        F = F + (x'*Q_xx{i}*x+bi'*x + di - r*s >= 0) + (cone(Bi(:,used)'*x+ci(used),s));\n                    end\n                    lastBici = [Bi' ci];\n                end\n            end\n        end\n    end\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/robust/filter_norm_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5843965656724871}}
{"text": "function Y = lp_fuse(M1, M2, zt, ap, mp)\n%Y = fuse_lap(M1, M2, zt, ap, mp) image fusion with laplacian pyramid\n%\n%    M1 - input image A\n%    M2 - input image B\n%    zt - maximum decomposition level\n%    ap - coefficient selection highpass (see selc.m) \n%    mp - coefficient selection base image (see selb.m) \n%\n%    Y  - fused image   \n\n%    (Oliver Rockinger 16.08.99)\n% whos\n% check inputs \n[z1 s1] = size(M1);\n[z2 s2] = size(M2);\nM1=double(M1);\nM2=double(M2);\nif (z1 ~= z2) | (s1 ~= s2)\n  error('Input images are not of same size');\nend;\n\n% define filter \nw  = [1 4 6 4 1] / 16;\n\n% cells for selected images\nE = cell(1,zt);\n% tic\n% loop over decomposition depth -> analysis\nfor i1 = 1:zt \n    tic\n  % calculate and store actual image size \n  [z s]  = size(M1); \n  zl(i1) = z; sl(i1)  = s;\n  \n  % check if image expansion necessary \n  if (floor(z/2) ~= z/2), ew(1) = 1; else, ew(1) = 0; end;\n  if (floor(s/2) ~= s/2), ew(2) = 1; else, ew(2) = 0; end;\n\n  % perform expansion if necessary\n  if (any(ew))\n  \tM1 = adb(M1,ew);\n  \tM2 = adb(M2,ew);\n  end;\t\n\n  % perform filtering \n  G1 = conv2(conv2(es2(M1,2), w, 'valid'),w', 'valid');\n  G2 = conv2(conv2(es2(M2,2), w, 'valid'),w', 'valid');\n \n  % decimate, undecimate and interpolate \n  M1T = conv2(conv2(es2(undec2(dec2(G1)), 2), 2*w, 'valid'),2*w', 'valid');\n  M2T = conv2(conv2(es2(undec2(dec2(G2)), 2), 2*w, 'valid'),2*w', 'valid');\n%   toc76\n\n% tic\n  % select coefficients and store them\n  E(i1) = {selc(M1-M1T, M2-M2T, ap)};\n% toc\n  % decimate \n%  tic\n  M1 = dec2(G1);\n  M2 = dec2(G2);\n%   toc\n% toc\n% feature ('memstats')\n\nend;\n% toc\n% select base coefficients of last decompostion stage\n% tic\nM1 = selb(M1,M2,mp);\n% toc\n% whos\n% feature ('memstats')\n% toc\n% loop over decomposition depth -> synthesis\n% tic\nfor i1 = zt:-1:1\n  % undecimate and interpolate \n%   tic\n  M1T = conv2(conv2(es2(undec2(M1), 2), 2*w, 'valid'), 2*w', 'valid');\n  % add coefficients\n  M1  = M1T + E{i1};\n%   toc\n  % select valid image region \n  M1 \t= M1(1:zl(i1),1:sl(i1));\n%   feature ('memstats')\n% whos\nend;\n\n% feature ('memstats')\n% copy image\nY = M1;\n% toc\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/lp_fuse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5843965598901341}}
{"text": "function [data g] = pre_detrend(varargin)\n%\n% Detrend each channel and trial using a least-squares linear fit.\n% Alternately, one can center the data by removing the mean from each\n% trial. See [1] for more details.\n%\n% Inputs:\n%\n%   data:           raw EEG data\n%   SamplingRate:   data sampling rate\n%\n% Optional:     <'Name',Value> pairs\n%\n%     VerbosityLevel:   Verbosity level. 0 = no output, 1 = text, 2 = graphical\n%                       Possible values: 0,1,2\n%                       Default value  : 1\n%                       Input Data Type: real number (double)\n%\n%     DetrendingMethod: Detrending options\n%                       Linear: removes the least-squares fit of a straight line from each trial.\n%                       Constant: removes the mean from each trial (centering)\n%                       Possible values: 'linear','constant'\n%                       Default value  : 'linear'\n%                       Input Data Type: boolean\n% Outputs:\n%\n%   data:       processed EEG data\n%   g:          argument specification structure\n%\n% See Also: pop_pre_prepData(), pre_prepData(), detrend()\n%\n% Refences:\n%\n% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):\n%   Theoretical Handbook and User Manual. Section 6.5.1\n%   Available at: http://www.sccn.ucsd.edu/wiki/Sift\n%\n% Author: Tim Mullen 2010, SCCN/INC, UCSD.\n% Email:  tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nSegLenRange = [eps 10];\nStepSizeRange = [eps 10];\n\ng = arg_define(varargin, ...\n    arg_norep('data',mandatory,[],'Raw data. This should be [num_chans x num_time x num_trials]'), ...\n    arg_norep({'srate','SamplingRate'},mandatory,[],'Sampling Rate'), ...\n    arg({'verb','VerbosityLevel'},1,{int32(0) int32(1) int32(2)}, ...\n    'Verbosity level. 0 = no output, 1 = text, 2 = graphical'), ...\n    arg({'method','DetrendingMethod'},{'linear'},{'linear','constant'}, ...\n    'Detrending options. Linear: removes the least-squares fit of a straight line from each trial. Constant: removes the mean from each trial (centering)','type','logical'), ...\n    arg_subtoggle({'piecewise','Piecewise'},[], ...\n    { ...\n    arg({'seglength','SegmentLength'},0.33,SegLenRange,'Length of each detrending segment (sec).'), ...\n    arg({'stepsize','StepSize'},0.0825,StepSizeRange,'Step size between segment centers (sec). It is recommended to use at least 0.5*SegmentLength (50% overlap).'), ...\n    },'Use piecewise detrending. Divide the data into (overlapping) segments and detrend each segment separately. Segment endpoints are merged and stitched together using a cubic spline function to minimize discontinuities at segment intersection points. This is useful for as an alternative to high-pass filtering for removing infraslow oscillations (e.g. SC drift) from the '), ...\n    arg({'plot','Plot'},false,[],'Plot results for inspection.') ...\n    );\n\n% commit data to workspace\ndata = g.data;\ng=rmfield(g,'data');\n\n[nbchan pnts trials] = size(data);\n\n% set sliding-window parameters\nif ~g.piecewise.arg_selection\n    % global detrending\n    g.piecewise.seglength = pnts/g.srate;\n    g.piecewise.stepsize = g.piecewise.seglength;\nend\nwindowing_params = [g.piecewise.seglength g.piecewise.stepsize];\n\n% apply each detrending method (centering,linear detrending, ...)\nfor i=1:length(g.method)\n    \n    % initialize verbose output\n    m = g.method{i};\n    if g.verb && g.piecewise.arg_selection,\n        pre = 'Piecewise ';\n        post = sprintf(' (using %0.4f sec segment length)',g.piecewise.seglength);\n    else\n        pre = '';\n        post = '';\n    end\n    if g.verb && strcmpi(m,'mean')\n        fprintf('%sCentering data%s...\\n',pre,post);    end\n    if g.verb && strcmpi(m,'linear')\n        fprintf('%sDetrending data%s...\\n',pre,post);   end\n    \n    if g.verb==2\n        multiWaitbar('Detrending','Reset','Color',hlp_getNextUniqueColor);\n    end\nend\n\n% variable intialization\nfitlines = zeros(size(data));\n\n% apply the detrending/centering\nfor ch=1:nbchan\n    \n    if g.verb==2\n        multiWaitbar('Detrending',ch/nbchan);\n    end\n    \n    if g.plot\n        % return detrended data as well as fitted curves\n        [data(ch,:,:) fitlines(ch,:,:)] = locdetrend_siftmod(squeeze(data(ch,:,:)),g.srate,windowing_params,m);\n    else\n        % return only detrended data (faster)\n        data(ch,:,:) = locdetrend_siftmod(squeeze(data(ch,:,:)),g.srate,windowing_params,m);\n    end\n    \nend\n\nif g.verb==2\n    multiWaitbar('Detrending','Close');\nend\n\n% plot results, if requested\nif g.plot\n    eegplot(data+fitlines,'srate',g.srate,'data2',fitlines,'title','Original Data');\n    h = gcf;\n    ax = findobj(gcf,'tag','eegaxis');\n    plts = get(ax,'children');\n    legend([plts(end) plts(1)],'original','best local-linear fit');\n    eegplot(data,'srate',g.srate,'title','Detrended Data','children',h);\n    ax = findobj(gcf,'tag','eegaxis');\n    plts = get(ax,'children');\n    legend(plts(end),'detrended data');\nend\n\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/pre/pre_detrend.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5843965595774024}}
{"text": "%% MATLAB code for blur-downsampled (BDx4) degradataion\nscale = 4;\nsigma = 1.6;\n\n% generate LR image\nkernelsize = ceil(sigma * 3) * 2 + 2;\nkernel = fspecial('gaussian', kernelsize, sigma);\nlq = imfilter(gt, kernel, 'replicate');\nlq = lq(scale/2:scale:end-scale/2, scale/2:scale:end-scale/2, :);", "meta": {"author": "ckkelvinchan", "repo": "BasicVSR-IconVSR", "sha": "15dda03d77127ca54f08c53e30aff42b61c0a0fb", "save_path": "github-repos/MATLAB/ckkelvinchan-BasicVSR-IconVSR", "path": "github-repos/MATLAB/ckkelvinchan-BasicVSR-IconVSR/BasicVSR-IconVSR-15dda03d77127ca54f08c53e30aff42b61c0a0fb/BD_degradation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.584350056097242}}
{"text": "% Copyright 2018 Marc Ren\u00e9 Sch\u00e4dler\n%\n% This file is part of the mobile hearing aid prototype project\n% The the mobile hearing aid prototype project is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n%\n% The mobile hearing aid prototype project is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License along with the mobile hearing aid prototype project. If not, see http://www.gnu.org/licenses/.\n\nfunction [gt_data, gt_freqs, gt_levels] = prescription_minimalistic(freqs, thresholds_left, thresholds_right, offset, marginfactor, rolloff, center, focus)\n  gt_freqs = [177 297 500 841 1414 2378 4000 6727 11314];\n  gt_levels = -10:1:110;\n  reference_freqs  = [125 250 500 1000 2000 4000 8000 16000];\n  reference_levels = abs(polyval([focus 0],log2(reference_freqs./1000)))+offset;\n  thresholds_left_ext = [0 0 thresholds_left 0 0];\n  thresholds_right_ext = [0 0 thresholds_right 0 0];\n  freqs_ext = [0 50 freqs 16000 48000];\n  gt_data_left = zeros(length(gt_levels),length(gt_freqs));\n  gt_data_right = zeros(length(gt_levels),length(gt_freqs));\n  maxgain = 40;\n  maxlevel = 110;\n  for i=1:length(gt_freqs)\n    reference_level = interp1(reference_freqs,reference_levels,gt_freqs(i),'extrap');\n    threshold_level_left = interp1(freqs_ext,thresholds_left_ext,gt_freqs(i),'extrap');\n    threshold_level_right = interp1(freqs_ext,thresholds_right_ext,gt_freqs(i),'extrap');\n    low_level_gain_left = max(0,threshold_level_left-reference_level);\n    low_level_gain_right = max(0,threshold_level_right-reference_level);\n    margin_left = marginfactor.*(center-(reference_level+low_level_gain_left));\n    margin_right = marginfactor.*(center-(reference_level+low_level_gain_right));\n    gt_data_left(:,i) = interp1([gt_levels(1);reference_level+margin_left;reference_level+margin_left+low_level_gain_left.*rolloff;gt_levels(end)],[low_level_gain_left;low_level_gain_left;0;0],gt_levels);\n    gt_data_right(:,i) = interp1([gt_levels(1);reference_level+margin_right;reference_level+margin_right+low_level_gain_right.*rolloff;gt_levels(end)],[low_level_gain_right;low_level_gain_right;0;0],gt_levels);\n  end\n  gt_data = [gt_data_left.';gt_data_right.'];\n  gt_data = min(maxgain,gt_data);\n  gt_data = gt_data + min(0,maxlevel - (gt_data+gt_levels));\nend\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/prescription_minimalistic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.584350028492889}}
{"text": "function [uout, tout] = spinsphere(varargin)\n%SPINSPHERE  Solve stiff PDEs on the sphere, double Fourier sphere method and \n%implicit-explicit schemes.\n%\n%   UOUT = SPINSPHERE(PDECHAR) solves the PDE specified by the string PDECHAR,\n%   and plays a movie of the solution. Possible strings include 'AC' and 'GL'\n%   for the Allen-Cahn and Ginzburg-Landau equations. Other PDEs are available, \n%   see Remark 1 and Examples 1-4. The output UOUT is a SPHEREFUN corresponding\n%   to the solution at the final time (a CHEBMATRIX for systems of equations, \n%   each row representing one variable).\n%\n%   UOUT = SPINSPHERE(S, N, DT) solves the PDE specified by the SPINOPSPHERE S \n%   with N grid points in each direction (longitude/latitude) and time-step DT, \n%   and plays a movie of the solution. See HELP/SPINOPSPHERE and Example 5.\n%\n%   UOUT = SPINSPHERE(S, N, DT, PREF) allows one to use the preferences \n%   specified by the SPINPREFSPHERE object PREF. See HELP/SPINPREFSPHERE and \n%   Example 6.\n%\n%   [UOUT, TOUT] = SPINSPHERE(...) also returns the times chunks TOUT at which \n%   UOUT was computed.\n%\n%   Users of SPINSPHERE will quickly find they want to vary aspects of the \n%   plotting. The fully general syntax for this involves using preferences \n%   specified by a SPINPREFSPHERE object PREF. See HELP/SPINPREFSPHERE and \n%   Example 6. However for many purposes it is most convenient to use the syntax\n%\n%   UOUT = SPINSPHERE(..., 'PREF1', VALUE1, 'PREF2', VALUE2, ...)\n%\n%   For example:\n%\n%   UOUT = SPINSPHERE(..., 'Clim', [a b]) changes colorbar limits to [a b] \n%   UOUT = SPINSPHERE(..., 'colormap', 'jet') changes the colormap to 'jet'\n%   UOUT = SPINSPHERE(..., 'dataplot', 'abs') plots absolute value\n%   UOUT = SPINSPHERE(..., 'grid', 'on') for lagitude/longitude circles\n%   UOUT = SPINSPHERE(..., 'iterplot', 4) plots only every 4th time step \n%   UOUT = SPINSPHERE(..., 'Nplot', 256) plays a movie at 256x256 resolution\n%   UOUT = SPINSPHERE(..., 'plot', 'off') for no movie\n%   UOUT = SPINSPHERE(..., 'view', [a b]) changes the view angle to [a b]\n%\n% Remark 1: List of PDEs (case-insensitive)\n%\n%    - 'AC' for the Allen-Cahn equation,\n%    - 'GL' for the Ginzburg-Landau equation,\n%    - 'GM' for the Gierer-Meinhardt equations,\n%    - 'NLS' for the focusing nonlinear Schroedinger equation.\n%\n% Example 1: Allen-Cahn equation (metastable solutions)\n%\n%        u = spinsphere('AC');\n%\n%    solves the Allen-Cahn equation\n%\n%        u_t = 1e-2*laplacian(u) + u - u^3\n%\n%    on the sphere from t=0 to t=60, with initial condition\n%\n%        u0(x, y, z) = cos(cosh(5*x*z) - 10*y).\n%\n% Example 2: Ginzburg-Landau equation (spiral waves)\n%\n%        u = spinsphere('GL');\n%\n%    solves the Ginzburg-Landau equation\n%\n%        u_t = 1e-3*laplacian(u) + u - (1+1.5i)*u*|u|^2,\n%\n%    on the sphere from t=0 to t=100 with a RANDNFUNSPHERE initial condition.   \n%    The movie shows the real part of u.\n%\n% Example 3: Gierer-Meinhardt equations (pattern formation - spots)\n%\n%        u = spinsphere('GM);\n%\n%    solves the Gierer-Meinhardt equations,\n%\n%       u_t = 1e-2*laplacian(u) + u^2/v - u,\n%       v_t = 1e-1*laplacian(v) + u^2 - v,\n%\n%    on the sphere from t=0 to t=80, with initial condition\n%\n%       u0(x,y,z) = 1 + .1*(cos(20*x) + cos(20*y) + cos(20*z)),\n%       v0(x,y,z) = 1 - .1*(cos(20*x) + cos(20*y) + cos(20*z)).\n%\n% Example 4: Nonlinear Schroedinger equation (spherical harmonic & breather)\n%\n%        u = spinsphere('NLS');\n%\n%    solves the focusing nonlinear Schroedinger equation\n%\n%        u_t = 1i*laplacian(u) + 1i*u|u|^2,\n%\n%    on the sphere from t=0 to t=3, with initial condition\n%\n%     u0(lam, th) = .1*(2*B^2./(2 - sqrt(2)*sqrt(2-B^2)*cos(A*B*th)) - 1)*A \n%                  + Y_8^6(lam, th), with A=1 and B=1.\n%\n%    The movie shows the absolute value of u.\n%\n% Example 5: PDE specified by a SPINOPSPHERE\n%\n%       tspan = [0 100];\n%       S = spinopsphere(tspan);\n%       S.lin = @(u) 1e-3*lap(u);\n%       S.nonlin = @(u) u - (1 + 1.5i)*u.*(abs(u).^2);\n%       S.init = randnfunsphere(.1);\n%       S.init = S.init/norm(S.init, inf);\n%       u = spinsphere(S, 128, 1e-1);\n%\n%   is equivalent to u = spinsphere('GL');\n%\n% Example 6: Using preferences\n%\n%       pref = spinprefsphere('Clim', [-1 1]);\n%       S = spinopsphere('AC');\n%       u = spinsphere(S, 128, 1e-1, pref);\n%   or simply,\n%       u = spinsphere(S, 128, 1e-1, 'Clim', [-1 1]);\n%\n%   solves the Allen-Cahn equation using N=128 grid points in each direction\n%   and a time-step dt=1e-1, and sets the limits of the colorbar to [-1 1].\n%\n% See also SPINOPSPHERE, SPINPREFSPHERE, IMEX.\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 SPINOPSPHERE object, N is the number of grid points in each \n% direction, DT is the time-step and PREF is a SPINPREFSPHERE object.\n\n% CASE 1. U = SPINSPHERE('GL'):\nif ( nargin == 1 ) \n    \n    try spinopsphere(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 = SPINSPHERE('GL', 'PREF1', VALUE1) or U = SPINSPHERE(S, N, DT):\nelseif ( nargin == 3 ) \n    \n    % CASE 2.1. U = SPINSPHERE('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 = SPINSPHERE(S, N, DT):\n    else\n        % Nothing to do here.\n    end\n    \n% CASE 3. U = SPINSPHERE(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 = SPINSPHERE('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 = SPINSPHERE(S, N, DT, 'PREF1', VALUE1, 'PREF2', VALUE2, ...)\n    else\n        pref = spinprefsphere();\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% SPINSPHERE 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 = spinprefsphere();\nS = spinopsphere(pdechar);\nif ( strcmpi(pdechar, 'AC') == 1 )\n    dt = 1e-1;\n    N = 128;\n    pref.Clim = [-1 1];\n    pref.iterplot = 2;\n    pref.Nplot = 256;\nelseif ( 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, 'GM') == 1 )\n    dt = 2e-1;\n    N = 64;\n    pref.Clim = [0 3 0.5 2];\n    pref.iterplot = 4;\n    pref.Nplot = 128;\nelseif ( strcmpi(pdechar, 'NLS') == 1 )\n    dt = 1e-2;\n    N = 128;\n    pref.colormap = 'jet';\n    pref.dataplot = 'abs';\n    pref.Clim = [0 1];\n    pref.iterplot = 1;\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/spinsphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.584282724300861}}
{"text": "function [Lb]=logicRemoveInterior(L)\n\n% function [Lb]=logicRemoveInterior(L)\n% ------------------------------------------------------------------------\n% This function removes the interior entries for the input logic L.\n% Interior entries are those fully surrounded by neighbours (e.g. in 3D all\n% entries which are attached to a top, bottom, left, right, front, and a\n% back neighbour).\n% Vectors and n-dimensional arrays are supported. \n% \n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% \n% Change log:\n% 2018/06/14 Created as alternative to bwmorph3 which requires a special\n% toolbox and is from R2018a. \n%------------------------------------------------------------------------\n\nif ~isempty(L)\n    if isvector(L) %Handle vector\n        h=ones(1,3);\n        if ~isrow(L)\n            h=h'; %Transpose for column\n        end\n    else\n        nd=ndims(L);\n        h=zeros(3*ones(1,nd)); %Initialize h\n        ijkMid=2*ones(1,nd); %Middle coordinate\n        I=eye(nd,nd); %Identify matrix to offset indices\n        ijkFilter=[ijkMid; ijkMid(ones(nd,1),:)+I; ijkMid(ones(nd,1),:)-I]; %Indices for filer\n        ind=sub2indn(size(h),ijkFilter);%Linear indices for filer\n        h(ind)=1; %Set ones for ND cross shape\n    end\n    L=L>0;\n    LC=convn(double(L),h,'same');\n    Lb=L & ~(LC==sum(h(:)));\nelse\n    Lb=[];\nend\n\n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/logicRemoveInterior.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.5842827155625816}}
{"text": "function y = vl_nnrelu(x,varargin)\n%VL_NNRELU CNN rectified linear unit.\n%   Y = VL_NNRELU(X) applies the rectified linear unit to the data\n%   X. X can have arbitrary size.\n%\n%   DZDX = VL_NNRELU(X, DZDY) computes the derivative of the block\n%   projected onto DZDY. DZDX and DZDY have the same dimensions as\n%   X and Y respectively.\n%\n%   VL_NNRELU(...,'OPT',VALUE,...) takes the following options:\n%\n%   `Leak`:: 0\n%      Set the leak factor, a non-negative number. Y is equal to X if\n%      X is not smaller than zero; otherwise, Y is equal to X\n%      multipied by the leak factor. By default, the leak factor is\n%      zero; for values greater than that one obtains the leaky ReLU\n%      unit.\n%\n%   ADVANCED USAGE\n%\n%   As a further optimization, in the backward computation it is\n%   possible to replace X with Y, namely, if Y = VL_NNRELU(X), then\n%   VL_NNRELU(X,DZDY) gives the same result as VL_NNRELU(Y,DZDY).\n%   This is useful because it means that the buffer X does not need to\n%   be remembered in the backward pass.\n\n% Copyright (C) 2014-15 Andrea Vedaldi.\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 ~isempty(varargin) && ~ischar(varargin{1})  % passed in dzdy\n  dzdy = varargin{1} ;\n  varargin(1) = [] ;\nelse\n  dzdy = [] ;\nend\n\nopts.leak = 0 ;\nopts = vl_argparse(opts, varargin, 'nonrecursive') ;\n\nif opts.leak == 0\n  if nargin <= 1 || isempty(dzdy)\n    y = max(x, 0) ;\n  else\n    y = dzdy .* (x > 0) ;\n  end\nelse\n  if nargin <= 1 || isempty(dzdy)\n    y = x .* (opts.leak + (1 - opts.leak) * (x > 0)) ;\n  else\n    y = dzdy .* (opts.leak + (1 - opts.leak) * (x > 0)) ;\n  end\nend\n", "meta": {"author": "phoenix104104", "repo": "LapSRN", "sha": "95154bba82a3aab9bdaec8e0eedd4187babc5ed2", "save_path": "github-repos/MATLAB/phoenix104104-LapSRN", "path": "github-repos/MATLAB/phoenix104104-LapSRN/LapSRN-95154bba82a3aab9bdaec8e0eedd4187babc5ed2/matconvnet/matlab/vl_nnrelu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5842827122697622}}
{"text": "function stroud_test207 ( )\n\n%*****************************************************************************80\n%\n%% STROUD_TEST207 tests the Stroud EN_R2 rules on monomials.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    23 January 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'STROUD_TEST207\\n' );\n  fprintf ( 1, '  Demonstrate the use of Stroud rules for the region\\n' );\n  fprintf ( 1, '  EN_R2, that is, all of N-dimensional space, with the\\n' );\n  fprintf ( 1, '  weight function W(X) = exp ( - X1^2 - X2^2 ... -XN^2 )\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  We use the formulas to integrate various monomials of\\n' );\n  fprintf ( 1, '  the form X1^ALPHA1 * X2^ALPHA2 * ... XN^ALPHAN\\n' );\n  fprintf ( 1, '  and compare to the exact integral.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The precision of each formula is known, and we only use\\n' );\n  fprintf ( 1, '  a formula if its precision indicates it should be able to\\n' );\n  fprintf ( 1, '  produce an exact result.\\n' );\n\n  for n = 1 : 7\n\n    alpha = zeros ( n, 1 );\n    en_r2_test ( n, alpha );\n\n    alpha = zeros ( n, 1 );\n    alpha(1) = 2;\n    en_r2_test ( n, alpha );\n\n    alpha = zeros ( n, 1 );\n    alpha(2) = 4;\n    en_r2_test ( n, alpha );\n\n    alpha = zeros ( n, 1 );\n    i = mod ( 3 - 1, n ) + 1;\n    alpha(i) = 6;\n    en_r2_test ( n, alpha );\n\n    alpha = zeros ( n, 1 );\n    alpha(1) = 2;\n    alpha(2) = 4;\n    en_r2_test ( n, alpha );\n\n    alpha = zeros ( n, 1 );\n    i = mod ( 4 - 1, n ) + 1;\n    alpha(i) = 8;\n    en_r2_test ( n, alpha );\n\n    alpha = zeros ( n, 1 );\n    i = mod ( 5 - 1, n ) + 1;\n    alpha(i) = 10;\n    en_r2_test ( n, alpha );\n\n    alpha = 1 : n;\n    en_r2_test ( n, alpha );\n\n    alpha(1:n) = 2;\n    en_r2_test ( n, alpha );\n\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/stroud_test207.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.5842827117316022}}
{"text": "function [A,J2,A2] = create_adjacency_graph(X,method,param,force_sym)\n%CREATE_ADJACENCY_GRAPH Summary of this function goes here\n%   Detailed explanation goes here\nif strcmp(method,'epsball')\n    fh = @(Z) find_indices_by_epsilon(Z,param);\n    [J2,A2] = create_adjacency_graph_internal(X,fh);\nelseif strcmp(method,'nn')\n    if 0 % my implementation\n        fh = @(Z) find_indices_by_nn(Z,param);\n        [J2,A2] = create_adjacency_graph_internal(X,fh);\n    else % Matlab implementation is faster\n        [D,I] = pdist2(X,X,'euclidean','Smallest',param+1);\n        D(1,:) = [];\n        I(1,:) = [];\n        J2 = cell(size(D,2),1);\n        A2 = cell(size(D,2),1);\n        for i = 1:length(J2)\n            J2{i} = I(:,i)';\n            A2{i} = D(:,i)';\n        end\n    end\nelse\n    disp('The method parameter can only take epsball or nn');\n    A = []; J2 = []; A2 = [];\n    return;\nend\nA = cellarr2sparse(J2,A2,length(J2),length(J2));\nif force_sym\n    A = max(A,A');\nend\n\nfunction [J2,A2] = create_adjacency_graph_internal(X,fh_find_indices)\nstep = 100;\nn = size(X,1);\nJ2 = cell(n,1);\nA2 = cell(n,1);\nfor i1 = 1:step:n\n    i2 = i1 + step - 1;\n    if (i2 > n)\n        i2 = n;\n    end;\n\n    XX = X(i1:i2,:);\n    D = calc_distance_matrix(XX,X);\n    [Z,I] = sort(D,2);\n\n    Z = Z(:,2:end); % remove itself as closest neighbor\n    I = I(:,2:end);\n    for i = i1:i2\n        ind = fh_find_indices(Z(i-i1+1,:));\n%         ind = find(Z(i-i1+1,:) < epsilon);\n        jj = I(i-i1+1,ind);\n        Z1 = Z(i-i1+1,ind);\n        J2{i} = jj;\n        A2{i} = Z1;\n    end\nend\n\nfunction ind = find_indices_by_epsilon(Z,epsilon)\nind = find(Z < epsilon);\n\nfunction ind = find_indices_by_nn(Z,nn)\nind = [1:min(nn,length(Z))];\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/common/create_adjacency_graph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.5842827117316022}}
{"text": "function filtScan3M = filtImgGabor(scan3M,r, sig, lam, theta, omega)\n% AI 03/22/18\n% INPUTS\n%  r       - final mask will be 2r+1 x 2r+1\n%  sig     - standard deviation of Gaussian mask\n%  lam     - elongation of Gaussian mask\n%  theta   - orientation (in degrees)\n%  omega   - [1] wavlength of underlying sine (sould be >=1)\n\nhFilt = filterGabor2d( r, sig, lam, theta, omega, 0 );\nfiltScan3M = convn(scan3M,hFilt,'same');  \n\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/heterogenity_metrics/filtImgGabor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5842626015558318}}
{"text": "%% Diplay mesh points based on Gaussian-Hermite quadrature\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\nclc;\nclear all;\nclose all;\n\nN = 50; \nX = NaN(N, N);\n\nfor i = 1:N\n    x = gaussHermiteMesh(i);\n    X(1:length(x), i) = x;\nend\n\n% mesh points\nfigure;\nplot(1:N, X', 'o', 'MarkerFace', 'k', 'Color', 'k', 'MarkerSize', 3);\ngrid on;", "meta": {"author": "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_plotGaussHermite.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.584215573242724}}
{"text": "function t=convertLabelsToTable(L,n)\n%convertLabelsToTable Converts labeled stack of images to the table of cluster-sizes.\n%   t=convertLabelsToTable(L,n)\n%   L is a labelled image, n number of clustrers - output of the function\n%   [L,n] = bwlabelStack(bw,ncon);\n%   t is the table (#frames X #clusters) containing sizes of the individual\n%   clusters in each frame.\nsizeZ=size(L,3); \nmaxClust = max(n); \nt=zeros(sizeZ,maxClust);\nfor frame=1:sizeZ\n    for cluster = 1:maxClust\n        clustTmp=L(:,:,frame)==cluster;\n        t(frame,cluster)=sum(clustTmp(:));\n    end\nend\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/image_proc/convertLabelsToTable.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5842155732427239}}
{"text": "% eml_em_test.m\n% compare aspire and matlab E-ML-EM\n% Copyright Jan 1998\tJeff Fessler, The University of Michigan\n\n\n%\n% generate data\n%\nif ~isvar('yi'), printm 'setup for eml_em_test'\n\tif has_aspire\n\t\tf.dir\t= test_dir;\n\t\tf.wtf\t= [f.dir 't,g.wtf'];\n\t\tf.yi\t= [f.dir 'yi.fld'];\n\t\tf.ci\t= [f.dir 'ci.fld'];\n\t\tf.ri\t= [f.dir 'ri.fld'];\n\t\tf.mask\t= [f.dir 'mask.fld'];\n\tend\n\tem_test_setup\nprompt\nend\n\n%\n% matlab iterations\n%\nif ~isvar('xmat'), printm 'matlab E-ML-EM'\n\tf.niter = 9;\n\txinit = ig.ones; % uniform\n\txmat = eml_em(xinit(ig.mask), G, yi(:), ci(:), ri(:), [], f.niter);\n\txmat = ig.embed(xmat);\n\n\tim clf, im(xmat, 'matlab E-ML-EM iterates')\nprompt\nend\n\nif ~has_aspire, return, end\n\n%\n% aspire iterations - this is for Fessler's testing only!\n%\nif ~isvar('xasp'), printm 'aspire E-ML-EM'\n\n\tf.init\t= [f.dir 't,init.fld'];\n\tf.out = [f.dir 't,out.fld'];\n\tfld_write(f.init, xinit, 'check', 0)\n\tif (exist(f.out) == 2), delete(f.out), end\n\n\tf.alg = 'em,1';\n\tf.saver = '-';\n\tf.saver = 'stack,1';\n\tf.penal = '-';\n\tf.method = sprintf('@%d@%s@%s', f.niter-1, f.alg, f.penal);\n\tf.scaleinit = 0;\n\n\tif 1\n\t\tf.com = sprintf('i -chat 0 empl2 %s %s  %s %s %s 1 %s %s  %s %s 0 1e9 %d -', ...\n\t\t\tf.out, f.init, f.yi, f.ci, f.ri, f.wtf, ...\n\t\t\tf.mask, f.method, f.saver, f.scaleinit);\n\t\tos_run(f.com)\n\n\t\txasp = double(fld_read(f.out));\n\tend\nend\n\nif 1\n\tim(221, xmat, 'xhat matlab')\n\tim(222, xasp, 'xhat aspire')\n\tim(223, (xasp-xmat)/max(xmat(:)), 'aspire-matlab')\n\n\tt = vcorrcoef(xasp, xmat);\n\tprintf('corr. %g,%g', t, t-1)\n\n\tt1 = eql_obj(xmat, G, yi(:), ci(:), ri(:), [], ig.mask);\n\tt2 = eql_obj(xasp, G, yi(:), ci(:), ri(:), [], ig.mask);\n\n\tif im\n\t\tsubplot(224)\n\t\tplot(0:f.niter-1, t1-t1(1), '-o', 0:f.niter-1, t2-t1(1), '-x')\n\t\tlegend('mat', 'asp', 4), xlabel iteration, ylabel objective\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/emission/eml_em_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5842155732427239}}
{"text": "function surf = specificSurface(img, varargin)\n%SPECIFICSURFACE implementation of Ohser's algo for surface comput.\n%\n%   compute surface area in discrete images.\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 16/02/2005.\n%\n\n%   HISTORY \n\nimg = img~=0;\n\ndelta = [1 1 1];\n\n% edges of the unit cell\nkl = [1 2;1 3;1 5;1 4;2 3;1 6;2 5;1 7;3 5;1 8;2 7;3 6;4 5];\n\n% unit surface for each cell\nc1 = 0.045778;\nc2 = 0.036981;\nc3 = 0.035196;\nc = [c1 c1 c1   c2 c2 c2   c2 c2 c2   c3 c3 c3 c3];\n\n% distances between pixels\nd12 = sqrt(delta(1)*delta(1) + delta(2)*delta(2));\nd13 = sqrt(delta(1)*delta(1) + delta(3)*delta(3));\nd23 = sqrt(delta(2)*delta(2) + delta(3)*delta(3));\nd123 = sqrt(sum(delta.*delta));\nr = [delta(1) delta(2) delta(3) d12 d12 d13 d13 d23 d23 d123 d123 d123 d123];\n\n\n% compute gray-tone histogram of the image\nh = grayHist(img);\n\n\nsv = 0;\n\n% for each type of configuration\nfor l=1:256\n    \n    v = l-1;\n    b(1) = bitand(v,1)~=0;\n    b(2) = bitand(v,2)~=0;\n    b(3) = bitand(v,4)~=0;\n    b(4) = bitand(v,8)~=0;\n    b(5) = bitand(v,16)~=0;\n    b(6) = bitand(v,32)~=0;\n    b(7) = bitand(v,64)~=0;\n    b(8) = bitand(v,128)~=0;\n\n    % for each edge of configuration\n    for nu=1:13\n        sv = sv + h(l)*c(nu)/r(nu)*xor( b(kl(nu, 1)), b(kl(nu,2)) );\n    end\nend\n\n\n\n\nsurf = 4*sv/sum(h(:));", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMinkowski/specificSurface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5842155622776629}}
{"text": "function [Ay, by]  = makeAy(baseMVA, ng, gencost, pgbas, qgbas, ybas)\n%MAKEAY  Make the A matrix and RHS for the CCV formulation.\n%   [AY, BY]  = MAKEAY(BASEMVA, NG, GENCOST, PGBAS, QGBAS, YBAS)\n%\n%   Constructs the parameters for linear \"basin constraints\" on Pg, Qg\n%   and Y used by the CCV cost formulation, expressed as\n%\n%       AY * X <= BY\n%\n%   where X is the vector of optimization variables. The starting index\n%   within the X vector for the active, reactive sources and the Y\n%   variables should be provided in arguments PGBAS, QGBAS, YBAS. The\n%   number of generators is NG.\n%\n%   Assumptions: All generators are in-service.  Filter any generators\n%   that are offline from the GENCOST matrix before calling MAKEAY.\n%   Efficiency depends on Qg variables being after Pg variables, and\n%   the Y variables must be the last variables within the vector X for\n%   the dimensions of the resulting AY to be conformable with X.\n%\n%   Example:\n%       [Ay, by]  = makeAy(baseMVA, ng, gencost, pgbas, qgbas, ybas);\n\n%   MATPOWER\n%   Copyright (c) 1996-2016, Power Systems Engineering Research Center (PSERC)\n%   by Carlos E. Murillo-Sanchez, PSERC Cornell & Universidad Nacional de Colombia\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;\n\n% find all pwl cost rows in gencost, either real or reactive\niycost = find(gencost(:, MODEL) == PW_LINEAR);\n\n% this is the number of extra \"y\" variables needed to model those costs\nny = size(iycost, 1);\n\nif ny == 0\n   Ay = sparse([], [], [], 0, ybas+ny-1, 0);\n   by = [];\n   return\nend\n\n% if p(i),p(i+1),c(i),c(i+1) define one of the cost segments, then\n% the corresponding constraint on Pg (or Qg) and Y is\n%                                             c(i+1) - c(i)\n%  Y   >=   c(i) + m * (Pg - p(i)),      m = ---------------\n%                                             p(i+1) - p(i)\n%\n% this becomes   m * Pg - Y   <=   m*p(i) - c(i)\n\n% Form A matrix.  Use two different loops, one for the Pg/Qg coeffs,\n% then another for the y coeffs so that everything is filled in the\n% same order as the compressed column sparse format used by MATLAB;\n% this should be the quickest.\n\nm = sum(gencost(iycost, NCOST));  % total number of cost points\nAy = sparse([], [], [], m-ny, ybas+ny-1, 2*(m-ny)); \nby = [];\n% First fill the Pg or Qg coefficients (since their columns come first)\n% and the rhs\nk = 1;\nfor i=iycost'\n   ns = gencost(i, NCOST);                % # of cost points; segments = ns-1\n   p = gencost(i, COST:2:COST+2*ns-1) / baseMVA;\n   c = gencost(i, COST+1:2:COST+2*ns);\n   m = diff(c) ./ diff(p);                % slopes for Pg (or Qg)\n   if any(diff(p) == 0)\n     fprintf('\\nmakeAy: bad x axis data in row %i of gencost matrix\\n',i);\n   end\n   b = m .* p(1:ns-1) - c(1:ns-1);        % and rhs\n   by = [by;  b'];\n   if i > ng\n     sidx = qgbas + (i-ng) - 1;           % this was for a q cost\n   else\n     sidx = pgbas + i - 1;                % this was for a p cost\n   end\n   Ay(k:k+ns-2, sidx) = m';\n   k = k + ns - 1;\nend\n% Now fill the y columns with -1's\nk = 1;\nj = 1;\nfor i=iycost'\n   ns = gencost(i, NCOST);\n   Ay(k:k+ns-2, ybas+j-1) = -ones(ns-1,1);\n   k = k + ns - 1;\n   j = j + 1;\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/makeAy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5842155570413875}}
{"text": "function G=framematrix(F,L);\n%FRAMEMATRIX  Frame synthesis operator matrix\n%   Usage: G=framematrix(F,L);\n%\n%   `G=frsynmatrix(F,L)` returns the matrix representation *G* of the frame\n%   synthesis operator for a frame *F* of length *L*. The frame object *F*\n%   must have been created using |frame|.\n%\n%   The frame synthesis operator matrix contains all the frame atoms as\n%   column vectors. It has dimensions $L \\times Ncoef$, where $Ncoef$ is the\n%   number of coefficients. The number of coefficients can be found as\n%   `Ncoef=framered(F)*L`. This means that the frame matrix is usually\n%   **very** large, and this routine should only be used for small values of\n%   *L*.\n%\n%   The action of the frame analysis operator |frana| is equal to\n%   multiplication with the Hermitean transpose of the frame\n%   matrix. Consider the following simple example:::\n%\n%     L=200;\n%     F=frame('dgt','gauss',10,20);\n%     G=frsynmatrix(F,L);\n%     testsig = randn(L,1);\n%     res = frana(F,testsig)-G'*testsig;\n%     norm(res)\n%\n%   See also: frame, frana, frsyn\n\nwarning(['LTFAT: FRAMEMATRIX has been deprecated and will be removed',...\n         ' in the future releases, please use FRSYNMATRIX instead.']);   \n\nif nargin<2\n  error('%s: Too few input parameters.',upper(mfilename));\nend;\n\nLcheck=framelength(F,L);\nif Lcheck~=L\n    error('%s: Incompatible frame length.',upper(mfilename));\nend;\n\nif F.realinput\n    \n    %switch(F.type)\n    %  case 'dgtreal'\n        \n    %  This code correctly reproduces the matrix represenation of the\n    %  analysis operator, but not of the synthesis.\n    %\n    %    F2=frame('dgt',F.g,F.a,F.M);\n    %    G2=frsynmatrix(F2,L);\n    %    M2=floor(F.M/2)+1;\n    %    N=L/F.a;\n    %    G=zeros(L,M2*N);\n    %    for n=0:N-1\n    %        G(:,1+n*M2:(n+1)*M2)=G2(:,1+n*F.M:M2+n*F.M);\n    %    end;\n        \n    %  otherwise\n        error(['%s: The synthesis operator of real-valued-input frames does is ' ...\n               'non-linear and does not have a matrix represenation.']);\n        %end;\nelse\n    \n  % Generic code handles all frames where there are no extra coefficients\n  % in the representation\n  Ncoef = framered(F)*L;\n  % sprintf for Octave compatibility\n  assert(abs(Ncoef-round(Ncoef))<1e-3,sprintf('%s: There is a bug. Ncoef=%d should be an integer.',upper(mfilename),Ncoef));\n  Ncoef=round(Ncoef);\n  coef=eye(Ncoef);\n  G = frsyn(F,coef);  \nend;\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/deprecated/framematrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.584215555162015}}
{"text": "function test_old_ft_freqanalysis\n\n% MEM 1gb\n% WALLTIME 00:10:00\n\n\nfunction test_ft_freqanalysis\n% DEPENDENCY_FT_FREQANALYSIS\n% This script tests the ft_freqanalysis functions using simulated data\n% A. Stolk and J.M. Schoffelen\n\n% simulate one second of data, samplefreq = 1200 hz\nt = (1:1200)/1200; \na = cos(2*pi*10*t);\nb = sin(2*pi*25*t);\nc = a + b;\n\n% simulate preprocessed data\n%cfg           = [];\n%cfg.layout    = 'CTF275.lay';\n%cfg.layout    = prepare_layout(cfg);\n%data.label    =  cfg.layout.label(1:273,1);\n% data.grad.pnt = zeros(595,3);\n% data.grad.ori = zeros(595,3);\n% data.grad.tra = zeros(302,595);\ndata.fsample  = 1200;\ndata.label    = {'chan01';'cos10';'sin25'};\n%for j = 1:273\nfor j = 1\n    %data.trial{1,1}(j,:) = c;\n  data.trial{1,1} = [c;a;b];  \n  data.time{1,1}(j,:)  = t;\nend\n\n% ft_freqnalysis_mtmfft\ncfg              = [];\ncfg.output       = 'pow';\n%cfg.channel      = 'MEG';\ncfg.channel      = 'all';\ncfg.method       = 'mtmfft';\ncfg.taper        = 'hanning';\ncfg.foilim       = [1 40];\ncfg.keeptrials   = 'no';\ncfg.keeptapers   = 'no';\nmtmfft           = ft_freqanalysis(cfg, data);\n\n% check whether the powerpeaks are at the given frequencies\nif mtmfft.powspctrm(1,9) < mtmfft.powspctrm(1,10) > mtmfft.powspctrm(1,11) && ...\n        mtmfft.powspctrm(1,24) < mtmfft.powspctrm(1,25) > mtmfft.powspctrm(1,26); \nelse  \n    error('test_ft_freqanalysis:notEqual', 'Incorrect output for ft_freqanalysis_mtmfft.');\nend\n\n% ft_freqnalysis_mtmconvol\ncfg              = [];\ncfg.output       = 'pow';\n%cfg.channel      = 'MEG';\ncfg.channel      = 'all';\ncfg.method       = 'mtmconvol';\ncfg.taper        = 'hanning';\ncfg.keeptrials   = 'no';\ncfg.keeptapers   = 'no';\ncfg.foi          = 1:1:40;\ncfg.t_ftimwin    = 0.5 * ones(1,length(cfg.foi)); % 500 ms\ncfg.toi          = 0.3:0.05:0.75; % center 1/2 second\nmtmconvol        = ft_freqanalysis(cfg, data);\n\n% check whether the powerpeaks are at the given frequencies\nif mtmconvol.powspctrm(1,9,1) < mtmconvol.powspctrm(1,10,1) > mtmconvol.powspctrm(1,11,1) && ...\n        mtmconvol.powspctrm(1,24,1) < mtmconvol.powspctrm(1,25,1) > mtmconvol.powspctrm(1,26,1); \nelse  \n    error('test_ft_freqanalysis:notEqual', 'Incorrect output for ft_freqanalysis_convol.');\nend\n\n\n% test new implementation specest\n\n% ft_freqnalysis_mtmfft\ncfg              = [];\ncfg.output       = 'fourier';\ncfg.channel      = 'all';\ncfg.method       = 'mtmfft';\ncfg.taper        = 'hanning';\ncfg.foilim       = [1 40];\ncfg.keeptrials   = 'yes';\ncfg.keeptapers   = 'yes';\nmtmfft1          = ft_freqanalysis(cfg, data);\nmtmfft2          = ft_freqanalysis(cfg, data, 1);\n\nx = [mtmfft1.fourierspctrm(:,1,10) mtmfft2.fourierspctrm(:,1,10)];\ny = [mtmfft1.fourierspctrm(:,1,25) mtmfft2.fourierspctrm(:,1,25)];\n\n% x(2) should only have real component (angle = 0)\n% y(2) should only have imag component (negative value, angle = -pi/2)\n% abs(x(1))==abs(x(2))\n% abs(y(1))==abs(y(2))\n\n% ft_freqnalysis_mtmconvol\ncfg              = [];\ncfg.output       = 'fourier';\ncfg.channel      = 'all';\ncfg.method       = 'mtmconvol';\ncfg.taper        = 'hanning';\ncfg.keeptrials   = 'no';\ncfg.keeptapers   = 'no';\ncfg.foi          = 1:1:40;\ncfg.t_ftimwin    = 0.5 * ones(1,length(cfg.foi)); % 500 ms\ncfg.toi          = 0.25:1./1200:0.75; % center 1/2 second\nmtmconvol1        = ft_freqanalysis(cfg, data);\nmtmconvol2        = ft_freqanalysis(cfg, data, 1);\n\nx = [squeeze(mtmconvol1.fourierspctrm(:,2,10,:)) ...\n     squeeze(mtmconvol2.fourierspctrm(:,2,10,:))];\ny = [squeeze(mtmconvol1.fourierspctrm(:,3,25,:)) ...\n     squeeze(mtmconvol2.fourierspctrm(:,3,25,:))];\n\n% observations: \n%  Old implementation has 1 Nan at the beginning\n%  New implementation has 1 Nan at the end\n\n% expectations:\n%  angle(x(1,2)) = -pi, (phase of cosine @10Hz @0.25 s: this is approximately true, but not exact\n%  angle(y(1,2)) = 0 (phase of sine @25Hz @0.25 s = 6.25 cycle: this is approximately true, but not exact\n\n% FIXME should we look into this?\n% issues are probably related to even numbered t_ftimwins...\n\n% ft_freqnalysis_mtmconvol\ncfg              = [];\ncfg.output       = 'fourier';\ncfg.channel      = 'all';\ncfg.method       = 'mtmconvol';\ncfg.taper        = 'dpss';\ncfg.keeptrials   = 'no';\ncfg.keeptapers   = 'no';\ncfg.foi          = 1:1:40;\ncfg.t_ftimwin    = 0.5 * ones(1,length(cfg.foi)); % 500 ms\ncfg.toi          = 0.25:1./1200:0.75; % center 1/2 second\ncfg.tapsmofrq    = ones(1,numel(cfg.foi)).*4;\nmtmconvol1        = ft_freqanalysis(cfg, data);\nmtmconvol2        = ft_freqanalysis(cfg, data, 1);\n\nx = [squeeze(mtmconvol1.fourierspctrm(:,2,10,:)); ...\n     squeeze(mtmconvol2.fourierspctrm(:,2,10,:))];\ny = [squeeze(mtmconvol1.fourierspctrm(:,3,25,:)); ...\n     squeeze(mtmconvol2.fourierspctrm(:,3,25,:))];\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_old_ft_freqanalysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5841815159961398}}
{"text": "function [ value, ifault ] = prncst ( st, idf, d )\n\n%*****************************************************************************80\n%\n%% PRNCST computes the lower tail of noncentral T distribution.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 January 2008\n%\n%  Author:\n%\n%    Original FORTRAN77 version by BE Cooper.\n%    MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    BE Cooper,\n%    Algorithm AS 5:\n%    The Integral of the Non-Central T-Distribution,\n%    Applied Statistics,\n%    Volume 17, Number 2, 1968, page 193.\n%\n%  Parameters:\n%\n%    Input, real ST, the argument.\n%\n%    Input, integer IDF, the number of degrees of freedom.\n%\n%    Input, real D, the noncentrality parameter.\n%\n%    Output, real PRNCST, the value of the lower tail of\n%    the noncentral T distribution.\n%\n%    Output, integer IFAULT, error flag.\n%    0, no error occurred.\n%    nonzero, an error occurred.\n%\n%  Local Parameters:\n%\n%    Local, real G1, 1.0 / sqrt(2.0 * pi)\n%\n%    Local, real G2, 1.0 / (2.0 * pi)\n%\n%    Local, real G3, sqrt(2.0 * pi)\n%\n  emin = 12.5;\n  g1 = 0.3989422804;\n  g2 = 0.1591549431;\n  g3 = 2.5066282746;\n\n  f = idf;\n%\n%  For very large IDF, use the normal approximation.\n%\n  if ( 100 < idf )\n\n    ifault = 1;\n\n    a = sqrt ( 0.5 * f ) * exp ( alngam ( 0.5 * ( f - 1.0 ) ) ...\n    - alngam ( 0.5 * f ) ) * d;\n\n    value = alnorm ( ( st - a ) / sqrt ( f * ( 1.0 + d * d ) ...\n    / ( f - 2.0 ) - a * a ), 0 );\n\n    return\n  end\n\n  ifault = 0;\n  ioe = mod ( idf, 2 );\n  a = st / sqrt ( f );\n  b = f / ( f + st * st );\n  rb = sqrt ( b );\n  da = d * a;\n  drb = d * rb;\n\n  if ( idf == 1 )\n    value = alnorm ( drb, 1 ) + 2.0 * tfn ( drb, a );\n    return\n  end\n\n  sum = 0.0;\n\n  if ( abs ( drb ) < emin )\n    fmkm2 = a * rb * exp ( - 0.5 * drb * drb ) * alnorm ( a * drb, 0 ) * g1;\n  else\n    fmkm2 = 0.0;\n  end\n\n  fmkm1 = b * da * fmkm2;\n\n  if ( abs ( d ) < emin )\n    fmkm1 = fmkm1 + b * a * g2 * exp ( - 0.5 * d * d );\n  end\n\n  if ( ioe == 0 )\n    sum = fmkm2;\n  else\n    sum = fmkm1;\n  end\n\n  ak = 1.0;\n  fk = 2.0;\n\n  for k = 2 : 2 : idf - 2\n\n    fkm1 = fk - 1.0;\n    fmkm2 = b * ( da * ak * fmkm1 + fmkm2 ) * fkm1 / fk;\n    ak = 1.0 / ( ak * fkm1 );\n    fmkm1 = b * ( da * ak * fmkm2 + fmkm1 ) * fk / ( fk + 1.0 );\n\n    if ( ioe == 0 )\n      sum = sum + fmkm2;\n    else\n      sum = sum + fmkm1;\n    end\n\n    ak = 1.0 / ( ak * fk );\n    fk = fk + 2.0;\n\n  end\n\n  if ( ioe == 0 )\n    value = alnorm ( d, 1 ) + sum * g3;\n  else\n    value = alnorm ( drb, 1 ) + 2.0 * ( sum + tfn ( drb, 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/asa005/prncst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5841815109768865}}
{"text": "% Cdiff_test.m\n% test Cdiff object\n\nif 1 % look at 2nd order case\n\tnx = 8; ny = 6;\n\tC = Cdiff(ones(nx,ny), 'order', 2);\n\tCf = C(:,:);\n\tt = reshape(Cf', nx*ny, nx*ny, []);\n\tim(t)\n\tt = zeros(nx,ny); t(nx/2+1,ny/2+1) = 1;\n\tt = C' * (C * t);\n\tim(t)\nend\n\nif 1\n\tnx = 16; ny = 14;\n\tnx = 512; ny = 500; % for large images, the mex file is much faster!\n\tig = image_geom('nx', nx, 'ny', ny, 'dx', 1);\n\tig.mask = [0 0 [nx ny]/2-5 0 1];\n\tig.mask = conv2(double(ellipse_im(ig, []) > 0), ones(2), 'same') > 0;\n%\tmask = ones(nx,ny); % all\n\n\tif 1, printm 'test penalty_mex'\n\t\tx = single(ig.mask);\n\t\toffsets = [nx-1];\n\t\toffsets = int32(offsets);\n\t\td1 = penalty_mex('diff2,forw1', x, offsets);\n\t\td2 = penalty_mex('diff2,forw1', x, offsets, int32(ndims(x)));\n\t\tif any(d1(:) ~= d2(:)), error 'bug', end\n\n\t\tx1 = penalty_mex('diff2,back1', d1, offsets);\n\t\tx2 = penalty_mex('diff2,back1', d1, offsets, int32(ndims(x)));\n\t\tif any(x1(:) ~= x2(:)), error 'bug', end\n\tend\n\n\tctype = 'leak';\n\tctype = 'tight';\n\torder = 1;\n\ttic\n\tC1 = Cdiff(ig.mask, 'edge_type', ctype, 'offsets', '2d,hvd', ...\n\t\t'distance_power', 1., 'order', 1);\n\tprintm('make C1 time %g', toc)\n\n\ttic\n\t[C2 wjk] = C2sparse(ctype, ig.mask, 8);\n\tprintm('make C2 time %g', toc)\n\tC2 = spdiag(sqrt(wjk)) * C2;\n\tC2 = C2(:,ig.mask(:));\n\n\tif 0 % test old Cmask\n\t\tcpu etic\n\t\tb1 = Cmask('tight,2d,hvd', ig.mask);\n\t\tcpu etoc 'make scale time:'\n\t\tb1(:,:,[3 4]) = b1(:,:,[3 4]) / sqrt(sqrt(2));\n\t\tif 0\n\t\t\tb1 = reshape(sqrt(wjk), [nx ny 4]);\n\t\tend\n\n\t\tcpu etic\n\t\tb2 = penalty_mex('scales,tight', single(ig.mask), C1.arg.offsets, 1.);\n\t\tb2 = double(b2);\n\t\tcpu doc 'make scale time:'\n\n\t\tim plc 1 3, im(1, b1), im(2, b2), im(3, b1-b2)\n\t\tprintm('old vs new: %g%%', max_percent_diff(b1, b2))\n\t\tequivs(b1, b2)\n\treturn\n\tend\n\n\trng(0)\n\tx = rand(nx, ny);\n\tx = dsingle(x);\n\tx = x .* ig.mask;\n\n%prompt\nend\n\nif 1\n\txm = double(x(ig.mask(:)));\n\tcpu etic\n\td1 = C1 * x; \n\tcpu etoc 'C1 forw time:'\n\n\tcpu etic\n\td2 = C2 * xm; \n\tcpu etoc 'C2 forw time:'\n\td2 = reshape(d2, [nx ny 4]); \n%\tprintm('Cx vs penalty_mex: %g%%', max_percent_diff(d1, d2))\n\tequivs(d1, d2)\n\n\tif im\n\t\tim plc 1 3\n\t\tim(1, d1, 'C * x'), cbar\n\t\tim(2, d2, 'penalty--mex'), cbar\n\t\tim(3, d2-d1, 'err'), cbar\n\tprompt\n\tend\nend\n\nif 1 % [x x]\n\txx = double([xm xm]);\n\tcpu etic\n\td11 = C1 * xx;\n\tcpu etoc 'C1 forw time:'\n\n\tcpu etic\n\td22 = C2 * xx; \n\tcpu etoc 'C2 forw time:'\n%\tprintm('Cxx vs penalty_mex: %g%%', max_percent_diff(d11, d22))\n\tequivs(d11, d22)\nend\n\nif 1\n\td = double(d1(:));\n\t%d = zeros(nx,ny,4);\n\t%d(end/2,end/2,1) = 1;\n\n\tcpu etic\n\tx1 = C1' * d;\n\tcpu etoc 'C1''d time:'\n\tx1 = embed(x1, ig.mask);\n\n\tcpu etic\n\tx2 = C2' * d;\n\tcpu etoc 'C2''d time:'\n\tx2 = embed(x2, ig.mask);\n\n%\tprintm('C1 vs C2: %g%%', max_percent_diff(x1, x2))\n\tequivs(x1, x2)\n\n\tif im\n\t\tim plc 1 3\n\t\tim(1, x1, 'C''d'), cbar\n\t\tim(2, x2, 'penalty--mex'), cbar\n\t\tim(3, x2-x1, 'err'), cbar\n\tend\nend\n\nif 1 % C' [d d]\n\tdd = double([d(:) d(:)]);\n\n\tcpu etic\n\tx11 = C1' * dd;\n\tcpu etoc 'C1''d time:'\n\n\tcpu etic\n\tx22 = C2' * dd;\n\tcpu etoc 'C2''d time:'\n\n%\tprintm('C1 vs C2 for dd: %g%%', max_percent_diff(x11, x22))\n\tequivs(x11, x22)\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/penalty/Cdiff_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5841815109768865}}
{"text": "%kcmindist_classify 'Classify an object using the Minimum Distance algorithm'\n% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros cmindist_classify.pane file\n%\n% Parameters: \n% InputFile: iimage 'Input Image', required: 'input image file'\n% InputFile: isigs 'Input Signatures', required: 'input signatures file'\n% Integer: distancerank 'Use distance rank', default: 1: 'distance rank integer'\n% OutputFile: oclass 'Output Classified', required: 'output classified image'\n% OutputFile: oprob 'Output Probabilities', optional: 'output a posteriori probabilities'\n% OutputFile: oinfo 'Output Information', optional: 'output information about classification'\n%\n% Example: [oclass, oprob, oinfo] = kcmindist_classify({iimage, isigs}, {'iimage','';'isigs','';'distancerank',1;'oclass','';'oprob','';'oinfo',''})\n%\n% Khoros helpfile follows below:\n%\n%  PROGRAM\n% cmindist_classify - Classify an object using the Minimum Distance algorithm\n%\n%  DESCRIPTION\n% This routine classifies an object using the Minimum Distance classification algorithm (or, more precisely, the Minimum Euclidean Distance to Class Means algorithm). The Minimum Distance algorithm is a simple algorithm that assigns a class C to a pixel X if the distance of a prototype of C to the vector X is the smallest between all known classes. More details about the Minimum Distance classifier are on the Classify Toolbox Manual.\n% This routine requires an input object to be classified (specified by the parameter [-iimage]) and a set of classes's signatures object created by \"cmindist_signature\" and appended by \\fIkappend\\fP (specified by the parameter [-isigs]).\n% This routine will create the output classification result in the file specified by [-oclass]. Optionally the final distances for each point and each class can be created if the parameter [-oprob] is used. If a file is specified in the  parameter [-oinfo] the classification results will be written to that file in ASCII (can get large for large images).\n% The expected dimensions of the input and output objects are shown below:\n% The input object which will be classified will have dimensions WxHxDxTxF, where F is the number of features. If it has mask, the masked points won't be classified, and the corresponding points in the output will have value 0 and mask 0.\n% The input signatures must have dimensions Fx2x1xNx1, where N is the number of classes. It must be created by using \"cmindist_signature\" and \\fIkappend\\fP. \n% The output object (specified with the parameter [-oclass]) will have dimensions WxHxDxTx1, and its value segment will have values on the range 0..N, where 0 means that the pixel was rejected (see below). It will also have a corresponding mask segment with values 0 for the rejected pixels and 1 for the non-rejected pixels. The values for the pixels will be associated accordingly to the order the signatures were appended with \"kappend\".\n% If the parameter [-oprob] is used, it will have dimensions WxHxDxTxN.\n% Alternatively to the Minimum Distance classification, the second (or third, or N-th) distance result can be obtained by specifying an index in the [-distancerank] parameter.\n% Points can be optionally rejected (with value and mask 0 in the output) if their distance to the center (or mean) in the signature is larger than an absolute value (specified with the [-reject] parameter) or a number of standard deviations (specified with the [-reject] parameter and the [-usestddev] flag).\n% Please refer to the Classify toolbox manual or for one of the example workspaces for usage examples and details.\n%\n%  \n%\n%  EXAMPLES\n% All examples for the Classify toolbox are listed on the Classify Toolbox Manual. For examples of this program, please see the Classify:workspaces:MINDIST and Classify:workspaces:MINDIST-Classify example workspaces.\n%\n%  \"SEE ALSO\"\n% cmindist_signature, kappend.\n%\n%  RESTRICTIONS \n% Expects the signatures to be valid signatures for the Minimum Distance algorithm.\n%\n%  REFERENCES \n% All references for the Classify toolbox are listed on the Classify Toolbox Manual.\n%\n%  COPYRIGHT\n% Copyright (C) 1997 Rafael Santos. Khoros (C) Khoral Research, Inc.\n% \n\n\nfunction varargout = kcmindist_classify(varargin)\nif nargin ==0\n  Inputs={};arglist={'',''};\nelseif nargin ==1\n  Inputs=varargin{1};arglist={'',''};\nelseif nargin ==2\n  Inputs=varargin{1}; arglist=varargin{2};\nelse error('Usage: [out1,..] = kcmindist_classify(Inputs,arglist).');\nend\nif size(arglist,2)~=2\n  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')\n end\nnarglist={'iimage', '__input';'isigs', '__input';'distancerank', 1;'oclass', '__output';'oprob', '__output';'oinfo', '__output'};\nmaxval={0,0,2,0,1,1};\nminval={0,0,2,0,1,1};\nistoggle=[0,0,1,0,1,1];\nwas_set=istoggle * 0;\nparamtype={'InputFile','InputFile','Integer','OutputFile','OutputFile','OutputFile'};\n% identify the input arrays and assign them to the arguments as stated by the user\nif ~iscell(Inputs)\nInputs = {Inputs};\nend\nNumReqOutputs=1; nextinput=1; nextoutput=1;\n  for ii=1:size(arglist,1)\n  wasmatched=0;\n  for jj=1:size(narglist,1)\n   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments\n     wasmatched = 1;\n     was_set(jj) = 1;\n     if strcmp(narglist{jj,2}, '__input')\n      if (nextinput > length(Inputs)) \n        error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n      end\n      narglist{jj,2} = 'OK_in';\n      nextinput = nextinput + 1;\n     elseif strcmp(narglist{jj,2}, '__output')\n      if (nextoutput > nargout) \n        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n      end\n      if (isempty(arglist{ii,2}))\n        narglist{jj,2} = 'OK_out';\n      else\n        narglist{jj,2} = arglist{ii,2};\n      end\n\n      nextoutput = nextoutput + 1;\n      if (minval{jj} == 0)  \n         NumReqOutputs = NumReqOutputs - 1;\n      end\n     elseif isstr(arglist{ii,2})\n      narglist{jj,2} = arglist{ii,2};\n     else\n        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n        end\n        if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n          end\n        end\n     end\n     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in') \n       narglist{jj,2} = arglist{ii,2};\n     end\n   end\n   end\n   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n   end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n     if  strcmp(paramtype{jj}, 'Toggle')\n        if (narglist{jj,2} ==0)\n          narglist{jj,1} = ''; \n        end;\n        narglist{jj,2} = ''; \n     end;\n     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n          narglist{jj,1} = ''; \n          narglist{jj,2} = ''; \n     end;\n     if strcmp(narglist{jj,2}, '__input')\n      if (minval{jj} == 0)  % meaning this input is required\n        if (nextinput > size(Inputs)) \n           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n        else\n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        end\n      else  % this is an optional input\n        if (nextinput <= length(Inputs)) \n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end;\n     else \n     if strcmp(narglist{jj,2}, '__output')\n      if (minval{jj} == 0) % this is a required output\n        if (nextoutput > nargout & nargout > 1) \n           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n        else\n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n          NumReqOutputs = NumReqOutputs-1;\n        end\n      else % this is an optional output\n        if (nargout - nextoutput >= NumReqOutputs) \n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end\n     end\n  end\nend\nif nargout\n   varargout = cell(1,nargout);\nelse\n  varargout = cell(1,1);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n  w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\n[varargout{:}]=callKhoros([w 'cmindist_classify\"  '],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kcmindist_classify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5841814949048723}}
{"text": "function net = initializeFaceCNN_simple_5(num_bins)\n\nf=1/100 ;\nnet.layers = {} ;\nnet.layers{end+1} = struct('type', 'conv', ...\n                           'weights', {{f*randn(9,9,1,10, 'single'), zeros(1, 10, 'single')}}, ...\n                           'stride', 1, ...\n                           'pad', 0) ;                       \nnet.layers{end+1} = struct('type', 'relu') ;       \nnet.layers{end+1} = struct('type', 'pool', ...\n                           'method', 'max', ...\n                           'pool', [2 2], ...\n                           'stride', 2, ...\n                           'pad', 0) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n                           'weights', {{f*randn(7,7,10,10, 'single'), zeros(1,10,'single')}}, ...\n                           'stride', 1, ...\n                           'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;       \nnet.layers{end+1} = struct('type', 'pool', ...\n                           'method', 'max', ...\n                           'pool', [2 2], ...\n                           'stride', 2, ...\n                           'pad', 0) ;               \n% This is basically an FC layer\nnet.layers{end+1} = struct('type', 'conv', ...\n                           'weights', {{f*randn(10,10,10,50, 'single'), zeros(1,50,'single')}}, ...\n                           'stride', 1, ...\n                           'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;       \nnet.layers{end+1} = struct('type', 'conv', ...\n                           'weights', {{f*randn(1,1,50,num_bins, 'single'), zeros(1,num_bins,'single')}}, ...\n                           'stride', 1, ...\n                           'pad', 0) ;   \nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\nnet = vl_simplenn_tidy(net) ;\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_validation/initializeFaceCNN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5841510270990932}}
{"text": "function [ x, y, z, w ] = ld0770 ( )\n\n%*****************************************************************************80\n%\n%% LD0770 computes the 770 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(770,1);\n  y = zeros(770,1);\n  z = zeros(770,1);\n  w = zeros(770,1);\n  a = 0.0;\n  b = 0.0;\n  v = 0.2192942088181184E-03;\n  [ n, x, y, z, w ] = gen_oh ( 1, n, a, b, v, x, y, z, w );\n  v = 0.1436433617319080E-02;\n  [ n, x, y, z, w ] = gen_oh ( 2, n, a, b, v, x, y, z, w );\n  v = 0.1421940344335877E-02;\n  [ n, x, y, z, w ] = gen_oh ( 3, n, a, b, v, x, y, z, w );\n  a = 0.5087204410502360E-01;\n  v = 0.6798123511050502E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.1228198790178831;\n  v = 0.9913184235294912E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.2026890814408786;\n  v = 0.1180207833238949E-02;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.2847745156464294;\n  v = 0.1296599602080921E-02;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.3656719078978026;\n  v = 0.1365871427428316E-02;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.4428264886713469;\n  v = 0.1402988604775325E-02;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.5140619627249735;\n  v = 0.1418645563595609E-02;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6306401219166803;\n  v = 0.1421376741851662E-02;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6716883332022612;\n  v = 0.1423996475490962E-02;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6979792685336881;\n  v = 0.1431554042178567E-02;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.1446865674195309;\n  v = 0.9254401499865368E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.3390263475411216;\n  v = 0.1250239995053509E-02;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.5335804651263506;\n  v = 0.1394365843329230E-02;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.6944024393349413E-01;\n  b = 0.2355187894242326;\n  v = 0.1127089094671749E-02;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2269004109529460;\n  b = 0.4102182474045730;\n  v = 0.1345753760910670E-02;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.8025574607775339E-01;\n  b = 0.6214302417481605;\n  v = 0.1424957283316783E-02;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.1467999527896572;\n  b = 0.3245284345717394;\n  v = 0.1261523341237750E-02;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.1571507769824727;\n  b = 0.5224482189696630;\n  v = 0.1392547106052696E-02;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2365702993157246;\n  b = 0.6017546634089558;\n  v = 0.1418761677877656E-02;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.7714815866765732E-01;\n  b = 0.4346575516141163;\n  v = 0.1338366684479554E-02;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3062936666210730;\n  b = 0.4908826589037616;\n  v = 0.1393700862676131E-02;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3822477379524787;\n  b = 0.5648768149099500;\n  v = 0.1415914757466932E-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/ld0770.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5841397827606799}}
{"text": "function yPred = objFcn(p , tObs, drug)\n%Copyright (c) 2011, The MathWorks, Inc.\n\nL0  = p(1)   ; % Drug-independent parameter 1\nL1  = p(2)   ; % Drug-independent parameter 2\nk1  = p(3)   ; % Drug-independent parameter 3\n\nk2_A  = p(4) ; % Drug dependent parameter (drug A)\nk2_B  = p(5) ; % Drug dependent parameter (drug B)\n\n% Simulate model for drug A \nyPred_A = evalTumorWeight(tObs(drug == 'A'), [L1, L0, k1, k2_A]) ;\n\n% Simulate model for drug B \nyPred_B = evalTumorWeight(tObs(drug == 'B'), [L1, L0, k1, k2_B]) ;\n\n% Combine prediction\nyPred = [yPred_A; yPred_B] ; \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/30869-fitting-with-matlab-statistics-optimization-and-curve-fitting/objFcn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5841397781935634}}
{"text": "% Fig. 5.26  Feedback Control of Dynamic Systems, 5e \n%             Franklin, Powell, Emami\n%script for Figure 5.26\nn=[1 5.4];\nd1=conv([1 1 0],[1 7 49]);\nd=conv(d1,[1 20]);\npzmap(n,d)\naxis([-20 0 -7.5 7.5])\nhold on\nr=roots([1 7 49]);\nplot(r,'*')\ntitle('Fig.5.26 Construction for placing a specific point')\nz=0:.1:.9;\n wn=2:2:19;\n sgrid(z, wn)\n hold off", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig5_26.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.584139772489277}}
{"text": "function pass = test_trigs(pref) \n% Test some trigonometric functions\n\nif ( nargin == 0 ) \n    pref = chebfunpref; \nend\ntol = 100*pref.cheb3Prefs.chebfun3eps;\n\nf = {@cos, @sin, @tan, @cosh, @sinh, @tanh, @tand}; \n\ng = chebfun3(@(x,y,z) x.*y.^2.*z.^3); \nfor jj = 1:numel(f)\n    h = f{jj}(g); \n    exact = chebfun3(@(x,y,z) f{jj}(x.*y.^2.*z.^3));\n    pass(jj) = norm(h - exact) < tol; \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_trigs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5841219046339939}}
{"text": "function slide34\n\t\n\ta = [0 0 0;\n\t\t3 0 0;\n\t\t3 1 0;\n\t\t0 1 0;\n\t\t0 0 1;\n\t\t3 0 1;\n\t\t3 1 1;\n\t\t0 1 1];\n\t\n\tb = [1 2 6 5;\n\t\t2 3 7 6;\n\t\t3 4 8 7;\n\t\t4 1 5 8;\n\t\t1 2 3 4;\n\t\t5 6 7 8];\n\t\n\tp1 = patch('faces',b,...\n\t\t'vertices',a,...\n\t\t'facecolor',[.5 .5 .5],...\n\t\t'edgecolor',[1,1,1],...\n\t\t'facealpha',0.5);\n\t\n\tview(3)\n\taxis([-3 7 -3 5 -3 5])\n\tgrid on\n\t\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/25856-using-patch-and-rotate-basics/slide34.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5841218899869098}}
{"text": "%%  Introduction to *wavelet_factory_2d*\n% *wavelet_factory_2d* is computing operators(except the modulus) and \n% filters required to compute the next layer of a scattering network.\n%\n%% Usage\n% [Wop, filters] = wavelet_factory_2d(size_in, filt_opt, scat_opt), documentation is given in\n% <matlab:doc('wavelet_factory_2d') wavelet_factory_2d>\n%\n%% Description\n% Given a size image, some filters options and scattering options, this\n% function comput the linear operators necessar to compute the next\n% coefficients of scattering.\n\nx = mandrill;\n\n% Create $ U[\\empty]x $\n[Wop, filters] = wavelet_factory_2d(size(x));\n\n% Then one can apply Wop as in *scat*. Please reference to its\n% documentation.\n\n\n%% Options\n% filt_opt has the same fields as in *morlet_filter_bank_2d*.\n%\n% scat_opt has the same fields as in *wavelet_layer_2d*.\n%\n% See their documentation for more details.\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_factory_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5841081572494383}}
{"text": "function bc = specific_bc(xbd,ybd)\n%collide_bc   Reference problem 5.4 boundary condition \n%   bc = specific_bc(xbd,ybd);\n%   input\n%          xbd          x boundary coordinate vector\n%          ybd          y boundary coordinate vector \n%\n%   specifies streamfunction associated with colliding flow\n%   IFISS function: DJS; 6 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nbc=-(xbd.^5)+5*xbd.*ybd.^4;\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/stokes_flow/test_problems/collide_bc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5841081479926613}}
{"text": "function [ ntri, tri ] = sphere_imp_gridfaces_3d ( maxtri, nlat, nlong )\n\n%*****************************************************************************80\n%\n%% SPHERE_IMP_GRIDFACES_3D produces a grid of triangles on an implicit sphere in 3D.\n%\n%  Discussion:\n%\n%    The point numbering system is the same used in SPHERE_IMP_GRIDPOINTS_3D,\n%    and that routine may be used to compute the coordinates of the points.\n%\n%    An implicit sphere in 3D satisfies the equation:\n%\n%      sum ( ( P(1:DIM_NUM) - CENTER(1:DIM_NUM) )**2 ) = R**2\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 May 2005\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer MAXTRI, the maximum number of triangles.\n%\n%    Input, integer NLAT, NLONG, the number of latitude and longitude\n%    lines to draw.  The latitudes do not include the North and South\n%    poles, which will be included automatically, so NLAT = 5, for instance,\n%    will result in points along 7 lines of latitude.\n%\n%    Output, integer NTRI, the number of triangles.\n%\n%    Output, integer TRI(3,MAXTRI), the triangle vertices.\n%\n  dim_num = 3;\n  ntri = 0;\n%\n%  The first row.\n%\n  n = 1;\n\n  sw = 2;\n  se = sw + 1;\n\n  s_min = 2;\n  s_max = nlong + 1;\n\n  for j = 0 : nlong - 1\n\n    if ( ntri < maxtri )\n      ntri = ntri + 1;\n      tri(1:dim_num,ntri) = [ sw, se, n ]';\n    end\n\n    sw = se;\n\n    if ( se == s_max )\n      se = s_min;\n    else\n      se = se + 1;\n    end\n\n  end\n%\n%  The intermediate rows.\n%\n  for i = 1 : nlat\n\n    n_max = s_max;\n    n_min = s_min;\n\n    s_max = s_max + nlong;\n    s_min = s_min + nlong;\n\n    nw = n_min;\n    ne = nw + 1;\n    sw = s_min;\n    se = sw + 1;\n\n    for j = 0 : nlong - 1\n\n      if ( ntri < maxtri )\n        ntri = ntri + 1;\n        tri(1:dim_num,ntri) = [ sw, se, nw ]';\n      end\n\n      if ( ntri < maxtri )\n        ntri = ntri + 1;\n        tri(1:dim_num,ntri) = [ ne, nw, se ]';\n      end\n\n      sw = se;\n      nw = ne;\n\n      if ( se == s_max )\n        se = s_min;\n      else\n        se = se + 1;\n      end\n\n      if ( ne == n_max )\n        ne = n_min;\n      else\n        ne = ne + 1;\n      end\n\n    end\n\n  end\n%\n%  The last row.\n%\n  n_max = s_max;\n  n_min = s_min;\n\n  s = n_max + 1;\n\n  nw = n_min;\n  ne = nw + 1;\n\n  for j = 0 : nlong - 1\n\n    if ( ntri < maxtri )\n      ntri = ntri + 1;\n      tri(1:dim_num,ntri) = [ ne, nw, s ]';\n    end\n\n    nw = ne;\n\n    if ( ne == n_max )\n      ne = n_min;\n    else\n      ne = ne + 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/geometry/sphere_imp_gridfaces_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5841081433642726}}
{"text": "function  [cct,  ta1, ta2] = srcint(la, k2, ct4, pp1, pp2, ctc0, nprimtilt, lmax, K, stfname, logstep)\n% srcpint.m integrates the source including polarisation over conformal time using the approach of Seljak :\n% integration over the photon past light cone, see M Zaldarriaga et al., ApJ nr 494, 491 (1998)\n% the function needs an l-range (la), a k-range (k2) a ctime-range (ct4),\n% ctc0 : the present conformal time, a series of splines of the source in conformal time \n% for the temperature (pp1) and for the polarisation (pp2),\n% the index of the primary power spectrum (nprimtilt), the maximum la of the anistropy spectrum (lmax)\n% and the curvature energy content from the Friedman equation (K), the startfile name of the\n% ultra-spherical function (stfname), an option for logaritmic variation of the\n% k2 vector : default logstep = 0 (constant steps in k2). k2 has 10-log steps, if logstep = 1. \n%\n% the result (cct) is the square of the temperature spectrum (1) resp the E-polarisation spectrum (2)\n% resp the cross-correlation of temperature and polarisation (3).\n%\n% D Vangheluwe 4 april 2005\n% remark 1: we use ultra-spherical bessel values which have two parameters and must be found by integration:\n%   for the calculation of the ultra-spherical bessel functions see: cmb/usphint.m\n% remark 2: for the ode equation of the u-function, see equation (36) of Zaldarriaga & Seljak.\n% remark 3: take attention the value of k2 should lie within the range of kb1 values : there is no check!!\n%   see spline of start  values x10 and pbd0.\n% remark 4: how do we get the ultra-spherical bessel function values? see development and test routine usphpar.m \n\nlla = size(la, 2);\nlk2 = size(k2, 2);\nk2min = k2(1);\nk2max = k2(lk2);\nlct4 = size(ct4, 2);\nkk0 = sign(K);\n\n% load the table and find the start values for the integration of the ode for u-functions\n% the startfile can be obtained by running usphst.m\n%  stv1 = load('usphst.dat');\nstv1 = load(stfname);\nlmax0 = stv1.ust.la(end);\n\nek2step = 1;\nif logstep == 1, ek2step = log(k2(2)/k2(1))/log(10); end\nnrsteps = 10000;   % default 10000\n%lmax = 1500;\nxmax = k2(lk2) * ctc0;   % =default 3000\nxstep = 2*lmax0/nrsteps;\nkx = 1e-12 : xstep : xmax;\n\n% allocate the data in order to speed up the routine\nkctc0 = zeros(1, lct4);\nkctc = zeros(1, lct4);\njl = zeros(lct4, 1);\nsrc = zeros(lct4, 1);\nhtable = zeros(lct4, 1);\ntetatl = zeros(1, lk2);\ntetael = zeros(1, lk2);\ncmbtable = zeros(1, lk2);\n\n% calculate the curvature length times wavenumber : a parameter for the ultra_spherical bessel function\nkb = sqrt(-K) ./k2;\n\n%#########\nkb(1)\nkb(end)\nif all(kb == 0), kbzero = 1; x10 = 1e-12 * ones(1, lk2);\nelse  % not all kb are zero\n\n  kbzero = 0;\n  ikb = find(kb > 10);\n  if ~isempty(ikb), \n      kb(ikb) = 10 * ones(1, size(ikb, 2));\n      message('boundary kb > 10 reached')\n  end\n\n% split the structure stv1 from the startfile : x1: start values where pbi_beta = 1e-6,\n% pbd : dphi_beta/dx at the start values, all data exact within 1e-6.\n% the la-values resp kb-vector should be the same as in the program usphst.m\n  la1 = stv1.ust.la;\n  lla1 = size(la1, 2);\n  kb1 = stv1.ust.kb;\n  lkb1 = size(kb1, 2);\n  x1v1 = stv1.ust.x1;\n  pbdv1 = stv1.ust.pbd;\n\n% find all start values (hs) for the ode integration step as a function of la and kb (is a surface):\n% the long sought magic formula : la1 is the la-vector from usphst.m!!\n  hs = sqrt(0.6* x1v1 ./ repmat(((la1+250) .^0.905)', 1, lkb1));\n  hs = hs.* repmat((kb1 + 1) ./ (4*kb1 + 1), lla1, 1);\n\nend %all(kb == 0)\n\n%############################# start\nfor il = 1:lla\n\n    l = la(il)\n\n    if ~kbzero\n       il1 = find(la1 == l);\n       if isempty(il1) \n           error('la value not found, try another value')\n           break;\n       else\n           x10 = spline(kb1, x1v1(il1,:), kb);\n           pbd0 = spline(kb1, pbdv1(il1,:), kb);\n       end\n\n% calculate the start values for the u-function : u0 = [u, du/dx] with u = r(x) * phi_beta(x) and\n%  du/dx = phi_beta(x) * dr(x)/dx + r(x) * dphi_beta(x)/dx :\n       r10 = sinh(kb .* x10) ./kb;\n       rd10 = cosh(kb .* x10);\n       u0 = [r10 *1e-6; r10 .* pbd0 + 1e-6 * rd10];\n\n% define the step and set 'odeint' to a constant number of steps for all cases (kb)\n       hstart = spline(kb1, hs(il1,:), kb);\n       toi = 1e-4;\n       hmax = 0.3;   %we take hmax = 0.3 as the default value\n       maxstp = 150;   % default maxstp = 150\n       x1e = ones(1, lk2) * xmax;\n% solve the u-function instead of the phi_beta function : xs2 does not have a constant step  \n       [xs2, u2, nok, nbad, nfev] = odeintp(u0, x10, x1e, toi, hstart, 0, hmax, maxstp, @uspheq1, l, kb, kk0);\n\n% prepare a spline of the solution for a constant step in xs (the values are found with ppval1):\n       y2der = splinep(xs2, u2);\n% calculate the number of constant steps, xstep in the solution xs2: ilast is the last one\n       ilast = ceil((xs2(end,:) - x10)/xstep);\n       ncsteps = 8;\n       ilast = ilast - ncsteps;\n% set the number of overlapping steps for the matching to the asymptotic solution (default=40):\n       noverflow = 40;  \n%       noverflow = 80;  %used for smaller xstep\n    end  % kbzero\n\n% calculate also the spherical bessel function as we may need it for kb < 1-5\n    table_bv = sphbes(l, kx);\n% set some constants needed for the polarisation formula\n    gl = sqrt((l + 2) * (l + 1) * l * (l - 1));\n\n\n% interpolate and integrate (sum with the Simpson rule) over conformal time :\n    for i = 1:lk2\n%    for i = 967:967\n\n       if kb(i) > 1e-5 * (1500/l)\n\n% define a vector of argument values for the ultra-spherical bessel function (x1): reverse ct4\n          clear('xs', 'x1', 'x2', 'yspl2','iover','iasym', 'yas', 'table_pb')\n          x1 = x10(i) : xstep : xmax;\n          lx1 = size(x1, 2);\n\n% in the next 10 lines make a table over x1 (table_pb) of ultra-spherical bessel values:\n\n% make the interpolation of the ode solution for a constant step xstep:\n          [xs, yspl2] = ppval1(xs2(:,i), u2(:,i), y2der(:,i), xstep);\n\n% define the overflow index in x1 (iover): \n%default 40 steps should at least include one zero and one maximum of u2\n          iover = (ilast(i) - noverflow) : ilast(i);\n% define the index of x1 where the asymptotic appr is applied (iasym)\n          iasym = ilast(i) : lx1;\n\n% calculate the ultra-spherical bessel values\n          kctc0 = ctc0 * k2(i) * ones(1, lct4);\n          kctc = k2(i) * ct4;\n          xctc = kctc0 - kctc;\n          ixode = find(xctc > x1(1)  &  xctc < x1(ilast(i)));\n          ul = zeros(1, lct4);\n          if  ~isempty(ixode)\n             r1 = sinh(kb(i) * xs)/kb(i);\n% interpolate the table of ultra-spherical bessel function in the range of k values of the ode solution\n             ul(ixode) = interpl(xs, yspl2 ./ r1, xctc(ixode));\n% calculate the necessry values of the asymptotic expansion of the ultra-spherical bessel function\n             ixas = find(xctc >= x1(ilast(i)));\n% find the asymptotic values and the phase correction in the overflow region:\n             if ~isempty(ixas)\n                 dphi = phdif(x1(iover), usphas(l, kb(i), x1(iover), 0, 0, kk0), yspl2(iover));\n                 ul(ixas) = usphas1(l, kb(i), xctc(ixas), dphi, 1, kk0); \n             end\n% integrate the source function over ct4, following formula (40) of Zaldarriaga et al.(1998)\n             src = ppval(pp1, k2(i));\n\nfigure(1)\nix5= ixode;\nplot(ct4(ix5), src(ix5)', ct4(ix5), ul(ix5),'--')\n% as we have an integration over tau (not k*tau) and the ultra-spherical bessel function is normalised on k2,\n% we have to multiply the integrant with k2 (then it agrees with the flat case, see kb < 1e-5)\n             htable = src .* ul';\n             tetatl(i) = simpsint(ct4(1), ct4(end), htable);\n%plot(ct4, src', ct4, ul,'--', ct4, htable)\n%a1= simpsint(ct4(1), ct4(end), src)\n%tetatl(i)\n             src = ppval(pp2, k2(i));\n             htable = src .* ul';\n             tetael(i) = simpsint(ct4(1), ct4(end), htable);\n          else\n             tetatl(i) = 0;\n             tetael(i) = 0;\n          end\n\n       else  %if kb(i) <= 1e-5 *(1500/l)\n\n  % interpolate the spherical bessel function\n          kctc0 = ctc0 * k2(i) * ones(1, lct4);\n          kctc = k2(i) * ct4;\n          xctc = kctc0 - kctc;\n          jl = interpl(kx, table_bv, xctc)';\n% integrate the source function following (12) and (13) of Seljak resp (18) of Zaldarriaga and Seljak\n% the integration interval is limited to ct4 where the source <> 0\n          src = ppval(pp1, k2(i));\n          htable = src .* jl;\n          tetatl(i) = simpsint(ct4(1), ct4(end), htable);\n          src = ppval(pp2, k2(i));\n          htable = src .* jl;\n          tetael(i) = simpsint(ct4(1), ct4(end), htable);\n       end  %if kb(i)\n\n\n   end  % forloop k2\n\nta1 = tetatl;\nta2 = tetael;\nfactor = 1;\nf2 = 1;\n%if (K ~= 0),  f2 = coth(pi*k2/sqrt(-K)); end\nif  logstep == 1, factor = k2 * log(10) * ek2step * (lk2-1)/(k2max - k2min); end\n% perform the integration over k2min-k2max, following (9) of Seljak resp (19) of Zaldarriaga and Seljak\n%   cmbtable = (tetatl .^2) ./ (k2 .^ (2-nprimtilt));\n   cmbtable = factor .* f2 .* (tetatl .^2) .* (k2 ./ (k2 .^2 - K)) .^ (2 - nprimtilt);\n   cct.ctt(il) = l*(l + 1) * simpsint(k2min, k2max, cmbtable');\n%   cmbtable = (tetael .^2) ./ (k2 .^ (2-nprimtilt));\n   cmbtable = factor .* (tetael .^2) .* (k2 ./ (k2 .^2 - K)) .^ (2 - nprimtilt);\n   cct.cee(il) = gl^2 * l*(l + 1) * simpsint(k2min, k2max, cmbtable');\n%   cmbtable = (tetael .* tetatl) ./ (k2 .^ (2-nprimtilt));\n   cmbtable = factor .* (tetael .* tetatl) .* (k2 ./ (k2 .^2 - K)) .^ (2 - nprimtilt);\n   cct.cte(il) = l*(l + 1) * gl * simpsint(k2min, k2max, cmbtable');\n\nend  % forloop la\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8491-cmbaccur/srcint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303678, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5840992031187282}}
{"text": "num = size(AllFeature1,2);\nF1 = AllFeature1';\n% F1 = sqrt(F1);\nF1 = bsxfun(@rdivide, F1, sqrt(sum(F1.^2,2)));\nF1 = [F1 F11];\n% F1 = bsxfun(@minus,F1,PCAmap.mean);\n% F1 = F1 * PCAmap.M;\nF2 = AllFeature2';\n% F2 = sqrt(F2);\nF2 = bsxfun(@rdivide, F2, sqrt(sum(F2.^2,2)));\nF2 = [F2 F21];\n% F2 = bsxfun(@minus,F2,PCAmap.mean);\n% F2 = F2 * PCAmap.M;\n% F1 = AllFeature1';\n% F2 = AllFeature2';\nthresh2 = zeros(num,1);\nfor i = 1:num\n%     thresh2(i) = F1(i,:) * mapping.A * F1(i,:)' + F2(i,:) * mapping.A * F2(i,:)' - 2 * F1(i,:) * mapping.G * F2(i,:)';\n    thresh2(i) = pdist2(F1(i,:),F2(i,:));\n%     thresh2(i) = F1(i,:) * F2(i,:)';\nend;\nfigure;\nhist(thresh2(1:3000),500);\nfigure;\nhist(thresh2(3001:end),500);\n\naccuracies = zeros(10,1);\nfor i=1:10\n    test_idx = [(i-1) * 300 + 1 : i*300, (i-1) * 300 + 3001 : i*300 + 3000];\n    train_idx = 1:6000;\n    train_idx(test_idx) = [];\n    bestc=256;\n    same_label = ones(6000,1);\n    same_label(3001:6000) = 0;\n    % predicted_label = predict(double(lfw_label),sparse(thresh2),model);\n    cmd = [' -t 0 -h 0'];\n    model = svmtrain(same_label(train_idx),thresh2(train_idx),cmd);\n    % model = svmtrain(double(sim_label),thresh,cmd);\n    [class, accuracy, deci] = svmpredict(same_label(test_idx),thresh2(test_idx),model);\n    accuracies(i) = accuracy(1);\nend;\nmean(accuracies)\ncmd = [' -t 0 -h 0'];\nmodel = svmtrain(same_label,thresh2,cmd);\n[class, accuracy, deci] = svmpredict(same_label,thresh2,model);\n% mean(thresh2(same_label==1)) / 4 + mean(max(0,1 - thresh2(same_label==0))) / 4\n% sum((thresh2<0.22) == same_label) / 6000", "meta": {"author": "happynear", "repo": "FaceVerification", "sha": "c8c2b4d805abf7240d9d39d7b57151e04958f6bf", "save_path": "github-repos/MATLAB/happynear-FaceVerification", "path": "github-repos/MATLAB/happynear-FaceVerification/FaceVerification-c8c2b4d805abf7240d9d39d7b57151e04958f6bf/lfwEnsemble.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.584099195187008}}
{"text": "function [C] = spm_mc_loss_C(x,P)\n% cost function for the mountain car problem\n% problem\n% FORMAT [C] = spm_mc_loss_C(x,P)\n%\n% x     - hidden states\n% v     - exogenous inputs\n% P.x,k - parameters for gradient function:     G(x(1),P.p)\n% P.q,p - parameters for cost or loss-function: C(x(1),P.q)\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_mc_loss_C.m 3757 2010-03-08 11:41:53Z guillaume $\n \n \n% gradient (G) (quadratic potential = (x(1) - P.x)^2*P.k/2)\n%--------------------------------------------------------------------------\nC   = abs(x(1,:) - 1) > 1/4;\n\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_mc_loss_C.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.5840991793235677}}
{"text": "function [y,dzdg,dzdb] = vl_nnbnorm_old(x,g,b,varargin)\n% VL_NNBNORM  CNN batch normalisation\n%   Y = VL_NNBNORM(X,G,B) computes the batch normalization of the\n%   input X. This is defined as:\n%\n%      Y(i,j,k,t) = G(k) * (X(i,j,k,t) - mu(k)) / sigma(k) + B(k)\n%\n%   where\n%\n%      mu(k) = mean_ijt X(i,j,k,t),\n%      sigma(k) = sqrt(sigma2(k) + EPSILON),\n%      sigma2(k) = mean_ijt (X(i,j,k,t) - mu(k))^2\n%\n%   are respectively the per-channel mean, standard deviation, and\n%   variance of the input and G(k) and B(k) define respectively a\n%   multiplicative and additive constant to scale each input\n%   channel. Note that statistics are computed across all feature maps\n%   in the batch packed in the 4D tensor X. Note also that the\n%   constant EPSILON is used to regularize the computation of sigma(k)\n%\n%   [Y,DZDG,DZDB] = VL_NNBNORM(X,G,B,DZDY) computes the derviatives of\n%   the output Z of the network given the derivatives with respect to\n%   the output Y of this function.\n%\n%   VL_NNBNROM(..., 'Option', value) takes the following options:\n%\n%   `Epsilon`:: 1e-4\n%       Specify the EPSILON constant.\n%\n%   See also: VL_NNNORMALIZE().\n\n% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n% ISSUE - needs to store internal state, another reason for having classes?\n\n% -------------------------------------------------------------------------\n%                                                             Parse options\n% -------------------------------------------------------------------------\n\nopts.epsilon = 1e-4 ;\nbackMode = numel(varargin) > 0 && ~ischar(varargin{1}) ;\nif backMode\n  dzdy = varargin{1} ;\n  opts = vl_argparse(opts, varargin(2:end)) ;\nelse\n  opts = vl_argparse(opts, varargin) ;\nend\n\n% -------------------------------------------------------------------------\n%                                                                    Do job\n% -------------------------------------------------------------------------\n\nx_size = [size(x,1), size(x,2), size(x,3), size(x,4)] ;\ng_size = size(g) ;\nb_size = size(b) ;\ng = reshape(g, [1 x_size(3) 1]) ;\nb = reshape(b, [1 x_size(3) 1]) ;\nx = reshape(x, [x_size(1)*x_size(2) x_size(3) x_size(4)]) ;\n\nmass = prod(x_size([1 2 4])) ;\nmu = sum(sum(x,1),3) / mass  ;\ny = bsxfun(@minus, x, mu); % y <- x_mu\nsigma2 = sum(sum(y .* y,1),3) / mass + opts.epsilon ;\nsigma = sqrt(sigma2) ;\n\nif ~backMode\n  y = bsxfun(@plus, bsxfun(@times, g ./ sigma, y), b) ;\nelse\n  % remember: y contains x_mu\n  dzdy = reshape(dzdy, size(x)) ;\n  dzdg = sum(sum(dzdy .* y,1),3) ./ sigma ;\n  dzdb = sum(sum(dzdy,1),3) ;\n\n  muz = dzdb / mass;\n  y = ...\n    bsxfun(@times, g ./ sigma, bsxfun(@minus, dzdy, muz)) - ...\n    bsxfun(@times, g .* dzdg ./ (sigma2 * mass), y) ;\n\n  dzdg = reshape(dzdg, g_size) ;\n  dzdb = reshape(dzdb, b_size) ;\nend\n\ny = reshape(y, x_size) ;\nend\n", "meta": {"author": "willard-yuan", "repo": "cnn-for-image-retrieval", "sha": "2e3e8ab76e2c971314be55b5ae44e02884003261", "save_path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval/cnn-for-image-retrieval-2e3e8ab76e2c971314be55b5ae44e02884003261/matconvnet-1.0-beta18/matlab/xtest/vl_nnbnorm_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5840991731836527}}
{"text": "function out = drawFromIG(theta, chi)\n    [m, n] = size(theta);\n    chisq1 = randn(m, n).^2;\n    out = theta + 0.5*theta./chi .* (theta.*chisq1 - sqrt(4*theta.*chi.*chisq1 + theta.^2.*chisq1.^2) );\n    l = (rand(m, n) >= theta./(theta+out));\n    out(l) = theta(l).^2 ./ out(l);\nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/MBRMF/Utilities/drawFromIG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5840423447114043}}
{"text": "function fx2 = p02_fx2 ( x )\n\n%*****************************************************************************80\n%\n%% P02_FX2 evaluates the second derivative of the function for problem 2.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    07 May 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X, the abscissa.\n%\n%    Output, real FX2, the second derivative of the function at X.\n%\n  fx2 = - 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/test_zero/p02_fx2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.5839788290151638}}
{"text": "function b = r8vec_bracket5 ( nd, xd, xi )\n\n%*****************************************************************************80\n%\n%% R8VEC_BRACKET5 brackets data between successive entries of a sorted R8VEC.\n%\n%  Discussion:\n%\n%    We assume XD is sorted.\n%\n%    If XI is contained in the interval [XD(1),XD(N)], then the returned \n%    value B indicates that XI is contained in [ XD(B), XD(B+1) ].\n%\n%    If XI is not contained in the interval [XD(1),XD(N)], then B = -1.\n%\n%    This code implements a version of binary search which is perhaps more\n%    understandable than the usual ones.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 October 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer ND, the number of data values.\n%\n%    Input, real XD(N), the sorted data.\n%\n%    Input, real XD, the query value.\n%\n%    Output, integer B, the bracket information.\n%\n  if ( xi < xd(1) || xd(nd) < xi )\n\n    b = -1;\n\n  else\n\n    l = 1;\n    r = nd;\n\n    while ( l + 1 < r )\n      m = floor ( ( l + r ) / 2 );\n      if ( xi < xd(m) )\n        r = m;\n      else\n        l = m;\n      end\n    end\n\n    b = l;\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_bracket5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.5839788239410196}}
{"text": "function value = bmi_english ( w_lb, h_ft, h_in )\n\n%*****************************************************************************80\n%\n%% BMI_ENGLISH computes the body mass index given English measurements.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 October 2005\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real W_LB, the body weight in pounds.\n%\n%    Input, real H_FT, H_IN, the body height in feet and inches\n%\n%    Output, real VALUE, the body mass index.\n%\n  w_kg = pounds_to_kilograms ( w_lb );\n\n  h_m = feet_to_meters ( h_ft + ( h_in / 12.0 ) );\n\n  value = bmi_metric ( w_kg, h_m );\n\n  return\nend\n", "meta": {"author": "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/bmi_english.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.583978822249638}}
{"text": "%MAX2d\tMaximum of image\n%\n%\t[r,c] = max2d(image)\n%\n%\tReturn the interpolated coordinates (r,c) of the greatest peak in image.\n%\n% SEE ALSO:\tihough xyhough\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 <http://www.gnu.org/licenses/>.\n\n\nfunction [r,c,m] = max2d(im)\n\n\tncols = numcols(im);\n\tnrows = numrows(im);\n\n\t[mx,where] = max(im(:));\n\n    [r,c] = ind2sub(size(im), where);\n    \n    m = mx;\n    \n\t%[r,c,mx2]\n\t% now try to interpolate the peak over a 3x3 window\n\n\t% can't interpolate if against an edge\n\tif (c>1) & (c<ncols) & (r>1) & (r<nrows),\n\t\tdx = [\n\t\t\tc-1 c c+1\n\t\t\tc-1 c c+1\n\t\t\tc-1 c c+1];\n\t\tdy = [\n\t\t\tr-1 r-1 r-1\n\t\t\tr   r  r\n\t\t\tr+1   r+1  r+1];\n\n\t\tp = im(r-1:r+1,c-1:c+1);\n\t\tc = sum(sum(dx.*p)) / sum(sum(p));\n\t\tr = sum(sum(dy.*p)) / sum(sum(p));\n    end\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/max2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321796478256, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5839788205582567}}
{"text": "%% Pei&Lin Normalization\n% This program demonstrates Pei-Lin Normalization.\n%\n% Sources:\n%\n% * <https://github.com/opencv/opencv_contrib/blob/3.3.1/modules/ximgproc/samples/peilin.cpp>\n%\n\n%%\n% Source images\nfname1 = fullfile(mexopencv.root(), 'test', 'peilin_plane.png');\nfname2 = fullfile(mexopencv.root(), 'test', 'peilin_shape.png');\nif exist(fname1, 'file') ~= 2\n    disp('Downloading Image...')\n    url = 'https://cdn.rawgit.com/opencv/opencv_contrib/3.3.1/modules/ximgproc/samples/peilin_plane.png';\n    urlwrite(url, fname1);\nend\nif exist(fname2, 'file') ~= 2\n    disp('Downloading Image...')\n    url = 'https://cdn.rawgit.com/opencv/opencv_contrib/3.3.1/modules/ximgproc/samples/peilin_shape.png';\n    urlwrite(url, fname2);\nend\n\n%%\n% Load images\nI = cv.imread(fname1, 'Grayscale',true);\nJ = cv.imread(fname2, 'Grayscale',true);\n\n%%\n% Apply normalization\nN = cv.warpAffine(I, cv.PeiLinNormalization(I));\nD = cv.warpAffine(I, cv.PeiLinNormalization(J), 'WarpInverse',true);\n\n%%\n% Show results\nsubplot(221), imshow(I), title('I')\nsubplot(222), imshow(N), title('N')\nsubplot(223), imshow(J), title('J')\nsubplot(224), imshow(D), title('D')\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/samples/peilin_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.5839749983470454}}
{"text": "function jed = datenum_to_jed ( dn )\n\n%*****************************************************************************80\n%\n%% DATENUM_TO_JED converts a MATLAB date number to a JED.\n%\n%  Discussion:\n%\n%    The MATLAB \"datenum\" function accepts a string defining\n%    a date and returns a datenumber:\n%\n%      dn = datenum ( 'Aug 17 1939' )\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 January 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real DN, a MATLAB date number.\n%\n%    Output, real JED, the Julian Ephemeris Date.\n%\n  jed = dn + 1721058.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/calendar_nyt/datenum_to_jed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5839749977113973}}
{"text": "function V = se3ToVec(se3mat)\n% *** CHAPTER 3: RIGID-BODY MOTIONS ***\n% Takes se3mat a 4x4 se(3) matrix\n% Returns the corresponding 6-vector (representing spatial velocity).\n% Example Input:\n% \n% clear; clc;\n% se3mat = [[0, -3, 2, 4]; [3, 0, -1, 5]; [-2, 1, 0, 6]; [0, 0, 0, 0]];\n% V = se3ToVec(se3mat)\n% \n% Output:\n% V =\n%     1\n%     2\n%     3\n%     4\n%     5\n%     6\n\nV = [se3mat(3, 2); se3mat(1, 3); se3mat(2, 1); se3mat(1: 3, 4)];\nend", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/mr/se3ToVec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5839544314968148}}
{"text": "function[data,h,hc]=provec(varargin)\n%PROVEC  Generate progressive vector diagrams (simple and fancy).\n%\n%   Simple provecs:\n%\n%     PROVEC(DT,U,V) generates a simple progressive vector diagram plotting\n%     CUMSUM(U*DT) vs CUMSUM(V*DT).  U and V are column vectors, or \n%     matrices with time oriented in columns. DT is a scalar with units of \n%     of hours, while U and V must have units of cm/s.\n%  \n%     PROVEC(DT,CV), where CV=U+iV, also works.\n%\n%     INT=PROVEC(...) outputs the integrated dispacement INT in km.\n%\t \n%   Fancy provecs:\n%\n%     A fancy provec use SCATTER to plot the color and/or sizes of the \n%     points according to another parameter, say density or temperature. \n%     A colorbar is also plotted.\n%\n%     PROVEC(DT,U,V,C) uses C, of size SIZE(U), as the symbol color.\n%\n%     PROVEC(DT,U,V,C,S) also uses S, of size SIZE(U), as the symbol size. \n%\t\n%     PROVEC(DT,CV,C) and PROVEC(DT,CV,C,S) also work.\n%\n%     Note that since SCATTER is slow for large datasets, it is useful to\n%     decimate the data after CUMSUMing but before plotting.  This is \n%     accomplished using PROVEC(...,INDEX).  Then only the points \n%     INT(INDEX,:) of the integrated trajectory are plotted.\n%\n%     [INT,H,HC]=PROVEC returns the intergrated displacement INT, the\n%     handle H to the data, and the handle HC to the colorbar axis.\n%\n%   As an example,\n%  \n%          load bravo94\n%          th=100*detrend(bravo94.cat.th(:,3));\n%          [int,h,hc]=provec(1,bravo94.rcm.cv(:,3),th,20+0*th,[1:10:4000]);\n%          caxis([-8 8])\n%\n%   makes part of Figure 6b of Lilly and Rhines (2002) JPO.\n%         \n%   Usage: int=provec(dt,cv);\n%          [int,h,hc]=provec(dt,cv,c,index);\n%          [int,h,hc]=provec(dt,cv,c,s,index);\n%   _________________________________________________________________\n%   This is part of JLAB --- type 'help jlab' for more information\n%   (C) 1999--2017 J.M. Lilly --- type 'help jlab_license' for details        \n\n%          [int,h,hc]=provec(dcol,cv,c,s,index,deltat);\n%\n\n%   PROVEC(DCOL,...), where DCOL is a scalar or a row vector, specifies \n%   that the columns of the data are to be offset by amount DCOL after \n%   plotting, for both simple and fancy provecs.  \n%\n%   If DCOL is a scalar, then successive columns after the first are offset\n%   by amount -DCOL.  If DCOL is a row vector, then it specifies the offset\n%   for each column of the data.\n\n\ninunits=100;\noutunits=1000;\nfactor=100*1000/3600;\n\nbcolor=0;\ndefsize=5;\n\ndeltat=varargin{1};\nvarargin=varargin(2:end);\nna=length(varargin);\n\n%/********************************************************\n% %Look for initial row vector\noffs=0;\n% if isrow(varargin{1}) || isscalar(varargin{1});\n%   offs=varargin{1};\n%   na=na-1;\n%   varargin=varargin(2:end);\n% end\n% %\\********************************************************\n\n% if length(varargin{end})==1\n%   deltat=varargin{end};\n%   na=na-1;\n% end\n\nindex=[];\nif length(varargin{na})~=length(varargin{1})\n  index=varargin{na};\n  na=na-1;\nend\n\nc=[];\nif isreal(varargin{1})\n  data=varargin{1}+sqrt(-1)*varargin{2};\n  if na>2\n      c=varargin{3};\n  end\n  if na>3\n      s=varargin{4};\n  else\n      s=defsize+zeros(size(data));\n  end \nelse\n  data=varargin{1};\n  if na>1\n      c=varargin{2};\n  end\n  if na>2\n      s=varargin{3};\n  else\n      s=defsize+zeros(size(data));\n  end \nend\n\ndata=vswap(data,nan,0);\ndata=cumsum(data)*deltat/factor;\nif ~(length(offs)==1&&allall(abs(offs)==0))\n  if isscalar(offs)\n    offs=-(0:1:size(data,2)-1)*offs;\n  end\n  if length(offs)~=size(data,2)\n    error('Length of DCOL must equal number of columns of the data.')\n  end\n  for i=1:size(data,2)\n      data(:,i)=data(:,i)+offs(i);\n  end\nend\n\n\nif ~isempty(index)\n  data=data(index,:);\n  if ~isempty(c)\n    c=c(index,:);\n  end\n  if ~isempty(s)\n    s=s(index,:);\n  end\nend\n\n\nif isempty(c)\n\th=plot(data);\nelse \n\tbcolor=1;\n        vcolon(data,s,c);\n\tif any(isnan(s))\n\t  error('S cannot contain NANs.')\n\tend\n\tif any(isnan(c))\n\t  error('C cannot contain NANs.')\n\tend\n\th=scatter(real(data),imag(data),s,c,'filled');\nend\n\nxlabel('Displacement eastward (km)')\nylabel('Displacement northward (km)')\n\nset(gca,'box','on')\nset(gca,'dataaspectratio',[1 1 1])\npos=get(gca,'position');\n\n%put a colorbar if needed\nif bcolor\n\tax=gca;\n\thc=colorbar;\n\t%posc=get(hc,'position');\n\t%set(hc,'position',[posc(1) pos(2) posc(3) pos(4)])\n\t%the above doesn't take care of the relative size\n\t%problem--- instead, try to change aspect ratio\n\taxes(ax)\nend\n\nhold on\n\nif nargout ==0\n    clear data h hc\nend\n  \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/jGraph/provec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5839544290103013}}
{"text": "function [ n_data, a, x, fx ] = gamma_inc_p_values ( n_data )\n\n%*****************************************************************************80\n%\n%% GAMMA_INC_P_VALUES: values of the normalized incomplete Gamma function P(A,X)\n%\n%  Discussion:\n%\n%    The (normalized) incomplete Gamma function is defined as:\n%\n%      P(A,X) = 1/Gamma(A) * Integral ( 0 <= T <= X ) T^(A-1) * exp(-T) dT.\n%\n%    With this definition, for all A and X,\n%\n%      0 <= P(A,X) <= 1\n%\n%    and\n%\n%      P(A,oo) = 1.0\n%\n%    In Mathematica, the function can be evaluated by:\n%\n%      1 - GammaRegularized[A,X]\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    11 April 2010\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 A, the parameter of the function.\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  a_vec = [ ...\n     0.10E+00, ...\n     0.10E+00, ...\n     0.10E+00, ...\n     0.50E+00, ...\n     0.50E+00, ...\n     0.50E+00, ...\n     0.10E+01, ...\n     0.10E+01, ...\n     0.10E+01, ...\n     0.11E+01, ...\n     0.11E+01, ...\n     0.11E+01, ...\n     0.20E+01, ...\n     0.20E+01, ...\n     0.20E+01, ...\n     0.60E+01, ...\n     0.60E+01, ...\n     0.11E+02, ...\n     0.26E+02, ...\n     0.41E+02  ];\n\n  fx_vec = [ ...\n     0.7382350532339351E+00, ...\n     0.9083579897300343E+00, ...\n     0.9886559833621947E+00, ...\n     0.3014646416966613E+00, ...\n     0.7793286380801532E+00, ...\n     0.9918490284064973E+00, ...\n     0.9516258196404043E-01, ...\n     0.6321205588285577E+00, ...\n     0.9932620530009145E+00, ...\n     0.7205974576054322E-01, ...\n     0.5891809618706485E+00, ...\n     0.9915368159845525E+00, ...\n     0.1018582711118352E-01, ...\n     0.4421745996289254E+00, ...\n     0.9927049442755639E+00, ...\n     0.4202103819530612E-01, ...\n     0.9796589705830716E+00, ...\n     0.9226039842296429E+00, ...\n     0.4470785799755852E+00, ...\n     0.7444549220718699E+00 ];\n\n  x_vec = [ ...\n     0.30E-01, ...\n     0.30E+00, ...\n     0.15E+01, ...\n     0.75E-01, ...\n     0.75E+00, ...\n     0.35E+01, ...\n     0.10E+00, ...\n     0.10E+01, ...\n     0.50E+01, ...\n     0.10E+00, ... \n     0.10E+01, ...\n     0.50E+01, ...\n     0.15E+00, ...\n     0.15E+01, ...\n     0.70E+01, ...\n     0.25E+01, ...\n     0.12E+02, ...\n     0.16E+02, ...\n     0.25E+02, ...\n     0.45E+02 ];\n\n  if ( n_data < 0 )\n    n_data = 0;\n  end\n\n  n_data = n_data + 1;\n\n  if ( n_max < n_data )\n    n_data = 0;\n    a = 0.0;\n    x = 0.0;\n    fx = 0.0;\n  else\n    a = a_vec(n_data);\n    x = x_vec(n_data);\n    fx = fx_vec(n_data);\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/gamma_inc_p_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5839544277495181}}
{"text": "function res = gt(a,b)\n%GT           Implements  a > b  elementwise for intervals a and b\n%\n%  if true,  a  is definitely greater than  b\n%\n\n% written  10/16/98     S.M. Rump\n% modified 11/30/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%\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 = real(inf(a)) > real(sup(b)) & imag(inf(a)) > imag(sup(b)) ;\n  else\n    res = inf(a) > sup(b) ;\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/gt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5839544227414377}}
{"text": "function Show_Intensity(Seqs, id, para, options)\n\n\nHistory = [Seqs(id).Time; Seqs(id).Mark];\nM = round(options.Tmax./options.dt);\ntime_stamp = 0:options.dt:(M-1)*options.dt;\nlambda = zeros(size(para.A, 1), M);\n\nfor m = 1:M\n    lambda(:, m) = Intensity_HP(time_stamp(m), History, para);\nend\n \nset(gcf,'Color','w');\n\nfigure\nfor u = 1:size(para.A, 1)\n    subplot(1,size(para.A, 1),u)\n    ind = find(History(2,:) == u);\n    hold on\n    stem(History(1, ind), ones(1, length(ind)), 'Color', 'k', 'LineWidth', 2);\n    plot(time_stamp, lambda(u,:), 'Color', [0.8, 0, 0], 'LineWidth', 2);\n    hold off\n    ylabel('Intensity, \\lambda(t)')\n    xlabel(['Event-occurrence time (' num2str(length(ind)) ' events total)'])\nend\n    ", "meta": {"author": "HongtengXu", "repo": "Hawkes-Process-Toolkit", "sha": "2548a41c7418b8edef3261ab4479cee4e8eaf071", "save_path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit", "path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit/Hawkes-Process-Toolkit-2548a41c7418b8edef3261ab4479cee4e8eaf071/Visualization/Show_Intensity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5839544214806544}}
{"text": "% Load, modify and export a fig file as an eps file.\n\nclear all;\naddpath('../lib');\n\n%% lets plot 3 cycles of 50Hz AC voltage\nf = 50;  % frequency\nVm = 10; % peak\nphi = 0; % phase\n\n% generate the signal\nt = [0:0.0001:3/f];\nth = 2*pi*f*t;\nv = Vm*sin(th+phi);\n\n% plot it\nplt = Plot(t*1E3, v);\n\nplt.Title = 'Voltage as a function of time'; % plot title\nplt.XLabel = 'Time, t (ms)'; % xlabel\nplt.YLabel = 'Voltage, V (V)'; %ylabel\n\nplt.export('plotSimple1.png');\n\n    ", "meta": {"author": "masumhabib", "repo": "PlotPub", "sha": "2359dea0ca741a9541d569ea42e7ba1b1445e5f2", "save_path": "github-repos/MATLAB/masumhabib-PlotPub", "path": "github-repos/MATLAB/masumhabib-PlotPub/PlotPub-2359dea0ca741a9541d569ea42e7ba1b1445e5f2/examples_class/plotSimple.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5839544177333573}}
{"text": "function Loglike = Loglike_Basis( Seqs, model, alg )\n                                                        \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Learning Hawkes processes via maximum likelihood estimation\n% Different regularizers (low-rank, sparse, group sparse) of parameters and\n% their combinations are considered, which are solved via ADMM.\n%\n% Reference:\n% Xu, Hongteng, Mehrdad Farajtabar, and Hongyuan Zha. \n% \"Learning Granger Causality for Hawkes Processes.\" \n% International Conference on Machine Learning (ICML). 2016.\n%\n% Provider:\n% Hongteng Xu @ Georgia Tech\n% June. 10, 2017\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% initial \nAest = model.A;        \nmuest = model.mu;\n\n\n\n%D = size(Aest, 1);\n\n\ntic;\n\n        \nLoglike = 0; % negative log-likelihood\n\n\n\n% E-step: evaluate the responsibility using the current parameters    \nfor c = 1:length(Seqs)\n    Time = Seqs(c).Time;\n    Event = Seqs(c).Mark;\n    Tstart = Seqs(c).Start;\n\n    if isempty(alg.Tmax)\n        Tstop = Seqs(c).Stop;\n    else\n        Tstop = alg.Tmax;\n        indt = Time < alg.Tmax;\n        Time = Time(indt);\n        Event = Event(indt);\n    end\n\n    %Amu = Amu + Tstop - Tstart;\n\n    dT = Tstop - Time;\n    GK = Kernel_Integration(dT, model);\n\n    Nc = length(Time);\n\n    for i = 1:Nc\n\n        ui = Event(i);\n\n\n        ti = Time(i);             \n\n        lambdai = muest(ui);\n        %pii = muest(ui);\n        %pij = [];\n\n\n        if i>1\n\n            tj = Time(1:i-1);\n            uj = Event(1:i-1);\n\n            dt = ti - tj;\n            gij = Kernel(dt, model);\n            auiuj = Aest(uj, :, ui);\n            pij = auiuj .* gij;\n            lambdai = lambdai + sum(pij(:));\n        end\n\n        Loglike = Loglike - log(lambdai);\n\n    end\n\n    Loglike = Loglike + (Tstop-Tstart).*sum(muest);\n    Loglike = Loglike + sum( sum( GK.*sum(Aest(Event,:,:),3) ) );\n\n\n\nend\n\nLoglike = -Loglike;\n                \n        \n", "meta": {"author": "HongtengXu", "repo": "Hawkes-Process-Toolkit", "sha": "2548a41c7418b8edef3261ab4479cee4e8eaf071", "save_path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit", "path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit/Hawkes-Process-Toolkit-2548a41c7418b8edef3261ab4479cee4e8eaf071/Analysis/Loglike_Basis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5839544051956299}}
{"text": "function [mmHg] = Pa2mmHg(Pa)\n% Convert pressure from pascals to millimeters of mercury.\n% Chad Greene 2012\nmmHg = Pa*0.00750062;", "meta": {"author": "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/Pa2mmHg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5839029782920013}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright (C) 2010, John T. Ramshur, jramshur@gmail.com\n% \n% This file is part of HRVAS\n%\n% HRVAS 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% HRVAS 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 HRVAS.  If not, see <http://www.gnu.org/licenses/>.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction output = freqDomainHRV(ibi,VLF,LF,HF,AR_order,window, ...\n    noverlap,nfft,fs,methods,flagPlot)\n%freqDomainHRV - calculates freq domain HRV using FFT, AR, and Lomb-Scargle\n%methods\n%\n%Inputs:    ibi = 2Dim array of time (s) and inter-beat interval (s)\n%           AR_order = order of AR model\n%           window = # of samples in window\n%           noverlap = # of samples to overlap\n%           fs = cubic spline interpolation rate / resample rate (Hz)\n%           nfft = # of points in the frequency axis\n%           methods = cell array of strings that defines the methods used to\n%               calculate freqDomain. The default is all to use\n%               all three methods. \n%               methods={'welch','ar','lomb'}\n%           flagPlot = flag to tell function to plot PSD. 1=plot,\n%           0=don't plot, default is 0.\n%Outputs:   output is a structure containg all HRV. One field for each \n%           PSD method.\n%           Output units include:\n%               peakHF,LF,VLF (Hz)\n%               aHF,aLF,aVLF (ms^2)\n%               pHF,pLF,pVLF (%)\n%               nHF,nLF,nVLF (%)\n%               PSD (ms^2/Hz)\n%               F (Hz)\n%Usage:  (1) To compute freq. domain HRV on a ibi data set named dIBI \n%        using VLF=[0.0-0.16], LF =[0.16-0.6], HF=[0.6 3], \n%        AR model order = 16, welch window width = 256, \n%        # of overlap pnts in welch window (50%) = 128, # of pnts in fft = 512, \n%        IBI resample rate = 10Hz\n%        \n%        Use: output = freqDomainHRV(sampledata,[0 .16],[.16 .6],[.6 3], ...\n%                       16, 256, 128, 512, 10);\n%\n%        (2) To do the above and also plot all three power\n%        spectrum densities (PSD)\n%\n%        Use: output = freqDomainHRV(sampledata,[0 .16],[.16 .6],[.6 3], ...\n%                       16,256,128,512,10,{'welch','ar','lomb'},1);\n\n\n    %check input\n    if nargin<9\n        error('Not enough input arguments!')\n    elseif nargin<10\n        methods={'welch','ar','lomb'};\n        flagPlot=false;\n    elseif nargin<11\n        flagPlot=false;\n    end    \n    \n    flagWelch=false; flagAR=false; flagLomb=false;\n    for m=1:length(methods)\n        if strcmpi(methods{m},'welch')\n            flagWelch=true;\n        elseif strcmpi(methods{m},'ar')\n            flagAR=true;\n        elseif strcmpi(methods{m},'lomb')\n            flagLomb=true;\n        end\n    end \n    \n    t=ibi(:,1); %time (s)\n    y=ibi(:,2); %ibi (s)     \n    \n    y=y.*1000; %convert ibi to ms\n    %assumes ibi units are seconds\n    \n    maxF=fs/2;\n    \n    %prepare y\n    y=detrend(y,'linear');\n    y=y-mean(y);\n    \n    %Welch FFT\n    if flagWelch\n        [output.welch.psd,output.welch.f] = ...\n            calcWelch(t,y,window,noverlap,nfft,fs);\n        output.welch.hrv = ...\n            calcAreas(output.welch.f,output.welch.psd,VLF,LF,HF);\n    else\n        output.welch=emptyData(nfft,maxF);\n    end\n    \n    %AR\n    if flagAR\n        [output.ar.psd,output.ar.f]=calcAR(t,y,fs,nfft,AR_order);\n        output.ar.hrv=calcAreas(output.ar.f,output.ar.psd,VLF,LF,HF);\n    else\n        output.ar=emptyData(nfft,maxF);\n    end\n    \n    %Lomb\n    if flagLomb\n        [output.lomb.psd,output.lomb.f]=calcLomb(t,y,nfft,maxF);\n        output.lomb.hrv = ...\n            calcAreas(output.lomb.f,output.lomb.psd,VLF,LF,HF,true);\n    else\n        output.lomb=emptyData(nfft,maxF);\n    end\n    \n    %plot all three psd\n    if flagPlot\n    figure;\n    h1=subplot(3,1,1);\n    plotPSD(h1,output.welch.f,output.welch.psd,VLF,LF,HF,[0 0.6],[]);\n    legend('welch')\n    h2=subplot(3,1,2);\n    plotPSD(h2,output.ar.f,output.ar.psd,VLF,LF,HF,[0 0.6],[]);\n    legend('AR')\n    h3=subplot(3,1,3);\n    plotPSD(h3,output.lomb.f,output.lomb.psd,VLF,LF,HF,[0 0.6],[]);\n    legend('Lomb-Scargle')\n    end\nend\n\nfunction [PSD,F]=calcWelch(t,y,window,noverlap,nfft,fs)\n%calFFT - Calculates the PSD using Welch method.\n%\n%Inputs:\n%Outputs:\n    \n    %Prepare y\n    t2 = t(1):1/fs:t(length(t));%time values for interp.\n    y=interp1(t,y,t2','spline')'; %cubic spline interpolation\n    y=y-mean(y); %remove mean\n    \n    %Calculate Welch PSD using hamming windowing    \n    [PSD,F] = pwelch(y,window,noverlap,(nfft*2)-1,fs,'onesided'); \n    \nend\n\nfunction [PSD,F]=calcAR(t,y,fs,nfft,AR_order)\n%calAR - Calculates the PSD using Auto Regression model.\n%\n%Inputs:\n%Outputs:\n    \n    %Prepare y    \n    t2 = t(1):1/fs:t(length(t)); %time values for interp.\n    y=interp1(t,y,t2,'spline')'; %cubic spline interpolation\n    y=y-mean(y); %remove mean\n    y = y.*hamming(length(y)); %hamming window\n    \n    %Calculate PSD\n    %Method 1\n%     [A, variance] = arburg(y,AR_order); %AR using Burg method\n%     [H,F] = freqz(1,A,nfft,fs);\n%     PSD=(abs(H).^2).*(variance/fs); %malik, p.67    \n    %Method 2\n    [PSD,F]=pburg(y,AR_order,(nfft*2)-1,fs,'onesided');\n    %Method 3\n%      h=spectrum.burg;\n%      hpsd = psd(h, y, 'NFFT', nfft, 'Fs', 2);\n%      F=hpsd.Frequencies;\n%      PSD=hpsd.Data;\n     \nend\n\nfunction [PSD,F]=calcLomb(t,y,nfft,maxF)\n%calLomb - Calculates the PSD using Lomb-Scargle method.\n%\n%Inputs:\n%Outputs:\n        \n    %Calculate PSD\n    deltaF=maxF/nfft;\n    F = linspace(0.0,maxF-deltaF,nfft);\n    PSD=lomb2(y,t,F,false); %calc lomb psd\nend\n\nfunction output=calcAreas(F,PSD,VLF,LF,HF,flagNorm)\n%calcAreas - Calulates areas/energy under the PSD curve within the freq\n%bands defined by VLF, LF, and HF. Returns areas/energies as ms^2,\n%percentage, and normalized units. Also returns LF/HF ratio.\n%\n%Inputs:\n%   PSD: PSD vector\n%   F: Freq vector\n%   VLF, LF, HF: array containing VLF, LF, and HF freq limits\n%   flagNormalize: option to normalize PSD to max(PSD)\n%Output:\n%\n%Usage:\n%   \n%\n%   Modified from Gary Clifford's ECG Toolbox: calc_lfhf.m   \n\n    if nargin<6\n       flagNorm=false;\n    end\n    \n    %normalize PSD if needed\n    if flagNorm\n        PSD=PSD/max(PSD);\n    end\n\n    % find the indexes corresponding to the VLF, LF, and HF bands\n    iVLF= (F>=VLF(1)) & (F<=VLF(2));\n    iLF = (F>=LF(1)) & (F<=LF(2));\n    iHF = (F>=HF(1)) & (F<=HF(2));\n      \n    %Find peaks\n      %VLF Peak\n      tmpF=F(iVLF);\n      tmppsd=PSD(iVLF);\n      [pks,ipks] = zipeaks(tmppsd);\n      if ~isempty(pks)\n        [tmpMax i]=max(pks);        \n        peakVLF=tmpF(ipks(i));\n      else\n        [tmpMax i]=max(tmppsd);\n        peakVLF=tmpF(i);\n      end\n      %LF Peak\n      tmpF=F(iLF);\n      tmppsd=PSD(iLF);\n      [pks,ipks] = zipeaks(tmppsd);\n      if ~isempty(pks)\n        [tmpMax i]=max(pks);\n        peakLF=tmpF(ipks(i));\n      else\n        [tmpMax i]=max(tmppsd);\n        peakLF=tmpF(i);\n      end\n      %HF Peak\n      tmpF=F(iHF);\n      tmppsd=PSD(iHF);\n      [pks,ipks] = zipeaks(tmppsd);\n      if ~isempty(pks)\n        [tmpMax i]=max(pks);        \n        peakHF=tmpF(ipks(i));\n      else\n        [tmpMax i]=max(tmppsd);\n        peakHF=tmpF(i);\n      end \n      \n    % calculate raw areas (power under curve), within the freq bands (ms^2)\n    aVLF=trapz(F(iVLF),PSD(iVLF));\n    aLF=trapz(F(iLF),PSD(iLF));\n    aHF=trapz(F(iHF),PSD(iHF));\n    aTotal=aVLF+aLF+aHF;\n        \n    %calculate areas relative to the total area (%)\n    pVLF=(aVLF/aTotal)*100;\n    pLF=(aLF/aTotal)*100;\n    pHF=(aHF/aTotal)*100;\n    \n    %calculate normalized areas (relative to HF+LF, n.u.)\n    nLF=aLF/(aLF+aHF);\n    nHF=aHF/(aLF+aHF);\n    \n    %calculate LF/HF ratio\n    lfhf =aLF/aHF;\n            \n    %create output structure\n    if flagNorm\n        output.aVLF=round(aVLF*1000)/1000;\n        output.aLF=round(aLF*1000)/1000;\n        output.aHF=round(aHF*1000)/1000;\n        output.aTotal=round(aTotal*1000)/1000;\n    else\n        output.aVLF=round(aVLF*100)/100; % round\n        output.aLF=round(aLF*100)/100;\n        output.aHF=round(aHF*100)/100;\n        output.aTotal=round(aTotal*100)/100;\n    end    \n    output.pVLF=round(pVLF*10)/10;\n    output.pLF=round(pLF*10)/10;\n    output.pHF=round(pHF*10)/10;\n    output.nLF=round(nLF*1000)/1000;\n    output.nHF=round(nHF*1000)/1000;\n    output.LFHF=round(lfhf*1000)/1000;\n    output.peakVLF=round(peakVLF(1)*100)/100;\n    output.peakLF=round(peakLF(1)*100)/100;\n    output.peakHF=round(peakHF(1)*100)/100;\nend\n\nfunction plotPSD(aH,F,PSD,VLF,LF,HF,limX,limY)\n\n    color.vlf=[.5 .5 1];    %vlf color\n    color.lf=[.7 .5 1];     %lf color\n    color.hf=[.5 1 1];      %hf color\n\n    % find the indexes corresponding to the VLF, LF, and HF bands\n    iVLF= find( (F>=VLF(1)) & (F<VLF(2)) );\n    iLF = find( (F>=LF(1)) & (F<LF(2)) );\n    iHF = find( (F>=HF(1)) & (F<HF(2)) );\n\n    %plot area under PSD curve\n    area(aH,F(:),PSD(:),'FaceColor',[.8 .8 .8]);        \n    hold(aH);\n    area(aH,F(iVLF(1):iVLF(end)+1),PSD(iVLF(1):iVLF(end)+1), ...\n        'FaceColor',color.vlf);\n    area(aH,F(iLF(1):iLF(end)+1),PSD(iLF(1):iLF(end)+1), ...\n        'FaceColor',color.lf);\n    area(aH,F(iHF(1):iHF(end)+1),PSD(iHF(1):iHF(end)+1), ...\n        'FaceColor',color.hf);\n    \n    if ~isempty(limX)\n        set(aH,'xlim',limX)\n    else\n        limX=[min(F) max(F)];\n    end\n    if ~isempty(limY)\n        set(aH,'ylim',limY)\n    else\n        limY=[min(PSD) max(PSD)];\n    end\n    \n    %draw vertical lines around freq bands\n    line1=line([VLF(2) VLF(2)],[limY(1) limY(2)]);\n    set(line1,'color',[1 0 0],'parent',aH);\n    line2=line([LF(2) LF(2)],[limY(1) limY(2)]);\n    set(line2,'color',[1 0 0],'parent',aH);\n    line3=line([HF(2) HF(2)],[limY(1) limY(2)]);\n    set(line3,'color',[1 0 0],'parent',aH);\n   \n    hold(aH)\n        \nend\n\nfunction output=emptyData(nfft,maxF)\n%create output structure of zeros\n    \n    output.hrv.aVLF=0;\n    output.hrv.aLF=0;\n    output.hrv.aHF=0;\n    output.hrv.aTotal=0;\n    output.hrv.pVLF=0;\n    output.hrv.pLF=0;\n    output.hrv.pHF=0;\n    output.hrv.nLF=0;\n    output.hrv.nHF=0;\n    output.hrv.LFHF=0;\n    output.hrv.peakVLF=0;\n    output.hrv.peakLF=0;\n    output.hrv.peakHF=0;\n        \n    %PSD with all zeros\n    deltaF=maxF/nfft;    \n    output.f = linspace(0.0,maxF-deltaF,nfft);\n    output.psd=zeros(length(output.f),1);\n\nend\n\nfunction [pks locs]=zipeaks(y)\n%zippeaks: finds local maxima of input signal y\n%Usage:  peak=zipeaks(y);\n%Returns 2x(number of maxima) array\n%pks = value at maximum\n%locs = index value for maximum\n%\n%Reference:  2009, George Zipfel (Mathworks File Exchange #24797)\n\n%check dimentions\nif isempty(y)\n    Warning('Empty input array')\n    pks=[]; locs=[];\n    return\nend\n[rows cols] = size(y);\nif cols==1 && rows>1 %all data in 1st col\n    y=y';\nelseif cols==1 && rows==1 \n    Warning('Short input array')\n    pks=[]; locs=[];\n    return    \nend         \n    \n%Find locations of local maxima\n%yD=1 at maxima, yD=0 otherwise, end point maxima excluded\n    N=length(y)-2;\n    yD=[0 (sign(sign(y(2:N+1)-y(3:N+2))-sign(y(1:N)-y(2:N+1))-.1)+1) 0];\n%Indices of maxima and corresponding values of y\n    Y=logical(yD);\n    I=1:length(Y);\n    locs=I(Y);\n    pks=y(Y);\nend\n", "meta": {"author": "jramshur", "repo": "HRVAS", "sha": "ffe2465a0b8f8bf21bc78db474e5da4890761a44", "save_path": "github-repos/MATLAB/jramshur-HRVAS", "path": "github-repos/MATLAB/jramshur-HRVAS/HRVAS-ffe2465a0b8f8bf21bc78db474e5da4890761a44/freqDomainHRV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5839029782920013}}
{"text": "% Compute null space vanilla\nfunction [qd_null] = null_space_7dof(robot, q)\n%compute nil-space!!\nJ = manipulator_jacobian(robot, q);\nI = eye(robot.DOF);\nJp=pinv(J);\n%null space projector\n%n_space_projector = (I-Jp*J);\n%for an arbitrary vector\n%do not use [1 1 1 1]\nqd3 = [0 0 1 0 0 0 0]';\n%qd3 = q;\nqd_null = project(J, Jp, I, qd3);\n\nfunction qd_null = project(J, Jp, I, qd)\n%q2 est\ufffd calculado a trav\ufffds de un proyector (I-Jp*J),\n%, de tal manera que q2 pertenece al null space de J\nqd_null = (I-Jp*J)*qd;\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/SCO_v0.5/null_space_7dof.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5839029775916891}}
{"text": "function c = tapas_hgf_binary_pu_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the Hierarchical Gaussian Filter (HGF)\n% for binary inputs in the *presence* of perceptual uncertainty.\n%\n% The HGF is the model introduced in \n%\n% Mathys C, Daunizeau J, Friston, KJ, and Stephan KE. (2011). A Bayesian foundation\n% for individual learning under uncertainty. Frontiers in Human Neuroscience, 5:39.\n%\n% The binary HGF model has since been augmented with a positive factor kappa1 which\n% scales the second level with respect to the first, i.e., the relation between the\n% first and second level is\n%\n% p(x1=1|x2) = s(kappa1*x2), where s(.) is the logistic sigmoid.\n%\n% By default, kappa1 is fixed to 1, leading exactly to the model introduced in\n% Mathys et al. (2011).\n%\n% This file refers to BINARY inputs (Eqs 1-3 in Mathys et al., (2011));\n% for continuous inputs, refer to tapas_hgf_config.\n%\n% This file refers to UNCERTAIN inputs (Eqs 45-47 in Mathys et al., (2011));\n% for inputs without uncertainty, refer to tapas_hgf_binary_config.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% The HGF configuration consists of the priors of parameters and initial values. All priors are\n% Gaussian in the space where the quantity they refer to is estimated. They are specified by their\n% sufficient statistics: mean and variance (NOT standard deviation).\n% \n% Quantities are estimated in their native space if they are unbounded (e.g., the omegas). They are\n% estimated in log-space if they have a natural lower bound at zero (e.g., the sigmas).\n% \n% Parameters can be fixed (i.e., set to a fixed value) by setting the variance of their prior to\n% zero. Aside from being useful for model comparison, the need for this arises whenever the scale\n% and origin at the j-th level are arbitrary. This is the case if the observation model does not\n% contain the representations mu_j and sigma_j. A choice of scale and origin is then implied by\n% fixing the initial value mu_j_0 of mu_j and either kappa_j-1 or omega_j-1.\n%\n% Fitted trajectories can be plotted by using the command\n%\n% >> tapas_hgf_binary_plotTraj(est)\n% \n% where est is the stucture returned by tapas_fitModel. This structure contains the estimated\n% perceptual parameters in est.p_prc and the estimated trajectories of the agent's\n% representations (cf. Mathys et al., 2011). Their meanings are:\n%              \n%         est.p_prc.mu_0       row vector of initial values of mu (in ascending order of levels)\n%         est.p_prc.sa_0       row vector of initial values of sigma (in ascending order of levels)\n%         est.p_prc.rho        row vector of rhos (representing drift; in ascending order of levels)\n%         est.p_prc.ka         row vector of kappas (in ascending order of levels)\n%         est.p_prc.om         row vector of omegas (in ascending order of levels)\n%         est.p_prc.al         scalar alpha (perceptual uncertainty)\n%         est.p_prc.eta0       scalar eta0 (mean of first input category)\n%         est.p_prc.eta1       scalar eta1 (mean of second input category)\n%\n% Note that the first entry in all of the row vectors will be NaN because, at the first level,\n% these parameters are either determined by the second level (mu_0 and sa_0) or undefined (rho,\n% kappa, and omega).\n%\n%         est.traj.mu          mu (rows: trials, columns: levels)\n%         est.traj.sa          sigma (rows: trials, columns: levels)\n%         est.traj.muhat       prediction of mu (rows: trials, columns: levels)\n%         est.traj.sahat       precisions of predictions (rows: trials, columns: levels)\n%         est.traj.v           inferred variance of random walk (rows: trials, columns: levels)\n%         est.traj.w           weighting factors (rows: trials, columns: levels)\n%         est.traj.da          volatility prediction errors  (rows: trials, columns: levels)\n%         est.traj.ud          updates with respect to prediction  (rows: trials, columns: levels)\n%         est.traj.psi         precision weights on prediction errors  (rows: trials, columns: levels)\n%         est.traj.epsi        precision-weighted prediction errors  (rows: trials, columns: levels)\n%         est.traj.wt          full weights on prediction errors (at the first level,\n%                                  this is the learning rate) (rows: trials, columns: levels)\n%\n% Note that in the absence of sensory uncertainty (which is the assumption here), the first\n% column of mu, corresponding to the first level, will be equal to the inputs. Likewise, the\n% first column of sa will be 0 always.\n%\n% Tips:\n% - When analyzing a new dataset, take your inputs u and use\n%\n%   >> est = tapas_fitModel([], u, 'tapas_hgf_binary_pu_config', 'tapas_bayes_optimal_binary_config');\n%\n%   to determine the Bayes optimal perceptual parameters (given your current priors as defined in\n%   this file here, so choose them wide and loose to let the inputs influence the result). You can\n%   then use the optimal parameters as your new prior means for the perceptual parameters.\n%\n% - When analyzing a new dataset, take your inputs u and use\n%\n% - If you get an error saying that the prior means are in a region where model assumptions are\n%   violated, lower the prior means of the omegas, starting with the highest level and proceeding\n%   downwards.\n%\n% - Alternatives are lowering the prior means of the kappas, if they are not fixed, or adjusting\n%   the values of the kappas or omegas, if any of them are fixed.\n%\n% - If the log-model evidence cannot be calculated because the Hessian poses problems, look at\n%   est.optim.H and fix the parameters that lead to NaNs.\n%\n% - Your guide to all these adjustments is the log-model evidence (LME). Whenever the LME increases\n%   by at least 3 across datasets, the adjustment was a good idea and can be justified by just this:\n%   the LME increased, so you had a better model.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2017 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 <http://www.gnu.org/licenses/>.\n\n\n% Config structure\nc = struct;\n\n% Model name\nc.model = 'hgf_binary_pu';\n\n% Number of levels (minimum: 3)\nc.n_levels = 3;\n\n% Input intervals\n% If input intervals are irregular, the last column of the input\n% matrix u has to contain the interval between inputs k-1 and k\n% in the k-th row, and this flag has to be set to true\nc.irregular_intervals = false;\n\n% Sufficient statistics of Gaussian parameter priors\n\n% Initial mus and sigmas\n% Format: row vectors of length n_levels\n% For all but the first two levels, this is usually best\n% kept fixed to 1 (determines origin on x_i-scale). The \n% first level is NaN because it is determined by the second,\n% and the second implies neutrality between outcomes when it\n% is centered at 0.\nc.mu_0mu = [NaN, 0, 1];\nc.mu_0sa = [NaN, 0, 0];\n\nc.logsa_0mu = [NaN,   log(0.1), log(1)];\nc.logsa_0sa = [NaN,          0,      0];\n\n% Rhos\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\n% Fix this to zero to turn off drift.\nc.rhomu = [NaN, 0, 0];\nc.rhosa = [NaN, 0, 0];\n\n% Kappas\n% Format: row vector of length n_levels-1.\n% Fixing log(kappa1) to log(1) leads to the original HGF model.\n% Higher log(kappas) should be fixed (preferably to log(1)) if the\n% observation model does not use mu_i+1 (kappa then determines the\n% scaling of x_i+1).\nc.logkamu = [log(1), log(1)];\nc.logkasa = [     0,      0];\n\n% Omegas\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\nc.ommu = [NaN,  -3,  -6];\nc.omsa = [NaN, 4^2, 4^2];\n\n% Alpha\n% Format: scalar.\nc.logalmu = log(0.5);\nc.logalsa = 1;\n\n% Eta0\n% Format: scalar.\nc.eta0mu = 0;\nc.eta0sa = 0;\n\n% Eta1\n% Format: scalar.\nc.eta1mu = 1;\nc.eta1sa = 0;\n\n% Gather prior settings in vectors\nc.priormus = [\n    c.mu_0mu,...\n    c.logsa_0mu,...\n    c.rhomu,...\n    c.logkamu,...\n    c.ommu,...\n    c.logalmu,...\n    c.eta0mu,...\n    c.eta1mu,...\n         ];\n\nc.priorsas = [\n    c.mu_0sa,...\n    c.logsa_0sa,...\n    c.rhosa,...\n    c.logkasa,...\n    c.omsa,...\n    c.logalsa,...\n    c.eta0sa,...\n    c.eta1sa,...\n         ];\n\n% Check whether we have the right number of priors\nexpectedLength = 3*c.n_levels+2*(c.n_levels-1)+4;\nif length([c.priormus, c.priorsas]) ~= 2*expectedLength;\n    error('tapas:hgf:PriorDefNotMatchingLevels', 'Prior definition does not match number of levels.')\nend\n\n% Model function handle\nc.prc_fun = @tapas_hgf_binary_pu;\n\n% Handle to function that transforms perceptual parameters to their native space\n% from the space they are estimated in\nc.transp_prc_fun = @tapas_hgf_binary_pu_transp;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_binary_pu_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5839029620622728}}
{"text": "%==============================================================================\n% This code is part of the Finite Element Method app for the Matlab-based toolbox\n%  FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR/FAIRFEM \n%==============================================================================\n%\n% classdef TriMesh2 < handle\n%\n% Finite Element Mesh based on triangular subdivision of rectangular mesh.\n%\n% Each Cell is divided into two triangles:\n%\n%  o---------o---------o---------o---------o\n%  | \\       | \\       | \\       | \\       |\n%  |   \\     |   \\     |   \\     |   \\     |\n%  |     \\   |     \\   |     \\   |     \\   |\n%  |       \\ |       \\ |       \\ |       \\ |\n%  o---------o---------o---------o---------o\n%  | \\       | \\       | \\       | \\       |\n%  |   \\     |   \\     |   \\     |   \\     |\n%  |     \\   |     \\   |     \\   |     \\   |\n%  |       \\ |       \\ |       \\ |       \\ |\n%  o---------o---------o---------o---------o\n%  | \\       | \\       | \\       | \\       |\n%  |   \\     |   \\     |   \\     |   \\     |\n%  |     \\   |     \\   |     \\   |     \\   |\n%  |       \\ |       \\ |       \\ |       \\ |\n%  o---------o---------o---------o---------o\n%\n%  To construct an instance of this class type:\n%\n%  >> Mesh = TriMesh2(omega,m)\n%\n% Input:\n% \tomega - description of spatial domain\n%   m     - number of cells\n%\n% Properties:\n%   xn     - node list\n%   tri    - triangle list\n%   dim    - space dimension\n%   omega  - description of spatial domain\n%   m      - number of cells\n%   type   - type of partition\n%   vol    - volume of triangles\n%   nnodes - number of nodes\n%   ntri   - number of triangles\n%   dx1    - partial derivative operator\n%   dx2    - partial derivative operator\n%   GRAD   - gradient operator\n%   P1     - projection operator for node 1\n%   P2     - projection operator for node 2\n%   P3     - projection operator for node 3\n%   PC     - projection operator for Barycentrum\n%   P      - prolongation operator\n%   Pt     - restriction operator\n%\n%  Methods:\n%   mfPu   - matrix free prolongation/restriction\n%   mfPi   - matrix free edge projector\n%   getP   - builds prolongation operator\n%   tri2cc - averaging\n%\n%\n% see also\n% =========================================================================\nclassdef TriMesh2 < handle\n    \n    properties\n        % ===================================\n        % node list\n        % ===================================\n        xn\n        % ===================================\n        % triangle list\n        % ===================================\n        tri\n        % ===================================\n        % space dimension\n        % ===================================\n        dim  = 2;\n        % ===================================\n        % description of computational domain\n        % ===================================\n        omega\n        % ===================================\n        % number of cells\n        % ===================================\n        m\n        % ===================================\n        % type of partition\n        % ===================================\n        type = 1;\n        % ===================================\n        % function handle to myself\n        % ===================================\n        me = @TriMesh2\n        % ===================================\n        % volume of triangles\n        % ===================================\n        vol\n        % ===================================\n        % number of nodes\n        % ===================================\n        nnodes\n        % ===================================\n        % number of triangles in mesh\n        % ===================================\n        ntri\n    end\n    \n    properties (Access = public, Dependent) % These will be created when first callend and stores persistently\n        % ===================================\n        % dx1  - partial derivative operator\n        % ===================================\n        dx1\n        % ===================================\n        % dx2  - Partial derivative operator\n        % ===================================\n        dx2\n        % ===================================\n        % GRAD - Gradient operator\n        %\n        %         | dx1 |\n        %  GRAD = |     |\n        %         | dx2 |\n        %\n        % ===================================\n        GRAD\n        % ===================================\n        % B - Vector gradient operator\n        %\n        %         | GRAD  0    |\n        %  B =    |            |\n        %         | 0     GRAD |\n        %\n        % ===================================\n        B\n        % ===================================\n        % P1 - Projection operator on Node 1\n        % ===================================\n        P1\n        % ===================================\n        % P2 - Projection operator on Node 2\n        % ===================================\n        P2\n        % ===================================\n        % P3 - Projection operator on Node 3\n        % ===================================\n        P3\n        % ===================================\n        % PC - Projection operator on Barycenter\n        % ===================================\n        PC\n        % ===================================\n        % P  - Prolongation operator\n        % ===================================\n        P\n        % ===================================\n        % Pt - Restriction operator\n        % ===================================\n        Pt\n        % ===================================\n        % Boundary indices\n        % ===================================\n        boundaryIdx\n        % ===================================\n        % Boundary projector\n        % ===================================\n        boundaryProj\n        mfdx1\n        mfdx2\n        mfGRAD\n    end\n    \n    properties (Access = private)\n        % These are where the dependent data is actually stored\n        dx1_\n        dx2_\n        GRAD_\n        B_\n        P1_\n        P2_\n        P3_\n        PC_\n        P_\n        Pt_\n        mfdx1_\n        mfdx2_\n        mfGRAD_\n        boundaryIdx_\n        boundaryProj_\n    end\n    \n    methods\n        function this = TriMesh2(omega,m)\n            if nargin==0,\n                help(mfilename);\n                this.runMinimalExample;\n                return;\n            end\n            this.omega = omega;\n            this.m     = m;\n            \n            this.xn = reshape(getNodalGrid(omega,m),[],2);\n            % get indices of bottom left vertices\n            nodes = reshape(1:prod(m+1),m+1);\n            nodes = reshape(nodes(1:end-1,1:end-1),1,[]);\n            % specify triangles\n            this.tri   = [nodes; nodes+1; nodes+m(1)+1; nodes+m(1)+2; nodes+m(1)+1; nodes+1];\n            this.tri   = reshape(this.tri,3,[])';\n            this.nnodes = prod(m+1);\n            this.ntri  = size(this.tri,1);\n            this.vol = prod((omega(2:2:end)-omega(1:2:end))./m)/2*ones(this.ntri,1);\n        end\n        \n        function runMinimalExample(~)\n            omega = [0 4 2 6]; m = [8 16];\n            Mesh  = feval(mfilename,omega,m);\n        end\n        \n        function x = mfPi(this,x,i)\n            % =============================================================\n            % function x = mfPi(this,x,i)\n            %\n            % matrix free edge projector\n            % =============================================================\n            switch i\n                case 1\n                    P = this.P1;\n                case 2\n                    P = this.P2;\n                case 3\n                    P = this.P3;\n                case 'C'\n                    P = this.PC;\n            end\n            if size(x,1) == this.ntri,\n                % ajoint\n                x = P'*x;\n            else\n                x = P * x;\n            end\n        end\n        \n        function x = tri2cc(this,x)\n            % =============================================================\n            % function x = tri2cc(x)\n            %\n            % averaging or adjoint\n            % =============================================================\n            if numel(x)==this.ntri,\n                x = mean(reshape(x,2,[]),1);\n            else\n                x = reshape(x,1,[]);\n                x = .5*[x;x];\n                x = x(:);\n            end\n            \n        end\n        \n        \n        \n        function Pu = mfPuNodal(~,yn,m,flag)\n            % =============================================================\n            % function Pu = mfPuNodal(~,yn,m,flag)\n            %\n            % matrix free prolongation/restriction for nodal quantities\n            % =============================================================\n            d  = numel(yn)/prod(m+1);\n            yn = reshape(yn,[m+1, d]);\n            switch flag\n                case 'Pu' % coarse --> fine\n                    yn = reshape(yn,[m+1 2]);\n                    Pu = zeros([2*m+1 2]);\n                    \n                    % include existing nodes\n                    Pu(1:2:end,1:2:end,:) = yn;\n                    % prolongate in x direction\n                    Pu(2:2:end-1,:,:) =  .5*(Pu(1:2:end-2,:,:) + Pu(3:2:end,:,:));\n                    % prolongate in y direction\n                    Pu(1:2:end,2:2:end-1,:) =  .5*(Pu(1:2:end,1:2:end-2,:) + Pu(1:2:end,3:2:end,:));\n                    % prolongate diagonal\n                    Pu(2:2:end,2:2:end,:) = .5* (Pu(3:2:end,1:2:end-2,:) + Pu(1:2:end-2,3:2:end,:));\n                    \n                    Pu = reshape(Pu,[],1);\n                case 'PTu'\n                    yn = reshape(yn,[m+1 2]);\n                    \n                    % include parent nodes\n                    Pu = yn(1:2:end,1:2:end,:);\n                    \n                    % distribute in x direction\n                    t = .5* yn(2:2:end-1,1:2:end,:);\n                    Pu(1:end-1,:,:) = Pu(1:end-1,:,:) + t;\n                    Pu(2:end,:,:)   = Pu(2:end,:,:) + t;\n                    \n                    % distribute in y direction\n                    t = .5* yn(1:2:end,2:2:end-1,:);\n                    Pu(:,1:end-1,:) = Pu(:,1:end-1,:) + t;\n                    Pu(:,2:end,:) = Pu(:,2:end,:) + t;\n                    \n                    % distribute diagonal\n                    t = .5* yn(2:2:end-1,2:2:end-1,:);\n                    Pu(2:end,1:end-1,:) = Pu(2:end,1:end-1,:) + t;\n                    Pu(1:end-1,2:end,:) = Pu(1:end-1,2:end,:) + t;\n                    \n                    Pu = reshape(Pu,[],1);\n            end\n        end\n        \n        function P = getPuNodal(~,m)\n            % =============================================================\n            % function P = getPuNodal(~,m)\n            %\n            % returns prolongation operator for input of cell-width m\n            % =============================================================\n            \n            mf = 2*m;\n            % indices of fine and coarse grid nodes\n            indf = reshape(1:prod(mf+1),mf+1);\n            indc = reshape(1:prod(m+1),m+1);\n            \n            % allocate space\n            I = []; J = []; W = [];\n            \n            % include existing nodes\n            ii = indf(1:2:end,1:2:end);\n            jj = indc(:);\n            ww = ones(size(jj));\n            I = [I; ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            \n            % prolongate in x direction\n            ii   = indf(2:2:end-1,1:2:end);\n            jj   = [reshape(indc(1:end-1,:),[],1); reshape(indc(2:end,:),[],1)];\n            ww = .5*ones(size(jj));\n            I = [I; ii(:);ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            \n            % prolongate in y direction\n            ii   = indf(1:2:end,2:2:end-1);\n            jj   = [reshape(indc(:,1:end-1),[],1); reshape(indc(:,2:end),[],1)];\n            ww   = .5*ones(size(jj));\n            I = [I; ii(:); ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            \n            % prolongate diagonally\n            ii   = indf(2:2:end-1,2:2:end-1);\n            jj   = [reshape(indc(1:end-1,2:end),[],1); reshape(indc(2:end,1:end-1),[],1)];\n            ww   = .5*ones(size(jj));\n            I = [I; ii(:);ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            \n            \n            P = sparse(I,J,W,prod(mf+1),prod(m+1));\n            \n        end\n        \n        \n        \n        % ========== get methods ========================================\n        function dx1 = get.dx1(this)\n            if isempty(this.dx1_),\n                [this.dx1_, this.dx2_] = getGradientMatrixFEM(this,0);\n            end\n            dx1 = this.dx1_;\n        end\n        \n        function dx2 = get.dx2(this)\n            if isempty(this.dx2_),\n                [this.dx1_, this.dx2_] = getGradientMatrixFEM(this,0);\n            end\n            dx2 = this.dx2_;\n        end\n        \n        function GRAD = get.GRAD(this)\n            if isempty(this.GRAD_),\n                this.GRAD_ = [this.dx1;this.dx2];\n            end\n            GRAD = this.GRAD_;\n        end\n        function B = get.B(this)\n            if isempty(this.B_),\n                this.B_ = blkdiag(this.GRAD,this.GRAD);\n            end\n            B = this.B_;\n        end\n        \n        function P1 = get.P1(this)\n            if isempty(this.P1_),\n                A = speye(this.nnodes);\n                this.P1_ = A(this.tri(:,1),:);\n            end\n            P1 = this.P1_;\n        end\n        function P2 = get.P2(this)\n            if isempty(this.P2_),\n                A = speye(this.nnodes);\n                this.P2_ = A(this.tri(:,2),:);\n            end\n            P2 = this.P2_;\n        end\n        \n        function P3 = get.P3(this)\n            if isempty(this.P3_),\n                A = speye(this.nnodes);\n                this.P3_ = A(this.tri(:,3),:);\n            end\n            P3 = this.P3_;\n        end\n        function PC = get.PC(this)\n            if isempty(this.PC_),\n                this.PC_ = (this.P1+this.P2+this.P3)/3;\n            end\n            PC = this.PC_;\n        end\n        function P = get.P(this)\n            if isempty(this.P_),\n                this.P_ = this.getPuNodal(this.m);\n            end\n            P = this.P_;\n        end\n        function Pt = get.Pt(this)\n            if isempty(this.Pt_),\n                this.Pt_ = this.getPuNodal(this.m/2);\n            end\n            Pt = this.Pt_;\n        end\n        \n        function mfdx1 = get.mfdx1(this)\n            if isempty(this.mfdx1_),\n                [this.mfdx1_, this.mfdx2_] = getGradientMatrixFEM(this,1);\n            end\n            mfdx1 = this.mfdx1_;\n        end\n        \n        function mfdx2 = get.mfdx2(this)\n            if isempty(this.mfdx2_),\n                [this.mfdx1_, this.mfdx2_] = getGradientMatrixFEM(this,1);\n            end\n            mfdx2 = this.mfdx2_;\n        end\n        \n        function mfGRAD = get.mfGRAD(this)\n            if isempty(this.mfGRAD_),\n                this.mfGRAD_ = getGradientMatrixFEM(this,1);\n            end\n            mfGRAD = this.mfGRAD_;\n        end\n        \n        function idx = get.boundaryIdx(this)\n            if isempty(this.boundaryIdx_),\n                id = reshape(1:prod(this.m+1),this.m+1);\n                idx = [reshape(id([1,end],:),[],1);reshape(id(2:end-1,[1,end]),[],1)] ;\n                this.boundaryIdx_ = idx;\n            end\n            idx = this.boundaryIdx_;\n        end\n        \n        function idx = get.boundaryProj(this)\n            if isempty(this.boundaryProj_),\n                idx = this.boundaryIdx;\n                \n                P = speye(prod(this.m+1));\n                P = P(idx,:);\n                P = kron(speye(2),P);\n                \n                this.boundaryProj_ = P;\n            end\n            idx = this.boundaryProj_;\n        end\n        \n        % ========== set methods ========================================\n        function set.xn(this,xn)\n            if numel(xn)~=(2*prod(this.m+1)),\n                error('Invalid number of nodes');\n            end\n            if isempty(this.xn),\n                this.xn = xn;\n            else\n                \n                this.xn = xn;\n                % delete operators that are sensitive to nodes\n                this.dx1_  = [];\n                this.dx2_  = [];\n                this.GRAD_ = [];\n                this.B_    = [];\n                \n                this.vol = volTetraGrid(this,this.xn,'matrixFree',1);\n            end\n        end\n    end\nend\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/add-ons/FAIRFEM/meshes/TriMesh2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5838823353541304}}
{"text": "function p_ = ViewRanking(X,p,Lower,Upper)\n\n[J,N]=size(X);\nK=length(Lower);\n\n% constrain probabilities to sum to one...\nAeq = ones(1,J);  \nbeq=1;\n\n% ...constrain the expectations...\nV=X(:,Lower) - X(:,Upper);\n\nA = V';\nb = 0;\n\n% ...compute posterior probabilities\np_ = EntropyProg(p,A,b,Aeq ,beq); ", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21307-fully-flexible-views-and-stress-testing/EntropyPooling/RankingInformation/ViewRanking.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5838823279737804}}
{"text": "clear;\nclc;\nclose all;\n\n\n\n\nRP = [ -2175464.65976786          4387261.15978363          4072912.71678943]';\nSP = [  15987741.24878          3203328.88432069          21122447.2672636]';\n\nthis_TOW = 225119;\n\n\n\n[lat,  lon, h] = ch_ECEF2LLA(RP);\n[az, el] = satellite_az_el(SP, RP);\n\nel = linspace(0.1, pi*0.9, 100);\n\n dtrop = tropo_correction(el, 1*1000);\n\nplot(dtrop)\ntitle(\"\u5bf9\u6d41\u5c42\u8bef\u5dee\");\nylabel(\"m\");\n\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/gps_spp_test/example5_\u5bf9\u6d41\u5c42\u8bef\u5dee/trop_corr_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5838653238483474}}
{"text": "function [Q_matrix] = adapt_noise_covariance(Phi_matrix, P_new, P_old, Q_matrix, n, GNSS_epoch, corrections)\n%% Adapt Q matrix to system noise\n% Adjust measurement noise covariance matrix Q according to state correction sequence\n% Adam Werries 2016, see Apache 2.0 license.\n\n%% Mohamed and Schwarz method, 1999\nk = GNSS_epoch-1;\nif k > n\n    C = zeros(15,15);\n    for j = k-n+1:k\n        C = C + corrections(:,j)*corrections(:,j)';\n    end\n    Q_matrix = C./n + P_new - Phi_matrix*P_old*Phi_matrix';\n    Q_matrix = diag(diag(Q_matrix));\nelse\n    \nend\n    \n%% Ding and Wang method, 2007\n% TODO\n\n\nend", "meta": {"author": "awerries", "repo": "kalman-localization", "sha": "558ca7fae1779aa71da61ec4829299bbbdbf62ff", "save_path": "github-repos/MATLAB/awerries-kalman-localization", "path": "github-repos/MATLAB/awerries-kalman-localization/kalman-localization-558ca7fae1779aa71da61ec4829299bbbdbf62ff/MATLAB/adapt_noise_covariance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.5838653189644938}}
{"text": "function varargout = cosh(varargin)\n%COSH (overloaded)\n\nswitch class(varargin{1})\n\n    case 'double'\n        error('Overloaded SDPVAR/COSH CALLED WITH DOUBLE. Report error')\n\n    case 'sdpvar'\n        varargout{1} = InstantiateElementWise(mfilename,varargin{:});\n\n    case 'char'\n\n        operator = struct('convexity','none','monotonicity','none','definiteness','positive','model','callback');\n        operator.convexhull = [];\n        operator.bounds = @bounds;\n        operator.derivative = @(x)(sinh(x));\n\n        varargout{1} = [];\n        varargout{2} = operator;\n        varargout{3} = varargin{3};\n\n    otherwise\n        error('SDPVAR/COSH called with CHAR argument?');\nend\n\nfunction [L,U] = bounds(xL,xU)\nif xL<0 & xU>0\n    L = 0;\n    U = max([cosh(xL) cosh(xU)]);\nelseif xL<0\n    L = cosh(xU);\n    U = cosh(xL);\nelse\n    L = cosh(xL);\n    U = cosh(xU);\nend\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/@sdpvar/cosh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.583865318265883}}
{"text": "function marginal = marginal_nodes(engine, query, add_ev)\n% MARGINAL_NODES Compute the marginal on the specified query nodes (cond_gauss)\n% marginal = marginal_nodes(engine, query, add_ev)\n%\n% 'query' must be a singleton set\n% add_ev is an optional argument; if 1, we will \"inflate\" the marginal of observed nodes\n% to their original size, adding 0s to the positions which contradict the evidence\n\nif nargin < 3, add_ev = 0; end\n\nif length(query) ~= 1\n  error('cond_gauss_inf_engine can only handle marginal queries on single nodes')\nend\nj = query;\nbnet = bnet_from_engine(engine);\n\nif myismember(j, bnet.cnodes)\n  if ~myismember(j, engine.onodes)\n    [m, C] = collapse_mog(engine.mu{j}, engine.Sigma{j}, engine.T);    \n    marginal.mu = m;\n    marginal.Sigma = C;\n    marginal.T = 1.0; % single mixture component\n  else\n    marginal.mu = engine.evidence{j};\n    k = bnet.node_sizes(j);\n    marginal.Sigma = zeros(k,k);\n    marginal.T = 1.0; % since P(E|E)=1\n  end\nelse\n  marginal = pot_to_marginal(marginalize_pot(engine.joint_dmarginal, j));\n  if add_ev\n    marginal = add_ev_to_dmarginal(marginal, engine.evidence, bnet.node_sizes);\n  end\nend\n\nmarginal.domain = query;\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/inference/static/@cond_gauss_inf_engine/marginal_nodes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5838653182658828}}
{"text": "function L = obslikebernoulli(X,hmm)\n%\n% Evaluate likelihood of data given observation model, for one continuous trial\n%\n% INPUT\n% X          N by ndim data matrix\n% hmm        hmm data structure\n%\n% OUTPUT\n% B          Likelihood of N data points\n%\n% Author: Cam Higgins, OHBA, University of Oxford\n\nK = hmm.K;\n[T,ndim] = size(X);\n\nL = zeros(T,K);  \n\nfor k=1:K\n    % expectation of log(p) is psi(a) - psi(a+b):\n    pterm = X .* repmat( psi(hmm.state(k).W.a) - psi(hmm.state(k).W.a + hmm.state(k).W.b) ,T,1);\n    qterm = (~X) .* repmat(psi(hmm.state(k).W.b) - psi(hmm.state(k).W.a + hmm.state(k).W.b) ,T,1);\n    L(:,k) = sum(pterm+qterm,2);\nend\n\nL = exp(L);\nend\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/train/obslikebernoulli.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.58386531408064}}
{"text": "function y = nbBernPred(model, X)\n% Prediction of naive Bayes classifier with independent Bernoulli.\n% input:\n%   model: trained model structure\n%   X: d x n data matrix\n% output:\n%   y: 1 x n predicted class label\n% Written by Mo Chen (sth4nth@gmail.com).\nmu = model.mu;\nw = model.w;\n[~,y] = max(log(mu)'*X+log(1-mu)'*(1-X)+log(w(:)),[],1);\n\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter08/NaiveBayes/nbBernPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5838653126834183}}
{"text": "function pde = jumpmgdata1\n%% Data of JUMPMG1\n%\n% Copyright (C)  Long Chen. See COPYRIGHT.txt for details.\n\npde = struct('f',@f,'g_D',@g_D,'d',@omega);\n\n    function s = f(p) % load data (right hand side function)\n    s = zeros(size(p,1),1);\n    end\n\n    function s = g_D(p) % Dirichlet boundary condition\n    s = zeros(size(p,1),1);\n    x = p(:,1); \n    idx = (abs(x-1)<eps);\n    s(idx) = 1;\n    s(~idx) = 0;\n    end\n\n    function c = omega(p) % diffusion constant\n    global epsilon\n    c = zeros(size(p,1),1);\n    x = p(:,1); y = p(:,2); z = p(:,3);\n    idx = (x>0) & (x<1) & (y>0) & (y<1) & (z>0) & (z<1);\n    c(idx) = 1/epsilon;\n    c(~idx) = 1;\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/jumpmgdata1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5838653084981756}}
{"text": "function value = r8vec_any_nonzero ( n, a )\n\n%*****************************************************************************80\n%\n%% R8VEC_ANY_NONZERO: ( any A nonzero ) for R8VEC's.\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%    25 December 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the number of entries.\n%\n%    Input, real A(N), the vector.\n%\n%    Output, logical R8VEC_ANY_NONZERO is TRUE if any entry is nonzero.\n%\n  value = any ( a(1:n) ~= 0.0 );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_any_nonzero.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.5838653065786015}}
{"text": "function Population = EnvironmentalSelection(Population,W,N)\n% The environmental selection of MOEA/IGD-NS\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    %% Non-dominated sorting\n    [FrontNo,MaxFNo] = NDSort(Population.objs,N);\n    Next = FrontNo < MaxFNo;\n    \n    %% Select the solutions in the last front\n    Last   = find(FrontNo==MaxFNo);\n    Choose = LastSelection(Population(Last).objs,W,N-sum(Next));\n    Next(Last(Choose)) = true;\n    % Population for next generation\n    Population = Population(Next);\nend\n\nfunction Remain = LastSelection(PopObj,W,K)\n% Select part of the solutions in the last front\n\n    N  = size(PopObj,1);\n    NW = size(W,1);\n\n    %% Calculate the distance between each solution and point\n    Distance = pdist2(PopObj,W);\n    Con      = min(Distance,[],2);\n    \n    %% Delete the solution which has the smallest metric contribution one by one\n    [dis,rank] = sort(Distance,1);\n    Remain     = true(1,N);\n    while sum(Remain) > K\n        % Calculate the fitness of outliers\n        Outliers = Remain;\n        Outliers(rank(1,:)) = false;\n        METRIC   = sum(dis(1,:)) + sum(Con(Outliers));\n        Metrics  = inf(1,N);\n        Metrics(Outliers) = METRIC - Con(Outliers);\n        % Calculate the fitness of other solutions\n        for p = find(Remain & ~Outliers)\n            temp = rank(1,:) == p;\n            outliers = false(1,N);\n            outliers(rank(2,temp)) = true;\n            outliers = outliers & Outliers;\n            Metrics(p) = METRIC - sum(dis(1,temp)) + sum(dis(2,temp)) - sum(Con(outliers));\n        end\n        % Delete the worst solution and update the variables\n        [~,del] = min(Metrics);\n        temp = rank ~= del;\n        dis  = reshape(dis(temp),sum(Remain)-1,NW);\n        rank = reshape(rank(temp),sum(Remain)-1,NW);\n        Remain(del) = false;\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/MOEA-IGD-NS/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5838652973332465}}
{"text": "function [x, infos] = palm_sparse_smooth_nmf(V, rank, in_options)\n% PALM framework with smoothness and sparsity constraints for non-negative\n% matrix factorization (PALM-Sparse-Smooth-NMF)\n%\n% The problem of interest is defined as\n%\n%           min || WH - V ||_F^2 + lambda * || W ||_1 + eta || HT ||_F^2 \n%                                   + betaW ||W||_F^2 + betaH ||H||_F^2,\n%           where \n%           {V, W, H} >= 0, \n%\n%           Algorithm for NMF with eucidian norm as objective function and \n%           L1 constraint on W for sparse paterns and Tikhonov regularization \n%           for smooth activation coefficients.\n%\n% Inputs:\n%       matrix      V\n%       rank        rank\n%       options     options\n%           lambda      weight for the L1 sparsity penalty (default: 0)\n%           eta         weight for the smoothness constraint.\n%           gamma1: \tconstant > 1 for the gradient descend step of W.\n%           gamma2:     constant > 1 for the gradient descend step of W.\n%           betaH:      constant. L-2 constraint for H.\n%           betaW:      constant. L-2 constraint for W.\n% Output:\n%       w           solution of w\n%       infos       information\n%\n% References:\n%    \n%\n% This file is part of NMFLibrary.\n%\n% This file has been ported from \n%       palm_nmf.m at https://github.com/raimon-fa/palm-nmf\n%\n%{\nThe MIT License\nCopyright (c) 2017 Raimon Fabregat\nPermission is hereby granted, free of charge, \nto any person obtaining a copy of this software and \nassociated documentation files (the \"Software\"), to \ndeal in the Software without restriction, including \nwithout limitation the rights to use, copy, modify, \nmerge, publish, distribute, sublicense, and/or sell \ncopies of the Software, and to permit persons to whom \nthe Software is furnished to do so, \nsubject to the following conditions:\nThe above copyright notice and this permission notice \nshall be included in all copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, \nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES \nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR \nANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE \nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%}\n%\n% Ported by M.Horie and H.Kasai on June 21, 2022 for NMFLibrary\n%\n% Change log: \n%\n\n\n    % set dimensions and samples\n    [m, n] = size(V);\n \n    % set local options\n    local_options = [];\n    local_options.lambda = 0;   % sparsity = lambda\n    local_options.eta   = 0;    % smoothness = eta\n    local_options.betaW = 0.1;\n    local_options.betaH = 0.1;\n    local_options.gamma1 = 1.001;\n    local_options.gamma2 = 1.001;\n    local_options.sub_mode = 'std';\n    \n    % check input options\n    if ~exist('in_options', 'var') || isempty(in_options)\n        in_options = struct();\n    end       \n    % merge options\n    options = mergeOptions(get_nmf_default_options(), local_options);   \n    options = mergeOptions(options, in_options);\n\n    % initialize factors\n    init_options = options;\n    [init_factors, ~] = generate_init_factors(V, rank, init_options);    \n    W = init_factors.W;\n    H = init_factors.H; \n\n    % initialize for PAML-NMF\n    TTp_norm = 0;\n    TTp = zeros(n);\n    if options.lambda == 0 && options.eta == 0\n        % NMF\n        % In the case without constraints it can be shown that \n        % the gammas can be divided by 2 (Bolte 2014)\n        options.gamma1 = options.gamma1 / 2;\n        options.gamma2 = options.gamma2 / 2;\n        options.betaW = 0;    \n        options.betaH = 0;          \n    elseif options.lambda > 0 && options.eta == 0\n        % sparse NMF       \n        options.betaW = 0;\n        options.sub_mode = 'sparse';        \n    elseif options.lambda == 0 && options.eta > 0\n        % smooth NMF\n        % Tikhonov regularization matrix\n        T = eye(n) - diag(ones(n-1, 1),-1);\n        T = T(:, 1:end-1);\n        TTp = T * T';\n        TTp_norm = norm(TTp, 'fro');\n        options.betaH = 0;  \n        options.sub_mode = 'smooth';          \n    elseif options.lambda > 0 && options.eta > 0\n        % smooth and sparse NMF\n        % Tikhonov regularization matrix\n        T = eye(n) - diag(ones(n-1, 1),-1);\n        T = T(:, 1:end-1);\n        TTp = T * T';\n        TTp_norm = norm(TTp, 'fro');\n        options.sub_mode = 'smooth & sparse';         \n    else\n        error('Give positive values to the parameters')\n    end\n    \n    % initialize\n    method_name = sprintf('PALM-Sparse-Smooth (%s)', options.sub_mode); \n    epoch = 0; \n    grad_calc_count = 0;\n\n    if options.verbose > 0\n        fprintf('%s: started ...\\n', method_name);           \n    end   \n            \n    % store initial info\n    clear infos;\n    [infos, f_val, optgap] = store_nmf_info(V, W, H, [], options, [], epoch, grad_calc_count, 0);\n    \n    if options.verbose > 1\n        fprintf('%s: Epoch = 0000, cost = %.16e, optgap = %.4e\\n', method_name, options.sub_mode, f_val, optgap); \n    end     \n         \n    % set start time\n    start_time = tic();\n\n    % main loop\n    while true\n        \n        % check stop condition\n        [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n        if stop_flag\n            display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n            break;\n        end\n\n        % update W\n        c = options.gamma1 * 2 * (norm(H * H', 'fro') + options.betaW);    \n        z1 = W - (1 / c) * 2 * ((W * H - V) * H' + options.betaW * W);\n        W = max(z1 - 2 * options.lambda / c, 0);\n        \n        % update H        \n        d = options.gamma2 * 2 * (norm(W*W', 'fro') + options.eta * TTp_norm + options.betaH);\n        z2 = H - (1 / d) * 2 * (W' * (W * H - V) + options.eta * (H * TTp) + options.betaH * H);   \n        H = max(z2, 0);\n\n        % measure elapsed time\n        elapsed_time = toc(start_time);          \n        \n        % measure gradient calc count\n        grad_calc_count = grad_calc_count + m*n;\n\n        % update epoch\n        epoch = epoch + 1;        \n        \n        % store info\n        infos = store_nmf_info(V, W, H, [], options, infos, epoch, grad_calc_count, elapsed_time);                  \n     \n        % display info\n        display_info(method_name, epoch, infos, options);\n    end\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/sparse/palm_sparse_smooth_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5838652973332465}}
{"text": "function y = VBA_sample(form,suffStat,N)\n% legacy code\ns = warning ('on');\nwarning ('*** The function `VBA_sample` is now deprecated. Please see `VBA_random` for an alternative.') \nwarning (s);\n\nif nargin < 3\n    N = 1;\nend\n\nswitch form\n    case 'gaussian'\n        if isscalar(suffstat.mu)\n            N = {1, N};\n        else\n            N = {N};\n        end\n        \n        y = VBA_random ('Gaussian', suffStat.mu, suffStat.Sigma, N{:});\n        \n    case 'gamma'\n        y = VBA_random ('Gamma', suffStat.a, suffStat.b, 1, N);\n    \n    case 'dirichlet'\n        y = VBA_random ('Dirichlet', suffStat.d, N);\n        \n     case 'bernoulli'\n        y = VBA_random ('Bernoulli', suffStat.p, 1, N);\n        \n    case 'binomial'\n        y = VBA_random ('Binomial', suffStat.n, suffstat.p, 1, N);\n        \n    case 'multinomial'\n        y = VBA_random ('Multinomial', suffStat.n, suffstat.p, N);\n\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/VBA_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.583777711205668}}
{"text": "function [ xy, line_pointer, line_data ] = xyl_example ( point_num, ...\n  line_num, line_data_num )\n\n%*****************************************************************************80\n%\n%% XYL_EXAMPLE sets data suitable for a pair of XY and XYL files.\n%\n%  Discussion:\n%\n%    There are 13 points.\n%    There are 3 lines.\n%    There are 15 line data items.\n%\n%         4 12-11\n%         /\\ | |\n%        /  \\| |\n%       /   13 |\n%      /      \\10\n%     /        \\\n%    5          3\n%    |          |\n%    |     9--8 |\n%    |     |  | |\n%    |     |  | |\n%    |     6--7 |\n%    |          |\n%    1----------2\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    01 January 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer POINT_NUM, the number of points.\n%\n%    Input, integer LINE_NUM, the number of lines.\n%\n%    Input, integer LINE_DATA_NUM, the number of line items.\n%\n%    Output, real XY(2,POINT_NUM), the point coordinates.\n%\n%    Output, integer LINE_POINTER(LINE_NUM+1), pointers to the\n%    first line item for each line.\n%\n%    Output, integer LINE_DATA(LINE_DATA_NUM), indices\n%    of points that form lines.\n%\n  xy(1:2,1:point_num) = [ ...\n     0.0,   0.0; ...\n     6.0,   0.0; ...\n     6.0,   7.0; ...\n     3.0,  10.0; ...\n     0.0,   7.0; ...\n     4.0,   1.0; ...\n     5.0,   1.0; ...\n     5.0,   4.0; ...\n     4.0,   4.0; ...\n     5.0,   8.0; ...\n     5.0,  11.0; ...\n     4.0,  11.0; ...\n     4.0,   9.0 ]';\n\n  line_pointer(1:line_num+1) = [ 1, 7, 12, 16 ];\n\n  line_data(1:line_data_num) = [ ...\n     1,  2,  3,  4,  5,  1, ...\n     6,  7,  8,  9,  6, ...\n    10, 11, 12, 13 ];\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/xy_io/xyl_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.5836162268730205}}
{"text": "function value = c8_mul ( z1, z2 )\n\n%*****************************************************************************80\n%\n%% C8_MUL multiplies two C8's.\n%\n%  Discussion:\n%\n%    A C8 is a complex value.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    02 March 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, complex Z1, Z2, the values to multiply.\n%\n%    Output, complex VALUE, the function value.\n%\n  value = z1 * z2;\n\n  return\nend\n", "meta": {"author": "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_mul.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.583616217938802}}
{"text": "function ttt=im2col_inds(a, block)\n%IM2COL Rearrange image blocks into columns.\n%   B = IM2COL(A,[M N],'distinct') rearranges each distinct\n%   M-by-N block in the image A into a column of B. IM2COL pads A\n%   with zeros, if necessary, so its size is an integer multiple\n%   of M-by-N. If A = [A11 A12; A21 A22], where each Aij is\n%   M-by-N, then B = [A11(:) A21(:) A12(:) A22(:)].\n%\n%   B = IM2COL(A,[M N],'sliding') converts each sliding M-by-N\n%   block of A into a column of B, with no zero padding. B has\n%   M*N rows and will contain as many columns as there are M-by-N\n%   neighborhoods in A. If the size of A is [MM NN], then the\n%   size of B is (M*N)-by-((MM-M+1)*(NN-N+1). Each column of B\n%   contains the neighborhoods of A reshaped as NHOOD(:), where\n%   NHOOD is a matrix containing an M-by-N neighborhood of\n%   A. IM2COL orders the columns of B so that they can be\n%   reshaped to form a matrix in the normal way. For example,\n%   suppose you use a function, such as SUM(B), that returns a\n%   scalar for each column of B. You can directly store the\n%   result in a matrix of size (MM-M+1)-by-(NN-N+1) using these\n%   calls:\n%\n%        B = im2col(A,[M N],'sliding');\n%        C = reshape(sum(B),MM-M+1,NN-N+1);\n%\n%   B = IM2COL(A,[M N]) uses the default block type of\n%   'sliding'.\n%\n%   B = IM2COL(A,'indexed',...) processes A as an indexed image,\n%   padding with zeros if the class of A is uint8 or uint16, or\n%   ones if the class of A is double.\n%\n%   Class Support\n%   -------------\n%   The input image A can be numeric or logical. The output matrix\n%   B is of the same class as the input image.\n%\n%   Example\n%   -------\n%   Calculate the local mean using a [2 2] neighborhood with zero padding.\n%\n%       A = reshape(linspace(0,1,16),[4 4])'\n%       B = im2col(A,[2 2])\n%       M = mean(B)\n%       newA = col2im(M,[1 1],[3 3])\n%\n%   See also BLOCKPROC, COL2IM, COLFILT, NLFILTER.\n\n%   Copyright 1993-2016 The MathWorks, Inc.\n\n[ma,na] = size(a);\nm = block(1); n = block(2);\n\nif any([ma na] < [m n]) % if neighborhood is larger than image\n    b = zeros(m*n,0);\n    return\nend\n\n% Create Hankel-like indexing sub matrix.\nmc = block(1); nc = ma-m+1; nn = na-n+1;\ncidx = (0:mc-1)'; ridx = 1:nc;\nt = cidx(:,ones(nc,1)) + ridx(ones(mc,1),:);    % Hankel Subscripts\ntt = zeros(mc*n,nc);\nrows = 1:mc;\nfor i=0:n-1,\n    tt(i*mc+rows,:) = t+ma*i;\nend\nttt = zeros(mc*n,nc*nn);\ncols = 1:nc;\nfor j=0:nn-1,\n    ttt(:,j*nc+cols) = tt+ma*j;\nend\n    \n\n%%%\n%%% Function parse_inputs\n%%%\nfunction [a, block, kind, padval] = parse_inputs(varargin)\n\nnarginchk(2,4);\n\nswitch nargin\n    case 2\n        if (strcmp(varargin{2},'indexed'))\n            error(message('images:im2col:tooFewInputs'))\n        else\n            % IM2COL(A, [M N])\n            a = varargin{1};\n            block = varargin{2};\n            kind = 'sliding';\n            padval = 0;\n        end\n        \n    case 3\n        if (strcmp(varargin{2},'indexed'))\n            % IM2COL(A, 'indexed', [M N])\n            a = varargin{1};\n            block = varargin{3};\n            kind = 'sliding';\n            padval = 1;\n        else\n            % IM2COL(A, [M N], 'kind')\n            a = varargin{1};\n            block = varargin{2};\n            kind = validatestring(varargin{3},{'sliding','distinct'},mfilename,'kind',3);\n            padval = 0;\n        end\n        \n    case 4\n        % IM2COL(A, 'indexed', [M N], 'kind')\n        a = varargin{1};\n        block = varargin{3};\n        kind = validatestring(varargin{4},{'sliding','distinct'},mfilename,'kind',4);\n        padval = 1;\n        \nend\n\nif (isa(a,'uint8') || isa(a, 'uint16'))\n    padval = 0;\nend\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/im2col_inds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5836162172058458}}
{"text": "%% element2HexLattice\n% Below is a demonstration of the features of the |element2HexLattice| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[Es,Vs,Cs]=element2HexLattice(E,V,cPar);|\n\n%% Description \n% This function converts an element description (elements and vertices i.e\n% nodes into a lattice structure. The lattice structure is returned as a\n% hexahederal mesh. \n\n%% Examples \n% \n\n%%\n% Plot settings\ncMap=gjet(4); \nfontSize=15; \n\n%% Example 1 Creating a lattice structure on hexahedral meshes\n\n%%\n% Creating example geometry. \n[V,~]=platonic_solid(2,1); %Vertices of cube\nE=1:8; %Element description of the 8-node cube (hexahedral element)\nC=(1:size(E,1))'; %color (e.g. material) labels for all elements\n[F,~]=element2patch(E,C); %Patch data for plotting\n\n%%\n% Create lattice structure\ncontrolParameter.growSteps=0; %0 is normal, positive or negative integers increase or decrease the edge lattice thickness respectively\ncontrolParameter.latticeSide=[]; %Empty outputs both, 1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n[Es,Vs,Cs]=element2HexLattice(E,V,controlParameter); %Get lattice structure\n\n%%\n% Visualizing input mesh and lattic structures\n\n% Create patch Data for visualization\n[Fs,CsF]=element2patch(Es,Cs); %Patch data for plotting\n[Fs1,CsF1]=element2patch(Es(Cs==1,:),Cs(Cs==1,:)); %Patch data for plotting\n[Fs2,CsF2]=element2patch(Es(Cs==2,:),Cs(Cs==2,:)); %Patch data for plotting\n\ncFigure;\nhs=subplot(2,2,1); \ntitle('The input mesh','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\nha=axis; axis off; \n\nsubplot(2,2,2); \ntitle('The two complementary lattice structures','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs,Vs,CsF);\ncolormap(cMap); \ncLim=caxis; caxis([1 2]);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\naxis(ha); axis off; \n\nsubplot(2,2,3); \ntitle('Lattice side 1','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs1,Vs,cMap(1,:));\ncolormap(cMap); \ncaxis(cLim);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\naxis(ha); axis off; \n\nsubplot(2,2,4); \ntitle('Lattice side 2','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs2,Vs,CsF2);\ncolormap(cMap); \ncaxis(cLim);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\naxis(ha); axis off; \n\ndrawnow;\n\n%% Example 2 Creating a lattice structure on tetrahedral meshes\n\n%%\n% Creating example geometry. \n\n[V,~]=platonic_solid(1,1); %Vertices of tetrahedron\nE=1:4; %Element description of the 4-node tetrahedron\nC=(1:size(E,1))'; %color (e.g. material) labels for all elements\n[F,~]=element2patch(E,C); %Patch data for plotting\n\n%%\n% Create lattice structure\ncontrolParameter.growSteps=0; %0 is normal, positive or negative integers increase or decrease the edge lattice thickness respectively\ncontrolParameter.latticeSide=[]; %Empty outputs both, 1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n[Es,Vs,Cs]=element2HexLattice(E,V,controlParameter); %Get lattice structure\n\n%%\n% Visualizing input mesh and lattic structures\n\n% Create patch Data for visualization\n[Fs,CsF]=element2patch(Es,Cs); %Patch data for plotting\n[Fs1,CsF1]=element2patch(Es(Cs==1,:),Cs(Cs==1,:)); %Patch data for plotting\n[Fs2,CsF2]=element2patch(Es(Cs==2,:),Cs(Cs==2,:)); %Patch data for plotting\n\ncFigure;\nhs=subplot(2,2,1); \ntitle('The input mesh','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\nha=axis; axis off; \n\nsubplot(2,2,2); \ntitle('The two complementary lattice structures','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs,Vs,CsF);\ncolormap(cMap); \ncLim=caxis; caxis([1 2]);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\naxis(ha); axis off; \n\nsubplot(2,2,3); \ntitle('Lattice side 1','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs1,Vs,cMap(1,:));\ncolormap(cMap); \ncaxis(cLim);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\naxis(ha); axis off; \n\nsubplot(2,2,4); \ntitle('Lattice side 2','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs2,Vs,CsF2);\ncolormap(cMap); \ncaxis(cLim);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\naxis(ha); axis off; \n\ndrawnow;\n\n%% Example 3 Changing lattice structure thickness\n\n%%\n% Creating example geometry. \n\n[V,~]=platonic_solid(1,1); %Vertices of tetrahedron\nE=1:4; %Element description of the 4-node tetrahedron\nC=(1:size(E,1))'; %color (e.g. material) labels for all elements\n[F,~]=element2patch(E,C); %Patch data for plotting\n\n%%\n% Create lattice structure\ncontrolParameter.latticeSide=[]; %Empty outputs both, 1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n\n%%\n% lattice structure for 0 growth steps\ncontrolParameter.growSteps=0; %0 is normal, positive or negative integers increase or decrease the edge lattice thickness respectively\n[Es_0,Vs_0,Cs_0]=element2HexLattice(E,V,controlParameter); %Get lattice structure\n\ncontrolParameter.growSteps=1; %0 is normal, positive or negative integers increase or decrease the edge lattice thickness respectively\n[Es_1,Vs_1,Cs_1]=element2HexLattice(E,V,controlParameter); %Get lattice structure\n\ncontrolParameter.growSteps=-1; %0 is normal, positive or negative integers increase or decrease the edge lattice thickness respectively\n[Es_n1,Vs_n1,Cs_n1]=element2HexLattice(E,V,controlParameter); %Get lattice structure\n\n%%\n% Visualizing input mesh and lattic structures\n\n% Create patch Data for visualization\n[Fs_0,CsF_0]=element2patch(Es_0,Cs_0); %Patch data for plotting\n[Fs_1,CsF_1]=element2patch(Es_1,Cs_1); %Patch data for plotting\n[Fs_n1,CsF_n1]=element2patch(Es_n1,Cs_n1); %Patch data for plotting\n\ncFigure;\nsubplot(1,3,1); \ntitle('growSteps=1','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs_1,Vs_1,CsF_1);\ncolormap(cMap); \ncLim=caxis; caxis([1 2]);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\naxis off;\n\nsubplot(1,3,2); \ntitle('growSteps=0','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs_0,Vs_0,CsF_0);\ncolormap(cMap); \ncLim=caxis; caxis([1 2]);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\naxis off;\n\nsubplot(1,3,3); \ntitle('growSteps=-1','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs_n1,Vs_n1,CsF_n1);\ncolormap(cMap); \ncLim=caxis; caxis([1 2]);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\naxis off;\n\ndrawnow;\n\n%% Example 4 Lattices on multiple elements, adjusting lattice type\n\n%%\n% Creating example geometry. \n[V,~]=platonic_solid(2,1); %Vertices of cube\nE=1:8; %Element description of the 8-node cube (hexahedral element)\n[E,V,C]=subHex(E,V); %Subdevide into 8 sub-cubes\n[E,V,C]=hex2tet(E,V,C,1); %Convert to tetrahedral elements\n\n[F,~]=element2patch(E,C); %Patch data for plotting\n\n%%\n% Create lattice structure\ncontrolParameter.growSteps=-1; %0 is normal, positive or negative integers increase or decrease the edge lattice thickness respectively\ncontrolParameter.latticeSide=1; %Empty outputs both, 1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n[Es,Vs,Cs]=element2HexLattice(E,V,controlParameter); %Get lattice structure\n\n%%\n% Visualizing input mesh and lattic structures\n\n% Create patch Data for visualization\n[Fs,CsF]=element2patch(Es,Cs); %Patch data for plotting\n\ncFigure;\nhs=subplot(1,2,1); \ntitle('The input mesh','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\n\nsubplot(1,2,2); \ntitle('Lattice side 1','fontSize',fontSize)\nhold on;\ngpatch(Fs,Vs,cMap(1,:));\ncolormap(cMap); \ncaxis(cLim);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\n\ndrawnow;\n\n%%\n% Create lattice structure\ncontrolParameter.growSteps=1; %0 is normal, positive or negative integers increase or decrease the edge lattice thickness respectively\ncontrolParameter.latticeSide=2; %Empty outputs both, 1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n[Es,Vs,Cs]=element2HexLattice(E,V,controlParameter); %Get lattice structure\n\n%%\n% Visualizing input mesh and lattic structures\n\n% Create patch Data for visualization\n[Fs,CsF]=element2patch(Es,Cs); %Patch data for plotting\n\ncFigure;\nhs=subplot(1,2,1); \ntitle('The input mesh','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\n\nsubplot(1,2,2); \ntitle('Lattice side 2','fontSize',fontSize)\nhold on;\ngpatch(Fs,Vs,cMap(1,:));\ncolormap(cMap); \ncaxis(cLim);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\n\ndrawnow;\n\n%% Example 5 Hierarchical lattice structures\n\n%%\n% Creating example geometry. \n\n% [V,~]=platonic_solid(2,1); %Vertices of cube\n% E=1:8; %Element description of the 8-node cube (hexahedral element)\n% C=(1:size(E,1))'; %color (e.g. material) labels for all elements\n% [F,~]=element2patch(E,C); %Patch data for plotting\n\n[V,~]=platonic_solid(1,1); %Vertices of tetrahedron\nE=1:4; %Element description of the 4-node tetrahedron\nC=(1:size(E,1))'; %color (e.g. material) labels for all elements\n[F,~]=element2patch(E,C); %Patch data for plotting\n\n%%\n% Create first order lattice structure\ncontrolParameter.growSteps=-1; %0 is normal, positive or negative integers increase or decrease the edge lattice thickness respectively\ncontrolParameter.latticeSide=1; %Empty outputs both, 1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n[Es1,Vs1,Cs1]=element2HexLattice(E,V,controlParameter); %Get lattice structure\n \n%%\n% Uncomment to create more complex structure\n[Es1,Vs1,Cs1]=hex2tet(Es1,Vs1,Cs1,5); %Convert to tetrahedral elements\n% [Es1,Vs1,Cs1]=tet2hex(Es1,Vs1,1); %Convert to tetrahedral elements\n\n%%\n% Create second order lattice structure\ncontrolParameter.growSteps=-1; %0 is normal, positive or negative integers increase or decrease the edge lattice thickness respectively\ncontrolParameter.latticeSide=1; %Empty outputs both, 1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n[Es2,Vs2,Cs2]=element2HexLattice(Es1,Vs1,controlParameter); %Get lattice structure\n\n%%\n% Visualizing input mesh and lattic structures\n\n% Create patch Data for visualization\n[Fs1,CsF1]=element2patch(Es1,Cs1); %Patch data for plotting\n[Fs2,CsF2]=element2patch(Es2,Cs2); %Patch data for plotting\n\n[indBounary]=tesBoundary(Fs2);\nFs2_b=Fs2(indBounary,:);\n\n[indBounary]=tesBoundary(Fs1);\nFs1_b=Fs1(indBounary,:);\n\n%%\n\ncFigure;\nhs=subplot(1,3,1); \ntitle('The input mesh','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\nha=axis; axis off; \n\nsubplot(1,3,2); \ntitle('Lattice order 1','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0,3);\ngpatch(Fs1_b,Vs1,cMap(1,:),'none');\ncolormap(cMap); \ncaxis(cLim);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\naxis(ha); axis off; \n\nsubplot(1,3,3); \ntitle('Lattice order 2','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0,3);\ngpatch(Fs2_b,Vs2,cMap(1,:),'none');\ncolormap(cMap); \ncaxis(cLim);\naxisGeom(gca,fontSize); \ncamlight headlight; lighting flat;\naxis(ha); axis off; \n\ndrawnow;\n\n%%\n% \n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_element2HexLattice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5836162142046487}}
{"text": "% \u907f\u514d\u5927\u6570\u5403\u5c0f\u6570\nclear;\n\n% \u8ba1\u7b97 (10^9+10^-9-10^9)/10^-9 \nS = (10^9 + 10^-9 - 10^9) / 10 ^ -9;\nfprintf('\u76f4\u63a5\u8ba1\u7b97\u7684\u7ed3\u679c\u4e3a: %.20e\\n',S);\n% S1 = S;\n\n% \u6539\u53d8\u987a\u5e8f\uff0c\u518d\u6b21\u8ba1\u7b97\nS = (10^9 - 10^9 + 10^-9) / 10 ^ -9;\nfprintf('\u6539\u53d8\u987a\u5e8f\u8ba1\u7b97\u7684\u7ed3\u679c\u4e3a: %.20e\\n',S);", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/\u7b2c\u4e00\u7ae0 \u5f15\u8bba/demo_1_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.5836162142046487}}
{"text": "function normal_01_cdf_inv_test ( )\n\n%*****************************************************************************80\n%\n%% NORMAL_01_CDF_INV_TEST tests NORMAL_01_CDF_INV.\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  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'NORMAL_01_CDF_INV_TEST\\n' );\n  fprintf ( 1, '  NORMAL_01_CDF_INV inverts the Normal 01 CDF;\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '      CDF             X                         X\\n' );\n  fprintf ( 1, '                     (exact)                   (computed)\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x1, cdf ] = normal_01_cdf_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    x2 = normal_01_cdf_inv ( cdf );\n\n    fprintf ( 1, '  %14.6g  %24.16g  %24.16g\\n', cdf, x1, 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/truncated_normal/normal_01_cdf_inv_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.5836162104704954}}
{"text": "%SOLVEPNPRANSAC  Finds an object pose from 3D-2D point correspondences using the RANSAC scheme\n%\n%     [rvec, tvec, success, inliers] = cv.solvePnPRansac(objectPoints, imagePoints, cameraMatrix)\n%     [...] = cv.solvePnPRansac(..., 'OptionName', optionValue, ...)\n%\n% ## Input\n% * __objectPoints__ Array of object points in the object coordinate space,\n%   1xNx3/Nx1x3 or Nx3 array, where `N` is the number of points, or cell\n%   array of length `N` of 3-element vectors can be also passed here\n%   `{[x,y,z], ...}`.\n% * __imagePoints__ Array of corresponding image points, 1xNx2/Nx1x2 or Nx2\n%   array, where `N` is the number of points, or cell array of length `N` of\n%   2-element vectors can be also passed here `{[x,y], ...}`.\n% * __cameraMatrix__ Input camera matrix `A = [fx 0 cx; 0 fy cy; 0 0 1]`.\n%\n% ## Output\n% * __rvec__ Output rotation vector (see cv.Rodrigues) that, together with\n%   `tvec`, brings points from the model coordinate system to the camera\n%   coordinate system.\n% * __tvec__ Output translation vector.\n% * __success__ success logical flag.\n% * __inliers__ Output vector that contains indices (zero-based) of inliers in\n%   `objectPoints` and `imagePoints`.\n%\n% ## Options\n% * __DistCoeffs__ Input vector of distortion coefficients\n%   `[k1,k2,p1,p2,k3,k4,k5,k6,s1,s2,s3,s4,taux,tauy]` of 4, 5, 8, 12 or 14\n%   elements. If the vector is empty, the zero distortion coefficients are\n%   assumed. default empty.\n% * __Rvec__ Initial `rvec`. Not set by default.\n% * __Tvec__ Initial `tvec`. Not set by default.\n% * __UseExtrinsicGuess__ Parameter used for `Method='Iterative'`. If true,\n%   the function uses the provided `rvec` and `tvec` values as initial\n%   approximations of the rotation and translation vectors, respectively, and\n%   further optimizes them. default false.\n% * __IterationsCount__ Number of iterations. default 100.\n% * __ReprojectionError__ Inlier threshold value used by the RANSAC procedure.\n%   The parameter value is the maximum allowed distance between the observed\n%   and computed point projections to consider it an inlier. default 8.0.\n% * __Confidence__ The probability that the algorithm produces a useful result.\n%   default 0.99\n% * __Method__ Method for solving the PnP problem. See cv.solvePnP.\n%   default 'Iterative'\n%\n% The function estimates an object pose given a set of object points, their\n% corresponding image projections, as well as the camera matrix and the\n% distortion coefficients. This function finds such a pose that minimizes\n% reprojection error, that is, the sum of squared distances between the\n% observed projections `imagePoints` and the projected (using cv.projectPoints)\n% `objectPoints`. The use of RANSAC makes the function resistant to outliers.\n%\n% Note: The default method used to estimate the camera pose for the Minimal\n% Sample Sets step is `EPnP`. Exceptions: if you choose `P3P` or `AP3P`, these\n% methods will be used; if the number of input points is equal to 4, `P3P` is\n% used.\n%\n% The method used to estimate the camera pose using all the inliers is defined\n% by the flags parameters unless it is equal to `P3P` or `AP3P`. In this case,\n% the method `EPnP` will be used instead.\n%\n% See also: cv.solvePnP, estimateWorldCameraPose\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/solvePnPRansac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5836162097375395}}
{"text": "function r = taylor(a,str)\n%TAYLOR       Taylor class constructor\n%\n%  r = taylor(a)\n%\n%An explicit call of the constructor is only necessary to initialize\n%  a constant to be of type taylor. Otherwise, any operation\n%  with a dependent variable produces a result of type taylor.\n%\n%For more details try\n%\n%  help taylorinit\n%\n%and demotaylor.\n%\n\n%taylor.size is size of input\n%taylor.t stored as column vector of length INTLAB_TAYLOR_ORDER; in case of \n%vector or matrix input, columns of taylor.t are the Taylor coefficients\n%\n\n% written  05/21/09     S.M. Rump\n% modified 02/28/10     S.M. Rump  rounding\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  superiorto('intval');\n\n  if nargin==0\n    r.size = [];\n    r.t = [];\n    r = class(r,'taylor');\n    return\n  end\n  \n  INTLAB_TAYLOR_ORDER = getappdata(0,'INTLAB_TAYLOR_ORDER');\n\n  if INTLAB_TAYLOR_ORDER==0\n    error('no dependent variables initialized for use of Taylor')\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 nargin==1\n\n    if isa(a,'taylor')\n      r = a;\n    else\n      r.size = size(a);      \n      len = prod(r.size);\n      r.t = [ a(:).' ; zeros(INTLAB_TAYLOR_ORDER,len) ];\n      r = class(r,'taylor');\n    end\n\n  elseif nargin==2\n    \n    if ischar(str)\n      \n      if isequal(str,'taylorinit')         % call by taylorinit\n        \n        r.size = size(a.init);\n        len = prod(r.size);\n        r.t = [ a.init(:).' ; ones(1,len) ; zeros(INTLAB_TAYLOR_ORDER-1,len) ];\n        r = class(r,'taylor');\n\n      elseif isequal(str,'taylor')         % call by @intval\\taylor\n        \n        r.size = size(a.init);\n        len = prod(r.size);\n        r.t = intval([ a.init(:).' ; zeros(INTLAB_TAYLOR_ORDER,len) ]);\n        r = class(r,'taylor');\n        \n      elseif isequal(str,'taylorintval')   % call by @intval\\intval\n        \n        r = a;\n        r.t = intval(r.t);\n        \n      elseif isequal(str,'random')          % generates .t randomly, only for test purposes\n        \n        if isa(a,'struct')                  % input interval\n          a = a.init;\n        end\n        r.size = size(a);\n        len = prod(r.size);\n        r.t = [ a(:).' ; randn(INTLAB_TAYLOR_ORDER,len) ];\n        r = class(r,'taylor');\n        \n      else\n        error('invalid call of taylor constructor')\n      end\n      \n    end\n      \n  else\n    \n    error('invalid call of constructor taylor')\n    \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/taylor/@taylor/taylor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.58361620527043}}
{"text": "function [nodeNo,nodeChildIdx] = depthIndex2NodeNo(d,k,wt)\n%DEPTHINDEX2NODENO Get node from depth and index in the tree\n%   Usage: [nodeNo,nodeChildIdx] = depthIndex2NodeNo(d,k,wt)\n%\n%   `[nodeNo,nodeChildIdx] = depthIndex2NodeNo(d,k,wt)` returns node \n%   *nodeNo* and an array of its children nodes *nodeChildIdx* positioned\n%   in depth *g* and index *k* in the tree *wt*.\n%\nif(d==0)\n    nodeNo=0;\n    nodeChildIdx=0;\n    return;\nend\n\n% find ordered nodes at depth d-1\nnodesNo = getNodesInDepth(d,wt);\nif(isempty(nodesNo))\n   error('%s: Depth of the tree is less than given d.',mfilename); \nend\n\n% k is index in children of ordered nodes at depth d\n\nnodeNo = zeros(numel(k),1);\nnodeChildIdx = zeros(numel(k),1);\nchNo = cumsum(cellfun( @(nEl) length(nEl.g),wt.nodes(nodesNo)));\nchNoZ = [0;chNo(:)];\n\nfor kIdx=1:numel(k)\n    ktmp = k(kIdx);\n    idx = find(chNo>ktmp,1);\n    if isempty(idx)\n       error('%s: Index k=%i out of bounds.',mfilename,ktmp); \n    end    \n    nodeNo(kIdx) = nodesNo(idx);\n    nodeChildIdx(kIdx) = ktmp-chNoZ(idx)+1;\nend\n\nfunction nodd = getNodesInDepth(d,wt)\n% find all nodes with d steps to the root ordered\nif d==1\n    % return root\n    nodd = find(wt.parents==0);\n    return;\nend    \n\nnbf = nodeBForder(0,wt);\nnbfTmp = nbf;\ntempd = 0;\nwhile tempd<d\n    nbf(nbfTmp==0) = [];\n    nbfTmp(nbfTmp==0) = [];\n    nbfTmp = wt.parents(nbfTmp);\n    tempd = tempd+1;\nend\nnodd = nbf(nbfTmp==0);\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/wavelets/wfbtmanip/depthIndex2NodeNo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.583521279519441}}
{"text": "%tstoolbox/mex/amutual\n%   Fast, but crude auto mutual information of a scalar timeseries for the\n%   timelags from zero to maxtau. The input time series should be much\n%   longer than maximal timelag maxtau. The algorithm uses equidistant\n%   histogram boxes, so results are bad in a mathematical sense. However,\n%   a fast algorithm based on ternary search trees to store only nonempty\n%   boxes is used.\n%\n%   Syntax:\n%\n%     * a = amutual(ts, maxtau, partitions)\n%\n%   Input arguments:\n%\n%     * ts - vector holding time series data\n%     * maxtau - maximal time lag\n%     * partitions - number of partitions for the one-dimensional\n%       histogram\n%\n%   Output arguments:\n%\n%     * a - vector of length maxtau+1, holding auto mutual information\n%\n% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt\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/mex/amutual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5834959537460228}}
{"text": "function C = calcConc(s,p,s0)\n% This function converts a DCE signal intensity time course to the time course of\n% tissue concentration of contrast agent\n% \n% INPUTS\n% s : Signal time course vector.\n% p : Parameter array. \n%     p(1) = R1 (mmolXsec), p(2) = TR (s), p(3) = FA, p(4) = T10 (s)\n% Optional -\n% s0: Signal at time t=0. If not input, s(1) is used.\n% \n% OUTPUT\n% C : Time course of Gd concentration (mmoles/L) in blood.\n% --------------------------------------------------------------------------------------\n% Knowing the relaxivity of the contrast agent, the T1 of blood without contrast, and\n% the blood signal value prior to contrast, the concentration of contrast\n% agent in the blood is:\n%                             1/T1  = 1/T10 + R1* C(t)\n% Given S/S0, 1/T1 (for each time point) can be obtained by substituting in from the\n% partial saturation equation:\n%                        S/S0 = (1-exp(-TR/T1)sin(theta))/(1-exp(-TR/T1)cos(theta)\n% Then you go back and solve for C(t).\n%\n% This function returns a vector (C) containing the blood or tissue Gd concentration time course\n% units are mmoles/L \n% --------------------------------------------------------------------------------------\n%\n% Kristen Zakian\n\n%Get inputs\nR1 = p(1); TR = p(2); FA = p(3); T10 = p(4);\na = FA*pi/180;       % calculate flip angle in radians\n\nif nargin == 2       % if no s0 specified, then use the first point\n    s0 = s(1);       \nend\n\nif s0 ~= 0          \n    v = s./s0;      \nelse\n    s0 = 0.001;      % fudge\n    v = s./s0;       % fudge\n    errordlg('concformula: s0 = 0!','ERROR');  %Got this error on Acevedo RT-BL\nend\n\nif T10 ~= 0\n    TT = TR/T10;\n    E10 = exp(-TT);\nelse\n    error('concformula: T10 = 0!')\nend\n\nu = 1 - E10;\nw = 1 - E10*cos(a);\n\nnum = w - u.*v.*cos(a);\ndenom = w - u.*v;\nif denom ~= 0\n    L = log(num./denom);\n    %y = 1/R1*1/TR*(L - TT)*1000; \n    C = 1/R1*1/TR*(L - TT);\nelse\n    error('calcconc: denom = 0');\nend\n\nfor i=1:size(L,1)\n    if ~isreal(L(i,:))\n        C(i,:) = double(0);\n    end\nend\n\nC(C <=0) = 0;\n\n\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanAnalysis/DCE-MR analysis/Toft's model/calcConc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5834959506247622}}
{"text": "function r4mat_uniform_ab_test ( )\n\n%*****************************************************************************80\n%\n%% R4MAT_UNIFORM_AB_TEST tests R4MAT_UNIFORM_AB.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    25 Deember 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 5;\n  n = 4;\n  a = -1.0;\n  b = +5.0;\n  seed = 123456789;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R4MAT_UNIFORM_AB_TEST\\n' );\n  fprintf ( 1, '  R4MAT_UNIFORM_AB computes a random R4MAT.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  %g <= x <= %g\\n', a, b );\n  fprintf ( 1, '  Initial seed is %d\\n', seed );\n\n  [ v, seed ] = r4mat_uniform_ab ( m, n, a, b, seed );\n\n  r4mat_print ( m, n, v, '  Uniform R4MAT:' );\n\n  return\nend\n", "meta": {"author": "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/r4mat_uniform_ab_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.5834808035780326}}
{"text": "function varargout = grMean(varargin)\n%GRMEAN Compute mean value from neighbour nodes.\n%\n%   LBL2 = grMean(EDGES, LBL1)\n%   new label for each node of the graph is computed as the mean of the\n%   values of neighbours and of old value.\n%\n%   Example\n%   grMean\n%\n%   See also \n%   grMedian, grDilate, grErode\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inrae.fr\n% Created: 2006-01-20\n% Copyright 2006-2022 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas)\n\nif length(varargin) == 2\n    edges   = varargin{1};\n    values \t= varargin{2};\nelseif length(varargin) == 3\n    edges   = varargin{2};\n    values  = varargin{3};\nelse\n    error('Wrong number of arguments in \"grMean\"');\nend\n   \n\nres = zeros(size(values));\n\nuni = unique(edges(:));\nfor n = 1:length(uni)\n    neigh = grAdjacentNodes(edges, uni(n));\n    res(uni(n)) = mean(values([uni(n); neigh]));    \nend\n\nvarargout{1} = res;\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/grMean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5834807996541916}}
{"text": "% LRR | ROSL | Robust Orthonormal Subspace Learning (Shu et al. 2014)\n% process_video('LRR', 'ROSL', 'dataset/demo.avi', 'output/demo_LRR-ROSL.avi');\n\nK = 1; % The initialiation of the subspace dimension\ntol = 1e-5;\nmaxIter = 30;\nlambda = 1e-1; %2e-3;\n[~,~,E_hat,A_hat] = inexact_alm_rosl(M,K,lambda,tol,maxIter);\nL = A_hat;\nS = E_hat;", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/lrr/ROSL/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5834494963385931}}
{"text": "function [mResult, fMls, fMc, fMu, fSigma, mDatPredBest, vPredBest, fBvalue, fAvalue] = calc_McCdflognormal(mCatalog, fBinning)\n% function [mResult, fMls, fMc, fMu, fSigma, mDatPredBest, vPredBest, fBvalue, fAvalue] = calc_McCdflognormal(mCatalog, fBinning);\n% -----------------------------------------------------------------------------------------------------------------------------\n% Determine Mc using maximum likelihood score\n% Fitting non-cumulative frequency magnitude distribution above and below Mc:\n% below: Cumulative LOGNORMAL density function\n% above: Gutenberg-Richter law\n%\n% Incoming variables:\n% mCatalog   : EQ catalog\n% fBinning   : Binning interval, usually 0.1\n%\n% Outgoing variables:\n% mResult     : Solution matrix including\n%               vProbability: maximum likelihood score\n%               vMc         : Mc values\n%               vX_res      : mu (of normal CDF), sigma (of normal CDF), residuum, exitflag\n%               vNmaxBest   : Number of events in lowest magnitude bin considered complete\n%               vABValue    : a and b-value\n% fMls       : minimum maximum likelihood score --> best Mc\n% fMc        : Best estimated magnitude of completeness\n% mDatPredBest   : Matrix of non-cumulative FMD [Prediction, magnitudes, original distribution]\n% vPredBest      : Matrix of non-cumulative FMD below Mc [magnitude, prediction, uncertainty of prediction]\n% fBvalue        : b-value\n%\n% J. Woessner: woessner@seismo.ifg.ethz.ch\n% last update: 03.11.03\n\n\n% Initialize\nvProbability = [];\nvMc = [];\nvABValue =[];\nmFitRes = [];\nvX_res = [];\nvNCumTmp = [];\nmDataPred = [];\nvPredBest = [];\nvDeltaBest = [];\nvX_res = [];\nvNmaxBest = [];\nmResult=[];\nmDatPredBest = [];\n\n% Determine exact time period\nfPeriod1 = max(mCatalog(:,3)) - min(mCatalog(:,3));\n\n% Determine max. and min. magnitude\nfMaxMag = ceil(10 * max(mCatalog(:,6))) / 10;\n\n% Set starting value for Mc loop and LSQ fitting procedure\nfMcTry= calc_Mc(mCatalog,1);\nfSmu = abs(fMcTry/2);\nfSSigma = abs(fMcTry/4);\nif (fSmu > 1)\n    fSmu = fMcTry/10;\n    fSSigma = fMcTry/20;\nend\nfMcBound = fMcTry;\n\n% Calculate FMD for original catalog\n[vFMDorg, vNonCFMDorg] = calc_FMD(mCatalog);\nfMinMag = min(vNonCFMDorg(1,:));\n\n%% Shift to positive values\n% if fMinMag ~= 0\n%     fMcBound = fMcTry-fMinMag;\n% end\n% Loop over Mc-values\nfor fMc = fMcBound-0.6:0.1:fMcBound+0.6\n    fMc = round(fMc*10)/10;\n    vFMD = vFMDorg;\n    vNonCFMD = vNonCFMDorg;\n    vNonCFMD = fliplr(vNonCFMD);\n    % Calculate a and b-value for GR-law and distribution vNCum\n    [nIndexLo, fMagHi, vSel, vMagnitudes] = fMagToFitBValue(mCatalog, vFMD, fMc);\n    if (length(mCatalog(vSel,1)) >= 20)\n        [fMeanMag, fBValue, fStdDev, fAValue] =  calc_bmemag(mCatalog(vSel,:), fBinning);\n        % Normalize to time period\n        vFMD(2,:) = vFMD(2,:)./fPeriod1; % ceil taken out\n        vNonCFMD(2,:) = vNonCFMD(2,:)./fPeriod1; % ceil removed\n        % Compute quantity of earthquakes by power law\n        fMaxMagFMD = max(vNonCFMD(1,:));\n        fMinMagFMD = min(vNonCFMD(1,:));\n        vMstep = [fMinMagFMD:0.1:fMaxMagFMD];\n        vNCum = 10.^(fAValue-fBValue.*vMstep); % Cumulative number\n\n        % Compute non-cumulative numbers vN\n        fNCumTmp = 10^(fAValue-fBValue*(fMaxMagFMD+0.1));\n        vNCumTmp  = [vNCum fNCumTmp ];\n        vN = abs(diff(vNCumTmp));\n\n        % Normalize vN\n        vN = vN./fPeriod1;\n        % Data selection\n        % mData = Non-cumulative FMD values from GR-law and original data\n        mData = [vN' vNonCFMD'];\n        vSel = (mData(:,2) >= fMc);\n        mDataTest = mData(~vSel,:);\n        mDataTmp = mData.subset(vSel);\n        % Choices of normalization\n        fNmax = mDataTmp(1,3); % Frequency of events in Mc bin\n        %fNmax = max(mDataTest(:,3));  % Use maximum frequency of events in bins below Mc\n        %fNmax = mDataTest(length(mDataTest(:,1)),3); % Use frequency of events at bin Mc-0.1 -> best fit\n        if (~isempty(fNmax) & ~isnan(fNmax) & fNmax ~= 0 & length(mDataTest(:,1)) > 4)\n            mDataTest(:,3) = mDataTest(:,3)/fNmax; % Normalize datavalues for fitting with CDF\n            % Move to M=0 to fit with lsq-algorithm\n            fMinMagTmp = min(mDataTest(:,2));\n            mDataTest(:,2) = mDataTest(:,2)-fMinMagTmp;\n            % Curve fitting: Non cumulative part below Mc\n            options = optimset;\n            %options = optimset('Display','off','Tolfun',1e-7,'TolX',0.0001,'MaxFunEvals', 100000,'MaxIter',10000);\n            options = optimset('Display','off','Tolfun',1e-5,'TolX',0.001,'MaxFunEvals', 1000,'MaxIter',1000);\n            [vX, resnorm, resid, exitflag, output, lambda, jacobian]=lsqcurvefit(@calc_lognormal,[fSmu  fSSigma], mDataTest(:,2), mDataTest(:,3),[],[],options);\n            mDataTest(:,1) = logncdf(mDataTest(:,2), vX(1), vX(2))*fNmax;\n            if (length(mDataTest(:,2)) > length(vX(1,:)))\n                %% Confidence interval determination\n                % vPred : Predicted values of lognormal function\n                % vPred+-delta : 95% confidence level of true values\n                [vPred,delta] = nlpredci(@calc_lognormal,mDataTest(:,2),vX, resid, jacobian);\n            else\n                vPred = NaN;\n                delta = NaN;\n            end; % END: This section is due for errors produced with datasets less long than amount of parameters in vX\n            % Results of fitting procedure\n            mFitRes = [mFitRes; vX resnorm exitflag];\n            % Move back to original magnitudes\n            mDataTest(:,2) = mDataTest(:,2)+fMinMagTmp;\n            % Set data together\n            mDataTest(:,3) = mDataTest(:,3)*fNmax;\n            mDataPred = [mDataTest; mDataTmp];\n            % Denormalize to calculate probabilities\n            mDataPred(:,1) = round(mDataPred(:,1).*fPeriod1);\n            mDataPred(:,3) = mDataPred(:,3).*fPeriod1;\n            vProb_ = calc_log10poisspdf2(mDataPred(:,3), mDataPred(:,1)); % Non-cumulative\n\n            % Sum the probabilities\n            fProbability = (-1) * sum(vProb_);\n            vProbability = [vProbability; fProbability];\n            % Move magnitude back\n            mDataPred(:,2) = mDataPred(:,2)+fMinMag;\n            vMc = [vMc; fMc];\n            vABValue = [vABValue; fAValue fBValue];\n\n            % Keep values\n            vDeltaBest = [vDeltaBest; delta];\n            vX_res = [vX_res; vX resnorm exitflag];\n            vNmaxBest = [vNmaxBest; fNmax];\n\n            % Keep best fitting model\n            if (fProbability == min(vProbability))\n                vDeltaBest = delta;\n                vPredBest = [mDataTest(:,2) vPred*fNmax*fPeriod1 delta*fNmax*fPeriod1]; % Gives back uncertainty\n                %fMc+fMinMag : Test procedure\n                mDatPredBest = [mDataPred];\n           end\n        else\n            %disp('Not enough data');\n            % Setting values\n            fProbability = NaN;\n            fMc = NaN;\n            vX(1) = NaN;\n            vX(2) = NaN;\n            resnorm = NaN;\n            exitflag = NaN;\n            delta = NaN;\n            vPred = [NaN NaN NaN];\n            fNmax = NaN;\n            fAValue = NaN;\n            fBValue = NaN;\n            vProbability = [vProbability; fProbability];\n            vMc = [vMc; fMc];\n            vX_res = [vX_res; vX resnorm exitflag];\n%             vDeltaBest = [vDeltaBest; NaN];\n%             vPredBest = [vPredBest; NaN NaN NaN];\n            vNmaxBest = [vNmaxBest; fNmax];\n            vABValue = [vABValue; fAValue fBValue];\n        end; % END of IF fNmax\n    end; % END of IF length(mCatalog(vSel,1))\n\n\n    % Clear variables\n    vNCumTmp = [];\n    mModelDat = [];\n    vNCum = [];\n    vSel = [];\n    mDataTest = [];\n    mDataPred = [];\nend; % END of FOR fMc\n% Result matrix\nmResult = [mResult; vProbability vMc vX_res vNmaxBest vABValue];\n\n% Find best estimate, excluding the case of mResult all NAN\nif  ~isempty(nan(mResult))\n    if ~isnan(nan(mResult(:,1)))\n        vSel = find(nan(mResult(:,1)) == mResult(:,1));\n        fMc = min(mResult(vSel,2));\n        fMls = min(mResult(vSel,1));\n        fMu = min(mResult(vSel,3));\n        fSigma = min(mResult(vSel,4));\n        fAvalue = min(mResult(vSel,8));\n        fBvalue = min(mResult(vSel,9));\n    else\n        fMc = NaN;\n        fMls = NaN;\n        fMu = NaN;\n        fSigma = NaN;\n        fAvalue = NaN;\n        fBvalue = NaN;\n    end\nelse\n    fMc = NaN;\n    fMls = NaN;\n    fMu = NaN;\n    fSigma = NaN;\n    fAvalue = NaN;\n    fBvalue = NaN;\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/jochen/seisvar/calc/calc_McCdflognormal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5832376286442941}}
{"text": "function [sv,vis] = visibleSegment(s,d,imSize,mrg,lmin)\n\n% VISIBLESEGMENT  Visible segment.\n%   VISIBLESEGMENT(S,D,IMSIZE) returns the segment portion of segment S\n%   that is visible in the image defined by IMSIZE. D is a vector of depths\n%   of the two segment's endpoints.\n%\n%   VISIBLESEGMENT(...,MRG) restricts the image size to be smaller in MRG\n%   pixels at its four borders. The default is MRG = 0 pix.\n%\n%   VISIBLESEGMENT(...,LMIN) sets all segments shorter than LMIN pixels to\n%   be invisible. The default is LMIN = 1 pix.\n%\n%   [SV,VIS] = VISIBLESEGMENT(...) returns the visible segment SV and a\n%   flag of visibility. In case of non visibility, the flag is set to false\n%   and the output segment is SV = [0;0;0;0].\n%\n%   The function works for segment matrices S = [S1 S2 ... Sn] and D = [D1\n%   D2 ... Dn], giving a segments matrix SV and a visibility vector VIS.\n\n%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n\n% input options and defaults\nif nargin < 5\n    lmin = 1;\n    if nargin < 4\n        mrg = 0;\n    end\nend\n\n% init output arrays\nn   = size(s,2);\nsv  = zeros(4,n);\nvis = false(1,n);\n\n% loop all segments\nfor i = 1:n\n    a = s(1:2,i); % endpoints\n    b = s(3:4,i);\n    ad = d(1,i);  % depths\n    bd = d(2,i);\n\n    if ad<0 && bd<0 % both depths negative -> not visible\n        sv(:,i) = zeros(4,1);\n        vis(i) = false;\n\n    else\n\n        u = normvec(b-a); % uncorrected direction\n        if ad<0           % endpoint A is behind the camera\n            a = b + 1e6*u;\n        elseif bd<0       % endpoint B is behind the camera\n            b = a - 1e6*u;\n        end\n\n        % trim segment at image borders, with margin\n        ss = trimSegment([a;b],imSize,mrg);\n\n        % check visibility and assign output\n        if ...  % conditions for visibility (add with AND if needed)\n                ~isempty(ss) ...           % no-null vector\n                && (segLength(ss) >= lmin) % minimum length\n            \n            sv(:,i) = ss; % visible\n            vis(i) = true;\n        end\n    end\nend\n\nreturn\n\n%% test - generate 2 line handles\nlmin = 10;\nmrg = 0;\nimSize = [100;100];\ncla\naxis([0,imSize(1),0,imSize(2)])\nlh = line('color','r','linestyle','--')\nyh = line('color','c','linewidth',3);\n\n%% test - plot random lines\ns = 300+randn(4,1)*400\n% d = randn(2,1)\n\ns = [-20;50;120;50]\nd = [-1;-1]\n\n[sv,vis] = visibleSegment(s,d,imSize,mrg,lmin)\n\nset(lh,'xdata',s([1,3]),'ydata',s([2,4]))\nset(yh,'xdata',sv([1,3]),'ydata',sv([2,4]))\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 <http://www.gnu.org/licenses/>.\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/visibleSegment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.5832064745816241}}
{"text": "% function [xpad, nup, n1, n2] = padsignal(x, padtype, padlength)\n%\n% Pads signal and returns indices of original signal\n%\n% Input:\n%\tx: original signal\n%\tpadtype (optional): either 'symmetric' (default) or 'replicate'\n%   padlength (optional): number of samples to pad on each side; default is nearest power of 2\n% Output:\n%\tx: padded signal\n%   nup: next power of 2\n%   n1: length on left\n%   n2: length on right\n%\n%---------------------------------------------------------------------------------\n%    Synchrosqueezing Toolbox\n%    Authors: Eugene Brevdo, Gaurav Thakur\n%---------------------------------------------------------------------------------\nfunction [xpad, nup, n1, n2] = padsignal(x, padtype, padlength)\n\n[nup, n1, n2] = p2up(length(x));\nif nargin<3\n\t[nup, n1, n2] = p2up(length(x));\t%if padlength not given, pad up to nearest power of 2\nelse\n\tnup = length(x)+2*padlength;\n\tn1 = padlength-1;\n\tn2 = padlength;\nend\n\n%xl = padarray(x(:), n1, padtype, 'pre');\n%xr = padarray(x(:), n2, padtype, 'post');\n%xpad = [xl(1:n1); x(:); xr(end-n2+1:end)];\n%padarray needs image processing toolbox; below is equivalent code to avoid that\n\nx=x(:);\nn=length(x);\nif strcmpi(padtype,'symmetric')\n\txl = repmat([x;flipud(x)],[ceil(n1/(2*n)),1]);\n\txr = repmat([flipud(x);x],[ceil(n2/(2*n)),1]);\nelseif strcmpi(padtype,'replicate')\n\txl = x(1)*ones(n1,1);\n\txr = x(end)*ones(n2,1);\nend\n\nxpad = [xl(end-n1+1:end); x; xr(1:n2)];", "meta": {"author": "ebrevdo", "repo": "synchrosqueezing", "sha": "7e9fec0c6c9ed478dafac4479c0658d24fc6d8ef", "save_path": "github-repos/MATLAB/ebrevdo-synchrosqueezing", "path": "github-repos/MATLAB/ebrevdo-synchrosqueezing/synchrosqueezing-7e9fec0c6c9ed478dafac4479c0658d24fc6d8ef/synchrosqueezing/padsignal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.5832064663796707}}
{"text": "function b = cpbsl ( abd, lda, n, m, b )\n\n%*****************************************************************************80\n%\n%% CPBSL solves a complex hermitian positive definite band system.\n%\n%  Discussion:\n%\n%    The system matrix must have been factored by CPBCO or CPBFA.\n%\n%    A division by zero will occur if the input factor contains\n%    a zero on the diagonal.  Technically this indicates\n%    singularity but it is usually caused by improper subroutine\n%    arguments.  It will not occur if the subroutines are called\n%    correctly and INFO == 0.\n%\n%    To compute inverse(A) * C where C is a matrix with P columns:\n%\n%      call cpbco(abd,lda,n,rcond,z,info)\n%\n%      if (rcond is too small .or. info /= 0) then\n%        error\n%      end if\n%\n%      do j = 1, p\n%        call cpbsl(abd,lda,n,c(1,j))\n%      end do\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 May 2007\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, complex ABD(LDA,N), the output from CPBCO or CPBFA.\n%\n%    Input, integer LDA, the leading dimension of ABD.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Input, integer M, the number of diagonals above the main diagonal.\n%\n%    Input, complex B(N), the right hand side.\n%\n%    Output, complex B(N), the solution.\n%\n\n%\n%  Solve hermitian(R) * Y = B.\n%\n  for k = 1 : n\n    lm = min ( k - 1, m );\n    la = m + 1 - lm;\n    lb = k - lm;\n    t = abd(la:la+lm-1,k)' * transpose ( b(lb:lb+lm-1) );\n    b(k) = ( b(k) - t ) / abd(m+1,k);\n  end\n%\n%  Solve R * X = Y.\n%\n  for k = n : -1 : 1\n    lm = min ( k - 1, m );\n    la = m + 1 - lm;\n    lb = k - lm;\n    b(k) = b(k) / abd(m+1,k);\n    t = -b(k);\n    b(lb:lb+lm-1) = b(lb:lb+lm-1) + t * transpose ( abd(la:la+lm-1,k) );\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/linpack_c/cpbsl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5832064536617118}}
{"text": "function M = decode_qform0(hdr)\n% Decode qform info from NIFTI-1 headers.\n% _______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n%\n% $Id$\n\n\ndim    = double(hdr.dim);\npixdim = double(hdr.pixdim);\nif ~isfield(hdr,'magic') || hdr.qform_code <= 0,\n    flp = spm_flip_analyze_images;\n    %disp('------------------------------------------------------');\n    %disp('The images are in a form whereby it is not possible to');\n    %disp('tell the left and right sides of the brain apart.');\n    %if flp,\n    %    disp('They are assumed to be stored left-handed.');\n    %else\n    %    disp('They are assumed to be stored right-handed.');\n    %end;\n    %disp('------------------------------------------------------');\n\n    %R     = eye(4);\n    n      = min(dim(1),3);\n    vox    = [pixdim(2:(n+1)) ones(1,3-n)];\n\n    if ~isfield(hdr,'origin') || ~any(hdr.origin(1:3)),\n       origin = (dim(2:4)+1)/2;\n    else\n        origin = double(hdr.origin(1:3));\n    end;\n    off     = -vox.*origin;\n    M       = [vox(1) 0 0 off(1) ; 0 vox(2) 0 off(2) ; 0 0 vox(3) off(3) ; 0 0 0 1];\n\n    % Stuff for default orientations\n    if flp, M = diag([-1 1 1 1])*M; end;\nelse\n\n    % Rotations from quaternions\n    R = Q2M(double([hdr.quatern_b hdr.quatern_c hdr.quatern_d]));\n\n    % Translations\n    T = [eye(4,3) double([hdr.qoffset_x hdr.qoffset_y hdr.qoffset_z 1]')];\n\n    % Zooms.  Note that flips are derived from the first\n    % element of pixdim, which is normally unused.\n    n = min(dim(1),3);\n    Z = [pixdim(2:(n+1)) ones(1,4-n)];\n    Z(Z<0) = 1;\n    if pixdim(1)<0, Z(3) = -Z(3); end;\n    Z = diag(Z);\n\n    M = T*R*Z;\n\n    % Convert from first voxel at [1,1,1]\n    % to first voxel at [0,0,0]\n    M = M * [eye(4,3) [-1 -1 -1 1]'];\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/@nifti/private/decode_qform0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5831152555005132}}
{"text": "function [mean_m1, b1, sig1, av2] =  bmemag(mag);\n    %BMEMAG\n    maximum_mag = max(mag );\n    minimum_mag = min(mag );\n    if minimum_mag > 0 ; minimum_mag = 0 ; end\n\n    % calculate the mean magnitude, b(mean) and std\n    n = length(mag );\n    mean_m1 = mean(mag );\n    b1 = (1/(mean_m1-min(mag -0.05)))*log10(exp(1));\n    sig1 = (sum((mag -mean_m1).^2))/(n*(n-1));\n    sig1 = sqrt(sig1);\n    sig1 = 2.30*sig1*b1^2;            % standard deviation\n    %disp ([' b-value segment 1 = ' num2str(b1) ]);\n    %disp ([' standard dev b_val_1 = ' num2str(sig1) ]);\n    av2 = log10(length(mag ))+b1*min(mag );\nend", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/+Catalog/+bvalue_lib/bmemag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5831152475239737}}
{"text": "classdef L2N < dagnn.Filter\n% L2N layer that is L2-normalizing input vectors\n%\n% Authors: F. Radenovic, G. Tolias, O. Chum. 2017. \n\n  methods\n    function outputs = forward(self, inputs, params)\n      outputs{1} = vl_nnnormalizelp(inputs{1}, 'p', 2, 'epsilon', 1e-6);\n    end\n\n    function [derInputs, derParams] = backward(self, inputs, params, derOutputs)\n      derInputs{1} = vl_nnnormalizelp(inputs{1}, derOutputs{1}, 'p', 2, 'epsilon', 1e-6);\n      derParams = {} ;\n    end\n\n    function obj = L2N(varargin)\n      obj.load(varargin) ;\n    end\n  end\nend\n", "meta": {"author": "filipradenovic", "repo": "cnnimageretrieval", "sha": "93a7391a2f8b13ff189d0c6131b95e0363542659", "save_path": "github-repos/MATLAB/filipradenovic-cnnimageretrieval", "path": "github-repos/MATLAB/filipradenovic-cnnimageretrieval/cnnimageretrieval-93a7391a2f8b13ff189d0c6131b95e0363542659/cnnblocks/L2N.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5831128735587515}}
{"text": "%Program for Construction of a two-out-of-two Visual Cryptography Scheme\n\n%Author : Athi Narayanan S\n%M.E, Embedded Systems,\n%K.S.R College of Engineering\n%Erode, Tamil Nadu, India.\n%http://sites.google.com/site/athisnarayanan/\n%s_athi1983@yahoo.co.in\n\n%Program Description\n%This program generates a two-out-of-two Visual Cryptography Scheme shares.\n%The input image for this program should be a binary image.\n%The shares and the overlapping result of the shares are written as output.\n%\n%Usage:\n%Input: inImg - A binary image\n%Output: share1  - Generated share 1\n%        share2  - Generated share 2\n%        share12 - Overlapped result of shares 1 & 2\n\nfunction [share1, share2, share12] = VisCrypt(inImg)\n\ns = size(inImg);\nshare1 = zeros(s(1), (2 * s(2)));\nshare2 = zeros(s(1), (2 * s(2)));\n\n%%White Pixel Processing\n%White Pixel share combinations\ndisp('White Pixel Processing...');\ns1a=[1 0];\ns1b=[1 0];\n[x y] = find(inImg == 1);\nlen = length(x);\n\nfor i=1:len\n    a=x(i);b=y(i);\n    pixShare=generateShare(s1a,s1b);\n    share1((a),(2*b-1):(2*b))=pixShare(1,1:2);\n    share2((a),(2*b-1):(2*b))=pixShare(2,1:2);\nend\n\n%Black Pixel Processing\n%Black Pixel share combinations\ndisp('Black Pixel Processing...');\ns0a=[1 0];\ns0b=[0 1];\n[x y] = find(inImg == 0);\nlen = length(x);\n\nfor i=1:len\n    a=x(i);b=y(i);\n    pixShare=generateShare(s0a,s0b);\n    share1((a),(2*b-1):(2*b))=pixShare(1,1:2);\n    share2((a),(2*b-1):(2*b))=pixShare(2,1:2);\nend\n\nshare12=bitor(share1, share2);\nshare12 = ~share12;\ndisp('Share Generation Completed.');", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24981-visual-cryptography/Visual_Cryptography/VisCrypt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727026, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5831128628050067}}
{"text": "function Population = ArchiveUpdate(Population,N)\n% Update archive\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    %% Select feasible solutions\n    fIndex     = all(Population.cons <= 0,2);\n    Population = Population(fIndex);\n    if isempty(Population)\n        return\n    else\n        if size(Population.objs,2)==2\n            %% Non-dominated sorting\n            [FrontNo,~] = NDSort(Population.objs,1);\n            Next = (FrontNo == 1);    \n            Population = Population(Next);    \n            if sum(Next) > N\n                %% Calculate the crowding distance of each solution\n                CrowdDis   = CrowdingDistance(Population.objs);\n                [~,Rank]   = sort(CrowdDis,'descend');\n                Population = Population(Rank(1:N));\n            end\n        else    \n            Population = Population(NDSort(Population.objs,1)==1);\n            Population = Population(randperm(length(Population)));\n            PCObj = Population.objs;\n            nND   = length(Population);\n            %% Population maintenance\n            if length(Population) > N\n                % Normalization\n                fmax  = max(PCObj,[],1);\n                fmin  = min(PCObj,[],1);\n                PCObj = (PCObj-repmat(fmin,nND,1))./repmat(fmax-fmin,nND,1);\n                % Determine the radius of the niche\n                d  = pdist2(PCObj,PCObj);\n                d(logical(eye(length(d)))) = inf;\n                sd = sort(d,2);\n                r  = mean(sd(:,min(3,size(sd,2))));\n                R  = min(d./r,1);\n                % Delete solution one by one\n                while length(Population) > N\n                    [~,worst]  = max(1-prod(R,2));\n                    Population(worst)  = [];\n                    R(worst,:) = [];\n                    R(:,worst) = [];\n                end\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/Algorithms/Multi-objective optimization/MOEA-D-DAE/ArchiveUpdate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5831128600829538}}
{"text": "function plotData(X, y)\n%PLOTDATA Plots the data points X and y into a new figure \n%   PLOTDATA(x,y) plots the data points with + for the positive examples\n%   and o for the negative examples. X is assumed to be a Mx2 matrix.\n\n% Create New Figure\nfigure; hold on;\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Plot the positive and negative examples on a\n%               2D plot, using the option 'k+' for the positive\n%               examples and 'ko' for the negative examples.\n%\n\npos = find(y == 1);\nneg = find(y == 0);\nplot(X(pos, 1), X(pos, 2), 'k+' ,'LineWidth', 2, 'MarkerSize', 7);\nplot(X(neg, 1), X(neg, 2), 'ko', 'MarkerFaceColor', 'y', 'MarkerSize', 7);\n\n\n\n\n\n% =========================================================================\n\n\n\nhold off;\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/plotData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.583083770960981}}
{"text": "%==============================================================================\n% This code is part of the Finite Element Method app for the Matlab-based toolbox\n%  FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR/FAIRFEM \n%==============================================================================\n%\n% classdef TriMesh3 < handle\n%\n% Finite Element Mesh based on triangular subdivision of rectangular mesh.\n%\n% Each Cell is divided into four triangles:\n%\n%  o---------o---------o---------o---------o\n%  | \\     / | \\     / | \\     / | \\     / |\n%  |   \\ /   |   \\ /   |   \\ /   |   \\ /   |\n%  |    X    |    X    |    X    |    X    |\n%  |  /  \\   |  /  \\   |  /  \\   |  /  \\   |\n%  |/      \\ |/      \\ |/      \\ |/      \\ |\n%  o---------o---------o---------o---------o\n%  | \\     / | \\     / | \\     / | \\     / |\n%  |   \\ /   |   \\ /   |   \\ /   |   \\ /   |\n%  |    X    |    X    |    X    |    X    |\n%  |  /  \\   |  /  \\   |  /  \\   |  /  \\   |\n%  |/      \\ |/      \\ |/      \\ |/      \\ |\n%  o---------o---------o---------o---------o\n%  | \\     / | \\     / | \\     / | \\     / |\n%  |   \\ /   |   \\ /   |   \\ /   |   \\ /   |\n%  |    X    |    X    |    X    |    X    |\n%  |  /  \\   |  /  \\   |  /  \\   |  /  \\   |\n%  |/      \\ |/      \\ |/      \\ |/      \\ |\n%  o---------o---------o---------o---------o\n%\n%  To construct an instance of this class type:\n%\n%  >> Mesh = TriMesh3(omega,m)\n%\n% Input:\n% \tomega - description of spatial domain\n%   m     - number of cells\n%\n% Properties:\n%   xn     - node list\n%   tri    - triangle list\n%   dim    - space dimension\n%   omega  - description of spatial domain\n%   m      - number of cells\n%   type   - type of partition\n%   vol    - volume of triangles\n%   nnodes - number of nodes\n%   ntri   - number of triangles\n%   dx1    - partial derivative operator\n%   dx2    - partial derivative operator\n%   GRAD   - gradient operator\n%   P1     - projection operator for node 1\n%   P2     - projection operator for node 2\n%   P3     - projection operator for node 3\n%   PC     - projection operator for Barycentrum\n%   P      - prolongation operator\n%   Pt     - restriction operator\n%\n%  Methods:\n%   mfPu   - matrix free prolongation/restriction\n%   mfPi   - matrix free edge projector\n%   getP   - builds prolongation operator\n%   tri2cc - averaging\n%\n%\n% see also\n% =========================================================================\nclassdef TriMesh3 < handle\n    \n    properties\n        % ===================================\n        % node list\n        % ===================================\n        xn\n        % ===================================\n        % triangle list\n        % ===================================\n        tri\n        % ===================================\n        % space dimension\n        % ===================================\n        dim  = 2;\n        % ===================================\n        % description of computational domain\n        % ===================================\n        omega\n        % ===================================\n        % number of cells\n        % ===================================\n        m\n        % ===================================\n        % type of partition\n        % ===================================\n        type = 3;\n        % ===================================\n        % function handle to myself\n        % ===================================\n        me = @TriMesh3\n        % ===================================\n        % volume of triangles\n        % ===================================\n        vol\n        % ===================================\n        % number of nodes\n        % ===================================\n        nnodes\n        % ===================================\n        % number of triangles in mesh\n        % ===================================\n        ntri\n    end\n    \n    properties (Access = public, Dependent) % These will be created when first callend and stores persistently\n        % ===================================\n        % dx1  - partial derivative operator\n        % ===================================\n        dx1\n        % ===================================\n        % dx2  - Partial derivative operator\n        % ===================================\n        dx2\n        % ===================================\n        % GRAD - Gradient operator\n        %\n        %         | dx1 |\n        %  GRAD = |     |\n        %         | dx2 |\n        %\n        % ===================================\n        GRAD\n        % ===================================\n        % B - Vector gradient operator\n        %\n        %         | GRAD  0    |\n        %  B =    |            |\n        %         | 0     GRAD |\n        %\n        % ===================================\n        B\n        % ===================================\n        % P1 - Projection operator on Node 1\n        % ===================================\n        P1\n        % ===================================\n        % P2 - Projection operator on Node 2\n        % ===================================\n        P2\n        % ===================================\n        % P3 - Projection operator on Node 3\n        % ===================================\n        P3\n        % ===================================\n        % PC - Projection operator on Barycenter\n        % ===================================\n        PC\n        % ===================================\n        % P  - Prolongation operator\n        % ===================================\n        P\n        % ===================================\n        % Pt - Restriction operator\n        % ===================================\n        Pt\n        % ===================================\n        % Boundary indices\n        % ===================================\n        boundaryIdx\n        % ===================================\n        % Boundary projector\n        % ===================================\n        boundaryProj\n        AvN\n        mfdx1\n        mfdx2\n        mfGRAD\n    end\n    \n    properties (Access = private)\n        % These are where the dependent data is actually stored\n        dx1_\n        dx2_\n        GRAD_\n        B_\n        P1_\n        P2_\n        P3_\n        PC_\n        P_\n        Pt_\n        mfdx1_\n        mfdx2_\n        mfGRAD_\n        boundaryIdx_\n        boundaryProj_\n        AvN_\n    end\n    \n    \n    methods\n        function this = TriMesh3(omega,m)\n            if nargin==0,\n                help(mfilename);\n                this.runMinimalExample;\n                return;\n            end\n            this.omega = omega;\n            this.m     = m;\n            \n            this.xn = [ reshape(getNodalGrid(omega,m),[],2);...\n               reshape(getCellCenteredGrid(omega,m),[],2)];\n  \n            % get indices of bottom left vertices\n            nodes = reshape(1:prod(m+1),m+1);\n            nodes = reshape(nodes(1:end-1,1:end-1),1,[]);\n            % get indices of cell-centered points\n            cc    = prod(m+1)+(1:prod(m));\n            % specify triangles\n            this.tri   = [...\n                nodes;          nodes+1;        cc; ...\n                nodes+1;        nodes+m(1)+2;   cc; ...\n                nodes+m(1)+2;   nodes+m(1)+1;   cc; ...\n                nodes+m(1)+1;   nodes;          cc; ...\n                ];\n            this.tri   = reshape(this.tri,3,[])';\n            \n            this.nnodes = prod(m+1)+prod(m);\n            this.ntri  = size(this.tri,1);\n            this.vol = prod((omega(2:2:end)-omega(1:2:end))./m)/4*ones(this.ntri,1);\n            \n        end\n        \n        function runMinimalExample(~)\n            omega = [0 4 2 6]; m = [3 6];\n            Mesh  = feval(mfilename,omega,m);\n            figure(3); clf;\n            set(gcf,'Name',sprintf('%s, m=[%d,%d]',mfilename,m));\n            plotTriMesh(Mesh,Mesh.xn);\n        end\n        \n        function x = mfPi(this,x,i)\n            % =============================================================\n            % function x = mfPi(this,x,i)\n            %\n            % matrix free edge projector\n            % =============================================================\n            switch i\n                case 1\n                    P = this.P1;\n                case 2\n                    P = this.P2;\n                case 3\n                    P = this.P3;\n                case 'C'\n                    P = this.PC;\n            end\n            if size(x,1) == this.ntri,\n                % ajoint\n                x = P'*x;\n            else\n                x = P * x;\n            end\n        end\n        \n        function x = tri2cc(this,x)\n            % =============================================================\n            % function x = tri2cc(x)\n            %\n            % averaging or adjoint\n            % =============================================================\n            if numel(x)==this.ntri,\n                x = mean(reshape(x,4,[]),1);\n            else\n                x = reshape(x,1,[]);\n                x = .25*repmat(x,[1 4]);\n                x = x(:);\n            end\n            \n        end\n        \n        % ===================================\n        % x = getNodalGridData(this,x)\n        %\n        % gets values at triangle nodes that belong the underlying nodal\n        % grid\n        % ===================================\n        function x = getNodalGridData(this,x)\n            x = reshape(x,prod(this.nnodes),[]);\n            x = x(1:prod(this.m+1),:);\n            x = x(:);\n        end\n        \n        % ===================================\n        % x = getCCGridData(this,x)\n        %\n        % gets values at cell-centers that belong the underlying nodal\n        % grid\n        % ===================================\n        function x = getCCGridData(this,x)\n            x = reshape(x,prod(this.nnodes),[]);\n            x = x(prod(this.m+1)+1:end,:);\n            x = x(:);\n        end\n        \n        \n        \n        function Pu = mfPuNodal(~,yn,m,flag)\n            % =============================================================\n            % function Pu = mfPuNodal(~,yn,m,flag)\n            %\n            % matrix free prolongation/restriction for nodal quantities\n            % =============================================================\n            switch flag\n                case 'Pu' % coarse --> fine\n                    yn = reshape(yn,[],2);\n                    yc = reshape(yn(prod(m+1)+1:end,:),[m 2]);\n                    yn = reshape(yn(1:prod(m+1),:),[m+1 2]);\n                    \n                    Pyn = zeros([2*m+1 2]);\n                    Pyc = zeros([2*m 2]);\n                    \n                    % include existing nodes\n                    Pyn(1:2:end,1:2:end,:) = yn;\n                    % prolongate in x direction\n                    Pyn(2:2:end-1,:,:) =  .5*(Pyn(1:2:end-2,:,:) + Pyn(3:2:end,:,:));\n                    % prolongate in y direction\n                    Pyn(1:2:end,2:2:end-1,:) =  .5*(Pyn(1:2:end,1:2:end-2,:) + Pyn(1:2:end,3:2:end,:));\n                    % midpoints\n                    Pyn(2:2:end,2:2:end,:)   = yc;\n                    \n                    % compute cell-centers\n                    Pyc(1:2:end-1,1:2:end-1,:) = .5*(yn(1:end-1,1:end-1,:) + yc);\n                    Pyc(2:2:end  ,1:2:end-1,:) = .5*(yn(2:end  ,1:end-1,:) + yc);\n                    Pyc(1:2:end-1,2:2:end  ,:) = .5*(yn(1:end-1,2:end  ,:) + yc);\n                    Pyc(2:2:end  ,2:2:end  ,:) = .5*(yn(2:end  ,2:end  ,:) + yc);\n                    \n                    Pu = [reshape(Pyn,[],2); reshape(Pyc,[],2)];\n                    Pu = Pu(:);\n                case 'PTu'\n                    yn = reshape(yn,[],2);\n                    yc = reshape(yn(prod(m+1)+1:end,:),[m 2]);\n                    yn = reshape(yn(1:prod(m+1),:),[m+1 2]);\n                    \n                    % include parent nodes\n                    Pyn = yn(1:2:end,1:2:end,:);\n                    % distribute in x direction\n                    t = .5* yn(2:2:end-1,1:2:end,:);\n                    Pyn(1:end-1,:,:)   = Pyn(1:end-1,:,:) + t;\n                    Pyn(2:end  ,:,:)   = Pyn(2:end  ,:,:) + t;\n                    \n                    % distribute in y direction\n                    t = .5* yn(1:2:end,2:2:end-1,:);\n                    Pyn(:,1:end-1,:) = Pyn(:,1:end-1,:) + t;\n                    Pyn(:,2:end  ,:) = Pyn(:,2:end  ,:) + t;\n                    \n                    % distribute cell-centers\n                    t1 = .5*yc(1:2:end-1,1:2:end-1,:);\n                    t2 = .5*yc(2:2:end  ,1:2:end-1,:);\n                    t3 = .5*yc(1:2:end-1,2:2:end  ,:);\n                    t4 = .5*yc(2:2:end  ,2:2:end  ,:);\n                    Pyc = yn(2:2:end,2:2:end,:) + (t1+t2+t3+t4);\n                    Pyn(1:end-1,1:end-1,:) = Pyn(1:end-1,1:end-1,:) + t1;\n                    Pyn(2:end  ,1:end-1,:) = Pyn(2:end  ,1:end-1,:) + t2;\n                    Pyn(1:end-1,2:end  ,:) = Pyn(1:end-1,2:end  ,:) + t3;\n                    Pyn(2:end  ,2:end  ,:) = Pyn(2:end  ,2:end  ,:) + t4;\n                    \n                    Pu = [reshape(Pyn,[],2); reshape(Pyc,[],2)];\n                    Pu = Pu(:);\n            end\n        end\n        \n        function P = getPuNodal(~,m)\n            % =============================================================\n            % function P = getPuNodal(~,m)\n            %\n            % returns prolongation operator for input of cell-width m\n            % =============================================================\n            \n            mf = 2*m;\n            % indices of fine and coarse grid nodes\n            indfn = reshape(1:prod(mf+1),mf+1);\n            indfc = reshape(prod(mf+1)+(1:prod(mf)),mf);\n            indcn = reshape(1:prod(m+1),m+1);\n            indcc = reshape(prod(m+1)+(1:prod(m)),m);\n            \n            % allocate space\n            I = []; J = []; W = [];\n            \n            % include existing nodes\n            ii = indfn(1:2:end,1:2:end);\n            jj = indcn(:);\n            ww = ones(size(jj));\n            I = [I; ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            \n            % include midpoint as node\n            ii = indfn(2:2:end,2:2:end);\n            jj = indcc(:);\n            ww = ones(size(jj));\n            I = [I; ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            \n            % prolongate in x direction\n            ii   = indfn(2:2:end-1,1:2:end);\n            jj   = [reshape(indcn(1:end-1,:),[],1); reshape(indcn(2:end,:),[],1)];\n            ww = .5*ones(size(jj));\n            I = [I; ii(:);ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            \n            % prolongate in y direction\n            ii   = indfn(1:2:end,2:2:end-1);\n            jj   = [reshape(indcn(:,1:end-1),[],1); reshape(indcn(:,2:end),[],1)];\n            ww   = .5*ones(size(jj));\n            I = [I; ii(:); ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            \n            % prolongate from bottom-left to top-right\n            ii   = indfc(1:2:end,1:2:end);\n            jj   = [reshape(indcn(1:end-1,1:end-1),[],1); reshape(indcc,[],1)];\n            ww   = .5*ones(size(jj));\n            I = [I; ii(:); ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            ii   = indfc(2:2:end,2:2:end);\n            jj   = [reshape(indcn(2:end,2:end),[],1); reshape(indcc,[],1)];\n            ww   = .5*ones(size(jj));\n            I = [I; ii(:); ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            \n            \n            % prolongate from top-left to bottom-right\n            ii   = indfc(2:2:end,1:2:end);\n            jj   = [reshape(indcn(2:end,1:end-1),[],1); reshape(indcc,[],1)];\n            ww   = .5*ones(size(jj));\n            I = [I; ii(:); ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            ii   = indfc(1:2:end,2:2:end);\n            jj   = [reshape(indcn(1:end-1,2:end),[],1); reshape(indcc,[],1)];\n            ww   = .5*ones(size(jj));\n            I = [I; ii(:); ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n            \n            P = sparse(I,J,W,prod(mf+1)+prod(mf),prod(m+1)+prod(m));\n        end\n        \n        \n        \n        % ========== get methods ========================================\n        function dx1 = get.dx1(this)\n            if isempty(this.dx1_),\n                [this.dx1_, this.dx2_] = getGradientMatrixFEM(this,0);\n            end\n            dx1 = this.dx1_;\n        end\n        \n        function dx2 = get.dx2(this)\n            if isempty(this.dx2_),\n                [this.dx1_, this.dx2_] = getGradientMatrixFEM(this,0);\n            end\n            dx2 = this.dx2_;\n        end\n        \n        function GRAD = get.GRAD(this)\n            if isempty(this.GRAD_),\n                this.GRAD_ = [this.dx1;this.dx2];\n            end\n            GRAD = this.GRAD_;\n        end\n        function B = get.B(this)\n            if isempty(this.B_),\n                this.B_ = blkdiag(this.GRAD,this.GRAD);\n            end\n            B = this.B_;\n        end\n        \n        function P1 = get.P1(this)\n            if isempty(this.P1_),\n                A = speye(this.nnodes);\n                this.P1_ = A(this.tri(:,1),:);\n            end\n            P1 = this.P1_;\n        end\n        function P2 = get.P2(this)\n            if isempty(this.P2_),\n                A = speye(this.nnodes);\n                this.P2_ = A(this.tri(:,2),:);\n            end\n            P2 = this.P2_;\n        end\n        \n        function P3 = get.P3(this)\n            if isempty(this.P3_),\n                A = speye(this.nnodes);\n                this.P3_ = A(this.tri(:,3),:);\n            end\n            P3 = this.P3_;\n        end\n        function PC = get.PC(this)\n            if isempty(this.PC_),\n                this.PC_ = (this.P1+this.P2+this.P3)/3;\n            end\n            PC = this.PC_;\n        end\n        function P = get.P(this)\n            if isempty(this.P_),\n                this.P_ = this.getPuNodal(this.m);\n            end\n            P = this.P_;\n        end\n        function Pt = get.Pt(this)\n            if isempty(this.Pt_),\n                this.Pt_ = this.getPuNodal(this.m/2);\n            end\n            Pt = this.Pt_;\n        end\n        \n        function mfdx1 = get.mfdx1(this)\n            if isempty(this.mfdx1_),\n                [this.mfdx1_, this.mfdx2_] = getGradientMatrixFEM(this,1);\n            end\n            mfdx1 = this.mfdx1_;\n        end\n        \n        function mfdx2 = get.mfdx2(this)\n            if isempty(this.mfdx2_),\n                [this.mfdx1_, this.mfdx2_] = getGradientMatrixFEM(this,1);\n            end\n            mfdx2 = this.mfdx2_;\n        end\n        \n        function AvN = get.AvN(this)\n            if isempty(this.AvN_),\n                av  = @(n) spdiags(ones(n+1,1)*[0.5 0.5],[0,1],n,n+1);\n                this.AvN_ = kron(speye(2), [speye(prod(this.m+1)); kron(av(this.m(2)),av(this.m(1)))]);\n            end\n            AvN = this.AvN_;\n        end\n        \n        function mfGRAD = get.mfGRAD(this)\n            if isempty(this.mfGRAD_),\n                this.mfGRAD_ = getGradientMatrixFEM(this,1);\n            end\n            mfGRAD = this.mfGRAD_;\n        end\n        function idx = get.boundaryIdx(this)\n            if isempty(this.boundaryIdx_),\n                id = reshape(1:prod(this.m+1),this.m+1);\n                idx = [reshape(id([1,end],:),[],1);reshape(id(2:end-1,[1,end]),[],1)] ;\n                this.boundaryIdx_ = idx;\n            end\n            idx = this.boundaryIdx_;\n        end\n        \n        function idx = get.boundaryProj(this)\n            if isempty(this.boundaryProj_),\n                idx = this.boundaryIdx;\n                \n                P = speye(prod(this.m+1));\n                P = P(idx,:);\n                P = [P,sparse(size(P,1),prod(this.m))];\n                P = kron(speye(2),P);\n                \n                this.boundaryProj_ = P;\n            end\n            idx = this.boundaryProj_;\n        end \n        \n        % ========== set methods ========================================\n        function set.xn(this,xn)\n            if numel(xn)~=(2*(prod(this.m+1)+prod(this.m))),\n                error('Invalid number of nodes');\n            end\n            if isempty(this.xn),\n                this.xn = xn;\n            else\n                \n                this.xn = xn;\n                % delete operators that are sensitive to nodes\n                this.dx1_  = [];\n                this.dx2_  = [];\n                this.GRAD_ = [];\n                this.B_    = [];\n                \n                this.vol = volTetraGrid(this,this.xn,'matrixFree',1);\n            end\n        end\n    end\nend\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/add-ons/FAIRFEM/meshes/TriMesh3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5830837695866633}}
{"text": "function l = lumHK(img)\n%\n%       l = lum(img)\n%\n%       This function calculates the Helmholtz-Kohlrausch luminance\n%\n%\n%       input:\n%           img: an RGB image\n%\n%       output:\n%           l: normalized Helmholtz-Kohlrausch luminance\n%\n%     Copyright (C) 2015  Francesco Banterle\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n%\n\ncheck3Color(img);\n\nimgXYZ = ConvertRGBtoXYZ(img, 0);\nimgLCh = ConvertXYZtoCIELCh(imgXYZ, 0);\n\nL = imgLCh(:,:,1);\nC = imgLCh(:,:,2);\nh = imgLCh(:,:,3);\n\nh2 = ((h - 90) / 2) * pi / 360;\n\nl = L + (2.5 - 0.025 * L) .* (0.116 * abs(sin(h2)) + 0.085) .* C;\nl = l / max(l(:));\n\nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/ColorSpace/lumHK.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5830490019805801}}
{"text": "function nMM=grMaxMatch(E)\n% Function nMM=grMaxMath(E) solve the maximal matching problem.\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 edge;\n%     m - number of edges.\n%     If we set the array E(m,2), then all weights is 1.\n% Output parameter:\n%   nMM - the list of the numbers of edges included \n%     in the maximal (weighted) matching.\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\n\n% ============= Parameters of integer LP problem ==========\nA=zeros(n,m); % for incidence matrix\nA(E(:,1:2)+repmat(([1:m]'-1)*n,1,2))=1; % we fill the incidence matrix\noptions=optimset('bintprog'); % the default options\noptions.Display='off'; % we change the output\n\n% ============= We solve the integer LP problem ==========\nxmin=bintprog(-E(:,3),A,ones(n,1),[],[],[],options);\nnMM=find(round(xmin)); % the answer - numbers of edges\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(\u56fe\u8bba)/basic/grMaxMatch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5830489858969816}}
{"text": "function out = binavgcol(in, numinbin)\n% Rebins image by averaging numinbin bins together along columns of the\n% 2D data.\n% out = binavgcol(in, numinbin)\n\ndi=0;\nif strcmp(class(in),'dip_image')\n    di=1;\n    in=double(in);\nend\ntmp = in;\n\nfor ii=2:numinbin\n    tmp = tmp + circshift(in,[-1*(ii-1) 0]);\nend\n\nnb = floor(size(in,1)/numinbin);\nix=numinbin*(1:nb)-(numinbin-1);\nout = tmp(ix,:)/numinbin;\nif di\n    out=dip_image(out);\nend", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/image_proc/binavgcol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5830372751425079}}
{"text": "function [p sres sres_ns] = ResidScan(res, FWHM)\n% Calculates P(M>=t) where M is the max value of the smoothed residuals.\n% In this implementation the residuals are smoothed using a Gaussian\n% kernel.\n%\n% :Usage:\n% ::\n%\n%     function [p sres sres_ns] = ResidScan(res, FWHM)\n%\n% :Inputs:\n%\n%   **res:**\n%        residual time course\n%\n%   **FWHM:**\n%        Full Width Half Maximum (in time units)\n%\n% :Outputs:\n%\n%   **p:**\n%        pvalues\n%\n%   **sres:**\n%        smoothed residuals\n%\n%   **sres_ns:**\n%        smoothed residuals (non standardized) \n%\n% ..\n%    By Martin Lindquist & Ji-Meng Loh, July 2007\n%\n%    Edited by ML on 10/02/09\n% ..\n\nres_ns = res;\nres = res./std(res);\nlen = length(res);\n\n% Create Gaussian Kernel\nsig = ceil(FWHM/(2*sqrt(2*log(2))));    \nklen = 3*sig;\nkern = normpdf((-klen:klen),0,sig); \nkern = kern./sqrt(sum(kern.^2));\n\n% Convolve\nx = conv(res,kern);\nsres = x((klen + 1):(end-klen));\n\nx = conv(res_ns,kern/sum(kern));\nsres_ns = x((klen + 1):(end-klen));\n\n\n% Find Max value\n[a,location] = max(abs(sres));\n\n% Find p-values using Gaussian Random Field theory\nz = Euler_p(1, a, len, FWHM);\nz = 2*z;        %Two-sided test\np = min(1, z);\n\nend\n\n% END MAIN FUNCTION\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Subfunctions\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nfunction pval = Euler_p(myDim, value, N, fwhm)\n% function z = Euler_p(myDim, value, N, fwhm)\n%\n% Finds the p value using the expected Euler characteristic. \n% \n% This function returns P(M \\ge value) using the approximation \n% \\sum_{d=0}^D R_d(V) \\rho_d(value) following Worsley et al's \"A Unified\n% Statistical Approach for Determining Significant Signals in Images of\n% Cerebral Activation\".\n%\n% INPUTS:\n%\n% myDim - the number of dimensions in the data\n% value - the value of the maximum. \n% N     - the number of (time) points in that 1 dimension \n% fwhm  - the full width half maximum\n%\n% OUTPUTS:\n%\n% pval - the p-value\n\n% NOTE: CURRENTLY THIS FUNCTION IS ONLY IMPLEMENTED FOR THE 1D CASE\n\n  % Constants \n  myfactor = 4*log(2);\n  pi2 = 2*pi;\n  exptsq = exp(-(value^2)/2);\n\n  % Euler Characteristc Densties\n  rho = zeros(5,1);\n  rho(1) = 1-normcdf(value);\n  rho(2) = myfactor^(0.5)*exptsq/pi2;\n  rho(3) = myfactor * exptsq * value / (pi2 ^ (1.5));\n  rho(4) = myfactor ^ (1.5) * exptsq * (value^2-1) / (pi2 ^2);\n  rho(5) = myfactor ^2 * exptsq * (value^3-3*value) / (pi2 ^ (5/2));\n     \n  % Resel Count\n  R0 = 1;\n  R1 = N/fwhm;\n\n  % P-value\n  pval = R0 * rho(1) + R1 * rho(2);\n\nend\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/HRF_Est_Toolbox2/ResidScan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5830372647149863}}
{"text": "% anova1_cell() - compute F-values in cell array using ANOVA.\n%\n% Usage:\n%    >> [F df] = anova1_cell( data );\n%\n% Inputs:\n%   data       = data consisting of PAIRED arrays to be compared. The last \n%                dimension of the data array is used to compute ANOVA.\n% Outputs:\n%   F   - F-value\n%   df  - degree of freedom (array)\n%\n% Note: the advantage over the ANOVA1 function of Matlab statistical\n%       toolbox is that this function works on arrays (see examples). Note\n%       also that you still need the statistical toolbox to assess\n%       significance using the fcdf() function. The other advantage is that\n%       this function will work with complex numbers.\n%\n% Example:\n%   a = { rand(1,10) rand(1,10) rand(1,10) }\n%   [F df] = anova1_cell(a)\n%   signif = 1-fcdf(F, df(1), df(2))\n%\n%   % for comparison \n%   anova1( [ a{1,1}' a{1,2}' a{1,3}' ]) % look in the graph for the F value\n%\n%   b = { [ a{1,1}; a{1,1} ] [ a{1,2}; a{1,2} ] [ a{1,3}; a{1,3} ] }\n%   [F df] = anova1_cell(b)\n%\n%   c{1,1} = reshape(repmat(b{1,1}, [2 1]),2,2,10);\n%   c{1,2} = reshape(repmat(b{1,2}, [2 1]),2,2,10);\n%   c{1,3} = reshape(repmat(b{1,3}, [2 1]),2,2,10);\n%   [F df] = anova1_cell(c)\n%\n% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005\n%\n% Reference:\n%   Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill.\n\n% Copyright (C) Arnaud Delorme\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction [F, df] = anova1_cell(data)\n    \n    % This function does not return\n    % correct values (see bug 336)\n    % It should be fixed with Schaum's outlines p363\n    % but requires some work. It now calls\n    % anova2_cell which returns correct values\n    \n    warning off;\n    [ F tmp tmp2 df] =  anova2_cell(data);\n    warning on;\n    return;\n    \n    % compute all means and all std\n    % -----------------------------\n    nd = myndims( data{1} );\n    if nd == 1\n        \n        for i = 1:length(data)\n            n( i) = length(data{i});\n            m( i) = mymean(  data{i});\n            sd(i) = mystd(   data{i});\n        end;\n        nt = sum(n);\n        n   = n';\n        m   = m';\n        sd  = sd';\n        \n    elseif nd == 2  \n\n        for i = 1:length(data)\n            n( :,i) = ones(size(data{i},1),1) * size(data{i},2, 'single');\n            m( :,i) = mymean(  data{i},2);\n            sd(:,i) = mystd(   data{i},[],2);\n        end;\n        nt = sum(n(1,:));\n    \n    elseif nd == 3        \n        \n        for i = 1:length(data)\n            n( :,:,i) = ones(size(data{i},1),size(data{i},2)) * size(data{i},3, 'single');\n            m( :,:,i) = mymean(  data{i},3);\n            sd(:,:,i) = mystd(   data{i},[],3);\n        end;\n        nt = sum(n(1,1,:));\n        \n    else\n\n        for i = 1:length(data)\n            n( :,:,:,i) = ones(size(data{i},1),size(data{i},2), size(data{i},3)) * size(data{i},4, 'single');\n            m( :,:,:,i) = mymean(  data{i},4);\n            sd(:,:,:,i) = mystd(   data{i},[],4);\n        end;\n        nt = sum(n(1,1,1,:));\n        \n    end;\n    \n    mt = mean(m,nd);\n    ng = length(data); % number of conditions\n    \n    VinterG  = ( sum( n.*(m.^2), nd ) - nt*mt.^2 )/(ng-1);\n    VwithinG = sum( (n-1).*(sd.^2), nd )/(nt-ng);\n    F  = VinterG./VwithinG;\n    df = [ ng-1 ng*(size(data{1},nd)-1) ];\n\nfunction val = myndims(a)\n    if ndims(a) > 2\n        val = ndims(a);\n    else\n        if size(a,1) == 1,\n            val = 2;\n        elseif size(a,2) == 1,\n            val = 1;\n        else\n            val = 2;\n        end;\n    end;\n\nfunction res = mymean( data, varargin) % deal with complex numbers\n    res = mean( data, varargin{:});\n    if ~isreal(data)\n        res = abs( res );\n    end;\n\nfunction res = mystd( data, varargin) % deal with complex numbers\n    res = std( abs(data), varargin{:});\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/statistics/anova1_cell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5830372592580864}}
{"text": "function r = cosh(a)\n%COSH         Taylor hyperbolic cosine  cosh(a)\n%\n\n% written  05/21/09     S.M. Rump\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  e = 1e-30;\n  if 1+e==1-e                   % fast check for rounding to nearest\n    rndold = 0;\n  else\n    rndold = getround;\n    setround(0)\n  end\n\n  K = getappdata(0,'INTLAB_TAYLOR_ORDER');\n\n  st = a.t;\n  r = a;\n  N = size(a.t,2);\n  st(1,:) = sinh(a.t(1,:));\n  r.t(1,:) = cosh(a.t(1,:));\n  for j=2:K\n    at_ = a.t(2:j,:);           % some 3 % faster \n    st(j,:) = sum( repmat((1:j-1)',1,N).*r.t(j-1:-1:1,:).*at_ , 1 ) ./ (j-1);\n    r.t(j,:) = sum( repmat((1:j-1)',1,N).*st(j-1:-1:1,:).*at_ , 1 ) ./ (j-1);\n  end\n  r.t(K+1,:) = sum( repmat((1:K)',1,N).*st(K:-1:1,:).*a.t(2:K+1,:) , 1 ) ./ K;\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/taylor/@taylor/cosh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5830372590149475}}
{"text": "function [ Acc ] = ssvep_performance(CNT , params)\nopt = opt_cellToStruct(params);\n%% CCA - Anaysis\nSMT=[];\nfor onoff=1:2\n    cnt = CNT{onoff};\n    cnt=prep_filter(cnt, {'frequency', opt.band});    \n    CNTch = prep_selectChannels(cnt, {'Index', opt.channel_index});\n    SMT_iter = prep_segmentation(CNTch, {'interval', opt.time_interval});\n    if onoff==1\n        SMT= SMT_iter;\n        clear SMT_iter\n    else\n        SMT = prep_addTrials(SMT, SMT_iter);\n        clear SMT_iter\n    end\nend\n\ntot = size(SMT.x, 2);\ncount1= tot;\nfor i = 1: size(SMT.x, 2)\n    res_cca = ssvep_cca_analysis(squeeze(SMT.x(:,i,:)),{'marker',opt.marker;'freq', opt.freq;'fs', opt.fs;'time',opt.time});\n    [~, ind] = max(res_cca);\n    if SMT.y_dec(i) ~= ind\n        count1 = count1 -1;\n    end\nend\nAcc =count1/tot;\nclear CNTch SMT tot count1 i res_cca in\nend\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/GigaScience/function_SSVEP/SSVEP_performance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5830372542874637}}
{"text": "function rect = pos2rect(obj_center, obj_size, win_size)\n%POS2RECT Get rectangle [x,y,w,h] from obj_center [cx,cy] and size [w,h]\n% Parameters:\n%   obj_center Rectangle center location [cx, cy]\n%   obj_size   Rectangle dimensions [w,h]\n%   win_size   (optional) If [width, height] are given, the rectangle will\n%              stay within the boundaries [1, 1, width, height]\n  rect = [round(obj_center - obj_size./2), obj_size];\n  if exist('win_size','var')\n    if rect(1) < 1\n      corr = abs(rect(1)) + 1;\n      rect(1) = 1;\n      rect(3) = rect(3) - corr;\n    end\n    if rect(2) < 1\n      corr = abs(rect(2)) + 1;\n      rect(2) = 1;\n      rect(4) = rect(4) - corr;\n    end\n    if rect(1) + rect(3) > win_size(1)\n      rect(3) = win_size(1) - rect(1);\n    end\n    if rect(2) + rect(4) > win_size(2)\n      rect(4) = win_size(2) - rect(2);\n    end\n  end\nend\n\n\n", "meta": {"author": "flyers", "repo": "drone-tracking", "sha": "c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad", "save_path": "github-repos/MATLAB/flyers-drone-tracking", "path": "github-repos/MATLAB/flyers-drone-tracking/drone-tracking-c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad/trackers/DAT/src/pos2rect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5830372540443253}}
{"text": "function [T, M, S] = dtiTsqTestStat(g1, g2, Y, mask)\n\n% Computes voxel-wise Hotelling T^2 statistics for two groups from a data array of\n% diffusion tensors in dt6 format.\n%\n%   [T, M, S] = dtiTsqTestStat(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 XxYxZxpxN (or nxpxN), where X, Y, Z are the volume\n%                   dimensions and N is the number of subjects.\n%                   p is the vector dimension (p = 6 for DT6 data).\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           XxYxZxpx2 array of mean vectors for both groups (0 where mask = 0)\n%   S           XxYxZxpxp array of covariances (0 where mask = 0)\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 nx6xN format\n    Y = shiftdim(Y, -2);\nelse\n    Ind = 0;    % Data in XxYxZx6xN 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\np = size(Y, 4);\nY = permute(Y, [4 5 1 2 3]); % permutation required by ndfun\nYavg1 = mean(Y(:,g1,:,:,:), 2);\nYavg2 = mean(Y(:,g2,:,:,:), 2);\ndavg = Yavg1 - Yavg2;\nd1 = Y(:,g1,:,:,:)-repmat(Yavg1, [1 N1 1 1 1]);\nd2 = Y(:,g2,:,:,:)-repmat(Yavg2, [1 N2 1 1 1]);\nM = cat(2, Yavg1(:,1,:,:,:), Yavg2(:,1,:,:,:));\nclear Y*\nS = ndfun('mult', d1, permute(d1, [2 1 3:5])) + ndfun('mult', d2, permute(d2, [2 1 3:5]));\noutmask = repmat(shiftdim(~mask, -2), [p p 1 1 1]);\nS(outmask) = 0;\noutmask = repmat(eye(p), [1 1 size(mask)]) & outmask;\nS(outmask) = 1;\nb = ndfun('backslash', S, davg);\nb = ndfun('mult', permute(davg, [2 1 3:5]), b);\nT = b * N1*N2/(N1+N2) * (N1+N2-p-1)/p;\n\n% Adjust output\nT = permute(T, [3 4 5 1 2]);\nM = permute(M, [3 4 5 1 2]);\nS = permute(S, [3 4 5 1 2]);\nif Ind,\n    T = shiftdim(T, 2);\n    M = shiftdim(M, 2);\n    S = shiftdim(S, 2);\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/dtiTsqTestStat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5830372485874256}}
{"text": "function [L, stored_at] = quadtree_laplacian(C,W,CH,D,A)\n% QUADTREE_LAPLACIAN\n% Builds a finite difference Laplacian on a quadtree following the scheme\n% suggested by Bickel et al. \"Adaptative Simulation of Electrical\n% Discharges\". This code is *purposefully* not optimized beyond\n% asymptotics for simplicity in understanding its functionality and\n% translating it to other programming languages beyond prototyping.\n%\n% L = octree_laplacian(C,W,CH,D,A)\n%\n% Inputs:\n%   C #nodes by 3 matrix of cell centers\n%   W #nodes vector of cell widths (**not** half widths)\n%   CH #nodes by 4 matrix of child indeces (-1 if leaf node)\n%   D #nodes vector of tree depths\n%   A #nodes by #nodes sparse adjacency matrix, where a value of a in the\n%       (i,j) entry means that node j is to the a-th direction of i\n%       (a=1: left;  a=2: right;  a=3: bottom;  a=4: top).\n%\n% Outputs:\n%   L #num_children by #num_children sparse Laplacian matrix\n%   stored_at #num_children by 3 matrix of child cell centers, where the\n%       values of L are stored\n%\n%\n% Example:\n%\n% % Build an octree\n% P = 0.5*[cos(th),sin(th)];\n% P = [P;[-1,-1];[1,1]];\n% [C,W,CH,PAR,D,A] = initialize_quadtree(P,'MaxDepth',8,'Graded',true);\n% % This is for plotting\n% [V,Q] = bad_quad_mesh_from_quadtree(C,W,CH);\n% % Call function to construct Laplacian\n% [L, stored_at] = quadtree_laplacian(C,W,CH,D,A);\n% % Dummy Laplacian function\n% gt_fun = stored_at(:,1).^2.0;\n% laplacian_fun = 2 + 0.*stored_at(:,1);\n% % Find boundary\n% Vmin = min(stored_at,[],1);\n% Vmax = max(stored_at,[],1);\n% is_boundary = (stored_at(:,1)<=(Vmin(1)+0.2)) + (stored_at(:,2)<=(Vmin(2)+0.2)) + ...\n%     (stored_at(:,1)>=(Vmax(1)-0.2)) + (stored_at(:,2)>=(Vmax(2)-0.2));\n% bb = find(is_boundary);\n% bc = gt_fun(bb);\n% % Solve as energy minimization\n% u = min_quad_with_fixed(0.5*L,-laplacian_fun,bb,bc);\n% % Plot solution\n% tsurf(Q,V,falpha(1,1),'FaceVertexCData',u)\n% hold on\n% sct(stored_at(bb,:)) % Visualize boundary conditions\n% set(gcf,'Color','w'); grid off; axis equal; colorbar; caxis([0 1]);\n%\n%\n% See also: initialize_quadtree.m\n\n\n\n\n\n% We will store Laplacian values at\n% child cell indeces\nchildren = find(CH(:,1)==-1);\n% map from all cells to children\ncell_to_children = -ones(size(W,1),1);\ncell_to_children(children) = 1:length(children);\n\n% Vectors for constructing the Laplacian\nI = [];\nJ = [];\nvals = [];\n\nfor i=1:size(children,1)\n    new_I = [];\n    new_J = [];\n    new_vals = [];\n    l = [1,1,1,1];\n    new_dirs = [];\n    child = children(i);\n    d = D(child);\n    num_dirs = 0;\n    % Let's build d u(child)/dx^2 ~ u(child+W(child)*[1,0])/hr(hl+hr) -\n    % 2u(child)/hlhr + u(child-W(child)*[1,0])/hr(hl+hr)\n    % So, let's look for the value to the j direction. To do this, we seek the\n    % lowest-depth neighbor to the j direction. As a reminder the octree\n    % adjacency convention is i->j (1:left-2:right-3:bottom-4:top)\n    for j=1:4\n        j_neighbors = find(A(child,:)==j);\n        if ~isempty(j_neighbors)\n            depths_j_neighbors = D(j_neighbors);\n            [max_depth_j, max_depth_j_neighbor] = max(depths_j_neighbors);\n            max_depth_j_neighbor = j_neighbors(max_depth_j_neighbor);\n            % There are two options:\n            % One: the leaf node to our j direction has lower or equal depth to\n            % us\n            if max_depth_j<=d\n                l(j) = (W(child) + W(max_depth_j_neighbor))/2;\n                % then it's easy, just add this node\n                new_I = [new_I;i];\n                % THIS HAS TO BE A CHILD !\n                assert(cell_to_children(max_depth_j_neighbor)>0);\n                new_J = [new_J;cell_to_children(max_depth_j_neighbor)];\n                new_vals = [new_vals;-1]; % Todo fix this\n                new_dirs = [new_dirs;j];\n            else\n                % In this case, assuming the grid is graded, there should\n                % be two j-neighbors at depth d+1\n                nn = j_neighbors(D(j_neighbors)==(d+1));\n                assert(length(nn)==2,\"Are you sure you are inputting a graded quadtree?\")\n                assert(all(CH(nn,1)==[-1;-1]))\n                % Then we simply average both\n                l(j) = (W(child) + W(nn(1)))/2;\n                new_I = [new_I;i;i];\n                new_J = [new_J;cell_to_children(nn(1));cell_to_children(nn(2))];\n                new_vals = [new_vals;-0.5;-0.5];\n                new_dirs = [new_dirs;j;j];\n            end\n            num_dirs = num_dirs + 1;\n        end\n    end\n    new_I = [new_I;i];\n    new_J = [new_J;i];\n    new_vals = [new_vals; 1.0];\n    new_dirs = [new_dirs;5]; % just a hack\n    % At this point, we have to divide by the edge-lengths\n    new_vals(new_dirs==1) = new_vals(new_dirs==1)/(l(1)*(l(1)+l(2)));\n    new_vals(new_dirs==2) = new_vals(new_dirs==2)/(l(2)*(l(1)+l(2)));\n    new_vals(new_dirs==3) = new_vals(new_dirs==3)/(l(3)*(l(3)+l(4)));\n    new_vals(new_dirs==4) = new_vals(new_dirs==4)/(l(4)*(l(3)+l(4)));\n    new_vals(new_dirs==5) = 1/(l(1)*l(2)) + 1/(l(3)*l(4));\n    \n    % And add them to the big sparse Laplacian construction vectors\n    I = [I;new_I];\n    J = [J;new_J];\n    vals = [vals;new_vals];\nend\n\n% THE LAPLACIAN IS NEGATIVE SEMI DEFINITE!\nL = -2*sparse(I,J,vals,length(children),length(children));\nstored_at = C(children,:);\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/quadtree_laplacian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940927, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5830197431801575}}
{"text": "% Compute Hoyer sparsity of x \n\nfunction spx = sp(x,w) \n\nr = length(x); \n\nspx = 0; \nfor i = 1 : r\n    if x{i} == 0\n        spx = 1; \n    else\n        ni = length(x{i}); \n        if nargin <= 1\n            spx = spx + (sqrt(ni)-norm(x{i},1)/norm(x{i},2))/(sqrt(ni)-1);\n        else\n            nw = norm(w{i},2); \n            spx = spx + (nw-w{i}'*abs(x{i})/norm(x{i},2))/(nw-min(w{i}));\n        end\n    end\nend\nspx = spx/r; ", "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/sparse/sparse_auxiliary/sp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5830197383590361}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   q = solve_spherical_wrist2(robot, q, T, wrist)\n%   Solves the inverse kinematic problem for a spherical wrist. This is for\n%   the particular RELATIVE orientation of the last three reference systems in\n%   ABB robots\n%\n%   robot: robot structure.\n%   q: vector containing the values of the joints 1, 2 and 3.\n%   T: orientation of the last reference system.\n%   wrist: select -1 or 1 for two possible solutions (wrist up, wrist down)\n%\n%\tSee also DIRECTKINEMATIC.\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 <http://www.gnu.org/licenses/>.\n\nfunction q = solve_spherical_wrist2(robot, q, T, wrist, method)\n\nswitch method\n    \n    %algebraic solution\n    case 'algebraic'\n        A01=dh(robot, q, 1);\n        A12=dh(robot, q, 2);\n        A23=dh(robot, q, 3);\n        \n        Q=inv(A23)*inv(A12)*inv(A01)*T;\n        \n        %detect the degenerate case when q(5)=0, this leads to zeros\n        % in Q13, Q23, Q31 and Q32 and Q33=1\n        thresh=1e-12;\n        %detect if q(5)==0\n        % this happens when cos(q5) in the matrix Q is close to 1\n        if abs(Q(3,3)-1)>thresh\n            %normal solution\n            if wrist==1 %wrist up\n                q(4)=atan2(Q(2,3),Q(1,3));\n                q(6)=atan2(-Q(3,2),Q(3,1));\n            else %wrist down\n                q(4)=atan2(Q(2,3),Q(1,3))+pi;\n                q(6)=atan2(-Q(3,2),Q(3,1))+pi;\n            end\n            if abs(cos(q(6)+q(4)))>thresh\n                cq5=(-Q(1,1)-Q(2,2))/cos(q(4)+q(6))-1;\n            end\n            if abs(sin(q(6)+q(4)))>thresh\n                cq5=(Q(1,2)-Q(2,1))/sin(q(4)+q(6))-1;\n            end\n            if abs(sin(q(6)))>thresh\n                sq5=Q(3,2)/sin(q(6));\n            end\n            if abs(cos(q(6)))>thresh\n                sq5=-Q(3,1)/cos(q(6));\n            end\n            q(5)=atan2(sq5,cq5);\n        else %degenerate solution, in this case, q4 cannot be determined,\n            % so q(4)=0 is assigned\n            if wrist==1 %wrist up\n                q(4)=0;\n                q(5)=0;\n                q(6)=atan2(Q(1,2)-Q(2,1),-Q(1,1)-Q(2,2));\n            else %wrist down\n                q(4)=-pi;\n                q(5)=0;\n                q(6)=atan2(Q(1,2)-Q(2,1),-Q(1,1)-Q(2,2))+pi;\n            end\n            \n        end\n        \n        %algebraic solution\n    case 'geometric'\n        \n        % Obtain the position and orientation of the system 3\n        % using the already computed joints q1, q2 and q3\n        T01=dh(robot, q, 1);\n        T12=dh(robot, q, 2);\n        T23=dh(robot, q, 3);\n        T03=T01*T12*T23;\n        \n        x3=T03(1:3,1);\n        y3=T03(1:3,2);\n        z3=T03(1:3,3);\n        \n        % T= [ nx ox ax Px;\n        %     ny oy ay Py;\n        %     nz oz az Pz];\n        a=T(1:3,3);\n        \n        % find z4 normal to the plane formed by z3 and a\n        z4=cross(z3, a);\t% end effector's vector a: T(1:3,3)\n        \n        % in case of degenerate solution,\n        % when z3 and z6 are parallel, choose q(4)=0 as solution\n        if norm(z4) <= 0.000001\n            if wrist == 1 %wrist up\n                q(4)=0;\n            else\n                q(4)=-pi;\n            end\n        else\n            cq4=wrist*dot(z4, -y3);\n            sq4=wrist*dot(z4, x3);\n            q(4)=atan2(sq4, cq4);\n        end\n        \n        % solve for q5\n        T34=dh(robot, q, 4);\n        T04=T03*T34;\n        x4=T04(1:3, 1);\n        y4=T04(1:3, 2);\n        \n        z5=T(1:3, 3); % The vector a T(1:3,3) is coincident with z5\n        \n        cq5=dot(z5, y4);\n        sq5=dot(z5, -x4);\n        q(5)=atan2(sq5, cq5);\n        \n        % solve for q6\n        x6=T(1:3, 1);\n        \n        T45=dh(robot, q, 5);\n        T05=T04*T45;\n        x5=T05(1:3, 1);\n        y5=T05(1:3, 2);\n        \n        cq6=dot(x6, -x5);\n        sq6=dot(x6, -y5);\n        q(6)=atan2(sq6, cq6);\n        \n        \n    otherwise\n        disp('no method specified in solve_spherical_wrist');\nend", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/lib/kinematics/solve_spherical_wrist2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5830197348953916}}
{"text": "function s = findspan(n,p,u,U)                 \n% FINDSPAN  Find the span of a B-Spline knot vector at a parametric point \n% ------------------------------------------------------------------------- \n% ADAPTATION of FINDSPAN from C \n% ------------------------------------------------------------------------- \n% \n% Calling Sequence: \n%  \n%   s = findspan(n,p,u,U) \n%  \n%  INPUT: \n%  \n%    n - number of control points - 1 \n%    p - spline degree \n%    u - parametric point \n%    U - knot sequence \n%  \n%  RETURN: \n%  \n%    s - knot span \n%  \n%  Algorithm A2.1 from 'The NURBS BOOK' pg68 \n                                                 \n                                                % int findspan(int n, int p, double u, double *U) { \n                                                 \n                                                %   int low, high, mid;                                                 \n                                                %   // special case \nif (u==U(n+2)), s=n; return,  end               %   if (u == U[n+1]) return(n); \n                                                % \n                                                %   // do binary search \nlow = p;                                        %   low = p; \nhigh = n + 1;                                   %   high = n + 1; \nmid = floor((low + high) / 2);                  %   mid = (low + high) / 2; \nwhile (u < U(mid+1) || u >= U(mid+2))           %   while (u < U[mid] || u >= U[mid+1])  { \n    if (u < U(mid+1))                           %     if (u < U[mid]) \n        high = mid;                             %       high = mid; \n    else                                        %     else \n        low = mid;                              %       low = mid;                   \n    end  \n    mid = floor((low + high) / 2);              %     mid = (low + high) / 2; \nend                                             %   } \n                                                % \ns = mid;                                        %   return(mid); \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/findspan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.5829485944393201}}
{"text": "function handle = draw_gmm(haxes,Priors,Mu,Sigma )\n%DRAW_GMM Summary of this function goes here\n%   Detailed explanation goes here\n\n\nK = size(Priors,2);\nSTD=3;\n\nfor k=1:K\n    l = max(Priors);\n    for i=3:(-1):STD\n        w = Priors(k)/l;\n        handle = plot_gaussian_ellipsoid(Mu(:,k),Sigma(:,:,k),i,100,haxes,w,[0 0 1]);\n        set(handle,'LineWidth',2);\n      %  obj.text_handle = [obj.text_handle text(obj.Mu(1,k),obj.Mu(2,k),num2str(k),'FontWeight','bold','FontSize',24,'Color',obj.color,'VerticalAlignment','middle','HorizontalAlignment','center')];\n    end\nend\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/functions/plot_functions/gmm_plot/plotGaussians/plot_2d_gaussian/draw_gmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.837619963333289, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5829485761316509}}
{"text": "function [elem,bdFlag] = sortelem3(elem,bdFlag)\n%% SORTELEM3 sort elem in ascend ordering\n%\n% [elem,bdFlag] = sortelem3(elem,bdFlag) sorts the elem such that\n% elem(t,1)< elem(t,2)< elem(t,3)<elem(t,4). A simple sort(elem,2) cannot\n% switch bdFlag.\n% \n% See also  sortelem\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n%% Step 1: elem(:,4) is the largest one\n[tempvar,idx] = max(elem,[],2);  %#ok<*ASGLU>\nelem(idx==1,1:4) = elem(idx==1,[2 4 3 1]);\nelem(idx==2,1:4) = elem(idx==2,[3 4 1 2]);\nelem(idx==3,1:4) = elem(idx==3,[4 2 1 3]);\nif exist('bdFlag','var')\n    bdFlag(idx==1,1:4) = bdFlag(idx==1,[2 4 3 1]);\n    bdFlag(idx==2,1:4) = bdFlag(idx==2,[3 4 1 2]);\n    bdFlag(idx==3,1:4) = bdFlag(idx==3,[4 2 1 3]);\nend\n\n%% Step 2: elem(:,1) is the smallest one\n[tempvar,idx] = min(elem(:,1:3),[],2);\n% elem(idx==1,1:3) = elem(idx==1,[1 2 3]);\nelem(idx==2,1:3) = elem(idx==2,[2 3 1]);\nelem(idx==3,1:3) = elem(idx==3,[3 1 2]);\nif exist('bdFlag','var')\n    bdFlag(idx==2,1:3) = bdFlag(idx==2,[2 3 1]);\n    bdFlag(idx==3,1:3) = bdFlag(idx==3,[3 1 2]);\nend\n\n%% Step 3: sort elem(:,2)<elem(:3)\nidx = (elem(:,3) < elem(:,2));\nelem(idx,[2 3]) = elem(idx,[3 2]);\nif exist('bdFlag','var')\n    bdFlag(idx,[2 3]) = bdFlag(idx,[3 2]); \nend\n\n%% Output\nif ~exist('bdFlag','var')\n    bdFlag = [];\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/dof/sortelem3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5829478425420348}}
{"text": "function [fal,dx0] = aliasing_frequency(x0,conf)\n%ALIASING_FREQUENCY aliasing frequency for the given secondary sources\n%\n%   Usage: [fal,dx0] = aliasing_frequency([x0],conf)\n%\n%   Input parameters:\n%       x0      - secondary sources / m\n%       conf    - configuration struct (see SFS_config)\n%\n%   Output parameters:\n%       fal     - aliasing frequency / Hz\n%       dx0     - mean distance between secondary sources / m\n%\n%   ALIASING_FREQUENCY(x0,conf) returns the aliasing frequency for the given\n%   secondary sources. First the mean distance dx0 between the secondary sources\n%   is calculated, afterwards the aliasing frequency is calculated after Spors\n%   (2009) as fal = c/(2*dx0). If no secondary sources x0 are provided, they are\n%   first calculated by calling secondary_source_positions().\n%   For a calculation that includes the dependency on the listener position have\n%   a look at Start (1997).\n%\n%   See also: sound_field_mono_wfs, secondary_source_positions,\n%       secondary_source_distance\n%\n%   References:\n%       Spors and Ahrens (2009) - \"Spatial sampling artifacts of wave field\n%       synthesis for the reproduction of virtual point sources\", 126th\n%       Convention of the Audio Engineering Society, Paper 7744,\n%       http://www.aes.org/e-lib/browse.cfm?elib=14940\n%\n%       Start (1997) - \"Direct Sound Enhancement by Wave Field Synthesis\",\n%       PhD thesis, TU Delft,\n%       http://resolver.tudelft.nl/uuid:c80d5b58-67d3-4d84-9e73-390cd30bde0d\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);\nif nargin<nargmax\n    conf = x0;\n    x0 = [];\nend\nisargstruct(conf);\n\n\n%% ===== Configuration ==================================================\nc = conf.c;\n\n\n%% ===== Computation =====================================================\n% If no explicit secondary source distribution is given, calculate one\nif isempty(x0)\n    x0 = secondary_source_positions(conf);\nend\n% Get average distance between secondary sources\ndx0 = secondary_source_distance(x0);\n% Calculate aliasing frequency\nfal = c/(2*dx0);\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_general/aliasing_frequency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.5829478301854606}}
{"text": "function check = logistic_check ( a, b )\n\n%*****************************************************************************80\n%\n%% LOGISTIC_CHECK checks the parameters of the Logistic CDF.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    13 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, logical CHECK, is true if the parameters are legal.\n%\n  if ( b <= 0.0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'LOGISTIC_CHECK - Fatal error!\\n' );\n    fprintf ( 1, '  B <= 0.\\n' );\n    check = 0;\n    return\n  end\n\n  check = 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/prob/logistic_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.5829478282193359}}
{"text": "function [f,relres,iter]=frsyniter(F,c,varargin)\n%FRSYNITER  Iterative synthesis\n%   Usage:  f=frsyniter(F,c);\n%           f=frsyniter(F,c,Ls);\n%           [f,relres,iter]=frsyniter(F,c,...);\n%\n%   Input parameters:\n%         F       : Frame\n%         c       : Array of coefficients.\n%         Ls      : length of signal.\n%   Output parameters:\n%         f       : Signal.\n%         relres  : Vector of residuals.\n%         iter    : Number of iterations done.\n%\n%   `f=frsyniter(F,c)` iteratively inverts the analysis operator of *F*, so\n%   `frsyniter` always performs the inverse operation of |frana|, even\n%   when a perfect reconstruction is not possible by using |frsyn|.\n%\n%   `[f,relres,iter]=frsyniter(...)` additionally returns the relative\n%   residuals in a vector *relres* and the number of iteration steps *iter*.\n%\n%   **Note:** If it is possible to explicitly calculate the canonical dual\n%   frame then this is usually a much faster method than invoking\n%   `frsyniter`.\n%\n%   `frsyniter` takes the following parameters at the end of the line of\n%   input arguments:\n%\n%     'tol',t      Stop if relative residual error is less than the\n%                  specified tolerance. Default is 1e-9 (1e-5 for single precision)\n%\n%     'maxit',n    Do at most n iterations.\n%\n%     'cg'         Solve the problem using the Conjugate Gradient\n%                  algorithm. This is the default.\n%\n%     'pcg'        Solve the problem using the Preconditioned Conjugate Gradient\n%                  algorithm. Please note that preconditioning is not supported\n%                  for all frame types.               \n%\n%     'print'      Display the progress.\n%\n%     'quiet'      Don't print anything, this is the default.\n%\n%   Algorithms\n%   ----------\n%\n%   The function uses the (Preconditioned) Conjugate Gradient algorithm\n%   to solve the following problem::\n%\n%   ..   FF*f=Fc\n%\n%   .. math:: FF* f = Fc\n%\n%   The preconditioning alters the equations such that\n%\n%   ..   inv(M)FF*f=inv(M)Fc\n%\n%   .. math:: M^{-1}FF* f = M^{-1}Fc\n%\n%   Examples\n%   --------\n%\n%   The following example shows how to rectruct a signal without ever\n%   using the dual frame:::\n%\n%      F=frame('dgtreal','gauss',10,20);\n%      c=frana(F,bat);\n%      [r,relres]=frsyniter(F,c,'tol',1e-14);\n%      norm(bat-r)/norm(bat)\n%      semilogy(relres);\n%      title('Conversion rate of the CG algorithm');\n%      xlabel('No. of iterations');\n%      ylabel('Relative residual');\n%\n%   See also: frame, frana, frsyn, franaiter\n\n% AUTHORS: Nicki Holighaus & Peter L. S\u00f8ndergaard\n\ncomplainif_notenoughargs(nargin,2,'FRSYNITER');\ncomplainif_notvalidframeobj(F,'FRSYNITER');\n\ntolchooser.double=1e-9;\ntolchooser.single=1e-5;\n\ndefinput.keyvals.Ls=[];\ndefinput.keyvals.tol=tolchooser.(class(c));\ndefinput.keyvals.maxit=100;\ndefinput.keyvals.Fd = [];\ndefinput.flags.alg={'cg','pcg'};\ndefinput.keyvals.printstep=10;\ndefinput.flags.print={'quiet','print'};\n\n[flags,kv,Ls]=ltfatarghelper({'Ls'},definput,varargin);\n\n% if flags.do_auto\n%     varargin2 = varargin;\n%     varargin2(strcmpi(varargin2,'auto')) = [];\n% \n%     try\n%         varargin2{end+1} = 'pcg';\n%         [f,relres,iter]=frsyniter(F,c,varargin2{:});\n%     catch\n%         if ~flags.do_quiet\n%             warning(sprintf('%s: Falling back to regular CG.',upper(mfilename)));\n%         end\n%         varargin2{end+1} = 'cg';\n%         [f,relres,iter]=frsyniter(F,c,varargin2{:});\n%     end\n%     return;\n% end\n\nL=framelengthcoef(F,size(c,1));\n\nFd = kv.Fd;\n% Compute the preconditioner\nif flags.do_pcg && isempty(Fd)\n    try\n       d = cast(1./framediag(F,L),class(c));\n    catch\n       switch F.type\n            case {'filterbank','ufilterbank'}\n                Fd = frame(F.type,{'dual',F.g,'forcepainless'},F.a,numel(F.g));\n            case {'filterbankreal','ufilterbankreal'}\n                Fd = frame(F.type,{'realdual',F.g,'forcepainless'},F.a,numel(F.g));\n            otherwise\n                error('%s: No preconditioning method available for given frame type.',...\n                upper(mfilename));\n       end\n    end\nend\n\nF=frameaccel(F,L);\n\nA=@(x) F.frsyn(F.frana(x));\n\n% It is possible to specify the initial guess, but this is not\n% currently done\n\nif flags.do_pcg && isempty(Fd)\n\n      [f,flag,~,iter,relres]=pcg(A,F.frsyn(c),kv.tol,kv.maxit,@(x)d.*x);\nelseif flags.do_pcg\n\n      Fd = frameaccel(Fd,L);\n      A=@(x) Fd.frsyn(F.frana(x));\n      [f,flag,~,iter,relres]=pcg(A,Fd.frsyn(c),kv.tol,kv.maxit);\nelse\n\n      [f,flag,~,iter,relres]=pcg(A,F.frsyn(c),kv.tol,kv.maxit);\nend\n\nif nargout>1\n      relres=relres/norm(c(:));\nend\n\n% Cut or extend f to the correct length, if desired.\nif ~isempty(Ls)\n    f=postpad(f,Ls);\nelse\n    Ls=L;\nend\n\n\nif 0\n      % This code has been disabled, as the PCG algorithm is so much faster.\n    if flags.do_unlocbox\n\n          % Get the upper frame bound (Or an estimation bigger than the bound)\n          [~,B]=framebounds(F,L,'a');\n\n          % Set the parameter for the fast projection on a B2 ball\n          param.At=@(x) frsyn(F,x);     % adjoint operator\n          param.A=@(x)  frana(F,x);     % direct operator\n          param.y=c;                    % coefficient\n          param.tight=0;                % It's not a tight frame\n          param.max_iter=kv.maxit;\n          param.tol=kv.tol;\n          param.nu=B;\n\n          % Display parameter 0 nothing, 1 summary at convergence, 2 all\n          % steps\n      if flags.do_print\n          param.verbose=1;\n      else\n          param.verbose=0;\n      end\n\n      % Make the projection. Requires UNLocBOX\n      [f, ~] = fast_proj_B2(zeros(L,1), 0, param);\n\n      % compute the residue\n      res = param.A(f) - param.y; norm_res = norm(res(:), 2);\n      relres=norm_res/norm(c(:), 2);\n\n      iter=0; % The code of the fast_proj_B2 is not yet compatible with this\n    end\n\nend\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/frames/frsyniter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5829478251301922}}
{"text": "function DEM_demo_DFP\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 starts by demonstrating\n% Variational filtering with spm_DFP; this is a stochastic filtering scheme\n% that propagates particles over a changing variational energy landscape \n% such that their sample density can be used to approximate the underlying\n% ensemble or conditional density.  We then repeat the inversion using \n% spm_DEM (i.e., under a Laplace assumption) which involves integrating the\n% path of just one particle (i.e., the mode).\n \n% get a simple convolution model\n%==========================================================================\nspm_figure('GetWin','DEM');\n\nM        = spm_DEM_M('convolution model');\nM(1).V   = exp(8);\nM(1).W   = exp(16);\nM(1).E.N = 32;\n\n \n% and generate data\n%==========================================================================\nN     = 32;                                        % length of data sequence\nU     = exp(-((1:N) - N/4).^2/(2*(N/32)^2));       % Gaussian cause\nDEM   = spm_DEM_generate(M,U,{},{32 16});\n \n% display\n%--------------------------------------------------------------------------\nspm_DEM_qU(DEM.pU)\n \n \n% invert model - VF\n%==========================================================================\nDEM  = spm_DFP(DEM);\n \n% overlay true values\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 1');\nspm_DEM_qU(DEM.qU,DEM.pU)\n\n\n% invert model - DEM\n%==========================================================================\nDEM  = spm_DEM(DEM);\n \n% overlay true values\n%--------------------------------------------------------------------------\nspm_DEM_qU(DEM.qU,DEM.pU)\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_DFP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5829356267095923}}
{"text": "% $Id: WB08_Fig_2.m,v 1.1.1.1 2008/05/09 21:34:52 myself Exp $\n%\n% This prepares data for Figure 2 which is created with the corresponding\n% shell script using GMT.  It also makes a plot in Matlab/Octave.\n%\n% Wessel, P. and J. M. Becker, 2008, Interpolation using a\n%  generalized Green's function for a spherical surface spline\n%  in tension, Geophys. J. Int., doi:10.1111/j.1365-246X.2008.03829.x\n%\n% Replicate Parker and then find the tension that minimizes the misfit at\n% his 8 extra validation stations.\n\nload mag_obs_1990.d\nloni = mag_obs_1990(:,1);\nlati = mag_obs_1990(:,2);\nzi   = mag_obs_1990(:,3);\nd=1;\n% Set global 1x1 grid output coordinates\n\n[X Y] = meshgrid (0:d:360, 0:d:90);\n\n% First Parker's solution (p = 0)\nZ = sphsplinet (loni, lati, zi, X, Y);\n\nfigure(1); clf\nsubplot (2,1,1)\ncontour (X, Y, Z)\ndrawnow\nA = [X(:) Y(:) Z(:)];\nsave Fig_2_p0.d A -ascii -tabs\n\n%Then used the wrong Oslo longitude to recreate Parker's figure\nk = find (loni == 10.45)\nloni(k) = 104.5;\nZ = sphsplinet (loni, lati, zi, X, Y);\nsubplot (2,1,2)\ncontour (X, Y, Z)\nA = [X(:) Y(:) Z(:)];\nsave Fig_2_orig.d A -ascii -tabs\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/sphsplineToolbox/WB08_Fig_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5829356199444694}}
{"text": "function [mResult, fMls, fMc, fMu, fSigma, mDatPredBest, vPredBest, fBvalue, fAvalue] = calc_McCdfnormal(mCatalog, fBinning)\n    % Determine Mc using maximum likelihood estimate; same as calc_McEMR but with output of modeled data\n    % [mResult, fMls, fMc, fMu, fSigma, mDatPredBest, vPredBest, fBvalue, fAvalue] = calc_McCdfnormal(mCatalog, fBinning);\n    % -----------------------------------------------------------------------------------------------------------------------------\n    % Determine Mc using maximum likelihood estimate; same as calc_McEMR but with output of modeled data\n    % Fitting non-cumulative frequency magnitude distribution above and below Mc:\n    % below: Cumulative NORMAL density function\n    % above: Gutenberg-Richter law\n    %\n    % Incoming variables:\n    % mCatalog   : EQ catalog\n    % fBinning   : Binning interval, usually 0.1\n    %\n    % Outgoing variables:\n    % mResult     : Solution matrix including\n    %               vProbability: maximum likelihood score\n    %               vMc         : Mc values\n    %               vX_res      : mu (of normal CDF), sigma (of normal CDF), residuum, exitflag\n    %               vNmaxBest   : Number of events in lowest magnitude bin considered complete\n    %               vABValue    : a and b-value\n    % fMls       : minimum maximum likelihood score --> best Mc\n    % fMc        : Best estimated magnitude of completeness\n    % mDatPredBest   : Matrix of non-cumulative FMD [Prediction, magnitudes, original distribution]\n    % vPredBest      : Matrix of non-cumulative FMD below Mc [magnitude, prediction, uncertainty of prediction]\n    % fBvalue        : b-value\n    %\n    % J. Woessner: woessner@seismo.ifg.ethz.ch\n    % updated: 03.11.03\n    \n    \n    % Initialize\n    vProbability = [];\n    vMc = [];\n    vABValue =[];\n    mFitRes = [];\n    vX_res = [];\n    vNCumTmp = [];\n    mDataPred = [];\n    vPredBest = [];\n    vDeltaBest = [];\n    vX_res = [];\n    vNmaxBest = [];\n    mResult=[];\n    mDatPredBest = [];\n    \n    % Determine exact time period\n    fPeriod1 = max(mCatalog.Date) - min(mCatalog.Date);\n    \n    % Determine max. and min. magnitude\n    fMaxMag = ceil(10 * max(mCatalog.Magnitude)) / 10;\n    \n    % Set starting value for Mc loop and LSQ fitting procedure\n    fMcTry= calc_Mc(mCatalog, McMethods.MaxCurvature);\n    fSmu = abs(fMcTry/2);\n    fSSigma = abs(fMcTry/4);\n    if (fSmu > 1)\n        fSmu = fMcTry/10;\n        fSSigma = fMcTry/20;\n    end\n    fMcBound = fMcTry;\n    \n    % Calculate FMD for original catalog\n    [vFMDorg, vNonCFMDorg, fmdbins] = calc_FMD(mCatalog);\n    % convert answer back to this file's expectations...\n    vFMDorg = [fmdbins'; vFMDorg'] % as rows\n    vNonCFMDorg = [fmdbins'; vNonCFMDorg'];\n\n    fMinMag = min(vNonCFMDorg(1,:));\n    \n    %% Shift to positive values\n    % if fMinMag ~= 0\n    %     fMcBound = fMcTry-fMinMag;\n    % end\n    % Loop over Mc-values\n    for fMc = fMcBound-0.4:0.1:fMcBound+0.4\n        fMc = round(fMc, -1);\n        vFMD = vFMDorg;\n        vNonCFMD = vNonCFMDorg;\n        vNonCFMD = fliplr(vNonCFMD);\n        % Calculate a and b-value for GR-law and distribution vNCum\n        [nIndexLo, fMagHi, vSel, vMagnitudes] = fMagToFitBValue(mCatalog, vFMD, fMc);\n        if (length(mCatalog.Longitude(vSel)) >= 20)\n            [ fBValue, fStdDev, fAValue] =  calc_bmemag(mCatalog.Magnitude(vSel), fBinning);\n            % Normalize to time period\n            vFMD(2,:) = vFMD(2,:)./fPeriod1; % ceil taken out\n            vNonCFMD(2,:) = vNonCFMD(2,:)./fPeriod1; % ceil removed\n            % Compute quantity of earthquakes by power law\n            fMaxMagFMD = max(vNonCFMD(1,:));\n            fMinMagFMD = min(vNonCFMD(1,:));\n            vMstep = [fMinMagFMD:0.1:fMaxMagFMD];\n            vNCum = 10.^(fAValue-fBValue.*vMstep); % Cumulative number\n            \n            % Compute non-cumulative numbers vN\n            fNCumTmp = 10^(fAValue-fBValue*(fMaxMagFMD+0.1));\n            vNCumTmp  = [vNCum fNCumTmp ];\n            vN = abs(diff(vNCumTmp));\n            \n            % Normalize vN\n            vN = vN./fPeriod1;\n            % Data selection\n            % mData = Non-cumulative FMD values from GR-law and original data\n            mData = [vN' vNonCFMD'];\n            vSel = (mData(:,2) >= fMc);\n            mDataTest = mData(~vSel,:);\n            mDataTmp = mData.subset(vSel);\n            %         % Check for zeros in observed data\n            vSelCheck = (mDataTest(:,3) == 0);\n            mDataTest = mDataTest(~vSelCheck,:);\n            % Choices of normalization\n            fNmax = mDataTmp(1,3); % Frequency of events in Mc bin\n            %fNmax = max(mDataTest(:,3));  % Use maximum frequency of events in bins below Mc\n            %fNmax = mDataTest(length(mDataTest(:,1)),3); % Use frequency of events at bin Mc-0.1 -> best fit\n            if (~isempty(isempty(fNmax)) &&  ~isnan(fNmax) & fNmax ~= 0 & length(mDataTest(:,1)) > 4)\n                mDataTest(:,3) = mDataTest(:,3)/fNmax; % Normalize datavalues for fitting with CDF\n                % Move to M=0 to fit with lsq-algorithm\n                fMinMagTmp = min(mDataTest(:,2));\n                mDataTest(:,2) = mDataTest(:,2)-fMinMagTmp;\n                % Curve fitting: Non cumulative part below Mc\n                options = optimset;\n                %options = optimset('Display','off','Tolfun',1e-7,'TolX',0.0001,'MaxFunEvals', 100000,'MaxIter',10000);\n                options = optimset('Display','off','Tolfun',1e-5,'TolX',0.001,'MaxFunEvals', 1000,'MaxIter',1000);\n                [vX, resnorm, resid, exitflag, output, lambda, jacobian]=lsqcurvefit(@calc_normalCDF,[fSmu  fSSigma], mDataTest(:,2), mDataTest(:,3),[],[],options);\n                mDataTest(:,1) = normcdf(mDataTest(:,2), vX(1), vX(2))*fNmax;\n                if (length(mDataTest(:,2)) > length(vX(1,:)))\n                    %% Confidence interval determination\n                    % vPred : Predicted values of lognormal function\n                    % vPred+-delta : 95% confidence level of true values\n                    [vPred,delta] = nlpredci(@calc_normalCDF,mDataTest(:,2),vX, resid, jacobian);\n                else\n                    vPred = NaN;\n                    delta = NaN;\n                end; % END: This section is due for errors produced with datasets less long than amount of parameters in vX\n                % Results of fitting procedure\n                mFitRes = [mFitRes; vX resnorm exitflag];\n                % Move back to original magnitudes\n                mDataTest(:,2) = mDataTest(:,2)+fMinMagTmp;\n                % Set data together\n                mDataTest(:,3) = mDataTest(:,3)*fNmax;\n                mDataPred = [mDataTest; mDataTmp];\n                % Denormalize to calculate probabilities\n                mDataPred(:,1) = round(mDataPred(:,1).*fPeriod1);\n                mDataPred(:,3) = mDataPred(:,3).*fPeriod1;\n                vProb_ = calc_log10poisspdf2(mDataPred(:,3), mDataPred(:,1)); % Non-cumulative\n                \n                % Sum the probabilities\n                fProbability = (-1) * sum(vProb_);\n                vProbability = [vProbability; fProbability];\n                % Move magnitude back\n                mDataPred(:,2) = mDataPred(:,2)+fMinMag;\n                vMc = [vMc; fMc];\n                vABValue = [vABValue; fAValue fBValue];\n                \n                % Keep values\n                vDeltaBest = [vDeltaBest; delta];\n                vX_res = [vX_res; vX resnorm exitflag];\n                vNmaxBest = [vNmaxBest; fNmax];\n                \n                % Keep best fitting model\n                if (fProbability == min(vProbability))\n                    vDeltaBest = delta;\n                    vPredBest = [mDataTest(:,2) vPred*fNmax*fPeriod1 delta*fNmax*fPeriod1]; % Gives back uncertainty\n                    %fMc+fMinMag : Test procedure\n                    mDatPredBest = [mDataPred];\n                end\n            else\n                %disp('Not enough data');\n                % Setting values\n                fProbability = NaN;\n                fMc = NaN;\n                vX(1) = NaN;\n                vX(2) = NaN;\n                resnorm = NaN;\n                exitflag = NaN;\n                delta = NaN;\n                vPred = [NaN NaN NaN];\n                fNmax = NaN;\n                fAValue = NaN;\n                fBValue = NaN;\n                vProbability = [vProbability; fProbability];\n                vMc = [vMc; fMc];\n                vX_res = [vX_res; vX resnorm exitflag];\n                %             vDeltaBest = [vDeltaBest; NaN];\n                %             vPredBest = [vPredBest; NaN NaN NaN];\n                vNmaxBest = [vNmaxBest; fNmax];\n                vABValue = [vABValue; fAValue fBValue];\n            end; % END of IF fNmax\n        end; % END of IF length(mCatalog.Longitude(vSel))\n        \n        \n        % Clear variables\n        vNCumTmp = [];\n        mModelDat = [];\n        vNCum = [];\n        vSel = [];\n        mDataTest = [];\n        mDataPred = [];\n    end; % END of FOR fMc\n    % Result matrix\n    mResult = [mResult; vProbability vMc vX_res vNmaxBest vABValue];\n    \n    % Find best estimate, excluding the case of mResult all NAN\n    if  ~isempty(min(mResult))\n        if ~isnan(min(mResult(:,1)))\n            vSel = find(min(mResult(:,1)) == mResult(:,1));\n            fMc = min(mResult(vSel,2));\n            fMls = min(mResult(vSel,1));\n            fMu = min(mResult(vSel,3));\n            fSigma = min(mResult(vSel,4));\n            fAvalue = min(mResult(vSel,8));\n            fBvalue = min(mResult(vSel,9));\n        else\n            fMc = NaN;\n            fMls = NaN;\n            fMu = NaN;\n            fSigma = NaN;\n            fAvalue = NaN;\n            fBvalue = NaN;\n        end\n    else\n        fMc = NaN;\n        fMls = NaN;\n        fMu = NaN;\n        fSigma = NaN;\n        fAvalue = NaN;\n        fBvalue = NaN;\n    end\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/jochen/seisvar/calc/calc_McCdfnormal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5829190698193691}}
{"text": "clear all; close all; clc\n\nload catData_w.mat; load dogData_w.mat; CD=[dog_wave cat_wave];\ntrain=[dog_wave(:,1:60) cat_wave(:,1:60)];\ntest=[dog_wave(:,61:80) cat_wave(:,61:80)];\nlabel=[ones(60,1); -1*ones(60,1)].';\n\nA=label*pinv(train); test_labels=sign(A*test);\nsubplot(4,1,1), bar(test_labels,'FaceColor',[.6 .6 .6],'EdgeColor','k'), axis off\nsubplot(4,1,2), bar(A,'FaceColor',[.6 .6 .6],'EdgeColor','k'), axis([0 1024 -0.002 0.002]), axis off\nfigure(2), subplot(2,2,1)\nA2=flipud(reshape(A,32,32)); pcolor(A2), colormap(gray), axis off\n\nfigure(1), subplot(4,1,3)\nA=lasso(train.',label.','Lambda',0.1).'; \ntest_labels=sign(A*test);\nbar(test_labels,'FaceColor',[.6 .6 .6],'EdgeColor','k'), axis off\nsubplot(4,1,4)\nbar(A,'FaceColor',[.6 .6 .6],'EdgeColor','k'), axis([0 1024 -0.008 0.008]), axis off\nfigure(2), subplot(2,2,2)\nA2=flipud(reshape(A,32,32)); pcolor(A2), colormap(gray), axis off\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/CH06/CH06_SEC01_1_NN_production.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5829190635588641}}
{"text": "%Navigation frame=Local geodetic Frame.\n%Position is mechanized in Cen (essentially Ceg) and h.\n%Attitude is mechanized in quat\n\n%Compare this with strapdown_Cen_dcm and strandown_wander_quat. Both of\n%these strapdowns implement wander frame mechanization. However, only the\n%2nd one is non-singular. Furthermore, also note that the only difference\n%between this script and the strandown_wander_quat is the 1st argument of\n%geoparam function.\n\nfunction [qbn_new, Vn_new, Cen_new, h_new]=strapdown_Cen_quat(qbn, Vn, Cen, h, velinc, anginc, dt)\n%Compute the transport rate of geodetic frame (also the gravity)\n[Fc, wen_n, wie_n, g]=geoparam_v001(2, Cen(:,3), h, Vn); %Compute the curvature matrix for local geodetic frame\n\n%% Update the velocity\nvel_inc1=quatrot_v000(qbn,velinc,0); %Note: 'a' is assumed to be output of a sculling module.\nvel_inc2=(cross(Vn,2*wie_n+wen_n)+[0;0;g])*dt;\nVn_new=Vn+vel_inc1+vel_inc2;\n\n%%update the attitude\n%Body frame updates\nqb=rvec2quat_v000(anginc);    %Note: 'w' is assumed to be the output of coning module\nqbn_new=quatmult_v000(qbn,qb);\n\n%Navigation frame updates\nqn=rvec2quat_v000(-(wen_n+wie_n)*dt);\nqbn_new=quatmult_v000(qn,qbn_new);\n\n%%Position update\nVmid=(Vn+Vn_new)/2;\nwen_n=Fc*[Vmid(2);-Vmid(1);0];\nCn=rot2dcm_v000(-wen_n*dt);\nCen_new=Cn*Cen;\n\nh_new=h-Vmid(3)*dt;", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/INS/strapdown_Cen_quat_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5829190464125085}}
{"text": "classdef RMMEDA_F2 < PROBLEM\n% <multi> <real> <large/none>\n% Benchmark MOP for testing RM-MEDA\n\n%------------------------------- Reference --------------------------------\n% Q. Zhang, A. Zhou, and Y. Jin, RM-MEDA: A regularity model-based\n% multiobjective estimation of distribution algorithm, IEEE Transactions on\n% Evolutionary Computation, 2008, 12(1): 41-63.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            g = 1 + 9*mean((X(:,2:end)-repmat(X(:,1),1,size(X,2)-1)).^2,2);\n            PopObj(:,1) = X(:,1);\n            PopObj(:,2) = g.*(1-(PopObj(:,1)./g).^2);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - R(:,1).^2;\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R = obj.GetOptimum(100);\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/MOPs with variable linkages/RMMEDA_F2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.5829074572110267}}
{"text": "function Y = spdiag(V,K)\n%SPDIAG Sparse diagonal matrices.\n%   SPDIAG(V,K) when V is a vector with N components is a sparse square\n%   matrix of order N+ABS(K) with the elements of V on the K-th diagonal. \n%   K = 0 is the main diagonal, K > 0 is above the main diagonal and K < 0\n%   is below the main diagonal. \n%\n%   SPDIAG(V) is the same as SPDIAG(V,0) and puts V on the main diagonal.\n%\n%   See also DIAG, SPDIAGS.\n\n\n%  Ron Rubinstein\n%  Computer Science Department\n%  Technion, Haifa 32000 Israel\n%  ronrubin@cs\n%\n%  June 2008\n\n\nif (nargin<2)\n  K = 0;\nend\n\nn = length(V) + abs(K);\n\nif (K>0)\n  i = 1:length(V);\n  j = K+1:n;\nelseif (K<0)\n  i = -K+1:n;\n  j = 1:length(V);\nelse\n  i = 1:n;\n  j = 1:n;\nend\n\nY = sparse(i,j,V(:),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/sparsefusion/ksvdbox/private/spdiag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920211198871, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5828841335101843}}
{"text": "function V = LR_sort(W)\nN = size(W, 2);\nLLR = zeros(1, N);\nfor i = 1 : N\n    if (W(1, i) ~= 0) && (W(2, i) ~= 0)\n        LLR(i) = log(W(1, i)) - log(W(2, i));\n    else\n        if (W(1, i) == 0) && (W(2, i) ~= 0)\n            LLR(i) = -inf;\n        else\n            if (W(1, i) ~= 0) && (W(2, i) == 0)\n                LLR(i) = inf;\n            end\n        end\n    end\nend\n[~, ordered]  = sort(LLR, 'descend');\nV = W(:, ordered);\nend", "meta": {"author": "YuYongRun", "repo": "PolarCodeDecodersInMatlab", "sha": "f1b512d10bf057e83f18685ea012d242bdaaf6ac", "save_path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab", "path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab/PolarCodeDecodersInMatlab-f1b512d10bf057e83f18685ea012d242bdaaf6ac/PolarFastSCL/HowToConstructPolarCode/UpgradingConstruction/LR_sort.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5828841313111266}}
{"text": "function phiFaceAverage = upwindMean3D(phi, u)\n% This function gets the value of the field variable phi defined\n% over the MeshStructure and calculates the upwind average on\n% the cell faces, based on the direction of the velocity vector for a uniform mesh.\n%\n% SYNOPSIS:\n%   phiFaceAverage = upwindMean3D(phivar, u)\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 the velocity data\n% note: size(ux) = [1:m+1, 1:n] and size(uy) = [1:m, 1:n+1]\nux = u.xvalue;\nuy = u.yvalue;\nuz = u.zvalue;\n\n% check the size of the variable and the mesh dimension\nNxyz = phi.domain.dims;\nNx = Nxyz(1); Ny = Nxyz(2); Nz = Nxyz(3);\n\n% assign to a temp variable for boundary corrections\nphi_tmp = phi.value;\n\n% correct the value of phi at the boundary (calculation trick)\n% assign the value of the left boundary to the left ghost cells\nphi_tmp(1,:,:) = (phi.value(1,:,:)+phi.value(2,:,:))/2;\n% assign the value of the right boundary to the right ghost cells\nphi_tmp(end,:,:) = (phi.value(end,:,:)+phi.value(end-1,:,:))/2;\n% assign the value of the bottom boundary to the bottom ghost cells\nphi_tmp(:,1,:) = (phi.value(:,1,:)+phi.value(:,2,:))/2;\n% assign the value of the top boundary to the top ghost cells\nphi_tmp(:,end,:) = (phi.value(:,end,:)+phi.value(:,end-1,:))/2;\n% assign the value of the back boundary to the back ghost cells\nphi_tmp(:,:,1) = (phi.value(:,:,1)+phi.value(:,:,2))/2;\n% assign the value of the front boundary to the front ghost cells\nphi_tmp(:,:,end) = (phi.value(:,:,end)+phi.value(:,:,end-1))/2;\n\n% calculate the average value\nxvalue = (ux>0).*phi_tmp(1:Nx+1,2:Ny+1,2:Nz+1)+ ...\n                        (ux<0).*phi_tmp(2:Nx+2,2:Ny+1,2:Nz+1)+ ...\n                        0.5*(ux==0).*(phi.value(1:Nx+1,2:Ny+1,2:Nz+1)+phi.value(2:Nx+2,2:Ny+1,2:Nz+1));\nyvalue = (uy>0).*phi_tmp(2:Nx+1,1:Ny+1,2:Nz+1)+ ...\n                        (uy<0).*phi_tmp(2:Nx+1,2:Ny+2,2:Nz+1)+ ...\n                        0.5*(uy==0).*(phi.value(2:Nx+1,1:Ny+1,2:Nz+1)+phi.value(2:Nx+1,2:Ny+2,2:Nz+1));\nzvalue = (uz>0).*phi_tmp(2:Nx+1,2:Ny+1,1:Nz+1)+ ...\n                        (uz<0).*phi_tmp(2:Nx+1,2:Ny+1,2:Nz+2)+ ...\n                        0.5*(uz==0).*(phi.value(2:Nx+1,2:Ny+1,1:Nz+1)+phi.value(2:Nx+1,2:Ny+1,2:Nz+2));\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/upwindMean3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5828841243866484}}
{"text": "function h = p02_fh ( p, varargin )\n\n%*****************************************************************************80\n%\n%% P02_FH returns a mesh size function for problem 2.\n%\n%  Licensing:\n%\n%    (C) 2004 Per-Olof Persson. \n%    See COPYRIGHT.TXT for details.\n%\n%  Modified:\n%\n%    06 February 2006\n%\n%  Reference:\n%\n%    Per-Olof Persson and Gilbert Strang,\n%    A Simple Mesh Generator in MATLAB,\n%    SIAM Review,\n%    Volume 46, Number 2, June 2004, pages 329-345.\n%\n%  Parameters:\n%\n%    Input, real P(NP,ND), the point coordinates.\n%\n%    Input, VARARGIN, room for extra arguments.\n%\n%    Output, real H(NP,1), the mesh size function.\n%\n  np = size ( p, 1 );\n  h = ones ( np, 1 );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/distmesh/p02_fh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.5828841196612282}}
{"text": "function [stats] = est_checkMVARStability(varargin)\n%\n% Test the stability of a fitted VAR model. See [1-2] for mathematical\n% details on testing VAR stability. A stable VAR process is also a\n% stationary VAR process [2].\n%\n% Inputs:\n%\n%   EEG:        EEGLAB data structure\n%   MODEL:      SIFT MODEL structure\n%   typeproc:   reserved for future use. Use 0\n%\n% Optional:\n%\n%   <Name,Value> pairs containing model fitting parameters. See\n%   est_fitMVAR(). Generally, these should be left unspecified.\n%\n% Outputs:\n%\n%   stats\n%       .stability:  [numwindows x 1] vector of results of stability tests. 1\n%                    indicates stable VAR process for that window, 0 indicates\n%                    an unstable VAR process.\n%\n%       .lambda:     [numwindows x nchs*morder] matrix of eigenvalues of VAR\n%                    process. All eigenvalues should be < 1 for stable VAR process\n%\n%\n% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):\n%     Theoretical Handbook and User Manual. Chapters 3,6.\n%     Available at: http://www.sccn.ucsd.edu/wiki/Sift\n% [2] Lutkepohl, H. (2007) New Introduction to Time Series Analysis.\n%     Springer.\n%\n% Author: Tim Mullen 2010, SCCN/INC, UCSD\n% Email:  tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\ng = arg_define([0 2],varargin, ...\n        arg_norep({'EEG','ALLEEG'},mandatory,[],'EEGLAB dataset'), ...\n        arg_norep({'MODEL','Model'},mandatory,[],'MVAR MODEL object'), ...\n        arg_nogui({'winStartIdx','WindowStartIndices'},[],[],'Starting indices for windows. This is a vector of sample points (start of windows) at which to estimate windowed VAR model. Default is empty (use all windows)','cat','Options'), ...\n        arg({'prctWinToSample','WindowSamplePercent'},100,[1 100],'Percent of windows to sample','cat','Options'), ...\n        arg({'verb','VerbosityLevel'},2,{int32(0) int32(1) int32(2)},'Verbosity level. 0 = no output, 1 = text, 2 = graphical') ...\n        );\n    \n% commit EEG and MODEL variables to workspace\n[data g] = hlp_splitstruct(g,{'EEG','MODEL'});\narg_toworkspace(data);\nclear data;\n\nmorder = MODEL.morder;\n\n% window size in points\n% winLenPnts = floor(MODEL.winlen*EEG.srate);\n\nif isempty(g.winStartIdx)\n    % starting point of each window (points)\n    g.winStartIdx  = round(MODEL.winStartTimes*EEG.srate)+1;\nend\n\nif g.prctWinToSample<100 \n    % randomly select percentage of windows to work with\n    randwin = randperm(length(g.winStartIdx));\n    randwin = sort(randwin(1:ceil(length(g.winStartIdx)*g.prctWinToSample/100)));\n    g.winStartIdx = g.winStartIdx(randwin);\n    g.winArrayIndex = randwin;\nend\n\n% get the array indices of the windows we are working with\ng.winArrayIndex = getindex(MODEL.winStartTimes,(g.winStartIdx-1)/EEG.srate);\n\n% initialize waitbar\nif g.verb==2\n    waitbarTitle = sprintf('Checking stability %s...', ...\n        fastif(isempty(EEG.condition),'',['for ' EEG.condition]));\n    \n    multiWaitbar(waitbarTitle,'Reset');\n    multiWaitbar(waitbarTitle,'ResetCancel',true);\n    multiWaitbar(waitbarTitle, ...\n                 'Color', hlp_getNextUniqueColor, ...\n                 'CanCancel','on', ...\n                 'CancelFcn',@(a,b) disp('[Cancel requested. Please wait...]'));\nend\n\nnumWins = length(g.winStartIdx);\n\nstats.stability = zeros(1,numWins);\n[nchs Mp] = size(MODEL.AR{1});\nstats.lambda = zeros(numWins,Mp);\n%lambda = [];\nI = eye(nchs*morder-nchs,nchs*morder-nchs);\nO = zeros(nchs*morder-nchs,nchs);\nfor t=1:numWins\n    % get the array index of the window we are working with\n    winArrIdx = g.winArrayIndex(t);\n        \n    % rewrite VAR[p] process as VAR[1]\n    A = [MODEL.AR{winArrIdx} ; [I O]];\n    stats.lambda(t,:) = log(abs(eig(A)));\n    stats.stability(t) = all(stats.lambda(t,:)<0);\n    \n    if g.verb==2\n        % update waitbar\n        drawnow;\n        cancel = multiWaitbar(waitbarTitle,t/numWins);\n        if cancel && hlp_confirmWaitbarCancel(waitbarTitle)\n            stats = [];\n            return;\n        end\n    end\n    \nend\n\nstats.winStartIdx = g.winStartIdx;\nstats.winStartTimes = MODEL.winStartTimes(g.winArrayIndex);\nstats.winArrayIndex = g.winArrayIndex;\n\n% clean up\nif g.verb==2\n    multiWaitbar(waitbarTitle,'Close'); \nend\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/est/est_checkMVARStability.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.5828841171348658}}
{"text": "function [M,fig] = plot_marginals(sampleCell,T,truespikes,int_show)\n\n% Plots marginal posterior empirical pdfs for # of spikes for each timebin\n% similar to figure 1B in Pnevmatikakis et al., Neuron 2016\n\n% Inputs:\n% sampleCell:   Cell array with spike times in continuous time (SAMPLES.ss)     \n% T:            Number of timebins\n% truespikes:   Number of true spikes per timebin (vector of size T x 1)\n% int_show:     Show only a specified interval (default: [1,T])\n\n% Output:\n% M:            matrix of empirical posterior pdfs for each timebin\n\n% Author: Eftychios A. Pnevmatikakis, 2016, Simons Foundation\n\nif nargin < 4\n    int_show = 1:T;\nend\nnT = length(int_show);\n\nif nargin == 2\n    truespikes = -0.5*ones(1,nT);\nend\n\nif length(truespikes) == T\n    truespikes = truespikes(int_show);\nend\n\nMat = samples_cell2mat(sampleCell,T);\nMat = Mat(:,int_show);\n\nmS = min(max([Mat(:);truespikes(:)])+1,6);\nM = zeros(mS,nT);\nfor i = 1:nT\n    M(:,i) = hist(Mat(:,i),0:mS-1)/size(Mat,1);\nend\n\ncmap = bone(100);\ncmap(2:26,:) = [];\nfig = figure;\nimagesc(M); axis xy; \n%set(gca,'Ytick',[0.5:(mS+.5)],'Yticklabel',[-1:(mS)]);  %hold all; plot(traceData.spikeFrames+1); set(gca,'YLim',[1,5])\n%set(gca,'YLim',[1.25,mS+.25]);\nhold all; scatter(1:nT,truespikes+1,[],'m');\nset(gca,'YLim',[1.5,mS+.125]);\npos = get(gca,'Position');\nset(gca,'Ytick',0.5+[-0.5:mS-.5],'Yticklabel',[-1+(0:mS)]);\ncolormap(cmap);\nylabel('# of Spikes ','fontweight','bold','fontsize',14);\nxlabel('Timestep ','fontweight','bold','fontsize',14);\ntitle('Posterior Spike Histogram (MCMC) ','fontweight','bold','fontsize',14);\ncbar = colorbar('Location','East');\ncpos = get(cbar,'Position');\nset(cbar,'Position',[pos(1)+pos(4),cpos(2:4)]);\n%set(gca,'Xtick',[])\n%set(cbar,'Color',[1,1,1]);\nset(cbar,'Fontsize',12);", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/deconvolution/MCMC/utilities/plot_marginals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720204, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5828841010868513}}
{"text": "function [v,y,w]=nearnonz(x,d)\n%NEARNONZ replace each zero element with the nearest non-zero element [V,Y,W]=nearnonz(X,D)\n%\n%  Inputs:  x         input vector, matrix or larger array\n%           d         dimension to apply filter along [default 1st non-singleton]\n%\n% Outputs:  v         v is the same size as x but with each zero entry replaced by\n%                     the nearest non-zero value along dimension d\n%                     elements equidistant from two non-zero entries will be taken\n%                     from the higher index\n%           y         y is the same size as x and gives the index along dimension d\n%                     from which the corresponding entry in v was taken\n%                     If there are no non-zero entries, then the corresponding\n%                     elements of y will be zero.\n%           w         w is the same size as x and gives the distance (+ or -) to the\n%                     nearest non-zero entry in x\n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: nearnonz.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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ne=size(x);\np=prod(e);\nif nargin<2             % if no dimension given, find the first non-singleton\n    d=find(e>1,1);\n    if ~numel(d)\n        d=1;\n    end\nend\nk=e(d);                 % size of active dimension\nq=p/k;                  % size of remainder\nif d==1\n    z=reshape(x,k,q);\nelse\n    z=shiftdim(x,d-1);\n    r=size(z);\n    z=reshape(z,k,q);\nend\nxx=z~=0;\ncx=cumsum(xx);\n[i,j]=find(z);\nqq=cx(xx);\npos=full(sparse(qq,j,i,k,q)); % list the positions of non-zero elements in each column\nmp=ceil((pos(1:end-1,:)+pos(2:end,:))*0.5); % find the mid point between consecutive non-zero elements\n[i2,j2]=find(pos(2:end,:)>0);\nzz=1+cumsum(full(sparse(mp(pos(2:end,:)>0),j2,1,k,q)));\ny=pos(zz+repmat((0:q-1)*k,k,1));\nv=z(max(y,1)+repmat((0:q-1)*k,k,1));\nw=y-repmat((1:k)',1,q);\nw(y==0)=0;\nif d==1\n    y=reshape(y,e);\n    v=reshape(v,e);\n    w=reshape(w,e);\nelse\n    y=shiftdim(reshape(y,r),length(e)+1-d);\n    v=shiftdim(reshape(v,r),length(e)+1-d);\n    w=shiftdim(reshape(w,r),length(e)+1-d);\nend\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/nearnonz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.5828817597557924}}
{"text": "function element_node = grid_q16_element ( nelemx, nelemy )\n\n%*****************************************************************************80\n%\n%% GRID_Q16_ELEMENT produces a grid of 16 node quadrilaterals.\n%\n%  Example:\n%\n%    Input:\n%\n%      NELEMX = 2, NELEMY = 2\n%\n%    Output:\n%\n%      ELEMENT_NODE =\n%         1,  2,  3,  4,  8,  9, 10, 11, 15, 16, 17, 18, 22, 23, 24, 25;\n%         4,  5,  6,  7, 11, 12, 13, 14, 18, 19, 20, 21, 25, 26, 27, 28;\n%        22, 23, 24, 25, 29, 30, 31, 32, 36, 37, 38, 39, 43, 44, 45, 46;\n%        25, 26, 27, 28, 32, 33, 34, 35, 39, 40, 41, 42, 46, 47, 48, 49.\n%\n%  Grid:\n%\n%   43-44-45-46-47-48-49\n%    |        |        |\n%    |        |        |\n%   36 37 38 39 40 41 42\n%    |        |        |\n%    |        |        |\n%   29 30 31 32 33 34 35\n%    |        |        |\n%    | 3      | 4      |\n%   22-23-24-25-26-27-28\n%    |        |        |\n%    |        |        |\n%   15 16 17 18 19 20 21\n%    |        |        |\n%    |        |        |\n%    8  9 10 11 12 13 14\n%    |        |        |\n%    | 1      | 2      |\n%    1--2--3--4--5--6--7\n%\n%  Reference Element Q16:\n%\n%    |\n%    1 13--14--15--16\n%    |  |   :   :   |\n%    |  |   :   :   |\n%    |  9..10..11..12\n%    S  |   :   :   |\n%    |  |   :   :   |\n%    |  5...6...7...8\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, integer NELEMX, NELEMY, the number of elements along the\n%    X and Y directions.  The number of elements generated will be\n%    NELEMX * NELEMY.\n%\n%    Output, integer ELEMENT_NODE(16,NELEMX*NELEMY), the nodes that form\n%    each element.\n%\n  element = 0;\n\n  for j = 1 : nelemy\n    for i = 1 : nelemx\n\n      base = ( j - 1 ) * 3 * ( 3 * nelemx + 1 ) + 3 * i - 2;\n\n      element = element + 1;\n\n      element_node( 1,element) = base;\n      element_node( 2,element) = base                          + 1;\n      element_node( 3,element) = base                          + 2;\n      element_node( 4,element) = base                          + 3;\n      element_node( 5,element) = base +     ( 3 * nelemx + 1 );\n      element_node( 6,element) = base +     ( 3 * nelemx + 1 ) + 1;\n      element_node( 7,element) = base +     ( 3 * nelemx + 1 ) + 2;\n      element_node( 8,element) = base +     ( 3 * nelemx + 1 ) + 3;\n      element_node( 9,element) = base + 2 * ( 3 * nelemx + 1 );\n      element_node(10,element) = base + 2 * ( 3 * nelemx + 1 ) + 1;\n      element_node(11,element) = base + 2 * ( 3 * nelemx + 1 ) + 2;\n      element_node(12,element) = base + 2 * ( 3 * nelemx + 1 ) + 3;\n      element_node(13,element) = base + 3 * ( 3 * nelemx + 1 );\n      element_node(14,element) = base + 3 * ( 3 * nelemx + 1 ) + 1;\n      element_node(15,element) = base + 3 * ( 3 * nelemx + 1 ) + 2;\n      element_node(16,element) = base + 3 * ( 3 * nelemx + 1 ) + 3;\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/fem2d_pack/grid_q16_element.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.5828817556960254}}
{"text": "%% Niblack Image Thresholding\n% Sample to compare Niblack thresholding against other algorithms\n% (global thresholding and adaptive thresholding) for an image with varying\n% illumination.\n%\n% Sources:\n%\n% * <https://github.com/opencv/opencv_contrib/blob/3.2.0/modules/ximgproc/samples/niblack_thresholding.cpp>\n% * <https://docs.opencv.org/3.2.0/d7/d4d/tutorial_py_thresholding.html>\n%\n\nfunction niblack_thresholding_demo()\n    % Input 8-bit grayscale image + Parameters\n    % - BS: block size (local neighborhood) [niblack, adaptive]\n    % - K : constant multiplied by std dev next subtracted from mean [niblack]\n    % - C : constant subtracted from mean [adaptive]\n    if ~mexopencv.isOctave() && mexopencv.require('images')\n        % image with dark pixels being foreground\n        im = which('printedtext.png');\n        K = -0.7;\n        C = 7;\n    elseif true\n        % image with dark pixels being foreground\n        im = fullfile(mexopencv.root(),'test','sudoku.jpg');\n        K = -0.7;\n        C = 7;\n    elseif ~mexopencv.isOctave() && mexopencv.require('images')\n        % image with white pixels being foreground\n        im = which('rice.png');\n        K = 0.7;\n        C = -17;\n    end\n    assert(~isempty(im) && exist(im, 'file') == 2);\n    img = cv.imread(im, 'Grayscale',true);\n    BS = min(floor(size(img)/16) * 2 + 1);\n    assert(~isempty(img), 'Failed to load image');\n\n    % Preprocess image\n    if true\n        % no processing\n        src = img;\n    elseif false\n        src = cv.medianBlur(img, 'KSize',3);\n    elseif true\n        % really effective for global thresholding [otsu]\n        src = localNormalization(img, 11, 33);\n    else\n        % rice image, estimate and subtract non-uniform illumination background\n        % (see NonuniformIlluminationExample.mlx example)\n        if mexopencv.require('images')\n            src = imtophat(img, strel('disk',15));\n            src = imadjust(src);\n        else\n            el = cv.getStructuringElement('Shape','Ellipse', 'KSize',[15 15]*2-1);\n            src = cv.morphologyEx(img, 'Tophat', 'Element',el);\n            obj = cv.SimpleWB();\n            src = obj.balanceWhite(src);\n        end\n    end\n\n    % Threshold\n    opts = {'Type','Binary', 'MaxValue',255};\n    bw1 = cv.threshold(src, 'Otsu', opts{:});\n    bw2 = cv.adaptiveThreshold(src, 'Method','Mean', ...\n        'C',C, 'BlockSize',BS, opts{:});\n    bw3 = cv.adaptiveThreshold(src, 'Method','Gaussian', ...\n        'C',C, 'BlockSize',BS, opts{:});\n    bw4 = cv.niBlackThreshold(src, K, 'Method','Niblack', ...\n        'BlockSize',BS, opts{:});\n    bw5 = cv.niBlackThreshold(src, -K, 'Method','Sauvola', ...\n        'BlockSize',BS, opts{:});\n    bw6 = cv.niBlackThreshold(src, -K, 'Method','Wolf', ...\n        'BlockSize',BS, opts{:});\n    bw7 = cv.niBlackThreshold(src, K, 'Method','Nick', ...\n        'BlockSize',BS, opts{:});\n    %bw8 = my_niblack(src, K, BS);\n\n    % Results\n    subplot(331), imshow(img), title('Source')\n    subplot(332), imshow(src), title('Processed')\n    subplot(333), imshow(bw1), title('Otsu')\n    subplot(334), imshow(bw2), title('Adaptive Mean')\n    subplot(335), imshow(bw3), title('Adaptive Gaussian')\n    subplot(336), imshow(bw4), title('Niblack')\n    subplot(337), imshow(bw5), title('Sauvola')\n    subplot(338), imshow(bw6), title('Wolf')\n    subplot(339), imshow(bw7), title('Nick')\nend\n\n%% Helper function\n\nfunction out = localNormalization(img, s1, s2)\n    %LOCALNORMALIZATION  local normalization to get uniform local mean and variance\n    %\n    %     out = localNormalization(img)\n    %     out = localNormalization(img, s1, s2)\n    %\n    % The local normalization tends to uniformize the mean and variance of an\n    % image around a local neighborhood. This is especially useful for correct\n    % non-uniform illumination or shading artifacts.\n    %\n    % ## Input\n    % * __img__ 8-bit input image\n    %\n    % ## Output\n    % * __out__ output image of same size and type.\n    %\n    % ## Options\n    % * __s1__ sigma to estimate the local mean. default 5\n    % * __s2__ sigma to estimate the local variance. Often `s2` should be\n    %   larger than `s1`. default 15\n    %\n    % ## References\n    % > http://bigwww.epfl.ch/sage/soft/localnormalization/\n    %\n\n    % check arguments\n    if nargin < 2, s1 = 5; end\n    if nargin < 3, s2 = 15; end\n    validateattributes(img, {'uint8'}, {});\n\n    % convert to grayscale\n    if size(img,3) == 3\n        gray = cv.cvtColor(img, 'RGB2GRAY');\n    else\n        gray = img;\n    end\n\n    % convert to floating-point image\n    gray = cv.convertTo(gray, 'RType','single', 'Alpha',1.0/255.0);\n\n    % numerator = img - gauss_blur(img)\n    blur = cv.GaussianBlur(gray, 'KSize',[0 0], 'SigmaX',s1, 'SigmaY',s1);\n    num = gray - blur;\n\n    % denominator = sqrt(gauss_blur(img^2))\n    den = sqrt(cv.GaussianBlur(num.^2, 'KSize',[0 0], 'SigmaX',s2, 'SigmaY',s2));\n\n    % output = numerator / denominator\n    out = num ./ den;\n\n    % normalize output into [0,1]\n    out = cv.normalize(out, 'Alpha',0.0, 'Beta',1.0, 'NormType','MinMax');\n\n    % convert to 8-bit\n    out = cv.convertTo(out, 'RType','uint8', 'Alpha',255.0);\nend\n\nfunction bw = my_niblack(img, K, BS)\n    %MY_NIBLACK  Manual implementation of Niblack thresholding\n\n    img = im2double(img);\n    mu = imboxfilt(img, [BS BS]);\n    sd = sqrt(imboxfilt(img.^2, [BS BS]) - mu.^2);\n    bw = img > (mu + K*sd);\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/samples/niblack_thresholding_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.5828817433206732}}
{"text": "% SYNTAX:\n% dod = hmrR_Intensity2OD( intensity )\n%\n% UI NAME:\n% Intensity_to_Delta_OD\n%\n% DESCRIPTION:\n% Converts intensity data to optical density\n%\n% INPUT:\n% intensity - SNIRF data type where the d matrix is intensity\n%\n% OUTPUT:\n% dod - SNIRF data type where the d matrix is change in optical density\n%\n% USAGE OPTIONS:\n% Intensity_to_Delta_OD: dod = hmrR_Intensity2OD(data)\n%\nfunction dod = hmrR_Intensity2OD( intensity )\n\n% convert to dod\ndod = DataClass().empty();\nfor ii=1:length(intensity)\n    dod(ii) = DataClass();\n    d = intensity(ii).GetDataTimeSeries();\n    dm = mean(abs(d),1);\n    nTpts = size(d,1);\n    dod(ii).SetTime(intensity(ii).GetTime());\n    dod(ii).SetDataTimeSeries(-log(abs(d)./(ones(nTpts,1)*dm)));\n    dod(ii).SetMl(intensity(ii).GetMl());\n    dod(ii).SetDataTypeDod();\nend\n", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/FuncRegistry/UserFunctions/hmrR_Intensity2OD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5828584064940986}}
{"text": "f = [143 60];\nA = [120 210; 110 30; 1 1];\nb = [15000; 4000; 75];\nlp = lp_maker(f, A, b, [-1; -1; -1], [], [], [], 1, 0);\nsolvestat = mxlpsolve('solve', lp)\nformat bank\nobj = mxlpsolve('get_objective', lp)\nformat short\nx = mxlpsolve('get_variables', lp)\nmxlpsolve('delete_lp', lp);\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/Solvers/lp_solve/distribution/example4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5828254721712623}}
{"text": "function [n,msg1,msg2] = firchk(n,Fend,a,exception)\n%FIRCHK   Check if specified filter order is valid.\n%   FIRCHK(N,Fend,A) checks if the specified order N is valid given the\n%   final frequency point Fend and the desired magnitude response vector A.\n%   Type 2 linear phase FIR filters (symmetric, odd order) must have a\n%   desired magnitude response vector that ends in zero if Fend = 1.  This\n%   is because type 2 filters necessarily have a zero at w = pi.\n%\n%   If the order is not valid, a warning is given and the order\n%   of the filter is incremented by one.\n%\n%   If A is a scalar (as when called from fircls1), A = 0 is\n%   interpreted as lowpass and A = 1 is interpreted as highpass.\n%\n%   FIRCHK(N,Fend,A,EXCEPTION) will not warn or increase the order\n%   if EXCEPTION = 1.  Examples of EXCEPTIONS are type 4 filters\n%   (such as differentiators or hilbert transformers) or non-linear\n%   phase filters (such as minimum and maximum phase filters).\n\n%   Author : R. Losada\n%   Copyright 1988-2004 The MathWorks, Inc.\n%   $Revision: 1.7.4.5 $  $Date: 2007/12/14 15:15:06 $\n\n\nmatlab_v = version('-release');\nmatlab_v = str2double(matlab_v(1:4));\n\nif matlab_v > 2012\n    narginchk(3,4)\nelse\n    error(nargchk(3,4,nargin,'struct'))\nend\n\nif nargin == 3,\n    exception = false;\nend\n\nmsg1 = '';\nmsg2 = '';\noddord = false; % Flag, initially we assume even order\n\nif isempty(n) || length(n) > 1 || ~isnumeric(n) || ~isreal(n) || n~=round(n) || n<=0,\n    msg1 = 'Filter order must be a real, positive integer.';\n    return\nend\n\nif rem(n,2) == 1,\n    oddord = true; % Overwrite flag\nend\n \nif (a(end) ~= 0) && Fend == 1 && oddord && ~exception,\n    str = ['Odd order symmetric FIR filters must have a gain of zero \\n'...\n     'at the Nyquist frequency. The order is being increased by one.'];\n    msg2 = sprintf(str);\n    n = n+1;\nend\n    \n\n", "meta": {"author": "ucdavis", "repo": "erplab", "sha": "e4f66f7a512c4dee2f7596982318e44bb1b72644", "save_path": "github-repos/MATLAB/ucdavis-erplab", "path": "github-repos/MATLAB/ucdavis-erplab/erplab-dd2f60aa41b01c866fcec342efafc48323523cc2/functions/firchk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.5828046789176171}}
{"text": "function gen_hermite_poly_test ( )\n\n%******************************hermite****************************************80\n%\n%% GEN_HERMITE_POLY_TEST tests GEN_HERMITE_POLY.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    09 February 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  i_test = 6;\n  n = 10;\n\n  mu_test = [ 0.0, 0.0, 0.1, 0.1, 0.5, 1.0 ];\n  x_test = [ 0.0, 1.0, 0.0, 0.5, 0.5, 0.5 ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'GEN_HERMITE_POLY_TEST\\n' );\n  fprintf ( 1, '  GEN_HERMITE_POLY evaluates the generalized Hermite \\n' );\n  fprintf ( 1, '  polynomials.\\n' );\n\n  for i = 1 : i_test\n\n    x = x_test(i);\n    mu = mu_test(i);\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Table of L(N,MU)(X) for\\n' );\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '    N(max) = %d\\n', n );\n    fprintf ( 1, '    MU =     %f\\n', mu );\n    fprintf ( 1, '    X =      %f\\n', x );\n    fprintf ( 1, '\\n' );\n  \n    c = gen_hermite_poly ( n, x, mu );\n \n    for j = 0 : n\n      fprintf ( 1, '  %4d  %12f\\n', j, c(j+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/polpak/gen_hermite_poly_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.5828046787215937}}
{"text": "function t = ktensor(varargin)\n%KTENSOR Tensor stored as a Kruskal operator (decomposed).\n%\n%   K = KTENSOR(lambda,U1,U2,...,UM) creates a Kruskal tensor from its\n%   constituent parts. Here lambda is a k-vector and each Um is a\n%   matrix with k columns.\n%\n%   K = KTENSOR(lambda, U) is the same as above except that U is a\n%   cell array containing matrix Um in cell m.\n%\n%   K = KTENSOR(U) assumes U is a cell array containing matrix Um in\n%   cell m and assigns the weight of each factor to be one.\n%\n%   K = KTENSOR(T) creates a ktensor by copying an existing ktensor.\n%\n%   Examples\n%   K = ktensor([3; 2], rand(4,2), rand(5,2), rand(3,2))\n%\n%   See also TENSOR, TTENSOR, KTENSOR/FULL.\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\n\n% EMPTY CONSTRUCTOR\nif nargin == 0\n    t.lambda = [];\n    t.u = {};\n    t = class(t,'ktensor');\n    return;\nend\n\n% Copy CONSTRUCTOR\nif (nargin == 1) && isa(varargin{1}, 'ktensor')\n    t.lambda = varargin{1}.lambda;\n    t.u = varargin{1}.u;\n    t = class(t, 'ktensor');\n    return;\nend\n\nif isa(varargin{1},'cell')\n\n    u = varargin{1};\n    t.lambda = ones(size(u{1},2),1);\n    t.u = u;\n    \nelse\n\n    t.lambda = varargin{1};\n    if ~isa(t.lambda,'numeric') || ndims(t.lambda) ~=2 || size(t.lambda,2) ~= 1\n\terror('LAMBDA must be a column vector.');\n    end\n    \n    if isa(varargin{2},'cell')\n\tt.u = varargin{2};\n    else\n\tfor i = 2 : nargin\n\t    t.u{i-1} = varargin{i};\n\tend\n    end\n\nend\n    \n    \n% Check that each Um is indeed a matrix\nfor i = 1 : length(t.u)\n    if ndims(t.u{i}) ~= 2\n\terror(['Matrix U' int2str(i) ' is not a matrix!']);\n    end\nend\n\n% Size error checking\t\t\t     \nk = length(t.lambda); \nfor i = 1 : length(t.u)            \n    if  size(t.u{i},2) ~= k\n       error(['Matrix U' int2str(i) ' does not have ' int2str(k) ' columns.']);\n    end\nend\n\nt = class(t, 'ktensor');\nreturn;\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/@ktensor/ktensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.5828046624822508}}
{"text": "function UNew = fluidDirichlet3D(varargin);\n% fluidDirichlet3D: solve fluid registraion in 3D with Dirichlet\n%        boundary conditions\n%\n%\n% author: Nathan D. Cahill\n% email: nathan.cahill@rit.edu\n% affiliation: Rochester Institute of Technology\n% date: January 2014\n% licence: GNU GPL v3\n%\n% Copyright Nathan D. Cahill\n% Code available from https://github.com/tomdoel/npReg\n%\n%\n\n% parse input arguments\n[DU,F,mu,lambda,PixSize,M,N,P,RegularizerFactor,HX,HY,HZ] = parse_inputs(varargin{:});\n\n% multiply F by adjoint of Navier-Lame equations\nFNew = adjointNL(F/RegularizerFactor,mu,lambda,0,M,N,P);\n\n% compute sine transform of new force field\nFS = discreteSineTransform(FNew,M,N,P);\n\n% construct images of coordinates scaled by pi/(N or M or P)\n[a,b,c] = ndgrid(pi*(0:(M-1))/(M-1),pi*(0:(N-1))/(N-1),pi*(0:(P-1))/(P-1));\n\n% construct LHS factor\nLHSfactor = mu.*(lambda+2*mu).*(2*cos(a) + 2*cos(b) + 2*cos(c) - 6).^2;\n\n% if gamma is zero, set origin term to 1, as DC term does not matter\nLHSfactor(1,1,1) = 1;\n\n% solve for FFT of U\nVS = cat(4,FS(:,:,:,1)./LHSfactor,FS(:,:,:,2)./LHSfactor,FS(:,:,:,3)./LHSfactor);\n\n% perform inverse DST\nV = discreteSineTransform(VS,M,N,P);\n\n% now perform Euler integration to construct new displacements\nUNew = zeros(M,N,P,3);\nUNew(:,:,:,1) = (1 - imfilter(V(:,:,:,1),HX,'replicate','same')).*V(:,:,:,1) - ...\n    imfilter(V(:,:,:,2),HY,'replicate','same').*V(:,:,:,2) - ...\n    imfilter(V(:,:,:,3),HZ,'replicate','same').*V(:,:,:,3);\nUNew(:,:,:,2) = -imfilter(V(:,:,:,1),HY,'replicate','same').*V(:,:,:,1) + ...\n    (1 - imfilter(V(:,:,:,2),HY,'replicate','same')).*V(:,:,:,2) - ...\n    imfilter(V(:,:,:,3),HY,'replicate','same').*V(:,:,:,3);\nUNew(:,:,:,3) = -imfilter(V(:,:,:,1),HZ,'replicate','same').*V(:,:,:,1) - ...\n    imfilter(V(:,:,:,2),HZ,'replicate','same').*V(:,:,:,2) + ...\n    (1 - imfilter(V(:,:,:,3),HZ,'replicate','same')).*V(:,:,:,3);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction FS = discreteSineTransform(F,M,N,P);\n% compute discrete sine transform of 3-D vector field\n\n% initialize resulting array\nFS = F;\n\n% first perform sine transform down columns\nlen = 2*M-2; ind = 1:M;\nfor p=1:P\n    for n=1:N\n        s = fft(FS(:,n,p,:),len,1);\n        FS(:,n,p,:) = imag(s(ind,:,:,:));\n    end\nend\nFS = sqrt(2/(M-1))*FS;\n\n% next perform sine transform across rows\nlen = 2*N-2; ind = 1:N;\nfor p=1:P\n    for m=1:M\n        s = fft(FS(m,:,p,:),len,2);\n        FS(m,:,p,:) = imag(s(:,ind,:,:));\n    end\nend\nFS = sqrt(2/(N-1))*FS;\n\n% finally perform sine transform across pages\nlen = 2*P-2; ind = 1:P;\nfor n=1:N\n    for m=1:M\n        s = fft(FS(m,n,:,:),len,3);\n        FS(m,n,:,:) = imag(s(:,:,ind,:));\n    end\nend\nFS = sqrt(2/(P-1))*FS;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction FNew = adjointNL(F,mu,lambda,gamma,M,N,P);\n% multiply vector field F by adjoint Navier-Lame equations\n\n% initialize FNew\nFNew = zeros(M,N,P,3);\n\n% construct filter that implements 3-D Laplacian\nL = (lambda+2*mu)*cat(3,[0 0 0;0 1 0;0 0 0],[0 1 0;1 -6 1;0 1 0],[0 0 0;0 1 0;0 0 0]);\n\n% we will need to use L to form two different filters\n% L1 = -(lambda+2*mu)*L; L1(2,2,2) = gamma + L1(2,2,2);\n% L2 = -mu*L; L2(2,2,2) = gamma + L2(2,2,2);\n\n% construct grad div filters\nGD11 = (lambda+mu)*cat(3,zeros(3,3),[0 1 0;0 -2 0;0 1 0],zeros(3,3));\nGD22 = ipermute(GD11,[2 1 3]);\nGD33 = ipermute(GD11,[3 2 1]);\nGD23 = zeros(3,3,3);\nGD23(2,1,1) = 1; GD23(2,3,3) = 1; GD23(2,1,3) = -1; GD23(2,3,1) = -1;\nGD23 = GD23*(lambda+mu)/4;\nGD12 = ipermute(GD23,[3 1 2]);\nGD13 = ipermute(GD23,[2 3 1]);\n\n% perform filtering\nFNew(:,:,:,1) = imfilter(F(:,:,:,1),L-GD11,'replicate') + ...\n    imfilter(F(:,:,:,2),-GD12,'replicate') + ...\n    imfilter(F(:,:,:,3),-GD13,'replicate');\nFNew(:,:,:,2) = imfilter(F(:,:,:,1),-GD12,'replicate') + ...\n    imfilter(F(:,:,:,2),L-GD22,'replicate') + ...\n    imfilter(F(:,:,:,3),-GD23,'replicate');\nFNew(:,:,:,3) = imfilter(F(:,:,:,1),-GD13,'replicate') + ...\n    imfilter(F(:,:,:,2),-GD23,'replicate') + ...\n    imfilter(F(:,:,:,3),L-GD33,'replicate');\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [DU,F,mu,lambda,PixSize,M,N,P,RegularizerFactor,HX,HY,HZ] = parse_inputs(varargin);\n\n% get displacement field and check size\nF = varargin{2};\nPixSize = varargin{4}(1:3);\nM = varargin{5};\nN = varargin{6};\nP = varargin{7};\nmu = varargin{8};\nlambda = varargin{9};\nRegularizerFactor = varargin{10};\nDU = varargin{11};\nHX = varargin{12};\nHY = varargin{13};\nHZ = varargin{14};\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/npReg/npRegLib/fluidDirichlet3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5827985939327267}}
{"text": "function x_hat=phit_fp(y,m,n,ops)\n% function x_hat=phit_fp(y,m,n,ops)\n% PHIT_FP projects a length m signal onto the transpose of an mxn measurment matrix.\n% Input:\n%       y   : length m signals (for example a vectorized image)\n%       m   : the number of measurements\n%       n   : the signal length\n%       ops : currently unused argument\n%Output:\n%       x   : result of projecting y onto phi'.\n    x_hat=zeros(n,1);\n    remaining_rows=n;\n    K=4096;\n    iters=ceil(n/K);\n    for i=0:iters-1\n        rng(i);\n        row_num=min(K,remaining_rows);\n        phi_columns=randn(m,row_num); \n        column_norms=sqrt(sum(abs(phi_columns).^2,1));\n        phi_columns=bsxfun(@rdivide,phi_columns,column_norms);\n        phit_rows=phi_columns';\n        x_hat(K*i+1:K*i+row_num)=phit_rows*y;\n        remaining_rows=remaining_rows-K;\n    end\nend", "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/Utils/phit_fp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5827985782617932}}
{"text": "function state = viterbi(feature, hmm)\n%VITERBI    Viterbi decoding of HMM.\n%   Format: state = viterbi(feature, hmm)\n%   Inputs:\n%       feature:    Feature matrix, where each column stands for a time\n%                   step.\n%       HMM:        HMM model.\n%   Output:\n%       state:      Decoded state sequence.\n\n    frames = size(feature, 2);\n    states = length(hmm.init);\n    decision = zeros(frames, states);\n\n    emit = -inf(frames, states);\n    for u = 1:states\n        if (~isempty(hmm.gmm{u}))\n            emit(:,u) = log(hmm.gmm{u}.pdf(feature'));\n        end\n    end\n\n    trans = log(hmm.trans);\n    prob = log(hmm.init);\n    for f = 1:frames\n        newProb = zeros(1, states);\n        for u = 1:states\n            [newProb(u) decision(f,u)] = max(prob + trans(:,u)');\n        end\n        prob = newProb + emit(f,:);\n    end\n\n    [temp state(frames)] = max(prob);\n    for f = frames:-1:2\n        state(f-1) = decision(f, state(f));\n    end\nend\n", "meta": {"author": "MaigoAkisame", "repo": "VMSep-2010", "sha": "8d9b89929642ff2a324f4a2f72e136d3cbb19b76", "save_path": "github-repos/MATLAB/MaigoAkisame-VMSep-2010", "path": "github-repos/MATLAB/MaigoAkisame-VMSep-2010/VMSep-2010-8d9b89929642ff2a324f4a2f72e136d3cbb19b76/code/viterbi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5827579129520979}}
{"text": "function [x,b,a] = bst_bandpass_filtfilt(x, Fs, HighPass, LowPass, isStopBand, FilterType)\n% BST_BANDPASS_FILTFILT: Bandpass filter for the signal x, using the filtfilt function (used by default after Nov 2014)\n%\n% USAGE:  [x,b,a] = bst_bandpass_filtfilt(x, Fs, HighPass, LowPass, isStopBand=0, FilterType='fir')\n% \n% INPUT: \n%    - x          : [nChannels,nTime] signal to process\n%    - Fs         : Sampling frequency\n%    - HighPass   : Frequency below this value are filtered (set to 0 for low-pass filter only)\n%    - LowPass    : Frequency above this value are filtered (set to 0 for high-pass filter only)\n%    - isStopBand : If 1, create a stop-band filter instead of a pass-band filter\n%    - FilterType : 'fir' or 'iir'\n%\n% OUTPUT:\n%    - x   : Filtered signals\n%    - b,a : Filter coefficients, as defined in all the Matlab functions\n%\n% DESCRIPTION: \n%    - A linear phase FIR filter is created and applied both forward and backward using filtfilt.\n%    - Function \"filtfilt\" is used to employ the filtering \"mirror\" trick, and to reset automatically the group delay.\n%    - Function \"kaiserord\" and \"kaiser\" are used to set the necessary order for fir1. \n%    - The transition band is hard-coded. \n%    - Requires Signal Processing Toolbox for the following functions: kaiserord, kaiser, ellipord, \n%      If not, using Octave-based alternatives\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: John Mosher, Francois Tadel, 2014\n\n% ===== PARSE INPUTS =====\nif (nargin < 6) || isempty(FilterType)\n    FilterType = 'fir';\nend\nif (nargin < 5) || isempty(isStopBand)\n    isStopBand = 0;\nend\nif isempty(HighPass)\n    HighPass = 0;\nend\nif isempty(LowPass)\n    LowPass = 0;\nend\n% If both high-pass and low-pass are zero: return signals unaltered\nif (HighPass == 0) && (LowPass == 0)\n    disp('BST_BANDPASS> Error: No frequency band in input');\n    return;\nend\n\n\n% ===== FILTER PARAMETERS =====\nPASSBAND_RIPPLE = 5;    % percent pass band ripple\nPASSBAND_DB     = 1;    % dB of pass band ripple\nSTOP_ATTEN_DB   = 40;   % dB of attenuation in the stop band\nTRANSITION_BAND = 0.05; % normalized to Nyquist, the allowed transition band\n% We use filtfilt, which doubles the effect (attenuation and ripple)\nPASSBAND_RIPPLE = PASSBAND_RIPPLE/2;\nSTOP_ATTEN_DB   = STOP_ATTEN_DB/2;\n% Conversion from percent\nRipple = PASSBAND_RIPPLE/100;    \n% Stop band attenuation\nAtten  = 10^(-STOP_ATTEN_DB/20);\n\n% Convert frequencies to normalized form\nNyquist = Fs/2;\nf_highpass = HighPass / Nyquist;\nf_lowpass  = LowPass  / Nyquist;\n% Reasonable digital transition band\nf_highstop = f_highpass - TRANSITION_BAND; \nf_lowstop  = f_lowpass  + TRANSITION_BAND;\n\n\n% ===== CREATE FILTER =====\nswitch FilterType\n    % ===== FIR =====\n    case 'fir'\n        % Build the general case first\n        fcuts = [f_highstop, f_highpass, f_lowpass, f_lowstop];\n        % Stop-band\n        if isStopBand\n            mags = [1 0 1];               % filter magnitudes\n            devs = [Ripple Atten Ripple]; % deviations\n        % Pass-band\n        else\n            mags = [0 1 0];               % filter magnitudes\n            devs = [Atten Ripple Atten];  % deviations\n        end\n        % Now adjust for desired properties\n        fcuts = max(0,fcuts);     % Can't go below zero\n        fcuts = min(1-eps,fcuts); % Can't go above or equal to 1\n        % We have implicitly created a bandpass, but now adjust for desired filter\n        if (f_lowpass == 0)  % User didn't want a lowpass\n            fcuts(3:4) = [];\n            mags(3) = [];\n            devs(3) = [];\n        end\n        if (f_highpass == 0)  % User didn't want a highpass\n            fcuts(1:2) = [];\n            mags(1) = [];\n            devs(1) = [];\n        end\n        % Generate FIR filter\n        [n,Wn,beta,ftype] = kaiserord(fcuts,mags,devs,2);\n        n = n + rem(n,2);  % ensure even order\n        b = fir1(n,Wn,ftype,kaiser(n+1,beta),'noscale');\n        a = 1;\n        \n    % ===== IIR =====\n    case 'iir'\n        % Stop-band\n        if isStopBand\n            ftype = 'stop';\n            Ws = [f_highpass f_lowpass]; % the range of stopped\n            Wp = [f_highstop f_lowstop]; % the transition band\n        % Pass-band\n        else\n            ftype = 'bandpass';\n            Ws = [f_highstop f_lowstop]; % the transition band\n            Wp = [f_highpass f_lowpass]; % the passband\n        end\n        % Now handle extremes\n        Ws = max(eps,Ws);   % Can't be zero or less\n        Wp = max(eps,Wp);\n        Ws = min(1-eps,Ws); % Can't be 1\n        Wp = min(1-eps,Wp);\n        % Now handle highpass or lowpass only\n        if (f_lowpass == 0)  % User didn't want a lowpass\n            ftype = 'high';\n            Ws(2) = [];\n            Wp(2) = [];\n        end\n        if (f_highpass == 0)  % User didn't want a highpass\n            ftype = 'low';\n            Ws(1) = [];\n            Wp(1) = [];\n        end\n        % Generate IIR filter\n        [n,WP] = ellipord(Wp,Ws,PASSBAND_DB,STOP_ATTEN_DB);\n        [b,a]  = ellip(n,PASSBAND_DB,STOP_ATTEN_DB,WP,ftype);\nend\n\n\n% ===== FILTER THE DATA =====\nNtime = size(x,2);\n% Remove the mean of the data before filtering, which wrecks most filters\nxmean = mean(x,2);\nx = bst_bsxfun(@minus, x, xmean)';    % Transposed output (time is now down the columns)\n% Using filtfilt to use the mirroring trick and remove group delay\ntry\n    x = filtfilt(b,a,x)';     % Transposed output\n    \n    % OCTAVE IMPLEMENTATION\n    % http://octave-signal.sourcearchive.com/documentation/1.0.8/filtfilt_8m-source.html\ncatch \n    fprintf('Sequence too short for filtfilt, using alternate approach.\\n')  \n    xmirror = [flipud(x); x; flipud(x)];      % Mirror either end\n    xmirror = filter(b,1,xmirror);            % Filter\n    xmirror = flipud(xmirror);                % Reverse in time\n    xmirror = flipud(filter(b,1,xmirror));    % Filter and flip again\n    x = xmirror(Ntime + (1:Ntime),:)';        % Transposed output\nend\n% Restore the mean of the signal (only if there is no high-pass filter)\nif (f_highpass == 0)\n    x = bst_bsxfun(@plus, x, xmean);\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/toolbox/math/bst_bandpass_filtfilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5827579121164789}}
{"text": "function margLogPr = calcLogMargPrObsSeqFAST( LL, Eta )\n% calcLogMargPrObsSeqFAST\n% Provides fast calculation of marginal likelihood\n%    for a particular sequence of data, given HMM parameters in the form\n%      soft evidence LL, where LL(kk,tt) = p( X{ii}(tt) | theta(kk) )\n%      transition weights Pz, which may be non-normalized\n% Massages input data and then calls a super-efficient MEX function\n%   \"FilterFwdC\" to perform dynamic programming.\n%INPUT\n% LL  := KiixTii matrix of log likelihoods soft evidence\n% Pz  := KiixKii matrix of transition weights (non-normalized)\n%OUTPUT\n%  margLogPr  := scalar value of log( X_ii | F_ii, theta, Eta_ii ) \n\nK = size(Eta,2);\nif K == 0\n    margLogPr = -Inf;\n    return;\nend\n\nPi = bsxfun( @rdivide, Eta, sum(Eta,2) );\n\n% Need to turn log_lik into lik.  We know lik = exp( log_lik )\n%   For numerical stability, we find M = max( log_lik )\n%       we compute L = exp( log_lik - M  )\n%       and we thus have lik up to multiplicative constant\n%              since lik \\propto L = exp( log_lik ) / exp( M )\n%   We find a unique \"normalizer\" M_t  for each time step\n   \n% normC = 1 x T\nnormC = max( LL,[],1);\n    \nif K == 1\n    margLogPr = sum(normC );\n    return;\nend\nLik = exp( bsxfun( @minus, LL, normC ) );\n    \n[~,margLogPr] = FilterFwdC( Pi, Lik, 1/K*ones(1,K) );\nmargLogPr = margLogPr + sum( normC );\n\nend % main function\n\n", "meta": {"author": "michaelchughes", "repo": "NPBayesHMM", "sha": "22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd", "save_path": "github-repos/MATLAB/michaelchughes-NPBayesHMM", "path": "github-repos/MATLAB/michaelchughes-NPBayesHMM/NPBayesHMM-22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd/code/obsModel/calcLogMargPrObsSeqFAST.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5827579086375492}}
{"text": "function [number_of_objectives, number_of_decision_variables, min_range_of_decesion_variable, max_range_of_decesion_variable] = objective_description_function()\n\n%% function [number_of_objectives, number_of_decision_variables, min_range_of_decesion_variable, max_range_of_decesion_variable] = objective_description_function()\n% This function is used to completely describe the objective functions and\n% the range for the decision variable space etc. The user is prompted for\n% inputing the number of objectives, numebr of decision variables, the\n% maximum and minimum range for each decision variable and finally the\n% function waits for the user to modify the evaluate_objective function to\n% suit their need.\n\n%  Copyright (c) 2009, Aravind Seshadri\n%  All rights reserved.\n\n\n% g = sprintf('Input the number of objective: ');\n% Obtain the number of objective function\nnumber_of_objectives = input('Input the number of objective: '); % modified by zzb\nif number_of_objectives < 2\n    error('This is a multi-objective optimization function hence the minimum number of objectives is two');\nend\n% g = sprintf('\\nInput the number of decision variables: ');\n% Obtain the number of decision variables\nnumber_of_decision_variables = input('Input the number of decision variables: '); % modified by zzb\nmin_range_of_decesion_variable = input('Input the array of minimum value for decision variable: '); % modified by zzb\nwhile(length(min_range_of_decesion_variable) ~= number_of_decision_variables)\n    min_range_of_decesion_variable = input('The size is wrong. \\nInput the array of minimum value for decision variable: ');    \nend\nmax_range_of_decesion_variable = input('Input the array of maximum value for decision variable: '); % modified by zzb\nwhile(length(max_range_of_decesion_variable) ~= number_of_decision_variables)\n    max_range_of_decesion_variable = input('The size is wrong. \\nInput the array of maximum value for decision variable: ');    \nend\nclc;\n% for i = 1 : number_of_decision_variables\n%     clc\n%     g = sprintf('\\nInput the minimum value for decision variable %d : ', i);\n%     % Obtain the minimum possible value for each decision variable\n%     min_range_of_decesion_variable(i) = input(g);\n%     g = sprintf('\\nInput the maximum value for decision variable %d : ', i);\n%     % Obtain the maximum possible value for each decision variable\n%     max_range_of_decesion_variable(i) = input(g);\n%     clc\n% end\nopen('D:\\ProgramFiles\\MATLAB\\toolbox\\genetic\\NSGA-II\\evaluate_objective.m');  % modified by zzb\ng = sprintf('Now edit the function named \"evaluate_objective\" appropriately to match your needs.\\nMake sure that the number of objective functions and decision variables match your numerical input. \\nMake each objective function as a corresponding array element. \\nAfter editing do not forget to save. \\nPress \"c\" and enter to continue... ');\n% Prompt the user to edit the evaluate_objective function and wait until\n% 'c' is pressed.\nx = input(g, 's');\nif isempty(x)\n    x = 'x';\nend\nwhile x ~= 'c'\n    clc;\n    x = input(g, 's');\n    if isempty(x)\n        x = 'x';\n    end\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/\u7f8e\u8d5bA\u9898\u5e38\u89c1\u4ee3\u7801/\u591a\u76ee\u6807\u5feb\u901f\u975e\u652f\u914d\u6392\u5e8f\u9057\u4f20\u7b97\u6cd5\u4f18\u5316\u4ee3\u7801/objective_description_function.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.5827458917992948}}
{"text": "function treepack_test04 ( )\n\n%*****************************************************************************80\n%\n%% TREEPACK_TEST04 tests TREE_ARC_CENTER.\n%\n%  Discussion:\n%\n%    The tree is\n%\n%    2---3---6---8---1---9\n%       /       / \\\n%      7       5   4\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    28 June 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  nnode = 9;\n\n  inode = [ 2, 3, 3, 6, 8, 8, 8, 1 ];\n  jnode = [ 3, 7, 6, 8, 4, 5, 1, 9 ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TREEPACK_TEST04\\n' );\n  fprintf ( 1, '  TREE_ARC_CENTER computes the center of a tree.\\n' );\n\n  graph_arc_print ( nnode-1, inode, jnode, '  The edge list of the tree:' );\n\n  [ center, eccent, parity ] = tree_arc_center ( nnode, inode, jnode );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Parity = %d\\n', parity );\n  fprintf ( 1, '  Eccentricity is %d\\n', eccent );\n\n  if ( parity == 0 )\n    fprintf ( 1, '  No center node (degenerate case).\\n' );\n  elseif ( parity == 1 )\n    fprintf ( 1, '  Center node: %d\\n', center(1) );\n  else\n   fprintf ( 1, '  Center nodes: %d %d\\n', center(1), center(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/treepack/treepack_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.5827458899803458}}
{"text": "classdef ZDT3 < PROBLEM\n% <multi> <real> <large/none> <expensive/none>\n% Benchmark MOP proposed by Zitzler, Deb, and Thiele\n\n%------------------------------- Reference --------------------------------\n% E. Zitzler, K. Deb, and L. Thiele, Comparison of multiobjective\n% evolutionary algorithms: Empirical results, Evolutionary computation,\n% 2000, 8(2): 173-195.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            PopObj(:,1) = PopDec(:,1);\n            g = 1 + 9*mean(PopDec(:,2:end),2);\n            h = 1 - (PopObj(:,1)./g).^0.5 - PopObj(:,1)./g.*sin(10*pi*PopObj(:,1));\n            PopObj(:,2) = g.*h;\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - R(:,1).^0.5 - R(:,1).*sin(10*pi*R(:,1));\n            R      = R(NDSort(R,1)==1,:);\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R(:,1) = linspace(0,1,100)';\n            R(:,2) = 1 - R(:,1).^0.5 - R(:,1).*sin(10*pi*R(:,1));\n            R(NDSort(R,1)>1,:) = nan;\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/ZDT/ZDT3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5827458844886004}}
{"text": "%% Colormaps that are pretty awesome: DEMO1\n% this is an exampe of 4 colormaps that are being considered as the default\n% colormap in python's matplotlib lybrary.\n%\n% All of them look quite good and they don't have any official name, so at\n% the moment they are A,B,C,D.\n%\n% colormaps from https://github.com/bids/colormap\n%\n% Ander Biguri\n%% Clear workspace and get screen data\nclear;\nclc\nclose all;\n\nscreen=get(0,'ScreenSize') ;\nw0=screen(1);\nh0=screen(2);\nw =screen(3);\nh =screen(4);\n%% Generate sample data\nload flujet\nX=X.';\n\n%% Plot original with jet and parula\n% Parula\nh2=figure('name','Sample data with \"parula\" colormap');\nset(h2,'position',[w0,h0,w/3,h/2])\nimagesc(X)\n\nif verLessThan('matlab', '8.4')\n   % if parula is the \"future\"\n   colormap(parula());\nelse\n   % if parula is already in Matlab\n   colormap('parula');\nend\naxis image\nxlabel('Parula Colormap')\nset(gca,'xtick',[],'ytick',[]) % This is axis off without offing the labels\n\n% Jet\nh1=figure('name','Sample data with \"jet\" colormap');\nset(h1,'position',[w0,h/2,w/3,h/2])\nimagesc(X)\ncolormap('jet')\nxlabel('jet Colormap')\nset(gca,'xtick',[],'ytick',[]) % This is axis off without offing the labels\naxis image\n\n\n%% Load new colormaps\n\nm=100;\ncm_magma=magma(m);\ncm_inferno=inferno(m);\ncm_plasma=plasma(m);\ncm_viridis=viridis(m);\n\n\n%% Plot new colormaps\nh3=figure('name','Super-cool new colormaps that you can easily use');\nset(h3,'position',[w/3,h0,2*w/3,h])\nif verLessThan('matlab', '8.4')\n% If you are using old Matlab figure engine do  it this way\n% (some very lousy colormap problems before)\n    subplot(2,2,1,'Position',[0.05 0.55 0.4 0.4])\n    subimage(uint8(X/max(X(:))*255),cm_magma)\n    xlabel('MAGMA')\n    set(gca,'xtick',[],'ytick',[]) \n\n\n    subplot(2,2,2,'Position',[0.55 0.55 0.4 0.4])\n    subimage(uint8(X/max(X(:))*255),cm_inferno)\n    xlabel('INFERNO')\n    set(gca,'xtick',[],'ytick',[]) \n\n\n    subplot(2,2,3,'Position',[0.05 0.05 0.4 0.4])\n    subimage(uint8(X/max(X(:))*255),cm_plasma)\n    xlabel('PLASMA')\n    set(gca,'xtick',[],'ytick',[])\n    \n    subplot(2,2,4,'Position',[0.55 0.05 0.4 0.4])\n    subimage(uint8(X/max(X(:))*255),cm_viridis)\n    xlabel('VIRIDIS')\n    set(gca,'xtick',[],'ytick',[])\nelse\n    sp1=subplot(2,2,1,'Position',[0.05 0.55 0.4 0.4]);\n    imagesc(X)\n    colormap(sp1,cm_magma)\n    xlabel('MAGMA')\n    set(gca,'xtick',[],'ytick',[])\n    \n    sp2=subplot(2,2,2,'Position',[0.55 0.55 0.4 0.4]);\n    imagesc(X)\n    colormap(sp2,cm_inferno)\n    xlabel('INFERNO')\n    set(gca,'xtick',[],'ytick',[])\n\n    sp3=subplot(2,2,3,'Position',[0.05 0.05 0.4 0.4]);\n    imagesc(X)\n    colormap(sp3,cm_plasma)\n    xlabel('PLASMA')\n    set(gca,'xtick',[],'ytick',[])\n    \n    sp4=subplot(2,2,4,'Position',[0.55 0.05 0.4 0.4]);\n    imagesc(X)\n    colormap(sp4,cm_viridis)\n    xlabel('VIRIDIS')\n    set(gca,'xtick',[],'ytick',[])\nend\n", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Colormaps/demo1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.582745875393856}}
{"text": "% sample = samplep(p,n)\n% returns n samples, where the probability of i is p(i) for 1 <=i\n% <= length(p), 0 otherwise. \n\nfunction s = samplep(p,n)\n\n% normalize, just in case\np = p(:);\np = normalizep(p);\np(end) = 1;\nm = length(p);\n\n% compute the cumulative sum of probabilities\nc = cumsum(p);\n\n% choose n random numbers uniformly between 0 and 1\nr = rand(1,n);\n\n% find the first element of c >= r\ns = findfirstdim(repmat(c,[1,n])>=repmat(r,[m,1]),1);", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/samplep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5827458745018309}}
{"text": "classdef UF1 < PROBLEM\n% <multi> <real> <large/none>\n% Unconstrained benchmark MOP\n\n%------------------------------- Reference --------------------------------\n% Q. Zhang, A. Zhou, S. Zhao, P. N. Suganthan, W. Liu, and S. Tiwari,\n% Multiobjective optimization test instances for the CEC 2009 special\n% session and competition, School of CS & EE, University of Essex, Working\n% Report CES-487, 2009.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = [0,zeros(1,obj.D-1)-1];\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            J1 = 3 : 2 : obj.D;\n            J2 = 2 : 2 : obj.D;\n            Y  = X - sin(6*pi*repmat(X(:,1),1,obj.D)+repmat(1:obj.D,size(X,1),1)*pi/obj.D);\n            PopObj(:,1) = X(:,1)         + 2*mean(Y(:,J1).^2,2);\n            PopObj(:,2) = 1-sqrt(X(:,1)) + 2*mean(Y(:,J2).^2,2);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - R(:,1).^0.5;\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n        \tR = obj.GetOptimum(100);\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/UF/UF1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303137346446, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5827458735749073}}
{"text": "classdef IntersectionCoordComputer < TotalCoordinatesCalculator\n    \n    properties (Access = public)\n        c\n        theta\n        nodes\n        vertCoord\n        boundCoord\n        div\n        totalCoord\n    end\n    \n    properties (Access = private)\n        vA\n        vB\n    end\n    \n    methods (Access = public)\n        \n        function obj = IntersectionCoordComputer(cParams)\n            obj.init(cParams);\n            obj.initBoundary();\n            obj.obtainPrincipalVectors();\n            obj.computeIntersections();\n        end\n        \n    end\n    \n    methods (Access = private)\n        \n        function obtainPrincipalVectors(obj)\n            A = obj.vertCoord(1,:);\n            B = obj.vertCoord(2,:);\n            C = obj.vertCoord(3,:);\n            obj.vA = IntersectionCoordComputer.computeUnitaryVector(A,B);\n            obj.vB = IntersectionCoordComputer.computeUnitaryVector(B,C);\n        end\n        \n        function computeIntersections(obj)\n            nodesX = obj.div(1)-1;\n            nodesY = obj.div(2)-1;\n            intNode = obj.nodes.bound +1;\n            for jNodes = 1:nodesY\n                pB = obj.boundCoord(obj.nodes.bound+1-jNodes,:);\n                for iNodes = 1:nodesX\n                    pA = obj.boundCoord(obj.nodes.vert+iNodes,:);\n                    if obj.vA(1) == 0\n                        [x,y] = IntersectionCoordComputer.computeVerticalIntersection(pA,pB,obj.vB);\n                    elseif obj.vB(1) == 0\n                        [x,y] = IntersectionCoordComputer.computeVerticalIntersection(pB,pA,obj.vA);\n                    else\n                        [x,y] = IntersectionCoordComputer.computeGeneralIntersection(pA,pB,obj.vA,obj.vB);\n                    end\n                    obj.totalCoord(intNode,:) = [x y];\n                    intNode = intNode+1;\n                end\n            end\n        end\n        \n    end\n    \n    methods (Static)\n        \n        function v_norm = computeUnitaryVector(A,B)\n            v = B-A;\n            m = norm(v);\n            v_norm = v/m;\n        end\n        \n        function [x,y] = computeVerticalIntersection(p1,p2,v)\n            x = p2(1);\n            y = (x-p1(1))*v(2)/v(1)+p1(2);\n        end\n        \n        function [x,y] = computeGeneralIntersection(p1,p2,v1,v2)\n            x = (p2(2)-p1(2)+p1(1)*v2(2)/v2(1)-p2(1)*v1(2)/v1(1))/(v2(2)/v2(1)-v1(2)/v1(1));\n            y = (x-p2(1))*v1(2)/v1(1)+p2(2);\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/ShapesInMicrostructures/SourceCode/IntersectionCoordComputer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5827059294723549}}
{"text": "\n% Copyright (c) Roman Garnett, 2012--2014.\n\nfunction pdfs = evaluate_pdfs(mus, Ks, x, weights)\n\n  persistent individual_pdfs;\n\n  % reset if no arguments given\n  if (nargin == 0)\n    individual_pdfs = [];\n    return;\n  end\n\n  % precompute N(x; mu, K) for every x\n  if (isempty(individual_pdfs))\n    num_points = size(x, 1);\n    num_nodes  = size(mus, 1);\n\n    individual_pdfs = zeros(num_nodes, num_points);\n    for i = 1:num_nodes\n        individual_pdfs(i, :) = mvnpdf(x, mus(i, :), Ks(:, :, i))';\n    end\n  end\n\n  pdfs = weights * individual_pdfs;\n\nend", "meta": {"author": "muhanzhang", "repo": "DGCNN", "sha": "7d3663b49561e57fe518f37af0023a364285eee1", "save_path": "github-repos/MATLAB/muhanzhang-DGCNN", "path": "github-repos/MATLAB/muhanzhang-DGCNN/DGCNN-7d3663b49561e57fe518f37af0023a364285eee1/software/propagation_kernels-master/transformations/evaluate_pdfs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5827059068827108}}
{"text": "function r8mat_house_form_test ( )\n\n%*****************************************************************************80\n%\n%% R8MAT_HOUSE_FORM_TEST tests R8MAT_HOUSE_FORM.\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\n  v = [ 0.0, 0.0, 1.0, 2.0, 3.0 ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8MAT_HOUSE_FORM_TEST\\n' );\n  fprintf ( 1, '  R8MAT_HOUSE_FORM forms a Householder\\n' );\n  fprintf ( 1, '  matrix from its compact form.\\n' );\n\n  r8vec_print ( n, v, '  Compact vector form V:' );\n\n  h = r8mat_house_form ( n, v );\n \n  r8mat_print ( n, n, h, '  Householder matrix 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/r8lib/r8mat_house_form_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.5827059027924103}}
{"text": "function [perimeterEdges,eulerCondition] = findLegalPerimeters2(mesh,perimDist)\n% Calculate edges that on distinct perimeters perimDist mm from startVertex\n% \n%  [perimeterEdges,eulerCondition] = findLegalPerimeters2(mesh,perimDist)\n%\n% Given a mesh structure (nodes, edges, distances from start point) and a\n% threshold distance return a list of edges that constitute separate\n% perimeters at a distance of perimDist from the start point.\n%\n% Note that because of intrinsic curvature, there can be more than one\n% perimeter at the required distance. This routine makes sure that it\n% returns separate perimeters (ones with no common nodes).\n%\n\n% Find perims with simple threshold\ninsideNodes = find(mesh.dist<=perimDist);\ninsideNodes = insideNodes(:);  \n\n% Some triangles have one or two vertices outside the perimeter.  These\n% triangles will not be included; any nodes that are within the perimeter\n% but only part of these excluded triangles are removed here.\ninsideNodes = removeHangingNodes2(mesh,insideNodes); \n\n% We could write a short piece of code that verifies these new nodes have\n% no hanging nodes ...\n\nnumBadNodes = 1; \n\nwhile (numBadNodes>0)\n    \n    [perimeterEdges,eulerCondition] = findGroupPerimeter2(mesh,insideNodes);\n\n    length(perimeterEdges);\n    length(unique(perimeterEdges,'rows'));\n    fprintf('Euler number=%d\\n',eulerCondition);\n\n    badPerimNodes = findBadPerimNodes2(mesh,perimeterEdges);\n    numBadNodes   = length(badPerimNodes);\n    fprintf('There are %d bad perim nodes.\\n',numBadNodes);\n\n    if(numBadNodes)\n        % Splits up joined perimeters\n        [insideNodes] = correctBadNodes2(mesh,insideNodes,badPerimNodes);\n        \n        % Cleans up mesh again\n        insideNodes = removeHangingNodes2(mesh,insideNodes);\n    end\nend\n\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/mrAnatomy/mrFlatMesh/mrFlatMeshNifti/findLegalPerimeters2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5827059022261886}}
{"text": "classdef TP8 < PROBLEM\n% <multi> <real> <large/none> <robust>\n% Test problem for robust multi-objective optimization\n% delta --- 0.05 --- Maximum disturbance degree\n% H     ---   50 --- Number of disturbances\n\n%------------------------------- Reference --------------------------------\n% A. Gaspar-Cunha, J. Ferreira, and G. Recio, Evolutionary robustness\n% analysis for multi-objective optimization: benchmark problems, Structural\n% and Multidisciplinary Optimization, 2014, 49: 771-793.\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        delta;      % Maximum disturbance degree\n        H;          % Number of disturbances\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            [obj.delta,obj.H] = obj.ParameterSet(0.05,50);\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 5; end\n            obj.lower    = [0,0,-ones(1,obj.D-2)];\n            obj.upper    = [1,1, ones(1,obj.D-2)];\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(~,PopDec)\n            PopObj(:,1) = PopDec(:,1);\n            h = 2 - 0.8*exp(-((PopDec(:,2)-0.35)/0.25).^2) - exp(-((PopDec(:,2)-0.85)/0.03).^2);\n            g = 50*sum(PopDec(:,3:end).^2,2);\n            S = 1 - sqrt(PopObj(:,1));\n            PopObj(:,2) = h.*(g+S);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - sqrt(R(:,1));\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R = obj.GetOptimum(100);\n        end\n        %% Calculate the metric value\n        function score = CalMetric(obj,metName,Population)\n            switch metName\n                case {'Mean_IGD','Mean_HV','Worst_IGD','Worst_HV'}\n                    score = feval(metName,Population,obj);\n                otherwise\n                    score = feval(metName,Population,obj.optimum);\n            end\n        end\n        %% Perturb solutions multiple times\n        function PopX = Perturb(obj,PopDec,N)\n            if nargin < 3; N = obj.H; end\n            Delta = repmat(obj.delta.*(obj.upper-obj.lower),N*size(PopDec,1),1);\n            w     = UniformPoint(N,obj.D,'Latin');\n            Dec   = 2*Delta.*w(reshape(repmat(1:end,size(PopDec,1),1),1,[]),:) + repmat(PopDec,N,1) - Delta;\n            Dec   = obj.CalDec(Dec);\n            PopX  = SOLUTION(Dec,obj.CalObj(Dec),obj.CalCon(Dec));\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/TP/TP8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5827058912144772}}
{"text": "function suborder_num = dunavant_suborder_num ( rule )\n\n%*****************************************************************************80\n%\n%% DUNAVANT_SUBORDER_NUM returns the number of suborders for a Dunavant rule.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    11 December 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    David Dunavant,\n%    High Degree Efficient Symmetrical Gaussian Quadrature Rules\n%    for the Triangle, \n%    International Journal for Numerical Methods in Engineering,\n%    Volume 21, 1985, pages 1129-1148.\n%\n%    James Lyness, Dennis Jespersen,\n%    Moderate Degree Symmetric Quadrature Rules for the Triangle,\n%    Journal of the Institute of Mathematics and its Applications,\n%    Volume 15, Number 1, February 1975, pages 19-32.\n%\n%  Parameters:\n%\n%    Input, integer RULE, the index of the rule.\n%\n%    Output, integer SUBORDER_NUM, the number of suborders of the rule.\n%\n  suborder = [ ...\n     1,  1 , 2,  2,  3,  3,  4,  5,  6,  6, ...\n     7,  8, 10, 10, 11, 13, 15, 17, 17, 19 ];\n\n  if ( 1 <= rule & rule <= 20 )\n    suborder_num = suborder(rule);\n  else\n\n    suborder_num = -1;\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'DUNAVANT_SUBORDER_NUM - Fatal error!\\n' );\n    fprintf ( 1, '  Illegal RULE = %d\\n', rule );\n    error ( 'DUNAVANT_SUBORDER_NUM - 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/triangle_dunavant_rule/dunavant_suborder_num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.582676232546903}}
{"text": "function x = blend_rst_2dn ( r, s, t, n, bound_rst )\n\n%*****************************************************************************80\n%\n%% BLEND_RST_2DN extends vector data on faces into a cube.\n%\n%  Diagram:\n%\n%    010-----r10-----110        011-----r11-----111\n%      |       .       |          |       .       |\n%      |       .       |          |       .       |\n%    0s0.....rs0.....1s0        0s1.....rs1.....1s1     S\n%      |       .       |          |       .       |     |\n%      |       .       |          |       .       |     |\n%    000-----r00-----100        001-----r01-----101     +----R\n%           BOTTOM                      TOP\n%\n%    011-----0s1-----001        111-----1s1-----101\n%      |       .       |          |       .       |\n%      |       .       |          |       .       |\n%    01t.....0st.....00t        11t.....1st.....10t          T\n%      |       .       |          |       .       |          |\n%      |       .       |          |       .       |          |\n%    010-----0s0-----000        110-----1s0-----100     S----+\n%           LEFT                       RIGHT\n%\n%    001-----r01-----101        011-----r11-----111\n%      |       .       |          |       .       |\n%      |       .       |          |       .       |\n%    00t.....r0t.....100        01t.....r1t.....11t     T\n%      |       .       |          |       .       |     |\n%      |       .       |          |       .       |     |\n%    000-----r00-----100        010-----r10-----110     +----R\n%           FRONT                       BACK\n%\n%  Discussion:\n%\n%    BLEND_RST_2DN is NOT equivalent to a trilinear finite element\n%    method, since the data is sampled everywhere along the corners,\n%    edges, and faces, rather than at a finite number of nodes.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 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 R, S, T, the (R,S,T) coordinates of the point\n%    to be evaluated.\n%\n%    Input, integer N, the dimension of the vector space.\n%\n%    External, BOUND_RST, is a function which is given (R,S,T)\n%    coordinates and an component value I, and returns XI, the value\n%    of the I-th component of the N-vector at that point.  BOUND_RST\n%    will only be called for \"faces\", that is, for values (R,S,T) where\n%    at least one of R, S and T is either 0.0 or 1.0.  BOUND_RST has\n%    the form:\n%      function xi = bound_rst ( r, s, t, i )\n%\n%    Output, real X(N), the interpolated value at the\n%    point (R,S,T).\n%\n  for i = 1 : n\n%\n%  Get the I-th coordinate component at the corners.\n%\n    x000 = bound_rst ( 0.0, 0.0, 0.0, i );\n    x001 = bound_rst ( 0.0, 0.0, 1.0, i );\n    x010 = bound_rst ( 0.0, 1.0, 0.0, i );\n    x011 = bound_rst ( 0.0, 1.0, 1.0, i );\n    x100 = bound_rst ( 1.0, 0.0, 0.0, i );\n    x101 = bound_rst ( 1.0, 0.0, 1.0, i );\n    x110 = bound_rst ( 1.0, 1.0, 0.0, i );\n    x111 = bound_rst ( 1.0, 1.0, 1.0, i );\n%\n%  Get the I-th coordinate component at the edges.\n%\n    xr00 = bound_rst ( r, 0.0, 0.0, i );\n    xr01 = bound_rst ( r, 0.0, 1.0, i );\n    xr10 = bound_rst ( r, 1.0, 0.0, i );\n    xr11 = bound_rst ( r, 1.0, 1.0, i );\n\n    x0s0 = bound_rst ( 0.0, s, 0.0, i );\n    x0s1 = bound_rst ( 0.0, s, 1.0, i );\n    x1s0 = bound_rst ( 1.0, s, 0.0, i );\n    x1s1 = bound_rst ( 1.0, s, 1.0, i );\n\n    x00t = bound_rst ( 0.0, 0.0, t, i );\n    x01t = bound_rst ( 0.0, 1.0, t, i );\n    x10t = bound_rst ( 1.0, 0.0, t, i );\n    x11t = bound_rst ( 1.0, 1.0, t, i );\n%\n%  Get the I-th component on the faces.\n%\n    x0st = bound_rst ( 0.0, s, t, i );\n    x1st = bound_rst ( 1.0, s, t, i );\n    xr0t = bound_rst ( r, 0.0, t, i );\n    xr1t = bound_rst ( r, 1.0, t, i );\n    xrs0 = bound_rst ( r, s, 0.0, i );\n    xrs1 = bound_rst ( r, s, 1.0, i );\n%\n%  Interpolate the I-th coordinate component of the interior point.\n%\n    x(i) = blend_123 ( r, s, t, x000, x001, x010, x011, x100, x101, x110, x111, ...\n      xr00, xr01, xr10, xr11, x0s0, x0s1, x1s0, x1s1, x00t, x01t, x10t, x11t, ...\n      x0st, x1st, xr0t, xr1t, xrs0, xrs1 );\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_rst_2dn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.5826762285849413}}
{"text": "function brnd = betarand(a,b,r,c)\n%  BETARAND Random matrices from beta distribution.\n%     R = BETARAND(A,B) returns an array of random numbers chosen from the\n%     beta distribution with parameters A and B.  The size of R is the common\n%     size of A and B if both are arrays.  If either parameter is a scalar,\n%     the size of R is the size of the other parameter.\n%\n%     R = BETARAND(A,B,M,N) returns an M-by-N matrix.\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 > 1)\n  if (~isscalar(a) || ~isscalar(b))\n    if (size(a,1) ~= size(b,1))\n      error ('betarnd: a and b must be of common size or scalar');\n    end\n  end\nend\n\nif (nargin == 4)\n  if (~(isscalar(r) && (r > 0) && (r == round(r))))\n    error ('betarnd: r must be a positive integer');\n  end\n  if (~(isscalar (c) && (c > 0) && (c == round (c))))\n    error ('betarnd: c must be a positive integer');\n  end\n  sz = [r, c];\n  \n  if (any (size (a) ~= 1) && (length (size (a)) ~= length (sz) || any (size (a) ~= sz)))\n    error ('betarnd: a and b must be scalar or of size [r,c]');\n  end\nelseif (nargin == 3)\n  if (isscalar (r) && (r > 0))\n    sz = [r, r];\n  elseif (isvector(r) && all (r > 0))\n    sz = r(:)';\n  else\n    error ('betarnd: r must be a positive integer or vector');\n  end\n  \n  if (any (size (a) ~= 1) && (length (size (a)) ~= length (sz) || any (size (a) ~= sz)))\n    error ('betarnd: a and b must be scalar or of size sz');\n  end\nelseif (nargin == 2)\n  sz = size(a);\nelse\n  error('must provide atleast 2 parameters')\nend\n\nif (isscalar(a) && isscalar(b))\n  if (find ((a < 0) | isinf(a) | (b < 0) | isinf(b)))\n    brnd = NaN * ones (sz);\n  else\n    r1 = gamrand(a,2.*a,sz(1),sz(2));\n    brnd = r1 ./ (r1 + gamrand(b,2.*b,sz(1),sz(2)));\n  end\nelse\n  brnd = zeros (sz);\n  \n  k = find ((a < 0) | isinf(a) | (b < 0) | isinf(b));\n  if (any (k))\n    brnd(k) = NaN * ones (size (k));\n  end\n  \n  k = find ((a > 0) & (a < Inf) & (b > 0) & (b < Inf));\n  if (any (k))\n    r1 = gamrnd(a(k),1,size(k,1),size(k,2));\n    brnd(k) = r1 ./ (r1 + gamrnd(b(k),1,size(k,1),size(k,2)));\n  end\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/betarand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5826762240350494}}
{"text": "% LFBuild4DFreqHyperfan - construct a 4D hyperfan passband filter in the frequency domain\n% \n% Usage: \n% \n%     [H, FiltOptions] = LFBuild4DFreqHyperfan( LFSize, Slope1, Slope2, BW, FiltOptions )\n%     H = LFBuild4DFreqHyperfan( LFSize, Slope1, Slope2, BW )\n% \n% This file constructs a real-valued magnitude response in 4D, for which the passband is a hyperfan.\n% This is useful for selecting objects over a range of depths from a lightfield, i.e. volumetric\n% focus.\n%\n% Once constructed the filter must be applied to a light field, e.g. using LFFilt4DFFT. The \n% LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters.\n% \n% A more technical discussion, including the use of filters for denoising and volumetric focus, and\n% the inclusion of aliases components, is included in:\n% \n% [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, \"Linear Volumetric Focus for Light Field\n% Cameras,\" to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015.\n% \n% Inputs:\n% \n%     LFSize : Size of the frequency-domain filter. This should match or exceed the size of the\n%     light field to be filtered. If it's larger than the input light field, the input is\n%     zero-padded to match the filter's size by LFFilt4DFFT.\n% \n%     Slope : The slope of the planar passband. If different slopes are desired in s,t and u,v,\n%     the optional aspect parameter should be used.\n% \n%     BW : 3-db Bandwidth of the planar passband.\n% \n%     [optional] FiltOptions : struct controlling filter construction\n%            HyperfanMethod : 'sweep' or 'direct', controls how the hyperfan is constructed. 'sweep'\n%                             concatenates frequency planes, while 'direct' evaluates a single 4D \n%                             equation; default 'direct'. Warning: sweep can be very slow.\n%               HyperconeBW : Sets the underlying hypercone's BW separately from the dual-fan,\n%                             default is to use the BW parameter for both; only applies when\n%                             HyperfanMethod is 'direct'\n%               SlopeMethod : 'Skew' or 'Rotate' default 'skew'\n%                 Precision : 'single' or 'double', default 'single'\n%                   Rolloff : 'Gaussian' or 'Butter', default 'Gaussian'\n%                     Order : controls the order of the filter when Rolloff is 'Butter', default 3\n%                  Aspect4D : aspect ratio of the light field, default [1 1 1 1]\n%                    Window : Default false. By default the edges of the passband are sharp; this adds \n%                             a smooth rolloff at the edges when used in conjunction with Extent4D or\n%                             IncludeAliased.\n%                  Extent4D : controls where the edge of the passband occurs, the default [1 1 1 1]\n%                             is the edge of the Nyquist box. When less than 1, enabling windowing\n%                             introduces a rolloff after the edge of the passband. Can be greater\n%                             than 1 when using IncludeAliased.\n%            IncludeAliased : default false; allows the passband to wrap around off the edge of the\n%                             Nyquist box; used in conjunction with Window and/or Extent4D. This can \n%                             increase processing time dramatically, e.g. Extent4D = [2,2,2,2] \n%                             requires a 2^4 = 16-fold increase in time to construct the filter. \n%                             Useful when passband content is aliased, see [2].\n%                SweepSteps : For HyperfanMethod 'sweep', how many steps to use in the sweep.\n% \n% Outputs:\n% \n%                 H : real-valued frequency magnitude response\n%       FiltOptions : The filter options including defaults, with an added PassbandInfo field\n%                     detailing the function and time of construction of the filter\n%\n% User guide: <a href=\"matlab:which LFToolbox.pdf; open('LFToolbox.pdf')\">LFToolbox.pdf</a>\n% See also:  LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01,\n% LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone,\n% LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum\n\n% Copyright (c) 2013-2020 Donald G. Dansereau\n\nfunction [H, FiltOptions] = LFBuild4DFreqHyperfan( LFSize, Slope1, Slope2, BW, FiltOptions )\n\nFiltOptions = LFDefaultField('FiltOptions', 'HyperfanMethod', 'Direct'); % 'Direct', 'Sweep'\n\nswitch( lower(FiltOptions.HyperfanMethod ))\n\tcase 'sweep'\n\t\tFiltOptions = LFDefaultField('FiltOptions', 'SweepSteps', 5);\n\t\tSweepVec = linspace(Slope1, Slope2, FiltOptions.SweepSteps);\n\t\t[H, FiltOptions] = LFBuild4DFreqPlane( LFSize, SweepVec(1), BW, FiltOptions );\n\t\tfor( CurSlope = SweepVec(2:end) )\n\t\t\tH = max(H, LFBuild4DFreqPlane( LFSize, CurSlope, BW, FiltOptions ));\n\t\tend\n\t\t\n\tcase 'direct'\n\t\tFiltOptions = LFDefaultField('FiltOptions', 'HyperconeBW', BW);\n\t\t[H, FiltOptions] = LFBuild4DFreqHypercone( LFSize, FiltOptions.HyperconeBW, FiltOptions );\n\t\t[Hdf, FiltOptions] = LFBuild4DFreqDualFan( LFSize, Slope1, Slope2, BW, FiltOptions );\n\t\tH = H .* Hdf;\n\t\t\n\totherwise\n\t\terror('Unrecognized hyperfan construction method');\nend\n\t\nTimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');\nFiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);\n\n", "meta": {"author": "doda42", "repo": "LFToolbox", "sha": "5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e", "save_path": "github-repos/MATLAB/doda42-LFToolbox", "path": "github-repos/MATLAB/doda42-LFToolbox/LFToolbox-5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e/LFBuild4DFreqHyperfan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5825778270038106}}
{"text": "function [path, j1, j2] = hmmViterbiCM(logpi, logA, logB)\n% Find the most-probable (Viterbi) path through the HMM state trellis. \n% logpi(j) = log of initial state distribution\n% logA(i,j) = log of transition matrix\n% logB(k,t) = log of soft evidence\n% * we use log of inputs for compatability with .mex version *\n% * called hmmViterbiC since Matlab has an hmmViterbi function already *\n%%\n\n% This file is from pmtk3.googlecode.com\n\n\npi = exp(logpi);\nA = exp(logA);\nB = exp(logB); \n\n[K T] = size(B);\ndelta = zeros(K,T);\npsi = zeros(K,T);\npath = zeros(1,T);\nt=1;\ndelta(:,t) = normalize(pi(:) .* B(:,t));\npsi(:,t) = 0; % arbitrary value, since there is no predecessor to t=1\nfor t=2:T\n    for j=1:K\n        [delta(j,t), psi(j,t)] = max(delta(:,t-1) .* A(:,j));\n        delta(j,t) = delta(j,t) * B(j,t);\n    end\n    delta(:,t) = normalize(delta(:,t));\nend\n\n% Traceback\n[p, path(T)] = max(delta(:,T));\nfor t=T-1:-1:1\n    path(t) = psi(path(t+1),t+1);\nend\n\nj1 = []; % for .mex compatability \nj2 = [];\nend\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools_addins/hmmViterbiCM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5825778208024112}}
{"text": "function [ x, status ] = p00_newton ( problem, option, nvar, x, par_index )\n\n%*****************************************************************************80\n%\n%% P00_NEWTON applies Newton's method to an approximate root.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    29 September 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer PROBLEM, the problem index.\n%\n%    Input, integer OPTION, the option index.\n%\n%    Input, integer NVAR, the number of variables.\n%\n%    Input, real X(NVAR), the starting point of Newton's method.\n%\n%    Input, integer PAR_INDEX, the index of the parameter to be held fixed.\n%    This variable should be between 1 and NVAR.  However, the user can\n%    set it to 0, indicating that the program should make an intelligent\n%    choice for the index.\n%\n%    Output, real X(NVAR), an improved estimate of the root of F(X)=0.\n%\n%    Output, integer STATUS, the status of the iteration.\n%    -3, the full number of steps was taken without convergence.\n%        (however, the output X might be CLOSE to a good solution).\n%    -2, the iteration seemed to be diverging, and was halted.\n%    -1, the jacobian was singular, and the iteration was halted.\n%     nonnegative, the convergence test was satisfied, and this is the\n%        number of steps taken (possibly 0).\n%\n  COND_MAX = 1.0E+10;\n  FX_ABS_TOL = 0.000001;\n  IT_MAX = 20;\n  VERBOSE = 0;\n\n  x = x(:);\n\n  if ( par_index < 1 | nvar < par_index )\n    par_index = p00_par_index ( problem, option, nvar, x );\n    if ( VERBOSE )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, '  Iteration will hold index %d fixed.\\n', par_index );\n    end\n  end\n  par_value = x(par_index);\n\n  if ( VERBOSE )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'P00_NEWTON\\n' );\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '      Step    ||F(X)||\\n' );\n    fprintf ( 1, '\\n' );\n  end\n\n  for it = 0 : IT_MAX\n%\n%  Compute the function value.\n%\n    fx = p00_fun ( problem, option, nvar, x );\n    fx(nvar) = x(par_index) - par_value;\n%\n%  Compute the norm of the function value.\n%\n    fx_max = max ( abs ( fx(1:nvar) ) );\n\n    if ( VERBOSE )\n      fprintf ( 1, '  %8d  %14e\\n', it, fx_max );\n    end\n\n    if ( it == 0 )\n      fx_max_init = fx_max;\n    end\n%\n%  If the function norm is small enough, return.\n%\n    if ( abs ( fx_max ) < FX_ABS_TOL )\n      status = it;\n      break\n    end\n%\n%  If the function norm seems to be exploding, halt.\n%\n    if ( 1000.0 * fx_max_init < abs ( fx_max ) )\n      status = -2;\n      break\n    end\n\n    if ( it == IT_MAX )\n      status = -3;\n      break\n    end\n%\n%  Compute the jacobian.\n%\n    jac = p00_jac ( problem, option, nvar, x );\n\n    jac(nvar,1:nvar) = 0.0;\n    jac(nvar,par_index) = 1.0;\n%\n%  Solve the system JAC * DX = - FX\n%\n    if ( cond ( jac ) < COND_MAX )\n      dx = - jac \\ fx;\n    else\n      if ( VERBOSE )\n        fprintf ( 1, '  (Using pseudoinverse.)\\n' );\n      end\n      dx = - pinv ( jac ) * fx;\n    end\n%\n%  Update X = X - DX.\n%\n    x(1:nvar) = x(1:nvar) + dx(1:nvar);\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_con/p00_newton.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5824964400124387}}
{"text": "function iOut = iVals(trialOrder,ignoreNulls);\n% iOut = iVals(trialOrder,ignoreNulls);\n% iVals: Calculate i-value (intervening trials) for fMR-A Expts (but maybe more generally useful).\n% \n% Here's the idea: trialOrder is an array of numbers, generally with values that are repeated. \n% The i-value of each element counts the number of intervening entries between repeated values.\n% If the value for a given element in trialOrder has not occurred before in trialOrder, i = -1. \n% If the value has occurred immediately before the current element, i = 0;\n% If the value last occurred two elements before, i = 1 (one element between repetitions), and so on.\n%\n% So if trialOrder is:\n%\n% 1 1 2 1 3 3 1 1 1 2\n%\n% nOut will be:\n%\n% -1 0 -1 1 -1 -1 2 0 0 6\n%\n% If ignoreNulls is set to 1, iOut will ignore intervening elements with a value of 0 in counting\n% (e.g., 1 0 0 1 will have an iOut of -1 -1 -1 0 instead of -1 -1 0 2).\n%\n% 1/03 by ras.\n% 10/03 ras: updated to work with matrices. If a matrix is passed, it will run through eac\n% row and get the ivals.\nif ~exist('ignoreNulls','var')\tignoreNulls = 0;\t\tend\n\nif size(trialOrder,1) > 1 & size(trialOrder,2) > 1\n\tiOut = [];\n\tfor i = 1:size(trialOrder,1)\n\t\tiOut = [iOut; iVals(trialOrder(i,:))];\n\tend\n\treturn\nend\n\n\nif ignoreNulls\n\tnonNulls = find(trialOrder~=0);\n\tnulls = find(trialOrder==0);\n\tfullOrder = trialOrder;\n\ttrialOrder = trialOrder(nonNulls);\nend\n\nfor i = 1:length(trialOrder)\n\tcurrVal = trialOrder(i);\n\tind = find(trialOrder==currVal);\n\tif ind(1)==i\n\t\tiOut(i) = -1;\n\telse\n\t\tloc = find(ind==i);\n\t\tlastInstance = ind(loc-1);\n\t\tiOut(i) = i - lastInstance - 1;\n\tend\nend\n\nif ignoreNulls\n\ttmp = iOut;\n\tiOut = zeros(1,length(fullOrder));\n\tiOut(nonNulls) = tmp;\n\tiOut(nulls) = -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/mrBOLD/Utilities/iVals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7520125626441471, "lm_q1q2_score": 0.582496427881089}}
{"text": "function Ainv = incremental_invert(Pinv,Q,S)  \n%\n%   Computes the new inverse of a symmetric matrix from an old submatrix inverse and the new parts. \n%\n%   So if   A = [P,Q;Q',S] incremental_invert gets inv(P) , Q and S and\n%   returns inv(A)\n%                           \n%\n\nif isempty(S) && isempty(Q)\n    Ainv = Pinv; return\nend\n\nQt = Q';\nM = S-Qt*Pinv*Q;\nMinv = pinv(M);\n\nPtmp = Pinv + Pinv*Q*Minv*Qt*Pinv;\nQtmp = -Pinv*Q*Minv;\n\nAinv = [Ptmp,Qtmp;Qtmp',Minv];", "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/incremental_invert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.58244921369084}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\nclear; clc;\n%% Parameters\nS = 100;                                   % Spot prices\nT = 5;      % maturities\n\nr = 0;                      % discount factors\nd = 0;                              % dividends\n\ntitS = 'MC NIG CIR - Asset Paths';\n\nlegend_base = 'Base scenario';\n\nalpha = 10;\nbeta = -3;                            % CEV exponent base scenario\ndelta = 1;\nmu = 0;\nlambda = 2;\nkappa = 1;\neta = 0.5;\n\n\n%% Simulation parameters\nNTime = 120; NSim = 1; NBatches = 1;\nNTime_clock = 10;\nK = ones(NTime+1,1);\nK = T*cumsum(K)/(NTime+1);\nK1 = K(2:end);\n\nrstream = RandStream('mt19937ar','Seed',12345);\nrstreamstate = rstream.State;\n\nPathS = MC_NIGCIR(S,r,d,T,alpha,beta,delta,kappa,eta,lambda,NTime,NSim,NBatches);\n%% Changing lambda\nlambda_low = 1;\nlambda_high = 3;\n\n    rstream.State = rstreamstate;\n    PathS_low = MC_NIGCIR(S,r,d,T,alpha,beta,delta,kappa,eta,lambda_low,NTime,NSim,NBatches);\n    rstream.State = rstreamstate;\n    PathS_high = MC_NIGCIR(S,r,d,T,alpha,beta,delta,kappa,eta,lambda_high,NTime,NSim,NBatches);\n    \nlegend_low = 'Changing \\lambda low';\nlegend_high = 'Changing \\lambda high';\n\ncreatefigure_path(K,PathS_low, PathS, PathS_high, titS, legend_low, legend_base, legend_high);\n\n% calculate the returns\nReturnsS1_low = calcreturns(PathS_low,0);\nReturnsS1 = calcreturns(PathS,0);\nReturnsS1_high = calcreturns(PathS_high,0);\n\ncreatefigure_returns(K1,ReturnsS1_low, ReturnsS1, ReturnsS1_high, titS, legend_low, legend_base, legend_high);\n\n%% Changing kappa\nkappa_low = 0.5;\nkappa_high = 2;\n\n    rstream.State = rstreamstate;\n    PathS_low = MC_NIGCIR(S,r,d,T,alpha,beta,delta,kappa_low,eta,lambda,NTime,NSim,NBatches);\n    rstream.State = rstreamstate;\n    PathS_high = MC_NIGCIR(S,r,d,T,alpha,beta,delta,kappa_high,eta,lambda,NTime,NSim,NBatches);\n    \nlegend_low = 'Changing \\kappa low';\nlegend_high = 'Changing \\kappa high';\n\ncreatefigure_path(K,PathS_low, PathS, PathS_high, titS, legend_low, legend_base, legend_high);\n\n% calculate the returns\nReturnsS1_low = calcreturns(PathS_low,0);\nReturnsS1 = calcreturns(PathS,0);\nReturnsS1_high = calcreturns(PathS_high,0);\n\ncreatefigure_returns(K1,ReturnsS1_low, ReturnsS1, ReturnsS1_high, titS, legend_low, legend_base, legend_high);\n\n%% Changing eta\neta_low = 0.25;\neta_high = 0.75;\n\n    rstream.State = rstreamstate;\n    PathS_low = MC_NIGCIR(S,r,d,T,alpha,beta,delta,kappa,eta_low,lambda,NTime,NSim,NBatches);\n    rstream.State = rstreamstate;\n    PathS_high = MC_NIGCIR(S,r,d,T,alpha,beta,delta,kappa,eta_high,lambda,NTime,NSim,NBatches);\n    \nlegend_low = 'Changing \\eta low';\nlegend_high = 'Changing \\eta high';\n\ncreatefigure_path(K,PathS_low, PathS, PathS_high, titS, legend_low, legend_base, legend_high);\n\n\n% calculate the returns\nReturnsS1_low = calcreturns(PathS_low,0);\nReturnsS1 = calcreturns(PathS,0);\nReturnsS1_high = calcreturns(PathS_high,0);\n\ncreatefigure_returns(K1,ReturnsS1_low, ReturnsS1, ReturnsS1_high, titS, legend_low, legend_base, legend_high);\n\nclear; clc;", "meta": {"author": "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/TestScriptPathNIGCIR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.582405608836177}}
{"text": "% Create some data.  First pick out the test dimensions, and the locations\n% of some files.\nD = 4;\nPythonCmd = 'python2.6';\nLSHCmd = 'lsh.py';\ntmpFile = '/tmp/lshtest.out';\ntmpFile2 = '/tmp/lshtest.out2';\nsubPlots = 1;\n\n%%\n% Now run the python command to create the data.\ncmd = sprintf('%s %s -d %d -create', PythonCmd, LSHCmd, D);\nfprintf('Running the command: %s\\n', cmd);\nsystem(cmd);\n%%\n% Now run the python command to measure the distance data\ncmd = sprintf('%s %s -d %d -histogram', PythonCmd, LSHCmd, D);\nfprintf('Running the command: %s\\n', cmd);\nsystem(cmd);\n%%\n% Load in the distance data and calculate the distance histograms.\ntestData = load(sprintf('testData%03d.distances', D));\nnBins = 40;\n[dnnHist, dnnBins] = hist(testData(:,1), nBins);\n[danyHist, danyBins] = hist(testData(:,2), nBins);\nif subPlots\n    subplot(2,2,1);\nend\nplot(dnnBins, dnnHist, danyBins, danyHist);\nlegend('Nearest Neighbor', 'Any Neighbor');\nxlabel('Distance')\nylabel('Frequency of Occurance');\ntitle(sprintf('Distance Histogram for %d-D data', D));\n%%\n% Now calculate the optimum LSH parameters.\nN=100000;\ndeltaTarget = 0.5;\nr = 0;\nuHash = 1;\nuCheck = 1;\nresults = CalculateMPLSHParameters(N, ... \n    dnnHist, dnnBins, danyHist, danyBins, deltaTarget, r, uHash, uCheck);\n%%\n% Now let's run the W test.\nw = results.exactW;\ncmd = sprintf('%s %s -d %d -w %g -wTest > %s', PythonCmd, LSHCmd, ...\n    D, w, tmpFile);\nfprintf('Running the command: %s\\n', cmd);\nsystem(cmd);\n\n%%\n% And load the W-test results.\ncmd = sprintf('egrep -v \"[a-zA-Z]\" %s | tail -20 > %s', tmpFile, tmpFile2);\n[s,res] = system(cmd);\nwTest = load(tmpFile2);\n\n\n%%\n% And now create the w-test plot.\nif subPlots\n    subplot(2,2,2);\nend\n\nsemilogx(results.wList/results.dScale, results.binNnProb, ...\n    wTest(:,1), wTest(:,2), 'bx', ...\n    results.wList/results.dScale, results.binAnyProb, ...\n    wTest(:,1), wTest(:,3), 'gx', ...\n    [results.exactW, results.exactW], [0 1], 'r--');\n\nxlabel('W');\nylabel('Probability of Collision');\nlegend('p_{nn}', 'p_{nn} experimental', ...\n    'p_{any}', 'p_{any} experimental', ...\n    'Optimum W', ...\n    'Location', 'SouthEast');\ntitle(sprintf('wTest for %d-D data', D));\n\n%%\n% Now let's run the K test\ncmd = sprintf('%s %s -d %d -w %g -kTest > %s', PythonCmd, LSHCmd, ...\n    D, w, tmpFile);\nfprintf('Running the command: %s\\n', cmd);\nsystem(cmd);\n\n%%\n% And grab the K-test results.\ncmd = sprintf('grep \" 10 \" %s > %s', tmpFile, tmpFile2);\nsystem(cmd);\nkTest = load(tmpFile2);\n\n%% \n% Now plot the k-test results.\nif subPlots\n    subplot(2,2,3);\nend\n\nsemilogy(kTest(:,2), kTest(:,4), 'bx', ...\n    kTest(:,2), kTest(1,4).^kTest(:,2), 'g-', ...\n    kTest(:,2), ...\n        results.binNnProb(results.exactBin).^kTest(:,2), 'r--');\nxlabel('Number of Projections (K)');\nylabel('Probability');\nlegend('Experimental Data', 'Extrapolated Prediction', ...\n    'Theoretical Prediction', 'Location', 'SouthWest');\ntitle(sprintf('kTest for %d-D data', D));\n\n%%\n% Now let's run the L test.\ncmd = sprintf('%s %s -d %d -w %g -lTest > %s', PythonCmd, LSHCmd, ...\n    D, w, tmpFile);\nfprintf('Running the command: %s\\n', cmd);\nsystem(cmd);\n\n%%\n% And grab the L-test results\ncmd = sprintf('grep \" 10 \" %s > %s', tmpFile, tmpFile2);\nsystem(cmd);\nlTest = load(tmpFile2);\n\n%% \n% Now plot the results.\nif subPlots\n    subplot(2,2,4);\nend\n\nbaseNN = results.binNnProb(results.exactBin).^lTest(1,2);\nbaseAny = results.binAnyProb(results.exactBin).^lTest(1,2);\nsemilogy(lTest(:,3), lTest(:,4), 'rx',  ...\n    lTest(:,3), lTest(:,5), 'kx', ...\n    lTest(:,3), (1-(1-baseNN).^lTest(:,3)), ...\n    lTest(:,3), (1-(1-baseAny).^lTest(:,3)), ...\n    lTest(:,3), (1-(1-kTest(8,4)).^lTest(:,3)), ...\n    lTest(:,3), (1-(1-kTest(8,5)).^lTest(:,3)));\n\nlegend('p_{nn} Experimental', 'p_{any} Experimental', ...\n    'p_{nn} Theory', 'p_{any} Theory',...\n    'p_{nn} k-Prediction', 'p_{any} k-Prediction', ...\n    'Location', 'SouthEast');\nxlabel('Number of Tables (L)');\nylabel('Probability');\ntitle(sprintf('kTest for %d-D data', D));\n\n%%\nsave TestLSHCode wTest lTest kTest results D subplots ...\n    dnnHist dnnBins danyHist danyBins\n\n%%\n% set(gcf,'Position', [100 100 900 800])\npictureFile = sprintf('TestLSHCode-%s.eps', date);\nprint('-depsc', pictureFile);\n", "meta": {"author": "YahooArchive", "repo": "Optimal-LSH", "sha": "64602c431315c8639ecd92f2917f8da9f0ccb52a", "save_path": "github-repos/MATLAB/YahooArchive-Optimal-LSH", "path": "github-repos/MATLAB/YahooArchive-Optimal-LSH/Optimal-LSH-64602c431315c8639ecd92f2917f8da9f0ccb52a/TestLSHCode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5824055990674407}}
{"text": "function node = meshsmoothing(node,elem,step,rho,method,fixedNode)\n%% MESHSMOOTHING improves the geometric mesh quality\n%\n% node = meshsmoothing(node,elem) improves shape regularity of\n% triangles while keeping the density of vertices. \n%\n% node = meshsmoothing(node,elem,m) performs m steps mesh smoothing.\n% The default setting is m=3.\n%\n% node = meshsmoothing(node,elem,m,rho) accept a non-uniform density\n% given by elementwise function rho. The default choice rho = 1/|t|. The\n% quasi-uniform grids corresponds to rho=1. The density function rho can be\n% given by a user specified function or a posteriori error estimator in the\n% setting of adaptive finite element method.\n%\n% node = meshsmoothing(node,elem,m,rho,method,fixedNode) accept the\n% extra input arguments method and fixedNode. The string |method| is to\n% specify the smoothing method: either 'CPT' or 'ODT'. The fixedNode array\n% will fix certain nodes, e.g., vertices on a interface. The boundary nodes\n% of the mesh will be automatically considered as fixed.\n%\n% The function meshsmoothing will keep the topology of the input mesh,\n% i.e., the node index and connectivity of nodes are unchanged. In\n% contrast, the edgeswap function will keep the node but change elem.\n%\n% The algorithm implemented is the simplified version of ODT smoothing; see\n% <a href=\"http://math.uci.edu/~chenlong/CH2008.html\">ODTmesh.</a> \n%\n% Example:\n%     load airfoilperturbmesh\n%     meshquality(node,elem);\n%     node = meshsmoothing(node,elem);\n%     meshquality(node,elem);\n%\n% See also  optmesh, bdsmoothing, edgeswap, rmisopoint\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('step','var'), step = 3; end\nif ~exist('method','var'), method = 'ODT'; end\n\n%% Smooth boundary nodes\n% [node,elem,bdNode] = bdsmoothing(node,elem);\n\n%% Find boundary and interior ndoes\n[bdNode,bdEdge,isBdNode,isBdElem] = findboundary(elem); %#ok<*ASGLU>\nN = size(node,1);  NT = size(elem,1);\n\n%% Compute mesh quality associated to elements and nodes\nqt = 1 - simpqual(node,elem);\nqtp = sparse([1:NT,1:NT,1:NT], elem(1:NT,:), [qt, qt, qt], NT, N);\nqp = max(qtp);\nqp = qp' + 0.01*rand(N,1);  % break the equal case\nqp(bdNode) = 0;             % do not include bdNode and fixed nodes\nif exist('fixedNode','var'), qp(fixedNode) = 0; end\n\n%% Decompose nodes into independent sets\nt2p = sparse([1:NT,1:NT,1:NT], elem(1:NT,:), 1, NT, N);\nA = t2p'*t2p;  % connectness of nodes \nnodeSet = coloring(A,5,qp);\n\n%% Move nodes one by one\nfor m = 1:step\n    for k = 1:5  \n        % find elements containing nodeSet\n        movingNode = nodeSet{k};\n        if isempty(movingNode)\n            break;\n        end\n        [i,j] = find(t2p(:,movingNode)); %#ok<*NASGU>\n        idx = false(NT,1);\n        idx(i) = true;\n        idx = find(idx);\n        % compute centers and areas\n        switch upper(method)\n          case 'CPT'    \n               center = (node(elem(idx,1),:)+node(elem(idx,2),:)+node(elem(idx,3),:))/3;\n          case 'ODT'\n               center = circumcenter(node,elem(idx,:));\n               % modification neary boundary elements: using barycenter to replace circumcenter               \n               center(isBdElem(idx),:) = (node(elem(idx(isBdElem(idx)),1),:) ...\n                                        + node(elem(idx(isBdElem(idx)),2),:) ...\n                                        + node(elem(idx(isBdElem(idx)),3),:))/3;\n        end\n        % compute the weight\n        if exist('rho','var') && ~isempty(rho)\n            weight = simplexvolume(node,elem(idx,:));\n            if (rho~=1)\n                weight = rho(idx).*weight;\n            end\n        end\n        % update to new averaging center\n        oldpi = node(movingNode,:);     % keep the location before moving\n        if exist('rho','var') && ~isempty(rho) % weighted average\n            newnode(:,1) = accumarray([elem(idx,1);elem(idx,2);elem(idx,3)],...\n                                repmat(weight.*center(:,1),3,1),[N,1]);\n            newnode(:,2) = accumarray([elem(idx,1);elem(idx,2);elem(idx,3)],...\n                                repmat(weight.*center(:,2),3,1),[N,1]);\n            valence = accumarray([elem(idx,1);elem(idx,2);elem(idx,3)], ...\n                                 [weight; weight; weight],[N 1]);            \n        else % simple average of centers\n            newnode(:,1) = accumarray([elem(idx,1);elem(idx,2);elem(idx,3)],...\n                                      [center(:,1);center(:,1);center(:,1)],[N,1]);\n            newnode(:,2) = accumarray([elem(idx,1);elem(idx,2);elem(idx,3)],...\n                                      [center(:,2);center(:,2);center(:,2)],[N,1]);\n            valence = accumarray([elem(idx,1);elem(idx,2);elem(idx,3)],...\n                                  ones(3*length(idx),1),[N 1]);\n        end\n        node(movingNode,:) = newnode(movingNode,:)./[valence(movingNode) valence(movingNode)];\n        % check if the moving is valid\n        ve2 = node(elem(idx,1),:)-node(elem(idx,3),:);\n        ve3 = node(elem(idx,2),:)-node(elem(idx,1),:);\n        area = 0.5*(-ve3(:,1).*ve2(:,2)+ve3(:,2).*ve2(:,1));\n        invalidElem = idx(area<0);\n        if any(invalidElem)\n            isNotmoving = false(N,1);\n            isNotmoving(elem(invalidElem,:)) = true;\n            pidx = isNotmoving(movingNode);\n            node(movingNode(pidx),:) = oldpi(pidx,:);\n        end\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/mesh/meshsmoothing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5824055924883905}}
{"text": "classdef prtKernelRbfNeighborhoodScaled < prtKernel\n    % prtKernelRbfNeighborhoodScaled  Radial basis function kernel where\n    % each entry is scaled according to the distance to neighbors in the\n    % training set.\n    %\n    %  KERNOBJ = prtKernelRbfNeighborhoodScaled Generates a kernel object\n    %  implementing a radial basis function.  Kernel objects are widely\n    %  used in several prt classifiers, such as prtClassRvm and\n    %  prtClassSvm.  RBF kernels implement the following function for 1 x N\n    %  vectors x1 and x2:\n    %\n    %   k(x1,x2) = exp(-sum((x1-x2).^2)./sigma1.^2);\n    %\n    %  sigma1 is learned based on the neighboord of the data in\n    %  feature space.\n    % \n    %  KERNOBJ = prtKernelRbfNeighborhoodScaled(PROPERTY1, VALUE1, ...) constructs a\n    %  prtKernelRbfNeighborhoodScaled object KERNOBJ with properties as specified by\n    %  PROPERTY/VALUE pairs. prtKernelRbfNeighborhoodScaled objects have the following\n    %  user-settable properties:\n    %\n    %   neighborhoodPercentile - Quantile distance that is used to define\n    %       the neighboorhood. THis is a value between 1 and 100. Smaller\n    %       values will make more local kernels. (Default value is 5)\n    %\n    %   prtKernelRbf objects inherit the TRAIN and RUN methods from prtKernel.\n    %\n    %   % Example\n    %   ds = prtDataGenMoon;                     % Generate a dataset\n    %   k1 = prtKernelRbfNeighborhoodScaled;    % Create a prtKernel object with \n    %                                            % default value of neighborhoodPercentile\n    %   k2 = prtKernelRbfNeighborhoodScaled('neighborhoodPercentile',2); % Create a prtKernel object with\n    %                                                                     % the specified value of neighborhoodPercentile\n    %   \n    %   k1 = k1.train(ds); % Train\n    %   g1 = k1.run(ds); % Evaluate\n    %\n    %   k2 = k2.train(ds); % Train\n    %   g2 = k2.run(ds); % Evaluate\n    %\n    %   subplot(2,1,1); imagesc(g1.getObservations);  %Plot the results\n    %   subplot(2,1,2); imagesc(g2.getObservations);\n    %\n    %   See also: prtKernel,prtKernelSet, prtKernelDc, prtKernelRbf, prtKernelDirect,\n    %   prtKernelHyperbolicTangent, prtKernelPolynomial,\n    %   prtKernelRbfNdimensionScale, \n\n\n\n\n\n\n\n    properties (SetAccess = private)\n        name = 'RBF Kernel Scaled'; % RBF Kernel Scaled\n        nameAbbreviation = 'RBF'; % RBF\n    end\n    \n    properties\n        neighborhoodPercentile = 5;\n        sigmas = []; % The inverse kernel width for each dimension\n    end \n    \n    methods (Access = protected, Hidden = true)\n        function Obj = trainAction(Obj,ds)\n            Obj.internalDataSet = ds;\n            \n            D = prtDistanceEuclidean(ds,ds);\n            D = sort(D,'ascend');\n            \n            nPointsAway = min(max(round(size(D,1)*Obj.neighborhoodPercentile/100),1),size(D,1));\n            \n            Obj.sigmas = sqrt(D(nPointsAway,:))';\n            Obj.sigmas(Obj.sigmas<=0) = 1; % Put weird values to 1\n            \n            Obj.isTrained = true;\n        end\n        \n        function dsOut = runAction(Obj,ds)\n            if ~Obj.isTrained\n                error('prtKernelRbfNeighboorhoodScaled:run','Attempt to run an untrained kernel; use kernel.train(ds) to train');\n            end\n            if Obj.internalDataSet.nObservations == 0\n                dsOut = prtDataSetClass;\n            else\n                gram = prtKernelRbfNeighborhoodScaled.kernelFn(ds.getObservations,Obj.internalDataSet.getObservations,Obj.sigmas);\n                dsOut = ds.setObservations(gram);\n            end\n        end\n    end\n    \n    methods\n        function Obj = prtKernelRbfNeighborhoodScaled(varargin)\n            Obj = prtUtilAssignStringValuePairs(Obj,varargin{:});\n        end\n    end\n    \n    methods(Hidden = true)\n        function Obj = retainKernelDimensions(Obj,keepLogical)\n            Obj.sigmas = Obj.sigmas(keepLogical);\n            Obj = retainKernelDimensions@prtKernel(Obj,keepLogical);\n        end\n         \n        function varargout = plot(obj)\n            x = obj.internalDataSet.getObservations;\n            \n            if size(x,2) <= 3\n                if size(x,2) == 1 && obj.internalDataSet.isLabeled\n                    xy = cat(2,x,obj.internalDataSet.getTargets);\n                    h = prtPlotUtilScatter(xy, {}, obj.plotOptions.symbol, obj.plotOptions.markerFaceColor, obj.plotOptions.color, obj.plotOptions.symbolLineWidth, obj.plotOptions.symbolSize);\n                else\n                    h = prtPlotUtilScatter(x, {}, obj.plotOptions.symbol, obj.plotOptions.markerFaceColor, obj.plotOptions.color, obj.plotOptions.symbolLineWidth, obj.plotOptions.symbolSize);\n                end\n            else\n                h = nan;\n            end\n            \n            varargout = {};\n            if nargout\n                varargout = {h};\n            end\n        end\n    end\n    \n    methods (Static, Hidden = true)\n        function gram = kernelFn(x,y,sigmas)\n            [n1, d] = size(x);\n            [n2, nin] = size(y);\n            if d ~= nin\n                error('size(x,2) must equal size(y,2)');\n            end\n            \n            %dist2 = prtDistanceLNorm(x,y,2); \n            dist2 = repmat(sum((x.^2), 2), [1 n2]) + repmat(sum((y.^2),2), [1 n1]).' - 2*x*(y.');\n            \n            if numel(sigmas) == 1\n                gram = exp(-dist2/(sigmas.^2));\n            else\n                gram = exp(-bsxfun(@rdivide,dist2,(sigmas.^2)'));\n            end\n        end\n    end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/kernels/prtKernelRbfNeighborhoodScaled.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5823544285871571}}
{"text": "function [mGal] = mmps22mGal(mmps2)\n% Convert acceleration from millimeters per square-second to milligalileos\n% Chad A. Greene 2012\nmGal = mmps2*1e+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/35258-unit-converters/unit_converters/mmps22mGal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.582354424199379}}
{"text": "function fused = Ying_2017_CAIP(I, mu, k, a, b) % camera a, b\n%%\n% @inproceedings{ying2017new,\n%   title={A New Image Contrast Enhancement Algorithm Using Exposure Fusion Framework},\n%   author={Ying, Zhenqiang and Li, Ge and Ren, Yurui and Wang, Ronggang and Wang, Wenmin},\n%   booktitle={International Conference on Computer Analysis of Images and Patterns},\n%   pages={36--46},\n%   year={2017},\n%   organization={Springer}\n% }\n%\n% Please feel free to contact me (yingzhenqiang-at-gmail-dot-com) if you\n% have any questions or concerns.\n\nif  ~exist( 'mu', 'var' )\n    mu = 0.5;\nend\n\nif ~exist( 'a', 'var' )\n    a = -0.3293;\nend\n\nif ~exist( 'b', 'var' )\n    b = 1.1258;\nend\n\nif ~isfloat(I)\n    I = im2double( I );\nend\n\nlambda = 0.5;\nsigma = 5;\n\n%% t: scene illumination map\nt_b = max( I, [], 3 ); % also work for single-channel image\nt_our =  imresize( tsmooth( imresize( t_b, 0.5 ), lambda, sigma ), size( t_b ) );\n\n%% k: exposure ratio\nif  ~exist( 'k', 'var' ) || isempty(k)\n    isBad = t_our < 0.5;\n    J = maxEntropyEnhance(I, isBad);\nelse\n    J = applyK(I, k, a, b); %k\n    J = min(J, 1); % fix overflow\nend\n\n%% W: Weight Matrix \nt = repmat(t_our, [1 1 size(I,3)]);\nW = t.^mu;\n\nI2 = I.*W;\nJ2 = J.*(1-W);\n\nfused = I2 + J2;\n\n    function J = maxEntropyEnhance(I, isBad)\n        Y = rgb2gm(real(max(imresize(I, [50 50]), 0))); % max - avoid complex number \n        \n        if exist('isBad', 'var')\n            isBad = (imresize(isBad, [50 50]));\n            Y = Y(isBad);\n        end\n        \n        if isempty(Y)\n           J = I; % no enhancement k = 1\n           return;\n        end\n        \n        opt_k = fminbnd(@(k) ( -entropy(applyK(Y, k)) ),1, 7);\n        J = applyK(I, opt_k, a, b) - 0.01;\n        \n    end\nend\n\nfunction I = rgb2gm(I)\nif size(I,3) == 3\n    I = im2double(max(0,I)); % negative double --> complex double\n    I = ( I(:,:,1).*I(:,:,2).*I(:,:,3) ).^(1/3);\nend\nend\n\nfunction J = applyK(I, k, a, b)\n\nif ~exist( 'a', 'var' )\n    a = -0.3293;\nend\n\nif ~exist( 'b', 'var' )\n    b = 1.1258;\nend\n\nf = @(x)exp((1-x.^a)*b);\nbeta = f(k);\ngamma = k.^a;\nJ = I.^gamma.*beta;\nend\n\nfunction S = tsmooth( I, lambda, sigma, sharpness)\nif ( ~exist( 'lambda', 'var' ) )\n    lambda = 0.01;\nend\nif ( ~exist( 'sigma', 'var' ) )\n    sigma = 3.0;\nend\nif ( ~exist( 'sharpness', 'var' ) )\n    sharpness = 0.001;\nend\nI = im2double( I );\nx = I;\n[ wx, wy ] = computeTextureWeights( x, sigma, sharpness);\nS = solveLinearEquation( I, wx, wy, lambda );\nend\n\nfunction [ W_h, W_v ] = computeTextureWeights( fin, sigma, sharpness)\n\ndt0_v = [diff(fin,1,1);fin(1,:)-fin(end,:)];\ndt0_h = [diff(fin,1,2)';fin(:,1)'-fin(:,end)']';\n\ngauker_h = filter2(ones(1,sigma),dt0_h);\ngauker_v = filter2(ones(sigma,1),dt0_v);\nW_h = 1./(abs(gauker_h).*abs(dt0_h)+sharpness);\nW_v = 1./(abs(gauker_v).*abs(dt0_v)+sharpness);\n\nend\n\nfunction OUT = solveLinearEquation( IN, wx, wy, lambda )\n[ r, c, ch ] = size( IN );\nk = r * c;\ndx =  -lambda * wx( : );\ndy =  -lambda * wy( : );\ntempx = [wx(:,end),wx(:,1:end-1)];\ntempy = [wy(end,:);wy(1:end-1,:)];\ndxa = -lambda *tempx(:);\ndya = -lambda *tempy(:);\ntempx = [wx(:,end),zeros(r,c-1)];\ntempy = [wy(end,:);zeros(r-1,c)];\ndxd1 = -lambda * tempx(:);\ndyd1 = -lambda * tempy(:);\nwx(:,end) = 0;\nwy(end,:) = 0;\ndxd2 = -lambda * wx(:);\ndyd2 = -lambda * wy(:);\n\nAx = spdiags( [dxd1,dxd2], [-k+r,-r], k, k );\nAy = spdiags( [dyd1,dyd2], [-r+1,-1], k, k );\n\nD = 1 - ( dx + dy + dxa + dya);\nA = (Ax+Ay) + (Ax+Ay)' + spdiags( D, 0, k, k );\n\nif exist( 'ichol', 'builtin' )\n    L = ichol( A, struct( 'michol', 'on' ) );\n    OUT = IN;\n    for ii = 1:ch\n        tin = IN( :, :, ii );\n        [ tout, ~ ] = pcg( A, tin( : ), 0.1, 50, L, L' );\n        OUT( :, :, ii ) = reshape( tout, r, c );\n    end\nelse\n    OUT = IN;\n    for ii = 1:ch\n        tin = IN( :, :, ii );\n        tout = A\\tin( : );\n        OUT( :, :, ii ) = reshape( tout, r, c );\n    end\nend\nend\n\n", "meta": {"author": "baidut", "repo": "OpenCE", "sha": "abbc8609b7d5069e20871b585dcf6d18b59f1c0e", "save_path": "github-repos/MATLAB/baidut-OpenCE", "path": "github-repos/MATLAB/baidut-OpenCE/OpenCE-abbc8609b7d5069e20871b585dcf6d18b59f1c0e/ours/Ying_2017_CAIP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387956435734, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5823544093551043}}
{"text": "function [EigenvectorsDiscrete,EigenVectors]=discretisation(EigenVectors)\n% \n% EigenvectorsDiscrete=discretisation(EigenVectors)\n% \n% Input: EigenVectors = continuous Ncut vector, size = ndata x nbEigenvectors \n% Output EigenvectorsDiscrete = discrete Ncut vector, size = ndata x nbEigenvectors\n%\n% Timothee Cour, Stella Yu, Jianbo Shi, 2004\n\n[n,k]=size(EigenVectors);\n\nvm = sqrt(sum(EigenVectors.*EigenVectors,2));\nEigenVectors = EigenVectors./repmat(vm,1,k);\n\nR=zeros(k);\nR(:,1)=EigenVectors(1+round(rand(1)*(n-1)),:)';\nc=zeros(n,1);\nfor j=2:k\n    c=c+abs(EigenVectors*R(:,j-1));\n    [minimum,i]=min(c);\n    R(:,j)=EigenVectors(i,:)';\nend\n\nlastObjectiveValue=0;\nexitLoop=0;\nnbIterationsDiscretisation = 0;\nnbIterationsDiscretisationMax = 20;%voir\nwhile exitLoop== 0 \n    nbIterationsDiscretisation = nbIterationsDiscretisation + 1 ;   \n    EigenvectorsDiscrete = discretisationEigenVectorData(EigenVectors*R);\n    [U,S,V] = svd(EigenvectorsDiscrete'*EigenVectors,0);    \n    NcutValue=2*(n-trace(S));\n    \n    if abs(NcutValue-lastObjectiveValue) < eps | nbIterationsDiscretisation > nbIterationsDiscretisationMax\n        exitLoop=1;\n    else\n        lastObjectiveValue = NcutValue;\n        R=V*U';\n    end\nend", "meta": {"author": "jwyang", "repo": "JULE.torch", "sha": "69bdfd82f9dfd431619a8ee25ac832da76a827e2", "save_path": "github-repos/MATLAB/jwyang-JULE.torch", "path": "github-repos/MATLAB/jwyang-JULE.torch/JULE.torch-69bdfd82f9dfd431619a8ee25ac832da76a827e2/matlab/approaches/n-cut/Ncut_9/discretisation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5823253333177395}}
{"text": "function [cor_ini, score_all] = sample_opt_pano(cor_id, im_w, im_h, corn, edg, edg2, options)\n\n\tscore_all = 0;\n        [wall_d, x, f] = pano_line_solver(cor_id, im_w, options); % bos-shape case\n        cor_id_t = cor_id;\n        d_m = 0;\n        % initialization\n        for j = 1:2:size(cor_id_t,1)\n            theta_y = pi*cor_id_t(j+1,2)/im_h-pi/2;\n            theta_y_ = pi/2 - pi*cor_id_t(j,2)/im_h;\n            d = abs(cot(theta_y));\n            d_m = d_m + d/wall_d((j+1)/2);\n        end\n        d_m = d_m/4;\n        cor_ini = [];\n        for j = 1:2:size(cor_id_t,1)\n            line_d = d_m*wall_d((j+1)/2);\n            line_theta_y = acot(line_d);\n            line_y = (line_theta_y + pi/2)*im_h/pi;\n            cor_ini = [cor_ini;cor_id_t(j,1) line_y];\n            cor_ini = [cor_ini;cor_id_t(j,1) line_y];\n        end\n        \n        score_btn = interp2(corn,cor_ini(2:2:end,1),cor_ini(2:2:end,2));\n        score_btn = sum(log(score_btn));\n       \n        % add floor score\n        cor_all = [cor_ini(2,:);cor_ini(4,:);cor_ini(4,:);cor_ini(6,:);\n               cor_ini(6,:);cor_ini(8,:);cor_ini(8,:);cor_ini(2,:)];\n    \t[ uv ] = coords2uv( cor_all, im_w, im_h );\n    \t[ xyz ] = uv2xyzN( uv);\n    \t[ lines ] = lineFromTwoPoint( xyz(1:2:end,:), xyz(2:2:end,:) );\n    \tim = zeros(im_h, im_w, 3);\n    \t[ panoEdgeC ] = paintParameterLine_my(lines, im_w, im_h, im);\n    \tscore_fl = zeros(1,4);\n    \tscore_fl(1) = max(max(edg2(:,:,3).*(panoEdgeC(:,:,1) == 1)));\n    \tscore_fl(2) = max(max(edg2(:,:,3).*(panoEdgeC(:,:,1) == 2)));\n    \tscore_fl(3) = max(max(edg2(:,:,3).*(panoEdgeC(:,:,1) == 3)));\n    \tscore_fl(4) = max(max(edg2(:,:,3).*(panoEdgeC(:,:,1) == 4)));\n    \tscore_fl = sum(log(score_fl));\n    \tscore_btn = score_btn + score_fl;\n\n        % sampling\n        % horizontal, bottoms\n        d_m_max = d_m + d_m*0.1;\n        d_m_min = d_m - d_m*0.1; \n        score_best = -Inf;\n\n        for j = d_m_min:d_m*0.02:d_m_max\n            cor_opt = [];\n            for k = 1:2:size(cor_id_t,1)\n                line_d = j*wall_d((k+1)/2);\n                line_theta_y = acot(line_d);\n                line_y = (line_theta_y + pi/2)*im_h/pi;\n                cor_opt = [cor_opt;cor_id_t(k,1) line_y];\n            end\n            % compute score\n            score = interp2(corn,cor_opt(:,1),cor_opt(:,2));\n            score = sum(log(score));\n\n            cor_all = [cor_opt(1,:);cor_opt(2,:);cor_opt(2,:);cor_opt(3,:);\n               cor_opt(3,:);cor_opt(4,:);cor_opt(4,:);cor_opt(1,:)];\n    \t\t[ uv ] = coords2uv( cor_all, im_w, im_h );\n    \t\t[ xyz ] = uv2xyzN( uv);\n    \t\t[ lines ] = lineFromTwoPoint( xyz(1:2:end,:), xyz(2:2:end,:) );\n    \t\t[ panoEdgeC ] = paintParameterLine_my(lines, im_w, im_h, im);\n    \t\tscore_fl = zeros(1,4);\n    \t\tscore_fl(1) = max(max(edg2(:,:,3).*(panoEdgeC(:,:,1) == 1)));\n    \t\tscore_fl(2) = max(max(edg2(:,:,3).*(panoEdgeC(:,:,1) == 2)));\n    \t\tscore_fl(3) = max(max(edg2(:,:,3).*(panoEdgeC(:,:,1) == 3)));\n    \t\tscore_fl(4) = max(max(edg2(:,:,3).*(panoEdgeC(:,:,1) == 4)));\n    \t\tscore_fl = sum(log(score_fl));\n    \t\tscore = score + score_fl;\n\n            if score > score_best\n                score_best = score;\n                cor_best = cor_opt;\n                d_m_best = j;\n            end\n        end\n        if score_best > score_btn\n            cor_ini(2:2:end,:) = cor_best;\n        else\n           score_best = score_btn;\n           d_m_best = d_m;\n        end\n        score_all = score_all + score_best;\n        % horizontal, top\n        h_m = 0;\n        for j = 1:2:size(cor_id_t,1)\n            theta_y_ = pi/2 - pi*cor_id_t(j,2)/im_h;\n            d = d_m_best*wall_d((j+1)/2);\n            h = d*tan(theta_y_);\n            h_m = h_m + h;\n        end\n        h_m = h_m/4;\n        for j = 1:2:size(cor_id_t,1)\n            line_d = d_m_best*wall_d((j+1)/2);\n            line_y_ = atan(h_m/line_d);\n            line_y_ = (pi/2-line_y_)*im_h/pi;\n            cor_ini(j,2) = line_y_;\n        end\n        score_tp = interp2(corn,cor_ini(1:2:end,1),cor_ini(1:2:end,2));\n        score_tp = sum(log(score_tp));\n\n        % add ceiling score\n        cor_all = [cor_ini(1,:);cor_ini(3,:);cor_ini(3,:);cor_ini(5,:);\n               cor_ini(5,:);cor_ini(7,:);cor_ini(7,:);cor_ini(1,:)];\n    \t[ uv ] = coords2uv( cor_all, im_w, im_h );\n    \t[ xyz ] = uv2xyzN( uv);\n    \t[ lines ] = lineFromTwoPoint( xyz(1:2:end,:), xyz(2:2:end,:) );\n    \tim = zeros(im_h, im_w, 3);\n    \t[ panoEdgeC ] = paintParameterLine_my(lines, im_w, im_h, im);\n    \tscore_cl = zeros(1,4);\n\n    \tscore_cl(1) = max(max(edg2(:,:,2).*(panoEdgeC(:,:,1) == 1)));\n    \tscore_cl(2) = max(max(edg2(:,:,2).*(panoEdgeC(:,:,1) == 2)));\n    \tscore_cl(3) = max(max(edg2(:,:,2).*(panoEdgeC(:,:,1) == 3)));\n    \tscore_cl(4) = max(max(edg2(:,:,2).*(panoEdgeC(:,:,1) == 4)));\n    \tscore_cl = sum(log(score_cl));\n    \tscore_tp = score_tp + 0.5*score_cl;\n\n        h_m_max = h_m + h_m*0.1;\n        h_m_min = h_m - h_m*0.1;\n        score_best = -Inf;\n        for j = h_m_min:h_m*0.02:h_m_max\n            cor_opt = [];\n            for k = 1:2:size(cor_ini,1)\n                line_d = d_m_best*wall_d((k+1)/2);\n                line_y_ = atan(j/line_d);\n                line_y_ = (pi/2-line_y_)*im_h/pi;\n                cor_opt = [cor_opt;cor_ini(k,1) line_y_];\n            end\n            % compute score\n            score = interp2(corn,cor_opt(:,1),cor_opt(:,2));\n            score = sum(log(score));\n            if 1\n            % add ceiling score\n        \tcor_all = [cor_opt(1,:);cor_opt(2,:);cor_opt(2,:);cor_opt(3,:);\n               \tcor_opt(3,:);cor_opt(4,:);cor_opt(4,:);cor_opt(1,:)];\n    \t\t[ uv ] = coords2uv( cor_all, im_w, im_h );\n    \t\t[ xyz ] = uv2xyzN( uv);\n    \t\t[ lines ] = lineFromTwoPoint( xyz(1:2:end,:), xyz(2:2:end,:) );\n    \t\tim = zeros(im_h, im_w, 3);\n    \t\t[ panoEdgeC ] = paintParameterLine_my(lines, im_w, im_h, im);\n    \t\tscore_cl = zeros(1,4);\n\n    \t\tscore_cl(1) = max(max(edg2(:,:,2).*(panoEdgeC(:,:,1) == 1)));\n    \t\tscore_cl(2) = max(max(edg2(:,:,2).*(panoEdgeC(:,:,1) == 2)));\n    \t\tscore_cl(3) = max(max(edg2(:,:,2).*(panoEdgeC(:,:,1) == 3)));\n    \t\tscore_cl(4) = max(max(edg2(:,:,2).*(panoEdgeC(:,:,1) == 4)));\n    \t\tscore_cl = sum(log(score_cl));\n    \t\tscore = score + 0.5*score_cl;\n    \tend\n\n            if score > score_best\n                score_best = score;\n                cor_best = cor_opt;\n                h_m_best = j;\n            end\n        end\n        if score_best > score_tp\n            cor_ini(1:2:end,:) = cor_best;\n        else\n            score_best = score_tp;\n            h_m_best = h_m;\n        end\n        score_all = score_all + score_best;\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/sample_opt_pano_joint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.582325329817012}}
{"text": "function [tg,theta] = tgmo2(tmap,ntex,radius,norient,varargin)\n% function [tg,theta] = tgmo2(tmap,ntex,radius,norient,...)\n%\n% Compute the texture gradient at a single scale and multiple\n% orientations.\n%\n% INPUT\n%\ttmap\t\tTexton map, values in [1,ntex].\n%\tntex\t\tNumber of textons.\n%\tradius\t\tRadius of disc for texture gradient.\n%\tnorient\t\tNumber of orientation at which to compute \n%\t\t\tthe texture gradient.\n%\t'smooth'\tSmoothing method, one of \n%\t\t\t{'gaussian','savgol','none'}, default 'none'.\n%\t'sigma'\t\tSigma for smoothing, default to radius.\n%\t'tsim'\t\tTexton similarity matrix.  If not \n%\t\t\tprovided, then use chi-squared.\n%\n% OUTPUT\n%\ttg\t\tSize [h w norient] array of tg images.\n%\ttheta\t\tVector of disc orientations (which are \n%\t\t\torthogonal to the texture gradient).\n%\n% David R. Martin <dmartin@eecs.berkeley.edu>\n% March 2003\n\n% process options\nsmooth = 'none';\nsigma = radius;\nusechi2 = true;\nfor i = 1:2:numel(varargin),\n  opt = varargin{i};\n  if ~ischar(opt), error('option names not a string'); end\n  if i==numel(varargin), error(sprintf('option ''%s'' has no value',opt)); end\n  val = varargin{i+1};\n  switch opt,\n   case 'smooth',\n    switch val,\n     case {'none','gaussian','savgol'}, smooth=val;\n     otherwise, error(sprintf('invalid option smooth=''%s''',val));\n    end\n   case 'sigma', sigma=val;\n   case 'tsim', tsim=val; usechi2=false;\n   otherwise, error(sprintf('invalid option ''%s''',opt));\n  end\nend\n\nradius = max(1,radius);\nnorient = max(1,norient);\ntheta = (0:norient-1)/norient*pi;\n\n% check texton labels\nif any(tmap~=round(tmap)),\n  error('texton labels not integral');\nend\nif min(tmap(:)) < 1 | max(tmap(:))>ntex, \n  error(sprintf('texton labels out of range [1,%d]',ntex)); \nend\n\n% radius of discrete disc\nwr = floor(radius);\n\n% count number of pixels in a disc\n[u,v] = meshgrid(-wr:wr,-wr:wr);\ngamma = mod(atan2(v,u),2*pi);\nmask = (u.^2 + v.^2 <= radius^2);\nmask(wr+1,wr+1) = 0; % mask out center pixel to remove bias\ncount = sum(mask(:));\n\n% determine which pie slice each pixel falls into\n% 0=masked [1,2*norient]=slice\nslice = 1 + floor(gamma/(pi/norient));\nslice = slice .* mask;\n\n[h,w] = size(tmap);\ntg = zeros(h,w,norient);\nfwrite(2,'[');\nfor x = 1:w,\n  fwrite(2,'.');\n  for y = 1:h,\n    pie = zeros(ntex,2*norient);\n    for u = -wr:wr,\n      xi = x + u;\n      if xi<1 | xi>w, continue; end\n      for v = -wr:wr,\n        yi = y + v;\n        if yi<1 | yi>h, continue; end\n        s = slice(v+wr+1,u+wr+1);\n        if s==0, continue; end % masked out\n        t = tmap(yi,xi);\n        pie(t,s) = pie(t,s) + 1;\n      end\n    end\n    pie = pie .* (2/count); % normalize\n    % initialize left/right histograms\n    lhist = sum(pie(:,1:norient),2);\n    rhist = sum(pie(:,norient+1:end),2);\n    % spin the disc to compute tg at each orientation\n    for i = 1:norient,\n      if usechi2,\n        chi = (lhist-rhist).^2 ./ (lhist+rhist+eps);\n        tg(y,x,i) = 0.5*sum(chi);\n      else\n        lrdiff = abs(lhist-rhist);\n        tg(y,x,i) = lrdiff' * tsim * lrdiff;\n      end\n      if i<norient,\n        inc = pie(:,norient+i) - pie(:,i);\n        lhist = lhist + inc;\n        rhist = rhist - inc;\n      end\n    end\n  end\nend\nfprintf(2,']\\n');\n\nfor i = 1:norient,\n  switch smooth,\n   case 'gaussian',\n    f = oeFilter([sigma .5],3,theta(i)+pi/2);\n    tg(:,:,i) = applyFilter(f,tg(:,:,i));\n   case 'savgol',\n    a = fitparab(tg(:,:,i),sigma,sigma/4,theta(i));\n    tg(:,:,i) = max(0,a);\n  end\nend\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/segbench/Gradients/tgmo2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5823253138326019}}
{"text": "function [kHz] = THz2kHz(THz)\n% Convert frequency from terahertz to kilohertz.\n% Chad A. Greene 2012\nkHz = THz*1e+9;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/THz2kHz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5823028726145612}}
{"text": "function test_failed = test_libltfat_solvehermitiansystem(varargin)\ntest_failed = 0;\n\nfprintf(' ===============  %s ================ \\n',upper(mfilename));\n\ndefinput.flags.complexity={'double','single'};\n[flags]=ltfatarghelper({},definput,varargin);\ndataPtr = [flags.complexity, 'Ptr'];\n\nLarr =    [301, 9,11,110, 9, 8, 11, 10, 301];\n\n\n    complexstring = 'complex'; \n    funname_init = makelibraryname('hermsystemsolver_init',flags.complexity,1);\n    funname_execute = makelibraryname('hermsystemsolver_execute',flags.complexity,1);\n    funname_done = makelibraryname('hermsystemsolver_done',flags.complexity,1);\n   \n    p = libpointer();\n    calllib('libltfat',funname_init,max(Larr),p); \n    \nfor Lidx = 1:numel(Larr)\n    L = Larr(Lidx);\n    \n\n    \n     \n\n    D = randn(L,flags.complexity)+1i*randn(L,flags.complexity);\n   % D(:,1) = D(:,end);\n    A = D*D';\n    Amessedup = A;\n    for n=2:size(A,2)\n        for m=1:n-1\n              Amessedup(m,n) = randn(1);\n        end\n    end\n    Aint = complex2interleaved(Amessedup);\n    APtr = libpointer(dataPtr,Aint);\n\n    b = randn(L,1,flags.complexity)+ 1i*randn(L,1,flags.complexity);\n    bint = complex2interleaved(b);\n    bPtr = libpointer(dataPtr,bint);\n    \n    tic\n    trueres = A\\b;\n    toc\n           \n    tic\n    status = calllib('libltfat',funname_execute,p,APtr,L,bPtr);\n    toc\n\n    \n    res = norm(trueres - interleaved2complex(bPtr.Value));\n\n    [test_failed,fail]=ltfatdiditfail(res+status,test_failed,1e-8);\n    fprintf(['SOLVEHERM L:%3i, %s %s %s %s\\n'],L,flags.complexity,complexstring,ltfatstatusstring(status),fail);\n\nend\n\n    calllib('libltfat',funname_done,p);\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/libltfat/modules/libltfat/testing/mUnit/test_libltfat_solvehermitiansystem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936435, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5823028649452439}}
{"text": "function [ gd,filtertype ] = gsp_jtv_design_can_dual(g,filtertype)\n%GSP_JTV_DESIGN_CAN_DUAL This function returns the canonical dual of the time-vertex filterbank g\n%   Usage:  [gd,filtertype] = gsp_jtv_design_can_dual( g,filtertype );\n%\n%   Inputs parameters:\n%       g          : cell array of time-vertex filters\n%       filtertype : Filter domain (ts,js,ts-array,js-array)\n%\n%   Ouputs parameters:\n%       g          : cell array of canonical dual time-vertex filters\n%       filtertype : Filter domain (ts,js)\n%\n%   This function returns the canonical dual of the time-vertex filterbank g\n%\n\n% Author: Francesco Grassi\n% Date:   September 2016\n\nNf = size(g,1);\ngd = cell(Nf,1);\n\nfor n = 1:Nf\n    gd{n} = @(x,t) can_dual(g,filtertype,n,x,t);\nend\n\nswitch filtertype\n    case {'ts','ts-array'}\n        filtertype = 'ts';\n    case {'js','js-array'}\n        filtertype = 'js';\nend\n\nend\n\n\nfunction sol = can_dual(g,ft,n,x,t)\n\n\nif ~isvector(x);x=x(:,1);end\nif ~isvector(t);t=t(1,:);end\n\nsol = gsp_jtv_evaluate_can_dual( g,ft,x,t,n );\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/filters/gsp_jtv_design_can_dual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5823028586136269}}
{"text": "function [P,Uinit,output] = cp_als(X,R,varargin)\n%CP_ALS Compute a CP decomposition of any type of tensor.\n%\n%   P = CP_ALS(X,R) computes an estimate of the best rank-R\n%   CP 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.\n%\n%   P = CP_ALS(X,R,'param',value,...) specifies optional parameters and\n%   values. Valid parameters and their default values are:\n%      'tol' - Tolerance on difference in fit {1.0e-4}\n%      'maxiters' - Maximum number of iterations {50}\n%      'dimorder' - Order to loop through dimensions {1:ndims(A)}\n%      'init' - Initial guess [{'random'}|'nvecs'|cell array]\n%      'printitn' - Print fit every n iterations; 0 for no printing {1}\n%\n%   [P,U0] = CP_ALS(...) also returns the initial guess.\n%\n%   [P,U0,out] = CP_ALS(...) also returns additional output that contains\n%   the input parameters.\n%\n%   Note: The \"fit\" is defined as 1 - norm(X-full(P))/norm(X) and is\n%   loosely the proportion of the data described by the CP model, i.e., a\n%   fit of 1 is perfect.\n%\n%   Examples:\n%   X = sptenrand([5 4 3], 10);\n%   P = cp_als(X,2);\n%   P = cp_als(X,2,'dimorder',[3 2 1]);\n%   P = cp_als(X,2,'dimorder',[3 2 1],'init','nvecs');\n%   U0 = {rand(5,2),rand(4,2),[]}; %<-- Initial guess for factors of P\n%   [P,U0,out] = cp_als(X,2,'dimorder',[3 2 1],'init',U0);\n%   P = cp_als(X,2,out.params); %<-- Same params as previous run\n%\n%   See also KTENSOR, TENSOR, SPTENSOR, TTENSOR.\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\n\n\n%% Extract number of dimensions and norm of X.\nN = ndims(X);\nnormX = norm(X);\n\n%% Set algorithm parameters from input or by using defaults\nparams = inputParser;\nparams.addParamValue('tol',1e-4,@isscalar);\nparams.addParamValue('maxiters',50,@(x) isscalar(x) & x > 0);\nparams.addParamValue('dimorder',1:N,@(x) isequal(sort(x),1:N));\nparams.addParamValue('init', 'random', @(x) (iscell(x) || ismember(x,{'random','nvecs'})));\nparams.addParamValue('printitn',1,@isscalar);\nparams.parse(varargin{:});\n\n%% Copy from params object\nfitchangetol = params.Results.tol;\nmaxiters = params.Results.maxiters;\ndimorder = params.Results.dimorder;\ninit = params.Results.init;\nprintitn = params.Results.printitn;\n\n%% Error checking \n\n%% Set up and error checking on initial guess for U.\nif iscell(init)\n    Uinit = init;\n    if numel(Uinit) ~= N\n        error('OPTS.init does not have %d cells',N);\n    end\n    for n = dimorder(2:end);\n        if ~isequal(size(Uinit{n}),[size(X,n) R])\n            error('OPTS.init{%d} is the wrong size',n);\n        end\n    end\nelse\n    % Observe that we don't need to calculate an initial guess for the\n    % first index in dimorder because that will be solved for in the first\n    % inner iteration.\n    if strcmp(init,'random')\n        Uinit = cell(N,1);\n        for n = dimorder(2:end)\n            Uinit{n} = rand(size(X,n),R);\n        end\n    elseif strcmp(init,'nvecs') || strcmp(init,'eigs') \n        Uinit = cell(N,1);\n        for n = dimorder(2:end)\n            Uinit{n} = nvecs(X,n,R);\n        end\n    else\n        error('The selected initialization method is not supported');\n    end\nend\n\n%% Set up for iterations - initializing U and the fit.\nU = Uinit;\nfit = 0;\n\nif printitn>0\n  fprintf('\\nCP_ALS:\\n');\nend\n\n%% Main Loop: Iterate until convergence\n\nif (isa(X,'sptensor') || isa(X,'tensor')) && (exist('cpals_core','file') == 3)\n \n    %fprintf('Using C++ code\\n');\n    [lambda,U] = cpals_core(X, Uinit, fitchangetol, maxiters, dimorder);\n    P = ktensor(lambda,U);\n    \nelse\n    \n    for iter = 1:maxiters\n        \n        fitold = fit;\n        \n        % Iterate over all N modes of the tensor\n        for n = dimorder(1:end)\n            \n            % Calculate Unew = X_(n) * khatrirao(all U except n, 'r').\n            Unew = mttkrp(X,U,n);\n            \n            % Compute the matrix of coefficients for linear system\n            Y = ones(R,R);\n            for i = [1:n-1,n+1:N]\n                Y = Y .* (U{i}'*U{i});\n            end\n            \n            % Need to figure out which of the following lines works better.\n            % Meanwhile, we'll stick witht he line from TTB 2.2 since that is\n            % what seems to work best based on preliminary testing.\n            %Unew = Unew * pinv(Y); %<- Line from TTB 2.3.\n            Unew = (Y \\ Unew')'; %<- Line from TTB 2.2.\n            \n            % Normalize each vector to prevent singularities in coefmatrix\n            if iter == 1\n                lambda = sqrt(sum(Unew.^2,1))'; %2-norm\n            else\n                lambda = max( max(Unew,[],1), 1 )'; %max-norm\n            end\n            Unew = Unew * spdiags(1./lambda,0,R,R);\n            if issparse(Unew)\n                U{n} = full(Unew);   % for the case R=1\n            else\n                U{n} = Unew;\n            end\n        end\n        \n        P = ktensor(lambda,U);\n        normresidual = sqrt( normX^2 + norm(P)^2 - 2 * innerprod(X,P) );\n        fit = 1 - (normresidual / normX); %fraction explained by model\n        fitchange = abs(fitold - fit);\n        \n        if mod(iter,printitn)==0\n            fprintf(' Iter %2d: fit = %e fitdelta = %7.1e\\n', iter, fit, fitchange);\n        end\n        \n        % Check for convergence\n        if (iter > 1) && (fitchange < fitchangetol)\n            break;\n        end        \n    end   \nend\n\n\n%% Clean up final result\n% Arrange the final tensor so that the columns are normalized.\nP = arrange(P);\n% Fix the signs\nP = fixsigns(P);\n\nif printitn>0\n  normresidual = sqrt( normX^2 + norm(P)^2 - 2 * innerprod(X,P) );\n  fit = 1 - (normresidual / normX); %fraction explained by model\n  fprintf(' Final fit = %e \\n', fit);\nend\n\noutput = struct;\noutput.params = params.Results;\noutput.iters = iter;\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/cp_als.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.5823028513011959}}
{"text": "function [d dt pred] = bfs(A,u,varargin)\n% BFS Compute the breadth first search order.\n%\n% [d dt pred] = bfs(A,u) returns the distance to each vertex (d) and the  \n% discover time (dt) in a breadth first search starting from vertex u.\n%    d(i) = dt(i) = -1 if vertex i is not reachable from vertex u.\n% pred is the predecessor array.  pred(i) = 0 if vertex (i)  \n% is in a component not reachable from u and i != u.\n%\n% This method works on directed graphs.\n% The runtime is O(V+E).\n%\n% ... = bfs(A,u,...) takes a set of\n% key-value pairs or an options structure.  See set_matlab_bgl_options\n% for the standard options. \n%   options.target: a special vertex that will stop the search when hit\n%       [{'none'} | any vertex number besides the u]\n%\n% Note: this function does not depend upon the non-zero values of A, but\n% only uses the non-zero structure of A.\n%\n% Example:\n%    load graphs/bfs_example.mat\n%    d = bfs(A,1)\n%\n% See also DFS\n\n% David Gleich\n% Copyright, Stanford University, 2006-2008\n\n%% History \n%  2006-04-19: Initial version\n%  2006-05-31: Added full2sparse check\n%  2007-04-19: Added target option\n%  2008-10-07: Changed options parsing\n%%\n\n[trans check full2sparse] = get_matlab_bgl_options(varargin{:});\nif full2sparse && ~issparse(A), A = sparse(A); end\n\noptions = struct('target', 'none');\noptions = merge_options(options,varargin{:});\n\nif check, check_matlab_bgl(A,struct()); end\n\nif strcmp(options.target,'none')\n    target = 0; % a flag used to denote \"no target\" to the mex\nelseif isa(options.target, 'double')\n    target = options.target;\nelse\n    error('matlab_bgl:invalidParameter', ...\n        'options.target is not ''none'' or a vertex number.');\nend\n\nif (trans) \n    A = A'; \nend\n\n[d dt pred] = bfs_mex(A,u,target);\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/matlab_bgl/bfs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.5822653906262985}}
{"text": "function s = trunc_singular(s, tol, relative, maxrank)\n% REL_TRUNC_SINGULAR Helper routine to truncate singular values\n\n%   TTeMPS Toolbox. \n%   Michael Steinlechner, 2013-2016\n%   Questions and contact: michael.steinlechner@epfl.ch\n%   BSD 2-clause license, see LICENSE.txt\n\n    if ~exist('relative','var'),    relative = true;     end\n    if ~exist('maxrank','var'), maxrank = length(s); end\n\n    summ = cumsum(s.^2,'reverse');\n\n    if relative\n        s = find(summ > tol^2, 1, 'last');\n        if isempty(s), s = 1; end\n    else\n        s = find(summ > tol^2*summ(1), 1, 'last');\n        if isempty(s), s = 1; end\n    end\n\n    s = min([s, maxrank, length(s)]);\n\nend\n\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/trunc_singular.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998714925402, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.5822653857826733}}
{"text": "function [xfinal,ffinal,exitflag,xstart] = rmsearch(fun,optname,x0,LB,UB,varargin)\n% RMSEARCH: Randomly multistarted overlay to several optimizers\n% usage: [xfinal,ffinal,exitflag,xstart] = RMSEARCH(fun,optname,x0,LB,UB)\n% usage: [xfinal,ffinal,exitflag,xstart] = RMSEARCH(fun,optname,x0,LB,UB,prop1,val1,prop2,val2,...)\n% \n% This tool is useful when little information is available\n% for good starting values for an optimization, or when many\n% local solutions exist. It is also useful to map out the various\n% basins of attaction of each local solution.\n%\n% RMSEARCH is normally used for bounded optimization problems,\n% but with care can be used when some variables are unbounded.\n% Whenever possible I'd still recommend the use of both lower\n% and upper bounds if you can possibly do so. Restriction of\n% the solution space is an important way to improve the\n% performance of any optimization.\n%\n%\n% arguments: (Input)\n%  fun - name of a function, inline function, or a function handle\n%\n%  optname - character string - the name of the\n%        optimizer to be used. Valid options are\n%\n%        'fminsearchbnd', 'fminsearchcon', 'fmincon'\n%        'fminbnd', 'fzero', 'lsqnonlin', 'fminsearch'\n%        \n%        No default is allowed, but the function name may\n%        be shortened as long as the shortening is unambiguous.\n%        Thus 'fminb' or 'fz' are acceptable, but 'fm' is not.\n%\n%        Note that fzero and fminbnd, since they work in 1-d\n%        will search EVERY bracketed interval they find that\n%        contains either a root or a minimizer (as appropriate.)\n%\n%        Remember to set the options structure properly for\n%        fmincon, turning off the largescale optimizer as\n%        appropriate. Otherwise you will see many warning\n%        messages generated, one for each call to the optimizer.\n%\n%  x0 -  starting value. Used to determine the dimension and\n%        shape of the parameter vector. Also used to determine\n%        the distribution of the random starts when the bounds\n%        are incompletely specified.\n% \n%        No default is allowed. \n%\n%        If both lower and upper bounds are supplied for a\n%        parameter, then the distribution for the multi-starts\n%        is chosen to be uniform between those bounds. If no\n%        upper bound or no lower bound, then the distribution\n%        follows a two parameter exponential distribution, with\n%        mean at x0(i). If both upper and lower bounds are\n%        missing (i.e., they are +/- inf), then that parameter \n%        will be normally distribued with mean at x0(i).\n%\n%  LB -  Lower bounds for the parameters, as used by fmincon,\n%        fminsearchbnd, lsqnonlin, etc.\n%\n%        LB must be the same size as x0, and LB(i)<=UB(i)\n%\n%        When no lower bound exists for a variable, use -inf\n%\n%  UB -  Upper bounds for the parameters, as used by fmincon,\n%        fminsearchbnd, lsqnonlin, etc.\n%\n%        UB must be the same size as x0, and LB(i)<=UB(i)\n%\n%        When no upper bound exists for a variable, use +inf\n%\n%\n% Additional inputs must be in the form of property/value pairs.\n%   Properties are character strings. They may be shortened\n%   to the extent that they are unambiguous. Properties are\n%   not case sensitive. Valid property names are:\n% \n%    'Plot', 'Nonlcon', 'FractionUsed', 'InitialSample',\n%    'OverSample', 'A', 'B' 'Options'\n%   \n%   All properties have default values, chosen as intelligently\n%   as I could manage. Values that are character strings may\n%   also be unambiguously shortened. The legal values for each\n%   property are:\n%   \n%   'Plot' - specifies if a plot is generated {'on', 'off'}\n%         A plot can only be generated for 1 or 2 dimensional\n%         problems. A warning is generated for more than 2\n%         variables if plot is turned on.\n%\n%         DEFAULT: 'off'\n% \n%   'Nonlcon' - Nonlinear constraint function or function handle\n%         Only used for 'fmincon' or 'fminsearchcon'. Other\n%         optimizers will cause an error if this is provided.\n%\n%         DEFAULT: ''\n%\n%   'FractionUsed' - Fractional amount of the total sample that\n%         are used as multiple starts for the optimizer. It must\n%         lie in the half open interval (0,1].\n%\n%         DEFAULT: 1  (100% of the samples are used as starting\n%         points.\n%\n%         Note: FractionUsed is ignored for fminbnd and fzero.\n%\n%   'InitialSample' - Size of the total initial random sample\n%         generated.\n%\n%         DEFAULT: 100  (100 points are generated)\n%\n%   'OverSample' - Over-sampling ratio. If linear inequality or\n%         or nonlinear inequality constraints are involved, a\n%         simple sampling strategy within the bounds may fail\n%         to produce as many feasible points as are requested.\n%\n%         Thus if 100 points are requested in the initial sample,\n%         a 20 to 1 oversampling ratio will generate a total of\n%         2000 initial samples that are all within the simple bound\n%         constraints. All of these points are compared to the\n%         inequality constraints, rejecting all of those that fail.\n%         The first InitialSample set of points are retained, only\n%         these points are considered as starting points for an\n%         optimization.\n%\n%         DEFAULT: 20  (a 20 to 1 over-sampling ratio)\n%\n%   'A', 'B' - Linear Inequality constraint matrix (A) and right\n%         hand side vector (B), used only for 'fmincon' or\n%         'fminsearchcon'. Other optimizers will cause an error\n%         if these are provided.\n%\n%   'Options' - options structure for the specified optimizer.\n%\n%        default: optimset('optname')\n%\n%        For fminsearchbnd or fminsearchcon, the default is\n%        optimset('fminsearch') \n%\n% arguments: (Output)\n%  xfinal - final solutions found for each xstart point. Each\n%         row of xfinal is one solution.\n%\n%  ffinal - objective function at xfinal.\n%\n%         For lsqnonlin or lsqcurvefit, ffinal is the sum\n%         of squares.\n%  \n%  exitflag - exitflags for each \"solution\" found\n%\n%  xstart - starting value used for each point in xfinal\n%\n%\n% Example usage:\n%  Find all zeros of besselj(2,x) betweeen x=0 and x=50. Note\n%  that x0 is actually ignored in this case. Generate a plot of\n%  the sample points and the solutions found.\n%\n%  fun = @(x) besselj(2,x);\n%  [xfinal,ffinal,exitflag,xstart] = rmsearch(fun,'fzero',...\n%       10,0,50,'initialsample',500,'plot','on')\n%\n% Example usage:\n%  Find local minimizers of besselj(2,x) betweeen x=0 and x=200\n%  Generate a plot of the sample points and the solutions found.\n%\n%  fun = @(x) besselj(2,x);\n%  [xfinal,ffinal,exitflag,xstart] = rmsearch(fun,'fminbnd',...\n%       10,0,200,'initialsample',500,'plot','on')\n%\n% Example usage:\n%  Find local minimizers of the peaks function. Generate\n%  a plot of the sample points and the solutions found. Use\n%  fminsearchbnd as the optimizer.\n%\n%  fun = inline('peaks(x(1),x(2))','x');\n%  [xfinal,ffinal,exitflag,xstart] = rmsearch(fun,'fminsearchbnd',...\n%      [0 0],[-5 -5],[5 5],'initialsample',100,'plot','on')\n%\n% Example usage:\n%  Find the local minimizers of the peaks function within a circle\n%  of radius 2 around the origin. Generate a plot of the sample points\n%  and the solutions found. Use fmincon as the optimizer, setting the\n%  appropriate options for its use. Note the trick with deal for nonlcon\n%  inside an anonymous function.\n%\n%  fun = inline('peaks(x(1),x(2))','x');\n%  opts = optimset('fmincon');\n%  opts.LargeScale = 'off';\n%  opts.Display = 'none';\n%  nonlcon = @(x) deal(norm(x) - 2,[]);\n%  [xfinal,ffinal,exitflag,xstart] = rmsearch(fun, ...\n%     'fmincon',[0 0],[-2 -2],[2 2],'initialsample',100, ...\n%     'plot','on','options',opts,'nonlcon',nonlcon)\n%\n%\n% See also: fminsearchbnd, fmincon, fminsearchcon, fzero, fminbnd, lsqnonlin\n%\n%\n% Author: John D'Errico\n% E-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 1/1/07\n\n% set defaults\npar.Plot = 'off';\npar.Nonlcon = '';\npar.FractionUsed = 1;\npar.InitialSample = 100;\npar.OverSample = 20;\npar.A = [];\npar.B = [];\npar.OptName = optname;\npar.Options = [];\n\nna = length(varargin);\nif (rem(na,2)==1)\n  error 'Property/value pairs must come as PAIRS of arguments.'\nelseif na>0\n  par = parse_pv_pairs(par,varargin);\nend\n\n% shape of x0, dimension of the problem\nif (nargin<3) || isempty(x0)\n  error 'x0 must be provided.'\nelse\n  par.Nx0 = size(x0);\n  x0 = x0(:);\n  par.Dim = prod(par.Nx0);\nend\n\n% checks for validity of parameters, any problems\npar = check_params(par);\n\n% Was fun a string, or an inline/anonymous function?\nif (nargin<1)\n  help rmsearch\n  return\nelseif isempty(fun)\n  error 'fun was not supplied.'\nelseif ischar(fun)\n  % a character function name\n  fun = str2func(fun);\nend\n\n% Check the bounds\nif (nargin<4) || isempty(LB)\n  LB = repmat(-inf,par.Dim,1);\nelse\n  LB = LB(:);\nend\nif (nargin<5) || isempty(UB)\n  UB = repmat(inf,par.Dim,1);\nelse\n  UB = UB(:);\nend\n% are they the same size as X0?\nif length(LB)~=par.Dim\n  error 'Lower bound array was inconsistent in size with x0'\nend\nif length(UB)~=par.Dim\n  error 'Upper bound array was inconsistent in size with x0'\nend\n\n% Were there any unusable inequalities provided?\nif ~ismember(par.OptName,{'fmincon','fminsearchcon'})\n  if par.UseLC\n    error(['Linear inequalities provided are not usable by ',par,OptName])\n  elseif par.UseNLC\n    error(['Nonlinear inequalities provided are not usable by ',par,OptName])\n  end\nend\n\n% are any of the bounds inconsistent?\nif any(LB>UB)\n  error 'It is required that: LB <= UB'\nend\n\n% Choose the distributions used to sample\n% from for each variable.\nLBinf=isinf(LB);\nUBinf=isinf(UB);\nfor i = 1:par.Dim\n  if LBinf(i) && UBinf(i)\n    % both are unbounded, use a normal\n    vardist(i).dist = 'normal';\n    vardist(i).mean = x0(i);\n    vardist(i).sd = 1;\n  elseif ~LBinf(i) && UBinf(i)\n    % only lower bound, use an exponential\n    vardist(i).dist = 'lower';\n    vardist(i).lambda = x0(i) - LB(i);\n    if vardist(i).lambda<=0\n      vardist(i).lambda = 0.5;\n    else\n      vardist(i).lambda = 0.5 ./(vardist(i).lambda);\n    end\n    vardist(i).shift = LB(i);\n  elseif LBinf(i) && ~UBinf(i)\n    % only upper bound, use an exponential\n    vardist(i).dist = 'upper';\n    vardist(i).lambda = UB(i) - x0(i);\n    if vardist(i).lambda <= 0\n      vardist(i).lambda = 0.5;\n    else\n      vardist(i).lambda = 0.5 ./(vardist(i).lambda);\n    end\n    vardist(i).shift = UB(i);\n  else\n    % dual bounds, use a uniform\n    vardist(i).dist = 'uniform';\n    vardist(i).a = LB(i);\n    vardist(i).b = UB(i);\n  end\nend\n\n% Generate the intial random samples. Choose enough\n% of them in case there are constraints to worry about.\nif par.UseLC || par.UseNLC\n  % oversampling for rejection\n  xinitial = rand(par.OverSample*par.InitialSample,par.Dim);\nelse\n  % No need to oversample\n  xinitial = rand(par.InitialSample,par.Dim);\nend\n\n% generate a sample with the specified distributions\nfor i = 1:par.Dim\n  switch vardist(i).dist\n    case 'uniform'\n      % uniform between two bounds\n      xinitial(:,i) = vardist(i).a + ...\n        (vardist(i).b - vardist(i).a)*xinitial(:,i);\n    case 'normal'\n      % unbounded - use a normal\n      xinitial(:,i) = vardist(i).mean + ...\n        vardist(i).sd*randn(par.InitialSample,1);\n    case 'lower'\n      % lower bound, use an exponential\n      xinitial(:,i) = vardist(i).shift - ...\n        log(xinitial(:,i))/vardist(i).lambda;\n    case 'upper'\n      % upper bound, use an exponential\n      xinitial(:,i) = vardist(i).shift + ...\n        log(xinitial(:,i))/vardist(i).lambda;\n  end\nend\n\n% if 1-d problem, fminbnd and fzero will both do best\n% if any bounds are included in the sample\nif (par.Dim == 1)\n  if ~isinf(LB) && ~isinf(UB)\n    xinitial = [LB;UB;xinitial];\n  elseif  (~isinf(LB) && isinf(UB))\n    xinitial = [LB;xinitial];\n  elseif (isinf(LB) && ~isinf(UB))\n    xinitial = [UB;xinitial];\n  end\nend\n\n% Do we need to reject any samples?\nif par.UseLC\n  k = ((repmat(par.B,1,size(xinitial,1)) - par.A*xinitial') < 0);\n  k = any(k,1);\n  xinitial(k,:) = [];\nend\nif size(xinitial,1)<1\n  error 'Linear inequalities too strict. No feasible points were identified.'\nend\nif par.UseNLC\n  % test any nonlinear constraints\n  nx = size(xinitial,1);\n  k = true(nx,1);\n  for i = 1:nx\n    [cineq,ceq] = par.Nonlcon(xinitial(i,:)); %#ok\n    k(i) = all(cineq>0);\n  end\n  % reject those that failed\n  xinitial(k,:) = [];\nend\nif size(xinitial,1)<1\n  error 'Nonlinear constraints too strict. No feasible points were identified.'\nend\n\n% Some points got through, but not as many as requested\nxsize = size(xinitial,1);\nif xsize < par.InitialSample\n  warning('RMSEARCH:FeasiblePoints',['Only ',num2str(xsize),' feasible points were found, ', ...\n    num2str(par.InitialSample),' were requested. Insufficiently Oversampled.'])\nend\n% keep as many samples as we need if oversampled\nxinitial = xinitial(1:min(xsize,par.InitialSample),:);\nxsize = size(xinitial,1);\n\n% Evaluate each sample through our objective function.\nfinitial = zeros(xsize,1);\nfor i = 1:xsize\n  if ~strcmp(par.OptName,'lsqnonlin')\n    % A simple optimizer:\n    % 'fminbnd', 'fzero', 'fmincon', 'fminsearchbnd', \n    % 'fminsearchcon','fminsearch'\n    finitial(i) = fun(reshape(xinitial(i,:),par.Nx0));\n  else\n    % lsqnonlin, so we need to form the sum of squares\n    f = fun(reshape(xinitial(i,:),par.Nx0));\n    finitial(i) = sum(f.^2);\n  end\nend\n\n% At which of these sample points will we\n% start the indicated optimizer? Was it a 1-d\n% problem? If so, then both fzero and fminbnd\n% use a bracketed interval.\nxfinal = zeros(size(xinitial));\nffinal = zeros(size(finitial));\nif (par.Dim==1) && ismember(par.OptName,{'fzero', 'fminbnd'})\n  switch par.OptName\n    case 'fzero'\n      % fzero - sort on x first\n      [xinitial,tags] = sort(xinitial);\n      finitial = finitial(tags);\n\n      % find zero crossings in f\n      ind = 1:(xsize-1);\n      k = find((sign(finitial(ind)) .* sign(finitial(ind+1))) <= 0);\n\n      % any crossings found?\n      if isempty(k)\n        error 'No zero crossings found in this sample for fzero'\n      end\n\n      xfinal = zeros(length(k),1);\n      ffinal = xfinal;\n      exitflag = xfinal;\n      xstart = xfinal;\n      fstart = xfinal;\n      % loop over the candidate intervals\n      for i = 1:length(k)\n        [xfinal(i),ffinal(i),exitflag(i)] = fzero(fun, ...\n          [xinitial(k(i)),xinitial(k(i)+1)],par.Options);\n\n        % store the better of the two points in each bracket\n        if abs(finitial(k(i))) <= abs(finitial(k(i)+1))\n          xstart(i) = xinitial(k(i));\n          fstart(i) = finitial(k(i));\n        else\n          xstart(i) = xinitial(k(i)+1);\n          fstart(i) = finitial(k(i)+1);\n        end\n      end\n\n    case 'fminbnd'\n      % fminbnd - sort on x first\n      [xinitial,tags] = sort(xinitial);\n      finitial = finitial(tags);\n\n      % find local minima in f\n      ind = 2:(xsize-1);\n      k = 1 + find((finitial(ind) <= finitial(ind-1)) & ...\n        (finitial(ind) <= finitial(ind+1)));\n\n      % do we look in the first interval?\n      if finitial(1) < finitial(2)\n        k = union(2,k);\n      end\n      % or the last one?\n      if finitial(end) < finitial(end-1)\n        k = union(xsize-1,k);\n      end\n\n      % any local minima found?\n      xfinal = zeros(length(k),1);\n      ffinal = xfinal;\n      exitflag = xfinal;\n      xstart = xfinal;\n      fstart = xfinal;\n      % loop over the candidate intervals\n      for i = 1:length(k)\n        [xfinal(i),ffinal(i),exitflag(i)] = fminbnd(fun, ...\n          xinitial(k(i)-1),xinitial(k(i)+1),par.Options);\n\n        % store in xstart\n        xstart(i) = xinitial(k(i));\n        fstart(i) = finitial(k(i));\n      end\n  end\nelse\n  % it must be a multivariable minimization, or only one\n  % variable, but not with a bracketed optimizer.\n  \n  % sort on f first in increasing order\n  [finitial,tags] = sort(finitial);\n  xinitial = xinitial(tags,:);\n  \n  if isempty(par.FractionUsed) || (par.FractionUsed==1)\n    % use all the points as starting values\n    nk = xsize;\n  else\n    nk = min(xsize,ceil(xsize*par.FractionUsed));\n  end\n  \n  % any local minima found?\n  xfinal = zeros(nk,par.Dim);\n  ffinal = zeros(nk,1);\n  exitflag = ffinal;\n  xstart = xfinal;\n  fstart = ffinal;\n  % loop over the candidates chosen\n  for i = 1:nk\n    % store the start points in xstart and\n    % fstart for plotting later\n    xstart(i,:) = xinitial(i,:);\n    fstart(i) = finitial(i);\n    \n    % but which optimizer?\n    switch par.OptName\n      case 'lsqnonlin'\n        [xfinal(i,:),ffinal(i),residual,exitflag(i)] = ...\n          lsqnonlin(fun,xinitial(i,:),LB,UB,par.Options); %#ok\n      case 'fminsearchbnd'\n        [xfinal(i,:),ffinal(i),exitflag(i)] = ...\n          fminsearchbnd(fun,xinitial(i,:),LB,UB,par.Options);\n      case 'fminsearchcon'\n        [xfinal(i,:),ffinal(i),exitflag(i)] = ...\n          fminsearchcon(fun,xinitial(i,:),LB,UB, ...\n          par.A,par.B,par.Nonlcon,par.Options);\n      case 'fminsearch'\n        [xfinal(i,:),ffinal(i),exitflag(i)] = ...\n          fminsearch(fun,xinitial(i,:),par.Options);\n      case 'fmincon'\n        [xfinal(i,:),ffinal(i),exitflag(i)] = ...\n          fmincon(fun,xinitial(i,:),par.A,par.B, ...\n          [],[],LB,UB,par.Nonlcon,par.Options);\n    end\n  end\nend\n\n% do we plot the results?\nif strcmp(par.Plot,'on') && par.Dim <= 2\n  switch par.Dim\n    case 1\n      % its a 1-d problem\n      figure\n      plot([xstart';xfinal'],[fstart';ffinal'],'g-')\n      hold on\n      plot(xfinal,ffinal,'ro')\n      plot(xinitial,finitial,'b+')\n      plot([xinitial(1),xinitial(end)],[0 0],'k:')\n      hold off\n      xlabel 'x'\n      ylabel 'fun(x)'\n      title(['Random multi-started search: ',par.OptName])\n      \n    case 2\n      % a 2-d problem\n      figure\n      C = finitial-min(finitial);\n      C = C/max(C);\n      colormap hsv\n      scatter3(xinitial(:,1),xinitial(:,2),finitial,50,C,'+')\n      hold on\n      plot3([xstart(:,1)';xfinal(:,1)'], ...\n        [xstart(:,2)';xfinal(:,2)'],[fstart';ffinal'],'g-')\n      plot3(xfinal(:,1),xfinal(:,2),ffinal,'ro')\n      hold off\n      xlabel 'x'\n      ylabel 'y'\n      zlabel 'fun([x,y])'\n      title(['Random multi-started search: ',par.OptName])\n      \n  end\nend\n\n% ============================================\n%     end of mainline rmsearch\n% ============================================\n\n% ============================================\n% subfunction - check_params\n% ============================================\nfunction par = check_params(par)\n% check the parameters for acceptability\n%\n% Defaults\n% par.Plot = 'off'\n% par.Nonlcon = '';\n% par.FractionUsed = 1;\n% par.InitialSample = 100;\n% par.OptName = optname;\n\n% Nonlcon == '' by default\nif ~isempty(par.Nonlcon)\n  if ischar(par.Nonlcon)\n    par.Nonlcon = str2func(par.Nonlcon);\n  end\n  par.UseNLC = true;\nelse\n  par.UseNLC = false;\nend\n\n% FractionUsed == 1 by default\nif isempty(par.FractionUsed)\n  par.FractionUsed = 1;\nelseif (length(par.FractionUsed)>1) || (par.FractionUsed<=0) || (par.FractionUsed>1)\n  error 'FractionUsed must be scalar, in the interval (0,1]'\nend\n\n% InitialSample == 100 by default\nif isempty(par.InitialSample)\n  par.InitialSample = 100;\nelseif (length(par.InitialSample)>1) || (par.InitialSample<=0)\n  error 'InitialSample must be positive and scalar'\nelse\n  par.InitialSample = ceil(par.InitialSample);\nend\n\n% OverSample == 20 by default\nif isempty(par.OverSample)\n  par.OverSample = 20;\nelseif (length(par.OverSample)>1) || (par.OverSample<1)\n  error 'OverSample must be positive and scalar, >= 1'\nend\n\n% OptName is char\nvalid = {'fmincon', 'fminsearchcon', 'fminsearchbnd', ...\n  'fminbnd', 'fzero', 'lsqnonlin', 'fminsearch'};\nif isempty(par.OptName) || ~ischar(par.OptName)\n  error 'Invalid OptName: Must be non-empty character'\nend\nind = strmatch(par.OptName,valid,'exact');\nif (length(ind)==1)\n  par.OptName = valid{ind};\nelse\n  ind = strmatch(par.OptName,valid);\n  if isempty(ind) || (length(ind)>1)\n    error(['Invalid OptName: ',par.OptName])\n  else\n    par.OptName = valid{ind};\n  end\nend\n% 2+ dimensions for a 1-d optimizer?\nif (par.Dim>1) && ismember(par.OptName,{'fminbnd', 'fzero'})\n  error '1-d optimizer specified, but more than 1 variable to optimize'\nend\n\n% Options is a struct\nif isempty(par.Options)\n  switch par.OptName\n    case 'fmincon'\n      par.options = optimset('fmincon');\n    case 'fzero'\n      par.options = optimset('fzero');\n    case 'fminbnd'\n      par.options = optimset('fminbnd');\n    case 'lsqnonlin'\n      par.options = optimset('lsqnonlin');\n    case {'fminsearch', 'fminsearchbnd', 'fminsearchcon'}\n      par.options = optimset('fminbnd');\n  end\nelseif ~isstruct(par.Options)\n  error 'If provided, Options must be a struct generated by optimset'\nend\n\n% Plot is char\nvalid = {'on', 'off'};\nif isempty(par.Plot)\n  error 'Invalid Plot: Must be character or empty'\nend\nind = find(strncmpi(par.Plot,valid,length(par.Plot)));\nif (length(ind)==1)\n  par.Plot = valid{ind};\nelse\n  error(['Invalid Plot: ',par.Plot])\nend\nif strcmp(par.Plot,'on') && (par.Dim>3)\n  % No plots available for 4 or more variables\n  Warning 'Sorry, plots are not generated for 4 or more variables.'\n  par.Plot = 'off';\nend\n\n% A & B are both empty by default\nif ~isempty(par.A) && (size(par.A,2)~=par.Dim)\n  error 'A must have the same number of columns as the # of variables'\nend\nif ~isempty(par.B) && (size(par.A,1)~=size(par.B,1))\n  error 'B must have the same number of rows as A'\nend\nif isempty(par.A)\n  par.UseLC = false;\nelse\n  par.UseLC = true;\nend\n\n\n\n\n% ============================================\n% Included subfunction - parse_pv_pairs\n% ============================================\nfunction params=parse_pv_pairs(params,pv_pairs)\n% parse_pv_pairs: parses sets of property value pairs, allows defaults\n% usage: params=parse_pv_pairs(default_params,pv_pairs)\n%\n% arguments: (input)\n%  default_params - structure, with one field for every potential\n%             property/value pair. Each field will contain the default\n%             value for that property. If no default is supplied for a\n%             given property, then that field must be empty.\n%\n%  pv_array - cell array of property/value pairs.\n%             Case is ignored when comparing properties to the list\n%             of field names. Also, any unambiguous shortening of a\n%             field/property name is allowed.\n%\n% arguments: (output)\n%  params   - parameter struct that reflects any updated property/value\n%             pairs in the pv_array.\n%\n% Example usage:\n% First, set default values for the parameters. Assume we\n% have four parameters that we wish to use optionally in\n% the function examplefun.\n%\n%  - 'viscosity', which will have a default value of 1\n%  - 'volume', which will default to 1\n%  - 'pie' - which will have default value 3.141592653589793\n%  - 'description' - a text field, left empty by default\n%\n% The first argument to examplefun is one which will always be\n% supplied.\n%\n%   function examplefun(dummyarg1,varargin)\n%   params.Viscosity = 1;\n%   params.Volume = 1;\n%   params.Pie = 3.141592653589793\n%\n%   params.Description = '';\n%   params=parse_pv_pairs(params,varargin);\n%   params\n%\n% Use examplefun, overriding the defaults for 'pie', 'viscosity'\n% and 'description'. The 'volume' parameter is left at its default.\n%\n%   examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world')\n%\n% params = \n%     Viscosity: 10\n%        Volume: 1\n%           Pie: 3\n%   Description: 'Hello world'\n%\n% Note that capitalization was ignored, and the property 'viscosity'\n% was truncated as supplied. Also note that the order the pairs were\n% supplied was arbitrary.\n\nnpv = length(pv_pairs);\nn = npv/2;\n\nif n~=floor(n)\n  error 'Property/value pairs must come in PAIRS.'\nend\nif n<=0\n  % just return the defaults\n  return\nend\n\nif ~isstruct(params)\n  error 'No structure for defaults was supplied'\nend\n\n% there was at least one pv pair. process any supplied\npropnames = fieldnames(params);\nlpropnames = lower(propnames);\nfor i=1:n\n  p_i = lower(pv_pairs{2*i-1});\n  v_i = pv_pairs{2*i};\n  \n  ind = strmatch(p_i,lpropnames,'exact');\n  if isempty(ind)\n    ind = find(strncmp(p_i,lpropnames,length(p_i)));\n    if isempty(ind)\n      error(['No matching property found for: ',pv_pairs{2*i-1}])\n    elseif length(ind)>1\n      error(['Ambiguous property name: ',pv_pairs{2*i-1}])\n    end\n  end\n  p_i = propnames{ind};\n  \n  % override the corresponding default in params\n  params = setfield(params,p_i,v_i); %#ok\n  \nend\n\n% end % parse_pv_pairs\n\n\n\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13733-rmsearch/RandomlyMultiStartedOptimizations/rmsearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.5822345636179415}}
{"text": "function [init_factors, init_factors_opts] = generate_init_factors(V, rank, options)\n% Initialization algorithm \n%\n% Created by H.Kasai on May 21, 2019\n%\n% Change log: \n%\n%\n%   May  21, 2019 (Hiroyuki Kasai): Created the initial version\n%\n%   Oct. 14, 2020 (H.Huangi): Added 'LPinit'\n%\n%   June. 20, 2022 (Hiroyuki Kasai): Modified to handle the case where one\n%                                   factorization matrix is input, and \n%                                   the other is not. \n\n    % V = WH + R\n\n    m = size(V, 1);\n    n = size(V, 2); \n\n    init_factors_opts = [];\n    \n    \n    \n    % initialize\n    generate_wh_init = true;\n    generate_r_init = true;    \n    \n    \n    %% generate W and H    \n    if isfield(options, 'x_init') \n        if isfield(options.x_init, 'W') && isfield(options.x_init, 'H')\n            init_factors.W = options.x_init.W;\n            init_factors.H = options.x_init.H;    \n            generate_wh_init = false;\n        elseif isfield(options.x_init, 'W') && ~isfield(options.x_init, 'H')\n            init_factors.W = options.x_init.W;\n            init_factors.H = rand(rank, n);\n            generate_wh_init = false;\n        elseif ~isfield(options.x_init, 'W') && isfield(options.x_init, 'H')\n            init_factors.W = rand(m, rank);\n            init_factors.H = options.x_init.H; \n            generate_wh_init = false;            \n        end        \n        \n        if isfield(options.x_init, 'R')\n            init_factors.R = options.x_init.R;\n            generate_r_init = false;\n        end\n    end\n\n\n    if isfield(options, 'special_init_factors')  \n\n        if generate_wh_init || generate_r_init      \n            [init_factors, init_factors_opts] = options.special_init_factors(V, rank, generate_wh_init, init_factors_opts, options);\n        end\n\n    else\n        \n    \n        if generate_wh_init\n            \n            if ~isfield(options, 'init_alg')\n                alg = 'random';\n            else\n                alg = options.init_alg;\n            end\n                \n            switch(alg)\n                \n                case 'LPinit'\n    \n                    H = LPinitSemiNMF(V, rank);\n                    W = V * pinv(H);\n                    \n                    init_factors.W = W;\n                    init_factors.H = H;             \n    \n                case 'random'\n    \n                    W = rand(m, rank);\n                    H = rand(rank, n);\n    \n                    init_factors.W = W;\n                    init_factors.H = H;  \n                    \n                case 'ones'\n                    \n                    W = ones(m, rank);\n                    H = ones(rank, n);\n    \n                    init_factors.W = W;\n                    init_factors.H = H;      \n                    \n                case 'semi_random' % for SemiNMF\n                    \n                    H = rand(rank, n);\n                    W = V / H; % V * inv(H)\n    \n                    init_factors.W = W;\n                    init_factors.H = H; \n                    \n                case 'symm'\n                    \n                    W = ones(m, rank);\n    \n                    init_factors.W = W;\n                    init_factors.H = W';  \n                    \n                case 'symm_mean'\n                    \n                    % make sure that entries of H fall into the interval [0, 2*sqrt(m/k)],\n                    % where 'm' is the average of all entries of V.\n                    % See https://github.com/dakuang/symnmf\n                    \n                    W = 2 * full(sqrt(mean(mean(V)) / rank)) * rand(m, rank);\n    \n                    init_factors.W = W;\n                    init_factors.H = W';  \n                    \n                case 'NNDSVD'\n                    \n                    [W, H] = NNDSVD(abs(V), rank, 0);      \n    \n                    init_factors.W = W;\n                    init_factors.H = H;  \n                    \n                case 'kmeans'\n                    \n                    [label, center] = litekmeans(V',rank, 'maxIter', 10);\n                    center = max(0,center);\n                    W = center';\n                    WTW = W'*W;\n                    WTW = max(WTW, WTW');\n                    WTX = W'*V;\n                    H = max(0, WTW\\WTX);\n                    \n                    init_factors.W = W;\n                    init_factors.H = H;      \n    \n                case {'prob_expectation', 'prob_random'}\n    \n    \n                    T = tn_vector();\n    \n                    if strcmp(alg, 'prob_random')\n                        E = exponential_dist();\n                    end\n    \n                    exp_U   = options.exp_U;\n                    exp_V   = options.exp_V;\n                    var_U   = options.var_U;\n                    var_V   = options.var_V;      \n                    mu_U    = options.mu_U;\n                    mu_V    = options.mu_V;             \n                    tau_U   = options.tau_U;\n                    tau_V   = options.tau_V;               \n    \n                    for k = 1 : rank\n                        for i = 1 : m\n                            tau_U(i, k) = 1;\n    \n                            if options.ard\n                                hyperparam = options.exp_lambdak(k);\n                            else\n                                hyperparam = options.hyperparams.lambdaU(i, k);\n                            end\n    \n                            if strcmp(alg, 'prob_random')\n                                mu_U(i, k) = E.exponential_draw(hyperparam);              \n                            else\n                                mu_U(i, k) = 1.0/hyperparam;\n                            end\n                        end\n                    end\n    \n                    for k = 1 : rank\n                        for j = 1 : n\n                            tau_V(j, k) = 1;\n    \n                            if options.ard\n                                hyperparam = options.exp_lambdak(k);\n                            else\n                                hyperparam = options.hyperparams.lambdaV(j, k);\n                            end\n    \n                            if strcmp(alg, 'prob_random')\n                                mu_V(j, k) = E.exponential_draw(hyperparam);              \n                            else\n                                mu_V(j, k) = 1.0/hyperparam;\n                            end\n                        end\n                    end   \n    \n                    for k = 1 : rank\n                        [exp_U, var_U] = update_exp(T, exp_U, var_U, mu_U, tau_U, k);\n                    end\n    \n                    for k = 1 : rank\n                        [exp_V, var_V] = update_exp(T, exp_V, var_V, mu_V, tau_V, k);\n                    end\n    \n    \n                    init_factors.W = exp_U;\n                    init_factors.H = exp_V';\n                    init_factors_opts.var_W = var_U;\n                    init_factors_opts.var_H = var_V';\n                    init_factors_opts.mu_W  = mu_U;\n                    init_factors_opts.mu_H  = mu_V';               \n                    init_factors_opts.tau_W = tau_U;\n                    init_factors_opts.tau_H = tau_V';            \n    \n                otherwise \n    \n                    % do random initialization \n    \n                    W = rand(m, rank);\n                    H = rand(rank, n);\n    \n                    init_factors.W = W;\n                    init_factors.H = H;                 \n    \n            end\n            \n        end\n        \n        if isfield(options, 'norm_w')\n            if options.norm_w ~= 0\n                % normalize W\n                init_factors.W = normalize_W(init_factors.W, options.norm_w);\n            end\n        end\n    \n        if isfield(options, 'norm_h')    \n            if options.norm_h ~= 0\n                % normalize H\n                init_factors.H = normalize_H(init_factors.H, options.norm_h);\n            end  \n        end\n        \n        \n        %% generate R\n        if generate_r_init    \n            if isfield(options, 'x_init_robust')     \n                if options.x_init_robust \n                    if isfield(options, 'x_init') \n                        if isfield(options.x_init, 'R')\n                            init_factors.R = options.x_init.R;\n                            generate_r_init = false;\n                        end\n                    end\n    \n                    if generate_r_init\n                        init_factors.R = rand(m, n);\n                    end\n                else\n                    init_factors.R = zeros(m, n);\n                end\n            else\n                init_factors.R = zeros(m, n);\n            end\n        end\n    \n    end\nend\n\n\nfunction [exp_A, var_A] = update_exp(T, exp_A, var_A, mu_A, tau_A, k)\n\n    exp_A(:,k) = T.expectation(mu_A(:,k), tau_A(:,k));\n    var_A(:,k) = T.variance(mu_A(:,k), tau_A(:,k));\n    \nend\n\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/auxiliary/initialization/generate_init_factors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.5822345564379147}}
{"text": "% -*- INTERNAL UNDOCUMENTED FUNCTION -*-\n%\n% Copyright (C) 2010 Carlo de Falco\n% Copyright (C) 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 Octave; see the file COPYING.  If not, see\n% <http://www.gnu.org/licenses/>.\n\nfunction [Jinv, geo_inv_der2] = geopdes_inv_der2__ (geo_map_jac, geo_map_der2)\n\nvsize = size (geo_map_jac);\nvsize(end+1:4) = 1;\n\nrdim = vsize(1);\nndim = vsize(2);\n\nJinv = geopdes_inv__ (geo_map_jac);\nJinv = reshape (Jinv, [ndim, rdim, vsize(3:end)]);\nJsize = size (Jinv);\nJsize(end+1:4) = 1;\n\nJinv1 = reshape (Jinv, [1, Jsize]);\nJinv2 = permute (Jinv1, [1 3 2 4:numel(Jsize)+1]);\nJinv3 = permute (Jinv1, [3 2 1 4:numel(Jsize)+1]);\n\ngeo_inv_der2 = zeros ([ndim, rdim, rdim, vsize(3:end)]);\n\nfor alp = 1:ndim\n  for idim = 1:rdim\n    for jdim = 1:rdim\n      aux1 = sum (bsxfun (@times, geo_map_der2, Jinv1(:,:,idim,:,:)), 2);\n      aux2 = sum (bsxfun (@times, aux1, Jinv2(:,jdim,:,:,:)), 3);\n      aux3 = sum (bsxfun (@times, aux2, Jinv3(:,alp,:,:,:)), 1);\n      \n      geo_inv_der2(alp,idim,jdim,:,:) = -reshape (aux3, vsize(3:end));\n    end\n  end\nend\n\nend\n\n%!test \n%!\n%! %% x = u^2 + u + 1 \n%! %% y = v^2 + v + 1 \n%!\n%! xufun = @(u, v) (2*u + 1);\n%! xvfun = @(u, v) (0*u);\n%! yufun = @(u, v) (0*u);\n%! yvfun = @(u, v) (2*v + 1);\n%!\n%! xuufun = @(u, v) (2+0*u);\n%! xuvfun = @(u, v) (0*u);\n%! xvvfun = @(u, v) (0*u);\n%!\n%! yuufun = @(u, v) (0*u);\n%! yuvfun = @(u, v) (0*u);\n%! yvvfun = @(u, v) (2+0*v);\n%!\n%! uxfun = @(u, v) (1./(2*u+1));\n%! vyfun = @(u, v) (1./(2*v+1));\n%! uxxfun = @(u, v) (-2./(2*u+1).^3);\n%! vyyfun = @(u, v) (-2./(2*v+1).^3);\n%!\n%! u = linspace (0,1, 10);\n%! v = linspace (0,1, 10);\n%! %u = rand (1, 10);\n%! %v = rand (1, 10);\n%! geo_map_jac(1,1,:) = xufun(u,v);\n%! geo_map_jac(1,2,:) = xvfun(u,v);\n%! geo_map_jac(2,1,:) = yufun(u,v);\n%! geo_map_jac(2,2,:) = yvfun(u,v);\n%!\n%! geo_map_der2(1,1,1,:) = xuufun(u,v);\n%! geo_map_der2(1,1,2,:) = xuvfun(u,v);\n%! geo_map_der2(1,2,1,:) = xuvfun(u,v);\n%! geo_map_der2(1,2,2,:) = xvvfun(u,v);\n%! geo_map_der2(2,1,1,:) = yuufun(u,v);\n%! geo_map_der2(2,1,2,:) = yuvfun(u,v);\n%! geo_map_der2(2,2,1,:) = yuvfun(u,v);\n%! geo_map_der2(2,2,2,:) = yvvfun(u,v);\n%!\n%! [Jinv, geo_inv_der2] = geopdes_inv_der2__ (geo_map_jac, geo_map_der2);\n%! assert (uxfun (u, v), reshape (Jinv(1,1,:), 1, numel(u)), 1e-14)\n%! assert (vyfun (u, v), reshape (Jinv(2,2,:), 1, numel(u)), 1e-14)\n%! assert (uxxfun (u, v), reshape (geo_inv_der2(1,1,1,:), 1, numel(u)), 1e-14)\n%! assert (vyyfun (u, v), reshape (geo_inv_der2(2,2,2,:), 1, numel(u)), 1e-14)", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/utils/geopdes_inv_der2__.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5822345538714301}}
{"text": "% Identical to isomapEmbed without the last part which sometimes causes exceptions\n\nfunction [X, sigma2] = isomap2Embed(Y, dims)\n\n% ISOMAP2EMBED Embed data set with Isomap.\n\n% SHEFFIELDML\n\n% Note: isomap code uses the transpose of a design matrix.\nif any(any(isnan(Y)))\n  error('Cannot initialise gplvm using isomap when missing data is present.')\nelse\n  D = L2_distance(Y', Y', 1);\n  options.dims = 1:dims;\n  neighbours = 7;\n   options.display = 0;\n\n  [Xstruct, sigma2, E] = Isomap(D, 'k', neighbours, options);\n  X = zeros(size(Y, 1), dims);\n  if length(Xstruct.index) ~= size(Y, 1)\n    % We don't really deal with this problem correctly here ...\n    warning('Isomap graph is not fully connected');\n  end\n  X(Xstruct.index, :) = Xstruct.coords{dims}';\n  % Rescale X so that variance is 1 and mean is zero.\n  meanX = mean(X);\n  X = X-ones(size(Y, 1), 1)*meanX;\n  varX = var(X);\n  X = X*diag(sqrt(1./varX));\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/isomap2Embed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5821970187330773}}
{"text": "function combo_test33 ( )\n\n%*****************************************************************************80\n%\n%% COMBO_TEST33 tests RGF_G_TABLE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 July 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 6;\n\n  fprintf ( 1, ' \\n' );\n  fprintf ( 1, 'COMBO_TEST33\\n' );\n  fprintf ( 1, '  RGF_G_TABLE tabulates generalized restricted\\n' );\n  fprintf ( 1, '  growth functions.\\n' );\n  fprintf ( 1, ' \\n' );\n\n  offset = 1;\n\n  d = rgf_g_table ( m );\n\n  for i = 0 : m\n    for j = 0 : m - i\n      fprintf ( 1, '%6d', d(i+offset,j+offset) );\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/combo/combo_test33.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.5821968279608578}}
{"text": "function [min] = hr2min(hr)\n% Convert time from hours to minutes.\n% Chad A. Greene 2012\nmin = hr*60;", "meta": {"author": "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/hr2min.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031738152021788, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.5821968156961459}}
{"text": "function [D, dist, aLongestString] = LCS(X,Y)\n%%%Calculates the longest common substring between to strings.\n%%%Code written by David Cumin\n%%%email: d.cumin@auckland.ac.nz\n%%%INPUT\n%%%X, Y - both are strings e.g. 'test' or 'stingtocompare'\n%%%OUTPUT\n%%%D is the substring over the length of the shortest string\n%%%dist is the length of the substring\n%%%aLongestString is a sting of length dist (only one of potentially many)\n\n%%%For example\n%%% X = 'abcabc';\n%%% Y = 'adcbac';\n%%% [D dist str] = LCS(X,Y);\n%%% results in:\n%%% D = 0.6667 \n%%% dist = 4\n%%% str = acbc\n%%% this is seen for X: 'a-c-bc' and Y: 'a-cb-c'\n\n%%%Make matrix\nn =length(X);\nm =length(Y);\nL=zeros(n+1,m+1);\nL(1,:)=0;\nL(:,1)=0;\nb = zeros(n+1,m+1);\nb(:,1)=1;%%%Up\nb(1,:)=2;%%%Left\n\nfor i = 2:n+1\n    for j = 2:m+1\n        if (X(i-1) == Y(j-1))\n            L(i,j) = L(i-1,j-1) + 1;\n            b(i,j) = 3;%%%Up and left\n        else\n            L(i,j) = L(i-1,j-1);\n        end\n        if(L(i-1,j) >= L(i,j))\n            L(i,j) = L(i-1,j);\n            b(i,j) = 1;%Up\n        end\n        if(L(i,j-1) >= L(i,j))\n            L(i,j) = L(i,j-1);\n            b(i,j) = 2;%Left\n        end\n    end\nend\nL(:,1) = [];\nL(1,:) = [];\nb(:,1) = [];\nb(1,:) = [];\ndist = L(n,m);\n\nD = (dist / min(m,n));\nif(dist == 0)\n    aLongestString = '';\nelse\n    %%%now backtrack to find the longest subsequence\n    i = n;\n    j = m;\n    p = dist;\n    aLongestString = {};\n    while(i>0 && j>0)\n        if(b(i,j) == 3)\n            aLongestString{p} = X(i);\n            p = p-1;\n            i = i-1;\n            j = j-1;\n        elseif(b(i,j) == 1)\n            i = i-1;\n        elseif(b(i,j) == 2)\n            j = j-1;\n        end\n    end\n\n    if ischar(aLongestString{1})\n        aLongestString = char(aLongestString)';\n    else\n        aLongestString = cell2mat(aLongestString);\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/24559-longest-common-subsequence/LCS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.582196811583216}}
{"text": "function unique_index = i4vec_unique_index ( n, a )\n\n%*****************************************************************************80\n%\n%% I4VEC_UNIQUE_INDEX indexes the first occurrence of values in an I4VEC.\n%\n%  Discussion:\n%\n%    For element A(I) of the vector, FIRST_UNIQUE(I) is the uniqueness index\n%    of A(I).  That is, if A_UNIQUE contains the unique elements of A, \n%    gathered in order, then \n%\n%      A_UNIQUE ( UNIQUE_INDEX(I) ) = A(I)\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    24 August 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the number of elements of A.\n%\n%    Input, integer A(N), the array.\n%\n%    Output, integer UNIQUE_INDEX(N), the unique index.\n%\n  unique_index(1:n) = -1;\n  unique_num = 0;\n\n  for i = 1 : n\n\n    if ( unique_index(i) == -1 )\n\n      unique_num = unique_num + 1;\n      unique_index(i) = unique_num;\n\n      for j = i + 1 : n\n        if ( a(i) == a(j) )\n          unique_index(j) = unique_num;\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/i4lib/i4vec_unique_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.5821967969131218}}
{"text": "function [Sl1, Sl2, Jac] = deformation_field_3d_analysis(Tr, pixel_resolution)\n% calculates sliding amount jacobian and other parameters of transformation\n% Tr should be given in physical units (mm)!\n\ndT = cell(3,3);\nsz = size(Tr);\n[m1,m2,m3] = ndgrid(1:sz(1), 1:sz(2), 1:sz(3));\nmm{1} = m1;\nmm{2} = m2;\nmm{3} = m3;\nfor i1 = 1 : 3\n    for i2 = 1: 3\n        tmp = Tr(:,:,:,i1)+mm{i1}*pixel_resolution(i1);\n        dT{i1,i2} = DGradient(tmp, [], i2) / pixel_resolution(i2);\n    end\nend\n\n% EV = zeros([3, sz(1), sz(2), sz(3)]);\nSl1 = zeros([sz(1), sz(2), sz(3)]);\nSl2 = zeros([sz(1), sz(2), sz(3)]);\nJac = zeros([sz(1), sz(2), sz(3)]);\nfor i3 = 1 : sz(3)\nfor i2 = 1 : sz(2)\nfor i1 = 1 : sz(1)\n    \n    mat = [dT{1,1}(i1,i2,i3), dT{1,2}(i1,i2,i3), dT{1,3}(i1,i2,i3);...\n           dT{2,1}(i1,i2,i3), dT{2,2}(i1,i2,i3), dT{2,3}(i1,i2,i3);...\n           dT{3,1}(i1,i2,i3), dT{3,2}(i1,i2,i3), dT{3,3}(i1,i2,i3); ];\n    \n    mat_sym = mat'*mat;\n    \n    v = eig(mat_sym);\n    v = sort(v);\n    v = sqrt(abs(v));\n    Sl1(i1,i2,i3) = (v(3)-v(1))/2;\n    Sl2(i1,i2,i3) = v(3)/(v(2) + v(1));\n    Jac(i1,i2,i3) = det(mat);\nend\nend\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/image_registration_utils/deformation_field_3d_analysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5820932046027287}}
{"text": "function dimacs = computedimacs(b,c,A,xin,y,s,K);\n% COMPUTEDIMACS\n%\n% min <C,X> s.t     AX = b, X > 0\n% max b'y   s.t S-C+A'y =0, S > 0\n\n% If no primal exist, fake till later\nif isempty(xin)\n    x = c*0;\nelse\n    x = xin;\nend\n\nif isempty(s)\n    s = c-A'*y;\nend\n\nxres = inf;\nsres = inf;\n\n% Not officially defined in DIMACS\nif K.f>0\n    sres = -min(norm(s(1:K.f),inf));\nend\n\n% Errors in linear cone\nif K.l>0\n    xres = min(x(1+K.f:K.f+K.l));\n    sres = min(s(1+K.f:K.f+K.l));\nend\n\n% Errors in quadratic cone\nif any(K.q)\n    top = K.f+K.l;\n    for i = 1:length(K.q)\n        X = x(1+top:top+K.q(i));\n        S = s(1+top:top+K.q(i));\n        xres = min(xres,X(1)-norm(X(2:end)));\n        sres = min(sres,S(1)-norm(S(2:end)));\n        top = top + K.q(i);\n    end\nend\n\n% Errors in semidefinite cone\nif any(K.s)\n    top = K.f+K.l+K.q+K.r;\n    for i = 1:length(K.s)\n        X = reshape(x(1+top:top+K.s(i)^2),K.s(i),K.s(i));\n        S = reshape(s(1+top:top+K.s(i)^2),K.s(i),K.s(i));\n        xres = min(xres,min(eig(full(X))));\n        sres = min(sres,min(eig(full(S))));\n        top = top + K.s(i)^2;\n    end\nend\n\nerr1 = norm(b-A*x)/(1 + norm(b,inf));\nerr2 = max(0,-xres)/(1 + norm(b,inf));\nerr3 = conenorm(s-(c-A'*y),K)/(1+norm(c,inf));\n%err3 = norm(s-(c-A'*y))/(1+norm(c,inf)); % Used by some solvers\nerr4 = max(0,-sres)/(1+max(abs(c)));\nerr5 = (c'*x-b'*y)/(1+abs(c'*x)+abs(b'*y));\nerr6 = x'*(c-A'*y)/(1+abs(c'*x)+abs(b'*y));\n\n% No primal was computed\nif isempty(xin)\n    err1 = nan;\n    err2 = nan;\n    err5 = nan;\n    err6 = nan;\nend\ndimacs = [err1 err2 err3 err4 err5 err6];\n\nfunction t = conenorm(s,K)\n\n% Implementation of the norm described on\n% http://plato.asu.edu/dimacs/node3.html\n\nt = 0;\n\nif K.f + K.l>0\n    t = t + norm(s(1:K.f+K.l));\nend\n\ntop = 1+K.f+K.l;\nif any(K.q)\n    for i = 1:length(K.q)\n        t = t + norm(s(top:top+K.q(i)-1));\n        top  = top + K.q(i);\n    end\nend\n\nif any(K.s)\n    for i = 1:length(K.s)\n        S = reshape(s(top:top+K.s(i)^2-1),K.s(i),K.s(i));\n        t = t + norm(S,'fro');\n        top  = top + K.s(i)^2;\n    end\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/computedimacs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.582043461220613}}
{"text": "function a = r8ri_to_r8ge ( nz, ija, sa, n )\n\n%*****************************************************************************80\n%\n%% R8RI_TO_R8GE converts an R8RI matrix to R8GE form.\n%\n%  Discussion:\n%\n%    An R8RI matrix is in row indexed sparse storage form.\n%\n%    A R8GE matrix is in general storage.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    19 January 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    William Press, Brian Flannery, Saul Teukolsky, William Vetterling,\n%    Numerical Recipes in FORTRAN: The Art of Scientific Computing,\n%    Third Edition,\n%    Cambridge University Press, 2007,\n%    ISBN13: 978-0-521-88068-8,\n%    LC: QA297.N866.\n%\n%  Parameters:\n%\n%    Input, integer NZ, the size required for the RI\n%    or \"row indexed\" sparse storage.\n%\n%    Input, integer IJA(NZ), the index vector.\n%\n%    Input, real SA(NZ), the value vector.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Output, real A(N,N), the matrix stored in GE \n%    or \"general\" format.\n%\n  a = zeros ( n, n );\n\n  for k = 1 : n\n    i = k;\n    j = k;\n    a(i,j) = sa(k);\n  end\n\n  for i = 1 : n\n    for k = ija(i) : ija(i+1) - 1\n      j = ija(k);\n      a(i,j) = sa(k);\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/r8ri_to_r8ge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.5819831171667345}}
{"text": "%   SCRIPT TO COMPUTE THE TORQUES AT EACH JOINT FOR DIFFERENT MOTION STATES OF\n%   THE ARM.\n%   \n\nfunction motor_selection\n\nclose all\nglobal robot\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% PARAMETERS SECTION\n%   Feel free to change the values of q, maximum_speeds and \n%   maximum_accels. \n%  \n%   This script tries to allow the student to test any mechanism\n%   at the worst case. In this sense, q should be adjusted \n%   as the pose where each joint would (statically) be needing a\n%   higher torque.\n%   The maximum_speeds and maximum_acceleration define a trapezoidal\n%   speed profile. This trapezoidal speed is used by most machines\n%   to command changes in speed in any of their joints.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\necho on\n%LOAD ANY ROBOT YOU WOULD LIKE TO ANALYZE\n%EXPERIMENTA CAMBIANDO EL ROBOT Y VIENDO LOS RESULTADOS!\nrobot = load_robot('ABB', 'IRB2600');\necho off\n\n% robot pose: experiment by changing the pose while observing the different\n%             torques at each joint\nq=[0 pi/2 -pi/2 0 0 0]; %rad\n\n%Velocidad maxima en cada articulacion en rad/s.\n% robot.velmax = [deg2rad(175); %Axis 1, rad/s\n%                 deg2rad(175); %Axis 2, rad/s\n%                 deg2rad(175); %Axis 3, rad/s\n%                 deg2rad(360); %Axis 4, rad/s\n%                 deg2rad(360); %Axis 5, rad/s\n%                 deg2rad(500)];%Axis 6, rad/s\n            \nmaximum_speeds=[3.5 3.5 3.5 6.5 6.5 8.5];%rad/second\n\n%maximum acceleration/deceleration for each joint\n\nmaximum_accels=maximum_speeds*2; %rad/second^2\n%maximum_accels=[5 5 6 7 8 9];\n\n% time of the trapezoidal profile that the joint moves at maximum speed\ntime_at_constant_speed=0.4; %seconds\n\n\n%load robot parameters. Just uncomment this line\n\ndrawrobot3d(robot, q)\n\n%START BY COMPUTING TORQUES AT G\n%    robot.motors.G = [1 1 1 1 1 1 ]\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%  FIRST, COMPUTE TRAPEZOIDAL PROFILES\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%compute acceleration plus deceleration times for every joint\ntime_acc = 2*maximum_speeds./maximum_accels+time_at_constant_speed;\n\n%compute the total time for the slowest joint\ntotal_time=max(time_acc);\n\n% Trapezoidal speed profiles for each joint\n[input_speeds, input_accels, time]=build_trapezoidal_speed_profile(maximum_speeds, maximum_accels, total_time);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% FINALLY, COMPUTE TORQUES FOR EACH MOTION STATE. \n% Please note that we consider that the robot is placed at a fixed position and consider\n% different motion situations when we change the acceleration and speed at\n% each joint. For each motion state, the inverse dynamic model returns the\n% torques at each joint that would bring the robot to that motion.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ncompute_inverse_dynamics(q, input_speeds, input_accels, time);\n\n\n  fprintf('\\n\\nOBSERVE THE PLOTS AND NOTE DOWN THE PEAK TORQUE, NOMINAL TORQUE AND MOTOR SPEEDS')\nfprintf('\\nNOW COMPUTE THE TORQUES FOR 5 DIFFERENT SELECTED MOTIONS STATES')\nfprintf('\\nPRESS ANY KEY TO CONTINUE...')\n\npause\n\n% NOW COMPUTE THE WORST CASE CONSIDERING ONLY THE SPEED AND ACCELERATION AT\n% 5 MOTIONS STATES\ninput_speeds = [zeros(6,1) maximum_speeds' maximum_speeds' maximum_speeds' zeros(6,1) ];\ninput_accels = [maximum_accels' maximum_accels' zeros(6,1) -maximum_accels' -maximum_accels' ];\n\ncompute_inverse_dynamics(q, input_speeds, input_accels, [1:5]);\n\n\n\n\n%Computes a trapezoidal speed profile for every joint given maximum\n%permitted accelerations and maximum joint speeds\nfunction [input_speeds, input_accelerations, time]=build_trapezoidal_speed_profile(maximum_speeds, maximum_accels, total_time)\n\ndelta_time=0.01;\n\n%build time vector: twice acceleration time plus time at constant speed\ntime = 0:delta_time:total_time;\n\ninput_speeds=[];\ninput_accelerations=[];\n\nfor j=1:length(maximum_speeds), \n    vel_row=[];\n    acc_row=[];\n    for i=1:length(time), \n        [vel acc] = compute_values(time(i), maximum_speeds(j), maximum_accels(j), total_time);\n        vel_row = [vel_row vel];\n        acc_row = [acc_row acc];        \n    end\n    input_speeds = [input_speeds; vel_row];\n    input_accelerations = [input_accelerations; acc_row];    \nend\n\n\n\n\n%returns the values of velocity and speed corresponding to a given time\nfunction [vel acc]=compute_values(time_i, vel_max, acc_max, total_time)\n\ntacc = vel_max/acc_max;\ntdec = total_time-tacc;\n\nif time_i < tacc\n    vel = time_i.*acc_max;\n    acc = acc_max;\n    return;\nelseif (time_i >= tacc) & (time_i < tdec)\n    vel = vel_max;\n    acc = 0;\n    return;\nelse % time_i> tdec\n    vel = vel_max-(time_i-tdec)*acc_max;\n    acc = -acc_max;    \nend\n \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   COMPUTE THE INVERSE DYNAMICS FOR EACH MOTION STATE\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction compute_inverse_dynamics(q, input_speeds, input_accels, time)\nglobal robot\n\n%adjust_view(robot)\ntorques=[];\nfor j=1:length(time), \n    fprintf('\\nComputing time %d out of %d', j, length(time));\n    % compute the torque to bring the robot instantaneously to this motion\n    % state. change M=1  to add the effects of a 1kg mass load at the end effector\n    M=20;\n    %please note that the force due to the load acts on the z axis of\n    tau=inversedynamic(robot, q, input_speeds(:,j), input_accels(:,j), [0  0 -9.81]', [ 0  0 -M 0 0 0 ]');\n    torques=[torques tau];\nend\n \n\n%plot trapezoidal profiles\nfigure, hold, xlabel('time (s)'), ylabel('Input reference speeds (rad/s)')\nplot(time, input_speeds(1,:), time, input_speeds(2,:), time, input_speeds(3,:),...\n        time, input_speeds(4,:), time, input_speeds(5,:), time, input_speeds(6,:));\nlegend('Speed for joint 1 (qd1)','Speed for joint 2 (qd2)','Speed for joint 3 (qd3)',... \n   'Speed for joint 4 (qd4)','Speed for joint 5 (qd5)','Speed for joint 6 (qd6)' )\n%plot trapezoidal profiles, acceleration\nfigure, hold, xlabel('time (s)'), ylabel('Input reference acceleration (rad/s)')\nplot(time, input_accels(1,:), time, input_accels(2,:), time, input_accels(3,:),...\n        time, input_accels(4,:), time, input_accels(5,:), time, input_accels(6,:));\nlegend('Acceleration for joint 1 (qd1)','Acceleration for joint 2 (qd2)','Acceleration for joint 3 (qd3)',... \n   'Acceleration for joint 4 (qd4)','Acceleration for joint 5 (qd5)','Acceleration for joint 6 (qd6)' )\n\n\n% plot results. First, torques at each joint\nfigure, hold, xlabel('time (s)'), ylabel('Join Torques (N m)')\nplot(time, torques(1,:), time, torques(2,:), time, torques(3,:),...\n        time, torques(4,:), time, torques(5,:), time, torques(6,:));\nlegend('Torque for joint 1 ','Torque  for joint 2 ','Torque  for joint 3 ',... \n   'Torque  for joint 4','Torque  for joint 5 ','Torque  for joint 6 ' )\n\n%plot torques at each motor\nfigure, hold, xlabel('time (s)'), ylabel('Motor Torques (N m)')\nplot(time, torques(1,:)/robot.motors.G(1), time, torques(2,:)/robot.motors.G(2), time, torques(3,:)/robot.motors.G(3),...\n        time, torques(4,:)/robot.motors.G(4), time, torques(5,:)/robot.motors.G(5), time, torques(6,:)/robot.motors.G(6));\nlegend('Torque at motor 1 ','Torque at motor 2 ','Torque at motor 3 ',... \n   'Torque at motor 4 ','Torque at motor 5 ','Torque at motor 6 ' )\n\n%plot power needed by the motor at each time step, without considering the\n%losses at the gears\nfigure, hold, xlabel('time (s)'), ylabel('Power needed by each motor (W)')\nplot(time, torques(1,:).*input_speeds(1,:), time, torques(2,:).*input_speeds(2,:), time, torques(3,:).*input_speeds(3,:),...\n        time, torques(4,:).*input_speeds(4,:), time, torques(5,:).*input_speeds(5,:), time, torques(6,:).*input_speeds(6,:));\nlegend('Power: motor 1','Power: motor 2','Power: motor 3',... \n   'Power: motor 4','Power: motor 5','Power: motor 6' )\n\n%plot motor speed in rpm for each motor\nfigure, hold, xlabel('time (s)'), ylabel('Speed in r.p.m of every motor (rev/min)')\nplot(time, robot.motors.G(1)*input_speeds(1,:)*30/pi, time, robot.motors.G(2)*input_speeds(2,:)*30/pi, time, robot.motors.G(3)*input_speeds(3,:)*30/pi,...\n        time, robot.motors.G(4)*input_speeds(4,:)*30/pi, time, robot.motors.G(5)*input_speeds(5,:)*30/pi, time, robot.motors.G(6)*input_speeds(6,:)*30/pi);\nlegend('Speed at motor 1 (qd1*G)','Speed at motor 2 (qd2*G)','Speed at motor 3 (qd3*G)',... \n   'Speed at motor 4 (qd4*G)','Speed at motor 5 (qd5*G)','Speed at motor 6 (qd6*G)' )\n\n\n\n%Now present results:\nfprintf('\\nMAIN RESULTS (referred to each motor): ')\nfprintf('\\n------------------------------------------------------------------------------------ ')\nfprintf('\\n                         Joint 1 - Joint 2 - Joint 3 - Joint 4  - Joint 5 - Joint 6: ')\nfprintf('\\nPeak Torque (N\ufffdm):        %.3f     %.3f     %.3f     %.3f      %.3f    %.3f ', max(abs(torques(1,:)/robot.motors.G(1))), max(abs(torques(2,:)/robot.motors.G(2))) , max(abs(torques(3,:)/robot.motors.G(3))) , max(abs(torques(4,:)/robot.motors.G(4))) , max(abs(torques(5,:)/robot.motors.G(5))) , max(abs(torques(6,:)/robot.motors.G(6))))\nfprintf('\\nNominal Torque (N\ufffdm):     %.3f     %.3f     %.3f     %.3f      %.3f    %.3f  ', abs(torques(1,round(length(torques)/2))/robot.motors.G(1)), abs(torques(2,round(length(torques)/2))/robot.motors.G(2)), abs(torques(3,round(length(torques)/2))/robot.motors.G(3))...\n    , abs(torques(4,round(length(torques)/2))/robot.motors.G(4)), abs(torques(5,round(length(torques)/2))/robot.motors.G(5)), abs(torques(6,round(length(torques)/2))/robot.motors.G(6)))\nfprintf('\\nMax motor speed (r.p.m.):   %.1f     %.1f     %.1f     %.1f      %.1f    %.1f  ', max(abs(robot.motors.G(1)*input_speeds(1,:))*30/pi), max(abs(robot.motors.G(2)*input_speeds(2,:))*30/pi), max(abs(robot.motors.G(3)*input_speeds(3,:))*30/pi)...\n    ,max(abs(robot.motors.G(4)*input_speeds(4,:))*30/pi), max(abs(robot.motors.G(5)*input_speeds(5,:))*30/pi), max(abs(robot.motors.G(6)*input_speeds(6,:))*30/pi))\nfprintf('\\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/ABB/IRB2600/motor_selectionIRB2600.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.5819831171667343}}
{"text": "function [ undx, xdnu ] = r8col_tol_undex ( m, n, a, unique_num, tol )\n\n%*****************************************************************************80\n%\n%% R8COL_TOL_UNDEX indexes tolerably unique entries of an R8COL.\n%\n%  Discussion:\n%\n%    An R8COL is an M x N array of R8 values, regarded as N columns\n%    each of M R8 values.\n%\n%    The goal of this routine is to determine a vector UNDX,\n%    which points to the unique elements of A, in sorted order,\n%    and a vector XDNU, which identifies, for each entry of A, the index of\n%    the unique sorted element of A.\n%\n%    This is all done with index vectors, so that the elements of\n%    A are never moved.\n%\n%    The first step of the algorithm requires the indexed sorting\n%    of A, which creates arrays INDX and XDNI.  (If all the entries\n%    of A are unique, then these arrays are the same as UNDX and XDNU.)\n%\n%    We then use INDX to examine the entries of A in sorted order,\n%    noting the unique entries, creating the entries of XDNU and\n%    UNDX as we go.\n%\n%    Once this process has been completed, the object A could be\n%    replaced by a compressed object XU, containing the unique entries\n%    of A in sorted order, using the formula\n%\n%      XU(1:UNIQUE_NUM) = A(UNDX(1:UNIQUE_NUM)).\n%\n%    We could then, if we wished, reconstruct the entire vector A, or\n%    any element of it, by index, as follows:\n%\n%      A(I) = XU(XDNU(I)).\n%\n%    We could then replace A by the combination of XU and XDNU.\n%\n%    Later, when we need the I-th entry of A, we can locate it as\n%    the XDNU(I)-th entry of XU.\n%\n%    Here is an example of a vector A, the sort and inverse sort\n%    index vectors, and the unique sort and inverse unique sort vectors\n%    and the compressed unique sorted vector.\n%\n%      I    A   Indx  Xdni      XU   Undx  Xdnu\n%    ----+-----+-----+-----+--------+-----+-----+\n%      1 : 11.     1     1 :    11.     1     1\n%      2 : 22.     3     5 :    22.     2     2\n%      3 : 11.     6     2 :    33.     4     1\n%      4 : 33.     9     8 :    55.     5     3\n%      5 : 55.     2     9 :                  4\n%      6 : 11.     7     3 :                  1\n%      7 : 22.     8     6 :                  2\n%      8 : 22.     4     7 :                  2\n%      9 : 11.     5     4 :                  1\n%\n%    INDX(2) = 3 means that sorted item(2) is A(3).\n%    XDNI(2) = 5 means that A(2) is sorted item(5).\n%\n%    UNDX(3) = 4 means that unique sorted item(3) is at A(4).\n%    XDNU(8) = 2 means that A(8) is at unique sorted item(2).\n%\n%    XU(XDNU(I))) = A(I).\n%    XU(I)        = A(UNDX(I)).\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    19 July 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer M, the dimension of the data values.\n%\n%    Input, integer N, the number of data values.\n%\n%    Input, real A(M,N), the data values.\n%\n%    Input, integer UNIQUE_NUM, the number of unique values in A.\n%    This value is only required for languages in which the size of\n%    UNDX must be known in advance.\n%\n%    Input, real TOL, a tolerance for equality.\n%\n%    Output, integer UNDX(UNIQUE_NUM), the UNDX vector.\n%\n%    Output, integer XDNU(N), the XDNU vector.\n%\n  undx = zeros ( unique_num, 1 );\n  xdnu = zeros ( n, 1 );\n%\n%  Implicitly sort the array.\n%\n  indx = r8col_sort_heap_index_a ( m, n, a );\n%\n%  Consider entry I = 1.\n%  It is unique, so set the number of unique items to K.\n%  Set the K-th unique item to I.\n%  Set the representative of item I to the K-th unique item.\n%\n  i = 1;\n  k = 1;\n  undx(k) = indx(i);\n  xdnu(indx(i)) = k;\n%\n%  Consider entry I.\n%\n%  If it is unique, increase the unique count K, set the\n%  K-th unique item to I, and set the representative of I to K.\n%\n%  If it is not unique, set the representative of item I to a\n%  previously determined unique item that is close to it.\n%\n  for i = 2 : n\n\n    unique = 1;\n\n    for j = 1 : k\n      diff = max ( abs ( a(1:m,indx(i)) - a(1:m,undx(j)) ) );\n      if ( diff <= tol )\n        unique = 0;\n        xdnu(indx(i)) = j;\n        break\n      end\n    end\n\n    if ( unique )\n      k = k + 1;\n      undx(k) = indx(i);\n      xdnu(indx(i)) = 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/r8lib/r8col_tol_undex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.5819831133508324}}
{"text": "function [node,edge] = ...\n        getiso2(xpos,ypos,zdat,ilev,filt)\n%GETISO2 extract an iso-contour from a structured two-dimen-\n%sional data-set. \n%   [NODE,EDGE] = GETISO2(XPOS,YPOS,ZFUN,ZLEV) returns the \n%   contour ZFUN(XPOS,YPOS) = ZLEV as a PSLG, by post-proce-\n%   ssing the output of the CONTOUR function. The arguments\n%   XPOS, YPOS and ZFUN must all be N-by-M arrays, and ZLEV \n%   a scalar contouring value.\n%   \n%   See also GETNAN2, FIXGEO2, BFSGEO2, REFINE2\n\n%-----------------------------------------------------------\n%   Darren Engwirda : 2018 --\n%   Email           : de2363@columbia.edu\n%   Last updated    : 25/03/2018\n%-----------------------------------------------------------\n\n    if (nargin < +5), filt = +0. ; end\n    \n%---------------------------------------------- basic checks    \n    if ( ~isnumeric(xpos) || ...\n         ~isnumeric(ypos) || ...\n         ~isnumeric(zdat) || ...\n         ~isnumeric(ilev) || ...\n         ~isnumeric(filt) )\n        error('getiso2:incorrectInputClass' , ...\n            'Incorrect input class.') ;\n    end\n    \n%---------------------------------------------- basic checks\n    if (ndims(xpos) ~= +2 || ...\n        ndims(ypos) ~= +2 || ...\n        ndims(zdat) ~= +2 )\n        error('getiso2:incorrectDimensions' , ...\n            'Incorrect input dimensions.');\n    end\n    \n    if (isvector(xpos))\n        xnum = length(xpos);\n    else\n        xnum = size(xpos,2);\n    end\n    \n    if (isvector(ypos))\n        ynum = length(ypos);\n    else\n        ynum = size(ypos,1);\n    end\n    \n    if (xnum ~= size(zdat,2) || ...\n        ynum ~= size(zdat,1) || ...\n        numel(ilev) ~= +1 || ...\n        numel(filt) ~= +1 )\n        error('getiso2:incorrectDimensions' , ...\n            'Incorrect input dimensions.');\n    end\n\n%------------------------------------ compute the isocontour\n    cmat = contourc( ...\n        xpos,ypos,zdat,[ilev,ilev]) ;\n\n%------------------------------------ \"walk\" contour segment\n    node = [] ; edge = [] ; ipos = +1 ;\n\n    while (ipos < size(cmat,2))\n       \n        numc = cmat(2,ipos);\n        ppts =[cmat(1,ipos+1:ipos+numc)', ...\n               cmat(2,ipos+1:ipos+numc)'\n              ] ;\n\n        pmin = min(ppts,[],1);\n        pmax = max(ppts,[],1);\n        \n        pdel = pmax - pmin ;\n        \n        if (min(pdel)>=filt)\n        \n            if all(ppts(1,:) == ppts(end,:))\n\n    %-------------------------------- closed - back to start\n            enew = ...\n           [(1:numc-1)',(2:numc-0)'; numc,1] ;\n\n            else\n            \n    %-------------------------------- open - dangling endpts\n            enew = ...\n           [(1:numc-1)',(2:numc-0)'] ;\n\n            end\n\n            enew = ...\n            enew + size(node,1);\n\n            node = [node; ppts];\n            edge = [edge; enew];\n\n        end\n\n        ipos = ipos + numc + 1 ;\n        \n    end\n\nend\n\n\n\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/GEOM_UTIL/geom-util/getiso2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5819831127636552}}
{"text": "function z = cpf_tangent(V, lam, Ybus, Sbusb, Sbust, pv, pq, ...\n                            zprv, Vprv, lamprv, parameterization, direction)\n%CPF_TANGENT  Computes normalized tangent predictor for continuation power flow\n%   Z = CPF_TANGENT(V, LAM, YBUS, SBUSB, SBUST, PV, PQ, ...\n%                                 ZPRV, VPRV, LAMPRV, PARAMETERIZATION, DIRECTION)\n%\n%   Computes a normalized tangent predictor for the continuation power flow.\n%\n%   Inputs:\n%       V : complex bus voltage vector at current solution\n%       LAM : scalar lambda value at current solution\n%       YBUS : complex bus admittance matrix\n%       SBUSB : handle of function returning nb x 1 vector of complex\n%               base case injections in p.u. and derivatives w.r.t. |V|\n%       SBUST : handle of function returning nb x 1 vector of complex\n%               target case injections in p.u. and derivatives w.r.t. |V|\n%       PV : vector of indices of PV buses\n%       PQ : vector of indices of PQ buses\n%       ZPRV : normalized tangent prediction vector from previous step\n%       VPRV : complex bus voltage vector at previous solution\n%       LAMPRV : scalar lambda value at previous solution\n%       PARAMETERIZATION : value of cpf.parameterization option.\n%       DIRECTION: continuation direction (+1 for postive lambda\n%                  increase, -1 otherwise)\n%\n%   Outputs:\n%       Z : the normalized tangent prediction vector\n\n%   MATPOWER\n%   Copyright (c) 1996-2016, Power Systems Engineering Research Center (PSERC)\n%   by Shrirang Abhyankar, Argonne National Laboratory\n%   and Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n%% sizes\nnb = length(V);\nnpv = length(pv);\nnpq = length(pq);\n\nVm = abs(V);\n\n%% compute Jacobian for the power flow equations\n[dSbus_dVa, dSbus_dVm] = dSbus_dV(Ybus, V);\n[dummy, neg_dSdb_dVm] = Sbusb(Vm);\n[dummy, neg_dSdt_dVm] = Sbust(Vm);\ndSbus_dVm = dSbus_dVm - neg_dSdb_dVm - lam * (neg_dSdt_dVm - neg_dSdb_dVm);\n\nj11 = real(dSbus_dVa([pv; pq], [pv; pq]));\nj12 = real(dSbus_dVm([pv; pq], pq));\nj21 = imag(dSbus_dVa(pq, [pv; pq]));\nj22 = imag(dSbus_dVm(pq, pq));\n\nJ = [   j11 j12;\n        j21 j22;    ];\n\nSxf = Sbust(Vm) - Sbusb(Vm);    %% \"transfer\" at current voltage level\ndF_dlam = -[real(Sxf([pv; pq])); imag(Sxf(pq))];\n[dP_dV, dP_dlam] = cpf_p_jac(parameterization, zprv, V, lam, Vprv, lamprv, pv, pq);\n\n%% linear operator for computing the tangent predictor\nJ = [   J   dF_dlam; \n      dP_dV dP_dlam ];\n\n% J = [ J, dF_dlam; \n%       z([pv; pq; nb+pq; 2*nb+1])'];\n\n%% compute normalized tangent predictor\nz = zeros(size(zprv));\ns = zeros(npv+2*npq+1, 1);\ns(end,1) = sign(direction);\nz([pv; pq; nb+pq; 2*nb+1]) = J\\s;   %% tangent vector\nz = z/norm(z);                      %% normalize tangent predictor\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/cpf_tangent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759583, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5819273704664645}}
{"text": "% largely drawn from run_readlsl of BCILAB\nfunction lslin(handles)\n% find stream\nresult = lsl_resolve_bypred(handles.lsllib, ['name=''' handles.streamName '''']);\n\n% open inlet \ninlet = lsl_inlet(result{1});\n% info = inlet.info();\n\n% create online stream data structure in base workspace (using appropriate meta-data)\nonl_newstream(parseStreamName(handles.streamName), 'srate', result{1}.nominal_srate(), ...\n    'chanlocs', {handles.chanlocs.labels}, 'buffer_len', 10);\n\n% state variables for recursive least squares jitter correction\nP = 1e10*eye(2);        % precision matrix (inverse covariance matrix of predictors)\nw = [0 0]';             % linear regression coefficients [offset,slope]\nlam = 2^(-1/(128 * 30)); % forget factor in RLS calculation\nn = 0;                  % number of samples observed so far    \nnumeric_offset = [];    % time-stamp offset to keep numerics healthy; will be initialized with first measured time stamp\n\n% start reading\nonl_read_background(parseStreamName(handles.streamName), @read_data, 20);\n\n    % reads from inlet\n    function results = read_data()\n        [chunk, stamps] = inlet.pull_chunk();\n        data_clock = inlet.time_correction([], 'median', 30);\n        stamps = stamps + data_clock;\n        stamps = update_regression(stamps);\n        chunk = double(chunk);\n        \n        % this is the source of grief\n        % taking only the last timestamp allows REST to run but the\n        % timestamps are garbage\n        % giving all the timestamps soft errors in onl_append. onl_append\n        % seems to expect only one value so perhaps this idea of many\n        % timestamps if not correct.\n        try %#ok<TRYNC>\n            stamps = stamps(end);\n        end\n        results = {chunk, stamps};\n    end\n    \n    \n    % perform RLS block update of regression coefficients\n    % this is a regression from sample index onto timestamp of the sample\n    function y = update_regression(y)\n        if ~isempty(y)\n            % sanitize numerics (all done relative to the first observed time stamp)\n            if isempty(numeric_offset)\n                numeric_offset = y(1); end\n            y = y - numeric_offset;        \n            % define predictor matrix (bias, sample index)\n            X = [ones(1,length(y)); n + (1:length(y))];\n            n = n + length(y);            \n            % apply updates...\n            for t=1:length(y)\n                u = X(:,t);\n                d = y(t);\n                pi = u'*P;\n                gam = lam + pi*u;\n                k = pi'/gam;\n                al = d - w'*u;\n                w = w + k*al;\n                Pp = k*pi;\n                P = (1/lam)*(P-Pp);\n            end            \n            % predict y\n            y = w'*X + numeric_offset;\n        end\n    end\n\n\n    % parse streamname\n    function streamnames = parseStreamName(streamnames)\n        if ~isvarname(streamnames)\n            streamnames = streamnames(~ismember(streamnames,['-' ' ']));\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/functions/lslin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5819273625073333}}
{"text": "function [u,eqn,info] = fracLapP2P2(node,elem,pde,option)\n%% FRACLAPP2P2 solves fractional Laplacian equation using P2-P2 element\n%\n% [u,eqn,info] = fracLapP1P1(node,elem,pde,option) solves the fractional\n% Laplacian equation\n% \n%  (-\\Delta^^s u = f in \\Omega with u = 0 on \\partial \\Omega.\n\n\n%% Options\nif ~exist('option','var'), option = []; end\nif ~isfield(option,'plotflag'), option.plotflag = 0; end\n\n%% Parameters\nglobal s;\nalpha = 1-2*s;\nif s == 0.5\n    gamma = 1;\nelse\n    gamma = 5/(2*s)+0.01; % a different grading factor\nend\n\n%% Mesh and data structure\n[elem2dof,edge,bdDof] = dofP2(elem);\nN = size(node,1);  NT = size(elem,1); NE = size(edge,1);\nMy = round(pde.L*sqrt(NT/2));\ny = gradmap(0,pde.L,gamma,My);\nNy = length(y); % number of vertices in y-direction  \nNTy = Ny - 1;   % number of elements in y-direction\nNTtotal = NT*NTy;\nNxdof = (N + NE); % dof in x  is number of vertices plus edges\nNydof = (Ny + NTy); % dof in y direction is number of vertices plus elements\nNdof = Nxdof*Nydof;\n\ntic;\n%% Stiffness matrix and mass matrix in the extended direction\n% quantities in y direction\nhy = diff(y);\na = zeros(NTy,5);\nfor i = 1:5\n    a(:,i) = diff(y.^(alpha+i)/(alpha+i));\nend\ny1 = y(1:end-1);\ny2 = y(2:end);\ny12 = y1 + y2;\ny1y2 = y1.*y2;\nym = y12/2;\n% stiffness matrix in y direction\nAy = zeros(NTy,3,3);\nAy(:,1,1) = a(:,1)./hy.^2;\nAy(:,1,2) = -Ay(:,1,1);           \nAy(:,2,1) = -Ay(:,1,1);           \nAy(:,2,2) = Ay(:,1,1);         \nAy(:,1,3) = 8*(a(:,2) - ym.*a(:,1))./hy.^3;\nAy(:,3,1) = Ay(:,1,3);\nAy(:,2,3) = -Ay(:,1,3);\nAy(:,3,2) = Ay(:,2,3);\nAy(:,3,3) = 64*(a(:,3) - 2*ym.*a(:,2) + ym.^2.*a(:,1))./hy.^4;\n% mass matrix in y direction\nMy = zeros(NTy,3,3);\nMy(:,1,1) = (a(:,3) - 2*y1.*a(:,2) + y1.^2.*a(:,1))./hy.^2;\nMy(:,1,2) = (-a(:,3) + (y1+y2).*a(:,2) - y1.*y2.*a(:,1))./hy.^2;\nMy(:,2,1) = My(:,1,2);\nMy(:,2,2) = (a(:,3) - 2*y2.*a(:,2) + y2.^2.*a(:,1))./hy.^2;\nMy(:,1,3) = 4*(a(:,4) - (y12+y2).*a(:,3) + (y2.*y12 + y1y2).*a(:,2) ...\n             - y2.*y1y2.*a(:,1))./hy.^3;\nMy(:,3,1) = My(:,1,3);\nMy(:,2,3) = 4*(-a(:,4) + (y12+y1).*a(:,3) - (y1.*y12 + y1y2).*a(:,2) ...\n             + y1.*y1y2.*a(:,1))./hy.^3;\nMy(:,3,2) = My(:,2,3);\nMy(:,3,3) = 16*(a(:,5) - 2*y12.*a(:,4) + (y12.^2 + 2*y1y2).*a(:,3)...\n               -2*y12.*y1.*y2.*a(:,2) + y1y2.^2.*a(:,1))./hy.^4;\n\n%% Stiffness matrix and mass matrix in the original direction\n[Dlambda,area] = gradbasis(node,elem);\n% Compute a piecewise constant diffusion coefficient\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\nif ~isempty(pde.d) % build the coefficients into the scaled area\n    areaK = K.*area;\nelse\n    areaK = area;\nend\nAt = zeros(NT,6,6);\nMt = zeros(NT,6,6);\n% stiffness matrix\n[lambda, w] = quadpts(2);\nnQuad = size(lambda,1);\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    for i = 1:6\n        for j = 1:6\n            At(:,i,j) = At(:,i,j) + w(p)*dot(Dphip(:,:,i),Dphip(:,:,j),2).*areaK;           \n        end\n    end\nend\n% mass matrix\n[lambda, w] = quadpts(4);\nnQuad = size(lambda,1);\nphi(:,6) = 4*lambda(:,1).*lambda(:,2);\nphi(:,1) = lambda(:,1).*(2*lambda(:,1)-1);\nphi(:,2) = lambda(:,2).*(2*lambda(:,2)-1);\nphi(:,3) = lambda(:,3).*(2*lambda(:,3)-1);\nphi(:,4) = 4*lambda(:,2).*lambda(:,3);\nphi(:,5) = 4*lambda(:,3).*lambda(:,1);\nfor i = 1:6\n    for j = 1:6\n        for p = 1:nQuad\n            Mt(:,i,j) = Mt(:,i,j) + w(p)*phi(p,i).*phi(p,j);\n        end\n        Mt(:,i,j) = Mt(:,i,j).*areaK;\n    end\nend\nclear phi Dphip lambda Dlambda\n\n%% Assemble stiffness matrix\ndofMap = repmat(1:Nxdof,Nydof,1) + repmat((0:Nydof-1)'*Nxdof,1,Nxdof);\nii = zeros(18*18*NTtotal,1); \njj = zeros(18*18*NTtotal,1); \nsA = zeros(18*18*NTtotal,1);\nindex = 0;\nfor m = 1:3\n    for n = 1:3\n        for i = 1:6\n            for j = 1:6\n                if m < 3\n                    ii(index+1:index+NTtotal) = dofMap(m:Ny+m-2,elem2dof(:,i));\n                else % m = 3: middle points of elements in y direction\n                    ii(index+1:index+NTtotal) = dofMap(Ny+1:Nydof,elem2dof(:,i));\n                end\n                if n < 3\n                    jj(index+1:index+NTtotal) = dofMap(n:Ny+n-2,elem2dof(:,j));\n                else % n = 3: middle points of elements in y direction\n                    jj(index+1:index+NTtotal) = dofMap(Ny+1:Nydof,elem2dof(:,j));\n                end                    \n                sA(index+1:index+NTtotal) = kron(At(:,i,j),My(:,m,n)) + ...\n                                            kron(Mt(:,i,j),Ay(:,m,n));\n                index = index + NTtotal;\n            end\n        end\n    end\nend\nA = sparse(ii,jj,sA,Ndof,Ndof);\nclear ii jj sA At Mt Ay My\n\n%% Assemble the right hand side\nb = zeros(Ndof,1);\nu = zeros(Ndof,1);\n\n%% Set up boundary conditions\n% bdDof is found in dofP2\nlateralbd = dofMap(:,bdDof);\ntopbd = dofMap(Ny,:);\n\n% Modify the matrix to include the Dirichlet boundary condition\nbdidx = zeros(Ndof,1); \nbdidx(lateralbd) = 1;\nbdidx(topbd) = 1;\nTbd = spdiags(bdidx,0,Ndof,Ndof);\nT = spdiags(1-bdidx,0,Ndof,Ndof);\nA = T*A*T + Tbd;\n\n% Compute boundary integral over the original domain\nif ~isfield(option,'fquadorder')\n    option.fquadorder = 6;   \nend\n[lambdaf,weightf] = quadpts(option.fquadorder);\nphif(:,1) = lambda(:,1).*(2*lambda(:,1)-1);\nphif(:,2) = lambda(:,2).*(2*lambda(:,2)-1);\nphif(:,3) = lambda(:,3).*(2*lambda(:,3)-1);\nphif(:,4) = 4*lambda(:,2).*lambda(:,3);\nphif(:,5) = 4*lambda(:,3).*lambda(:,1);\nphif(:,6) = 4*lambda(:,1).*lambda(:,2);\nnQuadf = size(lambdaf,1);\nft = zeros(NT,6);\nfor p = 1:nQuadf\n    % quadrature points in the x-y coordinate\n    pxy = lambdaf(p,1)*node(elem(:,1),:) ...\n        + lambdaf(p,2)*node(elem(:,2),:) ...\n        + lambdaf(p,3)*node(elem(:,3),:);\n    fp = pde.f(pxy);\n    for i = 1:6\n        ft(:,i) = ft(:,i) + weightf(p)*phif(p,i)*fp;\n    end\nend\nft = ds*ft.*repmat(area,1,6);\nb = b + accumarray(elem2dof(:),ft(:),[Ndof,1]); \n% Neumann edfts are considered as open set. So the corner points should be\n% set as Dirichlet boundary condition!\nb(lateralbd) = 0;\nclear ft\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\nfreeNode = find(bdidx==0);\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 larft size systems\n        option.solver = 'mg';\n    end\nend\nsolver = option.solver;\n% solve\nswitch solver\n    case 'direct'\n        tic;\n        u(freeNode) = A(freeNode,freeNode)\\b(freeNode);\n        residual = norm(b - A*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 = 'VCYCLE';\n        option.freeDof = freeDof;\n        [u,info] = mgfracLapP2P2(A,b,elem,option); \n    case 'amg'\n        option.solver = 'CG';\n        [u(freeNode),info] = amg(A(freeNode,freeNode),b(freeNode),option);                 \nend\n\n%% Compute error using boundary integral\nif isfield(pde,'exactu')\n    err = zeros(NT,1);\n    [lambda,weight] = quadpts(7);\n    phi(:,6) = 4*lambda(:,2).*lambda(:,1);\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(:,1).*lambda(:,3);\n    nQuad = size(lambda,1);\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        fp = pde.f(pxy);\n        uhp = u(elem2dof(:,1)).*phi(p,1) + ...\n              u(elem2dof(:,2)).*phi(p,2) + ...\n              u(elem2dof(:,3)).*phi(p,3) + ...        \n              u(elem2dof(:,4)).*phi(p,4) + ...\n              u(elem2dof(:,5)).*phi(p,5) + ...\n              u(elem2dof(:,6)).*phi(p,6);\n        up = pde.exactu(pxy);\n        err = err + weight(p)*fp.*(up - uhp);\n    end\nelse\n    err = 0;    \nend\nerr = ds*sum(err.*area);\nerr = sqrt(err);\ninfo.errH1 = err;\n\n%% Output information\neqn = struct('A',A,'b',b,'freeNode',freeNode,'edge',edge);\ninfo.assembleTime = assembleTime;", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fracLaplacian/fracLapP2P2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5819273583154695}}
{"text": "function vAberr=aberCorr(vOrig,obsVel,sunDist)\n%%ABERCORR Rotate vectors for stellar aberration, approximately including\n%          the effects of the gravitational potential of the Sun if the\n%          distances between the observers and the Sun are provided.\n%\n%INPUTS: vOrig A 3XN set of N vectors pointing from the observers to the\n%              objects being observed without corruption due to\n%              aberration. The units of the vector do not matter.\n%              Normally, one would expect vOrig to be composed of unit\n%              vectors as aberration affects the pointing direction of the\n%              vectors.\n%       obsVel The 3XN matrix of the velocity of each observer with\n%              respect to the stellar coordinate system origin in meters\n%              per second. For example, if using the barycentric celestial\n%              reference system (BCRS), they are the set of velocity\n%              vectors of the observers with respect to the barycenter.\n%      sunDist An optional 3XN vector of the scalar distances in meters\n%              from the Sun to the observer. If this parameter is\n%              included, an approximate correction due to the\n%              gravitational potential of the Sun is included.\n%\n%OUTPUTS: vAberr The 3XN set of N vectors rotated to deal with aberration\n%                effects.\n%\n%If all parameters are provided, the function is essentially a wrapper for\n%the function iauAb in the International Astronomical Union's Standards of\n%Fundamental Astronomy library with an adjustment so that the vector in\n%question need not have unit magnitude. If the distance to the Sun is\n%omitted, then the standard special relativistic aberration correction\n%without any gravitational effects is applied. The standard special\n%relativistic aberration correction is described in Chapter 7 of [1]\n%\n%Note that if the vectors provided are meant to be apparent distances,\n%rather than just unit vectors representing directions, the transformation\n%does not adjust the magnitudes of the vectors to account for special\n%relativistic contraction of space due to the motion of the observer with\n%respect to the origin. The magnitudes of the output vectors equal the\n%magnitudes of the input vectors.\n%\n%The algorithm can be compiled for use in Matlab  using the \n%CompileCLibraries function.\n%\n%The algorithm is run in Matlab using the command format\n%vAberr=aberCorr(vOrig,obsVel,sunDist);\n%or\n%vAberr=aberCorr(vOrig,obsVel);\n%\n%REFERENCES:\n%[1] S. E. Urban and K. P.Seidelmann, Eds.,Explanatory Supplement to the\n%    Astronomical Almanac, 3rd ed. Mill Valley, CA: University Science\n%    Books, 2013.\n%\n%March 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nerror('This function is only implemented as a mexed C or C++ function. Please run CompileCLibraries.m to compile the function for use.')\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/Astronomical_Code/aberCorr.c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5819273570687296}}
{"text": "function fhat = convSO3(fhat1,fhat2)\n%\n\n% old sizes\ns1 = size(fhat1);\ns2 = size(fhat2);\n\n% get bandwidth\nL = min(dim2deg(s1(1)),dim2deg(s2(1)));\n\n% new size\nl=length(s2)-length(s1);\ns = max([s1(2:end),ones(1,l);s2(2:end),ones(1,-l)]);\n\n% compute Fourier coefficients of the convolution\nfhat = zeros([deg2dim(L+1),s]);\nif prod(s) == 1 %simple SO3Fun\n  for l = 0:L\n    ind = deg2dim(l)+1:deg2dim(l+1);\n    fhat(ind) = reshape(fhat2(ind),2*l+1,2*l+1) * ...\n      reshape(fhat1(ind),2*l+1,2*l+1) ./ sqrt(2*l+1);     \n  end\nelse % vector valued SO3Fun  \n  for l = 0:L\n    ind = deg2dim(l)+1:deg2dim(l+1);\n    fhat_l = pagemtimes( full(reshape(fhat2(ind,:),[2*l+1,2*l+1,s2(2:end)])) , ...\n      full(reshape(fhat1(ind,:),[2*l+1,2*l+1,s1(2:end)])) ) ./ sqrt(2*l+1);\n    fhat(ind,:) = reshape(fhat_l,[],prod(s));\n  end\nend\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/SO3Fun/@SO3FunHarmonic/private/convSO3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5819273465890707}}
{"text": "function [ imgOut ] = hyperOrthorectify( imgIn, altitude, hpbw )\n%HYPERORTHORECTIFY Orthorectifies areal observed data.\n%   Orthorectifies areal observed data using nearest neighbor interpolation.\n%   \n% Inputs\n%   imgIn       Input image (m x n) or (m x n x p)\n%   altitude    Sensor altitude (meters)\n%   hpbw        Half power beam width (radians).\n% Outputs\n%   imgOut      Orthorectified image.\n\n% Input parameters\nif (ndims(imgIn) == 2)\n    [h, w] = size(imgIn);\n    p = 1;\nelseif (ndims(imgIn) == 3)\n    [h, w, p] = size(imgIn);\nend\n\nradPerPix = hpbw/w;\nx = tan(hpbw/2)*altitude;  % m\ngsd = altitude*radPerPix;  % m\nn = x/gsd;\n\nimgOut = zeros(h, floor(n)*2, p);\nfor k=1:p\n    for j=1:h\n        for i=-floor(n):1:floor(n)-1\n            boresiteDistance = gsd*i;\n            theta = atan(boresiteDistance/altitude);\n            imagePix = round(theta / radPerPix);\n            imgOut(j, floor(n)+i+1, k) = imgIn(j, (w/2)+imagePix+1, k);\n        end\n    end\nend\n", "meta": {"author": "davidkun", "repo": "HyperSpectralToolbox", "sha": "147d58e6efe839e8945dc0d4e8d65029884137f1", "save_path": "github-repos/MATLAB/davidkun-HyperSpectralToolbox", "path": "github-repos/MATLAB/davidkun-HyperSpectralToolbox/HyperSpectralToolbox-147d58e6efe839e8945dc0d4e8d65029884137f1/functions/hyperOrthorectify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5819248031480456}}
{"text": "function pass = test_biharm(pref)\n% Check the CHEBFUN2 BIHARM command.\n\nif ( nargin < 1 ) \n    pref = chebfunpref; \nend \ntol = 1e6*pref.cheb2Prefs.chebfun2eps;\n\n% Function to be used:\nff = @(x,y) x.^2.*y.^2;\n\n% Bihamrmonic operator applied to ff:\nf = chebfun2(ff); \nfB = biharm(f); \n\n% Exact solution:\ngg = @(x,y) 8;\ng = chebfun2(gg);\n\n% Compare:\npass = ( norm(fB - g) < tol );\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun2/test_biharm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5818928948487271}}
{"text": "function [sys,x0,str,ts]=NL_PID_fhan_c(t,x,u,flag,r0,h0,r1,h1,h,c,r2,h2)\nswitch flag,\n    case 0,\n        [sys,x0,str,ts]=mdlInitializeSizes(h);\n    case 2,\n        sys=mdlUpdates(x,u,r0,r1,h0,h1,h);\n    case 3,\n        sys=mdlOutputs(x,c,r2,h2);\n    case 4,\n        sys=mdlGetTimeOfNextVarHit(t,h);\n    case {1,9},\n        sys=[];\n    otherwise \n        error(['Unhandled flag=',num2str(flag)]);\nend\nfunction [sys,x0,str,ts]=mdlInitializeSizes(h)\n    sizes=simsizes;\n    sizes.NumContStates=0;\n    sizes.NumDiscStates=5;\n    sizes.NumOutputs=2;\n    sizes.NumInputs=2;\n    sizes.DirFeedthrough=1;\n    sizes.NumSampleTimes=1;\n    sys=simsizes(sizes);\n    x0=[0;0;0;0;0];\n    str=[];\n    ts=[h 0];  \nfunction sys=mdlUpdates(x,u,r0,r1,h0,h1,h)\n    fh0=fhan(x(1)-u(1),x(2),r0,h0);\n    x(1)=x(1)+h*x(2);\n    x(2)=x(2)+h*fh0;\n    fh1=fhan(x(3)-u(2),x(4),r1,h1);\n    x(3)=x(3)+h*x(4);\n    x(4)=x(4)+h*fh1;\n    x(5)=x(5)+h*(x(1)-x(3));\n    sys=x;\nfunction sys=mdlOutputs(x,c,r2,h2)   \n    sys(1)=-fhan(x(1)-x(3),c*(x(2)-x(4)),r2,h2);    \n    sys(2)=x(1);\nfunction sys=mdlGetTimeOfNextVarHit(t,h)\n    sys=t+h;\nfunction y=fhan(x1,x2,r,h)\nd=r*h;\nd0=h*d;\ny=x1+h*x2;\na0=sqrt(d^2+8*r*abs(y));\nif abs(y)>d0\n    a=x2+(a0-d)*sign(y)/2;\nelse\n    a=x2+y/h;\nend\n\nif abs(a)>d\n    y=-r*sign(a);\nelse \n    y=-r*a/d;\nend \n\n\n", "meta": {"author": "TianfaYao", "repo": "ADRC", "sha": "6f1f96ebda1684c44af4dec4214b4880f4aa8cec", "save_path": "github-repos/MATLAB/TianfaYao-ADRC", "path": "github-repos/MATLAB/TianfaYao-ADRC/ADRC-6f1f96ebda1684c44af4dec4214b4880f4aa8cec/\u8d3a\u5e86\u6bd5\u4e1a\u8bba\u6587ADRC\u5168\u96c6\u5305\u4ec5\u7528\u4e8e\u5185\u90e8\u5171\u4eab\u4e0d\u8981\u5916\u4f20/MyLibrary/NL_PID_fhan_c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619393159451, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5818928927906606}}
{"text": "function [Btuph] = GW2Btuph(GW)\n% Convert power from gigawatts to British thermal units per hour. \n% Chad A. Greene 2012\nBtuph = GW*3412141633.1279;", "meta": {"author": "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/GW2Btuph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5818928887604491}}
{"text": "%% 2's complement of binary no;\n\nfunction twos_comp = twos_complement_of_binary(bin)\nc=0;\ntemp=bin;\ntwos_comp=0;\nwhile(temp>0 && rem(temp,10)==0)\n    twos_comp=twos_comp*10 + rem(temp,10);\n    temp=fix(temp/10);\n    c=c+1;\nend\nif(temp>0)\n    twos_comp=twos_comp*10 + rem(temp,10);\n    temp=fix(temp/10);\n    c=c+1;\nend\nwhile(temp>0)\n    if(rem(temp,10)==1)\n        twos_comp=twos_comp*10 + 0;\n    else\n        twos_comp=twos_comp*10 + 1;\n    end\n    temp=fix(temp/10);\n    c=c+1;\nend\n\ntemp=twos_comp;\ntwos_comp=0;\nwhile(c>0)      %reversing the order;\n    twos_comp=twos_comp*10 + rem(temp,10);\n    temp=fix(temp/10);\n    c=c-1;\nend\nend\n\n", "meta": {"author": "TheAlgorithms", "repo": "MATLAB-Octave", "sha": "e150b77ad256de46c1ce3815c3d7945ac4fc28dc", "save_path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave", "path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave/MATLAB-Octave-e150b77ad256de46c1ce3815c3d7945ac4fc28dc/algorithms/maths/twos_complement_of_binary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5818928795421111}}
{"text": "% Copyright (C) Daphne Koller, Stanford University, 2012\n\nrand('seed', 1);\n\n% Construct the toy network\n[toy_network, toy_factors] = ConstructToyNetwork(1,0.2);\ntoy_evidence = zeros(1, length(toy_network.names));\n%toy_clique_tree = CreateCliqueTree(toy_factors, []);\n%toy_cluster_graph = CreateClusterGraph(toy_factors,[]);\n\n% Exact Inference\nExactM = ComputeExactMarginalsBP(toy_factors, toy_evidence, 0);\nfigure, VisualizeToyImageMarginals(toy_network, ExactM,1,'exact');\n\n% Comment this in to run Approximate Inference on the toy network\n% Approximate Inference\n% % ApproxM = ApproxInference(toy_cluster_graph, toy_factors, toy_evidence);\n% figure, VisualizeToyImageMarginals(toy_network, ApproxM);\n\n\n\n% MCMC Inference\ntransition_names = {'Gibbs', 'MHUniform', 'MHGibbs', 'MHSwendsenWang1', 'MHSwendsenWang2'};\n\nfor j = 1:length(transition_names)\n    samples_list = {};\n\n    num_chains_to_run = 1;\n    for i = 1:num_chains_to_run\n        % Random Initialization\n        A0 = ceil(rand(1, length(toy_network.names)) .* toy_network.card);\n\n        % Initialization to all ones\n        % A0 = i * ones(1, length(toy_network.names));\n\n        [M, all_samples] = ...\n            MCMCInference(toy_network, toy_factors, toy_evidence, transition_names{j}, 0, 500, 1, A0);\n        samples_list{i} = all_samples;\n        figure, VisualizeToyImageMarginals(toy_network, M, i, transition_names{j});\n    end\n \n    vis_vars = [3];\n    VisualizeMCMCMarginals(samples_list, vis_vars, toy_network.card(vis_vars), toy_factors, ...\n      500, ExactM(vis_vars),transition_names{j});\n    disp(['Displaying results for MCMC with transition ', transition_names{j}]);\n    disp(['Hit enter to continue']);\n    pause;\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/5.Approximate Inference/TestToy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5818928785560386}}
{"text": "function test_failed = test_blockfwt()\ntest_failed = 0;\n\ndisp('-------------TEST_BLOCKFWT--------------');\n\nL = 567;\nW = [1,3];\n\nLb = [78,64,58,1021];\n\nwa = {'dden3','ana:symorth1'};\nws = {'dden3','syn:symorth1'};\nJ = [5];\n\n\nfor wId = 1:numel(W)\nfor lId = 1:numel(L)\nf = tester_rand(L(lId),W(wId));\nfor lbId = 1:numel(Lb)\nfor waId=1:numel(wa)\n\nFa = blockframeaccel(frame('fwt',wa{waId},J),Lb(lbId),'segola');\nFs = blockframeaccel(frame('fwt',ws{waId},J),Lb(lbId),'segola');\n\na = Fa.g.a(1);\nm = numel(Fa.g.g{1}.h);\nrmax = (a^J-1)/(a-1)*(m-1);\n\n\nf = postpad(f,L(lId)+rmax);\nblock(f,'offline','L',Lb(lbId));\n\ncolC = {};\ncolfhat = {};\n\nfor ii=1:ceil(L(lId)/Lb(lbId))\n    fb = blockread();\n    c  = blockana(Fa,fb);\n    ccell = comp_fwtpack2cell(Fa,c);\n    \n    colC{end+1} = ccell;\n    \n    chat = cell2mat(ccell);\n    \n    fhat = blocksyn(Fs,chat,size(fb,1));\n    colfhat{end+1} = fhat;\nend\n\nerr = 0;\ncwhole = fwt(f,wa{waId},J,'zero','cell');\nfor ii=1:numel(colC{1})\n   cc{ii} = cell2mat(cellfun(@(cEl) cEl{ii},colC','UniformOutput',0));\n   Ltmp = min([size(cwhole{ii},1),size(cc{ii},1)]);\n   err = err + norm(cwhole{ii}(1:Ltmp,:)-cc{ii}(1:Ltmp,:));\nend\n\n[test_failed,fail]=ltfatdiditfail(err,test_failed);\nfprintf('COEFS L:%3i, W:%3i, Lb=%3i, %s, err=%.4e %s\\n',L(lId),W(wId),Lb(lbId),wa{waId},err,fail);\n\n\nfhat = cell2mat(colfhat.');\n\nfhat = fhat(rmax+1:end,:);\n\nLcrop = min([size(fhat,1),size(f,1)]);\n\n\nres = norm([f(1:Lcrop,:)-fhat(1:Lcrop,:)]);\n[test_failed,fail]=ltfatdiditfail(res,test_failed);\nfprintf('REC   L:%3i, W:%3i, Lb=%3i, %s, err=%.4e %s\\n',L(lId),W(wId),Lb(lbId),wa{waId},res,fail);\n\nend\nend\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/testing/test_blockfwt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5818928612772769}}
{"text": "%dout=A*din+b;\nfunction [A b]=cp_affine(dout,din)\nnvin=size(din,1);\nnvout=size(dout,1);\nndat=size(din,2);\n\ndata=[din;ones(1,ndat)];\nmx_a=(dout*data')/(data*data');\n\nA=mx_a(1:nvout,1:nvin);\nb=mx_a(1:nvout,nvin+1);\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/Calibration/cp_affine_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5818614333312369}}
{"text": "function [fess,X] = fess_vbmc(vp,gp,X)\n%FESS_VBMC Compute fractional effective sample size through importance sampling\n\nif nargin < 3 || isempty(X); X = 100; end\n\n% If a single number is passed, take it as the number of samples\nif numel(X) == 1\n    N = X;\n    X = vbmc_rnd(vp,N,0);\nelse\n    N = size(X,1);\nend\n\n% Can directly pass the estimated GP means instead of the full GP\nif isstruct(gp)\n    [~,~,fbar] = gplite_pred(gp,X,[],[],0,0);    \nelse\n    fbar = mean(gp,2);\nend\n\nif size(fbar,1) ~= size(X,1)\n    error('Mismatch between number of samples from VP and GP.');\nend\n                \n% Compute effective sample size (ESS) with importance sampling\nvlnpdf = max(vbmc_pdf(vp,X,0,1),log(realmin));\nlogw = fbar - vlnpdf;\nw = exp(logw - max(logw));\nw = w/sum(w);\nfess = 1/sum(w.^2) / N; % fractional ESS\n\nend", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/misc/fess_vbmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5818614333312367}}
{"text": "function Keff = electrolyteConductivity(ce,T,param,batterySection)\n% electrolyteConductivity  Evaluates the conductivity coefficients for the\n% electrolyte phase. The measurement unit is [S/m]\n%\n%   Keff = electrolyteConductivity(ce,T,param) evaluates\n%   the conductivity coefficients for the anode, separator and cathode electrolyte phase of the\n%   battery. You can modify the script to meet your particular needs.\n%\n%   The conductivity coefficients can be evaluated in isothermal case\n%   (param.TemperatureEnabled=0) or adiabatic case\n%   (param.TemperatureEnabled=1 or 2).\n%\n%   You can modify the way that the conductivity coefficients are computed, as\n%   function of electrolyte concentration and temperature. The main script\n%   will pass also the param array.\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\nif(param.TemperatureEnabled>=1)\n    switch(batterySection)\n        case'p'\n            Keff = param.eps_p^param.brugg_p *(1e-4*ce.*((-10.5+0.668*1e-3*ce+0.494*1e-6*ce.^2) +...\n                (0.074  -1.78*1e-5*ce -8.86*1e-10*ce.^2).*T + (-6.96*1e-5+2.8*1e-8*ce).*T.^2).^2);\n        case 's'\n            Keff = param.eps_s^param.brugg_s *(1e-4*ce.*((-10.5+0.668*1e-3*ce+0.494*1e-6*ce.^2) +...\n                (0.074  -1.78*1e-5*ce -8.86*1e-10*ce.^2).*T + (-6.96*1e-5+2.8*1e-8*ce).*T.^2).^2);\n        case 'n'\n            Keff = param.eps_n^param.brugg_n *(1e-4*ce.*((-10.5+0.668*1e-3*ce+0.494*1e-6*ce.^2) +...\n                (0.074  -1.78*1e-5*ce -8.86*1e-10*ce.^2).*T + (-6.96*1e-5+2.8*1e-8*ce).*T.^2).^2);\n    end\nelse\n        switch(batterySection)\n        case'p'\n            Keff = param.eps_p^param.brugg_p *(4.1253*1e-2 + 5.007*1e-4*ce - 4.7212*1e-7*ce.^2 +1.5094*1e-10*ce.^3 -1.6018*1e-14*ce.^4);\n        case 's'\n            Keff = param.eps_s^param.brugg_s *(4.1253*1e-2 + 5.007*1e-4*ce - 4.7212*1e-7*ce.^2 +1.5094*1e-10*ce.^3 -1.6018*1e-14*ce.^4);\n        case 'n'\n            Keff = param.eps_n^param.brugg_n *(4.1253*1e-2 + 5.007*1e-4*ce - 4.7212*1e-7*ce.^2 +1.5094*1e-10*ce.^3 -1.6018*1e-14*ce.^4);\n        end\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/P2D_equations/electrolyteConductivity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5818614272854437}}
{"text": "%-------------------------------------------------------\n% University of Zaragoza\n% Centro Politecnico Superior\n% Robotics, Perception and Real Time Group\n% Author:  Javier Civera -- jcivera@unizar.es\n% Date   :  2007-05-09\n%-------------------------------------------------------\n% Returns a camera data structure containing the calibration\n%-------------------------------------------------------\n\nfunction cam = initialize_cam()\n\n% Unibrain camera, calibrated on 04/09/07\nd =     0.0112;\nnRows = 240;\nnCols = 320;\nCx =    1.7945 / d;\nCy =    1.4433 / d;\nk1=     6.333e-2;\nk2=     1.390e-2;\nf =     2.1735;\n\n% % Visual Compass camera\n% d =     0.0112;\n% nRows = 240;\n% nCols = 320;\n% Cx =    1.6888/d;\n% Cy =    1.4393/d;\n% k1=     6.239e-2;\n% k2=     1.359e-2;\n% f =     2.1660;\n\ncam.k1 =    k1;\ncam.k2 =    k2;\ncam.nRows = nRows;\ncam.nCols = nCols;\ncam.Cx =    Cx;\ncam.Cy =    Cy;\ncam.f =     f;\ncam.dx =    d;\ncam.dy =    d;\ncam.model = 'two_distortion_parameters';\n\n\ncam.K =     sparse( [ f/d   0     Cx;\n                0  f/d    Cy;\n                0    0     1] );", "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/initialize_cam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5818614138392398}}
{"text": "clear,clc\n\naddpath(pwd);\ncd cvx;\naddpath(genpath(pwd));\ncd ..;\n\nload('Ns=2.mat');\n% load('Ns=8.mat');\n\nNs = 2;\n\nNRF = [2,3,4,6,9,12,18];\n\nSNR_dB = 0;\nSNR = 10.^(SNR_dB./10);\nrealization = size(H,3);\nsmax = length(SNR);% enable the parallel\n\nfor r = 1:length(NRF)\n    for reali = 1:realization\n        [ FRF, FBB ] = SDR_AltMin( Fopt(:,:,reali), NRF(r) );\n        [ WRF, WBB ] = Receiver( Wopt(:,:,reali), NRF(r) );\n        R(r,reali) = log2(det(eye(Ns) + SNR/Ns * pinv(WRF * WBB) * H(:,:,reali) * FRF * FBB * FBB' * FRF' * H(:,:,reali)' * WRF * WBB));    \n    end\nend\nplot(NRF,sum(R,2)/realization,'Marker','diamond','LineWidth',1.5,'Color',[0.87058824300766 0.490196079015732 0]);\ngrid on\nhold on", "meta": {"author": "yuxianghao", "repo": "Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems", "sha": "18f610e24498f2305a498459150492e17626754b", "save_path": "github-repos/MATLAB/yuxianghao-Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems", "path": "github-repos/MATLAB/yuxianghao-Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems/Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems-18f610e24498f2305a498459150492e17626754b/Narrowband/SDR-AltMin/main_NRF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5818614138392398}}
{"text": "function [err_norm,n] = InverseKinematics_LM_ver2(to, Target)\n% Levenberg-Marquardt, Chan-Lawrence, Sugihara's modification\nglobal uLINK\n\nidx = FindRoute(to);\nwn_pos = 1/0.3;\nwn_ang = 1/(2*pi);\nWe = diag([wn_pos wn_pos wn_pos wn_ang wn_ang wn_ang]);\nWn = eye(length(idx));\nWe2 = We*We;\n\nForwardKinematics(1);\nerr = CalcVWerr(Target, uLINK(to));\nEk = err'*We*err;\n\nfor n = 1:10\n  J  = CalcJacobian(idx);\n  Jh = J'*We*J + Wn*(Ek + 0.002);  %Hk + wn\n  \n  gerr = J'*We*err;    %gk\n  dq   = Jh \\ gerr;    %new\n  \n  MoveJoints(idx, dq);\n  ForwardKinematics(1);\n  err = CalcVWerr(Target, uLINK(to));\n  Ek2 = err'*We*err;\n  if Ek2 < 1E-12\n      break;\n  elseif Ek2 < Ek\n      Ek = Ek2;\n  else\n      MoveJoints(idx, -dq);  % revert\n      ForwardKinematics(1);\n      break, \n  end\nend\n \nerr_norm = norm(err);", "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/InverseKinematics_LM_ver2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252812, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5817748199069612}}
{"text": "function Sigma = UpdateCMA(X,Sigma,gen)\n% Update the CMA model\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    n = size(X,2);\n    \n    %% Calculate the CMA parameters\n    mu    = 4 + floor(3*log(n));\n    mu1   = floor(mu/2);\n    w     = log((mu+1)/2) - log(1:mu1);\n    w     = w./sum(w);\n    mueff = 1./sum(w.^2);\n    cs    = (mueff+2)./(n+mueff+5);\n    ds    = 1 + 2*max(0,sqrt((mueff-1)./(n+1))-1) + cs;\n    cc    = (4+mueff/n)./(n+4+2*mueff/n);\n    c1    = 2./((n+1.3).^2+mueff);\n    cmu   = min(1-c1,2*(mueff-2+1/mueff)./((n+2).^2+mueff)); % Modified\n    ENI   = sqrt(n)*(1-1/4/n+1/21/n^2);\n    \n    %% Update the CMA model\n    y           = (X(1:mu1,:)-repmat(Sigma.x,mu1,1))/Sigma.sigma;\n    yw          = w*y;\n    Sigma.x     = Sigma.x + Sigma.sigma*yw;\n    Sigma.ps    = (1-cs)*Sigma.ps + sqrt(cs*(2-cs)*mueff)*Sigma.C^(-1/2)*yw';\n    hs          = norm(Sigma.ps)./sqrt(1-(1-cs).^(2*(gen+1))) < (1.4+2/(n+1))*ENI;\n    deltahs     = 1 - hs; % Modified\n    Sigma.pc    = (1-cc)*Sigma.pc + hs*sqrt(cc*(2-cc)*mueff)*yw;\n    Sigma.sigma = Sigma.sigma*exp(cs/ds*(norm(Sigma.ps)/ENI-1));\n    Sigma.C     = (1-c1-cmu)*Sigma.C + c1*(Sigma.pc'*Sigma.pc+deltahs*Sigma.C) + cmu*y'*diag(w)*y;\n    Sigma.C     = triu(Sigma.C) + triu(Sigma.C,1)'; % Enforce symmetry\n    \n    %% Reset the CMA model if possible\n    [B,D] = eig(Sigma.C);\n    diagD = diag(D);\n    diagC = diag(Sigma.C);\n    ConditionCov  = max(diagD) > 1e14*min(diagD);\n    NoEffectCoord = any(Sigma.x==Sigma.x+0.2*Sigma.sigma*sqrt(diagC)');\n    NoEffectAxis  = all(Sigma.x==Sigma.x+0.1*Sigma.sigma*sqrt(diagD(mod(gen,n)+1))*B(:,mod(gen,n)+1)');\n    TolXUp        = any(Sigma.sigma*sqrt(diagC)>1e4);\n    if ConditionCov || NoEffectCoord || NoEffectAxis || TolXUp\n        Sigma = struct('s',[],'x',[],'sigma',0.5,'C',eye(n),'pc',0,'ps',0);\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/MOEA-D-CMA/UpdateCMA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5817748093107127}}
{"text": "function vesselness_wrapper = PTKComputeVesselnessFromHessianeigenvalues(hessian_eigs_wrapper, voxel_size)\n    % PTKComputeVesselnessFromHessianeigenvalues. Vesselness filter for detecting blood vessels\n    %\n    %     PTKComputeVesselnessFromHessianeigenvalues computes a mutiscale\n    %     vesselness filter based on Frangi et al., 1998. \"Multiscale Vessel\n    %     Enhancement Filtering\". The filter returns a value at each point which\n    %     in some sense representes the probability of that point belonging to a\n    %     blood vessel.\n    %\n    %     This function takes in a PTKWraper object which can either contain a nx6\n    %     matrix containing the 3 Hessian matrix eigenvalues for each of n\n    %     points, or it can be an ixjxkx3 matrix representing the 3 Hessian\n    %     matrix eigenvalues for an image of dimension ixjxk.\n    %\n    %     The output is a single vesselness value for each input point.\n    %\n    %     See the PTKVesselness plugin for example usage.\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    % lam1 = smallest eigenvalue, lam3 = largest eigenvalue\n    \n    vesselness_wrapper = CoreWrapper;\n    \n    % The input matrix could be a linear set of points, or an image matrix\n    if ndims(hessian_eigs_wrapper.RawImage) == 2\n        lam1 = hessian_eigs_wrapper.RawImage(:, 1); % smallest\n        lam2 = hessian_eigs_wrapper.RawImage(:, 2);\n        lam3 = hessian_eigs_wrapper.RawImage(:, 3); % biggest\n    else\n        lam1 = hessian_eigs_wrapper.RawImage(:,:,:,1); % smallest\n        lam2 = hessian_eigs_wrapper.RawImage(:,:,:,2);\n        lam3 = hessian_eigs_wrapper.RawImage(:,:,:,3); % biggest\n    end\n    \n    term_1 = abs(lam2./lam3); % Ra\n    alpha = 0.5;\n    term_1 = 1 - exp((-term_1.^2)./(2*alpha^2));\n        \n    term_2 = abs(lam1)./sqrt(abs(lam2.*lam3)); % Rb\n    beta = 0.5;\n    term_2 = exp((-term_2.^2)./(2*beta^2));\n\n    term_3 = sqrt(lam1.^2 + lam2.^2 + lam3.^2); % S\n    \n    % Frangi et al. choose a noise threshold based on the Hessian mean.\n    % However, we find a fixed experimentally-chosen threshold works better, but\n    % this must be scaled by the voxel size\n    multiple_matrix = voxel_size'*voxel_size;\n    c_scaling = 1/mean(multiple_matrix(:));\n    c = 400*c_scaling;\n    \n    term_3 = 1 - exp((-term_3.^2)./(2*c^2));\n    \n    check_signs = (lam2 <= 0) & (lam3 <= 0);\n\n    vesselness_wrapper.RawImage = term_1.*term_2.*term_3.*check_signs;\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/Vessels/PTKComputeVesselnessFromHessianeigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.581717588971128}}
{"text": "function Wmat = bst_shepards(destLoc, srcLoc, nbNeighbors, excludeParam, expDistance)\n% BST_SHEPARDS: 3D nearest-neighbor interpolation using Shepard's weighting.\n%\n% USAGE:  Wmat = bst_shepards(destLoc, srcLoc, nbNeighbors=8, excludeParam=0, expDistance=2)\n%\n% INPUT:\n%    - srcLoc       : Nx3 array of original locations, or tesselation structure (Faces,Vertices,VertConn)\n%    - destLoc      : NNx3 array of locations onto original data will be interpolated, or tesselation structure (Faces,Vertices,VertConn)\n%    - nbNeighbors  : Number of nearest neighbors to be considered in the interpolation (default is 8)\n%    - excludeParam : If > 0, the source points that are two far away from the destination surface are ignored.\n%                     Excluded points #i that have: (minDist(i) > mean(minDist) + excludeParam * std(minDist))\n%                     where minDist represents the minimal distance between each source point and the destination surface\n%                     If < 0, exclude the vertices that are further from the absolute distance excludeParam  (in millimeters)\n%    - expDistance  : Distance exponent (if higher, influence of a value decreases faster)\n%    \n% OUTPUT:\n%    - Wmat : Interpolation matrix\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, 2010-2017\n\n%% ===== PARSE INPUTS =====\n% Check number of arguments\nif (nargin < 2)\n    error('Usage: Wmat = bst_shepards(destLoc, srcLoc, nbNeighbors, excludeParam, expDistance)');\nend\n% Check matrices orientation\nif ((size(destLoc, 2) ~= 3) || (size(srcLoc, 2) ~= 3)) && ((size(destLoc, 2) ~= 2) || (size(srcLoc, 2) ~= 2))  \n    error('destLoc and srcLoc must have 2 or 3 columns.');\nend\n% Argument: Number of neighbors for interpolation\nif (nargin < 3) || isempty(nbNeighbors)\n    nbNeighbors = 8; \nend\n% Argument: excludeParam\nif (nargin < 4) || isempty(excludeParam)\n    excludeParam = 0;\nend\n% Argument: expDistance\nif (nargin < 5) || isempty(expDistance)\n    expDistance = 2;\nend\n\n%% ===== SHEPARDS INTERPOLATION =====\n% Allocate interpolation matrix\nnDest = size(destLoc,1);\nnSrc  = size(srcLoc,1);\n% Maximum number of neighbors = number of electrodes\nif (nbNeighbors > nSrc)\n    nbNeighbors = nSrc;\nend\n\n% Find nearest neighbors\n[I,dist] = bst_nearest(srcLoc, destLoc, nbNeighbors, 1);\n% Square the distance matrix\ndist = dist .^ 2;\n% Eliminate zeros in distance matrix for stability\ndist(dist == 0) = eps;\n\n% One neighbor\nif (nbNeighbors == 1)\n    Wmat = sparse(1:nDest, I(:)', ones(1,nDest), nDest, nSrc);\n\n% More complicated cases\nelseif (nbNeighbors > 1)\n    % Interpolation weights from Shepards method\n    W = (bst_bsxfun(@minus, dist(:,nbNeighbors), dist) ./ bst_bsxfun(@times, dist(:,nbNeighbors), dist)) .^ expDistance;\n    sumW = sum(W(:,1:nbNeighbors-1),2);\n    % Correct zero values: points overlap exactly => take only the first point\n    iZeroW = find(sumW == 0);\n    if ~isempty(iZeroW)\n        sumW(iZeroW) = 1;\n        W(iZeroW, 1:nbNeighbors-1) = ones(length(iZeroW),1) * [1,zeros(1,nbNeighbors-2)];\n    end\n    W = W(:,1:nbNeighbors-1) ./ (sumW * ones(1,nbNeighbors-1));    \n    % Create sparse matrix with those weights\n    i = repmat((1:nDest)', nbNeighbors-1, 1);\n    j = reshape(I(:, 1:nbNeighbors-1), [], 1);\n    Wmat = sparse(i, j, W(:), nDest, nSrc);\nend\n\n\n%% ===== IGNORE VERTICES TOO FAR AWAY =====\n% Set to zero the weights of the vertices that are too far away from the sources\n% EEG: Distance relative to the mean distance between sensors\nif (excludeParam > 0)\n    % Find vertices that are too far from their nearest neighbors\n    iTooFarVertices = (dist(:,1) > mean(dist(:,1)) + excludeParam * std(dist(:,1)));\n    % Remove them from the interpolation matrix\n    Wmat(iTooFarVertices, :) = 0;\n% SEEG/ECOG: Absolute distance\nelseif (excludeParam < 0)\n    % Find vertices that are too far from their nearest neighbors (in millimeters)\n    iTooFarVertices = (sqrt(dist(:,1)) >  abs(excludeParam));\n    % Remove them from the interpolation matrix\n    Wmat(iTooFarVertices, :) = 0;\nend\n\n\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_shepards.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5817175799464097}}
{"text": "function [ Z, H, dnorm ] = deep_seminmf ( X, layers, varargin )\n\n% Process optional arguments\npnames = { ...\n    'z0' 'h0' 'bUpdateH' 'bUpdateLastH' 'maxiter' 'TolFun', 'verbose', 'bUpdateZ', 'cache' ...\n};\n\nnum_of_layers = numel(layers);\n\nZ = cell(1, num_of_layers);\nH = cell(1, num_of_layers);\n\ndflts  = {0, 0, 1, 1, 500, 1e-5, 1, 1, 1};\n\n[z0, h0, bUpdateH, bUpdateLastH, maxiter, tolfun, verbose, bUpdateZ, cache] = ...\n        internal.stats.parseArgs(pnames,dflts,varargin{:});\n\nif  ~iscell(h0)\n    for i_layer = 1:length(layers)\n        if i_layer == 1\n            % For the first layer we go linear from X to Z*H, so we use id\n            V = X;\n        else \n            V = H{i_layer-1};\n        end\n        \n        if verbose\n            display(sprintf('Initialising Layer #%d with k=%d with size(V)=%s...', i_layer, layers(i_layer), mat2str(size(V))));\n        end\n        \n        % For the later layers we use nonlinearities as we go from\n        % g(H_{k-1}) to Z*H_k\n        [Z{i_layer}, H{i_layer}, init_err{i_layer}] = ...\n             seminmf(V, ...\n                 layers(i_layer), ...\n                 'maxiter', maxiter, ...\n                 'bUpdateH', true, 'bUpdateZ', bUpdateZ, 'verbose', verbose); \n                 %'bUpdateH', true, 'bUpdateZ', bUpdateZ, 'verbose', verbose, 'save', cache); \n    end\n\nelse\n    Z=z0;\n    H=h0;\n    \n    if verbose\n        display('Skipping initialization, using provided init matrices...');\n    end\nend\n\n\ndnorm0 = cost_function(X, Z, H);\ndnorm = dnorm0;\n\nif verbose\n    display(sprintf('#%d error: %f', 0, dnorm0));\nend\n\n%%% Error Propagation\nif verbose\n    display('Finetuning...');\nend\nH_err = cell(1, num_of_layers);\n\n\nfor iter = 1:maxiter  \n    H_err{numel(layers)} = H{numel(layers)};\n    for i_layer = numel(layers)-1:-1:1\n        H_err{i_layer} = Z{i_layer+1} * H_err{i_layer+1};\n    end\n    \n    for i = 1:numel(layers)\n        if bUpdateZ\n            try\n                if i == 1\n                    Z{i} = X  * pinv(H_err{1});\n                else\n                    Z{i} = pinv(D') * X * pinv(H_err{i});\n                end\n            catch \n                display(sprintf('Convergance error %f. min Z{i}: %f. max %f', norm(Z{i}, 'fro'), min(min(Z{i})), max(max(Z{i})))); \n            end\n        end\n        \n        if i == 1\n            D = Z{1}';\n        else\n            D = Z{i}' * D;\n        end\n       \n        if bUpdateH && (i < numel(layers) || (i == numel(layers) && bUpdateLastH))\n            A = D * X;\n            Ap = (abs(A)+A)./2;\n            An = (abs(A)-A)./2;\n\n            B = D * D';\n            \n            Bp = (abs(B)+B)./2;\n            Bn = (abs(B)-B)./2;\n    \n       \n            H{i} = H{i} .* sqrt((Ap + Bn * H{i}) ./ max(An + Bp * H{i}, 1e-10));\n        end\n    end\n    \n    assert(i == numel(layers));\n    \n    dnorm = cost_function(X, Z, H);\n    \n    if verbose\n        display(sprintf('#%d error: %f', iter, dnorm));\n    end\n    \n    assert(dnorm <= dnorm0 + 1, ...\n        sprintf('Rec. error increasing! From %f to %f. (%d)', ...\n        dnorm0, dnorm, iter) ...\n    );\n    \n    if dnorm0-dnorm <= tolfun*max(1,dnorm0) \n        if verbose\n            display( ...\n                sprintf('Stopped at %d: dnorm: %f, dnorm0: %f', ...\n                    iter, dnorm, dnorm0 ...\n                ) ...\n            );\n        end\n        break;\n    end\n    \n    dnorm0 = dnorm;\nend\nend\n\nfunction error = cost_function(X, Z, H)\n    error = norm(X - reconstruction(Z, H), 'fro');\nend\n\nfunction [ out ] = reconstruction( Z, H )\n\n    out = H{numel(H)};\n\n    for k = numel(H) : -1 : 1;\n        out =  Z{k} * out;\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/algorithms/nmf/Deep-Semi-NMF/deep_seminmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5817175625830395}}
{"text": "%SerialLink.cinertia Cartesian inertia matrix\n%\n% M = R.cinertia(Q) is the NxN Cartesian (operational space) inertia matrix which relates \n% Cartesian force/torque to Cartesian acceleration at the joint configuration Q, and N \n% is the number of robot joints.\n%\n% See also SerialLink.inertia, SerialLink.rne.\n\n% MOD HISTORY\n% \t4/99 add object support\n% $Log: not supported by cvs2svn $\n% $Revision: 1.2 $\n\n\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\nfunction Mx = cinertia(robot, q)\n\tJ = jacob0(robot, q);\n\tJi = inv(J);                %#ok<*MINV>\n\tM = inertia(robot, q);\n\tMx = Ji' * M * Ji;\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/@SerialLink/cinertia.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5817016395810637}}
{"text": "%function particles= resampleParticles(particles, Nmin, fp_debug, resample_randstream)\nfunction particles= resampleParticles(particles, Nmin) %, resample_randstream\n%\n% Resample particles if their weight variance is such that N-effective\n% is less than Nmin.\n%\n\nN = length(particles);\nw = [particles.w];\nws = sum(w); \nw  = w/ws;\n\nNeff = 1 / sum(w .^ 2);\n\n\nif Neff < Nmin\n    %fprintf(fp_debug, 'Particles resampled, Neff = %d\\n', Neff);\n    %disp(['Particles resampled, Neff = ', Neff]);\n    \n    %[keep]    = stratified_resample(w, resample_randstream);%, resample_randstream\n    [keep]    = stratified_resample(w);\n    %fprintf(fp_debug, 'Keep particles: ');\n    particles = particles(keep);\n%     for i=1:N\n%         particles(i).w= 1/N; \n%         fprintf(fp_debug, '%d ', keep(i));\n%         \n%     end\n    %fprintf(fp_debug, '\\n');\n    %disp('Keep particles: ');disp(keep);\nelse\n    for i=1:N\n        particles(i).w= particles(i).w / ws; \n    end\nend\n", "meta": {"author": "i2Nav-WHU", "repo": "Wheel-SLAM", "sha": "e4c2c527635e4383ec2a5aae7d8985dce98ef889", "save_path": "github-repos/MATLAB/i2Nav-WHU-Wheel-SLAM", "path": "github-repos/MATLAB/i2Nav-WHU-Wheel-SLAM/Wheel-SLAM-e4c2c527635e4383ec2a5aae7d8985dce98ef889/resampleParticles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5817016395547926}}
{"text": "%% Anisotropic Diffusion\n%\n% This sample demonstrates Perona-Malik anisotropic diffusion.\n%\n% Sources:\n%\n% * <https://github.com/opencv/opencv_contrib/blob/3.3.0/modules/ximgproc/samples/filterdemo.cpp>\n%\n\nfunction varargout = anisodiff_demo_gui(im)\n    % load source image\n    if nargin < 1\n        src = cv.imread(fullfile(mexopencv.root(),'test','fruits.jpg'), 'Color',true);\n    elseif ischar(im)\n        src = cv.imread(im, 'Color',true);\n    else\n        src = im;\n    end\n\n    % not too big\n    if size(src,1) > 480\n        src = cv.resize(src, [round(480*size(src,2)/size(src,1)), 480]);\n    end\n\n    % create the UI\n    h = buildGUI(src);\n    if nargout > 0, varargout{1} = h; end\nend\n\nfunction onChange(~,~,h)\n    %ONCHANGE  Event handler for UI controls\n\n    % retrieve current values from UI controls\n    niters = round(get(h.slid, 'Value'));\n    set(h.txt, 'String',sprintf('No. of time steps: %2d',niters));\n\n    % apply filtering\n    dst = cv.anisotropicDiffusion(h.src, ...\n        'Alpha',1.0, 'K',0.02, 'Iterations',niters);\n\n    % show result\n    set(h.img, 'CData',dst);\n    drawnow;\nend\n\nfunction h = buildGUI(img)\n    %BUILDGUI  Creates the UI\n\n    % parameters\n    niters = 10;\n    sz = size(img);\n    sz(2) = max(sz(2), 250);  % minimum figure width\n\n    % build the user interface (no resizing to keep it simple)\n    h = struct();\n    h.src = img;\n    h.fig = figure('Name','Anisotropic Diffusion', ...\n        'NumberTitle','off', 'Menubar','none', 'Resize','off', ...\n        'Position',[200 200 sz(2) sz(1)+30-1]);\n    if ~mexopencv.isOctave()\n        %HACK: not implemented in Octave\n        movegui(h.fig, 'center');\n    end\n    h.ax = axes('Parent',h.fig, 'Units','pixels', 'Position',[1 30 sz(2) sz(1)]);\n    if ~mexopencv.isOctave()\n        h.img = imshow(img, 'Parent',h.ax);\n    else\n        %HACK: https://savannah.gnu.org/bugs/index.php?45473\n        axes(h.ax);\n        h.img = imshow(img);\n    end\n    h.txt = uicontrol('Parent',h.fig, 'Style','text', ...\n        'Position',[5 5 150 20], 'FontSize',11, ...\n        'String',sprintf('No. of time steps: %2d',niters));\n    h.slid = uicontrol('Parent',h.fig, 'Style','slider', ...\n        'Position',[155 5 sz(2)-155-5 20], 'Value',niters, ...\n        'Min',0, 'Max',30, 'SliderStep',[1 5]./(30-0));\n\n    % hook event handlers, and trigger default start\n    set(h.slid, 'Callback',{@onChange,h}, ...\n        'Interruptible','off', 'BusyAction','cancel');\n    onChange([],[],h);\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/samples/anisodiff_demo_gui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.5816726908030779}}
{"text": "function [AF,BF]=framebounds(F,varargin);\n%FRAMEBOUNDS  Frame bounds\n%   Usage: fcond=framebounds(F);\n%          [A,B]=framebounds(F);\n%          [...]=framebounds(F,Ls);\n%\n%   `framebounds(F)` calculates the ratio $B/A$ of the frame bounds of the\n%   frame given by *F*. The length of the system the frame bounds are\n%   calculated for is given by `L=framelength(F,1)`.\n%\n%   `framebounds(F,Ls)` additionally specifies a signal length for which\n%   the frame should work. The actual length used is `L=framelength(F,Ls)`.\n%\n%   `[A,B]=framebounds(F)` returns the frame bounds *A* and *B* instead of\n%   just their ratio.\n%\n%\n%   'framebounds` accepts the following optional parameters:\n%\n%     'fac'        Use a factorization algorithm. The function will throw\n%                  an error if no algorithm is available.\n%\n%     'iter'       Call `eigs` to use an iterative algorithm.\n%\n%     'full'       Call `eig` to solve the full problem.\n%\n%     'auto'       Choose the `fac` method if possible, otherwise\n%                  use the `full` method for small problems and the\n%                  `iter` method for larger problems. \n%                  This is the default. \n%\n%     'crossover',c\n%                  Set the problem size for which the 'auto' method\n%                  switches between `full` and `iter`. Default is 200.\n%\n%   The following parameters specifically related to the `iter` method: \n%\n%     'tol',t      Stop if relative residual error of eighs is less than the\n%                  specified tolerance. Default is 1e-9 \n%\n%     'maxit',n    Do at most n iterations in eigs. Default is 100.\n%\n%     'pcgtol',t   Stop if relative residual error of pcg is less than the\n%                  specified tolerance. Default is 1e-6 \n%\n%     'pcgmaxit',n Do at most n iterations in pcg. Default is 150.\n%\n%     'p',p        The number of Lanzcos basis vectors to use.  More vectors\n%                  will result in faster convergence, but a larger amount of\n%                  memory.  The optimal value of `p` is problem dependent and\n%                  should be less than *L*.  The default value chosen \n%                  automatically by eigs.\n% \n%     'print'      Display the progress.\n%\n%     'quiet'      Don't print anything, this is the default.\n%\n%   See also: frame, framered\n\ncomplainif_notenoughargs(nargin,1,'FRAMEBOUNDS');\ncomplainif_notvalidframeobj(F,'FRAMEBOUNDS');\n\n% We handle the container frames first\n  if strcmp(F.type,'fusion')\n      AF=0;\n      BF=0;\n      for ii=1:F.Nframes\n          [A,B]=framebounds(F.frames{ii},varargin{:});\n          AF=AF+(A*F.w(ii)).^2;\n          BF=BF+(B*F.w(ii)).^2;\n      end;\n      AF=sqrt(AF);\n      BF=sqrt(BF);\n        \n      return;\n  end;    \n  \n  if strcmp(F.type,'tensor')\n    AF=1;\n    BF=1;\n    for ii=1:F.Nframes\n      [A,B]=framebounds(F.frames{ii},varargin{:});\n      AF=AF*A;\n      BF=BF*B;\n    end;\n    \n    return;\n  end;    \n    \n  definput.keyvals.Ls=1;\n  definput.keyvals.maxit=100;\n  definput.keyvals.tol=1e-9;\n  definput.keyvals.pcgmaxit=150;\n  definput.keyvals.pcgtol=1e-6;\n  definput.keyvals.crossover=200;\n  definput.keyvals.p=[];\n  definput.flags.print={'quiet','print'};\n  definput.flags.method={'auto','fac','iter','full'};\n  \n  [flags,kv]=ltfatarghelper({'Ls'},definput,varargin);\n  \n  F=frameaccel(F,kv.Ls);\n  L=F.L;\n  \n  % Default values, works for the pure frequency transforms.\n  AF=1;\n  BF=1;\n  \n  % Simple heuristic: If F.g is defined, the frame uses windows.\n  if isfield(F,'g')\n      if isempty(F.g)\n          error('%s: No analysis frame is defined.', upper(mfilename));\n      end;\n      g=F.g;\n      op    = @frana;\n      opadj = @frsyn;\n  end;\n\n  F_isfac = isfield(F,'isfac') && F.isfac;\n  \n  if flags.do_fac && ~F_isfac\n    error('%s: The type of frame has no factorization algorithm.',upper(mfilename));\n  end;\n    \n  if (flags.do_auto && F_isfac) || flags.do_fac\n    switch(F.type)\n     case 'gen'\n      V=svd(g);\n      AF=min(V)^2;\n      BF=max(V)^2;\n     case {'dgt','dgtreal'}\n      [AF,BF]=gabframebounds(g,F.a,F.M,L); \n     case {'dwilt','wmdct'}\n      [AF,BF]=wilbounds(g,F.M,L); \n     case {'filterbank','ufilterbank'}\n      [AF,BF]=filterbankbounds(g,F.a,L);\n     case {'filterbankreal','ufilterbankreal'}\n      [AF,BF]=filterbankrealbounds(g,F.a,L); \n     case 'fwt'\n      [AF,BF]=wfbtbounds({g,F.J,'dwt'},L);\n     case 'wfbt'\n      [AF,BF]=wfbtbounds(g,L);\n     case 'ufwt'\n      [AF,BF]=wfbtbounds({g,F.J,'dwt'},L,F.flags.scaling);\n     case 'uwfbt'\n      [AF,BF]=wfbtbounds(g,L,F.flags.scaling);\n     case 'wpfbt'\n      [AF,BF]=wpfbtbounds(g,L,F.flags.interscaling);\n     case 'uwpfbt'\n      [AF,BF]=wpfbtbounds(g,L,F.flags.interscaling,F.flags.scaling);\n    end;  \n  end;\n  \n  if (flags.do_auto && ~F_isfac && F.L>kv.crossover) || flags.do_iter\n    \n  \n    if flags.do_print\n      opts.disp=1;\n    else\n      opts.disp=0;\n    end;\n    opts.isreal = F.realinput;\n    opts.maxit  = kv.maxit;\n    opts.tol    = kv.tol;\n    opts.issym  = 0;\n    if ~isempty(kv.p)\n       opts.p      = kv.p;\n    end\n    \n    pcgopts.maxit = kv.pcgmaxit;\n    pcgopts.tol = kv.pcgtol;\n\n    % Upper frame bound\n    frameop = @(x) F.frsyn(F.frana(x));\n    BF = real(eigs(frameop,L,1,'LM',opts));\n    \n    % Lower frame bound\n    frameop2 = @(x) F.frsyn(F.frana(x));\n    invfrop = @(x) pcgwrapper(frameop2,x,pcgopts.tol,pcgopts.maxit);\n    \n    % Test convergence of pcg\n    test = randn(L,1);\n    if ~F.realinput, test = test +1i*randn(L,1); end\n    [~,flag] = invfrop(test);\n    \n    % If PCG converges, estimate the smallest eigenvalue, otherwise assume\n    % AF = 0;\n    if ~flag\n        AF = real(eigs(invfrop,L,1,'SM',opts));\n    else \n        AF = 0;\n    end\n\n    \n  end;\n  \n  if (flags.do_auto && ~F_isfac && F.L<=kv.crossover) || flags.do_full\n    % Compute thee transform matrix.\n    bigM=opadj(F,op(F,eye(L)));\n    \n    D=eig(bigM);\n    \n    % Clean the eigenvalues, we know they are real\n    D=real(D);\n    AF=min(D);\n    BF=max(D);\n  end;\n\n  if nargout<2\n    % Avoid the potential warning about division by zero.\n    if AF==0\n      AF=Inf;\n    else\n      AF=BF/AF;\n    end;\n  end;\n  \nend\n\n% In order to mute pprinting out pcg progress\nfunction [y,flag]=pcgwrapper(varargin)\n[y,flag,dummyrelres,dummyiter] = pcg(varargin{:});\nend\n\n% The function has been written in this way, because Octave (at the time\n% of writing) does not accept additional parameters at the end of the\n% line of input arguments for eigs\nfunction y=afun(x,F_in,op_in,opadj_in)\n  persistent F;\n  persistent op;\n  persistent opadj;\n  \n  if nargin>1\n    F     = F_in; \n    op    = op_in;\n    opadj = opadj_in;\n  else\n    y=opadj(F,op(F,x));\n  end;\n\nend\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/frames/framebounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5816726843697722}}
{"text": "function [ xmin, ixmin ] = i4row_min ( m, n, x )\n\n%*****************************************************************************80\n%\n%% I4ROW_MIN returns the minimums of rows of an I4ROW.\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, integer M, N, the number of rows and columns in the array.\n%\n%    Input, integer X(M,N), the array to be examined.\n%\n%    Output, integer XMIN(M), the minimums of the rows of X.\n%\n%    Output, integer IXMIN(M); IXMIN(I) is the column of X in which\n%    the minimum for row I occurs.\n%\n  for i = 1 : m\n\n    ixmin(i) = 1;\n    xmin(i) = x(i,1);\n    for j = 2 : n\n      if ( x(i,j) < xmin(i) )\n        ixmin(i) = j;\n        xmin(i) = x(i,j);\n      end\n    end\n\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/i4lib/i4row_min.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.5816726779364662}}
{"text": " function [err, sn, kernel] = nufft1_error(om, N1, J1, K1, kernel, sn)\n%function [err, sn, kernel] = nufft1_error(om, N1, J1, K1, kernel, sn)\n%\n% Compute worst-case error for each input frequency for 1D NUFFT\n% using specified (inline) `ad hoc' kernel function (e.g., gaussian).\n% This is worst-case for a unit-norm signal of length N1.\n% in\n%\tom\t[M,1]\tdigital frequency omega in radians\n%\tN1\t\tsignal length\n%\tJ1\t\t# of neighbors used per frequency location\n%\tK1\t\tFFT size (should be > N1)\n%\tkernel\t\tinline kernel function, args (k,J)\n%\t\t\t\t(or choose from built-in examples - see code!)\n%\tsn\t\toptional scaling factors (otherwise do-no-harm)\n% out\n%\terr\t[M,1]\tworst-case error over unit-norm signals\n%\tsn\t[N,1]\tscaling factors\n%\n% examples for kernel:\n% linear:\t\tinline('(1 - abs(k/(J/2))) .* (abs(k) < J/2)', 'k', 'J')\n% truncated diric:\tinline('sinc(k) .* (abs(k) < J/2)', 'k', 'J')\n%\n% Copyright 2001-12-7, Jeff Fessler, The University of Michigan\n\n% if no arguments, give an example, comparing triangular kernel to min-max\nif nargin < 4\n\thelp(mfilename)\n\tN = 2^7; K = 2*N; gam = 2*pi/K;\n\tJlist = [2:10]';\n\tom = gam * linspace(0,1,101);\n\n\terr.linear\t= zeros(size(Jlist));\n\terr.minmaxu\t= zeros(size(Jlist));\n\terr.minmax2\t= zeros(size(Jlist));\n\terr.minmaxo\t= zeros(size(Jlist));\n\terr.minmaxk\t= zeros(size(Jlist));\t% kaiser sn's\n\terr.gauss_zn\t= zeros(size(Jlist));\n\terr.gauss_ft\t= zeros(size(Jlist));\n\terr.kaiser\t= zeros(size(Jlist));\n\n\tfor ii=1:length(Jlist)\n\t\tJ = Jlist(ii);\n\t\tprintf('J=%d', J)\n\t\terr.linear(ii) = ...\n\t\t\tmax(nufft1_error(om, N, J, K, 'linear'));\n\t\terr.minmaxu(ii) = ...\n\t\t\tmax(nufft1_error(om, N, J, K, 'minmax,uniform'));\n\t\terr.minmax2(ii) = ...\n\t\t\tmax(nufft1_error(om, N, J, K, 'minmax,best,L=2'));\n\t\terr.minmaxo(ii) = ...\n\t\t\tmax(nufft1_error(om, N, J, K, 'minmax,best'));\n\t\terr.gauss_zn(ii) = ...\n\t\t\tmax(nufft1_error(om, N, J, K, 'gauss'));\n\t\terr.gauss_ft(ii) = ...\n\t\t\tmax(nufft1_error(om, N, J, K, 'gauss', 'ft'));\n\t\t[tmp, sn] = nufft1_error(om, N, J, K, 'kaiser', 'ft');\n\t\terr.kaiser(ii) = max(tmp);\n\t\terr.minmaxk(ii) = ...\n\t\t\tmax(nufft1_err_mm(om, N, J, K, 'qr', sn));\n\tend\n\tclf, semilogy(Jlist, err.linear, 'g-x', ...\n\t\tJlist, err.minmaxu, 'c-+', ...\n\t\tJlist, err.gauss_zn, 'b-*', ...\n\t\tJlist, err.gauss_ft, 'b-o', ...\n\t\tJlist, err.minmax2, 'r-^', ...\n\t\tJlist, err.kaiser, 'm->', ...\n\t\tJlist, err.minmaxo, 'y-<', ...\n\t\tJlist, err.minmaxk, 'w-o'), axis tight\n\txlabel J, ylabel 'worst-case error'\n\tlegend('linear', 'min-max, uniform', ...\n\t\t'gaussian (zn)', 'gaussian (FT)', ...\n\t\t'min-max, best L=2', 'kaiser', 'min-max, optimized', ...\n\t\t'min-max, kaiser s', 3)\n\tclear err\nreturn\nend\n\n\n%\n% kernel selection\n%\nif ischar(kernel)\n\n\t% min-max interpolators (uniform, best, etc., see nufft1_err_mm.m)\n\tif strncmp(kernel, 'minmax,', 7)\n\t\ttype = kernel(8:end);\t% uniform or best or best,L=2 etc.\n\t\t[err, sn] = nufft1_err_mm(om, N1, J1, K1, 'qr', type);\n\t\treturn\n\n\t% cos^3-tapered dirichlet\n\telseif streq(kernel, 'cos3diric')\n\t\tkernel = 'diric(2*pi*k/J, J) .* cos((2*pi*k/J)/2).^3';\n\n\t% Dirichlet (truncated)\n\telseif streq(kernel, 'diric')\n\t\tkernel = 'nufft_diric(k,%d,%d,1) .* (abs(k) < J/2)';\n\t\tkernel = sprintf(kernel, N1, N1);\n\n\t% gaussian (truncated) with previously numerically-optimized width\n\telseif streq(kernel, 'gauss')\n\t\tif isvar('sn') & ischar(sn) & streq(sn, 'ft')\n\t\t\tstype = 'ft';\n\t\telse\n\t\t\tstype = 'zn';\n\t\tend\n\t\t[dummy, kernel, kernel_ft] = nufft_best_gauss(J1, K1/N1, stype);\n\t\tkernel_ft = inline(kernel_ft, 't');\n\n\t% kaiser-bessel with previously numerically-optimized shape\n\telseif streq(kernel, 'kaiser')\n\t\t[kernel, kb_a, kb_m] = kaiser_bessel('string', J1, 'best', 0, K1/N1);\n\t\tkernel_ft = kaiser_bessel_ft('inline', J1, kb_a, kb_m, 1);\n\n\t% linear interpolation via triangular function (possibly \"wide\"!)\n\telseif streq(kernel, 'linear')\n\t\tkernel = '(1 - abs(k/(J/2))) .* (abs(k) < J/2)';\n\n\telse\n\t\terror(sprintf('unknown kernel \"%s\"', kernel))\n\tend\n\n\tkernel = inline(kernel, 'k', 'J');\n\nelseif ~streq('inline', class(kernel))\n\terror 'need inline kernel'\nend\n\ngam = 2*pi/K1;\n\nif 0\n\t%\tplot interpolator\n\tk = linspace(-J/2-1,J/2+1,101);\n\tclf, subplot(221), plot(k, kernel(k, J))\n\txlabel k, ylabel kernel(k), axis tight, grid\nend\n\n%\n% Compute scaling factors using the \"do no harm\" strategy.\n% This may not be optimal; analytical FT could also be reasonable.\n%\nif ~isvar('sn')\n\tsn = 1 ./ nufft_interp_zn(0, N1, J1, K1, kernel);\t% [N]\n%\tsn = 1 ./ mean(nufft_interp_zn([0 1/2], N1, J1, K1, kernel), 2); % alt\n\nelseif isa(sn, 'inline')\n\tn = [0:(N1-1)]'-(N1-1)/2;\n\tsn = 1 ./ sn(n/K1);\t\t% [N]\n\n% trick to use Gaussian FT scaling factors\nelseif ischar(sn) & streq(sn, 'ft') & isvar('kernel_ft')\n\tn = [0:(N1-1)]'-(N1-1)/2;\n\tsn = 1 ./ kernel_ft(n/K1);\t\t% [N]\n\tif 0 & J1 > 2\n\t\tsn_zn = 1 ./ nufft_interp_zn(0, N1, J1, K1, kernel);\t% [N]\n\t\tclf, plot(n, [sn reale(sn_zn)])\n\t\tkeyboard\n\tend\n\n% trick to use Kaiser-Bessel FT scaling factors\nelseif isstruct(sn) & streq(sn.type, 'kaiser')\n\tn = [0:(N1-1)]'-(N1-1)/2;\n\tsn = 1 ./ kaiser_bessel_ft(n/K1, J1, sn.alpha, sn.m, 1);\n\nelse\n\terror 'unsupport scaling factors type'\nend\n\n%\n% interpolator worst-case error for each frequency (scaled by 1/sqrt(N)),\n% from equations (46)-(47) in Fessler&Sutton NUFFT paper, T-SP, Feb. 2003\n%\nzn = nufft_interp_zn(om/gam, N1, J1, K1, kernel);\t\t% [N,M]\nerr = sqrt(mean(abs(spdiag(sn) * zn - 1).^2, 1))';\t% [M]\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/nufft1_error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5816726703833146}}
{"text": "function [mi3] = oz2mi3(oz)\n% Convert volume from US liquid ounces to cubic miles. \n% Chad Greene 2012\nmi3 = oz*7.0950670584e-15;", "meta": {"author": "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/oz2mi3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5816630377096857}}
{"text": "%   AUTHOR:\n%       Boguslaw Obara, http://boguslawobara.net/\n%% Read image\nim = imread('triple.tif');\nim = im<10;\n%% Skeleton\nim = bwmorph(im, 'thin', inf);\n%% Hit or Miss\nout1 = BOHitOrMiss(im, 'end');\nout2 = BOHitOrMiss(im, 'triple');\n%% Plot\nims = im;\nims = ims + 2*out1;\nims = ims + 8*out2;\nimagesc(ims);\n%%", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21573-skeleton-end-and-triple-points/BOHitOrMiss/BOHitOrMiss_TEST.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5816630218968956}}
{"text": "function pcut = addEvalVariableCuts(p)\n\npcut = p;\nif ~isempty(p.evalMap) \n    pcut = emptyNumericalModel;\n    for i = 1:length(p.evalMap)\n        y = p.evalVariables(i);\n        x = p.evalMap{i}.variableIndex;\n        xL = p.lb(x);\n        xU = p.ub(x);\n        \n        % Generate a convex hull polytope\n        if xL<xU\n            if ~isempty(p.evalMap{i}.properties.convexhull)\n                % A convex hull generator function is available!\n                % Might be able to reuse hull from last run node\n                if isfield(p.evalMap{i},'oldhull') && isequal(p.evalMap{i}.oldhull.xL,xL) && isequal(p.evalMap{i}.oldhull.xU,xU)\n                    [Ax,Ay,b,K] = getOldHull(p,i);\n                else\n                    [Ax,Ay,b,K,p] = updateHull(xL,xU,p,i);\n                    if isempty(Ax)\n                        % Operator bounder does not cover this interval so\n                        % use the sample-based instead\n                        [Ax,Ay,b,K,p] = convexhullSampled(xL,xU,p,i);\n                    end\n                end              \n            else               \n               [Ax,Ay,b,K] = convexhullSampled(xL,xU,p,i);               \n            end\n            if ~isempty(b)\n                if isempty(K)\n                    % Compatibility with old code\n                    K.f = 0;\n                    K.l = length(b);\n                end\n                F_structemp = zeros(size(b,1),length(p.c)+1);\n                F_structemp(:,1+y) = -Ay;\n                F_structemp(:,1+x) = -Ax;\n                F_structemp(:,1) = b;\n                localModel = createNumericalModel(F_structemp,K);\n                pcut = mergeNumericalModels(pcut,localModel);             \n            end\n        end\n    end\n    \n    pcut = mergeNumericalModels(p,pcut);\nend\n\nfunction [Ax,Ay,b,K] = getOldHull(p,i);\n\nAx = p.evalMap{i}.oldhull.Ax;\nAy = p.evalMap{i}.oldhull.Ay;\nb = p.evalMap{i}.oldhull.b;\nK = p.evalMap{i}.oldhull.K;\n\nfunction [Ax,Ay,b,K,p] = updateHull(xL,xU,p,i);\n\ntry\n    [Ax,Ay,b,K]=feval(p.evalMap{i}.properties.convexhull,xL,xU, p.evalMap{i}.arg{2:end-1});\ncatch\n    [Ax,Ay,b]=feval(p.evalMap{i}.properties.convexhull,xL,xU, p.evalMap{i}.arg{2:end-1});\n    if ~isempty(Ax)\n        problem = find(any(isinf([Ax Ay b]),2) | any(isnan([Ax Ay b]),2));\n        Ax(problem,:) = [];\n        Ay(problem,:) = [];\n        b(problem) = [];\n    end\n    K = [];\nend\np = saveOldHull(xL,xU,Ax,Ay,b,K,p,i);\n\nfunction p = saveOldHull(xL,xU,Ax,Ay,b,K,p,i)\np.evalMap{i}.oldhull.xL = xL;\np.evalMap{i}.oldhull.xU = xU;\np.evalMap{i}.oldhull.Ax = Ax;\np.evalMap{i}.oldhull.Ay = Ay;\np.evalMap{i}.oldhull.b = b;\np.evalMap{i}.oldhull.K = K;\n\nfunction [Ax,Ay,b,K,p] = convexhullSampled(xL,xU,p,i)\n\nif length(xL)>1\n    Ax = [];\n    Ay = [];\n    b = [];\n    K = [];\n    return\nend\n% sample function\nz = linspace(xL,xU,100);\n\nif isequal(p.evalMap{i}.fcn,'power_internal2')\n    % Special code for automatically converting sigmonial\n    % terms to be solvable with bmibnb\n    fz = feval(p.evalMap{i}.fcn,z,p.evalMap{i}.arg{2});\n    \nelse\n    arg = p.evalMap{i}.arg;\n    arg{1} = z;\n    fz = real(feval(p.evalMap{i}.fcn,arg{1:end-1}));\n    % end\n    [minval,minpos] = min(fz);\n    [maxval,maxpos] = max(fz);\n    xtestmin = linspace(z(max([1 minpos-5])),z(min([100 minpos+5])),100);\n    xtestmax = linspace(z(max([1 maxpos-5])),z(min([100 maxpos+5])),100);\n    arg{1} = xtestmin;\n    fz1 = real(feval(p.evalMap{i}.fcn,arg{1:end-1}));\n    arg{1} = xtestmax;\n    fz2 = real(feval(p.evalMap{i}.fcn,arg{1:end-1}));\n    z = [z(:);xtestmin(:);xtestmax(:)];\n    fz = [fz(:);fz1(:);fz2(:)];\n    [z,sorter] = sort(z);\n    fz = fz(sorter);\n    [z,ii,jj]=unique(z);\n    fz = fz(ii);\nend\n\n[Ax,Ay,b] = convexhullFromSampled(z,fz,xL,xU);\nK = [];\n\np = saveOldHull(xL,xU,Ax,Ay,b,K,p,i);", "meta": {"author": "shamilmamedov", "repo": "dynamic_calibration", "sha": "11af40e7deb758ec080a175fed8fcdd6c99aca29", "save_path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration", "path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration/dynamic_calibration-11af40e7deb758ec080a175fed8fcdd6c99aca29/utils/YALMIP-master/modules/global/addEvalVariableCuts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5816630215506806}}
{"text": "% SOLVE_MAXWELL_EIG_MIXED1: Solve the Maxwell eigenvalue problem with a mixed formulation, and a B-spline discretization.\n%\n% Example to solve the problem\n%\n%    curl (1/mu(x) curl (u)) = lambda (epsilon(x) u)   in Omega = F((0,1)^n)\n%          div (epsilon(x) u) = 0                       in Omega \n%       (1/mu(x) curl(u)) x n = 0                       on Gamma_N\n%                       u x n = 0                       on Gamma_D\n%\n% with the variational mixed formulation\n%\n%    \\int (1/mu(x) curl(u) curl(v)) + \\int (epsilon(x) v grad(p)) \n%                = lambda \\int (epsilon(x) u v),   \\forall v \\in H_0(curl),\n%                                     \\int (epsilon(x) u grad(q)) = 0,  \n%                                                  \\forall q \\in H^1_0.\n%\n% USAGE:\n%\n%  [geometry, msh, space, sp_mul, eigv, eigf] = \n%                  solve_maxwell_eig_mixed1 (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%    - c_elec_perm:  electric permittivity (epsilon in the equation)\n%    - c_magn_perm:  magnetic permeability (mu in the equation)\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 functions (see sp_vector)\n%  sp_mul:   space object for the multiplier (see sp_scalar)\n%  eigv:     the computed eigenvalues\n%  eigf:     degrees of freedom of the associated eigenfunctions\n%\n% See also EX_MAXWELL_EIG_MIXED1_SQUARE for an example\n%\n% Copyright (C) 2010, 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 <http://www.gnu.org/licenses/>.\n\nfunction [geometry, msh, space, sp_mul, eigv, eigf] = ...\n              solve_maxwell_eig_mixed1 (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);\n\n[knots, zeta] = kntrefine (geometry.nurbs.knots, nsub-1, degree, regularity);\n[knots_hcurl, degree_hcurl] = knt_derham (knots, degree, 'Hcurl');\n\n% Construct msh structure\nrule     = msh_gauss_nodes (nquad);\n[qn, qw] = msh_set_quad_nodes (zeta, rule);\nmsh      = msh_cartesian (zeta, qn, qw, geometry);\n\n% Construct the space structures for the field and the Lagrange multiplier\nscalar_spaces = cell (msh.ndim, 1);\nfor idim = 1:msh.ndim\n  scalar_spaces{idim} = sp_bspline (knots_hcurl{idim}, degree_hcurl{idim}, msh);\nend\nspace = sp_vector (scalar_spaces, msh, 'curl-preserving');\nsp_mul = sp_bspline (knots, degree, msh);\n\n% Assemble the matrices\nif (msh.rdim == 2)\n  invmu = @(x,y) 1./c_magn_perm (x,y);\nelseif (msh.rdim == 3)\n  invmu = @(x,y,z) 1./c_magn_perm (x,y,z);\nend\n\nstiff_mat = op_curlu_curlv_tp (space, space, msh, invmu);\nmass_mat  = op_u_v_tp (space, space, msh, c_elec_perm);\nsaddle_mat = op_v_gradp_tp (space, sp_mul, msh, c_elec_perm);\n\n% Apply homogeneous Dirichlet boundary conditions\ndrchlt_dofs = []; drchlt_dofs_mul = [];\nfor iside = 1:numel (drchlt_sides)\n  drchlt_dofs = union (drchlt_dofs, space.boundary(drchlt_sides(iside)).dofs);\n  drchlt_dofs_mul = union (drchlt_dofs_mul, sp_mul.boundary(drchlt_sides(iside)).dofs);\nend\nif (isempty (drchlt_dofs_mul))\n  drchlt_dofs_mul = sp_mul.ndof;\nend\n\nint_dofs = setdiff (1:space.ndof, drchlt_dofs);\nint_dofs_mul = setdiff (1:sp_mul.ndof, drchlt_dofs_mul);\n\n% Solve the eigenvalue problem\nstiff_mat  = stiff_mat (int_dofs, int_dofs);\nmass_mat   = mass_mat (int_dofs, int_dofs);\nsaddle_mat = saddle_mat (int_dofs_mul, int_dofs);\n\nA = [stiff_mat, saddle_mat.'; ...\n     saddle_mat, sparse(numel(int_dofs_mul),numel(int_dofs_mul))];\nM = [mass_mat, sparse(numel(int_dofs), numel(int_dofs_mul)); ...\n     sparse(numel(int_dofs_mul), numel(int_dofs)+numel(int_dofs_mul))];\n\neigf = zeros (space.ndof + sp_mul.ndof, numel(int_dofs) + numel(int_dofs_mul));\n[eigf([int_dofs space.ndof+int_dofs_mul], :), eigv] = eig (full(A), full(M));\neigv = diag (eigv);\n\nend\n\n%!demo\n%! ex_maxwell_eig_mixed1_square\n\n%!demo\n%! ex_maxwell_eig_mixed1_Lshaped\n\n%!demo\n%! ex_maxwell_eig_mixed1_cube\n\n%!demo\n%! ex_maxwell_eig_mixed1_thick_L\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_maxwell_eig_mixed1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5816630213775725}}
{"text": "function J = J_func_pTop(q, t, r, b, nv)\nlen = size(r, 1);\nR = q2R(q);\nJ = 0;\nfor i = 1 : len\n   rr = r(i, :).';\n   bb = b(i, :).';\n   J = J + 1 / len * (nv(i, :) * (R * rr + t - bb))^2; \nend\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/func_files/J_func_pTop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5816630166259651}}
{"text": "function X = coeffs2vals( X )\n%COEFFS2VALS Convert an array of Chebyshev--Fourier--Fourier of\n%            coefficients to an array of values.\n%\n%   COEFFS2VALS( CFS ) computes the values on a tensor-product doubled-up\n%   spherical grid of a function that is represented by a\n%   Chebyshev-Fourier-Fourier expansion with expansion coefficients CFS.\n%\n% See also CHEBFUN.COEFFS2VALS, VALS2COEFFS.\n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif isempty( X )\n    return\nend\n\n[m, n, p] = size( X );\n\n% Old slow approach:\n% for k = 1:p\n%     X(:,:,k) = chebtech2.coeffs2vals( X(:,:,k) );\n%     X(:,:,k) = trigtech.coeffs2vals( X(:,:,k).' ).';\n% end\n% for j = 1:n\n%     vj = reshape( X(:,j,:), m, p );\n%     vj = trigtech.coeffs2vals( vj.' ).';\n%     X(:,j,:) = reshape( vj, m, 1, p );\n% end\n\n% Faster approach, but code less readable:\nif ( m > 1 ) \n    X(2:m-1, :, :) = X(2:m-1, :, :)/2; \n    X = fft( vertcat(X, X(m-1:-1:2,:,:)), [], 1 );\n    X = X(m:-1:1, :, :);\nend\n\nscl_p = (n*p)*even_odd_fix( p );\nscl_n = even_odd_fix( n );\nEnp = reshape(scl_n.'*scl_p, [1 n p]);\n\nX = ifft(ifft(ifftshift(ifftshift(X.*repmat( Enp, m, 1, 1),2),3), [], 2),[],3);\n\nend\n\nfunction scl = even_odd_fix( n )\n\nif ( mod(n, 2) ) \n    scl = (-1).^(-(n-1)/2:(n-1)/2);\nelse\n    scl = (-1).^((-n/2):(n/2-1));\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/@ballfun/coeffs2vals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5816630166259651}}
{"text": "function y = logsumexp(x, dim)\n% compute log(sum(exp(x),dim)) while avoiding numerical underflow\nxmax = max(x, [], dim);\ny    = xmax + log(sum(exp(bsxfun(@minus, x, xmax)), dim));\nind  = find(~isfinite(xmax));\nif ~isempty(ind)\n    y(ind) = xmax(ind);\nend", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/GMM/logsumexp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5816630111819276}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\n% Script chap::2::script\n% Density CEV Model\n\nt = 10;                                      % maturity\nf0 = 0.03;                                  % spot value\n\nfigname = 'Risk Neutral Density - CEV';\n\nx = 0:0.001:2;                            % range\n\nsigma_base = 0.2;                           % volatility base scenario\nbeta_base = 0.5;                            % CEV exponent base scenario\n\ny_base = pcev(t,x,f0,sigma_base, beta_base);\nlegendname_base = 'Base';\n%% Changing sigma_base\nsigma_low = 0.15;\nsigma_high = 0.25;\n\ny_low = pcev(t,x,f0,sigma_low, beta_base);\ny_high = pcev(t,x,f0,sigma_high, beta_base);\n\nlegendname_low = 'Changing \\sigma low value';\nlegendname_high = 'Changing \\sigma high value';\n\ncreatefigure_density(x,y_base,y_low,y_high,...\n    figname, legendname_base,legendname_low,legendname_high);\n\n%% Changing beta_base\nbeta_low = 0.3;\nbeta_high = 0.7;\n\ny_low = pcev(t,x,f0,sigma_base, beta_low);\ny_high = pcev(t,x,f0,sigma_base, beta_high);\n\nlegendname_low = 'Changing \\beta low value';\nlegendname_high = 'Changing \\beta high value';\n\ncreatefigure_density(x,y_base,y_low,y_high,...\n    figname, legendname_base,legendname_low,legendname_high);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/36966-risk-neutral-densities-for-financial-models/Script_Density_CEV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.5816497121317227}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\n% Script chap::2::script\n% Density Heston Model\n%\n%   uses the characteristic function of the Heston model\n%\nt = 10;                             % maturity\na = 600;                            % spot value\nN = 512;                            % number of grid points  \nx = ( (0:N-1) - N/2 ) / a;          % range\n\nfigname = 'Risk Neutral Density - Heston-Hull-White';\n\nvInst_base = 0.02;                  % instantanuous variance of base parameter set  \nvLong_base = 0.02;                  % long term variance of base parameter set\nkappa_base = 0.1;                   % mean reversion speed of variance of base parameter set\nomega_base = 0.2;                   % volatility of variance of base parameter set\nrho_base = 0;                       % correlation of base parameter set\n\nlambda_base = 0.1;\neta_base = 0.02;\n\nicurveData = [0.999884333380315;0.996803132736937;0.993568709230647;0.990285301195274;0.986945903402709;0.983557350486521;0.980185549124449;0.976782934344041;0.973361992614499;0.969976793305220;0.966616749933289;0.962914317958160;0.959904777446077;0.920091903961326;0.882870065420196;0.847186544281939;0.812742515687365;0.779459552415061;0.747152463119429;0.715745016074346;0.685138723808460;0.655753392359115;0.627333845297308;0.599226698198774;0.572763319281569;0.547259133751455;0.523441996253080;0.499646068368557;0.477507905873099;0.456481811728753;0.436385788738282;0.417350253831050;0.399187111819286;0.381865611666566;0.365435617455498;0.349786183601181;0.334806921914717;0.320548897004994;0.306983265264429;0.294081800917050;0.282443547729164;0.269929224010243];\nicurveDates = [734472;734501;734534;734562;734591;734622;734653;734683;734713;734744;734775;734807;734836;735202;735567;735931;736298;736663;737028;737393;737758;738125;738489;738854;739219;739585;739949;740316;740680;741046;741411;741776;742140;742507;742872;743237;743602;743967;744334;744698;745063;745429];\nicurveInterpMethod = 'spline';\nicurveType = 'Discount';\nicurveSettle = 734471;\nirdc = IRDataCurve(icurveType,icurveSettle,icurveDates,icurveData);\n% cf (characteristic function) for the heston hull white model\nf = @(x) cf_heston(x,vInst_base,vLong_base,kappa_base,omega_base,rho_base,t,0) .* cf_hullwhite(x+1i,t,0,lambda_base,eta_base,irdc);\n\nlegendname_base = 'Base parameter set';\ny_base = fftdensity(f,a,N);         % density calculated from cf for base parameter set\n%% Changing lambda_base\nlambda_low = .005;                    % changing parameter (low value)\nlambda_high = .5;                   % changing parameter (high value)\n\nf_low = @(x) cf_heston(x,vInst_base,vLong_base,kappa_base,omega_base,rho_base,t,0).* cf_hullwhite(x+1i,t,0,lambda_low,eta_base,irdc);\nf_high = @(x)  cf_heston(x,vInst_base,vLong_base,kappa_base,omega_base,rho_base,t,0).* cf_hullwhite(x+1i,t,0,lambda_high,eta_base,irdc);\n\ny_low = fftdensity(f_low,a,N);\ny_high = fftdensity(f_high,a,N);\n\nlegendname_low = 'Changing \\lambda low value';\nlegendname_high = 'Changing \\lambda high value';\n\n% output density as figure\ncreatefigure_density(x,y_base,y_low,y_high,...\n    figname, legendname_base,legendname_low,legendname_high);\n%% Changing eta_base\neta_low = .01;\neta_high = .03;\n\nf_low =  @(x) cf_heston(x,vInst_base,vLong_base,kappa_base,omega_base,rho_base,t,0).* cf_hullwhite(x+1i,t,0,lambda_base,eta_low,irdc);\nf_high =  @(x) cf_heston(x,vInst_base,vLong_base,kappa_base,omega_base,rho_base,t,0).* cf_hullwhite(x+1i,t,0,lambda_base,eta_high,irdc);\n\ny_low = fftdensity(f_low,a,N);\ny_high = fftdensity(f_high,a,N);\n\nlegendname_low = 'Changing \\eta low value';\nlegendname_high = 'Changing \\eta high value';\n\ncreatefigure_density(x,y_base,y_low,y_high,...\n    figname, legendname_base,legendname_low,legendname_high);\n\n\n%% Changing curve_base\nzero = -log(icurveData)./(icurveDates-icurveSettle)*360 - 0.01;\nicurveData_low = exp(-zero .*(icurveDates-icurveSettle)/360);\nzero = -log(icurveData)./(icurveDates-icurveSettle)*360 + 0.01;\nicurveData_high = exp(-zero .*(icurveDates-icurveSettle)/360);\n\nirdc_low = IRDataCurve(icurveType,icurveSettle,icurveDates,icurveData_low);\nirdc_high = IRDataCurve(icurveType,icurveSettle,icurveDates,icurveData_high);\n\nf_low =  @(x) cf_heston(x,vInst_base,vLong_base,kappa_base,omega_base,rho_base,t,0).* cf_hullwhite(x+1i,t,0,lambda_base,eta_base,irdc_low);\nf_high =  @(x) cf_heston(x,vInst_base,vLong_base,kappa_base,omega_base,rho_base,t,0).* cf_hullwhite(x+1i,t,0,lambda_base,eta_base,irdc_high);\n\ny_low = fftdensity(f_low,a,N);\ny_high = fftdensity(f_high,a,N);\n\nlegendname_low = 'Changing curve parallel shift - low value';\nlegendname_high = 'Changing curve parallel shift - high value';\n\ncreatefigure_density(x,y_base,y_low,y_high,...\n    figname, legendname_base,legendname_low,legendname_high);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/36966-risk-neutral-densities-for-financial-models/Script_Density_Heston_HullWhite.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5816497114471052}}
{"text": "function mesh = genMesh3DType2(domain, nx, ny, nz)\n\n%% Usage: mesh structure of a uniform cubic partition\n%\n% INPUTS:\n% domain --- cubic domain = [xmin, xmax, ymin, ymax, zmin, zmax].\n% nx --- the number of uniform partition in x direction.\n% ny --- the number of uniform partition in y direction.\n% nz --- the number of uniform partition in z direction.\n%\n% option.meshinfo --- basic (default): generate only p and t.\n%                     all: enriched mesh information\n%\n% OUTPUTS:\n% mesh --- a struct data contains mesh information.\n% \n% Last Modified: 08/07/2020 by Xu Zhang\n%\n%                A8-------------------A7        The Cube is divided into\n%                /|                   /|        six congruent tetrahedrons\n%               / |                  / |        \n%              /  |                 /  |        \n%             /   |                /   |        (1) A1-A2-A3-A7\n%            /    |               /    |        (2) A1-A6-A2-A7\n%          A5-----+-------------A6     |        (3) A1-A5-A6-A7\n%           |     |             |      |        (4) A1-A8-A5-A7\n%           |     |             |      |        (5) A1-A4-A8-A7\n%           |     |             |      |        (6) A1-A3-A4-A7\n%           |     A4------------+------A3\n%           |     /             |      /\n%           |    /              |     /\n%           |   /               |    /\n%           |  /                |   /\n%           | /                 |  /\n%           |/                  | /\n%          A1-------------------A2\n%\n%% 1. Generate basic mesh info: p t\n[p,T] = genMesh3DRectPT(domain, nx, ny, nz);\nc1 = zeros(5,4);\nc1(1,:) = [1,2,4,5]; \nc1(2,:) = [2,7,5,6]; \nc1(3,:) = [3,2,4,7];\nc1(4,:) = [5,7,4,8];\nc1(5,:) = [2,4,5,7];\nc2 = zeros(5,4);\nc2(1,:) = [1,6,8,5]; \nc2(2,:) = [1,3,6,2]; \nc2(3,:) = [8,6,3,7];\nc2(4,:) = [1,8,3,4];\nc2(5,:) = [1,3,8,6];\n\nCBxy = zeros(nx,ny);\nCBxy(1:2:nx,2:2:ny)=1;\nCBxy(2:2:nx,1:2:ny)=1;\nCB = repmat(CBxy,1,1,nz);\nCB(:,:,1:2:nz) = repmat(1-CBxy,1,1,length(1:2:nz));\nCB = reshape(CB,[],1);\ntid1 = find(CB==1); tid2 = find(CB==0);\n\nt = T(:,c1(1,:));\nt(tid2,:) = T(tid2,c2(1,:));\nfor i = 2:5\n    tmp = T(:,c1(i,:));\n    tmp(tid2,:) = T(tid2,c2(i,:));\n    t = [t;tmp];\nend\n  \nmesh = struct('p',p,'t',t,'T',T);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/genMesh3DType2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5816497083642824}}
{"text": "% DEMOILFGPLVM9 Oil data with three dimensions and variational sparse approximation.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'oil';\nexperimentNo = 9;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('dtcvar');\noptions.kern = {'rbf', 'bias', 'whitefixed'};\noptions.optimiser = 'scg';\nlatentDim = 3;\nd = size(Y, 2);\n\nmodel = fgplvmCreate(latentDim, d, Y, options);\nmodel.kern.comp{3}.variance = 1e-4;\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\nmodelWriteResult(model, dataSetName, experimentNo);\n\nif exist('printDiagram') & printDiagram\n  lvmPrintPlot(model, lbls, dataSetName, experimentNo);\nend\n\n% Load the results and display them.\nlvmScatterPlot(model, lbls,[],[1,2]); % default [1,2], change to plot \n                                      % a different pair of lantent dims\n\n% compute the nearest neighbours errors in latent space.\nerrors = fgplvmNearestNeighbour(model, lbls);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demOilFgplvm9.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5816350117863527}}
{"text": "% generates a rounded rectangle as a test track for tracking control applications\n\nl1 = 100; \nl2 = 20; \nlstep = 2; \nr = 12.5; \nphistep = 0.1; \nphi = phistep:phistep:(pi/2); \nb0 = 10; \n\n% build track snippets\ntrackparts{1} = [lstep:lstep:l1; zeros(1, l1/lstep)]; \ntrackparts{2} = [lstep:lstep:l2; zeros(1, l2/lstep)]; \ntrackparts{3} = [r*cos(phi+3/2*pi); r*sin(phi+3/2*pi)+r]; \n\n% order of track snippets\ntrackgenerator = [1, 3, 2, 3, 1, 3, 2, 3];\n% rotation of track snippets\nrotgenerator = [0, 0, pi/2, pi/2, pi, pi, 3*pi/2, 3*pi/2] + pi/2; \n\n% build up track \nx_m = 0; \ny_m = 0;\nfor i = 1:1:length(trackgenerator)\n  R = [cos(rotgenerator(i)), -sin(rotgenerator(i));...\n    sin(rotgenerator(i)), cos(rotgenerator(i))]; \n  % rotate track part to the right position \n  x_loc = R(1, :)*trackparts{trackgenerator(i)}; \n  y_loc = R(2, :)*trackparts{trackgenerator(i)};\n  % transform trackpart origin to the last point\n  x_m = [x_m, x_loc+x_m(end)]; \n  y_m = [y_m, y_loc+y_m(end)]; \nend\n% generate width vector \nb_m = ones(1, length(x_m))*b0;\n\n% write to csv\ndlmwrite('roundedRectangle.csv', [x_m(1:end-1)',y_m(1:end-1)',b_m(1:end-1)'], ';'); \n\nfigure; \nplot(x_m(1:end-1), y_m(1:end-1)); \naxis equal; \ngrid on; \n", "meta": {"author": "TUMFTM", "repo": "mod_vehicle_dynamics_control", "sha": "48b12705b72740b0c1574b0da2eab66fe0c75127", "save_path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control", "path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control/mod_vehicle_dynamics_control-48b12705b72740b0c1574b0da2eab66fe0c75127/scripts/generateRacetracks/generateRoundedRectangle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5816350009024599}}
{"text": "function r = VBA_spm_gamrnd(a,b,varargin)\n% Random arrays from gamma distribution - a compiled routine\n% FORMAT r = spm_gamrnd(a,b,m,n,...)\n%\n% a        - shape parameter\n% b        - scale parameter\n% m,n,...  - dimensions of the output array [optional]\n%\n% r        - array of random numbers chosen from the gamma distribution\n%__________________________________________________________________________\n%\n% Reference\n% \n% George Marsaglia and Wai Wan Tsang, \"A Simple Method for Generating Gamma\n% Variables\": ACM Transactions on Mathematical Software, Vol. 26, No. 3,\n% September 2000, Pages 363-372\n% http://portal.acm.org/citation.cfm?id=358414\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin\n% $Id: spm_gamrnd.m 3251 2009-07-06 17:29:44Z guillaume $\n\n%-This is merely the help file for the compiled routine\nerror('spm_gamrnd.c not compiled - see Makefile');\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/thrid-party/spm/VBA_spm_gamrnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.5816349925682706}}
{"text": "function [B0,BV] = spm_MDP_DP(MDP)\n% dynamic programming using active inference\n% FORMAT [B0,BV] = spm_MDP_DP(MDP)\n%\n% MDP.A(O,N)      - Likelihood of O outcomes given N hidden states\n% MDP.B{M}(N,N)   - transition probabilities among hidden states (priors)\n% MDP.C(N,1)      - prior preferences (prior over future states)\n%\n% MDP.V(T - 1,P)  - P allowable policies (control sequences)\n%\n% B0      - optimal state action policy or transition matrix\n% BV      - corresponding policy using value iteration\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_MDP_DP.m 6598 2015-11-11 19:48:30Z karl $\n\n% set up and preliminaries\n%==========================================================================\n\n\n% generative model and initial states\n%--------------------------------------------------------------------------\nT     = size(MDP.V,1) + 1;        % number of outcomes\nNs    = size(MDP.B{1},1);         % number of hidden states\nNu    = size(MDP.B,2);            % number of hidden controls\np0    = exp(-8);                  % smallest probability\n\n% likelihood model (for a partially observed MDP implicit in G)\n%--------------------------------------------------------------------------\ntry\n    A = MDP.A + p0;\ncatch\n    A = speye(Ns,Ns) + p0;\nend\nA     = A*diag(1./sum(A));        % normalise\nlnA   = log(A);                   % log probabilities\nH     = sum(A.*lnA)';             % negentropy of observations\n\n% transition probabilities (priors)\n%--------------------------------------------------------------------------\nfor j = 1:Nu\n    B{j}   = MDP.B{j} + p0;\n    B{j}   = B{j}*diag(1./sum(B{j}));\n    sB{j}  = B{j};\n    rB{j}  = spm_softmax(log(B{j})');\n    lnB{j} = log(B{j});\nend\n\n\n% terminal probabilities over outcomes (priors)\n%--------------------------------------------------------------------------\ntry\n    C = MDP.C;\ncatch\n    C = zeros(No,1);\nend\n\n% asume constant preferences over states\n%--------------------------------------------------------------------------\nif size(C,2) ~= T\n    C = C(:,end)*ones(1,T);\nend\nC = A'*diag(1./sum(A,2))*spm_softmax(C);\nC = log(C);\n\n% policies, states and their expectations\n%--------------------------------------------------------------------------\nV     = MDP.V;\nNp    = size(V,2);                % number of allowable policies\n\n% policy iteration\n%==========================================================================\nfor s = 1:Ns\n    \n    \n    % Variational iterations (hidden states)\n    %======================================================================\n    x     = zeros(Ns,T,Np) + 1/Ns;\n    for k = 1:Np\n        \n        % gradient descent on free energy\n        %------------------------------------------------------------------\n        for i = 1:16\n            \n            % hiddens states (x)\n            %--------------------------------------------------------------\n            x(:,1,k) = 0;\n            x(s,1,k) = 1;\n            \n            for j = 2:T\n                \n                % current state\n                %----------------------------------------------------------\n                xj   = x(:,j,k);\n                qx   = log(xj);\n                v    = 0;\n                \n                % evaluate free energy and gradients (v = dFdx)\n                %----------------------------------------------------------\n                if j > 1, v = v + qx - log(sB{V(j - 1,k)}*x(:,j - 1,k)); end\n                if j < T, v = v      - log(rB{V(j    ,k)}*x(:,j + 1,k)); end\n                \n                % update\n                %----------------------------------------------------------\n                x(:,j,k) = spm_softmax(qx - v/4);\n                F(j,k)   = xj'*v;\n                \n            end\n            \n            % convergence\n            %--------------------------------------------------------------\n            if i > 1\n                dF = F0 - sum(F(:,k));\n                if dF > 1/128, F0 = F0 - dF; else, break, end\n            else\n                F0 = sum(F(:,k));\n            end\n            \n        end\n    end\n\n    % value of policies (Q)\n    %======================================================================\n    Q     = zeros(Np,1);\n    for k = 1:Np\n        \n        % path integral of expected free energy\n        %------------------------------------------------------------------\n        for j = 2:T                 \n            v    = C(:,j) - log(x(:,j,k)) + H;\n            Q(k) = Q(k) + v'*x(:,j,k);\n            \n        end\n    end\n    \n    % optimal transition from this state\n    %======================================================================\n    [u,k]   = max(Q);\n    B0(:,s) = lnB{V(1,k)}(:,s);\n    \nend\n\nif nargout < 2, return, end\n\n% value iteration\n%==========================================================================\nV     = zeros(Ns,1);\nC     = C(:,end);\ng     = 1 - 1/T;\nfor i = 1:32\n    for s  = 1:Ns\n        \n        % value of actions (Q)\n        %------------------------------------------------------------------\n        Q     = zeros(Nu,1);\n        for k = 1:Nu\n            Q(k)   = B{1,k}(:,s)'*(C + g*V);\n        end\n        \n        % optimal transition from this state\n        %------------------------------------------------------------------\n        [u,k]   = max(Q);\n        BV(:,s) = B{1,k}(:,s);\n        \n    end\n    \n    % optimal transition from this state\n    %----------------------------------------------------------------------\n    dV   = BV'*(C + g*V) - V;\n    V    = V + dV;\n    \n    % convergence\n    %----------------------------------------------------------------------\n    if norm(dV) < 1e-2, break, end\n    \nend\n\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_MDP_DP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5816202258043228}}
{"text": "function varargout = atan(varargin)\n%ATAN (overloaded)\n\nswitch class(varargin{1})\n\n    case 'sdpvar'\n        varargout{1} = InstantiateElementWise(mfilename,varargin{:});\n\n    case 'char'\n\n        operator = struct('convexity','none','monotonicity','increasing','definiteness','none','model','callback');\n        operator.convexhull = @convexhull;\n        operator.bounds = @bounds;\n        operator.derivative = @(x)((1+x.^2).^-1);\n        operator.inverse = @(x)(tan(x));\n        operator.range = [-pi/2 pi/2];\n        \n        varargout{1} = [];\n        varargout{2} = operator;\n        varargout{3} = varargin{3};\n\n    otherwise\n        error('SDPVAR/ATAN called with CHAR argument?');\nend\n\nfunction [L,U] = bounds(xL,xU)\nL = atan(xL);\nU = atan(xU);\n\nfunction [Ax, Ay, b] = convexhull(xL,xU)\nfL = atan(xL);\nfU = atan(xU);\ndfL = 1/(1+xL^2);\ndfU = 1/(1+xU^2);\nif xL >= 0\n    % Concave region\n    [Ax,Ay,b] = convexhullConcave(xL,xU,fL,fU,dfL,dfU);\nelseif xU <= 0\n    % Convex region\n    [Ax,Ay,b] = convexhullConvex(xL,xU,fL,fU,dfL,dfU);\nelse\n    % Changes convexity. We're lazy and let YALMIP sample instead\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/@sdpvar/atan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5816202228731774}}
{"text": "function [X, present] = block(X, past, weights, hyperParameters)\n% block   Transformer block for GPT-2\n%\n%   [X, present] = block(X, past, weights, hyperParameters) computes a\n%   GPT-2 style transformer block on the input X as described in [1] (see\n%   Section 2.3). One difference between this style of transformer block\n%   and others is that this block uses layer normalization at the\n%   beginning.\n%\n%   Inputs:\n%       X               - A (numFeatures*numHeads)-by-numInputSubwords\n%                         input array.\n%       past            - A numFeatures-by-numPastSubwords-by-numHeads-by-2\n%                         array. This contains the 'keys' and 'values' for\n%                         past subwords. These are needed to predict future\n%                         outputs in an autoregressive manner. 'keys' are\n%                         stored in past(:,:,:,1) and 'values' are stored\n%                         in past(:,:,:,2).\n%       weights         - The weights for the transformer block stored in a\n%                         struct. In this block we have:\n%                           - ln_1_g_0: Weight vector for the first layer\n%                             normalization.\n%                           - ln_1_b_0: Bias vector for the first layer\n%                             normalization.\n%                           - ln_2_g_0: Weight vector for the second layer\n%                             normalization.\n%                           - ln_2_b_0: Bias vector for the second layer\n%                             normalization.\n%                         In the attention sub-block:\n%                           - attn_c_attn_w_0: A weight matrix for the\n%                             first fully connected layer.\n%                           - attn_c_attn_b_0: A bias vector for the first\n%                             fully connected layer.\n%                           - attn_c_proj_w_0: A weight matrix for the\n%                             final fully connected layer.\n%                           - attn_c_proj_b_0: A bias vector for the final\n%                             fully connected layer.\n%                         In the multi-layer perceptron block:\n%                           - mlp_c_fc_w_0: A weight matrix for the first\n%                             fully connected layer.\n%                           - mlp_c_fc_b_0: A bias vector for the first\n%                             fully connected layer.\n%                           - mlp_c_proj_w_0: A weight matrix for the\n%                             second fully connected layer.\n%                           - mlp_c_proj_b_0: A bias vector for the second\n%                             fully connected layer.\n%       numHeads        - The number of attention heads. This is a\n%                         hyper-parameter.\n%\n%   Outputs:\n%       Z               - A (numFeatures*numHeads)-by-numInputSubwords\n%                         output array.\n%       present         - A numFeatures-by-numAllSubwords-by-numHeads-by-2\n%                         array. This contains the 'keys' and 'values' that\n%                         are created from inputs. These need to passed\n%                         back in as the 'past' input if we want to predict\n%                         future outputs in an autoregressive manner. 'keys'\n%                         are stored in present(:,:,:,1) and 'values' are\n%                         stored in present(:,:,:,2).\n%\n%   References:\n%\n%   [1] Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei,\n%       Ilya Sutskever, \"Language Models are Unsupervised Multitask\n%       Learners\",\n%       https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf\n\nXNorm1 = transformer.layer.normalization(X, ...\n    weights.ln_1_g_0, weights.ln_1_b_0);\n\n[A, present] = transformer.layer.attention(XNorm1, past, weights, hyperParameters);\n\nX = X + A;\n \nXNorm2 = transformer.layer.normalization(X, ...\n    weights.ln_2_g_0, weights.ln_2_b_0);\n\nM = transformer.layer.multiLayerPerceptron(XNorm2, weights);\n\nX = X + M;\n\nend", "meta": {"author": "matlab-deep-learning", "repo": "transformer-models", "sha": "87f02af6b91c5bd7ac8479ea433f20435644d165", "save_path": "github-repos/MATLAB/matlab-deep-learning-transformer-models", "path": "github-repos/MATLAB/matlab-deep-learning-transformer-models/transformer-models-87f02af6b91c5bd7ac8479ea433f20435644d165/+gpt2/+layer/block.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5816202214389249}}
{"text": "%% Read shape\n\n[X,T] = readOff('../data/meshes/sphere_102.off');\nM = getMeshData(X,T,10); % compute 10 LB eigenfunctions for fun\n\n%% Set up Gaussian blur function\n\nblurTime = .005; % if this gets too small, distances get noisy\nblurSteps = 50;\n\n% blur = @(x) blurOnMesh(x,M,blurTime,blurSteps)+1e-300; % faster than pre-factored?\n% blurTranspose = @(x) blurOnMesh(x,M,blurTime,blurSteps,1)+1e-300;\n\n% structure = prefactorMeshBlur(M,blurTime,blurSteps,5000);\n% blur = @(x) prefactoredBlur(x,structure,0)+1e-300; \n% blurTranspose = @(x) prefactoredBlur(x,structure,1)+1e-300;\n\nh = blurTime/blurSteps;\nnv = M.numVertices;\n\n% Sphere is small enough that we can just write down the heat kernel explicitly\nblurInverse = spdiags(M.areaWeights,0,nv,nv) - h*M.cotLaplacian;\nmtx = full(blurInverse) \\ diag(M.areaWeights);\nmtx = mtx^blurSteps;\n\nmtx(mtx<1e-50) = 1e-50;\n\nblur = @(x) mtx*x;\nblurTranspose = @(x) mtx'*x;\n\n%% Make boundary\n\n[~,fixedVerts(1)] = min(X(:,1));\n[~,fixedVerts(2)] = min(X(:,2));\n[~,fixedVerts(3)] = min(X(:,3));\n[~,fixedVerts(4)] = max(X(:,1));\n[~,fixedVerts(5)] = max(X(:,2));\n[~,fixedVerts(6)] = max(X(:,3));\n\nnFixed = length(fixedVerts);\n\nfixedDistributions = zeros(M.numVertices,nFixed);\n\nclose all;\nfor i=1:nFixed\n    fixedDistributions(fixedVerts(i),i) = 1/M.areaWeights(fixedVerts(i));\nend\n\nfixedDistributions = fixedDistributions+1e-10;\n% fixedDistributions = blur(fixedDistributions);\nshowDescriptor(M,fixedDistributions(:,1));\n\n%% Compute average entropy of data\n\naverageEntropy = -mean(sum(bsxfun(@times,M.areaWeights,(fixedDistributions.*log(fixedDistributions))),1));\n\n%% Solve barycenter problem using this machinery\n\nedges = [2 1; 3 1; 4 1];\nedgeWeights = [1 1 1 1 1 1];\n\ntargetEntropy = averageEntropy + 1;\n\nresult = convolutionalPropagation(edges, edgeWeights, [2 3 4], ...\n    fixedDistributions(:,1:3),M.areaWeights,blur,blurTranspose,targetEntropy);\n\nbarycenter = convolutionalBarycenter(fixedDistributions(:,1:3),[1 1 1],...\n    M.areaWeights,blur,blurTranspose,targetEntropy);\n\nclose all\n\nf = subplot(1,3,1);\nshowDescriptor(M,sum(fixedDistributions(:,1:3),2),[],[],[],f);\ntitle('Boundary distributions');\ncolorbar off;\n\nf = subplot(1,3,2);\nshowDescriptor(M,result(:,1),[],[],[],f);\ntitle('Barycenter computed using graph algorithm');\ncolorbar off;\n\nf = subplot(1,3,3);\nshowDescriptor(M,barycenter,[],[],[],f);\ntitle('Barycenter computed using specialized barycenter algorithm')\ncolorbar off;\n\n%% Solve displacement problem using this machinery\n\nk = 9;\n\nedges = [(1:(k-1))' (2:k)'];\nedges = [edges ; edges(:,2) edges(:,1)];\nedgeWeights = ones(1,size(edges,1));\n\ntargetEntropy = averageEntropy + 1.5;\n\nresult = convolutionalPropagation(edges, edgeWeights, [1 k], ...\n    fixedDistributions(:,[1 6]),M.areaWeights,blur,blurTranspose,targetEntropy);\n\nfigure\n\nfor i=1:k\n    f = subplot(1,k,i);\n    showDescriptor(M,result(:,i),[],[],[],f);\n    colorbar off;\nend\n\n\n%% Solve soft mapping problem\n\nedges = [T(:,1) T(:,2); T(:,2) T(:,3); T(:,3) T(:,1)];\nedges = sort(edges,2);\nedges = unique(edges,'rows');\nedges = [edges; edges(:,2) edges(:,1)];\n\nedgeWeights = ones(size(edges,1),1);\n\ntargetEntropy = averageEntropy+1.5;\n\nresult = convolutionalPropagation(edges, edgeWeights, fixedVerts, ...\n                    fixedDistributions,M.areaWeights,blur,blurTranspose,targetEntropy);\n                \n%% Show result\n\ntestVerts = randperm(M.numVertices);\nnTests = 5;\ntestVerts = testVerts(1:nTests);\n\nfigure;\nfor i=1:length(testVerts)\n    f = subplot(2,length(testVerts),i);\n    ind = zeros(M.numVertices,1);\n    ind(testVerts(i)) = 1;\n    showDescriptor(M,ind,[],[],[],f);\n    colorbar off;\n    colormap hot;\n    \n    f = subplot(2,length(testVerts),i+length(testVerts));\n    showDescriptor(M,result(:,testVerts(i)),[],[],[],f);\n    colorbar off;\n    colormap hot;\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/tests/testConvolutionalPropagation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5816202069084778}}
{"text": "% pivot_input.m // Jon Lee\n% data for pivoting example\n\nA = [1 2 1 0 0 0; 3 1 0 1 0 0; 1.5 1.5 0 0 1 0; 0 1 0 0 0 1];\nc = [6 7 -2 0 4 4.5]';\nb = [7 9 6 3.3]';\nbeta = [1,2,4,6];\n[m,n] = size(A);\neta = setdiff(1:n,beta); % lazy eta initialization", "meta": {"author": "jon77lee", "repo": "JLee_LinearOptimizationBook", "sha": "41c978a86f7ee0a42936934e16fde993b2487720", "save_path": "github-repos/MATLAB/jon77lee-JLee_LinearOptimizationBook", "path": "github-repos/MATLAB/jon77lee-JLee_LinearOptimizationBook/JLee_LinearOptimizationBook-41c978a86f7ee0a42936934e16fde993b2487720/JLee.2.1.softwareEtc/Matlab/pivot/pivot_input.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5815447944333438}}
{"text": "function [eMat,f2eMat,f2eIsDirMat] = mapface2edge(vMat,fMat)\n% MAPFACE2EDGE creates a mapping from faces to edges \n%\n% Input:\n%   regular:\n%       vMat: double[nVerts,3] - coordinates of vertices\n%       fMat: double[nFace,3] - indices of face vertices in vMat  \n%\n% Output:  \n%   eMat: double[nEdges,2] - contains indices of vertices corresponding\n%       to each edge\n%\n%   f2eMat: double[nFaces,3] - contains indices of edges for\n%       each face in this order (1-2, 2-3, 1-3)\n%               \n%   f2eIsDirMat: logical[nFaces,3] - contains true if face\n%       references edge in a direct order (i.e. 1-2 for instance)\n%       and false if reference is in an opposite order\n%\n% $Author: Peter Gagarinov, PhD  <pgagarinov@gmail.com> $\n% $Copyright: Peter Gagarinov, PhD, \n%            Moscow State University,\n%            Faculty of Computational Mathematics and Computer Science,\n%            System Analysis Department 2011-2016 $\n%\ntrObj = triangulation(fMat,vMat);\neMat=trObj.edges;\nnEdges=size(eMat,1);\nnFaces=size(fMat,1);\n%% Build Face to Edges map and edge orientation map for each face\nfMidCVec=trObj.edgeAttachments(eMat);\nindShiftVec=cellfun('length',fMidCVec);\nindF2EVec=zeros(sum(indShiftVec),1);\nindF2EVec(1)=1;\nindF2EVec(1+cumsum(indShiftVec(1:end-1)))=ones(nEdges-1,1);\nindF2EVec=cumsum(indF2EVec);\nindFVec=[fMidCVec{:}].';\n%edges for each face are expected to be oriented as \n%1-2, 2-3 , 3-1\nindEdgeNumVec=...\n    all(fMat(indFVec,[1,2])==eMat(indF2EVec,:),2)...\n    -all(fMat(indFVec,[2,1])==eMat(indF2EVec,:),2)...\n    +2*all(fMat(indFVec,[2,3])==eMat(indF2EVec,:),2)...\n    -2*all(fMat(indFVec,[3,2])==eMat(indF2EVec,:),2)...\n    +3*all(fMat(indFVec,[1,3])==eMat(indF2EVec,:),2)...\n    -3*all(fMat(indFVec,[3,1])==eMat(indF2EVec,:),2);\n%\n[~,indSortVec]=sortrows([indFVec,abs(indEdgeNumVec)]);\nindF2EVec=indF2EVec(indSortVec);\nf2eMat=reshape(indF2EVec,3,nFaces).';\nf2eIsDirMat=reshape(indEdgeNumVec(indSortVec)>0,3,nFaces).';", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/scenarios/icosahedrals/mapface2edge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5815447910556885}}
{"text": "function dick_grid_display ( ng, xy )\n\n%*****************************************************************************80\n%\n%% DISK_GRID_DISPLAY displays grid points inside a disk.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    05 September 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer NG, the number of grid points inside the disk.\n%\n%    Input, real XY(2,NG), the grid points.\n%\n  scatter ( xy(1,:), xy(2,:), 'b.' );\n  axis equal\n  title ( sprintf ( '%d grid points inside a disk', ng ) )\n  grid on\n\n  return\nend\n", "meta": {"author": "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_grid/disk_grid_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.5815447797042484}}
{"text": "function [xhk, pf] = particle_filter(sys, yk, pf, resampling_strategy)\n%% Generic particle filter\n%\n% Note: when resampling is performed on each step this algorithm is called\n% the Bootstrap particle filter\n%\n% Usage:\n% [xhk, pf] = particle_filter(sys, yk, pf, resamping_strategy)\n%\n% Inputs:\n% sys  = function handle to process equation\n% yk   = observation vector at time k (column vector)\n% pf   = structure with the following fields\n%   .k                = iteration number\n%   .Ns               = number of particles\n%   .w                = weights   (Ns x T)\n%   .particles        = particles (nx x Ns x T)\n%   .gen_x0           = function handle of a procedure that samples from the initial pdf p_x0\n%   .p_yk_given_xk    = function handle of the observation likelihood PDF p(y[k] | x[k])\n%   .gen_sys_noise    = function handle of a procedure that generates system noise\n% resampling_strategy = resampling strategy. Set it either to \n%                       'multinomial_resampling' or 'systematic_resampling'\n%\n% Outputs:\n% xhk   = estimated state\n% pf    = the same structure as in the input but updated at iteration k\n%\n% Reference:\n% [1] Arulampalam et. al. (2002).  A tutorial on particle filters for \n%     online nonlinear/non-gaussian bayesian tracking. IEEE Transactions on \n%     Signal Processing. 50 (2). p 174--188\n\n%% Programmed by:\n% Diego Andres Alvarez Marin (diegotorquemada@gmail.com)\n% Universidad Nacional de Colombia at Manizales, February 29, 2012\n\n%%\nk = pf.k;\nif k == 1\n   error('error: k must be an integer greater or equal than 2');\nend\n\n%% Initialize variables\nNs = pf.Ns;                              % number of particles\nnx = size(pf.particles,1);               % number of states\n\nwkm1 = pf.w(:, k-1);                     % weights of last iteration\nif k == 2\n   for i = 1:Ns                          % simulate initial particles\n      pf.particles(:,i,1) = pf.gen_x0(); % at time k=1\n   end   \n   wkm1 = repmat(1/Ns, Ns, 1);           % all particles have the same weight\nend\n\n%%\n% The importance sampling function:\n% PRIOR: (this method is sensitive to outliers)   THIS IS THE ONE USED HERE\n% q_xk_given_xkm1_yk = pf.p_xk_given_xkm1;\n\n% OPTIMAL:\n% q_xk_given_xkm1_yk = q_xk_given_xkm1^i_yk;\n% Note this PDF can be approximated by MCMC methods: they are expensive but \n% they may be useful when non-iterative schemes fail\n\n%% Separate memory\nxkm1 = pf.particles(:,:,k-1); % extract particles from last iteration;\nxk   = zeros(size(xkm1));     % = zeros(nx,Ns);\nwk   = zeros(size(wkm1));     % = zeros(Ns,1);\n\n%% Algorithm 3 of Ref [1]\nfor i = 1:Ns\n   % xk(:,i) = sample_vector_from q_xk_given_xkm1_yk given xkm1(:,i) and yk\n   % Using the PRIOR PDF: pf.p_xk_given_xkm1: eq 62, Ref 1.\n   xk(:,i) = sys(k, xkm1(:,i), pf.gen_sys_noise());\n   \n   % Equation 48, Ref 1.\n   % wk(i) = wkm1(i) * p_yk_given_xk(yk, xk(:,i))*p_xk_given_xkm1(xk(:,i), xkm1(:,i))/q_xk_given_xkm1_yk(xk(:,i), xkm1(:,i), yk);\n   \n   % weights (when using the PRIOR pdf): eq 63, Ref 1\n   wk(i) = wkm1(i) * pf.p_yk_given_xk(k, yk, xk(:,i));\n   \n   % weights (when using the OPTIMAL pdf): eq 53, Ref 1\n   % wk(i) = wkm1(i) * p_yk_given_xkm1(yk, xkm1(:,i)); % we do not know this PDF\nend;\n\n%% Normalize weight vector\nwk = wk./sum(wk);\n\n%% Calculate effective sample size: eq 48, Ref 1\nNeff = 1/sum(wk.^2);\n\n%% Resampling\n% remove this condition and sample on each iteration:\n% [xk, wk] = resample(xk, wk, resampling_strategy);\n%if you want to implement the bootstrap particle filter\nresample_percentaje = 0.50;\nNt = resample_percentaje*Ns;\nif Neff < Nt\n   disp('Resampling ...')\n   [xk, wk] = resample(xk, wk, resampling_strategy);\n   % {xk, wk} is an approximate discrete representation of p(x_k | y_{1:k})\nend\n\n%% Compute estimated state\nxhk = zeros(nx,1);\nfor i = 1:Ns;\n   xhk = xhk + wk(i)*xk(:,i);\nend\n\n%% Store new weights and particles\npf.w(:,k) = wk;\npf.particles(:,:,k) = xk;\n\nreturn; % bye, bye!!!\n\n%% Resampling function\nfunction [xk, wk, idx] = resample(xk, wk, resampling_strategy)\n\nNs = length(wk);  % Ns = number of particles\n\n% wk = wk./sum(wk); % normalize weight vector (already done)\n\nswitch resampling_strategy\n   case 'multinomial_resampling'\n      with_replacement = true;\n      idx = randsample(1:Ns, Ns, with_replacement, wk);\n%{\n      THIS IS EQUIVALENT TO:\n      edges = min([0 cumsum(wk)'],1); % protect against accumulated round-off\n      edges(end) = 1;                 % get the upper edge exact\n      % this works like the inverse of the empirical distribution and returns\n      % the interval where the sample is to be found\n      [~, idx] = histc(sort(rand(Ns,1)), edges);\n%}\n   case 'systematic_resampling'\n      % this is performing latin hypercube sampling on wk\n      edges = min([0 cumsum(wk)'],1); % protect against accumulated round-off\n      edges(end) = 1;                 % get the upper edge exact\n      u1 = rand/Ns;\n      % this works like the inverse of the empirical distribution and returns\n      % the interval where the sample is to be found\n      [~, idx] = histc(u1:1/Ns:1, edges);\n   % case 'regularized_pf'      TO BE IMPLEMENTED\n   % case 'stratified_sampling' TO BE IMPLEMENTED\n   % case 'residual_sampling'   TO BE IMPLEMENTED\n   otherwise\n      error('Resampling strategy not implemented')\nend;\n\nxk = xk(:,idx);                    % extract new particles\nwk = repmat(1/Ns, 1, Ns);          % now all particles have the same weight\n\nreturn;  % bye, bye!!!\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35468-particle-filter-tutorial/particle_filter/particle_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.581544779637055}}
{"text": "function im = ifft2c(d)\n% Function performs a centered ifft2\nim = ifftshift(ifft2(ifftshift(d)));", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/fileFilters/rsvistafiles/ssfp/ifft2c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5815254236871724}}
{"text": "function Fitness = Fit(PopObj,PopCon)\n% Calculate the fitness of each solution\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    N  = size(PopObj,1);\n    CV = sum(max(0,PopCon),2);\n\n    %% Detect the dominance relation between each two solutions\n    Dominate = false(N);\n    for i = 1 : N-1\n        for j = i+1 : N\n            if CV(i) < CV(j)\n                Dominate(i,j) = true;\n            elseif CV(i) > CV(j)\n                Dominate(j,i) = true;\n            else\n                k = any(PopObj(i,:)<PopObj(j,:))-any(PopObj(i,:)>PopObj(j,:));\n                if k == 1\n                    Dominate(i,j) = true;\n                elseif k == -1\n                    Dominate(j,i) = true;\n                end\n            end\n        end\n    end\n    \n    %% Calculate S(i)\n    S = sum(Dominate,2);\n    \n    %% Calculate R(i)\uff1a\n    R = zeros(1,N);\n    for i = 1 : N\n        R(i) = sum(S(Dominate(:,i)));\n    end\n    \n    %% Calculate D(i)\n    Distance = pdist2(PopObj,PopObj);\n    Distance(logical(eye(length(Distance)))) = inf;\n    Distance = sort(Distance,2);\n    D = 1./(Distance(:,floor(sqrt(N)))+2);\n    \n    %% Calculate the fitnesses\n    Fitness = R + D';\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/TSTI/Fit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.581520605582553}}
{"text": "function [retdat,algo] =  training(algo,dat)\n\nretdat=dat;\n\n disp(['training ' get_name(algo) '.... '])\n switch algo.optimizer\n  case {'svmtorch'}\n  %%<<----------------svmtorch optimizer-------------------->>\n\n    multi = 0;\n    regression = 1;   \n    degree = 1;\n    gamma = 1; \n    eps = algo.epsilon;\n    C = algo.C;\n    if strcmp(algo.child.ker,'linear')\n       kernelType = 0;\n    elseif strcmp(algo.child.ker,'poly')\n       kernelType = 1;\n       degree = algo.child.kerparam;\n    elseif strcmp(algo.child.ker,'rbf')\n    \tkernelType = 2;    \n\tgamma = algo.child.kerparam;\n    end;\n    [x y] = get_xy(dat);\n    numEx = get_dim(dat);    \n    [alpha,threshold0,xSV] = SVMTorch(x,y,regression,multi,kernelType,degree,gamma,C,eps);\n    if isempty(alpha)\n    \talpha = zeros(numEx,1);\n    end;\n\n %<<--------------sparse svr------------------>>%\n\n   case{'sparse'}\n   \tkern1=get_kernel(algo.child,dat,dat);\n\ty=get_y(dat);\n\tkNum=size(kern1,1);\n\tc=ones(kNum*4,1);\n\tc(2*kNum+1:4*kNum)=algo.C;\n\tkern2 = [-kern1 kern1 -1*eye(kNum) zeros(kNum); kern1 -kern1 zeros(kNum) -1*eye(kNum); -1*eye(4*kNum)];\n\tcst = zeros(6*kNum,1);\n\tcst(1:kNum) = (algo.epsilon+algo.b0) - y;\n\tcst(kNum+1:2*kNum) = (algo.epsilon-algo.b0) + y;\t\n\topts= optimset('display','off','MaxIter',10000,'LargeScale','off');\n\t[alphaTemp,fval,exit,out,lambda] = linprog(c,kern2,cst,[],[],[],[],[],opts);\n\tthreshold0=lambda.ineqlin(1);\n\talpha=alphaTemp(1:kNum)-alphaTemp(kNum+1:2*kNum);\n\n  %<<------------andre optimizer--------------------->> \n\n  case {'andre'}\n   kern1=get_kernel(algo.child,dat,dat);   %% <--- calculate kernel\n   y=get_y(dat); \n   yLen = length(y(:,1));\n   xSV = get_x(dat);\n   kern2 = [kern1 , -kern1 ; -kern1 , kern1];   \n   cst = ones(2*yLen,1); \n   cst(yLen+1:2*yLen) = -1;\n   if algo.nu ==0,\n       c = zeros(2*yLen,1);\n       c(1:yLen) = algo.epsilon*ones(yLen,1) - y;\n       c(yLen+1:2*yLen) = algo.epsilon*ones(yLen,1) + y;       \n       [alphaTemp,threshold] = quadsolve(kern2,c,cst',0,algo.C); \n       alpha=alphaTemp(1:yLen)-alphaTemp(yLen+1:2*yLen);\n       threshold0 = -threshold;\n   else\n     if algo.C==Inf,\n         algo.C=10000;\n     end;\n\n        c = zeros(2*yLen+1,1);\n        c(1:yLen) = -y;\n        c(yLen+1:2*yLen) = y;\n        cst2 = ones(1,2*yLen+1)/(yLen*algo.nu);\n        cst2(2*yLen+1)=-1;\n        kern2 = [kern2,zeros(2*yLen,1);zeros(1,2*yLen+1)];\n        cst=[cst',0;cst2];\n        [alphaTemp,threshold] = quadsolve(kern2,c,cst,[0;0],algo.C); threshold0 = -threshold(1);\n        alpha=alphaTemp(1:yLen)-alphaTemp(yLen+1:2*yLen);\n        epsilon = -threshold(2);\n    end\n    \n  %<<------------quadprog optimizer--------------------->> \n  \n  case {'quadprog'}\n   \n   kern1=get_kernel(algo.child,dat,[]);   %% calculate kernel\n   kNum=size(kern1,1);  y=get_y(dat); \n   kern2 = [kern1 , -kern1 ; -kern1 , kern1];\n   c = zeros(2*kNum,1);\n   c(1:kNum) = algo.epsilon*ones(kNum,1) - y;\n   c(kNum+1:2*kNum) = algo.epsilon*ones(kNum,1) + y;\n   cst(kNum+1:2*kNum) = -1;\n   cst = ones(2*kNum,1); \n   opts= optimset('display','off','MaxIter',10000,'LargeScale','off'); \n   [alphaTemp,fval,exit,out,lambda] = quadprog(kern2,c,[],[],cst',0,...\n\t\t\t\t       zeros(2*kNum,1),algo.C*ones(2*kNum,1),[],opts);\n   threshold0=lambda.eqlin(1);\n   alpha=alphaTemp(1:kNum)-alphaTemp(kNum+1:2*kNum);\n  \n%<<------------libsvm optimizer--------------------->> \ncase {'libsvm'}\n  \n        %      \n        x=[];\n        y=[];\n        svm_type=3;\n        kernelType=0;\n        degree=3;\n        gamma=0;\n        coef0=0;\n        \n        nu=algo.nu;\n        if(nu>0)\n            svm_type=4;\n        end\n\n        \n        cachesize=40;\n        C=algo.C;\n        eps=algo.epsilon;\n        p=0.05;\n        shrinking=1;\n        \n        \n        weight_label=[];\n        weight=[];\n        nr_weight=0;\n        \n        if strcmp(algo.child.ker,'linear')\n            kernelType = 0;\n        end;\n        if strcmp(algo.child.ker,'poly')\n            kernelType = 1; \n            degree = algo.child.kerparam;\n            coef0 = 1;\n            gamma = 1;\n        end;\n        if strcmp(algo.child.ker,'rbf'),\n            kernelType = 2; \n            sigma = algo.child.kerparam; \n            gamma = 1/(2*sigma^2);\n        end;\n\n        y=get_y(dat); \n        x=get_x(dat);\n\n        if strcmp(algo.child.ker,'custom'),\n          kernelType = 4; \n          K= algo.child.kerparam;\n          l = get_dim( retDat);\n          x = get_index( retDat);\n          x = [ reshape( x, l, 1) [ 1:l]']; % using x to pass indices in Matrix and real indices\n        end;\n \n        s=whos('libsvm_cachesize','global');\n        \n        if (length(s)>0)\n            global libsvm_cachesize;\n            cachesize=libsvm_cachesize;\n        else\n            cachesize=40;\n        end\n        if algo.algorithm.verbosity>1\n         fprintf('Using %d MB Cache for Libsvm\\n',cachesize)\n        end\n\n    \n         if( kernelType == 4)\n          [alpha,xSV,bias0]=libsvm_regressor_spider(x,y,svm_type,kernelType,...\n                     degree,gamma,coef0,nu,cachesize,C,eps,p,weight_label,weight,nr_weight,K);\n          algo.Xsv=get(retDat, xSV( :, 2));\n        else\n          [alpha,xSV,bias0]=libsvm_regressor_spider(x,y,svm_type,kernelType,...\n                     degree,gamma,coef0,nu,cachesize,C,eps,p,weight_label,weight,nr_weight);\n          algo.Xsv=data(xSV);\n        end\n       \n\n        \n        threshold0 = bias0 * y(1); \n        \n        algo.b0=bias0;\n\n        algo.epsilon = eps;\n        \n        algo.Xsv = data(xSV);\n        algo.alpha=alpha;\n      \n\n        if algo.algorithm.do_not_evaluate_training_error==1   \n            retdat=set_x(dat,get_y(dat));\n        else\n            retdat=test(algo,dat);\n        end\n        \n        return\n\n        \n        %         fin=find(abs(alpha)>algo.alpha_cutoff);\n\n% case {'libsvm'}\n%   \n%    if algo.nu ==0,\n%         svm_type = 3; \n%         C = algo.C; \n%         epsilon = algo.epsilon;  \n%         nu=0;\n%     else\n%         svm_type = 4; \n%         nu = algo.nu; \n%         C = algo.C; \n%         epsilon = -1;\n%     end;\n%     %% default values for libsvm\n%     cacheSize = 40; \n%     eps = 0.001; \n%     shrinking=1;\n%     nrWeight = 0; \n%     weightLabel =0; \n%     weight = 1; \n%     gamma=1; \n%     deg = 0; \n%     coef0 = 0; \n%     kerTmp = algo.child;\n%     if strcmp(kerTmp.ker,'linear')\n%       kernelType = 0;\n%     end;\n%     if strcmp(kerTmp.ker,'poly')\n%       kernelType = 1; \n%       ptmp = kerTmp.kerparam; \n%       deg = ptmp; \n%       coef0 = 1;\n%     end;\n%    if strcmp(kerTmp.ker,'rbf'),\n%          kernelType = 2; \n%          ptmp = kerTmp.kerparam; \n%          gamma = 1/(2*ptmp^2);\n%    end;\n% %    if algo.balanced_ridge~=0,\n% %         disp('Warning: balanced ridge not implemented for libsvm.');\n% %    end;\n%    y=get_y(dat); \n%    x=get_x(dat);\n%    [alpha,threshold0,xSV,eps,CC] = svmlibtrain(x,y,svm_type,kernelType,deg,gamma,coef0,nu,cacheSize,C,eps,epsilon,...\n%        shrinking,nrWeight,weightLabel,weight,0);    \n%    threshold0=-threshold0;% from libsvm\n%    % alpha is reordered in order to have the same xsp for all runs (important for one_vs_rest)\n%    alphaTemp = zeros(size(xSV,1),1);\n%    indTemp = find(xSV(:,size(xSV,2))~=0);\n%    indTemp2 = xSV(indTemp,size(xSV,2));\n%    alphaTemp(indTemp2) = alpha(indTemp);\n%    alpha = alphaTemp;\n%    epsilon=eps;\n%  end\nend\n\n if algo.nu~=0,\n   algo.epsilon = epsilon;\n end;\n\n \n algo.b0=threshold0;\n fin=find(abs(alpha)>algo.alpha_cutoff);\n algo.alpha=alpha(fin);\n algo.Xsv = get(dat,fin);\n      \n\n\n if algo.algorithm.do_not_evaluate_training_error==1   \n   retdat=set_x(dat,get_y(dat));\n else\n   retdat=test(algo,dat);\n end\n \n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/reg/@svr/training.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5815205953195273}}
{"text": "function J = lotkaObjectiveFCN_models(u,x,N,xref,u0,p,Q,R,Ru, select_model)\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% Q = diag([1,1,1]);\n% R = 0.01;\n\n%% Integrate system\nif strcmp(select_model,'DelayDMDc')\n    [xk,~] = lsim(p.sys,[p.udelay(1:N);u'],[0:N-1].*p.dt,[p.xdelay(:,1); x]-[p.xmean; p.xmean]);\n    xk = xk(:,3:4);\n    xk = xk + repmat(p.xmean',[N 1]); xk = xk';\nelseif strcmp(select_model,'DMDc')\n    [xk,~] = lsim(p.sys,[u' 0],[0:N].*p.dt,x-p.xmean);\n    xk = xk(2:end,:) + repmat(p.xmean',[N 1]); xk = xk';\nelseif strcmp(select_model,'SINDYc')\n    Ns = size(x,1);\n    xk = zeros(Ns,N+1); xk(:,1) = x;\n    for ct=1:N\n        % Obtain plant state at next prediction step.\n        xk(:,ct+1) = rk4u(@sparseGalerkinControl_Discrete,xk(:,ct),u(ct),p.dt,1,[],p);\n    end\n    xk = xk(:,2:N+1);\nelseif strcmp(select_model,'NARX')\n    Hu = [u',0];\n    Hx = zeros(2,length(Hu)); Hx(:,1) = x;\n    [Us,Ui,Si] = preparets(p.net,con2seq(Hu),{},con2seq(Hx));\n    xk = p.net(Us,Ui,Si);\n    xk = cell2mat(xk); \nend\n\n%% Cost Calculation\n% Set initial plant states, controller output and cost\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 = xk(:,ct);\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 uk for the next prediction step\n    if ct<N\n        uk = u(ct+1);\n    end\nend\n\n", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/EX_LOTKA_VOLTERRA/lotkaObjectiveFCN_models.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.581520589448624}}
{"text": "function [z,dz,ymu,ys,fmu,fs,fpi] = acqNegGEI(xi,target,gpstruct,optimState,grad)\n%ACQNEGEI Acquisition function for (negative) generalized expected improvement (unsupported).\n\nif nargin < 5 || isempty(grad); grad = 0; end\n\nn = size(xi,1);\n\nif grad == 1 && n > 1\n    error('acqNegGEI:gradient', ...\n        'Gradient of acquisition function is provided only at one test point XI (row vector).');\nend\n\nif grad\n    [ymu,ys2,fmu,fs2,hypw,dymu,dys2,dfmu,dfs2] = gppred(xi,gpstruct,'central');\nelse\n    [ymu,ys2,fmu,fs2,hypw] = gppred(xi,gpstruct);\nend\nfs = sqrt(fs2);\nys = sqrt(ys2);\n\n% Probability of improvement\ngammaz = real((target - fmu)./fs);\nfpi = 0.5*erfc(-gammaz/sqrt(2));            \n\n% Squared expected improvement\nz1 = -(fs.*(gammaz.*fpi + exp(-0.5*(gammaz.^2))/sqrt(2*pi))).^2;\n\n% Expected squared improvement\nz2 = -fs.^2.*((gammaz.^2+1).*fpi + gammaz.*exp(-0.5*(gammaz.^2))/sqrt(2*pi));\n\n% gamma(1,1,:) = linspace(0,1,11);\ngamma(1,1,:) = 0.5;\nz = bsxfun(@times,gamma,z1) + bsxfun(@times,1-gamma,z2);\n\nz = sum(bsxfun(@times,hypw(~isnan(hypw)),z(~isnan(hypw),:,:)),1);\n\n[zi,idx] = min(z,[],3);\n[~,idx2] = min(zi,[],2);\nidx = idx(idx2);\nz = z(:,:,idx);\n\n%try\n%    z = sum(bsxfun(@times,hypw(~isnan(hypw)),z(~isnan(hypw),:)),1);\n%catch\n%    z = Inf(1,n);\n%    dz = NaN(n,size(xi,2));\n%    return;\n%end\n\nif grad    \n    % Gradient of probability of improvement\n    dfs = 0.5*dfs2./fs;\n    dgammaz = -(dfmu.*fs + (target - fmu).*dfs)./fs2;\n    dfpi = -0.5*dgammaz/sqrt(2)*(-2*exp(-gammaz.^2/2)/sqrt(pi));\n    \n    % Gradient of expected improvement\n    %dz = -(dfs.*gammaz.*fpi + dgammaz.*fs.*fpi + dfpi.*gammaz.*fs) ...\n    %    + (fs.*gammaz.*dgammaz - dfs).*exp(-0.5*gammaz.^2)/sqrt(2*pi);\n    %dz = sum(bsxfun(@times,hypw,dz(~isnan(hypw),:)),1);    \nelse\n    dz = NaN(n,size(xi,2));     % Gradient not estimated\nend\n\nend", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/acq/private/acqNegGEI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5814617340460249}}
{"text": "\nfunction errors = test_wiener()\n\nerrors = 0;\ngsp_reset_seed\nN = 20;\nM = 3;\nsigma = 0.3;\n\nG = gsp_sensor(N);\nG = gsp_compute_fourier_basis(G);\ng = @(x) sin(x);\npsd = @(x) g(x).^2;\n\nMask = rand(N,1)>0.5;\n\nx = gsp_filter_analysis(G,g,randn(N,M));\n\nMop =@(x) bsxfun(@times,Mask,x);\n\ny1 = Mop(x);\n\ny2 = Mop(x+sigma*randn(N,M));\nclear paramopt\nparamopt.maxit = 1000;\nparamopt.tol = 1e-12;\nsol11 = gsp_wiener_inpainting(G,y1,Mask,psd,0,paramopt);\nsol12 = gsp_wiener_inpainting_exact(G,y1,Mask,psd,0);\n\nif norm(sol11-sol12,'fro')/norm(sol11,'fro') > 1e-10\n    errors = errors + 1;\n    norm(sol11-sol12,'fro')/norm(sol11,'fro') \n    warning('Test Wiener opt 1 - ERROR');\nelse\n    disp('Test Wiener opt 1 - OK');\nend\n\n\nsol21 = gsp_wiener_inpainting(G,y2,Mask,psd,sigma.^2,paramopt);\nsol22 = gsp_wiener_inpainting_exact(G,y2,Mask,psd,sigma.^2);\n\nif norm(sol21-sol22,'fro')/norm(sol22,'fro')> 1e-10\n    errors = errors + 1;\n    norm(sol21-sol22,'fro')/norm(sol22,'fro')\n    warning('Test Wiener opt 2 - ERROR');\nelse\n    disp('Test Wiener opt 2 - OK');\nend\n\n\n\n\n%%\n\ng = gsp_design_expwin(G,0.2);\npsd = @(x) g(x).^2;\n\nMask = rand(N,1)>0.5;\nx = gsp_filter_analysis(G,g,randn(N,M));\n\nMop =@(x) bsxfun(@times,Mask,x);\n\ny1 = Mop(x);\n\ny2 = Mop(x+sigma*randn(N,M));\n\nparamopt.tol = 1e-12;\n\n%%\nparamopt.maxit = 1000;\nparamopt.gamma = 0.01;\nsol11 = gsp_wiener_inpainting(G,y1,Mask,psd,0,paramopt);\nsol12 = gsp_wiener_inpainting_exact(G,y1,Mask,psd,0);\n\nif norm(sol11-sol12,'fro')/norm(sol11,'fro') > 1e-3\n    errors = errors + 1;\n    norm(sol11-sol12,'fro')/norm(sol11,'fro') \n    warning('Test Wiener opt 3 - ERROR');\nelse\n    disp('Test Wiener opt 3 - OK');\nend\n\nif norm(x-sol12,'fro')/norm(x,'fro') > 1e-10\n    errors = errors + 1;\n    norm(x-sol12,'fro')/norm(x,'fro') \n    warning('Test Wiener opt 4 - ERROR');\nelse\n    disp('Test Wiener opt 4 - OK');\nend\n\n\n\n\n%%\n% figure(1)\n% subplot(121)\n% gsp_plot_signal_spectral(G,gsp_gft(G,x(:,1)))\n% subplot(122)\n% gsp_plot_signal_spectral(G,gsp_gft(G,sol12(:,1)))\n\n\n%%\nparamopt.gamma = 0.1;\n\nparamopt.maxit = 1000;\n\nsol21 = gsp_wiener_inpainting(G,y2,Mask,psd,sigma.^2,paramopt);\nsol22 = gsp_wiener_inpainting_exact(G,y2,Mask,psd,sigma.^2);\n\n\nif norm(sol21-sol22,'fro')/norm(sol22,'fro')> 1e-10\n    errors = errors + 1;\n    norm(sol21-sol22,'fro')/norm(sol22,'fro')\n    warning('Test Wiener opt 5 - ERROR');\nelse\n    disp('Test Wiener opt 5 - OK');\nend\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_wiener.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5814617292103847}}
{"text": "%  Figure 10.73      Feedback Control of Dynamic Systems, 6e\n%                        Franklin, Powell, Emami\n%\n% Fig. 10.73\n% Data for RTP Demo 3-3-99\n% Data provided by Dr. Gwen van der Linden\n% Data is from System Identification Studies\nInputFlux=[3.460064464376177e-1 1.177299050104922e-1 2.838023866104041e-2;\n   3.880303397347619e-11 8.024902450324316e-2 1.807231516460469e-2;\n   8.004191616976514e-9 2.721604310757543e-3 3.171348842079633e-2];\nM_inv=diag([1.000040130716728 5.557442686788876 13.63821806414694]);\nRadiation=[5.47621193859299e-2 -8.570695054070524e-3 -8.296135532988507e-4... \n      -4.536181077856052e-2;\n   -8.570695054070524e-3 8.570946319867835e-3 -1.621311365067015e-7...\n      -8.913466080455817e-8;\n   -8.296135532988507e-4 -1.621311365067015e-7 8.299854517643017e-4...\n      -2.097673289443245e-7];\nConduction=[3.559939609150268e-7 -1.113667477845243e-7 -1.976161155515125e-7...\n      -4.701109757899004e-8;\n   -1.113667477845243e-7 1.160207476868843e-2 -2.502736022145532e-3...\n      -9.099227379795117e-3;\n   -1.976161155515125e-7 -2.502736022145532e-3 6.37364815665867e-3...\n      -3.870714518397587e-3];\nScaleTemp=diag([0.01 0.01 0.01 0.01]);\n\nclf;\n%\nsim('fig10_72')\n%plot(tout,r,'-');\n%hold on;\n%plot(tout,y,'--');\n%xlabel('Time (sec)');\n%ylabel('Temperature (K)');\n%hold off;\n%pause;\nii=240:876;\nplot(tout(ii),r(ii),'-',tout(ii),y(ii,2),'--');\nlegend('r','y');\ngrid on;\nxlabel('Time (sec)');\nylabel('Temperature (K)');\ntitle('Fig. 10.73(a) Temperature tracking response');\npause;\nhold off;\nii=240:876;\nplot(tout(ii),u(ii),'-');\nxlabel('Time (sec)');\nylabel('Lamp voltage (V)');\ngrid on;\nlegend('u');\ntitle('Fig. 10.73(b) Control effort');\n%grid\nnicegrid\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig10_73.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.581461728344243}}
{"text": "%% BVAR tutorial: Minnesota prior and heteroskedasticity weights \n% Author:   Filippo Ferroni and  Fabio Canova\n% Date:     09/14/2020, revised 16/12/2020\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% 1) baseline  forecasting\n% 2) forecasting  with  heteroskedastic  weights\n% 3) forecasting  with  optimal  heteroskedastic  weights\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclose all; clc; clear;\n\naddpath ../../cmintools/\naddpath ../../bvartools/\n\n%% read the data\nif exist('DataCovid.mat','file') == 2\n    load DataCovid\nelse    \n    url = 'https://fred.stlouisfed.org/';\n    c = fred(url); \n    series    = {'PAYEMS','UNRATE','PCE','INDPRO','CPIAUCSL','PCEPILFE'};\n    startdate = datenum('12/01/1988', 'mm/dd/yyyy');\n    enddate   = datenum('07/01/2020', 'mm/dd/yyyy');\n    time      = 1988+11/12 : 1/12 : 2020+6/12;\n    \n    y=zeros(380,size(series,2)); y0=y; y1=y;\n    for kk=1:size(series,2)\n        tmp        = fetch(c,series{kk},startdate,enddate);\n        if strcmp('UNRATE',series{kk})==1\n            y(:,kk)    = tmp.Data(:,2);\n            y0(:,kk)    = tmp.Data(:,2);\n            y1(:,kk)  =(y0(:,kk));\n        else\n            y0(:,kk)    = tmp.Data(:,2);\n            y1(:,kk)    = log(y0(:,kk));\n            % rebase the log variable, transform to a index (2020m1=100)\n            y(:,kk)= y1(:,kk) * 100 / y1(time==2019,kk);\n        end\n    end\n    save DataCovid y y1 y0 time\nend\n\n% y, y0, y1 are  in DataCovid.\n\n%% Forecast post COVID-19 (July 2020 - last insample data). Minnesota\nlags                 = 13;\noptions.priors.name  = 'Minnesota';\noptions.fhor         = 24;\noptions.K            = 1000;\nbvar0                = bvar_(y,lags,options);\n\noptions.nplots       = [2 3];                           \n% start of the forecast plot - default first date in-sample data\noptions.time_start   = 2019;\n% Titles for subplot\noptions.varnames = {'PAYMS','UNRATE','PCE','INDPRO','CPIAUCSL','PCEPILFE'};\n% multiple credible set - default .68\noptions.conf_sig_2   = 0.9;\nplot_frcst_(bvar0.forecasts.with_shocks,y,time,options)\npause;\n\n% Forecast post COVID-19 (July 2020 - last insample data). \n% Minnesota + Heteroskedasticity weights\n\nlags = 13;\ntstar  = find(time==2020) + 2; % pick march 2020\n% scale the variables by factor <1 in the periods that\n% characterize the COVID-19 induced recession\nst                   = ones(size(y,1),1);\nst(tstar:tstar+2 ,:) = [10 10 10]; % March, April, May\nst(1:lags)           = []; \n\noptions.heterosked_weights = st;\noptions.priors.name  = 'Minnesota';\noptions.fhor         = 24;\nbvar1                = bvar_(y,lags,options);\n\n% adding  forecast  without  weights\noptions.add_frcst = [y; mean(bvar0.forecasts.no_shocks,3)];\nplot_frcst_(bvar1.forecasts.with_shocks,y,time,options)\npause;\n\n% Forecast  with  optimal  weights\n\nhyperpara(1)    = 3;\t\t  % tau\nhyperpara(2)    = 0.5;\t\t  % decay\nhyperpara(3)    = 1;\t\t  % lambda\nhyperpara(4)    = 1;\t\t  % mu\nhyperpara(5)    = 2;\t\t  % omega\nhyperpara(6)    = 2; % s0: scale march 2020\nhyperpara(7)    = 2; % s1: scale april 2020\nhyperpara(8)    = 2; % s2: scale may   2020\n% setting the options\noptions.index_est          = [1 6:8]; % hyper-parameter over which maximize\noptions.objective_function = 'bvar_opt_heterosked';\noptions.tstar              = find(time==2020) + 2; %march 2020\n[postmode,logmlike,HH] = bvar_max_hyper(hyperpara,y,lags,options);\n\ndisp('weights for 2020:3, 2020:4, 2020:5')\ndisp(postmode(2:4))\nheterosked_esse             = postmode(2:end); % s0, s1, s2   \nesse                        = ones(size(y,1),1);\nesse(options.tstar : options.tstar+2 ,:)   = heterosked_esse;\nesse(1:lags)                = []; \n\noptions.heterosked_weights = esse;\noptions.minn_prior_tau = postmode(1);\nbvar2                 = bvar_(y,lags,options);\nplot_frcst_(bvar2.forecasts.with_shocks,y,time,options)\n\n\n", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/examples/BVAR tutorial/example_10_VAR_heterosked.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5814617230755323}}
{"text": "function y = idualtree3D(w, J, Fsf, sf)\n\n% Inverse 3D Dual-Tree Discrete Wavelet Transform\n%\n% USAGE:\n%   y = idualtree3D(w, J, Fsf, sf)\n% INPUT:\n%   w - wavelet coefficients\n%   J - number of stages\n%   Fsf - synthesis filter for the last stage\n%   sf - synthesis filters for the preceeding stages\n% OUTPUT:\n%   y - output arry\n% See dualtree3D\n%\n% WAVELET SOFTWARE AT POLYTECHNIC UNIVERSITY, BROOKLYN, NY\n% http://taco.poly.edu/WaveletSoftware/\n\nfor k = 1:J\n    for m = 1:7\n        [w{k}{1}{m} w{k}{2}{m} w{k}{3}{m} w{k}{4}{m}] = ...\n            pm4inv(w{k}{1}{m}, w{k}{2}{m}, w{k}{3}{m}, w{k}{4}{m});\n    end\nend\n\nM = [\n    1 1 1\n    2 2 1\n    2 1 2\n    1 2 2\n];\n\n% initialize output array\ny = zeros(2^J * size(w{J}{1}{1}));\n\nfor i = 1:4\n    f1 = M(i,1);\n    f2 = M(i,2);\n    f3 = M(i,3);\n    yi = w{J+1}{i};\n    for k = J:-1:2\n        yi = sfb3D(yi, w{k}{i}, sf{f1}, sf{f2}, sf{f3});\n    end\n    yi = sfb3D(yi, w{1}{i}, Fsf{f1}, Fsf{f2}, Fsf{f3});\n    y = y + yi;\nend\n\n% normalization\ny = y/2;\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/idualtree3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5814617230755323}}
{"text": "%DEMO_MULTICLASS  Classification problem demonstration for 3 classes\n%                 using Gaussian process prior\n%\n%  Description\n%    The data used in the demonstration program is the same used by\n%    Radford M. Neal in his three-way classification example in\n%    Software for Flexible Bayesian Modeling\n%    (http://www.cs.toronto.edu/~radford/fbm.software.html) The\n%    data consists of 1000 4-D vectors which are classified into\n%    three classes. The data is generated by drawing the components\n%    of vector, x1, x2, x3 and x4, uniformly form (0,1). The class\n%    of each vector is selected according to the first two\n%    components of the vector, x_1 and x_2. After this a Gaussian\n%    noise with standard deviation of 0.1 has been added to every\n%    component of the vector. Because there are two irrelevant\n%    components in the input vector a prior with ARD should be of\n%    help.\n%\n%    The data is divided into two parts, trainig set of 400 units\n%    and test set of 600 units.\n%\n%    The latent values for N training points and C classes are\n%    f=(f1_1,f2_1,...,fN_1,f1_2,f2_2,...,fN_2,...,f1_C,f2_C,...,fN_C)^T,\n%    and are given a zero mean Gaussian process prior\n%      \n%      f ~ N(0, K),\n%\n%    where K is a block diagonal covariance matrix with blocks\n%    K_1,...,K_C whose elements are given by K_ij = k(x_i, x_j |\n%    th). The function k(x_i, x_j | th) is covariance function and\n%    th its parameters.\n%\n%    In this demo we approximate the posterior distribution with\n%    Laplace approximation.\n%\n\n% Copyright (c) 2010 Jaakko Riihim\ufffdki, Jarno Vanhatalo, 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% Load the data\nS = which('demo_multiclass');\nL = strrep(S,'demo_multiclass.m','demodata/cdata.txt');\nx=load(L);\ny=repmat(0,size(x,1),3);\ny(x(:,5)==0,1) = 1;\ny(x(:,5)==1,2) = 1;\ny(x(:,5)==2,3) = 1;\nx(:,end)=[];\n\n% Divide the data into training and test parts.\nxt = x(401:end,:);\nx=x(1:400,:);\nyt=y(401:end,:);\ny=y(1:400,:);\n\n[n, nin] = size(x);\n\n% Create covariance functions\ngpcf1 = gpcf_sexp('lengthScale', ones(1,nin), 'magnSigma2', 1);\n% Set the prior for the parameters of covariance functions\npl = prior_t('s2',10,'nu',10);\npm = prior_sqrtt('s2',10,'nu',10);\ngpcf1 = gpcf_sexp(gpcf1, 'lengthScale_prior', pl,'magnSigma2_prior', pm);\n\n% Create the GP structure\ngp = gp_set('lik', lik_softmax, 'cf', gpcf1, 'jitterSigma2', 1e-2);\n\n% ------- Laplace approximation --------\nfprintf(['Softmax model with Laplace integration over the latent\\n' ...\n         'values and MAP estimate for the parameters\\n'])\n\n% Set the approximate inference method\ngp = gp_set(gp, 'latent_method', 'Laplace');\n\n% We could also use own covariance function for each output the following\n% way\n% gp2 = gp_set('lik', lik_softmax, 'cf', {gpcf1 gpcf1 gpcf1}, 'jitterSigma2', 1e-2);\n% gp2 = gp_set(gp2, 'latent_method', 'Laplace');\n% gp2.comp_cf = {1 2 3};\n% [Eft2, Varft2, ~, ~, pyt2] = gp_pred(gp2, x, y, xt, 'yt', ones(size(yt)));\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3,'Display','iter');\n% Optimize with the BFGS quasi-Newton method\ngp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);\n\n% make the prediction for test points\n[Eft, Varft, lpyt] = gp_pred(gp, x, y, xt, 'yt', ones(size(yt)));\nEft = reshape(Eft, size(xt,1), size(yt,2));\nlpyt = reshape(lpyt, size(xt,1), size(yt,2));\n\n% calculate the percentage of misclassified points\ntt = exp(lpyt)==repmat(max(exp(lpyt),[],2),1,size(exp(lpyt),2));\nmissed = (sum(sum(abs(tt-yt)))/2)/size(yt,1)\n\n% grid for making prediction\nxtg1 = meshgrid(linspace(min(x(:,1))-.1, max(x(:,1))+.1, 30)); \nxtg2 = meshgrid(linspace(min(x(:,2))-.1, max(x(:,2))+.1, 30))';\nxtg=[xtg1(:) xtg2(:) repmat(mean(x(:,3:4)), size(xtg1(:),1),1)];\n\n[Eft, Covft, pg] = gp_pred(gp, x, y, xtg, 'yt', ones(size(xtg,1),3));\nEft = reshape(Eft, size(xtg,1), 3);\npg=reshape(pg,size(xtg,1),3);\n\n% plot the train data o=0, x=1\nfigure, set(gcf, 'color', 'w'), hold on\nplot(x(y(:,1)==1,1),x(y(:,1)==1,2),'ro', 'linewidth', 2);\nplot(x(y(:,2)==1,1),x(y(:,2)==1,2),'x', 'linewidth', 2);\nplot(x(y(:,3)==1,1),x(y(:,3)==1,2),'kd', 'linewidth', 2);\naxis([-0.4 1.4 -0.4 1.4])\ncontour(xtg1, xtg2, reshape(exp(pg(:,1)),30,30),'r', 'linewidth', 2)\ncontour(xtg1, xtg2, reshape(exp(pg(:,2)),30,30),'b', 'linewidth', 2)\ncontour(xtg1, xtg2, reshape(exp(pg(:,3)),30,30),'k', 'linewidth', 2)\n\n% MCMC approach\n\n% Set the approximate inference method\n% Note that MCMC for latent values requires often more jitter\nlat = gp_pred(gp, x, y, x);\ngp = gp_set(gp, 'latent_method', 'MCMC', 'jitterSigma2', 1e-4);\ngp = gp_set(gp, 'latent_opt', struct('method',@scaled_mh));\ngp.latentValues = lat(:);\n\ngp_e(gp_pak(gp), gp, x,y)\ngp_g(gp_pak(gp), gp, x,y)\ngradcheck(randn(size(gp_pak(gp))), @gp_e, @gp_g, gp, x, y);\n\n% Set the parameters for MCMC...\nhmc_opt.steps=10;\nhmc_opt.stepadj=0.001;\nhmc_opt.nsamples=1;\nlatent_opt.display=0;\nlatent_opt.repeat = 20;\nlatent_opt.sample_latent_scale = 0.05;\nhmc2('state', sum(100*clock))\n\n% Sample\n[r,g,opt]=gp_mc(gp, x, y, 'hmc_opt', hmc_opt, 'latent_opt', latent_opt, 'nsamples', 1, 'repeat', 15);\n\n% re-set some of the sampling options\nhmc_opt.repeat=1;\nhmc_opt.steps=4;\nhmc_opt.stepadj=0.02;\nlatent_opt.repeat = 5;\nhmc2('state', sum(100*clock));\n\n% Sample \n[rgp,g,opt]=gp_mc(gp, x, y, 'nsamples', 400, 'hmc_opt', hmc_opt, 'latent_opt', latent_opt, 'record', r);\n% Remove burn-in\nrgp=thin(rgp,102);\n\n% Make predictions\n[Efs_mc, Varfs_mc, pgs_mc] = gpmc_preds(rgp, x, y, xtg, 'yt', ones(size(xtg,1),3));\n\nEf_mc = reshape(mean(Efs_mc,2),900,3);\npg_mc = reshape(mean(exp(pgs_mc),2),900,3);\n\nfigure, set(gcf, 'color', 'w'), hold on\nplot(x(y(:,1)==1,1),x(y(:,1)==1,2),'ro', 'linewidth', 2);\nplot(x(y(:,2)==1,1),x(y(:,2)==1,2),'x', 'linewidth', 2);\nplot(x(y(:,3)==1,1),x(y(:,3)==1,2),'kd', 'linewidth', 2);\naxis([-0.4 1.4 -0.4 1.4])\ncontour(xtg1, xtg2, reshape(pg_mc(:,1),30,30),'r', 'linewidth', 2)\ncontour(xtg1, xtg2, reshape(pg_mc(:,2),30,30),'b', 'linewidth', 2)\ncontour(xtg1, xtg2, reshape(pg_mc(:,3),30,30),'k', 'linewidth', 2)\n\n\n\n% With scaled HMCS\n\n\n\ngp2 = gp_set(gp, 'latent_opt', struct('method',@scaled_hmc));\ngp2.latentValues = lat(:);\n\n% Set the parameters for MCMC...\nhmc_opt.steps=10;\nhmc_opt.stepadj=0.001;\nhmc_opt.nsamples=1;\n\n% latent opt\nlatent_opt.nsamples=1;\nlatent_opt.nomit=0;\nlatent_opt.persistence=0;\nlatent_opt.repeat=20;\nlatent_opt.steps=20;\nlatent_opt.stepadj=0.15;\nlatent_opt.window=5;\nhmc2('state', sum(100*clock))\n\n% Here we make an initialization with \n% slow sampling parameters\n\n[rgp2,gp2,opt]=gp_mc(gp2, x, y, 'hmc_opt', hmc_opt, 'latent_opt', latent_opt, 'nsamples', 1, 'repeat', 15);\n\n% re-set some of the sampling options\nhmc_opt.repeat=1;\nhmc_opt.steps=4;\nhmc_opt.stepadj=0.02;\nlatent_opt.repeat = 20;\nhmc2('state', sum(100*clock));\n\n% Sample \n[rgp2,g2,opt2]=gp_mc(gp2, x, y, 'nsamples', 200, 'hmc_opt', hmc_opt, 'latent_opt', latent_opt, 'record', rgp2);\n% Remove burn-in\nrgp2=thin(rgp2,102);\n\n% Make predictions\n[Efs_mc, Varfs_mc, pgs_mc] = gpmc_preds(rgp2, x, y, xtg, 'yt', ones(size(xtg,1),3));\n\nEf_mc2 = reshape(mean(Efs_mc,2),900,3);\npg_mc2 = reshape(mean(exp(pgs_mc),2),900,3);\n\nfigure, set(gcf, 'color', 'w'), hold on\nplot(x(y(:,1)==1,1),x(y(:,1)==1,2),'ro', 'linewidth', 2);\nplot(x(y(:,2)==1,1),x(y(:,2)==1,2),'x', 'linewidth', 2);\nplot(x(y(:,3)==1,1),x(y(:,3)==1,2),'kd', 'linewidth', 2);\naxis([-0.4 1.4 -0.4 1.4])\ncontour(xtg1, xtg2, reshape(pg_mc2(:,1),30,30),'r', 'linewidth', 2)\ncontour(xtg1, xtg2, reshape(pg_mc2(:,2),30,30),'b', 'linewidth', 2)\ncontour(xtg1, xtg2, reshape(pg_mc2(:,3),30,30),'k', 'linewidth', 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/dmlt/external/gpstuff/gp/demo_multiclass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5814617230755323}}
{"text": "function [acc, pred] = CrossValidateKNN(y, X, tCL, k, knn_size);\n% [acc, pred] = CrossValidateKNN(y, X, tCL, k, knn_size);\n% \n% Cross-validation for evaluating the k-nearest neighbor classifier with\n% a learned metric.  Performs k-fold cross validation, training on the\n% training fold and evaluating on the test fold\n%\n% y: (n x 1) true labels\n%\n% X: (n x m) data matrix\n%\n% tCL: Metric learning algorithm that takes in true labels as first\n% argument, and data as a second\n%\n% k: Number of cross-validated folds\n%\n% knn_size: size of nearest neighbor window\n%\n% Returns \n% acc: cross-validated accuracy\n% pred: predictions on test set for each row in X\n\n[n,m] = size(X);\nif (n ~= length(y)),\n   disp('ERROR: num rows of X must equal length of y');\n   return;\nend\n\n%permute the rows of X and y\nrp = randperm(n);\ny = y(rp);\nX = X(rp, :);\n\npred = zeros(n,1);\nfor (i=1:k),\n   test_start = ceil(n/k * (i-1)) + 1;\n   test_end = ceil(n/k * i);\n\n   yt = [];\n   Xt = zeros(0, m);\n   if (i > 1);\n       yt = y(1:test_start-1);\n       Xt = X(1:test_start-1,:);\n   end\n   if (i < k),\n       yt = [yt; y(test_end+1:length(y))];\n       Xt = [Xt; X(test_end+1:length(y), :)];\n   end\n   \n   nt = length(yt);\n   yt = yt(1:nt);\n   Xt = Xt(1:nt, :);\n\n   %train model\n   M = feval(tCL, yt, Xt);\n   \n   %evaluate model \n   XT = X(test_start:test_end, :);\n   yT =  y(test_start:test_end);\n   pred(test_start:test_end) = KNN(yt, Xt, sqrtm(M), knn_size, XT); \nend\nacc = sum(pred==y)/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/itml/CrossValidateKNN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5814617178068215}}
{"text": "function drawIdpLin(MapFig,Lmk,color,MapOpt)\n\n% DRAWIDPLIN  Draw inverse-depth line landmark in MapFig.\n\n%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nglobal Map\n\n% get the lmk from the Map\nr   = Lmk.state.r;       % range in Map\nidl = Map.x(r);          % mean\nIDL = Map.P(r,r);        % covariances matrix\nt   = [Lmk.par.endp.t]'; % abscissas of endpoints, t = [t1;t2]\n\n% extract two endpoints - means and covariance\n[e1,e2,E1_idl,E2_idl] = idpLinEndpoints(idl,t(1),t(2)); % means and Jacobians\nE1 = E1_idl*IDL*E1_idl'; % covariances\nE2 = E2_idl*IDL*E2_idl';\n\n% draw the mean:\ndrawSeg(MapFig.Lmk(Lmk.lmk).mean,[e1;e2],color.mean)\n\n% draw the covariance ellipses\nif MapOpt.showEllip\n    drawEllipse(MapFig.Lmk(Lmk.lmk).ellipse(1), e1, E1, color.ellip)\n    drawEllipse(MapFig.Lmk(Lmk.lmk).ellipse(2), e2, E2, color.ellip)\nend\n\n% draw the label\nif MapOpt.showLmkId\n    e = e2-e1;\n    n = null([e e e]);\n    n = n(:,2)*sign(n(3,2)); % Inverse depth line's normal vector\n    posOffset = 0.2*n;     % label orthogonally out of the line.\n    drawLabel(MapFig.Lmk(Lmk.lmk).label,0.5*(e1+e2) + posOffset,num2str(Lmk.id))\nend\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 <http://www.gnu.org/licenses/>.\n%\n%---------------------------------------------------------------------\n\n%   SLAMTB is Copyright:\n%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n%   Copyright (c) 2010-2013, Joan Sola,\n%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n%   SLAMTB is Copyright 2009 \n%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n%   @ LAAS-CNRS.\n%   See on top of this file for its particular copyright.\n\n%   # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/Graphics/drawIdpLin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5814617178068215}}
{"text": "function S = globMatrixNed3DMass(fun,mesh,fem1,fem2)\n\n%% USAGE: generate stiffness global matrix on a 3D mesh \n%\n% INPUTS:\n% fun --- coefficient function\n% mesh --- a struct data contains very rich mesh information.\n% fem1 --- global DoF for test function space\n% fem2 --- global DoF for trial function space\n%\n% OUTPUTS:\n% [IN JN XN] --- triplets of the sparse matrix from regular elements. \n% [II JI XI] --- triplets of the sparse matrix from interface elements. \n\n% Last Modified: 08/07/2020 by Xu Zhang \n\n%% 0. Initializaiton\nfeEvalBas1 = @EvalNed1Bas3D;\nfeEvalBas2 = @EvalNed1Bas3D;\n\ndof1 = fem1.ldof; dof2 = fem2.ldof; nloc = dof1*dof2; \nnt = length(mesh.t);\nA = fem1.area; gx = fem1.gx; gy = fem1.gy; gz = fem1.gz; gw = fem1.gw;\nX = zeros(nloc*nt, 1);\n\ncoef = feval(fun,gx,gy,gz);\nIbasx = cell(dof1,1); Ibasy = cell(dof1,1); Ibasz = cell(dof1,1); \nJbasx = cell(dof2,1); Jbasy = cell(dof2,1); Jbasz = cell(dof2,1);\nfor i = 1:dof1\n    Ibasx{i} = feEvalBas1(fem1.bas, ':', gx, gy, gz, i, 0, 1).*fem1.t_e_orit(:,i);\n    Ibasy{i} = feEvalBas1(fem1.bas, ':', gx, gy, gz, i, 0, 2).*fem1.t_e_orit(:,i);\n    Ibasz{i} = feEvalBas1(fem1.bas, ':', gx, gy, gz, i, 0, 3).*fem1.t_e_orit(:,i);\nend\nfor j = 1:dof2\n    Jbasx{j} = feEvalBas2(fem2.bas, ':', gx, gy, gz, j, 0, 1).*fem2.t_e_orit(:,j);\n    Jbasy{j} = feEvalBas2(fem2.bas, ':', gx, gy, gz, j, 0, 2).*fem2.t_e_orit(:,j);\n    Jbasz{j} = feEvalBas2(fem2.bas, ':', gx, gy, gz, j, 0, 3).*fem2.t_e_orit(:,j);\nend\n\nI = reshape(repmat(fem1.g2ldof,6,1),nloc*nt,1);\nJ = repmat(reshape(fem2.g2ldof,dof2*nt,1),6,1);\nind = 0;\nfor i = 1:dof1\n    for j = 1:dof2\n        X(ind+1:ind+nt) = A.*(sum(((Ibasx{i}.*(coef.*Jbasx{j})).*gw'),2) + ...\n            sum(((Ibasy{i}.*(coef.*Jbasy{j})).*gw'),2) + ...\n            sum(((Ibasz{i}.*(coef.*Jbasz{j})).*gw'),2));\n        ind = ind + nt;\n    end\nend\nID = find(X~=0); \nS = sparse(I(ID),J(ID),X(ID),size(fem1.gdof,1),size(fem2.gdof,1));", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/globMatrixNed3DMass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5814617039854378}}
{"text": "% test_all_fbp\n\n% todo:\n% cuboid_im test\n% cuboid_proj test\n\nlist = {\n'cbct_back test'\n'ct_geom test'\n'image_geom test'\n'sino_geom test'\n'cylinder_proj test'\n'df_example1'\n'ellipse_im test'\n'ellipse_sino test'\n'ellipsoid_proj test'\n'ellipsoid_im test'\n'fbp_fan_arc_example'\n'fbp_fan_arc_point'\n'fbp_fan_flat_example'\n'fbp_ramp test'\n'fbp2_sino_filter test'\n'fbp2_example'\n'feldkamp_example'\n'jaszczak1 test'\n'ir_radon_zwart_powell test'\n'rebin_helix test' % helix_example\n'rect_im test'\n'rect_sino test'\n%'sphere_proj test'\n};\n\nim nan-fail\nrun_mfile_local(list)\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/fbp/test_all_fbp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5814595755519607}}
{"text": "% Proces MSE results into MSE curves: average out and/or limit to a\n% subset of temporal indices.\n%\n% Input:\n% - results: a configresults cell produced by kafbox_profiler.\n% - inds: array of indices for which to calculate output\n%\n% Output:\n% - MSE_avg_setups: cell containing averaged out MSE curves, structure\n% corresponds to \"results\" cell structure.\n%\n% This file is part of the Kernel Adaptive Filtering Toolbox for Matlab.\n% https://github.com/steven2358/kafbox/\n\nfunction MSE_avg_setups = kafbox_profiler_msecurves(results,inds)\n\nnum_setups = length(results);\nMSE_avg_setups = cell(num_setups,1);\n\nfor setup_ind = 1:num_setups\n    setup_results = results{setup_ind};\n    \n    num_configs = length(setup_results);\n    MSE_avg_configs = cell(num_configs,1);\n\n    for config_ind = 1:num_configs\n        config_results = setup_results{config_ind};\n        \n        if isfield(config_results{1},'NMSE')\n            N = length(config_results{1}.NMSE); % temporary\n        else\n            N = length(config_results{1}.MSE);\n        end\n        MSE = zeros(N,1);\n        \n        num_sim = length(config_results);\n        for sim_ind = 1:num_sim\n            simresults = config_results{sim_ind};\n            \n            if isfield(simresults,'NMSE') % temporary\n                simresults.MSE = simresults.NMSE;\n            end\n            if nargin<2\n                inds = 1:length(simresults.MSE);\n            end\n\n            mm = min(length(simresults.MSE(inds)),N);\n            MSE = MSE(1:mm) + simresults.MSE(inds(1:mm))/num_sim;\n        end\n        MSE_avg_configs{config_ind} = MSE;\n    end\n    MSE_avg_setups{setup_ind} = MSE_avg_configs;\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/profiler/kafbox_profiler_msecurves.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5814595688156212}}
{"text": "function p06_limit_test ( option )\n\n%*****************************************************************************80\n%\n%% P06_LIMIT_TEST seeks limit points for problem 6.\n%\n%  Discussion:\n%\n%    We want to find points X such that TAN(7) = 0.\n%\n%    The number of limit points that may be expected depends on the option:\n%\n%    There are five options, which vary in the value they fix the\n%    elevator value X(6):\n%\n%      Option   Elevator Value    Limit Points\n%\n%       1        -0.050              1\n%       2        -0.008              3\n%       3         0.0                2\n%       4         0.05               1\n%       5         0.1                1\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 October 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Raman Mehra, William Kessel, James Carroll,\n%    Global stability and contral analysis of aircraft at high angles of attack,\n%    Technical Report CR-215-248-1, -2, -3,\n%    Office of Naval Research, June 1977.\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%    Albert Schy, Margery Hannah,\n%    Prediction of Jump Phenomena in Roll-coupled Maneuvers of Airplanes,\n%    Journal of Aircraft,\n%    Volume 14, Number 4, 1977,  pages 375-382.\n%\n%    John Young, Albert Schy, Katherine Johnson,,\n%    Prediction of Jump Phenomena in Aircraft Maneuvers, Including\n%    Nonlinear Aerodynamic Effects,\n%    Journal of Guidance and Control,\n%    Volume 1, Number 1, 1978, pages 26-31.\n%\n%  Parameters:\n%\n%    Input, integer OPTION, the option index.\n%    1, X(6) fixed at -0.050, X(7) free, X(8) fixed at 0.0;\n%    2, X(6) fixed at -0.008, X(7) free, X(8) fixed at 0.0;\n%    3, X(6) fixed at  0.000, X(7) free, X(8) fixed at 0.0;\n%    4, X(6) fixed at  0.050, X(7) free, X(8) fixed at 0.0;\n%    5, X(6) fixed at  0.100, X(7) free, X(8) fixed at 0.0.\n%\n  problem = 6;\n  lim = 7;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'P06_LIMIT_TEST\\n' );\n  fprintf ( 1, '  Compute a series of solutions for problem 6.\\n' );\n  fprintf ( 1, '  We are trying to find limit points X such that\\n' );\n  fprintf ( 1, '  TAN(%d) = 0.\\n', lim );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The option chosen is %d\\n', option );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '   #   Tan(7)     X1       X2       X3       X4       X5       X6       X7      X8\\n' );\n  fprintf ( 1, '                Roll     Pitch    Yaw      Attack   Sideslip Elevator Aileron Rudder\\n' );\n  fprintf ( 1, '\\n' );\n%\n%  Get problem size.\n%\n  nvar = p00_nvar ( problem, option );\n\n  lim_num = 0;\n%\n%  Get starting point.\n%\n  x2 = p00_start ( problem, option, nvar );\n%\n%  Get the tangent vector.\n%\n  tan2 = p00_tan ( problem, option, nvar, x2 );\n%\n%  For correction of initial point, use variable index 7.\n%\n  par_index = 7;\n%\n%  Force F(X) = 0.\n%\n  step = -1;\n  fprintf ( 1, '  %2d %8.1e %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\\n', ...\n    step, tan2(lim), x2(1:nvar) );\n\n  [ x2, status ] = p00_newton ( problem, option, nvar, x2, par_index );\n\n  if ( status < 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Newton iteration failed on starting point.\\n' );\n    return\n  end\n\n  tan2 = p00_tan ( problem, option, nvar, x2 );\n\n  step = 0;\n  fprintf ( 1, '  %2d %8.1e %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\\n', ...\n    step, tan2(lim), x2(1:nvar) );\n%\n%  Get stepsize.\n%\n  [ h, hmin, hmax ] = p00_stepsize ( problem, option );\n%\n%  LOOP:\n%\n  step_max = 30;\n\n  for step = 1 : step_max\n%\n%  Save old data as X1, TAN1.\n%\n    x1 = x2;\n    tan1 = tan2;\n\n    h_reduction = 0;\n%\n%  Use X1 + H * TAN1 as a starting estimate for Newton iteration.\n%\n    while ( 1 )\n\n      if ( hmax < abs ( h ) )\n        h = hmax * r8_sign ( h );\n      end\n\n      if ( abs ( h ) < hmin )\n        h = hmin * r8_sign ( h );\n      end\n\n      x2 = x1 + h * tan1;\n\n      par_index = 0;\n      [ x2, status ] = p00_newton ( problem, option, nvar, x2, par_index );\n%\n%  If we didn't get it, can we try again?\n%\n      if ( status < 0 )\n\n        if ( abs ( h ) <= hmin )\n          fprintf ( 1, '\\n' );\n          fprintf ( 1, '  Cannot decrease stepsize any more.\\n' );\n          fprintf ( 1, '  Cannot complete the computation.\\n' );\n          return\n        else\n          h = h / 4.0;\n          h_reduction = h_reduction + 1;\n        end\n%\n%  We computed the point.\n%  Should we change the stepsize?\n%\n      else\n\n        if ( h_reduction == 0 )\n\n          if ( status <= 1 )\n            h = h * 4.0;\n          elseif ( status <= 3 )\n            h = h * 2.0;\n          elseif ( 12 <= status )\n            h = h / 4.0;\n          elseif ( 8 <= status )\n            h = h / 2.0;\n          end\n\n        end\n\n        break;\n\n      end\n\n    end\n%\n%  Compute the tangent vector.\n%\n    tan2 = p00_tan ( problem, option, nvar, x2 );\n%\n%  Check for a limit point.\n%\n    if ( tan1(lim) * tan2(lim) <= 0.0 )\n      [ x, tan, status ] = p00_limit ( problem, option, nvar, x1, tan1, x2, tan2, lim );\n      fprintf ( 1, '   L %8.1e %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\\n', ...\n        tan(lim), x(1:nvar) );\n      lim_num = lim_num + 1;\n    end\n\n    fprintf ( 1, '  %2d %8.1e %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\\n', ...\n      step, tan2(lim), x2(1:nvar) );\n\n    if ( step == step_max )\n      break\n    end\n\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of limit points found was %d\\n', lim_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/test_con/p06_limit_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5814595543500146}}
{"text": "% Test trajectory primitives\n\nmdl_puma560\n\n[q,qd,qdd] = jtraj(qz, qr, 20)\nq\nqd\nqdd\n\n[q,qd,qdd] = jtraj(qz, qr, 20, 0.1*mat(ones(1,6)), -0.1*mat(ones(1,6)) )\nq\nqd\nqdd\n\n[q,qd,qdd] = jtraj(qz, qr, [0:0.2:10])\nq\n\nt1 = trotx(0.1) * transl(0.2, 0.3, 0.4)\nt1\nt2 = troty(-0.3) * transl(-0.2, -0.3, 0.6)\nt2\nctraj(t1, t2, 5)\nctraj(t1, t2, [0:0.1:1])\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/unit_test/old/trajectory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.581320074107322}}
{"text": "function out = mirror_extend(in,bx,by)\n% Pad array with mirror reflections of itself.\n% bx and by specify the amount of padding to add.\n% ***********************************************\n\n[h,w] = size(in);\n\n%First flip up and down\nu = flipud(in(2:1+bx,:));\nd = flipud(in(h-bx:h-1,:));\n\nin2 = [u' in' d']';\n\n%Next flip left and right\nl = fliplr(in2(:, 2:1+by));\nr = fliplr(in2(:,w-by:w-1));\n\n%set the 'mirrored' image to out.\nout = [l in2 r];\n\nreturn\n\n%test\n% A = [1 2 3 4;5 6 7 8;9 10 11 12]\n% B = mirror_extend(A,2,2)\n\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/SRCF_Image_Fuion_Codes/Utils/mirror_extend.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.5813200729078911}}
{"text": "function [ n_data, x, fx ] = tran06_values ( n_data )\n\n%*****************************************************************************80\n%\n%% TRAN06_VALUES returns some values of the order 6 transportation function.\n%\n%  Discussion:\n%\n%    The function is defined by:\n%\n%      TRAN06(x) = Integral ( 0 <= t <= x ) t^6 * exp(t) / ( exp(t) - 1 )^2 dt\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    19 September 2004\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Milton Abramowitz and Irene Stegun,\n%    Handbook of Mathematical Functions,\n%    US Department of Commerce, 1964.\n%\n%    Allan McLeod,\n%    Algorithm 757, MISCFUN: A software package to compute uncommon\n%    special functions,\n%    ACM Transactions on Mathematical Software,\n%    Volume 22, Number 3, September 1996, pages 288-301.\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     0.56843405953641209574E-14, ...\n     0.59601180165247401484E-08, ...\n     0.60978424397580572815E-05, ...\n     0.61578909866319494394E-02, ...\n     0.18854360275680840514E+00, ...\n     0.13319251347921659134E+01, ...\n     0.50857202271697616755E+01, ...\n     0.13729222365466557122E+02, ...\n     0.29579592481641441292E+02, ...\n     0.88600835706899853768E+02, ...\n     0.10916037113373004909E+03, ...\n     0.18224323749575359518E+03, ...\n     0.23765383125586756031E+03, ...\n     0.29543246745959381136E+03, ...\n     0.50681244381280455592E+03, ...\n     0.63878231134946125623E+03, ...\n     0.72699203556994876111E+03, ...\n     0.73230331643146851717E+03, ...\n     0.73248692015882096369E+03, ...\n     0.73248700462879996604E+03 ];\n\n  x_vec = [ ...\n       0.0019531250E+00, ...\n       0.0312500000E+00, ...\n       0.1250000000E+00, ...\n       0.5000000000E+00, ...\n       1.0000000000E+00, ...\n       1.5000000000E+00, ...\n       2.0000000000E+00, ...\n       2.5000000000E+00, ...\n       3.0000000000E+00, ...\n       4.0000000000E+00, ...\n       4.2500000000E+00, ...\n       5.0000000000E+00, ...\n       5.5000000000E+00, ...\n       6.0000000000E+00, ...\n       8.0000000000E+00, ...\n      10.0000000000E+00, ...\n      15.0000000000E+00, ...\n      20.0000000000E+00, ...\n      30.0000000000E+00, ...\n      50.0000000000E+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/tran06_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5813200515438496}}
{"text": "function x = sample_fs(xf, grid_sz)\n\n% Samples the Fourier series\n\nsz = [size(xf,1) size(xf,2)];\n\nif nargin < 2\n    x = prod(sz) * cifft2(xf);\nelse\n    if any(grid_sz < sz)\n        error('The grid size must be larger than or equal to the signal size')\n    end\n    tot_pad = grid_sz - sz;\n    pad_sz = ceil(tot_pad/2);\n    xf_pad = padarray(xf, pad_sz);\n    if any(mod(tot_pad,2) == 1)\n        % Handle odd padding\n        xf_pad = xf_pad(1:end-mod(tot_pad(1),2), 1:end-mod(tot_pad(2),2), :, :);\n    end\n    x = prod(grid_sz) * cifft2(xf_pad);\nend\n\n\n", "meta": {"author": "he010103", "repo": "CFWCR", "sha": "c6a30234dd6448cef954b8b38f518fa8047c4850", "save_path": "github-repos/MATLAB/he010103-CFWCR", "path": "github-repos/MATLAB/he010103-CFWCR/CFWCR-c6a30234dd6448cef954b8b38f518fa8047c4850/implementation/fourier_tools/sample_fs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5813200503444184}}
{"text": "function [cum_ret, cumprod_ret, daily_ret, daily_portfolio] ...\n    = grw_run(fid, data, N, sigma, tc, opts)\n% This file is the run core for the EG strategy.\n%\n% function [cum_ret, cumprod_ret, daily_ret, daily_portfolio] ...\n%           = eg_run(fid, data, tc, opts)\n%\n% cum_ret: cumulative wealth achived at the end of a period.\n% cumprod_ret: cumulative wealth achieved till the end each period.\n% daily_ret: daily return achieved by a strategy.\n% daily_portfolio: daily portfolio, achieved by the strategy\n%\n% data: market sequence vectors\n% fid: handle for write log file\n% gamma: swtiching parameter\n% tc: transaction fee rate\n% opts: option parameter for behvaioral control\n%\n% Example: [cum_ret, cumprod_ret, daily_ret, daily_portfolio] ...\n%          = grw_run(fid, data, 10, 0.00005, 0, opts);\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[n, m] = size(data);\n\n% Variables for return, start with uniform weight\ncum_ret = 1;\ncumprod_ret = ones(n, 1);\ndaily_ret = ones(n, 1);\nday_weight = ones(m, 1)/m;  %#ok<*NASGU>\nday_weight_o = zeros(m, 1);\ndaily_portfolio = zeros(n, m);\n\n% print file head\nfprintf(fid, '-------------------------------------\\n');\nfprintf(fid, 'Parameters [N:%f, sigma:%f, tc:%f]\\n', N, sigma, tc);\nfprintf(fid, 'day\\t Daily Return\\t Total return\\n');\n\nfprintf(1, '-------------------------------------\\n');\nif(~opts.quiet_mode)\n    fprintf(1, 'Parameters [N:%f, sigma:%f, tc:%f]\\n', N, sigma, tc);\n    fprintf(1, 'day\\t Daily Return\\t Total return\\n');\nend\n\n% choose normal vectors\nxi = normrnd(1/m, sigma^2, N, m);\ngamma  = zeros(size(xi));\n\noptions = optimset('largescale','off', 'display', 'off');\n\nfor t = 1:1:n,\n    % Calculate t's portfolio at the beginning of t-th trading day\n    [day_weight] = grw_kernel(data(1, :), xi);\n    \n    % projection\n    C = eye(m, m); d = day_weight;\n    A = []; b=[];\n    Aeq = ones(m, 1)'; beq = 1;\n    lb = zeros(m, 1); ub = ones(m, 1);\n    day_weight = lsqlin(C, d, A, b, Aeq, beq, lb, ub, day_weight, options);\n    if or((day_weight < 0.0001), (day_weight'*ones(m, 1)>1.00001))\n        fprintf(1, 't=%d, sum(day_weight)=%d, pause', t, day_weight'*ones(m, 1));\n        pause;\n    end\n    \n    % Normalize the constraint, always useless\n    day_weight = day_weight./sum(day_weight);\n    \n    % Cal t's return and total return\n    daily_ret(t, 1) = (data(t, :)*day_weight)*(1-tc/2*sum(abs(day_weight-day_weight_o)));\n    cum_ret = cum_ret * daily_ret(t, 1);\n    cumprod_ret(t, 1) = cum_ret;\n    \n    % Adjust weight(t, :) for the transaction cost issue\n    day_weight_o = day_weight.*data(t, :)'/daily_ret(t, 1);\n    \n    % Monte Carlo update\n    k = 1;\n    while k <= N,   % Checks the size of our new sample\n        u = rand(1); % Choose u from \\mu[0, 1]\n        j = randi([1, N]);  % Choose j randomly from {1, ... , N}\n        \n        if (u <= exp(xi(j, :))./sum(exp(xi(j, :)))*data(t, :)'/(max(data(t, :))) )  % accept-reject condition\n            gamma(k, :) = xi(j, :);  k = k+1;   % Accepts xi if the above condition holds\n        end\n    end\n    \n    % Portfolio Update step\n    h = normrnd(0, sigma^2, N, m);   \n    xi = gamma + h;\n    \n    % Debug information\n    % Time consuming part, other way?\n    fprintf(fid, '%d\\t%f\\t%f\\n', t, daily_ret(t, 1), cumprod_ret(t, 1));\n    if (~opts.quiet_mode)\n        if (~mod(t, opts.display_interval)),\n            fprintf(1, '%d\\t%f\\t%f\\n', t, daily_ret(t, 1), cumprod_ret(t, 1));\n        end\n    end\nend\n\n% Debug Information\nfprintf(fid, 'GRW(N:%d, sigma:%f, tc:%f), Final return: %f\\n',...\n    N, sigma, tc, cum_ret);\nfprintf(fid, '-------------------------------------\\n');\nfprintf(1, 'GRW(N:%d, sigma:%f, tc:%f), Final return: %f\\n',...\n    N, sigma, tc, cum_ret);\nfprintf(1, '-------------------------------------\\n');\n\nend", "meta": {"author": "OLPS", "repo": "OLPS", "sha": "9120783cd59a7966b0f78e2b5668030a4378b8af", "save_path": "github-repos/MATLAB/OLPS-OLPS", "path": "github-repos/MATLAB/OLPS-OLPS/OLPS-9120783cd59a7966b0f78e2b5668030a4378b8af/Strategy/grw_run.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5812758792369858}}
{"text": "function [theta,e,hy,hp] = GLM_covComp(y,X,Qy,Qp,my,mp)\n% wraps GLM with multiple covariance components estimation into VBA\n% function [theta,e] = GLM_covComp(y,X,Qy,Qp,my,mp)\n% IN:\n%   - y: px1 data vector\n%   - X: pxn_phi GLM design matrix\n%   - Qy: nqyx1 cell array of data covariance components\n%   - Qp: nqpx1 cell array of GLM coef covariance components\n%   - my: prior mean on data precision hyperparameters in log-space\n%   - mp: prior mean on GLM coef precision hyperparameters in log-space\n% OUT:\n%   - theta: n_phix1 vector of estimated GLM coef\n%   - e: px1 vector of estimated residuals\n\nnqy = length(Qy);\nnqp = length(Qp);\n\n[ny,np] = size(X);\n\ndim.p = size(y,1);\ndim.n_phi = (np+1)*nqp + (ny+1)*nqy;\ndim.n_theta = 0;\ndim.n = 0;\ndim.n_t = 1;\n\npriors.muPhi = zeros(dim.n_phi,1);\npriors.SigmaPhi = zeros(dim.n_phi,dim.n_phi);\n\nind = cell(4,1);\nlast = 0;\nfor i=1:nqy\n    ind{1}(i) = last+1;\n    ind2i = ind{1}(i)+1:ind{1}(i)+ny;\n    ind{2} = [ind{2};ind2i];\n    last = ind2i(end);\n    priors.muPhi(ind{1}(i)) = my(i);\n    priors.SigmaPhi(ind{1}(i),ind{1}(i)) = 4;\n    priors.SigmaPhi(ind2i,ind2i) = Qy{i};\nend\nfor j=1:nqp\n    ind{3}(j) = last+1;\n    ind4j = ind{3}(j)+1:ind{3}(j)+np;\n    ind{4} = [ind{4};ind4j];\n    last = ind4j(end);\n    priors.muPhi(ind{3}(j)) = mp(j);\n    priors.SigmaPhi(ind{3}(j),ind{3}(j)) = 4;\n    priors.SigmaPhi(ind4j,ind4j) = Qp{j};\nend\npriors.a_sigma = 1e8;\npriors.b_sigma = 1e0;\n\ninG.X = X;\ninG.ind = ind;\ninG.dim = struct('ny',ny,'np',np,'nqy',nqy,'nqp',nqp);\n\noptions = struct(...\n    'priors',priors,...\n    'inG',inG,...\n    'updateHP',0,...\n    'MaxIter',128,...\n    'GnMaxIter',64);\ng_fname = @g_wrapGLM;\n\n[posterior,out] = VBA_NLStateSpaceModel(y,[],[],g_fname,dim,options);\n\n\n[theta,e,hy,hp] = collapseGLM(posterior.muPhi,inG);\n\n\n\n\n\nfunction [gx] = g_wrapGLM(x,P,u,in)\n[theta,e] = collapseGLM(P,in);\ngx = in.X*theta + e;\n\nfunction [theta,e,hy,hp] = collapseGLM(P,in)\nP1 = P(in.ind{1});\nP2 = reshape(P(in.ind{2}),in.dim.ny,in.dim.nqy);\nP3 = P(in.ind{3});\nP4 = reshape(P(in.ind{4}),in.dim.np,in.dim.nqp);\nhp = exp(P3);\ntheta = P4*hp;\nhy = exp(P1);\ne = P2*hy;\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/modules/GLM/GLM_covComp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5812758686849914}}
{"text": "function y = tan(x)\n%TAN          Implements  tan(x)  for intervals\n%\n%   y = tan(x)\n%\n%interval standard function implementation\n%\n\n% written  12/30/98     S.M. Rump\n% modified 09/13/99     S.M. Rump  complex allowed, sparse input, NaN 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 11/20/05     S.M. Rump  fast check for rounding to nearest\n% modified 12/04/05     S.M. Rump  extreme values for approximate part\n% modified 09/06/07     S.M. Rump  approximate std fcts removed\n% modified 08/26/12     S.M. Rump  global variables removed\n% modified 10/13/12     S.M. Rump  INTLAB_INTVAL_STDFCTS\n%\n\n  if issparse(x)\n    [ix,jx,sx] = find(x);\n    [m,n] = size(x);\n    y = sparse(ix,jx,tan(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 = sin(x)./cos(x);  \n    setround(rndold)\n    return\n  end\n\n  INTLAB_STDFCTS_PI = getappdata(0,'INTLAB_STDFCTS_PI');\n\n  y = x;\n\n  % transform x.inf and x.sup mod pi/2\n  [ xinfinf , xinfsup , Sinf ] = modpi2(x.inf);\n  [ xsupinf , xsupsup , Ssup ] = modpi2(x.sup);\n\n  % indices with result +/- inf\n  setround(1)\n  delta = x.sup-x.inf;\n  indexinf = ( delta >= INTLAB_STDFCTS_PI.PIINF ) | ...\n    ( floor(Sinf/4) ~= floor(Ssup/4) );\n  Sinf(Sinf>3) = Sinf(Sinf>3) - 4;\n  Ssup(Ssup>3) = Ssup(Ssup>3) - 4;\n\n  % transformation of input arguments by modpi2:\n  %   [ xinf,xsup,s ] = modpi2(y)  ==>  0 <= s <= 7, 0 <= x <= pi/4 and\n  %   x = -pi/2 + y + s*pi/4 + 2k*pi        for s even\n  %   x =       - y + (s-1)*pi/4 + 2k*pi    for s odd\n\n  y.inf(:) = -inf;\n  y.sup(:) = inf;\n\n  % treat non-infinity intervals\n  Sinf(indexinf) = -1;\n  Ssup(indexinf) = -1;\n\n  % save warning status\n  wng = warning;\n  warning off\n\n  % treat infimum\n  index = ( Sinf==0 );\n  if any(index(:))\n    y.inf(index) = 1 ./ ( - tan_pos(xinfinf(index),-1) );\n  end\n  index = ( Sinf==1 );\n  if any(index(:))\n    y.inf(index) = - tan_pos(xinfsup(index),1);\n  end\n  index = ( Sinf==2 );\n  if any(index(:))\n    y.inf(index) = tan_pos(xinfinf(index),-1);\n  end\n  index = ( Sinf==3 );\n  if any(index(:))\n    res = tan_pos(xinfsup(index),1);\n    setround(-1)\n    y.inf(index) = 1 ./ res;\n  end\n\n  % treat supremum\n  index = ( Ssup==0 );\n  if any(index(:))\n    y.sup(index) = 1 ./ ( - tan_pos(xsupsup(index),1) );\n  end\n  index = ( Ssup==1 );\n  if any(index(:))\n    y.sup(index) = - tan_pos(xsupinf(index),-1);\n  end\n  index = ( Ssup==2 );\n  if any(index(:))\n    y.sup(index) = tan_pos(xsupsup(index),1);\n  end\n  index = ( Ssup==3 );\n  if any(index(:))\n    res = tan_pos(xsupinf(index),-1);\n    setround(1)\n    y.sup(index) = 1 ./ res;\n  end\n\n  % restore warning status\n  warning(wng);\n\n  index = isnan(x.inf);\n  if any(index(:))\n    y.inf(index) = NaN;\n    y.sup(index) = NaN;\n  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/tan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5812758586964147}}
{"text": "classdef Polyhedron\n\n  properties\n    A;\n    b;\n    Aeq = [];\n    beq = [];\n    vertices;\n    has_vertices = false;\n  end\n\n  methods\n    function obj = Polyhedron(A, b, Aeq, beq)\n      if nargin < 3\n        Aeq = [];\n      end\n      if nargin < 4\n        beq = [];\n      end\n      obj.A = A;\n      obj.b = b;\n      obj.Aeq = Aeq;\n      obj.beq = beq;\n    end\n\n    function vertices = getVertices(obj)\n      obj = obj.reduce();\n      if ~obj.has_vertices\n        if exist('cddmex', 'file')\n          H = struct('A', [obj.Aeq; obj.A], 'B', [obj.beq; obj.b], 'lin', (1:size(obj.Aeq, 1))');\n          V = cddmex('extreme', H);\n          obj.vertices = V.V';\n        else\n          obj.vertices = iris.thirdParty.polytopes.lcon2vert(obj.A, obj.b, obj.Aeq, obj.beq)';\n        end\n        obj.has_vertices = true;\n      end\n      vertices = obj.vertices;\n    end\n    \n    function reduced_poly = reduce(obj)\n      % Find a minimal representation of the polyhedron\n      if ~exist('cddmex', 'file')\n        error('IRIS:MissingDependency', 'This function requires the cddmex tool. The easiest way to get it is using tbxmanager: http://www.tbxmanager.com/');\n      end\n      H = struct('A', [obj.Aeq; obj.A], 'B', [obj.beq; obj.b], 'lin', (1:size(obj.Aeq, 1))');\n      Hred = cddmex('reduce_h', H);\n      assert(isempty(Hred.lin), 'as far as I know, Hred.lin should always be empty. That is, the reduced polyhedron should not contain equality constraints. -rdeits');\n      reduced_poly = iris.Polyhedron(Hred.A, Hred.B);\n    end\n\n    function plotVertices(obj, varargin)\n      vertices = obj.getVertices();\n      if ~isempty(vertices)\n        if size(vertices, 2) > 2\n          k = convhull(vertices(1,:), vertices(2,:));\n        else\n          k = [1:size(vertices, 2), 1];\n        end\n        plot(vertices(1,k), vertices(2,k), varargin{:});\n      end\n    end\n\n    function drawLCMGL(obj, lcmgl)\n      lcmgl.glBegin(lcmgl.LCMGL_LINES);\n      vertices = obj.getVertices();\n      if size(vertices, 2) > 2\n        k = convhull(vertices(1,:), vertices(2,:));\n      else\n        k = [1:size(vertices, 2), 1];\n      end\n      for j = 1:length(k)-1\n        lcmgl.glVertex3d(vertices(1,k(j)), vertices(2,k(j)), vertices(3,k(j)));\n        lcmgl.glVertex3d(vertices(1,k(j+1)), vertices(2,k(j+1)), vertices(3,k(j+1)));\n      end\n      lcmgl.glEnd();\n    end\n    \n    function obj = normalize(obj)\n      n = zeros(size(obj.A, 1), 1);\n      for j = 1:size(obj.A, 1)\n        n(j) = norm(obj.A(j,:));\n        obj.A(j,:) = obj.A(j,:) / n(j);\n        obj.b(j) = obj.b(j) / n(j);\n      end\n      obj.A = obj.A(n > 0, :);\n      obj.b = obj.b(n > 0);\n      \n      n = zeros(size(obj.Aeq, 1), 1);\n      for j = 1:size(obj.Aeq, 1)\n        n(j) = norm(obj.Aeq(j,:));\n        obj.Aeq(j,:) = obj.Aeq(j,:) / n(j);\n        obj.beq(j) = obj.beq(j) / n(j);\n      end\n      obj.Aeq = obj.Aeq(n > 0, :);\n      obj.beq = obj.beq(n > 0);\n    end\n\n  end\n\n  methods(Static)\n    function obj = fromVertices(vertices)\n      [A, b] = iris.thirdParty.polytopes.vert2lcon(vertices');\n      obj = iris.Polyhedron(A, b);\n    end\n\n    function obj = from2DVertices(vertices)\n      assert(size(vertices, 1) == 2);\n      x = vertices(1,:);\n      y = vertices(2,:);\n      k = convhull(x,y, 'simplify', true);\n      A = [(y(k(2:end)) - y(k(1:end-1)))', (x(k(1:end-1)) - x(k(2:end)))'];\n      b = sum(A' .* [x(k(1:end-1)); y(k(1:end-1))], 1)';\n      obj = iris.Polyhedron(A, b);\n    end\n\n    function obj = from2DVerticesAndPlane(vertices, normal, v)\n      assert(size(vertices, 1) == 2);\n      % normal' * [x;y;z] = v;\n      obj = iris.Polyhedron.from2DVertices(vertices);\n      obj.Aeq = reshape(normal, 1, []);\n      obj.beq = v;\n      obj.A = [obj.A, zeros(size(obj.A, 1), 1)];\n    end\n\n    function obj = fromBounds(lb, ub)\n      % create a polyhedron representing a bounding box in n dimensions\n      dim = length(lb);\n      assert(length(lb) == length(ub));\n      A = [eye(dim); -eye(dim)];\n      b = [reshape(ub,[],1); reshape(-lb,[],1)];\n      obj = iris.Polyhedron(A, b);\n    end\n  end\nend\n", "meta": {"author": "rdeits", "repo": "iris-distro", "sha": "ff624610a82a858862d55732136dbc2cc9ab16fc", "save_path": "github-repos/MATLAB/rdeits-iris-distro", "path": "github-repos/MATLAB/rdeits-iris-distro/iris-distro-ff624610a82a858862d55732136dbc2cc9ab16fc/src/matlab/+iris/Polyhedron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5812758581329968}}
{"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%  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  i4_huge = 2147483647;\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, i4_huge );\n\n      if ( seed < 0 ) \n        seed = seed + i4_huge;\n      end \n\n      k = floor ( seed / 127773 );\n\n      seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n      if ( seed < 0 )\n        seed = seed + i4_huge;\n      end\n\n      r(i,j) = seed * 4.656612875E-10;\n\n    end\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8mat_uniform_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853086009863259, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5812653017407541}}
{"text": "function sparse_grid_mixed_unique_index_test ( dim_num, level_max_min, ...\n  level_max_max, rule, alpha, beta, tol )\n\n%*****************************************************************************80\n%\n%  Purpose:\n%\n%    SPARSE_GRID_MIXED_UNIQUE_INDEX_TEST tests SPARSE_GRID_MIXED_UNIQUE_INDEX.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 March 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer DIM_NUM, the spatial dimension.\n%\n%    Input, integer LEVEL_MAX_MIN, LEVEL_MAX_MAX, the minimum and\n%    maximum values of LEVEL_MAX.\n%\n%    Input, integer RULE(DIM_NUM), the rule in each dimension.\n%     1, \"CC\",  Clenshaw Curtis, Closed Fully Nested rule.\n%     2, \"F2\",  Fejer Type 2, Open Fully Nested rule.\n%     3, \"GP\",  Gauss Patterson, Open Fully Nested rule.\n%     4, \"GL\",  Gauss Legendre, Open Weakly Nested rule.\n%     5, \"GH\",  Gauss Hermite, Open Weakly Nested rule.\n%     6, \"GGH\", Generalized Gauss Hermite, Open Weakly Nested rule.\n%     7, \"LG\",  Gauss Laguerre, Open Non Nested rule.\n%     8, \"GLG\", Generalized Gauss Laguerre, Open Non Nested rule.\n%     9, \"GJ\",  Gauss Jacobi, Open Non Nested rule.\n%    10, \"GW\",  Golub Welsch, (presumed) Open Non Nested rule.\n%    11, \"CC_SE\", Clenshaw Curtis Slow Exponential, Closed Fully Nested rule.\n%    12, \"F2_SE\", Fejer Type 2 Slow Exponential, Closed Fully Nested rule.\n%    13, \"GP_SE\", Gauss Patterson Slow Exponential, Closed Fully Nested rule.\n%    14, \"CC_ME\", Clenshaw Curtis Moderate Exponential, Closed Fully Nested rule.\n%    15, \"F2_ME\", Fejer Type 2 Moderate Exponential, Closed Fully Nested rule.\n%    16, \"GP_ME\", Gauss Patterson Moderate Exponential, Closed Fully Nested rule.\n%    17, \"CCN\", Clenshaw Curtis Nested, Linear, Closed Fully Nested rule.\n%\n%    Input, real ALPHA(DIM_NUM), BETA(DIM_NUM), parameters used for\n%    Generalized Gauss Hermite, Generalized Gauss Laguerre, and Gauss Jacobi rules.\n%\n%    Input, real TOL, the tolerance for point equality.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'SPARSE_GRID_MIXED_UNIQUE_INDEX_TEST\\n' );\n  fprintf ( 1, '  SPARSE_GRID_MIXED_UNIQUE_INDEX returns a mapping between\\n' );\n  fprintf ( 1, '  the nonunique and unique points in a sparse grid.\\n' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ' Dimension      Rule     Alpha          Beta\\n' );\n  fprintf ( 1, '\\n' );\n\n  for dim = 1 : dim_num\n    fprintf ( 1, '  %8d  %8d', dim, rule(dim) );\n    if ( rule(dim) == 6 | rule(dim) == 8 | rule(dim) == 9 )\n      fprintf ( 1, '  %12e', alpha(dim) );\n    end\n    if ( rule(dim) == 9 )\n      fprintf ( 1, '  %12e', beta(dim) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n\n  for level_max = level_max_min : level_max_max\n\n    point_total_num = sparse_grid_mixed_size_total ( dim_num, level_max, rule );\n\n    point_num = sparse_grid_mixed_size ( dim_num, level_max, rule, alpha, ...\n      beta, tol );\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, ' LEVEL_MIN LEVEL_MAX POINT_NUM POINT_NUM\\n' );\n    fprintf ( 1, '                        Unique     Total\\n' );\n    fprintf ( 1, '\\n' );\n\n    level_min = max ( 0, level_max + 1 - dim_num );\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  %8d  %8d  %8d  %8d\\n', ...\n      level_min, level_max, point_num, point_total_num );\n\n    sparse_unique_index = sparse_grid_mixed_unique_index ( ...\n      dim_num, level_max, rule, alpha, beta, tol, point_num, point_total_num );\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '     POINT    UNIQUE\\n' );\n    fprintf ( 1, '\\n' );\n    for point = 1 : point_total_num\n      fprintf ( 1, '  %8d  %8d\\n', point, sparse_unique_index(point) );\n    end\n\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_mixed/sparse_grid_mixed_unique_index_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5812652853005841}}
{"text": "function [vert,conn,tria,tnum] = refine2(varargin)\n%REFINE2 (Frontal)-Delaunay-refinement for two-dimensional,\n%polygonal geometries.\n%   [VERT,EDGE,TRIA,TNUM] = REFINE2(NODE,EDGE) returns a co-\n%   nstrained Delaunay triangulation of the polygonal region\n%   {NODE,EDGE}. NODE is an N-by-2 array of polygonal verti-\n%   ces and EDGE is an E-by-2 array of edge indexing. Each\n%   row in EDGE represents an edge of the polygon, such that\n%   NODE(EDGE(JJ,1),:) and NODE(EDGE(JJ,2),:) are the coord-\n%   inates of the endpoints of the JJ-TH edge. If the argum-\n%   ent EDGE is omitted it assumed that the vertices in NODE\n%   are connected in ascending order.\n%\n%   [...] = REFINE2(NODE,EDGE,PART) computes a triangulation\n%   for a multiply-connected geometry. PART is a cell-array\n%   of polygonal \"parts\", where each element PART{KK} is an\n%   array of edge indices defining a given polygonal region.\n%   EDGE(PART{KK}, :) is the set of edges in the KK-TH part.\n%\n%   VERT is a V-by-2 array of XY coordinates in the triangu-\n%   lation, EDGE is an array of constrained edges, TRIA is a\n%   T-by-3 array of triangles, and TNUM is a T-by-1 array of\n%   part indices. Each row of TRIA and EDGE define an eleme-\n%   nt. VERT(TRIA(II,1),:), VERT(TRIA(II,2),:) and VERT(TRIA\n%   (II,3),:) are the coordinates of the II-TH triangle. The\n%   edges in EDGE are defined in a similar manner. NUM is an\n%   array of part indexing, such that TNUM(II) is the index\n%   of the part in which the II-TH triangle resides.\n%\n%   [...] = REFINE2(..., OPTS) passes an additional options\n%   structure OPTS, containing various user-defined paramet-\n%   ers, including:\n%\n% - OPTS.KIND = {'DELFRONT'}, 'DELAUNAY' -- the type of ref-\n%   inement employed. The 'DELFRONT' algorithm is typically\n%   slower, but produces higher quality output.\n%\n% - OPTS.RHO2 = {1.025} -- the maximum allowable radius-edge\n%   ratio. Refinement proceeds until all interior triangles\n%   satisfy the radius-edge threshold. Smaller radius-edge\n%   ratios lead to improved triangle shape, with RHO2=1 req-\n%   uiring that all angles exceed 30 degrees. Setting RHO2<1\n%   may lead to non-convergence.\n%\n% - OPTS.REF1 = {'REFINE'}, 'PRESERVE' -- refinement 'flag'\n%   for 1-dimensional faces (i.e. edges). The 'PRESERVE' op-\n%   tion results in minimal refinement, attempting to retain\n%   the initial edges without further subdivision. Edges are\n%   split only to satisfy basic geomertical conformance.\n%\n% - OPTS.REF2 = {'REFINE'}, 'PRESERVE' -- refinement 'flag'\n%   for 2-dimensional faces (i.e. trias). The 'PRESERVE' op-\n%   tion results in minimal refinement, attempting to retain\n%   the initial trias without further subdivision. Trias are\n%   split only to satisfy basic geomertical conformance.\n%\n% - OPTS.SIZ1 = {1.333} -- the normalised rel.-length th-\n%   reshold for edge-elements. Each exterior edge is refined\n%   until LL/HH<SIZ1, where LL is the edge-length, HH is the\n%   edge-centred mesh-size value.\n%\n% - OPTS.SIZ2 = {1.300} -- the normalised rel.-length th-\n%   reshold for tria-elements. Each interior tria is refined\n%   until RE/HH<SIZ2, where RE is an effective tria length,\n%   based on the circumradius, HH is the tria-centred mesh-\n%   size value.\n%\n% - OPTS.DISP = { +10 } -- refinement verbosity. Set to INF\n%   for quiet execution.\n%\n%   [...] = REFINE2(..., HFUN,ARGS) also passes an optional\n%   mesh-size function argument. Setting HFUN = HMAX, where\n%   HMAX is a scalar value, imposes a constant size constra-\n%   int over the full domain. HFUN can also be defined as a\n%   general function handle [HH] = HFUN(PP), where PP is an\n%   N-by-2 array of XY coordinates and HH is the associated\n%   vector of mesh-size values. User-defined HFUN must be\n%   fully vectorised. Additional arguments {A1,A2,...AN} for\n%   HFUN can be passed as trailing parameters to REFINE2. In\n%   such cases, HFUN must adopt a signature [HH] = HFUN(PP,\n%   A1,A2,...,AN). HFUN must return positive values.\n%\n%   See also SMOOTH2, TRIDIV2, TRICOST, TRIDEMO\n\n%   This routine implements a \"multi-refinement\" variant of\n%   Delaunay-refinement type mesh-generation. Both standard\n%   Delaunay-refinement and Frontal-Delaunay type algorithms\n%   are available. The Frontal-Delaunay approach is a simpl-\n%   ified version of the JIGSAW algorithm, described in:\n%\n% * D. Engwirda, (2014): \"Locally-optimal Delaunay-refineme-\n%   nt and optimisation-based mesh generation\", Ph.D. Thesis\n%   School of Mathematics and Statistics, Univ. of Sydney.\n%   http://hdl.handle.net/2123/13148\n%\n% * D. Engwirda & D. Ivers, (2016): \"Off-centre Steiner poi-\n%   nts for Delaunay-refinement on curved surfaces\", Comput-\n%   er-Aided Design, (72), 157--171.\n%   http://dx.doi.org/10.1016/j.cad.2015.10.007\n\n%   This work is an extension of the \"off-centre\" type tech-\n%   niques introduced in:\n%\n% * H. Erten & A. Ungor, (2009): \"Quality triangulation with\n%   locally optimal Steiner points\", SIAM Journal on Scient-\n%   ific Comp. 31(3), 2103--2130.\n%   http://doi.org/10.1137/080716748\n%\n% * S. Rebay, (1993): \"Efficient Unstructured Mesh Generati-\n%   on by Means of Delaunay Triangulation and Bowyer-Watson\n%   Algorithm, J. Comp. Physics 106(1), 125--138.\n%   http://dx.doi.org/10.1006/jcph.1993.1097\n\n%   Generally speaking, the Delaunay-refinement method impl-\n%   emented here is a variantion of the \"classical\" algorit-\n%   hm introduced in:\n%\n% * J. Ruppert, (1995): \"A Delaunay refinement algorithm for\n%   quality 2-dimensional mesh generation.\" Journal of Algo-\n%   rithms 18(3), 548--585.\n%   http://dx.doi.org/10.1006/jagm.1995.1021\n%\n%   See also: S. Cheng, T. Dey & J. Shewchuk, (2012): \"Dela-\n%   unay mesh generation\", CRC Press, for comprehensive cov-\n%   erage of Delaunay-based meshing techniques.\n\n%   A much more advanced, and fully three-dimensional imple-\n%   mentation is available in the JIGSAW library. For addit-\n%   ional information, see:\n%   https://github.com/dengwirda/jigsaw-matlab\n\n%-----------------------------------------------------------\n%   Darren Engwirda : 2017 --\n%   Email           : de2363@columbia.edu\n%   Last updated    : 13/02/2020\n%-----------------------------------------------------------\n\n    node = []; PSLG = []; part = {}; opts = [] ;\n    hfun = []; harg = {};\n\n%---------------------------------------------- extract args\n    if (nargin>=+1), node = varargin{1}; end\n    if (nargin>=+2), PSLG = varargin{2}; end\n    if (nargin>=+3), part = varargin{3}; end\n    if (nargin>=+4), opts = varargin{4}; end\n    if (nargin>=+5), hfun = varargin{5}; end\n    if (nargin>=+6), harg = varargin(6:end); end\n\n   [opts] = makeopt(opts) ;\n\n%---------------------------------------------- default EDGE\n    nnod = size(node,1) ;\n\n    if (isempty(PSLG))\n        PSLG = [(1:nnod-1)',(2:nnod)'; nnod,1] ;\n    end\n\n%---------------------------------------------- default PART\n    ncon = size(PSLG,1) ;\n\n    if (isempty(part)), part{1} = (1:ncon)'; end\n\n%---------------------------------------------- basic checks\n    if (~isnumeric(node) || ~isnumeric(PSLG) || ...\n        ~iscell   (part) || ~isstruct (opts) )\n        error('refine2:incorrectInputClass' , ...\n            'Incorrect input class.') ;\n    end\n\n%---------------------------------------------- basic checks\n    if (ndims(node) ~= +2 || ndims(PSLG) ~= +2)\n        error('refine2:incorrectDimensions' , ...\n            'Incorrect input dimensions.');\n    end\n    if (size(node,2) < +2 || size(PSLG,2) < +2)\n        error('refine2:incorrectDimensions' , ...\n            'Incorrect input dimensions.');\n    end\n\n%---------------------------------------------- basic checks\n    if (min([PSLG(:)])<+1 || max([PSLG(:)])>nnod)\n        error('refine2:invalidInputs', ...\n            'Invalid EDGE input array.') ;\n    end\n\n    pmin = cellfun(@min,part);\n    pmax = cellfun(@max,part);\n\n    if (min([pmin(:)])<+1 || max([pmax(:)])>ncon)\n        error('refine2:invalidInputs', ...\n            'Invalid PART input array.') ;\n    end\n\n%-------------------------------- prune any non-unique topo.\n   [ivec,ivec,jvec] = ...\n        unique(sort(PSLG,+2),'rows') ;\n\n    PSLG = PSLG(ivec,:) ;\n\n    for ppos = +1:length(part)\n\n        if ( ~isnumeric(part{ppos}) )\n            error (  ...\n            'refine2:incorrectInputClass', ...\n                'Incorrect input class. ') ;\n        end\n\n        part{ppos} = ...\n            unique(jvec(part{ppos})) ;\n\n    end\n\n%-------------------------------- check part \"manifold-ness\"\n    for ppos = +1:length(part)\n\n        eloc = PSLG(part{ppos},:) ;\n        nadj = ...\n            accumarray(eloc(:),1) ;\n\n        if (any(mod(nadj,2) ~= 0) )\n        error('refine2:nonmanifoldInputs', ...\n            'Non-manifold PART detected.') ;\n        end\n\n    end\n\n%---------------------------------------------- output title\n    if (~isinf(opts.disp))\n        fprintf(1,'\\n') ;\n        fprintf(1,' Refine triangulation...\\n') ;\n        fprintf(1,'\\n') ;\n        fprintf(1,[...\n' -------------------------------------------------------\\n', ...\n'      |ITER.|          |CDT1(X)|          |CDT2(X)|     \\n', ...\n' -------------------------------------------------------\\n', ...\n             ] ) ;\n    end\n\n%-------------------------------- PASS 0: inflate box bounds\n    vert = node; tria = []; tnum = []; iter = 0 ;\n    conn = PSLG;\n\n    vmin = min(vert,[],1);      % inflate bbox for stability\n    vmax = max(vert,[],1);\n\n    vdel = vmax - 1.*vmin;\n    vmin = vmin - .5*vdel;\n    vmax = vmax + .5*vdel;\n\n    vbox = [\n        vmin(1), vmin(2)\n        vmax(1), vmin(2)\n        vmax(1), vmax(2)\n        vmin(1), vmax(2)\n           ] ;\n    vert = [vert ; vbox] ;\n\n%-------------------------------- PASS 0: shield sharp feat.\n   [vert,conn,tria,tnum,iter] = ...\n        cdtbal0(vert,conn,tria,tnum, ...\n            node,PSLG,part,opts,hfun,harg,iter);\n\n%-------------------------------- PASS 1: refine 1-simplexes\n   [vert,conn,tria,tnum,iter] = ...\n        cdtref1(vert,conn,tria,tnum, ...\n            node,PSLG,part,opts,hfun,harg,iter);\n\n%-------------------------------- PASS 2: refine 2-simplexes\n   [vert,conn,tria,tnum,iter] = ...\n        cdtref2(vert,conn,tria,tnum, ...\n            node,PSLG,part,opts,hfun,harg,iter);\n\n    if (~isinf(opts.disp)), fprintf(1,'\\n'); end\n\n%-------------------------------- trim extra adjacency info.\n    tria = tria( :,1:3) ;\n\n%-------------------------------- trim vert. - deflate bbox.\n    keep = false(size(vert,1),1);\n    keep(tria(:)) = true;\n    keep(conn(:)) = true;\n\n    redo = zeros(size(vert,1),1);\n    redo(keep) = ...\n        (+1:length(find(keep)))';\n\n    conn = ...\n        reshape(redo(conn),[],2);\n    tria = ...\n        reshape(redo(tria),[],3);\n\n    vert = vert(keep,:) ;\n\nend\n\nfunction [vert,conn,tria,tnum,iter] = ...\n            cdtbal0(vert,conn,tria,tnum, ...\n                node,PSLG,part,opts,hfun,harg,iter)\n%CDTBAL0 constrained Delaunay-refinement for \"sharp\" 0-dim.\n%features at PSLG vertices.\n%   [...] = CDTBAL0(...) refines the set of 1-simplex eleme-\n%   nts incident to \"sharp\" features in the PSLG. Specifica-\n%   lly, edges that subtend \"small\" angles are split about a\n%   set of new \"collar\" vertices, equi-distributed about the\n%   centre of \"sharp\" features. Collar size is computed as a\n%   min. of the incident edge-len. and local mesh-size cons-\n%   traints.\n\n    if (iter <= opts.iter)\n\n    %------------------------------------- build current CDT\n       [vert,conn, ...\n        tria,tnum] = deltri2(vert,conn, ...\n                             node,PSLG, ...\n                             part, ...\n                             opts.dtri) ;\n\n    %------------------------------------- build current adj\n       [edge,tria] = tricon2(tria,conn) ;\n\n       [feat,ftri] = isfeat2(vert, ...\n                             edge,tria) ;\n\n        apex = false(size(vert,1), 1) ;\n        apex(tria(ftri)) =  true ;\n\n    %------------------------------------- eval. length-fun.\n        if (~isempty(hfun))\n            if (isnumeric(hfun))\n            vlen = hfun * ...\n              ones(size(vert,1),1) ;\n            else\n            vlen = feval( ...\n                hfun,vert,harg{:}) ;\n            vlen = vlen(:) ;\n            end\n        else\n            vlen = +inf * ...\n              ones(size(vert,1),1) ;\n        end\n\n    %------------------------------------- form edge vectors\n        evec = vert(conn(:,2),:) ...\n             - vert(conn(:,1),:) ;\n        elen = sqrt(sum(evec.^2,2));\n        evec = evec./[elen,elen] ;\n\n    %------------------------------------- min. adj. lengths\n        for epos = +1 : size(conn,1)\n\n            ivrt = conn(epos,1) ;\n            jvrt = conn(epos,2) ;\n\n            vlen(ivrt) = min( ...\n            vlen(ivrt), .67*elen(epos)) ;\n            vlen(jvrt) = min( ...\n            vlen(jvrt), .67*elen(epos)) ;\n\n        end\n\n    %------------------------------------- mark feature edge\n        iref = apex(conn(:,1)) ...      %- refine at vert. 1\n            & ~apex(conn(:,2)) ;\n        jref = apex(conn(:,2)) ...      %- refine at vert. 2\n            & ~apex(conn(:,1)) ;\n        dref = apex(conn(:,1)) ...      %- refine at both!\n            &  apex(conn(:,2)) ;\n\n        keep =~apex(conn(:,1)) ...      %- refine at neither\n            & ~apex(conn(:,2)) ;\n\n    %------------------------------------- protecting collar\n        ilen = vlen(conn(iref,1)) ;\n        inew = vert(conn(iref,1),:) ...\n        + [ilen,ilen].*evec(iref,:) ;\n\n        jlen = vlen(conn(jref,2)) ;\n        jnew = vert(conn(jref,2),:) ...\n        - [jlen,jlen].*evec(jref,:) ;\n\n        Ilen = vlen(conn(dref,1)) ;\n        Inew = vert(conn(dref,1),:) ...\n        + [Ilen,Ilen].*evec(dref,:) ;\n\n        Jlen = vlen(conn(dref,2)) ;\n        Jnew = vert(conn(dref,2),:) ...\n        - [Jlen,Jlen].*evec(dref,:) ;\n\n        vnew = [inew; jnew; Inew; Jnew] ;\n\n    %------------------------------------- add new vert/edge\n        iset = (1:size(inew,1))' ...\n                + size(vert,1) ;\n\n        jset = (1:size(jnew,1))' ...\n                + size(inew,1) + ...\n                + size(vert,1) ;\n\n        Iset = (1:size(Inew,1))' ...\n                + size(inew,1) + ...\n                + size(jnew,1) + ...\n                + size(vert,1) ;\n\n        Jset = (1:size(Jnew,1))' ...\n                + size(inew,1) + ...\n                + size(jnew,1) + ...\n                + size(Inew,1) + ...\n                + size(vert,1) ;\n\n        vert = [vert ; vnew] ;\n\n        cnew = [conn(iref,1), iset ;\n                conn(iref,2), iset ;\n                conn(jref,2), jset ;\n                conn(jref,1), jset ;\n                conn(dref,1), Iset ;\n                conn(dref,2), Jset ;\n                Iset, Jset] ;\n        conn = [conn(keep,:); cnew ] ;\n\n    end\n\nend\n\nfunction [vert,conn,tria,tnum,iter] = ...\n            cdtref1(vert,conn,tria,tnum, ...\n                node,PSLG,part,opts,hfun,harg,iter)\n%CDTREF1 constrained Delaunay-refinement for 1-simplex elem-\n%nts embedded in R^2.\n%   [...] = CDTREF1(...) refines the set of 1-simplex eleme-\n%   nts embedded in the triangulation until all constraints\n%   are satisfied. Specifically, edges are refined until all\n%   local mesh-spacing and encroachment conditions are met.\n%   Refinement proceeds according to either a Delaunay-refi-\n%   nement or Frontal-Delaunay type approach, depending on\n%   user-settings. In either case, new steiner vertices are\n%   introduced to split \"bad\" edges - those that violate the\n%   set of prescribed constraints. In the \"-DR\" type process\n%   edges are split about their circumballs (midpoints). In\n%   the \"-FD\" approach, new vertices are positioned such th-\n%   at mesh-spacing constraints are satisfied in a \"locally-\n%   optimal\" fashion.\n\n    tcpu.full = +0. ;\n    tcpu.ball = +0. ;\n    tcpu.hfun = +0. ;\n    tcpu.encr = +0. ;\n    tcpu.offc = +0. ;\n\n    vidx = (1:size(vert,1))';     %- \"new\" vert list to test\n\n    tnow =  tic ;\n\n    ntol = +1.55;\n\n    while (strcmpi(opts.ref1,'refine'))\n\n        iter = iter + 1 ;\n\n        if (iter>=opts.iter),break; end\n\n    %------------------------------------- calc. circumballs\n        ttic = tic ;\n\n        bal1 = cdtbal1(vert,conn) ;\n\n        tcpu.ball = ...\n            tcpu.ball + toc(ttic) ;\n\n    %------------------------------------- eval. length-fun.\n        ttic = tic ;\n\n        if (~isempty(hfun))\n            if (isnumeric(hfun))\n            fun0 = hfun * ...\n              ones(size(vert,1),1);\n            fun1 = hfun ;\n            else\n            fun0(vidx) = ...\n                feval(hfun, ...\n            vert(vidx,:), harg{:});\n            fun0 = fun0(:) ;\n            fun1 = fun0(conn(:,1))...\n                 + fun0(conn(:,2));\n            fun1 = fun1 / +2. ;\n            end\n        else\n            fun0 = +inf * ...\n              ones(size(vert,1),1);\n            fun1 = +inf ;\n        end\n\n        siz1 = ...\n         +4. * bal1(:,3)./(fun1.*fun1) ;\n\n        tcpu.hfun = ...\n            tcpu.hfun + toc(ttic) ;\n\n    %------------------------------------- test encroachment\n        ttic = tic ;\n\n        bal1(:,3) = ...\n            (1.-eps^.75) * bal1(:,3) ;\n\n       [vp,vi] = ...\n           findball(bal1,vert(:,1:2));\n\n    %------------------------------------- near=>[vert,edge]\n        next = +0;\n        ebad = false(size(conn,1),1) ;\n        near = zeros(size(conn,1),1) ;\n        for ii = +1 : size(vp,1)\n            for ip = vp(ii,1):vp(ii,2)\n                jj = vi(ip);\n                if (ii ~= conn(jj,1) ...\n                &&  ii ~= conn(jj,2) )\n                next = next + 1;\n                near(next,1) = ii;\n                near(next,2) = jj;\n                end\n            end\n        end\n\n        near = near(1:next-0,:);\n\n        if (~isempty(near))\n    %-- mark edge \"encroached\" if there is a vert within its\n    %-- dia.-ball that is not joined to either of its vert's\n    %-- via an existing edge...\n            ivrt = conn(near(:,2),1);\n            jvrt = conn(near(:,2),2);\n\n            pair = [near(:,1), ivrt];\n            ivec = setset2(pair,conn) ;\n\n            pair = [near(:,1), jvrt];\n            jvec = setset2(pair,conn) ;\n\n            okay = ~ivec & ~jvec ;\n\n            ebad(near(okay,2))=true ;\n\n        end\n\n        tcpu.encr = ...\n            tcpu.encr + toc(ttic);\n\n    %------------------------------------- refinement queues\n        ref1 = false(size(conn,1),1);\n        ref1(ebad)           = true ;   %- edge encroachment\n        ref1(siz1>opts.siz1* ...        %- bad equiv. length\n                  opts.siz1) = true ;\n\n        num1 = find(ref1)  ;\n\n    %------------------------------------- dump-out progess!\n        if (mod(iter,opts.disp)==0)\n            numc = size(conn,1) ;\n            numt = size(tria,1) ;\n            fprintf(+1, ...\n            '%11i %18i %18i\\n', ...\n            [iter,numc,numt]) ;\n        end\n\n    %------------------------------------- nothing to refine\n        if (isempty(num1)), break; end\n\n    %------------------------------------- refine \"bad\" tria\n        switch (lower(opts.kind))\n        case 'delaunay'\n    %------------------------------------- do circ-ball pt's\n        new1 = bal1(ref1, 1:2) ;\n\n        vidx = (1:size(new1,1))' ...\n                + size(vert,1) ;\n\n        cnew = [conn( ref1,1), vidx\n                conn( ref1,2), vidx];\n        conn = [conn(~ref1,:); cnew];\n\n    %------------------------------------- update vertex set\n        vert = [vert; new1(:,1:2)];\n\n\n        case 'delfront'\n    %-- symmetric off-centre scheme:- refine edges from both\n    %-- ends simultaneously, placing new vertices to satisfy\n    %-- the worst of mesh-spacing and local voronoi constra-\n    %-- ints.\n\n        ttic = tic ;\n\n        evec = vert(conn(ref1,2),:) ...\n             - vert(conn(ref1,1),:) ;\n        elen = sqrt(sum(evec.^2,2)) ;\n        evec = evec ./ [elen, elen] ;\n\n    %------------------------------------- \"voro\"-type dist.\n        vlen = sqrt(bal1(ref1,3));\n\n    %------------------------------------- \"size\"-type dist.\n        ihfn = fun0(conn(ref1,1));\n        jhfn = fun0(conn(ref1,2));\n\n    %------------------------------------- bind \"safe\" dist.\n        ilen = min(vlen,ihfn) ;\n        jlen = min(vlen,jhfn) ;\n\n    %------------------------------------- locate offcentres\n        inew = vert(conn(ref1,1),:) ...\n             + [ilen,ilen].*evec ;\n        jnew = vert(conn(ref1,2),:) ...\n             - [jlen,jlen].*evec ;\n\n    %------------------------------------- iter. \"size\"-type\n        for ioff = +1 : +3\n    %------------------------------------- eval. length-fun.\n        if (~isempty(hfun))\n            if (isnumeric(hfun))\n            iprj = hfun * ...\n              ones(size(inew,1),1);\n            jprj = hfun * ...\n              ones(size(jnew,1),1);\n            else\n            iprj = feval( ...\n                hfun,inew,harg{:});\n            jprj = feval( ...\n                hfun,jnew,harg{:});\n            iprj = iprj(:);\n            jprj = jprj(:);\n            end\n        else\n            iprj = +inf * ...\n              ones(size(inew,1),1);\n            jprj = +inf * ...\n              ones(size(jnew,1),1);\n        end\n\n        iprj = 0.5*ihfn + 0.5*iprj;\n        jprj = 0.5*jhfn + 0.5*jprj;\n\n    %------------------------------------- bind \"safe\" dist.\n        ilen = min(vlen,iprj) ;\n        jlen = min(vlen,jprj) ;\n\n    %------------------------------------- locate offcentres\n        inew = vert(conn(ref1,1),:) ...\n             + [ilen,ilen].*evec ;\n        jnew = vert(conn(ref1,2),:) ...\n             - [jlen,jlen].*evec ;\n\n        end\n\n    %------------------------------------- merge i,j if near\n        near = ...\n            ilen+jlen>=vlen*ntol ;\n\n        znew = inew(near,:) * .5 ...\n             + jnew(near,:) * .5 ;\n\n        inew = inew(~near,1:2) ;\n        jnew = jnew(~near,1:2) ;\n\n    %------------------------------------- split constraints\n        zset = (1:size(znew,1))' ...\n                + size(vert,1) ;\n\n        iset = (1:size(inew,1))' ...\n                + size(znew,1) + ...\n                + size(vert,1) ;\n\n        jset = (1:size(jnew,1))' ...\n                + size(znew,1) + ...\n                + size(inew,1) + ...\n                + size(vert,1) ;\n\n        set1 = num1( near);\n        set2 = num1(~near);\n\n        cnew = [conn( set1,1), zset\n                conn( set1,2), zset\n                conn( set2,1), iset\n                conn( set2,2), jset\n                iset, jset ] ;\n        conn = [conn(~ref1,:); cnew];\n\n    %------------------------------------- update vertex set\n        vert = [vert; znew(:,1:2)];\n        vert = [vert; inew(:,1:2)];\n        vert = [vert; jnew(:,1:2)];\n\n        vidx = [zset; iset; jset] ;\n\n        tcpu.offc = ...\n            tcpu.offc + toc(ttic) ;\n\n\n        end % switch(lower(opts.kind))\n\n    end\n\n    tcpu.full = ...\n        tcpu.full + toc(tnow) ;\n\n    if (~isinf(opts.disp) )\n    %------------------------------------- print final stats\n        numc = size(conn,1) ;\n        numt = size(tria,1) ;\n        fprintf(+1, ...\n        '%11i %18i %18i\\n', ...\n        [iter,numc,numt]) ;\n    end\n\n    if (opts.dbug)\n    %------------------------------------- print debug timer\n        fprintf(1,'\\n') ;\n        fprintf(1,' 1-simplex REF. timer...\\n');\n        fprintf(1,'\\n') ;\n        fprintf(1, ...\n        ' FULL: %f \\n', tcpu.full);\n        fprintf(1, ...\n        ' BALL: %f \\n', tcpu.ball);\n        fprintf(1, ...\n        ' HFUN: %f \\n', tcpu.hfun);\n        fprintf(1, ...\n        ' ENCR: %f \\n', tcpu.encr);\n        fprintf(1, ...\n        ' OFFC: %f \\n', tcpu.offc);\n        fprintf(1,'\\n') ;\n    end\n\nend\n\nfunction [vert,conn,tria,tnum,iter] = ...\n            cdtref2(vert,conn,tria,tnum, ...\n                node,PSLG,part,opts,hfun,harg,iter)\n%CDTREF2 constrained Delaunay-refinement for 2-simplex elem-\n%nts embedded in R^2.\n%   [...] = CDTREF2(...) refines the set of 2-simplex eleme-\n%   nts embedded in the triangulation until all constraints\n%   are satisfied. Specifically, triangles are refined until\n%   all local mesh-spacing and element-shape conditions are\n%   met. Refinement proceeds according to either a Delaunay-\n%   refinement or Frontal-Delaunay type approach, depending\n%   on user-settings. In either case, new steiner points are\n%   introduced to split \"bad\" triangles - those that violate\n%   the set of prescribed constraints. In the \"-DR\" type pr-\n%   ocess triangles are split about their circumballs. In\n%   the \"-FD\" approach, new vertices are positioned such th-\n%   at mesh-spacing and element-shape constraints are satis-\n%   fied in a \"locally-optimal\" fashion.\n\n    tcpu.full = +0. ;\n    tcpu.dtri = +0. ;\n    tcpu.tcon = +0. ;\n    tcpu.ball = +0. ;\n    tcpu.hfun = +0. ;\n    tcpu.offc = +0. ;\n    tcpu.filt = +0. ;\n\n    vidx = (1:size(vert,1))';     %- \"new\" vert list to test\n\n    tnow =  tic ;\n\n    near = +.775;\n\n    while (strcmpi(opts.ref2,'refine'))\n\n        iter = iter + 1 ;\n\n    %------------------------------------- build current CDT\n        ttic = tic ;\n\n        nold = size(vert,1) ;\n\n       [vert,conn, ...\n        tria,tnum]= deltri2(vert,conn, ...\n                            node,PSLG, ...\n                            part, ....\n                            opts.dtri) ;\n\n        nnew = size(vert,1) ;\n\n        vidx = ...\n       [vidx; (nold:nnew)'] ;\n\n        tcpu.dtri = ...\n            tcpu.dtri + toc(ttic) ;\n\n    %------------------------------------- build current adj\n        ttic = tic ;\n\n       [edge,tria]= tricon2(tria,conn) ;\n\n        tcpu.tcon = ...\n            tcpu.tcon + toc(ttic) ;\n\n        if (iter>=opts.iter),break; end\n\n    %------------------------------------- calc. circumballs\n        ttic = tic ;\n\n        bal1 = cdtbal1(vert,conn) ;\n        bal2 = cdtbal2(vert, ...\n                       edge,tria) ;\n        len2 = minlen2(vert,tria) ;\n\n        rho2 = bal2(:,+3) ./ len2 ;\n\n    %------------------------------------- refinement scores\n        scr2 = rho2 .* bal2(:,+3) ;\n\n        tcpu.ball = ...\n            tcpu.ball + toc(ttic) ;\n\n    %------------------------------------- eval. length-fun.\n        ttic = tic ;\n\n        if (~isempty(hfun))\n            if (isnumeric(hfun))\n            fun0 = hfun * ...\n              ones(size(vert,1),1);\n            fun2 = hfun ;\n            else\n            fun0(vidx) = ...\n                feval(hfun, ...\n            vert(vidx,:), harg{:});\n            fun0 = fun0(:) ;\n            fun2 = fun0(tria(:,1))...\n                 + fun0(tria(:,2))...\n                 + fun0(tria(:,3));\n            fun2 = fun2 / +3. ;\n            end\n        else\n            fun0 = +inf * ...\n              ones(size(vert,1),1);\n            fun2 = +inf ;\n        end\n\n        siz2 = ...\n         +3. * bal2(:,3)./(fun2.*fun2) ;\n\n        tcpu.hfun = ...\n            tcpu.hfun + toc(ttic) ;\n\n    %------------------------------------- refinement queues\n        ref1 = false(size(conn,1),1);\n        ref2 = false(size(tria,1),1);\n\n        stri = isfeat2(vert,edge,tria) ;\n\n        ref2(rho2>opts.rho2* ...        %- bad rad-edge len.\n                  opts.rho2) = true ;\n        ref2(stri) = false ;\n        ref2(siz2>opts.siz2* ...        %- bad equiv. length\n                  opts.siz2) = true ;\n\n        num2 = find(ref2);\n\n    %------------------------------------- dump-out progess!\n        if (mod(iter,opts.disp)==0)\n            numc = size(conn,1) ;\n            numt = size(tria,1) ;\n            fprintf(+1, ...\n            '%11i %18i %18i\\n', ...\n            [iter,numc,numt]) ;\n        end\n\n    %------------------------------------- nothing to refine\n        if (isempty(num2)), break; end\n\n       [scr2,idx2] = sort( ...\n            scr2(num2),'descend');\n        num2 = num2(idx2);\n\n    %------------------------------------- refine \"bad\" tria\n        switch (lower(opts.kind))\n        case 'delaunay'\n    %------------------------------------- do circ-ball pt's\n        new2 = zeros(length(num2),3);\n        new2(:,1:2) = bal2(num2,1:2);\n\n        rmin = ...                      %- min. insert radii\n            len2(num2)*(1.-eps^.75)^2 ;\n\n        new2(:,  3) = max( ...\n            bal2(num2,3)*near^2,rmin) ;\n\n\n        case 'delfront'\n    %-- off-centre scheme -- refine triangles by positioning\n    %-- new vertices along a local segment of the voronoi\n    %-- diagram, bounded by assoc. circmballs. New points\n    %-- are placed to satisfy the worst of local mesh-length\n    %-- and element-shape constraints.\n\n        ttic = tic ;\n\n    %------------------------------------- find frontal edge\n       [lmin,emin] = ...\n            minlen2(vert,tria(num2,:)) ;\n\n        ftri = false(length(num2),1) ;\n        epos = zeros(length(num2),1) ;\n        tadj = zeros(length(num2),1) ;\n\n        for ii = +1 : length(epos)\n            epos(ii) = tria( ...\n                num2(ii),emin(ii)+3) ;\n        end\n\n    %------------------------------------- find frontal tria\n        for enum = +1 : +3\n\n            eidx = tria(num2,enum+3) ;\n\n            ftri = ...\n            ftri | edge(eidx,5) > +0 ;\n\n            ione = ...\n                num2 ~= edge(eidx,3) ;\n            itwo = ~ione ;\n\n            tadj(ione) = ...\n                edge(eidx(ione),3);\n            tadj(itwo) = ...\n                edge(eidx(itwo),4);\n\n            okay = tadj > +0 ;\n            tidx = tadj(okay);\n\n            ftri(okay) = ...\n            ftri(okay) | ~ref2(tidx) ;\n\n        end\n\n        if (~any(ftri))                 %- can this happen!?\n        ftri = true(length(num2),+1) ;\n        end\n\n    %------------------------------------- locate offcentres\n        emid = vert(edge(epos,+1),:) ...\n             + vert(edge(epos,+2),:) ;\n        emid = emid * +0.50 ;\n\n        elen = sqrt(lmin(:));\n\n    %------------------------------------- \"voro\"-type dist.\n        vvec = bal2(num2,1:2)-emid ;\n        vlen = sqrt(sum(vvec.^2,2));\n        vvec = vvec ./ [vlen,vlen] ;\n\n        hmid = fun0(edge(epos,+1),:) ...\n             + fun0(edge(epos,+2),:) ;\n        hmid = hmid * +0.50 ;\n\n    %------------------------------------- \"ball\"-type dist.\n        rtri = elen * opts.off2 ;\n        rfac = elen * +0.50 ;\n        dsqr = rtri.^2 - rfac.^2;\n        doff = rtri + ...\n            sqrt(max(+0.,dsqr)) ;\n\n    %------------------------------------- \"size\"-type dist.\n        dsiz = +sqrt(3.)/2. * hmid ;\n\n    %------------------------------------- bind \"safe\" dist.\n       [dist,ioff] = ...\n          min([dsiz,doff,vlen],[],2) ;\n\n    %------------------------------------- locate offcentres\n        off2 = ...\n        emid + [dist,dist] .* vvec ;\n\n    %------------------------------------- iter. \"size\"-type\n        for isub = +1 : +3\n    %------------------------------------- eval. length-fun.\n        if (~isempty(hfun))\n            if (isnumeric(hfun))\n            hprj = hfun * ...\n              ones(size(off2,1),1) ;\n            else\n            hprj = feval( ...\n                hfun,off2,harg{:}) ;\n            hprj = hprj(:) ;\n            end\n        else\n            hprj = +inf * ...\n              ones(size(off2,1),1) ;\n        end\n\n    %------------------------------------- \"size\"-type dist.\n        hprj = .33*hmid + .67*hprj ;\n\n        dsiz = +sqrt(3.)/2. * hprj ;\n\n        dsiz(dsiz<elen*.50) = +inf ;    %- edge-ball limiter\n        dsiz(dsiz>vlen*.95) = +inf ;    %- circ-ball limiter\n\n    %------------------------------------- bind \"safe\" dist.\n       [dist,ioff] = ...\n          min([dsiz,doff,vlen],[],2) ;\n\n    %------------------------------------- locate offcentres\n        off2 = ...\n        emid + [dist,dist] .* vvec ;\n\n        end\n\n        orad = ...\n        sqrt((elen*.5).^2 + dist.^2) ;\n\n    %------------------------------------- do offcentre pt's\n        new2 = ...\n        zeros(length(find(ftri)),+3) ;\n        new2(:,1:2) = off2(ftri,1:2) ;\n\n        rmin = ...                      %- min. insert radii\n            lmin(ftri)*(1.-eps^.75)^2 ;\n\n        new2(:,  3) = max( ...\n            (orad(ftri)*near).^2,rmin);\n\n        tcpu.offc = ...\n            tcpu.offc + toc (ttic) ;\n\n\n        end % switch(lower(opts.kind))\n\n    %------------------------------------- inter.-ball dist.\n        ttic = tic ;\n\n    %------------------------------------- proximity filters\n       [vp,vi] = ...\n          findball(new2,new2(:,1:2)) ;\n\n        keep = true (size(new2,1),1) ;\n        for ii = size(vp,1):-1:+1\n            for ip = vp(ii,1) ...\n                   : vp(ii,2)\n                jj = vi(ip);\n                if (keep(jj) && ...\n                    keep(ii) && ...\n                    jj < ii )\n\n                keep(ii) = false ;\n                break;\n\n                end\n            end\n        end\n\n        new2 = new2(keep,:);\n\n    %------------------------------------- test encroachment\n        bal1(:,3) = ...\n            (1.-eps^.75) * bal1(:,3);\n\n       [vp,vi] = ...\n          findball(bal1,new2(:,1:2));\n\n        keep = true (size(new2,1),1);\n        for ii = +1:+1:size(vp,1)\n            for ip = vp(ii,1) ...\n                   : vp(ii,2)\n                jj = vi(ip);\n                ref1(jj) =  true ;\n                keep(ii) = false ;\n            end\n        end\n\n    %------------------------------------- leave sharp edges\n        ebnd = false(size(edge,1),1);\n        ebnd(tria(stri,4:6)) = true ;\n\n        enot = ...\n        setset2(conn,edge(ebnd,1:2));\n\n        ref1(enot) = false ;\n\n    %------------------------------------- preserve boundary\n        if (strcmp(lower(opts.ref1),...\n            'preserve'))\n        ref1(:)    = false ;\n        end\n\n    %------------------------------------- refinement points\n        new2 = new2(keep,:);\n        new1 = bal1(ref1,:);\n\n        tcpu.filt = ...\n            tcpu.filt + toc(ttic) ;\n\n    %------------------------------------- split constraints\n        idx1 = ...\n       (1:size(new1))'+size(vert,1) ;\n\n        idx2 = ...\n       (1:size(new2))'+size(new1,1) ...\n                      +size(vert,1) ;\n\n        cnew = [conn( ref1,1), idx1\n                conn( ref1,2), idx1];\n        conn = [conn(~ref1,:); cnew];\n\n        vidx = [idx1; idx2];\n\n    %------------------------------------- update vertex set\n        nold = size(vert,1);\n        vert = [vert; new1(:,1:2)];\n        vert = [vert; new2(:,1:2)];\n        nnew = size(vert,1);\n\n        if (nnew == nold), break; end   %- we *must* be done\n\n    end\n\n    tcpu.full = ...\n        tcpu.full + toc(tnow) ;\n\n    if (~isinf(opts.disp) )\n    %------------------------------------- print final stats\n        numc = size(conn,1) ;\n        numt = size(tria,1) ;\n        fprintf(+1, ...\n        '%11i %18i %18i\\n', ...\n        [iter,numc,numt]) ;\n    end\n\n    if (opts.dbug)\n    %------------------------------------- print debug timer\n        fprintf(1,'\\n') ;\n        fprintf(1,' 2-simplex REF. timer...\\n');\n        fprintf(1,'\\n') ;\n        fprintf(1, ...\n        ' FULL: %f \\n', tcpu.full);\n        fprintf(1, ...\n        ' DTRI: %f \\n', tcpu.dtri);\n        fprintf(1, ...\n        ' TCON: %f \\n', tcpu.tcon);\n        fprintf(1, ...\n        ' BALL: %f \\n', tcpu.ball);\n        fprintf(1, ...\n        ' HFUN: %f \\n', tcpu.hfun);\n        fprintf(1, ...\n        ' OFFC: %f \\n', tcpu.offc);\n        fprintf(1, ...\n        ' FILT: %f \\n', tcpu.filt);\n        fprintf(1,'\\n') ;\n    end\n\nend\n\nfunction [opts] = makeopt(opts)\n%MAKEOPT setup the options structure for REFINE2.\n\n    if (~isfield(opts,'dtri'))\n        opts.dtri = 'constrained';\n    else\n    if (~strcmpi(opts.dtri, 'conforming') && ...\n        ~strcmpi(opts.dtri,'constrained') )\n        error( ...\n    'refine2:invalidOption','Invalid constraint DTRI.');\n    end\n    end\n\n    if (~isfield(opts,'kind'))\n        opts.kind = 'delfront';\n    else\n    if (~strcmpi(opts.kind, 'delfront') && ...\n        ~strcmpi(opts.kind, 'delaunay') )\n        error( ...\n    'refine2:invalidOption','Invalid refinement KIND.');\n    end\n    end\n\n    if (~isfield(opts,'ref1'))\n        opts.ref1 = 'refine';\n    else\n    if (~strcmpi(opts.ref1,   'refine') && ...\n        ~strcmpi(opts.ref1, 'preserve') )\n        error( ...\n    'refine2:invalidOption','Invalid refinement REF1.');\n    end\n    end\n\n    if (~isfield(opts,'ref2'))\n        opts.ref2 = 'refine';\n    else\n    if (~strcmpi(opts.ref2,   'refine') && ...\n        ~strcmpi(opts.ref2, 'preserve') )\n        error( ...\n    'refine2:invalidOption','Invalid refinement REF2.');\n    end\n    end\n\n    if (~isfield(opts,'iter'))\n        opts.iter = +inf;\n    else\n    if (~isnumeric(opts.iter))\n        error('refine2:incorrectInputClass', ...\n            'Incorrect input class.');\n    end\n    if (numel(opts.iter)~= +1)\n        error('refine2:incorrectDimensions', ...\n            'Incorrect input dimensions.') ;\n    end\n    if (opts.iter <= +0)\n        error('refine2:invalidOptionValues', ...\n            'Invalid OPT.ITER selection.') ;\n    end\n    end\n\n    if (~isfield(opts,'disp'))\n        opts.disp = +10 ;\n    else\n    if (~isnumeric(opts.disp))\n        error('refine2:incorrectInputClass', ...\n            'Incorrect input class.');\n    end\n    if (numel(opts.disp)~= +1)\n        error('refine2:incorrectDimensions', ...\n            'Incorrect input dimensions.') ;\n    end\n    if (opts.disp <= +0)\n        error('refine2:invalidOptionValues', ...\n            'Invalid OPT.DISP selection.') ;\n    end\n    end\n\n    if (~isfield(opts,'rho2'))\n        opts.rho2 = 1.025;\n    else\n    if (~isnumeric(opts.rho2))\n        error('refine2:incorrectInputClass', ...\n            'Incorrect input class.');\n    end\n    if (numel(opts.rho2)~= +1)\n        error('refine2:incorrectDimensions', ...\n            'Incorrect input dimensions.') ;\n    end\n    if (opts.rho2 < +1.)\n        error('refine2:invalidOptionValues', ...\n            'Invalid OPT.RHO2 selection.') ;\n    end\n    end\n\n    if (~isfield(opts,'off2'))\n        opts.off2 = 0.933;\n    else\n    if (~isnumeric(opts.off2))\n        error('refine2:incorrectInputClass', ...\n            'Incorrect input class.');\n    end\n    if (numel(opts.off2)~= +1)\n        error('refine2:incorrectDimensions', ...\n            'Incorrect input dimensions.') ;\n    end\n    if (opts.off2 < +.7)\n        error('refine2:invalidOptionValues', ...\n            'Invalid OPT.OFF2 selection.') ;\n    end\n    end\n\n    if (~isfield(opts,'siz1'))\n        opts.siz1 = 1.333;\n    else\n    if (~isnumeric(opts.siz1))\n        error('refine2:incorrectInputClass', ...\n            'Incorrect input class.');\n    end\n    if (numel(opts.siz1)~= +1)\n        error('refine2:incorrectDimensions', ...\n            'Incorrect input dimensions.') ;\n    end\n    if (opts.siz1 <= 0.)\n        error('refine2:invalidOptionValues', ...\n            'Invalid OPT.SIZ1 selection.') ;\n    end\n    end\n\n    if (~isfield(opts,'siz2'))\n        opts.siz2 = 1.300;\n    else\n    if (~isnumeric(opts.siz2))\n        error('refine2:incorrectInputClass', ...\n            'Incorrect input class.');\n    end\n    if (numel(opts.siz2)~= +1)\n        error('refine2:incorrectDimensions', ...\n            'Incorrect input dimensions.') ;\n    end\n    if (opts.siz2 <= 0.)\n        error('refine2:invalidOptionValues', ...\n            'Invalid OPT.SIZ2 selection.') ;\n    end\n    end\n\n    if (~isfield(opts,'dbug'))\n        opts.dbug = false;\n    else\n    if (~islogical(opts.dbug))\n        error('refine2:incorrectInputClass', ...\n            'Incorrect input class.');\n    end\n    if (numel(opts.dbug)~= +1)\n        error('refine2:incorrectDimensions', ...\n            'Incorrect input dimensions.') ;\n    end\n    end\n\nend\n\n\n\n", "meta": {"author": "dengwirda", "repo": "mesh2d", "sha": "749a81073facc8b5db02e4f7bb0b10c9783cebd3", "save_path": "github-repos/MATLAB/dengwirda-mesh2d", "path": "github-repos/MATLAB/dengwirda-mesh2d/mesh2d-749a81073facc8b5db02e4f7bb0b10c9783cebd3/refine2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.581265276298636}}
{"text": "function hh = errorbar2(x, y, l,u,symbol)\n%ERRORBAR Error bar plot.\n%   ERRORBAR(X,Y,L,U) plots the graph of vector X vs. vector Y with\n%   error bars specified by the vectors L and U.  L and U contain the\n%   lower and upper error ranges for each point in Y.  Each error bar\n%   is L(i) + U(i) long and is drawn a distance of U(i) above and L(i)\n%   below the points in (X,Y).  The vectors X,Y,L and U must all be\n%   the same length.  If X,Y,L and U are matrices then each column\n%   produces a separate line.\n%\n%   ERRORBAR(X,Y,E) or ERRORBAR(Y,E) plots Y with error bars [Y-E Y+E].\n%   ERRORBAR(...,'LineSpec') uses the color and linestyle specified by\n%   the string 'LineSpec'.  See PLOT for possibilities.\n%\n%   H = ERRORBAR(...) returns a vector of line handles.\n%\n%   For example,\n%      x = 1:10;\n%      y = sin(x);\n%      e = std(y)*ones(size(x));\n%      errorbar(x,y,e)\n%   draws symmetric error bars of unit standard deviation.\n\n%   L. Shure 5-17-88, 10-1-91 B.A. Jones 4-5-93\n%   Copyright 1984-2000 The MathWorks, Inc. \n%   $Revision: 1.1 $  $Date: 2003/05/12 22:36:15 $\n\nif min(size(x))==1,\n  npt = length(x);\n  x = x(:);\n  y = y(:);\n    if nargin > 2,\n        if ~isstr(l),  \n            l = l(:);\n        end\n        if nargin > 3\n            if ~isstr(u)\n                u = u(:);\n            end\n        end\n    end\nelse\n  [npt,n] = size(x);\nend\n\nif nargin == 3\n    if ~isstr(l)  \n        u = l;\n        symbol = '-';\n    else\n        symbol = l;\n        l = y;\n        u = y;\n        y = x;\n        [m,n] = size(y);\n        x(:) = (1:npt)'*ones(1,n);;\n    end\nend\n\nif nargin == 4\n    if isstr(u),    \n        symbol = u;\n        u = l;\n    else\n        symbol = '-';\n    end\nend\n\n\nif nargin == 2\n    l = y;\n    u = y;\n    y = x;\n    [m,n] = size(y);\n    x(:) = (1:npt)'*ones(1,n);;\n    symbol = '-';\nend\n\nu = abs(u);\nl = abs(l);\n    \nif isstr(x) | isstr(y) | isstr(u) | isstr(l)\n    error('Arguments must be numeric.')\nend\n\nif ~isequal(size(x),size(y)) | ~isequal(size(x),size(l)) | ~isequal(size(x),size(u)),\n  error('The sizes of X, Y, L and U must be the same.');\nend\n\ntee = (max(x(:))-min(x(:)))/100;  % make tee .02 x-distance for error bars\nxl = x - tee;\nxr = x + tee;\nytop = y + u;\nybot = y - l;\nn = size(y,2);\n\n% Plot graph and bars\nhold_state = ishold;\ncax = newplot;\nnext = lower(get(cax,'NextPlot'));\n\n% build up nan-separated vector for bars\nxb = zeros(npt*9,n);\nxb(1:9:end,:) = x;\nxb(2:9:end,:) = x;\nxb(3:9:end,:) = NaN;\nxb(4:9:end,:) = xl;\nxb(5:9:end,:) = xr;\nxb(6:9:end,:) = NaN;\nxb(7:9:end,:) = xl;\nxb(8:9:end,:) = xr;\nxb(9:9:end,:) = NaN;\n\nyb = zeros(npt*9,n);\nyb(1:9:end,:) = ytop;\nyb(2:9:end,:) = ybot;\nyb(3:9:end,:) = NaN;\nyb(4:9:end,:) = ytop;\nyb(5:9:end,:) = ytop;\nyb(6:9:end,:) = NaN;\nyb(7:9:end,:) = ybot;\nyb(8:9:end,:) = ybot;\nyb(9:9:end,:) = NaN;\n\n[ls,col,mark,msg] = colstyle(symbol); if ~isempty(msg), error(msg); end\nsymbol = [ls mark col]; % Use marker only on data part\nesymbol = [ '-' col]; % Make sure bars are solid\n\nh = plot(xb,yb,esymbol); hold on\nh = [h;plot(x,y,symbol)]; \n\nif ~hold_state, hold off; end\n\nif nargout>0, hh = h; end\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/errorbar2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760727, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.5812652725795248}}
{"text": "function show_r3_point_set(points_x,varargin)\n%SHOW_R3_POINT_SET 3D illustration of a point set\n%\n%Syntax\n% show_r3_point_set(POINTS_X,options);\n%\n%Description\n% SHOW_R3_POINT_SET(POINTS_X) uses a 3d plot to illustrate a point set in relation to\n% the unit sphere S^2.\n%\n% The argument POINTS_X must be an array of real numbers of size (3 by N), where N is a\n% positive integer, representing N points of R^3.\n%\n% SHOW_R3_POINT_SET(POINTS_X,options) also recognizes a number of illustration\n% 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% SHOW_R3_POINT_SET(POINTS_X,'fontsize',size)\n% Font size used in titles (numeric, default 16).\n%\n% SHOW_R3_POINT_SET(POINTS_X,'title','show')\n% SHOW_R3_POINT_SET(POINTS_X,'title','hide')\n% Show or hide title (default 'hide').\n%\n% SHOW_R3_POINT_SET(POINTS_X,'sphere','show')\n% SHOW_R3_POINT_SET(POINTS_X,'sphere','hide')\n% Show or hide the unit sphere S^2 (default 'hide').\n%\n% For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS.\n%\n%Note\n% This function is primarily for use with the point set POINTS_X as a subset of the \n% unit sphere S^2, but this is not assumed and not checked.\n% If you show the unit sphere S^2 and POINTS_X contains points closer than radius 1\n% from the origin, the sphere will hide these points.\n%\n%Examples\n% > points_x\n% points_x =\n%          0    0.0000   -0.0000    0.0000\n%          0    1.0000   -1.0000         0\n%     1.0000    0.0000    0.0000   -1.0000\n%\n% > show_r3_point_set(points_x,'sphere','hide')\n% > show_r3_point_set(points_x,'sphere','show')\n%\n%See also\n% ILLUSTRATION_OPTIONS, SHOW_S2_PARTITION, PROJECT_POINT_SET\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\ngdefault.fontsize = 16;\ngdefault.show_title  = false;\ngdefault.show_sphere = false;\n\ngopt = illustration_options(gdefault, varargin{:});\n\nN = size(points_x,2);\n\nsurf_jet;\n\nif gopt.show_title\n    titlestr = sprintf(...\n        '\\nPoint set containing %d points.',N);\n    title(titlestr,'FontWeight','bold','FontUnits','normalized',...\n        'FontSize',gopt.fontsize/512);\nend\n\nif gopt.show_sphere\n    show_s2_sphere;\n    hold on\nend\n\n[X,Y,Z] = sphere;\n\nr = min(0.05,N^(-1/2)/2);\nrX = r*X; rY = r*Y; rZ = r*Z;\nfor n = 1:N\n   surf(points_x(1,n)+rX,points_x(2,n)+rY,points_x(3,n)+rZ,ones(size(rZ)),...\n   'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\nend\n%\naxis equal\naxis off\ngrid off\nhold off\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_illustrations/show_r3_point_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.5812652704241389}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\nfunction y = MC_merton_sgs(S,r,sigma,T, a,b,lambda,NSim)\n%Implements the SGS method for the Merton model\nnu = r - lambda*(exp(a+0.5*b^2)-1)-0.5*sigma^2; % martingale correction\n\nX = log(S)*ones(NSim,1);          % X is the log price path\n\nfor k=1:NSim\n    t = 0;\n    tau = [];\n    %simulate the jump times first\n    while t < T\n        dt = -log(rand)/lambda;% jump time\n        t = t + dt;            % add the jump times\n        tau = [tau; dt];             % not good matlab but works!\n    end\n    tau(end) = T-(t-dt);\n    N = length(tau);                    % N number of jumps + 1\n    W1 = randn(1,N);                    % uniforms for diffusion\n    if N > 1\n        W2 = randn(1,N-1);              % uniforms for jumps\n        for i = 1:N-1\n            Z = nu*tau(i) + sigma*sqrt(tau(i)) * W1(i);\n            lnY = a+b*W2(i);                                                              \n            X(k) = X(k) + Z + lnY;\n        end\n    end\n    \n    dt_end = tau(end);\n    Z = nu * dt_end + sigma * sqrt(dt_end) * W1(end);\n    X(k) = X(k) + Z;\nend\ny = exp(X);\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/37621-fixed-grid-and-stochastic-grid-monte-carlo-sampling/FGS_SGS_Sampling/MC_merton_sgs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5811804501068684}}
{"text": "function [y alpha eps eta] = sample_int(n, N, p, m, r, Znl, Tnl, Z, T, Hdyn, Zdyn, Tdyn, Rdyn, Qdyn, cdyn, Hmat, Rmat, Qmat, cmat, a1, P1)\n% y is p*N*n\n% alpha is m*N*n\n% eps is p*N*n\n% eta is r*N*n\n\n%% Determine nonlinear functions %%\nif Znl, Zdyn = false; else Zmat = getmat(Z); end\nif Tnl, Tdyn = false; else Tmat = getmat(T); end\n\n%% Draw from Gaussian distribution %%\nalpha1  = randn(m, N);\neps     = randn(p, N, n);\neta     = randn(r, N, n);\n\n%% Initialization for sampling %%\nif Hdyn, eps(:,:, 1) = sigma_int(Hmat{1}, eps(:,:, 1));\nelse eps = reshape(sigma_int(Hmat, reshape(eps, p, N*n)), p, N, n); end\nif Tdyn, T = Tmat{1}; elseif ~Tnl, T = Tmat; end\nif Rdyn, R = Rmat{1}; else R = Rmat; end\nif Qdyn, eta(:,:, 1) = sigma_int(Qmat{1}, eta(:,:, 1));\nelse eta = reshape(sigma_int(Qmat, reshape(eta, r, N*n)), r, N, n); end\nif cdyn, c = repmat(cmat{1}, 1, N); else c = repmat(cmat, 1, N); end\nP1(P1 == Inf) = 0;\ny       = zeros(p, N, n);\nalpha   = zeros(m, N, n);\n\n%% Generate independent samples from the model %%\nalpha(:,:, 1) = repmat(a1, 1, N) + sigma_int(P1, alpha1);\nif Znl, y(:,:, 1) = getfunc(Z, alpha(:,:, 1), 1);\nelseif Zdyn, y(:,:, 1) = Zmat{1}*alpha(:,:, 1);\nend\nfor t = 2 : n\n    if Hdyn, eps(:,:, t) = sigma_int(Hmat{t}, eps(:,:, t)); end\n    if Qdyn, eta(:,:, t) = sigma_int(Qmat{t}, eta(:,:, t)); end\n    if Tnl, alpha(:,:, t) = c + getfunc(T, alpha(:,:, t-1), t-1) + R*eta(:,:, t-1);\n    else alpha(:,:, t) = c + T*alpha(:,:, t-1) + R*eta(:,:, t-1);\n    end\n    if Znl, y(:,:, t) = getfunc(Z, alpha(:,:, t), t); end\n    if Zdyn, y(:,:, t) = Zmat{t}*alpha(:,:, t); end\n    if Tdyn, T = Tmat{t}; end\n    if Rdyn, R = Rmat{t}; end\n    if cdyn, c = repmat(cmat{t}, 1, N); end\nend\nif ~Znl && ~Zdyn, y = reshape(Zmat*reshape(alpha, m, N*n), p, N, n) + eps;\nelse y = y + eps; end\n\n%% Function for incorporating covariance into independent Gaussian samples %%\nfunction x = sigma_int(Sigma, u)\ndgSigma = diag(Sigma);\nif isequal(Sigma, diag(dgSigma)), x = diag(sqrt(dgSigma))*u;\nelse % Sigma is not diagonal\n    [U Lambda] = eig(full(Sigma));\n    x = U*(diag(sqrt(diag(Lambda)))*u);\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/ssm-1.0.1/ssm-release/@ssmodel/private/sample_int.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5811804448977963}}
{"text": "function pix = pixelize(datain_all, intens, box, nx, ny, namefile, showplot)\n\n% pix = pixelize(datain_all, intens, box, nx, ny, namefile,showplot)\n% pixelize PALM data\n% datain_all - input data, #points-by-2 matrix, each row correspond to xy\n% coordinate of the datapoint\n% intens - intensities of each center (stored in a0_phot)\n% box = [xlim1, xlim2, ylim1, ylim2] - selected ROI \n% nx - number of pixels in x direction \n% ny - number of pixels in y direction \n% namefile - (optional) name of the TXT file with matrix pix\nif ~exist ('showplot', 'var')\n    showplot = 1;\nend\n\nsx = (box(2)-box(1))/nx; %size of the pixels\nsy = (box(4)-box(3))/ny;\n\n[datain, indexGood] = ROIdata (datain_all, box(1), box(2), box(3),  box(4), showplot);\nintensGood=intens(indexGood);\npixvec = ceil ([(datain(:,1) - box(1))/sx , (datain(:,2) - box(3))/sy ]);\n\n% indrem_min = find (or(pixvec(:,1) < 0, pixvec(:,2) < 0));\n% indrem_max = find (or(pixvec(:,1) > nx, pixvec(:,2) > ny));\n\n\npix = zeros(nx, ny);\nind = sub2ind(size(pix), pixvec(:,1), pixvec(:,2));\n% pix(ind) = intens;\nfor ii=1:length(ind)\n    pix(ind(ii))=pix(ind(ii))+intensGood(ii);\nend\n\n% pix = flipud(pix'); % to follow the matlab notation for imagesc(pix)...\npix = pix'; % to follow the matlab notation for imagesc(pix)...\n\nif ~exist ('showplot', 'var')\n    showplot = 1;\nend\n    \nif showplot\n    figure\n    imagesc(pix)\n    set (gca, 'DataAspectRatio',[sy sx 1]);\nend\n\nif exist('namefile', 'var')\n    if ~isempty(namefile)\n        fid = fopen([namefile '.txt'], 'wt'); % Open for writing\n        for i=1:size(pix,1)\n            fprintf(fid, '%d ', pix(i,:));\n            fprintf(fid, '\\n');\n        end\n        fclose(fid);\n    end\nend", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/PatternAnalysis/pixelize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.581180444257485}}
{"text": "function [y]=col(x, k, varargin)\n%Computes the columns of a block TT-tensor \n%   [Y]=COL(X,K)\n%   It is useful for block algorithms when r(d+1) is not equal to 1\n%   For analogous thing on r(1) see ROW(X,K)\n%\n%\n% TT-Toolbox 2.2, 2009-2012\n%\n%This is TT Toolbox, written by Ivan Oseledets et al.\n%Institute of Numerical Mathematics, Moscow, Russia\n%webpage: http://spring.inm.ras.ru/osel\n%\n%For all questions, bugs and suggestions please mail\n%ivan.oseledets@gmail.com\n%---------------------------\n\nd=x.d;\nr=x.r;\n\nif nargin > 2\n    for j = 1 : nargin-2\n        k = [k, varargin{j}];\n    end\nend\n\nBlockSize = r(d+1);\nif max(k) > BlockSize\n    error('TT-tensor.col:Index exceeds dimensions in TT block.');\nend\n\nCutMatr = eye(BlockSize);\nCutMatr = CutMatr(:, k);\ny = x*CutMatr;  \n\nreturn\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/@tt_tensor/col.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5811804396887243}}
{"text": "\n% Load Alan\nx=imread('Alan.jpg','jpg');\n\n% Crop Alan\nstartx=100;\nstarty=300;\n\nN=256;\nxg=double(x(startx:startx+N-1,starty:starty+N-1,2));\nxg=xg-mean(mean(xg));\n\n% Maximum latent space dimension\nq=100;\npca=spm_vpca(xg,q);\n\nfigure; imagesc(pca.M_w); colormap gray; title('Bayes estimate');\nfigure; imagesc(pca.ml.W(:,1:q)); colormap gray; title('ML estimate');\n\nfigure\nplot(pca.Fm_evol);\nxlabel('Iterations');\nylabel('Neg. Free Energy');\n\nfigure\nplot(pca.ml.lambda);\ntitle('Eigenspectrum');\n\nfigure\nplot(pca.mean_alpha);\ntitle('Prior precision of factors');\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_vpca_big.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5811804390484131}}
{"text": "%\n% step 3: evaluation of performance\n%\n% using our third set of prices, we estimate dp at each time interval,\n% if dp > t and current position <= 0 , we buy\n% if dp < -t and current position >= 0, we sell\n% else, do:nothing\n%\n\n% trade using the above algorithm. returns expected profit\n%\n% given a list of prices\n% assumes k-means clustered patterns have already been calculated\n% assumes parameters w_i have already been calculated\n% position is 0 or 1 (we have nothing, we have a bitcoin)\n% bank is the amount of cash we have\n% threshold is the threshold for buying/selling\n% defined in the paper\nfunction [error,jinzhi,bank,buy,sell,proba] = brtrade(prices, bidVolume,askVolume, fee)\n    assert(exist('thetas.mat','file')==2)\n    load('thetas.mat');\n    assert(isequal(length(prices), length(bidVolume)));\n    assert(isequal(length(prices), length(askVolume)));\n    position = 0;\n    bank = 0;\n    jinzhi = zeros(length(prices)-750, 1);\n    error = 0; \n    %current error metric is sum(abs(error))/time interval = ~.9\n    %current error = 0.06\n    buy = [];\n    sell = [];\n    counttotal = 0;\n    counts = 0;\n    temp = 0;\n    for t = 720:length(prices)-1  \n        price180 = zscore(prices(t-179:t));      \n        price360 = zscore(prices(t-359:t));      \n        price720 = zscore(prices(t-719:t));\n\n        %average price change dp_j is given by bayesian regression    \n        dp1 = bayesian(price180,kmeans180s);\n        dp2 = bayesian(price360,kmeans360s);\n        dp3 = bayesian(price720,kmeans720s);\n\n        r = (bidVolume(t)-askVolume(t))/(bidVolume(t)+askVolume(t));\n        \n        dp = theta0 +  theta(1)*dp1 + theta(2)*dp2 + theta(3)*dp3;% + theta(4)*r;\n        \n        % compare price at t+1 with predicted price jump\n        error = error + abs(prices(t+1)-prices(t)-dp);\n        \n        % calculate transaction fee??\n        % threshold 1 and 2 before...but \n        % there is definitely not going to be a \n        % 5-8$ price jump predicted in the next ten seconds\n        % need to consider TODO\n\t\tfee = 0;\n\t\tif (fee == 0)\n            tfee_buy = 0.001;\n            tfee_sell = 0.003;\n        else\n            tfee_buy = fee*prices(2)/100;\n            tfee_sell = tfee_buy;\n        end\n        %BUY\n        if (dp > tfee_buy && position == 0)\n            position = 1;\n            temp = prices(t);\n            fprintf('Buying at %d\\n', temp);\n            buy = [buy;t];\n        end \n        %SELL\n        if (dp < -tfee_sell && position == 1)\n            position = 0;\n            bank = bank + prices(t)-temp;\n            fprintf('Selling at %d\\n', prices(t));\n            sell = [sell;t];\n            counttotal = counttotal+1;\n            if prices(t)-temp>0\n                counts = counts+1;\n            end\n        end\n\n        jinzhi(t) = bank;\n    end\n    \n    % forces us to close the position at the end\n    % tradeoffs to this decision\n    % on one side: more realistic\n    % but the algorithm doesn't yet account for it\n    if (position == 1)\n        bank = bank + prices(t)-temp;\n        fprintf('Final sale at %d\\n', prices(t));\n        sell = [sell;t];\n        counttotal = counttotal+1;\n        if prices(t)-temp>0\n            counts = counts+1;\n        end\n    end\n    proba = (counts./counttotal)*100;\n    end\n", "meta": {"author": "panditanvita", "repo": "BTCpredictor", "sha": "76fc3744563aa160c0fca76b9a7d7974bf1c1a20", "save_path": "github-repos/MATLAB/panditanvita-BTCpredictor", "path": "github-repos/MATLAB/panditanvita-BTCpredictor/BTCpredictor-76fc3744563aa160c0fca76b9a7d7974bf1c1a20/brtrade.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5811410860422807}}
{"text": "function test_ft_networkanalysis\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_networkanalysis\n\ndata = [];\nfor k = 1:5\n  x = randn(7,15);\n  cx = x*x';\n  cx = cx./sqrt(diag(x)*diag(x)');\n  data.cohspctrm(:,:,k) = cx;\nend\ndata.freq  = 1:5;\ndata.label = {'chan1';'chan2';'chan3';'chan4';'chan5';'chan6';'chan7'};\ndata.dimord = 'chan_chan_freq';\ndata.cfg    = 'this is the cfg';\n\ntmp = data;\ntmp.cohspctrm = data.cohspctrm>0.3;\n\n% at present just checks for undirected binary and weighted graphs\ncfg           = [];\ncfg.parameter = 'cohspctrm';\n\ncfg.method    = 'assortativity';\nstat1 = ft_networkanalysis(cfg, tmp);\nstat2 = ft_networkanalysis(cfg, data);\n\ncfg.method    = 'betweenness';\nstat3 = ft_networkanalysis(cfg, tmp);\nstat4 = ft_networkanalysis(cfg, data);\n\ncfg.method    = 'clustering_coef';\nstat5 = ft_networkanalysis(cfg, tmp);\nstat6 = ft_networkanalysis(cfg, data);\n\ncfg.method    = 'degrees';\nstat7 = ft_networkanalysis(cfg, tmp);\nstat8 = ft_networkanalysis(cfg, data);\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_ft_networkanalysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5811410803075008}}
{"text": "function a = asinh(a)\n%ASINH        Gradient inverse hyperbolic sine asinh(a)\n%\n\n% written  10/16/98     S.M. Rump\n% modified 10/14/00     S.M. Rump  use Tony's trick\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/28/08     S.M. Rump  check for rounding to nearest improved\n% modified 10/08/08     S.M. Rump  improved sparse multiplication: not using intval data type\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  e = 1e-30;\n  if 1+e==1-e                           % fast check for rounding to nearest\n    rndold = 0;\n  else\n    rndold = getround;\n    setround(0)\n  end\n\n  N = getappdata(0,'INTLAB_GRADIENT_NUMVAR');\n  % use full(a.x(:)): cures Matlab V6.0 bug\n  % a=7; i=[1 1]; x=a(i), b=sparse(a); y=b(i)  yields row vector x but column vector y\n  % ax is full anyway\n  ax = 1 ./ sqrt( 1 + sqr(full(a.x(:))) );\n  a.x = asinh(a.x);\n  if issparse(a.dx)\n    sizeax = size(a.dx,1);\n    [ia,ja,sa] = find(a.dx);\n    if isa(a.x,'intval')\n      adx = times(ax(ia),sa,0);\n      if adx.complex\n        a.dx = intval( sparse(ia,ja,adx.mid,sizeax,N) , sparse(ia,ja,adx.rad,sizeax,N) , 'midrad' );\n      else\n        a.dx = intval( sparse(ia,ja,adx.inf,sizeax,N) , sparse(ia,ja,adx.sup,sizeax,N) , 'infsup' );\n      end\n    else\n      a.dx = sparse(ia,ja,ax(ia).*sa,sizeax,N);\n    end\n  else\n    a.dx = a.dx .* ax(:,ones(1,N));\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/gradient/@gradient/asinh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.5810603872570866}}
{"text": "function [iQ] = VBA_inv(Q,indIn,flag,v)\n% overloaded sparse matrix pseudo-inverse\n% function [iQ] = VBA_inv(Q,indIn,flag,v)\n% IN:\n%   - Q: the nxn matrix to be inverted\n%   - indIn: a vector of indices that specifies the submatrix of Q that has\n%   to be inverted. The rest of the matrix is padded with zeros. If empty,\n%   the routine looks for infinite or below precision (close to zero)\n%   entries in the the diagonal of Q.\n%   - flag: if flag='replace', the routine returns Q, having replaced its\n%   elements not in 'indIn' with v (see below)\n%   - v: a number by which to padd the elements of Q not in 'indIn' (only\n%   for flag='replace')\n% OUT:\n%   - iQ: the nxn matrix that is either the inverse of Q or v-padded Q (for\n%   flag='replace').\n\nif nargin < 2 || isempty(indIn)\n    dq = diag(Q);\n    indIn = find(~isinf(dq)&dq~=0);\nend\n% use lazy evaluation if all matrix is used\nisSub = ~all(numel(indIn) == size(Q));\n\nif nargin < 3\n    replace = 0;\nelse\n    replace = isequal(flag,'replace');\nend\nif nargin < 4\n    v = 0;\nend\nif isSub\n    subQ = full(Q(indIn,indIn));\nelse\n    subQ = full(Q);\nend\nif replace % v-padd\n    iQ = v.*ones(size(Q));\n    iQ(indIn,indIn) = subQ;\nelse % (p)invert Q\n    if isequal(subQ,eye(length(indIn)))   % identity matrix\n        subiQ = subQ;\n    elseif isequal(subQ,diag(diag(subQ))) % diagonal matrix\n        tol  = max(eps(norm(diag(subQ),'inf'))*length(indIn),exp(-32)); \n        subiQ = diag((diag(subQ)+tol).^-1);\n    else % full matrix\n        tol  = max(eps(norm(subQ,'inf'))*length(indIn),exp(-32)); \n        subiQ = inv(subQ + eye(length(indIn))*tol);\n    end\n    if isSub\n        iQ = zeros(size(Q));\n        iQ(indIn,indIn) = subiQ;\n    else\n        iQ = subiQ;\n    end\nend\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/utils/VBA_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5810603801147595}}
{"text": "function [ fea, out ] = ex_linearelasticity4( varargin )\n%EX_LINEARELASTICITY4 Stress calculation of an I-beam attached to two brackets.\n%\n%   [ FEA, OUT ] = EX_LINEARELASTICITY4( VARARGIN ) Example to calculate displacements and\n%   stresses for an I-beam suppored by two brackets with circular holes.\n%\n%   Accepts the following property/value pairs.\n%\n%       Input       Value/{Default}        Description\n%       -----------------------------------------------------------------------------------\n%       E           scalar {200e9}         Modulus of elasticity\n%       nu          scalar {0.3}           Poissons ratio\n%       force       scalar {1e5}           Load force\n%       l           scalar {0.4}           Length of I-beam\n%       ilev        scalar {2}             Grid regfinement level\n%       sfun        string {sflag1}        Shape function for displacements\n%       iplot       scalar 0/{1}           Plot solution (=1)\n%                                                                                         .\n%       Output      Value/(Size)           Description\n%       -----------------------------------------------------------------------------------\n%       fea         struct                 Problem definition struct\n%       out         struct                 Output struct\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { ...\n  'E',        200e9; ...\n  'nu',       0.3; ...\n  'force',    1e5; ...\n  'l',        0.4; ...\n  'ilev',     2; ...\n  'sfun',     'sflag1'; ...\n  'iplot',    1; ...\n  'tol',      0.42; ...\n  'fid',      1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid       = opt.fid;\n\n\n% Geometry definition.\nfea.sdim = { 'x' 'y' 'z' };   % Coordinate names.\n\n\n% Grid generation.\nfea.grid = get_grid( opt.ilev );\n\n\n% Problem definition.\nfea = addphys(fea,@linearelasticity);\nfea.phys.el.eqn.coef{1,end} = { opt.nu };\nfea.phys.el.eqn.coef{2,end} = { opt.E  };\nfea.phys.el.sfun            = { opt.sfun opt.sfun opt.sfun };\n\n\n% Boundary conditions.\ndtol     = sqrt(eps);\nfixbdr   = findbdr( fea, ['(sqrt(x.^2+z.^2)<=0.03+sqrt(eps))&(z>=-sqrt(eps))'] );\nforcebdr = findbdr( fea, ['abs(y)>=0.2-sqrt(eps)'] );\n\n\n% Fix boundaries (set zero Dirichlet BCs).\nn_bdr  = max(fea.grid.b(3,:));        % Number of boundaries.\nbctype = num2cell( zeros(3,n_bdr) );  % First set homogenous Neumann BCs everywhere.\n[bctype{:,fixbdr}] = deal( 1 );       % Set Dirchlet BCs for right boundary.\nfea.phys.el.bdr.coef{1,5} = bctype;\n\n% Apply negative z-load to left boundary.\nbccoef = num2cell( zeros(3,n_bdr) );\n[bccoef{3,forcebdr}] = deal(-opt.force);\nfea.phys.el.bdr.coef{1,end} = bccoef;\n\n\n% Parse and solve problem.\nfea       = parsephys( fea );\nfea       = parseprob( fea );\nfea.sol.u = solvestat( fea, 'fid', fid );\n\n\n% Postprocessing.\nif ( opt.iplot>0 )\n  DSCALE = 5000;\n\n  subplot(1,2,1)\n  postplot( fea, 'surfexpr', 'sqrt(u^2+v^2+w^2)', 'linestyle', 'none' )\n  title( 'Total displacement' )\n  view([30 20])\n\n  subplot(1,2,2)\n  dp = zeros(size(fea.grid.p));\n  for i=1:3\n    dp(i,:) = DSCALE*evalexpr( fea.dvar{i}, fea.grid.p, fea );\n  end\n  fea_disp.grid   = fea.grid;\n  fea_disp.grid.p = fea_disp.grid.p + dp;\n  plotgrid( fea_disp )\n  title(['Displacement plot (at ',num2str(DSCALE),' times scale)'])\n  view([30 20])\n\nend\n\n\n% Error check.\ndisp_max_ref = 6.204e-6;\nxdisp = fea.sol.u(fea.eqn.dofm{1}(:));\nydisp = fea.sol.u(fea.eqn.dofm{2}(:)+fea.eqn.ndof(1));\nzdisp = fea.sol.u(fea.eqn.dofm{3}(:)+sum(fea.eqn.ndof(1:2)));\ndisp  = sqrt(xdisp.^2+ydisp.^2+zdisp.^2);\ndisp_max = max(disp);\n\nsvm_max_ref = 4.410e6;\nsvm = evalexpr( fea.phys.el.eqn.vars{1,2}, fea.grid.p, fea );\nsvm_max = max(svm);\n\nout.disp_max = disp_max;\nout.svm_max  = svm_max;\nout.err(1)   = abs(disp_max - disp_max_ref)/abs(disp_max_ref);\nout.err(2)   = abs(svm_max - svm_max_ref)/abs(svm_max_ref);\nout.pass     = all(out.err<opt.tol);\n\n\nif ( nargout==0 )\n  clear fea out\nend\n\n\n%------------------------------------------------------------------------------%\nfunction [ grid ] = get_grid( ilev )\n\nn0 = 12;\nnr = n0*2^(ilev-1);\nr  = 0.03;   % Radius of bracket holes.\nt  = 0.03;   % Thickness of brackets.\ngrid01 = ringgrid( 3*2^(ilev-1), 4*nr, r, r+t, [0;0] );\nindc01 = selcells( grid01, 'y<=sqrt(eps)' );\ngrid01 = delcells( grid01, indc01 );\n\ngrid02 = holegrid( nr, 3*2^(ilev-1), (r+t)*[-1 1;-1 1], r, [0;0] );\nindc02 = selcells( grid02, 'y>=-sqrt(eps)' );\ngrid02 = delcells( grid02, indc02 );\ngrid2d = gridmerge( grid01, findbdr(grid01,'y<=sqrt(eps)'), grid02, findbdr(grid02,'y>=-sqrt(eps)') );\nt_br = 0.02;   % Width/depth of brackets.\nd_br = 0.05;   % Separation distance between brackets.\ngrid1 = gridextrude( grid2d, 2^(ilev-1), t_br );\ngrid1 = gridrotate( grid1, pi/2, 1 );\ngrid2 = grid1;\ngrid1.p(2,:) = grid1.p(2,:) - d_br/2;\ngrid2.p(2,:) = grid2.p(2,:) + t_br + d_br/2;\n\n\n% Create grids for the I-beam.\nw_ib = 0.16;   % Beam width.\nl_ib = 0.4;    % Beam length.\nt_ib = 0.01;   % Beam thickness.\nh_ib = 0.1;    % Beam height.\n\nx_in    = linspace(-(r+t),r+t,n0+1);\nx_coord = [ -w_ib/2 x_in w_ib/2];\ny_coord = [ -0.2 -0.175 -0.15 -0.125 -0.1 -0.075 -(d_br/2+t_br) -d_br/2 0 d_br/2 d_br/2+t_br 0.075 0.1 0.125 0.15 0.175 0.2 ];\nfor i=2:ilev\n  x_coord = sort([ x_coord [x_coord(1:end-1) + x_coord(2:end)]/2 ]);\n  y_coord = sort([ y_coord [y_coord(1:end-1) + y_coord(2:end)]/2 ]);\nend\ngrid3 = blockgrid( x_coord, y_coord, 2^(ilev-1), ...\n                   [-w_ib/2 w_ib/2;-0.2 0.2;-(r+t)-t_ib -(r+t)] );\ntm_ib = 2*(x_in(2)-x_in(1));\ngrid4 = blockgrid( 2*2^(ilev-1), y_coord, 5*2^(ilev-1), ...\n                   [-tm_ib/2 tm_ib/2;-0.2 0.2;-(r+t)-t_ib-h_ib -(r+t)-t_ib] );\ngrid5 = grid3;\ngrid5.p(3,:) = grid5.p(3,:) - t_ib - h_ib;\n\n\n% Merge grids.\ntol = sqrt(eps)*1e3;\ngrid = gridmerge( grid1, findbdr(grid1,['z<=',num2str(-(r+t-tol))]), ...\n                  grid3, findbdr(grid3,['z>=',num2str(-(r+t+tol))]) );\ngrid = gridmerge( grid2, findbdr(grid1,['z<=',num2str(-(r+t-tol))]), ...\n                  grid,  findbdr(grid, ['(z>=',num2str(-(r+t+tol)),')&'...\n                                        '(z<=',num2str(-(r+t-tol)),')']) );\ngrid = gridmerge( grid,  findbdr(grid,  ['z<=',num2str(-(r+t+t_ib-tol))]), ...\n                  grid4, findbdr(grid4, ['z>=',num2str(-(r+t+t_ib+tol))]), 1 );\ngrid = gridmerge( grid,  findbdr(grid,  ['z<=',num2str(-(r+t+t_ib+h_ib-tol))]), ...\n                  grid5, findbdr(grid5, ['z>=',num2str(-(r+t+t_ib+h_ib+tol))]), 2 );\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/examples/ex_linearelasticity4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5810603778358163}}
{"text": "classdef OptimalControler < handle\n    % Let s :=[x(0), .., x(n), u(0)....u(n-1)] be decision variables, then\n    % optimal control problem is composed by\n    % (i) objective function V(s) = s'*H*S in quadratic form\n    % (ii) equality constraints specified by C_eq1 and C_eq2 where C_eq1*s =C_eq2\n    % (iii) inequality constraints specified by C_ineq1 and C_ineq2 where C_ineq1 * s <= C_ineq2\n    %\n    % For potential future extensions, all constraints will be managed by ConstraintManager class.\n    % Any time you add a new constraint, those constraint is pushed into the manager with a key (name of constraint). \n    \n    \n    properties (SetAccess = private)\n        sys; %system\n        Xc; Uc; % constraints set for statespace and input space\n        x_min; x_max; % lower and upper bound of Xc\n        N; % prediction horizon\n        Ak; % S.T.M of closed-roop system with LQR feedback\n        n_opt; % dim. of optimization parameter s :=[x(0), .., x(n), u(0)....u(n-1)]\n        H; % positive definite matrix for objective function V(s) = s'*H*s \n        constraint_manager;\n    end\n    \n    %% Public Methods\n    methods (Access = public)\n        \n        function obj = OptimalControler(sys, Xc, Uc, N)\n            obj.sys = sys;\n            obj.Xc = Xc;\n            obj.x_min = min(Xc.V, [], 1)';\n            obj.x_max = max(Xc.V, [], 2)';\n            obj.Uc = Uc;\n            obj.N = N;\n            \n            obj.n_opt = obj.sys.nx*(obj.N+1)+obj.sys.nu*obj.N;\n            obj.constraint_manager = ConstraintManager();\n            \n            obj.H = obj.construct_costfunction();\n            [C_eq1, C_eq2] = obj.construct_dynamics_constraint();\n            [C_ineq1, C_ineq2] = obj.construct_ineq_constraint(Xc, Uc);\n\n            %% Let's change initial and dynamics constraints!!\n            obj.constraint_manager.add_eq_constraint('dynamics', C_eq1, C_eq2);\n            obj.constraint_manager.add_ineq_constraint('feasible', C_ineq1, C_ineq2);\n        end\n\n        function add_initial_eq_constraint(obj, x_init)\n            % E * x0 = x_init\n            idx_x0_start = 1;\n            idx_x0_end = obj.sys.nx;\n\n            C_eq1_init = zeros(obj.sys.nx, obj.n_opt);\n            C_eq1_init(:, idx_x0_start:idx_x0_end) = eye(obj.sys.nx);\n            C_eq2_init = x_init;\n            obj.constraint_manager.add_eq_constraint('initial', C_eq1_init, C_eq2_init);\n        end\n\n        function add_terminal_constraint(obj, Xadd)\n            [C_ineq1_add, C_ineq2_add] = add_ineq_constraint(obj, Xadd, obj.N+1);\n            obj.constraint_manager.add_ineq_constraint('terinal', C_ineq1_add, C_ineq2_add);\n        end\n\n        function add_initial_constraint(obj, Xadd)\n            [C_ineq1_add, C_ineq2_add] = add_ineq_constraint(obj, Xadd, 1);\n            obj.constraint_manager.add_ineq_constraint('initial', C_ineq1_add, C_ineq2_add);\n        end\n        \n        function [x_seq, u_seq] = solve(obj)\n            quadprog_solved = 0;\n            [C_eq1, C_eq2] = obj.constraint_manager.combine_all_eq_constraints();\n            [C_ineq1, C_ineq2] = obj.constraint_manager.combine_all_ineq_constraints();\n\n            options = optimoptions('quadprog', 'Display', 'none');\n            [var_optim, ~, exitflag] = quadprog(obj.H, [], C_ineq1, C_ineq2, C_eq1, C_eq2, [], [], [], options);\n            x_seq = reshape(var_optim(1:obj.sys.nx*(obj.N+1)), obj.sys.nx, obj.N+1);\n            u_seq = reshape(var_optim(obj.sys.nx*(obj.N+1)+1:obj.n_opt), obj.sys.nu, obj.N);\n            \n        end\n        \n    end\n    \n    %% Methods Used in Constoructor\n    methods (Access = private)\n        \n        function H = construct_costfunction(obj)\n            % compute H\n            Q_block = [];\n            R_block = [];\n            for itr=1:obj.N\n                Q_block = blkdiag(Q_block, obj.sys.Q);\n                R_block = blkdiag(R_block, obj.sys.R);\n            end\n            H = blkdiag(Q_block, obj.sys.P, R_block);\n        end\n\n        function [C_eq1, C_eq2] = construct_dynamics_constraint(obj)\n            % compute C_eq1 and C_eq2\n            function C_ss_eq1 = single_step_dynamics_eq1(k)\n                % A x(k) - E x(k+1) + Bu(k) = 0\n                idx_xk_start = obj.sys.nx * k + 1;\n                idx_xk_end = obj.sys.nx * (k + 1);\n\n                idx_xkp1_start = obj.sys.nx * (k + 1) + 1;\n                idx_xkp1_end = obj.sys.nx * (k + 2);\n\n                idx_uk_start  = obj.sys.nx * (obj.N+1) + obj.sys.nu * k + 1;\n                idx_uk_end  = obj.sys.nx * (obj.N+1) + obj.sys.nu * (k + 1);\n\n                C_ss_eq1 = zeros(obj.sys.nx, obj.n_opt);\n\n                C_ss_eq1(:, idx_xk_start:idx_xk_end) = obj.sys.A;\n                C_ss_eq1(:, idx_xkp1_start:idx_xkp1_end) = - eye(obj.sys.nx);\n                C_ss_eq1(:, idx_uk_start:idx_uk_end) = obj.sys.B;\n            end\n\n            C_eq1 = [];\n            for k = 0:obj.N-1\n                C_ss_eq1 = single_step_dynamics_eq1(k);\n                C_eq1 = [C_eq1; C_ss_eq1];\n            end\n            C_eq2 = zeros(size(C_eq1, 1), 1);\n        end\n       \n        function [C_ineq1, C_ineq2] = construct_ineq_constraint(obj, Xc, Uc)\n            % compute C_ineq\n            [F, G, nc] = convert_Poly2Mat(Xc, Uc);\n            \n            F_block = [];\n            G_block = [];\n            for itr = 1:obj.N\n                G_block = blkdiag(G_block, G);\n            end\n            for itr = 1:obj.N+1\n                F_block = blkdiag(F_block, F);\n            end\n            C_ineq1 = [F_block, [G_block; zeros(nc, obj.sys.nu*obj.N)]];\n            nc_total = size(C_ineq1, 1);\n            C_ineq2 = ones(nc_total, 1);\n        end\n        \n    end\n    \n    methods (Access = private)\n        \n        function [C_ineq1_add, C_ineq2_add] = add_ineq_constraint(obj, Xadd, k_add)\n            % add a new constraint at time step k \n            if Xadd.contains(zeros(2, 1)) % If Xadd contains the origin, the contraint can be expressed as C1*x<=1\n                [F_add, ~, nc_add] = convert_Poly2Mat(Xadd, Polyhedron());\n                C_ineq2_add = ones(nc_add, 1);\n                \n            else % in other cases, expressed in a general affine form C1*x<=C2\n                F_add = Xadd.A;\n                nc_add = size(F_add, 1);\n                C_ineq2_add = Xadd.b;\n            end\n            \n            C_ineq1_add = zeros(nc_add, obj.n_opt);\n            C_ineq1_add(:, (k_add-1)*obj.sys.nx+1:k_add*obj.sys.nx) = F_add;\n        end\n        \n    end\nend\n\n", "meta": {"author": "HiroIshida", "repo": "robust-tube-mpc", "sha": "427a181dd368f0b60b1ecfa81e33e062ff0359e0", "save_path": "github-repos/MATLAB/HiroIshida-robust-tube-mpc", "path": "github-repos/MATLAB/HiroIshida-robust-tube-mpc/robust-tube-mpc-427a181dd368f0b60b1ecfa81e33e062ff0359e0/src/OptimalControler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5810288996248906}}
{"text": "% Assume a target positioned at x = 1, travelling with speed v = 0.1\nstate = [1;0.1;2;0;3;0.2;4;0.3];\n\n% Create an instance of a 3D Constant Velocity model\ncv = ConstantVelocityX('NumDims',4,'VelocityErrVariance',0.1);\n\n% View the transition matrix and process covariance matrices\nF = cv.feval();\nQ = cv.covar();\n\n% Predict the target's position and velocity after the interval has passed\nnewState  = cv.feval(state);\n\n% Do the same as above, but this time add process noise to the prediction\nnewState2 = cv.feval(state,true);\n\n% Generate 50 random noise samples from the dynamic model\nnoise = cv.random(50);\n\n% Check how likely the predictions we made are\nlik = cv.pdf(newState,state);\nlik2 = cv.pdf(newState2,state); % HINT: newState2 should be less likely", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Models/Transition/ConstantVelocityX/Example/example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.5810256101704863}}
{"text": "sigmoid1 = @(x) 1./(1+exp(-x));\n\nkl_tmp=zeros(1,maxiter);\nbeta_tmp=zeros(1,maxiter);\ndm_tmp=zeros(1,maxiter);\niter=0;\ndm=1;\neta=eta0;\nm=m+1e-13*randn(1,n);\nm=max(m,1e-10);\nm=min(m,1-1e-10);\nm0 = m;\nif (beta>=beta_max), beta=beta_max-1; end;\nwhile ((dm>dmmin)&&(iter<maxiter)&&(beta<beta_max)) \n\titer=iter+1;\n\tz=(1-m)./m.*diag(C)';\n\tC1=C+diag(z);\n    v=C1\\b; \n\tw1=v./m';\n\tbetaold=beta;\n\tbeta=1/(sigmay-b'*v);\n    \n    mold=m;\n    m=(1-eta)*m+eta*sigmoid1(gamma+0.5*p*beta*(w1').^2.*diag(C)');\n    m=max(m,1e-10);\n    m=min(m,1-1e-10);\n    dm=max(abs(m-mold));\n    kl_tmp(iter)=-p/2*log(beta)+beta*p/2*(v'*C*v+sum((1-m')./m'.*v.^2.*diag(C))-2*b'*v)+beta*p/2*sigmay- gamma*sum(m)+sum(m.*log(m)+(1-m).*log(1-m));\n    if iter>1 \n        dkl =(kl_tmp(iter)-kl_tmp(iter-1));\n        if dkl>1e-10,\n            eta=eta/2;\n            fprintf('\\t[%d] dkl=%e eta=%.3e, dm=%.3e\\n',iter,kl_tmp(iter)-kl_tmp(iter-1),eta,dm);\n            m=mold;\n        end\n    end\nend;\nif iter==maxiter, gamma, iter, \n\tfigure(3)\n\tplot(1:iter,kl_tmp(1:iter));\nend;\nkl1=-p/2*log(beta)+beta*p/2*(v'*C*v+sum((1-m')./m'.*v.^2.*diag(C))-2*b'*v)+beta*p/2*sigmay- gamma*sum(m)+sum(m.*log(m)+(1-m).*log(1-m));\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/vg/regression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5810059584001439}}
{"text": "function [x,y,z,s,w,flag] = squadsolve(Q,c,A,b,C),  \n%SQUADSOLVE\n% \n% USAGE:   [x,y,z,s,w,flag] = squadsolve(Q,c,A,b,C)\n%\n% PARAMETERS:  Q -> (n,n) symetric matrix (definite positive)\n%              c -> (n,1) vector\n%              A -> (m,n) matrix \n%              b -> (m,1) vector\n%              C -> scalar\n%\n%            x -> primal variables\n%            y -> lagrangian coeff of equality constraints\n%            z -> dual variables of x\n%            s -> primal auxiliary variable (only if C < Inf)\n%            w -> dual variable of s\n%            flag -> set to 0 => no problem, set to 1 => problem\n%\n% DESCRIPTION: Primal-dual method for quadratic programming\n%                \n%            minimize c'*x + 0.5*x'*Q*x\n%\n%            subject to  A*x=b\n%                        0<= x <= C\n%            The method used here is a primal dual method with a predictor-corrector\n%            approach and a logarithmic barrier. I used the heuristic from two \n%            existing methods LOQO and HOPDM. The method is an iterative method. The \n%            maximal number of iteration is stored in the variable 'max_iter'.\n%\n% ERRORS AND BUGS: there is no test about the conditionning of the matrix Q. If the iteration\n%                  50 has been reached, then the optimization may not be finished and the output\n%                  may be wrong.\n%\n% NOTES: 50 iterations have always been sufficient to solve all problems.\n%        This code should be read with the tech. report:\n%                \"Regularized Symmetric Indefinite Systems in Interior Point\n%                 Methods for Linear and Quadratic Optimization\", \n%                 A. Altman and J. Gondzio, Logilab Tech. Report 1998.6\n%\n% Andre Elisseeff, Dec. 1999\n% aelissee@eric.univ-lyon2.fr\n  \n disp('toto');\n% init    \n  verbose = 1;\n  n = size(Q,1);\n  m = size(A,1);\n  H = zeros(n+m,n+m);\n  flag=1;\n  \n% Values of the original HOPDM of Gondzio and Altmann\n  dinf = 10^(-14);\n  smallz = 10^(-14);\n  smallt = 2.3*10^(-16);  \n  opttol = 10^(-5)/C;\n  itref = 1;\n  mu = 1;\n  maxiter = 50; \n  \n% init values of the primal and dual variables\n  x=ones(n,1);\n  z=ones(n,1);\n  y=ones(m,1);\n  if C < Inf,\n    s=ones(n,1);\n    w=ones(n,1);\n  else\n    s=[];w=[];\n  end;\n% Description of variables:\n%\n%    x,s     -> primal variables\n%    z,w     -> dual variables\n%    n       -> number of variables in the initial pb (size of x)\n%    m       -> number of constraints in A\n%\n%    dinf     -> smallest value for all variables   \n%    smallz   -> smallest value of z\n%    smallt   -> smallest value for t in the computation of the matrix theta\n%    opttol   -> acceptable tolerance for optimality conditions\n%    itref    -> iteration counter\n%    maxiter  -> maximum number of iteration\n%    DEBUG    -> 0 => no debug, 1 => debug\n \n% Analyze the constraints...\n  if verbose,\n   disp(sprintf('Analyzing the equality constraints...\\n'));\n  end;\n  [QQ,RR]=qr(A',0);\n  [mm,nb] = size(QQ); %% number of eq constraints\n  ind = 1:1:nb;\n  for i=1:nb,\n    if abs(RR(i,i)) < 10^(-10),\n      disp(sprintf('Constraints %d removed because of dependence\\n',i));\n      ind(i)=0;\n    end;\n  end; \n  indice = find(ind >0);\n  \n  if (isempty(indice))\n    disp(sprintf('No equality constraints... \\n'));\n    A=[];\n    m=0;\n  else\n    A = A(indice,:); %% new independent eq constraints \n    b = b(indice);\n    y = y(indice);\n    m=length(indice);\n  end;\n  clear QQ;clear RR;\n%%%% AE : scale the problem, has been tested and seems to work\n%%%% better : more stable... \n  if C < Inf,\n    u = ones(n,1);\n    Q = Q*C;\n    b = b/C;\n    c = c;\n  end;\n% init values before looping\n  cont = 1;\n  objQ = 0.5*x'*Q*x;\n% init values of primal and dual objective functions\n  pobjo = abs(c'*x+objQ) + 1;\n  if C < inf,\n    dobjo = abs(b'*y - u'*w - objQ);\n  else\n    dobjo = abs(b'*y - objQ);\n  end;\n%%%%%%%%%%%%%%%\n%% MAIN LOOP\n%%%%%%%%%%%%%%%\n  while (cont)&(itref<=maxiter)\n  % Compute the primal objective function\n    objQ = 0.5*x'*Q*x;\n    pobj = c'*x+objQ;\n    if (C<Inf)\n        if ~isempty(A),\n            dobj = b'*y - u'*w - objQ;\n        else\n            dobj = - u'*w - objQ;\n        end;\n    else\n        if ~isempty(A),\n            dobj = b'*y - objQ;\n        else\n            dobj = - objQ;\n        end;      \n    end;\n    dlgap = pobj - dobj;\n    dp = abs(pobj)/(abs(pobjo)+1);\n    dd = abs(dobj)/(abs(dobjo)+1);\n    dobjo = dobj;\n    pobjo = pobj;\n    if verbose,\n        disp(sprintf('%d - pobj : %f - dobj : %f\\n',itref,pobj,dobj));\n    end;\n  % Check if the solution are bounded\n    if (dp > 10^6) \n      disp(sprintf('Solution not bounded in the primal. Exit.\\n'));\n      return;\n    end;\n    if (dd > 10^6) \n      disp(sprintf('Solution not bounded in the dual. Exit.\\n'));\n      return;\n    end;\n    \n  % test if optimality\n    oldgap = dlgap;\n    dp = abs(dobj) + 1;\n    if ((abs(dlgap)/dp) <= opttol)\n      if verbose,\n       disp(sprintf('Optimal solution found. Exit.\\n'));\n      end;\n      cont = 0;\n      break;\n    end;\n    \n    dp = dp + abs(pobj);\n    T = abs(dlgap)/dp;\n    \n  % put the variables away from zero (from HOPDM)\n    if (itref <= 3)\n      ax = 2*10^(-3);\n      az = 10^(-3);\n    elseif (T >= 0.8)\n      ax = 2*10^(-4);\n      az = 10^(-4);\n    elseif (T >= 0.1)\n      ax = 2*10^(-5);\n      az = 10^(-5);\n    elseif (T >=0.01)\n      ax = 2*10^(-6);\n      az = 10^(-6);\n    elseif (T>=0.001)\n      ax = 2*10^(-7);\n      az = 10^(-7);\n    elseif (T>=0.0001)\n      ax = 2*10^(-8);\n      az = 10^(-7);\n    elseif (T>=0.00001)\n      ax = 2*10^(-9);\n      az = 10^(-9);\n    else\n      ax = T*10^(-5);\n      az = ax;\n    end;\n    \n  % consider only variables that can be changed\n    x = x + ax;\n    z = z + az;\n    if C < Inf\n      s = s + ax;\n      w = w + az;\n    end;\n  % Compute the values of xi_b, xi_c and xi_u\n    if ~isempty(A),\n     xi_b = -A*x + b;    \n     xi_c = c - A'*y - z + Q*x;\n    else\n      xi_b = [];    \n      xi_c = c - z + Q*x;\n     end;\n     \n    xi_z =   - x.*z;\n    if C < Inf,\n      xi_c=xi_c + w;\n      xi_u = u - x - s;\n      xi_w =  - s.*w;\n    end;\n  % Compute theta = (z/x + w/s)\n    \n  % for bounded variables\n    if C<Inf,\n      dp = x;\n      if (max(abs(dp))<= smallz)\n        disp(sprintf('Conditioning problem to invert theta. Abort.\\n'));\n        return;\n      end;\n      dpp= s;\n      if (max(abs(dpp))<= smallz)\n        disp(sprintf('Conditioning problem to invert theta. Abort.\\n'));\n        return;\n      end;\n      theta=z./dp + w./dpp;\n    end;\n  % for unbounded variables\n    if C==Inf,\n      dp = x;\n      if (max(abs(dp))<= smallz) \n        disp(sprintf('Conditioning problem to invert theta. Abort.\\n'));\n        return;\n      end;\n      theta = z./dp;\n    end;\n     \n  % neglect small elements of theta array\n    \n    neglect = find(theta < smallt);\n    if ~isempty(neglect)\n      theta(neglect)=zeros(size(neglect));\n    end;\n    \n  % and control large elements of theta\n    \n    neglect = find(theta >= 10^8);\n    if ~isempty(neglect)\n      theta(neglect)=(10^4)*sqrt(theta(neglect));\n    end;\n  % factorize H = [-Q-theta^(-1)   A^T]\n  %               [ A               0 ]\n    \n    H = zeros(n+m,n+m);\n    H(1:n,1:n) = -Q-diag(theta);\n    H(n+1:n+m,1:n) = A;\n    H(1:n,n+1:n+m) = A';\n    \n  % Compute the predictor step\n    if C < Inf,\n      f = xi_c-xi_z./x+(xi_w - xi_u.*w)./s ;\n      h = xi_b;\n    else\n      f = xi_c - xi_z./x;\n      h = xi_b;\n    end;\n    delta=H\\[f;h];\n    dx = delta(1:n);\n    dy = delta(n+1:n+m);\n    dz = (xi_z-z.*dx)./x;\n    if C<Inf,\n      ds = xi_u - dx;\n      dw = (xi_w-w.*ds)./s;\n    end;      \n      \n % determine the maximum step size alpha_p (primal) and\n % alpha_d (dual) to stay in feasible region\n % (x,s,z,w must be positive and greater than dinf)\n      indz = find(dz<0);    \n      indx = find(dx<0);\n      inds=[];mins=1;\n      indw=[];minw=1;\n      if C < Inf,\n        inds = find(ds<0);\n        indw = find(dw<0);\n        if ~isempty(inds)\n          mins = min(-(s(inds)-dinf)./ds(inds));\n        else\n         mins = 1;\n        end;\n        if ~isempty(indw)\n          minw = min(-(w(indw)-dinf)./dw(indw));\n        else\n         minw = 1;\n        end;    \n      end;\n      if ~isempty(indx)\n        minx = min(-(x(indx)-dinf)./dx(indx));\n      else\n        minx = 1;\n      end;\n      apk = min([minx,mins,1]);\n      if ~isempty(indz),\n        minz = min(-(z(indz)-dinf)./dz(indz));\n      else\n        minz = 1;\n      end;\n      adk = min([minw,minz,1]);\n      \n      ax = sum(x.*z);\n      as = sum((x+apk*dx).*(z+adk*dz));\n      az = sum(dx.^2+dz.^2);\n      if C < Inf,\n        ax = ax + sum(s.*w);\n        as = as + sum((s+apk*ds).*(w+adk*dw));\n        az = az + sum(ds.^2+dw.^2);\n      end;\n    % check if complementary gap is less than opttol      \n      if (as <= opttol)\n        if verbose,\n            disp(sprintf('Complementary gap is less than %f\\n',opttol));\n        end;\n        cont = 0;\n        x = x + apk*dx;\n        y = y + adk*dy;\n        z = z + adk*dz;\n        if C < Inf,\n         s = s + apk*ds;\n         w = w + adk*dw;\n        end;\n        break;\n      end;\n      \n    % Set the barrier parameter : LOQO's heuristic\n      ap = min(apk,adk);\n      mu = (ax/(2*n))*(0.95*(1/ap) -1)^2/(0.95*(1/ap)+10)^2;\n      \n    % Compute the new direction (algo. of Mehrotra) of order 1 (corrector step)\n      xi_z =  - x.*z + mu*ones(size(x)) - dx.*dz;\n      f = xi_c - xi_z./x;\n      if C < Inf\n        xi_w = - s.*w + mu*ones(size(s)) - ds.*dw;\n        f=f+ xi_w./s - (w.*xi_u)./s;\n      end;\n      h = xi_b;\n      \n      delta=H\\[f;h];\n      dx = delta(1:n);\n      dy = delta(n+1:n+m);\n      dz = (xi_z-z.*dx)./x;  \n      if C<Inf,\n        ds = xi_u - dx;  \n        dw = (xi_w-w.*ds)./s;\n      end;      \n      \n      \n    % determine the maximum step size alpha_p (primal) and\n    % alpha_d (dual) to stay in feasible region\n    % (x,s,z,w must be positiv)\n      indz = find(dz<0);    \n      indx = find(dx<0);\n      if C < Inf,\n        inds = find(ds<0);\n        indw = find(dw<0);\n        if ~isempty(inds)\n          mins = min(-s(inds)./ds(inds));\n        else\n      mins=1;\n        end;\n        if ~isempty(indw)\n          minw = min(-w(indw)./dw(indw));\n        else\n      minw=1;\n        end;\n      end;\n      if ~isempty(indx)\n        minx = min(-x(indx)./dx(indx));\n      else\n        minx=1;\n      end;\n      alpha_p = min([minx,mins,1]);\n      if ~isempty(indz)\n        minz = min(-z(indz)./dz(indz));\n      else\n        minz=1;\n      end;\n      alpha_d = min([minw,minz,1]);\n      \n    % Compute step factors     \n      fp =0.9*min(alpha_p,alpha_d);\n      fd =0.9*min(alpha_d,alpha_p);    \n      x = x +fp*dx;      \n      y = y +fd*dy;\n      z= z + fd*dz;\n      if C < Inf,\n        w = w + fd*dw;\n        s = s +fp*ds;      \n      end;\n      itref=itref+1;\n  end;\n%%%%%%%%%%%%%%%%%%%%%\n%%% End of main loop\n%%%%%%%%%%%%%%%%%%%%%\n  \n    if (cont==0)\n        if verbose,\n          disp(sprintf('Optimal Solution found after %d iteration.\\n',itref));\n          disp(sprintf('Value of the objective : %f.\\n',pobj));\n        end;\n      flag=0;\n    end;\n  % rescale x and y\n    if C<Inf,\n      x= C*x;\n      %y = C*y;\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/Optimization/squadsolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5809303369873831}}
{"text": "%gaussian mixture model\n%>\n%> @param FeatureMatrix: features for all train observations (dimension iNumFeatures x iNumObservations)\n%> @param k: number of gaussians\n%> @param numMaxIter: maximum number of iterations (stop if not converged before)\n%> @param prevState: internal state that can be stored to continue clustering later\n%>\n%> @retval mu means\n%> @retval sigma standard deviations\n%> @retval state result containing internal state (if needed)\n% ======================================================================\nfunction [mu, sigma, state] = ToolGmm(V, k, numMaxIter, prevState)\n    \n    if (nargin < 3)\n        numMaxIter  = 1000;\n    end\n    if (nargin == 4)\n        state = prevState;\n    else\n        % initialize state\n        state = initState_I(V, k);\n    end\n    \n    for j = 1:numMaxIter\n        prevState = state;\n        \n        % compute weighted gaussian \n        p = computeProb_I(V, state);\n        \n        % update clusters\n        state = updateGaussians_I(V, p, state);\n         \n        % if we have converged, break\n        if (max(sum(abs(state.m-prevState.m))) <= 1e-20)\n            break;\n        end\n    end\n    \n    mu = state.m;\n    sigma = state.sigma;\nend\n\nfunction [state] = updateGaussians_I(FeatureMatrix, p, state)\n\n    % number of clusters\n    K = size(state.m, 2);\n \n    % update priors\n    state.prior = mean(p, 1)';\n\n    for k = 1:K\n        s = 0;\n        \n        % update means\n        state.m(:, k) = FeatureMatrix * p(:, k) / sum(p(:, k));\n        \n        % subtract mean\n        F = FeatureMatrix - repmat(state.m(:, k), 1, size(FeatureMatrix, 2));\n        \n        for n = 1:size(FeatureMatrix, 2)\n            s = s + p(n, k) * (F(:, n) * F(:, n)');\n        end\n        state.sigma(:, :, k) = s / sum(p(:, k));\n    end\nend\n\nfunction [p] = computeProb_I(FeatureMatrix, state)\n\n    K = size(state.m, 2);\n    p = zeros(size(FeatureMatrix, 2), K);\n    \n    % for each cluster\n    for k = 1:K\n        % subtract mean\n        F = FeatureMatrix - repmat(state.m(:, k), 1, size(FeatureMatrix, 2));\n\n        % weighted gaussian\n        p(:, k) = 1 / sqrt((2*pi)^size(F, 1) * det(state.sigma(:, :, k))) *...\n            exp(-1/2 * sum((F .* (inv(state.sigma(:, :, k)) * F)), 1)');\n        p(:, k) = state.prior(k) * p(:, k);\n    end\n    \n    % norm over clusters\n    p = p ./ repmat(sum(p, 2), 1, K);\nend\n\nfunction [state] = initState_I(FeatureMatrix, K)\n\n    %init\n    m       = zeros(size(FeatureMatrix, 1), K);\n    sigma   = zeros(size(FeatureMatrix, 1), size(FeatureMatrix, 1), K);\n    prior   = zeros(1, K);\n\n    % pick random points as cluster means\n    mIdx    = round(rand(1, K) * (size(FeatureMatrix, 2)-1)) + 1;\n \n    % assign means etc.\n    m       = FeatureMatrix(:, mIdx);\n    prior   = ones(1, K) / K;\n    sigma   = repmat(cov(FeatureMatrix'), 1, 1, K);\n\n    % write initial state\n    state   = struct('m', m, 'sigma', sigma, 'prior', prior);\nend\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/ToolGmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.580930331373872}}
{"text": "function fh = decomp_reconst_full(im,Nsc,Nor,block,noise,parent,covariance,optim,sig);\n\n% Decompose image into subbands, denoise, and recompose again.\n%\t\tfh = decomp_reconst(im,Nsc,Nor,block,noise,parent,covariance,optim,sig);\n%       covariance:\t are we considering covariance or just variance?\n%       optim:\t\t for choosing between BLS-GSM (optim = 1) and MAP-GSM (optim = 0)\n%       sig:        standard deviation (scalar for uniform noise or matrix for spatially varying noise)\n% Version using the Full steerable pyramid (2) (High pass residual\n% splitted into orientations).\n\n% JPM, Univ. de Granada, 5/02\n% Last Revision: 11/04\n\nif (block(1)/2==floor(block(1)/2))|(block(2)/2==floor(block(2)/2)),\n   error('Spatial dimensions of neighborhood must be odd!');\nend   \n\nif ~exist('parent'),\n        parent = 1;\nend\n\nif ~exist('covariance'),\n        covariance = 1;\nend\n\nif ~exist('optim'),\n        optim = 1;\nend\n\nif ~exist('sig'),\n        sig = sqrt(mean(noise.^2));\nend\n\n[pyr,pind] = buildFullSFpyr2(im,Nsc,Nor-1);\n[pyrN,pind] = buildFullSFpyr2(noise,Nsc,Nor-1);\npyrh = real(pyr);\nNband = size(pind,1)-1;\nfor nband = 2:Nband, % everything except the low-pass residual\n  fprintf('%d % ',round(100*(nband-1)/(Nband-1)))\n  aux = pyrBand(pyr, pind, nband);\n  auxn = pyrBand(pyrN, pind, nband);\n  [Nsy,Nsx] = size(aux);\n  prnt = parent & (nband < Nband-Nor);   % has the subband a parent?\n  BL = zeros(size(aux,1),size(aux,2),1 + prnt);\n  BLn = zeros(size(aux,1),size(aux,2),1 + prnt);\n  BL(:,:,1) = aux;\n  BLn(:,:,1) = auxn*sqrt(((Nsy-2)*(Nsx-2))/(Nsy*Nsx));     % because we are discarding 2 coefficients on every dimension  \n  if prnt,\n  \taux = pyrBand(pyr, pind, nband+Nor);\n    auxn = pyrBand(pyrN, pind, nband+Nor);\n    if nband>Nor+1,     % resample 2x2 the parent if not in the high-pass oriented subbands.\n\t   aux = real(expand(aux,2));\n       auxn = real(expand(auxn,2));\n    end    \n  \tBL(:,:,2) = aux;\n    BLn(:,:,2) = auxn*sqrt(((Nsy-2)*(Nsx-2))/(Nsy*Nsx)); % because we are discarding 2 coefficients on every dimension       \n  end\n  \n  sy2 = mean2(BL(:,:,1).^2);\n  sn2 = mean2(BLn(:,:,1).^2);\n  if sy2>sn2,\n     SNRin = 10*log10((sy2-sn2)/sn2);\n  else\n     disp('Signal is not detectable in noisy subband');\n  end   \n  \n  % main\n  BL = denoi_BLS_GSM_band(BL,block,BLn,prnt,covariance,optim,sig);\n  pyrh(pyrBandIndices(pind,nband)) = BL(:)';\nend\nfh = reconFullSFpyr2(pyrh,pind);\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/BLS-GSM/denoising_subprograms/decomp_reconst_full.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.580930331373872}}
{"text": "% change in body orientation\nfunction [data,units] = compute_dtheta(trx,n)\n\nflies = trx.exp2flies{n};\nnflies = numel(flies);\ndata = cell(1,nflies);\nfor i = 1:nflies,\n  fly = flies(i);\n  if trx(fly).nframes <= 1,\n    data{i} = [];\n  else\n    data{i} = modrange(diff(trx(fly).theta_mm,1,2),-pi,pi)./trx(fly).dt;\n  end\nend\nunits = parseunits('rad/s');\n\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/compute_dtheta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5809303257603607}}
{"text": "function [cd, score] = distance_metrics(model_gt, model, theta)\n\nif nargin < 3\n    theta = 0.1;\nend\n\nif ~isfield(model_gt, 'vtx')\n    [model_gt.vtx] = model_gt.vertices;\n    model_gt = rmfield(model_gt,'vertices');\n    [model_gt.mesh] = model_gt.faces;\n    model_gt = rmfield(model_gt,'faces');\nend\n\n% compare cad model\n% normalize both models\nmask = (model_gt.anchor~=0)&(model.anchor~=0);\nmean_est = mean(model.vtx(model.anchor(mask), :), 1);\nif isequal(size(model_gt.vtx,1), 36) && isequal(numel(model_gt.anchor), 8) % TODO\n    model_gt.anchor(2) = 36;\n    mean_gtr = mean(model_gt.vtx(model_gt.anchor(mask), :), 1);\nelse\n    mean_gtr = mean(model_gt.vtx(model_gt.anchor(mask), :), 1);\nend\nmodel.vtx = bsxfun(@minus, model.vtx, mean_est);\nmodel_gt.vtx = bsxfun(@minus, model_gt.vtx, mean_gtr);\n\nstd_est = mean(std(model.vtx(model.anchor(mask), :), 1, 1));\nstd_gtr = mean(std(model_gt.vtx(model_gt.anchor(mask), :), 1, 1));\nmodel.vtx = model.vtx/std_est;\nmodel_gt.vtx = model_gt.vtx/std_gtr;\n\nR = align_models(model, model_gt);\nmodel.vtx = model.vtx*R';\n\nmodel = computeMeshInfo(model);\nmodel_gt = computeMeshInfo(model_gt);\n\n% compute distance from model to target\nkdtree = KDTreeSearcher(model_gt.vtx);\n[U,~] = surfProjection(model, model_gt, kdtree);\ndist_model_target = sum(sum((model.vtx - U).^2, 2)) / size(model.vtx, 1);\n\ndist_model_target_theta = sum(sum((model.vtx - U).^2, 2) > theta)...\n    / size(model.vtx, 1);\n\n% compute distance from target to model\nkdtree = KDTreeSearcher(model.vtx);\n[U,~] = surfProjection(model_gt, model, kdtree);\ndist_target_model = sum(sum((model_gt.vtx - U).^2, 2)) / size(model_gt.vtx, 1);\n\ndist_target_model_theta = sum(sum((model_gt.vtx - U).^2, 2) > theta) ...\n    / size(model_gt.vtx, 1);\n\ncd = dist_model_target + dist_target_model;\nscore = dist_model_target_theta + dist_target_model_theta;\n", "meta": {"author": "jhonykaesemodel", "repo": "image2mesh", "sha": "839fdadf64187a3d2d3e4a84a5fa92226fccd668", "save_path": "github-repos/MATLAB/jhonykaesemodel-image2mesh", "path": "github-repos/MATLAB/jhonykaesemodel-image2mesh/image2mesh-839fdadf64187a3d2d3e4a84a5fa92226fccd668/matlab/utils/distance_metrics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5809303104282424}}
{"text": "function distance = getStructureDistance(structNum1,structNum2,planC)\n%distance = getStructureDistance.m(structNum1,structNum1,planC)\n%\n%This function returns the distance(cm) between center of masses of\n%structNum1 and structNum1\n%\n%APA, 10/08/2009\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\n%Check if plan passed, if not use global.\nif ~exist('planC')\n    global planC;\nend\nindexS = planC{end};\n\n%Compute centroid of structNum1\n[x1,y1,z1] = calcIsocenter(structNum1, 'COM', planC);\n\n%Compute centroid of structNum2\n[x2,y2,z2] = calcIsocenter(structNum2, 'COM', planC);\n\n%Compute distance between centroid1 and centroid2\ndistance = sqrt((x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2);\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/getStructureDistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.580885462808915}}
{"text": "function bw2 = hough_bin_pixels(bw, theta, rho, bin)\n%HOUGH_BIN_PIXELS Find pixels corresponding to Hough accumulator bin.\n%   BW2 = hough_bin_pixels(BW, THETA, RHO, BIN) finds the white pixels in a\n%   binary image that correspond to a particular Hough transform\n%   accumulator bin.  BW is the original binary image.  THETA and RHO are\n%   the Hough parameter vectors returned by the hough function.  BIN is a\n%   two-element vector containing the row-column coordinates of the Hough\n%   transform bin.  BW2 is a binary image containing only the white pixels\n%   in BW that contributed to the specified bin.\n%\n%   Example\n%   =======\n%   I  = imread('circuit.tif');\n%   BW = edge(I,'canny');\n%   imshow(BW)\n%   [H,theta,rho] = hough(BW);\n%   P = houghpeaks(H, 1);\n%   BW2 = hough_bin_pixels(BW, theta, rho, P);\n%   figure, imshow(BW2)\n%   title('Pixels corresponding to maximum Hough transform bin')\n%\n%   See also hough, houghlines, houghpeaks.\n\n%   Steven L. Eddins\n%   The MathWorks, Inc.\n\n[y, x] = find(bw);\nx = x - 1;\ny = y - 1;\n\ntheta_c = theta(bin(2)) * pi / 180;\nrho_xy = x*cos(theta_c) + y*sin(theta_c);\nnrho = length(rho);\nslope = (nrho - 1)/(rho(end) - rho(1));\nrho_bin_index = round(slope*(rho_xy - rho(1)) + 1);\n\nidx = find(rho_bin_index == bin(1));\n\nr = y(idx) + 1; \nc = x(idx) + 1;\n\nbw2 = false(size(bw));\n\nbw2(sub2ind(size(bw), r, c)) = true;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/12142-hough-accumulator-bin-pixels/hough_bin_pixels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.5808299015228471}}
{"text": "function [l,d,perm] = mchol(A,mu)\n% [l,d,perm] = mchol(A,mu)\n% Compute the Gill-Murray modified LDL factorization of A,\n\nif nargin < 2\n    mu = 1e-12;\nend\n\nn = size(A,1);\nl = eye(n);\nd = zeros(n,1);\nperm = 1:n;\n\nfor i = 1:n\n    c(i,i) = A(i,i);\nend\n\n% Compute modification parameters\ngamma = max(abs(diag(A)));\nxi = max(max(abs(setdiag(A,0))));\ndelta = mu*max(gamma+xi,1);\nif n > 1\n    beta = sqrt(max([gamma xi/sqrt(n^2-1) mu]));\nelse\n    beta = sqrt(max([gamma mu]));\nend\n\nfor j = 1:n\n    \n    % Find q that results in Best Permutation with j\n    [maxVal maxPos] = max(abs(diag(c(j:end,j:end))));\n    q = maxPos+j-1;\n    \n    % Permute d,c,l,a\n    d([j q]) = d([q j]);\n    perm([j q]) = perm([q j]);\n    c([j q],:) = c([q j],:);\n    c(:,[j q]) = c(:,[q j]);\n    l([j q],:) = l([q j],:);\n    l(:,[j q]) = l(:,[q j]);\n    A([j q],:) = A([q j],:);\n    A(:,[j q]) = A(:,[q j]);\n    \n    for s = 1:j-1\n        l(j,s) = c(j,s)/d(s);\n    end\n    for i = j+1:n\n        c(i,j) = A(i,j) - sum(l(j,1:j-1).*c(i,1:j-1));\n    end\n    theta = 0;\n    if j < n\n        theta = max(abs(c(j+1:n,j)));\n    end\n    d(j) = max([abs(c(j,j)) (theta/beta)^2 delta]);\n    if j < n\n        for i = j+1:n\n            c(i,i) = c(i,i) - (c(i,j)^2)/d(j);\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/minFunc/mchol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5808219687553713}}
{"text": "function [N,K,D,L,var,w_max,w_min,c1,c2,position,p_best,g_best,fitness,p_best_fit,...\n    Num_func,Min_Max_flag,Gl_Lo_flag]=initialize\nN = 50;    % N is the number of the particles\nK = 1000;  %K is the number of iteration\nvar = 5; % var is number of variables\nL = 15 ; % L is the lenght for each variable\nD = L*var; % D is the dimension of each particle\nw_min=0.1;w_max=0.6;c1=2;c2=2;% w is the inertia factor and c1 & c2 are learning factors\nposition = rand(N,D)>0.5; % Generates initial population\nfitness=0;\np_best = rand(N,D)>0.5;\ng_best = rand(N,D)>0.5;\np_best_fit = ones(N,1);\nNum_func = 1 ; % Select the number of function to be evaluated\nMin_Max_flag = 1 ;  % 1 if the function must be minimized  ....  2 if the function must be maximized\nGl_Lo_flag = 1  ;   % 1 if the search is global ...............  2 if the search is local\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/32522-nbpso-new-binary-particle-swarm-optimization-algorithm/NBPSO/initialize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5808219618822873}}
{"text": "% Version 1.000\n%\n% Code provided by Ruslan Salakhutdinov and Geoff Hinton\n%\n% Permission is granted for anyone to copy, use, modify, or distribute this\n% program and accompanying programs and documents for any purpose, provided\n% this copyright notice is retained and prominently displayed, along with\n% a note saying that the original programs are available from our\n% web page.\n% The programs and documents are distributed without any warranty, express or\n% implied.  As the programs were written for research purposes only, they have\n% not been tested to the degree that would be advisable in any important\n% application.  All use of these programs is entirely at the user's own risk.\n\n% This program fine-tunes an autoencoder with backpropagation.\n% Weights of the autoencoder are going to be saved in mnist_weights.mat\n% and trainig and test reconstruction errors in mnist_error.mat\n% You can also set maxepoch, default value is 200 as in our paper.  \n\nmaxepoch=200;\nfprintf(1,'\\nFine-tuning deep autoencoder by minimizing cross entropy error. \\n');\nfprintf(1,'60 batches of 1000 cases each. \\n');\n\nload mnistvh\nload mnisthp\nload mnisthp2\nload mnistpo \n\nmakebatches;\n[numcases numdims numbatches]=size(batchdata);\nN=numcases; \n\n%%%% PREINITIALIZE WEIGHTS OF THE AUTOENCODER %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nw1=[vishid; hidrecbiases];\nw2=[hidpen; penrecbiases];\nw3=[hidpen2; penrecbiases2];\nw4=[hidtop; toprecbiases];\nw5=[hidtop'; topgenbiases]; \nw6=[hidpen2'; hidgenbiases2]; \nw7=[hidpen'; hidgenbiases]; \nw8=[vishid'; visbiases];\n\n%%%%%%%%%% END OF PREINITIALIZATIO OF WEIGHTS  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nl1=size(w1,1)-1;\nl2=size(w2,1)-1;\nl3=size(w3,1)-1;\nl4=size(w4,1)-1;\nl5=size(w5,1)-1;\nl6=size(w6,1)-1;\nl7=size(w7,1)-1;\nl8=size(w8,1)-1;\nl9=l1; \ntest_err=[];\ntrain_err=[];\n\n\nfor epoch = 1:maxepoch\n\n%%%%%%%%%%%%%%%%%%%% COMPUTE TRAINING RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nerr=0; \n[numcases numdims numbatches]=size(batchdata);\nN=numcases;\n for batch = 1:numbatches\n  data = [batchdata(:,:,batch)];\n  data = [data ones(N,1)];\n  w1probs = 1./(1 + exp(-data*w1)); w1probs = [w1probs  ones(N,1)];\n  w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)];\n  w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs  ones(N,1)];\n  w4probs = w3probs*w4; w4probs = [w4probs  ones(N,1)];\n  w5probs = 1./(1 + exp(-w4probs*w5)); w5probs = [w5probs  ones(N,1)];\n  w6probs = 1./(1 + exp(-w5probs*w6)); w6probs = [w6probs  ones(N,1)];\n  w7probs = 1./(1 + exp(-w6probs*w7)); w7probs = [w7probs  ones(N,1)];\n  dataout = 1./(1 + exp(-w7probs*w8));\n  err= err +  1/N*sum(sum( (data(:,1:end-1)-dataout).^2 )); \n  end\n train_err(epoch)=err/numbatches;\n\n%%%%%%%%%%%%%% END OF COMPUTING TRAINING RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%% DISPLAY FIGURE TOP ROW REAL DATA BOTTOM ROW RECONSTRUCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%\nfprintf(1,'Displaying in figure 1: Top row - real data, Bottom row -- reconstructions \\n');\noutput=[];\n for ii=1:15\n  output = [output data(ii,1:end-1)' dataout(ii,:)'];\n end\n   if epoch==1 \n   close all \n   figure('Position',[100,600,1000,200]);\n   else \n   figure(1)\n   end \n   mnistdisp(output);\n   drawnow;\n\n%%%%%%%%%%%%%%%%%%%% COMPUTE TEST RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n[testnumcases testnumdims testnumbatches]=size(testbatchdata);\nN=testnumcases;\nerr=0;\nfor batch = 1:testnumbatches\n  data = [testbatchdata(:,:,batch)];\n  data = [data ones(N,1)];\n  w1probs = 1./(1 + exp(-data*w1)); w1probs = [w1probs  ones(N,1)];\n  w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)];\n  w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs  ones(N,1)];\n  w4probs = w3probs*w4; w4probs = [w4probs  ones(N,1)];\n  w5probs = 1./(1 + exp(-w4probs*w5)); w5probs = [w5probs  ones(N,1)];\n  w6probs = 1./(1 + exp(-w5probs*w6)); w6probs = [w6probs  ones(N,1)];\n  w7probs = 1./(1 + exp(-w6probs*w7)); w7probs = [w7probs  ones(N,1)];\n  dataout = 1./(1 + exp(-w7probs*w8));\n  err = err +  1/N*sum(sum( (data(:,1:end-1)-dataout).^2 ));\n  end\n test_err(epoch)=err/testnumbatches;\n fprintf(1,'Before epoch %d Train squared error: %6.3f Test squared error: %6.3f \\t \\t \\n',epoch,train_err(epoch),test_err(epoch));\n\n%%%%%%%%%%%%%% END OF COMPUTING TEST RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n tt=0;\n for batch = 1:numbatches/10\n fprintf(1,'epoch %d batch %d\\r',epoch,batch);\n\n%%%%%%%%%%% COMBINE 10 MINIBATCHES INTO 1 LARGER MINIBATCH %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n tt=tt+1; \n data=[];\n for kk=1:10\n  data=[data \n        batchdata(:,:,(tt-1)*10+kk)]; \n end \n\n%%%%%%%%%%%%%%% PERFORM CONJUGATE GRADIENT WITH 3 LINESEARCHES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  max_iter=3;\n  VV = [w1(:)' w2(:)' w3(:)' w4(:)' w5(:)' w6(:)' w7(:)' w8(:)']';\n  Dim = [l1; l2; l3; l4; l5; l6; l7; l8; l9];\n\n  [X, fX] = minimize(VV,'CG_MNIST',max_iter,Dim,data);\n\n  w1 = reshape(X(1:(l1+1)*l2),l1+1,l2);\n  xxx = (l1+1)*l2;\n  w2 = reshape(X(xxx+1:xxx+(l2+1)*l3),l2+1,l3);\n  xxx = xxx+(l2+1)*l3;\n  w3 = reshape(X(xxx+1:xxx+(l3+1)*l4),l3+1,l4);\n  xxx = xxx+(l3+1)*l4;\n  w4 = reshape(X(xxx+1:xxx+(l4+1)*l5),l4+1,l5);\n  xxx = xxx+(l4+1)*l5;\n  w5 = reshape(X(xxx+1:xxx+(l5+1)*l6),l5+1,l6);\n  xxx = xxx+(l5+1)*l6;\n  w6 = reshape(X(xxx+1:xxx+(l6+1)*l7),l6+1,l7);\n  xxx = xxx+(l6+1)*l7;\n  w7 = reshape(X(xxx+1:xxx+(l7+1)*l8),l7+1,l8);\n  xxx = xxx+(l7+1)*l8;\n  w8 = reshape(X(xxx+1:xxx+(l8+1)*l9),l8+1,l9);\n\n%%%%%%%%%%%%%%% END OF CONJUGATE GRADIENT WITH 3 LINESEARCHES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n end\n\n save mnist_weights w1 w2 w3 w4 w5 w6 w7 w8 \n save mnist_error test_err train_err;\n\nend\n\n\n\n", "meta": {"author": "qiuwch", "repo": "DeepLearning", "sha": "60508ffd8c39a085375eec82e576f446d1318bc9", "save_path": "github-repos/MATLAB/qiuwch-DeepLearning", "path": "github-repos/MATLAB/qiuwch-DeepLearning/DeepLearning-60508ffd8c39a085375eec82e576f446d1318bc9/backprop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5808219544198789}}
{"text": "function [ signal_filter2 ] = medianfilter_is( signal, fs )\n% [signal_filter2] = medianfilter_is( signal, fs )\n%   OVERVIEW:   This function estimates the baseline wander signal in the ECG and returns the estimate in the signal_filter2 variable\n%\n%\tINPUT: \tMANDATORY:\n%               signal          : a single row of ECG data in samples.\n%\n%               fs              : sampling frequency for the ecg signal (Hz)\n%\n%\n%   \tOUTPUT:\n%            \tsignal_filter2     : baseline wander estimate for the ecg in var signal.\n%\n%\n%\tREPO:\n%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n%   ORIGINAL SOURCE AND AUTHORS:\n%       Written by Ismail Sadiq\n%\tCOPYRIGHT (C) 2019\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. The license may be found in the Documents \n%       folder of the Physionet-Cardiovascular-Signal-Toolbox.\n\norderfilter1 = floor(0.2 * fs);\norderfilter2 = floor(0.6 * fs);\n\nsignal_filter1 = medfilt1(signal, orderfilter1);\nsignal_filter2 = medfilt1(signal_filter1, orderfilter2);\n\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/ECG_Analysis_Tools/MV/Tools/MVM/medianfilter_is.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5807898832877848}}
{"text": "function c=mapcolor(d,map,clim)\n% Usage: c=mapcolor(d,[map],[clim])\n% Given an array \"d\", mapcolor uses the colormap \"map\" to assign a color to\n% each entry in \"d\", returning the results as RGB triplets in \"c\". Provide\n% a two-element vector \"clim\" to impose limits on the colormap. Basically \n% this does exactly what Matlab's built-in colormaps do, but does not \n% affect the \"Colormap\" property of the current figure--so you can use\n% multiple colormaps on the same figure. See also mapcolorbar.m. \n%\n%   Example:\n%      load clown\n%      mylim=[min(X(:)) max(X(:))];\n%      Xhot=mapcolor(X,hot,mylim);\n%      subplot(211);\n%      imagesc(Xhot);\n%      mapcolorbar(hot,mylim);\n%      Xjet=mapcolor(X,jet,mylim);\n%      subplot(212);\n%      imagesc(Xjet);\n%      mapcolorbar(jet,mylim);\n\n% Written 29 April 2010 by Douglas H. Kelley, dhk [at] dougandneely.com.\n\nmapdefault=jet(256); % specifying a size prevents a figure from popping up\n\nif nargin<1\n    error(['Usage: c = ' mfilename '(d,[map],[clim])'])\nend\nif ~exist('map','var') || isempty(map)\n    map=mapdefault;\nelseif ischar(map)\n    warning(['MATLAB:' mfilename ':mapIsString'], ...\n        ['Map given as a string; attempting to evaluate ''' map '''.'])\n    map=eval(map);\nend\nif ~exist('clim','var') || isempty(clim)\n    clim=[min(d(:)) max(d(:))];\nend\n\nN=numel(d);\nNN=size(d);\nmapsize=size(map,1);\nbinnum=floor( mapsize/diff(clim)*(d-clim(1))+1 ); % A linear mapping...\nbinnum(isnan(binnum))=1; % ...setting NaNs to the mininum of the map, ...\nbinnum(binnum<1)=1; % ...then correcting for saturation at bottom...\nbinnum(binnum>mapsize)=mapsize; % ...and top.\nif isvector(d)\n    c=nan*ones(N,3);\n    for ii=1:N\n        c(ii,:)=map(binnum(ii),:);\n    end\nelseif ndims(d)==2\n    c=nan*ones([size(d) 3]);\n    [i,j]=ind2sub(NN,[1:N]);\n    for ii=1:N\n        c(i(ii),j(ii),:)=map(binnum(ii),:);\n    end\nelse\n    error(['Sorry, mapcolor does not support arrays of dimension '...\n        'greater than two.'])\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/31063-mapcolor-easily-apply-mulitple-colormaps-on-the-same-figure/mapcolor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.5807444312431098}}
{"text": "function [ranks, sortingInds, isTied] = prtUtilRank(ds)\n% prtUtilRank - Ranks the vector in increasing magnitude\n%   Ties have a rank of the middle of the tied ranks\n%   NaNs have a rank of NaN\n% \n% prtUtilRank([1 2 2 4 5 inf nan nan]')\n\n\n\n\n\n\n\nif ~isnumeric(ds) \n    if isa(ds,'prtDataSetBase')\n        ds = ds.getObservations();\n    else\n        error('prt:prtUtilRank','Input must be either a numerical vector or a prtDataSet containing 1 feature.')\n    end\nend\n\nif isvector(ds)\n    ds = ds(:);\nend\n\nassert(size(ds,2)==1,'prtUtilRank is only for 1 dimensional data');\n\n[sortedDS, sortingInds] = sort(ds);\n\nranks = (1:length(sortedDS))';\n\nif length(sortedDS) > 1\n    isTiedWithNext = cat(1,sortedDS(1:(end-1)) == sortedDS(2:end),false);\nelse\n    isTiedWithNext = false;\nend\n\n% If there are any ties we need to figure out the tied regions and set each\n% of the ranks to the average of the tied ranks.\ntieRegions = [];\nif any(isTiedWithNext)\n    diffIsTiedWithNext = diff(isTiedWithNext);\n    \n    if isTiedWithNext(1) % First one is tied\n        diffIsTiedWithNext = cat(1,1,diffIsTiedWithNext);\n    else\n        diffIsTiedWithNext = cat(1,0,diffIsTiedWithNext);\n    end\n\n    % Start and stop regions of the ties\n    tieRegions = cat(2,find(diffIsTiedWithNext==1),find(diffIsTiedWithNext==-1));\n\n    for iRegion = 1:size(tieRegions,1);\n        cInds = tieRegions(iRegion,1):tieRegions(iRegion,2);\n        \n        ranks(cInds) = mean(ranks(cInds));\n    end\nend\n    \nranks(isnan(sortedDS)) = nan;\n\nranks(sortingInds) = ranks;\n\nif nargout > 2\n    % We asked for the isTied vector\n    isTied = false(size(ds));\n    for iRegion = 1:size(tieRegions,1);\n        isTied(tieRegions(iRegion,1):tieRegions(iRegion,2)) = true;\n    end\n    isTied(sortingInds) = isTied;\nend\n\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/util/prtUtilRank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.5807444271986315}}
{"text": "% Copyright (C) 2008   Sylvain Pelissier   <sylvain.pelissier@gmail.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 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, see <http://www.gnu.org/licenses/>.\n\n% -*- texinfo -*-\n% @deftypefn {Function File} {[@var{yout}] =} bohmanwin(@var{xin},@var{h}),@var{p},@var{q})\n%\tUpsample, filter and downsample a signal.\n% @seealso{rectwin,  bartlett}\n% @end deftypefn\n\nfunction yout = upfirdn(xin,h,p,q)\n\nif(nargin < 2)\n  error('usage : yout = upfirdn(xin,h,p,q)');\nend\n\t\nif(nargin < 3)\n\tp = 1;\n\tq = 1;\nend\n\t\nif(nargin < 4)\n\tq = 1;\nend\n\t\nif(floor(p) ~= p || floor(q) ~= q || p < 1 || q < 1)\n\terror('p and q must be positive integer');\nend\n\t\nyout = upsample(xin,p);\nyout = convn(yout, h).*p; % original was filter(h, 1, yout);\n% the scaling with p is needed as per github issue 2085, causing the output\n% to be scaled by the value of p, with this change, the compat/matlab\n% versions will give an output that is about equal (scaled with about 0.9993)\nyout = downsample(yout,q);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/signal/upfirdn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.5807444189625726}}
{"text": "function triangulation_test27 ( )\n\n%*****************************************************************************80\n%\n%% TEST27 tests TRIANGULATION_ORDER6_VERTEX_COUNT.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    24 August 2006\n%\n%  Author:\n%\n%    John Burkardt\n%  \n  dim_num = 2;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST27\\n' );\n  fprintf ( 1, '  TRIANGULATION_ORDER6_VERTEX_COUNT counts the \\n' );\n  fprintf ( 1, '  vertex nodes and midside nodes in\\n' );\n  fprintf ( 1, '  an order 6 triangulation.\\n' );\n\n  [ node_num, triangle_num, hole_num ] = ...\n    triangulation_order6_example1_size ( );\n\n  [ node_xy, triangle_node, triangle_neighbor ] = ...\n    triangulation_order6_example1 ( node_num, triangle_num );\n\n  [ vertex_num, midside_num ] = triangulation_order6_vertex_count ( ...\n    node_num, triangle_num, triangle_node );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of nodes         = %d\\n', node_num );\n  fprintf ( 1, '  Number of vertex nodes  = %d\\n', vertex_num );\n  fprintf ( 1, '  Number of midside nodes = %d\\n', midside_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/triangulation/triangulation_test27.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5806930136656893}}
{"text": "function p=v_mos2pesq(m)\n%V_MOS2PESQ convert MOS speech quality scores to PESQ p=(m)\n%Inputs:    m  is a matrix of MOS scores\n%\n%Outputs:   p  is a matrix, the same size as m, of PESQ 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_mos2pesq.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    p=(log(b./(m-a)-1)-d)/c;\nelse\n    if nargin<1 || isempty(m)\n        pp=linspace(-0.5,4.5,100);\n        mm=v_pesq2mos(pp);\n    else\n        mm=m;\n    end\n    p=v_mos2pesq(mm);\n    plot(mm,p);\n    ylabel('PESQ (P.862)');\n    xlabel('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_mos2pesq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5806725684793722}}
{"text": "function [x, infos] = snpa(V, num_col, in_options)\n% Successive Nonnegative Projection Algorithm (variant with f(.) = ||.||^2)\n%\n%       At each step of the algorithm, the column of X maximizing ||.||_2 is \n%       extracted, and X is updated with the residual of the projection of its \n%       columns onto the convex hull of the columns extracted so far. \n%\n% Inputs:\n%       matrix      V\n%       num_col     number of columns to be extracted.\n%       options     options\n%           normalization: 1: scale the columns of X so that they sum to one,\n%                           hence matrix H will satisfy the assumption above for any\n%                           nonnegative separable matrix X. \n%                          0: the default value for which no scaling is\n%                           performed. For example, in hyperspectral imaging, this \n%                           assumption is already satisfied and normalization is not\n%                           necessary.\n%\n% Output:\n%       w           solution of w\n%           K        : index set of the extracted columns. \n%           H        : optimal weights, that is, H = argmin_{Y >= 0} ||X-X(:,K)Y||_F\n%       infos       information\n%\n% References:\n%       N. Gillis, \n%       \"Successive Nonnegative Projection Algorithm for Robust Nonnegative Blind Source Separation,\" \n%       SIAM J. on Imaging Sciences 7 (2), \n%       pp. 1420-1450, 2014.\n%    \n%\n% This file is part of NMFLibrary.\n%\n% This file has been ported from \n%   SNPA.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. 21, 2022 (Hiroyuki Kasai): Added initialization module.\n%\n\n\n    % set dimensions and samples\n    [m, n] = size(V);\n \n    % set local options\n    local_options = []; \n    local_options.disp_freq = 1;    \n    local_options.normalize = 0;\n    local_options.relerr = 1e-6;\n    local_options.inner_max_epoch = 500;\n    local_options.inner_nnls_alg = 'fpgm';\n    local_options.special_stop_condition = @(epoch, infos, options, stop_options) spna_stop_func(epoch, infos, options, stop_options);       \n    \n    % check input options\n    if ~exist('in_options', 'var') || isempty(in_options)\n        in_options = struct();\n    end      \n    % merge options\n    options = mergeOptions(get_nmf_default_options(), local_options);   \n    options = mergeOptions(options, in_options);\n    \n    % initialize\n    method_name = 'SNPA';    \n    i = 0; \n    grad_calc_count = 0;\n    stop_options = [];        \n\n    if options.verbose > 0\n        fprintf('# %s: started ...\\n', method_name);           \n    end      \n\n    % initialize for this algorithm\n    options.max_epoch = num_col+1;    \n    if options.normalize == 1\n        % normalize the columns of V of which colum is L1-norm = 1\n        V = normalize_W(V, 1);\n    end\n\n    U = zeros(m, num_col);\n    K = zeros(1, num_col);\n    H = zeros(num_col, n);    \n    normV0 = sum(V.^2); \n    nVmax = max(normV0); \n    normR = normV0; \n    VtUK = []; \n    UKtUK = [];\n\n    % set for nnls subsolver\n    nnls_options = [];\n    nnls_options.verbose = 0;\n    nnls_options.inner_max_epoch = options.inner_max_epoch;\n    nnls_options.algo = options.inner_nnls_alg;    \n     \n    % store initial info\n    clear infos;\n    [infos, f_val, optgap] = store_nmf_info(V, eye(m), V, [], options, [], i, grad_calc_count, 0);\n    \n    if options.verbose > 1\n        fprintf('%s: Epoch = 0000, cost = %.16e, optgap = %.4e\\n', method_name, f_val, optgap); \n    end     \n         \n    % set start time\n    start_time = tic();\n\n    % main loop\n    i = i + 1;\n    while true\n\n        % check stop condition\n        stop_options.normR = normR;\n        stop_options.nVmax = nVmax;        \n        [stop_flag, reason, max_reached_flag] = check_stop_condition(i, infos, options, stop_options);\n        if stop_flag\n            display_stop_reason(i, infos, options, method_name, reason, max_reached_flag);\n            break;\n        end        \n        \n        % select the column of the residual R with largest l2-norm\n        [a, ~] = max(normR); \n        \n        % check ties up to 1e-6 precision\n        b = find((a-normR)/a <= 1e-6); \n        \n        % In case of a tie, select column with largest norm of the input matrix X \n        if length(b) > 1\n            [~, d] = max(normX0(b)); \n            b = b(d); \n        end\n        \n        % update the index set, and extracted column\n        K(i) = b; \n        U(:, i) = V(:, b); \n        \n        % update MtUJ\n        VtUK = [VtUK, V' * U(:, i)]; \n        \n        % update UJtUJ\n        if i == 1\n            UtUi = [];\n        else\n            UtUi = U(:, 1:i-1)' * U(:, i); \n        end \n        UKtUK = [UKtUK, UtUi ; UtUi', U(:, i)' * U(:, i)]; \n        \n        % update residual \n        if i == 1\n            % Fast gradient method for min_{y in Delta} ||M(:, i)-M(:,J)y||\n            [H, ~, ~, ~] = nnls_solver(V, V(:, K(1:i)), nnls_options);   \n        else\n            H(:, K(i)) = 0; \n            h = zeros(1,n); h(K(i)) = 1; \n            H = [H; h]; \n            nnls_options.init = H; \n            [H, ~, ~, ~] = nnls_solver(V, V(:, K(1:i)), nnls_options);               \n        end\n        \n        % update the norm of the columns of the residual without computing it explicitely. \n        if i == 1\n            normR = normV0 - 2 * ((VtUK') .* H) + (H .* (UKtUK*H));\n        else\n            normR = normV0 - 2 * sum((VtUK') .* H) + sum(H .* (UKtUK*H));\n        end\n        \n        % measure elapsed time\n        elapsed_time = toc(start_time);        \n        \n        % measure gradient calc count\n        grad_calc_count = grad_calc_count + m*n;     \n\n        % update epoch\n        i = i + 1;        \n        \n        % store info\n        infos = store_nmf_info(V, U(:, 1:i-1), H, [], options, infos, i-1, grad_calc_count, elapsed_time);          \n        \n        % display info\n        display_info(method_name, i-1, infos, options);\n\n    end\n    \n    x.K = K;\n    x.U = U;\n    x.H = H;   \n\nend\n\n\nfunction [stop_flag, reason, rev_infos] = spna_stop_func(epoch, infos, options, stop_options)\n\n    stop_flag = false;\n    reason = [];\n    rev_infos = [];\n  \n    normR = stop_options.normR;\n    nVmax = stop_options.nVmax;\n\n    if sqrt(max(normR)/nVmax) < options.relerr \n        stop_flag = true;\n        reason = sprintf('precision reached: sqrt(max(normR)/nVmax) = %.4e < options.relerr = %.4e\\n', sqrt(max(normR)/nVmax), options.relerr);\n        return;        \n    end\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/separable/snpa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.58067255209676}}
{"text": "function V_RF  = yuweiA1\n\nglobal Vn H Nrf Nt Nk \nV_RF = ones(Nt,Nrf);\n\nfor k = 1:Nk\n    F(:,:,k) = H(:,:,k)'*H(:,:,k);\nend\nF = sum(F,3)/Nk;\ng = 1/Nrf/Nt;\na = g/Vn;\n\nfor Nloop = 1:10\n    for j = 1:Nrf\n        VRF = V_RF;\n        VRF(:,j)=[];\n        C = eye(Nrf-1)+a*VRF'*F*VRF;\n        G = a*F-a^2*F*VRF*C^(-1)*VRF'*F;\n        for i = 1:Nt\n            for l = 1:Nt\n                if i~=l\n                    x(l)=G(i,l)*V_RF(l,j);\n                end\n            end\n            n = sum(x);\n            if n ==0\n                V_RF(i,j)=1;\n            else\n                V_RF(i,j)=n/abs(n);\n            end\n        end\n    end\nend", "meta": {"author": "Zzhaoxingyu", "repo": "hybrid-beamforming-for-three-scenes", "sha": "396ae70db7dd464a65458f274a65aa113ed73c8b", "save_path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes", "path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes/hybrid-beamforming-for-three-scenes-396ae70db7dd464a65458f274a65aa113ed73c8b/broadband/Alogorithms/Yuwei2016/yuweiA1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5806445804785278}}
{"text": "%ROC Receiver-Operator Curve\n% \n%   E = ROC(B,C,N)\n%\n% INPUT\n%   A  Dataset\n%   W  Trained classifier, or\n%   B  Classification result, B = A*W*CLASSC\n%   C  Index of desired class (default: C = 1)\n%   N  Number of points on the Receiver-Operator Curve (default: 100)\n%\n% OUTPUT\n%   E  Structure containing the error of the two classes\n%\n% DESCRIPTION\n% Computes N points on the receiver-operator curve of the classifier W for\n% class C in the labeled dataset B, which is typically the result of\n% B = A*W; or for the dataset A labelled by applying the (cell array of)\n% trained classifiers W.\n%\n% Note that a Receiver-Operator Curve is related to a specific class (class C)\n% for which the errors are plotted horizontally. The total error on all other\n% classes is plotted vertically. The class index C refers to its position in\n% the label list of the dataset (A or B). It can be found by GETCLASSI.\n%\n% The curve is computed for N thresholds of the posteriori probabilities\n% stored in B. The resulting error frequencies for the two classes are\n% stored in the structure E. E.XVALUES contains the errors in the first\n% class, E.ERROR contains the errors in the second class. In multi-class\n% problems these are the mean values in a single class, respectively the\n% mean values in all other classes. This may not be very useful, but not\n% much more can be done as for multi-class cases the ROC is equivalent to a\n% multi-dimensional surface.\n%\n% Use PLOTE(E) for plotting the result. In the plot the two types of error\n% are annotated as 'Error I' (error of the first kind) and 'Error II' (error\n% of the second kind). All error estimates are weighted according the class\n% prior probabilities. Remove the priors in A or B (by setprior(A,[])) to\n% produce a vanilla ROC.\n%\n% EXAMPLES\n%\tTrain set A and test set T:\n%\t  B = T*NMC(A); E = ROC(T,50); PLOTE(E); % Plots a single curve\n%\t  E = ROC(T,A*{NMC,UDC,QDC});  PLOTE(E); % Plots 3 curves\n%\n\nfunction [roc, thr] = roc_detection(a,n)\n\n\t% Depending on the call, CLAS may the third or second argument.\n\t% and N the third or the fourth.\n\t\n\tif nargin < 2 || isempty(n), n = 100; end\n\t\n\tdatname = getname(a);\n\tlablist = getlablist(a,'string');\n    \n    required_labs = {'FP' 'TP'};\n    aux_lablist = intersect(cellstr(lablist), required_labs );\n\n    cant_required_labs = length(required_labs);\n\n    if( length(aux_lablist) ~= cant_required_labs )\n        fprintf(2, ['Esta funcion esta pensada para usarse en datasets de deteccion con labels:\\n' colvec([char(required_labs) repmat('\\n', cant_required_labs, 1)]')' ] );\n        error();\n    end\n    \n    clas = find( strcmpi(cellstr(lablist), 'TP') );\n\tclasname = lablist(clas,:);\n\t%DXD: also check the class sizes:\n\tcs = classsizes(a);\n\tif any(cs == 0)\n\t\terror('Ambas clases deben contener ejemplos');\n\tend\n\n\t% Set up the ROC structure.\n\n\n    % If a cell array of classifiers was given, apply each one here.\n\n    a = a*normm; % make sure we have a normalised classification matrix\n\n    [m,c] = size(a); \n    nlab = getnlab(a); \n    d = sort(a(:));\n\n    % Attempt to compute a good threshold range on the first classified\n    % dataset.\n%     thr = [max(0, min(d)-eps) rowvec(d(round(linspace(2,length(d)-1, n-1)))) 1];\n    thr = linspace(0,1,n+1);\n\n    % NLAB_OUT will be one where B is larger than THR.\n    I = matchlablist(getlablist(a),getfeatlab(a)); % Correct possible changes class orders\n    nlab_out = (repmat(+a(:,I(clas)),1,n+1) >= repmat(thr,m,1));\n\n    % aciertos will be 1 where the numeric label is unequal to NLAB_OUT\n    % (i.e., where errors occur).\n    bTP = nlab == clas;\n    aciertos = (repmat(bTP,1,n+1) == nlab_out);\n\n    sensitivity = mean(aciertos(bTP,:),1); % S\n    pospred = sum(aciertos(bTP,:)) ./ sum(nlab_out); % +P\n\n    roc = [ colvec(sensitivity) colvec(pospred) ];\n  \n    mod = sqrt(sum(roc.^2,2));\n    [max_mod max_mod_idx] = max(mod);\n    \n    figure(100);\n    h = subplot(1,2,1);\n    plot(h(1), sensitivity(:), pospred(:), 'bo-' )\n    hold(h(1), 'on');\n    plot(h(1), sensitivity(max_mod_idx), pospred(max_mod_idx), 'rx:', 'MarkerSize',11)\n    plot(h(1), sensitivity(max_mod_idx), pospred(max_mod_idx), 'mo:', 'MarkerSize',11)\n    hold(h(1), 'off');\n    axis(h(1), 'square');\n    box(h(1), 'off')\n    xlabel(h(1), 'Sensitivity')\n    ylabel(h(1), 'Positive predictivity')\n%     x_lim = xlim();\n%     y_lim = ylim();\n%     xlim([min([x_lim ylim]) 1.1]);\n%     xlim([min([x_lim ylim]) 1.1]);\n    \n    h(2) = subplot(1,2,2);\n    plot(h(2), thr, mod, 'bo-' )\n    hold(h(2), 'on');\n    plot(h(2), thr(max_mod_idx), mod(max_mod_idx), 'rx', 'MarkerSize',11)\n    plot(h(2), thr(max_mod_idx), mod(max_mod_idx), 'mo', 'MarkerSize',11)\n    plot(h(2), [0.5 0.5], ylim(), 'k--')\n    hold(h(2), 'off');\n    box(h(2), 'off')\n    ylabel(h(2), 'mod(S,P+)')\n    xlabel(h(2), 'Operating point')\n\n    ConfusionMat = [ sum(aciertos(~bTP,max_mod_idx))  sum(~aciertos(~bTP,max_mod_idx)); sum(~aciertos(bTP,max_mod_idx)) sum(aciertos(bTP,max_mod_idx)) ];\n    \n    DisplayResults('dsResult', ConfusionMat, 'SupportDataset', a);\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_addins/roc_detection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410784, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5806348197509951}}
{"text": "function [ x, seed ] = square01_sample ( n, seed )\n\n%*****************************************************************************80\n%\n%% SQUARE01_SAMPLE samples points in the unit square in 2D.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    18 January 2014\n%\n%  Author:\n%\n%    John Burkardt\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  [ x, seed ] = r8mat_uniform_01 ( m, n, seed );\n\n  return\nend\n", "meta": {"author": "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_integrals/square01_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.5806348181523621}}
{"text": "function [D, matches] = run_icp_fixed(M, N, C_init, max_iters)\n\nverbose = 1;\n\nif verbose\n    fprintf('Running ICP...\\n');\nend\n\nann_params = struct;\n% ann_params.algorithm = 'linear'; %use 'kmeans' for some speedup\n% ann_params.trees = 8;\n% ann_params.checks = 64;\n% ann_params.centers_init = 'kmeanspp';\n% ann_params.iterations = -1;\n\nkN = size(N.evecs,1);\n\n% flann_search(target, query)\n[matches, dists] = flann_search(C_init*M.evecs', N.evecs', 1, ann_params);\n% [matches, dists] = knnsearch(N.S*N.evecs, M.S*M.evecs*C_init');\n\nerr = sum(sqrt(dists));\nerr = err / (kN*size(C_init,1));\n\nif verbose\n    fprintf('(0) MSE: %.2e\\n', err);\nend\n\nif max_iters == 0\n    D = C_init;\n%     matches = matches';\n    return\nend\n\n% Start iterations\n\nD_prev = C_init;\nerr_prev = err;\nmatches_prev = matches;\n\n% vidx = 2:4;\n% figure, plot_cloud([],N.evecs(:,vidx),'b.'); axis equal; hold on; plot_cloud([],M.evecs(:,vidx),'r.');\n% figure, plot_cloud([],N.evecs(:,vidx),'b.'); axis equal; hold on; pp = M.evecs*C_init';plot_cloud([],pp(:,vidx),'r.');\n\n% [u,~,v] = svd(C_init);\n% D = u*v';\n\nfor i=1:max_iters\n    \n%     if i>1\n        [U,~,V] = svd((M.evecs(matches,:)'*M.S(matches,matches)) * (N.S*N.evecs));\n        D = U * V(:,1:size(C_init,2))';\n        D = D';\n%     end\n    \n%     figure, plot_cloud([],N.evecs(:,vidx),'b.'); axis equal; hold on; pp = M.evecs*D';plot_cloud([],pp(:,vidx),'r.');\n    \n    %     matches = flann_search(M.evecs', D*N.evecs', 1, ann_params);\n    [matches, dists] = flann_search(D*M.evecs', N.evecs', 1, ann_params);\n%     [matches, dists] = knnsearch(N.S*N.evecs, M.S*M.evecs*D');\n    err = sum(sqrt(dists));\n    err = err / (kN*size(C_init,1));\n    \n    if verbose\n        fprintf('(%d) MSE: %.2e\\n', i, err);\n    end\n    \n    if err > err_prev\n        if verbose\n            fprintf('Local optimum reached.\\n');\n        end\n        D = D_prev;\n        matches = matches_prev;\n        break;\n    end\n    \n    if (err_prev - err) < 5e-6\n        if verbose\n            fprintf('Local optimum reached.\\n');\n        end\n        break;\n    end\n    \n    err_prev = err;\n    D_prev = D;\n    matches_prev = matches;\n    \nend\n\n% matches = matches';\n\nend\n", "meta": {"author": "OshriHalimi", "repo": "unsupervised_learning_of_dense_shape_correspondence", "sha": "440643d633a6db3f947ac71a247c8083cb3aeadc", "save_path": "github-repos/MATLAB/OshriHalimi-unsupervised_learning_of_dense_shape_correspondence", "path": "github-repos/MATLAB/OshriHalimi-unsupervised_learning_of_dense_shape_correspondence/unsupervised_learning_of_dense_shape_correspondence-440643d633a6db3f947ac71a247c8083cb3aeadc/Tools/demo_upscaling/tools/run_icp_fixed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5806348151388073}}
{"text": "% SCRIPT TEST FOR THE KUKA LBR ROBOT KINEMATICS\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 <http://www.gnu.org/licenses/>.\nrobot = load_robot('KUKA', 'LBR_IIWA_R820_COP');\nclose all\n\n% test both solutions: based on the transpose an on the Moore-Penrose\nq = pi/8*[1,1,1,1,1,1,1]';\nq = [0.1 0.2 .3 .4 .5 .6 .7];\ndrawrobot3d(robot, q)\nJ = manipulator_jacobian(robot, q);\n\n% rigth\nR = J'*inv(J*J');\n\n% left\nL=inv(J'*J)*J';\n\nM = pinv(J)\n\nR-L\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/KUKA/LBR_IIWA_R820_COP/moore_penrose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5806029561993498}}
{"text": "function linplus_test50 ( )\n\n%*****************************************************************************80\n%\n%% TEST50 tests R8PO_FA, R8PO_SL.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 March 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 10;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST50\\n' );\n  fprintf ( 1, '  R8PO_FA factors a positive definite symmetric\\n' );\n  fprintf ( 1, '    linear system,\\n' );\n  fprintf ( 1, '  R8PO_SL solves a factored system.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Matrix order N = %d\\n', n );\n\n  for i = 1 : n\n    for j = 1 : n\n      a(i,j) = min ( i, j );\n    end\n  end\n%\n%  Set the desired solution.\n%\n  x = r8vec_indicator ( n );\n%\n%  Compute the corresponding right hand side.\n%\n  b = r8po_mxv ( n, a, x );\n%\n%  Factor the matrix.\n%\n  [ a_lu, info ] = r8po_fa ( n, a );\n\n  if ( info ~= 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Fatal error!\\n' );\n    fprintf ( 1, '  R8PO_FA declares the matrix is singular!\\n' );\n    fprintf ( 1, '  The value of INFO is %d\\n', info );\n    return\n  end\n%\n%  Solve the linear system.\n%\n  x = r8po_sl ( n, a_lu, b );\n \n  r8vec_print ( n, x, '  Solution:' );\n%\n%  Set the desired solution.\n%\n  x(1:n) = 1;\n%\n%  Compute the corresponding right hand side, using the factored matrix.\n%\n  b = r8po_ml ( n, a, x );\n%\n%  Solve the linear system.\n%\n  x = r8po_sl ( n, a, b );\n \n  r8vec_print ( n, x, '  Solution:' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/linplus_test50.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.5805902015541918}}
{"text": "%% Finding contours in an image\n% We learn how to find contours of objects in our image.\n%\n% In this sample you will learn how to use the following OpenCV functions:\n%\n% * <matlab:doc('cv.findContours') cv.findContours>\n% * <matlab:doc('cv.drawContours') cv.drawContours>\n%\n% Sources:\n%\n% * <https://docs.opencv.org/3.1.0/df/d0d/tutorial_find_contours.html>\n% * <https://github.com/opencv/opencv/blob/3.1.0/samples/cpp/tutorial_code/ShapeDescriptors/findContours_demo.cpp>\n%\n\nfunction varargout = findContours_demo_gui(im)\n    % load source image\n    if nargin < 1\n        src = imread(fullfile(mexopencv.root(),'test','HappyFish.jpg'));\n    elseif ischar(im)\n        src = imread(im);\n    else\n        src = im;\n    end\n\n    % Convert image to gray and blur it\n    if size(src,3) == 3\n        src = cv.cvtColor(src, 'RGB2GRAY');\n    end\n    src = cv.blur(src, 'KSize',[3 3]);\n\n    % create the UI\n    h = buildGUI(src);\n    if nargout > 0, varargout{1} = h; end\nend\n\nfunction onChange(~,~,h)\n    %ONCHANGE  Event handler for UI controls\n\n    % retrieve current values from UI controls\n    thresh = round(get(h.slid, 'Value'));\n    set(h.txt, 'String',sprintf('Canny thresh: %3d',thresh));\n\n    % Detect edges using canny\n    canny_output = cv.Canny(h.src, [thresh thresh*2], 'ApertureSize',3);\n\n    % Find contours\n    [contours, hierarchy] = cv.findContours(canny_output, ...\n        'Mode','Tree', 'Method','Simple');\n\n    % Draw contours\n    drawing = zeros([size(canny_output) 3], 'uint8');\n    for i=1:numel(contours)\n        clr = randi([0 255], [1 3], 'uint8');\n        drawing = cv.drawContours(drawing, contours, ...\n            'Hierarchy',hierarchy, 'ContourIdx',i-1, 'MaxLevel',0, ...\n            'Color',clr, 'Thickness',2, 'LineType',8);\n    end\n\n    % show result\n    set(h.img, 'CData',drawing);\n    drawnow;\nend\n\nfunction h = buildGUI(img)\n    %BUILDGUI  Creates the UI\n\n    % parameters\n    thresh = 100;\n    max_thresh = 255;\n    sz = size(img);\n    sz(2) = max(sz(2), 250);  % minimum figure width\n\n    % build the user interface (no resizing to keep it simple)\n    h = struct();\n    h.src = img;\n    h.fig = figure('Name','Contours Demo', ...\n        'NumberTitle','off', 'Menubar','none', 'Resize','off', ...\n        'Position',[200 200 sz(2) sz(1)+29]);\n    if ~mexopencv.isOctave()\n        %HACK: not implemented in Octave\n        movegui(h.fig, 'center');\n    end\n    h.ax = axes('Parent',h.fig, 'Units','pixels', 'Position',[1 30 sz(2) sz(1)]);\n    if ~mexopencv.isOctave()\n        h.img = imshow(img, 'Parent',h.ax);\n    else\n        %HACK: https://savannah.gnu.org/bugs/index.php?45473\n        axes(h.ax);\n        h.img = imshow(img);\n    end\n    h.txt = uicontrol('Parent',h.fig, 'Style','text', 'FontSize',11, ...\n        'Position',[5 5 130 20], 'String',sprintf('Canny thresh: %3d',thresh));\n    h.slid = uicontrol('Parent',h.fig, 'Style','slider', 'Value',thresh, ...\n        'Min',0, 'Max',max_thresh, 'SliderStep',[1 10]./(max_thresh-0), ...\n        'Position',[135 5 sz(2)-135-5 20]);\n\n    % hook event handlers, and trigger default start\n    set(h.slid, 'Callback',{@onChange,h}, ...\n        'Interruptible','off', 'BusyAction','cancel');\n    onChange([],[],h);\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/findContours_demo_gui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.5805901890772213}}
{"text": "function days = ymd_dif_common ( y1, m1, d1, y2, m2, d2 )\n\n%*****************************************************************************80\n%\n%% YMD_DIF_COMMON gets the day difference between two Common YMD dates.\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 Y1, M1, D1, the first YMD date.\n%\n%    Input, integer Y2, M2, D2, the second YMD date.\n%\n%    Output, integer DAYS, the number of days between the dates.\n%\n  days = 0;\n%\n%  Check the dates.\n%\n  [ y1, m1, d1, ierror ] = ymd_check_common ( y1, m1, d1 );\n\n  if ( ierror ~= 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'YMD_DIF_COMMON - Fatal error!\\n' );\n    fprintf ( 1, '  Y1/M1/D1 is illegal.\\n' );\n    error ( 'YMD_DIF_COMMON - Fatal error!' );\n  end\n\n  [ y2, m2, d2, ierror ] = ymd_check_common ( y2, m2, d2 );\n\n  if ( ierror ~= 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'YMD_DIF_COMMON - Fatal error!\\n' );\n    fprintf ( 1, '  Y2/M2/D2 is illegal.\\n' );\n    error ( 'YMD_DIF_COMMON - Fatal error!' );\n  end\n\n  jed1 = ymd_to_jed_common ( y1, m1, d1 );\n\n  jed2 = ymd_to_jed_common ( y2, m2, d2 );\n\n  days = round ( jed2 - jed1 );\n\n  return\nend\n", "meta": {"author": "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_dif_common.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.5805901845914304}}
{"text": "function [err, g] = metric_logssd(vol_fix, voldef, dvol)\n    vol_diff = voldef - vol_fix;\n    vdsq = vol_diff.^2;\n    err = log(1 + sum(sum(sum(vdsq)))) * dvol;\n    g = 2 * vol_diff ./ (1 + vdsq) * dvol;\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_metrics/metric_logssd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5805900473607156}}
{"text": "function [disp_row, disp_col, sind] = resp_newton(response, responsef, iterations, ky, kx, use_sz)\n\n[max_resp_row, max_row] = max(response, [], 1);\n[init_max_response, max_col] = max(max_resp_row, [], 2);\nmax_row_perm = permute(max_row, [2 3 1]);\ncol = max_col(:)';\nrow = max_row_perm(sub2ind(size(max_row_perm), col, 1:size(response,3)));\n\ntrans_row = mod(row - 1 + floor((use_sz(1)-1)/2), use_sz(1)) - floor((use_sz(1)-1)/2);\ntrans_col = mod(col - 1 + floor((use_sz(2)-1)/2), use_sz(2)) - floor((use_sz(2)-1)/2);\ninit_pos_y = permute(2*pi * trans_row / use_sz(1), [1 3 2]);\ninit_pos_x = permute(2*pi * trans_col / use_sz(2), [1 3 2]);\nmax_pos_y = init_pos_y;\nmax_pos_x = init_pos_x;\n\n% pre-compute complex exponential\nexp_iky = exp(bsxfun(@times, 1i * ky, max_pos_y));\nexp_ikx = exp(bsxfun(@times, 1i * kx, max_pos_x));\n\n% gradient_step_size = gradient_step_size / prod(use_sz);\n\nky2 = ky.*ky;\nkx2 = kx.*kx;\n\niter = 1;\nwhile iter <= iterations\n    % Compute gradient\n    ky_exp_ky = bsxfun(@times, ky, exp_iky);\n    kx_exp_kx = bsxfun(@times, kx, exp_ikx);\n    y_resp = mtimesx(exp_iky, responsef, 'speed');\n    resp_x = mtimesx(responsef, exp_ikx, 'speed');\n    grad_y = -imag(mtimesx(ky_exp_ky, resp_x, 'speed'));\n    grad_x = -imag(mtimesx(y_resp, kx_exp_kx, 'speed'));\n    ival = 1i * mtimesx(exp_iky, resp_x, 'speed');\n    H_yy = real(-mtimesx(bsxfun(@times, ky2, exp_iky), resp_x, 'speed') + ival);\n    H_xx = real(-mtimesx(y_resp, bsxfun(@times, kx2, exp_ikx), 'speed') + ival);\n    H_xy = real(-mtimesx(ky_exp_ky, mtimesx(responsef, kx_exp_kx, 'speed'), 'speed'));\n    det_H = H_yy .* H_xx - H_xy .* H_xy;\n    \n    % Compute new position using newtons method\n    max_pos_y = max_pos_y - (H_xx .* grad_y - H_xy .* grad_x) ./ det_H;\n    max_pos_x = max_pos_x - (H_yy .* grad_x - H_xy .* grad_y) ./ det_H;\n    \n    % Evaluate maximum\n    exp_iky = exp(bsxfun(@times, 1i * ky, max_pos_y));\n    exp_ikx = exp(bsxfun(@times, 1i * kx, max_pos_x));\n    \n    iter = iter + 1;\nend\nmax_response = 1 / prod(use_sz) * real(mtimesx(mtimesx(exp_iky, responsef, 'speed'), exp_ikx, 'speed'));\n\n% check for scales that have not increased in score\nind = max_response < init_max_response;\nmax_response(ind) = init_max_response(ind);\nmax_pos_y(ind) = init_pos_y(ind);\nmax_pos_x(ind) = init_pos_x(ind);\n\n[max_scale_response, sind] = max(max_response(:));\ndisp_row = (mod(max_pos_y(1,1,sind) + pi, 2*pi) - pi) / (2*pi) * use_sz(1);\ndisp_col = (mod(max_pos_x(1,1,sind) + pi, 2*pi) - pi) / (2*pi) * use_sz(2);\nend", "meta": {"author": "lifeng9472", "repo": "STRCF", "sha": "68c062d4aa7083b8721e37ce19d92497c8dc4de3", "save_path": "github-repos/MATLAB/lifeng9472-STRCF", "path": "github-repos/MATLAB/lifeng9472-STRCF/STRCF-68c062d4aa7083b8721e37ce19d92497c8dc4de3/implementation/resp_newton.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5805900423530912}}
{"text": "function Xsol=Bouguet2Devernay()\n%\n% J. Huai 19 jul 2014\nclear all\nclose all\nload H:\\relaylatest\\toolbox_calib\\calib_casios\\Calib_Results.mat\naddpath H:\\relaylatest\\EKF_monoSLAM_1pRANSAC\\matlab_code\\matlabcalibration2ourcalibration\\TOOLBOX_calib;\n% for the test case of casio 2\n\ncam.nRows = 720;\ncam.nCols = 1280;\ncam.fx= fc(1);\ncam.fy= fc(2);\ncam.cx= cc(1);\ncam.cy= cc(2);\nXini =0.99; %-kc(1)*5;\n\n% Image size\nnCols = cam.nCols;\nnRows = cam.nRows;\n\n% Step for the image grid\ninc = round(min(nCols,nRows)/30); \n% Image grid\n[u_grid,v_grid] = meshgrid(3*inc:inc:nCols-3*inc,3*inc:inc:nRows-3*inc);\n[nGrid,mGrid] = size(u_grid);\nuv_d = [reshape(u_grid,1, nGrid*mGrid); reshape(v_grid,1,nGrid*mGrid)];\n\nxy_u = normalize(uv_d,fc,cc,kc,alpha_c);\n\n% Non-linear minimization, minimizes the error in the image grid between the\n% Bouguet's calibration model and the one we use in our code. Xsol should\n% return the calibration parameters for our code in the following order:\n% omega, fx, fy, cx, cy. \nXsol = lsqnonlin('matlab2Devernay_error',...\n    Xini,0,1,...\n    optimset('LargeScale','on','Display','Iter','TolFun',1e-9),cam, uv_d,xy_u)", "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/Bouguet2Devernay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.6477982179521105, "lm_q1q2_score": 0.5805900387627804}}
{"text": "function [all] = VBA_classification(X,y,k,verbose,options,sparse)\n% performs binary classification using VBA\n% function [pv,stat,df,all] = VBA_classification(X,y,k,verbose,options)\n% In brief, this function fits the following logistic regresion model:\n%   p(y=1) = s(X*beta)\n% where y is the binary data, s is the standard sigmoid mapping, X is the\n% design matrix and beta are unknown weight parameters.\n% Statistical testing is performed using cross-validation scheme, such that\n% the p-value computes the probability of the test score under the null H0.\n% In cross-validation, the test score is the binary accuracy outcome\n% sampled across test sets. The null distribution accounts for potential\n% imbalance in the data in that the first-order moment of the corresponding\n% binomial distribution is specified in terms of the sample mean of the\n% data. VBA_classification uses a k-fold cross-validation scheme, which\n% involves partitioning the data into k subsamples of equal size, each of\n% which is used as the test set in turn.\n% Note: VBA_classification also performs a fully Bayesian model inversion\n% on the entire dataset (full-data inversion).\n% IN:\n%   - X: nXp design matrix\n%   - y: nX1 binary data matrix\n%   - k: the number of folds for the k-fold cross-validation scheme. If k\n%   is set to n (default), then VBA_classification uses a leave-one-out\n%   scheme. If k is set to 0, then the cross-validation scheme is entirely\n%   skipped (only the full-data inversion is performed).\n%   - verbose: flag for displaying results (default is 0)\n%   - options: structure containing VBA's options (can be used for passing,\n%   e.g., priors on classification weight parameters)\n%   - sparse: when sparse=1, VBA_classification uses sparsifying priors\n%   (default=0).\n% OUT:\n%   - all: structure array with fields:\n%       .stat: structure of summary statistics:\n%           .pv: classical p-value on classifier accuracy\n%           .success: nx1 vector of successful classifications\n%           .pa: cross-validation prediction accuracy\n%           .bpa: balanced prediction accuracy\n%           .pBayes: Bayesian exceedance prob. on prediction accuracy\n%       .P: pxk matrix of estimated classification weights\n%       .r: data imbalance (r=0.5 means balanced data)\n%       .in: structure storing the inputs to VBA_classification\n%       .date: date stamp\n%       .dt: computing time\n%       .handles: a structure containing the handles of the graphical\n%       objects (filled-in by VBA_classication_display.m)\n% Note: cross-validation results can be displayed using the following\n% command line: VBA_classification_display(all).\n\n% fill in default I/O\ntStart = tic;\nall = [];\n[n,m] = size(y);\n[n0,p] = size(X);\n\ntry,k;catch,k=n;end\ntry,verbose;catch,verbose=0;end\ntry % check whether VBA's options structure has been sepecified\n    options;\ncatch\n    options = [];\nend\ntry % use sparsify tansform?\n    sparse = ~~sparse(1);\ncatch\n    sparse = 0;\nend\n\n% check basic numerical requirements\ntry\n    if VBA_isWeird (y)\n        disp('Error: data contains weird values!')\n        return\n    end\nend\nif ~ VBA_isBinary (y)\n    disp('Error: data should be binary!')\n    return\nend\nif ~isequal(n,n0)\n    disp('Error: design matrix has to have as many rows as the data matrix!')\n    return\nend\nif ~isequal(m,1)\n    disp('Error: data should be a nx1 vector!')\n    return\nend\nif k>n || k<0\n    disp('Warning: number of folds reduced to data length!')\n    k = n;\nend\n\n\n% randomly re-order the data (for k-fold partitioning)\nif k ~= n\n    io = randperm(n);\n    y = y(io);\n    X = X(io,:);\nend\n\n% specify options and priors for VBA inversion\ndim.p = n;\ndim.n_t = 1;\ndim.n_phi = p;\ndim.n_theta = 0;\ndim.n = 0;\ng_fname = @g_classif0;\noptions.sources = struct('type',1,'out',1);\noptions.DisplayWin = 0;\noptions.verbose = 0;\noptions.inG.X = X';\noptions.inG.sparse = sparse;\noptions.n0 = 0; % number of dummy counts\n\nif ~isequal(k,0) % performing cross-validation scheme\n    if verbose\n        disp(' ')\n        fprintf(1,'Performing k-folds cross-validation scheme...')\n        fprintf(1,'%6.2f %%',0)\n        et0 = clock; % get time\n    end\n    sizeFolds = floor(n./k);\n    acc = zeros(n,1); % test accuracy\n    acc0 = zeros(n,1); % training accuracy\n    Eg = zeros(n,1); % out-of-sample prediction E[y] (on test data)\n    Vg = zeros(n,1); % out-of-sample prediction V[y] (on test data)\n    P = zeros(p,k);\n    for i=1:k\n        if i<k\n            itest = (i-1)*sizeFolds+1:i*sizeFolds;\n        else % last test fold contains all remaining data\n            itest = (i-1)*sizeFolds+1:n;\n        end\n        options.isYout = zeros(n,1);\n        options.isYout(itest) = 1;\n        [posterior,out] = VBA_NLStateSpaceModel(y,[],[],g_fname,dim,options);\n        Eg(itest) = out.suffStat.gx(itest);\n        Vg(itest) = out.suffStat.vy(itest);\n        ytest = Eg(itest)>=0.5;\n        acc(itest) = [y(itest)==ytest];  \n        acc0(itest) = out.fit.acc;\n        if sparse\n            P(:,i) = VBA_sparsifyPrior (posterior.muPhi);\n        else\n            P(:,i) = posterior.muPhi;\n        end\n        if verbose\n            fprintf(1,repmat('\\b',1,8))\n            fprintf(1,'%6.2f %%',floor(100*i/k))\n        end\n    end\n    if verbose\n        fprintf(1,repmat('\\b',1,8))\n        fprintf(1,[' OK (took ',num2str(etime(clock,et0)),' seconds).'])\n        fprintf(1,'\\n')\n    end\nend\n\n% performing full-data inversion\nif verbose\n    fprintf(1,'Performing whole-data inversion...')\n    et0 = clock; % get time\nend\noptions.isYout = zeros(n,1);\n[posterior,out] = VBA_NLStateSpaceModel(y,[],[],g_fname,dim,options);\nif verbose\n    fprintf(1,[' OK (took ',num2str(etime(clock,et0)),' seconds).'])\n    fprintf(1,'\\n')\nend\n\n% wrap-up\nall.in.X = X;\nall.in.y = y;\nall.in.k = k;\nall.in.sparse = sparse;\nall.date = clock;\nall.dt = toc(tStart);\nall.posterior = posterior;\nall.out = out;\nif ~isequal(k,0)\n    r = mean(y);\n    if r<0.5\n        r = 1-r;\n    end\n    nok = sum(acc);\n    [pdf0,cdf0] = VBA_binomial(nok,n,r);\n    all.stat.pv = 1 - cdf0; % classical p-value on classifier accuracy\n    all.stat.success = acc; % nx1 vector of successful classifications\n    all.stat.pa = nok./n; % cross-validation prediction accuracy\n    all.stat.bpa = 0.5*(sum(acc.*y)./sum(y) + sum(acc.*(1-y))./sum(1-y)); % balanced class. acc.\n    all.stat.pBayes = VBA_PPM(nok+options.n0,n-nok+options.n0,r,'beta',0); % Bayesian exceedance prob.\n    all.Eg = Eg;\n    all.Vg = Vg;\n    all.P = P; % set of estimated weights (for each k-fold)\n    all.r = r; % data imbalance (r=0.5 means balanced data)\n    if verbose\n        [all] = VBA_classification_display(all);\n    end\nend\n\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/modules/classification/VBA_classification.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5805900369676247}}
{"text": "%% This file is the PDE simulation file of Belousov-Zhabotinsky reaction.\n% Coded By: K\n% Last Updated: 2019/06/24\n%%\nfunction [rhs,x_t,z_t,s_t,u_t,x,z,s,u,x_x,z_x,s_x,u_x,x_y,z_y,s_y,u_y,x_xx,z_xx,s_xx,u_xx,x_yy,z_yy,s_yy,u_yy,x_lap,z_lap,s_lap,u_lap]=...\n    BZ_Reaction_PDE(t,xzsut,Kx,Kxx,Ky,Kyy,K22,n,N,Dx,Dz,Ds,Du,q,f,ksi,alpha,beta,gama,ksi2,ksi3,phi,NeedDev)\n\n% Calculate u and v terms\nxt=reshape((xzsut(1:N)),n,n);\nzt=reshape((xzsut((N+1):(2*N))),n,n);\nst=reshape((xzsut(2*N+1:3*N)),n,n);\nut=reshape((xzsut((3*N+1):(4*N))),n,n);\n\nx=real(ifft2(xt));\nz=real(ifft2(zt));\ns=real(ifft2(st));\nu=real(ifft2(ut));\n\n% Reaction Terms\nxtrhs=reshape((fft2(  (1/ksi)*( f.*z.*(q-x)./(q+x) + x - x.^2 - beta*x + s )  )),N,1);\nztrhs=reshape((fft2(  x - z - alpha*z + gama*u  )),N,1);\nstrhs=reshape((fft2(  (1/ksi2)*(beta*x - s + phi*u )  )),N,1);\nutrhs=reshape((fft2(  (1/ksi3)*(alpha*z - gama*u )  )),N,1);\n\n\nrhs=[-(Dx/Dx)*K22.*xzsut(1:N)+xtrhs\n     -(Dz/Du)*K22.*xzsut(N+1:2*N)+ztrhs\n     -(Ds/Du)*K22.*xzsut(2*N+1:3*N)+strhs\n     -(Du/Du)*K22.*xzsut(3*N+1:4*N)+utrhs\n     ];\n\n % If you don't need to extract the value, don't run the following code to\n % speed up\nif NeedDev==1\n    % Get the derivative you want\n    x_x=real(ifft2(reshape((1j*Kx).*xzsut(1:N),n,n)));\n    z_x=real(ifft2(reshape((1j*Kx).*xzsut(N+1:2*N),n,n)));\n    s_x=real(ifft2(reshape((1j*Kx).*xzsut(2*N+1:3*N),n,n)));\n    u_x=real(ifft2(reshape((1j*Kx).*xzsut(3*N+1:4*N),n,n)));\n    %\n    x_y=real(ifft2(reshape((1j*Ky).*xzsut(1:N),n,n)));\n    z_y=real(ifft2(reshape((1j*Ky).*xzsut(N+1:2*N),n,n)));\n    s_y=real(ifft2(reshape((1j*Ky).*xzsut(2*N+1:3*N),n,n)));\n    u_y=real(ifft2(reshape((1j*Ky).*xzsut(3*N+1:4*N),n,n)));\n    %\n    x_xx=real(ifft2(reshape((1j*Kxx).^2.*xzsut(1:N),n,n)));\n    z_xx=real(ifft2(reshape((1j*Kxx).^2.*xzsut(N+1:2*N),n,n)));\n    s_xx=real(ifft2(reshape((1j*Kxx).^2.*xzsut(2*N+1:3*N),n,n)));\n    u_xx=real(ifft2(reshape((1j*Kxx).^2.*xzsut(3*N+1:4*N),n,n)));\n    %\n    x_yy=real(ifft2(reshape((1j*Kyy).^2.*xzsut(1:N),n,n)));\n    z_yy=real(ifft2(reshape((1j*Kyy).^2.*xzsut(N+1:2*N),n,n)));\n    s_yy=real(ifft2(reshape((1j*Kyy).^2.*xzsut(2*N+1:3*N),n,n)));\n    u_yy=real(ifft2(reshape((1j*Kyy).^2.*xzsut(3*N+1:4*N),n,n)));\n    %\n    x_t=real(ifft2(reshape(rhs(1:N),n,n)));\n    z_t=real(ifft2(reshape(rhs(N+1:2*N),n,n)));\n    s_t=real(ifft2(reshape(rhs(2*N+1:3*N),n,n)));\n    u_t=real(ifft2(reshape(rhs(3*N+1:4*N),n,n)));\n    %\n    x_lap=real(ifft2(reshape(-K22.*xzsut(1:N),n,n)));\n    z_lap=real(ifft2(reshape(-K22.*xzsut(N+1:2*N),n,n)));\n    s_lap=real(ifft2(reshape(-K22.*xzsut(2*N+1:3*N),n,n)));\n    u_lap=real(ifft2(reshape(-K22.*xzsut(3*N+1:4*N),n,n)));\n    \n    \nend\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\n\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Implicit-PDE/BZ_Reaction/Functions/BZ_Reaction_PDE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5804855666179154}}
{"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%==============================================================================\n%\n% Tutorial for FAIR: midpoint quadrature rule for 2D spline\n%\n%==============================================================================\n\nclear, close all, help(mfilename)\n\nomega = [0,6,0,8]; I = 36; T = zeros(6,8); T(3,4) = 1; h = []; Q = [];\npsi = @(xc) splineInter(T,omega,xc);\nfor j=1:10,\n  m    = 2^j*[1,1]; \n  h(j) = prod((omega(2:2:end)-omega(1:2:end))./m); \n  xc   = getCellCenteredGrid(omega,m); \n  Q(j) = h(j)*sum(psi(xc));\nend;\nfigure(1); clf; p1=semilogx(h/h(1),Q+eps,'kx',h/h(1),Q,'k-');\nfigure(2); clf; p2=loglog(h/h(1),abs(I-Q)+eps,'kx',h/h(1),abs(I-Q),'k-');\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/E6_quadrature_Spline2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5804855548014142}}
{"text": "function noise = heavisideNoiseParamInit(noise, y)\n\n% HEAVISIDENOISEPARAMINIT Heaviside classification model's parameter initialisation.\n\n% IVM\n\nif nargin > 1\n  nClass1 = sum(y==1);\n  nClass2 = sum(y==-1);\n  noise.bias = invCumGaussian(nClass1./(nClass2+nClass1));  \n  noise.numProcess = size(y, 2);\nelse\n  noise.bias = zeros(1, noise.numProcess);\nend\n\nnoise.eta = 0.01;\nnoise.nParams = length(noise.bias) + length(noise.eta);\n  ", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/noise/heavisideNoise/heavisideNoiseParamInit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5804855505541114}}
{"text": "function K = cotmatrix3(V,T)\n  % COTMATRIX3 computes cotangent matrix for 3D tetmeshes, area/mass terms\n  % already cancelled out: laplacian mesh operator \n  %\n  % This is distinctly NOT following definition that\n  % appears in the appendix of: ``Interactive Topology-aware Surface\n  % Reconstruction,'' by Sharf, A. et al\n  % http://www.cs.bgu.ac.il/~asharf/Projects/InSuRe/Insure_siggraph_final.pdf\n  %\n  % Instead it is a purely geometric construction. Find more details in Section\n  % 1.1 of \"Algorithms and Interfaces for Real-Time Deformation of 2D and 3D\n  % shapes\" [Jacobson 2013]\n  %\n  % ND derivation given in \"A MONOTONE FINITE ELEMENT SCHEME FOR\n  % CONVECTION-DIFFUSION EQUATIONS\" [Xu & ZIKATANOV 1999]\n  %\n  % 3D derivation given in \"Aspects of unstructured grids and finite-volume\n  % solvers for the Euler and Navier-Stokes equations\" [Barth 1992]\n  %\n  % K = cotmatrix(V,T)\n  % Inputs:\n  %   V  #V x 3 matrix of vertex coordinates\n  %   T  #T x 4  matrix of indices of tetrahedral corners\n  % Output:\n  %   K  #V x #V matrix of cot weights \n  %\n  % Copyright 2011, Alec Jacobson (jacobson@inf.ethz.ch)\n  %\n  % See also cotmatrix\n  %\n  warning('Deprecated. Call cotmatrix directly.');\n  K = cotmatrix(V,T);\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/cotmatrix3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5804855491328126}}
{"text": "% book : Signals and Systems Laboratory with MATLAB  \n% authors : Alex Palamides & Anastasia Veloni\n\n\n% Discrete Fourier Transform  properties\n\n\n% symmetry\n\nx=[1 2 3 4 5];\nXk=dft(x)\n\nk=0:4\nN=5\nR=Xk(1+mod(N-k,N))\nXnk=conj(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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/7/c75c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5804855434642108}}
{"text": "function sF = unimodal(varargin)\n% defines a unimodal spherical function\n%\n% Syntax\n%\n%   sF = S2Fun.unimodal\n%   sF = S2Fun.unimodal('halfwidth',10*degree)\n%\n%   v = vector3d(1,1,1)\n%   psi = S2DeLaValleePoussinKernel('halfwidth',20*degree)\n%   sF = S2Fun.unimodal(v,psi)\n%\n% Input\n%  v - symmetry axis @vector3d \n%  psi - @S2Kernel\n%\n% Output\n%  sF - @S2FunHarmonic\n%\n\n\n% extract kernel\npsi = S2DeLaValleePoussinKernel('halfwidth',get_option(varargin,'halfwidth',25*degree));\npsi = getClass(varargin,'S2Kernel',psi);\n\n% define a radially symmetric function\nbw = psi.bandwidth;\n\n% 1 3 5  7  9 11 13\n% 1 3 7 13 21 31 43 \n\n% the indice of diagonal\nl = 0:bw; l = 1+l.^2+l;\n\nf_hat = zeros((2*bw+1)^2,1);\nf_hat(l) = psi.A ./ sqrt(2*l+1);\n\nsF = S2FunHarmonic(f_hat);\n\nv = getClass(varargin,'vector3d',vector3d.Z);\n\nif angle(v,vector3d.Z) > 0 \n  rot = rotation.map(v,vector3d.Z);\n  sF = rot * sF;\nend\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/S2Fun/@S2Fun/unimodal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.580469165582289}}
{"text": "function [u,dudx,dudp] = u_Fourier(x,P,t,in)\n% input function for free-form (Fourier decomposition) deterministic DCM\n% function [u,dudx,dudp] = u_Fourier(x,P,t,in)\n% IN:\n%   - x: [useless]\n%   - P: nW*nuX1 vector of Fourier projection parameters, where nW is the\n%   number of Fourier basis functions and nu is the dimensionality of the\n%   output\n%   - t: time at which the Fourier basis set is evaluated\n%   - in: user-defined structure containing the set of Fourier frequencies\n% OUT:\n%   - u: the nuXnt matrix of outputs, where nt is the length of the\n%   argument t.\n%   - dudx: [useless]\n%   - dudp: gradient wrt the parameters\n\n% construct Fourier basis at time t\nX = zeros(length(in.W),length(t));\nfor i = 1:length(t)\n    X(:,i) = cos(in.W(:).*pi.*t(i)./in.T);\nend\n\n% project basis onto input space\nP = reshape(P,length(in.W),[]);\nu = (X'*P)';\n\n% get gradients\ndudx = [];\ndudp = kron(eye(size(P,2)),X);", "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/DCM/u_Fourier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5804691597941163}}
{"text": "clear\n        % Memorarea timpului pornirii programului\nt0=clock;\n\t\t% Prealocarea vectorului y\ny=zeros(50001,1);\n\t\t% Initializarea unui contor de ciclu\nn=0;\n\t\t% Executarea ciclului for\nfor t=0:0.001:50\n\tn=n+1;\n\ty(n)=sin(t);\nend\n\t\t% Calcularea timpului parcurs de la \n\t\t% pornirea programului\ndurata=etime(clock,t0)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8416-widely-used-programming-environments-in-electrical-engineering-matlab/10/Ex_10_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5804360278759982}}
{"text": "%% Apparently it must be here!\n% Written by Ali Akbar Eftekhari\n% All rights reserved.\n%\n% Redistribution and use in source and binary forms, with or\n% without modification, are permitted provided that the following\n% conditions are met:\n%\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\n%         copyright notice, this list of conditions and the following\n%         disclaimer in the documentation and/or other materials provided\n%         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,\n% THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n% PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n% 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,\n% OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n% LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nclc; clear; close all;\n%% create a mesh and visualize it\n% The first part of this demo shows you how to create a mesh and visualize\n% it. The aim of the visualization is to introduce you to the mesh\n% structure.\n% Here, we are going to create and visualize a 1D uniform equidistant mesh\n% and show the cell centers with a 'o' marker and the face of each cell\n% with a '+' marker.\n% We start by defining the length of the domain:\nL = 1.0; % length of the domain\n%%\n% Then we define the number of cells in the domain:\n%\nNx = 10; % number of cells in the domain\n%%\n% Now we call createMesh1D, one of the functions from a group of createMesh*\n% functions:\n%\nm = createMesh1D(Nx, L);\n%%\n% This function generates a structure which keeps the domain and grid\n% information, which will be used by almost every other function in the\n% FVMtool.\n%\n% In general, 1D, 2D, 3D, 1D radial (axial symetry), and 2D cylindrical\n% grids can be constructed. For more information, type\n%%\n%\n%   help createMesh2D\n%   help createMesh3D\n%   help createMeshCylindrical1D\n%   help createMeshCylindrical2D\n%\n%%\n% Now, let's have a look at the structure of the created mesh:\n%\ndisp(m);\n%%\n% You can easily get more information about this structure by typing\n%%\n%   help createMesh1D\n%\n%%\n% As an example, we use the position of the cell centers to visualize the\n% domain, the cells, and the interfaces between them:\n%\nfigure(2);\nplot(m.cellcenters.x, ones(size(m.cellcenters.x)), 'or', ...\n     m.facecenters.x, ones(size(m.facecenters.x)), '-+b');\nlegend('cell centers', 'face centers');\ntitle('Visualization of a 1D discretized domain');\n%%\n% The generated figure shows a 1D domain of length 1.0 [unit], discretized\n% into 10 cells of the same size (dx = 1/10).\n% I'm going to assume that you are familiar with the cell-centred finite\n% volume method, discretization, and especially handling the boundary\n% conditions using the ghost cells.\n% You can also generate and visualize 2D and 3D meshes. To find some\n% examples, type:\n%\n%   help createMesh2D;\n%   help createMesh3D;\n%\n% You will end up with the following two simple examples:\n%\nNx = 5;\nNy = 7;\nLx = 10;\nLy = 20;\nm = createMesh2D(Nx, Ny, Lx, Ly);\n[X, Y] = ndgrid(m.cellcenters.x, m.cellcenters.y);\n[Xf,Yf]=ndgrid(m.facecenters.x, m.facecenters.y);\nfigure(3);\nplot(X, Y, 'or', ...\n     Xf, Yf, '-b', Xf', Yf', '-b');\n%%\n% that shows you a 2D grid, and\n%\nNx = 2;\nLx = 1.0;\nNy = 3;\nLy = 2.0;\nNz = 4;\nLz = 3.0;\nm = 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);\nfigure(4);\nplot3(X(:), Y(:), Z(:), 'or')\nhold on;\nplot3(Xf(:), Yf(:), Zf(:), '+b')\nlegend('cell centers', 'cell corners');\nhold off;\n%%\n% that shows a 3D grid.\n%% Boundary condition structure\n% I had so many reasons to write this toy toolbox, of which, the most\n% important one was to be able to implement different boundary conditions\n% in the most convenient way! My final implementation makes the user able\n% to define either a _periodic boundary condition_ or a _general boundary\n% condition_ of the following form:\n%%\n%\n% $$a (\\nabla \\phi .\\mathbf{n}) + b \\phi = c $$\n%\n%%\n% In the above equation, $\\phi$ is the unknown, and _a_, _b_, and _c_ are\n% constants. In practice, this boundary condition equation will be discretized\n% to the following system of algebraic equations:\n%%\n%\n% $$M_{bc} \\phi = {RHS}_{bc}$$\n%\n%%\n% By adjusting the values of _a_ and _b_, onne can easily define\n% one of the following well-known boundary conditions:\n%%\n%\n% * Neumann (_a_ is nonzero; _b_ is 0)\n% * Dirichlet (_a_ is zero; _b_ is nonzero)\n% * Robin (_a_ and _b_ are both nonzero)\n%\n%%\n% To clarify the above explanations, let us create a boundary condition\n% structure for a 1D mesh.\n%\nNx = 10; % number of cells in the domain\nLx = 1.0; % length of the domain\nm = createMesh1D(Nx, Lx); % createMesh and createMesh are identical\nBC = createBC(m); % creates a boundary condition structure\ndisp(BC); % display the BC structure\n%%\n% The BC structure has two substructures, i.e., _left_ that denotes the boundary\n% at the left side of the domain (at x=0), and _right_ that denotes the\n% boundary at the end of the domain (at x=Lx). Each of these substructures\n% have three fields, i.e., _a_, _b_, and _c_. The default values are _a_=1,\n% _b_=0, and _c_=0:\n%\ndisp(BC.left); % show the values of the coefficients for the left boundary\n%%\n% There is one other field, i.e., _periodic_, which has a zero value. If\n% you change it to one, then a periodic boundary condition will be created\n% and the _a_, _b_, and _c_ values will be ignored.\n% clearly, you can change the above boundary condition by assigning new\n% values to the |BC.left| fields. For instance, you can define a Dirichlet\n%  boundary (i.e., fixed value) with a value of 2.5 by typing\n%\nBC.left.a = 0;\nBC.left.b = 1;\nBC.left.c = 2.5;\n%%\n% You can define a periodic boundary condition simply by writing:\n%\nBC.left.periodic = 1;\n%%\n% For boundary condition structures created for 2D and 3D grids, we will\n% have _left_, _right_, _bottom_, _top_, _back_, and _front_ boundaries\n% and thus substructures. Let me show them to you in action:\n%\nm = createMesh2D(3,4, 1.0, 2.0);\nBC = createBC(m);\ndisp(BC);\ndisp(BC.top);\n%%\n% Yes, that's right. _a_, _b_, and _c_ are vectors. It means that you can\n% have different boundary conditions for\n% different cell faces at each boundary. For instance, I can have a Neumann\n% boundary condition for the first cell and a Dirichlet boundary condition\n% for the last cell at the top boundary:\nBC.top.a(1) = 1; BC.top.b(1) = 0; BC.top.c(1) = 0; % zero value Neumann\nBC.top.a(end) =0; BC.top.b(end)=1; BC.top.c(end) = 0; % zero value Dirichlet\ndisp('top.  a     b     c'); % some fancy display!\ndisp('   ---------------');\ndisp([BC.top.a BC.top.b BC.top.c]);\n%%\n% The same procedure can be followed for a 3D grid. However, _a_, _b_, and\n% _c_ values are 2D matrices for a 3D grid. I will discuss it in more\n% details when we reach the practical examples.\n% *Important note:* If you need to assign a boundary condition to the\n% entire boundary, use (:) in your assignment. For instance, to define a\n% Dirichlet boundary for the right boundary, you may write\nBC.right.a(:)=0; BC.right.b(:)=1; BC.right.c(:)=0;\n%% Solve a diffusion equation\n% As the first example, we solve a steady-state diffusion equation of the\n% following formform\n%\n% $$\\nabla.\\left(-D\\nabla c\\right)=0,$$\n%\n%%\n% where _D_ is the diffusivity and _c_ is the concentration. Let me assume\n% that we have a 1D domain, with Dirichlet boundary conditions at both\n% boundaries, i.e.,\n% at x=0, c=1; and at x=L, c=0.\n% First of all, we need to define our domain, discretize it, and define the\n% boundaries at the borders.\nclc; clear; % clear the screen and memory\nL = 0.01; % a 1 cm domain\nNx = 10; % number of cells\nm = createMesh3D(Nx,Nx,Nx,L, L,L); % create the mesh\nBC = createBC(m); % construct the BC structure (Neumann by default)\n%%\n% Now as you may remeber, we have to switch from Neumann to Dirichlet\n% boundary conditions\n%\nBC.left.a(:) = 0; BC.left.b(:) = 1; BC.left.c(:) = 1; % Left boundary to Dirichlet\nBC.right.a(:) = 0; BC.right.b(:) = 1; BC.left.c(:) = 1; % right boundary to Dirichlet\n%%\n% The next sep is to define the diffusivity coefficient. In this FVTool,\n% the physical properties of the domain are defined for each cell, with the\n% function createCellVariable\nD = createCellVariable(m, 1e-5); % assign a constant value of 1e-5 to diffusivity value on each cell\n%%\n% However, the transfer coefficients must be known on the face of each cell.\n% For this reason, we have a few averaging schemes implemented in the\n% Utilities folder. For a 1D domain, we can use a harmonic mean scheme:\nD_face = harmonicMean(D); % average diffusivity value on the cell faces\n%%\n% Now, we can convert the PDE to a algebraic system of linear equations,\n% i.e.,\n%%\n%\n% $$\\nabla.\\left(-D\\nabla c\\right) \\approx Mc = 0$$\n%\n%%\n% where M is the matrix of coefficient that is going to be calculated using\n% this toolbox. The matrix of coefficient, _M_ has two parts. The diffusion\n% equation and the boundary conditions. They are calculated by:\nM_diff = diffusionTerm(D_face); % matrix of coefficients for diffusion term\n[M_bc, RHS_bc] = boundaryCondition(BC); % matrix of coefficient and RHS vector for the boundary condition\n%%\n% A vector of right hand side values are always obtained during the\n% discretization of the boundary conditions.\n% Now that the PDE is discretized, we can solve it by a Matlab linear solver.\nc = solvePDE(m, M_diff+M_bc, RHS_bc);\n%%\n% finally, the resut can be visualized:\nvisualizeCells(c);\n%%\n% Just to get excited a little bit, only change the mesh definition command\n% from createMesh1D(Nx,L) to createMesh2D(Nx,Nx,L,L), run the code and see\n% what happens. For even more excitement, change it to\n% createMesh3D(Nx,Nx,Nx,L,L,L).\n% This is usually the way we develop new mathematical models for a physical\n% phenomenon. Write the equation, solve it in 1D, compare it to the\n% analytical solution, then solve it numerically in 2D and 3D for more\n% realistic cases with heterogeneous transfer coefficients and other\n% nonidealities (and perhaps compare it to some experimental data)\n%% Solve a convection-diffuison equation and compare it to analytical solution\n% Here, I'm going to add a convection term to what we solved in the\n% previous example. This tutorial is adopted from the fipy\n% convection-diffusion example you can find at this address:\n%%\n% <http://www.ctcms.nist.gov/fipy/examples/convection/index.html>\n%%\n% The differential equation reads\n%%\n%\n% $$\\nabla.\\left(\\mathbf{u} \\phi -D\\nabla \\phi \\right)=0$$\n%\n%%\n% Here, $\\mathbf{u}$ is a velocity vector (face variable) and $D$ is the\n% diffusion coefficient (again a face variable). Please see the PDF\n% document for an explanation of cell and face variables. We use Dirichlet\n% (constant value) boundary conditions on the left and right boundaries.\n% It is zero at the left boundary and one at the right boundary. The\n% analytical solution of this differential equation reads\n%%\n%\n% $$c = \\frac{1-exp(ux/D)}{1-exp(uL/D)}$$\n%\n%%\n% We start the code as always with some cleaning up:\nclc; clear;\n%%\n% Then we define the domain and mesh size:\nL = 1;  % domain length\nNx = 25; % number of cells\nmeshstruct = createMesh1D(Nx, L);\nx = meshstruct.cellcenters.x; % extract the cell center positions\n%%\n% The next step is to define the boundary condition:\nBC = createBC(meshstruct); % all Neumann boundary condition structure\nBC.left.a = 0; BC.left.b=1; % switch the left boundary to Dirichlet\nBC.left.c=0; % value = 0 at the left boundary\nBC.right.a = 0; BC.right.b=1; % switch the right boundary to Dirichlet\nBC.right.c=1; % value = 1 at the right boundary\n%%\n% Now we define the transfer coefficients:\nD_val = 1.0; % diffusion coefficient value\nD = createCellVariable(meshstruct, D_val); % assign dif. coef. to all the cells\nDave = harmonicMean(D); % convert a cell variable to face variable\nu = -10; % velocity value\nu_face = createFaceVariable(meshstruct, u); % assign velocity value to cell faces\n%%\n% Now we discretize the differential equation into a system of linear\n% algebraic equations:\n%%\n%\n% $$(M_{conv}-M_{diff}+M_{bc})\\phi={RHS}_{bc}$$\n%\n%%\n% or if we use an upwind discretization scheme, we will obtain:\n%%\n%\n% $$(M_{conv,uw}-M_{diff}+M_{bc})\\phi={RHS}_{bc}$$\n%\n%%\n%\nMconv =  convectionTerm(u_face); % convection term, central, second order\nMconvupwind = convectionUpwindTerm(u_face); % convection term, upwind, first order\nMdiff = diffusionTerm(Dave); % diffusion term\n[Mbc, RHSbc] = boundaryCondition(BC); % boundary condition discretization\nM = Mconv-Mdiff+Mbc; % matrix of coefficient for central scheme\nMupwind = Mconvupwind-Mdiff+Mbc; % matrix of coefficient for upwind scheme\nRHS = RHSbc; % right hand side vector\nc = solvePDE(meshstruct, M, RHS); % solve for the central scheme\nc_upwind = solvePDE(meshstruct, Mupwind, RHS); % solve for the upwind scheme\nc_analytical = (1-exp(u*x/D_val))/(1-exp(u*L/D_val)); % analytical solution\nfigure(5);\nplot(x, c.value(2:Nx+1), x, c_upwind.value(2:Nx+1), '--',...\n    x, c_analytical, '.');\nlegend('central', 'upwind', 'analytical');\n%%\n% As you see here, we obtain a more accurate result by using a central\n% difference discretization scheme for the convection term compared to the\n% first order upwind.\n%% solve a transient diffusion equation\n% This tutorial is adapted from the fipy 1D diffusion example\n%%\n% <http://www.ctcms.nist.gov/fipy/examples/diffusion/index.html FiPy diffusion tutorial>\n% The transient diffusion equation reads\n%%\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%%\n% Once again, clean up:\nclc; clear;\n%%\n% Define the domain and create a mesh structure\nL = 50;  % domain length\nNx = 20; % number of cells\nm = createMesh1D(Nx, L);\nx = m.cellcenters.x; % cell centers position\n%%\n% Create the boundary condition structure:\nBC = createBC(m); % all Neumann boundary condition structure\n%%\n% Switch the left and right boundaries to Dirichlet:\nBC.left.a = 0; BC.left.b=1; BC.left.c=1; % left boundary\nBC.right.a = 0; BC.right.b=1; BC.right.c=0; % right boundary\n%%\n% Define the transfer coefficients:\nD_val = 1;\nD = createCellVariable(m, D_val);\nDave = harmonicMean(D); % convert it to face variables\n% Define alfa, the coefficient of the transient term:\nalfa_val = 1;\nalfa = createCellVariable(m, alfa_val);\n%%\n% Define the initial values:\nc_init = 0;\nc_old = createCellVariable(m, c_init, BC); % initial values\nc = c_old; % assign the old value of the cells to the current values\n%%\n% Now define the time step and the final time:\ndt = 0.1; % time step\nfinal_t = 100;\n%%\n% Here, we first define the matrices of coefficients that will not change\n% as we progress in time, viz. diffusion term and boundary condition:\nMdiff = diffusionTerm(Dave);\n[Mbc, RHSbc] = boundaryCondition(BC);\n%%\n% The transitionTerm function gives a matrix of coefficient and a RHS\n% vector. The matrix of coefficient does not change in each time step, but\n% the RHS does (see the PDF documents). Therefore, we need to call the\n% function inside the time loop.\n% Start the loop here:\nfor t=dt:dt:final_t\n    [M_trans, RHS_trans] = transientTerm(c_old, dt, alfa);\n    M = M_trans-Mdiff+Mbc;\n    RHS = RHS_trans+RHSbc;\n    c = solvePDE(m,M, RHS);\n    c_analytical = 1-erf(x/(2*sqrt(D_val*t)));\n    c_old = c;\nend\n%%\n% Now visualize the final results\nfigure(6)\nplot(x, c.value(2:Nx+1), 'o', x, c_analytical);\nxlabel('Length [m]'); ylabel('c');\nlegend('Numerical', 'Analytical');\n%%\n% you can visualize the results from each time step by moving the plot line\n% inside the for loop.\n%% convection equations; different discretization schemes\n% If I want to highlight one special feature of this FVTool, I will point\n% a finger on its various discretization schemes for a linear convection\n% term, which includes central difference (second order), upwind (first\n% order), and TVD scheme with various flux limiters.\n%%\n% Here, we are going to compare the performance of each scheme for solving\n% two PDE's.\n% First, a simple linear transient convection equation with an strange initial\n% condition and later, we solve the well-known Burger's equation.\nclc; clear;\n% define a 1D domain and mesh\nW = 1;\nNx = 500;\nmesh1 = createMesh1D(Nx, W);\nx = mesh1.cellcenters.x;\n% define the boundaries\nBC = createBC(mesh1); % all Neumann\nBC.left.periodic=1;\nBC.right.periodic =1;\n% Initial values\nphi_old = createCellVariable(mesh1, 0.0, BC);\nphi_old.value(20:120) = 1;\nphi_old.value(180:400)= sin(x(180:400)*10*pi());\n% initial guess for phi\nphi = phi_old;\nphiuw_old=phi_old;\n% initial values for upwind scheme\nphiuw = phi;\n% keep the initial values for visualization\nphiinit=phi_old;\n% velocity field\nu = 0.3;\nuf = createFaceVariable(mesh1, u);\n% diffusion field\nD = 1e-2;\nDf = createFaceVariable(mesh1, D);\n% transient term coefficient\nalfa = createCellVariable(mesh1,1.0);\n% upwind convection term\nMconvuw = convectionUpwindTerm1D(uf);\n% define the BC term\n[Mbc, RHSbc] = boundaryCondition(BC);\n% choose a flux limiter\nFL = fluxLimiter('Superbee');\n% solver\ndt = 0.001; % time step\nfinal_t = W/u;\nt = 0;\nwhile t<final_t\n    t = t+dt;\n    % inner loop for TVD scheme\n    for j = 1:5\n        [Mt, RHSt] = transientTerm(phi_old, dt, alfa);\n        [Mconv, RHSconv] = convectionTvdTerm1D(uf, phi, FL);\n        M = Mconv+Mt+Mbc;\n        RHS = RHSt+RHSbc+RHSconv;\n        phi = solvePDE(mesh1, M, RHS);\n    end\n    [Mtuw, RHStuw] = transientTerm(phiuw_old, dt, alfa);\n    Muw = Mconvuw+Mtuw+Mbc;\n    RHSuw = RHStuw+RHSbc;\n    phiuw = solvePDE(mesh1, Muw, RHSuw);\n    phiuw_old = phiuw;\n    phi_old = phi;\nend\nfigure(7);plot(x, phiinit.value(2:Nx+1), x, phi.value(2:Nx+1), '-o', x, ...\n        phiuw.value(2:Nx+1));\n\n% %% method of lines: using Matlab's ODE solvers for adaptive time stepping\n%\n%\n%\n% %% solving a nonlinear PDE\n%\n% %% solving a system of linear PDE's: sequential and coupled methods\n%\n% %% solving a system of nonlinear PDE's: sequential and coupled olutions\n%\n% %% Real life cases: water-flooding in the production of oil\n%\n% %% and finally your examples?\n%\n%\n%\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/FVTdemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5804360196394981}}
{"text": "%System model for geodetic navigation frame mechanization for both phi and psi parametrization.\n\n%This script can be used for both quaternion and DCM attitude parametrizations.\n\n%Position errors are represented as delta_r^n (position error with respect to\n%earth defined in navigation frame) in meters rather than\n%Delta-Llh (llh perturbation model see:sys_llh_phipsi) or Delta-Theta (Cen perturbation: to be added later)\n\n%Delta_r^n, delta_llh and Delta_theta are assumed to be convertible to each\n%other. That is why this system model can be used for any of these position\n%mechanizations.\n\n%There is no difference between the psi form of this script and the \"sys_wander_psi\". This is because\n%theta_z does not appear anywhere in the error propagation model for the\n%psi model. (Ccn*dv^c is assumed to be equal to dv^c in position error model\n%and theta*g is independent of theta_z). Therefore, you can use\n%sys_wander_psi instead of this script. (Also note that sys_wander_psi is a\n%nonsingular implementation, whereas this script is singular at the pole as geoparam is called with arg 2)\n\n%Returns F and Q of discrete time model. The IMU error model must be\n%specified here. (Note that in the previous implementations I had seperated\n%nav and imu models in different m-files. I no longer follow that approach)\n\n%mode==1 --> PHI model\n%mode==2 --> PSI model\n\n%imutype is directly transferred to imu_err_defs_v000\n\nfunction [STM Qd]=sys_metric_phipsi(Cen, h, Vn, att, acc, gyro, dt, mode, imutype, modelNo)\n\n%%%Navigation error model\n%1-3:Position error in meters\n%4-6:vel errors\n%7-9:Attitude errors in psi form\n\n%N[da:dw]':Effect of IMU errors on nav states\nif(nargin<10)\n    modelNo=3; % random walk bias and scale factor\nend\nAnav=zeros(9); %pos, vel, attitude\nNnav=zeros(9,6);\n\n[Fc, wen_n, wie_n, g]=geoparam_v001(2, Cen(:,3), h, Vn);\n\nif (size(att,1)==1 || size(att,2)==1) %att is qbn\n    Cbn=quat2dcm_v000(att);\nelse %att is dcm\n    Cbn=att;\nend\n\n%%%Navigation System model\n%%Common terms for both phi and psi\n%position errors\nAnav(1:3,1:3)=-skew(wen_n);\nAnav(1:3,4:6)=eye(3);\n\n%Velocity Errors\nAnav(6,3)=2*g*Fc(1,1);  %effect of height on gravity (note that, drz is the negative of dh. Therefore, this is positive)\nAnav(4:6,4:6)=-skew(wen_n+2*wie_n);\nAnav(4:6,7:9)=skew(Cbn*acc);\n\nNnav(4:6,1:3)=Cbn; %%effect of accelerometer errors\n\n%Attitude errors\nAnav(7:9,7:9)=-skew(wen_n+ wie_n);\nNnav(7:9,4:6)=-Cbn; %Effect of gyroscope errors\n\n%PHI model\nif (mode==1)\n    sL=-Cen(3,3);\n    cL=Cen(3,1);    %Note that I assume wander=0 for Cen. (This is not a non-singular implementation)\n    %%position errors\n    Anav(1:3,1:2)=Anav(1:3,1:2)-skew(Vn)*[0 Fc(1,1);-Fc(2,2) 0; 0 Fc(3,1)];\n    \n    %%Velocity errors\n    %Effect of 2*d_wie_n\n    Anav(4:6,1)=Anav(4:6,1)+2*skew(Vn)*[wie_n(3);0;-wie_n(1)]*Fc(2,2);\n    %Effect of d_w_en_n\n    Anav(4:6,3:5)=Anav(4:6,3:5)+skew(Vn)*[Vn(2)*Fc(1,1)^2 0 Fc(1,1);-Vn(1)*Fc(2,2)^2 -Fc(2,2) 0;-Vn(2)*Fc(1,1)^2*sL/cL 0 Fc(3,1)];\n    Anav(4:6,1)=Anav(4:6,1)+skew(Vn)*[0;0;-(Vn(2)*Fc(1,1)/cL/cL)]*Fc(2,2);\n    \n    %%Attitude errors\n    %effect of dw_ie_n\n    Anav(7:9,1)=Anav(7:9,1)+[wie_n(3);0;-wie_n(1)]*Fc(2,2);\n    \n    %effect of dw_en_n\n    Anav(7:9,3:5)=Anav(7:9,3:5)+[-Vn(2)*Fc(1,1)^2 0 Fc(1,1);Vn(1)*Fc(2,2)^2 -Fc(2,2) 0;Vn(2)*Fc(1,1)^2*sL/cL 0 Fc(3,1)];\n    Anav(9,1)=Anav(9,1)-(Vn(2)*Fc(1,1)/cL/cL)*Fc(2,2);\nend\n\n%PSI model\nif (mode==2)\n    %Velocity errors\n    Anav(4:5,1:2)=Anav(4:5,1:2)+g*[-Fc(2,2) 0;0 -Fc(1,1)];    %effect of horizontal position error on gravity\nend\n\n%%%%Imu error model parameters\n[Aimu_d, Qimu_d, Cimu, Rimu]=imu_err_model_v001(acc, gyro, dt, imutype, modelNo);\n\n%%Convert continuous time Anav into discrete time\n%I used van loan's method here to perform conversion so that I can obtain a\n%correct Qnav_d. If you use a 1st order taylor series approximation, do not\n%forget to correct the cross-correlation effects caused by arw/vrw. (In,\n%the final implementation, it would be better to manually compute each\n%element rather than using this method)\nmx_a=dt*[-Anav,Nnav*Rimu*Nnav';zeros(9),Anav'];\nmx_b = expm(mx_a);\nAnav_d = mx_b(10:18,10:18)';\nQnav_d = Anav_d*mx_b(1:9,10:18);\n\n%%Combine everything\nnst_imu=size(Aimu_d);\nSTM=zeros(9+nst_imu);\nQd=zeros(9+nst_imu);\n\nSTM(1:9,1:9)=Anav_d;\nSTM(1:9,10:end)=Nnav*Cimu*dt;\nSTM(10:end,10:end)=Aimu_d;\n\nQd(1:9,1:9)=Qnav_d;\nQd(10:end,10:end)=Qimu_d;\nQd(1:9,10:end)=Nnav*Cimu*Qimu_d*dt/2;   %not necessary, but let's keep this\nQd(10:end,1:9)=Qd(1:9,10:end)';\nend", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/INS/sys_metric_phipsi_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.580409566309875}}
{"text": "function mean = normal_01_mean ( )\n\n%*****************************************************************************80\n%\n%% NORMAL_01_MEAN returns the mean of the Normal 01 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%    Output, real MEAN, the mean of the PDF.\n%\n  mean = 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/truncated_normal/normal_01_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.8006920116079208, "lm_q1q2_score": 0.5803978395868109}}
{"text": "function [nodes2, edges2] = grMergeNodesMedian(nodes, edges, mnodes)\n%GRMERGENODESMEDIAN Replace several nodes by their median coordinate.\n%\n%   [NODES2, EDGES2] = grMergeNodesMedian(NODES, EDGES, NODES2MERGE)\n%   NODES ans EDGES are the graph structure, and NODES2MERGE is the list of\n%   indices of nodes to be merged.\n%   The median coordinate of merged nodes is computed, and all nodes are\n%   merged to this new node.\n%\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2003-08-13\n% Copyright 2003-2022 INRA - TPV URPOI - BIA IMASTE\n\n% coordinates of reference node\nx = median(nodes(mnodes, 1));\ny = median(nodes(mnodes, 2));\n\n% index of reference node\nrefNode = findPoint([x y], nodes);\nmnodes = sort(mnodes(mnodes ~= refNode));\n\nfor n = 1:length(mnodes)\n    node = mnodes(n);\n    \n    % process each neighbor of the current node\n    neighbors = grAdjacentNodes(edges, node);\n    for e = 1:length(neighbors)\n        edge = neighbors(e);\n        \n        if edges(edge, 1) == refNode || edges(edge, 2) == refNode\n            continue;\n        end\n\n        % find if the node is referenced as 1 or 2 in the edge,\n        % and replace it with the reference node.\n        if edges(edge, 1) == node\n            edges(edge, 1) = refNode;\n        else\n            edges(edge, 2) = refNode;\n        end  \n        \n    end\nend   \n\n% remove nodes from the list, except the reference node.\nfor n = 1:length(mnodes)\n    [nodes, edges] = grRemoveNode(nodes, edges, mnodes(n)-n+1);\nend\n\nnodes2 = nodes;\nedges2 = edges;\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/graphs/grMergeNodesMedian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303384097947, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5803437534350799}}
{"text": "function [vertices, faces] = triangulatePolygonPair(poly1, poly2, varargin)\n%TRIANGULATEPOLYGONPAIR Compute triangulation between a pair of 3D closed curves.\n%\n%   [V, F] = triangulatePolygonPair(POLY1, POLY2)\n%\n%   [V, F] = triangulatePolygonPair(..., 'recenter', FLAG)\n%   Where FLAG is a boolean, specifies whether the second curve should be\n%   translated to have the same centroid as the first curve. This can\n%   improve mathcing of vertices. Default is true.\n%\n%\n%   Example\n%     % triangulate a surface patch between two ellipses\n%     % create two sample curves\n%     poly1 = ellipseToPolygon([50 50 40 20 0], 36);\n%     poly2 = ellipseToPolygon([50 50 40 20 60], 36);\n%     poly1 = poly1(1:end-1,:);\n%     poly2 = poly2(1:end-1,:);\n%     % transform to 3D polygons / curves\n%     curve1 = [poly1 10*ones(size(poly1, 1), 1)];\n%     curve2 = [poly2 20*ones(size(poly2, 1), 1)];\n%     % draw as 3D curves\n%     figure(1); clf; hold on;\n%     drawPolygon3d(curve1, 'b'); drawPoint3d(curve1, 'bo');\n%     drawPolygon3d(curve2, 'g'); drawPoint3d(curve2, 'go');\n%     view(3); axis equal;\n%     [vertices, faces] = triangulatePolygonPair(curve1, curve2);\n%     % display the resulting mesh\n%     figure(2); clf; hold on;\n%     drawMesh(vertices, faces);\n%     drawPolygon3d(curve1, 'color', 'b', 'linewidth', 2);\n%     drawPolygon3d(curve2, 'color', 'g', 'linewidth', 2);\n%     view(3); axis equal;\n%\n%   See also \n%     meshes3D, triangulatePolygonPair3d, triangulateCurvePair,\n%     meshSurfaceArea \n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2017-05-18, using Matlab 9.1.0.441655 (R2016b)\n% Copyright 2017-2022 INRA - Cepia Software Platform\n\n%% Settings\n\nrecenterFlag = true;\nwhile length(varargin) > 1\n    pname = varargin{1};\n    if strcmpi(pname, 'recenter')\n        recenterFlag = varargin{2};\n    else\n        error('Unknown parameter name: %s', pname);\n    end\n    varargin(1:2) = [];\nend\n\n\n%% Memory allocation\n\n% concatenate vertex coordinates for creating mesh\nvertices = [poly1 ; poly2];\n\n% number of vertices on each polygon\nn1 = size(poly1, 1);\nn2 = size(poly2, 1);\n\n% allocate the array of facets (each edge of each polygon provides a facet)\nnFaces = n1 + n2;\nfaces = zeros(nFaces, 3);\n\n\n% Translate the second polygon such that the centroids of the bounding\n% boxes coincide. This is expected to improve the matching of the two\n% curves.\nif recenterFlag\n    box1 = boundingBox3d(poly1);\n    box2 = boundingBox3d(poly2);\n    center1 = (box1(2:2:end) + box1(1:2:end-1)) / 2;\n    center2 = (box2(2:2:end) + box2(1:2:end-1)) / 2;\n    vecTrans = center1 - center2;\n    trans = createTranslation3d(vecTrans);\n    poly2 = transformPoint3d(poly2, trans);\nend\n\n\n%% Init iteration\n\n% find the pair of points with smallest distance.\n% This will be the current diagonal.\n[dists, inds] = minDistancePoints(poly1, poly2);\n[dummy, ind1] = min(dists); %#ok<ASGLU>\nind2 = inds(ind1);\n\n% consider two consecutive vertices on each polygon\ncurrentIndex1 = ind1;\ncurrentIndex2 = ind2;\n\n\n%% Main iteration\n% For each diagonal, consider the two possible facets (one for each 'next'\n% vertex on each polygon), each create current facet according to the\n% closest one. \n% Then update current diagonal for next iteration.\n\nfor iFace = 1:nFaces\n    nextIndex1 = mod(currentIndex1, n1) + 1;\n    nextIndex2 = mod(currentIndex2, n2) + 1;\n    \n    % compute lengths of diagonals\n    dist1 = distancePoints(poly1(currentIndex1, :), poly2(nextIndex2,:));\n    dist2 = distancePoints(poly1(nextIndex1, :), poly2(currentIndex2,:));\n    \n    if dist1 < dist2\n        % keep current vertex of curve1, use next vertex on curve2\n        face = [currentIndex1 currentIndex2+n1 nextIndex2+n1];\n        currentIndex2 = nextIndex2;\n    else\n        % keep current vertex of curve2, use next vertex on curve1\n        face = [currentIndex1 currentIndex2+n1 nextIndex1];\n        currentIndex1 = nextIndex1;\n    end\n    \n    % create the facet\n    faces(iFace, :) = face;\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/meshes3d/triangulatePolygonPair.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5803437527391525}}
{"text": "function [ x, c, m ] = dvandprg ( n, alpha, b, x, c, m )\n\n%*****************************************************************************80\n%\n%% DVANDPRG solves a Vandermonde system A' * x = f progressively.\n%\n%  Discussion:\n%\n%    This function receives the solution to the system of equations A' * x = f\n%    where A is a Vandermonde matrix for alpha(0) through alpha(n-1),\n%    and new values alpha(n) and f(n).  It updates the solution.\n%\n%    To solve a system of Nbig equations, this function may be called repeatedly,\n%    with N = 1, 2, ..., Nbig.  Each time, a solution to the current subsystem\n%    is returned.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    17 April 2014\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 new order of the matrix, which is 1 larger\n%    than on the previous call.  For the first call, N must be 1.\n%\n%    Input, real ALPHA(N), the parameters that define the matrix.\n%    The values should be distinct.  The value ALPHA(N) has just been\n%    added to the system.\n%\n%    Input, real B(N), the right hand side of the linear system.\n%\n%    Input, real X(N-1), the previous solution of the linear system.\n%\n%    Input, real C(N-1), real M(N-1), factorization data from the previous call.\n%\n%    Output, real X(N), the updated solution to the linear system.\n%\n%    Output, real C(N), M(N), updated factorization data.\n%\n  c(n) = b(n);\n  for j = n - 1 : -1 : 1\n    c(j) = ( c(j+1) - c(j) ) / ( alpha(n) - alpha(j) );\n  end\n\n  if ( n == 1 )\n    m(n) = 1.0;\n  else\n    m(n) = 0.0;\n  end\n  cn = c(1);\n  x(n) = c(1);\n\n  for j = n - 1 : -1 : 1\n    m(j+1) = m(j+1) - alpha(n-1) * m(j);\n    x(n-j) = x(n-j) + m(j+1) * cn;\n  end\n\n  return\nend\n", "meta": {"author": "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/dvandprg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.5803437481405925}}
{"text": "function [ triangle_num, triangle_node, triangle_neighbor ] = r8tris2 ( ...\n  node_num, node_xy )\n\n%*****************************************************************************80\n%\n%% R8TRIS2 constructs a Delaunay triangulation of 2D vertices.\n%\n%  Discussion:\n%\n%    The routine constructs the Delaunay triangulation of a set of 2D vertices\n%    using an incremental approach and diagonal edge swaps.  Vertices are\n%    first sorted in lexicographically increasing (X,Y) order, and\n%    then are inserted one at a time from outside the convex hull.\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, integer NODE_NUM, the number of nodes.\n%\n%    Input, real NODE_XY(2,NODE_NUM), the coordinates of the nodes.\n%\n%    Output, integer TRIANGLE_NUM, the number of triangles in the triangulation;\n%    TRIANGLE_NUM is equal to 2*NODE_NUM - BOUNDARY_NUM - 2, where BOUNDARY_NUM \n%    is the number of boundary vertices.\n%\n%    Output, integer TRIANGLE_NODE(3,TRIANGLE_NUM), the nodes that make up each triangle.\n%    The elements are indices of P.  The vertices of the triangles are\n%    in counter clockwise order.\n%\n%    Output, integer TRIANGLE_NEIGHBOR(3,TRIANGLE_NUM), the triangle neighbor list.\n%    Positive elements are indices of TIL; negative elements are used for links\n%    of a counter clockwise linked list of boundary edges; LINK = -(3*I + J-1)\n%    where I, J = triangle, edge index; TRIANGLE_NEIGHBOR(J,I) refers to\n%    the neighbor along edge from vertex J to J+1 (mod 3).\n%\n  triangle_num = 0;\n  triangle_node = [];\n  triangle_neighbor = [];\n\n  tol = 100.0 * eps;\n%\n%  Sort the vertices by increasing (x,y).\n%\n  indx = r82vec_sort_heap_index_a ( node_num, node_xy );\n\n  node_xy = r82vec_permute ( node_num, node_xy, indx );\n%\n%  Make sure that the data points are \"reasonably\" distinct.\n%\n  m1 = 1;\n\n  for i = 2 : node_num\n\n    m = m1;\n    m1 = i;\n\n    k = 0;\n\n    for j = 1 : 2\n\n      cmax = max ( abs ( node_xy(j,m) ), abs ( node_xy(j,m1) ) );\n\n      if ( tol * ( cmax + 1.0 ) < abs ( node_xy(j,m) - node_xy(j,m1) ) )\n        k = j;\n        break\n      end\n\n    end\n\n    if ( k == 0 )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'R8TRIS2 - Fatal error!\\n' );\n      fprintf ( 1, '  Fails for point number I = %d\\n', i );\n      fprintf ( 1, '  M = %d\\n', m );\n      fprintf ( 1, '  M1 = %d\\n', m1 );\n      fprintf ( 1, '  X,Y(M)  = %f  %f\\n', node_xy(1,m), node_xy(2,m) );\n      fprintf ( 1, '  X,Y(M1) = %f  %f\\n', node_xy(1,m1), node_xy(2,m1) );\n      error ( 'R8TRIS2 - Fatal error!' )\n      return\n    end\n\n  end\n%\n%  Starting from points M1 and M2, search for a third point M that\n%  makes a \"healthy\" triangle (M1,M2,M)\n%\n  m1 = 1;\n  m2 = 2;\n  j = 3;\n\n  while ( 1 )\n\n    if ( node_num < j )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'R8TRIS2 - Fatal error!\\n' );\n      error ( 'R8TRIS2 - Fatal error!' )\n      return\n    end\n\n    m = j;\n\n    lr = lrline ( node_xy(1,m), node_xy(2,m), node_xy(1,m1), node_xy(2,m1), ...\n      node_xy(1,m2), node_xy(2,m2), 0.0 );\n\n    if ( lr ~= 0 )\n      break\n    end\n\n    j = j + 1;\n\n  end\n%\n%  Set up the triangle information for (M1,M2,M), and for any other\n%  triangles you created because points were collinear with M1, M2.\n%\n  triangle_num = j - 2;\n\n  if ( lr == -1 )\n\n    triangle_node(1,1) = m1;\n    triangle_node(2,1) = m2;\n    triangle_node(3,1) = m;\n    triangle_neighbor(3,1) = -3;\n\n    for i = 2 : triangle_num\n\n      m1 = m2;\n      m2 = i+1;\n      triangle_node(1,i) = m1;\n      triangle_node(2,i) = m2;\n      triangle_node(3,i) = m;\n      triangle_neighbor(1,i-1) = -3 * i;\n      triangle_neighbor(2,i-1) = i;\n      triangle_neighbor(3,i) = i - 1;\n\n    end\n\n    triangle_neighbor(1,triangle_num) = -3 * triangle_num - 1;\n    triangle_neighbor(2,triangle_num) = -5;\n    ledg = 2;\n    ltri = triangle_num;\n\n  else\n\n    triangle_node(1,1) = m2;\n    triangle_node(2,1) = m1;\n    triangle_node(3,1) = m;\n    triangle_neighbor(1,1) = -4;\n\n    for i = 2 : triangle_num\n      m1 = m2;\n      m2 = i+1;\n      triangle_node(1,i) = m2;\n      triangle_node(2,i) = m1;\n      triangle_node(3,i) = m;\n      triangle_neighbor(3,i-1) = i;\n      triangle_neighbor(1,i) = -3 * i - 3;\n      triangle_neighbor(2,i) = i - 1;\n    end\n\n    triangle_neighbor(3,triangle_num) = -3 * triangle_num;\n    triangle_neighbor(2,1) = -3 * triangle_num - 2;\n    ledg = 2;\n    ltri = 1;\n\n  end\n%\n%  Insert the vertices one at a time from outside the convex hull,\n%  determine visible boundary edges, and apply diagonal edge swaps until\n%  Delaunay triangulation of vertices (so far) is obtained.\n%\n  top = 0;\n\n  for i = j+1 : node_num\n\n    m = i;\n    m1 = triangle_node(ledg,ltri);\n\n    if ( ledg <= 2 )\n      m2 = triangle_node(ledg+1,ltri);\n    else\n      m2 = triangle_node(1,ltri);\n    end\n\n    lr = lrline ( node_xy(1,m), node_xy(2,m), node_xy(1,m1), node_xy(2,m1), ...\n      node_xy(1,m2), node_xy(2,m2), 0.0 );\n\n    if ( 0 < lr ) \n      rtri = ltri;\n      redg = ledg;\n      ltri = 0;\n    else\n      l = -triangle_neighbor(ledg,ltri);\n      rtri = floor ( l / 3 );\n      redg = mod(l,3) + 1;\n    end\n\n    [ ltri, ledg, rtri, redg ] = vbedg ( node_xy(1,m), node_xy(2,m), node_num, node_xy, ...\n      triangle_num, triangle_node, triangle_neighbor, ltri, ledg, rtri, redg );\n\n    n = triangle_num + 1;\n    l = -triangle_neighbor(ledg,ltri);\n\n    while ( 1 )\n\n      t = floor ( l / 3 );\n      e = mod ( l, 3 ) + 1;\n      l = -triangle_neighbor(e,t);\n      m2 = triangle_node(e,t);\n\n      if ( e <= 2 )\n        m1 = triangle_node(e+1,t);\n      else\n        m1 = triangle_node(1,t);\n      end\n\n      triangle_num = triangle_num + 1;\n      triangle_neighbor(e,t) = triangle_num;\n      triangle_node(1,triangle_num) = m1;\n      triangle_node(2,triangle_num) = m2;\n      triangle_node(3,triangle_num) = m;\n      triangle_neighbor(1,triangle_num) = t;\n      triangle_neighbor(2,triangle_num) = triangle_num - 1;\n      triangle_neighbor(3,triangle_num) = triangle_num + 1;\n      top = top + 1;\n\n      if ( node_num < top )\n        fprintf ( 1, '\\n' );\n        fprintf ( 1, 'R8TRIS2 - Fatal error!\\n' );\n        fprintf ( 1, '  Stack overflow.\\n' );\n        error ( 'R8TRIS2 - Fatal error!' )\n      end\n\n      work(top) = triangle_num;\n\n      if ( t == rtri & e == redg )\n        break\n      end\n\n    end\n\n    triangle_neighbor(ledg,ltri) = -3 * n - 1;\n    triangle_neighbor(2,n) = -3 * triangle_num - 2;\n    triangle_neighbor(3,triangle_num) = -l;\n    ltri = n;\n    ledg = 2;\n\n    [ top, ltri, ledg, triangle_node, triangle_neighbor ] = swapec ( ...\n      m, top, ltri, ledg, node_num, node_xy, triangle_num, triangle_node, ...\n      triangle_neighbor, work );\n\n  end\n%\n%  Now account for the sorting that we did.\n%\n  for i = 1 : 3\n    for j = 1 : triangle_num\n      triangle_node(i,j) = indx ( triangle_node(i,j) );\n    end\n  end\n\n  indx = perm_inverse ( node_num, indx );\n\n  node_xy = r82vec_permute ( node_num, node_xy, indx );\n\n  return\nend\n", "meta": {"author": "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/r8tris2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5803437481405925}}
{"text": "function y = nanvar(x,w,dim)\n%NANVAR Variance, ignoring NaNs.\n%   Y = NANVAR(X) returns the sample variance of the values in X, treating\n%   NaNs as missing values.  For a vector input, Y is the variance of the\n%   non-NaN elements of X.  For a matrix input, Y is a row vector\n%   containing the variance of the non-NaN elements in each column of X.\n%   For N-D arrays, NANVAR operates along the first non-singleton dimension\n%   of X.\n%\n%   NANVAR normalizes Y by N-1 if N>1, where N is the sample size of the \n%   non-NaN elements.  This is an unbiased estimator of the variance of the\n%   population from which X is drawn, as long as X consists of independent,\n%   identically distributed samples, and data are missing at random.  For\n%   N=1, Y is normalized by N. \n%\n%   Y = NANVAR(X,1) normalizes by N and produces the second moment of the\n%   sample about its mean.  NANVAR(X,0) is the same as NANVAR(X).\n%\n%   Y = NANVAR(X,W) computes the variance using the weight vector W.  The\n%   length of W must equal the length of the dimension over which NANVAR\n%   operates, and its non-NaN elements must be nonnegative.  Elements of X\n%   corresponding to NaN elements of W are ignored.\n%\n%   Y = NANVAR(X,W,DIM) takes the variance along dimension DIM of X.\n%\n%   See also VAR, NANSTD, NANMEAN, NANMEDIAN, NANMIN, NANMAX, NANSUM.\n\n%   Copyright 1984-2010 The MathWorks, Inc.\n%   $Revision: 1.1.8.2 $  $Date: 2010/10/08 17:25:19 $\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(message('stats:nanvar:InvalidSizeWgts'));\nelseif ~(isvector(w) && all(w(~isnan(w)) >= 0))\n    error(message('stats:nanvar:InvalidWgts'));\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": "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/nanvar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5803437461892764}}
{"text": "function varargout = drawVector(pos, vect, varargin)\n%DRAWVECTOR Draw vector at a given position\n%\n%   drawVector(POS, VECT)\n%   POS should be a N-by-2 or N-by-3 array containing position of vector\n%   origins, and VECT should be a N-by-2 or N-by-3 array containing the\n%   direction of the vectors.\n%\n%   Example\n%     figure; hold on;\n%     drawVector([1 2], [3 2]);\n%     drawVector([1 2], [-2 3]);\n%     axis equal;\n%\n%   See also\n%     quiver, drawVector3d\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2013-03-18,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2013 INRA - Cepia Software Platform.\n\n% check input dimension\nnd = size(pos, 2);\nif size(vect, 2) ~= nd\n    error('input vector and position must have same dimension');\nend\n\nif nd == 2\n    % Display 2D vectors\n    h = quiver(pos(:, 1), pos(:, 2), vect(:, 1), vect(:, 2), 0, varargin{:});\n    \nelseif nd == 3\n    % Display 3D vectors\n    h = quiver3(pos(:, 1), pos(:, 2), pos(:, 3), ...\n        vect(:, 1), vect(:, 2), vect(:, 3), 0, varargin{:});\n    \nelse\n    error('Can not display vectors of dimension > 3');\nend\n\n% format output\nif nargout > 0\n    varargout{1} = h;\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/drawVector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.5803437453534835}}
{"text": "function [mapping, hs, axes_h, fig_h] = scatter_plot(Y,names,options)\n%ENDMEMBER_SCATTER_PLOT Summary of this function goes here\n%   Detailed explanation goes here\nM = length(names);\nXs = [];\ncolors = distinguishable_colors(M);\ndimension_num = 2;\n\nif nargin > 2 && isstruct(options)\n    arg_set = fieldnames(options);\n    for i = 1:length(arg_set)\n        eval([arg_set{i},'=options.',arg_set{i},';']);\n    end\nend\n\n[mappedX, mapping] = pca(Y,dimension_num);\n\nfig_h = figure;\nhs = cell(0);\nif dimension_num == 2\n    scatter_h = scatter(mappedX(:,1), mappedX(:,2), 10, '.', ...\n        'MarkerEdgeColor', [0.6 0.6 0.6]);\nelseif dimension_num == 3\n    scatter_h = scatter3(mappedX(:,1), mappedX(:,2), mappedX(:,3), 10, '.', ...\n        'MarkerEdgeColor', [0.6 0.6 0.6]);\nend\n\nhs(end+1) = {scatter_h};\nhold on; axis equal;\naxes_h = gca;\n\nfor i = 1:length(Xs)\n    marker_color = colors(i,:);\n    mappedX = (Xs{i} - repmat(mapping.mean, size(Xs{i},1), 1)) * mapping.M;\n    if dimension_num == 2\n        scatter_h = scatter(axes_h, mappedX(:,1), mappedX(:,2), 5, '+', ...\n            'MarkerEdgeColor', marker_color);\n    elseif dimension_num == 3\n        scatter_h = scatter3(axes_h, mappedX(:,1), mappedX(:,2), ...\n            mappedX(:,3), 5, '+', 'MarkerEdgeColor', marker_color);\n    end\n    hs(end+1) = {scatter_h};\nend\n\n% show legend\nnames = {'Pixels',names{:}};\n\nhs_legend = zeros(1,length(hs));\nfor j = 1:length(hs)\n    hs_legend(j) = hs{j}(1);\nend\nlegend(hs_legend, names,'Location','best');\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/common/scatter_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5803437435420326}}
{"text": "function [tt,ind_left]=tt_crossl(d,n,fun,ind_right)\n%One left-to-right sweep of the TT-cross method.\n%   [TT,IND_LEFT]=TT_CROSSL(D,N,FUN,IND_RIGHT) Computes one QR-maxvol sweep\n%   of the TT-cross method. The input is the pair (D,N) that determines the\n%   size of the tensor, FUN is the function handle to evaluate a particular\n%   element of the tensor, i.e., VAL=FUN(IND). To pass parameters, please\n%   use anonymous function handles in MATLAB\n% \n%\n%\n% TT-Toolbox 2.2, 2009-2012\n%\n%This is TT Toolbox, written by Ivan Oseledets et al.\n%Institute of Numerical Mathematics, Moscow, Russia\n%webpage: http://spring.inm.ras.ru/osel\n%\n%For all questions, bugs and suggestions please mail\n%ivan.oseledets@gmail.com\n%---------------------------\n\nif ( numel(n) == 1 )\n  n=n*ones(d,1);\nend\nsz=n;\ntt=cell(d,1);\nind_left=cell(d,1); %Computed ind_left\nind_r=ind_right{1};\nr1=size(ind_r,2);\nncur=sz(1);\nmat=zeros(ncur,r1);\nfor i=1:ncur\n   for s=1:r1\n      ind_f=[i,ind_r(:,s)'];\n      val=fun(ind_f);\n      mat(i,s)=val;\n   end\nend\n[qs,~]=qr(mat,0);\nind=maxvol2(qs);\nind_left{1}=ind;\nmat=qs/qs(ind,:);\ntt{1}=mat;\n\nfor k=2:d-1\n     ncur=sz(k);\n     ind_l=ind_left{k-1};\n     ind_r=ind_right{k};\n     r2=size(ind_l,2);\n     r3=size(ind_r,2);\n     core=zeros(ncur,r2,r3);\n     for i=1:ncur\n         for s2=1:r2\n             for s3=1:r3\n                 ind_f=[ind_l(:,s2)',i,ind_r(:,s3)'];\n                 val=fun(ind_f);\n                 core(i,s2,s3)=val;\n             end\n         end\n     end\n     core=permute(core,[2,1,3]); core=reshape(core,[r2*ncur,r3]);\n     rnew=min(r2*ncur,r3);\n     [qs,rs]=qr(core,0);\n     ind=maxvol2(qs);\n     ind_old=ind_left{k-1};\n     ind_new=zeros(k,rnew);\n     ncur=sz(k);\n     for s=1:rnew\n        f_in=ind(s);\n        w1=tt_ind2sub([r2,ncur],f_in);\n        rs=w1(1); js=w1(2);\n        ind_new(:,s)=[ind_old(:,rs)',js];\n     end\n     ind_left{k}=ind_new;\n     core=qs/qs(ind,:);\n     core=reshape(core,[r2,ncur,rnew]); core=permute(core,[2,1,3]);\n   \n    tt{k}=core;\nend\nncur=sz(d);\nind_l=ind_left{d-1};\nr=size(ind_l,2);\nmat=zeros(ncur,r);\nfor j=1:ncur\n    for s=1:r\n      ind_f=[ind_l(:,s)',j];\n      val=fun(ind_f);\n      mat(j,s)=val;\n    end\nend\ntt{d}=mat;\ntt=tt_tensor(tt);\nreturn\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/cross/oldcross/tt_crossl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5803437435420326}}
{"text": "function r4vec_uniform_ab_test ( )\n\n%*****************************************************************************80\n%\n%% R4VEC_UNIFORM_AB_TEST tests  R4VEC_UNIFORM_AB.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    29 October 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 10;\n  a = -1.0;\n  b = +5.0;\n  seed = 123456789;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R4VEC_UNIFORM_AB_TEST\\n' );\n  fprintf ( 1, '  R4VEC_UNIFORM_AB computes a random R4VEC.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  %g <= x <= %g\\n', a, b );\n  fprintf ( 1, '  Initial seed is %d\\n', seed );\n\n  [ v, seed ] = r4vec_uniform_ab ( n, a, b, seed );\n\n  r4vec_print ( n, v, '  Uniform R4VEC:' );\n\n  return\nend\n", "meta": {"author": "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/r4vec_uniform_ab_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.5802887768351964}}
{"text": "function test10\n%TEST10 test cs_qr\n%\n% Example:\n%   test10\n% See also: testall\n\n%   Copyright 2006-2007, Timothy A. Davis.\n%   http://www.cise.ufl.edu/research/sparse\n\n\nrand ('state', 0) ;\n\n\n% f = 185 ;\n% f = 449 ;\nclf\n\nfor trials = 1:100\n    \n    m = fix (100 * rand (1)) ;\n    n = fix (100 * rand (1)) ;\n    d = 0.1 * rand (1) ;\n    A = sprandn (m, n, d) ;\n    [m n] = size (A) ;\n    if (m < n)\n        A = A' ;\n    end\n    [m n] = size (A) ;\n    sp = sprank (A) ;\n    % if (sp < n)\n    %   continue ;\n    % end\n\n    Aorig = A ;\n\n    % A = A (:, colamd (A)) ;\n\n    tic ;\n    R = qr (A) ;\n    t1 = toc ;\n\n    % tic ;\n    % [Q,R] = qr (A) ;\n    % t1 = toc ;\n\n    [c,h,parent] = symbfact (A, 'col') ;                                    %#ok\n    rnz = sum (c) ;                                                         %#ok\n    tic ;\n    [V2,Beta2,p,R2] = cs_qr (sparse(A)) ;\n    t2 = toc ;\n\n    C = A ;\n    m2 = size (V2,1) ;\n    if (m2 > m)\n        C = [A ; sparse(m2-m, n)] ;\n    end\n    C = C (p,:) ;\n\n    [H1,R1] = myqr (C) ;\n    err1 = norm (R1-R2,1) / norm (R1) ;\n    disp ('err1 = ') ;\n    disp (err1) ;\n    % [svd(A) svd(R1) svd(full(R2))]\n    s1 = svd (full (A)) ;\n    s2 = svd (full (R2)) ;\n    if (n > 0)\n        err2 = norm (s1 - s2) / s1 (1)  ;\n        disp ('err2 = ') ;\n        disp (err2) ;\n    else\n        err2 = 0 ;\n    end\n    fprintf ('%10.6f %10.6f  cs speedup %8.3f sprank %d vs %d\\n', t1, t2, t1/t2, sp, n) ;\n\n    % H2 = full (H2)\n    % R2 = full (R2)\n\n    subplot (2,4,1) ; spy (A) ;         title ('A colamd') ;\n    subplot (2,4,4) ; spy (Aorig) ;     title ('Aorig') ;\n    subplot (2,4,2) ; spy (C) ;         title ('A rperm') ;\n    subplot (2,4,5) ; spy (abs(R2)>0) ; title ('spqr R, no zeros') ;\n    subplot (2,4,6) ; spy (R) ;         title ('matlab R') ;\n    subplot (2,4,7) ; spy (R2) ;        title ('spqr R') ;\n    subplot (2,4,8) ; spy (V2) ;        title ('spqr H') ;\n    drawnow\n\n    if (err2 > 1e-9)\n        error ('!') ;\n    end\n\n    if (m2 > m)\n        fprintf ('added %d rows, sprank %d n %d\\n', m2-m, sp, n) ;\n    end\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/CSparse/MATLAB/Test/test10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5802887762487904}}
{"text": "classdef ShiftColor < handle\n  \n  properties (Access = public)\n    \n  end\n  \n  methods (Access = public, Static = true)\n    \n    function newColor = shiftColorFwd(oldColor)\n      oldSize = size(oldColor);\n      oldColor = reshape(oldColor,[1 1 3]);\n      hh = rgb2hsv(oldColor);\n      hh(1) = mod(hh(1)+0.085,1);\n      newColor = hsv2rgb(hh);\n      newColor = reshape(newColor,oldSize);\n    end\n    \n    function newColor = shiftColorBkwd(oldColor)\n      oldSize = size(oldColor);\n      oldColor = reshape(oldColor,[1 1 3]);\n      hh = rgb2hsv(oldColor);\n      hh(1) = mod(hh(1)-0.065,1);\n      newColor = hsv2rgb(hh);\n      newColor = reshape(newColor,oldSize);\n      \n    end\n\n    function newColor = increaseIntensity(oldColor)\n      oldSize = size(oldColor);\n      oldColor = reshape(oldColor,[1 1 3]);\n      hh = rgb2hsv(oldColor);\n      hh(3) = min(hh(3)+0.2,1);\n      newColor = hsv2rgb(hh);\n      newColor = reshape(newColor,oldSize);\n      \n    end\n    \n    function newColor = decreaseIntensity(oldColor)\n      oldSize = size(oldColor);\n      oldColor = reshape(oldColor,[1 1 3]);\n      hh = rgb2hsv(oldColor);\n      hh(3) = min(hh(3)-0.2,1);\n      newColor = hsv2rgb(hh);\n      newColor = reshape(newColor,oldSize);\n    end\n\n  end\nend", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/ShiftColor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358016, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5802887743465485}}
{"text": "function pass = test_innerProduct(pref)\n\nif ( nargin < 1 )\n    pref = chebfunpref();\nend\n\nsingPref = pref;\nsingPref.blowup = true;\n\n% Seed for random number:\nseedRNG(6178);\n\n%% Functions on [-inf inf]:\n\n% Set the domain:\ndom = [-Inf Inf];\n\nopf = @(x) 2-exp(-x.^2);\nopg = @(x) exp(-x.^2);\nf = unbndfun(opf, struct('domain', dom));\ng = unbndfun(opg, struct('domain', dom));\n\nI = innerProduct(f, g);\nIExact = (sqrt(pi)*(4 - sqrt(2)))/2;\nerr = abs(I - IExact);\npass(1) = err < 2e7*max(eps*get(f,'vscale'), ...\n    eps*get(g,'vscale'));\n\n%% Functions on [a inf]:\n\n% Set the domain:\ndom = [1 Inf];\n\nopf = @(x) x;\nopg = @(x) exp(-x);\npref = chebfunpref();\nf = unbndfun(opf, struct('domain', dom, 'exponents', [0 1]), pref);\ng = unbndfun(opg, struct('domain', dom));\nwarning('off', 'CHEBFUN:UNBNDFUN:sum:slowDecay');\nI = innerProduct(f, g);\nwarning('off', 'CHEBFUN:UNBNDFUN:sum:slowDecay');\nIExact = 2*exp(-1);\nerr = abs(I - IExact);\npass(2) = err < 2e8*max(eps*get(f,'vscale'), ...\n    eps*get(g,'vscale'));\n\n%% Functions on [-inf b]:\n\n% Set the domain:\ndom = [-Inf -3*pi];\n\nopf = @(x) 1./x;\nopg = @(x) 2./x;\nf = unbndfun(opf, struct('domain', dom));\ng = unbndfun(opg, struct('domain', dom));\nI = innerProduct(f, g);\nIExact = 2/(3*pi);\nerr = abs(I - IExact);\npass(3) = err < 1e5*eps*get(f,'vscale');\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/unbndfun/test_innerProduct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.580288766072511}}
{"text": "function [atm] = hPa2atm(hPa)\n% Convert pressure from hectopascals to atmospheres.\n% Chad Greene 2012\natm = hPa*0.000986923;", "meta": {"author": "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/hPa2atm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5802751524753407}}
{"text": "switch input_sig\n    case 1          % 1: synthetic data\n        if load_sig\n            load matlab\n        else\n        A_0=randn(n1,data.r)*randn(data.r,n2);  % true low-rank matrix A_0\n%         A_max=max(abs(A_0(:)));\n        A_max=sqrt(max(n1,n2));\n        B_0=((rand(n1,n2)<.5)-.5)*2*A_max;\n        B_0(randperm(n1*n2,n1*n2-data.s))=0;    % true sparse matrix B_0\n%         X_0=A_0+B_0; Z=X_0;\n        Z=A_0+B_0;\n%         Z=randn(size(Z));\n        end\n        \n    case 2          % 2: airport video\n        addpath('./video_airport')\n        nFrame=200;\n        iFrame=1000;\n        pathname=['airport',num2str(iFrame),'.bmp'];\n        Z1=imread(pathname);\n        Z1=double(uint8(round(sum(Z1,3)/3)))/255;\n        Z=zeros(size(Z1,1),size(Z1,2),nFrame);\n        Z(:,:,1)=Z1;\n        for j=1:nFrame-1\n            pathname=['airport',num2str(iFrame+j),'.bmp'];\n            Z1=imread(pathname);\n            Z1=double(uint8(round(sum(Z1,3)/3)))/255;\n            Z(:,:,j+1)=Z1;\n        end\n        \n        [z1,z2,z3]=size(Z); \n        n1=z1*z2; n2=z3;\n        Z=reshape(Z,n1,n2);\n        \n        clear nFrame iFrame pathname Z1\n        \n    case 3          % 3: lobby video\n        addpath('./video_lobby')\n        nFrame=400;\n        iFrame=1900;\n        pathname=['SwitchLight',num2str(iFrame),'.bmp'];\n        Z1=imread(pathname);\n        Z1=double(uint8(round(sum(Z1,3)/3)))/255;\n        Z=zeros(size(Z1,1),size(Z1,2),nFrame);\n        Z(:,:,1)=Z1;\n        for j=1:nFrame-1\n            pathname=['SwitchLight',num2str(iFrame+j),'.bmp'];\n            Z1=imread(pathname);\n            Z1=double(uint8(round(sum(Z1,3)/3)))/255;\n            Z(:,:,j+1)=Z1;\n        end\n        \n        [z1,z2,z3]=size(Z); \n        n1=z1*z2; n2=z3;\n        Z=reshape(Z,n1,n2);\n        \n        clear nFrame iFrame pathname Z1\nend\n        \n% add noise\n% noise=.0;\n% noise=.05*std(data);\nif ~load_sig && noise~=0\n    Z=Z+noise*randn(size(Z));                       % Gaussian noise\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/R2PCP/data_formation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5802751415337583}}
{"text": "function SDP = chordal_relax_category_registration_v2(problem,varargin)\n%% Apply a sparse, chordal, SECOND-order relaxation to category registration\n%% Depending on multivariate polynomial package in SPOT\n%% residual of v1: b(i) - R * (sum_k c_k ak(i)) - t\n%% residual of v2: R*b(i) + t - sum_k c_k ak(i)\n%% Heng Yang\n%% July 06, 2021\n\nparams = inputParser;\nparams.CaseSensitive = false;\n\nparams.addParameter('checkMonomials',true, @(x) islogical(x));\nparams.addParameter('lambda',0.1, @(x) isscalar(x));\n\nparams.parse(varargin{:});\n\ncheckMonomials = params.Results.checkMonomials;\nlambda         = params.Results.lambda;\n\nfprintf('\\n===================================================================')\nfprintf('\\nApplying Chordal SDP relaxation to category registration problem')\nfprintf('\\n===================================================================\\n')\nt0              = tic;\n\nN               = problem.N;\nK               = problem.K;\nscene           = problem.scene;\nshapes          = problem.shapes;\nnoiseBoundSq    = problem.noiseBoundSq;\ntBound          = problem.translationBound;\ntBoundSq        = tBound^2; % t'*t <= tBoundSq\ncBoundSq        = problem.cBound^2; % should just be 1\nbarc2           = 1.0;\n\n%% define POP variables\nnrPrimalVars    = 9+3+K+N; % rotation: 9, translation: 3, binary: N, shape: K\np               = msspoly('p',nrPrimalVars);\nr               = p(1:9);\nR               = reshape(r,3,3); \ncol1 = R(:,1); col2 = R(:,2); col3 = R(:,3);\nt               = p(10:12);\nc               = p(12+1:12+K);\ntheta           = p(12+K+1:nrPrimalVars);\nx               = [r;t;c];\n\n%% define cost function\nshape           = combine_shapes(shapes,c);\nresiduals       = [];\nfor i = 1:N \n    distance            = R*scene(:,i) + t - shape(:,i);\n    residuals           = [residuals; (distance' * distance) / noiseBoundSq];\nend\nf_cost = lambda * (c'*c); % regularization term\nfor i = 1:N\n    f_cost = [f_cost;(1+theta(i))/2 * residuals(i) + (1-theta(i))/2 * barc2];\nend\n\n%% define constraints\nh_r  = [1.0-col1'*col1;...\n        1.0-col2'*col2;...\n        1.0-col3'*col3;... % column unit length\n        col1'*col2;...\n        col2'*col3;...\n        col3'*col1;... % colums orthogonal\n        cross(col1,col2) - col3;...\n        cross(col2,col3) - col1;...\n        cross(col3,col1) - col2]; % columns righthandedness\n\nh_theta = [];\nfor i = 1:N \n    h_theta =[h_theta; 1-theta(i)^2];\nend\n\ng_t = tBoundSq - t'*t; % Translation bounded\ng_c = [cBoundSq - c'*c;c]; % nonnegative and bounded shape parameters\ng_x = [g_t;g_c];\n\n%% Formulate the chordal sparse second-order relaxation\n%% the 0-th block [1;x] * [1;x]'\nbasis0          = [1;x];\nn0              = length(basis0);\nbasis_x0        = get_multiplier_basis(x,basis0,h_r(1));\npop0            = [mykron(basis_x0,h_r);...\n                   mykron(basis0,basis0);...\n                   f_cost(1)];\n[~,degmat,coef_all] = decomp(pop0);\ncoef_all            = coef_all';\ndim_loc0        = length(basis_x0) * length(h_r);\nn0delta         = triangle_number(n0);\nnterms          = size(degmat,1);   \nm_mom0          = n0delta - nterms;\n\nassert(m_mom0==0,'The zero-th blk should have 0 moment constraints.')\n\ncoef_mom    = coef_all(:,dim_loc0+1:dim_loc0+n0^2);\ncoef_mom    = coef_mom';\nB           = {};\nB_normalize = {};\n\nfor i = 1:nterms\n    [row,~,~]   = find(coef_mom(:,i));\n    SDP_coli    = floor((row-1)./n0) + 1;\n    SDP_rowi    = mod(row-1,n0) + 1;\n    nnz         = length(SDP_rowi);\n    \n    Bi          = sparse(SDP_rowi,SDP_coli,ones(nnz,1),n0,n0);\n    B{end+1}    = Bi;\n    B_normalize{end+1} = Bi/nnz;\nend\n\ncoef_loc0       = coef_all(:,1:dim_loc0);\nA0_local        = {};\n\nfor i = 1:dim_loc0\n    [rowi,~,vi] = find(coef_loc0(:,i));\n    Ai      = sparse(n0,n0);\n    for j   = 1:length(rowi)\n        Ai  = Ai + vi(j) * B_normalize{rowi(j)};\n    end\n    A0_local = [A0_local;{Ai}];\nend\nA0_0    = sparse([1],[1],[1],n0,n0);\n% The first block satisfies A0(X0) = b0;\nA0      = [{A0_0};A0_local];\nb0      = sparse(1,1,1,length(A0),1);\n\n% Now build the cost matrix\ncoef_cost   = coef_all(:,dim_loc0+n0^2+1);\n[row,~,v]   = find(coef_cost);\nC           = sparse(n0,n0);\nfor i = 1:length(row)\n    C       = C + v(i) * B_normalize{row(i)};\nend\n\n%% the 1-N blocks [1;x;theta(i);theta(i)*x] * [1;x;theta(i);theta(i)*x]'\n%% Since there are (2+K) inequality constraints, it will generate (K+3)*N blocks\nnrineq          = length(g_x);\nAall            = {};\nAsuball         = {};\nball            = [];\nCall            = {C};\nA0append        = {};\nfor blkidx = 1:N\n    basis       = [1;x;theta(blkidx);theta(blkidx)*x];\n    n           = length(basis);\n    basis_x     = get_multiplier_basis([x;theta(blkidx)],basis,h_r(1),0);\n    basis_theta = get_multiplier_basis([x;theta(blkidx)],basis,h_theta(blkidx),0);\n    basis_g     = [1;theta(blkidx)];\n    \n    out         = gen_chordal_subblk_catreg_v2(...\n        basis,basis_x,h_r,basis_theta,h_theta(blkidx),g_x,basis_g,f_cost(1+blkidx));\n    \n    Acell       = out.A;\n    Asub        = out.Asub;\n    b           = out.b;\n    C           = out.C;\n    \n    % add constraint that the top-left [1;x]*[1;x]' block is the same as\n    % the 0-th block\n    A0blk = {};\n    for i = 1:n0\n        for j = i:n0\n            if i == j\n                A0i  = sparse(i,j,-1,n0,n0);\n                Ai   = sparse(i,j,1,n,n);\n            else\n                A0i  = sparse([i,j],[j,i],[-0.5,-0.5],n0,n0);\n                Ai   = sparse([i,j],[j,i],[0.5,0.5],n,n);\n            end\n            A0blk    = [A0blk;{A0i}];\n            Acell    = [Acell;{Ai}];\n        end\n    end\n    \n    ball             = [ball;b;sparse(n0delta,1)];\n    A0append{end+1}  = A0blk;\n    Aall{end+1}      = Acell;\n    Call             = [Call;C];\n    Asuball{end+1}   = Asub;\nend\n\n%% Convert to standard SDPT3 format\nb           = [b0;ball];\nblk         = cell( (nrineq+1)*N+1,2);\nblk{1,1}    = 's'; blk{1,2} = n0;\nn1          = out.blk{2,2};\nn1delta     = triangle_number(n1);\nstep        = nrineq + 1;\nfor i = 1:N\n    blk{step*i-nrineq+1,1} = 's';\n    blk{step*i-nrineq+1,2} = n;\n    for j = 1:nrineq\n        blk{step*i-nrineq+j+1,1} = 's';\n        blk{step*i-nrineq+j+1,2} = n1;\n    end\nend\n\nA0t     = sparsesvec(blk(1,:),A0);\nfor i = 1:N\n    A0t = [A0t,...\n           sparse(n0delta,out.m),...\n           sparsesvec(blk(1,:),A0append{i})];\nend\n\nndelta  = triangle_number(n);\nAt      = {A0t};\nfor i = 1:N\n    Ait = [sparse(ndelta,length(b0)),...\n           sparse(ndelta,(i-1)*length(Aall{i})),...\n           sparsesvec(blk(step*i-nrineq+1,:),Aall{i}),... % the moment matrix block\n           sparse(ndelta,(N-i)*length(Aall{i}))];\n    At  = [At;{Ait}];\n    for j = 1:nrineq\n        Aijt    = [sparse(n1delta,length(b0)),...\n                    sparse(n1delta,(i-1)*length(Aall{i})),...\n                    sparse(n1delta,out.m_mom+out.m_loc),... % the moment constraint\n                    sparse(n1delta,(j-1)*n1delta),...\n                    sparsesvec(blk(step*i-nrineq+j+1,:),Asuball{i}{j}),...\n                    sparse(n1delta,(nrineq-j)*n1delta),...\n                    sparse(n1delta,n0delta),...\n                    sparse(n1delta,(N-i)*length(Aall{i}))];\n\n        At  = [At;{Aijt}];\n    end\nend\n\nSDP.blk = blk;\nSDP.At  = At;\nSDP.m   = length(b);\nSDP.C   = Call;\nSDP.b   = b;\n\ntf    = toc(t0);\nfprintf('\\nDone in %g seconds.\\n',tf);\nfprintf('===================================================================\\n')\n\n%% Convert to Sedumi format\nfprintf('Convert to Sedumi format ...\\n')\nt0    = tic;\nsK.s  = [n0];\nfor i = 1:N\n    sK.s        = [sK.s,n,n1*ones(1,nrineq)];\nend\n\nA0t     = sparsevec(blk(1,:),A0);\nn0sq    = n0^2;\nfor i = 1:N\n    A0t = [A0t,...\n           sparse(n0sq,out.m),...\n           sparsevec(blk(1,:),A0append{i})];\nend\n\nnsq     = n^2;\nn1sq    = n1^2;\nAt      = {A0t};\nfor i = 1:N\n    Ait = [sparse(nsq,length(b0)),...\n           sparse(nsq,(i-1)*length(Aall{i})),...\n           sparsevec(blk(step*i-nrineq+1,:),Aall{i}),... % the moment matrix block\n           sparse(nsq,(N-i)*length(Aall{i}))];\n    At  = [At;{Ait}];\n    for j = 1:nrineq\n        Aijt    = [sparse(n1sq,length(b0)),...\n                    sparse(n1sq,(i-1)*length(Aall{i})),...\n                    sparse(n1sq,out.m_mom+out.m_loc),... % the moment constraint\n                    sparse(n1sq,(j-1)*n1delta),...\n                    sparsevec(blk(step*i-nrineq+j+1,:),Asuball{i}{j}),...\n                    sparse(n1sq,(nrineq-j)*n1delta),...\n                    sparse(n1sq,n0delta),...\n                    sparse(n1sq,(N-i)*length(Aall{i}))];\n\n        At  = [At;{Aijt}];\n    end\nend\n\nsdata.K     = sK;\nsdata.At    = cat(1,At{:});\nsdata.b     = b;\n\nsc          = [];\nfor i = 1:length(Call)\n    sc      = [sc;sparsevec(blk(i,:),Call(i))];\nend\nsdata.c     = sc;\n\nSDP.sedumi   = sdata;\n\n\ntf    = toc(t0);\nfprintf('Done in %g seconds.\\n',tf);\nfprintf('===================================================================\\n')\n\n\nend", "meta": {"author": "MIT-SPARK", "repo": "CertifiablyRobustPerception", "sha": "dd149d0c54093cfb72a8f912f4ae807635db6f3b", "save_path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception", "path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception/CertifiablyRobustPerception-dd149d0c54093cfb72a8f912f4ae807635db6f3b/CategoryRegistration/solvers/chordal_relax_category_registration_v2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5802737538400777}}
{"text": "function [G1, impact] = sparse_solver(g1,psi,n_v,n_g)\n%% NOTE: THIS SOLVER WILL BE UPDATED TO MATCH SCHUR_SOLVER EVENTUALLY\n% Solves the rational expectation model with sparse iteration\n%    method. You should use this method of the number of stable and\n%    unstable solution differ a lot. Otherwise, full matrix \n%    decomposition method should be used.\n%\n% by SeHyoun Ahn, June 2016\n%\n% PARAMETERS/OUTPUTS:\n%     Read attached documentation\n%\n% SYNTAX:\n% [G1, impact] = sparse_solver(g1,psi,n_v,n_g)\n\n\n%-100 is set to find negative eigenvalues. This value can be changed\n[x,v,flag] = eigs(g1,n_g,-100);\nimpact = real(x*(x(n_v+1:end,:)\\psi(n_v+1:end,:)));\nG1 = real(x*v*(x(n_v+1:end,:)\\[sparse(n_g,n_v),speye(n_g,n_g)]));\n", "meta": {"author": "gregkaplan", "repo": "phact", "sha": "4cd7ff0c013b082db9c2ca070225feaff1056123", "save_path": "github-repos/MATLAB/gregkaplan-phact", "path": "github-repos/MATLAB/gregkaplan-phact/phact-4cd7ff0c013b082db9c2ca070225feaff1056123/sparse_solver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5802737485116868}}
{"text": "classdef nnpdist < nntest\n  properties (TestParameter)\n    oneToOne = {false, true}\n    noRoot = {false, true}\n    p = {.5 1 2 3}\n    aggregate = {false, true}\n  end\n  methods (Test)\n    function basic(test,oneToOne, noRoot, p, aggregate)\n      if aggregate\n        % make it smaller to avoid numerical derivative issues with\n        % float\n        h = 3 ;\n        w = 2 ;\n      else\n        h = 13 ;\n        w = 17 ;\n      end\n      d = 4 ;\n      n = 5 ;\n      x = test.randn(h,w,d,n) ;\n      if oneToOne\n        x0 = test.randn(h,w,d,n) ;\n      else\n        x0 = test.randn(1,1,d,n) ;\n      end\n      opts = {'noRoot', noRoot, 'aggregate', aggregate} ;\n\n      y = vl_nnpdist(x, x0, p, opts{:}) ;\n\n      % make sure they are not too close in any dimension as this may be a\n      % problem for the finite difference dereivatives as one could\n      % approach 0 which is not differentiable for some p-norms\n\n      s = abs(bsxfun(@minus, x, x0)) < test.range*1e-1 ;\n      x(s) = x(s) + 5*test.range ;\n\n      dzdy = test.rand(size(y)) ;\n      dzdx = vl_nnpdist(x,x0,p,dzdy,opts{:}) ;\n      test.der(@(x) vl_nnpdist(x,x0,p,opts{:}), x, dzdy, dzdx, test.range * 1e-3) ;\n    end\n  end\nend\n", "meta": {"author": "willard-yuan", "repo": "cnn-for-image-retrieval", "sha": "2e3e8ab76e2c971314be55b5ae44e02884003261", "save_path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval/cnn-for-image-retrieval-2e3e8ab76e2c971314be55b5ae44e02884003261/matconvnet-1.0-beta18/matlab/xtest/suite/nnpdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5802737429780079}}
{"text": "function test_ft_timelockstatistics\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_timelockstatistics findcluster clusterstat ft_statistics_montecarlo\n\n%For the case of \"chan_time\"\n\n% make fake dataset\ntimelock = cell(1,10);\nfor idat = 1:10\n  timelock{idat}.label = {'chan1','chan2','chan3'};\n  timelock{idat}.dimord = 'chan_time';\n  timelock{idat}.avg = rand(3,30);\n  timelock{idat}.time = 0.1:0.1:3;\n  timelock{idat}.cfg = [];\nend\n\n% do stats - montecarlo\ncfg = [];\nneighbours(1).label = 'chan1';\nneighbours(1).neighblabel = {'chan2', 'chan3'};\nneighbours(2).label = 'chan2';\nneighbours(2).neighblabel = {'chan1', 'chan3'};\nneighbours(3).label = 'chan3';\nneighbours(3).neighblabel = {'chan1', 'chan2'};\ncfg.neighbours  = neighbours;\ncfg.method      = 'montecarlo';\ncfg.statistic   = 'ft_statfun_depsamplesT';\ncfg.alpha       = 0.05; \ncfg.correctm    = 'cluster'; \ncfg.clusterstatistic = 'maxsum';\ncfg.clusterthreshold = 'parametric';\ncfg.numrandomization = 500;\ncfg.design = [ones(1,5) ones(1,5).*2; 1:5 1:5;];\ncfg.ivar   = 1;\ncfg.uvar   = 2;\nstat = ft_timelockstatistics(cfg,timelock{:});\n\n% do stats - analytic\ncfg = [];\ncfg.method      = 'analytic';\ncfg.statistic   = 'ft_statfun_depsamplesT';\ncfg.alpha       = 0.05; \ncfg.design = [ones(1,5) ones(1,5).*2; 1:5 1:5;];\ncfg.ivar   = 1;\ncfg.uvar   = 2;\nstat = ft_timelockstatistics(cfg,timelock{:});\n\n\n% do stats - analytic\ncfg = [];\ncfg.method      = 'stats';\ncfg.statistic   = 'ttest';\ncfg.alpha       = 0.05; \ncfg.design = [ones(1,10) ];\nstat = ft_timelockstatistics(cfg,timelock{:});\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/test/test_ft_timelockstatistics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5802737404164567}}
{"text": "function [gx] = g_rbf(x,P,u,in)\n\ncenters = in.centers + exp(P(1));\nsig = exp(P(2));\n\nN = length(in.centers);\nXrbf = zeros(length(in.grid),N);\nfor i=1:N\n    Xrbf(:,i) = exp(-0.5*(centers(i)-in.grid).^2./sig);\n    Xrbf(:,i) = Xrbf(:,i)./sum(Xrbf(:,i));\nend\n\ngx = zeros(N,1);\nfor i=1:N\n    y = Xrbf(:,i);\n    X = Xrbf(:,setdiff(1:N,i));\n    P0 = eye(length(in.grid)) - X*pinv(X'*X)*X';\n    err = y'*P0*y;\n    gx(i) = sum(err);\nend\n\ngx = gx + P(3);\n\nif ~in.corr\n    gx = Xrbf;\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/demos/_models/g_rbf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5802732445807106}}
{"text": "% Calculate feature vector for a triangle\n%\n\n% Feature vector is:\n%   centroid_x\n%   centroid_y\n%   orientation_1\n%   orientation_2\n%   orientation_3\n%   area\nfunction features = triangleFeatures(points)\n    features = zeros(6, 1);\n\n    fCentrX = 1;\n    fCentrY = 2;\n    fOr1 = 3;\n    fOr2 = 4;\n    fOr3 = 5;\n    fArea = 6;\n\n    centr = centroid(points);\n    features(fCentrX) = centr(1);\n    features(fCentrY) = centr(2);\n\n    line = createLine(centr, points(1, :));\n    features(fOr1) = rad2deg(lineAngle(line));\n\n    line = createLine(centr, points(2, :));\n    features(fOr2) = rad2deg(lineAngle(line));\n\n    line = createLine(centr, points(3, :));\n    features(fOr3) = rad2deg(lineAngle(line));\n    \n%     features(fArea) = triangleArea(points(1, :), points(2, :), points(3, :));\n\n    features(6) = points(1, 1);\n    features(7) = points(1, 2);\n    features(8) = points(2, 1);\n    features(9) = points(2, 2);\n    features(10) = points(3, 1);\n    features(11) = points(3, 2);\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/triangleFeatures.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5802732177714894}}
{"text": "%Hand-eye calibration\n%\n%This add on allows to compute the hand to eye calibration based ont he\n%calibration toolbox from Jean-Yves Bouguet\n%see http://www.vision.caltech.edu/bouguetj/calib_doc/\n%more information can be found here:\n%http://www.vision.ee.ethz.ch/~cwengert/calibration_toolbox.php\n%\n%You need to have computed the intrinsic and extrinsic parameters of your\n%camera (the extrinsic parameters with respect to the grid's local\n%coordinate system). Then you also need to supply the pose / transformation\n%of the robot arm / marker with repsect to the robot base / external\n%tracking device in the following format:\n%Pack into a 4x4xNumber_of_Views Matrix the following data\n%Hmarker2world(:,:,i) = [Ri_3x3 ti_3x1;[ 0 0 0 1]] \n%with \n%i = number of the view, \n%Ri_3x3 the rotation matrix \n%ti_3x1 the translation vector.\n%\n%The following parameters can be set (if not set the default values are\n%used):\n%doShow [default=0]: \n%Display the results from the calibration\n%doSortHandEyeMovement [default=0]:\n%Set this to 1 if you want your views sorted in a way that the interstation\n%movement is ideal for hand-eye calibration, see [Tsai]\n%HandEyeMethod\t[default = 'Tsai']\n%Here you specifiy which method you want to use for the\n%hand-eye calibration, default is using Tsai's method. See\n%ftp://ftp.vision.ee.ethz.ch/publications/proceedings/eth_biwi_00363.pdf\n%Possible values are 'Tsai', 'Inria', 'Dual_quaternion', 'Navy'\n%Tsai, Inria and Navy give the same results and are usually a bit better\n%than the Dual quaternion approach\n%\n%Christian Wengert\n%Computer Vision Laboratory\n%ETH Zurich\n%Sternwartstrasse 7\n%CH-8092 Zurich\n%www.vision.ee.ethz.ch/cwengert\n%wengert@vision.ee.ethz.ch\n\n\n%With the doShow flag you can show the results\nif(~exist('doShow')) \n    doShow = 0;\nend\n\n%Tsai states that the inter-station movement should be as large as possible\n%for better accuracy. This flag will sort the movements for higher\n%accuracy\nif(~exist('doSortHandEyeMovement'))\n    doSortHandEyeMovement = 0;\nend\n\n%If it does, check whether the Hrobot2hand exists\nif(~exist('Hmarker2world'))    \n    disp(['handeye:: No Hmarker2world data available, Hand eye calibration aborted']);\n    return\nend\n\n%If it does, check whether the Hrobot2hand exists\nif(~exist('HandEyeMethod'))    \n    HandEyeMethod = 'Tsai';\nend\n\n%Now go on\ndisp(['handeye:: Hand-Eye Calibration']);\ncorrectSets = 0;\nfor i=1:length(active_images)\n    if(active_images(i)~=0 && Hmarker2world(1,1,i)~=0) %Make sure its a calibration image and it has tracker info\n        %Extract extrinsic parameters\n        correctSets = correctSets+1;\n        eval(['Rc = Rc_' num2str(active_images(i)) ';']);%%%%%%%%%%%%%%%%%%%%%ACHTUNG\n        eval(['Tc = Tc_' num2str(active_images(i)) ';']);\n        Hgrid2cam(:,:,correctSets) = inv(([Rc Tc;[ 0 0 0 1]]));\n        Hcam2grid(:,:,correctSets) = inv(Hgrid2cam(:,:,correctSets));\n        Hm2w(:,:,correctSets) = Hmarker2world(:,:,active_images(i));\n    end\nend\nif(correctSets)        \n    %Remove bad trackerdata\n    badTrackerDataIndex = [];\n    for i=1:correctSets\n        if(abs(Hm2w(1,1,i))<1e-18) %Its bad\n            badTrackerDataIndex = [badTrackerDataIndex;i];\n            correctSets = correctSets-1;\n        end\n    end    \n    %Init\n    Hm2w(:,:,badTrackerDataIndex) = [];\n    Hcam2grid(:,:,badTrackerDataIndex) = [];\n    Hgrid2cam(:,:,badTrackerDataIndex) = [];\n    if(doSortHandEyeMovement)\n        index = sortHandEyeMovement(Hm2w);\n    else\n        index = 1:size(Hm2w,3);          \n    end\n    Hm2w2 = Hm2w(:,:,index);\n    Hcam2grid2 = Hcam2grid(:,:,index);\n    %Now calibrate\n    switch(HandEyeMethod)\n        case 'Tsai'\n            [Hcam2marker_, err] = TSAIleastSquareCalibration(Hm2w2, Hcam2grid2)\n        case 'Inria'\n            [Hcam2marker_, err] = inria_calibration(Hm2w, Hcam2grid2);\n        case 'Navy'\n            [Hcam2marker_, err] = navy_calibration(Hm2w, Hcam2grid2);\n        case 'Dual_quaternion'\n            [Hcam2marker_, err] = hand_eye_dual_quaternion(Hm2w, Hcam2grid) ;\n    end\n    %Create the average Hworld2grid, givin an idea where the grid is\n    %in the coordinate system of the tracker/robot\n    for i=1:correctSets\n        Hcam2world_(:,:,i) = Hm2w(:,:,i)*Hcam2marker_;  %Hc2m(:,:,k)\n        Hworld2cam_(:,:,i) = inv(Hcam2world_(:,:,i));\n        %The above is correct as it gives the same as in my\n        %simulation\n        Hgrid2world_(:,:,i) = Hcam2world_(:,:,i)*Hcam2grid(:,:,i);\n        Hworld2grid_(:,:,i) = inv(Hgrid2world_(:,:,i));\n    end\n    %Average it, using the algorithm described in ...                \n    Hgrid2worldAvg = averageTransformation(Hgrid2world_);\n    xd = [];\n\n\n    %BACKPROJECT, this computes and displays the result\n    errAvg = [];\n    correctSets = 0;\n    for i=1:length(active_images)\n        if(active_images(i)~=0)\n            correctSets  = correctSets + 1;\n            if(correctSets<=length(Hm2w))\n                err = [];\n                eval(['tmp = X_' num2str(active_images(i)) ';'])\n                eval(['ALLPTS.X_' num2str(correctSets) ' = X_' num2str(active_images(i)) ';'])\n                tmp = [tmp, [[0;0;0],[3;0;0]]];\n                eval(['xd_' num2str(correctSets) ' = x_' num2str(active_images(i)) ';']);\n                eval(['allpts.xd_' num2str(correctSets) ' = x_' num2str(active_images(i)) ';']);\n                Xworld = Hgrid2world_(:,:,correctSets)*[tmp;ones(1,length(tmp))];\n                XworldAvg = Hgrid2worldAvg*[tmp;ones(1,length(tmp))];     %\n                [P,x] = backprojectDistorted(KK,Hworld2cam_(1:3,1:3,correctSets),Hworld2cam_(1:3,4,correctSets),XworldAvg,kc);\n\n                %Compute error\n                eval(['xd = xd_' num2str(correctSets) ';']);\n                m = length(xd);\n                for j=1:m\n                    err(j) = norm(x(:,j)-xd(:,j));\n                end\n                %per point\n                errAvg(correctSets) = sum(err)/m;\n                %Store it\n                result.error_calib_avg(correctSets) = errAvg(correctSets);\n                %GFX\n                if(doShow)\n                    hold off,figure(n_ima+1),hold on\n                    if(isfloat(im))\n                        eval(['imshow(I_' num2str(i) '/255);']);,hold on\n                    else\n                        eval(['imshow(I_' num2str(i) ');']);,hold on\n                    end\n                    \n                    \n                    hold on\n                    draw2DPoints(x(:,1:m), '', 0, n_ima+1)\n                    plot(x(1,end-1:end),x(2,end-1:end),'rx','MarkerSize',25,'LineWidth',3);\n                    draw2DPoints(xd, 'blue(real), red guessed', 0, n_ima+1,'bd')\n                    title(['Error = ' num2str(sum(err)/m) ' image ' num2str(i)]);\n                    axis equal\n                    pause\n                end\n            end\n        end\n    end\n    backprojection_error = sum(errAvg)/correctSets\nend\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/handeye.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937772, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5801707715679871}}
{"text": "function [mps2] = cmps22mps2(cmps2)\n% Convert acceleration from centimeters per square centimeter to meters\n% per second-squared.\n% Chad A. Greene 2012\nmps2 = cmps2*1e-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/35258-unit-converters/unit_converters/cmps22mps2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5801707531181919}}
{"text": "function [pvals,is_significant] = test_significance(TestData,W,p,nnull)\n%\n% USAGE: \n%\n% [pvals,is_significant] = test_significance(TestData,W,0.01)\n%\n% ------------------------------------------------------------------------\n% DESCRIPTION:\n%\n% Tests each factor in W for significance using a held out test dataset at\n% a p-value of p using Bonferroni correction. \n%  \n% ------------------------------------------------------------------------\n%\n% INPUTS:\n%\n% Name              Default                 Description\n% TestData                                  Held out data matrix (NxT) \n% W                                         NxKxL tensor containing factor exemplars\n% p                 0.05                    Desired p-value to test\n% nnull             ceil(K/p)*2             Number of null datasets to use\n%\n% ------------------------------------------------------------------------\n% OUTPUTS:\n%\n% pvals                      A vector (1xK) containing the p-value of each factor\n% is_significant             A boolean vector (1xK) which is 1 if a factor\n%                            is significant using the specified pvalue with correction\n%\n% ------------------------------------------------------------------------\n% CREDITS:\n%   Emily Mackevicius and Andrew Bahle, 2/1/2018\n%\n%   Please cite our paper: \n%       XXXXXXXXXXXXXXXXXXXXX\n% Remove factors where there is obviously no sequence\n% That is, W is empty, or has one neuron with >99.9% of the power\n\nindempty = sum(sum(W>0,1),3)==0; % W is literally empty\nWflat = sum(W,3); \nindempty = indempty | (max(Wflat,[],1).^2> .999*sum(Wflat.^2,1)); % or one neuron has >99.9% of the power\nW(:,indempty,:) = []; % Delete factors that meet the above critera\n\n[N,K,L] = size(W);\n[~,T] = size(TestData);\n\nif nargin < 3\n    p = 0.05;\nend\n\nif nargin < 4\n    nnull = ceil(K/p)*2;\nend\n\n% make nnull shifted datasets \nskewnull = zeros(K,nnull);\n\nX = TestData;\n\nfor n = 1:nnull\n    % Make a null dataset\n    Wnull = zeros(N,K,L);\n    for k = 1:K\n        for ni = 1:N\n            %Wnull(ni,k,:) = circshift(W(ni,k,:),randi(L));\n            Wnull(ni,k,:) = circshift(W(ni,k,:),[0,0,randi(L)]);\n        end\n    end\n    %figure, imagesc(squeeze(Wnull(:,1,:))), colormap(gca, flip(gray)),axis off\n    % Calculate WTX\n    WTX = zeros(K, T);\n    for l = 1 : L\n        %X_shifted = circshift(X,-l+1,2);       \n        X_shifted = circshift(X,[0,-l+1]);       \n        WTX = WTX + Wnull(:, :, l)' * X_shifted;\n    end   \n    %figure, histogram(WTX(1,:),0:1:100,'FaceColor','k')\n    %set(gca,'yscale','log'), ylim([0,10e2])\n    % Get skewness of each\n    skewnull(:,n) = skewness(WTX,1,2);\nend\n\n\nWTX = zeros(K, T);\nfor l = 1 : L\n    %X_shifted = circshift(X,-l+1,2);       \n    X_shifted = circshift(X,[0,-l+1]);       \n    WTX = WTX + W(:, :, l)' * X_shifted;\nend   \nskew = skewness(WTX,1,2);\nfor k = 1:K\n    % Assign pvals from skewness\n    pvals(k) = (1+sum(skewnull(k,:)>skew(k)))/nnull;\nend\nallpvals(indempty) = Inf; \nallpvals(~indempty) = pvals; \npvals = allpvals;\nis_significant = (pvals <= p/K);\nend", "meta": {"author": "FeeLab", "repo": "seqNMF", "sha": "229b9b19ac3a34b8378945ec7f9e331e004bb777", "save_path": "github-repos/MATLAB/FeeLab-seqNMF", "path": "github-repos/MATLAB/FeeLab-seqNMF/seqNMF-229b9b19ac3a34b8378945ec7f9e331e004bb777/test_significance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5801707359715734}}
{"text": "function [SR, report] = mapsr(LRImages, model, varargin)\n  \n    if nargin > 2\n        solverParams = varargin{end};\n    else\n        % Use default solver parameters\n        solverParams = SRSolverParams;\n    end\n        \n    % Assemble equation system to be solved consisting of low-resolution\n    % observations and the system matrix.\n    lrDim = size(LRImages(:,:,1));\n    if solverParams.verbose\n        disp('Assemble equation system (system matrix)...');\n    end\n    [W, LRImages] = composeSREquationSystem(LRImages, model);\n        \n    if isempty(model.SR)\n        % Compute initial guess for the super-resolved image. We use the\n        % \"average image\" estimated from the system matrix and photometric\n        % parameters (if available).\n        if solverParams.verbose\n            disp('Compute average image used as initial guess...');\n        end\n        SR = getInitialSRImage(W, LRImages, model.photometricParams);\n    else\n        % Use initial guess provided by the user and reshape 2-D image into\n        % parameter vector.\n        SR = imageToVector(model.SR);\n    end\n        \n    scgOptions = setupSCGOptions(solverParams);\n    if solverParams.verbose\n        disp('Minimize objective function...');\n    end\n    [SR, ~, flog, ~, ~]  = scg(@mapfunc, SR', scgOptions, @mapfunc_grad, model, LRImages, W, W');\n    if nargout > 1\n        report.numFunEvals = length(flog);\n    end\n    \n    % Reshape parameter vector to a 2D image.\n    SR = vectorToImage(SR, model.magFactor * lrDim);\n    if solverParams.verbose\n        disp('DONE!');\n    end\n    \nfunction scgOptions = setupSCGOptions(solverParams)\n\n    scgOptions = zeros(1,18); \n    scgOptions(1) = 0;        \n    scgOptions(2) = solverParams.tolX;   \n    scgOptions(3) = solverParams.tolF;\n    scgOptions(9) = solverParams.gradCheck;\n    scgOptions(10) = solverParams.maxFunEvals;     \n    scgOptions(14) = solverParams.maxIter;\n\nfunction f = mapfunc(SR, model, LR, W, ~)\n    \n    if ~iscolumn(SR)\n        % Reshape to column vector. \n        SR = SR';\n    end\n    \n    % Evaluate the data fidelity term.\n    dataTerm = mapDataTerm(SR, model, LR, W);\n    \n    % Evaluate image prior for regularization the super-resolved estimate.\n    prior = model.imagePrior.function(SR, model.imagePrior.parameters{1:end});\n    \n    % Calculate objective function.\n    f = dataTerm + model.imagePrior.weight * prior;\n                \nfunction grad = mapfunc_grad(SR, model, LR, W, Wt)\n    \n    if ~iscolumn(SR)\n        % Reshape to column vector. \n        SR = SR';\n    end\n    \n    % Calculate gradient of the data fidelity term w.r.t. the\n    % super-resolved image.\n    dataTerm_grad = mapDataTerm_gradImage(SR, model, LR, W, Wt);\n    \n    % Calculate gradient of the regularization term w.r.t. the \n    % super-resolved image.\n    prior_grad = model.imagePrior.gradient(SR, model.imagePrior.parameters{1:end});\n    \n    % Sum up to total gradient\n    grad = dataTerm_grad + model.imagePrior.weight * prior_grad;\n    grad = grad';", "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/mapsr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5801680098876298}}
{"text": "%VGG_KR_FROM_P Extract K, R from camera matrix.\n%\n%    [K,R,t] = VGG_KR_FROM_P(P [,noscale]) finds K, R, t such that P = K*R*[eye(3) -t].\n%    It is det(R)==1.\n%    K is scaled so that K(3,3)==1 and K(1,1)>0. Optional parameter noscale prevents this.\n%\n%    Works also generally for any P of size N-by-(N+1).\n%    Works also for P of size N-by-N, then t is not computed.\n\n\n% Author: Andrew Fitzgibbon <awf@robots.ox.ac.uk>\n% Modified by werner.\n% Date: 15 May 98\n\n\nfunction [K, R, t] = vgg_KR_from_P(P, noscale)\n\nN = size(P,1);\nH = P(:,1:N);\n\n[K,R] = vgg_rq(H);\n  \nif nargin < 2\n  K = K / K(N,N);\n  if K(1,1) < 0\n    D = diag([-1 -1 ones(1,N-2)]);\n    K = K * D;\n    R = D * R;\n    \n  %  test = K*R; \n  %  vgg_assert0(test/test(1,1) - H/H(1,1), 1e-07)\n  end\nend\n\nif nargout > 2\n  t = -P(:,1:N)\\P(:,end);\nend\n\nreturn", "meta": {"author": "jmmanley", "repo": "VGG-Multiple-View-Geometry", "sha": "f114712de03082bb97229eaf2a65981908b64127", "save_path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry", "path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry/VGG-Multiple-View-Geometry-f114712de03082bb97229eaf2a65981908b64127/vgg_multiview/vgg_KR_from_P.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5801679937227022}}
{"text": "% demos for ch06\n\n\n%% Kernel regression with gaussian kernel\nclear; close all;\nn = 100;\nx = linspace(0,2*pi,n);   % test data\nt = sin(x)+rand(1,n)/2;\nmodel = knReg(x,t,1e-4,@knGauss);\n[y,s] = knRegPred(model,x);\nplotCurveBar(x,y,s);\nhold on;\nplot(x,t,'o');\nhold off;", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/demo/ch06/knReg_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.580167988834909}}
{"text": "classdef CEC2010_F14 < PROBLEM\n% <single> <real> <constrained>\n% CEC'2010 constrained optimization benchmark problem\n\n%------------------------------- Reference --------------------------------\n% R. Mallipeddi and P. N. Suganthan, Problem definitions and evaluation\n% criteria for the CEC 2010 competition on constrained real-parameter\n% optimization, Nanyang Technological University, Singapore, 2010.\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        O;  % Optimal decision vector\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2010.mat'),'Data');\n            obj.O = Data{14};\n            obj.M = 1;\n            if isempty(obj.D); obj.D = 10; end\n            obj.D = min(obj.D,length(obj.O));\n            obj.lower    = zeros(1,obj.D) - 1000;\n            obj.upper    = zeros(1,obj.D) + 1000;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            Z = 1 + PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopObj = sum(100*(Z(:,1:end-1).^2-Z(:,2:end)).^2+(Z(:,1:end-1)-1).^2,2);\n        end\n        %% Calculate constraint violations\n        function PopCon = CalCon(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopCon(:,1) = sum((-Z.*cos(sqrt(abs(Z)))),2) - size(Z,2);\n            PopCon(:,2) = sum((Z.*cos(sqrt(abs(Z)))),2) - size(Z,2);\n            PopCon(:,3) = sum((Z.*sin(sqrt(abs(Z)))),2) - 10*size(Z,2);\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/Single-objective optimization/CEC 2010/CEC2010_F14.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.580167988834909}}
{"text": "function gap = evalgap(fnc, fspec, dnorm, ww, uu, A, B, lambda)\n\n[ff,gg]=evalloss(fnc,ww,uu,A,B);\n\nfval = ff+lambda*sum(fspec(ww));\ndval = evaldual(fnc,dnorm,-gg,A,B,lambda);\n\ngap = (fval+dval)/fval;\n\nfunction [fval,gg]=evalloss(fnc, ww, uu, A, B)\n\nif ~isempty(uu)\n  zz=A*ww+B*uu;\nelse\n  zz=A*ww;\nend\n\n[fval, gg] =fnc.p(zz, fnc.args{:});\n\n\nfunction dval = evaldual(fnc, dnorm, aa, A, B, lambda)\n\nmm=length(aa);\n\nif ~isempty(B)\n  aa=aa-B*((B'*B)\\(B'*aa));\nend\n\n[dnm,ishard] =dnorm(A'*aa);\n\n\nif ishard && dnm>0\n  aa  = min(1, lambda/dnm)*aa;\n  dnm = 0; \nend\n\ndval = fnc.d(aa, fnc.args{:})+dnm;\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/external/dal_ver1.05/evalgap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5799953960077756}}
{"text": "function [K, sK] = heatXrbfhKernCompute(heatKern, rbfhKern, x1, x2)\n\n% HEATXRBFHKERNCOMPUTE Cross kernel between a HEAT and a RBF kernels.\n% FORMAT\n% DESC computes cross kernel terms between a HEAT kernel and a RBF kernel\n% for the multiple output kernel.\n% ARG heatKern : the kernel structure associated with the HEAT kernel.\n% ARG rbfKern : the kernel structure associated with the RBFH kernel.\n% ARG x1 : inputs for which kernel is to be computed. First column represent\n% the time points, while the second column represents the spatial points.\n% Entries with Inf indicate missing values.\n% RETURN K : block of values from kernel matrix.\n% RETURN sK : unscaled kernel matrix \n%\n% FORMAT\n% DESC computes cross kernel terms between a HEAT kernel and a RBF kernel\n% for the multiple output kernel.\n% ARG heatKern : the kernel structure associated with the HEAT kernel.\n% ARG rbfKern : the kernel structure associated with the RBFH kernel.\n% ARG x1 : row inputs for which kernel is to be computed. First column\n% corresponds to time points and the second column corresponds to spatial\n% points. Entries with Inf indicate missing values.\n% ARG x2 : column inputs for which kernel is to be computed. First column\n% corresponds to time points and the second column corresponds to spatial\n% points. Entries with Inf indicate missing values.\n% RETURN k : block of values from kernel matrix.\n% RETURN sK : unscaled kernel matrix \n%\n% SEEALSO : multiKernParamInit, multiKernCompute, heatKernParamInit\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\nif nargin < 4\n    x2 = x1;\nend\nif size(x1, 2) ~= 2 || size(x2, 2) ~= 2\n    error('Input can only have two columns');\nend\nif (heatKern.inverseWidthTime ~= rbfhKern.inverseWidthTime) || ...\n        (heatKern.inverseWidthSpace ~= rbfhKern.inverseWidthSpace)\n    error('Kernels cannot be cross combined if they have different inverse widths.')\nend\n\n% Split the domain into time domain and spatial domain and account for\n% missing values. If there are no missing values the computation of the\n% kernel is a pointwise prodruct, otherwise it is a kronecker product.\nt1 = x1(x1(:,1)~=Inf,1);\nt2 = x2(x2(:,1)~=Inf,1);\ns1 = x1(x1(:,2)~=Inf,2);\ns2 = x2(x2(:,2)~=Inf,2);\nif (length(t1) == length(s1)) && (length(t2) == length(s2))\n    ut1 = unique(t1);\n    ut2 = unique(t2);\n    us1 = unique(s1);\n    us2 = unique(s2);\n    if (length(ut1)*length(us1) == length(t1)) && ...\n            (length(ut2)*length(us2) == length(t2))\n        t1 = ut1; s1 = us1; t2 = ut2; s2 = us2;\n        isPointwise = false;\n        K = zeros(length(t1)*length(s1), length(t2)*length(s2));        \n    else        \n        isPointwise = true;\n        K = zeros(length(t1), length(t2));        \n    end\nelse\n    isPointwise = false;\n    K = zeros(length(t1)*length(s1), length(t2)*length(s2));\nend\n\n% Although this is done in heatKernExpandParam.m, we do it here again as a\n% precaution.\n\nheatKern.sim.inverseWidth = heatKern.inverseWidthTime;\nrbfhKern.rbf.inverseWidth = rbfhKern.inverseWidthTime;\n\n\nsigmax = sqrt(2/heatKern.inverseWidthSpace);\nlengthX = heatKern.lengthX;\nnterms = heatKern.nTerms;\ndecay = heatKern.decay;\ndiff = heatKern.diffusion;\n\n% Precompute some terms\nw = ((1:nterms)*(pi/lengthX))';\ngamma = sqrt(-1)*w;\nbeta = decay + diff*(w.^2);\ncK = 2/lengthX;\n\nif heatKern.includeIC\n   error('Not implemented yet')\nelse\n    if isPointwise\n        for i=1:nterms\n            heatKern.sim.decay = beta(i);\n            Kt = simXrbfKernCompute(heatKern.sim, rbfhKern.rbf, t1, t2);\n            Ks = srbfhKernCompute(sigmax, lengthX, s1, s2, w, gamma, i);\n            K = K + Kt.*Ks;\n        end\n    else\n        for i=1:nterms\n            heatKern.sim.decay = beta(i);\n            Kt = simXrbfKernCompute(heatKern.sim, rbfhKern.rbf, t1, t2);\n            Ks = srbfhKernCompute(sigmax, lengthX, s1, s2, w, gamma, i);\n            K = K + kron(Kt,Ks);\n        end\n    end\n    sK = cK*K;\n    K = heatKern.sensitivity*sK; \nend\n\n\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/heatXrbfhKernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5799953900425588}}
{"text": "function criterion = gbc_angle(q,CS,Dl,Dr,threshold,varargin)\n%\n\nd = angle(orientation(q(Dl),CS),orientation(q(Dr),CS));\n\nif length(threshold) == 1\n\n  criterion = d < threshold;\n\nelse\n  \n  criterion = 0.5 * ((d < threshold(1)) + (d < threshold(2)));\n  \nend\n\n% now check whether the have a misorientation heigher or lower than a\n% threshold\n%m = inv(q(Dl)).*q(Dr);\n\n%criterion = abs(dot(m,quaternion.id)) > cos(threshold/2);\n\n%if any(~criterion)\n%  qcs = quaternion(CS.properGroup);\n%  criterion(~criterion) = max(abs(dot_outer(m(~criterion),qcs)),[],2) > cos(threshold/2);\n%end \n\n% o_Dl = orientation(q(Dl),CS,symmetry);\n% o_Dr = orientation(q(Dr),CS,symmetry);\n% criterion = dot(o_Dl,o_Dr) > cos(threshold/2);\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/EBSDAnalysis/@EBSD/private/gbc_angle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314738181876, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5799953840773421}}
{"text": "EbN0=0:5:30;\nMSE=zeros(1,length(EbN0));\nfor i=1:length(EbN0)\n    SNR=EbN0(i);\n    sim('v_blast_t4_r4_8PSK_crrect_MSE');\n    MSE(i)=mse;\n    save MSE;\nend\nsemilogy(EbN0,MSE)\nxlabel('EbN0(dB)')\nylabel('MSE')\ngrid on\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/36805-vblast-matlab-code/pudn_site/VBLAST/simu_mse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5799953820658929}}
{"text": "function geometry_test022 ( )\n\n%*****************************************************************************80\n%\n%% TEST022 tests DIRECTION_UNIFORM_3D, GET_SEED.\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  seed = 123456789;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST022\\n' );\n  fprintf ( 1, '  DIRECTION_UNIFORM_3D picks a random direction vector.\\n' );\n  fprintf ( 1, '\\n' );\n\n  for i = 1 : 10\n    [ vran, seed ] = direction_uniform_3d ( seed );\n    fprintf ( 1, '  %10f  %10f  %10f\\n', vran(1:dim_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/geometry/geometry_test022.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.5799737356998266}}
{"text": "function [nu, g] = orderedNoiseUpdateParams(noise, mu, varsigma, y, index)\n\n% ORDEREDNOISEUPDATEPARAMS Update parameters for ordered categorical noise model.\n\n% NOISE\n\n% NOISE\n\n\n[g, dlnZ_dvs] = orderedNoiseGradVals(noise, mu(index, :), ...\n                                            varsigma(index, :), ...\n                                            y(index, :));\n\nnu = g.*g - 2*dlnZ_dvs;", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/noise/orderedNoiseUpdateParams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.579959368404103}}
{"text": "function plotCircle3D(center,normal,radius)\n\ntheta=0:0.01:2*pi;\nv=null(normal);\npoints=repmat(center',1,size(theta,2))+radius*(v(:,1)*cos(theta)+v(:,2)*sin(theta));\nplot3(points(1,:),points(2,:),points(3,:),'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/26588-plot-circle-in-3d/plotCircle3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5799593527590172}}
{"text": "%This directory contains functions for statistical analysis.\n%\n%STAT_NORMAL_CDF - evaluates the normal cumulative distribution function.\n%STAT_RMANOVA - repeated-measures ANOVA\n%STAT_CALCTCRIT - calculates the critical t-value given significance threshold and degrees of freedom\n%STAT_PERCENTILES - returns the percentiles for data samples.\n\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/statistics/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.6791786991753929, "lm_q1q2_score": 0.5799593451840416}}
{"text": "function [U,S,V] = spm_svd(X,U)\n% Computationally efficient SVD (that can handle sparse arguments)\n% FORMAT [U,S,V] = spm_svd(X,u)\n% X    - (m x n) matrix\n% u    - threshold (1 > u > 0) for normalized eigenvalues (default = 1e-6)\n%      - a value of zero induces u = 64*eps\n%\n% U    - {m x p} singular vectors\n% V    - {m x p} singular variates\n% S    - {p x p} singular values\n%__________________________________________________________________________\n% Copyright (C) 1994-2011 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_svd.m 6110 2014-07-21 09:36:13Z karl $\n\n\n% default thresholds - preclude singular vectors with small singular values\n%--------------------------------------------------------------------------\nif nargin < 2, U = 1e-6; end\nif U >= 1; U = U - 1e-6; end\nif U <= 0; U = 64*eps;   end\n\n% deal with sparse matrices\n%--------------------------------------------------------------------------\n[M,N] = size(X);\np     = find(any(X,2));\nq     = find(any(X,1));\nX     = X(p,q);\n\n% SVD\n%--------------------------------------------------------------------------\n[i, j, s] = find(X);\n[m, n]    = size(X);\nif any(i - j)\n    \n    % off-leading diagonal elements - full SVD\n    %----------------------------------------------------------------------\n    X     = full(X);\n    if m > n\n        \n        [v, S, v] = svd(X'*X,0);\n        S         = sparse(S);\n        s         = diag(S);\n        j         = find(s*length(s)/sum(s) > U);\n        v         = v(:,j);\n        u         = spm_en(X*v);\n        S         = sqrt(S(j,j));\n        \n    elseif m < n\n        \n        [u, S, u] = svd(X*X',0);\n        S         = sparse(S);\n        s         = diag(S);\n        j         = find(s*length(s)/sum(s) > U);\n        u         = u(:,j);\n        v         = spm_en(X'*u);\n        S         = sqrt(S(j,j));\n        \n    else\n        \n        [u, S, v] = svd(X,0);\n        S         = sparse(S);\n        s         = diag(S).^2;\n        j         = find(s*length(s)/sum(s) > U);\n        v         = v(:,j);\n        u         = u(:,j);\n        S         = S(j,j);\n    end\n    \nelse\n    S             = sparse(1:n,1:n,s,m,n);\n    u             = speye(m,n);\n    v             = speye(m,n);\n    [i, j]        = sort(-s);\n    S             = S(j,j);\n    v             = v(:,j);\n    u             = u(:,j);\n    s             = diag(S).^2;\n    j             = find(s*length(s)/sum(s) > U);\n    v             = v(:,j);\n    u             = u(:,j);\n    S             = S(j,j);\n    \nend\n\n% replace in full matrices\n%--------------------------------------------------------------------------\nj      = length(j);\nU      = sparse(M,j);\nV      = sparse(N,j);\nif j\n    U(p,:) = u;\n    V(q,:) = v;\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_svd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5799592063409891}}
{"text": "function w=pde(u)\n% PDE  W = PDE(U) is the residual for the convection-diffusion\n%      problem in Chapter 3\n%\n% \nglobal rhsf;\n%\n% C=20\n%\nv=20*u.*(dxmf(u)+dymf(u));\n%\n% uncomment this line for the unpreconditioned problem\n%\n%w=-lapmf(u)+20*u.*(dxmf(u)+dymf(u))-rhsf;\n%\n% uncomment this line for the preconditioned problem\n%\nw=u+fish2d(v)-rhsf;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/SNEwNM/Chapter3/pde.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695627, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5799592010858928}}
{"text": "function test3\n%TEST3 test cs_lsolve, cs_ltsolve, cs_usolve, cs_chol\n%\n% Example:\n%   test3\n% See also: testall\n\n%   Copyright 2006-2007, Timothy A. Davis.\n%   http://www.cise.ufl.edu/research/sparse\n\nindex = UFget ;\n[ignore f] = sort (max (index.nrows, index.ncols)) ;\nf = f (1:100) ;\n\nclf\n% f = f(1)\n\nfor i = f\n    Prob = UFget (i) ;\n    disp (Prob) ;\n    A = Prob.A ;\n    [m n] = size (A) ;\n    if (~isreal (A) | m ~= n)                                               %#ok\n        continue\n    end\n\n    A = A*A' + 2*n*speye (n) ;\n    try\n        p = amd (A) ;\n    catch\n        p = symamd (A) ;\n    end\n    try\n        L0 = chol (A)' ;\n    catch\n        continue\n    end\n    b = rand (n,1) ;\n\n    C = A(p,p) ;\n    c = condest (C) ;\n    fprintf ('condest: %g\\n', c) ;\n\n    x1 = L0\\b ;\n    x2 = cs_lsolve (L0,b) ;\n    err = norm (x1-x2,1) ;\n    if (err > 1e-12 * c)\n        error ('!') ;\n    end\n\n    x1 = L0'\\b ;\n    x2 = cs_ltsolve (L0,b) ;\n    err = norm (x1-x2,1) ;\n    if (err > 1e-10 * c)\n        error ('!') ;\n    end\n\n    U = L0' ;\n\n    x1 = U\\b ;\n    x2 = cs_usolve (U,b) ;\n    err = norm (x1-x2,1) ;\n    if (err > 1e-10 * c)\n        error ('!') ;\n    end\n\n    L2 = cs_chol (A) ;\n    subplot (2,3,1) ; spy (L0) ;\n    subplot (2,3,4) ; spy (L2) ;\n    err = norm (L0-L2,1) ;\n    if (err > 1e-8 * c)\n        error ('!') ;\n    end\n\n    L1 = chol (C)' ;\n    L2 = cs_chol (C) ;\n    subplot (2,3,2) ; spy (L1) ;\n    subplot (2,3,5) ; spy (L2) ;\n    err = norm (L1-L2,1) ;\n    if (err > 1e-8 * c)\n        error ('!') ;\n    end\n\n    [L3,p] = cs_chol (A) ;\n    C = A(p,p) ;\n    L4 = chol (C)' ;\n    subplot (2,3,3) ; spy (L4) ;\n    subplot (2,3,6) ; spy (L3) ;\n    err = norm (L4-L3,1) ;\n    if (err > 1e-8 * c)\n        error ('!') ;\n    end\n\n    drawnow\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/CSparse/MATLAB/Test/test3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.5799591948176316}}
{"text": "function b = power(a,n)\n% function B=power(A,N)\n%\n% DESCRIPTION\n%   Element-by-element powers\n%\n% INPUTS\n%   A: polynomial\n%   N: matrix of natural numbers\n%\n% OUTPUTS\n%   B: polynomial, result of element-by-element power A.^N.\n%\n% SYNTAX\n%   B = A.^N\n%     Element-by-element powers. A and B must have the same dimensions\n%     unless one is a scalar. A scalar can operate into anything.\n%   B=power(A,N)\n%     Function-call form of power.\n\n% 6/7/2002 PJS  Initial Coding\n% 12/12/2010 PJS Call matrix.^matrix code for scalar expansion cases\n\n% Check number of inputs\nerror(nargchk(2,2,nargin));\nsza=size(a);\nszn=size(n);\n\nif isempty(a) || isempty(n)\n    if isempty(a) && all(szn==[1 1])\n        % empty.^scalar = empty(sza)\n        b=polynomial(zeros(sza));\n        return;\n    elseif isempty(n) && all(sza==[1 1])\n        % scalar.^empty = empty(szn)\n        b=polynomial(zeros(szn));\n        return;\n    elseif all(sza==szn)\n        b=polynomial(zeros(sza));\n        return;\n    else\n        error('Matrix dimensions must agree.');\n    end\n    \nelseif sza==szn\n    % Matrix .^ Matrix\n    b = zeros(sza);\n    \n    % exponent = 0\n    idx = find( n==0 );\n    b(idx) = 1;\n    b = polynomial(b);\n    \n    % exponent = 1\n    idx = find( n==1 );\n    L.type = '()';\n    L.subs = {idx};\n    b = subsasgn(b,L,subsref(a,L));\n    \n    % exponent = 2;\n    idx = find( n>1 );\n    idx = idx(:)';\n    for i1=idx\n        L.subs = {i1};\n        ai = subsref(a,L);\n        Nt = size(ai.coefficient,1);\n        if Nt==1\n            bi = ai;\n            bi.coefficient = bi.coefficient^n(i1);\n            bi.degmat = bi.degmat*n(i1);\n        else\n            bi = mpower(ai,n(i1));\n        end\n        b = subsasgn(b,L,bi);\n    end\n    \n    %         % XXX This is pretty slow.\n    %         b = a;\n    %         L.type = '()';\n    %         for i1 = 1:sza(1);\n    %             for i2 = 1:sza(2);\n    %                 L.subs = {i1,i2};\n    %                 aij = subsref(a,L);\n    %                 bij = mpower(aij,n(i1,i2));\n    %                 b = subsasgn(b,L,bij);\n    %             end\n    %         end\n    %     end\nelseif all(szn==[1 1])\n    % Matrix.^Scalar:\n    n = repmat(n,sza);\n    b = power(a,n);\n    \n    %     b = polynomial(1);\n    %     for i1 = 1:n\n    %         b = b.*a;\n    %     end\nelseif all(sza==[1 1])\n    % Scalar .^ Matrix:\n    a = repmat(a,szn);\n    b = power(a,n);\n    \n    %     % XXX This is pretty slow.\n    %     b = polynomial(zeros(szn));\n    %     L.type = '()';\n    %     for i1 = 1:szn(1);\n    %         for i2 = 1:szn(2);\n    %             L.subs = {i1,i2};\n    %             bij = mpower(a,n(i1,i2));\n    %             b = subsasgn(b,L,bij);\n    %         end\n    %     end\nelse\n    error('Matrix dimensions must agree');\nend\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/multipoly/@polynomial/power.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.579959184814022}}
{"text": "% Test file for @deltafun/feval.m\n\nfunction pass = test_feval(pref)\n\nif ( nargin < 1 )\n    pref = chebfunpref();\nend\n\nseedRNG(1337)\n\n%%\nf = bndfun(@sin);\nd = deltafun(f, struct('deltaMag', 1, 'deltaLoc', 0));\npass(1) = isinf(feval(d, 0)) && feval(d, 0) > 0;\npass(2) = isinf(feval(-d, 0)) && feval(-d, 0) <0;\n\n%%\nf = fun.constructor(@(x) sin(x));\nd = deltafun(f, struct('deltaMag', [], 'deltaLoc', []));\nx = rand(1, 4);\npass(2) = norm(feval(f, x) - feval(d, x), inf) == 0;\n\n%%\nx = rand(1,4);\nd = deltafun(f, struct('deltaMag', rand(1, 4), 'deltaLoc', x));\npass(3) = all(isinf(feval(d, x)));\n\n%%\nx = chebfun('x');\nd = dirac(x-1);\npass(4) = isinf(feval(d, 1));\nval = feval(-d, 1);\npass(5) = isinf(val) && val < 0;\npass(6) = isinf(feval(d, 'right'));\npass(7) = feval(d, 'left') == 0;\npass(8) = feval(d, 1, 'left' ) == 0;\npass(9) = feval(d, 0, 'left' ) == 0;\npass(10) = feval(d, 0, 'right' ) == 0;\nd = diff(heaviside(x));\npass(11) = isinf(feval(d, 0));\npass(12) = feval(d, 'right') == 0;\npass(13) = feval(d, 'left') == 0;\npass(14) = feval(d, 0, 'left' ) == 0;\npass(15) = feval(d, 0, 'right' ) == 0;\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/deltafun/test_feval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5799591843074393}}
{"text": "% Copyright 2017 Google Inc.\n%\n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n%\n%     https://www.apache.org/licenses/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n\n% Demonstration of the image restoration experiments conducted in\n% Y. Romano, M. Elad, and P. Milanfar, \"The Little Engine that Could: \n% Regularization by Denoising (RED)\", submitted to SIAM Journal on Imaging\n% Sciences, 2016. https://arxiv.org/abs/1611.02862\n%\n% This example reads a ground-truth image, degrades the image by \n% first blurring or downscaling it, followed by an addition of random white\n% Gaussian noise. Then it calls to RED in order to restore the image. \n% This example compares the input and output PSNR, shows and saves the \n% results. The suggested image-adaptive Laplacian-regularization functional \n% is minimized using the Fixed-Point, ADMM, and Steepest Descent methods. \n% Please refer to the paper for more details.\n%\n% The following are the degradation models that this example handles:\n% 'UniformBlur'  - 9X9 uniform psf with noise-level equal to sqrt(2)\n% 'GaussianBlur' - 25X25 Gaussian psf with std 1.6 and noise-level\n%                  equal to sqrt(2)\n% 'Downscale'    - 7X7 Gaussian psf with std 1.6 and noise-level equal to 5\n%\n% The denoising engine is TNRD: Yunjin Chen, and Thomas Pock, \"Trainable \n% Nonlinear Reaction Diffusion: A Flexible Framework for Fast and Effective\n% Image Restoration\", IEEE TPAMI 2016. The code is available in\n% http://www.icg.tugraz.at/Members/Chenyunjin/about-yunjin-chen\n% Note: Enable parallel pool to reduce runtime.\n%\n% The degradation process is similar to the one suggested in NCSR paper:\n% Weisheng Dong, Lei Zhang, Guangming Shi, and Xin Li \"Nonlocally \n% Centralized Sparse Representation for Image Restoration\", IEEE-TIP, 2013.\n% The code is available in http://www4.comp.polyu.edu.hk/~cslzhang/NCSR.htm\n%\n\nclc;\nclear;\nclose all;\n\n% configure the path\n% denoising functions\naddpath(genpath('./tnrd_denoising/'));\n% SD, FP, and ADMM methods\naddpath(genpath('./minimizers/'));\n% contains the default params\naddpath(genpath('./parameters/'));\n% contains basic functions\naddpath(genpath('./helper_functions/'));\n% test images for the debluring and super resolution problems, \n% taken from NCSR software package\naddpath(genpath('./test_images/'));\n\n% set light_mode = true to run the code in a sub optimal but faster mode\n% set light_mode = false to obtain the results reported in the RED paper\nlight_mode = false;\n\nif light_mode\n    fprintf('Running in light mode. ');\n    fprintf('Turn off to obatain the results reported in RED paper.\\n');\nelse\n    fprintf('Light mode option is off. ');\n    fprintf('Reproducing the result in RED paper.\\n');\nend\n\n%% read the original image\n\nfile_name = 'starfish.tif';\n\nfprintf('Reading %s image...', file_name);\norig_im = imread(['./test_images/' file_name]);\norig_im = double(orig_im);\n\nfprintf(' Done.\\n');\n\n\n%% define the degradation model\n\n% choose the secenrio: 'UniformBlur', 'GaussianBlur', or 'Downscale'\ndegradation_model = 'UniformBlur';\n\nfprintf('Test case: %s degradation model.\\n', degradation_model);\n\nswitch degradation_model\n    case 'UniformBlur'\n        % noise level\n        input_sigma = sqrt(2);\n        % filter size\n        psf_sz = 9;\n        % create uniform filter\n        psf = fspecial('average', psf_sz);\n        % use fft to solve a system of linear equations in closed form\n        use_fft = true;\n        % create a function-handle to blur the image\n        ForwardFunc = ...\n            @(in_im) imfilter(in_im,psf,'conv','same','circular');\n        % the psf is symmetric, i.e., the ForwardFunc and BackwardFunc\n        % are the same\n        BackwardFunc = ForwardFunc;\n        % special initialization (e.g. the output of other method)\n        % set to identity mapping\n        InitEstFunc = @(in_im) in_im;\n        \n    case 'GaussianBlur'\n        % noise level\n        input_sigma = sqrt(2);\n        % filter size\n        psf_sz = 25;\n        % std of the Gaussian filter\n        gaussian_std = 1.6;\n        % create gaussian filter\n        psf = fspecial('gaussian', psf_sz, gaussian_std);\n        % use fft to solve a system of linear equations in closed form\n        use_fft = true;\n        % create a function handle to blur the image\n        ForwardFunc = ...\n            @(in_im) imfilter(in_im,psf,'conv','same','circular');\n        % the psf is symmetric, i.e., the ForwardFunc and BackwardFunc\n        % are the same\n        BackwardFunc = ForwardFunc;\n        % special initialization (e.g. the output of other method)\n        % set to identity mapping\n        InitEstFunc = @(in_im) in_im;\n        \n    case 'Downscale'\n        % noise level\n        input_sigma = 5;\n        % filter size\n        psf_sz = 7;\n        % std of the Gaussian filter\n        gaussian_std = 1.6;\n        % create gaussian filter\n        psf = fspecial('gaussian', psf_sz, gaussian_std);\n        % scaling factor\n        scale = 3;\n        \n        % compute the size of the low-res image\n        lr_im_sz = [ceil(size(orig_im,1)/scale),...\n                    ceil(size(orig_im,2)/scale)];        \n        % create the degradation operator\n        H = CreateBlurAndDecimationOperator(scale,lr_im_sz,psf);\n        % downscale\n        ForwardFunc = @(in_im) reshape(H*in_im(:),lr_im_sz);        \n        % upscale\n        BackwardFunc = @(in_im) reshape(H'*in_im(:),scale*lr_im_sz);\n        % special initialization (e.g. the output of other method)\n        % use bicubic upscaler\n        InitEstFunc = @(in_im) imresize(in_im,scale,'bicubic');\n        \n    otherwise\n        error('Degradation model is not defined');\nend\n\n\n%% degrade the original image\n\nswitch degradation_model\n    case {'UniformBlur', 'GaussianBlur'}\n        fprintf('Blurring...');\n        % blur each channel using the ForwardFunc\n        input_im = zeros( size(orig_im) );\n        for ch_id = 1:size(orig_im,3)\n            input_im(:,:,ch_id) = ForwardFunc(orig_im(:,:,ch_id));\n        end\n        % use 'seed' = 0 to be consistent with the experiments in NCSR\n        randn('seed', 0);\n\n    case 'Downscale'\n        fprintf('Downscaling...');\n        % blur the image, similar to the degradation process of NCSR\n        input_im = Blur(orig_im, psf);\n        % decimate\n        input_im = input_im(1:scale:end,1:scale:end,:);\n        % use 'state' = 0 to be consistent with the experiments in NCSR\n        randn('state', 0);\n\n    otherwise\n        error('Degradation model is not defined');\nend\n\n% add noise\nfprintf(' Adding noise...');\ninput_im = input_im + input_sigma*randn(size(input_im));\n\n% convert to YCbCr color space if needed\ninput_luma_im = PrepareImage(input_im);\norig_luma_im = PrepareImage(orig_im);\n\nif strcmp(degradation_model,'Downscale')\n    % upscale using bicubic\n    input_im = imresize(input_im,scale,'bicubic');\n    input_im = input_im(1:size(orig_im,1), 1:size(orig_im,2), :); \nend\nfprintf(' Done.\\n');\npsnr_input = ComputePSNR(orig_im, input_im);\n\n\n%% minimize the Laplacian regularization functional via Fixed Point\n\nfprintf('Restoring using RED: Fixed-Point method\\n');\n\nswitch degradation_model\n    case 'UniformBlur'\n        params_fp = GetUniformDeblurFPParams(light_mode, psf, use_fft);\n    case 'GaussianBlur'\n        params_fp = GetGaussianDeblurFPParams(light_mode, psf, use_fft);\n    case 'Downscale'\n        assert(exist('use_fft','var') == 0);\n        params_fp = GetSuperResFPParams(light_mode);\n    otherwise\n        error('Degradation model is not defined');\nend\n\n[est_fp_im, psnr_fp] = RunFP(input_luma_im,...\n                             ForwardFunc,...\n                             BackwardFunc,...\n                             InitEstFunc,...\n                             input_sigma,...\n                             params_fp,...\n                             orig_luma_im);\nout_fp_im = MergeChannels(input_im,est_fp_im);\n\nfprintf('Done.\\n');\n\n\n%% minimize the Laplacian regularization functional via ADMM\n\nfprintf('Restoring using RED: ADMM method\\n');\n\nswitch degradation_model\n    case 'UniformBlur'\n        params_admm = GetUniformDeblurADMMParams(light_mode, psf, use_fft);\n    case 'GaussianBlur'\n        params_admm = GetGaussianDeblurADMMParams(light_mode, psf, use_fft);\n    case 'Downscale'\n        assert(exist('use_fft','var') == 0);\n        params_admm = GetSuperResADMMParams(light_mode);        \n    otherwise\n        error('Degradation model is not defined');\nend\n\n[est_admm_im, psnr_admm] = RunADMM(input_luma_im,...\n                                   ForwardFunc,...\n                                   BackwardFunc,...\n                                   InitEstFunc,...\n                                   input_sigma,...\n                                   params_admm,...\n                                   orig_luma_im);\nout_admm_im = MergeChannels(input_im,est_admm_im);\n\nfprintf('Done.\\n');\n\n\n%% minimize the laplacian regularization functional via Steepest Descent\n\nfprintf('Restoring using RED: Steepest-Descent method\\n');\n\nswitch degradation_model\n    case 'UniformBlur'\n        params_sd = GetUniformDeblurSDParams(light_mode);\n    case 'GaussianBlur'\n        params_sd = GetGaussianDeblurSDParams(light_mode);\n    case 'Downscale'\n        params_sd = GetSuperResSDParams(light_mode);\n    otherwise\n        error('Degradation model is not defined');\nend\n\n[est_sd_im, psnr_sd] = RunSD(input_luma_im,...\n                             ForwardFunc,...\n                             BackwardFunc,...\n                             InitEstFunc,...\n                             input_sigma,...\n                             params_sd,...\n                             orig_luma_im);\n% convert back to rgb if needed\nout_sd_im = MergeChannels(input_im,est_sd_im);\n\nfprintf('Done.\\n');\n\n\n%% display final results\n\nfprintf('Image name %s \\n', file_name);\nfprintf('Input PSNR = %f \\n', psnr_input);\nfprintf('RED: Fixed-Point PSNR = %f \\n', psnr_fp);\nfprintf('RED: ADMM PSNR = %f \\n', psnr_admm);\nfprintf('RED: Steepest-Decent PSNR = %f \\n', psnr_sd);\n\n\n%% write images\n\nif ~exist('./results/','dir')\n    mkdir('./results/');\nend\n\nfprintf('Writing the images to ./results...');\n\nimwrite(uint8(input_im),['./results/input_' file_name]);\nimwrite(uint8(out_fp_im),['./results/est_fp_' file_name]);\nimwrite(uint8(out_admm_im),['./results/est_admm_' file_name]);\nimwrite(uint8(out_sd_im),['./results/est_sd_' file_name]);\n\nfprintf(' Done.\\n');\n\n", "meta": {"author": "google", "repo": "RED", "sha": "31142ab55ad37c25f6704f5bfe81e7fec39360f0", "save_path": "github-repos/MATLAB/google-RED", "path": "github-repos/MATLAB/google-RED/RED-31142ab55ad37c25f6704f5bfe81e7fec39360f0/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5799591780391771}}
{"text": "function mfunc = minmodB(v,M,h)\n\n% function mfunc = minmodB(v,M,h)\n% Purpose: Implement the TVB modified midmod function. v is a vector\n\nmfunc = v(1,:);\nids = find(abs(mfunc) > M*h.^2);\n\nif(size(ids,2)>0)\n  mfunc(ids) = minmod(v(:,ids));\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/minmodB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5799591732906643}}
{"text": "y       = load('data/gas.dat')';\ntime    = 1960:1/4:1986+3/4;\nfprintf(1, '\\n');\n\n%% Analysis based on Gaussian model %%\nstsm        = ssm_stsm('trend', 'dummy', 4);\n[stsm logL] = estimate(y, stsm, 0.01, [], 'fmin', 'bfgs', 'disp', 'off');\nfprintf(1, '[Gaussian STSM]\\n');\nfprintf(1, 'loglikelihood:      %g\\n', logL);\nfprintf(1, 'Irregular variance: %g\\n', stsm.param(1));\nfprintf(1, 'Trend variance:     %g\\n', stsm.param(2));\nfprintf(1, 'Level variance:     %g\\n', stsm.param(3));\nfprintf(1, 'Seasonal variance:  %g\\n\\n', stsm.param(4));\n\n[alpha irr] = fastsmo(y, stsm);\nycom        = signal(alpha, stsm);\nseas        = ycom(2, :);\nfigure('Name', 'Gaussian model analysis');\nsubplot(2, 1, 1), plot(time, seas), title('Seasonal'), xlim([1959 1988]), ylim([-0.9 0.8]);\nsubplot(2, 1, 2), plot(time, irr), title('Gaussian Irregular'), xlim([1959 1988]), ylim([-0.4 0.4]);\nif ispc, set(gcf, 'WindowStyle', 'docked'); end\ndrawnow;\n\n%% Analysis based on t-model %%\nstsmt           = [ssm_t ssm_llt ssm_seasonal('dummy', 4)];\nrandn('state', [3765023265; 2369472656]);\n[stsmt logLt]   = estimate(y, stsmt, [stsm.param(1) 4 stsm.param(2:end)], alpha, 'fmin', 'bfgs', 'disp', 'off');\n[alphat irrt]   = fastsmo(y, stsmt);\nycomt           = signal(alphat, stsmt);\nlvlt            = ycomt(1, :);\nseast           = ycomt(2, :);\n\nfprintf(1, '[t-dist error STSM]\\n');\nfprintf(1, 'loglikelihood:      %g\\n', logLt);\nfprintf(1, 't-dist variance:    %g\\n', stsmt.param(1));\nfprintf(1, 't-dist df:          %g\\n', stsmt.param(2));\nfprintf(1, 'Trend variance:     %g\\n', stsmt.param(3));\nfprintf(1, 'Level variance:     %g\\n', stsmt.param(4));\nfprintf(1, 'Seasonal variance:  %g\\n', stsmt.param(5));\n\nfigure('Name', 'Component comparison between Gaussian and t-dist. models');\nsubplot(2, 1, 1), plot(time, seas, 'r', 'DisplayName', 'Gaussian'), hold all, plot(time, seast, 'b', 'DisplayName', 't-distribution'), hold off, title('Seasonal component'), xlim([1959 1988]), ylim([-0.9 0.8]);\nsubplot(2, 1, 2), plot(time, irr, 'r', 'DisplayName', 'Gaussian'), hold all, plot(time, irrt, 'b', 'DisplayName', 't-distribution'), hold off, title('Irregular component'), xlim([1959 1988]), ylim([-0.4 0.4]);\nif ispc, set(gcf, 'WindowStyle', 'docked'); end\n\nfprintf(1, '\\n');\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/external/ssm-1.0.1/ssm-release/demos/demo_gas.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664173, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5799430967463853}}
{"text": "% Simulating 2*2 MIMO-LDPC Base-Band Systems\n% Copyright (C2010-2015) Yang XIAO, Beijing Jiaotong University, Aug.10, 2010, E-Mail: yxiao@bjtu.edu.cn. \n% This program can simulate 2*2 MIMO-LDPC base-band systems.\n% The MIMO system's design can refer my following book.\n% [1] Yang Xiao, MIMO Multiple Antenna Wireless Communication Systems, Press of Posts and Telecommunications, Beijing, 2009.\n% Different from the MIMO scheme of IEEE 802.16e, our MIMO-LDPC system has no space-time coding, \n% while it achieved good BER performance.    \n%---------------------------\nclear;\np=87;   %p is the prime number of rank of sub-matrices of parity check matrix;\nk2=3;   % k is the row weight of parity check matrix;\nj2=6;   % j is the column weight of parity check matrix;\nM=k2*p; % M is the number of row of parity check matrix;\nN=j2*p;  % N is the number of column of parity check matrix;            \n\n\nNT1=1;\nE0=eye(p);\nEZ=zeros(p);\na=3; b=5;\nR=0.5; % coding rate\nframe_num =200;       \nNpf=2*N*frame_num\ndlta=1/Npf;\n\nEZ=zeros(p);\nE0=eye(p);\n% The design of parity check matrix of QC LDPC without girth_4, see my book. \nE11=E0;                   E12=circshift(E0,a*NT1);   E13= circshift(E0,a^2*NT1);   E14= circshift(E0,a^3*NT1);   E15= circshift(E0,a^4*NT1);    E16= circshift(E0,a^5*NT1);\nE21=EZ;                   E22=E0;                    E23=circshift(E0,a^2*b*NT1);  E24=circshift(E0,a^3*b*NT1);  E25= circshift(E0,a^4*b*NT1);  E26= circshift(E0,a^5*b*NT1);\nE31=circshift(E0,b^2*NT1);E32=EZ;                    E33=E0;                       E34=circshift(E0,b^2*a^3*NT1);E35= circshift(E0,b^2*a^4*NT1);E36= circshift(E0,b^2*a^5*NT1);\n\nh1=[E11 E12 E13 E14 E15 E16;\n    E21 E22 E23 E24 E25 E26;\n    E31 E32 E33 E34 E35 E36]; \n A(:,1:M)=h1(:,1:M);\n B(:,1:M)=h1(:,M+1:N);\n% \n \n \nd=mod(inv_GF2(A)*B,2); \nE00=eye(M);\n% The generator matrix of QC LDPC, see my book. \nG=[d' E00];\nH=sparse(h1);\n\nN1=0;\nN2=16;\n% Flat fading MIMO Channel\nh11=0.9;\nh12=0.3;\nh21=0.4;\nh22=0.73;\n\nSNRindB1=N1:1:N2;\nfor i=1:length(SNRindB1)\nerror_count1= 0;\nerror_count2= 0;\n    for f_n = 1:frame_num \n    SNR=(10^(SNRindB1(i)/10)); \n  \tsigma = 1/sqrt(2*R*SNR); \n    x1 = (sign(randn(1,size(G,1)))+1)/2; % random information bits  \n    x2 = (sign(randn(1,size(G,1)))+1)/2; % random information bits  \n y1 = mod(x1*G,2);                   % LDPC Encoding for signal_1 from atenna 1 of the transmitter\n y2 = mod(x2*G,2);                   % LDPC Encoding for signal_2 from atenna 2 of the transmitter\n    z1=2*y1-1;                       % BPSK modulation\n    z2=2*y2-1;                         % BPSK modulation\n    z11=h11*z1+h12*z2+sigma*randn(1,size(G,2));    % AWGN transmission\n    z22=h21*z1+h22*z2+sigma*randn(1,size(G,2));\nHC=[h11 h12;h21 h22];   % Channel Matrix\nHC1=HC^(-1);\nu=HC1*[z11;z22];        % ZF spatial decoding\nu1=u(1,:);              % recieved signal_1 from atenna 1 of the receiver \nu2=u(2,:);              % recieved signal_2 from atenna 1 of the receiver \n    f11=1./(1+exp(-2*u1/sigma^2));        % likelihoods\n    f01=1-f11;\n    [z1_hat, success, k] = ldpc_decode(f01,f11,H);   %  LDPC decoding for signal_1\n    x1_hat = z1_hat(size(G,2)+1-size(G,1):size(G,2));\n    x1_hat1 = x1_hat';\n    f12=1./(1+exp(-2*u2/sigma^2));        % likelihoods\n    f02=1-f12;\n    [z2_hat, success, k] = ldpc_decode(f02,f12,H);   %  LDPC decoding for signal_2\n    x2_hat = z2_hat(size(G,2)+1-size(G,1):size(G,2));\n    x2_hat1 = x2_hat';\n    error_count2= sum(xor(x1,x1_hat1))+sum(xor(x2,x2_hat1));    % bit error count\n    error_count1 = error_count1 + error_count2; \n    end    \n    BER(i)= error_count1/Npf \n    if BER(i)<.1*dlta\n    BER(i)=.08*dlta;\n    end\nend\nfigure(1)\nsemilogy(SNRindB1,BER);\nxlabel('SNR(dB)');\nylabel('BER');\ntitle('2*2 MIMO-LDPC Simulation');\naxis([N1 N2 dlta 1]);\n%diary 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/28437-simulating-22-mimo-ldpc-base-band-systems/MIMO-LDPC_Simulation/MIMO_LDPC_yxiao1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.5799321946564211}}
{"text": "function x = chi2inv(p,nu)\n% Inverse-chi-squared distribution\n% x = Gamma(nu/2,1/(2*p)) / Gammma(nu/2)\n\nx = gammainc(1/(2*p),nu/2) / gamma(nu/2);\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/tools/math_tools/chi2inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.579897469143297}}
{"text": "function [x,fval,gp] = gplite_fmin(gp,x0,maxflag)\n%GPLITE_FMIN Find global minimum (or maximum) of GP.\n\nif nargin < 2; x0 = 0; end\nif nargin < 3 || isempty(maxflag); maxflag = 0; end\n\nMaxBnd = 10;\nhpd_frac = 0.5;\nD = size(gp.X,2);\nN0 = size(x0,1);\nNstarts = max(3,N0);\n\ndiam = max(gp.X) - min(gp.X);\nLB = min(gp.X) - MaxBnd*diam;\nUB = max(gp.X) + MaxBnd*diam;\n\n% First, train GP\nif ~isfield(gp,'post') || isempty(gp.post)\n    % How many samples for the GP?\n    if isfield(gp,'Ns') && ~isempty(gp.Ns); Ns_gp = gp.Ns; else; Ns_gp = 0; end\n    options.Nopts = 1;  % Do only one optimization    \n    gp = gplite_train(...\n        [],Ns_gp,gp.X,gp.y,gp.covfun,gp.meanfun,gp.noisefun,[],[],options);\nend\n\n% Start from the min (or max) of the training data\nif maxflag\n    [~,ord] = sort(gp.y,'descend');    \nelse\n    [~,ord] = sort(gp.y,'ascend');\nend\n\n% Take best for sure\nX = gp.X(ord,:);\nx0 = [x0; X(1,:)];\nX(1,:) = [];\n\nif Nstarts > N0+1\n    Nx = size(X,1);\n    N_hpd = ceil(Nx*hpd_frac);\n    idx = randperm(N_hpd,min(Nstarts-N0,N_hpd));\n    x0 = [x0; X(idx,:)];\nend\n\nN0 = size(x0,1);\nx = zeros(N0,D);\nf = zeros(N0,1);\nopts = optimoptions('fmincon','GradObj','off','Display','off');\nfor i = 1:N0\n    [x(i,:),f(i)] = fmincon(@(x) optfun(x,gp,maxflag),x0(i,:),[],[],[],[],LB,UB,[],opts);\nend\n\n[fval,idx] = min(f);\nx = x(idx,:);\n\nif maxflag; fval = -fval; end\n\nend\n\nfunction [f,df] = optfun(x,gp,maxflag)\n\nif nargout > 1\n    [f,df] = gplite_pred(gp,x);\nelse\n    f = gplite_pred(gp,x);\nend\n\nif maxflag  % Want to find maximum, swap sign\n    f = -f;\n    if nargout > 1; df = -df; end\nend\n\nend", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/gplite/gplite_fmin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5798360658891742}}
{"text": "function [A, B] = gsp_filterbank_bounds(G,W,param)\n%GSP_FILTERBANK_BOUNDS Compute approximated frame bounds for a filterbank\n%   Usage: [A, B] = gsp_filterbank_bounds(G,W);\n%          [A, B] = gsp_filterbank_bounds(G,W,param);\n%          [A, B] = gsp_filterbank_bounds([xmin, xmax],W);\n%          [A, B] = gsp_filterbank_bounds([xmin, xmax],W,param);\n%\n%   Input parameters\n%       G   : Graph structure or interval to compute the bound\n%       W   : Filterbank (cell array of inline function)\n%       param: optional parameter\n%   Output parameters\n%       A   : Filterbank lower bound\n%       B   : Filterbank Upper bound\n%\n%   *param* is a Matlab structure containing the following fields:\n%\n%   * *param.N* : Number of points for the line search default (default 999)\n%   * *param.use_eigenvalues* : Use eigenvalues if possible (default 1). To\n%     be used, the eigenvalues have to be computed first using\n%     |gsp_compute_fourier_basis|.\n%\n\n% Author: Nathanael Perraudin\n% Date : 26 March 2014\n\nif nargin < 3\n    param = struct;\nend\n\nif ~isfield(param,'N'), param.N = 999; end\nif ~isfield(param,'use_eigenvalues'),  param.use_eigenvalues = 1; end\n\nif iscell(G)\n    NG = numel(G);\n    A = cell(NG,1);\n    B = cell(NG,1);\n    for ii = 1:NG\n        [A{ii}, B{ii}] = gsp_filterbank_bounds(G{ii},W{ii},param);\n    end\n    return\nend\n\nif isstruct(G)\n    if ~isfield(G,'lmax')\n        G = gsp_estimate_lmax(G);\n    warning(['GSP_FILTERBANK_BOUNDS: To be more efficient you should run: ',...\n        'G = gsp_estimate_lmax(G); before using this proximal operator.']);\n    end\n    xmax = G.lmax;\n    xmin = 0;\nelse\n    xmin = G(1);\n    xmax = G(2);\nend\n    \n\nif param.use_eigenvalues && isstruct(G) && isfield(G,'e')\n    lambda = G.e;\nelse\n    lambda = linspace(xmin,xmax , param.N);\nend\n\n \nNf = numel(W);\n\n\nsum_filters = sum(abs(gsp_filter_evaluate(W,lambda).^2),2);\n% for ii=1:Nf\n%     sum_filters = sum_filters + (W{ii}(lambda)).^2;\n% end\n\nA = min(sum_filters);\nB = max(sum_filters);\n  \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/filters/gsp_filterbank_bounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5798360593391507}}
{"text": "function k = linardKernDiagCompute(kern, x)\n\n\n% LINARDKERNDIAGCOMPUTE Compute diagonal of LINARD kernel.\n% FORMAT\n% DESC computes the diagonal of the kernel matrix for the automatic relevance determination linear kernel given a design matrix of inputs.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x : input data matrix in the form of a design matrix.\n% RETURN k : a vector containing the diagonal of the kernel matrix\n% computed at the given points.\n%\n% SEEALSO : linardKernParamInit, kernDiagCompute, kernCreate, linardKernCompute\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006\n\n% KERN\n\n\nscales = sparse(diag(sqrt(kern.inputScales)));\nx = x*scales;\n\nk = sum(x.*x, 2)*kern.variance;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/linardKernDiagCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5798360478715223}}
{"text": "%INTLAB interval hessian toolbox\n%\n%Hessian constructors\n%  hessianinit  - Initialization of dependent variables\n%  horzcat      - Horizontal concatenation          [ , ]\n%  vertcat      - Vertical concatenation            [ ; ]\n%  subsasgn     - Subscripted assignment A(i,:) = 1\n%  subsref      - Subscripted reference r = A(3,4)\n%  hessian      - Double to gradient\n%\n%Display of hessians and interval hessians (rigorous)\n%  display      - Command window display of hessian\n%  disp         - Display function for pop-up windows in debugger\n%  realimag     - Real and Imaginary part separately\n%  infsup       - Display infimum and supremum\n%  midrad       - Display midpoint and radius\n%  disp_        - Display in \"_\" notation\n%\n%Hessian arithmetic operations\n%  plus         - Plus                              +\n%  uplus        - Unary plus                        +\n%  minus        - Minus                             -\n%  uminus       - Unary minus                       -\n%  mtimes       - Matrix multiply                   *\n%  times        - Elementwise multiply              .*\n%  mrdivide     - Slash or right division           /\n%  mldivide     - Backslash or left division        \\\n%  rdivide      - Elementwise right division        ./\n%  ldivide      - Elementwise left division         .\\\n%  mpower       - Matrix power                      ^\n%  power        - Elementwise power                 .^\n%  intersect    - Intersection\n%\n%Other hessian operations\n%  abs          - Absolute value\n%  inf          - Infimum\n%  sup          - Supremum\n%  mid          - Midpoint\n%  rad          - Radius\n%  diam         - Diameter\n%  real         - Real part\n%  imag         - Imaginary part\n%  trace        - Trace\n%  sum          - Sum\n%  prod         - Product\n%  ctranspose   - Complex conjugate transpose       '\n%  transpose    - Transpose                         .'\n%\n%Utility routines\n%  isnan        - True for Not a Number\n%  isreal       - Hessian is real\n%  isintval     - Hessian is intval\n%  isfinite     - Interval is finite\n%  isinf        - Interval is infinite\n%  isempty      - Hessian is empty in Matlab sense, i.e. []\n%  emptyintersect - detect empty intersections\n%  issparse     - Hessian has sparse structure\n%  find         - find indices of nonzero elements\n%  all          - Determine if all array elements are nonzero\n%  any          - Determine if any array elements are nonzero\n%  logical      - Convert hessian values to logical\n%  nnz          - number of nonzero elements\n%  end          - determine last index\n%\n%Structural operations\n%  full         - Convert to full hessian\n%  sparse       - Convert to sparse hessian\n%  band         - Extract band\n%  diag         - Extract diagonal\n%  tril         - Extract lower triangular\n%  triu         - Extract upper triangular\n%  bandwidth    - Bandwidth\n%  length       - Length\n%  size         - Size\n%  dim          - Dimension of square matrix\n%  reshape      - Reshape\n%  repmat       - Duplicate arrays\n%\n%Hessian trigonometric functions (rigorous, real and complex)\n%  sin          - Sine\n%  cos          - Cosine\n%  tan          - Tangent\n%  cot          - Cotangent\n%  sec          - Secant\n%  csc          - Cosecant\n%  asin         - Inverse sine\n%  acos         - Inverse cosine\n%  atan         - Inverse tangent\n%  acot         - Inverse cotangent\n%  asec         - Inverse secant\n%  acsc         - Inverse cosecant\n%  sinh         - Hyperbolic sine\n%  cosh         - Hyperbolic cosine\n%  tanh         - Hyperbolic tangent\n%  coth         - Hyperbolic cotangent\n%  asinh        - Inverse hyperbolic sine\n%  acosh        - Inverse hyperbolic cosine\n%  atanh        - Inverse hyperbolic tangent\n%  acoth        - Inverse hyperbolic cotangent\n%\n%Hessian exponential functions (rigorous, real and complex)\n%  exp          - Exponential\n%  log          - Natural logarithm\n%  log10        - Logarithm to base 10\n%  sqr          - Square\n%  sqrt         - Square root\n%\n%Hessian comparison of \".x\" part\n%  eq           - Equal                             ==\n%  ne           - Not equal                         ~=\n%  gt           - Greater than                      >\n%  ge           - Greater than or equal             >=\n%  lt           - Less than                         <\n%  le           - Less than or equal                <=\n%\n%Verification routines and auxiliary\n%  typeadj      - Type adjustment\n%  typeof       - Type for type adjustment\n%\n%Initialization of INTLAB hessian package and system variables\n%  hessianinit  - Initialization and definition of INTLAB switches, also\n%                   initialization of dependent variables\n%\n%Demonstration, samples\n%  demohessian - Some examples for using INTLAB hessian package\n%\n%\n%The hessian package uses forward mode of automatic differentiation. For\n%an introduction to forward differentation, see\n%  L.B. Rall: Automatic Differentiation: Techniques and Applications,\n%    Lecture Notes in Computer Science 120, Springer, 1981.\n%\n\n% written  04/04/04     S.M. Rump  INTLAB Version 5\n%\n% Copyright (c) Siegfried M. Rump, head of the Institute for Reliable Computing, \n%               Hamburg University of Technology\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/hessian/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5798069211729426}}
{"text": "function costs = surfprofile(problem, x, d1, d2, t1, t2)\n% Plot the cost function as a surface over a 2-dimensional subspace.\n%\n% function surfprofile(problem, x, d1, d2, t1, t2)\n% function costs = surfprofile(problem, x, d1, d2, t1, t2)\n%\n% Evaluates the cost function at points\n%\n%   gamma(t1, t2) = exponential_x(t1*d1 + t2*d2)\n% \n% where the exponential map at x is specified by problem.M.exp (retr is\n% used instead if needed). d1 and d2 are two tangent vectors to problem.M\n% at the point x. The values assigned to t1 and t2 are as specified in the\n% two input vectors t1 and t2.\n% \n% If the function is called with an output, the plot is not drawn and the\n% values of the cost are returned in a matrix of size\n% length(t1)*length(t2). To plot a surf, call surf(t1, t2, costs.') (notice\n% the transpose).\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Sep. 1, 2014.\n% Contributors: \n% Change log: \n%\n%   April 3, 2015 (NB):\n%       Works with the new StoreDB class system.\n\n    % Verify that the problem description is sufficient.\n    if ~canGetCost(problem)\n        error('It seems no cost was provided.');  \n    end\n    \n    if isfield(problem.M, 'exp')\n        expo = problem.M.exp;\n        str = 'Exp';\n    else\n        expo = problem.M.retr;\n        str = 'Retr';\n    end\n    \n    storedb = StoreDB();\n    linesearch_fun = @(ta, tb) getCost(problem, ...\n                         expo(x, problem.M.lincomb(x, ta, d1, tb, d2)), ...\n                         storedb);\n    \n    costs = zeros(length(t1), length(t2));\n    for i = 1 : length(t1)\n        for j = 1 : length(t2)\n            costs(i, j) = linesearch_fun(t1(i), t2(j));\n        end\n    end\n    \n    if nargout == 0\n        surf(t1, t2, costs.');\n        xlabel('t1');\n        ylabel('t2');\n        zlabel(['f(' str '_x(t1*d1+t2*d2))']);\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/manopt/tools/surfprofile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.579806918670051}}
{"text": "% Fig. 5.8   Feedback Control of Dynamic Systems, 5e \n%             Franklin, Powell, Emami\n\nn6=1;\nd6=[1 8 32 0];\npzmap(n6,d6)\ntitle('Fig.5.8 The locus crosses the j\\omega axis at *')\naxis([-10 6 -6 6] )\nhold on\nr=roots([1 0 32]);\n plot(r,'*')\nz=0:.1:.9;\n wn= 1:6;\n sgrid(z, wn)\n hold 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/fig5_08.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.579806906872763}}
{"text": "function sp=mtimes(sp1,sp2)\n% sympoly/mtimes: Matrix multiplication of sympoly objects or scalars\n% usage: sp=sp1*sp2;\n% \n% arguments:\n%  sp,sp1,sp2   - sympoly objects or numeric scalars or a numeric array\n\n% are they of compatible sizes?\ns1 = size(sp1);\ns2 = size(sp2);\nif (length(s1)>2) || (length(s2)>2)\n  error 'Matrix multiplication is only defined for vectors and simple arrays.'\nend\n\nif (s1(2) == s2(1)) || (numel(sp1)==1) || (numel(sp2)==1)\n  % they are compatible\n  \n  if (numel(sp1) == 1) && (numel(sp2) == 1)\n    % both are scalars. Just use .*\n    sp = sp1.*sp2;\n    \n  elseif (numel(sp1) == 1) && (numel(sp2) > 1)\n    % sp1 is a scalar, but not sp2\n    sp = sympoly(sp2);\n    for i = 1:numel(sp2)\n      sp(i) = sp1.*sp2(i);\n    end\n\n  elseif (numel(sp1) > 1) && (numel(sp2) == 1)\n    % sp2 is a scalar, but not sp1\n    sp = sympoly(sp1);\n    for i = 1:numel(sp1)\n      sp(i) = sp1(i).*sp2;\n    end\n    \n  elseif (numel(sp1) > 1) && (numel(sp2) > 1)\n    % both are arrays.\n    sp = sympoly(zeros(s1(1),s2(2)));\n\n    for i = 1:s1(1)\n      for j = 1:s2(2)\n        for k = 1:s1(2)\n          sp(i,j) = sp(i,j) + sp1(i,k).*sp2(k,j);\n        end\n      end\n    end\n    \n  end\n  \nelse\n  error 'sp1 and sp2 are of incompatible sizes for .* operation.'\n  \nend\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9577-symbolic-polynomial-manipulation/SymbolicPolynomials/@sympoly/mtimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5798069047284568}}
{"text": "function T = multiply_pots(T1, T2)\n% MULTIPLY_POTS Multiply a pair of dpots together pointwise.\n% T = multiply_pots(pots)\n\ndom = myunion(T1.domain, T2.domain);\n%ns = sparse(1, max(dom)); % causes problems in myreshape on NT\nns = zeros(1, max(dom));\nns(T1.domain) = T1.sizes;\nns(T2.domain) = T2.sizes;\nT = dpot(dom, ns(dom));\nT = multiply_by_pot(T, T1);\nT = multiply_by_pot(T, T2);   \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/@dpot/multiply_pots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5798069022255651}}
{"text": "function [E,J]=SynthMeasWatsonSHCylSingleRadTortGPD(x, protocol, fibredir, roots)\n% Substrate: Impermeable cylinders with one radius in a homogeneous background.\n% Orientation distribution: Watson's distribution with SH approximation\n% Pulse sequence: Any\n% Signal approximation: Gaussian phase distribution.\n% Notes: This version estimates the hindered diffusivity from the free diffusivity\n% and packing density using Szafer et al's tortuosity model for randomly\n% packed cylinders.\n%\n% [E,J]=SynthMeasWatsonSHCylSingleRadTortGPD(x, protocol, fibredir, roots)\n% returns the measurements E according to the model and the Jacobian J of the\n% measurements with respect to the parameters.  The Jacobian does not\n% include derivates with respect to the fibre direction.\n%\n% x is the list of model parameters in SI units:\n% x(1) is the volume fraction of the intracellular space.\n% x(2) is the free diffusivity of the material inside and outside the cylinders.\n% x(3) is the radius of the cylinders.\n% x(4) is the concentration parameter of the Watson's distribution.\n%\n% protocol is the object containing the acquisition protocol.\n%\n% fibredir is a unit vector along the symmetry axis of the Watson's\n% distribution.  It must be in Cartesian coordinates [x y z]' with size [3 1].\n%\n% roots contains solutions to the Bessel function equation from function\n% BesselJ_RootsCyl.\n%\n% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\n\nf=x(1);\ndPar=x(2);\n% This version is for cylinders with regular packing.\n%dPerp = dPar/((1 + f^(3/2))^2);\n% This one is for randomly packed cylinders\ndPerp = dPar*(1-f);\nR=[x(3)]; \nkappa=x(4);\n\nx_full = [f dPar dPerp R kappa];\n\n% Call the model with no isotropic component to get the anisotropic component.\nif(nargout == 1)\n    E=SynthMeasWatsonSHCylSingleRadGPD(x_full, protocol, fibredir, roots);\nelse\n    [E,J_full]=SynthMeasWatsonSHCylSingleRadGPD(x_full, protocol, fibredir, roots);\n    J(:,1) = J_full(:,1) - J_full(:,3)*dPar;\n    J(:,2) = J_full(:,2) + J_full(:,3)*(1-f);\n    J(:,3) = J_full(:,4);\n    J(:,4) = J_full(:,5);\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/NODDI_toolbox_v1.0/models/watson/SynthMeasWatsonSHCylSingleRadTortGPD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5797034499844161}}
{"text": "function value = dmach ( job )\n\n%*****************************************************************************80\n%\n%% DMACH computes machine parameters of floating point arithmetic.\n%\n%  Discussion:\n%\n%    This routine is for testing only.  It is not required by LINPACK.\n%\n%    If there is trouble with the automatic computation of these quantities,\n%    they can be set by direct assignment statements.\n%    We assume the computer has\n%\n%      B = base of arithmetic\n%      T = number of base B digits\n%      L = smallest possible exponent\n%      u = largest possible exponent\n%\n%    then\n%\n%      EPS = B**(1-T)\n%      TINY = 100.0D+00 *B**(-L+T)\n%      HUGE = 0.01D+00 *B**(U-T)\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    08 June 2005\n%\n%  Author:\n%\n%    MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Jack Dongarra, Cleve Moler, Jim Bunch and Pete Stewart,\n%    LINPACK User's Guide,\n%    SIAM, 1979.\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 JOB:\n%    1: requests EPSILON;\n%    2: requests TINY;\n%    3: requests HUGE.\n%\n%    Output, real VALUE, the requested value.\n%\n  s = 1.0;\n\n  while ( 1 )\n\n    tiny = s;\n    s = s / 2.0;\n\n    if ( s * 1.0 == 0.0 | s == 0.0 )\n      break\n    end\n\n  end\n\n  tiny = ( tiny / eps ) * 100.0;\n  huge = 1.0 / tiny;\n\n  if ( job == 1 )\n    value = eps;\n  elseif ( job == 2 )\n    value = tiny;\n  elseif ( job == 3 )\n    value = huge;\n  else\n    xerbla ( 'DMACH', 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/blas0/dmach.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5796852309968441}}
{"text": "function [kip] = ozf2kip(ozf)\n% Convert force from ounces force to kip. \n% Chad A. Greene 2012\nkip = ozf*0.0000625;", "meta": {"author": "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/ozf2kip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.57967596454862}}
{"text": "function h = int_hist(x, n)\n% INT_HIST(x, n) is a histogram of all integer values 1..n in x.\n% If n is not given, max(x) is used.\n\n% Hans Olsson's one-liner from matlab faq\nh = full(sum(sparse(1:length(x(:)),x(:),1)));\nif nargin == 2\n  if n > length(h)\n    % pad with zeros\n    h = [h zeros(1,n-length(h))];\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/libs/+lightspeed/int_hist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.57966577485059}}
{"text": "function W_down = get_W_down(W)\nN = size(W, 2);\nW_down = zeros(2, 2 * N^2);\nfor u2 = 0 : 1\n    for y1 = 1 : N\n        for y2 = 1 : N\n            for u1 = 0 : 1\n%                 P = 0.5 * W(mod(u1 + u2, 2) + 1, y1) * W(u2 + 1, y2);\n%                 if P == 0\n%                     W_down(u2 + 1, 2 * N * (y1 - 1) + 2 * (y2 - 1) + u1 + 1) = realmin;\n%                 else\n%                     W_down(u2 + 1, 2 * N * (y1 - 1) + 2 * (y2 - 1) + u1 + 1) = P;\n%                 end\n                W_down(u2 + 1, 2 * N * (y1 - 1) + 2 * (y2 - 1) + u1 + 1) = 0.5 * W(mod(u1 + u2, 2) + 1, y1) * W(u2 + 1, y2);\n            end\n        end\n    end\nend\nend\n", "meta": {"author": "YuYongRun", "repo": "PolarCodeDecodersInMatlab", "sha": "f1b512d10bf057e83f18685ea012d242bdaaf6ac", "save_path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab", "path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab/PolarCodeDecodersInMatlab-f1b512d10bf057e83f18685ea012d242bdaaf6ac/PolarFastSCL/HowToConstructPolarCode/UpgradingConstruction/get_W_down.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5796493261495842}}
{"text": "function []=PS_calc_ifg_std\n% PS_CALC_IFG_STD() calculate std for each ifg\n%\n%   Andy Hooper, June 2006\n%\n%   ======================================================\n%   09/2006 AH: small baselines added \n%   02/2010 AH: More informative info displayed\n%   ======================================================\n\nfprintf('\\nEstimating noise standard deviation (degrees)...\\n')\n\nsmall_baseline_flag=getparm('small_baseline_flag');\n\nload psver\npsname=['ps',num2str(psver)];\nphname=['ph',num2str(psver)];\npmname=['pm',num2str(psver)];\nbpname=['bp',num2str(psver)];\nifgstdname=['ifgstd',num2str(psver)];\n\nps=load(psname);\npm=load(pmname);\nbp=load(bpname);\n\nif exist([phname,'.mat'],'file')\n    phin=load(phname);\n    ph=phin.ph;\n    clear phin\nelse\n    ph=ps.ph;\nend\n\nn_ps=length(ps.xy);\nmaster_ix=sum(ps.master_day>ps.day)+1;\n\nif strcmpi(small_baseline_flag,'y')\n    ph_diff=angle(ph.*conj(pm.ph_patch).*exp(-j*(repmat(pm.K_ps,1,ps.n_ifg).*bp.bperp_mat)));    \nelse\n    bperp_mat=[bp.bperp_mat(:,1:ps.master_ix-1),zeros(ps.n_ps,1,'single'),bp.bperp_mat(:,ps.master_ix:end)];\n    ph_patch=[pm.ph_patch(:,1:master_ix-1),ones(n_ps,1),pm.ph_patch(:,master_ix:end)];\n    ph_diff=angle(ph.*conj(ph_patch).*exp(-j*(repmat(pm.K_ps,1,ps.n_ifg).*bperp_mat+repmat(pm.C_ps,1,ps.n_ifg))));\nend\n\nifg_std=[sqrt(sum(ph_diff.^2)/n_ps)*180/pi]';\nif strcmpi(small_baseline_flag,'y')\n  for i=1:ps.n_ifg\n    fprintf('%3d %s_%s %3.2f\\n',i,datestr(ps.ifgday(i,1)),datestr(ps.ifgday(i,2)),ifg_std(i))\n  end\nelse\n  for i=1:ps.n_ifg\n    fprintf('%3d %s %3.2f\\n',i,datestr(ps.day(i)),ifg_std(i))\n  end\nend\nfprintf('\\n')\n\nsave(ifgstdname,'ifg_std'); \n    \n    \n\n", "meta": {"author": "dbekaert", "repo": "StaMPS", "sha": "c159eb81b16c446e0e8fdef7dd435eb22e0240ed", "save_path": "github-repos/MATLAB/dbekaert-StaMPS", "path": "github-repos/MATLAB/dbekaert-StaMPS/StaMPS-c159eb81b16c446e0e8fdef7dd435eb22e0240ed/matlab/ps_calc_ifg_std.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5796493261495842}}
{"text": "function legendre_polynomial_test ( )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_POLYNOMIAL_TEST tests the LEGENDRE_POLYNOMIAL library.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    18 October 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'LEGENDRE_POLYNOMIAL_TEST:\\n' );\n  fprintf ( 1, '  MATLAB version.\\n' );\n  fprintf ( 1, '  Test the LEGENDRE_POLYNOMIAL library.\\n' );\n\n  legendre_polynomial_test01 ( );\n  legendre_polynomial_test015 ( );\n  legendre_polynomial_test016 ( );\n  legendre_polynomial_test02 ( );\n  legendre_polynomial_test03 ( );\n  legendre_polynomial_test04 ( );\n\n  p = 5;\n  b = 0.0;\n  legendre_polynomial_test05 ( p, b );\n\n  p = 5;\n  b = 1.0;\n  legendre_polynomial_test05 ( p, b );\n\n  p = 5;\n  e = 0;\n  legendre_polynomial_test06 ( p, e );\n\n  p = 5;\n  e = 1;\n  legendre_polynomial_test06 ( p, e );\n\n  legendre_polynomial_test07 ( );\n  legendre_polynomial_test08 ( );\n  legendre_polynomial_test09 ( );\n  legendre_polynomial_test095 ( );\n\n  p = 5;\n  legendre_polynomial_test10 ( p );\n\n  legendre_polynomial_plot01 ( );\n%\n%  Terminate.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'LEGENDRE_POLYNOMIAL_TEST:\\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/legendre_polynomial/legendre_polynomial_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.5796493249210636}}
{"text": "function [transprob, termprob] = remove_hhmm_end_state(A)\n% REMOVE_END_STATE Infer transition and termination probabilities from automaton with an end state\n% [transprob, termprob] = remove_end_state(A)\n%\n% A(i,k,j) = Pr( i->j | Qps=k), where i in 1:Q, j in 1:(Q+1), and Q+1 is the end state\n% This implements the equation in footnote 3 of my NIPS 01 paper,\n% transprob(i,k,j) = \\tilde{A}_k(i,j)\n% termprob(k,j) = \\tau_k(j)\n%\n% For the top level, the k index is missing.\n\nQ = size(A,1);\ntoplevel = (ndims(A)==2);\nif toplevel\n  Qk = 1;\n  A = reshape(A, [Q 1 Q+1]);\nelse\n  Qk = size(A, 2);\nend\n\ntransprob = A(:, :, 1:Q);\nterm = A(:,:,Q+1)'; % term(k,j) = P(Qj -> end | k)\ntermprob = term;\n%termprob = zeros(Qk, Q, 2);\n%termprob(:,:,2) = term;\n%termprob(:,:,1) = 1-term;\n\nfor k=1:Qk\n  for i=1:Q\n    for j=1:Q\n      denom = (1-termprob(k,i));\n      denom = denom + (denom==0)*eps;\n      transprob(i,k,j) = transprob(i,k,j) / denom;\n    end\n  end    \nend\n\nif toplevel\n  termprob = squeeze(termprob);\n  transprob = squeeze(transprob);\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/dynamic/HHMM/remove_hhmm_end_state.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.579649321235502}}
{"text": "% test for Fethalah code and Prados code\nn = 500;\n\nrep = 'results/anisotropic-feth/';\nif not(exist(rep))\n    mkdir(rep);\nend\n\n%% compute random tensor field\nrandn('seed', 12345);\nU = randn(n,n,2);\nsigma = (n/200)*30;\noptions.bound = 'per';\nfor it=1:10\n    U = perform_vf_normalization( perform_blurring(U, sigma,options) );\nend\nU = perform_vf_normalization( U );\n\naniso_list = [1 .5 .2 .1 .05 .01 .001];\n\np = 5;\nx = round( n/(p*2):n/p:n-n/(p*2) );\n[Y,X] = meshgrid(x,x);\n% start_points = round( start_points*(n-1)+1 );\nstart_points = cat(1, X(:)', Y(:)');    \n\ns = randperm(size(start_points,2));\nfor i=1:length(aniso_list)\n\n    aniso = aniso_list(i);\n    V = cat(3, -U(:,:,2), U(:,:,1)); % orthogonal vector\n    T = perform_tensor_recomp(U,V, ones(n),ones(n)*aniso );\n    Ti = perform_tensor_recomp(U,V, ones(n),ones(n)*1/aniso );\n\n    options.use_feth_code = 0;\n    tic;\n    [D,S,Q] = perform_fast_marching(T, start_points, options);\n    disp(['Prados: ' num2str(toc)]);\n\n    hx = 1/n; hy = 1/n;\n    tic;\n    [D1,dUx,dUy, Vor, L] = fm2dAniso([hx;hy], Ti, start_points);\n    disp(['Feth: ' num2str(toc)]);\n\n    imageplot(s(Q), 'Prados', 1,2,1);\n    imageplot(s(Vor+1), 'Feth', 1,2,2);\n    colormap jet(256);\n    saveas(gcf, [rep 'voronoi-' num2str(aniso) '.png'], 'png');\n    \n    clf;\n    plot_tensor_field(T, perform_histogram_equalization(D, 'linear'));\n    colormap jet(256);\n    saveas(gcf, [rep 'distance-aniso-' num2str(aniso) '-prados.png'], 'png');\n    \n    clf;\n    plot_tensor_field(T, perform_histogram_equalization(D1, 'linear'));\n    colormap jet(256);\n    saveas(gcf, [rep 'distance-' num2str(aniso) '-feth.png'], 'png');\n\nend", "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_anisotropic_feth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768094082276, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.579649313864378}}
{"text": "function res = GRAPPA(kData,kCalib,kSize,lambda, dispp)\n% res = GRAPPA(kData,kCalib,kSize,lambda [, disp)\n%\n% This is a GRAPPA reconstruction algorithm that supports \n% arbitrary Cartesian sampling. However, the implementation\n% is highly inefficient in Matlab because it uses for loops. \n% This implementation is very similar to the GE ARC implementation.\n%\n% The reconstruction looks at a neighborhood of a point and\n% does a calibration according to the neighborhood to synthesize\n% the missing point. This is a k-space varying interpolation.\n% A sampling configuration is stored in a list, and retrieved\n% when needed to accelerate the reconstruction (a bit)\n%\n% Inputs: \n%       kData     -   [Size x, Size y, num coils] 2D multi-coil k-space data to reconstruct from.\n%                   Make sure that the missing entries have exact zeros in them.\n%       kCalib    -   calibration data (fully sampled k-space)\n%       kSize     - size of the 2D GRAPPA kernel [kx, ky]\n%       lambda    - Tykhonov regularization for the kernel calibration.\n%       dispp      - Figure number to display images as they are\n%                   reconstructed\n% Outputs:\n%       res       - k-space data where missing entries have been filled in.\n%\n% Example:\n%   [x,y] = meshgrid(linspace(0,1,128));\n%   % Generate fake Sensitivity maps\n%   sMaps = cat(3,x.^2,1-x.^2,y.^2,1-y.^2);\n%   % generate 4 coil phantom\n%   imgs = repmat(phantom(128),[1,1,4]).*sMaps;\n%   DATA = fft2c(imgs);\n%   % crop 20x20 window from the center of k-space for calibration\n%   kCalib = crop(DATA,[20,20,4]);\n%\n%   %calibrate a kernel\n%   kSize = [5,5];\n%   coils = 4;\n%   \n%   % undersample by a factor of 2\n%   DATA(1:2:end,2:2:end,:) = 0;\n%   DATA(2:2:end,1:2:end,:) = 0;\n%   \n%   %reconstruct:\n%   [res] = GRAPPA(DATA,kCalib, kSize, 0.01);\n%   figure, imshow(cat(2,sos(imgs), 2*sos(ifft2c(DATA)), sos(ifft2c(res))),[]);\n%   title('full,  zero-fill,   result')\n%   \n%       \n%\n% (c) Michael Lustig 2008\n\n\nif nargin < 5\n    dispp = 0;\nend\n\n\npe = size(kData,2); fe = size(kData,1); coils = size(kData,3); % get sizes\n\nres = kData*0;\n%[AtA] = corrMatrix(kCalib,kSize); % build coil correlation matrix\nAtA = dat2AtA(kCalib, kSize); % build coil calibrating matrix\n\nfor n=1:coils\n\tdisp(sprintf('reconstructing coil %d',n)); \t\n\tres(:,:,n) = ARC(kData, AtA,kSize, n,lambda); % reconstruct single coil image\n    if dispp ~=0\n        figure(dispp), imshow3(abs(ifft2c(res)),[]); drawnow\n    end\n    \nend\n\n\nfunction [res] = ARC(kData, AtA, kSize, c,lambda);\n[sx,sy,nCoil] = size(kData);\n\n\nkData = zpad(kData,[sx+kSize(1)-1, sy+kSize(2)-1,nCoil]);\n\ndummyK = zeros(kSize(1),kSize(2),nCoil); dummyK((end+1)/2,(end+1)/2,c) = 1;\nidxy = find(dummyK);\n\nres = zeros(sx,sy);\n\nMaxListLen = 100;\nLIST = zeros(kSize(1)*kSize(2)*nCoil,MaxListLen);\nKEY =  zeros(kSize(1)*kSize(2)*nCoil,MaxListLen);\ncount = 0;\n\n%H = waitbar(0);\nfor y = 1:sy\n\tfor x=1:sx\n\t%\twaitbar((x + (y-1)*sx)/sx/sy,H);\n\t\ttmp = kData(x:x+kSize(1)-1,y:y+kSize(2)-1,:);\n\t\tpat = abs(tmp)>0;\n\t\tif pat(idxy) | sum(pat)==0\n\t\t\tres(x,y) = tmp(idxy);\n\t\telse\n\t\t\tkey = pat(:);\n            idx = 0;\n\t\t\tfor nn=1:size(KEY,2);\n\t\t\t\tif sum(key==KEY(:,nn))==length(key)\n\t\t\t\t   idx = nn;\n\t\t\t\t   break;\n\t\t\t   \tend\n\t\t\tend\n\t\t\tif idx == 0\n\t\t\t\tcount = count + 1;\n\t\t\t\tkernel = calibrate(AtA,kSize,nCoil,c,lambda,pat);\n\t\t\t\tKEY(:,mod(count,MaxListLen)+1) = key(:);\n\t\t\t\tLIST(:,mod(count,MaxListLen)+1) = kernel(:);\n\t\t\t\t%disp('add another key');size(KEY,2)\n\t\t\telse\n\t\t\t\tkernel = LIST(:,idx);\n\t\t\tend\n\t\t\tres(x,y) = sum(kernel(:).*tmp(:));\n\t\tend\n\n\tend\nend\n\t\n%close(H);\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_SPIRiT/GRAPPA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5796493107202868}}
{"text": "clear,clc\n\naddpath(pwd);\ncd cvx;\naddpath(genpath(pwd));\ncd ..;\n\nload('Ns=3.mat');\n\nNs = 3;\n\nNRF = 3;\n\nSNR_dB = -35:5:5;\nSNR = 10.^(SNR_dB./10);\nrealization = size(H,3);\nsmax = length(SNR);% enable the parallel\n\nparfor reali = 1:realization\n    [ FRF, FBB ] = SDR_AltMin( Fopt(:,:,reali), NRF);\n    [ WRF, WBB ] = Receiver( Wopt(:,:,reali), NRF);\n    for s = 1:smax\n        R(s,reali) = log2(det(eye(Ns) + SNR(s)/Ns * pinv(WRF * WBB) * H(:,:,reali) * FRF * FBB * FBB' * FRF' * H(:,:,reali)' * WRF * WBB));\n    end\nend\nplot(SNR_dB,sum(R,2)/realization,'Marker','diamond','LineWidth',1.5,'Color',[0.87058824300766 0.490196079015732 0]);\ngrid on\nhold on", "meta": {"author": "yuxianghao", "repo": "Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems", "sha": "18f610e24498f2305a498459150492e17626754b", "save_path": "github-repos/MATLAB/yuxianghao-Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems", "path": "github-repos/MATLAB/yuxianghao-Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems/Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems-18f610e24498f2305a498459150492e17626754b/Narrowband/SDR-AltMin/main_SNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5796430294852115}}
{"text": "function dXdt = dynamics_SRB(t,Xt,Ut,Xd,U_ext,p)\n\n%% parameters\nmass = p.mass;\nJ = p.J;       % inertia tensor in body frame {B}\ng = 9.81;\n\n%% decompose\n% X = [pc dpc vR wb pf]'\npc = reshape(Xt(1:3),[3,1]);\ndpc = reshape(Xt(4:6),[3,1]);\nR = reshape(Xt(7:15),[3,3]);\nwb = reshape(Xt(16:18),[3,1]);\npf34 = reshape(Xt(19:30),[3,4]);\npfd34 = reshape(Xd(19:30),[3,4]);\n\n% r\nr34 = pf34 - repmat(pc,[1,4]);\n\n% GRF\nf34 = reshape(Ut,[3,4]);\n\n%% dynamics\nddpc = 1/mass * (sum(f34,2) + U_ext) + [0;0;-g];\ndR = R * hatMap(wb);\n\ntau_s = zeros(3,1);       % body torque expressed in {S}\nfor ii = 1:4\n    tau_s = tau_s + hatMap(r34(:,ii)) * f34(:,ii);\nend\ntau_ext = hatMap(R * p.p_ext) * U_ext;\ntau_tot = sum(tau_s,2) + tau_ext;\ndwb = J \\ (R' * tau_tot - hatMap(wb) * J * wb);\n\ndpf = p.Kp_sw * (pfd34(:) - pf34(:));\n\ndXdt = [dpc;ddpc;dR(:);dwb;dpf];\n\n\nend\n\n\n\n\n\n\n\n", "meta": {"author": "YanranDing", "repo": "RF-MPC", "sha": "758525cded89be434b04eab838bed034f67c27fd", "save_path": "github-repos/MATLAB/YanranDing-RF-MPC", "path": "github-repos/MATLAB/YanranDing-RF-MPC/RF-MPC-758525cded89be434b04eab838bed034f67c27fd/fcns/dynamics_SRB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5796430252185096}}
{"text": "%{\nhelix_example.m\nExample of how to use rebin_helix.m for helical cone-beam CT reconstruction.\nCopyright 2010-7-21, Gregory Handy and Jeff Fessler, University of Michigan\n%}\n\nif 0 % test a particular geometry (case 2795)\n\tf.down = 4; % down sample a lot to save time\n\tcg = ct_geom('ge2', 'nt', 32, 'na', 3625, ...\n...%\t\t'dfs', inf, ...\n\t\t'dfs', 0, ...\n\t\t'down', f.down, ...\n\t\t'pitch', .53125, 'source_z0', -50.5494160, ...\n\t\t'orbit', 3625/984*360, ... % 1326.21951219512195,\n\t\t'orbit_start', 109.12139);\n\n\tig = image_geom('nx', 320, 'ny', 320, 'nz', 3*64, ... % 61\n\t\t'down', f.down, ...\n\t\t'dx', 2.191162, 'dz', 0.625, 'offset_z', 56.0);\n%\tcg.plot(ig), return\nend\n\n\nif ~isvar('cg'), printm 'cg: cone-beam CT geometry'\n\tf.down = 4; % down sample a lot to save time\n\tf.nturn = 12;\n\tcg = ct_geom('ge2', 'pitch', 0.5, 'source_z0', -100, ...\n\t\t'na', 984*f.nturn, 'orbit', 360*f.nturn, 'orbit_start', 17, ...\n\t\t'down', f.down);\nend\n\nif ~isvar('ig'), printm 'ig: image geometry'\n\tig = image_geom('nx', 256, 'ny', 256, 'nz', 160, ...\n\t\t\t'dx', 2, 'dz', 0.625, 'down', f.down);\n\tim clf, cg.plot(ig);\nprompt\nend\n\n\nif ~isvar('ell'), printm 'ell: ellipsoid object'\n\tz0 = ig.offset_z * ig.dz;\n\tell = [ ...\n\t\t[0 0 -z0\t[0.3 0.1]*ig.fov 0.6*ig.zfov\t0 0 1000];\n\t\t[80 10 -z0\t30 30 10\t0 0 1000];\n\t\t[-10 -40 75\t40 40 40\t0 0 1000];\n\t\t[-10 80 -20\t30 30 30\t0 0 1000];\n\t\t[0 0 -36\t20 20 5\t0 0 1000];\n\t\t[0 0 -12\t20 20 5\t0 0 1000];\n\t\t[0 0 12\t20 20 5\t0 0 1000];\n\t\t[0 0 36\t20 20 5\t0 0 1000];\n\t];\n\tclear z0\nend\n\n\nif ~isvar('xtrue'), printm 'xtrue: true image volume'\n\txtrue = ellipsoid_im(ig, ell, 'oversample', 2);\n\n\tclim = [0 2000];\n\tim plc 2 3\n%\tim(1, ig.x, ig.y, xtrue, clim), cbar\n\tim(1, 'mid3', xtrue, clim), cbar\n\ttitlef('x true, z=%g to %g', ig.z(1), ig.z(end))\nprompt\nend\n\n\nif ~isvar('proj'), printm 'proj: analytical ellipsoid projection views'\n\tproj = ellipsoid_proj(cg, ell);\n\n\tim(4, 'row', 1, permute(proj, [1 3 2]), 'true helix sinograms'), cbar\nprompt\nend\n\n\nif ~isvar('sino'), printm 'sino: rebin helix to fan-beam'\n%\tf.short = 1;\n\tf.short = 0; % for rebinned projection views below\n\tf.itype = 'linear';\n%\tf.itype = 'nearest';\n\t[sino, orbits, used] = rebin_helix(cg, ig, proj, ...\n\t\t'type', f.itype, 'short', f.short, 'collapse', 0);\n\n\tif exist('helix_rebin_mex') == 3 % matlab vs mex\n\t\t[sino0, orbits0, used] = rebin_helix(cg, ig, proj, ...\n\t\t\t'use_mex', 0, ...\n\t\t\t'type', f.itype, 'short', f.short, 'collapse', 0);\n\n\t\tequivs(orbits, orbits0)\n\t\tequivs(sino0, sino)\n\t\tclear sino0 orbits0\n\tend\n\n\tim(5, sino, 'SSRB sinos'), cbar, axis normal\n\tim(6, used), cbar, axis normal\nprompt\nend\n\n\n%% examine the projection views\nif false && ~f.short % not possible for short scans!\n%\tpview = permute(sino, [1 3 2]); % projection views\n%\tjf_slicer(pview) % awful, understandably because orbits vary!\n\n\t% rebin each fan-beam sinogram onto a common orbit_start parallel-beam\n\tsf = sino_geom('fan', 'dsd', cg.dsd, 'dso', cg.dso, ...\n\t\t'ns', cg.ns, 'ds', cg.ds, 'offset_s', cg.offset_s, ...\n\t\t'orbit', orbits(1,1), ...\n\t\t'na', size(sino, 2)); % # views in fan-beam sinogram, not helix cg.na\n\tsp = sino_geom('par', 'nb', cg.ns, 'dr', cg.ds/2, ...\n\t\t'orbit', 360, 'na', size(sino, 2)); % parallel-beam\n\n\tsino2 = zeros(size(sino));\n\tfor iz = 1:ig.nz % each slice\n\t\tsf.orbit_start = orbits(iz,2); % sino_geom for this slice!\n\t\tsino2(:,:,iz) = rebin_sino(sino(:,:,iz), sf, sp);\n\tend\n%\tjf_slicer(sino2)\n\n\tpview = permute(sino2, [1 3 2]); % projection views\n\tjf_slicer(pview) % animate views\nreturn\nend\n\n\n% helical cone-beam reconstruction based on SSRB\nif ~isvar('xssrb'), printm 'fbp from ssrb'\n\t[xssrb, tmp] = fbp_helix_stack(cg, ig, sino, orbits, ...\n\t\t'short', f.short, 'window', 'hanning,1.0');\n\txssrb = xssrb .* (ig.circ(cg.rmax) > 0); % mask\n\n%\tim(2, xssrb, 'SSRB recon', clim), cbar\n\tim(2, 'mid3', xssrb, 'SSRB recon', clim), cbar\n\tim(6, tmp, 'after weighting'), cbar, axis normal\n\tim(3, xssrb - xtrue, 'error', [-500 500]), cbar\nprompt\nend\n\n\nif im % profile, for checking HU accuracy\n\tim subplot 6\n\tiz = 1:ig.nz;\n\tix = ig.nx/2+1; iy = ig.ny/2+1;\n\tplot(\tig.z, squeeze(xtrue(ix,iy,iz)), 'o-', ...\n\t\tig.z, squeeze(xssrb(ix,iy,iz)), '.--')\n\taxis([minmax(ig.z)' -200 2100])\n\ttitlef('profile at (ix,iy)=(%g,%g)', ix,iy), xlabel z\nend\n\nif 0 % toggle\n\tfun = @(x) x;\n\tfun = @(x) jf_mip3(x, 'type', 'mid');\n\tfigure(2)\n\tim_toggle(fun(xssrb .* ig.circ), fun(xtrue))\nreturn\nend\n\n\nreturn % below here is comparisons with GH original method\n\nif ~isvar('xssrb_gh'), printm 'fbp from ssrb gh'\n\t[xssrb_gh, sino_gh] = fbp_helix_gh(cg, ig, proj, 'short', f.short);\n\tim(3, xssrb_gh, 'SSRB GH recon', clim), cbar\n\tim(4, sino, 'SSRB GH sinos'), cbar, axis normal\nprompt\nend\n\nif 0\n\tfigure(2)\n%\tim_toggle(fun(xssrb .* ig.circ), fun(xtrue), fun(xssrb_gh .* ig.circ), clim)\n\tim_toggle(fun(xssrb .* ig.circ), fun(xssrb_gh .* ig.circ), clim)\nend\n\nif im % profile\n\tiz = 21;\n\tiz = 1:ig.nz;\n\tim(3, xssrb_gh(:,:,iz) - xtrue(:,:,iz), 'GH Error'), cbar\n\n\tim subplot 6\n\tix = 1:ig.nx; iy = ceil(ig.ny/2); iz = ceil(ig.nz/2);\n\tiz = round(25/40 * ig.nz);\n\tplot(ix, xtrue(ix,iy,iz), '-', ix, xssrb_gh(ix,iy,iz), '--')\n\taxis([1 ig.nx -200 2100])\n\ttitlef('slice %d', iz), xlabel 'ix'\nend\n\n% xfdk = easyhelix(cg, ig, li_hat, 'use_mex', has_mex_jf, 'w1cyl', 0);\n% xfdk = myFeldkamp(cg, ig, li_hat, 'use_mex', 0);\n% im(4, xfdk(:,:,25), 'FDK recon Other'), 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/helix_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.579639136896443}}
{"text": "function offset = find_offset_multi_source(samples1, samples2)\n    [c, lags] = xcorr(samples1, samples2);\n    [~, ind] = max(c);\n    offset = lags(ind) + 1; % add 1 for Matlab indexing\nend", "meta": {"author": "yueyuzhao", "repo": "gyrophone", "sha": "aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e", "save_path": "github-repos/MATLAB/yueyuzhao-gyrophone", "path": "github-repos/MATLAB/yueyuzhao-gyrophone/gyrophone-aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e/find_offset_multi_source.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5796391317011858}}
{"text": "function cut = knapsack_create_cover_cut(a,b,x,alg,gubs)\n% Derive cover inequalities cut*[1;x]>=0 for a*x <= b\n\nif (all(a>=0) && sum(a)<=b) || (all(a<=0) && (b>=0))\n    % quick exit sum x <= large or sum x >= neg\n    cut = [];\n    return\nend\n\nif nargin < 3\n    x = ones(length(a),1);\n    alg = 'crowder';\n    gubs = [];\nelseif nargin < 4\n    alg = 'crowder';\n    gubs = [];\nelseif nargin < 5\n    gubs = spalloc(1,length(a),0);\nend\n\nif ~all(a)\n    nz = find(a);\n    a_ = a(nz); \n    cut_ = knapsack_create_cover_cut(a_,b,x(nz),alg,gubs(nz));\n    if ~isempty(cut_)\n        cut = spalloc(1,length(a)+1,0);\n        cut(1) = cut_(1);\n        cut(1+nz) = cut_(2:end);\n    else\n        cut = [];\n    end\n    return\nelseif any(a<0)\n    % Negative values in a*x <= b\n    % models -a*x >= -b i.e. typically something like sum stuff >= bound\n    %        -a*(1-y) >= -b  \n    %        -a*y <= b-sum(a)\n    neg = find(a < 0);\n    a_ = a;\n    a_(neg) = -a(neg);\n    x_ = x;\n    x_(neg) = 1-x(neg);\n    cut = knapsack_create_cover_cut(a_,b-sum(a(neg)),x_,alg,gubs);\n    % we know have a cut, cut(1) + cut(2:end)*y >=0\n    %                     cut(1) + cut(2:end)(1-x) >= 0\n    %                     cut(1) + sum(cut(2:end)) + (-cut(2))*x >= 0\n    if ~isempty(cut)\n        cut(1) = cut(1)+sum(cut(1 + neg));\n        cut(1 + neg) = -cut(1 + neg);\n    end\n    return\nend\n    \nswitch alg\n    case {'crowder',''}\n        % Heuristics from H. Crowder, E. Johnson, M. Padberg\n        % Solving large-scale 0\u20131 linear programming programs\n        [val,loc] = sort((1-x)./a(:),'ascend');\n    case 'gu'\n        [val,loc] = sort((x),'descend');\n    case 'gu-reverse'\n        [val,loc] = sort((x),'ascend');\n                \n    otherwise\n        error('Unsupport cover cut separation')\nend\n% Initial cover\nC = min(find(cumsum(a(loc))>b));\n\n% Apply Balas lifting\nq = knapsack_cover_lift_balas(a,loc(1:C));\n% qL = knapsack_cover_lift_letchford(a,b,loc(1:C));\n% if q~=qL\n%    'HEJ'\n% end\n% Return row where row*[1;x] hopefully is violated\ncut = spalloc(1,length(a)+1,0);\ncut(1) = C-1;\ncut(2:end)=-q;\n\n\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/modules/global/knapsack_create_cover_cut.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5796391309864181}}
{"text": "function [result,modified_q] = fit_q_to_range(qmin,qmax,q)\nmodified_q = q;\nwhile modified_q<qmin\n    modified_q = modified_q+2*pi;\nend\nwhile modified_q>qmax\n    modified_q = modified_q-2*pi;\nend\nif modified_q<qmin\n    result = false;\nelse\n    result = true;\nend\nend", "meta": {"author": "xuhuairuogu", "repo": "V-REP-Simulation-Projects", "sha": "841b944af4ea3a8fb250578d36434515f577f411", "save_path": "github-repos/MATLAB/xuhuairuogu-V-REP-Simulation-Projects", "path": "github-repos/MATLAB/xuhuairuogu-V-REP-Simulation-Projects/V-REP-Simulation-Projects-841b944af4ea3a8fb250578d36434515f577f411/admittance control(adapted from an example in the book--A Systematic Approach to Learning Robot Programming with ROS)/iiwa14_kinematics/fit_q_to_range.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5796391272206958}}
{"text": "mdl_p560\n\n% at zero pose\nt = p560.fkine(qz)\nt\nq = p560.ikine560(t)\nq\np560.fkine(q)\np560.ikine560(t, 'r')\np560.ikine560(t, 'rn')\n\np560.ikine(t)\n\n% at nominal pose\nqn\nt = p560.fkine(qn)\nt\n%q = ikine560(t)\nq\np560.fkine(q)\np560.ikine(t, [0, 0.7, 3, 0, 0.7, 0])\n\n% along trajectory\n[q,qd,qdd] = jtraj(qz, qr, 20)\nfkine(q)\n\nt1 = p560.fkine(qz)\nt2 = p560.fkine(qr)\ntraj = ctraj(t1, t2, 5)\np560.ikine(traj)\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/unit_test/old/kinematics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.579639125791161}}
{"text": "% DEMOIL100FGPLVM2 Oil100 data with FGPLVM.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'oil100';\nexperimentNo = 2;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('ftc');\noptions.optimiser = 'graddesc';\nlatentDim = 2;\nd = size(Y, 2);\noptions.initX = randn(size(Y, 1), latentDim)*1e-3;\nmodel = fgplvmCreate(latentDim, d, Y, options);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\nmodelWriteResult(model, dataSetName, experimentNo);\n\nif exist('printDiagram') & printDiagram\n  lvmPrintPlot(model, lbls, dataSetName, experimentNo);\nend\n\n\n% Load the results and display dynamically.\nlvmResultsDynamic(model.type, dataSetName, experimentNo, 'vector')\n\n% compute the nearest neighbours errors in latent space.\nerrors = lvmNearestNeighbour(model, lbls);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demOil100Fgplvm2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.579639125791161}}
{"text": "function J = NLMF2Dtree(I, Options)\n% This function NLMF2Dtree performs Non-Local Means noise filtering of \n% 2D grey/color image. This function constructs a KD-tree of the whole\n% image to find patches which have the closest intensity difference,\n% instead of searching only in the local neighboorhood like in the \n% NLMF function.\n% Warning, despite the usage of a kd-tree, this function will take more \n% then a hour for one image.\n%\n% Function:\n%\n%   J = NLMF2Dtree(I, Options);\n% \n% inputs, \n%   I : 2D grey/color or 3D image data, of type Single or Double \n%           in range [0..1]\n%   Options : Struct with options\n%\n% outputs,\n%   J : The NL-means filtered image or image volume \n%\n% options,\n%   Options.kernelratio : Radius of local Patch (default 3)\n%   Options.filterstrength : Strength of the NLMF filtering (default 0.05)\n%   Options.number : The number of patches which have the closest distance\n%                      to a local patch used for filtering (default 9).\n%\n% First Compile c-code!!!!, with :\n%   mex image2vectors_double.c -v\n%\n% Note: This function uses the \"Matlab Statistics Toolbox\"\n%\n\n% Process inputs\ndefaultoptions=struct('kernelratio',3,'filterstrength',0.05,'number',9);\nif(~exist('Options','var')), Options=defaultoptions;\nelse\n    tags = fieldnames(defaultoptions);\n    for i=1:length(tags), if(~isfield(Options,tags{i})), Options.(tags{i})=defaultoptions.(tags{i}); end, end\n    if(length(tags)~=length(fieldnames(Options))),\n        warning('NLMF2Dtree:unknownoption','unknown options found');\n    end\nend\n\n% Detect if this is a color or grey scale image\nswitch(size(I,3))\n    case 1, rgb=false;\n    case 3, rgb=true;\n    otherwise,error('NLMF2Dtree:inputs','This is not a 2D image');\nend\n\n% Pad the image, to allow simple extraction of local patches at the image\n% boundary\nIpad = padarray(I,[Options.kernelratio Options.kernelratio],'symmetric'); \n\n% Get the local patches\nV=image2vectors_double(double(Ipad),Options.kernelratio,2);\n\n% Create a KDtree with all local patches\nns = createns(V','nsmethod','kdtree');\n\n% Find the patches closest by in intensity in relation to the local patch\n% itself\n[VM,D] = knnsearch(ns,V','k',Options.number+1);\n\n% Calculate the weight of the patches used for a pixel\nW=exp(-(D.^2)*Options.filterstrength);\n% The first column is the local patch itself, set the weight to maximum\n% found in the other patches\nW(:,1)=max(W(:,2:end),[],2);\n% Make the sum of weights which will be used for one patch, equal to one.\nW=W./repmat((sum(W,2)+eps),[1 size(W,2)]);\n\n% Add the weighted intensities, of the center pixels of the in intensity\n% closest by patches\nif(rgb)\n    Ir=I(:,:,1);\n    Ig=I(:,:,2);\n    Ib=I(:,:,3);\n    Jr=sum(Ir(VM).*W,2);\n    Jg=sum(Ig(VM).*W,2);\n    Jb=sum(Ib(VM).*W,2);\n    Jr=reshape(Jr,[size(I,1) size(I,2)]);\n    Jg=reshape(Jg,[size(I,1) size(I,2)]);\n    Jb=reshape(Jb,[size(I,1) size(I,2)]);\n    J(:,:,1)=Jr;\n    J(:,:,2)=Jg;\n    J(:,:,3)=Jb;\nelse\n    J=sum(I(VM).*W,2); \n    J=reshape(J,size(I));\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_TVNLR/Toolbox_NLMeans/NLMF2Dtree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5795515738263529}}
{"text": "function [ x, y, z, w ] = ld1454 ( )\n\n%*****************************************************************************80\n%\n%% LD1454 computes the 1454 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(1454,1);\n  y = zeros(1454,1);\n  z = zeros(1454,1);\n  w = zeros(1454,1);\n  a = 0.0;\n  b = 0.0;\n  v = 0.7777160743261247E-04;\n  [ n, x, y, z, w ] = gen_oh ( 1, n, a, b, v, x, y, z, w );\n  v = 0.7557646413004701E-03;\n  [ n, x, y, z, w ] = gen_oh ( 3, n, a, b, v, x, y, z, w );\n  a = 0.3229290663413854E-01;\n  v = 0.2841633806090617E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.8036733271462222E-01;\n  v = 0.4374419127053555E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.1354289960531653;\n  v = 0.5417174740872172E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.1938963861114426;\n  v = 0.6148000891358593E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.2537343715011275;\n  v = 0.6664394485800705E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.3135251434752570;\n  v = 0.7025039356923220E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.3721558339375338;\n  v = 0.7268511789249627E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.4286809575195696;\n  v = 0.7422637534208629E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.4822510128282994;\n  v = 0.7509545035841214E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.5320679333566263;\n  v = 0.7548535057718401E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6172998195394274;\n  v = 0.7554088969774001E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6510679849127481;\n  v = 0.7553147174442808E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6777315251687360;\n  v = 0.7564767653292297E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6963109410648741;\n  v = 0.7587991808518730E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.7058935009831749;\n  v = 0.7608261832033027E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.9955546194091857;\n  v = 0.4021680447874916E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.9734115901794209;\n  v = 0.5804871793945964E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.9275693732388626;\n  v = 0.6792151955945159E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.8568022422795103;\n  v = 0.7336741211286294E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.7623495553719372;\n  v = 0.7581866300989608E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.5707522908892223;\n  b = 0.4387028039889501;\n  v = 0.7538257859800743E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5196463388403083;\n  b = 0.3858908414762617;\n  v = 0.7483517247053123E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4646337531215351;\n  b = 0.3301937372343854;\n  v = 0.7371763661112059E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4063901697557691;\n  b = 0.2725423573563777;\n  v = 0.7183448895756934E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3456329466643087;\n  b = 0.2139510237495250;\n  v = 0.6895815529822191E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2831395121050332;\n  b = 0.1555922309786647;\n  v = 0.6480105801792886E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2197682022925330;\n  b = 0.9892878979686097E-01;\n  v = 0.5897558896594636E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.1564696098650355;\n  b = 0.4598642910675510E-01;\n  v = 0.5095708849247346E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6027356673721295;\n  b = 0.3376625140173426;\n  v = 0.7536906428909755E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5496032320255096;\n  b = 0.2822301309727988;\n  v = 0.7472505965575118E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4921707755234567;\n  b = 0.2248632342592540;\n  v = 0.7343017132279698E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4309422998598483;\n  b = 0.1666224723456479;\n  v = 0.7130871582177445E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3664108182313672;\n  b = 0.1086964901822169;\n  v = 0.6817022032112776E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2990189057758436;\n  b = 0.5251989784120085E-01;\n  v = 0.6380941145604121E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6268724013144998;\n  b = 0.2297523657550023;\n  v = 0.7550381377920310E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5707324144834607;\n  b = 0.1723080607093800;\n  v = 0.7478646640144802E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5096360901960365;\n  b = 0.1140238465390513;\n  v = 0.7335918720601220E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4438729938312456;\n  b = 0.5611522095882537E-01;\n  v = 0.7110120527658118E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6419978471082389;\n  b = 0.1164174423140873;\n  v = 0.7571363978689501E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5817218061802611;\n  b = 0.5797589531445219E-01;\n  v = 0.7489908329079234E-03;\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/ld1454.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900945711678, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5795076619248427}}
{"text": "function numUnique=numUniqueElsInArray(vecList,skipEl)\n%%NUMUNIQUEELSINARRAY Count the number of unique elements in a vector.\n%\n%INPUTS: vecList A numElsXnumVecs list of vectors for which the number of\n%                unique elements in each vector (not considering across\n%                vectors) is desired. NaN values are not counted.\n%         skipEl If there is an element that should not count toward being\n%                unique (i.e. these are skipped), then it can be given. If\n%                no elements should be skipped, then this input can be\n%                omitted or an empty matrix can be passed.\n%\n%OUTPUTS: numUnique A numVecsX1 array, where the number of unique elements\n%               of each (column) vector in the matrix vecList is given.\n%\n%This function sorts the array, which puts makes duplicates consecutive.\n%then, it scans through the array, skipping duplicates. The sorting places\n%NaN values, if any, at the highest end of the array, past Inf. NaN values\n%are just skipped.\n%\n%EXAMPLE:\n% vecList=[17, 24,  1,  8, 15;\n%          17,  2,  7, 14, 16;\n%           4,  6,  2, 20, 22;\n%          10, 12, 19,  2,  3;\n%          11, 18, 25,  2,  0];\n% numUnique=numUniqueElsInArray(vecList,0)\n%One should get\n% numUnique=[4;5;5;4;4]\n%\n%September 2020 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumEls=size(vecList,1);\nnumVecs=size(vecList,2);\n\nif(nargin>1&&~isempty(skipEl))\n    vecList(vecList==skipEl)=NaN;\nend\n\n%Sorting the array makes all duplicates consecutive and places all NaN\n%values at the end of the array (even after Inf).\nvecList=sort(vecList,1,'ascend');\n\nnumUnique=zeros(numVecs,1);\nfor curVec=1:numVecs\n    curEl=1;\n    while(curEl<=numEls)\n        %Advance the index past duplicates.\n        while(curEl<numEls&&vecList(curEl,curVec)==vecList(curEl+1,curVec))\n            curEl=curEl+1;\n        end\n        \n        if(isnan(vecList(curEl,curVec)))\n            break; \n        end\n        numUnique(curVec)=numUnique(curVec)+1;\n        curEl=curEl+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/numUniqueElsInArray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5793067048031294}}
{"text": "function [beta,r,J,Sigma,mse,errorparam,robustw] = nlinmultifit(x_cell, y_cell, mdl_cell, beta0, options)\n%NLINMULTIFIT Nonlinear least-squares regression of multiple data sets\n%\n%\tA wrapper function for NLINFIT which allows simulatenous fitting of\n%\tmultiple data sets with shared fitting parameters. See example below.\n%\n%\tUnlike different solutions (using fminsearch or similar functions)\n%\tthis approach enables simple estimation of model predictions and\n%\ttheir confidence intervals, as well as confidence intervals on the\n%\tfitted parameters (using the built-in NLPREDCI and NLPARCI functions).\n%\n%\tKNOWN ISSUE:\n%\t\tIn this implementation, different data sets are weighted according\n%\t\tto their relative lengths. Special care should be taken when those\n%\t\tlengths are considerably different from one another to avoid\n%\t\tbiased results towards one data set in particular.\n%\n%\tINPUT:\n% \t\tx_cell,y_cell: Cell arrays containing the x,y vectors of the fitted\n%\t\t\t\t\t   data sets.\n% \t\tmdl_cell: Cell array containing model functions for each data set.\n% \t\tbeta0: Vector containing initial guess of the fitted parameters.\n% \t\toptions: Structure containing control parameters for NLINFIT (see\n%\t\t\t\t help file on NLINFIT for more details).\n%\n%\tOUTPUT:\n%\t\tbeta,r,J,Sigma,mse,errorparam,robustw: Direct output from NLINFIT.\n%\n%\tEXAMPLE:\n% \t\t% Generate X vectors for both data sets\n% \t\tx1 = 0:0.1:10;\n% \t\tx2 = 0:0.2:10;\n% \n% \t\t% Generate Y data with some noise\n% \t\ty1 = cos(2*pi*0.5*x1).*exp(-x1/5) + 0.1*randn(size(x1));\n% \t\ty2 = 0.5 + 2*exp(-(x2/5)) + 0.1*randn(size(x2));\n% \n% \t\t% Define fitting functions and parameters, with identical\n%\t\t% exponential decay for both data sets\n% \t\tmdl1 = @(beta,x) cos(2*pi*beta(1)*x).*exp(-x/beta(2));\n% \t\tmdl2 = @(beta,x) beta(4) + beta(3)*exp(-(x/beta(2)));\n% \n% \t\t% Prepare input for NLINMULTIFIT and perform fitting\n% \t\tx_cell = {x1, x2};\n% \t\ty_cell = {y1, y2};\n% \t\tmdl_cell = {mdl1, mdl2};\n% \t\tbeta0 = [1, 1, 1, 1];\n% \t\t[beta,r,J,Sigma,mse,errorparam,robustw] = ...\n%\t\t\t\t\tnlinmultifit(x_cell, y_cell, mdl_cell, beta0);\n% \n% \t\t% Calculate model predictions and confidence intervals\n% \t\t[ypred1,delta1] = nlpredci(mdl1,x1,beta,r,'covar',Sigma);\n% \t\t[ypred2,delta2] = nlpredci(mdl2,x2,beta,r,'covar',Sigma);\n% \n% \t\t% Calculate parameter confidence intervals\n% \t\tci = nlparci(beta,r,'Jacobian',J);\n% \n% \t\t% Plot results\n% \t\tfigure;\n% \t\thold all;\n% \t\tbox on;\n% \t\tscatter(x1,y1);\n% \t\tscatter(x2,y2);\n% \t\tplot(x1,ypred1,'Color','blue');\n% \t\tplot(x1,ypred1+delta1','Color','blue','LineStyle',':');\n% \t\tplot(x1,ypred1-delta1','Color','blue','LineStyle',':');\n% \t\tplot(x2,ypred2,'Color',[0 0.5 0]);\n% \t\tplot(x2,ypred2+delta2','Color',[0 0.5 0],'LineStyle',':');\n% \t\tplot(x2,ypred2-delta2','Color',[0 0.5 0],'LineStyle',':');\n%\n%\tAUTHOR:\n%\t\tChen Avinadav\n%\t\tmygiga (at) gmail\n%\n\n\tnum_curves = length(x_cell);\n\tif length(y_cell) ~= num_curves || length(mdl_cell) ~= num_curves\n\t\terror('Invalid input to NLINMULTIFIT');\n\tend\n\t\n\tx_vec = [];\n\ty_vec = [];\n\tmdl_vec = '@(beta,x) [';\n\tmdl_ind1 = 1;\n\tmdl_ind2 = 0;\n\tfor ii = 1:num_curves\n\t\tif length(x_cell{ii}) ~= length(y_cell{ii})\n\t\t\terror('Invalid input to NLINMULTIFIT');\n\t\tend\n\t\tif size(x_cell{ii},2) == 1\n\t\t\tx_cell{ii} = x_cell{ii}';\n\t\tend\n\t\tif size(y_cell{ii},2) == 1\n\t\t\ty_cell{ii} = y_cell{ii}';\n\t\tend\n\t\tx_vec = [x_vec, x_cell{ii}];\n\t\ty_vec = [y_vec, y_cell{ii}];\n\t\tmdl_ind2 = mdl_ind2 + length(x_cell{ii});\n\t\tmdl_vec = [mdl_vec, sprintf('mdl_cell{%d}(beta,x(%d:%d)), ', ii, mdl_ind1, mdl_ind2)];\n\t\tmdl_ind1 = mdl_ind1 + length(x_cell{ii});\n\tend\n\tmdl_vec = [mdl_vec(1:end-2), '];'];\n\tmdl_vec = eval(mdl_vec);\n\t\t\n\tif nargin == 4\n\t\t[beta,r,J,Sigma,mse,errorparam,robustw] = nlinfit(x_vec, y_vec, mdl_vec, beta0);\n\telse\n\t\t[beta,r,J,Sigma,mse,errorparam,robustw] = nlinfit(x_vec, y_vec, mdl_vec, beta0, options);\n\tend\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/40613-multiple-curve-fitting-with-common-parameters-using-nlinfit/nlinmultifit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.5793066890605301}}
{"text": "function x = lprec1(c, d, h, g, extmod)\n% LPREC1   One-level Laplacian pyramid reconstruction\n%\n%\tx = lprec1(c, d, h, g)\n%\n% Input:\n%   c:      coarse signal at half size\n%   d:      detail signal at full size\n%   h, g:   two biorthogonal 1-D lowpass filters\n%   extmod: [optional] extension mode (default is 'per')\n%\n% Output:\n%   x:      reconstructed signal\n%\n% Note:     This uses a new reconstruction method by Do and Vetterli,\n%           \"Framming pyramids\", IEEE Trans. on Sig Proc., Sep. 2003.\n%\n% See also:\tLPDEC1\n\nif ~exist('extmod', 'var')\n    extmod = 'per';\nend\n\nnd = ndims(c);\n\n% First, filter and downsample the detail image\nr = d;\nfor dim = 1:nd\n    r = filtdn(r, h, dim, extmod, 0);\nend\n\n% Then subtract the result from the coarse signal\np = c - r;\n\n% Even size filter needs to be adjusted to obtain perfect reconstruction\nadjust = mod(length(g) + 1, 2); \n\n% Then upsample and filter\nfor dim = 1:nd\n    p = upfilt(p, g, dim, extmod, adjust);\nend\n\n% Final combination\nx = p + d;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9868-laplacian-pyramid-toolbox/lprec1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5793046353045356}}
{"text": "function [tg,theta] = detTG(im,radius,norient)\n% function [tg,theta] = detTG(im,radius,norient)\n%\n% Compute smoothed but not thinned TG fields.\n\nif nargin<2, radius=0.02; end\nif nargin<3, norient=8; end\n\n[h,w,unused] = size(im);\nidiag = norm([h w]);\nif isrgb(im), im=rgb2gray(im); end\n\n% compute texture gradient\nno = 6;\nss = 1;\nns = 2;\nsc = sqrt(2);\nel = 2;\nk = 64;\nfname = sprintf( ...\n    'unitex_%.2g_%.2g_%.2g_%.2g_%.2g_%d.mat',no,ss,ns,sc,el,k);\ntextonData = load(fname); % defines fb,tex,tsim\ntmap = assignTextons(fbRun(textonData.fb,im),textonData.tex);\n[tg,theta] = tgmo(tmap,k,idiag*radius,norient,...\n                  'smooth','savgol','sigma',idiag*radius);\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/segbench/lib/matlab/detTG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5793046330704463}}
{"text": "%#codegen\nfunction [pixel_val, pixel_valid] = aMediantFilter_2D(c_data, c_idx)\n\nsmax = 9;\npersistent window;\nif isempty(window)\n    window = zeros(smax, smax);\nend\n\ncp = ceil(smax/2); % center pixel;\n\nw3 = -1:1;\nw5 = -2:2;\nw7 = -3:3;\nw9 = -4:4;\n\nr3 = cp + w3;      % 3x3 window\nr5 = cp + w5;      % 5x5 window\nr7 = cp + w7;      % 7x7 window\nr9 = cp + w9;      % 9x9 window\n\nd3x3 = window(r3, r3);\nd5x5 = window(r5, r5);\nd7x7 = window(r7, r7);\nd9x9 = window(r9, r9);\n\ncenter_pixel = window(cp, cp);\n\n\n% use 1D filter for 3x3 region\noutbuf = get_median_1d(d3x3(:)');\n[min3, med3, max3] = getMinMaxMed_1d(outbuf);\n\n% use 2D filter for 5x5 region\noutbuf = get_median_2d(d5x5);\n[min5, med5, max5] = getMinMaxMed_2d(outbuf);\n\n% use 2D filter for 7x7 region\noutbuf = get_median_2d(d7x7);\n[min7, med7, max7] = getMinMaxMed_2d(outbuf);\n\n% use 2D filter for 9x9 region\noutbuf = get_median_2d(d9x9);\n[min9, med9, max9] = getMinMaxMed_2d(outbuf);\n\n\npixel_val = get_new_pixel(min3, med3, max3, ...\n    min5, med5, max5, ...\n    min7, med7, max7, ...\n    min9, med9, max9, ...\n    center_pixel);\n\n\n% we need to wait until 9 cycles for the buffer to fill up\n% output is not valid every time we start from col1 for 9 cycles.\npersistent datavalid\nif isempty(datavalid)\n    datavalid = false;\nend\npixel_valid = datavalid;\ndatavalid = (c_idx >= smax);\n\n\n% build the 9x9 buffer\nwindow(:,2:smax) = window(:,1:smax-1);\nwindow(:,1) = c_data;\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [min, med, max] = getMinMaxMed_1d(inbuf)\n\nmax = inbuf(1);\nmed = inbuf(ceil(numel(inbuf)/2));\nmin = inbuf(numel(inbuf));\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [min, med, max] = getMinMaxMed_2d(inbuf)\n\n[nrows, ncols] = size(inbuf);\nmax = inbuf(1, 1);\nmed = inbuf(ceil(nrows/2), ceil(ncols/2));\nmin = inbuf(nrows, ncols);\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction new_pixel  = get_new_pixel(...\n    min3, med3, max3, ...\n    min5, med5, max5, ...\n    min7, med7, max7, ...\n    min9, med9, max9, ...\n    center_data)\n\nif (med3 > min3 && med3 < max3)\n    new_pixel = get_center_data(min3, med3, max3,center_data);\nelseif (med5 > min5 && med5 < max5)\n    new_pixel = get_center_data(min5, med5, max5,center_data);\nelseif (med7 > min7 && med7 < max7)\n    new_pixel = get_center_data(min7, med7, max7,center_data);\nelseif (med9 > min9 && med9 < max9)\n    new_pixel = get_center_data(min9, med9, max9,center_data);\nelse\n    new_pixel = center_data;\nend\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [new_data] = get_center_data(min,med,max,center_data)\nif center_data <= min || center_data >= max\n    new_data = med;\nelse\n    new_data = center_data;\nend\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/30068-adaptive-median-filter-matlab-code/AdaptiveMedianFilter_MATLAB_code/MALTAB_code/aMediantFilter_2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5793046295279751}}
{"text": "clear all;\nclc\n\n% File folder and name of int16 input signal\nint16FileFolder = '/Users/';\nint16FileName = 'inputsignal';\n\nfileName = [int16FileFolder int16FileName '.int16'];\n\nnMics = 128; % # mics in array\nfs = 44.1e3; %sampling rate\n\ndata = readInt16(nMics, fs, 0, fileName);\n\n% Get microphone positions\n%Here the microphone positions needs to be loaded. That is mic #1\n%corresponds to the first row in the timeSignal matrix, mic #2 to the\n%second row and so on\nXm = zeros(1, nMics);\nYm = zeros(1, nMics);\nZm = zeros(1, nMics);\nWm = ones(1, numel(Xm))/numel(Xm);\n\n\n% Scanning range (multiple frequencies, broadband)\nfmin = 3e3;\nfmax = 5e3;\nc = 340; %speed of sound\n\nt_start = 0.0;\nT = 0.035; %time weighting\nblock = T*fs;\n\n% Scanning parameters\ndistance = 2.0; %distance to source\nmaxX = 1; %max scanning extent x\nmaxY = 1; %max scanning extent y\ndeltaX = 0; %offset scanning grid\ndeltaY = 0; %offset scanning grid\nanglRes = 1; %angle resolution\nfilterFrequencies = [fmin, fmax];\n\n\ntic\n[anglex,angley, pow] = sweepPow2(Xm, Ym, Zm, Wm, data(:, (t_start*fs)+1:end), fs, filterFrequencies, distance, maxX, maxY, anglRes, block, deltaX, deltaY);\ntoc\n\nfigure;\nimagesc(angley, anglex, db(pow'))\n", "meta": {"author": "jorgengrythe", "repo": "beamforming", "sha": "0e0406044a102869f63c6006f952094827b81669", "save_path": "github-repos/MATLAB/jorgengrythe-beamforming", "path": "github-repos/MATLAB/jorgengrythe-beamforming/beamforming-0e0406044a102869f63c6006f952094827b81669/int16Beamforming/examplesInt16BeamformingTimeDomain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5793046205916179}}
{"text": "function spec = fwDs_spec(hatRxx, f, d, tauGrid, c)\n\n[nbin,nFrames] = size(hatRxx(:,:,1,1));\nngrid = length(tauGrid);\nR11 = hatRxx(:,:,1,1);\nR12 = hatRxx(:,:,1,2);\nR22 = hatRxx(:,:,2,2);\nTR = real(R11 + R22);\nSINC = sinc(2*f*d/c);\n\nSNR = zeros(nbin,nFrames,ngrid);\nfor pkInd=1:ngrid,\n    EXP = repmat(exp(-2*1i*pi*tauGrid(pkInd)*f),1,nFrames);\n    SNR(:,:,pkInd) = repmat(-(1+SINC)/2,1,nFrames) + repmat((1-SINC)/2,1,nFrames).*(TR + 2*real(R12.*EXP))./(TR - 2*real(R12.*EXP));\nend\nspec = SNR;\n\nend", "meta": {"author": "WenzheLiu-Speech", "repo": "sound-source-localization-algorithm_DOA_estimation", "sha": "9f7e91bce217d69a110441af939cf041c8f26cd9", "save_path": "github-repos/MATLAB/WenzheLiu-Speech-sound-source-localization-algorithm_DOA_estimation", "path": "github-repos/MATLAB/WenzheLiu-Speech-sound-source-localization-algorithm_DOA_estimation/sound-source-localization-algorithm_DOA_estimation-9f7e91bce217d69a110441af939cf041c8f26cd9/ssl_tools/pair_processing/fwDs_spec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5793046192832361}}
{"text": "function [mu,h] = apgarchcore(parameters, data, ar, ma, x, p, q, y, m, z, v, T)\n%{\n-----------------------------------------------------------------------\n PURPOSE:\n Estimation of conditional mean and variance of the \n APGARCH: Asymmetric Power GARCH: Ding, Granger and Engle (1993)\n-----------------------------------------------------------------------\n USAGE:\n [mu,h] = apgarchcore(parameters, data, p, q, m, T)\n\n INPUTS:\n parameters:\tvector of parameters\n data:         (T x 1) vector of data\n ar:        positive scalar integer representing the order of AR\n am:        positive scalar integer representing the order of MA\n x:         (T x N) vector of factors for the mean process\n p:         positive scalar integer representing the order of ARCH\n q:         positive scalar integer representing the order of GARCH\n y:         (T x N) vector of factors for the volatility process, must be positive!\n\n OUTPUTS:\n mu:           conditional mean\n h:            conditional variance\n-----------------------------------------------------------------------\n Author:\n Alexandros Gabrielsen, a.gabrielsen@city.ac.uk\n Date:     10/2010\n Update 1: 08/2011: ARMA-X Support\n-----------------------------------------------------------------------\n%}\n% Verifying that the vector of parameters is a column vector\n[r,c] = size(parameters);\nif c>r\n    parameters = parameters';\n    [r,c] = size(parameters);\nend\n\n% Asymmetric  and Nonlinear coefficients\ndelta = parameters(3+z+p+q+v);\nasym=parameters(4+z+p+q:3+z+2*p+q+v);\n\n% Initial parameters\nmu = [];\nh = [];\nmu(1:m,1) = parameters(1);\nh(1:m,1) = var(data);\n\n% Dimension of factors\nif isscalar(x)\n    xy=zeros(size(data,1),1);    \nelse\n    xy=x;\nend\nif isscalar(y)\n    yy=zeros(size(data,1),1);    \nelse\n    yy=y;\nend\n% Estimation of Conditional Mean and Variance\nfor t = (m+1):T; \n   mu(t,1) = parameters(1:1+z)'*[1; data(t-(1:ar)); data(t-(1:ma))-mu(t-(1:ma),1); xy(t,:)'*ones((isscalar(x) < 1))];\n   h(t,1) = (parameters(2+z:2+z+p+q+v)'*[1; (abs(data(t-(1:p)) - mu(t-(1:p))) - asym(1:p)*(data(t-(1:p)) - mu(t-1))).^delta; (h(t-(1:q))).^delta; yy(t,:)'*ones((isscalar(y) < 1))]).^(1/delta);\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/32882-armax-garch-k-toolbox-estimation-forecasting-simulation-and-value-at-risk-applications/apgarchcore.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5793046103468786}}
{"text": "%SF_LINE_P5 1D Fifth order Lagrange shape functions for lines (P5).\n%\n%   [ VBASE, NLDOF, XLDOF, SFUN ] = SF_LINE_P5( I_EVAL, N_SDIM, N_VERT, I_DOF, XI, AINVJAC, VBASE )\n%   Evaluates conforming fifth order P5 Lagrange shape functions on 1D line elements\n%   with values defined in the nodes and center. XI are Barycentric coordinates.\n%\n%       Input       Value/[Size]           Description\n%       -----------------------------------------------------------------------------------\n%       i_eval      scalar:  1             Evaluate function values\n%                           >1             Evaluate values of derivatives\n%       n_sdim      scalar: 1              Number of space dimensions\n%       n_vert      scalar: 2              Number of vertices per cell\n%       i_dof       scalar: 1-6            Local basis function to evaluate\n%       xi          array [2,1]            Local coordinates of evaluation point\n%       aInvJac     [n,3]                  Inverse of transformation Jacobian\n%       vBase       [n]                    Preallocated output vector\n%                                                                                         .\n%       Output      Value/[Size]           Description\n%       -----------------------------------------------------------------------------------\n%       vBase       [n]                    Evaluated function values\n%       nLDof       [4]                    Number of local degrees of freedom on\n%                                          vertices, edges, faces, and cell interiors\n%       xLDof       [2,n_ldof]             Local coordinates of local dofs\n%       sfun        string                 Function name of called shape function\n%\n%   See also SF_LINE_P1\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/ellib/sf_line_P5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5793046045703182}}
{"text": "function Population = EnvironmentalSelection(Population,R,N)\n% The environmental selection of RPEA\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    %% Calculate the Tchebychev distances\n    Distance = TchebychevDistance(Population.objs,R);\n    \n    %% Environmental selection\n    RemainP = 1 : length(Population);\n    RemainR = 1 : size(R,1);\n    while length(RemainP) > length(Population)-N\n        if isempty(RemainR)\n            RemainR = 1 : size(R,1);\n        end\n        [temp,imin] = min(Distance(RemainP,RemainR),[],1);\n        [~,jmin]    = min(temp);\n        imin        = imin(jmin);\n        RemainP(imin) = [];\n        RemainR(jmin) = [];\n    end\n    Population = Population(setdiff(1:length(Population),RemainP));\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/RPEA/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.5793045943255786}}
{"text": "function X = my_fftn(x)\n\nX = fft(x);\ndd = ndims(x);\nfor id=2:dd\n\tord = 1:dd;\n\tord([1 id]) = [id 1];\n\tx = permute(X, ord);\n\tX = fft(x);\n\tX = ipermute(X, ord);\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/my_fftn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.579239453911081}}
{"text": "x = linspace(-20,2,100);\nw = exp(-0.5*x.^2 -0.5*log(2*pi));\nf = exp(-normcdfln(x));\ng = 1./normcdf(x);\n%g = exp((log(1+exp(0.88+x))./1.5).^2);\n%g = exp(0.5*log(2*pi) +0.5*x.^2 + log(x));\nplot(x, f.*w, x, g.*w)\nlegend('exp(-normcdfln)','1/normcdf');\n\nif 0\n  true = -27.3843074988;\n  [abs(log(normcdf(-7))-true) abs(normcdfln(-7)-true)]\nend\n\nif 0\n  %matnet\n  %imports('c:/Documents and Settings/minka/Depots/Infer/Core/bin/Debug/Core.dll')\n  h = g;\n  for i = 1:length(x)\n    h(i) = 1./cl.MMath.NormalCdf(x(i));\n  end\n  %h = 0.5*(-x + sqrt(x.*x + 8/pi));\n  plot(x, f.*w, x, g.*w, x, h.*w)\n  legend('exp(-normcdfln)','1/normcdf', '1/normcdf2');\n  \n  plot(x, f.*w - h.*w)\nend\n\n% evalf(subs(t=1e-4,subs(x=2*(1-t)/t,erfc(x)*exp(x*x))),100);\n\nif 0\n% test approximations\na = exp(sqrt(2/pi));\nb = 1/log(2/pi*a);\ng = log(a-1 + exp(x.*exp(1./(x.^2 + b))));\ng = log(a-1 + exp(x));\nplot(x, f, x, g)\nplot(x, log(exp(f)+1-a)./x)\nplot(x, 1./log(log(exp(f)+1-a)./x))\nend\n\n% read `/u/tpminka/src/maple/gauss_cdf`; \n% f := 1/sqrt(2*Pi)*exp(-1/2*x^2)/gauss_cdf(-x);\n% g := exp(sqrt(2/Pi))-1+exp(x);\n% plot(f, x=0..50);\n% h := log(exp(f*sqrt(Pi/2)-1)+1);\n% h := log(exp(f - sqrt(2/Pi))+1);\n% h := 1/log(log(exp(f) +1-exp(sqrt(2/Pi)))/x);\n% asympt(h,x);\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/tests/test_normcdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759128, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5792394515208592}}
{"text": "% RENORM_PARENT_2D Renormalization for 2d scattering\n% \n% Usage\n%   Sx_rn = renorm_parent_2d(Sx)\n%\n% Input\n%   Sx (cell): output of 2d scattering\n%\n% Output\n%   Sx_rn (cell): the renormalized 2d scattering \n%\n% Description\n%   This function will renormalize every 2nd order node by its parent\n%   (hence his name renorm_PARENT_2d)\n%\n% See also\n%   SCAT, REMORM_PARENT_3D\n\nfunction Sx_rn = renorm_parent_2d(Sx)\n    \n    Sx_rn = Sx;\n    \n    % a function handle to find the parent node\n    parent = @(p)(find(Sx{2}.meta.j(1,:) == Sx{3}.meta.j(1,p) &...\n        Sx{2}.meta.theta(1,:) == Sx{3}.meta.theta(1,p) & ...\n        Sx{2}.meta.q(1,:) == Sx{3}.meta.q(1,p)));\n    \n    % for each signal in order 2, divide by its ancestor\n    for p = 1:numel(Sx{3}.signal)\n        Sx_rn{3}.signal{p} = Sx_rn{3}.signal{p}./Sx{2}.signal{parent(p)};\n    end\n    \nend\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/scatutils/renorm_parent_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5792394473786577}}
{"text": "function value = sum(SO3F, varargin)\n% Calculates the integral of a SO3FunHarmonic based on\n% \n% $$ v = \\int f(R) dR $$\n% \n% with $vol(SO(3)) = \\int_{SO(3)} 1 dR = 8\\pi^2$.\n% \n% If there is a second argument it sums up along a specified dimension of a \n% vector-valued SO3FunHarmonic.\n%\n% Syntax\n%   value = sum(SO3F)\n%   SO3F = sum(SO3F, d)\n%\n% Input\n%  SO3F - @SO3FunHarmonic\n%  d    - dimension to take the sum value over\n%\n% Output\n%  SO3F  - @SO3FunHarmonic\n%  value - double\n%\n% Description\n%\n% SO3F is a 3x3 SO3Fun\n% sum(SO3F) returns a 3x3 matrix with the integrals of each function\n% sum(SO3F, 1) returns a 1x3 SO3Fun which contains the pointwise sums along the first dimension\n%\n\nif nargin == 1\n  value = 8*pi^2*mean(SO3F,varargin{:});\nelse\n  SO3F.fhat = sum(SO3F.fhat, varargin{1}+1);\n  value = SO3F;\nend\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3FunHarmonic/sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5792394378177711}}
{"text": "function [ imgOut ] = hyperOrthorectify( imgIn, altitude, hpbw )\n%HYPERORTHORECTIFY Orthorectifies areal observed data.\n%   Orthorectifies areal observed data using nearest neighbor interpolation.\n%   \n% Inputs\n%   imgIn       Input image (m x n) or (m x n x p)\n%   altitude    Sensor altitude (meters)\n%   hpbw        Half power beam width (radians).\n% Outputs\n%   imgOut      Orthorectified image.\n\n% Input parameters\nif (ndims(imgIn) == 2)\n    [h, w] = size(imgIn);\n    p = 1;\nelseif (ndims(imgIn) == 3)\n    [h, w, p] = size(imgIn);\nend\n\nradPerPix = hpbw/w;\nx = tan(hpbw/2)*altitude;  % m\ngsd = altitude*radPerPix;  % m\nn = x/gsd;\n\noutImg = zeros(h, floor(n)*2, p);\nfor k=1:p\n    for j=1:h\n        for i=-floor(n):1:floor(n)-1\n            boresiteDistance = gsd*i;\n            theta = atan(boresiteDistance/altitude);\n            imagePix = round(theta / radPerPix);\n            imgOut(j, floor(n)+i+1, k) = imgIn(j, (w/2)+imagePix+1, k);\n        end\n    end\nend\n", "meta": {"author": "isaacgerg", "repo": "matlabHyperspectralToolbox", "sha": "26955b0abb442d06009c220980e974461e419bf8", "save_path": "github-repos/MATLAB/isaacgerg-matlabHyperspectralToolbox", "path": "github-repos/MATLAB/isaacgerg-matlabHyperspectralToolbox/matlabHyperspectralToolbox-26955b0abb442d06009c220980e974461e419bf8/hyperspectralToolbox/hyperOrthorectify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5792365650159007}}
{"text": "% \n% Smooth point-set registration method using neighboring constraints\n% -------------------------------------------------------------------\n% \n% Authors: Gerard Sanrom\u00e0, Ren\u00e9 Alqu\u00e9zar and Francesc Serratosa\n% \n% Contact: gsanorma@gmail.com\n% Date: 15/02/2012\n% \n% Demo of the non-rigid method\n% \n% For the execution of the non-rigid version you will need the 'ctps_gen'\n% and 'ctps_warp_pts' functions from the TPS-RPM implementation by\n% Haili Chui and Anand Rangarajan (\"A new algorithm for non-rigid point\n% matching\",IEEE CVPR 2000) available from:\n% http://www.cise.ufl.edu/~anand/students/chui/rpm/TPS-RPM.zip\n% \n% For the correct execution of this demo you will need the synthetic \n% datasets by Dr. Haili Chui and Prof. Anand Rangarajan, available at:\n% http://www.umiacs.umd.edu/~zhengyf/PointMatchDemo/DataChui.zip\n% \n\nclear variables;\n\nif exist('ctps_gen') ~= 2 || exist('ctps_warp_pts') ~= 2\n    disp('The MATLAB m-files (i.e., functions) \"ctps_gen\" and \"ctps_warp_pts\" are not available');\n    disp('You can get them from the TPS-RPM implementation by Haili Chui and Anand Rangarajan');\n    disp('\"A new algorithm for non-rigid point matching\",IEEE CVPR 2000');\n    disp('http://www.cise.ufl.edu/~anand/students/chui/rpm/TPS-RPM.zip');\n    return;\nend\n\nif exist('DataChui','dir') == 0\n    disp('Fish and Chinese character datasets are not available');\n    disp('You can download them from:')\n    disp('http://www.umiacs.umd.edu/~zhengyf/PointMatchDemo/DataChui.zip');\n    return;\nend\n\n% Type of experiments (uncomment the appropriate one)\nexp_type = 'fish_def';\n% exp_type = 'fish_noise';\n% exp_type = 'fish_outlier';\n% exp_type = 'chinese_def';\n% exp_type = 'chinese_noise';\n% exp_type = 'chinese_outlier';\n\n% Path to the Chui's dataset\npath = 'DataChui';\nfile_pattern = strcat('save_',exp_type,'_');\n\nsample_range = 1:100;\nif ~isempty(strfind(exp_type,'noise'))\n    perturb_range = 1:6;\nelse\n    perturb_range = 1:5;\nend\n\nE = inf(length(perturb_range),length(sample_range));\n\nfor perturb = perturb_range\n    for sample = sample_range\n        \n        disp(['perturb = ',num2str(perturb),' sample = ',num2str(sample)]);\n        \n        % Read sample\n        load(fullfile(path,strcat(file_pattern,num2str(perturb),'_',num2str(sample))),...\n            'x1','y2a');\n        gM = [-x1(:,2) x1(:,1)];\n        gD = [-y2a(:,2) y2a(:,1)];\n        lD = length(gD);\n        lM = length(gM);\n        \n        if ~isempty(strfind(exp_type,'outlier'))\n            vgM = match_chui_outl(gM,gD);\n        else\n            vgM = match_chui(gM,gD);\n        end\n\n        % gm \n        r = gD(1:lM,:) - vgM;\n        E(perturb,sample) = mean(sqrt(diag(r*r')));\n        disp(['ERROR=',num2str(E(perturb,sample))]);\n\n    end\nend\n\nsave(strcat('nonrigid_',exp_type),'E');\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/35179-smooth-point-set-registration-using-neighboring-constraints/smooth_point_reg_neighbor_constraints/demo_nonrigid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.57921955787344}}
{"text": "%SF_SIMP_P1BUB Linear Lagrange shape function for simplices with bubble (P1+).\n%\n%   [ VBASE, NLDOF, XLDOF, SFUN ] = SF_SIMP_P1BUB( I_EVAL, N_SDIM, N_VERT, I_DOF, XI, AINVJAC, VBASE )\n%   Evaluates conforming linear P1 Lagrange shape functions on simplices\n%   an additional with bubble function. XI Barycentric coordinates.\n%\n%       Input       Value/[Size]           Description\n%       -----------------------------------------------------------------------------------\n%       i_eval      scalar:  1             Evaluate function values\n%                           >1             Evaluate values of derivatives\n%       n_sdim      scalar: 1-3            Number of space dimensions\n%       n_vert      scalar: 2-4            Number of vertices per cell\n%       i_dof       scalar: 1-n_ldof       Local basis function to evaluate\n%       xi          [n_sdim+1]             Local coordinates of evaluation point\n%       aInvJac     [n,n_sdim+1*n_sdim]    Inverse of transformation Jacobian\n%       vBase       [n]                    Preallocated output vector\n%                                                                                         .\n%       Output      Value/[Size]           Description\n%       -----------------------------------------------------------------------------------\n%       vBase       [n]                    Evaluated function values\n%       nLDof       [4]                    Number of local degrees of freedom on\n%                                          vertices, edges, faces, and cell interiors\n%       xLDof       [n_sdim,n_ldof]        Local coordinates of local dofs\n%       sfun        string                 Function name of called shape function\n%\n%   See also SF_SIMP_P1\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\n\n\n\n% Evaluation type flag.\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\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\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/ellib/sf_simp_P1bub.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5792092965778929}}
{"text": "function varargout = hikmeans(varargin)\n% VL_HIKMEANS  Hierachical integer K-means\n%   [TREE,ASGN] = VL_HIKMEANS(DATA,K,NLEAVES) applies integer K-menas\n%   recursively to cluster the data DATA, returing a structure TREE\n%   representing the clusters and a vector ASGN with the data to\n%   cluster assignments. The depth of the recursive partition is\n%   computed so that at least NLEAVES are generated.\n%\n%   VL_HIKMEANS() is built on top of VL_IKMEANS() and requires the\n%   data to be of class UINT8.\n%\n%   TREE is a structure representing the hierarchical clusters.  Each\n%   node of the tree is also a structure with fields:\n%\n%   DEPTH::\n%     Depth of the tree (only at the root node)\n%\n%   CENTERS::\n%     K cluster centers\n%\n%   SUB::\n%     Array of K node structures representing subtrees\n%     (this field is missing at leaves).\n%\n%   ASGN is a matrix with one column per datum and height equal to the\n%   depth of the tree. Each column encodes the branch of the tree that\n%   correspond to each datum.\n%\n%   Example::\n%     ASGN(:,7) = [1 5 3] means that the tree as depth equal to 3 and\n%     that the datum X(:,7) corresponds to the branch\n%     ROOT->SUB(1)->SUB(5)->SUB(3).\n%\n%   See also: VL_HIKMEANSPUSH(), VL_HIKMEANSHIST(), VL_IKMEANS(), VL_HELP().\n[varargout{1:nargout}] = vl_hikmeans(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/hikmeans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5792092956525547}}
{"text": "% --------------------------------------------------------------------------- %\n% MarrRevisited - Surface Normal Estimation\n% Copyright (c) 2016 Adobe Systems Incorporated and Carnegie Mellon University. \n% All rights reserved.[see LICENSE for details]\n% -------------------------------------------------------------------------- %\n\n% Written by Aayush Bansal. Please contact ab.nsit@gmail.com\nfunction[nums_e] = eval_pred_sn(cache_dir, cache_list)\n\n\tnum_images = length(cache_list);\n\tfor i = 1:num_images\n\t\n\t\t% load the file from cache\n\t\tdisplay(['Loading image: ', num2str(i, '%06d'),'/',...\n\t\t\t\t\t    num2str(num_images, '%06d')]);\n\n\t\t% CHANGE THE NAME OF THE DATA FILE -- if \n\t\tpred = load([cache_dir, '/', num2str(cache_list(i), '%06d'),...\n\t\t\t\t\t\t\t '.mat'],  'predns');\n\t        gtd = load(['./dataset/NYU/GT_Normals/test/nm_',...\n\t\t\t\t\t num2str(cache_list(i),'%06d') '.mat']);\n\n\t\t%\n\t\tNG = cat(3,gtd.nx,gtd.ny,gtd.nz);\n\t\tNV = gtd.depthValid;\n\t\t%\n\t\tNP = pred.predns;\n\t\t%normalize both to be sure\n\t        NG = bsxfun(@rdivide,NG,sum(NG.^2,3).^0.5);\n                NP = bsxfun(@rdivide,NP,sum(NP.^2,3).^0.5);\n\t\t%compute the dot product, and keep on the valid\n\t\tDP = sum(NG.*NP,3);\n\t\tT = min(1,max(-1,DP));\n\t\tpixels{i} = T(find(NV));\n\tend\n\n\tE = acosd(cat(1,pixels{:}));\n\tnums_e = [mean(E(:)),median(E(:)),mean(E.^2).^0.5,mean(E < 11.25)*100,mean(E < 22.5)*100,mean(E < 30)*100]\n\tdisplay('---------------------------------------');\n\tdisplay(['Mean: ', num2str(mean(E(:)))]);\n\tdisplay(['Median: ', num2str(median(E(:)))]);\n\tdisplay(['RMSE: ', num2str(mean(E.^2).^0.5)]);\n\tdisplay(['11.25: ', num2str(mean(E < 11.25)*100)]);\n\tdisplay(['22.5: ', num2str(mean(E < 22.5)*100)]);\n\tdisplay(['30: ', num2str(mean(E < 30)*100)]);\n\tdisplay(['45: ', num2str(mean(E < 45)*100)]);\n\tdisplay('---------------------------------------');\nend\n", "meta": {"author": "aayushbansal", "repo": "MarrRevisited", "sha": "13ec38f9dcaa3aa88a0f4796f0c40aba8c2543a8", "save_path": "github-repos/MATLAB/aayushbansal-MarrRevisited", "path": "github-repos/MATLAB/aayushbansal-MarrRevisited/MarrRevisited-13ec38f9dcaa3aa88a0f4796f0c40aba8c2543a8/normals/eval/eval_pred_sn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5792092956525546}}
{"text": "\nseed = 1235; \nrng(seed); \n\n[Batch,~,~] = generate_data(5000,[10,10]',[10,10]',0.0,[0,0]',[1,1]',0,1,0,0,0);\n% generate_data(T,Nneurons,Dt,NeuronNoise,SeqNoiseTime,SeqNoiseNeuron,shared,diff,stretch,bin,seed)\n\nL = 250; K = 4;\nfigure(1)\n[W,H,temp,Loadings,Power] = seqNMF(Batch, ...     \n    'K', K, 'L', L, 'lambda',.0005, ...        \n    'showPlot', 1, 'maxiter', 100, 'shift', 1,...\n    'lambdaOrthoW', 0,'lambdaOrthoH',0);\nSimpleWHPlot(W,H,[],0)\nsavedir = 'C:\\Users\\emackev\\Dropbox (MIT)\\SeqNMF\\Figures';\nsaveTitle = 'SharedNeurons'; \npapersize = [8 6];\nset(gcf, 'papersize', papersize, 'paperposition', [0 0 papersize]);%, 'color', 'none')\n    saveas(gcf, fullfile(savedir, [saveTitle '_noshared.pdf'])); \n\n[W,H,temp,Loadings,Power] = seqNMF(Batch, ...     \n    'K', K, 'L', L, 'lambda',.00000, ...        \n    'showPlot', 1, 'maxiter', 100, 'shift', 1,...\n    'lambdaOrthoW', 0,'lambdaOrthoH',0);\nSimpleWHPlot(W,H,[],0)\nsavedir = 'C:\\Users\\emackev\\Dropbox (MIT)\\SeqNMF\\Figures';\nsaveTitle = 'SharedNeurons'; \npapersize = [8 6];\nset(gcf, 'papersize', papersize, 'paperposition', [0 0 papersize]);%, 'color', 'none')\n    saveas(gcf, fullfile(savedir, [saveTitle '_cnmf.pdf'])); \n\n[Batch,~,~] = generate_data(5000,[10,10]',[10,10]',0.0,[0,0]',[1,1]',1,1,0,0,0);\n[W,H,temp,Loadings,Power] = seqNMF(Batch, ...     \n    'K', K, 'L', L, 'lambda',.0005, ...        \n    'showPlot', 1, 'maxiter', 100, 'shift', 1,...\n    'lambdaOrthoW', 0,'lambdaOrthoH',0);\nSimpleWHPlot(W,H,[],0)\nsavedir = 'C:\\Users\\emackev\\Dropbox (MIT)\\SeqNMF\\Figures';\nsaveTitle = 'SharedNeurons'; \npapersize = [8 6];\nset(gcf, 'papersize', papersize, 'paperposition', [0 0 papersize]);%, 'color', 'none')\n    saveas(gcf, fullfile(savedir, [saveTitle '_sharedDiff.pdf'])); \n    \n[Batch,~,~] = generate_data(5000,[10,10]',[10,10]',0.0,[0,0]',[1,1]',1,0,0,0,0);\n[W,H,temp,Loadings,Power] = seqNMF(Batch, ...     \n    'K', K, 'L', L, 'lambda',.0005, ...        \n    'showPlot', 1, 'maxiter', 100, 'shift', 1,...\n    'lambdaOrthoW', 0,'lambdaOrthoH',0);\nSimpleWHPlot(W,H,[],0)\nsavedir = 'C:\\Users\\emackev\\Dropbox (MIT)\\SeqNMF\\Figures';\nsaveTitle = 'SharedNeurons'; \npapersize = [8 6];\nset(gcf, 'papersize', papersize, 'paperposition', [0 0 papersize]);%, 'color', 'none')\n    saveas(gcf, fullfile(savedir, [saveTitle '_sharedSame.pdf'])); \n%% Example parts-based vs events-based factorizations (W or H soft orthogonality)\n\n% change these parameters to switch between parts-based and events-based\nlambdaOrthoH = 0; % favor events-based (these can take any value, don't need to be zero and one)\nlambdaOrthoW = 1; % favor parts-based\n\n% rng(236); % fixed rng seed for reproduceability\nX = trainNEURAL;\nK = 3;\nL = 2/3; % units of seconds\nLneural = ceil(L*VIDEOfs);\nLsong = ceil(L*SONGfs);\nshg\ndisplay('For parts-based, set lambdaOrthoW=1 and lambdaOrthoH=0; for events-based, vice versa')\n[W, H, ~,loadings,power]= seqNMF(X,'K',K,'L',Lneural,...\n            'lambda', .00, 'maxiter', 100, 'showPlot', 1,...\n            'lambdaOrthoH', lambdaOrthoH, 'lambdaOrthoW', lambdaOrthoW); \n        \np = .05; % desired p value for factors\n\ndisplay('Testing significance of factors on held-out data')\n[pvals,is_significant] = test_significance(testNEURAL,W,p);\n\nW = W(:,is_significant,:); \nH = H(is_significant,:); \n\n% plot, sorting neurons by latency within each factor\n[max_factor, L_sort, max_sort, hybrid] = helper.ClusterByFactor(W(:,:,:),1);\nindSort = hybrid(:,3);\ntstart = 180; % plot data starting at this timebin\nfigure; WHPlot(W(indSort,:,:),H(:,tstart:end), X(indSort,tstart:end), 0,trainSONG(:,floor(tstart*SONGfs/VIDEOfs):end),0)\ntitle(['lambdaOrthoW=' num2str(lambdaOrthoW) ', lambdaOrthoH=' num2str(lambdaOrthoH)])\n\n\n% savedir = 'C:\\Users\\emackev\\Dropbox (MIT)\\SeqNMF\\Figures';\n% saveTitle = 'PartsBasedOrthW1'; \n% papersize = [8 6];\n% set(gcf, 'papersize', papersize, 'paperposition', [0 0 papersize]);%, 'color', 'none')\n%     saveas(gcf, fullfile(savedir, [saveTitle '_raw.pdf'])); \n\n\n\n% figure; WHPlot(W(indSort,:,:),H(:,tstart:end), ...\n%     helper.reconstruct(W(indSort,:,:),H(:,tstart:end)),...\n%     0,trainSONG(:,floor(tstart*SONGfs/VIDEOfs):end),0)\n% title('SeqNMF reconstruction')\n\n% set(gcf, 'papersize', papersize, 'paperposition', [0 0 papersize]);%, 'color', 'none')\n%     saveas(gcf, fullfile(savedir, [saveTitle '_reconstruction.pdf'])); ", "meta": {"author": "FeeLab", "repo": "seqNMF", "sha": "229b9b19ac3a34b8378945ec7f9e331e004bb777", "save_path": "github-repos/MATLAB/FeeLab-seqNMF", "path": "github-repos/MATLAB/FeeLab-seqNMF/seqNMF-229b9b19ac3a34b8378945ec7f9e331e004bb777/misc_elm/SharedNeuronsExample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896955, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5792092874875936}}
{"text": "function test_ft_plot_mesh\n\n% MEM 2gb\n% WALLTIME 00:15:00\n% DEPENDENCY ft_plot_mesh\n\n%% the first is a simple triangluar mesh\n\nbnd.pos = randn(20,3);\nbnd.tri = delaunay(bnd.pos(:,1:2));\n\nfigure\nft_plot_mesh(bnd);\n\n%% the following was made by Lilla Magyari in 2013 and pertains to FEM meshes\n\n% create an example segmentation\nexample.dim = [91 104 111]; % slightly different numbers\nexample.transform = eye(4);\nexample.coordsys = 'ctf';\nexample.unit = 'mm';\nexample.seg = zeros(example.dim);\n\n% adjusting transformation matrix: center of the head-coordinates [0 0 0] should\n% be the center of volume\n\n% center of volume in voxel coordinates\nx = round(example.dim(1)/2);\ny = round(example.dim(2)/2);\nz = round(example.dim(3)/2);\n\nx = round(x);\ny = round(y);\nz = round(z);\n\norigin = [x y z];\n\nexample.transform(1:4,4) = [-origin(:); 1]; % head-coordinate [0 0 0] is in the center of\n% the volume (x y z in voxel-coordinates)\n\n% compute position for each voxel in voxelspace and in headspace\n\n[X, Y, Z] = ndgrid(1:example.dim(1), 1:example.dim(2), 1:example.dim(3));\nvoxelpos = [X(:) Y(:) Z(:)];\nheadpos = ft_warp_apply(example.transform, voxelpos);\n\n% create 3 spheres\n\nradius1 = 40;\nradius2 = 30;\nradius3 = 20;\n\nfor i = 1:size(headpos,1)\n  % from small to large\n  if norm(headpos(i,:))<radius3\n    example.seg(i) = 3;\n  elseif norm(headpos(i,:))<radius2\n    example.seg(i) = 2;\n  elseif norm(headpos(i,:))<radius1\n    example.seg(i) = 1;\n  end\nend\n\n\n% convert it to probabilistic\nseg = ft_datatype_segmentation(example,'segmentationstyle','probabilistic');\n\n% create smaller segmentation\n\nexample.dim = [10 11 9]; % slightly different numbers\nexample.transform = eye(4);\nexample.coordsys = 'ctf';\nexample.unit = 'mm';\nexample.seg = zeros(example.dim);\n\n% adjusting transformation matrix: center of the head-coordinates [0 0 0] should\n% be the center of volume\n\n% center of volume in voxel coordinates\nx = round(example.dim(1)/2);\ny = round(example.dim(2)/2);\nz = round(example.dim(3)/2);\n\nx = round(x);\ny = round(y);\nz = round(z);\n\norigin = [x y z];\n\nexample.transform(1:4,4) = [-origin(:); 1]; % head-coordinate [0 0 0] is in the center of\n% the volume (x y z in voxel-coordinates)\n\n% compute position for each voxel in voxelspace and in headspace\n\n[X, Y, Z] = ndgrid(1:example.dim(1), 1:example.dim(2), 1:example.dim(3));\nvoxelpos = [X(:) Y(:) Z(:)];\nheadpos = ft_warp_apply(example.transform, voxelpos);\n\n% create 3 spheres\n\nradius1 = 4;\nradius2 = 3;\nradius3 = 2;\n\nfor i = 1:size(headpos,1)\n  % from small to large\n  if norm(headpos(i,:))<radius3\n    example.seg(i) = 3;\n  elseif norm(headpos(i,:))<radius2\n    example.seg(i) = 2;\n  elseif norm(headpos(i,:))<radius1\n    example.seg(i) = 1;\n  end\nend\n\n% convert it to probabilistic\nseg_small = ft_datatype_segmentation(example,'segmentationstyle','probabilistic');\n\n%% create mesh\ncfg = [];\ncfg.method = 'hexahedral';\n%cfg.tissue =\nmesh = ft_prepare_mesh(cfg,seg);\n\n% 1 cube mesh\nmesh0.pos = mesh.pos;\nmesh0.hex = mesh.hex(1,:);\nmesh0.tissue = mesh.tissue(1,:);\nmesh0.tissuelabel = mesh.tissuelabel;\nmesh0.unit = mesh.unit;\n\n% few hundreds cube mesh\n\ncfg = [];\ncfg.method = 'hexahedral';\n%cfg.tissue =\nmesh2 = ft_prepare_mesh(cfg,seg_small);\n\n%% plot mesh\n\n% larger mesh\nfigure; ft_plot_mesh(mesh,'surfaceonly','yes');\n% smaller mesh\nfigure; ft_plot_mesh(mesh2,'surfaceonly','yes');\n% smallest mesh\nfigure; ft_plot_mesh(mesh0,'surfaceonly','yes');\n\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_ft_plot_mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5792092853828321}}
{"text": "function resized_patch = sample_patch(im, pos, sample_sz, output_sz, gparams)\n\nif nargin < 4\n    output_sz = [];\nend\nif nargin < 5 || ~isfield(gparams, 'use_mexResize')\n    gparams.use_mexResize = false;\nend\n\n% Pos should be integer when input, but floor in just in case.\npos = floor(pos);\n\n% Downsample factor\nresize_factor = min(sample_sz ./ output_sz);\ndf = max(floor(resize_factor - 0.1), 1);\nif df > 1\n    % pos = 1 + of + df * (npos - 1)\n    \n    % compute offset and new center position\n    os = mod(pos - 1, df);\n    pos = (pos - 1 - os) / df + 1;\n    \n    % new sample size\n    sample_sz = sample_sz / df;\n    \n    % donwsample image\n    im = im(1+os(1):df:end, 1+os(2):df:end, :);\nend\n\n% make sure the size is not too small and round it\nsample_sz = max(round(sample_sz), 2);\n\nxs = pos(2) + (1:sample_sz(2)) - floor((sample_sz(2)+1)/2);\nys = pos(1) + (1:sample_sz(1)) - floor((sample_sz(1)+1)/2);\n\n%check for out-of-bounds coordinates, and set them to the values at\n%the borders\nxs(xs < 1) = 1;\nys(ys < 1) = 1;\nxs(xs > size(im,2)) = size(im,2);\nys(ys > size(im,1)) = size(im,1);\n\n%extract image\nim_patch = im(ys, xs, :);\n\nif isempty(output_sz) || isequal(sample_sz(:), output_sz(:))\n    resized_patch = im_patch;\nelse\n    if gparams.use_mexResize\n        resized_patch = mexResize(im_patch, output_sz, 'linear');\n    else\n        resized_patch = imresize(im_patch, output_sz, 'bilinear', 'Antialiasing',false);\n    end\nend\n\nend\n\n", "meta": {"author": "martin-danelljan", "repo": "ECO", "sha": "27e8ae565cd63ec14bafcaad8b5b993bec8f3e69", "save_path": "github-repos/MATLAB/martin-danelljan-ECO", "path": "github-repos/MATLAB/martin-danelljan-ECO/ECO-27e8ae565cd63ec14bafcaad8b5b993bec8f3e69/feature_extraction/sample_patch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5792092835321548}}
{"text": "function [X,y,isContinuous] = designMatrix(tbl,allTerms,responseVar,varargin)\n% Extract a design matix from a linear model.\n%  Dummy coded designs for categorical variables and zero-sum covariates for\n%  contiunuous variables are returned as X\n% INPUT\n% tbl =  A table\n% allTerms = A cell array of variable names to include in the\n% design matrix ( e.g. {'ori','freq','ori:freq'} for two mains and an interaction)\n% Parm/Value\n% ZeroSumConstraint -  Toggle to apply the zero sum constraint to\n%                   each categorical factor (This equates the marginal prior across terms in the\n%                           factor; see Rouder et al) [true]\n% treatAsRandom  - A char or a cell array of chars with factors that should be\n%               treated as random (i.e. not fixed) effects.\n%               [{}].\n% forceCategorical - Logical to force each term to be treated as a\n% categorical variable (useful for grouping variables like subject ID which\n% may look continuous...)\n% OUTPUT\n% X = The complete design matrix. Cell array with one element per term.\n% y = The response data\n% isContinuous = Logical indicating which columns are continuous co-variates.\n%\n% BK - 2019.\n\np = inputParser;\np.addParameter('zeroSumConstraint',true,@islogical);\np.addParameter('treatAsRandom',{},@(x) ischar(x) || iscell(x));\np.addParameter('forceCategorical',false,@islogical);\np.parse(varargin{:});\ntreatAsRandom =p.Results.treatAsRandom;\nif ischar(treatAsRandom);treatAsRandom = {treatAsRandom};end\n\nnrAllTerms =numel(allTerms);\nX = cell(1,nrAllTerms);\nN = height(tbl);\n\n%Options for modelutils.designmatrix . Its internal alg determines which\n%vars are categorical quite well. But use categorical() in the data table\n%to be sure (or chars/strings).\nisCategorical = bf.internal.isCategorical(tbl);\nif p.Results.forceCategorical\n    isCategorical = true(size(isCategorical));\nend\ncateoricalOpts = {'model','linear','intercept',false,'DummyVarCoding','full','responseVar',responseVar,'CategoricalVars',isCategorical};\nisContinuous = false(1,nrAllTerms);\nfor i=1:nrAllTerms\n    if any(allTerms{i}==':')\n        % An interaction term.\n       % names = strsplit(allTerms{i},':')\n        aName =extractBefore(allTerms{i},':');\n        bName = extractAfter(allTerms{i},':');\n        aCategorical  = bf.internal.isCategorical(tbl,aName);\n        bCategorical = bf.internal.isCategorical(tbl,bName);  \n        bothCategorical = aCategorical &&  bCategorical;\n        bothContinuous = ~aCategorical && ~bCategorical;\n        if bothCategorical || p.Results.forceCategorical\n            thisA = classreg.regr.modelutils.designmatrix(tbl,'PredictorVars',aName,cateoricalOpts{:});\n            if ~ismember(aName,treatAsRandom) && p.Results.zeroSumConstraint \n                thisA = bf.internal.zeroSumConstraint(thisA);\n            end\n            thisB = classreg.regr.modelutils.designmatrix(tbl,'PredictorVars',bName,cateoricalOpts{:});\n            if ~ismember(bName,treatAsRandom) && p.Results.zeroSumConstraint\n                thisB = bf.internal.zeroSumConstraint(thisB);\n            end\n            thisX = bf.internal.interaction(thisA,thisB); \n        elseif bothContinuous\n            thisX =  tbl.(aName).*tbl.(bName);\n            thisX = thisX - mean(thisX);\n            isContinuous(i) = true;\n        else\n            % Interaction between a categorical and a continuous covariate\n            if aCategorical\n                thisA = classreg.regr.modelutils.designmatrix(tbl,'PredictorVars',aName,'intercept',false,'model','linear','responseVar',tbl.(responseVar),'DummyVarCoding','full');\n                if ismember(bName,allTerms)\n                    % B is already included as a main effect, have to\n                    % remove one level from A to avoid colinearity,\n                     thisA = bf.internal.zeroSumConstraint(thisA);\n%                    thisA = thisA(:,2:end); % Remove first category\n                end\n            else\n                thisA = tbl.(aName);\n            end\n            if bCategorical\n                thisB = classreg.regr.modelutils.designmatrix(tbl,'PredictorVars',bName,'intercept',false,'model','linear','responseVar',tbl.(responseVar),'DummyVarCoding','full');\n                if ismember(aName,allTerms)\n                    % A is already included as a main effect, have to\n                    % remove one level from B to avoid colinearity,\n                    thisB = bf.internal.zeroSumConstraint(thisB);\n                    %thisB = thisB(:,2:end); % Remove first category\n                end\n            else\n                thisB = tbl.(bName);\n            end            \n            thisX  =  thisA.*thisB;\n            thisX  = thisX-mean(thisX);\n            isContinuous(i) = true;\n        end        \n    else\n        % A main term\n        if  bf.internal.isCategorical(tbl,allTerms{i}) || p.Results.forceCategorical        \n            thisX = classreg.regr.modelutils.designmatrix(tbl,'PredictorVars',allTerms{i},cateoricalOpts{:});\n            % Sum-to-zero contrasts that equates marginal priors across levels.\n            if ~ismember(allTerms{i},treatAsRandom) && p.Results.zeroSumConstraint \n                thisX = bf.internal.zeroSumConstraint(thisX);\n            end\n        else %Continuous\n             thisX =  tbl.(allTerms{i});\n             thisX  = thisX-mean(thisX);\n            isContinuous(i)= true;\n        end\n        \n    end\n    X{i} =thisX; % Store for later use\nend\n\nif nargout>1\n    y= tbl.(responseVar);\nend\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/designMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5792092783972939}}
{"text": "function [ feature_image ] = get_fhog(im, fparam, gparam )\n%extract fhog features using piotrs toolbox. Currently takes no parameters\n%except hog-cell-size\nif ~isfield(fparam, 'nOrients')\n    fparam.nOrients = 9;\nend\n[im_height, im_width,~, num_images] = size(im);\nfeature_image = zeros(floor(im_height/gparam.cell_size), floor(im_width/gparam.cell_size), fparam.nDim, num_images, 'single');\nfor k = 1:num_images\n    hog_image = fhog(single(im(:,:,:,k)), gparam.cell_size, fparam.nOrients);\n    %the last dimension is all 0 so we can discard it\n    feature_image(:,:,:,k) = hog_image(:,:,1:end-1);\nend\nend", "meta": {"author": "vision4robotics", "repo": "AutoTrack", "sha": "e9b34ae09702f152407a7bf7cce5e3ed75bf2797", "save_path": "github-repos/MATLAB/vision4robotics-AutoTrack", "path": "github-repos/MATLAB/vision4robotics-AutoTrack/AutoTrack-e9b34ae09702f152407a7bf7cce5e3ed75bf2797/feature/get_fhog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5792092681275712}}
{"text": "function [beta_gibbs,sigma_gibbs,beta_mean,sigma_mean,lambda_posterior]=panel4gibbs(N,n,h,T,k,q,Yi,Xi,s0,omegab,v0,It,Bu,pick,pickf)\n\n\n\n\n\n% compute first  preliminary elements\n% compute sbar\nsbar=h+s0;\n% compute the inverse of omegab\ninvomegab=diag(1./diag(omegab));\n% initiate the Gibbs sampler\n% initiate the counting of iterations\ncount=1;\npickcount=1;\n% initiate the record matrices\nbeta_gibbs=zeros(q,It-Bu,N);\nsigma_gibbs=zeros(n^2,It-Bu,N);\nbeta_mean=zeros(q,It-Bu);\nsigma_mean=zeros(n^2,It-Bu);\nlambda_posterior=zeros((It-Bu),1);\n\n% step 1: compute initial values\n% initial value for beta (use OLS values)\nfor ii=1:N\nbeta(:,ii)=bear.vec((Xi(:,:,ii)'*Xi(:,:,ii))\\(Xi(:,:,ii)'*Yi(:,:,ii)));\nend\n% initial value for b\nb=(1/N)*sum(beta,2);\n% initial value for lambda1\nlambda1=0.01;\nsigmab=lambda1*omegab;\n% initial value for sigma (use OLS values)\nfor ii=1:N\neps=Yi(:,:,ii)-Xi(:,:,ii)*reshape(beta(:,ii),k,n);\nsigma(:,:,ii)=(1/(T-k-1))*eps'*eps;\nend\n\n\nhbar = bear.parfor_progressbar(It-Bu,'Progress of Panel BVAR Gibbs Sampler');  %create the progress bar\n\n\n% run the Gibbs sampler\nwhile count<=It\n\n% step 2: obtain b\n% first compute betam, the mean value of the betas over all units\nbetam=(1/N)*sum(beta,2);\n% draw b from a multivariate normal N(betam,(1/N)*sigmab))\nb=betam+chol(bear.nspd((1/N)*sigmab),'lower')*mvnrnd(zeros(q,1),eye(q))';\n\n\n% step 3: obtain sigmab\n% compute first vbar\nfor ii=1:N\ntemp(1,ii)=(beta(:,ii)-b)'*invomegab*(beta(:,ii)-b);\nend\nvbar=v0+sum(temp,2);\n% compute lambda1\nlambda1=bear.igrandn(sbar/2,vbar/2);\n% recover sigmab\nsigmab=lambda1*omegab;\n\n\n% step 4: draw the series of betas\n% first obtain the inverse of sigmab\ninvsigmab=diag(1./diag(sigmab));\n% then loop over units\nfor ii=1:N\n% take the choleski factor of sigma of unit ii, inverse it, and obtain from it the inverse of the original sigma\nC=bear.trns(chol(bear.nspd(sigma(:,:,ii)),'Lower'));\ninvC=C\\speye(n);\ninvsigma=invC*invC';\n% obtain omegabar\ninvomegabar=kron(invsigma,Xi(:,:,ii)'*Xi(:,:,ii))+invsigmab;\n% invert\nC=bear.trns(chol(bear.nspd(invomegabar),'Lower'));\ninvC=C\\speye(q);\nomegabar=invC*invC';\n% obtain betabar\nbetabar=omegabar*(kron(invsigma,Xi(:,:,ii)')*bear.vec(Yi(:,:,ii))+invsigmab*b);\n% draw beta\nbeta(:,ii)=betabar+chol(bear.nspd(omegabar),'lower')*mvnrnd(zeros(q,1),eye(q))';\nend\n\n\n% step 5: draw the series of sigmas\n% loop over units\nfor ii=1:N\n% compute Stilde\nStilde=(Yi(:,:,ii)-Xi(:,:,ii)*reshape(beta(:,ii),k,n))'*(Yi(:,:,ii)-Xi(:,:,ii)*reshape(beta(:,ii),k,n));\n% draw sigma\nsigma(:,:,ii)=bear.iwdraw(Stilde,T);\nend\n\n\n   % record phase\n   % if the burn-in sample phase is not yet over\n   if count<=Bu\n   % simply add 1 to the iteration count\n   count=count+1;\n   % on the other hand, if the burn-in sample phase is over\n   elseif count>Bu\n   % adding one iteration to the count will depend on wether post-burn selection applies\n      % if there is no post burn selection\n      if pick==0\n      % record the draw\n         % loop over units\n         for ii=1:N\n         beta_gibbs(:,count-Bu,ii)=beta(:,ii);\n         sigma_gibbs(:,count-Bu,ii)=bear.vec(sigma(:,:,ii));\n         end\n      % and add one to the count\n      count=count+1;\n      % if there is post burn selection, only one draw over 'fpick' draws will be retained\n      elseif pick==1\n         % if the iteration does not correspond to fpick, don't record the results, don't increase the regular count, but do increase pickcount by 1\n         if pickcount~=pickf\n         pickcount=pickcount+1;\n         % on the other hand, if the iteration does correspond to fpick\n         elseif pickcount==pickf\n         % do record the results\n            % loop over units\n            beta_mean(:,count-Bu)=b;\n            sigma_mean(:,count-Bu)=bear.vec(mean(sigma,3));\n            lambda_posterior(count-Bu)=lambda1;\n            for ii=1:N\n            beta_gibbs(:,count-Bu,ii)=beta(:,ii);\n            sigma_gibbs(:,count-Bu,ii)=bear.vec(sigma(:,:,ii));\n            end\n         % then increase the regular count by 1 and re-initialise pickcount\n         count=count+1;\n         pickcount=1;\n         end\n      end\n   end\n   \n   hbar.iterate(1);   % update progress by one iteration\n\nend\n\nclose(hbar);   %close progress bar\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/panel4gibbs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5789526777906505}}
{"text": "function sensor = sensorfield(x, y)\n    xc = 60; yc = 90;\n    sensor = 200./((x-xc).^2 + (y-yc).^2 + 200);\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/simulink/sensorfield.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.5789526758377617}}
{"text": "function h=m_streamline(long,lat,u,v,varargin)\n% M_STREAMLINE Makes a quiverplot on a map (QUIVER-style)\n%    M_STREAMLINE(LONG,LAT,U,V) draws well-spaced streamlines (with direction \n%    arrows) with components (U,V) at the points (LONG,LAT) on the currently \n%    defined map.The arrays LONG and LAT, which define the coordinates for U and \n%    V, must be monotonic, but do not need to be uniformly spaced. The \n%    matrices LONG,LAT,U,V must all be the same size. U and V contain the \n%    eastward and northward components of velocity (in m/s or equivalent, NOT\n%    degrees lat/long  per sec or equivalent). Arrow scaling is automatic.\n% \n%   Note - this is basically a call to STREAMSLICE, which has some limitations and\n%   cannot be used for ALL projections. In particular, STREAMSLICE requires that\n%\n%            [X,Y]=m_ll2xy(LONG,LAT,'clip','point')\n%\n%   returns X/Y matrices that themselves must be monotonic and plaid (as if produced\n%   by MESHGRID). This means that a) none of the points are from outside the map\n%   boundaries (since the M_LL2XY call will turn them into NaN), and b) you are\n%   probably limited to cylindrical projections (miller, mercator, equidistant \n%   cylindrical). \n%\n%   M_STREAMLINE(...,density) modifies the automatic spacing of the streamlines. \n%   Density must be greater than 0. The default value is 1; higher values \n%   produce  more streamlines on each plane. For example, 2 produces \n%   approximately twice as many streamlines, while 0.5 produces approximately \n%   half as many.\n% \n%   M_STREAMLINE(...,'arrowsmode') determines if direction arrows are present \n%   or not. arrowmode can be:\n% \n%   arrows   - Draw direction arrows on the streamlines (default).\n%   noarrows - Do not draw direction arrows.\n% \n%   M_STREAMLINE(...,'method') specifies the interpolation method to use. \n%   method can be\n% \n%   linear   - Linear interpolation (default)\n%   cubic    - Cubic interpolation\n%   nearest  - Nearest-neighbor interpolation\n%   See interp3 for more information on interpolation methods.\n% \n%   M_STREAMLINE(axes_handle,...) plots into the axes object with the handle \n%   axes_handle instead of into the current axes object (gca).\n% \n%   h = M_STREAMLINE(...) returns a vector of handles to the line objects \n%   created.\n%\n%   [vertices arrowvertices] = M_STREAMLINE(...) returns two cell arrays of \n%   vertices  for drawing the streamlines and the arrows. You can pass these \n%   values to any of the streamline drawing functions (streamline, streamribbon, \n%   streamtube).\n% \n\n% Shi Weiheng (tfoterye@gmail.com) 29/Jun/17\n%\n% Based on m_quiver written by Prof Rich Pawlowicz.\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%  Nov/2017 - cleaned up comments.\n\nglobal MAP_PROJECTION MAP_VAR_LIST\n\n% Have to have initialized a map first\n\nif isempty(MAP_PROJECTION)\n  disp('No Map Projection initialized - call M_PROJ first!');\n  return;\nend\n\n\n\n[X,Y]=m_ll2xy(long,lat,'clip','point');\n\nif any(isnan(X(:)))\n  error(['M_Map : ' mfilename ' : InvalidInputs - input data includes points outside the map area']);\nend\n  \n\n[XN ,YN ]=m_ll2xy([long(:) long(:)]',[lat(:) lat(:)+.001]','clip','off');\n[XE ,YE ]=m_ll2xy([long(:) long(:)+(.001)./cos(lat(:)*pi/180)]',[lat(:) lat(:)]','clip','off');\nmU=u.*reshape(diff(XE),size(lat))*1000 + v.*reshape(diff(XN),size(lat))*1000;\nmV=u.*reshape(diff(YE),size(lat))*1000 + v.*reshape(diff(YN),size(lat))*1000;\n\nh=streamslice(X,Y,mU,mV,varargin{:});\nset(h,'tag','m_streamline');\n\nif nargout==0\n clear h\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/thirdParty/m_map/m_streamline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.5789502682647766}}
{"text": "function K = covADD(cov, hyp, x, z, i)\n\n% Additive covariance function using a 1d base covariance function \n% cov(x^p,x^q;hyp) with individual hyperparameters hyp.\n%\n% k(x^p,x^q) = \\sum_{r \\in R} sf_r \\sum_{|I|=r}\n%                 \\prod_{i \\in I} cov(x^p_i,x^q_i;hyp_i)\n%\n% hyp = [ hyp_1\n%         hyp_2\n%          ...\n%         hyp_D \n%         log(sf_R(1))\n%          ...\n%         log(sf_R(end)) ]\n%\n% where hyp_d are the parameters of the 1d covariance function which are shared\n% over the different values of R(1) to R(end).\n%\n% Please see the paper Additive Gaussian Processes by Duvenaud, Nickisch and \n% Rasmussen, NIPS, 2011 for details.\n%\n% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2010-09-10.\n%\n% See also COVFUNCTIONS.M.\n\nR = cov{1};\nnh = eval(feval(cov{2}));           % number of hypers per individual covariance\nnr = numel(R);                      % number of different degrees of interaction\nif nargin<3                                  % report number of hyper parameters\n  K = ['D*', int2str(nh), '+', int2str(nr)];\n  return\nend\nif nargin<4, z = []; end                                   % make sure, z exists\nxeqz = isempty(z); dg = strcmp(z,'diag');                       % determine mode\n\n[n,D] = size(x);                                                % dimensionality\nsf2 = exp( 2*hyp(D*nh+(1:nr)) );        % signal variances of individual degrees\n\nKd = Kdim(cov{2},hyp,x,z);                % evaluate dimensionwise covariances K\nif nargin<5                                                        % covariances\n  EE = elsympol(Kd,max(R));               % Rth elementary symmetric polynomials\n  K = 0; for ii=1:nr, K = K + sf2(ii)*EE(:,:,R(ii)+1); end    % sf2 weighted sum\nelse                                                               % derivatives\n  if i <= D*nh                       % individual covariance function parameters\n    j = fix(1+(i-1)/nh);              % j is the dimension of the hyperparameter\n    if dg, zj='diag'; else if xeqz, zj=[]; else zj=z(:,j); end, end\n    dKj = feval(cov{2},hyp(nh*(j-1)+(1:nh)),x(:,j),zj,i-(j-1)*nh);  % other dK=0\n    % the final derivative is a sum of multilinear terms, so if only one term\n    % depends on the hyperparameter under consideration, we can factorise it \n    % out and compute the sum with one degree less\n    E = elsympol(Kd(:,:,[1:j-1,j+1:D]),max(R)-1);  %  R-1th elementary sym polyn\n    K = 0; for ii=1:nr, K = K + sf2(ii)*E(:,:,R(ii)); end     % sf2 weighted sum\n    K = dKj.*K;\n  elseif i <= D*nh+nr\n    EE = elsympol(Kd,max(R));             % Rth elementary symmetric polynomials\n    j = i-D*nh;\n    K = 2*sf2(j)*EE(:,:,R(j)+1);                  % rest of the sf2 weighted sum\n  else\n    error('Unknown hyperparameter')\n  end\nend\n\n% evaluate dimensionwise covariances K\nfunction K = Kdim(cov,hyp,x,z)\n  [n,D] = size(x);                                              % dimensionality\n  nh = eval(feval(cov));            % number of hypers per individual covariance\n  if nargin<4, z = []; end                                 % make sure, z exists\n  xeqz = numel(z)==0; dg = strcmp(z,'diag') && numel(z)>0;      % determine mode\n  \n  if dg                                                        % allocate memory\n    K = zeros(n,1,D);\n  else\n    if xeqz, K = zeros(n,n,D); else K = zeros(n,size(z,1),D); end\n  end\n\n  for d=1:D\n    hyp_d = hyp(nh*(d-1)+(1:nh));                 % hyperparamter of dimension d\n    if dg\n      K(:,:,d) = feval(cov,hyp_d,x(:,d),'diag');\n    else\n      if xeqz\n        K(:,:,d) = feval(cov,hyp_d,x(:,d));\n      else\n        K(:,:,d) = feval(cov,hyp_d,x(:,d),z(:,d));\n      end\n    end\n  end", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/gpml/cov/covADD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.5789502585783803}}
{"text": "function [ errors ] = test_sparsify(  )\n    gsp_reset_seed(0);\n\nerrors = 0;\nerrors = errors + test1();\n\nerrors = errors + test2();\n\nend\n\nfunction [ errors ] = test1( )\n\nerrors = 0;\ntry\n    epsilon = 0.4;\n    param.distribute = 1;\n    param.Nc = 20;\n    G = gsp_sensor(256,param);\n    G2 = gsp_graph_sparsify(G,epsilon);\n    figure(100);\n    gsp_plot_graph(G);\n    title('Original graph')\n    figure(101);\n    gsp_plot_graph(G2);\n    title('Sparsified graph')\n    close(100);\n    close(101);\n   fprintf('SPARSIFY: test 1 ok\\n');\ncatch\n    errors = errors +1;\n    warning('SPARSIFY: test 1 error')\nend\n\nend\n\n\nfunction [ errors ] = test2( )\n\nerrors = 0;\n    N = 100;\n    epsilon = 0.6;\n    G = gsp_sensor(N);\n    gsp_reset_seed(0);\n    G2 = gsp_graph_sparsify(G,epsilon);\n    gsp_reset_seed(0);\n    L = gsp_graph_sparsify_old(G.L,epsilon);\n\nif sum(sum(abs(G2.L-L)))<1e-10\n    \n   fprintf('SPARSIFY: test  ok\\n');\nelse\n    errors = errors+1;\n    badness = sum(sum(abs(G2.L-L)))\n    warning('SPARSIFY: test 2 error')\nend\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/test_gsptoolbox/test_sparsify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5789227868904143}}
{"text": "function plotQuadCon(Q,l,rl,ru,data)\n%PLOTQUADCON Plot Quadratic Constraints on the current figure\n%   plotQuadCon(Q,l,r)\n\n%   Copyright (C) 2013 Jonathan Currie (IPL)\n\nxl = data.xl; yl = data.yl;\n\nhold on;\n\n%Colour\ndkg = [0.2 0.2 0.2];\n\n%Determine number of quad constraints\nif(iscell(Q))\n    no = length(Q);\nelse\n    no = 1;\nend\n%>= 2014b requires more points...\nif(~verLessThan('matlab','8.4'))\n    nmul = 2;\nelse\n    nmul = 1;\nend\n\n%Generate Constraint Surface Points\n[x1,x2] = meshgrid(linspace(xl(1),xl(2),data.npts*nmul),linspace(yl(1),yl(2),data.npts*nmul));\n\n%For each quadratic constraint, plot\nfor i = 1:no\n    %Get Constraint Variables\n    if(iscell(Q))\n        nQ = Q{i}; nl = l(:,i); nrl = rl(i); nru = ru(i);\n    else\n        nQ = Q; nl = l; nrl = rl; nru = ru;\n    end  \n    %Form Constraint Function\n    if(data.ndec==1)\n        con = @(x) x(1)*nQ*x(1) + nl*x(1);\n    else\n        con = @(x) x.'*nQ*x + nl.'*x;\n    end\n    %Plot Each Quad Con as General Nonlinear Constraint\n    plotNLCon(con,[],nrl,nru,x1,x2,dkg,data);    \nend\nhold off;\n\n\n\n%OLD CODE\n% %Plot Quadratic Inequality Constraints (Inefficient.. need to solve the quadratic)\n% [x1,x2] = meshgrid(linspace(xl(1),xl(2),npts),linspace(yl(1),yl(2),npts));\n% nox = size(x1);\n% noy = size(x2);\n% obj = zeros(nox(1),noy(2));\n% if(iscell(Q))\n%     no = length(Q);\n% else\n%     no = 1;\n% end\n% for i = 1:no\n%     %get vars\n%     if(iscell(Q))\n%         nQ = Q{i}; nl = l(:,i); nrl = rl(i); nru = ru(i);\n%     else\n%         nQ = Q; nl = l; nrl = rl; nru = ru;\n%     end    \n%     eq = false; sense = 'L';\n%     % check for double constraint or equality\n%     if(~isinf(nrl) && ~isinf(nru))\n%         if(nrl == nru)\n%             nr = nru;\n%             eq = true;\n%         else\n%             nr = [nrl nru];\n%             sense = 'GL';\n%         end\n%     elseif(~isinf(nrl))\n%         nr = nrl;\n%     else\n%         nr = nru;\n%     end\n%     % create surface\n%     for n = 1:nox(1)\n%         for m = 1:noy(2)\n%             x = [x1(n,m) x2(n,m)]';\n%             obj(n,m) = x.'*nQ*x + nl.'*x;\n%         end\n%     end\n%     if(eq)\n%         contour(x1,x2,obj,'color',[0 0 1],'levellist',nr);\n%     else\n%         for j = 1:length(nr) %each row constraint (max 2)\n%             c = contour(x1,x2,obj,'color',dkg,'levellist',nr(j));\n%             %Plot Hatch\n%             if(~isempty(c))\n%                 %See if we have multiple contours (non-convex or sd)\n%                 len = size(c,2)-1;\n%                 if(c(2,1) ~= len)\n%                     %Build contour array\n%                     cstrt = 2; cend = []; n = 2; ind = 1;\n%                     while(ind <= len)\n%                         ind = ind + c(2,ind) + 1;\n%                         cend(n-1) = ind-1; %#ok<AGROW>\n%                         cstrt(n) = ind+1;  %#ok<AGROW>\n%                         n = n + 1;\n%                     end\n%                 else\n%                     cstrt = 2;\n%                     cend = len;\n%                 end\n%                 %Plot each contour hatch\n%                 for n = 1:length(cend)\n%                     %Get contour vectors\n%                     vecx = diff(c(1,cstrt(n):cend(n)));\n%                     vecy = diff(c(2,cstrt(n):cend(n)));\n%                     if(isempty(vecx) || isempty(vecy))\n%                         continue;\n%                     end\n%                     %Rotate hatch lines based on infeasible region\n%                     xt = [c(1,cstrt(n))+vecy(1) c(2,cstrt(n))-vecx(1)]'; %check rotated -90\n%                     fval = xt.'*nQ*xt + nl.'*xt ;      \n%                     if(fval <= nr(j) || sense(j) == 'G') %rotate 90\n%                         hvecx = -vecy;\n%                         hvecy = vecx;\n%                     else %rotate -90\n%                         hvecx = vecy;\n%                         hvecy = -vecx;\n%                     end\n%                     %Normalize \n%                     av = mean(sqrt(hvecx.^2 + hvecy.^2));\n%                     dirs = atan2(hvecy,hvecx);    \n%                     hvecx = av*cos(dirs);\n%                     hvecy = av*sin(dirs);\n%                     %Shift origin\n%                     hvecx = c(1,cstrt(n):cend(n)-1) + hvecx;\n%                     hvecy = c(2,cstrt(n):cend(n)-1) + hvecy;\n%                     %Plot\n%                     line([c(1,cstrt(n):cend(n)-1)' hvecx']',[c(2,cstrt(n):cend(n)-1)' hvecy']','Color','k')\n%                 end                \n%             else\n%                 optiwarn('opti:plot','Cannot plot inequality constraint as contour data is empty!');\n%             end\n%         end\n%     end\n% end\n% \n% hold off;\n\n% CONVEX QC CODE\n% %Get contour vectors\n% vecx = diff(c(1,2:end));\n% vecy = diff(c(2,2:end));\n% %Rotate hatch lines based on infeasible region\n% xt = [c(1,2)+vecy(1) c(2,2)-vecx(1)]'; %check rotated -90\n% fval = xt.'*nQ*xt + nl.'*xt ;   \n% if(fval <= nr) %rotate 90\n%     hvecx = -vecy;\n%     hvecy = vecx;\n% else %rotate -90\n%     hvecx = vecy;\n%     hvecy = -vecx;\n% end\n% %Normalize\n% av = mean(sqrt(hvecx.^2 + hvecy.^2));\n% dirs = atan2(hvecy,hvecx);    \n% hvecx = av*cos(dirs);\n% hvecy = av*sin(dirs);\n% %Shift origin\n% hvecx = c(1,2:end-1) + hvecx;\n% hvecy = c(2,2:end-1) + hvecy;\n% %Plot\n% line([c(1,2:end-1)' hvecx']',[c(2,2:end-1)' hvecy']','Color','k')", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/math/opti/Utilities/opti/plotQuadCon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.7185944046238982, "lm_q1q2_score": 0.5789227831868331}}
{"text": "function [min_val, max_val] = arange(X)\n%ARANGE Returns the range (min and max) of an entire array.\n% Usage:\n%   R = arange(X)\n%   [min_val, max_val] = arange(X)\n%\n% See also: alims, amin, amax\n\nmin_val = min(X(:));\nmax_val = max(X(:));\n\nif nargout < 2\n    min_val = [min_val, max_val];\nend\nend\n\n", "meta": {"author": "talmo", "repo": "leap", "sha": "c39e07b647daa0d9bfc140a1ff93b1feabd538e2", "save_path": "github-repos/MATLAB/talmo-leap", "path": "github-repos/MATLAB/talmo-leap/leap-c39e07b647daa0d9bfc140a1ff93b1feabd538e2/leap/toolbox/utilities/arange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.5789227781566202}}
{"text": "  % 1 x 1  % 1 x 1% plot_info\n% plot Free energy and other infomation\na_min = 1e-5;\nNX = 2; \nNY = 2;\nalpha_plot = 0;\n\nFE  = Info.FE;\n\ntend = length(FE);\n\n% Start and End of iteration number for plot\ntmode = 2;\nt0 = 10;\nt3 = 600;\nswitch\ttmode\ncase\t1\n\tt1 = t0;\t\n\tt2 = tend;\t\ncase\t2\n\tt1 = t3;\t\n\tt2 = tend;\t\ncase\t3\n\tt1 = t0;\t\n\tt2 = t3;\nend\n\nHmode = 1;\nFmode = 2;\n% Fmode = 1 :Remove sudden drop of free energy due to weight pruning\n\nif Fmode == 1\n\t% Remove sudden drop of free energy due to weight pruning\n\tFdif = diff(FE);\n\t\n\tixz  = find( Fdif < 0);\n\tixz  = [ixz, ixz + 1, ixz + 2];\n\tixz  = ixz(:);\n\t\n\tix = setdiff2(1:tend,ixz);\nelse\n\tix = 1:tend;\nend\n\n% Free energy\nnfig = 1;\nsubplot(NX,NY,nfig)\n%hold on\nplot(ix,FE(ix))\n\ntitle('Free energy')\nxlim([t1 t2])\n\n%return\n\n% Model entropy\n\nif\tHmode < 2 &isfield(Info,'H')\n\tnfig = nfig + 1;\n\tsubplot(NX,NY,nfig)\n\t\n\tif isfield(parm,'T') \n\t\tswitch\tHmode \n\t\tcase 0\n\t\t\tH   = -Info.H * parm.T/log(parm.T);\n\t\tcase 1\n\t\t\tH   = -Info.H /log(parm.T);\n\t\tend\n\telse\n\t\tH   = -Info.H ;\n\tend\n\t\n\tplot(ix,H(ix))\n\thold on\n\ttitle('Effective parameter number')\n\txlim([t1 t2])\nend\n\nif\tHmode == 2 & isfield(Info,'M')\n\tnfig = nfig + 1;\n\tsubplot(NX,NY,nfig)\n\n\tplot(ix,Info.M(ix), '-b')\n\ttitle('Number of input dimension')\n\txlim([t1 t2])\nend\n\nif\tisfield(Info,'LP')\n\tnfig = nfig + 1;\n\tsubplot(NX,NY,nfig)\n\tLP  = Info.LP;\n\tplot(ix,LP(ix))\n\ttitle('Expected log-likelihood')\n\txlim([t1 t2])\nend\n\nif\tisfield(Info,'Err')\n\tnfig = nfig + 1;\n\tsubplot(NX,NY,nfig)\n\tErr  = Info.Err;\n\tplot(ix,Err(ix))\n\ttitle('Error')\n\txlim([t1 t2])\nend\n\n\n\nif alpha_plot == 0, return; end;\n\n% Hyper variance parameter\nif isfield(Model,'A')\n\tif isfield(Model,'ix_act')\n\t\tN = size(Model.A ,1);\n\t\tA = zeros(N,Model.M_all);\n\t\tA(:,Model.ix_act) = Model.A;\n\telse\n\t\tA =  Model.A;\n\tend\n\n    nfig = nfig + 1;\n\tsubplot(NX,NY,nfig)\n\tplot(A')\n\ttitle('Hyper variance parameter')\n\n    nfig = nfig + 1;\n\tsubplot(NX,NY,nfig)\n\thist(Model.A, 100)\n\ttitle('Hyper variance parameter')\n\t\n\tM=length(Model.A);\n\tK=sum(Model.A < a_min);\n\tfprintf('# of active dim = %d, # of near zero = %d\\n', M, K)\nend\n\n\nif alpha_plot == 1, return; end;\n\nif isfield(Info, 'A')\n    AA  = Info.A ;\n    nfig = nfig + 1;\n\tsubplot(NX,NY,nfig)\n\tplot(AA')\n\ttitle('Hyper variance histry')\nend\n", "meta": {"author": "KamitaniLab", "repo": "GenericObjectDecoding", "sha": "c98f24370668109fd9978bc8b43a33bd43926f47", "save_path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding", "path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding/GenericObjectDecoding-c98f24370668109fd9978bc8b43a33bd43926f47/code/matlab/lib/SPR_2009_12_17/plot_info.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.578922775328305}}
{"text": "function [Hist] = makeHistogram(Bin,XSize,YSize,NrX,NrY,NrBins)\n%  This function classifies the greylevels present in the array image into\n%  a greylevel histogram. The pLookupTable specifies the relationship\n%  between the greyvalue of the pixel (typically between 0 and 4095) and\n%  the corresponding bin in the histogram (usually containing only 128 bins).\n\nHist=zeros(NrX,NrY,NrBins);\n\nfor i=1:NrX\n    for j=1:NrY\n        bin=Bin(1+(i-1)*XSize:i*XSize,1+(j-1)*YSize:j*YSize);\n        for i1=1:XSize\n            for j1=1:YSize\n                Hist(i,j,bin(i1,j1)) = Hist(i,j,bin(i1,j1)) + 1;\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/22182-contrast-limited-adaptive-histogram-equalization-clahe/makeHistogram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5789227600626135}}
{"text": "function pp=lpcra2pp(ra)\n%LPCAR2PP LPC: Convert ar filter autocorrelation to power spectrum polynomial in cos(w) PP=(RA)\n% pp is a polynomial such that |polyval(ra,e^jw)| = polyval(pp,cos(w))\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: lpcra2pp.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\npersistent tp;\n[nf,p1]=size(ra);\n% we check here if p is the same as before and reuse the tp matrix\nif size(tp,1)~=p1\n   p=p1-1;\n   % chebyshev polynomials up to order p\n   tp=zeros(p1,p1);\n   tp(1,p1)=2;\n   tp(2,p)=2;\n   for i=3:p1\n      tp(i,p+2-i:p)=2*tp(i-1,p+3-i:p1)-tp(i-2,p+2-i:p);\n      tp(i,p1)=-tp(i-2,p1);\n   end\n   tp(1,p1)=1;\nend\npp=ra*tp;\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/lpcra2pp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478256, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.5789227570592455}}
{"text": "function J = calcJ(camera, imuState_k, camStates_k)\n% Jacobian of feature observations w.r.t. feature locations\n\n    C_CI = quatToRotMat(camera.q_CI);\n    C_IG = quatToRotMat(imuState_k.q_IG);\n\n    J = zeros(6, 12 + 6*size(camStates_k,2));\n    J(1:3,1:3) = C_CI;\n    J(4:6,1:3) = crossMat(C_IG' * camera.p_C_I);\n    J(4:6,10:12) = eye(3);\n\nend", "meta": {"author": "utiasSTARS", "repo": "msckf-swf-comparison", "sha": "ad9566ef35c3e4792a89b04623e1fa2f99238435", "save_path": "github-repos/MATLAB/utiasSTARS-msckf-swf-comparison", "path": "github-repos/MATLAB/utiasSTARS-msckf-swf-comparison/msckf-swf-comparison-ad9566ef35c3e4792a89b04623e1fa2f99238435/msckf/calcJ.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5788973833627846}}
{"text": "function dimacs = computedimacs(b,c,A,xin,y,s,K);\n% COMPUTEDIMACS\n%\n% min <C,X> s.t     AX = b, X > 0\n% max b'y   s.t S-C+A'y =0, S > 0\n\n% If no primal exist, fake till later\nif isempty(xin)\n    x = c*0;\nelse\n    x = xin;\nend\n\nif isempty(s)\n    s = c-A'*y;\nend\n\nxres = inf;\nsres = inf;\n\n% Not officially defined in DIMACS\nif K.f>0\n    sres = -min(norm(s(1:K.f),inf));\nend\n\n% Errors in linear cone\nif K.l>0\n    xres = min(x(1+K.f:K.f+K.l));\n    sres = min(s(1+K.f:K.f+K.l));\nend\n\n% Errors in quadratic cone\nif K.q(1)>0\n    top = K.f+K.l;\n    for i = 1:length(K.q)\n        X = x(1+top:top+K.q(i));\n        S = s(1+top:top+K.q(i));\n        xres = min(xres,X(1)-norm(X(2:end)));\n        sres = min(sres,S(1)-norm(S(2:end)));\n        top = top + K.q(i);\n    end\nend\n\n% Errors in semidefinite cone\nif K.s(1)>0\n    top = K.f+K.l+K.q+K.r;\n    for i = 1:length(K.s)\n        X = reshape(x(1+top:top+K.s(i)^2),K.s(i),K.s(i));\n        S = reshape(s(1+top:top+K.s(i)^2),K.s(i),K.s(i));\n        xres = min(xres,min(eig(full(X))));\n        sres = min(sres,min(eig(full(S))));\n        top = top + K.s(i)^2;\n    end\nend\n\nerr1 = norm(b-A*x)/(1 + norm(b,inf));\nerr2 = max(0,-xres)/(1 + norm(b,inf));\nerr3 = conenorm(s-(c-A'*y),K)/(1+norm(c,inf));\n%err3 = norm(s-(c-A'*y))/(1+norm(c,inf)); % Used by some solvers\nerr4 = max(0,-sres)/(1+max(abs(c)));\nerr5 = (c'*x-b'*y)/(1+abs(c'*x)+abs(b'*y));\nerr6 = x'*(c-A'*y)/(1+abs(c'*x)+abs(b'*y));\n\n% No primal was computed\nif isempty(xin)\n    err1 = nan;\n    err2 = nan;\n    err5 = nan;\n    err6 = nan;\nend\ndimacs = [err1 err2 err3 err4 err5 err6];\n\nfunction t = conenorm(s,K)\n\n% Implementation of the norm described on\n% http://plato.asu.edu/dimacs/node3.html\n\nt = 0;\n\nif K.f + K.l>0\n    t = t + norm(s(1:K.f+K.l));\nend\n\ntop = 1+K.f+K.l;\nif K.q(1)>0\n    for i = 1:length(K.q)\n        t = t + norm(s(top:top+K.q(i)-1));\n        top  = top + K.q(i);\n    end\nend\n\nif K.s(1)>0\n    for i = 1:length(K.s)\n        S = reshape(s(top:top+K.s(i)^2-1),K.s(i),K.s(i));\n        t = t + norm(S,'fro');\n        top  = top + K.s(i)^2;\n    end\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/extras/computedimacs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5788973559792953}}
{"text": "function bc = specific_bc(xbd,ybd)\n%solution3_bc   Reference problem 1.3  boundary condition \n%   bc = specific_bc(xbd,ybd);\n%   input\n%          xbd          x boundary coordinate vector\n%          ybd          y boundary coordinate vector \n%   IFISS function: DJS; 28 February 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nbc=2*(1+ybd)./((ybd+1).*(ybd+1) + (xbd+3).*(xbd+3));\nreturn\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/diffusion/test_problems/solution3_bc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5788966351184277}}
{"text": "function [nmps2] = mGal2nmps2(mGal)\n% Convert acceleration from milligalileos to nanometers per second squared\n% Chad A. Greene 2012\nnmps2 = mGal*1e+4; \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/35258-unit-converters/unit_converters/mGal2nmps2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5788694018715311}}
{"text": "function [axons,packing] = func_axonpack_main(numelobj, d_mean, d_var, gap, iter_max)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%       AxonPackin : Simulate arrangement of white matter axons \n%                     author : Tom Mingasson\n%             https://github.com/neuropoly/axonpacking \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                       CHANGE INPUTS BELOW\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% MAIN INPUTS\nN = numelobj;            % number of axons i.e disks to pack  \n%d_mean = 3;         % theoretical mean of axon diameters in um\n%d_var  = 1;         % theoretical variance of axon diameters in um\nDelta  = gap;         % gap between the edge of axons in um \n%iter_max = 30000;    % number of iteration i.e migrations to perform. Example: iter_max = 30000 ok if N = 1000\n\n% SECONDARY INPUTS\nthreshold_high = 10;     % no diameter above 'threshold_high'\nthreshold_low = 0.2;     % no diameter under 'threshold_low'\niter_fvf = iter_max/10;  % to study the packing convergence the disk density i.e Fiber Volume Fraction (FVF) can be computed and displayed every 'iter_fvf' iterations\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                     AxonPacking Process  \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfor k=1:length(d_mean)\n\n    % axons features\n    axons.N{k}      = N;\n    axons.d_mean{k} = d_mean(k);\n    axons.d_var{k}  = d_var(k);\n    axons.Delta{k}           = Delta(k);\n    axons.threshold_high{k} = threshold_high;\n    axons.threshold_low{k}  = threshold_low;\n    \n    % axon diameters sampling (under a gamma law or lognormal and initialization of positions 'x0' in a square area of length 'side')\n    [d, x0, side] = axons_setup(axons,'gamma', k);\n    axons.d{k} = d;\n    axons.g_ratio{k} = compute_gratio(d);\n    \n    % packing process of the axons\n    [final_positions, final_overlap, fvf_historic] = process_packing(x0, d, Delta(k), side, iter_max, iter_fvf);\n    \n    % store packing results\n    % main results\n    packing.initial_positions{k}    = reshape(x0,2,length(x0)/2);\n    packing.final_positions{k}      = final_positions;\n    % secondary results\n    packing.final_overlap{k}        = final_overlap;\n    packing.FVF_historic{k}         = fvf_historic;\n    packing.iter_max{k}             = iter_max;\n    \n    % Statistics from the packing\n    [FVF, FR, MVF, AVF] = compute_statistics(axons.d{k}, axons.Delta{k}, packing.final_positions{k}, side, axons.g_ratio{k});\n    \n    % store stats results\n    stats.FVF{k}        = FVF;\n    stats.FR{k}         = FR;\n    stats.MVF{k}        = MVF;\n    stats.AVF{k}        = AVF;\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                 Save results in a folder named 'results'\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% save_var = num2str(d_var);  save_var(save_var == ' ') = '';\n% save_mean = num2str(d_mean); save_mean(save_mean == ' ') = '';\n% save_Delta  = num2str(Delta);  save_Delta(save_Delta == ' ') = '';\n% save_iter  = num2str(iter_max);\n% saveName  = ['Axons', num2str(N), '_Mean', save_mean, '_Var', save_var, '_Delta', save_Delta, '_Iter',save_iter];\n% \n% mkdir('results')\n% cd([pwd,filesep, 'results'])\n% \n% % save outputs\n% save('axons.mat', '-struct', 'axons');\n% save('packing.mat', '-struct', 'packing');\n% save('stats.mat', '-struct', 'stats');\n% \n% % save final substrate\n% saveas(figure(1000),[saveName,'.png']);\n% \n\n\n\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Addons/SimMonteCarlo_Diffusion/func_axonpack_main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5788693911310178}}
{"text": "function [J,alpha,beta,T] = variationalDynLoreta(Ut,Y,s2,iLV,L,alpha,beta,options)\n\n%[J,alpha,beta,T] = variationalDynLoreta(Ut,Y,s2,iLV,L,alpha,beta,options)\n%\n% Computes the posterior distribution of the parameters J given some data V. \n% The program solves levels of inference: 1) optimization of parameters J, and\n% 2) optimization of hyperparameters alpha and beta. See Trujillo-Barreto\n% et. al. (2004) for details.\n%\n% Ut,s2, and iLV are defined as follows: \n%     Y: Nsensors x time points data matrix\n%     K: N x P predictor matrix\n%     L: sparse P x P square root of the precision matrix \n%     [U,s,V] = svd( K*inv(L) )\n%     iLV = inv(L)*V\n%     s2  = s.^2\n%\n% alpha, beta: hyperparameters\n% J: estimated parapeters\n% \n%                     P(V|J,alpha)*P(J|beta)\n% P(J|V,alpha,beta) = ---------------------- \n%                        P(V|alpha,beta)\n% \n% Author: Alejandro Ojeda, SCCN/INC/UCSD, Jan-2013\n%\n% References:\n%   Trujillo-Barreto, N., Aubert-Vazquez, E., Valdes-Sosa, P.A., 2004.\n%     Bayesian model averaging in EEG/MEG imaging. NeuroImage 21, 1300???1319\n\n\n\nif nargin < 5, error('Not enough input arguments.');end\nif nargin < 8\n    options.maxTol = 1e-3;\n    options.maxIter = 100;\n    options.verbose = true;\n    options.gridSize = 100;\nend\n\ns = s2.^(0.5);\nn = length(s);\np = size(L,1);\nntp = size(Y,2);\n\n% Initialize hyperparameters\nif nargin < 8\n    UtY = Ut*Y(:,1);\n    tol = max([n p])*eps(max(s));\n    lambda2 = logspace(log10(tol),log10(max(s)),options.gridSize);\n    gcv = zeros(options.gridSize,1);\n    parfor k=1:options.gridSize\n        d = lambda2(k)./(s2+lambda2(k));\n        f = diag(d)*UtY;\n        gcv(k) = dot(f,f,1)/sum(d)^2;\n    end\n    loc = getMinima(gcv);\n    if isempty(loc), loc = 1;end\n    loc = loc(end);\n    lambda2 = lambda2(loc);\n     \n    alpha = 0.001*(Y(:)'*Y(:))/n;\n    beta = alpha*lambda2;\nend\nerr = inf;\n\nfor it=1:options.maxIter\n    if err < options.maxTol, break;end\n    \n    % computing statistics\n    H = Ut'*diag(alpha.*s2./(alpha.*s2+beta))*Ut;    \n    SSE = mean( (Y - H*Y).^2 ,2);\n    sigma2 = mean(SSE);    \n    kSjk = diag(H);\n        \n    q = diag(alpha.*s./(alpha.*s2+beta))*Ut;%*Y;\n    Sj = mean((iLV*q).^2,2);\n    aic = -2*log(sigma2) + 2*p;\n    alpha_old = alpha;\n    beta_old = beta;\n    \n    % updating hyperparameters\n    alpha = updateAlpha(SSE,kSjk,ntp);\n    beta  = updateBeta(Sj,p);\n    \n    err = 0.5*abs(sum(alpha_old-alpha)) + 0.5*abs(beta_old-beta);\n    if options.verbose\n        disp([num2str(it) ' => alpha: ' num2str(alpha_old) '  beta: ' num2str(beta_old) ' sse: ' num2str(mean(SSE)) ' hyrp. error: ' num2str(err) ' aic: ' num2str(aic)]);\n    end\nend\nif it == options.maxIter, warning('Maximum iteration reached. Failed to converge.');end\n\n% parameters's estimation\nT = iLV*diag(alpha.*s./(alpha.*s2+beta))*Ut;\nJ = T*Y;\n\n% standardized Loreta\nE = sum(Y-H*Y,2);\nsigma = E'*E/(n-trace(H));\ndT = 1./sqrt(dot(T,T,2));\nS = 1./sigma*dT;\nS = S./std(eps+S);\nT = bsxfun(@times,T,S);%sqrt(p)*\nJ = bsxfun(@times,J,S);%sqrt(p)*\nend\n\n\n%---\nfunction indmin = getMinima(x)\nfminor = diff(x)>=0;\nfminor = ~fminor(1:end-1, :) & fminor(2:end, :);\nfminor = [0; fminor; 0];\nindmin = find(fminor);\nend\n\nfunction alpha = updateAlpha(SSE,kSjk,ntp,bp,cp)\nif nargin < 4, bp = 3;end\nif nargin < 5, cp = 3;end\nb = 1./( (1/bp) + 0.5*SSE + 0.5*kSjk );\nc = cp + ntp/2;\nalpha = median(1./(b*c));\nend\n\nfunction beta = updateBeta(r,p,bp,cp)\nif nargin < 3, bp = 3;end\nif nargin < 4, cp = 3;end\nb = 1./( 1/bp + sum(r) );\nc = cp+p/2;\nbeta = 1/(b*c);\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/code/filters/in_development/private/variationalDynLoreta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5788693910992619}}
{"text": "function Offspring = Operator(Problem,Population)\n% Differential evolution in FROFI\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    %% Parameter setting\n    PopDec = Population.decs;\n    [N,D]  = size(PopDec);\n    CR = [0.1 0.2 1]';\n    CR = repmat(CR(randi(end,N,1)),1,D);\n    F  = [0.6 0.8 1]';\n    F  = repmat(F(randi(end,N,1)),1,D);\n    \n    %% Parents\n    [~,P] = sort(rand(N),2);\n    P1    = PopDec(P(:,1),:);\n    P2    = PopDec(P(:,2),:);\n    P3    = PopDec(P(:,3),:);\n    [~,B] = min(Population.objs);\n    PB    = repmat(PopDec(B,:),N,1);\n    \n    %% Offspring generation\n    Rand   = rand(N,D);\n    k1     = repmat(rand(N,1)<0.5,1,D);\n    k2     = ~k1 & rand(N,D)<CR;\n    OffDec = PopDec;\n    OffDec(k1) = PopDec(k1) + Rand(k1).*(P1(k1)-PopDec(k1)) + F(k1).*(P2(k1)-P3(k1));\n    OffDec(k2) = P1(k2) + Rand(k2).*(PB(k2)-P1(k2)) + F(k2).*(P2(k2)-P3(k2));\n    Offspring  = Problem.Evaluation(OffDec);\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/Single-objective optimization/FROFI/Operator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5788693910357494}}
{"text": "% DEMSPGP1D1 Do a simple 1-D regression after Snelson & Ghahramani's example.\n\n% GP\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'spgp1d';\nexperimentNo = 1;\n\n% load data\n[X, y] = mapLoadData(dataSetName);\n\n% Set up model\noptions = gpOptions('dtc');\noptions.numActive = 9;\n\n% use the deterministic training conditional.\nq = size(X, 2);\nd = size(y, 2);\n\nmodel = gpCreate(q, d, X, y, options);\nmodel.X_u = randn(9, 1)*0.25 - 0.75;\nparams = gpExtractParam(model);\nmodel = gpExpandParam(model, params);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = gpOptimise(model, display, iters);\n\n% Save the results.\ncapName = dataSetName;\ncapName(1) = upper(capName(1));\nsave(['dem' capName num2str(experimentNo) '.mat'], 'model');\n\n\ndemSpgp1dPlot", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gp/demSpgp1d1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024554, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.578869385713127}}
{"text": "classdef TestGeneralTwoRankSequentialLaminate < handle\n    \n    properties (Access = private)\n      fractionVolume\n      directions\n      lamParams\n      stiffTensor\n      weakTensor\n      Rank2Ch\n      SeqLamCh\n    end\n    \n    methods (Access = public)\n\n        function obj = TestGeneralTwoRankSequentialLaminate()\n            obj.init()\n            obj.computeTwoRankSequentialLaminate()\n            obj.computeGeneralTwoRankSequentialLaminate()\n        end\n\n        function hasPassed = hasPassed(obj)\n            RankTwoCh  = obj.Rank2Ch;\n            SqCh = obj.SeqLamCh.getValue();\n            hasPassed = norm(RankTwoCh - SqCh)/norm(SqCh) > 1e-6;\n        end\n\n    end\n\n    methods (Access = private)\n\n        function init(obj)\n            obj.fractionVolume = 0.8000;\n            obj.lamParams = [1 0];\n            obj.loadLaminateDirections()\n            obj.createStiffAndWeakTensors()\n        end\n\n        function loadLaminateDirections(obj)\n            d1 = [rand(1) rand(1)  0];\n            d2 = [1     3     0];\n            obj.directions{1} = obj.createDirection(d1);\n            obj.directions{2} = obj.createDirection(d2);\n        end\n\n        function createStiffAndWeakTensors(obj)\n            epsilon = 1.0000e-03;\n            E1  = 1;\n            nu1 = 1/3;\n            E0  = epsilon*E1;\n            nu0 = 1/3;\n            obj.stiffTensor = IsotropicConstitutiveTensor(E1,nu1);\n            obj.weakTensor  = IsotropicConstitutiveTensor(E0,nu0);\n        end\n\n        function computeTwoRankSequentialLaminate(obj)\n            mi    = obj.lamParams;\n            dir   = obj.directions;\n            theta = obj.fractionVolume;\n            C1    = obj.stiffTensor.getValue();\n            C0    = obj.weakTensor.getValue();\n            mu    = obj.stiffTensor.getMu();\n            lambda2D = obj.stiffTensor.getLambda2D();\n            homogenizer = RankTwoLaminateHomogenizer(C1,C0,dir,mi,theta,lambda2D,mu);\n            obj.Rank2Ch = homogenizer.getTensor;\n        end\n        \n        function computeGeneralTwoRankSequentialLaminate(obj)\n            C0       = obj.weakTensor;\n            C1       = obj.stiffTensor;\n            mi       = obj.lamParams;\n            dir      = obj.directions;\n            Theta    = obj.fractionVolume;\n            SeqHomog      = VoigtPlaneStressHomogHomogenizer(C0,C1,dir,mi,Theta);\n            obj.SeqLamCh  = SeqHomog.getPlaneStressHomogenizedTensor();\n        end\n\n    end\n\n    methods (Access = private, Static)\n\n        function dir = createDirection(d)\n            dir = Vector3D;\n            dir.setValue(d);\n            dir.normalize();\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/tests/Source/HomogenizationTests/TestGeneralTwoRankSequentialLaminate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5788693856813713}}
{"text": "function ll = fgplvmSequenceLogLikelihood(model, X, Y, varargin)\n\n% FGPLVMSEQUENCELOGLIKELIHOOD Log-likelihood of a sequence for the GP-LVM.\n% FORMAT\n% DESC returns the log probability of a given latent sequence and an\n% associated observed data sequence under the posterior prediction\n% induced by the training data for a given GP-LVM model.\n% ARG model : the model for which the sequence prediction will be\n% made.\n% ARG X : the latent sequence for which the posterior distribution\n% will be evaluated.\n% ARG Y : the observed data sequence for which the posterior\n% distribution will be evaluated.\n% ARG P1, P2, P3 ... : optional additional arguments to be passed\n% to the dynamics' model sequence log likelihood.\n% RETURN ll : the sequence log likelihood.\n%\n% SEEALSO : fgplvmCreate, fgplvmOptimiseSequence, fgplvmSequenceObjective\n%\n% COPYRIGHT : Neil D. Lawrence, 2005, 2006\n%\n% MODIFICATIONS : Carl Henrik Ek, 2007\n\n% FGPLVM\nif(nargin<3)\n  error('This function requires at least two arguments.');\nend\n\nlogTwoPi = log(2*pi);\nif model.isMissingData\n  [mu, covarSigma]  = gpPosteriorMeanCovar(model, X);\n  for i = 1:model.d\n    missing = true;\n    if ~any(isnan(Y(:, i)))\n      U = jitChol(covarSigma{i});\n      missing = false;\n    end\n    Ydiff = (Y(:, i)-mu(:, i));\n    ll = 0;\n    if missing\n      ind = find(~isnan(Ydiff));\n      if length(ind) ~= 0    \n        U = jitChol(covarSigma{i}(ind, ind));\n      end\n    else\n      ind = [1:size(Ydiff, 1)]';\n    end\n    if length(ind) ~= 0    \n      UinvYdiff = U'\\Ydiff(ind);\n      logDet = logdet([], U);\n      ll = ll + logDet + (UinvYdiff'*UinvYdiff);\n      ll = ll + logTwoPi*length(ind);\n    end\n  end\nelse\n  [mu, covarSigma, factors] = gpPosteriorMeanCovar(model, X);\n  missing = true;\n  if ~any(isnan(Y))\n    U = jitChol(covarSigma);\n    missing = false;\n  end\n  Ydiff = (Y-mu);\n  ll =0;\n  for i = 1:model.d\n    if missing\n      ind = find(~isnan(Ydiff(:, i)));\n      if length(ind) ~= 0    \n        U = jitChol(covarSigma(ind, ind));\n      end\n    else\n      ind = [1:size(Ydiff, 1)]';\n    end\n    if length(ind) ~= 0    \n      UinvYdiff = U'\\Ydiff(ind, i);\n      logDet = logdet([], U);\n      ll = ll + logDet + log(factors(i)) + (UinvYdiff'*UinvYdiff)/factors(i);\n      ll = ll + logTwoPi*length(ind);\n    end\n  end\nend\nll = -0.5*ll;\n  \n  \nif isfield(model, 'dynamics') & ~isempty(model.dynamics)\n  % A dynamics model is being used.\n  feval = str2func([model.dynamics.type 'SequenceLogLikelihood']);\n  if isfield(model, 'dynamicsBalancing') & ~isempty(model.dynamicsBalancing)\n    ll = ll + model.dynamicsBalancing*feval(model.dynamics, X, varargin{:});\n  else\n    ll = ll + feval(model.dynamics, X, varargin{:});\n  end\nelseif isfield(model, 'prior') &  ~isempty(model.prior)\n  for i = 1:size(X, 1)\n    ll = ll + priorLogProb(model.prior, X(i, :));\n  end\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/fgplvmSequenceLogLikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5788456273527922}}
{"text": "% absolute difference in orientation between a fly and the closest fly\n% according to type\nfunction [data,units] = compute_absthetadiff(trx,n,type)\n\nflies = trx.exp2flies{n};\nnflies = numel(flies);\ndata = cell(1,nflies);\n\nfor i1 = 1:nflies,\n  fly1 = flies(i1);\n  \n  % fly closest to fly1 according to type\n  closestfly = trx(fly1).(['closestfly_',type]);\n  \n  % orientation of fly1\n  theta_mm1 = trx(fly1).theta_mm;\n\n  % loop over all flies\n  for i2 = 1:nflies,\n    \n    fly2 = flies(i2);\n    if i1 == i2, continue; end\n    \n    % frames where this fly is closest\n    idx = find(closestfly == fly2);\n    if isempty(idx), continue; end\n    \n    % orientation of fly2\n    off = trx(fly1).firstframe - trx(fly2).firstframe;\n    theta_mm2 = trx(fly2).theta_mm(off+idx);\n    \n    % absolute difference in orientation\n    data{i1}(idx) = abs(modrange(theta_mm2 - theta_mm1(idx),-pi,pi));\n\n  end\nend\n\nunits = parseunits('rad');", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/compute_absthetadiff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5788456207364183}}
{"text": "function f = sparsnessCol2(Hkt_T, varargin)\nk=varargin{1};\nt=varargin{2};\nHkt=exp(reshape(Hkt_T, k, t));\nsumH_t = sum(Hkt,2);\n% figure \n% bar(sumH_t)\nsumH_t_sq = sum(sumH_t.^2);\nsumH = sum(sumH_t);\nnh = length(sumH_t); \nf = (sqrt(nh)-sumH/(sqrt(sumH_t_sq)))/(sqrt(nh)-1);", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/aux/sparsnessCol2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.578845619013463}}
{"text": "function net = cnn_cifar_init(varargin)\nopts.networkType = 'simplenn' ;\nopts = vl_argparse(opts, varargin) ;\n\nlr = [.1 2] ;\n\n% Define network CIFAR10-quick\nnet.layers = {} ;\n\n% Block 1\nnet.layers{end+1} = struct('type', 'conv', ...\n                           'weights', {{0.01*randn(5,5,3,32, 'single'), zeros(1, 32, 'single')}}, ...\n                           'learningRate', lr, ...\n                           'stride', 1, ...\n                           'pad', 2) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n                           'method', 'max', ...\n                           'pool', [3 3], ...\n                           'stride', 2, ...\n                           'pad', [0 1 0 1]) ;\nnet.layers{end+1} = struct('type', 'relu') ;\n\n% Block 2\nnet.layers{end+1} = struct('type', 'conv', ...\n                           'weights', {{0.05*randn(5,5,32,32, 'single'), zeros(1,32,'single')}}, ...\n                           'learningRate', lr, ...\n                           'stride', 1, ...\n                           'pad', 2) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'pool', ...\n                           'method', 'avg', ...\n                           'pool', [3 3], ...\n                           'stride', 2, ...\n                           'pad', [0 1 0 1]) ; % Emulate caffe\n\n% Block 3\nnet.layers{end+1} = struct('type', 'conv', ...\n                           'weights', {{0.05*randn(5,5,32,64, 'single'), zeros(1,64,'single')}}, ...\n                           'learningRate', lr, ...\n                           'stride', 1, ...\n                           'pad', 2) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'pool', ...\n                           'method', 'avg', ...\n                           'pool', [3 3], ...\n                           'stride', 2, ...\n                           'pad', [0 1 0 1]) ; % Emulate caffe\n\n% Block 4\nnet.layers{end+1} = struct('type', 'conv', ...\n                           'weights', {{0.05*randn(4,4,64,64, 'single'), zeros(1,64,'single')}}, ...\n                           'learningRate', lr, ...\n                           'stride', 1, ...\n                           'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\n\n% Block 5\nnet.layers{end+1} = struct('type', 'conv', ...\n                           'weights', {{0.05*randn(1,1,64,10, 'single'), zeros(1,10,'single')}}, ...\n                           'learningRate', .1*lr, ...\n                           'stride', 1, ...\n                           'pad', 0) ;\n\n% Loss layer\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\n% Meta parameters\nnet.meta.inputSize = [32 32 3] ;\nnet.meta.trainOpts.learningRate = [0.05*ones(1,30) 0.005*ones(1,10) 0.0005*ones(1,5)] ;\nnet.meta.trainOpts.weightDecay = 0.0001 ;\nnet.meta.trainOpts.batchSize = 100 ;\nnet.meta.trainOpts.numEpochs = numel(net.meta.trainOpts.learningRate) ;\n\n% Fill in default values\nnet = vl_simplenn_tidy(net) ;\n\n% Switch to DagNN if requested\nswitch lower(opts.networkType)\n  case 'simplenn'\n    % done\n  case 'dagnn'\n    net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ;\n    net.addLayer('error', dagnn.Loss('loss', 'classerror'), ...\n             {'prediction','label'}, 'error') ;\n  otherwise\n    assert(false) ;\nend\n\n", "meta": {"author": "willard-yuan", "repo": "cnn-for-image-retrieval", "sha": "2e3e8ab76e2c971314be55b5ae44e02884003261", "save_path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval/cnn-for-image-retrieval-2e3e8ab76e2c971314be55b5ae44e02884003261/matconvnet-1.0-beta18/examples/cifar/cnn_cifar_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.578845619013463}}
{"text": "function [gew,pve,H] = spm_csd2gew(csd,Hz,u)\n% Convert cross sspectral density to Geweke Granger causality\n% FORMAT [gew,pve,H] = spm_csd2gew(csd,Hz)\n%\n% ccf  (N,m,m)   - cross covariance functions\n% Hz   (n x 1)   - vector of frequencies (Hz)\n% u    (1)       - regularizer (default: 1);\n%\n% gwe  (N,m,m)   - Geweke's frequency domain Granger causality\n% pve  (N,m,m)   - proportion of variance explained\n% H    (N,m,m)   - transfer function matrix\n%\n% This routine uses the Wilson-Burg algorithm to perform spectral matrix\n% factorisation. The minimum phase factor is then used to form the noise\n% covariance (covariance of the innovations) and implicitly derive the\n% transfer functions (and spectral Granger causality).\n%\n% See also:\n%  spm_ccf2csd.m, spm_ccf2mar, spm_csd2ccf.m, spm_csd2mar.m, spm_mar2csd.m,\n%  spm_csd2coh.m, spm_dcm_mtf.m, spm_Q.m, spm_mar.m and spm_mar_spectral.m\n%\n%__________________________________________________________________________\n% Copyright (C) 2014 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_csd2gew.m 5908 2014-03-05 20:31:57Z karl $\n\n% preliminaries\n%--------------------------------------------------------------------------\nif nargin < 3\n    try\n        [gew,pve,H] = spm_csd2gew(csd,Hz,2);\n        return\n    catch\n        [gew,pve,H] = spm_csd2gew(csd,Hz,16);\n        return\n    end\nend\n\n% pad spectrum if necessary\n%--------------------------------------------------------------------------\niw    = 1 + round(Hz/(Hz(2) - Hz(1)));\nn     = size(csd,2);\nnw    = 257;\nis    = ceil(nw/2):nw;\n\n% Wilson-Burg algorithm\n%==========================================================================\n\n% initialise transfer function\n%--------------------------------------------------------------------------\nH     = zeros(nw,n,n);\nP     = zeros(nw,n,n);\ne     = norm(squeeze(max(csd,[],1)))/128;\nE     = eye(n,n)*e;\n\nP(iw,:,:) = csd;\nfor i = 1:n\n    P(:,i,i) = P(:,i,i) + e;\n    H(:,i,i) = sqrt(P(:,i,i));\nend\n\n% iterate until convergence: solve for H*H' = P\n%--------------------------------------------------------------------------\nfor t = 1:128\n    \n    % compute left-hand side (deconvolution)\n    %----------------------------------------------------------------------\n    for w = 1:nw\n        S        = squeeze(H(w,:,:)) + E;\n        A(w,:,:) = (eye(n,n) + S*S'\\squeeze(P(w,:,:)));\n    end\n    \n    % retain causal signal and half zero lag\n    %----------------------------------------------------------------------\n    S           = ifft(A);\n    S(is,:,:)   = 0;\n    S(1,:,:)    = S(1,:,:)/2;\n    A           = fft(S);\n    \n    % recover next update (convolution)\n    %----------------------------------------------------------------------\n    nrm   = zeros(nw,1);\n    for w = 1:nw\n        U        = squeeze(A(w,:,:));\n        H(w,:,:) = squeeze(H(w,:,:))*U^(1/u);\n        nrm(w)   = nrm(w) + norm(eye(n,n) - U,'inf');\n    end\n    \n    % break if convergence\n    %----------------------------------------------------------------------\n    nrm = mean(nrm);\n    if nrm < 1e-6, break, end\n    if nrm > 8,   return, end\n   \nend\n\n% transfer function and noise covariance\n%==========================================================================\n\n% get noise covariance\n%--------------------------------------------------------------------------\nS     = ifft(H);\nR     = squeeze(S(1,:,:));\nC     = real(R*R');\nc     = sqrtm(C);\n\n% recover transfer function\n%--------------------------------------------------------------------------\nfor w = 1:nw\n    H(w,:,:) = squeeze(H(w,:,:))/c;\n    P(w,:,:) = squeeze(H(w,:,:))*C*squeeze(H(w,:,:))';\nend\n\n% Geweke Granger Causality in the Frequency domain\n%--------------------------------------------------------------------------\npve   = zeros(nw,n,n);\ngew   = zeros(nw,n,n);\nfor j = 1:n\n    for k = 1:n\n        rkj        = C(j,j) - (C(j,k)^2)/C(k,k);\n        sk         = abs(P(:,k,k));\n        hkj        = abs(H(:,k,j)).^2;\n        pve(:,k,j) = rkj*hkj./sk;\n        gew(:,k,j) = -log(1 - pve(:,k,j));\n    end\nend\n\n% return  specified frequencies\n%--------------------------------------------------------------------------\ngew = gew(iw,:,:);\npve = pve(iw,:,:);\nH   = H(iw,:,:);\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_csd2gew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5788456176523835}}
{"text": "function testGaborFilter\n%% by dzhg: zhgdai@126.com\n%% This code is to search the direction of the vessel for each point of\n%% the Image. I apply Gabor Filter to this work and the corresponding\n%% output Gabor filter will be choosed to be the direction of the vessel.\n%% if you have any question about this code, please contact with me by\n%% zhgdai@126.com without hesitate.\n%% This edition is to apply adaptative size of gabor filter to detect the\n%% direction of the vessel.\n\n\nI = imread('00005.bmp');\n\nif isgray(I) ==0\n    I = rgb2gray(I);\nend\n\n[ImageWidth,ImageHeight] = size(I);\nsizeinterval = 10;\nBegin_s = 10;\nEnd_s = 40;\nangleinterval = 18;\n\n%% papers parameters\ns = Begin_s:sizeinterval:End_s;\ntheta = 0:pi/angleinterval:(angleinterval-1)/angleinterval*pi;\n\nf = 1./s;\nSx = s/pi;\nSy = s/pi;\nLengthTheta = length(theta);\nLengthS = length(s);\n\nGaborFilter = zeros(ImageWidth,ImageHeight,(LengthTheta-1)*LengthS);\nIndex = 1;\nfor j = 1:LengthS\n    for i = 1:LengthTheta-1\n    [G,gabout] = gabordzhg(I,Sx(j),Sy(j),f(j),theta(i));\n    GaborModel{Index} = G;\n    GaborFilter(:,:,Index) = gabout;\n    Index = Index + 1;\n    end\nend\n\nimshow(I);\nhold on;\n[a,b] = ginput;\n% a = 275;\n% b = 245;\n\n\nGaborFilterValue = GaborFilter(floor(b),floor(a),1:end);\nsavevar = [];\nfor i = 1:LengthS\n    tempvar = var(GaborFilterValue((i-1)*(angleinterval-1)+1:i*(angleinterval-1)));\n    savevar = [savevar;tempvar];\nend\n[maxvar,maxindex] = max(savevar);\n[minvalue,minindex] = min(GaborFilterValue((maxindex-1)*(angleinterval-1)+1:maxindex*(angleinterval-1)));\nimshow(GaborModel{(maxindex-1)*(angleinterval-1)+minindex},[]);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25789-detect-vessel-direction/vessel direction/testGaborFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5788333512413179}}
{"text": "function [ ersp ] = visual_ERSP( data, varargin )\n% Description:  \n%   ERSP (Event-related spectral pergurbation) measures the average dynamic changes \n%   in amplitude of the broad band EEG frequency spectrum as a function of time \n%   relative to an experimental event \n%\n% Example code:\n%  [dat] = proc_ERSP(data , <OPT>)\n%\n% Input:\n%   data: Data structrue (ex) Epoched data structure\n%\n% Options:\n%   <OPT> : \n%      .Channel - Selecting the interested channel in Time-Frequency domain\n%                 (e.g. {'Channel', {'C4'}})\n%      .Interval - Selecting the interested time intervals\n%                 (e.g. {'Interval' , '[-2000 3000]'})\n%\n% Return:\n%    data:  Epoched data structure\n%\n% See also:\n%    opt_cellToStruct , visual_timef\n%\n% Reference:\n%         1. C. Brunner, A. Delorme, and S. Makeig, \"EEGLAB?An Open Source \n%          Matlab Toolbox for Electrophysiological Research,\" Biomedical Engineering/Biomedizinische Technik, 2013, pp.1-2.\n%         2. EEGLAB tutorial (http://sccn.ucsd.edu/eeglab/)\n%          Author: Sigurd Enghoff, Arnaud Delorme & Scott Makeig\n%          CNL / Salk Institute 1998- | SCCN/INC, UCSD 2002-\n%\n%         We used EEGLAB open source toolbox code related in ERSP (timef.m)  \n%\n%  \n% Ji Hoon, Jeong\n% jh_jeong@korea.ac.kr\n%\n%%\ndat = data;\nopt = opt_cellToStruct(varargin{:});\nchinx = find(strcmp(dat.chan,opt.Channel)==1);\neeg = [];\n\nif ndims(dat.x) == 2\n    if ~isfield(opt,'Interval')\n        warning('OpenBMI: please input the data intervals');return;\n    end\n    dat = prep_segmentation(dat, {'interval',opt.Interval});\n    dat.x = dat.x(:,:,chinx);\n    eeg = reshape(dat.x , [size(dat.x,1)*size(dat.x,2) 1])';\nelseif ndims(dat.x) == 3\n    dat.x = dat.x(:,:,chinx);\n    eeg = reshape(dat.x , [size(dat.x,1)*size(dat.x,2) 1])';\nend\n\nfigure; \nersp = visual_timef(eeg, size(dat.x,1), [dat.ival(1) dat.ival(end)], dat.fs, [3 0.5], 'plotersp','on','plotitc','off');\n\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/BMI_modules/Visualization/visual_ERSP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.578833346051366}}
{"text": "function aIdx = getPaddingIndices22(aSize,padSize,method,direction)\n%getPaddingIndices is used by padarray and blockproc. \n%   Computes padding indices of input image.  This is function is used to\n%   handle padding of in-memory images (via padarray) as well as\n%   arbitrarily large images (via blockproc).\n%\n%   aSize : result of size(I) where I is the image to be padded\n%   padSize : padding amount in each dimension.  \n%             numel(padSize) can be greater than numel(aSize)\n%   method : X or a 'string' padding method\n%   direction : pre, post, or both.\n%\n%   See the help for padarray for additional information.\n\n% Copyright 2010 The MathWorks, Inc.\n\n% make sure we have enough image dims for the requested padding\nif numel(padSize) > numel(aSize)\n    singleton_dims = numel(padSize) - numel(aSize);\n    aSize = [aSize ones(1,singleton_dims)];\nend\n\nswitch method\n    case 'circular'\n        aIdx = CircularPad(aSize, padSize, direction);\n    case 'symmetric'\n        aIdx = SymmetricPad(aSize, padSize, direction);\n    case 'replicate' \n        aIdx = ReplicatePad(aSize, padSize, direction);\nend\n\n\n%%%\n%%% CircularPad\n%%%\nfunction idx = CircularPad(aSize, padSize, direction)\n\nnumDims = numel(padSize);\n\n% Form index vectors to subsasgn input array into output array.\n% Also compute the size of the output array.\nidx   = cell(1,numDims);\nfor k = 1:numDims\n    M = aSize(k);\n    dimNums = uint32(1:M);\n    p = padSize(k);\n    \n    switch direction\n        case 'pre'\n            idx{k}   = dimNums(mod(-p:M-1, M) + 1);\n            \n        case 'post'\n            idx{k}   = dimNums(mod(0:M+p-1, M) + 1);\n            \n        case 'both'\n            idx{k}   = dimNums(mod(-p:M+p-1, M) + 1);\n            \n    end\nend\n\n\n%%%\n%%% SymmetricPad\n%%%\nfunction idx = SymmetricPad(aSize, padSize, direction)\n\nnumDims = numel(padSize);\n\n% Form index vectors to subsasgn input array into output array.\n% Also compute the size of the output array.\nidx   = cell(1,numDims);\nfor k = 1:numDims\n    M = aSize(k);\n    dimNums = uint32([1:M M:-1:1]);\n    p = padSize(k);\n    \n    switch direction\n        case 'pre'\n            idx{k}   = dimNums(mod(-p:M-1, 2*M) + 1);\n            \n        case 'post'\n            idx{k}   = dimNums(mod(0:M+p-1, 2*M) + 1);\n            \n        case 'both'\n            idx{k}   = dimNums(mod(-p:M+p-1, 2*M) + 1);\n    end\nend\n\n\n%%%\n%%% ReplicatePad\n%%%\nfunction idx = ReplicatePad(aSize, padSize, direction)\n\nnumDims = numel(padSize);\n\n% Form index vectors to subsasgn input array into output array.\n% Also compute the size of the output array.\nidx   = cell(1,numDims);\nfor k = 1:numDims\n    M = aSize(k);\n    p = padSize(k);\n    onesVector = uint32(ones(1,p));\n    \n    switch direction\n        case 'pre'\n            idx{k}   = [onesVector 1:M];\n            \n        case 'post'\n            idx{k}   = [1:M M*onesVector];\n            \n        case 'both'\n            idx{k}   = [onesVector 1:M M*onesVector];\n    end\nend\n\n", "meta": {"author": "yangyan92", "repo": "Deep-ADMM-Net", "sha": "f95738c6629364c87e0534a2a0bbf75843693ed7", "save_path": "github-repos/MATLAB/yangyan92-Deep-ADMM-Net", "path": "github-repos/MATLAB/yangyan92-Deep-ADMM-Net/Deep-ADMM-Net-f95738c6629364c87e0534a2a0bbf75843693ed7/util/getPaddingIndices22.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5788333458816604}}
{"text": "function TR=IcosahedronMesh\n% Name speaks for itself.\n\n% Get the vertex coordinates\nt=(1+sqrt(5))/2; % golden ratio\nx=[0 1 t];\ns=[1 1 1; 1 1 -1; 1 -1 -1; 1 -1 1];\nx=repmat(x,[4 1]).*s;\nx=[x;circshift(x,[0 -1]);circshift(x,[0 -2])];\nx_L2=sqrt(sum(x.^2,2));\nx=bsxfun(@rdivide,x,x_L2);\n\n% Triangulate the points\nTri = fliplr(convhulln(x));\nTR=TriRep(Tri,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/ThirdPartyToolbox/SphereUniformSamplingToolbox/IcosahedronMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5788333294632756}}
{"text": "function dat= proc_movingAverage(dat, ms, varargin)\n%PROC_MOVINGAVERAGE - Moving average (low-pass) filter\n%\n%Usage:\n% DAT= proc_movingAverage(DAT, MSEC, <METHOD='causal'>)\n%\n%Input:\n% DAT    - data structure of continuous or epoched data\n% MSEC   - length of interval in which the moving average is\n%          to be calculated, unit [msec].\n% METHOD - 'centered' or 'causal' (default).\n%\n%Output:\n% DAT    - updated data structure\n\n% Author(s): Benjamin Blankertz\n\n\nmisc_checkType(dat, 'STRUCT(x fs)');\nmisc_checkType(ms, '!DOUBLE[1]');\n\nnSamples = round(ms*dat.fs/1000);\ndat.x(:,:)= procutil_movingAverage(dat.x(:,:), nSamples, varargin{:});\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/processing/proc_movingAverage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5788005247421903}}
{"text": "function [U] = dualquatlbs(V,DQ,W)\n  % DUALQUATLBS Compute dual quaternions linear blend skinning deformation of\n  % vertices V, using rigid transformations stored as dual quaternions, DQ, at\n  % some control points, propogated to the mesh using weights W.\n  %\n  % [U] = dualquatlbs(V,DQ,W)\n  % \n  % Inputs:\n  %  V  list of vertex positions\n  %  DQ  list of rigid transformations for each control point stored as dual\n  %    quaternions\n  %    2 by 4 by #controls\n  %  W  weights, # vertices by # handles matrix of weights\n  % Output:\n  %  U  list of new vertex positions\n  %\n  % Copyright 2011, Alec Jacobson (jacobson@inf.ethz.ch)\n  %\n  % See also: lbs\n  %\n\n  % pad V with zeros if not 3D\n  if(size(V,2) ~= 3)\n    was_2d = true;\n    V = [V zeros(size(V,1),1)];\n  else\n    was_2d = false;\n  end\n\n  % number of control points\n  m = size(DQ,3);\n  % should be same in W\n  assert(m == size(W,2));\n\n  % number of domain vertices\n  n = size(V,1);\n\n  % See algorithm 1 in \"Geometric skinning with approximate dual quaternion\n  % blending\" by Kavan et al\n\n  % compute weighted combination of DQs for each domain vertex\n  % DQs seen by every vertex in domain, 2 by 4 by m by n\n  WDQ = permute(repmat(W',[1,1,2,4]),[3 4 1 2]) .* repmat(DQ,[1,1,1,n]);\n  % sum of weighted dual quaternions, 2 by 4 by n\n  VDQ = permute(sum(WDQ,3),[1 2 4 3]);\n  % regular part, n by 4\n  VDQ1 = permute(VDQ(1,:,:),[3 2 1]);\n  % dual part, n by 4\n  VDQ2 = permute(VDQ(2,:,:),[3 2 1]);\n  %VDQ2 = permute(sum(WDQ(2,:,:,:),3),[4 2 1 3]);\n  len = repmat(sqrt(sum(VDQ1.^2,2)),1,4);\n  VDQ1 = VDQ1./len;\n  VDQ2 = VDQ2./len;\n\n  U = ...\n    V + ...\n    2*cross( ...\n      VDQ1(:,2:4), ...\n      cross(VDQ1(:,2:4),V,2)+repmat(VDQ1(:,1),1,3).*V,2) + ...\n    2*( ...\n      repmat(VDQ1(:,1),1,3).*VDQ2(:,2:4) - ...\n      repmat(VDQ2(:,1),1,3).*VDQ1(:,2:4) + ...\n      cross(VDQ1(:,2:4),VDQ2(:,2:4),2));\n\n  %VDQ = zeros([2 size(VDQ1)]);\n  %VDQ(1,:,:) = VDQ1;\n  %VDQ(2,:,:) = VDQ2;\n  %% convert DQs into transformations, multiply against vertices\n  %% convert rotation to quaternion and translation\n  %[Q,T] = udq2quattrans(VDQ);\n  %% convert quaterion\n  %R = quat2mat(Q);\n\n  % unpad U if V was 2D\n  if(was_2d)\n    U = U(:,1:2);\n  end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/dualquatlbs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5788005194971999}}
{"text": "function [Timg, tThreshFDR, n_signif,index_signif, pvals] = dtiTTestImage(Tvalues, DISTR, df, mask)\n%\n% Basic interpretations of the dtiTTest results to produce images and other\n% values related to false discovery rate\n%\n%  [Timg, tThreshFDR, n_signif,index_signif, pvals] = ...\n%         dtiTTestImage(Tvalues, DISTR, df, mask)\n%\n\n\n% Create an image of the results\nTimg = dtiIndToImg(Tvalues, mask, NaN);\n\n% When you view the montage, this sets how many slices we use.\n% showSlices = [20:60];\n% showSlices = [10:50];\n% All the brain containing slices\n% showSlices = [25:50];  % Small number for debugging\n% showSlices = [15:62]; \n% figure; imagesc(makeMontage(Timg,showSlices)); axis image; colormap cool; colorbar;\n% set(gcf,'Name','FA test'); title(sprintf('tthresh, no FDR (p<10^-^4) = %0.1f',tThresh));\n\n\n% Figure out the statistical significance now.\ntThresh = tinv(1-10^-4, df(1));\ntMax = tinv(1-10^-12, df(1));\nTimg(abs(Timg)>tMax) = tMax;\ntMax = max(Timg(:));\n        \n% Perform an FDR analysis for the FA test\n%\nfdrVal = 0.05;   % This is the p-value we are using.\nfdrType = 'general';\nTvalues(isnan(Tvalues)) = 0;\npvals = 1-tcdf(Tvalues, df(1));\n[n_signif,index_signif] = fdr(pvals,fdrVal,fdrType,'mean');\n\n% Convert back to an fThreshold.  Needs more comments.  We think that this\n% function returns the t-value needed to achieve a significance fdrVal, say\n% 0.05 or 0.01.  It is possible that tThreshFDR/tMax is the fThreshold,\n% though the comment in the printf doesn't say that.  It just puts the\n% value in a parenthesis.\nif n_signif > 0\n    tThreshFDR = tinv(1-max(pvals(index_signif)), df(1));\n    fprintf('t-threshold for FDR (%s) when p < %0.3f: %0.2f (%0.3f).\\n',...\n        fdrType,fdrVal,tThreshFDR,tThreshFDR/tMax);\nelse\n    tThreshFDR = [];\n    fprintf('Nothing returned as significant');\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/mrScripts/diffusion/dtiTTestImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357569, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5788005168747046}}
{"text": "%% =======================================================================\n%  ARDrone Simulation Example: Hovering and Position Control\n%  =======================================================================\n%  \n%  The simulation is used to validate the controller and guidance logic of\n%  the ARDRone before flight testing. Control blocks are\n%  exactly the same for both simulation and real-time Wi-Fi control.\n%  \n%  Authors:\n%       David Escobar Sanabria -> descobar@aem.umn.edu\n%       Pieter J. Mosterman -> pieter.mosterman@mathworks.com\n%  =======================================================================\n\n%%\n%  Cleaning workspace\nbdclose all;\nclear all;\nclc\n\n%%\n% Adding ARDrone library path \naddpath ../lib; \n%% Simulation parameters\n\n% Flight management system sample time. This is the sample time at which\n% the control law is executed. \nFMS.Ts = 0.065; \n\n% Time delay due to communication between drone and host computer\ntimeDelay = FMS.Ts*4; \n\n\n%% Vehicle model based on linear dynamics\n\n% Loading state space representation of vehicle dynamics\nsetupARModel; \n\n%%\n% Loading list of waypoints\nwaypoints = getWaypoints() ;\n\n\n%% \n% Simulation time\nsimDT = 0.005 ;\n\n%%\n% Loading Simulink model of ARDrone\nARDroneHoverSim ;\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/43719-ar-drone-simulink-development-kit-v1/ARDroneSimulinkDevKit_V1/simulation/setupHoverSim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5787313280290574}}
{"text": "function varargout = ChristoffelTensor(S,varargin)\n% Christoffel tensor of an elasticity tensor for a given direction\n%\n% Formula: E_jk = C_ijkl n_j n_l\n%\n% Input\n%  S - elatic compliance @tensor\n%  x - list of @vector3d\n%\n% Output\n%  E - Christoffel @tensor\n%\n% See also\n% tensor/directionalMagnitude tensor/rotate\n\n% take formula using stiffness\n[varargout{1:nargout}] = ChristoffelTensor(inv(S),varargin{:});\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/ChristoffelTensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5787313246426097}}
{"text": "% DMRG eigenvalue solver.\n%   function [x,theta,testdata]=dmrg_eig(A, tol, varargin)\n% Tries to solve the lowest eigenvalue (ground state) problem A*x=theta*x\n% using the DMRG iteration.\n% With default parameters, reconstructs the genuine 2-site DMRG for one\n% targeted state, without enrichments.\n% However, it can also work as the \"block 1-site DMRG\" from ref. [*], where\n% at least 2 states must be targeted, but only one block at a time can be\n% considered. See parameters 'b' and 'numblocks' below.\n%\n% A must be a Hermitian matrix in the tt_matrix format,\n% tol is the relative truncation/stopping threshold,\n% varargin may contain a sequence of tuning parameters of the form \n% 'parameter1_name', parameter1_value, 'parameter2_name', parameter2_value\n% and so on. Available parameters and default values are the following.\n%   o b: Number of eigenpairs targeted (default: 1)\n%   o numblocks: Number of TT blocks included into the current supercore.\n%       Can be either 2 for 2-site dmrg, or 1 for 1-site dmrg (default: 2)\n%   o nswp: maximal number of DMRG sweeps (default: 20)\n%   o max_full_size: if the local system size (rx(i)*n(i)*rx(i+1)) is less\n%       than max_full_size, the local problem is solved via eig, otherwise via\n%       lobpcg (iteratively) (default: 50)\n%   o local_iters: maximal number of the lobpcg iterations (default: 100)\n%   o usemex: whether shall we use the optimized MEX library eig3d_primme\n%       instead of lobpcg. It safely switches off automatically if\n%       eig3d_primme is not found in the MATLAB path, as well as on complex\n%       data. To obtain eig3d_primme, you need to compile it in the\n%       TT-Toolbox/fmex directory, please follow instructions there (default: true)\n%   o resid_damp: residual gap for the local solvers, i.e. the real\n%       threshold for e.g. lobpcg is tol/(sqrt(d)*resid_damp) (default: 2)\n%   o trunc_norm: truncation strategy: either the standard Frobenius norm\n%       ('fro'), or the residual ('resid') (default: 'fro')\n%   o rmax: maximal TT rank (bond dimension) allowed (default: Inf)\n%   o tol_exit: stopping tolerance (default: tol)\n%   o verb: verbosity level: silent (0), sweep info (1), block info (2) or\n%       the full debug returned in the testdata output (3) (default: 1)\n%   o kickrank: size of the random enrichment (default: 0)\n%   o x0: Initial guess in the tt_tensor format (default: random rank-2)\n%\n% Output data are the solution x in the tt_tensor format, \n% the eigenvalue theta, and \n% (optionally) the history for debug (or convergence tests) purposes testdata.\n%\n%\n% Implementation: Sergey Dolgov (sergey.v.dolgov@gmail.com)\n% \n% [*] Dolgov, Khoromskij, Oseledets, Savostyanov,\n% \"Computation of extreme eigenvalues in higher dimensions using block\n% tensor train format\", Comp. Phys. Comm. 2014, http://dx.doi.org/10.1016/j.cpc.2013.12.017\n%\n\n\nfunction [x,theta,testdata]=dmrg_eig(A, tol, varargin)\n% Number of eigenstates\nb = 1;\n% Threshold on the local size between direct-iterative local solving\nmax_full_size=50;\n% Number of local iters\nlocal_iters = 100;\n% Whether shall we use the local solver from the MEX library eig3d_primme\nusemex = true;\n% Number of sweeps\nnswp=20;\n% Residual gap for the local solver\nresid_damp = 2;\n% Truncation strategy\n%trunc_norm = 'resid';\ntrunc_norm = 'fro';\n% Max rank\nrmax = Inf;\n% Exit tol\ntol_exit = tol;\n% Verb\nverb=1;\n% Random enrichment rank\nkickrank = 0;\n% Number of blocks to consider: 2 or 1\nnumblocks = 2;\n% Initial guess\nx=[];\n\nfor i=1:2:length(varargin)-1\n    switch lower(varargin{i})\n        case 'nswp'\n            nswp=varargin{i+1};\n        case 'rmax'\n            rmax=varargin{i+1};\n        case 'x0'\n            x=varargin{i+1};\n        case 'verb'\n            verb=varargin{i+1};\n        case 'resid_damp'\n            resid_damp=varargin{i+1};\n        case 'trunc_norm'\n            trunc_norm=varargin{i+1};\n        case 'kickrank'\n            kickrank=varargin{i+1};\n        case  'max_full_size'\n            max_full_size=varargin{i+1};\n        case  'local_iters'\n            local_iters=varargin{i+1};\n        case 'usemex'\n            usemex=varargin{i+1};\n        case 'tol_exit'\n            tol_exit=varargin{i+1};\n        case 'b'\n            b = varargin{i+1};\n        case 'numblocks'\n            numblocks = varargin{i+1};            \n        otherwise\n            error('Unknown tuning parameter \"%s\"', varargin{i});\n    end;\nend;\n\n% Extract the dimensions\nif (~isa(A, 'tt_matrix'))\n    error('A must be given in a tt_matrix class');\nend;\nd = A.d;\nn = A.n;\n% Initialize from random initial state if not passed otherwise\nif (isempty(x))\n    x = tt_rand(n, d, b, -1);\nelse\n    if (~isa(x, 'tt_tensor'))\n        error('x0 must be given in a tt_tensor class');\n    end;\n    if (x.d~=d)\n        error('Inconsistent dim(A) and dim(x0)');\n    end;\n    if (any(x.n~=n))\n        error('Inconsistent size(A) and size(x0)');\n    end;\nend;\n\n% Disable MEX if it does not exist\nif (usemex)&&(exist('eig3d_primme', 'file')<2)\n    warning('MEX local solver is not found, disabled');\n    usemex = false;\nend;\n\n% More housekeeping\nra = A.r;\nrx = x.r;\nif (rx(d+1)>1)\n    % Leave only the first component from the initial guess\n    x = x*eye(rx(d+1),1);\n    rx(d+1) = 1;\nend;\ncrA = core2cell(A);\ncrx = core2cell(x);\n\n% Threshold for local problems\nreal_tol = (tol/sqrt(d))/resid_damp;\n\n% Interfaces\nphixax = cell(d+1,1); phixax{1}=1; phixax{d+1}=1;\n\n% This is some convergence output for test purposes\ntestdata = cell(3,1);\ntestdata{1} = zeros(d-numblocks+1, nswp); % times\ntestdata{2} = zeros(d-numblocks+1, nswp, b); % evs\ntestdata{3} = zeros(d-numblocks+1, nswp); % local res or dx\nt_dmrg_eig = tic;\n\n% Presetup: compute the initial projections\nfor i=d:-1:2\n    % QR (Gauge conditions) right-to-left\n    ux = reshape(crx{i}, rx(i), n(i)*rx(i+1));\n    [ux,vx]=qr(ux.', 0);\n    cr2 = reshape(crx{i-1}, rx(i-1)*n(i-1), rx(i));\n    cr2 = cr2*vx.';\n    rx(i) = size(ux,2);\n    crx{i} = reshape(ux.', rx(i), n(i), rx(i+1));\n    crx{i-1} = reshape(cr2, rx(i-1), n(i-1), rx(i));\n    \n    % Pass the reduction to the left\n    phixax(i) = rightreduce_matrix(phixax(i+1), crx{i}, crA(i), crx{i}, rx(i),n(i),rx(i+1), 1,ra(i),ra(i+1), rx(i),n(i),rx(i+1));\n    if (usemex)&&(~isreal(phixax{i}))\n        warning('Complex data detected, turning MEX local solver off');\n        usemex = false;\n    end;\nend;\n% Initial guess for EVs\ntheta = rightreduce_matrix(phixax(2), crx{1}, crA(1), crx{1}, rx(1),n(1),rx(1+1), 1,ra(1),ra(1+1), rx(1),n(1),rx(1+1));\ntheta = squeeze(theta{1});\nif (usemex)&&(~isreal(theta))\n    warning('Complex data detected, turning MEX local solver off');\n    usemex = false;\nend;\ntheta = diag(theta);\nif (b>1)\n    crx{1} = randn(rx(1), n(1), rx(2), b);\nend;\n\n% DMRG sweeps\nswp = 1;\ni = 1; % Start from the first block\ndir = 1; % Current direction: forward(+1) or backward(-1)\n% Meausure the errors and # of operations\nmax_dx = 0;\nmax_res = 0;\nmax_matvecs = 0;\n\nwhile (swp<=nswp)||(dir>0)\n    % Extract the matrix parts, accelerate a plenty of iterations with them\n    % Phi1: 1, rx'1, rx1, ra1\n    % Phi2: ra2, rx'2, rx2, 1\n    Phi1 = phixax(i); \n    A1 = crA(i);\n    if (numblocks==1)\n        % one-block DMRG, everything is ready\n        Phi2 = phixax(i+1);\n        rx1 = rx(i);\n        nloc = n(i);\n        rx2 = rx(i+1);\n        ra1 = ra(i);\n        ra2 = ra(i+1);\n        % sol_prev. It is also an initial guess.\n        sol_prev = reshape(crx{i}, rx(i)*n(i)*rx(i+1), b);\n    else\n        % Two-block DMRG, we have to merge some of two blocks into one.\n        Phi2 = phixax(i+2);\n        A2 = crA(i+1);\n        if ((rx(i)*n(i))<=(n(i)*n(i+1)))&&((rx(i)*n(i))<=(n(i+1)*rx(i+2)))\n            % Merge Phi1 and A1\n            Phi1 = reshape(Phi1{1}, rx(i)*rx(i), ra(i));\n            A1 = reshape(A1{1}, ra(i), n(i)*n(i)*ra(i+1));\n            Phi1 = Phi1*A1;\n            Phi1 = reshape(Phi1, rx(i), rx(i), n(i), n(i)*ra(i+1));\n            Phi1 = permute(Phi1, [1,3,2,4]);\n            Phi1 = {reshape(Phi1, rx(i)*n(i), rx(i)*n(i), ra(i+1))};\n            A1 = A2;\n            rx1 = rx(i)*n(i);\n            nloc = n(i+1);\n            rx2 = rx(i+2);\n            ra1 = ra(i+1);\n            ra2 = ra(i+2);\n        elseif ((n(i)*n(i+1)<=(rx(i)*n(i))))&&((n(i)*n(i+1))<=(n(i+1)*rx(i+2)))\n            % Merge A1 and A2\n            A1 = reshape(A1{1}, ra(i)*n(i)*n(i), ra(i+1));\n            A2 = reshape(A2{1}, ra(i+1), n(i+1)*n(i+1)*ra(i+2));\n            A1 = A1*A2;\n            A1 = reshape(A1, ra(i)*n(i), n(i), n(i+1), n(i+1)*ra(i+2));\n            A1 = permute(A1, [1,3,2,4]);\n            A1 = {reshape(A1, ra(i), n(i)*n(i+1), n(i)*n(i+1), ra(i+2))};\n            rx1 = rx(i);\n            nloc = n(i)*n(i+1);\n            rx2 = rx(i+2);\n            ra1 = ra(i);\n            ra2 = ra(i+2);\n        else\n            % Merge A2 and Phi2\n            Phi2 = reshape(Phi2{1}, ra(i+2), rx(i+2)*rx(i+2));\n            A2 = reshape(A2{1}, ra(i+1)*n(i+1)*n(i+1), ra(i+2));\n            Phi2 = A2*Phi2;\n            Phi2 = reshape(Phi2, ra(i+1)*n(i+1), n(i+1), rx(i+2), rx(i+2));\n            Phi2 = permute(Phi2, [1,3,2,4]);\n            Phi2 = {reshape(Phi2, ra(i+1), n(i+1)*rx(i+2), n(i+1)*rx(i+2))};\n            rx1 = rx(i);\n            nloc = n(i);\n            rx2 = n(i+1)*rx(i+2);\n            ra1 = ra(i);\n            ra2 = ra(i+1);\n        end;\n        % sol_prev. It is also an initial guess.\n        if (dir>0)\n            sol_prev = reshape(crx{i}, rx(i)*n(i)*rx(i+1), b);\n            sol_prev = sol_prev.';\n            sol_prev = reshape(sol_prev, b*rx(i)*n(i), rx(i+1));\n            sol_prev = sol_prev*reshape(crx{i+1}, rx(i+1), n(i+1)*rx(i+2));\n            sol_prev = reshape(sol_prev, b, rx(i)*n(i)*n(i+1)*rx(i+2));\n            sol_prev = sol_prev.';\n        else\n            sol_prev = reshape(crx{i+1}, rx(i+1), n(i+1)*rx(i+2)*b);\n            sol_prev = reshape(crx{i}, rx(i)*n(i), rx(i+1))*sol_prev;\n            sol_prev = reshape(sol_prev, rx(i)*n(i)*n(i+1)*rx(i+2), b);\n        end;\n    end;\n    \n    % Initial residual\n    res_prev = norm(local_matvec(sol_prev, rx1,nloc,rx2,b, rx1,nloc,rx2, Phi1, A1, Phi2, 1,ra1,ra2)-sol_prev*diag(theta));\n    \n    if (rx1*nloc*rx2<max_full_size) % Full solution\n        %      |     |    |\n        % B = Phi1 - A1 - Phi2\n        %      |     |    |\n        Bxx = assemble_local_matrix(Phi1, A1, Phi2, 1,ra1,ra2, rx1,nloc,rx2, rx1,nloc,rx2);\n        Bxx = (Bxx+Bxx')*0.5; % Ensure the symmetry. At least now...\n        [sol,L]=eig(Bxx);\n        L = diag(L);\n        L = real(L); % exclude possible i*1e-15 noise\n        [~,ind] = sort(L, 'ascend');\n        theta = L(ind(1:b));\n        sol = sol(:,ind(1:b));\n        num_matvecs = 1;\n    else % Iterative solution\n        if (usemex)\n            Phi1m = reshape(Phi1{1}, rx1, rx1, ra1);\n            Phi2m = reshape(Phi2{1}, ra2*rx2, rx2);\n            Phi2m = Phi2m.';\n            Phi2m = reshape(Phi2m, rx2, ra2, rx2);\n            A1m = reshape(A1{1}, ra1, nloc, nloc, ra2);\n            [sol,theta, num_matvecs]=eig3d_primme(Phi1m,A1m,Phi2m,real_tol,b,sol_prev,local_iters);\n        else\n            [sol,theta,~,lambdaHistory]=lobpcg(sol_prev,@(x)local_matvec(x, rx1,nloc,rx2,[], rx1,nloc,rx2, Phi1, A1, Phi2, 1,ra1,ra2),  real_tol, local_iters);\n            num_matvecs = numel(lambdaHistory);\n        end;\n    end;\n    \n    % count the number of MatVecs\n    max_matvecs = max(max_matvecs, num_matvecs);\n    \n    if (~strcmp(trunc_norm, 'fro'))\n        % We need the new residual for the corresp. trunc. strategy\n        res_new = norm(local_matvec(sol, rx1,nloc,rx2,b, rx1,nloc,rx2, Phi1, A1, Phi2, 1,ra1,ra2)-sol*diag(theta));\n    end;\n\n    % L2-norm convergence check. \n    dx = norm(sol*(sol'*sol_prev)-sol_prev);\n    max_dx = max(max_dx, dx);\n    max_res = max(max_res, res_prev);\n    \n    if ((dir>0)&&(i<d))||((dir<0)&&(i>1))||(numblocks==2) % SVD and enrichment\n        if (dir>0)\n            if (numblocks==2)\n                % In 2-block DMRG, we have to separate modes\n                sol = reshape(sol, rx(i)*n(i), n(i+1)*rx(i+2)*b);\n            else\n                sol = reshape(sol, rx(i)*n(i), rx(i+1)*b);\n            end;\n        else\n            sol = sol.';\n            if (numblocks==2)\n                % In 2-block DMRG, we have to separate modes\n                sol = reshape(sol, b*rx(i)*n(i), n(i+1)*rx(i+2));\n            else\n                sol = reshape(sol, b*rx(i), n(i)*rx(i+1));\n            end;\n        end;\n        \n        [ux,s,vx]=svd(sol, 'econ');\n        s = diag(s);\n        \n        if (strcmp(trunc_norm, 'fro')) % Fro-norm truncation\n            r = my_chop2(s, real_tol*resid_damp*norm(s));\n        else\n            % Residual truncation\n            % start from the old rank\n            r = min([rx(i),rx(i+1),numel(s)]);\n            cursol = ux(:,1:r)*diag(s(1:r))*vx(:,1:r)';\n            if (dir>0)\n                cursol = reshape(cursol, rx1*nloc*rx2, b);\n            else\n                cursol = reshape(cursol, b, rx1*nloc*rx2);\n                cursol = cursol.';\n            end;\n            res = norm(local_matvec(cursol, rx1,nloc,rx2,b, rx1,nloc,rx2, Phi1, A1, Phi2, 1,ra1,ra2)-cursol*diag(theta));\n            if (res<max(real_tol, res_new)*resid_damp)\n                drank = -1; % rank is overestimated; decrease\n            else\n                drank = 1; % residual is large; increase the rank\n            end;\n            while (r>0)&&(r<=numel(s))\n                cursol = ux(:,1:r)*diag(s(1:r))*vx(:,1:r)';\n                if (dir>0)\n                    cursol = reshape(cursol, rx1*nloc*rx2, b);\n                else\n                    cursol = reshape(cursol, b, rx1*nloc*rx2);\n                    cursol = cursol.';\n                end;\n                res = norm(local_matvec(cursol, rx1,nloc,rx2,b, rx1,nloc,rx2, Phi1, A1, Phi2, 1,ra1,ra2)-cursol*diag(theta));\n                if (drank>0)\n                    if (res<max(real_tol, res_new)*resid_damp)\n                        break;\n                    end;\n                else\n                    if (res>=max(real_tol, res_new)*resid_damp)\n                        break;\n                    end;\n                end;\n                r = r+drank;\n            end;\n            if (drank<0)\n                r=r+1;\n            end;\n        end;\n        \n        r = min(r, numel(s));\n        r = min(r, rmax);\n        \n        if (verb==2)\n            fprintf('=dmrg_eig= swp=%d, block=%d, dx=%3.3e, r=%d\\n', swp, i, dx, r);\n        end;\n    end;\n    \n    if (dir>0)&&(i<d) % Forward sweep\n        ux = ux(:,1:r);\n        vx = conj(vx(:,1:r))*diag(s(1:r));\n        \n        if (kickrank>0) \n            % Enrich the solution\n            zx = randn(rx(i)*n(i), kickrank);\n            % Concatenate the bases and reinforce the gauges.\n            % In future: insert symmetries here?\n            [ux,rv]=qr([ux,zx], 0);\n            rv = rv(:,1:r);\n            vx = vx*rv.';\n        end;\n        \n        r = size(ux, 2);\n        \n        if (numblocks==1)\n            % Drop the [r x r] factor to the next core -- White's prediction\n            cr2 = crx{i+1};\n            cr2 = reshape(cr2, rx(i+1), n(i+1)*rx(i+2));\n            vx = reshape(vx, rx(i+1), b*r);\n            cr2 = vx.'*cr2;\n            cr2 = reshape(cr2, b, r*n(i+1)*rx(i+2));\n            cr2 = cr2.';\n        else\n            % Replace the next core by vx\n            cr2 = vx.';            \n            cr2 = reshape(cr2, r, n(i+1), rx(i+2), b);\n        end;\n        \n        % Stuff them back\n        rx(i+1) = r;\n        crx{i} = reshape(ux, rx(i), n(i), rx(i+1));\n        crx{i+1} = reshape(cr2, rx(i+1), n(i+1), rx(i+2), b);\n        \n        % Compute new reductions\n        phixax(i+1) = leftreduce_matrix(phixax(i), ux, crA(i), ux, rx(i),n(i),rx(i+1), 1,ra(i),ra(i+1), rx(i),n(i),rx(i+1));       \n    elseif (dir<0)&&((i>1)||(numblocks==2)) % Backward sweep\n        vx = conj(vx(:,1:r));\n        ux = ux(:,1:r)*diag(s(1:r));\n        \n        if (kickrank>0)\n            % Enrich the solution\n            if (numblocks==1)\n                zx = randn(n(i)*rx(i+1), kickrank);\n            else\n                zx = randn(n(i+1)*rx(i+2), kickrank);\n            end;\n            % Concatenate the bases and reinforce the gauges.\n            % In future: insert symmetries here?\n            [vx,rv]=qr([vx,zx], 0);\n            rv = rv(:,1:r);\n            ux = ux*rv.';\n        end;\n        \n        r = size(vx, 2);\n        \n        if (numblocks==1)\n            % Drop the [r x r] factor to the next core -- White's prediction\n            cr2 = crx{i-1};\n            cr2 = reshape(cr2, rx(i-1)*n(i-1), rx(i));\n            ux = reshape(ux, b, rx(i)*r);\n            ux = ux.';\n            ux = reshape(ux, rx(i), r*b);\n            cr2 = cr2*ux;\n            cr2 = reshape(cr2, rx(i-1), n(i-1), r, b);            \n            % Stuff them back\n            rx(i) = r;\n            vx = vx.';\n            crx{i} = reshape(vx, rx(i), n(i), rx(i+1));\n            crx{i-1} = reshape(cr2, rx(i-1), n(i-1), rx(i), b);            \n            % Compute new reductions\n            phixax(i) = rightreduce_matrix(phixax(i+1), vx, A1, vx, rx(i),n(i),rx(i+1), 1,ra(i),ra(i+1), rx(i),n(i),rx(i+1));            \n        else\n            % Replace both cores\n            vx = vx.';\n            vx = reshape(vx, r, n(i+1), rx(i+2));\n            ux = reshape(ux, b, rx(i)*n(i)*r);\n            ux = ux.';            \n            rx(i+1) = r;\n            crx{i+1} = vx;\n            crx{i} = reshape(ux, rx(i), n(i), r, b);\n            % Compute new reductions\n            phixax(i+1) = rightreduce_matrix(phixax(i+2), vx, crA(i+1), vx, rx(i+1),n(i+1),rx(i+2), 1,ra(i+1),ra(i+2), rx(i+1),n(i+1),rx(i+2));\n        end;\n    else\n        % Just stuff back the last core\n        sol = reshape(sol, rx(i), n(i), rx(i+1), b);\n        crx{i} = sol;\n    end;\n    \n    if (verb>2)\n        % Report the debug data if necessary\n        if (dir>0)\n            testdata{1}(i,swp) = toc(t_dmrg_eig);\n            testdata{2}(i,swp,:) = theta;\n            if (strcmp(trunc_norm, 'fro'))\n                testdata{3}(i,swp) = dx;\n            else\n                testdata{3}(i,swp) = res_prev;\n            end;\n        else\n            testdata{1}(d-numblocks+2-i,swp) = toc(t_dmrg_eig);\n            testdata{2}(d-numblocks+2-i,swp,:) = theta;\n            if (strcmp(trunc_norm, 'fro'))\n                testdata{3}(d-numblocks+2-i,swp) = dx;\n            else\n                testdata{3}(d-numblocks+2-i,swp) = res_prev;\n            end;\n        end;\n    end;\n    \n    i = i+dir;\n    \n    % Check for the end of the sweep\n    if ((dir>0)&&(i>d-numblocks+1))||((dir<0)&&(i<1))\n        % Report all\n        if (verb>0)\n            fprintf('=dmrg_eig= sweep %d, max_dx: %3.3e, max_res: %3.3e, erank: %g, theta: %3.15e, mv: %d\\n', swp, max_dx, max_res, sqrt(rx(1:d)'*(n.*rx(2:d+1))/sum(n)), sum(theta), max_matvecs);\n        end;\n        \n        % Check the stops\n        if (strcmp(trunc_norm, 'fro'))\n            if (max_dx<tol_exit)&&(verb<3)&&(dir>0)\n                break;\n            end;\n        else\n            if (max_res<tol_exit)&&(verb<3)&&(dir>0)\n                break;\n            end;\n        end;\n        \n        swp = swp+1;\n        % Go backward\n        dir = -dir;\n        i = i+dir;\n        % Clear the errors\n        max_dx = 0;\n        max_res = 0;\n        max_matvecs = 0;\n    end;\nend;\n\ncrx{d} = reshape(crx{d}, rx(d), n(d), b);\nx = cell2core(tt_tensor, crx);\n\nend\n\n\n% Accumulates the left reduction W{1:k}'*A{1:k}*X{1:k}\nfunction [WAX2] = leftreduce_matrix(WAX1, w, A, x, rw1,n,rw2, Ra,ra1,ra2, rx1,m,rx2)\n% Left WAX has the form of the first matrix TT block, i.e. [rw, rx, ra]\nWAX2 = WAX1;\nwc = reshape(w, rw1, n*rw2);\nxc = reshape(x, rx1*m, rx2);\nfor k=1:Ra\n    WAX2{k} = reshape(WAX2{k}, rw1, rx1*ra1(k));\n    WAX2{k} = wc'*WAX2{k}; % size n rw2 x rx1 ra1\n    WAX2{k} = reshape(WAX2{k}, n, rw2*rx1*ra1(k));\n    WAX2{k} = WAX2{k}.';\n    WAX2{k} = reshape(WAX2{k}, rw2*rx1, ra1(k)*n);\n    tmp = reshape(A{k}, ra1(k)*n, m*ra2(k));\n    WAX2{k} = WAX2{k}*tmp; % size rw2 rx1 m ra2\n    WAX2{k} = reshape(WAX2{k}, rw2, rx1*m*ra2(k));\n    WAX2{k} = WAX2{k}.';\n    WAX2{k} = reshape(WAX2{k}, rx1*m, ra2(k)*rw2);\n    WAX2{k} = xc.'*WAX2{k}; % size rx2, ra2 rw2\n    WAX2{k} = reshape(WAX2{k}, rx2*ra2(k), rw2);\n    WAX2{k} = WAX2{k}.';\nend;\nend\n\n% Accumulates the right reduction W{k:d}'*A{k:d}*X{k:d}\nfunction [WAX1] = rightreduce_matrix(WAX2, w, A, x, rw1,n,rw2, Ra,ra1,ra2, rx1,m,rx2)\n% Right WAX has the form of the last matrix TT block, i.e. [ra, rw, rx]\nWAX1 = WAX2;\nwc = reshape(w, rw1, n*rw2);\nwc = conj(wc);\nxc = reshape(x, rx1*m, rx2);\nfor k=1:Ra\n    WAX1{k} = reshape(WAX1{k}, ra2(k)*rw2, rx2);\n    WAX1{k} = xc*WAX1{k}.'; % size rx1 m x ra2 rw2\n    WAX1{k} = reshape(WAX1{k}, rx1, m*ra2(k)*rw2);\n    WAX1{k} = WAX1{k}.';\n    WAX1{k} = reshape(WAX1{k}, m*ra2(k), rw2*rx1);\n    tmp = reshape(A{k}, ra1(k)*n, m*ra2(k));\n    WAX1{k} = tmp*WAX1{k}; % size ra1(k)*n, rw2*rx1\n    WAX1{k} = reshape(WAX1{k}, ra1(k), n*rw2*rx1);\n    WAX1{k} = WAX1{k}.';\n    WAX1{k} = reshape(WAX1{k}, n*rw2, rx1*ra1(k));\n    WAX1{k} = wc*WAX1{k}; % size rw1, rx1 ra1\n    WAX1{k} = reshape(WAX1{k}, rw1*rx1, ra1(k));\n    WAX1{k} = WAX1{k}.';\nend;\nend\n\n% A matrix-vectors product for the matrix in the 3D TT (WAX1-A-WAX2), and\n% full vectors of size (rx1*m*rx2) x b. Returns (rw1*n*rw2) x b\nfunction [w]=local_matvec(x, rx1,m,rx2,b, rw1,n,rw2, WAX1, A, WAX2, Ra,ra1,ra2)\nxc = reshape(x, rx1*m*rx2, []);\nif (isempty(b))\n    b = size(xc, 2);\nend;\nw = zeros(rw1*n*rw2, b);\nxc = xc.';\nxc = reshape(xc, b*rx1*m, rx2);\nfor k=1:Ra\n    tmp = reshape(WAX2{k}, ra2(k)*rw2, rx2);\n    wk = xc*tmp.';\n    wk = reshape(wk, b*rx1, m*ra2(k)*rw2);\n    wk = wk.';\n    wk = reshape(wk, m*ra2(k), rw2*b*rx1);\n    tmp = reshape(A{k}, ra1(k)*n, m*ra2(k));\n    wk = tmp*wk;\n    wk = reshape(wk, ra1(k)*n*rw2*b, rx1);\n    wk = wk.';\n    wk = reshape(wk, rx1*ra1(k), n*rw2*b);\n    tmp = reshape(WAX1{k}, rw1, rx1*ra1(k));\n    wk = tmp*wk;\n    wk = reshape(wk, rw1*n*rw2, b);\n    w = w+wk;\nend;\nend\n\n% Builds the full (rw1*n*rw2) x (rx1*m*rx2) matrix from its TT blocks\nfunction [B,sparseflag]=assemble_local_matrix(WAX1, A, WAX2, Ra,ra1,ra2, rw1,n,rw2, rx1,m,rx2)\n% Check the sparsity of the matrix blocks\nsparseflag = true;\nfor k=1:Ra\n    if (~issparse(A{k}))\n        sparseflag=false;\n    end;\nend;\nif (sparseflag)\n    B = sparse(rw2*rw1*n, rx2*rx1*m); % reverse order !!!\n    % The reverse order is needed since usually the n x m part is large and\n    % sparse, so let it be the senior dimension.\n    % Note that currently only canonical sparse matrices are allowed\n    for k=1:Ra\n        tmp = reshape(WAX2{k}, rw2, rx2);\n        tmp = sparse(tmp);\n        Bk = reshape(WAX1{k}, rw1, rx1);\n        Bk = sparse(Bk);\n        Bk = kron(Bk, tmp); % mind endiannes\n        Bk = kron(A{k}, Bk); % mind endiannes\n        B = B+Bk;\n    end;\nelse\n    % There are dense blocks, everything is dense, and in the natural index\n    % order\n    B = zeros(rw1*n*rw2, rx1*m*rx2);\n    for k=1:Ra\n        Bk = reshape(WAX1{k}, rw1*rx1, ra1(k));\n        tmp = reshape(A{k}, ra1(k), n*m*ra2(k));\n        if (issparse(tmp))\n            % Don't mix sparse if we are already full\n            tmp = full(tmp);\n        end;\n        Bk = Bk*tmp;\n        Bk = reshape(Bk, rw1, rx1, n, m*ra2(k));\n        Bk = permute(Bk, [1,3,2,4]);\n        Bk = reshape(Bk, rw1*n*rx1*m, ra2(k));\n        tmp = reshape(WAX2{k}, ra2(k), rw2*rx2);\n        Bk = Bk*tmp;\n        Bk = reshape(Bk, rw1*n, rx1*m, rw2, rx2);\n        Bk = permute(Bk, [1,3,2,4]);\n        Bk = reshape(Bk, rw1*n*rw2, rx1*m*rx2);\n        B = B+Bk;\n    end;\nend;\nend\n\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/solve/dmrg_eig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5787313106952943}}
{"text": "function y = m_sxbfbt(x_it,aparams,mparams)\n%m_sxbfbt   ideal stabilized least squares commutator preconditioner\n%   y = m_sxbfbt(x_it,aparams,mparams);\n%   input\n%          x_it         operand for preconditioning operator\n%          aparams      structure defining coefficient matrix\n%          mparams      structure defining preconditioning matrix\n%   output\n%          y            result of preconditioning operation\n%\n%   IFISS function: HCE; 15 March 2005.\n\nnv = length(aparams.F);\nnu = nv/2;\nnp = size(aparams.B,1);\nGdiag=spdiags(diag(mparams.G),0,nv,nv);\n\nsigma = mparams.viscosity;\n\nrv=x_it(1:nv); rp=x_it(nv+1:nv+np);\n\n%% pressure solve\nxB = (Gdiag\\aparams.B')';\nBBt = aparams.B*xB';\n   \nif mparams.domain==1,\n   n_null = mparams.n_null;\n   minor = [1:n_null-1,n_null+1:np]';\n   rp1 = zeros(np,1);\n   rp1(minor) = (BBt(minor,minor)+mparams.Cp1(minor,minor))\\rp(minor);\n   rp2 =  xB*(aparams.F*(xB'*rp1)) + sigma*(mparams.Cp2*rp1);\n   zp = zeros(np,1);\n   zp(minor) = - (BBt(minor,minor)+mparams.Cp1(minor,minor))\\rp2(minor);\nelse \n   zp = (BBt+mparams.Cp1)\\rp;\n   zp = -(BBt+mparams.Cp1) \\ (xB*(aparams.F*(xB'*zp)) + sigma*(mparams.Cp2*zp) );\nend \n\n%% velocity solve\nrv = rv-(aparams.B')*zp;\nzv = aparams.F \\ rv;\ny = [zv;zp];\n", "meta": {"author": "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/m_sxbfbt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5787313096333997}}
{"text": "function L = watershedsegment(bw)\n\nD = bwdist(~bw);\nD = -D;\nD(~bw) = -Inf;\nL = watershed(D);", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/watershedsegment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5787313049842944}}
{"text": "classdef MOMBIII < ALGORITHM\n% <multi/many> <real/integer/label/binary/permutation>\n% Many objective metaheuristic based on the R2 indicator II\n% alpha   ---   0.5 --- Threshold of variances\n% epsilon --- 0.001 --- Tolerance threshold\n% record  ---     5 --- The record size of nadir vectors\n\n%------------------------------- Reference --------------------------------\n% R. Hernandez Gomez and C. A. Coello Coello, Improved metaheuristic based\n% on the R2 indicator for many-objective optimization, Proceedings of the\n% Annual Conference on Genetic and Evolutionary Computation, 2015, 679-686.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Parameter setting\n            [alpha,epsilon,recordSize] = Algorithm.ParameterSet(0.5,0.001,5);\n\n            %% Generate random population\n            [W,Problem.N] = UniformPoint(Problem.N,Problem.M);\n            Population    = Problem.Initialization();\n            % Ideal and nadir points\n            zmin = min(Population.objs,[],1);\n            zmax = max(Population.objs,[],1);\n            % For storing the nadir vectors of a few generations\n            Record = repmat(zmax,recordSize,1);\n            % For storing whether each objective has been marked for a few\n            % generations\n            Mark = false(recordSize,Problem.M);\n            % R2 ranking procedure\n            [Rank,Norm] = R2Ranking(Population.objs,W,zmin,zmax);\n\n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                MatingPool  = TournamentSelection(2,Problem.N,Rank,Norm);\n                Offspring   = OperatorGA(Problem,Population(MatingPool));\n                Population  = [Population,Offspring];\n                [Rank,Norm] = R2Ranking(Population.objs,W,zmin,zmax);\n                [~,rank]    = sortrows([Rank,Norm]);\n                Population  = Population(rank(1:Problem.N));\n                Rank        = Rank(rank(1:Problem.N));\n                Norm        = Norm(rank(1:Problem.N));\n                [zmin,zmax,Record,Mark] = UpdateReferencePoints(Population.objs,zmin,zmax,Record,Mark,alpha,epsilon);\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/Algorithms/Multi-objective optimization/MOMBI-II/MOMBIII.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5787312992732945}}
{"text": "function d = stoi(x, y, fs_signal)\n% The Short-Time Objective Intelligibility measure \n%   d = stoi(x, y, fs_signal) returns the output of the short-time\n%   objective intelligibility (STOI) measure described in [1, 2], where x \n%   and y denote the clean and processed speech, respectively, with sample\n%   rate fs_signal in Hz. The output d is expected to have a monotonic \n%   relation with the subjective speech-intelligibility, where a higher d \n%   denotes better intelligible speech. See [1, 2] for more details.\n%\n%   References:\n%      [1] C.H.Taal, R.C.Hendriks, R.Heusdens, J.Jensen 'A Short-Time\n%      Objective Intelligibility Measure for Time-Frequency Weighted Noisy\n%      Speech', ICASSP 2010, Texas, Dallas.\n%\n%      [2] C.H.Taal, R.C.Hendriks, R.Heusdens, J.Jensen 'An Algorithm for \n%      Intelligibility Prediction of Time-Frequency Weighted Noisy Speech', \n%      IEEE Transactions on Audio, Speech, and Language Processing, 2011. \n%\n%\n% Copyright 2009: Delft University of Technology, Signal & Information\n% Processing Lab. The software is free for non-commercial use. This program\n% comes WITHOUT ANY WARRANTY.\n%\n%\n%\n% Updates:\n% 2011-04-26 Using the more efficient 'taa_corr' instead of 'corr'\n\nif length(x)~=length(y)\n    error('x and y should have the same length');\nend\n\n% initialization\nx           = x(:);                             % clean speech column vector\ny           = y(:);                             % processed speech column vector\n\nfs          = 10000;                            % sample rate of proposed intelligibility measure 10000\nN_frame    \t= 256;                              % window support 256\nK           = 512;                              % FFT size 512\nJ           = 15;                               % Number of 1/3 octave bands\nmn          = 150;                              % Center frequency of first 1/3 octave band in Hz.\nH           = thirdoct(fs, K, J, mn);           % Get 1/3 octave band matrix\nN           = 30;                               % Number of frames for intermediate intelligibility measure (Length analysis window)\nBeta        = -15;                           \t% lower SDR-bound -15\ndyn_range   = 40;                               % speech dynamic range 40\n\n% resample signals if other samplerate is used than fs\nif fs_signal ~= fs\n    x\t= resample(x, fs, fs_signal);\n    y \t= resample(y, fs, fs_signal);\nend\n\n\n% remove silent frames\n[x y] = removeSilentFrames(x, y, dyn_range, N_frame, N_frame/2);\n\n% apply 1/3 octave band TF-decomposition\nx_hat     \t= stdft(x, N_frame, N_frame/2, K); \t% apply short-time DFT to clean speech\ny_hat     \t= stdft(y, N_frame, N_frame/2, K); \t% apply short-time DFT to processed speech\n\nx_hat       = x_hat(:, 1:(K/2+1)).';         \t% take clean single-sided spectrum\ny_hat       = y_hat(:, 1:(K/2+1)).';        \t% take processed single-sided spectrum\n\nX           = zeros(J, size(x_hat, 2));         % init memory for clean speech 1/3 octave band TF-representation \nY           = zeros(J, size(y_hat, 2));         % init memory for processed speech 1/3 octave band TF-representation \n\nfor i = 1:size(x_hat, 2)\n    X(:, i)\t= sqrt(H*abs(x_hat(:, i)).^2);      % apply 1/3 octave bands as described in Eq.(1) [1]\n    Y(:, i)\t= sqrt(H*abs(y_hat(:, i)).^2);\nend\n\n% loop al segments of length N and obtain intermediate intelligibility measure for all TF-regions\nd_interm  \t= zeros(J, length(N:size(X, 2)));                               % init memory for intermediate intelligibility measure\nc           = 10^(-Beta/20);                                                % constant for clipping procedure\n\nfor m = N:size(X, 2)\n    X_seg  \t= X(:, (m-N+1):m);                                              % region with length N of clean TF-units for all j\n    Y_seg  \t= Y(:, (m-N+1):m);                                              % region with length N of processed TF-units for all j\n    alpha   = sqrt(sum(X_seg.^2, 2)./sum(Y_seg.^2, 2));                     % obtain scale factor for normalizing processed TF-region for all j\n    aY_seg \t= Y_seg.*repmat(alpha, [1 N]);                               \t% obtain \\alpha*Y_j(n) from Eq.(2) [1]\n    for j = 1:J\n      \tY_prime             = min(aY_seg(j, :), X_seg(j, :)+X_seg(j, :)*c); % apply clipping from Eq.(3)   \t\n        d_interm(j, m-N+1)  = taa_corr(X_seg(j, :).', Y_prime(:));          % obtain correlation coeffecient from Eq.(4) [1]\n    end\nend\n        \nd = mean(d_interm(:));                                                      % combine all intermediate intelligibility measures as in Eq.(4) [1]\n\n%%\nfunction  [A cf] = thirdoct(fs, N_fft, numBands, mn)\n%   [A CF] = THIRDOCT(FS, N_FFT, NUMBANDS, MN) returns 1/3 octave band matrix\n%   inputs:\n%       FS:         samplerate \n%       N_FFT:      FFT size\n%       NUMBANDS:   number of bands\n%       MN:         center frequency of first 1/3 octave band\n%   outputs:\n%       A:          octave band matrix\n%       CF:         center frequencies\n\nf               = linspace(0, fs, N_fft+1);\nf               = f(1:(N_fft/2+1));\nk               = 0:(numBands-1); \ncf              = 2.^(k/3)*mn;\nfl              = sqrt((2.^(k/3)*mn).*2.^((k-1)/3)*mn);\nfr              = sqrt((2.^(k/3)*mn).*2.^((k+1)/3)*mn);\nA               = zeros(numBands, length(f));\n\nfor i = 1:(length(cf))\n    [a b]                   = min((f-fl(i)).^2);\n    fl(i)                   = f(b);\n    fl_ii                   = b;\n\n\t[a b]                   = min((f-fr(i)).^2);\n    fr(i)                   = f(b);\n    fr_ii                   = b;\n    A(i,fl_ii:(fr_ii-1))\t= 1;\nend\n\nrnk         = sum(A, 2);\nnumBands  \t= find((rnk(2:end)>=rnk(1:(end-1))) & (rnk(2:end)~=0)~=0, 1, 'last' )+1;\nA           = A(1:numBands, :);\ncf          = cf(1:numBands);\n\n%%\nfunction x_stdft = stdft(x, N, K, N_fft)\n%   X_STDFT = X_STDFT(X, N, K, N_FFT) returns the short-time\n%\thanning-windowed dft of X with frame-size N, overlap K and DFT size\n%   N_FFT. The columns and rows of X_STDFT denote the frame-index and\n%   dft-bin index, respectively.\n\nframes      = 1:K:(length(x)-N);\nx_stdft     = zeros(length(frames), N_fft);\n\nw           = hanning(N);\nx           = x(:);\n\nfor i = 1:length(frames)\n    ii              = frames(i):(frames(i)+N-1);\n\tx_stdft(i, :) \t= fft(x(ii).*w, N_fft);\nend\n\n%%\nfunction [x_sil y_sil] = removeSilentFrames(x, y, range, N, K)\n%   [X_SIL Y_SIL] = REMOVESILENTFRAMES(X, Y, RANGE, N, K) X and Y\n%   are segmented with frame-length N and overlap K, where the maximum energy\n%   of all frames of X is determined, say X_MAX. X_SIL and Y_SIL are the\n%   reconstructed signals, excluding the frames, where the energy of a frame\n%   of X is smaller than X_MAX-RANGE\n\nx       = x(:);\ny       = y(:);\n\nframes  = 1:K:(length(x)-N);\nw       = hanning(N);\nmsk     = zeros(size(frames));\n\nfor j = 1:length(frames)\n    jj      = frames(j):(frames(j)+N-1);\n    msk(j) \t= 20*log10(norm(x(jj).*w)./sqrt(N));\nend\n\nmsk     = (msk-max(msk)+range)>0;\ncount   = 1;\n\nx_sil   = zeros(size(x));\ny_sil   = zeros(size(y));\n\nfor j = 1:length(frames)\n    if msk(j)\n        jj_i            = frames(j):(frames(j)+N-1);\n        jj_o            = frames(count):(frames(count)+N-1);\n        x_sil(jj_o)     = x_sil(jj_o) + x(jj_i).*w;\n        y_sil(jj_o)  \t= y_sil(jj_o) + y(jj_i).*w;\n        count           = count+1;\n    end\nend\n\nx_sil = x_sil(1:jj_o(end));\ny_sil = y_sil(1:jj_o(end));\n\n%%\nfunction rho = taa_corr(x, y)\n%   RHO = TAA_CORR(X, Y) Returns correlation coeffecient between column\n%   vectors x and y. Gives same results as 'corr' from statistics toolbox.\nxn    \t= x-mean(x);\nxn  \t= xn/sqrt(sum(xn.^2));\nyn   \t= y-mean(y);\nyn    \t= yn/sqrt(sum(yn.^2));\nrho   \t= sum(xn.*yn);", "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/stoi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.5787312935622944}}
{"text": "% LFBuild4DFreqHypercone - construct a 4D hypercone passband filter in the frequency domain\n% \n% Usage: \n% \n%     [H, FiltOptions] = LFBuild4DFreqHypercone( LFSize, Slope, BW, FiltOptions )\n%     H = LFBuild4DFreqHypercone( LFSize, Slope, BW )\n% \n% This file constructs a real-valued magnitude response in 4D, for which the passband is a hypercone.\n%\n% Once constructed the filter must be applied to a light field, e.g. using LFFilt4DFFT. The \n% LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters.\n% \n% A more technical discussion, including the use of filters for denoising and volumetric focus, and\n% the inclusion of aliases components, is included in:\n% \n% [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, \"Linear Volumetric Focus for Light Field\n% Cameras,\" to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015.\n% \n% Inputs:\n% \n%     LFSize : Size of the frequency-domain filter. This should match or exceed the size of the\n%     light field to be filtered. If it's larger than the input light field, the input is\n%     zero-padded to match the filter's size by LFFilt4DFFT.\n% \n%     Slope : The slope of the planar passband. If different slopes are desired in s,t and u,v,\n%     the optional aspect parameter should be used.\n% \n%     BW : 3-db Bandwidth of the planar passband.\n% \n%     [optional] FiltOptions : struct controlling filter construction\n%               SlopeMethod : 'Skew' or 'Rotate' default 'skew'\n%                 Precision : 'single' or 'double', default 'single'\n%                   Rolloff : 'Gaussian' or 'Butter', default 'Gaussian'\n%                     Order : controls the order of the filter when Rolloff is 'Butter', default 3\n%                  Aspect4D : aspect ratio of the light field, default [1 1 1 1]\n%                    Window : Default false. By default the edges of the passband are sharp; this adds \n%                             a smooth rolloff at the edges when used in conjunction with Extent4D or\n%                             IncludeAliased.\n%                  Extent4D : controls where the edge of the passband occurs, the default [1 1 1 1]\n%                             is the edge of the Nyquist box. When less than 1, enabling windowing\n%                             introduces a rolloff after the edge of the passband. Can be greater\n%                             than 1 when using IncludeAliased.\n%            IncludeAliased : default false; allows the passband to wrap around off the edge of the\n%                             Nyquist box; used in conjunction with Window and/or Extent4D. This can \n%                             increase processing time dramatically, e.g. Extent4D = [2,2,2,2] \n%                             requires a 2^4 = 16-fold increase in time to construct the filter. \n%                             Useful when passband content is aliased, see [2].\n% \n% Outputs:\n% \n%                 H : real-valued frequency magnitude response\n%       FiltOptions : The filter options including defaults, with an added PassbandInfo field\n%                     detailing the function and time of construction of the filter\n%\n% User guide: <a href=\"matlab:which LFToolbox.pdf; open('LFToolbox.pdf')\">LFToolbox.pdf</a>\n% See also:  LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01,\n% LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone,\n% LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum\n\n% Copyright (c) 2013-2020 Donald G. Dansereau\n\nfunction [H, FiltOptions] = LFBuild4DFreqHypercone( LFSize, BW, FiltOptions )\n\nFiltOptions = LFDefaultField('FiltOptions', 'HyperconeMethod', 'Rotated'); % 'Direct', 'Rotated'\n\nDistFunc = @(P, FiltOptions) DistFunc_4DCone( P, FiltOptions );\n[H, FiltOptions] = LFHelperBuild4DFreq( LFSize, BW, FiltOptions, DistFunc );\n\nTimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');\nFiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);\n\nend\n\n%-----------------------------------------------------------------------------------------------------------------------\nfunction Dist = DistFunc_4DCone( P, FiltOptions )\nswitch( lower(FiltOptions.HyperconeMethod ))\n\tcase 'direct'\n\t\tDist = (P(1,:).*P(4,:) - P(2,:).*P(3,:)).^2 * 4;\n\t\t\n\tcase 'rotated'\n\t\tR = 1/sqrt(2) .* [1,0,0,1; 0,1,1,0; 0,1,-1,0; 1,0,0,-1];\n\t\tP = R*P;\n\t\tDist = (sqrt(P(1,:).^2 + P(3,:).^2) - sqrt(P(2,:).^2 + P(4,:).^2)).^2 /2;\n\t\t\n\totherwise\n\t\terror('Unrecognized hypercone construction method');\nend\nend\n\n\n\n", "meta": {"author": "doda42", "repo": "LFToolbox", "sha": "5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e", "save_path": "github-repos/MATLAB/doda42-LFToolbox", "path": "github-repos/MATLAB/doda42-LFToolbox/LFToolbox-5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e/LFBuild4DFreqHypercone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5786909772268668}}
{"text": "function [soln,eqn,info] = PoissonWG(node,elem,bdFlag,pde,option)\n%% POISSONWG Poisson equation: lowest order weak Galerkin element\n%\n%   u = POISSONWG(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 usage is the same as <a href=\"matlab:help Poisson\">Poisson</a>. Weak Galerkin method on a triangle is\n% summarized in <a href=\"matlab:ifem PoissonWGfemrate\">PoissonWGfemrate</a> for detail.\n%\n%   Example\n%\n%     squarePoissonWG;\n%\n%   See also Poisson, squarePoissonWG\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\nNT = size(elem,1); \nN = size(node,1);\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%% Construct data structure \n[elem2edge,edge] = dofedge(elem);\nNE = size(edge,1); \nNdof = NT + NE;\nelem2dof = NT + elem2edge;\n\n%% Assemble stiffness matrix\nA = sparse(Ndof,Ndof);\n\n% compute ct2 = 1/mean(||x-xc||^2)\ncenter = (node(elem(:,1),:) + node(elem(:,2),:) + node(elem(:,3),:))/3;\nmid1 = (node(elem(:,2),:) + node(elem(:,3),:))/2;\nmid2 = (node(elem(:,3),:) + node(elem(:,1),:))/2;\nmid3 = (node(elem(:,1),:) + node(elem(:,2),:))/2;\nct2 = 3./sum((mid1 - center).^2 + (mid2 - center).^2 + (mid3 - center).^2,2);\n[Dphi,area] = gradbasis(node,elem);\nclear center mid1 mid2 mid3\n\n% Mbb: edge - edge           \nfor i = 1:3\n    for j = i:3\n        % local to global index map\n        ii = double(elem2dof(:,i));\n        jj = double(elem2dof(:,j));\n        % local stiffness matrix\n        Aij = 4*dot(Dphi(:,:,i),Dphi(:,:,j),2).*area + 4/9*ct2.*area;\n        if ~isempty(pde.d)\n            Aij = K.*Aij;\n        end        \n        if (j==i)\n            A = A + sparse(ii,jj,Aij,Ndof,Ndof);\n        else\n            A = A + sparse([ii,jj],[jj,ii],[Aij; Aij],Ndof,Ndof);        \n        end        \n    end\nend\n\n% Mob: interior - edge\nAij = -4/3*ct2.*area;\nif ~isempty(pde.d)\n    Aij = K.*Aij;\nend\nMob = sparse([(1:NT)', (1:NT)', (1:NT)'], ...\n             double(elem2dof(:)), [Aij, Aij, Aij], Ndof, Ndof);\nA = A + Mob + Mob';\n\n% Moo: diagonal of interor\nAij = 4*ct2.*area;\nif ~isempty(pde.d)\n    Aij = K.*Aij;\nend\nA =  A + sparse(1:NT, 1:NT, Aij, Ndof, Ndof);\n\nclear K Aij\n\n%% Assemble the right hand side\nb = zeros(Ndof,1);\nif ~isfield(option,'fquadorder')\n    option.fquadorder = 2;   % 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         b(1:NT) = pde.f.*area;\n       case N   % f is piecewise linear\n         b(1:NT) = (pde.f(elem(:,1)) + pde.f(elem(:,2)) + pde.f(elem(:,3)))/3.*area;\n       case 1   % f is a scalar e.g. f = 1\n         b(1:NT) = pde.f*area;\n   end\nend\nif ~isempty(pde.f) && ~isreal(pde.f)  % f is a function\n    [lambda,weight] = quadpts(option.fquadorder);\n\tnQuad = size(lambda,1);\n    bt = zeros(NT,1);\n    for p = 1:nQuad\n\t\t% quadrature points in the x-y coordinate\n\t\tpxy = lambda(p,1)*node(elem(:,1),:) ...\n\t\t\t+ lambda(p,2)*node(elem(:,2),:) ...\n\t\t\t+ lambda(p,3)*node(elem(:,3),:);\n\t\tfp = pde.f(pxy);\n        bt = bt + weight(p)*fp;\n    end\n    bt = bt.*area;\n    b(1:NT) = bt;\nend\nclear pxy bt\n\n%% Set up boundary conditions\nif nargin<=3, bdFlag = []; end\n[AD,b,u,freeDof,isPureNeumann] = getbdWG(A,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(freeDof), return; end\n% Set up solver type\nif isempty(option) || ~isfield(option,'solver')    % no option.solver\n    if NE <= 1e3  % 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(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        % eleminate elementwise dof\n        option.solver = 'CG';\n        if isfield(option,'reducesystem') && (option.reducesystem == 0)\n            option.x0 = u;\n            [u,info] = mg(AD,b,elem,option,edge);        \n        else\n            option.x0 = u(NT+1:end);\n            Aoinv = spdiags(1./diag(AD(1:NT,1:NT)),0,NT,NT);\n            Aob = AD(1:NT,NT+1:end);\n            Abo = Aob';\n            Abb = AD(NT+1:end,NT+1:end);\n            Abbm = Abb - Abo*Aoinv*Aob;\n            bm = -Abo*Aoinv*b(1:NT) + b(NT+1:end);        \n            [ub,info] = mg(Abbm,bm,elem,option,edge);\n            u(1:NT) = Aoinv*(b(1:NT) - Aob*ub);\n            u(NT+1:end) = ub;        \n        end\n    case 'amg'\n        option.solver = 'CG';\n        [u(freeDof),info] = amg(AD(freeDof,freeDof),b(freeDof),option);                 \nend\n% post-process for pure Neumann problem\nif isPureNeumann\n    uc = sum(u(1:NT).*area);\n    u = u - uc;   % normalization for pure Neumann problem\nend\n\n%% Compute Du\ndudx =  u(elem2dof(:,1)).*Dphi(:,1,1) + u(elem2dof(:,2)).*Dphi(:,1,2) ...\n      + u(elem2dof(:,3)).*Dphi(:,1,3);\ndudy =  u(elem2dof(:,1)).*Dphi(:,2,1) + u(elem2dof(:,2)).*Dphi(:,2,2) ...\n      + u(elem2dof(:,3)).*Dphi(:,2,3);         \nDu = -2*[dudx, dudy];\n\n%% Output information\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);\n    info.assembleTime = assembleTime;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbdWG\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [AD,b,u,freeDof,isPureNeumann]= getbdWG(A,b)\n    %% GETBDCR Boundary conditions for Poisson equation: WG element.\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    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        ve = node(Robin(:,1),:) - node(Robin(:,2),:);\n        edgeLength = sqrt(sum(ve.^2,2)); \n        mid = (node(Robin(:,1),:) + node(Robin(:,2),:))/2;\n        ii = NT + find(isRobin);  % for WG: edge dof is after elem dof\n        ss = pde.g_R(mid).*edgeLength; % exact for linear g_R\n        A = A + sparse(ii,ii,ss,Ndof,Ndof);\n    end\n    \n    % Find Dirichlet boundary nodes: fixedEdge\n    fixedEdge = []; freeEdge = [];\n    if ~isempty(bdFlag)              % find boundary edges\n        idxD = (bdFlag(:) == 1);     % all Dirichlet edges in bdFlag\n        isFixedEdge = false(NE,1);\n        isFixedEdge(elem2edge(idxD)) = true;  % index of fixed boundary edges\n        fixedEdge = find(isFixedEdge);\n        freeEdge = find(~isFixedEdge);\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 in the input\n        s = accumarray(elem2edge(:), 1, [NE 1]);\n        fixedEdge = find(s == 1);\n        freeEdge = find(s == 2);\n    end\n    isPureNeumann = false;    \n    if isempty(fixedEdge) && isempty(Robin)  % pure Neumann boundary condition\n        % pde.g_N could be empty which is homogenous Neumann boundary condition\n        isPureNeumann = true;\n        fixedEdge = 1;\n        freeEdge = (2:NE)';    % 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(fixedEdge,fixedEdge)=I, AD(fixedEdge,freeEdge)=0, AD(freeEdge,fixedEdge)=0.\n    if ~isempty(fixedEdge)\n        bdidx = zeros(Ndof,1); \n        bdidx(NT + fixedEdge) = 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 right hand side b\n    % Find boundary edges: Neumann\n    Neumann = [];\n    if ~isempty(bdFlag)  % bdFlag specifies different bd conditions\n        idxN = (bdFlag(:) == 2);      % all Neumann edges in bdFlag\n        isNeumann = elem2edge(idxN | idxR); % index of Neumann and Robin edges\n        % since boundary integral is also needed for Robin edges\n        Neumann = edge(isNeumann,:);      % Neumann edges        \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        s = accumarray(elem2edge(:), 1, [NE 1]);\n        Neumann = edge(s == 1,:);\n    end\n\n    % Neumann boundary condition\n    if ~isempty(Neumann) && ~isempty(pde.g_N) && ~(isnumeric(pde.g_N) && (pde.g_N == 0))\n        if ~isfield(option,'gNquadorder')\n            option.gNquadorder = 3;   % default order exact for linear gN\n        end\n        [lambdagN,weightgN] = quadpts1(option.gNquadorder);\n        nQuadgN = size(lambdagN,1);\n        ge = zeros(size(Neumann,1),1);\n        el = sqrt(sum((node(Neumann(:,1),:) - node(Neumann(:,2),:)).^2,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            ge = ge+ weightgN(pp)*gNp;\n        end\n        ge = ge.*el;\n        b(NT+isNeumann) = b(NT+isNeumann) + ge;\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(fixedEdge) && ...\n       ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && all(pde.g_D == 0))    % nonzero g_D\n        if isnumeric(pde.g_D)  % pde.g_D could be a numerical array \n            u(fixedEdge) = pde.g_D(fixedEdge); \n        else % pde.g_D is a function handle\n            mid = (node(edge(fixedEdge,1),:) + node(edge(fixedEdge,2),:))/2;\n            u(NT+fixedEdge) = pde.g_D(mid);\n        end\n        b = b - A*u;\n        b(NT+fixedEdge) = u(NT+fixedEdge);\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    \n    freeDof = [(1:NT)'; NT+freeEdge];\n    end\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nend % end of PoissonWG\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/PoissonWG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5786909768530544}}
{"text": "% DEMSPGP1D2 Do a simple 1-D regression after Snelson & Ghahramani's example.\n\n% GP\n\n% Fix seeds\nrandn('seed', 2e5);\nrand('seed', 2e5);\nseedVal = 2e5;\ndataSetName = 'spgp1d';\nexperimentNo = 2;\n\n% load data\n[X, y] = mapLoadData(dataSetName, seedVal);\n\n% Set up model\noptions = gpOptions('fitc');\noptions.numActive = 9;\n\n% use the deterministic training conditional.\nq = size(X, 2);\nd = size(y, 2);\n\nmodel = gpCreate(q, d, X, y, options);\nmodel.X_u = randn(9, 1)*0.25 - 0.75;\nparams = gpExtractParam(model);\nmodel = gpExpandParam(model, params);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\nmodel.beta = 4/var(y);\nmodel.kern.variance = var(y);\nmodel.kern.inverseWidth = 1./((-min(X)+max(X))'/2).^2\n\nmodel = gpOptimise(model, display, iters);\n\n% Save the results.\ncapName = dataSetName;;\ncapName(1) = upper(capName(1));\nsave(['dem' capName num2str(experimentNo) '.mat'], 'model');\n\n\ndemSpgp1dPlot", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gp/demSpgp1d2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5786909690887615}}
{"text": "function [img,seg] = pre_process_isotropic(img_nii,seg_nii,use_isotropic,id)\n% Pre-process the data\n% Normalize the intensity of the images and also do some re-sample.\n%\n% If use_isotropic is True, we will resize all samples to same resolution,\n% otherwise, we will only resize the sample 4 and 5 (which have much low \n% resolution than other samples)\n%------------------------------------------------------------------------\n\n    if nargin <4\n        id = 1;\n    end\n    \n    if use_isotropic\n        scale = img_nii.hdr.dime.pixdim(2:4)./[0.80 0.7588 0.7588];\n        new_size = round(img_nii.hdr.dime.dim(2:4).*scale);\n        img = imresize3d(img_nii.img,[],new_size,'cubic','bound');\n        if ~isempty(seg_nii)\n            seg = imresize3d(seg_nii.img,[],new_size,'nearest','bound');\n        end\n    else\n        if id==4 || id==5\n            % resize img in up and down plane\n            img = permute(img_nii.img,[3,2,1]);\n            img = imresize(img,1.5,'bilinear');\n            img = permute(img,[3,2,1]);\n            if ~isempty(seg_nii)\n                seg = permute(seg_nii.img,[3,2,1]);\n                seg = imresize(seg,1.5,'nearest');\n                seg = permute(seg,[3,2,1]);\n            end\n        else\n            img = img_nii.img;\n            if ~isempty(seg_nii)\n                seg = seg_nii.img;\n            end\n        end\n    end\n    \n    %Normalize the intensity of images\n    img = single(img);\n    mask = img>0;\n    mean_value = mean(img(mask));\n    std_value  = std(img(mask),1);\n    img = bsxfun(@rdivide, bsxfun(@minus, img, mean_value), std_value);\nend\n", "meta": {"author": "yulequan", "repo": "HeartSeg", "sha": "b689b376d9cce9e02adf33606035892284c8814c", "save_path": "github-repos/MATLAB/yulequan-HeartSeg", "path": "github-repos/MATLAB/yulequan-HeartSeg/HeartSeg-b689b376d9cce9e02adf33606035892284c8814c/code/util/pre_process_isotropic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.578690967967323}}
{"text": "%  Matlab script to read DEM 3 arc seconds file.\n%\n%  Creates the following variables:\n%    elev: elevation data (row = lat; col = lon)\n%    xv: longitude vector\n%    yv: latitude vector\n%    clat & clon: SouthEast corner latitude and longitude of the file\n\n%  Written 27 Nov 96  by Guy Tytgat\n\nreport_this_filefun(mfilename('fullpath'));\n\n[file,path] = uigetfile('*','Select a .3CD file',300,300);\n\nif file == []\n    disp('Error selecting file')\n    clear file path\n    return\nelseif file == 0\n    disp('No file selected')\n    clear file path\n    return\nend\n\nfilename = sprintf('%s%s',path,file);\n[fid,message2] = fopen(filename);\nif file(7:9) ~= '3cd'\n    error('Wrong file type selected')\n    return\nend\n\nnrow = 1201;\nclat = str2double(file(1:2));\nclon = str2double(file(3:5));\n\nif fid ~= -1\n    if clat < 50\n        ncol = 1201;\n    elseif (50 <= clat)  &&  (clat < 70)\n        ncol = 601;\n    elseif (70 <= clat)  &&  (clat < 75)\n        ncol = 401;\n    elseif (75 <= clat)  &&  (clat < 80)\n        ncol = 301;\n    elseif (80 <= clat)  &&  (clat <= 90)\n        ncol = 201;\n    else\n        error('Incorrect file type selected')\n        return\n    end\n\n    elev = ones([nrow,ncol]);\n    [elev, count] = fread(fid,[nrow,ncol],'short');\n    if (nrow*ncol) ~= count\n        disp('WARNING: Not all data points were read')\n    end\n\n    xv = -(clon+1):1/ncol:-clon;\n    yv = clat:1/nrow:clat+1;\n    clear count fid file filename message2 ncol nrow path\nelse\n    clear fid file filename message2 clat clon path nrow\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/loaddem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5786909630403368}}
{"text": "function [L_,U_] = glover_sherali_raw(a,a0,u)\n    \nL_ = -inf(length(a),1);\nU_ = inf(length(a),1);\n% Map to sorted\n[a_, loc] = sort(a,'descend');\nn = length(a_);\n\n%From here, we only work with binary and in sorted\nfor j = 1:n\n    s = a_(1:j);\n    SN(j) = sum(s(s>0));\nend\n%SN = cumsum(max(a_,0));\ntry\n    SN_u_plus_1 = sum(a_(1:u+1));\ncatch\n    1\nend\nSN_u_minus_1 = sum(a_(1:u-1));\n\nfixed_at_one = find(a_ > SN_u_plus_1-a0);\nif ~isempty(fixed_at_one)\n    L_(fixed_at_one) = 1;\n    U_(fixed_at_one) = 1;\nend\n\njhat = u+1:n;\nfixed_at_zero = jhat(find(a_(jhat) < a0-SN_u_minus_1));\nif ~isempty(fixed_at_zero)\n    U_(fixed_at_zero) = 0;\n    L_(fixed_at_zero) = 0;\nend\n\nL = L_(loc);\nU = U_(loc);", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/glover_sherali_raw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5786909630403368}}
{"text": "function [llh] = tapas_sem_multiv_llh(data, theta, ptheta)\n%% Compute likelihood of the eye movement model in a hierarchical format. \n%\n%   Input\n%\n%   data        -- Stucture array of dimension Nx1 with fields y and u\n%   theta       -- Structure array of dimension 1 X 1 \n%   ptheta      -- Priors\n%\n%   Ouput\n%   \n%   llh         -- Matrix of dimensions NxM where N is the number fo subjects\n%                   and M the number of chains.\n%\n\n% aponteeduardo@gmail.com\n% copyright (C) 2016\n%\n\n\nns = size(theta.y, 1);\nnc = size(theta.y, 2);\n\natheta = cell(ns, nc);\n\nfor i = 1:ns\n    for j = 1:nc\n        atheta{i, j} = ptheta.model.p0 + ptheta.model.jm * theta.y{i, j};\n    end\nend\n\nllh =  ptheta.model.llh(data, atheta);\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/sem/multivar/tapas_sem_multiv_llh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5786909573657246}}
{"text": "function t = s2t(s, epsilon);\n\n% T = s2t(S, EPSILON)\n%\n% Scattering to Transmission Transformation\n% \n% since 2 is the only allowed number of ports for a T-matrix,\n% S, T are matrices of size [2,2,F], \n% where F is the number of frequencies\n%\n% EPSILON is used to produce an approximation of the corresponding S-matrix\n% in exceptional cases\n%\n% 3-d version 4 nov 1999\n\nif nargin < 2 epsilon = 1e-14; end;\n[n,i] = min(abs(s(2,1,:)));\nwhile n <= epsilon\n    s(2,1,i) = s(2,1,i)+rand*epsilon;\n    [n,i] = min(abs(s(2,1,:)));\nend;\n\nt(1,1,:) = 1./s(2,1,:);\nt(1,2,:) = -s(2,2,:)./s(2,1,:);\nt(2,1,:) = s(1, 1,:)./s(2,1,:);\nt(2,2,:) = s(1, 2,:) - s(1, 1,:).*s(2,2,:)./s(2,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/6080-s-parameter-toolbox-+-z-y-h-g-abcd-t/sbox/s2t.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5786842413218654}}
{"text": "function [w]=obtencion_w(R)\n    j=1;\n    x=1;\n    i=1;\n    \n    %Desmontamos la matriz\n    while j<100\n        r11(j)=R{j}(1,1);\n        r12(j)=R{j}(1,2);\n        r13(j)=R{j}(1,3);\n        \n        r21(j)=R{j}(2,1);\n        r22(j)=R{j}(2,2);\n        r23(j)=R{j}(2,3);\n        \n        r31(j)=R{j}(3,1);\n        r32(j)=R{j}(3,2);\n        r33(j)=R{j}(3,3);\n        \n        j=j+1;\n    end\n    \n    %Derivamos los vectores\n    rd11=diff(r11);\n    rd12=diff(r12);\n    rd13=diff(r13);\n    \n    rd21=diff(r21);\n    rd22=diff(r22);\n    rd23=diff(r23);\n    \n    rd31=diff(r31);\n    rd32=diff(r32);\n    rd33=diff(r33);\n    \n    %Motamos la matriz derivada\n    while x<99\n        dR{x}(1,1)=rd11(x);\n        dR{x}(1,2)=rd12(x);\n        dR{x}(1,3)=rd13(x);\n        \n        dR{x}(2,1)=rd21(x);\n        dR{x}(2,2)=rd22(x);\n        dR{x}(2,3)=rd23(x);\n        \n        dR{x}(3,1)=rd31(x);\n        dR{x}(3,2)=rd32(x);\n        dR{x}(3,3)=rd33(x);\n        \n        x=x+1;\n    end\n    \n    %Multiplicamos dR por R(transpuesta) para sacar w\n    while i<99\n        w{i}=dR{i}*(R{i}.');\n        \n        i=i+1;\n    end\nend", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/projects/sist_ambidextro/obtencion_w.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5786684448468616}}
{"text": "function similarity_output = canlab_pattern_similarity(dat, pattern_weights, varargin)\n% Calculate similarity between each column in a data matrix dat and a vector of pattern weights\n%\n% - Similarity options: dot product, cosine similarity, and correlation\n% - Columns are often images, e.g., from fmri_data.dat for fmri_data objects\n% - weights are pattern weights from one or more 'signature' patterns (each pattern is a column)\n%\n% - Assumes dat and pattern_weights matrices have equal rows (voxels) and include valid voxels\n% - Removes empty column data column-wise (image-wise) in case some images have uneven voxel coverage\n%\n% - Used in apply_mask, extract_roi_averages, image_similarity_plot***\n%\n% similarity_output = canlab_pattern_similarity(dat, pattern_weights)\n%\n% :Inputs:\n%   **dat**  voxels x images matrix of data to compare to patterns\n%\n%   **pattern_weights** voxels x images matrix of patterns to compare to data\n%\n% :Optional Inputs:\n%\n%   **dot_product**\n%       [Default] Use dot product\n%\n%   **cosine_similarity**\n%       Use cosine similarity metric for pattern expression instead of dot product\n%\n%   **correlation, corr**\n%       Use correlation metric for pattern expression instead of dot product\n%\n%   **binary_overlap**\n%       Use percent overlap of binary masks instead of dot product. needs\n%       binary masks and pattern weights.\n%\n%   **posterior_overlap**\n%       Using percent overlap of binary masks, this option calculates the\n%       posterior probability of observing non-zero pattern weights (binary)\n%       given binary masks\n%\n%   **ignore_missing**\n%       Suppress printing of warnings when thre are missing values\n%       (zeros/NaN) in data images. This function always removes voxels\n%       from analysis with missing data values. This does not affect the\n%       dot product metric, but does affect cosine similarity and\n%       correlation.\n%\n%   **no_warnings**\n%       Suppress output on missing values.\n%\n%\n%   **treat_zero_as_data**\n%       In some certain situations, zero value within data.obj could be\n%       meaningful. e.g, data.obj is a thresholded map (0 means value underthrethold \n%       rather than missing value) or binary map.\n%\n% :Outputs:\n%   **similarity_output**\n%       Matrix of similarity measures.\n%\n%\n% :Examples:\n% ::\n% dat = rand(100, 5);  % 100 voxels, 5 images\n% weights = rand(100, 2); % 100 voxels, 2 patterns\n% similarity_output = canlab_pattern_similarity(dat, weights, 'cosine_similarity');\n%\n% :See also:\n%\n% apply_mask\n% image_similarity_plot\n% extract_roi_averages, to get individual region averages / local pattern expression\n% apply_nps, which does whole-pattern and local regional expression\n%\n% ..\n%    Notes:\n%\n% Dealing with missing data and partial coverage\n% ---------------------------------------------------\n% Pattern pattern_weights can have zeros, which may be valid values in voxels,\n% i.e., with binary masks\n% Data images with values of zero or NaN are considered out-of-mask, as they\n% are not valid values. That is, 0 is often treated as a missing data value in images,\n% with the exception of \"signatures\" and binary pattern masks.\n% Thus, this function treats values of 0 in DATA images, not pattern masks,\n% as missing values, and excludes these voxels from both image and\n% mask when calculating similarity.\n% Thus, there is an asymmetry between pattern mask and image data\n% in considering which voxels to use.\n% Otherwise, all dot product, correlation, and other similarity metrics are standard.\n%\n% When comparing two sets of binary images (e.g. k-means clusters) and the\n% cluster of the input solution does not overlap with any of the target\n% patterns/clusters, cosine similarity is attempting division by 0. Instead\n% of returning NaN, we set those cosine values to 0.\n%\n% Effects of zeros/missing values on similarity metrics\n% ---------------------------------------------------\n% Dot product is affected by voxel size, coverage in image and mask, scale\n% in general.\n% Cosine similarity is affected by coverage in image\n% If we remove voxels from analysis that are not in image (NaN or zero) first,\n% then cosine similarity is unaffected by coverage, in the sense that the\n% upper bound is 1.\n% Correlation is affected by coverage in image and mean level in image. If\n% there are zeros in image, mean-centering will be affected.\n% If we remove NaN/zero values from analysis on an image-by-image basis, we\n% are computing partial similarity for the areas of the image that exist.\n% This is good in terms of preserving scale and analyzing the data we have,\n% but changes the measurement properties of the pattern measures, because\n% we're looking only at a subset of the model.\n%\n% We also need to calculate bad values on an image-by-image basis, not\n% relying on remove_empty to exclude voxels with ineligible values\n% across the entire set of images.\n%\n%  Created by Tor Wager - 3/7/17\n\n% Programmer's Notes:\n%\n% 2017/09/07 Stephan Geuter\n%   - added option for percent overlap of binary masks (see also\n%   image_similarity_plot.m and riverplot.m\n%   - Changed metric selection to string format.\n%\n% 2022/03/31 Ke Bo\n%   - added option for treating zero value in the map as real value rather\n%   than missing data\n%\n\n\n% ---------------------------------\n% Defaults and optional inputs\n% ---------------------------------\n\n% docorr = false;     % run correlation instead of dot-product for pattern expression\nsim_metric = 'dotproduct'; % Default: Correlation. SG. docosine = false;   % run cosine sim instead\ndoignoremissing = false; % ignore warnings for missing voxels\ndoprintwarnings = true;  % print warnings regarding missing voxels, etc.\ntreat_zero_as_data=false; % Treat zero value as missing data.\n\nif any(strcmp(varargin, 'ignore_missing'))\n    doignoremissing = true;\nend\n\nif any(strcmp(varargin, 'no_warnings'))\n    doprintwarnings = false;\nend\n\nif any(strcmp(varargin, 'cosine_similarity')) % run cosine instead of dot-product\n    sim_metric = 'cosine';\nend\n\nif any(strcmp(varargin, 'correlation')) || any(strcmp(varargin, 'corr')) % run correlation instead of dot-product\n    sim_metric = 'corr';\nend\n\nif any(strcmp(varargin, 'binary_overlap')) % run overlap instead of dot-product\n    sim_metric = 'overlap';\nend\n\nif any(strcmp(varargin, 'dotproduct')) % default. overwrites previous selections\n    sim_metric = 'dotproduct';\nend\n\nif any(strcmp(varargin, 'posterior_overlap')) % run overlap instead of dot-product\n    sim_metric = 'posterior_overlap';\nend\n\nif any(strcmp(varargin, 'treat_zero_as_data'))\n    treat_zero_as_data = true;\nend\n\n% if docosine && docorr, error('Choose either cosine_similarity or correlation, or no optional inputs for dot product'); end\n\n% ---------------------------------\n% Variable types and sizes\n% ---------------------------------\npattern_weights = double(pattern_weights); % force double b/c of matlab instabilities\ndat = double(dat); % force double b/c of matlab instabilities\n\n[n, k] = size(dat);\n[n2, npatt] = size(pattern_weights);\n\nif n ~= n2, error('Number of observations must be equal for data and patterns'); end\n\nsimilarity_output = NaN .* zeros(k, npatt);\n\n% ---------------------------------\n% Missing/excluded values image-wise\n% ---------------------------------\n\nif treat_zero_as_data==true\n    badvals = isnan(dat);\nelse\n    badvals = dat == 0 | isnan(dat);  % Matrix. not used for binary overlap (SG).\nend\n\n\n\n\n% ---------------------------------\n% Main similarity calculation\n% ---------------------------------\n\n% if ~docorr && ~docosine\nif strcmp(sim_metric,'dotproduct')\n    % dot product. No need to remove missing voxels because dotproduct is\n    % the same either way.\n    \n    similarity_output = dotproduct(dat, pattern_weights);\n    \nelse\n    \n    % all other metrics\n    for i = 1:npatt\n        \n        switch sim_metric\n            case 'corr'\n                \n               \n                    similarity_output(:, i) = image_correlation(dat, pattern_weights(:, i), badvals);\n            case 'cosine'\n                \n                similarity_output(:, i) = cosine_similarity(dat, pattern_weights(:, i), badvals);\n                \n            case 'overlap'\n                \n                similarity_output(:, i) = overlap_similarity(dat, pattern_weights(:, i));\n                \n            case 'posterior_overlap'\n                \n                similarity_output(:, i) = posterior_overlap_similarity(dat, pattern_weights(:, i));\n                \n            otherwise\n                error('Invalid similarity metric.');\n        end\n        \n    end\n    \nend % pattern sim calculation\n\n\n% ---------------------------------\n% Weight cases based on distance to mean\n% ---------------------------------\n\nif any(strcmp(varargin,'weighted')) % if we want to weight data based on similarity to group mean\n    mean_dat = mean(dat,2); %sample mean\n    distances = squareform(pdist([dat,mean_dat]')); %use other measures?\n    weights=1./distances(1:end-1,end);\n    weights=weights-min(weights)+1e-12; %min0\n    weights=weights./mean(weights); % scale so weights are positive with mean value one\nelse %\n    weights=ones(size(dat,2),1); %just use a weight of one\nend\n\n\nsimilarity_output = bsxfun(@times,similarity_output,weights);\n\n% ---------------------------------\n% Warnings\n% ---------------------------------\n\nif doprintwarnings && any(badvals(:)) && ~doignoremissing && ~strcmp(sim_metric,'overlap')\n    \n    \n    for i = 1:npatt\n        \n        inmask = ~(pattern_weights(:, i) == 0 | isnan(pattern_weights(:, i)));\n        \n        bad_in_mask = bsxfun(@times, badvals, inmask);\n        bad_in_mask = sum(bad_in_mask);  % how many bad values are in mask, across images\n        \n        if any(bad_in_mask)\n            fprintf('Warning: Some images have zero values in some of the %3.0f voxels in weight mask. These will be excluded from similarity analysis image-wise.\\n', sum(inmask));\n            disp('Number of zero or NaN values within weight mask, by input image:');\n            \n            for j = 1:length(bad_in_mask)\n                fprintf('%3.0f ', bad_in_mask(j));\n            end\n            fprintf('\\n');\n        end\n        \n    end  % pattern index\n    \nend % bad val warnings\n\nend % main function\n\n\n\n\n% ---------------------------------\n% *\n% Sub-functions\n% *\n% ---------------------------------\n\n\n% FUNCTIONS for dot product, cosine_similarity, correlation with missing\n% values (voxels) that may vary on a data image-by-image basis.\n\nfunction pexp = dotproduct(X, weights)\n\n% X = voxels x images data matrix, e.g., dat.dat\n% weights is voxels x 1 weight data\n% badvals is voxels x images logical matrix of voxels to exclude image-wise\n\n% badvals do not matter\npexp = (weights' * X)';\n\nend % function\n\n\nfunction [ab, a, b] = image_norms(dat, pattern_weights, badvals)\n% [a, b] = image_norms(dat, pattern_weights, badvals)\n% dat = voxels dat images data matrix, e.g., dat\n% pattern_weights is voxels dat 1 weight data\n% badvals is voxels dat images logical matrix of voxels to exclude image-wise\n\n% Norm for image data.\n% All non-zero, non-NaN values valid. zero/nan have no\n% effect implictly.\n\na = nansum(dat .^ 2)' .^ .5;\n\nfor i = 1:size(dat, 2)    % Loop because we may have different voxel exclusions in each image\n    \n    inmask = ~badvals(:, i);\n    \n    b(i, 1) = nansum(pattern_weights(inmask) .^ 2) .^ .5;  % Norm for pattern_weights, excluding out-of-image pattern_weights image-wise\n    \nend\n\nab = a .* b;\n\nend % function\n\n\nfunction cossim = cosine_similarity(dat, pattern_weights, badvals)\n\npexp = dotproduct(dat, pattern_weights);\n\nab = image_norms(dat, pattern_weights, badvals);\n\ncossim = pexp ./ ab;\n\n% when division by zero (e.g. non-overlapping binary masks) return 0.\n% Stephan 2017/3/8\nif any(ab==0)\n    cossim(isnan(cossim)) = 0;\nend\n\nend % function\n\n\nfunction r = image_correlation(dat, pattern_weights, badvals, varargin)\n\n\nfor i = 1:size(dat, 2)    % Loop because we may have different voxel exclusions in each image\n    \n    inmask = ~badvals(:, i);\n            \n    r(i, 1) = corr(pattern_weights(inmask), dat(inmask, i));  % Correlation, excluding out-of-image pattern_weights image-wise\n        \n   \nend\n\n\nend % function\n\n\nfunction r = overlap_similarity(dat, pattern_weights)\n\n% check for binary data\nif numel(unique(dat(:)))>2 || sum(unique(dat(:))-[0; 1])~=0 ...\n        || numel(unique(pattern_weights(:)))>2 || sum(unique(pattern_weights(:))-[0; 1])~=0\n    if numel(unique(round(pattern_weights))) == 2\n        pattern_weights = round(pattern_weights); % an easy (but maybe not optimal) solution for the resampled binary mask\n    else\n        error('Binary overlap similarity needs binary data [0 1] input.');\n    end\nend\n\n% compute overlap\nfor i = 1:size(dat, 2)\n    \n    inmask = isfinite(dat(:,i)) & isfinite(pattern_weights);\n    nVox = sum(inmask);\n    \n    r(i,1) = sum(dat(inmask,i)==1 & pattern_weights(inmask)==1) / nVox; % overlap excluding NaNs\n    \nend\n\nend % function\n\n\nfunction r = posterior_overlap_similarity(dat, pattern_weights)\n\n% check for binary data\nif numel(unique(dat(:)))>2 || sum(unique(dat(:))-[0; 1])~=0 ...\n        || numel(unique(pattern_weights(:)))>2 || sum(unique(pattern_weights(:))-[0; 1])~=0\n    if numel(unique(round(pattern_weights))) == 2\n        pattern_weights = round(pattern_weights); % an easy (but maybe not optimal) solution for the resampled binary mask\n    else\n        error('Binary overlap similarity needs binary data [0 1] input.');\n    end\nend\n\n% compute posterior overlap\nfor i = 1:size(dat, 2)\n    \n    % calculate the space\n    inmask = sum(dat,2)~=0;\n    % calculate P(pattern | data) using overlaps\n    r(i,1) = sum(dat(inmask,i)==1 & pattern_weights(inmask)==1)./sum(dat(inmask,i)==1);\n    \nend\n\n\nend\n\nfunction R = weightedcorrs(Y, w)\n%\n%   WEIGHTEDCORRS returns a symmetric matrix R of weighted correlation\n%   coefficients calculated from an input T-by-N matrix Y whose rows are\n%   observations and whose columns are variables and an input T-by-1 vector\n%   w of weights for the observations. This function may be a valid\n%   alternative to CORRCOEF if observations are not all equally relevant\n%   and need to be weighted according to some theoretical hypothesis or\n%   knowledge.\n%\n%   R = WEIGHTEDCORRS(Y, w) returns a positive semidefinite matrix R,\n%   i.e. all its eigenvalues are non-negative (see Example 1).\n\n%\n% % ======================================================================\n%\n%   See also CORRCOEF, COV, STD, MEAN.\n%\n% % ======================================================================\n%\n%-*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-*%\n%                                                                                               %\n%            Author: Liber Eleutherios                                             %\n%            E-Mail: libereleutherios@gmail.com                             %\n%            Date: 23 July 2008                                                      %\n%            Updated: 6 June 2012                                                 %\n%                                                                                               %\n%-*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-*%\n%\n% % ======================================================================\n%\n% Check input\nctrl = isvector(w) & isreal(w) & ~any(isnan(w)) & ~any(isinf(w)) & all(w > 0);\nif ctrl\n    w = w(:) / sum(w);                                                          % w is column vector\nelse\n    error('Check w: it needs be a vector of real positive numbers with no infinite or nan values!')\nend\nctrl = isreal(Y) & ~any(isnan(Y)) & ~any(isinf(Y)) & (size(size(Y), 2) == 2);\nif ~ctrl\n    error('Check Y: it needs be a 2D matrix of real numbers with no infinite or nan values!')\nend\nctrl = length(w) == size(Y, 1);\nif ~ctrl\n    error('size(Y, 1) has to be equal to length(w)!')\nend\n[T, N] = size(Y);                                                             % T: number of observations; N: number of variables\ntemp = Y - repmat(w' * Y, T, 1);                                              % Remove mean (which is, also, weighted)\ntemp = temp' * (temp .* repmat(w, 1, N));                                     % Covariance Matrix (which is weighted)\ntemp = 0.5 * (temp + temp');                                                  % Must be exactly symmetric\nR = diag(temp);                                                               % Variances\nR = temp ./ sqrt(R * R');\n\nend % function\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/Statistics_tools/canlab_pattern_similarity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5786282089910433}}
{"text": "% Copyright 2016 Google Inc.\n%\n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n%\n% http ://www.apache.org/licenses/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n\nfunction A = buildDerivXMatrix(grid_size)\n\n% d/dx for every entry in the first slice except the last column.\nm = grid_size(1) * (grid_size(2) - 1);\nn = grid_size(1) * grid_size(2);\ne = ones(m, 1);\nd_dx = spdiags([-e, e], [0, grid_size(1)], m, n);\n\nA = sparse(0, 0);\n\nfor v = 1:grid_size(5)\n    for u = 1:grid_size(4)\n        for k = 1:grid_size(3)\n            A = blkdiag(A, d_dx);\n        end\n    end\nend\n", "meta": {"author": "mahmoudnafifi", "repo": "Exposure_Correction", "sha": "01300c3ff186123d405141202f8201ebd59965fa", "save_path": "github-repos/MATLAB/mahmoudnafifi-Exposure_Correction", "path": "github-repos/MATLAB/mahmoudnafifi-Exposure_Correction/Exposure_Correction-01300c3ff186123d405141202f8201ebd59965fa/bgu/buildDerivXMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5786282004792547}}
{"text": "function result = regularizeGray(input,nodes,edges,lambda,tol,maxiters)\n%\n% result = regularizeMap(view,input,lambda)\n%\n% input: data from one scan, e.g.,\n%    co(:,1) or  z = amp(:,1).*exp(i*ph(:,1))\n% can have NaNs indicating no data (e.g., for voxels below cothresh)\n%\n% nodes:  8xN array of (x,y,z,num_edges,edge_offset,layer,dist,pqindex).\n%\n% edges:  1xM array of node indices.  The edge_offset of\n%    each node points into the starting location of its set\n%    of edges.\n% where N, M are the number of nodes, edges in the graph.\n%\n% lambda: smoothness coefficient\n%\n% result^{i+1}[x] = c2[x] s^i[x]               data missing\n% \t\t  = c1[x] (input[x] + lambda s^i[x])     otherwise\n% \n% c_1[x] = 1/(1 + numNeighbors * lambda)\n% c_2[x] = 1/numNeighbors\n% s[x] = sumNeighbors\n\n% Defaults for tol and maxiters\n%\nif ~exist('tol','var')\n  tol = 1e-2;\nend\nif ~exist('maxiters','var')\n  maxiters = 100;\nend\n\n% Get indices for missing data\n%\nNaNs=find(isnan(input));\nnotNaNs=find(~isnan(input));\n\n% Initialize result\n%\n\nnumNodes = length(input);\nresult = zeros(size(input));\nresult(notNaNs) = input(notNaNs);\nnewresult = zeros(size(input));\n\n% Get numNeighbors and compute c1 and c2\n%\nnumNeighbors = double(nodes(4,:));\nedges        = double(edges);\n\nedgeOffsets = double(nodes(5,:));\nc1 = 1 ./ (1 + lambda*numNeighbors);\nc2 = 1 ./ numNeighbors;\nc2(find(numNeighbors==0)) = 0;\nc = zeros(size(input));\nc(notNaNs) = c1(notNaNs);\nc(NaNs) = c2(NaNs);\n\n% Initialize iterations\n%\ninputSD=std(input(notNaNs));\nsnr=Inf;\niter=0;\n\nwaitHandle = mrvWaitbar(0,'Smoothing data.  Please wait...');\nwhile ((snr>tol) & (iter<maxiters))\n   mrvWaitbar(iter/maxiters)\n   iter = iter+1;\n   \n   % Compute sumNeighbors\n   sumNeighbors = sumOfNeighbors(real(result),edges,edgeOffsets,numNeighbors) + ...\n      j*sumOfNeighbors(imag(result),edges,edgeOffsets,numNeighbors);\n\n   \n   newresult(NaNs) = c(NaNs) .* sumNeighbors(NaNs);\n   newresult(notNaNs) = c(notNaNs) .* (input(notNaNs) + lambda*sumNeighbors(notNaNs));\n   \n\n   % Compute snr (stopping criterion)\n\n   snr=sqrt(mean(abs(newresult-result).^2))/inputSD;\n   result=newresult;\nend\nclose(waitHandle);\n\nif (iter >= maxiters)\n   disp(['Warning: maximum number of iterations exceeded: ',num2str(maxiters)]);\nend\n\nreturn;\n\n%%% Test code\n\nmrLoadRet\n\n% open volume window\n% switch to gray mode\n% load anatomy\n% view phase\n\n% coronal slice 60\n\ncurScan = getCurScan(VOLUME{1});\namp = VOLUME{1}.amp(:,curScan);\nco = VOLUME{1}.co(:,curScan);\nph = VOLUME{1}.ph(:,curScan);\nz = co.*exp(i*ph);\n\nzthresh = z;\nbelowThreshIndices = find(co<.2);\nzthresh(belowThreshIndices) = NaN;\n\nresult = regularizeGray(zthresh,VOLUME{1}.nodes,VOLUME{1}.edges,.1,1e-2);\nnewPh = angle(result);\nnewPh(newPh<0) = newPh(newPh<0)+pi*2;\nVOLUME{1}.ph(:,curScan) = newPh;\nVOLUME{1}.ph(:,curScan) = ph;\n\n%%% Compile MEX file for sumOfNeighbors\n% mcc -ir sumOfNeighbors\n\n%%% Test sumOfNeighbors\n\nnodes = VOLUME{1}.nodes;\nedges = VOLUME{1}.edges;\nnumNeighbors = nodes(4,:);\nsumNeighbors = sumOfNeighbors(real(z),nodes,edges,numNeighbors);\nfigure(3)\nplot(sumNeighbors,'.')\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/SignalProc/regularizeGray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5786281953732659}}
{"text": "function seg=bbxflatsegment(node,loop)\n%\n% seg=bbxflatsegment(node,loop)\n%\n% decompose edge loops into flat segments along the x/y/z \n% planes of the bounding box\n%\n% author: Qianqian Fang, <q.fang at neu.edu>\n% date: 2008/04/08\n%\n% input:   \n%    node:  x,y,z coordinates of each node of the mesh\n%    loop:  input, a single vector separated by NaN, each segment\n%             is a close-polygon consisted by node IDs \n% output:\n%    seg:   output, a single vector separated by NaN, each segment\n%             is a close-polygon on x/y/z plane \n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\npos=node(loop,:);\n\n% get the bounding box\nmi=min(pos);\nma=max(pos);\n\n% extract nodes on the bounding box\nidx0=find(abs(pos(:,1)-mi(1))<1e-6)';\nidx1=find(abs(pos(:,1)-ma(1))<1e-6)';\n\nidy0=find(abs(pos(:,2)-mi(2))<1e-6)';\nidy1=find(abs(pos(:,2)-ma(2))<1e-6)';\n\nidz0=find(abs(pos(:,3)-mi(3))<1e-6)';\nidz1=find(abs(pos(:,3)-ma(3))<1e-6)';\n\n% need to be more than 3 points to make a flat polygon\n\nif(length(idx0)<=3) idx0=[]; end\nif(length(idx1)<=3) idx1=[]; end\nif(length(idy0)<=3) idy0=[]; end\nif(length(idy1)<=3) idy1=[]; end\nif(length(idz0)<=3) idz0=[]; end\nif(length(idz1)<=3) idz1=[]; end\n\nnn=length(loop);\n\n% if the original is a flat polygon, return\n\nif(unique(length(idx0))==nn || unique(length(idx1))==nn ...\n  |unique(length(idy0))==nn || unique(length(idy1))==nn ...\n  |unique(length(idz0))==nn || unique(length(idz1))==nn) \n    seg=loop(:)';\n    return;\nend\n\n% otherwise, find the combination that split the loop\n\nif(length(unique([idx0 idy0 idz0]))==nn)\n   seg= [loop(idx0),nan,loop(idy0),nan,loop(idz0)];\nelseif(length(unique([idx0 idy1 idz0]))==nn)\n   seg= [loop(idx0),nan,loop(idy1),nan,loop(idz0)];\nelseif(length(unique([idx0 idy0 idz1]))==nn)\n   seg= [loop(idx0),nan,loop(idy0),nan,loop(idz1)];\nelseif(length(unique([idx0 idy1 idz1]))==nn)\n   seg= [loop(idx0),nan,loop(idy1),nan,loop(idz1)];\nelseif(length(unique([idx1 idy0 idz0]))==nn)\n   seg= [loop(idx1),nan,loop(idy0),nan,loop(idz0)];\nelseif(length(unique([idx1 idy1 idz0]))==nn)\n   seg= [loop(idx1),nan,loop(idy1),nan,loop(idz0)];\nelseif(length(unique([idx1 idy0 idz1]))==nn)\n   seg= [loop(idx1),nan,loop(idy0),nan,loop(idz1)];\nelseif(length(unique([idx1 idy1 idz1]))==nn)\n   seg= [loop(idx1),nan,loop(idy1),nan,loop(idz1)];\nelse\n    seg=[];\nend\n\n% remove pattern [ ... nan nan ...] in the result\n\nif(length(seg) && any(isnan(seg)))\n    id=regexp(sprintf('%d',isnan(seg)),'11');\n    if(length(id))\n        seg(id+1)=[];\n    end\nend\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/bbxflatsegment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5785818817246582}}
{"text": "function b = r8gb_vxm ( m, n, ml, mu, a, x )\n\n%*****************************************************************************80\n%\n%% R8GB_VXM multiplies a vector by a R8GB matrix.\n%\n%  Discussion:\n%\n%    An M by N banded matrix A with lower bandwidth ML and upper bandwidth MU\n%    is assumed to be entirely zero, except for the main diagonal, and\n%    entries in the ML nearest subdiagonals, and MU nearest superdiagonals.\n%\n%    LINPACK and LAPACK \"R8GB\" storage for such a matrix generally includes\n%    room for ML extra superdiagonals, which may be required to store\n%    nonzero entries generated during Gaussian elimination.\n%\n%    The original M by N matrix is \"collapsed\" downward, so that diagonals\n%    become rows of the storage array, while columns are preserved.  The\n%    collapsed array is logically 2*ML+MU+1 by N.\n%\n%    LINPACK and LAPACK storage of general band matrices requires\n%    an extra ML upper diagonals for possible fill in entries during\n%    Gauss elimination.  This routine does not access any entries\n%    in the fill in diagonals, because it assumes that the matrix\n%    has NOT had Gauss elimination applied to it.  If the matrix\n%    has been Gauss eliminated, then the routine R8GB_MU must be\n%    used instead.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    18 November 2003\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer M, the number of rows of the matrix.\n%    M must be positive.\n%\n%    Input, integer N, the number of columns of the matrix.\n%    N must be positive.\n%\n%    Input, integer ML, MU, the lower and upper bandwidths.\n%    ML and MU must be nonnegative, and no greater than min(M,N)-1.\n%\n%    Input, real A(2*ML+MU+1,N), the R8GB matrix.\n%\n%    Input, real X(M), 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 j = 1 : n\n    ilo = max ( 1, j - mu );\n    ihi = min ( m, j + ml );\n    for i = ilo : ihi\n      b(j) = b(j) + x(i) * a(i-j+ml+mu+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/r8gb_vxm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5785818700208091}}
{"text": "function mono_upto_next_grevlex_test ( )\n\n%*****************************************************************************80\n%\n%% MONO_UPTO_NEXT_GREVLEX_TEST tests MONO_UPTO_NEXT_GREVLEX.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 November 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'MONO_UPTO_NEXT_GREVLEX_TEST\\n' );\n  fprintf ( 1, '  MONO_UPTO_NEXT_GREVLEX can list the monomials\\n' );\n  fprintf ( 1, '  in M variables, of total degree up to N,\\n' );\n  fprintf ( 1, '  one at a time, in graded reverse lexicographic order.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  We start the process with (0,0,...0,0).\\n' );\n  fprintf ( 1, '  The process ends with (N,0,...,0,0)\\n' );\n\n  test_num = 2;\n  n_test = [ 4, 3 ];\n  m_test = [ 3, 4 ];\n\n  for test = 1 : test_num\n\n    n = n_test(test);\n    m = m_test(test);\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Let M = %d\\n', m );\n    fprintf ( 1, '      N = %d\\n', n );\n    fprintf ( 1, '\\n' );\n\n    x = zeros ( m, 1 );\n    i = 1;\n\n    while ( 1 )\n\n      fprintf ( 1, '  %2d:', i );\n      for j = 1 : m\n        fprintf ( 1, '  %1d', x(j) );\n      end\n      fprintf ( 1, '\\n' );\n\n      if ( x(1) == n )\n        break\n      end\n\n      x = mono_upto_next_grevlex ( m, n, x );\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/monomial/mono_upto_next_grevlex_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.5785818605326395}}
{"text": "function pass = test_eigs()\n% TAD, 10 Jan 2014\n\ntol = 1e-7;\n\ndom = [-pi/2, pi/2];\nD2 = operatorBlock.diff(dom, 2);\nE = functionalBlock.eval(dom);\nEl = E(dom(1));\nEr = E(dom(end));\nL = linop(D2);\nL = addbc(L, El, 0);\nL = addbc(L, Er, 0);\n\ne_true = flipud(-(1:6).'.^2);\n\n%%\nprefs = cheboppref;\nprefs.discretization = @chebcolloc2;\n[V, D] = eigs(L, 6, prefs);\ne = diag(D);\nerr(1) = norm(e - e_true, inf);\n% Check that we actually computed eigenfunctions\nerr(2) = norm(L*V-V*D);\n%%\nprefs.discretization = @ultraS;\n[V, D] = eigs(L, 6, 0, prefs);\ne = diag(D);\nerr(3) = norm(e - e_true, inf);\nerr(4) = norm(L*V-V*D);\n%%\nprefs.discretization = @chebcolloc1;\n[V, D] = eigs(L, 6, prefs);\ne = diag(D);\nerr(5) = norm(e - e_true, inf);\nerr(6) = norm(L*V-V*D);\n%%\npass = err < tol;\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/linop/test_eigs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867585368343, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.578581851357195}}
{"text": "function [Xw, Yw, Zw]=imageToWorld(Xi, Yi, camPar)\n\n% if scalar, just up/downscale = orthographic\nif camPar.ortho\n    Xw=Xi*camPar.scale;\n    Yw=Yi*camPar.scale;\n    Zw=0;\nelse\n    \n    mGeo=camPar.mGeo;\n    mExt=camPar.mExt;\n    mInt=camPar.mInt;\n    \n    mTx=mExt.mTx;\n    mTy=mExt.mTy;\n    mTz=mExt.mTz;\n    \n    mT=[mExt.mTx;mExt.mTy;mExt.mTz];\n    \n    %% internal init\n    sa = sin(mExt.mRx);\n    ca = cos(mExt.mRx);\n    sb = sin(mExt.mRy);\n    cb = cos(mExt.mRy);\n    sg = sin(mExt.mRz);\n    cg = cos(mExt.mRz);\n    \n    mR11 = cb * cg;\n    mR12 = cg * sa * sb - ca * sg;\n    mR13 = sa * sg + ca * cg * sb;\n    mR21 = cb * sg;\n    mR22 = sa * sb * sg + ca * cg;\n    mR23 = ca * sb * sg - cg * sa;\n    mR31 = -sb;\n    mR32 = cb * sa;\n    mR33 = ca * cb;\n    \n    \n    \n    % \t\t/* convert from image to distorted sensor coordinates */\n    Xd = mGeo.mDpx * (Xi - mInt.mCx) / mInt.mSx;\n    Yd = mGeo.mDpy * (Yi - mInt.mCy);\n    \n    % \t\t/* convert from distorted sensor to undistorted sensor plane coordinates */\n    [Xu Yu]=distortedToUndistortedSensorCoord (Xd, Yd, mInt.mKappa1);\n    \n    % \t\t/* calculate the corresponding xw and yw world coordinates\t */\n    % \t\t/* (these equations were derived by simply inverting\t */\n    % \t\t/* the perspective projection equations using Macsyma)\t */\n    Zw=0;\n    common_denominator = ((mR11 * mR32 - mR12 * mR31) * Yu + ...\n        (mR22 * mR31 - mR21 * mR32) * Xu - ...\n        mInt.mFocal * mR11 * mR22 + mInt.mFocal * mR12 * mR21);\n    \n    Xw = (((mR12 * mR33 - mR13 * mR32) * Yu + ...\n        (mR23 * mR32 - mR22 * mR33) * Xu - ...\n        mInt.mFocal * mR12 * mR23 + mInt.mFocal * mR13 * mR22) * Zw + ...\n        (mR12 * mTz - mR32 * mTx) * Yu + ...\n        (mR32 * mTy - mR22 * mTz) * Xu - ...\n        mInt.mFocal * mR12 * mTy + mInt.mFocal * mR22 * mTx) / common_denominator;\n    \n    Yw = -(((mR11 * mR33 - mR13 * mR31) * Yu + ...\n        (mR23 * mR31 - mR21 * mR33) * Xu - ...\n        mInt.mFocal * mR11 * mR23 + mInt.mFocal * mR13 * mR21) * Zw + ...\n        (mR11 * mTz - mR31 * mTx) * Yu + ...\n        (mR31 * mTy - mR21 * mTz) * Xu - ...\n        mInt.mFocal * mR11 * mTy + mInt.mFocal * mR21 * mTx) / common_denominator;\n% else\n%     error('imageToWorld: camera parameters format unknown');\nend\nend", "meta": {"author": "VisDrone", "repo": "DroneCrowd", "sha": "3d25637f93f9476b4c949b6b9362287635b1a8c3", "save_path": "github-repos/MATLAB/VisDrone-DroneCrowd", "path": "github-repos/MATLAB/VisDrone-DroneCrowd/DroneCrowd-3d25637f93f9476b4c949b6b9362287635b1a8c3/STNNet/DroneCrowd-MOT-toolkit/utils/camera/imageToWorld.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5785717259003751}}
{"text": "% @TENMAT\n%\n% Files\n%   ctranspose - Complex conjugate transpose for tenmat.\n%   disp       - Command window display of a matricized tensor (tenmat).\n%   display    - Command window display of a tenmat.\n%   double     - Convert tenmat to double array.\n%   end        - Last index of indexing expression for tenmat.\n%   minus      - Binary subtraction (-) for tenmat.\n%   mtimes     - Multiplies two tenmat objects.\n%   norm       - Frobenius norm of a tenmat.\n%   plus       - Binary addition (+) for tenmat. \n%   size       - Size of tenmat.\n%   subsasgn   - Subscripted assignment for tenmat.  \n%   subsref    - Subscripted reference for tenmat.\n%   tenmat     - Create a matricized tensor.\n%   tsize      - Tensor size of tenmat.\n%   uminus     - Unary minus (-) for tenmat.\n%   uplus      - Unary plus (+) for tenmat.\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/@tenmat/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7634837743174789, "lm_q1q2_score": 0.5785637067373035}}
{"text": "% See http://stackoverflow.com/questions/16146599/create-artificial-data-in-matlab\n% and http://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly\n\nfigure;\nhold on;\ndotsize = 12;\n colormap([1 0 .5;   % magenta\n           0 0 .8;   % blue\n           0 .6 0;   % dark green\n           .3 1 0]); % bright green\n\nsubplot(231);\ndata = twospirals();\nscatter(data(:,1), data(:,2), dotsize, data(:,3)); axis equal;\ntitle('Two spirals');\n\nsubplot(232);\ndata = clusterincluster();\nscatter(data(:,1), data(:,2), dotsize, data(:,3)); axis equal;\ntitle('Cluster in cluster');\n\nsubplot(233);\ndata = corners();\nscatter(data(:,1), data(:,2), dotsize, data(:,3)); axis equal;\ntitle('Corners');\n\nsubplot(234);\ndata = halfkernel();\nscatter(data(:,1), data(:,2), dotsize, data(:,3)); axis equal;\ntitle('Half-kernel');\n\nsubplot(235);\ndata = crescentfullmoon();\nscatter(data(:,1), data(:,2), dotsize, data(:,3)); axis equal;\ntitle('Crescent & Full Moon');\n\nsubplot(236);\ndata = outlier();\nscatter(data(:,1), data(:,2), dotsize, data(:,3)); axis equal;\ntitle('Outlier');", "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/pointsclouds/to_be_included/datasetsdemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.5785637067373034}}
{"text": "function y = sgemv ( trans, m, n, alpha, a, lda, x, incx, beta, y, incy )\n\n%*****************************************************************************80\n%\n%% SGEMV computes y := alpha * A * x + beta * y for general matrix A.\n%\n%  Discussion:\n%\n%    SGEMV performs one of the matrix-vector operations\n%      y := alpha*A *x + beta*y\n%    or\n%      y := alpha*A'*x + beta*y,\n%    where alpha and beta are scalars, x and y are vectors and A is an\n%    m by n matrix.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    11 February 2014\n%\n%  Author:\n%\n%    Jack Dongarra, Jeremy Du Croz, Sven Hammarling,  Richard Hanson.\n%\n%  Parameters:\n%\n%    Input, character TRANS, specifies the operation to be performed:\n%    'n' or 'N'   y := alpha*A *x + beta*y.\n%    't' or 'T'   y := alpha*A'*x + beta*y.\n%    'c' or 'C'   y := alpha*A'*x + beta*y.\n%\n%    Input, integer M, the number of rows of the matrix A.\n%    0 <= M.\n%\n%    Input, integer N, the number of columns of the matrix A.\n%    0 <= N.\n%\n%    Input, real ALPHA, the scalar multiplier for A * x.\n%\n%    Input, real A(LDA,N).  The M x N subarray contains\n%    the matrix A.\n%\n%    Input, integer LDA, the the first dimension of A as declared\n%    in the calling routine.  max ( 1, M ) <= LDA.\n%\n%    Input, real X(*), an array containing the vector to be \n%    multiplied by the matrix A.  \n%    If TRANS = 'N' or 'n', then X must contain N entries, stored in INCX \n%    increments in a space of at least ( 1 + ( N - 1 ) * abs ( INCX ) ) \n%    locations.\n%    Otherwise, X must contain M entries, store in INCX increments\n%    in a space of at least ( 1 + ( M - 1 ) * abs ( INCX ) ) locations.\n%\n%    Input, integer INCX, the increment for the elements of\n%    X.  INCX must not be zero.\n%\n%    Input, real BETA, the scalar multiplier for Y.\n%\n%    Input/output, real Y(*), an array containing the vector to\n%    be scaled and incremented by A*X.\n%    If TRANS = 'N' or 'n', then Y must contain M entries, stored in INCY\n%    increments in a space of at least ( 1 + ( M - 1 ) * abs ( INCY ) ) \n%    locations.\n%    Otherwise, Y must contain N entries, store in INCY increments\n%    in a space of at least ( 1 + ( N - 1 ) * abs ( INCY ) ) locations.\n%\n%    Input, integer INCY, the increment for the elements of\n%    Y.  INCY must not be zero.\n%\n\n%\n%  Test the input parameters.\n%\n  info = 0;\n  if ( ~ ( trans == 'N' || trans == 'n' || ...\n           trans == 'T' || trans == 't' || ...\n           trans == 'C' || trans == 'c' ) )\n    info = 1;\n    fprintf ( 1, 'SGEMV rejects input argument number %d\\n', info );\n    error ( 'SGEMV - Fatal error!' );\n  end\n\n  if ( m < 0 )\n    info = 2;\n    fprintf ( 1, 'SGEMV rejects input argument number %d\\n', info );\n    error ( 'SGEMV - Fatal error!' );\n  end\n\n  if ( n < 0 )\n    info = 3;\n    fprintf ( 1, 'SGEMV rejects input argument number %d\\n', info );\n    error ( 'SGEMV - Fatal error!' );\n  end\n\n  if ( lda < max ( 1 : m ) )\n    info = 6;\n    fprintf ( 1, 'SGEMV rejects input argument number %d\\n', info );\n    error ( 'SGEMV - Fatal error!' );\n  end\n\n  if ( incx == 0 )\n    info = 8;\n    fprintf ( 1, 'SGEMV rejects input argument number %d\\n', info );\n    error ( 'SGEMV - Fatal error!' );\n  end\n\n  if ( incy == 0 )\n    info = 11;\n    fprintf ( 1, 'SGEMV rejects input argument number %d\\n', info );\n    error ( 'SGEMV - Fatal error!' );\n  end\n%\n%  Quick return if possible.\n%\n  if ( ( m == 0 ) || ...\n       ( n == 0 ) || ...\n       ( alpha == 0.0 && beta == 1.0 ) )\n   return\n  end\n%\n%  Set LENX and LENY, the lengths of the vectors x and y, and set\n%  up the start points in X and Y.\n%\n  if ( trans == 'N' || trans == 'n' )\n    lenx = n;\n    leny = m;\n  else\n    lenx = m;\n    leny = n;\n  end\n\n  if ( 0 < incx )\n    kx = 1;\n  else\n    kx = 1 - ( lenx - 1 ) * incx;\n  end\n\n  if ( 0 < incy )\n    ky = 1;\n  else\n    ky = 1 - ( leny - 1 ) * incy;\n  end\n%\n%  Start the operations. In this version the elements of A are\n%  accessed sequentially with one pass through A.\n%\n%  First form  y := beta*y.\n%\n  if ( beta ~= 1.0 )\n    if ( incy == 1 )\n      if ( beta == 0.0 )\n        y(1:leny) = 0.0;\n      else\n        y(1:leny) = beta * y(1:leny);\n      end\n    else\n      iy = ky;\n      if ( beta == 0.0 )\n        for i = 1 : leny\n          y(iy) = 0.0;\n          iy = iy + incy;\n        end\n      else\n        for i = 1 : leny\n          y(iy) = beta * y(iy);\n          iy = iy + incy;\n        end\n      end\n    end\n  end\n\n  if ( alpha == 0.0 )\n    return\n  end\n%\n%  Form y := alpha*A*x + y.\n%\n  if ( trans == 'N' || trans == 'n' )\n    jx = kx;\n    if ( incy == 1 )\n      for j = 1 : n\n        if ( x(jx) ~= 0.0 )\n          temp = alpha * x(jx);\n          for i = 1 : m\n            y(i) = y(i) + temp * a(i,j);\n          end\n        end\n        jx = jx + incx;\n      end\n    else\n      for j = 1 : n\n        if ( x(jx) ~= 0.0 )\n          temp = alpha * x(jx);\n          iy = ky;\n          for i = 1 : m\n            y(iy) = y(iy) + temp * a(i,j);\n            iy = iy + incy;\n          end\n        end\n        jx = jx + incx;\n      end\n    end\n%\n%  Form y := alpha*A'*x + y.\n%\n  else\n    jy = ky;\n    if ( incx == 1 )\n      for j = 1 : n\n        temp = 0.0;\n        for i = 1 : m\n          temp = temp + a(i,j) * x(i);\n        end\n        y(jy) = y(jy) + alpha * temp;\n        jy = jy + incy;\n      end\n    else\n      for j = 1 : n\n        temp = 0.0;\n        ix = kx;\n        for i = 1 : m\n          temp = temp + a(i,j) * x(ix);\n          ix = ix + incx;\n        end\n        y(jy) = y(jy) + alpha * temp;\n        jy = jy + incy;\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/blas2/sgemv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.5785637025610627}}
{"text": "function varargout = ellipseAsPolygon(ellipse, N)\n%ELLIPSEASPOLYGON Convert an ellipse into a series of points\n%\n%   Deprecated, use ellipseToPolygon instead.\n%\n%   P = ellipseAsPolygon(ELL, N);\n%   converts ELL given as [x0 y0 a b] or [x0 y0 a b theta] into a polygon\n%   with N edges. The result P is (N+1)-by-2 array containing coordinates\n%   of the N+1 vertices of the polygon.\n%   The resulting polygon is closed, i.e. the last point is the same as the\n%   first one.\n%\n%   P = ellipseAsPolygon(ELL);\n%   Use a default number of edges equal to 72. This result in one piont for\n%   each 5 degrees.\n%   \n%   [X Y] = ellipseAsPolygon(...);\n%   Return the coordinates o fvertices in two separate arrays.\n%\n%   See also:\n%   ellipses2d, circleAsPolygon, rectAsPolygon, drawEllipse\n%\n%   ---------\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 06/04/2005.\n%\n\n%   HISTORY\n%   2011-03-30 use angles in degrees, add default value for N\n%   2011-12-09 deprecate\n\nwarning('matGeom:deprecated', ...\n    'function \"ellipseAsCurve\" is deprecated, use \"ellipseToPolygon\" instead');\n\n% format output\nif nargout <= 1\n    varargout = {ellipseToPolygon(ellipse, N)};\nelse\n    [x, y] = ellipseToPolygon(ellipse, N);\n    varargout = {x, y};\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/deprecated/geom2d/ellipseAsPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5785636985810213}}
{"text": "% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED \"AS IS.\"  THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.\n%\n% file: get_prop_diff_ci1.m\n% one-sided confidence intervals for the difference of proportions\n\n% 030113 tdr created\n\nfunction ci = get_prop_diff_ci1(x1,n1,x2,n2,alpha,method,verbose)\n\np1_hat = x1/n1; p2_hat = x2/n2; delta_p_hat = p1_hat - p2_hat;\na = find_lower_limit(x1,n1,x2,n2, alpha);\nb = find_upper_limit(x1,n1,x2,n2, alpha);\nci = [delta_p_hat a b];\n\n% ------------------------------------------------------------\n% find lower limit\n\nfunction limit = find_lower_limit(x1,n1,x2,n2,alpha)\n% alpha is 1-Pr{delta_p >= a}\np1_hat = x1/n1; p2_hat = x2/n2; delta_p_hat = p1_hat - p2_hat;\ntoo_small = -1; too_big = 1;\n\ntolerance = 1e-6;\nmax_count = 50;\n\ncount = 0;\nguess = (too_big + too_small)/2;\nalpha_guess = 1- prop_diff(x1,n1,x2,n2,guess);\nwhile (abs(alpha_guess - alpha) > tolerance & (count < max_count))\n    if (alpha_guess > alpha)\n        too_big = guess;\n        guess = (too_small + guess)/2;\n    else\n        too_small=guess;\n        guess = (too_big + guess)/2;\n    end;\n    count = count+1;\n    alpha_guess = 1 - prop_diff(x1,n1,x2,n2,guess);\nend;\n\nlimit = guess;\n\n\n% ------------------------------------------------------------\n% find upper limit\n\nfunction limit = find_upper_limit(x1,n1,x2,n2,alpha)\n% alpha is Pr{delta_p >= b}\np1_hat = x1/n1; p2_hat = x2/n2; delta_p_hat = p1_hat - p2_hat;\ntoo_small = -1; too_big = 1;\n\ntolerance = 1e-6;\nmax_count = 50;\ncount = 0;\nguess = (too_big + too_small)/2;\nalpha_guess = prop_diff(x1,n1,x2,n2,guess);\nwhile (abs(alpha_guess - alpha) > tolerance & (count < max_count))\n    if (alpha_guess < alpha)\n        too_big = guess;\n        guess = (too_small + guess)/2;\n    else\n        too_small=guess;\n        guess = (too_big + guess)/2;\n    end;\n    count = count+1;\n    alpha_guess = prop_diff(x1,n1,x2,n2,guess);\nend;\n\nlimit = guess;\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/3031-accurate-confidence-intervals/ci_tool/get_prop_diff_ci1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.5785636945028803}}
{"text": "% BOXPLOT Displays box plots of multiple data samples.\n%    BOXPLOT(X) produces a box plot of the data in X.  If X is a matrix there\n%    is one box per column, and if X is a vector there is just one box. On\n%    each box, the central mark is the median, the edges of the box are the\n%    25th and 75th percentiles, the whiskers extend to the most extreme\n%    datapoints the algorithm considers to be not outliers, and the outliers\n%    are plotted individually.  \n%    \n%    BOXPLOT(X,G) specifies one or more grouping variables G, producing a\n%    separate box for each set of X values sharing the same G value or\n%    values.  Grouping variables must have one row per element of X, or one\n%    row per column of X. Specify a single grouping variable in G by using a\n%    vector, a character array, a cell array of character vectors, a string\n%    array, or a vector categorical array; specify multiple grouping\n%    variables in G by using a cell array of these variable types, such as\n%    {G1 G2 G3}, or by using a matrix.  If multiple grouping variables are\n%    used, they must all be the same length.  Groups that contain a NaN or\n%    an empty string ('') in a grouping variable are omitted, and are not\n%    counted in the number of groups considered by other parameters.\n% \n%    By default, character and string grouping variables are sorted in the\n%    order they initially appear in the data, categorical grouping variables\n%    are sorted by the order of their levels, and numeric grouping variables\n%    are sorted in numeric order.  To control the order of the groups,\n%    you can either use categorical variables in G and specify the order of\n%    their levels, or use the 'positions' argument.\n% \n%    BOXPLOT(AX, X, ...) produces a box plot in axes with handle AX.\n%    \n%    BOXPLOT(..., 'PARAM1', val1, 'PARAM2', val2, ...) specifies optional\n%    parameter name/value pairs.\n%      'plotstyle'     'traditional' (default), or 'compact' to specify a\n%                      box style designed for plots with many groups.  The\n%                      plotstyle changes the defaults for some other\n%                      parameters, as described below.\n% \n%      'boxstyle'      'outline' (default) to draw an unfilled box with\n%                      dashed lines for whiskers, or 'filled' to draw a\n%                      narrow filled box with solid lines for whiskers.\n%      'colorgroup'    One or more grouping variables, of the same type as \n%                      permitted for G, specifying that the box color should\n%                      change when the specified variables change.  Default\n%                      is [] for no box color change.\n%      'colors'        Colors for boxes, specified as a single color (such\n%                      as 'r' or [1 0 0]) or multiple colors (such as 'rgbm'\n%                      or a three-column matrix of RGB values).  The sequence\n%                      is replicated or truncated as required, so for example\n%                      'rb' gives boxes that alternate in color.  Default\n%                      when no 'colorgroup' is specified is to use the same\n%                      color scheme for all boxes.  Default with\n%                      'colorgroup' is a modified hsv colormap. \n%      'datalim'       A two-element vector containing lower and upper limits,\n%                      used by 'extrememode' to determine which points are\n%                      extreme.  Default is [-Inf Inf].\n%      'extrememode'   'clip' (default) to move data outside the 'datalim'\n%                      limits to the limit, or 'compress' to distribute such\n%                      points evenly in a region just outside the limit,\n%                      retaining the relative order of the points.  A\n%                      dotted line marks the limit if any points are outside\n%                      it, and two gray lines mark the compression region if\n%                      any points are compressed.  Values at +/-Inf can be\n%                      clipped or compressed, but NaNs still do not appear\n%                      on the plot.  Box notches are drawn to scale and may\n%                      extend beyond the bounds if the median is inside the\n%                      limit; they are not drawn if the median is outside\n%                      the limits.  \n%      'factordirection' 'data' (default) to arrange the factors with the\n%                      first value next to the origin, 'list' to arrange the\n%                      factors left-to-right if on the x axis or top-to-\n%                      bottom if on the y axis, or 'auto' to use 'data' for\n%                      numeric grouping variables and 'list' for strings.\n%      'fullfactors'   'off' (default) to have one group for each unique row\n%                      of G, or 'on' to create a group for each possible \n%                      combination of group variable values, including\n%                      combinations that do not appear in the data.\n%      'factorseparator' Specifies which factors should have their values \n%                      separated by a grid line.  The value may be 'auto' or\n%                      a vector of grouping variable numbers.  For example,\n%                      [1 2] adds a separator line when the first or second\n%                      grouping variable changes value.  'auto' is [] for\n%                      one grouping variable and [1] for two or more\n%                      grouping variables. Default is [].\n%      'factorgap'     Specifies an extra gap to leave between boxes when\n%                      the corresponding grouping factor changes value,\n%                      expressed as a percentage of the width of the plot.\n%                      For example, with [3 1], the gap is 3% of the width\n%                      of the plot between groups with different values of\n%                      the first grouping variable, and 1% between groups\n%                      with the same value of the first grouping variable\n%                      but different values for the second.  'auto'\n%                      specifies that BOXPLOT should choose a gap\n%                      automatically.  Default is [].\n%      'grouporder'    Order of groups for plotting, specified as a cell\n%                      array of strings.  With multiple grouping variables,\n%                      separate values within each string with a comma.\n%                      Using categorical arrays as grouping variables is an\n%                      easier way to control the order of the boxes.\n%      'jitter'        Maximum distance D to displace outliers along the\n%                      factor axis by a uniform random amount, in order to\n%                      make duplicate points visible.  D = 1 makes the\n%                      jitter regions just touch between the closest\n%                      adjacent groups.  The default is 0.\n%      'labels'        Character array, cell array of strings, or numeric\n%                      vector of box labels.  May have one label per group\n%                      or per X value.  Multiple label variables may be\n%                      specified via a numeric matrix or a cell array\n%                      containing any of these types.\n%      'labelorientation' 'horizontal' (default) for horizontal labels, or\n%                      'inline' to draw the labels vertically when\n%                      'orientation' has its default 'vertical' value.\n%      'labelverbosity'  'all' (default) to display every label, 'minor' to\n%                      display a label for a factor only when that factor\n%                      has a different value from the previous group, or\n%                      'majorminor' to display a label for a factor when\n%                      that factor or any factor major to it has a\n%                      different value from the previous group.\n%      'medianstyle'   'line' (default) to draw a line for the median, or\n%                      'target' to draw a black dot inside a white circle.\n%      'notch'         'on' to draw comparison intervals using notches\n%                      ('plotstyle' is 'traditional) or triangular markers\n%                      ('plotstyle' is 'compact'), 'marker' to draw them\n%                      using triangular markers, or 'off' (default) to omit\n%                      them.  Two medians are significantly different at the\n%                      5% level if their intervals do not overlap.  The\n%                      interval endpoints are the extremes of the notches or\n%                      the centers of the triangular markers.  When the\n%                      sample size is small, notches may extend beyond the\n%                      end of the box.\n%      'orientation'   'vertical' (default) to plot X on the y axis, or\n%                      'horizontal' to plot X on the x axis.\n%      'outliersize'   Size of marker used for outliers, in points.\n%                      Default is 6.\n%      'positions'     Box positions specified as a numeric vector with one\n%                      entry per group or X value (default 1:NGROUPS when the\n%                      number of groups is NGROUPS).\n%      'symbol'        Symbol and color to use for outliers, using the same \n%                      values as the LineSpec parameter S in PLOT.  Default\n%                      is 'r+'. If the symbol is omitted then the outliers\n%                      are invisible; if the color is omitted then the\n%                      outliers have the same color as their corresponding\n%                      box.  Any line specification in S is ignored.\n%      'whisker'       Maximum whisker length W.  Default is W=1.5.  Points\n%                      are drawn as outliers if they are larger than\n%                      Q3+W*(Q3-Q1) or smaller than Q1-W*(Q3-Q1), where Q1\n%                      and Q3 are the 25th and 75th percentiles, respectively.\n%                      The default value 1.5 corresponds to approximately +/-\n%                      2.7 sigma and 99.3 coverage if the data are normally\n%                      distributed.  The plotted whisker extends to the\n%                      adjacent value, which is the most extreme data value\n%                      that is not an outlier. Set 'whisker' to 0 to give no\n%                      whiskers and to make every point outside of Q1 and Q3\n%                      an outlier.\n%      'widths'        A scalar or vector of box widths to use when the\n%                      'boxstyle' is 'outline'.  The default is half of the\n%                      minimum separation between boxes, which is .5 when\n%                      the 'positions' argument takes its default value.\n%                      The list of values is replicated or truncated as\n%                      necessary.\n% \n%    When the 'plotstyle' parameter takes the value 'compact', then the\n%    default values for other parameters are the following:\n%        boxstyle - 'filled'            labelverbosity - 'majorminor'\n%        factorgap - 'auto'             medianstyle - 'target'\n%        factorseparator - 'auto'       outliersize - 4\n%        jitter - 0.5                   symbol - 'o'\n%        labelorientation - 'inline'        \n% \n%    You can see the data values and group names by using the data cursor\n%    tool, available from the figure window.  The data cursor shows the\n%    original values of any points affected by the 'datalim' parameter.  You\n%    can label the specific group to which an outlier belongs using the gname\n%    function.\n% \n%    To modify the properties of box components, use findobj using tags to\n%    find their handles as in one of the examples below.  The tag names\n%    depend on the plotstyle and are:\n% \n%       all styles:  'Box', 'Outliers'\n%       traditional: 'Median', 'Upper Whisker', 'Lower Whisker',\n%                    'Upper Adjacent Value', 'Lower Adjacent Value', \n%       compact:     'Whisker', 'MedianOuter', 'MedianInner'\n%       when 'notch' is 'marker':\n%                    'NotchLo', 'NotchHi'\n% \n%    Examples:\n%       % Box plot of car gas mileage grouped by country\n%       load carsmall\n%       boxplot(MPG, Origin)\n%       boxplot(MPG, Origin, 'sym','r*', 'colors',hsv(7))\n%       boxplot(MPG, Origin, 'grouporder', ...\n%                    {'France' 'Germany' 'Italy' 'Japan' 'Sweden' 'USA'})\n% \n%       % Plot by median gas mileage\n%       [sortedMPG,sortedOrder] = sort(grpstats(MPG,Origin,@median));\n%       pos(sortedOrder) = 1:6;\n%       boxplot(MPG, Origin, 'positions', pos)\n% \n%       % Change some graphics properties\n%       boxplot(chi2rnd(1,100,10)); % Generate box plot\n%       h=findobj(gca,'tag','Outliers'); % Get handles for outlier lines.\n%       set(h,'Marker','o'); % Change symbols for all the groups.\n%       set(h(1),'MarkerEdgeColor','b'); % Change color for one group\n% \n%    See also ANOVA1, KRUSKALWALLIS, MULTCOMPARE.\n%\n%    Reference page in Doc Center\n%       doc boxplot\n%\n%    Other functions named boxplot\n%\n%       ts/boxplot\n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/classes/time_series/@ts/boxplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.5785636944047806}}
{"text": "function testspecgram(data)\n\n\n%cd 'C:\\Documents and Settings\\Admin\\Desktop\\';\n%data=wavread('bird109_26519_on_Aug_19_16_33.wav');\n\nparams.tapers = [3 5];\nparams.fpass = [100 20000];\nparams.Fs = 44100;\nparams.pad = 2;\nmax_time =10; % seconds per run\nmax_tapers = 150;\nincrement = 1.5;\nprofile on\n\n\nnsamples = 1000;\nif 1\nslow_results = [];\n    \nwhile 1\n    tic\n    [S,t,f] = mtspecgramc_slow( data(1:nsamples), [0.01 0.001], params );\n    time = toc;\n    result = [nsamples time];\n    fprintf( 'ran %d samples in %d seconds\\n',nsamples, time );\n    slow_results = [slow_results ;result];\n    if time > max_time \n        break\n    end\n    nsamples = round(nsamples * increment);\nend\nslow_results\nfig=figure();\nax=axes('XScale','log','YScale','log');\naxes(ax);\nh=line( 'Xdata',slow_results(:,1),'Ydata',slow_results(:,2),'Marker','*');\nxlabel('number of samples')\nylabel('time');\ntitle('Original mtspecgramc');\ngrid on\ndrawnow;\nsaveas(fig,'datalength_slow.png');\n\nnsamples = 1000;\nfast_results = [];\nwhile 1\n    tic\n    [S,t,f] = mtspecgramc( data(1:nsamples), [0.01 0.001], params );\n    time = toc;\n    result = [nsamples time];\n    fprintf( 'ran %d samples in %d seconds\\n',nsamples, time );\n    fast_results = [fast_results ;result];\n    if time > max_time \n        break\n    end\n    nsamples = round(nsamples * increment);\nend\nfast_results\nfig=figure();\nax=axes('XScale','log','YScale','log');\naxes(ax);\nh=line( 'Xdata',fast_results(:,1),'Ydata',fast_results(:,2),'Marker','*');\nxlabel('number of samples')\nylabel('time');\ntitle('Modified mtspecgramc - preallocate space');\ngrid on\ndrawnow;\nsaveas(fig,'datalength_fast.png');\n\ncompare = [];\nn = 1;\nwhile n <= min(length(slow_results(:,1)),length(fast_results(:,1)))\n    compare_one = [slow_results(n,1) slow_results(n,2)/fast_results(n,2)];\n    compare = [compare ;compare_one];\n    n = n + 1; \nend\ncompare\nfig=figure();\nax=axes('XScale','log','YScale','lin');\naxes(ax);\nh=line( 'Xdata',compare(:,1),'Ydata',compare(:,2),'Marker','*');\ntitle('Preallocation slowdown/speedup of mtspecgramc');\nxlabel('number of samples')\nylabel('speedup');\ngrid on\ndrawnow;\nsaveas(fig,'speedup.png');\n\n\nend;\n\nnsamples=10000;\nresults = [];\nn = 1;\nwhile 1\n    tic\n    params.tapers = [n (2*n-1)];\n    [S,t,f] = mtspecgramc( data(1:nsamples), [0.01 0.001], params );\n    time = toc;\n    result = [params.tapers(2) time];\n    fprintf( 'ran %d samples in %d seconds with tapers %d %d\\n',nsamples, time,params.tapers(1),params.tapers(2) );\n   results = [results ;result];\n    if time > max_time || params.tapers(2) > max_tapers\n        break\n    end\n    n = round(n * increment);\nend\nfig=figure();\nax=axes('XScale','log','YScale','log');\naxes(ax);\nh=line( 'Xdata',results(:,1),'Ydata',results(:,2),'Marker','*');\nxlabel('tapers')\nylabel('time');\n\ndrawnow;\nsaveas(fig,'tapers.png');\n\n\nstats = profile('info')\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/test/testspecgram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.578563690424739}}
{"text": "% test_cgal_fixed_alpha_shape3.m\n\n% Author: Ramon Casero <rcasero@gmail.com>\n% Copyright \u00a9 2013 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% <http://www.gnu.org/licenses/>.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% tetrahedron\n\nxyz = [\n    0 0 0\n    1 0 0\n    0 1 0\n    0 0 1\n    ];\n\n% compute alpha shape\ntri = cgal_fixed_alpha_shape3(xyz, 1);\n\n% plot meshes\nsubplot(1, 1, 1)\nhold off\ntrisurf(tri{1}, xyz(:, 1), xyz(:, 2), xyz(:, 3))\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% pyramid with an indentation in the base\n\nxyz = [\n    0 0 0\n    1 0 0\n    0 1 0\n    .25 .25 0\n    0 0 1\n    ];\n\n% compute alpha shape\ntri = cgal_fixed_alpha_shape3(xyz, [0 0.5625    1.5469]);\n\n% plot meshes\nsubplot(1, 2, 1)\nhold off\ntrisurf(tri{2}, xyz(:, 1), xyz(:, 2), xyz(:, 3))\nview(78, 40)\nsubplot(1, 2, 2)\nhold off\ntrisurf(tri{3}, xyz(:, 1), xyz(:, 2), xyz(:, 3))\nview(78, 40)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% crescent shape\n\nxyz = [\n    1.5 3 0\n    3.5 3 0\n    0 2 0\n    1 2 0\n    4 2 0\n    5 2 0\n    0 1 0\n    1 1 0\n    4 1 0\n    5 1 0\n    1 0 0\n    4 0 0\n    ...\n    1.5 3 1\n    3.5 3 1\n    0 2 1\n    1 2 1\n    4 2 1\n    5 2 1\n    0 1 1\n    1 1 1\n    4 1 1\n    5 1 1\n    1 0 1\n    4 0 1\n    ];\n\n% compute minimal alpha shape that creates one connected object\ntri = cgal_fixed_alpha_shape3(xyz, 2.5157);\ntri = tri{1};\n\n% plot mesh\nsubplot(1, 1, 1)\ntrisurf(tri, xyz(:, 1), xyz(:, 2), xyz(:, 3))\n\n% compute convex hull\ntri = cgal_fixed_alpha_shape3(xyz, Inf);\ntri = tri{1};\n\n% plot mesh\nsubplot(1, 1, 1)\ntrisurf(tri, xyz(:, 1), xyz(:, 2), xyz(:, 3))\n\n% two connected components\ntri = cgal_fixed_alpha_shape3(xyz, 1.2656);\ntri = tri{1};\n\n% plot mesh\nsubplot(1, 1, 1)\ntrisurf(tri, xyz(:, 1), xyz(:, 2), xyz(:, 3))\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_cgal_fixed_alpha_shape3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.766293648423189, "lm_q1q2_score": 0.578486567986789}}
{"text": "function triangle_ncc_rule_test02 ( )\n\n%*****************************************************************************80\n%\n%% TEST02 tests TRIANGLE_NCC_RULE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    29 January 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST02\\n' );\n  fprintf ( 1, '  TRIANGLE_NCC_RULE returns the points and weights\\n' );\n  fprintf ( 1, '  of an NCC rule for the triangle.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  In this test, we simply check that the weights\\n' );\n  fprintf ( 1, '  sum to 1.\\n' );\n\n  rule_num = triangle_ncc_rule_num ( );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of available rules = %d\\n', rule_num );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '      Rule    Sum of weights\\n' );\n  fprintf ( 1, '\\n' );\n\n  for rule = 1 : rule_num\n\n    order_num = triangle_ncc_order_num ( rule );\n\n    [ xy, w ] = triangle_ncc_rule ( rule, order_num );\n\n    w_sum = sum ( w(1:order_num) );\n\n    fprintf ( 1, '  %8d  %14f\\n', rule, w_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/triangle_ncc_rule/triangle_ncc_rule_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5784865597323096}}
{"text": "%% numReplace\n% Below is a demonstration of the features of the |numReplace| function\n\n%%\nclear; close all; clc;\n\n%% REPLACING NUMBERS IN ARRAYS\n%%\n% An example array\nA=[0,-6,3,0,0;-1,-4,-7,-9,-9;-4,-7,11,-5,12;10,-7,5,-7,13;0,11,-2,-6,2;12,4,2,-5,NaN]\n\n%%\n% Defining the input array for entries (NaN's allows) that need to be replaced\na=[2 -5 nan 0]\n%%\n% Defining the numbers (NaN's allows) to take their place\nb=[991 992 993 994]; %Numbers to take their place\n\n%%\n% Replacing the numbers using |numReplace|\nB=numReplace(A,a,b)\n\n%% NOTES ON PERFORMANCE FOR NON-INTEGERS\n% The |numReplace| function employs the |ismember| function. Hence it is\n% suitable for all number cases where ismember is able to detect\n% membership. Numerical precission difficulties may arise for non-integer\n% entires. Consider the below: \n\nlogicMember=ismember(pi,pi+eps(pi))\nlogicMember=ismember(pi,pi+eps(pi)/10)\n\n%%\n%\n% <<gibbVerySmall.gif>>\n%\n% _*GIBBON*_\n% <www.gibboncode.org>\n%\n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_numReplace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.766293648423189, "lm_q1q2_score": 0.5784865595361388}}
{"text": "function stroud_test163 ( )\n\n%*****************************************************************************80\n%\n%% STROUD_TEST163 tests the rules for CN with Gegenbauer weight on monomials.\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  test_num = 5;\n\n  alpha_test = [ -0.5, 0.0, 0.5, 1.0, 1.5 ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'STROUD_TEST163\\n' );\n  fprintf ( 1, '  Demonstrate the use of quadrature rules for the region\\n' );\n  fprintf ( 1, '  CN_GEG, that is, the hypercube [-1,+1]^N, with the\\n' );\n  fprintf ( 1, '  weight W(ALPHA;X) = product ( 1 <= I <= N )\\n' );\n  fprintf ( 1, '    (1-X(I)^2)^ALPHA\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  We use the formulas to integrate various monomials of\\n' );\n  fprintf ( 1, '  the form X(1)^E(1) * X(2)^E(2) * ... X(N)^E(N)\\n' );\n  fprintf ( 1, '  and compare to the exact integral.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The precision of each formula is known, and we only use\\n' );\n  fprintf ( 1, '  a formula if its precision indicates it should be able to\\n' );\n  fprintf ( 1, '  produce an exact result.\\n' );\n\n  for n = 1 : 6\n\n    for test = 1 : test_num\n\n      alpha = alpha_test(test);\n\n      expon(1:n) = 0;\n      cn_geg_test ( n, alpha, expon );\n\n    end\n\n    for test = 1 : test_num\n\n      alpha = alpha_test(test);\n\n      expon(1:n) = 0;\n      expon(n) = 1;\n      cn_geg_test ( n, alpha, expon );\n\n    end\n\n    if ( 2 <= n )\n\n      for test = 1 : test_num\n\n        alpha = alpha_test(test);\n\n        expon(1:n) = 0;\n        expon(1) = 1;\n        expon(2) = 1;\n        cn_geg_test ( n, alpha, expon );\n\n      end\n\n    end\n\n    for test = 1 : test_num\n\n      alpha = alpha_test(test);\n\n      expon(1:n) = 0;\n      expon(1) = 2;\n      cn_geg_test ( n, alpha, expon );\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/stroud/stroud_test163.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.5784865555069842}}
{"text": "function b = onLine(point, line)\n%ONLINE test if a point belongs to a line.\n%\n%   B = onLine(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*2 array of points, B is a N*1 array of booleans.\n%\n%   If LINE is a N*4 arrat of line, B is a 1*N array of booleans.\n%\n%   See also: \n%   lines2d, points2d, onEdge, onRay, angle3Points\n\n% ------\n% Author: David Legland \n% e-mail: david.legland@inrae.fr\n% Created: 2003-10-31\n% Copyright 2003 INRA - TPV URPOI - BIA IMASTE\n\n% deprecation warning\nwarning('geom2d:deprecated', ...\n    '''onLine'' is deprecated, use ''isPointOnLine'' instead');\n\nNl = size(line, 1);\nNp = size(point, 1);\n\nx0 = repmat(line(:,1)', Np, 1);\ny0 = repmat(line(:,2)', Np, 1);\ndx = repmat(line(:,3)', Np, 1);\ndy = repmat(line(:,4)', Np, 1);\nxp = repmat(point(:,1), 1, Nl);\nyp = repmat(point(:,2), 1, Nl);\n\n\n    \n% test if lines are colinear\nb = abs((xp-x0).*dy-(yp-y0).*dx)./sqrt(dx.*dx+dy.*dy) < 1e-14;\n\n\n\n\n\n\n\n\n\n\n\n\n\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/deprecated/geom2d/onLine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5784865516740005}}
{"text": "function y =fbtrim(NoisyData,Param)\n\n%   Author(s): Farhad Bayat, \n%   Email: fbayat@ee.iust.ac.ir\n%   Copyright 2000-2008 \n\n% Note:\n%   In some applications it is necessary to differentiate a signal such as \n%   position to obtain velocity signal. But always derivation makes noise \n%   in output signal and using common filters yeld delay in output signal. \n%   The \"fbtrim.m\" provides a heuristic soulotion for this problem. It\n%   contains several tunning parameters you can adjust to get suitable response.\n%   NoisyData: is the Data to be trim.\n\n%   fbtrim(NoisyData,Param) or  fbtrim(NoisyData)\n%   Param:  contain the trimming preferences described in the folowing:\n%   Param= [NPF,CF,MSV,LCF,Nd]; \n%   Leave param for default values.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%   Filter Parameters:\n% \n% NPF=0.5;        % Noise Power Factor\n% CF=0.6;         % Correction Factor\n% MSV=0.01;       % minnimum data value\n% LCF=5;          % Level Change factor\n% DF=5 ;          % Delay Factor\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n% Filter parameters' default values: \nNPF=0.5;        % Noise Power Factor\nCF=0.6;         % Correction Factor\nMSV=0.01;       % minnimum data value\nLCF=5;          % Level Change factor\nDF=5 ;          % Delay Factor\n\nif nargin==2\n    NPF=Param(1);\n    CF=Param(2);\n    MSV==Param(3);\n    LCF==Param(4);\n    DF==Param(5);\nend\n\nflag=0;\ndv=5*MSV;\n\nTrimed(1)=NoisyData(1);\nDyn_1=0;\n\nfor i=2:length(NoisyData)\n    Dyn=(NoisyData(i)-Trimed(i-1));\n    if abs(Dyn)>DF*abs(Dyn_1)\n       flag=(flag+sign(Dyn))*(1+sign(Dyn*Dyn_1))/2;\n    end\n    if abs(Dyn)>(1+NPF)*abs(Dyn_1)\n        if flag>=LCF || flag<=-LCF\n            flag=0;\n            Trimed(i)=NoisyData(i);\n        elseif abs(Dyn_1)<MSV\n            Trimed(i)=Trimed(i-1)+sign(Dyn)*dv;\n        else\n            Trimed(i)=Trimed(i-1)+CF*sign(Dyn)*abs(Dyn_1);\n        end\n    else\n        Trimed(i)= NoisyData(i);\n    end\n    Dyn_1=(Trimed(i)-Trimed(i-1));\nend\n\ny=Trimed;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/16845-signal-trimmer-smoothing/fbtrim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5784409397551608}}
{"text": "function [ozf] = kN2ozf(kN)\n% Convert force from kilonewtons to ounces-force. \n% Chad A. Greene 2012\nozf = kN*3596.9431019;", "meta": {"author": "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/kN2ozf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.578440923450673}}
{"text": "function gpcf = gpcf_linearLogistic(varargin)\n%GPCF_LINEARLOGISTIC  Create a covariance function corresponding to\n%                     logistic mean function \n%\n%  Description\n%    GPCF = GPCF_LINEARLOGISTIC('PARAM1',VALUE1,'PARAM2,VALUE2,...) creates\n%    a covariance function structure corresponding to logistic mean\n%    function in which the named parameters have the specified values. Any\n%    unspecified parameters are set to default values.\n%\n%    GPCF = GPCF_LINEARLOGISTIC(GPCF,'PARAM1',VALUE1,'PARAM2,VALUE2,...) \n%    modify a covariance function structure with the named\n%    parameters altered with the specified values.\n%\n%    The logistic functional form is given by\n%         h(x) = w* (logitinv(a.*x + b) - 0.5);\n%    By giving a zero mean Gaussian prior for weight, \n%         w ~ N(0, coeffSigma2)\n%    the prior for h(x) is\n%         h(x) ~ N(0, H(x)*H(x)'*coeffSigma2) )\n%    where H(x) = [h(x(1)), ... , h(x(n))]' and, hence,\n%    H(x)*H(x)'*coeffSigma2) is the covariance function related to the \n%    logistic mean function.\n%  \n%    Parameters for linearLogistic (dot product) covariance function\n%      a                 - regression coefficient of linear part [1].\n%                          For identifiability a is restricted to positive\n%                          values by log transformation\n%      b                 - intercept of the linear part [0].\n%                          b can be positive or negative.\n%      a_prior           - prior for a [prior_gaussian('s2',10)]\n%      b_prior           - prior for b [prior_gaussian('s2',10)]\n%      coeffSigma2       - prior variance for regressor coefficients [10]\n%                          This can be either scalar corresponding\n%                          to a common prior variance or vector\n%                          defining own prior variance for each\n%                          coefficient.\n%      coeffSigma2_prior - prior structure for coeffSigma2 [prior_logunif]\n%      selectedVariables - vector defining which inputs are used [all]\n%\n%    Note! If the prior is 'prior_fixed' then the parameter in\n%    question is considered fixed and it is not handled in\n%    optimization, grid integration, MCMC etc.\n%\n%  Example:\n%   a=0.2;\n%   b = -10;\n%   x = linspace(0,100,100)';\n%   y = 3.*(logitinv(a.*x + b) - 0.5) + 0.1*randn(100,1);\n%   cf = gpcf_linearLogistic('a', a, 'b', b, 'selectedVariables', 1)  ;\n%   gp = gp_set('cf', cf);\n%   Ef = gp_pred(gp,x,y,x);\n%   figure,plot(x,y,'.'), hold on, plot(x,Ef,'k')\n%\n%  See also\n%    GP_SET, GPCF_*, PRIOR_*, MEAN_*\n%\n% Copyright (c) 2007-2010 Jarno Vanhatalo\n% Copyright (c) 2008-2010 Jaakko Riihim\u00e4ki\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  ip=inputParser;\n  ip.FunctionName = 'GPCF_LINEARLOGISTIC';\n  ip.addOptional('gpcf', [], @isstruct);\n  ip.addParamValue('coeffSigma2',10, @(x) isvector(x) && all(x>0));\n  ip.addParamValue('a',1, @(x) isvector(x) && all(x>0));\n  ip.addParamValue('b',0, @(x) isvector(x) );\n  ip.addParamValue('coeffSigma2_prior',prior_logunif, @(x) isstruct(x) || isempty(x));\n  ip.addParamValue('a_prior',prior_gaussian('s2',10), @(x) isstruct(x) || isempty(x));\n  ip.addParamValue('b_prior',prior_gaussian('s2',10), @(x) isstruct(x) || isempty(x));\n  ip.addParamValue('selectedVariables',[], @(x) isvector(x) && all(x>0));\n  ip.parse(varargin{:});\n  gpcf=ip.Results.gpcf;\n\n  if isempty(gpcf)\n    init=true;\n    gpcf.type = 'gpcf_linearLogistic';\n  else\n    if ~isfield(gpcf,'type') && ~isequal(gpcf.type,'gpcf_linearLogistic')\n      error('First argument does not seem to be a valid covariance function structure')\n    end\n    init=false;\n  end\n  \n  % Initialize parameter\n  if init || ~ismember('coeffSigma2',ip.UsingDefaults)\n    gpcf.coeffSigma2=ip.Results.coeffSigma2;\n  end\n  if init || ~ismember('a',ip.UsingDefaults)\n    gpcf.a=ip.Results.a;\n  end\n  if init || ~ismember('b',ip.UsingDefaults)\n    gpcf.b=ip.Results.b;\n  end\n\n  % Initialize prior structure\n  if init\n    gpcf.p=[];\n  end\n  if init || ~ismember('coeffSigma2_prior',ip.UsingDefaults)\n    gpcf.p.coeffSigma2=ip.Results.coeffSigma2_prior;\n  end\n  if init || ~ismember('a_prior',ip.UsingDefaults)\n      gpcf.p.a=ip.Results.a_prior;\n  end\n  if init || ~ismember('b_prior',ip.UsingDefaults)\n      gpcf.p.b=ip.Results.b_prior;\n  end\n\n  if ~ismember('selectedVariables',ip.UsingDefaults)\n    selectedVariables=ip.Results.selectedVariables;\n    if ~isempty(selectedVariables)\n      gpcf.selectedVariables = selectedVariables;\n    end\n  end\n  \n  if init\n    % Set the function handles to the subfunctions\n    gpcf.fh.pak = @gpcf_linearLogistic_pak;\n    gpcf.fh.unpak = @gpcf_linearLogistic_unpak;\n    gpcf.fh.lp = @gpcf_linearLogistic_lp;\n    gpcf.fh.lpg = @gpcf_linearLogistic_lpg;\n    gpcf.fh.cfg = @gpcf_linearLogistic_cfg;\n    gpcf.fh.cfdg = @gpcf_linearLogistic_cfdg;\n    gpcf.fh.cfdg2 = @gpcf_linearLogistic_cfdg2;\n    gpcf.fh.ginput = @gpcf_linearLogistic_ginput;\n    gpcf.fh.ginput2 = @gpcf_linearLogistic_ginput2;\n    gpcf.fh.ginput3 = @gpcf_linearLogistic_ginput3;\n    gpcf.fh.ginput4 = @gpcf_linearLogistic_ginput4;\n    gpcf.fh.cov = @gpcf_linearLogistic_cov;\n    gpcf.fh.trcov  = @gpcf_linearLogistic_trcov;\n    gpcf.fh.trvar  = @gpcf_linearLogistic_trvar;\n    gpcf.fh.recappend = @gpcf_linearLogistic_recappend;\n  end        \n\nend\n\nfunction [w, s, h] = gpcf_linearLogistic_pak(gpcf, w)\n%GPCF_GPCF_LINEARLOGISTIC_PAK  Combine GP covariance function parameters into one vector\n%\n%  Description\n%    W = GPCF_GPCF_LINEARLOGISTIC_PAK(GPCF) takes a covariance function\n%    structure GPCF and combines the covariance function\n%    parameters and their hyperparameters into a single row\n%    vector W. This is a mandatory subfunction used for \n%    example in energy and gradient computations.\n%\n%       w = [ log(gpcf.coeffSigma2)\n%             (hyperparameters of gpcf.coeffSigma2)\n%              log(gpcf.a)\n%             (hyperparameters of gpcf.a)\n%              gpcf.b\n%             (hyperparameters of gpcf.b)]'\n%\n%  See also\n%    GPCF_GPCF_LINEARLOGISTIC_UNPAK\n  \n  w = []; s = {}; h =[];\n  if ~isempty(gpcf.p.coeffSigma2)\n    w = log(gpcf.coeffSigma2);\n    if numel(gpcf.coeffSigma2)>1\n      s = [s; sprintf('log(linearLogistic.coeffSigma2 x %d)',numel(gpcf.coeffSigma2))];\n    else\n      s = [s; 'log(linearLogistic.coeffSigma2)'];\n    end\n    h = [h ones(1, numel(gpcf.coeffSigma2))];\n    % Hyperparameters of coeffSigma2\n    [wh, sh, hh] = gpcf.p.coeffSigma2.fh.pak(gpcf.p.coeffSigma2);\n    sh=strcat(repmat('prior-', size(sh,1),1),sh);\n    w = [w wh];\n    s = [s; sh];\n    h = [h 1+hh];\n  end\n  \n  if ~isempty(gpcf.p.a)\n      w = [w log(gpcf.a)];\n      if numel(gpcf.a)>1\n          s = [s; sprintf('log(linearLogistic.a x %d)',numel(gpcf.a))];\n      else\n          s = [s; 'log(linearLogistic.a)'];\n      end\n      h = [h ones(1, numel(gpcf.a))];\n      % Hyperparameters of a\n      [wh, sh, hh] = gpcf.p.a.fh.pak(gpcf.p.a);\n      sh=strcat(repmat('prior-', size(sh,1),1),sh);\n      w = [w wh];\n      s = [s; sh];\n      h = [h 1+hh];\n  end\n  \n  if ~isempty(gpcf.p.b)\n      w = [w gpcf.b];\n      if numel(gpcf.b)>1\n          s = [s; sprintf('linearLogistic.b x %d',numel(gpcf.b))];\n      else\n          s = [s; 'linearLogistic.b'];\n      end\n      h = [h ones(1, numel(gpcf.b))];\n      % Hyperparameters of b\n      [wh, sh, hh] = gpcf.p.b.fh.pak(gpcf.p.b);\n      sh=strcat(repmat('prior-', size(sh,1),1),sh);\n      w = [w wh];\n      s = [s; sh];\n      h = [h 1+hh];\n  end\n\n  \nend\n\nfunction [gpcf, w] = gpcf_linearLogistic_unpak(gpcf, w)\n%GPCF_GPCF_LINEARLOGISTIC_UNPAK  Sets the covariance function parameters \n%                   into the structure\n%\n%  Description\n%    [GPCF, W] = GPCF_GPCF_LINEARLOGISTIC_UNPAK(GPCF, W) takes a covariance\n%    function structure GPCF and a hyper-parameter vector W, and\n%    returns a covariance function structure identical to the\n%    input, except that the covariance hyper-parameters have been\n%    set to the values in W. Deletes the values set to GPCF from\n%    W and returns the modified W. This is a mandatory subfunction \n%    used for example in energy and gradient computations.\n%\n%    Assignment is inverse of  \n%       w = [ log(gpcf.coeffSigma2)\n%             (hyperparameters of gpcf.coeffSigma2)\n%              log(gpcf.a)\n%             (hyperparameters of gpcf.a)\n%              log(gpcf.b)\n%             (hyperparameters of gpcf.b)]'\n%\n%  See also\n%   GPCF_GPCF_LINEARLOGISTIC_PAK\n  \n  gpp=gpcf.p;\n\n  if ~isempty(gpp.coeffSigma2)\n    i2=length(gpcf.coeffSigma2);\n    i1=1;\n    gpcf.coeffSigma2 = exp(w(i1:i2));\n    w = w(i2+1:end);\n    \n    % Hyperparameters of coeffSigma2\n    [p, w] = gpcf.p.coeffSigma2.fh.unpak(gpcf.p.coeffSigma2, w);\n    gpcf.p.coeffSigma2 = p;\n  end\n  \n  if ~isempty(gpp.a)\n      i2=length(gpcf.a);\n      i1=1;\n      gpcf.a = exp(w(i1:i2));\n      w = w(i2+1:end);\n      \n      % Hyperparameters of a\n      [p, w] = gpcf.p.a.fh.unpak(gpcf.p.a, w);\n      gpcf.p.a = p;\n  end\n  if ~isempty(gpp.b)\n      i2=length(gpcf.b);\n      i1=1;\n      gpcf.b = w(i1:i2);\n      w = w(i2+1:end);\n      \n      % Hyperparameters of b\n      [p, w] = gpcf.p.b.fh.unpak(gpcf.p.b, w);\n      gpcf.p.b = p;\n  end\nend\n\nfunction lp = gpcf_linearLogistic_lp(gpcf)\n%GPCF_GPCF_LINEARLOGISTIC_LP  Evaluate the log prior of covariance function\n%                             parameters \n%\n%  Description\n%    LP = GPCF_GPCF_LINEARLOGISTIC_LP(GPCF) takes a covariance function\n%    structure GPCF and returns log(p(th)), where th collects the\n%    parameters. This is a mandatory subfunction used for example \n%    in energy computations.\n%\n%  See also\n%   GPCF_GPCF_LINEARLOGISTIC_PAK, GPCF_GPCF_LINEARLOGISTIC_UNPAK,\n%   GPCF_GPCF_LINEARLOGISTIC_LPG, GP_E \n\n% Evaluate the prior contribution to the error. The parameters that\n% are sampled are from space W = log(w) where w is all the \"real\" samples.\n% On the other hand errors are evaluated in the W-space so we need take\n% into account also the  Jacobian of transformation W -> w = exp(W).\n% See Gelman et al. (2013), Bayesian Data Analysis, third edition, p. 21.\n  lp = 0;\n  gpp=gpcf.p;\n\n  if ~isempty(gpp.coeffSigma2)\n    lp = gpp.coeffSigma2.fh.lp(gpcf.coeffSigma2, gpp.coeffSigma2) + sum(log(gpcf.coeffSigma2));\n  end\n  if ~isempty(gpp.a)\n    lp = lp + gpp.a.fh.lp(gpcf.a, gpp.a) + sum(log(gpcf.a));\n  end\n  if ~isempty(gpp.b)\n    lp = lp + gpp.b.fh.lp(gpcf.b, gpp.b);\n  end\nend\n\nfunction lpg = gpcf_linearLogistic_lpg(gpcf)\n%GPCF_GPCF_LINEARLOGISTIC_LPG  Evaluate gradient of the log prior with respect\n%                 to the parameters.\n%\n%  Description\n%    LPG = GPCF_GPCF_LINEARLOGISTIC_LPG(GPCF) takes a covariance function\n%    structure GPCF and returns LPG = d log (p(th))/dth, where th\n%    is the vector of parameters. This is a mandatory subfunction \n%    used for example in gradient computations.\n%\n%  See also\n%    GPCF_GPCF_LINEARLOGISTIC_PAK, GPCF_GPCF_LINEARLOGISTIC_UNPAK,\n%    GPCF_GPCF_LINEARLOGISTIC_LP, GP_G \n\n  lpg = [];\n  gpp=gpcf.p;\n  \n  if ~isempty(gpcf.p.coeffSigma2)\n      lll=length(gpcf.coeffSigma2);\n      lpgs = gpp.coeffSigma2.fh.lpg(gpcf.coeffSigma2, gpp.coeffSigma2);\n      lpg = [lpg lpgs(1:lll).*gpcf.coeffSigma2+1 lpgs(lll+1:end)];\n  end\n  if ~isempty(gpcf.p.a)\n      lll=length(gpcf.a);\n      lpgs = gpp.a.fh.lpg(gpcf.a, gpp.a);\n      lpg = [lpg lpgs(1:lll).*gpcf.a+1 lpgs(lll+1:end)];\n  end\n  if ~isempty(gpcf.p.b)\n      lll=length(gpcf.b);\n      lpgs = gpp.b.fh.lpg(gpcf.b, gpp.b);\n      lpg = [lpg lpgs(1:lll) lpgs(lll+1:end)];\n  end\n\nend\n\nfunction DKff = gpcf_linearLogistic_cfg(gpcf, x, x2, mask, i1)\n%GPCF_GPCF_LINEARLOGISTIC_CFG  Evaluate gradient of covariance function\n%                 with respect to the parameters\n%\n%  Description\n%    DKff = GPCF_GPCF_LINEARLOGISTIC_CFG(GPCF, X) takes a covariance\n%    function structure GPCF, a matrix X of input vectors and returns \n%    DKff, the gradients of covariance matrix Kff = k(X,X) with\n%    respect to th (cell array with matrix elements). This is a \n%    mandatory subfunction used in gradient computations.\n%\n%    DKff = GPCF_GPCF_LINEARLOGISTIC_CFG(GPCF, X, X2) takes a covariance\n%    function structure GPCF, a matrix X of input vectors and\n%    returns DKff, the gradients of covariance matrix Kff =\n%    k(X,X2) with respect to th (cell array with matrix\n%    elements). This subfunction is needed when using sparse \n%    approximations (e.g. FIC).\n%\n%    DKff = GPCF_GPCF_LINEARLOGISTIC_CFG(GPCF, X, [], MASK) takes a\n%    covariance function structure GPCF, a matrix X of input vectors and\n%    returns DKff, the diagonal of gradients of covariance matrix\n%    Kff = k(X,X2) with respect to th (cell array with matrix\n%    elements). This subfunction is needed when using sparse \n%    approximations (e.g. FIC).\n%\n%    DKff = GPCF_GPCF_LINEARLOGISTIC_CFG(GPCF,X,X2,MASK,i) takes a\n%    covariance function structure GPCF, a matrix X of input vectors and \n%    returns DKff, the gradient of covariance matrix Kff = \n%    k(X,X2), or k(X,X) if X2 is empty, with respect to ith \n%    hyperparameter. This subfunction is needed when using\n%    memory save option in gp_set.\n%\n%  See also\n%   GPCF_GPCF_LINEARLOGISTIC_PAK, GPCF_GPCF_LINEARLOGISTIC_UNPAK,\n%   GPCF_GPCF_LINEARLOGISTIC_LP, GP_G \n\n  [n, m] =size(x);\n\n  DKff = {};\n  \n  if nargin==5\n    % Use memory save option\n    savememory=1;\n    if i1==0\n      % Return number of hyperparameters\n      DKff=0;\n      if ~isempty(gpcf.p.coeffSigma2)\n        DKff=length(gpcf.coeffSigma2);\n      end\n      if ~isempty(gpcf.p.a)\n          DKff=DKff+length(gpcf.a);\n      end\n      if ~isempty(gpcf.p.b)\n          DKff=DKff+length(gpcf.b);\n      end\n      return\n    end\n  else\n    savememory=0;\n  end\n  \n  % Evaluate: DKff{1} = d Kff / d coeffSigma2\n  % NOTE! Here we have already taken into account that the parameters are\n  % transformed through log() and thus dK/dlog(p) = p * dK/dp\n\n  h = logitinv(gpcf.a.*x + gpcf.b) - 0.5;\n  \n  % evaluate the gradient for training covariance\n  if nargin == 2 || (isempty(x2) && isempty(mask))\n    \n    if isfield(gpcf, 'selectedVariables')\n      if ~isempty(gpcf.p.coeffSigma2)\n        if length(gpcf.coeffSigma2) == 1\n          DKff{1}=gpcf.coeffSigma2*h(:,gpcf.selectedVariables)*(h(:,gpcf.selectedVariables)');\n        else\n          if ~savememory\n            i1=1:length(gpcf.coeffSigma2);\n          end\n          for ii1=i1\n            DD = gpcf.coeffSigma2(ii1)*h(:,gpcf.selectedVariables(ii1))*(h(:,gpcf.selectedVariables(ii1))');\n            DD(abs(DD)<=eps) = 0;\n            DKff{ii1}= (DD+DD')./2;\n          end\n        end\n      end\n      if ~isempty(gpcf.p.a)\n          ii1= length(DKff) +1 ;\n          hh = logitinv(gpcf.a.*x(:,gpcf.selectedVariables) + gpcf.b).^2.*...\n              gpcf.a.*x(:,gpcf.selectedVariables).*exp(-gpcf.a.*x(:,gpcf.selectedVariables)-gpcf.b);\n          DKff{ii1} = gpcf.coeffSigma2.* (hh*h(:,gpcf.selectedVariables)' + h(:,gpcf.selectedVariables)*hh');\n      end\n      if ~isempty(gpcf.p.b)\n          ii1= length(DKff) +1 ;\n          hh = logitinv(gpcf.a.*x(:,gpcf.selectedVariables) + gpcf.b).^2.*exp(-gpcf.a.*x(:,gpcf.selectedVariables)-gpcf.b);\n          DKff{ii1} = gpcf.coeffSigma2* (hh*h(:,gpcf.selectedVariables)' + h(:,gpcf.selectedVariables)*hh');\n      end\n    else\n      if ~isempty(gpcf.p.coeffSigma2)\n        if length(gpcf.coeffSigma2) == 1\n          DKff{1}=gpcf.coeffSigma2*h*(h');\n        else\n          if isa(gpcf.coeffSigma2,'single')\n            epsi=eps('single');\n          else\n            epsi=eps;\n          end\n          if ~savememory\n            i1=1:length(gpcf.coeffSigma2);\n          end\n          DKff=cell(1,length(i1));\n          for ii1=i1\n            DD = gpcf.coeffSigma2(ii1)*h(:,ii1)*(h(:,ii1)');\n            DD(abs(DD)<=epsi) = 0;\n            DKff{ii1}= (DD+DD')./2;\n          end\n        end\n      end\n      if ~isempty(gpcf.p.a)\n          ii1= length(DKff) +1 ;\n          hh = logitinv(gpcf.a.*x(:,gpcf.selectedVariables) + gpcf.b).^2.*gpcf.a.*x.*exp(gpcf.a.*x+gpcf.b);\n          DKff{ii1} = gpcf.coeffSigma2* (hh*h' + h*hh');\n      end\n      if ~isempty(gpcf.p.b)\n          ii1= length(DKff) +1 ;\n          hh = logitinv(gpcf.a.*x(:,gpcf.selectedVariables) + gpcf.b).^2.*exp(gpcf.a.*x+gpcf.b);\n          DKff{ii1} = gpcf.coeffSigma2* (hh*h' + h*hh');\n      end\n    end\n    \n    \n    % Evaluate the gradient of non-symmetric covariance (e.g. K_fu)\n  elseif nargin == 3 || isempty(mask)\n    if size(x,2) ~= size(x2,2)\n      error('gpcf_linearLogistic -> _ghyper: The number of columns in x and x2 has to be the same. ')\n    end\n    error('gpcf_linearLogistic -> _ghyper: \"nargin == 3 || isempty(mask)\" not implemented')\n    if isfield(gpcf, 'selectedVariables')\n      if ~isempty(gpcf.p.coeffSigma2)\n        if length(gpcf.coeffSigma2) == 1\n          DKff{1}=gpcf.coeffSigma2*x(:,gpcf.selectedVariables)*(x2(:,gpcf.selectedVariables)');\n        else\n          if ~savememory\n            i1=1:length(gpcf.coeffSigma2);\n          end\n          for ii1=i1\n            DKff{ii1}=gpcf.coeffSigma2(ii1)*x(:,gpcf.selectedVariables(ii1))*(x2(:,gpcf.selectedVariables(ii1))');\n          end\n        end\n      end\n    else\n      if ~isempty(gpcf.p.coeffSigma2)\n        if length(gpcf.coeffSigma2) == 1\n          DKff{1}=gpcf.coeffSigma2*x*(x2');\n        else\n          if ~savememory\n            i1=1:m;\n          end            \n          for ii1=i1\n            DKff{ii1}=gpcf.coeffSigma2(ii1)*x(:,ii1)*(x2(:,ii1)');\n          end\n        end\n      end\n    end\n    % Evaluate: DKff{1}    = d mask(Kff,I) / d coeffSigma2\n    %           DKff{2...} = d mask(Kff,I) / d coeffSigma2\n  elseif nargin == 4 || nargin == 5\n    error('gpcf_linearLogistic -> _ghyper: \"nargin == 4 || nargin == 5\" not implemented')\n    if isfield(gpcf, 'selectedVariables')\n      if ~isempty(gpcf.p.coeffSigma2)\n        if length(gpcf.coeffSigma2) == 1\n          DKff{1}=gpcf.coeffSigma2*sum(x(:,gpcf.selectedVariables).^2,2); % d mask(Kff,I) / d coeffSigma2\n        else\n          if ~savememory\n            i1=1:length(gpcf.coeffSigma2);\n          end\n          for ii1=i1\n            DKff{ii1}=gpcf.coeffSigma2(ii1)*(x(:,gpcf.selectedVariables(ii1)).^2); % d mask(Kff,I) / d coeffSigma2\n          end\n        end\n      end\n    else\n      if ~isempty(gpcf.p.coeffSigma2)\n        if length(gpcf.coeffSigma2) == 1\n          DKff{1}=gpcf.coeffSigma2*sum(x.^2,2); % d mask(Kff,I) / d coeffSigma2\n        else\n          if ~savememory\n            i1=1:m;\n          end\n          for ii1=i1\n            DKff{ii1}=gpcf.coeffSigma2(ii1)*(x(:,ii1).^2); % d mask(Kff,I) / d coeffSigma2\n          end\n        end\n      end\n    end\n  end\n  if savememory\n    DKff=DKff{i1};\n  end\nend\n\nfunction C = gpcf_linearLogistic_cov(gpcf, x1, x2, varargin)\n%GP_GPCF_LINEARLOGISTIC_COV  Evaluate covariance matrix between two input\n%                            vectors \n%\n%  Description         \n%    C = GP_GPCF_LINEARLOGISTIC_COV(GP, TX, X) takes in covariance function of\n%    a Gaussian process GP and two matrixes TX and X that contain\n%    input vectors to GP. Returns covariance matrix C. Every\n%    element ij of C contains covariance between inputs i in TX\n%    and j in X. This is a mandatory subfunction used for example in\n%    prediction and energy computations.\n%\n%  See also\n%    GPCF_GPCF_LINEARLOGISTIC_TRCOV, GPCF_GPCF_LINEARLOGISTIC_TRVAR,\n%    GP_COV, GP_TRCOV \n  \n  if isempty(x2)\n    x2=x1;\n  end\n  [n1,m1]=size(x1);\n  [n2,m2]=size(x2);\n\n  if m1~=m2\n    error('the number of columns of X1 and X2 has to be same')\n  end\n  \n  if isfield(gpcf, 'selectedVariables')\n      h1 = logitinv(gpcf.a.*x1(:,gpcf.selectedVariables) + gpcf.b) - 0.5;\n      h2 = logitinv(gpcf.a.*x2(:,gpcf.selectedVariables) + gpcf.b) - 0.5;        \n      C = h1*diag(gpcf.coeffSigma2)*(h2');\n  else\n      h1 = logitinv(gpcf.a.*x1 + gpcf.b) - 0.5;\n      h2 = logitinv(gpcf.a.*x2 + gpcf.b) - 0.5;\n      C = h1*diag(gpcf.coeffSigma2)*(h2');\n  end\n  C(abs(C)<=eps) = 0;\nend\n\nfunction C = gpcf_linearLogistic_trcov(gpcf, x)\n%GP_GPCF_LINEARLOGISTIC_TRCOV  Evaluate training covariance matrix of\n%                              inputs \n%\n%  Description\n%    C = GP_GPCF_LINEARLOGISTIC_TRCOV(GP, TX) takes in covariance function\n%    of a Gaussian process GP and matrix TX that contains training\n%    input vectors. Returns covariance matrix C. Every element ij\n%    of C contains covariance between inputs i and j in TX. This \n%    is a mandatory subfunction used for example in prediction and \n%    energy computations.\n%\n%  See also\n%    GPCF_GPCF_LINEARLOGISTIC_COV, GPCF_GPCF_LINEARLOGISTIC_TRVAR, GP_COV,\n%    GP_TRCOV \n\n  if isfield(gpcf, 'selectedVariables')\n      h = logitinv(gpcf.a.*x(:,gpcf.selectedVariables) + gpcf.b) - 0.5;\n      C = h*diag(gpcf.coeffSigma2)*(h');\n  else\n      h = logitinv(gpcf.a.*x + gpcf.b) - 0.5;\n      C = h*diag(gpcf.coeffSigma2)*(h');\n  end\n  C(abs(C)<=eps) = 0;\n  C = (C+C')./2;\n\nend\n\n\nfunction C = gpcf_linearLogistic_trvar(gpcf, x)\n%GP_GPCF_LINEARLOGISTIC_TRVAR  Evaluate training variance vector\n%\n%  Description\n%    C = GP_GPCF_LINEARLOGISTIC_TRVAR(GPCF, TX) takes in covariance\n%    function of a Gaussian process GPCF and matrix TX that contains\n%    training inputs. Returns variance vector C. Every element i\n%    of C contains variance of input i in TX. This is a mandatory \n%    subfunction used for example in prediction and energy computations.\n%\n%\n%  See also\n%    GPCF_GPCF_LINEARLOGISTIC_COV, GP_COV, GP_TRCOV\n\n  if length(gpcf.coeffSigma2) == 1\n    if isfield(gpcf, 'selectedVariables')\n        h = logitinv(gpcf.a.*x(:,gpcf.selectedVariables) + gpcf.b) - 0.5;\n      C=gpcf.coeffSigma2.*sum(h.^2,2);\n    else\n        h = logitinv(gpcf.a.*x + gpcf.b) - 0.5;\n      C=gpcf.coeffSigma2.*sum(h.^2,2);\n    end\n  else\n    if isfield(gpcf, 'selectedVariables')\n        h = logitinv(gpcf.a.*x(:,gpcf.selectedVariables) + gpcf.b) - 0.5;\n      C=sum(repmat(gpcf.coeffSigma2, size(x,1), 1).*h.^2,2);\n    else\n        h = logitinv(gpcf.a.*x + gpcf.b) - 0.5;\n      C=sum(repmat(gpcf.coeffSigma2, size(h,1), 1).*h.^2,2);\n    end\n  end\n  C(abs(C)<eps)=0;\n  \nend\n\nfunction reccf = gpcf_linearLogistic_recappend(reccf, ri, gpcf)\n%RECAPPEND Record append\n%\n%  Description\n%    RECCF = GPCF_GPCF_LINEARLOGISTIC_RECAPPEND(RECCF, RI, GPCF) takes a\n%    covariance function record structure RECCF, record index RI\n%    and covariance function structure GPCF with the current MCMC\n%    samples of the parameters. Returns RECCF which contains all\n%    the old samples and the current samples from GPCF. This \n%    subfunction is needed when using MCMC sampling (gp_mc).\n%\n%  See also\n%    GP_MC and GP_MC -> RECAPPEND\n\n  if nargin == 2\n    % Initialize the record\n    reccf.type = 'gpcf_linearLogistic';\n\n    % Initialize parameters\n    reccf.coeffSigma2= [];\n    reccf.a= [];\n    reccf.b= [];\n\n    % Set the function handles\n    reccf.fh.pak = @gpcf_linearLogistic_pak;\n    reccf.fh.unpak = @gpcf_linearLogistic_unpak;\n    reccf.fh.lp = @gpcf_linearLogistic_lp;\n    reccf.fh.lpg = @gpcf_linearLogistic_lpg;\n    reccf.fh.cfg = @gpcf_linearLogistic_cfg;\n    reccf.fh.cfdg = @gpcf_linearLogistic_cfdg;\n    reccf.fh.cfdg2 = @gpcf_linearLogistic_cfdg2;\n    reccf.fh.ginput = @gpcf_linearLogistic_ginput;\n    reccf.fh.ginput2 = @gpcf_linearLogistic_ginput2;\n    reccf.fh.ginput3 = @gpcf_linearLogistic_ginput3;\n    reccf.fh.ginput4 = @gpcf_linearLogistic_ginput4;\n    reccf.fh.cov = @gpcf_linearLogistic_cov;\n    reccf.fh.trcov  = @gpcf_linearLogistic_trcov;\n    reccf.fh.trvar  = @gpcf_linearLogistic_trvar;\n    reccf.fh.recappend = @gpcf_linearLogistic_recappend;\n    reccf.p=[];\n    reccf.p.coeffSigma2=[];\n    if ~isempty(ri.p.coeffSigma2)\n      reccf.p.coeffSigma2 = ri.p.coeffSigma2;\n    end\n    if ~isempty(ri.p.a)\n      reccf.p.a = ri.p.a;\n    end\n    if ~isempty(ri.p.b)\n      reccf.p.b = ri.p.b;\n    end\n\n  else\n    % Append to the record\n    gpp = gpcf.p;\n    \n    % record coeffSigma2\n    reccf.coeffSigma2(ri,:)=gpcf.coeffSigma2;\n    if isfield(gpp,'coeffSigma2') && ~isempty(gpp.coeffSigma2)\n      reccf.p.coeffSigma2 = gpp.coeffSigma2.fh.recappend(reccf.p.coeffSigma2, ri, gpcf.p.coeffSigma2);\n    end\n\n    reccf.a(ri,:)=gpcf.a;\n    if isfield(gpp,'a') && ~isempty(gpp.a)\n      reccf.p.a = gpp.a.fh.recappend(reccf.p.a, ri, gpcf.p.a);\n    end\n\n    reccf.b(ri,:)=gpcf.b;\n    if isfield(gpp,'b') && ~isempty(gpp.b)\n      reccf.p.b = gpp.b.fh.recappend(reccf.p.b, ri, gpcf.p.b);\n    end\n\n    \n    if isfield(gpcf, 'selectedVariables')\n      reccf.selectedVariables = gpcf.selectedVariables;\n    end\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/gp/gpcf_linearLogistic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5784356811586981}}
{"text": "classdef MeshSymmetrizerTest < testShowingError\n\n    properties (Access = protected)\n        tol = 1e-14;\n    end\n\n    properties (Access = private)\n        mesh\n        symmetricMesh\n    end\n\n    properties (Access = private)\n        alpha\n        nx\n        ny\n        x1Max\n        x1Min\n        x2Max\n        x2Min\n    end\n\n    methods (Access = public)\n\n        function obj = MeshSymmetrizerTest()\n            obj.init();\n            obj.createMesh();\n            obj.createSymmetricMesh();\n            obj.plotMeshes();\n        end\n\n    end\n\n    methods (Access = private)\n\n        function init(obj)\n            obj.nx = 20;\n            obj.ny = 30;\n            obj.x1Max = 3;\n            obj.x1Min = 0;\n            obj.x2Max = 2;\n            obj.x2Min = 0;\n            obj.alpha = 0.3;\n        end\n\n        function createMesh(obj)\n            [x1,x2] = obj.createCoord();\n            x3 = zeros(size(x2));\n            [F,V] = mesh2tri(x1,x2,x3,'x');\n            s.coord  = V(:,1:2);\n            s.connec = F;\n            m = Mesh(s);\n            obj.mesh = m;\n        end\n\n        function [x1,x2] = createCoord(obj)\n            [x1,x2] = obj.createHorizontalVerticalCoords();\n            [x1,x2] = obj.rotateCoord(x1,x2);\n        end\n\n        function [x1v,x2v] = createHorizontalVerticalCoords(obj)\n            x1 = linspace(obj.x1Min,obj.x1Max,obj.nx);\n            x2 = linspace(obj.x2Min,obj.x2Max,obj.ny);\n            [x1v,x2v] = meshgrid(x1,x2);\n        end\n\n        function [x1r,x2r] = rotateCoord(obj,x1,x2)\n            ca = cos(obj.alpha);\n            sa = sin(obj.alpha);\n            x1r = ca*x1 - sa*x2;\n            x2r = sa*x1 + ca*x2;\n        end\n\n        function createSymmetricMesh(obj)\n            s.mesh = obj.mesh;\n            s.symmetricLine.vector = [cos(obj.alpha);sin(obj.alpha)];\n            s.symmetricLine.point = [0;0];\n            mS = Symmetrizer(s);\n            m = mS.computeSymmetricMesh();\n            obj.symmetricMesh = m;\n        end\n\n        function plotMeshes(obj)\n            figure()\n            obj.mesh.plot();\n            figure()\n            obj.symmetricMesh.plot();\n        end\n\n    end\n\n    methods (Access = protected)\n\n        function computeError(obj)\n            obj.error = 0;\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/tests/Source/DehomogenizingTests/MeshSymmetrizerTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7341195210831258, "lm_q1q2_score": 0.5784356793034087}}
{"text": "function f = divergence(F)\n%DIVERGENCE   Divergence of a CHEBFUN3V object.\n%   DIVERGENCE(F) returns divergence of the CHEBFUN3V object F as a\n%   CHEBFUN3. If F = U i + V j + W k, then divergence(F) = U_x + V_y + W_z.\n%\n% See also CHEBFUN3V/DIV.\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    f = chebfun3();\n    return\nend\n\n% Two components:\nif ( F.nComponents == 2 )\n    Fc = F.components;\n    f = diff(Fc{1}, 1, 1) + diff(Fc{2}, 1, 2);\n    \n% Three components:\nelseif ( F.nComponents == 3 )\n    Fc = F.components;\n    diff1 = diff(Fc{1}, 1, 1);\n    diff2 = diff(Fc{2}, 1, 2);\n    diff3 = diff(Fc{3}, 1, 3);\n    %Developer Note: Instead of f = diff1 + diff2 + diff3; which calls the\n    % constructor two times, we use the following trick to call it just\n    % once. See CHEBFUN3/PLUS for more details:\n    vscales = [vscale(diff1) + vscale(diff2), vscale(diff3)];\n    \n    m = 51; % size of sampling grid\n    LVals = sample(diff1, m, m, m) + sample(diff2, m, m, m) + ...\n        sample(diff3, m, m, m);\n    LVscale = max(abs(LVals(:)));\n    if sum(vscales) == 0\n        f = chebfun3(0);\n    else\n        kappa = sum(vscales)/LVscale;\n        pref = chebfunpref().cheb3Prefs;\n        eps = pref.chebfun3eps;\n        tol = eps*kappa;\n        f = chebfun3(@(x,y,z) feval(diff1, x, y, z) + feval(diff2, x, y, z) + ...\n           feval(diff3, x, y, z) , Fc{1}.domain, 'eps', tol);\n    end\nelse\n    error('CHEBFUN:CHEBFUN3V:divergence:notSupported', ...\n        'Two or three components are needed.')\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/@chebfun3v/divergence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5784356719918167}}
{"text": "function box = boundingBox(points)\n%BOUNDINGBOX Bounding box of a set of points\n%\n%   BOX = boundingBox(POINTS)\n%   Returns the bounding box of the set of points POINTS. POINTS can be\n%   either a N-by-2 or N-by-3 array. The result BOX is a 1-by-4 or 1-by-6\n%   array, containing:\n%   [XMIN XMAX YMIN YMAX] (2D point sets)\n%   [XMIN XMAX YMIN YMAX ZMIN ZMAX] (3D point sets)\n%\n%   Example\n%   % Draw the bounding box of a set of random points\n%     points = rand(30, 2);\n%     figure; hold on;\n%     drawPoint(points, '.');\n%     box = boundingBox(points);\n%     drawBox(box, 'r');\n%\n%   % Draw bounding box of a cubeoctehedron\n%     [v e f] = createCubeOctahedron;\n%     box3d = boundingBox(v);\n%     figure; hold on;\n%     drawMesh(v, f);\n%     drawBox3d(box3d);\n%     set(gcf, 'renderer', 'opengl')\n%     axis([-2 2 -2 2 -2 2]);\n%     view(3)\n%     \n%   See also\n%   polygonBounds, drawBox\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2011-04-01,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n% HISTORY\n% 2011-04-08 add example\n% 2011-12-09 rename to boundingBox\n\n% compute extreme x and y values\nxmin = min(points(:,1));\nxmax = max(points(:,1));\nymin = min(points(:,2));\nymax = max(points(:,2));\n\nif size(points, 2) > 2\n    % process case of 3D points\n    zmin = min(points(:,3));\n    zmax = max(points(:,3));\n    \n    % format as box 3D data structure\n    box = [xmin xmax ymin ymax zmin zmax];\nelse\n    % format as box data structure\n    box = [xmin xmax ymin ymax];\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/boundingBox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.5784356710641718}}
{"text": "function price = PROJ_GMXB_Surrender(T, M, gmdb_params, modelInputs, N, alph)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Description: Price Gauranteed Minimum death benefits with period fees and early surrender in Levy Models\n%              using the PROJ method\n%\n% Author:      Justin Lars Kirkby\n% References:  (1) Valuation and optimal surrender of variable annuities\n%                   with guaranteed minimum benefits and periodic fees, \n%                   Kirkby and Aguilar 2022, Scandinavian Actuarial Journal\n%\n%              (2) Efficient Option Pricing By Frame Duality with The Fast\n%              Fourier Transform, SIAM J. Financial Math., 2015\n%\n% Models Supported: Levy Processes, including jump diffusions and Black-Scholes model\n% Returns: price of contract\n%\n% ----------------------\n% Contract/Model Params\n% ----------------------\n% T   = time remaining until maturity\n% M   = number of subintervals of [0,T] (total of M+1 monitoring points in time grid, including S_0)\n%\n% modelInputs\n% ------------------------\n% r     = interest rate\n% q     = dividend yield\n% rnCHF = risk netural characteristic function (function handle with single argument)\n%\n% gmdb_params\n% ------------------------\n% F_0       = initial fund value\n% alpha_fee = period fee rate\n% gamma     = surrender penalty rate, 1.0 = 100% fund lost upon surrender, 0.0 = 0% lost, ie no penalty\n% g         = floor on growth\n% c         = cap on growth\n% death_prob_cond = conditional probability of death (mortality) table, based on age\n%                   To construct see function make_mortality_table_pmf, set conditional=1\n%\n% ----------------------\n% Numerical (PROJ) Params \n% ----------------------\n% alph =  grid with is 2*alph\n% N  = number of grid points (power of 2, e.g. 2^12), resolution = 2*alph/(N-1)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndt   = T/M;\n\nr = modelInputs.r;\nq = modelInputs.q;\n\nrnCHF = modelInputs.rnCHF;\nrnCHF = @(u)rnCHF(u).*exp(-1i*(r-q)*u*dt);  % undo the drift\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%\nF_0 = gmdb_params.F_0;\n\ng = gmdb_params.g;\nc = gmdb_params.c;  % Cap on growth \nc_S = c;  % Cap on growth for surrender\ngamma = gmdb_params.gamma;\n\nalpha_fee = gmdb_params.alpha_fee;\ndeath_prob = gmdb_params.death_prob_cond;\n\n%%% NOTE: assume constant fee and r,q\nlambda_m = log(1-alpha_fee) + (r-q)*dt;\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nK = N/2;\ndx = 2*alph/(N-1); a = 1/dx;\n\nnnot = K/2;  % TODO: make sure 0 is on grid\n\n%%%% Populate Beta coefficients for orthogonal projection\nxmin = (1-K/2)*dx;\n\na2    = a^2;  \nCons2 = 24*a2*exp(-r*dt)/N;\nzmin  = (1 - K)*dx;  %Kbar corresponds to zero\n\ndw    = 2*pi*a/N;\ngrand = (dw: dw: (N-1)*dw);\ngrand = exp(-1i*zmin*grand).*rnCHF(grand).*(sin(grand/(2*a))./grand).^2./(2+cos(grand/a));\nbeta  = Cons2*real(fft([1/(24*a2) grand]));   %%%%  NOTE: all toep matrices incorporate exp(-r*dt)\n\ntoepM = [beta(K:-1:1)'; 0 ; beta(2*K-1:-1:K +1)'];\ntoepM = fft(toepM);\n\n%%%% Initial terminal payoff coefficients (recursion proceeds backwards in time)\ngrid = xmin + dx*(0:K-1);\nexpGrid = exp(grid);\n\n% Initialize Value function at maturity\nVals = F_0 * max(exp(g*T), min(exp(c*T), expGrid));\n\nThet = zeros(K,1);\n\ncusum_right = cumsum(beta(2*K:-1:K +1))';\ncusum_left = [ fliplr(cumsum(beta(1:1:K-1)))';0];\n\nfor m=M-1:-1:0\n\n    % Define the value function at next time\n    Vfunc = @(x)spline(grid, Vals, x);\n    \n    % Define maturity/death benefit function\n    Mfunc = @(x) F_0 * max(exp(g*(m+1)*dt), min(exp(c*(m+1)*dt), exp(x)));\n    \n    % Combine the two functions, weight by death prob, and shift by lambda\n    pw = death_prob(m+1);\n    H = @(x) pw*Mfunc(lambda_m + x) + (1-pw)*Vfunc(lambda_m + x);\n    \n    Vals = H(grid);\n    \n    Thet(2:K -1) = (Vals(1:K-2)+10*Vals(2:K-1)+Vals(3:K))/12;\n    Thet(1)      = (13*Vals(1)+15*Vals(2)-5*Vals(3)+Vals(4))/48;\n    Thet(K)      = 2*(13*Vals(K)+15*Vals(K-1)-5*Vals(K-2)+Vals(K-3))/48;\n   \n    p = ifft(toepM.*fft([Thet(1:K);zeros(K,1)]));\n\n    % update values with augmentation on the boundaries\n    Vals(1:K) = p(1:K) + cusum_left*Vals(1) + cusum_right*Vals(end); \n\n    if m > 0 && gamma < 1  %%% Cant surrender in first period\n        surrender = (1-gamma)*F_0*min(exp(c_S*m*dt), expGrid);\n        Vals = max(Vals, surrender);\n    end\nend\n\nprice = Vals(nnot);\n\nend\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/PROJ/LEVY/GMXB_Surrender/PROJ_GMXB_Surrender.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5784355414719439}}
{"text": "function f = isint(m)\n\n% function f = isint(m)\n%\n% <m> is a matrix\n%\n% return a logical matrix the same size as <m>.\n% an element is 1 iff it is a float and finite and exactly equal to an integer.\n% specifically:\n%   f = isfloat(m) & isfinite(m) & m==round(m);\n%\n% example:\n% isequal(isint([1 1.5 NaN Inf]),[1 0 0 0])\n\n% do it\nf = isfloat(m) & isfinite(m) & m==round(m);\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/isint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.5783580250166362}}
{"text": "function geometry_test0386 ( )\n\n%*****************************************************************************80\n%\n%% TEST0386 tests LINES_EXP_EQUAL_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  test_num = 6;\n\n  p1_test = [ ...\n    0.0, 0.0; ...\n    0.0, 0.0; ...\n    0.0, 0.0; ...\n    0.0, 0.0; ...\n    0.0, 0.0; ...\n    0.0, 0.0 ]';\n  p2_test = [ ...\n    1.0, 2.0; ...\n    1.0, 2.0; ...\n    1.0, 2.0; ...\n    1.0, 2.0; ...\n    1.0, 2.0; ...\n    1.0, 2.0 ]';\n  q1_test = [ ...\n    0.0,  0.0; ...\n    1.0,  2.0; ...\n    0.0,  0.0; ...\n    7.0, 14.0; ...\n    1.0,  2.0; ...\n    0.0, 10.0 ]';\n  q2_test = [ ...\n    1.0,  2.0; ...\n    0.0,  0.0; ...\n    2.0,  4.0; ...\n    5.5, 11.0; ...\n    3.0,  5.0; ...\n    1.0, 12.0 ]';\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST0386\\n' );\n  fprintf ( 1, '  LINES_EXP_EQUAL_2D tries to determine if two\\n' );\n  fprintf ( 1, '    explicit lines in 2D are equal.\\n' );\n  fprintf ( 1, '\\n' );\n\n  for test = 1 : test_num\n\n    p1(1:dim_num) = p1_test(1:dim_num,test)';\n    p2(1:dim_num) = p2_test(1:dim_num,test)';\n    q1(1:dim_num) = q1_test(1:dim_num,test)';\n    q2(1:dim_num) = q2_test(1:dim_num,test)';\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  P1  %8f  %8f\\n', p1(1:dim_num) );\n    fprintf ( 1, '  P2  %8f  %8f\\n', p2(1:dim_num) );\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Q1  %8f  %8f\\n', q1(1:dim_num) );\n    fprintf ( 1, '  Q2  %8f  %8f\\n', q2(1:dim_num) );\n \n    equal = lines_exp_equal_2d ( p1, p2, q1, q2 );\n \n    if ( equal )\n      fprintf ( 1, '  The lines are equal.\\n' );\n    else\n      fprintf ( 1, '  The lines are distinct.\\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/geometry/geometry_test0386.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.5783580085073534}}
{"text": "function [x cost info] = conjugategradient(problem, x, options)\n% Conjugate gradient minimization algorithm for Manopt.\n%\n% function [x cost info] = conjugategradient(problem)\n% function [x cost info] = conjugategradient(problem, x0)\n% function [x cost info] = conjugategradient(problem, x0, options)\n% function [x cost info] = conjugategradient(problem, [], options)\n%\n% Apply the conjugate gradient minimization algorithm to the problem\n% defined in the problem structure, starting at x0 if it is provided\n% (otherwise, at a random point on the manifold). To specify options whilst\n% not specifying an initial guess, give x0 as [] (the empty matrix).\n%\n% In most of the examples bundled with the toolbox (see link below), the\n% solver can be replaced by the present one if need be.\n%\n% The outputs x and cost are the best reached point on the manifold and its\n% cost. The struct-array info contains information about the iterations:\n%   iter : the iteration number (0 for the initial guess)\n%   cost : cost value\n%   time : elapsed time in seconds\n%   gradnorm : Riemannian norm of the gradient\n%   stepsize : norm of the last tangent vector retracted\n%   beta : value of the beta parameter (see options.beta_type)\n%   linesearch : information logged by options.linesearch\n%   And possibly additional information logged by options.statsfun.\n% For example, type [info.gradnorm] to obtain a vector of the successive\n% gradient norms reached.\n%\n% The options structure is used to overwrite the default values. All\n% options have a default value and are hence optional. To force an option\n% value, pass an options structure with a field options.optionname, where\n% optionname is one of the following and the default value is indicated\n% between parentheses:\n%\n%   tolgradnorm (1e-6)\n%       The algorithm terminates if the norm of the gradient drops below this.\n%   maxiter (1000)\n%       The algorithm terminates if maxiter iterations have been executed.\n%   maxtime (Inf)\n%       The algorithm terminates if maxtime seconds elapsed.\n%   minstepsize (1e-10)\n%       The algorithm terminates if the linesearch returns a displacement\n%       vector (to be retracted) smaller in norm than this value.\n%   beta_type ('H-S')\n%       Conjugate gradient beta rule used to construct the new search\n%       direction, based on a linear combination of the previous search\n%       direction and the new (preconditioned) gradient. Possible values\n%       for this parameter are:\n%           'S-D', 'steep' for beta = 0 (preconditioned steepest descent)\n%           'F-R' for Fletcher-Reeves's rule\n%           'P-R' for Polak-Ribiere's modified rule\n%           'H-S' for Hestenes-Stiefel's modified rule\n%           'H-Z' for Hager-Zhang's modified rule\n%       See Hager and Zhang 2006, \"A survey of nonlinear conjugate gradient\n%       methods\" for a description of these rules in the Euclidean case and\n%       for an explanation of how to adapt them to the preconditioned case.\n%       The adaption to the Riemannian case is straightforward: see in code\n%       for details. Modified rules take the max between 0 and the computed\n%       beta value, which provides automatic restart, except for H-Z which\n%       uses a different modification.\n%   orth_value (Inf)\n%       Following Powell's restart strategy (Math. prog. 1977), restart CG\n%       (that is, make a -preconditioned- gradient step) if two successive\n%       -preconditioned- gradients are \"too\" parallel. See for example\n%       Hager and Zhang 2006, \"A survey of nonlinear conjugate gradient\n%       methods\", page 12. An infinite value disables this strategy. See in\n%       code formula for the specific criterion used.\n%   linesearch (@linesearch_adaptive)\n%       Function handle to a line search function. The options structure is\n%       passed to the line search too, so you can pass it parameters. See\n%       each line search's documentation for info. Another available line\n%       search in manopt is @linesearch, in /manopt/linesearch/linesearch.m\n%   statsfun (none)\n%       Function handle to a function that will be called after each\n%       iteration to provide the opportunity to log additional statistics.\n%       They will be returned in the info struct. See the generic Manopt\n%       documentation about solvers for further information.\n%   stopfun (none)\n%       Function handle to a function that will be called at each iteration\n%       to provide the opportunity to specify additional stopping criteria.\n%       See the generic Manopt documentation about solvers for further\n%       information.\n%   verbosity (3)\n%       Integer number used to tune the amount of output the algorithm\n%       generates during execution (mostly as text in the command window).\n%       The higher, the more output. 0 means silent.\n%   storedepth (2)\n%       Maximum number of different points x of the manifold for which a\n%       store structure will be kept in memory in the storedb. If the\n%       caching features of Manopt are not used, this is irrelevant. For\n%       the CG algorithm, a store depth of 2 should always be sufficient.\n%\n%\n% See also: steepestdescent trustregions manopt/solvers/linesearch manopt/examples\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Bamdev Mishra, Dec. 30, 2012.\n% Contributors: Nicolas Boumal\n% Change log: \n%\n%   March 14, 2013, NB:\n%       Added preconditioner support : see Section 8 in\n%       https://www.math.lsu.edu/~hozhang/papers/cgsurvey.pdf\n%    \n%   Sept. 13, 2013, NB:\n%       Now logging beta parameter too.\n%    \n%\tNov. 7, 2013, NB:\n%       The search direction is not normalized before it is passed to the\n%       linesearch anymore. This way, it is up to the designers of the\n%       linesearch to decide whether they want to use the norm of the\n%       search direction in their algorithm or not. There are reasons\n%       against it, but practical evidence that it may help too, so we\n%       allow it. The default linesearch_adaptive used does exploit the\n%       norm information. The base linesearch does not. You may select it\n%       by setting options.linesearch = @linesearch;\n%\n%\tNov. 29, 2013, NB:\n%       Documentation improved: options are now explicitly described.\n%       Removed the Daniel rule for beta: it was not appropriate for\n%       preconditioned CG and I could not find a proper reference for it.\n\n\n% Verify that the problem description is sufficient for the solver.\nif ~canGetCost(problem)\n    warning('manopt:getCost', ...\n        'No cost provided. The algorithm will likely abort.');\nend\nif ~canGetGradient(problem)\n    warning('manopt:getGradient', ...\n        'No gradient provided. The algorithm will likely abort.');\nend\n\n% Set local defaults here\nlocaldefaults.minstepsize = 1e-10;\nlocaldefaults.maxiter = 1000;\nlocaldefaults.tolgradnorm = 1e-6;\nlocaldefaults.linesearch = @linesearch_adaptive;\nlocaldefaults.storedepth = 2;\n% Changed by NB : H-S has the \"auto restart\" property.\n% See Hager-Zhang 2005/2006 survey about CG methods.\n% Well, the auto restart comes from the 'max(0, ...)', not so much from the\n% reason stated in Hager-Zhang I believe. P-R also has auto restart.\nlocaldefaults.beta_type = 'H-S';\nlocaldefaults.orth_value = Inf; % by BM as suggested in Nocedal and Wright\n\n% Merge global and local defaults, then merge w/ user options, if any.\nlocaldefaults = mergeOptions(getGlobalDefaults(), localdefaults);\nif ~exist('options', 'var') || isempty(options)\n    options = struct();\nend\noptions = mergeOptions(localdefaults, options);\n\n% for convenience\ninner = problem.M.inner;\nlincomb = problem.M.lincomb;\n\n% Create a store database\nstoredb = struct();\n\ntimetic = tic();\n\n% If no initial point x is given by the user, generate one at random.\nif ~exist('x', 'var') || isempty(x)\n    x = problem.M.rand();\nend\n\n% Compute objective-related quantities for x\n[cost grad storedb] = getCostGrad(problem, x, storedb);\ngradnorm = problem.M.norm(x, grad);\n[Pgrad storedb] = getPrecon(problem, x, grad, storedb);\ngradPgrad = inner(x, grad, Pgrad);\n\n% Iteration counter (at any point, iter is the number of fully executed\n% iterations so far)\niter = 0;\n\n% Save stats in a struct array info and preallocate,\n% see http://people.csail.mit.edu/jskelly/blog/?x=entry:entry091030-033941\nstats = savestats();\ninfo(1) = stats;\ninfo(min(10000, options.maxiter+1)).iter = [];\n\n% Initial linesearch memory\nlsmem = [];\n\n\nif options.verbosity >= 2\n    fprintf(' iter\\t    cost val\\t grad. norm\\n');\nend\n\n% Compute a first descent direction (not normalized)\ndesc_dir = lincomb(x, -1, Pgrad);\n\n\n% Start iterating until stopping criterion triggers\nwhile true\n    \n    % Display iteration information\n    if options.verbosity >= 2\n        fprintf('%5d\\t%+.4e\\t%.4e\\n', iter, cost, gradnorm);\n    end\n    \n    % Start timing this iteration\n    timetic = tic();\n    \n    % Run standard stopping criterion checks\n    [stop reason] = stoppingcriterion(problem, x, options, info, iter+1);\n    \n    % Run specific stopping criterion check\n    if ~stop && abs(stats.stepsize) < options.minstepsize\n        stop = true;\n        reason = 'Last stepsize smaller than minimum allowed.';\n    end\n    \n    if stop\n        if options.verbosity >= 1\n            fprintf([reason '\\n']);\n        end\n        break;\n    end\n    \n    \n    % The line search algorithms require the directional derivative of the\n    % cost at the current point x along the search direction.\n    df0 = inner(x, grad, desc_dir);\n        \n    % If we didn't get a descent direction: restart, i.e., switch to the\n    % negative gradient. Equivalent to resetting the CG direction to a\n    % steepest descent step, which discards the past information.\n    if df0 >= 0\n        \n        % Or we switch to the negative gradient direction.\n        if options.verbosity >= 3\n            fprintf(['Conjugate gradient info: got an ascent direction '...\n                     '(df0 = %2e), reset to the (preconditioned) '...\n                     'steepest descent direction.\\n'], df0);\n        end\n        % Reset to negative gradient: this discards the CG memory.\n        desc_dir = lincomb(x, -1, Pgrad);\n        df0 = -gradPgrad;\n        \n    end\n    \n    \n    % Execute line search\n    [stepsize newx storedb lsmem lsstats] = options.linesearch(...\n                 problem, x, desc_dir, cost, df0, options, storedb, lsmem);\n\n    \n    % Compute the new cost-related quantities for x\n    [newcost newgrad storedb] = getCostGrad(problem, newx, storedb);\n    newgradnorm = problem.M.norm(newx, newgrad);\n    [Pnewgrad storedb] = getPrecon(problem, x, newgrad, storedb);\n    newgradPnewgrad = inner(newx, newgrad, Pnewgrad);\n    \n    \n    % Apply the CG scheme to compute the next search direction.\n    %\n    % This paper https://www.math.lsu.edu/~hozhang/papers/cgsurvey.pdf\n\t% by Hager and Zhang lists many known beta rules. The rules defined\n    % here can be found in that paper (or are provided with additional\n    % references), adapted to the Riemannian setting.\n\t% \n    if strcmpi(options.beta_type, 'steep') || ...\n       strcmpi(options.beta_type, 'S-D')              % Gradient Descent\n        \n        beta = 0;\n        desc_dir = lincomb(x, -1, Pnewgrad);\n        \n    else\n        \n        oldgrad = problem.M.transp(x, newx, grad);\n        orth_grads = inner(newx, oldgrad, Pnewgrad)/newgradPnewgrad;\n        \n        % Powell's restart strategy (see page 12 of Hager and Zhang's\n        % survey on conjugate gradient methods, for example)\n        if abs(orth_grads) >= options.orth_value,\n            beta = 0;\n            desc_dir = lincomb(x, -1, Pnewgrad);\n            \n        else % Compute the CG modification\n            \n            desc_dir = problem.M.transp(x, newx, desc_dir);\n            \n            if strcmp(options.beta_type, 'F-R')  % Fletcher-Reeves\n                beta = newgradPnewgrad / gradPgrad;\n                \n            elseif strcmp(options.beta_type, 'P-R')  % Polak-Ribiere+\n                % vector grad(new) - transported grad(current)\n                diff = lincomb(newx, 1, newgrad, -1, oldgrad);\n                ip_diff = inner(newx, Pnewgrad, diff);\n                beta = ip_diff/gradPgrad;\n                beta = max(0, beta);\n                \n            elseif strcmp(options.beta_type, 'H-S')  % Hestenes-Stiefel+\n                diff = lincomb(newx, 1, newgrad, -1, oldgrad);\n                ip_diff = inner(newx, Pnewgrad, diff);\n                beta = ip_diff / inner(newx, diff, desc_dir);\n                beta = max(0, beta);\n\n            elseif strcmp(options.beta_type, 'H-Z') % Hager-Zhang+\n                diff = lincomb(newx, 1, newgrad, -1, oldgrad);\n                Poldgrad = problem.M.transp(x, newx, Pgrad);\n                Pdiff = lincomb(newx, 1, Pnewgrad, -1, Poldgrad);\n                deno = inner(newx, diff, desc_dir);\n                numo = inner(newx, diff, Pnewgrad);\n                numo = numo - 2*inner(newx, diff, Pdiff)*...\n                                       inner(newx, desc_dir, newgrad)/deno;\n                beta = numo/deno;\n                \n                % Robustness (see Hager-Zhang paper mentioned above)\n                desc_dir_norm = problem.M.norm(newx, desc_dir);\n                eta_HZ = -1/(desc_dir_norm * min(0.01, gradnorm));\n                beta = max(beta,  eta_HZ);\n\n            else\n                error(['Unknown options.beta_type. ' ...\n                       'Should be steep, S-D, F-R, P-R, H-S or H-Z.']);\n            end\n            desc_dir = lincomb(newx, -1, Pnewgrad, beta, desc_dir);\n        end\n        \n    end\n    \n    % Make sure we don't use too much memory for the store database.\n    storedb = purgeStoredb(storedb, options.storedepth);\n    \n    % Update iterate info\n    x = newx;\n    cost = newcost;\n    grad = newgrad;\n    Pgrad = Pnewgrad;\n    gradnorm = newgradnorm;\n    gradPgrad = newgradPnewgrad;\n    \n    % iter is the number of iterations we have accomplished.\n    iter = iter + 1;\n    \n    % Log statistics for freshly executed iteration\n    stats = savestats();\n    info(iter+1) = stats; %#ok<AGROW>\n    \nend\n\n\ninfo = info(1:iter+1);\n\nif options.verbosity >= 1\n    fprintf('Total time is %f [s] (excludes statsfun)\\n', info(end).time);\nend\n\n\n% Routine in charge of collecting the current iteration stats\n    function stats = savestats()\n        stats.iter = iter;\n        stats.cost = cost;\n        stats.gradnorm = gradnorm;\n        if iter == 0\n            stats.stepsize = nan;\n            stats.time = toc(timetic);\n            stats.linesearch = [];\n            stats.beta = 0;\n        else\n            stats.stepsize = stepsize;\n            stats.time = info(iter).time + toc(timetic);\n            stats.linesearch = lsstats;\n            stats.beta = beta;\n        end\n        stats = applyStatsfun(problem, x, storedb, options, stats);\n    end\n\nend\n\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/lib/Riemannian_DL_SC_SPD/manopt/manopt/solvers/conjugategradient/conjugategradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5783580085073534}}
{"text": "function bnet  = mk_incinerator_bnet(ns)\n% MK_INCINERATOR_BNET The waste incinerator emissions example from Cowell et al p145\n% function bnet  = mk_incinerator_bnet(ns)\n% \n% If ns is omitted, we use the scalars and binary nodes and the original params.\n% Otherwise, we use random params of the desired size.\n%\n% Lauritzen, \"Propogation of Probabilities, Means and Variances in Mixed Graphical Association Models\", \n% JASA 87(420): 1098--1108\n% This example is reprinted on p145 of \"Probabilistic Networks and Expert Systems\",\n% Cowell, Dawid, Lauritzen and Spiegelhalter, 1999, Springer. \n% For a picture, see http://www.cs.berkeley.edu/~murphyk/Bayes/usage.html#cg_model\n\n% node numbers\nF = 1; W = 2; E = 3; B = 4; C = 5; D = 6; Min = 7; Mout = 8; L = 9;\nnames = {'F', 'W', 'E', 'B', 'C', 'D', 'Min', 'Mout', 'L'};\nn = 9;\ndnodes = [F W B];\ncnodes = mysetdiff(1:n, dnodes);\n\n% node sizes - all cts nodes are scalar, all discrete nodes are binary\nif nargin < 1\n  ns = ones(1, n);\n  ns(dnodes) = 2;\n  rnd = 0;\nelse\n  rnd = 1;\nend\n  \n% topology (p 1099, fig 1)\ndag = zeros(n);\ndag(F,E)=1;\ndag(W,[E Min D]) = 1;\ndag(E,D)=1;\ndag(B,[C D])=1;\ndag(D,[L Mout])=1;\ndag(Min,Mout)=1;\n\n% params (p 1102)\nbnet = mk_bnet(dag, ns, 'discrete', dnodes, 'names', names);\n\nif rnd\n  for i=dnodes(:)'\n    bnet.CPD{i} = tabular_CPD(bnet, i);\n  end\n  for i=cnodes(:)'\n    bnet.CPD{i} = gaussian_CPD(bnet, i);\n  end\nelse\n  bnet.CPD{B} = tabular_CPD(bnet, B, 'CPT', [0.85 0.15]); % 1=stable, 2=unstable\n  bnet.CPD{F} = tabular_CPD(bnet, F, 'CPT', [0.95 0.05]); % 1=intact, 2=defect\n  bnet.CPD{W} = tabular_CPD(bnet, W, 'CPT', [2/7 5/7]); % 1=industrial, 2=household\n  bnet.CPD{E} = gaussian_CPD(bnet, E, 'mean', [-3.9 -0.4 -3.2 -0.5], ...\n\t\t\t     'cov', [0.00002 0.0001 0.00002 0.0001]);\n  bnet.CPD{D} = gaussian_CPD(bnet, D, 'mean', [6.5 6.0 7.5 7.0], ...\n\t\t\t     'cov', [0.03 0.04 0.1 0.1], 'weights', [1 1 1 1]);\n  bnet.CPD{C} = gaussian_CPD(bnet, C, 'mean', [-2 -1], 'cov', [0.1 0.3]);\n  bnet.CPD{L} = gaussian_CPD(bnet, L, 'mean', 3, 'cov', 0.25, 'weights', -0.5);\n  bnet.CPD{Min} = gaussian_CPD(bnet, Min, 'mean', [0.5 -0.5], 'cov', [0.01 0.005]);\n  bnet.CPD{Mout} = gaussian_CPD(bnet, Mout, 'mean', 0, 'cov', 0.002, 'weights', [1 1]);\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/bnt/BNT/examples/static/Models/mk_incinerator_bnet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5783580042329399}}
{"text": "function degree = grNodeInnerDegree(node, edges)\n%GRNODEINNERDEGREE Inner degree of a node in a graph\n%\n%   DEG = grNodeInnerDegree(NODE, EDGES);\n%   Returns the inner degree of a node in the given edge list, i.e. the\n%   number of edges arriving to it.\n%   NODE is the index of the node, and EDGES is a liste of couples of\n%   indices (origin and destination node).   \n% \n%   Note: Also works when node is a vector of indices\n%\n%   See Also:\n%   grNodeDegree, grNodeOuterDegree\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2006-01-17\n% Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n%\n\n%   HISTORY\n%   2008-08-07 pre-allocate memory, update doc\n\n% allocate memory\nN = size(node, 1);\ndegree = zeros(N, 1);\n\n% compute inner degree of each vertex\nfor i=1:length(node)\n    degree(i) = sum(edges(:,2)==node(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/graphs/grNodeInnerDegree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.5783579959782983}}
{"text": "function [c, s] = onnls(y, g, lam, shift, win, tol, maxIter, mask, smin)\n%% Infer the most likely discretized spike train underlying an AR(2) fluorescence trace\n% Solves the sparse non-negative deconvolution problem\n%  min 1/2|Ks-y|^2 + lam * |s|_1 subject to s_t = c_t-g c_{t-1} >= 0\n\n%% inputs:\n%   y:  T*1 vector, vth dimensional array containing the fluorescence intensities \n        %withone entry per time-bin.\n%   g:  vector, shape (p,)\n%       if p in (1,2): AR coefficients for AR(p) process \n%       else: kernel that models the fluorescence implulse response \n%   lam:  scalar, sparsity penalty parameter lambda. \n%   shift: integer scalar, number of frames by which to shift window from on run of\n%       NNLS to the next, default-100\n%   win: integer acalar, window size \n%   tol: scalar, tolerance parameters \n%   maxIter: scalar, maximum number of iterations before termination \n%   mask: T * 1 boolean vector, restrict potential spike times \n%   smin: scalar, minimum spike size \n%% outputs\n%   c: T*1 vector, the inferred denoised fluorescence signal at each time-bin.\n%   s: T*1 vector, discetized deconvolved neural activity (spikes) \n\n%% Authors: Pengcheng Zhou, Carnegie Mellon University, 2016\n% ported from the Python implementation from Johannes Friedrich\n\n%% References \n% Friedrich J et.al., NIPS 2016, Fast Active Set Method for Online Spike Inference from Calcium Imaging\n\n%% input arguments  \nT = length(y); \ny = reshape(y, [], 1); \n\nif ~exist('lam', 'var') || isempty(lam)\n    lam = 0; \nend\nif ~exist('shift', 'var') || isempty(shift)\n    shift = 100; \nend\nif ~exist('win', 'var') || isempty(win)\n    win = 200; \nend\n\nif ~exist('tol', 'var') || isempty(tol)\n    tol = 1e-9; \nend\nif ~exist('maxIter', 'var') || isempty(maxIter)\n    maxIter = []; \nend\nif ~exist('mask', 'var') || isempty(mask)\n    mask = true(T,1); \nend\nif ~exist('smin', 'var') || isempty(smin)\n    smin = 0; \nend\n%% get the response kernel\nw = win; \nK = zeros(w); \n[u, t] = meshgrid(1:w, 1:w);  \nind = 1+t-u;\nif length(g)==1\n    h = exp(log(g)*(0:(w-1)));\nelseif length(g)==2\n    temp = roots([1, -g(1), -g(2)]);\n    d = max(temp);\n    r = min(temp);\n    h = (exp(log(d)*(1:w)) - exp(log(r)*(1:w))) / (d-r); % convolution kernel\nelse\n    h = g;\nend\nK(ind>0) = h(ind(ind>0));   % convolution matrix\nKK = K'*K;\n\n%% initialization \na = sum(inv(K));\nyp = y - lam * a(1);\nyp((end-w+1):end) = yp((end-w+1):end) - lam * a';\ns = zeros(T, 1); \nc = zeros(T, 1); \n\n%% run online deconvolution \nt = 1; \nyp0 = yp; \nwhile t <= T-w+1\n    ind = t:(t+w-1); \n    s(ind) = nnls(KK, K'*yp(ind), s(ind), tol, maxIter, mask(ind)); \n    yp(ind) = yp(ind) - K(:, 1:shift)*s(t:(t+shift-1)); \n    c(ind) = c(ind) + K(:, 1:shift)*s(t:(t+shift-1)); \n    t = t + shift; \nend \ns(t:T) = nnls(KK((t+w-T):w, (t+w-T):w), K(1:(T-t+1), 1:(T-t+1))'*yp(t:T), ...\n    s(t:T), tol, maxIter, mask(t:T)); \nc(t:T) = c(t:T) + K((t+w-T):w, (t+w-T):w) * s(t:T); \n\n%% running thresholded version \nif smin>0\n    yp = yp0; \n    c = zeros(size(c)); \n    mask = (s>smin/100); \n    t = 1;\n    while t <= T-w+1\n        ind = t:(t+w-1);\n        s(ind) = nnls(KK, K'*yp(ind), s(ind), tol, maxIter, mask(ind), smin);\n        yp(ind) = yp(ind) - K(:, 1:shift)*s(t:(t+shift-1));\n        c(ind) = c(ind) + K(:, 1:shift)*s(t:(t+shift-1));\n        t = t + shift;\n    end\n    s(t:T) = nnls(KK((t+w-T):w, (t+w-T):w), K(1:(T-t+1), 1:(T-t+1))'*yp(t:T), ...\n        s(t:T), tol, maxIter, mask(t:T), smin);\n    c(t:T) = c(t:T) + K((t+w-T):w, (t+w-T):w) * s(t:T); \nend\n\n\nfunction s = nnls(KK, Ky, s, tol, maxIter, mask, smin)\n%% fast algorithm for solving nonnegativity constrained least squared\n% problem minize norm(y-K*s, 2), s.t. s>=0. \n\n%% inputs: \n%   KK: p x p matrix, K'*K\n%   Ky: n x 1 vector, K'*y\n%   s: p x 1 vector, warm started s \n%   tol: scalar, smallest nonzero values \n%   maxIter: scalar, maximum nonzero values \n%   mask: p x 1 vector, mask to restrict potential spike times considered\n%   smin: scala, minimize size of the spike \n\n%% outputs: \n%   s: p x 1 vector, solution \n\n%% Authors: Pengcheng Zhou, Carnegie Mellon University, 2016\n% ported from the Python implementation from Johannes Friedrich\n\n%% References \n% Friedrich J et.al., NIPS 2016, Fast Active Set Method for Online Spike Inference from Calcium Imaging\n% Bro R & Jong S, Journal of Chemometrics 1997, A FAST NON-NEGATIVITY-CONSTRAINED LEAST SQUARES ALGORITHM\n\n\n%% input arguments \nif ~exist('mask', 'var')||isempty(mask)\n    mask = true(size(KK,1), 1); \nelseif any(mask)\n    KK = KK(mask, mask); \n    Ky = Ky(mask); \nelse\n    s = double(mask); \n    return; \nend\n\np = size(KK,2);      % dimension of s \nif ~exist('smin', 'var') || isempty(smin)\n    smin = 0; \nend\nvth = ones(p,1)*smin;  \nif ~exist('s', 'var') || isempty(s)\n    s = zeros(p, 1); \n    l = Ky; \n    Pset = false(p,1); \nelse\n    s = s(mask); \n    s = s - smin; \n    Pset = (s>0);    \n    s(~Pset) = 0; \n    l = Ky - KK*s - KK * Pset*smin; \nend\nif ~exist('tol', 'var') || isempty(tol)\n    tol = 1e-9; \nend\nif ~exist('maxIter', 'var') || isempty(maxIter)\n    maxIter = p; \nend\n\n\n% outer loop: loop for passive set\n[~, ind] = max(l); \nfor miter =1:maxIter   \n    % remove element from the active set \n    Pset(ind) = true;\n    \n    % solve unconstrained least squares over the passive set \n    try\n        mu = KK(Pset, Pset) \\ (Ky(Pset)-KK(Pset, Pset)*vth(Pset));\n    catch % sigular issue\n        mu = (KK(Pset, Pset) + tol*eye(sum(Pset))) \\ (Ky(Pset)...\n            -KK(Pset, Pset)*vth(Pset));\n    end\n    \n    % inner loop: correct nonnegativity violations \n    while any(mu<=0)   \n        temp = s(Pset) ./ (s(Pset)-mu);\n        a = min(temp(mu<0)); \n        s(Pset) = s(Pset) + a*(mu-s(Pset));\n        Pset(s<=tol) = false;\n        \n        % solve unconstrained least squares over the passive set\n        try\n            mu = KK(Pset, Pset) \\ (Ky(Pset)-KK(Pset, Pset)*vth(Pset));\n        catch % sigular issue\n            mu = (KK(Pset, Pset) + tol*eye(sum(Pset))) \\ (Ky(Pset)...\n                -KK(Pset, Pset)*vth(Pset));\n        end\n    end\n    \n    s(Pset) = mu; \n    l = Ky - KK*s - KK*Pset*smin; \n        % at least one iteration \n    [lmax, ind] = max(l); \n    if lmax < tol         % no more passive set\n        break;\n    end\nend\ns(Pset) = mu + smin; \ntemp = double(mask);\ntemp(mask) = s; \ns = temp; \n", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/deconvolution/oasis/onnls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5783539194198222}}
{"text": "function varargout = sqrt(varargin)\n%SQRT (overloaded)\n%\n% t = sqrt(x)\n%\n% The variable t can only be used in concavity preserving\n% operations such as t>=1, max t etc.\n%\n% When SQRT is used in a problem, the domain constraint\n% (x>=0) is automatically added to the problem.\n%\n% In nonconvex cases, use sqrtm instead.\n%\n% See also CPOWER\n\nswitch class(varargin{1})\n    \n    case 'sdpvar' % Overloaded operator for SDPVAR objects. Pass on args and save them.\n        \n        X = varargin{1};\n        [n,m] = size(X);\n        if is(varargin{1},'real') %& (n*m==1)\n            varargout{1} = InstantiateElementWise(mfilename,varargin{:});\n        else\n            error('SQRT can only be applied to real scalars');\n        end\n        \n        \n    case 'char' % YALMIP send 'model' when it wants the epigraph or hypograph\n        switch varargin{1}\n            case 'graph'\n                \n                t = varargin{2}; % Second arg is the extended operator variable\n                X = varargin{3}; % Third arg and above are the args user used when defining t.\n                if is(X,'linear')\n                    varargout{1} = (cone([(X-1)/2;t],(X+1)/2));\n                    varargout{2} = struct('convexity','concave','monotonicity','increasing','definiteness','positive');\n                    varargout{3} = X;\n                elseif is(X,'quadratic')\n                    [F,x] = check_for_special_cases(X,t);\n                    if isempty(F)\n                        varargout{1} = [];\n                        varargout{2} = [];\n                        varargout{3} = [];\n                    else\n                        varargout{1} = F;\n                        varargout{2} = struct('convexity','convex','monotonicity','none','definiteness','positive');\n                        varargout{3} = x;\n                    end\n                    \n                else\n                    varargout{1} = [];\n                    varargout{2} = [];\n                    varargout{3} = [];\n                end\n                \n            otherwise\n                varargout{1} = [];\n                varargout{2} = [];\n                varargout{3} = [];\n        end\n    otherwise\nend\n\n\nfunction [F,x] = check_for_special_cases(q,t)\n% Check if user is constructing sqrt(quadratic). If that is the case,\n% return norm(linear)\nF = [];\nx = [];\nif length(q)>1\n    return\nend\n[Q,c,f,x,info] = quaddecomp(q);\nif info==0 & nnz(Q)>0\n    index = find(any(Q,2));\n    if length(index) < length(Q)\n        Qsub = Q(index,index);\n        [Rsub,p]=chol(Qsub);\n        if p==0\n            [i,j,k] = find(Rsub);\n            R = sparse((i),index(j),k,length(Qsub),length(Q));\n        else\n            R = [];\n        end\n    else\n        [R,p]=chol(Q);\n        if p & min(eig(full(Q)))>=-1e-12\n            [U,S,V] = svd(full(Q));\n            r = max(find(diag(S)));\n            R = sqrtm(S(1:r,1:r))*V(:,1:r)';\n            p = 0;\n        end\n    end\n    d = 0.5*(R'\\c);\n    if p==0 &  f-d'*d>-1e-12\n        F = cone([R*x+d;sqrt(f-d'*d)],t);\n    end\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/sqrt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5783539144506396}}
{"text": "function s_mm=rmNeighborsCompare(vw,model)\n%  rmNeighborsCompare - compute pRF size in mm weighted by variance\n%  explained\n%\n% 2009/02: SD & BH wrote it.\n\nif ~exist('vw','var') || isempty(vw), error('Need view struct'); end\nif ~exist('model','var') || isempty(model), error('Need rm model file'); end\n\n\n% get gray connection structure\ngNodes = viewGet(vw,'nodes');\ngEdges = viewGet(vw,'edges');\ncoords = viewGet(vw,'coords');\n\n% load model params\nx = rmGet(model,'x');\ny = rmGet(model,'y');\ns = rmGet(model,'sigma');\nve = rmGet(model,'varexp');\n\n% output\ns_mm = zeros(size(s));\n\nnGnodes=length(gNodes);\n\ntic;\nfprintf('[%s]:Computing...',mfilename);\nfor t=1:nGnodes % for each gNode...\n    % Find its edges (the nodes of the things that it's connected to...)\n    thisOffset=gNodes(5,t);\n    thisNumEdges=gNodes(4,t);\n    theseEdges=gEdges(thisOffset:(thisOffset-1+thisNumEdges)); %thisoffset-1 or 0?        \n    \n    % variance explained for the neighbors\n    ven = ve(theseEdges);\n    ven = ven./sum(ven);\n    \n    % compute cortical distance from neighbors\n    cdist = coords(:,theseEdges);  \n    cdist = cdist - (coords(:,t)*ones(1,size(cdist,2)));\n    cdist = sum(sqrt(sum(cdist.^2)).*ven);    % distance\n\n    % compute distance from neighbors in visual field\n    vfdist = [x(theseEdges); y(theseEdges)];\n    vfdist = vfdist - ([x(t); y(t)]*ones(1,size(vfdist,2)));\n    vfdist = sum(sqrt(sum(vfdist.^2)).*ven);\n    \n    % compute cortical pRF size\n    s_mm(t) = s(t) * (cdist./vfdist);\nend\n\n% some are not finite when vfdist == 0, we interpolate these values\n% we do this only for spurious voxels, large patches will be set to global\n% mean\nii = find(~isfinite(s_mm));\nfor n=1:5\n    for t=ii\n        % Find its edges (the nodes of the things that it's connected to...)\n        thisOffset=gNodes(5,t);\n        thisNumEdges=gNodes(4,t);\n        theseEdges=gEdges(thisOffset:(thisOffset-1+thisNumEdges)); %thisoffset-1 or 0?\n        \n        % lookup neighboring values with data\n        nb = s_mm(theseEdges);\n        nb = nb(isfinite(nb));\n        \n        if ~isempty(nb)\n            s_mm(t) = mean(nb);\n        end\n    end\n    ii = find(~isfinite(s_mm));\nend\n\n% any left we set to the global mean\nii = ~isfinite(s_mm);\ns_mm(ii) = mean(s_mm(~ii));\n\nfprintf('Done[%dsecs].\\n',round(toc));\n\n% rmGet(model,'s_mm');\n\nreturn\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/retinotopyModel/rmNeighborsCompare.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5783539088620243}}
{"text": "function odf = FourierODF(C,varargin)\n% defines an ODF by its Fourier coefficients\n%\n% Syntax\n%   odf = FourierODF(C,CS,SS)\n%\n% Input\n%  C      - Fourier coefficients / C coefficients\n%  CS, SS - crystal, specimen @symmetry\n%\n% Output\n%  odf - @SO3Fun\n%\n% See also\n% uniformODF unimodalODF BinghamODF fibreODF\n\nodf = SO3FunHarmonic(C,varargin{:});\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/ODFAnalysis/FourierODF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5783538989236583}}
{"text": "function regressedBox = BoxRegresssLog(box, regressionFactor)\n% regressedBox = BoxRegresss(box, regressionFactor)\n%\n% Apply the regressionFactor to the box to get better bounding box:\n% regressedBox(4) = boxMiddle + 1/2 boxWidth + regressionFactor(4) * 1/2 boxWidth\n%                 = boxMiddle + (1+regressionFactor(4)) * 1/2 boxWidth\n%\n% box:              N x 4 vector with BB coordinates\n% regressionFactor: N x 4 vector with regression factors\n%\n% regressedBox:     N x 4 vector with updated BB coordinates\n%\n% In log-space, like Girshick\n%\n% Jasper Uijlings - 2015\n\n% regressedBox(N) = boxMiddle + (1+regressionFactor(N)) * 1/2 boxWidth\nregressionFactor = 2 * (exp(regressionFactor / 6.537) - 0.5);\n\n% Obtain middle\nmiddleOdd = (box(:,1) + box(:,3)) / 2;\nmiddleEven = (box(:,2) + box(:,4)) / 2;\n\n% Apply factors with respect to middle.\n% regress coord = middle       + distance to middle      .* F \nregressedBox(:,4) = middleEven + (box(:,4) - middleEven) .* regressionFactor(:,4);\nregressedBox(:,3) = middleOdd  + (box(:,3) - middleOdd)  .* regressionFactor(:,3);\nregressedBox(:,2) = middleEven + (box(:,2) - middleEven) .* regressionFactor(:,2);\nregressedBox(:,1) = middleOdd  + (box(:,1) - middleOdd)  .* regressionFactor(:,1);\n", "meta": {"author": "nightrome", "repo": "matconvnet-calvin", "sha": "42d7e80bac56741d39404b6646a0866c10aad021", "save_path": "github-repos/MATLAB/nightrome-matconvnet-calvin", "path": "github-repos/MATLAB/nightrome-matconvnet-calvin/matconvnet-calvin-42d7e80bac56741d39404b6646a0866c10aad021/matconvnet-calvin/examples/frcn/boxes/BoxRegresssLog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5783178425447987}}
{"text": "function [Hist] = clipHistogram(Hist,NrBins,ClipLimit,NrX,NrY)\n%  This function performs clipping of the histogram and redistribution of bins.\n%  The histogram is clipped and the number of excess pixels is counted. Afterwards\n%  the excess pixels are equally redistributed across the whole histogram (providing\n%  the bin count is smaller than the cliplimit).\n\nfor i = 1:NrX\n    for j = 1:NrY\n        %   Calculate the total number of excess pixels.\n        NrExcess = 0;\n        for nr = 1:NrBins\n            excess=Hist(i,j,nr) - ClipLimit;\n            if excess > 0\n                NrExcess = NrExcess + excess;\n            end\n        end\n\n        %  Clip histogram and redistribute excess pixels in each bin\n        binIncr = NrExcess / NrBins;\n        upper = ClipLimit - binIncr;\n        for nr = 1:NrBins\n            if Hist(i,j,nr) > ClipLimit\n                Hist(i,j,nr) = ClipLimit;\n            else\n                if Hist(i,j,nr) > upper\n                    NrExcess = NrExcess + upper - Hist(i,j,nr);\n                    Hist(i,j,nr) = ClipLimit;\n                else\n                    NrExcess = NrExcess - binIncr;\n                    Hist(i,j,nr) = Hist(i,j,nr) + binIncr;\n                end\n            end\n        end\n        \n        if NrExcess > 0\n            stepSize = max(1,fix(1+NrExcess/NrBins));\n            for nr = 1:NrBins\n                NrExcess = NrExcess - stepSize;\n                Hist(i,j,nr) = Hist(i,j,nr) + stepSize;\n                if NrExcess < 1\n                    break;\n                end\n            end\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/22182-contrast-limited-adaptive-histogram-equalization-clahe/clipHistogram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5781106912011136}}
{"text": "classdef spherefun < separableApprox\n%SPHEREFUN class for representing functions on the unit sphere.\n% \n%   Class for approximating functions defined on the unit sphere. The \n%   functions should be smooth.\n%\n% SPHEREFUN(F) constructs a SPHEREFUN object representing the function F on\n% the unit sphere. F can have the following form:\n%    1. A function handle in (x,y,z), e.g., @(x,y,z) x.*y.*z + cos(x).\n%    2. A function handle in spherical coordinates (lambda,theta), where\n%       lambda is the azimuthal variable and satisfies -pi <= lambda <= pi\n%       and theta is the polar angle and satisfies 0 <= theta < pi,\n%       e.g., @(lambda,theta) cos(cos(lambda).*sin(theta))\n%    3. A matrix of numbers. \n% If F is a function handle then it should allow for vectorized evaluations.\n%\n% If F is a matrix, F = (f_ij), the numbers fij are used as function values\n% at tensor equally-spaced points in the intrinsic spherical coordinate \n% system, i.e., [-pi,pi]x[0,pi].\n%\n% SPHEREFUN(F, k) returns a rank k approximation to F.\n%\n% SPHEREFUN(F, [m n]) returns a representation of F using a degree m\n% trigonometric approximation of F in the theta (polar) direction and a\n% degree n trigonometric approximation in the lambda (azimuthal) direction.\n% The result is compressed in low rank form and the rank k is still\n% determined adaptively (satisfying k<=min(m,n)+1).\n% \n% The SPHEREFUN software system is based on: \n%\n% A. Townsend, H. Wilber, and G. Wright, Computing with functions in\n% spherical and polar geometries I: The sphere, SIAM. J. Sci. Comput., 38-4\n% (2016), C403-C425.\n%\n% See also CHEBFUN2, DISKFUN, SPHEREFUNV\n\n% Copyright 2017 by The University of Oxford and The CHEBFUN Developers.\n% See http://www.chebfun.org/ for CHEBFUN information.\n\n% TODO: Include documentation of fixed eps construction\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% CLASS CONSTRUCTOR:\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    methods (Access = public, Static = false)\n        \n        function f = spherefun(varargin)\n            % The main spherefun constructor!\n            \n            % Return an empty CHEBFUN:\n            if ( (nargin == 0) || isempty(varargin{1}) )\n                f.domain = [-pi pi 0 pi];\n                return\n            end\n            \n            f = constructor(f, varargin{:});                    \n        end\n        \n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% CLASS METHODS:\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    methods\n        %f = conj(f);\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% HIDDEN METHODS:\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    methods (Access = public, Static = false, Hidden = true)\n        % Project a spherefun to have exact BMC-I symmetry so that it is \n        % a continuous function on the sphere.\n        f = projectOntoBMCI(f);\n       \n        % Fast evaluation of a spherefun using non-uniform fft.\n        vals = fastSphereEval( f, lambda, theta );\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% PUBLIC METHODS:\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    methods (Access = public, Static = false)\n        \n        % The main bulk of the SPHEREFUN constructor:\n        g = constructor(g, op, dom, varargin);\n        \n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% STATIC METHODS:\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    methods (Access = public, Static = true)\n  \n        % Poisson solver: \n        u = poisson(f, const, m, n);\n        \n        % Helmholtz solver: \n        u = helmholtz(f, K, m, n);\n        \n        % Convert matrix of coefficients to a spherefun: \n        f = coeffs2spherefun(CFS); \n        \n        varargout = coeffs2vals(U, varargin); \n        varargout = vals2coeffs(U, varargin);  \n        \n        % Convert a function in spherical coordinates to one in Cartesian\n        % coordinates on the sphere.\n        fdf = sphf2cartf(f, lam, th, coord);\n        \n        % Degree l Order m spherical harmonic.\n        Y = sphharm(l, m, coord);\n        \n        % Plot the outline of the landmasses of earth\n        h = plotEarth(linespec);\n \n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% Private Static methods implemented by SPHEREFUN class.\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    methods (Access = private, Static = true)\n        % Fast evaluation of a spherefun using non-uniform fft.\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% CLASS PROPERTIES\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    properties (Access = public)\n        % DOMAIN: default is [-pi,pi] x [0,pi] which corresponds to using \n        % colatitude for the elevation angle (second input argument). \n        % Doubled-up sphere will have a domain of [-pi,pi] x [-pi,pi].\n        idxPlus\n        idxMinus\n        nonZeroPoles = 0;\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% Private constant properties\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    properties (Constant)\n        % TODO: Add support for this constant here.\n        % alpha = 50;  % Growth factor control.\n    end\n        \nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@spherefun/spherefun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672089305841, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5781106812806602}}
{"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%==============================================================================\n%\n% Tutorial for FAIR:  Landmark Based Registration, quadratic transformation\n%\n% - load data (see setup2DhandData)\n% - setup  viewer (viewImage2D), interpolator (splineInter), \n% - setup landmarks (LM)\n% - run quadratic\n%==============================================================================\n\nclear, close all, help(mfilename)\n\n%% setup hand data\nsetup2DhandData\n\nif FAIRinput('','set new landmarks ? ',0),\n  [LM,fig] = getLandmarks(dataT,dataR,omega,m);\n  close(fig);\nend;\n\nomegaT = omega(1,:);\nomegaR = omega(end,:);\nxT = getCellCenteredGrid(omegaT,m);\nxR = getCellCenteredGrid(omegaR,m);\nTc = imgModel(dataT,omegaT,xT);\nRc = imgModel(dataR,omegaR,xR);\n\n%% visualize data\nFAIRfigure(1,'figname',mfilename); clf; \nsubplot(1,3,1); viewImage(Tc,omegaT,m); hold on;\nph = plotLM(LM(:,1:2),'numbering','on','color','r');\nset(ph,'linewidth',2,'markersize',20);\ntitle(sprintf('%s','T&LM'),'fontsize',20);\n\nsubplot(1,3,2); viewImage(Rc,omegaR,m); hold on;\nph = plotLM(LM(:,3:4),'numbering','on','color','g','marker','+');\nset(ph,'linewidth',2,'markersize',20);\ntitle(sprintf('%s','R&LM'),'fontsize',20);\n\n%% compute landmark based registration\n[yc,LM] = LMreg('quadratic',LM(:,1:4),xR);\nTLM = imgModel(dataT,omegaT,yc);\n\nsubplot(1,3,3); cla; viewImage(TLM,omegaR,m); hold on;\nph = plotLM(LM(:,3:4),'numbering','off','color','g','marker','+');\nqh = plotLM(LM(:,7:8),'numbering','off','color','m','marker','x');\nrh = plot(LM(:,[3,7])',LM(:,[4,8])','m-','linewidth',3);\nset([ph;qh;rh],'linewidth',2,'markersize',20);\ntitle(sprintf('%s','T(y^{quadratic})&LM'),'fontsize',20);\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/E5_2D_quadratic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5781106730708708}}
{"text": "% Computing most probable explanation.\n\n% If you don't break ties consistently, loopy can give wrong mpe\n% even though the graph has no cycles, and even though the max-marginals are the same.\n% This example was contributed by Wentau Yih <wtyih@yahoo.com> 29 Jan 02.\n\n% define loop-free graph structure (all edges point down)\n%\n% Xe1   Xe2\n%  |    |\n%  E1   E2\n%    \\ /\n%     R1\n%     |\n%    Xr1\n\nN = 6;\ndag = zeros(N,N);\nXe1 = 1; Xe2 = 2; E1 = 3; E2 = 4; R1 = 5; Xr1 = 6;\ndag(Xe1, E1) = 1;\ndag(Xe2, E2) = 1;\ndag([E1 E2], R1) = 1;\ndag(R1, Xr1) = 1;\n\nnode_sizes = [ 1 1 2 2 2 1 ];\n\n% create BN\n\nbnet = mk_bnet(dag, node_sizes, 'observed', [Xe1 Xe2 Xr1]);\n\n% fill in CPT\n\nbnet.CPD{Xe1} = tabular_CPD(bnet, Xe1, [1]);\nbnet.CPD{Xe2} = tabular_CPD(bnet, Xe2, [1]);\nbnet.CPD{E1} = tabular_CPD(bnet, E1, [0.2 0.8]);\nbnet.CPD{E2} = tabular_CPD(bnet, E2, [0.3 0.7]);\nbnet.CPD{R1} = tabular_CPD(bnet, R1, [1 1 1 0.8 0 0 0 0.2]);\nbnet.CPD{Xr1} = tabular_CPD(bnet, Xr1, [0.15 0.85]);\n\nclear engine;\nengine{1} = belprop_inf_engine(bnet);\nengine{2} = jtree_inf_engine(bnet);\nengine{3} = global_joint_inf_engine(bnet);\nengine{4} = var_elim_inf_engine(bnet);\n\nevidence = cell(1,N);\nevidence{Xe1} = 1;  evidence{Xe2} = 1;  evidence{Xr1} = 1;\n\nmpe = find_mpe(engine{1}, evidence, 'break_ties', 0) % gives wrong results\nmpe = find_mpe(engine{1}, evidence)\nfor i=2:4\n  mpe = find_mpe(engine{i}, evidence)\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/static/mpe2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5781106698785635}}
{"text": "function x = slopeinit(xs,X)\n%SLOPEINIT    Initialization of slope expansion\n%\n%  x = slopeinit(xs,X)\n%\n%This statement with interval quantities xs and X followed by\n%  a function evaluation\n%\n%  y = f(x)\n%\n%using arithmetic operations and standard functions (overloaded by\n%slope operators) implies 3 assertions:\n%\n%  1)  f(xs) in y.c\n%  2)  f(X)  in y.r\n%  3)  For all xp in X there exists s in y.s with  f(xp) = f(xs) + s*(xp-xs) .\n%\n%The expansion point xs and expansion interval X must be real quantities,\n%  non-interval input data is converted into interval data to ensure\n%  correctness of 1..3).\n%\n%The call\n%\n%  slopeinit\n%\n%without input parameters initializes the slope expansion to xs = X = [].\n%\n%The slope of arrays is stored in the 'next dimension'. So y.s is \n%  3-dimensional for a slope row vector y. Since Matlab does not \n%  support multi-dimensional sparse arrays, y.s is not accessible \n%  if y has more than one column.\n%\n%As a simple example of slopes\n%\n%  xs = [ -3 ; 7.15 ] ;  X = intval(' [ -3.1,-2.9 ]  [ 7,7.1 ] ') ;\n%  u = slopeinit( xs , X );\n%\n%initializes the slope package to have two dependent variables. The\n%expansion point is xs=[-3;7.15] with expansion interval X.\n%\n%For a function f from R^2 to R, y=f(u) computed by overloaded slope\n%operators has access y.c, y.r and y.s with the properties listed above.\n%Internally, slopes are computed and stored according to\n%\n%  S.M. Rump: Expansion and Estimation of the Range of Nonlinear Functions,\n%    Math. Comp. 65(216), p. 1503-1512 (1996).\n%\n%In contrast to the usual definition of slopes (see Neumaier's book),\n%\n%  - rather than one n-dimensional slope, n one-dimensional slopes\n%      are calculated treating the function\n%        f(X_1,...,X_k-1,z,xs_k+1,...,xs_n)\n%      as a function in one variable z.\n%  - intersections for the two definitions of multiplication and division\n%      sharpens results (note this is not possible for n-dimensional slopes)\n%  - intersections of the computed range y.r with y.c+y.s(X-xs) sharpens\n%      results\n%  - the sharp formulas for slopes of convex and concave functions are\n%      used (for details, see the paper).\n%\n%Slope are useful for verified inclusion of clustered or multiple zeros.\n%Sometimes, the range estimation is better than naive interval arithmetic\n%or gradient expansion.\n%\n%For a simple plot of one-dimensional slopes, see slopeplot.\n%\n\n% written  12/06/98     S.M. Rump\n% modified 09/28/01     S.M. Rump  matrices and multi-dimensional arrays\n% modified 04/06/04     S.M. Rump  handling of derivatives of sparse arrays\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 08/26/12     S.M. Rump  global variables removed\n% modified 10/03/12     S.M. Rump  SlopeSparseArrayDeriv removed\n%\n\n  if nargin==0\n    INTLAB_SLOPE.NUMVAR = 0;\n    INTLAB_SLOPE.Xxs = [];\n    setappdata(0,'INTLAB_SLOPE',INTLAB_SLOPE);\n    return\n  end\n\n  if ~isreal(xs) | ~isreal(X)\n    error('Complex numbers not allowed in slope expansion')\n  end\n\n  if ( ~isa(xs,'double') & ~isa(xs,'intval') ) | ...\n     ( ~isa(X,'double') & ~isa(X,'intval') )\n    error('invalid initialization of slopes: input must be double or intval')\n  end\n\n  if ~isequal(size(xs),size(X))\n    error('invalid initialization of slopes: dimensions do not match')\n  end\n\n  % initialize INTLAB constants\n  INTLAB_SLOPE.NUMVAR = prod(size(xs));\n  dummy.xs = intval(xs);\n  dummy.X = intval(X);\n  INTLAB_SLOPE.Xxs = dummy.X - dummy.xs;\n  INTLAB_SLOPE.Xxs = INTLAB_SLOPE.Xxs(:);\n  setappdata(0,'INTLAB_SLOPE',INTLAB_SLOPE);\n  x = slope( dummy, 'slopeinit' );\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/slope/slopeinit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672089305841, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5781106665717457}}
{"text": "function S_lags=bss_make_lags(S,L)\n\n% create a matrix containing lagged versions of some signal(s).\n%\n% Usage: S_lags=bss_make_lags(S,L)\n%\n% Input:\n%   - S: n x T matrix containing the input signal(s),\n%   - L: number of lagged versions of the signal(s).\n%\n% Output:\n%   - S_lags: n*L x T matrix containing lagged versions of S, S_lags(t)=\n%   [s1(t) ; s1(t-1) ; ...; s1(t-L+1); ... ; sn(t) ; sn(t-1) ; ...; sn(t-L+1)]\n%\n% WARNINGS:\n%   * S_lags is zero-padded where necessary,\n%   * We use the conventions make_lags(S,0)=makes_lags(S,1)=S.\n%\n% Developers:  - Cedric Fevotte (fevotte@tsi.enst.fr) - Emmanuel Vincent\n% (emmanuel.vincent@irisa.fr) - Remi Gribonval (remi.gribonval@irisa.fr)\n\n[n,T]=size(S);\n\nif L==0\n    S_lags=S;\nelse\n    \n    N=n*L;\n    S_lags=zeros(N,T);\n    for i=1:N\n        q=floor((i-1)/L);\n        r=mod(i-1,L);\n        B=zeros(1,r+1); B(end)=1;\n        S_lags(i,:)=filter(B,1,S(q+1,:));    \n    end\n    \nend", "meta": {"author": "posenhuang", "repo": "deeplearningsourceseparation", "sha": "6a6e54d9234756e9624507f66d9e8fcd0b868dc7", "save_path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation", "path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation/deeplearningsourceseparation-6a6e54d9234756e9624507f66d9e8fcd0b868dc7/tools/bss_eval_2.1/bss_make_lags.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5781106632649278}}
{"text": "function [Population,Archive,Fitness] = EnvironmentalSelection(Population,N)\n% The environmental selection of SPEA2\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    %% Calculate the fitness of each solution\n    Fitness = CalFitness(Population.objs);\n\n    %% Environmental selection\n    Next    = Fitness < 1;\n    Archive = Population(Next);\n    if sum(Next) < N\n        [~,Rank] = sort(Fitness);\n        Next(Rank(1:N)) = true;\n    elseif sum(Next) > N\n        Del  = Truncation(Population(Next).objs,sum(Next)-N);\n        Temp = find(Next);\n        Next(Temp(Del)) = false;\n        Archive = Population(Next);\n    end\n    % Population for Next generation\n    Population = Population(Next);\n    Fitness    = Fitness(Next);\nend\n\nfunction Del = Truncation(PopObj,K)\n% Select part of the solutions by truncation\n\n    %% Truncation\n    Distance = pdist2(PopObj,PopObj);\n    Distance(logical(eye(length(Distance)))) = inf;\n    Del = false(1,size(PopObj,1));\n    while sum(Del) < K\n        Remain   = find(~Del);\n        Temp     = sort(Distance(Remain,Remain),2);\n        [~,Rank] = sortrows(Temp);\n        Del(Remain(Rank(1))) = true;\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/SGEA/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.578081894068399}}
{"text": "classdef nnslice < nntest\n  methods (Test)\n\n    function basic(test)\n        sz = [3,3,5,4] ;\n        x = test.randn(sz) ;\n        dim = 4 ;\n        slicePoints = 1:dim - 1 ; % slice along fourth dim\n        y = vl_nnslice(x, dim, slicePoints, []) ;\n\n        % check derivatives with numerical approximation\n        dzdy = cellfun(@(x) test.randn(size(x)), y, 'Uni', 0) ;\n        dzdx = vl_nnslice(x, dim, slicePoints, dzdy, 'inputSizes', {sz}) ;\n        dzdy_ = cat(dim, dzdy{:}) ;\n        dzdx_ = dzdx{1} ;\n        test.der(@(x) forward_wrapper(x, dim, slicePoints), x, dzdy_, dzdx_, 1e-3*test.range) ;\n    end\n  end\nend\n\n% -----------------------------------------------------------------\nfunction y = forward_wrapper(x, dim, slicePoints)\n% -----------------------------------------------------------------\n  y = vl_nnslice(x, dim, slicePoints, []) ;\n  y = cat(dim, y{:}) ;\nend\n", "meta": {"author": "ShuaiBai623", "repo": "MFT", "sha": "8762f8cdf494ce0b1a1c3d431660c5c8fd91744a", "save_path": "github-repos/MATLAB/ShuaiBai623-MFT", "path": "github-repos/MATLAB/ShuaiBai623-MFT/MFT-8762f8cdf494ce0b1a1c3d431660c5c8fd91744a/external_libs/matconvnet/contrib/mcnExtraLayers/matlab/xtest/suite/nnslice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5780818888870992}}
{"text": "function [x,r,g,info] = spg_lasso(A,b,tau,varargin )\n%SPG_LASSO  Solve the LASSO problem\n%\n%   SPG_LASSO is designed to solve the LASSO problem\n%\n%   (LASSO)  minimize  ||AX - B||_2  subject to  ||X||_1 <= tau,\n%\n%   where A is an M-by-N matrix, B is an M-vector, and TAU is a\n%   nonnegative scalar.  In all cases below, A can be an explicit M-by-N\n%   matrix or matrix-like object for which the operations  A*x  and  A'*y\n%   are defined (i.e., matrix-vector multiplication with A and its\n%   adjoint.)\n%\n%   Also, A can be a function handle that points to a function with the\n%   signature\n%\n%   v = A(w,mode)   which returns  v = A *w  if mode == 1;\n%                                  v = A'*w  if mode == 2. \n%   \n%   X = SPG_LASSO(A,B,TAU) solves the LASSO problem.\n%\n%   X = SPG_LASSO(A,B,TAU,OPTIONS) specifies options that are set using\n%   SPGSETPARMS.\n%\n%   [X,R,G,INFO] = SPG_LASSO(A,B,TAU,OPTIONS) additionally returns the\n%   residual R = B - A*X, the objective gradient G = A'*R, and an INFO\n%   structure.  (See SPGL1 for a description of this last output argument.)\n%\n%   See also spgl1, spgSetParms, spg_bp, spg_bpdn.\n\n%   Copyright 2008, Ewout van den Berg and Michael P. Friedlander\n%   http://www.cs.ubc.ca/labs/scl/spgl1\n%   $Id: spg_lasso.m 1074 2008-08-19 05:24:28Z ewout78 $\n\nif ~exist('tau','var'), tau = []; end\nif ~exist('b','var') || isempty(b)\n    error('Second argument cannot be empty.');\nend\nif ~exist('A','var') || isempty(A)\n    error('First argument cannot be empty.');\nend\n\nsigma = [];\nx0  = [];\n[x,r,g,info] = spgl1(A,b,tau,sigma,x0,varargin{:});\n", "meta": {"author": "mpf", "repo": "spgl1", "sha": "361a5980667288857e4f4f84c53b536ddfac1d53", "save_path": "github-repos/MATLAB/mpf-spgl1", "path": "github-repos/MATLAB/mpf-spgl1/spgl1-361a5980667288857e4f4f84c53b536ddfac1d53/spg_lasso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5780818761557541}}
{"text": "function [Population,Dec,Mask,FrontNo,CrowdDis] = EnvironmentalSelection(Population,Dec,Mask,N)\n% The environmental selection of SLMEA\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    %% Delete duplicated solutions\n    objs = Population.objs;\n    objs = gather(objs);\n    \n    [objs,uni] = unique(objs,'rows');\n    Population = Population(uni);\n    Dec        = Dec(uni,:);\n    Mask       = Mask(uni,:);\n    N          = min(N,length(Population));\n    %% Non-dominated sorting\n    [FrontNo,MaxFNo] = NDSort(objs,gather(Population.cons),N);\n    Next = FrontNo < MaxFNo;\n    \n    %% Calculate the crowding distance of each solution\n    CrowdDis = CrowdingDistance(objs,FrontNo);\n    \n    %% Select the solutions in the last front based on their crowding distances\n    Last     = find(FrontNo==MaxFNo);\n    [~,Rank] = sort(CrowdDis(Last),'descend');\n    Next(Last(Rank(1:N-sum(Next)))) = true;\n    \n    %% Population for next generation\n    Population = Population(Next);\n    FrontNo    = FrontNo(Next);\n    CrowdDis   = CrowdDis(Next);\n    Dec        = Dec(Next,:);\n    Mask       = Mask(Next,:);\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/SLMEA/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5780818650035724}}
{"text": "function plota(a,peval,savethis)\n% plota(a,peval,savethis)\n\n% figure\n% plot(a','.:')\n% xlabel('time');\n% ylabel('a');\n% grid on\n% setfontsizefigure(12)\n% if savethis \n%     SaveImageFULL([peval.res_dir '/a'])\n% end\n\nfigure\nbar(mean(a,2))\nhold on\nerrorbar(1:size(a,1), mean(a,2),std(a,[],2),'+r')\nxlabel('component')\nylabel('mean(intensity)')\ngrid on\nsetfontsizefigure(12)\nif savethis \n    SaveImageFULL([peval.res_dir '/a_mean'])\nend\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/ploting/plota.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5780154397995051}}
{"text": "function F = besselk(nu, F, scale, pref)\n%BESSELK   Modified Bessel function of second kind of a CHEBFUN.\n%   K = BESSELK(NU, F) computes the modified Bessel function of second kind\n%   K_NU(F) of the nonzero CHEBFUN F. If F passes through the origin in its\n%   domain, then an error is returned. The order NU need not be an integer but\n%   must be real. The argument F can be complex.\n%\n%   K = BESSELK(NU, F, SCALE) returns a scaled K_NU(F) specified by SCALE:\n%         0 - (default) is the same as BESSELK(NU, F),\n%         1 - scales K_NU(F) by exp(F)).\n%\n%   K = BESSELK(NU, F, SCALE, PREF) uses the CHEBFUNPREF object PREF when\n%   building the CHEBFUN K.\n%\n% See also AIRY, BESSELH, BESSELI, BESSELJ, BESSELY.\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 < 4 )\n    pref = chebfunpref();\nend\nif ( nargin < 3 )\n    scale = 0;\nend\n\n% Loop over the columns:\nfor k = 1:numel(F)\n    F(k) = columnBesselk(nu, F(k), scale, pref);\nend\n\nend\n\nfunction g = columnBesselk(nu, f, scale, pref)\n\n% Check for roots:\nr = roots(f, 'nojump', 'nozerofun');\nif ( numel(r) > 0 )\n    error('CHEBFUN:CHEBFUN:besselk:zero', 'F has roots in its domain.');\nend\n\n% Compose:\ng = compose(f, @(x) besselk(nu, x), pref);\n\n% Scale (as described in help documentation):\nif ( scale == 1 )\n    scl = exp(f);\n    g = scl.*g;\nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun/besselk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5780154384463155}}
{"text": "function H = cross(F, G)\n%CROSS   Cross product of CHEBFUN3V objects.\n%   CROSS(F, G) returns a CHEBFUN3V representing the 3D cross product of \n%   the CHEBFUN3V objects F and G. \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) || isempty(G) )\n    H = chebfun3v;\n    return\nend\n\n% Get number of components:\nFc = F.components; \nGc = G.components; \n\nif ( F.nComponents == 3 && G.nComponents == 3 )\n    H = [ Fc{2} .* Gc{3} - Fc{3} .* Gc{2};\n          Fc{3} .* Gc{1} - Fc{1} .* Gc{3};\n          Fc{1} .* Gc{2} - Fc{2} .* Gc{1}];\nelse\n    error('CHEBFUN:CHEBFUN3V:cross:components', ...\n        'CHEBFUN3V objects must be both 3-vectors.');\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/@chebfun3v/cross.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5780154334338202}}
{"text": "clc\nclear \nclose all\n\n\n% To run this script we recommend running example2 first to create all the\n% necessary outpouts from GLMsingle that are going to be reused here.\n\n% This script shows how to find single-trial beta weights in the output of\n% the GLMsingle. We will show how to average them to create one response\n% to each condition rather then a response to each trial. This will produce\n% one beta weight for each condition. Additionaly we will show how to \n% calculatea t-statistic for each condition and a contrast between two \n% example conditions in the fLoc experiment (number vs. face) using single \n% trial betas.\n\n\n% load design\nload('./data/nsdflocexampledataset.mat')\n\nfigure(1);clf\n\n%Show design matricies.\nfor d = 1:length(design)\n    subplot(2,2,d)\n    imagesc(design{d}); colormap gray; drawnow\n    xlabel('Conditions')\n    ylabel('TRs')\n    title(sprintf('Design matrix for run%i',d))\nend\n\n% There are 10 differenet conditions in this dataset.\n\n%%\n% This NSD fLOC scan session has 6 repetitions of each condition per run.\n% In the code below, we are attempting to locate the indices in the beta\n% weight GLMsingle outputs modelmd(x,y,z,trials) that correspond to\n% repeated conditions.\n\n% Consolidate design matrices\ndesignALL = cat(1,design{:});\n\n% Construct a vector containing 1-indexed condition numbers in\n% chronological order.\n\ncorder = [];\nfor p=1:size(designALL,1)\n    if any(designALL(p,:))\n        corder = [corder find(designALL(p,:))];\n    end\nend\n\n\n% We will now find indices for each condition. First lets find all unique\n% condition in the corder list\n\ncondition_list = unique(corder);\n\n% We will now create a structure where each cell containst indices for\n% different condition. \n\ncondition_ind = cell(length(condition_list),1);\nfor i = 1 : length(condition_list)\n    \n    condition_ind{i} =  find(corder == condition_list(i));\n    \nend\n    \n% Knowing the indicies of each condition we can now load an example output\n% of GLMsingle and create 1 beta weight for each condition. In the example\n% 1 there are 10 unique conditions.\n\nresults = load('./example2outputs/GLMsingle/TYPED_FITHRF_GLMDENOISE_RR.mat');\nbetas = results.modelmd;\nsz = size(betas);\nbetas_average = zeros([sz(1) sz(2) sz(3) length(condition_ind),1]);\n\nfor i = 1 : length(condition_list)\n    \n    betas_average(:,:,:,i) = nanmean(betas(:,:,:,condition_ind{i}),4);\n    \nend\n\n% Initially there were 240 betas (each of 10 conditions was repeated 24\n% times. \n\nfprintf('GLMsingle output had %i betas before averaging \\n',size(betas,4))\n\n% After averaging there is 1 beta weight for each condition\n\nfprintf('GLMsingle output has %i betas after averaging \\n',size(betas_average,4))\n\n\n%% Calculate t-statistic for each condition\n% We calculate t-stat as the mean over the standard deviation across all\n% repetitions of the same condition. \n\nt_stat =  zeros([sz(1) sz(2) sz(3) length(condition_ind),1]);\n\nfor n = 1 : length(condition_list)\n\n    t_stat(:,:,:,n) = nanmean(betas(:,:,:,condition_ind{i}),4) ./ (std(betas(:,:,:,condition_ind{i}),[],4)./sqrt(length(condition_ind{i})));\n    \nend\n\n%% Calculate a contrast between condition 2 (number) and condition 5 (adult face)\n\n[~,p,~,stats] = ttest2(betas(:,:,:,condition_ind{2}),betas(:,:,:,condition_ind{5}),'dim',4);\n\n%% Plot estiamted contrasts \nslices = [20 10];\n\n\nunderlay = data{1}(:,:,:,1);\n\nthings2plot = {'t_stat';'stats.tstat'};\n\nfigure(1);clf\nfor f = 1 : length(things2plot)\n    \n    slice = slices(f);\n    subplot(1,2,f)\n    overlay  = eval(things2plot{f});\n    overlay  = overlay(:,:,slice);\n    \n    brainmask = (overlay < -3 | overlay > 3);\n\n    underlay_im = cmaplookup(underlay,min(underlay(:)),max(underlay(:)),[],gray(256));\n    overlay_im  = cmaplookup(overlay,-4,4,[],cmapsign2);\n    \n    hold on\n    imagesc(squeeze(underlay_im(:,:,slice,:)));\n    imagesc(overlay_im,'AlphaData',brainmask);\n    axis image\n    axis off\n    set(gca,'FontSize',14)\n    title(sprintf('%s, slice = %i',things2plot{f},slice),'Interpreter','None')\n    \n    colormap(cmapsign2)\n    c = colorbar;\n    c.Ticks = [0 0.5 1];\n    c.TickLabels = {'-3';'0';'3'};\n            \n\nend\n\n% The t-statistic (t_stat) shows high values in the visual cortex while the\n% t-test between two conditions shows positive voxels in more ventral and\n% lateral portions of the brain.\n\n\n", "meta": {"author": "cvnlab", "repo": "GLMsingle", "sha": "e37bbc9f26362094e3a574f8d6c2156f5fa92077", "save_path": "github-repos/MATLAB/cvnlab-GLMsingle", "path": "github-repos/MATLAB/cvnlab-GLMsingle/GLMsingle-e37bbc9f26362094e3a574f8d6c2156f5fa92077/matlab/examples/example5_average_single_trial_betas_t_stat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5780154284213249}}
{"text": "function [y,deriv] = sum_ai_f_of_w_i(w,a,f,b)\n% This is an MV2DF. See MV2DF_API_DEFINITION.readme.\n%\n% Does y = sum_i a_i f(w_i) + b, where f is non-linear.\n%\n%Notes: \n%\n%  f is a function handle, with behaviour as demonstrated in the test code\n%  of this function.\n%\n%  b is optional, defaults to 0 if omitted\n\nif nargin==0\n    test_this();\n    return;\nend\n\nif ~exist('b','var')\n    b = 0;\nend\n\n\nif isempty(w)\n    y = @(w)sum_ai_f_of_w_i(w,a,f,b);\n    return;\nend\n\nif isa(w,'function_handle')\n    outer = sum_ai_f_of_w_i([],a,f,b);\n    y = compose_mv(outer,w,[]);\n    return;\nend\n\nntot = length(a);\nnz = find(a~=0);\na = a(nz);\n\nif nargin==1\n    y = f(w(nz));\nelse\n    [y,dfdw,f2] = f(w(nz));\n    deriv = @(Dy) deriv_this(Dy,dfdw.*a,f2,a,nz,ntot);\nend\ny = y(:);\ny = a.'*y + b;\n\n\nfunction [g,hess,linear] = deriv_this(Dy,g0,f2,a,nz,ntot)\ng = zeros(ntot,1);\ng(nz) = Dy*g0(:);\nhess = @(d) hess_this(d,g0,f2,Dy,a,nz,ntot);\nlinear = false;\n\n\nfunction [h,Jd] = hess_this(d,g0,f2,Dy,a,nz,ntot)\nd = d(nz);\nhnz = f2();\nhnz = hnz(:).*d(:);\nh = zeros(ntot,1);\nh(nz) = Dy*(hnz.*a);\nif nargout>1 \n    Jd = g0.'*d(:);\nend\n\n\n\nfunction [y,ddx,f2] = test_f(x)\ny = log(x);\nif nargout>1\n    ddx = 1./x;\n    f2 = @() -1./(x.^2);\nend\n\n\nfunction test_this()\nn = 10;\na = randn(n,1);\na = bsxfun(@max,a,0);\nb = 5;\nf = sum_ai_f_of_w_i([],a,@(x)test_f(x),b);\n\nw = 1+rand(n,1);\ntest_MV2DF(f,w);\n", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/tDCF_v1/bosaris_toolkit.1.06/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_library/scalar/templates/sum_ai_f_of_w_i.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5780154220556398}}
{"text": "% MVNORMRND - Multivariate Normal - Random Number Generation\n% Copyright (c) 1998, Harvard University. Full copyright in the file Copyright\n% \n% Y = mvnormrnd(mu, sigma, n) \n%\n%   mu = p by 1 mean column vector or n by p matrix of means\n%   sigma = covariance matrix\n%   n = number of observations to generate\n%\n%   Y = an n by p matrix of row vectors with mean mu and covariance sigma\n%\n% Note: works slightly different from Matlab builtin MVNRND.\n%\n%   if mu is a column vector, n rows will be returned, all with mean mu\n%\n%   if mu is a matrix, a matrix of the same size will be returned with\n%   row Y(i,:) having mean mu(i,:) .\n% \n% See also: MVNORMPDF, MVNORMLPR\n\nfunction [Y] = mvnormrnd (mu,sigma,n) \n\n[d1,d2] = size(mu);\nS = chol(sigma)';\n\nif d2==1,\n  % then mu is a column vector\n  X = normrnd(0,1,n,d1);\n  Y = X*S' + ones(n,1)*mu' ;\nelse \n  X = normrnd(0,1,d1,d2);\n  Y = X*S' + mu ;\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/198-mcmc/mcmc/mvnormrnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5779791901031702}}
{"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox \n% LagLDDDM - A Lagrangian Gauss--Newton--Krylov Solver for Mass- and \n%                        Intensity-Preserving Diffeomorphic Image Registration\n% \n% For details and license info see \n% - https://github.com/C4IR/FAIR.m/tree/master/add-ons/LagLDDMM\n%\n% function [Sc,dS,d2S] = curvatureST(uc,omega,m,varargin)\n%\n% Matrix-free spatio-temporal curvature regularization energy for vc\n% where vc is cell-centered\n%\n% Sv) = 0.5 * \\int_{\\omega}\\int_0^1 \n%               alpha(1)*v(x,t)'*A*v(x,t)+ alpha(2)*v(x,t)'*B*v(x,t) dx dt,\n%\n% where A is the curvature operator and B the first-order time derivative\n% operator.\n%\n% Input:\n%\n%   vc          instationary velocity field (cell-centered)\n%   omega       spatial domain\n%   m           number of discretization points in space\n%   varargin    optional parameters (see below)\n%\n% Optional Input:\n%   tspan       time span (default: [0 1])\n%   nt          number of time points for velocity\n%\n%\n% Output:\n%\n%   Sc          current value  (0.5 * hd * uc'* A *uc)\n%   dS          derivative     (hd * uc'*A )\n%   d2S         Hessian        A\n%  if ~matrixFree,  d2S is sparse matrix; else, d2S is struct; endif\n%\n% see also curvature.m\n% ==================================================================================\n\nfunction [Sc,dS,d2S] = mbCurvatureST(vc,omega,m,varargin)\nif nargin == 0\n    help(mfilename);\n    return;\nend\n\nif strcmp(vc,'para')\n    Sc = 'cell-centered';       % grid\n    dS = 0;                     % matrixFree\n    d2S = 'pcg';  % solver\n    return;\nend\n\n\npersistent A omegaOld mOld alphaOld ntOld tspanOld\n\nif ~exist('mOld','var'),     mOld = [];     end;\nif ~exist('omegaOld','var'), omegaOld = []; end;\nif ~exist('alphaOld','var'), alphaOld = []; end;\n\nalpha       = [1 1e-3];\ntspan       = [0 1];\nnt          = [];\nfor k=1:2:length(varargin), % overwrites default parameter\n    eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend;\n\ndim = numel(omega)/2;\n\nif isempty(nt), % roughly estimate nt\n    nt = round(numel(vc)/(prod(m)*dim))-1;\nend\n\n\n    build =  isempty(mOld) || isempty(omegaOld) ...\n        || length(mOld) ~= length(m) || length(omegaOld) ~= length(omega) ...\n        || any(mOld ~= m) || any(omegaOld~=omega)|| any(alphaOld~=alpha) || any(tspanOld~=tspan) || any(ntOld~=nt);\n    if build,\n        fprintf('%s - rebuilding op\\n',mfilename);\n        A = getCurvatureMatrixST(omega,tspan,m,nt,alpha);\n        A = A'*A;\n        mOld = m; omegaOld = omega; alphaOld = alpha; ntOld = nt; tspanOld = tspan;\n    end;\n    dS  = vc'*A;\n    Sc  = 0.5*dS*vc;\n    d2S = A;\n\n\nfunction C = getCurvatureMatrixST(omega,tspan,m,nt,alpha)\n\nh   = (omega(2:2:end)-omega(1:2:end))./m;\nhd  = prod(h);\n% compute time-stepsize\ndt = abs(tspan(2)-tspan(1))/nt;\n\n% build gradient matrix for one transformation\nC =  getCurvatureMatrix(omega,m);\na = sqrt(alpha(1).*hd.*dt*[1/2;ones(nt-1,1);1/2]);\n% apply spatial regularization to all transformations and sum up in\n% time\nC =  kron(sdiag(a(:)),C);\n\n% get time regularization matrix\nif alpha(2)>0\n    b = sqrt(alpha(2)*hd.*dt);\n    Bt = b * getTimeDiffusionMatrix(nt,dt,prod(m),length(omega)/2);\n    C  = [C;Bt];\nend\n\nfunction D = sdiag(v)\nD = diag(sparse(v(:)));\n\nfunction A = getTimeDiffusionMatrix(nt,dt,n,dim)\nDt=spdiags(ones(nt+1,1)*[-1/dt 1/dt],0:1,nt,nt+1);\nA = kron(Dt, speye(n*dim)); % 2nd deriveative over time for two components\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/add-ons/LagLDDMM/mbCurvatureST.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5779791901031702}}
{"text": "function e = mohsst5_rmsew(Y, Yh)\n\nZ = Y-Yh;\nI = ~isnan(Z);\n\n% Weight proportional to area size\nload('mohsst5_data.mat', 'latitude', 'longitude');\n%[lat,lon] = meshgrid(latitude, longitude);\n[lon,lat] = meshgrid(longitude, latitude);\nW = repmat(cosd(lat(:)), [1, size(Y,2)]);\n\ne = rmsew(Z(I), W(I));\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/datasets/mohsst5/mohsst5_rmsew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5779791892936617}}
{"text": "function [mps] = ftps2mps(ftps)\n% Convert speed from feet per second to meters per hour\nmps = ftps*0.3048 ;", "meta": {"author": "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/ftps2mps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.577979185268552}}
{"text": "function [Im]=Walsh_DWT_Decoding(Header)\n%Walsh-Harmard Transform with Tow level Discrete Wavelete Transform for image Decompression  \n% Designed by  Mohammed M. Siddeq\n% Date 2012-2-22\n% Email :- mamadmmx76@yahoo.com\n% \n% this program is used for Decompress grayscale images by using : \n% INPUT\\  Header : this parameter contains all infmration about compressed file\n% \n%OUTPUT\\  Im : Decoded image from \"Header\" \n\n\n% --- Very important for you ----------------------------------------------\n%Befroe apply this function you need the following programs:\n% 1- \"Arith_code.m\" and \"Arith_Decode.m\"\n% 2- \"Walsh2D_Transform.m\"\n%Note\\ these programs free for download from the following website: \n%     www.MathWorks.com  -> Auther = Siddeq\n\n%--------------------------------------------------------------------------\n% Example (1) --- for compression grayscale images-------------------------\n%    I = imread('D:\\images\\image1.bmp'); % read an image\n%    [Header]=Walsh_DWT_Coding(I,[0.025, 0.025],'db3',2); % Apply function\n%    \n%     \n%    [Im]=Walsh_DWT_Decoding(Header); % for decoding;\n%    imshow(uint8(Im)); % show final decoded image \n\n\n% Example (2) -------------------------------------------------------------\n%    I = imread('D:\\images\\imageG.bmp'); %-> read an image\n%    [Header]=Walsh_DWT_Coding(I,[0.025, 0.025],'db5',3); %-> Apply function\n%    save('C:\\imageG.WWT', 'Header'); -> save compressed file....\n%   \n%   X=load('C:\\imageG.WWT', '-mat'); %-> load compressed file....\n%   H=X.Header;\n%   Im=Walsh_DWT_Decoding(H); %-> for decoding;\n%   imshow(Im); %-> show final decoded image \n%\n%----------------------------------- Good Luck -------------------------\n\n\n%--Read Header file for Decoding.....\nS_2=double(Header(1).S_2);\nS_=double(Header(2).S_);\nCode_Arr=double(Header(3).Code_Arr);\nArr_H1=double(Header(4).Arr_H1);\nArr_H2=double(Header(5).Arr_H2);\nCode_Data1=double(Header(6).Code_Data1);\nData1_H1=double(Header(7).Data1_H1);\nData1_H2=double(Header(8).Data1_H2);\nCode_Data2=double(Header(9).Code_Data2);\nData2_H1=double(Header(10).Data2_H1);\nData2_H2=double(Header(11).Data2_H2);\nCode_Data3=double(Header(12).Code_Data3);\nData3_H1=double(Header(13).Data3_H1);\nData3_H2=double(Header(14).Data3_H2);\nDC_Values=double(Header(15).DC_Values);\nM=double(Header(16).M);\nPara=double(Header(17).Para);\nF1=double(Header(18).F1);\nF2=double(Header(19).F2);\nwave_name=Header(20).wave_name;\n%---------------------------------------------------------------\n\n\n\n\nArr_Size=8; %window size 2x2 or 4x4 or 8x8 used by Walsh-Transformed ................ \n\n\n%--------Compute the Quantization Matrix\nQ(1:Arr_Size,1:Arr_Size)=1; % initilize quantization matrix........\nL=M.*F1;\nfor i=1:Arr_Size \n    for j=1:Arr_Size\n        Q(i,j)=round((L)+(i+j).*Para); \n    end;\nend;\n\n\n\n%----------Using Arihtmetic Decoding for extract original data.....\n[Arr]=Arith_Decode(Code_Arr,Arr_H1,Arr_H2); % Low-Freqeuncy Decoding...\n\n\n% High-Frequency Decoding......................................\nif (Code_Data1==0)\n  Data1(1:S_(1)*S_(2))=0;\nelse\n  [Data1]=Arith_Decode(Code_Data1,Data1_H1,Data1_H2); \nend;\n\nif (Code_Data2==0)\n Data2(1:S_(1)*S_(2))=0;\nelse\n [Data2]=Arith_Decode(Code_Data2,Data2_H1,Data2_H2);\nend;\n\nif (Code_Data3==0)\n  Data3(1:S_(1)*S_(2))=0;\nelse\n  [Data3]=Arith_Decode(Code_Data3,Data3_H1,Data3_H2);\nend;\n%-------------------------------------------------------------------------\n\n\n%Retrun \"SAVE_\" matrix from one-dimensional array \"Arr\"\nPOS=1;\nSAVE_(1:S_2(1),1:S_2(2))=0;\nsizeofArr=size(Arr);\nfor j=1:S_2(2)\n  if (POS<=sizeofArr(2)) % to be ensure the postions is not exceeding \n    for i=1:S_2(1) \n      if (POS<=sizeofArr(2)) % to be ensure again not exceeding\n        SAVE_(i,j)=Arr(POS);\n      end;\n      POS=POS+1;\n    end;\n  end;\nend;\n\n\n% Return \"DC_Values\" to matrix \"SAVE_\"..... \nSAVE_(1:S_2(1),1)=DC_Values(1:S_2(1));\n\n\n% Deocde - HH2\n% Return all original data from array \nk=1;\n\nfor j=1:S_(2)\n    for i=1:S_(1)\n        HH2(i,j)=Data3(k);\n        k=k+1;\n    end;\nend;\n%-----------------------------------------------------------------------\n% Decode HL2\n% Return all original data from array \nk=1;\nfor j=1:S_(2)\n    for i=1:S_(1)\n        HL2(i,j)=Data2(k);\n        k=k+1;\n    end;\nend;\n%-----------------------------------------------------------------------\n% Decode LH2\n% Return all original data from array \nk=1;\nfor j=1:S_(2)\n    for i=1:S_(1)\n        LH2(i,j)=Data1(k);\n        k=k+1;\n    end;\nend;\n\n\n\n\n%------------------- Reconstruct \"LL2\" from matrix \"SAVE_\"\nL=1;i=1;\nwhile (i<=S_(1))\n    j=1;\n    while(j<=S_(2))\n        Z=1;\n        for k1=1:Arr_Size \n            for k2=1:Arr_Size \n                T(k1,k2)=SAVE_(L,Z); \n                Z=Z+1; \n            end; \n        end;\n        L=L+1;\n        %------Apply inverse Quantization and inverse Walsh Transform------\n        T=T.*Q;\n        X=Walsh2D_Transform(T,Arr_Size,'i');\n        D(i:i+Arr_Size-1,j:j+Arr_Size-1)=X(1:Arr_Size,1:Arr_Size);\n        j=j+Arr_Size;\n    end;\n    i=i+Arr_Size;\nend;\n%-------------------------------------------------------------------------\n\n\n\n%Adjustment for D matrix to be same size alike \"LH2\" or others\nRELL(1:S_(1),1:S_(2))=D(1:S_(1),1:S_(2));\n%RELL=RELL.*1\n% Apply inverse Quantization for each sub-band (just high-Freqeuncy)\nLH2=round(LH2.*(M*F2)); HL2=round(HL2.*(M.*F2)); HH2=round(HH2.*(M.*F2));\n\n% Inverse -Wavelet Transform Stage-1\nS_=size(LH2); LL2=0;\nLL2(1:S_(1),1:S_(2))=RELL(1:S_(1),1:S_(2));\nL1=idwt2(LL2,LH2,HL2,HH2,wave_name);\nL1=L1*Para;\n% Inverse -Wavelet Transform Stage-2\nS_=size(L1);\nHL(1:S_(1),1:S_(2))=0; % all main sub-bands are zeros\n\n%L=0;\n%L(1:S_(1),1:S_(2))=L1(1:S_(1),1:S_(2));\n\nIm=idwt2(L1,HL,HL,HL,wave_name);% Decoded image \nIm=uint8(Im);\n'Decompression ..OK'\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/36335-walsh-and-wavelet-transform-for-colorgray-image-compression/WWT/Walsh_DWT_Decoding.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5779791804339336}}
{"text": "function [w, infos] = sag(problem, in_options)\n% Stochastic average descent (SAG) algorithm.\n%\n% Inputs:\n%       problem     function (cost/grad/hess)\n%       in_options  options\n% Output:\n%       w           solution of w\n%       infos       information\n%\n% References:\n%       N. L. Roux, M. Schmidt, and F. R. Bach, \n%       \"A stochastic gradient method with an exponential convergence rate for finite training sets,\"\n%       NIPS, 2012.\n%    \n% This file is part of SGDLibrary.\n%\n% Created by H.Kasai on Feb. 15, 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    % set local options \n    local_options.sub_mode = 'SAG';\n    \n    % merge options\n    options = mergeOptions(get_default_options(d), local_options);   \n    options = mergeOptions(options, in_options);      \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    % prepare an array of gradients, and a valiable of average gradient\n    grad_array = zeros(d, num_of_bachces);\n    grad_ave = mean(grad_array, 2);\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    % display infos\n    if options.verbose > 0\n        fprintf('%s: Epoch = %03d, cost = %.16e, optgap = %.4e\\n', options.sub_mode, epoch, f_val, optgap);\n    end      \n\n    % set start time\n    start_time = tic();\n    \n    % permute samples (ToDo)\n    perm_idx = 1:n;     \n\n    % main loop\n    while (optgap > options.tol_optgap) && (epoch < options.max_epoch)\n\n        for j = 1 : num_of_bachces\n            \n            % update step-size\n            step = options.stepsizefun(total_iter, options);\n            \n            % calculate gradient\n            start_index = (j-1) * options.batch_size + 1;\n            indice_j = perm_idx(start_index:start_index+options.batch_size-1);\n            grad = problem.grad(w, indice_j);\n            \n            % update average gradient\n            if strcmp(options.sub_mode, 'SAG')\n                grad_ave = grad_ave + (grad - grad_array(:, j)) / num_of_bachces;\n            else % SAGA\n                grad_ave = grad_ave + (grad - grad_array(:, j));                \n            end\n            % replace with new grad\n            grad_array(:, j) = grad;  \n            \n            % update w\n            w = w - step * grad_ave;\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 + num_of_bachces * options.batch_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 options.verbose > 0\n            fprintf('%s: Epoch = %03d, cost = %.16e, optgap = %.4e\\n', options.sub_mode, epoch, f_val, optgap);\n        end\n    end\n    \n    if optgap < options.tol_optgap\n        fprintf('Optimality gap tolerance reached: tol_optgap = %g\\n', options.tol_optgap);\n    elseif epoch == options.max_epoch\n        fprintf('Max epoch reached: max_epochr = %g\\n', options.max_epoch);\n    end    \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/sgd_solver/sag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5779468784169327}}
{"text": "function res = isign(x)\n%ISIGN        Interval sign, internal function for slope abs\n%\n\n%sign of interval array:\n%  +1      for x>=0\n%  -1      for x<=0\n%  [-1,1]  for 0 in x\n\n% written  12/06/98     S.M. Rump\n% modified 12/27/02     S.M. Rump  resinf,ressup changed to type double: fix of Matlab 6.5 discrepancy to 6.0\n%\n\n  xinf = inf(x);\n  xsup = sup(x);\n  resinf = double( xinf>=0 );\n  resinf(xsup<=0) = -1;\n  ressup = resinf;\n  index = ( xinf<0 ) & ( xsup>0 );\n  if any(index(:))\n    resinf(index) = -1;\n    ressup(index) = 1;\n  end\n  res = infsup(resinf,ressup);\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/slope/@slope/private/isign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5779468662791672}}
{"text": "%% stochasticMicrostructure\n% Below is a demonstration of the features of the |stochasticMicrostructure| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[F,V,C]=stochasticMicrostructure(inputStruct);|\n\n%% Description\n% This function generates Stochastic Bicontinuous Microstructures\n%\n% Input structure and default values:\n%\n%   inputStruct.L=1; % characteristic length\n%   inputStruct.Ns=80; % number of sampling points\n%   inputStruct.Nw=120; % number of waves\n%   inputStruct.q0=55; % wave number\n%   inputStruct.relD=0.5; % relative density\n%   inputStruct.anisotropyFactors=[1 1 1]; %Anisotropy factors\n%   inputStruct.isocap=1; %Option to cap the isosurface\n%\n% Based on: Soyarslan et al. \"3D stochastic bicontinuous\n% microstructures: Generation, topology and elasticity\"\n% https://doi.org/10.1016/j.actamat.2018.01.005 \n%\n% Original author: Sebastien Callens, September 2020\n\n%% Examples\n\n%%\n% Plot settings\ncMap=parula(250);\nfaceAlpha1=1;\nfaceAlpha2=0.5;\nedgeColor1='none';\nedgeColor2='none';\nfontSize=15; \n\n%% Example 1\ninputStruct.L=1; % characteristic length\ninputStruct.Ns=75; % number of sampling points\ninputStruct.Nw=500; % number of waves\ninputStruct.q0=55; % wave number\ninputStruct.relD=0.55; % relative density\ninputStruct.anisotropyFactors=[1 1 1]; %Anisotropy factors\ninputStruct.isocap=1; %Option to cap the isosurface\n\n%% \n% Create stochastic structure\n\n[F,V,C]=stochasticMicrostructure(inputStruct);\n\n%%\n% Using grouping to keep only largest group\ngroupOptStruct.outputType='label';\n[G,~,groupSize]=tesgroup(F,groupOptStruct); %Group connected faces\n[~,indKeep]=max(groupSize); %Index of largest group\n\n%Keep only largest group\nF=F(G==indKeep,:); %Trim faces\nC=C(G==indKeep,:); %Trim color data \n[F,V]=patchCleanUnused(F,V); %Remove unused nodes\n\n%%\n% Visualize surface\n\ncFigure; \ngpatch(F,V,C,'none');\naxisGeom; camlight headlight; \ncolormap gjet; icolorbar;\ngdrawnow;\n\n%% \n%\n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_stochasticMicrostructure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5779239783461694}}
{"text": "function ei_values_test ( )\n\n%*****************************************************************************80\n%\n%% EI_VALUES_TEST demonstrates the use of EI_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, 'EI_VALUES_TEST:\\n' );\n  fprintf ( 1, '  EI_VALUES stores values of\\n' );\n  fprintf ( 1, '  the exponential integral function EI(X).\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '      X          EI(X)\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x, fx ] = ei_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/ei_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.5779239765422713}}
{"text": "%GETRECTSUBPIX  Retrieves a pixel rectangle from an image with sub-pixel accuracy\n%\n%     dst = cv.getRectSubPix(src, patchSize, center)\n%     dst = cv.getRectSubPix(..., 'OptionName',optionValue, ...)\n%\n% ## Input\n% * __src__ Source image, 8-bit integer or 32-bit floating-point, 1- or\n%   3-channels.\n% * __patchSize__ Size of the extracted patch `[w,h]`.\n% * __center__ Floating-point coordinates of the center of the extracted\n%   rectangle within the source image. The center `[x,y]` must be inside the\n%   image.\n%\n% ## Output\n% * __dst__ Extracted patch that has the size `PatchSize`, the same number of\n%   channels as `src`, and the specified type in `PatchType`.\n%\n% ## Options\n% * __PatchType__ Depth of the extracted pixels. By default (-1), they have\n%   the same depth as `src`. Supports either `uint8` or `single`.\n%\n% The function cv.getRectSubPix extracts pixels from `src`:\n%\n%     dst(x,y) = src(x + center(1) - (size(dst,2)-1)*0.5,\n%                    y + center(2) - (size(dst,1)-1)*0.5)\n%\n% where the values of the pixels at non-integer coordinates are retrieved\n% using bilinear interpolation. Every channel of multi-channel images is\n% processed independently. Also the image should be a single channel or three\n% channel image. While the center of the rectangle must be inside the image,\n% parts of the rectangle may be outside. In this case, the pixel values\n% outside of the image are extrapolated.\n%\n% See also: cv.Rect.crop, cv.warpAffine, cv.warpPerspective\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/getRectSubPix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.5779239747383733}}
{"text": "function stats = rmanova2(data,alpha,doplot,ttst)\n%\n%Repeated-measures two-way ANOVA\n%\n% :Usage:\n% ::\n%\n%     stats = rmanova2(data,[alpha],[doplot],[ttst]);\n%\n% :Inputs:\n%\n%   **data:**\n%        can be one of two formats:\n%        1. Cell array - each row represents a level of factor 1, and\n%           each column represents a level of factor 2. Each cell contains a\n%           vector of values of the dependent variable for each subject.\n%        2. Matrix - each row represents a trial, with the following\n%           columns:\n%             - column1 - dependent variable\n%             - column2 - grouping variable for subject\n%             - column3 - grouping variable for factor 1\n%             - column4 - grouping variable for factor 2\n%\n%   **alpha:**\n%        (optional) p-value threshold (default: 0.05)\n%\n%   **doplot:**\n%        (optional) if 1, will produce a line plot.  \n%                       Works only for cell input data (default: 1)\n%\n%   **ttst:**\n%        (optional) if 1, will perform pairwise t-tests (default: 0)\n%\n% ..\n%    Aaron Schurger (2005.02.04)\n%    Derived from Keppel & Wickens (2004) \"Design and Analysis\" ch. 18\n%    Modified by Sam Gershman (2006.11.16)\n% ..\n\nif nargin < 2; alpha = 0.05; doplot = 0; ttst = 0; end\nif nargin < 3; doplot = 1;  ttst = 0; end\nif nargin < 4; ttst = 0; end\n\nif iscell(data);\n    Y = []; S = []; F1 = []; F2 = [];\n    [m n] = size(data);\n    for i = 1:m;\n        for j = 1:n;\n            Y = cat(1,Y,data{i,j});\n            nsubs = length(data{i,j});\n            S = cat(2,S,1:nsubs);\n            F1 = cat(1,F1,zeros(nsubs,1)+i);\n            F2 = cat(1,F2,zeros(nsubs,1)+j);\n        end\n    end\n    S = S';\nelse\n    Y = data(:,1);\n    S = data(:,2);\n    F1 = data(:,3); F2 = data(:,4);\n    clear data\n    su = unique(S); f1u = unique(F1); f2u = unique(F2);\n    for a = 1:length(f1u);\n        for b = 1:length(f2u);\n            ii = intersect(find(F1==f1u(a)),find(F2==f2u(b)));\n            d = [Y(ii) S(ii)];\n            d = sortrows(d,2);\n            data{a,b} = d(:,1);\n        end\n    end\nend\n\nF1_lvls = unique(F1);\nF2_lvls = unique(F2);\nSubjs = unique(S);\n\na = length(F1_lvls); % # of levels in factor 1\nb = length(F2_lvls); % # of levels in factor 2\nn = length(Subjs); % # of subjects\n\nINDS = cell(a,b,n); % this will hold arrays of indices\nCELLS = cell(a,b,n); % this will hold the data for each subject X condition\nMEANS = zeros(a,b,n); % this will hold the means for each subj X condition\n\n% Calculate means for each subject X condition.\n% Keep data in CELLS, because in future we may want to allow options for\n% how to compute the means (e.g. leaving out outliers > 3stdev, etc...).\nfor i=1:a % F1\n    for j=1:b % F2\n        for k=1:n % Subjs\n            INDS{i,j,k} = find(F1==F1_lvls(i) & F2==F2_lvls(j) & S==Subjs(k));\n            CELLS{i,j,k} = Y(INDS{i,j,k});\n            MEANS(i,j,k) = mean(CELLS{i,j,k});\n        end\n    end\nend\n\n% make tables (see table 18.1, p. 402)\nAB = reshape(sum(MEANS,3),a,b); % across subjects\nAS = reshape(sum(MEANS,2),a,n); % across factor 2\nBS = reshape(sum(MEANS,1),b,n); % across factor 1\n\nA = sum(AB,2); % sum across columns, so result is ax1 column vector\nB = sum(AB,1); % sum across rows, so result is 1xb row vector\nS = sum(AS,1); % sum across columns, so result is 1xs row vector\nT = sum(sum(A)); % could sum either A or B or S, choice is arbitrary\n\n% degrees of freedom\ndfA = a-1;\ndfB = b-1;\ndfAB = (a-1)*(b-1);\ndfS = n-1;\ndfAS = (a-1)*(n-1);\ndfBS = (b-1)*(n-1);\ndfABS = (a-1)*(b-1)*(n-1);\n\n% bracket terms (expected value)\nexpA = sum(A.^2)./(b*n);\nexpB = sum(B.^2)./(a*n);\nexpAB = sum(sum(AB.^2))./n;\nexpS = sum(S.^2)./(a*b);\nexpAS = sum(sum(AS.^2))./b;\nexpBS = sum(sum(BS.^2))./a;\nexpY = sum(Y.^2);\nexpT = T^2 / (a*b*n);\n\n% sums of squares\nssA = expA - expT;\nssB = expB - expT;\nssAB = expAB - expA - expB + expT;\nssS = expS - expT;\nssAS = expAS - expA - expS + expT;\nssBS = expBS - expB - expS + expT;\nssABS = expY - expAB - expAS - expBS + expA + expB + expS - expT;\nssTot = expY - expT;\n\n% mean squares\nmsA = ssA / dfA;\nmsB = ssB / dfB;\nmsAB = ssAB / dfAB;\nmsS = ssS / dfS;\nmsAS = ssAS / dfAS;\nmsBS = ssBS / dfBS;\nmsABS = ssABS / dfABS;\n\n% f statistic\nfA = msA / msAS;\nfB = msB / msBS;\nfAB = msAB / msABS;\n\n% p values\npA = 1-fcdf(fA,dfA,dfAS);\npB = 1-fcdf(fB,dfB,dfBS);\npAB = 1-fcdf(fAB,dfAB,dfABS);\n\n% return values\n stats.SS1 = ssA;\n stats.df1 = dfA;\n stats.MS1 = msA;\n stats.F1 = fA;\n stats.P1 = pA;\n stats.SS2 = ssB;\n stats.df2 = dfB;\n stats.MS2 = msB;\n stats.F2 = fB;\n stats.P2 = pB;\n stats.SS12 = ssAB;\n stats.df12 = dfAB;\n stats.MS12 = msAB;\n stats.F12 = fAB;\n stats.P12 = pAB;\n \n stats.alpha = alpha;\n \n %decision rule\nif stats.P1 < alpha; stats.significant1 = 'Yes'; else; stats.significant1 = 'No'; end;\nif stats.P2 < alpha; stats.significant2 = 'Yes'; else; stats.significant2 = 'No'; end;\nif stats.P12 < alpha; stats.significant12 = 'Yes'; else; stats.significant12 = 'No'; end;\n\n%make line plots\nif doplot\n    anova_line_plot(data);\n    \n%     [m n] = size(data); plotcounter = 0;\n%     figure;\n%     for i = 1:m;\n%         for j = 1:n;\n%             plotcounter = plotcounter + 1;\n%             subplot(m,n,plotcounter);\n%             boxplot(data{i,j});\n%             xlabel([num2str(i),',',num2str(j)]);\n%             set(gca,'XTickLabel',[]);\n%         end\n%     end\nend\n\n%pairwise t-tests\nif ttst;\n    disp('Performing post-hoc t-tests...');\n    tcounter = 0; a = 0; b = 0;\n    [m n] = size(data);\n    for t1 = 1:m;\n        for t2 = 1:n;\n            a = a + 1; b = 0;\n            for t3 = 1:m;\n                for t4 = 1:n;\n                    b = b + 1;\n                    if b > a;\n                        tcounter = tcounter + 1;\n                        [h,p,ci,stat] = ttest(data{t1,t2},data{t3,t4});\n                        stats.ttests(tcounter).P = p;\n                        stats.ttests(tcounter).comparison = [num2str(t1),',',num2str(t2),' > ',num2str(t3),',',num2str(t4)];\n                        stats.ttests(tcounter).means = [mean(data{t1,t2}) mean(data{t3,t4})];\n                        stats.ttests(tcounter).ci = ci';\n                    end\n                end\n            end\n        end\n    end\nend\n\nend\n  \n  \nfunction anova_line_plot(anova_dat)\n    \n    if ~iscell(anova_dat)\n        error('For line plots, enter cells rather than matrix input!');\n    end\n  \nfor i = 1:size(anova_dat, 1)\nfor j = 1:size(anova_dat, 2)\nlinedat(i, j) = nanmean(anova_dat{i, j});\nlineste(i, j) = ste(anova_dat{i, j});\nend\nend\n\n% Transpose so F2 is on X-axis, F1 is lines\nlinedat = linedat';\nlineste = lineste';\n\ncreate_figure('Lines');\n\nplot(linedat, 'o-', 'LineWidth', 3, 'MarkerSize', 12, 'MarkerFaceColor', [.5 .5 .5])\n\nset(gca, 'XLim', [.5 size(anova_dat, 2)+.5], 'XTick', [1:size(anova_dat, 2)]); xlabel('Factor 2');\n\nfor j = 1:size(anova_dat, 2), f1names{j} = ['F1: Level ' num2str(j)]; end\n\nlegend(f1names)\n\nend\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/rmanova2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5779239618663646}}
{"text": "\n% Show basic use of spm_mlm_bayes\n\nclear all\nclose all\n\nN=100;\nd=2;\np=3;\n\ny=randn(N,d);\nx=randn(N,p);\nverbose=1;\n\nmlm = spm_mlm_bayes (y,x,'input',verbose);\n\nfigure\nimagesc(mlm.wmean);\ncolorbar\nylabel('Inputs');\nxlabel('Outputs');\ncolormap(gray);\n\n\ndisp(sprintf('Model evidence = %1.2f', mlm.fm));", "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_basic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.5778973644445755}}
{"text": "clear all; clc; close all;\n\nOpenBMI('C:\\Users\\CVPR\\Desktop\\Open_Github') % Edit the variable BMI if necessary\nglobal BMI;\nBMI.EEG_DIR=['G:\\data2'];\n\n%% DATA LOAD MODULE\nfile=fullfile(BMI.EEG_DIR, '\\2016_08_05_hkkim_training');\nmarker= {'1','right';'2','left';'3','foot';'4','rest'};\n[EEG.data, EEG.marker, EEG.info]=Load_EEG(file,{'device','brainVision';'marker', marker;'fs', 500});\n\nfield={'x','t','fs','y_dec','y_logic','y_class','class', 'chan'};\nCNT=opt_eegStruct({EEG.data, EEG.marker, EEG.info}, field);\nCNT=prep_selectClass(CNT,{'class',{'right', 'rest'}});\n\nCNT2 = prep_laplacian(CNT, {'Channel', {'C3', 'Cz', 'C4'}})\n \n%% CROSS-VALIDATION MODULE\nCV.var.band=[7 20];\nCV.var.interval=[750 3500];\nCV.prep={ % commoly applied to training and test data before data split\n    'CNT=prep_filter(CNT, {\"frequency\", band})'\n    'SMT=prep_segmentation(CNT, {\"interval\", interval})'\n    };\nCV.train={\n    '[SMT, CSP_W, CSP_D]=func_csp(SMT,{\"nPatterns\", [3]})'\n    'FT=func_featureExtraction(SMT, {\"feature\",\"logvar\"})'\n    '[CF_PARAM]=func_train(FT,{\"classifier\",\"LDA\"})'\n    };\nCV.test={\n    'SMT=func_projection(SMT, CSP_W)'\n    'FT=func_featureExtraction(SMT, {\"feature\",\"logvar\"})'\n    '[cf_out]=func_predict(FT, CF_PARAM)'\n    };\nCV.option={\n'KFold','7'\n% 'leaveout'\n};\n\n[loss]=eval_crossValidation(CNT, CV); % input : eeg, or eeg_epo\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/Examples/old/example_crossValidation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5778973525572979}}
{"text": "function [params, names] = ardKernExtractParam(kern)\n\n% ARDKERNEXTRACTPARAM Extract parameters from the ARD kernel structure.\n% FORMAT\n% DESC Extract parameters from the pre-built RBF and linear ARD\n% kernel structure into a vector of parameters for optimisation.\n% ARG kern : the kernel structure containing the parameters to be\n% extracted.\n% RETURN param : vector of parameters extracted from the kernel. If\n% the field 'transforms' is not empty in the kernel matrix, the\n% parameters will be transformed before optimisation (for example\n% positive only parameters could be logged before being returned).\n%\n% FORMAT\n% DESC Extract parameters and names of parameters from the\n% pre-built RBF and linear ARD kernel structure.\n% ARG kern : the kernel structure containing the parameters to be\n% extracted.\n% RETURN param : vector of parameters extracted from the kernel. If\n% the field 'transforms' is not empty in the kernel matrix, the\n% parameters will be transformed before optimisation (for example\n% positive only parameters could be logged before being returned).\n% RETURN names : celly array of strings containing parameter names.\n%\n% SEEALSO ardKernParamInit, ardKernExpandParam, kernExtractParam, scg, conjgrad\n%\n% COPYRIGHT : Neil D. Lawrence, 2004\n%\n% KERN\n\n\nparams = [kern.inverseWidth kern.rbfVariance ...\n          kern.biasVariance kern.whiteVariance ...\n          kern.linearVariance kern.inputScales];\nif nargout > 1\n  names{1} = 'ard inverse width';\n  names{2} = 'ard rbf variance';\n  names{3} = 'ard bias variance';\n  names{4} = 'ard white variance';\n  names{5} = 'ard linear variance';\n  for i = 1:length(kern.inputScales)\n    names{5+i} = ['ard input scale ' num2str(i)];\n  end\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/ardKernExtractParam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.577894017641878}}
{"text": "function [lh_AR, varx] = ARMLfit(rcs,ng,xg,rc0,lag_max)\n\n% The conditional-likelihood fit.\n%\n%   rcs = tan(.5*pi*rc)\n%   In this way, the reflection coefficient [-1,+1] is mapped to\n%   [-Inf,+Inf], allowing the use of unconstrained optimization.\n\n%   S. de Waele, August 2001.\n\nrc = 2/pi*atan(rcs);\nif any(~isreal(rc)),lh_AR = +Inf; return; end \nnseg = length(xg);\nnpre = length(rcs)+length(rc0);\na = rc2arset([1 rc0 rc]);\n%cor = par2cor(a,lag_max+1);\ncor = arma2cor(a,1,lag_max);\n\nsum_s = 0;     %The squared error in the exponent of the normal distribution\n     \t\t   %without varx and the factor -.5;\nsum_lnd = 0;   %contribution of the log of the determinant without varx and the factor .5;\nnobs_used = 0;\n\nfor seg = 1:nseg,\n    nc = ng{seg};\n    if any(floor(nc)~=nc), error('Times must contain only integers.'), end\n    xc = xg{seg};\n    nobsc = length(nc);\n    nobs_used = nobs_used + nobsc;\n    \n    obs_start = 1;\n    if obs_start == 1,\n        obs = 1;\n        sum_s = sum_s+xc(1)^2;\n        sum_lnd= sum_lnd+log(1);\n    end\n    for obs = max(2,obs_start):nobsc\n        nprev_a = min(obs-1,lag_max); %nprev_a = available previous observations\n        it=find(nc(obs)-nc(obs-1:-1:obs-nprev_a)<lag_max+1);\n        nprev_a=length(it);\n        if nprev_a\n            n1 = nc(obs:-1:obs-nprev_a)*ones(1,nprev_a+1);\n            n2 = ones(nprev_a+1,1)*nc(obs:-1:obs-nprev_a)';\n            lags = abs(n1-n2);\n            Rn = cor(1+lags);   \n            %Notations as in Random signals, K.S. Shanmugan and A.M. Breipohl, p.51.\n            x1 = xc(obs);\n            x2 = xc(obs-1:-1:obs-nprev_a);\n            Rn11 = 1;\n            Rn12 = Rn(1,2:end);\n            Rn21 = Rn(2:end,1);\n            Rn22 = Rn(2:end,2:end);\n            muc = Rn12*(Rn22\\x2);       % = Conditional mean of x1 given x2\n            Rnc = 1-Rn12*(Rn22\\Rn21);   % = scaled Conditional variance of x1.\n            sum_s = sum_s + (x1-muc)^2/Rnc;\n            sum_lnd = sum_lnd + log(Rnc);\n        else\n            sum_s = sum_s+xc(obs)^2;\n            sum_lnd= sum_lnd+log(1);\n        end      \n    end  %for obs = \nend      %for seg = 1:nseg\n\nvarx = sum_s/nobs_used;\n\nlh_AR = -nobs_used/2*log(varx)-sum_lnd/2 - sum_s/2/varx;\n\n%Turning the Likelihood in an estimate of the K-L discrepancy:\nlh_AR = -2*lh_AR;\n\nif isnan(lh_AR), lh_AR = +Inf; 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/3680-automatic-spectral-analysis/AutomaticSpectra/SegmentsMissing/ARMLfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.577894017641878}}
{"text": "classdef MaF8 < PROBLEM\n% <multi/many> <real>\n% MP-DMP\n\n%------------------------------- Reference --------------------------------\n% R. Cheng, M. Li, Y. Tian, X. Zhang, S. Yang, Y. Jin, and X. Yao, A\n% benchmark test suite for evolutionary many-objective optimization,\n% Complex & Intelligent Systems, 2017, 3(1): 67-81.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    properties(Access = private)\n        Points; % Vertexes\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            % Parameter setting\n            if isempty(obj.M); obj.M = 10; end\n            obj.M        = max(obj.M,3);\n            obj.D        = 2;\n            obj.lower    = [-10000,-10000];\n            obj.upper    = [10000,10000];\n            obj.encoding = ones(1,obj.D);\n            % Generate vertexes\n            obj.Points  = [];\n            [thera,rho] = cart2pol(0,1);\n            [obj.Points(:,1),obj.Points(:,2)] = pol2cart(thera-(1:obj.M)*2*pi/obj.M,rho);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            PopObj = pdist2(PopDec,obj.Points);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            [X,Y] = ndgrid(linspace(-1,1,ceil(sqrt(N))));\n            ND    = inpolygon(X(:),Y(:),obj.Points(:,1),obj.Points(:,2));\n            R     = pdist2([X(ND),Y(ND)],obj.Points);\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            if obj.M == 3\n                [X,Y]    = ndgrid(linspace(-1,1,40));\n                R        = pdist2([X(:),Y(:)],obj.Points);\n                ND       = inpolygon(X(:),Y(:),obj.Points(:,1),obj.Points(:,2));\n                R(~ND,:) = nan;\n                R = {reshape(R(:,1),size(X)),reshape(R(:,2),size(X)),reshape(R(:,3),size(X))};\n            else\n                R = [];\n            end\n        end\n        %% Display a population in the decision space\n        function DrawDec(obj,Population)\n            Draw(obj.Points([1:end,1],:),'-k','LineWidth',1.5,{'\\it x\\rm_1','\\it x\\rm_2',[]});\n            Draw(obj.Points,'o','MarkerSize',6,'Marker','o','Markerfacecolor',[1 1 1],'Markeredgecolor',[.4 .4 .4]);\n            Draw(Population.decs);\n        end\n    end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/MaF/MaF8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5778940176418779}}
{"text": "function [nstate] = tapas_sampler_dlinear_cv_gibbs_node(data, model, ...\n    inference, state, node)\n%% Samples from a linear model with variance using a gibbs step and a \n% leave one out approach.\n%\n% Input \n%\n% Output\n%\n\n% aponteeduardo@gmail.com\n% copyright (C) 2016\n%\n\nnstate = state;\n\n[np, nc] = size(state.graph{node - 1}.y);\nnm = numel(state.graph{node}.y{1}.mu);\n% Compute the means\n\nmu = cell(1, nc);\n\n% Initilize at the prior\n\ny = state.graph{node + 1}.y;\n\n% First store the values somewhere\n% np + 1 Number of subjects plus prior\nvalues = zeros(size(y{1}.mu, 1), np + 1);\nvariance = cell(nc, 1);\nfor i = 1:nc\n    values(:, 1) = y{i}.mu;\n    for j = 1:np\n        values(:, j + 1)  = state.graph{node - 1}.y{j, i};\n    end\n    y{i}.mu = mean(values, 2);\n    % No bessel correction\n    variance{i} = var(values, 1, 2);\nend\n\nfor i = 1:nc\n    % Priors \n    alpha = state.graph{node + 1}.y{i}.alpha;\n    beta = state.graph{node + 1}.y{i}.beta;\n    % Sample variance for each of the components\n    % The one degree of freedom comes from the prior\n    pe = gamrnd(alpha + np/2, 1./(beta + ((np + 1)/2.0) .* variance{i}));\n    nstate.graph{node}.y{i}.pe = pe;\n    % Update the mean\n    nstate.graph{node}.y{i}.mu = y{i}.mu + ...\n        (1./sqrt((np + 1) * pe) .* randn(nm, 1));\nend\n\nnstate.llh{node} = model.graph{node}.llh(nstate.graph{node}, ...\n    nstate.graph{node + 1}, model.graph{node}.htheta);\n\nnstate.llh{node - 1} = model.graph{node - 1}.llh(...\n    nstate.graph{node - 1}, nstate.graph{node}, model.graph{node - 1}.htheta);\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/tools/ti/linear/tapas_sampler_dlinear_cv_gibbs_node.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5778940032649752}}
{"text": "function out = SY_SlidingWindow(y,windowStat,acrossWinStat,numSeg,incMove)\n% SY_SlidingWindow  Sliding window measures of stationarity.\n%\n% This function is based on sliding a window along the time series, measuring\n% some quantity in each window, and outputting some summary of this set of local\n% estimates of that quantity.\n%\n% Another way of saying it: calculate 'windowStat' in each window, and computes\n% 'acrossWinStat' for the set of statistics calculated in each window.\n%\n%---INPUTS:\n%\n% y, the input time series\n%\n% windowStat, the measure to calculate in each window:\n%               (i) 'mean', mean\n%               (ii) 'std', standard deviation\n%               (iii) 'ent', distribution entropy\n%               (iv) 'mom3', skewness\n%               (v) 'mom4', kurtosis\n%               (vi) 'mom5', the fifth moment of the distribution\n%               (vii) 'lillie', the p-value for a Lilliefors Gaussianity test\n%               (viii) 'AC1', the lag-1 autocorrelation\n%               (ix) 'apen', Approximate Entropy, ApEn(1,0.2)\n%               (ix) 'sampen', Sample Entropy, SampEn(2,0.1)\n%\n% acrossWinStat, controls how the obtained sequence of local estimates is\n%                   compared (as a ratio to the full time series):\n%                       (i) 'std': standard deviation\n%                       (ii) 'ent' histogram entropy\n%                       (iii) 'apen': Approximate Entropy, ApEn(1,0.2)\n%                       (iii) 'sampen': Sample Entropy, SampEn(2,0.1)\n%\n% numSeg, the number of segments to divide the time series up into, thus\n%       controlling the window length\n%\n% incMove, the increment to move the window at each iteration, as 1/fraction of the\n%       window length (e.g., incMove = 2, means the window moves half the length of the\n%       window at each increment)\n%\n% NOTE: SY_SlidingWindow(y,'mean','std',X,1) is the same as StatAvX, computed as\n%                       SY_StatAv(y,'seg',X);\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% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,\n% <http://www.benfulcher.com>\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 <http://www.gnu.org/licenses/>.\n% ------------------------------------------------------------------------------\n\ndoPlot = false; % plot outputs\n\n% ------------------------------------------------------------------------------\n% Check Inputs\n% ------------------------------------------------------------------------------\n\nif nargin < 2 || isempty(windowStat)\n    windowStat = 'mean'; % measure within each window\nend\nif nargin < 3 || isempty(acrossWinStat)\n    acrossWinStat = 'std'; % measure across all windows\nend\nif nargin < 4 || isempty(numSeg)\n    numSeg = 5;\nend\nif nargin < 5 || isempty(incMove)\n    incMove = 2;\nend\n\n% ------------------------------------------------------------------------------\n\nwinLength = floor(length(y)/numSeg); % length of window\nif winLength==0\n    warning('Time-series of length %u is too short for %u windows',length(y),numSeg);\n    out = NaN;\n    return\nend\ninc = floor(winLength/incMove); % increment to move at each step\n% If increment rounded down to zero, prop it up:\nif inc == 0\n    inc = 1;\nend\n\nnumSteps = (floor((length(y)-winLength)/inc)+1);\nqs = zeros(numSteps,1);\n\n% Convert a step index (stepInd) to a range of indices corresponding to that window:\ngetWindow = @(stepInd) ((stepInd-1)*inc + 1:(stepInd-1)*inc + winLength);\n\nswitch windowStat\n    case 'mean' % Sliding window mean\n        for i = 1:numSteps\n            qs(i) = mean(y(getWindow(i)));\n        end\n    case 'std' % Sliding window std\n        for i = 1:numSteps\n            qs(i) = std(y(getWindow(i)));\n        end\n    case 'ent' % Sliding window distributional entropy\n        for i = 1:numSteps\n            qs(i) = EN_DistributionEntropy(y(getWindow(i)),'ks',[]);\n        end\n    case 'apen' % Sliding window ApEn\n        for i = 1:numSteps\n            qs(i) = EN_ApEn(y(getWindow(i)),1,0.2);\n        end\n    case 'sampen' % Sliding window SampEn\n        for i = 1:numSteps\n            sampEn_struct = EN_SampEn(y(getWindow(i)),1,0.1);\n            qs(i) = sampEn_struct.sampen1;\n        end\n    case 'mom3' % Third moment\n        for i = 1:numSteps\n            qs(i) = DN_Moments(y(getWindow(i)),3);\n        end\n    case 'mom4' % Fourth moment\n        for i = 1:numSteps\n            qs(i) = DN_Moments(y(getWindow(i)),4);\n        end\n    case 'mom5' % Fifth moment\n        for i = 1:numSteps\n            qs(i) = DN_Moments(y(getWindow(i)),5);\n        end\n    case 'lillie' % Lilliefors test\n        for i = 1:numSteps\n            qs(i) = HT_DistributionTest(y(getWindow(i)),'lillie','norm');\n        end\n    case 'AC1' % Lag-1 autocorrelation\n        for i = 1:numSteps\n            qs(i) = CO_AutoCorr(y(getWindow(i)),1,'Fourier');\n        end\n    otherwise\n        error('Unknown statistic ''%s''',windowStat)\nend\n\n% Check for all errors (e.g., short time series):\nif all(isnan(qs))\n    warning('These sliding window settings are not suitable for this time series');\n    out = NaN;\n    return\nend\n\n% ------------------------------------------------------------------------------\n% Plot\n% ------------------------------------------------------------------------------\nif doPlot\n    figure('color','w'); box('on');\n    plot(round(winLength/2):inc:(numSteps-1)*inc+round(winLength/2),qs,'r');\nend\n\n% ------------------------------------------------------------------------------\n% Compute the output statistic\n% ------------------------------------------------------------------------------\nswitch acrossWinStat\n    case 'std'\n        % normalized by std of full time series\n        out = std(qs)/std(y);\n    case 'apen'\n        out = EN_ApEn(qs,1,0.2); % ApEn of the sliding window measures\n    case 'sampen'\n        sampEn_struct = EN_SampEn(qs,2,0.15);\n        out = sampEn_struct.quadSampEn1;\n    case 'ent'\n        % get a load of statistics from kernel-smoothed distribution (inefficient since only one is used)\n        kssimpouts = DN_FitKernelSmooth(qs);\n        out = kssimpouts.entropy; % distributional entropy\n    otherwise\n        error('Unknown statistic: ''%s''.',acrossWinStat)\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/SY_SlidingWindow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5778939963997778}}
{"text": "        % Ciclu repetitiv pentru calcularea coeficientilor binomiali\nfor k=1:10\n    binom(k,1:k+1)=mfun('binomial',k,0:k);\nend\n        % Afisarea rezultatului\ndisp('Coeficientii binomiali')\ndisp(binom)", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8416-widely-used-programming-environments-in-electrical-engineering-matlab/12/Ex_12_17.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5778850263057914}}
{"text": "% This function is designed to determine whether a sphere collides with a\n% give triangle\n\nfunction [haveCollided] = CheckSphereTriangleIntersection(p,r,pa,pb,pc)\n\n% INpUT pcHEpcK\nassert(numel(p) == 3,'pcentroid must be a column vector [3x1]');\nassert(numel(r) == 1,'Radius must be a scalar');\nassert(numel(pa) == 3 && numel(pb) == 3 && numel(pc) == 3,...\n       'Vertex point must be a column vector [3x1]');\n\n% pcHEpcK pLpaNpaR SEppaRpaTION\npa = pa - p;\npb = pb - p;\npc = pc - p;\nrr = r^2;\nV = cross(pb-pa,pc-pa);\nd = dot(pa,V);\ne = dot(V,V);\nsep1 = d^2 > rr*e;\n% pcHEpcK VERTIpcES\naa = dot(pa,pa);\nab = dot(pa,pb);\nac = dot(pa,pc);\nbb = dot(pb,pb);\nbc = dot(pb,pc);\ncc = dot(pc,pc);\nsep2 = (aa > rr) & (ab > aa) & (ac > aa);\nsep3 = (bb > rr) & (ab > bb) & (bc > bb);\nsep4 = (cc > rr) & (ac > cc) & (bc > cc);\n% pcHEpcK TRIpaNGLE EDGES\npapb = pb - pa;\npbpc = pc - pb;\npcpa = pa - pc;\nd1 = ab - aa;\nd2 = bc - bb;\nd3 = ac - cc;\ne1 = dot(papb,papb);\ne2 = dot(pbpc,pbpc);\ne3 = dot(pcpa,pcpa);\nQ1 = pa*e1 - d1*papb;\nQ2 = pb*e2 - d2*pbpc;\nQ3 = pc*e3 - d3*pcpa;\nQpc = pc*e1 - Q1;\nQpa = pa*e2 - Q2;\nQpb = pb*e3 - Q3;\nsep5 = dot(Q1,Q1) > (rr*e1*e1) & dot(Q1,Qpc) > 0;\nsep6 = dot(Q2,Q2) > (rr*e2*e2) & dot(Q2,Qpa) > 0;\nsep7 = dot(Q3,Q3) > (rr*e3*e3) & dot(Q3,Qpb) > 0;\nisSeparated = sep1 || sep2 || sep3 || sep4 || sep5 || sep6 || sep7;\nhaveCollided = ~isSeparated;\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/CheckSphereTriangleIntersection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.577885022067231}}
{"text": "function p = dirichlet_logProb_fast(a, bar_p)\n\np = gammaln(sum(a)) - sum(gammaln(a)) + sum((a-1).*bar_p);\nK = length(a);\nflops(flops + (K+1)*flops_digamma + 3*K);\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/dirichlet_logProb_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5778850181820347}}
{"text": "close all; clear all;\n\n%% Setting of the problem\nglobal s\npde = fracLapdata6; \noption.theta = 0.3;\noption.estType = 'star';\noption.maxIt = 18;\noption.maxN = 5e4;\noption.solver = 'mg';\noption.tol = 1e-6;\n[node,elem] = squaremesh([-1,1,-1,1],0.5);\nbdFlag = setboundary(node,elem,'Dirichlet');\n\n% %% s = 0.2\n% s = 0.2;\n% afemfracLap(node,elem,pde,bdFlag,option);\n% \n% %% s = 0.4\n% s = 0.4;\n% afemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.6\ns = 0.6;\nafemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.8\ns = 0.8;\nafemfracLap(node,elem,pde,bdFlag,option);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fracLaplacian/afemratefracLapdistributioncircle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.577802726984106}}
{"text": "% TTEST_CELL - compute paired t-test. Allow fast computation of \n%                multiple t-test using matrix manipulation.\n%\n% Usage:\n%    >> [F df] = ttest_cell( { a b } );\n%    >> [F df] = ttest_cell(a, b);\n%\n% Inputs:\n%   a,b       = data consisting of PAIRED arrays to be compared. The last \n%               dimension of the data array is used to compute the t-test.\n% Outputs:\n%   T   - T-value\n%   df  - degree of freedom (array)\n%\n% Example:\n%   a = { rand(1,10) rand(1,10)+0.5 }\n%   [T df] = ttest_cell(a)\n%   signif = 1-tcdf(T, df(1))\n%\n%   % for comparison, the same using the Matlab t-test function\n%   [h p ci stats] = ttest(a{1}', b{1}');\n%   [ stats.tstat' p] \n%\n%   % fast computation (fMRI scanner volume 100x100x100 and 10 subjects in\n%   % two conditions). The computation itself takes 0.5 seconds instead of \n%   % half an hour using the standard approach (1000000 loops and Matlab \n%   % t-test function)\n%   a = rand(100,100,100,10); b = rand(100,100,100,10);\n%   [F df] = ttest_cell({ a b });\n%\n% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005\n%\n% Reference:\n%   Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill.\n\n% Copyright (C) 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 [tval, df] = ttest_cell(a,b)\n    \n    if nargin < 1\n        help ttest_cell;\n        return;\n    end\n    \n    if iscell(a), b = a{2}; a = a{1}; end\n    tmpdiff = a-b;\n    diff = mymean(tmpdiff,    myndims(a));\n    sd   = mystd( tmpdiff,[], myndims(a));\n    tval = diff./sd*sqrt(size(a, myndims(a)));\n    df   = size(a, myndims(a))-1;\n    \n    % check values againg Matlab statistics toolbox\n    %[h p ci stats] = ttest(a', b');\n    % [ tval stats.tstat' ]  \n    \nfunction val = myndims(a)\n    if ndims(a) > 2\n        val = ndims(a);\n    else\n        if size(a,1) == 1,\n            val = 2;\n        elseif size(a,2) == 1,\n            val = 1;\n        else\n            val = 2;\n        end\n    end; \n  \nfunction res = mymean( data, varargin) % deal with complex numbers\n    res = mean( data, varargin{:});\n    if ~isreal(data)\n        res = abs( res );\n    end\n\nfunction res = mystd( data, varargin) % deal with complex numbers\n    if ~isreal(data)\n        res = std( abs(data), varargin{:});\n    else\n        res = sqrt(sum( bsxfun(@minus, data, mean( data, varargin{2})).^2, varargin{2})/(size(data,varargin{2})-1)); % 8 percent speedup\n        %res = std( data, varargin{:});\n    end\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/statistics/ttest_cell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.577746085424994}}
{"text": "% test for hessian tensor\n\nn = 256;\nname = 'barb';\nM = load_image(name);\nM = rescale(crop(M,n));\n\noptions.order = 2;\nT = compute_hessian(M, options);\n\n[e1,e2,l1,l2] = perform_tensor_decomp(T);\nl1 = abs(l1); l2 = abs(l2);\nT = perform_tensor_recomp(e1,e2,l2,l1);\n\nsigma = 5;\nT = perform_blurring(T,sigma);\n\noptions.sub = 8;\nclf;\nplot_tensor_field(T, M, options);\nfigure;\nclf;\nplot_tensor_field_nb(T, M, options);", "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_diffc/tests/test_hessian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5777460790961159}}
{"text": "% @authors:     Fuxin Li\n% @contact:     ahumayun@cc.gatech.edu\n% @affiliation: Georgia Institute of Technology\n% @date:        Fall 2013 - Summer 2014\n\nfunction s_feat = compute_all_relevant_features( sp_seg, edge_graph )\n% somehow, all the rest are computed on a halfed image, while the last one\n% is on full image...\n    s_feat = zeros(max(sp_seg(:)), 6);\n%    sp_seg_rszd = imresize(sp_seg,0.5,'nearest');\n    [cent, bb, area, perim, secondorder] = superpix_regionprops(uint16(sp_seg));\n    bb = double(bb);\n    bb(:,1:2) = bb(:,1:2) - 0.5;\n    bb(:,3:4) = bb(:,3:4) + 0.5;\n    % Left and top both have -0.5 as per MATLAB convention\n    s_feat(:,1:2) = double(bb(:,1:2));\n    % Eccentricity is a bit tricky...\n    % Now the secondorder information is non-central, to get centralized\n    % moments we need to use (x - centx)^2 = x^2 - 2 x*centx + centx^2\n    % but \\sum x /N = centx, therefore we get (x-centx)^2 = secondorder_x - 2\n    % centx * centx * N + N * centx * centx = secondorder_x - N * centx *\n    % centx\n    %1/12 is the normalized second central moment of a pixel with unit length.\n    uxx = secondorder(:,1) ./ single(area) - cent(:,1).^2 + 1/12;\n    uyy = secondorder(:,2) ./ single(area) - cent(:,2).^2 + 1/12;\n    % for uxy, we compute (x - centx) (y-centy)  = xy - centx y - centy x -\n    % centx centy, using the same idea we can get that is xy - N centx\n    % centy\n    uxy = secondorder(:,3) ./ single(area) - cent(:,1) .* cent(:,2);\n    common = sqrt((uxx - uyy).^2 + 4*uxy.^2);\n    MajorAxisLength =  2*sqrt(2)*sqrt(uxx + uyy + common);\n    MinorAxisLength = 2*sqrt(2)*sqrt(uxx + uyy - common);\n    Eccentricity = 2*sqrt((MajorAxisLength/2).^2 - (MinorAxisLength/2).^2) ./ MajorAxisLength;\n    s_feat(:,3) = Eccentricity;\n    % Extent, area / bounding box area\n    s_feat(:,4) = single(area) ./ single((bb(:,4) - bb(:,2)) .* (bb(:,3) - bb(:,1)));\n    % Perimeter\n    s_feat(:,5) = perim;\n    s_feat(:,6) = sum(edge_graph,2);\n    % Left here commented for verification of correctness\n%     for i=1:max(sp_seg(:))\n% %          s = regionprops(sp_seg==i,'BoundingBox','Eccentricity','EquivDiameter','Extent','Perimeter');\n% %          s = s(1);\n% %          s_feat(i,1:5) = [s.BoundingBox(1) s.BoundingBox(2) s.Eccentricity s.Extent s.Perimeter];\n% %         % Inter-contour energy, change this just to superpixel boundary\n%         % energy\n%         all_bw = imdilate(sp_seg==i, ones(5,5)) & imdilate(~(sp_seg==i), ones(5,5));\n%         s_feat(i,6) = sum(pb_thin(all_bw));\n%     end\nend\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/rigor/rigor_src/utils/compute_all_relevant_features.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5777460757717654}}
{"text": "% DEMROBOTWIRELESS3 Wireless Robot data from University of Washington with dynamics and no back constraints.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'robotWireless';\nexperimentNo = 3;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('ftc');\n\nlatentDim = 2;\nd = size(Y, 2);\n\nmodel = fgplvmCreate(latentDim, d, Y, options);\n\n% Add dynamics model.\noptions = gpOptions('ftc');\noptions.kern = kernCreate(model.X, {'rbf', 'white'});\noptions.kern.comp{1}.inverseWidth = 0.2;\n% This gives signal to noise of 0.1:1e-3 or 100:1.\noptions.kern.comp{1}.variance = 0.1^2;\noptions.kern.comp{2}.variance = 1e-3^2;\nmodel = fgplvmAddDynamics(model, 'gp', options);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\ncapName = dataSetName;;\ncapName(1) = upper(capName(1));\nsave(['dem' capName num2str(experimentNo) '.mat'], 'model');\n\n\n\n% Load the results and display dynamically.\nfgplvmResultsDynamic(dataSetName, experimentNo, 'vector')\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demRobotWireless3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5777460652236355}}
{"text": "function ss=lpczz2ss(zz)\n%LPCZZ2SS Convert z-place poles to s-plane poles SS=(ZZ)\n%the s-plane is in units of Normalized Hz and so the imaginary part\n% of each ss() value is in the range +-0.5\n%\n% If you multiply ss by the sample frequency, a formant with\n% frequency f and bandwidth b will give an s-plane pole-pair\n% of approximately -b/2 +- j f\n\n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: lpczz2ss.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\nss=log(max(zz,1e-8))*0.5/pi;\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/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/lpczz2ss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5777460647761841}}
{"text": "function rhs_lucas_test ( )\n\n%*****************************************************************************80\n%\n%% RHS_LUCAS_TEST samples the right hand side at the initial time.\n%\n%  Location:\n%\n%    http://people.sc.fsu.edu/~jburkardt/m_src/navier_stokes_2d_exact/rhs_lucas_test.m\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    07 March 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  nu = 1.0;\n  rho = 1.0;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'RHS_LUCAS_TEST\\n' );\n  fprintf ( 1, '  Lucas Bystricky Flow\\n' );\n  fprintf ( 1, '  Sample the Navier-Stokes right hand sides\\n' );\n  fprintf ( 1, '  at the initial time T = 0, using the unit square.\\n' );\n  fprintf ( 1, '  Kinematic viscosity NU = %g\\n', nu );\n  fprintf ( 1, '  Fluid density RHO = %g\\n', rho );\n\n  n = 1000;\n  xy_lo = 0.0;\n  xy_hi = 1.0;\n  seed = 123456789;\n  [ x, seed ] = r8vec_uniform_ab ( n, xy_lo, xy_hi, seed );\n  [ y, seed ] = r8vec_uniform_ab ( n, xy_lo, xy_hi, seed );\n  t = 0.0;\n\n  [ f, g, h ] = rhs_lucas ( nu, rho, n, x, y, t );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '           Minimum       Maximum\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  F:  %14.6g  %14.6g\\n', min ( f ), max ( f ) );\n  fprintf ( 1, '  G:  %14.6g  %14.6g\\n', min ( g ), max ( g ) );\n  fprintf ( 1, '  H:  %14.6g  %14.6g\\n', min ( h ), max ( 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/navier_stokes_2d_exact/rhs_lucas_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.5776644026010067}}
{"text": "function normal_01_cdf_values_test ( )\n\n%*****************************************************************************80\n%\n%% NORMAL_01_CDF_VALUES_TEST demonstrates the use of NORMAL_01_CDF_VALUES.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 November 2005\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'NORMAL_01_CDF_VALUES_TEST:\\n' );\n  fprintf ( 1, '  NORMAL_01_CDF_VALUES stores values of\\n' );\n  fprintf ( 1, '  the Normal 01 Cumulative Density Function.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '      X                  CDF(X)\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x, fx ] = normal_01_cdf_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fprintf ( 1, '  %24.16f  %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/normal_01_cdf_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.577664398767059}}
{"text": "function quad_mesh_test05 ( )\n\n%*****************************************************************************80\n%\n%% QUAD_MESH_TEST05 tests BOUNDARY_EDGE_COUNT_EULER_Q4_MESH.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    24 February 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'QUAD_MESH_TEST05\\n' );\n  fprintf ( 1, '  BOUNDARY_EDGE_COUNT_EULER_Q4_MESH counts the\\n' );\n  fprintf ( 1, '    boundary edges using Euler''s formula.\\n' );\n\n  [ node_num, element_num, hole_num ] = example1_q4_mesh_size ( );\n\n  boundary_edge_num = boundary_edge_count_euler_q4_mesh ( node_num, ...\n    element_num, hole_num );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of boundary edges = %d\\n', boundary_edge_num );\n  fprintf ( 1, '  Correct number =           %d\\n', 22 );\n\n  return\nend\n", "meta": {"author": "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/quad_mesh_test05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.5776643887487427}}
{"text": "function phiFaceAverage = upwindMean1D(phi, u)\n% This function gets the value of the field variable phi defined\n% over the MeshStructure and calculates the upwind average on\n% the cell faces, based on the direction of the velocity vector for a uniform mesh.\n%\n% SYNOPSIS:\n%   phiFaceAverage = upwindMean1D(phi, u)\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 the velocity data\n% note: size(ux) = [1:m+1, 1:n] and size(uy) = [1:m, 1:n+1]\nux = u.xvalue;\n\n% check the size of the variable and the mesh dimension\nNx = phi.domain.dims(1);\n\n% assign to a temp variable for boundary corrections\nphi_tmp = phi.value;\n\n% correct the value of phi at the boundary (calculation trick)\n% assign the value of the left boundary to the left ghost cell\nphi_tmp(1) = (phi.value(1)+phi.value(2))/2;\n% assign the value of the right boundary to the right ghost cell\nphi_tmp(end) = (phi.value(end)+phi.value(end-1))/2;\n\n% calculate the average value\nxvalue = (ux>0).*phi_tmp(1:Nx+1)+ ...\n                        (ux<0).*phi_tmp(2:Nx+2)+ ...\n                        0.5*(ux==0).*(phi.value(1:Nx+1)+phi.value(2:Nx+2));\nphiFaceAverage=FaceVariable(phi.domain, xvalue, [], []);\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Utilities/upwindMean1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5776125944194901}}
{"text": "function bwn = bw_filter(bw, keepnum)\nif nargin < 2\n    keepnum = 15;\nend\n[L, num] = bwlabel(bw, 8); \nLn = zeros(1, num);\nstats = regionprops(L, 'Area'); \nLn = cat(1, stats.Area);\n[Ln, ind] = sort(Ln);\nif num>keepnum || num==keepnum\n    for i = 1 : num-keepnum\n        bw(L == ind(i)) = 0;\n    end\nend\nbwn = bw;\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/\u7b2c 21 \u7ae0 \u8def\u9762\u88c2\u7f1d\u68c0\u6d4b\u8bc6\u522b\u7cfb\u7edf\u8bbe\u8ba1/bw_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5776125821760058}}
{"text": "function [FV] = mesh_grow(FV,origin,dist),\n\n% mesh_grow - explode vertices of mesh by specific distance\n%\n% FV = mesh_grow(FV,origin,dist)\n%\n% FV is a struct with fields:\n%\n% FV.vertices   - Nx3 matrix of Cartesian vertex coordindates (X,Y,Z)\n% FV.faces      - Mx3 matrix of triangulation of FV.vertices\n%\n% origin        - 1x3 row vector, usually (0,0,0)\n%\n% dist          - how far to explode the mesh away from the origin;\n%                 this distance is relative to current distance from\n%                 the origin, not the total distance from the origin.\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:57 $\n\n% Licence:  GNU GPL, no implied or express warranties\n% History:  10/2002, Darren.Weber_at_radiology.ucsf.edu\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n    xo = origin(1); yo = origin(2); zo = origin(3);\n    \n    Nvert = size(FV.vertices,1);\n    \n    fprintf('...mesh explosion...'); tic;\n    \n    for v = 1:Nvert,\n        \n        x = FV.vertices(v,1);\n        y = FV.vertices(v,2);\n        z = FV.vertices(v,3);\n        \n        % Find direction cosines for line from centre to vertex\n        d = sqrt( (x-xo)^2 + (y-yo)^2 + (z-zo)^2 );\n        \n        l = (x-xo)/d; % cos alpha\n        m = (y-yo)/d; % cos beta\n        n = (z-zo)/d; % cos gamma\n        \n        % now decrease d by dist\n        d = d + dist;\n        \n        % locate vertex at this new distance\n        x = (l * d) + xo;\n        y = (m * d) + yo;\n        z = (n * d) + zo;\n        \n        FV.vertices(v,:) = [ x y z ];\n    end\n    \n    t = toc; fprintf('...done (%5.2f sec)\\n',t);\n    \nreturn\n    \n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/mesh_grow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5776125790573718}}
{"text": "function [varargout] = likGauss(hyp, y, mu, s2, inf, i)\n\n% likGauss - Gaussian likelihood function for regression. The expression for the \n% likelihood is \n%   likGauss(t) = exp(-(t-y)^2/2*sn^2) / sqrt(2*pi*sn^2),\n% where y is the mean and sn is the standard deviation.\n%\n% The hyperparameters are:\n%\n% hyp = [  log(sn)  ]\n%\n% Several modes are provided, for computing likelihoods, derivatives and moments\n% respectively, see likFunctions.m for the details. In general, care is taken\n% to avoid numerical issues when the arguments are extreme.\n%\n% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2014-03-04.\n%                                      File automatically generated using noweb.\n%\n% See also LIKFUNCTIONS.M.\n\nif nargin<3, varargout = {'1'}; return; end   % report number of hyperparameters\n\nsn2 = exp(2*hyp);\n\nif nargin<5                              % prediction mode if inf is not present\n  if numel(y)==0,  y = zeros(size(mu)); end\n  s2zero = 1; if nargin>3, if norm(s2)>0, s2zero = 0; end, end         % s2==0 ?\n  if s2zero                                                    % log probability\n    lp = -(y-mu).^2./sn2/2-log(2*pi*sn2)/2; s2 = 0;\n  else\n    lp = likGauss(hyp, y, mu, s2, 'infEP');                         % prediction\n  end\n  ymu = {}; ys2 = {};\n  if nargout>1\n    ymu = mu;                                                   % first y moment\n    if nargout>2\n      ys2 = s2 + sn2;                                          % second y moment\n    end\n  end\n  varargout = {lp,ymu,ys2};\nelse\n  switch inf \n  case 'infLaplace'\n    if nargin<6                                             % no derivative mode\n      if numel(y)==0, y=0; end\n      ymmu = y-mu; dlp = {}; d2lp = {}; d3lp = {};\n      lp = -ymmu.^2/(2*sn2) - log(2*pi*sn2)/2; \n      if nargout>1\n        dlp = ymmu/sn2;                      % dlp, derivative of log likelihood\n        if nargout>2                    % d2lp, 2nd derivative of log likelihood\n          d2lp = -ones(size(ymmu))/sn2;\n          if nargout>3                  % d3lp, 3rd derivative of log likelihood\n            d3lp = zeros(size(ymmu));\n          end\n        end\n      end\n      varargout = {lp,dlp,d2lp,d3lp};\n    else                                                       % derivative mode\n      lp_dhyp = (y-mu).^2/sn2 - 1;  % derivative of log likelihood w.r.t. hypers\n      dlp_dhyp = 2*(mu-y)/sn2;                               % first derivative,\n      d2lp_dhyp = 2*ones(size(mu))/sn2;   % and also of the second mu derivative\n      varargout = {lp_dhyp,dlp_dhyp,d2lp_dhyp};\n    end\n\n  case 'infEP'\n    if nargin<6                                             % no derivative mode\n      lZ = -(y-mu).^2./(sn2+s2)/2 - log(2*pi*(sn2+s2))/2;    % log part function\n      dlZ = {}; d2lZ = {};\n      if nargout>1\n        dlZ  = (y-mu)./(sn2+s2);                    % 1st derivative w.r.t. mean\n        if nargout>2\n          d2lZ = -1./(sn2+s2);                      % 2nd derivative w.r.t. mean\n        end\n      end\n      varargout = {lZ,dlZ,d2lZ};\n    else                                                       % derivative mode\n      dlZhyp = ((y-mu).^2./(sn2+s2)-1) ./ (1+s2./sn2);   % deriv. w.r.t. hyp.lik\n      varargout = {dlZhyp};\n    end\n\n  case 'infVB'\n    % variational lower site bound\n    % t(s) = exp(-(y-s)^2/2sn2)/sqrt(2*pi*sn2)\n    % the bound has the form: (b+z/ga)*f - f.^2/(2*ga) - h(ga)/2\n    n = numel(s2); b = zeros(n,1); y = y.*ones(n,1); z = y;\n    varargout = {b,z};\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/IM-MOEA-D/gpml-matlab-v3.4-2013-11-11/likGauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5776125770552998}}
{"text": "function [Population,FrontNo,CrowdDis] = EnvironmentalSelection(Population,N,zmin,zmax)\n% The environmental selection of NSGA-II\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    %% Normalization\n    PopObj = Population.objs - repmat(zmin,length(Population),1);\n    range  = zmax - zmin;\n    if 0.05*max(range) < min(range)\n        PopObj = PopObj./repmat(range,length(Population),1);\n    end\n    [~,x]      = unique(round(PopObj*1e6)/1e6,'rows');\n    PopObj     = PopObj(x,:);\n    Population = Population(x);\n    N          = min(N,length(Population));\n\n    %% Non-dominated sorting\n    [FrontNo,MaxFNo] = NDSort_SDR(PopObj,N);\n    Next = FrontNo < MaxFNo;\n    \n    %% Calculate the crowding distance of each solution\n    CrowdDis = CrowdingDistance(PopObj,FrontNo);\n    \n    %% Select the solutions in the last front based on their crowding distances\n    Last     = find(FrontNo==MaxFNo);\n    [~,Rank] = sort(CrowdDis(Last),'descend');\n    Next(Last(Rank(1:N-sum(Next)))) = true;\n    \n    %% Population for next generation\n    Population = Population(Next);\n    FrontNo    = FrontNo(Next);\n    CrowdDis   = CrowdDis(Next);\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/NSGA-II-SDR/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5776125719345938}}
{"text": "function [err, Qd, dfx, dmat2] = QRDecom(dmat, cmat)\n%\n%   [err,] = QRDecom.m ()\n%\n%Purpose:\n%\n%\n%\n%Input Parameters:\n%\n%\n%\n%Output Parameters:\n%   err : 0 No Problem\n%       : 1  Problems\n%\n%\n%\n%Key Terms:\n%\n%More Info :\n%\n%\n%\n%\n%     Author : Gang Chen\n%     Date : Tue Mar 23 16:09:23 EST 2004\n%     SSCC/NIMH/ National Institutes of Health, Bethesda MD 20892\n\n\n%Define the function name for easy referencing\nFuncName = 'QRDecom.m';\n\n%Debug Flag\nDBG = 1;\n\n%initailize return variables\nerr = 1;\n\n% Tolerance for computing rank from diag(R) after QR decomposition\n%[nrows,ncols] = size(dmat);\n\n% Find the null space of the constraints matrix\n[Qc,Rc,Ec] = qr(cmat');\npc = Rrank(Rc);\nQc0 = Qc(:,pc+1:end);\n\n% Do qr decomposition on design matrix projected to null space\nDproj = dmat*Qc0;\n[Qd,Rd,Ed] = qr(Dproj,0);\ndfx = Rrank(Rd);\nQd = Qd(:,1:dfx);\n%Rd = Rd(1:dfx,1:dfx);\n\n% Return reduced design matrix if requested\nif nargout>3\n   dmat2 = Qd' * dmat;\nend\n\nerr = 0;\nreturn;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/afni/QRDecom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5776125709335572}}
{"text": "% feldkamp_example.m\n% example of how to use feldkamp.m for cone-beam CT reconstruction\n% Copyright 2004-8-28, Nicole Caparanis, Patty Laskowsky, Taka Masuda,\n% and Jeff Fessler, The University of Michigan\n% modified version by Ajay Paidi\n\nif ~isvar('proj')\n\tdown = 1/2;\n\tnv = 240*down;%240*down;\n\tnh = 256*down;%256*down;\n\tna = 224*down;%224*down;\n\tds = 1024/nh;\n\tdt = ds;\n\tdis_src_det = 949;\n\tdis_iso_det = 408;\n\tdis_src_iso = dis_src_det - dis_iso_det;\n\tdis_foc_src = inf; % flat detector panel\n\toffset_det_h = 0.25; % quarter detector\n\toffset_det_v = 0.0;\n\thoriz = ([-(nh-1)/2:(nh-1)/2]' - offset_det_h) * ds;\n\tverti = ([-(nv-1)/2:(nv-1)/2]' - offset_det_v) * dt;\n\tprintf('rmax=%g', dis_src_iso*sin(atan(max(abs(horiz)) / dis_src_det)))\n\n    \nell = [ ...\n\t\t[0 0 -72 150 200 15 0 5];\n\t\t[0 0 -32 150 200 20 0 10];\n        [0 0 12 150 200 15 0 10];\n\t\t[0 0 52 150 200 20 0 7];\n        [0 0 82 150 200 15 0 10];\n        ];\n    \n\t\n\tnx = 240*down;%256*down;\n\tny = 256*down;%240*down;\n\tnz = 112*down;%184*down;\n\tdx = 2/down; dy = dx; dz = dx;\n\tx = ellipsoids(nx, ny, nz, ell, dx, dy, dz);\n\n\t% cone-beam system geometry, generalized from fan-beam geometry.\n\t% see ASPIRE users guide under tech. reports on web page for details.\n\targs = arg_pair('system', NaN, 'nx', nx, 'ny', ny, 'nz', nz, ...\n\t\t'nv', nv, 'nh', nh, 'na', na, 'support', 'all', ...\n\t\t'orbit', 360, 'orbit_start', 0, ...\n\t\t'pixel_size', dx, 'ray_spacing', ds, 'strip_width', 0, ...\n\t\t'dis_src_det', dis_src_det, ...\n\t\t'dis_iso_det', dis_iso_det, ...\n\t\t'dis_foc_src', dis_foc_src, ...\n\t\t'offset_source', 0, ...\n\t\t'offset_det_h', offset_det_h, ...\n\t\t'offset_det_v', offset_det_v);\n    \n   \n\tpl=230;\n\tim(pl+1, x, 'x'), cbar\n\tim(pl+2, proj, 'proj'), cbar\n\tdrawnow\nprompt\nend\n\n% cone-beam reconstruction\nmask = true([nx ny nz]);\nrecon = feldkamp(proj, 'ramp', mask, args);\n\n% show results (off-center slices worse than central slice)\nim(pl+4, recon, 'recon'), cbar\nim(pl+5, recon - x, 'error'), cbar\nix = 1:nx; iy = ny/2; iz = nz/2;\nsubplot(236)\nplot(ix, x(ix,iy,iz), '-', ix, recon(ix,iy,iz), '--')\naxis([1 nx -1 16]), legend('true', 'recon', 2)\ntitle 'MIDDLE SLICE'\niz=12;\nsubplot(233)\nplot(ix, x(ix,iy,iz), '-', ix, recon(ix,iy,iz), '--')\naxis([1 nx -1 16]), legend('true', 'recon')\ntitle(sprintf('SLICE %d', iz))\n%figure\n%subplot(2,1,1)\n%ix1 = nx/2;\n%iy1 = ny/2;\n%iy = 1:ny;\n%ix = 1:nx;\n%iz = nx/2;\n%plot(iy, x(ix1, iy, iz), '-', iy, recon(ix1,iy,iz), '--');\n%title('plot of x vs. y on middle slice')\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/fdk_paida_ajay/feldkamp_wt_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650247, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5776125637530165}}
{"text": "classdef DEAGNG < ALGORITHM\n% <multi/many> <real/integer/label/binary/permutation>\n% Decomposition based evolutionary algorithm guided by growing neural gas\n% aph ---   0.1 --- Parameter alpha\n% eps --- 0.314 --- Parameter epsilon\n\n%------------------------------- Reference --------------------------------\n% Y. Liu, H. Ishibuchi, N. Masuyama, and Y. Nojima, Adapting reference\n% vectors and scalarizing functions by growing neural gas to handle\n% irregular Pareto fronts. IEEE Transactions on Evolutionary Computation,\n% 2020, 24(3): 439-453.\n%--------------------------------------------------------------------------\n% Copyright Yiping Liu\n% Please contact {yiping0liu@gmail.com} if you have any problem.\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Parameter setting\n            [aph,eps] = Algorithm.ParameterSet(0.1,0.314); \n                           \n            %% DEA Initialization\n            [Ru,Problem.N] = UniformPoint(Problem.N,Problem.M);\t% Uniform reference vectors\n            Population     = Problem.Initialization();          % Random population\n            Zmin           = min(Population.objs,[],1);         % Ideal Point  \n            AS             = [];                                % Input Signal Archive\n            Ruq            = Ru;                                % Refernce vectors in Ru for selection\n            [FrontNo,~]    = NDSort(Population.objs,Problem.N); % Fitness for the first mating selection\n            crd            = zeros(1,Problem.N);                % Fitness for the first mating selection   \n            MaxGen         = ceil(Problem.maxFE/Problem.N);    \t% Maximum Generation\n            \n            %% GNG Initialization\n            ArchiveSize = Problem.M*Problem.N;\t% Size of Input Signal Archive\n            NoG = aph*MaxGen;                   % Number of generations of Not Training GNG\n            GNGnet.maxIter = 1;                 % Number of iterations to train GNG per Generation  \n            GNGnet.maxAge = Problem.N;          % Maximum cluster age     \n            GNGnet.maxNode = Problem.N;         % Max number of nodes\n            GNGnet.lambda = 0.2*Problem.N;      % Cycle for topology reconstruction   \n            GNGnet.hp = [];                     % Hit point of node \n            GNGnet.maxHP = 2*ArchiveSize;       % Max HP of node \n            GNGnet.Node = [];                   % Node\n            GNGnet.NodeS = [];                  % Expanded node \n            GNGnet.NodeP = [];                  % Node mapped to hyperplane \n            GNGnet.Err = [];                    % Error \n            GNGnet.edge = zeros(2,2);           % Edge between nodes \n            GNGnet.age = zeros(2,2);            % Age of edge \n            GNGnet.epsilon_a = 0.2;             % Learning coefficient\n            GNGnet.epsilon_nb = 0.01;           % Learning coefficient of neighbor\n            GNGnet.alpha = 0.5;                 % Nodes r1max and r2max error reduction constant\n            GNGnet.delta = 0.9;                 % Error reduction coefficient \n\n            %% Optimization\n            while Algorithm.NotTerminated(Population)        \n                MatingPool = TournamentSelection(2,Problem.N,FrontNo,crd);\n                Offspring  = OperatorGA(Problem,Population(MatingPool));       \n                Zmin       = min([Zmin;Offspring.objs],[],1);\n\n                %% GNG-based adaptation\n                if ceil(Problem.FE/Problem.N) <= MaxGen - NoG   \n                    % Input Signal Archive Update\n                    AS = ArchiveUpdate([AS;Offspring.objs],ArchiveSize,Ruq,GNGnet.NodeS,Zmin);\n                    nAS = length(AS);      \n                    % GNG Update (and Algorithm 3)\n                    GNGnet.maxNode = min(Problem.N,floor(nAS/2)); % paramter reset \n                    GNGnet.maxHP = 2*nAS; % paramter reset\n                    GNGnet = GNGUpdate(AS,GNGnet);\n                    % Reference Vector Adaptation (Algorithm 4) \n                    if size(GNGnet.NodeS,1)>2\n                        [Ruq,GNGnet] = ReferenceCombination(Ru,GNGnet);\n                    end\n                    % Scalarizing Function Adaptation\n                    theta = TunePBI(GNGnet,eps); % Tune theta in PBI function                    \n                end\n\n               %% Environmental Selection                 \n               [Population,FrontNo,crd] = ESelection([Population,Offspring],Problem.N,Ruq,GNGnet.NodeS,theta,Zmin);\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/Algorithms/Multi-objective optimization/DEA-GNG/DEAGNG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5775056115768792}}
{"text": "% FitDataNDFast : Fits several ND Gaussians to N-dimensional image data\n% Synopsis: [fitted,params,myfunct] = FitDataNDFast(InitParm,Data,numdims,maxiter,method)\n% AFunctString should use the variable 'x' as a vector and x{1}, x{2} to access its components, \n% and the values to fit: c(1),c(2),...\n%\n% InitParm : Vector of initial parameters first row is global parameters,\n% meaning is as follows: [global background, global width, intensity, posy, posx, intensity2, posy2, posx2...]\n% other rows are local parameters\n% Data : Experimental multidimensional (e.g. image) data to be fitted\n% maxiter : maximum number of iterations in fit (default = 300)\n% method : figure of merit to use for fitting 'mes', 'idiv' or 'fidiv'\n%\n% Example:\n% a=noise(51.2*exp(-((xx(20,20)-2).^2+(yy(20,20)-1.2).^2)/20)+33,'poisson')\n% [params,res,fitted]=FitDataNDFast([30 15 40 2 2],a,2,300,'idiv')\n% fitted is the residual image (depending on method)\n% params contains the result of the fit\n\nfunction [params,res,fitted,residual] = FitDataNDFast(InitParm,Data,numdims,maxiter,mymethod)\n\nif nargin < 3\n    numdims = 2;\nend\nif nargin < 4\n    maxiter = 3000;\nend\n\nif nargin < 5\n    mymethod = 'mse';\nend\n\n%if nargin < 5\n%    placement = 'right';\n%end\n\n%fixedparams=[0 20];\nMultiGaussMSE(double(Data),mymethod,numdims)\n\n[res, fitted] = MultiGaussMSE(InitParm');\n%params=fixedparams;\n\n\nif (0)  % old method\noptions=optimset('Display','notify','TolX',10^-4,'TolFun',10^-8,'MaxIter',maxiter);\n[params,msevalue]=fminsearch(@MultiGaussMSE,InitParm',options);\nelse    % new method with smarter amd faster optimisation routine from http://www.cs.ubc.ca/~schmidtm\noptions=struct('Display','off','notify',1,'numDiff',1,'TolX',10^-4,'TolFun',10^-8,'MaxIter',maxiter);\n[params,msevalue,moreinfo]=minFunc(@MultiGaussMSE,InitParm',options);\nend\n\n[res, fitted,residual] = MultiGaussMSE(params);\nparams = params';\nfitted=dip_image(fitted);\nresidual=dip_image(residual);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/FitDataNDFast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5775055897778292}}
{"text": "function qout=qnorm(qin)\n% QNORM(Q) normalizes quaternions.\n%     Works on vectors of quaternions too.  If input is a vector of four\n%     quaternions, QNORM will determine whether the quaternions are row or\n%     column vectors according to ISQ.\n%\n% See also ISQ.\n\n% Release: $Name: quaternions-1_2_2 $\n% $Revision: 1.9 $\n% $Date: 2001/05/01 20:20:31 $\n \n% Copyright (C) 2001, Jay A. St. Pierre.  All rights reserved.\n\n\nif nargin~=1\n  error('qnorm() requires one input argument');\nelse\n  qtype = isq(qin);\n  if ( qtype == 0 )\n    error(['Invalid input: must be a quaternion or a vector of' ...\n          ' quaternions'])\n  elseif ( qtype==3 )\n    warning(['Component quaternion shape indeterminate... assuming row' ...\n             ' vectors'])\n  end\nend\n\n\n% Make sure qin is a column of quaternions\nif( qtype == 1 )\n  qin=qin.';\nend\n\n% Find the magnitude of each quaternion\nqmag=sqrt(sum(qin.^2,2));\n\n% Make qmag the same size a q\nqmag=[qmag qmag qmag qmag];\n\n% Divide each element of q by appropriate qmag\nqout=qin./qmag;\n\n% Make sure output is same shape as input\nif( qtype == 1 )\n  qout=qout.';\nend\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/qnorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5774498493882866}}
{"text": "% make the structure of an embedded HMM with 2 rows and 3 columns\n\n% 1------------>2\n% |\\   \\        | \\  \\\n% 3->4->5       6->7->8\n\nn = 8;\ndag = zeros(n);\ndag(1,[2 3 4 5])=1;\ndag(2,[6 7 8])=1;\nfor i=3:4\n  dag(i,i+1)=1;\nend\nfor i=6:7\n  dag(i,i+1)=1;\nend\nns = 2*ones(1,n);\nbnet = mk_bnet(dag,ns);\nfor i=1:n\n  bnet.CPD{i}=tabular_CPD(bnet,i);\nend\n[jtree, root, cliques] =  graph_to_jtree(moralize(bnet.dag), ones(1,n), {}, {});\n%[jtree, root, cliques, B, w, elim_order, moral_edges, fill_in_edges] = dag_to_jtree(bnet);\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/dynamic/ehmm1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5774498493487369}}
{"text": "function val = source(x_g, param)\n\n% Evaluate source terms (if any) at points x_g\n\n\n% characteristic functions for source terms\n    chi1_g = (x_g(:,1) < 0.2*param.L).*(x_g(:,2) < 0.5*param.W);\n    chi3_g = (x_g(:,1) > 0.8*param.L).*(x_g(:,2) > 0.5*param.W);\n%   chi2_g = ~chi1_g & ~chi3_g;\n\n    val =   0*chi1_g +   0*chi3_g;\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/fem2d_heat_rectangle_steady_spmd/source.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5774498493487368}}
{"text": "function r = mpower(a,b)\n%MPOWER       Hessian power  a ^ n\n%\n\n% written  04/04/04     S.M. Rump\n% modified 04/06/05     S.M. Rump  rounding unchanged\n% modified 09/28/08     S.M. Rump  check for rounding to nearest improved\n%\n\n  % for scalars use .^ with improved diameter for even exponent\n  if ( prod(size(a))==1 ) & ( prod(size(b))==1 )\n    r = a .^ b ;\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(b,'double') & isreal(b) & prod(size(b))==1 & b==round(b)\n    if b<0\n      error('negative exponent in mpower')\n    end\n    [m n] = size(a);\n    if m~=n\n      error('hessian mpower of non-square matrix')\n    end\n    if b==0\n      if issparse(a)\n        r = typeadj( hessian(speye(size(a))) , typeof(a) );\n      else\n        r = typeadj( hessian(eye(size(a))) , typeof(a) );\n      end\n    else                        % b is integer, at least 1\n      b = b - 1;\n      r = a;\n      while b>0\n        if mod(b,2)==1\n          r = r*a;\n        end\n        b = floor(b/2);\n        if b~=0\n          a = a*a;\n        end\n      end\n    end\n  else\n    error('invalid call of hessian mpower ^')\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/hessian/@hessian/mpower.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5774498384604273}}
{"text": "function ls=v_lpcar2ls(ar)\n%V_LPCAR2LS convert ar polynomial to line spectrum pair frequencies LS=(AR)\n% output vector elements will be in range 0 to 0.5\n% the returned vector will be of length p\n\n% This routine is nowhere near as efficient as it might be\n\n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: v_lpcar2ls.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(ar);\np = p1-1;\np2 = fix(p/2);\nd=0.5/pi;\n\nif rem(p,2)\t\t% odd order\n  for k=1:nf\n    aa=[ar(k,:) 0];\n    r = aa + fliplr(aa);\n    q = aa - fliplr(aa);\n    fr = sort(angle(roots(r)));\n    fq = [sort(angle(roots(deconv(q,[1 0 -1])))); 0];\n    f = [fr(p2+2:p+1).' ; fq(p2+1:p).'];\n    f(p+1) = [];\n    ls(k,:) = d*f(:).';\n  end\nelse\n  for k=1:nf\n    aa=[ar(k,:) 0];\n    r = aa + fliplr(aa);\n    q = aa - fliplr(aa);\n    fr = sort(angle(roots(deconv(r,[1 1]))));\n    fq = sort(angle(roots(deconv(q,[1 -1]))));\n    f = [fr(p2+1:p).' ; fq(p2+1:p).'];\n    ls(k,:) = d*f(:).';\n  end\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_lpcar2ls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5774498331349228}}
{"text": "function [x, infos] = fro_mu_partial_nmf(V, rank, in_options)\n%\n% This file is part of NMFLibrary\n%\n% Created by H.Kasai on Feb. 16, 2017\n%\n% Change log: \n%\n%       June 16, 2022 (Hiroyuki Kasai): Initial version.\n%\n%       Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n    % set dimensions and samples\n    [m, n] = size(V);\n \n    % set local options\n    local_options = [];\n    local_options.alg       = 'mu';\n    local_options.norm_h    = 0;\n    local_options.norm_w    = 1;    \n    local_options.alpha     = 2;\n    local_options.delta     = 0.1;\n    local_options.myeps     = 1e-16;\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 ~strcmp(options.alg, 'mu')\n        fprintf('Invalid algorithm: %s. Therfore, we use mu (i.e., multiplicative update).\\n', options.alg);\n        options.alg = 'mu';\n    end\n    \n    % initialize factors\n    init_options = options;\n    [init_factors, ~] = generate_init_factors(V, rank, init_options);    \n    W = init_factors.W;\n    H = init_factors.H;      \n    \n    % initialize\n    method_name = sprintf('MU-Partial (%s:%s)', options.alg, options.metric_type);\n    epoch = 0;    \n    R_zero = zeros(m, n);\n    grad_calc_count = 0;\n\n    if options.verbose > 0\n        fprintf('# %s: started ...\\n', method_name);           \n    end     \n    \n    % store initial info\n    clear infos;\n    [infos, f_val, optgap] = store_nmf_info(V, W, H, R_zero, options, [], epoch, grad_calc_count, 0);\n    \n    if options.verbose > 1\n        fprintf('MU-Partial (%s:%s): Epoch = 0000, cost = %.16e, optgap = %.4e\\n', options.alg, options.metric, f_val, optgap); \n    end  \n\n    % set start time\n    start_time = tic();\n\n    % main loop\n    while true\n        \n        % check stop condition\n        [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n        if stop_flag\n            display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n            break;\n        end       \n\n        if strcmp(options.alg, 'mu')\n                \n            % update H\n            H = H .* (W' * V) ./ (W' * W * H);\n            H = H + (H<options.myeps) .* options.myeps;\n\n            % update W\n            W(:, options.updateW) = W(:, options.updateW) .* (V * H(options.updateW, :)') ...                \n                ./ (W * (H * H(options.updateW, :)'));                \n            W = W + (W<options.myeps) .* options.myeps;\n\n        end\n        \n        % measure elapsed time\n        elapsed_time = toc(start_time);        \n        \n        % measure gradient calc count\n        grad_calc_count = grad_calc_count + m*n;\n\n        % update epoch\n        epoch = epoch + 1;         \n        \n        % store info\n        infos = store_nmf_info(V, W, H, R_zero, options, infos, epoch, grad_calc_count, elapsed_time);  \n        \n        % display info\n        display_info(method_name, epoch, infos, options);\n\n    end\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/frobenius_norm/fro_mu_partial_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.577426697591966}}
{"text": "function [C, S] = QLiftDec2MaxMax(X, N)\n%-----------------------------------------------------------------------------\n% QLiftDec2MaxMax\n% Multilevel 2-D decomposition by the lifting scheme and using quincunx grids\n%\n% The MaxMax scheme has been proposed by Heijmans and Goutsias, see e.g.\n%    H.J.A.M. Heijmans, J. Goutsias,\n%    Multiresolution signal decomposition schemes.\n%    Part 2: morphological wavelets.\n%    CWI Report PNA-R9905, Amsterdam, 1999.\n%    http://repository.cwi.nl:8888/cwi_repository/docs/IV/04/04625D.pdf\n%\n% Calls for: QLmaxlev,\n%            storeQ1001, storeR,\n%            getcolor01, getcolor10, getcolor00, getcolor11,\n%            putcolor01, putcolor10, putcolor00, putcolor11.        \n% See also: QLiftRec2MaxMin\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw <Paul.de.Zeeuw@cwi.nl>  http://homepages.cwi.nl/~pauldz/\n% Last Revision: February 6, 2003.\n% (c) 1999-2002 Stichting CWI, Amsterdam\n%-----------------------------------------------------------------------------\n%Firstly, check input data\n%\nif  isempty(X)\n  error(' QLiftDec2MaxMax - empty matrix ');\nelse\n  if mod(N, 2) == 1\n    error(' QLiftDec2MaxMax - only an even number of levels is accepted ');\n  end\n  if QLmaxlev(size(X), 'maxmax') < N \n    error(' QLiftDec2MaxMax - too many levels requested ');\n  end\n  if N < 2\n    disp([' QLiftDec2MaxMax - WARNING too few levels requested ' ...\n          '-> empty decomposition ']);\n  end\nend\n%\n%Secondly, start decomposition\n%\nO = X; % For the sake of efficient use of memory this could be improved upon.\n% We descend to coarser grids, integer lev indicates number of scale.\nC = []; S = [];\n\nfor lev=1:2:N\n%\n   [nO, mO] = size(O);\n   if ( nO < 3 ) || ( mO < 3)\n     error(' QLiftDec2MaxMax - too many levels ');\n   end\n   minO = min(min(O));\n   maxO = max(max(O));\n   cmin = minO-(maxO-minO);\n%  cmax = maxO+(maxO-minO);\n%\n%  The Lifting Scheme proceeds from a rectangular grid\n%  towards a quincunx grid.\n%\n%  Stage: predict\n   A00 =getcolor00(O);\n   A11 =getcolor11(O);\n%  Quincunx grid Q0011 is the union of the values at .00 and .11: \"even slots\"\n%  Quincunx grid Q1001 is the union of the values at .10 and .01: \"odd slots\"\n   Q1001D01 = getcolor01(O) - synA01max(A11, A00, cmin);                % Y1\n   Q1001D10 = getcolor10(O) - synA10max(A11, A00, cmin);                % Y1\n%  At this point the union (quincunx) of Q1001D01 & Q1001D10\n%  contains the DETAILS of O.\n%\n%  For the inverse transform Q1001D01 and Q1001D10 have to be stored:\n   [C, S] = storeQ1001( Q1001D10, Q1001D01, lev, 'd', C, S);\n%\n%  Stage: update\n   Q0011A00 = A00 + ...\n        max(zeros(size(A00)), synA00max(Q1001D10, Q1001D01, cmin));     % X1\n   clear A00;\n   Q0011A11 = A11 + ...\n        max(zeros(size(A11)), synA11max(Q1001D10, Q1001D01, cmin));     % X1\n   clear A11 Q1001D10 Q1001D01;   \n%  At this point the union (quincunx) of Q0011A00 & Q0011A11\n%  contains the updated APPROXIMATION of O, the DETAILS of O\n%  were in the union (quincunx) of Q1001D01 & Q1001D10 (see above).\n%\n%  The Lifting Scheme proceeds by a subsequent step from quincunx\n%  to rectangular grid.\n%\n%  Q0011 is split into the 11 colour with the \"odd slots\" and \n%  the 00 colour with the \"even slots\".\n%\n%  Stage: predict\n   DETAIL11 = Q0011A11 - synA11Qmax(Q0011A00, size(Q0011A11), cmin);        % Y2\n   clear Q0011A11;\n%  Stage: update\n   APPROX00 = Q0011A00 + ...\n     max(zeros(size(Q0011A00)), synA00Qmax(DETAIL11, size(Q0011A00), cmin));% X2\n%\n%  DETAIL11 presents the detail gridfunction w.r.t. Q0011\n%  APPROX00 now represents the updated version of the approximation of Q0011\n%\n%  For the inverse transform DETAIL11 has to be stored:\n   [C, S] = storeR( DETAIL11, lev+1, 'd', C, S);\n   clear Q0011A00 DETAIL11;     \n% \n%  At this point gridfunction DETAIL11 containing the DETAILS has been stored,\n%  gridfunction APPROX00 contains the updated APPROXIMATION, on the (down-\n%  sampled) rectangular grid and has to be stored as well if at the highest\n%  scale.\n%  Note that APPROX00 is downsampled onto a rectangular grid with dimensions of \n%  half size of the original O.\n   if lev+1 >= N\n     [C, S] = storeR(APPROX00, lev+1, 'a', C, S);\n%    It is obligatory that at least at one scale the Approximation has to be\n%    stored or else the scheme cannot be inverted.\n     clear APPROX00;\n%    In the Lifting Scheme all scales have now been processed!\n   else\n%    We proceed to the next scale.\n     O = APPROX00; clear APPROX00;\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/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/QLiftDec2MaxMax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5774266917741129}}
{"text": "function result = Main_Process(Img, n)\nif ndims(Img) == 3\n    I = rgb2gray(Img);\nelse\n    I = Img;\nend\ng1 = [0 1 0\n    0 1 0\n    0 1 0];\ng2 = [0 0 0\n    1 1 1\n    0 0 0];\ng3 = [0 0 1\n    0 1 0\n    1 0 0];\ng4 = [1 0 0\n    0 1 0\n    0 0 1];\ng5 = [0 1 0\n    1 1 1\n    0 1 0];\nGi1 = Multi_Process(I, g1, n);\nGi2 = Multi_Process(I, g2, n);\nGi3 = Multi_Process(I, g3, n);\nGi4 = Multi_Process(I, g4, n);\nGi5 = Multi_Process(I, g5, n);\nG{1} = Gi1;\nG{2} = Gi2;\nG{3} = Gi3;\nG{4} = Gi4;\nG{5} = Gi5;\nua1 = Coef(Gi1, G);\nua2 = Coef(Gi2, G);\nua3 = Coef(Gi3, G);\nua4 = Coef(Gi4, G);\nua5 = Coef(Gi5, G);\nu = [ua1, ua2, ua3, ua4, ua5];\nu = u/sum(u);\nGf1 = Edge_One(G, u);\nresult = Gf1;", "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/\u7b2c 03 \u7ae0 \u57fa\u4e8e\u591a\u5c3a\u5ea6\u5f62\u6001\u5b66\u63d0\u53d6\u773c\u524d\u8282\u7ec4\u7ec7/Main_Process.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.577426687380653}}
{"text": "function sF = regularisation(nodes,y,lambda,varargin)\n% computes a regularisation\n% Syntax\n%   sF = S2FunHarmonic.regularisation(S2Grid,f,lambda)\n%   sF = S2FunHarmonic.regularisation(S2Grid,f,lambda,'bandwidth',\n%        bandwidth,'node_weights',W,'fourier_weights',What)\n%\n% Input\n%  S2Grid - grid on the sphere\n%  f      - function values on the grid (may be multidimensional)\n%  lambda - parameter for regularisation\n%\n% Options\n%  bandwidth  - maximum harmonic degree\n%  W          - weight w_n for the node nodes (default: Voronoi weights)\n%  What       - weight what_{m,l} for the Fourier space (default Sobolev weights for s = 2)\n%\n\n[nodes,idx] = unique(nodes(:));\ny = reshape(y(idx),length(nodes),[]);\nN = length(nodes);\nW = get_option(varargin,'node_weights');\nif isempty(W) \n  W = nodes.calcVoronoiArea;\nend\nbw = get_option(varargin,'bandwidth',floor(sqrt(2*pi/mean(W))));\n\nWhat = get_option(varargin,'fourier_weights');\nif isempty(What) \n  s = 2;\n  What = (2*(0:bw)+1).^(2*s);\n  What = repelem(What,1:2:(2*bw+1))';\nend\n\n% initialize nfsft\nnfsftmex('precompute',bw,1000,1,0);\nplan = nfsftmex('init_advanced',bw,N,1);\nnfsftmex('set_x',plan,[nodes.rho';nodes.theta']);\nnfsftmex('precompute_x',plan);\n\ny = W.*y;\n\n% adjoint nfsft\nnfsftmex('set_f',plan, y);\nnfsftmex('adjoint',plan);\nfhat = nfsftmex('get_f_hat_linear',plan);\n\n[fhat,~] = pcg(@(x) afun(x,plan,lambda,W,What),fhat);\n\nsF = S2FunHarmonic(fhat);\n\n% finalize nfsft\nnfsftmex('finalize',plan);\n\nend\n\n\n\nfunction y = afun(x,plan,lambda,W,What)\n  nfsftmex('set_f_hat_linear',plan,x);\n  nfsftmex('trafo',plan);\n  y = nfsftmex('get_f',plan);\n\n  y = W.*y;\n\n  nfsftmex('set_f',plan,y);\n  nfsftmex('adjoint',plan);\n  y = nfsftmex('get_f_hat_linear',plan);\n\n  y = y+lambda*What.*x;\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/S2Fun/@S2FunHarmonic/regularisation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5774266859562597}}
{"text": "function ans = calc_meanDose(doseBinsMidPtsV, volsHistV, volumeType)\n%Calculate the mean dose for a given DVH\n%  The last parameter 'volumeType' is a wash in this function again\n%  \n%  MODIFICATION ALERT:  THIS FUNCTION IS UTILIZED BY THE DREXLER CODEBASE\n%\n%  LM: 6 Oct 06, JOD, corrected slight error in not taking middle of dose\n%  bin.  Added warning if relative volume not close to one (0.5%\n%  tolerance).\n%      4 Apr 17, APA, passed the dose as min-points of bins. Hence, no need\n%  to add half the binwidth to the passed dose. Call this function after \n%  obtaining DVH from loadDVHMatrix.m, since it returns mid-points of dose bins.\n%\n% Usage: calc_meanDose(doseBinsMidPtsV, volsHistV)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\n\n% doseBinsMidPtsV = (doseBinsLowerPtsV(1:end-1)+doseBinsLowerPtsV(2:end))/2;\n% ans = (sum(doseBinsMidPtsV.*volsHistV(1:end-1))+doseBinsLowerPtsV(end)*volsHistV(end))/sum(volsHistV);\n\nans = sum(doseBinsMidPtsV.*volsHistV)/sum(volsHistV);\n\nreturn;\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/calc_meanDose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5774266822148549}}
{"text": "% SP_EXTERIOR_DERIVAITVE: computes the exterior derivative as a matrix with size \n%  given by the dimension of two consecutive spaces in the De Rham sequence.\n%\n%   diff_op = sp_exterior_derivative (space1, space2);\n%\n% INPUT:\n%\n%   space1:  domain space of the exterior derivative (number of columns)\n%   space2:  image space of the exterior derivative (number of rows)\n%\n% OUTPUT:\n%\n%   diff_op: sparse matrix representation of the differential operator.\n% \n% Copyright (C) 2020-2023 Bernard Kapidani, 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%    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 <http://www.gnu.org/licenses/>.\n\nfunction diff_op = sp_exterior_derivative (space1, space2)\n\n  assert (~strcmpi(space1.transform, 'integral-preserving'), ...\n    'The first space cannot be the one for integral-preserving splines (or n-forms)')\n\n  ndim = numel (space1.scalar_spaces{1}.knots);\n  if (ndim == 1)\n    error ('Not implemented. For dimension 1, use the scalar spaces')\n  elseif (ndim == 2)\n    if (strcmpi (space1.transform, 'curl-preserving'))\n      grad_curl = 'grad';\n      output_der = 2;\n      deg_shift = {[0 1], [1 0]};\n      knt_shift = {[0 2], [2 0]};\n      degree = space1.scalar_spaces{1}.degree + [1 0];\n      knots = {space1.scalar_spaces{2}.knots{1}, space1.scalar_spaces{1}.knots{2}};\n    elseif (strcmpi (space1.transform, 'div-preserving'))\n      grad_curl = 'curl';\n      output_der = 2;\n      deg_shift = {[1 0], [0 1]};\n      knt_shift = {[2 0], [0 2]};\n      degree = space1.scalar_spaces{1}.degree + [0 1];\n      knots = {space1.scalar_spaces{1}.knots{1}, space1.scalar_spaces{2}.knots{2}};\n    else\n      error ('The second space should be either curl-preserving or div-preserving')\n    end\n    assert (isa(space2, 'sp_scalar'), 'The two spaces are not compatible')\n    for idim = 1:ndim\n      assert (all(space1.scalar_spaces{idim}.degree == space2.degree+deg_shift{idim}), 'The degrees are not compatible')\n      assert (all(cellfun(@numel,space1.scalar_spaces{idim}.knots) == (cellfun(@numel, space2.knots)+knt_shift{idim})), ...\n        'The knot vectors are not compatible')\n    end\n  elseif (ndim == 3)\n    grad_curl = 'grad';\n    if (strcmpi (space1.transform, 'curl-preserving'))\n      output_der = 2;\n      deg_shift = {[-1 1 1], [1 -1 1], [1 1 -1]};\n      knt_shift = {[-2 2 2], [2 -2 2], [2 2 -2]};\n      degree = space1.scalar_spaces{1}.degree + [1 0 0];\n      knots = {space1.scalar_spaces{2}.knots{1}, space1.scalar_spaces{1}.knots{2}, space1.scalar_spaces{1}.knots{3}};\n      assert (isa(space2, 'sp_vector'), 'The two spaces are not compatible')\n      for idim = 1:ndim\n        assert (all(space1.scalar_spaces{idim}.degree == space2.scalar_spaces{idim}.degree+deg_shift{idim}), 'The degrees are not compatible')\n        assert (all(cellfun(@numel,space1.scalar_spaces{idim}.knots) == (cellfun(@numel, space2.scalar_spaces{idim}.knots)+knt_shift{idim})), ...\n          'The knot vectors are not compatible')\n      end\n    elseif (strcmpi (space1.transform, 'div-preserving'))\n      output_der = 3;\n      deg_shift = {[1 0 0], [0 1 0], [0 0 1]};\n      knt_shift = {[2 0 0], [0 2 0], [0 0 2]};\n      degree = space1.scalar_spaces{1}.degree + [0 1 1];\n      knots = {space1.scalar_spaces{1}.knots{1}, space1.scalar_spaces{2}.knots{2}, space1.scalar_spaces{3}.knots{3}};\n      assert (isa(space2, 'sp_scalar'), 'The two spaces are not compatible')\n      for idim = 1:ndim\n        assert (all(space1.scalar_spaces{idim}.degree == space2.degree+deg_shift{idim}), 'The degrees are not compatible')\n        assert (all(cellfun(@numel,space1.scalar_spaces{idim}.knots) == (cellfun(@numel, space2.knots)+knt_shift{idim})), ...\n          'The knot vectors are not compatible')\n      end\n    else\n      error ('Only implemented for curl-preserving and div-preserving transforms')\n    end\n  end\n  \n  diff_ops = op_geom_exterior (knots, degree, grad_curl);\n  diff_op = diff_ops{output_der};\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_vector/sp_exterior_derivative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5774266793660697}}
{"text": "function em = errormatrix(fet,clu)\n\ncluIx = unique(clu);\nnClu = length(cluIx);\nnDim = size(fet,2);\n\nmu = zeros(nClu,nDim);\nsigma = zeros(nDim,nDim,nClu);\np = zeros(1,nClu);\nfor ii=1:nClu\n    f = fet(clu==cluIx(ii),:);\n    % Mean fet vector\n    mu(ii,:) = mean(f);\n    % Covariance. We add 1e-5 to the diagonal to ensure that it will be\n    % positive definite\n    sigma(:,:,ii) = cov(f)+1e-5*eye(nDim,nDim);\n    p(ii) = sum(clu==cluIx(ii));\nend\nobj = gmdistribution(mu,sigma,p);\n%keyboard\n\nem = zeros(nClu,nClu);\n\nfor ii=1:nClu\n    p = posterior(obj,fet(clu==cluIx(ii),:));\n    %keyboard\n    em(ii,:) = mean(p);\nend\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/preprocessing/autoClustering/errormatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033682, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5774266742002717}}
{"text": "function ll = dnetLogLikelihood(model)\n\n% DNETLOGLIKELIHOOD Density network log likelihood.\n% FORMAT\n% DESC computes the log likelihood of a density network\n% model. \n% ARG model : the model structure for computing the log likelihood.\n% RETURN ll : the model log likelihood.\n%\n% SEEALSO : modelLogLikeihood\n%\n% COPYRIGHT : Neil D. Lawrence, 2008\n\n% MLTOOLS\n\n  \nll = 0.5*model.d*model.N*log(model.beta/(2*pi)) ...\n     - model.N*log(model.M); \n\nll = ll - 0.5*model.alpha*sum(sum(model.A.*model.A)) ...\n     - 0.5*model.alpha*sum(model.b.*model.b);\n\n  \nllPointComp = zeros(model.N, model.M);\n% Get projections of latent samples.\nYpred = dnetOut(model);\n\nif model.N > model.M\n  for i = 1:model.M\n    diffY = model.y - repmat(Ypred(i, :), model.N, 1);\n    diffY = diffY.*diffY;\n    llPointComp(:, i) = - 0.5*model.beta*sum(diffY, 2);\n  end\nelse\n  for i = 1:model.N\n    diffY = repmat(model.y(i, :), model.M, 1) - Ypred;\n    diffY = diffY.*diffY;\n    llPointComp(i, :) = - 0.5*model.beta*sum(diffY, 2)';\n  end\nend\n\nmaxllPointComp = max(llPointComp, [], 2);\nllPointComp = exp(llPointComp - repmat(maxllPointComp, 1, model.M));\nll = ll + sum(log(sum(llPointComp, 2)) + maxllPointComp);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/dnetLogLikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5774180939939344}}
{"text": "function [imgOut, FC_MAX_L] = FalseColor(img, FC_compress, FC_Vis, FC_LMax, FC_figure, FC_title, FC_lin, FC_title_color_map)\n%\n%\n%       [imgOut, FC_MAX_L] = FalseColor(img, compress, FC_Vis, LMax)\n%\n%       This function creates a false color image for re-mapping luminance\n%       into an LDR RGB image.\n%\n%       Input:\n%           -img: the input img\n%           -FC_compress: compression option for HDR images:\n%               -'lin': no compression to the dynamic range (it typically creates\n%               good results for LDR images only!)\n%               -'log': the HDR domain is compressed using natural\n%               logarithm (default parameter)\n%               -'log2': the HDR domain is compressed using base 2\n%               logarithm\n%               -'log10': the HDR domain is compressed using base 10\n%               logarithm\n%               -'sigmoid': the HDR domain is compressed using a basic\n%               sigmoid curve\n%           -FC_Vis: a boolean parameter. If it is set to 1, it will show.\n%           Default values is 1, so the image will visualized\n%           the image as a complete figure including the visualization bar\n%           -FC_LMax: the maximum luminance for the color re-mapping functions.\n%               This needs to be used when creating false color images with the same scale. \n%           -FC_figure: index for the figure\n%           -FC_title: title for the false color window\n%           -FC_lin: linear scale or exponential one.\n%           -FC_title_color_map: color map unit\n%           \n%       Output:\n%           -imgOut: the false color LDR and RGB image (no gamma is\n%           required for visualization purposes)\n%           -FC_MAX_L: the maxium luminance value in the selected\n%           FC_compress domain\n%\n%     Copyright (C) 2011-17 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 <http://www.gnu.org/licenses/>.\n%\n\nL = lum(img);\n\nif(~exist('FC_Vis', 'var'))\n    FC_Vis = 1;\nend\n\nif(~exist('FC_compress', 'var'))\n    FC_compress = 'log';\nend\n\nif(~exist('FC_figure', 'var'))\n    FC_figure = 1;\nend\n\nif(~exist('FC_title', 'var'))\n    FC_title = 'False color visualization';\nend\n\nif(~exist('FC_lin', 'var'))\n    FC_lin = 0;\nend\n\nif(~exist('FC_title_color_map', 'var'))\n    FC_title_color_map = 'Lux';\nend\n\n%minimum luminance\nLMin = min(L(:));\n\n%maximum luminance\nif(~exist('FC_LMax', 'var'))\n    LMax = max(L(:));\nelse\n    if(FC_LMax < 0)\n        LMax = max(L(:));\n    else\n        tLMax = max(L(:));\n        if(FC_LMax < tLMax)\n            LMax = tLMax;\n        else\n            LMax = FC_LMax - LMin;\n        end\n    end\nend\n\nFC_MAX_L = LMax;\n\n%luminance compression\nepsilon = 1e-6; %for avoiding singularities\nswitch FC_compress\n    case 'log2'\n        L = log2(L + epsilon);\n        LMax = log2(LMax + epsilon);\n        LMin = log2(LMin + epsilon);   \n        \n    case 'log'\n        L = log(L + epsilon);    \n        LMax = log(LMax + epsilon);\n        LMin = log(LMin + epsilon);\n        \n    case 'log10'\n        L = log10(L + epsilon);\n        LMax = log10(LMax + epsilon);\n        LMin = log10(LMin + epsilon);\n        \n    case 'sigmoid'\n        L = (L ./ (L + 1.0)).^(1.0 / 2.2);\n        LMax = (LMax ./ (LMax + 1.0)).^(1.0 / 2.2);\n        LMin = (LMin ./ (LMax + 1.0)).^(1.0 / 2.2);\n        \n    otherwise\nend\n\n%creating ticks for the visualization\nif(FC_Vis)\n    delta = LMax - LMin;\n    yticks = LMin:(delta / 4):LMax;\n\n    switch FC_compress\n        case 'log2'\n            yticks = 2.^yticks - epsilon;\n        case 'log'\n            yticks = exp(yticks) - epsilon;\n        case 'log10'\n            yticks = 10.^yticks - epsilon;\n        case 'sigmoid'\n            yticks = yticks.^2.2;\n            yticks = yticks ./ (1.0 - yticks);\n        otherwise\n    end\nend\n\nL = L - LMin;\nLMax = LMax - LMin;\nL = L / LMax;\n\ncontrast = 1.0;\nL = L.^(1.0 / contrast);\n\n%Create a color map\nn_bit = 8;\nres = 2^n_bit;\ncolor_map = colormap(jet(res));\n%color_map = ldrimread('fc_colormap.png');\n\n\n%Coloring using the colormap\nL = ClampImg(round(L * res), 1, res);\nimgOut = ind2rgb(L, color_map);\n\nif(FC_Vis)%Visualization  \n    close(FC_figure);\n    h = figure(FC_figure);\n    axes1 = axes('Parent', h);\n    axis off\n    hold(axes1,'on');\n\n    set(h, 'Name', FC_title);\n    \n    image(imgOut, 'Parent', axes1);%'InitialMagnification', 'fit');\n    colormap(color_map);\n    \n    box(axes1,'on');\n    axis(axes1,'ij');\n    set(axes1,'DataAspectRatio',[1 1 1],'Layer','top','TickDir','out');\n\n    if(FC_lin)\n        str = {sprintf('%2.1f', yticks(1)), sprintf('%2.1f', yticks(2)), sprintf('%2.1f', yticks(3)), sprintf('%2.1f', yticks(4)), sprintf('%2.1f', yticks(5))};\n    else\n        str = {sprintf('%2.1e', yticks(1)), sprintf('%2.1e', yticks(2)), sprintf('%2.1e', yticks(3)), sprintf('%2.1e', yticks(4)), sprintf('%2.1e', yticks(5))};\n    end\n       \n\n\n    hcb = colorbar('peer',axes1, 'Position',...\n    [0.743515850144089 0.299424184261036 0.0374639769452479 0.566218809980805],...\n    'Ticks',[0 0.25 0.5 0.75 1],...    \n    'Ticks', 0:(1/4):1 ,'YtickLabel', str);%, 'Position',...\n%    [0.329470198675497 0.345738295318127 0.302152317880795 0.0261944917126994]);\n    \n    set(hcb, 'FontSize', 24);\n    set(hcb, 'FontName', 'Times New Roman');\n    \n    pos = hcb.Position;\n    set(get(hcb, 'XLabel'), 'Rotation', 0, 'String', FC_title_color_map, 'FontSize', 24, 'FontName', 'Times New Roman', 'Position', [pos(1), 0.0 , 0.0]);\n    hold(axes1,'off');\n    \nend\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/Tools/FalseColor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5774180886917658}}
{"text": "% MAIN.m\n%\n% Solve the cart-pole swing-up problem  --  minimum time\n%\n% Note:  This problem is much more difficult to solve than the\n% minimum-force version. This is because most of the control trajectory is\n% sitting on a constraint: the maximum or minimum control force. This is\n% generally true of minimum-time trajectories: they have bang-bang\n% solutions. To get the exact solution, you would need to do many steps of\n% mesh refinement. Here I only do two iterations, to keep total time\n% reasonable. Another problem with minimum-time objective functions is that\n% they sometimes have singular arcs: solutions where there is no single\n% best control trajectory. This will manifest itself as \"chattering\" in the\n% control trajectory and slow convergence. One solution is to include a\n% regularization term, such as force squared with a very small coefficient,\n% which forces a unique solution along the singular arc.\n%\n\nclc; clear;\naddpath ../../\n\np.m1 = 2.0;  % (kg) Cart mass\np.m2 = 0.5;  % (kg) pole mass\np.g = 9.81;  % (m/s^2) gravity\np.l = 0.5;   % (m) pendulum (pole) length\n\ndist = 1.0;  %How far must the cart translate during its swing-up\nmaxForce = 50;  %Maximum actuator forces\n\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                     Set up function handles                             %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nproblem.func.dynamics = @(t,x,u)( cartPoleDynamics(x,u,p) );\nproblem.func.pathObj = @(t,x,u)( ones(size(t)) ); \n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                     Set up problem bounds                               %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nproblem.bounds.initialTime.low = 0;\nproblem.bounds.initialTime.upp = 0;\nproblem.bounds.finalTime.low = 0.01;\nproblem.bounds.finalTime.upp = inf;\n\nproblem.bounds.initialState.low = zeros(4,1);\nproblem.bounds.initialState.upp = zeros(4,1);\nproblem.bounds.finalState.low = [dist;pi;0;0];\nproblem.bounds.finalState.upp = [dist;pi;0;0];\n\nproblem.bounds.state.low = [-2*dist;-2*pi;-inf;-inf];\nproblem.bounds.state.upp = [2*dist;2*pi;inf;inf];\n\nproblem.bounds.control.low = -maxForce;\nproblem.bounds.control.upp = maxForce;\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                    Initial guess at trajectory                          %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nproblem.guess.time = [0,2];\nproblem.guess.state = [problem.bounds.initialState.low, problem.bounds.finalState.low];\nproblem.guess.control = [0,0];\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                         Solver options                                  %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nproblem.options(1).nlpOpt = optimset(...\n    'Display','iter',...\n    'TolFun',1e-3,...\n    'MaxFunEvals',1e5);\nproblem.options(1).method = 'trapezoid';\nproblem.options(1).trapezoid.nGrid = 10;\n\nproblem.options(2).nlpOpt = optimset(...\n    'Display','iter',...\n    'TolFun',1e-6,...\n    'MaxFunEvals',1e5);\nproblem.options(2).method = 'trapezoid';\nproblem.options(2).trapezoid.nGrid = 30;\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                            Solve!                                       %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nsoln = optimTraj(problem);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                        Display Solution                                 %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n%%%% Unpack the simulation\nt = linspace(soln(end).grid.time(1), soln(end).grid.time(end), 150);\nz = soln(end).interp.state(t);\nu = soln(end).interp.control(t);\n\n%%%% Plots:\n\n%%%% Draw Trajectory:\n[p1,p2] = cartPoleKinematics(z,p);\n\nfigure(2); clf;\nnFrame = 9;  %Number of frames to draw\ndrawCartPoleTraj(t,p1,p2,nFrame);\n\n\n%%%% Show the error in the collocation constraint between grid points:\n%\nif strcmp(soln(end).problem.options.method,'trapezoid') || strcmp(soln(end).problem.options.method,'hermiteSimpson')\n    % Then we can plot an estimate of the error along the trajectory\n    figure(5); clf;\n    \n    % NOTE: the following commands have only been implemented for the direct\n    % collocation(trapezoid, hermiteSimpson) methods, and will not work for\n    % chebyshev or rungeKutta methods.\n    cc = soln(end).interp.collCst(t);\n    \n    subplot(2,2,1);\n    plot(t,cc(1,:))\n    title('Collocation Error:   dx/dt - f(t,x,u)')\n    ylabel('d/dt cart position')\n    \n    subplot(2,2,3);\n    plot(t,cc(2,:))\n    xlabel('time')\n    ylabel('d/dt pole angle')\n    \n    idx = 1:length(soln(end).info.error);\n    subplot(2,2,2); hold on;\n    plot(idx,soln(end).info.error(1,:),'ko');\n    title('State Error')\n    ylabel('cart position')\n    \n    subplot(2,2,4); hold on;\n    plot(idx,soln(end).info.error(2,:),'ko');\n    xlabel('segment index')\n    ylabel('pole angle');\nend\n\n%%%% Plot the state and control against time\nfigure(1); clf;\nplotPendulumCart(t,z,u,p);\n\n\n\n\n\n\n", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/cartPole/MAIN_minTime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5774180886917658}}
{"text": "% Demonstration of generative model functions.\n%\n% See GENERATIVE_MODEL and EVALUATE_GENERATIVE_MODEL for further details\n% and interpretation.\n\nclear\nclose all\nclc\n\ndata = load('demo_generative_models_data');\nA     = data.A;\nAseed = data.Aseed;\nD     = data.D;\n\n% get cardinality of network\nn = length(A);\n\n% set model type\nmodeltype = 'sptl';\n\n% set whether the model is based on powerlaw or exponentials\nmodelvar = [{'powerlaw'},{'powerlaw'}];\n\n% choose some model parameters\nnparams = 100;\nparams = unifrnd(-10,0,nparams,1);\n\n% generate synthetic networks and energy for the neighbors model;\n[B,E,K] = evaluate_generative_model(Aseed,A,D,modeltype,modelvar,params);\nX = [E,K];\n\n% show scatterplot of parameter values versus energy and KS statistics\nnames = [...\n    {'energy'},...\n    {'degree'},...\n    {'clustering'},...\n    {'betweenness'},...\n    {'edge length'}];\n\nf = figure(...\n    'units','inches',...\n    'position',[2,2,4,4]);\nfor i = 1:size(X,2)\n    subplot(3,2,i);\n    scatter(params,X(:,i),100,X(:,i),'filled');\n    set(gca,...\n        'ylim',[0,1],...\n        'clim',[0,1]);\n    colormap(jet);\n    xlabel('geometric parameter, \\eta');\n    ylabel(names{i});\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/2019_03_03_BCT/data_and_demos/demo_generative_models_geometric.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5774180832293678}}
{"text": "function [ theta,f1,m,W_new,beta,grt ] = armijo_theta_fullcycle_v3( Ltheta,dir,f0,phi0, grad,grt,W,K,M,Pt,omega,Hd,Hr,G)\n    m=0;\n    rhom=0.95;\n    rho0=1/Ltheta*100;    \n    len=-real(grad'*dir);\n    sig=0.4;\n    while(1)\n        rho=rho0*rhom^m;\n        phi=phi0-rho*grad;\n        x=exp(1j.*phi);\n        [f1,W_new,beta,grt] = par_fun_B(x,W,K,M,Pt,omega,Hd,Hr,G);\n        if (f1-f0)>=sig*rho*len\n            break\n        end\n        if (rho)<1/Ltheta/10\n            break\n        end\n        m=m+1;\n    end\n    theta=x;\nend\n\n", "meta": {"author": "guohuayan", "repo": "WSR_maximization_for_RIS_system", "sha": "180ffe88b68ba792f5f1ddcce405bb6576067c92", "save_path": "github-repos/MATLAB/guohuayan-WSR_maximization_for_RIS_system", "path": "github-repos/MATLAB/guohuayan-WSR_maximization_for_RIS_system/WSR_maximization_for_RIS_system-180ffe88b68ba792f5f1ddcce405bb6576067c92/fig4/armijo_theta_fullcycle_v3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5774180776067398}}
{"text": "classdef MW13 < PROBLEM\n% <multi> <real> <large/none> <constrained>\n% Constrained benchmark MOP proposed by Ma and Wang\n\n%------------------------------- Reference --------------------------------\n% Z. Ma and Y. Wang, Evolutionary constrained multiobjective optimization:\n% Test suite construction and performance comparisons. IEEE Transactions on\n% Evolutionary Computation, 2019, 23(6): 972-986.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 15; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values and constraint violations\n        function Population = Evaluation(obj,varargin)\n            X = varargin{1};\n            X = max(min(X,repmat(obj.upper,size(X,1),1)),repmat(obj.lower,size(X,1),1));\n            z = 1 - exp(-10*(X(:,obj.M:end) - (repmat(obj.M:obj.D,size(X,1),1) - 1)/obj.D).^2);\n            g = 1 + sum((1.5 + (0.1/obj.D)*z.^2 - 1.5*cos(2*pi*z)),2);\n            PopObj(:,1) = g.*X(:,1)*1.5;\n            PopObj(:,2) = g.*(5 - exp(PopObj(:,1)./g) - abs(0.5*sin(3*pi*PopObj(:,1)./g)));\n            PopCon(:,1) = (5 - exp(PopObj(:,1)) - 0.5*sin(3*pi*PopObj(:,1)) - PopObj(:,2)).*(5 - (1 + 0.4*PopObj(:,1)) - 0.5*sin(3*pi*PopObj(:,1)) - PopObj(:,2));\n            PopCon(:,2) = -(5 - (1 + PopObj(:,1) + 0.5*PopObj(:,1).^2) - 0.5*sin(3*pi*PopObj(:,1)) - PopObj(:,2)).*(5 - (1 + 0.7*PopObj(:,1)) - 0.5*sin(3*pi*PopObj(:,1)) - PopObj(:,2));\n            Population  = SOLUTION(X,PopObj,PopCon,varargin{2:end});\n            obj.FE      = obj.FE + length(Population);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1)  = (0:1.5/(N-1):1.5)';\n            R(:,2)  = 5 - exp(R(:,1)) - 0.5*abs(sin(3*pi*R(:,1)));\n            c1      = (5-exp(R(:,1))-0.5*sin(3*pi*R(:,1))-R(:,2)).*(5-(1+0.4*R(:,1))-0.5*sin(3*pi*R(:,1))-R(:,2));\n            invalid = c1>0;\n            while any(invalid)\n                R(invalid,:) = R(invalid,:).*1.001;\n                c1      = (5-exp(R(:,1))-0.5*sin(3*pi*R(:,1))-R(:,2)).*(5-(1+0.4*R(:,1))-0.5*sin(3*pi*R(:,1))-R(:,2));\n                invalid = c1>0;\n            end\n            R = R(NDSort(R,1)==1,:);\n        end\n        %% Generate the feasible region\n        function R = GetPF(obj)\n            [x,y] = meshgrid(linspace(0,2,400),linspace(0,4.5,400));\n            z     = nan(size(x));\n            fes1  = (5-exp(x)-0.5*sin(3*pi*x)-y).*(5-(1+0.4*x)-0.5*sin(3*pi*x)-y) <= 0;\n            fes2  = -(5-(1+x+0.5*x.^2)-0.5*sin(3*pi*x)-y).*(5-(1+0.7*x)-0.5*sin(3*pi*x)-y) <= 0;\n            z(fes1 & fes2 & exp(x)+abs(0.5*sin(3*pi*x))+y>=5) = 0;\n            R = {x,y,z};\n        end\n    end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/MW/MW13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937772, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5773761591857133}}
{"text": "function f = sum( f, dim )\n%SUM   Definite Integration of a DISKFUN.\n%   G = sum(F,DIM) where DIM is 1 or 2 integrates only over theta \n%   (angular direction) or r (radial direction) respectively,\n%   and returns as its output a chebfun in the remaining variable.\n%\n%   G = sum(F) is the same as sum(F,1)\n%\n% See also SUM2. \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    f = []; \n    return; \nend\n\n% Default to radial direction: \nif ( nargin == 1 )\n    dim = 1;\nend\n\n% Get the low rank representation for f. \n[cols, D, rows] = cdr(f);\ndom = f.domain; \n%restrict cols to match domain\n \n\nif ( dim == 1 )  \n    % Integrate over r. Need to include the measure on the disk.\n    r = chebfun('x');\n    cols = r.*cols;\n    cols = restrict(cols, [0 1]);\n    f = rows * ( sum(cols) * D ).';\n    if ( isa(f, 'chebfun') ) \n        f = simplify( f, [], 'globaltol' ); \n    else\n        % f = double \n        f = chebfun(f, dom(1:2)).'; \n    end\nelseif ( dim == 2 )\n    f = cols * ( D * sum( rows ).' );\n    if  ( isa(f, 'chebfun') ) \n        f = simplify( f.', [], 'globaltol' );\n    else\n        f = chebfun( f, dom(3:4) ); \n    end\nelse \n    error('CHEBFUN:DISKFUN:sum:unknown', ...\n          'Undefined function ''sum'' for that dimension');\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/@diskfun/sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5773761561495853}}
{"text": "%% alternating minimization scheme for low-rank+sparse decomposition\n\nZ_norm=norm(Z(:));\nstat.ener=[]; stat.ener(1)=vm.f(A,B);\nif input_sig==1\nA_norm=norm(A_0(:));\nB_norm=norm(B_0(:));\nstat.err_a=[]; stat.err_a(1)=norm(A(:)-A_0(:))/A_norm;\nstat.err_b=[]; stat.err_b(1)=norm(B(:)-B_0(:))/B_norm;\nend\nstat.f_a=[]; stat.f_a(1)=norm(proj_fr(A+B-Z,U,V),'fro');\n% stat.f_b=[]; %stat.f_b(1)=norm(proj_l0(A+B-Z,B),'fro');\n% stat.ts1=[]; stat.ts2=[];\n% stat.vi1=[]; stat.vi2=[];\nstat.ang1=[]; stat.ang2=[];\nstat.ls_count=[];\nstat.cg_count=[];\nstat.n3=[]; stat.n3(1)=n3;\nstat.n4=[]; stat.n4(1)=n4;\nstat.sfg_a=[]; stat.sfg_b=[];\nstat.cpu=[]; %stat.cpu=time_main;\nif ~isempty(A_ref), stat.diff_a=[]; stat.diff_a=norm(A(:)-A_ref(:))/A_norm; end\nif ~isempty(B_ref), stat.diff_b=[]; stat.diff_b=norm(B(:)-B_ref(:))/B_norm; end\nA_old=A; B_old=B;\n\n% I1=eye(n1); I2=eye(n2);\nwaiting=waitbar(0,'iterating...');\n%time_main=tic;\nfor k=1:slv.kmax\n    waiting=waitbar(k/slv.kmax);\n    \n    % A-subproblem \n    if sg.sig~=1\n    % first shot via partial SVD\n    [U,S,V]=lansvd(Z-B,n3);\n    A=U*S*V';\n    \n    % safeguard by projected dogleg method\n    v1=A_old(:)-A(:);\n    stat.ang1(end+1)=(vm.f(A_old,B)-vm.f(A,B))/norm(v1(:))^2;\n    \n    if sg.sig==2 && stat.ang1(end)<sg.thr\n        A=A_old;\n        stat.sfg_a(end+1)=1;\n        disp(['A safeguarded by Riemannian optim at iter ',num2str(k)])\n        riem_optim\n    else\n        stat.sfg_a(end+1)=0;\n    end\n    \n    else    % directly via projected dogleg method\n        riem_optim\n    end\n    \n    % B-subproblem by sorting\n    B=rtr_l0(Z-A,n4);\n    \n    % safeguard\n    v1=B_old(:)-B(:);\n    stat.ang2(end+1)=(vm.f(A,B_old)-vm.f(A,B))/norm(v1(:))^2;\n    \n    if sg.sig~=0 && stat.ang2(end)<sg.thr\n        B=Z-A; B(B_old==0)=0;\n        stat.ang2(end)=.5;\n        stat.sfg_b(end+1)=1;\n        disp(['B safeguarded at iter ',num2str(k)])\n    else\n        stat.sfg_b(end+1)=0;\n    end\n    \n%     fprintf('|A^k-A^{k-1}|=%1.4e\\n',norm(A(:)-A_old(:)))\n    \n    \n    % trimming\n    trimming\n    \n    \n    % stats\n    %stat.cpu(end+1)=stat.cpu(1)+toc(time_main);\n    stat.ener(end+1)=vm.f(A,B);\n    if input_sig==1\n    stat.err_a(end+1)=norm(A(:)-A_0(:))/A_norm;\n    stat.err_b(end+1)=norm(B(:)-B_0(:))/B_norm;\n    end\n    stat.f_a(end+1)=norm(proj_fr(vm.g(A,B_old),U,V),'fro');\n%     stat.f_b(end+1)=norm(proj_l0(A+B-Z,B),'fro');\n    if ~isempty(A_ref), stat.diff_a(end+1)=norm(A(:)-A_ref(:))/A_norm; end\n    if ~isempty(B_ref), stat.diff_b(end+1)=norm(B(:)-B_ref(:))/B_norm; end\n    stat.n3(end+1)=n3; stat.n4(end+1)=n4;\n    \n%     if sg.sig==1, cg.tol=1e-2*(stat.f_a(end)/stat.f_a(1))^.2; end\n    \n    % stopping rule\n    if stat.f_a(end)<slv.ktol*stat.f_a(1)\n%     if stat.err_a(end)<slv.ktol\n% \tif stat.ener(end-1)-stat.ener(end)<slv.ktol*stat.ener(end-1)\n        break\n    end\n    \n    A_old=A;\n    B_old=B;\nend\n%toc(time_main)\nclose(waiting)\n\n% [sum(stat.ls_count),sum(stat.cg_count)]\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/R2PCP/slv_lrs_ams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937772, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5773761538395483}}
{"text": "function [TAR,FAR,threshold] = rocplot(match, nonmatch)\n%TAR=Ver\n\n%match=-match;\n%nonmatch=-nonmatch;\n\n R1=min([match; nonmatch]);\n R2=max([nonmatch;match]);\n\na=100/(R2-R1);\nb=-a*R1;\n\nmatchN=a*match+b;\nmatchN(matchN<0)=0;\nnonmatch_score=a*nonmatch+b;\nTAR=[1:length(matchN)]'/length(matchN);\nFRR=1-TAR;\n\nnonmatchL=zeros(size(matchN));\nsmatch=sort(matchN);\nfor i=1:length(nonmatch_score)\n    low=1;\n    high=length(smatch);\n\twhile low <=high\n\t\tmid=ceil((low+high)*.5);\n%[nonmatch_score(i),smatch(mid)]\n\t\tif nonmatch_score(i)>smatch(mid) low=mid+1;\n\t\telse high=mid-1;\n\t\tend\n\tend\n\n %   [val,idx]=min((nonmatch_score(i)>smatch));\n %    nonmatchL(idx)=nonmatchL(idx)+1;\n\tif low > length(smatch) \n\tlow= length(smatch);\n\tend\n    nonmatchL(low)=nonmatchL(low)+1;\nend\ncnonmatchL=cumsum(nonmatchL);\nFAR=cnonmatchL/cnonmatchL(end);\niind=find(FAR>=0.1);\nVER1= TAR(iind(1));\niind=find(FAR>=0.01);\nVER01= TAR(iind(1));\niind=find(FAR>=0.001);\nVER001= TAR(iind(1));\n\nthreshold=(smatch-b)/a;\n\n\n", "meta": {"author": "happynear", "repo": "FaceVerification", "sha": "c8c2b4d805abf7240d9d39d7b57151e04958f6bf", "save_path": "github-repos/MATLAB/happynear-FaceVerification", "path": "github-repos/MATLAB/happynear-FaceVerification/FaceVerification-c8c2b4d805abf7240d9d39d7b57151e04958f6bf/rocplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5773761454572556}}
{"text": "%+========================================================================+\n%|                                                                        |\n%|            This script uses 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%|             francois.alouges@polytechnique.edu                         |\n%| WEBSITE   : www.cmap.polytechnique.fr/~aussal/gypsilab    \u00a0\u00a0\u00a0\u00a0         |\n%|                                                                        |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it.                                                      |\n%|________________________________________________________________________|\n%|   '&`   |                                                              |\n%|    #    |   FILE       : nrtDomND.m                                    |\n%|    #    |   VERSION    : 0.40                                          |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |\n%|  ( # )  |   CREATION   : 14.03.2017                                    |\n%|  / 0 \\  |   LAST MODIF : 14.03.2018                                    |\n%| ( === ) |   SYNOPSIS   : Multi-dimensional quadrature                  |\n%|  `---'  |                                                              |\n%+========================================================================+\n\n% Cleaning\nclear all\nclose all\nclc\n\n% Gypsilab path\nrun('../../addpathGypsilab.m')\n\n% Tetra mesh\nNvtx = 1e2;\nL    = [5 4 3];\nmesh = mshCube(Nvtx,L);\n\n% Boundary mesh\nbound = mesh.bnd;\nctr   = bound.ctr;\nbound.col(ctr(:,3)==0.5*L(3)) = 1;\n\n% Upperface\nupperface = bound.sub(bound.col==1); \nrectangle = upperface.bnd;\n\n% Domain\nomega = dom(mesh,5);\nfigure\nplot(mesh)\nhold on\nplot(omega)\nalpha(0.2)\naxis equal\nview(30,30)\n\n% Boundary domain\nsigma = dom(bound,3);\nfigure\nplot(bound)\nhold on\nplot(sigma,'.y')\nplotNrm(sigma,'y')\nalpha(0.5)\naxis equal\nview(30,30)\n\n% Rectangle\ngamma = dom(rectangle,3);\nfigure\nplot(rectangle)\nhold on\nplot(gamma)\nalpha(0.5)\naxis equal\nview(30,30)\n\n% Numerical integration on the cube\nfct = @(X) ones(size(X,1),1);\nV   = integral(omega,fct);\nnorm(V-prod(L),'inf')\n\n% Numerical integration on the bundary of the cube\nfct = @(X) ones(size(X,1),1);\nS   = integral(sigma,fct);\nnorm(S-2*(L(1)*L(2)+L(2)*L(3)+L(1)*L(3)),'inf')\n\n% Numerical integration on the rectangle\nfct = @(X) ones(size(X,1),1);\nP   = integral(gamma,fct);\nnorm(P-2*(L(1)+L(2)),'inf')\n\n\ndisp('~~> Michto gypsilab !')\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/gypsilabModified/nonRegressionTest/domainQuadrature/nrtDomND.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5773761398690601}}
{"text": "function M = oned_bilinear ( kernel, phi, test, w_g )\n\n%*****************************************************************************80\n%\n%% ONED_BILINEAR integrates a kernel times a basis times a test function.\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%    Jeff Borggaard\n%\n%  Parameters:\n%\n%    Input, real KERNEL(N_GAUSS), the kernel function evaluated\n%    at the Gauss points.\n%\n%    Input, real PHI(N_GAUSS,N_DOF), the element test functions evaluated\n%    at the Gauss points.\n%\n%    Input, real TEST(N_GAUSS,N_TEST), the test functions evaluated \n%    at the Gauss points.        \n%\n%    Input, real W_G(N_GAUSS), the Gauss weights.\n%\n%    Output, real M(N_TEST,N_DOF), the integral values.\n%\n  M = test' * diag ( kernel .* w_g ) * 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/heat_oned/oned_bilinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5773616608432561}}
{"text": "function [T1, M0] = Compute_M0_T1_OnSPGR(data, flipAngles, TR, b1Map, roi, verbose)\n%Perform a simple linear-least squares data fit on variable flip angle SPGR data \n%\n% function [M0, T1] = Compute_M0_T1_OnSPGR(data, flipAngles, TR [, b1Map, roi, verbose])\n% -----------------------------------------------------------\n% INPUTS:\n%   data: width x length x slices x flipAngles matrix\n%   flipAngles: vector of flip angles (in degrees) corresponding to last dimension of 'data'\n%   TR: Repetition time in seconds\n%   b1Map: width x length x slices matrix containing relative flip angle\n%         (i.e. if nominal alpha is 60 and measured alpha is 61, then b1Map = 61/60\n%   roi: width x length x slices binary mask \n%   verbose: logical - for debugging\n\n\nif ndims(data)<3, data = permute(data(:),[2 3 4 1]); end\n[nX, nY, nZ, nFlip] = size(data);\nnVox = nX*nY*nZ;\n\nif ~exist('b1Map', 'var') || isempty(b1Map)\n    b1Map = ones(nX, nY, nZ);\nend\n\nif ~exist('roi', 'var') || isempty(roi)\n    roi = true(nX, nY, nZ);\nend\n\nif ~exist('verbose', 'var')\n    verbose = 0;\nend\n \nif length(b1Map) ~= length(data(:,:,:,1)), error('B1 size is different from data size'); end\nif ~islogical(roi), roi = logical(roi); end\n\n% Reshape data into 2D array so that future steps are simpler\ndata = reshape(data,[nVox nFlip])'; % Transpose because MATLAB is column-major\ndata = data(:, roi(:));\nnVox = sum(roi(:));\n\n% Large matrix with redundant values will make computations faster,\n% but will also consume more memory\nalpha = deg2rad(flipAngles);\nif isrow(alpha), alpha = alpha'; end\nalpha = repmat(alpha,[1 nVox]) .* repmat(b1Map(roi(:))', [nFlip 1]);\n\n% Do the linear least squares fit and estimate M0 & T1\ny = data ./ sin(alpha);\nx = data ./ tan(alpha);\n[fittedSlope, fittedIntercept] = LinLeastSquares(x,y);\nestM0 = fittedIntercept ./ (1-fittedSlope);\nestT1 = -TR./log(fittedSlope);\n\n% Assign arbitrary M0 & T1 value if fitted value is unphysical. \n% Might be better to set this to NaN so users can identify voxels where fit fails\nfailedFit = isnan(fittedSlope)      | fittedSlope<0     | ...\n            isnan(fittedIntercept)  | fittedIntercept<0 ;\nfailedFitValue = NaN;\nestM0(failedFit) = failedFitValue;\nestT1(failedFit) = failedFitValue;\n\n% Assign estimated M0 and T1 values to correct voxel \n[T1, M0] = deal(zeros(nX,nY,nZ));\nM0(roi(:)) = estM0;\nT1(roi(:)) = estT1;\nend % END OF Compute_M0_T1_OnSPGR\n\nfunction [fittedSlope, fittedIntercept] = LinLeastSquares(x,y)\n% Simple linear least squares fit\n% Inputs:\n%   - x and y, arrays of equal sizes\n% The first dimension should contain the measurements\n% The second dimension could be different samples (e.g. voxels)\n\nif size(x)~=size(y), error('X and Y must have same size for linear fitting'); end\n% Use the fact that slope = cov(x,y) / cov(x,x)\nlengthX = size(x,1);\nnumerator = sum(x.*y) - sum(x).*sum(y) / lengthX;\ndenominator = sum(x.^2) - sum(x).^2 / lengthX;\nfittedSlope = numerator ./ denominator;\n% Line of best fit has to pass through point (meanX, meanY)\n% Use this fact to get intecept\nfittedIntercept = mean(y) - fittedSlope .* mean(x);\nend % END OF LinLeastSquares", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/MTVfun/Compute_M0_T1_OnSPGR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.577361649042671}}
{"text": "function sphere_llq_grid_line_count_test ( )\n\n%*****************************************************************************80\n%\n%% SPHERE_LLQ_GRID_LINE_COUNT_TEST tests SPHERE_LLQ_GRID_LINE_COUNT.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    28 April 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  lat_num = 3;\n  long_num = 4;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'SPHERE_LLQ_GRID_LINE_COUNT_TEST\\n' );\n  fprintf ( 1, '  SPHERE_LLQ_GRID_LINE_COUNT counts the lines used for a\\n' );\n  fprintf ( 1, '  grid based on quadrilaterals defined by latitude and longitude\\n' );\n  fprintf ( 1, '  lines on a sphere in 3D.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '     LAT_NUM    LONG_NUM   LINE_NUM\\n' );\n  for lat_num = 1 : 2 : 17\n    fprintf ( 1, '\\n' );\n    long_num = 1;\n    for long_log = 1 : 4\n      long_num = long_num * 2;\n      line_num = sphere_llq_grid_line_count ( lat_num, long_num );\n      fprintf ( 1, '  %8d  %8d  %8d\\n', lat_num, long_num, line_num );\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/sphere_llq_grid/sphere_llq_grid_line_count_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.5773307473405456}}
{"text": "function [ a, ipvt, info ] = zgefa ( a, lda, n )\n\n%*****************************************************************************80\n%\n%% ZGEFA factors a complex matrix by Gaussian elimination.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    29 April 2007\n%\n%  Author:\n%\n%    MATLAB version by John Burkardt\n%\n%  Reference:\n%\n%    Jack Dongarra, Cleve Moler, Jim Bunch and 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%\n%  Parameters:\n%\n%    Input, complex A(LDA,N), the matrix to be factored.\n%\n%    Input, integer LDA, the leading dimension of A.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Output, complex A(LDA,N); an upper triangular matrix and the multipliers\n%    which were used to obtain it.  The factorization can be written A = L*U\n%    where L is a product of permutation and unit lower triangular matrices\n%    and U is upper triangular.\n%\n%    Output, integer IPVT(N), the pivot indices.\n%\n%    Output, integer INFO,\n%    0, normal value.\n%    K, if U(K,K) == 0.0.  This is not an error condition for this\n%    subroutine, but it does indicate that ZGESL or ZGEDI will divide by zero\n%    if called.  Use RCOND in ZGECO for a reliable indication of singularity.\n%\n\n%\n%  Gaussian elimination with partial pivoting.\n%\n  info = 0;\n\n  for k = 1 : n - 1\n%\n%  Find L = pivot index.\n%\n    l = izamax ( n-k+1, a(k:n,k), 1 ) + k - 1;\n    ipvt(k) = l;\n%\n%  Zero pivot implies this column already triangularized.\n%\n    if ( zabs1 ( a(l,k) ) == 0.0 )\n      info = k;\n      continue;\n    end\n%\n%  Interchange if necessary.\n%\n    if ( l ~= k )\n      temp = a(l,k);\n      a(l,k) = a(k,k);\n      a(k,k) = temp;\n    end\n%\n%  Compute multipliers\n%\n    a(k+1:n,k) = - a(k+1:n,k) / a(k,k);\n%\n%  Row elimination with column indexing\n%\n    for j = k+1 : n\n      t = a(l,j);\n      if ( l ~= k )\n        a(l,j) = a(k,j);\n        a(k,j) = t;\n      end\n      a(k+1:n,j) = a(k+1:n,j) + t * a(k+1:n,k);\n    end\n\n  end\n\n  ipvt(n) = n;\n\n  if ( zabs1 ( a(n,n) ) == 0.0 )\n    info = 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/linpack_z/zgefa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5773307428700384}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\nfunction p = pnig(xnew, xold, t, r, alpha, beta, delta)\n% probability distribution of the NIG model\nd = delta * t;                          % time dependent parameter\n\ngamma = sqrt(alpha^2 - beta^2);\n\n% martingale correction removes the drift!\nomega = delta * gamma - delta*sqrt(alpha^2-(1+beta)^2); % martingale correction\n\nx = xnew -xold - (r - omega) * t;           % \narg = sqrt(1+(x./delta).^2);\n\np = real(alpha / pi * besselk(1,alpha .* d .* arg)./arg.* exp(d.*(gamma+beta.*(x./d))));\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/36966-risk-neutral-densities-for-financial-models/pnig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5772823336210352}}
{"text": "function aa=lpcrf2aa(rf)\n%LPCRF2AA Convert reflection coefficients to area function AA=(RF)\n%The areas are normalised so that aa(p+2)=1: the effective area of the free air beyond the lips.\n% aa(1) is the area of the glottis. This will be zero if rf(:,1)=1.\n\n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: lpcrf2aa.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\naa = fliplr(cumprod([ones(1,size(rf,1)); fliplr((1-rf)./(1+rf)).']).');\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/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/lpcrf2aa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5772823177769163}}
{"text": "%  demo_RoPS_FeatureMatching_Mesh.m\n%  Author: Yulan Guo {yulan.guo@nudt.edu.cn}\n%  NUDT, China & CSSE, UWA, Australia\n% This function performs feature matching on two input meshes to obtain feature\n% correspondences\n\nclose all;\nclc;\nclear all;\n\nkeypntNum = 1000;\n\nload ../../StanfordData/Bunny\nSelIdx = [ 1 3];\npcData0 = bunny{SelIdx(1)}';\ntmp = pcdownsample( pointCloud(pcData0'), 'gridAverage', 0.0015 );\npcData0 = tmp.Location';\npcData1 = bunny{SelIdx(2)}';\ntmp = pcdownsample( pointCloud(pcData1'), 'gridAverage', 0.0015 );\npcData1 = tmp.Location';\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nload data\\pointcloud_view1;\npointcloud = pcData0';\n% %============================transform a pointcloud into a triangular mesh============================%\nmesh = pointCloud2mesh(pointcloud,[0 0 1],0.4);                                         %other methods can also be used to perform triangulation\n%============================preprocessing============================%\nout = preprocessingFunc(mesh);\nmesh.faceCenter = out.centroid;\nmesh.faceArea = out.area;\nmesh.res = out.res ;\n%============================detect keypoints============================%\n%keypoints are randomly seleted in this demo, any other 3D keypoint detection methods can be used\ntemp = randperm(length(mesh.vertices));\nmesh.keypntIdx = temp(1:keypntNum);\n%============================extract RoPS features at the keypoints on a mesh============================%\npara.RoPS_nbSize = 15*mesh.res;\npara.RoPS_binSize = 5;\npara.RoPS_rotaSize = 3;\nmesh.LRF =  LRFforMeshFunc(mesh, mesh.keypntIdx, para.RoPS_nbSize);\ndisp('LRFs calculated');  \nRoPS = RoPSFunc(mesh, para.RoPS_nbSize, para.RoPS_binSize, para.RoPS_rotaSize,mesh.LRF);\nmesh.RoPS = RoPS;\ndisp(['RoPS features generated']);  \nmesh1 = mesh;\nmesh1Features = [];\nfor keypntIdx = 1:keypntNum\n    temp = trans2Dto1DFunc(mesh.RoPS{keypntIdx});\n    mesh1Features = [mesh1Features; temp];\nend \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nload data\\pointcloud_view2;\npointcloud = pcData1';\n% %============================transform a pointcloud into a triangular mesh============================%\nmesh = pointCloud2mesh(pointcloud,[0 0 1],0.4);                                         %other methods can also be used to perform triangulation\n%============================preprocessing============================%\nout = preprocessingFunc(mesh);\nmesh.faceCenter = out.centroid;\nmesh.faceArea = out.area;\nmesh.res = out.res ;\n%============================detect keypoints============================%\n%keypoints are randomly seleted in this demo, any other 3D keypoint detection methods can be used\ntemp = randperm(length(mesh.vertices));\nmesh.keypntIdx = temp(1:keypntNum);\n%============================extract RoPS features at the keypoints on a mesh============================%\npara.RoPS_nbSize = 15*mesh.res;\npara.RoPS_binSize = 5;\npara.RoPS_rotaSize = 3;\nmesh.LRF =  LRFforMeshFunc(mesh, mesh.keypntIdx, para.RoPS_nbSize);\ndisp('LRFs calculated');  \nRoPS = RoPSFunc(mesh, para.RoPS_nbSize, para.RoPS_binSize, para.RoPS_rotaSize,mesh.LRF);\nmesh.RoPS = RoPS;\ndisp(['RoPS features generated']);  \nmesh2 = mesh;\nmesh2Features = [];\nfor keypntIdx = 1:keypntNum\n    temp = trans2Dto1DFunc(mesh.RoPS{keypntIdx});\n    mesh2Features = [mesh2Features; temp];\nend \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %============================feature matching============================%\nNNDRthreshold = 0.9;\ncorNum = 0;\nkdtreeMesh1Features = KDTreeSearcher(mesh1Features,'Distance','euclidean');\nfor keypntIdx1 = 1:size(mesh2Features,1)\n    [idxSort,distSort] = knnsearch(kdtreeMesh1Features, mesh2Features(keypntIdx1,:),'k',2,'Distance','euclidean');\n    IDX = idxSort(1);\n    if distSort(1)/distSort(2)<=NNDRthreshold\n        corNum = corNum+1;\n        corPntIdx(corNum,:) = [IDX, keypntIdx1];\n        featureDis(corNum) = distSort(1);\n    end\nend\nshowCorresFunc(mesh1, mesh2, mesh1.keypntIdx(corPntIdx(:,1)), mesh2.keypntIdx(corPntIdx(:,2)), [0,200,0]);\n\n%============================links============================%\n%we may find more test datasets via the following links\n% url = 'https://sites.google.com/site/yulanguo66/research-resources/3d-object-recognition-datasets';\n% web(url,'-browser')\n\n\n", "meta": {"author": "DrGabor", "repo": "LiDAR", "sha": "707ca635db955cf00d833578ad1236f0790cdf98", "save_path": "github-repos/MATLAB/DrGabor-LiDAR", "path": "github-repos/MATLAB/DrGabor-LiDAR/LiDAR-707ca635db955cf00d833578ad1236f0790cdf98/RoPSMatcher/RoPS Toolbox2/demo_RoPS_FeatureMatching_Mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5772823177769162}}
{"text": "function CPad = directFilter(A,D,tensorOrder,lambda)\n% bsarray\\directFilter: compute B-spline coefficients from data array\n% usage: C = directFilter(A,D,tensorOrder,lambda);\n%\n% arguments: \n%   A - N-dimensional array (vector, image, volume, etc.)\n%   D (1xN vector) - degree of each dimension of tensor product BSpline.\n%   tensorOrder (scalar) - number of nonsingleton dimensions of A\n%   lambda (1xN vector) - smoothing factor for each dimension\n%\n%   C - array of BSpline coefficients\n%\n\n% author: Nathan D. Cahill\n% email: ndcahill@gmail.com\n% date: 18 April 2008\n\n% if D = 0 or 1, and lambda = 0, return A, with reflection padding\nif all(D<2) && all(lambda==0)\n    padNum = floor(D/2);\n    idx   = cell(1,tensorOrder);\n    for k = 1:tensorOrder\n        M = size(A,k);\n        dimNums = [1:M (M-1):-1:2];\n        p = padNum(k);\n        idx{k}   = dimNums(mod(-p:M+p, 2*M-2) + 1);\n    end\n    CPad = A(idx{:});\n    return;\nend\n\n% get coefficients for BSpline filters\nF = cell(tensorOrder,1);\nF0 = cell(tensorOrder,1);\nfor i=1:tensorOrder\n    % NEED TO UPDATE THIS TO SCALE LAMBDA FOR ELEMENT SPACING\n    [F{i},F0{i}] = getBSplineFiltCoeffs(D(i),true,'direct',lambda(i));\nend\n\n% initialize output\nC = double(A);\n\n% choose tolerance for K0\nK0Tol = eps;\n\nswitch tensorOrder\n    case 1 % X is a vector - easy case\n        \n        CLen = numel(C);\n        \n        % loop through poles of direct BSpline filter\n        for i = 1:length(F{1})\n            \n            % compute K0 for current pole\n            K0 = ceil(log(K0Tol)./log(abs(F{1}(i))));\n            \n            % now compute vector of indices of length K0 that runs back and\n            % forth through the length of the data vector (to mimic\n            % reflection of the data at each end)\n            indReflect = [1:CLen (CLen-1):-1:2];\n            numReps = ceil(K0/(2*CLen-2));\n            KVec = repmat(indReflect,[1 numReps]);\n            KVec = KVec(1:K0);\n                        \n            % compute scaling factor for current pole\n            C0 = -F{1}(i)./(1-F{1}(i)^2);\n            \n            % apply symmetric exponential filter\n            C(:) = symExpFilt(C(:),CLen,C0,F{1}(i),K0,KVec);\n        \n        end\n        \n        % multiply by numerator of direct BSpline filter\n        C = real(C)*F0{1};\n        \n    case 2 % X is a matrix - a little more difficult\n        \n        % first perform direct filtering over each column\n        [CRows,CCols] = size(C);\n        \n        % loop through poles of direct BSpline filter\n        for i = 1:length(F{1})\n            \n            % compute K0 for current pole\n            K0 = ceil(log(K0Tol)./log(abs(F{1}(i))));\n            \n            % now compute vector of indices of length K0 that runs back and\n            % forth through the length of the data vector (to mimic\n            % reflection of the data at each end)\n            indReflect = [1:CRows (CRows-1):-1:2];\n            numReps = ceil(K0/(2*CRows-2));\n            KVec = repmat(indReflect,[1 numReps]);\n            KVec = KVec(1:K0);\n                        \n            % compute scaling factor for current pole\n            C0 = -F{1}(i)./(1-F{1}(i)^2);\n            \n            % apply symmetric exponential filter for each column\n            for k = 1:CCols\n                C(:,k) = symExpFilt(C(:,k),CRows,C0,F{1}(i),K0,KVec);\n            end\n        end\n        \n        % multiply by numerator of direct BSpline filter\n        C = real(C)*F0{1};\n        \n        % now perform direct filtering across each row\n        % loop through poles of direct BSpline filter\n        for i = 1:length(F{2})\n            \n            % compute K0 for current pole\n            K0 = ceil(log(K0Tol)./log(abs(F{2}(i))));\n            \n            % now compute vector of indices of length K0 that runs back and\n            % forth through the length of the data vector (to mimic\n            % reflection of the data at each end)\n            indReflect = [1:CCols (CCols-1):-1:2];\n            numReps = ceil(K0/(2*CCols-2));\n            KVec = repmat(indReflect,[1 numReps]);\n            KVec = KVec(1:K0);\n                        \n            % compute scaling factor for current pole\n            C0 = -F{2}(i)./(1-F{2}(i)^2);\n            \n            % apply symmetric exponential filter for each column\n            for k = 1:CRows\n                C(k,:) = symExpFilt(C(k,:),CCols,C0,F{2}(i),K0,KVec);\n            end\n        end\n        \n        % multiply by numerator of direct BSpline filter\n        C = real(C)*F0{2};\n        \n    case 3 % X is a volume - a bit more difficult\n    \n        % first perform direct filtering over each column\n        [CRows,CCols,CSlices] = size(C);\n        \n        % loop through poles of direct BSpline filter\n        for i = 1:length(F{1})\n            \n            % compute K0 for current pole\n            K0 = ceil(log(K0Tol)./log(abs(F{1}(i))));\n            \n            % now compute vector of indices of length K0 that runs back and\n            % forth through the length of the data vector (to mimic\n            % reflection of the data at each end)\n            indReflect = [1:CRows (CRows-1):-1:2];\n            numReps = ceil(K0/(2*CRows-2));\n            KVec = repmat(indReflect,[1 numReps]);\n            KVec = KVec(1:K0);\n                        \n            % compute scaling factor for current pole\n            C0 = -F{1}(i)./(1-F{1}(i)^2);\n            \n            % apply symmetric exponential filter for each column\n            for k = 1:CSlices\n                for j = 1:CCols\n                    C(:,j,k) = symExpFilt(C(:,j,k),CRows,C0,F{1}(i),K0,KVec);\n                end\n            end\n        end\n        \n        % multiply by numerator of direct BSpline filter\n        C = real(C)*F0{1};\n        \n        % now perform direct filtering across each row\n        % loop through poles of direct BSpline filter\n        for i = 1:length(F{2})\n            \n            % compute K0 for current pole\n            K0 = ceil(log(K0Tol)./log(abs(F{2}(i))));\n            \n            % now compute vector of indices of length K0 that runs back and\n            % forth through the length of the data vector (to mimic\n            % reflection of the data at each end)\n            indReflect = [1:CCols (CCols-1):-1:2];\n            numReps = ceil(K0/(2*CCols-2));\n            KVec = repmat(indReflect,[1 numReps]);\n            KVec = KVec(1:K0);\n                        \n            % compute scaling factor for current pole\n            C0 = -F{2}(i)./(1-F{2}(i)^2);\n            \n            % apply symmetric exponential filter for each column\n            for k = 1:CSlices\n                for j = 1:CRows\n                    C(j,:,k) = symExpFilt(C(j,:,k),CCols,C0,F{2}(i),K0,KVec);\n                end\n            end\n        end\n        \n        % multiply by numerator of direct BSpline filter\n        C = real(C)*F0{2};\n\n        % now perform direct filtering across each slice\n        % loop through poles of direct BSpline filter\n        for i = 1:length(F{3})\n            \n            % compute K0 for current pole\n            K0 = ceil(log(K0Tol)./log(abs(F{3}(i))));\n            \n            % now compute vector of indices of length K0 that runs back and\n            % forth through the length of the data vector (to mimic\n            % reflection of the data at each end)\n            indReflect = [1:CSlices (CSlices-1):-1:2];\n            numReps = ceil(K0/(2*CSlices-2));\n            KVec = repmat(indReflect,[1 numReps]);\n            KVec = KVec(1:K0);\n                        \n            % compute scaling factor for current pole\n            C0 = -F{3}(i)./(1-F{3}(i)^2);\n            \n            % apply symmetric exponential filter for each column\n            for k = 1:CCols\n                for j = 1:CRows\n                    C(j,k,:) = symExpFilt(C(j,k,:),CSlices,C0,F{3}(i),K0,KVec);\n                end\n            end\n        end\n        \n        % multiply by numerator of direct BSpline filter\n        C = real(C)*F0{3};\n    \n    otherwise % X is multidimensional - the most difficult\n        \n        % get size of coefficients array\n        Csz = size(C);\n        \n        % set up vector of indices into each dimension\n        idx = cell(1,tensorOrder);\n        for k = 1:tensorOrder\n            idx{k} = 1:size(C,k);\n        end\n        \n        % loop through each dimension\n        for d = 1:tensorOrder\n            \n            % copy original version of idx\n            idxCurrent = idx;\n            \n            % construct vector of indices which will be used in computing\n            % the initial element of the filtered data\n            indReflect = [1:Csz(d) (Csz(d)-1):-1:2];\n            \n            % construct list of dimensions without d\n            dimList = setdiff(1:tensorOrder,d);\n            \n            % construct index into entries of remaining dimensions\n            [idxCurrent{dimList}] = ndgrid(idx{dimList});\n            dimListInd = sub2ind(Csz(dimList),idxCurrent{dimList});\n            dimListInd = dimListInd(:);\n            \n            % loop through poles of BSpline filter\n            for i = 1:length(F{d})\n                \n                % compute K0 for current pole\n                K0 = ceil(log(K0Tol)./log(abs(F{d}(i))));\n\n                % now compute vector of indices of length K0 that runs back and\n                % forth through the length of the data vector (to mimic\n                % reflection of the data at each end)\n                numReps = ceil(K0/(2*Csz(d)-2));\n                KVec = repmat(indReflect,[1 numReps]);\n                KVec = KVec(1:K0);\n\n                % compute scaling factor for current pole\n                C0 = -F{d}(i)./(1-F{d}(i)^2);\n                \n                % now loop through remaining dimensions, applying symmetric\n                % exponential filter\n                for k=1:numel(dimListInd)\n                    [idxCurrent{dimList}] = ind2sub(Csz(dimList),dimListInd(k));\n                    C(idxCurrent{:}) = symExpFilt(C(idxCurrent{:}),Csz(d),C0,F{d}(i),K0,KVec);\n                end                \n            end\n            \n            % multiply by numerator of direct BSpline filter\n            C = real(C)*F0{d};\n\n        end\n        \nend\n\n% now pad dimensions by reflection\npadNum = floor(D/2);\n\n% Form index vectors to subsasgn input array into output array.\n% Also compute the size of the output array.\nidx   = cell(1,tensorOrder);\nfor k = 1:tensorOrder\n  M = size(C,k);\n  dimNums = [1:M (M-1):-1:2];\n  p = padNum(k);\n  idx{k}   = dimNums(mod(-p:M+p, 2*M-2) + 1);\nend\nCPad = C(idx{:});\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/19632-n-dimensional-bsplines/@bsarray/private/directFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571775, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5772823148385422}}
{"text": "function f = fuison_base_parts(b1, b2)\n% ZCA + l1 norm\n% featrue1 = whitening_norm(b1, 1, 0);\n% featrue2 = whitening_norm(b2, 1, 0);\n% figure;imshow(featrue1);\n% figure;imshow(featrue2);\n\n% f_sum = featrue1+featrue2;\n% f_sum(f_sum==0) = 1;\n\n% w1 = featrue1./f_sum;\n% w2 = featrue2./f_sum;\n% figure;imshow(w1);\n% figure;imshow(w2);\n\nw1 = 0.5;\nw2 = 0.5;\nf = w1.*b1+w2.*b2;\n% figure;imshow(f);\nend\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/mdlatlrr/fuison_base_parts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5772823067378701}}
{"text": "function [sz] = size(tt,p)\n%Mode sizes of the TT-matrix\n%   [SZ]=SIZE(TT) Returns the mode sizes of the TT-matrix as a dx2 array of\n%   integers\n%\n%   [SZ]=SIZE(TT,P) Returns the mode-P sizes of the TT-matrix as an array\n%   of d integers\n%\n%\n% TT-Toolbox 2.2, 2009-2012\n%\n%This is TT Toolbox, written by Ivan Oseledets et al.\n%Institute of Numerical Mathematics, Moscow, Russia\n%webpage: http://spring.inm.ras.ru/osel\n%\n%For all questions, bugs and suggestions please mail\n%ivan.oseledets@gmail.com\n%---------------------------\n\nif (nargin==1) || isempty(p)\n    n=tt.n; m=tt.m;\n    sz=[n,m];\nelse\n    switch p\n        case 1\n            sz=tt.n;\n        case 2\n            sz=tt.m;\n        otherwise\n            error('tt_matrix/size : illegal value of parameter p.\\n');\n    end\nend\n\nreturn\nend", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/@tt_matrix/size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788903594355, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5772491602614083}}
{"text": "function status = test_exp_imp(modus)\n%TEST_EXP_IMP tests the different expansions of sound fields in time-domain\n%\n%   Usage: status = test_exp_imp(modus)\n%\n%   Input parameters:\n%       modus   - 0: numerical\n%                 1: visual\n%\n%   Output parameters:\n%       status  - true or false\n%\n%   TEST_EXP_IMP(modus) checks, if the circular basis expansions for plane waves\n%   and point sources are working. The circular basis expansions are converted\n%   to plane wave decompositions. Additionally, modal weighting functions are\n%   tested. Optionally, sound field plots of the plane wave decompositions are\n%   used for verification.\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\nstatus = false;\n\n\n%% ===== Checking of input  parameters ===================================\nnargmin = 1;\nnargmax = 1;\nnarginchk(nargmin,nargmax);\n\n\n%% ===== Configuration ===================================================\n% Parameters\nconf = SFS_config;\nconf.plot.loudspeakers = 0;  % do not plot loudspeakers\nconf.plot.usedb = 1;  % use decibel for sound field plot\nconf.modal_window_parameter = 2.0;  % parameter for kaiser window\n\nc = conf.c;  % speed of sound\n\n% for sound field plots\nX = [-2, 2];\nY = [-2, 2];\nZ = 0;\n\nfhp = 1000;  % high-pass filter corner-frequency for pwd of point source\n\n% plane waves with equi-angular distribution\nNpw = 1024;\nphi0 = (0:Npw-1).'*2*pi/Npw;\nx0 = [cos(phi0) sin(phi0)];\nx0(:,3) = 0;\nx0(:,4:6) = x0(:,1:3);\nx0(:,7) = 1;\n\n% test scenarios\nscenarios = { ...\n  'pw', [ 0.0 -1.0 0.0],  5, 'rect'   , [0.0 0.0 0.0]\n  'pw', [ 0.0 -1.0 0.0], 15, 'rect'   , [0.0 0.0 0.0]\n  'pw', [ 0.0 -1.0 0.0], 15, 'kaiser' , [0.0 0.0 0.0]\n  'pw', [ 0.0 -1.0 0.0],  5, 'rect'   , [0.5 1.0 0.0]\n  'pw', [ 0.0 -1.0 0.0], 15, 'rect'   , [0.5 1.0 0.0]\n  'pw', [ 0.0 -1.0 0.0], 15, 'kaiser' , [0.5 1.0 0.0]\n  'ps', [ 0.0  2.5 0.0],  5, 'rect'   , [0.0 0.0 0.0]\n  'ps', [ 0.0  2.5 0.0], 15, 'rect'   , [0.0 0.0 0.0]\n  'ps', [ 0.0  2.5 0.0], 15, 'kaiser' , [0.0 0.0 0.0]\n  'ps', [ 0.0  2.5 0.0],  5, 'rect'   , [0.5 1.0 0.0]\n  'ps', [ 0.0  2.5 0.0], 15, 'rect'   , [0.5 1.0 0.0]\n  'ps', [ 0.0  2.5 0.0], 15, 'kaiser' , [0.5 1.0 0.0]\n  };\n\n%% ===== Main ============================================================\n\nfor ii=1:size(scenarios)\n\n    src = scenarios{ii,1};  % source type\n    xs = scenarios{ii,2};  % source position / direction of plane wave\n    Nce = scenarios{ii,3};  % modal order\n    conf.modal_window = scenarios{ii,4};  % type of modal weighting function\n    xq = scenarios{ii,5};  % expansion centre\n\n    % circular expansion coefficients\n    switch src\n    case 'pw'\n        [pm, delay_offset] = circexp_imp_pw(xs,Nce,xq,conf);\n        t = xq*xs.'./c;\n    case 'ps'\n        [pm, delay_offset] = circexp_imp_ps(xs,Nce,xq,fhp,conf);\n        t = norm(xq-xs)./c;\n    end\n\n    % modal weighting of coefficients\n    wm = modal_weighting(Nce, conf);\n    pm = bsxfun(@times, pm, wm);\n\n    % conversion to plane wave decomposition\n    ppwd = pwd_imp_circexp(pm, Npw);\n\n    if modus\n      % delay plane waves according to expansion centre\n      delays = -xq*x0(:,1:3).'./c;\n      delay_offset = delay_offset - min(delays);\n      delays = delays - min(delays);\n      ppwd = delayline(ppwd,delays,1,conf);\n\n      % sound field plot\n      sound_field_imp(X,Y,Z,x0,'pw',ppwd,t+delay_offset,conf);\n\n      % title string\n      str = 'Plane wave decompostion of modally bandlimited';\n      switch src\n      case 'pw'\n          str = sprintf('%s plane wave', str);\n      case 'ps'\n          str = sprintf('%s point source', str);\n      end\n      str = sprintf(['%s ([%1.1f %1.1f %1.1f]):\\n%s-window (M=%d), ' ...\n        'center of modal expansion at [%1.1f %1.1f %1.1f]'], ...\n        str, xs, conf.modal_window, Nce, xq);\n      title(str);\n\n    end\nend\n\nstatus = true;\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/validation/test_exp_imp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5772491584512868}}
{"text": "function [anchorIDs, featIDs, PrQfeatIDs] = sampleAnchorAndFeatIDsToSplitMerge( Psi, data, algParams );\n% Sample anchor ids and feature ids to perform split/merge move.\n% Every split-merge move is defined by:\n%   -- two *distinct* sequences (ii,jj), which we call \"anchors\"\n%   -- two features, ki and kj, where F(ii,ki)=1 and F(jj,kj) = 1\n% If ki == kj, we propose splitting these into two features,\n%   otherwise, we merge ki and kj into a single feature.\n\nF = Psi.F==1;\nstateSeq = Psi.stateSeq;\nThetaM = Psi.ThetaM;\n\n% ---------------------------------------------  select anchor sequences\nif ~isfield( Psi, 'anchorIDs' ) \n    anchorIDs = randsample( data.N, 2 );\n    else\n    anchorIDs = Psi.anchorIDs;\nend\nii = anchorIDs(1);\njj = anchorIDs(2);\n\nif isfield( Psi, 'activeFeatIDs' )\n    ki = Psi.activeFeatIDs(1);\n    if length( Psi.activeFeatIDs ) > 1\n        kj = Psi.activeFeatIDs(2);\n    else\n        kj = ki;\n    end\nend\n\n% ---------------------------------------------  select feature IDs\nswitch algParams.SM.featSelectDistr\n    case 'random'\n        qs_ki = F(ii,:);\n        if ~exist('ki','var')\n            ki = multinomial_single_draw( qs_ki );\n        end\n        qs_kj = F(jj,:);\n        if ~exist('kj','var')\n            kj = multinomial_single_draw( qs_kj );\n        end\n    case 'splitBias'\n        qs_ki = F(ii,:);\n        if ~exist('ki','var')\n            ki = multinomial_single_draw( qs_ki );\n        end\n        \n        delta_ki = false( size(F,2) );\n        delta_ki( ki ) = 1;\n        \n        qs_kj = F(jj,:) .* ~delta_ki;\n        qs_kj( ki ) = F(jj,ki)*2*sum( qs_kj );\n        if ~exist('kj','var')\n            kj = multinomial_single_draw( qs_kj );\n        end\n    case 'splitBias+margLik'    \n        % Build cond distr. kj | ki, jj\n        %  based on margLik ratio between ki and kj\n        \n        qs_ki = F(ii,:);\n        if ~exist('ki','var')\n            ki = multinomial_single_draw( qs_ki );\n        end\n        log_qs_kj = -inf( 1, size(F,2)  );\n        for kk = find( F(jj,:) )\n            if kk == ki\n               continue;\n            end\n            log_qs_kj(kk) = ThetaM.calcMargLikRatio_MergeFeats( data, stateSeq, ki, kk );\n        end\n        M = max( log_qs_kj );\n        if all( isinf(log_qs_kj) )\n            qs_kj = zeros(1, size(F,2) );\n            qs_kj(ki) = F(jj,ki);\n        else\n        qs_kj = exp( log_qs_kj - M );\n        qs_kj( ki ) = F(jj,ki)*2*sum( qs_kj ); \n        qs_kj = qs_kj ./ sum( qs_kj );\n        end\n        % Final smoothing: take convex combo of 99% our qs and 1% us\n        %   this avoids terrible reverse probabilities\n        us = false( 1, size(F,2) );\n        us( F(jj,:) ) = 1;\n        us = us./sum(us);\n        qs_kj = .99*qs_kj + 0.01*us; \n        \n        if ~exist('kj','var')\n            kj = multinomial_single_draw( qs_kj );    \n        end  \nend\nqs_ki = qs_ki ./ sum( qs_ki );\nqs_kj = qs_kj ./ sum( qs_kj );\nfeatIDs = [ki kj];\n\nassert( ~any( isnan(qs_kj) ), 'ERROR: bad numerical calc of feat select distr.');\n\nPrQfeatIDs = qs_ki( ki ) * qs_kj( kj );\n", "meta": {"author": "michaelchughes", "repo": "NPBayesHMM", "sha": "22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd", "save_path": "github-repos/MATLAB/michaelchughes-NPBayesHMM", "path": "github-repos/MATLAB/michaelchughes-NPBayesHMM/NPBayesHMM-22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd/code/BPHMM/sampler/SplitMergeSeq/sampleAnchorAndFeatIDsToSplitMerge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.5772491535007117}}
{"text": "function net = cnn_mnist_init(varargin)\n% Initialize a simple TensorNet for MNIST.\n\nnet.layers = {} ;\ninputModeSize = [4, 8, 8, 4] ;\nsecondModeSize = [5, 5, 5, 5] ;\nranks = [1, 2, 2, 2, 1] ;\nW = tt_rand(secondModeSize.*inputModeSize, length(secondModeSize), ranks, []) ;\nW = tt_matrix(W, secondModeSize, inputModeSize) ;\nW.core = single(W.core) ;\nnet.layers{end+1} = struct('type', 'custom', ...\n                           'forward', @vl_nntt_forward, ...\n                           'backward', @vl_nntt_backward, ...\n                           'W', W, ...\n                           'weights', {{W.core, zeros(1,1,prod(secondModeSize),'single')}}, ...\n                           'learningRate', [1, 2], ...\n                           'weightDecay', [1, 0], ...\n                           'outHeight', 1, ...\n                           'outWidth', 1, ...\n                           'outChannels', prod(secondModeSize)) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'conv', ...\n                           'weights', {{0.1*randn(1,1,prod(secondModeSize),10, 'single'), zeros(1, 10, 'single')}}, ...\n                           'learningRate', [1, 2], ...\n                           'weightDecay', [1, 0], ...\n                           'stride', 1, ...\n                           'pad', 0) ;\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n", "meta": {"author": "Bihaqo", "repo": "TensorNet", "sha": "64c8cba08aba0ff6f0c79e3442afa0774b45c0f2", "save_path": "github-repos/MATLAB/Bihaqo-TensorNet", "path": "github-repos/MATLAB/Bihaqo-TensorNet/TensorNet-64c8cba08aba0ff6f0c79e3442afa0774b45c0f2/experiments/mnist/cnn_mnist_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5772459355398136}}
{"text": "function S = globMatrixNed3DStiff(fun,mesh,fem1,fem2)\n\n%% USAGE: generate stiffness global matrix on a 3D mesh \n%\n% INPUTS:\n% fun --- coefficient function\n% mesh --- a struct data contains very rich mesh information.\n% fem1 --- global DoF for test function space\n% fem2 --- global DoF for trial function space\n%\n% OUTPUTS:\n% [IN JN XN] --- triplets of the sparse matrix from regular elements. \n% [II JI XI] --- triplets of the sparse matrix from interface elements. \n\n% Last Modified: 08/07/2020 by Xu Zhang \n\n%% 0. Initializaiton\nfeEvalBas1 = @EvalNed1Bas3D;\nfeEvalBas2 = @EvalNed1Bas3D;\n\ndof1 = fem1.ldof; dof2 = fem2.ldof; nloc = dof1*dof2; \nnt = length(mesh.t);\nA = fem1.area; gx = fem1.gx; gy = fem1.gy; gz = fem1.gz; gw = fem1.gw;\nX = zeros(nloc*nt, 1);\n\ncoef = feval(fun,gx,gy,gz);\nIbasx = cell(dof1,1); Ibasy = cell(dof1,1); Ibasz = cell(dof1,1); \nJbasx = cell(dof2,1); Jbasy = cell(dof2,1); Jbasz = cell(dof2,1);\nfor i = 1:dof1\n    Ibasx{i} = feEvalBas1(fem1.bas, ':', gx, gy, gz, i, 1, 1).*fem1.t_e_orit(:,i);\n    Ibasy{i} = feEvalBas1(fem1.bas, ':', gx, gy, gz, i, 1, 2).*fem1.t_e_orit(:,i);\n    Ibasz{i} = feEvalBas1(fem1.bas, ':', gx, gy, gz, i, 1, 3).*fem1.t_e_orit(:,i);\nend\nfor j = 1:dof2\n    Jbasx{j} = feEvalBas2(fem2.bas, ':', gx, gy, gz, j, 1, 1).*fem2.t_e_orit(:,j);\n    Jbasy{j} = feEvalBas2(fem2.bas, ':', gx, gy, gz, j, 1, 2).*fem2.t_e_orit(:,j);\n    Jbasz{j} = feEvalBas2(fem2.bas, ':', gx, gy, gz, j, 1, 3).*fem2.t_e_orit(:,j);\nend\n\nI = reshape(repmat(fem1.g2ldof,6,1),nloc*nt,1);\nJ = repmat(reshape(fem2.g2ldof,dof2*nt,1),6,1);\nind = 0;\nfor i = 1:dof1\n    for j = 1:dof2\n        X(ind+1:ind+nt) = A.*(sum(((Ibasx{i}.*(coef.*Jbasx{j})).*gw'),2) + ...\n            sum(((Ibasy{i}.*(coef.*Jbasy{j})).*gw'),2) + ...\n            sum(((Ibasz{i}.*(coef.*Jbasz{j})).*gw'),2));\n        ind = ind + nt;\n    end\nend\nID = find(X~=0); \nS = sparse(I(ID),J(ID),X(ID),size(fem1.gdof,1),size(fem2.gdof,1));\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/globMatrixNed3DStiff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514082, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5771956084460849}}
{"text": "function [model, time] = rbf_build(Xtr, Ytr, bf_type, bf_c, usePolyPart, verbose)\n% RBFBUILD\n% Builds a Radial Basis Function (RBF) interpolant using training data\n%\n% Call\n%   [model, time] = rbf_build(Xtr, Ytr, bf_type, bf_c, usePolyPart, verbose)\n%   [model, time] = rbf_build(Xtr, Ytr, bf_type, bf_c, usePolyPart)\n%   [model, time] = rbf_build(Xtr, Ytr, bf_type, bf_c)\n%   [model, time] = rbf_build(Xtr, Ytr, bf_type)\n%   [model, time] = rbf_build(Xtr, Ytr)\n%\n% Input\n% Xtr, Ytr    : Training data points (Xtr(i,:), Ytr(i)), i = 1,...,n\n%               Note that the input variables must be scaled to e.g. [0,1]\n%               or [-1,1] for better predictive performance.\n% bf_type     : Type of the basis functions (default = 'MQ'):\n%               'BH' = Biharmonic\n%               'MQ' = Multiquadric\n%               'IMQ' = Inverse Multiquadric\n%               'TPS' = Thin plate spline\n%               'G' = Gaussian\n% bf_c        : Parameter c value (default = 1)\n% usePolyPart : Use also the polynomial term P of the model Y = P + RBF\n%               (default = 0, do not use)\n% verbose     : Set to 0 for no verbose (default = 1)\n%\n% Output\n% model     : RBF model - a struct with the following elements:\n%    n      : Number of data points in the training data set\n%    meanY  : Mean of Ytr\n%    bf_type: Type of the basis functions\n%    bf_c   : Parameter c value\n%    poly   : Use also the polynomial term\n%    coefs  : Coefficients of the model\n% time      : Execution time\n%\n% Please give a reference to the software web page in any publication\n% describing research performed using the software, e.g. like this:\n% Jekabsons G. Radial Basis Function interpolation for Matlab, 2009,\n% available at http://www.cs.rtu.lv/jekabsons/\n\n% This source code is tested with Matlab version 7.1 (R14SP3).\n\n% =========================================================================\n% RBF interpolation\n% Version: 1.1\n% Date: August 12, 2009\n% Author: Gints Jekabsons (gints.jekabsons@rtu.lv)\n% URL: http://www.cs.rtu.lv/jekabsons/\n%\n% Copyright (C) 2009  Gints Jekabsons\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, see <http://www.gnu.org/licenses/>.\n% =========================================================================\n\nif nargin < 2\n    error('Too few input arguments.');\nelse\n\n    [n, d] = size(Xtr);\n    [ny, dy] = size(Ytr);\n    if (n < 2) || (d < 1) || (ny ~= n) || (dy ~= 1)\n        error('Wrong training data sizes.');\n    end\n\n    if nargin < 3\n        bf_type = 'MQ';\n    end\n    if nargin < 4\n        bf_c = 1;\n    end\n    if nargin < 5\n        usePolyPart = 1;\n    end\n    if nargin < 6\n        verbose = 0;\n    end\n\n    tic;\n\n    model.n = n;\n    model.meanY = mean(Ytr);\n    model.bf_type = bf_type;\n    model.bf_c = bf_c;\n    model.poly = usePolyPart;\n\n    %calculate and transform distances between all the points in the training data\n    dist = zeros(n, n);\n    switch upper(model.bf_type)\n        case 'BH'\n            if verbose\n                fprintf('Building RBF (biharmonic) model...\\n');\n            end\n            for i = 1 : n\n                %for j = i : n\n                %    dist(i, j) = norm(Xtr(i,:) - Xtr(j,:));\n                %end\n                dist(i, i:n) = sqrt(sum((repmat(Xtr(i,:),n-i+1,1) - Xtr(i:n,:)).^2,2));\n                dist(i+1:n, i) = dist(i, i+1:n);\n            end\n        case 'IMQ'\n            if verbose\n                fprintf('Building RBF (inverse multiquadric) model...\\n');\n            end\n            for i = 1 : n\n                %for j = i : n\n                %    dist(i, j) = 1 / sqrt(sum((Xtr(i,:) - Xtr(j,:)).^2) + bf_c^2);\n                %end\n                dist(i, i:n) = 1 ./ sqrt(sum((repmat(Xtr(i,:),n-i+1,1) - Xtr(i:n,:)).^2,2) + bf_c^2);\n                dist(i+1:n, i) = dist(i, i+1:n);\n            end\n        case 'TPS'\n            if verbose\n                fprintf('Building RBF (thin plate spline) model...\\n');\n            end\n            for i = 1 : n\n                %for j = i : n\n                %    dist(i, j) = sum((Xtr(i,:) - Xtr(j,:)).^2);\n                %    dist(i, j) = (dist(i, j) + bf_c^2) * log(sqrt(dist(i, j) + bf_c^2));\n                %end\n                dist(i, i:n) = sum((repmat(Xtr(i,:),n-i+1,1) - Xtr(i:n,:)).^2,2);\n                dist(i, i:n) = (dist(i, i:n) + bf_c^2) .* log(sqrt(dist(i, i:n) + bf_c^2));\n                dist(i+1:n, i) = dist(i, i+1:n);\n            end\n        case 'G'\n            if verbose\n                fprintf('Building RBF (Gaussian) model...\\n');\n            end\n            for i = 1 : n\n                %for j = i : n\n                %    dist(i, j) = exp(-sum((Xtr(i,:) - Xtr(j,:)).^2) / (2*bf_c^2));\n                %end\n                dist(i, i:n) = exp(-sum((repmat(Xtr(i,:),n-i+1,1) - Xtr(i:n,:)).^2,2) / (2*bf_c^2));\n                dist(i+1:n, i) = dist(i, i+1:n);\n            end\n        otherwise %MQ\n            if verbose\n                fprintf('Building RBF (multiquadric) model...\\n');\n            end\n            for i = 1 : n\n                %for j = i : n\n                %    dist(i, j) = sqrt(sum((Xtr(i,:) - Xtr(j,:)).^2) + bf_c^2);\n                %end\n                dist(i, i:n) = sqrt(sum((repmat(Xtr(i,:),n-i+1,1) - Xtr(i:n,:)).^2,2) + bf_c^2);\n                dist(i+1:n, i) = dist(i, i+1:n);\n            end\n    end\n\n    %calculate coefs\n    if model.poly == 0\n        model.coefs = dist \\ (Ytr - model.meanY);\n    else\n        A = [dist, ones(n,1), Xtr; [ones(n,1), Xtr]', zeros(d+1,d+1)];\n        model.coefs  = A \\ [Ytr; zeros(d+1,1)];\n    end\n\n    time = toc;\n\n    if verbose\n        fprintf('Execution time: %0.2f seconds\\n', time);\n    end\n\nend\nreturn\n", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Single-objective optimization/SACC-EAM-II/rbf_build.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.5771955950047696}}
{"text": "% nlsS = getNLSStruct( extra, dispOn, zoom)\n%\n% extra.tVec    : defining TIs \n%               (not called TIVec because it looks too much like T1Vec)\n% extra.T1Vec   : defining T1s\n% dispOn        : 1 - display the struct at the end\n%                 0 (or omitted) - no display\n% zoom          : 1 (or omitted) - do a non-zoomed search\n%                 x>1 - do an iterative zoomed search (x-1) times (slower search)\n%                 NOTE: When zooming in, convergence is not guaranteed.\n%\n% Data Model    : a + b*exp(-TI/T1) \n%    \n% written by J. Barral, M. Etezadi-Amoli, E. Gudmundson, and N. Stikov, 2009\n%  (c) Board of Trustees, Leland Stanford Junior University \n\nfunction nlsS = getNLSStruct(extra, dispOn, zoom)\n\nnlsS.tVec = extra.tVec(:);\nnlsS.N = length(nlsS.tVec);\nnlsS.T1Vec = extra.T1Vec(:);\nnlsS.T1Start = nlsS.T1Vec(1);\nnlsS.T1Stop = nlsS.T1Vec(end);\nnlsS.T1Len = length(nlsS.T1Vec);\n\n% The search algorithm to be used\nnlsS.nlsAlg = 'grid'; % Grid search\n\n% Display the struct so that the user can see it went ok\nif nargin < 2 \n  dispOn = 0;\nend\n\n% Set the number of times you zoom the grid search in, 1 = no zoom\n% Setting this greater than 1 will reduce the step size in the grid search\n% (and slow down the fit significantly)\n\nif nargin < 3\n\tnlsS.nbrOfZoom = 2;\nelse\n\tnlsS.nbrOfZoom = zoom;\nend\n\nif nlsS.nbrOfZoom > 1\n    nlsS.T1LenZ = 21; % Length of the zoomed search\nend\n\t\t\nif dispOn\n  % Display the structure for inspection\n  nlsS\nend\n\n% Set the help variables that can be precomputed:\n% alpha is 1/T1,\n% theExp is a matrix of exp(-TI/T1) for different TI and T1,\n% rhoNormVec is a vector containing the norm-squared of rho over TI,\n% where rho = exp(-TI/T1), for different T1's.\nswitch(nlsS.nlsAlg)\n  case{'grid'}\n    alphaVec = 1./nlsS.T1Vec; \n    nlsS.theExp = exp( -nlsS.tVec*alphaVec' );\n    nlsS.rhoNormVec = ...\n        sum( nlsS.theExp.^2, 1)' - ...\n        1/nlsS.N*(sum(nlsS.theExp,1)').^2;    \nend \n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/IRfun/getNLSStruct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.57715619116226}}
{"text": "function [tgrad,fgrad,c]=gabphasegrad(method,varargin)\n%GABPHASEGRAD   Phase gradient of the DGT\n%   Usage:  [tgrad,fgrad,c] = gabphasegrad('dgt',f,g,a,M);\n%           [tgrad,fgrad]   = gabphasegrad('phase',cphase,a);\n%           [tgrad,fgrad]   = gabphasegrad('abs',s,g,a);\n%\n%   `[tgrad,fgrad]=gabphasegrad(method,...)` computes the relative \n%   time-frequency gradient of the phase of the |dgt| of a signal. \n%   The derivative in time *tgrad* is the relative instantaneous \n%   frequency while the frequency derivative *fgrad* is the negative\n%   of the local group delay.\n%\n%   *tgrad* is a measure the deviation from the current channel frequency,\n%   so a value of zero means that the instantaneous frequency is equal to \n%   the center frequency of the considered channel, a positive value means\n%   the true absolute intantaneous frequency is higher than the current \n%   channel frequency and vice versa. \n%   Similarly, *fgrad* is a measure of deviation from the current time \n%   positions.\n%\n%   *fgrad* is scaled such that distances are measured in samples. Similarly,\n%   *tgrad* is scaled such that the Nyquist frequency (the highest possible\n%   frequency) corresponds to a value of L/2. The absolute time and \n%   frequency positions can be obtained as\n%\n%      tgradabs = bsxfun(@plus,tgrad,fftindex(M)*L/M);\n%      fgradabs = bsxfun(@plus,fgrad,(0:L/a-1)*a);\n%\n%   Please note that neither *tgrad* and *fgrad* nor *tgradabs* and \n%   *fgradabs* are true derivatives of the |dgt| phase. To obtain the true\n%   phase derivatives, one has to explicitly pass either 'freqinv' or \n%   'timeinv' flags and scale both *tgrad* and *fgrad* by 2*pi/L.\n%\n%   The computation of *tgrad* and *fgrad* is inaccurate when the absolute\n%   value of the Gabor coefficients is low. This is due to the fact the the\n%   phase of complex numbers close to the machine precision is almost\n%   random. Therefore, *tgrad* and *fgrad* may attain very large random values\n%   when `abs(c)` is close to zero.\n%\n%   The computation can be done using four different methods.\n%\n%     'dgt'    Directly from the signal using algorithm by Auger and\n%              Flandrin.\n%\n%     'phase'  From the phase of a DGT of the signal. This is the\n%              classic method used in the phase vocoder.\n%\n%     'abs'    From the absolute value of the DGT. Currently this\n%              method works only for Gaussian windows.\n%\n%     'cross'  Directly from the signal using algorithm by Nelson.\n%\n%   `[tgrad,fgrad]=gabphasegrad('dgt',f,g,a,M)` computes the time-frequency\n%   gradient using a DGT of the signal *f*. The DGT is computed using the\n%   window *g* on the lattice specified by the time shift *a* and the number\n%   of channels *M*. The algorithm used to perform this calculation computes\n%   several DGTs, and therefore this routine takes the exact same input\n%   parameters as |dgt|.\n%\n%   The window *g* may be specified as in |dgt|. If the window used is\n%   'gauss', the computation will be done by a faster algorithm.\n%\n%   `[tgrad,fgrad,c]=gabphasegrad('dgt',f,g,a,M)` additionally returns the\n%   Gabor coefficients *c*, as they are always computed as a byproduct of the\n%   algorithm.\n%\n%   `[tgrad,fgrad]=gabphasegrad('cross',f,g,a,M)` does the same as above\n%   but this time using algorithm by Nelson which is based on computing \n%   several DGTs.\n%\n%   `[tgrad,fgrad]=gabphasegrad('phase',cphase,a)` computes the phase\n%   gradient from the phase *cphase* of a DGT of the signal. The original DGT\n%   from which the phase is obtained must have been computed using a\n%   time-shift of *a* using the default phase convention (`'freqinv'`) e.g.::\n%\n%        [tgrad,fgrad]=gabphasegrad('phase',angle(dgt(f,g,a,M)),a)\n%\n%   `[tgrad,fgrad]=gabphasegrad('abs',s,g,a)` computes the phase gradient\n%   from the spectrogram *s*. The spectrogram must have been computed using\n%   the window *g* and time-shift *a* e.g.::\n%\n%        [tgrad,fgrad]=gabphasegrad('abs',abs(dgt(f,g,a,M)),g,a)\n%\n%   `[tgrad,fgrad]=gabphasegrad('abs',s,g,a,difforder)` uses a centered finite\n%   diffence scheme of order *difforder* to perform the needed numerical\n%   differentiation. Default is to use a 4th order scheme.\n%\n%   Currently the `'abs'` method only works if the window *g* is a Gaussian\n%   window specified as a string or cell array.\n%\n%   See also: resgram, gabreassign, dgt\n%\n%   References: aufl95 cmdaaufl97 fl65 ltfatnote042\n\n\n% AUTHOR: Peter L. S\u00f8ndergaard, 2008; Zdenek Pr\u016f\u0161a 2015\n\n%narginchk(4,6);\n\n% If no phaseconv flag was passed, add 'relative'\ndefinput = arg_gabphasederivconv;\nif ~any(cellfun(@(el) any(strcmpi(el,varargin)),definput.flags.phaseconv))\n    varargin{end+1} = 'relative';\nend\n\nif nargout<3\n    phased = gabphasederiv({'t','f'},method,varargin{:});\nelse\n    [phased,c] = gabphasederiv({'t','f'},method,varargin{:});\nend\n\n[tgrad,fgrad] = deal(phased{:});\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/gabor/gabphasegrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5771561911622599}}
{"text": "classdef NMPCDCBF2 < handle\n    % MPC with distance constraints\n    properties\n        system\n        params\n        x0\n        x_curr\n        time_curr = 0.0\n        xlog = []\n        ulog = []\n        tt = 0\n        distlog = []\n        solvertime = []\n        xopenloop = {}\n        uopenloop = {}\n        u_cost = 0\n        obs\n    end\n    methods\n        function self = NMPCDCBF2(x0, system, params)\n            % Define MPC_CBF controller\n            self.x0 = x0;\n            self.x_curr = x0;\n            self.system = system;\n            self.params = params;\n        end\n        \n        function sim(self, time)\n            % Simulate the system until a given time\n            tic;\n            xk = self.x_curr;\n            while self.time_curr < time\n                [~, uk, tt] = self.solveNMPCDCBF1(self.x_curr);%if infeasiblility happens, stop\n                if tt == -1\n                    self.tt = tt;%record computing time for each time-step\n                    return\n                end\n                xk = self.system.A * xk + [xk(4,1) * cos(xk(3,1))*self.system.dt;xk(4,1) * sin(xk(3,1))*self.system.dt;0;0] + self.system.C * uk;\n                % update system\n                self.x_curr = xk;\n                self.time_curr = self.time_curr + self.system.dt;\n                self.xlog = [self.xlog, xk];\n                self.ulog = [self.ulog, uk];\n                self.u_cost = self.u_cost + uk'*uk;\n                tt = tt + toc;\n                self.tt = tt;\n                return\n            end\n            \n        end\n        \n        function [xopt, uopt,tt] = solveNMPCDCBF1(self, xk)\n            % Solve NMPC-DCBF\n            [feas, x, u, J] = self.solve_cftoc1(xk);\n            if ~feas\n                xopt = [];\n                uopt = [];\n                tt = -1;\n                return\n            else\n                xopt = x(:,2);\n                uopt = u(:,1);\n                tt = 0;\n            end\n        end\n        \n        function [feas, xopt, uopt, Jopt] = solve_cftoc1(self, xk)\n            % Solve CFTOC\n            % extract variables\n            N = self.params.N;\n            % define variables and cost\n            x = sdpvar(4, N+1);%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n            u = sdpvar(4, N);\n            constraints = [];\n            cost = 0;\n            % initial constraint\n            constraints = [constraints; x(:,1) == xk];\n            % add constraints and costs\n            AA=self.system.A;\n            BB=self.system.B;\n            CC=self.system.C;\n            constraints = [constraints;\n                    self.system.xl <= x(:,1) <= self.system.xu;\n                    self.system.ul <= u(:,1) <= self.system.uu;\n                    x(:,2) == AA * x(:,1) + [x(4,1)*cos(x(3,1))*self.system.dt;x(4,1)*sin(x(3,1))*self.system.dt;0; 0] + CC * u(:,1)];\n                cost = cost + (x(:,1)-[3;0.01;0;0])'*self.params.Q*(x(:,1)-[3;0.01;0;0]) + (u(:,1)-[0;0;1;1])'*self.params.R*(u(:,1)-[0;0;1;1]); % self.params.S*(w(:,1)-1)^2;\n            for i = 2:1:N\n                constraints = [constraints;\n                    self.system.xl <= x(:,i) <= self.system.xu;\n                    self.system.ul <= u(:,i) <= self.system.uu;\n                    x(:,i+1) == AA * x(:,i) + [x(4,i)*cos(x(3,i))*self.system.dt;x(4,i)*sin(x(3,i))*self.system.dt;0; 0] + CC * u(:,i)];\n                cost = cost + (x(:,i)-[3;0.01;0;0])'*self.params.Q*(x(:,i)-[3;0.01;0;0]) + (u(:,i)-[0;0;1;1])'*self.params.R*(u(:,i)-[0;0;1;1]);% self.params.S*(w(:,i)-1)^2;\n            end\n            % add CBF constraints\n            for i = 1:N-1\n                pos = self.obs.pos1;\n                r = self.obs.r1 ;\n                b = (x([1:2],i)-pos)'*((x([1:2],i)-pos))-r^2;\n                b_next = (x([1:2],i+1)-pos)'*((x([1:2],i+1)-pos))-r^2;\n                b_next_next = (x([1:2],i+2)-pos)'*((x([1:2],i+2)-pos))-r^2;                \n                b1 = (b_next - b)/self.system.dt + self.params.gamma1/self.system.dt * (b);\n                b1_next = (b_next_next - b_next)/self.system.dt + self.params.gamma1/self.system.dt * (b_next);\n                constraints = [constraints; b1_next  >=u(4,i)*(1-self.params.gamma2)*b1;b_next  >= u(3,i)*(1-self.params.gamma1)*b];%Highest order mcbf=2\n            end\n            % add terminal cost\n            cost = cost + (x(:,N+1)-[3;0.01;0;0])'*self.params.P*(x(:,N+1)-[3;0.01;0;0]);\n            ops = sdpsettings('solver','ipopt','verbose',0);\n            % solve optimization\n            diagnostics = optimize(constraints, cost, ops);\n            if diagnostics.problem == 0\n                feas = true;\n                xopt = value(x);\n                uopt = value(u);\n                Jopt = value(cost);\n            else\n                feas = false;\n                xopt = [];\n                uopt = [];\n                Jopt = [];\n            end\n            pos = self.obs.pos1;\n            r = self.obs.r1 ;\n            self.distlog = [self.distlog, (r^2-(xk(1:2)-pos)'*(xk(1:2)-pos))];\n            self.xopenloop{size(self.xopenloop,2)+1} = xopt;\n            self.uopenloop{size(self.uopenloop,2)+1} = uopt;\n            self.solvertime = [self.solvertime, diagnostics.solvertime];\n            fprintf('solver time: %f\\n', diagnostics.solvertime);\n        end\n    end\nend", "meta": {"author": "HybridRobotics", "repo": "NMPC-DCLF-DCBF", "sha": "3f40c67578f49114301b02e744e5a86fa671a981", "save_path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF", "path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF/NMPC-DCLF-DCBF-3f40c67578f49114301b02e744e5a86fa671a981/matlab/acc2023/closedloop_performance/NMPCDCBF2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.577150585154239}}
{"text": "%% FOURCURL3P2TEST\n%\n% Use the quadraticNedelec elements to approximate the velocity u and\n% the stream function w. \n%\n% We solve the following equations:\n%\n%  -w + curl curl u = 0 \n%  curl curl w + u  = f\n%\n% with Dirichlet boundary condition\n%\n% u\\times n = (curl u )\\times n  = 0  on \\partial \\Omega\n%\n% Please check fourCurl3doc for details.\n%\n% Lin Zhong, May, 2013. Clean up. Long Chen, Oct 21, 2018\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all; \nclear variables;\n\n%% Problem Setting\npde = fourCurl3data;\n[node,elem] = cubemesh([-1,1,-1,1,-1,1],2);\nbdFlag = setboundary3(node,elem,'Dirichlet');\n\n%% Parameters\nmaxIt = 3;\nerrwIwhL2 = zeros(maxIt,1); \nerrwIwhHcurl = zeros(maxIt,1);\nerrwL2 = zeros(maxIt,1);\nerrwwhHcurl = zeros(maxIt,1);\nerruIuhL2 = zeros(maxIt,1); \nerruIuhHcurl = zeros(maxIt,1);\nerruL2 = zeros(maxIt,1);\nerruuhHcurl = zeros(maxIt,1);\nassembleTime = zeros(maxIt,1);\nsolverTime = zeros(maxIt,1);\nN = zeros(maxIt,1);\nh = zeros(maxIt,1);\noption = [];\n\nfor k = 1:maxIt\n    % refine grid        \n    [node,elem,bdFlag] = uniformrefine3(node,elem,bdFlag);\n    % solve the equation\n    [w,u,eqn,info] = fourCurl3P2(node,elem,bdFlag,pde,option);\n    % compute error\n    uI = edgeinterpolate2(pde.exactu,node,eqn.edge,eqn.face,eqn.face2edge);\n    wI = edgeinterpolate2(pde.curlcurlu,node,eqn.edge,eqn.face,eqn.face2edge);\n    errwL2(k) = getL2error3ND2(node,elem,pde.curlcurlu,w);\n    erruL2(k) = getL2error3ND2(node,elem,pde.exactu,u);   \n    errwwhHcurl(k) = getHcurlerror3ND2(node,elem,pde.curlcurlcurlu,w);\n    erruuhHcurl(k) = getHcurlerror3ND2(node,elem,pde.curlu,u); \n    errwIwhL2(k) = sqrt((w-wI)'*eqn.M*(w-wI));\n    erruIuhL2(k) = sqrt((u-uI)'*eqn.M*(u-uI)); \n    errwIwhHcurl(k) = sqrt((w-wI)'*eqn.A*(w-wI));\n    erruIuhHcurl(k) = sqrt((u-uI)'*eqn.A*(u-uI));      \n    % record information\n    N(k) = length(u)+length(w);\n    h(k) = 1./(size(node,1)^(1/3)-1);            \n    assembleTime(k) = info.assembleTime;\n    solverTime(k) = info.solverTime;\nend\n\n%% Plot convergence rates\nsubplot(2,2,1)\nshowrateh2(h, errwIwhL2(1:maxIt), 1 , 'k-+', '||w_I-w_h||',...\n           h, erruIuhL2(1:maxIt), 1 , 'r-*', '||u_I-u_h||' );\nsubplot(2,2,2)\nshowrateh2(h, errwL2(1:maxIt), 1 , 'k-+', '||w-w_h||',...\n           h, erruL2(1:maxIt), 1 , 'r-*', '||u-u_h||' );                                     \nsubplot(2,2,3)               \nshowrateh2(h, errwIwhHcurl(1:maxIt), 1 , 'b-+', '||w_I-w_h||_1',...\n           h, erruIuhHcurl(1:maxIt), 1 , 'g-*', '||u_I-u_h||_1' );\nsubplot(2,2,4)               \nshowrateh2(h, errwwhHcurl(1:maxIt), 1 , 'b-+', '||w-w_h||_1',...\n           h, erruuhHcurl(1:maxIt), 1 , 'g-*', '||u-u_h||_1' );\n                                                                           \n%% Output\nerr = struct('N', N, 'h', h, ...\n             'wL2',errwL2(1:maxIt),'uL2',erruL2(1:maxIt),...\n             'wIwhL2',errwIwhL2(1:maxIt), 'uIuhL2',erruIuhL2(1:maxIt),...\n             'wIwhHcurl',errwIwhHcurl(1:maxIt),'uIuhHcurl',erruIuhHcurl(1:maxIt),...\n             'wwhHcurl',errwwhHcurl(1:maxIt),'uuhHcurl',erruuhHcurl(1:maxIt));\ntime = struct('N',N,'assemble',assembleTime(1:maxIt),'solver',solverTime(1:maxIt));\n       \n%% Display error on screen\ndisp('Table: Error')\ncolname = {'#Dof','h','||w_I-w_h||','||w-w_h||','||w_I-w_h||_1','||w-w_h||_1'};\ndisptable(colname,err.N,[],err.h,'%0.3e',err.wIwhL2,'%0.5e',err.wL2,'%0.5e',...\n              err.wIwhHcurl,'%0.5e',err.wwhHcurl,'%0.5e');\n\ncolname = {'#Dof','h','||u_I-u_h||','||u-u_h||','||u_I-u_h||_1','||u-u_h||_1'};\ndisptable(colname,err.N,[],err.h,'%0.3e',err.uIuhL2,'%0.5e',err.uL2,'%0.5e',...\n              err.uIuhHcurl,'%0.5e',err.uuhHcurl,'%0.5e');    \n          \n%     display('Table: CPU time')\ncolname = {'#Dof','Assemble','Solve'};\ndisptable(colname,time.N,[],time.assemble,'%0.2e',time.solver,'%0.2e');\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/Maxwell/fourCurl3P2test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.577044021404041}}
{"text": "function t=Tc(v,fc)\n\n% t=Tc(v,fc)\n%\n% Return the channel coherence time for a mobile moving v m/s and communicating\n% over carrier frequenc fc in Hz.\n\n% Copyright 2012 Evrytania LLC (http://www.evrytania.com)\n%\n% Written by James Peroulas <james@evrytania.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 <http://www.gnu.org/licenses/>.\n\nerror(nargchk(2,2,nargin));\nerror(chk_param(v,'v','scalar','real','>=',0));\nerror(chk_param(fc,'fc','scalar','real','>=',0));\n\ndop_spread=2*doppler_shift(fc,v);\nt=1/4/dop_spread;\n\n", "meta": {"author": "JiaoXianjun", "repo": "rtl-sdr-LTE", "sha": "037a25f164f17b1a1d82e2eb02285550f50af9b9", "save_path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE", "path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE/rtl-sdr-LTE-037a25f164f17b1a1d82e2eb02285550f50af9b9/matlab/Tc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.577044010803485}}
{"text": "% Version 1.000\n%\n% Code provided by Ruslan Salakhutdinov and Geoff Hinton\n%\n% Permission is granted for anyone to copy, use, modify, or distribute this\n% program and accompanying programs and documents for any purpose, provided\n% this copyright notice is retained and prominently displayed, along with\n% a note saying that the original programs are available from our\n% web page.\n% The programs and documents are distributed without any warranty, express or\n% implied.  As the programs were written for research purposes only, they have\n% not been tested to the degree that would be advisable in any important\n% application.  All use of these programs is entirely at the user's own risk.\n\n\nfunction [f, df] = CG_CLASSIFY(VV,Dim,XX,target);\n\nl1 = Dim(1);\nl2 = Dim(2);\nl3= Dim(3);\nl4= Dim(4);\nl5= Dim(5);\nN = size(XX,1);\n\n% Do decomversion.\n w1 = reshape(VV(1:(l1+1)*l2),l1+1,l2);\n xxx = (l1+1)*l2;\n w2 = reshape(VV(xxx+1:xxx+(l2+1)*l3),l2+1,l3);\n xxx = xxx+(l2+1)*l3;\n w3 = reshape(VV(xxx+1:xxx+(l3+1)*l4),l3+1,l4);\n xxx = xxx+(l3+1)*l4;\n w_class = reshape(VV(xxx+1:xxx+(l4+1)*l5),l4+1,l5);\n\n\n  XX = [XX ones(N,1)];\n  w1probs = 1./(1 + exp(-XX*w1)); w1probs = [w1probs  ones(N,1)];\n  w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)];\n  w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs  ones(N,1)];\n\n  targetout = exp(w3probs*w_class);\n  targetout = targetout./repmat(sum(targetout,2),1,10);\n  f = -sum(sum( target(:,1:end).*log(targetout))) ;\n\nIO = (targetout-target(:,1:end));\nIx_class=IO; \ndw_class =  w3probs'*Ix_class; \n\nIx3 = (Ix_class*w_class').*w3probs.*(1-w3probs);\nIx3 = Ix3(:,1:end-1);\ndw3 =  w2probs'*Ix3;\n\nIx2 = (Ix3*w3').*w2probs.*(1-w2probs); \nIx2 = Ix2(:,1:end-1);\ndw2 =  w1probs'*Ix2;\n\nIx1 = (Ix2*w2').*w1probs.*(1-w1probs); \nIx1 = Ix1(:,1:end-1);\ndw1 =  XX'*Ix1;\n\ndf = [dw1(:)' dw2(:)' dw3(:)' dw_class(:)']'; \n", "meta": {"author": "qiuwch", "repo": "DeepLearning", "sha": "60508ffd8c39a085375eec82e576f446d1318bc9", "save_path": "github-repos/MATLAB/qiuwch-DeepLearning", "path": "github-repos/MATLAB/qiuwch-DeepLearning/DeepLearning-60508ffd8c39a085375eec82e576f446d1318bc9/CG_CLASSIFY.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5770440102521254}}
{"text": "% add the path of RBM code\naddpath('..');\naddpath('~/work/Algorithms/liblinear-1.7/matlab');\n\nuse_whitening = 1;\n\n% load natural image patches\nload 'bsds500bw_patches_8.mat';\nX = (Xbw / 255);\n\n% shuffle the training data\nperm_idx = randperm (size(X,1));\n\nn_all = size(X, 1);\nn_train = ceil(n_all * 3 / 4);\nn_valid = floor(n_all /4);\n\nX_valid = X(perm_idx(n_train+1:end), :);\nX = X(perm_idx(1:n_train), :);\n\nif use_whitening\n    %% ZCA\n    %[Z, Wsep, Wmix, mX] = zca(X, 0.1);\n    load patch8_whiten.mat;\n    X = zca_whiten(X, Wsep, Wmix, mX);\n    X_valid = zca_whiten(X_valid, Wsep, Wmix, mX);\nend\n\n% construct RBM and use default configurations\nD = default_dae (size(X, 2), 320);\n\nif use_whitening\n    D.do_normalize = 0;\n    D.do_normalize_std = 0;\nend\n\n\nD.data.binary = 0;\nD.hidden.binary = 0;\n\nD.learning.lrate = 1e-1;\nD.learning.lrate0 = 10000;\n%D.learning.momentum = 0.5;\nD.learning.weight_decay = 0;\n\nD.adagrad.use = 1;\n\nD.rica.cost = 0.01;\n\nD.noise.drop = 0;\nD.noise.level = 0;\n\nD.sparsity.cost = 0;\nD.sparsity.target = 0;\n\n% max. 100 epochs\nD.iteration.n_epochs = 500;\n\n% set the stopping criterion\nD.stop.criterion = 0;\nD.stop.recon_error.tolerate_count = 1000;\n\n% save the intermediate data after every epoch\nD.hook.per_epoch = {@save_intermediate, {'rica_patch8.mat'}};\n\n% print learining process\nD.verbose = 0;\n\n% display the progress\nD.debug.do_display = 0;\n\nfprintf(1, 'Training rICA\\n');\ntic;\nD = dae (D, X, X_valid, 0.1);\nfprintf(1, 'Training is done after %f seconds\\n', toc);\n\n\n\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/example/example_patches_rica.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.5770440063302456}}
{"text": "function test_failed=test_dgt2\n\ntest_failed=0;\n  \ndisp(' ===============  TEST_DGT2 ================');\n\n% Run some fixed test to test the interface.\n% This is not a thourough tester.\n\n% --- first test\n\na=6;\nM=8;\n\nLf=71;\nL=72;\nW=3;\n\nf=tester_rand(Lf,Lf,W);\n\ng=pgauss(L,a*M/L);\ngd=gabdual(g,a,M);\n\n[c,Ls]=dgt2(f,g,a,M);\nr=idgt2(c,gd,a,Ls);\n\nres=f-r;\nnres=norm(res(:));\n\n[test_failed,fail]=ltfatdiditfail(nres,test_failed);\n%failed='';\n%if nres>10e-10\n%  failed='FAILED';\n%  test_failed=test_failed+1;\n%end;\n\ns=sprintf('DGT2 Lf:%3i L:%3i %0.5g %s',Lf,L,nres,fail);\ndisp(s)\n\n\n% --- second test\n\na1=6;\nM1=8;\n\na2=5;\nM2=10;\n\nL1=a1*M1;\nL2=a2*M2;\n\nW=1;\n\nf=tester_rand(L1,L2,W);\n\ng1=pgauss(L1,a1*M1/L1);\ng2=pgauss(L2,a2*M2/L2);\n\ngd1=gabdual(g1,a1,M1);\ngd2=gabdual(g2,a2,M2);\n\nc=dgt2(f,g1,g2,[a1,a2],[M1,M2]);\nc2=ref_dgt2(f,g1,g2,a1,a2,M1,M2);\n\nrc=c-c2;\nnres=norm(rc(:));\n\n[test_failed,fail]=ltfatdiditfail(nres,test_failed);\n%failed='';\n%if nres>10e-10\n%  failed='FAILED';\n%  test_failed=test_failed+1;\n%end;\n\ns=sprintf('DGT2 REF L1:%3i L2:%3i %0.5g %s',L1,L2,nres,fail);\ndisp(s)\n\n\nr=idgt2(c,gd1,gd2,[a1,a2]);\n\nres=r-f;\n\nnres=norm(res(:));\n\n[test_failed,fail]=ltfatdiditfail(nres,test_failed);\n%failed='';\n%if nres>10e-10\n%  failed='FAILED';\n%  test_failed=test_failed+1;\n%end;\n\ns=sprintf('DGT2 INV L1:%3i L2:%3i %0.5g %s',L1,L2,nres,fail);\ndisp(s)\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/testing/test_dgt2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5770318357730454}}
{"text": "function y = upfilt(x, f, dim, extmod, shift)\n% UPFILT   Upsample (by 2) and filter along a dimension\n%\n%       y = upfilt(x, f, dim, extmod, shift)\n%\n% Input:\n%   x:      input signal\n%   f:      1-D filter\n%   dim:    the processing dimension\n%   extmod: extension mode (e.g. 'per' or 'sym')\n%   shift:  specifies the window over which filtering occurs\n%\n% Output:\n%   y:      upsampled and filtered signal\n%\n% Note:\n%   The origin of the filter f is assumed to be floor(size(f)/2) + 1.\n%   Amount of shift should be no more than floor((size(f)-1)/2).\n\n% Skip singleton dimension\nif size(x, dim) == 1\n    y = x;\n    return\nend\n\nnd = ndims(x);\n% Consider column vectors as 1-D signals \nif nd == 2 & size(x, 2) == 1\n    nd = 1;\nend\n\n% Cell array of indexes for each dimension\nI = cell(1, ndims(x));\nfor d = 1:ndims(x)\n    I{d} = 1:size(x,d);\nend\n\n% Upsample (by 2)\nsx = size(x);\nsx(dim) = 2*sx(dim);\ny = zeros(sx);\nI{dim} = 1:2:sx(dim);\ny(I{:}) = x;\n\n% Border extend\nn = size(y, dim);\nhlf = (length(f) - 1) / 2;\n% Amount of extension at two ends\ne1 = floor(hlf) + shift;\ne2 = ceil(hlf) - shift;\n\nswitch extmod\n    case 'per'\n        I{dim} = [ly-e1+1:n , 1:n , 1:e2];\n        \n    case 'sym'\n        I{dim} = [e1+1:-1:2 , 1:n , n-1:-1:e2];\n        \n    otherwise\n        error('Invalid input for EXTMOD')\n        \nend\ny = y(I{:});\n    \n% Filter and return only the 'valid' part\ny = filter(f, 1, y, [], dim);\n    \nI{dim} = (1:n) + length(f) - 1;\ny = y(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/9868-laplacian-pyramid-toolbox/upfilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5770318294987427}}
{"text": "function varargout = circleAsPolygon(circle, varargin)\n%CIRCLEASPOLYGON Convert a circle into a series of points\n%\n%   Note: this function is deprecated, use \"circleToPolygon\" instead\n%\n%   P = circleAsPolygon(CIRCLE, N);\n%   convert circle given as [x0 y0 r], where x0 and y0 are coordinate of\n%   center, and r is the radius, into an array of  [(N+1)x2] double, \n%   containing x and y values of points. \n%   The polygon is closed\n%\n%   P = circleAsPolygon(CIRCLE);\n%   uses a default value of N=64 points\n%\n%   Example\n%   circle = circleAsPolygon([10 0 5], 16);\n%   figure;\n%   drawPolygon(circle);\n%\n%   See also:\n%   circles2d, circleToPolygon\n%\n%\n% ---------\n% author : David Legland \n% created the 06/04/2005.\n% Copyright 2010 INRA - Cepia Software Platform.\n%\n\n%   HISTORY\n%   20/04/2007: return a closed polygon with N+1 vertices, use default N=64\n\nwarning('matGeom:deprecated', ...\n    'function \"circleAsPolygon\" is deprecated, use \"circleToPolygon\" instead');\n\n% format output\nif nargout <= 1\n    varargout = {circleToPolygon(circle, varargin{:})};\nelse\n    [x, y] = circleToPolygon(circle, varargin{:});\n    varargout = {x, y};\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/deprecated/geom2d/circleAsPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7057850340255385, "lm_q1q2_score": 0.5770318294987425}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   demo script for using short-hand version of the meshing wrappers\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% preparation\n% user must add the path of iso2mesh to matlab path list\n% addpath('../');\n\n% user need to add the full path to .../iso2mesh/bin directory\n% to windows/Linux/Unix PATH environment variable\n\n%% load the sample data\nload rat_head.mat\n\n% volimage is a volumetric image such as an X-ray or MRI image\n%% v2m is the short-hand version of vol2mesh\n\n% mesh volimage at threshold level 0.05, max surface element size 3,\n% maximum tetrahedral element volume 2\n\n[node,elem,face]=v2m(volimage,0.05,3,2);\n\n%% visualize the resulting mesh\nsubplot(211);\nplotmesh(node,face);\naxis equal;\n\n%% alternatively, one can call vol2surf and surf2mesh separately\n\n% v2s: shorthand version of vol2surf, s2m: shorthand version of surf2mesh\n\n[node,face,regions,holes]=v2s(volimage,0.05,3);\n[node,elem,face]=s2m(node,face,1,2);\n\n%% visualize the resulting mesh\nsubplot(212)\nplotmesh(node,face);\naxis equal;\n\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/Iso2meshToolbox/sample/demo_shortcut_ex1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5770318256538812}}
{"text": "%example_accel_grad_mtl\n\nclear all;\nclc\n\n% add path\naddpath(genpath('../../SLEP/'));\n\n% load data and set regularization parameter\nload('../../data/dmoz.mat');\nlambda = 10^-4;\n\n% center data\nfor i = 1:length(Xtrain)\n        Xtrain{i} = CenterRowData(Xtrain{i});\n        Ytrain{i} = CenterRowData(Ytrain{i});\nend\n\n% call the main function\n[Wp,fval_vec,itr_counter] = accel_grad_mtl(Xtrain,Ytrain,lambda);\n\n\n\n\n\n\n\n", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Toolbox/SLEP_package_4.1/Examples/traceNorm/example_accel_grad_mtl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5770318143199964}}
{"text": "function [err,time,solver,eqn] = femPoisson3(node,elem,pde,bdFlag,option,varargin)\n%% FEMPOISSON3 solve Poisson equation by various finite element methods\n%\n%   FEMPOISSON3 computes approximations to the Poisson equation on a\n%   sequence of meshes obtained by uniform refinement of a input mesh.\n% \n% See also Poisson, crack, Lshape\n%\n% Copyright (C)  Long Chen. See COPYRIGHT.txt for details.\n\n%% Check input arguments\nif nargin >=1 && ischar(node)\n    option.elemType = node;\n    clear node\nend\nif ~exist('node','var') || ~exist('elem','var')\n    [node,elem] = cubemesh([0,1,0,1,0,1],0.25); % default mesh is a cube\nend\nif ~exist('option','var'), option = []; end\nif ~exist('pde','var')\n    pde = sincosdata3;                          % default data\nend\nif ~exist('bdFlag','var')\n    bdFlag = setboundary3(node,elem,'Dirichlet'); \nend\n\n%% Parameters\noption = femoption(option);\nmaxIt = option.maxIt;   maxN = option.maxN; L0 = option.L0;\nelemType = option.elemType; refType = option.refType;\n\n%% Generate an initial mesh \nfor k = 1:L0\n    if strcmp(refType,'red')\n        [node,elem,bdFlag] = uniformrefine3(node,elem,bdFlag);\n    elseif strcmp(refType,'bisect')\n        [node,elem,bdFlag] = uniformbisect3(node,elem,bdFlag);\n    end\nend\n\n%% Initialize err\nerrL2 = zeros(maxIt,1);   errH1 = zeros(maxIt,1); \nerruIuh = zeros(maxIt,1); errMax = zeros(maxIt,1);\nerrTime = zeros(maxIt,1); solverTime = zeros(maxIt,1); \nassembleTime = zeros(maxIt,1); meshTime = zeros(maxIt,1); \nitStep = zeros(maxIt,1);  stopErr = zeros(maxIt,1); flag = zeros(maxIt,1);\nN = zeros(maxIt,1);\n\n%% Finite Element Method        \nfor k = 1:maxIt\n    % solve the equation\n    switch elemType\n        case 'P1'     % piecewise linear function P1 element\n            [u,Du,eqn,info] = Poisson3(node,elem,pde,bdFlag,option);\n        case 'CR'     % piecewise linear function CR element\n            [u,Du,eqn,info] = Poisson3CR(node,elem,pde,bdFlag,option);\n        case 'P2'     % piecewise quadratic function\n            [u,Du,eqn,info] = Poisson3P2(node,elem,pde,bdFlag,option);\n        case 'WG'     % weak Galerkin element\n            [u,Du,eqn,info] = Poisson3WG(node,elem,pde,bdFlag,option);            \n    end\n    % compute error\n    tic;\n    if isfield(pde,'Du')\n        if ~isempty(Du)\n            errH1(k) = getH1error3(node,elem,pde.Du,Du);\n        else\n            errH1(k) = getH1error3(node,elem,pde.Du,u);            \n        end\n    end\n    if isfield(pde,'exactu')\n        errL2(k) = getL2error3(node,elem,pde.exactu,u);        \n        % interpolation\n        switch elemType\n            case 'P1'\n                uI = Lagrangeinterpolate(pde.exactu,node,elem);\n            case 'CR'\n                uI = Lagrangeinterpolate(pde.exactu,node,elem,'CR',eqn.face);\n            case 'P2'\n                uI = Lagrangeinterpolate(pde.exactu,node,elem,'P2',eqn.edge);\n            case 'WG'\n                uI = Lagrangeinterpolate(pde.exactu,node,elem,'WG',eqn.face);\n        end\n        erruIuh(k) = sqrt((u-uI)'*eqn.A*(u-uI));\n        errMax(k) = max(abs(u-uI));\n    end\n    errTime(k) = toc;\n    % record time\n    solverTime(k) = info.solverTime;\n    assembleTime(k) = info.assembleTime;\n    if option.printlevel>1\n        fprintf('Time to compute the error %4.2g s \\n H1 err %4.2g    L2err %4.2g \\n',...\n            errTime(k),errH1(k), errL2(k));    \n    end\n    % record solver information\n    itStep(k) = info.itStep;\n    stopErr(k) = info.stopErr;\n    flag(k) = info.flag;\n    % plot \n    N(k) = length(u);\n    if option.plotflag && N(k) < 2e3 % show mesh and solution for small size\n       figure(1);  showresult3(node,elem,u);    \n    end\n    if N(k) > maxN\n        break;\n    end\n    % refine mesh\n    tic;\n    if strcmp(refType,'red')\n        [node,elem,bdFlag] = uniformrefine3(node,elem,bdFlag);\n    elseif strcmp(refType,'bisect')\n        [node,elem,bdFlag] = uniformbisect3(node,elem,bdFlag);\n    end\n    meshTime(k) = toc;\nend\n\n%% Plot convergence rates\nif option.rateflag\n    figure;\n    set(gcf,'Units','normal'); \n    set(gcf,'Position',[0.25,0.25,0.55,0.4]);\n    subplot(1,2,1)\n    showrate2(N(1:k),errH1(1:k),1,'-*','||Du-Du_h||',...\n              N(1:k),errL2(1:k),1,'k-+','||u-u_h||');\n    subplot(1,2,2)\n    showrate2(N(1:k),erruIuh(1:k),1,'m-+','||Du_I-Du_h||',...\n              N(1:k),errMax(1:k),1,'r-*','||u_I-u_h||_{\\infty}');\nend\n\n%% Output\nerr = struct('N',N,'H1',errH1(1:k),'L2',errL2(1:k),...\n             'uIuhH1',erruIuh(1:k),'uIuhMax',errMax(1:k));\ntime = struct('N',N,'err',errTime(1:k),'solver',solverTime(1:k), ...\n              'assmble',assembleTime(1:k),'mesh',meshTime(1:k));\nsolver = struct('N',N(1:k),'itStep',itStep(1:k),'time',solverTime(1:k),...\n                'stopErr',stopErr(1:k),'flag',flag(1:k));\n\n%% Display error\nts = zeros(k,3); ts = char(ts);\ndisplay(' #Dof   ||u-u_h||     ||Du-Du_h||   ||DuI-Du_h||  ||uI-u_h||_{max}');\ndisplay([num2str(err.N) ts num2str(err.L2,'%0.5e') ts num2str(err.H1,'%0.5e')...\n         ts num2str(err.uIuhH1,'%0.5e') ts num2str(err.uIuhMax,'%0.5e')]);", "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/femPoisson3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5769460349433579}}
{"text": "function D = sldiff_pw(X1, X2, type)\n%SLDIFF_PW Measures the pair-wise difference\n%\n% $ Synatx $\n%   - D = sldiff_pw(X1, X2, type)\n%\n% $ Arguments $\n%   - X1, X2:             the two sample matrices\n%   - type:               the type of difference measurement\n%                         default = 'abssum'\n%\n% $ Description $\n%   - D = sldiff_pw(X1, X2, type) computes the measurment of differences\n%     between the samples in X1 and those in X2 in a pairwise manner.\n%     All samples should be stored in columns. And the samples in X1 and \n%     X2 should be of the same dimension. If X1 and X2 are of sizes\n%     dxn1 and dxn2 respectively. Then D is a matrix of size n1 x n2.\n%\n%   - The measurment types supported are listed below\n%     \\*\n%     \\t  Table 1. The difference measurement types                 \\\\\n%     \\h    name      &         description                         \\\\\n%          'abssum'   &   sum of absolute values of differences     \\\\\n%          'maxdiff'  &   maximum of absolute values of differences \\\\\n%          'mindiff'  &   minimum of absolute values of differences \\\\\n%     \\*\n%\n% $ History $\n%   - Created by Dahua Lin on Dec 06th, 2005\n%   - Modified by Dahua Lin on Sep 10th, 2006\n%       - Re-implement the core in C++: pwdiff_core\n%       - The efficiency is increased by 10 times.\n% \n\n%% parse and verify input arguments\n\nif nargin < 3 || isempty(type)\n    type = 'abssum';\nend\n\nswitch type\n    case 'abssum'\n        pdmcode = 1;\n    case 'maxdiff'\n        pdmcode = 2;\n    case 'mindiff'\n        pdmcode = 3;\n    otherwise\n        error('sltoolbox:invalidarg', ...\n            'Invalid type of pwdiff computation: %s', type);\nend\n\n%% Compute\n\nD = pwdiff_core(X1, X2, pdmcode);\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/core/sldiff_pw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.576946033378525}}
{"text": "function [] = visGaussianClassLearning(RBM);\n%-----------------------------------------\n%  [] =  visGaussianClassLearning(RBM);\n%-----------------------------------------\n% DES\n\nnVis = floor(sqrt(size(RBM.W,1))).^2;\n\nsubplot(331);\nscatter(RBM.auxVars.batchX(:,1),RBM.auxVars.batchX(:,2),'r.');\n\ntitle('Batch Data');\nxlim([-10, 10]); ylim([-20, 0]);\n%  xlim([-5, 5]); ylim([-5, 5]);\n\nsubplot(332);\nscatter(RBM.pVis(:,1),RBM.pVis(:,2),'b.');\ntitle('Fantasies');\n%  xlim([-5, 5]); ylim([-5, 5]);\nxlim([-10, 10]); ylim([-20, 0]);\n\n\nsubplot(333);\nvisWeights(flipud(RBM.dW(1:nVis,:)));\ntitle ('Weight Gradients');\n\n\nsubplot(334);\nbar(RBM.b);\ntitle('Visible Bias');\n\n%\n%  subplot(335)\n%  bar((RBM.sigma2));\n%  title('Visible Variance');\n\nsubplot(336);\nvisWeights(flipud(RBM.W(1:nVis,:)));\ntitle('Connection Weights');\n\nsubplot(337);\nplot(RBM.auxVars.error);\ntitle('Reconstruction errors');\n\nsubplot(339);\nsemilogy(RBM.auxVars.lRate);\ntitle('Learning Rate');\n\ndrawnow\n", "meta": {"author": "dustinstansbury", "repo": "medal", "sha": "f33110422ed937f97aaaf3aeb24338c6f13536d7", "save_path": "github-repos/MATLAB/dustinstansbury-medal", "path": "github-repos/MATLAB/dustinstansbury-medal/medal-f33110422ed937f97aaaf3aeb24338c6f13536d7/visualizations/visGaussianClassLearning.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5769347551363602}}
{"text": "%FxNLMS\n%Marko Stamenovic\n%April 28, 2016\n\nmus = [0.01 0.05 0.1 0.5 1 2 2.5 3];% 0.5 1];\nfor j = 1:length(mus)\n    for i = 1:100\n        %%INITIALIZE VALUES%%\n        % generate input signal\n        muOG=mus(j); %learning rate\n        M=128; %buffer size (num filter weights)\n        x=randn(10000,1); %input signal\n        x=x/max(x); %sample rate\n        fs=8000; %number of samples of the input signal\n        N=length(x); %length of input signal\n        \n        % generate known filter coefficients\n        Pz=0.5*[0:127];  %linear coefficients\n        %Pz=randn(128,1); %random coefficients\n        ylim = max(Pz)*1.20;\n        ymin = min(Pz)-.2*max(Pz);\n        % generate filtered input signal == desired signal\n        d=conv(Pz,x); %input signal filtered by known filter Pz (primary path)\n        \n        %% ESTIMATE SECONDARY PATH SIGNAL USING LMS %%\n        %generate dummy secondary path response Sz\n        Sz = Pz/2;\n        %run known signal through filter\n        xp=conv(Sz,x);\n        %initalize Sz hat values\n        Szh=zeros(M,1);\n        \n        for n=M:N\n            xpvec=x(n:-1:n-M+1); %input has to be in reverse orxer has to be\n            %update mu\n            mu(n) = 1/(xpvec'*xpvec);\n            e(n)=xp(n)-Szh'*xpvec; %update error\n            %plot(e)\n            Szh=Szh+mu(n)*xpvec*(e(n)); %update filter coefficient\n        end\n        Szh = abs(ifft(1./abs(fft(Szh))));\n        \n        %% LMS FOR MAIN ANC %%\n        emean=zeros(N,1);\n        %filter input by learned filter to get x prime\n        xph = conv(Szh,x);\n        %initalize Wz filter values\n        Wz=zeros(M,1);\n        %Make sure that x and d are column vectors\n        x=x(:);\n        d=d(:);\n        %LMS\n        for n=M:N\n            xvec=x(n:-1:n-M+1); %input has to be in reverse orxer\n            xpvec=xph(n:-1:n-M+1);\n            %update mu\n            mu(n) = muOG/(xvec'*xvec);\n            e(n)=d(n)-Wz'*xvec; %update error\n            %plot(e)\n            Wz=Wz+mu(n)*xpvec*(e(n)); %update filter coefficient\n            \n            %draw the learned filter in realtime\n            %         plot(Pz)\n            %         hold on\n            %         plot(Wz)\n            %         axis([0 inf ymin ylim])\n            %         title(sprintf('n=%f time=%fs error = %f',n-M, (n-M)/fs, e(n)))\n            %         hold off\n            %         legend('Input coefficients','Learned Coefficients')\n            %         drawnow;\n        end\n        e=e(:);\n        \n        emean = (emean(:)+e);\n    end\n    emean=(emean)/i;\n    if max(emean)>1e4\n        for l = 1:length(emean)\n            if abs(emean(l)) > 1e3\n                emean(l)=1e3;\n            end\n        end\n        eall(j,:)=emean;\n    else\n        try\n            [eall(j,:),q]=(envelope(abs(emean),500,'peaks'));\n        catch\n            eall(j,:) = 1e3;\n        end\n    end\nend\nfigure\nfor i = 1:length(mus)\n    plot(10*log10(abs(eall(i,:))))\n    hold on\nend\ntitle('Convergence Time in Cycles')\nylabel('Error (dB)');\nxlabel('Cycles');\nhleg=legend('0.01','0.05','0.1','0.5','1.0', '2.0');\nhtitle=get(hleg,'Title');\nset(htitle,'String','mu');\n% %% PLOT RESULTS %%\n% figure\n% subplot(2,1,1)\n% plot(e)\n% title('Convergence Time in Cycles')\n% ylabel('Amplitude');\n% xlabel('Cycles');\n% legend('Error');\n% subplot(2,1,2)\n% stem(Pz)\n% hold on\n% stem(Wz, 'r*')\n% title('Input Coefficients vs Learned Coefficients')\n% ylabel('Amplitude');\n% xlabel('Numbering of filter tap');\n% legend('Input Coefficients', 'learned coefficients')", "meta": {"author": "markostam", "repo": "active-noise-cancellation", "sha": "1476fa7fb9c449fd01a6cc0adf3d9dbbc1baf5af", "save_path": "github-repos/MATLAB/markostam-active-noise-cancellation", "path": "github-repos/MATLAB/markostam-active-noise-cancellation/active-noise-cancellation-1476fa7fb9c449fd01a6cc0adf3d9dbbc1baf5af/Code/FxNLMS_mss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5769347551363602}}
{"text": "% Construct various DBNs and examine their clique structure.\n% This was used to generate various figures in chap 3-4 of my thesis.\n\n% Examine the cliques in the unrolled mildew net\n\n%dbn = mk_mildew_dbn;\ndbn = mk_chmm(4);\nss = dbn.nnodes_per_slice;\nT = 7;\nN = ss*T;\nbnet = dbn_to_bnet(dbn, T);\n\nconstrained = 0;\nif constrained\n  stages = num2cell(unroll_set(1:ss, ss, T), 1);\nelse\n  stages = { 1:N; };\nend\nclusters = {};\n%[jtree, root, cliques, B, w, elim_order, moral_edges, fill_in_edges] = ...\n%    dag_to_jtree(bnet, bnet.observed, stages, clusters);\n[jtree, root, cliques] =  graph_to_jtree(moralize(bnet.dag), ones(1,N), stages, clusters);\n\nflip=1;\nclf;[dummyx, dummyy, h] = draw_dbn(dbn.intra, dbn.inter, flip, T, -1);\ndir = '/home/eecs/murphyk/WP/Thesis/Figures/Inf/MildewUnrolled';\nmk_ps_from_clqs(dbn, T, cliques, [])\n%mk_collage_from_clqs(dir, cliques)\n\n\n% Examine the cliques in the cascade DBN\n\n% A-A\n%  \\\n% B B\n%  \\\n% C C\n%  \\\n% D D\nss = 4;\nintra = zeros(ss);\ninter = zeros(ss);\ninter(1, [1 2])=1;\nfor i=2:ss-1\n  inter(i,i+1)=1;\nend\n\n\n% 2 coupled HMMs 1,3  and 2,4\nss = 4;\nintra = zeros(ss);\ninter = zeros(ss); % no persistent edges\n%inter = diag(ones(ss,1)); % persitence edges\ninter(1,3)=1; inter(3,1)=1;\ninter(2,4)=1; inter(4,2)=1;\n\n%bnet = mk_fhmm(3);\nbnet = mk_chmm(4);\nintra = bnet.intra;\ninter = bnet.inter;\n\nclqs = compute_minimal_interface(intra, inter);\ncelldisp(clqs)\n\n\n\n\n% A A\n%  \\\n% B B\n%  \\\n% C C\n%  \\\n% D-D\nss = 4;\nintra = zeros(ss);\ninter = zeros(ss);\nfor i=1:ss-1\n  inter(i,i+1)=1;\nend\ninter(4,4)=1;\n\n\n\nns = 2*ones(1,ss);\ndbn = mk_dbn(intra, inter, ns);\nfor i=2*ss\n  dbn.CPD{i} = tabular_CPD(bnet, i);\nend\n\nT = 4;\nN = ss*T;\nbnet = dbn_to_bnet(dbn, T);\n\nconstrained = 1;\nif constrained\n  % elim first 3 slices first in any order\n  stages = {1:12, 13:16};\n  %stages = num2cell(unroll_set(1:ss, ss, T), 1);\nelse\n  stages = { 1:N; };\nend\nclusters = {};\n%[jtree, root, cliques, B, w, elim_order, moral_edges, fill_in_edges] = ...\n%    dag_to_jtree(bnet, bnet.observed, stages, clusters);\n[jtree, root, cliques] =  graph_to_jtree(moralize(bnet.dag), ones(1,N), stages, clusters);\n\n\n\n\n\n% Examine the cliques in the 1.5 slice DBN\n\n%dbn = mk_mildew_dbn;\ndbn = mk_water_dbn;\n%dbn = mk_bat_dbn;\nss = dbn.nnodes_per_slice;\nint = compute_fwd_interface(dbn);\nbnet15 = mk_slice_and_half_dbn(dbn, int);\nN = length(bnet15.dag);\nstages = {1:N};\n\n% bat\n%cl1 = [16 17 19 7 14];\n%cl2 = [27 25 21 23 20];\n%clusters = {cl1, cl2, cl1+ss, cl2+ss};\n\n% water\n%cl1 = 1:2; cl2 = 3:6; cl3 = 7:8;\n%clusters = {cl1, cl2, cl3, cl1+ss, cl2+ss, cl3+ss};\n\n%clusters = {};\nclusters = {int, int+ss};\n%[jtree, root, cliques, B, w, elim_order, moral_edges, fill_in_edges] = ...\n%    dag_to_jtree(bnet15, bnet.observed, stages, clusters);\n[jtree, root, cliques] =  graph_to_jtree(moralize(bnet15.dag), ones(1,N), stages, clusters);\n\nclq_len = [];\nfor c=1:length(cliques)\n  clq_len(c) = length(cliques{c});\nend\nhist(clq_len, 1:max(clq_len));\nh=hist(clq_len, 1:max(clq_len));\naxis([1 max(clq_len)+1 0 max(h)+1])\nxlabel('clique size','fontsize',16)\nylabel('number','fontsize',16)\n\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/dynamic/jtree_clq_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938799869521, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5769068587124322}}
{"text": "% MANIPULATOR TRAJECTORY GENERATION\n% Generates Cartesian trajectories with independent \n% linearly interpolated rotation trajectories.\n%\n% Copyright 2019 The MathWorks, Inc.\n\n%% Setup\nclear, clc, close all\n\n% Define waypoint information\ncreateWaypointData;\n\n% Define IK\nik = inverseKinematics('RigidBodyTree',gen3);\nikWeights = [1 1 1 1 1 1];\nikInitGuess = gen3.homeConfiguration;\n\n% Set up plot\nplotMode = 2; % 0 = None, 1 = Trajectory, 2 = Coordinate Frames\nshow(gen3,gen3.homeConfiguration,'Frames','off','PreservePlot',false);\nxlim([-1 1]), ylim([-1 1]), zlim([0 1.2])\nhold on\nif plotMode == 1\n    hTraj = plot3(waypoints(1,1),waypoints(2,1),waypoints(3,1),'b.-');\nend\nplot3(waypoints(1,:),waypoints(2,:),waypoints(3,:),'ro','LineWidth',2);\n\n%% Generate and follow trajectory\n% Loop through segments one at a time\ntrajType = 'trap';\nnumWaypoints = size(waypoints,2);\nfor w = 1:numWaypoints-1\n    % Get the initial and final rotations and times for the segment\n    R0 = eul2quat(orientations(:,w)');\n    Rf = eul2quat(orientations(:,w+1)');\n    timeInterval = waypointTimes(w:w+1);\n    trajTimes = timeInterval(1):ts:timeInterval(2);\n\n    % Cartesian Motion only\n    switch trajType\n        case 'trap'\n            [q,qd,qdd] = trapveltraj(waypoints(:,w:w+1),numel(trajTimes), ...\n                'AccelTime',waypointAccelTimes(w), ... \n                'EndTime',diff(waypointTimes(w:w+1)));\n\n        case 'cubic'\n            [q,qd,qdd] = cubicpolytraj(waypoints(:,w:w+1),waypointTimes(w:w+1),trajTimes, ... \n                'VelocityBoundaryCondition',waypointVels(:,w:w+1));\n\n        case 'quintic'\n            [q,qd,qdd] = quinticpolytraj(waypoints(:,w:w+1),waypointTimes(w:w+1),trajTimes, ... \n                'VelocityBoundaryCondition',waypointVels(:,w:w+1), ...\n                'AccelerationBoundaryCondition',waypointAccels(:,w:w+1));\n\n        case 'bspline'\n            ctrlpoints = waypoints(:,idx:idx+1); % Can adapt this as needed\n            [q,qd,qdd] = bsplinepolytraj(ctrlpoints,timeInterval,trajTimes);\n\n        otherwise\n            error('Invalid trajectory type! Use ''trap'', ''cubic'', ''quintic'', or ''bspline''');\n    end\n        \n    % Find the quaternions from trajectory generation\n    [R, omega, alpha] = rottraj(R0, Rf, timeInterval, trajTimes);    \n    \n    % Plot trajectory\n    if plotMode == 1\n        set(hTraj,'xdata',q(1,:),'ydata',q(2,:),'zdata',q(3,:));\n    elseif plotMode == 2\n        plotTransforms(q',R','FrameSize',0.05)\n    end\n    \n    % Trajectory following loop\n    for idx = 1:numel(trajTimes) \n        % Solve IK\n        tgtPose = trvec2tform(q(:,idx)') * quat2tform(R(:,idx)');\n        [config,info] = ik(eeName,tgtPose,ikWeights,ikInitGuess);\n        ikInitGuess = config;\n\n        % Show the robot\n        show(gen3,config,'Frames','off','PreservePlot',false);\n        title(['Trajectory at t = ' num2str(trajTimes(idx))])\n        drawnow    \n    end\n    \n    \nend", "meta": {"author": "mathworks-robotics", "repo": "trajectory-planning-robot-manipulators", "sha": "e7ee8775b5ace44b5da5455b6aee9c4d8cbf0b4e", "save_path": "github-repos/MATLAB/mathworks-robotics-trajectory-planning-robot-manipulators", "path": "github-repos/MATLAB/mathworks-robotics-trajectory-planning-robot-manipulators/trajectory-planning-robot-manipulators-e7ee8775b5ace44b5da5455b6aee9c4d8cbf0b4e/matlab/manipTrajLinearRotation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5768293758036777}}
{"text": "classdef AxAyComputerFromVolumeAndR < handle\n\n    properties (Access = private)\n        theta\n        r\n        cx\n        cy\n    end\n    \n    methods (Access = public)\n        \n        function obj = AxAyComputerFromVolumeAndR(cParams)\n            obj.init(cParams)\n        end\n        \n        function [ax,ay] = compute(obj)\n            h  = obj.computeH(obj.theta,obj.r);\n            Tx = obj.computeTx(obj.r,h,obj.cx);\n            Ty = obj.computeTy(obj.r,h,obj.cx);\n            ax = obj.computeAx(Tx,Ty,obj.cx);\n            ay = obj.computeAy(Tx,Ty,obj.cx);\n        end\n        \n    end\n    \n    methods (Access = private)\n        \n        function init(obj,cParams)\n            obj.theta = 1 - cParams.volume;\n            obj.r     = cParams.r;\n            obj.cx    = cParams.cx;            \n            obj.cy    = cParams.cy;\n        end\n        \n    end\n    \n    methods (Access = private, Static)\n        \n        function Tx = computeTx(r,h,cx)\n            n = r*h*(1+h);\n            d = (1+r*h)*cx;\n            Tx = n/d;\n        end\n        \n        function Ty = computeTy(r,h,cx)\n            n = cx*h*(1+r*h);\n            d = (1+h);\n            Ty = n/d;\n        end\n        \n        function ax = computeAx(Tx,Ty,cx)\n            ax = (cx - Ty)/(1-Tx*Ty);\n        end\n        \n        function ay = computeAy(Tx,Ty,cx)\n            ay = (1-Tx*cx)/(1-Tx*Ty);\n        end\n        \n        function h = computeH(theta,r)\n            n = -(1+r)*theta + sqrt(theta^2*(r-1)^2 + 4*r);\n            d = 2*r*(1+theta);\n            h = n/d;\n        end\n        \n    end\n    \nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Vigdergauz/AxAyComputers/AxAyComputerFromVolumeAndR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.576829375588732}}
{"text": "function [ratio,initdl] = fitint(ratio);\n%fitint   computes contraction/expansion ratio\n%   [ratio,initdl] = fitint(ratio);\n%   input\n%          ratio      initial guess  \n%   output\n%          ratio      converged value\n%          initdl     associated first increment\n%\n%   called by subint\n%   IFISS function: DJS; 1 April 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n      global global_N global_INTL global_LASTDL\n      if(global_N==1)\n      initdl=global_INTL;\n      ratio=global_LASTDL/initdl;\n      return\n      else\n      x=ratio;\n% call nonlinear equation solver\n%     fprintf('\\n      x            f   \\n')\n      ratio=fzero('fint',x,optimset('Display','off'));\n      initdl=global_LASTDL/(ratio^global_N);\n      end\n% check solution validity\n      if ratio <= 1,\n         fprintf('\\n\\n\\nInfeasible ratio computed for stretch grid.\\n');\n         fprintf('Try changing the initial value for \"ratio\" in function \"subint.m\"\\n');\n         error(' '); \n      elseif ratio >= 2\n         fprintf('\\n\\n*** warning \\n computed ratio is large. \\n')\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/grids/fitint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5767489232178608}}
{"text": "classdef homochoricPlot < axisAnglePlot\n  \n  methods\n    \n    function oP = homochoricPlot(varargin)\n      % create a 3d Euler angle plot\n      \n      oP = oP@axisAnglePlot(varargin{:});\n      \n     end\n        \n     function [x,y,z] = project(oP,ori,varargin)\n      \n      if ~check_option(varargin,'noBoundaryCheck')\n        switch oP.fRMode\n          case 'project2FundamentalRegion'\n            ori = project2FundamentalRegion(ori);\n          case 'restrict2FundamentalRegion'\n            ori(~oP.oR.checkInside) = NaN;\n        end\n      end\n      \n      [x,y,z] = double(homochoric(ori));\n            \n    end\n    \n    function ori = iproject(oP,x,y,z,varargin)\n      ori = orientation.id;\n    end\n    \n    function ori = makeGrid(oP,varargin)\n      \n      [ori,S2G,omega] = makeGrid@axisAnglePlot(oP,varargin{:});\n      \n      [oP.plotGrid.x,oP.plotGrid.y,oP.plotGrid.z] = ...\n        double( S2G .* (3./4 * (omega - sin(omega))).^(1/3));\n      \n    end\n  end\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/plotting/orientationPlot/homochoricPlot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5767310214709092}}
{"text": "function [sigma,mu,var_dirs,var_amts] = scm_ex(Y,A,R,sigma0,mu0,sigma_max)\n%SCM_EX Summary of this function goes here\n%   Detailed explanation goes here\n[N,M] = size(A);\n[~,B] = size(R);\nsigma_min = 1e-6;\n\nC = kron((A'*A),eye(B));\nS = (mu0^2/(sigma0^2))*eye(M*B,M*B);\n    \nh = (Y-A*R)'*A;\nh = h(:);\ngamma = 1/(mu0^2);\nlsq = sum(sum((Y-A*R).^2));\ngamma0Inv = 1/(N*B)*lsq;\nobj_fun_sigma = @(S,gamma) gamma*lsq - gamma*h'*((S+C)\\h) ...\n    + logdet(S+C) - logdet(S) - N*B*log(gamma);\ncalc_ignores = @(S,gamma) [(gamma*h'*((S+C)\\h)) / (gamma*lsq), ...\n    (logdet(S+C) - logdet(S)) / (gamma*lsq)];\ndisp(['Inital ignores are: ',num2str(calc_ignores(S,gamma))]);\nif 0\n    % U1'*N1 has a much smaller frobenius norm than that of N1\n    global A_gt; global R_gt;\n    N = Y-A*R; N1 = Y-A_gt*R_gt;\n    [U,D,V] = svd(A,0); [U1,D1,V1] = svd(A_gt,0);\n    sum(sum(N.^2)), sum(sum((U'*N).^2))\n    sum(sum(N1.^2)), sum(sum((U1'*N1).^2))\nend\nEs = obj_fun_sigma(S,gamma);\ndelta_t0 = 1e-9;\n\nT = S + C;\nTh = T\\h;\n\ndisp('Start estimating the uncertainty...');\nfor i = 1:200\n    % update S\n    S2_old = S;\n\n    GammaTinv = gamma*Th*Th';\n    Tinv = inv(T);\n    E0 = obj_fun_sigma(S,gamma);\n    delta_t = delta_t0;\n\n    der = zeros(M*B,M*B);\n    for j = 1:M     \n        inds = (j-1)*B+1:j*B;\n        Sj = S(inds,inds);\n        der(inds,inds) = GammaTinv(inds,inds) - inv(Sj) + Tinv(inds,inds);\n    end\n\n\n    while 1\n        S2_new = S - delta_t*der;\n        S2_new = (S2_new + S2_new')/2;\n        for j = 1:M\n            inds = (j-1)*B+1:j*B;\n            S3 = S2_new(inds,inds);\n\n            [V,D] = eig(S3);\n            d = diag(D);\n\n            epsilon = 1/(gamma*sigma_max^2);\n            infinity = 1/(gamma*sigma_min^2);\n            d(d<epsilon) = epsilon;\n%                 d(d>infinity) = infinity;\n\n            D = diag(d);\n            S2_new(inds,inds) = V*D*V';\n        end\n\n        E0 = [E0; obj_fun_sigma(S2_new,gamma)];\n        if E0(end) >= E0(end-1)\n            S = S2_old;\n            break;\n        else\n            S2_old = S2_new;\n            delta_t = delta_t*10;\n        end\n    end\n    % Update gamma\n    T = S + C;\n    Th = T\\h;\n    gamma = gamma0Inv - 1/(N*B)*h'*Th;\n    gamma = 1/gamma;\n    % Check the amounts of ignored terms for estimating A and R\n    if 1\n        total_amt = gamma*lsq;\n        amt1 = gamma*h'*((S+C)\\h);\n        amt2 = logdet(S+C) - logdet(S);\n        ratio1(i) = amt1/total_amt;\n        ratio2(i) = amt2/total_amt;\n    end\n    % Check convergence\n    Es = [Es;obj_fun_sigma(S,gamma)];  \n    if Es(end-1) - Es(end) <= 1e-6*(Es(1) - Es(2))\n        disp(['Finishes at iteration ',num2str(i),', current energy: ',num2str(Es(end))]);\n        disp(['Final ignores are: ',num2str(calc_ignores(S,gamma))]);\n        break;\n    end\n\n    if mod(i,5) == 0\n        disp(['Process iteration ',num2str(i),', current energy: ',num2str(Es(end))]);\n    end\nend\n\nmu = gamma^(-1/2);\nd = (1/mu) * ones(B,1);\n\n[sigma,var_dirs,var_amts] = calc_uncertainty_range(S,d);\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/SCM/scm_ex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5767310191885211}}
{"text": "function [hrf, fit, e, param] = Fit_sFIR(tc,TR,Run,T,mode)\n% function [hrf, fit, e, param] = Fit_sFIR(tc,TR,Runs,T,mode)\n%\n% Fits FIR and smooth FIR model  \n%\n% INPUTS:\n% \n% tc    - time course\n% TR    - time resolution\n% Runs  - expermental design\n% T     - length of estimated HRF\n% mode  - FIR or smooth FIR\n%   options:\n%       0 - standard FIR \n%       1 - smooth FIR\n% \n% OUTPUTS:\n%\n% hrf   - estimated hemodynamic response function\n% fit   - estimated time course\n% e     - residual time course\n% param - estimated amplitude, height and width\n%\n% Created by Martin Lindquist on 10/02/09\n% Last edited: 05/26/10 (ML)\n\nnumstim = length(Run);\nlen = length(Run{1});\n\n\nRuns = zeros(len,numstim);\nfor i=1:numstim,\n    Runs(:,i) = Run{i};\nend;\n\n[DX] = tor_make_deconv_mtx3(Runs,T,1);\n\n% DX2 = DX(:,1:T); \n% num = T;\n\nif mode == 1\n\n    C=(1:T)'*(ones(1,T));\n    h = sqrt(1/(7/TR));                       % 7 seconds smoothing - ref. Goutte\n\n    v = 0.1;\n    sig = 1;\n\n    R = v*exp(-h/2*(C-C').^2);\n    RI = inv(R);\n    MRI = zeros(numstim*T+1);\n    for i=1:numstim,\n        MRI(((i-1)*T+1):(i*T),((i-1)*T+1):(i*T)) = RI;\n    end;\n\n    b = inv(DX'*DX+sig^2*MRI)*DX'*tc;\n    fit = DX*b;\n    e = tc - DX*b; \n\nelseif mode == 0\n\n    b = pinv(DX)*tc;\n    fit = DX*b;\n    e = tc - DX*b;\n    \nend\n\n\nhrf =zeros(T,numstim);\nparam = zeros(3,numstim);\n\nfor i=1:numstim,\n    hrf(:,i) = b(((i-1)*T+1):(i*T))';\n    param(:,i) = get_parameters2(hrf(:,i),T);\nend;\n\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/HRF_Est_Toolbox2/Old_stuff/More_recent_old_stuff/Fit_sFIR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5767310169061326}}
{"text": "\n\n% Example for the adjacency matrix of\n%      0     0     1     1     1    -1     1     0\n%      0     0     1    -1     0     1     1    -1\n%      1     1     0     0     0     1     0     0\n%      1    -1     0     0     0     0    -1     0\n%      1     0     0     0     0     1    -1     1\n%     -1     1     1     0     1     0     1    -1\n%      1     1     0    -1    -1     1     0     0\n%      0    -1     0     0     1    -1     0     0\n% and 100 iterations of simulations\n\nload adj2\nheider(adj2,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/7249-heider-balance-theory/heider/example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5767310010276688}}
{"text": "%DEMO_LGCP  Demonstration for a log Gaussian Cox process\n%           with inference via EP or Laplace approximation\n%\n%  Description \n%    Log Gaussian Cox process (LGCP) is a model for non-homogeneous\n%    point-process in which the log intensity is modelled using\n%    Gaussian process. LGCP can be modelled using log GP and\n%    Poisson observation model in a discretized space. \n%\n%    The model constructed is as follows:\n%\n%    The number of occurrences of the realised point pattern within cell w_i\n%\n%         y_i ~ Poisson(y_i| |w_i|exp(f_i))\n%\n%    where |w_i| is area of cell w_i and f_i is the log intensity.\n%\n%    We place a zero mean Gaussian process prior for f =\n%    [f_1, f_2,...,f_n] ~ 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. We place a\n%    prior for parameters, p(th).\n%\n%    The inference is conducted via EP or Laplace, where we find\n%    Gaussian approximation for p(f| th, data), where th is the\n%    maximum a posterior (MAP) estimate for the parameters.\n%\n%  See also  LGCP, DEMO_SPATIAL2\n%\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% =====================================\n% 1D-example\n% =====================================\nfprintf(['Coal disaster data with EP integration over the latent values\\n'])\n\n% Coal disaster data\nS = which('demo_lgcp');\nL = strrep(S,'demo_lgcp.m','demodata/coal.txt');\nx = load(L);\nxt = (1850:1963)';\n[p1,pq1] = lgcp(x,xt,'gpcf',@gpcf_exp);\n\nfigure()\nhp=patch([xt; xt(end:-1:1)],[pq1(:,1); pq1(end:-1:1,2)],[.9 .9 .9]);\nset(hp,'edgecolor',[.9 .9 .9])\nxlim([min(x) max(x)])\nline(xt,p1,'linewidth',2);\nline([x x],[5 5.3],'color','k')\nline(xlim,[5.15 5.15],'color','k')\nxlim([1850 1963])\nylim([0 5.29])\ntitle('The coal mine disaster data, estimated intensity, and 90% interval')\nxlabel('Year')\nylabel('Intensity')\n\n% =====================================\n% 2D-example\n% =====================================\nfprintf(['Redwood data with Laplace integration over the latent\\n' ...\n         'values and MAP estimate for the parameters\\n'])\n\n% Redwood data\nS = which('demo_lgcp');\nL = strrep(S,'demo_lgcp.m','demodata/redwoodfull.txt');\nx=load(L);\nx1min=min(x(:,1));x1max=max(x(:,1));\nx2min=min(x(:,2));x2max=max(x(:,2));\n[xt1,xt2]=meshgrid(linspace(x1min,x1max,100),...\n                   linspace(x2min,x2max,100));\nxt=[xt1(:) xt2(:)];\np2 = lgcp(x,xt,'range',[0 1 0 1],'latent_method','Laplace','gridn',20);\n\nfigure()\nG=zeros(size(xt1));\nG(:)=p2;\npcolor(xt1,xt2,G);\nshading flat\ncolormap('jet')\ncx=caxis;\ncx(1)=0;\ncaxis(cx);\ncolorbar\nh=line(x(:,1),x(:,2),'marker','.','linestyle','none','color','k','markersize',10);\ncolorbar\naxis square\nset(gca,'xtick',[0:.2:1],'ytick',[0:.2:1])\ntitle('Redwood data and intensity estimate')\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_lgcp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5767047004951512}}
{"text": "function [slug] = amu2slug(amu)\n% Convert mass from atomic mass units to slugs. \n% Chad Greene 2012\nslug = amu*(3.660864489409*1e-27)/32.17405;", "meta": {"author": "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/amu2slug.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5767046987931538}}
{"text": "% [R,Q] = vgg_rq(S)  Just like qr but the other way around.\n%\n% If [R,Q] = vgg_rq(X), then R is upper-triangular, Q is orthogonal, and X==R*Q.\n% Moreover, if S is a real matrix, then det(Q)>0.\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 <http://www.gnu.org/licenses/>.\n\n% By awf\n\nfunction [U,Q] = rq(S)\n\nS = S';\n[Q,U] = qr(S(end:-1:1,end:-1:1));\nQ = Q';\nQ = Q(end:-1:1,end:-1:1);\nU = U';\nU = U(end:-1:1,end:-1:1);\n\nif det(Q)<0\n  U(:,1) = -U(:,1);\n  Q(1,:) = -Q(1,:);\nend\n\nreturn\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/vgg_rq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5767046882723545}}
{"text": "function patches = construct_grid_even(grid_size,overlap,dim,min_diff)\n\nN = length(dim);\nstart_point = cell(N,1);\nend_point = cell(N,1);\n\nfor i = 1:N\n    start_point{i} = [1:grid_size(i):dim(i)-grid_size(i)-overlap(i)+1,max(dim(i)-grid_size(i)-overlap(i)+1,1)];\n    end_point{i} = [grid_size(i)+overlap(i):grid_size(i):dim(i),dim(i)];\n    if length(start_point{i}) > 1\n        if start_point{i}(end) - start_point{i}(end-1) < min_diff(i)        \n            start_point{i}(end-1) = [];\n            end_point{i}(end-1) = [];\n        end\n    end\nend\n\nstart_grid = cell(1,N);\n[start_grid{:}] = ndgrid(start_point{:});\n\nend_grid = cell(1,N);\n[end_grid{:}] = ndgrid(end_point{:});\npatches = zeros(numel(start_grid{1}),2*N);\n\nfor i = 1:N\n    patches(:,2*i-1) = start_grid{i}(:);\n    patches(:,2*i) = end_grid{i}(:);\nend", "meta": {"author": "flatironinstitute", "repo": "NoRMCorre", "sha": "1b39f82f9673d51cdf9b38d3419b62bf06cf7196", "save_path": "github-repos/MATLAB/flatironinstitute-NoRMCorre", "path": "github-repos/MATLAB/flatironinstitute-NoRMCorre/NoRMCorre-1b39f82f9673d51cdf9b38d3419b62bf06cf7196/construct_grid_even.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5767046875297928}}
{"text": "classdef OptimalSuperEllipsePrinter < handle\n    \n    properties (Access = private)\n        mesh\n        meshBackground\n        levelSet\n        mx\n        my     \n        iter\n    end\n    \n    properties (Access = private)\n        mxV\n        myV        \n        fileName\n    end\n    \n    methods (Access = public)\n        \n        function obj = OptimalSuperEllipsePrinter()\n            obj.init();\n            obj.compute();\n        end  \n        \n    end\n    \n    methods (Access = private)\n        \n        function init(obj)\n            obj.mxV = [0.8462 0.99 0.01 0.99 0.30108 0.1 0.2 0.2  0.85];\n            obj.myV = [0.8462 0.2  0.01 0.99 0.72687 0.1 0.6 0.95 0.85];\n            obj.fileName = 'OptimaSuperEllipseMicroEllipse';\n          %  iter = 0;\n        end\n        \n        function compute(obj)            \n            for iTest = 1:length(obj.mxV)\n                obj.iter = iTest;             \n                \n                rho = SuperEllipseParamsRelator.rho(obj.mxV(obj.iter),obj.myV(obj.iter),32)\n                \n                obj.createMeshBackground();\n                obj.createLevelSet();\n                obj.createMesh();\n                obj.print();\n            end\n        end\n        \n        function createMeshBackground(obj)\n            s.testName = 'RVE_Square_Triangle_FineFine';\n            obj.meshBackground = Mesh().createFromFile(s);\n        end\n        \n        function createLevelSet(obj)\n            sM.coord  = obj.meshBackground.coord;\n            sM.connec = obj.meshBackground.connec;\n            s.mesh = Mesh_Total(sM);\n            s.widthH = obj.mxV(obj.iter);\n            s.widthV = obj.myV(obj.iter);\n            %s.pnorm  = obj.computeSmoothingExponent();\n            s.pnorm  = 2;\n            s.type = 'smoothRectangle';\n            s.levelSetCreatorSettings = s;\n            s.type = 'LevelSet';\n            s.scalarProductSettings.epsilon = 1;\n            obj.levelSet = LevelSet(s);\n        end\n        \n        function q = computeSmoothingExponent(obj)\n            s.m1 = obj.mxV(obj.iter);\n            s.m2 = obj.myV(obj.iter);\n            s.type = 'Optimal';\n            qComputer = SmoothingExponentComputer.create(s);\n            q = qComputer.compute();\n        end\n        \n        function createMesh(obj)\n            s.fileName = obj.fileName;\n            s.levelSet = obj.levelSet.value;\n            s.meshBackground = obj.meshBackground;\n            mCreator = MeshCreatorFromLevelSetWithMMG(s);\n            obj.mesh = mCreator.create();\n        end\n        \n        function print(obj)\n            outputName = [obj.fileName,'Print',num2str(obj.iter)];\n            s.mesh       = obj.mesh;\n            s.outPutName = outputName;\n            printer = SuperEllipsePrinter(s);\n            printer.print();\n            printer.captureImage();\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/Homogenization/Sources/VadamecumCalculator/OptimalSuperEllipsePrinter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5767046875297926}}
{"text": "function [LX, MX, PX] = mppca(X, no_dims, no_analyzers, tol, maxiter, minstd)\n%MPPCA Runs EM algorithm and computes local factor analyzers\n%\n%   [LX, MX, PX] = mppca(X, no_dims, no_analyzers, tol, maxiter, minstd)\n%\n% Runs EM algorithm to determine coordinates of factor analyzers. The data\n% is given in the DxN matrix X. no_dims indicates the number of dimensions that\n% the local factor analyzers compute their embedding in. The number of \n% factor analyzers that is used is given by no_analyzers. The variable tol indicates \n% the tolreance in considering the EM as converged, whereas maxiter\n% indicates the maximum number of iterations for the EM algorithm. The\n% variable minstd sets the minimum standard deviation of the Gaussians that\n% the EM algorithm fits.\n% The function returns in LX the lowdimensional representations of X of all\n% factor analyzers, in MX the means of the factors analyzers, and in PX the\n% noise covariances.\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    % Initialize some variables\n    [D N] = size(X);                % size of data\n    epsilon = 1e-9;                 % regularization parameter\n    \n    % Estimate minimum variance allowed\n    minvar = minstd ^ 2;\n\n    % Randomly initialize factor analyzers\n    mm = mean(X, 2);\n    ss = cov(X');\n    try                                                 % for small problems        \n        cc = chol(ss);\n        MX = bsxfun(@plus, cc' * randn(D, no_analyzers), mm);\n        LX = minstd * randn(D, no_dims, no_analyzers);\n        PX = 2 * mean(diag(cc)) * ones(D, 1);\n    catch                                               % for large problems (or nearly singular covariance matrices)\n        cc = std(X, [], 2);\n        MX = bsxfun(@plus, bsxfun(@times, cc, randn(D, no_analyzers)), mm);\n        LX = minstd * randn(D, no_dims, no_analyzers);\n        PX = 2 * mean(cc) * ones(D, 1);\n    end\n    clear mm ss cc\n\n    % Compute squared data\n    X2 = X .^ 2;\n    \n    % Initialize some variables\n    const = -D / 2 * log(2 * pi);\n    lik = -Inf;\n    R  = zeros(no_analyzers, N);\n    czz = zeros(no_dims, no_dims, no_analyzers);\n    zz  = zeros(no_dims, N, no_analyzers);\n\n    % Run for maxiter iterations at max\n    for i=1:maxiter\n\n        % Progress bar\n        if rem(i, 10) == 0\n            fprintf('.');\n        end\n\n        % E step\n        pii = 1 ./ PX;\n        for k=1:no_analyzers\n            l        = LX(:,:,k);                                                                       % select k-th local representation\n            ltpi     = bsxfun(@times, pii, l)';\n            ltpil    = ltpi * l;\n            iltpil   = eye(no_dims) + ltpil;\n            cc       = chol(iltpil);\n            cci      = inv(cc);\n            covz     = cci * cci';                                                                      % compute covariance\n            delta    = X - MX(:,k * ones(1, N));\n            meanz    = ((eye(no_dims) - ltpil * covz) * ltpi) * delta;\n            czz(:,:,k) = covz;\n            zz(:,:,k)  = meanz;                                                                         % update local representation\n            R(k,:)    = -.5 * (pii' * (delta .* delta) - sum(meanz .* (iltpil * meanz), 1)) - ...       % update reponsibilie\n                          sum(log(diag(cc)));\n        end\n\n        % Compute responsibilities of datapoints to the clusters\n        R = R + const + .5 * sum(log(pi));\n        R = exp(bsxfun(@minus, R, max(R, [], 1)));\n        R = bsxfun(@rdivide, R, sum(R, 1));\n\n        % Update likelihood of estimation\n        oldlik = lik;\n        lik = sum(max(R, [], 1) + log(sum(R, 1)));\n        \n        % Stop EM after convergence\n        if abs(oldlik - lik) < tol\n            break;\n        end\n\n        % M step\n        PX = 0;\n        for k=1:no_analyzers                         % Update all factor analyzers\n            r    = R(k,:);\n            z    = zz(:,:,k);\n            rz   = bsxfun(@times, z, r);\n            sr   = sum(r);\n            srz  = sum(rz, 2);\n            srxz = X * rz';\n            srx  = X * r';\n            m1   = [srxz srx];\n            m2   = [sr * czz(:,:,k) + z * rz' srz; srz' sr];\n            m1   = m1 / (m2 + (rand(size(m2)) * epsilon));     % random regularization to make sure that INV(m2) does not contain Infs\n            LX(:,:,k) = m1(:,1:no_dims);\n            MX(:,k) = m1(:,no_dims + 1);\n            PX = PX + X2 * r' - sum(LX(:,:,k) .* srxz, 2) - MX(:,k) .* srx;\n        end\n        PX = max(minvar, PX / N);\n        PX(:) = mean(PX);\n    end\n\n    % Done\n    disp(' ');\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/mppca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5766334836661721}}
{"text": "function [ml] = ft32ml(ft3)\n% Convert volume from cubic feet to milliliters. \n% Chad Greene 2012\nml = ft3*28316.846592;", "meta": {"author": "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/ft32ml.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5766334820652765}}
{"text": "function [Q] = spm_P_clusterFDR(k,df,STAT,R,n,ui,Ps)\n% Return the corrected FDR q-value\n% FORMAT [Q] = spm_P_clusterFDR(k,df,STAT,R,n,ui,Ps)\n% \n% k        - extent {RESELS}\n% df       - [df{interest} df{residuals}]\n% STAT     - Statistical field\n%            'Z' - Gaussian field\n%            'T' - T - field\n%            'X' - Chi squared field\n%            'F' - F - field\n% R        - RESEL Count {defining search volume}\n% n        - Conjunction number\n% ui       - feature-inducing threshold\n% Ps       - Vector of sorted (ascending) p-values\n\n% Q        - FDR q-value\n%__________________________________________________________________________\n%\n% References\n%\n% J.R. Chumbley and K.J. Friston, \"False discovery rate revisited: FDR and \n% topological inference using Gaussian random fields\". NeuroImage,\n% 44(1):62-70, 2009.\n%\n% J.R. Chumbley, K.J. Worsley, G. Flandin and K.J. Friston, \"Topological\n% FDR for NeuroImaging\". Under revision.\n%__________________________________________________________________________\n% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging\n\n% Justin Chumbley & Guillaume Flandin\n% $Id: spm_P_clusterFDR.m 2764 2009-02-19 15:30:03Z guillaume $\n\n% Compute uncorrected p-values based on k using Random Field Theory\n%--------------------------------------------------------------------------\n[P, Z] = spm_P_RF(1, k, ui, df, STAT, R, n);\n\n% q value using the  Benjamini & Hochberch False Discovery Rate procedure\n%--------------------------------------------------------------------------\nQ = spm_P_FDR(Z, df, 'P', n, Ps);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_P_clusterFDR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5766334735268656}}
{"text": "function [ r,flag ] =  reward_grid_world_continuous(s,x,beta,s_goal,x_goal,x_bad,r_bad,r_goal)\n%\n%\n%\nif s == s_goal \n\n    r    = r_goal;\n    flag = true;\n   \nelseif ismember(s,x_bad)\n    \n    r    = r_bad;\n    flag = true;\n    \nelse\n    r    = r_goal .* exp(-beta * pdist([x;x_goal]).^2);\n    flag = false;\n    \nend\n\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/rl_2D_gworld_functions/rewards/reward_grid_world_continuous.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5765286754955865}}
{"text": "function traffic ( cycle_num )\n\n%*****************************************************************************80\n%\n%% TRAFFIC simulates the cars waiting at one traffic light.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 November 2009\n%\n%  Author:\n%\n%    Original MATLAB version by Brian Hahn, Dan Valentine.\n%    This MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Brian Hahn, Dan Valentine,\n%    Essential MATLAB for Engineers and Scientists,\n%    Academic Press, 2009,\n%    ISBN13: 978-0123748836,\n%    LC: TA345.V34.\n%\n%  Parameters:\n%\n%    Input, integer CYCLE_NUM, the number of 10-second time cycles to model.\n%\n%  Local Parameters:\n%\n%    Local, integer CARS, the number of cars waiting at the light.\n%\n%    Local, integer CARS_IN, the total number of cars that have come.\n%\n%    Local, integer CARS_OUT, the total number of cars that have left.\n%\n%    Local, integer CYCLE, the number of time cycles that have elapsed.\n%\n%    Local, integer CYCLE_LENGTH, the number of seconds in one time cycle.\n%\n%    Local, integer GREEN_CYCLES, the number of 10-second time cycles that \n%    a green light lasts.\n%\n%    Local, integer GREEN_TIMER, keeps track of the number of time cycles the\n%    green light has been on.\n%\n%    Local, integer LIGHT, the state of the light.\n%    'r', the light is now red.\n%    'g', the light is now green.\n%\n%    Local, real P, the probability that a new car will come to the light\n%    in the next second.\n%\n%    Local, integer RED_CYCLES, the number of 10-second time cycles that \n%    a red light lasts.\n%\n%    Local, integer RED_TIMER, keeps track of the number of time cycles the\n%    red light has been on.\n%\n\n%\n%  Initialize.\n%\n  cars = 0;\n  cars_in = 0;\n  cars_out = 0;\n  car_wait_cycles = 0;\n  cycle = 0;\n  cycle_length = 10;\n  green_cycles = 2;\n  green_timer = 0;\n  light = 'r';\n  p = 0.3;\n  red_cycles = 4;\n  red_timer = 0;\n%\n%  Set up the plot data.\n%\n  plot_data = zeros(2,cycle_num+1);\n%\n%  Handle the \"0\"-th cycle.\n%\n  plot_data(1,cycle+1) = cycle;\n  plot_data(2,cycle+1) = cars;\n\n  prq ( cars, light, cycle );\n%\n%  Handle cycles 1 through CYCLE_NUM.\n%\n  for cycle = 1 : cycle_num\n%\n%  Each second of the cycle, choose a random number.\n%  If it is less than P, then a new car appeared at the light at that second.\n%\n    r = rand ( cycle_length, 1 );\n    cars_new = sum ( r < p );\n    cars = cars + cars_new;\n    cars_in = cars_in + cars_new;\n%\n%  Handle this time cycle depending on whether the light is green or red.\n%\n    if ( light == 'g' )\n      [ cars, cars_out, light, green_timer ] = go ( green_cycles, cars, ...\n        cars_out, light, green_timer );\n    else\n      [ cars, light, red_timer ] = stop ( red_cycles, cars, light, red_timer );\n    end\n%\n%  At the end of this cycle, how many cars are waiting?\n%\n    car_wait_cycles = car_wait_cycles + cars;\n%\n%  Print the current status.\n%\n    prq ( cars, light, cycle );\n\n    plot_data(1,cycle+1) = cycle;\n    plot_data(2,cycle+1) = cars;\n\n  end\n\n  plot ( plot_data(1,1:cycle_num+1), plot_data(2,1:cycle_num+1) )\n  xlabel ( 'Time Cycles' )\n  ylabel ( 'Cars Waiting' )\n  title ( 'Traffic waiting at a Light' )\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of cycles =       %d\\n', cycle_num );\n  fprintf ( 1, '  Simulated time =         %d seconds\\n', cycle_num * cycle_length );\n  fprintf ( 1, '  Number of cars in =      %d\\n', cars_in );\n  fprintf ( 1, '  Number of cars waiting = %d\\n', cars );\n  fprintf ( 1, '  Number of cars out =     %d\\n', cars_out );\n  fprintf ( 1, '  Percentage Out/In = %7.1f%%\\n', 100 * cars_out / cars_in );\n  wait_average_seconds = car_wait_cycles * cycle_length / cars_in;\n  fprintf ( 1, '  Average wait = %7.2f seconds\\n', wait_average_seconds );\n  wait_average_lights = car_wait_cycles / cars_in / ( red_cycles + green_cycles );\n  fprintf ( 1, '  Average wait = %7.2f light cycles\\n', wait_average_lights );\n\n  return\nend\nfunction [ cars, cars_out, light, green_timer ] = go ( green_cycles, cars, ...\n  cars_out, light, green_timer )\n\n%*****************************************************************************80\n%\n%% GO simulates traffic when the light is green.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    06 November 2009\n%\n%  Author:\n%\n%    Original MATLAB version by Brian Hahn, Dan Valentine.\n%    This MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Brian Hahn, Dan Valentine,\n%    Essential MATLAB for Engineers and Scientists,\n%    Academic Press, 2009,\n%    ISBN13: 978-0123748836,\n%    LC: TA345.V34.\n%\n%  Parameters:\n%\n%    Input, integer GREEN_CYCLES, the number of 10-second time cycles that \n%    a green light lasts.\n%\n%    Input, integer CARS, the number of cars stopped at the light.\n%\n%    Input, integer CARS_OUT, the total number of cars that have gone\n%    through the light.\n%\n%    Input, integer LIGHT, the state of the light.\n%    'r', the light is now red.\n%    'g', the light is now green.\n%\n%    Input, integer GREEN_TIMER, keeps track of the number of time cycles the\n%    green light has been on.\n%\n%    Output, integer CARS, the number of cars stopped at the light.\n%\n%    Output, integer CARS_OUT, the total number of cars that have gone\n%    through the light.\n%\n%    Output, integer LIGHT, the state of the light.\n%    'r', the light is now red.\n%    'g', the light is now green.\n%\n%    Output, integer GREEN_TIMER, keeps track of the number of time cycles the\n%    green light has been on.\n%\n\n%\n%  In one 10-second time cycle, we estimate 8 cars can move out.\n%\n  cars_through = min ( 8, cars );\n\n  cars = cars - cars_through;\n  cars_out = cars_out + cars_through;\n%\n%  Advance the timer.  If the green light has timed out, reset the timer \n%  and switch to red.\n%\n  green_timer = green_timer + 1;\n\n  if ( green_cycles <= green_timer )\n    light = 'r';\n    green_timer = 0;\n  end\n\n  return\nend\nfunction [ cars, light, red_timer ] = stop ( red_cycles, cars, light, ...\n  red_timer )\n\n%*****************************************************************************80\n%\n%% STOP simulates the traffic when the light is red.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 November 2009\n%\n%  Author:\n%\n%    Original MATLAB version by Brian Hahn, Dan Valentine.\n%    This MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Brian Hahn, Dan Valentine,\n%    Essential MATLAB for Engineers and Scientists,\n%    Academic Press, 2009,\n%    ISBN13: 978-0123748836,\n%    LC: TA345.V34.\n%\n%  Parameters:\n%\n%    Input, integer RED_CYCLES, the number of 10-second time cycles that \n%    a red light lasts.\n%\n%    Input, integer CARS, the number of cars stopped at the light.\n%\n%    Input, integer LIGHT, the state of the light.\n%    'r', the light is now red.\n%    'g', the light is now green.\n%\n%    Input, integer RED_TIMER, keeps track of the number of time cycles the\n%    red light has been on.\n%\n%    Output, integer CARS, the number of cars stopped at the light.\n%\n%    Output, integer LIGHT, the state of the light.\n%    'r', the light is now red.\n%    'g', the light is now green.\n%\n%    Output, integer RED_TIMER, keeps track of the number of time cycles the\n%    red light has been on.\n%\n\n%\n%  Advance the timer.\n%  If the red light has timed out, reset the timer and switch to green.\n%\n  red_timer = red_timer + 1;\n\n  if ( red_cycles <= red_timer )\n    light = 'g';\n    red_timer = 0;\n  end\n\n  return\nend\nfunction prq ( cars, light, cycle )\n\n%*****************************************************************************80\n%\n%% PRQ prints the current traffic waiting at the light.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 November 2009\n%\n%  Author:\n%\n%    Original MATLAB version by Brian Hahn, Dan Valentine.\n%    This MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Brian Hahn, Dan Valentine,\n%    Essential MATLAB for Engineers and Scientists,\n%    Academic Press, 2009,\n%    ISBN13: 978-0123748836,\n%    LC: TA345.V34.\n%\n%  Parameters:\n%\n%    Input, integer CARS, the number of cars stopped at the light.\n%\n%    Input, integer LIGHT, the state of the light.\n%    'r', the light is now red.\n%    'g', the light is now green.\n%\n%    Input, integer CYCLE, the current 10-second time cycle.\n%\n  fprintf ( 1, '%4d ', cycle );\n  if ( light == 'r' )\n    fprintf ( 'R  ' );\n  else\n    fprintf ( 'G  ' );\n  end\n  i = cars;\n  c = floor ( i / 100 );\n  i = i - 100 * c;\n  for j = 1 : c\n    fprintf ( 'C' );\n  end\n  x = floor ( i / 10 );\n  i = i - 10 * x;\n  for j = 1 : x\n    fprintf ( 'X' );\n  end\n  for j = 1 : i\n    fprintf ( 'I' );\n  end\n  fprintf ( 1, '\\n' );\n\n  return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/traffic_simulation/traffic_simulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.5765103712493508}}
{"text": "function edge = createEdge3d(varargin)\n%CREATEEDGE3D Create an edge between two 3D points, or from a 3D line.\n%\n%   E = createEdge3d(P1, P2)\n%   Creates the 3D edge joining the two points P1 and P2.\n%\n%   E = createEdge3d(LIN)\n%   Creates the 3D edge with same origin and same direction vector as the\n%   3D line LIN.\n%\n%   Example\n%     p1 = [1 1 1];\n%     p2 = [3 4 5];\n%     edge = createEdge3d(p1, p2);\n%     edgeLength3d(edge)\n%     ans =\n%         5.3852\n%   \n%   See also \n%     edges3d, drawEdge3d, clipEdge3d, edgelength3d\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2018-08-29, using Matlab 9.4.0.813654 (R2018a)\n% Copyright 2018-2022 INRA - Cepia Software Platform\n\nif nargin == 1\n    % Only one input parameter. Assumes it corresponds to a 3D line with\n    % 6 params.\n    var = varargin{1};\n    \n    if size(var, 2) ~= 6\n        error('single input must have 6 columns');\n    end\n    \n    % converts 3D line into 3D edge\n    edge = zeros(size(var));\n    edge(:, 1:3) = var(:, 1:3);\n    edge(:, 4:6) = edge(:, 1:3) + var(:,4:6);\n    \nelseif nargin == 2    \n    % 2 input parameters correspond to two 3D points\n    \n    % extract the two arguments\n    v1 = varargin{1};\n    v2 = varargin{2};\n    \n    if size(v1, 2) ~= 3 || size(v2, 2) ~= 3\n        error('Input points must be arrays with 3 columns');\n    end\n    \n    % first input parameter is first point, and second input is the\n    % second point. Allows multiple points.\n    n1 = size(v1, 1);\n    n2 = size(v2, 1);\n    if n1 == n2\n        edge = [v1 v2];\n    elseif n1 == 1 || n2 == 1\n        edge = [repmat(v1, n2, 1) repmat(v2, n1, 1)];\n    end\n    \nelse\n    error('Wrong number of arguments in ''%s''', mfilename);\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/createEdge3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.5765103693196567}}
{"text": "%% Interpolating EBSD Data\n%\n%%\n% In the section <EBSDDenoising.html Denoising> and <EBSDFilling.html\n% Filling Missing Data> we have discussed how to work with noisy EBSD data\n% the contained non indexed pixels. Hereby, we made the assumption that the\n% grid before and after the operations is the same. \n%\n% In this section we explain how to interpolate an EBSD map at positions\n% that do not belong to the grid. Lets us consider a simple example\n\nmtexdata twins;\n\n[grains, ebsd.grainId] = calcGrains(ebsd('indexed'));\n\n% this command here is important :)\nebsd = ebsd.project2FundamentalRegion(grains);\n\nplot(ebsd('indexed'),ebsd('indexed').orientations)\n\n%%\n% Now we can use the command <EBSD.interp.html |interp|> to interpolate the\n% orientation at arbitrary coordinates |x| and |y|.\n\nx = 30.5; y = 5.5;\ne1 = interp(ebsd,x,y)\n\n%%\n% By default the command <EBSD.interp.html |interp|> performs inverse\n% distance interpolation. This is different to \n\ne2 = ebsd('xy',x,y)\n\n%%\n% which returns the nearest neighbour EBSD measurement. Lets have a look at\n% the difference\n\nangle(e1.orientations,e2.orientations)./degree\n\n%% Change of the measurement grid\n% The command <EBSD.interp.html |interp|> can be used to evaluate the EBSD\n% map on a different grid, which might have higher or lower resolution or\n% might even be rotated. Lets demonstrate this \n\n% define a rotated coarse grid\nomega = 5*degree;\n[xmin, xmax, ymin, ymax] = ebsd.extent;\nx = linspace(xmin-cos(omega)*ymax,xmax,100);\ny = linspace(ymin-sin(omega)*xmax,ymax,50);\n[x,y] = meshgrid(x,y);\n\nxy = [cos(omega) -sin(omega); sin(omega) cos(omega) ] * [x(:),y(:)].';\n\n% define the EBSD data set on this new grid\nebsdNewGrid = interp(ebsd,xy(1,:),xy(2,:))\n\n% plot the regridded EBSD data set\nplot(ebsdNewGrid('indexed'),ebsdNewGrid('indexed').orientations)\n\n%%\n% Note, that we have not rotated the EBSD data but only the grid. All\n% orientations as well as the position of all grains remains unchanged.\n%\n% Another example is the change from a square to an hexagonal grid or vice\n% versa. In this case the command <EBSD.interp.html |interp|> is\n% implicitely called by the command <EBSD.gridify.html |gridify|>. In order\n% to demonstrate this functionality we start by EBSD data on a hex grid\n\nmtexdata ferrite silent\n\nplot(ebsd,ebsd.orientations)\n\n%%\n% and resample the data on a square grid. To do so we first define a\n% smaller square unit cell corresponding to the hexagonal unit cell\n\n% define a square unit cell\nhexUnitCell = abs(round(ebsd.unitCell,4));\nminUnit = min(hexUnitCell(hexUnitCell>0));\nsqunitCell = minUnit * [-1 -1;-1 1; 1 1; 1 -1];\n\n% use the square unit cell for gridify\nebsd = ebsd.gridify('unitCell',squnitCell);\n\nplot(ebsd,ebsd.orientations)\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/EBSDInter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085758631159, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.576510364751472}}
{"text": "%%\n\ncs = crystalSymmetry('m-3m');\nss = specimenSymmetry('1');\n\nodf = unimodalODF(quaternion.id,cs,ss,'halfwidth',1.5*degree);\n\n%%\n\n[~,q] = max(odf)\n\n%%\nv = [];\nr = linspace(1*degree,10*degree,10);\nfor i = 1:length(r)\n  fprintf('.');\n  v(i,1) = volume(odf,q,r(i)); \n  v(i,2) = volume(odf,quaternion.id,r(i)); \n  %v(i,1) = volume(uniformODF(cs,ss),quaternion.id,r(i)); \nend\nfprintf('\\n');\n%v(:,2) = length(cs)*(r - sin(r))./pi;\n\nplot(r/degree,v);\n\n%%\nclear v;\ncs = crystalSymmetry('m-3m');\nss = specimenSymmetry('mmm');\nr = linspace(0*degree,60*degree,20);\nomega = linspace(0,45*degree,4);\nfor i = 1:length(r)\n  for j = 1:length(omega)\n    %disp(r(i));\n    %tic\n    v(i,j,1) = volume(uniformODF(cs,ss),axis2quat(vector3d(1,1,1),omega(j)),r(i));\n    %toc\n    %tic\n    %v(i,j,2) = volume(uniformODF(cs,ss),axis2quat(xvector,omega(j)),r(i),'local');\n    %toc\n    fprintf('.');\n  end\nend\nfprintf('\\n');\nplot(r/degree,reshape(v,size(v,1),[]));\n\n%%\n\n%r = linspace(0,100*degree,20);\n%for i = 1:length(r)\n%  v(i,1) = volume(odf,calcModes(odf),r(i));\n%  v(i,2) = volume(uniformODF(cs,ss),quaternion.id,r(i)); \n%end\n\n%plot(r/degree,v);\n\n%%\ncs = crystalSymmetry('m-3m');\nss = specimenSymmetry('mmm');\nS3G = SO3Grid(1*degree,cs,ss);\nr = plotS2Grid('resolution',10*degree,'hemisphere','upper','maxrho',90*degree,'RESTRICT2MINMAX');\nrv = vector3d(r);\nd1 = zeros(size(rv));\nd2 = zeros(size(rv));\nfor i = 1:length(rv)\n  q = axis2quat(rv(i),20*degree);\n  d1(i) = length(find(dot_outer(S3G,q,'epsilon',20*degree)));\n  d2(i) = volume(uniformODF(cs,ss),q,15*degree);\n  fprintf('.');\nend\nfprintf('\\n');\nfigure(1)\nplot(r,d1./d1(1),'smooth')\nfigure(2)\nplot(r,d2./d2(1),'smooth')\ncolorbar\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/tests/check_volume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5765086694117221}}
{"text": "function J=calcSpherJacob(x,systemType,useHalfRange,lTx,lRx,M)\n%%CALCSPHERJACOB Calculate the Jacobian for a monostatic or bistatic\n%           spherical measurement with respect to 3D Cartesian position.\n%\n%INPUTS: x The 3X1 position of the target in Cartesian coordinates in the\n%          order [x;y;z].\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% useHalfRange An optional boolean value specifying whether the bistatic\n%          (round-trip) range value has been divided by two. This normally\n%          comes up when operating in monostatic mode (the most common\n%          type of spherical coordinate system), so that the range\n%          reported is a one-way range (or just half a bistatic range).\n%          The default if this parameter is not provided is false if lTx\n%          is provided and true if it is omitted (monostatic). \n%      lTx The 3X1 transmitter position in the global coordinate system\n%          with [x;y;z] components. If omitted or an empty matrix is\n%          passed, then a vector of zeros is used.\n%      lRx The 3X1 receiver position in the global coordinate system\n%          with [x;y;z] components. If omitted or an empty matrix is\n%          passed, then a vector of zeros is used.\n%        M A 3X3 rotation matrices to go from the alignment of the global\n%          coordinate system to that at the receiver. If omitted, then it\n%          is assumed that the local coordinate system is aligned with the\n%          global and M=eye(3) --the identity matrix is used.\n%\n%OUTPUTS: J A 3X3 Jacobian matrix where the rows are\n%          [bistatic range;azimuth;elevation] in that order and the columns\n%          take the derivative of the row component with respect to\n%          [x,y,z] in that order.\n%\n%This function just calls rangeGradient and spherAngGradient.\n%\n%February 2017 David F.Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<6||isempty(M))\n    M=eye(3,3); \nend\n\nif((nargin<4||isempty(lTx))&&(nargin<3||isempty(useHalfRange)))\n    useHalfRange=true;\nelseif(nargin<3||isempty(useHalfRange))\n    useHalfRange=false;\nend\n\nif(nargin<5||isempty(lRx))\n    lRx=zeros(3,1);\nend\n\nif(nargin<4||isempty(lTx))\n    lTx=zeros(3,1);\nend\n\nif(nargin<2||isempty(systemType))\n    systemType=0;\nend\n\nJ=[rangeGradient(x(1:3,:),useHalfRange,lTx(1:3),lRx(1:3));\n   spherAngGradient(x(1:3,:),systemType,lRx(1:3),M)];\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/calcSpherJacob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5765086633797789}}
{"text": "% Chapter 8 - Planar Systems.\n% Program_8a - Program to Plot a Vector Field.\n% Save M-file as vectorfield.m. Do NOT run this function file.\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% See the phase protraits in the book.\nfunction vectorfield(deqns,xval,yval,t)\nif nargin==3;\n    t=0;\nend\nm=length(xval);\nn=length(yval);\nx1=zeros(n,m);\ny1=zeros(n,m);\nfor a=1:m\n  for b=1:n\n    pts = feval(deqns,t,[xval(a);yval(b)]);\n    x1(b,a) = pts(1);\n    y1(b,a) = pts(2);\n  end\nend\narrow=sqrt(x1.^2+y1.^2);\nquiver(xval,yval,x1./arrow,y1./arrow,.5,'r');\naxis tight;\n\n% End of Program_8a.\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/2374-dynamical-systems-with-applications-using-matlab/MATLAB files 20013a/vectorfield.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5765086582125799}}
{"text": "classdef RegularizedSuperEllipseExponentPlotter < handle\n    \n    properties (Access = private)\n        vademecum\n        mesh\n        errorF\n        qAveraged\n        qRegularized\n        qComputer        \n    end\n    \n    methods (Access = public)\n        \n        function obj = RegularizedSuperEllipseExponentPlotter()\n            obj.createQcomputer();\n            obj.loadVademecum();\n            obj.createMesh();\n            obj.createErrorFunction();\n            obj.computeNumericalAveragedValue();\n            obj.computeQregularized();\n            obj.plotQforSymmetricHoles();\n            obj.plotSuperEllipseOptimalExponent();\n        end\n        \n    end\n    \n    methods (Access = private)\n                \n        function createQcomputer(obj)\n            s.m1 = [];\n            s.m2 = [];\n            obj.qComputer = SmoothingExponentComputerOptimal(s);            \n        end        \n                \n        function loadVademecum(obj)\n            obj.vademecum = VademecumReader();            \n        end\n        \n        function createMesh(obj)\n            xi = obj.vademecum.xiV;\n            rho = obj.vademecum.rhoV;\n            obj.mesh = obj.obtainMesh(xi,rho);            \n        end\n        \n        function computeNumericalAveragedValue(obj)\n            s.vademecum = obj.vademecum;\n            p = PonderatedOptimalSuperEllipseComputer(s);\n            p.compute();\n            obj.qAveraged = p.qMean;            \n        end\n        \n        function error = computeError(obj,a,b,r,qS)\n            q = obj.computeQ(a,b,r,qS); \n            error = obj.errorF(q);\n        end\n        \n        function q = computeQ(obj,a,b,r,q)\n             obj.qComputer.setParamsValues(a,b,r,q)  \n             xi  = obj.vademecum.xiV;\n             rho = obj.vademecum.rhoV;             \n             q = obj.qComputer.computeQ(xi,rho);                \n        end\n        \n        function [alpha,beta,rhoQmin,qSoptMin] = computeBestParameters(obj)\n            s.errorComputer = @(a,b,c,d) obj.computeError(a,b,c,d);\n            r = RegularizedExponentBestCoeffComputer(s);\n            [alpha,beta,rhoQmin,qSoptMin] = r.compute();\n        end\n                \n        function createErrorFunction(obj)\n            s.type              = 'SIMPLE';\n            s.mesh              = obj.mesh;\n            s.backgroundMesh    = obj.mesh;\n            s.globalConnec      = obj.mesh.connec;\n            s.npnod = obj.mesh.nnodes;\n            int = Integrator.create(s);\n            int.computeLHS();\n            p = 2;            \n            normF = @(x) ((int.computeL2norm(x)).^(p))^(1/p);            \n            obj.errorF = @(x) normF(abs(x - obj.qAveraged))/normF(obj.qAveraged);\n        end        \n        \n        function computeQregularized(obj)\n            [alpha,beta,rhoQmin,qSoptMin] = obj.computeBestParameters();                       \n            q = obj.computeQ(alpha,beta,rhoQmin,qSoptMin);            \n            obj.qRegularized = q;\n        end\n        \n        function plotQforSymmetricHoles(obj)\n            xi     = obj.vademecum.xiV;\n            isSym  = abs(xi-pi/4) < 0.01;\n            isSym  = isSym(2:end);\n            rhoSym = obj.vademecum.rhoV(isSym);\n            qAsym  = obj.qAveraged(isSym);\n            qRsym  = obj.qRegularized(isSym);\n            f = figure();\n            hold on\n            h{1} = plot(rhoSym,qAsym,'-+');\n            h{2} = plot(rhoSym,qRsym,'-+');\n            xlabel('$\\rho$','Interpreter','Latex')\n            ylabel('$q(\\xi = \\pi/4,\\rho)$','Interpreter','Latex')            \n            legN = '$\\textrm{Numerical smoothing exponent} \\, q_N$';\n            legA = '$\\textrm{Analytical smoothing exponent} \\, q_A$';            \n            legend({legN,legA},'Interpreter','Latex','Location','Best');            \n            outPutPath = '/home/alex/git-repos/MicroStructurePaper/';\n            outputName = [outPutPath,'qMaxM1M2AnalyticalNumerical'];\n            printer = plotPrinter(f,h);\n            printer.print(outputName);            \n        end\n        \n        function plotSuperEllipseOptimalExponent(obj)\n            s.title = 'Proposed ';\n            s.fileName = '/home/alex/git-repos/MicroStructurePaper/ProposedOptimal';\n            s.rhoV = rho;\n            s.xiV = xi;\n            s.value = qA;\n            s.qMean = qA;\n            p = SuperEllipseExponentPlotter(s);\n            p.plot();            \n        end\n        \n        function m = obtainMesh(obj,x,y)\n            s.coord = [x,y];\n            s.connec = obj.obtainConnec(x,y);\n            m = Mesh().create(s);\n        end\n        \n        function connec = obtainConnec(obj,x,y)\n            connec = delaunay(x,y);\n            connec = obj.obtainQualityElements(connec,x,y);\n        end        \n        \n    end\n    \n    methods (Access = private, Static)\n               \n        function connec = obtainQualityElements(connec,x,y)\n            s.coord = [x,y];\n            s.connec = connec;\n            m = Mesh().create(s);\n            qua = m.computeElementQuality';\n            isQ = qua > 0.02;\n            connec = connec(isQ,:);\n        end\n        \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/Topology Optimization/Homogenization/Sources/VadamecumCalculator/VademecumPlotter/RegularizedSuperEllipseExponentPlotter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5765086521806367}}
{"text": "function [data,units] = compute_dwing_angle_imbalance(trx,n)\n\nflies = trx.exp2flies{n};\nnflies = numel(flies);\ndata = cell(1,nflies);\nfor i = 1:nflies,\n  fly = flies(i);\n\n  imbalancer = trx(fly).wing_angler+trx(fly).wing_anglel;\n  imbalancel = -imbalancer;\n  dimbalancer = diff(imbalancer);\n  dimbalancel = diff(imbalancel);\n  data{i} = dimbalancel;\n  idx = imbalancer(1:end-1) > imbalancel(1:end-1);\n  data{i}(idx) = dimbalancer(idx);\n  \n  data{i} = data{i} ./ trx(fly).dt;\n  \nend\nunits = parseunits('rad/s');\n\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/compute_dwing_angle_imbalance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5765086521806366}}
{"text": "function[varargout]=arrayify(varargin)\n%ARRAYIFY  Converts a set of scalars or arrays into column arrays.\n%\n%   [O1,O2,O3,...,ON]=ARRAYIFY(I1,I2,I3,...,IN) where each of the IN is\n%   either a scalar or an array with M elements, converts each input \n%   variable into a length M column vector.  \n%\n%   The input variables that are M-element arrays are resized to column\n%   vectors, while scalars are replicated to have M identical elements.\n%\n%   ARRAYIFY will return an error if any of the input variables that are \n%   not scalars have different numbers of elements from each other. \n%\n%   ARRAYIFY(I1,I2,...IN); with no output arguments overwrites the original\n%   input variables.\n%\n%   'arrayify --t' runs a test.\n%\n%   Usage: [o1,o2,o3]=arrayify(i1,i2,i3);\n%   __________________________________________________________________\n%   This is part of JLAB --- type 'help jlab' for more information\n%   (C) 2013--2016 J.M. Lilly --- type 'help jlab_license' for details\n \nif strcmpi(varargin{1}, '--t')\n    arrayify_test,return\nend\n\n\nM=zeros(length(varargin),1);\nfor i=1:length(varargin)\n    varargin{i}=varargin{i}(:);\n    M(i)=length(varargin{i});\nend\n\nif any(M>1)\n    if any(M(M~=1)~=max(M))\n        error('Input parameters must either be scalars or arrays having the same number of elements.')\n    end\n    M=max(M);\n    for i=1:length(varargin)\n        varargin{i}=varargin{i}+0*ones(M,1);\n    end\n    varargout=varargin;\n    eval(to_overwrite(nargin));\nelse\n    %Do nothing.  No need to overwrite in this case. \n    varargout=varargin;\nend\n\nfunction[]=arrayify_test\n\n[o1,o2,o3]=arrayify(4,1:10,[1:10]');\n\nreporttest('ARRAYIFY',aresame(o1,4+0*[1:10]')&aresame(o2,[1:10]')&aresame(o3,[1:10]'))\n\ni1=4;\ni2=1:10;\ni3=[1:10]';\n\narrayify(i1,i2,i3);\n\nreporttest('ARRAYIFY with overwriting',aresame(i1,4+0*[1:10]')&aresame(i2,[1:10]')&aresame(i3,[1:10]'))\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jCommon/arrayify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.5765086500294094}}
{"text": "\nmaxmag = ceil(10*max(newt2.Magnitude))/10;\nmima = min(newt2.Magnitude);\nif mima > 0 ; mima = 0 ; end\n\n[bval,xt2] = hist(newt2.Magnitude,(mima:0.1:maxmag));\n% normalise to annula rates\nbval = bval/(max(newt2.Date)-min(newt2.Date));\nbvalsum = cumsum(bval); % N for M <=\nbval2 = bval(length(bval):-1:1);\nbvalsum3 = cumsum(bval(length(bval):-1:1));    % N for M >= (counted backwards)\nxt3 = (maxmag:-0.1:mima);\n\nbackg_ab = log10(bvalsum3);\n\nfigure_w_normalized_uicontrolunits(bfig);delete(gca);delete(gca); delete(gca); delete(gca)\nrect = [0.22,  0.3, 0.65, 0.6];           % plot Freq-Mag curves\naxes('position',rect);\n\n%%\n% plot the cum. sum in each bin  %%\n%%\n\n%pl =semilogy(xt3,bvalsum3,'sb');\n%set(pl,'LineWidth',1.0,'MarkerSize',6,...\n%    'MarkerFaceColor','w','MarkerEdgeColor','k');\n%hold on\npl1 =semilogy(xt3,bval2,'^b');\nset(pl1,'LineWidth',1.0,'MarkerSize',4,...\n    'MarkerFaceColor',[0.7 0.7 .7],'MarkerEdgeColor','k');\n\n\nbv2 = [];bv3 = [] ; me = [];BV = [];\nni2 = 50;\n\nfor i = 1:ni2/1:length(newt2)-ni2\n    [bv magco stan ] =  bvalca2(newt2(i:i+ni2,:));\n    l = newt2(i:i+ni2,:) >= magco;\n    nn2 = newt2(i:i+ni2,l);\n\n    [bval,xt2] = hist(nn2(:,6),(mima:0.1:maxmag));\n    % normalise to annula rates\n    bval = bval/(max(nn2(:,3))-min(nn2(:,3)));\n    bvalsum = cumsum(bval); % N for M <=\n    bval2 = bval(length(bval):-1:1);\n    bvalsum3 = cumsum(bval(length(bval):-1:1));    % N for M >= (counted backwards)\n\n    hold on\n    pl1 =semilogy(xt3,bval2,'^b');\n    set(pl1,'LineWidth',1.0,'MarkerSize',4,...\n        'MarkerFaceColor',[0.7 0.7 .7],'MarkerEdgeColor','k');\n    pause\n\nend\n\nbv2 = [bv2 ; magco newt2(i+ni2/2,3)];\nBV = [BV ; magco newt2(i,3) ; magco newt2(i+ni2,3) ; inf inf];\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/bwithvarmv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.576508646148693}}
{"text": "function grains = smooth(grains,iter,varargin)\n% constraint laplacian smoothing of grain boundaries\n%\n% Input\n%  grains - @grain2d\n%  iter   - number of iterations (default: 1)\n%\n% Output\n%  grains - @grain2d\n%\n% Options\n%  moveTriplePoints  - do not exclude triple/quadruple points from smoothing\n%  moveOuterBoundary - do not exclude outer boundary from smoothing\n%  second_order, S2  - second order smoothing\n%  rate              - default smoothing kernel  \n%  gauss             - gaussian smoothing kernel  \n%  exp               - exponential smoothing kernel  \n%  umbrella          - umbrella smoothing kernel   \n \nif nargin < 2 || isempty(iter), iter = 1; end\n\n% compute incidence matrix vertices - faces\nI_VF = [grains.boundary.I_VF,grains.innerBoundary.I_VF];\n\n% compute vertice adjacency matrix\nA_V = I_VF * I_VF';\nt = size(A_V,1);\n\n% do not consider triple points\nif check_option(varargin,'moveTriplePoints')\n  ignore = false(size(A_V,1),1);\nelse\n  ignore = full(diag(A_V)) > 2;\nend\n\n% ignore outer boundary\nif ~check_option(varargin,'moveOuterBoundary')\n  ignore(grains.boundary.F(any(grains.boundary.grainId==0,2),:)) = true;\nend\n\nif check_option(varargin,{'second order','second_order','S','S2'})\n  A_V = logical(A_V + A_V*A_V);\n  A_V = A_V - diag(diag(A_V));\nend\n\nweight = get_flag(varargin,{'gauss','expotential','exp','umbrella','rate'},'rate');\nlambda = get_option(varargin,weight,.5);\n\nV = full(grains.V);\nisNotZero = ~all(~isfinite(V) | V == 0,2) & ~ignore;\n\nfor l=1:iter\n  if ~strcmpi(weight,'rate')\n    [i,j] = find(A_V);\n    d = sqrt(sum((V(i,:)-V(j,:)).^2,2)); % distance\n    switch weight\n      case 'umbrella'\n        w = 1./(d);\n        w(d==0) = 1;\n      case 'gauss'\n        w = exp(-(d./lambda).^2);\n      case {'expotential','exp'}\n        w = lambda*exp(-lambda*d);\n    end\n    \n    A_V = sparse(i,j,w,t,t);\n  end\n\n  % take the mean over the neigbours\n  Vt = A_V*V;\n  \n  m = sum(A_V,2);\n  \n  dV = V(isNotZero,:)-bsxfun(@rdivide,Vt(isNotZero,:),m(isNotZero,:));\n  \n  isZero = any(~isfinite(dV),2);\n  dV(isZero,:) = 0;\n  \n  V(isNotZero,:) = V(isNotZero,:) - lambda*dV;\n  \nend\n\ngrains.V = 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/EBSDAnalysis/@grain2d/smooth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5765086349495505}}
{"text": "function [D]=patchEdgeLengths(F,V)\n\n% function [D]=patchEdgeLengths(F,V)\n% -----------------------------------------------------------------------\n% Computes the edge lengths (D) for the patch data specified by the faces\n% (F) and vertices (V) arrays. If size(F,2)>2 it is assumed that F indeed\n% represents faces. If however size(F,2)==2 it is instead assumed that F is\n% an array representing edges. As such it skips the computation of the\n% edges array. The edges array used is non-unique by default. See the\n% |patchEdges| function for more details if the lengths of a unique set of\n% edges is desired. \n%\n%\n% See also: |patchEdges|\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% \n% 2014/03/17\n%------------------------------------------------------------------------\n\n%%\n\n%Derive edge array\nif size(F,2)>2 %The input is assumed to represent faces hence an edge array is derived\n    E=patchEdges(F);\nelse %It is assumed that the input array represents an edges array\n    E=F; \nend\n\n%Derive edge vertex arrays\nV_E1=V(E(:,1),:);\nV_E2=V(E(:,2),:);\n\n%Derive difference vectors\nVD=(V_E1-V_E2);\n\n%Compute the edge lengths\nD=sqrt(sum(VD.^2,2));\n\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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) 2017  Kevin Mattheus Moerman\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program.  If not, see <http://www.gnu.org/licenses/>.\n", "meta": {"author": "MultiDIC", "repo": "MultiDIC", "sha": "d363c3ea74673e58df275d4a4c8e528ef5472acb", "save_path": "github-repos/MATLAB/MultiDIC-MultiDIC", "path": "github-repos/MATLAB/MultiDIC-MultiDIC/MultiDIC-d363c3ea74673e58df275d4a4c8e528ef5472acb/lib_ext/GIBBON/lib/patchEdgeLengths.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.576416787315041}}
{"text": "function pass = test_constructor2( pref ) \n% This tests the chebfun3 constructor. \n\nif ( nargin < 1 ) \n    pref = chebfunpref; \nend \ntol = 1e2 * pref.cheb3Prefs.chebfun3eps;\n\n% Test building Chebfun3 objects from sample data: \nexactCoeffs = rand(3,3,3);\nconstructorCoeffs = chebcoeffs3(chebfun3(exactCoeffs, 'coeffs'));\npass(1) = norm(exactCoeffs(:) - constructorCoeffs(:)) < 10*tol;\n\nexactCoeffs = rand(4,4,4);\nconstructorCoeffs = chebcoeffs3(chebfun3(exactCoeffs, 'coeffs'));\npass(2) = norm(exactCoeffs(:) - constructorCoeffs(:)) < 10*tol;\n\n% Make a chebfun3 based on TRIGTECH by calling the 'trig' flag:\nf1 = chebfun3(@(x,y,z) cos(pi*x).*sin(pi*y).*cos(pi*z),'trig'); \nf2 = chebfun3(@(x,y,z) cos(pi*x).*sin(pi*y).*cos(pi*z), ...\n    [-1 1 -1 1 -1 1], 'trig');\npass(3) = norm( f1 - f2 ) < tol;\n\nf1 = chebfun3(@(x,y,z) cos(pi*cos(pi*x) + pi*sin(pi*y) + ...\n    pi*cos(pi*z)),'trig');\nf2 = chebfun3(@(x,y,z) cos(pi*cos(pi*x) + pi*sin(pi*y) + ...\n    pi*cos(pi*z)), [-1 1 -1 1 -1 1], 'trig');\npass(4) = ( norm(f1 -f2) < 10*tol );\n\n% Check underlying tech is a TRIGTECH: \ncolTech = get(f1.cols.funs{1}, 'tech');\nrowTech = get(f1.rows.funs{1}, 'tech');\ntubeTech = get(f1.tubes.funs{1}, 'tech');\npass(5) = isa(colTech(), 'trigtech'); \npass(6) = isa(rowTech(), 'trigtech'); \npass(7) = isa(tubeTech(), 'trigtech'); \n\n% Make sure the 'periodic' flag works as well:\nf1 = chebfun3(@(x,y,z) cos(pi*cos(pi*x) + pi*sin(pi*y) + ...\n    pi*cos(pi*z)),'periodic');\nf2 = chebfun3(@(x,y,z) cos(pi*cos(pi*x) + pi*sin(pi*y) + ...\n    pi*cos(pi*z)), [-1 1 -1 1 -1 1], 'periodic');\npass(8) = ( norm(f1 -f2) < 10*tol );\n\n% Check underlying tech is a TRIGTECH:\ncolTech = get(f1.cols.funs{1}, 'tech');\nrowTech = get(f1.rows.funs{1}, 'tech');\ntubeTech = get(f1.tubes.funs{1}, 'tech');\npass(9) = isa(colTech(), 'trigtech'); \npass(10) = isa(rowTech(), 'trigtech'); \npass(11) = isa(tubeTech(), 'trigtech') ; \n\n% Test making a chebfun3 from a scalar coefficient:\nf = chebfun3(1, 'coeffs'); \npass(12) = norm(f - 1) < tol ;\n\n% Test passing an 'eps' value. Make sure it affects both rank and lengths.\nff = @(x,y,z) -x.*sin(sqrt(x+15+2*y+3*z));\nf = chebfun3(ff);\nfEps = chebfun3(ff, 'eps', 1e-8);\n[m, n, p] = length(f);\n[mEps, nEps, pEps] = length(fEps);\npass(13) = mEps < m && nEps < n && pEps < p ;\n\n[r1, r2, r3] = rank(f);\n[r1Eps, r2Eps, r3Eps] = rank(fEps);\npass(14) = r1Eps < r1 && r2Eps < r2 && r3Eps < r3 ;\n\n% Construct from a string of constant type:\nf = chebfun3('pi');\npass(15) = f(0,0,0) - pi < tol;\n\n% Construct from a string of a univariate function\nf = chebfun3('cos(alpha)');\npass(16) = f(0,0,0) - cos(0) < tol;\n\n% Construct from a string of a bivariate function\nf = chebfun3('x+y');\npass(17) = f(0.25,0.5,0) - 0.75 < tol;\n\n% Construct from a string of a trivariate function\nf = chebfun3('cos(x+y+z)');\npass(18) = f(0.25,0.5,-0.3) - cos(0.25+0.5-0.3) < tol;\n\n% Test that the 'equi' flag outputs an error message if used for\n% adaptive construction of a chebfun3.\ntry\n    f = chebfun3(@(x, y, z) z.*x.^2.*exp(sin(x + y)), 'equi');\n    pass(19) = false;\ncatch ME\n    pass(19) = strcmp(ME.identifier, 'CHEBFUN:CHEBFUN3:constructor:equi');\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_constructor2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5763686229038686}}
{"text": "function c8_cube_root_test ( )\n\n%*****************************************************************************80\n%\n%% C8_CUBE_ROOT_TEST tests C8_CUBE_ROOT.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 March 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  test_num = 10;\n  seed = 123456678;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'C8_CUBE_ROOT_TEST\\n' );\n  fprintf ( 1, '  C8_CUBE_ROOT computes the principal cube root of a C8.\\n' );\n \n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ...\n    '            C1=random            C2=C8_CUBE_ROOT(C1)         C3=C2*C2*C2\\n' );\n  fprintf ( 1, '\\n' );\n\n  for test = 1 : test_num\n \n    [ c1, seed ] = c8_uniform_01 ( seed );\n    c2 = c8_cube_root ( c1 );\n    c3 = c1 * c1 * c1;\n\n    fprintf ( 1, '  %10f  %10f    %10f  %10f    %10f  %10f\\n', ...\n      real ( c1 ), imag ( c1 ), ...\n      real ( c2 ), imag ( c2 ), ...\n      real ( c3 ), imag ( c3 ) );\n \n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/c8lib/c8_cube_root_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5763653311274045}}
{"text": "function varargout = transformPoint(varargin)\n%TRANSFORMPOINT Transform a point with an affine transform.\n%\n%   PT2 = transformPoint(PT1, TRANS);\n%   where PT1 has the form [xp yp], and TRANS is a [2*2], [2*3] or [3*3]\n%   matrix, returns the point transformed with affine transform TRANS.\n%\n%   Format of TRANS can be one of :\n%   [a b]   ,   [a b c] , or [a b c]\n%   [d e]       [d e f]      [d e f]\n%                            [0 0 1]\n%\n%   PT2 = transformPoint(PT1, TRANS);\n%   Also works when PTA is a [N*2] array of double. In this case, PT2 has\n%   the same size as PT1.\n%\n%   [PX2 PY2] = transformPoint(PX1, PY1, TRANS);\n%   Also works when PX1 and PY1 are arrays the same size. The function\n%   transform each couple of (PX1, PY1), and return the result in \n%   (PX2, PY2), which is the same size as (PX1 PY1).\n%\n%\n%   See also:\n%   points2d, transforms2d, translation, rotation\n%\n%   ---------\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 06/04/2004.\n%\n\n%   HISTORY\n%   25/04/2005 : support for 2D arrays of points (px, py, trans).\n\n\nif length(varargin)==2\n    var = varargin{1};\n    px = var(:,1);\n    py = var(:,2);\n    trans = varargin{2};\nelseif length(varargin)==3\n    px = varargin{1};\n    py = varargin{2};\n    trans = varargin{3};\nelse\n    error('wrong number of arguments in \"transformPoint\"');\nend\n\n\n% compute position\npx2 = px*trans(1,1) + py*trans(1,2);\npy2 = px*trans(2,1) + py*trans(2,2);\n\n% add translation vector, if exist\nif size(trans, 2)>2\n    px2 = px2 + trans(1,3);\n    py2 = py2 + trans(2,3);\nend\n\n\nif nargout==0 || nargout==1\n    varargout{1} = [px2 py2];\nelseif nargout==2\n    varargout{1} = px2;\n    varargout{2} = py2;\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/private/transformPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5763385044282462}}
{"text": "function [ n_data, a, b, lambda, x, fx ] = beta_noncentral_cdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% BETA_NONCENTRAL_CDF_VALUES returns some values of the noncentral Beta CDF.\n%\n%  Discussion:\n%\n%    The values presented here are taken from the reference, where they\n%    were given to a limited number of decimal places.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 February 2003\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    R Chattamvelli, R Shanmugam,\n%    Algorithm AS 310:\n%    Computing the Non-central Beta Distribution Function,\n%    Applied Statistics,\n%    Volume 46, Number 1, 1997, pages 146-156.\n%\n%  Parameters:\n%\n%    Input/output, integer N_DATA.  The user sets N_DATA to 0\n%    before the first call.  On each call, the routine increments N_DATA by 1,\n%    and returns the corresponding data; when there is no more data, the\n%    output value of N_DATA will be 0 again.\n%\n%    Output, rea A, B, the shape parameters.\n%\n%    Output, real LAMBDA, the noncentrality parameter.\n%\n%    Output, real X, the argument of the function.\n%\n%    Output, real FX, the value of the function.\n%\n  n_max = 25;\n\n  a_vec = [ ...\n        5.0, ...\n        5.0, ...\n        5.0, ...\n       10.0, ...\n       10.0, ...\n       10.0, ...\n       20.0, ...\n       20.0, ...\n       20.0, ...\n       10.0, ...\n       10.0, ...\n       15.0, ...\n       20.0, ...\n       20.0, ...\n       20.0, ...\n       30.0, ...\n       30.0, ...\n       10.0, ...\n       10.0, ...\n       10.0, ...\n       15.0, ...\n       10.0, ...\n       12.0, ...\n       30.0, ...\n       35.0 ];\n  b_vec = [ ...\n        5.0, ...\n        5.0, ...\n        5.0, ...\n       10.0, ...\n       10.0, ...\n       10.0, ...\n       20.0, ...\n       20.0, ...\n       20.0, ...\n       20.0, ...\n       10.0, ...\n        5.0, ...\n       10.0, ...\n       30.0, ...\n       50.0, ...\n       20.0, ...\n       40.0, ...\n        5.0, ...\n       10.0, ...\n       30.0, ...\n       20.0, ...\n        5.0, ...\n       17.0, ...\n       30.0, ...\n       30.0 ];\n  fx_vec = [ ...\n       0.4563021, ...\n       0.1041337, ...\n       0.6022353, ...\n       0.9187770, ...\n       0.6008106, ...\n       0.0902850, ...\n       0.9998655, ...\n       0.9925997, ...\n       0.9641112, ...\n       0.9376626573, ...\n       0.7306817858, ...\n       0.1604256918, ...\n       0.1867485313, ...\n       0.6559386874, ...\n       0.9796881486, ...\n       0.1162386423, ...\n       0.9930430054, ...\n       0.0506899273, ...\n       0.1030959706, ...\n       0.9978417832, ...\n       0.2555552369, ...\n       0.0668307064, ...\n       0.0113601067, ...\n       0.7813366615, ...\n       0.8867126477 ];\n  lambda_vec = [ ...\n        54.0, ...\n       140.0, ...\n       170.0, ...\n        54.0, ...\n       140.0, ...\n       250.0, ...\n        54.0, ...\n       140.0, ...\n       250.0, ...\n       150.0, ...\n       120.0, ...\n        80.0, ...\n       110.0, ...\n        65.0, ...\n       130.0, ...\n        80.0, ...\n       130.0, ...\n        20.0, ...\n        54.0, ...\n        80.0, ...\n       120.0, ...\n        55.0, ...\n        64.0, ...\n       140.0, ...\n        20.0 ];\n  x_vec = [ ...\n       0.8640, ...\n       0.9000, ...\n       0.9560, ...\n       0.8686, ...\n       0.9000, ...\n       0.9000, ...\n       0.8787, ...\n       0.9000, ...\n       0.9220, ...\n       0.868, ...\n       0.900, ...\n       0.880, ...\n       0.850, ...\n       0.660, ...\n       0.720, ...\n       0.720, ...\n       0.800, ...\n       0.644, ...\n       0.700, ...\n       0.780, ...\n       0.760, ...\n       0.795, ...\n       0.560, ...\n       0.800, ...\n       0.670 ];\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    lambda = 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    lambda = lambda_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/asa226/beta_noncentral_cdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5763384944323403}}
{"text": "options = optimset('GradObj','on');\n[x,y]=fminunc('fun3',rand(1,2),options)\n", "meta": {"author": "Eurus-Holmes", "repo": "Mathematical_Modeling", "sha": "cb9dd53af84ffbd455ec62ab89886351e0ec98d9", "save_path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling", "path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling/Mathematical_Modeling-cb9dd53af84ffbd455ec62ab89886351e0ec98d9/Mathematical_Modeling_Algorithms_and_Applications_Second_Edition_Procedures_and_Data/03\u7b2c3\u7ae0/ex3_5_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5763384894343873}}
{"text": "function [stats,st] = lme_fit_EM(X,Zcols,y,ni,e)\n% [stats,st] = lme_fit_EM(X,Zcols,y,ni,e)\n%\n% Linear mixed-effects estimation by expectation maximization.\n%\n% Input\n% X: Ordered design Matrix (according to time for each subject).\n% Zcols: Vector with the indices of the colums of X that will be considered\n% as random effects.\n% y: Ordered data vector (according to X).\n% ni: Vector whose entries are the number of repeated measures for each\n% subject (ordered according to X).\n% e: Convergence epsilon. Default 10^-6;\n%\n% Output\n% stats.Bhat: Estimated vector of the population regresion parameters.\n% stats.CovBhat: Estimated covariance matrix of the population regresion \n% parameters.\n% stats.bihat: Estimated subject especific random effects. \n% stats.Covbihat: Estimated covariance of the subject especific random \n% coefficients.\n% stats.phisqhat: Estimated within-subject variability.\n% stats.SIGMA: Estimated marginal covariance matrices for each subject \n% stacked in SIGMA. \n% stats.W: Inverses of the estimated marginal covariance matrices for each \n% subject stacked in W.\n% stats.Dhat = Estimated random effects covariance matrix.\n% stats.X: Design matrix.\n% stats.Zcols: Same as Zcols in the input.\n% stats.re: Residuals;\n% stats.ni: Same as ni in the input.;\n%\n% $Revision: 1.2 $  $Date: 2015/01/06 17:14:57 $\n% Original Author: Jorge Luis Bernal Rusiel \n% CVS Revision Info:\n%    $Author: mreuter $\n%    $Date: 2015/01/06 17:14:57 $\n%    $Revision: 1.2 $\n% References: Bernal-Rusiel J.L., Greve D.N., Reuter M., Fischl B., Sabuncu\n% M.R., 2012. Statistical Analysis of Longitudinal Neuroimage Data with Linear \n% Mixed Effects Models, NeuroImage, doi:10.1016/j.neuroimage.2012.10.065.\n%\ntic;   \nif nargin < 4 \n    error('Too few inputs');   \nelseif nargin < 5\n    e = 10^-6;\nend;\ntry\n    Z = X(:,Zcols);\ncatch Me\n    error(['The colums of X specify in Zcols are not correct: ' Me.message]);\nend\nnit = 1000;\nst = 1;\nm = length(ni);\np = size(X,2);\nq = length(Zcols);\nn = sum(ni);\nnimax = max(ni);\nW = zeros(n,nimax);\nbihat = zeros(q,m);\ntheta3 = zeros(q*q+1,3);\n\n%Starting values\n[D,phisq] = lme_fit_init(X,Zcols,y,ni);\n\n%% Iterations\nlreml0 = -10^10; \ntf = true;\nit = 0;\ndisplay('Starting Expectation Maximization iterations');\nwhile tf \n    it = it+1;\n    %Computation of W = SIGMA^-1 and H.\n    posi = 1; H = 0; Term = 0;\n    scInvD = D\\eye(q)*phisq;\n    for i=1:m\n        posf = posi+ni(i)-1;\n        Zi = Z(posi:posf,:);\n        Wi = (eye(ni(i))-Zi/(Zi'*Zi+scInvD)*Zi')/phisq;\n        W(posi:posf,1:ni(i)) = Wi;\n        Xi = X(posi:posf,:);\n        Ti = Xi'*Wi;\n        H = H + Ti*Xi;\n        Term = Term + Ti*y(posi:posf);\n        posi = posf+1;\n    end;\n    invH = H\\eye(p);\n   %Estimation\n    Bhat = invH*Term;\n    r = y-X*Bhat;\n    Dhat = zeros(q,q);\n    phisqhat = 0;\n    posi = 1; lreml = 0; \n    for i=1:m\n        posf = posi+ni(i)-1;\n        Zi = Z(posi:posf,:);\n        Wi = W(posi:posf,1:ni(i));\n        Xi = X(posi:posf,:);\n        ri = r(posi:posf);\n        bihat(:,i) = D*Zi'*Wi*ri;\n        Pi = Wi - Wi*Xi*invH*Xi'*Wi;\n        phisqhat = phisqhat + (ri-Zi*bihat(:,i))'*(ri-Zi*bihat(:,i))+phisq*...\n                                             trace(eye(ni(i))-phisq*Pi);\n        Dhat = Dhat+bihat(:,i)*bihat(:,i)'+D-D*Zi'*Pi*Zi*D;\n        lreml = lreml + log(det(Wi))-ri'*Wi*ri;\n        posi = posf+1;\n    end;\n    phisqhat = phisqhat/n;\n    Dhat = Dhat/m;\n    %Restricted log-likelihood\n    lreml = 0.5*(lreml - log(det(H)));\n    eps = abs(lreml-lreml0);\n    display(['Likelihood at EM iteration ' num2str(it) ' : ' num2str(lreml)]);\n    display(['Epsilon: ' num2str(eps)]);\n    %Aitken acceleration\n    theta3(:,1) = theta3(:,2);\n    theta3(:,2) = theta3(:,3);\n    theta3(:,3) = [vec(Dhat);phisqhat];\n    if mod(it,10)==0 \n        lhat = mean((theta3(:,3)-theta3(:,2))./(theta3(:,2)-theta3(:,1)));\n        if (lhat > 0) && (lhat < 1)\n           theta3(:,3) = theta3(:,2) + (theta3(:,3)-theta3(:,2))/(1-lhat);\n           Dhat = reshape(theta3(1:end-1,3),q,q);\n           phisqhat = theta3(end,3);\n        end;\n    end; \n    \n    %Termination\n    if (it==nit) || (eps<e)\n        tf = false;\n        SIGMA = zeros(n,nimax);\n        Cbihat = zeros(q*m,q);\n        posi = 1; \n        for i=1:m\n            posf = posi+ni(i)-1;\n            Zi = Z(posi:posf,:);\n            SIGMA(posi:posf,1:ni(i)) = Zi*D*Zi'+ eye(ni(i))*phisq;\n            Wi = W(posi:posf,1:ni(i));\n            Xi = X(posi:posf,:);\n            Pi = Wi - Wi*Xi*invH*Xi'*Wi;\n            Cbihat((i-1)*q+1:i*q,:) = D-D*Zi'*Pi*Zi*D;\n            posi = posf+1;\n        end;\n       stats = struct('Bhat',Bhat,'CovBhat',invH,'bihat',bihat,...\n             'Covbihat',Cbihat,'phisqhat',phisq,'SIGMA',SIGMA,'W',W,...\n             'Dhat',D,'X',X,'Zcols',Zcols,'re',r,'ni',ni,'lreml',lreml);\n        if it == nit\n            st = 0;\n            display(['Algorithm does not converge after ' num2str(nit)...\n                                                        ' iterations!!!']);\n        end;\n    else\n        lreml0 = lreml;\n        D = Dhat;\n        phisq = phisqhat;\n    end;   \nend\ntoc;\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/lme/univariate/lme_fit_EM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5763384715795024}}
{"text": "%                               431-400 Year Long Project \n%                               LA1 - Medical Image Processing 2003\n% Supervisor     :  Dr Lachlan Andrew\n% Group Members  :  Alister Fong    78629   a.fong1@ugrad.unimelb.edu.au\n%                   Lee Siew Teng   102519  s.lee1@ugrad.unimelb.edu.au\n%                   Loh Jien Mei    103650  j.loh1@ugrad.unimelb.edu.au\n%\n% File and function name : calculate_min_distance\n% Version                : 1.0\n% Date of completion     : 6 October 2003   \n% Written by    :   Alister Fong    78629   a.fong1@ugrad.unimelb.edu.au\n%\n% Input   : \n%           edge1,edge2 -   [X,Y] coordinates to be compared and measured\n%           'testing' or 'not testing' (optional) - Default 'not testing'\n%\n% Output  : \n%           min_distance - Returns the minimum distance between the two \n%                          sets of coordinates.\n%           matching_coordinates - [edge1X,edge1Y,edge2X,edge2Y]\n%                           Pairs of coordinates of edge1 and edge 2 that \n%                           are of the minimum distance.\n%\n% Description:\n%       Calculates the minimum distance between 2 edges and returns the distance and\n%   the matrix linking the coordinates to both edge coordinates.\n%     \n% Usage >> [min_distance,matching_coordinates] = calculate_min_distance(edge1,edge2)\n%                   or\n%          [min_distance,matching_coordinates] = calculate_min_distance(edge1,edge2,'testing')\n%                   or\n%          [min_distance,matching_coordinates] = calculate_min_distance(edge1,edge2,'not testing')\n%\n% Example >> [min_distance,matching_coordinates] = calculate_min_distance(edge1,edge2)\n%                 figure;\n%                 plot(edge1(:,1),edge1(:,2),'r+-');\n%                 hold on;\n%                 plot(edge2(:,1),edge2(:,2),'b+-');\n%                 for n = 1:1:length(matching_coordinates(:,1))\n%                     plot([matching_coordinates(n,1);matching_coordinates(n,3)],...\n%                          [matching_coordinates(n,2);matching_coordinates(n,4)],'g*-');\n%                 end        \n%                 xlabel(strcat('minimum distance = ',num2str(min_distance)));\n%\n% WARNING >> In some coordinates there may visually be some overlaping lines that do not register\n%            as being of distance 0. This is because the pixels representing these lines\n%            do not coincide.\n\nfunction [min_distance,matching_coordinates] = calculate_min_distance(edge1,edge2,varargin)\n% ---------------------------------------------------------------------------------\n% Process the input\n% ---------------------------------------------------------------------------------\ntesting = 'not testing';\nif ~isempty(varargin)\n    for n = 1:1:length(varargin)\n        if strcmp(varargin{n},'not testing') | strcmp(varargin{n},'testing')\n            testing = varargin{n};            \n        end\n    end\nend\nif isempty(edge1) | isempty(edge2)\n    error('Input entry is a null matrix');\nend\n% ---------------------------------------------------------------------------------\n% Find the closest edge and calculate the distance\n% ---------------------------------------------------------------------------------\ntemp1 = [];\ntemp2 = [];\nfor n = 1:1:length(edge1(:,1))\n    temp = edge2;\n    temp(:,1) = edge1(n,1);\n    temp(:,2) = edge1(n,2);\n\ttemp1 = [temp1;temp];\n    temp2 = [temp2;edge2];\n    % Distance calculated here to reduce memory usage\n    distance = euclidean_distance(temp1,temp2);\n    min_distance = min(distance);\n    pos = find(distance == min_distance);\n    temp1 = temp1(pos,:);\n    temp2 = temp2(pos,:);\nend\ndistance = euclidean_distance(temp1,temp2);\npos = find(distance == min_distance);\nmin_distance = min(distance);\n\nmatching_coordinates = [temp1(pos,:),temp2(pos,:)];\n\n% ---------------------------------------------------------------------------------\n% Displaying the results for testing\n% ---------------------------------------------------------------------------------\nif strcmp(testing,'testing')\n    figure;\n    plot(edge1(:,1),edge1(:,2),'r+');\n    hold on;\n    plot(edge2(:,1),edge2(:,2),'b+');\n    for n = 1:1:length(matching_coordinates(:,1))\n        plot([matching_coordinates(n,1);matching_coordinates(n,3)],...\n             [matching_coordinates(n,2);matching_coordinates(n,4)],'g*-');\n    end        \n    title('edge1(red+), edge2(blue+) and selected edges(green*)');\n    xlabel(strcat('minimum distance = ',num2str(min_distance)));\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/4294-minimum-distance-calculations-between-2-groups-of-pixels/calculate_min_distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5763384701489891}}
{"text": "clear all\nclose all\npath(path,'..\\..\\..\\FUZZCLUST')\n%the data\nload motorcycle.txt\ndata.X = motorcycle(:,[1 2]);\n\n%parameters\nparam.c=4;\nparam.m=2;\nparam.e=1e-6;\nparam.ro=ones(1,param.c);\nparam.val=1;\n%normalization\ndata=clust_normalize(data,'range');\n%clustering\nresult = FCMclust(data,param);\nplot(data.X(:,1),data.X(:,2),'b.',result.cluster.v(:,1),result.cluster.v(:,2),'ro');\nhold on\n%draw contour-map\nnew.X=data.X;\neval=clusteval(new,result,param);\n%validation\nresult = validity(result,data,param);\nresult.validity", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/7486-clustering-toolbox/Demos/clusteringexamples/motorcycle/FCMcall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.576268250334855}}
{"text": "function prob = RidgeRegressionTest(data, model)\n\nprob = model.beta' * data.feat;\n% prob = data.feat' * model.beta;", "meta": {"author": "flyers", "repo": "drone-tracking", "sha": "c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad", "save_path": "github-repos/MATLAB/flyers-drone-tracking", "path": "github-repos/MATLAB/flyers-drone-tracking/drone-tracking-c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad/trackers/HOG_LR/ObservationModel/RidgeRegressionTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5762659170422799}}
{"text": "function test_tutorial_connectivityextended\n\n% WALLTIME 00:45:00\n% MEM 3gb\n% DEPENDENCY ft_connectivityanalysis ft_connectivitysimulation ft_freqanalysis ft_connectivityplot ft_mvaranalysis\n\n% This is the first section of the connectivity tutorial, which\n% starts with an MVAR model and then uses parametric and nonparametric\n% spectral decomposition for coherence and granger\n\n% See also test_tutorial_connectivity2 and test_tutorial_connectivity3\n\n%% simulate data\ncfg             = [];\ncfg.ntrials     = 500;\ncfg.triallength = 1;\ncfg.fsample     = 200;\ncfg.nsignal     = 3;\ncfg.method      = 'ar';\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];\ndata              = ft_connectivitysimulation(cfg);\n\nfigure\nplot(data.time{1}, data.trial{1})\nlegend(data.label)\nxlabel('time (s)')\n\ncfg = [];\ncfg.viewmode = 'vertical';  % you can also specify 'butterfly'\nft_databrowser(cfg, data);\n\n%% mvaranalysis\ncfg         = [];\ncfg.order   = 5;\ncfg.toolbox = 'bsmart';\nmdata       = ft_mvaranalysis(cfg, data);\n\n%% freqanalysis 1\ncfg        = [];\ncfg.method = 'mvar';\nmfreq      = ft_freqanalysis(cfg, mdata);\n\n%% freqanalysis 2\ncfg           = [];\ncfg.method    = 'mtmfft';\ncfg.taper     = 'dpss';\ncfg.output    = 'fourier';\ncfg.tapsmofrq = 2;\nfreq          = ft_freqanalysis(cfg, data);\n\n%% connectivityanalysis\ncfg           = [];\ncfg.method    = 'coh';\ncoh           = ft_connectivityanalysis(cfg, freq);\ncohm          = ft_connectivityanalysis(cfg, mfreq);\n\n%% visualisation\ncfg           = [];\ncfg.parameter = 'cohspctrm';\nft_connectivityplot(cfg, coh, cohm);\n\n%% do the same for granger\ncfg           = [];\ncfg.method    = 'granger';\ngranger       = ft_connectivityanalysis(cfg, mfreq);\n\ncfg           = [];\ncfg.parameter = 'grangerspctrm';\nft_connectivityplot(cfg, granger);\n\nfigure\nfor row=1:3\n  for col=1:3\n    subplot(3,3,(row-1)*3+col);\n    plot(granger.freq, squeeze(granger.grangerspctrm(row,col,:)))\n    ylim([0 1])\n  end\nend\n\n%% do the virtual channel stuff\nload(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer_extended/source_coh_lft.mat'));\nload(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer_extended/source_diff.mat'));\nload(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer_extended/data_cmb.mat'));\nload(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer_extended/sourcemodel.mat'));\nload(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer_extended/hdm.mat'));\n\n[maxval, maxcohindx] = max(source_coh_lft.avg.coh);\nsource_coh_lft.pos(maxcohindx, :)\n[maxval, maxpowindx] = max(source_diff.avg.pow);\nsource_diff.pos(maxpowindx, :)\n\ncfg                   = [];\ncfg.covariance        = 'yes';\ncfg.channel           = 'MEG';\ncfg.vartrllength      = 2;\ncfg.covariancewindow  = 'all';\ntlock                 = ft_timelockanalysis(cfg, data_cmb);\n\n% this is old-style stuff. as of end 2020 there's a ft_virtualchannel\n% function that does the virtualchannel creation\ncfg              = [];\ncfg.method       = 'lcmv';\ncfg.headmodel    = hdm;\ncfg.sourcemodel.pos     = sourcemodel.pos([maxcohindx maxpowindx], :);\ncfg.sourcemodel.inside  = true(2,1);\ncfg.sourcemodel.unit    = sourcemodel.unit;\ncfg.lcmv.keepfilter = 'yes';\nsource_idx       = ft_sourceanalysis(cfg, tlock);\n\n%% old style\nbeamformer_lft_coh = source_idx.avg.filter{1};\nbeamformer_gam_pow = source_idx.avg.filter{2};\n\nchansel = ft_channelselection('MEG', data_cmb.label); % find MEG sensor names\nchansel = match_str(data_cmb.label, chansel);         % find MEG sensor indices\n\ncoh_lft_data = [];\ncoh_lft_data.label = {'coh_lft_x', 'coh_lft_y', 'coh_lft_z'};\ncoh_lft_data.time = data_cmb.time;\ngam_pow_data = [];\ngam_pow_data.label = {'gam_pow_x', 'gam_pow_y', 'gam_pow_z'};\ngam_pow_data.time = data_cmb.time;\nfor i=1:length(data_cmb.trial)\n  coh_lft_data.trial{i} = beamformer_lft_coh * data_cmb.trial{i}(chansel,:);\n  gam_pow_data.trial{i} = beamformer_gam_pow * data_cmb.trial{i}(chansel,:);\nend\n\ncfg = [];\ncfg.viewmode = 'vertical';  % you can also specify 'butterfly'\n%ft_databrowser(cfg, gam_pow_data);\n\nvisualTimeseries = cat(2, gam_pow_data.trial{:});\nmotorTimeseries = cat(2, coh_lft_data.trial{:});\n[u1, s1, v1] = svd(visualTimeseries, 'econ');\n[u2, s2, v2] = svd(motorTimeseries, 'econ');\n\nvirtualchanneldata = [];\nvirtualchanneldata.label = {'visual', 'motor'};\nvirtualchanneldata.time = data_cmb.time;\n\nfor k = 1:length(data_cmb.trial)\n  virtualchanneldata.trial{k}(1,:) = u1(:,1)' * beamformer_gam_pow * data_cmb.trial{k}(chansel,:);\n  virtualchanneldata.trial{k}(2,:) = u2(:,1)' * beamformer_lft_coh * data_cmb.trial{k}(chansel,:);\nend\nvirtualchanneldata_old = virtualchanneldata;\n\n%% new-style\ncfg = [];\ncfg.pos            = source_idx.pos;\ncfg.method         = 'svd';\ncfg.numcomponent   = 1;\nvirtualchanneldata = ft_virtualchannel(cfg, data_cmb, source_idx);\nvirtualchanneldata.label = {'motor';'visual'}; % note the order is reversed w.r.t. old-style\n\n% do a sanity check on whether the old and new style vcs match more or less\nc = corr([virtualchanneldata_old.trial{1}' virtualchanneldata.trial{1}']);\nassert(c(2,3)>0.99);\nassert(c(1,4)>0.99);\n\n% select the two EMG channels\ncfg = [];\ncfg.channel = 'EMG';\nemgdata = ft_selectdata(cfg, data_cmb);\n\n% combine the virtual channel with the two EMG channels\ncfg = [];\ncombineddata = ft_appenddata(cfg, virtualchanneldata, emgdata);\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    = {'visual' 'motor' 'EMGlft' 'EMGrgt'};\nfreq    = ft_freqanalysis(cfg, combineddata);\n\ncfg = [];\ncfg.method = 'coh';\ncoherence = ft_connectivityanalysis(cfg, freq);\n\ncfg = [];\ncfg.zlim = [0 0.25];\nfigure\nft_connectivityplot(cfg, coherence);\n\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_connectivityextended.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5762659018438036}}
{"text": "function z = geoatan2(x, y)\n%-------------------------------------------------------\n% z = geoatan2(x, y);\n% Yudan Yi, May 26, 2005\n%-------------------------------------------------------\n% return -pi~pi of y/x\nz = 0.0;\nif (abs(x)<1e-12)  if (y>0) z = pi/2.0; else z =-pi/2.0; end; return; end;\nz = atan(abs(y/x));\nif (x>0)  \n\tif (y<0) z =-z; end; return;\nelse \n\tif (y>0) z = pi-z; else z =-pi+z; end; \nend\nreturn;\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/geodetic/geoatan2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5762658970879008}}
{"text": "function [tt]=tt_qlaplace_dn(d)\n\n% returns a rank-4,5...5 QTT decomposition of\n% Delta_{1} \\otimes \\Id_{2} \\ otimes \\ldots \\otimes \\Id_{D} + \\ldots +\n%  + \\Id_{1} \\ otimes \\ldots \\otimes \\Id_{D-1} \\otimes Delta_{D},\n% Delta_{k} being a discretization of Laplace operator on 2^d(k) points\n% uniform grid,\n% Dirichlet-Neumann boundary conditions being imposed\n%\n% D=size(d,2) must be >= 1\n%\n% September 3, 2010\n% Vladimir Kazeev\n% vladimir.kazeev@gmail.com\n% INM RAS\n% Moscow, Russia\n%\n% Look for details in the Preprint No. 75, 2010 of\n% Max-Planck Institute for Mathematics in the Sciences\n% Vladimir A. Kazeev and Boris N. Khoromskij\n% On explicit QTT representation of Laplace operator and its inverse\n% http://www.mis.mpg.de/publications/preprints/2010/prepr2010-75.html\n\nd=fliplr(d);\nD=size(d,2);\ntt=cell(sum(d),1);\nI=eye(2);\nJ=zeros(2);\nJ(1,2)=1;\nI2=zeros(2);\nI2(2,2)=1;\n\nif (D == 1)\n\tfor key=1 : d\n\t\tif (key == 1)\n\t\t\ttt{key}=zeros(2,2,4);\n\t\t\ttt{key}(:,:,1)=2*I-J-J';\n\t\t\ttt{key}(:,:,2)=-J;\n\t\t\ttt{key}(:,:,3)=-J';\n\t\t\ttt{key}(:,:,4)=-I2;\n\t\telseif (key == d)\n\t\t\ttt{key}=zeros(2,2,4);\n\t\t\ttt{key}(:,:,1)=I;\n\t\t\ttt{key}(:,:,2)=J';\n\t\t\ttt{key}(:,:,3)=J;\n\t\t\ttt{key}(:,:,4)=I2;\n\t\telse\n\t\t\ttt{key}=zeros(2,2,4,4);\n\t\t\ttt{key}(:,:,1,1)=I;\n\t\t\ttt{key}(:,:,2,2)=J;\n\t\t\ttt{key}(:,:,3,3)=J';\n\t\t\ttt{key}(:,:,4,4)=I2;\n\t\t\ttt{key}(:,:,2,1)=J';\n\t\t\ttt{key}(:,:,3,1)=J;\n\t\tend\n\tend\nelse\n\n\tkey=0;\n\tfor k=1 : D\n\t\tfor kappa=1 : d(k)\n\t\t\tkey=key+1;\n\t\t\tif (kappa == 1)\n\t\t\t\tif (k == 1)\n\t\t\t\t\ttt{key}=zeros(2,2,5);\n\t\t\t\t\ttt{key}(:,:,1)=2*I-J-J';\n\t\t\t\t\ttt{key}(:,:,2)=-J;\n\t\t\t\t\ttt{key}(:,:,3)=-J';\n\t\t\t\t\ttt{key}(:,:,4)=-I2;\n\t\t\t\t\ttt{key}(:,:,5)=I;\n\t\t\t\telseif (k == D)\n\t\t\t\t\ttt{key}=zeros(2,2,2,4);\n\t\t\t\t\ttt{key}(:,:,1,1)=2*I-J-J';\n\t\t\t\t\ttt{key}(:,:,1,2)=-J;\n\t\t\t\t\ttt{key}(:,:,1,3)=-J';\n\t\t\t\t\ttt{key}(:,:,1,4)=-I2;\n\t\t\t\t\ttt{key}(:,:,2,1)=I;\n\t\t\t\telse\n\t\t\t\t\ttt{key}=zeros(2,2,2,5);\n\t\t\t\t\ttt{key}(:,:,1,1)=2*I-J-J';\n\t\t\t\t\ttt{key}(:,:,1,2)=-J;\n\t\t\t\t\ttt{key}(:,:,1,3)=-J';\n\t\t\t\t\ttt{key}(:,:,1,4)=-I2;\n\t\t\t\t\ttt{key}(:,:,1,5)=I;\n\t\t\t\t\ttt{key}(:,:,2,1)=I;\n\t\t\t\tend\n\t\t\telseif (kappa == d(k))\n\t\t\t\tif (k == D)\n\t\t\t\t\ttt{key}=zeros(2,2,4);\n\t\t\t\t\ttt{key}(:,:,1)=I;\n\t\t\t\t\ttt{key}(:,:,2)=J';\n\t\t\t\t\ttt{key}(:,:,3)=J;\n\t\t\t\t\ttt{key}(:,:,4)=I2;\n\t\t\t\telse\n\t\t\t\t\ttt{key}=zeros(2,2,5,2);\n\t\t\t\t\ttt{key}(:,:,5,1)=I;\n\t\t\t\t\ttt{key}(:,:,1,2)=I;\n\t\t\t\t\ttt{key}(:,:,2,2)=J';\n\t\t\t\t\ttt{key}(:,:,3,2)=J;\n\t\t\t\t\ttt{key}(:,:,4,2)=I2;\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tif (k == D)\n\t\t\t\t\ttt{key}=zeros(2,2,4,4);\n\t\t\t\t\ttt{key}(:,:,1,1)=I;\n\t\t\t\t\ttt{key}(:,:,2,2)=J;\n\t\t\t\t\ttt{key}(:,:,3,3)=J';\n\t\t\t\t\ttt{key}(:,:,4,4)=I2;\n\t\t\t\t\ttt{key}(:,:,2,1)=J';\n\t\t\t\t\ttt{key}(:,:,3,1)=J;\n\t\t\t\telse\n\t\t\t\t\ttt{key}=zeros(2,2,5,5);\n\t\t\t\t\ttt{key}(:,:,1,1)=I;\n\t\t\t\t\ttt{key}(:,:,2,2)=J;\n\t\t\t\t\ttt{key}(:,:,3,3)=J';\n\t\t\t\t\ttt{key}(:,:,4,4)=I2;\n\t\t\t\t\ttt{key}(:,:,2,1)=J';\n\t\t\t\t\ttt{key}(:,:,3,1)=J;\n\t\t\t\t\ttt{key}(:,:,5,5)=I;\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\nend\ntt=tt_matrix(tt); % @Bydlocode\nreturn\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/exp/tt_qlaplace_dn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5762658809586556}}
{"text": "function p = exactness_1d ( family, growth, level )\n\n%*****************************************************************************80\n%\n%% EXACTNESS_1D returns the exactness of a 1D quadrature rule.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    06 March 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, string FAMILY, indicates the family of 1D quadrature rules used\n%    to provide factors.\n%    'CC': Clenshaw-Curtis;\n%    'L':  Gauss-Legendre\n%\n%    Input, string GROWTH, indicates the growth rate.\n%    'E': exponential, for CC, L;\n%    'HC': Hyperbolic Cross;\n%    'L': linear growth, for CC, HC, L;\n%    'LO', linear odd growth, for CC, L;\n%    'SE': slow exponential, for CC, L.\n%\n%    Input, int LEVEL, the level of the sparse grid to be constructed.\n%    0 <= LEVEL <= 5.\n%\n%    Output, integer P, the exactness of the rule.\n%\n  if ( upper ( family ) == 'CC' )\n  \n    o = order_1d ( family, growth, level );\n    p = o;\n\n  elseif ( upper ( family ) == 'L' )\n  \n    o = order_1d ( family, growth, level );\n    p = 2 * o - 1;\n\n  else\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'EXACTNESS_1D - Fatal error!\\n' );\n    fprintf ( 1, '  Unknown family.\\n' );\n    error ( 'EXACTNESS_1D - 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/smolyak_display/exactness_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.576262454792844}}
{"text": "\n\nclear all; close all;\nI=imread('cameraman.tif');\nJ=imnoise(I, 'poisson');\nfigure;\nsubplot(121);  imshow(I);\nsubplot(122);  imshow(J);\n\n", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/\u300aMATLAB\u56fe\u50cf\u5904\u7406\u300b\u6e90\u6587\u4ef6/\u672c\u4e66\u6e90\u6587\u4ef6/chap6/chap6_6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5762624425065909}}
{"text": "function b = is3DImage(img)\n%IS3DIMAGE  Check if an image is 3D\n%\n%   B = isColorImage(IMG);\n%   Returns TRUE if the image IMG is 3D. An image is assumed to be 3D if\n%   all conditions are satisfied:\n%   - number of dimensions is >= 3\n%   - size of third dimension is not equal to 3, or all sizes equal 3\n%\n%   Example\n%   % planar image\n%   is3DImage(imread('cameraman.tif'))\n%   ans = \n%       0\n%\n%   % Three-D image\n%   is3DImage(ones(5, 5, 5))\n%   ans =\n%       1\n%\n%   % planar color image\n%   is3DImage(ones(5, 5, 3))\n%   ans =\n%       0\n%\n%   Three-D color image\n%   is3DImage(ones(5, 5, 3, 4));\n%   ans =\n%       1\n%\n%   See also\n%     isColorImage\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-05-20,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% check number of dimension\ndim = size(img);\nif length(dim) < 3\n    b = false;\n    return\nend\n\n% check all dimensions equal to 3\nif sum(dim([1:2 4:end])~=3) == 0\n    b = true;\n    return\nend\n\n% check third dimension\nif dim(3) == 3\n    dim(3) = [];\nend\n\n% 3D if 3 dimensions...\nb = length(dim) == 3;\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/is3DImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5761081678274481}}
{"text": "function varargout = gpr(hyper, cov, x, y, xs)\n\n% gpr - Gaussian process regression, with a named covariance function. Two\n% modes are possible: training and prediction: if no test data are given, the\n% function returns minus the log likelihood and its partial derivatives with\n% respect to the hyperparameters; this mode is used to fit the hyperparameters.\n% If test data are given, then (marginal) Gaussian predictions are computed,\n% whose mean and variance are returned. Note that in cases where the covariance\n% function has noise contributions, the variance returned in s2 is for noisy\n% test targets; if you want the variance of the noise-free latent function, you\n% must substract the noise variance.\n%\n% usage: [nlZ dnlZ] = gpr(hyp, cov, x, y)\n%    or: [mu s2]    = gpr(hyp, cov, x, y, xs)\n%\n% where:\n%\n%   hyp      is a (column) vector of log hyperparameters\n%   cov      is the covariance function\n%   x        is a n by D matrix of training inputs\n%   y        is a (column) vector (of size n) of targets\n%   xs       is a ns by D matrix of test inputs\n%   nlZ      is the returned value of the negative log marginal likelihood\n%   dnlZ     is a (column) vector of partial derivatives of the negative\n%                 log marginal likelihood wrt each log hyperparameter\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% For more help on covariance functions, see \"help covFunctions\".\n%\n% Copyright (c) 2010 Carl Edward Rasmussen and Hannes Nickisch 2010-06-18.\n\nerr = 'we need cov = {''covSum'', {cov1, ..,''covNoise'', .., covP} }; to map to gp.m';\nif ~strcmp(cov{1},'covSum'), error(err), end\nid = 0; nhyp = zeros(length(cov{2}),1);\nfor i=1:length(cov{2})\n  if strcmp(cov{2}{i},'covNoise'), id = i; break, end\n  nhyp(i) = eval(feval(cov{2}{i}));\nend\nif id==0, error(err), else nhyp = sum(nhyp(1:id-1)); end\ncov{2} = cov{2}([1:id-1,id+1:end]);\nhyp.lik = hyper(nhyp+1); hyp.cov = hyper([1:nhyp,nhyp+2:end]);\n\n% Note, this function is just a wrapper provided for backward compatibility,\n% the functionality is now provided by the more general gp function.\nlik = @likGauss; inf = @infExact; mean = @meanZero;\n\nvarargout = cell(nargout, 1);    % allocate the right number of output arguments\nif nargin==4\n  [varargout{:}] = gp(hyp,inf,mean,cov,lik,x,y);\n  if nargout>1, varargout{2} = [varargout{2}.lik; varargout{2}.cov]; end\nelse\n  [varargout{:}] = gp(hyp,inf,mean,cov,lik,x,y,xs);\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/gpml/util/gpr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5761081671409133}}
{"text": "function [x] = denormdata(xn,xmean,xstd)\n%DENORMDATA  De-normalize normalized data\n%\n%  Description\n%    X = DENORMDATA(XN,XMEAN,XSTD) de-normalize XN using\n%    precomputed XMEAN and XSTD.\n%\n%  See also NORMDATA\n%\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  if nargin<3\n    error('Too few arguments')\n  end\n  x=bsxfun(@plus,bsxfun(@times,xn,xstd),xmean);\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/denormdata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.5761081635194358}}
{"text": "function [stepsize, newx, newkey, ssstats] = ...\n                    stepsize_sg(problem, x, d, iter, options, storedb, key) %#ok<INUSD>\n% Standard step size selection algorithm for the stochastic gradient method\n%\n% Given a problem structure, a point x on the manifold problem.d and a\n% tangent vector d at x, produces a stepsize (a positive real number) and a\n% new point newx obtained by retraction -stepsize*d at x. Additional inputs\n% include iter (the iteration number of x, where 0 marks the initial\n% guess), an options structure, a storedb database and the key of point x\n% in that database. Additional outputs include the key of newx in the\n% database, newkey, as well as a structure ssstats collecting statistics\n% about the work done during the call to this function.\n%\n% See in code for the role of available options:\n%    options.stepsize_type\n%    options.stepsize_init\n%    options.stepsize_lambda\n%    options.stepsize_decaysteps\n%\n% This function may create and maintain a structure called sssgmem inside\n% storedb.internal. This gives the function the opportunity to remember\n% what happened in previous calls.\n%\n% See also: stochasticgradient\n\n% This file is part of Manopt: www.manopt.org.\n% Original authors: Bamdev Mishra and Nicolas Boumal, March 30, 2017.\n% Contributors: Hiroyuki Kasai and Hiroyuki Sato.\n% Change log: \n\n\n    % Allow omission of the key, and even of storedb.\n    if ~exist('key', 'var')\n        if ~exist('storedb', 'var')\n            storedb = StoreDB();\n        end\n        key = storedb.getNewKey(); %#ok<NASGU>\n    end\n    \n\n    % Initial stepsize guess.\n    default_options.stepsize_init = 0.1;\n    % Stepsize evolution type. Options are 'decay', 'fix' and 'hybrid'.\n    default_options.stepsize_type = 'decay';\n    % If stepsize_type = 'decay' or 'hybrid', lambda is a weighting factor.\n    default_options.stepsize_lambda = 0.1;\n    % If stepsize_type = 'hybrid', decaysteps states for how many\n    % iterations the step size decays before becoming constant.\n    default_options.stepsize_decaysteps = 100;\n    \n    if ~exist('options', 'var') || isempty(options)\n        options = struct();\n    end\n    options = mergeOptions(default_options, options);\n    \n\n    type = options.stepsize_type;\n    init = options.stepsize_init;\n    lambda = options.stepsize_lambda;\n    decaysteps = options.stepsize_decaysteps;\n\n    \n    switch lower(type)\n        \n        % Step size decays as O(1/iter).\n        case 'decay'\n            stepsize = init / (1 + init*lambda*iter);\n\n        % Step size is fixed.\n        case {'fix', 'fixed'}\n            stepsize = init;\n\n        % Step size decays only for the few initial iterations.\n        case 'hybrid'\n            if iter < decaysteps\n                stepsize = init / (1 + init*lambda*iter);\n            else\n                stepsize = init / (1 + init*lambda*decaysteps);\n            end\n\n        otherwise\n            error(['Unknown options.stepsize_type. ' ...\n                   'Should be ''fix'', ''decay'' or ''hybrid''.']);\n               \n    end\n\n    % Store some information.\n    ssstats = struct();\n    ssstats.stepsize = stepsize;\n\n    % Compute the new point and give it a key.\n    newx = problem.M.retr(x, d, -stepsize);\n    newkey = storedb.getNewKey();\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/solvers/stochasticgradient/stepsize_sg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5761081592114236}}
{"text": "function showsolution3(node,elem,u,expr,varargin)\n%% SHOWSOLUTION3 plots the solution u on a tetrahedron mesh in 3-D.\n%\n%    showsolution3(node,elem,u) displays the functoin u on a topological\n%    2-dimensional mesh given by node and elem matrices. The function u\n%    could be piecewise constant or piecewise linear. \n%\n%    showsolution3(node,elem,u,expr) displays the function u on the\n%    boundary of parts of the mesh specificed by the expression. For\n%    example, showsoluiton3(node,elem,'z==0') will show the function on the\n%    cross section of z=0. \n%\n%    showsolution3(node,elem,u,viewangle) changes the display angle. The\n%    deault view angle on planar meshes is view(2) and view(3) for surface\n%    meshes. \n%\n%    showsolution3(node,elem,u,expr,'param','value','param','value'...) allows\n%    additional patch param/value pairs to be used when displaying the\n%    mesh. \n%\n%   Example:\n%     f = inline('x.^2 + y.^2 + z.^2');\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%     for k=1:4\n%       [node,elem] = uniformbisect3(node,elem);\n%     end\n%     u = f(node(:,1),node(:,2),node(:,3));\n%     subplot(1,2,1);\n%     showsolution3(node,elem,u);\n%     subplot(1,2,2);\n%     showsolution3(node,elem,u,'~(x>0 & y>0)',[139,16],'EdgeColor','k');\n%\n%   See also showmesh, showsolution3.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif (nargin >= 4) && (any(expr))\n    x = node(:,1);  y = node(:,2);  z = node(:,3); %#ok<*NASGU>\n    incl = find(eval(expr));\n    elem = elem(any(ismember(elem,incl),2),:);\nend\n[bdNode, bdFace] = findboundary3(elem); %#ok<ASGLU>\nif isempty(varargin)\n    showsolution(node,bdFace,u,'EdgeColor','k');\nelseif (nargin == 5) && isnumeric(varargin{1})\n    showsolution(node,bdFace,u,'EdgeColor','k');\n    view(varargin{1});\nelse\n    showsolution(node,bdFace,u,varargin{1:end});\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/tool/showsolution3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.576085878100399}}
{"text": "function [B,twom] = modularitydir_f(A,gamma)\n% MODULARITYDIR_F returns monolayer Leicht-Newman modularity matrix for directed network given by adjacency matrix A, function handle version\n%\n% Version: 2.2.0\n% Date: Thu 11 Jul 2019 12:25:42 CEST\n%\n%\n%   Input: A:  NxN adjacency matrices of a directed network\n%          gamma: resolution parameter\n%\n%   Output: B: function handle where B(i) returns the ith column of\n%          [N]x[N] modularity matrix of the monolayer network\n%           with adjacency matrix A\n%           twom: normalisation constant\n%\n%   Example of usage: [B,twom]=modularitydir_f(A,gamma);\n%          [S,Q]= genlouvain(B);\n%          Q=Q/twom;\n%   Notes:\n%     The matrix A is assumed to be square. This assumption is not checked\n%     here.\n%\n%     For smaller systems, it is potentially more efficient (and easier) to\n%     directly use the sparse quality/modularity matrix B in MODULARITY. For\n%     large systems with undirected networks, use MODULARITY_F.\n%\n%     This code serves as a template and can be modified for situations\n%     with other wrinkles (e.g., different null models).\n%\n%     By using this code, the user implicitly acknowledges that the authors\n%     accept no liability associated with that use.  (What are you doing\n%     with it anyway that might cause there to be a potential liability?!?)\n%\n%   References\n%     Elizabeth A. Leicht and Mark E. J. Newman. \"Community structure in\n%     Directed Networks\", Physical Review Letters 100, 118703 (2008).\n\n\nif nargin<2||isempty(gamma)\n\tgamma=1;\nend\n\nk=sum(A,2);\nd=sum(A,1);\ntwom=sum(k);\nA=(A+A')/2;\n\nB=@(i) full(A(:,i)-gamma/2*(k*d(i)+d'*k(i))/twom);\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/modularitydir_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5760238672260409}}
{"text": "%% Check rate of convergence for 3D H1 interface problem\n%     -div(A grad u)  = f,    x\\in \\Omega\n%      where A is a piecewise constant on Omega^+ and Omega^-.\n%\n% Domain: Rectangular domain: [xmin,xmax] X [ymin,ymax] X [zmin,zmax]\n% Mesh: Cartesian triangular mesh.\n% Method: PP-IFE\n\n\n%% Geometry and Boundary Conditions\n% clear\n% close all\n%clc\n\ndomain = [-1,1,-1,1,-1,1];\nbc = [1,1,1,1,1,1]; % Dirichelet BC\n\n%% Finite Element Type\nfemtype = 'P1';\ndisp(['FEM Type =  Conforming ', femtype]);\n\n%% Initial Partition\nnx0 = 10;\nny0 = nx0;\nnz0 = nx0;\n\n%% Task\nshowErr = 0;\nshowMesh = 0;\ncomputErr = 1;\n\n%% PDE\ntest = 6;\nswitch test\n    case 0\n        pde = poissonNonPoly3D;\n    case 1 % circular interface\n        r = pi/4; bm = 1; bp = pi/(2*r^2);\n        %r = sqrt(pi/2); bm = 1; bp = pi/(2*r^2);domain = [-2,2,-2,2,-2,2];\n        x0 = 0; y0 = 0; z0 = 0; rx = r; ry = r; rz = r;\n        pde = elli3DcircIntf(bm,bp,r,x0,y0,z0,rx,ry,rz);\n    case 2 % orthotorus interface\n        domain = [-1.2,1.2,-1.2,1.2,-1.2,1.2];\n        bm = 1; bp = 1;\n        rx = 1; ry = 0.075; rz = 3;\n        pde = elli3DorthocircIntf(bm,bp,rx,ry,rz);\n    case 3 % line interface\n        bm = 1; bp = 1;\n        rx = 1; ry = 10^(-4); rz = -1; cx = 10^(-4); cy = 0; cz = 0;\n        cm = 1; cp = 1; a = 1;\n        pde = elli3DlinIntf(bm,bp,cx,cy,cz,rx,ry,rz,a,cm,cp);\n    case 4 % line interface but with zero boundary conditions\n        bm = 1; bp = 10; delta = pi/100; % delta can not be -1,1\n        pde = elli3DlinIntf2(bm,bp,delta);\n    case 5 % circular interface\n        r = pi/4; bm = 1; bp = 10;domain = [-1,1,-1,1,-1,1];\n        x0 = 0; y0 = 0; z0 = 0;\n        pde = elli3DcircIntf5(bm,bp,r,x0,y0,z0);\n    case 6 % circular interface\n        bm = 1; bp = 1;domain = [-1.3,1.3,-1.3,1.3,-1.3,1.3];\n        x1 = -0.3; y1 = 0; z1 = 0; r11 = pi/5; r12 = 0.2;\n        x2 =  0.3; y2 = 0; z2 = 0; r21 = pi/5; r22 = 0.2;\n        pde = elli3DtorusTwin(bm,bp,x1,y1,z1,r11,r12,x2,y2,z2,r21,r22);\nend\n%% PPIFEM Type\nPPtype = 'S';\ndisp(['PPIFEM Type = ', PPtype]);\nsig = max(bm,bp)/min(bm,bp);\n\n%% Max Iteration\nmaxIt = 10;\ntime = zeros(9,maxIt);\n\nfor i = 1:maxIt\n    \n    %% 1. Generate Mesh\n    tic\n    nx = nx0 + 10*(i-1); h = (domain(2) - domain(1))/nx;\n    ny = ny0 + 10*(i-1);\n    nz = nz0 + 10*(i-1);\n    time(1,i) = nx;\n    disp(' ')\n    disp('**************************************************************************************')\n    disp(['Partition =  ',int2str(nx),' X ',int2str(ny),' X ',int2str(nz)]);\n    disp(' ')\n    \n    mesh = genMesh3D(domain, nx, ny, nz);\n    mesh = enrichMesh3D(mesh,2); % Mesh detail level = 2 (for PPIFE).\n    disp(['number of element =  ', int2str(length(mesh.t))]);\n    mesh = genIntfMesh3D(mesh,pde.intf);\n    disp(['number of interface element =  ', int2str(-min(mesh.tLoc)),...\n        ', is ', num2str(100*-min(mesh.tLoc)/length(mesh.t)), '% of all elements']);\n    if showMesh == 1\n        tetramesh(mesh.t,mesh.p,ones(size(mesh.t)));\n    end\n    time(2,i) = toc;\n    \n    %% 2. Generate FEM DoF\n    tic\n    fem = genFEM3D(mesh,femtype,bc);\n    disp(['number of DoF =  ', int2str(length(fem.p))]);\n    time(3,i) = toc;\n    tic\n    femI = genP1IFEM3D(mesh,fem,bm,bp);\n    time(4,i) = toc;\n    tic\n    femIF = genP1IFEM3DFace(mesh,fem,femI);\n    time(5,i) = toc;\n    \n    %% 3. Assemble Matrix\n    tic\n    disp(' '); disp('Start Assembling Matrix');\n    matrix = genMatEllPPIFE3D(pde,mesh,fem,femI,femIF,PPtype,sig);\n    time(6,i) = toc;\n    \n    %% 4. Solve the linear system Au = f\n    tic\n    disp(' ')\n    if strcmp(PPtype,'S')\n        disp('Start Solving Linear System: using PCG with ichol precond');\n        L = ichol(matrix.A);\n        u = pcg(matrix.A,matrix.f,1e-8,300,L,L');\n    elseif strcmp(PPtype,'N') || strcmp(PPtype,'I')\n        disp('Start Solving Linear System: using GMRES with ilu precond');\n        [L,U] = ilu(matrix.A,struct('milu','row'));\n        u = gmres(matrix.A,matrix.f,[],1e-8,300,L,U);\n    end\n    time(7,i) = toc;\n    tu = pde.exactu(fem.p(:,1),fem.p(:,2),fem.p(:,3));\n    uh = tu; uh(fem.mapper) = u;\n    \n    %% 5. Postprocess: Calculating Errors\n    tic\n    errND = max(abs(uh - tu)); % Error on nodes\n    err.nd = errND; err.inf = 0; err.l2 = 0; err.h1 = 0;\n    if computErr == 1\n        disp(' ');  disp('Start computing error in Inf norm');\n        [errInfN,errInfI] = getErrInfIFE3D(uh,pde.exactu,mesh,femI,fem,[0,0,0]);        \n        eNorm = 'L2'; disp(['Start computing error in ',eNorm,'  norm']);\n        [errL2,errL2K] = getErrIFE3D(uh, pde, mesh, fem, femI,eNorm);\n        eNorm = 'H1x'; disp(['Start computing error in ',eNorm,' norm']);\n        [errH1x,errH1xK] = getErrIFE3D(uh, pde, mesh, fem, femI, eNorm);\n        eNorm = 'H1y'; disp(['Start computing error in ',eNorm,' norm']);\n        [errH1y,errH1yK] = getErrIFE3D(uh, pde, mesh, fem, femI, eNorm);\n        eNorm = 'H1z'; disp(['Start computing error in ',eNorm,' norm']);\n        [errH1z,errH1zK] = getErrIFE3D(uh, pde, mesh, fem, femI, eNorm);\n        \n        disp(' ')\n        disp(['Max error on Regular Elements   = ', num2str(errInfN)])\n        disp(['Max error on Interface Elements = ', num2str(errInfI)])\n        err.inf = max([errND,errInfN,errInfI]);\n        err.l2 = errL2;\n        err.h1 = sqrt(errH1x^2+errH1y^2+errH1z^2);\n    end\n    time(8,i) = toc;\n    time(9,i) = 1e6*sum(time(2:8,i))/length(mesh.t);\n    \n    %% 6: Display Output\n    disp(' ')\n    disp('Errors')\n    disp('Node        Inf norm    L2 norm     H1 norm')\n    formatSpec = '%6.4e  %6.4e  %6.4e  %6.4e\\n';\n    fprintf(formatSpec, err.nd, err.inf, err.l2, err.h1)\n    \n    if i > 1\n        format short\n        rNd = log(err0.nd/err.nd)./log(h0/h);\n        rInf = log(err0.inf/err.inf)./log(h0/h);\n        rL2 = log(err0.l2/err.l2)./log(h0/h);\n        rH1 = log(err0.h1/err.h1)./log(h0/h);\n        disp(' ')\n        disp('Convergence Rate')\n        disp('Node        Inf norm    L2 norm     H1 norm')\n        formatSpec = '%6.4f      %6.4f      %6.4f      %6.4f\\n';\n        fprintf(formatSpec, rNd, rInf, rL2, rH1)\n    end\n    err0 = err; h0 = h;\n    \n    disp(' '); disp('CPU Time')\n    disp('   N     Mesh     FEM      FEMI    FEMIF    Matrix   Solve    Error    Time/1M cell')\n    formatSpec = '%4i  %7.2f  %7.2f  %7.2f  %7.2f  %7.2f  %7.2f  %7.2f   %7.2f\\n';\n    fprintf(formatSpec, time(:,1:i))\n    \n    %% 6. Plot Solution and Error\n    if showErr == 1\n    end\n   \nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/checkPPIFEMrate3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5760206397319177}}
{"text": "function view = linearizeCmap(view)\n%\n% AUTHOR: Baseler/Poirson/Huk\n% DATE:   3.4.99\n% PURPOSE: Correct for the non linear input-output relationship\n%\t   between colormap entries and colors produced on the\n%          the monitor.  This works best for 'hsv' colormaps.\n% USAGE:   \n% HISTORY:  2.28.97 hab, poirson    Wrote mrLinearCmap\n%           3.4.99 huk              Updated to mrLoadRet-2.0\n% INPUT:   view (i.e. FLAT, INPLANE, or VOLUME)\n% OUTPUT:  view with corrected colormap\n%\n% 2006/10 SD: updated so it works for every displayMode and colormap.\n\ngammaLeft = 2;\ngammaRight = 1.3;\n \n\ncmap = eval(['view.ui.' view.ui.displayMode 'Mode.cmap']);\nnGrays = eval(['view.ui.' view.ui.displayMode 'Mode.numGrays']);\nnColors = eval(['view.ui.' view.ui.displayMode 'Mode.numColors']);\n\n% different correction for different parts\niiLower = [nGrays+1:nGrays+round(nColors/2)];\niiUpper = [round(nGrays+nColors/2)+1:nGrays+nColors];\n\ncmap(iiLower,:) = cmap(iiLower,:).^(1/gammaLeft);\ncmap(iiUpper,:) = cmap(iiUpper,:).^(1/gammaRight);\n\ncolormap(cmap);\n\neval(['view.ui.' view.ui.displayMode 'Mode.cmap=cmap;']);\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/Colormap/linearizeCmap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.5760206315133753}}
{"text": "function ci = cilssvm(model,alpha,conftype)\n%\n% Construction of bias corrected 100(1-\\alpha)% pointwise or\n% simultaneous confidence intervals\n%\n% >> ci = cilssvm({X,Y,type,gam,kernel_par,kernel,preprocess},alpha,conftype)\n% >> ci = cilssvm(model,alpha,conftype)\n%\n% This function calculates bias corrected 100(1-\\alpha)% pointwise or \n% simultaneous confidence intervals. The procedure support homoscedastic \n% data sets as well heteroscedastic data sets. The construction of the  \n% confidence 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% >> ci = cilssvm({X,Y,type,gam,kernel_par,kernel,preprocess})\n% >> ci = cilssvm({X,Y,type,gam,kernel_par,kernel,preprocess}, alpha)\n% >> ci = cilssvm({X,Y,type,gam,kernel_par,kernel,preprocess}, alpha, conftype)\n%\n%\n%      Outputs\n%        ci            : N x 2 matrix containing the lower and upper confidence 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 confidence interval 'pointwise' or 'simultaneous' (by default 'simultaneous')\n%\n% 2. Using the object oriented interface:\n%\n%\n% >> ci = cilssvm(model)\n% >> ci = cilssvm(model, alpha)\n% >> ci = cilssvm(model, alpha, conftype)\n%\n%\n%      Outputs\n%        ci          : 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 confidence interval 'pointwise' or 'simultaneous' (by default 'simultaneous')\n%\n%\n%  See also:\n%    trainlssvm, simlssvm, predlssvm\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    alpha = 0.05;\n    conftype = 'simul';\n    \nelseif nargin <= 2\n    conftype = 'simul';\nend\n\nif model.preprocess(1)=='p'\n    error('Please use original data to compute confidence intervals...')\nend\n\nx = model.xtrain; y = model.ytrain;\n\n% train model\nif isempty(model.gam) && isempty(model.kernel.pars)\n    error('Please tune model first with ''tunelssvm'' to obtain tuning parameters');\nend\nmodel = trainlssvm(model);\n\ns = smootherlssvm(model);\nYhat = simlssvm(model,x);\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\nbiascorr = (s-eye(size(x,1)))*simlssvm(modelb,x);\n\n% construct approximate 100(1-alpha)% confidence interval\n%1) estimate variance nonparametrically\nsigma2 = varest(model);\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    z = tbform(model,alpha) + delta;\nelseif conftype(1)=='p'\n    z = norminv(alpha/2);\n    Yhat = Yhat - biascorr;\nelse\n    error('Wrong type of confidence interval. Please choose ''pointwise'' or ''simultaneous''');\nend\n    \nci = [Yhat+z*sqrt(diag(s)) Yhat-z*sqrt(diag(s))];\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/cilssvm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5760206315133753}}
{"text": "function [ce_flux_p, ce_flux_ps, ce_flux_s, ce_flux_sn, ce_flux_n] = interpolateElectrolyteConcetrationFluxes(ce,param)\n%\tinterpolateElectrolyteConcetrationFluxes interpolates the electrolyte concentration flux 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% Fluxes within the positive electrode\nce_flux_p = (ce(2:param.Np)-ce(1:param.Np-1))/(param.deltax_p*param.len_p);\n\n% Fluxes at the separator-positive interface\nce_flux_ps = (ce(param.Np+1)-ce(param.Np)) / ((param.deltax_p*param.len_p/2+param.deltax_s*param.len_s/2));\n\n% Fluxes within the separator\nce_flux_s = (ce(param.Np+2:param.Np+param.Ns)-ce(param.Np+1:param.Np+param.Ns-1))/(param.deltax_s*param.len_s);\n\n% Fluxes at the separator-negative interface\nce_flux_sn = (ce(param.Np+param.Ns+1)-ce(param.Np+param.Ns)) / ((param.deltax_n*param.len_n/2+param.deltax_s*param.len_s/2));\n\n% Fluxes within the negative electrode\nce_flux_n = (ce(param.Np+param.Ns+2:end)-ce(param.Np+param.Ns+1:end-1))/(param.deltax_n*param.len_n);\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/interpolateElectrolyteConcetrationFluxes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503682, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5760206208836685}}
{"text": "function sofa_pw = extrapolate_farfield_hrtfset(sofa,conf)\n%EXTRAPOLATE_FARFIELD_HRTFSET far-field extrapolation of a given HRTF dataset\n%\n%   Usage: sofa = extrapolate_farfield_hrtfset(sofa,conf)\n%\n%   Input parameters:\n%       sofa    - IR data set for the virtual secondary sources\n%       conf    - configuration struct (see SFS_config)\n%\n%   Output parameters:\n%       sofa    - IR data set extra polated to conation plane wave IRs\n%\n%   EXTRAPOLATE_FARFIELD_HRTFSET(SOFA,conf) generates a far-field extrapolated\n%   set of impulse responses, using the given irs set. Far-field means that the\n%   resulting impulse responses are plane waves. The extrapolation is done via\n%   WFS.\n%\n%   See also: get_ir, driving_function_imp_wfs\n%\n%   References:\n%       Spors and Ahrens (2011) - \"Generation of far-field head-related\n%       transfer functions using sound field synthesis\", 37th German Annual\n%       Conference on Acoustics (DAGA), pp. 673-674,\n%       http://pub.dega-akustik.de/DAGA_2011/data/articles/000370.pdf\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 = 2;\nnargmax = 2;\nnarginchk(nargmin,nargmax);\nisargstruct(sofa,conf);\n\n\n%% ===== Configuration ===================================================\nfs = conf.fs;\ndimension = conf.dimension;\nshowprogress = conf.showprogress;\nconf.ir.usehcomp = false;\n\n\n%% ===== Variables ======================================================\n[nls,~,N] = size(sofa.Data.IR);\nAPV = SOFAcalculateAPV(sofa);\nphi = rad(APV(:,1));\ntheta = rad(APV(:,2));\nR = APV(:,3);\nconf.secondary_sources.number = nls;\n[conf.secondary_sources.x0(:,1), ...\n conf.secondary_sources.x0(:,2), ...\n conf.secondary_sources.x0(:,3)] = sph2cart(phi,theta,R);\nconf.secondary_sources.x0(:,4:6) = ...\n    direction_vector(conf.secondary_sources.x0,repmat(conf.xref,nls,1));\n% Weights\nif strcmp('3D',dimension)\n    % Use rectangular grid to get a first approximation of the grid weights\n    % R^2 * cos(theta) is the integrational weight for integration on a sphere\n    conf.secondary_sources.x0(:,7) = ...\n        weights_for_points_on_a_sphere_rectangle(phi,theta) .* ...\n        R.^2 .* cos(theta);\nelse\n    conf.secondary_sources.x0(:,7) = ones(nls,1);\nend\n% Check if we have a 2D or 3D secondary source setup\nif any(phi-phi(1)>eps('single')) && any(theta-theta(1)>eps('single'))\n    % 3D case\n    conf.usetapwin = false;\n    if ~strcmp('3D',dimension)\n        warning(['You have a 3D HRTF data set, but are not using ', ...\n            'conf.dimension=\"3D\".']);\n    end\nelse\n    if strcmp('3D',dimension)\n        warning(['You are using a 2D HRTF data set, but are using ', ...\n            'conf.dimension=\"3D\".']);\n    end\nend\nif strcmp('2.5D',dimension)\n    % Apply a amplitude correction, due to 2.5D. This will result in a correct\n    % reproduced ILD in the resulting impulse responses, see Spors and\n    % Ahrens (2011).\n    amplitude_correction = -1.7 * sin(phi);\nelse\n    amplitude_correction = zeros(nls,1);\nend\n\n\n%% ===== Computation =====================================================\n% Get virtual secondary source positions\nx0_all = secondary_source_positions(conf);\nconf.wfs.hpreflow = 50;\nconf.wfs.hprefhigh = aliasing_frequency(x0_all,conf);\n\n% Initialize new irs set\nsofa_pw = sofa;\nsofa_pw.GLOBAL_Comment = 'Extrapolated HRTF set containing plane waves';\nsofa_pw.Data.IR = zeros(nls,2,N);\nsofa_pw.SourcePosition = [Inf 0 0];\n\n% Get all HRTFs for the secondary source positions\nir_all = zeros(nls,2,N);\nX = SOFAconvertCoordinates(sofa.ListenerPosition, ...\n                           sofa.ListenerPosition_Type, ...\n                           'cartesian');\nhead_orientation = SOFAconvertCoordinates(sofa.ListenerView, ...\n                                          sofa.ListenerView_Type, ...\n                                          'spherical');\nhead_orientation = rad(head_orientation(1,1:2));\nwarning('off','SFS:get_ir'); % Disable warning for short N\nfor ii=1:nls\n    ir_all(ii,:,:) = get_ir(sofa,X,head_orientation, ...\n                            x0_all(ii,1:3),'cartesian',conf)';\nend\nwarning('on','SFS:get_ir');\n\n% Generate a impulse response set for all given angles\nfor ii=1:nls\n\n    % Show progress\n    if showprogress, progress_bar(ii,nls); end;\n\n    % Direction of plane wave\n    [xs(1),xs(2),xs(3)] = sph2cart(phi(ii),theta(ii),R(ii));\n    xs = -xs;\n\n    % Calculate active virtual speakers\n    [x0,idx] = secondary_source_selection(x0_all,xs,'pw');\n    ir = ir_all(idx,:,:);\n    % Apply tapering window\n    x0 = secondary_source_tapering(x0,conf);\n\n    % Get driving signals, temporarely deactivate WFS pre-filter, because it\n    % will be applied once at the end\n    tmp_usehpre = conf.wfs.usehpre;\n    conf.wfs.usehpre = false;\n    [~,delay,weight] = driving_function_imp_wfs(x0,xs,'pw',conf);\n    conf.wfs.usehpre = tmp_usehpre;\n    % Sum up contributions from individual virtual speakers\n    for jj=1:size(x0,1)\n        % Delay and weight HRTFs\n        sofa_pw.Data.IR(ii,:,:) = squeeze(sofa_pw.Data.IR(ii,:,:)) + ...\n            delayline(squeeze(ir(jj,:,:))',delay(jj),weight(jj),conf)';\n    end\n    sofa_pw.Data.IR(ii,1,:) = sofa_pw.Data.IR(ii,1,:)/10^(amplitude_correction(ii)/20);\n    sofa_pw.Data.IR(ii,2,:) = sofa_pw.Data.IR(ii,2,:)/10^(-amplitude_correction(ii)/20);\n\nend\n\n%% ===== Pre-equalization ===============================================\nsofa_pw.Data.IR(:,1,:) = wfs_preequalization(squeeze(sofa_pw.Data.IR(:,1,:))',conf)';\nsofa_pw.Data.IR(:,2,:) = wfs_preequalization(squeeze(sofa_pw.Data.IR(:,2,:))',conf)';\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_HRTF_extrapolation/extrapolate_farfield_hrtfset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5760150711214774}}
{"text": "function m_full = getFullMask(m,frame_d,delay,kernel)\n%GETFULLMASK Convert frame rate mask to a sample-by-sample mask\n% \n%   M_FULL = IOSR.BSS.GETFULLMASK(M,FRAME_D) expands the time-frequency\n%   mask M, which has one unit for each frequency channel and frame of\n%   length FRAME_D (in samples), to a sample-by-sample mask. The mask M is\n%   a time-frequency mask, with one column for each frequency channel, and\n%   one row for each time frame. The resulting mask will have dimensions\n%   [FRAME_D*size(M,1) size(M,2)].\n% \n%   M_FULL = IOSR.BSS.GETFULLMASK(M,FRAME_D,DELAY) removes a delay from\n%   each frequency channel in the mask. DELAY is a vector, with the same\n%   number of elements as M has columns, containing a delay (in samples)\n%   that is removed from the corresponding frequency channel. The mask is\n%   subsequently zero-padded.\n% \n%   M_FULL = IOSR.BSS.GETFULLMASK(M,FRAME_D,DELAY,KERNEL) allows smoothing\n%   to be applied to the full mask. By default, the full mask contains\n%   rectangular transitions at unit boundaries. Specifying KERNEL allows\n%   the transitions to be smoother, by convolving the full mask with a\n%   two-dimensional kernel (dimensions [frequency time]). The central part\n%   of the convolution is returned, so the centre of the KERNEL should be\n%   in the centre of the matrix. The kernel is normalised in order to\n%   ensure zero gain at DC.\n% \n%   See also IOSR.BSS.RESYNTHESISE.\n\n%   Copyright 2016 University of Surrey.\n\n\n    if nargin < 2\n        error('iosr:getFullMask:nargin','Not enough input arguments')\n    end\n\n    numchans = size(m,2);\n    frameCount = size(m,1);\n\n    if nargin < 3\n        delay = zeros(1,numchans);\n    end\n    if nargin < 4\n        kernel = 1;\n    end\n\n    % Create the sample-by-sample mask\n    m_full = zeros(frameCount*frame_d,numchans);\n    for i = 1:numchans\n        for j = 1:frameCount\n            m_full(((j-1)*frame_d+1):((j-1)*frame_d+1)+frame_d-1,i) = m(j,i); \n        end\n        m_full(:,i) = [m_full(delay(i)+1:end,i); zeros(delay(i),1)];\n    end\n\n    % convolve with kernel\n    kernel = kernel./sum(abs(kernel(:)));\n    m_full = conv2(m_full,kernel,'same');\n    \nend\n", "meta": {"author": "IoSR-Surrey", "repo": "MatlabToolbox", "sha": "4bff1bb2da7c95de0ce2713e7c710a0afa70c705", "save_path": "github-repos/MATLAB/IoSR-Surrey-MatlabToolbox", "path": "github-repos/MATLAB/IoSR-Surrey-MatlabToolbox/MatlabToolbox-4bff1bb2da7c95de0ce2713e7c710a0afa70c705/+iosr/+bss/getFullMask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5760150628678156}}
{"text": "function [ma,ASAsellog,ASAcontrol] = sig2ma(sig,cand_order,last)\n%SIG2MA MA model identification\n%   [MA,SELLOG] = SIG2MA(SIG) estimates moving average models from the \n%   data vector SIG and selects a model with optimal predictive \n%   qualities. The selected model is returned in the parameter vector MA. \n%   The structure SELLOG provides additional information on the selection \n%   process.\n%   \n%   SIG2MA(SIG,CAND_ORDER) selects only from candidate models whose \n%   orders are entered in CAND_ORDER. CAND_ORDER must either be a row of \n%   ascending orders, or a single order (in which case no true order \n%   selection is performed).\n%   \n%   Without user intervention, the mean of SIG is subtracted from the \n%   data. To control the subtraction of the mean, see the help topics on \n%   ASAGLOB_SUBTR_MEAN and ASAGLOB_MEAN_ADJ.\n%     \n%   SIG2MA is an ARMASA main function.\n%   \n%   See also: SIG2AR, SIG2ARMA, ARMASEL.\n\n%   References: P. M. T. Broersen, Autoregressive Model Orders for\n%               Durbin's MA and ARMA estimators, IEEE Transactions on\n%               Signal Processing, Vol. 48, No. 8, August 2000,\n%               pp. 2454-2457.\n\n%Header\n%=========================================================================\n\n%Declaration of variables\n%------------------------\n\n%Declare and assign values to local variables\n%according to the input argument pattern\nswitch nargin\ncase 1 \n   if isa(sig,'struct'), ASAcontrol=sig; sig=[];\n   else, ASAcontrol=[];\n   end\n   cand_order=[];\ncase 2 \n   if isa(cand_order,'struct'), ASAcontrol=cand_order; cand_order=[]; \n   else, ASAcontrol=[]; \n   end\ncase 3 \n   if isa(last,'struct'), ASAcontrol=last;\n   else, error(ASAerr(39))\n   end\notherwise\n   error(ASAerr(1,mfilename))\nend\n\nif isequal(nargin,1) & ~isempty(ASAcontrol)\n      %ASAcontrol is the only input argument\n   ASAcontrol.error_chk = 0;\n   ASAcontrol.run = 0;\nend\n\n%Declare ASAglob variables \nASAglob = {'ASAglob_subtr_mean';'ASAglob_mean_adj'; ...\n      'ASAglob_rc';'ASAglob_ar';'ASAglob_final_f'; ...\n      'ASAglob_final_b';'ASAglob_ar_cond'};\n\n%Assign values to ASAglob variables by screening the\n%caller workspace\nfor ASAcounter = 1:length(ASAglob)\n   ASAvar = ASAglob{ASAcounter};\n   eval(['global ' ASAvar]);\n   if evalin('caller',['exist(''' ASAvar ''',''var'')'])\n      eval([ASAvar '=evalin(''caller'',ASAvar);']);\n   else\n      eval([ASAvar '=[];']);\n   end\nend\n\n%ARMASA-function version information\n%-----------------------------------\n\n%This ARMASA-function is characterized by\n%its current version,\nASAcontrol.is_version = [2000 12 30 20 0 0];\n%and its compatability with versions down to,\nASAcontrol.comp_version = [2000 12 30 20 0 0];\n\n%This function calls other functions of the ARMASA\n%toolbox. The versions of these other functions must\n%be greater than or equal to:\nASAcontrol.req_version.burg = [2000 12 30 20 0 0];\nASAcontrol.req_version.cic = [2000 12 30 20 0 0];\nASAcontrol.req_version.rc2arset = [2000 12 30 20 0 0];\nASAcontrol.req_version.cov2arset = [2000 12 30 20 0 0];\nASAcontrol.req_version.armafilter = [2000 12 12 14 0 0];\nASAcontrol.req_version.convol = [2000 12 6 12 17 20];\nASAcontrol.req_version.convolrev = [2000 12 6 12 17 20];\n\n%Checks\n%------\n\nif ~any(strcmp(fieldnames(ASAcontrol),'error_chk')) | ASAcontrol.error_chk\n   %Perform standard error checks\n   %Input argument format checks\n   ASAcontrol.error_chk = 1;\n   if ~isnum(sig)\n      error(ASAerr(11,'sig'))\n   end\n   if ~isavector(sig)\n      error([ASAerr(14) ASAerr(15,'sig')])\n   elseif size(sig,2)>1\n      sig = sig(:);\n      warning(ASAwarn(25,{'row';'sig';'column'},ASAcontrol))\n   end\n   if ~isempty(cand_order)\n      if ~isnum(cand_order) | ~isintvector(cand_order) |...\n            cand_order(1)<0 | ~isascending(cand_order)\n         error(ASAerr(12,{'candidate';'cand_order'}))\n      elseif size(cand_order,1)>1\n         cand_order = cand_order';\n         warning(ASAwarn(25,{'column';'cand_order';'row'},ASAcontrol))\n      end\n   end\n   \n   %Input argument value checks\n   if ~isreal(sig)\n      error(ASAerr(13))\n   end\n   if max(cand_order) > length(sig)-1\n      error(ASAerr(21))\n   end\nend\n\nif ~any(strcmp(fieldnames(ASAcontrol),'version_chk')) | ASAcontrol.version_chk\n      %Perform version check\n   ASAcontrol.version_chk = 1;\n      \n   %Make sure the requested version of this function\n   %complies with its actual version\n   ASAversionchk(ASAcontrol);\n   \n   %Make sure the requested versions of the called\n   %functions comply with their actual versions\n   burg(ASAcontrol);\n   cic(ASAcontrol);\n   rc2arset(ASAcontrol);\n   cov2arset(ASAcontrol);\n   armafilter(ASAcontrol);\n   convol(ASAcontrol);\n   convolrev(ASAcontrol);\nend\n\nif ~any(strcmp(fieldnames(ASAcontrol),'run')) | ASAcontrol.run\n      %Run the computational kernel\n   ASAcontrol.run = 1;\n   ASAcontrol.version_chk = 0;\n   ASAcontrol.error_chk = 0;\n   ASAtime = clock;\n   ASAdate = now;\n\n%Main   \n%================================================================================================\n  \n%Initialization of variables\n%---------------------------\n\nif isempty(ASAglob_subtr_mean) | ASAglob_subtr_mean\n   sig = sig-mean(sig);\n   if isempty(ASAglob_mean_adj)\n      ASAglob_mean_adj = 1;\n   end\nelseif isempty(ASAglob_mean_adj)\n   ASAglob_mean_adj = 0;\nend\n\nn_obs = length(sig);\nar_stack = cell(4,1);\nar_entry = ones(1,4);\nrc = [];\nma_sel = 1;\n\n%Combined determination of the maximum candidate MA\n%order and the max. candidate sliding AR order \n%--------------------------------------------------\n\ndef_max_ma_order = min(fix(n_obs/5),fix(80*log10(n_obs)));\nif def_max_ma_order > 400; \n   def_max_ma_order = 400;\nend\n\nif isempty(cand_order)\n   cand_order = 0:def_max_ma_order;\nend\nmax_ma_order = cand_order(end);\n\nif max_ma_order <= def_max_ma_order\n   max_slid_ar_order = fix(2.5*def_max_ma_order);\nelse\n   max_slid_ar_order = fix(2.5*max_ma_order);\n   if max_slid_ar_order > n_obs-1\n      max_slid_ar_order = n_obs-1;\n   end\nend\n\n%Preparations for the estimation procedure\n%-----------------------------------------\n\nl_cand_order = length(cand_order);\nma = zeros(1,max_ma_order);\nvar = sig'*sig/n_obs;\nif cand_order(1)==0\n   zero_incl = 1;\n   gic3 = zeros(1,l_cand_order);\n   gic3(1) = log(var)+3/n_obs;\n   pe_est = zeros(1,l_cand_order);\n   if ASAglob_mean_adj\n      pe_est(1) = var*(n_obs+1)/(n_obs-1);\n   else\n      pe_est(1) = var;\n   end\nelse\n   zero_incl = 0;\n   cand_order = [0 cand_order];\n   gic3 = zeros(1,l_cand_order+1);\n   gic3(1) = inf;\n   pe_est = zeros(1,l_cand_order+1);\nend\n\nif max_ma_order > 0\n   %Conditioning AR orders to the previously selected AR model\n   if isequal(ASAglob_ar_cond,1) & ~isempty(ASAglob_ar)\n      ar = ASAglob_ar;\n      sel_ar_order = length(ar)-1;\n      if  2*sel_ar_order+max_ma_order < max_slid_ar_order\n         max_slid_ar_order = 2*sel_ar_order+max_ma_order;\n      end\n   end \n   \n   %AR model estimation\n   l_rc = length(ASAglob_rc);\n   if l_rc>1\n      rc = ASAglob_rc;\n      if (l_rc < max_slid_ar_order+1)\n         if isempty(ASAglob_final_f)\n            ar_det = rc2arset(ASAglob_rc(1:end-1),ASAcontrol);\n            ASAglob_final_f = convol(sig,ar_det,l_rc-1,n_obs,ASAcontrol);\n            ASAglob_final_b = convolrev(ar_det,sig,l_rc-1,n_obs,ASAcontrol);\n         end\n         rc = [ASAglob_rc burg(ASAglob_final_f, ...\n               ASAglob_final_b,max_slid_ar_order+1-l_rc,ASAcontrol)];\n      end\n   else\n      rc = burg(sig,max_slid_ar_order,ASAcontrol);\n   end\n\n   %AR model order selection\n   if ~isequal(ASAglob_ar_cond,1) | isempty(ASAglob_ar)\n      rc(1) = 0;\n      res = var*cumprod(1-rc(1:max_slid_ar_order+1).^2);\n      rc(1) = 1;\n      [min_value,sel_location] = min(cic(res,n_obs,ASAcontrol));\n      sel_ar_order = sel_location-1;\n   end\n   \n   min_ma_order = max(1,cand_order(1));\n   \n   slid_ar_order = 2*sel_ar_order+min_ma_order;\n   if slid_ar_order > max_slid_ar_order\n      slid_ar_order = max_slid_ar_order;\n   elseif slid_ar_order < 3\n      slid_ar_order = min(3,max_slid_ar_order);\n   end\n   \n   pred_ar_order = min(3*sel_ar_order+min(9,1+fix(n_obs/10)),max_slid_ar_order);\n   \n   %Determine a minimum set of AR parameter vectors, as needed for the preparations\n   [cand_ar_order,ar_entry] = sort([sel_ar_order pred_ar_order slid_ar_order max_slid_ar_order]);\n   equal_entry = zeros(1,4);\n   [dummy,redirect] = sort(ar_entry);\n   equal_counter = 0;\n   for i = 2:4\n      if isequal(cand_ar_order(i),cand_ar_order(i-1));\n         equal_counter = equal_counter+1;\n         equal_entry(i) = i;\n         index = find(max(0,redirect-i+equal_counter));\n         redirect(index) = redirect(index)-1;\n      end\n   end\n   cand_ar_order(find(equal_entry)) = [];\n   ar_entry = redirect;\n   ar_stack = rc2arset(rc,cand_ar_order,ASAcontrol);\n   \n   ar_pred = ar_stack{ar_entry(2)};\n   l_ar_pred = length(ar_pred);\n   l_pred_sig = fix(n_obs/2);\n   pred_sig_rev = armafilter(zeros(l_pred_sig,1),ar_pred,1,...\n      sig(end:-1:1),convolrev(sig,ar_pred,1,l_ar_pred,ASAcontrol),ASAcontrol);\n   pred_sig = pred_sig_rev(end:-1:1);\n   \n   counter = 2;\n   req_counter = 2;\n   sel_index = 1;\n   ar_slid = zeros(1,max_slid_ar_order+1); \n   ar_slid(1:slid_ar_order+1) = ar_stack{ar_entry(3)};\n   \n   %Estimation procedure and model order selection\n   %----------------------------------------------\n   \n   for order = min_ma_order:max_ma_order\n      if cand_order(req_counter)==order\n         ar_corr = convolrev(ar_slid(1:slid_ar_order+1),order,ASAcontrol);\n         ma = cov2arset(ar_corr,ASAcontrol);\n         \n         e = armafilter(sig,ma,1,filter(1,ma,pred_sig),pred_sig,ASAcontrol);\n         res = e'*e/n_obs;\n         gic3_temp = log(res)+3*(order+1)/n_obs;\n         gic3(req_counter) = gic3_temp;\n         if gic3_temp < gic3(sel_index)\n           sel_index = req_counter;\n           ma_sel = ma;\n         end\n         if ASAglob_mean_adj\n            pe_est(req_counter) = res*(n_obs+order+1)/(n_obs-order-1);\n         else\n            pe_est(req_counter) = res*(n_obs+order)/(n_obs-order);\n         end\n         req_counter = req_counter+1;            \n      end\n      \n      if slid_ar_order < max_slid_ar_order\n         slid_ar_order = slid_ar_order+1;\n         rc_temp = rc(slid_ar_order+1);\n         ar_slid(2:slid_ar_order) = ar_slid(2:slid_ar_order)+rc_temp*ar_slid(slid_ar_order:-1:2);\n         ar_slid(slid_ar_order+1) = rc_temp;\n      end\n      \n      counter = counter+1;\n   end\nend\n\n%Arranging output arguments\n%--------------------------\n\nma = ma_sel;\n\nif ~zero_incl\n   gic3(1) = [];\n   pe_est(1) = [];\n   cand_order(1) =[];\nend\n\nif ~isempty(rc)\n   ASAglob_rc = rc;\nend\n\nif nargout>1\n   ASAsellog.funct_name = mfilename;\n   ASAsellog.funct_version = ASAcontrol.is_version;\n   ASAsellog.date_time = [datestr(ASAdate,8) 32 datestr(ASAdate,0)];\n   ASAsellog.comp_time = etime(clock,ASAtime);\n   ASAsellog.ma = ma_sel;\n   ASAsellog.ar_sel = ar_stack{ar_entry(1)};\n   ASAsellog.mean_adj = ASAglob_mean_adj;\n   ASAsellog.cand_order = cand_order;\n   ASAsellog.gic3 = gic3;\n   ASAsellog.pe_est = pe_est;\nend\n\n%Footer\n%=====================================================\n\nelse %Skip the computational kernel\n   %Return ASAcontrol as the first output argument\n   if nargout>1\n      warning(ASAwarn(9,mfilename,ASAcontrol))\n   end\n   ma = ASAcontrol;\n   ASAcontrol = [];\nend\n\n%Program history\n%======================================================================\n%\n% Version                Programmer(s)          E-mail address\n% -------                -------------          --------------\n% former versions        P.M.T. Broersen        p.m.t.broersen@tudelft.nl\n% [2000 12 30 20 0 0]    W. Wunderink           wwunderink01@freeler.nl\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1330-armasa/ARMASA/fast/estimation/sig2ma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5760150628678155}}
{"text": "function [soln,eqn,info] = StokesCRP0(node,elem,bdFlag,pde,option)\n%% STOKESCR Stokes equation: CR elements.\n%\n%   [u,p] = STOKESPCR(node,elem,bdFlag,pde) use Crouzeix and Raviart\n%   nonconforming elements to approximate velocity u and piecewise constant\n%   to approximate pressure p, repectively.\n%\n%       -div(mu*grad u) + grad p = f in \\Omega,\n%                        - div u = 0 in \\Omega,\n%   with\n%       Dirichlet boundary condition        u = g_D  on \\Gamma_D,\n%       Neumann boundary condition du/dn - np = g_N  on \\Gamma_N.\n%\n%  Created by Ming Wang at July, 2012, with discussion of Lin Zhong.\n%\n% See also Stokes, StokesP2P1, PoissonCR.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('option','var'), option = []; end\n\n%% Construct Data Structure\n[elem2dof,edge] = dofedge(elem);\nNE = size(edge,1); NT = size(elem,1); Nu = NE; Np = NT; N = size(node,1);\n\nt = cputime;\n%% Compute geometric quantities and gradient of local basis\n[Dlambda,area] = gradbasis(node,elem);\n\n%% Assemble stiffness matrix for Laplace operator\nA = sparse(Nu,Nu);\nfor i = 1:3\n    for j = i:3\n        % local to global index map\n        ii = double(elem2dof(:,i));\n        jj = double(elem2dof(:,j));\n        % local stiffness matrix\n        Aij = 4*dot(Dlambda(:,:,i),Dlambda(:,:,j),2).*area;\n        if (j==i)\n            A = A + sparse(ii,jj,Aij,Nu,Nu);\n        else\n            A = A + sparse([ii,jj],[jj,ii],[Aij; Aij],Nu,Nu);\n        end\n    end\nend\nclear Aij\nA = blkdiag(A,A);\n\n%% Assemble matrix for divergence operator\nd1 = -2.*Dlambda(:,:,1).*[area,area];\nd2 = -2.*Dlambda(:,:,2).*[area,area];\nd3 = -2.*Dlambda(:,:,3).*[area,area];\nDx = sparse(repmat((1:Np)',3,1),double(elem2dof(:)),...\n            [d1(:,1);d2(:,1);d3(:,1)],Np,Nu);\nDy = sparse(repmat((1:Np)',3,1),double(elem2dof(:)),...\n            [d1(:,2);d2(:,2);d3(:,2)],Np,Nu);\nB = -[Dx Dy];\nclear d1 d2 d3 B1 B2\n\n%% Assemble right hand side\nf1 = zeros(Nu,1);\nf2 = zeros(Nu,1);\nif ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n    pde.f = [];\nend\nif ~isempty(pde.f)\n    mid1 = (node(elem(:,2),:) + node(elem(:,3),:))/2;\n    mid2 = (node(elem(:,3),:) + node(elem(:,1),:))/2;\n    mid3 = (node(elem(:,1),:) + node(elem(:,2),:))/2;\n    ft1 = repmat(area,1,2).*pde.f(mid1)/3;\n    ft2 = repmat(area,1,2).*pde.f(mid2)/3;\n    ft3 = repmat(area,1,2).*pde.f(mid3)/3;\n    f1 = accumarray(elem2dof(:),[ft1(:,1);ft2(:,1);ft3(:,1)],[Nu 1]);\n    f2 = accumarray(elem2dof(:),[ft1(:,2);ft2(:,2);ft3(:,2)],[Nu 1]);\nend\n\n[AD,BD,f,g,u,p,ufreeDof,pDof] = getbdStokesCR;\n\n\n%% Record assembeling time\nassembleTime = cputime - t;\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(ufreeDof), return; end\nif isempty(option) || ~isfield(option,'solver')    % no option.solver\n    if length(f)+length(g) <= 1e3  % Direct solver for small size systems\n        option.solver = 'direct';\n    else          % Multigrid-type  solver for large size systems\n        option.solver = 'asmg';\n    end\nend\nsolver = option.solver;\n\n%% Solver\nswitch solver\n    case 'direct'\n        t = cputime;\n        bigA = [AD, BD'; ...\n                BD, sparse(Np,Np)];\n        bigF = [f; g];\n        bigu = [u; p];\n        bigFreeDof = [ufreeDof; 2*Nu+pDof];\n        bigu(bigFreeDof) = bigA(bigFreeDof,bigFreeDof)\\bigF(bigFreeDof);\n        u = bigu(1:2*Nu);\n        p = bigu(2*Nu+1:end);\n        residual = norm(bigF - bigA*bigu);\n        info = struct('solverTime',cputime - t,'itStep',0,'err',residual,'flag',2,'stopErr',residual);        \n    case 'mg'\n        option.solver  = 'WCYCLE';\n        [u(ufreeDof),p,info] = mgstokes(A(ufreeDof,ufreeDof),B(:,ufreeDof),f(ufreeDof),g,...\n                                        u(ufreeDof),p,elem,ufreeDof,option);         \n    case 'asmg'\n        [u(ufreeDof),p,info] = asmgstokes(A(ufreeDof,ufreeDof),B(:,ufreeDof),f(ufreeDof),g,...\n                                          u,p,node,elem,bdFlag,ufreeDof,option); \nend\n\n%% Post-process\nif length(pDof) ~= Np % p is unique up to a constant\n    % impose the condition int(p)=0\n    c = sum(p.*area)/sum(area);\n    p = p - c;\nend\n\n%% Output\nsoln = struct('u',u,'p',p);\neqn = struct('A',AD,'B',BD,'Lap',A,'f',f,'g',g,...\n             'edge',edge,'ufreeDof',ufreeDof,'pDof',pDof);\ninfo.assembleTime = assembleTime;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbdStokesCR\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    function [AD,BD,f,g,u,p,ufreeDof,pDof] = getbdStokesCR\n        %% Boundary condition of Stokes equation: CR elements\n        \n        %% Initial set up\n        f = [f1; f2];    % set in Neumann boundary condition\n        g = zeros(Np,1);\n        u = zeros(2*Nu,1);\n        p = zeros(Np,1);\n        ufreeDof = (1:Nu)';\n        pDof = (1:Np)';\n        \n        if ~exist('bdFlag','var'), bdFlag = []; end\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: Find Dirichlet dof and modify the matrix\n        % Find Dirichlet boundary dof: fixedDof and pDof\n        isFixedDof = false(Nu,1);\n        if ~isempty(bdFlag)       % case: bdFlag is not empty\n            isDirichlet(elem2dof(bdFlag(:)==1)) = true;\n            isFixedDof(isDirichlet) = true;% dof on D-edges\n            fixedDof = find(isFixedDof);\n            ufreeDof = find(~isFixedDof);\n        end\n        if isempty(bdFlag) && ~isempty(pde.g_D) && isempty(pde.g_N) && isempty(pde.g_R)\n            s = accumarray(elem2dof(:), 1, [Nu 1]);\n            isFixedDof = (s==1);\n            fixedDof = find(isFixedDof);\n            ufreeDof = find(~isFixedDof);\n        end\n        if isempty(fixedDof) % pure Neumann boundary condition\n            % pde.g_N could be empty which is homogenous Neumann boundary condition\n            fixedDof = 1;\n            ufreeDof = 2:Nu;    % eliminate the kernel by enforcing u(1) = 0;\n        end\n        \n        % Modify the matrix\n        % Build Dirichlet boundary condition into the matrix AD by enforcing\n        % AD(fixedDof,fixedDof)=I, AD(fixedDof,ufreeDof)=0, AD(ufreeDof,fixedDof)=0.\n        % BD(:,fixedDof) = 0 and thus BD'(fixedDof,:) = 0.\n        bdidx = zeros(2*Nu,1);\n        bdidx(fixedDof) = 1;\n        bdidx(Nu+fixedDof) = 1;\n        Tbd = spdiags(bdidx,0,2*Nu,2*Nu);\n        T = spdiags(1-bdidx,0,2*Nu,2*Nu);\n        AD = T*A*T + Tbd;\n        BD = B*T;\n        \n        %% Part 2: Find boundary edges and modify the right hand side f and g\n        % Find boundary edges: Neumann and Robin\n        Neumann = []; Robin = []; %#ok<*NASGU>\n        if ~isempty(bdFlag)\n            isNeumann(elem2dof((bdFlag(:)==2)|(bdFlag(:) == 3))) = true;\n            isRobin(elem2dof(bdFlag(:)==3)) = true;\n            Neumannidx = find(isNeumann);\n            Neumann   = edge(isNeumann,:);\n            Robin     = edge(isRobin,:);\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);\n            if ~isempty(pde.g_R)\n                Robin = Neumann;\n            end\n        end\n        \n        % Neumann boundary condition\n        if ~isempty(pde.g_N) && ~isempty(Neumann) && ~(isnumeric(pde.g_N) && (pde.g_N == 0))\n            [lambda,w] = quadpts1(3);\n            nQuad = size(lambda,1);\n            % edge bases \n            bdphi = 2*(lambda(:,1)+lambda(:,2))-1;\n            % length of edge\n            ve = node(Neumann(:,1),:) - node(Neumann(:,2),:);\n            edgeLength = sqrt(sum(ve.^2,2));\n            % update RHS\n            for pp = 1:nQuad\n                pxy = lambda(pp,1)*node(Neumann(:,1),:)+lambda(pp,2)*node(Neumann(:,2),:);\n                gp = pde.g_N(pxy);\n                f1(Neumannidx) = f1(Neumannidx) + w(pp)*edgeLength.*gp(:,1).*bdphi(pp); % interior bubble\n                f2(Neumannidx) = f2(Neumannidx) + w(pp)*edgeLength.*gp(:,2).*bdphi(pp); % interior bubble\n            end\n        end\n        f = [f1; f2];\n        % The case non-empty Neumann but g_N=[] corresponds to the zero flux\n        % boundary condition on Neumann edges and no modification is needed.\n        \n        % Dirichlet boundary conditions\n        if ~isempty(fixedDof) && ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && (pde.g_D == 0))\n            u1 = zeros(Nu,1);\n            u2 = zeros(Nu,1);\n            bdEdgeMid = (node(edge(fixedDof,1),:)+node(edge(fixedDof,2),:))/2;\n            uD = pde.g_D(bdEdgeMid);         % bd values at middle points of edges\n            u1(fixedDof) = uD(:,1);\n            u2(fixedDof) = uD(:,2);\n            u = [u1; u2]; % Dirichlet bd condition is built into u\n            f = f - A*u;  % bring affect of nonhomgenous Dirichlet bd condition to\n            g = g - B*u;  % the right hand side\n            g = g - mean(g); % impose the compatible condition\n            f(fixedDof) = u1(fixedDof);\n            f(fixedDof+Nu) = u2(fixedDof);\n            u = [u1; u2]; % Dirichlet bd condition is built into u\n        end\n        % The case non-empty Dirichlet but g_D=[] corresponds to the zero Dirichlet\n        % boundary condition and no modification is needed.\n        \n        % modfiy pressure dof for pure Dirichlet\n        if isempty(Neumann)\n            pDof = (1:Np-1)';\n        end\n        \n        ufreeDof = [ufreeDof; Nu+ufreeDof];                \n    end % end of function getbdStokesCR\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/StokesCRP0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5760150627565496}}
{"text": "%% SegmentalCylinder\n% Concrete subclass of <GenericCylinder.html |GenericCylinder|>\n% representing a cylinder with a cross section of a circular segment.\n\n%%% Description\n% |SegmentalCylinder| represents the shape of a segmental cylinder.  Its\n% cross section is a circular segment (region surrounded by an arc and the\n% chord connecting its end points).  The axis of the cylinder should be\n% aligned with one of the axes of the Cartesian coordinate system.\n\n%%% Construction\n%  shape = SegmentalCylinder(normal_axis, height, center, radius, theta, d_theta)\n%  shape = SegmentalCylinder(normal_axis, height, center, radius, theta, d_theta, dl_max)\n% \n% *Input Arguments*\n%\n% * |normal_axis|: axis of the cylinder.  It should be one of |Axis.x|,\n% |Axis.y|, |Axis.z|.\n% * |height|: size of the cylinder along its axis.\n% * |center|: center of the cylinder in the format of |[x y z]|.  For\n% |normal_axis = Axis.z|, |(x, y)| is the coordinate of the center of the\n% circle.\n% * |radius|: radius of the circle\n% * |theta|: beginning angle of the segment in radian\n% * |d_theta|: angular width of the segment in radian between -|pi| and |pi|\n% (the angle of a segment should not be reflex)\n% * |dl_max|: maximum grid size allowed in the cylinder.  It can be either |[dx\n% dy dz]| or a single real number |dl| for |dx = dy = dz|.  If unassigned,\n% |dl_max = Inf| is used.\n\n%%% Example\n%   % Create an instance of SegmentalCylinder.\n%   shape = SegmentalCylinder(Axis.z, 100, [0 0 50], 50, pi/6, pi/3);\n%\n%   % Use the constructed shape in maxwell_run().\n%   [E, H] = maxwell_run({INITIAL ARGUMENTS}, 'OBJ', {'vacuum', 'none', 1.0}, shape, {REMAINING ARGUMENTS});\n\n%%% See Also\n% <SectoralCylinder.html |CircularCylinder|>, <CircularCylinder.html\n% |CircularCylinder|>, <CircularShellCylinder.html\n% |CircularShellCylinder|>, <EllipticCylinder.html |EllipticCylinder|>,\n% <PolyognalCylinder.html |PolygonalCylinder|>, <Shape.html |Shape|>,\n% <maxwell_run.html |maxwell_run|>\n\nclassdef SegmentalCylinder < GenericCylinder\n\n\tmethods\n        function this = SegmentalCylinder(normal_axis, height, center, radius, theta, d_theta, dl_max)\n\t\t\tchkarg(istypesizeof(normal_axis, 'Axis'), '\"normal_axis\" should be instance of Axis.');\n\t\t\tchkarg(istypesizeof(height, 'real') && height > 0, '\"height\" should be positive.');\n\t\t\tchkarg(istypesizeof(center, 'real', [1, Axis.count]), ...\n\t\t\t\t'\"center\" should be length-%d row vector with real elements.', Axis.count);\n\t\t\tchkarg(istypesizeof(radius, 'real') && radius > 0, '\"radius\" should be positive.');\n\t\t\tchkarg(istypesizeof(theta, 'real'), '\"theta\" should be real.');\n\t\t\tchkarg(istypesizeof(d_theta, 'real') && (d_theta < pi || d_theta > -pi), '\"d_theta\" should be real between -pi and pi.');\n\t\t\t\n\t\t\tsectoral = SectoralCylinder(normal_axis, height, center, radius, theta, d_theta, dl_max);\n\t\t\t\n\t\t\tthetas = [theta, theta + d_theta];\n\t\t\t\n\t\t\tmc_dir = mean([cos(thetas.') sin(thetas.')]);  % direction bisecting the segment\n\t\t\tmc_dir = mc_dir / norm(mc_dir);\n\t\t\t\n\t\t\t[h, v, n] = cycle(normal_axis);\n\t\t\tmidpt = center([h, v]) + mean(radius .* [cos(thetas.') sin(thetas.')]);  % midpoint of chord\n\n\t\t\t% lsf2d() can handle rho = [p q] with column vectors p and q.  The\n\t\t\t% level set function is the one for a rectangle defined in the\n\t\t\t% (theta, radius) domain.\n\t\t\tfunction level = lsf2d(p, q)\n\t\t\t\tchkarg(istypeof(p, 'real'), '\"p\" should be array with real elements.');\n\t\t\t\tchkarg(istypeof(q, 'real'), '\"q\" should be array with real elements.');\n\t\t\t\tchkarg(isequal(size(p), size(q)), '\"p\" and \"q\" should have same size.');\n\t\t\t\t\n\t\t\t\tlevel1 = sectoral.lsf2d(p, q);  % level set function of sectoral cylinder\n\n\t\t\t\tlm = {p - midpt(Dir.h), q - midpt(Dir.v)};\n\t\t\t\tlevel2 = zeros(size(p));\n\t\t\t\tfor d = Dir.elems\n\t\t\t\t\tlevel2 = level2 + lm{d} .* mc_dir(d);\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tlevel = min(level1, level2);  % intersection of regions defined by level1 and level2\n\t\t\tend\n\t\t\t\n\t\t\tlprim = cell(1, Axis.count);\n\t\t\tlprim{h} = radius * cos(thetas) + center(h);\n\t\t\tlprim{v} = radius * sin(thetas) + center(v);\n\t\t\tlprim{n} = [-height height]/2 + center(n);\n\t\t\t\n\t\t\tif sectoral.lsf_th(0) > 0\n\t\t\t\tlprim{h} = [lprim{h}, center(h) + radius];\n\t\t\tend\n\t\t\tif sectoral.lsf_th(pi/2) > 0\n\t\t\t\tlprim{v} = [lprim{v}, center(v) + radius];\n\t\t\tend\n\t\t\tif sectoral.lsf_th(pi) > 0\n\t\t\t\tlprim{h} = [lprim{h}, center(h) - radius];\n\t\t\tend\n\t\t\tif sectoral.lsf_th(3*pi/2) > 0\n\t\t\t\tlprim{v} = [lprim{v}, center(v) - radius];\n\t\t\tend\n\t\t\t\t\t\t\n\t\t\tif nargin < 7  % no dl_max\n\t\t\t\tsuper_args = {normal_axis, @lsf2d, lprim};\n\t\t\telse\n\t\t\t\tsuper_args = {normal_axis, @lsf2d, lprim, dl_max};\n\t\t\tend\n\t\t\t\n\t\t\tthis = this@GenericCylinder(super_args{:});\n\t\tend\n\tend\nend\n\n", "meta": {"author": "wsshin", "repo": "maxwellfdfd", "sha": "f7d583813781694c8a6f0533a91f56c2a78a9ee5", "save_path": "github-repos/MATLAB/wsshin-maxwellfdfd", "path": "github-repos/MATLAB/wsshin-maxwellfdfd/maxwellfdfd-f7d583813781694c8a6f0533a91f56c2a78a9ee5/shape/SegmentalCylinder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5760150520854639}}
{"text": "function [ grSOrtho, H ] = msfmGradientLsml( anim, d )\n% Compute the LSML gradient in MSFM from Rabaud CVPR08\n%\n% Just check Rabaud's CVPR08 paper\n% the notations follow Rabaud's PhD thesis: Appendix D3\n%\n% USAGE\n%  [ grSOrtho, H ] = msfmGradientLsml( anim, d )\n%\n% INPUTS\n%  anim          - Animation object\n%  d             - dimensionality of the shape manifold\n%\n% OUTPUTS\n%  grSOrtho      - LSML gradient, orthogonal to the manifold\n%  H             - [ 3nPoint x d x nFrame ] tangent basis at every point\n%                  of the manifold\n%\n% EXAMPLE\n%\n% See also MSFMGRADIENTSRT\n%\n% Vincent's Structure From Motion Toolbox      Version 3.0\n% Copyright (C) 2008-2011 Vincent Rabaud.  [vrabaud-at-cs.ucsd.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the GPL [see external/gpl.txt]\n\nnFrame = anim.nFrame; nPoint = anim.nPoint;\n\nX3 = reshape(anim.S,3*nPoint, nFrame);\n\n% figure out neighbors in the data we have\nneigh = computeNeighbor( X3,'k',3,'forceConn',2);\nNmat = neigh.Nmat;\n\n% force temporally closeby frames to be considered together\nrow = zeros(1,nFrame); row(2) = 1;\nNmat(logical(toeplitz(row))) = 1;\n\n% learn the manifold from here\npTh=struct('d',d,'rbfK',5,'nRestart',5,'nSamples',250,'show',0);\nmanifold=lsmlOptimizeTh(X3,Nmat,pTh);\n\n% get the gradient for denoising\n[Chi3, Chi] = lsmlDenoise( X3, Nmat, manifold, 'nItr', 1 );\n\ngrSOrtho = reshape(X3-Chi,3,nPoint,nFrame);\n\nif nargout >=2; H = lsmlComputeH( X3, manifold, 1 ); end\nend\n", "meta": {"author": "vrabaud", "repo": "sfm_toolbox", "sha": "7ce933b31b71292eddabb40bacfd619720fa221d", "save_path": "github-repos/MATLAB/vrabaud-sfm_toolbox", "path": "github-repos/MATLAB/vrabaud-sfm_toolbox/sfm_toolbox-7ce933b31b71292eddabb40bacfd619720fa221d/msfm/msfmGradientLsml.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5760150520854638}}
{"text": "% Lawn sprinker example from Russell and Norvig p454\n% See www.cs.berkeley.edu/~murphyk/Bayes/usage.html for details.\n\nrand('state', 0);\nrandn('state', 0);\n\nN = 4;\ndag = zeros(N,N);\nC = 1; S = 2; R = 3; W = 4;\ndag(C,[R S]) = 1;\ndag(R,W) = 1;\ndag(S,W)=1;\n\nfalse = 1; true = 2;\nns = 2*ones(1,N); % binary nodes\n\nbnet = mk_bnet(dag, ns);\nbnet.CPD{C} = tabular_CPD(bnet, C, [0.5 0.5]);\nbnet.CPD{R} = tabular_CPD(bnet, R, [0.8 0.2 0.2 0.8]);\nbnet.CPD{S} = tabular_CPD(bnet, S, [0.5 0.9 0.5 0.1]);\nbnet.CPD{W} = tabular_CPD(bnet, W, [1 0.1 0.1 0.01 0 0.9 0.9 0.99]);\n\nnsamples = 500;\nsamplesM = cell(N, nsamples);\nfor i=1:nsamples\n  samplesM(:,i) = sample_bnet(bnet);\nend\n\nhide = rand(N, nsamples) > 0.9;\n[I,J]=find(hide);\nfor k=1:length(I)\n  samplesM{I(k), J(k)} = [];\nend\n\n% Make a initial chain like dag\nG0 = zeros(N,N);\nfor i=1:N-1\n   G0(i, i+1) = 1;\nend\n\nfigure;\ndraw_graph(G0);\n\nB0 = mk_bnet(G0, ns);\n% use random params\nfor i=1:N\n  B0.CPD{i} = tabular_CPD(B0, i, 'prior_type', 'dirichlet', 'dirichlet_weight', 0);\nend\n\nmax_loop = 30;\n%profile on -detail mmex\n[B0, order, best_score] = learn_struct_EM(B0, samplesM, max_loop);\n%profile report\n\ndag1 = B0.dag;\ndag1 = dag1(order,order);\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/examples/test_sem1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5760150518629322}}
{"text": "function sr=gabreassign(s,tgrad,fgrad,a)\n%GABREASSIGN  Reassign time-frequency distribution\n%   Usage:  sr = gabreassign(s,tgrad,fgrad,a);\n%\n%   `gabreassign(s,tgrad,fgrad,a)` reassigns the values of the positive\n%   time-frequency distribution *s* using the phase gradient given by *fgrad*\n%   and *tgrad*. The lattice is determined by the time shift *a* and the \n%   number of channels deduced from the size of *s*.\n%\n%   *fgrad* and *tgrad* can be obtained by the routine |gabphasegrad|.\n%\n%   Examples:\n%   ---------\n%\n%   The following example demonstrates how to manually create a\n%   reassigned spectrogram. An easier way is to just call |resgram|:::\n%\n%     % Create reassigned vector field of the bat signal.\n%     a=4; M=100;\n%     [tgrad, fgrad, c] = gabphasegrad('dgt',bat,'gauss',a,M);\n%\n%     % Perform the actual reassignment\n%     sr = gabreassign(abs(c).^2,tgrad,fgrad,a);\n%\n%     % Display it using plotdgt\n%     plotdgt(sr,a,143000,50);\n%  \n%   See also: resgram, gabphasegrad\n%\n%   References: aufl95\n\n% AUTHOR: Peter L. S\u00f8ndergaard, 2008.\n\nthisname = upper(mfilename);\ncomplainif_notenoughargs(nargin,4,thisname);\ncomplainif_notposint(a,'a',thisname);\n\n\n% Basic checks\nif any(cellfun(@(el) isempty(el) || ~isnumeric(el),{s,tgrad,fgrad}))\n    error('%s: s, tgrad, fgrad must be non-empty and numeric.',...\n          upper(mfilename));\nend\n\n% Check if argument sizes are consistent\nif ~isequal(size(s),size(tgrad),size(fgrad))\n   error('%s: s, tgrad, fgrad must all have the same size.',...\n          upper(mfilename));\nend\n\n% Check if any argument is not real\nif any(cellfun(@(el) ~isreal(el),{tgrad,fgrad}))\n   error('%s: tgrad, fgrad must be real.',...\n          upper(mfilename));\nend\n\n% if any(s<0)\n%     error('%s: s must contain positive numbers only.',...\n%         upper(mfilename));\n% end\n\nsr=comp_gabreassign(s,tgrad,fgrad,a);\n\n\n% The following code is currently not actived. It calculates the\n% reassigment using anti-aliasing, but it make very little visual\n% difference, and it is slower.\n  %   [M,N,W]=size(s);\n  %   L=N*a;\n  %   b=L/M;\n    \n  %   freqpos=fftindex(M);  \n  %   tgrad=bsxfun(@plus,tgrad/b,freqpos);\n        \n  %   timepos=fftindex(N);\n  %   fgrad=bsxfun(@plus,fgrad/a,timepos.');\n    \n  %   tgrad=round(tgrad);\n  %   fgrad=round(fgrad);\n    \n  %   tgrad=mod(tgrad,M);\n  %   fgrad=mod(fgrad,N);  \n    \n  %   sr=zeros(M,N,W);\n    \n  %   fk=mod(floor(tgrad),M)+1;\n  %   ck=mod(ceil(tgrad),M)+1;\n  %   fn=mod(floor(fgrad),N)+1;\n  %   cn=mod(ceil(fgrad),N)+1;\n    \n  %   alpha = fgrad-floor(fgrad);\n  %   beta  = tgrad-floor(tgrad);\n  %   m1 =(1-alpha).*(1-beta).*s;\n  %   m2 =(1-alpha).*beta.*s;\n  %   m3 =alpha.*(1-beta).*s;\n  %   m4 =alpha.*beta.*s;\n  %   for ii=1:M\n  %     for jj=1:N\n  %       sr(fk(ii,jj),fn(ii,jj))=sr(fk(ii,jj),fn(ii,jj))+m1(ii,jj);\n  %       sr(ck(ii,jj),fn(ii,jj))=sr(ck(ii,jj),fn(ii,jj))+m2(ii,jj);\n  %       sr(fk(ii,jj),cn(ii,jj))=sr(fk(ii,jj),cn(ii,jj))+m3(ii,jj);\n  %       sr(ck(ii,jj),cn(ii,jj))=sr(ck(ii,jj),cn(ii,jj))+m4(ii,jj);\n        \n  %     end;\n  %   end;\n  % end;\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/gabor/gabreassign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5760150410805808}}
{"text": "\nfunction  [X] =  WNNM( Y, C, NSig, m, Iter )\n    [U,SigmaY,V] =   svd(full(Y),'econ');    \n    PatNum       = size(Y,2);\n    TempC  = C*sqrt(PatNum)*2*NSig^2;\n    [SigmaX,svp] = ClosedWNNM(SigmaY,TempC,eps);                        \n    X =  U(:,1:svp)*diag(SigmaX)*V(:,1:svp)' + m;     \nreturn;\n", "meta": {"author": "lbasek", "repo": "image-denoising-benchmark", "sha": "9d753198d715b7628c8e7d9259dfa5c219d033ea", "save_path": "github-repos/MATLAB/lbasek-image-denoising-benchmark", "path": "github-repos/MATLAB/lbasek-image-denoising-benchmark/image-denoising-benchmark-9d753198d715b7628c8e7d9259dfa5c219d033ea/algoritms/matlab/WNNM/extra/WNNM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5760094010066973}}
{"text": "function [valFeature] = batch_peridoc_pitch_count_fast(testWave, Fs, numFrame, nSamplePerFrame, nSampleForward)\nx_start   = 1;\nx_end     = nSamplePerFrame;\nact_frame_x = zeros(nSamplePerFrame*2,numFrame);\nfor j=1:numFrame\n    act_frame_x(:,j) =  [testWave(x_start:x_end); zeros(x_end-x_start+1,1)];\n    x_start = x_start + nSampleForward;\n    x_end   = x_end   + nSampleForward;\nend\n\n[frSize, nFr] = size(act_frame_x);\nbinWidth = Fs/frSize;\nhammWinFrame  = hamming(frSize);\nHighPassFreqUpper = 800;\nnumHighPassFreqUpperBin = ceil(HighPassFreqUpper/binWidth);\nmapX=[1:numHighPassFreqUpperBin];\nmapX = 1/numHighPassFreqUpperBin.*mapX;\nmapX = mapX';\n\nframe_x = zeros(nSamplePerFrame*2,numFrame);\nfor i=1:nFr    \n    frame_x(:,i) = act_frame_x(:,i)/norm(act_frame_x(:,i));\n% so that signal level is NOT at play here!!!\nend\n\nframe_x_hamm  = bsxfun(@times, frame_x, hammWinFrame);\nabs_fft_x = abs(fft(frame_x_hamm));\nabs_fft_x(1:numHighPassFreqUpperBin,:) = bsxfun(@times, abs_fft_x(1:numHighPassFreqUpperBin,:), mapX);\nabs_fft_x = bsxfun(@times, abs_fft_x, 1./max(abs_fft_x(1:2*HighPassFreqUpper/binWidth,:)));\n\n% The above operation with mapX reduces low frequency power, basically\n% frequency filtering!!!\n\n% extract noise level from 2K-3K freq range\nabs_fft_x = abs_fft_x.^1.2;\n\nL = floor(frSize/2);\nbinWidth = (Fs/(L*2));\nPitchRangeLower = 80;\nPitchRangeUpper = 250;\n\nPitchIdxRange = ceil(PitchRangeUpper - PitchRangeLower)/binWidth;\nval_histPeak = [];\nval_histTrough = [];\n\nSumPeakVal = [];\nSumTroughVal = [];\nbeamWidth =2;\n\nfor (i=1:PitchIdxRange)\n    pitchVal  = floor( ((PitchRangeLower/binWidth) +i-1)*binWidth);\n    \n    % number of harmonics, skipping the first harmonics bcos very noisy!!!\n    for (j=2:7)\n        idx          = floor((j*pitchVal)/binWidth);\n        idx_trough   = floor(idx + (pitchVal/(2*binWidth)));\n        \n        Pi  = sum(abs_fft_x(idx-beamWidth:idx+beamWidth,:));\n        Ti =  sum(abs_fft_x(idx_trough-beamWidth:idx_trough+beamWidth,:));\n        \n        SumPeakVal(:,i,j-1)   =  Pi;\n        SumTroughVal(:,i,j-1) = Ti;\n    end\n    \nend\nSP = sum(SumPeakVal,3);\nST = sum(SumTroughVal,3);\nval_histTrough  = ST.^2;\n\nfor i=1:PitchIdxRange\n    currSumPeakVal = squeeze(SumPeakVal(:,i,:))';\n    currSumTroughVal = squeeze(SumTroughVal(:,i,:))';\n    val_histPeak(:,i)   = SP(:,i).^2 - var(currSumPeakVal)' - var(currSumTroughVal)';\nend\n\n[V1 iV1] = max(val_histPeak');\nfor i=1:nFr\n    V2(i) = abs(val_histTrough(i,iV1(i)));\nend\nvalFeature      = V1./V2;\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/utils/vad/Comb/batch_peridoc_pitch_count_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5760093955956057}}
{"text": "%  Figure 10.6      Feedback Control of Dynamic Systems, 6e\n%                        Franklin, Powell, Emami\n%\n% fig10_06.m is a script to generate Fig. 10.6        \n% frequency response for the PD design for the satellite   \nclf;\n% parameters for the two-mass spring model\nm=[1 .1]; k0=[0 .091] ; d0=[0 .0036]; k1=[0 .4];\n\n% call function\n[f,g,h,j]=twomass(m,k0,d0);\nnc1=0.25*[2 1];\ndc1=[1/40 1];\n\n% convert to state-space\n[ac,bc,cc,dc]=tf2ss(nc1, dc1);\n\n% series of controller and plant\n[aol,bol,col,dol]= series(ac, bc,cc,dc,f,g,h,j);\n[acl]=aol-bol*col;\nw=logspace(-1,1);w(26)=1;\n[magcl1, phcl1]= bode(aol,bol,col,dol,1,w);\nsubplot(211) ; \nloglog(w,[magcl1, ones(size(magcl1))]); \nxlabel('\\omega (rad/sec)');\nylabel('Magnitude, |KD_1(s)G(s)|');\ntitle('Fig. 10.6 Frequency response for the satellite PD design')\ngrid\nsubplot(212);  \nsemilogx(w, [phcl1, -180*ones(size(phcl1))]); grid\nxlabel('\\omega (rad/sec)');\nylabel('Phase (deg)');\n\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_06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.6406358548398982, "lm_q1q2_score": 0.5760093921321568}}
{"text": "function [x,g,j,gg] = kmeans(d,k,x0,l)\n%KMEANS Vector quantisation using K-means algorithm [X,ESQ,J]=(D,K,X0,L)\n%\n%  Inputs:\n%\n%    D(N,P)  contains N data vectors of dimension P\n%    K       is number of centres required\n%    X0(K,P) are the initial centres (optional)\n%     \n%      or alternatively\n%\n%    X0      gives the initialization method\n%            'f'   pick K random elements of D as the initial centres [default]\n%            'p'   randomly divide D into K sets and choose the centroids\n%    L       gives max number of iterations (use 0 if you just want to calculate G and J)\n%\n%  Outputs:\n%\n%    X(K,P)  is output row vectors (omitted if L=0)\n%    G       is mean square error\n%    J(N)    indicates which centre each data vector belongs to\n%    GG(L)   gives the mean square error at the start of each iteration (omitted if L=0)\n%\n% It is often a good idea to scale the input data so that it has equal variance in each\n% dimension before calling KMEANS.\n\n%  Originally based on a routine by Chuck Anderson, anderson@cs.colostate.edu, 1996\n\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: kmeans.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\nmemsize=voicebox('memsize'); \n[n,p] = size(d);\nnb=min(n,max(1,floor(memsize/(8*p*k))));    % block size for testing data points\nnl=ceil(n/nb);                  % number of blocks\nif nargin<4\n    l=300;                  % very large max iteration count\n    if nargin<3\n        x0='f';             % use 'f' initialization mode\n    end\nend\nif ischar(x0)\n    if k<n\n        if any(x0)=='p'                  % Initialize using a random partition\n            ix=ceil(rand(1,n)*k);       % allocate to random clusters\n            ix(rnsubset(k,n))=1:k;      % but force at least one point per cluster\n            x=zeros(k,p);\n            for i=1:k\n                x(i,:)=mean(d(ix==i,:),1);\n            end\n        else                                % Forgy initialization: choose k random points [default] \n            x=d(rnsubset(k,n),:);         % sample k centres without replacement\n        end\n    else\n        x=d(mod((1:k)-1,n)+1,:);    % just include all points several times\n    end\nelse\n    x=x0;\nend\nm=zeros(n,1);           % minimum distance to a centre\nj=zeros(n,1);           % index of closest centre\ngg=zeros(l,1);\nwp=ones(1,p);\nkk=1:p;\nkk=kk(ones(n,1),:);\nkk=kk(:);\n\nif l>0\n    for ll=1:l                 % loop until x==y causes a break\n        \n        % find closest centre to each data point [m(:),j(:)] = distance, index\n        \n        ix=1;\n        jx=n-nl*nb;\n        for il=1:nl\n            jx=jx+nb;        % increment upper limit\n            ii=ix:jx;\n            z = disteusq(d(ii,:),x,'x');\n            [m(ii),j(ii)] = min(z,[],2);\n            ix=jx+1;\n        end\n        y = x;              % save old centre list\n        \n        % calculate new centres as the mean of their assigned data values (or zero for unused centres)\n        \n        nd=full(sparse(j,1,1,k,1));         % number of points allocated to each centre\n        md=max(nd,1);                       % remove zeros\n        jj=j(:,wp);\n        x=full(sparse(jj(:),kk,d(:),k,p))./md(:,wp);    % calculate the new means \n        fx=find(nd==0);\n        \n        % if any centres are unused, assign them to data values that are not exactly on centres\n        % choose randomly if there are more such points than needed\n        \n        if ~isempty(fx)\n            q=find(m~=0);\n            if length(q)<=length(fx)\n                x(fx(1:length(q)),:)=d(q,:);\n            else\n                if length(fx)>1\n                    [rr,ri]=sort(rand(length(q),1));\n                    x(fx,:)=d(q(ri(1:length(fx))),:);\n                else\n                    x(fx,:) = d(q(ceil(rand(1)*length(q))),:);\n                end\n            end\n        end\n        \n        % quit if the centres are unchanged\n        \n        gg(ll)=sum(m,1);\n        if x==y\n            break\n        end\n    end\n    gg=gg(1:ll)/n;\n%     ll % *** DEBUG ***\n%     gg' % *** DEBUG ***\n    g=gg(end);\nelse            % if l==0 then just calculate G and J (but rename as X and G)\n    ix=1;\n    jx=n-nl*nb;\n    for il=1:nl\n        jx=jx+nb;        % increment upper limit\n        ii=ix:jx;\n        z = disteusq(d(ii,:),x,'x');\n        [m(ii),j(ii)] = min(z,[],2);\n        ix=jx+1;\n    end\n    x=sum(m,1)/n;\n    g=j;\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/v_kmeans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5759997072308755}}
{"text": "function x = stft_iw(Sx, opt)\n% ISTFT  Inverse short-time Fourier transform\n%\n% Very closely based on Steven Schimmel's stft.m and istft.m from\n% his SPHSC 503: Speech Signal Processing course at Univ. Washington.\n\nif nargin<2, opt = struct(); end\n\nif ~isfield(opt, 'window'), opt.window = round(size(Sx,2)/16); end\nif length(opt.window) == 1, opt.window = hamming(opt.window); end\nopt.overlap = length(opt.window)-1;\n\nwindow = opt.window / norm(opt.window, 2); % Unit norm\n\nNwin = length(window);\nn = size(Sx, 2);\n\n% regenerate the full spectrum 0...2pi (minus zero Hz value)\nSx = [Sx; conj(Sx(floor((Nwin+1)/2):-1:2,:))];\n\n% take the inverse fft over the columns\nxbuf = real(ifft(Sx,[],1));\n\n% apply the window to the columns\nxbuf = xbuf .* repmat(window(:),1,size(xbuf,2));\n\n% overlap-add the columns\nx = unbuffer(xbuf,Nwin,opt.overlap);\n\n%%% subfunction\nfunction y = unbuffer(x,w,o)\n% UNBUFFER  undo the effect of 'buffering' by overlap-add (see BUFFER)\n%    A = UNBUFFER(B,WINDOWLEN,OVERLAP) returns the signal A that is\n%    the unbuffered version of B.\n\ny    = [];\nskip = w - o;\nN    = ceil(w/skip);\nL    = (size(x,2) - 1) * skip + size(x,1);\n\n% zero pad columns to make length nearest integer multiple of skip\nif size(x,1)<skip*N, x(skip*N,end) = 0; end;\n\n% selectively reshape columns of input into 1-d signals\nfor i = 1:N\n    t = reshape(x(:,i:N:end),1,[]);\n    l = length(t);\n    y(i,l+(i-1)*skip) = 0;\n    y(i,[1:l]+(i-1)*skip) = t;\nend;\n\n% overlap-add\ny = sum(y,1);\ny = y(1:L);\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/stft_iw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5759997010474067}}
{"text": "% DEMCLASSIFICATION3 IVM for classification on a data-set sampled from a GP with null category.\n\n% IVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'classificationThree';\nexperimentNo = 3;\n\n% load data\n[X, y] = mapLoadData(dataSetName);\n\n\n% Set up model\noptions = ivmOptions;\noptions.display = 2;\noptions.kern = {'rbf', 'white'};\n\nmodel = ivmCreate(size(X, 1), size(y, 2), X, y, options);\n\nif options.display > 1\n  ivm3dPlot(model, 'ivmContour', i);\nend\nfor i = 1:options.extIters;\n\n  % Select the active set.\n  model = ivmOptimiseIVM(model, options.display);\n  % Plot the data.\n  if options.display > 1\n    ivm3dPlot(model, 'ivmContour', i);\n  end\n  % Optimise the kernel parameters.\n  model = ivmOptimiseKernel(model, options.display, options.kernIters);\nend\nmodel = ivmOptimiseIVM(model, options.display);\nif options.display > 1\n  ivm3dPlot(model, 'ivmContour', i);\nend\n% display active points.\nmodel = ivmOptimiseIVM(model, options.display);\n\n% Display the final model.\nivmDisplay(model);\n\n% Save the results.\ncapName = dataSetName;;\ncapName(1) = upper(capName(1));\n[kern, noise, ivmInfo] = ivmDeconstruct(model);\nsave(['dem' capName num2str(experimentNo) '.mat'], ...\n     'kern', ...\n     'noise', ...\n     'ivmInfo');\n\nif exist('printDiagram') & printDiagram\n  ivmPrintPlot(model, 'ivmContour', [], [], [], capName, experimentNo);\nend\n\n\n\n\n\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ivm/demClassification3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5759216495155306}}
{"text": "function [sys,x0,str,ts]=ADRC_2(t,x,u,flag,h,TD,ESO,NLSEF,b0)\n\nswitch flag\n    case 0\n        [sys,x0,str,ts]=mdlInitializeSizes(h);\n    case 2\n        sys=mdlUpdate(x,u,h,TD,ESO,b0);\n    case 3\n        sys=mdlOutputs(x,NLSEF,b0);\n    case 4,\n        sys=mdlGetTimeOfNextVarHit(t,h);\n    case {1,9}\n        sys=[];\n    otherwise \n        error(['Unhandled flag=',num2str(flag)]);\nend\nfunction [sys,x0,str,ts]=mdlInitializeSizes(h)\n    sizes=simsizes;\n    sizes.NumContStates=0;\n    sizes.NumDiscStates=5;\n    sizes.NumOutputs=2;\n    sizes.NumInputs=3;\n    sizes.DirFeedthrough=1;\n    sizes.NumSampleTimes=1;\n    sys=simsizes(sizes);\n    x0=[0;0;0;0;0];\n    str=[];\n    ts=[h 0];\nfunction sys=mdlUpdate(x,u,h,TD,ESO,b0)\n    e1=x(1)-u(1);\n    fh=fhan(e1,x(2),TD(1),TD(2));\n    sys(1)=x(1)+h*x(2);\n    sys(2)=x(2)+h*fh;\n    e2=x(3)-u(2);\n    sys(3)=x(3)+h*(x(4)-ESO(1)*e2);\n    sys(4)=x(4)+h*(x(5)-ESO(2)*fal(e2,0.5,ESO(4))+b0*u(3));\n    sys(5)=x(5)+h*(-ESO(3)*fal(e2,0.25,ESO(4)));\n%     fe=fal(e,0.5,Delta);\n%     fe1=fal(e,0.25,Delta);\n%     sys(1,1)=x(1)+h2*(x(2)-BB(1)*e);\n%     sys(2,1)=x(2)+h2*(x(3)-BB(2)*fe+u(1));\n%     sys(3,1)=x(3)+h2*(-BB(3)*fe1);\nfunction sys=mdlOutputs(x,NLSEF,b0)\n    e3=x(1)-x(3);\n    e4=x(2)-x(4);\n    sys(1)=-fhan(e3,NLSEF(1)*e4,NLSEF(2),NLSEF(3))-x(5)/b0;\n    sys(2)=x(1);\nfunction sys=mdlGetTimeOfNextVarHit(t,h)\n    sys=t+h;\n        \nfunction y=fhan(x1,x2,r,h)\nd=r*h;\nd0=h*d;\ny=x1+h*x2;\na0=sqrt(d^2+8*r*abs(y));\nif abs(y)>d0\n    a=x2+(a0-d)*sign(y)/2;\nelse\n    a=x2+y/h;\nend\n\nif abs(a)>d\n    y=-r*sign(a);\nelse \n    y=-r*a/d;\nend\n\nfunction f=fal(e,a,d)\n    if abs(e)<d\n        f=e*d^(a-1);\n    else f=(abs(e))^a*sign(e);\n    end", "meta": {"author": "TianfaYao", "repo": "ADRC", "sha": "6f1f96ebda1684c44af4dec4214b4880f4aa8cec", "save_path": "github-repos/MATLAB/TianfaYao-ADRC", "path": "github-repos/MATLAB/TianfaYao-ADRC/ADRC-6f1f96ebda1684c44af4dec4214b4880f4aa8cec/\u8d3a\u5e86\u6bd5\u4e1a\u8bba\u6587ADRC\u5168\u96c6\u5305\u4ec5\u7528\u4e8e\u5185\u90e8\u5171\u4eab\u4e0d\u8981\u5916\u4f20/MyLibrary/ADRC_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5759216419747876}}
{"text": "function results = lowrank_sparse_fista( data, params, funs )\n% FISTA implementation for solving\n%   min 0.5*||AY - T|| + \\lambda_*\\sum_i||Xi,(i)||_* + \\lambda1*||E||_1\n% where Z = [ X1,...,X_N,E ]', Y is the FISTA auxiliary variable, \n% A is a linear operator, T is given observation.\n\n% tic;\n% function handles\neval_f = funs.f;\neval_grad_f = funs.grad_f;\nAprod = funs.Aprod;\nAtprod = funs.Atprod;\nsolve_prox_grad = funs.prox_grad_solver;\n\nT = data.T;\nif params.IsTC\n    T = data.b;\nend\nN = length( size(params.X0) );\nY = cell(1,N+1);\nfor i = 1:N\n    Y{i} = params.X0;\nend\nY{N+1} = params.E0;\nZ = Y;\n\nuse_cont = isfield( params, 'use_cont' ) && params.use_cont;\nlambda1 = params.lambda;\nlambdaS = params.lambdaS;\nif use_cont\n    if lambdaS > 0\n        lambdaS_min = lambdaS;\n        r = lambda1 / lambdaS;      lambdaS = 0.99*norm(T);     lambda1 = lambdaS*r;\n    else\n        r = params.rRatio /sqrt( max(size(data.T)) );\n        lambdaS = 0.99*norm(T);     lambda1 = lambdaS*r;\n        lambdaS_min = lambdaS * 1e-5;\n    end\n    eta = 0.97;\nend\n\nmu = params.mu0;\nbeta = 0.5;\nt = 0;\n\nfZ = eval_f( Z, Aprod, T );\ntrnorm = 0;\noneNorm = 0;\n\nfor iter = 1:params.max_iter\n    \n    % compute gradient at Y\n    grad_f = eval_grad_f( Y, Aprod, Atprod, T );\n    \n    Zp = Z;     trnorm_p = trnorm;    fZp = fZ;     oneNorm_p = oneNorm;\n    [ Z, trnorm ] = solve_prox_grad( Y, mu, grad_f, lambdaS, lambda1 );\n    % backtrack linesearch\n    fY = eval_f( Y, Aprod, T );\n    ZYdiff = tensor_array_diff( Z, Y );\n    approx = fY + tensor_array_innerprod( grad_f, ZYdiff ) + tensor_array_norm(ZYdiff)^2 / (2*mu);\n    fZ = eval_f( Z, Aprod, T );\n    while fZ > approx\n        mu = mu * beta;\n        [ Z, trnorm ] = solve_prox_grad( Y, mu, grad_f, lambdaS, lambda1 );\n        ZYdiff = tensor_array_diff( Z, Y );\n        approx = fY + tensor_array_innerprod( grad_f, ZYdiff ) + tensor_array_norm(ZYdiff)^2 / (2*mu);\n        fZ = eval_f( Z, Aprod, T );\n    end\n    oneNorm = tensor_1norm(Z{N+1});\n    \n    % FISTA acceleration step\n    tp = t;\n    t = (1 + sqrt(1+4*tp^2))/2;\n    Zdiff = tensor_array_diff( Z, Zp );\n    Y = tensor_array_add( Zp, tensor_array_scale(Zdiff,(tp-1)/t) );\n    \n    \n    % compute optimality stats\n    Fp = fZp + lambdaS*trnorm_p + lambda1*oneNorm_p;\n    F = fZ + lambdaS*trnorm + lambda1*oneNorm;\n    rel_F = abs(F-Fp)/Fp;\n    denom = tensor_array_norm(Zp);\n    rel_X = tensor_array_norm(Zdiff) / denom;   if denom == 0; rel_X = 1; end\n    rel_err = norm(ten_sum_all(Z(1:N))-data.X) / norm(data.X);\n    \n    % print\n    if params.verbose && rem( iter, 50 ) == 0\n        fprintf('Iter: %d,   fit: %3.2e,   rel_F: %3.2e,    rel_X: %3.2e,   rel_err: %3.2e, S: %3.2e\\n', ...\n            iter, fZ, rel_F, rel_X, rel_err, lambdaS);\n    end\n    \n    if max(rel_F,rel_X) < params.opt_tol\n        break;\n    end\n    \n    % update lambda's\n    if use_cont\n        lambdaS = max( lambdaS*eta, lambdaS_min );\n        lambda1 = lambdaS*r;\n    end\nend\n\nresults.vars = Z;\nresults.V = params.V0;\nresults.T = data.T;\nresults.iter = iter;\n% results.cpu = toc;\nresults.mu = mu;\nresults.lambda1 = lambda1;\nresults.lambdaS = lambdaS;\nresults.IsTC = params.IsTC;\n\nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/td/RLRT/rpca/lowrank_sparse_fista.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.57592163067415}}
{"text": "function [newTS,newTBase] = mrSliceTiming(ts,frameAdjustment,method)\n% Adjust the time series of a slice/scan based on the slice position\n%\n%   [newTS,newTBase] = mrSliceTiming(ts,frameAdjustment,method)\n%\n% This function takes in the time series (ts) and recreates a new time\n% series at each voxel.  It calculates the time at which the ts was\n% actually measured and then interpolates to a new time frame.  All of the\n% different slices are interpolated to the same time frame, which is the\n% basis of slice timing adjustment.  The adjustment to all of the slices is\n% done by calling this routine repeated from AdjustSliceTiming.\n%\n% This is  the core routine for time series slice timing adjustment.\n% AdjustSliceTiming has overhead associated with creating the data type and\n% so forth.  This routine is just the calculation.\n%\n% ts:               Time series from a single slice within a scan \n% frameAdjustment:  The fraction of the frame (TR) this time series must\n%                   be resampled (not in seconds)\n% method:           'linear' or 'spline'\n%\n% Slice timing adjustment smooths noisy time series a little bit.  The\n% linear choice smooths more than the spline choice.\n%\n% Example:\n%   We don't call this routine on its own.  We call it from the\n%   wrapper AdjustSliceTiming().\n%\n\nif notDefined('ts'), error('Time series required'); end\nif notDefined('frameAdjustment'), error('frameAdjustment value required'); end\nif notDefined('method'), method = 'spline'; end\n\n% get nFrames, the number of time samples, from data\nnFrames    = size(ts,1);\n\n% Pad the with a replication of the first and last frames to deal with\n% extrapolation: \nts = [ts(1, :); ts; ts(nFrames, :)];\n\n% deal w/ NaNs. These may occur due to motion correction, for example. \n% For now, replace with zero. We should probably replace with the mean of\n% the neighbors at some point. \n%\n% nanInds = find(isnan(ts));\n% ts(nanInds) = 0;\nts(isnan(ts)) = 0;\n\n% These are the time samples for the amended (padded) ts.  We don't\n% bother multiplying by TR, though of course we could.\ntBaseRef = (0:nFrames+1);\n\n% If the timing between frames is deltaFrame, and the difference in slice\n% between this one and the standard slice is refSlice - slice, then we need\n% to adjust the times between this slice and the reference as here.  This\n% calculation should be replaced by a routine that includes the slice\n% ordering; the slice ordering should be saved!\n% newTBase = (1:nFrames) + deltaFrame * (refSlice - slice);\nnewTBase = (1:nFrames) + frameAdjustment;\n\nswitch lower(method)\n    case 'spline'\n        % Ress used spline temporal interpolation routine\n        newTS = spline(tBaseRef, ts', newTBase)';\n    case 'linear'\n        % This should be an option, as well as others.\n        newTS = interp1(tBaseRef(:), ts, newTBase(:));\n    otherwise\n        error('Undefined method %s\\n',method);\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/EventAnalysis/mrSliceTiming.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924953, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5759035033280876}}
{"text": "function DataSet = prtDataGenSwissRoll\n% prtDataGenSwissRoll  Generates data from the Swiss Roll data set.\n%\n%   DataSet = prtDataGenSwissRoll generates a prtDataSetRegress from the\n%   swiss roll data set. This data is drawn from a 2-D manifold embedded in\n%   3-dimensions. For more information on ths data set see the following:\n% \n%   http://isomap.stanford.edu/code/Readme\n%\n%   Example:\n%\n%   ds = prtDataGenSwissRoll;\n%\n%   See also: prtDataSetClass, prtDataGenBiModal, prtDataGenIris,\n%   prtDataGenManual, prtDataGenMary, prtDataGenNoisySinc,\n%   prtDataGenOldFaithful,prtDataGenProtate, prtDataGenSprial,\n%   prtDataGenSpiral3Regress, prtDataGenUnimodal, prtDataGenSwissRoll,\n%   prtDataGenUnimodal, prtDataGenXor\n\n\n\n\n\n\n\n\n% The 2-D manifold locations are in ds.getTargets, and the 3-dimensional \n% embedding is in ds.getObservations.\n\nswissRollFile = fullfile(prtRoot,']beta','dataGen','swissRoll','swiss_roll_data.mat');\nswiss = load(swissRollFile);\nX = swiss.X_data';\nY = swiss.Y_data';\n\nDataSet = prtDataSetRegress(X,Y,'name','Standard Swiss Roll Data');\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/dataGen/prtDataGenSwissRoll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.5759025350532276}}
{"text": "clear all; close all; clc;\n\n% Define path to a urdf file\npath_to_urdf = 'ur10e.urdf';\n\n\n% Generate functions for dynamics based on Lagrange method\n% Note that it might take some time\n% generate_rb_dynamics(path_to_urdf);\ngenerate_friction_eq();\n\n\n% Generate regressors for inverse dynamics of the robot, friction and load\n% Note that it might take some time\n% generate_rb_regressor(path_to_urdf);\n% generate_load_regressor(path_to_urdf);\n\n\n% Run tests\ntest_rb_inverse_dynamics()\ntest_base_params()\n\n\n% Perform QR decompostion in order to get base parameters of the robot\ninclude_motor_dynamics = 1;\n[pi_lgr_base, baseQR] = base_params_qr(include_motor_dynamics);\n\n\n% Estimate drive gains\ndrive_gains = estimate_drive_gains(baseQR, 'PC-OLS');\n% Or use those found in the paper by De Luca\n% drive_gains = [14.87; 13.26; 11.13; 10.62; 11.03; 11.47]; \n\n\n% Estimate dynamic parameters\npath_to_est_data = 'ur-20_02_10-30sec_12harm.csv';      idxs = [635, 3510];\n% path_to_data = 'ur-20_02_12-40sec_12harm.csv';    idxs = [500, 4460];    \n% path_to_data = 'ur-20_02_05-20sec_8harm.csv';     idxs = [320, 2310];\n% path_to_data = 'ur-20_02_12-50sec_12harm.csv';    idxs = [355, 5090];\nsol = estimate_dynamic_params(path_to_est_data, idxs, ...\n                              drive_gains, baseQR, 'PC-OLS');\n\n                          \n% Validate estimated parameters\npath_to_val_data = 'ur-20_01_17-ptp_10_points.csv';     idxs = [700, 4200];\n\nrre = validate_dynamic_params(path_to_val_data, idxs, ...\n                              drive_gains, baseQR, sol.pi_b, sol.pi_fr)\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "shamilmamedov", "repo": "dynamic_calibration", "sha": "11af40e7deb758ec080a175fed8fcdd6c99aca29", "save_path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration", "path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration/dynamic_calibration-11af40e7deb758ec080a175fed8fcdd6c99aca29/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5758232887111502}}
{"text": "% some variables needed\nu = P.x_trim(4);\nv = P.x_trim(5);\nw = P.x_trim(6);\nVa_trim = sqrt(u^2 + v^2 + w^2);\ntheta_trim = P.x_trim(8);\nalpha_trim = atan(w/u);\ndelta_e_trim = P.u_trim(1);\ndelta_t_trim = P.u_trim(4);\n\n% Roll attitude hold\nP.delta_a_max = 45 * pi / 180;\nP.phi_max = 15 * pi / 180;\nP.roll_max = 45 * pi / 180;\na_phi1 = -0.5 * P.rho * Va_trim^2 * P.S_wing * P.b * P.C_p_p * P.b / (2 * Va_trim);\na_phi2 = 0.5 * P.rho * Va_trim^2 * P.S_wing * P.b * P.C_p_delta_a;\nP.kp_phi = P.delta_a_max / P.phi_max * sign(a_phi2);\nomega_phi = sqrt(abs(a_phi2) * P.delta_a_max / P.phi_max);\nzeta_phi = 1.2;   % design parameter\nP.kd_phi = (2 * zeta_phi * omega_phi - a_phi1) / a_phi2;\nP.ki_phi = 0.2;    % design parameter\n\n% Course hold\nW_chi = 8;  % design parameter\nomega_chi = 1 / W_chi * omega_phi;\nzeta_chi = 0.707;   % design parameter\nVg = P.Va0;\nP.kp_chi = 2 * zeta_chi * omega_chi * Vg / P.gravity;\nP.ki_chi = omega_chi^2 * Vg / P.gravity;\n\n% Pitch attitude hold\nP.delta_e_max = 45 * pi / 180;\nP.e_theta_max = 10 * pi / 180;\na_theta1 = -P.rho * Va_trim^2 * P.c * P.S_wing * P.C_m_q * P.c / (2 * P.Jy * 2 * Va_trim);\na_theta2 = -P.rho * Va_trim^2 * P.c * P.S_wing * P.C_m_alpha / (2 * P.Jy);\na_theta3 = P.rho * Va_trim^2 * P.c * P.S_wing * P.C_m_delta_e / (2 * P.Jy);\nP.kp_theta = P.delta_e_max / P.e_theta_max * sign(a_theta3);\nomega_theta = sqrt(a_theta2 + P.delta_e_max / P.e_theta_max * abs(a_theta3));\nzeta_theta = 0.707;     % design parameter\nP.kd_theta = (2 * zeta_theta * omega_theta - a_theta1) / a_theta3;\nP.theta_max = 20 * pi / 180;\nP.pitch_max = 40 * pi / 180;\n\n% Airspeed hold using Throttle\na_V1 = P.rho * Va_trim * P.S_wing / P.mass ...\n       * (P.C_D_0 + P.C_D_alpha * alpha_trim + P.C_L_delta_e * delta_e_trim) ...\n       + P.rho * P.S_prop / P.mass * P.C_prop * Va_trim;\na_V2 = P.rho * P.S_prop / P.mass * P.C_prop * P.k_motor^2 * delta_t_trim;\na_V3 = P.gravity * cos(theta_trim - alpha_trim);\nomega_v = 5;   % design parameter\nzeta_v = 0.707;     % design parameter\nP.delta_t_max = 1;\nP.delta_t_min = 0;\nP.ki_v = omega_v^2 / a_V2;\nP.kp_v = (2 * zeta_v * omega_v - a_V1) / a_V2;\n\n% Airspeed hold using Pitch\nW_v2 = 7;   % design parameter\nzeta_v2 = 0.707;    % design parameter\nomega_v2 = 1 / W_v2 * omega_theta;\nK_theta_dc = P.kp_theta * a_theta3 / (a_theta2 + P.kp_theta * a_theta3);\nP.ki_v2 = -omega_v2^2/(K_theta_dc * P.gravity);\nP.kp_v2 = (a_V1 - 2 * zeta_v2 * omega_v2) / (K_theta_dc * P.gravity);\n\n% Altitude hold using Pitch\nW_h = 10;   % design parameter\nomega_h = 1 / W_h * omega_theta;\nVa = P.Va0;\nzeta_h = 1.2;     % design parameter\nP.h_max = 1000;\nP.h_min = 0;\nP.ki_h = omega_h^2 / (K_theta_dc * Va);\nP.kp_h = 2 * zeta_h * omega_h / (K_theta_dc * Va);\n\n", "meta": {"author": "chengji253", "repo": "Multiple-fixed-wing-UAVs-flight-simulation-platform", "sha": "7c1fa69d9033355461c0753c2a7408a9bcf1e3e7", "save_path": "github-repos/MATLAB/chengji253-Multiple-fixed-wing-UAVs-flight-simulation-platform", "path": "github-repos/MATLAB/chengji253-Multiple-fixed-wing-UAVs-flight-simulation-platform/Multiple-fixed-wing-UAVs-flight-simulation-platform-7c1fa69d9033355461c0753c2a7408a9bcf1e3e7/platform_code/uavA1/compute_gains.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5758232767450414}}
{"text": "%Simple function to test the cross method\nd=10;\n%elem_fun=@(x) sum(x); %Just sum of everything \np=0:d-1; p = 2.^p; \na=-5;b=5;\nn=2^d;\nh=(b-a)/(n-1);\n%mv=@(x) x.^3;\n%elem_fun=@(x) 1.0./(dot((x-1),p)+1e-3); %Just sum of everything \n%elem_fun=@(x) mv(1e-12+dot(x-1,p)*h);\n\n%Compare functions of TT-tensors\nx=tt_x(d,2); x=tt_tensor(x); \ne=tt_ones(d,2);e=tt_tensor(e);\nx=a*e+h*x; x=round(x,1e-13);\nrs=x;\n%fun=@(x) 1.0./sqrt(x);\n%fun=@(x) 1.0./x;\nfun=@(x) exp(-(x).^4) + 1;\nelem_fun = @(ind) fun(rs(ind));\n%elem_fun=@(ind) rs(ind);\n%elem_fun=@(x) sqrt(x(1))+x(2);\n\neps=1e-6;\n%y=tt_rc2(2*d,2,elem_fun,1e-12);\ny=tt_rc(d,2,elem_fun,1e-6,'nswp',40,'change_dir_on',false);\n\nz=funcrs2(rs,fun,1e-12,rs,20);\n\n\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/tests/ancient/test_cross2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5758232687850937}}
{"text": "function [AtA,A] = corrMatrix4D(obj,i)\n% calucate 4D correlation matrix\n%\n% (c) Thomas Kuestner \n% ---------------------------------------------------------------------\n\nnCha = size(obj.kCalib{i},4);\n\n% A = [];\n\nif(isreal(obj.kCalib))\n    A = zeros(prod(obj.calibSize{i} - obj.kernelSize + 1), prod(obj.kernelSize)*nCha,obj.measPara.precision);\nelse\n    A = complex(zeros(prod(obj.calibSize{i} - obj.kernelSize + 1), prod(obj.kernelSize)*nCha,obj.measPara.precision),zeros(prod(obj.calibSize{i} - obj.kernelSize + 1), prod(obj.kernelSize)*nCha,obj.measPara.precision));\nend\nif(isempty(A))\n    error('corrMatrix4D(): Unable to create GRAPPA kernel. Check kernel and calibration size dimensionality');\nend\ncounter = 1;\nfor n=1:nCha\n    if(isreal(obj.kCalib{i}(:,:,:,n)))\n        if(strcmp(obj.measPara.precision,'single'))\n            A(:,counter:counter+prod(obj.kernelSize)-1) = im3colRSingle(obj.kCalib{i}(:,:,:,n),obj.kernelSize).';\n        else\n            A(:,counter:counter+prod(obj.kernelSize)-1) = im3colR(obj.kCalib{i}(:,:,:,n),obj.kernelSize).'; % before: tmp =\n        end\n    else\n        if(strcmp(obj.measPara.precision,'single'))\n            A(:,counter:counter+prod(obj.kernelSize)-1) = im3colCSingle(obj.kCalib{i}(:,:,:,n),obj.kernelSize).';\n        else\n            A(:,counter:counter+prod(obj.kernelSize)-1) = im3colC(obj.kCalib{i}(:,:,:,n),obj.kernelSize).';\n        end\n    end\n    counter = counter + prod(obj.kernelSize);\nend\n\nAtA = A'*A;\n\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/@FOCUSS/corrMatrix4D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5757485900179543}}
{"text": "function S=PSNR(sss,aaa)\n\n[m n p]=size(sss);\nA=double(sss);\nB=double(aaa);\nsumaDif=0;\nmaxI=m*n*max(max(A.^2));\nfor u=1:m\n    for v=1:n\n        sumaDif=sumaDif+(A(u,v)-B(u,v))^2;\n    end\nend\nif  (sumaDif==0)\n    sumaDif=1;\nend\nS=maxI/sumaDif;\nS=10*log10(S);\n\n\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/\u7b2c 13 \u7ae0 \u57fa\u4e8e\u970d\u592b\u66fc\u56fe\u50cf\u538b\u7f29\u91cd\u5efa/PSNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276222, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5757292391128699}}
{"text": "function tests = test_ft_preproc_online_filter\n\n% MEM 1gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_preproc_online_filter_init ft_preproc_online_filter_apply\n\nif nargout\n  % assume that this is called by RUNTESTS\n  tests = functiontests(localfunctions);\nelse\n  % assume that this is called from the command line\n  fn = localfunctions;\n  for i=1:numel(fn)\n    feval(fn{i});\n  end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction testOptions(testCase)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nnchan   = 2;\nnsample = 100;\n\nresult = {};\n\n[B,A] = butter(6, 0.05, 'high');\nstate = ft_preproc_online_filter_init(B, A, zeros(nchan,1));\n\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n\n[B,A] = butter(6, 0.20, 'low');\nstate = ft_preproc_online_filter_init(B, A, zeros(nchan,1));\n\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n\n[B,A] = butter(6, [0.05 0.20]);\nstate = ft_preproc_online_filter_init(B, A, zeros(nchan,1));\n\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n[state, result{end+1}] = ft_preproc_online_filter_apply(state, randn(nchan, nsample) + 10);\n\n% the first  part is high-pass filtered\n% the second part is low-pass  filtered\n% the third  part is band-pass filtered\nplot(cat(2, result{:})');\n\n% all iterations were done with (slightly) different options, hence the results should not be equal\nfor i=1:numel(result)\n  for j=(i+1):numel(result)\n    assert(~isequal(result{i}, result{j}), 'the results %d and %d should not be equal', i, j);\n  end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_ft_preproc_online_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5757195554698192}}
{"text": "function [net, sName] = addOneLoop_forMeanShiftGrouping(net, sName, loopIdx, GaussianBandwidth)\n\nif ~exist('GaussianBandwidth', 'var')\n    GaussianBandwidth = 0.1;\nend\n%%\npre_input_layer = sName;\n\nlName = sprintf('loop%d_meanshift_S_is_XX', loopIdx);\nnet.addLayer(lName, ...\n    meanshift_S_is_XX(), ... \n    {sName}, lName);\nsName = lName;\n\nlName = sprintf('loop%d_meanshift_G_is_Gaussian', loopIdx);\nnet.addLayer(lName, ...\n    meanshift_G_is_Gaussian('delta', GaussianBandwidth), ...\n    {sName}, lName);\nG_layer = lName;\nsName = lName;\n\n\nlName = sprintf('loop%d_meanshift_d_is_sumG', loopIdx);\nnet.addLayer(lName, ...\n    meanshift_d_is_sumG(), ...\n    {sName}, lName);\nsName = lName;\n\n\nlName = sprintf('loop%d_meanshift_q_is_inv_d', loopIdx);\nnet.addLayer(lName, ...\n    meanshift_q_is_inv_d(), ...\n    {sName}, lName);\nsName = lName;\n\n\nlName = sprintf('loop%d_meanshift_P_is_G_diag_q', loopIdx);\nnet.addLayer(lName, ...\n    meanshift_P_is_G_diag_q(), ...\n    {G_layer, sName}, lName);\nsName = lName;\n\n\nlName = sprintf('loop%d_meanshift_Y_is_XP', loopIdx);\nnet.addLayer(lName, ...\n    meanshift_Y_is_XP(), ...\n    {pre_input_layer, sName}, lName);\nsName = lName;\n\n\n", "meta": {"author": "aimerykong", "repo": "Recurrent-Pixel-Embedding-for-Instance-Grouping", "sha": "748ade6b969c7861c2a9009cd0f0ffb27004677c", "save_path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping", "path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping/Recurrent-Pixel-Embedding-for-Instance-Grouping-748ade6b969c7861c2a9009cd0f0ffb27004677c/demo5_analysis_MShift_gradient/fun4MShift_analysis/addOneLoop_forMeanShiftGrouping.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5757195457920119}}
{"text": "function [U, Theta, V, numiter ] = OR1MP(m, n, r, Known, data, opts )\n%ORTHOGONAL-RANK-1-MATRIX-PURSUIT Infinit dimension matching pursuit for \n%low rank matrix\n%\n%For the problem           min    L(X) = ||X - Y||^2\n%                          s.t.   rank(X) <= r\n%                          X = Theta * M = sum_i theta_i * M_i = U Theta V'\n%   Detail variable\n%   Input:\n%         m ---- row number\n%         n ---- column number\n%         r ---- number of basis\n%         Known ---- index of the known spot in the matrix\n%         data ---- the content of the known spot in the matrix \n%         opts ---- parameters for the algorithm\n%   Output:\n%         U ---- output matrix: U\n%         Theta ---- output matrix: Theta\n%         V ---- output matrix: V\n%         numiter ---- number of iterations\n%\n%   Copyright Zheng Wang @ Arizona State University\n%   $Date: 2013/01/29$\n\nfn = mfilename;\nerror(nargchk(5, 6, nargin));\nif nargin < 6\n    epsilon = 1e-4; % convergence threshold\nelse\n    epsilon = opts.epsilon;\nend\n\n%addpath('PROPACK/');\n%addpath('largescale_ops/');\n%addpath('SLEP_package_4.1/');\n\n% initialization, \n[indm, indn] = ind2sub([m, n], Known);\ndata( data == 0 )= eps;\nres = sparse(indm, indn, data, m, n);\n[indm, indn, data] = find(res);\nU = [];\nV = [];\nMsup = [];\n\nverbosity = 1;\nprintsyb = ['-', 'X', '|'];\nif verbosity == 1\n    fprintf('\\nIteration:        ');\nend\n\ni = 0;\nW = 0;\noldresnorm = 0;\ngresnorm = 1;\nyy = [];\nnnorm = norm(data, 'fro');\n% main iteration\n% In OR1MP, the stop criterion is small gradient of residual\nwhile (i < r) && (gresnorm > epsilon )\n    % 1. find the top singular pair of the residual and update the gresnorm\n    resvec = data - W;\n    sparse_update(res, resvec); % sparse update the res using resvec\n\n    [u, ~, v] = topsvd(res, 20); % run our power method for 10 iterations\n    %[u, ~, v] = topsvd(res, 1);\n    %[u, ~, v] = lansvd(res, 1, 'L'); % fast sparse svd using PROPACK\n    %[u, s, v] = svds(res, 1); % use matlab sparse top svd\n    \n    resnorm = normest(res, 'fro')/nnorm;\n    gresnorm = abs(resnorm - oldresnorm);\n    oldresnorm = resnorm;\n\n    % 2. update the weight Theta, the pursuit basis is uv', its weight is s.\n    Mi = sparse_inp(u', v', indm, indn)';\n\n    % b) use incremental inverse to solve the least sqare problem\n    if i~=0\n        Minv = inverse_incremental(Minv, Msup'*Mi, Mi'*Mi);\n    else\n        Minv = 1/(Mi'*Mi);\n    end\n    yy = [yy; Mi'*data];\n    Theta = Minv*yy;\n    Msup = [Msup Mi];\n     \n    U = [U u];\n    V = [V v];\n\n    % 3. update the learned matrix W = U' * diag(Theta) * V;\n    W = Msup * Theta;\n    \n    if verbosity == 1\n        fprintf('\\b\\b\\b\\b\\b\\b\\b\\b  %c:%4d', printsyb(1+mod(i,length(printsyb))), i);\n    end\n    i = i + 1;\nend\n% V = diag(Theta)*V;\nnumiter = i;\n% fprintf( '\\n OR1MP run %d rounds! \\n', numiter);\n\n% %* Sparse selection: for sharpe low rank problem, we may need the lasso \n% %fine selection. Use lasso to learn a more sparse weights.\n% % Starting point\n% opts.init=2;        % starting from a zero point\n% % termination criterion\n% opts.tFlag=5;       % run .maxIter iterations\n% opts.maxIter=100;   % maximum number of iterations\n% % normalization\n% opts.nFlag=0;       % without normalization\n% % regularization\n% opts.rFlag=1;       % the input parameter 'rho' is a ratio in (0, 1)\n% opts.mFlag=0;       % treating it as compositive function\n% opts.lFlag=0;       % Nemirovski's line search\n% % get the final sparse Theta by lasso in SLEP toolbox\n% [Theta, ~, ~] = LeastR(Msup, data, 0.00001, opts); %  [W, funVal, ValueL] 00001\n\nfunction Ninv = inverse_incremental(Minv, MMi, d)\n% calculate the inverse of the blocked matrix of \nP = MMi' * Minv; % vector\nq = 1/(d - P*MMi); % scaler\ny = q*P;\nNinv = [Minv+P'*y, -y'; -y, q];\n\nfunction [u, s, v] = topsvd(A, round)\n% calculate the top svd of matrix A using round iterations\nstopeps = 1e-3;\n[m,n] = size(A);\nu = ones(m,1); % this is the sigma*u\nvo = 0;\nfor i=1:round\n    v = u'*A/(norm(u))^2;\n    u = A*v'/(norm(v))^2;\n    if norm(v-vo) < stopeps\n        break\n    end\n    vo = v;\nend\nnu = norm(u);\nnv = norm(v);\nu = u/nu;\nv = v'/nv;\n% v = v/nv;\ns = nu*nv;\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/OR1MP/OR1MP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.575719534665693}}
{"text": "function [rc,fval,it] = ARhat_misd(ng,xg,rcinit,rc0,lag_max)\n\n%ARHAT_MISD AR model from measurements with missing data\n%  [rc,fval,it] = ARhat_misd(ng,xg,rcinit,rc0,lag_max) estimates\n%  reflection coefficients from missing data (ng,xg). ng contains\n%  measurement times and xg the corresponding measurements.\n%  \n%  The starting value for the reflection coefficients is given by\n%  rc_start = [1 rc0 rcinit]\n%  An AR model is estimated using approximate Maximum Likelihood (ML)\n%  estimation, where rc0 is fixed and the ML is sought over the last\n%  reflection coefficients, starting in rcinit.\n%\n%  See also ARMLFIT, ARHAT_MISD.\n\nnseg = length(ng);\nn_obs = 0;\nfor seg = 1:nseg\n   n_obs = n_obs+length(ng{seg});\nend\n\nopties = optimset('Display','iter','TolX',.001/sqrt(n_obs),'TolFun',.0001);\n\n[rc_tan,fval,exitflag,output]= fminunc('ARMLfit',tan(.5*pi*rcinit),opties,ng,xg,rc0,lag_max);\nrc = 2/pi*atan(rc_tan);\nit = output.iterations;\n", "meta": {"author": "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/SegmentsMissing/ARhat_misd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5757195295853705}}
{"text": "function loadings = computeLoadingPercentPower(V,W,H)\n    loadings = [];\n    K = size(H,1); \n    varv = sum(V(:).^2); \n    for fi = 1:K\n        WH = helper.reconstruct(W(:,fi,:),H(fi,:)); \n        loadings(fi) = sum(2*V(:).*WH(:) - WH(:).^2)/varv;        \n    end\n    loadings(loadings<0)=0;\nend", "meta": {"author": "FeeLab", "repo": "seqNMF", "sha": "229b9b19ac3a34b8378945ec7f9e331e004bb777", "save_path": "github-repos/MATLAB/FeeLab-seqNMF", "path": "github-repos/MATLAB/FeeLab-seqNMF/seqNMF-229b9b19ac3a34b8378945ec7f9e331e004bb777/+helper/computeLoadingPercentPower.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5757195291025335}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   PARAMETERS Returns a data structure containing the parameters of the\n%   ABB IRB2400.\n%\n%   Author: Arturo Gil. Universidad Miguel Hern\ufffdndez de Elche. \n%   email: arturo.gil@umh.es date:   09/01/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 <http://www.gnu.org/licenses/>.\nfunction robot = parameters()\n\nrobot.name= 'ABB_IRB2400';\n\n%Path where everything is stored for this robot\nrobot.path = 'robots/abb/IRB2400';\n\nrobot.DH.theta= '[q(1) q(2)-pi/2 q(3) q(4) q(5) q(6)+pi]';\nrobot.DH.d='[0.615 0 0 0.755 0 0.085]';\nrobot.DH.a='[0.100 0.705 0.135 0 0 0]';\nrobot.DH.alpha= '[-pi/2 0 -pi/2 pi/2 -pi/2 0]';\n\nrobot.J=[];\n\n\nrobot.inversekinematic_fn = 'inversekinematic_irb2400(robot, T)';\n\n%number of degrees of freedom\nrobot.DOF = 6;\n\n%rotational: 0, translational: 1\nrobot.kind=['R' 'R' 'R' 'R' 'R' 'R'];\n\n%minimum and maximum rotation angle in rad\nrobot.maxangle =[deg2rad(-180) deg2rad(180); %Axis 1, minimum, maximum\n                deg2rad(-105) deg2rad(105); %Axis 2, minimum, maximum\n                deg2rad(-62.5) deg2rad(62.5); %Axis 3\n                deg2rad(-200) deg2rad(200); %Axis 4: \n                deg2rad(-120) deg2rad(120); %Axis 5\n                deg2rad(-400) deg2rad(400)]; %Axis 6: \n\n%maximum absolute speed of each joint rad/s or m/s\nrobot.velmax = [deg2rad(150); %Axis 1, rad/s\n                deg2rad(150); %Axis 2, rad/s\n                deg2rad(150); %Axis 3, rad/s\n                deg2rad(360); %Axis 4, rad/s\n                deg2rad(360); %Axis 5, rad/s\n                deg2rad(450)];%Axis 6, rad/s\n\nrobot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time\n            % end effectors maximum velocity\nrobot.linear_velmax = 1.0; %m/s, unavailable from datasheet\n\n%base reference system \nrobot.T0 = eye(4);\n\n%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION\n%position, velocity and acceleration\nrobot=init_sim_variables(robot);\n\n\n% GRAPHICS\nrobot.graphical.has_graphics=1;\nrobot.graphical.color = [255 20 20]./255;\n%for transparency\nrobot.graphical.draw_transparent=0;\n%draw DH systems\nrobot.graphical.draw_axes=1;\n%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for\n%bigger robots\nrobot.graphical.axes_scale=1;\n%adjust for a default view of the robot\nrobot.axis=[-2 2 -2 2 0 2.5];\n%read graphics files\nrobot = read_graphics(robot);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%DYNAMIC PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nrobot.has_dynamics=1;\n\n%link masses (kg)\nrobot.dynamics.masses=[0 269 60 30 20 1];\n\n%COM of each link with respect to own reference system\nrobot.dynamics.r_com=[0       0.05          0; %(rx, ry, rz) link 1\n    -0.550\t0\t 0.020; %(rx, ry, rz) link 2\n    0       0       0;  %(rx, ry, rz) link 3\n    0       -0.3775       0;%(rx, ry, rz) link 4\n    0       0           0;%(rx, ry, rz) link 5\n    0       0         0.032];%(rx, ry, rz) link 6\n\n\n%Inertia matrices of each link with respect to its D-H reference system.\n% Ixx\tIyy\tIzz\tIxy\tIyz\tIxz, for each row\nrobot.dynamics.Inertia=[0      0.35\t0   \t0\t0\t0;\n    .13     .524\t.539\t0\t0\t0;\n    .066\t.086\t.0125\t0\t0\t0;\n    1.8e-3\t1.3e-3\t1.8e-3\t0\t0\t0;\n    .3e-3\t.4e-3\t.3e-3\t0\t0\t0;\n    .15e-3\t.15e-3\t.04e-3\t0\t0\t0];\n\n\nrobot.motors=load_motors([5 5 5 4 4 4]);\n%Speed reductor at each joint\nrobot.motors.G=[300 300 300 300 300 300];\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/ABB/IRB2400/parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5756845794837547}}
{"text": "% Take in a vector of complex samples representing individual QPSK constellation points with the constellation rotated\n% such that the points are ideally at 1+i, -1+i, -1-i, and 1-i.\n%\n% This function uses hard decision, so it's not what you want to use in low SNR environments\n%\n% The constellation mapping is:\n%     1+i == 0b00\n%     1-i == 0b01\n%    -1+i == 0b10\n%    -1-i == 0b11\n%\n% Which comes from https://github.com/ttsou/openphy/blob/master/src/lte/qam.c#L35\n%\n% @param data_carriers Row or column vector of complex samples\n% @return quantized_bits Vector of 1/0 values that make up the bits demapped from the provided sample vector\nfunction [quantized_bits] = quantize_qpsk(data_carriers)\n    assert(iscolumn(data_carriers) || isrow(data_carriers), \"Data carriers must be row/column vector\");\n    \n    quantized_bits = zeros(length(data_carriers), 1);\n\n    % Track where in the `quantized_bits` vector the new bits should be placed\n    bits_offset = 1;\n    \n    % Walk through each complex sample in the input vector\n    for sample_idx = 1:length(data_carriers)\n        sample = data_carriers(sample_idx);\n\n        % Determine bit mapping based on the quadrant that the sample is located\n        if (real(sample) > 0 && imag(sample) > 0)\n            bits = [0, 0];\n        elseif (real(sample) > 0 && imag(sample) < 0)\n            bits = [0, 1];\n        elseif (real(sample) < 0 && imag(sample) > 0)\n            bits = [1, 0];\n        elseif (real(sample) < 0 && imag(sample) < 0)\n            bits = [1, 1];\n        else\n            bits = [0, 0];\n        end\n        \n        % Save off the quatized bits and move the counter ahead by 2\n        quantized_bits(bits_offset:bits_offset+1) = bits;\n        bits_offset = bits_offset + 2;\n    end\nend\n\n", "meta": {"author": "proto17", "repo": "dji_droneid", "sha": "6ecbd20bdb1babbe2481a3870221553a10cdfe21", "save_path": "github-repos/MATLAB/proto17-dji_droneid", "path": "github-repos/MATLAB/proto17-dji_droneid/dji_droneid-6ecbd20bdb1babbe2481a3870221553a10cdfe21/matlab/updated_scripts/quantize_qpsk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5756845694580414}}
{"text": "function mObject3 = waveformMorphing(mObject1,mObject2,mRate);\n%   Morphing with minimum information\n%   (Actually this is not real morphing.\n%   It is simply blending two waveform.)\n%   mObject3 = waveformMorphing(mObject1,mObject2,mRate);\n\n%   Designed and coded by Hideki Kawahara\n%   27/Feb./2005\n%   Copyright(c) 2005, Hideki Kawahara\n\nnLength = max(length(mObject1.waveform),length(mObject2.waveform));\nif mObject1.samplingFrequency ~= mObject2.samplingFrequency\n    mObject3 = [];\n    return\nend;\nx = zeros(nLength,1);\nx(1:length(mObject1.waveform)) = (1-mRate)*mObject1.waveform;\nx(1:length(mObject2.waveform)) = mRate*mObject2.waveform + x(1:length(mObject2.waveform));\n\nmObject3=createMobject;\nmObject3.waveform = x;\nmObject3.samplingFrequency = mObject1.samplingFrequency;\n", "meta": {"author": "HidekiKawahara", "repo": "legacy_STRAIGHT", "sha": "964684981fe12cd232c5e882259dff126b3af0f2", "save_path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT", "path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT/legacy_STRAIGHT-964684981fe12cd232c5e882259dff126b3af0f2/morphing_src/waveformMorphing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5756845694580413}}
{"text": "function y = centroid(M, x)\n% Attempts the computation of a centroid of a set of points on a manifold.\n% \n% function y = centroid(M, x)\n%\n% M is a structure representing a manifold.\n% x is a cell of points on that manifold.\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    % For now, just apply a few steps of gradient descent for Karcher means\n    \n    n = numel(x);\n    \n    problem.M = M;\n    \n    problem.cost = @cost;\n    function val = cost(y)\n        val = 0;\n        for i = 1 : n\n            val = val + M.dist(y, x{i})^2;\n        end\n        val = val/2;\n    end\n\n    problem.grad = @grad;\n    function g = grad(y)\n        g = M.zerovec(y);\n        for i = 1 : n\n            g = M.lincomb(y, 1, g, -1, M.log(y, x{i}));\n        end\n    end\n\n    % This line can be uncommented to check that the gradient is indeed\n    % correct. This should always be the case if the dist and the log\n    % functions in the manifold are correct.\n    % checkgradient(problem); pause;\n    \n    query = warning('query', 'manopt:getHessian:approx');\n    warning('off', 'manopt:getHessian:approx');\n    options.verbosity = 0;\n    options.maxiter = 15;\n    y = trustregions(problem, x{randi(n)}, options);\n    warning(query.state, 'manopt:getHessian:approx');\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/solvers/neldermead/centroid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5756845525966433}}
{"text": "%ASSEMBLEPROB Assembly of system matrix and right hand side/load vector.\n%\n%   [ M, A, F, T_M, T_A, T_F, T_SP ] = ASSEMBLEPROB( PROB, VARARGIN ) Calls the\n%   assembly routines to compute and assemble a monolithic sparse system\n%   matrix and a right hand side/load vector as specified in the PROB struct.\n%   Accepts optional propery value pairs in VARARGIN.\n%\n%       Input       Value/[Size]           Description\n%       -----------------------------------------------------------------------------------\n%       prob        struct                 Problem definition struct\n%       icub        scalar/{auto}          Numnerical integration rule used in assembly\n%                                                Default 1+max(shape function order)\n%       imass       scalar {1}             Mass matrix lumping:  1 = Full mass matrix\n%                                          2 = row sum lumping,  3 = diagonal lumping\n%                                          4 = HRZ diagonal lumping\n%       n_cmax      scalar {50000}         Max number of cells to assemble\n%                                          for at once (to limit memory consumption)\n%       f_m         logical {false}        Assembly flag for mass matrix\n%       f_a         logical {false}        Assembly flag for system matrix\n%       f_f         logical {false}        Assembly flag for load vector\n%       f_c         logical {true}         Assembly flag for integral constraints\n%       f_sparse    logical {false}        Return sparse/struct matrix format\n%       solcomp     {all dvars/subd}       Dependent variables/subdomains to assemble for\n%                                                                                         .\n%       Output      Value/[Size]           Description\n%       -----------------------------------------------------------------------------------\n%       M           sparse [n_M]           Assembled mass matrix\n%       A           sparse [n_A]           Assembled system matrix\n%       f           [n_A,1]                Assembled rhs/load vector\n%       t_m         scalar                 Time spent assembling mass matrix\n%       t_a         scalar                 Time spent assembling system matrix\n%       t_f         scalar                 Time spent assembling rhs/load vector\n%       t_sp        scalar                 Time for sparse matrix conversion\n%\n%   See also ASSEMBLEA, ASSEMBLEF, ASSEMMAT\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/core/assembleprob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5756845468025744}}
{"text": "function determ = conex3_determinant ( n )\n\n%*****************************************************************************80\n%\n%% CONEX3_DETERMINANT returns the determinant of the CONEX3 matrix.\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%  Parameters:\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Output, real DETERM, the determinant.\n%\n  determ = - 1.0;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/conex3_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.5756455999263635}}
{"text": "function [ edge_pointer, edge_data, xy ] = grf_example ( node_num, edge_num )\n\n%*****************************************************************************80\n%\n%% GRF_EXAMPLE sets up a GRF example.\n%\n%  Discussion:\n%\n%    The example is known as the Coxeter graph.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    12 January 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Stephen Skiena,\n%    Implementing Discrete Mathematics,\n%    Combinatorics and Graph Theory with Mathematica,\n%    Addison-Wesley, 1990.\n%\n%  Parameters:\n%\n%    Input, integer NODE_NUM, the number of nodes.\n%\n%    Input, integer EDGE_NUM, the number of edges.\n%\n%    Output, integer EDGE_POINTER(NODE_NUM+1), pointers to\n%    the beginning of edge data for each node.\n%\n%    Output, integer EDGE_DATA(EDGE_NUM), the edge data.\n%\n%    Output, real XY(2,NODE_NUM), the node coordinates.\n%\n  edge_pointer = [ ...\n    1,  4,  7, 10, 13, 16, 19, 22, 25, 28, ...\n   31, 34, 37, 40, 43, 46, 49, 52, 55, 58, ...\n   61, 64, 67, 70, 73, 76, 79, 82, 85 ]';\n\n  edge_data = [ ...\n     8,   2,   3, ...\n    14,   1,   5, ...\n     9,   4,   1, ...\n    10,   7,   3, ...\n    13,   2,   6, ...\n    12,   5,   7, ...\n    11,   6,   4, ...\n    25,  20,   1, ...\n    24,  21,   3, ...\n    23,  15,   4, ...\n    22,  16,   7, ...\n    28,  17,   6, ...\n    27,  18,   5, ...\n    26,  19,   2, ...\n    10,  18,  19, ...\n    11,  19,  20, ...\n    12,  21,  20, ...\n    13,  15,  21, ...\n    14,  16,  15, ...\n     8,  17,  16, ...\n     9,  18,  17, ...\n    11,  27,  24, ...\n    10,  28,  25, ...\n     9,  26,  22, ...\n     8,  23,  27, ...\n    14,  24,  28, ...\n    13,  25,  22, ...\n    12,  26,  23 ]';\n\n  xy = [ ...\n    0.412,   0.984; ...\n    0.494,   0.984; ...\n    0.366,   0.926; ...\n    0.388,   0.862; ...\n    0.546,   0.926; ...\n    0.518,   0.860; ...\n    0.458,   0.818; ...\n    0.152,   0.684; ...\n    0.264,   0.682; ...\n    0.354,   0.680; ...\n    0.458,   0.670; ...\n    0.554,   0.672; ...\n    0.658,   0.668; ...\n    0.774,   0.692; ...\n    0.164,   0.450; ...\n    0.228,   0.448; ...\n    0.274,   0.390; ...\n    0.242,   0.330; ...\n    0.194,   0.278; ...\n    0.146,   0.328; ...\n    0.102,   0.390; ...\n    0.668,   0.472; ...\n    0.638,   0.416; ...\n    0.656,   0.334; ...\n    0.714,   0.270; ...\n    0.798,   0.326; ...\n    0.830,   0.408; ...\n    0.754,   0.466 ]';\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/grf_io/grf_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5756455944423652}}
{"text": "%  Script file: plotsinc.m\n%\n%  Purpose: \n%    This program illustrates the use of handle graphics \n%    commands by creating a plot of sinc(x) from -3*pi to\n%    3*pi, and modifying the characteristics of the figure,\n%    axes, and line using the \"set\" function.\n%\n%  Record of revisions:\n%      Date       Programmer          Description of change\n%      ====       ==========          =====================\n%    04/02/07    S. J. Chapman        Original code\n%\n% Define variables:\n%   hndl         -- Handle of line\n%   x            -- Independent variable\n%   y            -- sinc(x)\n\n% Calculate sinc(x)\nx = -3*pi:pi/10:3*pi;\ny = sin(x) ./ x;\n\n% Find the zero value and fix it up.  The zero is\n% located in the middle of the x array.\nindex = fix(length(y)/2) + 1;\ny(index) = 1;\n\n% Plot the function.\nhndl = plot(x,y);\n\n% Now modify the figure to create a pink background,\n% modify the axis to turn on y-axis grid lines, and \n% modify the line to be a 2-point wide orange line.\nset(gcf,'Color',[1 0.8 0.8]);\nset(gca,'YGrid','on');\nset(hndl,'Color',[1 0.5 0],'LineWidth',3);\n", "meta": {"author": "101Hub", "repo": "Matlab101", "sha": "07273f68f1147a110443aeb121fa10962234f298", "save_path": "github-repos/MATLAB/101Hub-Matlab101", "path": "github-repos/MATLAB/101Hub-Matlab101/Matlab101-07273f68f1147a110443aeb121fa10962234f298/assets/\u300aMatlab\u7f16\u7a0b\u300b\u6e90\u7801/chap9/plotsinc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.5755314748745317}}
{"text": "function [a_opt,dt_opt] = refine(params,ref,tgt,varargin)\n% function [anew,dtnew] = refine(params,ref,tgt,{cons,projmodel})\n%\n% Optimize initial estimates (from Hough accumulator) using non-linear\n% minimization.\n% \n% For a variable alpha: params = [dt0,alpha0].\n% For a fixed alpha: params = [dt0] and cons = [alpha].\n\t\n% read in variable arguments\ncons\t= [];\n\tif (length(varargin)>0), cons = varargin{1}; end\nprojmodel\t= 'affine';\n\tif (length(varargin)>1), projmodel = varargin{2}; end\n\t\n% parameters+constraints must equal 2\nif (size(params,2)+size(cons,2) ~= 2)\n\terror('Incorrect number of parameters/constraints');\nend\n\n% extract alpha and dt from params/cons\ndt = params(:,1);\nif isempty(cons),\ta = params(:,2);\nelse,\t\t\t\t\t\t\ta = cons(:,1);\nend\n\n% perform non-linear optimization of initial estimates using sub-frame cost\n% function\ncmax = inf;\nfor hyp\t= 1:length(a)\n\tfprintf('  (a=%0.3f,dt=%0.3f) -> ',a(hyp),dt(hyp));\n\tif isempty(cons)\n\t\t[pmin,c]\t=\tfminsearch(@subframecost,[dt(hyp),a(hyp)],[],ref,tgt,[],projmodel);\n\t\tdtnew\t= pmin(1);\t\n\t\tanew\t= pmin(2);\n\telse\n\t\t[pmin,c]\t=\tfminsearch(@subframecost,[dt(hyp)],[],ref,tgt,[a(hyp)],projmodel);\n\t\tdtnew\t= pmin(1);\t\n\t\tanew\t= a(hyp);\n\tend\n\tfprintf('(a=%0.3f,dt=%0.3f)\\n',anew,dtnew);\n\t\n\tif (c < cmax)\n\t\tcmax\t\t= c;\n\t\tdt_opt\t= dtnew;\n\t\ta_opt\t\t= anew;\n\tend\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/43265-video-synchronization-from-human-motion-using-rank-constraints/sync/toolbox/refine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5755314715847203}}
{"text": "function [f] = spm_SHC_fx(x,v,P,varargin)\n% equations of motion for Lotka-Volterra dynamics\n% FORMAT [f] = spm_SHC_fx(x,v,P)\n%\n% x   - hidden states\n% v   - exogenous inputs\n% P.f - lateral connectivity\n% P.k - rate [default 1]\n%\n% returns f = dx/dt = P.f*S(x) - x/8 + 1;\n%              S(x) = 1./(1 + exp(-x))\n%\n% where C determines the order of unstable fixed points visited in the\n% stable heteroclinic channel.\n%\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_SHC_fx.m 3265 2009-07-10 14:02:22Z karl $\n\n\n\n% intialise\n%==========================================================================\n\n% SHC states \n%--------------------------------------------------------------------------\nf.x  = P.f*spm_phi(x.x) - x.x/32 + 1;\nf.c  = (spm_phi(x.x) - x.c)/64;\n\nf    = spm_vec(f)*16;\n\n\n\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_SHC_fx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5755279032642233}}
{"text": "function I = domIntegral4(data)\n%+========================================================================+\n%|                                                                        |\n%|              OPENDOM - LIBRARY FOR NUMERICAL INTEGRATION               |\n%|           openDom is part of the GYPSILAB toolbox for Matlab           |\n%|                                                                        |\n%| COPYRIGHT : Matthieu Aussal & Francois Alouges (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%|             francois.alouges@polytechnique.edu                         |\n%| WEBSITE   : www.cmap.polytechnique.fr/~aussal/gypsilab    \u00a0\u00a0\u00a0\u00a0         |\n%|                                                                        |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it.                                                      |\n%|________________________________________________________________________|\n%|   '&`   |                                                              |\n%|    #    |   FILE       : domIntegral4.m                                |\n%|    #    |   VERSION    : 0.40                                          |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |\n%|  ( # )  |   CREATION   : 14.03.2017                                    |\n%|  / 0 \\  |   LAST MODIF : 14.03.2018                                    |\n%| ( === ) |   SYNOPSIS   : Numerical integation with 4 input arguments   |\n%|  `---'  |                                                              |\n%+========================================================================+\n\n%%% FINITE ELEMENT OPERATOR --> \\int_{mesh(x)} psi(x)' f(x) psi(x) dx \nif isa(data{1},'dom') && isa(data{2},'fem')\n    % Domain with quadrature\n    Xdom   = data{1};\n    [X,Wx] = Xdom.qud;\n    Nx     = size(X,1);\n    Wx     = spdiags(Wx,0,Nx,Nx);\n    \n    % Integrated finite element matrix\n    u  = data{2};\n    Mu = u.uqm(Xdom);\n    if iscell(Mu)\n        Mu{1} = Mu{1}' * Wx;\n        Mu{2} = Mu{2}' * Wx;\n        Mu{3} = Mu{3}' * Wx;\n    else\n        Mu = Mu' * Wx;\n    end\n    \n    % Function evaluation on quadrature\n    F = data{3};\n    if iscell(F)\n        Fx{1} = spdiags(F{1}(X),0,Nx,Nx);\n        Fx{2} = spdiags(F{2}(X),0,Nx,Nx);\n        Fx{3} = spdiags(F{3}(X),0,Nx,Nx);\n    else\n        Fx = spdiags(F(X),0,Nx,Nx);\n    end\n    \n    % Finite element matrix\n    v  = data{4};\n    Mv = v.uqm(Xdom);\n    \n    % Integration\n    I = femMultiplyCell(Mu,Fx,Mv);\n\n    \n%%% BOUNDARY ELEMENT INTEGRATION --> \\int_{mesh(y)} f(x,y) psi(y) dy\nelseif isnumeric(data{1}) && isa(data{2},'dom')\n    % Evaluation points\n    X  = data{1};\n    Nx = size(X,1);\n    \n    % Domain with quadrature\n    Ydom   = data{2};\n    [Y,Wy] = Ydom.qud;\n    Ny     = size(Y,1);\n    Wy     = spdiags(Wy,0,Ny,Ny);\n\n    % Function evaluation on quadrature\n    F = data{3};\n    if iscell(F)\n        Fxy = {zeros(Nx,Ny),zeros(Nx,Ny),zeros(Nx,Ny)};\n        for i = 1:3\n            for j = 1:Ny\n                Fxy{i}(:,j) = F{i}(X,Y(j,:));\n            end\n        end\n    else\n        Fxy = zeros(Nx,Ny);\n        for j = 1:Ny\n            Fxy(:,j) = F(X,Y(j,:));\n        end\n    end    \n\n    % Integrated finite element matrix\n    v  = data{4};\n    Mv = v.uqm(Ydom);\n    if iscell(Mv)\n        Mv{1} = Wy * Mv{1};\n        Mv{2} = Wy * Mv{2};\n        Mv{3} = Wy * Mv{3};\n    else\n        Mv = Wy * Mv;\n    end\n        \n    % Integration\n    I = femMultiplyCell(Fxy,Mv);\n\n    \n%%% BOUNDARY ELEMENT INTEGRATION --> \\int_{mesh(x)} psi(x)' f(x,y) dx\nelseif isa(data{1},'dom') && isnumeric(data{2})\n    % Domain with quadrature\n    Xdom   = data{1};\n    [X,Wx] = Xdom.qud;\n    Nx     = size(X,1);\n    Wx     = spdiags(Wx,0,Nx,Nx);\n    \n    % Evaluation points\n    Y  = data{2};\n    Ny = size(Y,1);\n    \n    % Integrated finite element matrix\n    u  = data{3};\n    Mu = u.uqm(Xdom);\n    if iscell(Mu)\n        Mu{1} = Mu{1}' * Wx;\n        Mu{2} = Mu{2}' * Wx;\n        Mu{3} = Mu{3}' * Wx;\n    else\n        Mu = Mu' * Wx;\n    end\n    \n    % Function evaluation on quadrature\n    F = data{4};\n    if iscell(F)\n        Fxy = {zeros(Nx,Ny),zeros(Nx,Ny),zeros(Nx,Ny)};\n        for i = 1:3\n            for j = 1:Ny\n                Fxy{i}(:,j) = F{i}(X,Y(j,:));\n            end\n        end\n    else\n        Fxy = zeros(Nx,Ny);\n        for j = 1:Ny\n            Fxy(:,j) = F(X,Y(j,:));\n        end\n    end\n    \n    % Integration\n    I = femMultiplyCell(Mu,Fxy);\n    \n    \nelse\n    error('domIntegral4.m : unavailable case')\nend\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/openDom/domIntegral4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073575, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5755279032460195}}
{"text": "function H = mnorm_entropy(U)\nwarning('This function is deprecated')\n\n% H = mnorm_entropy(U)\n%\n% U is the Cholesky factor of a covariance matrix C, that is, a lower or\n% upper triangylar matrix such that C=U*U' or C=U'*U.\n\nd = size(U,1);\n\nH = d/2*log(2*pi) + 0.5*logdet_chol(U) + d/2;\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/deprecated/mnorm_entropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5755077586532801}}
{"text": "function [fin_im] =  main_function(or_im)\n    \n \n    % PREPROCESSING\n        or_im = pre_pro(or_im);\n     \n    \n    % NORMALIZE\n        or_im = normal(or_im,1);\n    \n       \n    % SEGMENTATION\n        blksze = 15; thresh = 0.08;\n        [norm_im, mask] = segmentation(or_im, blksze, thresh);\n \n    \n    % DIFFUSION\n        norm_im = diffusion(norm_im);\n    \n  \n    % ORIENTATION\n        [orientim, G_xx, G_yy, G_xy, cos2theta, sin2theta, denom] = orient(norm_im, 1, 5, 6);\n    %    showorient(orientim, 20);\n    \n    \n    % RELIABILTY\n        reliability = reliability_f(G_xx, G_yy, G_xy, cos2theta, sin2theta, denom);\n    \n    \n    % FREQUENCY\n        [freq] = frequency(norm_im, mask, orientim, 33, 5, 4, 14);\n    \n    \n    % GABOR FILTERS\n        gabor_im = gabor(freq);\n    \n    % MORE FILTERS FOR RIDGE PATTERNS\n        new_im = more_filter(norm_im, orientim, gabor_im, 0.5, 0.5);\n    \n \n    % BINARISE\n        thres = 0;\n        binim = binarise(new_im, thres);\n    \n    \n    % Applying reliabilty factor to the final enhanced image\n        rel = 0.5;  % reliability factor (above 0.5 is considered to be reliable)\n        %binim = binim.*mask.*(reliability>rel);\n        \n    fin_im = imcomplement(binim);\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u589e\u5f3a\u7b97\u6cd5/Fingerprint-Image-Enhancement-Algorithm-master/src/main_function.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.57550775865328}}
{"text": "function out = PeubChannel(P, n, L)\n%upper bound for the error probability of the AWGN channel\n%P - channel SNR\n%n - block length (scalar)\n%L - length of messages transmitter between the source encoder and the channel encoder   \n\n%\n%   Created in 2012 by Victoria Kostina (vkostina@caltech.edu)\n%\n\n\n%dP/dQ is bounded by a constant. Find that constant.\n[~, gamma2] = fminbnd(@(x)-ncx2pdf(n*x, n, n*P)./chi2pdf(n*x/(1+P), n)*(1+P), 0, 10);\ngamma2 = -gamma2;\n\nA = n/2*log(1+P) + n/2 - L - log(gamma2);\n\n\nFinner = @(v) ncx2pdf(n*v, n, n/P).*n.*exp(P/2/(1+P)*n*(v - thresv()));\ntail = 1 - ncx2cdf(thresv()*n,n,n/P);\nout = quad(Finner, 0, thresv())...                      %exponent < 1\n    + tail;                                             %exponent = 1\n\n    function out = thresv()\n        %threshold for v as a function of v0\n        out = max( 0, 2*(1+P)/P/n*A );\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/jscc/GMS-AWGN/PeubChannel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.575507750014239}}
{"text": "% Fig. 5.28  Feedback Control of Dynamic Systems, 6e \n%             Franklin, Powell, Emami\n% script for right side of Figure 5.28\n\nclf\nn=[1 2]; \nd=conv([1 1 0],[1 13]);\nnc=[1 .05];\ndc=[1 .01];\nnol=conv([0 0 n],nc);\ndol=conv(d,dc);\nsysOL=tf(nol,dol);\nK=0:.001:10;\nrlocus(sysOL,K); \n hold on\n title('Fig.5.28b Root locus for lead plus lag')\n  axis([-.15 .05 -.1 .1])\n z=0:.1:.9;\n wn=2:2:19;\n sgrid(z, wn)\n dcl=91*nol+dol;\n r=roots(dcl) % shows that extra  root from Lag comp is almost right on the zero.\n plot(r,'*')  \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_28b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5755077426164774}}
{"text": "function [gray_enhanced]=gray_level_images(current_image);\n %% trying dc coefficients\n[mrows,ncolumns]=size(current_image);\n current_image=mat2gray(current_image);\n        H = fspecial('disk',10);\n        gray_filtering=current_image;\n        blurred_gray = imfilter(gray_filtering,H,'replicate');\n        k=2;\n    for i=1:1:mrows\n        for j=1:1:ncolumns\ngray_enhanced(i,j)=mat2gray((gray_filtering(i,j)+(k.*(gray_filtering(i,j)-blurred_gray(i,j)))));\n        end\n    end\n%figure(10001);\nimshow(gray_enhanced);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37578-video-enhancement/video enhancement/gray_level_images.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.575507738296957}}
{"text": "% Demonstrates the projection of x^2 function\nclear all; close all; clc;\n\n% The function to be projected.\nfunc = @(x) (x-2).^2;\n\n% epsilon\npolarity = 0;\nstep = 0.01;\nepsilon = 0.2;\nstop = 2;\nx = 0:step:stop;\nfunc_x = func(x);\nprojection = spx.wavelet.lcs.project_0_right(func, step, stop, epsilon, polarity);\nsubplot(311);\nplot(x, func_x, 'r');\nsubplot(312);\nplot(x, projection, 'b');\nresidual = func_x - projection;\nsubplot(313);\nplot(x, residual, 'g');\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/wavelet/local_sine_cosine_bases/ex_project_square.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5755077339774364}}
{"text": "function [ FV ] = mesh_refine(FV,Nface)\n\n% mesh_refine - creates smaller triangles from a triangle mesh\n%\n% [ FV ] = mesh_refine( FV, Nface )\n%\n% FV.vertices   - vertex matrix (Nx3)\n% FV.faces      - face matrix (Mx3), indices into vertex matrix rows\n%\n% Nface         - subdivide faces into 4 or 6 faces,\n%                 the default 4 provides an even subdivision\n% \n% This function calls mesh_refine_tri4 or mesh_refine_tri6.  See\n% these for more details.\n% \n\n\n% This can be done until some minimal distance (D) of the mean \n% distance between vertices of all triangles is achieved.  If\n% no D argument is given, the function refines the mesh once.\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:57 $\n\n% Licence:  GNU GPL, no implied or express warranties\n% History:  08/2002, Darren.Weber_at_radiology.ucsf.edu, created\n%                    adapted this function as a wrapper to\n%                    mesh_refine_tri4 & mesh_refine_tri6\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nif ~exist('FV','var'),\n    error('MESH_REFINE: NO input FV struct');\nelseif isempty(FV),\n    error('MESH_REFINE: NO input FV struct');\nend\n\nif ~exist('Nface','var'),\n    Nface = 4;\nelseif isempty(Nface),\n    Nface = 4;\nend\n\n\nswitch Nface,\n    \ncase 4,\n    FV = mesh_refine_tri4(FV);\ncase 6,\n    FV = mesh_refine_tri6(FV);\notherwise\n    FV = mesh_refine_tri4(FV);\nend\n\n\nreturn\n \n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/mesh_refine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5754866682727912}}
{"text": "% Author: Relja Arandjelovic (relja@relja.info)\n\nfunction Y= relja_l1normalize_col( X )\n    Y= bsxfun(@rdivide, X, sum(abs(X),1) + 1e-12 );\nend\n", "meta": {"author": "HajimeTaira", "repo": "InLoc_demo", "sha": "b4c42de09d288f35e65ec0156608c704d6176b4f", "save_path": "github-repos/MATLAB/HajimeTaira-InLoc_demo", "path": "github-repos/MATLAB/HajimeTaira-InLoc_demo/InLoc_demo-b4c42de09d288f35e65ec0156608c704d6176b4f/functions/utils/relja_l1normalize_col.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5754866589418925}}
{"text": "function value = p14_gu ( u )\n\n%*****************************************************************************80\n%\n%% P14_GU computes the auxilliary function G(U).\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 U, the argument of the function.\n%\n%    Output, real VALUE, the value of the function.\n%\n  beta = 0.1;\n  gamma = 0.1;\n\n  value = u / ( beta * ( u + gamma ) );\n\n  return\nend\n", "meta": {"author": "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/p14_gu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.5754866542764432}}
{"text": "function [ a, seed ] = r8but_random ( n, mu, seed )\n\n%*****************************************************************************80\n%\n%% R8BUT_RANDOM randomizes a R8BUT matrix.\n%\n%  Discussion:\n%\n%    The R8BUT storage format is used for a banded upper triangular matrix.\n%    The matrix is assumed to be zero above the MU-th superdiagonal.\n%    The matrix is stored in an MU+1 by N array.\n%    Columns are preserved.\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%  Example:\n%\n%    N = 5, MU = 2\n%\n%    A11 A12 A13   0   0\n%      0 A22 A23 A24   0\n%      0   0 A33 A34 A35\n%      0   0   0 A44 A45\n%      0   0   0   0 A55\n%                --- ---\n%                    ---\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 number of columns of the matrix.\n%\n%    Input, integer MU, the upper bandwidth.\n%\n%    Input, integer SEED, a seed for the random number generator.\n%\n%    Output, real A(MU+1,N), the R8BUT matrix.\n%\n%    Output, integer SEED, an updated seed for the random number generator.\n%\n  for i = 1 : mu + 1\n\n    for j = 1 : mu + 1 - i\n      a(i,j) = 0.0;\n    end\n\n    for j = max ( 1, mu + 2 - i ) : n\n      [ a(i,j), seed ] = r8_uniform_01 ( seed );\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/r8but_random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5754866470912816}}
{"text": "function [Vdraw, phi_Vdraw]=sampleV(Psi,phi_V,Vold,priorValues,dataValues)\n% This function takes a draw from the conditional posterior of the variance\n% V of the SV in the local mean.\n\n%% Initialize\noffset_c=priorValues.offset_c;\n\np = find(isnan(Psi(:,1)),1,'last');\n[T,M] = size(Psi);\n% Ppsi=dataValues.Ppsi;\n \n% obtain prior data\nstartMeanVector=priorValues.mean_ln_v0;\nstartVarVector=priorValues.var_ln_v0;\n\npriorPhi_V=priorValues.phi_v;\npriorD_V  =priorValues.d_v;\n \n%% Prepare Sampling\n\nVvars=zeros(T,M);\nphi_Vdraw=zeros(M,1);\n\n% construct VvarsOld\n% VvarsOld=zeros(T,M);\n% \n% for i=1:M\n%     VvarsOld(:,i)=reshape(Vold(i,i,:),T,1,1); \n% end\n\n%% Sample Vvars\nfor i=1:M\n    \n    % prepare for each i\n        zEntry=p+1;\n        \n        PsiDiff=Psi(zEntry+1:T,i)-Psi(zEntry:T-1,i);\n        \n        residsTemp=PsiDiff;\n        yStar=log(residsTemp.^2+offset_c);\n        phi=phi_V(i);\n        lnSigma2=log(Vold(zEntry+1:T,i)); % note log => h = ln sigma2\n    \n        startMean=startMeanVector(i);\n        startVar=startVarVector(i);\n\n        % sample states\n        [yStarAdj, Ht] = bear.statesMix(yStar,lnSigma2);\n    \n        % sample log variances\n        [logVarsDraw_Vi]=bear.KF_CKsimSV(yStarAdj,Ht,phi,startMean,startVar);\n        Vvars(:,i)=[0.00000001*ones(zEntry,1) ;exp(logVarsDraw_Vi)];\n    \n        % sample phi\n        [phiDraw_Vi]=bear.samplePhi(logVarsDraw_Vi,priorD_V,priorPhi_V);\n        phi_Vdraw(i)=phiDraw_Vi; \n   \nend\n    \n\n%% Construct V\n% Vdraw=zeros(M,M,T);\n% \n% for i=1:M\n%     Vdraw(i,:)=Vvars(:,i);\n% end\nVdraw=Vvars;\nend\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/sampleV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.575415857681852}}
{"text": "% Test file for trigtech/circconv\n\nfunction pass = test_circconv(pref)\n\n% Get preferences.\nif ( nargin < 1 )\n    pref = trigtech.techPref();\nend\n\ntestclass = trigtech();\n\n% Generate a random point to use as test values.\nseedRNG(6178);\nx = 2 * rand - 1;\n\n%%\n% Check operation in the face of empty arguments.\n\nf = testclass.make();\ng = testclass.make(@(x) sin(pi*x), [], pref);\npass(1) = (isempty(circconv(f,g)) && isempty(circconv(g,f)));\n\n%%\n% Simple checks\n\nf_op = @(x) tanh(5*cos(pi*(x)));\ng_op = @(x) ones(size(x));\nf = testclass.make(f_op, [], pref);\ng = testclass.make(g_op, [], pref);\n\nhfg = circconv(f,g);\nhgf = circconv(g,f);\n% Answer should be zero since the functions are odd.\napprox_fg = feval(hfg,x);\napprox_gf = feval(hgf,x);\nexpected = 0;\nerr = abs(approx_fg - expected);\ntol = 1e2*eps;\npass(2) = err < tol;\n\nf_op = @(x) tanh(cos(pi*(x)));\na = x;\nfa_op = @(x) tanh(cos(pi*(x-a)));\n\n% Harder tests\nf = testclass.make(f_op, [], pref);\ng = circconv(f,f);\n\n% Computed answer at zero:\napprox = feval(g,0);\n% Expected answer:\nexpected = sum(f.*f);\nerr = abs(approx - expected);\ntol = 1e2*eps*vscale(g);\npass(3) = err < tol;\n\n% Computed answer at x:\napprox = feval(g,x);\n% Expected answer:\nh = testclass.make(fa_op, [], pref);\nexpected = sum(f.*h);\nerr = abs(approx - expected);\ntol = 1e2*eps*vscale(g);\npass(4) = err < tol;\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/trigtech/test_circconv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5754158552098826}}
{"text": "function [K, Kbase, n2]  = gaussianKernCompute(kern, x, x2)\n\n% GAUSSIANKERNCOMPUTE Compute the Gaussian kernel given the parameters and X.\n% FORMAT\n% DESC computes the kernel parameters for the Gaussian kernel given\n% inputs associated with rows and columns.\n% RETURN K : the kernel matrix computed at the given points.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG X : the input matrix associated with the rows of the kernel.\n% ARG X2 : the input matrix associated with the columns of the kernel.\n%\n% FORMAT\n% DESC computes the kernel matrix for the Gaussian kernel given a design matrix of inputs.\n% RETURN K : the kernel matrix computed at the given points.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x : input data matrix in the form of a design matrix.\n%\t\n% SEEALSO : gaussianKernParamInit, kernCompute, kernCreate, gaussianKernDiagCompute\n% \n% COPYRIGHT : Mauricio Alvarez and Neil D. Lawrence, 2008\n%\n% MODIFICATIONS: Mauricio Alvarez, 2009\n\n% KERN\n\nif kern.isArd\n    sqrtP = sqrt(kern.precisionU);\n    sqrtPx = x*sparseDiag(sqrtP);\n    if nargin < 3\n        n2 = dist2(sqrtPx, sqrtPx);        \n    else\n        sqrtPx2 = x2*sparseDiag(sqrtP);\n        n2 = dist2(sqrtPx, sqrtPx2);        \n    end\n    Kbase = exp(-0.5*n2);    \nelse\n    if nargin < 3\n        n2 = dist2(x, x);        \n    else        \n        n2 = dist2(x, x2);        \n    end\n    Kbase = exp(-0.5*kern.precisionU*n2);    \nend\nK = kern.sigma2Latent*Kbase;    \n\n\n\n\n\n\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/gaussianKernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5753789016177631}}
{"text": "function X = normrow(X)\nif nargin < 1\n    error('Not enough input arguments.'); end\n\nC = size(X,2);\nif C == 1\n    X = X ./ abs(X);\nelse\n    X = sqrt(ones./(sum(X.*X,2)'))'*ones(1,C).*X;\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/normrow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5753788902360258}}
{"text": "function [ceq,ceqJac] = autoGen_cst_steplength(q1m,q2m,q4m,q5m,l1,l2,l4,l5,stepLength)\n%AUTOGEN_CST_STEPLENGTH\n%    [CEQ,CEQJAC] = AUTOGEN_CST_STEPLENGTH(Q1M,Q2M,Q4M,Q5M,L1,L2,L4,L5,STEPLENGTH)\n\n%    This function was generated by the Symbolic Math Toolbox version 6.2.\n%    22-Oct-2015 19:14:35\n\nt2 = cos(q1m);\nt3 = l1.*t2;\nt4 = cos(q2m);\nt5 = l2.*t4;\nt6 = cos(q4m);\nt7 = cos(q5m);\nt8 = sin(q1m);\nt9 = sin(q2m);\nt10 = sin(q4m);\nt11 = l4.*t10;\nt12 = sin(q5m);\nt13 = l5.*t12;\nceq = [-stepLength+t11+t13-l1.*t8-l2.*t9;t3+t5-l4.*t6-l5.*t7];\nif nargout > 1\n    ceqJac = reshape([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-t3,-l1.*t8,-t5,-l2.*t9,0.0,0.0,l4.*t6,t11,l5.*t7,t13,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],[2, 22]);\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_cst_steplength.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5753788864824972}}
{"text": "function test26\n%TEST26 test cs_dmsol and cs_dmspy\n%\n% Example:\n%   test26\n% See also: testall\n\n%   Copyright 2006-2007, Timothy A. Davis.\n%   http://www.cise.ufl.edu/research/sparse\n\n\nclear functions\n\nrandn ('state', 0) ;\nrand ('state', 0) ;\n\nclf\n\nntrials = 1000 ;\ne1 = zeros (ntrials,1) ;\ne2 = zeros (ntrials,1) ;\n\nfor trials = 1:ntrials\n\n    m = fix (100 * rand (1)) ;\n    n = fix (100 * rand (1)) ;\n    % d = 0.1 * rand (1) ;\n    d = rand (1) * 4 * max (m,n) / max (m*n,1) ;\n    A = sprandn (m,n,d) ;\n    % S = sprandn (m,m,d) + speye (m) ;\n\n    if (~ispc)\n        if (rand ( ) > .5)\n            A = A + 1i * sprand (A) ;\n        end\n    end\n\n    subplot (1,3,2) ; spy (A) ;\n    subplot (1,3,3) ; cs_dmspy (A) ;\n\n    b = rand (m,1) ;\n\n    if (~ispc)\n        if (rand ( ) > .5)\n            b = b + 1i * rand (size (b)) ;\n        end\n    end\n    % MATLAB cannot do A\\b when A is sparse and rectangular and either\n    % A or b are complex\n    if (m ~= n & isreal (A) & ~isreal (b))                                  %#ok\n        x1 = (A\\real(b)) + 1i * (A\\imag(b)) ;\n        err1 = norm (A*x1-b) ;\n    elseif ((m ~= n) & ~isreal (A))                                         %#ok\n        err1 = 1 ;\n    else\n        x1 = A\\b ;\n        err1 = norm (A*x1-b) ;\n    end\n\n    x2 = cs_dmsol (A,b) ; \n\n    err2 = norm (A*x2-b) ;\n\n    lerr1 = log10 (max (err1, eps)) ;\n    lerr2 = log10 (max (err2, eps)) ;\n\n    fprintf ('rank: %3d %3d err %6.2e  %6.2e  :   %6.1f\\n', ...\n        sprank(A), rank(full(A)), err1, err2, lerr1 - lerr2) ;\n\n    if (isnan (err1))\n        lerr1 = 10 ;\n    end\n    if (isnan (err2))\n        lerr2 = 10 ;\n    end\n\n    if (lerr2 > lerr1 + 5)\n        % pause\n    end\n\n    e1 (trials) = lerr1 ;\n    e2 (trials) = lerr2 ;\n\n    subplot (1,3,1) ; plot (e1, e2, 'o', [-16 10], [-16 10], 'r') ;\n    xlabel ('MATLAB error') ;\n    ylabel ('dmsol error') ;\n\n\n    drawnow\n    % pause\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_newfiles/MATLAB/Test/test26.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5753727780570977}}
{"text": "function [ p, t ] = cvt_square_uniform ( n, sample_num, delaunay_display )\n\n%*****************************************************************************80\n%\n%% CVT_SQUARE_UNIFORM demonstrates how a CVT can be computed and displayed in MATLAB.\n%\n%  Discussion:\n%\n%    This simple example carries out an iterative CVT calculation in the \n%    unit square, with a uniform density.  The initial placement of the\n%    generators is random.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 May 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Qiang Du, Vance Faber, Max Gunzburger,\n%    Centroidal Voronoi Tessellations: Applications and Algorithms,\n%    SIAM Review, \n%    Volume 41, 1999, pages 637-676.\n%\n%  Parameters:\n%\n%    Input, integer N, the number of generators.\n%\n%    Input, integer SAMPLE_NUM, the number of sample points.\n%\n%    Input, logical DELAUNAY_DISPLAY, is TRUE (nonzero) if the Delaunay\n%    triangulation is to be displayed.\n%\n%    Output, real P(N,2), the location of the generators.\n%\n%    Output, integer T(NT,3), information defining the Delaunay\n%    triangulation of the generators.  NT is the number of triangles,\n%    which varies depending on the arrangement of the generators.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CVT_SQUARE_UNIFORM:\\n' );\n  fprintf ( 1, '  A simple demonstration of a CVT computation\\n' );\n  fprintf ( 1, '  (Centroidal Voronoi Tessellation)\\n' );\n  fprintf ( 1, '  in a square, with a uniform density.\\n' );\n  \n  if ( nargin < 1 )\n    n = 100;\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'CVT_SQUARE_UNIFORM - Note:\\n' );\n    fprintf ( 1, '  No value of N was supplied.\\n' );\n    fprintf ( 1, '  N is the number of generators.\\n' );\n    fprintf ( 1, '  A default value N = %d will be used.\\n', n );\n  else\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  User specified number of generators = %d\\n',  n );\n  end\n\n  if ( nargin < 2 )\n    sample_num = 1000 * n;\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'CVT_SQUARE_UNIFORM - Note:\\n' );\n    fprintf ( 1, '  No value of SAMPLE_NUM was supplied.\\n' );\n    fprintf ( 1, '  SAMPLE_NUM is the number of sample points.\\n' );\n    fprintf ( 1, '  A default value SAMPLE_NUM = %d will be used.\\n', ...\n      sample_num );\n  else\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  User specified number of sample points = %d\\n', ...\n      sample_num );\n  end\n\n  if ( nargin < 3 )\n    delaunay_display = 0;\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'CVT_SQUARE_UNIFORM - Note:\\n' );\n    fprintf ( 1, '  No value of DELAUNAY_DISPLAY was supplied.\\n' );\n    fprintf ( 1, '  DELAUNAY_DISPLAY is TRUE (nonzero) if the\\n' );\n    fprintf ( 1, '  Delaunay triangulation is also to be displayed.\\n' );\n    fprintf ( 1, '  A default value DELAUNAY_DISPLAY = %d will be used.\\n', ...\n      delaunay_display );\n  else\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  User specified DELAUNAY_DISPLAY = %d\\n', ...\n      delaunay_display );\n  end\n%\n%  This switch is set to 1 (TRUE) if the ACCUMARRAY command is available.\n%  That speeds up the calculation a lot.  If you don't have the ACCUMARRAY\n%  command, just set this to 0.\n% \n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CVT_SQUARE_UNIFORM:\\n' );\n  fprintf ( 1, '  MATLAB''s ACCUMARRAY command can be used for faster\\n' );\n  fprintf ( 1, '  computation.  This command is not available in\\n' );\n  fprintf ( 1, '  some versions of MATLAB.  If ACCUMARRAY is available,\\n' );\n  fprintf ( 1, '  simply make sure that the ACCUMARAY_AVAILABLE variable\\n' );\n  fprintf ( 1, '  is set to 1!\\n' );\n  \n  accumarray_available = 1;\n\n  if ( accumarray_available )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  The ACCUMARRAY command will be used.\\n' );\n  else\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  The ACCUMARRAY command will NOT be used.\\n' );\n  end\n%\n%  Clear the figure screen, if already open.\n%\n  clf\n%\n%  Randomize the initial locations of the generators in the unit square.\n%  If another region is used, then this initialization should be changed.\n%\n  p = rand ( n, 2 );\n  plot ( p(:,1), p(:,2), 'b.' );\n  axis ( [ 0.0, 1.0, 0.0, 1.0 ] )\n  line ( [ 0.0, 1.0, 1.0, 0.0, 0.0 ], [ 0.0, 0.0, 1.0, 1.0, 0.0 ], ...\n    'Color', 'r', 'LineWidth', 2 );\n  title_string = sprintf ( 'Initial Generators' );\n  title ( title_string );\n  axis equal\n  drawnow\n\n  string = input ( 'RETURN, or Q to quit: ', 's' );\n\n  if ( string == 'q' | string == 'Q' )\n    return\n  end\n\n  it = 0;\n  \n  while ( 1 )\n%\n%  Compute the Delaunay triangle information T for the current nodes.\n%\n    t = delaunay ( p(:,1), p(:,2) );\n%\n%  Display the Delaunay triangulation, if requested.\n%\n    if ( delaunay_display )\n      subplot ( 1, 2, 2 )\n      trimesh ( t, p(:,1), p(:,2), zeros(n,1), 'EdgeColor', 'b' )\n      hold on\n      plot ( p(:,1), p(:,2), 'b.' );\n      axis ( [ -0.0, 1.0, -0.0, 1.0 ] )\n      line ( [ 0.0, 1.0, 1.0, 0.0, 0.0 ], [ 0.0, 0.0, 1.0, 1.0, 0.0 ], ...\n        'Color', 'r', 'LineWidth', 2 );\n      title_string = sprintf ( 'Delaunay, step %d', it );\n      title ( title_string );\n      axis equal\n      view ( 2 )\n      hold off\n    end\n%\n%  Display the CVT generators, and the associated Voronoi diagram.\n%\n    if ( delaunay_display )\n      subplot ( 1, 2, 1 )\n    end\n    \n    voronoi ( p(:,1), p(:,2), t );\n    axis ( [ -0.0, 1.0, -0.0, 1.0 ] )\n    line ( [ 0.0, 1.0, 1.0, 0.0, 0.0 ], [ 0.0, 0.0, 1.0, 1.0, 0.0 ], ...\n      'Color', 'r', 'LineWidth', 2 );\n    title_string = sprintf ( 'Voronoi, step %d', it );\n    title ( title_string );\n    axis equal\n    axis tight\n    drawnow\n%\n%  Generate sample points.  \n%\n%  These sample points implicitly define the geometry of the region.  \n%  If the region is not a unit square, then the range of the sample \n%  data must be changed.\n%\n%  The data is sampled uniformly.  If a nonuniform density is desired,\n%  then the sampling must be done in a biased way.\n%    \n    xs = rand ( sample_num, 1 );\n    ys = rand ( sample_num, 1 );\n%\n%  For each sample point, find K, the index of the nearest generator.\n%  We do this efficiently by using the Delaunay information with\n%  Matlab's DSEARCH command, rather than a brute force nearest neighbor\n%  computation.\n%  \n    k(1:sample_num,1) = dsearch ( p(:,1), p(:,2), t, xs, ys );\n%\n%  The centroid of the Voronoi region associated with each generator\n%  is approximated by the average of the sample points it was closest to.\n%\n    if ( accumarray_available )\n\n      count(1:n) = accumarray ( k, ones(sample_num,1) );\n      centroid(1,1:n) = accumarray ( k, xs );\n      centroid(2,1:n) = accumarray ( k, ys );\n\n    else\n\n      count(1:n) = 0;\n      centroid(1,1:n) = 0.0;\n      centroid(2,1:n) = 0.0;\n\n      for i = 1 : sample_num\n        j = k(i);\n        count(j) = count(j) + 1;\n        centroid(1,j) = centroid(1,j) + xs(i);\n        centroid(2,j) = centroid(2,j) + ys(i);\n      end\n\n    end\n%\n%  Replace the generators by the centroids.\n%\n    p(1:n,1) = ( centroid(1,1:n) ./ count(1:n) )';\n    p(1:n,2) = ( centroid(2,1:n) ./ count(1:n) )';\n\n    string = input ( 'RETURN, or Q to quit: ', 's' );\n\n    if ( string == 'q' | string == 'Q' )\n      break\n    end\n\n    it = it + 1;\n    \n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CVT_SQUARE_UNIFORM:\\n' );\n  fprintf ( 1, '  Normal end of execution.\\n' );\n\n  return\nend\nfunction p = square_uniform ( n )\n\n%*****************************************************************************80\n%\n%% SQUARE_UNIFORM returns sample points from the unit square.\n%\n%  Discussion:\n%\n%    This routine returns N points sampled uniformly at random\n%    from within the unit square.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    24 May 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the number of points to generate.\n%\n%    Output, real P(N,2), the sample points.\n%\n  p(1:n,1:2) = rand(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/cvt_demo/cvt_square_uniform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.5753569688849837}}
{"text": "%% Mean-Shift Video Tracking\n% by Sylvain Bernhardt\n% July 2008\n%% Description\n% Estimate the density of data samples\n% (here colour histogram) in a patch T\n% with a kernel profile k. Lmap is the\n% colormap length and H,W the patch size.\n\nfunction q = Density_estim(T,Lmap,k,H,W,graph)\nq = zeros(Lmap,1);\ncolour = linspace(1,Lmap,Lmap);\nfor x=1:W\n    for y=1:H \n        q(T(y,x)+1) = q(T(y,x)+1)+k(y,x);\n    end\nend\n\n% Normalizing\nC = 1/sum(sum(k));\nq = C.*q;\n\n% Plotting the estimated densities\nif graph==1\n    figure\n    plot(colour,q);\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/35520-mean-shift-video-tracking/MeanShift_Code/Density_estim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5753569673722991}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   demo script for mesh generation from binary volumetric image\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% preparation\n% user must add the path of iso2mesh to matlab path list\n% addpath('../');\n\n% user need to add the full path to .../iso2mesh/bin directory\n% to windows/Linux/Unix PATH environment variable\n\n%% load the sample data\nload rat_head.mat\n\n% volimage is a volumetric image such as an X-ray or MRI image\n% A,b are registration matrix and vector, respectively\n%% perform mesh generation\n\n%% use the alternative 'cgalmesh' method. This will call \n% cgalmesher to process labled volume to produce surfaces\n% and tetrahedral mesh in a single run.\nclear opt\nopt.radbound=2;\n[node,elem,face]=v2m(uint8(volimage),0.5,opt,100,'cgalmesh');\n\n\n%% visualize the resulting mesh\n\nplotmesh(node,face(:,1:3));\naxis equal;\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_vol2mesh_ex1c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5753569673722991}}
{"text": "%Test weka's Naive Bayes implementation on the iris data. \n\nload fisheriris;    %built in to matlab\n\n%Shuffle the data\nrand('twister',0);\nperm = randperm(150);\nmeas = meas(perm,:);\nspecies = species(perm,:);\n\nfeatureNames = {'sepallength','sepalwidth','petallength','petalwidth','class'};\n\n%Prepare test and training sets. \ndata = [num2cell(meas),species];\ntrain = data(1:120  ,:);\ntest  = data(121:end,:);\n\nclassindex = 5;\n\n%Convert to weka format\ntrain = matlab2weka('iris-train',featureNames,train,classindex);\ntest =  matlab2weka('iris-test',featureNames,test);\n\n%Train the classifier\nnb = trainWekaClassifier(train,'bayes.NaiveBayes');\n\n%Test the classifier\npredicted = wekaClassify(test,nb);\n\n%The actual class labels (i.e. indices thereof)\nactual = test.attributeToDoubleArray(classindex-1); %java indexes from 0\n\nerrorRate = sum(actual ~= predicted)/30\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/21204-matlab-weka-interface/wekaNBexample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5753569659136154}}
{"text": "clear;\nnoOfNodes  = 100;\n%rand('state', 0);\nplot_flag = 1;\nif plot_flag==1\n    figure(1);\n    clf;\n    hold on;\nend\nL = 1000; % size of the whole area\nR = 300; % maximum range;\n\ns = 1; % source id\nd = 10; % destination id\n\nnetXloc = double(rand(1,noOfNodes)*L);\nnetYloc = double(rand(1,noOfNodes)*L);\n%netXloc = [0 1 0 1];\n%netYloc = [0 0 1 1];\nAstar_connect = zeros(noOfNodes, noOfNodes);\nAstar_coord = zeros(noOfNodes, 2);\nfor i = 1:noOfNodes\n    if plot_flag==1\n        plot(netXloc(i), netYloc(i), '.');\n    end\n    Astar_coord(i,1) = netXloc(i);\n    Astar_coord(i,2) = netYloc(i);\n    if plot_flag == 1\n        %text(netXloc(i), netYloc(i), num2str(i));\n    end\n    for j = 1:noOfNodes\n        distance = sqrt((netXloc(i) - netXloc(j))^2 + (netYloc(i) - netYloc(j))^2);\n        if distance <= R\n            matrix(i, j) = distance;   % if set to '1', Dijkstra computes Spath in terms of hops; if set to 'distance', it is the real shortest path\n            if i~=j % must be satisfied\n                Astar_connect(i, j) = 1;\n            else\n                Astar_connect(i, j) = 0;\n            end\n            if plot_flag==1\n                %line([netXloc(i) netXloc(j)], [netYloc(i) netYloc(j)], 'LineStyle', ':');\n            end\n        else\n            matrix(i, j) = inf;\n            Astar_connect(i, j) = 0;\n        end;\n    end;\nend;\n\n\nactiveNodes = [];\nfor i = 1:noOfNodes,\n    % initialize the farthest node to be itself;\n    farthestPreviousHop(i) = i;     % used to compute the RTS/CTS range;\n    farthestNextHop(i) = i;\nend;\n\nAstar_coord;\nAstar_connect;\n\n[path, totalCost, farthestPreviousHop, farthestNextHop] = dijkstra(noOfNodes, matrix, s, d, farthestPreviousHop, farthestNextHop);\ncombo = [noOfNodes s-1 d-1 R/2];\n[Astar_path, Astar_search] = Astar(Astar_coord', Astar_connect, combo); % notice, we must put Astar_coord' rather than Astar_coord\npath\ntotalCost\nAstar_path\nAstar_search\nif length(path) ~= 0\n    for i = 1:(length(path)-1)\n        if plot_flag==1\n            line([netXloc(path(i)) netXloc(path(i+1))], [netYloc(path(i)) netYloc(path(i+1))], 'Color','g','LineWidth', 2.50, 'LineStyle', '-.');\n            text(netXloc(i), netYloc(i), num2str(i));\n        end    \n    end;\nend;\n\nif length(Astar_path) ~= 0\n    for i = 1:(length(Astar_path)-1)\n        if plot_flag==1\n            line([netXloc(Astar_path(i)) netXloc(Astar_path(i+1))], [netYloc(Astar_path(i)) netYloc(Astar_path(i+1))], 'Color','r','LineWidth', 2.50, 'LineStyle', '-.');\n            text(netXloc(i), netYloc(i), num2str(i));\n        end    \n    end;\nend;\nif plot_flag == 1\n    hold off;\nend\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/8288-a-star-search-algorithm/Spath_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.6959583250334527, "lm_q1q2_score": 0.575356961429563}}
{"text": "function [ fea, out ] = ex_planestress2( varargin )\n%EX_PLANESTRESS2 NAFEMS benchmark challenge 1 plane stress example.\n%\n%   [ FEA, OUT ] = EX_PLANESTRESS2( VARARGIN ) NAFEMS benchmark example to calculate von Mieses stress\n%   thin plate under plane stress assumption with loads all around.\n%\n%   Accepts the following property/value pairs.\n%\n%       Input       Value/{Default}        Description\n%       -----------------------------------------------------------------------------------\n%       E           scalar {210e9}         Modulus of elasticity\n%       nu          scalar {0.3}           Poissons ratio\n%       igrid       scalar 1/{0}           Cell type (0=quadrilaterals, 1=triangles)\n%       hmax        scalar {1/20}          Max grid cell size\n%       sfun        string {sflag1}        Shape function for displacements\n%       iplot       scalar 0/{1}           Plot solution (=1)\n%                                                                                         .\n%       Output      Value/(Size)           Description\n%       -----------------------------------------------------------------------------------\n%       fea         struct                 Problem definition struct\n%       out         struct                 Output struct\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { ...\n  'E',        210e9; ...\n  'nu',       0.3; ...\n  'igrid',    0; ...\n  'hmax',     1/20; ...\n  'sfun',     'sflag1'; ...\n  'iplot',    1; ...\n  'fid',      1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid       = opt.fid;\n\n\n% Geometry definition.\ngobj1 = gobj_rectangle( 0, 1, 0, 1, 'R1' );\nfea.geom.objects = { gobj1 };\nfea.sdim = { 'x' 'y' };\n\n\n% Grid generation.\nif( opt.igrid==1 )\n  fea.grid = gridgen(fea,'hmax',opt.hmax,'fid',fid);\nelse\n  nx = 1/opt.hmax;\n  fea.grid = rectgrid( nx, nx );\nend\n\n% Boundary conditions.\ndtol = 0.1;\nif( opt.igrid==1 )\n  lbdr = findbdr( fea, ['x<',num2str(dtol)] );     % Left boundary number.\n  rbdr = findbdr( fea, ['x>',num2str(1-dtol)] );   % Right boundary number.\n  tbdr = findbdr( fea, ['y>',num2str(1-dtol)] );   % Top boundary number.\n  bbdr = findbdr( fea, ['y<',num2str(dtol)] );     % Bottom boundary number.\nelse\n  lbdr = 4;\n  rbdr = 2;\n  tbdr = 3;\n  bbdr = 1;\nend\n\n\n% Add plane stress physics mode.\nfea = addphys(fea,@planestress);\nfea.phys.pss.eqn.coef{1,end} = { opt.nu };\nfea.phys.pss.eqn.coef{2,end} = { opt.E  };\nfea.phys.pss.sfun            = { opt.sfun opt.sfun };\n\n% Set boundary condition types.\nbctype = mat2cell( zeros(2,4), [1 1], [1 1 1 1] );\nfea.phys.pss.bdr.coef{1,5}   = bctype;\n\n% Set loads on boundary.\nbccoef = mat2cell( zeros(2,4), [1 1], [1 1 1 1] );\nbccoef{1,tbdr} = '-x';\nbccoef{2,tbdr} = 'x';\nbccoef{1,bbdr} = '-(1-x)';\nbccoef{2,bbdr} = '1-x';\nbccoef{1,lbdr} = '1-y';\nbccoef{2,lbdr} = '-(1-y)';\nbccoef{1,rbdr} = 'y';\nbccoef{2,rbdr} = '-y';\nfea.phys.pss.bdr.coef{1,end} = bccoef;\n\n\n% Parse and solve problem.\nfea       = parsephys(fea);             % Check and parse physics modes.\nfea       = parseprob(fea);             % Check and parse problem struct.\nfea.sol.u = solvestat(fea,'fid',fid);   % Call to stationary solver.\n\n\n% Postprocessing.\ns_vm = fea.phys.pss.eqn.vars{1,2};\nif ( opt.iplot>0 )\n  figure\n  postplot( fea, 'surfexpr', s_vm, 'isoexpr', s_vm )\n  title('von Mieses stress')\nend\n\n% Error checking.\ndtol = sqrt(eps);\nsm  = evalexpr( s_vm, [0.5;0.5], fea );\ns01 = evalexpr( s_vm, [dtol;1],    fea );\ns10 = evalexpr( s_vm, [1;dtol],    fea );\ns00 = evalexpr( s_vm, [dtol;dtol], fea );\ns11 = evalexpr( s_vm, [1;1],       fea );\n\nsol = [ sm s01 s10 s00 s11 ];\nref = [  0   0   0   2   2 ];\nout.err    = norm(sol-ref)/norm(ref);\nout.pass   = out.err < 0.1;\n\n\nif ( nargout==0 )\n  clear fea out\nend\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/examples/ex_planestress2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5753569614295629}}
{"text": "function n=grid2n(i,j,Nj)\nn=i+(j-1)*Nj;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25562-boggle/boggle/grid2n.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5753569547574842}}
{"text": "function [error_x,error_y] = stokespost_q1q1_bc(aez,fezx,fezy,elerrorx,elerrory,xy,ev,ebound)\n%stokespost_q1q1_bc   postprocesses Poisson error estimator \n%   [error_x,error_y] = stokespost_q1q1_bc(aez,fezx,fezy,elerrorx,elerrory,xy,ev,ebound);\n%   input\n%          aez                  elementwise Poisson problem matrices\n%          fezx,fezy            elementwise rhs vectors\n%          elerrorx, elerrory   elementwise error estimate (without BC imposition) \n%          xy                   vertex coordinate vector  \n%          ev                   element mapping matrix\n%          ebound               element edge boundary matrix \n%   output\n%          error_x, error_y     component elementwise error estimate\n%\n%   calls function localbc_xy\n%   IFISS function: DJS; 8 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n      x=xy(:,1); y=xy(:,2);\n      nel=length(ev(:,1));\n      lev=[ev,ev(:,1)]; \n\t  error_x=elerrorx;  error_y=elerrory;\n%\n% recompute contributions from elements with Dirichlet boundaries\n      nbde=length(ebound(:,1));\n      ebdy = zeros(nel,1);\n      edge = zeros(nel,1);\n% isolate boundary elements\n      for el = 1:nbde\n      ee = ebound(el,1);\n      ebdy(ee) = ebdy(ee)+1; edge(ee)=ebound(el,2);\n      end  \n%\n% two edge elements\n      k2=find(ebdy==2);\n      nel2b=length(k2);\n% loop over two edge elements\n      for el = 1:nel2b\n      el2e=k2(el);\n      kk=find(ebound(:,1) == el2e);\n      edges=ebound(kk,2);\n% set up original matrix and RHS vector\n\t  ae=squeeze(aez(el2e,1:5,1:5)); \n      fex=fezx(el2e,:)'; fey=fezy(el2e,:)';\n% set up local coordinates and impose interpolated error as Dirichlet bc\n      xl=x(lev(el2e,:)); yl=y(lev(el2e,:)); \n\t  [bae,fex,fey] = localbc_xy(ae,fex,fey,edges,xl,yl);\n% solve local problems\n      errx=bae\\fex;  erry=bae\\fey;\n\t  error_x(el2e,1) = errx'*ae*errx; error_y(el2e,1) = erry'*ae*erry;\n\t  end\n% end of element loop\n%\n% one edge elements\n      k1=find(ebdy==1);\n      nel1b=length(k1);\n% loop over one edge elements\n      for el = 1:nel1b\n      el1e=k1(el);\n      kk=find(ebound(:,1) == el1e);\n      edges=ebound(kk,2);\n% set up original matrix and RHS vector \n      fex=fezx(el1e,:)'; fey=fezy(el1e,:)';\n\t  ae=squeeze(aez(el1e,1:5,1:5)); \n% set up local coordinates and impose interpolated error as Dirichlet bc\n      xl=x(lev(el1e,:)); yl=y(lev(el1e,:));\n\t  [bae,fex,fey] = localbc_xy(ae,fex,fey,edges,xl,yl);\n% solve local problems\n      errx=bae\\fex;  erry=bae\\fey;\n\t  error_x(el1e,1) = errx'*ae*errx; error_y(el1e,1) = erry'*ae*erry;\n\n      end\n% end of element loop\n%\n      err_x = sqrt(sum(error_x)); error_x = sqrt(error_x);\n\t  err_y = sqrt(sum(error_y)); error_y = sqrt(error_y);\n      fprintf('estimated velocity error (in energy):  (%10.6e,%10.6e) \\n',err_x,err_y)   \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/stokes_flow/stokespost_q1q1_bc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6959583250334527, "lm_q1q2_score": 0.5753569495440899}}
{"text": "function [x_sil, y_sil] = removeSilentFrames(x, y, range, N, K)\n\nx       = x(:);\ny       = y(:);\n\nframes  = 1:K:(length(x)-N);\nw       = ml_hanning(N);\nmsk     = zeros(size(frames));\n\nfor j = 1:length(frames)\n    jj      = frames(j):(frames(j)+N-1);\n    msk(j) \t= 20*log10(norm(x(jj).*w)./sqrt(N));\nend\n\nmsk     = (msk-max(msk)+range)>0;\ncount   = 1;\n\nx_sil   = zeros(size(x));\ny_sil   = zeros(size(y));\n\nfor j = 1:length(frames)\n    if msk(j)\n        jj_i            = frames(j):(frames(j)+N-1);\n        jj_o            = frames(count):(frames(count)+N-1);\n        x_sil(jj_o)     = x_sil(jj_o) + x(jj_i).*w;\n        y_sil(jj_o)  \t= y_sil(jj_o) + y(jj_i).*w;\n        count           = count+1;\n    end\nend\n\nx_sil = x_sil(1:jj_o(end));\ny_sil = y_sil(1:jj_o(end));\n", "meta": {"author": "mpariente", "repo": "pystoi", "sha": "9ff1cfa743d59b50f1bd35c21c2e8686de6ac026", "save_path": "github-repos/MATLAB/mpariente-pystoi", "path": "github-repos/MATLAB/mpariente-pystoi/pystoi-9ff1cfa743d59b50f1bd35c21c2e8686de6ac026/tests/octave/removeSilentFrames.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5753569391173007}}
{"text": "function[z]=celldiv(x,y)\n%CELLDIV  Division acting on each element in a cell array.\n%\n%   Z=CELLDIV(X,Y) where X and Y are both cell arrays of N arrays, with the\n%   corresponding elements in X and in Y having the same size, returns the\n%   cell array Z containing their ratios, \n%\n%       Z{1}=Y{1}./X{1}, Z{2}=Y{2}./X{2},..., Z{N}=Y{N}./X{N}.\n%\n%   One of X or Y may also be a scalar or a numeric array of the same \n%   length as the other input argument.\n%\n%   Usage: z=celldiv(x,y);\n%   __________________________________________________________________\n%   This is part of JLAB --- type 'help jlab' for more information\n%   (C) 2015--2019 J.M. Lilly --- type 'help jlab_license' for details\n\nif ~iscell(x)&&iscell(y)\n    z=y;\n    if length(x)==1\n        x=x.*ones(length(y),1);\n    end\n    if length(x)==length(y)\n        for i=1:length(x)\n            z{i}=y{i}./x(i);\n        end\n    else \n        error('LENGTH(X) and LENGTH(Y) must be the same.')\n    end\nelseif iscell(x)&&~iscell(y)\n    z=x;\n    if length(y)==1\n        y=y.*ones(length(x),1);\n    end\n    if length(x)==length(y)\n        for i=1:length(x)\n            z{i}=y(i)./x{i};\n        end\n    else \n        error('LENGTH(X) and LENGTH(Y) must be the same.')\n    end\nelseif iscell(x)&&iscell(y)\n    z=y;\n    for i=1:length(x)\n        z{i}=y{i}./x{i};\n    end\nend\n\n ", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jCell/celldiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5753374320399282}}
{"text": "function wishart_test04 ( )\n\n%*****************************************************************************80\n%\n%% WISHART_TEST04 demonstrates the Wishart sampling function.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 July 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n\n%\n%  Access the PDFLIB and RNGLIB libraries.\n%\n  addpath ( '../pdflib' );\n  addpath ( '../rnglib' );\n%\n%  Initialize the RNGLIB library.\n%\n  initialize ( );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'WISHART_TEST04:\\n' );\n  fprintf ( 1, '  We can compute sample Wishart matrices by:\\n' );\n  fprintf ( 1, '    W = wishart_sample ( n, df, sigma );\\n' );\n%\n%  Set the parameters and call.\n%\n  n = 5;\n  df = 8;\n  sigma = eye ( 5, 5 );\n  w = wishart_sample ( n, df, sigma );\n  r8mat_print ( n, n, w, '  wishart_sample ( 5, 8, Identity ):' );\n%\n%  Calling again yields a new matrix.\n%\n  w = wishart_sample ( n, df, sigma );\n  r8mat_print ( n, n, w, '  wishart_sample ( 5, 8, Identity ):' );\n%\n%  Try a diagonal matrix.\n%\n  sigma = diag ( [1.0, 2.0, 3.0, 4.0, 5.0 ] );\n  w = wishart_sample ( n, df, sigma );\n  r8mat_print ( n, n, w, '  wishart_sample ( 5, 8, diag(1,2,3,4,5) ):' );\n%\n%  Try a smaller matrix.  Sigma must be positive definite symmetric.\n%\n  n = 3;\n  df = 3;\n  r = [ 5.0, 1.0, 3.0; ...\n        0.0, 4.0, 2.0; ...\n        0.0, 0.0, 6.0 ];\n  sigma = r' * r;\n  r8mat_print ( n, n, sigma, '  Set covariance SIGMA:' );\n  w = wishart_sample ( n, df, sigma );\n  r8mat_print ( n, n, w, '  wishart_sample ( 3, 3, sigma ):' );\n%\n%  What is the eigendecomposition of this matrix?\n%\n  [ v, lambda ] = eigs ( w );\n  r8mat_print ( n, n, v, '  Eigenvectors of previous matrix:' );\n  r8mat_print ( n, n, lambda, '  Eigenvalues of previous matrix:' );\n\n  rmpath ( '../pdflib' );\n  rmpath ( '../rnglib' );\n\n  return\nend\n", "meta": {"author": "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/wishart_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.575337425039489}}
{"text": "function p00_start_test ( problem_num )\n\n%*****************************************************************************80\n%\n%% P00_START_TEST prints the norm of the starting point and its function value.\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, integer PROBLEM_NUM, the number of problems.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'P00_START_TEST\\n' );\n  fprintf ( 1, '  Get norms of starting point X0 and F(X0)\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '   Problem    Option        ||X0||          ||F(X0)||\\n' );\n  fprintf ( 1, '\\n' );\n\n  for problem = 1 : problem_num\n\n    option_num = p00_option_num ( problem );\n\n    fprintf ( 1, '\\n' );\n\n    for option = 1 : option_num\n\n      nvar = p00_nvar ( problem, option );\n\n      x0 = p00_start ( problem, option, nvar );\n\n      x0_norm = norm ( x0(1:nvar) );\n\n      fx0 = p00_fun ( problem, option, nvar, x0 );\n\n      fx0_norm = norm ( fx0(1:nvar-1) );\n\n      fprintf ( 1, '  %8d  %8d  %14f  %14f\\n', ...\n        problem, option, x0_norm, fx0_norm )\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_con/p00_start_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5753374212209853}}
{"text": "function [ m, d ] = mothers_day ( y )\n\n%*****************************************************************************80\n%\n%% MOTHERS_DAY computes the date of Mother's Day (US) for a Common year.\n%\n%  Discussion:\n%\n%    Mother's Day occurs on the second Sunday in May.\n%\n%  Example:\n%\n%    Input:\n%\n%      Y = 2003\n%\n%    Output:\n%\n%      M = 5\n%      D = 11\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%  Parameters:\n%\n%    Input, integer Y, the year.\n%\n%    Output, integer M, D, the month and day of Mother's Day.\n%\n\n%\n%  Determine the day of the week for 8 May, the earliest day\n%  that Mother's day can occur.\n%\n  m = 5;\n  d = 8;\n  f = 0.0;\n\n  w = ymdf_to_weekday_common ( y, m, d, f );\n%\n%  W = 1 means this day is Sunday, and day D is Mother's day.\n%  Otherwise, figure out how to increment W to 8 (Sunday again);\n%  The same increment makes D the correct day number.\n%\n  if ( w ~= 1 )\n    d = d + 8 - w;\n  end\n\n  return\nend\n", "meta": {"author": "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/mothers_day.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.5753374212209852}}
{"text": "function [Sf,AI,AIrows,AIcols] = imageStats1(f)\n%imageStats1 Sample function used in Chapter 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\nSf = size(f);\nAI = mean2(f);\nAIrows = mean(f,2);\nAIcols = mean(f,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/sampleFunctions/imageStats1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5753374199478486}}
{"text": "function test_stepsize_alg_demo()\n% demonstration file for original stepsize algorithm.\n%\n% This file illustrates how to set user's own stepsize algorithm in case of linear\n% regression problem. This demonstrates SGD and SVRG algorithms.\n%\n% This file is part of SGDLibrary.\n%\n% Created by H.Kasai on Sep. 25, 2017\n\n\n    clc;\n    clear;\n    close all;\n\n    %% generate synthetic data        \n    % set number of dimensions\n    d = 10;\n    % set number of samples    \n    n = 1000;\n    % generate data\n    data = logistic_regression_data_generator(n, d);\n        \n    \n    %% define problem definitions\n    problem = logistic_regression(data.x_train, data.y_train, data.x_test, data.y_test); \n    \n    \n%     %% define user-defined stepsize algorithm\n%     function step = my_stepalg(iter, options)\n%         step = options.step_init / (10 + iter*0.5);\n%     end       \n%     \n    \n    %% perform algorithms SGD and SVRG \n    options.w_init = data.w_init;    \n    options.step_init = 0.01;  \n    options.verbose = 2;\n    \n    options.step_alg = 'fix';\n    [w_sgd_fix, info_sgd_fix] = sgd(problem, options); \n    \n    options.step_alg = 'decay';\n    [w_sgd_decay, info_sgd_decay] = sgd(problem, options);      \n    \n    options.step_alg = 'decay-2';\n    [w_sgd_decay2, info_sgd_decay2] = sgd(problem, options);       \n    \n    options.stepsizefun = @my_stepalg;  % set my_stepalg (user-defined stepsize algorithm)\n    [w_sgd_my, info_sgd_my] = sgd(problem, options);      \n    \n    \n    %% display cost/optimality gap vs number of gradient evaluations\n    display_graph('grad_calc_count','cost', {'SGD (fix)','SGD (decay)', 'SGD (decay-2)', 'SGD (My stepsize algorithm)'}, ...\n            {w_sgd_fix, w_sgd_decay w_sgd_decay2, w_sgd_my}, {info_sgd_fix, info_sgd_decay, info_sgd_decay2, info_sgd_my});\n\nend\n\n    %% define user-defined stepsize algorithm\n    function step = my_stepalg(iter, options)\n        step = options.step_init / (10 + iter*0.5);\n    end       \n    \n\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/sgd_test/test_stepsize_alg_demo_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.5753374199478486}}
{"text": "function asa136_test01 ( )\n\n%*****************************************************************************80\n%\n%% TEST01 tries out the ASA136 routine.\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  k = 5;\n  m = 100;\n  n = 2;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST01\\n' );\n  fprintf ( 1, '  Test the KMNS algorithm.\\n' );\n  fprintf ( 1, '  Applied Statistics Algorithm 136\\n' );\n%\n%  Read the data.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Reading the data.\\n' );\n\n  input_unit = fopen ( 'points_100.txt', 'rt' );\n\n  for i = 1 : m\n    x(i,1:n) = fscanf ( input_unit, '%f', n );\n  end\n\n  fclose ( input_unit );\n%\n%  Print a few data values.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  First 5 data values:\\n' );\n  fprintf ( 1, '\\n' );\n  for i = 1 : 5\n    fprintf ( 1, '  %8d', j );\n    for j = 1 : n\n      fprintf ( 1, '  %14f', x(i,j) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n%\n%  Initialize the cluster centers.\n%  Here, we arbitrarily make the first K data points cluster centers.\n%\n  for i = 1 : k\n    for j = 1 : n\n      c(i,j) = x(i,j);\n    end\n  end\n%\n%  Compute the clusters.\n%\n  iter = 50;\n\n [ c, ic1, nc, wss, ifault ] = kmns ( x, m, n, c, k, iter );\n\n  if ( ifault ~= 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'TEST01 - Fatal error!\\n' );\n    fprintf ( 1, '  KMNS returned IFAULT = %d\\n', ifault );\n    return\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Cluster  Population  Energy\\n' );\n  fprintf ( 1, '\\n' );\n\n  for i = 1 : k\n    fprintf ( 1, '  %8d  %8d  %14f\\n', i, nc(i), wss(i) );\n  end\n\n  nc_sum = sum ( nc(1:k) );\n  wss_sum = sum ( wss(1:k) );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '     Total  %8d  %14f\\n', nc_sum, wss_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/asa136/asa136_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.5753374167659132}}
{"text": "function [index]=elementdof(node,nnel,ndof)\n%----------------------------------------------------------\n%  Purpose:\n%     Compute system dofs associated with each element \n%\n%  Synopsis:\n%     [index]=elementdof(node,nnel,ndof)\n%\n%  Variable Description:\n%     index - system dof vector associated with element \"iel\"\n%     iel - element number whose system dofs are to be determined\n%     node - nodes associated with the element \"iel\"\n%     nnel - number of nodes per element\n%     ndof - number of dofs per node \n%-----------------------------------------------------------\n \n \n   k=0;\n   for i=1:nnel\n     start = (node(i)-1)*ndof;\n       for j=1:ndof\n         k=k+1;\n         index(k)=start+j;\n       end\n   end\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/32029-plate-bending/Plate Bending/elementdof.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.5753374161293447}}
{"text": "function out = spm_series_align(job)\n% Longitudinal registration of image series\n% FORMAT out = spm_series_align(job)\n%__________________________________________________________________________\n% Copyright (C) 2012-2019 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_series_align.m 7563 2019-04-01 10:39:24Z guillaume $\n\n\nN = numel(job.vols);\ntim = job.times(:);\nif numel(tim) ~= N\n    error('Incompatible numbers of times and scans.');\nend\nif any(abs(diff(tim)) > 50)\n    error('Time differences should be in years.');\nend\n\nif numel(job.noise)==1\n    noise = repmat(job.noise,[N,1]);\nelseif numel(job.noise) ~= N\n    error('Incompatible numbers of noise estimates and scans.');\nelse\n    noise = job.noise(:);\nend\nfor i=find(~isfinite(noise(:)))'\n    % Make an estimate of the scanner noise\n    noise(i,1) = spm_noise_estimate(job.vols{i});\n    fprintf('Estimated noise sd for \"%s\" = %g\\n', job.vols{i}, noise(i,1));\nend\nprec   = noise.^(-2);\n\n\nbparam    = [0 0 job.bparam];\nwparam0   = job.wparam;\n\nmidtim = median(tim);\ntim    = tim - midtim;\nwparam = kron(wparam0,1./(abs(tim)+1/365));\nsparam = round(3*abs(tim)+2);\nNii    = nifti(strvcat(job.vols));\n\noutput = {};\nif job.write_avg, output = [output, {'wavg'}]; end\nif job.write_jac, output = [output, {'wjac'}]; end\nif job.write_div, output = [output, {'wdiv'}]; end\nif job.write_def, output = [output, {'wdef'}]; end\n\nout = spm_groupwise_ls(Nii, output, prec, wparam, bparam, sparam);\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_series_align.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.575096334428215}}
{"text": "%% Read shape\n\n[X,T] = readOff('../data/meshes/cat1.off');\nM = getMeshData(X,T,10); % compute 10 LB eigenfunctions for fun\n\n%% Design two distributions\n\nblurTime = .0001; % if this gets too small, distances get noisy\nblurSteps = 10; % was 3\n\nfrontVtx = [18962];% 15966];\nbackVtx = [22553];%26142 \n\np0 = zeros(M.numVertices,1);\nfor i=1:length(frontVtx)\n    p0(frontVtx(i)) = .5 / M.areaWeights(frontVtx(i));\nend\np0 = blurOnMesh(p0,M,blurTime,blurSteps);\nshowDescriptor(M,p0);\n\np1 = zeros(M.numVertices,1);\nfor i=1:length(backVtx)\n    p1(backVtx(i)) = .5 / M.areaWeights(backVtx(i));\nend\np1 = blurOnMesh(p1,M,blurTime,blurSteps);\nshowDescriptor(M,p1);\n\n%% Set up Gaussian blur function for barycenter\n\nblurTime = .00015; % if this gets too small, distances get noisy\nblurSteps = 10;\n\nblur = @(x) applySymmetricKernel(x,M,blurTime,blurSteps); % faster than pre-factored?\nblurTranspose = @(x) blur(x);\n\n%% Take the barycenter\n\np = [p0 p1];\np(p<1e-10) = 1e-10;\nnFunctions = 2;\n\nmaxEntropy = max(-sum(p.*log(p).*repmat(M.areaWeights,1,2),1));\n\nentropyLimits = [maxEntropy (maxEntropy+1) (maxEntropy+2) (maxEntropy+3) inf];\nnEntropies = length(entropyLimits);\n\neuclideanBarycenter = sum(p,2)/nFunctions;\nalpha = [1 1];\n\noptions = [];\noptions.niter = 100; % diminishing returns after that...\n%options.unit_area_projection = 1;\n\nbarycenter = zeros(M.numVertices,nEntropies);\nparfor i=1:length(entropyLimits)\n    barycenter(:,i) = convolutionalBarycenter(p,alpha,M.areaWeights,blur,blurTranspose,entropyLimits(i),options);\nend\n\nsave entropyTest.mat\n\n%%\n\nfor i=1:nEntropies\n    showDescriptor(M,barycenter(:,i));\nend\n\n%% Write meshes\n\nclear full\nfor i=1:nEntropies\n    e = entropyLimits(i);\n    e = full(e);\n    name = sprintf('entropy_barycenter_%g.obj',e);\n    writeTexturedObj(name, M, barycenter(:,i), 'scalar_function.mtl');\nend\n\n%% Write boundary\n\nwriteTexturedObj('p0.obj', M, p0, 'scalar_function.mtl');\nwriteTexturedObj('p1.obj', M, p1, 'scalar_function.mtl');", "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/figures/generateEntropyFigure2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346598, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5750963205912633}}
{"text": "function arx=lpcbwexp(ar,bw)\n%LPCBWEXP expand formant bandwidths of LPC filter ARX=(AR,BW)\n%minimum bandwidth will be BW*fs where fs is the sampling frequency\n%the radius of each pole will be multiplied by R=exp(-BW*pi)\n% To set the maximum pole radius to R use BW=-log(R)/PI.\n\n\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: lpcbwexp.m 713 2011-10-16 14:45:43Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[nf,p1]=size(ar);\nk=exp(-pi*(0:p1-1)*bw);\narx=ar.*k(ones(nf,1),:);\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/lpcbwexp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5750963196410218}}
{"text": "%% BernoulliParticleFilterX Demo \n% ----------------------\n% * This script demonstrates the process of configuring an running a\n%   BernoulliParticleFilterX object to perform single-target state estimation.\n%\n% * A toy single-target scenario is considered, for a target that generates\n%   regular reports of it's position with the possibility of clutter and\n%   missed detections\n%\n%% Extract the GroundTruth data from the example workspace\nload('single-target-tracking.mat');\nNumIter = size(TrueTrack.Trajectory,2);\n\n%% Models\n\nlambdaV = 5; % Expected number of clutter measurements over entire surveillance region\nV = 10^2;     % Volume of surveillance region (10x10 2D-grid)\nV_bounds = [0 10 0 10]; % [x_min x_max y_min y_max]\nP_D = 0.5; \n\n% Instantiate a Transitionamic model\ntransition_model = ConstantVelocityX('NumDims',2,'VelocityErrVariance',0.0001);\n\n% Instantiate an Observation model\nmeasurement_model = LinearGaussianX('NumMeasDims',2,'NumStateDims',4,'MeasurementErrVariance',0.02,'Mapping',[1 3]);\n\n% Instantiate a clutter model\nclutter_model = PoissonRateUniformPositionX('ClutterRate',lambdaV,'Limits',[V_bounds(1:2);V_bounds(3:4)]);\n\n% Instantiate birth model\nbirth_model = DistributionBasedBirthModelX('Distribution', UniformDistributionX([V_bounds(1:2); ...\n                                                                                [-0.1 0.1 ];...\n                                                                                V_bounds(3:4);...\n                                                                                [-0.1 0.1 ]]),...\n                                           'BirthIntensity', 0.00005);\n% Instantiate detection model                                       \ndetection_model = ConstantDetectionProbabilityX('DetectionProbability',P_D);\n                                       \n\n% Compile the State-Space model\nmodel = StateSpaceModelX(transition_model,...\n                       measurement_model,...\n                       'Clutter',clutter_model,...\n                       'Birth', birth_model,...\n                       'Detection', detection_model);\n\n%% Simulation\n% Data Simulator\ndataSim = SingleTargetMeasurementSimulatorX(model);\n\n% Simulate some measurements from ground-truth data\nMeasurementScans = dataSim.simulate(TrueTrack);\nmeasurements = [MeasurementScans.Vectors];\n\n%% Initiation\n\n% Setup prior assuming we have some intuition of the target's initial\n% position\npriorParticles = TrueTrack.Trajectory(1).Vector ...\n                 + model.Measurement.finv(model.Measurement.random(4000));\npriorWeights = ones(1,4000)/4000;\nconfig.Model = model;\nconfig.StatePrior = ParticleStateX(priorParticles,priorWeights./sum(priorWeights));\nconfig.StatePrior.Metadata.ExistenceProbability = 0.5;\nconfig.BirthScheme = {'Expansion', 5000};\nconfig.SurvivalProbability = 0.99;\n\n% Initiate a track using the generated prior\ntrack = TrackX(config.StatePrior, TagX(1));\n\n%% Estimation           \n% Instantiate a filter objects\nfilter = BernoulliParticleFilterX(config);                            \nfigure;\nfor t = 2:NumIter\n    \n    % Provide filter with the new measurement\n    MeasurementList = MeasurementScans(t);\n    \n    % Perform filtering\n    filter.MeasurementList = MeasurementList;\n    filter.predict();\n    filter.update();\n    \n    % Log the data\n    track.Trajectory(end+1) = filter.StatePosterior;\n    \n    clf;\n    hold on;\n    measurements = [MeasurementScans(1:t).Vectors];\n    meas = measurement_model.finv(measurements);\n    true_means = [TrueTrack.Trajectory(1:t).Vector];\n    track_means = [track.Trajectory(1:t).Mean];\n    plot(true_means(1,1:t), true_means(3,1:t),'.-k', track_means(1,1:t), track_means(3,1:t), 'b-', meas(1,:), meas(3,:), 'rx');\n    plotgaussellipse(track.Trajectory(t).Mean([1,3],1), ...\n                     track.Trajectory(t).Covar([1,3],[1,3]),...\n                     'Color','g');\n    legend('GroundTrouth','Estimated Mean','Measurements', 'Estimated Covariance');\n    xlabel(\"x coordinate (m)\");\n    ylabel(\"y coordinate (m)\");\n    axis([2 9 1 9]);\n    drawnow();\nend    ", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Filters/Bernoulli/BernoulliParticleFilterX/Example/example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6619228758499943, "lm_q1q2_score": 0.5750963138466486}}
{"text": "function z=rpsola(x,y,t)\n  % The solution of a Riemann problem (continuous)  \n  z=zeros(size(x));\n  lne=0.25*t;\n  lm=-0.5*t;\n  lM=0.5*t; \n  \n  ind=find((x>=lM)&(y>=lM));\n  z(ind)=0.5;\n  \n  ind=find((x<lM)&(x>=lne)&(y>=lne)&(y>=x));\n  z(ind)=x(ind)/t;\n  \n  ind=find((x>=lne)&(y<lM)&(y>=lne)&(y<x));\n  z(ind)=y(ind)/t;\n  \n  ind=find(((x>=lne)&(y<lne))|((x<lne)&(y>=lne)));\n  z(ind)=0.25;\n  \n  ind=find((x<lne)&(x>=lm)&(x>=y));\n  z(ind)=x(ind)/t;\n  \n  ind=find((y<lne)&(y>=lm)&(x<y));\n  z(ind)=y(ind)/t;\n\n  ind=find((x<=lm)&(y<=lm));\n  z(ind)=-0.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/OperatorSplitting/Chapter5/Dimsplit/rpsola.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5750958066702027}}
{"text": "function [PB] = GB2PB(GB)\n% Convert computery things from gigabytes to petabytes.\n% Chad A. Greene 2012\nPB = GB*2^-20 ;", "meta": {"author": "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/GB2PB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5750121172178907}}
{"text": "function [data,units] = compute_min_dwing_angle_out(trx,n)\n\nflies = trx.exp2flies{n};\nnflies = numel(flies);\ndata = cell(1,nflies);\nfor i = 1:nflies,\n  fly = flies(i);\n\n  data{i} = min(-diff(trx(fly).wing_anglel),diff(trx(fly).wing_angler)) ./ trx(fly).dt;\n  \nend\nunits = parseunits('rad/s');\n\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/compute_min_dwing_angle_out.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5750121027884929}}
{"text": "function [ vS ] = RecSignalFreqSamples( vF, mF, vFIdx )\n% ----------------------------------------------------------------------------------------------- %\n%[ estFreq ] = EstimateSineFreqKay( vX, samplingFreq, estType )\n% Estimates the frequency of a single Real Harmonic signal with arbitrary\n% phase.\n% Input:\n%   - vX                -   Input Samples.\n%                           The vector to be optimized. Initialization of\n%                           the iterative process.\n%                           Structure: Vector (numSamples X 1).\n%                           Type: 'Single' / 'Double'.\n%                           Range: (-inf, inf).\n%   - paramLambda       -   Parameter Lambda.\n%                           The L1 Regularization parameter.\n%                           Structure: Scalar.\n%                           Type: 'Single' / 'Double'.\n%                           Range: (0, inf).\n%   - numIterations     -   Number of Iterations.\n%                           Number of iterations of the algorithm.\n%                           Structure: Scalar.\n%                           Type: 'Single' / 'Double'.\n%                           Range {1, 2, ...}.\n% Output:\n%   - estFreq           -   Number of Iterations.\n%                           Number of iterations of the algorithm.\n%                           Structure: Scalar.\n%                           Type: 'Single' / 'Double'.\n%                           Range {1, 2, ...}.\n% References\n%   1.  Steven Kay - A Fast and Accurate Single Frequency Estimator.\n% Remarks:\n%   1.  It would work with complex numbers (Harmonic Signla) by changing:\n%       vX(ii) * vX(ii + 1) -> vX(ii)' * vX(ii + 1).\n%   2.  fds\n% Known Issues:\n%   1.  C\n% TODO:\n%   1.  D\n% Release Notes:\n%   -   1.0.000     09/08/2021  Royi Avital\n%       *   First release version.\n% ----------------------------------------------------------------------------------------------- %\n\n% arguments\n%     vX (:, 1) {mustBeNumeric, mustBeReal}\n%     samplingFreq (1, 1) {mustBeNumeric, mustBeReal, mustBePositive}\n%     estType (1, 1) {mustBeNumeric, mustBeReal, mustBePositive, mustBeInteger, mustBeMember(estType, [1, 2])} = 2\n% end\n\nnumSamples = size(mF, 2);\n\nmFR = real(mF);\nmFI = imag(mF);\n\nvS = real(SolveBasisPursuitLp001([mFR(vFIdx, :); mFI(vFIdx, :)], [real(vF); imag(vF)]));\n% vSRec = real(SolveBasisPursuitLp002(mF(vFIdx, :), vF));\n\n% vS = complex(vSRec(1:numSamples), vSRec((numSamples + 1):end));\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/Q78143/RecSignalFreqSamples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5750121019239939}}
{"text": "function [sma, ecc, inc, raan, arg, tru] = vect_getKeplerFromState(rVect,vVect,gmu, varargin)\n% getKeplerFromState() returns Keplerian orbital elements when provided\n% with the state (cartesian position vector, cartesian velocity vector) of\n% a spacecraft or celestial body.\n%\n%INPUTS\n% rVect - a 3x1 vector that contains the x,y,z components of the orbiting\n% body's current position relative to the central body.  Units: [km]\n% vVect - a 3x1 vector that contains the x,y,z components of the orbiting\n% body's current velocity vector relative to the central body.  Units: [km/sec]\n% muCB - the gravitational parameter of the central body.  Units: km^3/s^2\n%\n%OUTPUTS\n% sma - semi-major axis of the orbit.  Units: [km]\n% ecc - eccentricity of the orbit.  Units: dimensionless\n% inc - inclination angle of the orbit.  Units: radian\n% raan - Longitude of ascending node of the orbit.  Units: radian\n% arg - Argument of periapse of the orbit.  Units: radian.\n% tru - Current true anomaly of the spacecraft/body in the orbit.\n% Units: radian\nif(~isempty(varargin))\n    consistencyCheck = varargin{1};\nelse\n    consistencyCheck = true;\nend\n\nnumRV = size(rVect,2);\n\nrVect = reshape(rVect,3,numRV);\nvVect = reshape(vVect,3,numRV);\n\nif(isscalar(gmu))\n    gmu = gmu * ones(1,numRV);\nend\n\ntry\n    [sma, ecc, inc, raan, arg, tru] = vect_getKeplerFromState_Alg_mex(rVect,vVect,gmu(:)');\ncatch\n    [sma, ecc, inc, raan, arg, tru] = vect_getKeplerFromState_Alg(rVect,vVect,gmu(:)');\nend\n\nbool = ecc<1.0;\n\ntru(bool)=AngleZero2Pi(tru(bool));\ntru(~bool) = angleNegPiToPi(tru(~bool));\n\ntol = 1E-6;\nif(consistencyCheck)\n    [rVect2,~]=vect_getStatefromKepler(sma, ecc, inc, raan, arg, tru, gmu, false);\n    rDang = real(acos(dot(rVect,rVect2)./(sqrt(sum(abs(rVect).^2,1)) .* sqrt(sum(abs(rVect2).^2,1)) )));\n    if(all(rDang < tol))\n        return;\n    end\n    \n    [rVect3,~]=vect_getStatefromKepler(sma, ecc, inc, raan-rDang, arg+rDang, tru, gmu, false);\n    rDang2 = real(acos(dot(rVect,rVect3)./(sqrt(sum(abs(rVect).^2,1)) .* sqrt(sum(abs(rVect3).^2,1)) )));\n    if(any(rDang2 < tol))\n        raan(rDang2 < tol) = raan(rDang2 < tol) - rDang(rDang2 < tol);\n        arg(rDang2 < tol)  = arg(rDang2 < tol)  + rDang(rDang2 < tol);\n        raan = AngleZero2Pi(raan);\n        arg = AngleZero2Pi(arg);\n        \n        if(all(rDang2 < tol))\n            return;\n        end\n    end\n\n    [rVect4,~]=vect_getStatefromKepler(sma, ecc, inc, raan+rDang, arg-rDang, tru, gmu, false);\n    rDang3 = real(acos(dot(rVect,rVect4)./(sqrt(sum(abs(rVect).^2,1)) .* sqrt(sum(abs(rVect4).^2,1)) )));\n    if(any(rDang3 < tol))\n        raan(rDang3 < tol) = raan(rDang3 < tol) + rDang(rDang3 < tol);\n        arg(rDang3 < tol)  = arg(rDang3 < tol)  - rDang(rDang3 < tol);\n        raan = AngleZero2Pi(raan);\n        arg = AngleZero2Pi(arg);\n        \n        if(all(rDang3 < tol))\n            return;\n        end\n    end\n\n    [rVect5,~]=vect_getStatefromKepler(sma, ecc, inc, raan+rDang, arg+rDang, tru, gmu, false);\n    rDang4 = real(acos(dot(rVect,rVect5)./(sqrt(sum(abs(rVect).^2,1)) .* sqrt(sum(abs(rVect5).^2,1)) )));\n    if(any(rDang4 < tol))\n        raan(rDang4 < tol) = raan(rDang4 < tol) + rDang(rDang4 < tol);\n        arg(rDang4 < tol)  = arg(rDang4 < tol) + rDang(rDang4 < tol);\n        raan = AngleZero2Pi(raan);\n        arg = AngleZero2Pi(arg);\n        \n        if(all(rDang4 < tol))\n            return;\n        end\n    end\n\n    [rVect6,~]=vect_getStatefromKepler(sma, ecc, inc, raan-rDang, arg-rDang, tru, gmu, false);\n    rDang5 = real(acos(dot(rVect,rVect6)./(sqrt(sum(abs(rVect).^2,1)) .* sqrt(sum(abs(rVect6).^2,1)) )));\n    if(any(rDang5 < tol))\n        raan(rDang5 < tol) = raan(rDang5 < tol) - rDang(rDang5 < tol);\n        arg(rDang5 < tol)  = arg(rDang5 < tol) - rDang(rDang5 < tol);\n        raan = AngleZero2Pi(raan);\n        arg = AngleZero2Pi(arg);\n        \n        if(all(rDang5 < tol))\n            return;\n        end\n    end\n    \n    [rVect7,~]=vect_getStatefromKepler(sma, ecc, inc, raan, arg, tru-rDang, gmu, false);\n    rDang6 = real(acos(dot(rVect,rVect7)./(sqrt(sum(abs(rVect).^2,1)) .* sqrt(sum(abs(rVect7).^2,1)) )));\n    if(any(rDang6 < tol))\n        tru(rDang6 < tol) = tru(rDang6 < tol) - rDang(rDang6 < tol);\n        \n        if(all(rDang6 < tol))\n            return;\n        end\n    end\n    \n    [rVect8,~]=vect_getStatefromKepler(sma, ecc, inc, raan, arg, tru+rDang, gmu, false);\n    rDang7 = real(acos(dot(rVect,rVect8)./(sqrt(sum(abs(rVect).^2,1)) .* sqrt(sum(abs(rVect8).^2,1)) )));\n    if(any(rDang7 < tol))\n        tru(rDang7 < tol) = tru(rDang7 < tol) + rDang(rDang7 < tol);\n        \n        if(all(rDang7 < tol))\n            return;\n        end\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/astrodynamics/vectorized_elem_conv/vect_getKeplerFromState.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5750120971141944}}
{"text": "function value = t_polynomial_value ( n, x )\n\n%*****************************************************************************80\n%\n%% T_POLYNOMIAL_VALUE: returns the single value T(n,x).\n%\n%  Discussion:\n%\n%    In cases where calling T_POLYNOMIAL is inconvenient, because it returns\n%    a vector of values for multiple arguments X, this simpler interface\n%    may be appropriate.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 April 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the order of the polynomial.\n%\n%    Input, real X, the argument of the polynomial.\n%\n%    Output, real VALUE, the value of T(n,x).\n%\n  m = 1;\n\n  v_vec = t_polynomial ( m, n, x );\n\n  value = v_vec(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/chebyshev_polynomial/t_polynomial_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.5749781332147353}}
{"text": "function newS = align_shape( TransM , S )\n\nnewS = zeros(size(S));\n\nx = S(1:2:end);\ny = S(2:2:end);\n\nxy = [x'; y'; ones(1, size(x,1))];\nnewXY = [TransM ; [0 0 1]]\\xy;\n\nnewS(1:2:end) = newXY(1,:);\nnewS(2:2:end) = newXY(2,:);\n\nend\n\n", "meta": {"author": "tntrung", "repo": "sdm_face_alignment", "sha": "f546cbb1e77b8bad971e8c5914d2ca73e0bb9b67", "save_path": "github-repos/MATLAB/tntrung-sdm_face_alignment", "path": "github-repos/MATLAB/tntrung-sdm_face_alignment/sdm_face_alignment-f546cbb1e77b8bad971e8c5914d2ca73e0bb9b67/common/align/align_shape.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5749193905571294}}
{"text": "function [p,CI] = compareAUC(X1,X2,Y)\n% -------------------------------------------------------------------------\n% function [p,CI] = compareAUC(X1,X2,Y)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function calculates the significance (p-value) for the difference\n% between two CORRELATED AUCs (i.e. computed from the same samples) \n% computed for two different prediction situations. The implementation of \n% this function is based on ref. [1].\n% -------------------------------------------------------------------------\n% REFERENCE:\n% [1] DeLong, E. R., DeLong, D. M. & Clarke-Pearson, D. L. Comparing the \n%     areas under two or more correlated receiver operating characteristic \n%     curves: a nonparametric approach. Biometrics 44, 837\u2013845 (1988).\n% -------------------------------------------------------------------------\n% INPUTS:\n% 1. X1: [N X 1] vector of probabilities of outcome Y for situation 1.\n% 2. X2: [N X 1] vector of probabilities of outcome Y for situation 2.\n% 3. Y:  [N X 1] vector defining if each nth intance has the outcome or not\n%        (1's or 0's), where N is the total number of patients.\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% 1. p: p-value for the difference in AUC.\n% 2. CI: 95 % confidence interval for the difference in AUCs (diff), to be \n%    subsequently applied as diff - CI and diff + CI.\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: January 2017\n% -------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of <https://github.com/mvallieres/radiomics/>, \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015-2017  Martin Vallieres\n% \n%    This package 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 package 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 package.  If not, see <http://www.gnu.org/licenses/>.\n% -------------------------------------------------------------------------\n\n\n% SANITY CHECKS\nif numel(X1) ~= numel(Y) || numel(X2) ~= numel(Y)\n    error('The number of instances in vectors X1, X2, and Y must be the same')\nend\nY = logical(Y);\n\n\n% PARAMETERS OR INTEREST\nsigma = 1.96; % For 95 % confidence interval\nL = [1,-1]; % Contrast vector. We are always comparing 2 variables at a time, not more. This is hardcoded for now and should stay as is.\n\n\n% INITIALIZATION\nX = [X1,X2]; % Combining the variables into a single matrix. We are always comparing 2 variables at a time, not more.\nnVar = size(X,2); % Number of variables we compare (referred to \"r\" in ref. [1], so here, \"v\" --> \"r\" in ref. [1])\nnInst = numel(Y); nPos = sum(Y); nNeg = nInst - nPos; % Total number of instances, number of positive instances (\"nPos\" --> \"m\" in ref. [1]) and number of negative instances (\"nNeg\" --> \"n\" in ref. [1]), respectively\nVpos = zeros(nPos,nVar); Vneg = zeros(nNeg,nVar); % Matrices \"Vpos\" --> \"V10\" and \"Vneg\" --> \"V01\" in ref. [1], respectively. \nauc = zeros(1,nVar); % AUC estimates (\"auc\" --> \"theta\" in ref. [1])\n\n\n% COMPUTATION OF AUC ESTIMATES (\"auc\" --> \"theta\"), VPOS (\"Vpos\" --> \"V10\") and VNEG (\"Vneg\" --> \"V01\")\nXpos = X(Y,:); Xneg = X(~Y,:); % Separating positive and negative instances (\"Xpos\" --> \"X\" and Xneg --> \"Y\" in ref. [1]. Here, our \"Y\" refers to the outcomes, or targets, to defined if an instance as the condition or not)\nfor v = 1:nVar\n    for i = 1:nPos\n        val = Xpos(i,v);\n        Vpos(i,v) = sum(Xneg(:,v) < val) + 0.5*sum(Xneg(:,v) == val);\n    end\n    for i = 1:nNeg\n        val = Xneg(i,v);\n        Vneg(i,v) = sum(Xpos(:,v) > val) + 0.5*sum(Xpos(:,v) == val);\n    end\nend\nauc = sum(Vpos)/(nNeg*nPos);\nVpos = Vpos/nNeg; Vneg = Vneg/nPos;\n\n\n% COMPUTATION OF COVARIANCE MATRICES (\"Spos\" --> \"S10\" and \"Sneg\" --> \"S01\" in ref. [1])\nSpos = (1/nPos) * ((Vpos'*Vpos) - nPos*(auc*auc'));\nSneg = (1/nNeg) * ((Vneg'*Vneg) - nNeg*(auc*auc'));\nS = (1/nPos)*Spos + (1/nNeg)*Sneg; \n\n\n% COMPUTATION OF CHI-SQUARE STATISTICS\nLSL = L*S*L';\nval_chi2 = (auc*L')*(inv(LSL))*(L*auc')*sqrt(2);\ndf_chi2 = rank(LSL);\np = 1-chi2cdf(val_chi2,df_chi2);\nCI = sigma * sqrt(LSL);\n\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/UTILITIES/compareAUC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5749193896168849}}
{"text": "function [W] = hpe2W(hpe)\n% Convert power from electrical horsepower to watts.\n% Chad A. Greene 2012\nW = hpe*746;\n", "meta": {"author": "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/hpe2W.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5749193896168849}}
{"text": "classdef SOP_F21 < PROBLEM\n% <single> <real> <expensive/none>\n% Shekel's family\n\n%------------------------------- Reference --------------------------------\n% X. Yao, Y. Liu, and G. Lin, Evolutionary programming made faster, IEEE\n% Transactions on Evolutionary Computation, 1999, 3(2): 82-102.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 1;\n            obj.D = 4;\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = zeros(1,obj.D) + 10;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            a = [4 4 4 4;1 1 1 1;8 8 8 8;6 6 6 6;3 7 3 7];\n            c = [0.1;0.2;0.2;0.4;0.4];\n            PopObj = zeros(size(PopDec,1),1);\n            for i = 1 : size(PopDec,1)\n                PopObj(i) = -sum(1./(sum((repmat(PopDec(i,:),5,1)-a).^2,2)+c));\n            end\n        end\n        %% Generate the minimum objective value\n        function R = GetOptimum(obj,N)\n            R = -10.16;\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/Single-objective optimization/Simple SOPs/SOP_F21.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5749193896168849}}
{"text": "% Infrared Small-Target Detection Using Multiscale Gray Difference Weighted Image Entropy\nclearvars;\nclose all;\nclc;\nwflag = 1;\nfor kk = 1\n    fold = '.\\data\\';% 27 images\n    try\n        img = imread([fold, num2str(kk), '.jpg']);\n    catch\n        img = imread([fold, num2str(kk), '.bmp']);\n    end\n    img = img(:,:,1);\n    re = mgdwe(img);\n    bw = bwfunc(re);\n    if wflag\n        refold = '.\\';\n        if exist(refold,'dir')==0\n            mkdir(refold);\n        end\n        imwrite(uint8(img), [refold, num2str(kk), '1.png']);\n        imwrite(uint8( mat2gray(re) * 255), [refold, num2str(kk), '2.png']);\n        imwrite(bw, [refold, num2str(kk), '3.png']);\n    end\nend\n", "meta": {"author": "daxjuanxiong", "repo": "infrared-small-target-detection", "sha": "bf9b82519b235b776749ca8d89018de71ec65f7b", "save_path": "github-repos/MATLAB/daxjuanxiong-infrared-small-target-detection", "path": "github-repos/MATLAB/daxjuanxiong-infrared-small-target-detection/infrared-small-target-detection-bf9b82519b235b776749ca8d89018de71ec65f7b/cpy_mgdwe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5749193854041748}}
{"text": "function [xi,yi] = snakeinterp(x,y,dmax,dmin)\n%SNAKEINTERP  Interpolate the snake adaptively\n%   [xi,yi] = snakeinterp(x,y,dmax,dmin)\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)<dmin, then either i or i+1 is removed \n%  \n%   NOTE: the spacing of original curve must be close to the \n%         range defined by dmax and dmin. For arbitrary spacing,\n%         try snakeinterp1.\n% \n%   See also SNAKEINTERP1\n\n%    there is a bug in the program for points removal\n\n%   Chenyang Xu and Jerry L. Prince, 4/1/95, 6/17/97\n%   Copyright (c) 1995-97 by Chenyang Xu and Jerry L. Prince\n%   Image Analysis and Communications Lab, Johns Hopkins University\n    xi=x;\n    yi=y;\n% convert to column vector\nx = x(:); y = y(:);\n\nN = length(x);\n\nd = abs(x([2:N 1])- x(:)) + abs(y([2:N 1])- y(:));\n\n% remove the points which distance to neighbor points is shorter than dmin\nIDX = (d<dmin);\n\nidx = find(IDX==0);\nx = x(idx);\ny = y(idx);\n\nN = length(x);\n\nif N>0\n    \n    d = abs(x([2:N 1])- x(:)) + abs(y([2:N 1])- y(:));\n    \n    IDX = (d>dmax);\n    \n    z = snakeindex(IDX);\n    \n    p = 1:N+1;\n    \n    xi = interp1(p,[x;x(1)],z');\n    yi = interp1(p,[y;y(1)],z');\n    \n    N = length(xi);\n    d = abs(xi([2:N 1])- xi(:)) + abs(yi([2:N 1])- yi(:));\n    \n    while (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(:));\n    end\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/42435-adaptive-diffusion-flow-active-contours-for-image-segmentation/ADF code/snakeinterp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5749193854041748}}
{"text": "function asa066_test02 ( )\n\n%*****************************************************************************80\n%\n%% TEST02 tests NORMP.\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, 'TEST02:\\n' );\n  fprintf ( 1, '  Compare tabulated values of the normal\\n' );\n  fprintf ( 1, '  Cumulative Density Function against values\\n' );\n  fprintf ( 1, '  computed by NORMP.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '         X        CDF                       CDF' );\n  fprintf ( 1, '                    DIFF\\n' );\n  fprintf ( 1, '               (tabulated)                 (NORMP)\\n' );\n  fprintf ( 1, '\\n' );\n\n  upper = 0;\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x, fx ] = normal_01_cdf_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    [ p, q, pdf ] = normp ( x );\n    fx2 = p;\n\n    fprintf ( 1, '  %10.4e  %24.16e  %24.16e  %10.4e\\n', ...\n    x, fx, fx2, abs ( fx - fx2 ) );\n\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/asa066/asa066_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059707450325, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5748989487653271}}
{"text": "function out = EN_SampEn(y,M,r,preProcessHow)\n% EN_SampEn     Sample Entropy of a time series\n%\n% SampEn(m,r), using code from PhysioNet.\n%\n% Uses a compiled C version of the code if available, otherwise uses a (slower)\n% Matlab implementation (which can actually be faster for shorter time series\n% due to overheads of reading/writing to disk)\n%\n% The publicly-available PhysioNet Matlab code, sampenc (renamed here to\n% RN_sampenc) is available from:\n% http://www.physionet.org/physiotools/sampen/matlab/1.1/sampenc.m\n%\n% cf. \"Physiological time-series analysis using approximate entropy and sample\n% entropy\", J. S. Richman and J. R. Moorman, Am. J. Physiol. Heart Circ.\n% Physiol., 278(6) H2039 (2000)\n%\n% This function can also calculate the SampEn of successive increments of time\n% series, i.e., we using an incremental differencing pre-processing, as\n% used in the so-called Control Entropy quantity:\n%\n% \"Control Entropy: A complexity measure for nonstationary signals\"\n% E. M. Bollt and J. Skufca, Math. Biosci. Eng., 6(1) 1 (2009)\n%\n%---INPUTS:\n% y, the input time series\n% M, the embedding dimension\n% r, the threshold\n% preProcessHow [opt], (i) 'diff1', incremental differencing (as per 'Control Entropy').\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,\n% <http://www.benfulcher.com>\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 <http://www.gnu.org/licenses/>.\n% ------------------------------------------------------------------------------\n\n% Check y is a column vector:\nif isempty(y)\n    error('Must input a valid data vector');\nend\nif size(y,1)==1\n    y = y';\nend\n\n% Embedding dimension:\nif nargin < 2\n    M = 2;\nend\n\n% Tolerance:\nif nargin < 3\n    r = 0.1*std(y);\nend\n\nif nargin < 4\n    preProcessHow = ''; % don't apply any preprocessing\nend\n\n%-------------------------------------------------------------------------------\n% Can specify to first apply an incremental differencing of the time series\n% thus yielding the 'Control Entropy':\n% \"Control Entropy: A complexity measure for nonstationary signals\"\n% E. M. Bollt and J. Skufca, Math. Biosci. Eng., 6(1) 1 (2009)\nif ~isempty(preProcessHow)\n    y = BF_PreProcess(y,preProcessHow);\nend\n\n% ------------------------------------------------------------------------------\n% Use the physionet code to calculate the Sample Entropy using these parameters:\n% ------------------------------------------------------------------------------\n% Check if a compiled C version exists:\n% [a,b] = system('which sampen');\n\nsampEn = sampen_mex(y',M+1,r);\nsampEn = sampEn(1:M+1); % always that extra one for the M=0\n\n%-------------------------------------------------------------------------------\n% This is dangerous because it could lead to inconsistent implementations across runs\n%-------------------------------------------------------------------------------\n% warning('No mex file found: using a slower native Matlab implementation instead');\n% No mex version available; use (much slower) Matlab implementation\n% if isempty(b) || length(y) < 3000 % faster to run within Matlab\n% sampEn = PN_sampenc(y,M+1,r,false);\n%     fprintf('Using compiled C code~~~\\n')\n%     % http://www.physionet.org/physiotools/sampen/c/\n%     % (use Makefile in Toolboxes/Physionet/ to run make, then make install)\n%\n%     % Run compiled C code:\n%     filePath = BF_WriteTempFile(y);\n%     command = sprintf('sampen -m %u -r %f < %s',M,r,filePath);\n%     [~,res] = system(command);\n%     fprintf(1,'%s\\n',res)\n%     s = textscan(res,'%[^\\n]'); s = s{1};\n%     sampEn = zeros(M,1);\n%     for i = 1:M\n%         [~,params] = regexp(s{i},'\\((\\S+)\\)','tokens','match');\n%         params = regexp(params{1}(2:end-1),',','split');\n%         [~,result] = regexp(s{i},'= (\\S+)','tokens','match');\n%         result = str2num(result{1}(3:end));\n%         sampEn(i) = result;\n%     end\n% end\n% end\n\n% ------------------------------------------------------------------------------\n% Compute outputs from the code\n% ------------------------------------------------------------------------------\nfor i = 1:M+1\n    % Sample entropy:\n    out.(sprintf('sampen%u',i-1)) = sampEn(i);\n\n    % Quadratic sample entropy (QSE), Lake (2006):\n    % (allows better comparison across r values)\n    out.(sprintf('quadSampEn%u',i-1)) = sampEn(i) + log(2*r);\n\n    % COSEn (Lake and Moorman, 2011), doesn't really make sense in general;\n    % especially for z-scored series!:\n    % out.(sprintf('COSEn%u',i)) = sampEn(i) + log(2*r) - log(mean(y));\nend\n\nif M > 1\n    out.meanchsampen = mean(diff(sampEn));\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/EN_SampEn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5748989393000833}}
{"text": "function msm_to_mm_test07 ( )\n\n%*****************************************************************************80\n%\n%% MSM_TO_MM_TEST07 tests MSM_TO_MM_ARRAY_INTEGER_SYMMETRIC.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 November 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'MSM_TO_MM_TEST07\\n' );\n  fprintf ( 1, '  Convert an MSM to MM array integer symmetric format.\\n' );\n\n  output_filename = 'msm_to_mm_test07.mm';\n\n  a = i4mat_indicator ( 4, 4 );\n  a = a + a';\n%\n%  Have MSM_TO_MM write the matrix to a file.\n%\n  msm_to_mm ( output_filename, a, 'array', 'integer', 'symmetric' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/msm_to_mm/msm_to_mm_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.574898937527692}}
{"text": "function fg = mk_fgraph(G, node_sizes, factors, varargin)\n% MK_FGRAPH Make a factor graph\n% fg = mk_fgraph(G, node_sizes, factors, ...)\n%\n% A factor graph is a bipartite graph, with one side containing variables,\n% and the other containing functions of (subsets of) these variables.\n% For details, see \"Factor Graphs and the Sum-Product Algorithm\",\n%  F. Kschischang and B. Frey and H-A. Loeliger,\n%  IEEE Trans. Info. Theory, 2001\n%\n% G(i,j) = 1 if there is an arc from variable i to factor j\n%\n% node_sizes(i) is the number of values node i can take on,\n%   or the length of node i if i is a continuous-valued vector.\n%\n% 'factors' is the list of factors (kernel functions)\n%\n% The list below gives optional arguments [default value in brackets].\n% \n% equiv_class - equiv_class(i)=j  means factor node i gets its params from factors{j} [1:F]\n% discrete - the list of nodes which are discrete random variables [1:N]\n%\n% e.g., fg = mk_fgraph(G, [2 2], {bnet.CPD{1},bnet.CPD{2}}, 'discrete', [1 2])\n\nfg.G = G;\nfg.node_sizes = node_sizes;\nfg.factors = factors;\n[fg.nvars fg.nfactors] = size(G);\n\n% default values for parameters\nfg.equiv_class = 1:fg.nfactors;\nfg.dnodes = 1:fg.nvars;\n\nif nargin >= 4\n  args = varargin;\n  nargs = length(args);\n  for i=1:2:nargs\n    switch args{i},\n     case 'equiv_class', fg.equiv_class = args{i+1}; \n     case 'discrete',    fg.dnodes = args{i+1}; \n     otherwise,  \n      error(['invalid argument name ' args{i}]);       \n    end\n  end\nend\n\n% so that determine_pot_type will work...\nfg.utility_nodes = [];\n%fg.decision_nodes = [];\n%fg.chance_nodes = fg.nvars;\n\nfg.dom = cell(1, fg.nfactors);\nfor f=1:fg.nfactors\n  fg.dom{f} = find(G(:,f));\nend\nfg.dep = cell(1, fg.nvars);\nfor x=1:fg.nvars\n  fg.dep{x} = find(G(x,:));\nend\nfg.cnodes = mysetdiff(1:fg.nvars, fg.dnodes);\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/general/mk_fgraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5748989298723105}}
{"text": "function im = ibwt(decomp)\n% function im = ibwt(decomp)\n%\n% BWT reconstruction\n% Version 1.2\n%\n% Arguments:\n%  decomp: A square BWT decomposition, as produced by bwt.m\n%\n% Result:\n%  im: An image\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%  <http://dx.doi.org/10.1162/neco.2007.05-07-513>\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\nsz = size(decomp);\n\nif (length(sz) ~= 2) || (sz(1) ~= sz(2))\n  disp('Input must be square');\n  im = nan;\n  return;\nend\n\nsz = sz(1);\n\nnumlevels = log(sz)/log(3);\n\nif ( (numlevels-floor(numlevels)) > abs(numlevels)*eps )\n  disp('Input side length must be a power of 3');\n  im = nan;\n  return;\nend\n\nim = zeros(sz);\n\nfor level = 1:numlevels\n  ssz = size(decomp,1);\n  decomp_thislevel = decomp;\n  \n  if (ssz>3)\n    decomp_thislevel(end-ssz/3+1:end,1:ssz/3) = 0;\n  end\n\n  im_thislevel = ibwt_onelevel(decomp_thislevel)/sz*ssz*((3^level)^2);\n  idx = ceil((1:sz)*ssz/sz);\n  im = im + im_thislevel(idx,idx); % upsample by sz/ssz times\n  \n  if (ssz>1)\n    decomp = decomp(end-ssz/3+1:end,1:ssz/3);\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/19860-berkeley-wavelet-transform/bwt/ibwt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5748989275341024}}
{"text": "function err_shape = error_depth(param_dist,xcn,xpn,R,T,X_shape,ind);\n\n\n\nX_new = depth_compute(xcn,xpn,[param_dist],R,T);\n\n\nN_pt_calib = size(xcn,2);\n\n% UnNormalized shape extraction:\n\nX_shape2 = X_new;\nX_shape2 = X_shape2 - (X_shape2(:,1)*ones(1,N_pt_calib));\n\n% map the second vector at [1;0;0]:\n\nomu = -cross([1;0;0],X_shape2(:,2));\nomu = acos((dot([1;0;0],X_shape2(:,2)))/norm(X_shape2(:,2)))*(omu / norm(omu));\nRu = rodrigues(omu);\n\nX_shape2 = Ru* X_shape2;\n\nomu2 = -cross([0;1;0],[0;X_shape2(2:3,ind)]);\nomu2 = acos((dot([0;1;0],[0;X_shape2(2:3,ind)]))/norm([0;X_shape2(2:3,ind)]))*(omu2 / norm(omu2));\nRu2 = rodrigues(omu2);\n\nX_shape2 = Ru2* X_shape2;\n\n\n% Error:\n\nerr_shape = X_shape2(:,2:end) - X_shape(:,2:end);\n\nerr_shape = err_shape(:);\n\n\n\n%err_depth = Z_new - Z_ref;\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/error_depth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5747736814483181}}
{"text": "function [rVectECEF, vVectECEF, REci2Ecef] = getFixedFrameVectFromInertialVect(ut, rVectECI, bodyInfo, varargin)\n% %getFixedFrameVectFromInertialVect Summary of this function goes here\n% %   Detailed explanation goes here\n% \n    inputs = bodyInfo.getFixedFrameFromInertialFrameInputsCache();\n    [rVectECEF, vVectECEF, REci2Ecef] = getFixedFrameVectFromInertialVect_alg(ut, rVectECI, inputs{:}, varargin{:});\nend\n\n% %getFixedFrameVectFromInertialVect Summary of this function goes here\n% %   Detailed explanation goes here\n% \n%     if(~isempty(varargin))\n%         vVectECI = varargin{1};\n%     else\n%         vVectECI = [NaN;NaN;NaN];\n%     end\n% \n%     numElems = length(ut);\n%     \n%     spinAngle = getBodySpinAngle(bodyInfo, ut);\n%     \n%     cSA = reshape(cos(spinAngle),1,1,numElems);\n%     sSA = reshape(sin(spinAngle),1,1,numElems);\n%     zero = zeros(1,1,numElems);\n%     one = zero + 1;\n%     \n% %     R = [cos(spinAngle) -sin(spinAngle) 0;\n% %          sin(spinAngle) cos(spinAngle) 0;\n% %          0 0 1];\n% \n%     R = [cSA, -sSA, zero;\n%          sSA, cSA, zero;\n%          zero, zero, one];\n%      \n% %     rVectECI = reshape(rVectECI,3,1);\n%     rVectECI = reshape(rVectECI,3,1,numElems);\n%     \n%     REci2Ecef = permute(R,[2,1,3]); %ND transpose\n% %     rVectECEF = REci2Ecef * rVectECI;\n%     rVectECEF = mtimesx(REci2Ecef, rVectECI);\n%     rVectECEF = reshape(rVectECEF,3,numElems);\n%         \n%     if(~any(isnan(vVectECI)))\n%         rotRateRadSec = 2*pi/bodyInfo.rotperiod;\n%         omegaRI = repmat([0;0;rotRateRadSec],1,1,numElems);\n%         vVectECI = reshape(vVectECI,3,1,numElems);\n%         \n% %         vVectECEF = REci2Ecef*(vVectECI - cross(omegaRI, rVectECI));\n%         vVectECEF = mtimesx(REci2Ecef, (vVectECI - cross(omegaRI, rVectECI)));\n%         vVectECEF = reshape(vVectECEF,3,numElems);\n%     else\n%         vVectECEF = repmat([NaN;NaN;NaN],1,numElems);\n%     end\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/astrodynamics/fixed_frame/getFixedFrameVectFromInertialVect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88242786954645, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5747736736016855}}
{"text": "function log_b = binomial_coeff(n_max)\n    % Compute log binomial coefficients\n    log_b = {};\n    for n = 0:n_max\n        Ks = 0:n;\n        log_b{n+1} = gammaln(n+1) - gammaln(Ks+1) - gammaln(n-Ks+1);\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/lossless-sc/binomial_coeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5747295427036494}}
{"text": "% capillary pressure curve for drainage\n% Written by Ali A. Eftekhari\n% TBD, probably not required in the new IMPES formulation\nfunction res=dpc_drain(sw, pce, swc, labda, pc_max)\nsw0=swc+(1-labda*log(pc_max/pce)+sqrt((-1+labda*log(pc_max/pce))^2+...\n      4*swc/(1-swc)))/2*(1-swc);\nres = (sw>sw0).*(-1.0/((1-swc)*labda)*pce*((sw-swc)/(1-swc)).^(-1.0/labda-1))+...\n    (0.0<=sw).*(sw<=sw0).*(-1.0/((1-swc)*labda)*pce*((sw0-swc)/(1-swc)).^(-1.0/labda-1))+...\n    (sw<0)*0.0;\nend", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/FieldGeology/dpc_drain_vec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.574728601580935}}
{"text": "function [F, subF, Data] = ObjFun(Track, UAV)\n%OBJFUN \u76ee\u6807\u51fd\u6570\u3001\u9002\u5e94\u5ea6\u51fd\u6570\uff08\u4e00\u4e2aagent\u7684\uff09\n\n% \u591a\u76ee\u6807\u4f18\u5316\u6743\u91cd\u8bbe\u7f6e\uff08\u5fc5\u9700\u4e3a\u884c\u5411\u91cf\uff09\nweight = [ 0.05, 0.05, 0.1, 0.7, 0.7 ]; % \u9ed8\u8ba4\u6743\u91cd\n\n\n% \u8868\u8fbe\u5f0f\u7cfb\u6570\u8c03\u6574\uff08\u5c06\u5404\u9879\u6307\u6807\u65e0\u91cf\u7eb2\u5316\uff09\np1 = 1;   % \u71c3\u6599\u9879\uff08\u5df2\u9664\u4ee5\u6700\u5927\u822a\u7a0b\uff09\np21 = 1; % \u9ad8\u5ea6\u9879\np22 = 1; % \u4f4e\u5ea6\u9879\np31 = 1.2; % \u96f7\u8fbe\u5a01\u80c1\np32 = 1.1; % \u5176\u4f59\u5a01\u80c1\np4 = 1.2;   % \u65f6\u95f4\u540c\u6b65\u9879\np5 = 1;   % \u78b0\u649e\u9879\n\n\n% \u8fdb\u884c\u822a\u8ff9\u68c0\u6d4b\nreport = TrackDetect(Track, UAV);  % Track \u4e3a struck\u7ed3\u6784\n\n% \u71c3\u6cb9\uff08\u8bba\u65873\uff09\nZZ = sum(UAV.limt.L);\nMaxL_mt = ZZ(2);\nf_o = p1 * report.L_mt / MaxL_mt;\n\n% \u9ad8\u5ea6\uff08\u8bba\u65873\uff09\ndim = UAV.PointDim;\nif dim < 3\n    f_h = 0;\nelse\n    f_h = 0;\n    for i = 1 : UAV.num\n        Hmax = UAV.limt.h(i, 2);\n        Hmin = UAV.limt.h(i, 1); \n        for k = 1 : UAV.PointNum(i)\n            z = Track.P{i}(3, k);\n            if z>Hmax\n                fk = p21 * (z - Hmax);\n            elseif z >= Hmin\n                fk = 0;\n            else\n                fk = p22 * (Hmin - z);\n            end\n            f_h = f_h + fk;\n        end\n    end\nend\n\n% \u5a01\u80c1\uff08\u8bba\u65872\uff09\n% \u6ce8\u610f\uff1a\u53ea\u9002\u5e94\u7403\u6216\u5706\u533a\u57df\uff0c\u4e0d\u9002\u5408\u5706\u67f1\u533a\u57df\nO_r = UAV.Menace.radar(: ,1:end-1);             %\u96f7\u8fbe            \nO_o = UAV.Menace.other(: ,1:end-1);            %\u5bfc\u5f39\uff0c\u706b\u70ae\uff0c\u6c14\u8c61\u7b49    \nf_t = 0;  % \u5a01\u80c1\u4ee3\u4ef7\nfor i = 1 : UAV.num\n    for k = 1 : UAV.PointNum(i)\n        P = Track.P{i}(:, k)' ;  % \u8f6c\u7f6e\u6210 1*dim\n        for m = 1 : size(O_r, 1)\n            fk = p31 / (norm(P - O_r(m, :)))^4;\n            f_t = f_t + fk;\n        end\n        for m = 1 : size(O_o, 1)\n            fk = p32 / norm(P - O_o(m, :));\n            f_t = f_t + fk;\n        end\n    end\nend\n\n% \u540c\u6b65\uff08\u8bba\u65871\uff09\nf_m = 0;\nfor i = 1 : UAV.num\n    Li = report.L(i);\n    tmax = Li / UAV.limt.v(i,1);\n    tmin = Li / UAV.limt.v(i,2);\n    ti = report.time(i);\n    tc = UAV.tc;\n    if tc <= tmax && tc >= tmin\n        fk = 0;\n    else\n        fk = p4 * abs(ti - tc);\n    end\n    f_m = f_m + fk;\nend\n\n% \u78b0\u649e\uff08\u8bba\u65871\uff09\nf_c = p5 * report.col_times;\n\n\n% \u76ee\u6807\u51fd\u6570\u5206\u91cf\uff08\u5fc5\u9700\u662f\u5217\u5411\u91cf\uff0c\u5426\u5219\u65e0\u6cd5\u805a\u7c7b\uff09\nsubF = [ f_o; f_h; f_t; f_m; f_c ]; % 5*1\n\n\n% \u52a0\u6743\u76ee\u6807\u51fd\u6570\nF = weight * subF ;\n\n% \u8f93\u51fa\u4fe1\u606f\nData.ProbPoint = report.ProbPoint;      % \u6240\u6709\u6709\u95ee\u9898\u7684\u70b9\nData.AngleProb = report.AngleProb;    % \u4e0d\u6ee1\u8db3\u89d2\u5ea6\u7ea6\u675f\u7684\u70b9\nData.TrajProb = report.TrajProb;           % \u4e0d\u6ee1\u8db3\u6700\u5c0f\u822a\u8ff9\u95f4\u9694\u7684\u70b9\nData.Threat = report.Threat;                  % \u53d7\u5a01\u80c1\u7684\u70b9\n\nData.L = report.L;                                      % \u6bcf\u4e2a\u65e0\u4eba\u673a\u7684\u822a\u7a0b\nData.t = report.time;                                 % \u6bcf\u4e2a\u65e0\u4eba\u673a\u7684\u65f6\u95f4\nData.c = report.col_times;                         % \u6240\u6709\u65e0\u4eba\u673a\u603b\u78b0\u649e\u6b21\u6570\n\n\nend\n\n", "meta": {"author": "zhaohaojie1998", "repo": "Grey-Wolf-Optimizer-for-Path-Planning", "sha": "ff6d042c58ca6f2fbcb880124e5513ad7d5848a9", "save_path": "github-repos/MATLAB/zhaohaojie1998-Grey-Wolf-Optimizer-for-Path-Planning", "path": "github-repos/MATLAB/zhaohaojie1998-Grey-Wolf-Optimizer-for-Path-Planning/Grey-Wolf-Optimizer-for-Path-Planning-ff6d042c58ca6f2fbcb880124e5513ad7d5848a9/ObjFun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5746549327009188}}
{"text": "% TD | Tucker-ALS | Tucker Decomposition solved by Alternating Least Squares\n% process_video('TD', 'Tucker-ALS', 'dataset/demo.avi', 'output/demo_Tucker-ALS.avi');\n\nr = [size(T,1) size(T,2) 1];\nA = double(T);\nL = double(tucker_als(T,r));\nS = A - L;\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/td/Tucker-ALS/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5746549292736929}}
{"text": "%% Radar Plan Position Indicator(PPI) Simulation\n\n% Created by\n% R.Vivek\n% MIT (Anna University)\n\n\n%% Description\n% This function displays the Radar PPI plot for detection and ...\n% tracking of a single target approaching at a specified angle.\n\n%% \n\nfunction PPI_plot(dist,Angle,Max_Range)\n\n%% \"dist\" is an array containing the distance (in meters) of the target\n\n%% \"Angle\" is the angle (in radians) with respect to the radar transceiver \n%  at which the target is approaching \n\n%% \"Max_Range\" is the maximum detectable range of the radar\n\n%% -------------------------------------------------------------------------\n\nangle=repmat(Angle,1,(length(dist)));\n\nfor j=1:length(dist)\n    for i=(2*pi):-(pi/180):(pi/180)\n        [x,y]=(pol2cart(i,55));\n        x=ceil(x);\n        z=complex(x,y); \n        h=compass(z);\n        title('Radar PPI Plot');\n        ph=findall(gca,'type','patch');\n        set(ph,'facecolor',[0,0.5,0]);\n        set( h, 'Color', [0.5,1,0] ); \n        set( h, 'LineWidth', 4 );  \n        for k = 1:length(h)\n            a = get(h(k), 'xdata'); \n            b = get(h(k), 'ydata'); \n            set(h(k), 'xdata', a(1:2), 'ydata', b(1:2)')\n        end\n        \n        if(j>1)\n            if(angle(j-1)<i)\n                hold on\n                plothandle=polar(angle(j-1),dist(j-1),'o');\n                set(plothandle,'markerfacecolor',[0,1,0],'markeredgecolor',[0,1,0]);  \n                get( plothandle ) ;\n                set( plothandle, 'Color', [ 0.5, 1, 0 ] );  \n                set ( plothandle, 'LineWidth', 2 );   \n                hold off\n            end\n        end\n        if(dist(j)<=Max_Range)\n        if(angle(j)>=i)\n            hold on\n            plothandle=polar(angle(j),dist(j),'o');\n            set(plothandle,'markerfacecolor',[0,1,0],'markeredgecolor',[0,1,0])\n            get( plothandle ) ;\n            set( plothandle, 'Color', [ 0.5, 1, 0 ] );  \n            set ( plothandle, 'LineWidth', 2 ); \n            hold off\n        end\n        end\n        pause(1*10^-6);\n        end\n    end\n\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39894-radar-plan-position-indicator-ppi/PPI_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5746549187819988}}
{"text": "function [w0, t] = adw_fan(ob, wi, mask, Phi, varargin)\n% function [w0, phi, t] = adw_fan(ob, wi)\n% Compute the angular-dependent weighting for 3rd gen fan-beam\n% w0(\\Phi) = w(x0, y0, \\Phi) \n%         for fully corrected penalty:  \n%          = w(s',\\beta')*J(s')|\\phi'=\\Phi + ... \n%            w(s',\\beta')*J(s')|\\phi'=\\Phi-pi \n% see fessler chapter 3.5.3\n%\n% in: \n%    ob         a struct or object \n%               including system parameters, such as pixel-size etc.\n%    wi         cov(yi)\n%    varargin   default: only compute phi' = Phi\n%               'all': compute phi' = Phi + phi' = Phi- pi\n% out: \n%    w0     angular-dependent weighting \n%    t      computation time\n%\n% Copyright 2005-4-07, Yingying Zhang, The University of Michigan\n\nall = logical(0);\nif ~isempty(varargin)\n    arg = varargin{1};\n    if isempty(arg)\n\t\t\t%\tdo nothing for empty arguments\n\n\telseif ~ischar(arg) \n        error 'unknown non-string argument?'\n    elseif streq(arg, 'all')\n        all = logical(1);\n    else\n        error 'unknown string argument?'\n    end\nend      \n\n% default argument\nob.Df = 0; % 3rd generation CT scanner\n\n% image domain pixel locations\n% only compute within mask\n\nyflip = (-1); % since the top is positive in y direction % \n% x = ([1:ob.nx] - (ob.nx+1)/2)* ob.dx;\n% y = ([1:ob.ny] - (ob.ny+1)/2)* ob.dx * yflip;\n\nx = ([0:ob.nx-1] - ob.nx/2)* ob.dx;\ny = ([0:ob.ny-1] - ob.ny/2)* ob.dx * yflip;\n\n[x y] = ndgrid(x, y);\n\nrr = sqrt(x.^2 + y.^2);\ntheta = atan2(y,x); % use it for our purpose since atan will have pi flip\n\nr0 = rr(mask(:));\nphi0 = theta(mask(:));\n\nclear rr theta\n\n% dummy variables in freq. domain\nphi = Phi;\n\n% if ~isempty(varargin) & isnumeric(varargin{1})\n%     phi = varargin{1};\n% end\n\n% sinogram domain locations\nob.beta = ([0:ob.na-1]'/ob.na * ob.orbit ... \n    + ob.orbit_start) * pi / 180;\nob.s = ([-(ob.nb-1)/2:(ob.nb-1)/2]' ...\n\t\t\t- ob.offset_s) * ob.ds;\nob.gamma = ob.s / ob.dis_src_det;\n[ss, beta] = meshgrid(ob.s,ob.beta); % meshgrid and ndgrid reverse\n\n\n% loop over \\phi_i\nDcf = ob.dis_src_det + ob.Df;\nratio_fcf = ob.Df/Dcf;\n% w0 = zeros(ob.nx, ob.ny, ob.na);\nw0 = zeros([size(r0,1) length(phi)]);\n\ntic    \nfor ia = 1:length(phi)\n    % -------------------------\n    % for \\phi' = \\phi\n    % -------------------------\n    \n    % compute new variables in (3.5.2)\n    r_p = r0 .* cos(phi(ia) - phi0); % use ob.beta, not outer_sum(ob.gamma, ob.beta) \n%                                         since evaluate at \\phi_p = \\phi(view angle)\n    s_p = Dcf.*(asin(r_p./ob.dis_src_iso) - asin(ratio_fcf.*r_p./ob.dis_src_iso));\n    beta_p = phi(ia) - asin(r_p./ob.dis_src_iso);\n    \n    % compute Jacobian determinant (2.8.9) \n    Jacob = ob.dis_src_det ./ sqrt(ob.dis_src_iso.^2 - r_p.^2);\n    \n%     % find corresponding wi: nearest neighbor method\n%     s_cen = (ob.nb - 1)/2 + ob.offset_s; % for nb = even % <-----(yy) plus:(to me account for the right index) or (hugo) minus? \n%     s_loc = round(s_p./ob.ds + s_cen); \n%     s_loc = min(s_loc, ob.nb);\n%     s_loc = max(s_loc, 1);\n%     beta_loc = round((mod(beta_p,2*pi)-ob.orbit_start)./(2*pi/ob.na)) + 1; \n%     beta_loc = min(beta_loc, ob.na);\n%     beta_loc = max(beta_loc, 1);\n% \n%     % find the corresponding index in column-stack wi\n%     loc = 1 + (s_loc(:)-1) + (beta_loc(:)-1)*ob.nb; \n\n    % compute w0 at \\phi' = \\phi\n%     w0(:,ia) =wi(loc(:)) .* Jacob;\n    si = min(s_p, ob.s(end)); si = max(si, ob.s(1));\n    betai = min(beta_p, ob.beta(end)); betai = max(betai, ob.beta(1));\n    w0(:,ia) = interp2(ss, beta, wi.', si(:), betai(:)) .* Jacob;\n    \n    clear s_loc beta_loc loc \n    % -------------------------\n    % for \\phi' = \\phi - pi\n    % -------------------------\n    if all\n        phi_pi = phi(ia) - pi;\n        r_p = r0 .* cos(phi_pi - phi0);\n        s_p = Dcf.*(asin(r_p./ob.dis_src_iso) - asin(ratio_fcf.*r_p./ob.dis_src_iso)); \n        beta_p = phi_pi - asin(r_p./ob.dis_src_iso);\n    \n% %         Jacob_p again: not needed since same\n%         Jacob_p = abs(ob.dis_src_iso*cos(s_p./ob.dis_src_det) - ...\n%             ob.source_offset*sin(s_p./ob.dis_src_det))./ob.dis_src_det;\n%     \n%         % find corresponding wi: nearest neighbor method\n%         s_loc = round(s_p./ob.ds + s_cen); \n%         s_loc = min(s_loc, ob.nb);\n%         s_loc = max(s_loc, 1);\n%     \n%         beta_loc = round((mod(beta_p,2*pi)-ob.orbit_start)./(2*pi/ob.na)) + 1; \n%         beta_loc = min(beta_loc, ob.na);\n%         beta_loc = max(beta_loc, 1);\n%     \n%         % find the corresponding index in column-stack wi\n%         loc = 1 + (s_loc(:)-1) + (beta_loc(:)-1)*ob.nb; \n% \n%         % compute w0 at \\phi' = \\phi - pi and sum with \\phi' = \\phi\n%         w0(:,ia) = w0(:,ia) + wi(loc(:)).*Jacob;\n\n        si = min(s_p, ob.s(end)); si = max(si, ob.s(1));\n        betai = min(beta_p, ob.beta(end)); betai = max(betai, ob.beta(1));\n        w0(:,ia) = w0(:,ia) + interp2(ss, beta, wi.', si(:), betai(:)) .* Jacob;\n        clear s_loc beta_loc loc \n    end\n    \n%     % angle_dependent blur\n%     b0(:,:,ia) = (ob.ray_spacing./Dcf) .* sqrt(ob.dis_src_iso^2 + r0^2 + 2 .* ob.dis_src_iso .* Dcf .* cos(phi(ia)-phi0)); \nend\n \nt = toc;\nsprintf('angular weighting computation time %.4f', t)\n    \n    ", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/zhang-var2/adw_fan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5746549166836601}}
{"text": "classdef DNSGAII < ALGORITHM\n % <multi> <real/integer/label/binary/permutation> <constrained/none> <dynamic>\n % Dynamic NSGA-II\n % type ---   1 --- 1. Mutation based reinitialization 2. Random reinitialization\n % zeta --- 0.2 --- Ratio of reinitialized solutions\n \n%------------------------------- Reference --------------------------------\n% K. Deb, U. Bhaskara Rao N., and S. Karthik, Dynamic multi-objective\n% optimization and decision-making using modified NSGA-II: A case study on\n% hydro-thermal power scheduling, Proceedings of the International\n% Conference on Evolutionary Multi-Criterion Optimization, 2007, 803-817.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Parameter setting\n            [type,zeta] = Algorithm.ParameterSet(1,0.2);\n            % Reset the number of saved populations (only for dynamic optimization)\n            Algorithm.save = sign(Algorithm.save)*inf;\n            \n            %% Generate random population\n            Population = Problem.Initialization();\n            [~,FrontNo,CrowdDis] = EnvironmentalSelection(Population,Problem.N);\n            % Archive for storing all populations before each change\n            AllPop = [];\n\n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                if Changed(Problem,Population)\n                    % Save the population before the change\n                    AllPop = [AllPop,Population];\n                    % React to the change\n                    [Population,FrontNo,CrowdDis] = Reinitialization(Problem,Population,type,zeta);\n                end\n                MatingPool = TournamentSelection(2,Problem.N,FrontNo,-CrowdDis);\n                Offspring  = OperatorGA(Problem,Population(MatingPool));\n                [Population,FrontNo,CrowdDis] = EnvironmentalSelection([Population,Offspring],Problem.N);\n                if Problem.FE >= Problem.maxFE\n                    % Return all populations\n                    Population = [AllPop,Population];\n                    [~,rank]   = sort(Population.adds(zeros(length(Population),1)));\n                    Population = Population(rank);\n                end\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/Algorithms/Multi-objective optimization/DNSGA-II/DNSGAII.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5746450587597872}}
{"text": "function spm_slice_timing(P, sliceorder, refslice, timing, prefix)\n% Correct differences in slice acquisition times\n% FORMAT spm_slice_timing(P, sliceorder, refslice, timing, prefix)\n% P           - char array of image filenames\n%               can also be a cell array of the above (multiple subjects).\n% sliceorder  - slice acquisition order, a vector of integers, each\n%               integer referring the slice number in the image file\n%               (1=first), and the order of integers representing their\n%               temporal acquisition order\n%               OR vector containig the acquisition time for each slice\n%               in milliseconds\n% refslice    - slice for time 0\n%               OR time in milliseconds for the reference slice\n% timing      - additional information for sequence timing\n%               timing(1) = time between slices\n%                         = TA / (nslices - 1)\n%               timing(2) = time between last slices and next volume\n%                         = TR - TA\n%               OR timing = [0 TR] when previous inputs are specified in\n%               milliseconds\n% prefix      - filename prefix for corrected image files, defaults to 'a'\n%__________________________________________________________________________\n%\n%   Note: The sliceorder arg that specifies slice acquisition order is\n%   a vector of N numbers, where N is the number of slices per volume.\n%   Each number refers to the position of a slice within the image file.\n%   The order of numbers within the vector is the temporal order in which\n%   those slices were acquired.\n%\n%   To check the order of slices within an image file, use the SPM Display\n%   option and move the crosshairs to a voxel co-ordinate of z=1.  This\n%   corresponds to a point in the first slice of the volume.\n%\n%   The function corrects differences in slice acquisition times.\n%   This routine is intended to correct for the staggered order of\n%   slice acquisition that is used during echoplanar scanning. The\n%   correction is necessary to make the data on each slice correspond\n%   to the same point in time. Without correction, the data on one\n%   slice will represent a point in time as far removed as 1/2 the TR\n%   from an adjacent slice (in the case of an interleaved sequence).\n%\n%   This routine \"shifts\" a signal in time to provide an output\n%   vector that represents the same (continuous) signal sampled\n%   starting either later or earlier. This is accomplished by a simple\n%   shift of the phase of the sines that make up the signal.\n%\n%   Recall that a Fourier transform allows for a representation of any\n%   signal as the linear combination of sinusoids of different\n%   frequencies and phases. Effectively, we will add a constant\n%   to the phase of every frequency, shifting the data in time.\n%\n%   Shifter - This is the filter by which the signal will be convolved\n%   to introduce the phase shift. It is constructed explicitly in\n%   the Fourier domain. In the time domain, it may be described as\n%   an impulse (delta function) that has been shifted in time the\n%   amount described by TimeShift.\n%\n%   The correction works by lagging (shifting forward) the time-series\n%   data on each slice using sinc-interpolation. This results in each\n%   time series having the values that would have been obtained had\n%   the slice been acquired at the same time as the reference slice.\n%\n%   To make this clear, consider a neural event (and ensuing hemodynamic\n%   response) that occurs simultaneously on two adjacent slices. Values\n%   from slice \"A\" are acquired starting at time zero, simultaneous to\n%   the neural event, while values from slice \"B\" are acquired one\n%   second later. Without corection, the \"B\" values will describe a\n%   hemodynamic response that will appear to have began one second\n%   EARLIER on the \"B\" slice than on slice \"A\". To correct for this,\n%   the \"B\" values need to be shifted towards the Right, i.e., towards\n%   the last value.\n%\n% Written by Darren Gitelman at Northwestern U., 1998\n%\n% Based (in large part) on ACQCORRECT.PRO from G. Aguirre and E. Zarahn\n% at U. Penn.\n%\n% Modified by R. Henson, C. Buechel and J. Ashburner, FIL, to\n% handle different reference slices and memory mapping.\n%\n% Modified by M. Erb, at U. Tuebingen, 1999, to ask for non-continuous\n% slice timing and number of sessions.\n%\n% Modified by R. Henson for more general slice order and SPM2.\n%\n% Modified by A. Hoffmann, M. Woletz and C. Windischberger from Medical\n% University of Vienna, Austria, to handle multi-band EPI sequences.\n%__________________________________________________________________________\n% Copyright (C) 1998-2014 Wellcome Trust Centre for Neuroimaging\n\n% Darren Gitelman et al.\n% $Id: spm_slice_timing.m 6130 2014-08-01 17:41:18Z guillaume $\n\n\nSVNid = '$Rev: 6130 $';\n\n%-Say hello\n%--------------------------------------------------------------------------\nSPMid = spm('FnBanner',mfilename,SVNid);\n\n%-Parameters & Arguments\n%==========================================================================\nif nargin < 4, error('Not enough input arguments.'); end\nif nargin < 5, prefix = 'a'; end\n\nif ~iscell(P), P = {P}; end\nnsubjects = numel(P);\n\n% Acquisition order: 1=first slice in image\n% Reference slice: 1=first slice in image, in Analyze format, slice 1 = bottom\n% TR: Interscan interval (TR) {secs}\n% TA: Acquisition Time (TA) {secs} [Def: TR-TR/nslices], TA <= TR\n% timing(2) = TR - TA, time between last slices and next volume\n% timing(1) = TA / (nslices -1), time between slices\n\nVin     = spm_vol(P{1}(1,:));\nnslices = Vin(1).dim(3);\n\nTR      = (nslices-1)*timing(1)+timing(2);\nfprintf('%-40s: %30s\\n','Number of slices is...',num2str(nslices))      %-#\nfprintf('%-40s: %30s\\n','Time to Repeat (TR) is...',num2str(TR))        %-#\n\nif ~isequal(1:nslices,sort(sliceorder))\n    if ~all(sliceorder >= 0 & sliceorder <= TR*1000)\n        error('Input is neither slice indices nor slice times.');\n    end\n    unit = 'slice times (ms)';\nelse\n    if ~ismember(refslice,sliceorder)\n        error('Reference slice should contain a slice index.');\n    end\n    unit = 'slice indices';\nend\nfprintf('%-40s: %30s\\n','Parameters are specified as...',unit)          %-#\n\nif nslices ~= numel(sliceorder)\n    error('Mismatch between number of slices and length of ''sliceorder'' vector.');\nend\n\n%-Slice timing correction\n%==========================================================================\nfor subj = 1:nsubjects\n    Vin   = spm_vol(P{subj});\n    nimgo = numel(Vin);\n    nimg  = 2^(floor(log2(nimgo))+1);\n    if Vin(1).dim(3) ~= nslices\n        error('Number of slices differ: %d vs %d.', nslices, Vin(1).dim(3));\n    end\n        \n    % Create new header files\n    Vout  = Vin;\n    for k=1:nimgo\n        Vout(k).fname  = spm_file(Vin(k).fname, 'prefix', prefix);\n        if isfield(Vout(k),'descrip')\n            desc = [Vout(k).descrip ' '];\n        else\n            desc = '';\n        end\n        Vout(k).descrip = [desc 'acq-fix ref-slice ' num2str(refslice)];\n    end\n    Vout = spm_create_vol(Vout);\n    \n    % Set up [time x voxels] matrix for holding image info\n    slices = zeros([Vout(1).dim(1:2) nimgo]);\n    stack  = zeros([nimg Vout(1).dim(1)]);\n    \n    task = sprintf('Correcting acquisition delay: session %d', subj);\n    spm_progress_bar('Init',nslices,task,'planes complete');\n    \n    % Compute shifting amount from reference slice and slice order\n    if isequal(unit,'slice times (ms)')\n        % Compute time difference between the acquisition time of the\n        % reference slice and the current slice by using slice times\n        % supplied in sliceorder vector\n        shiftamount = (sliceorder - refslice) / (1000 * TR);\n    else\n        rslice      = find(sliceorder==refslice);\n        [Y, I]      = sort(sliceorder);\n        shiftamount = (I - rslice) * timing(1) / TR;\n    end\n    \n    % For loop to perform correction slice by slice\n    for k = 1:nslices\n        \n        % Read in slice data\n        B  = spm_matrix([0 0 k]);\n        for m=1:nimgo\n            slices(:,:,m) = spm_slice_vol(Vin(m),B,Vin(1).dim(1:2),1);\n        end\n        \n        % Set up shifting variables\n        len     = size(stack,1);\n        phi     = zeros(1,len);\n        \n        % Check if signal is odd or even -- impacts how Phi is reflected\n        %  across the Nyquist frequency. Opposite to use in pvwave.\n        OffSet  = 0;\n        if rem(len,2) ~= 0, OffSet = 1; end\n        \n        % Phi represents a range of phases up to the Nyquist frequency\n        % Shifted phi 1 to right.\n        for f = 1:len/2\n            phi(f+1) = -1*shiftamount(k)*2*pi/(len/f);\n        end\n        \n        % Mirror phi about the center\n        % 1 is added on both sides to reflect Matlab's 1 based indices\n        % Offset is opposite to program in pvwave again because indices are 1 based\n        phi(len/2+1+1-OffSet:len) = -fliplr(phi(1+1:len/2+OffSet));\n        \n        % Transform phi to the frequency domain and take the complex transpose\n        shifter = [cos(phi) + sin(phi)*sqrt(-1)].';\n        shifter = shifter(:,ones(size(stack,2),1)); % Tony's trick\n        \n        % Loop over columns\n        for i=1:Vout(1).dim(2)\n            \n            % Extract columns from slices\n            stack(1:nimgo,:) = reshape(slices(:,i,:),[Vout(1).dim(1) nimgo])';\n            \n            % Fill in continous function to avoid edge effects\n            for g=1:size(stack,2)\n                stack(nimgo+1:end,g) = linspace(stack(nimgo,g),...\n                    stack(1,g),nimg-nimgo)';\n            end\n            \n            % Shift the columns\n            stack = real(ifft(fft(stack,[],1).*shifter,[],1));\n            \n            % Re-insert shifted columns\n            slices(:,i,:) = reshape(stack(1:nimgo,:)',[Vout(1).dim(1) 1 nimgo]);\n        end\n        \n        % Write out the slice for all volumes\n        for p = 1:nimgo\n            Vout(p) = spm_write_plane(Vout(p),slices(:,:,p),k);\n        end\n        spm_progress_bar('Set',k);\n    end\n    spm_progress_bar('Clear');\nend\n\nfprintf('%-40s: %30s\\n','Completed',spm('time'))                        %-#\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_slice_timing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5746450487932521}}
{"text": "function x = r83p_sl ( n, a_lu, b, job, work2, work3, work4 )\n\n%*****************************************************************************80\n%\n%% R83P_SL solves a R83P system.\n%\n%  Discussion:\n%\n%    The R83P storage format stores a periodic tridiagonal matrix as\n%    a 3 by N array, in which each row corresponds to a diagonal, and\n%    column locations are preserved.  The matrix value\n%    A(1,N) is stored as the array entry A(3,N), and the matrix value\n%    A(N,1) is stored as the array entry A(1,1).\n%\n%    The linear system must have been factored by R83P_FA.\n%\n%  Example:\n%\n%    Here is how a R83P matrix of order 5 would be stored:\n%\n%      A51 A12 A23 A34 A45\n%      A11 A22 A33 A44 A55\n%      A21 A32 A43 A54 A15\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 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 at least 3.\n%\n%    Input, real A_LU(3,N), the LU factors from R83P_FA.\n%\n%    Input, real B(N), the right hand side of the linear system.\n%\n%    Input, integer JOB, specifies the system to solve.\n%    0, solve A * x = b.\n%    nonzero, solve A' * x = b.\n%\n%    Input, real WORK2(N-1), WORK3(N-1), WORK4, factor data from R83P_FA.\n%\n%    Output, real X(N), the solution to the linear system.\n%\n  x(1:n) = b(1:n);\n\n  if ( job == 0 )\n%\n%  Solve A1 * X1 = B1.\n%\n    x(1:n-1) = r83_np_sl ( n-1, a_lu, x, job );\n%\n%  X2 = B2 - A3 * X1\n%\n    x(n) = x(n) - a_lu(1,1) * x(1) - a_lu(3,n-1) * x(n-1);\n%\n%  Solve A4 * X2 = X2\n%\n    x(n) = x(n) / work4;\n%\n%  X1 := X1 - inverse ( A1 ) * A2 * X2.\n%\n    x(1:n-1) = x(1:n-1) - work2(1:n-1) * x(n);\n\n  else\n%\n%  Solve A1' * X1 = B1.\n%\n    x(1:n-1) = r83_np_sl ( n-1, a_lu, x, job );\n%\n%  X2 := X2 - A2' * B1\n%\n    x(n) = x(n) - a_lu(3,n) * x(1) - a_lu(1,n) * x(n-1);\n%\n%  Solve A4 * X2 = X2.\n%\n    x(n) = x(n) / work4;\n%\n%  X1 := X1 - transpose ( inverse ( A1 ) * A3 ) * X2.\n%\n    x(1:n-1) = x(1:n-1) - work3(1:n-1) * x(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/linplus/r83p_sl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594355, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.574645045777018}}
{"text": "function [matching, objective] = greedy_matching_rowwise(iou_matrix)\n  assert(size(iou_matrix, 1) <= size(iou_matrix, 2));\n  n = size(iou_matrix, 1);\n  matching = zeros(n, 1);\n  objective = 0;\n  for i = 1:n\n    % find max element int matrix\n % [max_per_row, max_col_per_row] = max(iou_matrix, [], 2);\n%       size(max_per_row)\n%       size( max_col_per_row)\n   [max_per_row, max_col_per_row] = max(iou_matrix')\n    [max_iou,row] = max(max_per_row);\n    if max_iou == -inf\n      break\n    end\n\n    objective = objective + max_iou;\n    col = max_col_per_row(row);\n    matching(row) = col;\n    iou_matrix(row,:) = -inf;\n    iou_matrix(:,col) = -inf;\n  end\nend\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/evaluation-metrics/maxRow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5746450438099842}}
{"text": "function F = acotd(F, varargin)\n%ACOTD   Inverse cotangent of a CHEBFUN, result in degrees.\n%   ACOTD(F) computes the inverse cotangent (in degrees) of the CHEBFUN F.\n%\n%   ACOTD(F, PREF) does the same but uses the CHEBFUNPREF object PREF when\n%   computing the composition.\n%\n% See also COTD, ACOT.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. See\n% http://www.chebfun.org/ for Chebfun information.\n\n% Call the compose method:\nF = compose(F, @acotd, varargin{:});\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/acotd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5746450407937506}}
{"text": "function [ value, x ] = randlc_jump ( x, k )\n\n%*****************************************************************************80\n%\n%% RANDLC_JUMP returns the K-th element of a uniform pseudorandom sequence.\n%\n%  Discussion:\n%\n%    The sequence uses the linear congruential generator:\n%\n%      X(K+1) = A * X(K)  mod 2^46\n%\n%    The K-th element, which can be represented as\n%\n%      X(K) = A^K * X(0)  mod 2^46\n%\n%    is computed directly using the binary algorithm for exponentiation.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    08 March 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    David Bailey, Eric Barszcz, John Barton, D Browning, Robert Carter, \n%    Leonardo Dagum, Rod Fatoohi,\n%    Samuel Fineberg, Paul Frederickson, Thomas Lasinski, Robert Schreiber, \n%    Horst Simon, V Venkatakrishnan, Sisira Weeratunga,\n%    The NAS Parallel Benchmarks,\n%    RNR Technical Report RNR-94-007,\n%    March 1994.\n%\n%    Donald Knuth,\n%    The Art of Computer Programming,\n%    Volume 2, Seminumerical Algorithms,\n%    Third Edition,\n%    Addison Wesley, 1997,\n%    ISBN: 0201896842,\n%    LC: QA76.6.K64.\n%\n%  Parameters:\n%\n%    Input, uint64 X, the initial seed (with index 0).  \n%\n%    Input, integer K, the index of the desired value.\n%\n%    Output, real VALUE, the K-th value in the sequence.\n%\n%    Output, uint64 X, the K-th seed.\n%\n  persistent a;\n  persistent a1;\n  persistent a2;\n  persistent ks;\n  persistent r23;\n  persistent r46;\n  persistent t23;\n  persistent t46;\n%\n%  If this is the first call, compute \n%\n%    R23 = 2 ^ -23, \n%    R46 = 2 ^ -46,\n%    T23 = 2 ^ 23, \n%    T46 = 2 ^ 46.  \n%\n%  These are computed in loops, rather than by merely using the power operator, \n%  in order to insure that the results are exact on all systems.  \n%\n  if ( isempty ( ks ) )\n\n    r23 = 1.0;\n    r46 = 1.0;\n    t23 = 1.0;\n    t46 = 1.0;\n\n    for i = 1 : 23\n      r23 = 0.5 * r23;\n      t23 = 2.0 * t23;\n    end\n\n    for i = 1 : 46\n      r46 = 0.5 * r46;\n      t46 = 2.0 * t46;\n    end\n\n    a = 1220703125.0;\n%\n%  Break A into two parts such that A = 2^23 * A1 + A2.\n%\n    t1 = r23 * a;\n    a1 = floor ( t1 );\n    a2 = a - t23 * a1;\n\n    ks = 1;\n\n  end\n\n  if ( k < 0 )\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'RANDLC_JUMP - Fatal error!\\n' );\n    fprintf ( 1, '  K < 0.\\n' );\n    error ( 'RANDLC_JUMP - Fatal error!' )\n\n  elseif ( k == 0 )\n\n%\n%  Find M so that K < 2^M.\n%\n  else\n\n    m = 1;\n    twom = 2;\n    while ( twom <= k )\n      twom = twom * 2;\n      m = m + 1;\n    end\n\n    b = a;\n    b1 = a1;\n    b2 = a2;\n\n    for i = 1 : m\n\n      j = floor ( k / 2 );\n%\n%  Replace X by A * X, if appropriate.\n%\n      if ( 2 * j ~= k )\n\n        t1 = r23 * x;\n        x1 = floor ( t1 );\n        x2 = x - t23 * x1;\n\n        t1 = b1 * x2 + b2 * x1;\n        t2 = floor ( r23 * t1 );\n        z = t1 - t23 * t2;\n\n        t3 = t23 * z + b2 * x2;\n        t4 = floor ( r46 * t3 );\n        x = t3 - t46 * t4;\n\n      end\n%\n%  Replace A by A * A mod 2^46.\n%\n      t1 = r23 * b;\n      x1 = floor ( t1 );\n      x2 = b - t23 * x1;\n\n      t1 = b1 * x2 + b2 * x1;\n      t2 = floor ( r23 * t1 );\n      z = t1 - t23 * t2;\n\n      t3 = t23 * z + b2 * x2;\n      t4 = floor ( r46 * t3 );\n      b = t3 - t46 * t4;\n%\n%  Update A1, A2.\n%\n      t1 = r23 * b;\n      b1 = floor ( t1 );\n      b2 = b - t23 * b1;\n\n      k = j;\n\n    end\n\n  end\n\n  value = r46 * 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/randlc/randlc_jump.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5746098018249554}}
{"text": "function [A, C, Q, R, initx, initV, LL] = ...\n    learn_kalman(data, A, C, Q, R, initx, initV, max_iter, diagQ, diagR, ARmode, constr_fun, varargin)\n% LEARN_KALMAN Find the ML parameters of a stochastic Linear Dynamical System using EM.\n%\n% [A, C, Q, R, INITX, INITV, LL] = LEARN_KALMAN(DATA, A0, C0, Q0, R0, INITX0, INITV0) fits\n% the parameters which are defined as follows\n%   x(t+1) = A*x(t) + w(t),  w ~ N(0, Q),  x(0) ~ N(init_x, init_V)\n%   y(t)   = C*x(t) + v(t),  v ~ N(0, R)\n% A0 is the initial value, A is the final value, etc.\n% DATA(:,t,l) is the observation vector at time t for sequence l. If the sequences are of\n% different lengths, you can pass in a cell array, so DATA{l} is an O*T matrix.\n% LL is the \"learning curve\": a vector of the log lik. values at each iteration.\n% LL might go positive, since prob. densities can exceed 1, although this probably\n% indicates that something has gone wrong e.g., a variance has collapsed to 0.\n%\n% There are several optional arguments, that should be passed in the following order.\n% LEARN_KALMAN(DATA, A0, C0, Q0, R0, INITX0, INITV0, MAX_ITER, DIAGQ, DIAGR, ARmode)\n% MAX_ITER specifies the maximum number of EM iterations (default 10).\n% DIAGQ=1 specifies that the Q matrix should be diagonal. (Default 0).\n% DIAGR=1 specifies that the R matrix should also be diagonal. (Default 0).\n% ARMODE=1 specifies that C=I, R=0. i.e., a Gauss-Markov process. (Default 0).\n% This problem has a global MLE. Hence the initial parameter values are not important.\n% \n% LEARN_KALMAN(DATA, A0, C0, Q0, R0, INITX0, INITV0, MAX_ITER, DIAGQ, DIAGR, F, P1, P2, ...)\n% calls [A,C,Q,R,initx,initV] = f(A,C,Q,R,initx,initV,P1,P2,...) after every M step. f can be\n% used to enforce any constraints on the params. \n%\n% For details, see\n% - Ghahramani and Hinton, \"Parameter Estimation for LDS\", U. Toronto tech. report, 1996\n% - Digalakis, Rohlicek and Ostendorf, \"ML Estimation of a stochastic linear system with the EM\n%      algorithm and its application to speech recognition\",\n%       IEEE Trans. Speech and Audio Proc., 1(4):431--442, 1993.\n\n\n%    learn_kalman(data, A, C, Q, R, initx, initV, max_iter, diagQ, diagR, ARmode, constr_fun, varargin)\nif nargin < 8, max_iter = 10; end\nif nargin < 9, diagQ = 0; end\nif nargin < 10, diagR = 0; end\nif nargin < 11, ARmode = 0; end\nif nargin < 12, constr_fun = []; end\nverbose = 1;\nthresh = 1e-4;\n\n\nif ~iscell(data)\n  N = size(data, 3);\n  data = num2cell(data, [1 2]); % each elt of the 3rd dim gets its own cell\nelse\n  N = length(data);\nend\n\nN = length(data);\nss = size(A, 1);\nos = size(C,1);\n\nalpha = zeros(os, os);\nTsum = 0;\nfor ex = 1:N\n  %y = data(:,:,ex);\n  y = data{ex};\n  T = length(y);\n  Tsum = Tsum + T;\n  alpha_temp = zeros(os, os);\n  for t=1:T\n    alpha_temp = alpha_temp + y(:,t)*y(:,t)';\n  end\n  alpha = alpha + alpha_temp;\nend\n\nprevious_loglik = -inf;\nloglik = 0;\nconverged = 0;\nnum_iter = 1;\nLL = [];\n\n% Convert to inline function as needed.\nif ~isempty(constr_fun)\n  constr_fun = fcnchk(constr_fun,length(varargin));\nend\n\n\nwhile ~converged & (num_iter <= max_iter) \n\n  %%% E step\n  \n  delta = zeros(os, ss);\n  gamma = zeros(ss, ss);\n  gamma1 = zeros(ss, ss);\n  gamma2 = zeros(ss, ss);\n  beta = zeros(ss, ss);\n  P1sum = zeros(ss, ss);\n  x1sum = zeros(ss, 1);\n  loglik = 0;\n  \n  for ex = 1:N\n    y = data{ex};\n    T = length(y);\n    [beta_t, gamma_t, delta_t, gamma1_t, gamma2_t, x1, V1, loglik_t] = ...\n\tEstep(y, A, C, Q, R, initx, initV, ARmode);\n    beta = beta + beta_t;\n    gamma = gamma + gamma_t;\n    delta = delta + delta_t;\n    gamma1 = gamma1 + gamma1_t;\n    gamma2 = gamma2 + gamma2_t;\n    P1sum = P1sum + V1 + x1*x1';\n    x1sum = x1sum + x1;\n    %fprintf(1, 'example %d, ll/T %5.3f\\n', ex, loglik_t/T);\n    loglik = loglik + loglik_t;\n  end\n  LL = [LL loglik];\n  if verbose, fprintf(1, 'iteration %d, loglik = %f\\n', num_iter, loglik); end\n  %fprintf(1, 'iteration %d, loglik/NT = %f\\n', num_iter, loglik/Tsum);\n  num_iter =  num_iter + 1;\n  \n  %%% M step\n  \n  % Tsum =  N*T\n  % Tsum1 = N*(T-1);\n  Tsum1 = Tsum - N;\n  A = beta * inv(gamma1);\n  %A = (gamma1' \\ beta')';\n  Q = (gamma2 - A*beta') / Tsum1;\n  if diagQ\n    Q = diag(diag(Q));\n  end\n  if ~ARmode\n    C = delta * inv(gamma);\n    %C = (gamma' \\ delta')';\n    R = (alpha - C*delta') / Tsum;\n    if diagR\n      R = diag(diag(R));\n    end\n  end\n  initx = x1sum / N;\n  initV = P1sum/N - initx*initx';\n\n  if ~isempty(constr_fun)\n    [A,C,Q,R,initx,initV] = feval(constr_fun, A, C, Q, R, initx, initV, varargin{:});\n  end\n  \n  converged = em_converged(loglik, previous_loglik, thresh);\n  previous_loglik = loglik;\nend\n\n\n\n%%%%%%%%%\n\nfunction [beta, gamma, delta, gamma1, gamma2, x1, V1, loglik] = ...\n    Estep(y, A, C, Q, R, initx, initV, ARmode)\n%\n% Compute the (expected) sufficient statistics for a single Kalman filter sequence.\n%\n\n[os T] = size(y);\nss = length(A);\n\nif ARmode\n  xsmooth = y;\n  Vsmooth = zeros(ss, ss, T); % no uncertainty about the hidden states\n  VVsmooth = zeros(ss, ss, T);\n  loglik = 0;\nelse\n  [xsmooth, Vsmooth, VVsmooth, loglik] = kalman_smoother(y, A, C, Q, R, initx, initV);\nend\n\ndelta = zeros(os, ss);\ngamma = zeros(ss, ss);\nbeta = zeros(ss, ss);\nfor t=1:T\n  delta = delta + y(:,t)*xsmooth(:,t)';\n  gamma = gamma + xsmooth(:,t)*xsmooth(:,t)' + Vsmooth(:,:,t);\n  if t>1 beta = beta + xsmooth(:,t)*xsmooth(:,t-1)' + VVsmooth(:,:,t); end\nend\ngamma1 = gamma - xsmooth(:,T)*xsmooth(:,T)' - Vsmooth(:,:,T);\ngamma2 = gamma - xsmooth(:,1)*xsmooth(:,1)' - Vsmooth(:,:,1);\n\nx1 = xsmooth(:,1);\nV1 = Vsmooth(:,:,1);\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/Kalman/learn_kalman.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256591565729, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5746080893304336}}
{"text": "function [gains]=lookup_gain_in_table(G,a_post,a_priori,a_post_range,a_priori_range,step);\n% function [gains]=lookup_gain_in_table(G,a_post,a_priori,a_post_range,a_priori_range,step);\n% This function selects the right gain value from the table G, given\n% vectors with a priori and a posteriori SNRs\n%\n% INPUT variables:\n% G: Matrix with gain values for speech DFT or magnitude estimation,\n% evaluated at all combinations of a priori and a posteriori SNR in the\n% input variables Rksi and Rgam. \n% \n%\n% a_priori: Array of \"a priori\" SNR (SNRprior) values for which values\n% have to be selected from the gain table   NOTE: The values must be in dBs.\n% a_post: Array of \"a posteriori\" SNR (SNRpost) values for which values\n% have to be selected from the gain table  NOTE: The values must be in dBs.\n%\n% a_post_range: The range of \"a posteriori\" SNR values\n%\n% a_priori_range: The range of \"a priori\" SNR values\n%\n% step: step is the stepsize in db's in the table\n%\n% OUTPUT variables:\n% gains: Matrix with gain values that are selected from the gain table G\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\n\n\na_prioridb=round(10*log10(a_priori)/step)*step;\na_postdb=round(10*log10(a_post)/step)*step;\n[Ia_post]=min(max(min(a_post_range),a_postdb), max(a_post_range));\nIa_post=Ia_post-min(a_post_range)+1;\nIa_post=Ia_post/step;\n[Ia_priori]=min(max(min(a_priori_range),a_prioridb), max(a_priori_range));\nIa_priori=Ia_priori-min(a_priori_range)+1;\nIa_priori=Ia_priori/step;\n\ngains=G(Ia_priori+(Ia_post-1)*length(G(:,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/27312-mmse-based-noise-psd-tracking-algorithm/TabGenGam/lookup_gain_in_table.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.5746080757501217}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Author: Eugenio Alcala Baselga\n% Date: 02/06/2018\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclassdef automatic_kinematic_control\n    \n    properties(Constant)\n        V_vec           = [1 18];  % Case of State FEedback LPV kinematic control\n%         V_vec           = [2 18]; % Case of MPC kinematic control\n\n        Theta_err_vec   = [deg2rad(-5) deg2rad(5)];\n        W_vec           = [-1.417 1.417];\n        gamma = 0.01;\n        Q               = [ 2    0     0;\n                            0    3     0;\n                            0    0    20];\n        R               = [ 0.5   0; \n                            0   0.001];\n    end\n    \n    methods\n    end\n    \nend\n\n", "meta": {"author": "euge2838", "repo": "Autonomous_Guidance_MPC_and_LQR-LMI", "sha": "33be5e39f4f1a1ed8e11e67506f471094f52f309", "save_path": "github-repos/MATLAB/euge2838-Autonomous_Guidance_MPC_and_LQR-LMI", "path": "github-repos/MATLAB/euge2838-Autonomous_Guidance_MPC_and_LQR-LMI/Autonomous_Guidance_MPC_and_LQR-LMI-33be5e39f4f1a1ed8e11e67506f471094f52f309/Kinematic parts/automatic_kinematic_control.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5746080703512123}}
{"text": "% Copyright (C) 2009 International Business Machines \n% All Rights Reserved.\n% This code is published under the Eclipse Public License.\n%\n% $Id: hs071_c.c 699 2006-04-05 21:05:18Z andreasw $\n%\n% Author:  Andreas Waechter               IBM    2009-04-02\n%\n% This file is part of the Ipopt tutorial.  It is a version with\n% mistakes for the matlab implemention of the coding exercise problem\n% (in AMPL formulation):\n%\n% param n := 4;\n%\n% var x {1..n} <= 0, >= -1.5, := -0.5;\n%\n% minimize obj:\n%   sum{i in 1..n} (x[i]-1)^2;\n%\n% subject to constr {i in 2..n-1}:\n%   (x[i]^2+1.5*x[i]-i/n)*cos(x[i+1]) - x[i-1] = 0;\n%\n% The constant term \"i/n\" in the constraint is supposed to be input data\n\nfunction [x, info] = TutorialMatlab\n\n  % Size of the problem\n  n = 5;\n\n  % Problem data\n  a = ((1:n)/n)';\n\n  % Starting point\n  x0 = -0.5*ones(n,1);\n\n  % Lower and upper bounds for the variables\n  options.lb = -1.5*ones(n,1);\n  options.ub = zeros(n,1);\n\n  % Constraint bounds\n  options.cl = zeros(n-2,1);\n  options.cu = zeros(n-2,1);\n\n  % Set the Ipopt options\n  % options.ipopt.mu_strategy = 'adaptive';\n  options.ipopt.derivative_test = 'second-order';\n  options.ipopt.max_iter = 10;\n\n  % Set the callback functions\n  funcs.objective         = @eval_f;\n  funcs.constraints       = @eval_g;\n  funcs.gradient          = @eval_grad_f;\n  funcs.jacobian          = @eval_jac_g;\n  funcs.jacobianstructure = @eval_jac_g_struct;\n  funcs.hessian           = @eval_hess;\n  funcs.hessianstructure  = @eval_hess_struct;\n\n  [x info] = ipopt(x0, funcs, options);\n \n \n  % End of main function\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % Evaluate value of objective function\n  function f = eval_f(x)\n\n    tmp = (x - 1).^2;\n    f = sum(tmp);\n\n  end\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % Evaluate gradient of objective function\n  function df = eval_grad_f(x)\n\n    df = (x - 1);\n\n  end\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % Evaluate value of constraint bodies\n  function g = eval_g(x)\n\n    g = (x(2:n-1).^2 + 1.5*x(1:n-2) - a(2:n-1)).*cos(x(3:n)) - x(1:n-2);\n\n  end\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % Return constraint Jacobian strcture\n  function A = eval_jac_g_struct\n\n    % tri-diagonal structure\n    Diags = ones(n, 3);\n    A = spdiags(Diags, 0:2, n-2, n);\n\n  end\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % Evaluate constraint Jacobian\n  function A = eval_jac_g(x)\n\n    Diags = -1*ones(n-2,3);\n    Diags(:,2) = (2*x(2:n-1)+1.5).*cos(x(3:n));\n    Diags(:,3) = -(x(2:n-1).^2 + 1.5*x(2:n-1) - a(2:n-1)).*sin(x(3:n));\n    A = spdiags(Diags, 0:2, n-2, n);\n\n  end\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % Return Hessian of Lagrangian function structure\n  function H = eval_hess_struct\n\n    Diags = ones(n, 2);\n    H = spdiags(Diags, -1:0, n, n);\n\n  end\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % Evaluate Hessian of Lagrangian function\n  function H = eval_hess(x, sigma, lambda)\n\n    Diags = zeros(n,2);\n\n    % part from the objective function\n    Diags(:,2) = sigma * 2;\n\n    % (x_i , x_i) part\n    Diags(2:n-1,2) = Diags(2:n-1,2) + lambda.*cos(x(3:n));\n\n    % (x_{i+1}, x_{i+1}) part\n    Diags(3:n,2) = Diags(3:n,2) ...\n      - lambda.*(x(2:n-1).^2 + 1.5*x(1:n-2) - a(2:n-1)).*cos(x(3:n));\n\n    % (x_i, x_{i+1}) part\n    Diags(2:n-1,1) = -lambda.*sin(x(3:n)).*(2*x(2:n-1)+1.5);\n\n    H = spdiags(Diags, -1:0, n, n);\n\n  end\n\nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/cpp/src/third-party/Ipopt-3.11.6/Ipopt/tutorial/CodingExercise/Matlab/2-mistake/TutorialMatlab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5746080540622188}}
{"text": "%% Copyright (C) 2016 Utkarsh Gautam\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see <http://www.gnu.org/licenses/>.\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defmethod @@sym besseljn (@var{alpha}, @var{x})\n%% Symbolic Spherical Bessel function of the first kind.\n%%\n%% Example:\n%% @example\n%% @group\n%% syms n x\n%% A = besseljn(n, x)\n%%   @result{} A = (sym) jn(n, x)\n%% diff(A)\n%%   @result{} ans = (sym)\n%%\n%%                      (n + 1)\u22c5jn(n, x)\n%%       jn(n - 1, x) - \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n%%                           x\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/besselyn, @@sym/besselj}\n%% @end defmethod\n\nfunction Y = besseljn(n, x)\n  if (nargin ~= 2)\n    print_usage ();\n  end\n  Y = elementwise_op ('jn', sym(n), sym(x));\nend\n\n\n%!test\n%! % roundtrip\n%! syms x\n%! A = double(besseljn(sym(2), sym(9)));\n%! q = besseljn(sym(2), x);\n%! h = function_handle(q);\n%! B = h(9);\n%! assert (abs (A - B) <= eps)\n\n%!error jn(sym('x'))\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/besseljn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5745678042186626}}
{"text": "function pass = test_spherefun( pref )\n\n% Grab some preferences\nif ( nargin == 0 )\n    pref = chebfunpref();\nend\ntol = 1e2*pref.techPrefs.chebfuneps;\n\n% Example 1\nf = ballfun(@(x,y,z)cos(x.*y));\ng = spherefun(f);\nh = spherefun(@(x,y,z)cos(x.*y));\npass(1) = norm(g-h) < tol;\n\n% Example 2\nf = ballfun(@(x,y,z)sin(z));\ng = spherefun(f, 0.5);\nh = spherefun(@(x,y,z)sin(0.5*z));\npass(2) = norm(g-h) < tol;\n\n% Example 3\nf = ballfun(@(x,y,z)x);\ng = f(10,:,:,'spherical');\nh = spherefun(@(x,y,z)10*x);\npass(3) = norm(g-h) < tol;\n\nif (nargout > 0)\n    pass = all(pass(:));\nend\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/ballfun/test_spherefun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.5745677996658702}}
{"text": "function [ i, j ] = i4mat_min_index ( m, n, a )\n\n%*****************************************************************************80\n%\n%% I4MAT_MIN_INDEX returns the location of the minimum of an I4AMT.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    04 November 2005\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, integer A(M,N), the M by N matrix.\n%\n%    Output, integer I, J, the indices of the minimum entry of A.\n%\n  i = -1;\n  j = -1;\n\n  for jj = 1 : n\n    for ii = 1 : m\n      if ( ii == 1 && jj == 1 )\n        i = ii;\n        j = jj;\n      elseif ( a(ii,jj) < a(i,j) )\n        i = ii;\n        j = jj;\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/i4lib/i4mat_min_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.5745677996658701}}
{"text": "function [dxdB dxdD dxdS dxdalpha dxdgParam] = gpsimXGradient(model, i, j)\n\n% GPSIMXGRADIENT ...\n%\n% COPYRIGHT : Pei Gao, 2008\n  \n% SHEFFIELDML\n\n% i: ti\n% j: jth gene\n\ndxdB = 1./model.D(j);\n\nendPoint = model.times_index(i);\n\ndxdD = 0;\ndxdS = 0;\ndxdalpha = [];\ndxdgParam = [];\n\nif model.ngParam > 0\n  ngParamk = model.ngParam/model.numGenes;\n  dxdgParam = zeros(1, ngParamk);\n  gInd = j;\nelse\n  gInd = 1;\nend\n\nfor m = 1:endPoint  \n    arg = model.t(i)-model.mapt(m);\n    if arg >= 0\n        dxdD = dxdD+model.g(m,gInd)*arg*exp(-model.D(j)*arg+log(model.step)+log(model.S(j)));\n        dxdS = dxdS+exp(-model.D(j)*arg+log(model.step))*model.g(m,gInd); % g=Sf\n      \n        if model.ngParam > 0\n          for gParamInd = 1:ngParamk\n            dxdgParam(gParamInd) = dxdgParam(gParamInd) + exp(- ...\n            model.D(j)*arg+log(model.step)+log(model.S(j)))*model.dg(m,gInd);\n          end\n        end\n    end\nend\n\ndxdD = -model.B(j)/(model.D(j)*model.D(j))-dxdD;\n\n% check if g(f) is different for each gene.\nif isfield(model, 'isGroupNonlinearity') && strcmp(model.nonLinearity{j}, ...\n                                                   'repression')\n      dxdalpha = exp(-model.D(j)*model.t(i));\n      dxdD = -model.t(i)*model.alpha(j)*exp(-model.D(j)*model.t(i))+dxdD;\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/gpsim/gpsimXGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5745649738520292}}
{"text": "%FINDHOMOGRAPHY  Finds a perspective transformation between two planes\n%\n%     H = cv.findHomography(srcPoints, dstPoints)\n%     [H, mask] = cv.findHomography(...)\n%     [...] = cv.findHomography(..., 'OptionName', optionValue, ...)\n%\n% ## Input\n% * __srcPoints__ Coordinates of the points in the original plane, a numeric\n%   array of size Nx2/1xNx2/Nx1x2 or cell array of 2-elements vectors\n%   `{[x,y], ...}` (single floating-point precision).\n% * __dstPoints__ Coordinates of the points in the target plane, of same size\n%   and type as `srcPoints`.\n%\n% ## Output\n% * __H__ 3x3 Homography matrix.\n% * __mask__ Nx1 mask array of same length as input points, indicates inliers\n%   (which points were actually used in the best computation of `H`).\n%\n% ## Options\n% * __Method__ Method used to compute a homography matrix. The following\n%   methods are possible:\n%   * __0__ a regular method using all the points, i.e. the least squares\n%     method (default)\n%   * __Ransac__ RANSAC-based robust method.\n%   * __LMedS__ Least-Median of squares robust method.\n%   * __Rho__ PROSAC-based robust method, introduced in [Bazargani15].\n%     (weighted RANSAC modification, faster in the case of many outliers).\n% * __RansacReprojThreshold__ Maximum allowed reprojection error to treat a\n%   point pair as an inlier (used in the RANSAC and RHO methods only). That\n%   is, if\n%   `|| dstPoints_i - convertPointsToHomogeneous(H*srcPoints_i) ||_2 > RansacReprojThreshold`\n%   then the point `i` is considered as an outlier. If `srcPoints` and\n%   `dstPoints` are measured in pixels, it usually makes sense to set this\n%   parameter somewhere in the range of 1 to 10. default 3.0.\n% * __MaxIters__ The maximum number of RANSAC iterations. default 2000\n% * __Confidence__ Confidence level, between 0 and 1. default 0.995\n%\n% The function finds and returns the perspective transformation `H` between\n% the source and the destination planes:\n%\n%     s_i * [x_i'; y_i'; 1] ~ H * [x_i; y_i; 1]\n%\n% so that the back-projection error:\n%\n%     sum_{i} (x_i' - (h11*x_i + h12*y_i + h13)/(h31*x_i + h32*y_i + h33))^2 +\n%             (y_i' - (h21*x_i + h22*y_i + h23)/(h31*x_i + h32*y_i + h33))^2\n%\n% is minimized. If the parameter method is set to the default value 0, the\n% function uses all the point pairs to compute an initial homography estimate\n% with a simple least-squares scheme.\n%\n% However, if not all of the point pairs `(srcPoints_i, dstPoints_i)` fit the\n% rigid perspective transformation (that is, there are some outliers), this\n% initial estimate will be poor. In this case, you can use one of the three\n% robust methods. The methods RANSAC, LMedS and RHO try many different\n% random subsets of the corresponding point pairs (of four pairs each,\n% collinear pairs are discarded), estimate the homography matrix using this\n% subset and a simple least-squares algorithm, and then compute the\n% quality/goodness of the computed homography (which is the number of inliers\n% for RANSAC or the least median re-projection error for LMedS). The best\n% subset is then used to produce the initial estimate of the homography matrix\n% and the mask of inliers/outliers.\n%\n% Regardless of the method, robust or not, the computed homography matrix\n% is refined further (using inliers only in case of a robust method) with\n% the Levenberg-Marquardt method to reduce the re-projection error even\n% more.\n%\n% The methods RANSAC and RHO handle practically any ratio of outliers but\n% need a threshold to distinguish inliers from outliers. The method LMedS\n% does not need any threshold but it works correctly only when there are\n% more than 50% of inliers. Finally, if there are no outliers and the noise\n% is rather small, use the default method (`Method=0`).\n%\n% The function is used to find initial intrinsic and extrinsic matrices.\n% Homography matrix is determined up to a scale. Thus, it is normalized so\n% that `h33 = 1`. Note that whenever an `H` matrix cannot be estimated, an\n% empty one will be returned.\n%\n% ## References\n% [Fischler81]:\n% > Fischler, M. A., and R. C. Bolles. \"Random sample consensus: A paradigm\n% > for model fitting with applications to image analysis and automated\n% > cartography\", Communications of the Association for Computing Machinery\n% > 24 (1981): 381-395.\n%\n% [Rousseeuw84]:\n% > Rousseeuw, P. J. \"Least median of squares regression\", Journal of the\n% > American Statistical Association, 79 (1984): 871-880.\n%\n% [Inui03]:\n% > Inui, K., S. Kaneko, and S. Igarashi. \"Robust Line Fitting using LMedS\n% > Clustering\", Systems and Computers in Japan 34 (2003): 92-100.\n%\n% [Bazargani15]:\n% > Hamid Bazargani, Olexa Bilaniuk, and Robert Laganiere. \"A fast and robust\n% > homography scheme for real-time planar target detection\". Journal of\n% > Real-Time Image Processing (2015): 1-20.\n%\n% See also: cv.getAffineTransform, cv.estimateAffine2D,\n% cv.estimateAffinePartial2D, cv.getPerspectiveTransform,\n% cv.estimateRigidTransform, cv.warpPerspective, cv.perspectiveTransform\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/findHomography.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199754937772, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5745649710715358}}
{"text": "function S = PMSAFinit(w0,mu,N,L,H,F,alpha,delta)\n\n% PMSAFinit        Initialize Parameter Structure for the PMSAF Algorithm\n%\n%                  Psuedo-QMF CMFB is Used by default, H and F are used otherwise\n% Arguments: \n% w0               Coefficients of FIR filter at start\n% mu               Step size\n% N                Number of subbands\n% L                length of analysis filter\n% M                length of adaptive weight vector\n% H                Analysis filter bank (optional), each column represents a filter\n% F                Synthesis filter bank (optional), each column represents a filter\n% alpha            Adjust scaling of tap weights \n% delta            Small constant\n\nif nargin > 4\n    if (size(H,2)~=N)||(size(F,2)~=N)\n        error('Columns of H (%d) or F (%d) not match with N = %d',size(H,2),size(F,2),N);\n    end\nelse\n% Defualt filter bank: Pseudo-QMF CMFB\n\n    [hopt,passedge] = opt_filter(L-1,N); % Generate prototype lowpass filter\n    [H,F] = make_bank(hopt,N);           % Generate filter banks using cosine modulation\n    H = sqrt(N)*H';                      % Analysis section\n    F = sqrt(N)*F';                      % Synthesis section\nend\n\nif nargin < 7 || isempty(alpha),         % Use default\n    alpha = 0;                           % Try -0.5\nend\n\nif nargin < 8 || isempty(delta),\n    delta = 1e-4;                        % Use default                 \nend\n\n\n% Assign structure fields\n\nS.coeffs        = w0(:);                 % Convert to column vector of length M\nS.step          = mu;                    % Step size\nS.analysis      = H;                     % Analysis filter\nS.synthesis     = F;                     % Synthesis filter\nS.iter          = 0;                     % Iteration count\nS.alpha         = alpha;                 % Tap weight scaling\nS.delta         = ones(1,N)*delta;       % Small positive constant\nS.AdaptStart    = L + length(w0);        % Running effect of analysis and adaptive filter, \n                                         %   minimum L+M\n     \n\n\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 5 -- Critically Sampled and Oversampled Subband Structures/PMSAFinit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5745649629134388}}
{"text": "classdef CEC2013_F2 < PROBLEM\n% <single> <real> <large>\n% Shifted Rastrigin's function\n\n%------------------------------- Reference --------------------------------\n% X. Li, K. Tang, M. N. Omidvar, Z. Yang, and K. Qin, Benchmark functions\n% for the CEC'2013 special session and competition on large-scale global\n% optimization, RMIT University, Australia, 2013.\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        Xopt;\t% Optimal decision vector\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2013.mat'),'Data');\n            obj.Xopt = Data{2};\n            obj.M    = 1;\n            obj.D    = 1000;\n            obj.lower    = zeros(1,obj.D) - 5;\n            obj.upper    = zeros(1,obj.D) + 5;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            PopObj = Rastrigin(Tdiag(Tasy(Tosz(PopDec-repmat(obj.Xopt,size(PopDec,1),1)),0.2),10));\n        end\n    end\nend\n\nfunction F = Rastrigin(X)\n    F = sum(X.^2-10*cos(2*pi*X)+10,2);\nend\n\nfunction Z = Tosz(X)\n    X1 = zeros(size(X));\n    X1(X~=0) = log(abs(X(X~=0)));\n    C1 = zeros(size(X)) + 5.5;\n    C1(X>0) = 10;\n    C2 = zeros(size(X)) + 3.1;\n    C2(X>0) = 7.9;\n    Z = sign(X).*exp(X1+0.049*(sin(C1.*X1)+sin(C2.*X1)));\nend\n\nfunction Z = Tasy(X,beta)\n    Z = X.^(1+repmat(beta*linspace(0,1,size(X,2)),size(X,1),1).*sqrt(X));\n    Z(X<=0) = X(X<=0);\nend\n\nfunction Z = Tdiag(X,alpha)\n    Z = X.*repmat(sqrt(alpha).^linspace(0,1,size(X,2)),size(X,1),1);\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/Single-objective optimization/CEC 2013/CEC2013_F2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5745649629134386}}
{"text": "function [data,units] = compute_min_wing_angle(trx,n)\n\nflies = trx.exp2flies{n};\nnflies = numel(flies);\ndata = cell(1,nflies);\nfor i = 1:nflies,\n  fly = flies(i);\n\n  % signed minimum: left wing will be negative, right wing positive\n  data{i} = min(-trx(fly).wing_anglel,trx(fly).wing_angler);\n  \nend\nunits = parseunits('rad');\n\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/compute_min_wing_angle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5745649627300556}}
{"text": "\n% Test whether it is necessary to rotate VB PCA\nfunction nc2010_vbpca_mlexperiment(flatW, rotate, ncomps)\n\nif nargin < 3\n  ncomps = 100;\nend\n\nrandn('state', 1);\nrand('state', 1);\n\n% Movie lens data with 100.000 ratings\nU = load('/share/bayes/data/jaakko/movielens/u.data');\n%Y = sparse(U(:,1), U(:,2), U(:,3));\n\n% Divide into training (90%) and test sets (10%)\nm = max(U(:,1));\nn = max(U(:,2));\ntestset = (rand(rows(U),1) < 0.1);\nYtrain = full(sparse(U(~testset,1), U(~testset,2), U(~testset,3),m,n));\nYtest = full(sparse(U(testset,1), U(testset,2), U(testset,3),m,n));\nYtrain(Ytrain==0) = nan;\nYtest(Ytest==0) = nan;\n\n%size(Ytrain)\n\nif flatW\n  disp('Using non-hierarchical flat prior for W');\n  stringW = 'flatW';\nelse\n  disp('Using hierarchical prior for W');\n  stringW = 'hierW';\nend\n\nfilename = sprintf(['/home/jluttine/matlab/neurocomputing2010/' ...\n                    'nc2010_vbpca_mlexperiment_%s_ncomps=%d_rotate=%d'], ...\n                   stringW, ncomps, rotate);\n\n\nresults = vbpcamv(Ytrain, ncomps, 'testset', Ytest, 'maxiters', 1e7, ...\n                  'rotate', rotate, 'startupdatehyper', 1, ...\n                  'startrotate', 1, 'autosavetime', 1, ...\n                  'autosavefile', filename, 'fixw', flatW);\n  \n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/publications/neurocomputing2010/nc2010_vbpca_mlexperiment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5745649573524519}}
{"text": "function ps = getSplitMergeFeatChoiceProbs( F, stateSeq, data_struct, model, jj, ki )\n%function ps = getSplitMergeFeatChoiceProbs( F, jj, ki )\nps = F(jj,:);\n\navailFeatIDs = find( F(jj,:) );\nrelFeatIDs = union( availFeatIDs, ki);\n\n%Ustats  = getStateSeqSuffStats_C1( stateSeq, F, data_struct, model, 1:size(F,1), 1:size(F,2) );\n%Ustats.Nkv = Ustats.Nkv(relFeatIDs,:);\n%myTheta = getTheta_PosteriorMean( myTheta, Ustats, model.obsModel, relFeatIDs );\n\nXstats = getXSuffStats( F, stateSeq, data_struct, model, 1:size(F,1),  relFeatIDs );\nmyTheta = setThetaToPosteriorMean(  [], Xstats, model.obsModel, relFeatIDs );\n        \n\nEPS = 1e-9;\nswitch model.obsModel.type\n    case 'Multinomial'\n        pHat = exp( myTheta.logp )';\n        pHat = bsxfun( @rdivide, pHat, sum(pHat,1) );\n        D = calcChiSqDistanceBetter( pHat(:,ki), pHat );\n    case 'Gaussian'\n        if size( myTheta.Mu, 1) > 1\n            D = pdist( myTheta.Mu, 'euclidean');        \n            D = squareform(D);\n            D = D(ki,:);\n        else\n            D = 0; % Default distance from self is zero.\n        end\n        D = D./(EPS+max(max(D)) ); % Ensure D varies from 0 to 1. \n        \n    case 'AR-Gaussian'\n        [D DR K] = size( myTheta.A );\n        \n        %Avec = -100*ones(K,D);\n        Avec = zeros(K, D*DR);\n        for kk = relFeatIDs\n            %Sig = myTheta.invSigma(:,:,kk) \\ eye(D);\n            %Avec(kk,:) = diag( Sig );\n            Avec(kk,:) = reshape( myTheta.A(:,:,kk), 1, D*DR );\n        end\n        if K > 1\n            D = pdist( Avec, 'euclidean');        \n            D = squareform(D);\n            D = D(ki,:);\n        else\n            D = 0; % Default distance from self is zero.\n        end\n        D = D./(EPS+max(max(D)) ); \n        % Ensure D varies from 0 to 1. \n        %  but is never quite 0 (must be at least EPS)\nend\n\nD( ~F(jj,:)  ) = Inf;\n\nps = 1 - D;\nps( ~F(jj,:) ) = 0;\n\nps = ps./sum( ps );\n\nif F( jj, ki ) && length( ps( ps>0 ) ) > 1\n    % If object jj possesses feature ki,\n    %    then let prob kj =ki = 2/3\n    %                  kj~=ki = 1/3 (unif. distrib. over all jj's feats)\n    ps( ki ) = 2*( sum( ps( [1:ki-1 ki+1:end] ) ) );\nend\n\nps = ps./sum(ps);\n\n% NOTE: Alternate distance metric\n%sig = eps+min(D(availFeatIDs));\n%ps = exp(-D./sig );\n\nend ", "meta": {"author": "michaelchughes", "repo": "NPBayesHMM", "sha": "22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd", "save_path": "github-repos/MATLAB/michaelchughes-NPBayesHMM", "path": "github-repos/MATLAB/michaelchughes-NPBayesHMM/NPBayesHMM-22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd/code/BPHMM/sampler/SplitMerge/getSplitMergeFeatChoiceProbs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5745649571690685}}
{"text": "function Gxy = femGreenKernel(X,Y,green,k)\n%+========================================================================+\n%|                                                                        |\n%|              OPENFEM - LIBRARY FOR FINITE ELEMENT METHOD               |\n%|           openFem is part of the GYPSILAB toolbox for Matlab           |\n%|                                                                        |\n%| COPYRIGHT : Matthieu Aussal & Francois Alouges (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%|             francois.alouges@polytechnique.edu                         |\n%| WEBSITE   : www.cmap.polytechnique.fr/~aussal/gypsilab    \u00a0\u00a0\u00a0\u00a0         |\n%|                                                                        |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it.                                                      |\n%|________________________________________________________________________|\n%|   '&`   |                                                              |\n%|    #    |   FILE       : femGreenKernel.m                              |\n%|    #    |   VERSION    : 0.55                                          |\n%|   _#_   |   AUTHOR(S)  : M. Aussal & F. Alouges & M. Averseng          |\n%|  ( # )  |   CREATION   : 14.03.2017                                    |\n%|  / 0 \\  |   LAST MODIF : 01.05.2019                                    |\n%| ( === ) |   SYNOPSIS   : Usefull green kernel functions                |\n%|  `---'  |                                                              |\n%+========================================================================+\n\n% Security\nif (size(X,2) ~= 3) || (size(Y,2) ~= 3)\n    error('femGreenKernel.m : unavailable case')\nend\nif isempty(k)\n    k = 0;\nend\n\n% Distances between particles\nRxy = sqrt( ...\n    (X(:,1) - Y(:,1)).^2 + ...\n    (X(:,2) - Y(:,2)).^2 + ...\n    (X(:,3) - Y(:,3)).^2 );\n\n% For empty wave-number\nif isempty(k)\n    k = 0;\nend\n\n% Green kernel definition\nif strcmp(green,'[1/r]')\n    Gxy = 1./Rxy;   \n    \nelseif strcmp(green,'dx[1/r]')\n    Gxy = - 1 ./ (Rxy.^3);\n    \nelseif strcmp(green,'dy[1/r]')\n    Gxy = 1 ./ (Rxy.^3);\n    \nelseif strcmp(green,'[exp(ikr)/r]')\n    Gxy = exp(1i*k*Rxy)./Rxy;          \n    \nelseif strcmp(green,'dx[exp(ikr)/r]')\n    Gxy = (1i*k - 1./Rxy) .* exp(1i*k.*Rxy) ./ (Rxy.^2);\n\nelseif strcmp(green,'dy[exp(ikr)/r]')\n    Gxy = - (1i*k - 1./Rxy) .* exp(1i*k.*Rxy) ./ (Rxy.^2);\n\nelseif strcmp(green(1:end-1),'gradx[1/r]')    \n    j = str2double(green(end));\n    Gxy = - (X(:,j)-Y(:,j)) ./ (Rxy.^3);\n    \nelseif strcmp(green(1:end-1),'grady[1/r]')     \n    j = str2double(green(end));\n    Gxy = (X(:,j)-Y(:,j)) ./ (Rxy.^3);    \n    \nelseif strcmp(green(1:end-1),'gradx[exp(ikr)/r]')  \n    j = str2double(green(end));\n    Gxy = (1i*k - 1./Rxy) .* exp(1i*k.*Rxy) .* ...\n        (X(:,j)-Y(:,j)) ./ (Rxy.^2);\n    \nelseif strcmp(green(1:end-1),'grady[exp(ikr)/r]')    \n    j = str2double(green(end));\n    Gxy = - (1i*k - 1./Rxy) .* exp(1i*k.*Rxy) .* ...\n        (X(:,j)-Y(:,j)) ./ (Rxy.^2);\n    \nelseif strcmp(green,'[log(r)]')\n    Gxy = log(Rxy);\n    \nelseif strcmp(green,'[H0(kr)]')\n    Gxy = besselh(0,k*Rxy);\n    \nelseif strcmp(green(1:end-1),'gradx[log(r)]')\n    j = str2double(green(end));\n    Gxy = (X(:,j)-Y(:,j)) ./ (Rxy.^2);    \n    \nelseif strcmp(green(1:end-1),'grady[log(r)]')\n    j = str2double(green(end));\n    Gxy = - (X(:,j)-Y(:,j)) ./ (Rxy.^2);    \n    \nelseif strcmp(green(1:end-1),'gradx[H0(kr)]')\n    j   = str2double(green(end));\n    Gxy = - k * besselh(1,k*Rxy) .* (X(:,j)-Y(:,j)) ./ Rxy;\n    \nelseif strcmp(green(1:end-1),'grady[H0(kr)]')\n    j   = str2double(green(end));\n    Gxy = k * besselh(1,k*Rxy) .* (X(:,j)-Y(:,j)) ./ Rxy;\n    \nelseif strcmp(green(1:end-2),'[ij/r+rirj/r^3]')        \n    i = str2double(green(end-1));\n    j = str2double(green(end));\n    Gxy = (i==j)./Rxy + (X(:,i)-Y(:,i)).*(X(:,j)-Y(:,j))./(Rxy.^3);\n    \nelseif strcmp(green(1:end-3),'[rirjrk/r^5]')      \n    i = str2double(green(end-2));\n    j = str2double(green(end-1));\n    k = str2double(green(end));    \n    Gxy = (X(:,i)-Y(:,i)).*(X(:,j)-Y(:,j)).*(X(:,k)-Y(:,k))./(Rxy.^5);\n    \nelse\n    error('Error in femGreenKernel.m : unknown green kernel')\nend\n\n% Singularity\nif strcmp(green,'[exp(ikr)/r]')\n    Gxy(Rxy<1e-12) = 0 + 1i*k;\nelseif strcmp(green,'[H0(kr)]')\n    gamma         = 0.5772156649;\n    Gxy(Rxy<1e-12) = 1 + 1i*(2/pi*(gamma+log(k/2)));    \nelse\n    Gxy(Rxy<1e-12) = 0;\nend\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/openFem/femGreenKernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.574546095135181}}
{"text": "function pval = lme_mass_LR(statsfull,statsred,q)\n% pval = lme_mass_LR(statsfull,statsred,q) \n%\n% Likelihood ratio test for the random effects. It can be used to test if a\n% model with q+1 random effects is significantly better than a model with q\n% random effects.\n%\n% Input\n% statsfull: Structure array containing statistiscs for every voxel/vertex\n% (see lme_FSfit for more details on these statistics) for the full \n% model (the one with q+1 random effects).\n% statsred: Structure array containing statistiscs for every voxel/vertex\n% for the reduced model (the one with q random effects).\n% q: Number of random effects in the reduced model.\n%\n% Output\n% pval: P-value of the test at each voxel/vertex (based on a 50:50 mixture  \n% of chi-squared distributions with q and q+1 degrees of freedom). \n%\n% $Revision: 1.2 $  $Date: 2015/01/06 17:14:55 $\n% Original Author: Jorge Luis Bernal Rusiel \n% CVS Revision Info:\n%    $Author: mreuter $\n%    $Date: 2015/01/06 17:14:55 $\n%    $Revision: 1.2 $\n% References: Bernal-Rusiel J.L., Greve D.N., Reuter M., Fischl B., Sabuncu\n% M.R., 2012. Statistical Analysis of Longitudinal Neuroimage Data with Linear \n% Mixed Effects Models, NeuroImage, doi:10.1016/j.neuroimage.2012.10.065.\n%\n\nif nargin < 3 \n    error('Too few inputs');   \nend;\n\nnv = length(statsfull);\npval = zeros(1,nv);\nfor i=1:nv\n    lrstats = lme_LR(statsfull(i).lreml,statsred(i).lreml,q);\n    pval(i) = lrstats.pval;\nend;\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/lme/mass_univariate/lme_mass_LR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5745460839308927}}
{"text": "function r8col_unique_count_test ( )\n\n%*****************************************************************************80\n%\n%% R8COL_UNIQUE_COUNT_TEST tests R8COL_UNIQUE_COUNT.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    17 July 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 3;\n  n = 15;\n\n  a = [ ...\n    2.0,  6.0, 10.0; ...\n    4.0,  8.0, 12.0; ...\n    1.0,  5.0,  9.0; ...\n    3.0,  7.0, 11.0; ...\n    2.0,  6.0,  0.0; ...\n    3.0,  4.0, 18.0; ...\n    0.0,  0.0,  0.0; ...\n    0.0,  6.0, 10.0; ...\n    2.0,  6.0, 10.0; ...\n    3.0,  7.0, 11.0; ...\n    2.0,  0.0, 10.0; ...\n    2.0,  6.0, 10.0; ...\n    1.0,  5.0,  9.0; ...\n    1.0,  5.0,  9.1; ...\n    1.0,  5.1,  9.0 ]';\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8COL_UNIQUE_COUNT_TEST\\n' );\n  fprintf ( 1, '  For an R8COL;\\n' );\n  fprintf ( 1, '  R8COL_UNIQUE_COUNT counts unique columns.\\n' );\n  fprintf ( 1, '\\n' );\n\n  r8mat_transpose_print ( m, n, a, '  The R8COL (transposed):' );\n\n  unique_num = r8col_unique_count ( m, n, a );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of unique columns is %d\\n', unique_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/r8lib/r8col_unique_count_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.5745460828295094}}
{"text": "%\n%CA driver\n%\n%forest fire\n\nclf\nclear all\n\nn=100;\n\nPlightning = .000005;\nPgrowth = .01; %.01\n\nz=zeros(n,n);\no=ones(n,n);\nveg=z;\nsum=z;\n\n\nimh = image(cat(3,z,veg*.02,z));\nset(imh, 'erasemode', 'none')\naxis equal\naxis tight\n \n% burning -> empty\n% green -> burning if one neigbor burning or with prob=f (lightning)\n% empty -> green with prob=p (growth)\n% veg = {empty=0 burning=1 green=2}\nfor i=1:3000\n    %nearby fires?\n    \n     sum = (veg(1:n,[n 1:n-1])==1) + (veg(1:n,[2:n 1])==1) + ...\n           (veg([n 1:n-1], 1:n)==1) + (veg([2:n 1],1:n)==1) ;\n \n    veg = ...\n         2*(veg==2) - ((veg==2) & (sum>0 | (rand(n,n)<Plightning))) + ...\n         2*((veg==0) & rand(n,n)<Pgrowth) ;\n     \n    set(imh, 'cdata', cat(3,(veg==1),(veg==2),z) )\n    drawnow\nend\n\n\n", "meta": {"author": "Eurus-Holmes", "repo": "Mathematical_Modeling", "sha": "cb9dd53af84ffbd455ec62ab89886351e0ec98d9", "save_path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling", "path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling/Mathematical_Modeling-cb9dd53af84ffbd455ec62ab89886351e0ec98d9/Cellular automaton/\u5143\u80de\u81ea\u52a8\u673a/1\u670813\u65e5\u8bfe\u4ef6\uff08\u5143\u80de\u81ea\u52a8\u673a\uff09/\u7a0b\u5e8f/forest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5745460790902271}}
{"text": "%%*******************************************************************\n%% randinfsdp.m : creates random infeasible SDP problems with various block\n%%                diagonal structures. \n%%\n%% [blk,Avec,C,b,X0,y0,Z0] = \n%%      randinfsdp(dense_blk,sparse_blk,diag_blk,m,infeas,solve);\n%%\n%% E.g.\n%%      randinfsdp([32 20],[10 5],100,10,infeas,solve);\n%%\n%%  dense_blk : for generating dense blocks, where\n%%              dense_blk(i) is the dimension of the ith block\n%%  sparse_blk: for generating a sparse block of small subblocks, where \n%%              sparse_blk(i) is the size of the ith subblock.\n%%  diag_blk: for generating a column vector of length specified by \n%%            diag_blk (this corresponds to a diagonal block). \n%%\n%%  infeas = 1 if want primal infeasible pair of problems\n%%         = 2 if want dual infeasible pair of problems\n%%\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] = ...\n                randinfsdp(dense_blk,sparse_blk,diag_blk,m,infeas,solve);\n\n   if nargin < 6; solve = 0; end;\n   if nargin < 5; error(' insufficient number of inputs '); end;   \n   if all(infeas-[1 2]); \n      error(' infeas must be 1 or 2 ');\n   end\n\n   blk = [];\n   if ~isempty(dense_blk);  \n      for k = 1:length(dense_blk); \n          blk{k,1} = 's';  blk{k,2} = dense_blk(k);\n      end; \n   end;\n   if ~isempty(sparse_blk); \n      if size(sparse_blk,1) > size(sparse_blk,2); sparse_blk = sparse_blk'; end; \n      tmp = size(blk,1); \n      blk{tmp+1,1} = 's';  \n      blk{tmp+1,2} = sparse_blk; \n   end;\n   if ~isempty(diag_blk); \n      tmp = size(blk,1); \n      blk{tmp+1,1} = 'l';        \n      blk{tmp+1,2} = diag_blk;  \n   end; \n   N = size(blk,1); \n\n   if (infeas == 1),\n%%\n%% primal infeasible\n%%\n%% generate infeasibility certificate Zi and Z0\n%%\n   tmp_sp = sparse(sum(sparse_blk));  \n   for L = 1:2,\n       T = [];\n       if ~isempty(dense_blk); \n          for k = 1:length(dense_blk);\n              n = dense_blk(k); \n              tmp = randn(n); \n              tmp = tmp*tmp'; \n              tmp = 0.5*(tmp + tmp');\n              %mineig = min(real(eig(tmp)));\n              %if (mineig < 0); tmp = tmp - 1.1*mineig*eye(n); end;\n              T{k,1} = tmp; \n          end;\n       end;\n       if ~isempty(sparse_blk); \n          for k = 1:length(sparse_blk);\n              n = sparse_blk(k);\n              pos = [sum(sparse_blk(1:k-1))+1 : sum(sparse_blk(1:k))]; \n              tmp = randn(n);  \n              tmp = tmp*tmp'; \n              tmp = 0.5*(tmp + tmp');\n              %mineig = min(real(eig(tmp)));\n              %if (mineig < 0); tmp = tmp - 1.1*mineig*eye(n); end;\n              tmp_sp(pos,pos) = sparse(tmp); \n          end; \n          T{size(T,1)+1,1} = tmp_sp; \n       end;\n       if ~isempty(diag_blk);           \n          tmp = randn(diag_blk,1); \n          tmp = tmp.*tmp;\n          %mineig = min(tmp);\n          %if (mineig < 0); tmp = tmp - 1.1*mineig*ones(diag_blk,1); end;\n          T{size(T,1)+1,1} = tmp; \n       end; \n       if (L == 1);  Zi = T; else; Z0 = T; end;\n   end;\n%%\n%% set up the matrices Ak and b\n%%\n   A  = cell(N,m);  \n   Ak_sp = sparse(sum(sparse_blk),sum(sparse_blk)); \n   for k = 1:m;\n       Ak = []; \n       if ~isempty(dense_blk); \n          for j = 1:length(dense_blk); \n              tmp = randn(dense_blk(j)); tmp = 0.5*(tmp+tmp');\n              Ak{j,1} = tmp;\n          end;\n       end;\n       if ~isempty(sparse_blk);   \n          for j = 1:length(sparse_blk);\n              n = sparse_blk(j);\n              tmp = randn(n); tmp = 0.5*(tmp+tmp');\n              pos = [sum(sparse_blk(1:j-1))+1 : sum(sparse_blk(1:j))]; \n              Ak_sp(pos,pos) = tmp; \n          end;\n          Ak{size(Ak,1)+1,1} = Ak_sp; \n       end;\n       if ~isempty(diag_blk);  \n          Ak{size(Ak,1)+1,1} = randn(diag_blk,1); \n       end;\n       A(:,k) = Ak;\n   end;\n\n   y = ones(m,1);\n   SAZm = ops(ops(Zi,'+',Asum(blk,A,y)),'/',m);\n   SAZm = ops(ops(SAZm,'+',ops(SAZm,'transpose')),'*',0.5);\n   yi  = randn(m,1);\n   for k = 1:m,\n      Ak = A(:,k);\n      Ak = ops(ops(Ak,'-',SAZm),'/',yi(k));\n      Ak = ops(ops(Ak,'+',ops(Ak,'transpose')),'*',0.5);\n      A(:,k) = Ak;\n   end;\n   b = randn(m,1);\n   if (b'*yi < 0), b = -b; end;\n   y0  = randn(m,1);\n   C = ops(Z0,'+',Asum(blk,A,y0));\n   C = ops(ops(C,'+',ops(C,'transpose')),'*',0.5);\n%%\n%% (yi,Zi) is a primal infeasibility certificate\n%%\n   elseif (infeas == 2),\n%%\n%% dual infeasible\n%%\n%% generate infeasibility certificate Xi, positive definite X0, and C\n%%\n   tmp_sp_Xi  = sparse(sum(sparse_blk));\n   tmp_sp_X0 = sparse(sum(sparse_blk));\n   tmp_sp_C   = sparse(sum(sparse_blk));\n   Xi = [];\n   X0 = [];\n   C  = [];\n       if ~isempty(dense_blk);\n          for k = 1:length(dense_blk);\n              n = dense_blk(k);\n              tmp = randn(n); \n              tmp = tmp*tmp'; \n              tmp = 0.5*(tmp + tmp');\n              %mineig = min(real(eig(tmp)));\n              %if (mineig < 0); tmp = tmp - 1.1*mineig*eye(n); end;\n              Xi{k,1} = tmp;\n              tmp = randn(n); \n              tmp = tmp*tmp'; \n              tmp = 0.5*(tmp + tmp');\n              %mineig = min(real(eig(tmp)));\n              %if (mineig < 0); tmp = tmp - 1.1*mineig*eye(n); end;\n              X0{k,1} = tmp;\n              tmp = randn(n); tmp = 0.5*(tmp + tmp');\n              C{k,1} = tmp;\n          end;\n       end;\n       if ~isempty(sparse_blk);\n          for k = 1:length(sparse_blk);\n              n = sparse_blk(k);\n              pos = [sum(sparse_blk(1:k-1))+1 : sum(sparse_blk(1:k))];\n              tmp = randn(n);  \n              tmp = tmp*tmp'; \n              tmp = 0.5*(tmp + tmp');\n              %mineig = min(real(eig(tmp)));\n              %if (mineig < 0); tmp = tmp - 1.1*mineig*eye(n); end;\n              tmp_sp_Xi(pos,pos) = sparse(tmp);\n              tmp = randn(n);  \n              tmp = tmp*tmp'; \n              tmp = 0.5*(tmp + tmp');\n              %mineig = min(real(eig(tmp)));\n              %if (mineig < 0); tmp = tmp - 1.1*mineig*eye(n); end;\n              tmp_sp_X0(pos,pos) = sparse(tmp);\n              tmp = randn(n);  tmp = 0.5*(tmp + tmp');\n              tmp_sp_C(pos,pos) = sparse(tmp);\n          end;\n          Xi{size(Xi,1)+1,1} = tmp_sp_Xi;\n          X0{size(X0,1)+1,1} = tmp_sp_X0;\n          C{size(C,1)+1,1}   = tmp_sp_C;\n       end;\n       if ~isempty(diag_blk);\n          n = diag_blk;\n          tmp = randn(n,1); \n          tmp = tmp.*tmp;\n          %mineig = min(tmp);\n          %if (mineig < 0); tmp = tmp - 1.1*mineig*ones(n,1); end;\n          Xi{size(X0,1)+1,1} = tmp;\n          tmp = randn(n,1); \n          tmp = tmp.*tmp;\n          %mineig = min(tmp);\n          %if (mineig < 0); tmp = tmp - 1.1*mineig*ones(n,1); end;\n          X0{size(X0,1)+1,1} = tmp;\n          tmp = randn(n,1);\n          C{size(C,1)+1,1} = tmp;\n       end;\n%%\n%% set up the matrices Ak and b\n%%\n   trXX = blktrace(blk,Xi,Xi);\n   A  = cell(N,m);\n   Ak_sp = sparse(sum(sparse_blk),sum(sparse_blk));\n   b = ones(m,1);\n   for k = 1:m;\n       Ak = [];\n       if ~isempty(dense_blk);\n          for j = 1:length(dense_blk);\n              n = dense_blk(j);\n              Aj  = randn(n);\n              Ak{j,1} = (Aj + Aj')/2;\n          end;\n       end;\n       if ~isempty(sparse_blk);\n          for j = 1:length(sparse_blk);\n              pos = [sum(sparse_blk(1:j-1))+1 : sum(sparse_blk(1:j))];\n              n = sparse_blk(j);\n              Aj  = randn(n);\n              Ak_sp(pos,pos) = (Aj + Aj')/2;\n          end;\n          Ak{size(Ak,1)+1,1} = Ak_sp;\n       end;\n       if ~isempty(diag_blk);\n          n = diag_blk;\n          Ak{size(Ak,1)+1,1} = randn(n,1);\n       end;\n       trAX = blktrace(blk,Ak,Xi);\n       Ak = ops(Ak,'-',ops(Xi,'*',(trAX/trXX)));\n       Ak = ops(ops(Ak,'+',ops(Ak,'transpose')),'*',0.5);\n       A(:,k) = Ak;\n       b(k) = blktrace(blk,Ak,X0);\n   end;\n   if (blktrace(blk,C,Xi) > 0), C = ops(C,'*',-1); end;\n%%\n%% Xi is a dual infeasibility certificate\n%%\n   end;\n\n%%\n%% infeasible initial iterate\n%%\n   Avec = svec(blk,A,ones(size(blk,1),1));    \n   [X0,y0,Z0] = infeaspt(blk,Avec,C,b);    \n%%\n   if solve; \n      [obj,X,y,Z] = sqlp(blk,Avec,C,b,[],X0,y0,Z0);\n   end; \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/sdpt3/Examples/randinfsdp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5745460735968658}}
{"text": "function [yn,en,S] = LMSadapt_dec(un,S)\n\n% LMSadapt_dec      LMS Algorithm for Decision-Directed Channel Equalization\n%\n%                   The history of output, squared error and coefficients \n%                   of FIR filter are passed to calling function. \n%                   Only for decision-directed mode channel equalization\n%\n% Arguments:\n% un                Input signal\n% S                 Adptive filter parameters as defined in LMSinit.m\n% yn                History of output signal\n% en                History of error signal\n%\n% by Lee, Gan, and Kuo, 2008\n% Subband Adaptive Filtering: Theory and Implementation\n% Publisher: John Wiley and Sons, Ltd\n\nM = length(S.coeffs);               % Length of FIR filter\nmu = S.step;                        % Step size mu\nleak = S.leakage;                   % Leaky factor\nw = S.coeffs;                       % Weight vector of FIR filter\nu = zeros(M,1);                     % Input signal vector\n\nITER = length(un);                  % Length of input sequence\nyn = zeros(1,ITER);                 % Initialize output sequence to zero\nen = zeros(1,ITER);                 % Initialize error sequence to zero\n\nif isfield(S,'unknownsys')\n    b = S.unknownsys;\n    norm_b = norm(b);\n    eml = zeros(1,ITER);\n    ComputeEML = 1;\nelse\n    ComputeEML = 0;\nend\n\nfor n = 1:ITER    \n    u = [un(n); u(1:end-1)];         % Input signal vector [u(n),u(n-1),...,u(n-M+1)]'\n    yn(n) = w'*u;                    % Output signal\n    dn(n) = sign(yn(n));             % Only for decision directed mode channel equalizer\n    en(n) = dn(n) - yn(n);           % Estimation error\n    w = (1-mu*leak)*w + (mu*en(n))*u;% Tap-weight adaptation\n    S.iter = S.iter + 1;\nend\n\nS.coeffs = w;                        % Coefficient values at the final iteration\nif ComputeEML == 1;\n    S.eml = eml;\nend\n\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/Common Code/LMSadapt_dec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5745460733793009}}
{"text": "% This script provides a tutorial application of the Gaussian-Copula Mutual\n% Information (GCMI) estimator with a 2 category discrete stimulus (face \n% vs noise images) event-related EEG data set.\n\n% This script uses cell mode - cells are delimited by %% lines and can \n% be run with:\n% ctrl-enter (windows, linux) or cmd-enter (mac)\n% or \"Run Section\" button from the toolbar \n% or right click -> Evaluate currect section\n\n% You need the gcmi/matlab directory on your matlab path.\n% If you are running from the gcmi project tree you can add this with the\n% following command:\n% addpath('../matlab')\n\n% Questions / comments : robince@gmail.com\n\n%% Download and load data\n\n% this will attempt to download the eeg data from the internet (~210MB)\n% alternatively you can download the file eeg_face_vs_noise.mat manually\n% and place it in the same directory as this script\nfname = 'eeg_face_vs_noise.mat';\ndata_url = ['https://www.robince.net/data/gcmi/data/' fname];\n\n% checks for data in current working directory\nif ~exist(fname)\n    disp(sprintf('Downloading %s ...', data_url))\n    websave(fname,data_url);\n    disp('Done.')\nend\n\nload(fname);\n% csddat : [channels x time x trials]\n% permute to trials first axis for looping\ncsddat = permute(csddat, [3 1 2]);\n[Ntrl, Nch, Nt] = size(csddat);\n\n% stim : stimulus class on each trial (0, 1)\n\n%% Calculate GCMI at a specific sensor and time point\n\n% this is the strongest effect\nchi = 41;\nti = 168;\n\n% for a t-test we contrast the data from the two classes\nfaceeeg = csddat(stim==0,chi,ti);\nnoiseeeg = csddat(stim==1,chi,ti);\n[h,p,ci,stats] = ttest2(faceeeg, noiseeeg, 'VarType', 'unequal');\nt = stats.tstat\n\n% for MI we use the stimulus labels for each trial\n% this works in the same way if there are more than 2 classes\n% Reminder: stim must take values 0 or 1\nI = gcmi_model_cd(csddat(:,chi,ti), stim, 2)\n\n\n%% Calculate GCMI across all sensors and time point\n\n% following the commonly used mass-univeriate approach we repeat \n% the calculation above for each sensor and time point\n% we could call gcmi_cd as above inside the loop, but here we first\n% normalise the data separately so we can reuse it for the permutation\n% testing\n\n% Gaussian-copula normalisation, works along first axis, applied to each \n% other dimension independently\nceeg = copnorm(csddat);\nIeeg = zeros(Nch,Nt);\nfor ti=1:Nt\n    for chi=1:Nch\n        % as the data has been copula-normalised we can use the \n        % Gaussian parametric estimator (whatever the distribution was\n        % originally)\n        Ieeg(chi,ti) = mi_model_gd(ceeg(:,chi,ti), stim, 2, true, true);\n    end\nend\n\nfigure\nimagesc(time,[],Ieeg)\nxlabel('Time')\nylabel('Channels')\n\n%% Permutation test for signifiance with the method of maximum statistics\nNperm = 100;\n\n% to reduce computation time, we consider a single time point here - the\n% same method should normally be applied over all sensors and time points\nti = 168;\nI = Ieeg(:,ti);\nIperm = zeros(Nch,Nperm);\nfor pi=1:Nperm\n    idx = randperm(Ntrl);\n    % randomly permute stimulus labels\n    pstim = stim(idx);\n    % repeat mass-univariate MI calculation\n    for chi=1:Nch\n        Iperm(chi,pi) = mi_model_gd(ceeg(:,chi,ti), pstim, 2, true, true);\n    end\nend\n\n% method of maximum statistics\n% maximum values across permutations\nImax = max(Iperm,[],1);\nthresh = prctile(Imax, 99);\nIsig = I>thresh;\n\n% if you have eeglab we can plot the topologies\nif exist('topoplot')\n    figure\n    subplot(1,2,1)\n    topoplot(I, chanlocs, 'maplimits', [0 max(I)]);\n    title(sprintf('MI, t = %d ms', time(ti)))\n    colorbar\n    \n    subplot(1,2,2)\n    topoplot(Isig, chanlocs, 'maplimits', [0 1])\n    title(sprintf('MI, p<0.01, t = %d ms', time(ti)));\n    colorbar\n    \n    colormap parula    \nend\n\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/gcmi/matlab_examples/discrete_eeg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5745270816011723}}
{"text": "% DURATION_FEATURE Calculate the log-duration of an object\n%\n% Usage\n%    duration = DURATION_FEATURE(x, object)\n%\n% Input\n%    x (numeric): The file data (not used).\n%    object (struct): The objects contained in the data.\n%\n% Output\n%    duration (numeric): The log-duration of the objects.\n%\n% See also\n%    PREPARE_DATABASE\n\nfunction t = duration_feature(x, object)\n\tt = permute(log([object.u2]-[object.u1]+1),[1 3 2]);\nend\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/classification/duration_feature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5745270778962976}}
{"text": "function FtI = warped_img_inv(I,u,v)\n\n[M,N] = size(I);\n\n% Stack the motion field into vector\nvectors = zeros(length(xPos),2);\nvectors(:,1) = u(sub2ind(size(u),yPos,xPos));\nvectors(:,2) = v(sub2ind(size(u),yPos,xPos));\n\n% Calculate frame2to1\n[xPosv, yPosv] = meshgrid(1:1:n_size(2),1:1:n_size(1));\n% vectors_full is the full size motion field\nvectors_full = zeros(n_size(1),n_size(2),2);\nvectors_full(:,:,1) = u;\nvectors_full(:,:,2) = v;\n\nxPosv = xPosv+vectors_full(:,:,1);\nyPosv = yPosv+vectors_full(:,:,2);\nxPosv = reshape(xPosv,n_size(1),n_size(2));\nyPosv = reshape(yPosv,n_size(1),n_size(2));\n\nxPosv(xPosv <= 1) = 1;\nyPosv(yPosv <= 1) = 1;\nxPosv(xPosv >= n_size(2)) = n_size(2);\nyPosv(yPosv >= n_size(1)) = n_size(1);\n\nFtI = interp2(I,xPosv,yPosv,'cubic');", "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/warped_img_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.6442251064863698, "lm_q1q2_score": 0.574527065712971}}
{"text": "function [trl] = ft_trialfun_emgdetect(cfg)\n\n% Note that there are some parameters, like the EMG channel name and the\n% processing that is done on the EMG channel data, which are hardcoded in\n% this trial function. You should change these parameters if necessary.\n\n% read the header and determine the channel number corresponding with the EMG\nhdr         = ft_read_header(cfg.headerfile);\nchanindx    = strmatch('EMGlft', hdr.label);\n\nif length(chanindx)>1\n  error('only one EMG channel supported');\nend\n\n% read all data of the EMG channel, assume continuous file format\nemg = ft_read_data(cfg.datafile, 'header', hdr, ...\n              'begsample', 1, 'endsample', hdr.nSamples*hdr.nTrials, ...\n              'chanindx', chanindx, 'checkboundary', false);\n\n% apply filtering, hilbert transformation and boxcar convolution (for smoothing)\nemgflt      = ft_preproc_highpassfilter(emg, hdr.Fs, 10); % highpassfilter\nemghlb      = abs(hilbert(emgflt')');                     % hilbert transform\nemgcnv      = conv2([1], ones(1,hdr.Fs), emghlb, 'same'); % smooth using convolution\nemgstd      = ft_preproc_standardize(emgcnv, 2);          % z-transform, i.e. mean=0 and stdev=1\nemgtrl      = emgstd>0;                                   % detect the muscle activity\nemgtrl      = diff(emgtrl, [], 2);\n\nemgon       = find(emgtrl(:)== 1);\nemgoff      = find(emgtrl(:)==-1);\n\ntrl(:,1) = emgon (:) + hdr.Fs*0.5;  % as a consequence of the convolution with a one-second boxcar\ntrl(:,2) = emgoff(:) - hdr.Fs*0.5;  % as a consequence of the convolution with a one-second boxcar\ntrl(:,3) = 0;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/trialfun/ft_trialfun_emgdetect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5745098915083519}}
{"text": "function plot_bootfitloglike_a2(mycat,time,timef,bootloops,maepi)\n    % Plots Ncum (observed vs. modeled) for specified time windows (choose model for the learning period)\n    %\n    % plot_bootfitloglike_a2(mycat,time,timef,bootloops,ZG.maepi);\n    % --------------------------------------------------\n    % Plots Ncum observed vs. Ncum modeled for specified time windows\n    % with choosing the model for the learning period\n    % Input variables:\n    % mycat         : earthquake catalog\n    % time      : learning period fo fit Omori parameters [days]\n    % timef     : forecast period [days]\n    % bootloops : Number of bootstraps\n    % ZG.maepi     : mainshock\n    %\n    % J.Woessner, S. Wiemer\n\n%FIXME mCat ZG.maepi still treated as arrays\nreport_this_filefun();\n    % Surpress warnings from fmincon\n    % warning off;\n\n    if ~ensure_mainshock()\n        return\n    end\n    date_matlab = datenum(mycat.Date);\n    date_main = datenum(ZG.maepi.Date);\n    time_aftershock = date_matlab-date_main;\n\n% Select biggest aftershock earliest in time, but more than 1 day after mainshock\n    fDay = 1; %days\n    vSel = (mycat.Date > ZG.maepi.Date + days(fDay)) & mycat.Date<= ZG.maepi.Date+days(time);\n    mCat = mycat.subset(vSel);\n    vSel = mCat.Magnitude == max(mCat.Magnitude);\n    vBigAf = mCat(vSel,:);\n    if sum(vSel) > 1\n        vBigAf.sort('Date')\n        vBigAf = vBigAf.subset(1);\n    end\n    date_biga = datenum(vBigAf.Date);\n    fT1 = date_biga - date_main; % Time of big aftershock\n\n\n    % Aftershock times\n    l = time_aftershock(:) > 0;\n    tas = time_aftershock(l);\n    eqcatalogue = mycat.subset(l);\n\n    % time_as: Learning period\n    l = tas <= time;\n    time_as=tas(l);\n\n    % Times up to the forecast time\n    lf = tas <= time+timef ;\n    time_asf= [tas(lf) ];\n    time_asf=sort(time_asf);\n\n    % % Calculate p,c,k for dataset\n    % prompt  = {'Enter model number (1:pck, 2:pckk, 3:ppckk, 4:ppcckk:'};\n    % title   = 'Model selection for fitting aftershock sequence';\n    % lines= 1;\n    % def     = {'1'};\n    % answer  = inputdlg(prompt,title,lines,def);\n    % nMod = str2double(answer{1});\n    % Calculate fits of different models\n    % see OmoriModel for enumaration details\n\n    MOL_models = sort(enumeration('OmoriModel'));\n\n    mRes = [];\n    % Modified Omori law (pck)\n\n    for nMod=1:numel(MOL_models) % do this for each model\n        [pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL] = bruteforceloglike_a2(time_as, fT1, MOL_models(nMod));\n        mRes(nMod,:) = [nMod, pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL];\n    end\n\n    % Select best fitting model by AIC\n    vSel = (mRes(:,8)==min(mRes(:,8)));\n    mRes = mRes(vSel,:);\n    if length(mRes(:,1)) > 1\n        vSel = (mRes(:,1)==min(mRes(:,1)));\n        mRes = mRes(vSel,:);\n    end\n    % Model to use for bootstrapping as of lowest AIC to observed data\n    nMod = OmoriModel(mRes(1,1));\n    pval1= mRes(1,2); \n    pval2= mRes(1,3);\n    cval1= mRes(1,4); \n    cval2= mRes(1,5);\n    kval1= mRes(1,6); \n    kval2= mRes(1,7);\n\n    % Calculate goodness of fit with KS-Test and RMS\n    [H,P,KSSTAT,fRMS] = calc_llkstest_a2(time_as,fT1,pval1, pval2, cval1, cval2, kval1, kval2, nMod);\n\n    % Calculate uncertainty and mean values of p,c,and k\n    [mMedModF, mStdL, loopout] = brutebootloglike_a2(time_as, time_asf, bootloops,fT1,nMod);\n    pmed1 = mMedModF(1,1);\n    pmed2 = mMedModF(1,3);\n    cmed1 = mMedModF(1,5);\n    cmed2 = mMedModF(1,7);\n    kmed1 = mMedModF(1,9);\n    kmed2 = mMedModF(1,11);\n\n    % Start plotting\n    if (~isnan(pval1) && ~isnan(pval2))\n\n        figure_w_normalized_uicontrolunits('Numbertitle','off','Name','Forecast aftershock occurence')\n        loopout(:,end+1) = 0; % add a column\n\n        pval1s = loopout(:,1);\n        pval2s = loopout(:,2);\n        cval1s = loopout(:,3);\n        cval2s = loopout(:,4);\n        kval1s = loopout(:,5);\n        kval2s = loopout(:,6);\n        \n        cumnr_model = OmoriModel.doForecast(nMod, time_asf, pval1s, cval1s, kval1s, fT1, kval2s, pval2s, cval2s);\n        \n        loopout(:,9)=max(cumnr_model);\n        \n        pfloop = plot(time_asf,cumnr_model,'color',[0.8 0.8 0.8]);\n        set(gca,'NextPlot','add')\n        \n        warning('This uses only the last values')\n        % 2nd moment of bootstrap number of forecasted number of events\n        fStdBst = std(loopout(:,9),1,'omitnan');\n        %\n        % Plot the forecast ...\n        cumnrf = (1:length(time_asf))';\n        \n        cumnr_modelf = OmoriModel.doForecast(nMod, time_asf, pval1s(end), cval1s(end), kval1s(end), fT1, kval2s(end), pval2s(end), cval2s(end));\n        \n        time_asf=sort(time_asf);\n        cumnr_modelf=sort(cumnr_modelf);\n\n        pf1 =  plot(time_asf,cumnr_modelf,'g-.','Linewidth',2);\n        set(gca,'NextPlot','add')\n        %pf2 =  plot(time_asf,cumnrf, 'b-','Linewidth',2);\n        %\n        % Plot the  fit to the observed data\n        % Cumulative number of observed events\n        cumnr = (1:length(time_as))';\n        cumnr_model = [];\n        cumnr_model= OmoriModel.doForecast(nMod, time_as, pval1s(end), cval1s(end), kval1s(end), fT1, kval2s(end), pval2s(end), cval2s(end));\n        \n        \n        time_as=sort(time_as);\n        cumnr_model=sort(cumnr_model);\n        p1 = plot(time_as,cumnr_model,'r','Linewidth',2,'Linestyle','--');\n        set(gca,'NextPlot','add');\n        p2 = plot(time_as,cumnr,'b','Linewidth',2,'Linestyle','--');\n\n        % Plot the forecast from median value\n        cumnr_modelmed = [];\n        cumnr_modelmed= OmoriModel.doForecast(nMod, time_asf, pmed1, cmed1, kmed1, fT1, kmed2, pmed2, cmed2);\n        \n        time_asf=sort(time_asf);\n        cumnr_modelmed=sort(cumnr_modelmed);\n        pmedmod =  plot(time_asf,cumnr_modelmed,'y-.','Linewidth',2);\n\n        % Plot observed events in forecast period from endpoint of modeled events in learning period\n        vSel = time_asf >= max(time_as);\n        vCumnr_forecast = cumnrf(vSel,:);\n        vTime_forecast = time_asf(vSel,:);\n        % Difference of modelled and observed number of events at time_as\n        fDiff_timeas = cumnr_modelmed(length(time_as))-cumnrf(length(time_as));\n        vCumnr_forecast = vCumnr_forecast+fDiff_timeas;\n        pf3 = plot(vTime_forecast, vCumnr_forecast,'m-.','Linewidth',2);\n\n        xlabel('Time [days]')\n        ylabel('Cumulative number of aftershocks')\n        xlim([0 max(time_asf)]);\n\n        % Plot standard deviation from bootstrap\n        ps2=errorbar(max(time_asf),max(cumnr_modelmed),fStdBst,fStdBst);\n        set(ps2,'Linewidth',2,'Color',[1 0 0])\n        %\n        %     % Title\n        % Find amount of events in forecast period for modeled data\n        nummod2 = max(cumnr_modelf)-cumnr_modelf(length(time_as));\n        nummod = max(cumnr_modelmed)-cumnr_modelmed(length(time_as));\n        %     % Find amount of  events in forecast period for observed data\n        l = time_asf <=time+timef & time_asf > time;\n        numreal = sum(l); % observed number of aftershocks\n        %     fRc_Flaw = (numreal-nummod)/sigma;\n        fRc_Bst2 = (numreal-nummod2)/fStdBst;\n        fRc_Bst = (numreal-nummod)/fStdBst;\n\n        % Round values for output\n        pval1 = round(pval1,2);\n        pval2 = round(pval2,2);\n        cval1 = round(cval1,3);\n        cval2 = round(cval2,3);\n        kval1 = round(kval1,1);\n        kval2 = round(kval2,1);\n        pmed1 = round(pmed1,2); mStdL(1,1) = round(mStdL(1,1),2);\n        pmed2 = round(pmed2,2); mStdL(1,2) = round(mStdL(1,2),2);\n        cmed1 = round(cmed1,3); mStdL(1,3) = round(mStdL(1,3),3);\n        cmed2 = round(cmed2,3); mStdL(1,4) = round(mStdL(1,4),3);\n        kmed1 = round(kmed1,1); mStdL(1,5) = round(mStdL(1,5),2);\n        kmed2 = round(kmed2,1); mStdL(1,6)= round(mStdL(1,6),2);\n        fAIC = round(fAIC,2);\n        fStdBst = round(fStdBst,2);\n        fRc_Bst = round(fRc_Bst,2);\n\n        % Set line for learning period\n        yy = get(gca,'ylim');\n        plot([max(time_as) max(time_as)],[0 yy(2)],'k-.')\n        textX = max(time_asf)*0.1;\n        textY = @(z) yy(2)* z;\n        \n        switch nMod\n            case OmoriModel.pck\n                string1 = sprintf('p = %g; c = %g; k = %g', pval1, cval1, kval1);\n                string3 = sprintf('pm = %g+-%g; cm = %g+-%g; km = %g+-%g', mped1, mStdL(1,1), cmed1, mStdL(1,3), kmed1, mStdL(1,5));\n                % string3=['pm = ' num2str(pmed1) '+-' num2str(mStdL(1,1)) '; cm = ' num2str(cmed1) '+-' num2str(mStdL(1,3)) '; km = ' num2str(kmed1) '+-' num2str(mStdL(1,5))];\n                text(textX,textY(0.9),string1,'FontSize',8);\n                text(textX,textY(0.8),string3,'FontSize',8);\n            case  OmoriModel.pckk\n                string1 = sprintf('p = %g; c = %g; k1 = %g; k2 = %g', pval1, cval1, kval1, kval2);\n                string3 = sprintf('pm = %g+-%g; cm = %g+-%g; km1 = %g+-%g; km2 = %g+-%g',...\n                    mped1, mStdL(1,1), cmed1, mStdL(1,3), kmed1, mStdL(1,5), kmed2, mStdL(1,6));\n                text(textX,textY(0.9),string1,'FontSize',8);\n                text(textX,textY(0.8),string3,'FontSize',8);\n            case OmoriModel.ppckk\n                string1 = sprintf('p1 = %g; c = %g; k1 = %g', pval1, cval1, kval1);\n                string2 = sprintf('p2 = %g; k2 = %g', pval2, kval2);\n                string3 = sprintf('pm1 = %g+-%g; cm = %g+-%g; km1 = %g+-%g', mped1, mStdL(1,1), cmed1, mStdL(1,3), kmed1, mStdL(1,5));\n                string4 = sprintf('pm2 = %g+-%g; km2 = %g+-%g', mped2, mStdL(1,2), kmed2, mStdL(1,6));\n                text(textX,textY(0.9),string1,'FontSize',8);\n                text(textX,textY(0.85),string2,'FontSize',8);\n                text(textX,textY(0.8),string3,'FontSize',8);\n                text(textX,textY(0.75),string4,'FontSize',8);\n            case OmoriModel.ppcckk\n                string1 = sprintf('p1 = %g; c1 = %g; k1 = %g', pval1, cval1, kval1);\n                string2 = sprintf('p2 = %g; c2 = %g; k2 = %g', pval2, cval2, kval2);\n                string3 = sprintf('pm1 = %g+-%g; cm1 = %g+-%g; km1 = %g+-%g', mped1, mStdL(1,1), cmed1, mStdL(1,3), kmed1, mStdL(1,5));\n                string4 = sprintf('pm2 = %g+-%g; cm2 = %g+-%g; km2 = %g+-%g', mped2, mStdL(1,2), cmed2, mStdL(1,4), kmed2, mStdL(1,6));\n                text(textX,textY(0.9),string1,'FontSize',8);\n                text(textX,textY(0.85),string2,'FontSize',8);\n                text(textX,textY(0.8),string3,'FontSize',8);\n                text(textX,textY(0.75),string4,'FontSize',8);\n        end\n        string=sprintf('\\sigma(Bst) = %g Rc = %g',fStdBst, fRc_Bst);%' Rc(Obfit) = ' num2str(fRc_Bst2)];\n        text(textX,yy(2)*0.1,string,'FontSize',8);\n        \n        sAIC = sprintf('AIC = %g',fAIC);\n        text(textX,yy(2)*0.05,sAIC,'FontSize',8);\n        \n        paf = plot(fT1, 0,'h','MarkerFaceColor',[1 1 0],'MarkerSize',12,'MarkerEdgeColor',[0 0 0] );\n        sGoodfit = sprintf('KS Test: H = %g, KS statistic = %g P value = %g; RMS = %g', H, KSSTAG, P,fRMS);\n        text(textX,yy(2)*0.15,sGoodfit,'FontSize',8);\n        % Legend\n        legend([p2 p1 pf1 pf3 pmedmod min(ps2) paf],'data','model to data','forecast','observed', 'Mean Bst-model', '\\sigma (Bst)','Sec. AF', 'location', 'Best');\n    else\n        disp('no result')\n    end\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/afterrate/plot_bootfitloglike_a2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.574509885542243}}
{"text": "function y = efilter2(x, f, extmod, shift)\n% EFILTER2   2D Filtering with edge handling (via extension)\n%\n%\ty = efilter2(x, f, [extmod], [shift])\n%\n% Input:\n%\tx:\tinput image\n%\tf:\t2D filter\n%\textmod:\t[optional] extension mode (default is 'per')\n%\tshift:\t[optional] specify the window over which the \n%\t\tconvolution occurs. By default shift = [0; 0].\n%\n% Output:\n%\ty:\tfiltered image that has:\n%\t\tY(z1,z2) = X(z1,z2)*F(z1,z2)*z1^shift(1)*z2^shift(2)\n%\n% Note:\n%\tThe origin of filter f is assumed to be floor(size(f)/2) + 1.\n%\tAmount of shift should be no more than floor((size(f)-1)/2).\n%\tThe output image has the same size with the input image.\n%\n% See also:\tEXTEND2, SEFILTER2\n\nif ~exist('extmod', 'var')\n    extmod = 'per';\nend\n\nif ~exist('shift', 'var')\n    shift = [0; 0];\nend\n\n% Periodized extension\nsf = (size(f) - 1) / 2;\n\nxext = extend2(x, floor(sf(1)) + shift(1), ceil(sf(1)) - shift(1), ...\n\t       floor(sf(2)) + shift(2), ceil(sf(2)) - shift(2), extmod);\n\n% Convolution and keep the central part that has the size as the input\ny = conv2(xext, f, 'valid');", "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/nsct_toolbox/efilter2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5744153462047403}}
{"text": "function area = sphericalCapsAreaC6(varargin)\n%SPHERICALCAPSAREAC6 compute area of spherical caps on the unit sphere\n%\n%   AREA = sphericalCapsAreaC6\n%   Compute the area of the spherical caps associated to the voronoi\n%   diagram on the unit sphere, when the germs correspond to the 26\n%   discrete directions in the unit cube.\n%   Result is a 1x3 array, containing fraction of area of each type of\n%   spherical cap.\n%   area(1) concerns the direction [1 0 0]\n%   area(2) concerns the direction [0 1 0]\n%   area(3) concerns the direction [0 0 1]\n%   Result is formatted such that 2*(area(1)+area(2)+area(3))=1.\n%   For homogeneous lattices, all areas are equal.\n%\n%   AREA = sphericalCapsAreaC6(DELTA)\n%   where DELTA = [DELTA1 DELTA2 DELTA3]  specifies the resolution of unit\n%   voxel in each direction.\n%\n%\n%   Algorithm :\n%   - separate 3 basic case, corresponding on the type of directions\n%   - for each cases, specify manually germ and neighbours\n%   - compute great circle between each couple of germ\n%   - compute intersection points of these circles\n%   - sort intersection points around the central germ, giving a spherical\n%      polygon\n%   - compute triangulation of the resulting polygon\n%   - compute spherical area of each triangle\n%   - and area of each polygon\n%\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 21/02/2005.\n%\n\n%   HISTORY\n%   27/04/2007 extends to non uniform grid spacing\n\n\n%% Initializations\n\n% grid resolution\ndelta = [1 1 1];\nif ~isempty(varargin)\n    delta = varargin{1};\nend\n\n% poins in the 26 discrete directions\n%pt000 = normalize([-1 -1 -1].*delta);\n%pt100 = normalize([ 0 -1 -1].*delta);\n%pt200 = normalize([+1 -1 -1].*delta);\n%pt010 = normalize([-1  0 -1].*delta);\npt110 = normalize([ 0  0 -1].*delta);\n% pt210 = normalize([+1  0 -1].*delta);\n% pt020 = normalize([-1 +1 -1].*delta);\n% pt120 = normalize([ 0 +1 -1].*delta);\n% pt220 = normalize([+1 +1 -1].*delta);\n\n%pt001 = normalize([-1 -1  0].*delta);\npt101 = normalize([ 0 -1  0].*delta);\n% pt201 = normalize([+1 -1  0].*delta);\npt011 = normalize([-1  0  0].*delta);\n%pt111 = [ 0  0  0];             % origin point\npt211 = normalize([+1  0  0].*delta);\n% pt021 = normalize([-1 +1  0].*delta);\npt121 = normalize([ 0 +1  0].*delta);\n% pt221 = normalize([+1 +1  0].*delta);\n\n% pt002 = normalize([-1 -1 +1].*delta);\n% pt102 = normalize([ 0 -1 +1].*delta);\n% pt202 = normalize([+1 -1 +1].*delta);\n% pt012 = normalize([-1  0 +1].*delta);\npt112 = normalize([ 0  0 +1].*delta);\n% pt212 = normalize([+1  0 +1].*delta);\n% pt022 = normalize([-1 +1 +1].*delta);\n% pt122 = normalize([ 0 +1 +1].*delta);\n% pt222 = normalize([+1 +1 +1].*delta);\n\n% basic unit sphere\nsphere = [0 0 0  1];\n\n\n%% Spherical cap type 1 direction [1 0 0]\n% ----------------------------------------------------------------------\n\n% Compute area of voronoi cell for a point on the Ox axis, i.e. a point\n% in the 6-neighboorhoud of the center.\ncentre1 = pt211;\n% neighbours of chosen point, sorted by angle\n%voisins1 = [pt200;pt201;pt202;pt212;pt222;pt221;pt220;pt210];\nvoisins1 = [pt112;pt121;pt110;pt101];\nn1 = size(voisins1, 1);\n\n% compute separating circles\nplanes1 = zeros(n1, 9);\nfor i=1:n1\n    planes1(i,1:9) = normalizePlane(medianPlane(centre1, voisins1(i,:)));\n%    circles1(i,1:7) = intersectPlaneSphere(planes1(i,:), sphere);\nend\n\n% compute circle intersections\nlines1 = zeros(n1, 6);\nfor i=1:n1\n    lines1(i,1:6) = intersectPlanes(planes1(i,:), ...\n        planes1(mod(i,n1)+1,:));\n    points1(2*i-1:2*i,1:3) = intersectLineSphere(lines1(i,:), sphere);\nend\n\n% keep only points with x>0\nind = dot(points1, repmat(centre1, [2*n1 1]), 2)>0;\npoints1 = points1(ind,:);\nn1 = size(points1, 1);\n\n% compute spherical area of each triangle [center  pt[i+1]%4   pt[i] ]\nangles1 = zeros(n1, 1);\nfor i=1:n1\n    pt1 = points1(i, :);\n    pt2 = points1(mod(i  , n1)+1, :);\n    pt3 = points1(mod(i+1, n1)+1, :);\n    \n    angles1(i) = sphericalAngle(pt1, pt2, pt3); \nend\n\n% compute area of spherical polygon\narea1 = sum(angles1)-pi*(n1-2);\n\n\n%% Spherical cap type 1 direction [0 1 0]\n% ----------------------------------------------------------------------\n\n% Compute area of voronoi cell for a point on the Oy axis, i.e. a point\n% in the 6-neighboorhoud of the center.\ncentre1 = pt121;\n% neighbours of chosen point, sorted by angle\n%voisins1 = [pt200;pt201;pt202;pt212;pt222;pt221;pt220;pt210];\n%voisins1 = [pt221;pt222;pt122;pt022;pt021;pt020;pt120;pt220];\nvoisins1 = [pt211;pt112;pt011;pt110];\nn1 = size(voisins1, 1);\n\n% compute separating circles\nplanes1 = zeros(n1, 9);\nfor i=1:n1\n    planes1(i,1:9) = normalizePlane(medianPlane(centre1, voisins1(i,:)));\n%    circles1(i,1:7) = intersectPlaneSphere(planes1(i,:), sphere);\nend\n\n% compute circle intersections\nlines1 = zeros(n1, 6);\nfor i=1:n1\n    lines1(i,1:6) = intersectPlanes(planes1(i,:), ...\n        planes1(mod(i,n1)+1,:));\n    points1(2*i-1:2*i,1:3) = intersectLineSphere(lines1(i,:), sphere);\nend\n\n% keep only points with x>0\nind = dot(points1, repmat(centre1, [2*n1 1]), 2)>0;\npoints1 = points1(ind,:);\nn1 = size(points1, 1);\n\n% compute spherical area of each triangle [center  pt[i+1]%4   pt[i] ]\nangles1 = zeros(n1, 1);\nfor i=1:n1\n    pt1 = points1(i, :);\n    pt2 = points1(mod(i  , n1)+1, :);\n    pt3 = points1(mod(i+1, n1)+1, :);\n    \n    angles1(i) = sphericalAngle(pt1, pt2, pt3); \nend\n\n% compute area of spherical polygon\narea2 = sum(angles1)-pi*(n1-2);\n\n\n%% Spherical cap type 1 direction [0 0 1]\n% ----------------------------------------------------------------------\n\n% Compute area of voronoi cell for a point on the Oz axis, i.e. a point\n% in the 6-neighboorhoud of the center.\ncentre1 = pt112;\n% neighbours of chosen point, sorted by angle\n%voisins1 = [pt200;pt201;pt202;pt212;pt222;pt221;pt220;pt210];\n%voisins1 = [pt212;pt222;pt122;pt022;pt012;pt002;pt102;pt202];\nvoisins1 = [pt121;pt011;pt101;pt211];\n\nn1 = size(voisins1, 1);\n\n% compute separating circles\nplanes1 = zeros(n1, 9);\nfor i=1:n1\n    planes1(i,1:9) = normalizePlane(medianPlane(centre1, voisins1(i,:)));\n%    circles1(i,1:7) = intersectPlaneSphere(planes1(i,:), sphere);\nend\n\n% compute circle intersections\nlines1 = zeros(n1, 6);\nfor i=1:n1\n    lines1(i,1:6) = intersectPlanes(planes1(i,:), ...\n        planes1(mod(i,n1)+1,:));\n    points1(2*i-1:2*i,1:3) = intersectLineSphere(lines1(i,:), sphere);\nend\n\n% keep only points with z>0\nind = dot(points1, repmat(centre1, [2*n1 1]), 2)>0;\npoints1 = points1(ind,:);\nn1 = size(points1, 1);\n\n% compute spherical area of each triangle [center  pt[i+1]%4   pt[i] ]\nangles1 = zeros(n1, 1);\nfor i=1:n1\n    pt1 = points1(i, :);\n    pt2 = points1(mod(i  , n1)+1, :);\n    pt3 = points1(mod(i+1, n1)+1, :);\n    \n    angles1(i) = sphericalAngle(pt1, pt2, pt3);\n    angles1(i) = min(angles1(i), 2*pi-angles1(i));\nend\n\n% compute area of spherical polygon\narea3 = sum(angles1)-pi*(n1-2);\n\n\n%% Results\n% -------------------------------------------------------------------\n\n% display some results\ndisp('results : ')\npattern = 'area of cell in direction %d: %12.10f sr, = %12.10f %%';\ndisp(sprintf(pattern, 1, area1, area1*100/4/pi));\ndisp(sprintf(pattern, 2, area2, area2*100/4/pi));\ndisp(sprintf(pattern, 3, area3, area3*100/4/pi));\n\n% return computed areas, formatted as fraction of sphere surface\narea = [area1 area2 area3]/4/pi;\n\n\n\n%% Internal functions\n% -------------------------------------------------------------------\n% This functions are part of a more general geometric library, but are\n% included here for avoiding dependencies\n\nfunction theta = angle3Points(varargin)\n%ANGLE3POINTS return oriented angle made by 3 points\n%\n%   ALPHA = ANGLE3POINTS(P1, P2, P3).\n%   Pi are either [1*2] arrays, or [N*2] arrays, in this case ALPHA is a \n%   [N*1] array. The angle computed is the directed angle between line \n%   (P2P1) and line (P2P3).\n%   Result is always given in radians, between 0 and 2*pi.\n%\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 23/02/2004.\n%\n\n%   HISTORY :\n%   25/09/2005 : enable single parameter\n\nif length(varargin)==3\n    p1 = varargin{1};\n    p2 = varargin{2};\n    p3 = varargin{3};\nelseif length(varargin)==1\n    var = varargin{1};\n    p1 = var(1,:);\n    p2 = var(2,:);\n    p3 = var(3,:);\nend    \n\n% angle line (P2 P1)\ntheta = lineAngle(createLine(p2, p1), createLine(p2, p3));\n\n\n\nfunction line = createLine(varargin)\n%CREATELINE create a line with various inputs.\n%\n%   Line is represented in a parametric form : [x0 y0 dx dy]\n%   x = x0 + t*dx\n%   y = y0 + t*dy;\n%\n%\n%   l = CREATELINE(p1, p2) return the line going through the two given\n%   points.\n%   \n%   l = CREATELINE(x0, y0, dx, dy) the line going through point (x0, y0)\n%   and with direction vector(dx, dy).\n%\n%   l = CREATELINE(param) where param is an array of 4 values, create the\n%   line oing through the point (param(1) param(2)), and with direction\n%   vector (param(3) param(4)).\n%   \n%   l = CREATELINE(theta) create a line originated at (0,0) and\n%   with angle theta.\n%\n%   l = CREATELINE(rho, theta) create a line with normal theta, and with\n%   min distance to origin equal to rho. rho can be negative, in this case,\n%   the line is the same as with CREATELINE(-rho, theta+pi), but the\n%   orientation is different.\n%\n%\n%   Note : in all cases, parameters can be vertical arrays of the same\n%   dimension. The result is then an array of lines, of dimensions [N*4].\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 31/10/2003.\n%\n\nif length(varargin)==1\n    % Only one input parameter. It can be :\n    % - line angle\n    % - array of four parameters\n    var = varargin{1};\n    \n    if size(var, 2)==4\n        % 4 parameters of the line in a single array.\n        line = var;\n    elseif size(var, 2)==1\n        % 1 parameter : angle of the line, going through origin.\n        line = [zeros(size(var)) zeros(size(var)) cos(var) sin(var)];\n    else\n        error('wrong number of dimension for arg1 : can be 1 or 4');\n    end\n    \nelseif length(varargin)==2    \n    % 2 input parameters. They can be :\n    % - line angle and signed distance to origin.\n    % - 2 points, then 2 arrays of 1*2 double.\n    v1 = varargin{1};\n    v2 = varargin{2};\n    if size(v1, 2)==1\n        % first param is angle of line, and second param is signed distance\n        % to origin.\n        line = [v1.*cos(v2) v1.*sin(v2) -sin(v2) cos(v2)];\n    else\n        % first input parameter is first point, and second input is the\n        % second point.\n        line = [v1(:,1), v1(:,2), v2(:,1)-v1(:,1), v2(:,2)-v1(:,2)];    \n    end\n    \nelseif length(varargin)==3\n    % 3 input parameters :\n    % first one is a point belonging to the line,\n    % second and third ones are direction vector of the line (dx and dy).\n    p = varargin{1};\n    line = [p(:,1) p(:,2) varargin{2} varargin{3}];\n   \nelseif length(varargin)==4\n    % 4 input parameters :\n    % they are x0, y0 (point belongng to line) and dx, dy (direction vector\n    % of the line).\n    % All parameters should have the same size.\n    line = [varargin{1} varargin{2} varargin{3} varargin{4}];\nelse\n    error('Wrong number of arguments in ''createLine'' ');\nend\n\nfunction plane = createPlane(varargin)\n%CREATEPLANE create a plane in parametrized form\n%\n%   Create a plane in the following format : \n%   PLANE = [X0 Y0 Z0  DX1 DY1 DZ1  DX2 DY2 DZ2], where :\n%   - (X0, Y0, Z0) is a point belonging to the plane\n%   - (DX1, DY1, DZ1) is a first direction vector\n%   - (DX2, DY2, DZ2) is a second direction vector\n%   \n%\n%\n%   PLANE = createPlane(P1, P2, P3) \n%   create a plane containing the 3 points\n%\n%   PLANE = createPlane(PTS) \n%   The 3 points are packed into a single 3x3 array.\n%\n%   PLANE = createPlane(P0, N);\n%   create a plane from a point and from a normal to the plane.\n%   \n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 18/02/2005.\n%\n\n%   HISTORY :\n%   24/11/2005 : add possibility to pack points for plane creation\n\nif length(varargin)==1\n    var = varargin{1};\n    \n    if iscell(var)\n        plane = zeros(length(var), 9);\n        for i=1:length(var)\n            plane(i,:) = createPlane(var{i});\n        end\n    elseif size(var, 1)==3\n        % 3 points in a single array\n        p1 = var(1,:);\n        p2 = var(2,:);\n        p3 = var(3,:);\n        \n        % create direction vectors\n        v1 = p2-p1;\n        v2 = p3-p1;\n\n        % create plane\n        plane = [p1 v1 v2];\n        return;\n    end\n    \nelseif length(varargin)==2\n    \n    p0 = varargin{1};\n    \n    var = varargin{2};\n    if size(var, 2)==2\n        n = sph2cart2([var repmat(1, [size(var, 1) 1])]);\n    elseif size(var, 2)==3\n        n  = normalize3d(var);\n    else\n        error ('wrong number of parameters in createPlane');\n    end\n    \n    % find a vector not colinear to the normal\n    v0 = repmat([1 0 0], [size(p0, 1) 1]);    \n    if abs(cross(n, v0, 2))<1e-14\n        v0 = repmat([0 1 0], [size(p0, 1) 1]);\n    end\n    \n    % create direction vectors\n    v1 = normalize3d(cross(n, v0, 2));\n    v2 = -normalize3d(cross(v1, n, 2));\n    \n    plane = [p0 v1 v2];\n    return;\n    \nelseif length(varargin)==3\n    p1 = varargin{1};    \n    p2 = varargin{2};\n    p3 = varargin{3};\n    \n    % create direction vectors\n    v1 = p2-p1;\n    v2 = p3-p1;\n   \n    plane = [p1 v1 v2];\n    return;\n  \nelse\n    error('wrong number of arguments in \"createPlane\".');\nend\n\n\nfunction point = intersectLineSphere(line, sphere)\n%INTERSECTLINESPHERE return intersection between a line and a sphere\n%\n%   GC = intersectLineSphere(LINE, SPHERE) return the two points which are \n%   the intersection of the given line and sphere.\n%   LINE   : [x0 y0 z0  dx dy dz]\n%   SPHERE : [xc yc zc  R]\n%   GC     : [x1 y1 z1 ; x2 y2 z2]\n%   \n%\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 18/02/2005.\n%\n\n%   HISTORY\n\n% difference between centers\ndc = line(1:3)-sphere(1:3);\n\na = sum(line(:, 4:6).*line(:, 4:6), 2);\nb = 2*sum(dc.*line(4:6), 2);\nc = sum(dc.*dc, 2) - sphere(:,4).*sphere(:,4);\n\ndelta = b.*b -4*a.*c;\n\nif delta>1e-14\n    % find two roots of second order equation\n    u1 = (-b -sqrt(delta))/2/a;\n    u2 = (-b +sqrt(delta))/2/a;\n    \n    % convert into 3D coordinate\n    point = [line(1:3)+u1*line(4:6) ; line(1:3)+u2*line(4:6)];\n\nelseif abs(delta) > 1e-14\n    % find unique root, and convert to 3D coord.\n    u = -b/2./a;    \n    point = line(1:3) + u*line(4:6);\n    \nelse\n    point = zeros(0, 3);\n    return;\nend\n\nfunction point = intersectPlaneLine(plane, line)\n%INTERSECTPLANELINE return intersection between a plane and a line\n%\n%   PT = intersectPlaneSphere(PLANE, LINE) return the intersection point of\n%   the given line and the given plane.\n%   PLANE : [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2]\n%   LINE :  [x0 y0 z0 dx dy dz]\n%   PT :    [XI YI ZI]\n%   \n%\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 17/02/2005.\n%\n\n%   HISTORY\n%   24/11/2005 add support for multiple input\n\n% unify sizes of data\nif size(plane, 1)~=size(line, 1)\n    if size(plane, 1)==1\n        plane = repmat(plane, [size(line, 1) 1]);\n    elseif size(line,1)==1\n        line = repmat(line, [size(plane, 1) 1]);\n    else\n        error('line and plane do not have the same dimension');\n    end\nend\n\n\n% plane normal\nn = cross(plane(:,4:6), plane(:, 7:9), 2);\n\n% test if line and plane are parallel\nif abs(dot(n, line(:,4:6), 2))<1e-14\n    point = [NaN NaN NaN];\n    return;\nend\n\n% difference between origins of plane and line\ndp = plane(:,1:3) - line(:,1:3);\n\n% relative position of intersection on line\nt = dot(n, dp, 2)/dot(n, line(:,4:6), 2);\n\n% compute coord of intersection point\npoint = line(:,1:3) + t*line(:,4:6);\n\n\nfunction line = intersectPlanes(plane1, plane2)\n%INTERSECTPLANES return intersection between 2 planes in space\n%\n%   PT = intersectPlanes(PLANE1, PLANE2) return the straight line belonging\n%   to both planes\n%   PLANE : [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2]\n%   LINE :  [x0 y0 z0 dx dy dz]\n%\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 17/02/2005.\n%\n\n%   HISTORY\n\n\n% plane normal\nn1 = normalize3d(cross(plane1(:,4:6), plane1(:, 7:9), 2));\nn2 = normalize3d(cross(plane2(:,4:6), plane2(:, 7:9), 2));\n\n% test if planes are parallel\nif abs(cross(n1, n2, 2))<1e-14\n    line = [NaN NaN NaN NaN NaN NaN];\n    return;\nend\n\n% Uses hessian form, ie : N.p = d\n% I this case, d can be found as : -N.p0, when N is normalized\nd1 = dot(n1, plane1(:,1:3), 2);\nd2 = dot(n2, plane2(:,1:3), 2);\n\n% compute dot products\ndot1 = dot(n1, n1, 2);\ndot2 = dot(n2, n2, 2);\ndot12 = dot(n1, n2, 2);\n\n\ndet = dot1*dot2 - dot12*dot12;\nc1 = (d1*dot2 - d2*dot12)./det;\nc2 = (d2*dot1 - d1*dot12)./det;\n\np0 = c1*n1 + c2*n2;\ndp = cross(n1, n2, 2);\n\nline = [p0 dp];\n\n\nfunction theta = lineAngle(varargin)\n%LINEANGLE return angle between lines\n%\n%   a = LINEANGLE(line) return the angle between horizontal, right-axis \n%   and the given line. Angle is fiven in radians, between 0 and 2*pi,\n%   in counter-clockwise direction.\n%\n%   a = LINEANGLE(line1, line2) return the directed angle between the\n%   two lines. Angle is given in radians between 0 and 2*pi.\n%\n%   see createLine for more details on line representation.\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 31/10/2003.\n%\n\n%   HISTORY :\n%   19/02/2004 : added support for multiple lines.\n\nnargs = length(varargin);\nif nargs == 1\n    % one line\n    line = varargin{1};\n    theta = mod(atan2(line(:,4), line(:,3)) + 2*pi, 2*pi);\nelseif nargs==2\n    % two lines\n    theta1 = lineAngle(varargin{1});\n    theta2 = lineAngle(varargin{2});\n    theta = mod(theta2-theta1+2*pi, 2*pi);\nend\n\nfunction plane = medianPlane(p1, p2)\n%MEDIANPLANE create a plane in the middle of 2 points\n%\n%   plane = medianPlane(P1, P2)\n%   plane is perpendicular to line (P1 P2) and contains the midpoint of p1\n%   and p2.\n%   \n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 18/02/2005.\n%\n\n\np0 = (p1 + p2)/2;\nn = p2-p1;\n\nplane = createPlane(p0, n);\n\n\nfunction vn = normalize(v)\n%NORMALIZE normalize a vector\n%\n%   V2 = normalize(V);\n%   return the normalization of vector V, such that ||V|| = 1. V can be\n%   either a row or a column vector.\n%\n%   When V is a MxN array, normalization is performed for each row of the\n%   array.\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 29/11/2004.\n%\n\ndim = size(v);\nif dim(1)==1 || dim(2)==1\n    vn = v/sqrt(sum(v.*v));\nelse\n    vn = v./repmat(sqrt(sum(v.*v, 2)), [1 dim(2)]);\nend\n\nfunction vn = normalize3d(v)\n%NORMALIZE3D normalize a 3D vector\n%\n%   V2 = normalize3d(V);\n%   return the normalization of vector V, such that ||V|| = 1. Vector V is\n%   given in vertical form.\n%\n%   When V is a Nx3 array, normalization is performed for each row of the\n%   array.\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 29/11/2004.\n%\n\n%   HISTORY\n%   30/11/2005  : correct a bug\n\nn = sqrt(v(:,1).*v(:,1) + v(:,2).*v(:,2) + v(:,3).*v(:,3));\nvn = v./[n n n];\n\nfunction plane2 = normalizePlane(plane1)\n%NORMALIZEPLANE normalize parametric form of a plane\n%\n%   plane2 = normalizePlane(plane1);\n%   transform the plane PANE1 in the following format :\n%   [X0 Y0 Z0  DX1 DY1 DZ1  DX2 DY2 DZ2], where :\n%   - (X0, Y0, Z0) is a point belonging to the plane\n%   - (DX1, DY1, DZ1) is a first direction vector\n%   - (DX2, DY2, DZ2) is a second direction vector\n%   into another plane, with the same format, but with :\n%   - (x0 y0 z0) is the closest point of plane to origin\n%   - (DX1 DY1 DZ1) has norm equal to 1\n%   - (DX2 DY2 DZ2) has norm equal to 1 and is orthogonal to (DX1 DY1 DZ1)\n%   \n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 21/02/2005.\n%\n\n%   HISTORY :\n\n\n% compute origin point of the plane\np0 = projPointOnPlane([0 0 0], plane1);\n\n% compute first direction vector\nd1 = normalize3d(plane1(:,4:6));\n\n% compute second direction vector\nn = normalize3d(planeNormal(plane1));\nd2 = -normalize3d(cross(d1, n));\n\n% create the resulting plane\nplane2 = [p0 d1 d2];\n\nfunction n = planeNormal(plane)\n%PLANENORMAL compute the normal to a plane\n%\n%   N = planeNormal(PLANE) \n%   compute the normal of the given plane\n%   PLANE : [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2]\n%   N : [dx dy dz]\n%   \n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 17/02/2005.\n%\n\n%   HISTORY\n\n\n% plane normal\nn = cross(plane(:,4:6), plane(:, 7:9), 2);\n\nfunction pos = planePosition(point, plane)\n%PLANEPOSITION compute position of a point on a plane\n%\n%   PT2 = PLANEPOSITION(POINT, PLANE)\n%   POINT has format [X Y Z], and plane has format\n%   [X0 Y0 Z0  DX1 DY1 DZ1  DX2 DY2 DZ2], where :\n%   - (X0, Y0, Z0) is a point belonging to the plane\n%   - (DX1, DY1, DZ1) is a first direction vector\n%   - (DX2, DY2, DZ2) is a second direction vector\n%\n%   Result PT2 has the form [XP YP], with [XP YP] coordinate of the point\n%   in the coordinate system of the plane.\n%\n%   \n%   CAUTION :\n%   WORKS ONLY FOR PLANES WITH ORTHOGONAL DIRECTION VECTORS\n%\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 21/02/2005.\n%\n\n%   HISTORY :\n%   24/11/2005 add support for multiple input\n\n% unify size of data\nif size(point, 1)~=size(plane, 1)\n    if size(point, 1)==1\n        point = repmat(point, [size(plane, 1) 1]);\n    elseif size(plane, 1)==1\n        plane = repmat(plane, [size(point, 1) 1]);\n    else\n        error('point and plane do not have the same dimension');\n    end\nend\n\n\np0 = plane(:,1:3);\nd1 = plane(:,4:6);\nd2 = plane(:,7:9);\n\ns = dot(point-p0, d1, 2)./vecnorm3d(d1);\nt = dot(point-p0, d2, 2)./vecnorm3d(d2);\n\npos = [s t];\n\nfunction point = projPointOnPlane(point, plane)\n%PROJPOINTONPLANE return the projection of a point on a plane\n%\n%   PT2 = PROJECTEDPOINT(PT1, PLANE).\n%   Compute the (orthogonal) projection of point PT1 onto the line PLANE.\n%   \n%   Function works also for multiple points and planes. In this case, it\n%   returns multiple points.\n%   Point PT1 is a [N*3] array, and PLANE is a [N*9] array (see createPlane\n%   for details). Result PT2 is a [N*3] array, containing coordinates of\n%   orthogonal projections of PT1 onto planes PLANE.\n%\n%   See also planePosition\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 18/02/2005.\n%\n\nn = planeNormal(plane);\nline = [point repmat(n, [size(point, 1) 1])];\npoint = intersectPlaneLine(plane, line);\n\n\n\nfunction varargout = sph2cart2(varargin)\n%SPH2CART2 convert spherical coordinate to cartesian coordinate\n%\n%   usage :\n%   C = SPH2CART2(S)\n%   C = SPH2CART2(PHI, THETA)       (assume rho = 1)\n%   C = SPH2CART2(PHI, THETA, RHO)   \n%   [X, Y, Z] = SPH2CART2(PHI, THETA, RHO);\n%\n%   S = [phi theta rho] (sphercial coordiante).\n%   C = [X Y Z]  (cartesian coordinate)\n%\n%   Math convention is used : theta is angle with vertical, 0 for north\n%   pole, +pi for south pole, pi/2 for points with z=0.\n%   phi is the same as matlab cart2sph : angle from Ox axis, counted\n%   counter-clockwise.\n%\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 18/02/2005.\n%\n\n%   HISTORY\n%   22/03/2005 : make test for 2 args, and add radius if not specified for\n%       1 arg.\n\nif length(varargin)==1\n    var = varargin{1};\n    if size(var, 2)==2\n        var = [var ones(size(var, 1), 1)];\n    end\nelseif length(varargin)==2\n    var = [varargin{1} varargin{2} ones(size(varargin{1}))];\nelseif length(varargin)==3\n    var = [varargin{1} varargin{2} varargin{3}];\nend\n\n[x y z] = sph2cart(var(:,1), pi/2-var(:,2), var(:,3));\n\nif nargout == 1 || nargout == 0\n    varargout{1} = [x, y, z];\nelse\n    varargout{1} = x;\n    varargout{2} = y;\n    varargout{3} = z;\nend\n    \n\nfunction alpha = sphericalAngle(p1, p2, p3)\n%SPHERICALANGLE compute angle on the sphere\n%\n%   ALPHA = sphericalAngle(P1, P2, P3)\n%   compute angle (P1, P2, P2), in radians, between 0 and 2*PI.\n%\n%   Points are given either as [x y z] (there will be normalized to lie on\n%   the unit sphere), or as [phi theta], with phi being the longitude in [0\n%   2*PI] and theta being the elevation on horizontal [-pi/2 pi/2].\n%\n%\n%   NOTE : \n%   this is an 'oriented' version of the angle computation, that is, the\n%   result of sphericalAngle(P1, P2, P3) equals\n%   2*pi-sphericalAngle(P3,P2,P1). To have the more classical relation\n%   (with results given betwen 0 and PI), it suffices to take the minimum\n%   of angle and 2*pi-angle.\n%   \n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 21/02/2005.\n%\n\n%   HISTORY\n\n% test if points are given as matlab spherical coordinate\nif size(p1, 2) ==2\n    [x y z] = sph2cart(p1(:,1), p1(:,2));\n    p1 = [x y z];\n    [x y z] = sph2cart(p2(:,1), p2(:,2));\n    p2 = [x y z];\n    [x y z] = sph2cart(p3(:,1), p3(:,2));\n    p3 = [x y z];\nend\n\n% normalize points\np1 = normalize3d(p1);\np2 = normalize3d(p2);\np3 = normalize3d(p3);\n\n% create the plane tangent to the unit sphere and containing central point\nplane = createPlane(p2, p2);\n\n% project the two other points on the plane\npi1 = planePosition(intersectPlaneLine(plane, [0 0 0 p1]), plane);\npi3 = planePosition(intersectPlaneLine(plane, [0 0 0 p3]), plane);\n\n% compute angle on the tangent plane\nalpha = angle3Points(pi1, [0 0], pi3);\n\n\nfunction n = vecnorm3d(v)\n%VECNORM3D compute euclidean norm of vector or of set of 3D vectors\n%\n%   n = vecnorm(V);\n%   return euclidean norm of vector V.\n%\n%   When V is a Nx3 array, compute norm for each vector of the array.\n%   Vector are given as rows. Result is then a [N*1] array.\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 21/02/2005.\n%\n\n%   HISTORY\n\nn = sqrt(sum(v.*v, 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/imMinkowski/private/sphericalCapsAreaC6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5744153404981379}}
{"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%==============================================================================\n%\n% Tutorial for FAIR: demo for 2D data setup and visualization\n%\n% load images                        (hands-?.jpg)\n% visualize ij and omega based data  (viewImage)\n% creates multi-lebel representation (getMultilevel) \n% \n%==============================================================================\n\nclear, close all, help(mfilename); \n\n% load data\nTij = imread('hands-T.jpg'); Tdata = double(flipud(Tij))';\nRij = imread('hands-R.jpg'); Rdata = double(flipud(Rij))';\n\n% specify domain Omega = [omega(1),omega(2)]x[omega(3),omega(3)];\nomega = [0,20,0,25];\nm     = size(Tdata);\n\n% setup image viewer\nviewImage('reset','viewImage','viewImage2D','colormap','gray(256)');\n\n% visualize\nFAIRfigure(1);  colormap(gray(256));\nsubplot(2,2,1); imagesc(Tij);              title('original T data, uint8, ij');\nsubplot(2,2,2); viewImage(Tdata,omega,m);  title('FAIR T data on \\Omega, xy');\nsubplot(2,2,3); imagesc(Rij);              title('original R data, uint8, ij');\nsubplot(2,2,4); viewImage(Rdata,omega,m);  title('FAIR R data on \\Omega, xy');\n\n% create multi-level representaion\nML = getMultilevel({Tdata,Rdata},omega,m,'fig',2);\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/E3_Hands_ij2xy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324611869563, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.574415330248492}}
{"text": "function [km] = A2km(A)\n% Convert length from angstroms to kilometers. \n% Chad A. Greene 2012\nkm = A*1e-13;", "meta": {"author": "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/A2km.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5744153245418895}}
{"text": "function [surfDice,addedPathLen,addedPathLenNorm] = ...\n    calc_surfDice_addPathLen(structNum1,structNum2,margin,planC)\n% function [surfDice,addedPathLen,addedPathLenNorm] = ...\n%     calc_surfDice_addPathLen(structNum1,structNum2,margin,planC)\n\n\nmask1M = getSurfaceRing(structNum1,margin,planC);\nmask2M = getSurfaceRing(structNum2,margin,planC);\navgMask = (sum(mask1M(:))+sum(mask2M(:)))/2;\nintrsctM = mask1M & mask2M;\nsurfDice = sum(intrsctM(:))/avgMask;\n\n% addedPathLenNorm = sum((mask1M(:) | mask2M(:)) & ~intrsctM(:))/(avgMask*2);\n% addedPathLen = sum((mask1M(:) | mask2M(:)) & ~intrsctM(:));\n\nscanNum = getStructureAssociatedScan(structNum1,planC);\n% [~,~,numSlcs] = size(intrsctM);\n\nindexS = planC{end};\n\n[xScanV,yScanV,zScanV] = getScanXYZVals(planC{indexS.scan}(scanNum));\n[~,~,zUnifScanV] = getUniformScanXYZVals(planC{indexS.scan}(scanNum));\nnumSlcs = length(zScanV);\n\nstructLen = 0;\nintersectStructLen = 0;\nfor slc = 1:numSlcs\n    if length(planC{indexS.structures}(structNum1).contour(slc).segments) ~= 1\n        continue\n    end\n    xV = planC{indexS.structures}(structNum1).contour(slc).segments(1).points(:,1);\n    yV = planC{indexS.structures}(structNum1).contour(slc).segments(1).points(:,2);\n    %[rowV, colV] = xytom(xV, yV, slc, planC,scanNum);\n    siz = size(intrsctM(:,:,slc));\n    %indV = sub2ind(siz, round(rowV), round(colV));\n    \n    structXYv = [xV';yV'];\n        \n    d = hypot(diff(xV), diff(yV)); % Distance Of Each Segment\n    contourLen = sum(d);\n    \n    structLen = structLen + contourLen;\n    \n    unifSlc = findnearest(zUnifScanV,zScanV(slc));\n    cc = bwconncomp(intrsctM(:,:,unifSlc));\n    intersectLen = 0;\n    for comp = 1:cc.NumObjects\n        compIndV = cc.PixelIdxList{comp};\n        [compiV,compjV] = ind2sub(siz,compIndV);\n        compXYv = [xScanV(compjV);yScanV(compiV)];\n        \n        distM = sepsq(structXYv,compXYv);\n        [~,indMinV] = min(distM,[],1);\n        indMinV = unique(indMinV);\n        segX = xV(indMinV);\n        segY = yV(indMinV);\n        \n        d = hypot(diff(segX), diff(segY)); % Distance Of Segment between points\n        segDist = sum(d);\n        \n        intersectLen = intersectLen + segDist;\n        \n    end\n    \n    intersectStructLen = intersectStructLen + intersectLen;\n    \nend\n\naddedPathLen = structLen - intersectStructLen;\naddedPathLenNorm = addedPathLen / structLen;\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/calc_surfDice_addPathLen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5744153241540364}}
{"text": "%PROBLEM SPECIFICATION\n% Specification of parameters, grid and boundary conditions\n\nglobal Re\n\ntic\nif geval == 1\t% Horizontal Poiseuille flow to the right\n  dt = 0.1;\t% Time step\n  tend = 10;\t% End time\n  Re = 100;\t% Reynolds number based on unit length and unit velocity\n  central = 1;\t% Enter 1 for central scheme or something else for upwind scheme\n  omega = 1/2;  % Omega-scheme for time-stepping\n  umax = 0.75;\t% Estimates of max. velocity components required for stability\n  vmax = 0;\t% condition for Adams-Bashforth-crank-Nicolson scheme\n  \n  xseglen = [1,1];\t% Enter segment lengths of horizontal boundary in\n\t\t% order of increasing x. Number of segments is arbitrary.\n\t\t% These segments are used for grid generation and boundary \n\t\t% conditions. \n  yseglen = [1,1];\t% Similar to xseglen in y-direction.\n  nx = [4,4];\t% Number of cells along x-segments.\n  ny = [4,4];\t% Number of cells along y-segments.\n\t\t\n  % Type of boundary condition: 1: no-slip\n  %\t\t\t\t2: inflow\n  %\t\t\t\t3: outflow\t\t\n  % Give type of boundary condition along lower (first row) and upper \n  %(second row) horizontal segments in order of increasing x:\n   \n  xbc = [1,1; 1,1];\n   \t\n  % Give type of boundary condition along left (first row) and right \n  % (second row) vertical segments in order of increasing y:\n  \n  ybc = [2,2; 3,3];\n    \nelseif geval == 2\t% Vertical Poiseuille flow upward\n  dt = 0.5;\t% Time step\n  tend = 10;\t% End time\n  Re = 100;\t% Reynolds number based on unit length and unit velocity\n  central = 1;\t% Enter 1 for central scheme or something else for upwind scheme\n  omega = 1/2;  % Omega-scheme for time-stepping\n  umax = 0;\t% Estimates of max. velocity components required for stability\n  vmax = 0.75;\t% condition for Adams-Bashforth-crank-Nicolson scheme\n\n  xseglen = [1,1];\t% Enter segment lengths of horizontal boundary in\n\t\t% order of increasing x. Number of segments is arbitrary.\n\t\t% These segments are used for grid generation and boundary \n\t\t% conditions. \n  yseglen = [1,1];\t% Similar to xseglen in y-direction.\n  nx = [8,16];\t% Number of cells along x-segments.\n  ny = [8,8];\t% Number of cells along y-segments.\n\t\t\n  % Type of boundary condition: 1: no-slip\n  %\t\t\t\t2: inflow\n  %\t\t\t\t3: outflow\t\t\n  % Give type of boundary condition along lower (first row) and upper \n  %(second row) horizontal segments in order of increasing x:\n   \n  xbc = [2,2; 3,3];\n   \t\n  % Give type of boundary condition along left (first row) and right \n  % (second row) vertical segments in order of increasing y:\n  \n  ybc = [1,1; 1,1];\n  \nelseif geval == 3\t% Backward facing step\n  dt = 3;\t% Time step\n  tend = 140;\t% End time\n  Re = 100;\t% Reynolds number based on unit length and unit velocity\n  central = 1;\t% Enter 1 for central scheme or something else for upwind scheme\n  omega = 1/2;  % Omega-scheme for time-stepping\n  umax = 1.25;\t% Estimates of max. velocity components required for stability\n  vmax = 0.25;\t% condition for Adams-Bashforth-Crank-Nicolson scheme\n  \t\t% (not used in program ns1)\n\n  xseglen = [5,5];\t% Enter segment lengths of horizontal boundary in\n\t\t% order of increasing x. Number of segments is arbitrary.\n\t\t% These segments are used for grid generation and boundary \n\t\t% conditions. \n  yseglen = [1,1];\t% Similar to xseglen in y-direction.\n  nx = [20,10];\t% Number of cells along x-segments.\n  ny = [25,25];\t% Number of cells along y-segments.\n\n  % Type of boundary condition: 1: no-slip\n  %\t\t\t\t2: inflow\n  %\t\t\t\t3: outflow\t\t\n  % Give type of boundary condition along lower (first row) and upper \n  %(second row) horizontal segments in order of increasing x:\n   \n  xbc = [1,1; 1,1];\n   \t\n  % Give type of boundary condition along left (first row) and right \n  % (second row) vertical segments in order of increasing y:\n  \n  ybc = [1,2; 3,3];\n  \nelseif geval == 4\t% Driven cavity\n  dt = 0.5;\t% Time step\n  tend = 25;\t% End time\n  Re = 200;\t% Reynolds number based on unit length and unit velocity\n  central = 1;\t% Enter 1 for central scheme or something else for upwind scheme\n  omega = 0.55;  % Omega-scheme for time-stepping\n  umax = 1;\t% Estimates of max. velocity components required for stability\n  vmax = 0;\t% condition for Adams-Bashforth-crank-Nicolson scheme\n\n  xseglen = [1,1];\t% Enter segment lengths of horizontal boundary in\n\t\t% order of increasing x. Number of segments is arbitrary.\n\t\t% These segments are used for grid generation and boundary \n\t\t% conditions. \n  yseglen = [1,1];\t% Similar to xseglen in y-direction.\n  nx = [15,15];\t% Number of cells along x-segments.\n  ny = [15,15];\t% Number of cells along y-segments.\n  % Type of boundary condition: 1: no-slip\n  %\t\t\t\t2: inflow\n  %\t\t\t\t3: outflow\t\t\n  % Give type of boundary condition along lower (first row) and upper \n  %(second row) horizontal segments in order of increasing x:\n   \n  xbc = [1,1; 2,2];\n   \t\n  % Give type of boundary condition along left (first row) and right \n  % (second row) vertical segments in order of increasing y:\n  \n  ybc = [1,1; 1,1];\n  \nelseif geval == 5\t% Uniform flow under angle alpha in [0,pi/2] without\n\t\t\t% segmentation\n  alpha = pi/4;\n  dt = 3;\t% Time step\n  tend = 60;\t% End time\n  Re = 100;\t% Reynolds number based on unit length and unit velocity\n  central = 1;\t% Enter 1 for central scheme or something else for upwind scheme\n  omega = 1/2;  % Omega-scheme for time-stepping\n  umax = abs(cos(alpha));% Estimates of max. velocity components required for stability\n  vmax = abs(sin(alpha));% condition for Adams-Bashforth-crank-Nicolson scheme\n\n  xseglen = [1];\t% Enter segment lengths of horizontal boundary in\n\t\t% order of increasing x. Number of segments is arbitrary.\n\t\t% These segments are used for grid generation and boundary \n\t\t% conditions. \n  yseglen = [1];\t% Similar to xseglen in y-direction.\n  nx = [2];\t% Number of cells along x-segments.\n  ny = [2];\t% Number of cells along y-segments.\n\n  % Type of boundary condition: 1: no-slip\n  %\t\t\t\t2: inflow\n  %\t\t\t\t3: outflow\t\t\n  % Give type of boundary condition along lower (first row) and upper \n  %(second row) horizontal segments in order of increasing x:\n   \n  xbc = [2; 3];\n   \t\n  % Give type of boundary condition along left (first row) and right \n  % (second row) vertical segments in order of increasing y:\n  \n  ybc = [2; 3];\n  \nelseif geval == 6\t% Uniform flow under angle alpha in [0,pi/2] with\n\t\t\t% segmentation\n  alpha = pi/4;\n  dt = 3;\t% Time step\n  tend = 60;\t% End time\n  Re = 100;\t% Reynolds number based on unit length and unit velocity\n  central = 1;\t% Enter 1 for central scheme or something else for upwind scheme\n  omega = 1/2;  % Omega-scheme for time-stepping\n  umax = abs(cos(alpha));% Estimates of max. velocity components required for stability\n  vmax = abs(sin(alpha));% condition for Adams-Bashforth-crank-Nicolson scheme\n\n  xseglen = [1,1];\t% Enter segment lengths of horizontal boundary in\n\t\t% order of increasing x. Number of segments is arbitrary.\n\t\t% These segments are used for grid generation and boundary \n\t\t% conditions. \n  yseglen = [1,1];\t% Similar to xseglen in y-direction.\n  nx = [2,6];\t% Number of cells along x-segments.\n  ny = [2,3];\t% Number of cells along y-segments.\n\n  % Type of boundary condition: 1: no-slip\n  %\t\t\t\t2: inflow\n  %\t\t\t\t3: outflow\t\t\n  % Give type of boundary condition along lower (first row) and upper \n  %(second row) horizontal segments in order of increasing x:\n   \n  xbc = [2,2; 3,3];\n   \t\n  % Give type of boundary condition along left (first row) and right \n  % (second row) vertical segments in order of increasing y:\n  \n  ybc = [2,2; 3,3];\n  \nelseif geval == 7\t% Horizontal Poiseuille flow to the left\n  dt = 0.5;\t% Time step\n  tend = 60;\t% End time\n  Re = 100;\t% Reynolds number based on unit length and unit velocity\n  central = 1;\t% Enter 1 for central scheme or something else for upwind scheme\n  omega = 1/2;  % Omega-scheme for time-stepping\n  umax = 0.75;\t% Estimates of max. velocity components required for stability\n  vmax = 0;\t% condition for Adams-Bashforth-crank-Nicolson scheme\n\n  xseglen = [1,1];\t% Enter segment lengths of horizontal boundary in\n\t\t% order of increasing x. Number of segments is arbitrary.\n\t\t% These segments are used for grid generation and boundary \n\t\t% conditions. \n  yseglen = [1,1];\t% Similar to xseglen in y-direction.\n  nx = [4,4];\t% Number of cells along x-segments.\n  ny = [4,4];\t% Number of cells along y-segments.\n\t\t\n  % Type of boundary condition: 1: no-slip\n  %\t\t\t\t2: inflow\n  %\t\t\t\t3: outflow\t\t\n  % Give type of boundary condition along lower (first row) and upper \n  %(second row) horizontal segments in order of increasing x:\n   \n  xbc = [1,1; 1,1];\n   \t\n  % Give type of boundary condition along left (first row) and right \n  % (second row) vertical segments in order of increasing y:\n  \n  ybc = [3,3; 2,2];    \n  \nelse\n  error('Wrong value in input for parameter geval')  \t\nend\n\t\t\nif (size(xseglen)~=size(nx))|(size(yseglen)~=size(ny))\n  error('Wrong correspondence between xseglen,nx or yseglen,ny in problem_specification')\nend\nif (size(xbc(1,:))~=size(nx))|(size(ybc(1,:))~=size(nx))\n  error('Wrong correspondence between nx,xbc or ny,ybc in problem_specification')\nend\n\ntijd = toc; disp(['problem_specification time = ',num2str(tijd)])\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/problem_specification.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5744153131286842}}
{"text": "clear,clc\n% compute the background image\nImzero = zeros(240,320,3);\nfor i = 1:5\nIm{i} = double(imread(['DATA/',int2str(i),'.jpg']));\nImzero = Im{i}+Imzero;\nend\nImback = Imzero/5;\n[MR,MC,Dim] = size(Imback);\n\n% Kalman filter initialization\nR=[[0.2845,0.0045]',[0.0045,0.0455]'];\nH=[[1,0]',[0,1]',[0,0]',[0,0]'];\nQ=0.01*eye(4);\nP = 100*eye(4);\ndt=1;\nA=[[1,0,0,0]',[0,1,0,0]',[dt,0,1,0]',[0,dt,0,1]'];\ng = 6; % pixels^2/time step\nBu = [0,0,0,g]';\nkfinit=0;\nx=zeros(100,4);\n\n% loop over all images\nfor i = 1 : 60\n  % load image\n  Im = (imread(['DATA/',int2str(i), '.jpg'])); \n  imshow(Im)\n  imshow(Im)\n  Imwork = double(Im);\n\n  %extract ball\n  [cc(i),cr(i),radius,flag] = extractball(Imwork,Imback,i);\n  if flag==0\n    continue\n  end\n\n  hold on\n    for c = -1*radius: radius/20 : 1*radius\n      r = sqrt(radius^2-c^2);\n      plot(cc(i)+c,cr(i)+r,'g.')\n      plot(cc(i)+c,cr(i)-r,'g.')\n    end\n  % Kalman update\ni\n  if kfinit==0\n    xp = [MC/2,MR/2,0,0]'\n  else\n    xp=A*x(i-1,:)' + Bu\n  end\n  kfinit=1;\n  PP = A*P*A' + Q\n  K = PP*H'*inv(H*PP*H'+R)\n  x(i,:) = (xp + K*([cc(i),cr(i)]' - H*xp))';\n  x(i,:)\n  [cc(i),cr(i)]\n  P = (eye(4)-K*H)*PP\n\n  hold on\n    for c = -1*radius: radius/20 : 1*radius\n      r = sqrt(radius^2-c^2);\n      plot(x(i,1)+c,x(i,2)+r,'r.')\n      plot(x(i,1)+c,x(i,2)-r,'r.')\n    end\n      pause(0.3)\nend\n\n% show positions\n  figure\n  plot(cc,'r*')\n  hold on\n  plot(cr,'g*')\n%end\n\n%estimate image noise (R) from stationary ball\n  posn = [cc(55:60)',cr(55:60)'];\n  mp = mean(posn);\n  diffp = posn - ones(6,1)*mp;\n  Rnew = (diffp'*diffp)/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/14243-2d-target-tracking-using-kalman-filter/target tracking using kalman/kalman.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5743804294138862}}
{"text": " % Copyright 2001, Brown University, Providence, Rhode Island.\n %\n % All Rights Reserved\n % \n % Permission to use this software for noncommercial research and\n % educational purposes is hereby granted without fee.\n % Redistribution, sale, or incorporation of this software into a\n % commercial product is prohibited.\n % \n % BROWN UNIVERSITY DISCLAIMS ANY AND ALL WARRANTIES WITH REGARD TO\n % THIS SOFTWARE,INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n % AND FITNESS FOR ANY PARTICULAR PURPOSE.  IN NO EVENT SHALL BROWN\n % UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n % DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n % DATA OR PROFITS.\n\n  function [a,b] = am282ab(x,y)\n\n   dims = size(x);\n   Np = dims(1)*dims(2);\n\n   a = zeros(dims);\n   b = zeros(dims);\n   for n=1:Np  % hack\n    if(y(n) ~= 1)\n     a(n) = 2*(1+x(n))/(1-y(n))-1;\n    else\n     a(n) = -1;\n    end\n   end\n\n   b = y;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/umFEKETE/am282ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5743804110227961}}
{"text": "function[newPop] = normGeomSelect(oldPop,options)\n% NormGeomSelect is a ranking selection function based on the normalized\n% geometric distribution.  \n%\n% function[newPop] = normGeomSelect(oldPop,options)\n% newPop  - the new population selected from the oldPop\n% oldPop  - the current population\n% options - options to normGeomSelect [gen probability_of_selecting_best]\n\n% Binary and Real-Valued Simulation Evolution for Matlab \n% Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay \n%\n% C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function\n% optimization: A Matlab implementation. ACM Transactions on Mathmatical\n% Software, Submitted 1996.\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 1, or (at your option)\n% any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details. A copy of the GNU \n% General Public License can be obtained from the \n% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\nq=options(2); \t\t\t\t% Probability of selecting the best\ne = size(oldPop,2); \t\t\t% Length of xZome, i.e. numvars+fit\nn = size(oldPop,1); \t\t\t% Number of individuals in pop\nnewPop = zeros(n,e); \t\t\t% Allocate space for return pop\nfit = zeros(n,1); \t\t\t% Allocates space for prob of select\nx=zeros(n,2); \t\t\t        % Sorted list of rank and id\nx(:,1) =[n:-1:1]'; \t\t\t% To know what element it was\n[y x(:,2)] = sort(oldPop(:,e)); \t% Get the index after a sort\nr = q/(1-(1-q)^n); \t\t\t% Normalize the distribution, q prime\nfit(x(:,2))=r*(1-q).^(x(:,1)-1); \t% Generates Prob of selection \nfit = cumsum(fit); \t\t\t% Calculate the cumulative prob. func\nrNums=sort(rand(n,1)); \t\t\t% Generate n sorted random numbers\nfitIn=1; newIn=1; \t\t\t% Initialize loop control\nwhile newIn<=n \t\t\t\t% Get n new individuals\n  if(rNums(newIn)<fit(fitIn)) \t\t\n    newPop(newIn,:) = oldPop(fitIn,:); \t% Select the fitIn individual \n    newIn = newIn+1; \t\t\t% Looking for next new individual\n  else\n    fitIn = fitIn + 1; \t\t\t% Looking at next potential selection\n  end\nend\n", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/\u300aMATLAB \u795e\u7ecf\u7f51\u7edc30\u4e2a\u6848\u4f8b\u5206\u6790\u300b\u6e90\u7a0b\u5e8f \u6570\u636e/chapter27/gaot/normGeomSelect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5743706663598389}}
{"text": "function y=fst(x,a,b)\nif x>b\n    y=1;\nelseif x<a\n    y=0;\nelse \n    y=(x-a)/(b-a);\nend\n        ", "meta": {"author": "TianfaYao", "repo": "ADRC", "sha": "6f1f96ebda1684c44af4dec4214b4880f4aa8cec", "save_path": "github-repos/MATLAB/TianfaYao-ADRC", "path": "github-repos/MATLAB/TianfaYao-ADRC/ADRC-6f1f96ebda1684c44af4dec4214b4880f4aa8cec/\u8d3a\u5e86\u6bd5\u4e1a\u8bba\u6587ADRC\u5168\u96c6\u5305\u4ec5\u7528\u4e8e\u5185\u90e8\u5171\u4eab\u4e0d\u8981\u5916\u4f20/MyLibrary/function/fst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581194449495, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5742608374827428}}
{"text": "%MINC Minimum combining classifier\n% \n% \tW = MINC(V)\n% \tW = V*MINC\n% \n% INPUT\n%   V     Set of classifiers\n%\n% OUTPUT\n%   W    Minimum combining classifier on V\n%\n% DESCRIPTION\n% If V = [V1,V2,V3, ... ] is a set of classifiers trained on the \n% same classes and W is the minimum combiner: it selects the class \n% with the minimum of the outputs of the input classifiers. This \n% might also be used as A*[V1,V2,V3]*MINC in which A is a dataset to \n% be classified. Consequently, if S is a dissimilarity matrix with\n% class feature labels (e.g. S = A*PROXM(A,'d')) then S*MINC*LABELD\n% is the nearest neighbor classifier.\n% \n% If it is desired to operate on posterior probabilities then the \n% input classifiers should be extended like V = V*CLASSC;\n%\n% The base classifiers may be combined in a stacked way (operating\n% in the same feature space by V = [V1,V2,V3, ... ] or in a parallel\n% way (operating in different feature spaces) by V = [V1;V2;V3; ... ]\n% \n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% MAPPINGS, DATASETS, VOTEC, MAXC, MEANC, MEDIANC, PRODC,\n% AVERAGEC, STACKED, PARALLEL\n%\n% EXAMPLES\n% See PREX_COMBINING\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: minc.m,v 1.2 2006/03/08 22:06:58 duin Exp $\n\nfunction w = minc(p1)\n\n\ttype = 'min'; % define the operation processed by FIXEDCC.\n\n\t% define the name of the combiner. \n\t% this is the general procedure for all possible calls of fixed combiners\n\t% handled by FIXEDCC\n\tname = 'Minimum combiner'; \n\n\tif nargin == 0\n\t\tw = prmapping('fixedcc','combiner',{[],type,name});\n\telse\n\t\tw = fixedcc(p1,[],type,name);\n\tend\n\n\tif isa(w,'prmapping')\n\t\tw = setname(w,name);\n\tend\n\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/minc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5742608282562358}}
{"text": "function s = resampdet(p,m,n);\n%RESAMPDET Deterministic resampling\n%\n%   Description\n%   S = RESAMPDET(P) returns a new set of indices according to the\n%   probabilities P. P is array of probabilities, which are not\n%   necessarily normalized, though they must be non-negative, and\n%   not all zero. The size of S is the size of P. \n%\n%   S = RESAMPDET(P,M,N) returns M by N matrix.\n%\n%   S = RESAMPDET(P,M) returns M by M matrix.\n%\n%   Default is to use no-sort resampling. For sorted resampling use\n%    [PS,PI]=SORT(P);\n%    S=PI(RESAMPDET(PS));\n%   Sorted re-sampling is slower but has smaller variance. Note\n%   that deterministic resampling is not unbiased. Stratified\n%   resampling (RESAMPSTR) is unbiased, almost as fast as\n%   deterministic resampling, and has only slightly larger\n%   variance.\n%\n%   In deterministic resampling indices are sampled using\n%   deterministic numbers u_j~(j-a)/n, for fixed a in [0,1) and\n%   n is length of P. Compare this to simple random resampling\n%   where u_j~U[0,n]. See, Kitagawa, G., Monte Carlo Filter and\n%   Smoother for Non-Gaussian Nonlinear State Space Models,\n%   Journal of Computational and Graphical Statistics, 5(1):1-25,\n%   1996. \n%\n%   See also RESAMPSIM, RESAMPRES, RESAMPSTR\n%\n% Copyright (c) 2003-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    [m,n]=size(p);\nelseif nargin==2\n    n=m;\nend\nmn=m.*n;\npn=p./sum(p(:)).*mn;\nfpn=floor(pn);\ns=zeros(m,n);\nk=0;\nc=0.5;\nfor i=1:numel(p)\n  if pn(i)>=1\n    a=fpn(i);\n    pn(i)=pn(i)-a;\n    s(k+[1:a])=i;\n    k=k+a;\n  end\n  c=c+pn(i);\n  if c>=1\n    k=k+1;\n    s(k)=i;\n    c=c-1;\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/mc/resampdet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5742608212618959}}
{"text": "% NANMIN Minimum value, ignoring NaNs.\n%    M = NANMIN(A) returns the minimum of A with NaNs treated as missing. \n%    For vectors, M is the smallest non-NaN element in A.  For matrices, M\n%    is a row vector containing the minimum non-NaN element from each\n%    column.  For N-D arrays, NANMIN operates along the first non-singleton\n%    dimension.\n% \n%    [M,NDX] = NANMIN(A) returns the indices of the minimum values in A.  If\n%    the values along the first non-singleton dimension contain more than\n%    one minimal element, the index of the first one is returned.\n%   \n%    M = NANMIN(A,B) returns an array the same size as A and B with the\n%    smallest elements taken from A or B.  Either one can be a scalar.\n% \n%    [M,NDX] = NANMIN(A,[],DIM) operates along the dimension DIM.\n% \n%    See also MIN, NANMAX, NANMEAN, NANMEDIAN, NANVAR, NANSTD.\n%\n%    Reference page in Doc Center\n%       doc stats/nanmin\n%\n%    Other functions named nanmin\n%\n%       distributed/nanmin    fints/nanmin\n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/m/+utils/+stat/nanmin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.5742523091355274}}
{"text": "function f = prolong(f, nOut)\n%PROLONG   Manually adjust the number of points used in a TRIGTECH.\n%   G = PROLONG(F, N) returns a TRIGTECH G where LENGTH(G) = N and G represents\n%   the same function as F but using more or less coefficients than F.\n%\n%   If N < LENGTH(F) the representation is compressed by chopping\n%   coefficients, which may result in a loss of accuracy.\n%\n%   If N > LENGTH(F) the coefficients are padded with zeros.\n%\n% See also ALIAS.\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 = length(f);\n\n% Return if nOut == n\nif ( nOut == n )\n    return\nend\n\n% Get coefficients\ncoeffs = f.coeffs;\n\n% If n is even extend to coeffs to n+1\nif ( mod(n,2) == 0 )\n    coeffs = [.5*coeffs(1,:);coeffs(2:end,:);.5*coeffs(1,:)];\n    n = n + 1;\nend\n\n% Return if nOut == n\nif ( nOut == n )\n    f.coeffs = coeffs;\n    f.values = f.coeffs2vals(f.coeffs);\n    f.values(:,f.isReal) = real(f.values(:,f.isReal));\n    return\nend\n\n% Pad with zeros when nOut > n:\nif ( nOut > n )\n    kup = ceil((nOut-n)/2);\n    kdown = floor((nOut-n)/2);\n    coeffs = [zeros(kup, size(coeffs, 2)); coeffs; zeros(kdown, size(coeffs,2))];\n    f.coeffs = coeffs;\n    f.values = f.coeffs2vals(f.coeffs);\n    f.values(:,f.isReal) = real(f.values(:,f.isReal));\n    return\nend\n\n% Chop coefficients when nOut < n:\nif ( nOut < n ) \n    kup = floor((n-nOut)/2);\n    kdown = ceil((n-nOut)/2);\n    coeffs(end-kdown+1:end,:) = [];\n    coeffs(1:kup,:) = [];\n    if ( kup < kdown ) \n        coeffs(1,:) = 2*coeffs(1,:); % scale coefficients in even case\n    end \n    f.coeffs = coeffs;\n    f.values = f.coeffs2vals(f.coeffs);\n    f.values(:,f.isReal) = real(f.values(:,f.isReal));\n    return\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/prolong.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.574226573184362}}
{"text": "function e = rmModelSearchFit_twoGaussiansDoGSigmasOnly(p,Y,XvYv,stim,t)\n% rmModelSearchFit_twoGaussians - actual fit function of rmSearchFit\n%\n% error = rmModelSearchFit_twoGaussians(p,Y,trends,Gx,Gy,stim,rawrss);\n%\n% Basic barebones fit of a single time-series. Error is returned in\n% percentage: 100% is RSS of unfitted time-series. This way we can quantify\n% the improvement of the fit independend of the variation in the raw\n% time-series.\n%\n% 2006/06 SOD: wrote it.\n% 2006/12 SOD: modifications for fmincon, this is litterally called >>10000\n% times so we cut every corner possible. \n\n\n% make RF (taken from rfGaussian2d)\np = -2.*(p.^2);\nRF = zeros(numel(XvYv),2);\nRF(:,1) = exp( (XvYv) ./ p(1) );\nRF(:,2) = exp( (XvYv) ./ p(2) );\n\n% make prediction (taken from rfMakePrediction)\nX = [stim * RF t];\n\n% fit\n%b = pinv(X)*Y; \n[U,S,V] = svd(X,0);\ns = diag(S); \ntol = numel(X) * eps(max(s));\nr = sum(s > tol);\nif (r == 0)\n    pinvX = zeros(size(X'));\nelse\n    s = diag(ones(r,1)./s(1:r));\n    pinvX = V(:,1:r)*s*U(:,1:r)';\nend\nb = pinvX*Y;\n\n% force positive fit\nb(1) = abs(b(1));\n\n%force negative b2 fit\nb(2) = -(abs(b(2)));\n\n% The center of the pRF should be positive. Thus, b(1)+b(2)>=0, or \n% b(2) should be larger than -b(1) (implemented).\nb(2) = max(b(2),-b(1));\n\n% force second Gaussian to be negative\nb(2) = -abs(b(2));\n\n% compute residual sum of squares (e)\ne = norm(Y - X*b);\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/rmModelSearchFit_twoGaussiansDoGSigmasOnly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.574170769904811}}
{"text": "function val= froNormMatn(x,y)\n\nval =sqrt(sum( (x(:)-y(:)).^2));", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/Shearlet/Util/froNormMatn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5741707522802821}}
{"text": "function L=computeLap(X)\n% Compute graph Laplacian\n\noptL=[];\noptL.NeighborMode='KNN';\noptL.k=5;\noptL.WeightMode='Cosine';   % 'Cosine' or 'HeatKernel'\noptL.t=1;\nL=constructW(X,optL);\n", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Function/supportFunctions/computeLap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5741578370606396}}
{"text": "function E = compose(disc, y)\n%FEVAL   Evaluation functional for CHEBCOLLOC.\n%   FEVAL(DISC, LOC, DIRN) returns a functional that evaluates the Chebyshev\n%   polynomial represented by a COLLOC discretization at the given point LOC as\n%   approached from the direction DIRN (either +1 or -1).\n%\n% See also CHEBCOLLOC.FEVAL\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nn = disc.dimension;\n\n% Find the collocation points and create an empty functional.\n[x, ~, v] = functionPoints(disc);\noffset = cumsum([0 ; n(:)]);\nN = offset(end);\nE = zeros(1, N);\n\n% Evaluate the given input at x:\ny = y(x);\n% Find which point is in which subinterval\nintnum = chebfun.whichInterval(disc.domain, y);\nintnum = max(intnum, 1); intnum = min(intnum,numel(n));\n% Loop over each interval:\nfor i = unique(intnum)'\n    j = i == intnum;\n    active = offset(i) + (1:n(i));\n    E(j,active) = barymat(y(j), x(active), v(active));\nend\n\nend\n\n\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebcolloc/compose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5741578154286755}}
{"text": "function DCV=plsldadcv(X,y,A,K,method,OPT,order)\n%+++ K-fold double cross validation Cross-validation for PLS-LDA\n%+++ Input:  X: m x n  (Sample matrix)\n%            y: m x 1  (measured property)\n%            A: The max PC for cross-validation\n%            K: fold. when K = m, it is leave-one-out CV\n%       method: pretreatment method. Contains: autoscaling, center etc.\n%          OPT: =1 Print process.\n%               =0 No print.\n%               pareto,minmax,center or none.\n%+++ Order: =1  sorted,default. For CV partition.\n%           =0  random. \n%+++ Output: Structural data: CV\n%+++ Hongdong Li, Oct. 16, 2008.\n%+++ Revised in Jan.12, 2009.\n\nif nargin<7;order=1;end;\nif nargin<6;OPT=1;end;\nif nargin<5;method='autoscaling';end;\nif nargin<4;K=10;end;\nif nargin<3;A=2;end;\n\n\ncheck=0; %+++ status variable:  1: Inf\n\nif order==1\n  [y,indexyy]=sort(y);\n  X=X(indexyy,:);\nelse\n  indexyy=randperm(length(y));\n  X=X(indexyy,:);\n  y=y(indexyy);\nend\n\n\nA=min([size(X,1)-ceil(length(y)/K) size(X,2) A]);\nyytest=[];YR=[];\n[Mx,Nx]=size(X);\ngroups = 1+rem(0:Mx-1,K);\nyytest=[];yp=[];nLV=zeros(K,1);\nfor group=1:K\n    testk = find(groups==group);  calk = find(groups~=group);\n    Xcal=X(calk,:);ycal=y(calk);\n    Xtest=X(testk,:);ytest=y(testk);\n    \n    CV=plsldacv(Xcal,ycal,A,K,method,0,order);\n    if CV.check==1;check==1;break;end;\n    LDA=plslda(Xcal,ycal,CV.optPC,method);\n    ypred=plsldaval(LDA,Xtest,ytest);\n    yytest=[yytest;ytest];\n    yp=[yp;ypred;];\n    nLV(group)=CV.optPC;       \n    if OPT==1;fprintf('The %dth outer loop finished.\\n',group);end;\nend\n\n%+++ Find the most frequently chosen nLV.\nuniLV=unique(nLV);\nfor j=1:length(uniLV); freq(j)=length(find(nLV==uniLV(j)));end\n[maxf,maxindex]=max(freq);\noptPC=uniLV(maxindex(1));\n\n\n%+++ output\nif check==0\n  F=roccurve(yytest,yp,0);\n  error=sum(sign(yp)~=yytest)/Mx; \n  DCV.method=method;\n  DCV.check=check;\n  DCV.error=error; \n  DCV.Sensitivity=F.sensitivity;\n  DCV.Specificity=F.specificity;\n  DCV.nLV=nLV;\n  DCV.optPC=optPC;\nelseif check==1\n  DCV.method=method;\n  DCV.check=check;  \nend\n  \n  ", "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/plslda/plsldadcv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5741578148338145}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Jellyfish Example Courtesy of Alexander P. Hoover, PhD\n%\n% Converted from IBAMR: 1/16/2018 by NAB.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Make_Jelly_Geometry()\n\nclose all;\nclear all;\nL = 8;                              % height of computational domain (m) for keeping desired resolution\nLh = 10;                            % actual height of computational domain (m) (MATCHES INPUT2D)\nLw = 3;                             % width of computational domain (m) (MATCHES INPUT2D)\nN = 96;                            % number of Cartesian grid meshwidths at the finest level of the AMR grid\ndx = L/N;                           % Cartesian mesh width (m)\nds = dx/2;\n \na=.5;                               % bell radius (semi-minor axis, horizontal axis, note width=2a)\nb=.75;                              % bell semi-major axis \nd=-0.25;\nfactor_a=.8;\n \nF=1e5; %5e0\n \ntheta=zeros(1000,1);\ntheta_lim=asin(d/b);\ntheta_test=pi/2;\n \nx_points=zeros(1000,1);\nz_points=zeros(1000,1);\nid_points=zeros(1000,1);\noffset = 0;\n \nkappa_spring = 1e7; %1e5               % spring constant (Newton)\nkappa_beam = 2.5e5; %1e5    %5e3              % beam stiffness constant (Newton m^2)\n%kappa_beam_flexible = kappa_beam/5;   % beam stiffness constant (Newton m^2)\nkappa_target = kappa_spring;           % target point penalty spring constant (Newton)\n \nc=0;\nwhile(theta_test<(pi-theta_lim))\n    c=c+1;\n    theta(c)=theta_test;\n     \n    x_points(c)=a*cos(theta(c));\n    z_points(c)=b*sin(theta(c));\n    id_points(c)=c-1;\n     \n    theta_test=ds/((a*sin(theta(c)))^(2)+(b*cos(theta(c)))^(2))^(.5)+theta(c);\n     \nend\n \nc_stiff=c;\n \n \nnpts=2*c-1;\nnpts_wing=floor(npts/2);\nnpts_musc=floor(npts_wing/4);\n \nfor j=(c+1):(npts)\n    x_points(j)=-1*x_points(j-c+1);\n    z_points(j)=z_points(j-c+1);\n    id_points(j)=j-1;\nend\n \n\nmesh_name = 'jelly';\nxShift = 1.5;\nyShift = 2;\n \nx_points=x_points(1:npts)+xShift;\nz_points=z_points(1:npts)+yShift;\nit_points=id_points(1:npts);\n \nplot(x_points(:),z_points(:),'*'); hold on;\naxis([0 8 0 8])\n\n% Lag Pts to Mess up Flow At Edge\nxBlock = ds:4*ds:Lw-ds;\nyBlock = (Lh-5*ds)*ones(1,length(xBlock))+ds;\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Print .vertex information\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nvertex_fid = fopen([mesh_name num2str(N) '.vertex'], 'w');\n \n    fprintf(vertex_fid, '%d\\n', npts + npts_musc*2 + length(xBlock));\n    lag_ct = 0;\n    \n    %\n    % bell\n    %\n    for j=1:npts\n        fprintf(vertex_fid, '%1.16e %1.16e\\n', x_points(j), z_points(j));\n        lag_ct = lag_ct + 1;\n    end\n \n    %\n    % muscles\n    %\n    for s = 1:npts_musc\n        fprintf(vertex_fid, '%1.16e %1.16e\\n', x_points(npts_wing+1-npts_musc+s), z_points(npts_wing+1-npts_musc+s));\n        plot(x_points(npts_wing+1-npts_musc+s),z_points(npts_wing+1-npts_musc+s),'r*'); hold on;\n        lag_ct = lag_ct + 1;\n    end\n    for s = 1:npts_musc\n        fprintf(vertex_fid, '%1.16e %1.16e\\n', x_points(npts-npts_musc+s), z_points(npts-npts_musc+s));\n        plot(x_points(npts-npts_musc+s),z_points(npts-npts_musc+s),'r*'); hold on;\n        lag_ct = lag_ct + 1;\n    end\n    \n    for ii=1:length(xBlock)\n        fprintf(vertex_fid, '%1.16e %1.16e\\n', xBlock(ii), yBlock(ii));\n    end\n\nfclose(vertex_fid);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Print .spring information\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nspring_fid = fopen([mesh_name num2str(N) '.spring'], 'w');\n    \n    npts_spring_type1=npts-1;\n \n    fprintf(spring_fid, '%d\\n', npts-1 + npts_musc);\n \n    fprintf('\\nNumber of springs before muscles: %d \\n\\n',npts-1)\n    \n    factor = 1;%ds^2/ds;\n    \n    %\n    % bell\n    %\n    for s = 1:c-1\n        resting=sqrt((x_points(s)-x_points(s+1))^(2)+(z_points(s)-z_points(s+1))^(2));\n        fprintf(spring_fid, '%d %d %1.16e %1.16e %d\\n', id_points(s)+1, id_points(s+1)+1, kappa_spring*ds/(ds^2)*factor, resting, 1);\n    end\n    for s = c+1:npts-1\n        resting=sqrt((x_points(s)-x_points(s+1))^(2)+(z_points(s)-z_points(s+1))^(2));\n        fprintf(spring_fid, '%d %d %1.16e %1.16e %d\\n', id_points(s)+1, id_points(s+1)+1, kappa_spring*ds/(ds^2)*factor, resting, 1);\n    end\n    resting=sqrt((x_points(1)-x_points(c+1))^(2)+(z_points(1)-z_points(c+1))^(2));\n    fprintf(spring_fid, '%d %d %1.16e %1.16e %d\\n', id_points(1)+1, id_points(c+1)+1, kappa_spring*ds/(ds^2)*factor, resting, 1);\n\n    %\n    % muscles\n    %\n    for s = 1:npts_musc\n        fprintf(spring_fid, '%d %d %1.16e %1.16e %d\\n',npts+s-1+1, npts+s+npts_musc-1+1, F, 0, 1);\n    end\n \n \n    fclose(spring_fid);\n \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Print .nonInv_beam information\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nbeam_fid = fopen([mesh_name num2str(N) '.nonInv_beam'], 'w');\n \n    fprintf(beam_fid, '%d\\n', npts-2);\n\n    factor=1;% = (ds^4)/ds;\n    \n    for s = 2:c-1\n        C1 = x_points(s-1)+x_points(s+1)-2*x_points(s);\n        C2 = z_points(s-1)+z_points(s+1)-2*z_points(s);\n        fprintf(beam_fid, '%d %d %d %1.16e %1.16e %1.16e\\n', id_points(s-1)+1, id_points(s)+1, id_points(s+1)+1, kappa_beam*ds/(ds^4)*factor, C1, C2);\n    end\n    for s = c+2:npts-1\n        C1 = x_points(s-1)+x_points(s+1)-2*x_points(s);\n        C2 = z_points(s-1)+z_points(s+1)-2*z_points(s);\n        fprintf(beam_fid, '%d %d %d %1.16e %1.16e %1.16e\\n', id_points(s-1)+1, id_points(s)+1, id_points(s+1)+1, kappa_beam*ds/(ds^4)*factor, C1, C2);\n    end\n\n    C1 = x_points(c+2)+x_points(1)-2*x_points(c+1);\n    C2 = z_points(c+2)+z_points(1)-2*z_points(c+1);\n    fprintf(beam_fid, '%d %d %d %1.16e %1.16e %1.16e\\n', id_points(c+2)+1, id_points(c+1)+1, id_points(1)+1, kappa_beam*ds/(ds^4)*factor, C1, C2);\n\n    C1 = x_points(c+1)+x_points(2)-2*x_points(1);\n    C2 = z_points(c+1)+z_points(2)-2*z_points(1);\n    fprintf(beam_fid, '%d %d %d %1.16e %1.16e %1.16e\\n', id_points(c+1)+1, id_points(1)+1, id_points(2)+1, kappa_beam*ds/(ds^4)*factor, C1, C2);\n\n \n    fclose(beam_fid);\n \n    \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   \n%\n% PRINT TARGET POINTS!!!\n%\n% print target points (flow blocker along edge)\nk_Target = 2.5e6;\nnBefore = lag_ct; % Counts pts in jellyfish for bookkeeping for .target file\nstruct_name = ['jelly' num2str(N)];\nprint_Lagrangian_Target_Pts(xBlock,k_Target,struct_name,nBefore)    \n    \n    \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints TARGET points to a file called 'struct_name'.target\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Target_Pts(xLag,k_Target,struct_name,nBefore)\n\n    N = length(xLag);\n    Nstart = nBefore+1;\n    Nend = nBefore+N;\n\n    target_fid = fopen([struct_name '.target'], 'w');\n\n    fprintf(target_fid, '%d\\n', N );\n\n    %Loops over all Lagrangian Pts.\n    for s = Nstart:Nend\n        fprintf(target_fid, '%d %1.16e\\n', s, k_Target);\n    end\n\n    fclose(target_fid); ", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Examples_Education/Convergence/Jellyfish/Simulation_Skeletons/Re37pt5/Res_96_120x36/Make_Jelly_Geometry.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.5741578142389532}}
{"text": "function lam_msg = CPD_to_lambda_msg(CPD, msg_type, n, ps, msg, p, evidence)\n% CPD_TO_LAMBDA_MSG Compute lambda message (gaussian)\n% lam_msg = compute_lambda_msg(CPD, msg_type, n, ps, msg, p, evidence)\n% Pearl p183 eq 4.52\n\nswitch msg_type\n case 'd',\n  error('gaussian_CPD can''t create discrete msgs')\n case 'g',\n  cps = ps(CPD.cps);\n  cpsizes = CPD.sizes(CPD.cps);\n  self_size = CPD.sizes(end);\n  i = find_equiv_posns(p, cps); % p is n's i'th cts parent\n  psz = cpsizes(i);\n  if all(msg{n}.lambda.precision == 0) % no info to send on\n    lam_msg.precision = zeros(psz, psz);\n    lam_msg.info_state = zeros(psz, 1);\n    return;\n  end\n  [m, Q, W] = gaussian_CPD_params_given_dps(CPD, [ps n], evidence);\n  Bmu = m;\n  BSigma = Q;\n  for k=1:length(cps) % only get pi msgs from cts parents\n    pk = cps(k);\n    if pk ~= p\n      %bk = block(k, cpsizes);\n      bk = CPD.cps_block_ndx{k};\n      Bk = W(:, bk);\n      m = msg{n}.pi_from_parent{k}; \n      BSigma = BSigma + Bk * m.Sigma * Bk';\n      Bmu = Bmu + Bk * m.mu;\n    end\n  end\n  % BSigma = Q + sum_{k \\neq i} B_k Sigma_k B_k'\n  %bi = block(i, cpsizes);\n  bi = CPD.cps_block_ndx{i};\n  Bi = W(:,bi);\n  P = msg{n}.lambda.precision;\n  if (rcond(P) > 1e-3) | isinf(P)\n    if isinf(P) % Y is observed\n      Sigma_lambda = zeros(self_size, self_size); % infinite precision => 0 variance\n      mu_lambda = msg{n}.lambda.mu; % observed_value;\n    else\n      Sigma_lambda = inv(P);\n      mu_lambda = Sigma_lambda * msg{n}.lambda.info_state;\n    end\n    C = inv(Sigma_lambda + BSigma);\n    lam_msg.precision = Bi' * C * Bi;\n    lam_msg.info_state = Bi' * C * (mu_lambda - Bmu);\n  else\n    % method that uses matrix inversion lemma to avoid inverting P\n    A = inv(P + inv(BSigma));\n    C = P - P*A*P;\n    lam_msg.precision = Bi' * C * Bi;\n    D = eye(self_size) - P*A;\n    z = msg{n}.lambda.info_state;\n    lam_msg.info_state = Bi' * (D*z - D*P*Bmu);\n  end\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/CPDs/@gaussian_CPD/CPD_to_lambda_msg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5741578142389531}}
{"text": "% Test file for singfun/flipud.m\n\nfunction pass = test_flipud(pref)\n\n% Get preferences.\nif ( nargin < 1 )\n    pref = chebfunpref();\nend\n\n% Generate a few random points to use as test values.\nseedRNG(6178);\nd = 10;\nx = 2*(1-10^(-d)) * rand(100, 1) - (1-10^(-d));\n\n% The order of the exponents:\na = 0.64;\nb = -0.64;\nc = 1.28;\nd = -1.28;\n\n%%\n% Spot-check derivatives for a couple of functions.\n\n% fractional root at the left endpoint\ndata.exponents = [a 0];\ndata.singType = {'root', 'none'};\nf = singfun(@(x) (1+x).^a.*exp(x), data, pref);\ng = flipud(f);\nvals_df = feval(g, x); \nflip_exact = @(x) (1-x).^a.*exp(-x);\nvals_exact = feval(flip_exact, x);\nerr = vals_df - vals_exact;\npass(1) = (norm(err, inf) < 1e1*eps*norm(vals_exact, inf));\n    \n    \n% fractional pole at the left endpoint\ndata.exponents = [d 0];\ndata.singType = {'sing', 'none'};\nf = singfun(@(x) (1+x).^d.*sin(x), data, pref);\ng = flipud(f);\nvals_df = feval(g, x); \nflip_exact = @(x) -(1-x).^d.*sin(x);\nvals_exact = feval(flip_exact, x);\nerr = vals_df - vals_exact;\npass(2) = (norm(err, inf) < 10*eps*norm(vals_exact, inf));\n\n% fractional root at the right endpoint\ndata.exponents = [0 c];\ndata.singType = {'none', 'root'};\nf = singfun(@(x) (1-x).^c.*cos(x), data, pref);\ng = flipud(f);\nvals_df = feval(g, x);\nflip_exact = @(x) (1+x).^c.*cos(x);\nvals_exact = feval(flip_exact, x);\nerr = vals_df - vals_exact;\npass(3) = (norm(err, inf) < 1e1*eps*norm(vals_exact, inf));\n    \n    \n% fractional pole at the right endpoint\ndata.exponents = [0 b];\ndata.singType = {'none', 'sing'};\nf = singfun(@(x) (1-x).^b.*(x.^5), data, pref);\ng = flipud(f);\nvals_df = feval(g, x);\nflip_exact = @(x) -(1+x).^b.*(x.^5);\nvals_exact = feval(flip_exact, x);\nerr = vals_df - vals_exact;\npass(4) = (norm(err, inf) < 1e1*eps*norm(vals_exact, inf));\n\n% a combination of fractional pole and fractional root\ndata.exponents = [b c];\ndata.singType = {'sing', 'root'};\nf = singfun(@(x) (1+x).^b.*sin(x).*(1-x).^c, data, pref);\ng = flipud(f);\nvals_df = feval(g, x);\nflip_exact = @(x) -(1-x).^b.*sin(x).*(1+x).^c;\nvals_exact = feval(flip_exact, x);\nerr = vals_df - vals_exact;\npass(5) = (norm(err, inf) < 1e1*eps*norm(vals_exact, inf));\n    \n    \n%%\n% Verify that calling flipud() gives the reasonably accurate answer as direct \n% construction.\n\ndata.exponents = [b b];\ndata.singType = {'sing', 'sing'};\nf = singfun(@(x) (1+x).^b.*sin(2*x).*(1-x).^b, data, pref);\ng = flipud(f);\nvals_df = feval(g, x);\nflip_exact = @(x) -(1-x).^b.*sin(2*x).*(1+x).^b;\nvals_exact = feval(flip_exact, x);\nerr = vals_df - vals_exact;\npass(6) = (norm(err, inf) < 1e1*eps*norm(vals_exact, inf));\n\n%%\n% Check higher-order derivatives.\n\ndata.exponents = [a b];\ndata.singType = {'root', 'sing'};\nf = singfun(@(x) (1+x).^a.*sin(x).*(1-x).^b, data, pref);\ndf2 = flipud(f);\nvals_df2 = feval(df2, x);\ndf2_exact = @(x) -(1-x).^a.*sin(x).*(1+x).^b;\nvals_exact = feval(df2_exact, x);\nerr = vals_df2 - vals_exact;\npass(7) = (norm(err, inf) < 5*eps*norm(vals_exact, inf));\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/singfun/test_flipud.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387956435734, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.5741578113118846}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D \n% shape modeling and analysis toolkit. \n% It is a software package developed at Shenlab in Center for Neuroimaging, \n% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)\n% It is available to the scientific community as copyright freeware \n% under the terms of the GNU General Public Licence.\n% \n% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University\n% \n% This file is part of SPHARM-MAT.\n% \n% SPHARM-MAT is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% SPHARM-MAT is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with SPHARM-MAT. If not, see <http://www.gnu.org/licenses/>.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\n% Rotate around x, y, z (counterclockwise when looking towards the origin)\n%\n\nfunction R = rotate_mat(x, y, z)\n% It is assumed that this matrix is muplied from the hind, rotating objects\n% along x-axis, y-axis, and z-axis in this order.\n\nRx = [      1       0       0; ...\n            0  cos(x) -sin(x); ...\n            0  sin(x)  cos(x)];\n\nRy = [ cos(y)       0  sin(y); ...\n            0       1       0; ...\n      -sin(y)       0  cos(y)];\n\nRz = [ cos(z) -sin(z)       0; ...\n       sin(z)  cos(z)       0; ...\n            0      0        1];\n\nR = Rz*Ry*Rx;\n\nreturn;", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SpharmToolbox/code/rotate_mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5741578083848158}}
{"text": "function tfplot(imp);\n\n% tfplot(imp);\n%\n% Plot the transfer function of the filter whose impulse response is imp.\n%\n% Multiple transfer functions can be plotted simultaneously where each\n% impulse response represents one row of imp.\n\n% Copyright 2012 Evrytania LLC (http://www.evrytania.com)\n%\n% Written by James Peroulas <james@evrytania.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 <http://www.gnu.org/licenses/>.\n\nerror(nargchk(1,1,nargin));\n%error(chk_param(imp,'imp','vector'));\n\nn_pts_min=4096;\nif (isvector(imp))\n  n_pts=max(n_pts_min,length(imp));\nelse\n  n_pts=max(n_pts_min,size(imp,2));\nend\n\nf=linspace(0,2,n_pts+1);\nf=f(1:end-1);\nf(f>=1)=f(f>=1)-2;\nf=fftshift(f);\nm=transpose(fftshift(fft(transpose(imp),n_pts)));\nplot(f,db20(abs(m)));\n\nxlabel('Frequency/(fs/2)');\nylabel('Power gain (dB)');\ntitle('Transfer function');\nzgo;\n\n", "meta": {"author": "JiaoXianjun", "repo": "rtl-sdr-LTE", "sha": "037a25f164f17b1a1d82e2eb02285550f50af9b9", "save_path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE", "path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE/rtl-sdr-LTE-037a25f164f17b1a1d82e2eb02285550f50af9b9/matlab/tfplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938799869521, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5741578037204017}}
{"text": "clear all\n    % Generarea matricei A\nA=[11,12,13,14;21,22,23,24;31,32,33,34;41,42,43,44]\n    % Manipulari cu matricea A\nB=A(2,2:4)\nC=A(2,:)\nD=A(1:2:3,:)\nE(:,[3,5,7])=A(:,2:4)\nF=A(:,[1 3 2 4])\n    % Utilizarea filtrelor logice\nFilt=zeros(size(A));\nFilt(1,3)=1; Filt(2,4)=1; Filt(4,4)=1;\n    % Transforarea matricei numerice in matrice logica\nFilt=logical(Filt)\nA_filtrat=A(Filt)'\n    % Stergerea unei coloane din matricea A\nA(:,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/8416-widely-used-programming-environments-in-electrical-engineering-matlab/3/Ex_3_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5741578031255401}}
{"text": "function [Qout,fcount] = quadgui_adaptive(F,a,b,tol,varargin)\n%QUADGUI  Demonstrate numerical evaluation of a definite integral.\n%   Q = QUADGUI(F,A,B) shows the steps in approximating the integral\n%   of F(x) from A to B by adaptive extrapolated Simpson's quadrature.\n%\n%   The shaded area shows the integral over the current subinterval.\n%   The color switches to green when the desired accuracy is obtained.\n%\n%   Q = QUADGUI(F,A,B,tol) uses the given tolerance instead of 1.e-4.\n%\n%   The first argument, F, is a function handle or an anonymous function\n%   that defines F(x).\n%   Arguments beyond the first four, Q = QUADGUI(F,a,b,tol,p1,p2,...),\n%   are passed on to the integrand, F(x,p1,p2,..).\n%\n%   [Q,fcount] = QUADGUI(F,...) also counts the number of evaluations\n%   of F(x).\n%   \n%   Examples:\n%        F                      a     b       tol(optional)\n%      humps(x)                 0     1\n%      humps(x)                 0     1       1.e-6\n%      humps(x)                -1     2\n%      sin(x)                   0     pi      1.e-8\n%      cos(x)                   0     9*pi/2  1.e-6\n%      sqrt(x)                  0     1       1.e-8\n%      -sqrt(x)*log(x)          eps   1       1.e-8\n%      1/(3*x-1)                0     1\n%      t^(8/3)*(1-t)^(10/3)     0     1       1.e-8\n%      tan(sin(x))-sin(tan(x))  0     pi\n%\n%      quadgui(@(x)F,a,b)\n%\n%   See also QUADTX, QUAD, QUADL, DBLQUAD.\n\n%   Copyright 2014 Cleve Moler\n%   Copyright 2014 The MathWorks, Inc.\n\nshg\nclf reset\nset(gcf,'menubar','none','numbertitle','off','name','Quad gui')\n\n% Default tolerance\nif nargin < 4 | isempty(tol)\n   tol = 1.e-4;\nend\n\n% Default function and interval.\nif nargin < 3\n   F = @humps;\n   a = 0;\n   b = 1;\nend\n\n% Initialization\nc = (a + b)/2;\nfa = F(a,varargin{:});\nfc = F(c,varargin{:});\nfb = F(b,varargin{:});\n\n% Scale the plot\nh = b - a;\nx = [a c b];\ny = [fa fc fb];\nmaxy = max(y);\nminy = min(y);\nfor k = 1:63\n   v = F(a+k*h/64,varargin{:});\n   maxy = real(max(maxy,v));\n   miny = real(min(miny,v));\nend\nset(gcf,'userdata',0)\nhold on\np(1) = fill(a,fa,'k');\np(2) = fill(b,fb,'k');\np(3) = plot(x,y,'.','markersize',16);\nhold off\ns = (maxy - miny)/20;\naxis([a b miny-s maxy+s])\nq(1) = uicontrol('string','step', ...\n   'units','normal','pos',[.65 .02 .08 .06], ...\n   'callback','set(gcf,''userdata'',1)');\nq(2) = uicontrol('string','auto', ...\n   'units','normal','pos',[.75 .02 .08 .06], ...\n   'callback','set(gcf,''userdata'',2)');\nq(3) = uicontrol('string','quit', ...\n   'units','normal','pos',[.85 .02 .08 .06], ...\n   'callback','set(gcf,''userdata'',3)');\n\n% Recursive call \n[Q,k] = quadguistep(F, a, b, tol, fa, fc, fb, varargin{:});\nfcount = k + 3;\n\n% Finish\ntitle(sprintf('Q = %8.4f, fcount = %4.0f',Q,fcount))\ndelete(p(1:2));\ndelete(q(1:2));\nset(q(3),'string','close','callback','close(gcf)')\nif nargout > 0, Qout = Q; end\n\n\n% ---------------------------------------------------------\n\nfunction [Q,fcount] = quadguistep(F,a,b,tol,fa,fc,fb,varargin)\n\n% Recursive subfunction used by quadtx.\n\nh = b - a; \nc = (a + b)/2;\nd = (a + c)/2;\ne = (c + b)/2;\nfd = F(d,varargin{:});\nfe = F(e,varargin{:});\nQ1 = h/6 * (fa + 4*fc + fb);\nQ2 = h/12 * (fa + 4*fd + 2*fc + 4*fe + fb);\n\nu1 = a:h/64:c;\nv1 = polyinterp([a d c],[fa fd fc],u1);\nu1 = [a u1 c];\nv1 = [0 v1 0];\nu2 = c:h/64:b;\nv2 = polyinterp([c e b],[fc fe fb],u2);\nu2 = [c u2 b];\nv2 = [0 v2 0];\nif (abs(Q2 - Q1) <= tol)\n   color = [0 2/3 0];\nelse\n   color = [.6 .6 .6];\nend\np = flipud(get(gca,'child'));\nx = [get(p(3),'xdata') d e];\ny = [get(p(3),'ydata') fd fe];\nset(p(1),'xdata',u1,'ydata',v1,'facecolor',color)\nset(p(2),'xdata',u2,'ydata',v2,'facecolor',color)\nset(p(3),'xdata',x,'ydata',y)\nset(gca,'xtick',sort(x),'xticklabel',[]);\ntitle(num2str(length(x)))\npause(.25)\nwhile get(gcf,'userdata') == 0\n   pause(.25)\nend\nif get(gcf,'userdata') == 1\n   set(gcf,'userdata',0)\nend\n\nif (abs(Q2 - Q1) <= tol) | (get(gcf,'userdata') == 3)\n   Q  = Q2 + (Q2 - Q1)/15;\n   fcount = 2;\nelse\n   [Qa,ka] = quadguistep(F, a, c, tol, fa, fd, fc, varargin{:});\n   [Qb,kb] = quadguistep(F, c, b, tol, fc, fe, fb, varargin{:});\n   Q  = Qa + Qb;\n   fcount = ka + kb + 2;\nend\n", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/\u7b2c\u516d\u7ae0 \u7ebf\u6027\u65b9\u7a0b\u7ec4\u7684\u76f4\u63a5\u6cd5/quadgui_adaptive.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.5741494066349498}}
{"text": "function lev = QLmaxlev(sizeX, filtername)\n%-----------------------------------------------------------------------------\n% QLmaxlev\n% This function determines the maximum level possible for the QL-schemes.\n%\n% Syntax: lev = QLmaxlev(sizeX, filtername)\n%\n% QLmaxlev is a utility for the lifting scheme decomposition. It helps one to \n% avoid silly values for the maximum level in the lifting scheme decomposition.\n% \n% lev is the integer outcome.\n% \n% sizeX is an integer row vector of dimension 2. Usually it will be the size of\n% an image.\n%\n% filtername must be a string from the set:\n% {Neville2, Neville4, Neville6, Neville8, MaxMin, MinMin, MaxMax}\n%\n% See also: QLiftDec2, QLiftRec2, wmaxlev\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw <Paul.de.Zeeuw@cwi.nl>  http://homepages.cwi.nl/~pauldz/\n% Last Revision: February 17, 2003.\n% (c) 1999-2003 Stichting CWI, Amsterdam\n%-----------------------------------------------------------------------------\n%Firstly, check input data\nif nargin ~= 2\n  error(' QLmaxlev - number of arguments should be 2 ');\nend\nif ~ischar(filtername)\n  error(' QLmaxlev - format of filtername should be character array ');\nend\n%\nswitch lower(filtername)\n case 'neville2'\n   diam =  3;\n case 'neville4'\n   diam =  5;\n case 'neville6'\n   diam =  7;\n case 'neville8'\n   diam = 11;\n case 'maxmin'\n   diam =  3;\n case 'maxmax'\n   diam =  3;\n case 'minmax'\n   diam =  3;\n case 'minmin'\n   diam =  3;\n otherwise\n   error(' QLmaxlev - unknown filter ')\nend\n%\nif isempty(sizeX)\n  lev = [];\n  return;\nelse\n  lev=0;\n  n=min(sizeX);\n  z=2*diam-1;\n  while z<=n\n    lev=lev+2;\n    z=2*z-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/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/QLmaxlev.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5741493942975892}}
{"text": "function s = volumeVisualization(x,y,z,v)\n%volumeVisualization Engine for choosing y-z planes to view.\n%   s = volumeVisualization(X,Y,Z,V) returns a structure \n%   containing information about the visualization of volume\n%   data described by X,Y,Z,V.  The fields are:\n%          addSlicePlane -- function handle to add a slice\n%                           plane at location x\n%   deleteLastSlicePLane -- function handle to delete the\n%                           last slice plane added\n%                   xMin -- minimum x location for a plane\n%                   xMax -- maximum x location for a plane\n%\n%      Example:\n%      [x,y,z,v] = flow;\n%      s = volumeVisualization(x,y,z,v);\n%      s.addSlicePlane(3.7)\n%      s.addSlicePlane(7.5)\n%      pause\n%      s.deleteLastSlicePlane()\n%      pause\n%      s.deleteLastSlicePlane()\n\n%   Copyright 2007 The MathWorks, Inc.\n\n%% Store handles to the various planes\n%initialize handle to axis\n%initialize handle to slice plane\nhAxis = [];         \nhSlicePlanes = [];  \n\n%% Create data for generic slice through yz-plane\n[yd,zd] = meshgrid(linspace(min(y(:)),max(y(:)),100), ...\n    linspace(min(z(:)),max(z(:)),100));\n\n%% Plot the volume initially\ninitDisplay()\n\n%% Nested Functions\n    function addSlicePlane(xLoc)\n    %addSlicePlane   Add a slice plane xLoc.\n        xd            = xLoc*ones(size(yd));\n        newSlicePlane = slice(hAxis, x, y, z, v, xd, yd, zd);\n        hSlicePlanes   = [ hSlicePlanes, newSlicePlane ];\n        set(newSlicePlane,'FaceColor'      ,'interp',...\n                          'EdgeColor'      ,'none'  ,...\n                          'DiffuseStrength',.8       );\n    end\n\n    function deleteLastSlicePlane()\n    %deleteLastSlicePlane Delete the last slice plane added.\n        if ~isempty(hSlicePlanes)\n            delete(hSlicePlanes(end));\n            hSlicePlanes = hSlicePlanes(1:end-1);\n        end\n    end\n\n    function initDisplay()\n    %initDisplay  Initialize Display.\n\n        % Draw back and bottom walls\n        if isempty(hAxis) || ~ishandle(hAxis)\n            hAxis = gca;\n            hold on;\n        end\n        hx = slice(hAxis, x, y, z, v, ...\n            max(x(:)),       [],       []) ;\n        hy = slice(hAxis, x, y, z, v, ...\n            [],       max(y(:)),       []) ;\n        hz = slice(hAxis, x, y, z, v, ...\n            [],              [],min(z(:))) ;\n\n        % Make everything look nice\n        set([hx hy hz],'FaceColor','interp',...\n            'EdgeColor','none')\n        set(hAxis,'FontSize',18,'FontWeight','Bold');\n        xlabel('X');ylabel('Y');zlabel('Z')\n        daspect([1,1,1])\n        axis tight\n        box on\n        view(-38.5,16)\n        colormap (jet(128))\n    end\n\ns.addSlicePlane = @addSlicePlane;\ns.deleteLastSlicePlane = @deleteLastSlicePlane;\ns.xMin = min(x(:));\ns.xMax = max(x(:));\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/15867-volume-visualization-example/volumeVisualization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5741493900542799}}
{"text": "function solplotl(sol,xy,x,y,fig)\n%solplotl   plots nodal data on L-shaped domain\n%   solplotl(sol,xy,x,y,fig);\n%   input\n%          sol        nodal solution vector\n%          xy         nodal coordinate vector  \n%          x          vector of x-axis interpolation points\n%          y          vector of y-axis interpolation points\n%          fig        figure number\n%\n%   IFISS function: DJS; 30 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nfprintf('plotting solution... ')\n% interpolate to a cartesian product mesh\n[X,Y]=meshgrid(x,y);\nxysol = griddata(xy(:,1),xy(:,2),sol,X,Y);\n[II,JJ]=find(X<0 & Y<0); xysol(II,JJ)=nan;\nfigure(fig)\nsubplot(121),contour(X,Y,xysol,20),axis('square')\naxis('off'), \nif all([min(x),max(x),min(y),max(y)] == [-1,1,-1,1]), ellx, end\nsubplot(122),mesh(X,Y,xysol),axis('square')\nview(330,30)\nfprintf('done\\n')\nreturn\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/graphs/solplotl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5741493858109707}}
{"text": "classdef RMMEDA_F6 < PROBLEM\n% <multi> <real> <large/none>\n% Benchmark MOP for testing RM-MEDA\n\n%------------------------------- Reference --------------------------------\n% Q. Zhang, A. Zhou, and Y. Jin, RM-MEDA: A regularity model-based\n% multiobjective estimation of distribution algorithm, IEEE Transactions on\n% Evolutionary Computation, 2008, 12(1): 41-63.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            g = 1 + 9*mean((X(:,2:end).^2-repmat(X(:,1),1,size(X,2)-1)).^2,2);\n            PopObj(:,1) = sqrt(X(:,1));\n            PopObj(:,2) = g.*(1-(PopObj(:,1)./g).^2);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - R(:,1).^2;\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R = obj.GetOptimum(100);\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/MOPs with variable linkages/RMMEDA_F6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5741493858109707}}
{"text": "function [vals, locs] = minandmax3(f)\n%MINANDMAX3   returns the global minimum and maximum value of a CHEBFUN3.\n%   VALS = minandmax3(F) returns the global minimum and maximum value of a \n%   CHEBFUN3 object F over its domain. VALS is a vector of length 2 such \n%   that Y(1) = min3(F(x,y,z)) and Y(2) = max3(F(x,y,z)).\n%\n%   [VALS, LOCS] = minandmax3(F) also returns the position of the global \n%   minimum and maximum.\n%\n% See also CHEBFUN3/MAX, CHEBFUN3/MAX2, CHEBFUN3/NORM.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% check for empty CHEBFUN3.\nif ( isempty(f) )\n    vals = []; \n    locs = [];\n    return\nend\n\ndoNewton = 1;   % Newton polishing?\n\n% Extract low rank representation of f:\n[fCore, fCols, fRows, fTubes] = tucker(f);\ndom = f.domain;\n\n% Is f the zero function?\nif ( iszero(f) ) \n    locs = [(dom(1) + dom(2))/2  (dom(3) + dom(4))/2  (dom(5) + dom(6))/2];\n    locs = [locs; locs];\n    vals = [0; 0];\nend\n\n[m, n, p] = length(f);\nif ( ndf(f) > 5e4 )\n    m = min(m, 129);\n    n = min(n, 129);\n    p = min(p, 129);\nend\n\n% We seek a fast initial guess. So we first discretize the object.\nxpts = chebpts(m, fCols.domain);\nypts = chebpts(n, fRows.domain);\nzpts = chebpts(p, fTubes.domain);\ncolVals = feval(fCols, xpts); \nrowVals = feval(fRows, ypts); \ntubeVals = feval(fTubes, zpts); \nT = chebfun3.txm(chebfun3.txm(chebfun3.txm(fCore,colVals,1), rowVals,2), ...\n    tubeVals,3);\n    \n% Minimum entry in the sample:\n[ignored, ind] = min(T(:));\n[col, row, tub] = ind2sub(size(T), ind);\nloc(1,1) = xpts(col);\nloc(1,2) = ypts(row);\nloc(1,3) = zpts(tub);\nvals(1) = feval(f, loc(1, 1), loc(1, 2), loc(1, 3));\n\n% Maximum entry in the sample:\n[ignored, ind] = max(T(:)); \n[col, row, tub] = ind2sub(size(T), ind);\nloc(2,1) = xpts(col);\nloc(2,2) = ypts(row);\nloc(2,3) = zpts(tub);\nvals(2) = feval(f, loc(2, 1), loc(2, 2), loc(2, 3));\n\n% Get more digits with optimisation algorithms.\nlb = [dom(1); dom(3); dom(5)];\nub = [dom(2); dom(4); dom(6)];\n\nif ( ~isempty(ver('optim')) )\n% Matlab's Optimization Toolbox is available. So, use fmincon command.\n    options = optimset('Display', 'none', 'TolFun', eps, 'TolX', eps, ...\n        'algorithm', 'active-set');\n    [minLoc, vals(1)] = fmincon(@(x) feval(f, x(1), x(2), x(3)), ...\n        loc(1, :), [], [], [], [], lb, ub, [], options);\n    \n    [maxLoc, vals(2)] = fmincon(@(x) -feval(f, x(1), x(2), x(3)), ...\n        loc(2,:), [], [], [], [], lb, ub, [], options);\n    vals(2) = -vals(2);\n    loc(1,:) = minLoc;\n    loc(2,:) = maxLoc;\n    locs = loc;\nelse\n    try\n        % Use core Matlab fminsearch command by converting to an \n        % unconstrained optimization problem.\n        % Maps from [-1, 1] to dom(1:2), dom(3:4), and dom(5:6) \n        % respectively.\n        map1 = bndfun.createMap(dom(1:2));\n        map2 = bndfun.createMap(dom(3:4));\n        map3 = bndfun.createMap(dom(5:6));\n        \n        % Unconstrained initial guesses:\n        loc(:, 1) = asin(map1.Inv(loc(:, 1)));\n        loc(:, 2) = asin(map2.Inv(loc(:, 2)));\n        loc(:, 3) = asin(map3.Inv(loc(:, 3)));\n        \n        % Maps from R to dom(1:2), dom(3:4), and dom(5:6) respectively.\n        map1 = @(x) map1.For(sin(x));\n        map2 = @(x) map2.For(sin(x));\n        map3 = @(x) map3.For(sin(x));\n        \n        % Set options:\n        options = optimset('Display', 'off', 'TolFun', eps, 'TolX', eps);\n        warnstate = warning;\n        warning('off'); % Disable verbose warnings from fminsearch.\n        f_mapped = @(x) feval(f, map1(x(1)), map2(x(2)),map3(x(3)));\n        \n        [minLoc, vals(1)] = fminsearch(@(x) f_mapped(x), loc(1, :), options);\n        [maxLoc, vals(2)] = fminsearch(@(x) -f_mapped(x), loc(2, :), options);\n        \n        vals(2) = -vals(2);\n        loc(1:2, 1) = map1([minLoc(1); maxLoc(1)]);\n        loc(1:2, 2) = map2([minLoc(2); maxLoc(2)]);\n        loc(1:2, 3) = map3([minLoc(3); maxLoc(3)]);\n        warning(warnstate);\n        locs = loc;\n        \n    catch\n        % Nothing is going to work. So we will have to go with initial \n        % guesses.\n    end\nend\n    \nif ( doNewton )\n    % Store values before applying any Newton iterations to restore if \n    % Newton was diverging.\n    locsOld = locs;\n    valsOld = vals;\n    \n    % If the global max or min is already on the edge or out of domain, \n    % do NOT apply Newton iteration:\n    if ( isOutOfDomain(locs, dom) )\n        return\n    end    \n    \n    % A few steps of Newton for optimization (involves computing Hessian)\n    H = Hessian(f);\n    gradF = grad(f);\n    gradF = @(x,y,z) gradF(x,y,z);\n    \n    % Disable verbose warnings from Newton step if e.g., the Hessian \n    % matrix is singular which happens e.g., if a 2D function is passed to\n    % minandmax3.    \n    warning_state = warning('off','MATLAB:singularMatrix');\n\t% Use try-catch to guarantee original warning state is restored.\n    try\n        lastwarn('')\n        k = 1; % k Newton iterations:\n        for iter = 1:k\n            locs(1,:) = newton_opt(locs(1,:), H, gradF);\n            vals(:,1) = feval(f, locs(1, 1), locs(1, 2), locs(1, 3));\n            \n            locs(2,:) = newton_opt(locs(2, :), H, gradF);\n            vals(:,2) = feval(f,locs(2, 1), locs(2, 2), locs(2, 3));\n        end\n        [ignored, last_warn] = lastwarn;\n        if strcmp(last_warn,'MATLAB:singularMatrix')\n            % Return the old value if the Hessian matrix was singular.\n            locs = locsOld;\n            vals = valsOld;\n            return\n        end\n        warning(warning_state)\n    catch err\n        warning(warning_state)\n        rethrow(err)\n    end\n   \n    % If Newton's method moved us outside of the domain, then return old \n    % value.\n    if ( isOutOfDomain(locs, dom) )\n        locs = locsOld;\n        vals = valsOld;\n    end\n    \nend\n   \nend\n\n%%\nfunction H = Hessian(f)\n% Forms the Hessian matrix of a CHEBFUN3 object f\n\nH11 = diff(f, 2, 1);\nH12 = diff(diff(f, 1, 2), 1, 1); \nH13 = diff(diff(f, 1, 3), 1, 1);\n\nH21 = diff(diff(f, 1, 1), 1, 2);\nH22 = diff(f, 2, 2);\nH23 = diff(diff(f, 1, 3), 1, 2);\n\nH31 = diff(diff(f, 1, 1), 1, 3); \nH32 = diff(diff(f, 1, 2), 1, 3);\nH33 = diff(f, 2, 3);\nH = @(x,y,z) [feval(H11, x, y, z)  feval(H12, x, y, z)  feval(H13, x, y, z);\n              feval(H21, x, y, z)  feval(H22, x, y, z)  feval(H23, x, y, z);\n              feval(H31, x, y, z)  feval(H32, x, y, z)  feval(H33, x, y, z)];\nend\n\n%%\nfunction sol = newton_opt(init, H, gradF)\n% Perform one step of multivariate optimization using Newton's method.\nx = init(1); \ny = init(2); \nz = init(3);\nrhs = -gradF(x, y, z);\nh = H(x,y,z)\\rhs;\nsol = init.' + h;\nend\n\n%%\nfunction check = isOutOfDomain(locs, dom)\n% Check whether both points in the rows of LOCS are inside the cuboid DOM.\nif ( locs(1, 1) <= dom(1) || locs(1, 1) >=dom(2) || ...\n         locs(1, 2) <= dom(3) || locs(1, 2)>=dom(4) || ...\n         locs(1, 3) <= dom(5) || locs(1, 3)>=dom(6) )\n     check = true;\nelseif ( locs(2, 1) <= dom(1) || locs(2, 1) >= dom(2) || ...\n             locs(2, 2) <= dom(3) || locs(2, 2) >= dom(4) || ...\n             locs(2, 3) <= dom(5) || locs(2, 3) >= dom(6) )\n         check = true;\nelse\n    check = false;\nend\nend\n%%", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3/minandmax3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.574112616534659}}
{"text": "function [x_guess Iter] = VMPCM(ode,tau,x_guess,omega1,omega2,errTol,varargin)\n%Purpose:\n%Generic Function wrapper for the Vectorized Picard Chebyshev Method\n%-------------------------------------------------------------------------%\n%                                                                         %\n% Inputs:                                                                 %\n%--------                                                                  \n%ode                    object                          function name to\n%                                                       evaluate i.e.\n%                                                       @jatForces\n%\n%tau                    [N x 1]                         transformed time\n%                                                       domain vector\n%\n%x_guess                [N x M]                         Initial Guess of\n%                                                       solution values for\n%                                                       the Picard\n%                                                       Chebyshev Method\n%\n%omega1                 double                          First Omega Term\n%\n%omega2                 double                          Second Omega Term\n%\n%errTol                 double                          Error Tolerance of\n%                                                       solution\n%\n%varargin                                                Additional inputs\n%                                                       which are needed to\n%                                                       be passed to the\n%                                                       evaluation function\n%                                                       ode\n%\n% Outputs:\n%---------                                                                %\n%x_guess                  [N x M]                        Refined solution\n%                                                        meeting the error\n%                                                        tolerances defined\n%                                                        by errTol\n%\n%--------------------------------------------------------------------------\n% Programmed by Darin Koblick 03-04-2012                                  %\n%-------------------------------------------------------------------------- \ntau = tau(:)';\nN = numel(tau)-1;\nerr1 = Inf;\nerr2 = Inf;\nIter = 0;\nMaxIter = 300;\n%disp('Running The Picard Chebyshev Algorithm')\ntic;\n%Initialize Constant Matricies up front so we don't have to recompute them\n%which would slow down the iterative process\n%--------------------------------------------------------------------------\nT = ChebyshevPolynomial((0:N+1)',tau);\nV = ones(1,length(tau))./N;\nV(2:end-1) = V(2:end-1).*2;\nTV1 = bsxfun(@times,T(1:N,:),V);\nTV2 = bsxfun(@times,T(3:N+2,:),V);\nTV = bsxfun(@rdivide,(TV1-TV2),(2.*(1:N))');\nTV(end,:) = TV1(end,:)./(2*N)';\nS = 2.*((-1).^((1:N)+1));\nCx = T(1:N+1,1:N+1)';\nCx(:,1) = Cx(:,1)./2;\n%--------------------------------------------------------------------------\nwhile (any(errTol < err1 ) || any(errTol < err2)) && Iter < MaxIter\n    Iter = Iter + 1;\n    %disp(['-------- Iteration # ',num2str(Iter),' -----------']);\n    input = {omega2.*tau+omega1,x_guess,varargin{:}};\n    F = ode(input{:}).*omega2;\n    if size(F,2) == 1 || size(F,1) == 1\n       F = F'; \n    end\n    Beta_r = NaN(size(TV,1),size(F,2));\n    Beta_k = NaN(size(TV,1) + 1, size(F,2));\n    x_new = Beta_k;\n    %Matrix Multiply\n    for i=1:size(F,2)\n        Beta_r(:,i) = TV*F(:,i);\n        Beta_k(:,i) = [S*Beta_r(:,i) + 2.*x_guess(1,i); Beta_r(:,i)];\n        x_new(:,i) = (Cx*Beta_k(:,i));\n    end\n    if any(size(x_new) ~= size(F))\n       x_new = x_new'; \n    end\n    err2 = err1;\n    err1 = max(abs(x_new - x_guess),[],2);\n    disp(['Max Error Is found to be: ', num2str(max(err1))]);\n    x_guess = x_new;\nend\nend\n\nfunction Tk = ChebyshevPolynomial(k,tau)\n%The Chebyshev polynomial,T, corresponding to degree k\nTk = cos(bsxfun(@times,k,acos(tau)));\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/36940-vectorized-picard-chebyshev-method/VMPCM/VMPCM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808498, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5741126077511026}}
{"text": "%% Clear and Close Figures\nclear ; close all; clc\n\ncorrectPredictedSpam = 85\nincorrectPredictedSpam = 890\ncorrectPredictedNoSpam = 10\nincorrectPredictedNoSpam = 15\n\ntotal = correctPredictedSpam + incorrectPredictedSpam + correctPredictedNoSpam + incorrectPredictedNoSpam\n\naccuracy = ( correctPredictedSpam + correctPredictedNoSpam ) / total\nprecision = correctPredictedSpam / (correctPredictedSpam + incorrectPredictedSpam)\nrecall = correctPredictedSpam / (correctPredictedSpam + incorrectPredictedNoSpam)\nF1 = (2 * precision * recall) / (precision + recall) \nF1\n", "meta": {"author": "vugsus", "repo": "coursera-machine-learning", "sha": "4c2d45cb729355593509abcd41779d19de5a1970", "save_path": "github-repos/MATLAB/vugsus-coursera-machine-learning", "path": "github-repos/MATLAB/vugsus-coursera-machine-learning/coursera-machine-learning-4c2d45cb729355593509abcd41779d19de5a1970/quiz/week6_quiz1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5741125965383662}}
{"text": "function toms655_test ( )\n\n%*****************************************************************************80\n%\n%% TOMS655_TEST tests the TOMS655 library.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 February 2010\n%\n%  Author:\n%\n%    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n%    MATLAB version by John Burkardt.\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TOMS655_PRB\\n' );\n  fprintf ( 1, '  MATLAB version\\n' );\n  fprintf ( 1, '  Test the TOMS655 library.\\n' );\n\n  test01 ( );\n  test02 ( );\n  test03 ( );\n  test04 ( );\n  test05 ( );\n  test06 ( );\n  test07 ( );\n  test08 ( );\n  test09 ( );\n%\n%  Compute 15 points of an example of each rule.\n%\n  for kind = 1 : 9\n    nt = 15;\n    if ( kind == 8 )\n      alpha = 1.0;\n      beta = - alpha - 2 * nt - 2;\n    else\n      alpha = 0.0;\n      beta = 0.0;\n    end\n    test10 ( nt, kind, alpha, beta );\n  end\n%\n%  Compute 15 points of an example of each rule using nondefault A, B.\n%\n  for kind = 1 : 9\n\n    nt = 15;\n\n    if ( kind == 1 )\n      alpha = 0.0;\n      beta = 0.0;\n      a = 0.0;\n      b = 1.0;\n    elseif ( kind == 2 )\n      alpha = 0.0;\n      beta = 0.0;\n      a = 0.0;\n      b = 1.0;\n    elseif ( kind == 3 )\n      alpha = 1.0;\n      beta = 0.0;\n      a = 0.0;\n      b = 1.0;\n    elseif ( kind == 4 )\n      alpha = 1.5;\n      beta = 0.5;\n      a = 0.0;\n      b = 1.0;\n    elseif ( kind == 5 )\n      alpha = 1.0;\n      beta = 0.0;\n      a = 1.0;\n      b = 1.0;\n    elseif ( kind == 6 )\n      alpha = 1.0;\n      beta = 0.0;\n      a = 0.0;\n      b = 0.5;\n    elseif ( kind == 7 )\n      alpha = 1.0;\n      beta = 0.0;\n      a = 0.0;\n      b = 1.0;\n    elseif ( kind == 8 )\n      alpha = 1.0;\n      beta = - alpha - 2 * nt - 2;\n      a = 0.0;\n      b = 1.0;\n    elseif ( kind == 9 )\n      alpha = 0.0;\n      beta = 0.0;\n      a = 0.0;\n      b = 1.0;\n    end\n\n    test11 ( nt, kind, alpha, beta, a, b );\n\n  end\n%\n%  Terminate.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TOMS655_PRB\\n' );\n  fprintf ( 1, '  Normal end of TOMS655 tests.\\n' );\n  fprintf ( 1, '\\n' );\n  timestamp ( );\n\n  return\nend\nfunction test01 ( )\n\n%*****************************************************************************80\n%\n%% TEST01 tests CIQFS.\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  fprintf ( 1, '  ----------------------------------------\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST01\\n' );\n  fprintf ( 1, '  Test CIQFS.\\n' );\n%\n%  Number of knots.\n%\n  nt = 5;\n%\n%  Set the knots in the default interval [-1,+1].\n%\n  t = zeros ( nt, 1 );\n  for i = 1 : nt\n    t(i) = cos ( ( 2 * i - 1 ) * pi / 2.0 / nt );\n  end\n%\n%  Set the knot multiplicities.\n%\n  mlt(1:nt) = 2;\n%\n%  Set the size of the weights array.\n%\n  nwts = sum ( mlt(1:nt) );\n%\n%  Because KEY = 1, NDX will be set up for us.\n%\n  ndx = zeros(nt,1);\n%\n%  KEY = 1 indicates that the WTS array should hold the weights\n%  in the usual order.\n%\n  key = 1;\n%\n%  Request Legendre weight function.\n%\n  kind = 1;\n%\n%  ALPHA, BETA not used in Legendre weight function but set anyway.\n%\n  alpha = 0.0;\n  beta  = 0.0;\n%\n%  LU controls printing.\n%  A positive value requests that we compute and print weights, and\n%  conduct a moments check.\n%\n  lu = 6;\n\n  [ wts, ndx ] = ciqfs ( nt, t, mlt, nwts, ndx, key, kind, alpha, beta, lu );\n\n  return\nend\nfunction test02 ( )\n\n%*****************************************************************************80\n%\n%% TEST02 tests CIQFS.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    06 January 2010\n%\n%  Author:\n%\n%    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n%    MATLAB version by John Burkardt.\n%\n  fprintf ( 1, '  ----------------------------------------\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST02\\n' );\n  fprintf ( 1, '  Test CIQF, CIQFS, CGQF and CGQFS\\n' );\n  fprintf ( 1, '  with all classical weight functions.\\n' );\n%\n%  Try all weight functions.\n%\n  for kind = 1 : 9\n%\n%  Number of knots.\n%\n    nt = 5;\n%\n%  Set parameters ALPHA and BETA.\n%\n    alpha = 0.5;\n    if ( kind ~= 8 )\n      beta  = 2.0;\n    else\n      beta = - 16.0;\n    end\n%\n%  Set A and B.\n%\n    lo = 6;\n    a = - 0.5;\n    b = 2.0;\n%\n%  Have CGQF compute the knots and weights.\n%\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Knots and weights of Gauss quadrature formula\\n' );\n    fprintf ( 1, '  computed by CGQF.\\n' );\n    [ t, wts ] = cgqf ( nt, kind, alpha, beta, lo, a, b );\n%\n%  Now compute the weights for the same knots by CIQF.\n%\n%  Set the knot multiplicities.\n%\n    mlt = zeros(nt,1);\n    mlt(1:nt) = 2;\n%\n%  Set the size of the weights array.\n%\n    nwts = sum ( mlt(1:nt) );\n%\n%  Because KEY = 1, NDX will be set up for us.\n%\n    ndx = zeros(nt,1);\n%\n%  KEY = 1 indicates that the WTS array should hold the weights\n%  in the usual order.\n%\n    key = 1;\n%\n%  LU controls printing.\n%  A positive value requests that we compute and print weights, and\n%  conduct a moments check.\n%\n    lu = 6;\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Weights of Gauss quadrature formula computed from the\\n' );\n    fprintf ( 1, '  knots by CIQF.\\n' );\n\n    wts = ciqf ( nt, t, mlt, nwts, ndx, key, kind, alpha, beta, a, b, lu );\n\n  end\n\n  return\nend\nfunction test03 ( )\n\n%*****************************************************************************80\n%\n%% TEST03 tests CEIQFS.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    06 January 2010\n%\n%  Author:\n%\n%    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n%    MATLAB version by John Burkardt.\n%\n  fprintf ( 1, '  ----------------------------------------\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST03\\n' );\n  fprintf ( 1, '  Test CEIQFS.\\n' );\n%\n%  Number of knots.\n%\n  nt = 5;\n%\n%  Set the knots in the default interval [-1,+1].\n%\n  t = zeros ( nt, 1 );\n\n  for i = 1 : nt\n    t(i) = cos ( ( 2 * i - 1 ) * pi / 2.0 / nt );\n  end\n%\n%  Set the knot multiplicities.\n%\n  mlt = zeros ( nt, 1 );\n  mlt(1:nt) = 2;\n%\n%  Set KIND to the Legendre weight function.\n%\n  kind = 1;\n%\n%  ALPHA, BETA not used in Legendre weight function but set anyway.\n%\n  alpha = 0.0;\n  beta  = 0.0;\n%\n%  Call CEIQFS to set up the quadrature formula and evaluate it on F.\n%\n  qfsum = ceiqfs ( nt, t, mlt, kind, alpha, beta, @f );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Integral of sin(x) on -1, 1 by Fejer type rule\\n' );\n  fprintf ( 1, '  with %d points of multiplicity 2.\\n', nt );\n  fprintf ( 1, '  Quadrature formula: %24.16f\\n', qfsum );\n\n  qfsx = cos ( - 1.0 ) - cos ( 1.0 );\n  fprintf ( 1, '  Exact value       : %24.16f\\n', qfsx );\n  fprintf ( 1, '  Error             : %e\\n', abs ( qfsum - qfsx ) );\n\n  return\nend\nfunction test04 ( )\n\n%*****************************************************************************80\n%\n%% TEST04 tests CEIQF.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    06 January 2010\n%\n%  Author:\n%\n%    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n%    MATLAB version by John Burkardt.\n%\n  fprintf ( 1, '  ----------------------------------------\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST04\\n' );\n  fprintf ( 1, '  Test CEIQF.\\n' );\n%\n%  Number of knots.\n%\n  nt = 5;\n%\n%  Set the knots in the default interval [-1,+1].\n%\n  t = zeros ( nt, 1 );\n\n  for i = 1 : nt\n    t(i) = cos ( ( 2 * i - 1 ) * pi / 2.0 / nt );\n  end\n%\n%  Set the knot multiplicities.\n%\n  mlt = zeros ( nt, 1 );\n  mlt(1:nt) = 2;\n%\n%  Set KIND to the Legendre weight function.\n%\n  kind = 1;\n%\n%  ALPHA, BETA not used in Legendre weight function but set anyway.\n%\n  alpha = 0.0;\n  beta  = 0.0;\n%\n%  Set nonstandard interval A, B.\n%\n  a = - 0.5;\n  b = 2.0;\n%\n%  Shift knots from [-1,1] to [A,B].\n%\n  for i = 1 : nt\n    t(i) = ( ( b - a ) * t(i) + ( a + b ) ) / 2.0;\n  end\n%\n%  Call CEIQF to set up the quadrature formula and evaluate it on F.\n%\n  qfsum = ceiqf ( nt, t, mlt, kind, alpha, beta, a, b, @f );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Integral of sin(x) from %f to %f by Fejer type rule\\n', a, b );\n  fprintf ( 1, '  with %d points of multiplicity 2.\\n', nt );\n  fprintf ( 1, '  Quadrature formula: %24.16f\\n', qfsum );\n\n  qfsx = cos ( a ) - cos ( b );\n  fprintf ( 1, '  Exact value       : %24.16f\\n', qfsx );\n  fprintf ( 1, '  Error             : %e\\n', abs ( qfsum - qfsx ) );\n\n  return\nend\nfunction test05 ( )\n\n%*****************************************************************************80\n%\n%% TEST05 tests CLIQFS.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    06 January 2010\n%\n%  Author:\n%\n%    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n%    MATLAB version by John Burkardt.\n%\n  fprintf ( 1, '  ----------------------------------------\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST05\\n' );\n  fprintf ( 1, '  Test CLIQFS.\\n' );\n%\n%  Number of knots.\n%\n  nt = 5;\n%\n%  Set the knots in the default interval [-1,+1].\n%\n  t = zeros(nt,1);\n\n  for i = 1 : nt\n    t(i) = cos ( ( 2 * i - 1 ) * pi / ( 2 * nt ) );\n  end\n%\n%  Request Legendre weight function.\n%\n  kind = 1;\n%\n%  ALPHA, BETA not used in Legendre weight function but set anyway.\n%\n  alpha = 0.0;\n  beta  = 0.0;\n%\n%  LU controls printing.\n%  A positive value requests that we compute and print weights, and\n%  conduct a moments check.\n%\n  lu = 6;\n%\n%  This call returns the WTS array.\n%\n  wts = cliqfs ( nt, t, kind, alpha, beta, lu );\n\n  return\nend\nfunction test06 ( )\n\n%*****************************************************************************80\n%\n%% TEST06 tests CLIQF and EIQFS..\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    06 January 2010\n%\n%  Author:\n%\n%    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n%    MATLAB version by John Burkardt.\n%\n  fprintf ( 1, '  ----------------------------------------\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST06\\n' );\n  fprintf ( 1, '  Test CLIQF and EIQFS.\\n' );\n%\n%  Number of knots.\n%\n  nt = 5;\n%\n%  Set the knots in the default interval [-1,+1].\n%\n  t = zeros(nt,1);\n\n  for i = 1 : nt\n    t(i) = cos ( ( 2 * i - 1 ) * pi / ( 2 * nt ) );\n  end\n%\n%  Set KIND to the Legendre weight function.\n%\n  kind = 1;\n%\n%  ALPHA, BETA not used in Legendre weight function but set anyway.\n%\n  alpha = 0.0;\n  beta  = 0.0;\n%\n%  Set nonstandard interval A, B.\n%\n  a = - 0.5;\n  b = 2.0;\n%\n%  Shift knots from [-1,1] to [A,B].\n%\n  for i = 1 : nt\n    t(i) = ( ( b - a ) * t(i) + ( a + b ) ) / 2.0;\n  end\n%\n%  LU controls printout.\n%\n  lu = 6;\n%\n%  Call CLIQF to set up the quadrature formula.\n%\n  wts = cliqf ( nt, t, kind, alpha, beta, a, b, lu );\n%\n%  Call EIQFS to evaluate the quadrature formula.\n%\n  qfsum = eiqfs ( nt, t, wts, @f );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Integral of sin(x) from %f to %f\\n', a, b );\n  fprintf ( 1, '  by Fejer type rule with %d points\\n', nt );\n  fprintf ( 1, '  of multiplicity 1.\\n' );\n  fprintf ( 1, '  Quadrature formula: %24.16f\\n', qfsum );\n\n  qfsx = cos ( a ) - cos ( b );\n  fprintf ( 1, '  Exact value       : %24.16f\\n', qfsx );\n  fprintf ( 1, '  Error             : %e\\n', abs ( qfsum - qfsx ) );\n\n  return\nend\nfunction test07 ( )\n\n%*****************************************************************************80\n%\n%% TEST07 tests CEGQF.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    06 January 2010\n%\n%  Author:\n%\n%    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n%    MATLAB version by John Burkardt.\n%\n  fprintf ( 1, '  ----------------------------------------\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST07\\n' );\n  fprintf ( 1, '  Test CEGQF.\\n' );\n%\n%  Number of knots.\n%\n  nt = 12;\n%\n%  Request exponential weight function.\n%\n  kind = 7;\n%\n%  Set ALPHA and BETA.\n%\n  alpha = 1.0;\n  beta  = 0.0;\n%\n%  Set interval [A,B].\n%\n  a = - 0.5;\n  b = 2.0;\n%\n%  Call CEGQF to compute and evaluate the Gauss quadrature formula.\n%\n  qfsum = cegqf ( nt, kind, alpha, beta, a, b, @f );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Integral of x*sin(x) from %f to %f\\n', a, b );\n  fprintf ( 1, '  by Gauss-exponential rule with %d points\\n', nt );\n  fprintf ( 1, '  Quadrature formula: %24.16f\\n', qfsum );\n\n  qfsx = ( b - a ) * 0.5 * ( cos ( a ) - cos ( b ) ) ...\n    + sin ( b ) + sin ( a ) - 2.0 * sin ( ( a + b ) / 2.0 );\n\n  fprintf ( 1, '  Exact value       : %24.16f\\n', qfsx );\n  fprintf ( 1, '  Error             : %e\\n', abs ( qfsum - qfsx ) );\n\n  return\nend\nfunction test08 ( )\n\n%*****************************************************************************80\n%\n%% TEST08 tests CEGQFS.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    06 January 2010\n%\n%  Author:\n%\n%    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n%    MATLAB version by John Burkardt.\n%\n  fprintf ( 1,'  ----------------------------------------\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST08\\n' );\n  fprintf ( 1, '  Test CEGQFS.\\n' );\n%\n%  Number of knots.\n%\n  nt = 12;\n%\n%  Request exponential weight function.\n%\n  kind = 7;\n%\n%  Set ALPHA and BETA.\n%\n  alpha = 1.0;\n  beta  = 0.0;\n%\n%  Call CEGQFS to compute and evaluate the Gauss quadrature formula.\n%\n  qfsum = cegqfs ( nt, kind, alpha, beta, @f );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Integral of x*sin(x) from -1 to +1\\n' );\n  fprintf ( 1, '  by Gauss-exponential rule with %d points.\\n', nt )\n  fprintf ( 1, '  Quadrature formula: %24.16f\\n', qfsum );\n\n  qfsx = cos ( -1.0 ) - cos ( +1.0 );\n\n  fprintf ( 1, '  Exact value       : %24.16f\\n', qfsx );\n  fprintf ( 1, '  Error             : %e\\n', abs ( qfsum - qfsx ) );\n\n  return\nend\nfunction test09 ( )\n\n%*****************************************************************************80\n%\n%% TEST09 calls CGQFS to compute and print generalized Gauss-Hermite rules.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    10 January 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST09\\n' );\n  fprintf ( 1, '  Call CGQFS for a generalized Gauss Hermite rule.\\n' );\n\n  nt = 15;\n  kind = 6;\n  alpha = 1.0;\n  beta = 0.0;\n  io = - 6;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  NT = %d\\n', nt );\n  fprintf ( 1, '  ALPHA = %f\\n', alpha );\n\n  [ t, wts ] = cgqfs ( nt, kind, alpha, beta, io );\n\n  return\nend\nfunction test10 ( nt, kind, alpha, beta )\n\n%*****************************************************************************80\n%\n%% TEST10 calls CDGQF to compute a quadrature formula.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    06 January 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST10\\n' );\n  fprintf ( 1, '  Call CDGQF to compute a quadrature formula.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  KIND = %d\\n', kind );\n  fprintf ( 1, '  ALPHA = %f\\n', alpha );\n  fprintf ( 1, '  BETA  = %f\\n', beta );\n\n  [ t, wts ] = cdgqf ( nt, kind, alpha, beta );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ' Index     Abscissas                 Weights\\n' );\n  fprintf ( 1, '\\n' );\n  for i = 1 : nt\n    fprintf ( 1, '  %4d  %24.16e  %24.16e\\n', i, t(i), wts(i) );\n  end\n\n  return\nend\nfunction test11 ( nt, kind, alpha, beta, a, b )\n\n%*****************************************************************************80\n%\n%% TEST11 calls CGQF to compute a quadrature formula.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 February 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST11\\n' );\n  fprintf ( 1, '  Call CGQF to compute a quadrature formula\\n' );\n  fprintf ( 1, '  with nondefault values of A and B.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  KIND = %d\\n', kind );\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\n  lo = 0;\n  [ t, wts ] = cgqf ( nt, kind, alpha, beta, lo, a, b );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ' Index     Abscissas                 Weights\\n' );\n  fprintf ( 1, '\\n' );\n  for i = 1 : nt\n    fprintf ( 1, '  %4d  %24.16e  %24.16e\\n', i, t(i), wts(i) );\n  end\n\n  return\nend\nfunction value = f ( x, i )\n\n%*****************************************************************************80\n%\n%% F returns values of the integrand or its derivatives.\n%\n%  Discussion:\n%\n%    This function is an example of an integrand function.\n%\n%    The package can generate quadrature formulas that use derivative \n%    information as well as function values.  Therefore, this routine is\n%    set up to provide derivatives of any order as well as the function\n%    value.  In an actual application, the highest derivative needed\n%    is of order one less than the highest knot multiplicity.\n%\n%    In other words, in the usual case where knots are not repeated,\n%    this routine only needs to return function values, not any derivatives.\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%  Parameters:\n%\n%    Input, real X, the evaluation point.\n%\n%    Input, integer I, the order of the derivative of F to\n%    be evaluated.\n%\n%    Output, real VALUE, the value of the I-th derivative of F at X.\n%\n  l = mod ( i, 4 );\n\n  if ( l == 0 )\n    value = sin ( x );\n  elseif ( l == 1 )\n    value = cos ( x );\n  elseif ( l == 2 )\n    value = - sin ( x );\n  elseif ( l == 3 )\n    value = - cos ( 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/toms655/toms655_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.574106591479385}}
{"text": "function varargout = information(R, opts, varargin)\n\n%INFORMATION Computes mutual information using different methods and\n% different bias correction procedures.\n%\n%   ------\n%   SYNTAX\n%   ------\n%       [...] = information(R, opts, output list...)\n%\n%   ---------\n%   ARGUMENTS\n%   ---------\n%   R           - Response matrix.\n%   opts        - Options structure.\n%   output list - List of strings specifying what to compute.\n%\n%   -------------------\n%   THE RESPONSE MATRIX\n%   -------------------\n%   L-dimensional responses to S distinct stimuli are stored in a response\n%   matrix R of size L-by-T-by-S, T being the maximum number of trials\n%   available for any of the stimuli. Emtpy trials, i.e., elements of R not\n%   corresponding to a recorded response, can take any value.\n%\n%   ---------------------\n%   THE OPTIONS STRUCTURE\n%   ---------------------\n%   The options structure can include any the following fields:\n%\n%   opts.nt\n%   -------\n%       This field specifies the number of trials (responses) recorded for\n%       each stimulus. It can be either a scalar (for constant number of\n%       trials per stimulus) or an array of length S.\n%\n%       NT must satisfy the following two conditions:\n%       - max(nt) = T\n%       - length(nt) = S (if nt is an array)\n%\n%   opts.method\n%   -----------\n%       This field specifies which estimation method to use and can be one\n%       of the following strings:\n%\n%       --------------------------\n%       | 'dr' | Direct method   |\n%       | 'gs' | Gaussian method |\n%       --------------------------\n%\n%       IMPORTANT!\n%       ==========\n%       The direct method requires the response values to be discretized\n%       into non-negative integer values (this is meant only in a numerical\n%       sense, the MATLAB variable still needs to be of type double). See\n%       function BINR.M for instruction on how to discretize the responses.\n%       Failing to properly discretizing the response will result in Matlab\n%       crashing.\n%\n%   opts.bias\n%   ---------\n%       This field specifies the bias correction procedure. It can be one\n%       of the following strings:\n%\n%       -------------------------------------\n%       | 'qe'    | Quadratic EXtrapolation |\n%       | 'pt'    | Panzeri & Treves 1996   |\n%       | 'gsb'   | Gaussian bias           |\n%       | 'naive' | Biased naive estimates  |\n%       -------------------------------------\n%\n%   opts.btsp (optional)\n%   --------------------\n%       This field must be a (non-negative) scalar specifying how many \n%       bootstrap estimates to compute.\n%\n%       Bootstrap estimates are performed by means of pairing stimuli and\n%       responses at random and computing the entropy quantities for these\n%       random pairings; each estimate corresponds to a different random\n%       pairing configuration.\n%\n%       See the examples below for additional information on how to use\n%       this option.\n%\n%       DEFAULT: 0.\n%\n%   opts.verbose (optional)\n%   -----------------------\n%       If this field exists and is set to true a summary of the selected\n%       options is displayed and additional checks are performed on the\n%       input variables. No warnings are displayed unless this options is\n%       enabled.\n%\n%       This feature is useful to check whether INFORMATION is being called\n%       correctly. It is therefore highly reccomended for new users or when\n%       first running of the program with new input options. However, keep\n%       in mind that these checks drammatically increases computation time\n%       and are thus not reccommended for computationally intensive\n%       session.\n%\n%       DEFAULT: false.\n%   \n%   ---------------\n%   THE OUTPUT LIST\n%   ---------------\n%   To specify which IT quantities need to compute, one or more of the\n%   following strings has to be specified:\n%\n%       =================================================================\n%       | Option  | Description       | Expression (in terms of ENTROPY |\n%       |         |                   | output options)                 |\n%       =================================================================\n%       | 'I'     | I(R;S)            | I     = HR - HRS                |\n%       | 'Ish'   | I(R;S) shuffle    | Ish   = HR - HiRS + HshRS - HRS |\n%       |---------------------------------------------------------------|\n%       | 'IX'    | I(R)              | IX    = HlR - HR                |\n%       |---------------------------------------------------------------|\n%       | 'ILIN'  | I_lin(S;R)        | ILIN  = HlR - HiRS              |\n%       |---------------------------------------------------------------|\n%       | 'SYN'   | Syn               | SYN   = HR - HRS - HlR + HiRS   |\n%       | 'SYNsh' | Syn shuffle       | SYNsh = HR + HshRS - HRS - HlR  |\n%       |---------------------------------------------------------------|\n%       | 'ISS'   | I_sig_sim         | ISS   = HiR - HlR               |\n%       |---------------------------------------------------------------|\n%       | 'IC'    | I_cor             | IC    = HR - HRS + HiRS - HiR   |\n%       | 'ICsh'  | I_cor shuffle     | ICsh  = HR + HshRS - HRS - HiR  |\n%       |---------------------------------------------------------------|\n%       | 'ICI'   | I_cor_ind         | ICI   = ChiR - HiR              |\n%       |---------------------------------------------------------------|\n%       | 'ICD'   | I_cor_dep         | ICD   = HR - HRS - ChiR + HiRS  |\n%       | 'ICDsh' | I_cor_dep shuffle | ICDsh = HR + HshRS - HRS - ChiR |\n%       |---------------------------------------------------------------|\n%       | 'ILB1'  | I_LB1             | ILB1  = HR - HiRS               |\n%       |---------------------------------------------------------------|\n%       | 'ILB2'  | I_LB2             | ILB2  = ChiR - HiRS             |\n%       =================================================================\n%\n%   Outputs are returned IN THE SAME ORDER as that specified in the output\n%   list.\n%\n%   IMPORTANT: Not all combinations of method, bias and output options are\n%   possible. For example, bias correction 'pt' can only be used together \n%   with method 'dr'. The allowed combinations of method, bias and output\n%   options are summarized in the following tables:\n%\n%       =============================================\n%       | DIRECT METHOD                             |\n%       =============================================\n%       |         | 'naive' | 'qe'  | 'pt'  | 'gsb' |\n%       |-------------------------------------------|\n%       | 'I'     |    X    |   X   |   X   |   -   |\n%       | 'Ish'   |    X    |   X   |   X   |   -   |\n%       |---------|---------|-------|-------|-------|\n%       | 'IX'    |    X    |   X   |   X   |   -   |\n%       |---------|---------|-------|-------|-------|\n%       | 'ILIN'  |    X    |   X   |   X   |   -   |\n%       |---------|---------|-------|-------|-------|\n%       | 'SYN'   |    X    |   X   |   X   |   -   |\n%       | 'SYNsh' |    X    |   X   |   X   |   -   |\n%       |---------|---------|-------|-------|-------|\n%       | 'ISS'   |    X    |   X   |   -   |   -   |\n%       |---------|---------|-------|-------|-------|\n%       | 'IC'    |    X    |   X   |   -   |   -   |\n%       | 'ICsh'  |    X    |   X   |   -   |   -   |\n%       |---------|---------|-------|-------|-------|\n%       | 'ICI'   |    X    |   X   |   -   |   -   |\n%       |---------|---------|-------|-------|-------|\n%       | 'ICD'   |    X    |   X   |   -   |   -   |\n%       | 'ICDsh' |    X    |   X   |   -   |   -   |\n%       |---------|---------|-------|-------|-------|\n%       | 'ILB1'  |    X    |   X   |   X   |   -   |\n%       |---------|---------|-------|-------|-------|\n%       | 'ILB2'  |    X    |   X   |   -   |   -   |\n%       =============================================\n%\n%   Legend: X: combination available\n%           -: combination NOT permitted\n%\n%\n%       =============================================\n%       | GAUSSIAN METHOD                           |\n%       =============================================\n%       |         | 'naive' | 'qe'  | 'pt'  | 'gsb' |\n%       |-------------------------------------------|\n%       | 'I'     |    X    |  n.r. |   -   |   X   |\n%       | 'Ish'   |    X    |  n.r. |   -   |   X   |\n%       |---------|---------|-------|-------|-------|\n%       | 'IX'    |    X    |  n.r. |   -   |   X   |\n%       |---------|---------|-------|-------|-------|\n%       | 'ILIN'  |    X    |  n.r. |   -   |   X   |\n%       |---------|---------|-------|-------|-------|\n%       | 'SYN'   |    X    |  n.r. |   -   |   X   |\n%       | 'SYNsh' |    X    |  n.r. |   -   |   X   |\n%       |---------|---------|-------|-------|-------|\n%       | 'ISS'   |   NaN   |  NaN  |   -   |  NaN  |\n%       |---------|---------|-------|-------|-------|\n%       | 'IC'    |   NaN   |  NaN  |   -   |  NaN  |\n%       | 'ICsh'  |   NaN   |  NaN  |   -   |  NaN  |\n%       |---------|---------|-------|-------|-------|\n%       | 'ICI'   |   NaN   |  NaN  |   -   |  NaN  |\n%       |---------|---------|-------|-------|-------|\n%       | 'ICD'   |   NaN   |  NaN  |   -   |  NaN  |\n%       | 'ICDsh' |   NaN   |  NaN  |   -   |  NaN  |\n%       |---------|---------|-------|-------|-------|\n%       | 'ILB1'  |    X    |  n.r. |   -   |   X   |\n%       |---------|---------|-------|-------|-------|\n%       | 'ILB2'  |   NaN   |  NaN  |   -   |  NaN  |\n%       =============================================\n%\n%   Legend: X   : combination available\n%           -   : combination NOT permitted\n%           n.r.: combination available but not recommended\n%           NaN : NaN returned\n%\n%   --------\n%   EXAMPLES\n%   --------\n%   In the following examples, we assume R to be a 2-by-10-by-3 matrix\n%   i.e., R stores 2-dimensional responses to 3 different stimuli. We also\n%   assume that, while 10 trials are available for stimulus 1 and 2, only 7\n%   trials have been recorded for stimulus 3.\n%\n%   - Estimate I(S;R) using the direct method and no bias corrections\n%\n%       opts.nt = [10 10 7];\n%       opts.method = 'dr';\n%       opts.bias = 'naive';\n%       X = information(R, opts, 'I');\n%\n%   - Estimate I(S;R) and I_shuffle(S;R) using direct method and the\n%     quadratic extrapolation bias correction\n%\n%       opts.nt = [10 10 7];\n%       opts.method = 'dr';\n%       opts.bias = 'gsb';\n%       [X, Y] = information(R, opts, 'Ish', 'I');\n%\n%     where the estimate of I_shuffle(S;R) is stored in the X and that of\n%     I(S;R) in Y.\n%\n%   - Compute gaussian naive estimate of I(S;R) together with 20 bootstrap\n%     estimates:\n%\n%       opts.nt = [10 10 7];\n%       opts.method = 'gs';\n%       opts.bias = 'naive';\n%       opts.btsp = 20;\n%       X = information(R, opts, 'I');\n%\n%     Note that, in this case, Y is an array of size 21-by-1: Y(1) gives\n%     the estimate for I(S;R) computed using the input matrix R; Y(2:21)\n%     are are 20 distinct bootstrap estimates of I(S;R).\n%\n%   -------\n%   REMARKS\n%   -------\n%   - Field-names in the option structure are case-sensitive\n%\n%   - Ouput options are case INsensitive\n%\n%   - It is more efficient to call INFORMATION with several output options\n%     rather than calling the function repeatedly. For example:\n%\n%         [X, Y] = information(R, opts, 'I', 'Ish');\n%\n%     is faster than\n%\n%         X = information(R, opts, 'I');\n%         Y = information(R, opts, 'Ish');\n%\n%   - Some MEX files in the toolbox create static arrays which are used\n%     to store computations performed in previous calls to the routines.\n%     This memory is freed automatically when Matlab is quitted. However,\n%     consider using\n%\n%         clear mex;\n%\n%     when needing to free all of Matlab's available memory.\n\n% NOTE:\n% The function also computes IXS and IXSsh according to the following\n% equations:\n%\n%       =================================================================\n%       | Option  | Description       | Expression (in terms of ENTROPY |\n%       |         |                   | output options)                 |\n%       =================================================================\n%       | 'IXS'   | I(R|S)            | IXS   = HiRS - HRS              |\n%       | 'IXSsh' | I(R|S) shuffle    | IXSsh = HshRS - HRS             |\n%       =================================================================\n%\n% However, since this quantity is meaningful only for L=2, this feature\n% is kept hidden. The combination tables for this quantity are\n% as follows:\n%\n%       =============================================\n%       | DIRECT METHOD                             |\n%       =============================================\n%       |         | 'naive' | 'qe'  | 'pt'  | 'gsb' |\n%       |-------------------------------------------|\n%       | 'IXS'   |    X    |   X   |   X   |   -   |\n%       | 'IXSsh' |    X    |   X   |   X   |   -   |\n%       =============================================\n%\n%   Legend: X: combination available\n%           -: combination NOT available\n%\n%\n%       =============================================\n%       | GAUSSIAN METHOD                           |\n%       =============================================\n%       |         | 'naive' | 'qe'  | 'pt'  | 'gsb' |\n%       |-------------------------------------------|\n%       | 'IXS'   |    X    |  n.r. |   -   |   X   |\n%       | 'IXSsh' |    X    |  n.r. |   -   |   X   |\n%       =============================================\n%\n%   Legend: X   : combination available\n%           -   : combination NOT available\n%           n.r.: combination available but not recommended\n\n%   Copyright (C) 2009 Cesare Magri\n%   Version: 1.0.5\n\n% -------\n% LICENSE\n% -------\n% This software is distributed free under the condition that:\n%\n% 1. it shall not be incorporated in software that is subsequently sold;\n%\n% 2. the authorship of the software shall be acknowledged and the following\n%    article shall be properly cited in any publication that uses results\n%    generated by the software:\n%\n%      Magri C, Whittingstall K, Singh V, Logothetis NK, Panzeri S: A\n%      toolbox for the fast information analysis of multiple-site LFP, EEG\n%      and spike train recordings. BMC Neuroscience 2009 10(1):81;\n%\n% 3.  this notice shall remain in place in each source file.\n\n% NOTE:\n% In this function HiRS is indeed output option 'HiRS' of function\n% entropy.m, thus corresponding to the variable HlRS in the same function.\n\nwhereI     = strcmpi(varargin, 'i');\nwhereIsh   = strcmpi(varargin, 'ish');\nwhereIX    = strcmpi(varargin, 'ix');\nwhereIXS   = strcmpi(varargin, 'ixs');\nwhereIXSsh = strcmpi(varargin, 'ixssh');\nwhereILIN  = strcmpi(varargin, 'ilin');\nwhereSYN   = strcmpi(varargin, 'syn');\nwhereSYNsh = strcmpi(varargin, 'synsh');\nwhereISS   = strcmpi(varargin, 'iss');\nwhereIC    = strcmpi(varargin, 'ic');\nwhereICsh  = strcmpi(varargin, 'icsh');\nwhereICI   = strcmpi(varargin, 'ici');\nwhereICD   = strcmpi(varargin, 'icd');\nwhereICDsh = strcmpi(varargin, 'icdsh');\nwhereILB1  = strcmpi(varargin, 'ilb1');\nwhereILB2  = strcmpi(varargin, 'ilb2');\n\nwhereuvar  = strcmpi(varargin, 'uvar');\nif sum(whereuvar)\n  Runit = varargin{find(whereuvar)+1};\n  sel = find(whereuvar);\n  sel = [sel sel+1];\n  varargin(sel) = [];\nend\n\ndoI     = any(whereI);\ndoIsh   = any(whereIsh);\ndoIX    = any(whereIX);\ndoIXS   = any(whereIXS);\ndoIXSsh = any(whereIXSsh);\ndoILIN  = any(whereILIN);\ndoSYN   = any(whereSYN);\ndoSYNsh = any(whereSYNsh);\ndoISS   = any(whereISS);\ndoIC    = any(whereIC);\ndoICsh  = any(whereICsh);\ndoICI   = any(whereICI);\ndoICD   = any(whereICD);\ndoICDsh = any(whereICDsh);\ndoILB1  = any(whereILB1);\ndoILB2  = any(whereILB2);\n\n% Checks ------------------------------------------------------------------\nspecifiedOutputOptsVec = ...\n    [doI doIsh doIX doIXS doIXSsh doILIN doSYN doSYNsh doISS doIC doICsh doICI doICD doICDsh doILB1 doILB2];\nNspecifiedOutputOpts = sum(specifiedOutputOptsVec);\nlengthVarargin = length(varargin);\nif NspecifiedOutputOpts~=lengthVarargin\n    msg = 'Unknown selection or repeated option in output list.';\n    error('information:unknownOutputOpt', msg);\nend\n\n% Restrictions on possible combinantions ----------------------------------\nif strcmpi(opts.method, 'dr')\n    % Can't apply bias-correction gsb with method dr:\n    if strcmpi(opts.bias, 'gsb')\n        msg = 'Bias correction ''gsb'' can only be used in conjunction with method ''gs''.';\n        error('Information:drMethodAndGsbBias', msg);\n    end\n\n    % Can't compute ISS, IC, ICsh, ICI, ICD, ICDsh or ILB2 for\n    % bias-correction pt\n    if strcmpi(opts.bias, 'pt') && (doISS || doIC || doICsh || doICI || doICD || doICDsh || doILB2)\n        msg = 'One or more of the selected output options are not available for bias correction ''pt''.';\n        error('information:ptBiasAndNonAvailableOutputOpt', msg);\n    end\nend\n\n% Default verbose value:\nif ~isfield(opts, 'verbose')\n    opts.verbose = false;\nend;\n\nisGaussianMethod = false;\nif strcmpi(opts.method, 'gs')\n    isGaussianMethod = true;\n    \n    % Gaussian and QE is not recommended:\n    if opts.verbose && strcmpi(opts.bias, 'qe')\n        msg = 'Usage of bias correction ''qe'' in conjunction with gaussian method is not recommended.';\n        warning('Information:gsMethodAndQeBias', msg);\n    end\n    \n    % Gaussian and PT is not allowed:\n    if strcmpi(opts.bias, 'pt')\n        msg = 'Bias correction ''pt'' can only be used in conjunction with method ''dr''.';\n        error('Information:gsMethodAndPtBias', msg);\n    end\nend\n\nallOutputOpts = {'HR' 'HRS' 'HlR' 'HiR' 'HiRS' 'ChiR' 'HshRS'};\npositionInOuputOptsList = 0;\n\n% What needs to be computed by ENTTROPY -----------------------------------\n% Need to compute H(R)? \ndoHR = false;\nif doI || doIsh || doIX || doSYN || doSYNsh || doIC || doICsh || doICD || doICDsh || doILB1\n    positionInOuputOptsList = positionInOuputOptsList + 1;\n    whereHR = positionInOuputOptsList;\n    doHR = true;\nend\n\n% Need to compute H(R|S)?\ndoHRS = false;\nif doI || doIsh || doIXS || doIXSsh || doSYN || doSYNsh || doIC || doICsh || doICD || doICDsh\n    positionInOuputOptsList = positionInOuputOptsList + 1;\n    whereHRS = positionInOuputOptsList;\n    doHRS = true;\nend\n\n% Need to compute H_lin(R)?\ndoHlR = false;\nif doIX || doSYN || doILIN || doSYNsh || doISS\n    positionInOuputOptsList = positionInOuputOptsList + 1;\n    whereHlR = positionInOuputOptsList;\n    doHlR = true;\nend\n\n% Need to compute H_ind(R)?\ndoHiR = false;\nif (doISS || doIC || doICsh || doICI) && ~isGaussianMethod\n    positionInOuputOptsList = positionInOuputOptsList + 1;\n    whereHiR = positionInOuputOptsList;\n    doHiR = true;\nend\n\n% Need to compute H_ind(R|S)?\ndoHiRS = false;\nif doIsh || doIXS || doILIN || doSYN || doIC || doICD || doILB1 || doILB2\n    positionInOuputOptsList = positionInOuputOptsList + 1;\n    whereHiRS = positionInOuputOptsList;\n    doHiRS = true;\nend\n\n% Need to compute Chi(R)?\ndoChiR = false;\nif (doICI || doICD || doICDsh || doILB2) && ~isGaussianMethod\n    positionInOuputOptsList = positionInOuputOptsList + 1;\n    whereChiR = positionInOuputOptsList;\n    doChiR = true;\nend\n\n% Need to compute H_sh(R|S)?\ndoHshRS = false;\nif doIsh || doIXSsh || doSYNsh || doICsh || doICDsh\n    positionInOuputOptsList = positionInOuputOptsList + 1;\n    whereHshRS = positionInOuputOptsList;\n    doHshRS = true;\nend\n\n% Computing information theoretic quantities ------------------------------\noutputOptsList = allOutputOpts([doHR doHRS doHlR doHiR doHiRS doChiR doHshRS]);\n\nH = cell(positionInOuputOptsList, 1);\nif ~exist('Runit', 'var')\n  [H{:}] = entropy(R, opts, outputOptsList{:});\nelse\n  [H{:}] = entropy(R, opts, outputOptsList{:}, 'uvar', Runit);\nend\n  \n% Assigning output --------------------------------------------------------\nvarargout = cell(length(varargin),1);\n\n% I = HR - HRS\nif doI\n    varargout(whereI) = {H{whereHR} - H{whereHRS}};\nend\n\n% Ish = HR - HiRS + HshRS - HRS\nif doIsh\n    varargout(whereIsh) = {H{whereHR} - H{whereHiRS} + H{whereHshRS} - H{whereHRS}};\nend\n\n% IX = HlR - HR\nif doIX\n    varargout(whereIX) = {H{whereHlR} - H{whereHR}};\nend\n\n% IXS = HiRS - HRS\nif doIXS\n    varargout(whereIXS) = {H{whereHiRS} - H{whereHRS}};\nend\n\n% IXSsh = HshRS - HRS\nif doIXSsh\n    varargout(whereIXSsh) = {H{whereHshRS} - H{whereHRS}};\nend\n\n% ILIN = HlR - HiRS\nif doILIN\n    varargout(whereILIN) = {H{whereHlR} - H{whereHiRS}};\nend\n\n% SYN = HR - HRS - HlR + HiRS\nif doSYN\n    varargout(whereSYN) = {H{whereHR} - H{whereHRS} - H{whereHlR} + H{whereHiRS}};\nend\n\n% SYNsh = HR + HshRS - HRS - HlR\nif doSYNsh\n    varargout(whereSYNsh) = {H{whereHR} + H{whereHshRS} - H{whereHRS} - H{whereHlR}};\nend\n\n% ISS = HiR - HlR\nif doISS\n    if ~isGaussianMethod\n        varargout(whereISS) = {H{whereHiR} - H{whereHlR}};\n    else\n        varargout(whereISS) = {NaN};\n    end\nend\n\n% IC = HR - HRS + HiRS - HiR\nif doIC\n    if ~isGaussianMethod\n        varargout(whereIC) = {H{whereHR} - H{whereHRS} + H{whereHiRS} - H{whereHiR}};\n    else\n        varargout(whereIC) = {NaN};\n    end\nend\n\n% ICsh  = HR + HshRS - HRS - HiR\nif doICsh\n    if ~isGaussianMethod\n        varargout(whereICsh) = {H{whereHR} + H{whereHshRS} - H{whereHRS} - H{whereHiR}};\n    else\n        varargout(whereICsh) = {NaN};\n    end\nend\n\n% ICI= ChiR - HiR\nif doICI\n    if ~isGaussianMethod\n        varargout(whereICI) = {H{whereChiR} - H{whereHiR}};\n    else\n        varargout(whereICI) = {NaN};\n    end\nend\n\n% ICD = HR - HRS - ChiR + HiRS\nif doICD\n    if ~isGaussianMethod\n        varargout(whereICD) = {H{whereHR} - H{whereHRS} - H{whereChiR} + H{whereHiRS}};\n    else\n        varargout(whereICD) = {NaN};\n    end\nend\n\n% ICDsh = HR + HshRS - HRS - ChiR\nif doICDsh\n    if ~isGaussianMethod\n        varargout(whereICDsh) = {H{whereHR} + H{whereHshRS} - H{whereHRS} - H{whereChiR}};\n    else\n        varargout(whereICDsh) = {NaN};\n    end\nend\n\n% ILB1 = HR - HiRS\nif doILB1\n    varargout(whereILB1) = {H{whereHR} - H{whereHiRS}};\nend\n\n% ILB2 = ChiR - HiRS\nif doILB2\n    if ~isGaussianMethod\n        varargout(whereILB2) = {H{whereChiR} - H{whereHiRS}};\n    else\n        varargout(whereILB2) = {NaN};\n    end\nend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/ibtb/information.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5741065841327695}}
{"text": "function PlotMesh(coordinates,nodes)\n%--------------------------------------------------------------------------\n% Code written by : Siva Srinivas Kolukula                                |\n%                   Senior Research Fellow                                |\n%                   Structural Mechanics Laboratory                       |\n%                   Indira Gandhi Center for Atomic Research              |\n%                   India                                                 |\n% E-mail : allwayzitzme@gmail.com                                         |\n%          http://sites.google.com/site/kolukulasivasrinivas/             |    \n%--------------------------------------------------------------------------\n%--------------------------------------------------------------------------\n% Purpose:\n%         To plot the Finite Element Method Mesh\n% Synopsis :\n%           PlotMesh(coordinates,nodes)\n% Variable Description:\n%           coordinates - The nodal coordinates of the mesh\n%           -----> coordinates = [node X Y] \n%           nodes - The nodal connectivity of the elements\n%           -----> nodes = [node1 node2......]    \n%--------------------------------------------------------------------------\n\nnel = length(nodes) ;                  % number of elements\nnnode = length(coordinates) ;          % total number of nodes in system\nnnel = size(nodes,2);                % number of nodes per element\n% \n% Initialization of the required matrices\nX = zeros(nnel,nel) ;\nY = zeros(nnel,nel) ;\n\nfor iel=1:nel   \n     for i=1:nnel\n     nd(i)=nodes(iel,i);         % extract connected node for (iel)-th element\n     X(i,iel)=coordinates(nd(i),1);    % extract x value of the node\n     Y(i,iel)=coordinates(nd(i),2);    % extract y value of the node\n     end\nend\n    \n% Plotting the FEM mesh, diaplay Node numbers and Element numbers\n     f1 = figure ;\n     set(f1,'name','Mesh','numbertitle','off') ;\n     plot(X,Y,'k')\n     fill(X,Y,'w')\n     \n     title('Finite Element Mesh') ;\n     axis off ;\n     k = nodes(:,1:end);\n     nd = k' ;\n    for i = 1:nel\n     text(X(:,i),Y(:,i),int2str(nd(:,i)),'fontsize',8,'color','k');\n     text(sum(X(:,i))/4,sum(Y(:,i))/4,int2str(i),'fontsize',10,'color','r') ;\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/31788-the-plane-stress-problem/Plane Stress/PlotMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.5741065749297506}}
{"text": "function Solution = GhiaSolution\n%GhiaSolution returns a benchmark solution for lid-driven cavity flow\n%   The data is taken from:\n%     Ghia, U. K. N. G., Kirti N. Ghia, and C. T. Shin. \n%     \"High-Re solutions for incompressible flow using the Navier-Stokes \n%     equations and a multigrid method.\"\n%     Journal of computational physics 48.3 (1982): 387-411.\n\nSolution.Re=[100 400 1000];\n\nSolution.y = [1.0000,...\n              0.9766,...\n              0.9688,...\n              0.9609,...\n              0.9531,...\n              0.8516,...\n              0.7344,...\n              0.6172,...\n              0.5000,...\n              0.4531,...\n              0.2813,...\n              0.1719,...\n              0.1016,...\n              0.0703,...\n              0.0625,...\n              0.0547,...\n              0.0000];\n% Re=100\nSolution.u{1}=   [1.0000,...\n                  0.84123,...\n                  0.78871,...\n                  0.73722,...\n                  0.68717,...\n                  0.23151,...\n                  0.00332,...\n                 -0.13641,...\n                 -0.20581,...\n                 -0.21090,...\n                 -0.15662,...\n                 -0.10150,...\n                 -0.06434,...\n                 -0.04775,...\n                 -0.04192,...\n                 -0.03717,...\n                  0.00000];\n% Re=400\nSolution.u{2}=   [1.00000,...\n                  0.75837,...\n                  0.68439,...\n                  0.61756,...\n                  0.55892,...\n                  0.29093,...\n                  0.16256,...\n                  0.02135,...\n                 -0.11477,...\n                 -0.17119,...\n                 -0.32726,...\n                 -0.24299,...\n                 -0.14612,...\n                 -0.10338,...\n                 -0.09266,...\n                 -0.08186,...\n                  0.00000];\n%Re=1000\nSolution.u{3}=   [1.0000,...\n                  0.65928,...\n                  0.57492,...\n                  0.51117,...\n                  0.46604,...\n                  0.33304,...\n                  0.18719,...\n                  0.05702,...\n                 -0.06080,...\n                 -0.10648,...\n                 -0.27805,...\n                 -0.38289,...\n                 -0.29730,...\n                 -0.22220,...\n                 -0.20196,...\n                 -0.18109,...\n                  0.00000];\n              \nSolution.x = [1.0000,...\n              0.9688,...\n              0.9609,...\n              0.9531,...\n              0.9453,...\n              0.9063,...\n              0.8594,...\n              0.8047,...\n              0.5000,...\n              0.2344,...\n              0.2266,...\n              0.1563,...\n              0.0938,...\n              0.0781,...\n              0.0703,...\n              0.0625,...\n              0.0000];    \n%Re=100\nSolution.v{1}=[0.00000,...\n              -0.05906,...\n              -0.07391,...\n              -0.08864,...\n              -0.10313,...\n              -0.16914,...\n              -0.22445,...\n              -0.24533,...\n               0.05454,...\n               0.17527,...\n               0.17507,...\n               0.16077,...\n               0.12317,...\n               0.10890,...\n               0.10091,...\n               0.09233,...\n               0.00000];\n% Re=400\nSolution.v{2}=[0.00000,...\n              -0.12146,...\n              -0.15663,...\n              -0.19254,...\n              -0.22847,...\n              -0.23827,...\n              -0.44993,...\n              -0.38598,...\n               0.05186,...\n               0.30174,...\n               0.30203,...\n               0.28124,...\n               0.22965,...\n               0.20920,...\n               0.19713,...\n               0.18360,...\n               0.00000];\n%Re=1000\nSolution.v{3}=[0.00000,...\n              -0.21388,...\n              -0.27669,...\n              -0.33714,...\n              -0.39188,...\n              -0.51550,...\n              -0.42665,...\n              -0.31966,...\n               0.02526,...\n               0.32235,...\n               0.33075,...\n               0.37095,...\n               0.32627,...\n               0.30353,...\n               0.29012,...\n               0.27485,...\n               0.00000];\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/Functions/GhiaSolution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.574106570328241}}
{"text": "function life3D(action)\n%LIFE3D   MATLAB's version of Conway's Game of Life.\n%   \"Life\" is a cellular automaton invented by John\n%   Conway that involves live and dead cells in a  \n%   rectangular, two-dimensional universe. In      \n%   MATLAB, the universe is a sparse matrix that   \n%   is initially all zero.                         \n%                                                  \n%   Whether cells stay alive, die, or generate new \n%   cells depends upon how many of their eight     \n%   possible neighbors are alive. By using sparse  \n%   matrices, the calculations required become     \n%   astonishingly simple. We use periodic (torus)  \n%   boundary conditions at the edges of the        \n%   universe. Pressing the \"Start\" button          \n%   automatically seeds this universe with several \n%   small random communities. Some will succeed    \n%   and some will fail.     \n%\n%   Expanded to 3D by:\n%       Leandro Barajas 06-20-2002 L.G.Barajas@ieee.org\n%\n%   C. Moler, 7-11-92, 8-7-92.\n%   Adapted by Ned Gulley, 6-21-93\n%\n\n%   Copyright 1984-2001 The MathWorks, Inc. \n%   $Revision: 5.9 $  $Date: 2001/04/15 12:03:02 $\n\n% Possible actions:\n% initialize\n% start\n\n% Information regarding the play status will be held in\n% the axis user data according to the following table:\nplay= 1;\nstop=-1;\n\nif nargin<1,\n   action='initialize';\nend;\n\nif strcmp(action,'initialize'),\n   figNumber=figure( ...\n      'Name','Life3D: Conway''s Game of Life in 3-Dimesions', ...\n      'NumberTitle','off', ...\n      'DoubleBuffer','on', ...\n      'Visible','off', ...\n      'Color','white', ...\n      'BackingStore','off');\n   axes( ...\n      'Units','normalized', ...\n      'Position',[0.05 0.05 0.75 0.90], ...\n      'Visible','off', ...\n      'DrawMode','fast', ...\n      'Color','none',...\n      'NextPlot','add');\n%      'NextPlot','replace' );\n\n   text(0,0,{'Press the \"Start\" button to see the Game of Life demo' 'Use the slider to change the number of initial cells.'}, ...\n      'HorizontalAlignment','center');\n   axis([-1 1 -1 1]);\n   \n   %===================================\n   % Information for all buttons\n   labelColor=[0.8 0.8 0.8];\n   yInitPos=0.90;\n   xPos=0.85;\n   btnLen=0.10;\n   btnWid=0.10;\n   % Spacing between the button and the next command's label\n   spacing=0.05;\n   \n   %====================================\n   % The CONSOLE frame\n   frmBorder=0.02;\n   yPos=0.05-frmBorder;\n   frmPos=[xPos-frmBorder yPos btnLen+2*frmBorder 0.9+2*frmBorder];\n   h=uicontrol( ...\n      'Style','frame', ...\n      'Units','normalized', ...\n      'Position',frmPos, ...\n      'BackgroundColor',[0.50 0.50 0.50]);\n   \n   %====================================\n   % The START button\n   btnNumber=1;\n   yPos=0.90-(btnNumber-1)*(btnWid+spacing);\n   labelStr='Start';\n   cmdStr='start';\n   callbackStr='life3D(''start'');';\n   \n   % Generic button information\n   btnPos=[xPos yPos-spacing btnLen btnWid];\n   startHndl=uicontrol( ...\n      'Style','pushbutton', ...\n      'Units','normalized', ...\n      'Position',btnPos, ...\n      'String',labelStr, ...\n      'Interruptible','on', ...\n      'Callback',callbackStr);\n   \n   %====================================\n   % The STOP button\n   btnNumber=2;\n   yPos=0.90-(btnNumber-1)*(btnWid+spacing);\n   labelStr='Stop';\n   % Setting userdata to -1 (=stop) will stop the demo.\n   callbackStr='set(gca,''Userdata'',-1)';\n\n   \n   % Generic button information\n   btnPos=[xPos yPos-spacing btnLen btnWid];\n   stopHndl=uicontrol( ...\n      'Style','pushbutton', ...\n      'Units','normalized', ...\n      'Position',btnPos, ...\n      'Enable','off', ...\n      'String',labelStr, ...\n      'Callback',callbackStr);\n   \n   %====================================\n   % The NumberOfCell Slider\n   labelStr='# Cells';\n      \n   callbackStr='h=findobj(gcf,''Tag'',''StartCells'');set(h,''Tooltip'',sprintf(''Initial Cells: %4d'',floor(get(h,''Value''))));';\n   infoHndl=uicontrol( ...\n      'Style','slider', ...\n      'Units','normalized', ...\n      'Position',[xPos btnWid+btnWid*2+0.05 btnLen/4 0.10*3], ...\n      'String',labelStr, ...\n      'SliderStep',[.01 .1], ...\n      'Max',100, ...\n      'Min',1, ...\n      'Value',20, ...\n      'Tooltip','Initial Cells:  20',...\n      'Tag','StartCells', ...\n      'Callback',callbackStr);\n\n\n  %====================================\n   % The INFO button\n   labelStr='Info';\n   callbackStr='life3D(''info'')';\n   infoHndl=uicontrol( ...\n      'Style','push', ...\n      'Units','normalized', ...\n      'Position',[xPos 0.20 btnLen 0.10], ...\n      'String',labelStr, ...\n      'Callback',callbackStr);\n   \n   %====================================\n   % The CLOSE button\n   labelStr='Close';\n   callbackStr='close(gcf)';\n   closeHndl=uicontrol( ...\n      'Style','push', ...\n      'Units','normalized', ...\n      'Position',[xPos 0.05 btnLen 0.10], ...\n      'String',labelStr, ...\n      'Callback',callbackStr);\n   \n   % Uncover the figure\n   hndlList=[startHndl stopHndl infoHndl closeHndl];\n   set(figNumber,'Visible','on', ...\n      'UserData',hndlList);\n  \n   view(3);  \n   StartCells = 20;\n   m = 19;\n   colormap(jet(m));\n   colorbar;\n\nelseif strcmp(action,'start'),\n   objh=findobj(gcf,'Tag','StartCells');\n   StartCells = get(objh,'Value');\n   m = 19;\n   cla;\n   axHndl=gca;\n   figNumber=gcf;\n   hndlList=get(figNumber,'Userdata');\n   startHndl=hndlList(1);\n   stopHndl=hndlList(2);\n   infoHndl=hndlList(3);\n   closeHndl=hndlList(4);\n   set([startHndl closeHndl infoHndl],'Enable','off');\n   set(stopHndl,'Enable','on');\n   \n   % ====== Start of Demo\n   set(axHndl, ...\n      'UserData',play, ...\n      'DrawMode','fast', ...\n      'Visible','on');\n   box off\n   \n   X = zeros(m,m,m);\n   \n   p = -1:1;\n   for count=1:StartCells,\n      kx=floor(rand*(m-4))+2; \n      ky=floor(rand*(m-4))+2; \n      kz=floor(rand*(m-4))+2; \n      X(kx+p,ky+p,kz+p)=(rand(3,3,3)>0.5);\n   end;\n\n   \n   % The following statements plot the initial configuration.\n   % The \"find\" function returns the indices of the nonzero elements.\n   plothandle=[];\n   figure(gcf);\n   hold on\n   colour=jet(m);\n   for k=1:m\n       [i,j] = find(X(:,:,k));\n%       kd = sub2ind(size(X(i,j,k)),i,j)      \n       kd = k(ones(size(i)));\n       if isempty(i)\n           i = 1;\n           j = 1;\n           kd = NaN;\n       end\n       plothandle(k) = line(i,j,kd);\n       set(plothandle(k),'linestyle','none',...\n                      'Marker','.',...\n                      'MarkerSize',20*2,...\n                      'MarkerFaceColor',colour(k,:),...\n                      'MarkerEdgeColor',colour(k,:),...\n                      'EraseMode','normal');\n\n   end   \n   drawnow                  \n   axis([0 m+1 0 m+1 0 m+1]);\n\n   hold off\n\n\n   % Whether cells stay alive, die, or generate new cells depends\n   % upon how many of their eight possible neighbors are alive.\n   % Here we generate index vectors for four of the eight neighbors.\n   % We use periodic (torus) boundary conditions at the edges of the universe.\n   \n   n = [m 1:m-1];\n   e = [2:m 1];\n   s = [2:m 1];\n   w = [m 1:m-1];\n   u = [m 1:m-1];\n   d = [2:m 1];\n\n   rotate3d on\n   while get(axHndl,'UserData')==play,\n    % How many of eight+5+5 neighbors are alive. (only the ones that share at least one border\n    %      N = X(n,:,:) + X(s,:,:) + X(:,e,:) + X(:,w,:) + ...\n    %          X(n,e,:) + X(n,w,:) + X(s,e,:) + X(s,w,:);\n    \n    % 3D Version\n    \n    % Use Euclidean distance\n    d1 = 1/1;           % Adjacent cells (Share 4 vertix)\n    d2 = 1/sqrt(2);     % Diagonal cells (Share 2 vertix)\n    d3 = 1/sqrt(3);     % Double Diagonal cells (Share 1 vertix)\n\n    % How many of 9+9+8 neighbors are alive. (Only the ones that share at least one vertix)\n      N = X(n,:,:)*d1 + X(s,:,:)*d1 + X(:,e,:)*d1 + X(:,w,:)*d1 + ...\n          X(n,e,:)*d2 + X(n,w,:)*d2 + X(s,e,:)*d2 + X(s,w,:)*d2 + ...\n          X(n,:,u)*d2 + X(s,:,u)*d2 + X(:,e,u)*d2 + X(:,w,u)*d2 + ...\n          X(n,:,d)*d2 + X(s,:,d)*d2 + X(:,e,d)*d2 + X(:,w,d)*d2 + ...\n          X(n,e,u)*d3 + X(s,e,u)*d3 + X(s,w,u)*d3 + X(n,w,u)*d3 + ...\n          X(n,e,d)*d3 + X(s,e,d)*d3 + X(s,w,d)*d3 + X(n,w,d)*d3 + ...\n          X(:,:,u)*d1 + X(:,:,d)*d1;\n\n      \n      % A live cell with two live neighbors, or any cell with three\n      % neigbhors, is alive at the next time step.\n      Xold = X;\n\n      CL = 3.0;             % Minimun # cells to create a new one\n      CH = 4.0;             % Maximum # cells to create a new one\n      KL = 4.0;             % Minimun # cells to kill one\n      \n      X = ( (    ((N >= CL) & (N <= CH)) ) &...    % Create cells\n         ~(  X & ((N >  KL)           )) ) ;       % Kill cells by overpopulation\n    \n      Xsum = sum(X(:));\n      if (Xsum>prod(size(X))/8);\n         X = ( X & (rand(size(X))>0.1) ); % Expontaneous cell annihilation\n      end\n    \n      if Xold==X   % if no change the exit\n         break;\n      end\n\n      % Update plot.\n      for k=1:m\n          [i,j] = find(X(:,:,k));\n          set(plothandle(k),'xdata',i,'ydata',j,'zdata',k(ones(size(i))));\n      end   \n\n      set(plothandle,'Visible','on');\n      box on\n      title( sprintf('Total Cells: %d',Xsum))\n      xlabel(sprintf('Density: %5.2f%%',mean(X(:))*100))\n      ylabel(sprintf('Rate: %5.2f%%',(mean(X(:))-mean(Xold(:)))*100))\n      \n      drawnow\n      pause(0.2)\n   end\n   \n   % ====== End of Demo\n\n   set([startHndl closeHndl infoHndl],'Enable','on');\n   set(stopHndl,'Enable','off');\n   \nelseif strcmp(action,'info');\n   helpwin(mfilename);\n   \nend;    % if strcmp(action, ...\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4892-conways-game-of-life-in-3d/life3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.5741065620534237}}
{"text": "function stroud_test27 ( )\n\n%*****************************************************************************80\n%\n%% TEST27 tests SIMPLEX_ND.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    06 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  global FUNC_ND_INDEX;\n\n  num = function_nd_num ( );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST27\\n' );\n  fprintf ( 1, '  SIMPLEX_ND approximates integrals inside an\\n' );\n  fprintf ( 1, '    arbitrary simplex in ND.\\n' );\n  fprintf ( 1, '\\n' );\n \n  for n = 2 : 4\n \n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Spatial dimension N = %d\\n', n );\n%\n%  Restore values of simplex.\n%\n    v = setsim ( n );\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Simplex vertices:\\n' );\n    fprintf ( 1, '\\n' );\n \n    for i = 1 : n+1\n      for j = 1 : n\n        fprintf ( 1, '  %4f', v(i,j) );\n      end\n      fprintf ( 1, '\\n' );\n    end\n \n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  F(X)    SIMPLEX_ND\\n' );\n    fprintf ( 1, '\\n' );\n\n    for i = 1 : num\n\n      FUNC_ND_INDEX = i;\n\n      result = simplex_nd ( 'function_nd', n, v );\n\n      fname = function_nd_name ( i );\n\n      fprintf ( 1, '  %s  %14f\\n', fname, result );\n \n      v = setsim ( 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/stroud/stroud_test27.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.5740207615306928}}
{"text": "function x = project_box(v, l, u)\n% PROJECT_BOX    Project a point onto a box (hyper-rectangle).\n%\n%   project_box(v,l,u) is the projection of v onto\n%   the set { x | l <= x <= u }.\n\n    x = max(l, min(v, u));\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_box.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.5740207609419867}}
{"text": "function nMC=grMinEdgeCover(E)\n% Function nMC=grMinEdgeCover(E) solve the minimal edge cover problem.\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 edge;\n%     m - number of edges.\n%     If we set the array E(m,2), then all weights is 1.\n% Output parameter:\n%   nMC - the list of the numbers of edges included \n%     in the minimal (weighted) edge 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\n\n% ============= Parameters of integer LP problem ==========\nA=zeros(n,m); % for incidence matrix\nA(E(:,1:2)+repmat(([1:m]'-1)*n,1,2))=1; % we fill the incidence matrix\noptions=optimset('bintprog'); % the default options\noptions.Display='off'; % we change the output\n\n% ============= We solve the integer LP problem ==========\nxmin=bintprog(E(:,3),-A,-ones(n,1),[],[],[],options);\nnMC=find(round(xmin)); % the answer - numbers of edges\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(\u56fe\u8bba)/basic/grMinEdgeCover.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5739108048270589}}
{"text": "function classifier = train_boosted_dt_mc(features, cat_features, labels, ...\n    num_iterations, num_nodes, stopval, init_weights, varargin)\n%\n%classifier = train_boosted_dt_mc(features, cat_features, labels, ...\n%    num_iterations, num_nodes, stopval, init_weights, varargin)\n%\n% Train a classifier based on boosted decision trees.  Boosting done by the\n% logistic regression version of Adaboost (Adaboost.L - Collins, Schapire,\n% Singer 2002).  At each\n% iteration, a set of decision trees is created for each class, with\n% confidences equal to 1/2*ln(P+/P-) for that class, according to the\n% weighted distribution.  Final classification is based on the largest\n% confidence label (possibly incorporating a prior as h0(c) =\n% 1/2*ln(Pc/(1-Pc)).  Weights are assigned as\n% w(i,j) = 1 / (1+exp(sum{t in iterations}[yij*ht(xi, j)])).  \n\nif length(varargin) == 1  % class names supplied\n    gn = varargin{1};\n    gid = zeros(size(labels));\n    for c = 1:length(gn)\n        ind = find(strcmp(labels, gn{c}));\n        gid(ind) = c;\n        if ~isempty(init_weights)\n            disp([gn{c} ': ' num2str(sum(init_weights(ind)))]);\n        else\n            disp([gn{c} ': ' num2str(length(ind))]);\n        end\n    end\n    ind = find(gid==0);\n    gid(ind) = [];\n    labels(ind) = [];\n    features(ind, :) = [];\nelse    \n    [gid, gn] = grp2idx(labels);    \nend\n\nif ~exist('stopval', 'var') || isempty(stopval)\n    stopval = 0;\nend\nif ~exist('init_weights', 'var') \n    init_weights = [];\nend\n\nclassifier.names = gn;\n\nnum_classes = length(gn);\nnum_data = length(gid);\n\nif isempty(init_weights)\n    init_weights = ones(num_data, 1)/num_data;\nelse\n    init_weights = init_weights / sum(init_weights);\nend\n\n% if no examples from a class are present, create one dummy example for\n% that class with very small weight\nfor c = 1:numel(gn)\n    if ~any(gid==c)\n        disp(['warning: no examples from class ' gn(c)])\n        gid(end+1) = c;\n        features(end+1, :) = zeros(size(features(end, 1)));\n        num_data = num_data + 1;\n        init_weights(end+1) = min(init_weights)/2;        \n    end\nend\n\nall_conf = zeros(num_data, num_classes);\nfor c = 1:num_classes\n\n    disp(['class: ' num2str(gn{c})]);    \n    y = (gid == c)*2-1;\n    cl = [-1 1];\n    nc = 2;\n    w = zeros(num_data, 1);\n    cw = zeros(num_classes, 1);  \n    for i = 1:2\n        indices = find(y==cl(i));\n        %count = sum(init_weights(indices));\n        %w(indices) = init_weights(indices) / count / 2;\n        w(indices) = init_weights(indices);\n        \n        if cl(i)==1\n            %classifier.h0(c) = log(count / (1-count));\n            classifier.h0(c) = 0;\n        end\n        \n    end\n        \n    data_confidences = zeros(num_data, 1);\n    aveconf = [];\n    \n    for t = 1:num_iterations\n        % learn decision tree based on weighted distribution\n        dt = treefitw(features, y, w, 1/num_data/2, 'catidx', cat_features, 'method', 'classification', 'maxnodes', num_nodes*4);\n        [tmp, level] = min(abs(dt.ntermnodes-num_nodes));\n        dt = treeprune(dt, 'level', level-1);\n\n        % assign partition confidences\n        pi = (strcmp(dt.classname{1},'1')) + (2*strcmp(dt.classname{2},'1'));\n        ni = (strcmp(dt.classname{1},'-1')) + (2*strcmp(dt.classname{2},'-1'));\n        \n        classprob = dt.classprob;\n        confidences = 1/2*(log(classprob(:, pi)) - log(classprob(:, ni)));             \n\n        % assign weights\n        [class_indices, nodes, classes] = treeval(dt, features);        \n        data_confidences = data_confidences + confidences(nodes);\n        \n        w = 1 ./ (1+exp(y.*data_confidences));        \n        w = w / sum(w);   \n                \n        %disp(['c: ' num2str(mean(1 ./ (1+exp(-y.*data_confidences)))) '  e: ' num2str(mean(y.*data_confidences < 0)) '   w: ' num2str(max(w))]);  \n        \n        classifier.wcs(t, c).dt = dt;\n        classifier.wcs(t, c).confidences = confidences;       \n             \n        \n        aveconf(t) = mean(1 ./ (1+exp(-y.*data_confidences)));\n        if t>10 && (aveconf(t)-aveconf(t-10) < stopval)\n            disp(num2str(aveconf))\n            disp(['Stopping after ' num2str(t) ' trees'])            \n            break;\n        end\n        \n    end\n\n    finalconf = 1 ./ (1+exp(-y.*data_confidences));\n    finalerr = (y.*data_confidences < 0);\n    disp(['confidence:: mean: ' num2str(mean(finalconf)) ...\n        '  pos: ' num2str(mean(finalconf(y==1))) ...\n        '  neg: ' num2str(mean(finalconf(y~=1)))]);\n    disp(['training error:: mean: ' num2str(mean(finalerr)) ...\n        '  pos: ' num2str(mean(finalerr(y==1))) ...\n        '  neg: ' num2str(mean(finalerr(y~=1)))]);    \n    all_conf(:, c) = data_confidences+classifier.h0(c);\n  \nend\n\n% compute and display training error\n[tmp, assigned_label] = max(all_conf, [], 2);\nconf_matrix = zeros(num_classes, num_classes);\nfor c = 1:num_classes    \n    indices = find(gid==c);\n    for c2 = 1:num_classes\n        conf_matrix(c, c2) = mean(assigned_label(indices)==c2);\n    end\n    disp([gn{c} ' error: ' num2str(mean(assigned_label(indices)~=c))]);\nend\ndisp('Confusion Matrix: ');\ndisp(num2str(conf_matrix));\ndisp(['total error: ' num2str(mean(assigned_label~=gid))]);\n\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/boosting/train_boosted_dt_mc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5739107965765872}}
{"text": "% Kernel Affine Projection Subgradient Method\n%\n% K. Slavakis, S. Theodoridis, and I. Yamada, \"Online kernel-based\n% classification using adaptive projection algorithms,\" IEEE Transactions\n% on Signal Processing, Vol. 56, No. 7, pp. 2781-2796, 2008.\n% http://dx.doi.org/10.1109/TSP.2008.917376\n%\n% Remark: implemented with L2-ball forgetting. Code contributed by\n% Pantelis Bouboulis.\n%\n% This file is part of the Kernel Adaptive Filtering Toolbox for Matlab.\n% https://github.com/steven2358/kafbox/\n\nclassdef kapsm < kernel_adaptive_filter\n    \n    properties (GetAccess = 'public', SetAccess = 'private') % parameters\n        M = 200; % dictionary size\n        Delta = 10; % L2-ball forgetting radius\n        mu = 1.8, % learning rate\n        Q = 10; % number of subgradients\n        loss = 'l2'; % loss function type\n        loss_param = 2; % Huber loss parameter\n        kerneltype = 'gauss'; % kernel type\n        kernelpar = .5; % kernel parameter\n    end\n    \n    properties (GetAccess = 'public', SetAccess = 'private') % variables\n        dict = []; % dictionary\n        alpha = []; % expansion coefficients\n        norm_f = []; % function norm for L2-ball forgetting\n        xmem = []; % input memory\n        ymem = []; % output memory\n    end\n    \n    methods\n        function kaf = kapsm(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.xmem,1)<kaf.Q\n                % grow memory\n                kaf.xmem = [kaf.xmem; x];\n                kaf.ymem = [kaf.ymem; y];\n            else\n                % slide memory\n                kaf.xmem = [kaf.xmem(2:kaf.Q,:); x];\n                kaf.ymem = [kaf.ymem(2:kaf.Q); y];\n            end\n            q = size(kaf.xmem,1);\n            \n            d_hat = kaf.evaluate(kaf.xmem);\n            e = kaf.ymem - d_hat;\n            \n            L_n = kaf.loss_fun(e,kaf.loss,kaf.loss_param);\n            subgrad = kaf.compute_subgrad_coef(e,kaf.loss,kaf.loss_param);\n            norm_subgrad = subgrad.^2 .* ...\n                kernel(kaf.xmem(end-q+1:end,:),...\n                kaf.xmem(end-q+1:end,:),...\n                [kaf.kerneltype '-diag'],kaf.kernelpar);\n            \n            omega = 1/q*ones(q,1); % convex weights\n            \n            beta = omega.*L_n.*subgrad./(norm_subgrad+eps);\n            \n            % % extrapolation parameter\n            % nominator = (omega.*L_n)'*(L_n./(norm_subgrad+eps));\n            % K = kernel(kaf.xmem,kaf.xmem,kaf.kerneltype,kaf.kernelpar);\n            % denominator = beta'*K*beta;\n            % Mn = nominator/(denominator+eps);\n            % mu = .5*Mn;\n            \n            kaf.alpha = [kaf.alpha; 0];\n            kaf.alpha(end-q+1:end) = kaf.alpha(end-q+1:end) - kaf.mu*beta;\n            kaf.dict = [kaf.dict; x];\n            \n            % L2-ball forgetting: update function norm\n            K = kernel(kaf.xmem,kaf.xmem,kaf.kerneltype,kaf.kernelpar);\n            R_sum = beta(end-q+1:end)'*K*beta(end-q+1:end);\n            sum2 = beta(1:end-q)'*d_hat(1:end-q);\n            kaf.norm_f = sqrt(kaf.norm_f*kaf.norm_f + 2*sum2 + R_sum);\n            if kaf.norm_f > kaf.Delta\n                kaf.alpha = kaf.Delta/kaf.norm_f * kaf.alpha;\n                kaf.norm_f = kaf.Delta;\n            end\n            \n            % sliding-window pruning\n            if length(kaf.alpha)>kaf.M\n                k = kernel(kaf.dict,kaf.dict(1,:),...\n                    kaf.kerneltype,kaf.kernelpar);\n                kaf.norm_f = sqrt(kaf.norm_f.^2 + kaf.alpha(1)^2*k(1) - ...\n                    2*kaf.alpha(1)*k'*kaf.alpha);\n                kaf.dict(1,:) = [];\n                kaf.alpha(1) = [];\n            end\n        end\n        \n    end\n    \n    methods (Static = true)\n        \n        function loss = loss_fun(ksi,loss_type,loss_param)\n            switch loss_type\n                case 'l2'\n                    loss = ksi.^2;\n                case 'l1'\n                    loss = abs(ksi);\n                case 'huber'\n                    sigma = loss_param;\n                    loss = zeros(length(ksi),1);\n                    for i=1:length(ksi)\n                        if abs(ksi(i)) <= sigma\n                            loss(i) = ksi(i)^2/(2*sigma);\n                        else\n                            loss(i) = abs(ksi(i)) - sigma/2;\n                        end\n                    end\n            end\n        end\n        \n        function subgrad_coef = ...\n                compute_subgrad_coef(e,loss_type,loss_param)\n            subgrad_coef = zeros(length(e),1);\n            for i=1:length(e)\n                switch loss_type\n                    case 'l2'\n                        subgrad_coef(i) = -2*e(i);\n                    case 'l1'\n                        subgrad_coef(i) = -sign(e(i));\n                    case 'huber'\n                        sigma = loss_param;\n                        if abs(e(i)) <= sigma\n                            subgrad_coef(i) = -e(i)/sigma;\n                        else\n                            subgrad_coef(i) = -sign(e(i));\n                        end\n                end\n            end\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/kapsm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5739107887137936}}
{"text": "function value = r8_mach ( i )\n\n%*****************************************************************************80\n%\n%% R8_MACH returns double precision real machine constants.\n%\n%  Discussion:\n%\n%    Assume that double precision real numbers are stored with a mantissa\n%    of T digits in base B, with an exponent whose value must lie\n%    between EMIN and EMAX.  Then for values of I between 1 and 5,\n%    D1MACH will return the following values:\n%\n%      D1MACH(1) = B^(EMIN-1), the smallest positive magnitude.\n%      D1MACH(2) = B^EMAX*(1-B^(-T)), the largest magnitude.\n%      D1MACH(3) = B^(-T), the smallest relative spacing.\n%      D1MACH(4) = B^(1-T), the largest relative spacing.\n%      D1MACH(5) = log10(B)\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 April 2007\n%\n%  Author:\n%\n%    Original FORTRAN77 version by Phyllis Fox, Andrew Hall, Norman Schryer\n%    MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Phyllis Fox, Andrew Hall, Norman Schryer,\n%    Algorithm 528,\n%    Framework for a Portable Library,\n%    ACM Transactions on Mathematical Software,\n%    Volume 4, Number 2, June 1978, page 176-188.\n%\n%  Parameters:\n%\n%    Input, integer I, chooses the parameter to be returned.\n%    1 <= I <= 5.\n%\n%    Output, real VALUE, the value of the chosen parameter.\n%\n  if ( i < 1 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8_MACH - Fatal error!\\n' );\n    fprintf ( 1, '  The input argument I is out of bounds.\\n' );\n    fprintf ( 1, '  Legal values satisfy 1 <= I <= 5.\\n' );\n    fprintf ( 1, '  I = %d\\n', i );\n    value = 0.0;\n    error ( 'R8_MACH - Fatal error!' );\n  elseif ( i == 1 )\n    value = 1.112536929253601E-308;\n  elseif ( i == 2 )\n    value = 4.494232837155789E+307;\n  elseif ( i == 3 )\n    value = 1.110223024625157E-016;\n  elseif ( i == 4 )\n    value = 2.220446049250313E-016;\n  elseif ( i == 5 )\n    value = 0.301029995663981;\n  elseif ( 5 < i )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8_MACH - Fatal error!\\n' );\n    fprintf ( 1, '  The input argument I is out of bounds.\\n' );\n    fprintf ( 1, '  Legal values satisfy 1 <= I <= 5.\\n' );\n    fprintf ( 1, '  I = %d\\n', i );\n    value = 0.0;\n    error ( 'R8_MACH - 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/test_interp_nd/r8_mach.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5738407579892812}}
{"text": "function c = c8mat_add ( m, n, alpha, a, beta, b )\n\n%*****************************************************************************80\n%\n%% C8MAT_ADD combines two C8MAT's with scalar factors.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 March 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer M, N, the order of A.\n%\n%    Input, complex ALPHA, the first scale factor.\n%\n%    Input, complex A(M,N), the first matrix.\n%\n%    Input, complex BETA, the second scale factor.\n%\n%    Input, complex B(M,N), the second matrix.\n%\n%    Output, complex C(M,N), the result.\n%\n  c(1:m,1:n) = alpha * a(1:m,1:n) + beta * b(1:m,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/c8lib/c8mat_add.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.5738407493063276}}
{"text": "classdef TestPlotLargeCylinderTethaedra < handle\n                                     \n    properties (Access = private)\n        backgroundMesh\n        boundaryMesh\n        levelSet\n        unfittedMesh\n    end\n    \n    methods (Access = public)\n        \n        function obj = TestPlotLargeCylinderTethaedra() \n            obj.createBackgroundMesh();\n            obj.createBoundaryMesh();\n            obj.createLevelSet();\n            obj.createUnfittedMesh();\n            obj.plotUnfittedMesh();\n        end\n        \n    end\n    \n    methods (Access = private)\n\n        function createBackgroundMesh(obj)\n            x = linspace(0,1,10);\n            y = linspace(0,1,10);\n            z = linspace(0,2,20);\n            [X,Y,Z] = meshgrid(x,y,z);   \n            coord  = [X(:) Y(:) Z(:)];\n            d = delaunayTriangulation(coord);\n            s.connec = d.ConnectivityList;\n            s.coord  = coord;\n            obj.backgroundMesh = Mesh(s);            \n        end\n        \n        function createBoundaryMesh(obj)\n            s.backgroundMesh = obj.backgroundMesh;\n            s.dimension = 1:obj.backgroundMesh.ndim;\n            bC = BoundaryMeshCreatorFromRectangularBox(s);\n            bM = bC.create();   \n            obj.boundaryMesh = bM;\n        end        \n        \n        function createLevelSet(obj)\n            s.type = 'cylinder';\n            s.fracRadius = 1.1;\n            s.coord      = obj.backgroundMesh.coord;\n            s.ndim       = obj.backgroundMesh.ndim;\n            lsCreator = LevelSetCreator.create(s);\n            obj.levelSet = lsCreator.getValue();            \n        end        \n        \n        function createUnfittedMesh(obj)\n            s.backgroundMesh = obj.backgroundMesh;\n            s.boundaryMesh   = obj.boundaryMesh;\n            uM = UnfittedMesh(s);            \n            uM.compute(obj.levelSet);     \n            obj.unfittedMesh = uM;\n        end\n        \n        function plotUnfittedMesh(obj) \n            figure();\n            obj.unfittedMesh.plot();\n            view([1 1 1])            \n        end\n        \n    end\nend\n\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/tests/Source/PlottingTests/TestPlotLargeCylinderTethaedra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5737971785722937}}
{"text": "function [hd_record]=mahdecomp(beta_gibbs,delta_gibbs,D_record,strshocks_record,It,Bu,Y,X,Z,n,m,p,k1,k3,T)\n\n\n% function [hd_record]=mahdecomp(beta_gibbs,delta_gibbs,sigma_gibbs,D_record,It,Bu,Y,X,Z,n,m,p,k1,k3,T)\n% performs algortihm 3.2.1, and returns posterior draws from the historical decomposition of the data sample\n% inputs:  - matrix 'beta_gibbs': the matrix recording the post-burn draws of beta\n%          - matrix 'delta_gibbs': the matrix recording the post-burn draws of delta\n%          - matrix 'D_record': the matrix recording the simulated values of the D matrix\n%          - integer 'It': the total number of iterations run by the Gibbs sampler\n%          - integer 'Bu': the number of initial iterations discared as burn-in sample\n%          - matrix 'Y': the matrix of endogenous variables, defined in (3.5.10)\n%          - matrix 'X': the matrix of endogenous regressors, defined in (3.5.10)\n%          - matrix 'Z': the matrix of exogenous regressors, defined in (3.5.10)\n%          - integer 'n': the number of endogenous variables in the model\n%          - integer 'm': the number of exogenous variables in the model\n%          - integer 'p': the number of lags in the model\n%          - integer 'k1': the number of coefficients related to the endogenous variables for each equation in the model\n%          - integer 'k3': the number of coefficients related to the exogenous variables for each equation, in the reformulated model (3.5.5)\n%          - integer 'T': the sample size, i.e. the number of time periods used to estimate the model\n% outputs: - cell 'hd_record': the cell array containing records of simulated  hisotrical decompositions\n\n\n\n% this function implements algorithm 3.2.1, adapted to the mean-adjusted VAR model\n\n\n\n% preliminary tasks\n% first create the hd_record and temp cells\nhd_record=cell(n,n+1);\ntemp=cell(n,2);\n\n\n\n% then initiate the Gibbs algorithm\nfor ii=1:It-Bu\n\n\n% step 2: recover parameters\nbeta=beta_gibbs(:,ii);\nB=reshape(beta,k1,n);\ndelta=delta_gibbs(:,ii);\nDelta=reshape(delta,k3,n);\nD=reshape(D_record(:,ii),n,n);\n\n\n% step 3: obtain irfs and orthogonalised irfs\n[~,ortirfmatrix]=bear.mairfsim(B,D,p,n,T);\n\n\n% step 5: compute the historical contribution of each shock\n   % fill the Yhd matrices\n   % loop over rows of temp\n   for jj=1:n\n      % loop over columns of temp\n      for kk=1:n\n      % create the virf and vshocks vectors (shocks correspond to step 4)\n         for ll=1:T\n         virf(ll,1)=ortirfmatrix(jj,kk,ll);\n         end\n      vshocks=strshocks_record{kk,1}(ii,:)';\n         % loop over sample periods\n         for ll=1:T\n         hd_record{jj,kk}(ii,ll)=virf(1:ll,1)'*flipud(vshocks(1:ll,1));\n         end\n      end\n   end\n\n\n% then go for next Gibbs iteration\nend\n\n\n\n\n% step 6: compute the contributions of deterministic variables\n% loop over rows of temp/hd_record\nfor ii=1:n\n% fill the Ytot matrix in temp\n% initial condition\ntemp{ii,1}=hd_record{ii,1};\n   % sum over the remaining columns of hd_record\n   for jj=2:n\n   temp{ii,1}=temp{ii,1}+hd_record{ii,jj};\n   end\n% fill the Y matrix in temp\ntemp{ii,2}=repmat(Y(:,ii)',It-Bu,1);\n% fill the Yd matrix in hd_record\nhd_record{ii,n+1}=temp{ii,2}-temp{ii,1};\n% go for next variable\nend\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/unreachableCode_ToRemove/mahdecomp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5737971785722937}}
{"text": "function [y, s2, fmu, fs2] = simulGPnaive(hyp, inf, mean, cov, lik, input, target, test, lag) \n% simulGPnaive - 'Naive' (i.e. without propagation of variance) simulation of the GP\n% ARX and AR model.\n%\n%% Syntax\n%   [y, s2] = simulGPnaive(hyp, inf, mean, cov, lik, input, target, test, lag) \n%\n%% Description\n% GP-NARX model is used to predict a further step ahead by replacing the data at \n% present time instant with the data at one time instant before and using the mean \n% value of prediction from the previous prediction step instead of the measured \n% output value. This is then repeated as many times as there are test samples.\n%\n% Input:\n% * hyp    ... the column vector of hyperparameters\n% * inf    ... the function specifying the inference method\n% * cov    ... the prior covariance function (see below)\n% * mean   ... the prior mean function\n% * lik    ... the likelihood function\n% * input  ... the input part of the training data,  NxD matrix\n% * target ... the output part of the training data (ie. target), Nx1 vector \n% * test   ... the input matrix, kxD matrix, see construct.m for more info \n% * lag    ... the order of the model (number of used lagged outputs) \n% \n% Output:\n% * y    ... the mean predicted output \n% * s2   ... associated variances\n% * fmu  ... the mean predicted output without noise\n% * fs2  ... associated variances without noise\n%\n% See also: \n% gpx.m, simulGPmc, construct.m\n%\n% Examples: \n% demo_example_gp_simulation.m\n%\n%% \n% Written by K. Azman in J. Kocijan, 2007\n\n[NN,D] = size(test); % D - input space dimension, NN - number or test samples\n\n% allocate memory\ny = zeros(1,D);\ns2 = y;\nfmu = y;\nfs2 = y;\n\n% first step: k=1\nxt = test(1,:);\n[y(1), s2(1) ,fmu(1), fs2(1), post] = gpx(hyp, inf, mean, cov, lik, input, target, xt);\n\n% future steps ... \nfor k=2:NN\n    \n    if (mod(k,100) == 0)  % remark on every 100th step\n        disp(['simulGPnaive, step: ', int2str(k), '/', int2str(NN)]);\n    end\n        % For the next prediction prepare the input vector ...\n        if D > lag\n            if (k>lag)\n                xt = [y(k-lag:k-1) test(k, lag+1:end)];\n            elseif (k<=lag)\n                xt = [test(k, 1:lag-k+1) y(1:k-1) test(k, lag+1:end)];\n            end\n        else                                            % if D <= lag\n            if (k>lag)\n                xt = y(k-lag:k-1);\n            elseif (k<=lag)\n                xt = [test(k, 1:lag-k+1) y(1:k-1)];\n            end\n        end\n        % ... and calculate the one-step-ahead prediction\n    [y(k), s2(k) ,fmu(k), fs2(k), post] = gpx(hyp, inf, mean, cov, lik, input, target, xt, post);\n    \nend\n\n\n% transform into column vectors \ny = y'; \ns2 = s2'; \nfmu = fmu';\nfs2 = fs2';\n", "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-gp-evaluation/simulGPnaive.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5737971785722937}}
{"text": "function [V,E,I] = spline_to_poly(P,C,tol)\n  % SPLINE_TO_POLY Evaluate a cubic Bezier spline as a polyline where each\n  % segment corresponds to a locally flat segment of the curve up to given\n  % tolerance\n  % \n  % [V,E] = spline_to_poly(P,C,tol)\n  % \n  % Inputs:\n  %   P  #P by dim list of control point locations\n  %   C  #C by 4 list of indices into P of cubic Bezier curves\n  %   tol  tolerance \n  % Outputs:\n  %   V  #V by dim list of vertex locations\n  %   E  #E by dim list of edge indices into V\n  %   I  #E list of indices into 1:#C\n  %\n\n  V = P;\n  E = [];\n  I = [];\n  % consider each cubic\n  for c = 1:size(C,1)\n    Pc = cubic_flat_eval(P(C(c,:),:),tol);\n    J = [C(c,1) size(V,1)+(1:size(Pc,1)-2) C(c,4)];\n    Ec = [J(1:end-1);J(2:end)]';\n    E = [E; Ec];\n    V = [V;Pc(2:end-1,:)];\n    I = [I;repmat(c,size(Ec,1),1)];\n  end\n  [V,~,~,E] = remove_unreferenced(V,E);\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/spline_to_poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5737971771045203}}
{"text": "classdef CantileverBeamMeshCreator < handle\n    \n    properties (Access = public)\n        connec\n        coords\n    end\n    \n    properties (Access = private)\n        dim\n        length\n        height\n    end\n    \n    methods (Access = public)\n        \n        function obj = CantileverBeamMeshCreator(cParams)\n            obj.init(cParams)\n        end\n\n        function mesh = create(obj, xdiv, ydiv)\n            switch obj.dim\n                case '2D'\n                    mesh = obj.create2Dcantilever(xdiv, ydiv);\n                case '3D'\n                    mesh = obj.create3Dcantilever(xdiv, ydiv);\n            end\n        end\n        \n    end\n    \n    methods (Access = private)\n        \n        function init(obj,cParams)\n            obj.dim    = cParams.dim;\n            obj.length = cParams.length;\n            obj.height = cParams.height;\n        end\n\n        function mesh = create2Dcantilever(obj, xdiv, ydiv)\n            obj.computeCoords2D(xdiv, ydiv);\n            obj.computeConnec2D(xdiv, ydiv);\n            mesh = obj.createMesh();\n        end\n\n        function mesh = create3Dcantilever(obj, xdiv, ydiv)\n            obj.computeCoords3D(xdiv, ydiv);\n            obj.computeConnec3D(xdiv, ydiv);\n            mesh = obj.createMesh();\n        end\n\n        function coords = computeCoords2D(obj, xdiv, ydiv)\n            x = linspace(0, obj.length, xdiv+1);\n            y = linspace(0, obj.height, ydiv+1);\n            [X,Y,Z] = meshgrid(x,y,0);\n            fvc = surf2patch(X,Y,Z,'triangles');\n            fvc.vertices(:,3) = []; % 2D\n            coords = fvc.vertices;\n            obj.coords = coords;\n        end\n\n        function computeConnec2D(obj, xdiv, ydiv)\n            conn = [];\n            for j = 0:1:xdiv-1\n                for i = 1:1:ydiv\n                    node1 = j*(ydiv+1) + i;\n                    node2 = node1 + 1;\n                    node3 = node1 + (ydiv+1);\n                    node4 = node2 + (ydiv+1);\n                    elem = [node1, node2, node4, node3];\n                    conn = [conn; elem];\n                end\n            end\n            obj.connec = conn;\n        end\n\n        function computeCoords3D(obj, xdiv, ydiv)\n            x = linspace(0, obj.length,    xdiv+1);\n            y = linspace(0, obj.height, ydiv+1);\n            z = linspace(0, obj.height, ydiv+1);\n            [X,Y,Z] = meshgrid(x,y,z);\n            npnod = size(X,1)*size(X,2)*size(X,3);\n            Xr = reshape(X, npnod,1);\n            Yr = reshape(Y, npnod,1);\n            Zr = reshape(Z, npnod,1);\n            coor = [Xr, Yr, Zr];\n            obj.coords = coor;\n        end\n\n        function computeConnec3D(obj, xdiv, ydiv)\n            conn = [];\n%             for z = 0:1:ydiv-1\n%                 for j = 0:1:ydiv-1\n%                     for i = 1:1:xdiv\n%                         addZ = (xdiv+1)*(ydiv+1)*z;\n%                         addZ1 = (xdiv+1)*(ydiv+1)*(z+1);\n%                         node1 = j*(xdiv+1)+i + addZ;\n%                         node2 = j*(xdiv+1)+i+1 + addZ;\n%                         node3 = (j+1)*(xdiv+1)+i + addZ;\n%                         node4 = (j+1)*(xdiv+1)+i+1 + addZ;\n%                         node5 = j*(xdiv+1)+i + addZ1;\n%                         node6 = j*(xdiv+1)+i+1 + addZ1;\n%                         node7 = (j+1)*(xdiv+1)+i + addZ1;\n%                         node8 = (j+1)*(xdiv+1)+i+1 + addZ1;\n%                         elem = [node1, node2, node3, node4, ...\n%                                 node5, node6, node7, node8];\n%                         conn = [conn; elem];\n%                     end\n%                 end\n%             end\n            for z = 0:1:ydiv\n                for j = 0:1:xdiv-1\n                    for i = 1:1:ydiv\n                        addZ  = (xdiv+1)*(ydiv+1)*z;\n                        node1 = j*(ydiv+1) + i;\n                        node2 = node1 + 1;\n                        node3 = node1 + (ydiv+1);\n                        node4 = node2 + (ydiv+1);\n                        node5 = j*(ydiv+1) + i + addZ;\n                        node6 = node5 + 1;\n                        node7 = node5 + (ydiv+1);\n                        node8 = node6 + (ydiv+1);\n                        elem = [node1, node2, node4, node3, ...\n                                node5, node6, node7, node8];\n                        conn = [conn; elem];\n                    end\n                end\n            end\n            obj.connec = conn;\n        end\n\n        function mesh = createMesh(obj)\n            m.coord  = obj.coords;\n            m.connec = obj.connec;\n            mesh = Mesh(m);\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/tests/Source/PerformanceTests/CantileverBeamMeshCreator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5737971736513235}}
{"text": "function [inputImageFiltered, additionalOutput] = fftImage(inputImage,varargin)\n\t% Computes FFT on input image.\n\t% Biafra Ahanonu\n\t% started: 2013.11.09\n\t% inputs\n\t\t% inputImage - [x y] matrix\n\t% outputs\n\t\t% inputImageFiltered - [x y] matrix\n\t% example\n\t\t% test the lowpass and highpass on an image with a range of options\n\t\t% f = fftImage(frame,'runfftTest',1,'bandpassType','lowpass');\n\t\t% f = fftImage(frame,'runfftTest',1,'bandpassType','highpass');\n\n\n\t[inputImageFiltered, additionalOutput] = ciapkg.image.fftImage(inputImage,'passArgs', varargin);\nend", "meta": {"author": "bahanonu", "repo": "ciatah", "sha": "f25f27660d985795ccb1012a799ab7e0d7afc596", "save_path": "github-repos/MATLAB/bahanonu-ciatah", "path": "github-repos/MATLAB/bahanonu-ciatah/ciatah-f25f27660d985795ccb1012a799ab7e0d7afc596/+ciapkg/+api/fftImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5737971719247246}}
{"text": "function [x] = qdToState(qd)\n% Converts state vector for simulation to qd struct used in hardware.\n% x is 1 x 13 vector of state variables [pos vel quat omega]\n% qd is a struct including the fields pos, vel, euler, and omega\n\nx = zeros(1,13); %initialize dimensions\n\nx(1:3) = qd.pos;\nx(4:6) = qd.vel;\n\nRot = RPYtoRot_ZXY(qd.euler(1), qd.euler(2), qd.euler(3));\nquat = RotToQuat(Rot);\n\nx(7:10) = quat;\nx(11:13) = qd.omega;\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/qdToState.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5737911585411188}}
{"text": "function [ qy, qty, b, rsd, xb, info ] = zqrsl ( x, ldx, n, k, qraux, y, job )\n\n%*****************************************************************************80\n%\n%% ZQRSL solves, transforms or projects systems factored by ZQRDC.\n%\n%  Discussion:\n%\n%    The routine applies the output of ZQRDC to compute coordinate\n%    transformations, projections, and least squares solutions.\n%\n%    For K <= min ( N, P ), let XK be the matrix\n%\n%      XK = ( X(IPVT(1)), X(IPVT(2)), ... ,X(IPVT(k)) )\n%\n%    formed from columnns IPVT(1), ... ,IPVT(K) of the original\n%    N by P matrix X that was input to ZQRDC (if no pivoting was\n%    done, XK consists of the first K columns of X in their\n%    original order).  ZQRDC produces a factored unitary matrix Q\n%    and an upper triangular matrix R such that\n%\n%      XK = Q * ( R )\n%               ( 0 )\n%\n%    This information is contained in coded form in the arrays\n%    X and QRAUX.\n%\n%    The parameters QY, QTY, B, RSD, and XB are not referenced\n%    if their computation is not requested and in this case\n%    can be replaced by dummy variables in the calling program.\n%\n%    To save storage, the user may in some cases use the same\n%    array for different parameters in the calling sequence.  A\n%    frequently occuring example is when one wishes to compute\n%    any of B, RSD, or XB and does not need Y or QTY.  In this\n%    case one may identify Y, QTY, and one of B, RSD, or XB, while\n%    providing separate arrays for anything else that is to be\n%    computed.  Thus the calling sequence\n%\n%      call zqrsl ( x, ldx, n, k, qraux, y, dum, y, b, y, dum, 110, info )\n%\n%    will result in the computation of B and RSD, with RSD\n%    overwriting Y.  More generally, each item in the following\n%    list contains groups of permissible identifications for\n%    a single callinng sequence.\n%\n%    1. ( Y, QTY, B )   ( RSD )      ( XB )  ( QY )\n%    2. ( Y, QTY, RSD ) ( B )        ( XB )  ( QY )\n%    3. ( Y, QTY, XB )  ( B )        ( RSD ) ( QY )\n%    4. ( Y, QY )       ( QTY, B )   ( RSD ) ( XB )\n%    5. ( Y, QY )       ( QTY, RSD ) ( B )   ( XB )\n%    6. ( Y, QY )       ( QTY, XB )  ( B )   ( RSD )\n%\n%    In any group the value returned in the array allocated to\n%    the group corresponds to the last member of the group.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 May 2007\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, complex X(LDX,P), the output of ZQRDC.\n%\n%    Input, integer LDX, the leading dimension of X.\n%\n%    Input, integer N, the number of rows of the matrix XK, which\n%    must have the same value as N in ZQRDC.\n%\n%    Input, integer K, the number of columns of the matrix XK.  K must not\n%    be greater than min ( N, P), where P is the same as in the calling\n%    sequence to ZQRDC.\n%\n%    Input, complex QRAUX(P), the auxiliary output from ZQRDC.\n%\n%    Input, complex Y(N), a vector that is to be manipulated by ZQRSL.\n%\n%    Input, integer JOB, specifies what is to be computed.  JOB has\n%    the decimal expansion ABCDE, meaning:\n%    if A /= 0, compute QY.\n%    if B, D, D, or E /= 0, compute QTY.\n%    if C /= 0, compute B.\n%    if D /= 0, compute RSD.\n%    if E /= 0, compute XB.\n%    A request to compute B, RSD, or XB automatically triggers the\n%    computation of QTY, for which an array must be provided in the\n%    calling sequence.\n%\n%    Output, complex QY(N), contains Q*Y, if it has been requested.\n%\n%    Output, complex QTY(N), contains hermitian(Q)*Y, if it has\n%    been requested.  Here hermitian(Q) is the conjugate transpose\n%    of the matrix Q.\n%\n%    Output, complex B(K), the solution of the least squares problem\n%      minimize norm2 ( Y - XK * B ),\n%    if it has been requested.  If pivoting was requested in ZQRDC,\n%    the J-th component of B will be associated with column IPVT(J)\n%    of the original matrix X that was input into ZQRDC.\n%\n%    Output, complex RSD(N), the least squares residual Y - XK*B,\n%    if it has been requested.  RSD is also the orthogonal projection\n%    of Y onto the orthogonal complement of the column space of XK.\n%\n%    Output, complex XB(N), the least squares approximation XK*N,\n%    if its computation has been requested.  XB is also the orthogonal\n%    projection of Y onto the column space of X.\n%\n%    Output, integer INFO, is zero unless the computation of B has\n%    been requested and R is exactly singular.  In this case, INFO is the\n%    index of the first zero diagonal element of R and B is left unaltered.\n%\n  qy = [];\n  qty = [];\n  b = [];\n  rsd = [];\n  xb = [];\n  info = 0;\n%\n%  Determine what is to be computed.\n%\n  cqy =  ( floor (       job / 10000        ) ~= 0 );\n  cqty = (         mod ( job,  10000 )        ~= 0 );\n  cb =   ( floor ( mod ( job,   1000 ) /100 ) ~= 0 );\n  cr =   ( floor ( mod ( job,    100 ) / 10 ) ~= 0 );\n  cxb =  (         mod ( job,     10 )        ~= 0 );\n\n  ju = min ( k, n - 1 );\n%\n%  Special action when N=1.\n%\n  if ( ju == 0 )\n\n    if ( cqy )\n      qy(1) = y(1);\n    end\n\n    if ( cqty )\n      qty(1) = y(1);\n    end\n\n    if ( cxb )\n      xb(1) = y(1);\n    end\n\n    if ( cb )\n      if ( zabs1 ( x(1,1) ) == 0.0 )\n        info = 1;\n      else\n        b(1) = y(1) / x(1,1);\n      end\n    end\n\n    if ( cr )\n      rsd(1) = 0.0;\n    end\n\n    return\n\n  end\n%\n%  Set up to compute QY or QTY.\n%\n  if ( cqy )\n    qy(1:n) = y(1:n);\n  end\n\n  if ( cqty )\n    qty(1:n) = y(1:n);\n  end\n%\n%  Compute QY.\n%\n  if ( cqy )\n\n    for jj = 1 : ju\n\n      j = ju - jj + 1;\n\n      if ( zabs1 ( qraux(j) ) ~= 0.0 )\n        temp = x(j,j);\n        x(j,j) = qraux(j);\n        t = - ( qy(j:n) * conj ( x(j:n,j) ) ) / x(j,j);\n        qy(j:n) = qy(j:n) + t * transpose ( x(j:n,j) );\n        x(j,j) = temp;\n      end\n\n    end\n\n  end\n%\n%  Compute hermitian ( A ) * Y.\n%\n  if ( cqty )\n    for j = 1 : ju\n      if ( zabs1 ( qraux(j) ) ~= 0.0 )\n        temp = x(j,j);\n        x(j,j) = qraux(j);\n        t = - ( qty(j:n) * conj ( x(j:n,j) ) ) / x(j,j);\n        qty(j:n) = qty(j:n) + t * x(j:n,j);\n        x(j,j) = temp;\n      end\n    end\n  end\n%\n%  Set up to compute B, RSD, or XB.\n%\n  if ( cb )\n    b(1:k) = qty(1:k);\n  end\n\n  kp1 = k + 1;\n\n  if ( cxb )\n    xb(1:k) = qty(1:k);\n  end\n\n  if ( cr & k < n )\n    rsd(k+1:n) = qty(k+1:n);\n  end\n\n  if ( cxb )\n    xb(k+1:n) = 0.0;\n  end\n\n  if ( cr )\n    rsd(1:k) = 0.0;\n  end\n%\n%  Compute B.\n%\n  if ( cb )\n\n    for jj = 1 : k\n\n      j = k - jj + 1;\n\n      if ( zabs1 ( x(j,j) ) == 0.0 )\n        info = j;\n        break\n      end\n\n      b(j) = b(j) / x(j,j);\n\n      if ( j ~= 1 )\n        t = -b(j);\n        b(1:j-1) = b(1:j-1) + t * x(1:j-1,j);\n      end\n\n    end\n\n  end\n\n  if ( cr | cxb )\n%\n%  Compute RSD or XB as required.\n%\n    for jj = 1 : ju\n\n      j = ju - jj + 1;\n\n      if ( zabs1 ( qraux(j) ) ~= 0.0 )\n\n        temp = x(j,j);\n        x(j,j) = qraux(j);\n\n        if ( cr )\n          t = - ( rsd(j:n) * conj ( x(j:n,j) ) ) / x(j,j);\n          rsd(j:n) = rsd(j:n) + t * x(j:n,j);\n        end\n\n        if ( cxb )\n          t = - ( xb(j:n) * conj ( x(j:n,j) ) ) / x(j,j);\n          xb(j:n) = xb(j:n) + t * x(j:n,j);\n        end\n\n        x(j,j) = temp;\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/linpack_z/zqrsl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5737911577368151}}
{"text": "function [centers,mincenter,mindist,q2,quality] = kmeansFast(data,initcenters,method)\n% output: final centers\n% input: data points and initial centers\n% if initcenters is a number k, create k centers and start with these\n% otherwise, use centers given as input\n% method = 0: unoptimized, using n by k matrix of distances O(nk) space\n%          1: vectorized, using only O(n+k) space\n%          2: like 1, in addition using distance inequalities (default)\n% URL: http://cseweb.ucsd.edu/~elkan/fastkmeans.html\n\ntic\nif nargin < 3 method = 2; end\n[n,dim] = size(data);\n\nif max(size(initcenters)) == 1\n    k = initcenters;\n    [centers, mincenter, mindist, lower, computed] = anchors(mean(data),k,data);\n    total = computed;\n    skipestep = 1;\nelse \n    centers = initcenters;\n    mincenter = zeros(n,1);\n    total = 0;\n    skipestep = 0;\n    [k,dim2] = size(centers);    \n    if dim ~= dim2 error('dim(data) ~= dim(centers)'); end;\nend\n\nnchanged = n;\niteration = 0;\noldmincenter = zeros(n,1);\n\nwhile nchanged > 0\n    % do one E step, then one M step\n    computed = 0;\n    \n    if method == 0 && ~skipestep\n        for i = 1:n\n            for j = 1:k\n                distmat(i,j) = calcdist(data(i,:),centers(j,:));\n            end\n        end\n        [mindist,mincenter] = min(distmat,[],2);\n        computed = k*n;\n\n    elseif (method == 1 || (method == 2 && iteration == 0)) && ~skipestep\n        mindist = Inf*ones(n,1);\n        lower = zeros(n,k);\n        for j = 1:k\n           jdist = calcdist(data,centers(j,:));\n           lower(:,j) = jdist;\n           track = find(jdist < mindist);\n           mindist(track) = jdist(track);\n           mincenter(track) = j;\n        end\n        computed = k*n;\n\n    elseif method == 2 && ~skipestep \n        computed = 0;\n\n% for each center, nndist is half the distance to the nearest center\n% if d(x,center) < nndist then x cannot belong to any other center\n% mindist is an upper bound on the distance of each point to its nearest center\n\n        nndist = min(centdist,[],2);\n% the following usually is not faster        \n%        ldist = min(lower,[],2);\n%        mobile = find(mindist > max(nndist(mincenter),ldist));\n        mobile = find(mindist > nndist(mincenter));\n        \n% recompute distances for point i and center j \n%       only if j can possibly be the new nearest center\n% for speed, the first check has been optimized by modifying centdist\n% swapping the order of the checks is slower for data with natural clusters\n\n        mdm = mindist(mobile);\n        mcm = mincenter(mobile);\n \n        for j = 1:k\n% the following is incorrect: for j = unique(mcm)'\n            track = find(mdm > centdist(mcm,j));\n            if isempty(track) continue; end\n            alt = find(mdm(track) > lower(mobile(track),j));          \n            if isempty(alt) continue; end\n            track1 = mobile(track(alt));\n                    \n% calculate exact distances to the mincenter\n% recalculate separately for each jj to avoid copying too much of data\n% redo may be empty, but we don't need to check this\n            redo = find(~recalculated(track1));\n            redo = track1(redo);\n            c = mincenter(redo);\n            computed = computed + size(redo,1);\n            for jj = unique(c)'\n                rp = redo(find(c == jj));\n                udist = calcdist(data(rp,:),centers(jj,:));\n                lower(rp,jj) = udist;\n                mindist(rp) = udist;\n            end\n            recalculated(redo) = 1;\n            \n            track2 = find(mindist(track1) > centdist(mincenter(track1),j));\n            track1 = track1(track2);\n            if isempty(track1) continue; end\n           \n            % calculate exact distances to center j\n            track4 = find(lower(track1,j) < mindist(track1));\n            if isempty(track4) continue; end\n            track5 = track1(track4);\n            jdist = calcdist(data(track5,:),centers(j,:));\n            computed = computed + size(track5,1);\n            lower(track5,j) = jdist;\n                    \n            % find which points really are assigned to center j\n            track2 = find(jdist < mindist(track5));\n            track3 = track5(track2);\n            mindist(track3) = jdist(track2);\n            mincenter(track3) = j;\n        end % for j=1:k\n    end % if method\n      \n    oldcenters = centers;\n        \n% M step: recalculate the means for each cluster\n% if a cluster is empty, its mean is left unchanged\n% we minimize computations for clusters with little changed membership\n    \n    diff = find(mincenter ~= oldmincenter);\n    diffj = unique([mincenter(diff);oldmincenter(diff)])';\n    diffj = diffj(diffj > 0);\n    \n    if size(diff,1) < n/3 && iteration > 0\n         for j = diffj\n            plus = find(mincenter(diff) == j);\n            minus = find(oldmincenter(diff) == j);\n            oldpop = pop(j);\n            pop(j) = pop(j) + size(plus,1) - size(minus,1);\n            if pop(j) == 0 continue; end\n            centers(j,:) = (centers(j,:)*oldpop + sum(data(diff(plus),:),1) - sum(data(diff(minus),:),1))/pop(j); \n        end\n    else\n        for j = diffj\n            track = find(mincenter == j);\n            pop(j) = size(track,1);\n            if pop(j) == 0 continue; end\n% it's correct to have mean(data(track,:),1) but this can make answer worse!\n            centers(j,:) = mean(data(track,:),1);\n        end\n    end\n    \n    if method == 2\n        for j = diffj\n            offset = calcdist(centers(j,:),oldcenters(j,:));\n            computed = computed + 1;\n            if offset == 0 continue; end\n            track = find(mincenter == j);\n            mindist(track) = mindist(track) + offset;\n            lower(:,j) = max(lower(:,j) - offset,0);\n        end\n\n% compute distance between each pair of centers\n% modify centdist to make \"find\" using it faster\n        recalculated = zeros(n,1);\n        realdist = alldist(centers);\n        centdist = 0.5*realdist + diag(Inf*ones(k,1));\n        computed = computed + k + k*(k-1)/2;   \n    end\n    \n    nchanged = size(diff,1) + skipestep;\n    iteration = iteration+1;\n    skipestep = 0;\n    oldmincenter = mincenter;\n\n%   difference = max(max(abs(oldcenters - centers)));\n%   [iteration toc nchanged computed size(diffj,2)]\n    %[iteration toc nchanged computed]\n    total = total + computed;\nend % while nchanged > 0\n\nudist = calcdist(data,centers(mincenter,:));\nquality = mean(udist);\nq2 = mean(udist.^2);\n%[iteration toc quality q2 total]\n", "meta": {"author": "adikhosla", "repo": "feature-extraction", "sha": "290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8", "save_path": "github-repos/MATLAB/adikhosla-feature-extraction", "path": "github-repos/MATLAB/adikhosla-feature-extraction/feature-extraction-290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8/util/kmeansFast/kmeansFast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5737911517333046}}
{"text": "function s = mean(f, dim)\n%MEAN   Average or mean value of a DISKFUN. \n%   MEAN(F) takes the mean in the angular direction (default), i.e., \n%          MEAN(F) = sum(F).\n%\n%   MEAN(F, DIM) takes the mean along the direction DIM. If DIM = 1 it is the\n%   radial direction, and if DIM = 2 then it is the angular direction,\n%   i.e., MEAN(F,2) = 1/(2*pi)*sum(F,2).\n%\n% See also DISKFUN/MEAN2, DISKFUN/STD2.\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    s = chebfun;\n    return\nend \n\nif ( nargin == 1)\n    % Default to the angular direction.\n    dim = 1;    \nend\n\ns = sum(f, dim);\nif ( dim == 1 )\n    return; % Mean in the angular direction (default)\nelseif ( dim == 2 )\n    s = s / (2*pi); % Mean in the radial direction\nelse\n    error('CHEBFUN:DISKFUN:mean:dim', ...\n        'dim must be 1 or 2.')\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/@diskfun/mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5737911457297938}}
{"text": "function [t]=tt_heaviside(n,L,ind)\n% Heaviside vector in the TT format\n% function [t]=tt_heaviside(n,L,ind)\n% Returns the tt_tensor with elements \n%   theta(i-ind), i=1:N, ind=1,...,N, N=prod(n), theta(0)=1.\n%\n% See also: tt_unit, tt_shift\n%\n% TT-Toolbox 2.2, 2009-2012\n%\n%This is TT Toolbox, written by Ivan Oseledets et. al.\n%Institute of Numerical Mathematics, Moscow, Russia\n%webpage: http://spring.inm.ras.ru/osel\n%\n%For all questions, bugs and suggestions please mail\n%ivan.oseledets@gmail.com\n%---------------------------\n\nif (numel(n)==1)\n    n = n*ones(1,L);\nend;\n\nif (numel(ind)==1)\n    ind = tt_ind2sub(reshape(n, 1, []), ind);\nend;\n\nt = cell(L,1);\n\nt{1} = zeros(1,n(1),2);\nt{1}(1,:,1) = heaviside((1:n(1))-ind(1));\nt{1}(1,:,2) = 1;\n\nfor i=2:L-1\n    t{i} = zeros(2,n(i),2);\n    t{i}(1,:,1)=[zeros(ind(i)-1,1); 1; zeros(n(i)-ind(i), 1)];\n    t{i}(2,:,1)=heaviside((1:n(i))-ind(i)-1);\n    t{i}(2,:,2)=1;\nend;\n\nt{L} = zeros(2,n(L),1);\nt{L}(1,:,1)=[zeros(ind(L)-1,1); 1; zeros(n(L)-ind(L), 1)];\nt{L}(2,:,1)=heaviside((1:n(L))-ind(L)-1);\n\nif (L==1)\n    t{1} = sum(t{1}, 1);\nend;\n\nt = cell2core(tt_tensor,t);\nend\n\nfunction [y]=heaviside(x)\n% Heaviside function of a _real_ array\n% function [y]=heaviside(x)\n% Zeroes strictly negative values in x, all others are cast to 1\n\ny = sign(x)+1;\ny(y==1)=2;\ny = y*0.5;\nend", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/core/tt_heaviside.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5737911421391956}}
{"text": "function [model, pca_model] = project_model(model, coeff, k)\n% [model, pcamodel] = project_model(model, coeff, k)\n%\n% Project a model's filters onto the top k PCA eigenvectors\n% stored in the columns of the matrix coeff.  The output\n% variable 'model' holds the original model augmented to\n% hold the PCA filters as extra data.  The output variable\n% 'pcamodel' has its filters replaced with the PCA filters.\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2009-2012 Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\n% take the top k eigenvectors from coeff as the projection matrix\ncoeff = coeff(:, 1:k);\n% augment the projection matrix by adding a vector with all zeros ...\ncoeff = padarray(coeff, [1 1], 0, 'post');\n% ... except in the last position to preserve the occlusion feature\ncoeff(end,end) = 1;\n% save the projection matrix in the model\nmodel.pca_coeff = coeff;\n% Make a new model with projected filters\npca_model = model;\nfor i = 1:model.numfilters\n  bl = model.filters(i).blocklabel;\n  % w is reshaped and appropriately flipped\n  w = model_get_block(model, model.filters(i));\n  w_pca = project(w, coeff);\n  if model.filters(i).flip\n    pca_model.blocks(bl).type      = block_types.PCAFilter;\n    pca_model.blocks(bl).shape(3)  = k+1;\n    pca_model.blocks(bl).w_flipped = w_pca;\n\n    model.blocks(bl).w_pca_flipped = w_pca;\n    model.blocks(bl).w_flipped     = w;\n  else\n    pca_model.blocks(bl).type      = block_types.PCAFilter;\n    pca_model.blocks(bl).shape(3)  = k+1;\n    pca_model.blocks(bl).w         = w_pca;\n\n    model.blocks(bl).w_pca         = w_pca;\n    model.blocks(bl).w             = w;\n  end\n  pca_model.blocks(bl).dim = numel(w_pca);\nend\n", "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/star-cascade/project_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.573791139726283}}
{"text": "function [U,Usteps] = conformalized_mean_curvature_flow(V,F,varargin)\n  % CONFORMALIZED_MEAN_CURVATURE_FLOW Flow a surface according to \"Can mean\n  % curvature flow be made non-singular?\" [Kazhdan et al. 2012]\n  %\n  % Inputs:\n  %   V  #V by dim list of vertex positions\n  %   F  #F by 3 list of triangle indices into V\n  %   Optional:\n  %     'MaxIter' followed by maximum number of iterations {100}\n  %     'MinDiff' followed by minimum difference between iterations {1e-13}\n  %     'Conformalize' followed by whether to rebuild _just_ the mass\n  %       matrix each step {true}\n  %     'delta' followed by delta value, should roughly be in range\n  %       [1e-13,1e13] {1}\n  %     'LaplacianType' followed by 'cotangent' of 'uniform'.\n  %     'V0' followed by #V by 3 mesh positions to treat as initial mesh (to\n  %       build laplacian from)\n  %     'RescaleOutput' followed by whether to scale output to match input\n  %       (otherwise scaled to unit surface area and moved to origin for\n  %       numerical robustness) {false}\n  % Outputs:\n  %   U  #V by dim list of new vertex positions\n  %   Usteps  #V by dim by iterations list of vertex positions during flow\n  %\n  function L = laplacian(V,F)\n    switch laplacian_type\n    case 'cotangent'\n      L = cotmatrix(V,F);\n    case 'uniform'\n      A = adjacency_matrix(F);\n      L = A - diag(sparse(sum(A,2)));\n    end\n  end\n\n  % default values\n  delta = 1;\n  max_iter = 100;\n  laplacian_type = 'cotangent';\n  until_self_intersection_free = false;\n  V0 = V;\n  rescale_output = false;\n  min_diff = 1e-13;\n  conformalize = true;\n  % Map of parameter names to variable names\n  params_to_variables = containers.Map( ...\n    {'MaxIter','Conformalize','delta','LaplacianType','V0', ...\n      'RescaleOutput', 'UntilSelfIntersectionFree','MinDiff'}, ...\n    {'max_iter','conformalize','delta','laplacian_type','V0', ...\n      'rescale_output', 'until_self_intersection_free','min_diff'});\n  v = 1;\n  while v <= numel(varargin)\n    param_name = varargin{v};\n    if isKey(params_to_variables,param_name)\n      assert(v+1<=numel(varargin));\n      v = v+1;\n      % Trick: use feval on anonymous function to use assignin to this workspace \n      feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n    else\n      error('Unsupported parameter: %s',varargin{v});\n    end\n    v=v+1;\n  end\n\n  L = laplacian(V,F);\n\n  switch size(F,2)\n  case 3\n    SF = F;\n  case 4\n    SF = boundary_faces(F);\n  end\n\n  if nargout > 1\n    Usteps = zeros([size(V) max_iter]);\n  end\n  U = V;\n  iter = 1;\n  while true\n    if nargout > 1\n      Usteps(:,:,iter) = U;\n    end\n    if until_self_intersection_free\n      [~,~,IF] = selfintersect(U,SF,'DetectOnly',true,'FirstOnly',true);\n      if isempty(IF)\n        break;\n      end\n    end\n    U_prev = U;\n    % 'full' seems slight more stable than 'barycentric' which is more stable\n    % than 'voronoi'\n    M = massmatrix(U,F,'barycentric');\n    if ~conformalize\n      L = laplacian(V,F);\n    end\n    U = (M-delta(min(iter,end))*L)\\(M*U);\n    area = sum(doublearea(U,SF)*0.5);\n    c = sum(bsxfun(@times,0.5*doublearea(U,SF)/area,barycenter(U,SF)));\n    U = bsxfun(@minus,U,c);\n    U = U/sqrt(area);\n    % Use difference from previous as stopping criterion\n    % Better would be to look for convergence while factoring out M??bius\n    % transformation.\n    % Q: Stop when no change in angles?\n    d = trace(((U-U_prev)'*M*(U-U_prev)).^2);\n    if d < min_diff\n      warning('converged...');\n      break;\n    end\n    % Volume of unit area sphere: pi^-0.5/6\n    %[c,vol] = centroid(U,F);\n    %tsurf(F,U);\n    %%[vol pi^-0.5/6]\n    %title(sprintf('%g',sum(doublearea(U,F)*0.5)));\n    %drawnow;\n    if iter >= max_iter\n      warning('Max iterations (%d) exceeded without convergence',max_iter);\n      break;\n    end\n    iter = iter + 1;\n  end\n\n  if nargout > 1\n    Usteps = Usteps(:,:,1:iter);\n  end\n\n  if rescale_output\n    area = sum(doublearea(V,SF)*0.5);\n    c = sum(bsxfun(@times,0.5*doublearea(V,SF)/area,barycenter(V,SF)));\n    U = U*sqrt(area);\n    U = bsxfun(@plus,U,c);\n    if nargout > 1\n      for iter = 2:size(Usteps,3)\n        Usteps(:,:,iter) = Usteps(:,:,iter)*sqrt(area);\n        Usteps(:,:,iter) = bsxfun(@plus,Usteps(:,:,iter),c);\n      end\n    end\n  end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/conformalized_mean_curvature_flow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5737441631317671}}
{"text": "function crops_data = prepare_image(im)\n% ------------------------------------------------------------------------\n% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that\n% is already in W x H x C with BGR channels\nd = load('ilsvrc_2012_mean.mat');\nmean_data = d.mean_data;\nIMAGE_DIM = 256;\nCROPPED_DIM = 224; % 224 for googLeNet , 227 for VGG and AlexNet\n\n% Convert an image returned by Matlab's imread to im_data in caffe's data\n% format: W x H x C with BGR channels\nim_data = im(:, :, [3, 2, 1]);  % permute channels from RGB to BGR\nim_data = permute(im_data, [2, 1, 3]);  % flip width and height\nim_data = single(im_data);  % convert from uint8 to single\nim_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');  % resize im_data\nim_data = im_data - mean_data;  % subtract mean_data (already in W x H x C, BGR)\n\n% oversample (4 corners, center, and their x-axis flips)\ncrops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');\nindices = [0 IMAGE_DIM-CROPPED_DIM] + 1;\nn = 1;\nfor i = indices\n  for j = indices\n    crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);\n    crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);\n    n = n + 1;\n  end\nend\ncenter = floor(indices(2) / 2) + 1;\ncrops_data(:,:,:,5) = ...\n  im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);\ncrops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);\n", "meta": {"author": "zhoubolei", "repo": "CAM", "sha": "c63f2850a7a3dadc21fa1b021875e2d4d053ece5", "save_path": "github-repos/MATLAB/zhoubolei-CAM", "path": "github-repos/MATLAB/zhoubolei-CAM/CAM-c63f2850a7a3dadc21fa1b021875e2d4d053ece5/prepare_image.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5737441590655132}}
{"text": "% LRR | EALM | Exact ALM (Lin et al. 2009)\n% process_video('LRR', 'EALM', 'dataset/demo.avi', 'output/demo_LRR-EALM.avi');\n\nalg_path_aux = fullfile(lrs_conf.lrr_path,'ALM');\naddpath(genpath(alg_path_aux));\n\nA = mean(M,2);\nlambda = 0.01;\n[Z,E] = solve_lrr(M,A,lambda,0,0,1);\n% M_hat = A*Z + E;\nL = A*Z;\nS = E;\n\nrmpath(genpath(alg_path_aux));", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/lrr/EALM/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5737441582677473}}
{"text": "classdef MOEADSTM < ALGORITHM\n% <multi/many> <real/integer>\n% MOEA/D with stable matching\n\n%------------------------------- Reference --------------------------------\n% K. Li, Q. Zhang, S. Kwong, M. Li, and R. Wang, Stable matching-based\n% selection in evolutionary multiobjective optimization, IEEE Transactions\n% on Evolutionary Computation, 2014, 18(6): 909-923.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Generate the weight vectors\n            [W,Problem.N] = UniformPoint(Problem.N,Problem.M);\n            % Size of neighborhood\n            T  = ceil(Problem.N/10);\n\n            %% Detect the neighbours of each solution\n            B = pdist2(W,W);\n            [~,B] = sort(B,2);\n            B = B(:,1:T);\n\n            %% Generate random population\n            Population = Problem.Initialization();\n            z          = min(Population.objs,[],1);\n            % Utility for each subproblem\n            Pi = ones(Problem.N,1);\n            % Old Tchebycheff function value of each solution on its subproblem\n            oldObj = max(abs((Population.objs-repmat(z,Problem.N,1))./W),[],2);\n\n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                for subgeneration = 1 : 5\n                    % Choose I\n                    Bounday = find(sum(W<1e-3,2)==Problem.M-1)';\n                    I = [Bounday,TournamentSelection(10,floor(Problem.N/5)-length(Bounday),-Pi)];\n                    % Generate an offspring for each solution in I\n                    P = zeros(length(I),3);\n                    for i = 1 : length(I)\n                        % Choose the parents\n                        if rand < 0.9\n                            P(i,:) = B(I(i),randperm(size(B,2),3));\n                        else\n                            P(i,:) = randperm(Problem.N,3);\n                        end\n                    end\n                    Offspring = OperatorDE(Problem,Population(P(:,1)),Population(P(:,2)),Population(P(:,3)));\n                    z         = min([z;Offspring.objs],[],1);\n\n                    % STM selection\n                    Population = STM([Population,Offspring],W,z,max(Population.objs,[],1));\n                end\n                if ~mod(ceil(Problem.FE/Problem.N),10)\n                    % Update Pi for each solution\n                    newObj    = max(abs((Population.objs-repmat(z,Problem.N,1))./W),[],2);\n                    DELTA     = oldObj - newObj;\n                    Temp      = DELTA < 0.001;\n                    Pi(~Temp) = 1;\n                    Pi(Temp)  = (0.95+0.05*DELTA(Temp)/0.001).*Pi(Temp);\n                    oldObj    = newObj;\n                end\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/Algorithms/Multi-objective optimization/MOEA-D-STM/MOEADSTM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338729, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5737441518081948}}
{"text": "%converts frequency to bark\n%>\n%> @param fInHz: frequency\n%> @param cModel: 'Schroeder','Terhardt', 'Zwicker', or 'Traunmuller'\n%>\n%> @retval bark value\n% ======================================================================\nfunction [bark] = ToolFreq2Bark(fInHz, cModel)\n\n    if (nargin < 2)\n        cModel = 'Schroeder';\n    end\n\n    % set function handle\n    hPitchFunc = str2func (['aca' cModel '_I']);\n    \n    bark = hPitchFunc(fInHz);\nend\n\nfunction [bark] = acaSchroeder_I(f)\n    bark    = 7 * asinh(f/650);\nend\n\nfunction [bark] = acaTerhardt_I(f)\n    bark    = 13.3 * atan(0.75 * f/1000);\nend\n\nfunction [bark] = acaZwicker_I(f)\n    bark    = 13 * atan(0.76 * f/1000) + 3.5 * atan(f/7500);\nend\n\nfunction [bark] = acaTraunmuller_I(f)\n    bark    = 26.81/(1+1960./f) - 0.53;\nend\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/ToolFreq2Bark.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5737441436756863}}
{"text": "function [Kd] = arap_linear_block(varargin)\n  % ARAP_LINEAR_BLOCK constructs a block of the matrix which constructs the\n  % linear terms of a given arap energy. When treating rotations as knowns\n  % (arranged in a column) then this constructs Kd of K such that the linear\n  % portion of the energy is as a column:\n  %   K * R = [Kx Z  ... Ky Z  ... \n  %            Z  Kx ... Z  Ky ... \n  %            ... ]\n  % These blocks are also used to build the \"covariance scatter matrices\". Here\n  % we want to build a scatter matrix that multiplies against positions\n  % (treated as known) producing covariance matrices to fit each rotation.\n  % Notice that in the case of the RHS of the poisson solve the rotations are\n  % known and the positions unknown, and vice versa for rotation fitting. These\n  % linear block just relate the rotations to the positions, linearly in each.\n  %\n  % Kd = arap_linear_block(V,F,d)\n  % Kd = arap_linear_block(V,F,d,'ParameterName','ParameterValue,...)\n  % \n  % Inputs:\n  %   V  #V by dim list of initial domain positions\n  %   F  #F by #simplex size list of triangle indices into V\n  %   d  coordinate of linear constructor to build\n  %   Optional:\n  %     'Energy'\n  %       followed by a string specifying which arap energy definition to use.\n  %       One of the following:\n  %         'spokes'  \"As-rigid-as-possible Surface Modeling\" by [Sorkine and\n  %           Alexa 2007], rotations defined at vertices affecting incident\n  %           edges, default\n  %         'elements'  \"A local-global approach to mesh parameterization\" by\n  %           [Liu et al.  2010] or \"A simple geometric model for elastic\n  %           deformation\" by [Chao et al.  2010], rotations defined at\n  %           elements (triangles or tets) \n  %         'spokes-and-rims'  Adapted version of \"As-rigid-as-possible Surface\n  %           Modeling\" by [Sorkine and Alexa 2007] presented in section 4.2 of\n  %           or \"A simple geometric model for elastic deformation\" by [Chao et\n  %           al.  2010], rotations defined at vertices affecting incident\n  %           edges and opposite edges\n  % Outputs:\n  %   Kd  #V by #V/#F block of the linear constructor matrix corresponding to\n  %     coordinate d\n  %\n  % See also: arap, arap_rhs, covariance_scatter_matrix\n  %\n\n  % default is Sorkine and Alexa style local rigidity energy\n  energy = 'spokes';\n  V = varargin{1};\n  F = varargin{2};\n  d = varargin{3};\n  % number of vertices\n  n = size(V,1);\n  % number of elements\n  m = size(F,1);\n  % simplex size\n  simplex_size = size(F,2);\n  assert(simplex_size == 3 || simplex_size == 4);\n  % number of dimensions\n  dim = size(V,2);\n  assert(d <= dim);\n\n  ii = 4;\n  while(ii <= nargin)\n    switch varargin{ii}\n    case 'Energy'\n      ii = ii + 1;\n      assert(ii<=nargin);\n      energy = varargin{ii};\n    otherwise\n      error(['Unsupported parameter: ' varargin{ii}]);\n    end\n    ii = ii + 1;\n  end\n\n  switch energy\n  case 'spokes'\n    Kd = spokes_linear_block(V,F,d);\n  case 'spokes-and-rims'\n    Kd = spokes_and_rims_linear_block(V,F,d);\n  case 'elements'\n    Kd = elements_linear_block(V,F,d);\n  otherwise\n    error(['Unsupported energy type: ' energy]);\n  end\n\n  function K = spokes_linear_block(V,F,d)\n    % Computes a matrix K such that V'* K * R computes\n    %  \u2211 wij * 0.5 * (V(i,d)-V(j,d)) * (Ri + Rj)\n    % j\u2208N(i)\n    % \n    % Inputs:\n    %   V  #V by dim list of coordinates\n    %   F  #F by 3 list of triangle indices into V\n    %   d  index into columns of V\n    % Output:\n    %   K  #V by #V matrix\n    %\n    E = edges(F);\n    % Build upper part of adjacency matrix where instead of a 1 for edge from i\n    % to j we have the difference of position in dimension d\n    A = sparse(E(:,1),E(:,2),V(E(:,1),d)-V(E(:,2),d),size(V,1),size(V,1));\n    % anti-symmetric, or considers direction of edges\n    A = A-A';\n    % Multiply with cotangent weights (don't worry about diagonal begin wrong\n    % since in A it's all zeros\n    L = cotmatrix(V,F);\n    K = L.*A;\n    % correct the diagonal (notice that the sign is positive\n    K = K + diag(sum(K,2));\n    K = 0.5*K;\n  end\n\n  function K = spokes_and_rims_linear_block(V,F,d)\n    % Computes a matrix K such that V' * K * R computes\n    %  \u2211    -2*(cot(aij) + cot(bij) * (V(i,d)-V(j,d)) * (Ri + Rj) +\n    %       -2*cot(aij) * (V(i,d)-V(j,d)) * Raij +\n    %       -2*cot(bij) * (V(i,d)-V(j,d)) * Rbij\n    % j\u2208N(i)\n    % \n    % where:          vj\n    %              /  |  \\\n    %             /   |   \\\n    %            /    |    \\\n    %           /     |     \\\n    %          aij    |    bij\n    %           \\     |     /\n    %            \\    |    /\n    %             \\fij|gij/\n    %              \\  |  /\n    %                 vi\n    % \n    % Inputs:\n    %   V  #V by dim list of coordinates\n    %   F  #F by 3 list of triangle indices into V\n    %   d  index into columns of V\n    % Output:\n    %   K  #V by #F matrix\n    %\n    if simplex_size == 3\n      % triangles\n      C = cotangent(V,F);\n      i1 = F(:,1); i2 = F(:,2); i3 = F(:,3);\n      I = [i1;i2;i2;i3;i3;i1;i1;i2;i3];\n      J = [i2;i1;i3;i2;i1;i3;i1;i2;i3];\n      v = [ ...\n         C(:,3).*(V(i1,d)-V(i2,d)) + C(:,2).*(V(i1,d)-V(i3,d)); ... \n        -C(:,3).*(V(i1,d)-V(i2,d)) + C(:,1).*(V(i2,d)-V(i3,d)); ... \n         C(:,1).*(V(i2,d)-V(i3,d)) + C(:,3).*(V(i2,d)-V(i1,d)); ... \n        -C(:,1).*(V(i2,d)-V(i3,d)) + C(:,2).*(V(i3,d)-V(i1,d)); ... \n         C(:,2).*(V(i3,d)-V(i1,d)) + C(:,1).*(V(i3,d)-V(i2,d)); ... \n        -C(:,2).*(V(i3,d)-V(i1,d)) + C(:,3).*(V(i1,d)-V(i2,d)); ... \n         ... % diagonal\n        C(:,3).*(V(i1,d)-V(i2,d)) - C(:,2).*(V(i3,d)-V(i1,d)); ... \n        C(:,1).*(V(i2,d)-V(i3,d)) - C(:,3).*(V(i1,d)-V(i2,d)); ... \n        C(:,2).*(V(i3,d)-V(i1,d)) - C(:,1).*(V(i2,d)-V(i3,d)); ... \n        ];\n      % construct and divide by 3 so laplacian can be used as is\n      K = sparse(I,J,v,n,n)/3;\n    elseif simplex_size == 4\n      % tetrahedra\n      assert(false)\n    end\n  end\n\n  function K = elements_linear_block(V,F,d)\n    % Computes a matrix K such that V' * K * R computes\n    %  \u2211    -2*cot(aij) * (V(i,d)-V(j,d)) * Raij +\n    %       -2*cot(bij) * (V(i,d)-V(j,d)) * Rbij\n    % j\u2208N(i)\n    % \n    % where:        vj\n    %              / |\\\n    %             /  | \\\n    %            aij | bij\n    %             \\  | /\n    %              \\ |/\n    %               vi\n    % \n    % Inputs:\n    %   V  #V by dim list of coordinates\n    %   F  #F by 3 list of triangle indices into V\n    %   d  index into columns of V\n    % Output:\n    %   K  #V by #F matrix\n    %\n    if simplex_size == 3\n      % triangles, #T by 3\n      C = cotangent(V,F);\n      i1 = F(:,1); i2 = F(:,2); i3 = F(:,3);\n      I = [i2;i3;i3;i1;i1;i2];\n      J = repmat((1:m)',3*2,1);\n      v = [ ...\n         C(:,1).*(V(i2,d)-V(i3,d)); ...\n        -C(:,1).*(V(i2,d)-V(i3,d)); ...\n         C(:,2).*(V(i3,d)-V(i1,d)); ...\n        -C(:,2).*(V(i3,d)-V(i1,d)); ...\n         C(:,3).*(V(i1,d)-V(i2,d)); ...\n        -C(:,3).*(V(i1,d)-V(i2,d))];\n      K = sparse(I,J,v,n,m);\n    elseif simplex_size == 4\n      % tetrahedra, #T by 6\n      C = cotangent(V,F);\n      i1 = F(:,1); i2 = F(:,2); i3 = F(:,3); i4 = F(:,4);\n      I = [i2;i3;i3;i1;i1;i2;i4;i1;i4;i2;i4;i3];\n      J = repmat((1:m)',6*2,1);\n      v = [ ...\n         C(:,1).*(V(i2,d)-V(i3,d)); ...\n        -C(:,1).*(V(i2,d)-V(i3,d)); ...\n         C(:,2).*(V(i3,d)-V(i1,d)); ...\n        -C(:,2).*(V(i3,d)-V(i1,d)); ...\n         C(:,3).*(V(i1,d)-V(i2,d)); ...\n        -C(:,3).*(V(i1,d)-V(i2,d)); ...\n         C(:,4).*(V(i4,d)-V(i1,d)); ...\n        -C(:,4).*(V(i4,d)-V(i1,d)); ...\n         C(:,5).*(V(i4,d)-V(i2,d)); ...\n        -C(:,5).*(V(i4,d)-V(i2,d)); ...\n         C(:,6).*(V(i4,d)-V(i3,d)); ...\n        -C(:,6).*(V(i4,d)-V(i3,d))];\n      K = sparse(I,J,v,n,m);\n    end\n  end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/arap_linear_block.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650403, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5737114557166874}}
{"text": "classdef VigdergauzParametersFromVolumeAndPhi < handle\n    \n    properties (Access = public)\n        parameters\n    end\n    \n    properties (Access = private)\n        cx\n        cy\n        phi\n        volume\n        ax\n        ay        \n    end\n    \n    methods (Access = public)\n        \n        function obj = VigdergauzParametersFromVolumeAndPhi(cParams)\n            obj.init(cParams);\n            obj.checkValidityOfParameters();\n        end\n        \n        function compute(obj)\n            r = obj.computeOptimalR();\n            obj.computeAxAy(r)  \n            obj.computeVigergauzParameters();\n        end        \n        \n    end\n    \n    methods (Access = private)\n        \n        function init(obj,cParams)\n            obj.volume = cParams.volumeMicro;\n            obj.phi    = atan(cParams.superEllipseRatio);\n            obj.cx     = cParams.cx;\n            obj.cy     = cParams.cy;            \n        end\n        \n        function computeAxAy(obj,r)\n            s.r = r;\n            s.volume = obj.volume;\n            s.cx = obj.cx;\n            s.cy = obj.cy;\n            axay = AxAyComputerFromVolumeAndR(s); \n            [obj.ax,obj.ay] = axay.compute();            \n        end\n        \n        function r = computeOptimalR(obj)\n            s.x0 = 1;\n            s.functionToSolve = @(r) obj.equationForR(r);\n            solver = ImplicitEquationSolver(s);\n            r = solver.solve();\n        end\n               \n        function f = equationForR(obj,r)\n            obj.computeAxAy(r);\n            obj.computeVigergauzParameters();\n            mx = obj.parameters.mx;\n            my = obj.parameters.my;\n            f = tan(obj.phi) - mx/my;\n        end\n        \n        function computeVigergauzParameters(obj)\n            s.ax = obj.ax;\n            s.ay = obj.ay;\n            s.cx = obj.cx;\n            s.cy = obj.cy;\n            s.type = 'AxAndAy';\n            obj.parameters = VigdergauzParameters.create(s);\n        end \n        \n        function checkValidityOfParameters(obj)\n            if ~obj.isMicroStructureValid()\n                error('Not possible axisRatio with this volume')\n            end            \n        end\n        \n        function itIs = isMicroStructureValid(obj)\n            mMax = 0.99;\n            phiMin = atan((1 - obj.volume)/(mMax^2));\n            phiMax = atan((mMax^2)/(1 - obj.volume));\n            itIs = obj.phi <= phiMax && obj.phi >= phiMin;\n        end        \n        \n    end\n    \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Vigdergauz/VigerdergauzParameters/VigdergauzParametersFromVolumeAndPhi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5737114554101684}}
{"text": "function [K,C,strain,A,M] = linear_elasticity_stiffness(V,F,varargin)\n  %\n  % [K,C,strain,A,M] = linear_elasticity_stiffness(V,F)\n  %\n  % Inputs:\n  %   V  #V by d list of vertex positions\n  %   F  #F by d+1 list of  element indices into V\n  %   Optional:\n  %     'Lambda'  followed by first Lam\u00e9 parameter {1.7423333}, scalar\n  %       (homogeneous) or #F by 1 list of per-element values\n  %     'Mu'  followed by shear modulus {0.0115}, scalar (homogeneous) or #F by\n  %       1 list of per-element values\n  %     'Young'  followed by Young's modulus, scalar (homogeneous) or #F by 1\n  %       list of per-element values\n  %     'Nu'  followed by Poisson's ratio, scalar (homogeneous) or #F by 1 list\n  %       of per-element values\n  % Outputs:\n  %   K  #V*d by #V*d sparse stiffness matrix\n  %   C  #F**(d*(d+1)/2) by #F**(d*(d+1)/2) sparse constituitive model matrix \n  %   strain  #F*(d*(d+1)/2) by #V*d sparse strain matrix\n  %   A  #F*(d*(d+1)/2) by #F*(d*(d+1)/2) diagonal element area matrix\n  %   M  #V*d by #V*d sparse mass matrix\n  %\n\n  % Silicone rubber: http://www.azom.com/properties.aspx?ArticleID=920\n  mu = 0.0115;\n  % Bulk modulus\n  K = 1.75;\n  lambda = K-2/3*mu;\n  young = [];\n  nu = [];\n  % Map of parameter names to variable names\n  params_to_variables = containers.Map( ...\n    {'Lambda','Mu','Nu','Young'}, ...\n    {'lambda','mu','nu','young'});\n  v = 1;\n  while v <= numel(varargin)\n    param_name = varargin{v};\n    if isKey(params_to_variables,param_name)\n      assert(v+1<=numel(varargin));\n      v = v+1;\n      % Trick: use feval on anonymous function to use assignin to this workspace\n      feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n    else\n      error('Unsupported parameter: %s',varargin{v});\n    end\n    v=v+1;\n  end\n\n  assert( ...\n    (~isempty(lambda) && ~isempty(mu))||(~isempty(young) && ~isempty(nu)), ...\n    'Must define either lambda and mu or young and nu');\n  if (~isempty(young) && ~isempty(nu))\n    lambda = young.*nu./((1+nu).*(1-2.*nu));\n    mu = .5.*young./(1+nu);\n  end\n\n  dim = size(V,2);\n\n  % This matches the matlab code by Jonas Koko, in\n  % \"Vectorized Matlab Codes for Linear Two-Dimensional Elasticity\"\n\n  % Gradient/divergence operator\n  G = grad(V,F);\n\n  I = speye(size(F,1));\n  Z = sparse(size(F,1),size(V,1));\n  lambda = diag(sparse(lambda));\n  mu = diag(sparse(mu));\n  % Strain tensor \n  %\n  %   \u03f5 = \u00bd(\u2207u + (\u2207u)')\n  %   \u03f5 = \u00bd // \u2202u\u2081/\u2202x\u2081  \u2202u\u2082/\u2202x\u2081 \\  + / \u2202u\u2081/\u2202x\u2081  \u2202u\u2081/\u2202x\u2082 \\\\\n  %         \\\\ \u2202u\u2081/\u2202x\u2082  \u2202u\u2082/\u2202x\u2082 /    \\ \u2202u\u2082/\u2202x\u2081  \u2202u\u2082/\u2202x\u2082 //\n  %\n  %                                \"Voigt\" notation\n  %   \u03f5\u2081\u2081 = \u2202u\u2081/\u2202x\u2081              = \u03f5\u2081\n  %   \u03f5\u2082\u2082 = \u2202u\u2082/\u2202x\u2082              = \u03f5\u2082\n  %   \u03f5\u2081\u2082 = \u00bd(\u2202u\u2082/\u2202x\u2081 + \u2202u\u2081/\u2202x\u2081) = \u00bd \u03f5\u2083\n  %   \u03f5\u2082\u2081 = \u03f5\u2081\u2082                  = \u00bd \u03f5\u2083\n  %  \n  switch dim\n  case 2\n    G1 = G(1:size(F,1),:);\n    G2 = G(size(F,1)+(1:size(F,1)),:);\n    % 3#F by 2#V\n    strain = [G1 Z;Z G2;G2 G1];\n    % Stiffness tensor\n    %\n    %    \u03c3 = C:\u03f5        %  A:B = Aij Bij \n    %                   %      = \u2211\u2211 Aij Bij, where in this case Aij is a 2x2\n    %                   %                    matrix, and Bij is a scalar\n    %  \n    % For each face we have:\n    %   \n    %    2x2 = 2x2x2x2 2x2\n    %    \u03c3f  = Cf : \u03f5f\n    %    \u03c3 = \u2211\u2211 Cij \u03f5ij, where Cij is a 2x2 matrix\n    %    \u03c3kl = \u2211\u2211 Cijkl \u03f5ij, where Cijkl is a scalar\n    %\n    % But really \u03f5f and \u03c3f are just 3 distinct values:\n    %\n    %   \u03c3\u2081 = [\u03f5\u2081 \u03f5\u2082 \u03f5\u2083] [ c\u2081\u2081 ; c\u2081\u2082 ; c\u2081\u2083 ]\n    %   \u03c3\u2082 = [\u03f5\u2081 \u03f5\u2082 \u03f5\u2083] [ c\u2082\u2081 ; c\u2082\u2082 ; c\u2082\u2083 ]\n    %   \u03c3\u2083 = [\u03f5\u2081 \u03f5\u2082 \u03f5\u2083] [ c\u2083\u2081 ; c\u2083\u2082 ; c\u2083\u2083 ]\n    %\n    %    /\u03c3\u2081\\     /c\u2081\u2081 c\u2081\u2082 c\u2081\u2083\\  /\u03f5\u2081\\\n    %   | \u03c3\u2082 | = | c\u2082\u2081 c\u2082\u2082 c\u2082\u2083 || \u03f5\u2082 |\n    %    \\\u03c3\u2083/     \\c\u2083\u2081 c\u2083\u2082 c\u2083\u2083/  \\\u03f5\u2083/\n    %  \n    % So if \u03c3 is a 3#F by 1 vector and \u03f5 is a 3#F vector then:\n    %  \n    %   \u03c3 = C \u03f5\n    %        /C\u2081\u2081 C\u2081\u2082 C\u2081\u2083\\  /\u03f5\u2081\\\n    %   \u03c3 = | C\u2082\u2081 C\u2082\u2082 C\u2082\u2083 || \u03f5\u2082 |\n    %        \\C\u2083\u2081 C\u2083\u2082 C\u2083\u2083/  \\\u03f5\u2083/\n    % \n    %  where C is 3#F by 3#F matrix and Cij = diagonal #F by #F matrix.\n    %\n    % For Isotropic homogeneous media, we have that:\n    %\n    %   \u03c3ij = \u03bb \u03b4ij \u03f5kk + 2\u03bc \u03f5ij\n    %   \u03c3ij = \u03bb \u03b4ij (\u2211 \u03f5kk) + 2\u03bc \u03f5ij\n    % \n    % where \u03bb is Lam\u00e9's first parameter and \u03bc is the shear modulus: the bulk\n    % modulus is thus K := \u03bb + \u2154 \u03bc\n    %\n    % Or in Voigt notation:\n    % \n    %   \u03c3\u2081 = \u03c3\u2081\u2081 = \u03bb (\u03f5\u2081 + \u03f5\u2082) + 2\u03bc \u03f5\u2081\n    %   \u03c3\u2082 = \u03c3\u2082\u2082 = \u03bb (\u03f5\u2081 + \u03f5\u2082) + 2\u03bc \u03f5\u2082\n    %   \u03c3\u2083 = \u03c3\u2081\u2082 = \u03bb (\u03f5\u2081 + \u03f5\u2082) + 2\u03bc \u03f5\u2081\u2082\n    %            = \u03bb (\u03f5\u2081 + \u03f5\u2082) + \u03bc \u03f5\u2083\n    %\n    %        //\u03bb  \u03bb 0\\   /2\u03bc  0  0\\\\  \n    %  \u03c3 =  || \u03bb  \u03bb 0 |+|  0 2\u03bc  0 || \u03f5\n    %        \\\\0  0 0/   \\ 0  0  \u03bc//\n    %\n    %\n    %Z = sparse(size(F,1),size(F,1));\n    %I = speye(size(F,1));\n    %C = lambda*[[I I Z;I I Z;Z Z Z]] + mu*[2*I Z Z;Z 2*I Z;Z Z I];\n    %C = lambda*[1 1 0;1 1 0;0 0 0] + mu*diag([2 2 1]);\n    %C = kroneye(C,size(F,1));\n    C = [ ...\n      (lambda+2*mu)*I        lambda*I  0*I; ...\n            lambda*I (lambda+2*mu)*I  0*I; ...\n                  0*I             0*I mu*I];\n    %   \u2207\u22c5\u03c3 = /\u2207\u22c5/\u03c3\u2081\u2081\\  \u2207\u22c5/\u03c3\u2081\u2082\\\\\n    %         \\  \\\u03c3\u2082\u2081/    \\\u03c3\u2082\u2082//\n    % \n    % If D is the divergence operator then D is 2#V by 3#F, where \u03c3 is 3#F by 1\n    % vectorized stress tensor using Voigt notation:\n    %\n    %   X = D \u03c3\n    %\n    A = diag(sparse(doublearea(V,F)/2));\n  case 3\n    G1 = G(1:size(F,1),:);\n    G2 = G(size(F,1)+(1:size(F,1)),:);\n    G3 = G(2*size(F,1)+(1:size(F,1)),:);\n    strain = [G1 Z Z;Z G2 Z; Z Z G3; Z G3 G2; G3 Z G1; G2 G1 Z];\n    C = [ ...\n        (lambda+2*mu)*I        lambda*I        lambda*I     0*I     0*I     0*I ; ...\n        lambda*I (lambda+2*mu)*I        lambda*I     0*I     0*I     0*I ; ...\n        lambda*I        lambda*I (lambda+2*mu)*I     0*I     0*I     0*I ; ...\n        0*I             0*I             0*I    mu*I     0*I     0*I ; ...\n        0*I             0*I             0*I     0*I    mu*I     0*I ; ...\n        0*I             0*I             0*I     0*I     0*I    mu*I ];\n    A = diag(sparse(volume(V,F)));\n  end\n  Z = sparse(size(V,1),size(F,1));\n  D = strain';\n  A = repdiag(A,dim*(dim+1)/2);\n  K = D * A * C * strain;\n\n\n  M = massmatrix(V,F);\n  M = repdiag(M,size(V,2));\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/linear_elasticity_stiffness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5737114536785637}}
{"text": "function vcell = lift_ape_v1(r,t,theta,tBound,depthBound,FOV)\n    r       = r(:);\n    t       = t(:);\n    x       = [r;t];\n    theta   = theta(:);\n    v       = [1;x;theta;kron(theta,x)];\n    if tBound^2 < t'*t\n        v1  = [1;theta] * 0;\n    else\n        v1  = [1;theta] * sqrt(tBound^2 - t'*t);\n    end\n    \n    if t(end) < depthBound\n        v2  = [1;theta] * 0; \n    else\n        v2  = [1;theta] * sqrt(t(end)-depthBound);\n    end\n    \n    scale = tan(deg2rad(FOV)/2);\n    if scale^2 * t(3)^2 < t(1)^2 + t(2)^2\n        v3  = [1;theta] * 0; \n    else\n        v3  = [1;theta] * sqrt(scale^2 * t(3)^2 - t(1)^2 - t(2)^2);\n    end\n    \n    vcell   = {v;v1;v2;v3};\nend", "meta": {"author": "MIT-SPARK", "repo": "CertifiablyRobustPerception", "sha": "dd149d0c54093cfb72a8f912f4ae807635db6f3b", "save_path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception", "path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception/CertifiablyRobustPerception-dd149d0c54093cfb72a8f912f4ae807635db6f3b/AbsolutePoseEstimation/solvers/lift_ape_v1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5737104924571851}}
{"text": "function [old_dirs,old_stps,Hdiag,Bcompact] = lbfgsUpdate(y,s,corrections,debug,old_dirs,old_stps,Hdiag)\n\n%B0 = eye(length(y))/Hdiag;\nS = old_dirs(:,2:end);\nY = old_stps(:,2:end);\nk = size(Y,2);\nL = zeros(k);\nfor j = 1:k\n    for i = j+1:k\n        L(i,j) = S(:,i)'*Y(:,j);\n    end\nend\nD = diag(diag(S'*Y));\nN = [S/Hdiag Y];\nM = [S'*S/Hdiag L;L' -D];\n\nys = y'*s;\nBs = s/Hdiag - N*(M\\(N'*s)); % Product B*s\nsBs = s'*Bs;\n\neta = .02;\nif ys < eta*sBs\n    if debug\n        fprintf('Damped Update\\n');\n    end\n    theta = min(max(0,((1-eta)*sBs)/(sBs - ys)),1);\n    y = theta*y + (1-theta)*Bs;\nend\n\n\nnumCorrections = size(old_dirs,2);\nif numCorrections < corrections\n    % Full Update\n    old_dirs(:,numCorrections+1) = s;\n    old_stps(:,numCorrections+1) = y;\nelse\n    % Limited-Memory Update\n    old_dirs = [old_dirs(:,2:corrections) s];\n    old_stps = [old_stps(:,2:corrections) y];\nend\n\n% Update scale of initial Hessian approximation\nHdiag = (y'*s)/(y'*y);", "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/minFunc/dampedUpdate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5737104883907346}}
{"text": "%% housekeeping\nclose all\nclearvars\nclc\n\n%% read the model\nm=rise('kaiji1207_exp');\n\n%% alternatively, solve the model directly\n\nm=solve(m);\n\n%% print the solution of the model\n\nm.print_solution\n% alternative call\n% print_solution(kaiji)\n\n%% print solution of a subset of variables\n\nm.print_solution({'C','H','K'})\n\n%% doing things the RBC way: waste of time\n% RISE write the solution of the whole system as: X_t=T*X_{t-1}+R*e_t. The\n% RBC guys write solutions as S_t=P*S_{t-1}+K*e_t and Y_t=F*S_t . Below, we\n% show how to recover matrices P, K and F.\n% collect the T and R matrices\n[T,R]=load_solution(m,'iov');\nT=T{1}; R=R{1};\n% set some elements to 0 sharp\nT(abs(T)<1e-10)=0;\nR(abs(R)<1e-10)=0;\n% get the state columns\nstate_cols=any(T); \n% Kaiji wastes time double-checking check that find(any(T)) gives the\n% columns of the states \n% get the control columns as the columns that are not states\ncontrol_cols=~state_cols;\n% now build the P matrix expressing the states as a function of the states\nP=T(state_cols,state_cols);\n% recover the solution of the controls as a function of states\nFP=T(control_cols,state_cols);\nF=FP/P; % F=FP*inv(P) P should always be invertible unless collinearity\n% recover the shock impact on the states\nK=R(state_cols,:);\n\nallvars=m.endogenous.name;\n\nstate_variables=allvars(state_cols);\n\ncontrol_variables=allvars(control_cols);\n\n%% compute impulse responses\n% In general, if you want to see the options for a particular method,\n% create an empty rise object. e.g. tmp=rise.empty(0); then you can go\n% ahead and call the specific function you want to use on that empty object\n% and it will list out the various options and the defaults of those\n% options. e.g. irf(tmp)\nsimple_irfs=irf(m,'irf_periods',20);\n%% construct a vector of models with different anticipation options\nkaiji_unant=m.set('irf_anticipate',false);\nmyvector=[m,kaiji_unant];\n\n%% change some option in the vector\n% here we set:\n% 1- the number of irf periods. If we don't the default of 40 will be used\n% 2- we assume that we know as of today that shocks will hit 3 periods from\n% now. And we choose to act on that information (anticipated) or disregard\n% the information (unanticipated)\n% 3- we can also choose the sign of the shocks. By default, the shocks will\n% be positive.\nmyirfs=irf(myvector,'irf_periods',20,'solve_shock_horizon',3,'irf_shock_sign',1);\n\n%% plot the irfs\nshock_list=m.exogenous.name;\ntex=get(m,'tex');\n% var_list=allvars;\n% just re-ordering the variables in a way that I like for the plotting\nvar_list={'A','B','D','PSI','C','K','H','R'}; \nfor ishock=1:numel(shock_list)\n    shock=shock_list{ishock};\n    figure('name',['IRFs to a ',tex.(shock), 'shock']);\n    for ivar=1:numel(var_list)\n        endovar=var_list{ivar};\n        subplot(3,3,ivar)\n        plot(myirfs.(shock).(endovar),'linewidth',2)\n        title(tex.(endovar))\n        if ivar==1\n            legend('anticipated','unanticipated')\n        end\n    end\nend\n%% estimation. Now the DSGE way\n\n%% read the data and create the time series\n[datta,names]=xlsread('data.xlsx');\nnames=names(1,2:end);\nstart_date='1960';\n\nmydata=struct();\nfor ii=1:numel(names)\n    mydata.(names{ii})=ts(start_date,datta(:,ii+1));\nend\n\n%% plot the data\nfigure('name','Observed data');\nfor ii=1:numel(names)\n    subplot(3,1,ii)\n    plot(mydata.(names{ii}))\n    title(names{ii});\nend\n\n%% estimate the model\n\nm=estimate(m,'data',mydata);\n\n%% historical decomposition of shocks\nhistdec=historical_decomposition(m);\n\n%% plot the decomposition\nfigure('name','historical decomposition of shocks and initial conditions')\nfor ivar=1:numel(var_list)\n    vname=var_list{ivar};\n    subplot(3,3,ivar)\n    plot_decomp(histdec.(vname))\n    title(tex.(vname))\n    if ivar==1\n        contrib_names=histdec.(vname).varnames;\n        for jj=1:numel(contrib_names)\n            if ~isfield(tex,contrib_names{jj})\n                continue\n            end\n            contrib_names{jj}=tex.(contrib_names{jj});\n        end\n        hleg=legend(contrib_names,...\n            'Location','BestOutside','orientation','horizontal');\n        pp=get(hleg,'position');\n        pp(1:2)=0;\n        set(hleg,'position',pp)\n    end\nend\n\n%% counterfactual: what if only one shock had been alive?\nfor ishock=1:numel(shock_list)\n    %,{'EPS_PSI','EPS_B','EPS_D'}\n    [counterf,actual]=counterfactual(m,[],1,shock_list{ishock});\n    figure('name',['Counterfactual: ',tex.(shock_list{ishock}),' shock only'])\n    for ivar=1:numel(var_list)\n        vname=var_list{ivar};\n        subplot(3,3,ivar)\n        plot([actual.(vname),counterf.(vname)])\n        title(tex.(vname))\n        if ivar==1\n            legend({'actual','counterfactual'})\n        end\n    end\nend\n\n%% counterfactual for a subset of shocks\nclose all\n[counterf,actual]=counterfactual(m,[],1,{'EPS_PSI','EPS_B','EPS_D'});\nfigure('name','Counterfactual: EPS_PSI and EPS_B shock only');\nfor ivar=1:numel(var_list)\n    vname=var_list{ivar};\n    subplot(3,3,ivar)\n    plot([actual.(vname),counterf.(vname)])\n    title(tex.(vname))\n    if ivar==1\n        legend({'actual','counterfactual'})\n    end\nend\n\n%% variance decomposition\nvardec=variance_decomposition(m);\n\n%% plot the decomposition\nclose all\nfigure('name','Variance decomposition of shocks')\nfor ivar=1:numel(var_list)\n    vname=var_list{ivar};\n    subplot(3,3,ivar)\n    plot_decomp('0:50',vardec.conditional.(vname))\n    title(tex.(vname))\n    if ivar==1\n        contrib_names=vardec.conditional.(vname).varnames;\n        for jj=1:numel(contrib_names)\n            if ~isfield(tex,contrib_names{jj})\n                continue\n            end\n            contrib_names{jj}=tex.(contrib_names{jj});\n        end\n        hleg=legend(contrib_names,...\n            'Location','BestOutside','orientation','horizontal');\n        pp=get(hleg,'position');\n        pp(1:2)=0;\n        set(hleg,'position',pp)\n    end\nend\n", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/KaijiTutorial/howto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5737095939773835}}
{"text": "function f = p06_f ( x )\n\n%*****************************************************************************80\n%\n%% P06_F evaluates the objective function for problem 6.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 February 2002\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Richard Brent,\n%    Algorithms for Minimization Without Derivatives,\n%    Prentice Hall 1973,\n%    Reprinted Dover, 2002\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 = 2.0 - 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/test_min/p06_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.8128673269042768, "lm_q1q2_score": 0.5737095889469319}}
{"text": "function varargout=sde_correlate(c,r1)\n%SDE_CORRELATE  Correlated values.\n%   R2 = SDE_CORRELATE(C, R1) returns the matrix R2 of M correlated values given\n%   the N-by-N correlation matrix C and the M-by-N matrix of (uncorrelated)\n%   values R1. The first column of R2 is always SQRT(C(1,1)) times the first\n%   column of R1.\n%\n%   [R2, D] = SDE_CORRELATE(C, R1) also returns the N-by-N diffusion matrix, D,\n%   created from the correlation matrix, C.\n%\n%   D = SDE_CORRELATE(C) without a second input argument returns only the N-by-N\n%   diffusion matrix, D, created from the correlation matrix, C.\n%\n%   Note:\n%       C may either be a symmetric positive semidefinite correlation matrix or\n%       covariance matrix.\n%\n%   Example:\n%       % Plot uncorrelated and correlated normally-distributed points\n%       r1 = randn(1e4,2); corr(r1)\n%       r2 = sde_correlate([1 -0.8;-0.8 1],r1); corr(r2)\n%       figure; plot(r1(:,1),r1(:,2),'b.',r2(:,1),r2(:,2),'r*'); axis equal;\n%\n%   See also: SDE_DECORRELATE, RAND, RANDN, RANDSTREAM, RANDSTREAM/RANDN\n\n%   Andrew D. Horchler, horchler @ gmail . com, Created 5-20-13\n%   Revision: 1.2, 7-17-13\n\n\nif nargout > min(nargin,2)\n    error('SDETools:sde_correlate:TooManyOutputs',...\n          'Too many output arguments for number of supplied inputs.');\nend\n\nif isempty(c) || isempty(r1)\n    if nargin == 1\n        varargout{1} = [];\n    else\n        varargout{2} = [];\n    end\nelse\n    [m,n] = size(c);\n    if ndims(c) ~= 2 || m ~= n              %#ok<ISMAT>\n        error('SDETools:sde_correlate:NonSquareMatrix',...\n              'The correlation matrix must be square.');\n    end\n    \n    if sde_isdiag(c)\n        num = rank(c);\n        c = diag(c);\n        if any(c) < 0\n            error('SDETools:sde_correlate:NegativeDiagonal',...\n                 ['All elements of the diagonal of the correlation matrix '...\n                  'must be non-negative.']);\n        end\n        \n        d = sqrt(c);\n        isDiag = isscalar(c);\n    else\n        [d,num] = cholcov(c);\n        if isempty(d)\n            error('SDETools:sde_correlate:NonSymmetricSemiDefinite',...\n                 ['The correlation matrix must be a symmetric positive '...\n                  'semidefinite matrix.']);\n        end\n        isDiag = false;\n    end\n    \n    if nargin == 1\n        if num ~= m\n            warning('SDETools:sde_correlate:NonFullRank1',...\n                    'The correlation matrix is not full rank.');\n        end\n        \n        if isDiag\n            varargout{1} = diag(d);\n        else\n            varargout{1} = d;\n        end\n    else\n        if ndims(r1) ~= 2 || size(r1,2) ~= m\t%#ok<ISMAT>\n            error('SDETools:sde_correlate:DimensionMismatch',...\n                 ['The number of columns in the matrix of normally '...\n                  'distributed values must equal the dimension of the '...\n                  'correlation matrix.']);\n        end\n        if num ~= m\n            warning('SDETools:sde_correlate:NonFullRank2',...\n                   ['The correlation matrix is not full rank. Only the '...\n                    'first %d columns of the input values will be '...\n                    'correlated.'],num);\n        end\n        \n        if isDiag\n            varargout{1} = bsxfun(@mtimes,r1,d);\n            if nargout == 2\n                varargout{2} = diag(d);\n            end\n        else\n            varargout{1} = r1*d;\n            if nargout == 2\n                varargout{2} = d;\n            end\n        end\n    end\nend", "meta": {"author": "horchler", "repo": "SDETools", "sha": "b5da17fc1c7b900ef4dc6d2fa0c6ad19e31b0fcf", "save_path": "github-repos/MATLAB/horchler-SDETools", "path": "github-repos/MATLAB/horchler-SDETools/SDETools-b5da17fc1c7b900ef4dc6d2fa0c6ad19e31b0fcf/SDETools/sde_correlate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673269042765, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5737095889469317}}
{"text": "%FEATRANK Feature ranking on individual performance for classification\n% \n% \t[I,F] = FEATRANK(A,CRIT,T)\n% \t  I   = A*FEATRANK([],CRIT,T)\n% \t  I   = A*FEATRANK(CRIT,T)\n% \n% INPUT\n%   A      input dataset\n%   CRIT   string name of a method or untrained mapping, default 'NN'\n%   T      validation dataset (optional)\n%\n% OUTPUT\n%   I      vector with sorted feature indices\n%   F      vector with criteria values\n%\n% DESCRIPTION\n% Feature ranking based on the training dataset A. CRIT determines \n% the criterion used by the feature evaluation routine feateval. If \n% the dataset T is given, it is used as test set for feateval. In I \n% the features are returned in decreasing performance. In F the \n% corresponding values of feateval are given. Default: crit='NN'.\n% \n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% MAPPINGS, DATASETS, FEATEVAL, FEATSELO, FEATSELB, FEATSELF,\n% FEATSELP, FEATSELM\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\nfunction [I,F] = featrank(varargin)\n\nargin = shiftargin(varargin,'char');\nargin = setdefaults(argin,[],'NN',[]);\nif mapping_task(argin,'definition')\n  I = define_mapping(argin,'fixed');\nelse\n  [a,crit,t] = deal(argin{:});\n\t[m,k,c] = getsize(a);\n\tF = zeros(1,k);\n\tisvaldfile(a,1,2); % at least 1 object per class, 2 classes\n\ta = testdatasize(a);\n\tiscomdset(a,t);\n\t\n\tif isempty(t)\n\t\tfor j = 1:k\n\t\t\tF(j) = feateval(a(:,j),crit);\n\t\tend\n\telse\n\t\t% run the criterion on the validation set\n\t\tfor j = 1:k\n\t\t\tF(j) = feateval(a(:,j),crit,t(:,j));\n\t\tend\n\tend\n\t\n\t[F,I] = sort(-F);\n\tF = -F;\nend\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/featrank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5737095875782401}}
{"text": "function [W] = hp2W(hp)\n% Convert power from mechanical horsepower to watts.\n% Chad A. Greene 2012\nW = hp*745.699871582;\n", "meta": {"author": "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/hp2W.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5737095862095479}}
{"text": "function r8_erf_inverse_test ( )\n\n%*****************************************************************************80\n%\n%% R8_ERF_INVERSE_TEST tests R8_ERF_INVERSE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    05 August 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8_ERF_INVERSE_TEST:\\n' );\n  fprintf ( 1, '  R8_ERF_INVERSE inverts the error function.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '    FX            X    R8_ERF_INVERSE(FX)\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x1, fx ] = erf_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    x2 = r8_erf_inverse ( fx );\n\n    fprintf ( 1, '  %6f  %12f  %12f\\n', fx, x1, 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/polpak/r8_erf_inverse_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.5737095756864566}}
{"text": "function K = dexpKernDiagCompute(kern, x)\n\n% DEXPKERNDIAGCOMPUTE Compute diagonal of the double exponential kernel.\n%\n% FORMAT\n% DESC computes the diagonal of the kernel matrix for the double\n% exponential kernel given a column vector of inputs.\n% ARG kern : the kernel structure for which the kernel matrix is computed.\n% ARG x : input data in the form of a design matrix.\n% RETURN K : a vector of the same size as x containing the diagonal of the\n% kernel matrix computed at the given points.\n%\n% SEEALSO : dexpKernParamInit, kernDiagCompute, kernCreate, dexpKernCompute\n%\n% COPYRIGHT : David Luengo, 2009\n\n% KERN\n\n\nK = 0.5 * kern.variance * kern.decay * ones(size(x));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/dexpKernDiagCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5737095724868848}}
{"text": "%% housekeeping\nclear \nclose all\nclc()\n\n%% Create dataset\nclc\n\ndo_plot=true;\n\nscale=100;\n\n[db,varlist0]=create_dataset(scale,do_plot);\n\nvarlist=fieldnames(varlist0);\n%% Choose a model type: see cell \"create the structural VAR model\" below\nmodel_type=4;\n\n%% set up the restrictions\nclose()\n\n% create restrictions on parameters as well as markov chains\n%------------------------------------------------------------\nswitch model_type\n    case 0 \n        % constant-parameter model\n        [lin_restr,nonlin_restr,markov_chains]=create_restrictions_and_markov_chains0();\n    case 1 \n        % Coefficients are switching regimes across all equations\n        % (synchronized case) \n        [lin_restr,nonlin_restr,markov_chains]=create_restrictions_and_markov_chains1();\n    case 2 \n        % Coefficients and variances have different chains, different\n        % regimes, and different durations \n        [lin_restr,nonlin_restr,markov_chains]=create_restrictions_and_markov_chains2();\n    case 3 \n        % Only coefficients in monetary policy equation are changing\n        [lin_restr,nonlin_restr,markov_chains]=create_restrictions_and_markov_chains3();\n    case 4 \n        % Only variance in monetary policy equation is changing\n        [lin_restr,nonlin_restr,markov_chains]=create_restrictions_and_markov_chains4();\n    case 5 \n        % Both coefficients and variances in monetary policy equation\n        % change with two independent Markov processes \n        [lin_restr,nonlin_restr,markov_chains]=create_restrictions_and_markov_chains5();\n    case 6 % ok\n        % Only variances in ALL three equations switch\n        [lin_restr,nonlin_restr,markov_chains]=create_restrictions_and_markov_chains6();\n    otherwise\n        error('the coded model types are 0, 1, 2, 3, 4 and 6')\nend\n\n%% Create the VAR\n\nnlags=2;\n\nexog={};\n\npanel=[];\n\nconstant=true;\n\n% first we create a template structure\n% ------------------------------------\nsv0=svar(varlist,exog,nlags,constant,panel,markov_chains);\n\n%% set priors\n\nprior=svar.prior_template();\n\nprior.type='sz';\n\n% prior.L1=0.1/2;\n% \n% prior.coefprior=0.5;\n\nis_prior=~true;\n\n%% Find posterior mode\nclc\n\nsv=sv0;\n\nif is_prior\n    \n    sv=set(sv,'prior',prior);\n    \nend\n\nsv=estimate(sv,{'1960Q1','2015Q2'},'data',db,...\n    'linear_restrictions',[lin_restr;nonlin_restr]);\n\n%% Printing estimates\n\nprint_structural_form(sv)\n\n%% Printing solution\nclc\n\nprint_solution(sv)\n\n%% plot smoothed state and regime probabilities\n\nclose all\n\nplot_probabilities(sv)\n\n%% plots probabilities against data\nclose all\n\nplot_data_against_probabilities(sv,'state')\n\n%% Impulse responses\n\nmyirfs=irf(sv);\n\n%% Posterior sampling\n\n%% Marginal data density\n\n%% Out-of sample forecasts\n\n%% Conditional forecast\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/examples/VariousModels/TaoZha/Tutorials/SVAR/+deprecated/driver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5737095660877414}}
{"text": "function CPD = deterministic_CPD(bnet, self, fname, pfail)\n% DETERMINISTIC_CPD Make a tabular CPD representing a (noisy) deterministic function\n%\n% CPD = deterministic_CPD(bnet, self, fname)\n% This calls feval(fname, pvals) for each possible vector of parent values.\n% e.g., suppose there are 2 ternary parents, then pvals = \n%  [1 1], [2 1], [3 1],   [1 2], [2 2], [3 2],   [1 3], [2 3], [3 3]\n% If v = feval(fname, pvals(i)), then\n%  CPD(x | parents=pvals(i)) = 1 if x==v, and = 0 if x<>v\n% e.g., suppose X4 = X2 AND (NOT X3). Then\n%    bnet.CPD{4} = deterministic_CPD(bnet, 4, inline('((x(1)-1) & ~(x(2)-1)) + 1'));  \n% Note that x(1) refers pvals(1) = X2, and x(2) refers to pvals(2)=X3\n% See also boolean_CPD.\n%\n% CPD = deterministic_CPD(bnet, self, fname, pfail)\n% will put probability mass 1-pfail on f(parents), and distribute pfail over the other values.\n% This is useful for simulating noisy deterministic functions.\n% If pfail is omitted, it is set to 0.\n%\n\n\nif nargin==0\n  % This occurs if we are trying to load an object from a file.\n  CPD = tabular_CPD(bnet, self);\n  return;\nelseif isa(bnet, 'deterministic_CPD')\n  % This might occur if we are copying an object.\n  CPD = bnet;\n  return;\nend\n\nif nargin < 4, pfail = 0; end\n\nps = parents(bnet.dag, self);\nns = bnet.node_sizes;\npsizes = ns(ps);\nself_size = ns(self);\n\npsucc = 1-pfail;\n\nCPT = zeros(prod(psizes), self_size);\npvals = zeros(1, length(ps));\nfor i=1:prod(psizes)\n  pvals = ind2subv(psizes, i);\n  x = feval(fname, pvals);\n  %fprintf('%d ', [pvals x]); fprintf('\\n');\n  if psucc == 1\n    CPT(i, x) = 1;\n  else\n    CPT(i, x) = psucc;\n    rest = mysetdiff(1:self_size, x);\n    CPT(i, rest) = pfail/length(rest);\n  end\nend\nCPT = reshape(CPT, [psizes self_size]);  \n\nCPD = tabular_CPD(bnet, self, 'CPT',CPT, 'clamped',1);\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/CPDs/@deterministic_CPD/deterministic_CPD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041658, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5737095647190492}}
{"text": "function check = reciprocal_check ( a, b )\n\n%*****************************************************************************80\n%\n%% RECIPROCAL_CHECK checks the parameters of the Reciprocal CDF.\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, B, the parameters of the PDF.\n%    0.0 < A <= B.\n%\n%    Output, logical CHECK, is true if the parameters are legal.\n%\n  if ( a <= 0.0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'RECIPROCAL_CHECK - Fatal error!\\n' );\n    fprintf ( 1, '  A <= 0.0\\n' );\n    check = 0;\n    return\n  end\n\n  if ( b < a ) then\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'RECIPROCAL_CHECK - Fatal error!\\n' );\n    fprintf ( 1, '  B < A\\n' );\n    check = 0;\n    return\n  end\n\n  check = 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/prob/reciprocal_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.5736094040305874}}
{"text": "function pass = test_imag( pref ) \n% Test IMAG\nif ( nargin == 0 ) \n    pref = chebfunpref; \nend\n\ntol = 100*pref.cheb2Prefs.chebfun2eps;\n\nf = chebfun2(@(x,y) cos(x.*y)); \ng = chebfun2(@(x,y) sin(x+y.^2));\n\n% Simple consistency check: \nx = linspace(-1,1,3); \n[xx, yy] = meshgrid(x);\nh = f + 1i *g; \npass(1) = norm( imag( feval(h,xx,yy) ) - feval(g,xx,yy) ) < 10*tol;\npass(2) = norm( imag( h ) - g ) < tol;\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun2/test_imag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.5736094040305872}}
{"text": "function value = daub8_condition ( n )\n\n%*****************************************************************************80\n%\n%% DAUB8_DETERMINANT returns the L1 condition of the DAUB8 matrix.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 January 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Output, real VALUE, the L1 condition.\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  a_norm = sum ( abs ( c(1:8) ) );\n  b_norm = a_norm;\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/daub8_condition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5736093996400721}}
{"text": "function p = abs(p);\n%ABS          Polynomial with absolute values of coefficients\n%\n%   r = abs(p);\n%\n% r_i = abs(p_i), i.e. result is interval polynomial for interval polynomial input\n%\n\n% written  08/28/00     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%\n\n  p.c = abs(p.c);\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/polynom/@polynom/abs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.573609395249557}}
{"text": "function stats = UFstats (A, kind, nometis, skip_chol, skip_dmperm, Z)\n%UFSTATS compute matrix statistics for the UF Sparse Matrix Collection\n% Example:\n%   stats = UFstats (A, kind, nometis, skip_chol, skip_dmperm, Z)\n%\n% A: a sparse matrix\n% kind: a string with the Problem.kind\n% nometis: if nonzero then metis(A,'col') is not used, nor is metis used in the\n%       dmperm+ ordering.\n% Z: empty, or a sparse matrix the same size as A.  Only used for psym and\n%       nzero statistics, described below.\n%\n% Requires amd, cholmod, metis, RBio, and CSparse.  Computes the following\n% statistics, returning them as fields in the stats struct:\n%\n%   nrows           number of rows\n%   ncols           number of columns\n%   nnz             number of entries in A\n%   RBtype          Rutherford/Boeing type\n%   isBinary        1 if binary, 0 otherwise\n%   isReal          1 if real, 0 if complex\n%   cholcand        1 if a candidate for sparse Cholesky, 0 otherwise\n%   nsym            numeric symmetry (0 to 1, where 1=symmetric)\n%   psym            pattern symmetry (0 to 1, where 1=symmetric)\n%   nnzdiag         nnz (diag (A)) if A is square, 0 otherwise\n%   nzero           nnz (Z)\n%   amd_lnz         nnz(L) for chol(C(p,p)) where, C=A+A', p=amd(C)\n%   amd_flops       flop count for chol(C(p,p)) where, C=A+A', p=amd(C)\n%   amd_vnz         nnz in Householder vectors for qr(A(:,colamd(A)))\n%   amd_rnz         nnz in R for qr(A(:,colamd(A)))\n%   metis_lnz       nnz(L) for chol(C(p,p)) where, C=A+A', p=metis(C)\n%   metis_flops     flop count for chol(C(p,p)) where, C=A+A', p=metis(C)\n%   metis_vnz       nnz in Householder vectors for qr(A(:,metis(A,'col')))\n%   metis_rnz       nnz in R for qr(A(:,metis(A,'col')))\n%   nblocks         # of blocks from dmperm\n%   sprank          sprank(A)\n%   nzoff           # of entries not in diagonal blocks from dmperm\n%   ncc             # of strongly connected components\n%   dmperm_lnz      nnz(L), using dmperm plus amd or metis\n%   dmperm_unz      nnz(U), using dmperm plus amd or metis\n%   dmperm_flops    flop count with dperm plus\n%   dmperm_vnz      nnz in Householder vectors for dmperm plus\n%   dmperm_rnz      nnz in R for dmperm plus\n%   posdef          1 if positive definite, 0 otherwise\n%   isND\t    1 if a 2D/3D problem, 0 otherwise\n%\n% The *_lnz, *_unz, and *_flops statistics are not computed for rectangular\n% or structurally singular matrices.  nzoff and the dmperm_* stats are not\n% computed for structurally singular matrices.  If a statistic is not computed,\n% it is set to -2.  If an attempt to compute the statistic was made but failed,\n% it is set to -1.\n%\n% See also UFget, UFindex, amd, metis, RBtype, cs_scc, cs_sqr, dmperm.\n\n% Copyright 2006-2007, Timothy A. Davis\n\n% Requires the SuiteSparse set of packages: CHOLMOD, AMD, COLAMD, RBio, CSparse;\n% and METIS.\n\nif (nargin < 3)\n    nometis = 0 ;\nend\n\n%-------------------------------------------------------------------------------\n% ensure the matrix is sparse\n%-------------------------------------------------------------------------------\n\nif (~issparse (A))\n    A = sparse (A) ;\nend\n\n%-------------------------------------------------------------------------------\n% basic stats\n%-------------------------------------------------------------------------------\n\ntic ;\n[m n] = size (A) ;\nstats.nrows = m ;\nstats.ncols = n ;\nstats.nnz = nnz (A) ;\nstats.RBtype = RBtype (A) ;\t\t\t% Rutherford/Boeing type\nstats.isBinary = (stats.RBtype (1) == 'p') ;\nstats.isReal = (stats.RBtype (1) ~= 'c') ;\n\nfprintf ('RBtype: %s time: %g\\n', stats.RBtype, toc) ;\n\n%-------------------------------------------------------------------------------\n% symmetry and Cholesky candidacy\n%-------------------------------------------------------------------------------\n\n% get the symmetry\ntic ;\n[s xmatched pmatched nzoffdiag nnzdiag] = spsym (A) ;\n\nstats.cholcand = (s >= 6) ; % check if Cholesky candidate\n\nif (m ~= n)\n    stats.nsym = 0 ;\n    stats.psym = 0 ;\nelseif (nzoffdiag > 0)\n    stats.nsym = xmatched / nzoffdiag ;\n    stats.psym = pmatched / nzoffdiag ;\nelse\n    stats.nsym = 1 ;\n    stats.psym = 1 ;\nend\n\nfprintf ('cholcand: %d\\n', stats.cholcand) ;\nfprintf ('nsym: %g psym: %g time: %g\\n', stats.nsym, stats.psym, toc) ;\ntic ;\n\nstats.nnzdiag = nnzdiag ;\n\nif (nargin > 5)\n    stats.nzero = nnz (Z) ;\n\n    % recompute the pattern symmetry with Z included\n    if (m == n)\n\ttry\n\t    AZ = A+Z ;\n\t    if (nnz (AZ) ~= nnz (A) + nnz (Z))\n\t\terror ('A and Z overlap!')\n\t    end\n\t    [s xmatched pmatched nzoffdiag] = spsym (AZ) ;\n\t    clear AZ\n\t    if (nzoffdiag > 0)\n\t\tstats.psym = pmatched / nzoffdiag ;\n\t    else\n\t\tstats.psym = 1 ;\n\t    end\n\tcatch\n\t    fprintf ('failed to compute symmetry of pattern of A+Z\\n') ;\n\tend\n    end\n\nelse\n    stats.nzero = 0 ;\nend\n\nfprintf ('nsym: %g psym: %g time: %g\\n', stats.nsym, stats.psym, toc) ;\ntic ;\n\n%-------------------------------------------------------------------------------\n% intialize ordering statistics\n%-------------------------------------------------------------------------------\n\n% if square, Cholesky of C(p,p) where C=A+A', p = amd(C)\nstats.amd_lnz = -1 ;\t    % nnz (chol (C))\nstats.amd_flops = -1 ;\t    % flop counts for chol (C)\n\n% if square or rectangular\nstats.amd_vnz = -1 ;\t    % nnz (V), upper bound on L, for A(:,colamd(A))\nstats.amd_rnz = -1 ;\t    % nnz (R), upper bound on U, for A(:,colamd(A))\n\n% if square, Cholesky of C(p,p) where C=A+A', p = metis(C)\nstats.metis_lnz = -1 ;\t    % nnz (chol (C))\nstats.metis_flops = -1 ;    % flop counts for chol (C)\n\n% if square or rectangular\nstats.metis_vnz = -1 ;\t    % nnz (V), upper bound on L, for A(:,metis(A))\nstats.metis_rnz = -1 ;\t    % nnz (R), upper bound on U, for A(:,metis(A))\n\n% dmperm analysis\nstats.nblocks = -1 ;\t    % # of blocks in block-triangular form\nstats.sprank = -1 ;\t    % structural rank\nstats.nzoff = -1 ;\t    % # of entries of A in off-diagonal blocks\n\n% cs_scc2\nstats.ncc = -1 ;\t    % # of strongly connected components\n\n% dmperm: best of amd/metis on each square block, best of colamd/metis\n% on rectangular blocks\nstats.dmperm_lnz = -1 ;\t    % nnz (L), for square struct full rank matrices \nstats.dmperm_unz = -1 ;\t    % nnz (U) + nzoff, for square struct full rank mat\nstats.dmperm_flops = -1 ;   % Cholesky flop count of each square block\nstats.dmperm_vnz = -1 ;\t    % nnz (V), upper bound on L\nstats.dmperm_rnz = -1 ;\t    % nnz (R), upper bound on U\n\nstats.isND = -1 ;\t    % 1 if 2D/3D problem, 0 otherwise\n\nd = max (m,n) ;\n\n% if the matrix has a symmetric nonzero pattern, nzoff will always be zero\nif (stats.psym == 1)\n    stats.nzoff = 0 ;\nend\n\n%-------------------------------------------------------------------------------\n% determine if positive definite\n%-------------------------------------------------------------------------------\n\nif (~stats.cholcand)\n\n    % not a candidate for Cholesky, so it cannot be positive definite\n    stats.posdef = 0 ;\n\nelseif (skip_chol)\n\n    % Cholesky was skipped\n    fprintf ('skip Cholesky\\n') ;\n    stats.posdef = -1 ;\n\nelse\n\n    % try chol\n    try\n\t[x, cstats] = cholmod2 (A, ones (stats.ncols,1)) ;\n\trcond = cstats (1) ;\n\tfprintf ('rcond: %g\\n', rcond) ;\n\tstats.posdef = (rcond > 0) ;\n    catch\n\t% chol failed\n\tdisp (lasterr) ;\n\tfprintf ('sparse Cholesky failed\\n') ;\n\tstats.posdef = -1 ;\n    end\n    clear x cstats\nend\n\nfprintf ('posdef: %d time: %g\\n', stats.posdef, toc) ;\ntic ;\n\n%-------------------------------------------------------------------------------\n% transpose A if m < n, for ordering methods\n%-------------------------------------------------------------------------------\n\nif (m < n)\n    try\n\tA = A' ;\t\t    % A is now tall and thin, or square\n    catch\n\tdisp (lasterr) ;\n\tfprintf ('transpose failed...\\n') ;\n\treturn ;\n    end\n    [m n] = size (A) ;\nend\n\nif (~isreal (A))\n    try\n\tA = spones (A) ;\n    catch\n\tdisp (lasterr) ;\n\tfprintf ('conversion from complex failed...\\n') ;\n\treturn ;\n    end\nend\n\nfprintf ('computed A transpose if needed, time: %g\\n', toc) ;\ntic ;\n\n%-------------------------------------------------------------------------------\n% order entire matrix with AMD and METIS, if square\n%-------------------------------------------------------------------------------\n\nif (m == n)\n\n    tic ;\n    try\n\tif (stats.RBtype (2) == 'u')\n\t    C = A|A' ;\n\telse\n\t    C = A ;\n\tend\n    catch\n\tdisp (lasterr) ;\n\tfprintf ('A+A'' failed\\n') ;\n    end\n    fprintf ('computed A+A'', time: %g\\n', toc) ;\n\n    % order the whole matrix with AMD\n    tic ;\n    try\n\tp = amd (C) ;\n\tc = symbfact (C (p,p)) ;\n\tstats.amd_lnz = sum (c) ;\n\tstats.amd_flops = sum (c.^2) ;\n    catch\n\tdisp (lasterr) ;\n\tfprintf ('amd failed\\n') ;\n    end\n    clear p c\n    fprintf ('AMD   lnz %d flops %g time: %g\\n', ...\n\tstats.amd_lnz, stats.amd_flops, toc) ;\n\n    % order the whole matrix with METIS\n    tic ;\n    try\n\tp = metis (C) ;\n\tc = symbfact (C (p,p)) ;\n\tstats.metis_lnz = sum (c) ;\n\tstats.metis_flops = sum (c.^2) ;\n    catch\n\tdisp (lasterr) ;\n\tfprintf ('metis failed\\n') ;\n    end\n    clear p c C\n    fprintf ('METIS lnz %d flops %g time: %g\\n', ...\n\tstats.metis_lnz, stats.metis_flops, toc) ;\n\nelse\n\n    % not computed if rectangular\n    stats.amd_lnz = -2 ;\n    stats.amd_flops = -2 ;\n    stats.metis_lnz = -2 ;\n    stats.metis_flops = -2 ;\n\nend\n\n%-------------------------------------------------------------------------------\n% order entire matrix with COLAMD, for LU bounds\n%-------------------------------------------------------------------------------\n\ntic ;\ntry\n    % do not ignore any rows, and do not do etree postordering\n    q = colamd2mex (A, [d 10]) ;\n    [vnz,rnz] = cs_sqr (A (:,q)) ;\n    stats.amd_rnz = rnz ;\n    stats.amd_vnz = vnz ;\ncatch\n    disp (lasterr) ;\n    fprintf ('colamd2 and cs_sqr failed\\n') ;\nend\nclear q\nfprintf ('COLAMD rnz %d vnz %d time: %g\\n', stats.amd_rnz, stats.amd_vnz, toc) ;\ntic ;\n\n%-------------------------------------------------------------------------------\n% order entire matrix with METIS, for LU bounds\n%-------------------------------------------------------------------------------\n\nif (~nometis)\n    try\n\tq = metis (A, 'col') ;\n\t[vnz,rnz] = cs_sqr (A (:,q)) ;\n\tstats.metis_rnz = rnz ;\n\tstats.metis_vnz = vnz ;\n    catch\n\tdisp (lasterr) ;\n\tfprintf ('metis(A''*A) and cs_sqr failed\\n') ;\n    end\nend\nclear q\nfprintf ('METIS  rnz %d vnz %d time: %g\\n', ...\n    stats.metis_rnz, stats.metis_vnz, toc) ;\ntic ;\n\n%-------------------------------------------------------------------------------\n% strongly connected components\n%-------------------------------------------------------------------------------\n\ntry\n    % find the # of strongly connected components of the graph of a square A,\n    % or # of connected components of the bipartite graph of a rectangular A.\n    % [p,q,r,s] = cs_scc2 (A) ;\n    if (m == n)\n\t[p r] = cs_scc (A) ;\n    else\n\t[p r] = cs_scc (spaugment (A)) ;\n    end\n    stats.ncc = length (r) - 1 ;\n    clear p r\ncatch\n    disp (lasterr) ;\n    fprintf ('cs_scc failed\\n') ;\nend\n\nfprintf ('scc %d, time: %g\\n', stats.ncc, toc) ;\ntic ;\n\n%-------------------------------------------------------------------------------\n% isND\n%-------------------------------------------------------------------------------\n\ns = 0 ;\nif (strfind (kind, 'structural'))\n    s = 1 ;\nelseif (strfind (kind, 'fluid'))\n    s = 1 ;\nelseif (strfind (kind, '2D'))\n    s = 1 ;\nelseif (strfind (kind, 'reduction'))\n    s = 1 ;\nelseif (strfind (kind, 'electromagnetics'))\n    s = 1 ;\nelseif (strfind (kind, 'semiconductor'))\n    s = 1 ;\nelseif (strfind (kind, 'thermal'))\n    s = 1 ;\nelseif (strfind (kind, 'materials'))\n    s = 1 ;\nelseif (strfind (kind, 'acoustics'))\n    s = 1 ;\nelseif (strfind (kind, 'vision'))\n    s = 1 ;\nelseif (strfind (kind, 'robotics'))\n    s = 1 ;\nend\nstats.isND = s ;\n\nfprintf ('isND %d\\n', stats.isND) ;\n\n%-------------------------------------------------------------------------------\n% Dulmage-Mendelsohn permutation, and order each block\n%-------------------------------------------------------------------------------\n\nif (skip_dmperm)\n    fprintf ('skip cs_dmperm, known irreducible\\n') ;\nelse\n    try\n        % find the Dulmage-Mendelsohn decomposition\n        [p,q,r,s,cc,rr] = cs_dmperm (A) ;\n        nblocks = length (r) - 1 ;\n        stats.nblocks = nblocks ;\n        stats.sprank = rr(4)-1 ;\n    catch\n        disp (lasterr) ;\n        fprintf ('cs_dmperm failed\\n') ;\n    end\nend\n\nfprintf ('sprank %d, time: %g\\n', stats.sprank, toc) ;\nfprintf ('nblocks %d\\n', stats.nblocks) ;\ntic\n\nok_square = 1 ;\nok_vnz = 1 ;\n\ntry\n\n    mm = diff (r) ;\n    nn = diff (s) ;\n    square = all (mm == nn) ;\n\n    if (~square)\n\n\t% not computed if the matrix is rectangular\n\tstats.dmperm_lnz = -2 ;\n\tstats.dmperm_unz = -2 ;\n\tstats.dmperm_flops = -2 ;\n\n    end\n\n    if (stats.sprank < min (m,n))\n\n\t% do not report DMPERM results for structurally singular matrices\n\tstats.nzoff = -2 ;\n\tstats.dmperm_lnz = -2 ;\n\tstats.dmperm_unz = -2 ;\n\tstats.dmperm_flops = -2 ;\n\tstats.dmperm_vnz = -2 ;\n\tstats.dmperm_rnz = -2 ;\n\n    elseif (nblocks == n && m == n)\n\n\t% square triangular or diagonal\n\tC = A (p,q) ;\n\tclear p q r s\n\n\tstats.nzoff = nnz (triu (C, 1)) ;\n\tstats.dmperm_lnz = n ;\n\tstats.dmperm_unz = n + stats.nzoff ;\n\tstats.dmperm_flops = n ;\n\tstats.dmperm_vnz = n ;\n\tstats.dmperm_rnz = nnz (C) ;\n\n    elseif (nblocks == 1 && m == n)\n\n\t% only one block of structural full rank, so don't redo analysis\n\tclear p q r s\n\n\tstats.nzoff = 0 ;\n\tif (stats.metis_lnz < 0 || stats.amd_lnz < stats.metis_lnz)\n\t    stats.dmperm_lnz = stats.amd_lnz ;\n\t    stats.dmperm_unz = stats.amd_lnz ;\n\t    stats.dmperm_flops = stats.amd_flops ;\n\telse\n\t    stats.dmperm_lnz = stats.metis_lnz ;\n\t    stats.dmperm_unz = stats.metis_lnz ;\n\t    stats.dmperm_flops = stats.metis_flops ;\n\tend\n\n\tif (stats.metis_vnz < 0 || stats.amd_rnz < stats.metis_rnz)\n\t    stats.dmperm_vnz = stats.amd_vnz ;\n\t    stats.dmperm_rnz = stats.amd_rnz ;\n\telse\n\t    stats.dmperm_vnz = stats.metis_vnz ;\n\t    stats.dmperm_rnz = stats.metis_rnz ;\n\tend\n\n    else\n\n\t% analyze each block of the permuted matrix\n\tC = A (p,q) ;\n\tclear p q\n\n\tnzoff = nnz (C) ;\n\tlnz = 0 ;\n\tunz = 0 ;\n\tflops = 0 ;\n\tvnz = 0 ;\n\trnz = 0 ;\n\n\tfor k = 1:nblocks\n\t    i1 = r (k) ;\n\t    i2 = r (k+1) - 1 ;\n\t    j1 = s (k) ;\n\t    j2 = s (k+1) - 1 ;\n\n\t    if (i2-i1 == 1 && j2-j1 == 1)\n\t\t% singleton case\n\t\tnzoff = nzoff - 1 ;\n\t\tunz = unz + 1 ;\n\t\tlnz = lnz + 1 ;\n\t\tflops = flops + 1 ;\n\t\trnz = rnz + 1 ;\n\t\tvnz = vnz + 1 ;\n\t\tcontinue ;\n\t    end\n\n\t    % get the kth block\n\t    S = C (i1:i2, j1:j2) ;\n\t    [ms ns] = size (S) ;\n\t    nzoff = nzoff - nnz (S) ;\n\n\t    if (ok_square)\n\t\ttry\n\t\t    if (square)\n\n\t\t\t% all blocks are square, analyze a square block\n\t\t\t% best of amd and metis\n\t\t\tif (nometis)\n\t\t\t    [pblock c] = analyze (S|S', 'sym', 1) ;\n\t\t\telse\n\t\t\t    [pblock c] = analyze (S|S', 'sym', 3) ;\n\t\t\tend\n\t\t\tlnzblock = sum (c) ;\n\t\t\tunz = unz + lnzblock ;\n\t\t\tlnz = lnz + lnzblock ;\n\t\t\tflops = flops + sum (c.^2) ;\n\t\t\tclear c pblock\n\n\t\t    end\n\t\tcatch\n\t\t    % ordering failed, but keep going to compute nzoff\n\t\t    ok_square = 0 ;\n\t\tend\n\t    end\n\n\t    if (ok_vnz)\n\t\ttry\n\n\t\t    % analyze a rectangular block, or LU bounds for square block\n\t\t    if (ms < ns)\n\t\t\tS = S' ;\n\t\t    end\n\t\t    % best of amd and metis\n\t\t    try\n\t\t\tif (nometis)\n\t\t\t    pblock = analyze (S, 'col', 1) ;\n\t\t\telse\n\t\t\t    pblock = analyze (S, 'col', 3) ;\n\t\t\tend\n\t\t    catch\n\t\t\tpblock = colamd2mex (S, [d 10]) ;\n\t\t    end\n\t\t    [vnz2,rnz2] = cs_sqr (S (:, pblock)) ;\n\t\t    rnz = rnz + rnz2 ;\n\t\t    vnz = vnz + vnz2 ;\n\n\t\tcatch\n\t\t    % ordering failed, but keep going to compute nzoff\n\t\t    ok_vnz = 0 ;\n\t\tend\n\t    end\n\n\t    clear S pblock\n\n\tend\n\n\tstats.nzoff = nzoff ;\n\n\tif (ok_square)\n\t    if (~square)\n\t\tstats.dmperm_unz = -2 ;\n\t\tstats.dmperm_lnz = -2 ;\n\t\tstats.dmperm_flops = -2 ;\n\t    else\n\t\tstats.dmperm_lnz = lnz ;\n\t\tstats.dmperm_unz = unz + nzoff ;\n\t\tstats.dmperm_flops = flops ;\n\t    end\n\tend\n\n\tif (ok_vnz)\n\t    stats.dmperm_vnz = vnz ;\n\t    stats.dmperm_rnz = rnz + nzoff ;\n\tend\n\n\tclear C r s\n\n    end\n\n    if (~ok_square)\n\tdisp (lasterr) ;\n\tfprintf ('cs_dmperm (square: lnz, unz, flops) ordering failed\\n') ;\n    end\n    if (~ok_vnz)\n\tdisp (lasterr) ;\n\tfprintf ('cs_dmperm (LU bounds: vnz, rnz) ordering failed\\n') ;\n    end\n\ncatch\n    disp (lasterr) ;\n    fprintf ('cs_dmperm ordering and nzoff failed (or skipped)\\n') ;\nend\n\nfprintf ('dmperm stats done, time %g\\n', toc) ;\nfprintf ('UFstats done\\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/UFcollection/UFstats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.5736093830584202}}
{"text": "%GETNEXTCLIQUES Find a pair of cliques ready for message passing\n%   [i, j] = GETNEXTCLIQUES(P, messages) finds ready cliques in a given\n%   clique tree, P, and a matrix of current messages. Returns indices i and j\n%   such that clique i is ready to transmit a message to clique j.\n%\n%   We are doing clique tree message passing, so\n%   do not return (i,j) if clique i has already passed a message to clique j.\n%\n%\t messages is a n x n matrix of passed messages, where messages(i,j)\n% \t represents the message going from clique i to clique j. \n%   This matrix is initialized in CliqueTreeCalibrate as such:\n%      MESSAGES = repmat(struct('var', [], 'card', [], 'val', []), N, N);\n%\n%   If more than one message is ready to be transmitted, return \n%   the pair (i,j) that is numerically smallest. If you use an outer\n%   for loop over i and an inner for loop over j, breaking when you find a \n%   ready pair of cliques, you will get the right answer.\n%\n%   If no such cliques exist, returns i = j = 0.\n%\n%   See also CLIQUETREECALIBRATE\n%\n% Copyright (C) Daphne Koller, Stanford University, 2012\n\n\nfunction [i, j] = GetNextCliques(P, messages)\n\n% initialization\n% you should set them to the correct values in your code\ni = 0;\nj = 0;\n\nN = length(messages);\nmess = ones(size(messages));\n\n\nfor k = 1:N\n\tfor l = 1:N\n\t\tmess(k,l) = length(messages(k,l).var)!=0;\n\tend\nend\n%mess=messages;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% YOUR CODE HERE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfor k = 1:N\n\tfor l = 1:N\n\t\tif P.edges(k,l)==0 || mess(k,l)==1\n\t\t\tcontinue;\n\t\tend\n\t\tkmess = mess(:,k)';\n\t \tedges = P.edges(:,k);\t\n\t\tedges(l) = 0;\n\t\tkmess(l) = 0;\n\t\t%if sum(kmess) == sum(P.edges(k,:))-1\n\t\tif sum(kmess' == edges)==N\n\t\t\ti = k;\n\t\t\tj = l;\n\t\t\treturn;\n\t\tend\n\t\tif i!=0\n\t\t\tbreak;\n\t\tend\n\tend\n\tif i!=0\n\t\tbreak;\n\tend\nend\nreturn;\n", "meta": {"author": "anhncs", "repo": "Probabilistic-Graphical-Models", "sha": "7fd4ef255db59ecbfe1a134cadbc4be5ca839894", "save_path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models", "path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models/Probabilistic-Graphical-Models-7fd4ef255db59ecbfe1a134cadbc4be5ca839894/4.Exact Inference/GetNextCliques.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.5735945824057792}}
{"text": "function [x,state] = struct_poly(z,task,t)\n%STRUCT_POLY Matrix with columns as polynomials.\n%   [x,state] = struct_poly(z,[],t) computes a matrix x in which the\n%   jth column is equal to the polynomial\n%\n%      polyval(z(j,:),s)\n%\n%   evaluated at the points s, defined as\n%\n%      (t-0.5*(min(t)+max(t)))/(0.5*(max(t)-min(t))).\n%\n%   The degree of the polynomial is equal to size(z,2)-1. The structure\n%   state stores information which is reused in computing the right and\n%   left Jacobian-vector products.\n%\n%   struct_poly(z,task,t) computes the right or left Jacobian-vector\n%   product of this transformation, depending on the structure task. Use\n%   the structure state and add the field 'r' of the same shape as z or the\n%   field 'l' of the same shape as x to obtain the structure task for\n%   computing the right and left Jacobian-vector products\n%   \n%      (dF(:)/dz(:).')*task.r(:) and\n%      (dF(:)/dz(:).')'*task.l(:) + conj((dF(:)/dconj(z(:)).')'*task.l(:)),\n%   \n%   respectively. Here, F(z) represents this transormation, (:) signifies\n%   vectorization and the derivative w.r.t. z (conj(z)) is a partial\n%   derivative which treats conj(z) (z) as constant. The output has the\n%   same shape as x or z for the right and left Jacobian-vector products,\n%   respectively.\n%   \n%   See also struct_rational, struct_rbf.\n\n%   Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n%            Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)\n%            Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)\n%\n%   References:\n%   [1] L. Sorber, M. Van Barel, L. De Lathauwer, \"Structured data fusion,\"\n%       ESAT-SISTA Internal Report 13-177, KU Leuven, 2013.\n\nif nargin < 2, task = []; end\nif nargin < 3\n    error('struct_poly:t','Please supply evaluation points.');\nend\n\nif isempty(task)\n    [x,state] = struct_rational({z,[]},task,t);\nelseif ~isempty(task.r)\n    task.r = {task.r,[]};\n    [x,state] = struct_rational({z,[]},task,t);\nelseif ~isempty(task.l)\n    [x,state] = struct_rational({z,[]},task,t); x = x{1};\nend\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+tensorlab/struct_poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5735725544176885}}
{"text": "%INTBDR Integation of expression over boundaries.\n%\n%   [ VAL ] = INTBDR( S_EXPR, PROB, IND_B, I_CUB, SOLNUM, IND_S )\n%   Integrates the expression S_EXPR over the boundaries indicated in\n%   IND_B. PROB is a valid finite element problem struct, and I_CUB\n%   specifies the numerical integration rule. IND_S optionally\n%   specifies which subdomain to use as reference for internal/\n%   interior boundaries (normals point out from these subdomains).\n%\n%       Input       Value/[Size]           Description\n%       -----------------------------------------------------------------------------------\n%       s_expr      string                 Expression to integrate\n%       prob        struct                 Finite element problem struct\n%       ind_b       [1,n_bdr]              Boundary numbers (default all)\n%       i_cub       scalar                 Numerical integration rule (default 2)\n%       solnum      scalar {n_sols}        Solution number/time to evaluate\n%       ind_s       integer array          Integration subdomains for internal boundaries\n%                                                                                         .\n%       Output      Value/[Size]           Description\n%       -----------------------------------------------------------------------------------\n%       val         scalar                 Result of integration\n%\n%   See also INTSUBD, MINMAXSUBD, MINMAXBDR\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/intbdr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.573572540618674}}
{"text": "function exact = p47_exact ( )\n\n%*****************************************************************************80\n%\n%% P47_EXACT returns the exact integral for problem 47.\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  exact = - 4.0 / 9.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/p47_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943805178138, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.5735725382619432}}
{"text": "function N=patchnormals(FV)\n% This function PATCHNORMALS calculates the normals of a triangulated\n% mesh. PATCHNORMALS calls the patchnormal_double.c mex function which \n% first calculates the normals of all faces, and after that calculates \n% the vertice normals from the face normals weighted by the angles \n% of the faces.\n%\n% N=patchnormals(FV);\n%\n% Inputs,\n%   FV : A struct containing FV.faces with a facelist Nx3 and FV.vertices\n%        with a Nx3 vertices list. Such a structure is created by Matlab\n%        Patch function\n% Outputs,\n%   N : A Mx3 list with the normals of all vertices\n%\n% Example,\n%   % Compile the c-coded function\n%   mex patchnormals_double.c -v\n%\n%   % Load a triangulated mesh of a sphere\n%   load sphere; \n%\n%   % Calculate the normals\n%   N=patchnormals(FV);\n%\n%   % Show the normals\n%   figure, patch(FV,'FaceColor',[1 0 0]); axis square; hold on;\n%   for i=1:size(N,1);\n%       p1=FV.vertices(i,:); p2=FV.vertices(i,:)+10*N(i,:);       \n%       plot3([p1(1) p2(1)],[p1(2) p2(2)],[p1(3) p2(3)],'g-');\n%   end       \n%\n% Function is written by D.Kroon University of Twente (June 2009)\n\n\nsizev=size(FV.vertices);\n% Check size of vertice array\nif((sizev(2)~=3)||(length(sizev)~=2))\n    error('patchnormals:inputs','The vertice list is not a m x 3 array')\nend\n\nsizef=size(FV.faces);\n% Check size of vertice array\nif((sizef(2)~=3)||(length(sizef)~=2))\n    error('patchnormals:inputs','The vertice list is not a m x 3 array')\nend\n\n% Check if vertice indices exist\nif(max(FV.faces(:))>size(FV.vertices,1))\n    error('patchnormals:inputs','The face list contains an undefined vertex index')\nend\n\n% Check if vertice indices exist\nif(min(FV.faces(:))<1)\n    error('patchnormals:inputs','The face list contains an vertex index smaller then 1')\nend\n\n[Nx,Ny,Nz]=patchnormals_double(double(FV.faces(:,1)),double(FV.faces(:,2)),double(FV.faces(:,3)),double(FV.vertices(:,1)),double(FV.vertices(:,2)),double(FV.vertices(:,3)));\n\nN=zeros(length(Nx),3);\nN(:,1)=Nx;\nN(:,2)=Ny;\nN(:,3)=Nz;\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/meshTools/renderpatch_version0/patchnormals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5735725378976025}}
{"text": "function ind = squareNeighbors2(RowsCols,Nid)\n% return the neighbor ids in a square grid\n%\n%\n\n[col,row] = meshgrid(1:RowsCols(2),1:RowsCols(1));\n\ndRow = [1 -1 0  0 1  1 -1 -1];\ndCol = [0  0 1 -1 1 -1  1 -1];\n\nif nargin == 2\n  ind = calcInd(Nid);\nelse\n  \n  ind = zeros([RowsCols,length(dRow)]);\n  for Nid = 1:length(dRow)\n    ind(:,:,Nid) = calcInd(Nid);\n  end\n  \nend\n \n  function indLocal = calcInd(Nid)\n  \n  nrow = row + dRow(Nid);\n  ncol = col + dCol(Nid);\n  \n  % ensure coordinates are within the range\n  ncol = max(min(ncol,RowsCols(2)),1);\n  nrow = max(min(nrow,RowsCols(1)),1);\n\n  indLocal = sub2ind(RowsCols,nrow,ncol);\n  \n  end\n  \nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/geometry_tools/squareNeighbors2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.5735725261878057}}
{"text": "% op_rmNworstaverages.m\n% Jamie Near, McGill University 2014.\n% \n% USAGE:\n% [out,metric,badAverages]=op_rmNworstaverages(in,n);\n% \n% DESCRIPTION:\n% Removes motion corrupted averages from a dataset containing multiple\n% averages.  The N most badly motion corrupted averages are discarded.\n% \n% INPUTS:\n% in         = input data in matlab structure format\n% n          = number of bad averages to remove\n%\n% OUTPUTS:\n% out         = Output dataset following removal of motion corrupted averages.\n% metric      = Vector of unlikeness metrics corresponding to all input\n%               averages. \n% badAverages = Indices of the averages that were removed. \n\nfunction [out,metric,badAverages]=op_rmNworstaverages(in,n);\n\nif in.flags.averaged\n    error('ERROR:  Averaging has already been performed!  Aborting!');\nend\n\nif ~in.flags.addedrcvrs\n    error('ERROR:  Receivers should be combined first!  Aborting!');\nend\n\n%first, make a metric by subtracting all averages from the first average, \n%and then taking the sum of all all the spectral points.  \nif in.dims.subSpecs>0\n    SS=in.sz(in.dims.subSpecs);\nelse\n    SS=1;\nend\ninfilt=op_filter(in,10);\n%inavg=op_averaging(infilt);\ninavg=op_median(infilt);\nfor k=1:in.sz(in.dims.averages)\n    for m=1:SS\n            metric(k,m)=sum((real(infilt.specs(:,k,m))-(real(inavg.specs(:,m)))).^2);\n    end\nend\n\n%find the average and standard deviation of the metric\navg=mean(metric);\nstdev=std(metric);\n\n%Now z-transform the metric so that it is centered about zero, and they\n%have a standard deviation of 1.0.  \nzmetric=(metric-avg)/stdev;\n\nfor m=1:SS\n    P(m,:)=polyfit([1:in.sz(in.dims.averages)]',zmetric(:,m),2);\n    figure\n    plot([1:in.sz(in.dims.averages)],zmetric(:,m),'.',[1:in.sz(in.dims.averages)],polyval(P(m,:),[1:in.sz(in.dims.averages)]));\nend\n\n%Now make a mask that represents the locations of the averages \n%whose metric values are more than nsd standard deviations away from the \n%mean metric value.\n\n%first sort the zmetric array to find the n highest values:\n\n[zmetric_sorted,inds]=sort(zmetric-polyval(P,[1:in.sz(in.dims.averages)])',1,'descend');\n\nmask=zeros(size(zmetric));\n\n\nfor l=1:SS\n    %mask(:,l)=metric(:,l)>(avg(l)+(nsd*stdev(l))) | metric(:,l)<(avg(l)-(nsd*stdev(l)));\n    %mask(:,l)=metric(:,l)>(polyval(P(l,:),[1:in.sz(in.dims.averages)])'+(nsd*stdev(l))) | metric(:,l)<(polyval(P(l,:),[1:in.sz(in.dims.averages)])'-(nsd*stdev(l)));\n    %mask(:,l)=metric(:,l)>(polyval(P(l,:),[1:in.sz(in.dims.averages)])'+(nsd*stdev(l)));\n    %mask(:,l)=(metric(:,l)-polyval(P(l,:),[1:in.sz(in.dims.averages)])')==max((metric(:,l)-polyval(P(l,:),[1:in.sz(in.dims.averages)])'));\n    for b=1:n\n        mask(inds(b),l)=1;\n    end\nend\n\n\n%Unfortunately, if one average is corrupted, then all of the subspecs\n%corresponding to that average have to be thrown away.  Therefore, take the\n%minimum intensity projection along the subspecs dimension to find out\n%which averages contain at least one corrupted subspec:\nif size(mask,2)>1\n    mask=sum(mask')'>0;\nend\n\n%now the corrupted and uncorrupted average numbers are given by:\nbadAverages=find(mask);\ngoodAverages=find(~mask);\n\n%make a new fids array containing only good averages\nfids=in.fids(:,goodAverages,:,:);\n\n%%re-calculate Specs using fft\nspecs=fftshift(ifft(fids,[],in.dims.t),in.dims.t);\n\n%re-calculate the sz variable\nsz=size(fids);\n\n%FILLING IN DATA STRUCTURE\nout=in;\nout.fids=fids;\nout.specs=specs;\nout.sz=sz;\nout.averages=length(goodAverages) * in.rawSubspecs;\n\n%FILLING IN THE FLAGS\nout.flags=in.flags;\nout.flags.writtentostruct=1;\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/processingTools/op_rmNworstaverages.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5735499001285194}}
{"text": "function [K] = ku1u1(x, xp, hyp, i)\n\nlogsigma = hyp(1);\nlogtheta = hyp(2);\n\nn_x = size(x,1);\nn_xp = size(xp,1);\n\nx = repmat(x,1,n_xp);\nxp = repmat(xp',n_x,1);\n\nswitch i\n\n\ncase 0\n\nK=exp(1).^(logsigma+(-1/2).*exp(1).^((-1).*logtheta).*(x+(-1).*xp).^2);\n\n\ncase 1 % logsigma\n\nK=exp(1).^(logsigma+(-1/2).*exp(1).^((-1).*logtheta).*(x+(-1).*xp).^2);\n\n\ncase 2 % logtheta\n\nK=(1/2).*exp(1).^(logsigma+(-1).*logtheta+(-1/2).*exp(1).^((-1).*logtheta) ...\n  .*(x+(-1).*xp).^2).*(x+(-1).*xp).^2;\n\n\notherwise\n        \n        K = zeros(n_x, n_xp);\nend\n\nif K == 0\n\n    K = zeros(n_x, n_xp);\n\nend\n\nend\n", "meta": {"author": "maziarraissi", "repo": "HPM", "sha": "21a7429cceb55d5ab688256db75ac360e2d8a925", "save_path": "github-repos/MATLAB/maziarraissi-HPM", "path": "github-repos/MATLAB/maziarraissi-HPM/HPM-21a7429cceb55d5ab688256db75ac360e2d8a925/Kernels/Fractional/+k11/ku1u1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5735498767146314}}
{"text": "% predicting numerical values using Logistic Regression\nclear all;\nformat long\ndisp('===== Logistic Regression ====');\ndisp('Reading featur vector');\n\n\n\nfor feat = 1:3\n    featurs = csvread('data\\forWeka_featuresonly.csv');\n    num_data = 50%size(featurs,1); %5000;\n    disp(sprintf('Number of datapoints %d',num_data))\n    \n    possiblefeaturizations =  {'bernouli', 'tfidf','multinomial'};\n    %featurization = 'bernouli'%'tfidf'%'tfidf'%'multinomial'%'tfidf' %'multinomial'; % 'bernouli', 'tfidf'\n    featurization  = possiblefeaturizations{feat}\n    \n    \n    featurs = featurs(:,2:size(featurs,2));\n    if strcmp(featurization,'multinomial')\n        %just pass\n    elseif strcmp(featurization,'bernouli')\n        featurs = double(featurs>0);\n    elseif strcmp(featurization,'tfidf')\n        occurance = (featurs>0);\n        idf = log(size(featurs,1)./sum(occurance));\n        featurs = featurs.*repmat( idf, size(featurs,1),1);\n    end\n    \n    \n    size_training = floor(.8*num_data);\n    \n    \n    trainingset = featurs(1:size_training,:);\n    testset = featurs((size_training+1):num_data,:);\n    \n    \n    disp('Splitting up data into training/test sets');\n    [num,txt,raw] = xlsread('data\\final104.xls');\n    \n    % reading the description of each shoe\n    descriptions = raw(2:size(raw,1),2);\n    style_ratings = num(1:size(num,1),1);\n    comfort_ratings = num(1:size(num,1),4);\n    overal_ratings = num(1:size(num,1),5);\n    \n    % only take m data points\n    m=num_data;\n    descriptions = descriptions(1:m);\n    style_ratings = style_ratings(1:m);\n    comfort_ratings = comfort_ratings(1:m);\n    overal_ratings = overal_ratings(1:m);\n    \n    responsevals = [style_ratings, comfort_ratings, overal_ratings];\n    \n    responsevals_training = responsevals(1:size_training,:);\n    responsevals_test = responsevals((size_training+1):num_data,:);\n    \n    disp('Logistic Regression');\n    % \n    \n    tic;\n    \n    predictions = [];\n    actual = [];\n    for i =1:3\n        a = responsevals_training(:,i);\n        b = responsevals_test(:,i)';\n        [COEFF,SCORE] = princomp(trainingset);\n        regresscoeff = mnrfit(SCORE,a);\n        C2 = (regresscoeff'*(testset'));\n        predictions = [predictions, C2'];\n        actual = [actual, b'];\n    end\n    \n    \n    MSE = mean(sum(((predictions-actual).^2)'))\n    toc;\n    \nend\n", "meta": {"author": "faridani", "repo": "MatlabNLP", "sha": "e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f", "save_path": "github-repos/MATLAB/faridani-MatlabNLP", "path": "github-repos/MATLAB/faridani-MatlabNLP/MatlabNLP-e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f/sandboxes/siamak sandbox/multivariate6D/NOT- logisticRegression_generalized.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059267, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5735482824707203}}
{"text": "function [parameters, LL, ht, VCVrobust, VCV, scores, diagnostics] = tarch(epsilon, p, o, q, error_type, tarch_type, startingvals, options)\n% TARCH(P,O,Q) parameter estimation with different error distributions:\n% Normal, Students-T, Generalized Error Distribution, Skewed T\n% Estimation of ARCH or GARCH models if o=0 and tarch_type=2\n% Estimation of TARCH or GJR asymmetric models if o>0 and tarch_type=1 or 2\n%\n% USAGE:\n%   [PARAMETERS] = tarch(EPSILON,P,O,Q)\n%   [PARAMETERS,LL,HT,VCVROBUST,VCV,SCORES,DIAGNOSTICS] = \n%                                   tarch(EPSILON,P,O,Q,ERROR_TYPE,TARCH_TYPE,STARTINGVALS,OPTIONS)\n%\n% INPUTS:\n%   EPSILON      - A column of mean zero data\n%   P            - Positive, scalar integer representing the number of symmetric innovations\n%   O            - Non-negative scalar integer representing the number of asymmetric innovations (0\n%                    for symmetric processes)    \n%   Q            - Non-negative, scalar integer representing the number of lags of conditional\n%                    variance (0 for ARCH) \n%   ERROR_TYPE   - [OPTIONAL] The error distribution used, valid types are:\n%                    'NORMAL'    - Gaussian Innovations [DEFAULT]\n%                    'STUDENTST' - T distributed errors\n%                    'GED'       - Generalized Error Distribution\n%                    'SKEWT'     - Skewed T distribution\n%   TARCH_TYPE   - [OPTIONAL] The type of variance process, either\n%                    1 - Model evolves in absolute values\n%                    2 - Model evolves in squares [DEFAULT]\n%   STARTINGVALS - [OPTIONAL] A (1+p+o+q), plus 1 for STUDENTST OR GED (nu), plus 2 for SKEWT\n%                    (nu,lambda), vector of starting values. \n%                     [omega alpha(1) ... alpha(p) gamma(1) ... gamma(o) beta(1) ... beta(q) [nu lambda]]'.\n%   OPTIONS      - [OPTIONAL] A user provided options structure. Default options are below.\n%\n% OUTPUTS:\n%   PARAMETERS   - A 1+p+o+q column vector of parameters with\n%                  [omega alpha(1) ... alpha(p) gamma(1) ... gamma(o) beta(1) ... beta(q) [nu lambda]]'.\n%   LL           - The log likelihood at the optimum\n%   HT           - The estimated conditional variances\n%   VCVROBUST    - Robust parameter covariance matrix\n%   VCV          - Non-robust standard errors (inverse Hessian)\n%   SCORES       - Matrix of scores (# of params by t)\n%   DIAGNOSTICS  - Structure of optimization outputs and other values useful for functions calling TARCH.\n% \n% COMMENTS:\n% The following (generally wrong) constraints are used:\n%   (1) omega > 0\n%   (2) alpha(i) >= 0 for i = 1,2,...,p\n%   (3) gamma(i) + alpha(i) > 0 for i=1,...,o\n%   (3) beta(i)  >= 0 for i = 1,2,...,q\n%   (4) sum(alpha(i) + 0.5*gamma(j) + beta(k)) < 1 for i = 1,2,...p and\n%   j = 1,2,...o, k=1,2,...,q\n%   (5) nu>2 of Students T and nu>1 for GED\n%   (6) -.99<lambda<.99 for Skewed T\n%\n%   The conditional variance, h(t), of a TARCH(P,O,Q) process is modeled as follows:\n%\n%    g(h(t)) = omega\n%            + alpha(1)*f(r_{t-1}) + ... + alpha(p)*f(r_{t-p})+...\n%            + gamma(1)*I(t-1)*f(r_{t-1}) +...+ gamma(o)*I(t-o)*f(r_{t-o})+...\n%            beta(1)*g(h(t-1)) +...+ beta(q)*g(h(t-q))\n%\n%     where f(x) = abs(x)  if tarch_type=1\n%          g(x) = sqrt(x) if tarch_type=1\n%          f(x) = x^2     if tarch_type=2\n%          g(x) = x       if tarch_type=2\n%\n%   Default Options\n%    options  =  optimset('fminunc');\n%    options  =  optimset(options , 'TolFun'      , 1e-005);\n%    options  =  optimset(options , 'TolX'        , 1e-005);\n%    options  =  optimset(options , 'Display'     , 'iter');\n%    options  =  optimset(options , 'Diagnostics' , 'on');\n%    options  =  optimset(options , 'LargeScale'  , 'off');\n%    options  =  optimset(options , 'MaxFunEvals' , '400*numberOfVariables');\n%\n%  See also TARCH_LIKELIHOOD, TARCH_CORE, TARCH_PARAMETER_CHECK, TARCH_STARTING_VALUES,\n%  TARCH_TRANSFORM, TARCH_ITRANSFORM \n%\n%  You should use the MEX files (or compile if not using Win64 Matlab) as they provide speed ups of\n%  approx 100 times relative to the m file.\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3    Date: 9/1/2005\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch nargin\n    case 4\n        [p,o,q,error_type,tarch_type,startingvals,options]=tarch_parameter_check(epsilon, p, o, q);\n    case 5\n        [p,o,q,error_type,tarch_type,startingvals,options]=tarch_parameter_check(epsilon, p, o, q, error_type);\n    case 6\n        [p,o,q,error_type,tarch_type,startingvals,options]=tarch_parameter_check(epsilon, p, o, q, error_type, tarch_type);\n    case 7\n        [p,o,q,error_type,tarch_type,startingvals,options]=tarch_parameter_check(epsilon, p, o, q, error_type, tarch_type, startingvals);\n    case 8\n        [p,o,q,error_type,tarch_type,startingvals,options]=tarch_parameter_check(epsilon, p, o, q, error_type, tarch_type, startingvals, options);\n    otherwise\n        error('Number of inputs must be between 4 and 8');\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%Initial setup\nm  =  max([p o q]);\n\n\n%Augment the data with back casts to avoid costly memory allocations\nif tarch_type==1\n    %fepsilon is f(epsilon), as above\n    fepsilon   =  [mean(abs(epsilon))*ones(m,1) ; abs(epsilon)];\n    %fIepsilon is fepsilon*(epsilon<0)\n    fIepsilon   =  [0.5*mean(abs(epsilon))*ones(m,1) ; abs(epsilon).*(epsilon<0)];\n    \n    % Local back casting\n    back_cast_length = max(floor(length(epsilon)^(1/2)),1);\n    back_cast_weights = .05*(.9.^(0:back_cast_length ));\n    back_cast_weights = back_cast_weights/sum(back_cast_weights);\n    back_cast = back_cast_weights*(abs(epsilon(1:back_cast_length+1)));\n    if back_cast==0\n        back_cast=mean(abs(epsilon));\n    end\nelse\n    %fepsilon is f(epsilon), as above\n    fepsilon   =  [mean(epsilon.^2)*ones(m,1) ; epsilon.^2];\n    %fIepsilon is fepsilon*(epsilon<0)\n    fIepsilon   =  [0.5*mean(epsilon.^2)*ones(m,1) ; epsilon.^2.*(epsilon<0)];\n    % Local back casting\n    back_cast_length = max(floor(length(epsilon)^(1/2)),1);\n    back_cast_weights = .05*(.9.^(0:back_cast_length ));\n    back_cast_weights = back_cast_weights/sum(back_cast_weights);\n    back_cast = back_cast_weights*((epsilon(1:back_cast_length+1)).^2);\n    if back_cast==0\n        back_cast=mean(epsilon.^2);\n    end\nend\nepsilon_augmented=[zeros(m,1);epsilon];\n%Compute the length of the augmented epsilon\nT     = size(fepsilon,1);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Starting values\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%This flag is for the robustness check below, if the user supplies starting\n%values, there will be no robustness check\nif isempty(startingvals)\n    startingflag=0;\nelse\n    startingflag=1;\nend\n%Grid search for starting values.\n[startingvals,nu,lambda,~,ordered_parameters]=tarch_starting_values(startingvals,epsilon_augmented,fepsilon,fIepsilon,p,o,q,T,error_type,tarch_type);\n%Finally, initialize the starting values\nstartingvals = [startingvals; nu; lambda];\n%Transform the starting vals\n[garch_params_transformed,nu_transformed,lambda_transformed]=tarch_transform(startingvals,p,o,q,error_type);\n%Re-append nu, lambda\nstartingvals_transformed = [garch_params_transformed; nu_transformed; lambda_transformed];\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Starting values\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Estimate the parameters. Note the 1 in the last argument to indicate it\n% is a constrained optimization\n\n%LL0 is used to make sure the log likelihood improves\nLL0=tarch_likelihood(startingvals_transformed,epsilon_augmented,fepsilon,fIepsilon,p,o,q,error_type,tarch_type,back_cast,T,1);\n%Parameter estimation\n[parameters,LL,exitflag,output]=fminunc('tarch_likelihood',startingvals_transformed,options,epsilon_augmented,fepsilon,fIepsilon,p,o,q,error_type,tarch_type,back_cast,T,1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Estimation Robustness\n%This portion of the code is to make sure that the optimization converged\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%This is the case where the optimization did not converge, but improved on\n%the initial log likelihood\nif  exitflag<=0 && LL<LL0\n    %Try more iterations, only do more iterations if the final likelihood is\n    %actually better than the initial\n    \n    %Increase the max iterations and max fun evals\n    %Also switch to steepest descent\n    if ischar(options.MaxFunEvals)\n        options.MaxIter=2*100*length(parameters);\n    else\n        options.MaxIter=2*options.MaxIter;\n    end\n    if ischar(options.MaxFunEvals)\n        options.MaxFunEvals=4*100*length(parameters);\n    else\n        options.MaxFunEvals=2*options.MaxFunEvals;\n    end\n    options.HessUpdate='steepdesc';\n    % Estimate the parameters.\n    [parameters,LL,exitflag,output]=fminunc('tarch_likelihood',parameters,options,epsilon_augmented,fepsilon,fIepsilon,p,o,q,error_type,tarch_type,back_cast,T,1);\nend\n\n\n\n%If the optimization still hasn't converged, try other starting values\nif startingflag==0 && exitflag<=0\n    %Keep track of the final estimates, if nothing converges, we will\n    %return the\n    robust_parameters(1,:)=parameters';\n    %Also keep the LL\n    robust_LL = zeros(2,1);\n    robust_LL(1) = LL;\n    %Keep track of the iteration\n    index=2;\n    while exitflag<=0\n        %This condition checks that we haven't converged\n        %OR that the best objective is worse than best grid search\n        %Sort the original grid search log likelihoods and parameters\n        \n        startingvals=[ordered_parameters(index,:)' ; nu; lambda];\n        %Transform the starting vals\n        [garch_params_transformed,nu_transformed,lambda_transformed]=tarch_transform(startingvals,p,o,q,error_type);\n        %Reappend nu\n        startingvals_transformed = [garch_params_transformed; nu_transformed; lambda_transformed];\n        \n        LL0=tarch_likelihood(startingvals_transformed,epsilon_augmented,fepsilon,fIepsilon,p,o,q,error_type,tarch_type,back_cast,T,1);\n        options.HessUpdate='bfgs';\n        %Try the second set of starting values\n        [parameters,LL,exitflag,output]=fminunc('tarch_likelihood',startingvals_transformed,options,epsilon_augmented,fepsilon,fIepsilon,p,o,q,error_type,tarch_type,back_cast,T,1);\n        if  exitflag<=0 && LL<LL0\n            %Again, if the LL improved, try more iterations\n            %Increase the max iterations and max fun evals\n            %Also switch to steepest descent\n            options.MaxIter=2*options.MaxIter;\n            options.MaxFunEvals=2*options.MaxFunEvals;\n            options.HessUpdate='steepdesc';\n            % Estimate the parameters.\n            [parameters,LL,exitflag,output]=fminunc('tarch_likelihood',parameters,options,epsilon_augmented,fepsilon,fIepsilon,p,o,q,error_type,tarch_type,back_cast,T,1);\n        end\n        %Save the parameter estimates\n        robust_parameters(index,:)=parameters';\n        robust_LL(index)=LL;\n        %Increment the index\n        index=index+1;\n        \n        if index>size(ordered_parameters,1);\n            %save the best LL and parameters and break\n            warning('MFEToolbox:Convergence','Convergence not achieved.  Use results with caution');\n            [LL,index]=min(robust_LL);\n            parameters=robust_parameters(index,:)';\n            break\n        end\n    end\nend\n\n%Transform the parameters from the real line to the restricted space\n[parameters,nu,lambda]=tarch_itransform(parameters,p,o,q,error_type);\nparameters=[parameters;nu;lambda];\n%Compute the log likelihood if needed\nif nargout>1\n    [LL, ~, ht]=tarch_likelihood(parameters,epsilon_augmented,fepsilon,fIepsilon,p,o,q,error_type,tarch_type,back_cast,T);\n    LL=-LL;\nend\n\n%Compute standard errors using RobustVCV if needed.\nif nargout>3\n    nw=0; %No newey west on scores\n    [VCVrobust,A,~,scores,hess]=robustvcv('tarch_likelihood',parameters,nw,epsilon_augmented,fepsilon,fIepsilon,p,o,q,error_type,tarch_type,back_cast,T);\n    VCV=hess^(-1)/(T-m);\n    diagnostics.A = A;\nend\n\n%Report diagnostics in case requested\ndiagnostics.EXITFLAG=exitflag;\ndiagnostics.ITERATIONS=output.iterations;\ndiagnostics.FUNCCOUNT=output.funcCount;\ndiagnostics.MESSAGE=output.message;\ndiagnostics.m = m;\ndiagnostics.T = T;\ndiagnostics.fdata = fepsilon;\ndiagnostics.fIdata = fIepsilon;\ndiagnostics.back_cast = back_cast;", "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/univariate/tarch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5735482770424476}}
{"text": "function PSNRdb = PSNR(x, y)\n\nerr = x - y;\nerr = err(:);\nPSNRdb = 20 * log10(256/sqrt(mean(err .^2)));", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/Shearlet/Util/PSNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533013520764, "lm_q2_score": 0.6150878555160664, "lm_q1q2_score": 0.573540701497525}}
{"text": "function [ lo, hi ] = p02_box ( m )\n\n%*****************************************************************************80\n%\n%% P02_BOX returns a bounding box for problem 02.\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%    Output, real LO(M), HI(M), the low and high corners of the box.\n%\n  center = [ 0.0, 0.0 ];\n  r1 = 1.0;\n  r2 = 0.4;\n\n  lo(1:m) = [ center(1) - r1, center(2) - r1 ];\n  hi(1:m) = [ center(1) + r1, center(2) + r1 ];\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_triangulation/p02_box.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.5733267622202944}}
{"text": "function [err, time] = spincomp(S, N, dt, pref)\n%SPINCOMP  Compare time-stepping schemes in 1D/2D/3D.\n%   SPINCOMP(S, N, DT, PREF) compares the time-stepping schemes in PREF.SCHEME\n%   applied to the PDE specified by the SPINOP/SPINOP2/SPINOP3 S, using a fixed \n%   number N of grid points and different time-steps DT. The results are shown\n%   in a pair of log-log plots. PREF is a SPINPREF/SPINPREF2/SPINPREF3 object.\n%\n%   [ERR, TIME] = SPINCOMP(S, N, DT, PREF) returns the errors and the computer\n%   times. \n%\n% Example 1: Compare the ETDRK schemes for 1D Kuramoto-Sivashinsky equation\n%\n%   dom = [0 32*pi]; tspan = [0 30];\n%   u0 = chebfun('cos(x/16).*(1 + sin(x/16))',dom,'trig');\n%   S = spinop('KS');\n%   S.init = u0; S.tspan = tspan;\n%   N = 256; dt = [1, 5e-1, 2e-1, 1e-1, 5e-2, 2e-2];\n%   pref = spinpref;\n%   pref.scheme = {'etdrk4', 'exprk5s8', 'krogstad', 'friedli', ...\n%      'hochbruck-ostermann', 'minchev', 'strehmel-weiner'};\n%   spincomp(S, N, dt, pref);\n%\n% Example 2: Compare the PREDICTOR-CORRECTOR schemes for 2D Gray-Scott equations\n%\n%   G = 3; dom = G*[0 1 0 1]; tspan = [0 10];\n%   u01 = chebfun2(@(x,y) 1-exp(-150*((x-G/2).^2 + (y-G/2).^2)), dom, 'trig');\n%   u02 = chebfun2(@(x,y) exp(-150*((x-G/2).^2 + 2*(y-G/2).^2)), dom, 'trig');\n%   u0 = chebmatrix(u01);\n%   u0(2,1) = u02;\n%   S = spinop2('GS'); S.init = u0; S.tspan = tspan;\n%   N = 128; dt = [1, 5e-1, 2e-1, 5e-2, 2e-2];\n%   pref = spinpref2;\n%   pref.scheme = {'pec423', 'pecec433', 'pec524', 'pecec534', 'pec625', ...\n%      'pecec635', 'pec726', 'pecec736'};\n%   spincomp(S, N, dt, pref);\n%\n% See also SPINOP, SPINOP2, SPINOP3, SPINSCHEME.\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 schemes:\nschemes = pref.scheme;\nnSchemes = length(schemes);\n\n% Get the time-steps:\ntimesteps = dt;\nnTimesteps = length(timesteps);\n\n% Convert the initial conditiona to a CHEBMATRIX:\nu0 = S.init;\nif ( isa(u0, 'chebfun') == 1 || isa(u0, 'chebfun2') == 1 || ...\n    isa(u0, 'chebfun3') == 1)\n    u0 = chebmatrix(u0);\nelseif ( isa(u0, 'chebfun2v') == 1 || isa(u0, 'chebfun3v') == 1 )\n    temp = chebmatrix(u0(1));\n    for k = 2:size(u0, 1)\n        temp(k,1) = u0(k);\n    end\n    u0 = temp;\nend\nnVars = length(u0);\n\n% Create a grid to compare exact and computed solutions:\ndom = u0{1}.domain;\nxx = trigpts(32, dom);\nif ( isa(u0{1}, 'chebfun') == 1 )\n    dim = 1;\nelseif ( isa(u0{1}, 'chebfun2') == 1 )\n    dim = 2;\n    [xx, yy] = meshgrid(xx);\nelseif ( isa(u0{1}, 'chebfun3') == 1 )\n    dim = 3;\n    [xx, yy, zz] = meshgrid(xx);\nend\n    \n% First, estimate the exact solution using a very small time step (half the \n% smallest time-step) and with PECEC736 (7th-order multistep scheme):\nif ( isa(pref, 'spinpref') == 1 )\n    prefu = spinpref();\nelseif ( isa(pref, 'spinpref2') == 1 )\n    prefu = spinpref2();\nelseif ( isa(pref, 'spinpref3') == 1 )\n    prefu = spinpref3();\nend\nprefu.scheme = 'pecec736';\nprefu.plot = 'off';\nprefu.M = pref.M;\nuexact = spinoperator.solvepde(S, N, min(timesteps)/2, prefu);\nif ( isa(uexact, 'chebmatrix') == 0 )\n    uexact = chebmatrix(uexact);\nend\n\n% Scale (i.e., maximum amplitude) of the exact solution:\nscale = 0;\nfor i = 1:nVars\n    if ( dim == 1 )\n        scale = max(scale, max(abs(uexact{i}(xx))));\n    elseif( dim == 2 )\n        scale = max(scale, max(max(abs(uexact{i}(xx,yy)))));\n    elseif ( dim == 3 )\n        scale = max(scale, max(max(max(abs(uexact{i}(xx,yy,zz))))));\n    end\nend\n\n% Second, compute solutions for different schemes and time-steps:\nerr = zeros(nTimesteps, nSchemes);\ntime = zeros(nTimesteps, nSchemes);\nfor k = 1:nTimesteps\n    for l = 1:nSchemes\n        prefu.scheme = schemes{l};\n        [u, ~, t] = spinoperator.solvepde(S, N, timesteps(k), prefu); \n        time(k,l) = t;\n        if ( isa(u, 'chebmatrix') == 0 )\n            u = chebmatrix(u);\n        end\n        isNan = isNanTest(u, dim);\n        if ( isNan == 1 )\n            err(k,l) = NaN;\n        else\n            for i = 1:nVars\n                if ( dim == 1 )\n                    temp = abs(u{i}(xx) - uexact{i}(xx));\n                elseif( dim == 2 )\n                    temp = abs(u{i}(xx,yy) - uexact{i}(xx,yy));\n                elseif ( dim == 3 )\n                    temp = abs(u{i}(xx,yy,zz) - uexact{i}(xx,yy,zz));\n                end\n                temp = max(temp(:));\n                err(k,l) = max(err(k,l), temp);\n            end\n        end\n    end\nend\nerr = err/scale; % Relative error\ntspan = S.tspan;\nTF = tspan(end);\ntimesteps = timesteps/TF; % Relative time-steps\n\n% Plot Accuarcy vs time-step:\nfigure, subplot(1, 2, 1)\nlabels = cell(nSchemes, 1);\nfor l = 1:nSchemes\n    labels{l} = schemes{l};\n    if ( l > 1 )\n        hold on\n    end\n    if ( l < 8 )\n        loglog(timesteps, err(:, l), '.-', 'linewidth', 2, 'markersize', 30)\n    elseif ( l < 15 )\n        loglog(timesteps, err(:, l), 'x-', 'linewidth', 2, 'markersize', 10)\n    else\n        loglog(timesteps, err(:, l), 'o-', 'linewidth', 2, 'markersize', 10)\n    end\nend\nleft = 10^floor(log10(min(timesteps)));\nright = 10^ceil(log10(max(timesteps)));\ndown = max(min(1e-10, 10^floor(log10(min(err(:))))), 1e-12);\nup = min(max(1e0, 10^ceil(log10(max(err(:))))), 1e2);\nset(gca, 'fontsize', 16), axis([left right down up])\nxlabel('Relative time-step'), ylabel(sprintf('Relative error at t = %.3f', TF))\nlegend(labels, 'Location', 'NorthWest')\n\n% Plot Accuarcy vs computer time:\nsubplot(1, 2, 2)\nfor l = 1:nSchemes\n    if ( l > 1 )\n        hold on\n    end\n    if ( l < 8 )\n        loglog(time(:,l), err(:, l), '.-', 'linewidth', 2, 'markersize', 30)\n   elseif ( l < 15 )\n        loglog(time(:,l), err(:, l), 'x-', 'linewidth', 2, 'markersize', 10)\n    else\n        loglog(time(:,l), err(:, l), 'o-', 'linewidth', 2, 'markersize', 10)\n    end\nend\nleft = 10^(floor(log10(min(min(time)))));\nright = 10^(ceil(log10(max(max(time)))));\nset(gca, 'fontsize', 16), axis([left right down up])\nxlabel('Computer time (s)'), ylabel(sprintf('Relative error at t = %.3f', TF))\nlegend(labels, 'Location', 'NorthEast')\n\nend\n\nfunction out = isNanTest(u, dim)\n\nB = u.blocks;\nif ( dim == 1 )\n    out = any(cell2mat(cellfun(@(C) isnan(C), B, 'UniformOutput', 0))); \nelseif ( dim == 2 )\n    out = any(cell2mat(cellfun(@(C) isnan(C.cols), B, 'UniformOutput', 0))); \n    out = out || ...\n        any(cell2mat(cellfun(@(C) isnan(C.rows), B, 'UniformOutput', 0))); \nelseif ( dim == 3 )\n    out = any(cell2mat(cellfun(@(C) isnan(C.cols), B, 'UniformOutput', 0))); \n    out = out || ...\n        any(cell2mat(cellfun(@(C) isnan(C.rows), B, 'UniformOutput', 0))); \n    out = out || ...\n        any(cell2mat(cellfun(@(C) isnan(C.tubes), B, 'UniformOutput', 0))); \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/spincomp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.5733267622202943}}
{"text": "function [idx, iter, obj, H] = symnmf_cluster(X, k, options)\n%SYMNMF_CLUSTER\n% [idx, iter, obj, H] = symnmf_cluster(X, k, options)\n%\n% This function performs graph clustering on a data matrix.\n%\n% Input:\n% X - NxP data matrix (N observations with dimension P),\n%     where each row is one observation,\n%     and each column is one feature/variable.\n%     (If an NxN similarity matrix is available,\n%      please call 'symnmf_anls' directly.)\n% k - Specifying the number of clusters.\n% options - A structure of optional parameters for\n%           clustering (see details below).\n%\n% Default configurations:\n%   options.graph_type = 'sparse';\n%   options.similarity_type = 'gaussian';\n%   options.graph_objfun = 'ncut';\n%   (no options.kk given)\n%   options.nn = 7;\n%   options.tol = 1e-3;\n%   options.maxiter = 10000;\n%   options.rep = 1;\n%   (no options.Hinit given)\n%   options.computeobj = true;\n%   options.alg = 'anls';\n%\n% Output:\n% idx - Nx1 vector, containing the clustering assignment\n%       of each observation.\n% iter - Number of iterations actually used\n% obj - Final value of the objective function\n%           f(H) = ||A - HH'||_F^2\n% H - Final result of low-rank matrix H\n%\n% Available options:\n% 1. options.graph_type\n%    = 'full': to construct a fully-connected graph\n%    = 'sparse': to construct a sparse graph where\n%                each observation is connected to\n%                its KK nearest neighbors. (DEFAULT)\n%\n%    (Note: Only undirected graph is supported,\n%           so the resulting similarity matrix\n%           is symmetric.)\n%\n% 2. options.similarity_type\n%    = 'gaussian': to use self-tuning Gaussian similarity,\n%                  proposed in [Zelnik-Manor and Perona,\n%                  2004] (see more details in functions\n%                  'scale_dist3' and 'scale_dist3_knn') (DEFAULT)\n%    = 'inner_product': to use inner product similarity\n%                       (good choice for text data)\n%\n% 3. options.graph_objfun\n%    = 'ncut': to use normalized cut (DEFAULT)\n%    = 'rcut': to use ratio cut\n%\n% 4. options.kk (DEFAULT is unset, i.e. depending on N)\n%    specifies the number of nearest neighbors WHEN\n%    options.graph_type = 'sparse'.\n%\n%    The default value depends on N:\n%    option.kk = floor(log2(N)) + 1;\n%\n% 5. options.nn (DEFAULT is 7)\n%    specifies the nn-th neighbor, which is used in\n%    the self-tuning Gaussian similarity WHEN\n%    options.similarity_type = 'gaussian'.\n%\n% 6. options.tol (DEFAULT is 1e-3)\n%    controls the termination of SymNMF algorithm.\n%\n% 7. options.maxiter (DEFAULT is 10000)\n%    limits the number of iteration allowed in each run.\n%\n% 8. options.rep (DEFAULT is 1)\n%    sets the nubmer of runs of SymNMF algorithm.\n%\n%    The return values 'idx', 'iter', 'obj', and 'H' are\n%    corresponding to a single run, which is the run that\n%    yields the lowest objective function value.\n%\n%    Using multiple runs of SymNMF may help avoid local minima.\n%\n% 9. options.Hinit (DEFAULT is unset, i.e. random initialization)\n%    sets the initialization of matrix H in each run.\n%\n%    options.Hinit is a 3-dim array. The 3rd dimension may imply\n%    the choice of options.rep, and each 2-dim array in the 1st\n%    and 2nd dimensions is a NxK nonnegative matrix.\n%\n%    Random initialization is recommended. If options.Hinit has to\n%    be a fixed set of matrices for testing, the instructions on\n%    how to initialize H should be followed. Please consult the\n%    usage of 'symnmf_newton'.\n%\n% 10. options.computeobj (DEFAULT is true)\n%     specifies whether to compute the objective value\n%     f(H) at the final solution H.\n%\n% 11. options.alg\n%     = 'anls' to use ANLS algorithm (DEFAULT)\n%     = 'newton' to use Newton-like algorithm\n%\n% This function is used for experiments in the following paper:\n%     Da Kuang, Chris Ding, Haesun Park,\n%     Symmetric Nonnegative Matrix Factorization for Graph Clustering,\n%     The 12th SIAM International Conference on Data Mining (SDM '12), pp. 106--117.\n% Please cite this paper if you find this code useful.\n%\n\n[n, p] = size(X);\n\nif ~exist('options', 'var')\n    graph_type = 'sparse';\n    similarity_type = 'gaussian';\n    graph_objfun = 'ncut';\n    kk = floor(log2(n)) + 1;\n    nn = 7;\n    tol = 1e-3;\n    maxiter = 10000;\n    rep = 1;\n    Hinit = [];\n    computeobj = true;\n    alg = 'anls';\nelse\n    if isfield(options, 'graph_type')\n        graph_type_names = {'full', 'sparse'};\n        j = find(strcmpi(options.graph_type, graph_type_names));\n        if ~isempty(j)\n            graph_type = graph_type_names{j};\n        else\n            error('Invalid options.graph_type value!');\n        end\n    else\n        graph_type = 'sparse';\n    end\n    if isfield(options, 'similarity_type')\n        similarity_type_names = {'gaussian', 'inner_product'};\n        j = find(strcmpi(options.similarity_type, similarity_type_names));\n        if ~isempty(j)\n            similarity_type = similarity_type_names{j};\n        else\n            error('Invalid options.similarity_type value!');\n        end\n    else\n        similarity_type = 'gaussian';\n    end\n    if isfield(options, 'graph_objfun')\n        graph_objfun_names = {'ncut', 'rcut'};\n        j = find(strcmpi(options.graph_objfun, graph_objfun_names));\n        if ~isempty(j)\n            graph_objfun = graph_objfun_names{j};\n        else\n            error('Invalid options.graph_objfun value!');\n        end\n    else\n        graph_objfun = 'ncut';\n    end\n    if isfield(options, 'kk')\n        if ~isempty(options.kk) & isnumeric(options.kk) & options.kk < n\n            kk = options.kk;\n        else\n            error('options.kk must be an integer less than N!');\n        end\n    else\n        kk = floor(log2(n)) + 1;\n    end\n    if isfield(options, 'nn')\n        if ~isempty(options.nn) & isnumeric(options.nn) & options.nn < n\n            nn = options.nn;\n        else\n            error('options.nn must be an integer less than N!');\n        end\n    else\n        nn = 7;\n    end\n    if isfield(options, 'tol')\n        if ~isempty(options.tol) & isnumeric(options.tol) & options.tol > 0 & options.tol < 1\n            tol = options.tol;\n        else\n            error('options.tol must be a real number and 0 < options.tol < 1!');\n        end\n    else\n        tol = 1e-3;\n    end\n    if isfield(options, 'maxiter')\n        if ~isempty(options.maxiter) & isnumeric(options.maxiter) & options.maxiter > 0\n            maxiter = options.maxiter;\n        else\n            error('options.maxiter must be a positive integer!');\n        end\n    else\n        maxiter = 10000;\n    end\n    if isfield(options, 'rep')\n        if ~isempty(options.rep) & isnumeric(options.rep) & options.rep > 0\n            rep = options.rep;\n        else\n            error('options.rep must be a positive integer!');\n        end\n        if isfield(options, 'Hinit') & size(options.Hinit, 3) ~= rep\n            error('The third dimension of options.Hinit must match options.rep!')\n        end\n    else\n        if isfield(options, 'Hinit') & ~isempty(options.Hinit)\n            rep = size(options.Hinit, 3);\n        else\n            rep = 1;\n        end\n    end\n    if isfield(options, 'Hinit')\n        if ~isempty(options.Hinit) & isnumeric(options.Hinit) & size(options.Hinit, 1) == n & size(options.Hinit, 2) == k\n            Hinit = options.Hinit;\n        else\n            error('The size of each initialization of H must be Nxk!');\n        end\n    else\n        Hinit = [];\n    end\n    if isfield(options, 'computeobj')\n        if ~isempty(options.computeobj) & (isnumeric(options.computeobj) | isboolean(options.computeobj))\n            computeobj = options.computeobj;\n        else\n            error('options.computeobj must be boolean or a real number!');\n        end\n    else\n        computeobj = true;\n    end\n    if computeobj == false & rep > 1\n        error('options.computeobj must be true if options.rep > 1!');\n    end\n    if isfield(options, 'alg')\n        alg_names = {'anls', 'newton'};\n        j = find(strcmpi(options.alg, alg_names));\n        if ~isempty(j)\n            alg = alg_names{j};\n        else\n            error('Invalid options.alg value!');\n        end\n    else\n        alg = 'anls';\n    end\nend\n\nD = dist2(X, X);\nif strcmp(graph_type, 'full') & strcmp(similarity_type, 'gaussian')\n    A = scale_dist3(D, nn);\nelseif strcmp(graph_type, 'full') & strcmp(similarity_type, 'inner_product')\n    A = X * X';\nelseif strcmp(graph_type, 'sparse') & strcmp(similarity_type, 'gaussian')\n    A = scale_dist3_knn(D, nn, kk, true);\nelse % graph_type == 'sparse' & similarity_type == 'inner_product'\n    Xnorm = X';\n    d = 1./sqrt(sum(Xnorm.^2));\n    Xnorm = bsxfun(@times, Xnorm, d);\n    A = inner_product_knn(D, Xnorm, knn, true);\n    clear Xnorm, d;\nend\nclear D;\n\nif strcmp(graph_objfun, 'ncut')\n    dd = 1 ./ sum(A);\n    dd = sqrt(dd);\n    A = bsxfun(@times, A, dd);\n    A = A';\n    A = bsxfun(@times, A, dd);\n    clear dd;\nend\nA = (A + A') / 2;\n\nparams.maxiter = maxiter;\nparams.tol = tol;\n\nobj_best = Inf;\nfor i = 1 : rep\n    if isempty(Hinit)\n        if strcmp(alg, 'newton')\n            [sol, infos] = symm_newton(A, k, params);\n        else % strcmp(alg, 'anls')\n            [sol, infos] = symm_anls(A, k, params);\n        end\n    else\n        params.Hinit = Hinit(:, :, i);\n        if strcmp(alg, 'newton')\n            [sol, infos] = symm_newton(A, k, params);\n        else % strcmp(alg, 'anls')\n            [sol, infos] = symm_anls(A, k, params);\n        end\n    end\n    H = sol.H;\n    [max_val, idx] = max(H, [], 2);\n    if infos.cost(end) < obj_best\n        idx_best = idx;\n        iter_best = infos.iter(end);\n        obj_best = infos.cost(end);\n        H_best = H;\n    end\nend\n\nidx = idx_best;\niter = iter_best;\nobj = obj_best;\nH = H_best;\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/applications/graph_clustering/symnmf_cluster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5733267589566489}}
{"text": "function point_merge_test04 ( m, n, n_unique, tol, seed )\n\n%*****************************************************************************80\n%\n%% POINT_MERGE_TEST04 tests uniqueness indexing with a tolerance. \n%\n%  Discussion:\n%\n%    POINT_RADIAL_TOL_UNIQUE_COUNT uses an algorithm that should be,\n%      in general, O(N);\n%    POINT_TOL_UNIQUE_COUNT uses an O(N^2) algorithm.\n%\n%    For this test, we just want to make sure the algorithms agree\n%    in the counting.\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  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'POINT_MERGE_TEST04\\n' );\n  fprintf ( 1, '  To index the unique columns in an R8COL, we call\\n' );\n  fprintf ( 1, '  POINT_RADIAL_TOL_UNIQUE_COUNT, (with random center)\\n' );\n  fprintf ( 1, '  POINT_TOL_UNIQUE_COUNT, (with zero tolerance)\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  M = %d\\n', m );\n  fprintf ( 1, '  N = %d\\n', n );\n  fprintf ( 1, '  TOL = %f\\n', tol );\n  fprintf ( 1, '  SEED = %d\\n', seed );\n\n  [ a, seed ] = r8col_duplicates ( m, n, n_unique, seed );\n\n  r8mat_transpose_print ( m, n, a, '  Matrix with N_UNIQUE unique columns:' );\n%\n%  The form of the tolerance test means that if two vectors are initially\n%  equal, they remain \"tolerably equal\" after the addition of random\n%  perturbation vectors whose 2-norm is no greater than TOL/2.\n%\n  for j = 1 : n\n    [ r, seed ] = r8vec_uniform_01 ( m, seed );\n    r(1:m) = r(1:m) / sqrt ( sum ( r(1:m).^2 ) );\n    a(1:m,j) = a(1:m,j) + 0.5 * tol * r(1:m,1);\n  end\n\n  r8mat_transpose_print ( m, n, a, '  Blurred matrix:' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  N_UNIQUE =                      %d\\n', n_unique );\n\n  [ unique_num, undx, xdnu, seed ] = point_radial_tol_unique_index ( m, n, a, ...\n    tol, seed );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  POINT_RADIAL_TOL_UNIQUE_INDEX\\n' );\n  fprintf ( 1, '  Unique_num = %d\\n', unique_num );\n\n  i4vec_print ( unique_num, undx, '  UNDX:' );\n\n  i4vec_print ( n, xdnu, '  XDNU:' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  List of nonunique points P(J), represented by\\n' );\n  fprintf ( 1, '  point with index I(J).\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  J, P(J)\\n' );\n  fprintf ( 1, '  I(J), P(I(J))\\n' );\n  fprintf ( 1, '  || P(J) - P(I(J)) || (should be <= TOL)\\n' );\n  fprintf ( 1, '\\n' );\n  for j = 1 : n\n    k = undx(xdnu(j));\n    if ( j ~= k )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, '  %4d', j );\n      for i = 1 : m\n        fprintf ( 1, '  %14f', a(i,j) );\n      end\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, '  %4d', k );\n      for i = 1 : m\n        fprintf ( 1, '  %14f', a(i,k) );\n      end\n      fprintf ( 1, '\\n' );\n      dist = sqrt ( sum ( ( a(1:m,j) - a(1:m,k) ).^2 ) );\n      fprintf ( 1, '          %10f\\n', dist );\n    end\n  end\n%\n%  The interpretation of XDNU is simpler for POINT_TOL_UNIQUE_INDEX.\n%\n  [ unique_num, xdnu ] = point_tol_unique_index ( m, n, a, tol );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  POINT_TOL_UNIQUE_INDEX\\n' );\n  fprintf ( 1, '  Unique_num = %d\\n', unique_num );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  List of nonunique points P(J), represented by\\n' );\n  fprintf ( 1, '  point with index I(J).\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  J, P(J)\\n' );\n  fprintf ( 1, '  I(J), P(I(J))\\n' );\n  fprintf ( 1, '  || P(J) - P(I(J)) || (should be <= TOL)\\n' );\n  fprintf ( 1, '\\n' );\n  for j = 1 : n\n    k = xdnu(j);\n    if ( j ~= k )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, '  %4d', j );\n      for i = 1 : m\n        fprintf ( 1, '  %14f', a(i,j) );\n      end\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, '  %4d', k );\n      for i = 1 : m\n        fprintf ( 1, '  %14f', a(i,k) );\n      end\n      fprintf ( 1, '\\n' );\n      dist = sqrt ( sum ( ( a(1:m,j) - a(1:m,k) ).^2 ) );\n      fprintf ( 1, '          %10f\\n', dist );\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/point_merge/point_merge_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5733267577807917}}
{"text": "function a = r8row_sort_heap_a ( m, n, a )\n\n%*****************************************************************************80\n%\n%% R8ROW_SORT_HEAP_A ascending heapsorts an R8ROW.\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%    25 May 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 of M rows of N-vectors.\n%\n%    Output, real A(M,N), the rows of A have been sorted.\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 ( m, indx, isgn );\n%\n%  Interchange the I and J objects.\n%\n    if ( 0 < indx )\n\n      a = r8row_swap ( m, n, a, i, j );\n%\n%  Compare the I and J objects.\n%\n    elseif ( indx < 0 )\n\n      isgn = r8row_compare ( m, n, a, i, j );\n\n    elseif ( indx == 0 )\n\n      break\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/r8row_sort_heap_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.5733267545171462}}
{"text": "function [ V ] = T2V( T )\n%T2V converts 4x4 transformation matrix into a 1x6 vector\n%   Inputs -\n%   T - a standard 4x4 transformation matrix\n%\n%   Outputs -\n%   V - 1x6 vector of form [x,y,z,rx,ry,rz] where x,y,z is the translation\n%   and rx,ry,rz is an angle-axis representation of the angle where the\n%   unit vector representing the axis has been multipled by the angle of\n%   rotation about it\n\nvalidateattributes(T, {'numeric'},{'size',[4,4]});\n\nT = double(T);\n\nV(1:3) = T(1:3,4);\nV(4:6) = R2V(T(1:3,1:3));\n\nend\n\n", "meta": {"author": "ZacharyTaylor", "repo": "Camera-to-Arm-Calibration", "sha": "d3f0d2e00e2eeaba451e4a8edd226ce0bdb24d08", "save_path": "github-repos/MATLAB/ZacharyTaylor-Camera-to-Arm-Calibration", "path": "github-repos/MATLAB/ZacharyTaylor-Camera-to-Arm-Calibration/Camera-to-Arm-Calibration-d3f0d2e00e2eeaba451e4a8edd226ce0bdb24d08/private/T2V.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5733267456381408}}
{"text": "function H = psd_project_rows(H,tol)\n  % H = psd_project_rows(H)\n  if nargin < 2\n    tol = 0;\n  end\n  m = round(sqrt(size(H,2)));\n  assert(m*m==size(H,2));\n  for i = 1:size(H,1)\n    A = reshape(H(i,:),m,m);\n    [V,D] = eig(triu(A)+triu(A,1)','vector');\n    B = V*(max(D,tol).*V');\n    H(i,:) = B(:);\n    if any(~isreal(B(:)))\n      keyboard\n    end\n  end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mex/psd_project_rows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5733140389180824}}
{"text": "function [score]=crps(ygibbs,yo)\n\n\n\n\n\n% compute first the dimension of the gibbs sampler draws (normally, 'It' iterations minus 'Bu' discarded burn iterations)\nIt_Bu=size(ygibbs,1);\n\n% compute the first summation term\nsum1=sum(abs(ygibbs-repmat(yo,It_Bu,1)));\n\n% compute the second summation term\n temp=abs(repmat(ygibbs,1,It_Bu)-repmat(ygibbs',It_Bu,1));\n sum2=sum(temp(:));\n\n% eventually compute the score\nscore=(1/It_Bu)*sum1-(1/(2*It_Bu^2))*sum2;\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/crps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5732766327521392}}
{"text": "function T_hat = run_tc(params)\n  T = params.T;\n  Idx = params.Idx;\n  \n  Omega = find(Idx);\n  Ak = T(Omega);\n  \n  N = ndims(T);\n  Nway = size(T); % dimension of tensor\n  coreNway = [Nway(1),Nway(2),1];\n  \n  % rank_dec strategy\n  opts = [];\n  opts.alpha_adj = 0;\n  opts.rank_adj = -1*ones(1,3);\n  opts.rank_min = 5*ones(1,3);\n  opts.rank_max = 20*ones(1,3);\n  EstCoreNway = round(1.25*coreNway);\n  coNway = zeros(1,N);\n  for n = 1:N\n    coNway(n) = prod(Nway)/Nway(n);\n  end\n  % use random generated starting point\n  for i = 1:3\n    X0{i} = randn(Nway(i),EstCoreNway(i));\n    Y0{i} = randn(EstCoreNway(i),coNway(i));\n  end\n  opts.X0 = X0; opts.Y0 = Y0;\n  [X_dec,Y_dec,Out_dec] = TMac(Ak,Omega,Nway,EstCoreNway,opts);\n  % use the weighted sum of all mode matrix factorizations as estimated tensor\n  T_hat = zeros(Nway);\n  for i = 1:N\n    T_hat = T_hat+Out_dec.alpha(i)*Fold(X_dec{i}*Y_dec{i},Nway,i);\n  end\nend\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/TMac/run_tc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5732766317669196}}
{"text": "% Local Regression and Likelihood, Figure 4.4.\n% Author: Catherine Loader\n%\n% AIC plot for a local poisson regression.\n\nload mine;\na = (0.4:0.05:1)';\nfigure('Name','fig4_4: AIC plot for local poisson regression' );\naicplot(a,extrp,frac,'family','poisson','deg',1);\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/fig4_4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5732766270356873}}
{"text": "function [Z_hat, E_hat] = exact_alm_lrr_l21v2(D, A, lambda, tol, maxIter,display)\n\n% Aug 2013\n% This matlab code implements the Exact ALM algorithm for\n% min_{Z,E}  |Z|_* + lambda |E|_2,1  s.t.  D = AZ + E\n%\n% D - m x n matrix of observations/data (required input)\n% A - m x k matrix of the dictionary (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[m n] = size(D);\nk = size(A,2);\n\n\nif nargin < 4 || isempty(tol)\n    tol = 1e-7;\nend\n\nif nargin < 5 || isempty(maxIter)\n    maxIter = 1000;\nend\n\nif nargin<6 || isempty(display)\n    display = false;\nend\n\nmaxIter_primal = 10000;\n% initialize\nY = sign(D);\nnorm_two = norm(Y,2);\nnorm_inf = norm( Y(:), inf) / lambda;\ndual_norm = max(norm_two, norm_inf);\nY = Y / dual_norm;\n\nW = zeros(k,n);\n\nZ_hat = zeros(k,n);\nE_hat = zeros(m,n);\n%parameters\ndnorm = norm(D, 'fro');\ntolProj1 = 1e-6 * dnorm;\n\nanorm = norm(A,2);\ntolProj2 = 1e-6 * dnorm/anorm;\n\nmu = .5/norm_two; % this one can be tuned\nrho = 6;          % this one can be tuned\n\n%pre-computation\nif m>=k\n    inv_ata = inv(eye(k) + A'*A);\nelse\n    inv_ata = eye(k) - A'/(eye(m)+A*A')*A;\nend\n\niter = 0;\nwhile iter < maxIter       \n    iter = iter + 1;\n    \n    % solve the primal problem by alternative projection\n    primal_iter = 0;\n    \n    while primal_iter < maxIter_primal\n        primal_iter = primal_iter + 1;\n        temp_Z = Z_hat;\n        temp_E = E_hat;\n        \n        %update J\n        temp = temp_Z + W/mu;\n        \n        [U,S,V] = svd(temp, 'econ'); % stable \n        %[U,S,V] = svdecon(temp); % fastest, but EIG must not contain NaN or Inf.\n       \n        diagS = diag(S);\n        svp = length(find(diagS > 1/mu));\n        diagS = max(0,diagS - 1/mu);\n        \n        if svp < 0.5 %svp = 0\n            svp = 1;\n        end\n        J_hat = U(:,1:svp)*diag(diagS(1:svp))*V(:,1:svp)';  \n        \n        % update Z\n        temp = J_hat + A'*(D - temp_E) + (A'*Y-W)/mu;\n        Z_hat = inv_ata*temp;\n        \n        %update E\n        temp = D - A*Z_hat + Y/mu;\n        E_hat =  solve_l1l2(temp, lambda/mu);\n        \n        if norm(E_hat - temp_E, 'fro') < tolProj1 && norm(Z_hat - temp_Z)<tolProj2\n            break;\n        end\n    end\n        \n    H1 = D - A*Z_hat - E_hat;\n    H2 = Z_hat - J_hat;\n    Y = Y + mu*H1;\n    W = W + mu*H2;\n    mu = rho * mu;\n    \n    %% stop Criterion    \n    stopCriterion = max(norm(H1, 'fro')/dnorm, norm(H2,'fro')/dnorm*anorm);\n    if display\n        disp(['LRR: Iteration' num2str(iter) '(' num2str(primal_iter) '), mu ' num2str(mu) ', |E|_2,0 ' num2str(sum(sum(E_hat.^2,1)>0))...\n        ', stopCriterion ' num2str(stopCriterion)]);\n    end\n    \n    if stopCriterion < tol\n        break;\n    end    \n    \n   \nend\n\nend\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/lrr/ALM/exact_alm_lrr_l21v2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.573276615602783}}
{"text": "function z0 = bicinter(x, y, z, x0, y0)\nN = 16;\nM = 4;\n[xn, yn, zn] = findnearest(x, y, z, x0, y0, N);\nF = zeros(N, N);\nfor p = 1:N\n    Fr = zeros(1, N);\n    for i = 1:M\n    for j = 1:M\n        Fr( map_ijk(i, j, M) ) = (xn(p)^(i-1))*(yn(p)^(j-1));\n    end\n    end\n    F(p, :) = Fr;\nend\na = F\\zn;\nz0 = 0;\nfor i = 1:M\nfor j = 1:M\n    z0 = z0 + a( map_ijk(i, j, M) )*(x0^(i-1))*(y0^(j-1));\nend\nend\n\nfunction k = map_ijk (i, j, M)\n    k = (i-1)*M + j;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25443-interpolation-for-missing-data/interpolation/bicinter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5732342163157246}}
{"text": "function ds_plumb=cosmo_fmri_deoblique(ds)\n% de-oblique a dataset\n%\n% Input:\n%     ds                fmri dataset struct\n%\n% Output:\n%\n% Example:\n%     % start with a simple dataset\n%     x=cosmo_synthetic_dataset('size','huge','ntargets',1,'nchunks',1);\n%     % make dataset oblique (manually)\n%     x.a.vol.mat(1,1)=.8;\n%     x.a.vol.mat(2,1)=.6;\n%     y=cosmo_fmri_deoblique(x);\n%     cosmo_disp(x.a.vol)\n%     %|| .mat\n%     %||   [ 0.8         0         0        -3\n%     %||     0.6         2         0        -3\n%     %||       0         0         2        -3\n%     %||       0         0         0         1 ]\n%     %|| .dim\n%     %||   [ 20        17        19 ]\n%     %|| .xform\n%     %||   'scanner_anat'\n%     cosmo_disp(y.a.vol)\n%     %|| .mat\n%     %||   [ 1         0         0      -3.2\n%     %||     0         2         0      -2.4\n%     %||     0         0         2        -3\n%     %||     0         0         0         1 ]\n%     %|| .dim\n%     %||   [ 20        17        19 ]\n%     %|| .xform\n%     %||   'scanner_anat'\n%     %\n%     % other attributes are unchanged:\n%     assert(isequal({x.samples x.fa x.sa x.a.fdim},...\n%                    {y.samples y.fa y.sa y.a.fdim}));\n%     %\n%     % a plump dataset does not change after de-obliqueing\n%     z=cosmo_fmri_deoblique(y);\n%     isequal(y,z)\n%     %|| true\n%\n% Notes:\n%   - Using this function changes the location of the voxels in\n%     world-space, that is world coordinates (x, y, z).\n%   - This function is intended for AFNI and BrainVoyager, as these\n%     programs prefer 'plump' (non-oblique) volumes.\n%   - When using this function, it is recommended to inspect the result\n%     visually.\n%\n% #   For CoSMoMVPA's copyright information and license terms,   #\n% #   see the COPYING file distributed with CoSMoMVPA.           #\n\n% get canonical orthogonal matrix\n[unused,rot_ortho]=cosmo_fmri_orientation(ds);\nmat=ds.a.vol.mat;\n\n\n% convert base1 -> base0\nmat(1:3,4)=mat(1:3,4)+mat(1:3,1:3)*[1 1 1]';\n\n% use pixel dimension to set non-zero elements\nmat_ortho=mat;\npixdim=sqrt(sum(mat(1:3,1:3).^2,1));\nmat_ortho(1:3,1:3)=bsxfun(@times,rot_ortho(1:3,1:3),pixdim);\n\n% convert base0 -> base1\nmat_ortho(1:3,4)=mat_ortho(1:3,1:3)*-[1 1 1]'+mat_ortho(1:3,4);\n\n% ensure single element in rotation part\nassert(all(sum(mat_ortho(:,1:3)~=0,1)==1));\nassert(all(sum(mat_ortho(1:3,1:3)~=0,2)==1));\n\nds_plumb=ds;\nds_plumb.a.vol.mat=mat_ortho;\n\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_fmri_deoblique.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5732164788753568}}
{"text": "function [Ep M] = spm_induced_optimise_parameters(PARAMS)\n% Demo routine that optimises free parameters\n%==========================================================================\n%\n% This exemplar routine illustrates how one can adjust or tune prior\n% parameter expectations to produce desired spectral responses as specified\n% by the complex eigenvalue spectrum - or a reduced form that considers a\n% small number of complex values (roots).\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_induced_optimise_parameters.m 6856 2016-08-10 17:55:05Z karl $\n \n% Parameters to optimise\n%--------------------------------------------------------------------------\nif ~nargin, PARAMS = {'G','T','L'}; end\n\n\n% spectral specification\n%==========================================================================\nJ      = [3 7];                % indices of hidden states producing outputs\nNp     = length(J);\n\n% Target spectrum - gamma, beta and alpha\n%--------------------------------------------------------------------------\nHz     = 1:128;\ns(:,1) = -[128 64 32 64]'   + 1j*2*pi*[4 12 48 64]';\ns(:,2) = -[128 64 256 256]' + 1j*2*pi*[8 16 48 64]';\n\n\n\n% Model specification\n%==========================================================================\nNc    = 1;\nNs    = 1;\noptions.spatial  = 'LFP';\noptions.model    = 'TFM';\nM.dipfit.model = options.model;\nM.dipfit.type  = options.spatial;\nM.dipfit.Nc    = Nc;\nM.dipfit.Ns    = Ns;\nM.J            = J;\nM.Hz           = Hz;\n\n% get priors\n%--------------------------------------------------------------------------\n[pE pC] = spm_dcm_neural_priors({0 0 0},{},1,options.model);\n[pE pC] = spm_L_priors(M.dipfit,pE,pC);\n[pE pC] = spm_ssr_priors(pE,pC);\n[x,f]   = spm_dcm_x_neural(pE,options.model);\n\n% suppress measurement noise\n%--------------------------------------------------------------------------\npE.a(2) =      - 2;\npE.b    = pE.b - 16;\npE.c    = pE.c - 16;\n\n\n% a target data\n%--------------------------------------------------------------------------\nGu    = spm_csd_mtf_gu(pE,M.Hz);\nfor i = 1:Np\n    csd(:,i,i) = 512*full(Gu.*sum(spm_s2csd(s(:,i),Hz),2));\nend\n \n% orders and model\n%==========================================================================\nnx      = length(spm_vec(x));\nnu      = Ns;\nu       = sparse(1,nu);\n \n% fix priors if a subset of parameters are specified\n%--------------------------------------------------------------------------\npV    = spm_vec(pC);\nV     = pV - pV;\nfor i = 1:length(PARAMS)\n    V(spm_fieldindices(pE,PARAMS{i})) = 1;\nend\npC    = spm_unvec(V.*pV,pC);\n\n\n\n% create LFP model\n%--------------------------------------------------------------------------\nM.IS   = 'spm_csd_mtf';\nM.FS   = 'spm_diag_array';\nM.g    = @(x,u,P,M) P.L*x(M.J(:));\n\nM.f    = f;\nM.x    = x;\nM.n    = nx;\nM.pE   = pE;\nM.pC   = pC;\nM.hE   = 8;\nM.hC   = 1/128;\nM.m    = nu;\nM.l    = Np;\n \n% solve for steady state\n%--------------------------------------------------------------------------\nM.x    = spm_dcm_neural_x(pE,M);\nM.u    = u;\nM.Nmax = 32;\n\n% Optimisation: Target (Y)\n%==========================================================================\n[Ep Cp] = spm_nlsi_GN(M,[],{csd});\n\n\n% Characterise contributions of parameters to spectral representation\n%==========================================================================\n \n% Show results with current (prior) parameters\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Spectral responses'); clf\n \n% and plot spectra\n%--------------------------------------------------------------------------\nsubplot(2,2,1)\nGp    = spm_csd_mtf(pE,M);\nGq    = spm_csd_mtf(Ep,M);\nplot(Hz,abs(spm_diag_array(Gp{1})),'r'), hold on\nplot(Hz,abs(spm_diag_array(Gq{1})),'b'),  hold on\nplot(Hz,abs(spm_diag_array(csd)),  '--'),  hold off\n\ntitle({'Spectral responses';'Before (red) and after (blue)'},'FontSize',16)\nxlabel('Frequency')\nylabel('Spectral density')\naxis square\n\n \n% Show results with optimised parameters\n%--------------------------------------------------------------------------\nsubplot(2,2,2)\nsp  = spm_ssm2s(pE,M);\nsq  = spm_ssm2s(Ep,M);\ngp  = spm_s2csd(sp,Hz);\ngq  = spm_s2csd(sq,Hz);\nplot(Hz,gp,'r',Hz,gq,'b')\n\ntitle({'Eigenmodes';'Before (red) and after (blue)'},'FontSize',16)\nxlabel('Frequency')\nylabel('Spectral density of modes')\naxis square\n\n \n% Show old and new priors\n%==========================================================================\n\n% change in parameters (and conditional confidence)\n%--------------------------------------------------------------------------\nE     = spm_vec(Ep) - spm_vec(pE);\nC     = diag(Cp);\n\n% eliminate an interesting parameters and sought on basis of contribution\n%--------------------------------------------------------------------------\n[c,j] = sort(C,'ascend');\nj     = j(find(abs(E(j)) > exp(-8) & C(j) > 0));\n\nsubplot(4,1,3)\nspm_plot_ci(E(j),C(j))\ntitle('Posterior updates','FontSize',16)\nxlabel('Free parameters')\nylabel('Value')\nset(gca,'XTick',1:length(j))\nset(gca,'XTickLabel',spm_fieldindices(pE,j))\n \nsubplot(4,1,4)\nbar(-log(C(j,:)))\ntitle('Contribution (log precision)','FontSize',16)\nxlabel('Free parameters')\nylabel('log precision')\nset(gca,'XTick',1:length(j))\nset(gca,'XLim',[0 (length(j) + 1)])\nset(gca,'XTickLabel',spm_fieldindices(pE,j))\n\nreturn\n\n% examine Jacobian\n%==========================================================================\nspm_figure('GetWin','Jacobian'); clf\n\n% get transfer functions and Jacobian\n%--------------------------------------------------------------------------\n[S,K,s,w,t,dfdx] = spm_dcm_mtf(Ep,M,[]);\n \n% and plot\n%--------------------------------------------------------------------------\nsubplot(2,2,1)\nimagesc(dfdx)\ntitle('Jacobian','FontSize',16)\nxlabel('hidden state')\nylabel('hidden state')\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/Neural_Models/spm_induced_optimise_parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5732164708294301}}
{"text": "function f = diff( f, varargin )\n%DIFF   Derivative of a diskfun in Cartesian coordinates.\n%\n%   F = DIFF( F ) computes the first derivative of F with respect to x.\n%\n%   F = DIFF( F, DIM )  computes the first derivative of F. If DIM = 1, the\n%   derivative is taken in the x-direction. If DIM = 2, the derivative\n%   is taken in the y-direction.\n%\n%   F = DIFF( F, DIM, K) computes the kth derivatives of F in the variable\n%   given by DIM.\n%\n% See also DISKFUN/LAPLACIAN, DISKFUN/DIFFX, DISKFUN/DIFFY\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n\nif ( isempty(f) )\n    f = diskfun;\n    return\nend\n\n% Parse user inputs:\nif ( nargin == 1 )\n    dim = 1;\n    K = 1;\nelseif ( nargin == 2 )\n    dim = varargin{1};\n    K = 1;\nelse\n    dim = varargin{1};\n    K = varargin{2};\nend\n\nif ( dim ~= 1 && dim ~= 2  )\n    error('DISKFUN:DIFF:DIM', 'Unrecognized coordinate dimension.');\nend\n\nif ( abs( K - round(K) ) > eps )\n    error('DISKFUN:DIFF:DIFFORDER', 'Fractional derivatives not allowed.')\nend\nK = round( K );\n\n% Implement higher derivatives as repeated (iterated) differentiation\nfor j=1:K\n    f = onediff(f, dim);\nend\n\nend\n% TODO: This code will not work for complex valued diskfuns, if we ever\n% allow them.\n\nfunction f = onediff(f, dim)\n\n% Make sure f has as short a length as possible.\nf=simplify(f); \n\n% We are going to work at the tech level to make things faster.\n[C, ~, R] = cdr( f );\n\n% Do everything with even length columns since then no special\n% modifications are required for dividing by rho series expansion.\nparity = mod(length(C),2);\nn = length(C)+parity;\nm = length(R);\n\n% The variable coefficients in the definitions of the derivatives means\n% that the length of the columns and rows will increase by one wave number\n% after taking the derivatives with respect to x and y. \nm = m+2;\nn = n+2;\n\n% Matrices for multiplying by sin(theta), cos(theta) and 1/r in coefficient space.\nMsinm = .5i*spdiags(ones(m,1)*[-1,1],[-1 1],m,m);\nMcosm = .5*spdiags(ones(m,1)*[1,1],[-1 1],m,m);\nMn = ultraS.multmat(n, [0;1], 0);\n\n% Work at the tech level to make things faster.\nctechs = C.funs{1}.onefun;\nrtechs = R.funs{1}.onefun;\n\n% Alias to get the extra zeros in place.\nctechs.coeffs = ctechs.alias(ctechs.coeffs, n); \nrtechs.coeffs = rtechs.alias(rtechs.coeffs, m); \n\n% Compute the derivatives.\ndCdr = diff(ctechs);\ndRdth = diff(rtechs)/pi;\n\n% 1/r*col\nrinv = Mn \\ ctechs.coeffs; \n\nif (dim==1) %d/dx \n\n    %CDR for -1/r.*sin(th).*d/dth\n    C1 = rinv; \n    R1 = -Msinm*dRdth.coeffs;\n    \n    %CDR for cos(th).*d/dr\n    C2 = dCdr.coeffs;\n    R2 = Mcosm*rtechs.coeffs;\n    \nelse  %d/dy\n    \n    %CDR for 1/r.*cos(th).*d/dth\n    C1 = rinv; \n    R1 = Mcosm*dRdth.coeffs;\n    \n    %CDR for sin(th).*d/dr\n    C2 = dCdr.coeffs;\n    R2 = Msinm*rtechs.coeffs;\nend\n\n% Put pieces back together\nf1 = f; \nc1techs = chebtech2({' ',C1}); \nf1.cols.funs{1}.onefun = c1techs; \nr1techs = real(trigtech({'',R1}));\nf1.rows.funs{1}.onefun = r1techs;\n\n% Parity changes\ntemp = f1.idxPlus;\nf1.idxPlus = f1.idxMinus;\nf1.idxMinus = temp;\n\nf2 = f; \nc2techs = chebtech2({'',C2}); \nf2.cols.funs{1}.onefun = c2techs; \nr2techs = real(trigtech({'',R2}));\nf2.rows.funs{1}.onefun = r2techs;\n\n% Parity changes\ntemp = f2.idxPlus;\nf2.idxPlus = f2.idxMinus;\nf2.idxMinus = temp;\n\n% Compression plus may not preserve the expansion properties we want.\n% So we sample each piece add them together and construct a diskfun.\n% TODO: Fix this so everything is done in coefficient space, like this\n% f = f1 + f2; \n\n% Constructor requires even m\nm = m + mod(m, 2); \n\nf = diskfun(sample(f1,m,n/2+1)+sample(f2,m,n/2+1));    \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/@diskfun/diff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5732164672047246}}
{"text": "function [S,Li] = eeg_interp_sph_spline(V,X,Y,Z,Npoints)\n\n% eeg_interp_sph_spline - Spherical Spline Laplacian of Potential\n%\n% Useage: [S,Li] = eeg_lap_sph_spline(voltage,X,Y,Z,Npoints)\n%\n% where:    'voltage' is an EEG/ERP measurement at time t from\n%           electrode positions (X,Y,Z) on a scalp surface.  All\n%           input arrays are the same size, assumed (Nelec x 1).\n%           The origin of X,Y,Z is assumed (0,0,0).\n%\n%           S  => the x,y,z points on a hemisphere\n%           Li => spherical spline Laplacian of voltages\n%\n%           S is generated by 'elec_sphere_points' with \n%           Rpoints=Npoints and Epoints=16.\n%\n% Notes:    This function calculates the spherical spline Laplacian \n%           of Perrin et al (1989).  Electroenceph. & Clin. \n%             Neurophysiology, 72: 184-187.\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:52 $\n\n% Licence:  GNU GPL, no implied or express warranties\n% History:  08/01  Darren.Weber_at_radiology.ucsf.edu, with\n%                  mathematical and matlab advice from\n%                  Dr. Murk Bottema (Flinders University of SA)\n%\n%           08/01  Needs testing & verification!\n%                  With large electrode arrays, the result should be\n%                  regularized (not sure why).\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Check for correct size & orientation of X,Y,Z,V\n    [x1,x2] = size(X);\n    [y1,y2] = size(Y);\n    [z1,z2] = size(Z); \n    [v1,v2] = size(V); \n    if ~and(isequal(x1,y1,z1,v1),isequal(x2,y2,z2,v2))\n        error('ERROR: all X, Y, Z, V must be size (Nx1)'); \n    end\n    if x1 < x2, X = X'; [x1,x2] = size(X); end\n    if y1 < y2, Y = Y'; [y1,y2] = size(Y); end\n    if z1 < z2, Z = Z'; [z1,z2] = size(Z); end\n    if v1 < v2, V = V'; [v1,v2] = size(V); end\n    if ~(isequal(x2,y2,z2,v2,1))\n        error('ERROR: all X, Y, Z, V must be size (Nx1)');\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Computations derived from Perrin et al. (1989)\n\n    % G * C = V,  where:\n    %\n    % G  (NxN)    spherical spline\n    % C  (Nx1)    spline coefficients\n    % V  (Nx1)    voltage potentials at (X,Y,Z) electrode locations\n    %\n    % solve for C = V * Sp' (C = V\\Sp; (see \"help slash\"))\n\n    % First calc G, where G is a function of the cosine of \n    % the angle (theta) between electrode point vectors\n    A   = [ X Y Z ];\n    COS = cosines(A,A);\n    G   = spheric_spline(COS);\n    C   = spline_coefficients(G,V); % spline coefficients (Co,C1,...,Cn)\n    Co  = C(1);\n    Ci  = C(2:end);\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Obtain interpolated potentials at S (eq.1, Perrin et al., 1989)\n    % V(s) = Co + sum( Ci * g(x) )\n\n    % get spherical electrode radius\n    [r,x,y,z] = elec_sphere_fit(X,Y,Z,0,0,0,0);\n    % Generate spherical points for interpolation\n    [x,y,z]   = elec_sphere_points(16,Npoints,r);\n    S         = [x y z];\n    \n    fprintf('...Spherical Interpolation Progress:\\n');\n    rows = 80;  % progress indicator\n    \n    for p = 1:length(S)\n        \n        B = S(p,:);\n        Cos = cosines(A,B);         %(1xN)\n        \n        Gx  = spheric_spline(Cos);  %(1xN)\n        \n        CiGx = Ci .* Gx';           %(1xN)\n        \n        Vi(p,1) = Co + sum(CiGx);\n        \n        fprintf('.');  % progress indicator\n        if([p] == rows ) fprintf('\\n'); rows = rows + 80; end\n    end\n    \nreturn\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Solve eq. 3 Perrin et al. (1989)\n% g(COS) = 1/4pi * sum[n=1:inf] (( (2*n+1)/(n^m * (n+1)^m) ) * Pn(COS));\n\nfunction [Gx] = spheric_spline(Cosine)\n    \n    m = 4;    N = 7;    % gives accuracy of 10^-6\n    \n    P = legendre(N,Cosine);\n    %P = LEGENDRE(N,X) computes the associated Legendre functions \n    %of degree N and order m = 0, 1, ..., N, evaluated for each element\n    %of X.\n    %In general, P has one more dimension than X.\n    %Each element P(m+1,i,j,k,...) contains the associated Legendre\n    %function of degree N and order m evaluated at X(i,j,k,...).\n    \n    ndim = ndims(P);\n    switch ndim\n    case 2, P = P(2:N+1,:);\n    case 3, P = P(2:N+1,:,:);\n    case 4, P = P(2:N+1,:,:,:);\n    otherwise\n    end\n    \n    k = (1/4 * pi);\n    \n    for n = 1:(N),  Series(n,1) = (2*n + 1) / (n^(m-1) * (n+1)^(m-1));  end\n    \n    if min(size(Cosine)) == 1,    Gx      = k * ( Series' * P );\n    else\n        for i = 1:length(Cosine), Gx(i,:) = k * ( Series' * P(:,:,i) );\n        end\n    end\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Solve eq. 2 Perrin et al. (1989)\nfunction [C] = spline_coefficients(Gx,V)\n    \n    % add ones to first row & column of Gx\n    tmp =  ones(size(V));       Gx   = [tmp Gx];\n    tmp = [ones(size(V))' 1]';  Gx   = [tmp Gx']';\n    \n    Gx(1,1) = 0;    % according to Murk\n    %Gx(1,1) = 1;    % according to EMSE, Greenblatt\n    \n    CoV = [0 V']';\n    \n    C = Gx\\CoV;\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [Cos] = cosines(A,B)\n\n    for     a = 1:size(A,1),  Aa = A(a,:); A_len = norm(Aa);\n        for b = 1:size(B,1),  Bb = B(b,:); B_len = norm(Bb);\n\n            Cos(a,b) = dot(Aa,Bb) / (A_len * B_len);\n        end\n    end\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/eeg_lap_sph_spline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5732164591587979}}
{"text": "function [A,B,flag] = oprACAv(opr,k,X,Xnrm,Y,Ynrm,tol)\n%+========================================================================+\n%|                                                                        |\n%|            OPENOPR - LIBRARY FOR SPECIFIC OPERATORS IN BEM             |\n%|           openOpr is part of the GYPSILAB toolbox for Matlab           |\n%|                                                                        |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2019.                             |\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       : oprACAv.m                                     |\n%|    #    |   VERSION    : 0.61                                          |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |\n%|  ( # )  |   CREATION   : 14.03.2017                                    |\n%|  / 0 \\  |   LAST MODIF : 05.09.2019                                    |\n%| ( === ) |   SYNOPSIS   : Adaptative Cross Approximation, partial       |\n%|  `---'  |                & total pivoting                              |\n%+========================================================================+\n\n% Matrix dimensions\nNx = size(X,1);\nNy = size(Y,1);\n\n% Initialize indices\nIr = (1:Nx)';\nIc = (1:Ny)';\n\n% Partial pivoting with handle function\nrow = @(i) oprGreenKernel(opr,k,X(i,:),Xnrm(i,:),Y,Ynrm);\ncol = @(j) oprGreenKernel(opr,k,X,Xnrm,Y(j,:),Ynrm(j,:));\n\n% First row (row index of maximum reference value)\ni   = 1;\nB   = row(i);\ndim = size(B,3);\n\n% First pivot (maximum of the first row) \n[~,j] = max(max(abs(B),[],3));\ndelta = B(j,:,:);\n\n% Securitys\ndelta(abs(delta)<1e-12) = 1e-12;\n\n% First column\nA = col(j)./delta;\n\n% Unused indices1\nIr = [Ir(1:i-1);Ir(i+1:end)];\nIc = [Ic(1:j-1);Ic(j+1:end)];\n\n% Frobenius norm for the initial tensor product\nRn2 = zeros(dim,1);\nerr = 0;\nfor l = 1:dim\n    An2    = A(:,1,l)'*A(:,1,l);\n    Bn2    = B(:,1,l)'*B(:,1,l);\n    Rn2(l) = An2*Bn2;\n    err    = max(err,sqrt(An2)*sqrt(Bn2)/sqrt(Rn2(l)));\nend\n\n% Iterative construction using frobenius norm\nn = 1;\nwhile (err > tol)\n    % New pivot by maximum \n    [~,i] = max(max(abs(A(Ir,n,:)),[],3));\n    new   = row(Ir(i));\n    for l = 1:dim\n        new(:,:,l) = new(:,:,l) - B(:,:,l)*A(Ir(i),1:n,l).';\n    end\n    [~,j] = max(max(abs(new(Ic,:,:)),[],3));\n    delta = new(Ic(j),:,:);\n\n    % New pivot by minimum \n    [~,iMin] = min(min(abs(A(Ir,n,:)),[],3));\n    newMin   = row(Ir(iMin));\n    for l = 1:dim\n        newMin(:,:,l) = newMin(:,:,l) - B(:,:,l)*A(Ir(iMin),:,l).';\n    end\n    [~,jMin] = max(max(abs(newMin(Ic,:,:)),[],3));\n    deltaMin = newMin(Ic(jMin),:,:);\n    \n    % Best pivot\n    if (norm(deltaMin(:)) > norm(delta(:)))\n        i     = iMin;\n        new   = newMin;\n        j     = jMin;\n        delta = deltaMin;\n    end\n    \n    % Security\n    delta(abs(delta)<1e-12) = 1e-12;\n    \n    % Update row\n    B(:,n+1,:) = new;\n    \n    % New column\n    new = col(Ic(j));\n    for l = 1:dim\n        new(:,:,l) = (new(:,:,l) - A(:,:,l)*B(Ic(j),1:n,l).')./delta(l);    %B(:,:,l)*A(Ir(i),:,l).';\n    end\n    A(:,n+1,:) = new;\n    \n    % Update row and column indices\n    Ir = [Ir(1:i-1);Ir(i+1:end)];\n    Ic = [Ic(1:j-1);Ic(j+1:end)];\n    \n    % Incrementation\n    n = n + 1;\n\n    % Relative Frobenius error by block\n    err = 0;\n    for l = 1:dim\n        An2    = A(:,n,l)'*A(:,n,l);\n        Bn2    = B(:,n,l)'*B(:,n,l);\n        u      = B(:,n,l)'*B(:,1:n-1,l);\n        v      = A(:,n,l)'*A(:,1:n-1,l);\n        AB     = v*u.';\n        Rn2(l) = Rn2(l) + 2*real(AB) + An2*Bn2;\n        err    = max(err,sqrt(An2)*sqrt(Bn2)/sqrt(Rn2(l)));\n    end\n    \n    % Compression failed\n    if (n*(Nx+Ny) > Nx*Ny)\n        A    = [];\n        B    = [];\n        flag = 0;\n        return\n    end    \n%     sqrt(An2)*sqrt(Bn2)/sqrt(Rn2)\n%     norm(A*B.' - A(:,1:n-1)*B(:,1:n-1).','fro')/norm(A*B.','fro')\n%     norm(A(:,n)*B(:,n).','fro')/norm(A*B.','fro')    \n%     norm(ref,'inf')/nrm\n%     '================================'\nend\n\n% B transposition lead to  A * B\nB    = permute(B,[2 1,3]);\nflag = 1;\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/openOpr/oprACAv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339556397749, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5731803528584918}}
{"text": "function check_NFSOFT\n%\n% checks for Y_l(g h) = T_l(g) Y_l(h)\n%\n\n%% input data\nL = 16;\n\n%q = axis2quat(xvector+yvector,25*degree);\n%q = axis2quat(zvector,90*degree);\n%h = [xvector,-xvector,yvector];\n\nqq = quaternion(SO3Grid(10));\nh = equispacedS2Grid('points',20,'antipodal');\n\nprogress(0,length(qq));\n\nfor iq = 1:length(qq)\n\n  progress(iq,length(qq));\n  \n  q = qq(iq);\n  \n  %% convert to export parameters\n  g = Euler(q,'nfft');\n%   alpha = fft_rho(alpha); %-->z\n%   beta  = fft_theta(beta);\n%   gamma = fft_rho(gamma); %-->z\n%   g = 2*pi*[alpha;beta;gamma];\n  %g = [0;pi/2;0];\n      \n  %% set parameters\n  c = 1;\n  A = ones(1,L+1);\n\n  %% run NFSOFT\n  T = call_extern('odf2fc','EXTERN',g,c,A); % conjugate(D)\n\n  % extract result\n  T = complex(T(1:2:end),T(2:2:end));\n\n\n  %% check result\n\n  for l = 0:L\n  \n    Y = sphericalY(l,h).'; % -> Y\n    gY = sphericalY(l,q*h).'; % -> Y\n    Tl = reshape(T(deg2dim(l)+1:deg2dim(l+1)),2*l+1,2*l+1);\n    %    TY = flipud(Tl * flipud(Y));\n    %    TY = flipud(fliplr(Tl) * Y);\n    TY = Tl * Y;\n    er(l+1,iq) = sqrt(norm(TY(:) - gY(:)));\n    %TY = conj(Tl) * Y;norm(TY(:) - gY(:))\n    %TY = Tl' * Y;norm(TY(:) - gY(:))\n    %TY = Tl.' * Y;norm(TY(:) - gY(:))\n    \n  end\n\nend\n\n%plot(mean(er,2));\nif mean(er(:)) > 0.001\n  error('Error in NFSOFT');\nelse\n  disp('checking NFSOFT: ok')\n  disp(mean(er(:)))\nend\n\npcolor(er)\n\nfunction d = deg2dim(l)\n% dimension of the harmonic space up to order l\n\nd = l*(2*l-1)*(2*l+1)/3;\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/tests/check_NFSOFT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5731803502269184}}
{"text": "function [y,err]=golaycodec(x,enc,ext)\n% GOLAYCODEC - encode/decode a binary array using the Golay code with error correction.\n%\n% golaycodec encodes or decodes a binary array using the Golay code.\n% Words of length 12 are encoded as codewords of length 23 (or 24 for the\n% extended Golay code).  The Golay code is tolerant of up to 3 errors,\n% i.e. for any word of length 23 there is a unique codeword that differs\n% in at most 3 positions.\n%\n% The Golay code can be constructed as a polynomial code using one of the \n% degree 11 factors of z^23+1 (mod 2).  Here we use\n%   g = 1 + z^2 + z^4 + z^5 + z^6 + z^10 + z^11\n% For more details see Wikipedia etc.\n%\n% Usage:\n%   y = golaycodec(x)\n%   [y,err] = golaycodec(x)\n%   ... = golaycodec(x,enc)\n%   ... = golaycodec(x,enc,ext)\n%\n% Inputs:\n%   x can be an Mx12, Mx23 or Mx24 binary (logical) array or an Mx1 integer array.\n%     If x is Mx1, the binary representation of each integer is used.\n%   enc is a logical; if true x is to be encoded, otherwise x is to be decoded.\n%     If not specified, enc is inferred from the size of x or set to true.\n%   ext is a logical; if true use the extended Golay code (length 24),\n%     otherwise use the non-extended Golay code (length 23).\n%     If not specified, enc is inferred from the size of x or set to false.\n%     NOTE: the algorithm has so far only been implemented for ext=false\n%\n% Outputs:\n%   y is an array consisting of the coded or decoded rows of x\n%     If x is Mx12 and ext=false then y is Mx23\n%     If x is Mx12 and ext=true then y is Mx24\n%     If x is Mx23 or Mx24 then y is Mx12\n%     If x is Mx1 then y is Mx1\n%   err (only available if decoding is done, e.g enc=false) is an array\n%     with the errors that differ each word in x from its closest codeword)\n%\n% Example: encode some messages, add transmission errors and decode\n%   n=10;\n%   x=zeros(n,12);for i=1:n,x(i,ceil(12*rand(1,8)))=1;end; % random message\n%   y=golaycodec(x);\n%   err=zeros(n,23);for i=1:n,err(i,ceil(23*rand(1,3)))=1;end; % 3 random errors per message\n%   y1=xor(y,err); % add transmission error\n%   [x1,err1]=golaycodec(y1); % decode: should have x1==x and err1==err\n%\n\n% Author: Ben Petschel 18/3/2009\n%\n% Change history:\n%  18/3/2009 - created\n%  30/4/2009 - updated to implement extended Golay codes\n%\n\nencdef = true; % default value of \"enc\" if not specified for integer input\nextdef = false; % default value of \"ext\" if not specified\n\n% input checking: x\nnx=size(x,2);\nif any(~isfinite(x(:))) || any(~isreal(x(:)))\n  error('golaycodec: input array must be finite real values');\nend;\nif nx==1\n  if any(x~=round(x))\n    error('golaycodec: column input must be integers');\n  end;\n  if any(x<0)\n    % check later that integers are small enough\n    error('golaycodec: column input must be non-negative integers');\n  end;\n  intout = true;\n\nelseif nx>1\n  if any((x(:)~=0)&(x(:)~=1))\n    error('golaycodec: entries of row or matrix input must be 0 or 1');\n  end;\n  if ~any(nx==[12,23,24]),\n    error('golaycodec: number of columns of input must be 1, 12, 23 or 24');\n  end;\n  intout = false; % binary output\n  \nelse\n  error('golaycodec: empty input');\nend; % if nx==1 elseif ... else ... end;\n\n% input checking: enc, ext must be booleans\nif nargin>=2,\n  if isnumeric(enc),\n    enc = enc>0;\n  end;\n  if ~islogical(enc) || ~isscalar(enc)\n    error('golaycodec: enc must be 1x1 logical value');\n  end;\nend;\nif nargin>=3,\n  if isnumeric(ext),\n    ext = ext>0;\n  end;\n  if ~islogical(ext) || ~isscalar(ext)\n    error('golaycodec: enc must be 1x1 logical value');\n  end;\nend;\n\n% input checking: consistency of nx with enc and ext if specified\nswitch nx\n  case 1\n    if nargin == 1,\n      enc = encdef; % set to default value (usually true)\n    end;\n    if nargin <= 2,\n      ext = extdef; % set to default value (usually false)\n    end;\n  case 12\n    if nargin == 1,\n      enc = true; % encode 12-digit word\n    elseif ~enc,\n      error('golaycodec: cannot decode 12-digit words');\n    end;\n    if nargin <=2,\n      ext = extdef; % set to default value (usually false)\n    end;\n  case 23\n    if nargin == 1,\n      enc = false; % decode 23-digit word\n    elseif enc,\n      error('golaycodec: cannot encode 23-digit words');\n    end;\n    if nargin <=2,\n      ext = false; % not from the extended code\n    elseif ext,\n      error('golaycodec: 23 digit words are not in the extended code');\n    end;\n  case 24\n    if nargin == 1,\n      enc = false; % decode 24-digit word\n    elseif enc,\n      error('golaycodec: cannot encode 24-digit words');\n    end;\n    if nargin <=2,\n      ext = true; % use the extended code\n    elseif ~ext,\n      error('golaycodec: 24-digit words are not in the non-extended code');\n    end;\n  otherwise\n    error('golaycodec: input must have 1, 12, 23 or 24 columns');\nend; % switch nx\n\n% for integer inputs, check that the integers are not too large\nif intout\n  if enc\n    if any(x(:)>=2^12),\n      error('golaycodec: integers for coding must be less than 2^12');\n    end;\n  elseif any(x(:)>=2^23),\n    error('golaycodec: integers for decoding must be less than 2^23');\n  end;\nend;\n\n% output checking: nargout>1 only for decoding\nif (nargout>2) || ((nargout>1) && enc)\n  error('golaycodec: can only specify two outputs when decoding');\nend;\n\n\nif nx==1,\n  % convert integers to the appropriate length\n  if enc\n    nx=12;\n  elseif ext\n    % decode extended code\n    nx=24;\n  else\n    % decode non-extended code\n    nx=23;\n  end;\n  x = dec2logi(x,nx);\nend; % if nx==1\n\n\n% retain generating polynomial, parity check and error parity table\npersistent g h errtab\n\nif isempty(g)\n  % generating polynomial: g = 1+x^2+x^4+x^5+x^6+x^10+x^11\n  g=zeros(1,12);g([0,2,4,5,6,10,11]+1)=1;\nend;\n\nif isempty(h)\n  % parity check polynomial is the other factor of x^23-1 (mod 2)\n  % h = (1+x)*(1+x+x^5+x^6+x^7+x^9+x^11)\n  h=mod(deconv([1,zeros(1,22),1],g),2);\nend;\n\nif isempty(errtab),\n  % set up the error table for decoding: determine all errors of up to 3 bits\n  % the error will be determined by simple table lookup of the parity check\n  % the table is a sparse array indexed by the integer representation of the parity bits\n  errtab = geterrtab(h,3,23);\nend;\n\n% now encode or decode the array\nif enc\n  y = circprod(x,g,23);\n  if ext\n    % if using extended code, append a checksum bit (row sums mod 2)\n    y = [y,mod(sum(y,2),2)]; \n  end;\nelse\n  if ext\n    % drop the checksum bit if using extended code\n    c = x(:,24);\n    x = x(:,1:23);\n  end;\n  % check parity\n  p = circprod(x,h,23);\n  % look up parity in error table\n  err = dec2logi(errtab(logi2dec(p)+1),23);\n  y = zeros(size(x,1),12);\n  for i=1:size(x,1),\n    y(i,:) = mod(deconv(x(i,:)-err(i,:),g),2);\n  end;\n  if ext\n    % if using extended code, append the checksum bit error\n    err = [err,mod(c-sum(y,2),2)];\n  end;\nend;\n\n% convert back to integers, if necessary\nif intout,\n  y = logi2dec(y);\n  if nargout == 2,\n    err = logi2dec(err);\n  end;\nend;\n\nend % main function golaycodec\n\n\n\n\nfunction t=geterrtab(h,k,n)\n% produces lookup table of parity checks of all errors with weight <=k on n digits\n% y is a sparse matrix: index is 1 + (h*err converted to integer)\n% and y(i) is (err) converted to binary\n%\n% h must be row vector of length <= n\n% also 0 <= k <= n.\n\nm=length(h);\nif (2^n-1)>intmax,\n  error('golaycodec:geterrtab: too many digits to convert to integer');\nend;\nif m>n,\n  error('golaycodec:geterrtab: parity check polynomial is too long');\nend;\n\nt = sparse(1,1,0,2^n,1); % initialize with 0*h+1 -> 0\n\nfor i=1:k,\n  ind = nchoosek(1:n,i); % all possible combinations of i error digits\n  nck = size(ind,1);\n  errbin = zeros(nck,n); % error in binary format\n  errbin(sub2ind([nck,n],repmat((1:nck)',i,1),ind(:)))=1; % in row j place 1's in columns ind(j,:)\n  errint = logi2dec(errbin); % error in integer format\n  errh = circprod(errbin,h,n); % do parity check using h\n  t(logi2dec(errh)+1)=errint;\nend;\n\nend % helper function geterrtab(...)\n\nfunction z=circprod(x,h,n)\n% does parity check of rows of x using polynomial h\nm=size(x,1);\n\n% do circular convolution by fourier transform (fft acts on columns)\n% (could also use conv and wrap the tail elements, but conv isn't vectorized)\nz = mod(round(ifft(fft(x',n).*repmat(fft(h',n),1,m))'),2);\n\nend % helper function paritycheck\n\n\nfunction y=logi2dec(x)\n% converts each row of logical array from binary to a decimal number\nn=size(x,2);\ny=x*(2.^(n-1:-1:0))';\n\nend % helper function logi2dec\n\nfunction y=dec2logi(x,n)\n% converts vector of integers to array of logicals (binary representation)\ny=rem(floor(x(:)*2.^(1-n:0)),2); % see dec2bin.m (base matlab) for details\n\nend % helper function dec2logi\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23341-golaycodec/golaycodec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5731803502269184}}
{"text": "function pass = test_mean( pref ) \n\n% Grab some preferences\nif ( nargin == 0 )\n    pref = chebfunpref();\nend\ntol = pref.techPrefs.chebfuneps;\n\n% Example 1:\nf = ballfun(@(x,y,z)1);\nI = mean(f,1);\ng = spherefun(1);\npass(1) = ( norm(I-g) < tol );\n\n% Example 2:\nf = ballfun(@(x,y,z)2);\nI = mean(f,2);\ng = diskfun(2);\npass(2) = ( norm(I-g) < tol );\n\n% Example 3:\nf = ballfun(@(x,y,z)3);\nI = mean(f,3);\ng = diskfun(3);\npass(3) = ( norm(I-g) < tol );\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/ballfun/test_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722392, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5731803502269182}}
{"text": "function pobjs = APPfitGroundHough(x,y, imsize)\n% pobjs = APPfitGroundHough(x,y, imsize)\n% Fits the ground-vertical boundary with a set of polylines\n%\n% Input:\n%   x, y: the x and y positions of ground-vertical boundaries\n%   imsize: the image size\n% Output:\n%   pobjs(nplanes, [m b x1 x2 maxy disconnect])\n%\n% Copyright(C) Derek Hoiem, Carnegie Mellon University, 2005\n% Permission granted to non-commercial enterprises for\n% modification/redistribution under GNU GPL.  \n% Current Version: 1.0  09/30/2005\n\nMAKE_PLOTS = 0; % whether to make displays\n\n[x, inds] =  sort(x);\ny = y(inds);\n\nheight = imsize(1);\nwidth = imsize(2);\ny = height-round(y*(height-1));\nx = round(x*(width-1)+1);\n%figure(1), hold off, plot(x, y, '.b'), axis equal, hold on\n\nty =y;\ntx =x;\nminpts = sqrt(width^2+height^2)/20;\ndistt = sqrt(width^2+height^2)/100;\nmingapt = sqrt(width^2+height^2)/20;\ncount = 0;\n\npobjs = {};\n\n% find initial line segments\nwhile length(tx)>minpts        \n\n    % get the hough transform image for the points (tx, ty)\n    gim = zeros(imsize);\n    inds = round(ty+(tx-1)*height);\n    gim(inds) = 1;\n    gim = conv2(gim, fspecial('gaussian', 5, 1), 'same');\n    theta = [0:179];\n    [R, xp] = radon(gim, theta);\n    theta = theta';\n    \n    % get the best line from the hough transform image \n    [maxval, ind] = max(R(:));    \n\n    % get line parameters (ax + by = c)\n    [rind,thind] = ind2sub(size(R),ind);\n    t = -theta(thind)*pi/180;\n    r = xp(rind); \n    lines = [cos(t) sin(t) -r];\n    cx = width/2-1;\n    cy = height/2-1;\n    lines(:,3) = lines(:,3) - lines(:,1)*cx - lines(:,2)*cy;  \n    a = lines(1, 1);\n    b2 = lines(1, 2);\n    c = lines(1, 3);\n\n    % get line parameters in y = mx+b form\n    m = -lines(:, 1)/lines(:, 2);\n    b = -lines(:, 3)/lines(:, 2);         \n\n    % get the distance of each point from the line\n    pdst = abs(a*tx+b2*ty+c)/sqrt(a^2+b2^2);\n    inds = find(pdst < distt);\n\n    % while there is a big gap take only the larger side of the gap\n    sortx = sort(tx(inds));\n    gapt = max((sortx(end)-sortx(1))/5, mingapt);        \n    endpoints(count+1, 1:2) = [sortx(1)  sortx(end)];\n    %disp(['initlength: ' num2str(length(inds))]) \n    %disp(['gapt: ' num2str(gapt)])\n    while (max(abs(sortx(1:end-1)-sortx(2:end))) > gapt)\n        [maxval, maxind] = max(abs(sortx(1:end-1)-sortx(2:end)));\n        if maxind > length(inds)/2\n            inds = inds(1:maxind);\n        else\n            inds = inds((maxind+1):end);\n        end\n        sortx = sort(tx(inds));\n        endpoints(count+1, 1:2) = [sortx(1)  sortx(end)];\n        gapt = max((sortx(end)-sortx(1))/5, mingapt); \n        %disp(['gapt: ' num2str(gapt)])\n    end        \n    \n    %disp(['length: ' num2str(length(inds))])    \n    % check that best line has enough points \n    if length(inds) < minpts\n        break;\n    end    \n    \n    count = count + 1;\n    \n    % plot the lines and points on each line\n    if MAKE_PLOTS\n        figure(1)\n        color_chars = ['y'];\n        ab = axis; \n        col = color_chars(mod(count-1, length(color_chars))+1);\n        if abs(m)<1\n             %px = [ab(1:2)];\n             px = endpoints(count, 1:2);\n             plot(px, height-(m*px+b)+1, ['-' col], 'LineWidth', 5);\n        else\n             py = ab(3:4);\n             plot((height-(py-b)+1)/m,  height-py+1,  ['-' col], 'LineWidth', 5);\n        end\n        %plot(tx(inds), height-ty(inds)+1, ['.' col])\n        drawnow;\n        pause(1)\n    end            \n\n   \n    \n    % add assigned points to x and y\n    % remove assigned points from tx and ty\n    tx(inds) = [];\n    ty(inds) = [];\n\n    % store current line\n    pobjs{count}(1, :) = [m b 0 0 a b2 c];\n\nend\n\t\ncount = length(pobjs);\n\nif ~isempty(pobjs)\n\n    px = cell(count, 1);\n    py = cell(count, 1);\n    pmedx = zeros(count, 1);\n    pmedy = zeros(count, 1);\n    oldpinds = cell(count, 1);\n\n\n    % reassign points to each object and re-estimate lines\n    distt2 = distt;\n    changed = 1;\n    while changed\n        changed = 0;\n        pdsts = zeros(length(x), count);\n        for p1 = 1:length(pobjs)\n            a = pobjs{p1}(5);\n            b = pobjs{p1}(6);\n            c = pobjs{p1}(7);\n            pdsts(:, p1) = abs(a*x+b*y+c)/sqrt(a^2+b^2);\n            %pobjs{p1}(6:7) = [];\n        end\n        [mdists, inds] = min(pdsts, [], 2);\n        inds2 = find(mdists<=distt2);\n        for p1 = 1:length(pobjs)\n            pinds = inds2(find(inds(inds2)==p1));\n            pinds = pinds(find( (x(pinds)>=(endpoints(p1, 1)-mingapt)) & ...\n                (x(pinds)<=(endpoints(p1, 2)+mingapt))));\n            if length(setdiff(pinds, oldpinds{p1}))>2\n                changed = 1;\n                %disp('changed')\n                oldpinds{p1} = pinds;\n            end\n            px{p1} = x(pinds);\n            py{p1} = y(pinds);\n\n            if length(pinds) > 0\n                endpoints(p1, 1) = min(px{p1});\n                endpoints(p1, 2) = max(px{p1});\n                \n\n                % re-estimate line params\n                p = polyfit(px{p1},py{p1},1);\n                pobjs{p1}(1:2) = p;\n\n                pm = p(1);\n                pb = p(2);\n\n                a = 1;\n                b = -1/pm;\n                c = pb/pm;        \n                pobjs{p1}(5:7) = [a b c];       \n\n                pmedx(p1) = median(px{p1});    \n                pmedy(p1) = median(py{p1});                 \n                \n            else\n                endpoints(p1, 1:2) = 0;\n                px{p1} = [];\n                py{p1} = [];\n            end\n\n        end\n    end\n\n    % remove smaller of overlapping segments\n    reminds = [];\n    for p1 = 1:length(pobjs)\n        for p2 = (p1+1):length(pobjs)\n            if (endpoints(p1, 1)-endpoints(p2, 1))*...\n                    (endpoints(p1, 2)-endpoints(p2, 2)) < 0\n                if MAKE_PLOTS, disp('removing overlapping segment'), end;\n                if length(px{p1}) < length(px{p2})\n                    reminds(end+1) = p1;\n                else\n                    reminds(end+1) = p2;\n                end\n            end\n        end\n        if isempty(px{p1})\n            if MAKE_PLOTS, disp('removing empty segment'), end;\n            reminds = union(reminds, p1);\n        end\n    end\n    [pobjs, pmedx, pmedy, px, py] = removeIndices(reminds, pobjs, pmedx, pmedy, px, py);\n    endpoints(reminds, :) = [];\n    \n\n    if MAKE_PLOTS\n        figure(2)\n        disp(length(pobjs))\n        for p1 = 1:length(pobjs)\n            color_chars = ['r' 'y' 'g' 'c' 'k'];\n            ab = axis; \n            col = color_chars(mod(p1-1, length(color_chars))+1);\n            m = pobjs{p1}(1);\n            b = pobjs{p1}(2);\n            if abs(m)<1\n                 tpx = [ab(1:2)];\n                 plot(tpx, height-(m*tpx+b)+1, ['-' col], 'LineWidth', 3);\n            else\n                 tpy = ab(3:4);\n                 plot((height-(tpy-b)+1)/m,  height-tpy+1,  ['-' col], 'LineWidth', 3);\n            end\n            plot(px{p1}, height-py{p1}+1, ['.' col])\n            %plot(pmedx(p1), height-pmedy(p1)+1, '+k');\n        end\n        drawnow;\n        pause(5)\n    end\n\n    count = length(pobjs);\n    \n    if length(pobjs) > 0\n    \n    \n    % determine which objects should be merged \n    domerge = zeros(count, count);\n    intersectx = zeros(count, count);\n    for p1 = 1:length(pobjs)\n        for p2 = (p1+1):length(pobjs)\n            % if slopes are not same\n            if pobjs{p1}(1) ~= pobjs{p2}(1)\n                xi = (pobjs{p2}(2)-pobjs{p1}(2))/(pobjs{p1}(1)-pobjs{p2}(1));\n                yi = xi*pobjs{p1}(1) + pobjs{p1}(2);\n                %plot(xi, height-yi+1, '*k')\n                % if med x's appear on opposite sides of intersection \n                if (sign(pmedx(p1)-xi)~=sign(pmedx(p2)-xi))\n                    domerge(p1, p2) = 1;\n                    domerge(p2, p1) = 1;\n                    intersectx(p1, p2) = xi;\n                    intersectx(p2, p1) = xi;\n                end\n            end\n        end\n    end\n    intersectx = round(intersectx);\n    if MAKE_PLOTS, disp(['num merges: ' num2str(sum(domerge(:))/2)]), end;\n\n    % merge objects that should be merged\n    reminds = [];\n    for p1 = 1:length(pobjs)\n        mergeinds = find(domerge(p1, :));\n        if ~isempty(mergeinds)\n            domerge(p1, mergeinds) = 0;\n            domerge(mergeinds, p1) = 0;\n            oldlength = 0;\n            while length(mergeinds)~=oldlength\n                oldlength = length(mergeinds);\n                for p2 = mergeinds\n                    mergeinds = union(mergeinds, find(domerge(p2, :)));\n                    domerge(p2, mergeinds) = 0;\n                    domerge(mergeinds, p2) = 0;\n                end\n            end      \n            mergeinds = union(mergeinds, p1);\n                       \n            [tmp, sind] = sort(pmedx(mergeinds));\n\n            % sort mergeinds by their x-medians\n            mergeinds = mergeinds(sind);    \n            tpx = [];\n            tpy = [];\n            tobj = [];\n            for i = 1:length(mergeinds)\n\n                % if (i) and (i-1) should merge or or (i == 1)\n                if (i == 1 || intersectx(mergeinds(i), mergeinds(i-1))~=0)                    \n                        \n                    if MAKE_PLOTS, disp(['merge: ' num2str(i)]), end;\n                    tobj(end+1, :) = pobjs{mergeinds(i)};\n\n                    % set endpoints to intersection points\n                    if size(tobj, 1) > 1\n                        \n                        tobj(end-1, 4) = intersectx(mergeinds(i), mergeinds(i-1));\n                        tobj(end, 3) = tobj(end-1, 4);\n                                                                   \n                    end        \n\n                    % add points from (i) to merged segment\n                    tpx = [tpx ; px{mergeinds(i)}];\n                    tpy = [tpy ; py{mergeinds(i)}];\n                else\n                    % effectively remove (i) from merginds\n                    mergeinds(i) = mergeinds(i-1);\n                end\n            end\n            pobjs{p1} = tobj;\n            [px{p1}, inds] = sort(tpx);\n            py{p1} = tpy(inds);\n            mergeinds = setdiff(mergeinds, p1);    \n\n            % set indices to remove\n            reminds = [reminds(:) ; mergeinds(:)];      \n        end\n    end\n    % remove merged segments\n    [pobjs, px, py, pmedx, pmedy] = removeIndices(reminds, pobjs, px, py, pmedx, pmedy);\n    endpoints(reminds, :) = [];\n\n    % set endpoints (that were not found by merging)\n    for i = 1:length(pobjs) \n        for j = 1:size(pobjs{i}, 1)\n            if pobjs{i}(j, 3) == 0\n                pobjs{i}(j, 3) = min(px{i});\n            end    \n            if pobjs{i}(j, 4) == 0\n                pobjs{i}(j, 4) = max(px{i});\n            end\n        end\n    end\n\n    % find overlapping segments and resolve\n    reminds = [];\n    for p1 = 1:length(pobjs)\n        for p2 = p1+1:length(pobjs)\n            if isempty(intersect(reminds, [p1 p2]))\n                overx1 = max([px{p1}(1) px{p2}(1)]);\n                overx2 = min([px{p1}(end) px{p2}(end)]);\n                if (overx2 > overx1) % then p1 and p2 overlap\n\n                    if MAKE_PLOTS, disp('warning: removing segment'), end;                \n                    if length(px{p1}) > length(px{p2})                                  \n                        reminds(end+1) = p2;              \n                    else\n                        reminds(end+1) = p1;\n                    end\n\n                end\n            end\n        end\n    end\n\n    [pobjs, px, py, pmedx, pmedy] = removeIndices(reminds, pobjs, px, py, pmedx, pmedy);\n\n    % make sure all ground points belong to one segment\n    xstart = zeros(length(pobjs), 1);\n    xend = zeros(length(pobjs), 1);\n    for p1 = 1:length(pobjs)\n        xstart(p1) = pobjs{p1}(1, 3);\n        xend(p1) = pobjs{p1}(end, 4);\n    end\n    [xstart, ind] = sort(xstart);\n    xend = xend(ind);\n    pobjs = pobjs(ind);\n    if xstart(1) ~= x(1)\n        pobjs{1}(1, 3) = x(1);    \n    end\n    for p1 = 1:length(xstart)-1\n        if xend(p1)<xstart(p1+1)\n            if pmedy(p1) > pmedy(p1+1) % p1 lower than than p2\n                pobjs{p1}(end, 4) = xstart(p1+1)-1;\n            else\n                pobjs{p1+1}(1, 3) = xend(p1)+1;\n            end\n        end\n    end\n    [xend, ind] = sort(xend);\n    if xend(end) ~= x(end)\n        pobjs{ind(end)}(end, 4) = x(end);\n    end\n    \n    end % if at least one object\n    \nend\n\nif isempty(pobjs)\n    \n    reminds = [];\n    for i =2:length(x)\n        if x(i) == x(i-1)\n            reminds(end+1) = i;\n        end\n    end\n    x(reminds) = [];\n    y(reminds) = [];\n    pobjs{1} = piecewise_linear_spline(x, y, 3);\n    pobjs{1}(:, 5) = 0;    \nend\n\n\n% reverse height\nfor i = 1:length(pobjs)\n    ind = find(pobjs{i}(:, 5)~=0);\n    pobjs{i}(ind, 5) = height - pobjs{i}(ind, 5) + 1;\n    pobjs{i}(:, 1) = -pobjs{i}(:, 1);\n    pobjs{i}(:, 2) = height- pobjs{i}(:, 2)+1;\nend\n\n%figure(1) %, hold off, \n%hold on, plot(oldx, height-oldy+1, '.k');\nif MAKE_PLOTS\n    figure(3)\n    color_chars = ['r' 'g' 'c' 'b' 'm'];\n    count = 0;\n    for p = 1:length(pobjs)\n        rc = mod(p-1, 5)+1;\n        for j = 1:size(pobjs{p}, 1)\n            count = count + 1;\n            m = pobjs{p}(j, 1);\n            b = pobjs{p}(j, 2);\n            ppx = pobjs{p}(j, 3:4);\n            plot(ppx, ppx*m+b, ['-' color_chars(rc)], 'LineWidth', 5);\n            if j > 1\n                plot([ppx(1) ppx(1)], [ppx(1)*m+b ppx(1)*m+b-50], ...\n                    ['-' color_chars(rc)], 'LineWidth', 5);\n            end\n        end\n    end\n    drawnow;\nend\n\n\ntp = pobjs;\npobjs = zeros(0, 6);\nfor i = 1:length(tp)\n    for j = 1:size(tp{i},1)  \n        pobjs(end+1, 1:5) = tp{i}(j, 1:5);       \n    end\n    pobjs(end, 6) = 1;\nend\n\npobjs(:, 1) = pobjs(:, 1)*(width-1)/(height-1);\npobjs(:, 2) = (pobjs(:, 2)-1)/(height-1);\npobjs(:, 3:4) = (pobjs(:, 3:4)-1)/(width-1);\npobjs(:, 5) = (pobjs(:, 5)-1)/(height-1);       \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction varargout = removeIndices(indices, varargin)\n\nfor i = 1:length(varargin)\n    varargout(i) = varargin(i);\n    varargout{i}(indices) = [];\nend\n\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/GeometricContext/vrml/APPfitGroundHough.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5731803393823002}}
{"text": "function cout = intermutual(cin1, cin2, n)\n\n%tstoolbox/@core/intermutual\n%   Syntax:\n%     * intermutual(cin1,cin2,n)\n%\n%   Input Arguments:\n%     * cin1,cin2 - core objects\n%\n%   Calculates the mutual information of cin1 and cin2.\n%\n% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt\n\n\nN = dlens(cin1,1);\ncout = zeros(n,1);\nepsilon = 1e-9;\npoints1 = data(cin1);\npoints1 = points1 - min(points1);\npoints2 = data(cin2);\npoints2 = points2 - min(points2);\nma1 = max(points1);\nma2 = max(points2);\nincrement = 1/N;\n\nfor i=1:n\n\tpartitionen = 2^i;\n\tpointsA = 1+floor(points1 / (ma1/(partitionen-epsilon)));\n\tpointsB = 1+floor(points2 / (ma2/(partitionen-epsilon)));\n\t% Aus den Werten sind jetzt fertige Indizes fuer die Partititonen geworden\n\t\n\thistA = sparse(pointsA, ones(N,1), increment);\n\thistB = sparse(ones(N,1), pointsB, increment);\n\thistAB = sparse(pointsA, pointsB, increment);\n\t[ind1, ind2, value] = find(histAB);\n\tamf = sum(value .* log2(value ./ (histA(ind1) .* histB(ind2)')));\t% '\n\n\tcout(i) = amf;\nend\n\n%cout = core(amf);\n\n\t\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/intermutual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5731555996195521}}
{"text": "function SE = functionComputeSE_DL_poweralloc(rho,signal,interference,prelogFactor)\n%Compute the SE in Theorem 4.6 using the formulation in (7.1) for a given\n%power allocation scheme.\n%\n%INPUT:\n%rho          = K x L matrix where element (k,j) is the downlink transmit\n%               power allocated to UE k in cell j\n%signal       = K x L matrix where element (k,j,n) is a_jk in (7.2)\n%interference = K x L x K x L matrix where (l,i,jk,n) is b_lijk in (7.3)\n%prelogFactor = Prelog factor\n%\n%OUTPUT:\n%SE = K x L matrix where element (k,j) is the downlink SE of UE k in cell j\n%     using the power allocation given as input\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%Extract number of UEs\nK = size(signal,1);\n\n%Extract number of cells\nL = size(signal,2);\n\n%Prepare to save results\nSE = zeros(K,L);\n\n\n%% Go through all cells\nfor j = 1:L\n    \n    %Go through all UEs in cell j\n    for k = 1:K\n        \n        %Compute the SE in Theorem 4.6 using the formulation in (7.1)\n        SE(k,j) = prelogFactor*log2(1+(rho(k,j)*signal(k,j)) / (sum(sum(rho.*interference(:,:,k,j))) + 1));\n        \n    end\n    \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/functionComputeSE_DL_poweralloc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5731555673275383}}
{"text": "function bs = ISC(bs)\n% Calculate brain-wide inter-subject correlations in patterns across parcel means\n%\n% :Usage:\n% ::\n%\n%     bs = ISC(bs)\n%\n% For objects: Type methods(object_name) for a list of special commands\n%              Type help object_name.method_name for help on specific\n%              methods.\n%\n% ..\n%     Author and copyright information:\n%\n%     Copyright (C)2020 Tor Wager\n%\n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n%\n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n%\n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n% ..\n%\n% :Inputs:\n%\n%   **bs:**\n%        A brainpathway_multisubject object\n%\n%\n% :Optional Inputs:\n%   **'nofactor':**\n%        Omit factor analysis\n%\n%\n% :Outputs:\n%\n%   **bs:**\n%        A brainpathway_multisubject object\n%        Output is added to relevant object properties:\n%\n%         bs.connectivity.regions.isc = intersubject correlation matrix;\n%         bs.connectivity.regions.isc_subj_unusualness = 1/mean isc with others for each subject. 1/isc = [0 Inf] (bounded at zero);\n%         bs.connectivity.regions.isc_outliers = subjects with isc_subj_unusualness > 2 SD above the mean\n%         bs.connectivity.regions.isc_numfactors = estimated number of factors from elbow of PCA eigenvalues\n%         bs.connectivity.regions.isc_Lambda = Subject factor loadings, can be correlated with other variables\n%         bs.connectivity.regions.isc_Lambda_descrip = 'Lambdas are n_subjects x numfactors factor loadings, describing dimensions of subject similarity here';\n%\n%\n% :Examples:\n% ::\n%\n%    % None yet - example from HCP data\n%\n% :References:\n%\n% :See also:\n%   - methods(brainpathway_multisubject)\n%\n\n% ..\n%    Programmers' notes:\n%    12/2020 Created by Tor Wager\n% ..\n\n\nfprintf('Flattening conn matrices. ')\nmat = bs.flatten_conn_matrices('replacenans');\n\n% Find NaNs and replace with subject mean (so regions will have min=zero influence on isc)\n% Done now in flatten_conn_matrices\n% fprintf('Imputing missing values. ')\n%\n% whnan = isnan(mat);\n% subjmean = nanmean(mat');\n%\n% for i = 1:size(mat, 1)\n% \tmat(i, whnan(i, :)) = subjmean(i);\n% end\n\nfprintf('Calculating ISC. ')\nisc = corrcoef(double(mat'));\n\ncreate_figure('region isc');\nimagesc(isc); colorbar\ndrawnow\n\n%whnan = all(isnan(isc), 1);\n% anynans = sum(any(whnan, 2));\n\n% Subject unusualness (potential outliers)\n% --------------------------\nmeanisc = mean(isc) - (1./size(isc, 1)); % subtract the 1 on the diagonal\nisc_subj_unusualness = 1 ./ meanisc;\n\nisc_outliers = isc_subj_unusualness > (mean(isc_subj_unusualness) + 2 * std(isc_subj_unusualness));\n\nfigure; plot( 1 ./ meanisc, 'bo', 'MarkerFaceColor', [.3 .3 1]);\n\n\n% Factor analysis\n% --------------------------\nfprintf('Factor analysis ')\n\n% Choose # dimensions: where acceleration is greatest, i.e., derivative of\n% eigenvalues changes fastest and the curve flattens at the \"elbow\"\n[eigvec, eigval] = pcacov(isc);\ngg = gradient(gradient(eigval));\n[~, isc_numfactors] = max(gg);\n\nfprintf('(%d) factors. ', isc_numfactors)\n\nLambda = factoran(isc, isc_numfactors, 'Xtype', 'cov');\n\nif isc_numfactors > 1\n    \n    create_figure('region isc');\n    scatterhist(Lambda(:, 1), Lambda(:, 2));\n    xlabel('Factor 1')\n    ylabel('Factor 2')\n    \nend\n\nfprintf('\\n');\ndisp('Added results to bs.connectivity.regions.isc');\n\nbs.connectivity.regions.isc = isc;\nbs.connectivity.regions.isc_subj_unusualness = isc_subj_unusualness;\nbs.connectivity.regions.isc_outliers = isc_outliers;\nbs.connectivity.regions.isc_numfactors = isc_numfactors;\nbs.connectivity.regions.isc_Lambda = Lambda;\nbs.connectivity.regions.isc_Lambda_descrip = 'Lambdas are n_subjects x numfactors factor loadings, describing dimensions of subject similarity here';\n\n% bs.connectivity.regions.isc = intersubject correlation matrix;\n% bs.connectivity.regions.isc_subj_unusualness = 1/mean isc with others for each subject. 1/isc = [0 Inf] (bounded at zero);\n% bs.connectivity.regions.isc_outliers = subjects with isc_subj_unusualness > 2 SD above the mean\n% bs.connectivity.regions.isc_numfactors = estimated number of factors from elbow of PCA eigenvalues\n% bs.connectivity.regions.isc_Lambda = Subject factor loadings, can be correlated with other variables\n% bs.connectivity.regions.isc_Lambda_descrip = 'Lambdas are n_subjects x numfactors factor loadings, describing dimensions of subject similarity here';\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/@brainpathway_multisubject/ISC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5730994820524123}}
{"text": "%ISHOMOG Test if SE(3) homogeneous transformation\n%\n% ISHOMOG(T) is true (1) if the argument T is of dimension 4x4 or 4x4xN, else \n% false (0).\n%\n% ISHOMOG(T, 'valid') as above, but also checks the validity of the rotation\n% sub-matrix.\n%\n% Notes::\n% - The first form is a fast, but incomplete, test for a transform is SE(3).\n% - Does not work for the SE(2) case.\n%\n% See also ISROT, ISVEC.\n\n\n\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\nfunction h = ishomog(tr, rtest)\n    d = size(tr);\n    if ndims(tr) >= 2\n        h =  all(d(1:2) == [4 4]);\n\n        if h && nargin > 1\n            h = abs(det(tr(1:3,1:3)) - 1) < eps;\n        end\n\n    else\n        h = false;\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/common/ishomog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.573099477200314}}
{"text": "function polygon_grid_display ( n, nv, v, ng, xg )\n\n%*****************************************************************************80\n%\n%% POLYGON_GRID_DISPLAY displays grid points inside a polygon.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 April 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the number of subintervals.\n%\n%    Input, integer NV, the number of vertices in the polygon.\n%\n%    Input, real V[NV,2], the coordinates of the vertices.\n%\n%    Input, integer NG, the number of grid points.\n%\n%    Input, real XG(NG,2), the grid points.\n%\n  clf\n\n  hold on\n\n  plot ( [v(nv,1),v(1,1)], [v(nv,2),v(1,2)], 'r-', 'LineWidth', 2 );\n  for i = 1 : nv - 1\n    plot ( v(i:i+1,1), v(i:i+1,2), 'r-', 'LineWidth', 2 );\n  end\n  plot ( v(:,1), v(:,2), 'r.', 'MarkerSize', 25 );\n\n  vc(1,1) = sum ( v(1:nv,1) ) / nv;\n  vc(1,2) = sum ( v(1:nv,2) ) / nv;\n  for i = 1 : nv\n    plot ( [v(i,1),vc(1,1)], [v(i,2),vc(1,2)], 'b-', 'LineWidth', 2 );\n  end\n  plot ( xg(:,1), xg(:,2), 'b.', 'MarkerSize', 20 );\n  axis equal\n  title ( sprintf ( 'Polygonal grid, N = %d, NG = %d', n, ng ) )\n  grid on\n  hold off\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polygon_grid/polygon_grid_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.5730994620018075}}
{"text": "function gmst=utc2gmst(t,ut1_utc)\n\nep2000=[2000 1 1 12 0 0];\n\ntut=timeadd(t,ut1_utc);\n[ut,tut0]=time2sec(tut);\nt1=timediff(tut0,epoch2time(ep2000))/86400.0/36525.0;\nt2=t1^2; t3=t1^2;\ngmst0=24110.54841+8640184.812866*t1+0.093104*t2-6.2E-6*t3;\ngmst=gmst0+1.002737909350795*ut;\n\nif gmst<0\n    gmst=-mod(abs(gmst),86400.0)*pi/43200.0;\nelse\n    gmst=mod(abs(gmst),86400.0)*pi/43200.0;\nend\n\nreturn\n\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/common/utc2gmst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5730363148568566}}
{"text": "% Slopes of temperature distribution with altitude.\nm12=-6.5e-3;\nm34=9.92e-4;\nm45=2.78e-3;\nm67=-1.96e-3;\nm78=-3.94e-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/19470-isa-chart/slopes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.573036311779674}}
{"text": "function [ node_xy, element_node, element_neighbor ] = example2_q4_mesh ( ...\n  node_num, element_num )\n\n%*****************************************************************************80\n%\n%% EXAMPLE2_Q4_MESH sets up example #2 Q4 mesh.\n%\n%  Discussion:\n%\n%    The region is a semicircle.  This example includes degenerate elements\n%    (the first layer of elements is touching the origin, and so has a side\n%    of length zero).  The elements are not parallelograms.  And the elements\n%    vary in size.\n%\n%    Because of the treatment of node 1, algorithms for counting boundary \n%    edges may become \"confused\".\n%\n%    The appropriate values of NODE_NUM and ELEMENT_NUM can be found by\n%    calling EXAMPLE1_Q4_MESH_SIZE first.\n%\n%   29---30---31---32---33---34---35---36---37\n%    | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 |\n%   20---21---22---23---24---25---26---27---28\n%    | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |\n%   11---12---13---14---15---16---17---18---19\n%    |  9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |\n%    2----3----4----5----6----7----8----9---10\n%    |  1 |  2 |  3 |  4 |  5 |  6 |  7 |  8 |\n%    1----1----1----1----1----1----1----1----1\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 February 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer NODE_NUM, the number of nodes.\n%\n%    Input, integer ELEMENT_NUM, the number of elements.\n%\n%    Output, real NODE_XY(2,NODE_NUM), the coordinates of the\n%    nodes.\n%\n%    Output, integer ELEMENT_NODE(4,ELEMENT_NUM), the nodes\n%    that make up the elements.\n%\n%    Output, integer ELEMENT_NEIGHBOR(4,ELEMENT_NUM), the\n%    element neighbors on each side.  Negative values indicate edges that\n%    lie on the exterior.\n%\n  k = 1;\n  node_xy(1,k) = 0.0;\n  node_xy(2,k) = 0.0;\n\n  for row = 1 : 4\n    r = row;\n    for col = 0 : 8\n      a = ( 8 - col ) * pi / 8.0;\n      k = k + 1;\n      node_xy(1,k) = r * cos ( a );\n      node_xy(2,k) = r * sin ( a );\n    end\n  end\n\n  element = 0;\n  for row = 0 : 3\n    for col = 0 : 7\n      element = element + 1;\n      if ( row == 0 )\n        element_node(1,element) = 1;\n        element_node(2,element) = 1;\n        element_node(3,element) = col + 3;\n        element_node(4,element) = col + 2;\n      else\n        element_node(1,element) = element_node(4,element-8);\n        element_node(2,element) = element_node(3,element-8);\n        element_node(3,element) = element_node(2,element) + 9;\n        element_node(4,element) = element_node(1,element) + 9;\n      end\n    end\n  end\n\n  element = 0;\n  for row = 0 : 3\n    for col = 0 : 7\n      element = element + 1;\n      if ( row == 0 )\n        element_neighbor(1,element) = -1;\n      else\n        element_neighbor(1,element) = element - 8;\n      end\n      if ( col == 7 )\n        element_neighbor(2,element) = -1;\n      else\n        element_neighbor(2,element) = element + 1;\n      end\n      if ( row == 3 )\n        element_neighbor(3,element) = - 1;\n      else\n        element_neighbor(3,element) = element + 8;\n      end\n      if ( col == 0 )\n        element_neighbor(4,element) = - 1;\n      else\n        element_neighbor(4,element) = element - 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/quad_mesh/example2_q4_mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5730319422733317}}
{"text": "function r = rank(f, tol)\n%RANK      Rank of a SEPARABLEAPPROX.\n%   RANK(F) produces an estimate of the rank of the approximant F.\n%\n%   RANK(F, TOL) is the number of singular values of F greater than TOL*N, where\n%   N is the first singular value of F.\n%\n% See also LENGTH.\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    r = [];\n    return\nend\n\n% HARD tolerance. \nif ( nargin == 1 )\n    tol = 0;\nend\n\n% Compute the singular values of f. \ns = svd( f ); \n\n% Check for zero function.\nif ( max(s) == 0  )  \n    r = 0; \nelse\n    % r = no. of s.v. above relative tol.\n    r = find(s/s(1) > tol, 1, 'last');  \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/@separableApprox/rank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5730319328761755}}
{"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%==============================================================================\n% function [fh,ph,th] = checkDerivative(fctn,x0);\n%\n% checks the implementation of a derivative by comparing the function \n% with the Taylor-poly\n%\n%   \\| f(x0 + h ) - TP_p(x0,h) \\|   !=   O( h^{p+1} ) \n%\n% Input:\n%  fctn    function handle\n%  x0      expanding point\n%\n% Output:\n%  fh      figure handle to graphical output\n%  ph      plot handle\n%  th      text handle\n% call checkDerivative for a minimal example.\n%==============================================================================\n\nfunction varargout = checkDerivative(fctn,x0,varargin)\n\nif nargin == 0, % help and minimal example\n  help(mfilename); \n  fctn = @xSquare;  \n  x0   = 1;  \n  checkDerivative(fctn,x0);\n  return;\nend;\n\n\nfig = [];\nfor k=1:2:length(varargin),     % overwrites default parameter\n  eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend;\n\nFAIRmessage(mfilename,'.')\nfprintf('test derivative of function <%s>\\n',func2str(fctn));\n\nfprintf('T0 = |f0 - ft|, T1 = |f0+h*f0'' - ft|\\n');\n[f0,df] = feval(fctn,x0);  \nif ~isnumeric(df),\n  try\n    [f0,para,df] = feval(fctn,x0);  \n  catch\n    if isfield(df,'Q'), df = df.Q;  end;\n  end;\nend;\n\nh = logspace(-1,-10,10);\nv = randn(size(x0)); \nif isnumeric(df),\n  dvf = df*v; \nelseif isa(df,'function_handle'),\n  dvf = df(v);\nelse\n  keyboard;\nend;\n\nfor j=1:length(h),\n  ft = feval(fctn,x0+h(j)*v);      % function value\n  T0(j) = norm(f0-ft);             % TaylorPoly 0\n  T1(j) = norm(f0+h(j)*dvf - ft);  % TaylorPoly 1\n  fprintf('h=%12.4e     T0=%12.4e    T1=%12.4e\\n',h(j),T0(j),T1(j));\nend;\n\nfh = FAIRfigure(fig);\nph = loglog(h,[T0;T1]); set(ph(2),'linestyle','--')\nth = title(sprintf('%s: |f-f(h)|,|f+h*dvf -f(h)| vs. h',mfilename));\n\nif nargout>0,\n  varargout = {fh,ph,th};\nend;\nFAIRmessage('.');\n%------------------------------------------------------------------------------\nfunction [y,dy] = xSquare(x)\nif nargin == 0, return; end;\ny = x.^2; dy = reshape(2*x,1,[]);\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/numerics/checkDerivative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.5730319304202404}}
{"text": "function disp(tt,name,varargin)\n%Command window display of a QTT_TUCKER\n%\ndisp_mode_sizes=false;\nfor i=1:2:length(varargin)-1\n    switch lower(varargin{i})\n        case 'modes'\n            disp_mode_sizes=varargin{i+1};\n        otherwise\n            error('Unrecognized option: %s\\n',varargin{i});\n    end\nend\n\nif ~exist('name','var')\n    name = 'ans';\nend\nfprintf('%s is a QTT-tucker tensor: \\n',name);\nfprintf('Tucker ranks: \\n');\nsz=size(tt.core);\nrk=rank(tt.core);\nfor i=1:tt.dphys-1\n   fprintf('%d-',sz(i)); \nend\nfprintf('%d\\n',sz(tt.dphys));\nfprintf('TT-ranks for the core: \\n');\nfor i=1:tt.dphys\n   fprintf('%d-',rk(i)); \nend\nfprintf('%d\\n',rk(tt.dphys+1));\ntk=tt.tuck;\nfprintf('TT-ranks/mode sizes for the factors: \\n');\nfor i=1:tt.dphys\n   di=ndims(tk{i});\n   ri=rank(tk{i});\n   ni=size(tk{i});\n   fprintf('Factor %d: ',i);\n   for j=1:di\n      fprintf('%d-',ri(j));\n   end   \n   fprintf('%d\\n',ri(di+1));\n   if ( disp_mode_sizes ) \n     fprintf('Modes   : ');\n     for j=1:di-1\n       fprintf('%d-',ni(j));\n     end\n     fprintf('%d\\n',ni(di));\n   end\nend\n% %fprintf('r(1)=%d \\n', r(1));\n% for i=1:d\n%    fprintf('r(%d)=%d \\t n(%d)=%d \\n',i,r(i),i,n(i));\n% end\n% fprintf('r(%d)=%d \\n',d+1,r(d+1));\n\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/@qtt_tucker/disp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5730319210230843}}
{"text": "function y = time_varying_estimate(meth,data,varargin)\n% Performs correlation operation (default) or any function you pass in (as a function handle) on symmetric moving average of data\n%\n% :Usage:\n% ::\n%\n%     y = time_varying_estimate(meth,data,[window width],[function handle])\n%\n% - Works on all columns of the data input matrix together, so function handles can\n%   operate on multivariate data (e.g. cond())\n% - For moving averages, use the Matlab built-in smoothdata.m\n%\n% :Inputs:\n%\n%   **meth:**\n%   Window-type options, either:\n%   - 'gaussian'\n%   - 'tukey'\n%\n% :Optional Inputs: \n%\n%   **stepby:**\n%\n%   Sometimes input data is very high resolution, and it would take too much\n%   time to work element by element across the inputs.  You can enter an\n%   option here to compute estimates at every n-th lag.\n%\n% \t**Any function handle**\n%   Any function handle to a function to evaluate on local rows of [data]\n%\n%   e.g., @corr\n%\n% :Examples:\n% ::\n%\n%    y =  time_varying_estimate('gaussian',data,20);\n%\n%    % Generate sample data:\n%    x = mvnrnd([0 0], [1 .6; .6 1], 100);\n%\n%    % Correlation between columns of x:\n%    r = time_varying_estimate('tukey', x, 20);\n% \n%    % St. deviation of first column\n%    mystd = time_varying_estimate('tukey', x(:, 1), 20, @(y) std(y));\n%\n% ..\n%    By Tor Wager\n%    Last updated: Dec 2008\n% ..\n\nnshift = 0;\nstepby = 1;                 % step size for shift\ncenter_local_data = true;   % mean-center local data: good for corr, bad for moving average\n\n% set up the kernel\n% -------------------------------------------\nswitch meth\n    \n    case 'gaussian'\n        \n         ntrials = varargin{1};\n         kern = normpdf(-3:6/ntrials:3); \n         kern = kern./max(kern);            % norm to max of 1\n         \n         mymax = find(kern == max(kern));\n         nshift = mymax - 1;  % kernel shifts by n points; adjust\n         \n         kern = kern';  % column\n\n    case 'tukey'\n        % Window length is the zero-influence to zero-influence time\n        kern = tukeywin(varargin{1});\n        nshift = round(varargin{1} ./ 2);\n        \n        % kludgey adjust in case we need extra element\n        %if length(i - shift : i + nshift) > length(kern)\n            kern = [kern; 0];\n        %end\n    otherwise error('Unknown method.')\n        \nend\n\n% set up function handle\n% -------------------------------------------\nif length(varargin) > 1\n    fhandle = varargin{2};\nelse\n    fhandle = @(y) my_corrcoef(y);\nend\n\nif length(varargin) > 2\n    stepby = varargin{3};\nend\n\n% set up data\n% -------------------------------------------\n[nobs,ncols] = size(data);\n\n% replicate kernel for each column\nkern = repmat(kern,1,ncols);\n\nif nobs < nshift, error('Not enough observations to support kernel.'); end\ny = zeros(nobs,1);\n\n% pad data at ends to avoid edge artifacts\n% -------------------------------------------\npaddat = data(end:-1:end-nshift,:);\n\ndata = [data; paddat];\n\npaddat = data(nshift:-1:1,:);\n\ndata = [paddat; data];\n\n\n% execute\n% -------------------------------------------\nfor i = [(nshift+1):stepby:(nobs + nshift) (nobs + nshift)]\n    % start at nshift to avoid ends; data is padded\n    \n    % set up windowed data\n        \n    dati = data(i - nshift : i + nshift,:);\n    \n    if center_local_data\n        dati = scale(dati,1) .* kern;   % center and multiply by kern so data taper towards mean\n    else\n        dati = dati .* kern;\n    end\n    \n    % execute: IN DEVELOPMENT: THIS is hard-coded for weighted correlation\n    %r = weighted_corrcoef(dati,kern(:,1));\n    %r = corrcoef(dati);\n    \n    y(i, :) = fhandle(dati);  %r(1,2);\n    \n    %y(:,i) = tmpy(nshift+1:nshift+nobs);\n    \nend\n\nif stepby == 1\n    y = y( (nshift+1):(nobs + nshift) );\n\nelse\n    indx = [(nshift+1):stepby:(nobs + nshift) (nobs + nshift)];\n    y = interp1(indx, y(indx), (nshift+1):(nobs + nshift));\n\nend\n\nend\n\n\n\nfunction y = my_corrcoef(dati)\nr = corrcoef(dati);\ny = r(1,2);\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/time_varying_estimate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5730319210230843}}
{"text": "function stirling2_test ( )\n\n%*****************************************************************************80\n%\n%% STIRLING2_TEST tests STIRLING2.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    19 October 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 8;\n  n = 8;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'STIRLING2_TEST\\n' );\n  fprintf ( 1, '  STIRLING2: Stirling numbers of second kind.\\n' );\n  fprintf ( 1, '  Get rows 1 through %d\\n', m );\n  fprintf ( 1, '\\n' );\n \n  s2 = stirling2 ( m, n );\n \n  for i = 1 : m\n    fprintf ( 1, '  %4d', i );\n    for j = 1 : n\n      fprintf ( 1, '  %6d', s2(i,j) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/stirling2_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.5730319174458277}}
{"text": "function [] = visBinaryCRBMLearning(RBM);\n%------------------------------------------------------------------\n%  visBinaryCRBMLearning(RBM);\n%------------------------------------------------------------------\n% DES\n\n\nfigure(99)\ncolormap gray\nset(99,'name','Learning Convolutional RBM (Binary Visible)');\nsubplot(221);\nimagesc(RBM.auxVars.batchX'); axis image; axis off;\ntitle('Visible Data');\n\nsubplot(222);\nimagesc(RBM.eVis'); axis image; axis off;\ntitle('Reconstruction');\n\n[c,r,k]=size(RBM.eHid);\nsubplot(223);\ndata = reshape(RBM.eHid,r*c,k);\nvisWeights(data,1);\ntitle('Feature Maps');\n\n[c,r,k]=size(RBM.W);\nsubplot(224);\ndata = reshape(RBM.W,r*c,k);\nvisWeights(data,1);\ntitle('Learned Filters');\ndrawnow\n\nfigure(98)\ncolormap gray;\nset(98,'name','Learning Convolutional RBM (Binary Visible)');\nsubplot(221);\nbar(1:RBM.nFM,RBM.c);  axis square\nxlim([1 RBM.nFM]);axis square;\nxlabel('Feature Index')\ntitle('Hidden Biases')\n\nsubplot(222);\ndata = squeeze(mean(mean(RBM.eHid0)));\nbar(1:RBM.nFM,data);\nxlim([1 RBM.nFM]);axis square;\nxlabel('Feature Index')\ntitle(sprintf('Mean Hidden Activation\\nactual=%g \\n target = %g\\n',mean(data),RBM.sparsity))\ndrawnow\n\nsubplot(223);\ndata = reshape(RBM.dW,r*c,k);\nvisWeights(data); axis image; axis off\ntitle('Weight Gradients')\n\nsubplot(224);\nbar(1:RBM.nFM,RBM.auxVars.dcSparse); axis square;\nxlim([1 RBM.nFM]);axis square;\nxlabel('Hidden Feature Index')\ntitle('Sparsenss Offset')\n%  title('Hidden Bias Gradients')\n\n", "meta": {"author": "dustinstansbury", "repo": "medal", "sha": "f33110422ed937f97aaaf3aeb24338c6f13536d7", "save_path": "github-repos/MATLAB/dustinstansbury-medal", "path": "github-repos/MATLAB/dustinstansbury-medal/medal-f33110422ed937f97aaaf3aeb24338c6f13536d7/visualizations/visBinaryCRBMLearning.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5730266049914826}}
{"text": "function [ n_data, h, a, t ] = owen_values ( n_data )\n\n%*****************************************************************************80\n%\n%% OWEN_VALUES returns some values of Owen's T function.\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%    In Mathematica, the function can be evaluated by:\n%\n%      fx = 1/(2*Pi) * Integrate [ E^(-h^2*(1+x^2)/2)/(1+x^2), {x,0,a} ]\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    10 December 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, real H, a parameter.\n%\n%    Output, real A, the upper limit of the integral.\n%\n%    Output, real T, the value of the function.\n%\n  n_max = 22;\n\n  a_vec = [ ...\n    0.5000000000000000E+00, ...\n    0.1000000000000000E+01, ...\n    0.2000000000000000E+01, ...\n    0.3000000000000000E+01, ...\n    0.5000000000000000E+00, ...\n    0.1000000000000000E+01, ...\n    0.2000000000000000E+01, ...\n    0.3000000000000000E+01, ...\n    0.5000000000000000E+00, ...\n    0.1000000000000000E+01, ...\n    0.2000000000000000E+01, ...\n    0.3000000000000000E+01, ...\n    0.5000000000000000E+00, ...\n    0.1000000000000000E+01, ...\n    0.2000000000000000E+01, ...\n    0.3000000000000000E+01, ...\n    0.5000000000000000E+00, ...\n    0.1000000000000000E+01, ...\n    0.2000000000000000E+01, ...\n    0.3000000000000000E+01, ...\n    0.1000000000000000E+02, ...\n    0.1000000000000000E+03 ];\n\n  h_vec = [ ...\n    0.1000000000000000E+01, ...\n    0.1000000000000000E+01, ...\n    0.1000000000000000E+01, ...\n    0.1000000000000000E+01, ...\n    0.5000000000000000E+00, ...\n    0.5000000000000000E+00, ...\n    0.5000000000000000E+00, ...\n    0.5000000000000000E+00, ...\n    0.2500000000000000E+00, ...\n    0.2500000000000000E+00, ...\n    0.2500000000000000E+00, ...\n    0.2500000000000000E+00, ...\n    0.1250000000000000E+00, ...\n    0.1250000000000000E+00, ...\n    0.1250000000000000E+00, ...\n    0.1250000000000000E+00, ...\n    0.7812500000000000E-02, ...\n    0.7812500000000000E-02, ...\n    0.7812500000000000E-02, ...\n    0.7812500000000000E-02, ...\n    0.7812500000000000E-02, ...\n    0.7812500000000000E-02 ];\n\n  t_vec = [ ...\n    0.4306469112078537E-01, ...\n    0.6674188216570097E-01, ...\n    0.7846818699308410E-01, ...\n    0.7929950474887259E-01, ...\n    0.6448860284750376E-01, ...\n    0.1066710629614485E+00, ...\n    0.1415806036539784E+00, ...\n    0.1510840430760184E+00, ...\n    0.7134663382271778E-01, ...\n    0.1201285306350883E+00, ...\n    0.1666128410939293E+00, ...\n    0.1847501847929859E+00, ...\n    0.7317273327500385E-01, ...\n    0.1237630544953746E+00, ...\n    0.1737438887583106E+00, ...\n    0.1951190307092811E+00, ...\n    0.7378938035365546E-01, ...\n    0.1249951430754052E+00, ...\n    0.1761984774738108E+00, ...\n    0.1987772386442824E+00, ...\n    0.2340886964802671E+00, ...\n    0.2479460829231492E+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    h = 0.0;\n    a = 0.0;\n    t = 0.0;\n  else\n    h = h_vec(n_data);\n    a = a_vec(n_data);\n    t = t_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/owen_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5730266046470134}}
{"text": "%*******************************************************\n%\n% DESCRIPTION:\n% \t\tThis script contains many useful constants for GPS\n%       and related work.  It should be kept in only\n%       one place so that updates are immediately available \n%       to all other scripts/functions.\n%  \n% ARGUMENTS:\n% \t\tNone, just call this script to place \n% \t\tthe constants in your workspace.\n%  \n% OUTPUT:\n% \t\tVariables in your current workspace.\n%  \n% CALLED BY:\n% \t\tMany other codes.\n%\n% FUNCTIONS CALLED:\n% \t\tNone.\n%\n% MODIFICATIONS:    \n%       XX-XX-02  :  Jan Weiss - Original\n%       07-25-04  :  Jan Weiss - updated header.\n%       10-19-04  :  Jan Weiss - Cleanup and added \n%                                some conversion factors.\n%                 :  See SVN log for further updates.\n% \n% Colorado Center for Astrodynamics Research\n% Copyright 2005 University of Colorado, Boulder\n%*******************************************************\n\n% GENERAL CONSTANTS\n% =========================================================================\nc = 299792458;          %----> Speed of light (meters/s).\nRe = 6378137 ;          %----> Earth Radius (meters)\n% =========================================================================\n\n\n% CONVERSION FACTORS\n% =========================================================================\nHz2MHz = 1E-6;\nMHz2Hz = 1E6;\ns2ns = 1E9;\nns2s = 1E-9;\ns2micros = 1E6;\nmicros2s = 1E-6;\ns2ms = 1E3;\nms2s = 1E-3;\ndtr = pi / 180;\nrtd = 180 / pi;\nm2cm = 100;\ncm2m = 1 / 100;\nm2mm = 1000;\nmm2m = 1 / 1000;\nft2m = 0.3048;  % Source: http://www.nodc.noaa.gov/dsdt/ucg/\nm2ft = 1 / 0.3048;\nns2m = c * ns2s;  % Converts time in nano-sec to distance,\n                  % assuming the speed of light.\n% =========================================================================\n  \n\n% GNSS SPECIFIC CONSTANTS\n% =========================================================================\nL1 = 1575.42e6;         %----> Freqs in Hz.\nL2 = 1227.60e6;\nL5 = 1176.45e6;\n\nL1MHz = 1575.42;        %----> Freqs in MHz.\nL2MHz = 1227.60;\nL5MHz = 1176.45;\n\nL1GHz = 1.57542;        %----> Freqs in GHz.\nL2GHz = 1.22760;\nL5GHz = 1.17645;\n\nLAMBDA_L1 = c / L1;     %----> Wavelengths in meters.\nLAMBDA_L2 = c / L2;\nLAMBDA_L5 = c / L5;\n\nCA_CODE_RATE = 1.023e6; %----> C/A and P code chipping rate in chips/s.\nP_CODE_RATE = 10.23e6;\n\nCA_CHIP_PERIOD = 1 / CA_CODE_RATE;   %----> C/A & P code chip periods in s.\nP_CHIP_PERIOD = 1 / P_CODE_RATE;\n\nCA_CHIP_LENGTH = c / CA_CODE_RATE;  %----> C/A & P code chip lengths in meters.\nP_CHIP_LENGTH = c / P_CODE_RATE;\n\nCA_CODE_LENGTH = 1023;  % chips\n% =========================================================================\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/lib/gnss/set_constants.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5730265991098757}}
{"text": " function X = nufft2_bilinear(omega, x, K1, K2, n_shift)\n%function X = nufft2_bilinear(omega, x, K1, K2, n_shift)\n%\tin:\n%\t\tomega\t[M 2]\t\tfrequencies in radians\n%\t\tx\t[N1 N2]\t\timage dimensions\n%\t\tJ\t\t\t# of neighbors used\n%\t\tK1,K2\t\t\tFFT sizes (should be > N1,N2)\n%\t\tn_shift [2]\t\tn = 0-n_shift to N-1-n_shift\n%\tout:\n%\t\tX\t[M 1]\tDTFT2 at omega, approximated by bilinear interp\n%\n%\tLike fft(), this expects the signals to be x(0,0), ...\n%\tUse n_shift = [N1/2 N2/2] for x(-N1/2,-N2/2), ...\n%\n% Copyright 2001-9-20, Jeff Fessler, University of Michigan\n\nwarn('This function is obsolete.  Use nufft_init with the \"linear\" option')\n\n% if no arguments, then run a simple test\nif nargin < 1\n\tN1 = 4;\n\tN2 = 8;\n\tn_shift = [2.7 3.3];\n\tx = [[1:N1]'*ones(1,3), ones(N1,N2-3)]; % test signal\n%\tx = zeros(N1,N2); x(1,1) = 1;\n\tif 0\t% test with uniform frequency locations\n\t\to1 = 2 * pi * [0:(N1-1)]' / N1;\n\t\to2 = 2 * pi * [0:(N2-1)]' / N2;\n\t\t[o1, o2] = ndgrid(o1, o2);\n\t\tomega = [o1(:) o2(:)];\n\telse\t% nonuniform frequencies\n\t\to1 = [0 7.2 2.6 3.3]';\n\t\to2 = [0 4.2 -1 5.5]';\n\t\tomega = [o1(:) o2(:)];\n\tend\n\tXd = dtft2(x, omega, n_shift);\n\tXb = nufft2_bilinear(omega, x, 2*N1, 2*N2, n_shift);\n%\tXb = reshape(Xb, N1, N2)\n%\tdisp([Xd Xb Xb-Xd])\n\thelp(mfilename)\n\tdisp(sprintf('max %% difference = %g', max_percent_diff(Xd,Xb)))\n\treturn\nend\n\n\nif ~isvar('n_shift') || isempty(n_shift), n_shift = [0 0]; end\nif ~isvar('useloop') || isempty(useloop), useloop = 0; end\n\nM = size(omega,1);\n[N1 N2] = size(x);\n\nkoff1 = bilinear_offset(omega(:,1), K1);\t% [M 1] nearest\nkoff2 = bilinear_offset(omega(:,2), K2);\t% [M 1] nearest\n\n% indices into oversampled FFT components\nk1 = mod(outer_sum(koff1, [0 1]), K1) + 1;\t% [M 2] {1,...,K1}\nk2 = mod(outer_sum(koff2, [0 1]), K2) + 1;\t% [M 2] {1,...,K2}\n\n% 1D interpolation coefficient vectors\n[u1l u1r] = interp_coef(omega(:,1), koff1, K1, N1);\t% [M 1]\n[u2l u2r] = interp_coef(omega(:,2), koff2, K2, N2);\t% [M 1]\n\n\n% precorrect for bilinear interpolation filtering\nif 0\n\twarning 'applying precorrection'\n\t[i1, i2] = ndgrid([0:(N1-1)]-n_shift(1), [0:(N2-1)]-n_shift(2));\n\ttmp = (nufft_sinc(i1 / K1) .* nufft_sinc(i2 / K2)).^2;\n\tprintm('sinc correction min=%g', min(tmp(:)))\n\tx = x ./ tmp;\nend\n\n% FFT and bilinear interpolation\n% can't use interp2 here because we want periodic end conditions!\n% oh, maybe i could with a little padding of ends... \nXk = fft2(x, K1, K2);\nkk11 = k1(:,1) + (k2(:,1) - 1) * K1;\nkk21 = k1(:,2) + (k2(:,1) - 1) * K1;\nkk12 = k1(:,1) + (k2(:,2) - 1) * K1;\nkk22 = k1(:,2) + (k2(:,2) - 1) * K1;\nt1 = u1l .* Xk(kk11) + u1r .* Xk(kk21);\nt2 = u1l .* Xk(kk12) + u1r .* Xk(kk22);\nX = u2l .* t1 + u2r .* t2;\n\n% apply phase shift\nphase = exp(i * (omega * n_shift(:)));\t% [M 1]\nX = X .* phase;\n\n\n% index from 0 to K-1 (will modulo later)\nfunction koff = bilinear_offset(om, K)\ngam = 2*pi/K;\nkoff = floor(om / gam);\n\n% make 1D interpolation coefficient vectors\nfunction [ul, ur] = interp_coef(om, koff, K, N)\ngam = 2*pi/K;\nul = 1 - (om/gam - koff);\nur = 1 - ul;\nul = ul .* kphase(om - koff * gam, N);\nur = ur .* kphase(om - (koff+1) * gam, N);\n\n% natural phase function. trick: force it to be 2pi periodic\nfunction ph = kphase(om, N)\nph = exp(-i * mod0(om,2*pi) * (N-1)/2);\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/archive/nufft2_bilinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5730265991098757}}
{"text": "% add the path of RBM code\naddpath('..');\naddpath('~/work/Algorithms/liblinear-1.7/matlab');\n\n% load MNIST\nload 'mnist_14x14.mat';\n\n% shuffle the training data\nX_labels = X_labels + 1;\nX_test_labels = X_test_labels + 1;\n\nperm_idx = randperm (size(X,1));\n\nn_all = size(X, 1);\nn_train = ceil(n_all * 3 / 4);\nn_valid = floor(n_all /4);\n\nX_valid = X(perm_idx(n_train+1:end), :);\nX_valid_labels = X_labels(perm_idx(n_train+1:end));\nX = X(perm_idx(1:n_train), :);\nX_labels = X_labels(perm_idx(1:n_train));\n\nlayers = [size(X,2), 500, 500, 10];\nn_layers = length(layers);\nblayers = [1, 1, 1, 1];\n\nuse_tanh = 0;\ndo_pretrain = 1;\n\nif do_pretrain\n    Ds = cell(n_layers - 2, 1);\n    H = X;\n    H_valid = X_valid;\n\n    for l = 1:n_layers-2\n        % construct DAE and use default configurations\n        D = default_dae (layers(l), layers(l+1));\n\n        D.data.binary = blayers(l);\n        D.hidden.binary = blayers(l+1);\n\n        if use_tanh \n            if l > 1\n                D.visible.use_tanh = 1;\n            end\n            D.hidden.use_tanh = 1;\n        else\n            if D.data.binary\n                mH = mean(H, 1)';\n                D.vbias = min(max(log(mH./(1 - mH)), -4), 4);\n            else\n                D.vbias = mean(H, 1)';\n            end\n        end\n\n        D.learning.lrate = 1e-1;\n        D.learning.lrate0 = 5000;\n        D.learning.minibatch_sz = 128;\n\n        D.noise.drop = 0.2;\n        D.noise.level = 0;\n\n        %D.adagrad.use = 1;\n        %D.adagrad.epsilon = 1e-8;\n        D.adadelta.use = 1;\n        D.adadelta.epsilon = 1e-8;\n        D.adadelta.momentum = 0.99;\n\n        D.valid_min_epochs = 10;\n\n        if blayers(l+1)\n            D.cae.cost = 0.01;\n            %D.sparsity.target = 0.1;\n            %D.sparsity.cost = 0.01;\n        end\n\n        D.iteration.n_epochs = 500;\n\n        % save the intermediate data after every epoch\n        D.hook.per_epoch = {@save_intermediate, {sprintf('dae_mnist_%d.mat', l)}};\n\n        % print learining process\n        D.verbose = 0;\n        % display the progress\n        D.debug.do_display = 0;\n\n        % train RBM\n        fprintf(1, 'Training DAE (%d)\\n', l);\n        tic;\n        D = dae (D, H, H_valid, 0.1);\n        fprintf(1, 'Training is done after %f seconds\\n', toc);\n\n        H = dae_get_hidden(H, D);\n        H_valid = dae_get_hidden(H_valid, D);\n\n        Ds{l} = D;\n    end\nend\n\nM = default_mlp (layers);\n\nM.output.binary = blayers(end);\nM.hidden.use_tanh = use_tanh;\n\nM.valid_min_epochs = 10;\nM.dropout.use = 1;\n\nM.hook.per_epoch = {@save_intermediate, {'mlp_mnist.mat'}};\n\nM.learning.lrate = 1e-3;\nM.learning.lrate0 = 5000;\nM.learning.minibatch_sz = 128;\n\nM.adadelta.use = 1;\nM.adadelta.epsilon = 1e-8;\nM.adadelta.momentum = 0.99;\n\nM.noise.drop = 0;\nM.noise.level = 0;\n\nM.iteration.n_epochs = 100;\n\nif do_pretrain\n    for l = 1:n_layers-2\n        M.biases{l+1} = Ds{l}.hbias;\n        M.W{l} = Ds{l}.W;\n    end\nend\n\nfprintf(1, 'Training MLP\\n');\ntic;\nM = mlp (M, X, X_labels, X_valid, X_valid_labels, 0.1);\nfprintf(1, 'Training is done after %f seconds\\n', toc);\n\n[pred] = mlp_classify (M, X_test);\nn_correct = sum(X_test_labels == pred);\n\nfprintf(2, 'Correctly classified test samples: %d/%d\\n', n_correct, size(X_test, 1));\n\n\n\n\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/example/example_mnist_mlp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5730265939172076}}
{"text": "function theta = moment_estimation( M, default_beta, default_dev )\n\n% Parameter estimates from moment equations\n% Note that parameter estimation is bad for small data sets: The\n% variances can be negative and the beta's are numerically too large.\n%\n% Syntax:\n%   E = moment_estimation( M, n_dev[, def_b, max_v] )\n%\n% Input:\n%   M       : Matrix with moments from compute_moments.\n%\n%   def_b   : If beta is estimated to be negative or too large it is \n%             replaced by DEF_B\n%\t\t\t  Default: 1\n%\n%   def_std : If sigma and kappa are estimated to be negative they are\n%             replaced by STD_VAL.\n%             Default: 0.5\n%\n%\n% Output:\n%   theta : L-by-5-by-D matrix where L is the number of levels in the\n%           wavelet transform, D is the number of directions and the\n%           (l+1)'th row is estimates of\n%           mu_l, sigma_l, alpha_l, beta_l, kappa_l\n%\n% See also: COMPUTE_MOMENTS\n\n% Default values\nif ~exist( 'default_beta', 'var' )\n    default_beta = 1;\nend\n\nif ~exist( 'std_val', 'var' )\n    default_dev = 0.5;\nend\n\n% Preallocate output\nL = size(M, 1) - 1;\ntheta = zeros( L+1, 5, size(M,3) );\n\n% Indices for beta's, alpha's and kappa's\nidx = 1:L;\n\n% sigma's\nsigma2 = log(M(:,2,:)/3) - 2*log(M(:,1,:));\ntheta(:, 2, :) = sqrt( sigma2 );\n\n% mu's\ntheta(:, 1, :) = log(M(:,1,:)) - sigma2/2;\n\n% TODO: Is there a good way to test if the beta estimate is too large\n\n% beta's\ntheta(1+idx, 4, :) = ( log(M(1+idx,3,:)) - 2*log(M(1+idx,1,:)) ) ./ ...\n    ( log(M(idx,4,:)) - log(M(1+idx,1,:)) - log(M(idx,1,:)) );\n\n% Restrict large beta's\nbeta_idx = false( size(theta) );\nbeta_idx(1+idx, 4, :) = true;\n\npositive_idx = real(theta) > 2;\nnegative_idx = real(theta) < 0;\n\ntheta( beta_idx & (positive_idx | negative_idx) ) = default_beta;\n\n% alpha's\ntheta(1+idx, 3, :) = theta(1+idx, 1, :) - theta(1+idx, 4, :).*theta(idx, 1, :);\n\n% kappa's\nkappa2 = sigma2(1+idx, :, :) - theta(1+idx, 4, :).^2 .* sigma2(idx, :, :);\ntheta(1+idx, 5, :) = sqrt( kappa2 );\n\n\n% ---------------------------------------------------------------------- \n%\n% If any of the variances are estimated to be negative, we estimate \n% parameters in the homogeneous GLG model\n\nind = find( imag(theta) );\n[~, ~, D] = ind2sub( size(theta), ind );\nD = unique( D );\n\nif isempty(D)\n    return\nend\n\nmu    = theta(1,1,:);\nsigma = theta(1,2,:);\nalpha = theta(2,3,:);\nbeta  = theta(2,4,:);\nkappa = theta(2,5,:);\n\n% Default values\nsigma( imag(sigma) ~= 0 ) = default_dev;\nkappa( imag(kappa) ~= 0 ) = default_dev;\nalpha( imag(alpha) ~= 0 ) = -default_beta;\nbeta( imag(beta) ~= 0 )   = default_beta;\n\nhomogeneous_theta = homogeneous_to_full_GLG( L+1, mu, sigma, alpha, beta, kappa );\ntheta(:,:,D) = homogeneous_theta(:,:,D);\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/GLG/moment_estimation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5730265935727381}}
{"text": "function [winscores]=mvg_windowbec_fast(img, windows)\n\nif size(img,3)==3\n  if isinteger(img)\n    grayimage=double(rgb2gray(img))/255.0;\n    img=double(img)/255.0;\n  else\n    grayimage=0.2989*img(:,:,1)+0.5879*img(:,:,2)+0.1140*img(:,:,3);\n  end\nelse\n  grayimage=img;\nend\n\ngmagth=0.02;%0.025;\nnsubbox=3;\nnbin=4; % 4, 6 or 8\nbinids=1:nbin;\nbinbounds=[1:2:2*nbin]/(2*nbin)*180;\nbinbounds=binbounds/180*pi;\nbincenters=[0:2:(2*nbin-1)]/(2*nbin)*180;\nbincenters=bincenters/180*pi;\nbinvects=[cos(bincenters);sin(bincenters)];\n\nnr=size(grayimage,1);\nnc=size(grayimage,2);\n%edgeim=edge(grayimage,'canny');\n[X,Y]=meshgrid(1:nc,1:nr);\n\n[gv,Ngv,gvx,gvy]=gaussianderiv1D_(1);\nGx=zeros(nr,nc);\nGy=zeros(nr,nc);\nif size(img,3)>1\n  for cdim=1:size(img,3)\n    Gxc=conv2(gv,gvx,img(:,:,cdim),'same');\n    Gindicator=logical(abs(Gxc)>abs(Gx));\n    Gx=Gindicator.*Gxc+~Gindicator.*Gx;\n    Gyc=conv2(gvy,gv,img(:,:,cdim),'same');\n    Gindicator=logical(abs(Gyc)>abs(Gy));\n    Gy=Gindicator.*Gyc+~Gindicator.*Gy;\n  end\nelse\n  Gx=conv2(gv,gvx,grayimage,'same');%.*edgeim;\n  Gy=conv2(gvy,gv,grayimage,'same');%.*edgeim;\nend\n\nGx(1:Ngv,:)=0;Gx((nr-Ngv+1):nr,:)=0;\nGx(:,1:Ngv)=0;Gx(:,(nc-Ngv+1):nc)=0;\nGy(1:Ngv,:)=0;Gy((nr-Ngv+1):nr,:)=0;\nGy(:,1:Ngv)=0;Gy(:,(nc-Ngv+1):nc)=0;\n\n\nGmag=sqrt(Gx.^2+Gy.^2);\nGxu=Gx./(Gmag+eps);\nGyu=Gy./(Gmag+eps);\n\n[cedge,cannyth]=edge(grayimage,'canny');\n[cedge,cannyth]=edge(grayimage,'canny',0.5*cannyth);\n\ncedgeint=integralimage(double(cedge));\n\nGvalid=conv2(gv,gv,double(cedge).*(Gmag>gmagth),'same');\n\nGxvalid=Gx.*Gvalid;\nGyvalid=Gy.*Gvalid;\n\nGs(:,:,1)=Gxvalid;\nGs(:,:,2)=Gyvalid;\n%keyboard\n%figure;sc(Gs,'flow');\n%keyboard\n\noribins=zeros(nr,nc,nbin);\ntmp=zeros(nr,nc);\ngvs=gaussianderiv1D_(1.5);\noribinintim=zeros(nr,nc,nbin);\nfor i=1:nbin\n  tmp=Gmag.*Gvalid.*reshape(abs([Gxu(:) Gyu(:)]*binvects(:,i)),nr,nc);\n  tmp=conv2(gvs,gvs,tmp,'same');\n  oribins(:,:,i)=tmp;\n  %oribinintim(:,:,i)=integralimage(tmp);\n  %figure;sc(tmp);\nend\noribinsum=sum(oribins,3);\noribinsummax=max(oribinsum(:));\noribins=oribins/oribinsummax;\noribinsum=oribinsum/oribinsummax;\nfor i=1:nbin\n  oribinintim(:,:,i)=integralimage(oribins(:,:,i));\n  %figure;sc(tmp);\nend\n\nwincx=0.5*(windows(:,1)+windows(:,3));\nwincy=0.5*(windows(:,2)+windows(:,4));\nnw=size(windows,1);\n\n%for i=1:4\n  winhists=zeros(2*nsubbox,nbin,2*nsubbox);\n  winhistsums=zeros(2*nsubbox,2*nsubbox);\n%end\n\nwinscores=zeros(nw,1);\nwinareas=zeros(nw,1);\nnedgepixels=zeros(nw,1);\n\nonesv=ones(2*nsubbox+1,1);\nonesh=ones(1,2*nsubbox+1);\n\nsubboxind=1:(2*nsubbox);\nintersection=0;\nsuma=0;sumb=0;\n\nBoxWeights=[ones(1,6); 1 0.5*ones(1,4) 1; 1 0.5 0 0 0.5 1];\nBoxWeights=[BoxWeights;flipud(BoxWeights)];\nBoxIndices=[2 3*ones(1,4) 4; 1 2 3 3 4 1; 1 1 2 4 1 1;1 1 4 2 1 1; ...\n\t    1 4 3 3 2 1; 4 3*ones(1,4) 2];\n\nwinscores=bescores(windows,oribinintim,nbin,nsubbox,BoxWeights,BoxIndices);\n%fprintf('BE scores computed in C \\n');\nif 0\nfor i=1:nw\n  %fprintf('%d / %d \\n',i,nw);\n  xa=windows(i,1);ya=windows(i,2);\n  xb=windows(i,3);yb=windows(i,4);\n  xaa=max(1,xa-1);yaa=max(1,ya-1);\n  \n  wi=xb-xa+1;\n  hi=yb-ya+1;\n  winareas(i,1)=wi*hi;\n  if wi<(2*nsubbox) | hi<(2*nsubbox)\n    continue;\n  end\n  \n  xs=[-0.5:1/(2*nsubbox):0.5]*wi;\n  ys=[-0.5:1/(2*nsubbox):0.5]*hi;\n  xsr=ceil(xs+wincx(i));\n  ysr=ceil(ys+wincy(i))';\n  \n  Xstart=max(1,onesv*xsr-1);\n  Ystart=max(1,ysr*onesh-1);\n  \n \n  for j=subboxind\n    for k=subboxind\n      for l=binids\n\twinhists(j,l,k)=oribinintim(Ystart(j+1,k+1),Xstart(j+1,k+1),l)+oribinintim(Ystart(j,k),Xstart(j,k),l)-oribinintim(Ystart(j+1,k),Xstart(j+1,k),l)-oribinintim(Ystart(j,k+1),Xstart(j,k+1),l);\n      end    \n      winhistsum(j,k)=sum(winhists(j,:,k));\n    end\n  end\n  \n  for j=1:(2*nsubbox)\n    for k=1:(2*nsubbox)\n      winscores(i,1)=winscores(i,1)+BoxWeights(j,k)*winhists(j,BoxIndices(j,k),k);\n    end\n  end\n  \n\nend\nend\nwinscoremax=max(winscores);\nwinscores=(winscores./winscoremax);\n%winscoremaxtmp=max(winscorestmp);\n%winscorestmp=(winscorestmp./winscoremaxtmp);\n\n%keyboard\n%%%%%%%%%%%%%%%%%%%%%%%%\n% Additional functions %\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [g,N,gx,gy]=gaussianderiv1D_(sigma,N)\n\nif nargin<2\n  N=4*sigma+1;\nend\n\n% make sure that N is odd\nN=2*floor(N/2)+1;\nsigma2=sigma^2;\n\nt=1:N;\nmu=(N-1)/2+1;\ng=1/(sqrt(2*pi)*sigma)*exp(-0.5*(t-mu).^2/sigma2);\ngx=-(t-mu)/sigma2.*g;\ngy=gx';\n\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/rahtu/rahtuObjectness/mvg_windowbec_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5730265887245392}}
{"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%==============================================================================\n%\n% function B = getElasticMatrixStg(omega,m,mu,lambda)\n%\n% Builds the elasticity matrix B for a domain defined by omega\n% and a staggered grid discretization defined by m:\n%\n%     | a\\nabla       0        0 | \n% B = |       0 a\\nabla        0 |\n%     |       0       0  a\\nabla |\n%     |           b \\div         |,\n%\n% where \\nabla and \\div are weighted by a=\\sqrt(mu) and b=\\sqrt(\\lambda+\\mu),\n% respectively; defaults: \\mu = 1, \\lambda = 0.\n% Note: the matrices are simple, it is size that matters.\n%\n% =============================================================================\n\nfunction B = getElasticMatrixStg(omega,m,mu,lambda)\nif nargin == 0,\n  help(mfilename);\n  runMinimalExample;\n  B = 'endOfMinimalExample';\n  return;\nend;\n\n                                        % set defautls\nif ~exist('mu','var'),     mu     = [];  end;\nif ~exist('lambda','var'), lambda = [];  end;\nif isempty(mu),     \n  warning('mu has not yet been set! set mu=1');  \n  mu = 1;  \nend;\nif isempty(lambda), \n  warning('lambda has not yet been set! lambda=0');  \n  lambda = 0;  \nend;\n\ndim = length(omega)/2; \nh   = (omega(2:2:end)-omega(1:2:end))./m; % voxel size for integration\na   = sqrt(mu); \nb   = sqrt(mu+lambda);\n\n% for the dimension ms(i) of the i-th staggered grid, the i-th component \n% of of m=[m(1),m(2),m(3)] has to be increased by one; the i-th staggered \n% grid contains ns(i) points\n\nms  = @(i)   m + ((1:dim)==i); \nns  = @(i)   prod(ms(i));\n% Example: m=(2,3), ms(1) = (3,3); ms(2)=(2,4), ns(1) = 9, ns(2) = 8.\n\n% the dimension of \\partial^{h,i}_k is p(i,k)-by-ns(i),\n% where q(i)=prod(ms(i)) is the length of the i-th staggered grid \n% and p(i,k) is the product of a modified m: \n%   m(i) has to be increase by one and\n%   m(k) has to be decrase  by one\np = @(i,k) prod(m + ((1:dim)==i) - ((1:dim==k)));\n\n% Example:\n% p(1,1) = 2*3         = 6,   p(1,2) = (2+1)*(3-1) = 6, ns(1) = 9\n% p(2,1) = (2-1)*(3+1) = 4,   p(2,2) = 2*3         = 6, ns(2) = 8\n\n% E is a q-by-q identity matrix, where q=m(k)+1 for i==k and q=m(k) (i~=k)\nE = @(i,k) speye(m(k)+(i==k));\n\n% Example: \n% E(1,1) = speye(m(1)+1) = speye(3)\n% E(1,2) = speye(m(2))   = speye(3)\n% E(2,1) = speye(m(1))   = speye(2)\n% E(2,2) = speye(m(2)+1) = speye(4)\n\n% D is the 1D derivative matrix of size p-by-(p+1)\n%        |-1 1     |      \n% D = |  .  .   |/h(k), where p=m(k) (i==k) and p=m(k)-1 (i~=k)\n%        |     -1 1|      \n\nD = @(i,k) spdiags(ones(m(k)-(i~=k),1)*[-1,1],...\n  [0,1],m(k)-(i~=k),m(k)+(i==k))/h(k);\n\n% Example: \n% D(1,1) is m(1)-by-(m(1)+1) = 2-by-3\n% D(1,2) is (m(2)-1)-by-m(2) = 2-by-3\n% D(2,1) is (m(1)-1)-by-m(1) = 1-by-2\n% D(2,2) is m(2)-by-(m(2)+1) = 3-by-4\n\n\nswitch dim\n  case 2\n    % build the 2D elasticity operator\n    %\n    %      | a\\nabla 0      |   |a D11  0     |\n    %  B = |                | = |a D12  0     |\n    %      | 0      a\\nabla |   |0      a D21 |\n    %      |                |   |0      a D22 |\n    %      | b Div1 b Div2  |   |b D11  b D22 |\n\n    D11 = kron(E(1,2),D(1,1));  D12 = kron(D(1,2),E(1,1));\n    D21 = kron(E(2,2),D(2,1));  D22 = kron(D(2,2),E(2,1));\n    \n    % Example:\n    % D11 = 3-by-3 \\otimes 2-by-3 = 6-by-9\n    % D12 = 2-by-3 \\otimes 3-by-3 = 6-by-9\n    % D21 = 4-by-4 \\otimes 1-by-2 = 4-by-8\n    % D22 = 3-by-4 \\otimes 2-by-2 = 6-by-8\n    \n    B = [  a*D11,sparse(p(1,1),ns(2));\n           a*D12,sparse(p(1,2),ns(2));\n           sparse(p(2,1),ns(1)),a*D21;\n           sparse(p(2,2),ns(1)),a*D22;\n           b*D11,b*D22];\n    % Example: B = 28-by-17\n  case 3\n    % build the 3D elasticity operator\n    %\n    %      |a D11  0      0    |\n    %  B = |a D12  0      0    |\n    %      |a D13  0      0    |\n    %      |0      a D21  0    |\n    %      |0      a D22  0    |\n    %      |0      a D23  0    |\n    %      |0      0      a D31|\n    %      |0      0      a D32|\n    %      |0      0      a D33|\n    %      |b D11  b D22  b D33|\n\n    % Example: m=[2,3,4] ns = (36,32,30)\n    D11 = kron(kron(E(1,3),E(1,2)),D(1,1));\n    D12 = kron(kron(E(1,3),D(1,2)),E(1,1));\n    D13 = kron(kron(D(1,3),E(1,2)),E(1,1));\n    D21 = kron(kron(E(2,3),E(2,2)),D(2,1));\n    D22 = kron(kron(E(2,3),D(2,2)),E(2,1));\n    D23 = kron(kron(D(2,3),E(2,2)),E(2,1));\n    D31 = kron(kron(E(3,3),E(3,2)),D(3,1));\n    D32 = kron(kron(E(3,3),D(3,2)),E(3,1));\n    D33 = kron(kron(D(3,3),E(3,2)),E(3,1));   \n\n    % Example:\n    % D11 = kron(kron(4-by-4,3-by-3),2-by-3) = 24-by-36\n    % D12 = kron(kron(4-by-4,2-by-3),3-by-3) = 24-by-36\n    % D13 = kron(kron(3-by-4,3-by-3),3-by-3) = 27-by-36\n    % D21 = kron(kron(4-by-4,4-by-4),1-by-2) = 16-by-32\n    % D22 = kron(kron(4-by-4,3-by-4),2-by-2) = 24-by-32\n    % D23 = kron(kron(3-by-4,4-by-4),2-by-2) = 24-by-32\n    % D31 = kron(kron(5-by-5,3-by-3),1-by-2) = 15-by-30\n    % D32 = kron(kron(5-by-5,2-by-3),2-by-2) = 20-by-30\n    % D32 = kron(kron(4-by-5,3-by-3),2-by-2) = 24-by-30\n        \n    B = [\n      a * D11, sparse(p(1,1),ns(2)), sparse(p(1,1),ns(3)); ...\n      a * D12, sparse(p(1,2),ns(2)), sparse(p(1,2),ns(3)); ...\n      a * D13, sparse(p(1,3),ns(2)), sparse(p(1,3),ns(3)); ...\n      sparse(p(2,1),ns(1)), a * D21, sparse(p(2,1),ns(3)); ...\n      sparse(p(2,2),ns(1)), a * D22, sparse(p(2,2),ns(3)); ...\n      sparse(p(2,3),ns(1)), a * D23, sparse(p(2,3),ns(3)); ...\n      sparse(p(3,1),ns(1)), sparse(p(3,1),ns(2)), a * D31; ...\n      sparse(p(3,2),ns(1)), sparse(p(3,2),ns(2)), a * D32; ...\n      sparse(p(3,3),ns(1)), sparse(p(3,3),ns(2)), a * D33; ...\n      b * D11,              b * D22,              b * D33      \n      ];\n    % Example:\n    % B = [75-by-36    0      0\n    %         0     64-by-32  0\n    %         0        0     59-by-30\n    %      24-by-36 24-by-32 24-by-30 ] \n    %   = 228-by-98\n    \n  otherwise,  error('nyi');\nend;\n%------------------------------------------------------------------------------\nfunction runMinimalExample\n\nomega = [0,1,0,2,0,3]; m = [4,5,6];\nB2 = getElasticMatrixStg(omega(1:4),m(1:2),1,0);\nB3 = getElasticMatrixStg(omega,m,1,0);\nfigure(1); clf;\nsubplot(1,2,1); spy(B2); title(sprintf('%s: B2',mfilename));\nsubplot(1,2,2); spy(B3); title(sprintf('%s: B3',mfilename));\n%==============================================================================\n\n\n\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/regularizers/getElasticMatrixStg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5730149339745542}}
{"text": "function [rho,rhou,rhov,Ener] = ChannelIC2D(x, y, time);\n  \n%  function [Q] = ChannelIC2D(x, y, time)\n%  Purpose: Impose uniform plane flow \n\nmu = 1e-2; pbar = 10; gamma = 1.5;\n\nrho  = 1;\nrhou = y.^2;\nrhov = 0;\nEner = (2*mu*x + pbar)/(gamma-1) + .5*(y.^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/ChannelIC2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5730149263388179}}
{"text": "%isiscalar - Test if parameter is a scalar (integer) satisfying an optional list of tests.\n%\n%  USAGE\n%\n%    test = isiscalar(x,test1,test2,...)\n%\n%    x              parameter to test\n%    test1...       optional list of additional tests\n%\n%  EXAMPLES\n%\n%    % Test if x is a scalar (double)\n%    isiscalar(x)\n%\n%    % Test if x is a strictly positive scalar (double)\n%    isiscalar(x,'>0')\n%\n%    % Test if x is a scalar (double) included in [2,3]\n%    isiscalar(x,'>=2','<=3')\n%\n%  NOTE\n%\n%    The tests ignore NaN, e.g. isiscalar(nan), isiscalar(nan,'>0') and isiscalar(nan,'<=0')\n%    all return 1.\n%\n%  SEE ALSO\n%\n%    See also isdmatrix, isdvector, isdscalar, isimatrix, isivector, isstring,\n%    islscalar, islvector, islmatrix.\n%\n\n\n% Copyright (C) 2010 by Micha\u00ebl Zugaro\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\nfunction test = isiscalar(x,varargin)\n\n% Check number of parameters\nif nargin < 1,\n  error('Incorrect number of parameters (type ''help <a href=\"matlab:help isiscalar\">isiscalar</a>'' for details).');\nend\n\n% Test: double, scalar\ntest = isa(x,'double') & isscalar(x);\nif ~test, return; end\n\n% Test: integers?\ntest = test & round(x)==x;\n\n% Optional tests\nfor i = 1:length(varargin),\n\ttry\n\t\tif ~eval(['x' varargin{i} ';']), test = false; return; end\n\tcatch err\n\t\terror(['Incorrect test ''' varargin{i} ''' (type ''help <a href=\"matlab:help isiscalar\">isiscalar</a>'' for details).']);\n\tend\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/isiscalar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.5729929464519138}}
{"text": "function tec_io_test02 ( )\n\n%*****************************************************************************80\n%\n%% TEC_IO_TEST02 tests TEC_WRITE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 February 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n  tec_file_name = 'tiny.dat';\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEC_IO_TEST02\\n' );\n  fprintf ( 1, '  TEC_WRITE can write finite element data to a TECPLOT ASCII file.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  In this example, we will write data to \"%s\".\\n', tec_file_name );\n\n  dim_num = 2;\n  node_num = 5;\n  element_num = 3;\n  element_order = 3;\n  node_data_num = 2;\n  node_coord = [ ...\n    0.0, 0.0; ...\n    1.0, 0.0; ...\n    2.0, 0.0; ...\n    0.0, 1.0; ...\n    1.0, 1.0 ]';\n  element_node = [ ...\n    1, 2, 4;\n    5, 4, 2;\n    2, 3, 5 ]';\n  node_data = [ ...\n    1.0, 0.0; ...\n    0.8, 0.2; ...\n    0.6, 0.4; ...\n    0.9, 0.1; ...\n    0.5, 0.5 ]';\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Spatial dimension         = %d\\n', dim_num );\n  fprintf ( 1, '  Number of nodes           = %d\\n', node_num );\n  fprintf ( 1, '  Number of elements        = %d\\n', element_num );\n  fprintf ( 1, '  Element order             = %d\\n', element_order );\n  fprintf ( 1, '  Number of node data items = %d\\n', node_data_num );\n\n  r8mat_transpose_print ( dim_num, node_num, node_coord, ...\n    '  Coordinates of nodes:' );\n\n  i4mat_transpose_print ( element_order, element_num, element_node, ...\n    '  Nodes of elements:' );\n\n  r8mat_transpose_print ( node_data_num, node_num, node_data, ...\n    '  Node data for nodes:' );\n\n  tec_write ( tec_file_name, dim_num, node_num, element_num, ...\n    element_order, node_data_num, node_coord, element_node, node_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/tec_io/tec_io_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.5729929336721226}}
{"text": "function varargout = tucker(f)\n%TUCKER   SLICE-TUCKER expansion of a CHEBFUN3 object.\n%   [CORE, COLS, ROWS, TUBES] = TUCKER(F) returns the core tensor CORE and \n%   the three factor quasimatrices COLS, ROWS, and TUBES in the low-rank \n%   representation of a CHEBFUN3 object F. The factor quasimatrices are of \n%   size Inf-by-length(F, 1), Inf-by-length(F, 2) and Inf-by-length(F, 3), \n%   respectively and we have\n%\n%   F(x,y,z) = CORE x_1 COLS(x,:,:) x_2 ROWS(:,y,:) x_3 TUBES(:,:,z).\n%\n%   CORE = TUCKER(F) returns the core tensor used in the construction of F.\n%\n% See also CHEBFUN2/CDR.\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(f) )\n    varargout = cell(1, nargout); \n    return\nend\n\n% Get the low rank representation for f. \nfCore = f.core;\nfCols = f.cols; \nfRows = f.rows;\nfTubes = f.tubes;\n\n% Output:\nif ( nargout <= 1 )\n    varargout = {fCore};\nelse\n    % ST decomposition\n    varargout = {fCore, fCols, fRows, fTubes};\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/@chebfun3/tucker.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.5729929208923311}}
{"text": "% Test file for ADCHEBFUN CUMSUM, DIFF, MEAN and SUM\n\nfunction pass = test_cumsumDiffSumMean\n\n% List of trigonometric functions to test.\nfuncList = {@diff, @(u)diff(u, 2), @(u)diff(u, 4), ...\n                 @sum, @(u) sum(u, -.25, .8), ...\n                 @cumsum, @(u)cumsum(u,2), ...\n                 @mean, ...\n                 @(u) deriv(u, 0:0.01:0.1, 2)};\n\n% Tolerance for Taylor testing\ntolOrder = 1e-2;\ntolDiff = 1e-12;\n% Initialise vector with pass information\npass = zeros(2, numel(funcList));\n\n% Do the tests.\nfor k = 1:numel(funcList)\n    % Call the valueTesting method, which also returns linearity information\n    [err, lin] = adchebfun.valueTesting(funcList{k});\n    \n    % First, check that the computed function values match what we expect\n    pass(1, k) = ( err == 0 );\n    \n    % Call the taylorTesting method\n    [order1, order2, nDiff2] = adchebfun.taylorTesting(funcList{k});\n    \n    % We expect all elements of ORDER1 to be close to 1. Since the methods being\n    % tested in this case are all linear, ORDER2 will be noise. However, since\n    % the methods are indeed linear, we should expect nDiff2 to have values all\n    % close to machine epsilon, which we can use to check for the correctness of\n    % the derivative computed.\n    pass(2,k) = ( (max(abs(order1 - 1)) < tolOrder) && ...\n        (max(abs(nDiff2)) < tolDiff) );\n    \n    % Check that we received the correct linearity information\n    pass(3, k) = ( lin == 1 );\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/adchebfun/test_cumsumDiffSumMean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5729351207617533}}
{"text": "function [s] = gsp_jtv_filter_inverse(G, filter, filtertype,c, param)\n%GSP_JTV_FILTER_INVERSE Inverse operator of a joint timve_vertex filterbank\n%   Usage:  s = gsp_jtv_filter_inverse(G, filter, c);\n%           s = gsp_jtv_filter_inverse(G, filter, c, param);\n%\n%   Input parameters:\n%         G          : Time-vertex Graph structure.\n%         filter     : Cell array of time-vertex filters.\n%         filtertype : Filter domain (ts,js,ts-array,js-array)\n%         c          : Transform coefficients\n%         param      : Optional parameter\n%   Output parameters:\n%         signal     : sythesis signal\n%\n\n% Author: Francesco Grassi\n% Testing: test_jtv_filter\n% Date: September 2016\n\nif nargin<5\n    param = struct;\nend\n\n[dual_filter,filtertype] = gsp_jtv_design_can_dual(filter,filtertype);\n\ns = gsp_jtv_filter_synthesis(G,dual_filter,filtertype,c,param);\n\n\nend\n\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/filters/gsp_jtv_filter_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5729351157933141}}
{"text": "function c=projkern(c,p2,p3,p4,p5);\n%PROJKERN  Projection onto generating kernel space\n%   Usage:  cout=projkern(cin,a);\n%           cout=projkern(cin,g,a);\n%           cout=projkern(cin,ga,gs,a);\n%\n%   Input parameters:\n%         cin   : Input coefficients\n%         g     : analysis/synthesis window\n%         ga    : analysis window\n%         gs    : synthesis window\n%         a     : Length of time shift.\n%   Output parameters:\n%         cout  : Output coefficients\n%\n%   `cout=projkern(cin,a)` projects a set of Gabor coefficients *c* onto the\n%   space of possible Gabor coefficients. This means that *cin* and *cout*\n%   synthesize to the same signal. A tight window generated from a Gaussian\n%   will be used for both analysis and synthesis.\n%\n%   The rationale for this function is a follows: Because the coefficient\n%   space of a Gabor frame is larger than the signal space (since the frame\n%   is redundant) then there are many coefficients that correspond to the\n%   same signal.\n%\n%   Therefore, you might desire to work with the coefficients *cin*, but you\n%   are in reality working with *cout*.\n%\n%   `cout=projkern(cin,g,a)` does the same, using the window *g* for analysis\n%   and synthesis.\n%\n%   `cout=projkern(cin,ga,gs,a)` does the same, but for different analysis\n%   *ga* and synthesis *gs* windows.\n%\n%   See also: dgt, idgt\n\ncomplainif_argnonotinrange(nargin,2,4,mfilename);\n\nM=size(c,1);\nN=size(c,2);\n\nif nargin==2\n  a=p2;\n  L=a*N;\n  ga=gabtight(a,M,L);\n  gs=ga;\nend;\n\nif nargin==3;\n  ga=p2;\n  gs=p2;\n  a=p3;\n  L=a*N;\nend;\n\nif nargin==4;  \n  ga=p2;\n  gs=p3;\n  a=p4;\n  L=a*N;\nend;\n\nassert_squarelat(a,M,1,'PROJKERN');\n\nc=dgt(idgt(c,gs,a),ga,a,M);\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/gabor/projkern.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.572935115793314}}
{"text": "function cc=lpczz2cc(zz,np)\n%LPCZZ2CC Convert poles to \"complex\" cepstrum CC=(ZZ,NP)\n\n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: lpczz2cc.m 713 2011-10-16 14:45:43Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[nf,p]=size(zz);\nif (nargin < 2) np=p; end\ncc=zeros(nf,np);\nyy=zz.';\nif p<2\t\t\t% special case 'cos sum() is weird\n  cc(:,1)=real(zz);\n  for k=2:np\n    yy=yy.*zz.';\n    cc(:,k)=real(yy).'/k;\n  end\nelse\n  cc(:,1)=sum(real(yy)).';\n  for k=2:np\n    yy=yy.*zz.';\n    cc(:,k)=sum(real(yy)).'/k;\n  end\nend\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/lpczz2cc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5729351026844602}}
{"text": "figure;\n\n%% Cartesian\n% subplot(1,2,1);\n% hold on;\n% truth_100 = truth.*100;\n% %h1 = plot(ax(1),measurement(1,k),measurement(2,k),'k*','MarkerSize', 10);\n% meas = 100*obs.heval_inv([measurement(1,:);measurement(2,:)]);\n% h1 = plot(meas(obs.Mapping(1),:),meas(obs.Mapping(2),:),'r+','MarkerSize', 15);\n% h2 = plot(truth_100(1,1:end),truth_100(2,1:end),'k--','LineWidth',2);\n% h3 = plot(truth_100(1,1),truth_100(2,1),'ko','MarkerSize', 20, 'MarkerFaceColor','Green');\n% h4 = plot(truth_100(1,end),truth_100(2,end),'ko','MarkerSize', 20, 'MarkerFaceColor','Red');\n% h5 = plot(0,0,'rd','MarkerSize', 20, 'MarkerFaceColor','Blue');\n% legend([h1,h2,h3,h4,h5],'Measurements','Trajectory', 'Start', 'End','Radar','Location','southeast')\n% str = sprintf('Vessel trajectory');\n% title(str)\n% xlabel('X (m)')\n% ylabel('Y (m)')\n% axis([0,2500,0,1500])\n% box on\n\n%% Polar\n% subplot(1,2,2);\n% truth2meas = obs.heval(truth_100(1:2,:));\n% % [a,b]=obs.heval(truth_100(1:2,:));\n% %h1 = polarplot(a(x_start),b(y_start),'ko','LineWidth',2,'MarkerSize',15,'MarkerFaceColor','w');hold on;\n% polarplot(truth2meas(1,:),truth2meas(2,:),'k-','LineWidth',2,'MarkerSize',10,'MarkerFaceColor','w');hold on;\n% thetalim([0 90])\n% %h2 = polarplot(a(x_end),b(y_end),'k^','LineWidth',2,'MarkerSize',15,'MarkerFaceColor','w');hold on;\n% h3 = polarplot(measurement(1,:),100*measurement(2,:),'+r','MarkerSize',15);\n% pax = gca;\n% pax.ThetaAxisUnits = 'radians';\n% %rlabel('Range (m)');\n% %thetalabel('Bearing (rad)');", "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/plot_trajectories_multi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5729115765457381}}
{"text": "function G = curl(F)\n%CURL Curl of a BALLFUNV.\n%   G = CURL(F) returns the BALLFUNV of the curl of F.\n%\n% See also DIV. \n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif isempty( F )\n    G = ballfunv();\n    return\nend\n\n% Extract the components of a BALLFUNV:\nFc = F.comp;\n\n% Formula for 3D curl\nG = [ diff(Fc{3},2) - diff(Fc{2},3); ...\n      diff(Fc{1},3) - diff(Fc{3},1); ...\n      diff(Fc{2},1) - diff(Fc{1},2) ];\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@ballfunv/curl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5729115663974206}}
{"text": "function merged_sample = merge_samples(sample1, sample2, w1, w2, sample_merge_type)\n% Merge sample1 and sample2 using weights w1 and w2. The type of merging is\n% decided by sample_merge_type. \n% The sample_merge_type can be\n% 1) Merge: The output is the weighted sum of the input samples\n% 2) Replace: The output is the first sample. ie w2 is assumed to be 0\n\n\n% Normalise the weights so that they sum to one\nalpha1 = w1/(w1+w2);\nalpha2 = 1 - alpha1;\n\n% Build the merged sample\nif strcmpi(sample_merge_type, 'replace')\n    merged_sample = sample1;\nelseif strcmpi(sample_merge_type, 'merge')\n    num_feature_blocks = numel(sample1);\n    \n    merged_sample = cell(1, 1, num_feature_blocks);\n    for k = 1:num_feature_blocks\n        merged_sample{k} = alpha1*sample1{k} + alpha2*sample2{k};\n    end\nelse\n    error('Invalid sample merge type');\nend\n", "meta": {"author": "martin-danelljan", "repo": "ECO", "sha": "27e8ae565cd63ec14bafcaad8b5b993bec8f3e69", "save_path": "github-repos/MATLAB/martin-danelljan-ECO", "path": "github-repos/MATLAB/martin-danelljan-ECO/ECO-27e8ae565cd63ec14bafcaad8b5b993bec8f3e69/implementation/sample_space_model/merge_samples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5729115606312614}}
{"text": "function Sp = querytp(S, U, domain, p)\n%QUERYTP Query TP model at a given parameter point\n%\tSp = QUERYTP(S, U, domain, p)\n%\t\n%\tS        - core tensor of the TP model\n%\tU        - (discrete) weight function data of the TP model\n%\tdomain   - intervals for each dimension\n%\tp        - parameter point where we query the model\n%\n%\tSp       - system at p (linear interpollated weights)\n\n% TODO: method param to interp1 (spline,..)\n\nW = queryw1(U, domain, p);\nSp = squeeze(tprod(S, 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/25514-tp-tool/tptool/util/querytp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5728342734782237}}
{"text": "function [X,Y,U] = CollectData(SimPar,IC1,IC2,f1,f2,umin,umax,Ntraj,SimLength)\n% Collect data for Burgers equation\ndisp('Starting data collection ...')\n\n\n% random input\nUbig= rand(2,SimLength,Ntraj)* (umax-umin)+umin;\n\n% Transition mapping of the controleld dynamical system\n% control is a linear combination of u1 and u2\nf = @(x,u)(BurgerSolver(x,u(1)*f1+u(2)*f2,SimPar));\n\n\n% initialize \nX = []; Y = []; U=[];\n\n% loop pver trajectories\nfor i = 1:Ntraj\n    xx = [];\n    % Intial state is a random convex combination of IniitialConditions\n    b = rand;\n    a = [b,1-b];\n    xx =b*IC1 + (1-b)*IC2;\n    tic\n    fprintf('Trajectory %d out of %d \\n',i,Ntraj)\n    % loop over each time step\n    for j = 1:SimLength \n        xx = [xx f(xx(:,end),Ubig(:,j,i))];\n        U  = [U,Ubig(:,j,i)];\n        % if the solution diverges, go to the next trajectory\n        if ~isempty(find(isnan(xx(:,end)),1))\n            break\n        end\n        \n    end\n    toc\n    % Store\n    X = [X xx(:,1:end-1)];\n    Y = [Y xx(:,2:end)];\n\nend\n\n\nsave('BurgersTrajectoryData','X','Y','U','SimLength','Ntraj')\nend", "meta": {"author": "arbabiha", "repo": "KoopmanMPC_for_flowcontrol", "sha": "4581c284bed5420fee7a7e9a58590fe93a196c97", "save_path": "github-repos/MATLAB/arbabiha-KoopmanMPC_for_flowcontrol", "path": "github-repos/MATLAB/arbabiha-KoopmanMPC_for_flowcontrol/KoopmanMPC_for_flowcontrol-4581c284bed5420fee7a7e9a58590fe93a196c97/thehood/CollectData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720204, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5728342627794001}}
{"text": "function [ sindex ] = tournament(pop, index1, index2)\n%   Apply tournament selection to row indexed by index1 and index2\n%   Vectorization on this function may not give better speed, so beter\n%   to keep as it is.\n\nglobal nreal ;\nglobal nobj ;\nglobal ncon ;\n\nobj_col = nreal+1:nreal+nobj;\ncv_col = nreal+nobj+ncon+1;\n\n% check the dominance\nflag = check_dominance([pop(index1,obj_col), pop(index1,cv_col)], ...\n                       [pop(index2,obj_col), pop(index2,cv_col)]);\n\ncdist1 = pop(index1, end);\ncdist2 = pop(index2, end);\nif (flag == 1)\n    sindex = index1 ;\n    return ;\nend\nif(flag == -1)\n    sindex = index2 ;\n    return ;\nend\nif(cdist1 > cdist2)\n    sindex = index1 ;\n    return ;\nend\nif(cdist2 > cdist1)\n    sindex = index2 ;\n    return ;\nend\nif(rand(1) < 0.5)\n% if(randomperc() < 0.5) % SLOW !!!\n    sindex = index1 ;\n    return ;\nelse\n    sindex = index2 ;\n    return ;\nend\n\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/tournament.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5728342598680453}}
{"text": "function f = feature_extract( imdist ,scale)\n    f=[];\n    imdist=rgb2gray(imdist);\n    weight=[0.2 0.8];\n    for i=1:scale\n        im=imdist;\n        fun0=@(x)secal(x);\n        emat=blkproc(im,[8 8] ,fun0); \n\n        sort_t = sort(emat(:),'ascend');\n        len = length(sort_t);\n        t=sort_t(ceil(len*weight(1)):ceil(len*weight(2)));\n        mu= mean(t);\n        ske=skewness(sort_t);\n        \n        f1=[ mu  ske];\n\n        im=imdist;\n        fun1=@(x)fecal(x);\n        im=double(im);\n        femat=blkproc(im,[8 8],fun1);\n\n        sort_t = sort(femat(:),'ascend');\n        len = length(sort_t);\n        t=sort_t(ceil(len*weight(1)):ceil(len*weight(2)));\n        mu= mean(t);\n        ske=skewness(sort_t);\n   \n        f2=[ mu  ske];\n\n        f=[f f1 f2] ;\n        \n        imdist = imresize(imdist,0.5);\n    end\nend\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/qualityMeasures/SSEQ/feature_extract.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5727948794834357}}
{"text": "classdef FollowWall < simiam.controller.Controller\n\n% Copyright (C) 2013, Georgia Tech Research Corporation\n% see the LICENSE file included with this software\n\n    properties\n        \n        % memory banks\n        E_k\n        e_k_1\n        \n        % gains\n        Kp\n        Ki\n        Kd\n        \n        % plot support\n        p\n        \n        % sensor geometry\n        calibrated\n        sensor_placement\n        \n    end\n    \n    properties (Constant)\n        inputs = struct('v', 0, 'direction', 'right');\n        outputs = struct('v', 0, 'w', 0)\n    end\n    \n    methods\n        \n        function obj = FollowWall()\n            obj = obj@simiam.controller.Controller('follow_wall');            \n            obj.calibrated = false;\n            \n            obj.Kp = 2;\n            obj.Ki = 0;\n            obj.Kd = 0;\n            \n            obj.E_k = 0;\n            obj.e_k_1 = 0;\n            \n            \n%             obj.p = simiam.util.Plotter();\n        end\n        \n        function outputs = execute(obj, robot, state_estimate, inputs, dt)\n            \n            % Compute the placement of the sensors\n            if(~obj.calibrated)\n                obj.set_sensor_geometry(robot);\n            end\n            \n            % Unpack state estimate\n            [x, y, theta] = state_estimate.unpack();\n            \n            % Poll the current IR sensor values 1-5\n            ir_distances = robot.get_ir_distances();\n                        \n            % Interpret the IR sensor measurements geometrically\n            ir_distances_wf = obj.apply_sensor_geometry(ir_distances, state_estimate);            \n            \n            % Compute the heading vector\n            d_fw = inputs.d_fw;\n\n            % 1. Select p_2 and p_1, then compute u_fw_t\n            if(strcmp(inputs.direction,'right'))\n                % Pick two of the right sensors based on ir_distances\n                S = [1:3 ; ir_distances(5:-1:3)'];\n                [Y,i] = sort(S(2,:));\n                S = S(1,i);\n                \n                Sp = 5:-1:3;\n                \n                S1 = Sp(S(1));\n                S2 = Sp(S(2));\n                \n                if(S1 < S2)\n                    p_1 = ir_distances_wf(:,S2);\n                    p_2 = ir_distances_wf(:,S1);\n                else\n                    p_1 = ir_distances_wf(:,S1);\n                    p_2 = ir_distances_wf(:,S2);\n                end\n                \n            else\n                % Pick two of the left sensors based on ir_distances\n                S = [1:3 ; ir_distances(1:3)'];\n                [Y,i] = sort(S(2,:));\n                S = S(1,i);\n                \n                if(S(1) > S(2))\n                    p_1 = ir_distances_wf(:,S(2));\n                    p_2 = ir_distances_wf(:,S(1));\n                else\n                    p_1 = ir_distances_wf(:,S(1));\n                    p_2 = ir_distances_wf(:,S(2));\n                end\n            end\n            \n            u_fw_t = p_2-p_1;\n\n            % 2. Compute u_a, u_p, and u_fw_tp to compute u_fw_p\n            \n            u_fw_tp = u_fw_t/norm(u_fw_t);\n            u_a = p_1;\n            u_p = [x;y];\n            \n            u_fw_p = ((u_a-u_p)-((u_a-u_p)'*u_fw_tp)*u_fw_tp);\n            \n            % 3. Combine u_fw_tp and u_fw_pp into u_fw;\n            u_fw_pp = u_fw_p/norm(u_fw_p);\n            u_fw = d_fw*u_fw_tp+(u_fw_p-d_fw*u_fw_pp);\n            \n            \n            % Compute the heading and error for the PID controller\n            theta_fw = atan2(u_fw(2),u_fw(1));\n            e_k = theta_fw-theta;\n            e_k = atan2(sin(e_k),cos(e_k));\n                                    \n            e_P = e_k;\n            e_I = obj.E_k + e_k*dt;\n            e_D = (e_k-obj.e_k_1)/dt;\n              \n            % PID control on w\n            v = inputs.v;\n            w = obj.Kp*e_P + obj.Ki*e_I + obj.Kd*e_D;\n            \n            % Save errors for next time step\n            obj.E_k = e_I;\n            obj.e_k_1 = e_k;\n                        \n            % plot\n%             obj.p.plot_2d_ref(dt, atan2(sin(theta),cos(theta)), theta_fw, 'c');\n            \n%             fprintf('(v,w) = (%0.4g,%0.4g)\\n', v,w);            \n\n            outputs.v = v;\n            outputs.w = w;\n        end\n        \n        % Helper functions\n        \n        function ir_distances_wf = apply_sensor_geometry(obj, ir_distances, state_estimate)\n                    \n            % Apply the transformation to robot frame.\n            \n            ir_distances_rf = zeros(3,5);\n            for i=1:5\n                x_s = obj.sensor_placement(1,i);\n                y_s = obj.sensor_placement(2,i);\n                theta_s = obj.sensor_placement(3,i);\n                \n                R = obj.get_transformation_matrix(x_s,y_s,theta_s);\n                ir_distances_rf(:,i) = R*[ir_distances(i); 0; 1];\n            end\n            \n            % Apply the transformation to world frame.\n            \n            [x,y,theta] = state_estimate.unpack();\n            \n            R = obj.get_transformation_matrix(x,y,theta);\n            ir_distances_wf = R*ir_distances_rf;\n            \n            ir_distances_wf = ir_distances_wf(1:2,:);\n        end\n        \n        function set_sensor_geometry(obj, robot)\n            obj.sensor_placement = zeros(3,5);\n            for i=1:5\n                [x, y, theta] = robot.ir_array(i).location.unpack();\n                obj.sensor_placement(:,i) = [x; y; theta];\n            end                        \n            obj.calibrated = true;\n        end\n        \n        function R = get_transformation_matrix(obj, x, y, theta)\n            R = [cos(theta) -sin(theta) x; sin(theta) cos(theta) y; 0 0 1];\n        end\n        \n        function reset(obj)\n            % Reset accumulated and previous error\n            obj.E_k = 0;\n            obj.e_k_1 = 0;\n        end\n        \n    end\n    \nend\n\n", "meta": {"author": "jdelacroix", "repo": "simiam", "sha": "cd67b5b97d6781d32333c0a33a51cfd5116640a9", "save_path": "github-repos/MATLAB/jdelacroix-simiam", "path": "github-repos/MATLAB/jdelacroix-simiam/simiam-cd67b5b97d6781d32333c0a33a51cfd5116640a9/+simiam/+controller/FollowWall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5727948755068939}}
{"text": "\nclear all; close all;\nI=imread('tire.tif');\nJ=histeq(I);\nfigure;\nsubplot(121);\nimshow(uint8(I));\nsubplot(122);\nimshow(uint8(J));\nfigure;\nsubplot(121);\nimhist(I, 64);\nsubplot(122);\nimhist(J, 64);\n", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/\u300aMATLAB\u56fe\u50cf\u5904\u7406\u300b\u6e90\u6587\u4ef6/\u672c\u4e66\u6e90\u6587\u4ef6/chap5/chap5_12.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.572794874967908}}
{"text": "function x = rot2quat (R, tol)\n% Use:  q = rot2quat(R)\n%\n% Computes the unit quaternion corresponding to the 3x3 rotation matrix R\n% tol controls the tolerance to check is R == identity(3)\n% Note: quaternion is q = [qw qx qy qz], where qw is the scalar part of q\n%\n% From Luca Carlone's\n% https://bitbucket.org/lucacarlone/pgo3d-duality-opencode/annotate/ebb6e1b8cebaad7f2aaf581b1d0c0bad737faebb/lib/rot2quat.m?at=master&fileviewer=file-view-default\n \nif nargin < 2\n  tol =  1.0e-5;\nend\n\nif isrot(R, tol) == 0\n  s(4) = .5 * sqrt( 1 + R(1,1) + R(2,2) + R(3,3) );\n  if norm(s(4)) <= tol\n    %disp ('rotation = 180 degrees')\n    [u,teta]=rot2uth(R);\n    s(1)=u(1);\n    s(2)=u(2);\n    s(3)=u(3);\n  elseif norm(s(4)-1) <= tol\n    % disp ('rotation = 0 degrees')\n    s(1) = 0;\n    s(2) = 0;\n    s(3) = 0;\n  else\n    s(1) = (R(3,2) - R(2,3))/(4 * s(4));\n    s(2) = (R(1,3) - R(3,1))/(4 * s(4));\n    s(3) = (R(2,1) - R(1,2))/(4 * s(4));\n  end\n  x(1) = s(4);\n  x(2) = s(1);\n  x(3) = s(2);\n  x(4) = s(3);\nelse\n  disp ('Error in input matrix')\n  x=[1 0 0 0]';\nend", "meta": {"author": "uzh-rpg", "repo": "dslam_open", "sha": "3428893cffa5e832e8d51a6f3e18213b47205a83", "save_path": "github-repos/MATLAB/uzh-rpg-dslam_open", "path": "github-repos/MATLAB/uzh-rpg-dslam_open/dslam_open-3428893cffa5e832e8d51a6f3e18213b47205a83/dslam/matlab/rot2quat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5727948738899351}}
{"text": "function [e, g] = gp_eg(w, gp, x, y, varargin)\n%GP_EG  Evaluate the energy function (un-normalized negative marginal\n%       log posterior) and its gradient\n%\n%  Description\n%    [E, G] = GP_EG(W, GP, X, Y, OPTIONS) takes a Gaussian process\n%    structure GP together with a matrix X of input vectors and a\n%    matrix Y of targets, and evaluates the energy function E and\n%    its gradient G. Each row of X corresponds to one input vector\n%    and each row of Y corresponds to one target vector.\n%\n%    The energy is minus log posterior cost function:\n%        E = EDATA + EPRIOR \n%          = - log p(Y|X, th) - log p(th),\n%    where th represents the parameters (lengthScale,\n%    magnSigma2...), X is inputs and Y is observations (regression)\n%    or latent values (non-Gaussian likelihood).\n%\n%    OPTIONS is optional parameter-value pair\n%      z - optional observed quantity in triplet (x_i,y_i,z_i)\n%          Some likelihoods may use this. For example, in case of\n%          Poisson likelihood we have z_i=E_i, that is, expected\n%          value for ith case.\n%\n%  See also\n%    GP_E, GP_G\n%\n\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% Single function for some optimization routines, no need for mydeal...\ne=gp_e(w, gp, x, y, varargin{:});\nif nargout>1\n  if isnan(e)\n    g=NaN;\n  else\n    g=gp_g(w, gp, x, y, varargin{:});\n  end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/gp_eg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5727948699133937}}
{"text": "function warped_img = mdlt_warping(height, width, img, Hmdlt, offset, X, Y)\n\nwarped_img = zeros(height,width,3);\n[imgh,imgw,~] = size(img);\n\nfor xidx= 1:width\n    for yidx = 1:height\n        \n        x_grididx = min(find(X >= xidx,1));\n        y_grididx = min(find(Y >= yidx,1));\n        \n        grididx = (x_grididx-1) * size(Y,2) + y_grididx;\n        h = reshape(Hmdlt(grididx,:),3,3);\n        \n        x = xidx - offset(1) + 1;\n        y = yidx - offset(2) + 1;\n        \n        % [_x;_y;1] = H * [x;y;1]   \n        posz =  h(3,1) * x + h(3,2) * y + h(3,3) ;\n        posx = (h(1,1) * x + h(1,2) * y + h(1,3)) ./ posz;\n        posy = (h(2,1) * x + h(2,2) * y + h(2,3)) ./ posz;\n\n        if (posx>=1)&&(posx<=imgw)&&(posy>=1)&&(posy<=imgh)\n%             warped_img(yidx,xidx,:) = img(posy,posx,:);\n            \n            pix = [posy posx];\n            float_Y=pix(1)-floor(pix(1)); \n            float_X=pix(2)-floor(pix(2));\n            \n            pix_up_left=[floor(pix(1)) floor(pix(2))];\n            pix_up_right=[floor(pix(1)) ceil(pix(2))];\n            pix_down_left=[ceil(pix(1)) floor(pix(2))];\n            pix_down_right=[ceil(pix(1)) ceil(pix(2))];\n            \n            value_up_left   = (1-float_X) * (1-float_Y);\n            value_up_right  =     float_X * (1-float_Y);\n            value_down_left = (1-float_X) * float_Y;\n            value_down_right=     float_X * float_Y;\n                                                            \n            warped_img(yidx,xidx,:) = ...\n               value_up_left*img(   pix_up_left(1),   pix_up_left(2),:)+ ...\n              value_up_right*img(  pix_up_right(1),  pix_up_right(2),:)+ ...\n             value_down_left*img( pix_down_left(1), pix_down_left(2),:)+ ...\n            value_down_right*img(pix_down_right(1),pix_down_right(2),:);\n\n        else\n            warped_img(yidx,xidx,:) = [0,0,0];\n        end\n    end\nend\n\nend\n", "meta": {"author": "YaqiLYU", "repo": "AANAP", "sha": "59c2f4614293e83166fd7f34ec6c47386e054482", "save_path": "github-repos/MATLAB/YaqiLYU-AANAP", "path": "github-repos/MATLAB/YaqiLYU-AANAP/AANAP-59c2f4614293e83166fd7f34ec6c47386e054482/mdlt_warping.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5727948587263932}}
{"text": "function [out] = recharge_1(p1,S,Smax,flux)\n%recharge_1 \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 <https://www.gnu.org/licenses/> for details.\n\n% Flux function\n% ------------------\n% Description:  Recharge as scaled fraction of incoming flux\n% Constraints:  -\n% @(Inputs):    p1   - fraction of flux that is recharge [-]\n%               S    - current storage [mm]\n%               Smax - maximum contributing storage [mm]\n%               flux - incoming flux [mm/d]\n\nout = p1*S/Smax*flux;\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/recharge_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5727253503045046}}
{"text": "function [cost, info, x, A] = test22(n)\n% Test for the preconditioner support of RCG and RTR.\n%\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\n    clc;\n%     reset(RandStream.getDefaultStream);\n%     randnfoo = randn(123456, 1); %#ok<NASGU>\n    \n    if ~exist('n', 'var') || isempty(n)\n        n = 3000;\n    end\n\n    % Define the problem data : a random symmetric, positive definite\n    % matrix with an ill-conditioned diagonal part.\n    [Q, ~] = qr(randn(n));\n    A = Q*diag(rand(n, 1))*Q';\n    A = A + 150*diag(logspace(-3, 3, n));\n%     A = -A;\n    \n    % Compute a preconditioner for A\n%     P = diag(1./diag(A));\n%     fprintf('Cond. of  A : %e\\n', cond(A));\n%     fprintf('Cond. of PA : %e\\n', cond(A*P));\n    \n%     keyboard;\n    \n    % Create the problem structure\n    M = spherefactory(n);\n    problem.M = M;\n\n    % The cost and gradient\n    problem.costgrad = @costgrad;\n    function [cost grad store] = costgrad(x, store)\n        \n        if ~isfield(store, 'cost')\n            Ax = A*x;\n            store.cost = -x'*Ax;\n        end\n        cost = store.cost;\n        \n        if ~isfield(store, 'grad')\n            store.grad = -2*(Ax + cost*x);\n        end\n        grad = store.grad;\n        \n    end\n\n    % The preconditioner, which is an approximation for the inverse of the\n    % Hessian and should be a symmetric, positive definite linear operator.\n    % See notes March 18, 2013\n    problem.precon = @precon;\n    function [Pu store] = precon(x, u, store)\n        cost = store.cost;\n%         approx_hess = 2*(diag(diag(A)) - cost*eye(n));\n        approx_hess = 2*(-cost - diag(A));\n        approx_hess(approx_hess < 1e-8) = 1;\n%         if any(approx_hess < 0)\n%             fprintf('oops\\n');\n%         end\n%         Pu = M.proj(x, approx_hess\\u);\n        Pu = M.proj(x, u./approx_hess);\n%         Pu = (-2*(A+cost*eye(n)))\\u;\n%         H = 2*(x*x'*A + (x'*A*x)*eye(n) - A)*(eye(n)-x*x');\n%         keyboard;\n%         Pu = H\\u;\n%         Pu = u;\n%         Pu = M.proj(x, Pu);\n%         hist(log10(approx_hess));\n%         drawnow;\n    end\n\n\n    % If the optimization algorithms require Hessians, since we do not\n    % provide it, it will go for a standard approximation of it. This line\n    % tells Matlab not to issue a warning when this happens.\n    warning('off', 'manopt:getHessian:approx');\n    \n    % Check gradient consistency.\n%     checkgradient(problem);\n    \n    % Solve\n    fprintf('\\n ---- With preconditioning ---- \\n');\n    \n    options = struct();\n    options.maxinner = n;\n    options.tolgradnorm = 1e-5;\n    options.minstepsize = 1e-15;\n    options.beta_type = 'H-Z';\n    [x cost info] = trustregions(problem, [], options);\n    fprintf('Inner work: %d\\n', sum([info.numinner]));\n    [x cost info] = conjugategradient(problem, [], options);\n\n    fprintf('\\n ---- Without preconditioning ---- \\n');\n    problem = rmfield(problem, 'precon');\n    options.maxinner = n;\n    [x cost info] = trustregions(problem, [], options);\n    fprintf('Inner work: %d\\n', sum([info.numinner]));\n    [x cost info] = conjugategradient(problem, [], options);\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/test22.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083132, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5727253350723672}}
{"text": "function [ftlb] = J2ftlb(J)\n% Convert energy or work from joules to foot-pounds.\n% Chad A. Greene 2012\nftlb = J*0.73756217557;", "meta": {"author": "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/J2ftlb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5727253275348967}}
{"text": "% Test file for @chebfun/svd.m.\n\nfunction pass = test_svd()\n\nif ( nargin < 1 )\n    pref = chebfunpref();\nend\n\n% Check a simple example.\nf = chebfun(@(x) [sin(x) cos(x) exp(x)], [-1 -0.5 0 0.5 1]);\n[U, S, V] = svd(f);\ng = U*S*V';\npass(1) = ~U.isTransposed && (normest(f - g) < ...\n    1e2*max(vscale(f)*eps, vscale(g)*eps));\n\npass(2) = norm(U'*U - eye(3), 'fro') < 10*vscale(U)*eps;\npass(3) = norm(V'*V - eye(3), 'fro') < 10*vscale(f)*eps;\npass(4) = isequal(svd(f), diag(S));\n\nft = f.';\n[U, S, V] = svd(ft);\ng = U*S*V';\npass(5) = ~V.isTransposed && (normest(ft - g) < ...\n    1e2*max(vscale(ft)*eps, vscale(g)*eps));\n\npass(6) = norm(U'*U - eye(3), 'fro') < 10*vscale(f)*eps;\npass(7) = norm(V'*V - eye(3), 'fro') < 10*vscale(V)*eps;\n\n% Check error conditions.\ntry\n    g = svd(f, 1);\n    pass(8) = false;\ncatch ME\n    pass(7) = strcmp(ME.identifier, 'CHEBFUN:CHEBFUN:svd:twoArgs');\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/tests/chebfun/test_svd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5727253161500925}}
{"text": "function xf = shift_sample(xf, shift, kx, ky)\n\n% Shift a sample in the Fourier domain. The shift should be normalized to\n% the range [-pi, pi].\n\nshift_exp_y =exp((1i * shift(1)) * ky);\nshift_exp_x = exp((1i * shift(2)) * kx);\nxf =bsxfun(@times, bsxfun(@times, xf, shift_exp_y), shift_exp_x);", "meta": {"author": "Daikenan", "repo": "ASRCF", "sha": "5dedd83105a547be97ec4d914154439cbfd6ee9b", "save_path": "github-repos/MATLAB/Daikenan-ASRCF", "path": "github-repos/MATLAB/Daikenan-ASRCF/ASRCF-5dedd83105a547be97ec4d914154439cbfd6ee9b/utils/shift_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5727116141636681}}
{"text": "function solution = solveCobraEP(EPproblem, varargin)\n% Solves the following optimisation problem:\n%\n% minimize   osense*(c.*d)'x + d.*x'(log(x) -1) + (1/2)*x'*Q*x\n%   x\n%\n% subject to    A*x    <=> b         : y\n%               lb <= x  <=  ub      : z\n%\n% or \n% subject to    blc <= A*x <= buc   : y\n%               lb <= x  <=  ub     : z\n%\n%\n% However, when EPproblem.P is present, the following optimisation problem\n% is solved:\n% \n% minimize   osense*(c.*d)'*x  + (d.*x)'*log(x./q) + (1/2)*x'*Q*x = osense*(c.*d)'*x  + (d.*x)'*log(x) - (d.*x)'*log(q) + (1/2)*x'*Q*x\n%   x,q\n%\n% subject to    A*x    <=> b         : y\n%               P*x - q =  0         : r  \n%               lb <= x  <=  ub      : z\n%\n% or \n% subject to    blc <= A*x <= buc   : y\n%               P*x  -q =  0        : r \n%               lb <= x  <=  ub     : z\n%\n%\n%\n% USAGE:\n%    solution = solveCobraEP(EPproblem, varargin)\n%\n% INPUT:\n%    EPproblem:     Structure containing the following fields describing the EP problem to be solved\n%                     * .A  - m x n Linear constraint matrix\n%                     * .c  - n x 1 Linear objective coeff vector\n%                     * .lb - n x 1 Lower bound vector\n%                     * .ub - n x 1 Upper bound vector\n%                     * .d  - n x 1 Non-negative vector indicating the non-negative\n%                                   variables whose entropy is maximised. If d(i)==0\n%                                   then there is only a linear objective on x(i).\n%                     * .osense - Linear objective sense (-1 means maximise, 1 means minimise)\n%\n%                   With either the following fields\n%                     * .b - m x 1 right hand side vector i.e. A <=> b\n%                     * .csense - m x 1 string containting the constraint sense for\n%                                 each row in A ('E', equality, 'G' greater than, 'L' less than).\n%\n%                   Or with the following fields\n%                     * .blc - m x 1  left hand side vector i.e.  blc <= A*x\n%                     * .buc - m x 1 right hand side vector i.e.  A*x <= buc\n%\n%\n% OPTIONAL INPUTS:\n%    EPproblem:     Structure containing the following fields describing the EP problem to be solved\n%                     * .P - p x n matrix with entries {0,1}, such that q_i := P_{i,:}*x is the sums\n%                            of the x corresponding to nonzero columns of the ith row of P, i.e. P_{i,:}.\n%                            Used for normalised entropy maximisation.\n%\n%                     * .Q - positive semidefinite matrix for quadratic part of objective (see above)\n%\n%    varargin:      Additional parameters either as parameter struct, or as\n%                   parameter/value pairs. A combination is possible, if\n%                   the parameter struct is either at the beginning or the\n%                   end of the optional input.\n%                   All fields of the struct which are not COBRA parameters\n%                   (see `getCobraSolverParamsOptionsForType`) for this\n%                   problem type will be passed on to the solver in a\n%                   solver specific manner. Some optional parameters which\n%                   can be passed to the function as parameter value pairs,\n%                   or as part of the options struct are listed below:\n%                  'verify'\n%                  'printLevel'\n%                  'debug'\n%                  'feasTol'\n%                  'optTol'\n%                  'solver'\n%\n%\n%    printLevel:    Printing level\n%\n%                     * 0 - Silent (Default)\n%                     * 1 - Warnings and Errors\n%                     * 2 - Summary information\n%                     * 3 - More detailed information\n%                     * > 10 - Pause statements, and maximal printing (debug mode)\n%\n%   solver:         Optimisation solver used, {('mosek'),'pdco'}\n%   feasTol:        Feasibility tolerance\n%   optTol:         Optimality tolerance\n%\n% OUTPUT:\n%    solution:      Structure containing the following fields describing a LP solution:\n%                     * .obj:          Objective value\n%                     *.objLinear      osense*c'*x;\n%                     *.objEntropy     d.*x'*(log(x) -1);\n%                     *.objQuadratic   (1/2)*x'*Q*x;\n%                     * .full:         Primal solution vector\n%                     * .slack:        bl = A*x + s = bu\n%                     * .rcost:        Reduced costs, dual solution to :math:`lb <= x <= ub`\n%                     * .dual:         dual solution to constraints :math: `A*x ('E' | 'G' | 'L') b`\n%\n%                     * .solver:       Solver used to solve EP problem\n%                     * .stat:         Solver status in standardized form\n%                       * 0 - Infeasible problem\n%                       * 1 - Optimal solution\n%                       * 2 - Unbounded solution\n%                       * 3 - Almost optimal solution\n%                       * -1 - Some other problem (timelimit, numerical problem etc)\n%                     * .origStat:         Original status returned by the specific solver\n%                     * .origStatText:     Original status text returned by the specific solver\n%                     * .time:         Solve time in seconds\n%\n% OPTIONAL OUTPUT (from conic optimisation with mosek):\n%  solution.auxPrimal:  auxiliary primal variable\n%  solution.auxRcost:   dual to auxiliary primal variable\n%  solution.coneF:      affine constraint matrix\n%  solution.coneDual:   dual to affine constraints\n%  solution.dualNorm:   dual to the probability normalisation constraint\n%\n% OPTIONAL OUTPUT (from optimisation with pdco):\n%  solution.d1:  primal regularisation parameter, see pdco.m\n%  solution.d2:  dual regularisation parameter, see pdco.m\n%\n% EXAMPLE:\n%\n% NOTE: This code is a draft version released for the ELIXIR Fluxomic course and is not yet published and not to be redistributed without express permission of the author.\n%\n% Author(s): Ronan M.T. Fleming, 2021\n\n[problemTypeParams, solverParams] = parseSolverParameters('EP', varargin{:});\n\nif ~isfield(problemTypeParams,'debug')\n    problemTypeParams.debug = 1;\nend\n\n% Remove outer function specific parameters to avoid crashing solver interfaces\n% Default EP parameters are removed within solveCobraEP, so are not removed here\nsolverParams = mosekParamStrip(solverParams);\n\nif any(EPproblem.lb>EPproblem.ub)\n    error('EPproblem.lb>EPproblem.ub');\nend\n\n\n% assume constraint A*v = b if csense not provided\nif isfield(EPproblem, 'csense')\n    bool = EPproblem.csense == 'E' | EPproblem.csense == 'G' | EPproblem.csense == 'L';\n    if any(~bool)\n        error('Incorrect formulation of EPproblem.csense \\n%s','EPproblem.csense must be an m x 1 character array containing the constraint sense {''E'',''L'',''G''} corresponding to each row of EPproblem.A')\n    end\nend\n\nif isequal(problemTypeParams.solver,'mosek')\n    if ~(isfield(EPproblem,'blc') || isfield(EPproblem,'blc'))\n        % blc <= A*x <= buc\n        EPproblem.blc = EPproblem.b;\n        EPproblem.blc(EPproblem.csense == 'L',1) = -inf;\n        EPproblem.buc = EPproblem.b;\n        EPproblem.buc(EPproblem.csense == 'G',1) = inf;\n        %remove other specification of constraints to avoid conflict\n        EPproblem = rmfield(EPproblem,'csense');\n        EPproblem = rmfield(EPproblem,'b');\n    end\nend\n\n%% if in debug mode, test to see if the LP part of the problem is feasible\nif problemTypeParams.debug\n    switch problemTypeParams.solver\n        case 'pdco'\n            solutionLP2 = solveCobraLP(EPproblem);\n            if problemTypeParams.printLevel>2\n                disp(solutionLP2)\n            end\n            \n        case 'mosek'\n            %https://docs.mosek.com/8.1/toolbox/solving-linear.html\n            if ~isfield(problemTypeParams, 'MSK_DPAR_INTPNT_TOL_PFEAS')\n                solverParams.MSK_DPAR_INTPNT_TOL_PFEAS=problemTypeParams.feasTol;\n            end\n            if ~isfield(problemTypeParams, 'MSK_DPAR_INTPNT_TOL_DFEAS.')\n                solverParams.MSK_DPAR_INTPNT_TOL_DFEAS=problemTypeParams.feasTol;\n            end\n            %If the feasibility tolerance is changed by the solverParams\n            %struct, this needs to be forwarded to the cobra Params for the\n            %final consistency test!\n            if isfield(problemTypeParams,'MSK_DPAR_INTPNT_TOL_PFEAS')\n                solverParams.feasTol = solverParams.MSK_DPAR_INTPNT_TOL_PFEAS;\n            end\n            [res] = msklpopt(EPproblem.c,EPproblem.A,EPproblem.blc,EPproblem.buc,EPproblem.lb,EPproblem.ub,solverParams,'minimize');\n            \n            %parse mosek result structure\n            [solutionLP2.stat,solutionLP2.origStat,x,y,w] = parseMskResult(res);\n%             if stat ==1\n%                 f=c'*x;\n%                 % slack for blc <= A*x <= buc\n%                 s = b - A * x; % output the slack variables\n%             else\n%                 f = NaN;\n%                 s = NaN*ones(size(A,1),1);\n%             end\n        \n            switch solutionLP2.stat\n                case 0\n                    solution = solutionLP2;\n                    message = ['solveCobraEP: LP part of EPproblem is infeasible according to solveCobraLP with ' problemTypeParams.solver '.'];\n                    warning(message)\n                    \n                    return\n                case 2\n                    solution = solutionLP2;\n                    message = ['solveCobraEP: LP part of EPproblem is unbounded according to solveCobraLP with ' problemTypeParams.solver '.'];\n                    warning(message)\n                    \n                    return\n                case 1\n                    message =['solveCobraEP: LP part of EPproblem is feasible according to solveCobraLP with ' problemTypeParams.solver '.'];\n                    fprintf('%s\\n',message)\n                otherwise\n                    error('inconclusive solveCobraLP')\n            end\n            messages = cellstr(message);\n    end\nend\n\nif ~isfield(EPproblem, 'b')\n    EPproblem.b = zeros(size(EPproblem.A, 1), 1);\nend\n\nif ~isfield(EPproblem,'d')\n    EPproblem.d = zeros(size(EPproblem.A,2),1);\nend\nif ~isfield(EPproblem,'sumFluxes')\n    EPproblem.sumFluxes = [];\nend\nif ~isfield(EPproblem,'sumConc')\n    EPproblem.sumConc = [];\nend\nif ~isfield(EPproblem,'sumConc0')\n    EPproblem.sumConc0 = [];\nend\nif ~isfield(EPproblem,'Q')\n    if isfield(EPproblem,'F')\n        % solveCobraQP uses F for a positive semidefinite matrix\n        % we use Q instead, because F is used to denote the matrix of\n        % affine constraints arising from conic reformulation\n        EPproblem.Q = EPproblem.F;\n        EPproblem = rmfield(EPproblem,'F');\n    end\nend\n\n[A,lb,ub,c,osense,d] = ...\n    deal(EPproblem.A,EPproblem.lb,EPproblem.ub,EPproblem.c,EPproblem.osense,EPproblem.d);\n\nif isfield(EPproblem,'b')\n    b = EPproblem.b;\nelse\n    b = zeros(size(A,1),1);\nend\n\nif isfield(EPproblem,'csense')\n    csense = EPproblem.csense;\n    if isfield(EPproblem,'blc')\n        error('Ambiguous specification of EP problem to have EPproblem.blc and EPproblem.csense')\n    end\nend\n\nif isfield(EPproblem,'blc')\n    blc = EPproblem.blc;\n    buc = EPproblem.buc;\n    if any(blc> buc)\n        error('EPproblem.blc must be less than or equal to EPproblem.buc')\n    end\n    if isfield(EPproblem,'csense')\n        error('Ambiguous specification of EP problem to have EPproblem.blc and EPproblem.csense')\n    end\nend\n\n[mlt,nlt]=size(A);\n\nswitch problemTypeParams.solver\n    case 'pdco'\n        % solves optimization problems of the form\n        %\n        %    minimize    phi(x) + 1/2 norm(D1*x)^2 + 1/2 norm(r)^2\n        %      x,r\n        %    subject to  A*x + D2*r = b,   bl <= x <= bu,   r unconstrained,\n        \n        %pdco only works with equality constraints and box constraints so\n        %any other linear constraints need to be reformulated in terms of\n        %slack variables\n        %indl = find(csense == 'L'); %  A*x + s =   b\n        %indg = find(csense == 'G'); % -A*x + s = - b\n        \n        if ~any(csense == 'L' | csense == 'G')\n            Aeq  =  A;\n            beq  =  b;\n            lbeq = lb;\n            ubeq = ub;\n            ceq  =  osense*c;\n            deq  = d;\n            if isfield(EPproblem,'Q')\n                Q = EPproblem.Q;\n            end\n        else\n            Aeq = A;\n            Aeq(csense == 'G',:) = -1*Aeq(csense == 'G',:);\n            beq = b;\n            beq(csense == 'G',:) = -1*beq(csense == 'G',:);\n            K = speye(mlt);\n            K = K(:,csense == 'L' | csense == 'G');\n            Aeq = [Aeq K];\n            nSlacks = nnz(csense == 'L' | csense == 'G');\n            lbeq = [lb ; zeros(nSlacks,1)];\n            ubeq = [ub ; inf*ones(nSlacks,1)];\n            ceq  = [osense*c  ; zeros(nSlacks,1)];\n            deq  = [d  ; zeros(nSlacks,1)];\n            \n            if isfield(EPproblem,'Q')\n                %extend Q matrix to account for slack variables\n                Q = sparse(size(Aeq,2),size(Aeq,2));\n                Q(1:nlt,1:nlt) = EPproblem.Q;\n                \n            end\n        end\n        \n        %add regularisation in case its not positive definite\n        if isfield(EPproblem,'Q')\n            try\n                R = chol(Q);\n                clear R;\n            catch ME\n                fprintf('%s\\n',ME.message)\n                Q = Q + diag(sparse(ones(size(Q,1),1)*1e-4));\n            end\n        end\n                \n        if isfield(solverParams,'d1')\n            d1 = solverParams.d1;\n        else\n            d1 = 1e-4;\n        end\n        if isfield(solverParams,'d2')\n            d2 = solverParams.d2;\n        else\n            d2 = 1e-4;\n        end\n        if isfield(solverParams,'x0')\n            x0 = solverParams.x0;\n        else\n            x0 = ones(size(Aeq,2),1);\n        end\n        if isfield(solverParams,'y0')\n            y0 = solverParams.y0;\n        else\n            y0 = ones(size(Aeq,1),1);\n        end\n        if isfield(solverParams,'z0')\n            z0 = solverParams.z0;\n        else\n            z0 = ones(size(Aeq,2),1);\n        end\n        if isfield(solverParams,'xsize')\n            xsize = solverParams.xsize;\n        else\n            xsize = 1;\n        end\n        if isfield(solverParams,'zsize')\n            zsize = solverParams.zsize;\n        else\n            zsize = 1;\n        end\n        \n        %TODO - still have no idea what the best parameters for pdco are\n        options = pdcoSet;\n        %options.mu0       = 1; %very small only for entropy function\n        options.mu0       = 0; %pdco chooses its own\n        options.FeaTol    = problemTypeParams.feasTol;\n        options.OptTol    = problemTypeParams.optTol;\n        %   If getting linesearch failures, slacken tolerances\n        %   i.e. Linesearch failed (nf too big)\n        %options.FeaTol    = 1e-6; %%Ecoli core working at 1e-7\n        %options.OptTol    = 1e-6;\n        %        options.StepSame  = 0; %(allow different primal and dual steps)\n        \n        %%%%%%\n        %Additional parameter specifications by Ronan\n        %increasing to 0.99 reduced the number of iterations required\n        %options.StepTol   = 0.9;\n        % needed more than 30 iterations when xsize & zsize not tuned set\n        options.MaxIter   = 200;\n        options.Method = 1;\n        \n        if 0\n            %options from Michael's pdcotestENTROPY\n            xsize = 5/nlt;               % A few elements of x are much bigger than 1/n.\n            xsize = min(xsize,1);      % Safeguard for tiny problems.\n            zsize = 1;                 % This makes y (sic) about the right size.\n            % 10 makes ||y|| even closer to 1,\n            % but for some reason doesn't help.\n            \n            x0min = xsize;             % Applies to scaled x1, x2\n            z0min = zsize;             % Applies to scaled z1, z2\n            \n            en    = ones(size(Aeq,2),1);\n            x0    = en*xsize;          %\n            y0    = zeros(size(Aeq,1),1);\n            z0    = en*z0min;          % z is nominally zero (but converges to mu/x)\n            \n            d1    = 0;                 % gamma. 1e-3 is normal.  0 seems fine for entropy\n            d2    = 1e-3;              % delta\n            \n            options = pdcoSet;\n            options.MaxIter      =    50;\n            options.FeaTol       =  1e-6;\n            options.OptTol       =  1e-6;\n            options.x0min        = x0min;  % This applies to scaled x1, x2.\n            options.z0min        = z0min;  % This applies to scaled z1, z2.\n            options.mu0          =  1e-0;  % 09 Dec 2005: BEWARE: mu0 = 1e-5 happens\n            %    to be ok for the entropy problem,\n            %    but mu0 = 1e-0 is SAFER IN GENERAL.\n            \n            options.Method       =     1;  % 1=Chol  2=QR  3=LSQR\n            options.LSMRatol1    =  1e-3;\n            options.LSMRatol2    =  1e-6;\n            options.wait         =     0;\n        end\n                 \n        if 0\n            %Michael Saunders suggestion for badly scaled/almost infeasible\n            %problem\n            options.FeaTol = 1e-8;\n            options.OptTol = 1e-8;\n            options.Method = 2;\n            options.d1    = 1e-4;\n            options.d2    = 1e-4;\n            options.xsize = 1000;\n            options.zsize = 1e+8;\n        end\n        \n        %set the objective\n        if isfield(EPproblem,'Q')\n            objHandle = @(x) entropyQPObj(x,ceq,deq,Q);\n        else\n            objHandle = @(x) entropyObj(x,ceq,deq);\n        end\n        options.Print = problemTypeParams.printLevel-1;\n        \n        saveAndDebug=0;\n        if saveAndDebug\n            clearvars -except entropyhandle Aeq beq lbeq ubeq d1 d2 options x0 y0 z0 xsize zsize ceq deq saveAndDebug\n        end\n        tic;\n        [x,y,z,inform,~,~,~] = ...\n            pdco(objHandle,Aeq,beq,lbeq,ubeq,d1,d2,options,x0,y0,z0,xsize,zsize);\n        \n        logx = zeros(length(x),1);\n        logx(deq~=0) = reallog(x(deq~=0));     % error if negative\n        grad = ceq + deq.*logx;\n        \n        if problemTypeParams.printLevel > 2 || problemTypeParams.debug\n            % determine the residuals\n            fprintf('\\n%s\\n','KKT with pdco signs:')\n            fprintf('%8.2g %s\\n',norm(Aeq*x - beq,inf), '|| Aeq*x - beq ||_inf');\n            fprintf('%8.2g %s\\n',norm(Aeq*x - beq + (d2^2)*y,inf), '|| Aeq*x - beq + (d2^2)*y ||_inf');\n\n            %gradient may differ depending on the solver\n            % z includes (d1.^2).*x from the primal regularization.\n            fprintf('%8.2g %s\\n',norm(grad  - Aeq' * y - z,inf), '|| grad - Aeq''*y - z ||_inf');\n            fprintf('%8.2g %s\\n',norm(grad  - Aeq' * y - z - (d1^2)*x,inf), '|| grad - Aeq''*y - z - (d1^2)*x ||_inf');\n        end\n        if saveAndDebug\n            save([datestr(now,29) '_pdco_problem_debug.mat'])\n            return\n        end\n        \n        solution.time = toc;\n        \n        % inform = 0 if a solution is found;\n        %        = 1 if too many iterations were required;\n        %        = 2 if the linesearch failed too often;\n        %        = 3 if the step lengths became too small;\n        %        = 4 if Cholesky said ADDA was not positive definite.\n        if (inform == 0)\n            solution.stat = 1;\n            \n\n            if ~any(csense == 'L' | csense == 'G')\n                slack = zeros(mlt,1);\n            else\n                slack = zeros(mlt,1);\n                slack(csense == 'L' | csense == 'G') = x(nlt+1:end);\n                slack(csense == 'G') = -slack(csense == 'G');\n                %important to flip the signs of the dual variables for any\n                %greater than constraint\n                y(csense == 'G') = -y(csense == 'G');\n            end\n            \n            solution.slack = slack;\n            solution.full = x(1:nlt,1);\n            solution.dual = -y;\n            solution.rcost = -z(1:nlt,1);\n            solution.origStat = inform;\n\n            %objective\n            logx = zeros(size(A,2),1);\n            logx(d~=0) = reallog(solution.full(d~=0));     % error if negative\n            if isfield(EPproblem,'Q')\n                solution.obj  = c'*solution.full + (d.*solution.full)'*logx + (1/2)*solution.full'*EPproblem.Q*solution.full;\n                grad = c + d.*logx + EPproblem.Q*solution.full;\n            else\n                solution.obj  = c'*solution.full + (d.*solution.full)'*logx;\n                grad = c + d.*logx;\n            end\n            Aty = -A'*y;\n            \n            if problemTypeParams.printLevel > 2 || problemTypeParams.debug\n                fprintf('\\n%s\\n','KKT with Rockafellar signs:')\n                fprintf('%8.2g %s\\n',norm(A*solution.full + solution.slack - b,inf), '|| A*x + s - b ||_inf');\n                fprintf('%8.2g %s\\n',norm(A*solution.full + solution.slack - b - (d2^2)*solution.dual,inf), '|| A*x + s - b - (d2^2)*y ||_inf');\n                res2 = grad  + A'*solution.dual + solution.rcost;\n                fprintf('%8.2g %s\\n',norm(res2,inf), '|| grad + A''*y + z ||_inf');\n                \n                fprintf('%8.2g %s\\n',norm(grad  + A'*solution.dual + solution.rcost - (d1^2)*solution.full,inf), '|| grad + A''*y + z - (d1^2)*x ||_inf');\n                if problemTypeParams.debug\n                    %res2 = grad  + Aty + solution.rcost;\n                    res2 = grad  + A'*solution.dual + solution.rcost;\n                    solution.T = table(res2,c,d.*logx, -A'*y, solution.rcost,...\n                        'VariableNames',{'total','c','dlogx','Aty','z'});\n                end\n                if any(~isfinite(res2))\n                    warning('Infinite variables in dual optimality condition')\n                    solution.Tinf=solution.T(~isfinite(solution.T.total),:);\n                    ind = find(~isfinite(solution.T.total));\n                    solution.Tinf.ind = ind;\n                end\n            end\n            \n            solution.d1=d1;\n            solution.d2=d2;\n            \n        elseif (inform == 1 || inform == 2 || inform == 3)\n            solution.stat = 0;\n            solution.obj = NaN;\n        else\n            solution.stat = -1;\n            solution.obj = NaN;\n        end\n        solution.origStat = inform;\n        \n        %update parameters for testing optimality criterion\n        problemTypeParams.feasTol = options.FeaTol;\n        problemTypeParams.optTol = options.OptTol;\n        %                     * .full:         Full LP solution vector\n        %                     * .obj:          Objective value\n        %                     * .rcost:        Reduced costs, dual solution to :math:`lb <= v <= ub`\n        %                     * .dual:         dual solution to `A*v ('E' | 'G' | 'L') b`\n        %                     * .solver:       Solver used to solve LP problem\n        %                     * .algorithm:    Algorithm used by solver to solve LP problem\n        %                     * .stat:         Solver status in standardized form\n               \n    case 'mosek'\n        %%\n        %         https://docs.mosek.com/modeling-cookbook/expo.html\n        %         https://docs.mosek.com/modeling-cookbook/qcqo.html#conic-reformulation\n        %         min  (d.*x)'*(log(x./y) + c)  + (1/2)*x'*Q*x\n        %         s.t. l <= A[x;y] <= u\n        %\n        %         Assuming Q is positive semidefinite, there exists an F such that Q = F'*F\n        %\n        %         min  (d.*x)'*(log(x./y) + c)  + (1/2)*x'*(R'*R)*x\n        %         s.t. l <= A[x;y] <= u\n        %\n        %         where d,c,A,l,u,Q are data and x,y are variables, is equivalent to\n        %\n        %         min   d*e + d*c*x  + q\n        %         s.t.   x*log(x/y)    <= e\n        %                (1/2)*x'*Q'*x <= s\n        %         l <= [A, 0, 0]*[x;y;e;s] <= u\n        %\n        %         which is equivalent to:\n        %\n        %         min   d*e + d*c*x + q \n        %         s.t.   (y, x, -e) \\in K_{exp}     Exponential cone % MSK_CT_PEXP\n        %                (1, s, Fx) \\in Q^{k+2}_{r} Quadratic cone % MSK_CT_QUAD\n        %         l <= A[x;y] <= u\n        %\n        %         Such a problem could be formulated using the Affine conic constraints, as shown in the following code:\n        \n        \n        % subject to    blc <=  A*x      <= buc   : y\n        %               0   <= -P*x +  q <= 0     : r \n        %               lb  <=    x      <=  ub   : z\n        %             -inf  <=    q      <=  inf  : z\n        \n        nExpCone  = nnz(d);\n        expCone1 = (nExpCone>0)+0;\n        \n        if isfield(EPproblem,'Q')\n            quadRows  = any(EPproblem.Q,2);\n            quadCols  = any(EPproblem.Q,1)';\n            quadBool  = quadRows | quadCols;\n            nQuadCone = nnz(quadBool);\n            R = sparse(nQuadCone,size(A,2));\n            %cholesky factorisation of Q\n            R(:,quadBool) = chol(EPproblem.Q(quadBool,quadBool));\n        else\n            R=[];\n            nQuadCone = 0; \n        end\n\n        if isfield(EPproblem,'P')\n            p = size(EPproblem.P,1);\n            P = EPproblem.P;\n            pBool=(sum(P,1)~=0)'; %identify normalised variables\n        else\n            p = 0;\n            P = [];\n            pBool = false(size(d));\n        end\n        varNotNorm= any(d & ~pBool)+0;\n        quadCone1 = (nQuadCone>0)+0;\n        \n        Om1 = sparse(size(A,1),varNotNorm);\n        Omp = sparse(size(A,1),p);\n        Omd = sparse(size(A,1),nExpCone);\n        Omq = sparse(size(A,1),nQuadCone);\n        Oz1 = sparse(size(A,1),quadCone1);\n        \n        Ox1 = sparse(p,varNotNorm);\n        Ip  = spdiag(ones(p,1));\n        Opd = sparse(p,nExpCone);\n        Opq = sparse(p,nQuadCone);\n        Op1 = sparse(p,quadCone1);\n        \n        prob.a = [...\n           %x,   1,   p,   e,   1,    q;\n            A, Om1, Omp, Omd, Oz1, Omq;\n            P, Ox1, -Ip, Opd, Op1, Opq];\n        \n\n        %This should not be here!!!!!!!!!!!!!1\n%         if isfield(EPproblem,'csense')\n%             blc(csense == 'E',1) = b(csense == 'E');\n%             buc(csense == 'E',1) = b(csense == 'E');\n%             blc(csense == 'G',1) = b(csense == 'G');\n%             buc(csense == 'G',1) = inf;\n%             blc(csense == 'L',1) = -inf;\n%             buc(csense == 'L',1) = b(csense == 'L');\n%         else\n%             blc = b;\n%             buc = b;\n%         end\n        \n        prob.blc = [blc;zeros(p,1)];\n        prob.buc = [buc;zeros(p,1)];\n        \n        %remove the normalisation constant from the optimality conditions\n        %ed = double(d~=0);\n        \n        %maximise the variable corresponding to the exponential cone\n        %minimise the variable corresponding to the quadratic cone\n        %                x,                  1,         p,       e,          1,                       q;\n        prob.c = [osense*c;zeros(varNotNorm,1);zeros(p,1);-d(d~=0);zeros(quadCone1,1);ones(nQuadCone,quadCone1)];\n        \n        %fix the non-normalised variables corresponding to the exponential cone to one y = 1\n        %            x,                  1,                                                          p,                    e, 1,                     q\n        prob.blx = [lb; ones(varNotNorm,1);                                                 zeros(p,1);-inf*ones(nExpCone,1); ones(quadCone1,1);-inf*ones(nQuadCone,1)];\n        prob.bux = [ub; ones(varNotNorm,1); EPproblem.sumFluxes; EPproblem.sumConc; EPproblem.sumConc0; inf*ones(nExpCone,1); ones(quadCone1,1); inf*ones(nQuadCone,1)];\n\n        % Specify conic part of the problem\n        % https://docs.mosek.com/9.2/toolbox/data-types.html#cones\n        if problemTypeParams.printLevel>1 || problemTypeParams.debug\n            [~, res] = mosekopt('symbcon');\n        else\n            [~, res] = mosekopt('symbcon echo(0)');\n        end\n%         For affine conic constraints Fx+g\u2208\ue237, where \ue237=\ue2371\u00d7\u22ef\u00d7\ue237s, cones is a list consisting of s\n%         concatenated cone descriptions. If a cone requires no additional parameters (quadratic, rotated quadratic, exponential, zero) then its description is\n%         [type,len]\n%         where type is the type (conetype) and len is the length (dimension). The length must be present.\n        %cone type \n        prob.cones(1:2:2*nExpCone) = res.symbcon.MSK_CT_PEXP;\n        nCone = nExpCone+nQuadCone;\n        if nQuadCone>0\n            prob.cones(2*nExpCone+1:2:2*nCone) = res.symbcon.MSK_CT_QUAD;\n        end\n        %dimensions of cone\n        prob.cones(2:2:2*nCone) = 3;\n        \n        %Conic problem with affine conic constraints\n        %https://docs.mosek.com/9.2/toolbox/data-types.html#equation-doc-notation-conic\n        %f (double[][]) \u2013 The matrix of affine conic constraints. It must be a sparse matrix.\n        \n        % Primal exponential cone.\n        %  max e <= x * log(x/1),      x >= 0  <=> [ 1; x; e] \\in K_{exp}\n        %  min e >= x * log(1/x),      x >= 0  <=> [ 1; x;-e] \\in K_{exp}\n        % x3 <= x2 * log(x1 /x2), x1, x2 >= 0  <=> [x1;x2;x3] \\in K_{exp}\n        % x1 = 1 (no normalisation)\n        % x2 = x\n        % x3 = e\n        \n        % Primal exponential cone.\n        % -e <=  x * log(y /x),    y,  x >= 0  <=> [y;  x;-e] \\in K_{exp}\n        %  e >=  x * log(x /y),    y,  x >= 0  <=> [y;  x; e] \\in K_{exp}\n        % x3 <= x2 * log(x1 /x2), x1, x2 >= 0  <=> [x1;x2;x3] \\in K_{exp}\n        % x1 = 1 or y (normalisation)\n        % x2 = x\n        % x3 = e\n        Id=speye(nExpCone);\n        Idn=speye(size(A,2));\n        Idn = Idn(d~=0,:);\n        Od1 = sparse(nExpCone,varNotNorm);\n        Odp = sparse(nExpCone,p);\n        Od  = sparse(nExpCone,nExpCone);\n        Odn = sparse(nExpCone,size(A,2));\n        \n        if varNotNorm\n            %entropy maximisation without normalisation\n            Id1 = ones(size(A,2),varNotNorm);\n            Id1(pBool)=0;\n            Id1=Id1(d~=0); %zero out normalised variables from y=1;\n        else\n            %relative entropy maximsation with normalisation\n            Id1 = sparse(nExpCone,varNotNorm);\n        end\n        Ox1 = sparse(nQuadCone,varNotNorm);\n        Oz1 = sparse(nExpCone,quadCone1);\n        \n        if isfield(EPproblem,'P')\n            Idp = P(:,d~=0)';\n            Oqp = sparse(nQuadCone,size(Idp,2));\n        else\n            Idp = [];\n            Oqp = [];\n        end\n\n        % Quadratic cone\n        % https://docs.mosek.com/modeling-cookbook/cqo.html#convex-quadratic-sets\n        % (1/2)*x'*(R'*R)*x <= q            <=>  [ q; 1; R*x] \\in Q^{k+2}_{r} Quadratic cone\n        % (1/2)*x3'*(R'*R)*x3 <= x1, x2 = 1 <=>  [x1;x2;R*x3] \\in Q^{k+2}_{r} Quadratic cone\n        % x1 =   q\n        % x2 =   1\n        % x3 = R*x      \n        Iq  =  speye(nQuadCone);\n        Iq1 =   ones(nQuadCone,quadCone1);\n        Oq1 = sparse(nQuadCone,quadCone1);\n        Oq  = sparse(nQuadCone,nQuadCone);\n        Oqn = sparse(nQuadCone,size(A,2));\n                \n        %two cones\n        Odq = sparse(nExpCone,nQuadCone);\n        Oqd = sparse(nQuadCone,nExpCone);\n        \n        F = [...\n            %  x,   1,  p,   e,  1,    q;\n            Odn, Id1, Idp,  Od, Oz1, Odq;  % exp cone    x1  = 1 or y (if normalisation)\n            Oqn, Ox1, Oqp, Oqd, Oq1,  Iq;  % quad cone   x1  = q \n            Idn, Od1, Odp,  Od, Oz1, Odq;  % exp cone    x2  = x\n            Oqn, Ox1, Oqp, Oqd, Iq1,  Oq;  % quad cone   x2  = 1\n            Odn, Od1, Odp,  Id, Oz1, Odq;  % exp cone    x3  = e\n              R, Ox1, Oqp, Oqd, Oq1,  Oq]; % quad cone R*x3  = F3*x\n\n        %permute the rows of F to form (x1, x2, x3) triples for each cone\n        prob.f = sparse(size(F,1),size(F,2));\n        prob.f(1:3:(3*nCone),:) = F((1:nCone)',:);\n        prob.f(2:3:(3*nCone),:) = F((nCone+1:2*nCone)',:);\n        prob.f(3:3:(3*nCone),:) = F((2*nCone+1:3*nCone)',:);\n        \n        %g (double[]) \u2013 The constant term of affine conic constraints. If not present or g==[] it is assumed g=0\n        prob.g = zeros(size(prob.f,1),1);\n        \n        if nlt==1 && 0 %TODO implement for general small problem\n            %names on all of the variables, used for debugging small\n            %problems\n            prob.names.var = cell(size(prob.a,2)+size(prob.f,1),1);    \n            if 1\n                prob.names.var{1,1} = 'f';\n                prob.names.var{2,1} = 'r';\n                prob.names.var{3,1} = 'vA';\n                prob.names.var{4,1} = 'vB';\n                prob.names.var{5,1} = 's';\n                prob.names.var{6,1} = 'tf';\n                prob.names.var{7,1} = 'tr';\n                prob.names.var{8,1} = 'xf';\n                prob.names.var{9,1} = 'xr';\n                prob.names.var{10,1} = 'yf';\n                prob.names.var{11,1} = 'yr';\n                prob.names.var{12,1} = 'mtf';\n                prob.names.var{13,1} = 'mtr';\n                %rearrange the names of the variables according to ind\n                prob.names.var(8:13)=prob.names.var(7+ind);\n            else\n                for i=1:nlt\n                    prob.names.var{i,1} = ['f' int2str(i)];\n                    prob.names.var{nlt+i,1} = ['r' int2str(i)];\n                    prob.names.var{2*nlt+1+i,1} = ['tf' int2str(i)];\n                    prob.names.var{3*nlt+1+i,1} = ['tr' int2str(i)];\n                    prob.names.var{4*nlt+1+i,1} = ['xf' int2str(i)];\n                    prob.names.var{5*nlt+1+i,1} = ['xr' int2str(i)];\n                    prob.names.var{6*nlt+1+i,1} = ['yf' int2str(i)];\n                    prob.names.var{7*nlt+1+i,1} = ['yr' int2str(i)];\n                    prob.names.var{8*nlt+1+i,1} = ['mtf' int2str(i)];\n                    prob.names.var{9*nlt+1+i,1} = ['mtr' int2str(i)];\n                end\n            end\n            \n            %print out the problem to diagnose problems manually\n            mosekopt('write(problem.opf)',prob)\n        end\n        \n        %set default mosek parameters for this type of problem\n        paramMosek=mosekParamSetEFBA;\n        \n        if ~isfield(solverParams,'MSK_DPAR_INTPNT_CO_TOL_PFEAS')\n            if isfield(solverParams,'MSK_DPAR_INTPNT_CO_TOL_PFEAS')\n                paramMosek.MSK_DPAR_INTPNT_CO_TOL_PFEAS = solverParams.feasTol;\n            else\n                paramMosek.MSK_DPAR_INTPNT_CO_TOL_PFEAS = problemTypeParams.feasTol;\n            end\n        end\n        if ~isfield(solverParams,'MSK_DPAR_INTPNT_CO_TOL_DFEAS')\n            if isfield(solverParams,'MSK_DPAR_INTPNT_CO_TOL_DFEAS')\n                paramMosek.MSK_DPAR_INTPNT_CO_TOL_DFEAS = solverParams.optTol;\n            else\n                paramMosek.MSK_DPAR_INTPNT_CO_TOL_DFEAS = problemTypeParams.optTol;\n            end\n        end\n        \n        % only set the print level if not already set via solverParams structure\n        if ~isfield(solverParams, 'MSK_IPAR_LOG')\n            switch problemTypeParams.printLevel\n                case 0\n                    echolev = 0;\n                case 1\n                    echolev = 3;\n                case 2\n                    paramMosek.MSK_IPAR_LOG_INTPNT = 1;\n                    paramMosek.MSK_IPAR_LOG_SIM = 1;\n                    echolev = 3;\n                otherwise\n                    echolev = 0;\n            end\n            if echolev == 0\n                paramMosek.MSK_IPAR_LOG = 0;\n                cmd = ['minimize echo(' int2str(echolev) ')'];\n            else\n                cmd = 'minimize';\n            end\n            \n        end\n        %overised if in debug mode\n        if problemTypeParams.debug\n            cmd = 'minimize';\n        end\n            \n        if problemTypeParams.debug && 0\n            probBeforeMosekopt = prob;\n            save('probBeforeMosekopt','probBeforeMosekopt');\n        end\n\n        %param = updateStructData(param,solverParams);\n        \n        %call mosek exponential cone solver\n        tic;\n        if 0\n            %default\n            [~,res]=mosekopt('minimize',prob);\n        else\n            [~,res]=mosekopt(cmd,prob,paramMosek);\n        end\n        solution.time = toc;\n        \n        %parse mosek result structure      \n        [stat,origStat,x,y,z,s,doty] = parseMskResult(res,prob.a,prob.blc,prob.buc,problemTypeParams.printLevel,paramMosek);\n        \n        solution.stat = stat;\n        solution.origStat = origStat;\n        switch stat\n            case 1\n                %check for zeros in variables within entropy functions\n                zeroxBool = x(1:length(d))==0 & d~=0;\n                if any(zeroxBool)\n                    warning([num2str(nnz(zeroxBool)) ' optimal values that equal zero within entropy objective(s)'])\n                    ind = find(zeroxBool);\n                    fprintf('%8s %8s %8s\\n','xl','x','xu')\n                    for i=1:length(ind)\n                        fprintf('%8.4g %8.4g %8.4g\\n',prob.blx(ind(i)),x(ind(i)),prob.bux(ind(i)));\n                    end\n                end\n                \n                if problemTypeParams.printLevel > 1\n                    % Problem definition here: https://docs.mosek.com/9.2/toolbox/prob-def-affine-conic.html\n                    fprintf('%s\\n','Optimality conditions (numerical)')\n                    % Guide to interpreting the solution summary: https://docs.mosek.com/9.2/toolbox/debugging-log.html#continuous-problem\n                    fprintf('%8.2g %s\\n',norm(prob.a(prob.blc==prob.buc,:)*x - prob.blc(prob.blc==prob.buc),inf), '|| A*x - b ||_inf');\n                    val = norm(prob.c - prob.a'*y - z - prob.f'*doty,inf);\n                    fprintf('%8.2g %s\\n',val, '|| c - A''*y - z - F''*doty ||_inf');\n                    if val>1e-6 || problemTypeParams.debug\n                        solution.T0 = table(prob.c - prob.a'*y - z - prob.f'*doty,prob.c, prob.a'*y, z,prob.f'*doty,'VariableNames',{'tot','c','Aty','z','Ftdoty'});\n                    end\n                    %fprintf('%8.2g %s\\n',norm(prob.c - prob.f'*s,inf), '|| c - F''s ||_inf');\n                    fprintf('%8.2g %s\\n',norm(-y + res.sol.itr.slc - res.sol.itr.suc,inf), '|| -y + res.sol.itr.slc - res.sol.itr.suc ||_inf');\n                    %fprintf('%8.2g %s\\n',prob.c'*x - prob.b'*y, ' c''*x -b''*y');\n                    \n                    fprintf('%8.2g %s\\n',(prob.f*x + prob.g)'*doty, '(F*x + g)''*s >= 0');\n                end\n                \n                %%% Reorder\n                % Dual variables to affine conic constraints, based on original order of rows in F matrix\n                y_K = zeros(length(doty),1);\n                y_K(1:nCone,1) = doty(1:3:3*nCone);\n                y_K(nCone+1:2*nCone,1) = doty(2:3:3*nCone);\n                y_K(2*nCone+1:3*nCone,1) = doty(3:3:3*nCone);\n                \n                %check with the original order of the affine cone constraints\n                val = norm(prob.c - prob.a'*y - z - F'*y_K,inf);\n                if problemTypeParams.printLevel > 1\n                    fprintf('%8.2g %s\\n',val, '|| c - A''*y - z - F''*y_K ||_inf');\n                end\n                if val>1e-6 || problemTypeParams.debug\n                    solution.T = table(prob.c - prob.a'*y - z - F'*y_K,prob.c, prob.a'*y, z,prob.f'*doty,F'*y_K,'VariableNames',{'tot','c','Aty','z','Ftdoty','Fty_K'});\n                end\n                \n                if problemTypeParams.printLevel > 1\n                    x1 = F(1:nCone,:)*x;\n                    x2 = F(nCone+1:2*nCone,:)*x;\n                    x3 = F(2*nCone+1:3*nCone,:)*x;\n                    \n                    if nExpCone>0\n                        fprintf('\\n%s\\n','Primal exponential cone:')\n                        fprintf('%8.2g %s\\n',min(x1(1:nExpCone) - x2(1:nExpCone).*exp(x3(1:nExpCone)./x2(1:nExpCone))), 'min(x1 - x2*exp(x3/x2)) >= 0');\n                        %https://docs.mosek.com/modeling-cookbook/expo.html#entropy\n                        fprintf('%8.2g %s\\n',max(x3(1:nExpCone) - x2(1:nExpCone).*log(x1(1:nExpCone)./x2(1:nExpCone))), 'max(x3 - x2*log(x1/x2)) <= 0');\n                        fprintf('%8.2g %s\\n',norm(x3(1:nExpCone) - x2(1:nExpCone).*log(x1(1:nExpCone)./x2(1:nExpCone)),inf), '|| x3 - x2*log(x1/x2) ||_inf for exp cones');\n                        \n                        if nExpCone<=5 && isfield(prob,'names') && 0\n                            %TODO complete for general input\n                            for i=1:nExpCone %exp cones first\n                                fprintf('%7.2g\\t%s\\n',norm(x3(i) - x2(i).*log(x1(i)/x2(i)),inf),...\n                                    ['|| ' prob.names.var{2*n+1+i} ' - ' prob.names.var{i} '.* log(' prob.names.var{i} ' / ' prob.names.var{2*n+1} ') ||_inf']);\n                            end\n                        end\n                    end\n                    \n                    if nQuadCone>0\n                        fprintf('\\n%s\\n','Primal quadratic cone:')\n                        % (1/2)*x'*(R'*R)*x <= q\n                        % x1 =   q\n                        % x2 =   1\n                        % x3 = R*x\n                        fprintf('%8.2g %s\\n',min(x1 - (1/2)*(x3'*x3)), 'min(x1 - (1/2)*x3''*x3)) >= 0');\n                    end\n                    \n                    y1_K = y_K(1:nCone);          % 1 should  be non-negative\n                    y2_K = y_K(nCone+1:2*nCone);  % x\n                    y3_K = y_K(2*nCone+1:3*nCone);% e should  be non-positive\n                    \n                    fprintf('\\n%s\\n','Dual exponential cone:')\n                    % https://docs.mosek.com/9.2/toolbox/prob-def-affine-conic.html\n                    % This is moseks convention to the dual exponential cone\n                    fprintf('%7.2g\\t%s\\n',min(y1_K(1:nExpCone) + y3_K(1:nExpCone).*exp(y2_K(1:nExpCone)./y3_K(1:nExpCone))/exp(1)), 'min(y1_k + y3_k.*exp(y2_K./y3_K)/exp(1))  >= 0');\n                end\n                \n                solution.full = x(1:size(A,2));\n                %switch to Rockafellar signs\n                solution.dual = -y(1:size(A,1));\n                solution.dualNorm = -y(size(A,1)+1:size(A,1)+p);\n                solution.rcost = -z(1:size(A,2)+p);\n                solution.slack = s;\n                \n                %need to zero out the NaN due to log(0) for some variables\n                logSolutionFull = real(log(solution.full));\n                logSolutionFull(~isfinite(logSolutionFull))=0;\n                if isfield(EPproblem,'Q')\n                    solution.obj = EPproblem.c'*solution.full + (EPproblem.d.*solution.full)'*(logSolutionFull -1) + (1/2)*solution.full'*EPproblem.Q*solution.full;\n                    solution.objLinear = EPproblem.c'*solution.full;\n                    solution.objEntropy = -(EPproblem.d.*solution.full)'*(logSolutionFull -1);\n                    solution.objQuadratic = (1/2)*solution.full'*EPproblem.Q*solution.full;\n                else\n                    solution.obj = EPproblem.c'*solution.full + (EPproblem.d.*solution.full)'*(logSolutionFull -1);\n                    solution.objLinear = EPproblem.c'*solution.full;\n                    solution.objEntropy = -(EPproblem.d.*solution.full)'*(logSolutionFull -1);\n                    solution.objQuadratic = 0;\n\n                end\n                \n                posRcost = solution.rcost>0;\n                negRcost = solution.rcost<0;\n                blx = prob.blx(1:size(A,2));\n                bux = prob.bux(1:size(A,2));\n                solution.lagRcost = sum(solution.rcost(negRcost)'*blx(negRcost) + solution.rcost(posRcost)'*bux(posRcost));\n                \n                %pass back the F matrix to check biochemical optimality criteria\n                solution.coneF = F;\n                solution.auxPrimal = x(size(A,2)+p+1:end);\n                solution.auxRcost = -z(size(A,2)+p+1:end);\n                solution.coneDual = -y_K;\n                \n                % variable to determine the residual 1\n                b = prob.blc;\n                % variable to determine the residual 2\n                grad = prob.c - F'*y_K;\n                grad = grad(1:size(A,2)+p,1);\n                Aty = -prob.a'*y;\n                Aty = Aty(1:size(A,2)+p,1);%strictly this is [A;P]'*y\n                \n            otherwise\n                \n                doty = NaN*ones(size(prob.f,1),1);\n        end              \n    otherwise\n        error([problemTypeParams.solver ' is an unrecognised solver'])\nend\n\nswitch solution.stat\n    case 0\n        switch problemTypeParams.solver\n            case 'pdco'\n                %infeasible, debug the situtation\n                disp(solution.origStat)\n                %solution.origStat: 'PRIMAL_INFEASIBLE_CER'\n                solutionLP = solveCobraLP(EPproblem);\n            case 'mosek'\n                %https://docs.mosek.com/8.1/toolbox/solving-linear.html\n                if ~isfield(problemTypeParams, 'MSK_DPAR_INTPNT_TOL_PFEAS')\n                    solverParams.MSK_DPAR_INTPNT_TOL_PFEAS=problemTypeParams.feasTol;\n                end\n                if ~isfield(problemTypeParams, 'MSK_DPAR_INTPNT_TOL_DFEAS.')\n                    solverParams.MSK_DPAR_INTPNT_TOL_DFEAS=problemTypeParams.feasTol;\n                end\n                %If the feasibility tolerance is changed by the solverParams\n                %struct, this needs to be forwarded to the cobra Params for the\n                %final consistency test!\n                if isfield(problemTypeParams,'MSK_DPAR_INTPNT_TOL_PFEAS')\n                    solverParams.feasTol = solverParams.MSK_DPAR_INTPNT_TOL_PFEAS;\n                end\n\n                \n                % only set the print level if not already set via solverParams structure\n                if ~isfield(solverParams, 'MSK_IPAR_LOG')\n                    switch problemTypeParams.printLevel\n                        case 0\n                            echolev = 0;\n                        case 1\n                            echolev = 3;\n                        case 2\n                            solverParams.MSK_IPAR_LOG_INTPNT = 1;\n                            solverParams.MSK_IPAR_LOG_SIM = 1;\n                            echolev = 3;\n                        otherwise\n                            echolev = 0;\n                    end\n                end\n                if echolev == 0\n                    solverParams.MSK_IPAR_LOG = 0;\n                    cmd = ['minimize echo(' int2str(echolev) ')'];\n                else\n                    cmd = 'minimize';\n                end\n                [res] = msklpopt(EPproblem.c,EPproblem.A,EPproblem.blc,EPproblem.buc,EPproblem.lb,EPproblem.ub,solverParams,cmd);\n                \n                [statLP,origStat,x,y,z,s,doty] = parseMskResult(res,EPproblem.A,EPproblem.blc,EPproblem.buc,problemTypeParams.printLevel);\n                \n   \n        end\n        \n        switch statLP\n            case 1\n                message =['solveCobraEP: EPproblem with ' problemTypeParams.solver ' is infeasible, but corresponding LPproblem is feasible according to solveCobraLP with ' problemTypeParams.solver];\n                warning(message)\n            otherwise\n                message = ['solveCobraEP: EPproblem with ' problemTypeParams.solver ' is infeasible, because corresponding LPproblem is infeasible according to solveCobraLP with ' problemTypeParams.solver];\n                warning(message)\n        end\n        if exist('messages','var')\n            if isfield(solution,'messages')\n                solution.messages = [messages;solution.messages;message];\n            else\n                solution.messages = [messages;message];\n            end\n        else\n            solution.messages = cellstr(message);\n        end\n      \n    case 1\n        % check the optimality conditions for various solvers\n        if ~isempty(solution.slack) && ~isempty(solution.full)\n            % determine the residual 1\n            switch problemTypeParams.solver\n                case 'pdco'\n                    feasTol = 1e-3;\n                    res1 = A*solution.full + solution.slack - b;\n                    res1(~isfinite(res1))=0;\n                case 'mosek'\n                    feasTol = problemTypeParams.feasTol * 1e2;\n                    res1 = A(blc==buc,:)*solution.full - blc(blc==buc);\n            end\n            tmp1 = norm(res1, inf);\n            \n            % evaluate the optimality condition 1\n            if tmp1 > feasTol\n                if strcmp(problemTypeParams.solver,'pdco')\n                    res1b = norm(A*solution.full + solution.slack - b + (d2^2)*y,inf);\n                    tmp1b = norm(res1b, inf);\n                    if tmp1b > feasTol\n                        displayError = 1;\n                    else\n                        displayError = 0;\n                        warning(['[' problemTypeParams.solver '] Primal optimality condition in solveCobraEP only approximately satisfied, residual = ' num2str(tmp1) ', regularised residual = ' num2str(tmp1b) ', while problem feasTol = ' num2str(feasTol) '.  origStat = ' solution.origStat])\n                    end\n                else\n                    %TODO - debug why solver reporting optimal but unscaled seems less so.\n                    displayError = 0;\n                end\n                if displayError\n                    %disp(solution.origStat)\n                    fprintf('%s\\n',['[' problemTypeParams.solver '] Primal optimality condition in solveCobraEP not satisfied, residual = ' num2str(tmp1) ', while problem feasTol = ' num2str(feasTol) '.  origStat = ' solution.origStat])\n                end\n            else\n                if problemTypeParams.printLevel > 0\n                    fprintf(['\\n > [' problemTypeParams.solver '] Primal optimality condition in solveCobraEP satisfied.']);\n                end\n            end\n        end\n        \n        %gradient may differ depending on the solver\n        res2 = grad  + Aty + solution.rcost;\n        tmp2 = norm(res2, inf);\n        \n        if 0\n            optTol = problemTypeParams.optTol * 1e2;\n        else\n            optTol = 5e-5;\n        end\n        % evaluate the optimality condition 2\n        if tmp2 > optTol\n            disp(solution.origStat)\n            if ~(length(A)==1 && strcmp(problemTypeParams.solver,'pdco')) %todo, why does pdco choke on small A?\n                warning(['[' problemTypeParams.solver '] Dual   optimality condition in solveCobraEP not satisfied, residual = ' num2str(tmp2) ', while problem optTol = ' num2str(optTol)])\n            end\n        else\n            if problemTypeParams.printLevel > 0\n                fprintf(['\\n > [' problemTypeParams.solver '] Dual   optimality condition in solveCobraEP satisfied.\\n']);\n            end\n        end\nend\n\nsolution.solver=problemTypeParams.solver;\n\nend\n\n\nfunction [obj,grad,hess] = entropyObj(x,c,d)\n    \nn=length(x);\nlogx = zeros(n,1);\ne = double(d~=0);\nlogx(d~=0) = reallog(x(d~=0));     % error if negative\nobj  = c'*x + (d.*x)'*(logx - e);\ngrad = c + d.*logx;\nhess = d./x;\nhess(d==0)=0;\n%hess = diag(hess); % not necessary as pdco knows to treat vector as a\n%diagonal of a hessian.\nend\n\nfunction [obj,grad,hess] = entropyQPObj(x,c,d,Q)\n    \nn=length(x);\nlogx = zeros(n,1);\ne = double(d~=0);\nlogx(d~=0) = reallog(x(d~=0));     % error if negative\nobj  = c'*x + (d.*x)'*(logx - e) + 1/2*x'*Q*x;\ngrad = c + d.*logx + Q*x;\nhess = d./x;\nhess(d==0)=0;\nhess = spdiags(hess,0,n,n) + Q;\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/base/solvers/entropicFBA/solveCobraEP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5727116037537501}}
{"text": "classdef sincos < dml.method\n% SINCOS circular regression by decomposing into sine and cosine.\n%\n%   DESCRIPTION\n%   Angle is represented as sine and cosine on which regularized linear\n%   regression is performed\n%\n%   EXAMPLE\n%\n%   DEVELOPER\n%   Marcel van Gerven (m.vangerven@donders.ru.nl)\n\n    properties        \n        \n      regressor = dml.enet('family','gaussian','alpha',1);\n        \n      sinreg; % regressor applied to sine\n      cosreg; % regressor applied to cosine\n      \n    end\n    \n    methods\n        \n        function obj = sincos(varargin)\n            \n            obj = obj@dml.method(varargin{:});            \n        end        \n        \n        function obj = train(obj,X,Y)\n          \n          obj.sinreg = obj.regressor.train(X,sin(Y));\n          obj.cosreg = obj.regressor.train(X,cos(Y));\n          \n        end\n        \n        function Y = test(obj,X)\n          \n          Y = atan2(obj.sinreg.test(X),obj.cosreg.test(X));\n          \n        end\n        \n    end\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/+dml/sincos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5726790773258303}}
{"text": "function [dLdp,iCpY,L] = mci_discount_deriv (P,M,U,Y)\n% Gradient of likelihood for discounting model\n% FORMAT [dLdp,iCpY,L] = mci_discount_deriv (P,M,U,Y)\n%\n% P         parameters\n% M         model structure\n% U         contains rewards and times\n% Y         data\n%\n% dLdp      gradient of log joint\n% iCpY      curvature (Fisher Information)\n% L         log joint\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: mci_discount_deriv.m 6548 2015-09-11 12:39:47Z will $\n\ndLdp = spm_diff(M.L,P,M,U,Y,1);\ndLdp = full(dLdp(:));\n\nX = spm_diff('mci_discount_act',P,M,U,1);\ng = mci_discount_gen (P,M,U);\nLambda=diag(g.*(1-g));\niCpY=X'*Lambda*X;\n\nif nargout > 2\n    L=mci_discount_like (P,M,U,Y);\nend", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/models/discount/mci_discount_deriv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5726790713147439}}
{"text": "classdef MONRP < PROBLEM\n% <multi> <binary> <large/none>\n% The multi-objective next release problem\n% m --- 100 --- Number of customers\n\n%------------------------------- Reference --------------------------------\n% Y. Zhang, M. Harman, and S. A. Mansouri, The multi-objective next release\n% problem, Proceedings of the Annual Conference on Genetic and Evolutionary\n% Computation, 2007, 1129-1137.\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        Cost;   % Cost of each requirement\n        Value;  % Value of each customer on each requirement\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            % Parameter setting\n            m = obj.ParameterSet(100);\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 100; end\n            obj.encoding = 4 + zeros(1,obj.D);\n            % Randomly generate costs and values\n            n    = obj.D;\n            file = sprintf('MONRP-n%d-m%d.mat',n,m);\n            file = fullfile(fileparts(mfilename('fullpath')),file);\n            if exist(file,'file') == 2\n                load(file,'Cost','Value');\n            else\n                Cost  = randi(9,1,n);\n                Value = randi([0 5],n,m);\n                save(file,'Cost','Value');\n            end\n            obj.Cost  = Cost;\n            obj.Value = Value;\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            PopObj(:,1) = sum(repmat(obj.Cost,size(PopDec,1),1).*PopDec,2);\n            PopObj(:,2) = sum(obj.Value(:)) - sum(PopDec*obj.Value,2);\n        end\n        %% Generate a point for hypervolume calculation\n        function R = GetOptimum(obj,~)\n            R = [sum(obj.Cost),sum(obj.Value(:))];\n        end\n        %% Display a population in the objective space\n        function DrawObj(obj,Population)\n            PopObj(:,1) = sum(repmat(obj.Cost,length(Population),1).*Population.decs,2);\n            PopObj(:,2) = sum(Population.decs*obj.Value,2);\n            Draw(PopObj,{'Cost','Satisfaction score',[]});\n        end\n    end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/Real-world MOPs/MONRP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5726153135999699}}
{"text": "function ef = cpf_vlim_event(cb_data, cx)\n%CPF_VLIM_EVENT  Event function to detect bus voltage limit violations\n%   EF = CPF_VLIM_EVENT(CB_DATA, CX)\n%\n%   CPF event function to detect bus voltage limits violations,\n%   i.e. Vm <= Vmin or Vm >= Vmax.\n%\n%   Inputs:\n%       CB_DATA : struct of data for callback functions\n%       CX : struct containing info about current point (continuation soln)\n%\n%   Outputs:\n%       EF : event function value\n\n%   MATPOWER\n%   Copyright (c) 2016-2017, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%   and Ahmad Abubakar Sadiq, Federal University of Technology Minna, Nigeria\n%   and Shrirang Abhyankar, Argonne National Laboratory\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n%% event function value is 2 nb x 1 vector equal to:\n%%      [ Vmin - Vm ]\n%%      [ Vm - Vmax ]\n\n%% define named indices into bus, gen, branch matrices\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n\n%% get updated MPC\nd = cb_data;\nmpc = cpf_current_mpc(d.mpc_base, d.mpc_target, ...\n    d.Ybus, d.Yf, d.Yt, d.ref, d.pv, d.pq, cx.V, cx.lam, d.mpopt);\n\n%% voltage magnitude violations\nv_Vmin = mpc.bus(:, VMIN) - mpc.bus(:, VM);\nv_Vmax = mpc.bus(:, VM) - mpc.bus(:, VMAX);\n\n%% assemble event function value\nef = [v_Vmin;v_Vmax];\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/cpf_vlim_event.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5726153076855516}}
{"text": "function ar=lpccc2ar(cc)\n%LPCCC2AR Convert complex cepstrum to ar coefficients AR=(CC)\n%\n% MATLAB5 version\n\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: lpccc2ar.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[nf,p]=size(cc);\nrp=-(1:p);\ncc = cc .* rp(ones(nf,1),:);\nif p<2\n  ar = [ones(nf,1) cc(:,1)];\nelse\n ar=zeros(nf,p+1);\n ar(:,1:3) = [ones(nf,1) cc(:,1) (cc(:,2)+cc(:,1).^2)/2];\n  for k=3:p\n    ar(:,k+1) = (cc(:,k) + sum(cc(:,1:k-1).*ar(:,k:-1:2),2))/k;\n  end\nend\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/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/lpccc2ar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5726153011018604}}
{"text": "function stage_transition_type\n\nbefore_contact = ocl.Stage([], @before_contact_vars, @before_contact_ode, 'N', 3, 'd', 2);\nafter_contact = ocl.Stage(1, @after_contact_vars, @after_contact_ode, ...\n  @after_contact_cost, 'N', 5, 'd', 2);\n\nbefore_contact.setInitialBounds('s', 1);\nbefore_contact.setInitialBounds('v', 0);\nbefore_contact.setEndBounds('s', 0);\n\nbefore_contact.setBounds('energy_loss', 2);\n\nafter_contact.setBounds('s', 0, 2);\n\nafter_contact.setEndBounds('s', 1);\n\nocp = ocl.MultiStageProblem({before_contact, after_contact}, {@stage_transition},...\n  'transition_type', 2);\n\n[sol,times] = ocp.solve(ocp.getInitialGuess());\n\nstage_1 = sol{1}.states(:,[1,end]).value;\nocl.utils.assertAlmostEqual(stage_1, [1 0;0 -4.47214], 'Feature test bouncing ball failed.');\n\nend\n\nfunction before_contact_vars(sh)\nsh.addState('s');\nsh.addState('v');\n\nsh.addParameter('energy_loss');\nend\n\nfunction before_contact_ode(sh,x,~,~,~)\nsh.setODE('s', x.v);\nsh.setODE('v', -10);\nend\n\nfunction after_contact_vars(sh)\nsh.addState('s');\nsh.addState('v');\nsh.addControl('F');\nend\n\nfunction after_contact_ode(dh,x,~,u,~)\ndh.setODE('s', x.v);\ndh.setODE('v', -10 + 10*u.F);\n\nocl.utils.assert(isempty(dh.userdata()));\nend\n\nfunction after_contact_cost(ch,~,~,u,~)\nch.add( u.F^2 );\nend\n\nfunction stage_transition(ch, x0_cur, xF_prev, p_cur, p_prev)\n% x0 current stage\n% xF previous stage\nch.add(x0_cur.s, '==', xF_prev.s);\nch.add(x0_cur.v, '==', -xF_prev.v / p_prev.energy_loss);\nend\n\n\n", "meta": {"author": "OpenOCL", "repo": "OpenOCL", "sha": "348fc31929791ddc8ed15a15733cf060a2e4674c", "save_path": "github-repos/MATLAB/OpenOCL-OpenOCL", "path": "github-repos/MATLAB/OpenOCL-OpenOCL/OpenOCL-348fc31929791ddc8ed15a15733cf060a2e4674c/+ocl/+tests/+feature_tests/stage_transition_type.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5726152978645306}}
{"text": "function [ out ] = EMD1D( u, v )\n%UNTITLED3 Summary of this function goes here\n%   Detailed explanation goes here\nN = length(u);\ncumDif = zeros(N+1,1);\n\nfor i = 1:N\n    cumDif(i+1) = cumDif(i) + u(i) - v(i);\nend\n\ncumDif = abs(cumDif);\nout = sum(cumDif);\n\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/Surgery_DetectionTracking-master/kmeansClassification/EMD1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5726152965259869}}
{"text": "function [vp f] = compute_vp(lines, imgsize, camcalib)\n% compute vanishing points 'vp' using 'lines'\n% assign line class to 'lines' and 'linesmore'\n\nvpmultitype = 0;\n\n% if camcalib.provided==1     % true camera parameters provided\n%     [normal_vec, vp] = vanishline(lines, camcalib);\n% else                        % images from the web\n\n    if vpmultitype==0\n        [vp f] = vanish_from_minevidence(lines, imgsize);\n\n    elseif vpmultitype==1\n        [normal_vec, vp] = vanishline_weakorthoconst(lines, camcalib);\n\n    elseif vpmultitype==2\n        vpset = vanishline_multi(lines, camcalib);\n        % script_dispmultivp(vpset, lines, linesmore, img);\n        % figure;\n\n    elseif vpmultitype==3\n        vpset = vanishline_multi3(lines, camcalib);\n        % script_dispmultivp(vpset, lines, linesmore, img);\n        % figure;\n\n    elseif vpmultitype==4\n        vpset = vanishline_multi4(lines, camcalib);\n        % script_dispmultivp(vpset, lines, linesmore, img);\n    end\n\n% end\n\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/vanishingpoint/compute_vp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.5726152912808407}}
{"text": "%CALCHIST  Calculates a histogram of a set of arrays\n%\n%     H = cv.calcHist(images, ranges)\n%     H = cv.calcHist(..., 'OptionName',optionValue, ...)\n%\n% ## Input\n% * __images__ Source arrays. A numeric array, or cell array of numeric arrays\n%   are accepted. They all should have the same class (`uint8`, `uint16`, or\n%   `single`) and the same row/column size. Each of them can have an arbitrary\n%   number of channels. Note that passing `{img1, img2, ...}` as input is\n%   similar to using `cat(3, img1, img2, ...)`, i.e the function computes the\n%   histogram from channels of input arrays.\n% * __ranges__ Cell-array of length `N` (histogram dimensionality) of the\n%   histogram bin boundaries in each dimension.\n%   * When the histogram is uniform (`Uniform=true`), then for each dimension\n%     `i` it is enough to specify the lower (inclusive) boundary\n%     `L(1) = ranges{i}(1)` of the first histogram bin and the upper\n%     (exclusive) boundary `U(n) = ranges{i}(end)` for the last histogram bin\n%     `HistSize(i)`. That is, in case of a uniform histogram each of\n%     `ranges{i}` is an array of 2 elements forming an interval `[L,U)` which\n%     is automatically divided according to `HistSize(i)`.\n%   * When the histogram is not uniform (`Uniform=false`), then each of\n%     `ranges{i}` contains `HistSize(i)+1` elements, specifying the bin edges\n%     of dimension `i`: `L(1), L(2), ..., L(n), U(n)` forming the half-open\n%     intervals: `[L(1), U(1)), [L(2), U(2)), ..., [L(n-1), U(n-1)), [L(n), U(n))`\n%     where `U(1)==L(2), U(2)==L(3), ..., U(n-1)==L(n)`, and `n` is the\n%     histogram size of the current dimension (`n = HistSize(i)`). The array\n%     elements, that are not between `L(1)` and `U(n)`, are not counted in the\n%     histogram.\n%\n% ## Output\n% * __H__ Output histogram, which is a dense or sparse N-dimensional array of\n%   type `single` (`N` is the histogram dimensionality that must be positive\n%   and not greater than 32 in the current OpenCV version). The size of the\n%   output N-D array is `HistSize(1)-by-HistSize(2)-by-...-by-HistSize(N)`.\n%\n% ## Options\n% * __Channels__ List of channels used to compute the histogram (as 0-based\n%   indices). The number of channels must match the histogram dimensionality\n%   `N`. The first array channels are numerated from `0` to\n%   `size(images{1},3)-1`, the second array channels are counted from\n%   `size(images{1},3)` to `size(images{1},3) + size(images{2},3)-1`, and so\n%   on. By default, all channels from all images are used to compute the\n%   histogram, i.e default is `0:sum(cellfun(@(im)size(im,3), images))-1` when\n%   input `images` is a cell array, and `0:(size(images,3)-1)` when input\n%   `images` is a numeric array.\n% * __Mask__ Optional mask. If the matrix is not empty, it must be an 8-bit or\n%   logical array of the same row/column size as `images{i}`. The non-zero\n%   mask elements mark the array elements (pixels) counted in the histogram.\n%   Not set by default.\n% * __HistSize__ Array of histogram sizes in each dimension. Use together\n%   with the `Uniform` flag. Default is `cellfun(@numel,ranges)-1`.\n%   * When the histogram is uniform, the range specified in `ranges{i}` is\n%     divided into `HistSize(i)` uniform bins. The interval is divided into\n%     bins using equally-spaced boundaries defined as:\n%     `ranges{i} = linspace(ranges{i}(1), ranges{i}(end), HistSize(i)+1)`.\n%   * When the histogram is not uniform, `ranges{i}` is used as is for the\n%     bin boundaries without considering `HistSize`.\n% * __Uniform__ Logical flag indicating whether the histogram is uniform or\n%   not (see above). default false.\n% * __Hist__ Input histogram, used in accumulation mode. Either a dense or\n%   sparse array, see `H`. If it is set, the output histogram is initialized\n%   with it instead of being cleared in the beginning when it is allocated.\n%   This feature enables you to compute a single histogram from several sets\n%   of arrays, or to update the histogram in time. Not set by default.\n% * __Sparse__ Logical flag indicating whether the output should be sparse.\n%   default false (i.e output histogram is a dense array). Keep in mind that\n%   MATLAB only supports 2D sparse matrices, so use you must use dense arrays\n%   if the histogram has more than two dimensions.\n%\n% The function cv.calcHist calculates the histogram of one or more arrays. The\n% elements of a tuple used to increment a histogram bin are taken from the\n% corresponding input arrays at the same location.\n%\n% ## Example\n% The sample below shows how to compute a 2D Hue-Saturation histogram for a\n% color image:\n%\n%     hsv = cv.cvtColor(img, 'RGB2HSV');\n%     edges = {linspace(0,180,30+1), linspace(0,256,32+1)};\n%     H = cv.calcHist(hsv(:,:,1:2), edges);\n%\n% Here is another example showing the different options:\n%\n%     % read some image, and convert to HSV colorspace\n%     imgRGB = imread(fullfile(mexopencv.root(),'test','img001.jpg'));\n%     imgHSV = cv.cvtColor(imgRGB, 'RGB2HSV');\n%\n%     % quantize the hue to 30 levels, and the saturation to 32 levels\n%     histSize = [30, 32];\n%     hranges = linspace(0, 180, histSize(1)+1);  % hue varies from 0 to 179\n%     sranges = linspace(0, 256, histSize(2)+1);  % sat varies from 0 to 255\n%     ranges = {hranges, sranges};\n%\n%     % one way\n%     H = cv.calcHist(imgHSV(:,:,[1 2]), ranges);\n%\n%     % another way\n%     H = cv.calcHist(imgHSV, ranges, 'Channels',[1 2]-1, 'HistSize',histSize);\n%\n%     % or similarly\n%     H = cv.calcHist({imgHSV(:,:,1), imgHSV(:,:,2)}, {[0,180], [0,256]}, ...\n%         'HistSize',histSize, 'Uniform',true);\n%\n%     % show H-S histogram\n%     imagesc(H, 'YData',[0 180], 'XData',[0 256])\n%     axis image; colormap gray; colorbar\n%     ylabel('Hue'); xlabel('Saturation'); title('Histogram')\n%\n% See also: cv.calcBackProject, cv.compareHist, cv.EMD, hist, histc,\n%  histogram, histcounts, histcounts2, discretize, imhist, hist3\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/calcHist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.572608020485709}}
{"text": "function realtest_AD1()\n% Test AD for a real optimization problem on a product manifold (struct)\n\n    % Verify that Manopt was indeed added to the Matlab path.\n    if isempty(which('spherefactory'))\n        error(['You should first add Manopt to the Matlab path.\\n' ...\n\t\t       'Please run importmanopt.']);\n    end\n    \n    % Verify that the deep learning tool box was installed\n    assert(exist('dlarray', 'file') == 2, ['Deep learning tool box is '... \n    'needed for automatic differentiation.\\n Please install the'...\n    'latest version of the deep learning tool box and \\nupgrade to Matlab'...\n    ' R2021b if possible.'])\n    \n    % Generate the problem data.\n    n = 100;\n    A = randn(n);\n    A = .5*(A+A');\n    \n    % Create the product manifold\n    S = spherefactory(n);\n    manifold.x = S;\n    manifold.y = S;\n    problem.M = productmanifold(manifold);\n    \n    % Define the problem cost function\n    problem.cost  = @(X) -X.x'*(A*X.y);\n    \n    % Define the gradient and the hessian via automatic differentiation\n    problem = manoptAD(problem);\n\n    % Numerically check gradient and Hessian consistency.\n    figure;\n    checkgradient(problem);\n    figure;\n    checkhessian(problem);\n    \n    % Solve.\n    [x, xcost, info] = trustregions(problem);          %#ok<ASGLU>\n    \n    % Test\n    ground_truth = svd(A);\n    distance = abs(ground_truth(1) - (-problem.cost(x)));\n    fprintf('The distance between the ground truth and the solution is %e \\n',distance);\n\n    \nend", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/autodiff/basic_examples_AD/realtest_AD1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5724619387528602}}
{"text": "% l1_softth - soft threshold function for L1 regularization\n%\n% Copyright(c) 2009 Ryota Tomioka\n% This software is distributed under the MIT license. See license.txt\n\nfunction [vv,ss]=l1_softth(vv,lambda,info)\n\nn = size(vv,1);\n\nIp=find(vv>lambda);\nIn=find(vv<-lambda);\n\nvv=sparse([Ip;In],1,[vv(Ip)-lambda;vv(In)+lambda],n,1);\n\nss=abs(vv);", "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/dal_ver1.05/l1_softth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5724619323731538}}
{"text": "% RES = corrDn(IM, FILT, EDGES, STEP, START, STOP)\n%\n% Compute correlation of matrices IM with FILT, followed by\n% downsampling.  These arguments should be 1D or 2D matrices, and IM\n% must be larger (in both dimensions) than FILT.  The origin of filt\n% is assumed to be floor(size(filt)/2)+1.\n% \n% EDGES is a string determining boundary handling:\n%    'circular' - Circular convolution\n%    'reflect1' - Reflect about the edge pixels\n%    'reflect2' - Reflect, doubling the edge pixels\n%    'repeat'   - Repeat the edge pixels\n%    'zero'     - Assume values of zero outside image boundary\n%    'extend'   - Reflect and invert (continuous values and derivs)\n%    'dont-compute' - Zero output when filter overhangs input boundaries\n%\n% Downsampling factors are determined by STEP (optional, default=[1 1]), \n% which should be a 2-vector [y,x].\n% \n% The window over which the convolution occurs is specfied by START \n% (optional, default=[1,1], and STOP (optional, default=size(IM)).\n% \n% NOTE: this operation corresponds to multiplication of a signal\n% vector by a matrix whose rows contain copies of the FILT shifted by\n% multiples of STEP.  See upConv.m for the operation corresponding to\n% the transpose of this matrix.\n\n% Eero Simoncelli, 6/96, revised 2/97.\n\nfunction res = corrDn(im, filt, edges, step, start, stop)\n\n%% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD)\n\n% fprintf(1,'WARNING: You should compile the MEX version of \"corrDn.c\",\\n         found in the MEX subdirectory of matlabPyrTools, and put it in your matlab path.  It is MUCH faster, and provides more boundary-handling options.\\n');\n\n%------------------------------------------------------------\n%% OPTIONAL ARGS:\n\nif (exist('edges') == 1) \n  if (strcmp(edges,'reflect1') ~= 1)\n    warning('Using REFLECT1 edge-handling (use MEX code for other options).');\n  end\nend\n\nif (exist('step') ~= 1)\n\tstep = [1,1];\nend\t\n\nif (exist('start') ~= 1)\n\tstart = [1,1];\nend\t\n\nif (exist('stop') ~= 1)\n\tstop = size(im);\nend\t\n\n%------------------------------------------------------------\n\n% Reverse order of taps in filt, to do correlation instead of convolution\nfilt = filt(size(filt,1):-1:1,size(filt,2):-1:1);\n\ntmp = rconv2(im,filt);\nres = tmp(start(1):step(1):stop(1),start(2):step(2):stop(2));\n", "meta": {"author": "tyshiwo", "repo": "DRRN_CVPR17", "sha": "cafe98bc73997c10947911de74279d63cb786b8a", "save_path": "github-repos/MATLAB/tyshiwo-DRRN_CVPR17", "path": "github-repos/MATLAB/tyshiwo-DRRN_CVPR17/DRRN_CVPR17-cafe98bc73997c10947911de74279d63cb786b8a/test/evaluation_func/matlabPyrTools-master/corrDn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.5724619316425799}}
{"text": "% planarcams ... alignment under assumption of planar camera arrangements\n%\n% [align,cam] = planarmove(in,cam,config,idx)\n% in, cam, config ... see the main GOCAL script\n% idx ... indexes of cameras which are suppose to be in one plane\n%\n% align ... structures aligned wit the specified world frame\n%\n% $Id: planarcams.m,v 1.1 2003/07/03 15:36:55 svoboda Exp $\n\nfunction [align,cam] = planarcams(in,cam,config,idx)\n\n% fit a plane to the reconstructed points and estimate normal\n\nplane.n = planefit(in.Ce(:,idx)');\n\nnew.n = [0,0,1]'; % align the xy plane horizontally\n\nrotaxis = cross(new.n,plane.n);\nrotangle = acos( (plane.n'*new.n)/norm(plane.n)*norm(new.n) );\n\nR = nfi2r(rotaxis,rotangle);\ns = 3;\nt = [0,0,1]' - s*R*mean(in.Xe(1:3,:)')';\n\nalign.simT.s = s;\nalign.simT.R = R;\nalign.simT.t = t;\n\n[align.P, align.X]\t= align3d(in.Pe,in.Xe,align.simT);\n% save aligned data\nif 1 % SAVE_STEPHI | SAVE_PGUHA\n\t[align.Cst,align.Rot] = savecalpar(align.P,config);\nend\ndrawscene(align.X,align.Cst',align.Rot,61,'cloud','Graphical Output Validation: Aligned data, TopView',config.cal.cams2use);\n\nset(gca,'CameraTarget',[0,0,0]);\nset(gca,'CameraPosition',[0,0,1]);\n\nfigure(61),\n% print -depsc graphevalaligned.eps\neval(['print -depsc ', config.paths.data, 'topview.eps'])\n\ndrawscene(align.X,align.Cst',align.Rot,62,'cloud','Graphical Output Validation: Aligned data, SideView',config.cal.cams2use);\n\nset(gca,'CameraTarget',[0,0,0.9]);\nset(gca,'CameraPosition',[2,0,0.9]);\n\nfigure(62),\n% print -depsc graphevalaligned.eps\neval(['print -depsc ', config.paths.data, 'sideview.eps'])\n\nreturn\n\n\n", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamSelfCal/LocalAlignments/planarcams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5724619274545945}}
{"text": " function [xs, info] = pwls_sps_os(x, yi, wi, Ab, R, niter, pixmax, ...\n\t\tdenom, aai, relax0, chat)\n%function [xs, info] = pwls_sps_os(x, yi, wi, Ab, R, niter, pixmax, ...\n%|\t\tdenom, aai, relax0, chat)\n%|\n%| penalized weighted least squares estimation/reconstruction\n%| using separable paraboloidal surrogates algorithm with\n%| (optionally relaxed) ordered subsets.  (relaxation ensures convergence.)\n%|\n%| cost(x) = (y-Gx)' W (y-Gx) / 2 + R(x)\n%|\n%| in\n%|\tx\t[np 1]\t\tinitial estimate\n%|\tyi\t[nb na]\t\tmeasurements (noisy sinogram)\n%|\twi\t[nb na]\t\tweighting sinogram (or [] for uniform)\n%|\tAb\t[nd np]\t\tGblock object, aij >= 0 required!\n%|\t\t\t\t\tor sparse matrix (implies nsubset=1)\n%|\tR\t\t\tpenalty object (see Reg1.m)\n%|\tniter\t\t\t# of iterations (including 0)\n%|\n%| optional\n%|\tpixmax\t[1] or [2]\tmax pixel value, or [min max] (default [0 inf])\n%|\tdenom\t[np 1]\t\tprecomputed denominator\n%|\taai\t[nb na]\t\tprecomputed row sums of |Ab|\n%|\trelax0\t[1] or [2]\trelax0 or (relax0, relax_rate)\n%|\tchat\n%|\n%| out\n%|\txs\t[np niter]\titerates\n%|\tinfo\t[niter 1]\ttime\n%|\n%| Copyright 2002-2-12, Jeff Fessler, University of Michigan\n\nif nargin < 4, ir_usage, end\n\ncpu etic\ninfo = zeros(niter,1);\n\nAb = block_op(Ab, 'ensure'); % make it a block object (if not already)\nnblock = block_op(Ab, 'n');\nstarts = subset_start(nblock);\n\nif ~isvar('niter')\t|| isempty(niter),\tniter = 1;\tend\nif ~isvar('pixmax')\t|| isempty(pixmax),\tpixmax = inf;\tend\nif ~isvar('chat')\t|| isempty(chat),\tchat = false;\tend\nif isempty(wi)\n\twi = ones(size(yi));\nend\nif ~isvar('aai') || isempty(aai)\n\taai = reshape(sum(Ab'), size(yi)); % a_i = sum_j |a_ij|\n\t\t\t\t\t% requires real a_ij and a_ij >= 0\nend\n\nif ~isvar('relax0') || isempty(relax0)\n\trelax0 = 1;\nend\nif length(relax0) == 1\n\trelax_rate = 0;\nelseif length(relax0) == 2\n\trelax_rate = relax0(2);\n\trelax0 = relax0(1);\nelse\n\terror relax\nend\n\nif length(pixmax) == 2\n\tpixmin = pixmax(1);\n\tpixmax = pixmax(2);\nelseif length(pixmax) == 1\n\tpixmin = 0;\nelse\n\terror pixmax\nend\n\n%\n% likelihood denom, if not provided\n%\nif ~isvar('denom') || isempty(denom)\n\tdenom = Ab' * col(aai .* wi);\t% requires real a_ij and a_ij >= 0\nend, clear aai\n\nif ~isvar('R') || isempty(R)\n\tpgrad = 0;\t\t% unregularized default\n\tRdenom = 0;\nend\n\n[nb na] = size(yi);\n\n\n%\n% loop over iterations\n%\n\nxs = zeros(numel(x), niter, class(x));\nx = max(x,pixmin);\nx = min(x,pixmax);\nxs(:,1) = x;\n\nfor iter = 2:niter\n\tticker(mfilename, iter, niter)\n\n\trelax = relax0 / (1 + relax_rate * (iter-2));\n\n\t%\n\t% loop over subsets\n\t%\n\tfor iset=1:nblock\n\t\tiblock = starts(iset);\n\t\tia = iblock:nblock:na;\n\n\t\tli = Ab{iblock} * x;\n\t\tli = reshape(li, nb, length(ia));\n\t\tresid = wi(:,ia) .* (yi(:,ia) - li);\n\t\tgrad = Ab{iblock}' * resid(:); % G' * W * (y - G*x)\n\n\t\tif ~isempty(R)\n\t\t\tpgrad = R.cgrad(R, x);\n\t\t\tRdenom = R.denom(R, x);\n\t\tend\n\n\t\tnum = nblock * grad - pgrad;\n\t\tden = denom + Rdenom;\n\n\t\tx = x + relax * num ./ den;\t% relaxed update\n\t\tx = max(x,pixmin);\t\t% lower bound\n\t\tx = min(x,pixmax);\t\t% upper bound\n\tend\n\n\tif chat, printm('range(x) = %g %g', min(x), max(x)), end\n\txs(:,iter) = x;\n\tinfo(iter,1) = cpu('etoc');\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/wls/pwls_sps_os.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5724619193461816}}
{"text": "function TAU = int_tau(Z)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   Program:    Tau Integral Computation for Hydrogen Composition Program\n%               in Atmospheric Model\n%   Author:     Brent Lewis(RocketLion@gmail.com)\n%               University of Colorado-Boulder\n%   History:    Original-1/10/2007\n%   Input:      Z:      Altitude value\n%   Output:     TAU:    Integral Value\n%   Note:       This program computes the value of Tau directly with the\n%               integral done by hand and only the second integration limit\n%               needing to be inputed\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%   Constants\nL_K_9 = 12;\nT_10 = 360;\nT_inf = 1000;\nZ_10 = 120;\ng_0 = 9.80665;\nr_E = 6.356766e3;\nR = 8.31432e3;\nlambda = L_K_9/(T_inf-T_10);\nM_H = 1.00797;\n\n%   Value of Integration limit computed previously\ntau_11 = 8.329503912749350e-004;\n\ntau_Z = M_H*g_0*r_E^2/R*...\n    log((exp(lambda*(Z-Z_10)*(r_E+Z_10)/(r_E+Z))-1)*T_inf+T_10)/...\n    (lambda*T_inf*(r_E+Z_10)^2);\n\nTAU = tau_Z-tau_11;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13635-complete-1976-standard-atmosphere/int_tau.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.5724400827134718}}
{"text": "% written by Ali A. Eftekhari\nclc\nL = 50;  % domain length\nNx = 20; % number of cells\nm = createMesh3D(Nx, Nx, Nx, L, L, L);\nBC = createBC(m); % all Neumann boundary condition structure\nBC.left.a(:) = 0; BC.left.b(:)=1; BC.left.c(:)=1; % Dirichlet for the left boundary\nBC.right.a(:) = 0; BC.right.b(:)=1; BC.right.c(:)=0; % right boundary\nD_val = 1; % value of the diffusion coefficient\nD = createCellVariable(m, D_val); % assign the diffusion coefficient to the cells\nD_face = harmonicMean(D); % calculate harmonic average of the diffusion coef on the cell faces\nMdiff = diffusionTerm(D_face); % matrix of coefficients for the diffusion term\n[Mbc, RHSbc] = boundaryCondition(BC); % matix of coefficients and RHS vector for the BC\nM = Mdiff + Mbc; % matrix of cefficients for the PDE\nc = solvePDE(m,M, RHSbc); % send M and RHS to the solver\nvisualizeCells(c); % visualize the results", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Tests/readme_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5724400749017097}}
{"text": "\nclear\n%Process definition\nar = rc2arset([1 -.4 .2]);\nma = rc2arset([1 .8]);\n%End of Process definition\nn_obs = 10;\n\nrch = [1 -.6 -.3 -.2];\nLar = length(rch)-1;\narh_set = rc2arset(rch,0:Lar);\n\n%function pe_set = prederrAR(rc,cov)\n%PREDERRAR Prediction error of AR models of increasing order\nvareps = 1/pgain(ar,ma);\ncor = arma2cor(ar,ma,Lar);\n\nr = [cor(end:-1:1) cor(2:end)];\npe(1) = 1;\neo = r; %cor;\nfo = r; %cor;\npe_old(1) = 1;\nfor p = 1:Lar\n    carh = [arh_set{p+1} zeros(1,Lar-p)];\n    crc = rch(p+1);\n    ahahp = convol(fliplr(carh),carh)\n    ahah  = convol(carh,carh);\n    e = xcorr(ahah,r);  e = e(Lar+1:3*Lar+1);\n    f = xcorr(ahahp,r); f = f(2*Lar+1:3*Lar+1);\n    %Recursieve berekening van e en f.\n    er = NaN*ones(1,Lar+1);\n    for q = p:Lar\n        er(q+1) = eo(q+1) + 2*crc*fo(q-p+1) + crc^2*eo(2*p-q+1);\n    end\n    fr = NaN*ones(1,Lar+1);\n%     for q = 0:Lar-p\n%         fr(q+1) = (1+crc^2)*fo(q+1) + crc*eo(p+q+1); %Klopt alleen voor witte ruis!\n%     end\n%     e,er\n%     f,fr;\n    disp(' ')\n    pe(p+1) = f(Lar+1) %werkt\n\n    %Preparations for next step\n    eo = e;\n    fo = f;\n\n    %Old PE\n    pe_old(p+1) = (moderr(carh,1,ar,ma,1)+1)*vareps;\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/3680-automatic-spectral-analysis/AutomaticSpectra/TimserTools/prederrAR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5724285756761711}}
{"text": "function X = Inv_CoarseCurveCoeff(C);\n% Inv_CoarseCurveCoeff: Reconstruct the low-frequency subband from\n%                           the coarsest scale curvelet coefficients\n%  Usage:\n%    X = Inv_CoarseCurveCoeff(C);\n%  Inputs:\n%    C   m by m matrix, m = 2*2^L\n%  Outputs:\n%    X   m by m matrix  \n% See Also\n%   CoaseCurveCoeff, Inv_Curvelet02Xform\n%\n% By Emmanuel Candes, 2003-2004\n\nX = fft2_mid0(C)/sqrt(prod(size(C)));\n\t \n\t \n\t \n\t \t \n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/CurveLab-2.1.3/fdct_usfft_matlab/CurveCoeff/Inv_CoarseCurveCoeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5724285687550162}}
{"text": "function plot3d (type)\nglobal A cds opt holdon leg label figmain smmethod subpl\n\n\n% Check if there IS data to plot\nif isempty(A) errordlg ('No data present. Sure you read a file yet?','Error'); return; end\n\n% Add or substitute plot\nfigure (figmain);\nsubplot(subpl(1),subpl(2),subpl(3),'Parent',figmain);\nif holdon hold on; else \thold off; end\n\n% Columns\nX= A(:,opt.xc(1));\nY= A(:,opt.yc(1));\nM= A(:,opt.zc);\n\nswitch type\n\tcase 'histo'\n\t\thist(Y,10);\n\tcase 'histo3'\n\t\thist3([X,Y],[10,10]);\n\tcase 'corrxy'\n\t\t[rho,pval]= corr(X,Y);\n\t\tplot(X,Y,'o');\n\t\tL= ['rho= ',num2str(rho),' p< ',num2str(pval)];\n\t\tlegend(L);\n\tcase 'corrall'\n\t\tfprintf('Col Row  Rho  Pval \\n')\n\t\toutput= mcorr(A,'sig');\n\t\tfprintf('  %d   %d %4.2f  %4.2f \\n',output)\n\tcase 'qqplot'\n\t\tqqplot(X,Y);\n\tcase 'normplot'\n\t\tnormplot(X);\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/8309-qplot/plotstat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5724188416351207}}
{"text": "function [Y, R, E] = IsomapII(D, n_fcn, n_size, options); \n\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\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 ischar(D)\n     mode = 3; \n     d_func = D; \n     N = length(feval(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 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 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,:) = feval(d_func,ceil(N*rand)); \n         end\n         K = 2*max(sum(tmp'<epsilon));    % just to be safe\n     end\nelse \n     error('Neighborhood function must be either epsilon or k'); \nend\n\nif (mode == 3)\n     INF = inf; \nelse\n     INF =  1000*max(max(D))*N;  %% effectively infinite distance\nend\n\nif ~isfield(options,'dims')\n     options.dims = 1:10; \nend\nif ~isfield(options,'overlay')\n     options.overlay = 1; \nend\nif ~isfield(options,'comp')\n     options.comp = 1; \nend\nif ~isfield(options,'display')\n     options.display = 1; \nend\nif ~isfield(options,'verbose')\n     options.verbose = 1; \nend\nif ~isfield(options,'landmarks')\n     options.landmarks = 1:N; \nend\nif ~isfield(options,'dijkstra')\n     options.dijkstra = 1; \nend\ndims = options.dims; \ncomp = options.comp; \noverlay = options.overlay; \ndispl = options.display; \nverbose = options.verbose; \nlandmarks = options.landmarks; \nuse_dijk = options.dijkstra;\n\nY.coords = cell(length(dims),1); \nR = zeros(1,length(dims)); \n\n%%%%% Step 1: Construct neighborhood graph %%%%%\ndisp('Constructing neighborhood graph...'); \n\nif ((mode == 1) & (use_dijk == 0))\n     if n_fcn == 'k'\n         [tmp, ind] = sort(D); \n         tic; \n         for i=1:N\n             D(i,ind((2+K):end,i)) = INF; \n             if ((verbose == 1) & (rem(i,50) == 0)) \n                 disp([' Iteration: ' num2str(i) '     Estimated time to completion: 'num2str((N-i)*toc/60/50) ' minutes']); tic; \n             end\n         end\n     elseif n_fcn == 'epsilon'\n         warning off    %% Next line causes an unnecessary warning, so turn it off\n         D =  D./(D<=epsilon); \n         D = min(D,INF); \n         warning on\n     end\n     D = min(D,D');    %% Make sure distance matrix is symmetric\nelseif ((mode == 1) & (use_dijk == 1))\n     if n_fcn == 'k'\n         [tmp, ind] = sort(D); \n         tic;\n         for i=1:N\n             D(i,ind((2+K):end,i)) = 0; \n             if ((verbose == 1) & (rem(i,50) == 0)) \n                 disp([' Iteration: ' num2str(i) '     Estimated time to completion: 'num2str((N-i)*toc/60/50) ' minutes']); tic; \n             end\n         end\n     elseif n_fcn == 'epsilon'\n         D =  D.*(D<=epsilon); \n     end\n     D = sparse(D); \n     D = max(D,D');    %% Make sure distance matrix is symmetric\nelseif (mode == 2)\n     if n_fcn == 'k'\n         Di = zeros(N*K,1);      Dj = zeros(N*K,1);       Ds = zeros(N*K,1); \n         counter = 0; \n         [a,b,c] = find(D); \n         tic; \n         for i=1:N\n             l = find(a==i); \n             [g,f] = sort(c(l)); \n             Di(counter+(1:K)) = i; \n             Dj(counter+(1:K)) = b(l(f(1:K))); \n             Ds(counter+(1:K)) = g(1:K); \n             counter = counter+K; \n             if ((verbose == 1) & (rem(i,50) == 0)) \n                  disp([' Iteration: ' num2str(i) '     Estimated time to completion: 'num2str((N-i)*toc/60/50) ' minutes']); tic; \n             end\n         end\n         D = sparse(Di(1:counter), Dj(1:counter), Ds(1:counter));\n         clear Di Dj Ds counter; \n     elseif n_fcn == 'epsilon'\n         D =  D.*(D<=epsilon); \n     end\n     D = max(D,D');    %% Make sure distance matrix is symmetric\nelseif (mode == 3)\n     Di = zeros(N*(K+1),1);      Dj = zeros(N*(K+1),1);       Ds = zeros(N*(K+1),1); \n     counter = 0; \n     tic; \n     for i=1:N\n         d = feval(d_func,i); \n         if n_fcn == 'k'\n             [c,b] = sort(d); \n             Di(counter+(1:(K+1))) = i; \n             Dj(counter+(1:(K+1))) = b(1:(K+1)); \n             Ds(counter+(1:(K+1))) = c(1:(K+1)); \n             counter = counter+(K+1); \n         elseif n_fcn == 'epsilon'\n             [a,b,c] = find(d.*(d<=epsilon)); \n             l = length(a); \n             Di(counter+(1:l)) = i; \n             Dj(counter+(1:l)) = b; \n             Ds(counter+(1:l)) = c; \n             counter = counter+l; \n         end\n         if ((verbose == 1) & (rem(i,50) == 0)) \n              disp([' Iteration: ' num2str(i) '     Estimated time to completion: 'num2str((N-i)*toc/60/50) ' minutes']); tic; \n         end\n     end\n     D = sparse(Di(1:counter), Dj(1:counter), Ds(1:counter));\n     clear Di Dj Ds counter; \n     D = max(D,D');    %% Make sure distance matrix is symmetric\nend    \n\nif (overlay == 1)\n     if ((mode == 1) & (use_dijk == 0))\n         E = int8(1-(D==INF));  %%  Edge information for subsequent graph overlay\n     else\n         [a,b,c] = find(D); \n         E = sparse(a,b,ones(size(a))); \n     end\nend\n\n%%%%% Step 2: Compute shortest paths %%%%%\ndisp('Computing shortest paths...'); \n\nif ((mode==1) & (use_dijk == 0))\n     tic; \n     for k=1:N\n         D = min(D,repmat(D(:,k),[1 N])+repmat(D(k,:),[N 1])); \n         if ((verbose == 1) & (rem(k,20) == 0)) \n              disp([' Iteration: ' num2str(k) '     Estimated time to completion: 'num2str((N-i)*toc/i/60) ' minutes']); \n         end\n     end\nelse\n     D = dijkstra(D, landmarks);\nend\n\n%%%%% Step 3: Construct low-dimensional embeddings (Classical MDS) %%%%%\ndisp('Constructing low-dimensional embeddings (Classical MDS)...'); \n\n%%%%% Remove outliers from graph %%%%%\ndisp('  Checking for outliers...'); \n\nif ((mode == 1) & (use_dijk == 0))\n     [tmp, firsts] = min(D==INF);     %% first point each point connects to\nelse\n     [tmp, firsts] = min(D==inf);     %% first point each point connects to\nend\n[comps, I, J] = unique(firsts);    %% first point in each connected component\nn_comps = length(comps);           %% number of connected components\nsize_comps = sum((repmat(firsts,n_comps,1)==((1:n_comps)'*ones(1,N)))'); \n                                   %% size of each connected component\n[tmp, comp_order] = sort(size_comps);  %% sort connected components by size\ncomps = comps(comp_order(end:-1:1));    \nsize_comps = size_comps(comp_order(end:-1:1)); \nif (comp>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": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/mrFlatMesh/mex/CSource/IsomapII.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5724188345761394}}
{"text": "function A = makehatch_plus(hatch,n,m)\n%MAKEHATCH_PLUS Predefined hatch patterns\n%\n% Modification of MAKEHATCH to allow for selection of matrix size. Useful whe using \n%   APPLYHATCH_PLUS with higher resolution output.\n%\n% input (optional) N    size of hatch matrix (default = 6)\n% input (optional) M    width of lines and dots in hatching (default = 1)\n%\n%  MAKEHATCH_PLUS(HATCH,N,M) returns a matrix with the hatch pattern for HATCH\n%   according to the following table:\n%      HATCH        pattern\n%     -------      ---------\n%        /          right-slanted lines\n%        \\          left-slanted lines\n%        |          vertical lines\n%        -          horizontal lines\n%        +          crossing vertical and horizontal lines\n%        x          criss-crossing lines\n%        .          square dots\n%        c          circular dots\n%        w          Just a blank white pattern\n%        k          Just a totally black pattern\n%\n%  See also: APPLYHATCH_PLUS\n\n%  By Ben Hinkle, bhinkle@mathworks.com\n%  This code is in the public domain. \n\n% Modified Brian FG Katz    8-aout-03\n% Modified David M Kaplan    19-fevrier-08\n\nif ~exist('n','var'), n = 6; end\nif ~exist('m','var'), m = 1; end\nn=round(n);\n\nswitch (hatch)\n  case '\\'\n    [B,C] = meshgrid( 0:n-1 );\n    B = B-C; \n    clear C\n    A = abs(B) <= m/2;\n    A = A | abs(B-n) <= m/2;\n    A = A | abs(B+n) <= m/2;\n  case '/'\n    A = fliplr(makehatch_plus('\\',n,m));\n  case '|'\n    A=zeros(n);\n    A(:,1:m) = 1;\n  case '-'\n    A = makehatch_plus('|',n,m);\n    A = A';\n  case '+'\n    A = makehatch_plus('|',n,m);\n    A = A | A';\n  case 'x'\n    A = makehatch_plus('\\',n,m);\n    A = A | fliplr(A);\n  case '.'\n    A=zeros(n);\n    A(1:2*m,1:2*m)=1;\n  case 'c'\n    [B,C] = meshgrid( 0:n-1 );\n    A = sqrt(B.^2+C.^2) <= m;\n    A = A | fliplr(A) | flipud(A) | flipud(fliplr(A));\n  case 'w'\n    A = zeros(n);\n  case 'k'\n    A = ones(n);\n  otherwise\n    error(['Undefined hatch pattern \"' hatch '\".']);\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/18826-hatch-fill-patterns-plus-plus/hatchpattern_plus/makehatch_plus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059316231899, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5724188132764678}}
{"text": "function [Q2,Bg2,delta_X2,Pk2]=ESKF(Q1,Bg1,delta_X1,ImuData,t,Vm,Pk1)\n\n% ESKF( Error State Kalman Filter)\n% derivation <Quaternion Kinematics for the Error-state Kalman Filter>\n% author Zhang xin \n\n\nif isempty(Pk1)\n    Para_delta_theta0=0.00001;\n    Para_delta_Bg0=0.00001;\n    Pk1=diag([[1,1,1]*Para_delta_theta0,[1,1,1]*Para_delta_Bg0]);\nend\n\nnorm_a=norm(ImuData(1,2:4));\n%norm_g=norm(ImuData(1,5:7)-Bg1);\nwx=(ImuData(1,5)-Bg1(1))*t;\nwy=(ImuData(1,6)-Bg1(2))*t;\nwz=(ImuData(1,7)-Bg1(3))*t;\n\nQp=[ 1    , -wx/2 , -wy/2 , -wz/2  ;...\n     wx/2 ,   1   ,  wz/2 , -wy/2  ;...\n     wy/2 , -wz/2 ,   1   ,  wx/2  ;...\n     wz/2 ,  wy/2 , -wx/2 ,   1   ]*Q1';\nQp=Qp/norm(Qp);\n \ndelta_theta=norm([wx,wy,wz]);\n\nif delta_theta==0\n    R_u_delta_theta=eye(3);\nelse\n    u= [wx,wy,wz]'/delta_theta;\n    R_u_delta_theta=eye(3)-Skew_symmetric(u)*sin(delta_theta)+Skew_symmetric(u)*Skew_symmetric(u)*(1-cos(delta_theta));\nend\n\nF_delta_X=[R_u_delta_theta, -eye(3)*t;...\n           zeros(3,3),       eye(3) ];\nPara_delta_theta=0.000001;\nPara_delta_Bg=0.000001;\nQ_delta_X=diag([[1,1,1]*Para_delta_theta,[1,1,1]*Para_delta_Bg]);\n       \ndelta_Xp = F_delta_X*delta_X1';     \n\nP_k=F_delta_X*Pk1*F_delta_X'+Q_delta_X;\n\nif abs(norm_a-9.8)<2 %&& norm_g< 2\n   \n   % R1=[2*Qp(1)^2+2*Qp(2)^2-1;...\n   %     2*Qp(2)*Qp(3)-2*Qp(1)*Qp(4);...\n   %     2*Qp(1)*Qp(3)+2*Qp(2)*Qp(4)];\n    \n    R2=[2*Qp(2)*Qp(3)+2*Qp(1)*Qp(4);...\n        2*Qp(1)^2+2*Qp(3)^2-1;...\n        2*Qp(3)*Qp(4)-2*Qp(1)*Qp(2)];\n    \n    R3=[2*Qp(2)*Qp(4)-2*Qp(1)*Qp(3);...\n        2*Qp(3)*Qp(4)+2*Qp(1)*Qp(2);...\n        2*Qp(1)^2+2*Qp(4)^2-1 ];  \n    \n   % J1=2*[ Qp(1), Qp(2),-Qp(3),-Qp(4);...\n   %       -Qp(4), Qp(3), Qp(2), Qp(1);...\n   %        Qp(3), Qp(4), Qp(1), Qp(2)];    \n    \n    J2=2*[ Qp(4), Qp(3), Qp(2) , Qp(1);...\n           Qp(1),-Qp(2), Qp(3) ,-Qp(4);...\n          -Qp(2),-Qp(1), Qp(4) , Qp(3)] ;  \n      \n    J3=2*[-Qp(3), Qp(4),-Qp(1) , Qp(2);...\n           Qp(2), Qp(1), Qp(4) , Qp(3);...\n           Qp(1),-Qp(2),-Qp(3) , Qp(4)] ;   \n       \n    h_acc= R3;\n    h_mag = Vm(2)*R2+Vm(3)*R3;\n    \n    H_acc = [J3,zeros(3,3)];\n    H_mag = [Vm(2)*J2+Vm(3)*J3,zeros(3,3)];\n    \n    Q_delta_theta= 1/2*[ -Qp(2), -Qp(3), -Qp(4) ;...\n                          Qp(1), -Qp(4),  Qp(3) ;...\n                          Qp(4),  Qp(1), -Qp(2) ;...\n                         -Qp(3),  Qp(2),  Qp(1) ];\n     \n    X_delta_x=[Q_delta_theta, zeros(4,3);...\n                zeros(3,3),      eye(3)];\n    \n    Hk= [H_acc;H_mag]* X_delta_x;     \n    \n    para_Rk_acc=0.1;\n    para_Rk_mag=0.2;\n    Rk=diag([[1,1,1]*para_Rk_acc,[1,1,1]*para_Rk_mag]);\n    \n    Kk=P_k*Hk'*inv(Hk*P_k*Hk'+Rk);\n    \n    delta_X_hat=Kk*([ImuData(1,2:4)'/norm_a;ImuData(1,8:10)'/norm(ImuData(1,8:10))]-[h_acc;h_mag]);\n    \n    Q2=quaternProd(Qp, [1;delta_X_hat(1:3)/2])';\n    Q2=Q2/norm(Q2);\n    Bg2=Bg1+delta_X_hat(4:6)';\n    \n    Pk2_=(eye(6)-Kk*Hk)*P_k;\n    \n    delta_X2=delta_Xp'+delta_X_hat';\n    \n    G=[eye(3)-Skew_symmetric(-delta_X2(1:3)/2),zeros(3,3);...\n        zeros(3,3)   ,                 eye(3)];\n    \n    Pk2=G*Pk2_*G';\n    \nelse\n    Q2=Qp';\n    Bg2=Bg1;\n    delta_X2=delta_Xp';\n    Pk2=P_k;\n    \nend\n    delta_X2(1:3)=[0,0,0];\n    \n    if Q2(1)<0\n        Q2=-Q2;\n    end\n\n\nend\n\n\nfunction S=Skew_symmetric(u)\n%Skew_Operator\n\nS=[  0  , -u(3) ,  u(2) ;...\n    u(3),   0   , -u(1) ;...\n   -u(2),  u(1),    0 ];\n\nend\n\nfunction ab = quaternProd(a, b)\n    ab(1,1) = a(1)*b(1)-a(2)*b(2)-a(3)*b(3)-a(4)*b(4);\n    ab(2,1) = a(1)*b(2)+a(2)*b(1)+a(3)*b(4)-a(4)*b(3);\n    ab(3,1) = a(1)*b(3)-a(2)*b(4)+a(3)*b(1)+a(4)*b(2);\n    ab(4,1) = a(1)*b(4)+a(2)*b(3)-a(3)*b(2)+a(4)*b(1);\n    if ab(1)<0\n        ab=-ab;\n    end\nend\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/ESKF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5722860386234621}}
{"text": "%Let Cpn_est=(I-S(e))Cpn. Then e=[Egyro Eplat]*[gyro error;Platform error]\n%platform err def:Cbp_est=(I-S(p))*Cbp\n%gyro err def: gyro_meas=gyro+gyro_error\nfunction [Cnp, Egyro, Eplat]=alingc_hd(gyro, Lat, Cbp)\n\nWIE_E=7292115e-11;\nnrot=WIE_E*cos(Lat);\n\n%normalize gyro;\ngyro=gyro/norm(gyro)*WIE_E;\n\n%Compute the earth rotation in platform frame\nif isempty(Cbp)\n    Cbp=eye(3);\nend\ngyro_p=Cbp*gyro;\n\n%Transformation\nCnp=zeros(3);\nCnp(1,1)=gyro_p(1)/nrot;\nCnp(2,2)=gyro_p(1)/nrot;\nCnp(2,1)=gyro_p(2)/nrot;\nCnp(1,2)=-Cnp(2,1);\nCnp(3,3)=1;\n\n%Error matrices\nEgyro=[-gyro_p(2)/nrot^2 gyro_p(1)/nrot^2 0]*Cbp;\nEplat=[-gyro_p(2)/nrot^2 gyro_p(1)/nrot^2 0]*skew(gyro_p);\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/alingc_hd_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5722244730879136}}
{"text": "% Replication of the trivariate VAR in Stock and Watson (2001, JEP).\n% Figure 1 and Table 1.B.\n%==========================================================================\n% The VAR Toolbox 3.0 is required to run this code. To get the \n% latest version of the toolboxes visit: \n% https://github.com/ambropo/VAR-Toolbox\n%==========================================================================\n% Ambrogio Cesa Bianchi, November 2020\n% ambrogio.cesabianchi@gmail.com\n\n\n%% PRELIMINARIES\n%==========================================================================\nclear all; clear session; close all; clc\nwarning off all\n\n% Load data\n[xlsdata, xlstext] = xlsread('SW2001_Data.xlsx','Sheet1');\nX = xlsdata;\ndates = xlstext(3:end,1);\nvnames_long = xlstext(1,2:end);\nvnames = xlstext(2,2:end);\nnvar = length(vnames);\ndata   = Num2NaN(xlsdata);\n% Store variables in the structure DATA\nfor ii=1:length(vnames)\n    DATA.(vnames{ii}) = data(:,ii);\nend\n% Convert the first date to numeric\nyear = str2double(xlstext{3,1}(1:4));\nquarter = str2double(xlstext{3,1}(6));\n% Observations\nnobs = size(data,1);\n\n%% VAR ESTIMATION\n%==========================================================================\n% Set deterministics for the VAR\ndet = 1;\n% Set number of nlags\nnlags = 4;\n% Estimate VAR\n[VAR, VARopt] = VARmodel(X,nlags,det);\n% Print estimation on screen\nVARopt.vnames = vnames;\n[TABLE, beta] = VARprint(VAR,VARopt,2);\n\n\n%% COMPUTE IR AND VD\n%==========================================================================\n% Set options some options for IRF calculation\nVARopt.nsteps = 24;\nVARopt.ident = 'short';\nVARopt.vnames = vnames_long;\nVARopt.FigSize = [26,12];\n% Compute IRF\n[IRF, VAR] = VARir(VAR,VARopt);\n% Compute error bands\n[IRinf,IRsup,IRmed,IRbar] = VARirband(VAR,VARopt);\n% Plot\nVARirplot(IRbar,VARopt,IRinf,IRsup);\n\n% Compute VD\n[VD, VAR] = VARvd(VAR,VARopt);\n% Compute VD error bands\n[VDinf,VDsup,VDmed,VDbar] = VARvdband(VAR,VARopt);\n% Plot VD\nVARvdplot(VDbar,VARopt);\n\n\n%% Print Table 1.B on screen\n%==========================================================================\n% Retrieve Forecast Error Variance Decomposition\nFEVD_Table(1, :) = VD(1,:,1);\nFEVD_Table(2, :) = VD(4,:,1);\nFEVD_Table(3, :) = VD(8,:,1);\nFEVD_Table(4, :) = VD(12,:,1);\n\nFEVD_Table(5, :) = VD(1,:,2);\nFEVD_Table(6, :) = VD(4,:,2);\nFEVD_Table(7, :) = VD(8,:,2);\nFEVD_Table(8, :) = VD(12,:,2);\n\nFEVD_Table(9, :) = VD(1,:,3);\nFEVD_Table(10,:) = VD(4,:,3);\nFEVD_Table(11,:) = VD(8,:,3);\nFEVD_Table(12,:) = VD(12,:,3);\n\n% Print on screen\ndisp(' ')\ndisp('Variance Decomposition of Inflation (t=1,4,8,12)')\ndisp('---------------------------------------------------')\nmprint(FEVD_Table(1:4,:));\ndisp('Variance Decomposition of Unemployment (t=1,4,8,12)')\ndisp('---------------------------------------------------')\nmprint(FEVD_Table(5:8,:));\ndisp('Variance Decomposition of Fed Funds (t=1,4,8,12)')\ndisp('---------------------------------------------------')\nmprint(FEVD_Table(9:12,:));", "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/Replic/SW2001/GO_SW2001.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5722093865729921}}
{"text": "function [nodeBel, edgeBel, L] = mrfMf(A, nodePot, edgePot, epoch)\n% Mean field for MRF\n% Assuming egdePot is symmetric\n% Input: \n%   A: n x n adjacent matrix of undirected graph, where value is edge index\n%   nodePot: k x n node potential\n%   edgePot: k x k x m edge potential\n% Output:\n%   nodeBel: k x n node belief\n%   edgeBel: k x k x m edge belief\n% Written by Mo Chen (sth4nth@gmail.com)\nif nargin < 4\n    epoch = 10;\nend\nL = -inf(1,epoch+1);\n[nodeBel,lnZ] = softmax(nodePot,1);    % initialization    \nfor iter = 1:epoch\n    for i = 1:size(nodePot,2)\n        [~,j,e] = find(A(i,:));             % neighbors\n        [nodeBel(:,i),lnZ(i)] = softmax(nodePot(:,i)+reshape(edgePot(:,:,e),2,[])*reshape(nodeBel(:,j),[],1));\n    end\n%     E = dot(nodeBel,nodePot,1);\n%     H = -dot(nodeBel,log(nodeBel),1);\n%     L(iter+1) = sum(lnZ+E+H)/2;\n    L(iter+1) = mrfGibbs(A,nodePot,edgePot,nodeBel);\n%     if abs(L(iter+1)-L(iter))/abs(L(iter)) < tol; break; end\nend\nL = L(1,2:iter+1);\n\n[s,t,e] = find(triu(A));\nedgeBel = zeros(size(edgePot));\nfor l = 1:numel(e)\n    edgeBel(:,:,e(l)) = nodeBel(:,s(l))*nodeBel(:,t(l))';\nend", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter08/MRF/mrfMf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5722093701387673}}
{"text": "function  [h, compUp] =  lfmComputeH4(gamma1_p, gamma1_m, sigma2, t1, preFactor, preExp,...\n    mode, term )\n% LFMCOMPUTEH4 Helper function for computing part of the LFM kernel.\n% FORMAT\n% DESC computes a portion of the LFM kernel.\n% ARG gamma1 : Gamma value for first system.\n% ARG gamma2 : Gamma value for second system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG mode: indicates in which way the vectors t1 and t2 must be transposed\n% RETURN h : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : David Luengo, 2007\n%\n% COPYRIGHT : Mauricio Alvarez, 2008\n%\n% MODIFICATIONS : Neil D. Lawrence, 2007\n%\n%\n%\n% SEEALSO : lfmKernParamInit, lfmXlfmKernCompute\n\n% KERN\n\n% Evaluation of h\n\nif nargin<8\n    term =[];\nend\n\nif ~mode\n    if ~term\n        if nargout>1\n            compUp = lfmComputeUpsilonVector(gamma1_p,sigma2, t1);\n            h = compUp*( preExp/preFactor(1) - conj(preExp)/preFactor(2)).';\n        else\n            h = lfmComputeUpsilonVector(gamma1_p,sigma2, t1)*( preExp/preFactor(1) - conj(preExp)/preFactor(2)).';\n        end\n    else\n        if nargout>1\n            compUp = lfmComputeUpsilonVector(gamma1_p,sigma2, t1);\n            h = compUp*(preExp/preFactor(1)).' - conj(compUp)*(preExp/preFactor(2)).';\n        else\n            upsilon = lfmComputeUpsilonVector(gamma1_p,sigma2, t1);\n            h = upsilon*(preExp/preFactor(1)).' - conj(upsilon)*(preExp/preFactor(2)).';\n        end\n    end\nelse\n    if nargout > 1\n        compUp{1} = lfmComputeUpsilonVector(gamma1_p,sigma2, t1);\n        compUp{2} = lfmComputeUpsilonVector(gamma1_m,sigma2, t1);\n        h =  compUp{1}*( preExp(:,1)/preFactor(1) - preExp(:,2)/preFactor(2)).' ...\n            + compUp{2}*( preExp(:,2)/preFactor(3) - preExp(:,1)/preFactor(4)).';\n    else\n        h =  lfmComputeUpsilonVector(gamma1_p,sigma2, t1)*( preExp(:,1)/preFactor(1) - preExp(:,2)/preFactor(2)).' ...\n            + lfmComputeUpsilonVector(gamma1_m,sigma2, t1)*( preExp(:,2)/preFactor(3) - preExp(:,1)/preFactor(4)).';\n    end\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmComputeH4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5722093640742899}}
{"text": "function beta_vector = scattering_coefficient_random(number_of_images,...\n    parameters)\n%SCATTERING_COEFFICIENT_RANDOM  Generate scattering coefficient values for a set\n%of images uniformly at random.\n%   Inputs:\n%       -|number_of_images|: number of images for which scattering coefficient\n%       is simulated.\n%       -|parameters|: structure containing miscellaneous parameters, such as\n%       range of values for scattering coefficient and type of random number\n%       generator. Guarantees uniformity with other functions that implement\n%       generation of scattering coefficient values.\n%\n%   Outputs:\n%       -|beta_vector|: 1-by-|number_of_images| vector containing the random\n%       values of scattering coefficient for every image in the set.\n\n% Determine the range of random values for scattering coefficient.\nmaximum_value = parameters.maximum_value;\nminimum_value = parameters.minimum_value;\n\n% Get type of random number generator, e.g. 'default'.\nrandom_generator = parameters.random_generator;\n\n% Get binary flag that indicates whether the random number generator should be\n% configured or not.\nconfigure_random_generator = parameters.configure_random_generator;\n\n% Optionally configure random number generation for repeatability.\nif configure_random_generator\n    rng(random_generator);\nend\n\n% Generate random scattering coefficient for each image following a uniform\n% distribution inside the specified range.\nbeta_vector = minimum_value + (maximum_value - minimum_value) *...\n    rand(1, number_of_images);\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/scattering_coefficient_random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5721721268224745}}
{"text": "classdef PoolingNode < GraphNode\n    properties\n        poolingDimension = 3;      % poolinig happens along this dimension\n        poolingType = 'max';       % [max|min|mean|median|sum]\n        selectedIdx = [];          % remember the index of data selected by pooling in [max|min|median]\n    end\n    \n    methods\n        function obj = PoolingNode(dimOut, poolingType, poolingDimension)\n            obj = obj@GraphNode('Pooling',dimOut);\n            if nargin>=2\n                obj.poolingType = poolingType;\n            end\n            if nargin>=3\n                obj.poolingDimension = poolingDimension;\n            end\n        end\n        \n        function obj = forward(obj,prev_layers)\n            obj = obj.preprocessingForward(prev_layers);\n            input = prev_layers{1}.a;\n            \n            switch lower(obj.poolingType)\n                case 'max'\n                    [obj.a, obj.selectedIdx] = max(input, [], obj.poolingDimension);\n                case 'min'\n                    [obj.a, obj.selectedIdx] = min(input, [], obj.poolingDimension);\n                case 'mean'\n                    obj.a = mean(input, obj.poolingDimension);\n                case 'median'\n                    obj.a = median(input, obj.poolingDimension);\n                    % need to implement selectedIdx by myself in the future\n                case 'sum'\n                    obj.a = sum(input, obj.poolingDimension);\n            end\n            \n            obj = forward@GraphNode(obj, prev_layers);\n        end\n        \n        function obj = backward(obj,prev_layers, future_layers)\n            if obj.skipGrad || obj.skipBP\n                return;\n            end\n            \n            future_grad = obj.GetFutureGrad(future_layers);\n            input = prev_layers{1}.a;\n            [D(1), D(2), D(3), D(4)] = size(input);\n            \n            switch lower(obj.poolingType)\n                case {'max', 'min', 'median'}\n                    obj.grad{1} = obj.AllocateMemoryLike(D, future_grad);\n                    obj.grad{1}(obj.selectedIdx) = future_grad;\n                case {'mean','sum'}\n                    if strcmpi(obj.poolingType, 'mean')\n                        future_grad = future_grad / D(obj.poolingDimension);\n                    end\n                    shape = ones(1,4);\n                    shape(obj.poolingDimension) = D(obj.poolingDimension);\n                    obj.grad{1} = repmat(future_grad, shape);\n            end\n            \n            obj = backward@GraphNode(obj, prev_layers, future_layers);\n        end\n        \n    end\n    \nend", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/graph_obj/nodes/PoolingNode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5721721239963753}}
{"text": "function [dat,beta,x] = ft_preproc_detrend(dat, begsample, endsample)\n\n% FT_PREPROC_DETREND removes mean and linear trend from the\n% data using using a General Linear Modeling approach.\n%\n% Use as\n%   [dat] = ft_preproc_detrend(dat, begin, end)\n% where\n%   dat        = data matrix (Nchans X Ntime)\n%   begsample  = index of the begin sample for the trend estimate\n%   endsample  = index of the end sample for the trend estimate\n%\n% If no begin and end sample are specified for the trend estimate, it\n% will be estimated on the complete data.\n%\n% See also FT_PREPROC_BASELINECORRECT, FT_PREPROC_POLYREMOVAL\n\n% Copyright (C) 2008-2014, 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 <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% take the whole segment if begsample and endsample are not specified\nif nargin<2 || isempty(begsample)\n  begsample = 1;\nend\nif nargin<3|| isempty(endsample)\n  endsample = size(dat,2);\nend\n\n[dat,beta,x] = ft_preproc_polyremoval(dat, 1, begsample, endsample);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/preproc/ft_preproc_detrend.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5721721194103707}}
{"text": "% @author: Maziar Raissi\n\nfunction KDV()\nclc; close all;\n\nplt = 1;\nplt_pred = 0;\nsave_plt = 1;\n\naddpath ..\naddpath ../Utilities\naddpath ../Kernels/KDV\naddpath ../Utilities/export_fig\n\nfunction CleanupFun()\n    rmpath ..\n    rmpath ../Utilities\n    rmpath ../Kernels/KDV\n    rmpath ../Utilities/export_fig\nend\n\nfinishup = onCleanup(@() CleanupFun());\n\nset(0,'defaulttextinterpreter','latex')\n\n%% Load Data\nload('../Data/kdv.mat', 'usol', 't', 'x')\nu_star = real(usol); % 512x201\nt_star = t; % 201x1\nx_star = x';   % 512x1\nN_star = size(x_star,1);\nnsteps = size(t_star,1)-1;\n    \n%% Setup\nN0 = 111;\nN1 = 109;\n%% Clean Data\nrng('default')\ni = randi(nsteps);\ndt = t_star(i+1) - t_star(i);\n\nidx0 = randsample(N_star, N0);\nx0 = x_star(idx0,:);\nu0 = u_star(idx0,i);\n\nidx1 = randsample(N_star,N1);\nx1 = x_star(idx1,:);\nu1 = u_star(idx1,i+1);\n\nhyp = [log([1.0 1.0]) 0.0 0.0 -4.0];\nmodel = HPM(x1, u1, x0, u0, dt, hyp);\nmodel = model.train(5000);\n\nhyp = model.hyp;\nparams = hyp(3:4);\n\n[pred_n_star, var_n_star] = model.predict(x_star);\nvar_n_star = abs(diag(var_n_star));\n\nerror = norm(pred_n_star - u_star(:,i+1))/norm(u_star(:,i+1));\n\nfprintf(1,'=========================\\n');\nfprintf(1,'Step: %d, Time = %.2f\\n\\nNLML = %.2f, Error = %.2e\\n\\n', i, ...\n    t_star(i+1), model.NLML, error);\n\nstr = sprintf('%.4f  ', params);\nfprintf('Parameters: %s\\n\\n', str)\nfprintf(1,'=========================\\n\\n');\n\nif plt_pred == 1\n    figure();\n    plot_prediction_1D(x_star, u_star(:,i+1), pred_n_star, var_n_star, ...\n        '$x$', '$u(t,x)$', 'Prediction (clean data)');\n    \n    drawnow;\nend\n\n%% Noisy Data\nnoise = 0.01;\nu0 = u0 + noise*std(u0)*randn(size(u0));\nu1 = u1 + noise*std(u1)*randn(size(u1));\n\nhyp = [log([1.0 1.0]) 0.0 0.0 -4.0];\nmodel = HPM(x1, u1, x0, u0, dt, hyp);\nmodel = model.train(5000);\n\nhyp = model.hyp;\nparams_noise = hyp(3:4);\n\n[pred_n_star, var_n_star] = model.predict(x_star);\nvar_n_star = abs(diag(var_n_star));\n\nerror = norm(pred_n_star - u_star(:,i+1))/norm(u_star(:,i+1));\n\nfprintf(1,'=========================\\n');\nfprintf(1,'Step: %d, Time = %.2f\\n\\nNLML = %.2f, Error = %.2e\\n\\n', i, ...\n    t_star(i+1), model.NLML, error);\n\nstr = sprintf('%.4f  ', params_noise);\nfprintf('Parameters: %s\\n\\n', str)\nfprintf(1,'=========================\\n\\n');\n\nif plt_pred == 1\n    figure();\n    plot_prediction_1D(x_star, u_star(:,i+1), pred_n_star, var_n_star, ...\n        '$x$', '$u(t,x)$', 'Prediction (noisy data)');\n    \n    drawnow;\nend\n\n%% Plot Results\n\nif plt == 1\n    fig = figure();\n    set(fig,'units','normalized','outerposition',[0 0 1 .5])\n    subplot(3,2,1:2)\n    plot_surface(t_star, x_star, u_star, '$t$', '$x$', '$u(t,x)$');\n    \n    hold on\n    plot3([t_star(i) t_star(i)],get(gca,'ylim'),[10 10],'w','LineWidth',2)\n    plot3([t_star(i+1) t_star(i+1)],get(gca,'ylim'),[10 10],'w','LineWidth',2)\n    \n    subplot(3,2,3);\n    tit = sprintf('$t = $ %.2f\\n%d training data\\n', t_star(i), N0);\n    plot_data_1D(x_star, u_star(:,i), x0, u0, '$x$', '$u(t,x)$', tit);\n    \n    subplot(3,2,4);\n    tit = sprintf('$t = $ %.2f\\n%d training data\\n', t_star(i+1), N1);\n    plot_data_1D(x_star, u_star(:,i+1), x1, u1, '$x$', '$u(t,x)$', tit);\n    \n    subplot(3,2,5:6);\n    s1 = '$\\begin{tabular}{ |c|c| }  \\hline Correct PDE & $u_t + 6 u u_x + u_{xxx} = 0$ \\\\  \\hline Identified PDE (clean data) &';\n    s2 = sprintf('$u_t + %.3f u u_x + %.3f u_{xxx} = 0$', params(1), params(2));\n    s3 = ' \\\\  \\hline Identified PDE (1\\% noise) &';\n    s4 = sprintf('$u_t + %.3f u u_x + %.3f u_{xxx} = 0$', params_noise(1), params_noise(2));\n    s5 = ' \\\\  \\hline \\end{tabular}$';\n    s = strcat(s1,s2,s3,s4,s5);\n    text(0.1,0.8,s,'interpreter','latex','FontSize',18)\n    axis off\n    \n    if save_plt == 1\n        export_fig ../Figures/KDV.png -r300\n    end\n    \n    drawnow();\nend\n\nend", "meta": {"author": "maziarraissi", "repo": "HPM", "sha": "21a7429cceb55d5ab688256db75ac360e2d8a925", "save_path": "github-repos/MATLAB/maziarraissi-HPM", "path": "github-repos/MATLAB/maziarraissi-HPM/HPM-21a7429cceb55d5ab688256db75ac360e2d8a925/Examples/KDV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.572172110238361}}
{"text": "function matrix = genMatEllPPIFE3D(pde,mesh,fem,femI,femIF,PPtype,sig)\n%% Generate global matrices and load vector of PPIFEM for 3D ellipic eq\n%     -div(A grad u)  = f,    x\\in \\Omega\n%      where A is a piecewise constant on Omega^+ and Omega^-.\n% INPUTS:\n% pde --- given data function from equation, e.g. \n%         pde.A --- diffusion coefficient\n%         pde.f --- right hand side function\n%         pde.gD --- Dirichlet boundary value function \n%         pde.one --- constant function 1.\n% mesh --- mesh structure. \n% fem --- global degree of freedom of FEM \n% femI --- quadrature info on interface cells\n% femIF --- quadrature info on interface faces, required in PPIFE.\n% PPtype --- partial penalty type possible value \n%            'N' : Nonsymmetric PPIFE (e = 1)\n%            'S' : Symmetric PPIFE (e = -1)\n%            'I' : Incomplete PPIFE (e = 0)\n% OUTPUTS:\n% matrix.S --- stiffness matrix (w/o boundary condition)\n% matrix.E --- consistence matrix (w/o boundary condition)\n% matrix.P --- penalty matrix (w/o boundary condition)\n% matrix.A --- final FEM matrix (after boundary condition)\n% matrix.rhsF --- load vector (w/o boundary condition)\n% matrix.rhsE --- consistence vector (=0 if no interface face on boundary)\n% matrix.rhsP --- penalty vector (=0 if no interface face on boundary)\n% matrix.f --- final RHS matrix (after boundary condition)\n\n% Last Modified: 08/07/2020 by Xu Zhang\n\n%% 1. Stiffness Matrix\nS = globMatrixIFE3DStiff(pde.A,mesh,femI,fem,fem);\n% This matrix generator is a little faster than doing it separately.\n% Sx = globMatrixIFE3D(pde.A,mesh,femI,fem,[1,0,0],fem,[1,0,0]);\n% Sy = globMatrixIFE3D(pde.A,mesh,femI,fem,[0,1,0],fem,[0,1,0]);\n% Sz = globMatrixIFE3D(pde.A,mesh,femI,fem,[0,0,1],fem,[0,0,1]);\n% S = Sx+Sy+Sz;\n\n%% 2. Face Matrices\nd1 = 0; j1 = 1; d2 = 1; j2 = 0;\nE = globMatrixIFE3DFace(pde.one, pde.A, fem, fem, femIF, d1,j1, d2,j2);\n\nd1 = 0; j1 = 1; d2 = 0; j2 = 1;\nP = globMatrixIFE3DFace(pde.one, pde.one,fem,fem, femIF, d1,j1, d2,j2);\n\n%% 3. Generate the Right Hand Side Vector\nrhsF = globRHSIFE3D(pde.f, mesh, fem, femI, [0,0,0]);\nrhsE = globRHSIFE3DFace(pde.A, pde.exactu, fem, femIF, 1);\nrhsP = globRHSIFE3DFace(pde.one, pde.exactu, fem, femIF, 0);\n\n%% 4. Dirichlet Boundary Conditions\nif strcmp(PPtype,'N')\n    e = 1; \nelseif strcmp(PPtype,'S')\n    e = -1; \nelseif strcmp(PPtype,'I')\n    e = 0;\nend\nh = mesh.p(2,1) - mesh.p(1,1);\nAtotal = S - E + e*E' + (sig/h)*P;\nrhs = rhsF + e*rhsE + (sig/h)*rhsP;\ntu = feval(pde.gD,fem.p(:,1),fem.p(:,2),fem.p(:,3));\nub = tu;\nub(fem.mapper) = 0;\nrhsB = Atotal*ub;\nA = Atotal(fem.mapper,fem.mapper);\nf = rhs(fem.mapper) - rhsB(fem.mapper);\n\n%% 5. Outputs\nmatrix = struct('A',A,'f',f,'S',S,'E',E,'P',P,'rhsF',rhsF,'rhsE',rhsE,...\n    'rhsP',rhsP);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/genMatEllPPIFE3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5721558150510255}}
{"text": "function centroids = faceCentroids(nodes, faces)\n%FACECENTROIDS Compute centroids of a mesh faces.\n%\n%   NORMALS = faceCentroids(VERTICES, FACES)\n%   VERTICES is a set of 3D points  (as a N-by-3 array), and FACES is\n%   either a N-by-3 index array or a cell array of indices. The function\n%   computes the centroid of each face, and returns a Nf-by-3 array\n%   containing their coordinates.\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%\n%   See also:\n%   meshes3d, drawMesh, faceNormal, convhull, convhulln\n%\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 ''meshFaceCentroids'' instead']);\n\n\nif isnumeric(faces)\n    % trimesh or quadmesh\n    nf = size(faces, 1);\n    centroids = zeros(nf, size(nodes, 2));\n    if size(nodes, 2) == 2\n        % planar case\n        for f = 1:nf\n            centroids(f,:) = polygonCentroid(nodes(faces(f,:), :));\n        end\n    else\n        % 3D case\n        for f = 1:nf\n            centroids(f,:) = polygonCentroid3d(nodes(faces(f,:), :));\n        end\n    end        \nelse\n    % mesh with faces stored as cell array\n    nf = length(faces);\n    centroids = zeros(nf, size(nodes, 2));\n    if size(nodes, 2) == 2\n        % planar case\n        for f = 1:nf\n            centroids(f,:) = polygonCentroid(nodes(faces{f}, :));\n        end\n    else\n        % 3D case\n        for f = 1:nf\n            centroids(f,:) = polygonCentroid3d(nodes(faces{f}, :));\n        end\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/faceCentroids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5720703278391579}}
{"text": "function [post nlZ dnlZ] = infExactWarp(hyp, mean, cov, lik, x, y)\n\n% Exact inference for a GP with Gaussian likelihood. Compute a parametrization\n% of the posterior, the negative log marginal likelihood and its derivatives\n% w.r.t. the hyperparameters. See also \"help infMethods\".\n%\n% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2015-07-13.\n%                                      File automatically generated using noweb.\n%\n% See also INFMETHODS.M.\n\nif iscell(lik), likstr = lik{1}; else likstr = lik; end\nif ~ischar(likstr), likstr = func2str(likstr); end\nif ~strcmp(likstr,'likGaussWarpExact')               % NOTE: no explicit call to likGaussWarpExact\n  error('Exact inference only possible with warped exact Gaussian likelihood');\nend\nwarp = lik{2}; if ischar(warp); warp = str2func(warp); end\n\nng = feval(warp{:});               % number of hyperparameters for the warping function\nnhyp = feval(lik{:});              % number of hyperparameters\n% if nargin<4, varargout = {nhyp}; return, end       % report number of parameters\nnhyp = eval(nhyp);\nif nhyp>length(hyp.lik), error('not enough hyperparameters'), end\n\n[gy,lgpy] = feval(warp{:},y,hyp.lik(1:ng));                     % evaluate warping function\n\n% figure(100); scatter(y,gy); drawnow;\n\n[n, D] = size(x);\nK = feval(cov{:}, hyp.cov, x);                      % evaluate covariance matrix\nm = feval(mean{:}, hyp.mean, x);                    % evaluate mean vector\n[gm,lgpm] = feval(warp{:},m,hyp.lik(1:ng));         % evaluate warped mean\n\nsn2 = exp(2*hyp.lik(end));                          % noise variance of likGauss\nif sn2<1e-6                        % very tiny sn2 can lead to numerical trouble\n  L = chol(K+sn2*eye(n)); sl =   1;   % Cholesky factor of covariance with noise\n  pL = -solve_chol(L,eye(n));                            % L = -inv(K+inv(sW^2))\nelse\n  L = chol(K/sn2+eye(n)); sl = sn2;                       % Cholesky factor of B\n  pL = L;                                           % L = chol(eye(n)+sW*sW'.*K)\nend\nalpha = solve_chol(L,gy-gm)/sl;\n\npost.alpha = alpha;                            % return the posterior parameters\npost.sW = ones(n,1)/sqrt(sn2);                  % sqrt of noise precision vector\npost.L = pL;\n\nif nargout>1                               % do we want the marginal likelihood?\n  nlZ = (gy-gm)'*alpha/2 + sum(log(diag(L))) + n*log(2*pi*sl)/2 - sum(lgpy);   % -log marg lik\n  if nargout>2                                         % do we want derivatives?\n    dnlZ = hyp;                                 % allocate space for derivatives\n    Q = solve_chol(L,eye(n))/sl - alpha*alpha';     % precompute for convenience\n    for i = 1:numel(hyp.cov)\n      dnlZ.cov(i) = sum(sum(Q.*feval(cov{:}, hyp.cov, x, [], i)))/2;\n    end\n    for i = 1:ng\n        [dgy,dlgpy] = feval(warp{:},y,hyp.lik(1:ng),i);\n        dgm = feval(warp{:},m,hyp.lik(1:ng),i);\n        dnlZ.lik(i) = -sum(dlgpy) + (dgy - dgm)'*alpha;\n    end\n    dnlZ.lik(ng+1) = sn2*trace(Q);\n    for i = 1:numel(hyp.mean)\n      dnlZ.mean(i) = -(exp(lgpm)'.*feval(mean{:}, hyp.mean, x, i)')*alpha;\n    end\n  end\n  \nend", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/warp/infExactWarp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.572050766078708}}
{"text": "function mtrPlotCorr(ccFilenameBase,threshVec,paramNames,midP,whichParams,strLineProp)\n% \n% paramNames = {'kLength','kSmooth','kMidSD'};\n% midP = [0 18 0.175];\n\n\nfor pp = 1:length(whichParams)\n    strThreshVec = {};\n    parVecs = [];\n    corrVecs = [];\n    ovrVecs = [];\n    for tt = 1:length(threshVec)\n        cc = load([ccFilenameBase '_thresh_' num2str(threshVec(tt)) '.mat']);\n        ccGrid = mtrCCMatrix2Grid(cc.ccMatrix,cc.paramData,paramNames);\n        indGrid = ones(size(ccGrid,1),1);\n        for ss = 1:length(paramNames)\n            if ss ~= whichParams(pp)\n                indGrid = indGrid & ccGrid(:,ss) == midP(ss);\n            end\n        end\n        subGrid = ccGrid(indGrid,:);\n        [foo, sortI] = sort(subGrid(:,whichParams(pp)));\n        parVecs(:,tt) = subGrid(sortI(:),whichParams(pp));\n        corrVecs(:,tt) = subGrid(sortI(:),4);\n        strThreshVec{tt} = ['Top ' num2str(threshVec(tt))];\n    end\n    if( pp>1 ) figure; end\n    if strcmp(paramNames{whichParams(pp)},'kSmooth')\n        parVecs = asin(sqrt(1./parVecs)).*180./pi;\n        plot(parVecs,corrVecs,strLineProp);\n    else\n        plot(parVecs,corrVecs,strLineProp);\n    end\n    %legend(strThreshVec);\n    xlabel([paramNames{whichParams(pp)} ' parameter']);\n    ylabel('Corr. Coef.');\nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/fiber/tractography/contrack/metrotrac/mtrPlotCorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5720507589044079}}
{"text": "x = [ 1 2 3 4 5 6];\ny = [ 2 6 8 7 8 5];\nstairs(x,y);\ntitle('\\bfExample of a Stair Plot');\nxlabel('\\bf\\itx');\nylabel('\\bf\\ity');\naxis([0 7 0 10]);\n ", "meta": {"author": "101Hub", "repo": "Matlab101", "sha": "07273f68f1147a110443aeb121fa10962234f298", "save_path": "github-repos/MATLAB/101Hub-Matlab101", "path": "github-repos/MATLAB/101Hub-Matlab101/Matlab101-07273f68f1147a110443aeb121fa10962234f298/assets/\u300aMatlab\u7f16\u7a0b\u300b\u6e90\u7801/chap6/stair_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.5720462337591171}}
{"text": "function h = p00_h ( problem, n, x )\n\n%*****************************************************************************80\n%\n%% P00_H evaluates the Hessian for any problem.\n%\n%  Discussion:\n%\n%    H(I,J) = d2 F(X) / dX(I)dX(J)\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    16 October 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer PROBLEM, the problem number.\n%\n%    Input, integer N, the number of variables.\n%\n%    Input, real X(N), the values of the variables.\n%\n%    Output, real H(N,N), the Hessian matrix.\n%\n  if ( problem == 1 )\n    h = p01_h ( n, x );\n  elseif ( problem == 2 )\n    h = p02_h ( n, x );\n  elseif ( problem == 3 )\n    h = p03_h ( n, x );\n  elseif ( problem == 4 )\n    h = p04_h ( n, x );\n  elseif ( problem == 5 )\n    h = p05_h ( n, x );\n  elseif ( problem == 6 )\n    h = p06_h ( n, x );\n  elseif ( problem == 7 )\n    h = p07_h ( n, x );\n  elseif ( problem == 8 )\n    h = p08_h ( n, x );\n  elseif ( problem == 9 )\n    h = p09_h ( n, x );\n  elseif ( problem == 10 )\n    h = p10_h ( n, x );\n  elseif ( problem == 11 )\n    h = p11_h ( n, x );\n  elseif ( problem == 12 )\n    h = p12_h ( n, x );\n  elseif ( problem == 13 )\n    h = p13_h ( n, x );\n  elseif ( problem == 14 )\n    h = p14_h ( n, x );\n  elseif ( problem == 15 )\n    h = p15_h ( n, x );\n  elseif ( problem == 16 )\n    h = p16_h ( n, x );\n  elseif ( problem == 17 )\n    h = p17_h ( n, x );\n  elseif ( problem == 18 )\n    h = p18_h ( n, x );\n  elseif ( problem == 19 )\n    h = p19_h ( n, x );\n  elseif ( problem == 20 )\n    h = p20_h ( n, x );\n  elseif ( problem == 21 )\n    h = p21_h ( n, x );\n  elseif ( problem == 22 )\n    h = p22_h ( n, x );\n  elseif ( problem == 23 )\n    h = p23_h ( n, x );\n  elseif ( problem == 24 )\n    h = p24_h ( n, x );\n  elseif ( problem == 25 )\n    h = p25_h ( n, x );\n  elseif ( problem == 26 )\n    h = p26_h ( n, x );\n  elseif ( problem == 27 )\n    h = p27_h ( n, x );\n  elseif ( problem == 28 )\n    h = p28_h ( n, x );\n  elseif ( problem == 29 )\n    h = p29_h ( n, x );\n  elseif ( problem == 30 )\n    h = p30_h ( n, x );\n  elseif ( problem == 31 )\n    h = p31_h ( n, x );\n  elseif ( problem == 32 )\n    h = p32_h ( n, x );\n  elseif ( problem == 33 )\n    h = p33_h ( n, x );\n  elseif ( problem == 34 )\n    h = p34_h ( n, x );\n  elseif ( problem == 35 )\n    h = p35_h ( n, x );\n  elseif ( problem == 36 )\n    h = p36_h ( n, x );\n  elseif ( problem == 37 )\n    h = p37_h ( n, x );\n  elseif ( problem == 38 )\n    h = p38_h ( n, x );\n  elseif ( problem == 39 )\n    h = p39_h ( n, x );\n  elseif ( problem == 40 )\n    h = p40_h ( n, x );\n  elseif ( problem == 41 )\n    h = p41_h ( n, x );\n  elseif ( problem == 42 )\n    h = p42_h ( n, x );\n  elseif ( problem == 43 )\n    h = p43_h ( n, x );\n  else\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'P00_H - Fatal error!\\n' );\n    fprintf ( 1, '  Illegal value of PROBLEM = %d\\n', problem );\n    error ( ' - 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/test_opt/p00_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5720462322087169}}
{"text": "function [pnt] = elec1020_fraction(cnt1, cnt2, fraction)\n\n% ELEC1020_FRACTION\n\n% Copyright (C) 2003, 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 <http://www.gnu.org/licenses/>.\n\nncnt = size(cnt1,1);\n\n% determine the total length of the contour\ntot_l = 0;\nfor i=1:ncnt\n  tot_l = tot_l + pntdist(cnt1(i,:), cnt2(i,:));\nend\n\nfrac_l = fraction * tot_l;\n\n% propagate along the contour untill we get at the desired fraction\nsum_l = 0;\nfor i=1:ncnt\n  seg_l = pntdist(cnt1(i,:), cnt2(i,:));\n  if (sum_l+seg_l)>=frac_l\n    % the desired point lies on this segment\n    la = frac_l - sum_l;\n    vec = cnt2(i,:)-cnt1(i,:);\n    pnt = cnt1(i,:) + la * vec/norm(vec);\n    return\n  else\n    sum_l = sum_l + seg_l;\n    sum_f = sum_l/tot_l;\n  end\nend\n\npnt = [nan nan nan];\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/private/elec1020_fraction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5720462273027631}}
{"text": "%\n% Copyright (c) 2015, Yarpiz (www.yarpiz.com)\n% All rights reserved. Please read the \"license.txt\" for license terms.\n%\n% Project Code: YPML110\n% Project Title: Implementation of DBSCAN Clustering in MATLAB\n% Publisher: Yarpiz (www.yarpiz.com)\n% \n% Developer: S. Mostapha Kalami Heris (Member of Yarpiz Team)\n% \n% Contact Info: sm.kalami@gmail.com, info@yarpiz.com\n%\n\nfunction PlotClusterinResult(X, IDX)\n    nDim = size(X, 2); \n    k=max(IDX);\n\n    Colors=hsv(k);\n\n    Legends = {};\n    for i=0:k\n        Xi=X(IDX==i,:);\n        if i~=0\n            Style = 'x';\n            MarkerSize = 8;\n            Color = Colors(i,:);\n            Legends{end+1} = ['Cluster #' num2str(i)];\n        else\n            Style = 'o';\n            MarkerSize = 6;\n            Color = [0 0 0];\n            if ~isempty(Xi)\n                Legends{end+1} = 'Noise';\n            end\n        end\n        if ~isempty(Xi)\n            str = sprintf('Id=%02d, Len=%02d', i-1, length(Xi(:, 1))); \n            pt = Xi(1, :); \n            if nDim == 2 \n                text(pt(1), pt(2), str, 'FontSize', 12 ); \n                plot(Xi(:,1),Xi(:,2),Style,'MarkerSize',MarkerSize,'Color',Color);\n            else\n                text(pt(1), pt(2), pt(3), str, 'FontSize', 12 );\n                plot3(Xi(:,1),Xi(:,2),Xi(:, 3), Style,'MarkerSize',MarkerSize,'Color',Color);\n            end\n        end\n        hold on;\n    end\n    hold off;\n    axis equal;\n    grid on;\n    % legend(Legends);\n    % legend('Location', 'NorthEastOutside');\n\nend", "meta": {"author": "DrGabor", "repo": "LiDAR", "sha": "707ca635db955cf00d833578ad1236f0790cdf98", "save_path": "github-repos/MATLAB/DrGabor-LiDAR", "path": "github-repos/MATLAB/DrGabor-LiDAR/LiDAR-707ca635db955cf00d833578ad1236f0790cdf98/iGPR/DBSCAN Clustering/PlotClusterinResult.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.572046222269433}}
{"text": "function [chirpF, Freqs] = bst_chirplet(sRate, nTime, chirpCenterFreqs)\n% BST_CHIRPLET: Compute the Phase-Amplitude Coupling in one of several time series (directPAC)\n%\n% INPUTS:\n%    - sRate  : Signal sampling rate (in Hz)\n%    - nTime  : Number of time points of the signal to filter\n%    - chirpCenterFreqs: Center frequencies of the chirplets to calculate\n%\n% DOCUMENTATION:  \n%    - The current code is inspired from Ryan Canolty's code provided originally with the article:\n%         Canolty RT, Edwards E, Dalal SS, Soltani M, Nagarajan SS, Kirsch HE, Berger MS, Barbaro NM, Knight RT,\n%         \"High gamma power is phase-locked to theta oscillations in human neocortex\",\n%         Science, 2006 Sep 15;313(5793):1626-8.\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: Ryan Canolty, 2006\n%          Sylvain Baillet, 2011-2013\n%          Francois Tadel, 2013\n\n% ===== PARSE INPUTS =====\n% To avoid out-of-memeory issues: Check this on your machine, machine-specific threshold\n% ***** TODO: EVALUALATE THOSE LINES *****\nif (nTime > 2^23)\n    nFreq = nTime;\nelse\n    % Fixed parameter for computational ease\n    nFreq = 2^ceil(log2(nTime)); \nend\n% Raw time_support\nFreqs = (sRate/nFreq) * (0:nFreq-1);\ninds = Freqs > (sRate/2);\nFreqs(inds) = Freqs(inds) - sRate;\n% Reduce storage space\n% % ***** TODO: EVALUALATE THIS LINES *****\n% Freqs = single(Freqs);\n\n% ===== CALCULATE CHIRPLETS =====\n% Initialize returned matrix\nchirpF = zeros(1, nFreq, length(chirpCenterFreqs));\n% Make set of chirplets\nfbw = 0.15; \nfor iif = 1:length(chirpCenterFreqs)\n    % Assign or compute duration parameter\n    v0 = chirpCenterFreqs(iif);  % center_frequency\n    c0 = 0;  % chirp_rate\n    s0 = log((2*log(2)) / (fbw^2*pi*v0^2));\n    % Frequency support\n    std_multiple = 6;\n    vstd = sqrt((exp(-s0) + c0^2*exp(s0)) / (4*pi));\n    v = Freqs; % in Hz\n    iFreq = find(...\n        (v0 - std_multiple * vstd <= v) & ...\n        (v <= v0 + std_multiple * vstd));\n    % Shorten to include only chirplet support\n    v = v(iFreq);\n    % Chirplet in frequency domain: \n    Gk = 2^(1/4)*sqrt(-1i*c0+exp(-s0))^-1 * exp(-s0/4 + (exp(s0)*pi*(v-v0).^2)/(-1+1i*c0*exp(s0)));\n    n1 = sqrt(length(Freqs)) / norm(Gk);\n    % Because of discrete sampling and different time/freq sample numbers\n    Gk = n1 * Gk;  % filter\n    % Report in returned structures\n    chirpF(1, iFreq, iif) = Gk;\nend\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_chirplet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5720293575389135}}
{"text": "\nfunction [D,C]=JDDLDR_UDC(X,trls,lambda_a,lambda_b,D,C,Max_iteration)\n\nnClass = max(trls);\nJstep_T = 1e-3;\n\ndisp_cycle = floor(nClass/10);\nif disp_cycle < 1\n    disp_cycle = 1;\nend\n\nfprintf('Update of D and C: class ');\nfor ci = 1:nClass\n    cdat = X(:,trls==ci);\n    temD = D(ci).M;\n    iteration = 1;\n    while  iteration < Max_iteration\n    % update C\n    afa = inv(temD'*temD+lambda_a*eye(size(temD,2)))*(temD'*cdat);\n    PinvD = inv(temD'*temD+(lambda_a+lambda_b)*eye(size(temD,2)));\n    for tj = 1:10\n%         plot(afa(:,1));title(num2str(tj));pause(1);\n        avg_afa = repmat(mean(afa,2),[1 size(afa,2)]);\n        afa = PinvD*(temD'*cdat+lambda_b*avg_afa);\n    end\n    C(ci).M = afa;\n    \n    % update D\n    for i=1:size(temD,2)\n        ai        =    afa(i,:);\n        Y         =    cdat-temD*afa+temD(:,i)*ai;\n        di        =    Y*ai';\n        di        =    di./norm(di,2);\n        temD(:,i)    =    di;\n    end\n    D(ci).M  = temD;\n    \n    zz            =    cdat-temD*afa;\n    zalpha        =    afa(:);\n    avg_afa       =    repmat(mean(C(ci).M,2),[1 size(C(ci).M,2)]);\n    z_afa         =    afa - avg_afa;\n    Jnow          =    zz(:)'*zz(:)+lambda_a*sum(zalpha(:).*zalpha(:))+lambda_b*sum(z_afa(:).*z_afa(:));\n    iteration     =    iteration+1;\n    end\n    \n    if mod(ci, disp_cycle) == 0\n        fprintf('%03d ', ci);\n    end  \nend\nfprintf('\\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/lib/JDDLDR_PR/utilities/JDDLDR_UDC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5720293479692148}}
{"text": "function [Knots_n] = refine_cubic_grid_2d(Knots, old_spacing, old_vsz, new_spacing, new_vsz, varargin)\n    %[Knots_n] = refine_linear_grid_3d(Knots, old_spacing, ds, volsz,\n    %  {upsampling_type}\n    Nd = size(Knots, 4);\n    \n    upsampling_type = 'sample_std';\n    if nargin >= 6\n        upsampling_type = varargin{1};\n    end\n    \n    ksz_new = ceil(new_vsz(1:Nd) ./ new_spacing(1:Nd)) + 3;\n    k = (old_vsz(1:Nd)) ./ (new_vsz(1:Nd));\n    d = 2 * (1-k);\n    interp_type = 1;\n\n    tmp = cat(3, volresize_kd(squeeze(Knots(:,:,1)), k,d, interp_type), ...\n                 volresize_kd(squeeze(Knots(:,:,2)), k,d, interp_type));\n    if any(size(tmp) < [ksz_new,2])\n        warning('Knots upsampling unexpected behavior');\n        tmp2 = zeros([ksz_new, 2]);\n        szs = min([size(tmp,1), size(tmp,2)], ksz_new);\n        tmp2(1:szs(1), 1:szs(2),  :) = tmp(1:szs(1), 1:szs(2),  :);\n        tmp = tmp2;\n    end\n    Kn = tmp(1:ksz_new(1), 1:ksz_new(2), :);\n   \n    Knots_n = Kn;\n    if strcmp(upsampling_type, 'variation')\n        Tmin = cubic_disp_2d(squeeze(Knots), old_vsz, old_spacing);\n        Tmin_u = cat(3, imresize_my(Tmin(:,:, 1), new_vsz, 1), ...\n                        imresize_my(Tmin(:,:, 2), new_vsz, 1));\n        objf = @(x) align_knots(x, Tmin_u, new_vsz, [ksz_new, 2], new_spacing);\n        uopt = []; uopt.method = 'cg'; \n        uopt.MaxIter = 10; \n        uopt.Corr = 15; \n        uopt.Display = 'off';\n        uopt.DerivativeCheck = 'off';\n        uopt.LS_type = 0; uopt.LS_init = 8;\n        K2 = minFunc(objf, Kn(:), uopt);\n        Knots_n = reshape(K2, [ksz_new, 2]);\n    end\nend\n\n\nfunction [f, gr] = align_knots(K, T, szv, szk, grid_spacing)\n    K = reshape(K, szk);\n    Kx = cubic_disp_2d(K, szv, grid_spacing);\n    df = Kx - T;\n    f = sum(df(:).^2)/2;\n    [gr1, gr2] = cubic_partial_conv_2d(df(:,:, 1), df(:,:, 2), size(K), grid_spacing);\n    gr = [gr1(:); gr2(:)];\nend\n", "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/refine_cubic_grid_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5720293437384594}}
{"text": "function [res] = runsvm(Ks,lk)\n% Copyright 2012 Nino Shervashidze, Karsten Borgwardt\n% runsvm(Ks,lk)\n% K = 1 x h cell array of kernelmatrices (n*n)\n% lk = vector of class labels (n*1)\n% cv = number of folds in cross-validation\n\n% independent scheme\n% best c\n\naddpath('~/code/libsvm');\nn=length(lk) % size of the dataset\n% randomly permute labels: r will be also used for permuting the kernel matrices\nr = randperm(n);\nlk = lk(r);\n\n% specify range of c-values\ncvalues = (10 .^ [-7:2:7]) / size(lk,1);\n\ncv = 10;\np80 = ceil(n * (1-2/cv));\np90 = ceil(n * (1-1/cv));\nfs = n - p90; % fold size\n\n\n% output variables\nres.optkernel=zeros(cv,1);\nres.optc=zeros(cv,1);\nres.accuracy=zeros(cv,1);\n\n% cross-validation loop\nopth=zeros(1,cv);\nfor k = 1:cv\n  imresult=[];\n  \n  height = length(Ks);\n  for h=1:height\n    K = Ks{h}(r,r);\n    K_current = K([k*fs+1:size(K,2),1:(k-1)*fs,(k-1)*fs+1:k*fs],[k*fs+1:size(K,2),1:(k-1)*fs,(k-1)*fs+1:k*fs]);  \n    lk_current = lk([k*fs+1:size(K,2),1:(k-1)*fs,(k-1)*fs+1:k*fs]); \n    K_current = makepos(K_current);\n    K1 = [(1:size(K_current,1))', normalizekm(K_current)];\n    \n    \n    for i = 1:size(cvalues,2)\n      % train on 80%, predict on 10% (from 81% to 90%) \n      size(lk_current(1:p80));\n      size(K1(1:p80,1:p80+1));\n      model = svmtrain(lk_current(1:p80,1), K1(1:p80,1:p80+1), strcat(['-t 4  -c ' num2str(cvalues(i))]));\n      [predict_label, accuracy, dec_values] = svmpredict(lk_current(p80+1:p90,1),K1(p80+1:p90,1:p80+1), model);\n      imresult(h,i)= accuracy(1);\n    end\n  end\n  \n  % determine optimal h and c\n  [junk,position]= max(imresult(:));\n  [optimalh, indoptimalc]=ind2sub(size(imresult),position);\n  \n  opth(k)=optimalh;\n  res.optc(k)= cvalues(indoptimalc);\n  res.optkernel(k)=optimalh;\n  % train on 90% with optimal c, predict on 10% (from 91% to 100%)\n  K = Ks{optimalh}(r,r);\n  K_current = K([k*fs+1:size(K,2),1:(k-1)*fs,(k-1)*fs+1:k*fs],[k*fs+1:size(K,2),1:(k-1)*fs,(k-1)*fs+1:k*fs]);  \n  lk_current = lk([k*fs+1:size(K,2),1:(k-1)*fs,(k-1)*fs+1:k*fs]); \n  K_current = makepos(K_current);\n  K1 = [(1:size(K_current,1))', normalizekm(K_current)];\n  \n  model = svmtrain(lk_current(1:p90,1), K1(1:p90,1:p90+1),strcat(['-t 4  -c ' num2str(cvalues(indoptimalc))]) );\n  [predict_label, accuracy, dec_values] = svmpredict(lk_current(p90+1:size(K,1),1), K1(p90+1:size(K,1),1:p90+1), model);\n  res.accuracy(k)=accuracy(1)\nend\nres.mean_acc =  mean(res.accuracy) \nres.std_acc = std(res.accuracy)\nend\n\n\nfunction result = makepos(K)\npd = 0;\naddc = 10e-7;\nwhile (pd ==  0)\n \naddc = addc * 10\ntry\nif (isinf(addc) == 1)\npd = 1;\nelse \nchol(normalizekm(K + eye(size(K,1),size(K,1)) * addc));\npd = 1;\nend\ncatch\n\nend\n\nend\nif (isinf(addc)==0)\nresult = K + eye(size(K,1),size(K,1)) * addc;\nelse\nresult = eye(size(K,1));\nend\nend\n", "meta": {"author": "muhanzhang", "repo": "DGCNN", "sha": "7d3663b49561e57fe518f37af0023a364285eee1", "save_path": "github-repos/MATLAB/muhanzhang-DGCNN", "path": "github-repos/MATLAB/muhanzhang-DGCNN/DGCNN-7d3663b49561e57fe518f37af0023a364285eee1/software/graphkernels/svm/runsvm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5720293413460348}}
{"text": "function analyticalSolution = analyticalSolutionQP(HessianMatrixQP,gradientQP)\n\n    % ANALYTICALSOLUTIONQP provides the unconstrained solution of a QP\n    %                      problem. To be used as possible alternative when\n    %                      the WBToolbox \"QP block\" fails to find a solution.\n    %                                        \n    % FORMAT: analyticalSolution = analyticalSolutionQP(HessianMatrixQP,gradientQP)\n    %\n    % INPUT:   - HessianMatrixQP = hessian matrix of the QP problem;\n    %          - gradientQP      = gradient of the QP problem.\n    %\n    % OUTPUT:  - analyticalSolution = the analytical solution of the QP problem.\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    analyticalSolution = -inv(HessianMatrixQP)*gradientQP;\nend", "meta": {"author": "robotology", "repo": "whole-body-controllers", "sha": "90ff965a523f0a120e6a8981b71326c1485e7742", "save_path": "github-repos/MATLAB/robotology-whole-body-controllers", "path": "github-repos/MATLAB/robotology-whole-body-controllers/whole-body-controllers-90ff965a523f0a120e6a8981b71326c1485e7742/library/matlab-wbc/+wbc/analyticalSolutionQP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.572029331776336}}
{"text": "function [mu, sigma, sigma_points] = prediction_step(mu, sigma, u)\n% Updates the belief concerning the robot pose according to the motion model.\n% mu: state vector containing robot pose and poses of landmarks obeserved so far\n% Current robot pose = mu(1:3)\n% Note that the landmark poses in mu are stacked in the order by which they were observed\n% sigma: the covariance matrix of the system.\n% u: odometry reading (r1, t, r2)\n% Use u.r1, u.t, and u.r2 to access the rotation and translation values\n\n% For computing lambda.\nglobal scale;\n\n% Compute sigma points\nsigma_points = compute_sigma_points(mu, sigma);\n\n% Dimensionality\nn = length(mu);\n% lambda\nlambda = scale - n;\n\n% TODO: Transform all sigma points according to the odometry command\n% Remember to vectorize your operations and normalize angles\n% Tip: the function normalize_angle also works on a vector (row) of angles\nfor i=1:2*n+1\n    sigma_points(1:3,i) = sigma_points(1:3,i) + [u.t*cos(sigma_points(3,i) + u.r1); u.t*sin(sigma_points(3,i) + u.r1); u.r1 + u.r2];\n    sigma_points(3,i) = normalize_angle(sigma_points(3,i));\nendfor\n% Computing the weights for recovering the mean\nwm = [lambda/scale, repmat(1/(2*scale),1,2*n)];\nwc = wm;\n\n% -------- My initialization ----------- %\nxbar = 0;\nybar = 0;\nmu = zeros(n,1);\nsigma = zeros(n);\n% TODO: recover mu.\n% Be careful when computing the robot's orientation (sum up the sines and\n% cosines and recover the 'average' angle via atan2)\nfor i=1:2*n+1\n    mu = mu + wm(i)*sigma_points(:,i);\n    xbar = xbar + wm(i)*cos(sigma_points(3,i));\n    ybar = ybar + wm(i)*sin(sigma_points(3,i));    \nendfor\nmu(3) = atan2(ybar,xbar);\nmu(3) = normalize_angle(mu(3));\n\n% TODO: Recover sigma. Again, normalize the angular difference\nfor i=1:2*n+1\n    tmp = sigma_points(:,i) - mu;\n    tmp(3) = normalize_angle(tmp(3));\n    sigma = sigma + wc(i)*tmp*tmp';\nendfor\n\n% Motion noise\nmotionNoise = 0.1;\nR3 = [motionNoise, 0, 0; \n     0, motionNoise, 0; \n     0, 0, motionNoise/10];\nR = zeros(size(sigma,1));\nR(1:3,1:3) = R3;\n\n% TODO: Add motion noise to sigma\nsigma = sigma + R;\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/3_UKF_SLAM/octave/prediction_step.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5720293308571706}}
{"text": "function varargout = weights_int(mode, n, t0, Hdyn, Zdyn, Tdyn, Rdyn, Qdyn, Hmat, Zmat, Tmat, Rmat, Qmat, P, tol)\n% mode:\n%   0 - all primitive outputs.\n%   1 - calculate Kalman filter weights.\n%   2 - calculate Kalman smoother weights.\n\n%% Initialization %%\nm       = size(P, 1);\nD       = (P == Inf);\ninit    = any(any(D)); % use exact initialization if init = true.\nif init, d = n+1; P(D) = 0; P_inf = double(D);\nelse d = 0; end\nstationary  = ~Hdyn && ~Zdyn && ~Tdyn && ~Rdyn && ~Qdyn;\nconverged   = false;\nRQdyn       = Rdyn || Qdyn;\nif ~Hdyn, H = Hmat; end\nif ~Zdyn, Z = Zmat; end\nif ~Tdyn, T = Tmat; end\nif ~Rdyn, R = Rmat; end\nif ~Qdyn, Q = Qmat; end\nif ~RQdyn, RQRt = R*Q*R'; end\n\n%% Preallocate Output Results %%\nswitch mode\n    case 0 % all primitive outputs\n        Result_P    = cell(1, n);\n        Result_P{1} = P;\n        Result_invF = cell(1, n);\n        Result_K    = cell(1, n);\n        Result_L    = cell(1, n);\n        Result_N    = cell(1, n);\n        Result_W    = cell(1, n);\n    case 1 % calculate Kalman filter weights\n        Result_K        = cell(1, t0-1);\n        Result_L        = cell(1, t0-1);\n        Result_omega    = cell(1, t0-1);\n    case 2 % calculate Kalman smoother weights\n        Result_invF         = cell(1, n);\n        Result_K            = cell(1, n);\n        Result_L            = cell(1, n);\n        Result_LLasc        = cell(1, n);\n        if t0 > 1, Result_LLasc{t0-1} = eye(m);\n        else Result_P = P; end % t0 == 1\n        Result_omega        = cell(1, t0-1);\n        Result_omegaalpha   = cell(1, n);\nend\nFns     = true(1, n); % Is F_inf nonsingular for each iteration\n\n%% Kalman filter loop %%\nfor t = 1 : n\n    if Hdyn, H = Hmat{t}; end\n    if Zdyn, Z = Zmat{t}; end\n    if Tdyn, T = Tmat{t}; end\n    if Rdyn, R = Rmat{t}; end\n    if Qdyn, Q = Qmat{t}; end\n    if RQdyn, RQRt = R*Q*R'; end\n    if ~converged\n        if init\n            %% Exact initial Kalman filter %%\n            M       = P*Z';\n            M_inf   = P_inf*Z';\n            A_inf   = T*P_inf;\n            if abs(M_inf) < tol % F_inf is zero\n                Fns(t)  = false;\n                invF    = inv(Z*M + H);\n                K       = T*M*invF;\n                L       = T - K*Z;\n                P       = T*P*L' + RQRt;\n                P_inf   = A_inf*T';\n            else % F_inf is assumed to be nonsingular\n                invF    = inv(Z*M_inf); % This is actually invF1\n                F2      = -invF*(Z*M + H)*invF;\n                K       = T*M_inf*invF;\n                K1      = T*(M*invF + M_inf*F2);\n                L       = T - K*Z;\n                L1      = -K1*Z;\n                P       = A_inf*L1' + T*P*L' + RQRt;\n                P_inf   = A_inf*L';\n            end\n            if abs(P_inf) < tol, d=t; init=false; end\n        else\n            %% Normal Kalman filter %%\n            M       = P*Z';\n            invF    = inv(Z*M + H);\n            K       = T*M*invF;\n            L       = T - K*Z;\n            prevP   = P;\n            P       = T*P*L' + RQRt;\n            if stationary, if abs(P-prevP) < tol, converged = true; end, end\n        end\n    end\n    %% Store results for this time point %%\n    switch mode\n        case 0 % all primitive outputs\n            Result_P{t+1}   = P;\n            Result_invF{t}  = invF;\n            Result_K{t}     = K;\n            Result_L{t}     = L;\n        case 1 % calculate Kalman filter weights\n            Result_K{t}     = K;\n            Result_L{t}     = L;\n            if t >= t0 - 1, break; end\n        case 2 % calculate Kalman smoother weights\n            if t == t0 - 1, Result_P    = P; end\n            if t == t0, Result_LLasc{t} = L'; end\n            Result_invF{t}  = invF;\n            Result_K{t}     = K;\n            Result_L{t}     = L;\n            if t > t0\n                Result_LLasc{t} = Result_LLasc{t-1}*L';\n            end\n    end\nend\n\n%% Backwards recursion %%\nswitch mode\n    case 0 % all primitive outputs\n        N       = zeros(m);\n        for t = n : -1 : 1\n            if Hdyn, H = Hmat{t}; end\n            if Zdyn, Z = Zmat{t}; end\n            invF        = Result_invF{t};\n            K           = Result_K{t};\n            L           = Result_L{t};\n            Result_W{t} = H*(invF*Z - K'*N*L);\n            Result_N{t} = N;\n            if t <= d && Fns(t), N = L'*N*L; else N = Z'*invF*Z + L'*N*L; end\n        end\n    case 1 % calculate Kalman filter weights\n        LLdsc   = eye(m);\n        for t = t0-1 : -1 : 1\n            Result_omega{t} = LLdsc*Result_K{t};\n            LLdsc           = LLdsc*Result_L{t};\n        end\n    case 2 % calculate Kalman smoother weights\n        N       = zeros(m);\n        LLdsc   = eye(m);\n        for t = n : -1 : 1\n            if t >= t0\n                if t <= d && Fns(t)\n                    K       = Result_K{t};\n                    L       = Result_L{t};\n                    W2      = -K'*N*L;\n                    N       = L'*N*L;\n                else\n                    if Zdyn, Z = Zmat{t}; end\n                    invF    = Result_invF{t};\n                    K       = Result_K{t};\n                    L       = Result_L{t};\n                    W2      = invF*Z - K'*N*L;\n                    N       = Z'*invF*Z + L'*N*L;\n                end\n                if t == t0\n                    Result_omegaalpha{t} = Result_P*W2';\n                    IPN = eye(m) - Result_P*N;\n                else Result_omegaalpha{t} = Result_P*Result_LLasc{t-1}*W2'; end\n            else\n                Result_omega{t}         = LLdsc*Result_K{t};\n                LLdsc                   = LLdsc*Result_L{t};\n                Result_omegaalpha{t}    = IPN*Result_omega{t};\n            end\n        end\nend\n\n%% Output Results %%\nswitch mode\n    case 0 % all primitive outputs\n        varargout = {Result_P Result_invF Result_K Result_L Result_W Result_N};\n    case 1 % calculate Kalman filter weights\n        varargout = {Result_omega};\n    case 2 % calculate Kalman smoother weights\n        varargout = {Result_omega Result_omegaalpha};\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/ssm-1.0.1/ssm-release/@ssmodel/private/weights_int.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5720293269914863}}
{"text": "function value = r8_gamma ( x )\n\n%*****************************************************************************80\n%\n%% R8_GAMMA evaluates Gamma(X) for a real argument.\n%\n%  Discussion:\n%\n%    This routine calculates the gamma function for a real argument X.\n%\n%    Computation is based on an algorithm outlined in reference 1.\n%    The program uses rational functions that approximate the gamma\n%    function to at least 20 significant decimal digits.  Coefficients\n%    for the approximation over the interval (1,2) are unpublished.\n%    Those for the approximation for 12 <= X are from reference 2.\n%\n%    MATLAB provides a GAMMA function, which is likely to be faster, more\n%    accurate, and which vectorizes.  \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%    Original FORTRAN77 version by William Cody, Laura Stoltz.\n%    MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    William Cody,\n%    An Overview of Software Development for Special Functions,\n%    in Numerical Analysis Dundee, 1975,\n%    edited by GA Watson,\n%    Lecture Notes in Mathematics 506,\n%    Springer, 1976.\n%\n%    John Hart, Ward Cheney, Charles Lawson, Hans Maehly,\n%    Charles Mesztenyi, John Rice, Henry Thatcher,\n%    Christoph Witzgall,\n%    Computer Approximations,\n%    Wiley, 1968,\n%    LC: QA297.C64.\n%\n%  Parameters:\n%\n%    Input, real X, the argument of the function.\n%\n%    Output, real VALUE, the value of the function.\n%\n\n%\n%  Coefficients for minimax approximation over (12, INF).\n%\n  c = [ ...\n   -1.910444077728E-03, ...\n    8.4171387781295E-04, ...\n   -5.952379913043012E-04, ...\n    7.93650793500350248E-04, ...\n   -2.777777777777681622553E-03, ...\n    8.333333333333333331554247E-02, ...\n    5.7083835261E-03 ];\n%\n%  Mathematical constants\n%\n  sqrtpi = 0.9189385332046727417803297;\n%\n%  Machine dependent parameters\n%\n  xbig = 171.624E+00;\n  xminin = 2.23E-308;\n  eps = 2.22E-16;\n  xinf = 1.79E+308;\n%\n%  Numerator and denominator coefficients for rational minimax\n%  approximation over (1,2).\n%\n  p = [ ...\n   -1.71618513886549492533811E+00, ...\n    2.47656508055759199108314E+01, ...\n   -3.79804256470945635097577E+02, ...\n    6.29331155312818442661052E+02, ...\n    8.66966202790413211295064E+02, ...\n   -3.14512729688483675254357E+04, ...\n   -3.61444134186911729807069E+04, ...\n    6.64561438202405440627855E+04 ];\n\n  q = [ ...\n   -3.08402300119738975254353E+01, ...\n    3.15350626979604161529144E+02, ...\n   -1.01515636749021914166146E+03, ...\n   -3.10777167157231109440444E+03, ...\n    2.25381184209801510330112E+04, ...\n    4.75584627752788110767815E+03, ...\n   -1.34659959864969306392456E+05, ...\n   -1.15132259675553483497211E+05 ];\n\n  parity = 0;\n  fact = 1.0;\n  n = 0;\n  y = x;\n%\n%  Argument is negative.\n%\n  if ( y <= 0.0 )\n\n    y = - x;\n    y1 = floor ( y );\n    res = y - y1;\n\n    if ( res ~= 0.0 )\n\n      if ( y1 ~= floor ( y1 * 0.5 ) * 2.0 )\n        parity = 1;\n      end\n\n      fact = - pi / sin ( pi * res );\n      y = y + 1.0;\n\n    else\n\n      res = xinf;\n      value = res;\n      return\n\n    end\n\n  end\n%\n%  Argument is positive.\n%\n  if ( y < eps )\n%\n%  Argument < EPS.\n%\n    if ( xminin <= y )\n      res = 1.0 / y;\n    else\n      res = xinf;\n      value = res;\n      return\n    end\n\n  elseif ( y < 12.0 )\n\n    y1 = y;\n%\n%  0.0 < argument < 1.0.\n%\n    if ( y < 1.0 )\n\n      z = y;\n      y = y + 1.0;\n%\n%  1.0 < argument < 12.0.\n%  Reduce argument if necessary.\n%\n    else\n\n      n = floor ( y ) - 1;\n      y = y - n;\n      z = y - 1.0;\n\n    end\n%\n%  Evaluate approximation for 1.0 < argument < 2.0.\n%\n    xnum = 0.0;\n    xden = 1.0;\n    for i = 1 : 8\n      xnum = ( xnum + p(i) ) * z;\n      xden = xden * z + q(i);\n    end\n\n    res = xnum / xden + 1.0;\n%\n%  Adjust result for case  0.0 < argument < 1.0.\n%\n    if ( y1 < y )\n\n      res = res / y1;\n%\n%  Adjust result for case 2.0 < argument < 12.0.\n%\n    elseif ( y < y1 )\n\n      for i = 1 : n\n        res = res * y;\n        y = y + 1.0;\n      end\n\n    end\n\n  else\n%\n%  Evaluate for 12.0 <= argument.\n%\n    if ( y <= xbig )\n\n      ysq = y * y;\n      sum = c(7);\n      for i = 1 : 6\n        sum = sum / ysq + c(i);\n      end\n      sum = sum / y - y + sqrtpi;\n      sum = sum + ( y - 0.5 ) * log ( y );\n      res = exp ( sum );\n\n    else\n\n      res = xinf;\n      value = res;\n      return\n\n    end\n\n  end\n%\n%  Final adjustments and return.\n%\n  if ( parity )\n    res = - res;\n  end\n\n  if ( fact ~= 1.0 )\n    res = fact / res;\n  end\n\n  value = res;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/laguerre_polynomial/r8_gamma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5720238905946395}}
{"text": "function [y,mask] = vl_nndropout(x,varargin)\n%VL_NNDROPOUT CNN dropout.\n%   [Y,MASK] = VL_NNDROPOUT(X) applies dropout to the data X. MASK\n%   is the randomly sampled dropout mask. Both Y and MASK have the\n%   same size as X.\n%\n%   VL_NNDROPOUT(X, 'rate', R) sets the dropout rate to R.\n%\n%   [DZDX] = VL_NNDROPOUT(X, DZDY, 'mask', MASK) computes the\n%   derivatives of the blocks projected onto DZDY. Note that MASK must\n%   be specified in order to compute the derivative consistently with\n%   the MASK randomly sampled in the forward pass. DZDX and DZDY have\n%   the same dimesnions as X and Y respectivey.\n%\n%   Note that in the original paper on dropout, at test time the\n%   network weights for the dropout layers are scaled down to\n%   compensate for having all the neurons active. In this\n%   implementation the dropout function itself already does this\n%   compensation during training. So at test time no alterations are\n%   required.\n\n% Copyright (C) 2014-15 Andrea Vedaldi.\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\nopts.rate = 0.5 ;\nopts.mask = [] ;\n\nbackMode = numel(varargin) > 0 && ~isstr(varargin{1}) ;\nif backMode\n  dzdy = varargin{1} ;\n  opts = vl_argparse(opts, varargin(2:end)) ;\nelse\n  opts = vl_argparse(opts, varargin) ;\nend\n\n% determine mask\nmask = opts.mask ;\nscale = single(1 / (1 - opts.rate)) ;\nif backMode && isempty(mask)\n  warning('vl_nndropout: when using in backward mode, the mask should be specified') ;\nend\nif isempty(mask)\n  if isa(x,'gpuArray')\n    mask = scale * single(gpuArray.rand(size(x)) >= opts.rate) ;\n  else\n    mask = scale * single(rand(size(x)) >= opts.rate) ;\n  end\nend\n\n% do job\nif ~backMode\n  y = mask .* x ;\nelse\n  y = mask .* dzdy ;\nend\n", "meta": {"author": "willard-yuan", "repo": "cnn-for-image-retrieval", "sha": "2e3e8ab76e2c971314be55b5ae44e02884003261", "save_path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval/cnn-for-image-retrieval-2e3e8ab76e2c971314be55b5ae44e02884003261/matconvnet-1.0-beta17/matlab/vl_nndropout.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5720238855789685}}
{"text": "%% This file is the main file of camparing the noise sensitivity of iSINDy\n% and SINDy-PI method. This file takes a long time to run.\n%\n% Last Update: 2019/07/17\n% Coded By: K\n\n%% Close all, clear all, clc\nclose all;clear all; clc;\naddpath('./Functions')\naddpath('Datas')\nset(0,'defaulttextInterpreter','latex')\n%% Simulate the budworm population growth and gather the simulation data\n\n% Define the system parameters\njx=0.6;Vmax=1.5;Km=0.3;\n\n% Determine the simulation time step and time span\ndt=0.1; T=5; tspan=0:dt:T;\n\n% Define noise level and add gaussian noise to the data\nnoise=0;\n\n% Define whehter you have control, if you have it, please define it\nControl=0;u=0;\n\n%Define whether you want to shuffel the final data\nShuffle=0;\n\n%% Set up some parameters\n% Get the number of states we have\nn_state=1;\n\n% Define the control input(Should be zero in our example)\nn_control=0;\n\n% Choose whether you want to display actual ODE or not\ndisp_actual_ode=1;\n\n% If the ODEs you want to display is the actual underlyting dynamics of the\n% system, please set actual as 1\nactual=1;\n\n% Print the actual ODE we try to discover\nPrint_ODEs(@(t,y)MMK_ODE(t,y,jx,Vmax,Km),n_state,n_control,disp_actual_ode,actual);\n\n% Create symbolic states\ndz=sym('dz',[n_state,1]);\n\n% Now we first create the parameters of the function right hand side\nHighest_Poly_Order_Guess=1;\nHighest_Trig_Order_Guess=0;\nHighest_U_Order_Guess=0;\n\n% Then create the right hand side library parameters\nHighest_Poly_Order=4;\nHighest_Trig_Order=0;\nHighest_U_Order=0;\nHighest_dPoly_Order=1;\n\n% Determine whether you want to normalize your libary or not. 1 is yes and\n% 0 is no.\nNormalizeLib=0;\n\n% Determine the model selection method\nModel_Selection_Method=1;\n% Determine the prediction step\nPrediction_Steps=0;\n\n% The follwoing parameters will determine the for loop and loop through the\n% different noise level\nd_percent=1;\npercent=0;\npercent_start=1;\n% Must be smaller or equal to 24\npercent_end=24;\n\n% Determine a vector to store whether SINDy-PI identification is correct\nis_Right=zeros(percent_end-percent_start+1,1);\n\n% Define a matrix to store the null space vector\nXi_ns=cell(percent_end-percent_start+1,1);\n\n% Turn off the rank deficient warning\nMSGID='MATLAB:rankDeficientMatrix';\nwarning('off',MSGID);\n\n% Determine how many iteration you need\nFinal_pin=30;\n\n% Choose which denoise method you want:\n% 1 is adding Guassian noise to actual derivative, 2 is direct\n% finite difference, 3 is TVRegDiff.\nNoisy_Data_Generation_Method=3;\n\n% Determine how many initial conditions you need\ninit_num=2400;\n\n% Create the new directory to save the function files\nFolderName=strcat('Result_i_SINDy_Derivative_Method',num2str(Noisy_Data_Generation_Method),'_PridictionStep_',num2str(Prediction_Steps),'_IniNum_',num2str(init_num));\n[fld_status, fld_msg, fld_msgID]=mkdir('TempFunctions_iSINDy');\n[fld_status, fld_msg, fld_msgID]=mkdir(FolderName);\naddpath('TempFunctions_iSINDy')\n\n\n%% Now calculate the sensitivity of the iSINDy and SINDy-PI to the noise.\n\n% Print the start process\nfprintf('Start calculating ....\\n\\n\\n')\n\nfor total=1:Final_pin\n    percent=0;\n    \n    for percent_iter=percent_start:d_percent:percent_end\n        % Set the pin one step forward\n        percent=percent+1;\n        \n        % Set the noise level\n        noise_level(percent,1)=Determine_Noise_Level(percent_iter);\n        \n        % Print the current noise level\n        fprintf('Using the noise level as %i on implicit-SINDy.\\n',noise_level(percent,1))\n        \n        % Read files, load the training data and testing data\n        File_Name=strcat('Data_Iter_',num2str(total),'_NoiseLevel_',num2str(noise_level(percent,1)),'_NoiseMethod_',num2str(Noisy_Data_Generation_Method),'_GoodLuck.mat');\n        load(File_Name)\n        [size1,size2]=size(xt_test);\n        \n        %% Run implicit-SINDy (some function in this section is obtained from the github code iSINDy )\n        fprintf('\\n\\n\\n\\n USing implicit-SINDy now...\\n')\n        \n        % Sweep through the states\n        %tic\n        for iter=1:n_state\n            fprintf('\\n \\n Calculating the %i expression...\\n',iter)\n            \n            % Build library data\n            [iSINDy_Data,iSINDy_Struct]=SINDyLib(Data,dData(:,iter),u,Highest_Poly_Order,Highest_Trig_Order,Highest_U_Order,Highest_dPoly_Order);\n            \n            % Use Null-Space method and set the tolerance\n            tol = 1e-5;\n            \n            % Plotting option\n            pflag=0;\n            \n            % Print process\n            fprintf('\\n \\n \\t Calculating the null space...\\n')\n            try\n                % Sparse Regression\n                [Xi_ns{percent,1}, indTheta, lambdavec, numterms, errorv] = ADMpareto(iSINDy_Data, tol, pflag);\n                Xi_dum=zeros(10,28);\n                Xi_dum=Xi_ns{percent,1};\n                %Define the variable to store the ODE expression and score of each\n                % expression. This is necessary to perform the parallel for loop.\n                ODEs_iS=cell(n_state,size(Xi_dum,2)-1);\n                if percent==1 && iter==1\n                    Score_iS=NaN*ones(percent_end-percent_start+1,size(Xi_dum,2)-1);\n                end\n                dz_dum=dz(iter);\n                \n                % Sweep the null space and store the score\n                parfor j=1:(size(Xi_dum,2)-1)\n                    \n                    % Print which vector we are working on\n                    fprintf('\\t\\t Sweeping the %i null sapce vector...\\n',j)\n                    \n                    % Validate each sparse vector\n                    try\n                        % Solve for the ODE expression\n                        ODEs_iS{iter,j}=solve(vpa(cell2sym(iSINDy_Struct)*Xi_dum(:,j))==0,dz_dum);\n                        \n                        % Store the previous result into a matrix\n                        Generate_ODE_RHS(ODEs_iS{iter,j},n_state,n_control,strcat('TempFunctions_iSINDy/ParForiS',num2str(j)));\n                        \n                        % Calculate the accuracy of the file\n                        Test_Score=0;\n                        Test_Score=Get_Score(dxt_test,xt_test,u,Control,tspan,Shuffle,strcat('ParForiS',num2str(j)),Prediction_Steps,dt,size1,size2,Model_Selection_Method);\n                        Score_iS(percent,j)=Test_Score;\n                    catch\n                        ODEs_iS{iter,j}=NaN;\n                        Score_iS(percent,j)=NaN;\n                    end\n                end\n            catch\n                fprintf('\\n\\t\\t\\tSomething is wrong....\\n')\n            end\n            \n        end\n        \n    end\n    \n    % Store the result for this iteration\n    \n    % Store the minimum of implicit SINDy\n    for pin1=1:size(Score_iS,1)\n        [min_iS_Val(total,pin1),Index1(total,pin1)]=min(Score_iS(pin1,:));\n        \n    end\n    \n    % Test whether the correct structure is identified\n    for pin1=1:size(Score_iS,1)\n        Xi_dum=Xi_ns{pin1,1};\n        Coffs=Xi_dum(:,Index1(total,pin1));\n        Coffs_dum=Coffs~=0;\n        if Coffs_dum==[1;1;0;0;0;1;1;0;0;0]\n            is_Right(pin1,1)=is_Right(pin1,1)+1;\n            Coffs_norm=Coffs/Coffs(7);\n            Coffs_error(total,pin1)=norm(Coffs_norm-[-0.18;0.9;0;0;0;0.3;1;0;0;0]);\n        elseif Coffs_dum==[0;1;1;0;0;0;1;1;0;0]\n            is_Right(pin1,1)=is_Right(pin1,1)+1;\n            Coffs_norm=Coffs/Coffs(8);\n            Coffs_error(total,pin1)=norm(Coffs_norm-[0;-0.18;0.9;0;0;0;0.3;1;0;0]);\n        elseif Coffs_dum==[0;0;1;1;0;0;0;1;1;0]\n            is_Right(pin1,1)=is_Right(pin1,1)+1;\n            Coffs_norm=Coffs/Coffs(9);\n            Coffs_error(total,pin1)=norm(Coffs_norm-[0;0;-0.18;0.9;0;0;0;0.3;1;0]);\n        elseif Coffs_dum==[0;0;0;1;1;0;0;0;1;1]\n            is_Right(pin1,1)=is_Right(pin1,1)+1;\n            Coffs_norm=Coffs/Coffs(10);\n            Coffs_error(total,pin1)=norm(Coffs_norm-[0;0;0;-0.18;0.9;0;0;0;0.3;1]);\n        end\n    end\n    \n    for pin1=1:size(Score_iS,1)\n        try\n            Num=sum(Coffs_error(:,pin1)~=0);\n            Ave_Coff_Error(pin1,1)=sum(Coffs_error(:,pin1))/Num;\n        catch\n            Ave_Coff_Error(pin1,1)=NaN;\n        end\n    end\n    \n    %% Plot the result\n    figure(1)\n    plot(noise_level,log(1+mean(min_iS_Val,1)),'o','linewidth',2,'color','blue')\n    drawnow\n    grid on\n    title('Peformance Comparison','FontSize',18)\n    xlabel('Noise Level $\\sigma$','FontSize', 18)\n    ylabel('Average L2 Norm','FontSize', 18)\n    set(gca,'FontSize',18);\n    set(gcf,'Position',[100 100 600 400]);\n    set(gcf,'PaperPositionMode','auto');\n    \n    figure(2)\n    plot(noise_level,is_Right/total,'o')\n    drawnow\n    grid on\n    title('Success Rate','FontSize',18)\n    xlabel('Noise Level $\\sigma$','FontSize', 18)\n    ylabel('Success Rate','FontSize', 18)\n    ylim([0 1])\n    set(gca,'FontSize',18);\n    set(gcf,'Position',[100 100 600 400]);\n    set(gcf,'PaperPositionMode','auto');\n    set(gca, 'XScale', 'log')\n    \n    figure(3)\n    plot(noise_level,Ave_Coff_Error,'o')\n    drawnow\n    grid on\n    title('Average Parameter Error','FontSize',18)\n    xlabel('Noise Level $\\sigma$','FontSize', 18)\n    ylabel('L2 norm','FontSize', 18)\n    ylim([0 total])\n    set(gca,'FontSize',18);\n    set(gcf,'Position',[100 100 600 400]);\n    set(gcf,'PaperPositionMode','auto');\n    set(gca, 'XScale', 'log')\n    \n    % Save the calculation result of current iteration\n    cc=clock;\n    ResultName=strcat(FolderName,'/implicit_SINDY_Result',num2str(total),'__',num2str(cc(3)),'_',num2str(cc(4)),'_',num2str(cc(5)),'_',num2str(round(cc(6))),'.mat');\n    save(ResultName,'Score_iS','Xi_ns')\n    \nend\n\n\n\n\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Comparison/NoiseSensitivity/Michaelis-Menten kinetics/MMK_Noise_implicit_SINDy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.572023884132865}}
{"text": "% OP_SU_EV_TP: assemble the matrix A = [a(i,j)], a(i,j) = 1/2 (sigma (u_j), epsilon (v_i)), exploiting the tensor product structure.\n%\n%   mat = op_su_ev_tp (spu, spv, msh, lambda, mu);\n%   [rows, cols, values] = op_su_ev_tp (spu, spv, msh, lambda, mu);\n%\n% INPUT:\n%    \n%   spu:     object representing the space of trial functions (see sp_vector)\n%   spv:     object representing the space of test functions (see sp_vector)\n%   msh:     object that defines the domain partition and the quadrature rule (see msh_cartesian)\n%   lambda, mu: function handles to compute the Lame' coefficients\n%\n% OUTPUT:\n%\n%   mat:    assembled matrix\n%   rows:   row indices of the nonzero entries\n%   cols:   column indices of the nonzero entries\n%   values: values of the nonzero entries\n% \n% Copyright (C) 2011, 2017 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 <http://www.gnu.org/licenses/>.\n\nfunction varargout = op_su_ev_tp (space1, space2, msh, lambda, mu)\n\n  for icomp = 1:space1.ncomp_param\n    for idim = 1:msh.ndim\n      size1 = size (space1.scalar_spaces{icomp}.sp_univ(idim).connectivity);\n      size2 = size (space2.scalar_spaces{icomp}.sp_univ(idim).connectivity);\n      if (size1(2) ~= size2(2) || size1(2) ~= msh.nel_dir(idim))\n        error ('One of the discrete spaces is not associated to the mesh')\n      end\n    end\n  end\n\n  A = spalloc (space2.ndof, space1.ndof, 5*space1.ndof);\n\n  for iel = 1:msh.nel_dir(1)\n    msh_col = msh_evaluate_col (msh, iel);\n    sp1_col = sp_evaluate_col (space1, msh_col, 'value', false, ...\n                               'gradient', true, 'divergence', true);\n    sp2_col = sp_evaluate_col (space2, msh_col, 'value', false, ...\n                               'gradient', true, 'divergence', true);\n\n    for idim = 1:msh.rdim\n      x{idim} = reshape (msh_col.geo_map(idim,:,:), msh_col.nqn, msh_col.nel);\n    end\n\n    A = A + op_su_ev (sp1_col, sp2_col, msh_col, lambda (x{:}), mu (x{:}));\n  end\n\n  if (nargout == 1)\n    varargout{1} = A;\n  elseif (nargout == 3)\n    [rows, cols, vals] = find (A);\n    varargout{1} = rows;\n    varargout{2} = cols;\n    varargout{3} = vals;\n  end\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_vector/op_su_ev_tp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.572023879117194}}
{"text": "%--- help for arima/simulate ---\n%\n% SIMULATE Simulate ARIMA model responses and conditional variances\n% \n%  Syntax:\n% \n%    [Y,E,V] = simulate(Mdl,numObs)\n%    [Y,E,V] = simulate(Mdl,numObs,param1,val1,param2,val2,...)\n% \n%  Description:\n% \n%    Simulate sample paths of responses, innovations, and conditional \n%    variances of a univariate ARIMA process.\n% \n%  Input Arguments:\n% \n%    Mdl - ARIMA model specification object, as produced by the ARIMA \n%      constructor or ARIMA/ESTIMATE method.\n% \n%    numObs - Positive integer indicating the number of observations (rows)\n%      generated for each path of the outputs Y, E, and V.\n% \n%  Optional Input Parameter Name/Value Pairs:\n% \n%    'NumPaths'   Positive integer indicating the number of sample paths \n%                 (columns) generated for all simulated outputs. The default \n%                 is 1.\n% \n%    'Y0'         Presample response data, providing initial values for the \n%                 model. Y0 is a column vector or a matrix. If Y0 is a \n%                 column vector, then it is applied to each simulated path. \n%                 If Y0 is a matrix, then it must have at least NumPaths \n%                 columns. Y0 may have any number of rows, provided at least \n%                 Mdl.P observations exist to initialize the model. If the\n%                 number of rows exceeds Mdl.P, then only the most recent \n%                 Mdl.P observations are used. If the number of columns \n%                 exceeds NumPaths, then only the first NumPaths columns are \n%                 used. If Y0 is unspecified, any necessary presample \n%                 observations are set to the unconditional mean for stationary \n%                 AR processes, and to zero if the process is non-stationary \n%                 or contains a regression component. The last row contains \n%                 the most recent observation.\n% \n%    'E0'         Mean-zero presample innovations, providing initial values \n%                 for the model. E0 is a column vector or a matrix. If E0 is \n%                 a column vector, then it is applied to each simulated path. \n%                 If E0 is a matrix, then it must have at least NumPaths\n%                 columns. E0 may have any number of rows, provided sufficient \n%                 observations exist to initialize the ARIMA model as well \n%                 as any conditional variance model (the number of observations\n%                 required is at least Mdl.Q, but may be more if a conditional \n%                 variance model is included). If the number of rows \n%                 exceeds the number necessary, then only the most recent \n%                 observations are used. If the number of columns exceeds \n%                 NumPaths, then only the first NumPaths columns are used. If\n%                 no presample data is specified, any necessary observations \n%                 are set to zero. The last row contains the most recent \n%                 observation.\n% \n%    'V0'         Positive presample conditional variances, providing initial\n%                 values for any conditional variance model; if the variance \n%                 of the model is constant, then V0 is unnecessary. V0 is a \n%                 column vector or a matrix. If V0 is a column vector, then \n%                 it is applied to each simulated path. If V0 is a matrix, \n%                 then it must have at least NumPaths columns. V0 may have \n%                 any number of rows, provided sufficient observations exist \n%                 to initialize any conditional variance model. If the number \n%                 of rows exceeds the number necessary, then only the most \n%                 recent observations are used. If the number of columns \n%                 exceeds NumPaths, then only the first NumPaths columns are \n%                 used. If no presample variance data is specified, any \n%                 necessary observations are set to the unconditional variance \n%                 of the conditional variance process. The last row contains \n%                 the most recent observation.\n% \n%    'X'          Matrix of predictor data used to include a regression \n%                 component in the conditional mean. Each column of X is a\n%                 separate time series, and the last row of each contains\n%                 the most recent observation of each series. The number of\n%                 observations in X must equal or exceed numObs. When the \n%                 number of observations in X exceeds numObs, only the most \n%                 recent observations are used. If missing, the conditional \n%                 mean will have no regression component regardless of the \n%                 presence of any regression coefficients found in the model.\n% \n%  Output Arguments:\n% \n%    Y - numObs-by-NumPaths matrix of simulated response data.\n% \n%    E - numObs-by-NumPaths matrix of simulated mean-zero innovations. \n% \n%    V - numObs-by-NumPaths matrix of conditional variances of the \n%      innovations in E.\n% \n%  Notes:\n% \n%    o Missing data values, indicated by NaNs, are removed from X by listwise \n%      deletion (i.e., any row in X with at least one NaN is removed), reducing\n%      the effective sample size. The presample data Y0, E0, and V0 are merged\n%      into a composite series, and any row of the combined series with at \n%      least one NaN is also removed by listwise deletion. The presample data \n%      is also synchronized such that the last (most recent) observation of \n%      each series occurs at the same time.\n% \n%   o  Regression models included in the conditional mean are based on the\n%      presence of the predictor matrix X. Although each column of the output \n%      time series represents a different path of the corresponding univariate \n%      stochastic process, the regression matrix X represents as a single \n%      path of a (possibly) multivariate time series matrix in which each \n%      column is a different time series. When the conditional mean has a \n%      regression component, the entire predictor matrix X is applied to \n%      every column of the output time series. \n% \n%  References:\n% \n%    [1] Box, G. E. P., G. M. Jenkins, and G. C. Reinsel. Time Series\n%        Analysis: Forecasting and Control. 3rd edition. Upper Saddle River,\n%        NJ: Prentice-Hall, 1994.\n% \n%    [2] Enders, W. Applied Econometric Time Series. Hoboken, NJ: John Wiley\n%        & Sons, 1995.\n% \n%    [3] Hamilton, J. D. Time Series Analysis. Princeton, NJ: Princeton\n%        University Press, 1994.\n% \n%  See also ARIMA, FORECAST, ESTIMATE, INFER, FILTER.\n%\n%    Reference page in Doc Center\n%       doc arima/simulate\n%\n%    Other functions named simulate\n%\n%       conjugateblm/simulate    generic/simulate\n%       customblm/simulate       gjr/simulate\n%       diffuseblm/simulate      regARIMA/simulate\n%       dsge/simulate            sde/simulate\n%       dtmc/simulate            semiconjugateblm/simulate\n%       egarch/simulate          ssm/simulate\n%       empiricalblm/simulate    varm/simulate\n%       garch/simulate           vecm/simulate\n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/classes/models/+vartools/simulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.572023874101523}}
{"text": "function seed = latin_center_test01 ( seed )\n\n%*****************************************************************************80\n%\n%% LATIN_CENTER_TEST01 tests LATIN_CENTER.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 April 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer SEED, an initial seed for the random number generator.\n%\n%    Output, integer SEED, the updated random number seed.\n%\n  dim_num = 2;\n  point_num = 10;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST01\\n' );\n  fprintf ( 1, '  LATIN_CENTER chooses a Latin cell arrangement,\\n' );\n  fprintf ( 1, '  and returns the centers of those cells.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Spatial dimension = %d\\n', dim_num );\n  fprintf ( 1, '  Number of points =  %d\\n', point_num );\n  fprintf ( 1, '  Using seed = %d\\n', seed );\n\n  [ x, seed ] = latin_center ( dim_num, point_num, seed );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The Latin center points:\\n' );\n  fprintf ( 1, '\\n' );\n\n  for j = 1: point_num\n    for i = 1: dim_num\n      fprintf ( 1, '%10f  ', x(i,j) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/latin_center/latin_center_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.572018859132223}}
{"text": "%% Copyright (C) 2016 Lagu\n%% Copyright (C) 2016, 2018-2019, 2022 Colin B. Macdonald\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see <http://www.gnu.org/licenses/>.\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @deftypemethod  @@sym {[@var{A}, @var{b}] =} equationsToMatrix (@var{eqns}, @var{vars})\n%% @deftypemethodx @@sym {[@var{A}, @var{b}] =} equationsToMatrix (@var{eqns})\n%% @deftypemethodx @@sym {[@var{A}, @var{b}] =} equationsToMatrix (@var{eq1}, @var{eq2}, @dots{})\n%% @deftypemethodx @@sym {[@var{A}, @var{b}] =} equationsToMatrix (@var{eq1}, @dots{}, @var{v1}, @var{v2}, @dots{})\n%% Convert set of linear equations to matrix form.\n%%\n%% In its simplest form, equations @var{eq1}, @var{eq2}, etc can be\n%% passed as inputs:\n%% @example\n%% @group\n%% syms x y z\n%% [A, b] = equationsToMatrix (x + y == 1, x - y + 1 == 0)\n%%   @result{} A = (sym 2\u00d72 matrix)\n%%\n%%       \u23a11  1 \u23a4\n%%       \u23a2     \u23a5\n%%       \u23a31  -1\u23a6\n%%\n%%   @result{} b = (sym 2\u00d71 matrix)\n%%\n%%       \u23a11 \u23a4\n%%       \u23a2  \u23a5\n%%       \u23a3-1\u23a6\n%% @end group\n%% @end example\n%% In this case, appropriate variables @emph{and their ordering} will be\n%% determined automatically using @code{symvar} (@pxref{@@sym/symvar}).\n%%\n%% In some cases it is important to specify the variables as additional\n%% inputs @var{v1}, @var{v2}, etc:\n%% @example\n%% @group\n%% syms a\n%% [A, b] = equationsToMatrix (a*x + y == 1, y - x == a)\n%%   @print{} ??? ... nonlinear...\n%%\n%% [A, b] = equationsToMatrix (a*x + y == 1, y - x == a, x, y)\n%%   @result{} A = (sym 2\u00d72 matrix)\n%%\n%%       \u23a1a   1\u23a4\n%%       \u23a2     \u23a5\n%%       \u23a3-1  1\u23a6\n%%\n%%   @result{} b = (sym 2\u00d71 matrix)\n%%\n%%       \u23a11\u23a4\n%%       \u23a2 \u23a5\n%%       \u23a3a\u23a6\n%% @end group\n%% @end example\n%%\n%% The equations and variables can also be passed as vectors @var{eqns}\n%% and @var{vars}:\n%% @example\n%% @group\n%% eqns = [x + y - 2*z == 0, x + y + z == 1, 2*y - z + 5 == 0];\n%% [A, B] = equationsToMatrix (eqns, [x y])\n%%   @result{} A = (sym 3\u00d72 matrix)\n%%\n%%       \u23a11  1\u23a4\n%%       \u23a2    \u23a5\n%%       \u23a21  1\u23a5\n%%       \u23a2    \u23a5\n%%       \u23a30  2\u23a6\n%%\n%%   B = (sym 3\u00d71 matrix)\n%%\n%%       \u23a1 2\u22c5z \u23a4\n%%       \u23a2     \u23a5\n%%       \u23a21 - z\u23a5\n%%       \u23a2     \u23a5\n%%       \u23a3z - 5\u23a6\n%% @end group\n%% @end example\n%% @seealso{@@sym/solve}\n%% @end deftypemethod\n\n\nfunction [A, b] = equationsToMatrix(varargin)\n\n  % when Symbols are specified, this won't be used\n  s = findsymbols (varargin);\n\n  cmd = {'L, symvars = _ins'\n         'if not isinstance(L[-1], MatrixBase):'\n         '    if isinstance(L[-1], Symbol):'  % Symbol given, fill vars...\n         '        vars = list()'\n         '        for i in reversed(range(len(L))):'\n         '            if isinstance(L[i], Symbol):'\n         '                vars = [L.pop(i)] + vars'\n         '            else:'  % ... until we find a non-Symbol\n         '                break'\n         '    else:'\n         '        vars = symvars'\n         'else:'\n         '    if len(L) == 1:'  % we have only a list of equations\n         '        vars = symvars'\n         '    else:'\n         '        vars = L.pop(-1)'\n         'if len(L) == 1:'  % might be matrix of eqns, don't want [Matrix]\n         '    L = L[0]'\n         'vars = list(vars)'\n         'A, B = linear_eq_to_matrix(L, vars)'\n         'return True, A, B' };\n\n  for i = 1:length(varargin)\n    varargin{i} = sym (varargin{i});\n  end\n\n  [s, A, b] = pycall_sympy__ (cmd, varargin, s);\n\n\n  if ~s\n    error('Cannot convert to matrix; system may be nonlinear.');\n  end\n\nend\n\n\n%!test\n%! syms x y z\n%! [A, B] = equationsToMatrix ([x + y - z == 1, 3*x - 2*y + z == 3, 4*x - 2*y + z + 9 == 0], [x, y, z]);\n%! a = sym ([1 1 -1; 3 -2 1; 4 -2 1]);\n%! b = sym ([1; 3; -9]);\n%! assert (isequal (A, a))\n%! assert (isequal (B, b))\n\n%!test\n%! syms x y z\n%! A = equationsToMatrix ([3*x + -3*y - 5*z == 9, 4*x - 7*y + -3*z == -1, 4*x - 9*y - 3*z + 2 == 0], [x, y, z]);\n%! a = sym ([3 -3 -5; 4 -7 -3; 4 -9 -3]);\n%! assert (isequal (A, a))\n\n%!test\n%! syms x y\n%! [A, B] = equationsToMatrix ([3*x + 9*y - 5 == 0, -8*x - 3*y == -2]);\n%! a = sym ([3 9; -8 -3]);\n%! b = sym ([5; -2]);\n%! assert (isequal (A, a))\n%! assert (isequal (B, b))\n\n%!test\n%! % override symvar order\n%! syms x y\n%! [A, B] = equationsToMatrix ([3*x + 9*y - 5 == 0, -8*x - 3*y == -2], [y x]);\n%! a = sym ([9 3; -3 -8]);\n%! b = sym ([5; -2]);\n%! assert (isequal (A, a))\n%! assert (isequal (B, b))\n\n%!test\n%! syms x y z\n%! [A, B] = equationsToMatrix ([x - 9*y + z == -5, -9*y*z == -5], [y, x]);\n%! a = sym ([[-9 1]; -9*z 0]);\n%! b = sym ([-5 - z; -5]);\n%! assert (isequal (A, a))\n%! assert (isequal (B, b))\n\n%!test\n%! syms x y\n%! [A, B] = equationsToMatrix (-6*x + 4*y == 5, 4*x - 4*y - 5, x, y);\n%! a = sym ([-6 4; 4 -4]);\n%! b = sym ([5; 5]);\n%! assert (isequal (A, a))\n%! assert (isequal (B, b))\n\n%!test\n%! % vertical list of equations\n%! syms x y\n%! [A, B] = equationsToMatrix ([-6*x + 4*y == 5; 4*x - 4*y - 5], [x y]);\n%! a = sym ([-6 4; 4 -4]);\n%! b = sym ([5; 5]);\n%! assert (isequal (A, a))\n%! assert (isequal (B, b))\n\n%!test\n%! syms x y\n%! [A, B] = equationsToMatrix (5*x == 1, y, x - 6*y - 7, y);\n%! a = sym ([0; 1; -6]);\n%! b = sym ([1 - 5*x; 0; -x + 7]);\n%! assert (isequal (A, a))\n%! assert (isequal (B, b))\n\n%!error <nonlinear>\n%! syms x y\n%! [A, B] = equationsToMatrix (x^2 + y^2 == 1, x - y + 1, x, y);\n\n%!test\n%! % single equation\n%! syms x\n%! [A, B] = equationsToMatrix (3*x == 2, x);\n%! a = sym (3);\n%! b = sym (2);\n%! assert (isequal (A, a))\n%! assert (isequal (B, b))\n\n%!test\n%! % single equation w/ symvar\n%! syms x\n%! [A, B] = equationsToMatrix (3*x == 2);\n%! a = sym (3);\n%! b = sym (2);\n%! assert (isequal (A, a))\n%! assert (isequal (B, b))\n\n%!error <unique>\n%! syms x\n%! equationsToMatrix (3*x == 2, [x x])\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/equationsToMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5720188589849651}}
{"text": "function p = nodes_brick27 ( )\n\n%*****************************************************************************80\n%\n%% NODES_BRICK27 returns the natural coordinates of the BRICK27 element.\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%    Output, real P(3,27), the coordinates.\n%\n  p = [ ...\n    -1.0, -1.0, -1.0; ...\n    +1.0, -1.0, -1.0; ...\n    +1.0, +1.0, -1.0; ...\n    -1.0, +1.0, -1.0; ...\n    -1.0, -1.0, +1.0; ...\n    +1.0, -1.0, +1.0; ...\n    +1.0, +1.0, +1.0; ...\n    -1.0, +1.0, +1.0; ...\n     0.0, -1.0, -1.0; ...\n    +1.0,  0.0, -1.0; ...\n     0.0, +1.0, -1.0; ...\n    -1.0,  0.0, -1.0; ...\n    -1.0, -1.0,  0.0; ...\n    +1.0, -1.0,  0.0; ...\n    +1.0, +1.0,  0.0; ...\n    -1.0, +1.0,  0.0; ...\n     0.0, -1.0, +1.0; ...\n    +1.0,  0.0, +1.0; ...\n     0.0, +1.0, +1.0; ...\n    -1.0,  0.0, +1.0; ...\n     0.0,  0.0, -1.0; ...\n     0.0, -1.0,  0.0; ...\n    +1.0,  0.0,  0.0; ...\n     0.0, +1.0,  0.0; ...\n    -1.0,  0.0,  0.0; ...\n     0.0,  0.0, +1.0; ...\n     0.0,  0.0,  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/fem3d_pack/nodes_brick27.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5720188468913058}}
{"text": "function [p1Clip, p2Clip]=clipLineSegment2Rect(rectMaxMin,p1,p2)\n%%CLIPLINESEGMENT2RECT Given a 2D rectangle (axis-aligned) and given the\n%           two endpoints of a line segment clip the line segment to the\n%           rectangle. If the segment and the rectangle do not overlap,\n%           then an empty matrix is returned.\n%\n%INPUTS: rectMaxMin A length-4 array specifying the maximum and minimum\n%                   bounds in x and y. rectMaxMin=[xMin;xMax;yMin;yMax].\n%                   The minimum values must be <=the maximum values.\n%                p1 A length-2 array specifying the start of the line\n%                   segment.\n%                p2 A length-2 array specifying the end of the line\n%                   segment.\n%\n%OUTPUTS: p1Clip, p2Clip These are the same p1 and p2 but have been clipped to the\n%                start and end of the line segment. If nothing clips, the\n%                empty matrices are returned.\n%\n%The algorithm of [1] is used, without speed improvements that are possible\n%from direct substitution, which is mentioned in Section IX of [1]. The\n%performance of the algorithm is discussed in [2].\n%\n%EXAMPLE:\n% rect=[-1;1;-1;1];\n% numLines=6;\n% p1=zeros(2,numLines);\n% %Lines entirely inside the box.\n% p1(:,1)=[0;0]; p2(:,1)=[0.8;0.8];\n% p1(:,2)=[0.6;0]; p2(:,2)=[-0.8;0.8];\n% %Lines leaving via each edge of the box.\n% p1(:,3)=[0.6;-0.1]; p2(:,3)=[1.6;-0.2];\n% p1(:,4)=[-0.6;0.1]; p2(:,4)=[-1.6;0.2];\n% p1(:,5)=[-0.1;0.5]; p2(:,5)=[-0.2;2.8];\n% p1(:,6)=[0.1;-0.5]; p2(:,6)=[0.2;-1.8];\n% \n% figure(1)\n% clf\n% hold on\n% %Draw the bounding box lines, extending them.\n% extDist=3;\n% plot([-extDist,extDist],[-1,-1],'-k','linewidth',2)\n% plot([-extDist,extDist],[1,1],'-k','linewidth',2)\n% plot([-1,-1],[-extDist,extDist],'-k','linewidth',2)\n% plot([1,1],[-extDist,extDist],'-k','linewidth',2)\n% for k=1:numLines\n%     %Plot the line segments\n%     plot([p1(1,k),p2(1,k)],[p1(2,k),p2(2,k)],'-b','linewidth',4)\n%     %Clip the segments\n%     [p1Clip,p2Clip]=clipLineSegment2Rect(rect,p1(:,k),p2(:,k));\n%     %Plot the clipped segments.\n%     if(~isempty(p1Clip))\n%         plot([p1Clip(1),p2Clip(1)],[p1Clip(2),p2Clip(2)],'-r','linewidth',2)\n%     end\n% end\n%\n%REFERENCES:\n%[1] T. M. Nicholl, D. T. Lee, and R. A. Nicholl, \"An Efficient  New\n%    Algorithm for 2-D Line Clipping: its Development and Analysis\", \n%    ACM SIGGRAPH Computer Graphics, vol. 21, no. 4, pp. 253-262, Jul.\n%    1987.\n%[2] F. D\u00e9vai, \"Analysis of the Nichioll-Lee-Nicholl Algorithm,\" in\n%    Proceedings of the International Conference on Computational Science\n%    and its Applications, Signapore, pp. 726-736, 9-12 May, 2005.\n%\n%August 2020 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nxMin=rectMaxMin(1);\nxMax=rectMaxMin(2);\nyMin=rectMaxMin(3);\nyMax=rectMaxMin(4);\n\nx1=p1(1);\ny1=p1(2);\nx2=p2(1);\ny2=p2(2);\n\nif(x1<xMin)\n    [x1,y1,x2,y2,isVisible]=leftColumn(xMin,yMax,xMax,yMin,x1,y1,x2,y2); \nelseif(x1>xMax)\n    [x1,y1]=rotate180c(x1,y1);\n    [x2,y2]=rotate180c(x2,y2);\n    \n    [x1,y1,x2,y2,isVisible]=leftColumn(-xMax,-yMin,-xMin,-yMax,x1,y1,x2,y2);\n    \n    [x1,y1]=rotate180c(x1,y1);\n    [x2,y2]=rotate180c(x2,y2);\nelse\n    [x1,y1,x2,y2,isVisible]=centerColumn(xMin,yMax,xMax,yMin,x1,y1,x2,y2);\nend\n\nif(isVisible==false)\n    %If the line is not in the box at all.\n    p1Clip=[];\n    p2Clip=[];\nelse\n    p1Clip=[x1;y1];\n    p2Clip=[x2;y2];\nend\nend\n\nfunction [x1,y1,x2,y2,isVisible]=leftColumn(xL,yT,xR,yB,x1,y1,x2,y2)\n%%LEFTCOLUMN The case where (x1,y1) is to the left of the vertical line\n%            x=xL.\n\nif(x2<xL)\n    isVisible=false;\nelseif(y1>yT)\n    [x1,y1,x2,y2,isVisible]=topLeftCorner(xL,yT,xR,yB,x1,y1,x2,y2);\nelseif(y1<yB)\n    y1=reflectxAxis(y1);\n    y2=reflectxAxis(y2);\n    [x1,y1,x2,y2,isVisible]=topLeftCorner(xL,-yB,xR,-yT,x1,y1,x2,y2);\n    \n    y1=reflectxAxis(y1);\n    y2=reflectxAxis(y2);\nelse\n    [x1,y1,x2,y2,isVisible]=leftEdge(xL,yT,xR,yB,x1,y1,x2,y2);\nend\nend\n\nfunction [x1,y1,x2,y2,isVisible]=topLeftCorner(xL,yT,xR,yB,x1,y1,x2,y2)\n%TOPLEFTCORNER The case where (x1,y1) is in the top-left corner.\n\n    if(y2>yT)\n        isVisible=false;\n    else\n        relx2=x2-x1;\n        rely2=y2-y1;\n        \n        topProd=(yT-y1)*relx2;\n        leftProd=(xL-x1)*rely2;\n        %If (x2,y2) is below the line connecting (x1,y1) and (xL,yT).\n        if(topProd>leftProd)\n            [x1,y1,x2,y2,isVisible]=leftBottomRegion(xL,xR,yB,x1,y1,x2,y2,relx2,rely2,leftProd);\n        else\n            [x1,y1]=reflectxMinusy(x1,y1);\n            [x2,y2]=reflectxMinusy(x2,y2);\n          \n            [x1,y1,x2,y2,isVisible]=leftBottomRegion(-yT,-yB,-xR,x1,y1,x2,y2,-rely2,-relx2,topProd);\n            \n            [x1,y1]=reflectxMinusy(x1,y1);\n            [x2,y2]=reflectxMinusy(x2,y2);\n        end\n    end\nend\n\nfunction [x1,y1,x2,y2,isVisible]=leftBottomRegion(xL,xR,yB,x1,y1,x2,y2,relx2,rely2,leftProd)\n%%LEFTBOTTOMREGION The case where (x1,y1) is in the left bottom corner.\n\nif(y2>=yB)\n    if(x2>xR)\n        %The right-edge intersection.\n        y2=y1+(xR-x1)*rely2/relx2;\n        x2=xR;\n    end\n    \n    %The left-edge intersection.\n    y1=y1+leftProd/relx2;\n    x1=xL;\n    isVisible=true;\nelse\n    bottomProd=(yB-y1)*relx2;\n    \n    %If (x2,y2) is below the (x1,y1) to (xR,yB) line.\n    if(bottomProd>leftProd)\n        isVisible=false;\n    else\n        if(x2>xR)\n            rightProd=(xR-x1)*rely2;\n            \n            %If (x2,y2) is below the (x1,y1) to (xR,yB) line .\n            if(bottomProd>rightProd)\n                %The bottom-edge intersection.\n                x2=x1+bottomProd/rely2;\n                y2=yB;\n            else\n                %The right-edge intersection.\n                y2=y1+rightProd/relx2;\n                x2=xR;\n            end\n        else\n            %The bottom-edge intersection.\n            x2=x1+bottomProd/rely2;\n            y2=yB;\n        end\n        \n        %The left-edge intersection.\n        y1=y1+leftProd/relx2;\n        x1=xL;\n        isVisible=true;\n    end\nend\nend\n\nfunction [x1,y1,x2,y2,isVisible]=leftEdge(xL,yT,xR,yB,x1,y1,x2,y2)\n%%LEFTEDGE (x1,y1) is in the left edge.\n\n    if(x2<xL)\n        isVisible=false;\n    elseif(y2<yB)\n        [x1,y1,x2,y2,isVisible]=p2Bottom(xL,xR,yB,x1,y1,x2,y2);\n    elseif(y2>yT)\n        y1=reflectxAxis(y1);\n        y2=reflectxAxis(y2);\n        \n        [x1,y1,x2,y2,isVisible]=p2Bottom(xL,xR,-yT,x1,y1,x2,y2);\n        \n        y1=reflectxAxis(y1);\n        y2=reflectxAxis(y2);\n    else\n        relx2=x2-x1;\n        rely2=y2-y1;\n        \n        if(x2>xR)%The right-edge intersection.\n            y2=y1+(xR-x1)*rely2/relx2;\n            x2=xR;\n        end\n        \n        %The left-edge intersection.\n        y1=y1+(xL-x1)*rely2/relx2;\n        x1=xL;\n        isVisible=true;\n    end\nend\n\nfunction [x1,y1,x2,y2,isVisible]=centerColumn(xL,yT,xR,yB,x1,y1,x2,y2)\n%CENTERCOLUMN The case where (x1,y1) is between the left and right\n%             boundaries.\n\n    if(y1>yT)\n        [x1,y1]=rotate270c(x1,y1);\n        [x2,y2]=rotate270c(x2,y2);\n        [x1,y1,x2,y2,isVisible]=leftEdge(-yT,xR,-yB,xL,x1,y1,x2,y2);\n        [x1,y1]=rotate90c(x1,y1);\n        [x2,y2]=rotate90c(x2,y2);\n    elseif(y1<yB)\n        [x1,y1]=rotate90c(x1,y1);\n        [x2,y2]=rotate90c(x2,y2);\n        [x1,y1,x2,y2,isVisible]=leftEdge(yB,-xL,yT,-xR,x1,y1,x2,y2);\n        [x1,y1]=rotate270c(x1,y1);\n        [x2,y2]=rotate270c(x2,y2);\n    else\n        [x1,y1,x2,y2,isVisible]=inside(xL,yT,xR,yB,x1,y1,x2,y2);\n    end\nend\n\nfunction [x1,y1,x2,y2,isVisible]=inside(xL,yT,xR,yB,x1,y1,x2,y2)\n%%INSIDE The case where (x1,y1) is inside the rectangle.\n\nif(x2<xL)\n    [x1,y1,x2,y2]=p2Left(xL,yT,yB,x1,y1,x2,y2);\nelseif(x2>xR)\n\t[x1,y1]=rotate180c(x1,y1);\n\t[x2,y2]=rotate180c(x2,y2);\n    [x1,y1,x2,y2]=p2Left(-xR,-yB,-yT,x1,y1,x2,y2);\n    [x1,y1]=rotate180c(x1,y1);\n\t[x2,y2]=rotate180c(x2,y2);\nelseif(y2>yT)\n    x2=x1+(x2-x1)*(yT-y1)/(y2-y1);\n    y2=yT;\nelseif(y2<yB)\n    x2=x1+(x2-x1)*(yB-y1)/(y2-y1);\n    y2=yB;\nend\n\nisVisible=true;\nend\n\nfunction [x1,y1,x2,y2]=p2Left(xL,yT,yB,x1,y1,x2,y2)\n%%P2LEFT\n\n    if(y2>yT)\n        [x1,y1,x2,y2]=p2LeftTop(xL,yT,x1,y1,x2,y2);\n    elseif(y2<yB)\n        [x1,y1]=rotate90c(x1,y1);\n        [x2,y2]=rotate90c(x2,y2);\n        [x1,y1,x2,y2]=p2LeftTop(yB,-xL,x1,y1,x2,y2);\n        [x1,y1]=rotate270c(x1,y1);\n        [x2,y2]=rotate270c(x2,y2);\n    else\n        y2=y1+(y2-y1)*(xL-x1)/(x2-x1); \n        x2=xL;\n    end\nend\n\nfunction [x1,y1,x2,y2]=p2LeftTop(xL,yT,x1,y1,x2,y2)\n%%P2LEFTTOP\n\n    relx2=x2-x1;\n    rely2=y2-y1;\n    leftProduct=rely2*(xL-x1);\n    topProduct=relx2*(yT-y1);\n    \n    if(topProduct>leftProduct)\n        x2=x1+topProduct/rely2;\n        y2=yT;\n    else\n        y2=y1+leftProduct/relx2;\n        x2=xL;\n    end\nend\n\nfunction [x1,y1,x2,y2,isVisible]=p2Bottom(xL,xR,yB,x1,y1,x2,y2)\n%%P2BOTTOM (x1,y1) is in the left edge; (x2,y2) is not beyond the left\n%          edge,  and (x2,y2) is beyond the bottom edge.\n\n    relx2=x2-x1;\n    rely2=y2-y1;\n    leftProd=(xL-x1)*rely2;\n    bottomProd=(yB-y1)*relx2;\n    if(bottomProd>leftProd)\n        isVisible=false;\n    else\n       if(x2<=xR)\n           x2=x1+bottomProd/rely2;\n           y2=yB;\n       else\n           rightProd=(xR-x1)*rely2;\n           if(bottomProd>rightProd)\n               x2=x1+bottomProd/rely2;\n               y2=yB;\n           else\n               y2=y1+rightProd/relx2;\n               x2=xR;\n           end\n       end\n       y1=y1+leftProd/relx2;\n       x1=xL;\n       isVisible=true;\n    end\nend\n\nfunction [x,y]=reflectxMinusy(x,y)\n%%REFLECTXMINUSY This function is from Section VI-2 of [1].\n%\n%REFERENCES:\n%[1] T. M. Nicholl, D. T. Lee, and R. A. Nicholl, \"An Efficient  New\n%    Algorithm for 2-D Line Clipping: its Development and Analysis\", \n%    ACM SIGGRAPH Computer Graphics, vol. 21, no. 4, pp. 253-262, Jul.\n%    1987.\n\nt=x;\nx=-y;\ny=-t;\n\nend\n\nfunction y=reflectxAxis(y)\n%%REFLECTAXIS This function is from Section VI-2 of [1].\n%\n%REFERENCES:\n%[1] T. M. Nicholl, D. T. Lee, and R. A. Nicholl, \"An Efficient  New\n%    Algorithm for 2-D Line Clipping: its Development and Analysis\", \n%    ACM SIGGRAPH Computer Graphics, vol. 21, no. 4, pp. 253-262, Jul.\n%    1987.\n\ny=-y;\n\nend\n\nfunction [x,y]=rotate90c(x,y)\n%%ROTATE90C This function is from Section VI-2 of [1].\n%\n%REFERENCES:\n%[1] T. M. Nicholl, D. T. Lee, and R. A. Nicholl, \"An Efficient  New\n%    Algorithm for 2-D Line Clipping: its Development and Analysis\", \n%    ACM SIGGRAPH Computer Graphics, vol. 21, no. 4, pp. 253-262, Jul.\n%    1987.\n\nt=x;\nx=y;\ny=-t;\n\nend\n\nfunction [x,y]=rotate180c(x,y)\n%%ROTATE180C This function is from Section VI-2 of [1].\n%\n%REFERENCES:\n%[1] T. M. Nicholl, D. T. Lee, and R. A. Nicholl, \"An Efficient  New\n%    Algorithm for 2-D Line Clipping: its Development and Analysis\", \n%    ACM SIGGRAPH Computer Graphics, vol. 21, no. 4, pp. 253-262, Jul.\n%    1987.\n\nx=-x;\ny=-y;\nend\n\nfunction [x,y]=rotate270c(x,y)\n%%ROTATE270C This function is from Section VI-2 of [1].\n%\n%REFERENCES:\n%[1] T. M. Nicholl, D. T. Lee, and R. A. Nicholl, \"An Efficient  New\n%    Algorithm for 2-D Line Clipping: its Development and Analysis\", \n%    ACM SIGGRAPH Computer Graphics, vol. 21, no. 4, pp. 253-262, Jul.\n%    1987.\n\nt=x;\nx=-y;\ny=t;\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/clipLineSegment2Rect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.5719159332525555}}
{"text": "function f=midi2frq(n,s)\n%MIDI2FRQ\tConvert musical note numbers to frequencies F=(N,S)\n%\t\ts is:\t'e' equal tempered (default)\n%\t\t\t'p' pythagorean scale\n%\t\t\t'j' just intonation\n%\n% notes are numbered in semitones with middle C being 60\n% On the equal tempered scale, note 69 (the A above middle C)\n% has a frequency of 440 Hz.\n%\n% see FRQ2NOTE for the inverse transform\n\n% Pythagorean\n%     sharps 1 2187/2048 9/8 19683/16384 81/64 4/3 729/512  3/2 6561/4096 27/16 59049/32768 243/128 2\n%     flats  1 256/243   9/8 32/27       81/64 4/3 1024/729 3/2 128/81    27/16 16/9        243/128 2\n%\n% Just Intonation\n%     sharps 1 25/24 9/8 75/64 5/4 4/3 45/32  3/2 25/16 5/3 225/128 15/8 2\n%     flats  1 16/15 9/8 6/5   5/4 4/3 108/75 3/2 8/5   5/3 18/10   15/8 2\n\n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: midi2frq.m 713 2011-10-16 14:45:43Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin > 1\n  if s(1)=='p'\n    r=[256/243 9/8 32/27 81/64 4/3 729/512 3/2 128/81 27/16 16/9 243/128];\n  elseif s(1)=='j'\n    r=[16/15 9/8 6/5 5/4 4/3 36/25 3/2 8/5 5/3 9/5 15/8];\n  else\n    r=0;\n  end\n  if r(1)\n    c=[0 0 12*log(r)/log(2)-(1:11) 0];\n    nm=mod(n,12);\n    na=floor(nm);\n    nb=nm-na;\n    f=440*exp((n+c(na+2).*(1-nb)+c(na+3).*nb-69)*log(2)/12);\n  else\n    f=440*exp((n-69)*log(2)/12);\n  end\nelse\n  f=440*exp((n-69)*log(2)/12);\nend\n\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/midi2frq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5718595292733557}}
{"text": "x=[1 2 3 4 5 6 7 8 9]\npause\nfind(x<6)\npause\ny=[1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]\npause\nfind(y<6)'\npause\n[l,c,v]=find(y<6);\npause\nl'\npause\nc'\npause\nv'", "meta": {"author": "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/10/Ex_10_4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.5717615798518315}}
{"text": "function varargout = frame2oell(varargin)\n% VL_FRAMES2OELL   Convert a geometric frame to an oriented ellipse\n%   EFRAME = VL_FRAME2OELL(FRAME) converts the generic FRAME to an\n%   oriented ellipses EFRAME. FRAME and EFRAME can be matrices, with\n%   one frame per column.\n%\n%   A frame is either a point, a disc, an oriented disc, an ellipse,\n%   or an oriented ellipse. These are represented respectively by 2,\n%   3, 4, 5 and 6 parameters each, as described in VL_PLOTFRAME().  An\n%   oriented ellipse is the most general geometric frame; hence, there\n%   is no loss of information in this conversion.\n%\n%   If FRAME is an oriented disc or ellipse, then the conversion is\n%   immediate. If, however, FRAME is not oriented (it is either a\n%   point or an unoriented disc or ellipse), then an orientation must\n%   be assigned. The orientation is chosen in such a way that the\n%   affine transformation that maps the standard oriented frame into\n%   the output EFRAME does not rotate the Y axis. If frames represent\n%   detected visual features, this convention corresponds to assume\n%   that features are upright.\n%\n%   If FRAME is a point, then the output is an ellipse with null area.\n%\n%   See: <a href=\"matlab:vl_help('tut.frame')\">feature frames</a>,\n%   VL_PLOTFRAME(), VL_HELP().\n[varargout{1:nargout}] = vl_frame2oell(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/frame2oell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.5717615632357089}}
{"text": "%% Projection Based Shape Parameters\n%\n%%\n% In this section we discuss shape parameters grains that depend on one\n% dimensional projections, i.e., \n%\n% || <grain2d.caliper.html |caliper|>  || caliper or Feret diameter in $\\mu m$ || <grain2d.diameter.html |diameter|>  || diameter in $\\mu m$ || \n%\n% In order to demonstrate these parameters we first import a small sample\n% data set.\n\n% load sample EBSD data set\nmtexdata forsterite silent\n\n% reconstruct grains, discard boudnary grains and smooth them\n[grains, ebsd.grainId] = calcGrains(ebsd('indexed'),'angle',5*degree);\nebsd(grains(grains.grainSize<5)) = [];\n[grains, ebsd.grainId] = calcGrains(ebsd('indexed'),'angle',5*degree);\ngrains(grains.isBoundary) = [];\n\ngrains = smooth(grains('indexed'),10,'moveTriplePoints');\n\n% plot all grains and highlight a specific one\nplot(grains)\n\nind = 654;\nhold on\nplot(grains(ind).boundary,'lineWidth',5,'linecolor','blue')\nhold off\n\n%%\n% The most well known projection based parameter is the\n% <grain2d.diamter.html |diameter|> which refers to the longest distance\n% between any two boundary points and is given in $\\mu m$.\n\ngrains(ind).diameter\n\n%%\n% The diameter is a special case of the <grain2d.caliper.html |caliper|> or\n% Feret diameter of a grain. By definition the caliper is the length of a\n% grain when projected onto a line. We may trace the caliper with respect\n% to projection direction\n\nclose all\nomega = linspace(0,180);\nplot(omega,grains(ind).caliper(omega*degree),'LineWidth',2)\nylabel('length in $\\mu$m','Interpreter','latex')\nxlabel('angle of the projection line in degree')\nxlim([0,180])\n\n%%\n% We observe that that maximum caliper is about 7000 while the minimum\n% caliper is about 2000. We may compute the exact direction and length of\n% the maximum or minimum by passing the options |'longest'| or |'shortest'|\n% to the function <grain2d.caliper.html |caliper|>. In this case the the\n% output is of type @vector3d indicating the direction. The\n% <vector3d.norm.html |norm|> of the vector coincides with the caliper for\n% this projection direction. Hence, the |norm(grains.caliper('longest'))|\n% coincides with the diameter.\n\nplot(grains(ind),'micronbar','off')\nlegend('off')\n\nnorm(grains(ind).caliper('longest'))\nnorm(grains(ind).caliper('shortest'))\n\nhold on\nquiver(grains(ind),grains(ind).caliper('longest'),'noScaling')\nquiver(grains(ind),grains(ind).caliper('shortest'),'noScaling')\nhold off\n\n\n%%\n% The difference between the longest and the shortest caliper can be taken\n% as a measure how round a grain is. \n\ncMin = grains.caliper('shortest');\ncMax = grains.caliper('longest');\n\nplot(grains,(norm(cMax) - norm(cMin))./norm(cMax),'micronbar','off')\nmtexColorbar('title','TODO')\n\n%%\n% This longest and shortest caliper are comparable to\n% <grain2d.longAxis.html |grains.longAxis|> and <grain2d.shortAxis.html\n% |grains.shortAxis|> computed from an ellipse fitted to the grain. In the\n% case of rectangular particles, one might not primarily be interested in\n% the longest caliper of a grain but rather in the direction normal to the\n% shortest caliper. This is computed when specifying the option\n% |'shortestPerp'|. If we imagine a very strong alignment of the long axes\n% of orthorhombic particles, the maximum diameter may show a bimodal\n% distribution (the two, roughly equally distributed diagonals of the\n% particle).\n\n% load some test grains\ntestgrains = mtexdata('testgrains');\ntestgrains = smooth(testgrains([6 8]),10);\n\n% compute the longest caliper and the caliper perpendicular to the shortest\ncMax = testgrains.caliper('longest');\ncMinPerp = testgrains.caliper('shortestPerp');\n\n% plot the grains and visualize the different long axes\nplot(testgrains,'micronbar','off','lineWidth',2)\nhold on\nquiver(testgrains,cMax,'DisplayName','longest calliper','LineWidth',3)\nquiver(testgrains,testgrains.longAxis,'DisplayName','long axis','LineWidth',3)\nquiver(testgrains,cMinPerp,'DisplayName','perp to shortest','LineWidth',3)\nhold off\nlegend('Location','east')\n\n%% PAROR and SURFOR\n% \n% Another way of quantifying shape farbics is by making use of the\n% cumulative projection function of the grains or the grain boundary\n% segments. These methods are heavily inspired by\n% <https://en.wikipedia.org/wiki/Flatland Edwin A. Abbotts 'Flatland - A\n% romance of many dimensions' (1884)> and based on Panozzo, R., 1983,\n% \"Two-dimensional analysis of shape fabric using projections of digitized\n% lines in a plane\". Tectonophysics 95, 279-294. and Panozzo, R., 1984,\n% \"Two-dimensional strain from the orientation of lines in a plane.\" J.\n% Struct. Geol. 6, 215-221. implemented in Mtex as <grain2d.paror.html\n% |grains.paror|> and <grainBoundary.surfor.html |grainBoudnary.surfor|>\n%\n% As mentioned above the function <grain2d.caliper.html |caliper|> can be\n% called with a list of angles and returns the projection length of all\n% grains with respect to all angles. \n\n% projection angle\nomega = linspace(0,360*degree,361);\nc = grains('Fo').caliper(omega);\n\nsubplot(1,2,1)\npolarplot(omega,c,'LineWidth',2,'color',[0 0.25 0.5 0.25])\ntitle('Forsterite') \n\n% take the average\nhold on\npolarplot(omega,5*mean(c),'LineWidth',3,'color','k');\nhold off\n\nsubplot(1,2,2)\nc = grains('Enstatite').caliper(omega);\n\npolarplot(omega,c,'LineWidth',2,'color',[0 0.25 0.5 0.25])\ntitle('Enstatite') \n\n% take the average\nhold on\npolarplot(omega,5*mean(c),'LineWidth',3,'color','k');\nhold off\n\n%%\n% The above averaged caliper can be computed more directly by the function\n% <grain2d.paror.html |grains.paror|> which returns the cumulative particle\n% projection function normalized to 1. The projection angles can be\n% regarded as the rotation angle of the particle (counterclockwise) while\n% projecting from the y-axis onto the x-axis.\n\nclose all\ncumplF = paror(grains('fo'),omega);\ncumplE = paror(grains('en'),omega);\n\nsubplot(1,2,1)\npolarplot(omega,cumplF,'LineWidth',3,'color','k')\n\nsubplot(1,2,2)\npolarplot(omega,cumplE,'LineWidth',3,'color','k')\n\n\n%%\n% We can interpret the results in the following way. The minimum of the\n% curve is a measure of the amplitude of the projection function and can be\n% compared to an averaged axial ratio $b/a$ of the entire  fabric;\n% isotropic fabrics would have a $b/a$ close to 1 while highly anisotropic\n% fabrics can be identified by small $b/a$ values.\n\nmin(cumplF), min(cumplE)\n\n%%\n% The position of the maxima and minima of the projection function derived\n% from <grain2d.paror.html |paror|> can be interpreted in the following\n% way: the maximum position represents the preferred axis parallel to the\n% longest projection and the normal the minimum position represents the\n% preferred axis related to the normal to the shortest projection function.\n\n% for the Forsterite\n[~, id_max] = max(cumplF);\n[~, id_min] = min(cumplF);\n\nmod(omega(id_max)./degree,180)\nmod(omega(id_min)./degree-90,180)\n\n% for the Enstatite\n[~, id_max] = max(cumplE);\n[~, id_min] = min(cumplE);\n\nmod(omega(id_max)./degree,180)\nmod(omega(id_min)./degree-90,180)\n\n%%\n% The smaller the difference between these values, the closer the fabric is\n% to an orthorhombic symmetry.\n%\n% Similarly to using the entire particle (the convex hull in case of the\n% projection functions), we can use a distribution of lines\n% <grainBoundary.surfor.html |grainBoudnary.surfor|>. This can be useful\n% for the quantification of the grain boundary anisotropy or in general\n% might be needed if we look at boundaries which do not form closed\n% outlines, e.g. a list of subgrain or twin boundaries or the contact\n% between certain phases.\n% \n% Let's compare the boundaries between the different unlike phases and\n% between forsterite-forsterite in our sample:\n\nclose all\npairs = [1 1; nchoosek(1:3,2)];\nphase = {'Fo' 'En' 'Di'};\nfor i=1:length(pairs)\n  \n  gB = grains.boundary(phase{pairs(i,:)});\n  polarplot(omega, surfor(gB,omega), 'linewidth',2, ...\n    'DisplayName',[phase{pairs(i,1)} '-' phase{pairs(i,2)}]);\n  hold on\n  \nend\nhold off\nlegend('Location','southoutside','Orientation','horizontal')\n\n%%\n% We can see that Forsterite-Forsterite boundaries form a fabric slightly\n% more inclined with respect to the other phase boundariesand that the\n% phase boundaries between the two pyroxenes (Enstatite and Diopside) show\n% the lowest anisotropy.\n%\n%% Characteristic Shape\n%\n% The characteristic shape results from the cummulative sum of all grain\n% boundary segements ordered by the angle of the segment direction. It can\n% be regarded as to represent the average grain shape, however without the\n% need to use closed areas such as it would be required when working with\n% grains.\n%\n% Here we can compare the shape defined by Forterite-Forsterite,\n% Enstatite-Enstatite and Forsterite-Enstatite boundaries\n\nplotopts = {'normalize','linewidth',2, 'plain'};\n\nshapeF = characteristicShape(grains.boundary('Fo','Fo'))\nplot(shapeF,plotopts{:},'DisplayName','Fo-Fo')\n\nhold on\nshapeE = characteristicShape(grains.boundary('En','En'));\nplot(shapeE,plotopts{:},'DisplayName','En-En')\n\nhold on\nshapeEF = characteristicShape(grains.boundary('En','Fo'));\nplot(shapeEF,plotopts{:},'DisplayName','En-Fo')\nhold off\n\nlegend('Location','southoutside','Orientation','horizontal')\n\n%%\n% The output of the command <grainBoundary.characteristicShape.html\n% |characteristicShape|> is a <shape2d.shape2d.html |shape2d|> object which\n% behaves very similar to a <grain2d.grain2d.html |grain2d|> object. Hence\n% it is easy to derive things such as a long axis or e.g. the angle between\n% the longest and the shortest caliper which can be regarded as a measure\n% of asymmetry.\n\nangle(shapeF.caliper('longest'),shapeF.caliper('shortest'))/degree\nangle(shapeE.caliper('longest'),shapeE.caliper('shortest'))/degree\nangle(shapeEF.caliper('longest'),shapeF.caliper('shortest'))/degree\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/Grains/ProjectionBasedParameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5717615628922772}}
{"text": "function B = BoundMirrorShrink(A)\n% Shrink the matrix to remove the padded mirror boundaries\n%\n% for example \n%\n% A = [\n%     5  4  5  6  12  6\n%     2  1  2  3  11  3\n%     5  4  5  6  12  6 \n%     8  7  8  9  13  9 \n%     5  4  5  6  12  6\n%     ]\n% \n% B = BoundMirrorShrink(A) will yield\n%\n%     1  2  3  11\n%     4  5  6  12\n%     7  8  9  13\n\n% Chenyang Xu and Jerry L. Prince, 9/9/1999\n% http://iacl.ece.jhu.edu/projects/gvf\n\n[m,n] = size(A);\nyi = 2:m-1;\nxi = 2:n-1;\nB = A(yi,xi);\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/42435-adaptive-diffusion-flow-active-contours-for-image-segmentation/ADF code/BoundMirrorShrink.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.5717615545842158}}
{"text": "function [XTrain XTest yTrain yTest] = splitData(X, y)\n\n% Splits the data into training and testing\n\n% Useful Variables\ntotalEgs = size(X,1);\nnumTrain = 0.8*totalEgs; % 80% data reserved for training\nnumTest = 0.2*totalEgs; % 20% reserved for testing\nnumLabels = unique(y); % how many unique labels present\nTrainPerLable = numTrain/length(numLabels); % how many egs per lable in training\nTestPerLable = numTest/length(numLabels);  % how many egs per lable in test\n\nfor i=1:length(numLabels)\n    temp = (y==numLabels(i,1)); % find out where each label is present\n    idx = find(temp==1); % get the index of that row where the lable is present\n    Xtemp = X(idx(:,1),:); % get values of X stored at that particular index\n    idxTemp = (randperm(size(Xtemp,1)))'; % randomly choose rows to put into train\n    XTrainTemp = Xtemp(idxTemp(1:TrainPerLable,1),:);\n    yTrainTemp = (ones(TrainPerLable,1))*i; \n    XTestTemp = Xtemp(idxTemp(TrainPerLable+1:end),:); % select remaining rows for testing\n    yTestTemp = (ones(TestPerLable,1))*i;\n    \n    if i==1 % set up first input to train and test\n        XTrain = XTrainTemp;\n        yTrain = yTrainTemp;\n        XTest = XTestTemp;\n        yTest = yTestTemp;\n    else % keep adding new egs to the training and testing sets\n        XTrain = [XTrain; XTrainTemp];\n        yTrain = [yTrain; yTrainTemp];\n        XTest = [XTest; XTestTemp];\n        yTest = [yTest; yTestTemp];\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/42770-logistic-regression-with-regularization-used-to-classify-hand-written-digits/Logistic Regression with regularisation/splitData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540518, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.5717554464826875}}
{"text": "function r = get_consensus_set_rank(CS, E, mode, T_noise_squared)\n\n% r = get_consensus_set_rank(CS, E, mode, T_noise_squared)\n%\n% DESC:\n% get the rank of a consensus set \n%\n% AUTHOR\n% Marco Zuliani - marco.zuliani@gmail.com\n%\n% VERSION:\n% 1.0.2\n%\n% INPUT:\n% CS                = logical array identifyng the CS\n% E                 = error associated to each data element\n% mode              = specify the type of ranking\n%                     0 -> RANSAC (cardinality of the CS)\n%                     1 -> MSAC \n% T_noise_squared   = noise threshold to discriminate inliers vs outliers\n%\n% OUTPUT:\n% r                 = consensus set rank\n\n% HISTORY:\n%\n% 1.0.0             - 01/13/08 - Initial version\n% 1.0.1             - 01/17/08 - Added different M-estimators\n% 1.0.2             - 02/22/08 - Removed the M-estimators\n%                                Added different ranking modes\n% 1.0.3             - 05/26/14 - Removed MLESAC\n\nN = length(CS);\n\nswitch mode\n\n    case 'RANSAC'\n\n        r = sum(CS);\n        \n    case 'MSAC'\n\n        rho = E;\n        rho(rho >= T_noise_squared) = T_noise_squared;\n        \n        % set to negative sothat also this rank is to be\n        % maximized\n        r = -sum(rho)/N;\n        \n    otherwise\n        \n        error('RANSACToolbox:optionError', 'Unknown ranking mode');\n        \nend\n\nreturn\n", "meta": {"author": "RANSAC", "repo": "RANSAC-Toolbox", "sha": "c08308bf61aaf669b00533409cb0daaa10c000aa", "save_path": "github-repos/MATLAB/RANSAC-RANSAC-Toolbox", "path": "github-repos/MATLAB/RANSAC-RANSAC-Toolbox/RANSAC-Toolbox-c08308bf61aaf669b00533409cb0daaa10c000aa/Common/get_consensus_set_rank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5717500697468934}}
{"text": "function outsig=frsyn(F,insig);\n%FRSYN  Frame synthesis operator\n%   Usage: f=frsyn(F,c);\n%\n%   `f=frsyn(F,c)` constructs a signal *f* from the frame coefficients *c*\n%   using the frame *F*. The frame object *F* must have been created using\n%   |frame|.\n%\n%   Examples:\n%   ---------\n%\n%   In the following example a signal *f* is constructed through the frame\n%   synthesis operator using a Gabor frame. The coefficients associated with \n%   this Gabor expansion are contained in an identity matrix. The identity \n%   matrix corresponds to a diagonal in the time-frequency plane, that is, \n%   one atom at each time position with increasing frequency.:::\n%\n%      a = 10;\n%      M = 40;\n%\n%      F = frame('dgt', 'gauss', a, M);\n%\n%      c = framenative2coef(F, eye(40));\n%\n%      f = frsyn(F, c);\n%\n%   See also: frame, frana, plotframe\n  \ncomplainif_notenoughargs(nargin,2,'FRSYN');\ncomplainif_notvalidframeobj(F,'FRSYN');\n\nL=framelengthcoef(F,size(insig,1));\n\nF=frameaccel(F,L);\n\noutsig=F.frsyn(insig);\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/frames/frsyn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5717500643564764}}
{"text": "function [alpha,xp] = StepSizeSW(f,x,d,alpha,params)\n% Line search algorithm satisfying strong Wolfe conditions.\n% Algorithms 3.5 on pages 60-61 in Nocedal and Wright.\n% Requires x.p, x.f and x.g to be initialized.\n\nalpha0 = params.stpmin;\nc1 = params.ftol;\nc2 = params.gtol;\n% alpha is alpha_i\ngxd = x.g'*d;\n% alphap is alpha_{i-1}\nalphap = alpha0;\nfxp = x.f;\ni=1;\nwhile norm(alphap-alpha) > params.xtol\n  xp.p = x.p + alpha*d;\n  xp.f = feval(f,xp.p,1);\n  if (xp.f > x.f + c1*alpha*gxd) | ((i > 1) & (xp.f >= fxp)),\n    [alpha,xp] = zoom(f,x,d,alphap,alpha,fxp,c1,c2);\n    return;\n  end\n  xp.g = feval(f,xp.p,2); gxpd = xp.g'*d;\n  if abs(gxpd) <= -c2*gxd,\n    return;\n  end\n  if gxpd >= 0,\n    [alpha,xp] = zoom(f,x,d,alpha,alphap,xp.f,c1,c2);\n    return;\n  end\n  alphap = alpha;\n  fxp = xp.f;\n  %  alpha = alpha + (params.stpmax-alpha)*rand(1);\n  alpha = alpha + (params.stpmax-alpha)*0.5;\n  i = i+1;\nend\nalpha,\nerror('No stepsize found');\n\nfunction [alpha,xp] = zoom(f,x,d,alphal,alphah,fxl,c1,c2)\n% function [alpha,xp] = zoom(f,x,d,alphal,alphah,fxl)\n% Algorithm 3.6 on page 61 in Nocedal and Wright\n\ngxd = x.g'*d;\n\nwhile 1\n   alpha = 1/2*(alphal+alphah);\n   xp.p = x.p + alpha*d;\n   xp.f = feval(f,xp.p,1); \n   if ((xp.f > x.f + c1*alpha*gxd) | (xp.f >= fxl)),\n      alphah = alpha;\n   else\n      xp.g = feval(f,xp.p,2); gxpd = xp.g'*d;\n      if abs(gxpd) <= -c2*gxd,\n        return;\n      end\n      if gxpd*(alphah-alphal) >= 0,\n        alphah = alphal;\n      end\n      alphal = alpha;\n      fxl = xp.f;\n   end\nend ", "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/StepSizeSW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.571750042642386}}
{"text": "function [x, infos] = admm_seq_conv_nmf(V, rank, t, in_options)\n% ADMM based convolutive non-negative matrix factorization (ADMM-Conv-NMF).\n%\n% The problem of interest is defined as\n%\n%\n% Given a non-negative matrix V, factorized non-negative matrices {W, H} are calculated.\n%\n%\n% Inputs:\n%       matrix      V\n%       rank        rank\n%           \n% Output:\n%       w           solution of w\n%       infos       information\n%\n% References:\n%\n%    \n% This file is part of NMFLibrary\n%\n% This file has been ported from \n% convNMF_MM1.m and convNMF_MM2.m at https://github.com/lyn202206/ADMM-Convolutive-NMF\n% by Yinan Li.\n%\n% Ported by H.Kasai on June 29, 2022\n%\n% Change log: \n%\n\n\n    % set dimensions and samples\n    [m, n] = size(V);\n \n    % set local options\n    local_options = [];    \n    local_options.metric_type = 'beta-div';\n    local_options.d_beta = 2;  \n    local_options.rho = 1;\n    local_options.flag = 1;\n    \n    % check input options\n    if ~exist('in_options', 'var') || isempty(in_options)\n        in_options = struct();\n    end     \n    % merge options\n    options = mergeOptions(get_nmf_default_options(), local_options);   \n    options = mergeOptions(options, in_options);\n\n    % initialize factors\n    init_options = options;\n    if ~isfield(options, 'x_init')\n        W = zeros(m, rank, t);\n        for i = 1 : t\n            [init_factors, ~] = generate_init_factors(V, rank, init_options);    \n            W(:, :, i) = init_factors.W;\n        end\n        H = init_factors.H;   \n    else\n        W = init_options.x_init.W;\n        H = init_options.x_init.H;        \n    end\n\n    % initialize\n    epoch = 0; \n    grad_calc_count = 0;\n\n    options = check_divergence(options);\n    sub_mode = sprintf('beta=%.1f', options.d_beta);\n    if ~strcmp(options.metric_type, 'beta-div')\n        sub_mode = options.metric_type;\n    end    \n    method_name = sprintf('ADMM-Seq-Conv (%s)', sub_mode);    \n\n    if options.verbose > 0\n        fprintf('# %s: started ...\\n', method_name);           \n    end     \n\n    % initialize for this algorithm\n    X = zeros(m, n, t);\n    for i=0:t-1\n        tW = W(:, :, i+1);\n        tH = shift_t(H, i);\n        % initial X\n        X(:, :, i+1) = tW * tH;\n    end\n    \n    % some variable for test\n    Xplus = X;\n    U = zeros(m, n,t);\n    \n    alphaX = zeros(m, n,t);\n    alphaH = zeros(rank,n);\n    alphaW = zeros(m,rank,t);\n    \n    Wplus = W;\n    Hplus = H;\n    \n    % store initial info\n    clear infos;   \n\n    [Wcon, Hcon] = reconstruct_wh(W, H, t);\n    [infos, f_val, optgap] = store_nmf_info(V, Wcon, Hcon, [], options, [], epoch, grad_calc_count, 0);\n      \n    \n    if options.verbose > 1\n        fprintf('ADMM-Seq-Conv (%s): Epoch = 0000, cost = %.16e, optgap = %.4e\\n', sub_mode, f_val, optgap); \n    end     \n         \n    % set start time\n    start_time = tic();\n\n    % main loop\n    while true\n        \n        % check stop condition\n        [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n        if stop_flag\n            display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n            break;\n        end\n        \n        % update H by accumulation\n        P1 = zeros(rank,rank);\n        P2 = zeros(rank,n);\n        P3 = zeros(rank,n);\n        for i = 0 : t-1\n            tW = W(:, :, i+1);\n            tX = shift_t(X(:, :, i+1), -i);\n            talphaX = shift_t(alphaX(:, :, i+1), -i);\n            P1 = P1 + tW'*tW;\n            P2 = P2 + tW'*tX;\n            P3 = P3 + tW'*talphaX;\n        end\n        H = (P1 + eye(rank)) \\ (P2 + Hplus + 1/options.rho * (P3-alphaH));\n        \n        % update Hplus\n        Hplus = max(H + 1/options.rho * alphaH, 0);\n        \n        % update alphaH\n        alphaH = alphaH + options.rho * (H - Hplus);\n      \n        % update parameters sequentially\n        for i = 0 : t-1\n            % update Xplus in each time slice\n            tW = Wplus(:, :, i+1);\n            tH = shift_t(Hplus, i);\n            % calculate Xplus\n            Xplus(:, :, i+1) = tW * tH;\n           \n            % splite V in each time slice which result in U\n            U(:, :, i+1) = (tW * tH + eps).*V./(sum(Xplus, 3) + t*eps);\n           \n            % update X in each time slice\n            if options.d_beta ==2\n\n                % update for Euclidean distance\n                tW = W(:, :, i+1);\n                tH = shift_t(H, i);\n                tV = U(:, :, i+1);\n\n                % update X\n                X(:, :, i+1) = (options.rho*tW * tH + tV - alphaX(:, :, i+1)) / (1 + options.rho);\n\n            elseif options.d_beta == 1\n\n                % update for Kullback-Leibler divergence\n                tW = W(:, :, i+1);\n                tH = shift_t(H, i);\n                tV = U(:, :, i+1);\n\n                % update X\n                b = options.rho * tW * tH - alphaX(:, :, i+1) - 1;\n                X(:, :, i+1) = (b + sqrt(b.^2 + 4 * options.rho * tV)) / (2 * options.rho);  \n\n            elseif options.d_beta == 0\n\n                % update for Itakura-Saito divergence\n                tW = W(:, :, i+1);\n                tH = shift_t(H, i);\n                tV = U(:, :, i+1);\n\n                % parameters for update\n                A = alphaX(:, :, i+1) / options.rho - tW * tH;\n                B = 1/(3 * options.rho) - A.^2/9;\n                C = - A.^3/27 + A/(6 * options.rho) + tV / (2*options.rho);\n                D = B.^3 + C.^2;\n\n                % update X\n                tX = X(:, :, i+1);\n                tX(D>=0) = nthroot(C(D>=0)+sqrt(D(D>=0)),3) + ...\n                nthroot(C(D>=0)-sqrt(D(D>=0)),3) - ...\n                A(D>=0)/3;\n\n                phi = acos(C(D<0) ./ ((-B(D<0)).^1.5));\n                tX(D<0) = 2*sqrt(-B(D<0)).*cos(phi/3) - A(D<0)/3;\n                X(:, :, i+1) = tX;\n            else       \n                error('The options.d_beta you specified is not currently supported.')\n            end\n\n            % update alphaX\n            alphaX(:, :, i+1) = alphaX(:, :, i+1) +  options.rho * (X(:, :, i+1) - tW * tH);\n             \n            % update W\n            tH = shift_t(H, i);\n            tX = X(:, :, i+1);\n            P = tH * tH' + eye(rank);\n            Q = tH * tX' + Wplus(:, :, i+1)' + 1/options.rho*(tH * alphaX(:, :, i+1)' - alphaW(:, :, i+1)');\n            W(:, :, i+1) = (P \\ Q)';\n           \n            % update Wplus\n            Wplus(:, :, i+1) = max(W(:, :, i+1) + 1/options.rho * alphaW(:, :, i+1), 0);\n           \n            % udpate alphaW\n            alphaW(:, :, i+1) = alphaW(:, :, i+1) + options.rho * (W(:, :, i+1) - Wplus(:, :, i+1));          \n        end\n        \n        %  if to update X before the update of U\n        if options.flag == 1\n\n            %  update Xplus in each time slice\n            for i=0:t-1\n                tW = Wplus(:, :, i+1);\n                tH = shift_t(Hplus, i);\n                % initial X\n                Xplus(:, :, i+1) = tW * tH;\n            end\n\n            % splite V in each time slice which result in U\n            for i=0:t-1\n                tW = Wplus(:, :, i+1);\n                tH = shift_t(Hplus, i);\n                U(:, :, i+1) = (tW * tH + eps) .* V ./ (sum(Xplus, 3) + t*eps);\n            end\n\n            % update X in each time slice after the update of the whole W\n            if options.d_beta == 2\n\n                % update for Euclidean distance\n                for i=0:t-1\n                    tW = W(:, :, i+1);\n                    tH = shift_t(H, i);\n                    tV = U(:, :, i+1);\n                    % update X\n                    X(:, :, i+1) = (options.rho*tW * tH + tV-alphaX(:, :, i+1)) / (1 + options.rho);\n                end\n\n            elseif options.d_beta == 1\n\n                % update for Kullback-Leibler divergence\n                for i=0:t-1                    \n                    tW = W(:, :, i+1);\n                    tH = shift_t(H, i);\n                    tV = U(:, :, i+1);\n                    % update X\n                    b = options.rho * tW * tH - alphaX(:, :, i+1) - 1;\n                    X(:, :, i+1) = (b + sqrt(b.^2 + 4 * options.rho * tV)) / (2 * options.rho);                \n                end\n\n            elseif options.d_beta == 0\n\n                % update for Itakura-Saito divergence\n                for i=0:t-1\n                    tW = W(:, :, i+1);\n                    tH = shift_t(H, i);\n                    tV = U(:, :, i+1);\n\n                    % parameters for update\n                    A = alphaX(:, :, i+1) / options.rho - tW * tH;\n                    B = 1 / (3 * options.rho) - A.^2/9;\n                    C = - A.^3/27 + A / (6 * options.rho) + tV/(2 * options.rho);\n                    D = B.^3 + C.^2;\n\n                    % update X\n                    tX = X(:, :, i+1);\n                    tX(D>=0) = nthroot(C(D>=0)+sqrt(D(D>=0)),3) + ...\n                    nthroot(C(D>=0)-sqrt(D(D>=0)),3) - ...\n                    A(D>=0)/3;\n\n                    phi = acos(C(D<0) ./ ((-B(D<0)).^1.5));\n                    tX(D<0) = 2*sqrt(-B(D<0)).*cos(phi/3) - A(D<0)/3;\n                    X(:, :, i+1) = tX;\n                end\n            else       \n                error('The options.d_beta you specified is not currently supported.')\n            end          \n\n           % update for dual variables\n            for i=0:t-1\n                tW = W(:, :, i+1);\n                tH = shift_t(H, i);\n                % update alphaX\n                alphaX(:, :, i+1) = alphaX(:, :, i+1) +  options.rho*(X(:, :, i+1)-tW * tH);\n            end       \n        end\n        \n\n        % measure gradient calc count\n        grad_calc_count = grad_calc_count + m*n;\n\n        % measure elapsed time\n        elapsed_time = toc(start_time);        \n\n        % update epoch\n        epoch = epoch + 1;        \n        \n        % store info\n        [Wcon, Hcon] = reconstruct_wh(W, H, t);        \n        infos = store_nmf_info(V, Wcon, Hcon, [], options, infos, epoch, grad_calc_count, elapsed_time);          \n       \n        % display info\n        display_info(method_name, epoch, infos, options);\n\n    end\n\n    W = Wplus;\n    H = Hplus;\n    [W, H] = renormalize_convNMF(W, H);     \n    \n    x.W = W;\n    x.H = H;\n\nend\n\n\nfunction [W_concat, H_concat] = reconstruct_wh(W, H, t)\n    \n    W_concat = [];\n    H_concat = [];  \n    for j = 1 : t\n        W_concat = [W_concat W(:, :,j)];\n        H_concat = [H_concat; shift_t(H, j-1)]; \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/convolutive/admm_seq_conv_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5717373973329957}}
{"text": "function test_bug2338\n\n% MEM 2gb\n% WALLTIME 00:20:00\n% DEPENDENCY ft_prepare_bemmodel ft_prepare_headmodel ft_prepare_leadfield ft_compute_leadfield ft_headmodel_openmeeg \n\n% 4 Layers\nr = [85 88 92 100];\nc = [1 1/20 1/80 1];\n\norder = [1 2 3 4];\n\n% Description of the spherical mesh\n[pnt, tri] = mesh_sphere(42);\n\n% Create a set of electrodes on the outer surface\nelec.elecpos = max(r) * pnt;\nelec.label = {};\nnelec = size(elec.elecpos,1);\nfor ii=1:nelec\n  elec.label{ii} = sprintf('vertex%03d', ii);\nend\n\n% Create one triangulated mesh for each boundary, the first boundary is inside\nmesh = [];\nfor ii=1:length(r)\n  mesh.bnd(ii).pnt = pnt * r(ii);\n  mesh.bnd(ii).tri = tri;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Compute the BEM model using the old code\ncfg = [];\ncfg.method = 'openmeeg';\n\ncfg.conductivity = c(order);\nmesh1 = mesh;\nmesh1.bnd = mesh1.bnd(order);\nvol1 = ft_prepare_bemmodel(cfg, mesh1);\n\n% flip the geometry and conductivity around\norder = [4 3 2 1];\n\ncfg.conductivity = c(order);\nmesh2 = mesh;\nmesh2.bnd = mesh2.bnd(order);\nvol2 = ft_prepare_bemmodel(cfg, mesh2);\n\ncfg = [];\ncfg.sourcemodel.pos = [0 0 70];\ncfg.elec = elec;\ncfg.headmodel = vol1;\nlf1 = ft_prepare_leadfield(cfg);\ncfg.headmodel = vol2;\nlf2 = ft_prepare_leadfield(cfg);\n\nassert(isalmostequal(lf1.leadfield{1}, lf2.leadfield{1}, 'reltol', 1e-6));\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Compute the BEM model using the new code\ncfg = [];\ncfg.method = 'openmeeg';\n\ncfg.conductivity = c(order);\nmesh1 = mesh;\nmesh1.bnd = mesh1.bnd(order);\nvol1 = ft_prepare_headmodel(cfg, mesh1);\n\n% flip the geometry and conductivity around\norder = [4 3 2 1];\n\ncfg.conductivity = c(order);\nmesh2 = mesh;\nmesh2.bnd = mesh2.bnd(order);\nvol2 = ft_prepare_headmodel(cfg, mesh2);\n\ncfg = [];\ncfg.sourcemodel.pos = [0 0 70];\ncfg.elec = elec;\ncfg.headmodel = vol1;\nlf1 = ft_prepare_leadfield(cfg);\ncfg.headmodel = vol2;\nlf2 = ft_prepare_leadfield(cfg);\n\nassert(isalmostequal(lf1.leadfield{1}, lf2.leadfield{1}, 'reltol', 1e-6));\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/obsolete_bug2338.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.571737391924337}}
{"text": "%\n% Bayesian Optimization of Combinatorial Structures\n%\n% Copyright (C) 2018 R. Baptista & M. Poloczek\n%\n% BOCS 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% BOCS 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 BOCS.  If not, see <http://www.gnu.org/licenses/>.\n%\n% Copyright (C) 2018 MIT & University of Arizona\n% Authors: Ricardo Baptista & Matthias Poloczek\n% E-mails: rsb@mit.edu & poloczek@email.arizona.edu\n%\n\n% Script runs discrete optimization algorithms for the\n% contamination control simulation problem. The results are \n% compared for different values of the \\lambda tuning \n% parameter.\n\nclear; close all; clc\naddpath(genpath('../algorithms'))\naddpath(genpath('../stat_model'))\naddpath(genpath('../test_problems/ContStudy'))\naddpath(genpath('../tools'))\n\n%% Setup parameters\n\n% Setup fixed parameters\nn_vars  = 30;\nn_proc  = 1;\ntest_name = 'contamination';\n\n% Number of runs and optimization iterations\nn_func     = 10;\nn_runs     = 10;\nn_init     = 20;\nevalBudget = 270;\n\n% problem parameters (Monte Carlo samples)\nmcSamps = 1e2;\n\n% Variance prior parameters (Inverse Gamma)\naPr    = 2;\nbPr    = 1;\n\n% Regularization parameters\nlambda_vals = [0, 1e-4, 1e-2, 1];\nlambda_str  = {'0', '1em4', '1em2', '1'};\n\n% Set additive regularization function\nreg_term = @(x) sum(x,2);\n\n%% Generate Test Cases\n\n% setup objective functions\ninputs_all = cell(n_func, n_runs);\n\nfor t1=1:n_func\n\n    fprintf('Setting up test function %d\\n', t1);\n\n    % Generate random case study\n    seed = randi(10000,1);\n\n    for t2=1:n_runs\n\n        % Set inputs struct for each problem\n        inputs_all{t1,t2} = struct;\n        inputs_all{t1,t2}.n_vars      = n_vars;\n\n        % Save other definitions\n        inputs_all{t1,t2}.evalBudget  = evalBudget;\n        inputs_all{t1,t2}.n_runs      = n_runs;\n        inputs_all{t1,t2}.n_init      = n_init;\n        inputs_all{t1,t2}.lambda_vals = lambda_vals;\n\n        % Set priors for estimator\n        inputs_all{t1,t2}.aPr         = aPr;\n        inputs_all{t1,t2}.bPr         = bPr;\n\n        % Save objective function and regularization term\n        inputs_all{t1,t2}.model = @(x) contamination_prob(x, mcSamps, seed);\n        inputs_all{t1,t2}.reg_term = @(x) reg_term(x);\n\n        % Generate initial samples for statistical models\n        inputs_all{t1,t2}.x_vals = sample_models(n_init, n_vars);\n        inputs_all{t1,t2}.y_vals = inputs_all{t1,t2}.model(inputs_all{t1,t2}.x_vals);\n\n    end\nend\n\ninputs_all = reshape(inputs_all, n_func*n_runs, 1);\n\n% Make folder\nmkdir(['../results/' test_name])\n\n% Save test cases\nsave(['../results/' test_name '/all_tests'])\n\n% Run cases\nrun_cases(inputs_all, lambda_vals, test_name, n_proc);\n\n% -- END OF FILE --", "meta": {"author": "baptistar", "repo": "BOCS", "sha": "fef0d4e34e376e8bb0dae9955d70c2155530b9eb", "save_path": "github-repos/MATLAB/baptistar-BOCS", "path": "github-repos/MATLAB/baptistar-BOCS/BOCS-fef0d4e34e376e8bb0dae9955d70c2155530b9eb/scripts/opt_runs_cont.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5717373862657555}}
{"text": "function kern = diagKernParamInit(kern)\n\n% DIAGKERNPARAMINIT DIAG kernel parameter initialisation.\n% The diag covariance function takes a one dimensional input and outputs a diagonal noise that is provided by an exponentiated and scaled version of the input.\n%\n% k(x_i, x_j) = delta_ij sigma2 exp(x_i)\n%\n% The only parameter is sigma2, the process variance (kern.variance).\n%\n% SEEALSO : whiteKernParamInit\n%\n% FORMAT\n% DESC initialises the diagonal noise covariance function\n%  kernel structure with some default parameters.\n% ARG kern : the kernel structure which requires initialisation.\n% RETURN kern : the kernel structure with the default parameters placed in.\n%\n% SEEALSO : kernCreate, kernParamInit\n%\n% COPYRIGHT : Neil D. Lawrence, 2011\n\n% KERN\n\nkern.variance = exp(-2);\nkern.nParams = 1;\n\nkern.transforms.index = 1;\nkern.transforms.type = optimiDefaultConstraint('positive');\nkern.trans = optimiDefaultConstraint('positive');\n\n\nkern.isStationary = false;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/diagKernParamInit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5717373754484386}}
{"text": "function DSO3 = refine(DSO3)\n\n\n% step 1: compute center of any two orientation connected by an edge\n\n% all combinations of vertices of all tetrahegons\nv1 = DSO3.tetra(:,[1 1 1 2 2 3]).';\nv2 = DSO3.tetra(:,[2 3 4 3 4 4]).';\n\n% unique edges\nvv = sort([v1(:),v2(:)],2);\n[v,~,iCenterEdges] = unique(vv,'rows');\niCenterEdges = length(DSO3) + reshape(iCenterEdges,6,[]).';\n\n% step 2: set up corner tetrahegons\n% bases\nbase = iCenterEdges(:,[1 2 3  1 4 5  2 4 6  3 5 6]);\nbase = reshape(base.',3,[]);\ncorner = reshape(DSO3.tetra.',1,[]);\n\n% split center octaeder into four tetrahegons\noctaeder = iCenterEdges(:,[1 3 4 5  3 4 5 6  1 2 3 4  2 3 4 6]);\noctaeder = reshape(octaeder.',4,[]);\n\n% set up tetraeder\nnewTetra = [[base;corner],octaeder].';\n\n% new vertices as mean of all edges\ncenterEdges = mean2(DSO3.subSet(v(:,1)),DSO3.subSet(v(:,2)));\n\n% set up refined grid\nDSO3.a = [DSO3.a(:);centerEdges.a];\nDSO3.b = [DSO3.b(:);centerEdges.b];\nDSO3.c = [DSO3.c(:);centerEdges.c];\nDSO3.d = [DSO3.d(:);centerEdges.d];\nDSO3.i = zeros(size(DSO3.d));\n\n% set up new tetrahegons\nDSO3.tetra = sort(newTetra,2);\n\n% compute neighbouring list\nDSO3.tetraNeighbour = calcNeighbour(DSO3.tetra);\n\n% the neighbours of the four corner tetrahegons\n%1 2 3 4\n%cornerNeighbour = \n%DSO3.tetraNeighbour\n\n% set up new lookup\n%DSO3.lookup = DSO3.lookup*8;\n%DSO3.lookup = calcLookUp(DSO3,5*degree);\nDSO3.lookup = [];\nres = 40*degree;\nfor i = 1:3\n  res = res / 2;\n  DSO3.lookup = calcLookUp(DSO3,res);\nend\n\n\nend\n\n% -----------------------------------------------------------------\nfunction v = mean2(v1,v2)\n% compute the mean of two orientations\n\ndv = inv(v1) .* v2;\ndv.SS = specimenSymmetry;\n\n[dv,omega] = dv.project2FundamentalRegion;\n\n% half angle\ndv.a = dv.a .* cos(omega./4) ./ cos(omega./2);\ndv.b = dv.b .* sin(omega./4) ./ sin(omega./2);\ndv.c = dv.c .* sin(omega./4) ./ sin(omega./2);\ndv.d = dv.d .* sin(omega./4) ./ sin(omega./2);\n\n% new vertices\nv = v1 .* dv;\n\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@DelaunaySO3/refine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5717373699148184}}
{"text": "function ppg_filt(up)\n%PPG_FILT extracts respiratory signals using various filtering techniques \n% from the PPG signal as specified in PC's literature review.\n%\t            ppg_filt(option, up)\n%\n%\tInputs:\n%\t\toption          the option which has led to this function being used\n%       up              universal parameters structure\n%\n%\tOutputs:\n%       ... \n%\n\nfprintf('\\n--- Extracting Respiratory Signals from PPG using Filtering Techniques ');\nlog_int_respSig = 0;             % Has value 1 unless this is a final respiratory signal\n\nfor subj = up.paramSet.subj_list\n    \n    %% Cycle through each ppg signal\n    for sig_no = 1 : length(up.paramSet.ppg_sigs)\n        \n        %% Cycle through each method\n        for filt_no = 1 : length(up.al.options.ppg_filt)\n            \n            %% Skip if this processing has been done previously\n            eval(['save_name = ''' up.paramSet.ppg_sigs{sig_no}, up.paths.filenames.filt '_' up.al.options.ppg_filt{filt_no} ''';']);\n            iden_resp_sig_file_ending\n            savepath = [up.paths.data_save_folder, num2str(subj), ending];\n            exist_log = check_exists(savepath, save_name);\n            if exist_log\n                continue\n            end\n            \n            %% Load relevant data\n            if ~exist('data', 'var')\n                load([up.paths.data_load_folder, up.paths.data_load_filename]);\n            end\n            % Extract PPG data\n            eval(['rel_data = data(subj).' up.paramSet.ppg_sigs{sig_no} ';']);\n            \n            %% Filter the raw signal using this method\n            respWave = feval(up.al.options.ppg_filt{filt_no}, rel_data, up);\n            \n            %% Band-pass filter\n            filtered_data = bpf_signal_to_remove_non_resp_freqs(respWave, respWave.fs, up);\n            eval([save_name ' = filtered_data;']);\n            \n            %% Save processed data\n            save_or_append_data\n            \n        end\n        \n    end\n    \nend\n\nend", "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/filt/ppg_filt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6992544335934765, "lm_q1q2_score": 0.5716925834875164}}
{"text": "function b = dppsl ( ap, n, b )\n\n%*****************************************************************************80\n%\n%% DPPSL solves a real symmetric positive definite system factored by DPPCO or DPPFA.\n%\n%  Discussion:\n%\n%    To compute inverse(A) * C where C is a matrix with P columns\n%\n%      call dppco ( ap, n, rcond, z, info )\n%\n%      if ( rcond is too small .or. info /= 0 ) then\n%        exit\n%      end if\n%\n%      do j = 1, p\n%        call dppsl ( ap, n, c(1,j) )\n%      end do\n%\n%    A division by zero will occur if the input factor contains\n%    a zero on the diagonal.  Technically this indicates\n%    singularity but it is usually caused by improper subroutine\n%    arguments.  It will not occur if the subroutines are called\n%    correctly and INFO == 0.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    17 June 2005\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, real AP(N*(N+1)/2), the output from DPPCO or DPPFA.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Input, real B(N), the right hand side.\n%\n%    Output, real B(N), the solution.\n%\n  kk = 0;\n\n  for k = 1 : n\n    t = ddot ( k-1, ap(kk+1:kk+k-1), 1, b(1:k-1), 1 );\n    kk = kk + k;\n    b(k) = ( b(k) - t ) / ap(kk);\n  end\n\n  for k = n : -1 : 1\n    b(k) = b(k) / ap(kk);\n    kk = kk - k;\n    t = -b(k);\n    b(1:k-1) = daxpy ( k-1, t, ap(kk+1:kk+k-1), 1, b(1:k-1), 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/linpack_d/dppsl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6992544335934765, "lm_q1q2_score": 0.5716925710550225}}
{"text": "function M = productmanifold(elements)\n% Returns a structure describing a product manifold M = M1 x M2 x ... x Mn.\n%\n% function M = productmanifold(elements)\n%\n% Input: an elements structure such that each field contains a manifold\n% structure.\n% \n% Output: a manifold structure M representing the manifold obtained by\n% taking the Cartesian product of the manifolds described in the elements\n% structure, with the metric obtainded by element-wise extension. Points\n% and vectors are stored as structures with the same fieldnames as in\n% elements.\n%\n% Example:\n% M = productmanifold(struct('X', spherefactory(3), 'Y', spherefactory(4)))\n% disp(M.name());\n% x = M.rand()\n%\n% Points of M = S^2 x S^3 are represented as structures with two fields, X\n% and Y. The values associated to X are points of S^2, and likewise points\n% of S^3 for the field Y. Tangent vectors are also represented as\n% structures with two corresponding fields X and Y.\n% \n% See also: powermanifold\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%   July  4, 2013 (NB):\n%       Added support for vec, mat, tangent.\n%       Added support for egrad2rgrad and ehess2rhess.\n%       Modified hash function to make hash strings shorter.\n%\n%   Dec. 17, 2018 (NB):\n%       Added check all_elements_provide() to many functions, so that if,\n%       for example, one of the elements does not provide exp(), then the\n%       product manifold also won't provide exp(). This makes it easier for\n%       tools such as, for example, checkgradient, to determine whether exp\n%       is available or not.\n%\n%   Feb. 10, 2020 (NB):\n%       Added warnings about calling egrad2rgrad and ehess2rhess without\n%       storedb and key, even if some base manifolds allow them.\n%\n%   Jan. 4, 2021 (NB):\n%       Changes for compatibility with Octave 6.1.0: by introducing a\n%       \"helper\" function, we separate out the pre-computations. This way,\n%       all pre-computed quantities are passed as input to the helper\n%       function. This makes them available to nested subfunctions.\n%       The extra step is not necessary in Matlab.\n\n\n    elems = fieldnames(elements);\n    nelems = numel(elems);\n    \n    assert(nelems >= 1, ...\n           'elements must be a structure with at least one field.');\n\n    % Below are some precomputations for the mat/vec pair.\n    %\n    % Gather the length of the column vector representations of tangent\n    % vectors for each of the manifolds. Raise a flag if any of the base\n    % manifolds has no vec function available.\n    vec_available = true;\n    vec_lens = zeros(nelems, 1);\n    for ii = 1 : nelems\n        Mi = elements.(elems{ii});\n        if isfield(Mi, 'vec')\n            rand_x = Mi.rand();\n            zero_u = Mi.zerovec(rand_x);\n            vec_lens(ii) = length(Mi.vec(rand_x, zero_u));\n        else\n            vec_available = false;\n            break;\n        end\n    end\n    vec_pos = cumsum([1 ; vec_lens]);\n    %\n    vecmatareisometries = vec_available;\n    for ii = 1 : nelems\n        if ~isfield(elements.(elems{ii}), 'vecmatareisometries') || ...\n           ~elements.(elems{ii}).vecmatareisometries()\n            vecmatareisometries = false;\n            break;\n        end\n    end\n    %\n    % Above are some precomputations for the mat/vec pair.\n    \n    % The helper function is the actual factory.\n    M = productmanifoldhelper(elements, elems, nelems, vec_available, ...\n                              vec_pos, vecmatareisometries);\n    \nend\n\n\nfunction M = productmanifoldhelper(elements, elems, nelems, ...\n                                   vec_available, vec_pos, ...\n                                   vecmatareisometries)\n\n    % Handy function to check if all elements provide the necessary methods\n    function answer = all_elements_provide(method_name)\n        answer = false;\n        for i = 1 : nelems\n            if ~isfield(elements.(elems{i}), method_name)\n                return;\n            end\n        end\n        answer = true;\n    end\n       \n    M.name = @name;\n    function str = name()\n        str = 'Product manifold: ';\n        str = [str sprintf('[%s: %s]', ...\n                           elems{1}, elements.(elems{1}).name())];\n        for i = 2 : nelems\n            str = [str sprintf(' x [%s: %s]', ...\n                   elems{i}, elements.(elems{i}).name())]; %#ok<AGROW>\n        end\n    end\n    \n    M.dim = @dim;\n    function d = dim()\n        d = 0;\n        for i = 1 : nelems\n            d = d + elements.(elems{i}).dim();\n        end\n    end\n    \n    M.inner = @inner;\n    function val = inner(x, u, v)\n        val = 0;\n        for i = 1 : nelems\n            val = val + elements.(elems{i}).inner(x.(elems{i}), ...\n                                               u.(elems{i}), v.(elems{i}));\n        end\n    end\n\n    M.norm = @(x, d) sqrt(M.inner(x, d, d));\n\n    if all_elements_provide('dist')\n        M.dist = @dist;\n    end\n    function d = dist(x, y)\n        sqd = 0;\n        for i = 1 : nelems\n            sqd = sqd + elements.(elems{i}).dist(x.(elems{i}), ...\n                                                 y.(elems{i}))^2;\n        end\n        d = sqrt(sqd);\n    end\n    \n    if all_elements_provide('typicaldist')\n        M.typicaldist = @typicaldist;\n    end\n    function d = typicaldist\n        sqd = 0;\n        for i = 1 : nelems\n            sqd = sqd + elements.(elems{i}).typicaldist()^2;\n        end\n        d = sqrt(sqd);\n    end\n\n    M.proj = @proj;\n    function v = proj(x, u)\n        for i = 1 : nelems\n            v.(elems{i}) = elements.(elems{i}).proj(x.(elems{i}), ...\n                                                    u.(elems{i}));\n        end\n    end\n\n    M.tangent = @tangent;\n    function v = tangent(x, u)\n        for i = 1 : nelems\n            v.(elems{i}) = elements.(elems{i}).tangent(x.(elems{i}), ...\n                                                       u.(elems{i}));\n        end\n    end\n\n    % True by default, false if any false encountered\n    M.tangent2ambient_is_identity = true;\n    for k = 1 : nelems\n        if isfield(elements.(elems{k}), 'tangent2ambient_is_identity')\n            if ~elements.(elems{k}).tangent2ambient_is_identity\n                M.tangent2ambient_is_identity = false;\n                break;\n            end\n        end\n    end\n    \n    M.tangent2ambient = @tangent2ambient;\n    function v = tangent2ambient(x, u)\n        for i = 1 : nelems\n            if isfield(elements.(elems{i}), 'tangent2ambient')\n                v.(elems{i}) = ...\n                    elements.(elems{i}).tangent2ambient( ...\n                                               x.(elems{i}), u.(elems{i}));\n            else\n                v.(elems{i}) = u.(elems{i});\n            end\n        end\n    end\n\n    M.egrad2rgrad = @egrad2rgrad;\n    function g = egrad2rgrad(x, g)\n        for i = 1 : nelems\n            g.(elems{i}) = elements.(elems{i}).egrad2rgrad(...\n                                               x.(elems{i}), g.(elems{i}));\n        end\n    end\n    for ii = 1 : nelems\n        if nargin(elements.(elems{ii}).egrad2rgrad) > 2\n            warning('manopt:productmanifold:egrad2rgrad', ...\n                   ['Product manifolds call M.egrad2rgrad with only two ', ...\n                    'inputs:\\nstoredb and key won''t be available.']);\n            break;\n        end\n    end\n\n    M.ehess2rhess = @ehess2rhess;\n    function h = ehess2rhess(x, eg, eh, h)\n        for i = 1 : nelems\n            h.(elems{i}) = elements.(elems{i}).ehess2rhess(...\n                 x.(elems{i}), eg.(elems{i}), eh.(elems{i}), h.(elems{i}));\n        end\n    end\n    for ii = 1 : nelems\n        if nargin(elements.(elems{ii}).ehess2rhess) > 4\n            warning('manopt:productmanifold:ehess2rhess', ...\n                   ['Product manifolds call M.ehess2rhess with only two ', ...\n                    'inputs:\\nstoredb and key won''t be available.']);\n            break;\n        end\n    end\n    \n    if all_elements_provide('exp')\n        M.exp = @exp;\n    end\n    function y = exp(x, u, t)\n        if nargin < 3\n            t = 1.0;\n        end\n        for i = 1 : nelems\n            y.(elems{i}) = elements.(elems{i}).exp(x.(elems{i}), ...\n                                                   u.(elems{i}), t);\n        end\n    end\n    \n    M.retr = @retr;\n    function y = retr(x, u, t)\n        if nargin < 3\n            t = 1.0;\n        end\n        for i = 1 : nelems\n            y.(elems{i}) = elements.(elems{i}).retr(x.(elems{i}), ...\n                                                    u.(elems{i}), t);\n        end\n    end\n    \n    if all_elements_provide('log')\n        M.log = @log;\n    end\n    function u = log(x1, x2)\n        for i = 1 : nelems\n            u.(elems{i}) = elements.(elems{i}).log(x1.(elems{i}), ...\n                                                   x2.(elems{i}));\n        end\n    end\n\n    M.hash = @hash;\n    function str = hash(x)\n        str = '';\n        for i = 1 : nelems\n            str = [str elements.(elems{i}).hash(x.(elems{i}))]; %#ok<AGROW>\n        end\n        str = ['z' hashmd5(str)];\n    end\n\n    M.lincomb = @lincomb;\n    function v = lincomb(x, a1, u1, a2, u2)\n        if nargin == 3\n            for i = 1 : nelems\n                v.(elems{i}) = elements.(elems{i}).lincomb(x.(elems{i}), ...\n                                                        a1, u1.(elems{i}));\n            end\n        elseif nargin == 5\n            for i = 1 : nelems\n                v.(elems{i}) = elements.(elems{i}).lincomb(x.(elems{i}), ...\n                                     a1, u1.(elems{i}), a2, u2.(elems{i}));\n            end\n        else\n            error('Bad usage of productmanifold.lincomb');\n        end\n    end\n\n    M.rand = @rand;\n    function x = rand()\n        for i = 1 : nelems\n            x.(elems{i}) = elements.(elems{i}).rand();\n        end\n    end\n\n    M.randvec = @randvec;\n    function u = randvec(x)\n        for i = 1 : nelems\n            u.(elems{i}) = elements.(elems{i}).randvec(x.(elems{i}));\n        end\n        u = M.lincomb(x, 1/sqrt(nelems), u);\n    end\n\n    M.zerovec = @zerovec;\n    function u = zerovec(x)\n        for i = 1 : nelems\n            u.(elems{i}) = elements.(elems{i}).zerovec(x.(elems{i}));\n        end\n    end\n\n    if all_elements_provide('transp')\n        M.transp = @transp;\n    end\n    function v = transp(x1, x2, u)\n        for i = 1 : nelems\n            v.(elems{i}) = elements.(elems{i}).transp(x1.(elems{i}), ...\n                                              x2.(elems{i}), u.(elems{i}));\n        end\n    end\n\n    if all_elements_provide('pairmean')\n        M.pairmean = @pairmean;\n    end\n    function y = pairmean(x1, x2)\n        for i = 1 : nelems\n            y.(elems{i}) = elements.(elems{i}).pairmean(x1.(elems{i}), ...\n                                                        x2.(elems{i}));\n        end\n    end\n    \n    if vec_available\n        M.vec = @vec;\n        M.mat = @mat;\n    end\n    \n    function u_vec = vec(x, u_mat)\n        u_vec = zeros(vec_pos(end)-1, 1);\n        for i = 1 : nelems\n            range = vec_pos(i) : (vec_pos(i+1)-1);\n            u_vec(range) = elements.(elems{i}).vec(x.(elems{i}), ...\n                                                   u_mat.(elems{i}));\n        end\n    end\n\n    function u_mat = mat(x, u_vec)\n        u_mat = struct();\n        for i = 1 : nelems\n            range = vec_pos(i) : (vec_pos(i+1)-1);\n            u_mat.(elems{i}) = elements.(elems{i}).mat(x.(elems{i}), ...\n                                                       u_vec(range));\n        end\n    end\n\n    M.vecmatareisometries = @() vecmatareisometries;    \n    \n    if all_elements_provide('lie_identity')\n        M.lie_identity = @lie_identity;\n    end\n\n    function I = lie_identity()\n        I = struct();\n        for i = 1 : nelems\n            Mi = elements.(elems{i});\n            Ii = Mi.lie_identity();\n            I.(elems{i}) = Ii;\n        end\n    end\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/tools/productmanifold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.571692567023204}}
{"text": "function testBranin(varargin)\n\nrun_high_dim = 0;\nembedding = 1;\nembedding_consecutive = 0;\ntest_percentage = 0;\n\ntotal_iter = 500;\nhigh_dim = 25;\nrotate = 0;\n\n%% Test the percentage of success\nif test_percentage\n    dim = 2;                                         % Intrinsic Dimensionality.\n    used_dim = 2;                                              % Dimension used.\n    \n    maximizers = trueMaximizer();\n    scale = max(1.5*log(used_dim));\n    test_bounds = stardardBounds(dim)*scale;                  % Standard Bounds.    \n    \n    prct = success_prctg(high_dim, 1000, dim, used_dim, test_bounds, ...\n        maximizers);                         % Success Percentage by simulation.\n    \n    fprintf('Success Percentage by using %d dimensions is approximately: \\n%f.\\n', ...\n        used_dim, prct);\nend\n\n\n%% Random embedding with true intrisic dimensions\n%  True maximum is ensured to fall in to the bounds\nif embedding\n    dim = 2;\n    model = rembo(total_iter, dim, high_dim, rotate, 1);\n    ditance_log_plot(total_iter, model.f);\nend\n\n\n%% Random embedding with true intrisic dimensions\n%  True maximum is NOT ensured to fall in to the bounds\n%  Runs are repeated to ensure covering of the true maximum\nif embedding_consecutive\n    dim = 2;\n    rotate = 0;\n    run_iter = 125; num_trial = 4;\n    f_values = zeros(run_iter*num_trial,1);\n    \n    for i = 1:num_trial\n        model = rembo(run_iter, dim, high_dim, rotate);\n        f_values((i-1)*run_iter+1:i*run_iter) = model.f;    \n    end    \n\n    ditance_log_plot(run_iter*num_trial, f_values);\nend\n\n\n%% High Dim\nif run_high_dim\n    rotate = 0;\n    model = rembo(total_iter, high_dim, high_dim, rotate, 0, 0);\n    \n    ditance_log_plot(total_iter, model.f);\nend\n\n\n%% Run rembo.\n    function model = rembo(total_iter, dim, high_dim, rotate, force_in_bounds, ...\n        embed)\n        % total_iter: total number of iterations.\n        % dim: embedding dimension.\n        % high_dim: ambient dimension.\n        % roate: whether to randomly rotate the objective function.\n        % force_in_bounds: to force an optimizer in bound by repeatly drawing\n        %                  random embedding matrices.\n        % embed: Whether to use a randome embedding matrix. (If not \n        %        then we effectively use regular BO.)\n\n        \n    \n        if nargin < 5\n            force_in_bounds = 0;       % Whether to force an optimizer in bound.\n        end\n\n        if nargin < 6\n            embed = 1;                        % Whether to use embedding or not.\n        end\n\n        if rotate\n            % Rotate the objective function.\n            [rm, ~] = qr(randn(high_dim, high_dim), 0);\n        else\n            % Do not rotate the objective function.\n            rm = eye(high_dim);\n        end\n\n        if embed\n            % Generate random projection matrix A.\n            [in_bounds, A] = test_fall_in_bound(dim, rm);       \n            while ~in_bounds && force_in_bounds\n                % Ensure that at least one maximizer fall in bound by \n                % generating as many random projection matrix A as needed.\n                [in_bounds, A] = test_fall_in_bound(dim, rm);\n            end\n        else\n            % By setting A to be identity we do not use embedding here.\n            A = eye(high_dim, dim);\n        end\n\n        scale = max(1.5*log(dim), 1);\n        bounds = stardardBounds(dim)*scale;                 % Initialize bounds.\n        obj_fct = @(x)-branin((A*x')');     % Initialize the objective function.\n\n        init_pt = zeros(1, dim);                                % Initial point.\n        init_f = obj_fct(init_pt);                     % Evaluate initial point.\n\n        hyp = [ones(dim, 1)*0.1 ; 1];          % Setup initial hyper-parameters.\n        hyp = log(hyp);\n\n        % Initialize model.\n        model = init_model(dim, bounds, init_pt, init_f, hyp, 1e-10, 'ard');\n        % Do optimization.\n        model = sparse_opt(obj_fct, total_iter-1, model);\n    end\n\n%% Helper functions.\n    function ditance_log_plot(total_iter, fvalues)\n        maximazer = trueMaximizer();\n        figure;\n        dis = zeros(total_iter,1);\n        for i =1:total_iter\n            dis(i) = -branin(maximazer(:, 1)') - max(fvalues(1:i));\n        end\n        loglog(1:total_iter, dis); \n    end\n\n    function [in_bounds, A] = test_fall_in_bound(used_dim, rm)\n        maximizers = trueMaximizer();\n        test_bounds = stardardBounds(2);\n        scale = max(1.5*log(used_dim));\n        test_bounds = test_bounds*scale;\n\n        [prct, A] = success_prctg(high_dim, 1, 2, used_dim, test_bounds,...\n            maximizers, rm);\n        in_bounds =  prct;\n        \n        if in_bounds\n            fprintf('At least one maximizer in bounds.\\n');\n        else\n            fprintf('NO maximizer in bounds.\\n');\n        end\n    end\n\n\n    function [maximizers] = trueMaximizer() \n        bounds_branin = [-5,10; 0, 15];\n        maximizers = [pi, -pi, 9.42478; 2.275, 12.275, 2.475];\n        maximizers = bsxfun(@minus, maximizers, bounds_branin(:, 1));\n        maximizers = bsxfun(@rdivide, maximizers, bounds_branin(:, 2) - ...\n            bounds_branin(:, 1))*2-1;\n    end\n\n    function [prct, A] = success_prctg(high_dim, num_trial, dim,...\n        used_dim, bounds, maximizers, rm)\n\n        total = 0;\n        cmbnts = combntns(1:used_dim,dim);\n        num_maximizers = size(maximizers, 2);\n\n        for i = 1:num_trial\n            indices = 1:high_dim;\n            A = randn(high_dim, used_dim);\n\n            if nargin > 6\n                A = rm*A;\n            end\n            fail = 1;\n\n            for j = 1:size(cmbnts, 1)\n                for k = 1:num_maximizers\n                    true_maximizer = inv(A(indices(1:dim), cmbnts(j, :))) * ...\n                        maximizers(:, k);\n                    if ~(sum(true_maximizer <= bounds(:,2)) < dim || ...\n                        sum(true_maximizer >= bounds(:,1)) < dim)\n                        fail = 0;\n                    end\n                end\n            end\n            total = total + fail;\n        end\n        prct = 1 - total/num_trial;\n    end\nend", "meta": {"author": "ziyuw", "repo": "rembo", "sha": "7926c00a802ad33e7c7f61e3571a32bacaba3d00", "save_path": "github-repos/MATLAB/ziyuw-rembo", "path": "github-repos/MATLAB/ziyuw-rembo/rembo-7926c00a802ad33e7c7f61e3571a32bacaba3d00/demos/branin/testBranin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5716925659309898}}
{"text": "% SP_EVALUATE_ELEMENT_LIST_PARAM: compute the basis functions, in the parametric domain, in a given list of elements.\n%\n%     sp = sp_evaluate_element_list_param (space, msh_elems, 'option1', value1, ...)\n%\n% INPUTS:\n%     \n%    space:   object defining the space of discrete functions (see sp_vector)\n%    msh_elems: msh structure containing the information of quadrature or\n%               visualization points, for a given list of elements \n%               (see msh_cartesian/msh_evaluate_element_list)\n%   'option', value: additional optional parameters, currently available options are:\n%            \n%              Name     |   Default value |  Meaning\n%           ------------+-----------------+----------------------------------\n%            value      |      true       |  compute shape_functions\n%            gradient   |      false      |  compute shape_function_gradients\n%            divergence |      false      |  compute shape_function_divs\n%            curl       |      false      |  compute shape_function_curls\n%            hessian    |      false      |  compute shape_function_hessians\n%\n% OUTPUT:\n%\n%    sp: struct representing the discrete function space, with the following fields:\n%              (see the article for a detailed description)\n%\n%    FIELD_NAME      (SIZE)                                     DESCRIPTION\n%    ncomp           (scalar)                                   number of components of the functions of the space\n%    ndof            (scalar)                                   total number of degrees of freedom\n%    ndof_dir        (ncomp_param x ndim matrix)                for each component, number of degrees of freedom along each direction\n%    nsh_max         (scalar)                                   maximum number of shape functions per element\n%    nsh             (1 x msh_col.nel vector)                   actual number of shape functions per each element\n%    connectivity    (nsh_max x msh_col.nel vector)             indices of basis functions that do not vanish in each element\n%    shape_functions (ncomp_param x msh_col.nqn x nsh_max x msh_col.nel)  basis functions evaluated at each quadrature node in each element\n%    shape_function_gradients\n%       (ncomp_param x ndim x msh_col.nqn x nsh_max x msh_col.nel) basis function gradients evaluated at each quadrature node in each element\n%    shape_function_hessians\n%       (ncomp_param x ndim x ndim x msh_col.nqn x nsh_max x msh_col.nel) basis function hessians evaluated at each quadrature node in each element\n%    shape_function_divs (msh_col.nqn x nsh_max x msh_col.nel)     basis function divergence evaluated at each quadrature node in each element\n%    shape_function_curls \n%         2D:  (msh_col.nqn x nsh_max x msh_col.nel)               basis function curl evaluated at each quadrature node in each element\n%         3D:  (3 x msh_col.nqn x nsh_max x msh_col.nel)        \n%\n% Copyright (C) 2009, 2010, 2011 Carlo de Falco\n% Copyright (C) 2011, 2015, 2019 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 <http://www.gnu.org/licenses/>.\n\nfunction sp = sp_evaluate_element_list_param (space, msh, varargin)\n\nvalue = true;\ngradient = false;\ndivergence = false;\ncurl = false;\nhessian = false;\nif (~isempty (varargin))\n  if (~rem (length (varargin), 2) == 0)\n    error ('sp_evaluate_element_list_param: options must be passed in the [option, value] format');\n  end\n  for ii=1:2:length(varargin)-1\n    if (strcmpi (varargin {ii}, 'value'))\n      value = varargin {ii+1};\n    elseif (strcmpi (varargin {ii}, 'gradient'))\n      gradient = varargin {ii+1};\n    elseif (strcmpi (varargin {ii}, 'curl'))\n      curl = varargin {ii+1};\n    elseif (strcmpi (varargin {ii}, 'divergence'))\n      divergence = varargin {ii+1};\n    elseif (strcmpi (varargin {ii}, 'hessian'))\n      hessian = varargin {ii+1};\n    else\n      warning ('Ignoring unknown option %s', varargin {ii});\n    end\n  end\nend\n\nfirst_der = gradient || divergence || curl;\nfor icomp = 1:space.ncomp_param\n  sp_col_scalar(icomp) = sp_evaluate_element_list_param (space.scalar_spaces{icomp}, msh, 'value', value, 'gradient', first_der, 'hessian', hessian);\nend\n\nndof_scalar = [sp_col_scalar.ndof];\n\nndof = sum (ndof_scalar);\nnsh  = zeros (1, msh.nel);\nconnectivity = [];\naux = 0;\nfor icomp = 1:space.ncomp_param\n  ndof_dir(icomp,:) = sp_col_scalar(icomp).ndof_dir;\n  nsh = nsh + sp_col_scalar(icomp).nsh(:)';\n  \n  inds = find (sp_col_scalar(icomp).connectivity);\n  sp_col_scalar(icomp).connectivity(inds) = sp_col_scalar(icomp).connectivity(inds) + aux;\n  connectivity = [connectivity; sp_col_scalar(icomp).connectivity];\n  aux = aux + ndof_scalar(icomp);\nend\n\nsp = struct('nsh_max', space.nsh_max, 'nsh', nsh, 'ndof', ndof,  ...\n            'ndof_dir', ndof_dir, 'connectivity', connectivity, ...\n            'ncomp', space.ncomp, 'ncomp_param', space.ncomp_param);\n\nif (value)\n  sp.shape_functions = zeros (sp.ncomp_param, msh.nqn, sp.nsh_max, msh.nel);\n  for icomp = 1:space.ncomp_param\n    indices = space.cumsum_nsh(icomp)+(1:sp_col_scalar(icomp).nsh_max);\n    sp.shape_functions(icomp,:,indices,:) = sp_col_scalar(icomp).shape_functions;\n  end\nend\n\nif (gradient || curl || divergence)\n  shape_fun_grads = zeros (space.ncomp_param, msh.ndim, msh.nqn, sp.nsh_max, msh.nel);\n\n  for icomp = 1:space.ncomp_param\n    indices = space.cumsum_nsh(icomp)+(1:sp_col_scalar(icomp).nsh_max);\n    shape_fun_grads(icomp,:,:,indices,:) = sp_col_scalar(icomp).shape_function_gradients;\n  end\n  \n  if (gradient)\n    sp.shape_function_gradients = shape_fun_grads;\n  end\n\n  if (divergence)\n    sp.shape_function_divs = zeros (msh.nqn, sp.nsh_max, msh.nel);\n    for icomp = 1:space.ncomp_param\n      sp.shape_function_divs = sp.shape_function_divs + ...\n        reshape (shape_fun_grads(icomp,icomp,:,:,:), msh.nqn, sp.nsh_max, msh.nel);\n    end\n  end\n\n  if (curl)\n    if (space.ncomp_param == 2)\n      sp.shape_function_curls = reshape (shape_fun_grads(2,1,:,:,:) - ...\n\t \t       shape_fun_grads(1,2,:,:,:), msh.nqn, sp.nsh_max, msh.nel);\n    elseif (space.ncomp_param == 3)\n      shape_fun_curls = zeros (space.ncomp, msh.nqn, sp.nsh_max, msh.nel);\n      for icomp = 1:space.ncomp\n        ind1 = mod(icomp,3) + 1;\n        ind2 = mod(ind1, 3) + 1;\n        shape_fun_curls(icomp,:,:,:) = reshape (shape_fun_grads(ind2,ind1,:,:,:) - ...\n                   shape_fun_grads(ind1,ind2,:,:,:), 1, msh.nqn, sp.nsh_max, msh.nel);\n      end\n      sp.shape_function_curls = shape_fun_curls;\n    end\n  end\nend\n\nif (hessian)\n  sp.shape_function_hessians = zeros (space.ncomp, msh.ndim, msh.ndim, msh.nqn, sp.nsh_max, msh.nel);\n  for icomp = 1:space.ncomp_param\n    indices = space.cumsum_nsh(icomp)+(1:sp_col_scalar(icomp).nsh_max);\n    sp.shape_function_hessians(icomp,:,:,:,indices,:) = sp_col_scalar(icomp).shape_function_hessians;\n  end\nend\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_vector/sp_evaluate_element_list_param.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5716925648387752}}
{"text": "function G = Grid2GlinearROI(Grid,Grid_dec,npxdtc,ctrIdx,block,interp,nblk,vmsk,nnzmsk)\n% Grid2Glinear\n% input Grid/s generated in fbkp_geometry\n% -Grid is a matrix of integers that are coordinate of the detector pixel\n% -Grid_dec is [] is the 'nearest neighbour' interp option is used\n% -block (integer & scalar) sets the projection undergoing backprojection\n% -nblk number of blocks (i.e. projections) used to make up the (rows) sparse matrix\n% i.e. the the large block goes from block (i.e. projection) to block + nblk\n% -vmsk is the mask as a vector (logical)\n% -npxdtc number of detector pixels ( nb in Glinear)\n% output one sparse matrix G as by Glinear (see Fessler code)\n%\n% Gianni Schena March  2003\n\nG=[];\nblock\nnargin\n\nNx=size(Grid(:,:,1),1); Ny=size(Grid(:,:,1),2); % get the size of the problem\nnm=Nx*Ny\n%\n\nif nargin < 8\n\tvmsk=logical(ones(1,nm)); nnzmsk=nm;\n\t% define default mask - if the mask is not an input parameter\nend\n\nif nargin < 7, nblk=1, end\n\n%SPALLOC(M,N,NZMAX) creates an M-by-N all zero sparse matrix with room to eventually hold NZMAX nonzeros.\n\nif strcmp(interp, 'nearest neighbor')\n\tG = spalloc(nblk*npxdtc,nnzmsk, nblk*nnzmsk);\nelse\n\tG = spalloc(nblk*npxdtc,nnzmsk, 2*nblk*nnzmsk); % pre-allocation\nend\n\njc=[1:1:nnzmsk]; % index of columns in the matrix G\n\nfor ib=1:nblk % for nblk projections and starting from block\n\n\tGv=Grid(:,:,block+ib-1) ; Gv=Gv(:) ; % starts from block\n\tir = double(Gv) + ctrIdx  ; % the coordinate (saved as 'round') + centre\n\tir=[ir+npxdtc*(ib-1)]; ir=ir(vmsk)';\n\n\t% S = SPARSE(i,j,s,m,n,nzmax) uses the rows of [i,j,s] to generate an\n\t% m-by-n sparse matrix with space allocated for nzmax nonzeros.\n\n\tif strcmp(interp, 'nearest neighbor')\n\t\tv=1.;\n\t\tT=sparse(ir,jc,double(v),npxdtc*nblk,nnzmsk);\n\n\telse % i.e. interp == linear\n\t\tdec=double(Grid_dec(:,:,block+ib-1))/100; % use also the decimal saved as integer\n\t\tvc = dec(:); % weight for (floor +1) == weight of 'ceil' term\n\t\tvc=vc(vmsk);\n\t\tT= [sparse(ir,jc,(1-vc),npxdtc*(nblk),nnzmsk) + sparse(ir+1,jc,vc,npxdtc*(nblk),nnzmsk)];\n\t\t%T= [sparse(ir,jc',(1-vc)) + sparse([ir+1],jc',vc)];\n\tend\n\n\tG=[G+T];\nend % end ib\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/Grid2GlinearROI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5716853693824815}}
{"text": "function A = makehatch(hatch)\n%MAKEHATCH Predefined hatch patterns\n%  MAKEHATCH(HATCH) returns a matrix with the hatch pattern for HATCH\n%   according to the following table:\n%      HATCH        pattern\n%     -------      ---------\n%        /          right-slanted lines\n%        \\          left-slanted lines\n%        |          vertical lines\n%        -          horizontal lines\n%        +          crossing vertical and horizontal lines\n%        x          criss-crossing lines\n%        .          single dots\n%\n%  See also: APPLYHATCH\n\n%  By Ben Hinkle, bhinkle@mathworks.com\n%  This code is in the public domain.\n\nn = 6;\nA=zeros(n);\nswitch (hatch)\ncase '/'\n  A = fliplr(eye(n));\ncase '\\'\n  A = eye(n);\ncase '|'\n  A(:,1) = 1;\ncase '-'\n  A(1,:) = 1;\ncase '+'\n  A(:,1) = 1;\n  A(1,:) = 1;\ncase 'x'\n  A = eye(n) | fliplr(diag(ones(n-1,1),-1));\ncase '.'\n  A(1:2,1:2)=1;\notherwise\n  error(['Undefined hatch pattern \"' hatch '\".']);\nend", "meta": {"author": "jacoxu", "repo": "STC2", "sha": "34a28c5a8cf2d6e1db300d32f271f6522db3bde5", "save_path": "github-repos/MATLAB/jacoxu-STC2", "path": "github-repos/MATLAB/jacoxu-STC2/STC2-34a28c5a8cf2d6e1db300d32f271f6522db3bde5/software/DCNN/makehatch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.5716853686551138}}
{"text": "function results = vl_test_binsearch(varargin)\n% VL_TEST_BINSEARCH\nvl_test_init ;\n\nfunction test_inf_bins()\nx = [-inf -1 0 1 +inf] ;\nvl_assert_equal(vl_binsearch([],          x), [0 0 0 0 0]) ;\nvl_assert_equal(vl_binsearch([-inf 0],    x), [1 1 2 2 2]) ;\nvl_assert_equal(vl_binsearch([-inf],      x), [1 1 1 1 1]) ;\nvl_assert_equal(vl_binsearch([-inf +inf], x), [1 1 1 1 2]) ;\n\nfunction test_empty()\nvl_assert_equal(vl_binsearch([], []), []) ;\n\nfunction test_bnd()\nvl_assert_equal(vl_binsearch([], [1]),    [0]) ;\nvl_assert_equal(vl_binsearch([], [-inf]), [0]) ;\nvl_assert_equal(vl_binsearch([], [+inf]), [0]) ;\n\nvl_assert_equal(vl_binsearch([1], [.9]),   [0]) ;\nvl_assert_equal(vl_binsearch([1], [1]),    [1]) ;\nvl_assert_equal(vl_binsearch([1], [-inf]), [0]) ;\nvl_assert_equal(vl_binsearch([1], [+inf]), [1]) ;\n\nfunction test_basic()\nvl_assert_equal(vl_binsearch(-10:10, -10:10), 1:21) ;\nvl_assert_equal(vl_binsearch(-10:10, -11:10), 0:21) ;\nvl_assert_equal(vl_binsearch(-10:10, [-inf, -11:10, +inf]), [0 0:21 21]) ;\n\nfunction test_frac()\nvl_assert_equal(vl_binsearch(1:10, 1:.5:10), floor(1:.5:10))\nvl_assert_equal(vl_binsearch(1:10, fliplr(1:.5:10)), ...\n                fliplr(floor(1:.5:10))) ;\n\nfunction test_array()\na = reshape(1:100,10,10) ;\nb = reshape(1:.5:100.5, 2, []) ;\nc = floor(b) ;\nvl_assert_equal(vl_binsearch(a,b), c) ;\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/xtest/vl_test_binsearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5716853667014818}}
{"text": "function obox = orientedBox(points)\n%ORIENTEDBOX Minimum-width oriented bounding box of a set of points\n%\n%   OBOX = orientedBox(PTS)\n%   Computes the oriented bounding box of a set of points. Oriented box is\n%   defined by a center, two dimensions (the length and the width), and the\n%   orientation of the length axis. Orientation is counted in degrees, \n%   counter-clockwise.\n%\n%   Example\n%     % Draw oriented bounding box of an ellipse\n%     elli = [30 40 40 20 30];\n%     pts = ellipseToPolygon(elli, 120);\n%     obox = orientedBox(pts);\n%     figure; hold on;\n%     drawEllipse(elli);\n%     drawOrientedBox(obox, 'm');\n%\n%   See also\n%   drawOrientedBox, orientedBoxToPolygon\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@nantes.inra.fr\n% Created: 2012-03-29,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n\n%% initialisations\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% compute convex hull centroid, that corresponds to approximate\n% location of rectangle center\ncenter = mean(hull, 1);\nhull = bsxfun(@minus, hull, center);\n\n% number of hull vertices\nnV = size(hull, 1);\n\n% default values\nrotatedAngle = 0;\nminWidth = inf;\nminAngle = 0;\n\n% avoid degenerated cases\nif nV < 3\n    return;\nend\n\n% indices of vertices in extreme y directions\n[tmp, indA] = min(hull(:, 2)); %#ok<ASGLU>\n[tmp, indB] = max(hull(:, 2)); %#ok<ASGLU>\n\ncaliperA = [ 1 0];    % Caliper A points along the positive x-axis\ncaliperB = [-1 0];    % Caliper B points along the negative x-axis\n\n\n%% Find the direction with minimum width (rotating caliper algorithm)\n\nwhile rotatedAngle < pi\n    % compute the direction vectors corresponding to each edge\n    indA2 = mod(indA, nV) + 1;\n    vectorA = hull(indA2, :) - hull(indA, :);\n    \n    indB2 = mod(indB, nV) + 1;\n    vectorB = hull(indB2, :) - hull(indB, :);\n    \n    % Determine the angle between each caliper and the next adjacent edge\n    % in the polygon \n    angleA = vectorAngle(caliperA, vectorA);\n    angleB = vectorAngle(caliperB, vectorB);\n    \n    % Determine the smallest of these angles\n    angleIncrement = min(angleA, angleB);\n    \n    % Rotate the calipers by the smallest angle\n    caliperA = rotateVector(caliperA, angleIncrement);\n    caliperB = rotateVector(caliperB, angleIncrement);\n    \n    rotatedAngle = rotatedAngle + angleIncrement;\n    \n    % compute current width, and update opposite vertex\n    if angleA < angleB\n        line = createLine(hull(indA, :), hull(indA2, :));\n        width = distancePointLine(hull(indB, :), line);\n        indA = mod(indA, nV) + 1;\n    \n    else\n        line = createLine(hull(indB, :), hull(indB2, :));\n        width = distancePointLine(hull(indA, :), line);\n        indB = mod(indB, nV) + 1;\n\n    end\n    \n    % update minimum width and corresponding angle if needed\n    if width < minWidth\n        minWidth = width;\n        minAngle = rotatedAngle;\n    end\nend\n\n\n%% Compute box dimensions\n\n% orientation of the main axis\ntheta = rad2deg(minAngle);\n\n% pre-compute trigonometric functions\ncot = cos(minAngle);\nsit = sin(minAngle);\n\n% elongation in direction of rectangle length\nx = hull(:,1);\ny = hull(:,2);\nx2  =   x * cot + y * sit;\ny2  = - x * sit + y * cot;\n\n% compute extension along main directions\nxmin = min(x2);    xmax = max(x2);\nymin = min(y2);    ymax = max(y2);\n\n% position of the center with respect to the centroid compute before\ndl = (xmax + xmin)/2;\ndw = (ymax + ymin)/2;\n\n% change  coordinate from rectangle to user-space\ndx  = dl * cot - dw * sit;\ndy  = dl * sit + dw * cot;\n\n% coordinates of oriented box center\ncenter = center + [dx dy];\n\n% size of the rectangle\nrectLength  = xmax - xmin;\nrectWidth   = ymax - ymin;\n\n% concatenate rectangle data\nobox = [center rectLength rectWidth theta];\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/geom2d/orientedBox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5716853667014818}}
{"text": "function test04 ( dim_num, n, z )\n\n%*****************************************************************************80\n%\n%% TEST04 tests GAMMA_MEASURE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    05 November 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST04\\n' );\n  fprintf ( 1, '  GAMMA_MEASURE computes the GAMMA measure of quality.\\n' );\n  fprintf ( 1, '  The mesh ratio               Gamma = %14f\\n', ...\n    gamma_measure ( dim_num, n, z ) );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quality/quality_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.5716853630436656}}
{"text": "function view = computeProbMap(view,scanList)\n%\n% view = computeProbMap(view,[scanList])\n%\n% Cycles through tSeries, computing the -log10 P values\n% for each voxel. This is a first pass at a P map - not taking into account\n% the non-gaussian properties of the spatio-temporal noise distribution.\n%\n% scanList: \n%   0 - do all scans\n%   number or list of numbers - do only those scans\n%   default - prompt user via selectScans dialog\n%\n% Based on computeMeanMap\n% and  Bantettini el al, 1993, \n% Processing Strategies for Time Course Data Sets\n% MRM 30:161-173 (1993) pp 171\n% \n\nnScans = numScans(view);\nlogProb=cell(1,nScans);\nif strcmp(view.mapName,'logProbMap')\n    % If exists, initialize to existing map\n    map=view.map;\nelse\n    % Otherwise, initialize to empty cell array\n    map = cell(1,nScans);\nend\n\n% (Re-)set scanList\nif ~exist('scanList','var')\n    scanList = selectScans(view);\nelseif scanList == 0\n    scanList = 1:nScans;\nend\nif isempty(scanList)\n    error('Analysis aborted');\nend\n\n% Compute it\nwaitHandle = mrvWaitbar(0,'Computing log10 P values from the tSeries.  Please wait...');\nncScans = length(scanList);\nfor iScan = 1:ncScans\n    scan = scanList(iScan);\n    nFrames=numFrames(view,scan);\n    \n    logProb{scanList(iScan)}=-(log10(computeCoherenceSignificance(view.co{scanList(iScan)},nFrames)));\n    \n    mrvWaitbar(scan/ncScans)\nend\nclose(waitHandle);\n\n% Set parameter map\nview = setParameterMap(view,logProb,'log10Prob');\n\n% Save file\nsaveParameterMap(view);\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/SignalProc/computeProbMap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.571657964406057}}
{"text": "randinit\nclf\nhold on\ng = PGraph(3);\n\nsim_time = 2;\n\nxinit = [0, 0, 0];\nplot(xinit(1), xinit(2), 'go');\nrho = 1;\n\ng.add_node(xinit);\nt =2;\n\nfor k=1:500\n    % Step 3\n    % find random state x,y in [-10, 10], th in [0 2pi]\n    x = (rand-0.5)*20;\n    y = (rand-0.5)*20;\n    theta = rand*2*pi;\n    xrand = [x, y, theta]';\n    xrand'\n\n    % Step 4\n    % find the existing node closest in state space\n    dmin = Inf;\n    for v=1:g.n\n        xv = g.coord(v);\n        d = sum( (xv(1:2)-xrand(1:2)).^2 ) + t*angdiff(xv(3)-xrand(3))^2;\n        if d < dmin\n            xnear = xv;\n            vnear = v;\n            dmin = d;\n        end\n    end\n\n    % Step 5\n    % figure how to drive the robot from xnear to xrand\n    x0 = xnear';\n    xg = xrand';\n    %set_param('sl_movepoint2/Bicycle', 'x0', sprintf('[%f,%f,%f]', xnear) );\n    %set_param('sl_movepoint2/Goal pose', 'Value', sprintf('trans2([%f,%f,0])', xrand(1:2)) );\n\n    r = sim('sl_drivepose', sim_time);\n    t = r.find('tout');\n    y = r.find('yout');\n    plot2(y)\n    drawnow\n    xnew = y(end,:)';\n    plot2(xnew', 'go');\n\n    % ensure that the path is collision free\n\n    % Step 7,8\n    % add xnew to the graph, with an edge to xnear\n    g.add_node(xnew, vnear);\nend\n\ngrid on\nxyzlabel\nzlabel('\\theta');\naxis([-10 10 -10 10])\niprint('rrt_paths');\nview(0, 0);\niprint('rrt_paths_xt');\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/unit_test/old/nav_rrt2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.5716579644060569}}
{"text": "function LnX = coefficient(x,y,L)\n% Lagrange form for the polynomial interpolation\n% this function produces elements of the form y_k*L_k(x) \nn = length(x);\nNum = '';\nDen = '';\nsyms X\n\nfor i = 1:n\n    if i ~= L\n    TempNum = strcat('(X-x(',num2str(i),')',')','*');\n    Num = strcat(Num,TempNum); \n    TempDen = strcat('(x(',num2str(L),')','-','x(',num2str(i),')',')','*');\n    Den = strcat(Den,TempDen);\n    end\nend\n\nNum(end) = []; Den(end) = [];\nLnX = (eval(strcat('(',Num,')','/','(',Den,')')))*y(L);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26724-lagrange-polynomial/LagrangePoly/coefficient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424217727028, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5716579486582297}}
{"text": "function [au] = km2au(km)\n% Convert length from kilometers to astronomical units.\n% Chad A. Greene 2012\nau = km*6.684587122671e-9;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/km2au.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424217727028, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5716579431343174}}
{"text": "function [dpixc, dveccr, dpixc_ind, blinkmat, N] = generatedata2(sizevec, psf, separ, maxphotvec, offset, Nt)\n% generate 2 points with different shift\n\nnx = sizevec(2)-sizevec(1);\nny = sizevec(4)-sizevec(3);\nN = 2;\n\nif size(maxphotvec,2)>size(maxphotvec,1); maxphotvec = maxphotvec'; end\nmaxphotmat = repmat(maxphotvec, 1,Nt);\n\nblinkmat_equal = rand(N, Nt);\nblinkmat = blinkmat_equal .* maxphotmat; %different intensities...\ncenter = round([nx ny]/2);\ncenterim = pixelize(center, 1, sizevec, nx, ny, [],0);\ndpixc_ind = newimar(2);\ndpixc_ind{1} = clip(dip_image(conv2(centerim,psf,'same')), 0, Inf);\ndpixc_ind{2} = clip(shift(dpixc_ind{1}, separ), 0, Inf);\n\ndpixc_nonoise = array2im(dpixc_ind'*blinkmat + offset);\n\ndpixc_dip = noise(dpixc_nonoise,'poisson');\ndpixc = double(dpixc_dip);\ndveccr = double(squeeze(reshape(dpixc, nx*ny, 1, Nt))); % vectors of resized images\n\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/simulationdatatool/generatedata2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5716579431343173}}
{"text": "function [A,B]= useconvhulln(Z2)\n\n% This file is part of SOSTOOLS - Sum of Squares Toolbox ver 3.00.\n%\n% Copyright (C)2002, 2004, 2013  A. Papachristodoulou (1), J. Anderson (1),\n%                                G. Valmorbida (1), S. Prajna (2), \n%                                P. Seiler (3), P. A. Parrilo (4)\n% (1) Department of Engineering Science, University of Oxford, Oxford, U.K.\n% (2) Control and Dynamical Systems - California Institute of Technology,\n%     Pasadena, CA 91125, USA.\n% (3) Aerospace and Engineering Mechanics Department, University of\n%     Minnesota, Minneapolis, MN 55455-0153, USA.\n% (4) Laboratory for Information and Decision Systems, M.I.T.,\n%     Massachusetts, MA 02139-4307\n%\n% Send bug reports and feedback to: sostools@cds.caltech.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n% AP Apr 03 02\n% AP Feb 01 03\n\n% First, find the convex hull of Z2\n\nconvh = convhulln(Z2);\nfacets = size(convh,1);\n[nZ1,nZ2] = size(Z2);\n\n% Form the hyperplanes\n% A hyperplane of the form [x1 ... xn -ones][A';b'] = 0\n% [A';b'] is in the nullspace of the matrix [x1,...,xn -ones].\n% Ignore it if it has dimension greater than 1\n% Normalise if possible.\n\nfor i = 1:facets\n    vert = [Z2(convh(i,:),:) -ones(nZ2,1)];\n    nullvert = null(vert,'r');\n    if size(nullvert,2) == 1  \n        if nullvert(end) ~=0\n            nullvert = nullvert./nullvert(end);\n        end\n        coeff(:,i) = nullvert(1:end-1);\n        cold(i,1) = nullvert(end); \n    end\nend\n\ncoeff = coeff';\n\n% Condition the matrix a bit\n\ncoeffcold = [coeff cold];\ncoeffcold = round(coeffcold*100000)/100000;\n\n% Discard same hyperplanes (due to convhulln result)\n[coeff2cold,Ix,Iy] = unique(coeffcold,'rows');\n\n%Remove a possible zero row\n\nyind = find(sum(coeff2cold.^2,2) == 0);\nif ~isempty(yind)\n    Ix = [Ix([1:yind-1],1);Ix(yind+1:end,1)];\nend\n\ncoeff2 = coeff(Ix,:);\nconvhnew = convh(Ix,:);\ncnew = cold(Ix);\nfacetsnew = size(convhnew,1);\n\n% Make inequalities out of them by testing a point not on the hyperplane\n% Notation: convex hull is now Ax-b<=0\nfor fac = 1:facetsnew\n    for ind = 1:nZ1\n        matr = find(convhnew(fac,:) - ind*ones(1,nZ2) == 0);\n        tests(fac) = coeff2(fac,:)*Z2(ind,:)'-cnew(fac);\n        if isempty(matr) & abs(tests(fac)) > 1e-8\n            break\n        end\n    end\n    if tests(fac)>0\n        coeff2(fac,:)=-coeff2(fac,:);\n        cnew(fac)=-cnew(fac);\n    end\nend\n\nA = coeff2;\nB = cnew;\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/internal/useconvhulln.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5716579428596809}}
{"text": "% Implementation of the MEM-EKF* algorithm based on the article\n% \n% \"Tracking the Orientation and Axes Lengths of an Elliptical Extended Object\"\n% Shishan Yang and Marcus Baum\n% arXiv preprint, 2018,\n% https://arxiv.org/abs/1805.03276\n% \n% Further information:\n% http://www.fusion.informatik.uni-goettingen.de\n% https://github.com/Fusion-Goettingen\n% \n% Source code written by Shishan Yang\n% =============================\n\nfunction [r,p,Cr,Cp]= time_update(r,p,Cr,Cp,Ar, Ap,Cwr, Cwp)\nr = Ar*r;\nCr = Ar*Cr*Ar'+Cwr;\n\np = Ap*p;\nCp = Ap*Cp*Ap'+Cwp;\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/MEM-EKFstar/time_update.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5716352033664331}}
{"text": "function [M, RHS, Mx, My, Mz, RHSx, RHSy, RHSz] = ...\n    convectionTvdTermCylindrical3D(u, phi, FL)\n% This function uses the TVD scheme to discretize a 3D\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%\n%\n% PARAMETERS:\n%\n%\n% RETURNS:\n%\n%\n% EXAMPLE:\n%\n% SEE ALSO:\n%\n\n% extract data from the mesh structure\nNr = u.domain.dims(1);\nNtetta = u.domain.dims(2);\nNz = u.domain.dims(3);\nG=reshape((1:(Nr+2)*(Ntetta+2)*(Nz+2)), Nr+2, Ntetta+2, Nz+2);\nDRp = repmat(u.domain.cellsize.x(2:end-1), 1, Ntetta, Nz);\nDTHETAp = repmat(u.domain.cellsize.y(2:end-1)', Nr, 1, Nz);\nDZ = zeros(1,1,Nz+2);\nDZ(1,1,:) = u.domain.cellsize.z;\nDZp=repmat(DZ(1,1,2:end-1), Nr, Ntetta, 1);\nrp = repmat(u.domain.cellcenters.x, 1, Ntetta, Nz);\nrf = repmat(u.domain.facecenters.x, 1, Ntetta, Nz);\ndx=repmat(0.5*(u.domain.cellsize.x(1:end-1)+u.domain.cellsize.x(2:end)), 1, Ntetta, Nz);\ndy=repmat(0.5*(u.domain.cellsize.y(1:end-1)+u.domain.cellsize.y(2:end))', Nr, 1, Nz);\ndz=zeros(1, 1, Nz+1);\ndz(1,1,:)=0.5*(u.domain.cellsize.z(1:end-1)+u.domain.cellsize.z(2:end));\ndz=repmat(dz, Nr, Ntetta, 1);\npsiX_p = zeros(Nr+1,Ntetta,Nz);\npsiX_m = zeros(Nr+1,Ntetta,Nz);\npsiY_p = zeros(Nr,Ntetta+1,Nz);\npsiY_m = zeros(Nr,Ntetta+1,Nz);\npsiZ_p = zeros(Nr,Ntetta,Nz+1);\npsiZ_m = zeros(Nr,Ntetta,Nz+1);\n\n% define the vectors to stores the sparse matrix data\niix = zeros(3*(Nr+2)*(Ntetta+2)*(Nz+2),1);\njjx = zeros(3*(Nr+2)*(Ntetta+2)*(Nz+2),1);\nsx = zeros(3*(Nr+2)*(Ntetta+2)*(Nz+2),1);\niiy = zeros(3*(Nr+2)*(Ntetta+2)*(Nz+2),1);\njjy = zeros(3*(Nr+2)*(Ntetta+2)*(Nz+2),1);\nsy = zeros(3*(Nr+2)*(Ntetta+2)*(Nz+2),1);\niiz = zeros(3*(Nr+2)*(Ntetta+2)*(Nz+2),1);\njjz = zeros(3*(Nr+2)*(Ntetta+2)*(Nz+2),1);\nsz = zeros(3*(Nr+2)*(Ntetta+2)*(Nz+2),1);\nmnx = Nr*Ntetta*Nz;\tmny = Nr*Ntetta*Nz;   mnz = Nr*Ntetta*Nz;\n\n% extract the velocity data\n% note: size(ux) = [1:m+1, 1:n] and size(uy) = [1:m, 1:n+1]\nux = u.xvalue;\nuy = u.yvalue;\nuz = u.zvalue;\n\n% calculate the upstream to downstream gradient ratios for u>0 (+ ratio)\n% x direction\ndphiX_p = (phi.value(2:Nr+2, 2:Ntetta+1, 2:Nz+1)-phi.value(1:Nr+1, 2:Ntetta+1, 2:Nz+1))./dx;\nrX_p = dphiX_p(1:end-1,:,:)./fsign(dphiX_p(2:end,:,:));\npsiX_p(2:Nr+1,:,:) = 0.5*FL(rX_p).* ...\n    (phi.value(3:Nr+2,2:Ntetta+1,2:Nz+1)-phi.value(2:Nr+1,2:Ntetta+1,2:Nz+1));\npsiX_p(1,:,:) = 0; % left boundary\n% y direction\ndphiY_p = (phi.value(2:Nr+1, 2:Ntetta+2, 2:Nz+1)-phi.value(2:Nr+1, 1:Ntetta+1, 2:Nz+1))./dy;\nrY_p = dphiY_p(:,1:end-1,:)./fsign(dphiY_p(:,2:end,:));\npsiY_p(:,2:Ntetta+1,:) = 0.5*FL(rY_p).* ...\n    (phi.value(2:Nr+1,3:Ntetta+2,2:Nz+1)-phi.value(2:Nr+1, 2:Ntetta+1,2:Nz+1));\npsiY_p(:,1,:) = 0; % Bottom boundary\n% z direction\ndphiZ_p = (phi.value(2:Nr+1, 2:Ntetta+1, 2:Nz+2)-phi.value(2:Nr+1, 2:Ntetta+1, 1:Nz+1))./dz;\nrZ_p = dphiZ_p(:,:,1:end-1)./fsign(dphiZ_p(:,:,2:end));\npsiZ_p(:,:,2:Nz+1) = 0.5*FL(rZ_p).* ...\n    (phi.value(2:Nr+1,2:Ntetta+1,3:Nz+2)-phi.value(2:Nr+1,2:Ntetta+1,2:Nz+1));\npsiZ_p(:,:,1) = 0; % Back boundary\n\n% calculate the upstream to downstream gradient ratios for u<0 (- ratio)\n% x direction\nrX_m = dphiX_p(2:end,:,:)./fsign(dphiX_p(1:end-1,:,:));\npsiX_m(1:Nr,:,:) = 0.5*FL(rX_m).* ...\n    (phi.value(1:Nr, 2:Ntetta+1, 2:Nz+1)-phi.value(2:Nr+1, 2:Ntetta+1, 2:Nz+1));\npsiX_m(Nr+1,:,:) = 0; % right boundary\n% y direction\nrY_m = dphiY_p(:,2:end,:)./fsign(dphiY_p(:,1:end-1,:));\npsiY_m(:,1:Ntetta,:) = 0.5*FL(rY_m).* ...\n    (phi.value(2:Nr+1,1:Ntetta,2:Nz+1)-phi.value(2:Nr+1,2:Ntetta+1,2:Nz+1));\npsiY_m(:,Ntetta+1,:) = 0; % top boundary\n% z direction\nrZ_m = dphiZ_p(:,:,2:end)./fsign(dphiZ_p(:,:,1:end-1));\npsiZ_m(:,:,1:Nz) = 0.5*FL(rZ_m).* ...\n    (phi.value(2:Nr+1,2:Ntetta+1,1:Nz)-phi.value(2:Nr+1,2:Ntetta+1,2:Nz+1));\npsiZ_m(:,:,Nz+1) = 0; % front boundary\n% reassign the east, west, north, and south velocity vectors for the\n% code readability\nue = ux(2:Nr+1,:,:);\t\tuw = ux(1:Nr,:,:);\nvn = uy(:,2:Ntetta+1,:);     vs = uy(:,1:Ntetta,:);\nwf = uz(:,:,2:Nz+1);     wb = uz(:,:,1:Nz);\nre = rf(2:Nr+1,:,:);         rw = rf(1:Nr,:,:);\n\n% find the velocity direction for the upwind scheme\nue_min = min(ue,0);\tue_max = max(ue,0);\nuw_min = min(uw,0);\tuw_max = max(uw,0);\nvn_min = min(vn,0);\tvn_max = max(vn,0);\nvs_min = min(vs,0);\tvs_max = max(vs,0);\nwf_min = min(wf,0);\twf_max = max(wf,0);\nwb_min = min(wb,0);\twb_max = max(wb,0);\n\n% calculate the coefficients for the internal cells\nAE = re.*ue_min./(DRp.*rp);\nAW = -rw.*uw_max./(DRp.*rp);\nAN = vn_min./(DTHETAp.*rp);\nAS = -vs_max./(DTHETAp.*rp);\nAF = wf_min./DZp;\nAB = -wb_max./DZp;\nAPx = (re.*ue_max-rw.*uw_min)./(DRp.*rp);\nAPy = (vn_max-vs_min)./(DTHETAp.*rp);\nAPz = (wf_max-wb_min)./DZp;\n\n% Also correct for the boundary cells (not the ghost cells)\n% Left boundary:\nAPx(1,:,:) = APx(1,:,:)-rw(1,:,:).*uw_max(1,:,:)./(2*rp(1,:,:)*DRp(1));   AW(1,:,:) = AW(1,:,:)/2;\n% Right boundary:\nAE(end,:,:) = AE(end,:,:)/2;    APx(end,:,:) = APx(end,:,:)+re(end,:,:).*ue_min(end,:,:)./(2*DRp(end)*rp(end,:,:));\n% Bottom boundary:\nAPy(:,1,:) = APy(:,1,:)-vs_max(:,1,:)./(2*DTHETAp(1)*rp(:,1,:));   AS(:,1,:) = AS(:,1,:)/2;\n% Top boundary:\nAN(:,end,:) = AN(:,end,:)/2;    APy(:,end,:) = APy(:,end,:)+vn_min(:,end,:)./(2*DTHETAp(end)*rp(:,end,:));\n% Back boundary:\nAPz(:,:,1) = APz(:,:,1)-wb_max(:,:,1)/(2*DZp(1));   AB(:,:,1) = AB(:,:,1)/2;\n% Front boundary:\nAF(:,:,end) = AF(:,:,end)/2;    APz(:,:,end) = APz(:,:,end) + wf_min(:,:,end)/(2*DZp(end));\n\nAE = reshape(AE,mnx,1);\nAW = reshape(AW,mnx,1);\nAN = reshape(AN,mny,1);\nAS = reshape(AS,mny,1);\nAF = reshape(AF,mnz,1);\nAB = reshape(AB,mnz,1);\nAPx = reshape(APx,mnx,1);\nAPy = reshape(APy,mny,1);\nAPz = reshape(APz,mnz,1);\n\n% build the sparse matrix based on the numbering system\nrowx_index = reshape(G(2:Nr+1,2:Ntetta+1,2:Nz+1),mnx,1); % main diagonal x\niix(1:3*mnx) = repmat(rowx_index,3,1);\nrowy_index = reshape(G(2:Nr+1,2:Ntetta+1,2:Nz+1),mny,1); % main diagonal y\niiy(1:3*mny) = repmat(rowy_index,3,1);\nrowz_index = reshape(G(2:Nr+1,2:Ntetta+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:Nr,2:Ntetta+1,2:Nz+1),mnx,1); reshape(G(2:Nr+1,2:Ntetta+1,2:Nz+1),mnx,1); reshape(G(3:Nr+2,2:Ntetta+1,2:Nz+1),mnx,1)];\njjy(1:3*mny) = [reshape(G(2:Nr+1,1:Ntetta,2:Nz+1),mny,1); reshape(G(2:Nr+1,2:Ntetta+1,2:Nz+1),mny,1); reshape(G(2:Nr+1,3:Ntetta+2,2:Nz+1),mny,1)];\njjz(1:3*mnz) = [reshape(G(2:Nr+1,2:Ntetta+1,1:Nz),mnz,1); reshape(G(2:Nr+1,2:Ntetta+1,2:Nz+1),mnz,1); reshape(G(2:Nr+1,2:Ntetta+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% calculate the TVD correction term\ndiv_x = -(1./(DRp.*rp)).*(re.*(ue_max.*psiX_p(2:Nr+1,:,:)+ue_min.*psiX_m(2:Nr+1,:,:))- ...\n              rw.*(uw_max.*psiX_p(1:Nr,:,:)+uw_min.*psiX_m(1:Nr,:,:)));\ndiv_y = -(1./(DTHETAp.*rp)).*((vn_max.*psiY_p(:,2:Ntetta+1,:)+vn_min.*psiY_m(:,2:Ntetta+1,:))- ...\n              (vs_max.*psiY_p(:,1:Ntetta,:)+vs_min.*psiY_m(:,1:Ntetta,:)));\ndiv_z = -(1./DZp).*((wf_max.*psiZ_p(:,:,2:Nz+1)+wf_min.*psiZ_m(:,:,2:Nz+1))- ...\n              (wb_max.*psiZ_p(:,:,1:Nz)+wb_min.*psiZ_m(:,:,1:Nz)));\n\n% define the RHS Vector\nRHS = zeros((Nr+2)*(Ntetta+2)*(Nz+2),1);\nRHSx = zeros((Nr+2)*(Ntetta+2)*(Nz+2),1);\nRHSy = zeros((Nr+2)*(Ntetta+2)*(Nz+2),1);\nRHSz = zeros((Nr+2)*(Ntetta+2)*(Nz+2),1);\n\n% assign the values of the RHS vector\nrow_index = rowx_index;\nRHS(row_index) = reshape(div_x+div_y+div_z,Nr*Ntetta*Nz,1);\nRHSx(rowx_index) = reshape(div_x,Nr*Ntetta*Nz,1);\nRHSy(rowy_index) = reshape(div_y,Nr*Ntetta*Nz,1);\nRHSz(rowz_index) = reshape(div_z,Nr*Ntetta*Nz,1);\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), (Nr+2)*(Ntetta+2)*(Nz+2), (Nr+2)*(Ntetta+2)*(Nz+2));\nMy = sparse(iiy(1:ky), jjy(1:ky), sy(1:ky), (Nr+2)*(Ntetta+2)*(Nz+2), (Nr+2)*(Ntetta+2)*(Nz+2));\nMz = sparse(iiz(1:kz), jjz(1:kz), sz(1:kz), (Nr+2)*(Ntetta+2)*(Nz+2), (Nr+2)*(Ntetta+2)*(Nz+2));\nM = Mx + My + Mz;\n\nend\n\nfunction phi_out = fsign(phi_in)\n% This function checks the value of phi_in and assigns an eps value to the\n% elements that are less than or equal to zero, while keeping the signs of\n% the nonzero elements\n    phi_out = (abs(phi_in)>=eps).*phi_in+eps*(phi_in==0)+eps*(abs(phi_in)<eps).*sign(phi_in);\nend\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Discretization/convectionTvdTermCylindrical3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5716351973575367}}
{"text": "function p=lin2pcmu(x,s)\n%LIN2PCMU Convert linear to Mu-law PCM P=(X,S)\n%\tpcmu = lin2pcmu(lin) where lin contains a vector\n%\tor matrix of signal values within a range determined by\n%\tthe scale factor s (see table below).\n%\tValues outside this range will be clipped.\n%\tThe input values will be converted to integer\n%\tMu-law pcm vlues in the range 0 to 255.\n%\t\n%\tInput values are multiplied by the scale factor s:\n%\n%\t\t   s\t\tInput Range\n%\n%\t\t   1\t\t+-8159\n%\t\t4004.189931\t+-2.03761563 (default)\n%\t\t8159\t\t+-1\n%\n%\tThe default input scaling factor 4004.189931 is equal to\n%\tsqrt((2207^2 + 5215^2)/2) and follows ITU standard G.711.\n%\tThe sine wave with PCM-Mu values [158 139 139 158 30 11 11 30]\n%\thas a mean square value of unity corresponding to 0 dBm0.\n\n\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: lin2pcmu.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\nif nargin < 2 s=4004.189931; end\ny=x*s;\ny=(abs(y+8031)-abs(y-8031))/2;\nq=floor((y+8032)/8032);\n[m,e]=log2(abs(y)+33);\np=175+128*q-8*(e+abs(e-6))-floor(32*m-16);\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/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/lin2pcmu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5716185576780228}}
{"text": "function rule_num = triangle_ncc_rule_num ( )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_NCC_RULE_NUM returns the number of NCC rules available.\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%  Reference:\n%\n%    Peter Silvester,\n%    Symmetric Quadrature Formulae for Simplexes,\n%    Mathematics of Computation,\n%    Volume 24, Number 109, January 1970, pages 95-100.\n%\n%  Parameters:\n%\n%    Output, integer RULE_NUM, the number of rules available.\n%\n  rule_num = 9;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/triangle_ncc_rule/triangle_ncc_rule_num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.5716185477400915}}
{"text": "function [f,g] = call_log_reg(v, y, X, lambda)\n% Primal objective function (Omega = inv(Sigma))\n% f = 0.5*(logdet(V) - logdet(Sigma) - tr(V*SigmaInv) - (m-mu)'*SigmaInv*(m-mu)\n%     + L) - sum_d fb(mbar_d, vbar_d)\n% where mbar = X*m, vbar = diag(X*V*X')\n%\n% Written by Emtiyaz,\n% Modified by Wu Lin\n  global m_cache;\n  global V_cache;\n  global iter_counter;\n  global is_cache;\n  global times_cache;\n  iter_counter = iter_counter + 1;\n\n  [D L] = size(X);\n\n  Omega = diag(lambda);\n  %Extract mean, Cholesky and bias\n  m = v(1:L);\n  idx = L + [1:L*(L+1)/2];\n  U = triu(unpackcovariance(v(idx),L));\n\n  % compute V\n  V = U'*U;\n\n  if is_cache==1\n      m_cache(:,iter_counter) = m;\n      V_cache(:,:,iter_counter) = V;\n  end\n\n  % compute kl and its gradient\n  kl = 0.5*(2*sum(log(diag(U))) + sum(log(lambda(2:end))) - trace(V*Omega) -m'*(Omega*m) + L);\n\n  % contribution from the bound\n  mbar = X*m;\n  vbar = sum(X.*(V*X')',2); % diag(X*V*X') efficient\n  [fb, gmb, gvb] = E_log_p('bernoulli_logit', y, mbar, vbar, []);\n  fb = -fb;\n  gm_lvb = X'*(-gmb);\n  gV_lvb = X'*bsxfun(@times, -gvb, X); %efficient X'*diag(gllp/2)*X;\n\n  % final\n  f = kl - sum(fb);\n  gm = - Omega*m - gm_lvb;\n  gU = diag(1./diag(U)) - triu(U*Omega) - triu(2*U*gV_lvb);\n\n  g=[gm(:); gU(triu(ones(L))==1)];\n\n  % return\n  g=-g;\n  f=-f;\n\n  if iter_counter+1<=length(times_cache)\n      times_cache(iter_counter+1) = toc;\n  else\n      times_cache(end) = toc;\n  end\n", "meta": {"author": "emtiyaz", "repo": "vadam", "sha": "d8ea6bdc82ac8765b873578660e1d9ba95c701d4", "save_path": "github-repos/MATLAB/emtiyaz-vadam", "path": "github-repos/MATLAB/emtiyaz-vadam/vadam-d8ea6bdc82ac8765b873578660e1d9ba95c701d4/matlab/lib/log_reg/call_log_reg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5716185412991509}}
{"text": "clear all, close all, clc\naddpath('./utils');\nload allFaces.mat\nX = faces(:,1:nfaces(1));\n[L,S] = RPCA(X);\n\n\n%%\ninds = [3 4 14 15 17 18 19 20 21 32 43];\nfor k=[3 4 14 15 17 18 19 20 21 32 43]\n    k\n    subplot(2,2,1)\n    imagesc(reshape(X(:,k),192,168)), colormap gray\n    subplot(2,2,3)\n    imagesc(reshape(L(:,k),192,168)), colormap gray\n    subplot(2,2,4)\n    imagesc(reshape(S(:,k),192,168)), colormap gray\n    pause\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/CH03/CH03_SEC07_RPCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.57161854097036}}
{"text": "function [Rlat,Rlon,alt] = LatLongCalcSingle_ADI(msg, inputLat, inputLong)\n% Calculate latitude, longitude and altitude from message bits\n% Copyright 2010, The MathWorks, Inc.\n\npersistent NL\npersistent latzones\npersistent Dlat0\npersistent Dlat1\npersistent latOffset0\npersistent latOffset1\n\nif isempty(NL)\n    Dlat0 = 360/(4*15-0);\n    latOffset0 = floor(inputLat/Dlat0);\n    Dlat1 = 360/(4*15-1);\n    latOffset1 = floor(inputLat/Dlat1);\n    NL=2:59;\n    latzones = [(180/pi)*acos(sqrt((1-cos(pi/2/15))./(1-cos(2*pi./NL)))) 0];\nend\n\n% Altitude calculation\nq = msg(48);\nif q == 0\n    af = 100;\nelse\n    af = 25;\nend\naltBits=[msg(41:47);msg(49:52)]';\nalt = altBits*[1024;512;256;128;64;32;16;8;4;2;1]*af - 1000;\n\nevenOdd1 = msg(54);\nlatBits = msg(55:71)';\nlongBits = msg(72:88)';\nla1 = latBits*[65536;32768;16384;8192;4096;2048;1024;512;256;128;64;32;16;8;4;2;1];\nlo1 = longBits*[65536;32768;16384;8192;4096;2048;1024;512;256;128;64;32;16;8;4;2;1];\n\n% Technically you need both even and odd messages to calculate lat/long\n% unambiguously. For this code, use a single message and then check to see\n% if the lat/long values are reasonable. If not, change the lat/long base\n% factors (LL.a1, LL.a2, etc.) and recompute.\n\n% Latitude calculation\nif evenOdd1 == 0\n    Rlat = Dlat0*(latOffset0 + la1/131072);\nelse\n    Rlat = Dlat1*(latOffset1 + la1/131072);\nend\n\n% Compare latitude to known location. If it's off by more than two degrees,\n% use new base factors.\nif Rlat > inputLat+2\n    if strcmp(evenOdd1,'Even')\n        Rlat = Dlat0*(latOffset0 - 1 + la1/131072);\n    else\n        Rlat = Dlat1*(latOffset1 - 1 + la1/131072);\n    end\nelseif Rlat < inputLat-2\n    if strcmp(evenOdd1,'Even')\n        Rlat = Dlat0*(latOffset0 + 1 + la1/131072);\n    else\n        Rlat = Dlat1*(latOffset1 + 1 + la1/131072);\n    end\nend\n\n% Based on latitude, calculate longitude\nNL0 = find(latzones<Rlat,1,'first');\nni0 = NL0;\nni1 = NL0 - 1;\n\nDlon0 = 360/ni0;\nlongOffset0 = floor(inputLong/Dlon0);\nDlon1 = 360/ni1;\nlongOffset1 = floor(inputLong/Dlon1);\n\nif evenOdd1 == 0\n    Rlon = Dlon0*(longOffset0 + lo1/131072);\nelse\n    Rlon = Dlon1*(longOffset1 + lo1/131072);\nend\n\n% Compare longitude to known location. If it's off by more than two \n% degrees, use new base factors.\nif Rlon > inputLong+2\n    if strcmp(evenOdd1,'Even')\n        Rlon = Dlon0*(longOffset0 - 1 + lo1/131072);\n    else\n        Rlon = Dlon1*(longOffset1 - 1 + lo1/131072);\n    end\nelseif Rlon < inputLong-2\n    if strcmp(evenOdd1,'Even')\n        Rlon = Dlon0*(longOffset0 + 1 + lo1/131072);\n    else\n        Rlon = Dlon1*(longOffset1 + 1 + lo1/131072);\n    end\nend\n\n% disp(sprintf('Plane is at altitude %d\\nLatitude value: %d\\nLongitude value: %d', alt, la1, lo1));\n\n% GoogleMap(aircraftID, alt1, Rlat, Rlon)", "meta": {"author": "analogdevicesinc", "repo": "MathWorks_tools", "sha": "5f8df06d4fc2f4832ed9ec8b722fb750b2261f20", "save_path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools", "path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools/MathWorks_tools-5f8df06d4fc2f4832ed9ec8b722fb750b2261f20/targeting_models/ADSB/LatLongCalcSingle_ADI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5715594700199307}}
{"text": "function out = Dstar(R, n, e, fun)\n%finds excess distortion for a given rate at a given blocklength for\n%Gaussian source with unit variance\n%R - rate\n%n - block length (scalar)\n%e - excess probability\n%fun - which function to use for calculation\n\n%\n%   Created in 2012 by Victoria Kostina (vkostina@caltech.edu)\n%\n\n\n%starting points - 'persistent' to make optimization faster\npersistent x0;\npersistent y0;\n\ntry\n\n    switch lower(fun)\n        case 'shannon'\n            %achievability via Shannon's upper bound:\n            tol = 1e-4;\n            qglb = [2^(-2*R); 1];\n            qgub = [1; Inf];\n            options = optimset('TolX',tol, 'MaxFunEvals', 500, 'Algorithm', 'active-set');\n\n            if isempty(x0) && isempty (y0)\n                x0 = [2^(-2*R) 1];\n                y0 = [(2^(-2*R)+1)/2 1]; %q gamma\n            end\n            out = DShannon();\n        case 'normal'\n            %normal approximation\n            out = DNormal(); \n        case 'spherecoveringc'\n            %converse via sphere covering\n            out = DSphereCovering();\n        case 'spherecoveringa'\n            %achievability via sphere covering\n            if isempty(x0) && isempty (y0)\n                x0 = [2^(-2*R) .5]; %distortion\n             %   y0 = [0 1];        %auxiliary parameter q\n            end \n            out = DSphereCoveringA();\n        otherwise\n            disp('Unknown type.')\n    end\n\ncatch ME\n    fprintf('Error: %s\\n', ME.message);\n    out = NaN;\nend\n\n\n%--------------------------------------------------------------------------\n    function out = DShannon()\n        %achievability via Shannon's upper bound:\n        out = fzero(@(x)Pexcess(x) - e,x0);\n        x0 = out;\n        function out = Pexcess(x)\n            D = x;\n            [y0, Pe] = fmincon(@optqg, y0,[],[],[],[],qglb, qgub, [], options);\n            out = Pe;\n\n            function out = optqg(y)\n                q = y(1);\n                g = log2(y(2));\n                out = PeubShannon(R, n, D, q, g);\n            end\n        end\n\n    end\n\n%--------------------------------------------------------------------------\n    function out = DNormal()\n        out = 2^(-2*R)*(1 + sqrt(2/n)*Qinv(e));\n    end\n\n%--------------------------------------------------------------------------\n    function out = DSphereCovering()\n        %converse via sphere covering\n\n        %find rstar:\n        factor = 10;\n        rstar = fzero(@(x)chi2cdf(x^2*n, n) - chi2cdf(factor*n, n) + e, 1);\n        out = fminbnd(@(x) abs(R - rate(x)),2^(-2*R),1);\n\n\n        function out = rate(x)\n            out = 1/2*log2(rstar^2/x);\n        end\n    end\n\n%--------------------------------------------------------------------------\n    function out = DSphereCoveringA()\n        %achievability via sphere covering\n        M = 2.^(n*R);\n        out = fzero(@(x)Pexcess(x) - e, x0);\n    function out = Pexcess(x)\n        d = x;\n        s0 = 1; %variance of source\n        r0 = sqrt(s0^2 - d); %distance from the center of the representation sphere\n        \n        out = quad(@density, r0 - sqrt(d), r0 + sqrt(d))...\n            + 1 - chi2cdf((r0 + sqrt(d))^2*n,n)...\n            + chi2cdf((r0 - sqrt(d))^2*n,n);\n        out = real(out);\n        \n        function out = density(r)\n          cosa = (r0^2 + r.^2 - d)./(2*r0.*r);\n          sina = (1 - cosa.^2).^(1/2);\n          out = ub(sina).*chi2pdf(n*r.^2, n).*n*2.*r;         \n        end\n        \n        function out = ub(sina)\n            if (n < 50)\n                A = 1/sqrt(pi).*gamma(n/2+1)./n./gamma((n-1)/2+1);\n                out = (1 - A.*(sina).^(n-1)).^M;\n            else\n                out = exp(-M*sina.^(n-1)./sqrt(2*pi*n));\n            end\n        end\n    end  \n        \n    end\n\n\n\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/sc/GMS/Dstar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5715594639597323}}
{"text": "function H = comp_nyquistfilt(wintype,fs,chan_max,freqtoscale,scaletofreq,bwmul,bins,Ls)\n%COMP_NYQUISTFILT high-pass filter for warped filter banks\n\n    kk = chan_max;\n    while scaletofreq(kk-bwmul) < fs/2;\n      kk = kk+1/bins;\n    end\n    Maxfilt = kk;\n    \n    Minpos = ceil(Ls/fs*scaletofreq(chan_max+1/bins-bwmul));\n    samples = freqtoscale((Minpos-1:floor(Ls/2))*fs/Ls);\n    \n    FILTS = zeros(round(bins*(Maxfilt-chan_max)),numel(samples));\n    for kk = 1:size(FILTS,1)\n       FILTS(kk,:) = firwin(wintype,(samples-(chan_max+kk/bins))/(2*bwmul));\n    end\n    H = zeros(2*numel(samples)-1,1);\n    H(1:numel(samples)) = sqrt(sum(abs(FILTS.^2),1));\n    H(numel(samples)+1:end) = H(numel(samples)-1:-1:1); \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_nyquistfilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.571559457899534}}
{"text": "function H = elec_meshplot(X,Y,Z,interp,grid_res)\n\n% elec_meshplot - Plot a mesh and points for 3D electrode positions.\n%\n% Usage: H = elec_meshplot(X,Y,Z [,interp] [,grid_resolution])\n%\n% Uses an interpolated mesh at 0.25 cm resolution, unless\n% user specifies alternative grid resolution (optional).\n%\n% Interpolation can be 'linear' or 'cubic'.  Unless specified,\n% cubic is the default. \n%\n% Returns a handle to the figure created.\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:55 $\n\n% Licence: Gnu GPL\n% Author: Darren.Weber_at_radiology.ucsf.edu\n% Created:  18/05/00\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  H = figure('NumberTitle','off','Name','Electrode Mesh Plot','Position',[200 200 650 500],'PaperUnits','centimeters','PaperType','A4','Units','centimeters');\n\n  colormap(gray);\n\n  if ~exist( 'grid_res', 'var' )  grid_res = 0.25;  end\n\n  xi =   (min(X) - 2):grid_res:(max(X) + 2);\n  yi =  [(min(Y) - 2):grid_res:(max(Y) + 2)]';\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % Use 'linear' for a linear grid or 'cubic' for a polynomial grid\n\n  if ~exist( 'interp', 'var' )  interp = 'cubic';  end\n  \n  [Xi,Yi,Zi] = griddata(X,Y,Z,xi,yi,interp);\n\n  surf(Xi,Yi,Zi);\n\n  brighten(0.75);\n\n  mesh(Xi,Yi,Zi);\n\n  hold on;\n\n  plot3(X,Y,Z,'ro');\n  \n  rotate3d;\n\n  clear xi yi Xi Yi Zi X Y Z;\n\n%  view(2);  % top view\n%  view(   0,0);  % back view\n%  view(-180,0);  % front view\n%  view(-90, 0);  % left side view\n%  view( 90, 0);  % right side view\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_meshplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.571555820380236}}
{"text": "%ComputeMarginal Computes the marginal over a set of given variables\n%   M = ComputeMarginal(V, F, E) computes the marginal over variables V\n%   in the distribution induced by the set of factors F, given evidence E\n%\n%   M is a factor containing the marginal over variables V\n%   V is a vector containing the variables in the marginal e.g. [1 2 3] for\n%     X_1, X_2 and X_3.\n%   F is a vector of factors (struct array) containing the factors \n%     defining the distribution\n%   E is an N-by-2 matrix, each row being a variable/value pair. \n%     Variables are in the first column and values are in the second column.\n%\n% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n\nfunction M = ComputeMarginal(V, F, E)\n\n% Check for empty factor list\nassert(numel(F) ~= 0, 'Error: empty factor list');\n\n  F = ObserveEvidence(F, E);\n  Joint = ComputeJointDistribution(F);\n  Joint.val = Joint.val ./ sum(Joint.val);\n  M = FactorMarginalization(Joint, setdiff(Joint.var, V));\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/7.CRF Learning for OCR/ComputeMarginal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5715487842704721}}
{"text": "function MV = ffmInteractionsSparseHF(X,Xbox,Y,Ybox,V,Ibox,green,k,edg,tol)\n%+========================================================================+\n%|                                                                        |\n%|         OPENFFM - LIBRARY FOR FAST AND FREE MEMORY CONVOLUTION         |\n%|           openFfm is part of the GYPSILAB toolbox for Matlab           |\n%|                                                                        |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2019.                             |\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    \u00a0\u00a0\u00a0\u00a0         |\n%|                                                                        |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it.                                                      |\n%|________________________________________________________________________|\n%|   '&`   |                                                              |\n%|    #    |   FILE       : ffmInteractionsSparseHF.m                     |\n%|    #    |   VERSION    : 0.6                                           |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |\n%|  ( # )  |   CREATION   : 14.03.2017                                    |\n%|  / 0 \\  |   LAST MODIF : 05.09.2019                                    |\n%| ( === ) |   SYNOPSIS   : Sparse product for high-frequency compressible|\n%|  `---'  |                leaves                                        |\n%+========================================================================+\n\n% Initialisation du produit Matrice-Vecteur\nMV = zeros(size(X,1),1,class(V));\n\n% Quadrature spherique de Geggenbauer\n[Xq,Wq,l] = ffmQuadratureHF(k,edg,tol);\n\n% Unicite des vecteurs de translation\nXY        = Ybox.ctr(Ibox(:,2),:) - Xbox.ctr(Ibox(:,1),:);\n[~,Il,It] = unique(floor(XY*1e6),'rows','stable');\nNt        = length(Il);\n\n% Fonctions de transfert\nTxy = cell(Nt,1);\nfor i = 1:Nt\n    Txy{i} = ffmTransfertHF(Xq,Wq,XY(Il(i),:),k,l);\nend\n\n% Convolution en Y\nVy = cell(size(Ybox.ind));\nfor i = unique(Ibox(:,2)')\n    % Boite centree en Y\n    iy = Ybox.ind{i};\n    ny = length(iy);\n    Ym = Y(iy,:) - ones(ny,1)*Ybox.ctr(i,:);\n    \n    % Transformee de Fourier inverse (Ym->Xq)\n    Vy{i} = ffmInterpHF(Xq,Ym,V(iy),-1,tol);\n    \n    % Derivation du noyau en Y\n    if strcmp(green(1:end-1),'grady[exp(ikr)/r]') \n        j     = str2double(green(end));\n        Vy{i} = -1i*Xq(:,j) .* Vy{i};\n    end    \nend\n\n% Translations\nTVy = cell(size(Xbox.ind));\nfor i = 1:length(TVy)\n    TVy{i} = 0;\nend\nfor i = 1:size(Ibox,1)\n    TVy{Ibox(i,1)} = TVy{Ibox(i,1)} + Txy{It(i)}.*Vy{Ibox(i,2)};\nend\n\n% Convolutions en X\nfor i = unique(Ibox(:,1)')\n    % Boite centree en X\n    ix = Xbox.ind{i};\n    nx = length(ix);\n    Xm = X(ix,:) - ones(nx,1)*Xbox.ctr(i,:);\n    \n    % Derivation du noyau en X\n    if strcmp(green(1:end-1),'gradx[exp(ikr)/r]') \n        j      = str2double(green(end));\n        TVy{i} = 1i*Xq(:,j) .* TVy{i};\n    end      \n    \n    % Transformee de Fourier (Xq->X)\n    MV(ix) = ffmInterpHF(Xm,Xq,TVy{i},+1,tol);\nend\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [Xq,Wq,l] = ffmQuadratureHF(k,edg,tol)\n% Ordre harmonique (E. Darve)\nl = floor( abs(k)*sqrt(3)*edg - log(tol) );\n\n% Quadrature de Gauss sur [-1,1]\nu     = 1:l;\nu     = u ./ sqrt(4*u.^2 - 1);\n[V,x] = eig( diag(u,-1) + diag(u,+1) );\n[x,I] = sort(diag(x));\nw     = 2*V(1,I)'.^2;\n\n% Quadrature de Gauss sur [0,1] par transformation lineaire\na = 0;   b = 1;\nx = 0.5*(b-a)*x + 0.5*(a+b);\nw = 0.5*(b-a)*w;\n\n% Quadrature de Gauss en elevation (phi)\nphi = acos(2*x(end:-1:1)-1) - pi/2;\nWp  = 2*w(end:-1:1)';\n\n% Quadrature reguliere en azimut (theta)\nNtheta = 2*(l+1);\ntheta  = 2*pi/Ntheta*(0:Ntheta-1)';\nWt     = 2*pi/Ntheta*ones(Ntheta,1);\n\n% Quadrature spherique par produit tensoriel\n[theta,phi] = ndgrid(theta,phi);\ntheta       = theta(:);\nphi         = phi(:);\nWq          = Wt * Wp;\nWq          = Wq(:);\n\n% Coordonnees carthesienne et produit par le nombre d'onde\n[x,y,z] = sph2cart(theta,phi,1);\nXq      = k*[x,y,z];\n\n% Securite\nif (l>3)\n    % Harmoniques spheriques jusqu'a l'ordre 3\n    n   = 1;\n    Ylm = zeros(length(theta),16);\n    for ll = 0:3\n        Plm = sqrt((2*ll+1)/(4*pi)) * legendre(ll,cos(pi/2-phi),'sch').';\n        for m = -ll:ll\n            if m<0\n                Ylm(:,n) = Plm(:,abs(m)+1) .* sin(abs(m).*theta);\n            else\n                Ylm(:,n) = Plm(:,abs(m)+1) .* cos(abs(m).*theta);\n            end\n            n = n+1;\n        end\n    end\n    \n    % Test de l'integration spherique des harmoniques (produit scalaire)\n    [m,n] = size(Ylm);\n    if norm( (Ylm' * spdiags(Wq,0,m,m) * Ylm) - eye(n) , 'inf') > 1e-5\n        error('ffmQuadratureHF.m - error 1');\n    end\nend\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction T = ffmTransfertHF(Xq,ws,xy,k,l)\n% Fonctions de hankel spherique 1ere espece\nbesselhs = @(n,z) sqrt(pi./(2.*z)) .* besselh(n+0.5,1,z);\n\n% Distance\nkr = k*norm(xy);\n\n% cosinus(angle incidence)\nx = Xq*(-xy/kr)';\n\n% Initialisation de la recursion sur (besselhs(kr) * Pl(cos(phi))\nP0 = ones(size(x));\nP1 = x;\nT  = besselhs(0,kr).*P0 + 3i*besselhs(1,kr).*P1;\n\n% Construction recursive des polynomes de Legendre\nfor ll = 2:l\n    P2 = 1/ll .* ( (2*(ll-1)+1).*x.*P1 - (ll-1).*P0 );\n    T  = T + (2*ll+1) * 1i^ll * besselhs(ll,kr) .* P2;\n    P0 = P1;\n    P1 = P2;\nend\n\n% Operateur de Translation\nT = 1i*abs(k)/(4*pi) .* ws .* T;\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction MV = ffmInterpHF(X,Y,V,iflag,tol)\n% Dimensions\nNx   = size(X,1);\nNy   = size(Y,1);\nNmax = max(Nx,Ny);\nNmin = min(Nx,Ny);\n\n% DFT non uniforme\nif (Nmin<100) || (Nmin<log(Nmax))\n    MV = exp(1i*iflag*X*Y') * V;\n    \n% FFT non uniforme    \nelse \n    % Conversion de type\n    if isa(X,'single') || isa(Y,'single') || isa(V,'single')\n        sgl = 1;\n        X = double(X); Y = double(Y); V = double(V);\n    else\n        sgl = 0;\n    end\n    \n    % Initialisation produit Matrice-Vecteur\n    MV = zeros(Nx,1) + 1i*zeros(Nx,1);\n    \n    % Prevention de coplanarite en X\n    Nx         = Nx + 1;\n    X(end+1,:) = X(end,:) + tol;\n    MV(end+1)  = 0;\n\n    % Prevention de coplanarite en X\n    Ny         = Ny + 1;\n    Y(end+1,:) = Y(end,:) + tol;\n    V(end+1)   = 0;\n    \n    % Transformee de Fourier\n    ier    = 0;\n    mex_id = 'nufft3d3f90(i int[x], i double[], i double[], i double[], i dcomplex[], i int[x], i double[x], i int[x], i double[], i double[], i double[], io dcomplex[], io int[x])';\n    MV     = nufft3d(mex_id,Ny,Y(:,1),Y(:,2),Y(:,3),V, iflag, tol, ...\n        Nx,X(:,1),X(:,2),X(:,3),MV, ier, 1, 1, 1, 1, 1);\n    \n    % Supression dernier point\n    MV = MV(1:end-1);\n    \n    % Conversion de type\n    if sgl\n        MV = single(MV);\n    end    \nend\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openFfm/ffmInteractionsSparseHF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5715487699838447}}
{"text": "function [mMedModF, mStdL, loopout] = brutebootloglike_a2(time_as, time_asf, bootloops,fT1, nMod)\n    % BRUTEBOOTLOGLIKE_A2 Bootstrap analysis of Omori parameters calculated by brute force\n    % (p1,p2,c1,c2,k1,k2)-pair is mean of the bootstrap values by determining the mean cumulative \n    % number modeled a end of the learning period\n    % Standard deviations are calculated as the 2nd moment, not to rely fully on normal distributions\n    %\n    % [mMedModF, mStdL, loopout] = BRUTEBOOTLOGLIKE_A2(time_as, time_asf, bootloops,fT1, nMod);\n    % -------------------------------------------------------------------------------\n    %\n    % Input parameters:\n    %   time_as     Delay times [days] of learning period\n    %   time_asf    Delay times [days] until end of forecast period\n    %   bootloops   Number of bootstraps\n    %   fT1         Time of biggest aftershock in learning period\n    %   nMod        Model to fit data, three models including a secondary aftershock sequence.\n    %               Different models have varying amount of free parameters\n    %               before (p1,c1,k1) and after (p2,c2,k2) the aftershock occurence\n    %               1: modified Omori law (MOL): 3 free parameters\n    %                  p1=p2,c1=c2,k1=k2\n    %               2: MOL with one secondary aftershock sequence:4 free parameters\n    %                  p1=p2,c1=c2,k1~=k2\n    %               3: MOL with one secondary aftershock sequence:5 free parameters\n    %                  p1~=p2,c1=c2,k1~=k2\n    %               4: MOL with one secondary aftershock sequence:6 free parameters\n    %                  p1~=p2,c1~=c2,k1~=k2\n    %\n    % Output parameters:\n    %  mMedModF :  Result matrix including the values for the mean forecast at end of forecast period\n    %  mStdL    :  Uncertainties of fit to the data in learning period\n    %  loopout     contains all results\n    %\n    % Samuel Neukomm / S. Wiemer / J. Woessner\n    % updated: 05.08.03\n\n    time_as = sort(time_as);\n    %bootloops = 50; % number of bootstrap samples\n    n = length(time_as);\n    loopout = nan(bootloops,9); % 8 from bruteforceloglike_a2, plus variate column.\n    % Initialize random seed\n    rng('shuffle');\n    \n    % i = (1:n)';\n    for j = 1:bootloops\n        newtas = sort(datasample(time_as, n, 'Replace',true)); \n        [pv1, pv2, cv1, cv2, kv1, kv2, fAIC, fL] = bruteforceloglike_a2(newtas, fT1, nMod);\n        loopout(j,1:8) = [pv1, pv2, cv1, cv2, kv1, kv2, fAIC, fL];\n    end\n\n    % New version: Choose mean (p,c,k)-variables by modelling the cumulative number at end of\n    % the learning period\n\n    % 2nd moment i.e. Standard deviations\n    [pstd1] = std(loopout(:,1),1,'omitnan');\n    [pstd2] = std(loopout(:,2),1,'omitnan');\n    [cstd1] = std(loopout(:,3),1,'omitnan');\n    [cstd2] = std(loopout(:,4),1,'omitnan');\n    [kstd1] = std(loopout(:,5),1,'omitnan');\n    [kstd2] = std(loopout(:,6),1,'omitnan');\n\n    % Uncertainties of fit\n    mStdL = [pstd1 pstd2 cstd1 cstd2 kstd1 kstd2];\n\n   \n    %% Compute best fitting pair of variates\n    % TODO (maybe) vectorize this\n    n_time_asf = length(time_asf);\n    \n    \n    \n    pv1=loopout(:,1);\n    pv2=loopout(:,2);\n    cv1=loopout(:,3);\n    cv2=loopout(:,4);\n    kv1=loopout(:,5);\n    kv2=loopout(:,6);\n    \n    cumnr_model = OmoriModel.doForecast(nMod,time_asf, pv1, cv1, kv1, fT1, kv2, pv2, cv2);\n    loopout(:,9) = max(cumnr_model);\n    \n    %%\n    [Y, in] = sort(loopout(:,9));\n    loops = loopout(in,:);\n    % % Median values: Old version\n    % vMedian = abs(loops(:,9)-median(loops(:,9)));\n    % nMedian = (find(vMedian == min(vMedian)));\n    %\n    % if length(nMedian(:,1)) > 1\n    %     nMedian = nMedian(1,1);\n    % end\n    % pmedian1 = loops(nMedian,1);\n    % pmedian2 = loops(nMedian,2);\n    % cmedian1 = loops(nMedian,3);\n    % cmedian2 = loops(nMedian,4);\n    % kmedian1 = loops(nMedian,5);\n    % kmedian2 = loops(nMedian,6);\n    %\n    % mMedModF = [pmedian1, pstd1, pmedian2, pstd2, cmedian1, cstd1, cmedian2, cstd2, kmedian1, kstd1, kmedian2, kstd2];\n\n    % Mean values\n    vMean = abs(loops(:,9)-mean(loops(:,9)));\n    nMean = (find(vMean == min(vMean)));\n\n    if length(nMean(:,1)) > 1\n        nMean = nMean(1,1);\n    end\n    pMean1 = loops(nMean,1);\n    pMean2 = loops(nMean,2);\n    cMean1 = loops(nMean,3);\n    cMean2 = loops(nMean,4);\n    kMean1 = loops(nMean,5);\n    kMean2 = loops(nMean,6);\n\n    mMedModF = [pMean1, pstd1, pMean2, pstd2, cMean1, cstd1, cMean2, cstd2, kMean1, kstd1, kMean2, kstd2];\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/afterrate/brutebootloglike_a2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5715487664545513}}
{"text": "clear all; close all; clc;\naddpath('./toolbox');\n\n% load feature trajectories\nload('./data/running.mat');\n\n% define some variables\ndtrng\t\t\t= 20:0.5:40;\narng\t\t\t= 0.8:0.02:1.2;\nprojmodel = 'affine';\na_con\t\t\t= [];\t\t\t\t\t\t% set to a value to constrain a\n\n% define noise parameters\nnnoise\t\t= 21;\nnits\t\t\t= 20;\nnoisevec\t= linspace(0,5,nnoise);\ndts\t\t\t\t= zeros(nits,nnoise);\n\n% offset W1 by 30 frames\nW1\t\t= W1(31:end-30,:);\n\nfor n = 1:nnoise\n\tfor it = 1:nits\n\t\tW1n = W1 + noisevec(n)*randn(size(W1));\n\t\tW2n\t= W2 + noisevec(n)*randn(size(W2));\n\t\t\n\t\t% run synchronization script\n\t\t[a,dt] = sync(W1n,W2n,a_con,projmodel);\n\t\n\t\tdts(it,n)\t= dt;\n\tend\nend\n\n% this took a while so save to a temporary file just in case\nsave('temp.mat','dts');\n\nmn\t= mean(dts,1);\nsd\t= 3*std(dts,[],1);\n\nfigure;\n\tplot([0,5],[30,30],'r--',...\n\t\t\t\tnoisevec,dts,'b.');\n\taxis('equal',[minmax(noisevec),28,32]);\n\txlabel('\\sigma_n (pixels)'); ylabel('Recovered offset (frames)');\n\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/43265-video-synchronization-from-human-motion-using-rank-constraints/sync/demo_noise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.571548765809851}}
{"text": "%% housekeeping\ngentle_clear()\nclose all\nclc\n\n%% load and transform the data\ndb=xlsread('usmacro2.xlsx');\n\ndb=ts('1955Q1',db(:,4:end),{'Y','P','R','C','N','I','E'});\n\ndb=pages2struct(db);\n\n%% Rise the madel\n\nm=rise('model10');\n\n%% priors\npriors=struct();\npriors.beta={0.98,0.1,0.999};\npriors.kappa={0.1,0.001,5};\npriors.psi={0.5,0.001,1};\npriors.rhou={0.5,-0.999,0.999};\npriors.rhog={0.5,-0.999,0.999};\npriors.rhoe={0.5,-0.999,0.999};\npriors.sigu={0.1,0.001,15};\npriors.sigg={0.1,0.001,15};\npriors.sige={0.1,0.001,15};\n%% estimate model\n\nmest=estimate(m,'data_demean',true,'data',db,'priors',priors,...\n    'estim_start_date','1973Q2','estim_end_date','2015Q4');\n\n", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/stata/driver10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5714986736282766}}
{"text": "function p_ = ViewRealizedVol(X,p)\n\n[J,K]=size(X);\n\n% constrain probabilities to sum to one...\nAeq = ones(1,J);\nbeq=1;\n\n% ...constrain the median...\nV = abs(X(:,1));\n\n[V_Sort I_Sort]=sort(V);\nF=cumsum(p(I_Sort));\n\nI_Reference=max(find(F<=3/5));\nV_Reference=V_Sort(I_Reference);\n\n\nI_Select=find(V<=V_Reference);\n\na=zeros(1,J);\na(I_Select)=1;\n\nA = a;\nb = .5;\n\n% ...compute posterior probabilities\np_ = EntropyProg(p,A,b,Aeq ,beq);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21307-fully-flexible-views-and-stress-testing/EntropyPooling/ButterflyTrading/ViewRealizedVol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.571498662112026}}
{"text": "classdef (Abstract) AbstractSimulator < handle\n% Abstract class for movement simulation. \n% Author: Yu Jiang\n% Contact: yu.jiang@nyu.edu\n% Copyright 2015 Yu Jiang\n\n    properties (Constant)      \n        % Constant simulation parameters\n        tau = 0.05;   % Time constant\n        m1 = 2;       % mass on x direction\n        m2 = 2;       % mass on y direction\n        \n        c1 = 0.15/2;  % noise scale\n        c2 = 0.05/2;  % noise scale\n        dt_ = 0.005;   % sample time for learning\n        \n        Q0 = [500 0; 0 1000];   % Initial weighting matrices\n        R = diag([0.01,0.01]);  % Initial weighting matrices\n        \n        % The null filed dynamics\n        A0 = [zeros(2) eye(2) zeros(2);\n              zeros(2,4) diag([1/AbstractSimulator.m1 1/AbstractSimulator.m2])\n              zeros(2,4) -diag([1/AbstractSimulator.tau 1/AbstractSimulator.tau])];\n        B =  [zeros(4,2); diag([1/AbstractSimulator.tau 1/AbstractSimulator.tau])];\n    end\n    \n    properties\n        % Variables \n        dt % Sample time for simulation               \n        A  % Dynamics with Force field\n    end\n    \n    \n    properties        \n        % Others\n        fig1;\n        fig2;\n        fig3;\n    end\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/Chapter7_Example1/AbstractSimulator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915994285382, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5714986619947144}}
{"text": "function fv= proc_rSquareSigned(fv, varargin)\n%PROC_RSQUARESIGNED - computes signed r^2 values (measure for discriminance)\n%\n%Synopsis:\n% \tfv = proc_rSquareSigned(fv, <opt>)\n%\n%Returns:\n% FV_RVAL - data structure of signed squared biserial correlation coefficients\n%  .x     - signed squared biserial correlation between each featur and the \n%           class label\n%  .se    - contains the standard error of atanh(r), if opt.Stats==1\n%  .p     - contains the p value of null hypothesis that there is zero\n%           correlation between feature and class-label, if opt.Stats==1\n%  .sgnlogp - contains the signed log10 p-value, if opt.Stats==1\n%             if opt.Bonferroni==1, the p-value is multiplied by\n%             fv_rval.corrfac\n%  .sgnlogp - contains the signed log10 p-value, if opt.Stats==1\n%           if opt.Bonferroni==1, the p-value is multiplied by\n%           fv_rval.corrfac and then logarithmized\n%  .sigmask - binary array indicating significance at alpha level\n%             opt.Alphalevel, if opt.Stats==1 and opt.Alphalevel > 0\n%  .corrfac - Bonferroni correction factor (number of simultaneous tests), \n%             if opt.Bonferroni==1\n%\n%Properties:\n% 'TolerateNans': observations with NaN value are skipped\n%    (nanmean/nanstd are used instead of mean/std). Deafult: 0\n% 'ValueForConst': constant feauture dimensions are assigned this\n%    value. Default: NaN.\n% 'MulticlassPolicy': possible options: 'pairwise' (default), \n%    'all-against-last', 'each-against-rest', or provide specified\n%    pairs as an [nPairs x 2] sized matrix. ('specified_pairs' is obsolete)\n% 'Stats' - if true, additional statistics are calculated, including the\n%           standard error of atanh(r), the p-value for the null \n%           Hypothesis that the correlation is zero, \n%           and the \"signed log p-value\"\n% 'Bonferroni' - if true, Bonferroni corrected is used to adjust p-values\n%                and their logarithms\n% 'Alphalevel' - if provided, a binary indicator of the significance to the\n%                alpha level is returned for each feature in fv_rval.sigmask\n% \n%Description:\n% Computes the r^2 value for each feature, multiplied by the sign of\n% of r value. The r^2 value is a measure\n% of how much variance of the joint distribution can be explained by\n% class membership.\n%\n% Example:\n%  [cnt, mrk]= file_readBV(some_file);   %load EEG-data in BV-format\n%  mrk= mrk_defineClasses(mrk, {1, 2; 'target','nontarget'}); \n%  epo= proc_segmentation(cnt, mrk, [-200 800], 'CLab', {'Fz','Cz','Pz'});\n%  epo_r = proc_rSquareSigned(epo);\n%\n% See also proc_classmeanDiff, proc_rValues, proc_rSquare\n%\n% 03-03 Benjamin Blankertz\n% 09-2012 stefan.haufe@tu-berlin.de\n\nif nargin==0,\n  fv=proc_rValues; return\nend\n\nfv= proc_rValues(fv, varargin{:});\nfv.x= fv.x .* abs(fv.x);\nfor cc= 1:length(fv.className),\n  fv.className{cc}= ['sgn r^2' fv.className{cc}(2:end)];\nend\nfv.yUnit= 'sgn r^2';\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/processing/proc_rSquareSigned.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5714625754740179}}
{"text": "function [rRelmTest] = relm_NTest(vRatesH, vRatesN, nNumberSimulation, fMagThreshold, bOptimized, bDrawFigure)\n% function [rRelmTest] = relm_NTest(vRatesH, vRatesN, nNumberSimulation, fMagThreshold, bOptimized, bDrawFigure)\n% --------------------------------------------------------------------------------------------------------------\n% Computation of the N-test for the RELM framework\n%\n% Input parameters:\n%   vRatesH                       Matrix with rates of the test hypothesis\n%   vRatesN                       Matrix with rates of the null hypothesis\n%   nNumberSimulation             Number of random simulations\n%   fMagThreshold                 Magnitude threshold (Use only bins with magnitude >= threshold\n%   bOptimized                    0 (default): use a for loop, 1: matrix-wise calculation (needs a lot of memory)\n%   bDrawFigure                   Draw the cumulative density plot after testing (default: off)\n%\n% Output paramters:\n%   rRelmTest.fAlpha              Alpha-value of the cumulative density\n%   rRelmTest.fBeta               Beta-value of the cumulative density\n%   rRelmTest.vSimValues_H        Vector containing the sorted simulated numbers of events for the test hypothesis\n%   rRelmTest.vSimValues_N        Vector containing the sorted simulated numbers of events for the null hypothesis\n%   rRelmTest.nNumberSimulation   Number of random simulations\n%   rRelmTest.fObservedData       Observed total number of events\n%\n% Danijel Schorlemmer\n% October 4, 2002\n\n% Exit on empty rate matrices\nif isempty(vRatesH)  ||  isempty(vRatesN)\n  rRelmTest.fAlpha = nan;\n  rRelmTest.fBeta = nan;\n  rRelmTest.vSimValues_H = nan;\n  rRelmTest.vSimValues_N = nan;\n  rRelmTest.nNumberSimulation = nan;\n  rRelmTest.fObservedData = nan;\n  return;\nend\n\nif ~exist('bDrawFigure')\n  bDrawFigure = 0;\nend\n\nif ~exist('bOptimized')\n  bOptimized = 0;\nend\n\n% Randomize\nrand('state',sum(100*clock));\n\n% Get the necessary data from the rate matrices and weight them properly\n[vLambdaH, vLambdaN, vNumberQuake] = relm_PrepareData(vRatesH, vRatesN, fMagThreshold);\nnNumberQuake = sum(vNumberQuake);\n\n% Get the number of bins (rows)\n[nRow, nColumn] = size(vLambdaH);\n\nif bOptimized\n  % Create the random numbers for the simulation\n  vRandom = rand(nRow, nNumberSimulation);\n\n  % Replicate the rate vectors\n  vLambdaH = repmat(vLambdaH, 1, nNumberSimulation);\n  vLambdaN = repmat(vLambdaN, 1, nNumberSimulation);\n\n  % Compute the simulated number of events and sum them up\n  vNum_H = poissinv(vRandom, vLambdaH);\n  vNum_N = poissinv(vRandom, vLambdaN);\n  vSimNum_H = sum(vNum_H);\n  vSimNum_N = sum(vNum_N);\nelse\n  % Create empty vectors for the total number of events\n  vSimNum_H = [];\n  vSimNum_N = [];\n\n  % Loop over the simulations\n  for nCnt = 1:nNumberSimulation\n    % Create the random numbers for the simulation\n    vRandom = rand(nRow, 1);\n\n    % Compute the simulated number of events and sum them up\n    vNum_H = poissinv(vRandom, vLambdaH);\n    vNum_N = poissinv(vRandom, vLambdaN);\n    vSimNum_H = [vSimNum_H; nansum(vNum_H)];\n    vSimNum_N = [vSimNum_N; nansum(vNum_N)];\n  end\nend\n\n% Sort them for the cumulative density plot\nrRelmTest.vSimValues_H = sort(vSimNum_H);\nrRelmTest.vSimValues_N = sort(vSimNum_N);\n\n% Compute Alpha and Beta and store the important parameters\nrRelmTest.fAlpha = sum(rRelmTest.vSimValues_N > nNumberQuake)/nNumberSimulation;\nrRelmTest.fBeta = sum(rRelmTest.vSimValues_H < nNumberQuake)/nNumberSimulation;\nrRelmTest.nNumberSimulation = nNumberSimulation;\nrRelmTest.fObservedData = nNumberQuake;\n\nif bDrawFigure\n  relm_PaintCumPlot(rRelmTest, 'Number of earthquakes');\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/zmap_deprecated/orphaned/src/danijel/relm/relm_NTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5714625750037831}}
{"text": "function [occGrad,occlusionErrors] = occlusionGrad(S,state)\n\noccGrad = zeros(size(S));\nnumpoints = size(S,1);\n\nmask = double(state.mask);\n[Y,X]=size(mask);\nmkp = mean(state.kps,2);% we had shifted everything by this when computing projected points so shift back now\n\n%% Finding points projected outside the image\npoints2d = state.cameraScale*state.cameraRot*S'; %% Verify this later\npoints2d = points2d' + repmat(mkp',size(S,1),1);\npoints2d = round(points2d(:,1:2)); %% Verify correctness later\n\nbadX = double(points2d(:,1)>X) + double(points2d(:,1)<1);\nbadY = double(points2d(:,2)>Y) + double(points2d(:,2)<1);\n\n%% Visualization\n%imagesc(mask);hold on;\n%plot(points2d(:,1),points2d(:,2));pause();\n%close;\n\n%% Restructuring to ease computation to determine of projected points inside silhoutte\npoints2d = points2d*[Y;1]-Y;\npoints2d(points2d>X*Y)=X*Y;\npoints2d(points2d<1)=1;\n\nmask = double(mask(:)==0);\nocclusionErrors = double((mask(points2d)+badX+badY)>0);\noccGrad = repmat(occlusionErrors,1,3).*(repmat(mean(S,1),numpoints,1)-S);\n\nend\n", "meta": {"author": "akar43", "repo": "CategoryShapes", "sha": "55c9dab2293bcaceaaa3bf5fea782fdbf930fadb", "save_path": "github-repos/MATLAB/akar43-CategoryShapes", "path": "github-repos/MATLAB/akar43-CategoryShapes/CategoryShapes-55c9dab2293bcaceaaa3bf5fea782fdbf930fadb/basisShapes/optimization/occlusionGrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5714625698935278}}
{"text": "% Script demonstrating usage of the cbpdndlms function.\n%\n% Author: Brendt Wohlberg <brendt@lanl.gov>  Modified: 2017-04-29\n%\n% This file is part of the SPORCO library. Details of the copyright\n% and user license can be found in the 'Copyright' and 'License' files\n% distributed with the library.\n\n\n% Training images\nS0 = zeros(512, 512, 2, 'single');\nS0(:,:,1) = single(stdimage('lena.grey')) / 255;\nS0(:,:,2) = single(stdimage('barbara.grey')) / 255;\n\n\n%Reduce images size to speed up demo script\ntmp = zeros(128, 128, 2, 'single');\nfor k = 1:size(S0,3),\n  tmp(:,:,k) = imresize(S0(:,:,k), 0.25);\nend\nS0 = tmp;\n\n\n% Filter input images and compute highpass images\nnpd = 16;\nfltlmbd = 5;\n[Sl, Sh] = lowpass(S0, fltlmbd, npd);\n\n\n% Construct weight matrix and padded test image set\nShp = padarray(Sh, [7 7], 'post');\nt = 0.5;\nW = randn(size(Sh));\nW(abs(W) > t) = 1;\nW(abs(W) < t) = 0;\nW = padarray(W, [7 7], 'post');\nShW = W .* Shp;\n\n\n% Construct initial dictionary\nD0 = zeros(8,8,32, 'single');\nD0(3:6,3:6,:) = single(randn(4,4,32));\n\n\n% Set up cbpdndl parameters\nlambda = 0.05;\nopt = [];\nopt.Verbose = 1;\nopt.MaxMainIter = 500;\nopt.rho = 50*lambda + 0.5;\nopt.sigma = size(Sh,3);\nopt.AutoRho = 1;\nopt.AutoRhoPeriod = 10;\nopt.AutoSigma = 1;\nopt.AutoSigmaPeriod = 10;\nopt.XRelaxParam = 1.8;\nopt.DRelaxParam = 1.8;\n\n\n% Do standard dictionary learning and reconstruct\n[D1, X1, optinf1] = cbpdndl(D0, ShW, lambda, opt);\nDX1 = ifft2(bsxfun(@times, fft2(D1, size(X1,1), size(X1,2)), fft2(X1)), ...\n           'symmetric');\nSr1 = squeeze(sum(DX1,3)) + padarray(Sl, [7 7], 'post');\n\n% Do dictionary learning with additive mask simulation and reconstruct\nopt.W = W;\n[D2, X2, optinf2] = cbpdndlms(D0, ShW, lambda, opt);\nDX2 = ifft2(bsxfun(@times, fft2(D2, size(X2,1), size(X2,2)), fft2(X2)), ...\n           'symmetric');\nSr2 = squeeze(sum(DX2,3)) + padarray(Sl, [7 7], 'post');\n\n\n% Display dictionaries\nfigure;\nsubplot(1,2,1);\nimdisp(tiledict(D1));\ntitle('Standard DL');\nsubplot(1,2,2);\nimdisp(tiledict(D2));\ntitle('DL with additive mask simulation');\n\n\n% Display reconstructions\nfigure;\nsubplot(2,2,1);\nimdisp(Sr1(:,:,1));\ntitle('Standard DL');\nsubplot(2,2,2);\nimdisp(Sr2(:,:,1));\ntitle('DL with additive mask simulation');\nsubplot(2,2,3);\nimdisp(Sr1(:,:,2));\ntitle('Standard DL');\nsubplot(2,2,4);\nimdisp(Sr2(:,:,2));\ntitle('DL with additive mask simulation');\n\n\n% Plot functional value evolution\nfigure;\nsubplot(1,2,1);\nsemilogx(optinf1.itstat(:,2), 'LineWidth', 2);\nylim([15, 45]);\nxlabel('Iterations');\nylabel('Functional value');\ntitle('Standard DL');\nsubplot(1,2,2);\nsemilogx(optinf2.itstat(:,2), 'LineWidth', 2);\nylim([15, 45]);\nxlabel('Iterations');\nylabel('Functional value');\ntitle('DL with additive mask simulation');\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/ConvSR_Image_Fusion_Codes/sporco/Demo/demo_cbpdndlms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5714625657237412}}
{"text": "%[2018]-\"Tree growth algorithm (TGA): A novel approach for solving\n%optimization problems\"\n\nfunction TGA = jTreeGrowthAlgorithm(feat,label,opts)\n% Parameters\nlb         = 0;\nub         = 1; \nthres      = 0.5; \nnum_tree1  = 3;    % size of first group\nnum_tree2  = 5;    % size of second group\nnum_tree4  = 3;    % size of fourth group\ntheta      = 0.8;  % tree reduction rate of power\nlambda     = 0.5;  % control nearest tree\n\nif isfield(opts,'T'), max_Iter = opts.T; end\nif isfield(opts,'N'), N = opts.N; end\nif isfield(opts,'N1'), num_tree1 = opts.N1; end \nif isfield(opts,'N2'), num_tree2 = opts.N2; end \nif isfield(opts,'N4'), num_tree4 = opts.N4; end \nif isfield(opts,'theta'), theta = opts.theta; end \nif isfield(opts,'lambda'), lambda = opts.lambda; end \nif isfield(opts,'thres'), thres = opts.thres; end \n\n% Limit number of N4 to N1\nif num_tree4 > num_tree1 + num_tree2\n  num_tree4 = num_tree1 + num_tree2; \nend\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  % Best \n  if fit(i) < fitG\n    fitG = fit(i); \n    Xgb  = X(i,:);\n  end\nend\n% Sort tree from best to worst\n[fit, idx] = sort(fit,'ascend');\nX          = X(idx,:); \n% Initial\ndist = zeros(1,num_tree1 + num_tree2);\nX1   = zeros(num_tree1,dim);\nXnew = zeros(num_tree4,dim);\nFnew = zeros(1,num_tree4);\n\ncurve = zeros(1,max_Iter);\ncurve(1) = fitG;\nt = 2;\n% Iterations\nwhile t <= max_Iter\n\t% {1} Best trees group\n  for i = 1:num_tree1\n    r1 = rand();\n    for d = 1:dim\n      % Local search (1)\n      X1(i,d) = (X(i,d) / theta) + r1 * X(i,d);\n    end\n  \t% Boundary\n    XB = X1(i,:); XB(XB > ub) = ub; XB(XB < lb) = lb;\n    X1(i,:) = XB;\n    % Fitness\n    fitT = fun(feat,label,(X1(i,:) > thres),opts);\n    % Greedy selection\n    if fitT <= fit(i)\n      X(i,:) = X1(i,:);\n      fit(i) = fitT;\n    end\n  end\n  % {2} Competitive for light tree group\n  X_ori = X;\n  for i = num_tree1 + 1 : num_tree1 + num_tree2\n    % Neighbor tree\n    for j = 1 : num_tree1 + num_tree2           \n      if j ~= i\n        % Compute Euclidean distance (2)\n        dist(j) = sqrt(sum((X_ori(j,:) - X_ori(i,:)) .^ 2));\n      else\n        % Solve same tree problem\n        dist(j) = inf;\n      end\n    end\n    % Find 2 trees with shorter distance\n    [~, idx] = sort(dist,'ascend'); \n    T1       = X_ori(idx(1),:);\n    T2       = X_ori(idx(2),:); \n    % Alpha in [0,1]\n    alpha    = rand();\n    for d = 1:dim\n      % Compute linear combination between 2 shorter tree (3)\n      y = lambda * T1(d) + (1 - lambda) * T2(d);\n      % Move tree i between 2 adjacent trees (4)\n      X(i,d) = X(i,d) + alpha * y;\n    end\n    % Boundary\n    XB = X(i,:); XB(XB > ub) = ub; XB(XB < lb) = lb;\n    X(i,:) = XB;\n    % Fitness\n    fit(i) = fun(feat,label,(X(i,:) > thres),opts);\n  end\n  % {3} Remove and replace group\n  for i = num_tree1 + num_tree2 + 1 : N\n    for d = 1:dim\n      % Generate new tree by remove worst tree\n      X(i,d) = lb + (ub - lb) * rand();\n    end\n    % Fitness\n    fit(i) = fun(feat,label,(X(i,:) > thres),opts);\n  end\n  % {4} Reproduction group\n  for i = 1:num_tree4\n    % Random a best tree\n    r     = randi([1,num_tree1]);\n    Xbest = X(r,:);\n    % Mask operator\n    mask  = randi([0,1],1,dim);\n    % Mask opration between new & best trees\n    for d = 1:dim\n      % Generate new solution \n      Xn = lb + (ub - lb) * rand();\n      if mask(d) == 1\n        Xnew(i,d) = Xbest(d);\n      elseif mask(d) == 0\n        % Generate new tree\n        Xnew(i,d) = Xn;\n      end\n    end\n    % Fitness\n    Fnew(i) = fun(feat,label,(Xnew(i,:) > thres),opts);\n  end\n  % Sort population get best nPop trees\n  XX        = [X; Xnew];\n  FF        = [fit, Fnew];\n  [FF, idx] = sort(FF,'ascend');\n  X         = XX(idx(1:N),:);\n  fit       = FF(1:N);\n  % Global best\n  if fit(1) < fitG\n    fitG = fit(1); \n    Xgb  = X(1,:);\n  end\n  curve(t) = fitG;\n  fprintf('\\nIteration %d Best (TGA)= %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\nTGA.sf = Sf; \nTGA.ff = sFeat; \nTGA.nf = length(Sf); \nTGA.c  = curve;\nTGA.f  = feat;\nTGA.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/jTreeGrowthAlgorithm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5714625647832727}}
{"text": "function marginal = marginal_family(engine, i, t)\n% MARGINAL_FAMILY Compute the marginal on the specified family (ff)\n% marginal = marginal_family(engine, i, t)\n\nif nargin < 3, t = 1; end\n\n% The method is similar to the following HMM equation:\n% xi(i,j,t) = normalise( alpha(i,t) * transmat(i,j) * obsmat(j,t+1) * beta(j,t+1) )\n% where xi(i,j,t) = Pr(Q(t)=i, Q(t+1)=j | y(1:T))\n\nbnet = bnet_from_engine(engine);\n\nif myismember(i, engine.onodes)\n  ps = parents(bnet.dag, i);\n  p = ps(1);\n  marginal = pot_to_marginal(engine.marginals{p,t});\n  marginal.domain = [p i];\n  return;\nend\n\nif t==1\n  marginal = pot_to_marginal(engine.marginals{i,t});\n  return;\nend\n\nbnet = bnet_from_engine(engine);\nss = length(bnet.intra);\npot = engine.CPDpot{i,t};\nc = engine.obschild(i);\npot = multiply_by_pot(pot, engine.CPDpot{c,t});\npot = multiply_by_pot(pot, engine.back{i,t});\nps = parents(bnet.dag, i+ss);\nfor p=ps(:)'\n  pot = multiply_by_pot(pot, engine.fwd{p,t-1});\nend\nmarginal = pot_to_marginal(normalize_pot(pot));\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/inference/dynamic/@ff_inf_engine/Old/marginal_family.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5714625596730174}}
{"text": "% SYNTAX:\n% intensity = hmrR_PreprocessIntensity_MedianFilter( intensity )\n%\n% UI NAME:\n% hmrR_PreprocessIntensity_MedianFilter\n%\n% DESCRIPTION:\n% Applies a median filter to data to remove huge spikes.\n%\n% INPUT:\n% intensity - SNIRF data type where the d matrix is intensity\n%\n% OUTPUT:\n% intensity - SNIRF data type where the d matrix is intensity\n%\n% USAGE OPTIONS:\n% Intensity_to_Intensity: d = hmrR_PreprocessIntensity_MedianFilter(data)\n\n\nfunction d = hmrR_PreprocessIntensity_MedianFilter( intensity)\n\n\nfor ii=1:length(intensity)\n    d = intensity(ii).GetDataTimeSeries();\n    \n    for j = 1:size(d,2)\n        foo = d(:,j);\n        \n        \n        xdata = (1:length( foo))';\n        d(:,j) = interp1(xdata(~isnan( foo)), foo(~isnan( foo)),xdata,'spline');\n        \n        new_signal = zeros(size(foo));\n        new_signal(1) = foo(1);\n        new_signal(end) = foo(end);\n        for tp = 2:length(foo)-1\n            values = foo([tp-1,tp,tp+1]);\n            median_value = median(values);\n            new_signal(tp) = median_value;\n        end\n        d(:,j) = new_signal;\n        \n    end\n    \n    intensity(ii).SetDataTimeSeries(d);\nend\n", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/FuncRegistry/UserFunctions/hmrR_PreprocessIntensity_MedianFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5714625540925276}}
{"text": "function www=trajt3(para,chrom)\n\nx0=para(1);\ny0=para(2);\nz0=para(3);\nvx0=0;\nvy0=0;\nvz0=0;\nax0=0;\nay0=0;\naz0=0;\nx2=para(4);\ny2=para(5);\nz2=para(6);\nvx2=0;\nvy2=0; \nvz2=0;\nax2=0;\nay2=0;\naz2=0;\nx1=chrom(1);\ny1=chrom(2);\nz1=chrom(3);\nvx1=chrom(4);\nvy1=chrom(5);\nvz1=chrom(6);\nt1=chrom(7);\nt2=chrom(8);\n\na00=x0;\na01=vx0;\na02=ax0/2;\na03=(4*x1-vx1*t1-4*x0-3*vx0*t1-ax0*t1^2)/t1^3;\na04=(vx1*t1-3*x1+3*x0+2*vx0*t1+ax0*t1^2/2)/t1^4;\nax1=2*a02+6*a03*t1+12*a04*t1^2;\n\nc00=y0;\nc01=vy0;\nc02=ay0/2;\nc03=(4*y1-vy1*t1-4*y0-3*vy0*t1-ay0*t1^2)/t1^3;\nc04=(vy1*t1-3*y1+3*y0+2*vy0*t1+ay0*t1^2/2)/t1^4;\nay1=2*c02+6*c03*t1+12*c04*t1^2;\n\ne00=z0;\ne01=vz0;\ne02=az0/2;\ne03=(4*z1-vz1*t1-4*z0-3*vz0*t1-az0*t1^2)/t1^3;\ne04=(vz1*t1-3*z1+3*z0+2*vz0*t1+az0*t1^2/2)/t1^4;\naz1=2*e02+6*e03*t1+12*e04*t1^2;\n%--------------------------------------------------------------------------\nb10=x1;\nb11=vx1;\nb12=ax1/2;\nb13=(20*x2-20*x1-(8*vx2+12*vx1)*t2-(3*ax1-ax2)*t2^2)/(2*t2^3);\nb14=(30*x1-30*x2+(14*vx2+16*vx1)*t2+(3*ax1-2*ax2)*t2^2)/(2*t2^4);\nb15=(12*x2-12*x1-(6*vx2+6*vx1)*t2-(ax1-ax2)*t2^2)/(2*t2^5);\n\nd10=y1;\nd11=vy1;\nd12=ay1/2;\nd13=(20*y2-20*y1-(8*vy2+12*vy1)*t2-(3*ay1-ay2)*t2^2)/(2*t2^3);\nd14=(30*y1-30*y2+(14*vy2+16*vy1)*t2+(3*ay1-2*ay2)*t2^2)/(2*t2^4);\nd15=(12*y2-12*y1-(6*vy2+6*vy1)*t2-(ay1-ay2)*t2^2)/(2*t2^5);\n\nf10=z1;\nf11=vz1;\nf12=az1/2;\nf13=(20*z2-20*z1-(8*vz2+12*vz1)*t2-(3*az1-az2)*t2^2)/(2*t2^3);\nf14=(30*z1-30*z2+(14*vz2+16*vz1)*t2+(3*az1-2*az2)*t2^2)/(2*t2^4);\nf15=(12*z2-12*z1-(6*vz2+6*vz1)*t2-(az1-az2)*t2^2)/(2*t2^5);\n%--------------------------------------------------------------------------\n\nt=linspace(0,t1,20);\n\nx01=a00+a01*t+a02*t.^2+a03*t.^3+a04*t.^4;\nvx01=a01+2*a02*t+3*a03*t.^2+4*a04*t.^3;\nax01=2*a02+6*a03*t+12*a04*t.^2;\n\ny01=c00+c01*t+c02*t.^2+c03*t.^3+c04*t.^4;\nvy01=c01+2*c02*t+3*c03*t.^2+4*c04*t.^3;\nay01=2*c02+6*c03*t+12*c04*t.^2;\n\nz01=e00+e01*t+e02*t.^2+e03*t.^3+e04*t.^4;\nvz01=e01+2*e02*t+3*e03*t.^2+4*e04*t.^3;\naz01=2*e02+6*e03*t+12*e04*t.^2;\n%--------------------------------------------------------------------------\nt=linspace(0,t2,20);\n\nx12=b10+b11*t+b12*t.^2+b13*t.^3+b14*t.^4+b15*t.^5;\nvx12=b11+2*b12*t+3*b13*t.^2+4*b14*t.^3+5*b15*t.^4;\nax12=2*b12+6*b13*t+12*b14*t.^2+20*b15*t.^3;\n\ny12=d10+d11*t+d12*t.^2+d13*t.^3+d14*t.^4+d15*t.^5;\nvy12=d11+2*d12*t+3*d13*t.^2+4*d14*t.^3+5*d15*t.^4;\nay12=2*d12+6*d13*t+12*d14*t.^2+20*d15*t.^3;\n\nz12=f10+f11*t+f12*t.^2+f13*t.^3+f14*t.^4+f15*t.^5;\nvz12=f11+2*f12*t+3*f13*t.^2+4*f14*t.^3+5*f15*t.^4;\naz12=2*f12+6*f13*t+12*f14*t.^2+20*f15*t.^3;\n%--------------------------------------------------------------------------\nppx=[x01 x12];ppy=[y01 y12];ppz=[z01 z12];\nq1=ppx;q2=ppy;q3=ppz;\n\nvvx=[vx01 vx12];vvy=[vy01 vy12];vvz=[vz01 vz12];\nvq1=vvx;vq2=vvy;vq3=vvz;\n\naax=[ax01 ax12];aay=[ay01 ay12];aaz=[az01 az12];\naq1=aax;aq2=aay;aq3=aaz;\n\nwww=[q1;q2;q3;vq1;vq2;vq3;aq1;aq2;aq3];\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/23289-motion-planning-for-a-robot-arm-by-using-genetic-algorithm/robot motion planning/matlab code/trajt3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5714021916870505}}
{"text": "function setG(OCP,G)\n    % assert\n    if OCP.dim.u + OCP.dim.x < 30\n        Gux = jacobian(G,[OCP.u;OCP.x]);\n        hasUX = has(Gux(:),[OCP.u;OCP.x]);\n        if sum(hasUX(:)) ~= 0\n            error('G must be a linear function of u and x!');\n        end\n    end\n    OCP.G = G;\n    % Global variable\n    global ParNMPCGlobalVariable\n    G_formula = formula(OCP.G);\n    [zDim,~] = size(G_formula);\n    ParNMPCGlobalVariable.dim.z = zDim;\n    ParNMPCGlobalVariable.solutionInitGuess.z = zeros(zDim,ParNMPCGlobalVariable.N);\n    OCP.dim.z      = zDim;\n    OCP.z          = sym('z',[OCP.dim.z,1]);\n    if size(OCP.z,1) ~= OCP.dim.z\n       OCP.z = OCP.z.';\n    end\n    OCP.LBarrier   = sym(0);\n    %% barrier term\n    for i = 1:zDim\n        OCP.LBarrier = OCP.LBarrier - log(G_formula(i));\n    end\n    %% linear damping term\n    for i = 1:zDim\n        OCP.LBarrier = OCP.LBarrier + 1e-4*G_formula(i);\n    end\nend", "meta": {"author": "deng-haoyang", "repo": "ParNMPC", "sha": "ddbe418e630b49897e8bc17e5c2f9e1ef1ab453b", "save_path": "github-repos/MATLAB/deng-haoyang-ParNMPC", "path": "github-repos/MATLAB/deng-haoyang-ParNMPC/ParNMPC-ddbe418e630b49897e8bc17e5c2f9e1ef1ab453b/ParNMPC/@OptimalControlProblem/setG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5713921934900191}}
{"text": "function [y] = cellcrossproduct(x)\n\n% [Y] = CELLSUBSELECT(X, BOOLVEC, DIM) outputs a cell-arry Y with the same dimension as X\n% but for each input cell the n(n+1)/2 cross products of the rows are computed.\n% the cross-products are ordered along the lower-triangle of the pairwise\n% matrix.\n\nnx = size(x);\nif ~iscell(x) || length(nx)>2 || all(nx>1),\n  error('incorrect input for cellcrossproduct');\nend\n\nn = cellfun('size', x, 1);\nif ~all(n==n(1))\n  error('each cell should have the same number of rows');\nend\n%[ix{1}(:,1),ix{1}(:,2)] = find(tril(ones(n(1))));\n\n%y = cellfun(@crossprod, x, repmat(ix, nx), 'UniformOutput', 0);\ny = cellfun(@crossprod, x, 'UniformOutput', 0);\n\nfunction [y] = crossprod(x)\n\n% FIXME only works in case of dim=2\nn    = size(x);\nindx = tril(ones(n(1)))==1;\ny = zeros(0.5*n(1)*(n(1)+1), n(2));\nfor k = 1:n(2)\n  tmp = tril(x(:,k)*x(:,k)');\n  y(:,k) = tmp(indx);\nend\n\n\n% function [y] = crossprod(x, ix)\n% \n% %FIXME works only in case of dim=2\n% n = size(x);\n% y = zeros(0.5*n(1)*(n(1)+1), n(2));\n% for k = 1:size(ix,1)\n%   y(k,:) = x(ix(k,1),:).*x(ix(k,2),:);\n% end\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/cellfunction/cellcrossproduct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.6893056040203136, "lm_q1q2_score": 0.5713921717918105}}
{"text": "% TIMEFDETAILS - details of the TIMEF function for time/frequency analysis \n%                  of multiple epochs of single-channel event-related data.\n%\n% Global Description:\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% TIMEF performs normalized time/frequency averaging using either \n% FFT-, wavelet-, or multitaper DFT estimates. The wavelets are N-cycle \n% Hanning-windowed sinusoids. (Note: To substitute for HANNING windowing \n% GAUSS or other windowing, replace the timef.m reference to HANNING).\n%\n% By default, the two image panels of the output plot show, respectively, the\n% event-related spectral perturbation (ERSP) and inter-trial coherence (ITC)\n% of the input data.\n%\n% The ERSP: \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The ERSP (S. Makeig, Electroencephalogr Clin Neurophysiol 86:283-93, 1993) \n% shows mean log event-loced deviations from epoch-mean (or baseline-mean) power\n% at each frequency. If bootstrap statistics are computed (via the 'alpha'\n% probability input parameter), (time, freq) points with non-significant \n% differences from 0 are colored green in the image (but not in the 'ersp' \n% output variable - use the output 'erspboot' variable to re-mask the 'ersp'\n% output if desired). The baseline mean spectrum removed from each epoch\n% is available as output parameter \"powbase\". Note that log(power) differences\n% are equivalent to log(power ratios) between baseline and observed spectra,\n% meaning the implicit ERSP model is one of (multiplicative) amplitude modulation\n% of the EEG/MEG spectrum by e.g. subcortical and/or intra-cortical influences.\n%\n% In the default view, the thin bottom panel below the upper (ERSP) image shows \n% the ERSP envelope (the most positive and most negative values at each output \n% time point). The thin left panel shows the mean (or baseline) log spectrum \n% (blue trace). When bootstrap statistics are computed (via the \"alpha\" argument), \n% the left panel (green trace) also shows the bootstrap significant levels (+/-) \n% at each frequency.\n%\n% The ITC: \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% (Inter-trial Coherence, cf. Tallon-Baudry et al., \"Phase-locking factor\")\n% The lower panel shows the degree of tendency for spectral phase at each\n% (time, freq) point to repeat across the data epochs. If bootstrap statistics\n% are computed (as per the 'alpha' input parameter), non-significant points\n% are colored green (but again not in the 'itc' output variable - use the \n% itcboot output to re-mask if desired in later plotting).\n%\n% The lower thin panel shows the time-domain average (ERP) of the input data \n% (blue) plus a zero-line (green). The average (ERP) is created principally by\n% partial phase resetting of the EEG as measured by the ITC. (While phase resetting \n% dominates, event-related spectral power changes (as measured by the ERSP) \n% may also play a minor role). The thin left panel shows the frequency-mean ITC \n% (blue trace) and, if bootstrap statistics are computed, the ITC significance \n% limits at each frequency (green trace).\n%\n% ITC Math Derivation:\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% By definition, linear coherence is\n%       R=mean(Fxy)/sqrt(mean(abs(Fxx))*mean(abs(Fyy)));\n% where Fxy is the cross-spectrum (FxFy*) and Fxx and Fyy the autospectra of  \n% processes x and y.  We define the phase coherence to be\n%       R=mean(Fxy/(abs(Fxx))*abs(Fyy));  % mean of individually normed Fxy\n% To derive the ITC, we consider y to be a stimulus-locked process \n% such that, at each time and frequency, angle(Fyy) = 0 and abs(Fyy) = 1.\n% Thus Pxy = Pxx, and the (complex) inter-trial phase coherence between x and\n% the constant stimulus-locked process y is\n%       ITC=mean(Pxx/abs(Pxx));\n%\n% USAGE:\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%   >> [ersp,itc,powbase,times,freqs,erspboot,itcboot]  ...\n%                = timef(data,frames,tlimits,srate,cycles,...\n%                              'key1',value1,'key2',value2, ... );        \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% NOTE:\n% * Left-click on subplots to view and zoom in separate windows (uses AXCOPY).\n%\n% Required Inputs:\n%   data        = Single-channel data vector (1,frames*ntrials) (required)\n%\n%   frames      = Frames per trial                        {750}\n%  Here, a frame is a data point (one channel at one time point) and the data\n%  is assumed to be composed of concatenated epochs of the same length (frames).\n%\n%   tlimits     = [mintime maxtime] (ms) Epoch time limits {[-1000 2000]}\n%  These should be the starting and ending times of the input epochs.\n%\n%   srate       = data sampling rate (Hz)                 {250}\n%  This is sample rate per channel (i.e., data frames per second).\n%\n%   cycles      = >0 -> Number of cycles in each analysis wavelet \n%                 =0 -> Use FFTs (with constant window length) {0}\n%                 If [wavecycles factor] -> wavelet cycles increase with frequency\n%                 beginning at wavecyles (0<factor<1; factor=1 -> no increase,\n%                 standard wavelets; factor=0 -> fixed epoch length, as in FFT.\n%                 OR multitaper decomposition (with 'mtaper').\n%  Here, the user chooses either to use the FFT method (fixed window size\n%  for all frequencies) or the wavelet DFT method (the data window length\n%  depends inversely on the frequency, e.g. '3' means that the data\n%  windows will each be three cycles wide (at each frequency). A higher\n%  number here (e.g., '5') will narrow the frequency band and widen the\n%  time window.\n%\n% Optional Inter-Irial Coherence Type:\n%   'type'      = ['coher'|'phasecoher'] Compute either linear coherence \n%                  ('coher') or phase coherence ('phasecoher') also known\n%                  as the phase coupling factor           {'phasecoher'}.\n%\n% Optional Detrending:\n%   'detret'    = ['on'|'off'], Detrend data in time.       {'off'}\n%   'detrep'    = ['on'|'off'], Detrend data across trials (at each time point\n%                 compute the linear trend across the set of ordered trials and \n%                 remove it; not that this also subtract the ERP) {'off'}\n%\n% Optional FFT/DFT Parameters:\n%   'winsize'   = If cycles==0: data subwindow length (fastest is 2^n < frames);\n%                 If cycles >0: *longest* window length to use. This determines \n%                 the lowest output frequency  {default: ~frames/8}\n%  When cycles>0, winsize determines the lowest computed frequency. For example,\n%  with srate=100 and cycles=3, a winsize of 100 means that 3 cycles must fit\n%  within a 1-sec ( 100-sample) window. So, the lowest output frequency is 3 Hz.\n%\n%  When cycles=0, winsize is the length of data in each FFT window. This may be \n%  extended with zeroes (to give more output frequencies) using padratio (below).\n%\n%  'timesout'  = Number of output times (int<frames-winframes) {200}\n%  The number of FFTs or wavelet DFTs computed and plotted.\n%\n%   'padratio'  = FFT-length/winframes (2^k)                    {2}\n%                  Multiplies the number of output frequencies by\n%                  dividing their spacing. When cycles==0, frequency\n%                  spacing is (low_freq/padratio).\n%  This factor multiplies the number of output frequencies. In the FFT method\n%  (cycles=0), this is done by zero-padding each analysis window. In the wavelet\n%  DFT method (cycles>0), this gives the number of frequencies per Hz.\n%\n%   'maxfreq'   = Maximum frequency (Hz) to plot (& to output, if cycles>0) \n%                  If cycles==0, all FFT frequencies are output. {50}\n%   'baseline'  = Spectral baseline end-time (in ms). Use NaN for no baseline\n%                 removal{0}\n%   'powbase'   = Baseline spectrum to log-subtract. 'baseline' parameter is\n%                 ignored if this parameter is used {def|NaN->from data}\n%  This is useful only when you want to use a known baseline spectrum (e.g. from\n%  another condition) instead of using the actual mean baseline spectrum of the data.\n%  Otherwise, leave this out or specify as 'NaN' (not a number).\n%\n% Optional Multitaper Parameters:\n%   'mtaper'    = If [N W], performs multitaper decomposition. \n%                  (N is the time resolution and W the frequency resolution; \n%                  maximum taper number is 2NW-1). Overwrites 'winsize' and \n%                  'padratio'. \n%                  If [N W K], forces the use of K Slepian tapers (if possible).\n%                  Phase is calculated using standard methods.\n%                  The use of mutitaper with wavelets (cycles>0) is not \n%                  recommended (as multiwavelets are not implemented). \n%                  Uses Matlab functions DPSS, PMTM.   {no multitaper}\n%\n% Optional Bootstrap Parameters:\n%   'alpha'     = If non-0, compute two-tailed bootstrap significance prob. \n%                  level. Show non-signif. output values as green.   {0}\n%  This optional parameter lengthens the computation time but gives bootstrap\n%  estimates of which ERSP and ITC values are significantly different from 0,\n%  by setting to 0 (green) all non-significant values in the ERSP and ITC images.\n%  Normal values for alpha are 0 ([], or none) -> no bootstrap computation, or\n%  0.01 (which should allow about 1% of random images to appear \"significant\" \n%\n%   'naccu'     = Number of bootstrap replications to accumulate     {200}\n%   'baseboot'  = Bootstrap baseline subtract (0 -> use 'baseline';\n%                                                  1 -> use whole trial) {0}\n% Optional Scalp Map Plotting Parameters:\n%   'topovec'   = Scalp topography (map) to plot                     {none}\n%   'elocs'     = Electrode location file for scalp map   {no default}\n%                     File should be ascii in format of  >> topoplot example   \n%  This is an optional map-plotting feature. Given an input map vector \n%  (one weight at each channel, and a electrode location file, TIMEF plots\n%  a TOPOPLOT-style 2-d scalp map on the left side of the figure. See\n%  >> topoplot example % for the format of the electrode location file.\n%\n% Other Optional Plotting Parameters:\n%   'vert'      = [vector of ms times] -> plot vertical dashed lines  {0 only}\n%  Use this to add extra vertical dashed lines at significant epoch times.\n%  Time 0 is marked by default.\n%                     \n%   'plotersp'  = ['on'|'off'] Plot power spectral perturbations    {'on'} \n%   'plotitc'   = ['on'|'off'] Plot inter trial coherence            {'on'}\n%   'title'     = Optional figure title                              {none}\n%\n%   'pboot'     = Bootstrap power limits (e.g., from TIMEF)   {from data}\n%   'rboot'     = Bootstrap ITC limits (e.g., from TIMEF)     {from data}\n%  These are useful if you want to apply significance limits from another condition \n%  to new data. {default|NaN, compute from data}\n%\n%   'linewidth' = Line width for 'marktimes' traces (thick=2, thin=1) {2}\n%   'axesfont'  = Axes text font size                                {10}\n%   'titlefont' = Title text font size                               {8}\n%\n% Outputs: \n%        ersp   = Matrix (nfreqs,timesout) of log spectral diffs. from baseline (dB) \n%        itc    = Matrix (nfreqs,timesout) of inter-trial phase coherence (range: [0 1])\n%   Note that when cycles=0, nfreqs is total number of FFT frequencies, which \n%   typically include frequencies higher than maxfreq. When cycles>0, *no* extra \n%   (higher) frequencies are computed.\n%\n%      powbase  = Baseline power spectrum (removed to compute the ERSP)\n%        times  = Vector of output times (subwindow centers) (in ms).\n%        freqs  = Vector of frequency bin centers (in Hz).\n%\n%     erspboot  = Matrix (2,nfreqs) of [lower;upper] ERSP significance diffs.\n%      itcboot  = Matrix (2,nfreqs) of [lower;upper] ITC thresholds (abs., not diffs)\n%  Note that the itcboot lower bound is practically meaningless.\n%\n%  Plot description:\n%    Assuming both 'plotersp' and 'plotitc' options are 'on' (= default). The upper panel\n%    presents the data ERSP (Event-Related Spectral Perturbation) in dB, with mean baseline\n%    spectral activity (in dB) subtracted. Use \"'baseline', NaN\" to prevent TIMEF from\n%    removing the baseline. The lower panel presents the data ITC (Inter-Trial Coherence).\n%    Click on any plot axes to pop up a new window (using 'AXCOPY')\n%    -- Upper left marginal panel presents the mean spectrum during the baseline period\n%       (blue), and when significance is set, the significance threshold at each frequency\n%       (dotted green-black trace).\n%    -- The marginal panel under the ERSP image shows the maximum (green) and minimum\n%       (blue) ERSP values relative to baseline power at each frequency.\n%    -- The lower left marginal panel shows mean ITC across the imaged time range (blue),\n%       and when significance is set, the significance threshold (dotted green-black).\n%    -- The marginal panel under the ITC image shows the ERP (which is produced by ITC\n%       across the data spectral pass band).\n%\n% Author: Sigurd Enghoff, Arnaud Delorme & Scott Makeig\n%          CNL / Salk Institute 1998- | SCCN/INC, UCSD 2002-\n%\n% See also: CROSSF - event-related cross-spectral coherence between two input\n%                      time series.\n%\n% History: \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% TIMEF was coded by Sigurd Enghoff and Scott Makeig at The Salk \n% Institute, La Jolla CA in August, 1998, using methods developed \n% in Makeig, 1993. Arno Delorme added the multitaper option, recoded\n% the function to use 'keyword','parameter' argument pairs, and added the\n% 'type' argument with advice from Joern Anemueller at SCCN/Institute for\n% Neural Computation, UCSD in early 2002.\n\n% Copyright (C) 8/01/00 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", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/sigprocfunc/timefdetails.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938799869521, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5713921654306908}}
{"text": "function asa266_test06 ( )\n\n%*****************************************************************************80\n%\n%% TEST06 tests GAMAIN, GAMMDS, GAMMAD.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    04 August 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n  ntest = 10;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST06\\n' );\n  fprintf ( 1, '  GAMAIN,\\n' );\n  fprintf ( 1, '  GAMMDS and \\n' );\n  fprintf ( 1, '  GAMMAD compute the incomplete Gamma integral.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  X  P  GAMMDS  GAMMAD  GAMAIN\\n' );\n  fprintf ( 1, '\\n' );\n\n  for i = 1 : ntest\n\n    x = i / ntest;\n\n    fprintf ( 1, '\\n' );\n\n    for j = 1 : ntest\n\n      p = j / ntest;\n      [ g1, ifault ] = gammds ( x, p );\n      if ( ifault ~= 0 )\n        g1 = -99.0;\n      end\n\n      [ g2, ifault ] = gammad ( x, p );\n      if ( ifault ~= 0 )\n        g2 = -99.0;\n      end\n\n      [ g3, ifault ] = gamain ( x, p );\n      if ( ifault ~= 0 )\n        g3 = - 99.0;\n      end\n\n      fprintf ( 1, '  %12f  %12f  %12f  %12f  %12f\\n', x, p, g1, g2, g3 );\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/asa266/asa266_test06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5712987641832008}}
{"text": "function [gradient, delta] = gradchek(w, func, grad, varargin)\n%GRADCHEK Checks a user-defined gradient function using finite differences.\n%\n%\tDescription\n%\tThis function is intended as a utility for other netlab functions\n%\t(particularly optimisation functions) to use.  It enables the user to\n%\tcheck whether a gradient calculation has been correctly implmented\n%\tfor a given function. GRADCHEK(W, FUNC, GRAD) checks how accurate the\n%\tgradient  GRAD of a function FUNC is at a parameter vector X.   A\n%\tcentral difference formula with step size 1.0e-6 is used, and the\n%\tresults for both gradient function and finite difference\n%\tapproximation are printed. The optional return value GRADIENT is the\n%\tgradient calculated using the function GRAD and the return value\n%\tDELTA is the difference between the functional and finite difference\n%\tmethods of calculating the graident.\n%\n%\tGRADCHEK(X, FUNC, GRAD, P1, P2, ...) allows additional arguments to\n%\tbe passed to FUNC and GRAD.\n%\n%\tSee also\n%\tCONJGRAD, GRADDESC, HMC, OLGD, QUASINEW, SCG\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n% Reasonable value for step size\nepsilon = 1.0e-6;\n\nfunc = fcnchk(func, length(varargin));\ngrad = fcnchk(grad, length(varargin));\n\n% Treat\nnparams = length(w);\ndeltaf = zeros(1, nparams);\nstep = zeros(1, nparams);\nfor i = 1:nparams\n  % Move a small way in the ith coordinate of w\n  step(i) = 1.0;\n  fplus  = feval('linef', epsilon, func, w, step, varargin{:});\n  fminus = feval('linef', -epsilon, func, w, step, varargin{:});\n  % Use central difference formula for approximation\n  deltaf(i) = 0.5*(fplus - fminus)/epsilon;\n  step(i) = 0.0;\nend\ngradient = feval(grad, w, varargin{:});\nfprintf(1, 'Checking gradient ...\\n\\n');\ndelta = gradient - deltaf;\nfprintf(1, '   analytic   diffs     delta\\n\\n');\ndisp([gradient', deltaf', delta'])\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/gradchek.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.5712987519902026}}
{"text": "%%  kmeans algorithm for an image\n%---input---------------------------------------------------------\n%   Y: 3D image\n%   k: number of clusters\n%   g: number of GMM components\n%---output--------------------------------------------------------\n%   X: 3D labels\n%   GMM: Gaussian mixture model parameters\n\nfunction [X GMM]=image_kmeans(Y,k,g)\n[m n l]=size(Y);\ny=Y(:);\nx=kmeans(y,k);\nX=reshape(x,[m n l]);\n\nGMM=get_GMM(X,Y,g);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39553-gmm-hmrf/GMM-HMRF_v1.0/code/three-dimensional/image_kmeans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.571298334288523}}
{"text": "%features\n% load 'facefeature_lw6lr1_512.mat'\n% features1=features;\n\n%mirror feature\n% load 'Mfacefeature_lw6lr1_512.mat'\n% features=[features,features1];\n\ntgt_method='facefeature_512'\ntgtDir='./LFWTest/';\n\nload pair_lfw\nfeatures=double(feature)';\nfeatures= bsxfun(@rdivide, features, sqrt(sum(features.^2,2)));\n\nimage_path = list;\n\nfor i=1:10\t\n\tintra_pairs=pair_lfw.IntraPersonPair{i};\n\textra_pairs=pair_lfw.ExtraPersonPair{i};\n\n        train_features=features;\n        train_features([intra_pairs(:);extra_pairs(:)],:)=[];\n\t[coeff,~,latent] = pca(double(train_features)');\n        m_feature=mean(double(train_features));\n        accuracies = zeros(10,1);\n\n%test the result with the range of PCA components\n%\tfor numDim=64:64:1024\n    for numDim=256:256\n    %\tfor numDim=79:104\n\n        test_features1=double(features([intra_pairs(:,1);extra_pairs(:,1)],:));\n        test_features2=double(features([intra_pairs(:,2);extra_pairs(:,2)],:));\n\n        test_features1=(test_features1-ones([size(test_features1,1) 1])*m_feature)*coeff(:,1:numDim);\n        test_features2=(test_features2-ones([size(test_features2,1) 1])*m_feature)*coeff(:,1:numDim);\n\n        test_features1= bsxfun(@rdivide, test_features1, sqrt(sum(test_features1.^2,2)));\n        test_features2= bsxfun(@rdivide, test_features2, sqrt(sum(test_features2.^2,2)));\n\n        scores=diag(test_features1*test_features2');\n\n        test_path1=image_path([intra_pairs(:,1);extra_pairs(:,1)]);\n        test_path2=image_path([intra_pairs(:,2);extra_pairs(:,2)]);\t\n        [tgtDir, '/',tgt_method, '_', num2str(numDim),  '/TR',num2str(i)]\n        mkdir([tgtDir, '/',tgt_method, '_', num2str(numDim)]);\n        mkdir([tgtDir, '/',tgt_method, '_', num2str(numDim),  '/TR',num2str(i)]);\n        \n        fid=fopen([tgtDir, '/' ,tgt_method, '_', num2str(numDim), '/TR',num2str(i),'/NCMNCM52evaC.dat'],'w');\n        for j=1:length(scores)\n            idx=0;\n            if ~isempty(strmatch(test_path1{j}(1:end-9),test_path2{j}(1:end-9)))\n                idx=1;\n            end\n            fprintf(fid,'%s\\t%s\\t1\\t%d\\t%f\\n',test_path1{j}(1:end-4),test_path2{j}(1:end-4),idx,-scores(j));\n        end\n        fclose(fid);\n        accuracy = Match_measure([tgtDir, '/' ,tgt_method, '_', num2str(numDim), '/TR',num2str(i),'/NCMNCM52evaC.dat'])\n        accuracies(i,1) = accuracy;\n    end\nend\nmean(accuracy)\n\n", "meta": {"author": "happynear", "repo": "FaceVerification", "sha": "c8c2b4d805abf7240d9d39d7b57151e04958f6bf", "save_path": "github-repos/MATLAB/happynear-FaceVerification", "path": "github-repos/MATLAB/happynear-FaceVerification/FaceVerification-c8c2b4d805abf7240d9d39d7b57151e04958f6bf/PCA_matching_tp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5712983319933346}}
{"text": "classdef LossSmoothL1 < dagnn.Loss\n%LossSmoothL1  Smooth L1 loss\n%  `LossSmoothL1.forward({x, x0, w})` computes the smooth L1 distance \n%  between `x` and `x0`, weighting the elements by `w`.\n%\n%  Here the smooth L1 loss between two vectors is defined as:\n%\n%     Loss = sum_i f(x_i - x0_i) w_i.\n%\n%  where f is the function (following the Faster R-CNN definition):\n%\n%              { 0.5 * sigma^2 * delta^2,         if |delta| < 1 / sigma^2,\n%   f(delta) = {\n%              { |delta| - 0.5 / sigma^2,         otherwise.\n%\n%  In practice, `x` and `x0` can pack multiple instances as 1 x 1 x C\n%  x N arrays (or simply C x N arrays).\n\n  properties\n    sigma = 1.\n  end\n\n  methods\n    function outputs = forward(obj, inputs, params)\n      sigma2 = obj.sigma^2 ;\n      delta = inputs{1} - inputs{2} ;\n      absDelta = abs(delta) ;\n\n      linearRegion = (absDelta > 1. / sigma2) ;\n      absDelta(linearRegion) = absDelta(linearRegion) - 0.5/sigma2 ;\n      absDelta(~linearRegion) = 0.5 * sigma2 * absDelta(~linearRegion).^2 ;\n\n      % Mutliply by instance weights and sum.\n      outputs{1} = inputs{3}(:)' * absDelta(:) ;\n\n      % Accumulate loss statistics.\n      n = obj.numAveraged ;\n      m = n + gather(sum(inputs{3}(:))) + 1e-9 ;\n      obj.average = (n * obj.average + gather(outputs{1})) / m ;\n      obj.numAveraged = m ;\n    end\n\n    function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)\n    % Function derivative:\n    %\n    %          { sigma^2 * x,             if |x| < 1 / sigma^2,\n    %  f'(x) = {\n    %          { sign(x),                 otherwise.\n\n      sigma2 = obj.sigma^2 ;\n      delta = inputs{1} - inputs{2} ;\n      absDelta = abs(delta) ;\n\n      linearRegion = (absDelta > 1. / sigma2) ;\n      delta(linearRegion) = sign(delta(linearRegion));\n      delta(~linearRegion) = sigma2 * delta(~linearRegion) ;\n\n      derInputs = {inputs{3} .* delta .* derOutputs{1}, [], []} ;\n      derParams = {} ;\n    end\n\n    function obj = LossSmoothL1(varargin)\n      obj.load(varargin) ;\n      obj.loss = 'smoothl1';\n    end\n  end\nend\n", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/libs/matconvnet/examples/fast_rcnn/+dagnn/LossSmoothL1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5712957062641199}}
{"text": "function [row_sum,col_sum]=calc_sum(Image,rowsize,z)\ncol_sum=sum(Image)'/z;\nfor i=1:rowsize,\nrow_sum(i)=sum(Image(i,:))/z;\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/41709-reconstruction-of-image-from-projections-by-algebraic-reconstruction-technique/ARTCode/calc_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033684, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5712956888768739}}
{"text": "%MDL_TWOLINK_MDH Create model of a 2-link mechanism using modified DH convention\n%\n% MDL_TWOLINK_MDH is a script that the workspace variable tl which\n% describes the kinematic and dynamic characteristics of a simple planar\n% 2-link mechanism using modified Denavit-Hartenberg conventions.\n%\n% Also defines the vector:\n%   qz   corresponds to the zero joint angle configuration.\n%\n% Notes::\n% - SI units of metres are used.\n% - It is a planar mechanism operating in the XY (horizontal) plane and is \n%   therefore not affected by gravity.\n%\n% References::\n%  - Based on Fig 3.8 (p71) of Craig (3rd edition).  \n%\n% See also SerialLink, mdl_onelink, mdl_twolink, mdl_planar2.\n\n% MODEL: generic, planar, 2DOF, modified_DH\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\n\na1 = 1;\na2 = 1;\n\n% for MDH parameters we need to implement the second link as a tool\n% transform\n\ntwolink = SerialLink([\n        RevoluteMDH('d', 0, 'a', 0,  'alpha', 0)\n        RevoluteMDH('d', 0, 'a', a1, 'alpha', 0)\n    ], ...\n    'tool', transl(a2, 0, 0), ...\n    'name', 'two link', ...\n    'comment', 'from Craig');\nqz = [0 0];\nqn = [pi/6, -pi/6];\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/mdl_twolink_mdh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.571208653305393}}
{"text": "function plot_mls1p(vPar, vMlsprob, nType)\n    % Plot maximum likelihod score (MLS) versus parameter variation\n    %  plot_mls1p(vPar, vMlsprob, nType)\n    % -----------------------------------------------\n    % Plot maximum likelihod score (MLS) versus parameter variation\n    % vPar is e.g. a shift, a stretch or a rate change\n    %\n    % Incoming variable\n    % vPar          : Vector of parameter used in search\n    % vMlsprob      : Maximum likelihood score for parameter\n    % nType    : Parameter identification\n    %            1 = dM (Simple shift)\n    %            2 = dS (Simple stretch)\n    %            3 = Rf (Rate factor)\n    %\n    % See also plot_mls2p, plot_mls3p\n    %\n    % Author: J. Woessner, woessner@seismo.ifg,.ethz.ch\n    % updated: 28.10.02\n    \n    switch nType\n        case 1\n            sTitle = 'Simple magnitude shift';\n            sX = 'dM';\n        case 2\n            sTitle = 'Simple stretch';\n            sX = 'dS';\n        case 3\n            sTitle = 'Rate factor';\n            sX = 'R_f';\n        otherwise\n            return;\n    end\n    if exist('mls2_fig','var') &  ishandle(mls2_fig)\n        set(0,'Currentfigure',mls2_fig);\n    else\n        mls2_fig=figure_w_normalized_uicontrolunits('tag','mls2','Name','Max. Likelikehood score','Units','normalized','Nextplot','add',...\n            'Numbertitle','off');\n        mls2_axs=axes('tag','ax_mls2','Nextplot','add','box','off');\n    end\n    \n    set(gcf,'tag','mls2');\n    set(gca,'tag','ax_mls2','Nextplot','replace','box','off','visible','off');\n    plot(vPar, log10(vMlsprob), 'r-^');\n    xlabel(sX);\n    ylabel('log10(Likelihood score)');\n    title(sTitle);\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/jochen/plot/plot_mls1p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5712086202563631}}
{"text": "function [T, score_mat] = learn_struct_mwst(data, discrete, node_sizes, node_type, scoring_fn, root)\n% LEARN_STRUCT_MWST Learn an oriented tree using the MSWT algorithm\n% T = learn_struct_mwst(data, discrete, node_sizes, node_type, scoring_fn, root)\n%\n% Input : \n%   data(i,m) is the node i in the case m,\n%   discrete = [ 1 if discret-node 0 if not ],\n%   node_sizes = 1 if gaussian node,\n%   node_type = {'tabular','gaussian',...},\n%   score = 'bic' (for complete data and any node types) or 'mutual_info' (tabular nodes),\n%   root is the futur root-node of the tree T.\n%\n% Output :\n%\tT = adjacency matrix of the tree\n%\n% V1.2 : 17 feb 2003 (O. Francois - francois.olivier.c.h@gmail.com, Ph. Leray - philippe.leray@univ-nantes.fr)\n%\n%\n% See Chow&Liu 1968 for the original algorithm using Mutual Information scoring.\n% Or Heckerman 1994.\n\nif nargin <4\n    error('Requires at least 4 arguments.')\nend\n\nif nargin == 4\n    scoring_fn='bic'; root=1;\nend;\n\nif nargin == 5\n    root=1;\nend;\n\n\nN=size(data,1);\nscore_mat=zeros(N,N);\n\nswitch scoring_fn\ncase 'bic',\n    for i=1:(N-1)\n            score2 = score_family(i, [], node_type{i}, scoring_fn, node_sizes, discrete, data,[]);\n        for j=(i+1):N\n            score1 = score_family(i, [j], node_type{i}, scoring_fn, node_sizes, discrete, data,[]);\n            score = score2-score1;\n            score_mat(i,j)=score;\n            score_mat(j,i)=score;\n        end\n    end\ncase 'mutual_info',\n    for i=1:(N-1)\n        for j=(i+1):N\n            score_mat(i,j)= -mutual_info_score(i,node_sizes(i),j,node_sizes(j),data);\n            score_mat(j,i)=score_mat(i,j);\n        end\n    end\notherwise,\n    error(['unrecognized scoring fn ' scoring_fn]);\nend\n\nG = minimum_spanning_tree(score_mat);\nT = mk_rooted_tree(G, root);\nT=full(T);", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/learning/learn_struct_mwst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5711653901647992}}
{"text": "% Digital circuit sizing for an inverter chain (GP)\n% Boyd, Kim, Patil, and Horowitz, \"Digital circuit optimization\n% via geometric programming\"\n% Written for CVX by Almir Mutapcic 02/08/06\n%\n% We consider a chain of N inverters driving a load capacitance CL.\n% The problem is to find optimal scale factors for the inverter\n% that minimize the sum of them (area), while obeying constraints\n% on the maximum delay through the circuit, and minimum and maximum\n% limits on scale factors. There are no limits on the total power.\n% (For more details about the inverter chain see sec. 2.1.11 in the paper.)\n%\n%   minimize   sum(x)\n%       s.t.   T_j <= Dmax          for j an output gate\n%              T_j + d_i <= T_i     for j in FI(i)\n%              x_min <= x <= x_max\n%\n% where variables are x and T.\n% Here we use data structures and digital circuit models from the\n% referenced paper.\n\n%********************************************************************\n% problem data\n%********************************************************************\nN  = 8;      % number of inverters\nCL = 20;     % capacitance load\nDmax = 20;   % maximum delay through the circuit\nx_min = 1;   % minimum scale factor\nx_max = 20;  % maximum scale factor\n\n% circuit labeling convention:\n% label primary input (input to the first inverter in the chain) with N+1\n% label primary output (output of the last inverter in the chain) with N+2\n% label inverters in the chain with 1,2,...,N based on their location\n\n% primary input and primary output labels (start with N+1)\nprimary_inputs  = [N+1];\nprimary_outputs = [N+2];\nM = N + length( primary_inputs ) + length( primary_outputs );\n\n% fan-in cell array for a straight chain of inverters\nFI{1} = [N+1];   % fan-in of the first inverter is the primary input\nfor k = 2:N\n  FI{k} = [k-1]; % fan-in of other inverters is the inverter feeding into them\nend\nFI{N+2} = [N];   % fan-in of the primary output is the last inverter in the chain\n\n% fan-out cell array\n% (will be computed from the fan-in cell array, no need to modify)\nFO = cell(M,1);\nfor gate = [1:N primary_outputs]\n  preds = FI{gate};\n  for k = 1:length(preds)\n    FO{preds(k)}(end+1) = gate;\n  end\nend\n\n% input and internal capacitance of gates and the driving resistance\nCin_norm  = ones(N,1);\nCint_norm = ones(N,1);\nRdrv_norm = ones(N,1);\n\n% place extra capacitance before the input of the 5th inverter\nCin_norm(5) = 80;\n\n% primary output has Cin capacitance (but has no Cload)\nCin_po = sparse(M,1);\nCin_po(primary_outputs) = CL;\n\n% primary input has Cload capacitance (but has no Cin)\nCload_pi = sparse(M,1);\nCload_pi(primary_inputs) = 1;\n\n%********************************************************************\n% optimization\n%********************************************************************\ncvx_begin gp\n  % optimization variables\n  variable x(N)                 % sizes\n  variable T(N)                 % arrival times\n\n  % minimize the sum of scale factors subject to above constraints\n  minimize( sum(x) )\n  subject to\n\n    % input capacitance is an affine function of sizes\n    Cin  = Cin_norm.*x;\n    Cint = Cint_norm.*x;\n\n    % driving resistance is inversily proportional to sizes\n    R = Rdrv_norm./x;\n\n    % gate delay is the product of its driving resistance and load cap.\n    Cload = cvx( zeros(N,1) );\n    for gate = 1:N\n      if ~ismember( FO{gate}, primary_outputs )\n        Cload(gate) = sum( Cin(FO{gate}) );\n      else\n        Cload(gate) = Cin_po( FO{gate} );\n      end\n    end\n\n    % delay\n    D = 0.69*ones(N,1).*R.*( Cint + Cload );\n\n    % create timing constraints\n    for gate = 1:N\n      if ~ismember( FI{gate}, primary_inputs )\n        for j = FI{gate}\n          % enforce T_j + D_j <= T_i over all gates j that drive i\n          D(gate) + T(j) <= T(gate);\n        end\n      else\n        % enforce D_i <= T_i for gates i connected to primary inputs\n        D(gate) <= T(gate);\n      end\n    end\n\n    % circuit delay is the max of arrival times for output gates\n    output_gates = [FI{primary_outputs}];\n    circuit_delay = max( T(output_gates) );\n\n    % collect all the constraints\n    circuit_delay <= Dmax;\n    x_min <= x <= x_max;\ncvx_end\n\n% message about extra capacitance and result display\ndisp(' ')\ndisp(['Note: there is an extra capacitance between the 4th and 5th inverter'...\n     ' in the chain.'])\nfprintf(1,'\\nOptimal scale factors are: \\n'), x\n\n% plot scale factors and maximum delay for inverter i\nclose all;\nsubplot(2,1,1); plot([1:N],T,'g--',[1:N],T,'bo');\nylabel('maximum delay T')\nsubplot(2,1,2); stem([1:N],x);\nylabel('scale factor x')\nxlabel('inverter stage')\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/inverter_chain_sizing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339907, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5711653876780938}}
{"text": "classdef VehicleSimpleLinear < VehicleDynamicsLateral.VehicleSimple\n    % VehicleSimpleLinear Linear simple vehicle model.\n    %\n    % It inherits properties from VehicleSimple.\n\n    methods\n        function self = VehicleSimpleLinear()\n            % Constructor for the vehicle\n            self.mF0 = 700;\n            self.mR0 = 600;\n            self.IT = 10000;\n            self.lT = 3.5;\n            self.nF = 2;\n            self.nR = 2;\n            self.wT = 2;\n            self.muy = .8;\n            self.deltaf = 0;\n            self.Fxf = 0;\n            self.Fxr = 0;\n        end\n\n        %% Model\n        % Function with the model\n        function dx = Model(self, t, states,tspan)\n            % Data\n            mT = self.mT;\n            IT = self.IT;\n            a = self.a;\n            b = self.b;\n            nF = self.nF;\n            nR = self.nR;\n            muy = self.muy;\n\n\n\n            g = 9.81;                 % Gravity [m/s^2]\n\n            FzF = self.mF0 * g;       % Vertical load @ F [N]\n            FzR = self.mR0 * g;       % Vertical load @ R [N]\n\n            v0 = 20;                  % [m/s]\n\n            % State variables\n            X = states(1,1);         % Not used\n            Y = states(2,1);         % Not used\n            PSI     = states(3,1);\n            VT       = states(4,1);\n            ALPHAT  = states(5,1);\n            dPSI    = states(6,1);\n\n            if isa(self.deltaf,'function_handle')\n                deltaf = self.deltaf([X;Y;PSI;VT;ALPHAT;dPSI],t);\n            elseif length(self.deltaf)>1\n                deltaf = interp1(tspan,self.deltaf,t);\n            else\n                deltaf = self.deltaf;\n            end\n\n            % Slip angles\n            ALPHAF = ALPHAT + a/v0*dPSI - deltaf;\n            ALPHAR = ALPHAT - b/v0*dPSI;\n\n            % Longitudinal forces\n            if isa(self.Fxf,'function_handle')\n                FxF = self.Fxf([X;Y;PSI;VT;ALPHAT;dPSI],t);\n            elseif length(self.Fxf)>1\n                FxF = interp1(tspan,self.Fxf,t);\n            else\n                FxF = self.Fxf;\n            end\n\n            if isa(self.Fxr,'function_handle')\n                FxR = self.Fxr([X;Y;PSI;VT;ALPHAT;dPSI],t);\n            elseif length(self.Fxr)>1\n                FxR = interp1(tspan,self.Fxr,t);\n            else\n                FxR = self.Fxr;\n            end\n\n            % Lateral force\n            FyF = nF * self.tire.Characteristic(ALPHAF, FzF / nF, muy);\n            FyR = nR * self.tire.Characteristic(ALPHAR, FzR / nR, muy);\n\n            % State equations\n            dx(1,1) = VT;\n            dx(2,1) = v0*(PSI + ALPHAT);\n            dx(3,1) = dPSI;\n            dx(4,1) = (FxF + FxR)/mT;\n            dx(5,1) = (FyF + FyR)/(mT*v0) - dPSI;\n            dx(6,1) = (a*FyF - b*FyR)/IT;\n\n        end\n    end\nend\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/+VehicleDynamicsLateral/@VehicleSimpleLinear/VehicleSimpleLinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5711653788921224}}
{"text": "function [t,x] = unrz(bits, bitrate)\n% UNRZ Encode bit string using unipolar NRZ code.\n%   [T, X] = UNRZ(BITS, BITRATE) encodes BITS array using unipolar NRZ\n%   code with given BITRATE. Outputs are time T and encoded signal\n%   values X.\n\n% Copyright (c) 2013 Yuriy Skalko <yuriy.skalko@gmail.com>\n\nT = length(bits)/bitrate; % full time of bit sequence\nn = 200;\nN = n*length(bits);\ndt = T/N;\nt = 0:dt:T;\nx = zeros(1,length(t)); % output signal\n\nfor i = 0:length(bits)-1\n  if bits(i+1) == 1\n    x(i*n+1:(i+1)*n) = 1;\n  else\n    x(i*n+1:(i+1)*n) = 0;\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/41320-line-coding-manchester-unipolar-and-polar-rz-unipolar-nrz/unrz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5711479127602606}}
{"text": "function test_optimization_test03 ( )\n\n%*****************************************************************************80\n%\n%% TEST_OPTIMIZATION_TEST03 tries Compass Search on each problem.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    15 January 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 2;\n  n = 1000;\n  delta_tol = 0.000001;\n  k_max = 20000;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST_OPTIMIZATION_TEST03\\n' );\n  fprintf ( 1, '  For each problem, using dimension M = 2\\n' );\n  fprintf ( 1, '  try compass search.\\n' );\n%\n%  Get the number of problems.\n%\n  problem_num = p00_problem_num ( );\n\n  for problem = 1 : problem_num\n\n    seed = 123456789;\n\n    [ a, b ] = p00_ab ( problem, m );\n    [ x0, seed ] = r8col_uniform ( m, 1, a, b, seed );\n    fx = p00_f ( problem, m, 1, x0 );\n    delta_init = 0.3 * norm ( x0 ) / m;\n    delta_init = max ( delta_init, 1000.0 * delta_tol );\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Problem %2d  DELTA_INIT = %14g\\n', problem, delta_init );\n    fprintf ( 1, '  Initial:  %14g  %14g  %14g\\n', x0, fx );\n    [ x, fx, k ] = p00_compass_search ( problem, m, x0, delta_tol, delta_init, ...\n      k_max );\n    fprintf ( 1, '  Final:    %14g  %14g  %14g  Steps = %d\\n', x, fx, k );\n\n    know = 0;\n    while ( 1 )\n      [ know, x ] = p00_sol ( problem, m, know );\n      if ( know == 0 )\n        break\n      end\n      fx = p00_f ( problem, m, 1, x );\n      fprintf ( 1, '  Exact:    %14g  %14g  %14g\\n', x, fx );\n    end\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/test_optimization/test_optimization_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.787931185683219, "lm_q1q2_score": 0.5711479055407876}}
{"text": "function ranks=cosmo_tiedrank(data, dim)\n% Compute ranks for the input along the specified dimension\n%\n% ranks=cosmo_tiedrank(data[, dim])\n%\n% Inputs:\n%   data                        numeric N-dimensional array\n%   dim                         optional dimension along which the ranks\n%                               are computed (default: 1)\n%\n% Output:\n%   ranks                       numeric N-dimensional array with the same\n%                               size as the input containing the rank of\n%                               each vector along the dim-th dimension.\n%                               Equal values have the same rank, which is\n%                               the average of the rank the values would\n%                               have if they differed by a minimal amount.\n%                               NaN values in the input result in a NaN\n%                               values in the output at the corresponding\n%                               locations.\n%                               If dim is greater than the number of\n%                               dimensions in data, then all values in rank\n%                               are one (or NaN of the corresponding value\n%                               in data is NaN).\n%\n% Examples:\n%     cosmo_tiedrank([1 2 2],2)\n%     %|| [ 1 2.5 2.5]\n%\n%     cosmo_tiedrank([NaN 2 2;3 NaN 4],1)\n%     %|| [ NaN     1     1;\n%     %||     1   NaN     2];\n%\n%     cosmo_tiedrank([NaN 2 2;3 NaN 4],2)\n%     %|| [ NaN   1.5   1.5;\n%     %||     1   NaN     2];\n%\n%     cosmo_tiedrank([2 4 3 3 3 3 5 5 5],2)\n%     %|| [ 1.0 6.0 3.5 3.5 3.5 3.5 8.0 8.0 8.0 ]\n%\n% Notes:\n% - Unlike the Matlab builtin function 'tiedrank' (part of the statistics\n%   toolbox), the meaning of the second argument is the dimension along\n%   which the ranks are computed.\n%\n% #   For CoSMoMVPA's copyright information and license terms,   #\n% #   see the COPYING file distributed with CoSMoMVPA.           #\n\n    if nargin<2\n        dim=1;\n    end\n\n    check_inputs(data, dim);\n    orig_size=size(data);\n\n    if numel(orig_size)<dim\n        % if the input data does not have enough data, then the output\n        % consists of an array with only ones (or NaNs, if present)\n        ranks=singleton_ranks(data);\n        return;\n    end\n\n    [values,idx]=sort(data,dim);\n\n    data_is_vector=numel(orig_size)<=2 && orig_size(3-dim)==1;\n    if data_is_vector\n        ranks=vector_tied_rank(values(:), idx(:));\n        if orig_size(1)==1\n            % transpose to turn it back into a row vector\n            ranks=ranks';\n        end\n        return\n    end\n\n\n    % make the dim-th dimension the first dimension\n    values_sh=shiftdim(values,dim-1);\n    idx_sh=shiftdim(idx,dim-1);\n    sh_size=size(values_sh);\n\n    count_along_dim=size(values_sh,1);\n\n    % reshape into a matrix\n    values_mat=reshape(values_sh,count_along_dim,[]);\n    idx_mat=reshape(idx_sh,count_along_dim,[]);\n\n    % space for output\n    ranks_mat=zeros(size(idx_mat));\n\n    % compute for each column vector\n    n_col=size(ranks_mat,2);\n    for k=1:n_col\n        ranks_mat(:,k)=vector_tied_rank(values_mat(:,k),idx_mat(:,k));\n    end\n\n    % put back in shape after shiftdim\n    ranks_sh=reshape(ranks_mat,sh_size);\n\n    % undo shiftdim\n    unshift_count=numel(orig_size)-dim+1;\n    ranks=reshape(shiftdim(ranks_sh,unshift_count),orig_size);\n\n\n\nfunction ranks=vector_tied_rank(sorted_values, sort_idx)\n% sorted_values and sort_idx are the output from 'sort'\n% it is assumes that sorted_values is a vector\n    n_values=numel(sorted_values);\n    nan_msk=isnan(sorted_values);\n    nan_count=sum(nan_msk);\n    non_nan_count=numel(sorted_values)-nan_count;\n\n    % first set ranks for values without ties\n    ranks=sort_idx+NaN;\n    ranks(sort_idx(1:non_nan_count))=1:non_nan_count;\n\n    % now deal with ties\n    tie_msk=sorted_values(2:end)==sorted_values(1:(end-1));\n    tie_idx=find(tie_msk);\n    tie_count=numel(tie_idx);\n\n    k=0;\n    while k<tie_count\n        k=k+1;\n\n        tie_start=tie_idx(k);\n        tie_end=tie_start+1;\n\n        while tie_end<n_values ...\n                && sorted_values(tie_end)==sorted_values(tie_end+1)\n            tie_end=tie_end+1;\n            k=k+1;\n        end\n\n        tie_value=(tie_start+tie_end)/2;\n        pos=tie_start+(0:(tie_end-tie_start));\n        ranks(sort_idx(pos))=tie_value;\n    end\n\n\nfunction ranks=singleton_ranks(data)\n    % all ranks are either NaN or 1\n    ranks=ones(size(data));\n    ranks(isnan(data))=NaN;\n\n\nfunction check_inputs(data, dim)\n    if ~isnumeric(data)\n        error('First input must be numeric')\n    end\n\n    if ~(isnumeric(dim) ...\n            && isscalar(dim) ...\n            && round(dim)==dim ...\n            && dim>0)\n        error('Second argument must be numeric integer');\n    end\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_tiedrank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5711478987108709}}
{"text": "\n% Test code for irntv.m\n%\n% Legal:\n%   irnTest.m is part of NUMIPAD (http://numipad.sf.net). \n%\n%   The NUMIPAD library is being developed under U.S. Government contract\n%   W-7405-ENG-36 for Los Alamos National Laboratory.\n%  \n% Authors\n%   Paul Rodriguez    prodrig@pucp.edu.pe\n%   Brendt Wohlberg   brendt@tmail.lanl.gov\n\n\n\n%  example = 'l1deconv';\n%  example = 'l2deconv';\n%  example = 'l1denoise';\nexample = 'l2denoise';\n\n%  Img = 'lena';\n%  Img = 'peppers';\n%  Img = 'goldhill';\nImg = 'lena';\n%  nmppath;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%       Input images        %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nswitch lower(Img)\n\n  case{'lena'}\n    Ig = double( imread('lena_gray_512.png') ) / 255;\n    Ic = double( imread('lena_color_512.png') ) / 255;\n\n  case{'peppers'}\n    Ig = double( imread('peppers_gray.png') ) / 255;\n    Ic = double( imread('peppers_color.png') ) / 255;\n\n  case{'goldhill'}\n    Ig = double( imread('goldhill_gray.png') ) / 255;\n    Ic = double( imread('goldhill_color.png') ) / 255;\n\n  case{'none'}\n    disp(' ');\n    disp('Select a test image (see code for an example)...');\n    disp(' ');\n    disp('Exiting irnTest code...');\n    return;\n\n  otherwise\n    error('Not a valid image\\n');\n\nend\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n%     Normalize        %\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nNormalize = @(x) (x - min(x(:)))/(max(x(:)) - min(x(:)));\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n%       kernels        %\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nkernel = fspecial('disk',3.2);\n\nK = @(x) imfilter(x, kernel, 'symmetric','conv');\nKT = @(x) K(x);\nKC = {K, KT};\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%       Blurred & noisy images        %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nswitch lower(example)\n\n  case{'l1deconv'}\n    IgBlur = K(Ig);\n    Ig_01L1 = imnoise(IgBlur, 'salt & pepper', 0.1);\n    Ig_03L1 = imnoise(IgBlur, 'salt & pepper', 0.3);\n\n    IcBlur = K(Ic);\n    Ic_01L1 = imnoise(IcBlur, 'salt & pepper', 0.1);\n    Ic_03L1 = imnoise(IcBlur, 'salt & pepper', 0.3);\n\n  case{'l1denoise'}\n\n    Ig_01L1 = imnoise(Ig, 'salt & pepper', 0.1);\n    Ig_03L1 = imnoise(Ig, 'salt & pepper', 0.3);\n\n    Ic_01L1 = imnoise(Ic, 'salt & pepper', 0.1);\n    Ic_03L1 = imnoise(Ic, 'salt & pepper', 0.3);\n\n  case{'l2deconv'}\n\n    IgBlur = K(Ig);\n                                             %NOTE sigma^2 in imnoise\n    Ig_01L2 = imnoise(IgBlur, 'gaussian', 0, 0.01*max(IgBlur(:)) ); \n    Ig_001L2 = imnoise(IgBlur,'gaussian', 0, 0.0001*max(IgBlur(:)) );\n\n    IcBlur = K(Ic);\n    Ic_01L2 = imnoise(IcBlur,'gaussian', 0, 0.01*max(IgBlur(:)) );\n    Ic_001L2 = imnoise(IcBlur,'gaussian', 0, 0.0001*max(IgBlur(:)) ); \n\n  case{'l2denoise'}\n    Ig_01L2 = imnoise(Ig,'gaussian', 0, 0.01*max(Ig(:)) );\n    Ic_01L2 = imnoise(Ic,'gaussian', 0, 0.01*max(Ig(:)) ); \n\n    Ig_005L2 = imnoise(Ig,'gaussian', 0, 0.0025*max(Ig(:)) ); \n    Ic_005L2 = imnoise(Ic,'gaussian', 0, 0.0025*max(Ig(:)) ); \n\nend\n\n\n\n%-----------------------------------------------------------------------------\n\n\nif( strcmp(example,'l1deconv') || strcmp(example,'all') )\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%       L1 Deconvolved        %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%noise level: 0.1\n\nlambda = 0.45;\n\npars = irntvInputPars('l1tv');\n\n%  pars.pcgtol_ini   = 1e-4;\npars.adapt_epsR   = 1;\npars.epsR_cutoff  = 0.01;\npars.adapt_epsF   = 1;\npars.epsF_cutoff  = 0.05;\npars.loops        = 4;\n\n%-----------------%\n% -- Grayscale -- %\n\npars.U0           = Ig_01L1;  % initial solution\n\n% >> Deconvolution via IRN <<\nIRN_Ig_01L1 = irntv(Ig_01L1, KC, lambda, pars);\n\nfigure; imagesc( Normalize(IRN_Ig_01L1) ); \ncolormap gray; axis image; axis off;\ntitle(sprintf('Deconvolved Image - Scalar IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ig, IRN_Ig_01L1), snr(Ig, Ig_01L1)));\n\n%-------------%\n% -- Color -- %\n\npars.U0           = Ic_01L1;  % initial solution\n\n% >> Deconvolution via IRN <<\nIRN_Ic_01L1 = irntv(Ic_01L1, KC, lambda, pars);\n\nfigure; imagesc( Normalize(IRN_Ic_01L1) ); axis image; axis off;\ntitle(sprintf('Deconvolved Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ic, IRN_Ic_01L1), snr(Ic, Ic_01L1)));\n\n\n%------------------\n%------------------\n\n%noise level: 0.3\n\nlambda = 0.95;\n\npars = irntvInputPars('l1tv');\n\n%  pars.pcgtol_ini   = 1e-4;\npars.adapt_epsR   = 1;\npars.epsR_cutoff  = 0.01;\npars.adapt_epsF   = 1;\npars.epsF_cutoff  = 0.05;\npars.loops        = 4;\n\n%-----------------%\n% -- Grayscale -- %\n\npars.U0           = Ig_03L1;  % initial solution\n\n% >> Deconvolution via IRN <<\nIRN_Ig_03L1 = irntv(Ig_03L1, KC, lambda, pars);\n\nfigure; imagesc( Normalize(IRN_Ig_03L1) ); \ncolormap gray; axis image; axis off;\ntitle(sprintf('Deconvolved Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n', ...\n               snr(Ig, IRN_Ig_03L1), snr(Ig, Ig_03L1)));\n\n\n%-------------%\n% -- Color -- %\n\npars.U0           = Ic_03L1;  % initial solution\n\n% >> Deconvolution via IRN <<\nIRN_Ic_03L1 = irntv(Ic_03L1, KC, lambda, pars);\n\nfigure; imagesc( Normalize(IRN_Ic_03L1) ); axis image; axis off;\ntitle(sprintf('Deconvolved Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB). \\n', ...\n               snr(Ic, IRN_Ic_03L1), snr(Ic, Ic_03L1)));\n\n\nend % _END_ if( strcmp(example,'l1deconv') || strcmp(example,'all') )\n\n%-----------------------------------------------------------------------------\n\n\nif( strcmp(example,'l2deconv') || strcmp(example,'all') )\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%       L2 Deconvolved        %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% sigma (noise level) : 0.01\n\nlambda  = 0.001;\n\npars = irntvInputPars('l2tv');\n\npars.pcgtol_ini   = 1e-4;\npars.adapt_epsR   = 1;\npars.epsR_cutoff  = 0.01;\npars.adapt_epsF   = 1;\npars.epsF_cutoff  = 0.05;\npars.loops        = 3;\n\n%-----------------%\n% -- Grayscale -- %\n\npars.U0           = Ig_001L2;  % initial solution\n\n% >> Deconvolution via IRN <<\nIRN_Ig_001L2 = irntv(Ig_001L2, KC, lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ig_001L2) ); \ncolormap gray; axis image; axis off;\ntitle(sprintf('Deconvolved Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ig, IRN_Ig_001L2), snr(Ig, Ig_001L2)));\n\n\n%-------------%\n% -- Color -- %\n\npars.U0           = Ic_001L2;  % initial solution\n\n% >> Deconvolution via IRN <<\nIRN_Ic_001L2 = irntv(Ic_001L2, KC, lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ic_001L2) ); axis image; axis off;\ntitle(sprintf('Deconvolved Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ic, IRN_Ic_001L2), snr(Ic, Ic_001L2)));\n\n\n% sigma (noise level) : 0.1\n\nlambda  = 0.05;\n\npars = irntvInputPars('l2tv');\n\npars.pcgtol_ini   = 1e-4;\npars.adapt_epsR   = 1;\npars.epsR_cutoff  = 0.05;\npars.adapt_epsF   = 1;\npars.epsF_cutoff  = 0.01;\npars.loops        = 3;\n\n\n%-----------------%\n% -- Grayscale -- %\n\npars.U0           = Ig_01L2;  % initial solution\n\n% >> Deconvolution via IRN <<\nIRN_Ig_01L2 = irntv(Ig_01L2, KC, lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ig_01L2) ); \ncolormap gray; axis image; axis off;\ntitle(sprintf('Deconvolved Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ig, IRN_Ig_01L2), snr(Ig, Ig_01L2)));\n\n\n%-------------%\n% -- Color -- %\n\npars.U0           = Ic_01L2;  % initial solution\n\n% >> Deconvolution via IRN <<\nIRN_Ic_01L2 = irntv(Ic_01L2, KC, lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ic_01L2) ); \ncolormap gray; axis image; axis off;\ntitle(sprintf('Deconvolved Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ic, IRN_Ic_01L2), snr(Ic, Ic_01L2)));\n\n\nend % _END_ if( strcmp(example,'l2deconv') || strcmp(example,'all') )\n\n%-----------------------------------------------------------------------------\n\n\n\n\nif( strcmp(example,'l1denoise') || strcmp(example,'all') )\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%       L1 Denoise        %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%noise level: 10%\n\n%-- IRN\nlambda  = 1.1;\n\npars = irntvInputPars('l1tv');\n\npars.pcgtol_ini = 1e-4;\npars.epsf       = 1e-2;    \npars.epsr       = 1e-4;\npars.loops      = 2;\n\n%-----------------%\n% -- Grayscale -- %\n\n% >> Denoising via IRN <<\nIRN_Ig_01L1 = irntv(Ig_01L1, [], lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ig_01L1) ); \ncolormap gray; axis image; axis off;\ntitle(sprintf('Denoised Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ig, IRN_Ig_01L1), snr(Ig, Ig_01L1)));\n\n\n%-------------%\n% -- Color -- %\n\n% >> Denoising via IRN <<\nIRN_Ic_01L1 = irntv(Ic_01L1, [], lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ic_01L1) ); \ncolormap gray; axis image; axis off;\ntitle(sprintf('Denoised Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ic, IRN_Ic_01L1), snr(Ic, Ic_01L1)));\n\n\n%-----------------\n%-----------------\n\n%noise level: 30%\n\nlambda  = 1.2;\n\npars = irntvInputPars('l1tv');\n\npars.pcgtol_ini   = 1e-4;\npars.adapt_epsR   = 1;\npars.epsR_cutoff  = 0.01;\npars.adapt_epsF   = 1;\npars.epsF_cutoff  = 0.05;\npars.loops        = 3;\n\n\n%-----------------%\n% -- Grayscale -- %\n\n% >> Denoising via IRN <<\nIRN_Ig_03L1 = irntv(Ig_03L1, [], lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ig_03L1) ); \ncolormap gray; axis image; axis off;\ntitle(sprintf('Denoised Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ig, IRN_Ig_03L1), snr(Ig, Ig_03L1)));\n\n\n%-------------%\n% -- Color -- %\n\n% >> Denoising via IRN <<\nIRN_Ic_03L1 = irntv(Ic_03L1, [], lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ic_03L1) ); axis image; axis off;\ntitle(sprintf('Denoised Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ic, IRN_Ic_03L1), snr(Ic, Ic_03L1)));\n\n\nend % _END_ if( strcmp(example,'l1denoise') || strcmp(example,'all') )\n\n\n%-----------------------------------------------------------------------------\n\n\nif( strcmp(example,'l2denoise') || strcmp(example,'all') )\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%       L2 Denoise        %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% sigma (noise level) : 0.05\n\nlambda  = 0.05;\n\npars = irntvInputPars('l2tv');\n\npars.pcgtol_ini = 1e-4;\npars.epsf       = 1e-2;    \npars.epsr       = 1e-5;    \npars.loops      = 2;\n\n%-----------------%\n% -- Grayscale -- %\n\n% >> Denoising via IRN <<\nIRN_Ig_005L2 = irntv(Ig_005L2, [], lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ig_005L2) ); \ncolormap gray; axis image; axis off;\ntitle(sprintf('Denoised Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ig, IRN_Ig_005L2), snr(Ig, Ig_005L2)));\n\n%-------------%\n% -- Color -- %\n\n% >> Denoising via IRN <<\nIRN_Ic_005L2 = irntv(Ic_005L2, [], lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ic_005L2) ); axis image; axis off;\ntitle(sprintf('Denoised Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ic, IRN_Ic_005L2), snr(Ic, Ic_005L2)));\n\n%-----------------\n%-----------------\n\n\n% sigma (noise level) : 0.1\n\nlambda  = 0.1;\n\npars = irntvInputPars('l2tv');\n\npars.pcgtol_ini = 1e-4;\npars.epsf       = 1e-2;    \npars.epsr       = 1e-5;    \npars.loops      = 2;\n\n%-----------------%\n% -- Grayscale -- %\n\n% >> Denoising via IRN <<\nIRN_Ig_01L2 = irntv(Ig_01L2, [], lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ig_01L2) ); \ncolormap gray; axis image; axis off;\ntitle(sprintf('Denoised Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ig, IRN_Ig_01L2), snr(Ig, Ig_01L2)));\n\n%-------------%\n% -- Color -- %\n\n% >> Denoising via IRN <<\nIRN_Ic_01L2 = irntv(Ic_01L2, [], lambda, pars);\n\n\nfigure; imagesc( Normalize(IRN_Ic_01L2) ); axis image; axis off;\ntitle(sprintf('Denoised Image - Vector IRN. \\nSNR: %4.1fdB (noisy SNR: %4.1fdB).\\n ', ...\n               snr(Ic, IRN_Ic_01L2), snr(Ic, Ic_01L2)));\n\n\nend % _END_ if( strcmp(example,'l2denoise') || strcmp(example,'all') )\n\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/GTF/source/irnTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5711478987108708}}
{"text": "function hess = cstepHess(fun,x,isTril,h)\n%CSTEPHESS  Complex Step Hessian of a Scalar Function\n%\n%  cstepHess uses a complex step approach to finite difference to ensure\n%  robust estimate of the Hessian. Note your function MUST be\n%  written in Matlab code only and must not contain any if/else statements.\n%\n%  If it does not work - ensure you are using .' (transpose) and not ' (complex conjugate).\n%\n%   hess = cstepHess(fun,x) calculates the Hessian of fun at the point x.\n%\n%   hess = cstepHess(fun,x,isTril) specifies if the returned Hessian\n%   should be Symmetric Lower Triangular.\n%\n%   hess = cstepHess(fun,x,isTril,h) specifies the step-size. This defaults to\n%   1e-3.\n\n%   Copyright (C) 2013 Jonathan Currie (IPL)\n%\n%   This code follows ideas from \"New Complex-Step Derivative Approximations\n%   with Application to Second-Order Kalman Filtering\", by Kok-Lam Lai, John\n%   L. Crassidis and Yang Cheng.\n\nif(nargin < 4), h = 1e-3; end\nif(nargin < 3 || isempty(isTril)), isTril = false; end\n\n%Constants from paper\nI = sqrt(2)/2*(1i + 1);\nn = length(x); hess = zeros(n,n);\n%Diagonal Elements\nfor k = 1:n\n    xu = x; xu(k) = xu(k) + I*h;\n    xl = x; xl(k) = xl(k) - I*h;\n    hess(k,k) = imag((fun(xu) + fun(xl))/h^2); \nend\n%Lower Triangular Elements\nlam = 1; k = n-1;\nwhile(k > 0)\n    for phi = 1:k\n        xu = x; xu(phi:phi+lam) = xu(phi:phi+lam) + I*h;\n        xl = x; xl(phi:phi+lam) = xl(phi:phi+lam) - I*h;\n        Fsum = sum(sum(hess(phi:phi+lam,phi:phi+lam)));\n        hess(phi+lam,phi) = (imag((fun(xu) + fun(xl))/h^2) - Fsum)/2;\n        hess(phi,phi+lam) = hess(phi+lam,phi); %copy to upper tri        \n    end\n    k = k - 1;\n    lam = lam + 1;\nend\n%Make tril if requested\nif(isTril), hess = tril(hess); end", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/math/opti/Utilities/opti/cstepHess.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5710637285177654}}
{"text": "function s=compressShape(w, forceCompression)\n%compressShape Compress a gradient or pulse shape.\n%   s=compressShape(w) Compress the waveform using a run-length compression\n%   scheme on the derivative. This strategy encodes constant and linear\n%   waveforms with very few samples. A structure is returned with the\n%   fields: \n%     num_samples - the number of samples in the uncompressed waveform\n%     data - containing the compressed waveform\n%\n%   See also decompressShape\n\nif nargin<2\n    forceCompression=false;\nend\n\nif any(~isfinite(w))\n    error('compressShape() received infinite samples');\nend\n\nif ~forceCompression && length(w) <= 4 % avoid compressing very short shapes\n    s.num_samples=length(w);\n    s.data = w(:)';\n    return;\nend\n\n\n% %MZ: old code with implicit quantization\n% data = [w(1); diff(w(:))];\n% maskChanges = [true; abs(diff(data))>1e-8];   % TRUE if values change\n% vals = data(maskChanges);                     % Elements without repetitions\n\n% MZ: explicit quantization with error correction\nquant_fac=1e-7; % single precision floating point has ~7.25 decimal places \nws=w./quant_fac;\ndatq=round([ws(1); diff(ws(:))]);\nqerr=ws(:)-cumsum(datq);\nqcor=[0; diff(round(qerr))];\ndatd=datq+qcor;\nmaskChanges=[true; diff(datd)~=0];\nvals=datd(maskChanges).*quant_fac;            % Elements without repetitions\n\nk = find([maskChanges', true]);               % Indices of changes\nn = diff(k)';                                 % Number of repetitions\n\n% Encode in Pulseq format\nnExtra=n-2;\nvals2=vals; \nvals2(nExtra<0)=nan;\nnExtra(nExtra<0)=nan;\nv=[vals vals2 nExtra]';\nv=v(isfinite(v));\nv(abs(v)<1e-10)=0;\ns.num_samples = length(w);\n% decide whether compression makes sense, otherwise store the original\nif forceCompression || s.num_samples > length(v)\n    s.data = v';\nelse\n    s.data = w(:)';\nend\n\n\n", "meta": {"author": "pulseq", "repo": "pulseq", "sha": "b4c8fee2a1ffa491d53bd6f507cba2029bf32835", "save_path": "github-repos/MATLAB/pulseq-pulseq", "path": "github-repos/MATLAB/pulseq-pulseq/pulseq-b4c8fee2a1ffa491d53bd6f507cba2029bf32835/matlab/+mr/compressShape.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5710637221481336}}
{"text": "function scr_lin = linear_calibrate_scores(scr,key,obj_func,niters,prior,addzeros)\n% A function for doing 'cheating' calibration on scores.  It trains\n% a linear calibration (scaling and offset) on the scores and then\n% applies the calibration to the same scores.  \n% Inputs:\n%   scr: The object (of class Scores) containing the scores to be\n%     calibrated. \n%   key: The Key indicating target and non-target trials.\n%   obj_func: The objective function for the calibration training.  The\n%     default is cllr objective.\n%   niters: The maximum number of iterations in the calibration\n%     training.\n%   prior: The effective target prior.  \n%   addzeros: If true, missing scores (required by key but not\n%     present in scr) are added (with value zero).\n% Outputs:\n%   scr_lin: The calibrated version of the input scores.\n\nassert(nargin==6)\nassert(isa(scr,'Scores'))\nassert(isa(key,'Key'))\nassert(scr.validate())\nassert(key.validate())\n\n[tar,non] = scr.get_tar_non(key);\nlogprint(Logger.Info,'training calibration\\n')\n[flin,nxe,w_lin] = train_linear_calibration(tar,non,prior,obj_func,niters,true);\n\nlogprint(Logger.Info,'calibrating scores\\n')\nscr_lin = scr.align_with_ndx(key);\nscr_lin = scr_lin.transform(flin);\n\nlogprint(Logger.Info,'displaying calibration results\\n')\nlogprint(Logger.Info,'weights: scaling %f, offset %f\\n',w_lin(1),w_lin(2))\nres = Results(scr_lin,key);\nlogprint(Logger.Info,'norm_act_dcf = %g, norm_min_dcf = %g, prbep = %g, nxe = %g\\n',res.get_norm_act_dcf(prior),res.get_norm_min_dcf(prior),res.get_prbep(),nxe); \n\nif addzeros\n    scr_lin = scr_lin.set_missing_to_value(key,0.0);\nend\n\nassert(scr_lin.validate())\n\nend\n", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/tDCF_v1/bosaris_toolkit.1.06/bosaris_toolkit/calibration/linear_calibrate_scores.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5710569496794554}}
{"text": "function [X_den,P]=denoise_TV_One(Xobs,lambda,l,u,P_init,pars)\n%This function implements the FISTA method for TV denoising problems. \n%\n% INPUT\n% Xobs ..............................an observed noisy image.\n% lambda ........................ parameter\n% pars.................................parameters structure\n% pars.MAXITER ..................... maximum number of iterations\n%                                                      (Default=100)\n% pars.epsilon ..................... tolerance for relative error used in\n%                                                       the stopping criteria (Default=1e-4)\n% pars.print ..........................  1 if a report on the iterations is\n%                                                       given, 0 if the  report is silenced\n% pars.tv .................................. type of total variation\n%                                                      penatly.  'iso' for isotropic (default)\n%                                                      and 'l1' for nonisotropic\n%  \n% OUTPUT\n% X_den ........................... The solution of the problem \n%                                            min{||X-Xobs||^2+2*lambda*TV(X)}\n\n%%% Written by Chen Chen and Junzhou Huang at UT Arlington\n%%% April. 13, 2012\n\n%%% Related paper: Chen Chen and Junzhou Huang, \"Compressive Sensing MRI\n%%% with Wavelet Tree Sparsity\"\n\n%Define the Projection onto the box\nif((l==-Inf)&&(u==Inf))\n    project=@(x)x;\nelseif (isfinite(l)&&(u==Inf))\n    project=@(x)(((l<x).*x)+(l*(x<=l)));\nelseif (isfinite(u)&&(l==-Inf))\n     project=@(x)(((x<u).*x)+((x>=u)*u));\nelseif ((isfinite(u)&&isfinite(l))&&(l<u))\n    project=@(x)(((l<x)&(x<u)).*x)+((x>=u)*u)+(l*(x<=l));\nelse\n    error('lower and upper bound l,u should satisfy l<u');\nend\n\n% Assigning parameres according to pars and/or default values\nflag=exist('pars', 'var');\nif (flag&&isfield(pars,'MAXITER'))\n    MAXITER=pars.MAXITER;\nelse\n    MAXITER=100;\nend\n% if (flag&&isfield(pars,'epsilon'))\n%     epsilon=pars.epsilon;\n% else\n%     epsilon=1e-4;\n% end\n% if(flag&&isfield(pars,'print'))\n%     prnt=pars.print;\n% else\n%     prnt=1;\n% end\nif(flag&&isfield(pars,'tv'))\n    tv=pars.tv;\nelse\n    tv='iso';\nend\n\n[m,n]=size(Xobs);\n% clear P; clear R;\nif(isempty(P_init))\n    P{1}=zeros(m-1,n);    P{2}=zeros(m,n-1);\n    R{1}=zeros(m-1,n);    R{2}=zeros(m,n-1);\nelse\n    P{1}=P_init{1};    P{2}=P_init{2};\n    R{1}=P_init{1};    R{2}=P_init{2};\nend\ntk=1;tkp1=1;count=0;i=0;\n\nD=zeros(m,n);%fval=inf;fun_all=[];\nwhile((i<MAXITER)&&(count<5))\n%    fold=fval;  \n    i=i+1;    \n%     Dold=D;    \n    Pold=P;    \n    tk=tkp1;\n    D=project(Xobs-lambda*Lforward(R, m, n));\n    Q=Ltrans(D, m, n);\n    %%%%%%%%%%\n    % Taking a step towards minus of the gradient\n    P{1}=R{1}+1/(8*lambda)*Q{1};\n    P{2}=R{2}+1/(8*lambda)*Q{2};\n    \n    %%%%%%%%%%\n    % Peforming the projection step\n    switch tv\n        case 'iso'\n            A=[P{1}.^2;zeros(1,n)]+[P{2}.^2,zeros(m,1)];\n            A=sqrt(max(A,1));\n            P{1}=P{1}./A(1:m-1,:); P{2}=P{2}./A(:,1:n-1);\n        case 'l1'\n            P{1}=P{1}./(max(abs(P{1}),1));\n            P{2}=P{2}./(max(abs(P{2}),1));\n        otherwise\n            error('unknown type of total variation. should be iso or l1');\n    end\n\n    %%%%%%%%%%\n    %Updating R and t\n    tkp1=(1+sqrt(1+4*tk^2))/2;\n    \n    R{1}=P{1}+(tk-1)/(tkp1)*(P{1}-Pold{1});\n    R{2}=P{2}+(tk-1)/tkp1*(P{2}-Pold{2});\n    \n%     re=norm(D-Dold,'fro')/norm(D,'fro');\n%     if (re<epsilon)\n%         count=count+1;\n%     else\n%         count=0;\n%     end\n    C=Xobs-lambda*Lforward(P, m, n);\n    PC=project(C);\n%     fval=-norm(C-PC,'fro')^2+norm(C,'fro')^2;\n%     fun_all=[fun_all;fval];\nend\nX_den=D;iter=i;\n\n\nfunction X=Lforward(P, m, n)\n\n%       [m2,n2]=size(P{1});\n%       [m1,n1]=size(P{2});\n% \n%       if (n2~=n1+1)\n%           error('dimensions are not consistent')\n%       end\n%       if(m1~=m2+1)\n%           error('dimensions are not consistent')\n%       end\n% \n%       m=m2+1;\n%       n=n2;\n\n      X=zeros(m,n);\n      X(1:m-1,:)=P{1};\n      X(:,1:n-1)=X(:,1:n-1)+P{2};\n      X(2:m,:)=X(2:m,:)-P{1};\n      X(:,2:n)=X(:,2:n)-P{2};\n   end\n \n   function P=Ltrans(X, m, n)\n%       [m,n]=size(X);\n      P{1}=X(1:m-1,:)-X(2:m,:);\n      P{2}=X(:,1:n-1)-X(:,2:n);\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_Proximal/denoise_TV_One.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5710569444485837}}
{"text": "function [gKern, gVarmeans, gVarcovars, gInd] = linard2VardistPsi2Gradient(linard2Kern, vardist, Z, covGrad, learnInducing)\n\n% LINARD2VARDISTPSI2GRADIENT description.\n\n% VARGPLVM\n\nif nargin < 5\n    learnInducing = 1;\nend\n\n% inverse variances\nA = linard2Kern.inputScales;\n\nPsi1 = linard2VardistPsi1Compute(linard2Kern, vardist, Z);\n\nAmat = sparse(diag(A));\nK1 = (vardist.means'*vardist.means + diag(sum(vardist.covars,1)));\nK = Amat*K1*Amat;\n\n% TYPICAL WAY\n%sumS = sum(vardist.covars,1);\n%for q=1:vardist.latentDimension\n%   sc = sum(vardist.means(:,q)*ones(1,size(Z,1)).*Psi1,1); \n%   \n%   ZZ = Z(:,q)*Z(:,q)';\n%      \n%   gKern(q)  = sum(sum( (Z(:,q)*sc + (sumS(q)*A(q))*ZZ).*covGrad )); \n%   \n%   gVarmeans(:,q) =  A(q)*sum(Psi1*((ones(size(Z,1),1)*Z(:,q)').*covGrad),2);\n%   \n%   gVarcovars(q) = sum(sum((ZZ.*covGrad)));   \n%end\n%gKern = 2*gKern(:)';\n%gVarmeans = 2*gVarmeans(:)'; \n%gVarcovars = (A.^2).*gVarcovars;\n%gVarcovars = ones(size(Psi1,1),1)*gVarcovars;\n%gVarcovars = gVarcovars(:)';\n%gInd = covGrad*Z*K;\n%gInd = 2*gInd(:)';\n%%% end of typical way \n\n% FAST WAY\nAZ = Z*Amat;\nAZK = AZ*K1;\ngKern = sum((covGrad*Z).*AZK,1);\ngVarmeans = (Psi1*(covGrad*Z))*Amat;\nAZ = AZ*Amat;\ngVarcovars = ones(size(Psi1,1),1)*sum((covGrad*Z).*AZ,1);\nif learnInducing\n    gInd = covGrad*Z*K;\nelse\n    [M Q] = size(Z); \n    gInd = zeros(M, Q);\nend\n%\ngKern = 2*gKern(:)';\ngVarmeans = 2*gVarmeans(:)'; \ngVarcovars = gVarcovars(:)';\ngInd = 2*gInd(:)';\n%%%  end of FAST WAY\n\n%sum(sum(abs(gKern1-gKern)))\n%sum(sum(abs(gVarmeans1 - gVarmeans)))\n%sum(sum(abs(gVarcovars1 - gVarcovars)))\n%sum(sum(abs(gInd1 - gInd)))\n%pause\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/linard2VardistPsi2Gradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5710569444485836}}
{"text": "function [V]=quad_smooth(V,Ev,IND_V_not_Ev,Lc,n,Ls,w1)\n\nL1=Ev>0;\nL2=IND_V_not_Ev>0;\nw2=1-w1;\n\np=V;\n\nfor i=1:n\n    Xp=NaN(size(Ev));  Yp=NaN(size(Ev));  Zp=NaN(size(Ev));\n    Xp(L1)=p(Ev(L1),1); Yp(L1)=p(Ev(L1),2); Zp(L1)=p(Ev(L1),3);\n    Vp1=[gnanmean(Xp,2) gnanmean(Yp,2) gnanmean(Zp,2)];\n    \n    Xp=NaN(size(Ev));  Yp=NaN(size(Ev));  Zp=NaN(size(Ev));\n    Xp(L2)=p(IND_V_not_Ev(L2),1); Yp(L2)=p(IND_V_not_Ev(L2),2); Zp(L2)=p(IND_V_not_Ev(L2),3);\n    Vp2=[gnanmean(Xp,2) gnanmean(Yp,2) gnanmean(Zp,2)];\n    \n    Vp=(w1.*Vp1+w2.*Vp2)./(w1+w2);\n    p=p+Ls.*(Vp-p);\n    \n    p(Lc,:)=V(Lc,:);    \n    if i>1\n        D=gnansum((p-p_old).^2,2);\n        SSQD_new=gnansum(D(:));\n        if i>2\n            SSQD_ratio=SSQD_new./SSQD_old;\n            disp(num2str(SSQD_ratio));\n        end\n        SSQD_old=SSQD_new;\n    end    \n    p_old=p;\n    \nend\nV=p;\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/quad_smooth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5710569444485836}}
{"text": "function [mu, s2, MU, SIG2] = simulGPmc(hyp, inf, meanfunc, cov, lik, input, target, test, lag, Nsamples)\n% simulGPmc - Simulation of the dynamic GP model, where the output variance is\n% propagated using the Monte Carlo method\n%\n%% Syntax\n%  [mu, s2, MU, SIG2] = simulGPmc(hyp, inf, mean, cov, lik, input, target, test,\n%  lag, Nsamples)\n% \n%% Description\n% Idea: at every time step the output of GP model is approximated with\n% Nsamples samples, which are used as the future inputs of the GP model.\n% Samples are re-used if necessary (ie. y(k-1) for y(k-2) if lag=2 etc.) \n% Uses routines gpx and gmx_sample. \n% \n% Input:\n% * hyp      ... the structure of optimized hyperparameters \n% * inf      ... the function specifying the inference method \n% * meanfunc ... the prior mean function\n% * cov      ... the specified covariance function, see help covFun for more info \n% * lik      ... the likelihood function\n% * input    ... the input part of the training data,  NxD matrix\n% * target   ... the output part of the training data (ie. target), Nx1 vector \n% * test     ... the input matrix for simulation, kxD vector, see\n%                construct.m for more info  \n% * lag      ... the order of the model (number of used lagged outputs) \n% * Nsamples ... the number of samples used in algorithm (ie. runs of simulation) \n% \n% Output:\n% * mu    ... the mean predicted output \n% * s2    ... the associated variances (with noise variances)\n% * MU    ... the matrix of all predicted means, kxNsamples\n% * SIG2  ... the associated predicted variances \n% \n% See also: \n% gpx, gmx_sample, simulGPnaive\n% \n% Examples: \n% demo_example_gp_simulation\n% \n%% \n% * Written by J. Prikryl, November 2010\n% * Based on the work of C.E. Rasmussen, A. Girard, K. Azman. \n%\n\n% meanfunc ... 'mean' is used as a matlab core function in this file\n\n\nNdx = 800;\nDSig = 3;\nnum_iters = length(test);\nsum_time  = 0;\n\n[N, D] = size(input);\nPDF = zeros(Nsamples,lag);\n\n% Preallocate mu and s2\nmu = zeros ( num_iters, 1 );\ns2 = zeros ( num_iters, 1 );\n\n% 1st step - input is a point\ntest_ = test(1,:);\n[mu(1), s2(1), post] = gpx(hyp, inf, meanfunc, cov, lik, input, target, test_);\n\nMU(1,:) = mu(1)*ones(1,Nsamples);\nSIG2(1,:) = s2(1)*ones(1,Nsamples);\n\npdf = gmx_sample(mu(1),s2(1),Nsamples);\nPDF(:,lag) = pdf;\n% instead of a cycle, create one monstrous test_ matrix\ntest_ = repmat( test(2,:), Nsamples, 1 );\ntest_(:,lag) = pdf;\n[MU(2,:), SIG2(2,:), post] = gpx(hyp, inf, meanfunc, cov, lik, input, target, test_, post);\nmu(2,1) = mean(MU(2,:));\ns2(2,1) = mean(SIG2(2,:)) + mean((MU(2,:)-mu(2)).^2);\n\n% steps from 3 on ...\nfor k=3:num_iters\n\n    if(mod(k,50)==0 || k==3)\n        disp(['simulGPmc, step: ',int2str(k),'/',int2str(length(test))]);    \n    end\n\n    \n    if(k>lag)\n        % samples of previous distributions \n        for jj=1:lag-1\n            PDF(:,jj) = PDF(:,jj+1);\n        end\n\n    else  % k <= lag\n        % part after 'else' not yet tested for lag>=3 \n        col0 = lag-(k-1);\n        PDF(:,1:col0) = repmat(test(k,1:col0),Nsamples,1);\n        for jj=col0+1:lag-1\n            PDF(:,jj) = PDF(:,jj+1);\n        end\n    end\n\n    pdf = gmx_sample(MU(k-1,:),SIG2(k-1,:),Nsamples);\n    PDF(:,lag) = pdf;\n\n    % simulate for all cases, again using the matrix version\n    t0 = tic;\n    test_ = repmat ( test(k,:), Nsamples, 1 );\n    test_(:,1:lag) = PDF;\n    [MU(k,:), SIG2(k,:), post] = gpx(hyp, inf, meanfunc, cov, lik, input, target, test_, post);\n    calltime = toc(t0);\n%     fprintf ( 'gpr_simul() ....... %f sec\\n\\n', calltime ); % uncomment\n%     if you wish \n    sum_time = sum_time + calltime;\n    \n    % approximate output distribution with gauss - calculate m and v\n    mu(k,1) = mean(MU(k,:));\n    s2(k,1) = mean(SIG2(k,:)) + mean((MU(k,:)-mu(k)).^2);\n\nend\n\n%     fprintf ( 'average time needed for gpr_simul() .... %f sec\\n', sum_time/(num_iters-2) );\n%     uncomment if you wish\nreturn;\n\n\n\n\n\n", "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-gp-evaluation/simulGPmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5710569429605215}}
{"text": "function [kPa] = dynpcm22kPa(dynpcm2)\n% Convert pressure from dynes per square centimeter to kilopascals\n% Chad Greene 2012\nkPa = dynpcm2*0.000100000;", "meta": {"author": "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/dynpcm22kPa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5710569377296497}}
{"text": "function out = DN_Unique(x)\n% DN_Unique     The proportion of the time series that are unique values\n%\n%---INPUTS:\n%\n% x, the input data vector\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,\n% <http://www.benfulcher.com>\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 <http://www.gnu.org/licenses/>.\n% ------------------------------------------------------------------------------\n\nout = length(unique(x))/length(x);\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_Unique.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5710419904671251}}
{"text": " function [data M m] =scale_func(data,M,m)\n%\n% function data =rescale(data)\n%\n% This function rescale the input data between -1 and 1\n%\n% INPUT\n%\n% data: the data to rescale\n% max: the maximum value of the ouput data\n% min: the minimum value of the output data\n% \n% OUTPUT\n%\n% data: the rescaled data\n[Nb_s Nb_b]=size(data);\nif nargin==1\n    M=max(data,[],1);\n    m=min(data,[],1);\nend\n\ndata = 2*(data-repmat(m,Nb_s,1))./(repmat(M-m,Nb_s,1))-1;", "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/scale_func.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5710419807810817}}
{"text": "function gamma_inc_values_test ( )\n\n%*****************************************************************************80\n%\n%% GAMMA_INC_VALUES_TEST demonstrates the use of GAMMA_INC_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, 'GAMMA_INC_VALUES_TEST:\\n' );\n  fprintf ( 1, '  GAMMA_INC_VALUES stores values of\\n' );\n  fprintf ( 1, '  the incomplete Gamma function.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '      A            X            GAMMA_INC(A)(X)\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, a, x, fx ] = gamma_inc_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fprintf ( 1, '  %12f  %12f  %24.16f\\n', a, 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/gamma_inc_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.5710419704774813}}
{"text": "function [vert, fac] = voxel_image( pts, vox_sz, color, alpha, edgec )\n%VOXEL_IMAGE Creates a 3D voxel image\n%   Parameters:\n%   pts    - n x 3 matrix with 3D points\n%   vox_sz - 1 x 3 vector with voxel size - if vox_sz is a scalar, all\n%            edges will have the same length\n%   color  - face color\n%   alpha  - face alpha (opacity)\n%   edgec  - edge color\n%\n%   Return values:\n%   vert   - 8n x 3 matrix containing the vertices of the voxels\n%   fac    - 6n x 4 matrixes containing the indexes of vert that form a\n%            face\n\n% Example:\n%\n% pts = [1,1,1; 2,2,2];\n% vs = [0.5, 0.5, 0.5];\n% voxel_image(pts, vs);\n% view([-37.5, 30]);\n%\n% This example creates two voxels (at (1,1,1) and (2,2,2)) with edges of\n% length 0.5\n%\n% Author: Stefan Schalk, 11 Feb 2011\n\nif (nargin < 1)\n    error('No input arguments given');\nend\nif (nargin < 2)\n    vox_sz = [1,1,1];\nend\nif (nargin < 3)\n    color = 'b';\nend\nif (nargin < 4)\n    alpha = 1;\nend\nif (nargin < 5)\n    edgec = 'k';\nend\n\nif (size(pts,2) ~= 3)\n    error('pts should be an n x 3 matrix');\nend\nif (isscalar(vox_sz))\n    vox_sz = vox_sz*ones(1,3);\nend\nif (size(vox_sz,1) ~= 1 || size(vox_sz,2) ~= 3)\n    error('vox_sz should be an 1 x 3 vector');\nend\n\nnp = size(pts,1);\nvert = zeros(8*np,3);\nfac = zeros(6*np,4,'uint32');\nvert_bas = [...\n        -0.5,-0.5,-0.5;\n        0.5,-0.5,-0.5;\n        0.5,0.5,-0.5;\n        -0.5,0.5,-0.5;\n        -0.5,-0.5,0.5;\n        0.5,-0.5,0.5;\n        0.5,0.5,0.5;\n        -0.5,0.5,0.5];\nvert_bas = vert_bas.*([vox_sz(1).*ones(8,1), vox_sz(2).*ones(8,1), vox_sz(3).*ones(8,1)]);\nfac_bas = [...\n        1,2,3,4;\n        1,2,6,5;\n        2,3,7,6;\n        3,4,8,7;\n        4,1,5,8;\n        5,6,7,8];\nfor vx = 1:np\n    a = ((vx-1)*8+1):vx*8;\n    for dim = 1:3\n        vert( a,dim ) = vert_bas(:,dim) + pts(vx,dim);\n    end\n    fac ( ((vx-1)*6+1):vx*6,: ) = (vx - 1)*8*ones(6,4) + fac_bas;\nend\npatch('Vertices',vert,'Faces',fac,'FaceColor',color,'FaceAlpha',alpha,'Edgecolor',edgec);\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/30374-voxel-image/voxel_image.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5710419690689931}}
{"text": "function npts = plotObj(prob,xb,data)\n%PLOTOBJ Plot the objective function contour\n%   plotObj(prob,xb,data)\n\n%   Copyright (C) 2011 Jonathan Currie (I2C2)\n\n%Contour Colour\ndkg = [0.4 0.4 0.4];\n%Gather Commonly Used Inputs\nnpts = data.npts;\nscale = data.scale;\nidx = data.idx;\nfval = [];\n\n%Detail based on problem type, only if not specified by the user\nif(isempty(npts))\n    switch(lower(prob.type))\n        case {'lp','milp','bilp'}\n            npts = 5;\n        case {'qp','qcqp','miqp','miqcqp','sdp','misdp'}\n            npts = 30;\n        case {'nls','uno','nlp','minlp'}\n            npts = 50;\n        otherwise\n            npts = 50;\n    end\nend\n\n%Determine if we have a 1D or 2D problem\nif((~isempty(prob.lb) && length(prob.lb) == 1) || (~isempty(xb) && length(xb) == 1))\n    %Generate vector Based On Mode\n    switch(data.mode)\n        case {'normal','usex0','bounded_scale'}\n            if(length(scale) == 2)\n                x = linspace(scale(1),scale(2),npts);\n            elseif(length(scale) == 1)\n                x = linspace(xb(1)-scale,xb(1)+scale,npts);\n            else\n                error('Input ''scale'' should be a vector with two inputs [xmin,xmax] for 1D problems');\n            end\n        case {'multi','bounded'}\n            x = linspace(prob.lb(1),prob.ub(1),npts);\n    end\n    obj = zeros(npts,1);\n    %Get Objective (created in buildConfig)\n    fun = prob.objective;\n    %Create Objective Line\n    for i = 1:npts\n    \tobj(i) = fun(x(i));\n    end\n    %Do Log Plot if asked\n    if(data.dolog)\n        obj = log(obj);\n    end\n    %Draw Plot\n    plot(x,obj.*prob.sense,'-','color',dkg);\n    yl = ylim; axis([x(1) x(end) yl]);\n    %Get Min\n    if(~isempty(xb))\n        fval = fun(xb).*prob.sense;\n    end\n    \nelse %2D or higher Problem\n    %Generate Grid Based On Mode\n    switch(data.mode)\n        case {'normal','usex0','bounded_scale'}\n            if(length(scale) == 4)\n                [x1,x2] = meshgrid(linspace(scale(1),scale(2),npts),linspace(scale(3),scale(4),npts));\n            elseif(length(scale) == 1)\n                [x1,x2] = meshgrid(linspace(xb(idx(1))-scale,xb(idx(1))+scale,npts),linspace(xb(idx(2))-scale,xb(idx(2))+scale,npts));\n            else\n                error('Input ''scale'' should be a vector with four inputs [x1min, x1max, x2min, x2max] for 2D problems');\n            end\n        case {'multi','bounded'}\n            [x1,x2] = meshgrid(linspace(prob.lb(idx(1)),prob.ub(idx(1)),npts),linspace(prob.lb(idx(2)),prob.ub(idx(2)),npts));\n    end\n    nox = size(x1);\n    noy = size(x2);\n    obj = zeros(nox(1),noy(2));\n    %Get Objective (created in buildConfig)\n    fun = prob.objective;\n    x = data.fixval;\n    %Create Objective Surface\n    for npts = 1:nox(1)\n        for m = 1:noy(2)\n            x(idx) = [x1(npts,m) x2(npts,m)]';\n            obj(npts,m) = fun(x);\n        end\n    end\n    %Do Log Plot if asked\n    if(data.dolog)\n        obj = log(obj);\n    end\n    %Draw Contour Plot\n    [hc,hl] = contour(x1,x2,obj.*prob.sense,':','color',dkg);\n    if(~isempty(hc))\n        clabel(hc,hl);\n        hold on;\n        %Plot Minimum Contour\n        if(~isempty(xb))\n            fval = fun(xb).*prob.sense;\n            contour(x1,x2,obj.*prob.sense,':','color',dkg,'levellist',fval);\n        end \n    else\n        optiwarn('OPTI:EmptyContour','Objective Contour Data is Empty - Cannot Plot Objective!');\n        %Manually set axis of interest\n        try\n            axis([min(min(x1)) max(max(x1)) min(min(x2)) max(max(x2))]);\n        catch\n        end\n    end\n   \n    xlabel(sprintf('x_%d',idx(1))); ylabel(sprintf('x_%d',idx(2)));\nend\n\n%Plot Optimum + Title\ndata.fval = fval;\ntitle(plotTitle(prob,xb,data));\nhold off;\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/OptiToolbox/Utilities/Plots/plotObj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867825403176, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5710419676605046}}
{"text": "function D = sparseDiag(d)\n\n% SPARSEDIAG Create a diagonal matrix that is sparse from a vector.\n% FORMAT\n% DESC creates a diagonal matrix that is sparse from a vector.\n% ARG d : the diagonal vector from which the sparse diagonal matrix\n% is formed.\n% RETURN D : the sparse diagonal matrix containing the vector as\n% its diagonal.\n%\n% SEEALSO : diag, spdiags\n%\n% COPYRIGHT : Neil D. Lawrence, 2005\n\n% NDLUTIL\n\nif length(size(d)) ~=2\n  error('Input must be a vector.');\nend\nif size(d, 1) ~= 1 & size(d, 2) ~=1\n  error('Input must be a vector.');\nend\n\nD = spdiags(d, 0, length(d), length(d));\n% % Can be made more efficient.\n% n = length(d);\n% D = spalloc(n, n, n);\n% for i = 1:n\n%   D(i, i) = d(i);\n% end\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ndlutil/sparseDiag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.5709904681096013}}
{"text": "function b = r8to_to_r8ge ( n, a )\n\n%*****************************************************************************80\n%\n%% R8TO_TO_R8GE copies a R8TO matrix to a R8GE matrix.\n%\n%  Discussion:\n%\n%    The R8TO storage format is used for a Toeplitz matrix, which is constant\n%    along diagonals.  Thus, in an N by N Toeplitz matrix, there are at most \n%    2*N-1 distinct entries.  The format stores the N elements of the first\n%    row, followed by the N-1 elements of the first column (skipping the\n%    entry in the first row).\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    09 February 2004\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Input, real A(2*N-1), the R8TO matrix.\n%\n%    Output, real B(N,N), the R8GE matrix.\n%\n  for i = 1 : n\n    b(i,1:i-1) = a(n+i-1:-1:n+1,1);\n    b(i,i:n) = a(1:n-i+1,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/linplus/r8to_to_r8ge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5709904598009844}}
{"text": "function [cdstr, utstr] = jd2str(jdate)\n\n% convert Julian date to string equivalent\n% calendar date and universal time\n\n% input\n\n%  jdate = Julian date\n\n% output\n\n%  cdstr = calendar date string\n%  utstr = universal time string\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[month, day, year] = gdate(jdate);\n\n% serial date number\n\nsdn = datenum(year, month, day);\n\n% create calendar date string\n\ncdstr = datestr(sdn, 1);\n\n% create universal time string\n\nutstr = datestr(day - fix(day), 'HH:MM:SS.FFF');\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/jd2str.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.5709904514923675}}
{"text": "function [near,in,on,B,L] = near_mesh(V,F,Q,epsilon)\n  % NEAR_MESH test whether a list of points are in or near a given mesh\n  %  \n  % [near] = near_mesh(V,F,Q)\n  % [near,in,on,B,L] = near_mesh(V,F,Q)\n  % \n  % Inputs:\n  %   V  #V by dim list of vertex positions\n  %   F  #F by 3 list of face indices\n  %   Q  #Q by dim list of query points\n  %   epsilon  minium distance allowed after collapses are complete, default is to\n  %     use fraction of maximum edge length\n  % Outputs:\n  %   near #Q list of flags revealing whether queries are near (V,F)\n  %   in #Q list of flags revealing whether queries are in (V,F)\n  %   on #Q list of flags revealing whether queries are on boundary of (V,F)\n  %   B  #B by 1 list of mesh outline edges \n  %   L  #loops+1 by 1 list of boundary loop start indices into B, the last\n  %     entries is (by tradition) always the numel of B + 1\n  %\n  % See in_mesh, inpolygon\n  %\n\n  if ~exist('epsilon','var') || isempty(epsilon)\n    EE = edges(F);\n    % maximum edge length\n    %maxD = max(sqrt(sum((V(EE(:,1),:) - V(EE(:,2),:)).^2,2)));\n    minD = min(sqrt(sum((V(EE(:,1),:) - V(EE(:,2),:)).^2,2)));\n    epsilon = minD/2;\n  end\n\n  dim = size(V,2);\n  % only works in 2D\n  assert(dim == 2);\n\n  % first determine points strictly in or on mesh\n  [in,on,B,L] = in_mesh(V,F,Q);\n\n  % avoid sqrts\n  sqr_eps = epsilon.^2;\n\n  % boundary edges\n  BE = [B; B(2:end) B(1)]';\n  % compute projection of each point to each boundary line segment\n  [T,sqrD] = project_to_lines(Q,V(BE(:,1),:),V(BE(:,2),:));\n  % each vertex seen by each edge\n  QBE = repmat(Q,[1 1 size(BE,1)]);\n  % edge start positions\n  S = V(BE(:,1),:);\n  % edge destination positions\n  D = V(BE(:,2),:);\n  % distance of each point to each edge start\n  sqrDS = ...\n    squeeze(sum((QBE - permute(repmat(S,[1 1 size(Q,1)]),[3 2 1])).^2,2));\n  % distance of each point to each edge dest\n  sqrDD = ...\n    squeeze(sum((QBE - permute(repmat(D,[1 1 size(Q,1)]),[3 2 1])).^2,2));\n  % replace distances to edges when point is closest to start or dest endpoints\n  % respectively\n  sqrD(T<0) = sqrDS(T<0);\n  sqrD(T>1) = sqrDD(T>1);\n  % compute minimum distance to boundary\n  [minD] = min(sqrD,[],2);\n  % mask telling whether closest point for each edge is close enough\n  near = minD<sqr_eps;\n  % all strictly in points are also close\n  near = in | near;\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/near_mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5708715191536692}}
{"text": "classdef comparison\n\nmethods(Static)\n\n        function result = matching_atoms_ratio(original, new, options)\n            % Returns distance betweeen two dictionaries\n            % in terms of how many atoms from the original\n            % dictionary could be \n            % found in the new dictionary\n            % Assumes that all atoms in dictionary are normalized.\n            % Works well if the dictionaries have low coherence.\n            distance_threshold=0.01;\n            if nargin > 2\n                if isfield(options, 'distance_threshold')\n                    distance_threshold = options.distance_threshold;\n                end\n            end\n            % Number of atoms which could be \n            % identified properly\n            atomsFound=0;\n            % We compute inner product of each\n            % atom in one dictionary with all\n            % atoms in other dictionary\n            innerProducts =abs(original'*new);\n            % Find the number of atoms in original dictionary\n            numAtoms = size(original,2);\n            for i=1:1:numAtoms\n                %  Trying to find a match for the i-th atom in original dictionary.\n                % We find its highest inner product\n                % with atoms in new dictionary\n                max_similarity = max(innerProducts(i,:));\n                % The distance is 1  - max_similarity\n                min_distance =1- max_similarity;\n                % If distance is less than the threshold\n                % then the atom has been found.\n                match_found = (min_distance<distance_threshold);\n                atomsFound=atomsFound + match_found;\n            end;\n            % Find the ratio of found atoms with total atoms\n            result= atomsFound/numAtoms;\n        end\n        \n\n\nend\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/+dict/comparison.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5708715017193355}}
{"text": "function [mach] = ftps2mach(ftps)\n% Convert speed from feet per second to mach number (at STP!)\n% Chad A. Greene 2012\nmach = ftps*0.0008886297376093 ;", "meta": {"author": "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/ftps2mach.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5707679693856752}}
{"text": "%VOCEVALSEG Evaluates a set of segmentation results.\n% VOCEVALSEG(VOCopts,ID); prints out the per class and overall\n% segmentation accuracies. Accuracies are given using the intersection/union \n% metric:\n%   true positives / (true positives + false positives + false negatives) \n%\n% [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class\n% percentage ACCURACIES, the average accuracy AVACC and the confusion\n% matrix CONF.\n%\n% [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns\n% the unnormalised confusion matrix, which contains raw pixel counts.\nfunction [accuracies,avacc,conf,rawcounts] = tvg_VOCevalseg(VOCopts,id)\n\n% image test set\n[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d');\n\n% number of labels = number of classes plus one for the background\nnum = VOCopts.nclasses+1; \nconfcounts = zeros(num);\ncount=0;\ntic;\nfor i=1:length(gtids)\n    % display progress\n    if toc>1\n        fprintf('test confusion: %d/%d\\n',i,length(gtids));\n        drawnow;\n        tic;\n    end\n        \n    imname = gtids{i};\n    \n    % ground truth label file\n    gtfile = sprintf(VOCopts.seg.clsimgpath,imname);\n    [gtim,map] = imread(gtfile);    \n    gtim = double(gtim);\n    \n    % results file\n    resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname);\n    [resim,map] = imread(resfile);\n    resim = double(resim);\n    \n    % Check validity of results image\n    maxlabel = max(resim(:));\n    if (maxlabel>VOCopts.nclasses), \n        error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses);\n    end\n\n    szgtim = size(gtim); szresim = size(resim);\n    if any(szgtim~=szresim)\n        error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2));\n    end\n    \n    %pixel locations to include in computation\n    locs = gtim<255;\n    \n    % joint histogram\n    sumim = 1+gtim+resim*num; \n    hs = histc(sumim(locs),1:num*num); \n    count = count + numel(find(locs));\n    confcounts(:) = confcounts(:) + hs(:);\nend\n\n% confusion matrix - first index is true label, second is inferred label\n%conf = zeros(num);\nconf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]);\nrawcounts = confcounts;\n\n% Percentage correct labels measure is no longer being used.  Uncomment if\n% you wish to see it anyway\n%overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:));\n%fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\\n',overall_acc);\n\naccuracies = zeros(VOCopts.nclasses,1);\nfprintf('Accuracy for each class (intersection/union measure)\\n');\nfor j=1:num\n   \n   gtj=sum(confcounts(j,:));\n   resj=sum(confcounts(:,j));\n   gtjresj=confcounts(j,j);\n   % The accuracy is: true positive / (true positive + false positive + false negative) \n   % which is equivalent to the following percentage:\n   accuracies(j)=100*gtjresj/(gtj+resj-gtjresj);   \n   \n   clname = 'background';\n   if (j>1), clname = VOCopts.classes{j-1};end;\n   fprintf('  %14s: %6.3f%%\\n',clname,accuracies(j));\nend\naccuracies = accuracies(1:end);\navacc = mean(accuracies);\nfprintf('-------------------------\\n');\nfprintf('Average accuracy: %6.3f%%\\n',avacc);\n", "meta": {"author": "torrvision", "repo": "crfasrnn", "sha": "215666972c5e4c9fb10f965d2aab056b6f3f91fe", "save_path": "github-repos/MATLAB/torrvision-crfasrnn", "path": "github-repos/MATLAB/torrvision-crfasrnn/crfasrnn-215666972c5e4c9fb10f965d2aab056b6f3f91fe/matlab-scripts/devtools/tvg_VOCevalseg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.57076794989197}}
{"text": "function K = covPPERard(cov, hyp, x, z, i)\n\n% Stationary partially periodic covariance function for a stationary \n% covariance function k0 such as covMaternard, covPPard, covRQard and covSEard.\n% Partially periodic means that the covariance function is periodic only\n% along some dimensions (as opposed to all dimensions).\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)), \n% [u(x)]([i,i+D]) = [sin(pi*x/p); cos(pi*x/p)]      if p_i is finite\n% [u(x)]([i,i+D]) = [x; 0]                          if p_i is not finite\n%\n% where the period p belongs to covPPERard 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 Luigi Acerbi, 2015-12-20.\n% Original code by Hannes Nickisch.\n%\n% See also COVFUNCTIONS, COVPERARD.\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 isfinite(p(i))                             % periodic dimension  \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                                            % non-periodic dimension\n      K = zeros(n);        \n    end\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        if isfinite(p(i-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-D);            \n        end\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  [~,D] = size(x);\n  pd = find(isfinite(p));     % periodic dimensions\n  x(:,pd) = 2*pi*x(:,pd)*diag(1./p(pd));\n  x = [x, zeros(size(x))];\n  x(:,pd+D) = cos(x(:,pd)); x(:,pd) = sin(x(:,pd)); \n  if numel(z)>0 && ~dg\n    z(:,pd) = 2*pi*z(:,pd)*diag(1./p(pd));\n    z = [z, zeros(size(z))];  \n    z(:,pd+D) = cos(z(:,pd)); z(:,pd) = sin(z(:,pd)); \n  end", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/gpml_fast/covPPERard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5707679491778715}}
{"text": "% Observation models and vision library.\n%\n% Sensor management\n%   composeRobSen                   - Compose robot and sensor frames and parameters.\n%\n% Pin-hole model functions\n%   distort                         - Distort projected point with radial distortion.\n%   undistort                       - Undistorts projected point with radial distortion.\n%   pixellise                       - Metric to pixellic conversion\n%   depixellise                     - Pixellic to metric conversion\n%   intrinsic                       - Build intrinsic matrix\n%   invIntrinsic                    - Build inverse intrinsic matrix\n%   essential                       - Essential matrix from frame specification.\n%   fundamental                     - Fundamental matrix between 2 cameras.\n%   pinHole                         - Pin-hole camera model, with optional radial distortion.\n%   invPinHole                      - Inverse pin-hole camera model, with radial distortion correction.\n%   pinHoleIdp                      - Pin-hole camera model for Inverse depth points, with radial distortion.\n%   invPinHoleIdp                   - Inverse pin-hole camera model for IDP, with radial distortion correction.\n%   pinHolePlucker                  - Projects plucker line.\n%   invPinHolePlucker               - Retro-projects plucker line\n%   aInvPinHolePlucker              - Inverse pin hole model for Plucker lines\n%   pinHoleSegment                  - Pin hole projection of a segment.\n%   pluckerInvCamera                - Inverse Plucker projection matrix\n%   isVisible                       - Points visible from pinHole camera.\n%   invDistortion                   - Radial distortion correction calibration.\n%   invPinHoleHmg                   - Retro-project anchored homogeneous point AHP.\n%   visibleSegment                  - Visible segment.\n%   invPinHoleAPlucker              - Retro-projects anchored plucker line\n%   invPinHoleIdpLin                - IDP line retro projection.\n%   invPinHoleAhm                   - Retro-project anchored homogeneous point AHP.\n%   persp_project                   - Project point into plane using pin-hole camera model\n%   persp_retro                     - Retroproject pixel into 3D space.\n%   pinHoleHmg                      - Pin-hole camera model for HMG points, with optional radial distortion.\n%   projAhmPntIntoPinHole           - Project AHM pnt into pinhole camera.\n%   projIdpPntIntoPinHole           - Project Idp pnt into pinhole.\n%   invPinHoleDepth                 - \n%   pinHoleDepth                    - Pin hole projection with distance measurement\n%\n% Functions related to Omnicam camera model\n%   depixelliseOmniCam              - TODO: can inverse A up front - will save calculation esp in Jac part\n%   invOmniCam                      - Inverse omnidirectional camera model\n%   invOmniCamAhm                   - Retro-project anchored homogeneous point AHP.\n%   invPinHoleAhmLin                - AHM line retro projection.\n%   invPinHoleHmgLin                - IDP line retro projection.\n%   omniCam                         - Gives projected pixel u of 3D point p for Omnidirectional Camera model\n%   omni_project                    - Gives projected pixel u of 3D point p for Omnidirectional Camera model\n%   omni_retro                      - Retroproject pixel into 3D space.\n%   pixelliseOmniCam                - Omnicam Affine correction step\n%\n% Observation models, with 2 frame transforms\n%   projEucPntIntoPinHoleOnRob      - Project Euc pnt into pinhole on robot.\n%   projIdpPntIntoPinHoleOnRob      - Project Idp pnt into pinhole on robot.\n%   projHmgPntIntoPinHoleOnRob      - Project Hmg pnt into pinhole on robot.\n%   projSegLinIntoPinHoleOnRob      - Project segment line into pinhole on robot.\n%   projPlkLinIntoPinHoleOnRob      - Project Plucker line into pinhole on robot.\n%   projAplLinIntoPinHoleOnRob      - Project anchored Plucker line into pinhole on robot.\n%   projIdpLinIntoPinHoleOnRob      - Project Idp line into pinhole on robot.\n%   retroProjIdpPntFromPinHoleOnRob - Retro-project idp from pinhole on robot.\n%   retroProjHmgPntFromPinHoleOnRob - Retro-proj. Hmg pnt from pinhole on rob.\n%   retroProjPlkLinFromPinHoleOnRob - Retro-project Plucker line from pinhole on robot.\n%   retroProjPlkEndPnts             - Retro project Plucker endpoints.\n%   retroProjAplLinFromPinHoleOnRob - Retro-project anchored Plucker line from pinhole on robot.\n%   retroProjAplEndPnts             - Retro project anchored Plucker endpoints.\n%   retroProjIdpLinFromPinHoleOnRob - retroprj Idp Line from pinhole on robot.\n%   projAhmPntIntoPinHoleOnRob      - Project Ahm pnt into pinhole on robot.\n%   retroProjAhmPntFromPinHoleOnRob - Retro-project ahm from pinhole on robot.\n%   projAhmLinIntoPinHoleOnRob      - Project Ahm line into pinhole on robot.\n%   projHmgLinIntoPinHoleOnRob      - Project Hmg line into pinhole on robot.\n%   retroProjAhmLinFromPinHoleOnRob - retroprj Ahm Line from pinhole on robot.\n%   retroProjHmgLinFromPinHoleOnRob - retroprj Hmg Line from pinhole on robot.\n%   projAhmPntIntoOmniCamOnRob      - Project Ahm pnt into omnidirectional camera on robot.\n%   projEucPntIntoOmniCamOnRob      - Project Euc pnt into omnidirec cam on robot.\n%   retroProjAhmPntFromOmniCamOnRob - Retro-project ahm from omnicam on robot.\n%   projEucPntIntoPhdOnRob          - Project Eucliden point into Pinhole-depth in Robot\n%   retroProjEucPntFromPhdOnRob     - Retro-proj Euc. pnt. from Pinhole-depth in Rob\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/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5707679434864349}}
{"text": "%SNR\nfunction Sn=SNR(Im_original,Im_modified)\n\nif (size(Im_original)~=size(Im_modified))\n    error ('error:image sizes do not agree')\nend\n\nelse\n    A=double(Im_original);\n    B=double(Im_modified);\nend\n\n[m,n]=size(A);\nsumaI=0;\nsumaDif=0;\nfor u=1:m\n    for v=1:n\n        sumaI=sumaI+A(u,v)^2;\n        sumaDif=sumaDif+(A(u,v)-B(u,v))^2;\n    end\nend\n\nif (sumaDif==0)\n    sumaDif=1;\nend\n\nSn=sumaI/sumaDif;\nSn=10*log10(Sn);", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u53bb\u566a\u7b97\u6cd5/an-improved-NLM-image-denoising-algorithm-based-on-edge-detection-master/NLMeans2/SNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5707679386476455}}
{"text": "function x = elastix_transf_imcoord2(x, t)\n% elastix_transf_imcoord  Convert 2D pixel coordinates using\n% elastix/transformix transform.\n%\n% Let x be the (x, y)-coordinates of a pixel in an image (instead of\n% row/column). This function computes the coordinates that the same pixel\n% will have in the new image after transformix or elastix transforms.\n%\n% XT = elastix_transf_imcoord2(X, T)\n%\n%   X is a two-column matrix with the Cartesian coordinates of one or more\n%   points in the input image.\n%\n%   T is a struct produced by elastix with the details of the image\n%   transformation. See help elastix for details.\n%\n%   XT has the same size as X, and contains the coordinates of the same\n%   points in the output image.\n%\n% See also: elastix, transformix, elastix_read_file2param,\n% elastix_read_reg_output, elastix_write_param2file,\n% elastix_compose_afftransf.\n\n% Author: Ramon Casero <rcasero@gmail.com>\n% Copyright \u00a9 2014 University of Oxford\n% Version: 0.1.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 <http://www.gnu.org/licenses/>.\n\n% check arguments\nnarginchk(2, 2);\nnargoutchk(0, 1);\n\nif (size(x, 2) ~= 2)\n    error('X must have two columns (2D points)')\nend\nif (~isstruct(t))\n    error('T must be a struct with the transform parameters')\nend\nif (isfield(t, 'Direction') && any(t.Direction ~= [1 0 0 1]))\n    error('Not implemented for Direction ~= [1 0 0 1]')\nend\n\n% defaults\nif (~isfield(t, 'CenterOfRotationPoint'))\n    t.CenterOfRotationPoint = [0 0];\nend\n\n% select type of transform\nswitch (t.Transform)\n    \n    case 'SimilarityTransform' % similarity transform\n        \n        if (length(t.TransformParameters) ~= 4)\n            error('SimilarityTransform must have 4 parameters')\n        end\n        \n        % transformation nomenclature\n        s =     t.TransformParameters(1);\n        theta = t.TransformParameters(2);\n        tx =    t.TransformParameters(3);\n        ty =    t.TransformParameters(4);\n        cx =    t.CenterOfRotationPoint(1);\n        cy =    t.CenterOfRotationPoint(2);\n        \n        % transform points\n        %\n        % note that this is the inverse of the similarity transform. The\n        % reason is the way that ITK, and by extension elastix/transformix,\n        % implement image transformations\n        x = [cos(theta) sin(theta); -sin(theta) cos(theta)] ...\n            * [x(:, 1)' - tx - cx; x(:, 2)' - ty - cy] / s;\n        x = x';\n        x(:, 1) = x(:, 1) + cx;\n        x(:, 2) = x(:, 2) + cy;\n        \n    otherwise\n        \n        error('Transform not implemented')\n        \nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ElastixToolbox/elastix_transf_imcoord2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5707679386476455}}
{"text": "function quality_test11 ( dim_num, n, z )\n\n%*****************************************************************************80\n%\n%% TEST11 tests POINTSET_SPACING.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    05 November 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n');\n  fprintf ( 1, 'TEST11\\n');\n  fprintf ( 1, '  POINTSET_SPACING computes pointset spacing parameters.\\n');\n\n  gamma = pointset_spacing ( dim_num, n, z );\n\n  gamma_min = min ( gamma(1:n) );\n  gamma_max = max ( gamma(1:n) );\n\n  gamma_ave = sum ( gamma(1:n) ) / n;\n\n  if ( 1 < n )\n    gamma_std = sqrt ( sum ( ( gamma(1:n) - gamma_ave ).^2 )  / ( n - 1 ) );\n  else\n    gamma_std = 0.0;\n  end\n\n  fprintf ( 1, '\\n');\n  fprintf ( 1, '  Minimum spacing          GAMMA_MIN = %f\\n', gamma_min );\n  fprintf ( 1, '  Average spacing          GAMMA_AVE = %f\\n', gamma_ave );\n  fprintf ( 1, '  Maximum spacing          GAMMA_MAX = %f\\n', gamma_max );\n  fprintf ( 1, '  Spacing standard dev     GAMMA_STD = %f\\n', gamma_std );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quality/quality_test11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.5706310025578749}}
{"text": "function exact = p03_exact ( )\n\n%*****************************************************************************80\n%\n%% P03_EXACT returns the exact integral for problem 3.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    17 January 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Output, real EXACT, the value of the integral.\n%\n  exact = ( 16.0 / 3.0 ) * ( 2.0 - sqrt ( 2.0 ) );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_int_2d/p03_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.5706309987706074}}
{"text": "function [wl,wr] = cvwindow(x)\n\n  wr = zeros(size(x));\n  wl = zeros(size(x));\n  \n  eps = 1e-16;\n  sml = find(x<eps); %too small\n  mid = find(x>=eps & x<=1-eps); %just right\n  lrg = find(x>1-eps); %too large\n  \n  wl(sml) = 0;  wr(sml) = 1;\n  wl(lrg) = 1;  wr(lrg) = 0;\n  \n  xmid = x(mid);\n  a = exp(1-1./(1-exp(1-1./(1-xmid))));\n  b = exp(1-1./(1-exp(1-1./xmid)));\n  n = sqrt(a.^2 + b.^2);\n  wl(mid) = a./n;  wr(mid) = b./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/CurveLab-2.1.3/mecv/cvwindow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5706116040644964}}
{"text": "function net = mlpunpak(net, w)\n%MLPUNPAK Separates weights vector into weight and bias matrices. \n%\n%\tDescription\n%\tNET = MLPUNPAK(NET, W) takes an mlp network data structure NET and  a\n%\tweight vector W, and returns a network data structure identical to\n%\tthe input network, except that the first-layer weight matrix W1, the\n%\tfirst-layer bias vector B1, the second-layer weight matrix W2 and the\n%\tsecond-layer bias vector B2 have all been set to the corresponding\n%\telements of W.\n%\n%\tSee also\n%\tMLP, MLPPAK, MLPFWD, MLPERR, MLPBKP, MLPGRAD\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n% Check arguments for consistency\nerrstring = consist(net, 'mlp');\nif ~isempty(errstring);\n  error(errstring);\nend\n\nif net.nwts ~= length(w)\n  error('Invalid weight vector length')\nend\n\nnin = net.nin;\nnhidden = net.nhidden;\nnout = net.nout;\n\nmark1 = nin*nhidden;\nnet.w1 = reshape(w(1:mark1), nin, nhidden);\nmark2 = mark1 + nhidden;\nnet.b1 = reshape(w(mark1 + 1: mark2), 1, nhidden);\nmark3 = mark2 + nhidden*nout;\nnet.w2 = reshape(w(mark2 + 1: mark3), nhidden, nout);\nmark4 = mark3 + nout;\nnet.b2 = reshape(w(mark3 + 1: mark4), 1, nout);\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/mlpunpak.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.570611580517222}}
{"text": "function M = prepare_mesh_fittemplate(headshape,template)\n\n% PREPARE_MESH_FITTEMPLATE computes an affine transformation matrix between 2 point clouds \n%\n% This function relies on cpd toolbox from  Myronenko, see https://sites.google.com/site/myronenko/research/cpd\n%\n%\n% See also FT_PREPARE_MESH\n\n% Copyright (C) 2019, Simon Homoelle\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 <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% add toolbox cpd\nft_hastoolbox('cpd', 2);\n\n%\nopt.corresp = 0;\nopt.method  = 'affine';\nopt.max_it = 100;\nopt.fgt = 0;\nopt.tol = 10e-12;\nopt.outliers = 0.0;\nopt.outliers = 0;\n[transform,~] = cpd_register(headshape,template, opt);\n\nM = eye(4,4);\nM(1:3,1:3) = transform.R;\nM(1:3,4)   = transform.t;\n\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/private/prepare_mesh_fittemplate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5705787915885178}}
{"text": "classdef Optimizer_MMA < Optimizer\n    \n    properties (GetAccess = public, SetAccess = protected)\n        type = 'MMA'\n    end\n    \n    properties (Access = private)\n        kkttol\n        maxoutit\n        x\n        xold1\n        xold2\n        xmin\n        xmax\n        low\n        outit = 0;\n        outeriter = 0;\n        upp\n        m\n        c\n        d\n        a0\n        a\n        n\n        f0val\n        df0dx\n        fval\n        dfdx\n        upperBound\n        lowerBound\n        hasFinished\n        incrementalScheme\n        hasConverged\n        historicalVariables\n       % targetParameters\n        KKTnorm\n    end\n    \n    methods (Access = public)\n        \n        function obj = Optimizer_MMA(cParams)\n            obj.initOptimizer(cParams);\n            obj.init(cParams);\n            obj.outputFunction.monitoring.create(cParams);\n%             obj.upperBound = cParams.uncOptimizerSettings.ub;\n%             obj.lowerBound = cParams.uncOptimizerSettings.lb;\n            obj.maxoutit = 1e4;\n        end\n\n       function solveProblem(obj)\n            % obj.cost.computeFunctionAndGradient();\n            % obj.constraint.computeFunctionAndGradient();\n%             obj.printOptimizerVariable();\n            obj.hasFinished = false;\n            obj.printOptimizerVariable();\n            while ~obj.hasFinished\n                obj.update();\n                obj.updateIterInfo();\n                obj.updateMonitoring();\n                obj.printOptimizerVariable();\n            end\n%             obj.printOptimizerVariable();\n%             obj.printHistory();\n            obj.hasConverged = 0;\n%             obj.printHistoryFinalValues();\n       end\n        \n        function update(obj)\n            x = obj.designVariable.value;\n            obj.cost.computeFunctionAndGradient(); \n            obj.constraint.computeFunctionAndGradient();\n            obj.checkInitial(x);\n            obj.outit = obj.outit+1;\n            obj.outeriter = obj.outeriter+1;\n            %%%% The MMA subproblem is solved at the point xval:\n            [xmma,ymma,zmma,lam,xsi,eta,mu,zet,s,obj.low,obj.upp] = ...\n                obj.mmasub(obj.m,obj.n,obj.outeriter,x,obj.xmin,obj.xmax,obj.xold1,obj.xold2, ...\n                obj.f0val,obj.df0dx,obj.fval,obj.dfdx,obj.low,obj.upp,obj.a0,obj.a,obj.c,obj.d);\n            %%%% Some vectors are updated:\n            obj.xold2 = obj.xold1;\n            obj.xold1 = x;\n            x = xmma;\n            %%%% The user should now calculate function values and gradients\n            %%%% of the objective- and constraint functions at xval.\n            %%%% The results should be put in f0val, df0dx, fval and dfdx.\n            obj.designVariable.update(x);\n            obj.cost.computeFunctionAndGradient();\n            obj.constraint.computeFunctionAndGradient();\n            \n            [obj.f0val,obj.df0dx,obj.fval,obj.dfdx] = obj.funmma();\n            %%%% The residual vector of the KKT conditions is calculated:\n            [~,kktnorm] = obj.kktcheck(obj.m,obj.n,xmma,ymma,zmma,lam,xsi,eta,mu,zet,s, ...\n                obj.xmin,obj.xmax,obj.df0dx,obj.fval,obj.dfdx,obj.a0,obj.a,obj.c,obj.d);\n            \n            obj.historicalVariables.kktnorm = kktnorm;\n            obj.dualVariable.value = lam;            \n            obj.updateConvergenceStatus();\n            obj.KKTnorm     = kktnorm;\n        end\n        \n    end\n    \n    methods (Access = private)\n\n        function updateMonitoring(obj)\n            s.hasFinished          = obj.hasFinished;\n            s.nIter                = obj.nIter;\n            s.KKTnorm              = obj.KKTnorm;\n            s.outitFrac            = obj.outit/obj.maxoutit;\n            obj.outputFunction.monitoring.compute(s);\n        end\n\n        function init(obj,cParams)\n            obj.outputFunction         = cParams.outputFunction.monitoring;\n            obj.upperBound             = cParams.uncOptimizerSettings.ub;\n            obj.lowerBound             = cParams.uncOptimizerSettings.lb;\n            obj.incrementalScheme      = cParams.incrementalScheme;\n            obj.hasConverged           = false;\n            obj.constraintCase         = cParams.constraintCase;\n            obj.targetParameters       = cParams.targetParameters;\n        end\n        \n        function [f,df,c,dc] = funmma(obj)\n            f  = obj.cost.value;\n            df = obj.cost.gradient;\n            c  = obj.constraint.value;\n            dc = obj.constraint.gradient;\n            dc = dc';\n            \n            [c,dc] = obj.checkConstraintCase(c,dc);\n            \n            %% Re-scale constraints\n            % In many applications, the constraints are on the form yi(x) < =  ymaxi\n            % The user should then preferably scale the constraints in such a way that 1 < =  ymaxi < =  100 for each i\n            % (and not ymaxi = 10^10 for example).\n\n            \n\n            % kconstr = 100;\n            kconstr = 1;\n            cconstr = 0;\n            c = kconstr*c;\n            c(c > 0) = c(c > 0) + cconstr;\n            c(c < 0) = c(c < 0) - cconstr;\n            % dc = kconstr*dc;\n            \n            %% Re-scale objective function\n            % The objective function f(x) should preferably be scaled such that\n            % 1 < =  f0(x) < =  100 for reasonable values on the variables.\n            kfun = 1;\n            cfun = 0;\n            f = kfun*f + cfun;\n            df = kfun*df;\n        end\n        \n        function checkInitial(obj,x0)\n            if isempty(obj.x)\n                obj.x = x0;\n                obj.xold1 = obj.x;\n                obj.xold2 = obj.xold1;\n                obj.xmin = obj.lowerBound*ones(length(x0),1);\n                obj.xmax = obj.upperBound*ones(length(x0),1);\n                % obj.low = obj.xmin;\n                obj.low = zeros(length(x0),1);\n                % obj.upp = obj.xmax;\n                obj.upp = ones(length(x0),1);\n                [obj.f0val,obj.df0dx,obj.fval,obj.dfdx] = obj.funmma();\n                obj.m = length(obj.fval);\n                obj.c = 1000*ones(obj.m,1);\n                obj.d = 0*ones(obj.m,1);\n                obj.a0 = 1;\n                obj.a = 0*ones(obj.m,1);\n                obj.n = length(obj.x);\n            end\n        end\n\n        function [xmma,ymma,zmma,lam,xsi,eta,mu,zet,s,low,upp] = ...\n                mmasub(obj,m,n,iter,xval,xmin,xmax,xold1,xold2, ...\n                ~,df0dx,fval,dfdx,low,upp,a0,a,c,d)\n            epsimin = sqrt(m+n)*10^(-9); %10^(-7);  \n            raa0 = 1e-5;\n            move = 1.0;\n            albefa = 0.1;\n            asyinit = 0.1 ; %0.2 % 0.5; \n            asyincr = 1.1; % 1.2;\n            asydecr = 0.65; % 0.7\n            eeen = ones(n,1);\n            eeem = ones(m,1);\n            zeron = zeros(n,1);\n\n            % Calculation of the asymptotes low and upp :\n            if iter < 2.5\n                low = xval - asyinit*(xmax-xmin);\n                upp = xval + asyinit*(xmax-xmin);\n            else\n                zzz = (xval-xold1).*(xold1-xold2);\n                factor = eeen;\n                factor(find(zzz > 0)) = asyincr;\n                factor(find(zzz < 0)) = asydecr;\n                low = xval - factor.*(xold1 - low);\n                upp = xval + factor.*(upp - xold1);\n                lowmin = xval - 10*(xmax-xmin);\n                lowmax = xval - 0.01*(xmax-xmin);\n                uppmin = xval + 0.01*(xmax-xmin);\n                uppmax = xval + 10*(xmax-xmin);\n                low = max(low,lowmin);\n                low = min(low,lowmax);\n                upp = min(upp,uppmax);\n                upp = max(upp,uppmin);\n            end\n            \n            % Calculation of the bounds alfa and beta :\n            \n            zzz1 = low + albefa*(xval-low);\n            zzz2 = xval - move*(xmax-xmin);\n            zzz  = max(zzz1,zzz2);\n            alfa = max(zzz,xmin);\n            zzz1 = upp - albefa*(upp-xval);\n            zzz2 = xval + move*(xmax-xmin);\n            zzz  = min(zzz1,zzz2);\n            beta = min(zzz,xmax);\n            \n            % Calculations of p0, q0, P, Q and b.\n            \n            xmami = xmax-xmin;\n            xmamieps = 1e-5*eeen;\n            xmami = max(xmami,xmamieps);\n            xmamiinv = eeen./xmami;\n            ux1 = upp-xval;\n            ux2 = ux1.*ux1;\n            xl1 = xval-low;\n            xl2 = xl1.*xl1;\n            uxinv = eeen./ux1;\n            xlinv = eeen./xl1;\n            %\n            p0 = zeron;\n            q0 = zeron;\n            p0 = max(df0dx,0);\n            q0 = max(-df0dx,0);\n            %p0(find(df0dx > 0)) = df0dx(find(df0dx > 0));\n            %q0(find(df0dx < 0)) = -df0dx(find(df0dx < 0));\n            pq0 = 0.001*(p0 + q0) + raa0*xmamiinv;\n            p0 = p0 + pq0;\n            q0 = q0 + pq0;\n            p0 = p0.*ux2;\n            q0 = q0.*xl2;\n            %\n            dfdx = sparse(dfdx);\n            P = max(dfdx,0);\n            Q = max(-dfdx,0);\n            %P(find(dfdx > 0)) = dfdx(find(dfdx > 0));\n            %Q(find(dfdx < 0)) = -dfdx(find(dfdx < 0));\n            PQ = 0.001*(P + Q) + raa0*(eeem*xmamiinv');\n            %PQ = 0.001*(P + Q) + raa0*eeem*xmamiinv;\n            P = P + PQ;\n            Q = Q + PQ;\n            P = P * spdiags(ux2,0,n,n);\n            Q = Q * spdiags(xl2,0,n,n);\n            b = P*uxinv + Q*xlinv - fval ;\n            %\n            %%% Solving the subproblem by a primal-dual Newton method\n            [xmma,ymma,zmma,lam,xsi,eta,mu,zet,s] = ...\n                obj.subsolv(m,n,epsimin,low,upp,alfa,beta,p0,q0,P,Q,a0,a,b,c,d);\n        end\n        \n        function updateConvergenceStatus(obj)\n            kktnorm = obj.historicalVariables.kktnorm;\n            has_not_converged = kktnorm > obj.kkttol && obj.outit < obj.maxoutit;\n            obj.hasConverged = ~has_not_converged;\n        end\n\n        function [c,dc] = checkConstraintCase(obj,c,dc)\n            if strcmp(obj.constraintCase,'EQUALITY')\n                c  = [c;-c];\n                dc = [dc;-dc];\n            end\n        end\n\n        function updateIterInfo(obj)\n            obj.increaseIter();\n            obj.updateStatus();\n        end\n\n        function increaseIter(obj)\n            obj.nIter = obj.nIter + 1;\n        end\n\n        function updateStatus(obj)\n            obj.hasFinished = obj.hasConverged || obj.hasExceededStepIterations();\n        end\n\n        function itHas = hasExceededStepIterations(obj)\n            iStep = obj.incrementalScheme.iStep;\n            nStep = obj.incrementalScheme.nSteps;\n            itHas = obj.nIter >= obj.maxIter*(iStep/nStep);\n        end\n\n    end\n\n    methods (Access = private, Static)\n\n        function [xmma,ymma,zmma,lamma,xsimma,etamma,mumma,zetmma,smma] = ...\n                subsolv(m,n,epsimin,low,upp,alfa,beta,p0,q0,P,Q,a0,a,b,c,d)\n            %\n            % This function subsolv solves the MMA subproblem:\n            %\n            % minimize   SUM[ p0j/(uppj-xj) + q0j/(xj-lowj) ] + a0*z +\n            %          + SUM[ ci*yi + 0.5*di*(yi)^2 ],\n            %\n            % subject to SUM[ pij/(uppj-xj) + qij/(xj-lowj) ] - ai*z - yi < =  bi,\n            %            alfaj < =   xj < =   betaj,  yi > =  0,  z > =  0.\n            %\n            % Input:  m, n, low, upp, alfa, beta, p0, q0, P, Q, a0, a, b, c, d.\n            % Output: xmma,ymma,zmma, slack variables and Lagrange multiplers.\n            %\n            een = ones(n,1);\n            eem = ones(m,1);\n            epsi = 1;\n            epsvecn = epsi*een;\n            epsvecm = epsi*eem;\n            x = 0.5*(alfa+beta);\n            y = eem;\n            z = 1;\n            lam = eem;\n            xsi = een./(x-alfa);\n            xsi = max(xsi,een);\n            eta = een./(beta-x);\n            eta = max(eta,een);\n            mu  = max(eem,0.5*c);\n            zet = 1;\n            s = eem;\n            itera = 0;\n            while epsi > epsimin\n                epsvecn = epsi*een;\n                epsvecm = epsi*eem;\n                ux1 = upp-x;\n                xl1 = x-low;\n                ux2 = ux1.*ux1;\n                xl2 = xl1.*xl1;\n                uxinv1 = een./ux1;\n                xlinv1 = een./xl1;\n                plam = p0 + P'*lam ;\n                qlam = q0 + Q'*lam ;\n                gvec = P*uxinv1 + Q*xlinv1;\n                dpsidx = plam./ux2 - qlam./xl2 ;\n                rex = dpsidx - xsi + eta;\n                rey = c + d.*y - mu - lam;\n                rez = a0 - zet - a'*lam;\n                relam = gvec - a*z - y + s - b;\n                rexsi = xsi.*(x-alfa) - epsvecn;\n                reeta = eta.*(beta-x) - epsvecn;\n                remu = mu.*y - epsvecm;\n                rezet = zet*z - epsi;\n                res = lam.*s - epsvecm;\n                residu1 = [rex' rey' rez]';\n                residu2 = [relam' rexsi' reeta' remu' rezet res']';\n                residu = [residu1' residu2']';\n                residunorm = sqrt(residu'*residu);\n                residumax = max(abs(residu));\n                ittt = 0;\n                while residumax > 0.9*epsi & ittt < 200 % 100\n                    ittt = ittt + 1;\n                    itera = itera + 1;\n                    ux1 = upp-x;\n                    xl1 = x-low;\n                    ux2 = ux1.*ux1;\n                    xl2 = xl1.*xl1;\n                    ux3 = ux1.*ux2;\n                    xl3 = xl1.*xl2;\n                    uxinv1 = een./ux1;\n                    xlinv1 = een./xl1;\n                    uxinv2 = een./ux2;\n                    xlinv2 = een./xl2;\n                    plam = p0 + P'*lam ;\n                    qlam = q0 + Q'*lam ;\n                    gvec = P*uxinv1 + Q*xlinv1;\n                    GG = P*spdiags(uxinv2,0,n,n) - Q*spdiags(xlinv2,0,n,n);\n                    dpsidx = plam./ux2 - qlam./xl2 ;\n                    delx = dpsidx - epsvecn./(x-alfa) + epsvecn./(beta-x);\n                    dely = c + d.*y - lam - epsvecm./y;\n                    delz = a0 - a'*lam - epsi/z;\n                    dellam = gvec - a*z - y - b + epsvecm./lam;\n                    diagx = plam./ux3 + qlam./xl3;\n                    diagx = 2*diagx + xsi./(x-alfa) + eta./(beta-x);\n                    diagxinv = een./diagx;\n                    diagy = d + mu./y;\n                    diagyinv = eem./diagy;\n                    diaglam = s./lam;\n                    diaglamyi = diaglam+diagyinv;\n                    if m < n\n                        blam = dellam + dely./diagy - GG*(delx./diagx);\n                        bb = [blam' delz]';\n                        Alam = spdiags(diaglamyi,0,m,m) + GG*spdiags(diagxinv,0,n,n)*GG';\n                        AA = [Alam     a\n                            a'    -zet/z ];\n                        solut = AA\\bb;\n                        dlam = solut(1:m);\n                        dz = solut(m+1);\n                        dx = -delx./diagx - (GG'*dlam)./diagx;\n                    else\n                        diaglamyiinv = eem./diaglamyi;\n                        dellamyi = dellam + dely./diagy;\n                        Axx = spdiags(diagx,0,n,n) + GG'*spdiags(diaglamyiinv,0,m,m)*GG;\n                        azz = zet/z + a'*(a./diaglamyi);\n                        axz = -GG'*(a./diaglamyi);\n                        bx = delx + GG'*(dellamyi./diaglamyi);\n                        bz  = delz - a'*(dellamyi./diaglamyi);\n                        AA = [Axx   axz\n                            axz'  azz ];\n                        bb = [-bx' -bz]';\n                        solut = AA\\bb;\n                        dx  = solut(1:n);\n                        dz = solut(n+1);\n                        dlam = (GG*dx)./diaglamyi - dz*(a./diaglamyi) + dellamyi./diaglamyi;\n                    end\n                    %\n                    dy = -dely./diagy + dlam./diagy;\n                    dxsi = -xsi + epsvecn./(x-alfa) - (xsi.*dx)./(x-alfa);\n                    deta = -eta + epsvecn./(beta-x) + (eta.*dx)./(beta-x);\n                    dmu  = -mu + epsvecm./y - (mu.*dy)./y;\n                    dzet = -zet + epsi/z - zet*dz/z;\n                    ds   = -s + epsvecm./lam - (s.*dlam)./lam;\n                    xx  = [ y'  z  lam'  xsi'  eta'  mu'  zet  s']';\n                    dxx = [dy' dz dlam' dxsi' deta' dmu' dzet ds']';\n                    %\n                    stepxx = -1.01*dxx./xx;\n                    stmxx  = max(stepxx);\n                    stepalfa = -1.01*dx./(x-alfa);\n                    stmalfa = max(stepalfa);\n                    stepbeta = 1.01*dx./(beta-x);\n                    stmbeta = max(stepbeta);\n                    stmalbe  = max(stmalfa,stmbeta);\n                    stmalbexx = max(stmalbe,stmxx);\n                    stminv = max(stmalbexx,1);\n                    steg = 1/stminv;\n                    %\n                    xold   =   x;\n                    yold   =   y;\n                    zold   =   z;\n                    lamold =  lam;\n                    xsiold =  xsi;\n                    etaold =  eta;\n                    muold  =  mu;\n                    zetold =  zet;\n                    sold   =   s;\n                    %\n                    itto = 0;\n                    resinew = 2*residunorm;\n                    while resinew > residunorm & itto < 50\n                        itto = itto+1;\n                        x   =   xold + steg*dx;\n                        y   =   yold + steg*dy;\n                        z   =   zold + steg*dz;\n                        lam = lamold + steg*dlam;\n                        xsi = xsiold + steg*dxsi;\n                        eta = etaold + steg*deta;\n                        mu  = muold  + steg*dmu;\n                        zet = zetold + steg*dzet;\n                        s   =   sold + steg*ds;\n                        ux1 = upp-x;\n                        xl1 = x-low;\n                        ux2 = ux1.*ux1;\n                        xl2 = xl1.*xl1;\n                        uxinv1 = een./ux1;\n                        xlinv1 = een./xl1;\n                        plam = p0 + P'*lam ;\n                        qlam = q0 + Q'*lam ;\n                        gvec = P*uxinv1 + Q*xlinv1;\n                        dpsidx = plam./ux2 - qlam./xl2 ;\n                        rex = dpsidx - xsi + eta;\n                        rey = c + d.*y - mu - lam;\n                        rez = a0 - zet - a'*lam;\n                        relam = gvec - a*z - y + s - b;\n                        rexsi = xsi.*(x-alfa) - epsvecn;\n                        reeta = eta.*(beta-x) - epsvecn;\n                        remu = mu.*y - epsvecm;\n                        rezet = zet*z - epsi;\n                        res = lam.*s - epsvecm;\n                        residu1 = [rex' rey' rez]';\n                        residu2 = [relam' rexsi' reeta' remu' rezet res']';\n                        residu = [residu1' residu2']';\n                        resinew = sqrt(residu'*residu);\n                        steg = steg/2;\n                    end\n                    residunorm = resinew;\n                    residumax = max(abs(residu));\n                    steg = 2*steg;\n                end\n                if ittt > 198\n                    epsi;\n                    ittt;\n                end\n                epsi = 0.1*epsi;\n            end\n            xmma   =   x;\n            ymma   =   y;\n            zmma   =   z;\n            lamma =  lam;\n            xsimma =  xsi;\n            etamma =  eta;\n            mumma  =  mu;\n            zetmma =  zet;\n            smma   =   s;\n        end\n        \n        function [residu,residunorm,residumax] = ...\n                kktcheck(~,~,x,y,z,lam,xsi,eta,mu,zet,s, ...\n                xmin,xmax,df0dx,fval,dfdx,a0,a,c,d)\n            \n            rex   = df0dx + dfdx'*lam - xsi + eta;\n            rey   = c + d.*y - mu - lam;\n            rez   = a0 - zet - a'*lam;\n            relam = fval - a*z - y + s;\n            rexsi = xsi.*(x-xmin);\n            reeta = eta.*(xmax-x);\n            remu  = mu.*y;\n            rezet = zet*z;\n            res   = lam.*s;\n            %\n            residu1 = [rex' rey' rez]';\n            residu2 = [relam' rexsi' reeta' remu' rezet res']';\n            residu = [residu1' residu2']';\n            residunorm = sqrt(residu'*residu);\n            residumax = max(abs(residu));\n        end\n        \n    end\n    \n    methods\n        \n        function kkttol = get.kkttol(obj)\n            kkttol = obj.targetParameters.optimality_tol;\n        end\n        \n    end\nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Optimizers/OptimizerConstrained/Optimizer_MMA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5705787815454877}}
{"text": "function x = combin_eigen_right ( alpha, beta, n )\n\n%*****************************************************************************80\n%\n%% COMBIN_EIGEN_RIGHT returns the right eigenvectors of the COMBIN matrix.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 November 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real ALPHA, BETA, scalars that define A.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Output, real X(N,N), the right eigenvectors.\n%\n  x(1:n,1:n) = 0.0;\n\n  for j = 1 : n - 1\n    x(  1,j) = +1.0;\n    x(j+1,j) = -1.0;\n  end\n\n  j = n;\n  x(1:n,j) = 1.0;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/combin_eigen_right.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679955, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.5705598998968996}}
{"text": "function [mmHg] = psi2mmHg(psi)\n% Convert units of pressure from pounds per square inch to millimeters of mercury. \n% Chad Greene 2012\nmmHg = psi*51.7149;", "meta": {"author": "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/psi2mmHg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303384097947, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5705598963879289}}
{"text": "function out = tangentspace(A, B)\n\n% Get tangent space between A and B\n\n\nfor i = 1:size(A, 3)\n    out(:, :, i) = sqrtm(B) * logm(B ^ (-1 / 2) * A(:, :, i) * B ^ (-1 / 2)) * sqrtm(B);\nend\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_StarLab/HJKim/Riemannian/tangentspace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.570546028368102}}
{"text": "function [b a]=get_high_shelving_filter(g,Q,f,Fs)\n\nA=10^(g/40);\nw=2*pi*f/Fs;\nsn=sin(w);\ncs=cos(w);\nal=sn/(2*Q);\nbt=sqrt(A)/Q;\n\nb=A*[(A+1)+(A-1)*cs+bt*sn,...\n   -2*((A-1)+(A+1)*cs),...\n   (A+1)+(A-1)*cs-bt*sn];\n\n\n\na=[(A+1)-(A-1)*cs+bt*sn,...\n   2*((A-1)-(A+1)*cs),...\n   (A+1)-(A-1)*cs-bt*sn];\n\n\n\nb=b/a(1);\na=a/a(1);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34739-equalizer-audioplayer-gui/equalizer_matlab_cut/get_high_shelving_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5705116447281023}}
{"text": "function [Cbe_new, Ve_new, ecef_new]=strapdown_ecef_dcm(Cbe, Ve, ecef, a, w, dt)\n%Gravity (most time consuming part of ecef implementations)\nLlh=ecef2geo_v000(ecef,0);\n[Rn, Re, g, sL, cL, WIE_E]=geoparam_v000(Llh);\nCne=pos2Cne_v000(Llh(1), Llh(2));\nge=-Cne(:,3)*g;\n\n%Update attitude\nrot=w*dt;\nrot_norm=norm(rot);\nsr_a=1-(rot_norm^2/6)+(rot_norm^4/120);\nsr_b=(1/2)-(rot_norm^2/24)+(rot_norm^4/720);\nmx_a=eye(3)+sr_a*skew(rot)+sr_b*skew(rot)*skew(rot);\n\nrot=-([0;0;WIE_E])*dt;\nrot_norm=norm(rot);\nsr_a=1-(rot_norm^2/6)+(rot_norm^4/120);\nsr_b=(1/2)-(rot_norm^2/24)+(rot_norm^4/720);\nmx_b=eye(3)+sr_a*skew(rot)+sr_b*skew(rot)*skew(rot);\n\nCbe_new=mx_b*Cbe*mx_a;\n\n%%Update Velocity\n%Update Vel\nvel_inc1=Cbe*a*dt;\nvel_inc2=(-ge+2*cross(Ve,[0;0;WIE_E]))*dt;\nVe_new=Ve+vel_inc1+vel_inc2;\n\n%Update_pos\necef_new=ecef+Ve*dt;\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/strapdown_ecef_dcm_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5704671955043856}}
{"text": "function varargout = log10(varargin)\n%log10 (overloaded)\n\nvarargout{1} = log(varargin{1})/log(10);", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/@sdpvar/log10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.5704671837134729}}
{"text": "% TIMEF - Returns estimates and plots of mean event-related spectral\n%           perturbation (ERSP) and inter-trial coherence (ITC) changes \n%           across event-related trials (epochs) of a single input time series. \n%        * Uses either fixed-window, zero-padded FFTs (fastest), wavelet\n%           0-padded DFTs (both Hanning-tapered), OR multitaper spectra ('mtaper').\n%        * For the wavelet and FFT methods, output frequency spacing \n%           is the lowest frequency ('srate'/'winsize') divided by 'padratio'.\n%           NaN input values (such as returned by EVENTLOCK) are ignored.\n%        * If 'alpha' is given, then bootstrap statistics are computed \n%           (from a distribution of 'naccu' surrogate data trials) and \n%           non-significant features of the output plots are zeroed out \n%           (i.e., plotted in green). \n%        * Given a 'topovec' scalp map weights vector and an 'elocs' electrode \n%           location file or structure, the figure also shows a TOPOPLOT \n%           image of the specified scalp map.\n%\n%        * Note: Left-click on subplots to view and zoom in separate windows.\n% Usage: \n%        >> [ersp,itc,powbase,times,freqs,erspboot,itcboot,itcphase] = ...\n%                timef(data,frames,tlimits,srate,cycles,...\n%                                 'key1',value1,'key2',value2, ... );        \n% NOTE:                                        \n%        * For more detailed information about TIMEF, >> timef details  \n%        * Default values may differ when called from POP_TIMEF\n%\n% Required inputs:     \n%       data        = Single-channel data vector (1,frames*ntrials) (required)\n%       frames      = Frames per trial                     {def|[]: datalength}\n%       tlimits     = [mintime maxtime] (ms) Epoch time limits \n%                      {def|[]: from frames,srate}\n%       srate       = data sampling rate (Hz)                  {def:250}\n%       cycles      = If 0 -> Use FFTs (with constant window length) {0 = FFT}\n%                     If >0 -> Number of cycles in each analysis wavelet \n%                     If [wavecycles factor] -> wavelet cycles increase with \n%                     frequency  beginning at wavecyles (0<factor<1; factor=1 \n%                     -> no increase, standard wavelets; factor=0 -> fixed epoch \n%                     length, as in FFT.  Else, 'mtaper' -> multitaper decomp. \n%\n%    Optional Inter-Irial Coherence (ITC) type:\n%       'type'      = ['coher'|'phasecoher'] Compute either linear coherence \n%                      ('coher') or phase coherence ('phasecoher') also known\n%                      as the phase coupling factor           {'phasecoher'}.\n%    Optional detrending:\n%       'detret'    = ['on'|'off'], Detrend data in time.               {'off'}\n%       'detrep'    = ['on'|'off'], Detrend data across trials          {'off'}\n%\n%    Optional FFT/DFT parameters:\n%       'winsize'   = If cycles==0: data subwindow length (fastest, 2^n<frames);\n%                     If cycles >0: *longest* window length to use. This\n%                      determines the lowest output frequency       {~frames/8}\n%       'timesout'  = Number of output times (int<frames-winframes)       {200}\n%       'padratio'  = FFT-length/winframes (2^k)                            {2}\n%                      Multiplies the number of output frequencies by\n%                      dividing their spacing. When cycles==0, frequency\n%                      spacing is (low_freq/padratio).\n%       'maxfreq'   = Maximum frequency (Hz) to plot (& to output if cycles>0) \n%                      If cycles==0, all FFT frequencies are output.      {50}\n%       'baseline'  = Spectral baseline window center end-time (in ms).    {0}\n%       'powbase'   = Baseline spectrum (power, not dB) to normalize the data. \n%                      {def|NaN->from data}\n%\n%    Optional multitaper parameters:\n%       'mtaper'    = If [N W], performs multitaper decomposition. \n%                      (N is the time resolution and W the frequency resolution; \n%                      maximum taper number is 2NW-1). Overwrites 'winsize' and \n%                      'padratio'. \n%                     If [N W K], uses K Slepian tapers (if possible).\n%                      Phase is calculated using standard methods.\n%                      The use of mutitaper with wavelets (cycles>0) is not \n%                      recommended (as multiwavelets are not implemented). \n%                      Uses Matlab functions DPSS, PMTM.      {no multitaper}\n%\n%    Optional bootstrap parameters:\n%       'alpha'     = If non-0, compute two-tailed bootstrap significance prob. \n%                     level. Show non-signif. output values in green       {0}\n%       'naccu'     = Number of bootstrap replications to accumulate       {200}\n%       'baseboot'  = Bootstrap baseline to subtract (1 -> use 'baseline'(above)\n%                                                     0 -> use whole trial) {1}\n%    Optional scalp map:\n%       'topovec'   = Scalp topography (map) to plot                     {none}\n%       'elocs'     = Electrode location file for scalp map   \n%                     File should be ascii in format of  >> topoplot example   \n%                     May also be an EEG.chanlocs struct. \n%                     {default: file named in icadefs.m}\n%    Optional plotting parameters:\n%       'hzdir'     = ['up'|'down'] Direction of the frequency axes; reads default\n%                     from icadefs.m                                     {'up'}\n%       'plotersp'  = ['on'|'off'] Plot power spectral perturbations     {'on'} \n%       'plotitc'   = ['on'|'off'] Plot inter trial coherence            {'on'}\n%       'plotphase' = ['on'|'off'] Plot sign of the phase in the ITC panel, i.e.\n%                     green->red, pos.-phase ITC, green->blue, neg.-phase ITC {'on'}\n%       'erspmax'   = [real dB] set the ERSP max. for the scale (min= -max){auto}\n%       'itcmax'    = [real<=1] set the ITC maximum for the scale          {auto}\n%       'title'     = Optional figure title                                {none}\n%       'marktimes' = Non-0 times to mark with a dotted vertical line (ms) {none}\n%       'linewidth' = Line width for 'marktimes' traces (thick=2, thin=1)  {2}\n%       'pboot'     = Bootstrap power limits (e.g., from TIMEF)    {from data}\n%       'rboot'     = Bootstrap ITC limits (e.g., from TIMEF)      {from data}\n%       'axesfont'  = Axes text font size                                  {10}\n%       'titlefont' = Title text font size                                 {8}\n%       'vert'      = [times_vector] -> plot vertical dashed lines at given ms.\n%       'verbose'   = ['on'|'off'] print text                              {'on'}\n%\n%    Outputs: \n%            ersp   = Matrix (nfreqs,timesout) of log spectral diffs. from \n%                     baseline (in dB).  NB: Not masked for significance. \n%                     Must do this using erspboot\n%            itc    = Matrix of inter-trial coherencies (nfreqs,timesout) \n%                     (range: [0 1]) NB: Not masked for significance. \n%                     Must do this using itcboot\n%          powbase  = Baseline power spectrum (NOT in dB, used to norm. the ERSP)\n%            times  = Vector of output times (sub-window centers) (in ms)\n%            freqs  = Vector of frequency bin centers (in Hz)\n%         erspboot  = Matrix (2,nfreqs) of [lower;upper] ERSP significance diffs\n%          itcboot  = Matrix (2,nfreqs) of [lower;upper] ITC thresholds (not diffs)\n%          itcphase = Matrix (nfreqs,timesout) of ITC phase (in radians)\n%\n% Plot description:\n%   Assuming both 'plotersp' and 'plotitc' options are 'on' (= default). \n%   The upper panel presents the data ERSP (Event-Related Spectral Perturbation) \n%   in dB, with mean baseline spectral activity (in dB) subtracted. Use \n%   \"'baseline', NaN\" to prevent TIMEF from removing the baseline. \n%   The lower panel presents the data ITC (Inter-Trial Coherence). \n%   Click on any plot axes to pop up a new window (using 'AXCOPY')\n%   -- Upper left marginal panel presents the mean spectrum during the baseline \n%      period (blue), and when significance is set, the significance threshold \n%      at each frequency (dotted green-black trace).\n%   -- The marginal panel under the ERSP image shows the maximum (green) and \n%      minimum (blue) ERSP values relative to baseline power at each frequency.\n%   -- The lower left marginal panel shows mean ITC across the imaged time range \n%      (blue), and when significance is set, the significance threshold (dotted \n%      green-black).  \n%   -- The marginal panel under the ITC image shows the ERP (which is produced by \n%      ITC across the data spectral pass band).\n%\n% Author: Sigurd Enghoff, Arnaud Delorme & Scott Makeig\n%          CNL / Salk Institute 1998- | SCCN/INC, UCSD 2002-\n%\n% Known problems:\n%   Significance masking currently fails for linear coherence.\n%\n% See also: CROSSF\n \n% Copyright (C) 1998 Sigurd Enghoff, Scott Makeig, Arnaud Delorme, \n% CNL / Salk Institute 8/1/98-8/28/01\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% 10-19-98 avoided division by zero (using MIN_ABS) -sm\n% 10-19-98 improved usage message and commandline info printing -sm\n% 10-19-98 made valid [] values for tvec and g.elocs -sm\n% 04-01-99 added missing freq in freqs and plots, fixed log scaling bug -se & -tpj\n% 06-29-99 fixed frequency indexing for constant-Q -se\n% 08-24-99 reworked to handle NaN input values -sm\n% 12-07-99 adjusted ERPtimes to plot ERP under ITC -sm\n% 12-22-99 debugged ERPtimes, added BASE_BOOT -sm \n% 01-10-00 debugged BASE_BOOT=0 -sm\n% 02-28-00 added NOTE on formula derivation below -sm\n% 03-16-00 added AXCOPY feature -sm & tpj\n% 04-16-00 added multiple marktimes loop -sm\n% 04-20-00 fixed ITC cbar limits when specified in input -sm\n% 07-29-00 changed frequencies displayed msg -sm\n% 10-12-00 fixed bug in freqs when cycles>0 -sm\n% 02-07-01 fixed inconsistency in BASE_BOOT use -sm\n% 08-28-01 matlab 'key' value arguments -ad\n% 08-28-01 multitaper decomposition -ad\n% 01-25-02 reformated help & license -ad \n% 03-08-02 debug & compare to old timef function -ad \n% 03-16-02 timeout automatically adjusted if too high -ad \n% 04-02-02 added 'coher' option -ad \n\nfunction [P,R,mbase,times,freqs,Pboot,Rboot,Rphase,PA] = timef(X,frames,tlimits,Fs,varwin,varargin);\n\n% Note: undocumented arg PA is output of 'phsamp','on' \n\n%varwin,winsize,g.timesout,g.padratio,g.maxfreq,g.topovec,g.elocs,g.alpha,g.marktimes,g.powbase,g.pboot,g.rboot)\n\n% ITC:   Normally, R = |Sum(Pxy)| / (Sum(|Pxx|)*Sum(|Pyy|)) is linear coherence.\n%        But here, we consider:  Phase(Pyy) = 0 and |Pyy| = 1 -> Pxy = Pxx\n%        Giving, R = |Sum(Pxx)|/Sum(|Pxx|), the inter-trial coherence (ITC)\n%        Also called 'phase-locking factor' by Tallon-Baudry et al. (1996),\n%        the ITC is the phase coherence between the data time series and the\n%        time-locking event time series.\n\n% Read system-wide / dir-wide constants: \nicadefs\n\n% Constants set here:\nERSP_CAXIS_LIMIT = 0;           % 0 -> use data limits; else positive value\n                                % giving symmetric +/- caxis limits.\nITC_CAXIS_LIMIT  = 0;           % 0 -> use data limits; else positive value\n                                % giving symmetric +/- caxis limits.\n\n% Commandline arg defaults:\nDEFAULT_EPOCH\t= NaN;\t\t% Frames per trial\nDEFAULT_TIMLIM  = NaN;\t                % Time range of g.frames (ms)\nDEFAULT_FS\t= 250;\t\t\t% Sampling frequency (Hz)\nDEFAULT_NWIN\t= 200;\t\t\t% Number of windows = horizontal resolution\nDEFAULT_VARWIN\t= 0;\t\t\t% Fixed window length or fixed number of cycles.\n\t\t\t\t% =0: fix window length to that determined by nwin\n\t\t\t\t% >0: set window length equal to varwin cycles\n\t\t\t\t%     Bounded above by winsize, which determines\n\t\t\t\t%     the min. freq. to be computed.\nDEFAULT_OVERSMP\t= 2;\t\t\t% Number of times to oversample frequencies \nDEFAULT_MAXFREQ = 50;\t\t\t% Maximum frequency to display (Hz)\nDEFAULT_TITLE\t= '';\t\t\t% Figure title\nDEFAULT_ELOC    = 'chan.locs';\t% Channel location file\nDEFAULT_ALPHA   = NaN;\t\t\t% Percentile of bins to keep\nDEFAULT_MARKTIME= NaN;\n\n% Font sizes:\nAXES_FONT       = 10;           % axes text FontSize\nTITLE_FONT      = 8;\n\nif nargout>7\n   Rphase = []; % initialize in case Rphase asked for, but ITC not computed\nend\n\nif (nargin < 1)\n\thelp timef\n\treturn\nend\n\nif ischar(X) && strcmp(X,'details')\n   more on\n   help timefdetails\n   more off\n   return\nend\n\nif (min(size(X))~=1 || length(X)<2)\n\terror('Data must be a row or column vector.');\nend\n\nif nargin < 2 || isempty(frames) || isnan(frames) \n\tframes = DEFAULT_EPOCH;\nelseif (~isnumeric(frames) || length(frames)~=1 || frames~=round(frames))\n\terror('Value of frames must be an integer.');\nelseif (frames <= 0)\n\terror('Value of frames must be positive.');\nelseif (rem(length(X),frames) ~= 0)\n\terror('Length of data vector must be divisible by frames.');\nend\nif isnan(frames) || isempty(frames)\n    frames = length(X);\nend\n\nif nargin < 3 || isempty(tlimits) || isnan(tlimits(1)) \n\ttlimits = DEFAULT_TIMLIM;\nelseif (~isnumeric(tlimits) || sum(size(tlimits))~=3)\n\terror('Value of tlimits must be a vector containing two numbers.');\nelseif (tlimits(1) >= tlimits(2))\n\terror('tlimits interval must be ascending.');\nend\n\nif (nargin < 4)\n\tFs = DEFAULT_FS;\nelseif (~isnumeric(Fs) || length(Fs)~=1)\n\terror('Value of srate must be a number.');\nelseif (Fs <= 0)\n\terror('Value of srate must be positive.');\nend\n\nif isempty(tlimits) || isnan(tlimits(1))\n   hlim = 1000*frames/Fs;  % fit default tlimits to srate and frames\n   tlimits = [0 hlim];\nend\n\nframesdiff = frames - Fs*(tlimits(2)-tlimits(1))/1000;\nif abs(framesdiff) > 1\n        error('Given time limits, frames and sampling rate are incompatible');\nelseif framesdiff ~= 0\n   \ttlimits(1) = tlimits(1) - 0.5*framesdiff*1000/Fs;\n   \ttlimits(2) = tlimits(2) + 0.5*framesdiff*1000/Fs;\n    \tfprintf('Adjusted time limits slightly, to [%.1f,%.1f] ms, to match frames and srate.\\n',tlimits(1),tlimits(2));\nend\n\nif (nargin < 5)\n\tvarwin = DEFAULT_VARWIN;\nelseif (~isnumeric(varwin) || length(varwin)>2)\n\terror('Value of cycles must be a number.');\nelseif (varwin < 0)\n\terror('Value of cycles must be zero or positive.');\nend\n\n% consider structure for these arguments\n% --------------------------------------\nif ~isempty(varargin)\n    try, g = struct(varargin{:}); \n    catch, error('Argument error in the {''param'', value} sequence'); end; \nend\ng.tlimits = tlimits;\ng.frames   = frames;\ng.srate   = Fs;\ng.cycles  = varwin(1);\nif length(varwin)>1\n\tg.cyclesfact = varwin(2);\nelse \n\tg.cyclesfact = 1;\nend\n\ntry, g.title;      catch, g.title = DEFAULT_TITLE; end\ntry, g.winsize;    catch, g.winsize = max(pow2(nextpow2(g.frames)-3),4); end\ntry, g.pad;        catch, g.pad = max(pow2(nextpow2(g.winsize)),4); end\ntry, g.timesout;   catch, g.timesout = DEFAULT_NWIN; end\ntry, g.padratio;   catch, g.padratio = DEFAULT_OVERSMP; end\ntry, g.maxfreq;    catch, g.maxfreq = DEFAULT_MAXFREQ; end\ntry, g.topovec;    catch, g.topovec = []; end\ntry, g.elocs;      catch, g.elocs = DEFAULT_ELOC; end\ntry, g.alpha;      catch, g.alpha = DEFAULT_ALPHA; end;  \ntry, g.marktimes;  catch, g.marktimes = DEFAULT_MARKTIME; end\ntry, g.powbase;    catch, g.powbase = NaN; end\ntry, g.pboot;      catch, g.pboot = NaN; end\ntry, g.rboot;      catch, g.rboot = NaN; end\ntry, g.plotersp;   catch, g.plotersp = 'on'; end\ntry, g.plotitc;    catch, g.plotitc  = 'on'; end\ntry, g.detrep;     catch, g.detrep = 'off'; end\ntry, g.detret;     catch, g.detret = 'off'; end\ntry, g.baseline;   catch, g.baseline = 0; end\ntry, g.baseboot;   catch, g.baseboot = 1; end\ntry, g.linewidth;  catch, g.linewidth = 2; end\ntry, g.naccu;      catch, g.naccu = 200; end\ntry, g.mtaper;     catch, g.mtaper = []; end\ntry, g.vert;       catch, g.vert = []; end\ntry, g.type;       catch, g.type = 'phasecoher'; end\ntry, g.phsamp;     catch, g.phsamp = 'off'; end\ntry, g.plotphase;  catch, g.plotphase = 'on'; end\ntry, g.itcmax;     catch, g.itcmax = []; end\ntry, g.erspmax;    catch, g.erspmax = []; end\ntry, g.verbose;    catch, g.verbose = 'on'; end\ntry, g.chaninfo;   catch, g.chaninfo = []; end\ntry, g.hzdir;      catch, g.hzdir = HZDIR; end; % default from icadefs\nlasterr('');\n\n% testing arguments consistency\n% -----------------------------\nif strcmp(g.hzdir,'up')\n    g.hzdir = 'normal';\nelseif strcmp(g.hzdir,'down')\n    g.hzdir = 'reverse';\nelse\n    error('unknown ''hzdir'' value - not ''up'' or ''down''');\nend\n\nswitch lower(g.verbose)\n    case { 'on', 'off' }, ;\n    otherwise error('verbose must be either on or off');\nend\nif (~ischar(g.title))\n\terror('Title must be a string.');\nend\n\nif (~isnumeric(g.winsize) || length(g.winsize)~=1 || g.winsize~=round(g.winsize))\n\terror('Value of winsize must be an integer number.');\nelseif (g.winsize <= 0)\n\terror('Value of winsize must be positive.');\nelseif (g.cycles == 0 && pow2(nextpow2(g.winsize)) ~= g.winsize)\n\terror('Value of winsize must be an integer power of two [1,2,4,8,16,...]');\nelseif (g.winsize > g.frames)\n\terror('Value of winsize must be less than frames per epoch.');\nend\n\nif (~isnumeric(g.timesout) || length(g.timesout)~=1 || g.timesout~=round(g.timesout))\n\terror('Value of timesout must be an integer number.');\nelseif (g.timesout <= 0)\n\terror('Value of timesout must be positive.');\nend\nif (g.timesout > g.frames-g.winsize)\n\tg.timesout = g.frames-g.winsize;\n\tdisp(['Value of timesout must be <= frames-winsize, timeout adjusted to ' int2str(g.timesout) ]);\nend\n\nif (~isnumeric(g.padratio) || length(g.padratio)~=1 || g.padratio~=round(g.padratio))\n\terror('Value of padratio must be an integer.');\nelseif (g.padratio <= 0)\n\terror('Value of padratio must be positive.');\nelseif (pow2(nextpow2(g.padratio)) ~= g.padratio)\n\terror('Value of padratio must be an integer power of two [1,2,4,8,16,...]');\nend\n\nif (~isnumeric(g.maxfreq) || length(g.maxfreq)~=1)\n\terror('Value of maxfreq must be a number.');\nelseif (g.maxfreq <= 0)\n\terror('Value of maxfreq must be positive.');\nelseif (g.maxfreq > Fs/2)\n\tmyprintf(g.verbose,['Warning: value of maxfreq reduced to Nyquist rate' ...\n\t\t ' (%3.2f)\\n\\n'], Fs/2);\n\tg.maxfreq = Fs/2;\nend\n\nif isempty(g.topovec)\n\tg.topovec = [];\n\tif isempty(g.elocs)\n\t\terror('Channel location file must be specified.');\n\tend\nend\nif isempty(g.elocs)\n\tg.elocs = DEFAULT_ELOC;\nelseif (~ischar(g.elocs)) && ~isstruct(g.elocs)\n\terror('Channel location file must be a valid text file.');\nend\n\nif (~isnumeric(g.alpha) || length(g.alpha)~=1)\n\terror('timef(): Value of g.alpha must be a number.\\n');\nelseif (round(g.naccu*g.alpha) < 2)\n\tmyprintf(g.verbose,'Value of g.alpha is out of the normal range [%g,0.5]\\n',2/g.naccu);\n    g.naccu = round(2/g.alpha);\n\tmyprintf(g.verbose,'  Increasing the number of bootstrap iterations to %d\\n',g.naccu);\nend\nif g.alpha>0.5 || g.alpha<=0\n    error('Value of g.alpha is out of the allowed range (0.00,0.5).');\nend\nif ~isnan(g.alpha)\n   if g.baseboot > 0\n     myprintf(g.verbose,'Bootstrap analysis will use data in baseline (pre-0 centered) subwindows only.\\n')\n   else\n     myprintf(g.verbose,'Bootstrap analysis will use data in all subwindows.\\n')\n   end\nend\nif ~isnumeric(g.vert)\n    error('vertical line(s) option must be a vector');\nelse\n\tif ~isempty(g.vert)\n        if min(g.vert(:)) < g.tlimits(1) || max(g.vert(:)) > g.tlimits(2)\n            error('vertical line(s) time out-of-bound');\n        end\n\tend\nend\n\nif ~isnan (g.rboot)\n  if size(g.rboot) == [1,1]\n    if g.cycles == 0\n        g.rboot = g.rboot*ones(g.winsize*g.padratio/2);\n    end\n  end\nend\n\nif ~isempty(g.mtaper) % mutitaper, inspired from Bijan Pesaran matlab function\n  if length(g.mtaper) < 3\n        %error('mtaper argument must be [N W] or [N W K]');\n    \n    if g.mtaper(1) * g.mtaper(2) < 1\n        error('mtaper 2 first arguments'' product must be higher than 1');\n    end\n    if length(g.mtaper) == 2\n        g.mtaper(3) = floor( 2*g.mtaper(2)*g.mtaper(1) - 1);\n    end\n    if length(g.mtaper) == 3\n        if g.mtaper(3) > 2 * g.mtaper(1) * g.mtaper(2) -1\n            error('mtaper number too high (maximum (2*N*W-1))');\n        end\n    end\n    disp(['Using ' num2str(g.mtaper(3)) ' tapers.']);\n    NW = g.mtaper(1)*g.mtaper(2);   % product NW\n    N  = g.mtaper(1)*g.srate;     \n    [e,v] = dpss(N, NW, 'calc');\n    e=e(:,1:g.mtaper(3));\n    g.alltapers = e;\n  else    \n    g.alltapers = g.mtaper;\n    disp('mtaper argument not [N W] or [N W K]; considering raw taper matrix');\n  end\n\n  g.winsize = size(g.alltapers, 1);\n  g.pad = max(pow2(nextpow2(g.winsize)),256); % pad*nextpow\n\n  %nfk = floor([0 g.maxfreq]./g.srate.*g.pad); % not used any more\n  %g.padratio = 2*nfk(2)/g.winsize;\n\n  g.padratio = g.pad/g.winsize;\n \n  %compute number of frequencies\n  %nf = max(256, g.pad*2^nextpow2(g.winsize+1)); \n  %nfk = floor([0 g.maxfreq]./g.srate.*nf);\n  %freqs = linspace( 0, g.maxfreq, diff(nfk)); % this also work in the case of a FFT\n  \nend;           \n\nswitch lower(g.plotphase)\n    case { 'on', 'off' }, ;\n    otherwise error('plotphase must be either on or off');\nend\nswitch lower(g.plotersp)\n    case { 'on', 'off' }, ;\n    otherwise error('plotersp must be either on or off');\nend\nswitch lower(g.plotitc)\n    case { 'on', 'off' }, ;\n    otherwise error('plotitc must be either on or off');\nend\nswitch lower(g.detrep)\n    case { 'on', 'off' }, ;\n    otherwise error('detrep must be either on or off');\nend\nswitch lower(g.detret)\n    case { 'on', 'off' }, ;\n    otherwise error('detret must be either on or off');\nend\nswitch lower(g.phsamp)\n    case { 'on', 'off' }, ;\n    otherwise error('phsamp must be either on or off');\nend\nif ~isnumeric(g.linewidth)\n    error('linewidth must be numeric');\nend\nif ~isnumeric(g.naccu)\n    error('naccu must be numeric');\nend\nif ~isnumeric(g.baseline)\n    error('baseline must be numeric');\nend\nswitch g.baseboot\n    case {0,1}, ;\n    otherwise, error('baseboot must be 0 or 1');\nend\nswitch g.type\n    case { 'coher', 'phasecoher', 'phasecoher2' },;\n    otherwise error('Type must be either ''coher'' or ''phasecoher''');\nend;    \nif isnan(g.baseline)\n    g.unitpower = 'uV/Hz';\nelse\n    g.unitpower = 'dB';\nend\n\nif (g.cycles == 0) %%%%%%%%%%%%%% constant window-length FFTs %%%%%%%%%%%%%%%%\n    freqs = linspace(0, g.srate/2, g.padratio*g.winsize/2+1);\n    freqs = freqs(2:end);\n    win = hanning(g.winsize);\n\n    P  = zeros(g.padratio*g.winsize/2,g.timesout); % summed power\n    PP = zeros(g.padratio*g.winsize/2,g.timesout); % power\n    R  = zeros(g.padratio*g.winsize/2,g.timesout); % mean coherence\n    RR = zeros(g.padratio*g.winsize/2,g.timesout); % (coherence)\n    Pboot = zeros(g.padratio*g.winsize/2,g.naccu); % summed bootstrap power\n    Rboot = zeros(g.padratio*g.winsize/2,g.naccu); % summed bootstrap coher\n    Rn = zeros(1,g.timesout);\n    Rbn = 0;\n\n\tswitch g.type\n\t    case { 'coher' 'phasecoher2' },\n           cumulX = zeros(g.padratio*g.winsize/2,g.timesout);\n           cumulXboot = zeros(g.padratio*g.winsize/2,g.naccu);\n        case 'phasecoher'\n           switch g.phsamp\n             case 'on'\n               cumulX = zeros(g.padratio*g.winsize/2,g.timesout);\n           end\n    end;        \n\nelse % %%%%%%%%%%%%%%%%%% cycles>0, Constant-Q (wavelet) DFTs %%%%%%%%%%%%%%%%%%%%\n\n    freqs = g.srate*g.cycles/g.winsize*[2:2/g.padratio:g.winsize]/2;\n    dispf = find(freqs <= g.maxfreq);\n    freqs = freqs(dispf);\n\n    win = dftfilt(g.winsize,g.maxfreq/g.srate,g.cycles,g.padratio,g.cyclesfact);\n    P = zeros(size(win,2),g.timesout);       % summed power\n    R = zeros(size(win,2),g.timesout);       % mean coherence\n    PP = repmat(NaN,size(win,2),g.timesout); % initialize with NaN\n    RR = repmat(NaN,size(win,2),g.timesout); % initialize with NaN\n    Pboot = zeros(size(win,2),g.naccu);  % summed bootstrap power\n    Rboot = zeros(size(win,2),g.naccu);  % summed bootstrap coher\n    Rn = zeros(1,g.timesout);\n    Rbn = 0;\n\n\tswitch g.type\n\t  case { 'coher' 'phasecoher2' },\n           cumulX = zeros(size(win,2),g.timesout);\n           cumulXboot = zeros(size(win,2),g.naccu);\n      case 'phasecoher'\n           switch g.phsamp\n             case 'on'\n               cumulX = zeros(size(win,2),g.timesout);\n           end\n   end;        \nend\n\nswitch g.phsamp\n  case 'on'\n    PA = zeros(size(P,1),size(P,1),g.timesout); % NB: (freqs,freqs,times)\nend                                             %       phs   amp\n\nwintime = 1000/g.srate*(g.winsize/2); % (1000/g.srate)*(g.winsize/2);\ntimes = [g.tlimits(1)+wintime:(g.tlimits(2)-g.tlimits(1)-2*wintime)/(g.timesout-1):g.tlimits(2)-wintime];\nERPtimes = [g.tlimits(1):(g.tlimits(2)-g.tlimits(1))/(g.frames-1):g.tlimits(2)+0.000001];\nERPindices = [];\nfor ti=times\n [tmp indx] = min(abs(ERPtimes-ti));\n ERPindices  = [ERPindices indx];\nend\nERPtimes = ERPtimes(ERPindices); % subset of ERP frames on t/f window centers\n\nif ~isempty(find(times < g.baseline))\n   baseln = find(times < g.baseline); % subtract means of pre-0 (centered) windows\nelse\n   baseln = 1:length(times); % use all times as baseline\nend\nif ~isnan(g.alpha) && length(baseln)==0\n  myprintf(g.verbose,'timef(): no window centers in baseline (times<%g) - shorten (max) window length.\\n', g.baseline)\n  return\nelseif ~isnan(g.alpha) && g.baseboot\n  myprintf(g.verbose,'   %d bootstrap windows in baseline (center times < %g).\\n',...\n          length(baseln), g.baseline)\nend\ndispf = find(freqs <= g.maxfreq);\nstp = (g.frames-g.winsize)/(g.timesout-1);\n\nmyprintf(g.verbose,'Computing Event-Related Spectral Perturbation (ERSP) and\\n');\nswitch g.type\n    case 'phasecoher',  myprintf(g.verbose,'  Inter-Trial Phase Coherence (ITC) images based on %d trials\\n',length(X)/g.frames);\n    case 'phasecoher2', myprintf(g.verbose,'  Inter-Trial Phase Coherence 2 (ITC) images based on %d trials\\n',length(X)/g.frames);\n    case 'coher',       myprintf(g.verbose,'  Linear Inter-Trial Coherence (ITC) images based on %d trials\\n',length(X)/g.frames);\nend\nmyprintf(g.verbose,'  of %d frames sampled at %g Hz.\\n',g.frames,g.srate);\nmyprintf(g.verbose,'Each trial contains samples from %d ms before to\\n',g.tlimits(1));\nmyprintf(g.verbose,'  %.0f ms after the timelocking event.\\n',g.tlimits(2));\nmyprintf(g.verbose,'The window size used is %d samples (%g ms) wide.\\n',g.winsize,2*wintime);\nmyprintf(g.verbose,'The window is applied %d times at an average step\\n',g.timesout);\nmyprintf(g.verbose,'  size of %g samples (%g ms).\\n',stp,1000*stp/g.srate);\nmyprintf(g.verbose,'Results are oversampled %d times; the %d frequencies\\n',g.padratio,length(dispf));\nmyprintf(g.verbose,'  displayed are from %2.1f Hz to %3.1f Hz.\\n',freqs(dispf(1)),freqs(dispf(end)));\nif ~isnan(g.alpha)\n  myprintf(g.verbose,'Only significant values (bootstrap p<%g) will be colored;\\n',g.alpha) \n  myprintf(g.verbose,'  non-significant values will be plotted in green\\n');\nend\n\ntrials = length(X)/g.frames;\nbaselength = length(baseln);\nmyprintf(g.verbose,'\\nOf %d trials total, processing trial:',trials);\n\n% detrend over epochs (trials) if requested\n% -----------------------------------------\nswitch g.detrep\n    case 'on'\n        X = reshape(X, g.frames, length(X)/g.frames);\n        X = X - mean(X,2)*ones(1, length(X(:))/g.frames);\n        X = X(:)';\nend;        \n\nfor i=1:trials\n    if (rem(i,100)==0)\n        myprintf(g.verbose,'\\n');\n    end\n\tif (rem(i,10) == 0)\n\t\tmyprintf(g.verbose,'%d',i);\n\telseif (rem(i,2) == 0)\n\t\tmyprintf(g.verbose,'.');\n\tend\n\n    ERP = blockave(X,g.frames); % compute the ERP trial average\n\n    Wn = zeros(1,g.timesout);\n\tfor j=1:g.timesout,\n\t\ttmpX = X([1:g.winsize]+floor((j-1)*stp)+(i-1)*g.frames); \n                                                      % pull out data g.frames\n\t\ttmpX = tmpX - mean(tmpX); % remove the mean for that window\n        switch g.detret, case 'on', tmpX = detrend(tmpX); end\n\t\tif ~any(isnan(tmpX))\n\t\t  if (g.cycles == 0) % FFT\n            if ~isempty(g.mtaper)   % apply multitaper (no hanning window)\n                tmpXMT = fft(g.alltapers .* ...\n                             (tmpX(:) * ones(1,size(g.alltapers,2))), g.pad);\n\t\t\t    %tmpXMT = tmpXMT(nfk(1)+1:nfk(2),:);\n\t\t\t    tmpXMT = tmpXMT(2:g.padratio*g.winsize/2+1,:);\n                PP(:,j) = mean(abs(tmpXMT).^2, 2); \n                  % power; can also ponderate multitaper by their eigenvalues v\n\t\t        tmpX = win .* tmpX(:);\n               \ttmpX = fft(tmpX, g.pad);\n    \t\t    tmpX = tmpX(2:g.padratio*g.winsize/2+1);\n            else\n               % TF and MC (12/2006): Calculation changes made so that\n                % power can be correctly calculated from ERSP.\n\t\t        tmpX = win .* tmpX(:);     \n               \ttmpX = fft(tmpX,g.padratio*g.winsize);\n                tmpX = tmpX / g.winsize;    % TF and MC (12/11/2006): normalization, divide by g.winsize\n    \t\t    tmpX = tmpX(2:g.padratio*g.winsize/2+1);\n                PP(:,j) = 2/0.375*abs(tmpX).^2; % power\n                % TF and MC (12/14/2006): multiply by 2 account for negative frequencies,\n                % Counteract the reduction by a factor 0.375 \n                % that occurs as a result of cosine (Hann) tapering. Refer to Bug 446\n            end;    \n          else % wavelet\n            if ~isempty(g.mtaper)  % apply multitaper\n\t\t\t    tmpXMT = g.alltapers .* (tmpX(:) * ones(1,size(g.alltapers,2)));\n\t\t\t    tmpXMT = transpose(win) * tmpXMT;\n                PP(:,j) = mean(abs(tmpXMT).^2, 2); % power\n\t\t        tmpX = transpose(win) * tmpX(:);\n            else\n\t\t        tmpX = transpose(win) * tmpX(:); \n                PP(:,j) = abs(tmpX).^2; % power\n            end    \n          end\n\t\t\n          if abs(tmpX) < eps    % If less than smallest possible machine value \n                                % (i.e. if it's zero) then call it 0.\n\t\t        RR(:,j) = zeros(size(RR(:,j)));\n          else\n\t\t      switch g.type\n\t\t        case { 'coher' },\n\t\t          RR(:,j) = tmpX; \n                  cumulX(:,j) = cumulX(:,j)+abs(tmpX).^2;\n\t\t        case { 'phasecoher2' },\n\t\t          RR(:,j) = tmpX; \n                  cumulX(:,j) = cumulX(:,j)+abs(tmpX);\n\t\t        case 'phasecoher',\n\t\t          RR(:,j) = tmpX ./ abs(tmpX); % normalized cross-spectral vector\n         \t\t  switch g.phsamp\n             \t\t  case 'on'\n                \t    cumulX(:,j) = cumulX(:,j)+abs(tmpX); % accumulate for PA\n          \t\t  end\n              end\n         end\n          Wn(j) = 1;\n        end\n\n        switch g.phsamp\n         case 'on' % PA (freq x freq x time)\n          PA(:,:,j) = PA(:,:,j)  + (tmpX ./ abs(tmpX)) * ((PP(:,j)))';\n                                           % cross-product: unit phase (column)\n                                           %                times amplitude (row)\n        end\n\tend % window\n\n\tif ~isnan(g.alpha) % save surrogate data for bootstrap analysis\n        j = 1;\n        goodbasewins = find(Wn==1);\n        if g.baseboot % use baseline windows only\n          goodbasewins = find(goodbasewins<=baselength); \n        end\n        ngdbasewins = length(goodbasewins);\n        if ngdbasewins>1\n\t\t  while j <= g.naccu\n            i=ceil(rand*ngdbasewins);\n            i=goodbasewins(i);\n\t\t\tPboot(:,j) = Pboot(:,j) + PP(:,i);\n\t\t    Rboot(:,j) = Rboot(:,j) + RR(:,i);\n\t\t    switch g.type\n\t\t        case 'coher',       cumulXboot(:,j) = cumulXboot(:,j)+abs(tmpX).^2;\n\t\t        case 'phasecoher2', cumulXboot(:,j) = cumulXboot(:,j)+abs(tmpX);\n            end\n            j = j+1;\n          end\n          Rbn = Rbn + 1;\n\t    end\n\tend % bootstrap\n\t\n    Wn = find(Wn>0);\n    if length(Wn)>0\n\t  P(:,Wn) = P(:,Wn) + PP(:,Wn); % add non-NaN windows\n\t  R(:,Wn) = R(:,Wn) + RR(:,Wn);\n\t  Rn(Wn) = Rn(Wn) + ones(1,length(Wn)); % count number of addends\n    end\nend % trial\n\n% if coherence, perform the division\n% ----------------------------------\nswitch g.type\n case 'coher',\n  R = R ./ ( sqrt( trials*cumulX ) );\n  if ~isnan(g.alpha)\n\t  Rboot = Rboot ./ ( sqrt( trials*cumulXboot ) );\n  end\n case 'phasecoher2',\n  R = R ./ ( cumulX );\n  if ~isnan(g.alpha)\n\t  Rboot = Rboot ./ cumulXboot;\n  end;   \n case 'phasecoher',\n  R = R ./ (ones(size(R,1),1)*Rn);\nend;        \n\nswitch g.phsamp\n case 'on'\n  tmpcx(1,:,:) = cumulX; % allow ./ below\n  for j=1:g.timesout\n    PA(:,:,j) = PA(:,:,j) ./ repmat(PP(:,j)', [size(PP,1) 1]);\n  end\nend\n\nif min(Rn) < 1\n  myprintf(g.verbose,'timef(): No valid timef estimates for windows %s of %d.\\n',...\n                         int2str(find(Rn==0)),length(Rn));\n  Rn(find(Rn<1))==1;\n  return\nend\nP = P ./ (ones(size(P,1),1) * Rn);\n\nif isnan(g.powbase)\n  myprintf(g.verbose,'\\nComputing the mean baseline spectrum\\n');\n  mbase = mean(P(:,baseln),2)';\nelse\n  myprintf(g.verbose,'Using the input baseline spectrum\\n');\n  mbase = g.powbase;\nend\nif ~isnan( g.baseline(1) ) && ~isnan( mbase(1) )\n    P = 10 * (log10(P) - repmat(log10(mbase(1:size(P,1)))',[1 g.timesout])); % convert to (10log10) dB\nelse\n    P = 10 * log10(P);\nend\n\nRsign = sign(imag(R));\nif nargout > 7\n   for lp = 1:size(R,1)\n       Rphase(lp,:) = rem(angle(R(lp,:)),2*pi); % replaced obsolete phase() -sm 2/1/6\n   end\n   Rphase(find(Rphase>pi))  = 2*pi-Rphase(find(Rphase>pi));\n   Rphase(find(Rphase<-pi)) = -2*pi-Rphase(find(Rphase<-pi));\nend\n\nR = abs(R); % convert coherence vector to magnitude\n\nif ~isnan(g.alpha) % if bootstrap analysis included . . .\n    if Rbn>0\n\t   i = round(g.naccu*g.alpha);\n       if isnan(g.pboot)\n            Pboot = Pboot / Rbn; % normalize\n            if ~isnan( g.baseline ) \n\t            Pboot = 10 * (log10(Pboot) - repmat(log10(mbase)',[1 g.naccu]));\n            else\n                Pboot = 10 * log10(Pboot);\n            end;  \n            Pboot = sort(Pboot');\n\t        Pboot = [mean(Pboot(1:i,:)) ; mean(Pboot(g.naccu-i+1:g.naccu,:))];\n       else\n            Pboot = g.pboot;\n       end\n  \n      if isnan(g.rboot)\n\t       Rboot = abs(Rboot) / Rbn;\n\t       Rboot = sort(Rboot');\n\t       Rboot = mean(Rboot(g.naccu-i+1:g.naccu,:));\n      else\n           Rboot = g.rboot;\n      end\n    else\n      myprintf(g.verbose,'No valid bootstrap trials...!\\n');\n    end\nend\n\nswitch lower(g.plotitc)\n   case 'on',  \n       switch lower(g.plotersp), \n          case 'on', ordinate1 = 0.67; ordinate2 = 0.1; height = 0.33; g.plot = 1;\n          case 'off', ordinate2 = 0.1; height = 0.9; g.plot = 1;\n       end;     \n   case 'off', ordinate1 = 0.1; height = 0.9; \n       switch lower(g.plotersp), \n          case 'on', ordinate1 = 0.1; height = 0.9;  g.plot = 1;\n          case 'off', g.plot = 0;\n       end;     \nend;    \n\nif g.plot\n    myprintf(g.verbose,'\\nNow plotting...\\n');\n    set(gcf,'DefaultAxesFontSize',AXES_FONT)\n    colormap(jet(256));\n    pos = get(gca,'position');\n    q = [pos(1) pos(2) 0 0];\n    s = [pos(3) pos(4) pos(3) pos(4)];\nend\n\nswitch lower(g.plotersp)\n case 'on' \n    %\n    %%%%%%% image the ERSP %%%%%%%%%%%%%%%%%%%%%%%%%%\n    %\n\th(1) = subplot('Position',[.1 ordinate1 .9 height].*s+q);\n\t\n\tPP = P;            % PP will be ERSP power after\n\tif ~isnan(g.alpha) % zero out nonsignif. power differences\n\t\tPP(find((PP > repmat(Pboot(1,:)',[1 g.timesout])) ...\n                    & (PP < repmat(Pboot(2,:)',[1 g.timesout])))) = 0;\n\tend\n\n    if ERSP_CAXIS_LIMIT == 0\n\t   ersp_caxis = [-1 1]*1.1*max(max(abs(P(dispf,:))));\n    else\n       ersp_caxis = ERSP_CAXIS_LIMIT*[-1 1];\n    end\n\n    if ~isnan( g.baseline ) \n        imagesc(times,freqs(dispf),PP(dispf,:),ersp_caxis); \n    else\n        imagesc(times,freqs(dispf),PP(dispf,:));\n    end\n    set(gca,'ydir',g.hzdir);  % make frequency ascend or descend\n\tif ~isempty(g.erspmax)\n\t\tcaxis([-g.erspmax g.erspmax]);\n\tend\n    \n\thold on\n\tplot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth); % plot time 0\n    if ~isnan(g.marktimes) % plot marked time\n     for mt = g.marktimes(:)'\n\t   plot([mt mt],[0 freqs(max(dispf))],'--k','LineWidth',g.linewidth);\n     end\n    end\n\thold off\n\tset(h(1),'YTickLabel',[],'YTick',[])\n\tset(h(1),'XTickLabel',[],'XTick',[])\n\tif ~isempty(g.vert)\n\t\tfor index = 1:length(g.vert)\n\t\t\tline([g.vert(index), g.vert(index)], [min(freqs(dispf)) max(freqs(dispf))], 'linewidth', 1, 'color', 'm');\n\t\tend\n\tend\n\n\th(2) = gca;\n\th(3) = cbar('vert'); % ERSP colorbar axes\n\tset(h(2),'Position',[.1 ordinate1 .8 height].*s+q)\n\tset(h(3),'Position',[.95 ordinate1 .05 height].*s+q)\n\ttitle([ 'ERSP(' g.unitpower ')' ])\n\n\tE = [min(P(dispf,:));max(P(dispf,:))];\n\th(4) = subplot('Position',[.1 ordinate1-0.1 .8 .1].*s+q); % plot marginal ERSP means\n                                                    % below the ERSP image\n\tplot(times,E,[0 0],...\n\t     [min(E(1,:))-max(max(abs(E)))/3 max(E(2,:))+max(max(abs(E)))/3], ...\n             '--m','LineWidth',g.linewidth)\n\taxis([min(times) max(times) ...\n             min(E(1,:))-max(max(abs(E)))/3 max(E(2,:))+max(max(abs(E)))/3])\n\t\n\ttick = get(h(4),'YTick');\n\tset(h(4),'YTick',[tick(1) ; tick(end)])\n\tset(h(4),'YAxisLocation','right')\n    set(h(4),'TickLength',[0.020 0.025]);\n\txlabel('Time (ms)')\n\tylabel( g.unitpower )\n\n\tE = 10 * log10(mbase(dispf));\n\th(5) = subplot('Position',[0 ordinate1 .1 height].*s+q); % plot mean spectrum\n                                                    % to left of ERSP image\n    plot(freqs(dispf),E,'LineWidth',g.linewidth)\n\tif ~isnan(g.alpha)\n        hold on;\n\t\tplot(freqs(dispf),Pboot(:,dispf)+[E;E],'g', 'LineWidth',g.linewidth);\n\t\tplot(freqs(dispf),Pboot(:,dispf)+[E;E],'k:','LineWidth',g.linewidth)\n\tend\n\n\taxis([freqs(1) freqs(max(dispf)) min(E)-max(abs(E))/3 max(E)+max(abs(E))/3])\n\ttick = get(h(5),'YTick');\n    if (length(tick)>1)\n\t   set(h(5),'YTick',[tick(1) ; tick(end-1)])\n    end\n    set(h(5),'TickLength',[0.020 0.025]);\n\tset(h(5),'View',[90 90])\n\txlabel('Frequency (Hz)')\n\tylabel( g.unitpower )\n    if strcmp(g.hzdir,'normal')\n        freqdir = 'reverse';\n    else\n        freqdir = 'normal';\n    end\n    set(h(5),'xdir',freqdir);  % make frequency ascend or descend\nend\n\nswitch lower(g.plotitc)\n  case 'on'\n    %\n    %%%%%%%%%%%% Image the ITC %%%%%%%%%%%%%%%%%%\n    %\n\th(6) = subplot('Position',[.1 ordinate2 .9 height].*s+q); % ITC image\n\n\tRR = R; % RR is the masked ITC (R)\n\tif ~isnan(g.alpha)\n\t\tRR(find(RR < repmat(Rboot(1,:)',[1 g.timesout]))) = 0;\n\tend\n\n    if ITC_CAXIS_LIMIT == 0\n\t   coh_caxis = min(max(max(R(dispf,:))),1)*[-1 1]; % 1 WAS 0.4 !\n    else\n       coh_caxis = ITC_CAXIS_LIMIT*[-1 1];\n    end\n\n\tif exist('Rsign') && strcmp(g.plotphase, 'on')\n\t\timagesc(times,freqs(dispf),Rsign(dispf,:).*RR(dispf,:),coh_caxis); % <---\n\telse\n\t\timagesc(times,freqs(dispf),RR(dispf,:),coh_caxis); % <---\n\tend\n\tif ~isempty(g.itcmax)\n\t\tcaxis([-g.itcmax g.itcmax]);\n\tend\n\ttmpcaxis = caxis;\n    set(gca,'ydir',g.hzdir);  % make frequency ascend or descend\n\n\thold on\n\tplot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth);\n    if ~isnan(g.marktimes)\n     for mt = g.marktimes(:)'\n\t   plot([mt mt],[0 freqs(max(dispf))],'--k','LineWidth',g.linewidth);\n     end\n    end\n\thold off\n\tset(h(6),'YTickLabel',[],'YTick',[])\n\tset(h(6),'XTickLabel',[],'XTick',[])\n\tif ~isempty(g.vert)\n\t\tfor index = 1:length(g.vert)\n\t\t\tline([g.vert(index), g.vert(index)], ...\n                  [min(freqs(dispf)) max(freqs(dispf))], ...\n                  'linewidth', 1, 'color', 'm');\n\t\tend\n\tend\n\n\th(7) = gca;\n\th(8) = cbar('vert');\n\t%h(9) = get(h(8),'Children');\n\tset(h(7),'Position',[.1 ordinate2 .8 height].*s+q)\n\tset(h(8),'Position',[.95 ordinate2 .05 height].*s+q)\n\tset(h(8),'YLim',[0 tmpcaxis(2)]); \n\ttitle('ITC')\n\n    %\n    %%%%% plot the ERP below the ITC image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %\n\t% E = mean(R(dispf,:));\n\n    ERPmax = max(ERP);\n    ERPmin = min(ERP);\n    ERPmax = ERPmax + 0.1*(ERPmax-ERPmin);\n    ERPmin = ERPmin - 0.1*(ERPmax-ERPmin);\n\th(10) = subplot('Position',[.1 ordinate2-0.1 .8 .1].*s+q); % ERP\n\n    plot(ERPtimes,ERP(ERPindices),...\n         [0 0],[ERPmin ERPmax],'--m','LineWidth',g.linewidth);\n    hold on; plot([times(1) times(length(times))],[0 0], 'k');\n    axis([min(ERPtimes) max(ERPtimes) ERPmin ERPmax]);\n\n\ttick = get(h(10),'YTick');\n\tset(h(10),'YTick',[tick(1) ; tick(end)])\n    set(h(10),'TickLength',[0.02 0.025]);\n\tset(h(10),'YAxisLocation','right')\n\txlabel('Time (ms)')\n    ylabel('\\muV')\n    if (~isempty(g.topovec))\n      if length(g.topovec) ~= 1, ylabel(''); end; % ICA component\n    end\n\n\tE = mean(R(dispf,:)');\n\th(11) = subplot('Position',[0 ordinate2 .1 height].*s+q); % plot the marginal mean\n                                                    % ITC left of the ITC image\n\tif ~isnan(g.alpha)\n\t\tplot(freqs(dispf),E,'LineWidth',g.linewidth); hold on;\n        plot(freqs(dispf),Rboot(dispf),'g', 'LineWidth',g.linewidth);\n        plot(freqs(dispf),Rboot(dispf),'k:','LineWidth',g.linewidth);\n        axis([freqs(1) freqs(max(dispf)) 0 max([E Rboot(dispf)])+max(E)/3])\n\telse\n\t\tplot(freqs(dispf),E,'LineWidth',g.linewidth)\n\t\taxis([freqs(1) freqs(max(dispf)) min(E)-max(E)/3 max(E)+max(E)/3])\n\tend\n\n\ttick = get(h(11),'YTick');\n\tset(h(11),'YTick',[tick(1) ; tick(length(tick))])\n\tset(h(11),'View',[90 90])\n        set(h(11),'TickLength',[0.020 0.025]);\n\txlabel('Frequency (Hz)')\n\tylabel('ERP')\n    if strcmp(g.hzdir,'normal')\n        freqdir = 'reverse';\n    else\n        freqdir = 'normal';\n    end\n    set(gca,'xdir',freqdir);  % make frequency ascend or descend\n\n    %\n    %%%%%%%%%%%%%%% plot a topoplot() %%%%%%%%%%%%%%%%%%%%%%%\n    %\n\tif (~isempty(g.topovec))\n\t\th(12) = subplot('Position',[-.1 .43 .2 .14].*s+q);\n\t\tif length(g.topovec) == 1\n\t\t  topoplot(g.topovec,g.elocs,'electrodes','off', ...\n\t\t\t   'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo);\n\t\telse\n\t\t  topoplot(g.topovec,g.elocs,'electrodes','off', 'chaninfo', g.chaninfo);\n\t\tend\n\t\t    axis('square')\n\tend\nend; % switch\n\nif g.plot\n\ttry, icadefs; set(gcf, 'color', BACKCOLOR); catch, end\n    if (length(g.title) > 0)\n\t    axes('Position',pos,'Visible','Off');               \n\t    h(13) = text(-.05,1.01,g.title);\n\t    set(h(13),'VerticalAlignment','bottom')     \n\t    set(h(13),'HorizontalAlignment','left') \n        set(h(13),'FontSize',TITLE_FONT);\n    end\n\n    axcopy(gcf);\nend\n\n% symmetric Hanning tapering function\n% -----------------------------------\nfunction w = hanning(n)\nif ~rem(n,2)\n   w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1)));\n   w = [w; w(end:-1:1)];\nelse\n   w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1)));\n   w = [w; w(end-1:-1:1)];\nend\n\nfunction myprintf(verbose, varargin)\n    if strcmpi(verbose, 'on')\n        fprintf(varargin{:});\n    end\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/timefreqfunc/timef.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5704481313872523}}
{"text": "function [elem,idx,volume,bdFlag] = fixorder3(node,elem,bdFlag)\n%% FIXORDER3 fix orientation of tetrahedron \n% \n%   elem = FIXORDER3(node,elem) computes signed volume of all tetrahedron\n%   in the triangulation and switch the vertices such that all signed\n%   volume is positive.\n%   \n%   [elem,idx,volume] = FIXORDER3(node,elem) also outputs the index set of\n%   elements whose volume is negative.\n%\n%   [elem,idx,volume,bdFlag] = FIXORDER3(node,elem,bdFlag) changes the bdFlag\n%   for boundary conditions. \n%\n% See also fixorder\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif (nargin==2)\n    bdFlag = [];\nend\n% compute volume and elemSign of each tetrahedron\n[volume,elemSign] = simplexvolume(node,elem);\n% find tetrahedron with negative volume and switch the vertices\nidx = find(elemSign==-1); \nelem(idx,[2 3]) = elem(idx,[3 2]);\nif exist('bdFlag','var') && ~isempty(bdFlag)\n    bdFlag(idx,[2 3]) = bdFlag(idx,[3 2]);\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/mesh/fixorder3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5704481114939352}}
{"text": "% IALM + LMSVDS (Liu et al. 2012)\n% process_video('RPCA', 'IALM_LMSVDS', 'dataset/demo.avi', 'output/demo_IALM_LMSVDS.avi');\n[L,S] = inexact_alm_rpca_with_lmsvds(M);\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/IALM_LMSVDS/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5703544073685076}}
{"text": "% Data File DTX2\n% Free damped vibrations\n% of a particle\n  m    = 'm';    % mass of the particle\n  Fx   = '-k*v - c*x'; % projections of forces on x\n  x0   = '0.1';  % initial coordinate\n  v0   = '10';   % initial velocity\n  Tend = 20;     % upper bound of integration\n  eps  = 1e-10;  % desirable accuracy\n  np   = 3;      % number of parameters\n  P{1} = 'm';    % mass of the particle\n  P{2} = 'k';    % coefficient of resistance\n  P{3} = 'c';    % spring stiffness", "meta": {"author": "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/DTX2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5703294347181967}}
{"text": "% Snell's Law And Critical Angle Reflection Example\n%\n% This example illustrates Snell's law by steering a tone burst from a\n% linear array transducer within a layered heterogeneous medium. It builds\n% on the Simulating Transducer Field Patterns Example.\n%\n% author: Bradley Treeby\n% date: 10th December 2009\n% last update: 24th August 2014\n%  \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see <http://www.gnu.org/licenses/>. \n\nclear all;\n\n% =========================================================================\n% SIMULATION\n% =========================================================================\n\n% create the computational grid\nNx = 128;           % number of grid points in the x (row) direction\nNy = Nx;            % number of grid points in the y (column) direction\ndx = 50e-3/Nx;    \t% grid point spacing in the x direction [m]\ndy = dx;            % grid point spacing in the y direction [m]\nkgrid = makeGrid(Nx, dx, Ny, dy);\n\n% define the properties of a layered propagation medium\nmedium.alpha_power = 1.5;   % [dB/(MHz^y cm)]\nmedium.alpha_coeff = 0.75;  % [dB/(MHz^y cm)]\nmedium.density = 1000;      % [kg/m^3]\nc0 = 1500;                  % [m/s]\nmedium_mulp = 2;\nmedium.sound_speed = c0*ones(Nx, Ny); \nmedium.sound_speed(Nx/2:end, :) = medium_mulp*c0;\n\n% create the time array\n[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);\nkgrid.t_array = 0:dt:1000*dt;\n\n% define a source mask for a linear element transducer with an odd number\n% of elements \nnum_elements = 61;\nsource.p_mask = zeros(Nx, Ny);\nx_offset = 25;\ny_offset = 20;\nstart_index = Ny/2 - round(num_elements/2) + 1 - y_offset;\nsource.p_mask(x_offset, start_index:start_index + num_elements - 1) = 1;\n\n% define the properties of the tone burst\nsampling_freq = 1/dt;   % [Hz]\nsteering_angle = 20;    % [deg]\nelement_spacing = dx;   % [m]\ntone_burst_freq = 1e6;  % [Hz]\ntone_burst_cycles = 8;\n\n% create an element index relative to the centre element of the transducer\nelement_index = -(num_elements - 1)/2:(num_elements - 1)/2;\n\n% use geometric beam forming to calculate the tone burst offsets for each\n% transducer element based on the element index\ntone_burst_offset = 200 + element_spacing*element_index*sin(steering_angle*pi/180)/(c0*dt);\n\n% create the tone burst signals\nsource.p = toneBurst(sampling_freq, tone_burst_freq, tone_burst_cycles, 'SignalOffset', tone_burst_offset);\n\n% assign the input options\ninput_args = {'DisplayMask', source.p_mask};\n\n% run the simulation\nkspaceFirstOrder2D(kgrid, medium, source, [], input_args{:});", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/examples/example_tvsp_snells_law.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5703294238268546}}
{"text": "function [ x, qraux, ipvt ] = cqrdc ( x, ldx, n, p, ipvt, job )\n\n%*****************************************************************************80\n%\n%% CQRDC computes the QR factorization of an N by P complex matrix.\n%\n%  Discussion:\n%\n%    CQRDC uses Householder transformations to compute the QR factorization \n%    of an N by P matrix X.  Column pivoting based on the 2-norms of the \n%    reduced columns may be performed at the user's option.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 May 2007\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, complex X(LDX,P), the matrix whose decomposition \n%    is to be computed. \n%\n%    Input, integer LDX, the leading dimension of X.  N <= LDX.\n%\n%    Input, integer N, the number of rows of the matrix.\n%\n%    Input, integer P, the number of columns in the matrix X.\n%\n%    Input, integer IPVT(P), integers that control the \n%    selection of the pivot columns.  The K-th column X(K) of X is placed \n%    in one of three classes according to the value of IPVT(K):\n%      IPVT(K) > 0, then X(K) is an initial column.\n%      IPVT(K) == 0, then X(K) is a free column.\n%      IPVT(K) < 0, then X(K) is a final column.\n%    Before the decomposition is computed, initial columns are moved to the \n%    beginning of the array X and final columns to the end.  Both initial \n%    and final columns are frozen in place during the computation and only\n%    free columns are moved.  At the K-th stage of the reduction, if X(K) \n%    is occupied by a free column it is interchanged with the free column \n%    of largest reduced norm.  \n%\n%    Input, integer JOB, initiates column pivoting.\n%    0, no pivoting is done.\n%    nonzero, pivoting is done.\n%\n%    Output, complex X(LDX,P); the upper triangle contains the upper\n%    triangular matrix R of the QR factorization.  Below its diagonal, X \n%    contains information from which the unitary part of the decomposition\n%    can be recovered.  If pivoting has been requested, the decomposition is \n%    not that of the original matrix X, but that of X with its columns \n%    permuted as described by IPVT.\n%\n%    Output, complex QRAUX(P), further information required to recover\n%    the unitary part of the decomposition.\n%\n%    Output, integer IPVT(P); the index of the column of the\n%    original matrix that has been interchanged into\n%    the K-th column, if pivoting was requested.\n%    IPVT is not referenced if JOB == 0.\n%\n  pl = 1;\n  pu = 0;\n\n  if ( job ~= 0 )\n%\n%  Pivoting has been requested.  Rearrange the columns according to IPVT.\n%\n    for j = 1 : p\n\n      swapj = ( 0 < ipvt(j) );\n      negj = ( ipvt(j) < 0 );\n\n      if ( negj )\n        ipvt(j) = -j;\n      else\n        ipvt(j) = j;\n      end\n\n      if ( swapj )\n\n        if ( j ~= pl )\n          temp      = x(1:n,pl);\n          x(1:n,pl) = x(1:n,j);\n          x(1:n,j)  = temp;\n        end\n\n        ipvt(j) = ipvt(pl);\n        ipvt(pl) = j;\n        pl = pl + 1;\n\n      end\n\n    end\n\n    pu = p;\n\n    for jj = 1 : p\n\n      j = p - jj + 1;\n\n      if ( ipvt(j) < 0 )\n\n        ipvt(j) = -ipvt(j);\n\n        if ( j ~= pu )\n\n          temp      = x(1:n,pu);\n          x(1:n,pu) = x(1:n,j);\n          x(1:n,j)  = temp;\n\n          i        = ipvt(pu);\n          ipvt(pu) = ipvt(j);\n          ipvt(j)  = i;\n\n        end\n\n        pu = pu - 1;\n\n      end\n\n    end\n\n  end\n%\n%  Compute the norms of the free columns.\n%\n  for j = pl : pu\n    qraux(j) = scnrm2 ( n, x(1:n,j), 1 );\n    work(j) = qraux(j);\n  end\n%\n%  Perform the Householder reduction of X.\n%\n  lup = min ( n, p );\n\n  for l = 1 : lup\n%\n%  Locate the column of largest norm and bring it\n%  into the pivot position.\n%\n    if ( pl <= l & l < pu )\n\n      maxnrm = 0.0;\n      maxj = l;\n\n      for j = l : pu\n        if ( maxnrm < real ( qraux(j) ) )\n          maxnrm = real ( qraux(j) );\n          maxj = j;\n        end\n      end\n\n      if ( maxj ~= l )\n\n        temp        = x(1:n,l);\n        x(1:n,l)    = x(1:n,maxj);\n        x(1:n,maxj) = temp;\n\n        qraux(maxj) = qraux(l);\n        work(maxj)  = work(l);\n\n        i          = ipvt(maxj);\n        ipvt(maxj) = ipvt(l);\n        ipvt(l)    = i;\n\n      end\n\n    end\n\n    qraux(l) = 0.0;\n\n    if ( l ~= n )\n%\n%  Compute the Householder transformation for column L.\n%\n      nrmxl = scnrm2 ( n-l+1, x(l:n,l), 1 );\n\n      if ( cabs1 ( nrmxl ) ~= 0.0 )\n\n        if ( cabs1 ( x(l,l) ) ~= 0.0 )\n          nrmxl = csign2 ( nrmxl, x(l,l) );\n        end\n\n        x(l:n,l) = x(l:n,l) / nrmxl;\n        x(l,l) = 1.0 + x(l,l);\n%\n%  Apply the transformation to the remaining columns,\n%  updating the norms.\n%\n        for j = l+1 : p\n\n          t = - ( conj ( transpose ( x(l:n,l) ) ) * x(l:n,j) ) / x(l,l);\n          x(l:n,j) = x(l:n,j) + t * x(l:n,l);\n\n          if ( j < pl | pu < j )\n            continue\n          end\n\n          if ( cabs1 ( qraux(j) ) == 0.0 )\n            continue\n          end\n\n          tt = 1.0 - ( abs ( x(l,j) ) / real ( qraux(j) ) )^2;\n          tt = max ( tt, 0.0 );\n          t = tt;\n          tt = 1.0 + 0.05 * tt * ( real ( qraux(j) ) / real ( work(j) ) )^2;\n\n          if ( tt ~= 1.0 )\n            qraux(j) = qraux(j) * sqrt ( t );\n          else\n            qraux(j) = scnrm2 ( n-l, x(l+1:n,j), 1 );\n            work(j) = qraux(j);\n          end\n\n        end\n%\n%  Save the transformation.\n%\n        qraux(l) = x(l,l);\n        x(l,l) = -nrmxl;\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/linpack_c/cqrdc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5703294238121066}}
{"text": "% op_freqrange.m\n% Jamie Near, McGill University 2014.\n% \n% USAGE:\n% out=op_freqrange(in,ppmmin,ppmmax);\n% \n% DESCRIPTION:\n% Output only a specified frequency range of the input spectrum.\n% \n% INPUTS:\n% in         = input data in matlab structure format.\n% ppmmin     = minimum extent of frequency range in ppm.\n% ppmmax     = maximum extent of frequency range in ppm.\n%\n% OUTPUTS:\n% out        = Output following frequency range selection.\n\nfunction out=op_freqrange(in,ppmmin,ppmmax);\n\n%Calculate Specs using fft\nfullspecs=fftshift(ifft(in.fids,[],in.dims.t),in.dims.t);\n\n%now take only the specified range of the spectrum\nspecs=fullspecs(in.ppm>ppmmin & in.ppm<ppmmax,:,:);\n\n%convert back to time domain\n%if the length of Fids is odd, then you have to do a circshift of one to\n%make sure that you don't introduce a small frequency shift into the fids\n%vector.\nif mod(size(specs,in.dims.t),2)==0\n    %disp('Length of vector is even.  Doing normal conversion');\n    fids=fft(fftshift(specs,in.dims.t),[],in.dims.t);\nelse\n    %disp('Length of vector is odd.  Doing circshift by 1');\n    fids=fft(circshift(fftshift(specs,in.dims.t),1),[],in.dims.t);\nend\n\n%calculate the size;\nsz=size(fids);\n\n%calculate the ppm scale\nppm=in.ppm(in.ppm>ppmmin & in.ppm<ppmmax);\n\n%calculate the new spectral width and dwelltime:\ndppm=abs(ppm(2)-ppm(1));\nppmrange=abs((ppm(end)-ppm(1)))+dppm;\nspectralwidth=ppmrange*in.Bo*42.577;\ndwelltime=1/spectralwidth;\n\n%calculate the time scale\nt=[0:dwelltime:(sz(1)-1)*dwelltime];\n\n\n\n%FILLING IN DATA STRUCTURE\nout=in;\nout.fids=fids;\nout.specs=specs;\nout.sz=sz;\nout.ppm=ppm;  \nout.t=t; \nout.spectralwidth=spectralwidth;\nout.dwelltime=dwelltime;\n\n%FILLING IN THE FLAGS\nout.flags=in.flags;\nout.flags.writtentostruct=1;\nout.flags.freqranged=1;", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/processingTools/op_freqrange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5703294183688941}}
{"text": "function [qua, DCMbn, euler] = att_update(wb, DCMbn, qua, omega_ie_n, omega_en_n, dt, att_mode)\n% att_update: updates attitude using quaternion or DCM.\n%\n% INPUT\n%   wb,         3x1 incremental turn-rates in body-frame (rad/s).\n%   DCMbn,      3x3 body-to-nav DCM.\n%   qua,        4x1 quaternion.\n%   omega_ie_n, 3x3 skew-symmetric Earth rate matrix (rad/s).\n%   omega_en_n, 3x3 skew-symmetric transport rate (rad/s).\n%   dt,         1x1 IMU sampling interval (s).\n%\tatt_mode,   attitude mode (string).\n%      'quaternion': attitude updated as quaternion. Default value.\n%             'dcm': attitude updated as Direct Cosine Matrix.\n%\n% OUTPUT\n%   qua,      4x1 updated quaternion.\n%   DCMbn,    3x3 updated body-to-nav DCM.\n%   euler,    3x1 updated Euler angles (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%   <http://www.gnu.org/licenses/>.\n%\n% Reference:\n%\n%\tTitterton, D.H. and Weston, J.L. (2004). Strapdown\n% Inertial Navigation Technology (2nd Ed.). Institution\n% of Engineering and Technology, USA.\n%\n%\tCrassidis, J.L. and Junkins, J.L. (2011). Optimal Esti-\n% mation of Dynamic Systems, 2nd Ed. Chapman and Hall/CRC, USA.\n% Eq. 7.39, p. 458.\n%\n% Version: 004\n% Date:    2022/03/06\n% Author:  Rodrigo Gonzalez <rodralez@frm.utn.edu.ar>\n% URL:     https://github.com/rodralez/navego\n\nif nargin < 7, att_mode  = 'quaternion'; end\n\n%% Gyros output correction for Earth and transport rates\n\nom_ie_n = skewm_inv(omega_ie_n);\nom_en_n = skewm_inv(omega_en_n);\nwb = (wb - DCMbn' * (om_ie_n + om_en_n));  % Titterton, Eq. 3.29, p. 32\n\nif strcmp(att_mode, 'quaternion')\n%% Quaternion update   \n\n    qua   = qua_update(qua, wb, dt);    % Quaternion update\n    qua   = qua / norm(qua);            % Brute-force normalization\n    DCMbn = qua2dcm(qua);               % DCM update\n    euler = qua2euler(qua);             % Euler angles update\n    \nelseif strcmp(att_mode, 'dcm')\n%% DCM update    \n    \n    delta_theta = wb * dt;                  % Incremental Euler angles \n    DCMbn = dcm_update(DCMbn, delta_theta); % DCM update\n    euler = dcm2euler(DCMbn);               % Euler angles update\n    qua   = euler2qua(euler);               % Quaternion update\n    qua   = qua / norm(qua);                % Brute-force normalization\n    \nelse\n    error('att_update: no attitude update mode defined. Check the attitude update mode selected.')\nend\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/ins/att_update.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5703294129158492}}
{"text": "function [varargout]=triSurfRemoveThreeConnect(varargin)\n\n% function [Ft,Vt,Ct,L]=triSurfRemoveThreeConnect(Fd,Vd,Cd)\n% ------------------------------------------------------------------------\n% In a surface triangulation \"3-connected\" locations often contain poor\n% quality triangles of a locally smaller area then the rest of the surface.\n% Smoothening does not resolve this issue since the quality is not great\n% improved even after vertex is at the centre of its neighbouring nodes.\n% Hence the function triSurfRemoveThreeConnect instead removes the central\n% nodes and groups the affected triangles into a single triangle.\n% The input sets Fd, Vd and Cd represent the input faces, vertices and face\n% colours respectively. The output sets Ft, Vt and Ct represent the fixed\n% faces, vertices and face colours respectively. In addition a logic L can\n% be output which defines the affected vertices in Vd. The output may\n% consist of [Ft,Vt] or [Ft,Vt,Ct] or [Ft,Vt,Ct,L].\n% The last nnz(L)/3 faces in Ft represent the fixed faces.\n%\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% \n% 2014/06/03 Created\n% 2015/05/01 Updated with varagin type input\n%------------------------------------------------------------------------\n\n%% Parse input\nFd=varargin{1};\nVd=varargin{2};\n\nif nargin==3\n    Cd=varargin{3};\nelse\n    Cd=[];\nend\n\nif isempty(Cd)\n    Cd=(1:1:size(Fd,1))';\nend\n\n%%\n\n%Get patch face/vertex connectivity matrices\n[IND_F,IND_V]=patchIND(Fd,Vd,1);\n\n%Count point connectivity\nnumFriends=sum(IND_V>0,2); %Number of vertex neighbours\nlogicThree=numFriends==3; %Logic for vertices with only three connected neighbours\n\n%Remove boundary points from list\nTR=triangulation(Fd,Vd);\nindFree=freeBoundary(TR);\nindFree=unique(indFree(:));\nif ~isempty(indFree)\n    logicThree(indFree)=0;\nend\n\nif nnz(logicThree)>0\n    \n    %IND_V subset\n    IND_V_three=IND_V(logicThree,:);\n    \n    %Snap vertices to mean of neighbours such that vertex normal should\n    %coincide with new surface normal\n    logicValid=IND_V_three>0;\n    Xp=NaN(size(IND_V_three));\n    Yp=NaN(size(IND_V_three));\n    Zp=NaN(size(IND_V_three));\n    Xp(logicValid)=Vd(IND_V_three(logicValid),1);\n    Yp(logicValid)=Vd(IND_V_three(logicValid),2);\n    Zp(logicValid)=Vd(IND_V_three(logicValid),3);\n    Vp=[gnanmean(Xp,2) gnanmean(Yp,2) gnanmean(Zp,2)];\n    Vd(logicThree,:)=Vp; %Replace points\n    \n    %Get new faces\n    IND_F_three=IND_F(logicThree,:);\n    indFacesThree=IND_F_three(IND_F_three>0);\n    logicFacesThree=false(size(Fd,1),1);\n    logicFacesThree(indFacesThree)=1;\n    IND_V_three=sort(IND_V_three,2);\n    if size(IND_V_three,2)>3\n        IND_V_three=IND_V_three(:,end-2:end);\n    end\n    F_new=IND_V_three;\n    \n    %Fix face orientation based on normals\n    indUsed=unique(F_new(:));\n    V_new=Vd(indUsed,:);\n    indFix=zeros(size(Vd,1),1);\n    indFix(indUsed)=1:numel(indUsed);\n    F_new_fix=indFix(F_new);\n    if size(F_new,1)==1\n        F_new_fix=F_new_fix';\n    end    \n    [~,~,Nd]=patchNormal(Fd,Vd);\n    [N_new]=patchNormal(F_new_fix,V_new);\n    N_sum_mag=sqrt(sum((Nd(logicThree,:)+N_new).^2,2));\n    logicFlip=N_sum_mag<1;\n    F_new(logicFlip,:)=fliplr(F_new(logicFlip,:));\n    \n    %Get color information for new faces\n    logicValid=IND_F_three>0;\n    \n    C_F_three=nan(size(IND_F_three));\n    C_F_three(logicValid)=Cd(IND_F_three(logicValid));\n    C_new=gnanmean(C_F_three,2);\n    \n    %Faces to keep\n    F_keep=Fd(~logicFacesThree,:);\n    C_keep=Cd(~logicFacesThree,:);\n    \n    %Join and create vertex/face/color sets\n    Ft=[F_keep;F_new];\n    Ct=[C_keep;C_new];\n    \n    indUsed=unique(Ft(:));\n    Vt=Vd(indUsed,:);\n    indFix=zeros(size(Vd,1),1);\n    indFix(indUsed)=1:numel(indUsed);\n    Ft=indFix(Ft);\n    \nelse\n    Ft=Fd;\n    Vt=Vd;\n    Ct=Cd;\n    logicFacesThree=false(size(Ft,1),1);\nend\n\nswitch nargout\n    case 2\n        varargout{1}=Ft;\n        varargout{2}=Vt;\n    case 3\n        varargout{1}=Ft;\n        varargout{2}=Vt;\n        varargout{3}=Ct;\n    case 4\n        varargout{1}=Ft;\n        varargout{2}=Vt;\n        varargout{3}=Ct;\n        varargout{4}=logicFacesThree;\n    otherwise\n        error('Wrong number of output arguments');\nend\n\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/triSurfRemoveThreeConnect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.57032173733455}}
{"text": "function randint_test ( )\n\n%*****************************************************************************80\n%\n%% RANDINT_TEST shows how random integers are generated in MATLAB.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    13 February 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'RANDINT_TEST:\\n' );\n  fprintf ( 1, '  MATLAB version\\n' );\n  fprintf ( 1, '  Test the MATLAB RANDINT function.\\n' );\n\n  randint_test01 ( );\n\n  randint_test02 ( );\n\n  seed = 123456789;\n  randint_test03 ( seed );\n\n  seed = 987654321;\n  randint_test03 ( seed );\n\n  seed = 123456789;\n  randint_test03 ( seed );\n%\n%  Terminate.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'RANDINT_TEST:\\n' );\n  fprintf ( 1, '  Normal end of execution.\\n' );\n\n  fprintf ( 1, '\\n' );\n  timestamp ( );\n\n  return\nend\nfunction randint_test01 ( )\n\n%*****************************************************************************80\n%\n%% RANDINT_TEST01 simply calls the random integer generator a few times.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    13 February 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'RANDINT_TEST01:\\n' );\n  fprintf ( 1, '  In MATLAB, random integers are generated by calling RANDINT:\\n' );\n  fprintf ( 1, '  If a range is not specified, the values are 0 or 1.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  A = randint ( )      a random scalar value.\\n' );\n  fprintf ( 1, '  B = randint ( 5, 1 ) a random column vector of 5 entries.\\n' );\n  fprintf ( 1, '  C = randint ( 1, 5 ) a random row vector of 5 entries.\\n' );\n  fprintf ( 1, '  D = randint ( 3, 4 ) a 3 by 4 random matrix.\\n' );\n  fprintf ( 1, '  E = randint ( 5 )    a 5 by 5 random matrix.\\n' );\n\n  a = randint ( )\n  b = randint ( 5, 1 )\n  c = randint ( 1, 5 )\n  d = randint ( 3, 4 )\n  e = randint ( 5 )\n\n  return\nend\nfunction randint_test02 ( )\n\n%*****************************************************************************80\n%\n%% RANDINT_TEST02 specifies the range.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    13 February 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'RANDINT_TEST02:\\n' );\n  fprintf ( 1, '  RANDINT allows the user to specify the numeric range.\\n' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  A = randint (  1, 1, [ 5,    10 ] ) a random scalar value.\\n' );\n  fprintf ( 1, '  B = randint ( 10, 1, [ 7,     8 ] ) a random column vector of 5 entries.\\n' );\n  fprintf ( 1, '  C = randint (  1, 5, [ -1,   +1 ] ) a random row vector of 5 entries.\\n' );\n  fprintf ( 1, '  D = randint (  3, 4, [ -5,   +5 ] ) a 3 by 4 random matrix.\\n' );\n  fprintf ( 1, '  E = randint (  5, 5, [ 100, 200 ] ) a 5 by 5 random matrix.\\n' );\n\n  a = randint ( 1,  1, [   5,  10 ] )\n  b = randint ( 10, 1, [   7,   8 ] )\n  c = randint ( 1,  5, [  -1,  +1 ] )\n  d = randint ( 3,  4, [  -5,  +5 ] )\n  e = randint ( 5,  5, [ 100, 200 ] )\n\n  return\nend\nfunction randint_test03 ( seed )\n\n%*****************************************************************************80\n%\n%% RANDINT_TEST03 sets the seed before calling RANDINT.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    13 February 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'RANDINT_TEST03:\\n' );\n  fprintf ( 1, '  By setting the random number seed, you can control\\n' );\n  fprintf ( 1, '  how the random number sequence begins.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The command \"rng ( 123456789 )\" sets the seed to 123456789.\\n' );\n\n  rng ( seed );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Seed has been set to %d\\n', seed );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Now generate 5 random values.\\n' );\n\n  for i = 1 : 5\n    a = randint ( 1, 1, [ 1, 100 ] );\n    fprintf ( 1, '  RANDINT(1,1,[1,100]) = %g\\n', a );\n  end\n\n  rng ( seed );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Seed has been reset to %d\\n', seed );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Now generate 5 more random values.\\n' );\n\n  for i = 1 : 5\n    a = randint ( 1, 1, [ 1, 100 ] );\n    fprintf ( 1, '  RANDINT(1,1,[1,100]) = %g\\n', a );\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/matlab_random/randint_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.570321735918116}}
{"text": "function [c,Ls,g,shift,M] = erblett(f,bins,fs,varargin)\n%ERBLETT  ERBlet non-stationary Gabor filterbank\n%   Usage: [c,Ls,g,shift,M] = erblett(f,bins,fs,varargin)\n%          [c,Ls,g,shift] = erblett(...)\n%          [c,Ls] = erblett(...)\n%          c = erblett(...)\n%\n%   Input parameters: \n%         f         : The signal to be analyzed (For multichannel\n%                     signals, input should be a matrix which each\n%                     column storing a channel of the signal)\n%         bins      : Desired bins per ERB\n%         fs        : Sampling rate of f (in Hz)\n%         varargin  : Optional input pairs (see table below)\n%   Output parameters:\n%         c         : Transform coefficients (matrix or cell array)\n%         Ls        : Original signal length (in samples)\n%         g         : Cell array of Fourier transforms of the analysis \n%                     windows\n%         shift     : Vector of frequency shifts\n%         M         : Number of time channels\n%\n%   This function computes an ERBlet constant-Q transform via non-stationary \n%   Gabor filterbanks. Given the signal *f*, the ERBlet parameter *bins*, \n%   as well as the sampling rate *fs* of *f*, the corresponding ERBlet\n%   coefficients *c* are given as output. For reconstruction, the length of\n%   *f* and the filterbank parameters can be returned also.\n% \n%   The transform produces phase-locked coefficients in the\n%   sense that each filter is considered to be centered at\n%   0 and the signal itself is modulated accordingly.\n%\n%   Optional input arguments arguments can be supplied like this::\n%\n%       erblett(f,bins,fs,'Qvar',Qvar)\n%\n%   The arguments must be character strings followed by an\n%   argument:\n%\n%     'Qvar',Qvar              Bandwidth variation factor\n%\n%     'M_fac',M_fac            Number of time channels are rounded to \n%                              multiples of this\n%\n%     'winfun',winfun          Filter prototype (see |firwin| for available \n%                              filters)\n%\n%   Examples:\n%   ---------\n%\n%   The following example shows analysis and synthesis with |erblett| and\n%   |ierblett|:::\n%\n%       [f,fs] = gspi;\n%       binsPerERB = 4;\n%       [c,Ls,g,shift,M] = erblett(f,binsPerERB,fs);\n%       fr = ierblett(c,g,shift,Ls);\n%       rel_err = norm(f-fr)/norm(f)\n%       plotfilterbank(c,Ls./M,[],fs,'dynrange',60);\n%\n%   See also:  ierblett, firwin\n% \n%   References:  ltfatnote027\n\n% Authors: Thibaud Necciari, Nicki Holighaus\n% Date: 10.04.13\n\nwarning(['LTFAT: ERBLETT has been deprecated and will be removed',...\n         ' in the future releases, please use AUDFILTERS with ''erb'' and FILTERBANK instead.']);   \n\n%% Check input arguments\nif nargin < 3\n    error('Not enough input arguments');\nend\n\n[f,Ls,W]=comp_sigreshape_pre(f,upper(mfilename),0);\n\n% Set defaults\n\ndefinput.keyvals.usrM = [];\ndefinput.keyvals.Qvar = 1;\ndefinput.keyvals.M_fac = 1;\ndefinput.keyvals.winfun = 'nuttall';\n\n% Check input arguments\n\n[flags,keyvals,usrM]=ltfatarghelper({'usrM'},definput,varargin);\n\n%% Create the ERBlet dictionary\n\ndf = fs/Ls; % frequency resolution in the FFT\n\nfmin = 0;\nfmax = fs/2;\n\n% Convert fmin and fmax into ERB\nerblims = freqtoerb([fmin,fmax]);\n\n% Determine number of freq. channels\nNf = bins*ceil(erblims(2)-erblims(1));\n\n% Determine center frequencies\nfc = erbspace(fmin,fmax,Nf)';\n\n% Concatenate \"virtual\" frequency positions of negative-frequency windows\nfc = [fc ; flipud(fc(1:end-1))];\n\ngamma = audfiltbw(fc); % ERB scale\n\n% Convert center frequencies in Hz into samples\n\nposit = round(fc/df);% Positions of center frequencies in samples\nposit(Nf+1:end) = Ls-posit(Nf+1:end);% Extension to negative freq.\n\n% Compute desired essential (Gaussian) support for each filter\nLwin = 4*round(gamma/df);\n\n% Nuttall windows are slightly broader than Gaussians, this is offset by \n% the factor 1.1\n\nM = round(keyvals.Qvar*Lwin/1.1);\n\n% Compute cell array of analysis filters\ng = arrayfun(@(x) firwin(keyvals.winfun,x)/sqrt(x),M,'UniformOutput',0);\n\ng{1}=1/sqrt(2)*g{1};\ng{end}=1/sqrt(2)*g{end};\n\nM = keyvals.M_fac*ceil(M/keyvals.M_fac);\nN = length(posit);  % The number of frequency channels\n\nif ~isempty(usrM)\n    if numel(usrM) == 1\n        M = usrM*ones(N,1);\n    else\n        M = usrM;\n    end    \nend\n\n%% The ERBlet transform\n\n% some preparation\n\nf = fft(f);\n\nc=cell(N,1); % Initialisation of the result\n\n% The actual transform\n\nfor ii = 1:N\n    Lg = length(g{ii});\n    \n    idx = [ceil(Lg/2)+1:Lg,1:ceil(Lg/2)];\n    win_range = mod(posit(ii)+(-floor(Lg/2):ceil(Lg/2)-1),Ls)+1;\n    \n    if M(ii) < Lg % if the number of frequency channels is too small,\n        % aliasing is introduced\n        col = ceil(Lg/M(ii));\n        temp = zeros(col*M(ii),W,assert_classname(f));\n        \n        temp([end-floor(Lg/2)+1:end,1:ceil(Lg/2)],:) = ...\n            bsxfun(@times,f(win_range,:),g{ii}(idx));\n        temp = reshape(temp,M(ii),col,W);\n        \n        c{ii} = squeeze(ifft(sum(temp,2)));\n        \n        % Using c = cellfun(@(x) squeeze(ifft(x)),c,'UniformOutput',0);\n        % outside the loop instead does not provide speedup; instead it is\n        % slower in most cases.\n    else\n        temp = zeros(M(ii),W,assert_classname(f));\n        temp([end-floor(Lg/2)+1:end,1:ceil(Lg/2)],:) = ...\n            bsxfun(@times,f(win_range,:),g{ii}(idx));\n        \n        c{ii} = ifft(temp);\n    end\nend\n\nif max(M) == min(M)\n    c = cell2mat(c);\n    c = reshape(c,M(1),N,W);\nend\n\nif nargout > 3\n    shift = [Ls-posit(end); diff(posit)];% Frequency hop sizes in samples\nend\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/deprecated/erblett.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5703217292862374}}
{"text": "\nfunction XYZtransform = transformPointCloud(XYZ,Rt)\n    XYZtransform = Rt(1:3,1:3) * XYZ + repmat(Rt(1:3,4),1,size(XYZ,2));\nend\n\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/WarpDepthMesh/transformPointCloud.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.682573734412324, "lm_q1q2_score": 0.5702791235528362}}
{"text": "function c=comp_wfbt(f,wtNodes,rangeLoc,rangeOut,ext)\n%COMP_WFBT Compute Wavelet Filterbank Tree\n%   Usage:  c=comp_wfbt(f,wtNodes,rangeLoc,rangeOut,ext);\n%\n%   Input parameters:\n%         f        : Input L*W array.\n%         wtNodes  : Filterbank tree nodes (elementary filterbanks) in\n%                    BF order. Length *nodeNo* cell array of structures.\n%         rangeLoc : Idxs of each node terminal outputs. Length *nodeNo* \n%                    cell array of vectors.\n%         rangeOut : Output subband idxs of each node terminal outputs.\n%         ext      : Type of the forward transform boundary handling.\n%\n%   Output parameters:\n%         c        : Cell array of coefficients. Each element is one\n%                    subband (matrix with W columns).\n%\n\n% Do non-expansve transform if ext=='per'\ndoPer = strcmp(ext,'per');\n% Pre-allocated output\nc = cell(sum(cellfun(@(rEl) numel(rEl),rangeOut)),1);\n\n ca = {f};\n % Go over all nodes in breadth-first order\n for jj=1:numel(wtNodes)\n    % Load current filterbank\n    wtNode = wtNodes{jj}.h(:);\n    % Node filters to a cell array\n    % hCell = cellfun(@(hEl) conj(flipud(hEl.h(:))),wtNode,'UniformOutput',0);\n    hCell = cellfun(@(hEl) hEl.h(:),wtNode,'UniformOutput',0);\n    % Node filters subs. factors\n    a = wtNodes{jj}.a;\n    % Node filters initial skips\n    if(doPer)\n       %offset = cellfun(@(hEl) 1-numel(hEl.h)-hEl.offset,wtNode);\n       offset = cellfun(@(hEl) hEl.offset,wtNode);\n    else\n       offset = -(a-1);\n    end\n\n    % Run filterbank\n    catmp=comp_filterbank_td(ca{1},hCell,a,offset,ext);\n    % Pick what goes directy to the output...\n    c(rangeOut{jj}) = catmp(rangeLoc{jj});\n    % and save the rest.\n    diffRange = 1:numel(hCell);\n    diffRange(rangeLoc{jj}) = [];\n    ca = [ca(2:end);catmp(diffRange)];\n end        \n\n\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_wfbt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5702791231583108}}
{"text": "clc;\nclose all\n%% which one to show?\nidx = 24;\ncoordIndices = [1,2,3];\n\nimgFig1 = figure(1);\nset(imgFig1, 'Position', [100 100 1400 900]) % [1 1 width height]\n\nsubplot(2,2,1);\nimagesc(imgMat(:,:,:,idx)); axis off image;\nsubplot(2,2,2);\nimagesc(instanceMaskMat(:,:,:,idx)); axis off image;\nsubplot(2,2,3);\nA = (predInstanceMaskMat0(:,:,coordIndices,idx) + 1) / 2;\nimagesc(A);  axis off image;\n%% 3D surface\nsubplot(2,2,4);\n\nr = 1;\n[x,y,z] = sphere(50);\nx0 = 0; y0 = 0; z0 = 0;\nx = x*r + x0;\ny = y*r + y0;\nz = z*r + z0;\n\n% figure\nlightGrey = 0.7*[1 1 1]; % It looks better if the lines are lighter\nsurface(x,y,z, 'FaceColor', 'none', 'EdgeColor',lightGrey)\nhold on\n%% points\nhold on;\npoints = reshape(predInstanceMaskMat0(:,:,coordIndices,idx), [], 3);\npoints = points';\npointsColor = points - (-1);%min(points(:)); % -1\npointsColor = pointsColor ./ 2;%max(pointsColor(:));\nfor i = 1:size(points,2)\n    plot3( points(1,i), points(2,i), points(3,i), 's', 'MarkerSize',3, 'MarkerFaceColor', pointsColor(:,i)', 'MarkerEdgeColor', pointsColor(:,i)');\nend\nhold off;\n\naxis off square\nview([1 1 0.75]) % adjust the viewing angle\nzoom(1.4)\n\n%% save result\nif flagSaveFig    \n    export_fig( sprintf('%s/%04d_visualization_single.jpg', saveFolder, i) );\nend\n\n", "meta": {"author": "aimerykong", "repo": "Recurrent-Pixel-Embedding-for-Instance-Grouping", "sha": "748ade6b969c7861c2a9009cd0f0ffb27004677c", "save_path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping", "path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping/Recurrent-Pixel-Embedding-for-Instance-Grouping-748ade6b969c7861c2a9009cd0f0ffb27004677c/demo1_tutorial_instance_segmentation/fun4MeanShift/main001_instSeg_proj3Dsphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5702791177634475}}
{"text": "% V = est_calcInvCovMatFourierPDC(Rinv,E,foi,fs,N,p, verb)\n%\n% Obtain the frequency domain transform of the inverse covariance matrix of \n% an M-variate VAR[p] process\n% This is needed for calculating the analytic statistics for the PDC [1]\n%\n% Inputs:\n%\n%     Rinv: inverse process covariance matrix obtained from est_calcInvCovMat\n%     E:    noise covariance matrix\n%     foi:  frequencies of interest (Hz)\n%     fs:   sampling rate\n%     N:    # chans\n%     p:    model order\n%     verb: verbosity level. 0 = no output, 1=text.\n%\n% Outputs:\n%\n%     V:    Frequency-domain transform of the inverse covariance matrix\n%\n% References:\n%\n% [1] Schelter et al, (2009). Testing for directed influences among neural \n% signals using partial directed coherence. J. Neuroscience Methods. 152:210-9.\n%\n% see also: est_calcInvCovMat(), est_calcInvCovMatFourier()\n%\n% Author: Tim Mullen 2010, SCCN/INC, UCSD\n% Email:  tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction V = est_calcInvCovMatFourierPDC(Rinv,E,foi,fs,N,p,verb,DEBUG)\n\nif nargin<8\n    DEBUG = false;\nend\n\n%% extract the diagonal elements of H=Rinv\n% structure of Hd is (e.g., for p=2): \n% [diag(H(1,1)), diag(H(2,1)), diag(H(1,2)), diag(H(2,2))]\n% where diag(H(u,v)) is the column vector formed by the diagonal of\n% submatrix H(u,v) of H\nHd = zeros(N,p^2);\ncnt=1;\nfor v=1:p\n    for u=1:p\n        Hd(:,cnt)=diag(Rinv((u-1)*N+1:u*N,(v-1)*N+1:v*N));\n        cnt=cnt+1;\n    end\nend\n\nif DEBUG\n    for j=1:N\n        try chol(reshape(Hd(j,:),[p p])); catch; fprintf('Hj<0: j=%d - ',j); keyboard; end;\n    end\nend\n\n%% create u,v index vectors\n% us = [1 2 ... p 1 2 ... p ... ]'   (p^2 length)\n% vs = [1 1 ... 1 2 2 ... 2 ... ]'   (p^2 length)\nus = repmat(1:p,1,p)';\nvs = zeros(p^2,1);\nfor ii=1:p\n    vs((ii-1)*p+1:(ii-1)*p+p)=ones(p,1)*ii;\nend\n\n\n\n%% construct the V matrix for all freqs\nfi=0;\nCOS=zeros(p^2,1); \nfreqs=(2*pi*foi)/fs;\nV = zeros(length(freqs),N,N); % NOTE: V will end up (N,N,freqs)\nif verb, h=waitbar(0,'calculating V^-1...'); end\nfor f=freqs\n    fi=fi+1;\n\n    %% construct cosine matrix\n    COS(:,1) = cos(us*f).*cos(vs*f)+sin(us*f).*sin(vs*f);\n%     COS(:,2) = sin(us*f).*sin(vs*f);\n%     COS(:,3) = cos(us*f).*sin(vs*f);\n%     COS(:,4) = sin(us*f).*sin(vs*f);\n\n    %% multiply Hd and COS matrices to get matrix where row j is \n    % [sum_{u,v=1 : p} Hjj(u,v)COS_11(u,v), ...\n    %  sum_{u,v=1 : p} Hjj(u,v)COS_21(u,v), ...\n    %  sum_{u,v=1 : p} Hjj(u,v)COS_12(u,v), ...\n    %  sum_{u,v=1 : p} Hjj(u,v)COS_22(u,v)]\n    %\n    % where COSab(u,v) is the a,bth element of the sine-cos transform\n    % matrix evaluated at u,v.\n    %\n    % NOTE: reshaping row j to 2x2 yeilds a matrix proportional to V_ij(f) \n    % for some specific i\n    Vm = Hd*COS;\n    \n    % now we multiply in the variances of the i's (E(i,i)) to generate the\n    % full V matrix\n    Vm = kron(diag(E)',Vm);\n    \n    % next, reshape to desired structure (NxNx2x2)\n    V(fi,:,:) = Vm';\n    \n    \n    if verb, waitbar(fi/length(freqs),h); end\nend % for freqs\n\n% permute V: (chs,chs,freqs,2,2)\nV = permute(V,[2 3 1]);\nif verb, close(h); 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/SIFT-private/est/est_calcInvCovMatFourierPDC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5702791067764583}}
{"text": "function [LL, LLS, ht] = igarch_likelihood(parameters, epsilon, fepsilon, p, q, errorType, igarchType, constant, backCast, T, estimFlag)\n% Log likelihood for IGARCH(P,Q) estimation\n%\n% USAGE:\n%   [LL, LLS, HT] = igarch_likelihood(PARAMETERS,EPSILON,FEPSILON,P,Q,ERRORTYPE,IGARCHTYPE,CONSTANT,BACKCAST,T,ESTIMFLAG)\n%\n% INPUTS:\n%   PARAMETERS   - A vector of IGARCH process parameters\n%                    [omega alpha beta [nu lambda]]\n%   DATA         - Vector of mean zero residuals\n%   EPSILON      - A column of mean zero data\n%   FEPSILON     - Either abs(EPSILON) or EPSILON.^2, depending on IGARCHTYPE\n%   P            - Positive, scalar integer representing the number of\n%                    symmetric innovations\n%   Q            - Non-negative, scalar integer representing the number\n%                    of lags of conditional variance (0 for ARCH)\n%   ERRORTYPE    - [OPTIONAL] The error distribution used, valid types are:\n%                    'NORMAL'    - Gaussian Innovations [DEFAULT]\n%                    'STUDENTST' - T distributed errors\n%                    'GED'       - Generalized Error Distribution\n%                    'SKEWT'     - Skewed T distribution\n%   IGARCHTYPE   - [OPTIONAL] The type of variance process, either\n%                    1 - Model evolves in absolute values\n%                    2 - Model evolves in squares [DEFAULT]\n%   CONSTANT     - [OPTIONAL] Logical value indicating whether model\n%                    should include a constant.  Default is true (include).\n%   BACKCAST     - The value used for variance recursion\n%   T            - Length of data\n%   ESTIMFLAG    - [OPTIONAL] Flag (0 or 1) to indicate if the function\n%                    is being used in estimation.  If it is 1, then the parameters are\n%                    transformed from unconstrained values to constrained by standard\n%                    garch model constraints\n%\n% OUTPUTS:\n%   LL             - Minus 1 times the log likelihood\n%   LLS            - Time series of log likelihoods (Also multiplied by -1)\n%   HT             - Time series of conditional variances\n%\n% COMMENTS:\n%   See also IGARCH\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 7/12/2009\n\nif nargin==11 && estimFlag\n    %If for estimation, transform the parameters\n    [parameters,nu,lambda]=igarch_itransform(parameters,p,q,errorType,constant);\nelse\n    %Otherwise the parameters simply must be parsed\n    if errorType==2 || errorType==3\n        %Seperate nu from the remaning parameters\n        nu=parameters(p+q+constant);\n        parameters=parameters(1:constant+p+q-1);\n    elseif errorType==4\n        lambda=parameters(p+q+constant+1);\n        nu=parameters(p+q+constant);\n        parameters=parameters(1:constant+p+q-1);\n    end\nend\n\n%Backcast length\nm  =  max([p q]);\n%Compute the conditional variances\nht=igarch_core(fepsilon,parameters,backCast,p,q,m,T,igarchType,constant);\n%Indices for the relevant opservations\nt  = (m + 1):T;\nht = ht(t);\n%Compute the log likelihoods\nswitch errorType\n    case 1\n        [LL, LLS] = normloglik(epsilon,0,ht);\n        LLS = -LLS;\n        LL = -LL;\n    case 2\n        [LL, LLS] = stdtloglik(epsilon,0,ht,nu);\n        LLS = -LLS;\n        LL = -LL;\n    case 3\n        [LL, LLS] = gedloglik(epsilon,0,ht,nu);\n        LLS = -LLS;\n        LL = -LL;\n    case 4\n        [LL, LLS] = skewtloglik(epsilon,0,ht,nu,lambda);\n        LLS = -LLS;\n        LL = -LL;\nend\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/univariate/igarch_likelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.570279101578858}}
{"text": "function combo_test30 ( )\n\n%*****************************************************************************80\n%\n%% COMBO_TEST30 tests PRUEFER_*.\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 = 4;\n\n  fprintf ( 1, ' \\n' );\n  fprintf ( 1, 'COMBO_TEST30\\n' );\n  fprintf ( 1, '  Pruefer codes:\\n' );\n  fprintf ( 1, ' \\n' );\n  fprintf ( 1, '  PRUEFER_ENUM enumerates,\\n' );\n  fprintf ( 1, '  PRUEFER_RANK ranks,\\n' );\n  fprintf ( 1, '  PRUEFER_SUCCESSOR lists,\\n' );\n  fprintf ( 1, '  PRUEFER_UNRANK unranks.\\n' );\n%\n%  Enumerate.\n%\n  ncode = pruefer_enum ( n );\n\n  fprintf ( 1, ' \\n' );\n  fprintf ( 1, '  For N = %d\\n', n );\n  fprintf ( 1, '  the number of Pruefer codes is %d\\n', ncode );\n  fprintf ( 1, ' \\n' );\n%\n%  List\n%\n  p = [];\n  rank = -1;\n\n  while ( 1 );\n\n    rank_old = rank;\n\n    [ p, rank ] = pruefer_successor ( n, p, rank );\n\n    if ( rank <= rank_old )\n      break\n    end\n\n    fprintf ( 1, '  %3d  ', rank );\n    for i = 1 : n - 2\n      fprintf ( 1, '%5d', p(i) );\n    end\n    fprintf ( 1, '\\n' );\n\n  end\n%\n%  Unrank.\n%\n  rank = floor ( ncode / 2 );\n\n  p = pruefer_unrank ( rank, n );\n\n  fprintf ( 1, ' \\n' );\n  fprintf ( 1, '  The element of rank %d:\\n', rank );\n  fprintf ( 1, ' \\n' );\n  for i = 1 : n - 2\n    fprintf ( 1, '%5d', p(i) );\n  end\n  fprintf ( 1, '\\n' );\n%\n%  Rank.\n%\n  rank = pruefer_rank ( n, p );\n\n  fprintf ( 1, ' \\n' );\n  fprintf ( 1, '  The rank of the element is computed as %d:\\n', rank );\n\n  return\nend\n", "meta": {"author": "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_test30.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.5702786169428213}}
{"text": "%demo_SOFAcalculateITD - Load HRTF and plots ITD.\n\n% #Author: Piotr Majdak\n% #Author: Michael Mihocic: bugs fixed (10.2021)\n% #Author: Michael Mihocic: header documentation updated (28.10.2021)\n% \n% SOFA Toolbox - demo script\n% Copyright (C) Acoustics Research Institute - Austrian Academy of Sciences\n% Licensed under the EUPL, Version 1.2 or \u2013 as soon they will be approved by the European Commission - subsequent versions of the EUPL (the \"License\")\n% You may not use this work except in compliance with the License.\n% You may obtain a copy of the License at: https://joinup.ec.europa.eu/software/page/eupl\n% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing  permissions and limitations under the License. \n% \n\n%% Define parameters\n% Subject index of the file to convert\nsubject=3;\n\n%% load SOFA file\nSOFAfn=fullfile(SOFAdbPath, 'database', 'cipic', ['subject_' sprintf('%03d',subject) '.sofa']);\nObj=SOFAload(SOFAfn, 'nochecks');\n\n%% Calculate Interaural time delay\n[itd_time, ~, ~, Obj_time] = SOFAcalculateITD(Obj, 'time', 'thr', 20);\n[itd_samples, ~, ~, Obj_samples] = SOFAcalculateITD(Obj, 'samples', 'thr', 20);\n\n%% Plot results\nh = figure('Name',mfilename);\nsubplot(211)\nplot((Obj_time.Data.Delay(:,1) - Obj_time.Data.Delay(:,2))*1e6)\nxlabel('Position')\nylabel('Time (\\mus)')    \ntitle('ITD (time)')\naxis tight\n\nsubplot(212)\nplot((Obj_samples.Data.Delay(:,1) - Obj_samples.Data.Delay(:,2)))\nxlabel('Position')\nylabel(['Samples (Fs:' num2str(Obj.Data.SamplingRate), 'Hz)'])       \ntitle('ITD (samples)')\naxis tight\n\n%% Polar plot (not working in Octave)\nif ~exist('OCTAVE_VERSION','builtin')\n    figure('Name',mfilename);\n    SOFAplotHRTF(Obj, 'itdhorizontal');\n    title('ITD (time, horizontal plane)')\nend\n\n", "meta": {"author": "sofacoustics", "repo": "SOFAtoolbox", "sha": "a3a93981f4ea25edc37380c39cafc661548de8c7", "save_path": "github-repos/MATLAB/sofacoustics-SOFAtoolbox", "path": "github-repos/MATLAB/sofacoustics-SOFAtoolbox/SOFAtoolbox-a3a93981f4ea25edc37380c39cafc661548de8c7/SOFAtoolbox/demos/demo_SOFAcalculateITD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5702786086646625}}
{"text": "function y = cropbyval(x, val)\n%CROPBYVAL Crop an array by\n%\n%   Y = CROPBYVAL(X, VAL) returns a subarray identical to X but where any\n%   values VAL on the borders of X have been removed.\n%\n%   Y = CROPBYVAL(X) will determine VAL automatically by looking at the\n%   borders of X and picking the most common value.  En error is given if\n%   there is no value which is more common that the other values on the\n%   border.  Note that automatically chosing VAL slowes down CROPBYVAL.\n%\n%   For example, if\n%\n%     X = [ 0  0  0  0\n%           1  2  3  0\n%           4  5  6  0 ]\n%\n%   then both Y = CROPBYVAL(X, 0) and Y = CROPBYVAL(X) will return\n%\n%     Y = [ 1  2  3\n%           4  5  6 ]\n\n%   Author:      Peter J. Acklam\n%   Time-stamp:  2002-03-03 13:51:33 +0100\n%   E-mail:      pjacklam@online.no\n%   URL:         http://home.online.no/~pjacklam\n\n   % check number of input arguments\n   error(nargchk(1, 2, nargin));\n\n   % if VAL is give, check it, otherwise compute default value\n   if nargin == 2\n      if any(size(val) ~= 1)\n         error('VAL must be a scalar.');\n      end\n   else\n      vals = [];\n      sx = size(x);\n      dx = ndims(x);\n      c = cell(dx, 1);\n      for i = 1:dx\n         c{i} = 2:sx(i)-1;\n      end\n      t(prod(sx)) = logical(uint8(1));          % use uint8 to save memory\n      t = reshape(t, sx);\n      t(:) = t(end);\n      t(c{:}) = 0;\n      [lens, vals] = rlencode(sort(x(t(:))));\n      len = max(lens);\n      k = find(len == lens);\n      if length(k) > 1\n         error('No unique most common value on boundary.');\n      end\n      val = vals(k);\n   end\n\n   % get linear index values of elements different from VAL\n   if isnan(val)\n      i = find(~isnan(x));\n   elseif val == 0\n      i = find(x);\n   else\n      i = find(x ~= val);\n   end\n\n   % quick exit if output will be empty\n   if isempty(i)\n      y = [];\n      return\n   end\n\n   % The following is based on code by\n   % Doug Schwarz <douglas.schwarz@kodak.com>\n\n   sx     = size(x);            % size vector of x\n   dx     = length(sx);         % number of dimensions of x\n   c      = cell(dx, 1);        % initialize list of subscript\n   [c{:}] = ind2sub(sx, i);     % compute the subscripts\n   for j = 1:dx\n      c{j} = min(c{j}) : max(c{j});\n   end\n   y = x(c{:});\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/lib/util/matutil/cropbyval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225279, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.5702786071612324}}
{"text": "function [qd] = stateToQd(x)\n%Converts qd struct used in hardware to x vector used in simulation\n% x is 1 x 13 vector of state variables [pos vel quat omega]\n% qd is a struct including the fields pos, vel, euler, and omega\n\n%current state\nqd.pos = x(1:3);\nqd.vel = x(4:6);\n\nRot = QuatToRot(x(7:10)');\n[phi, theta, yaw] = RotToRPY_ZXY(Rot);\n\nqd.euler = [phi; theta; yaw];\nqd.omega = x(11:13);\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/stateToQd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.570278603773868}}
{"text": "classdef LIRCMOP13 < PROBLEM\n% <multi> <real> <large/none> <constrained>\n% Constrained benchmark MOP with large infeasible regions\n\n%------------------------------- Reference --------------------------------\n% Z. Fan, W. Li, X. Cai, H. Huang, Y. Fang, Y. You, J. Mo, C. Wei, and E.\n% Goodman, An improved epsilon constraint-handling method in MOEA/D for\n% CMOPs with large infeasible regions, Soft Computing, 2019, 23:\n% 12491-12510.\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 Wenji Li\n    \n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 3;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values and constraint violations\n        function Population = Evaluation(obj,varargin)\n            X = varargin{1};\n            X = max(min(X,repmat(obj.upper,size(X,1),1)),repmat(obj.lower,size(X,1),1));\n            [popsize,variable_length] = size(X);\n            sum1 = zeros(popsize,1);\n            for j = 3 : variable_length\n                sum1 = sum1+10*(X(:,j)-0.5).^2;\n            end\n            PopObj(:,1) = (1.7057+sum1).*cos(0.5*pi*X(:,1)).*cos(0.5*pi*X(:,2));\n            PopObj(:,2) = (1.7057+sum1).*cos(0.5*pi*X(:,1)).*sin(0.5*pi*X(:,2));\n            PopObj(:,3) = (1.7057+sum1).*sin(0.5*pi*X(:,1));\n            gx          =  PopObj(:,1).^2+PopObj(:,2).^2+PopObj(:,3).^2;\n            PopCon(:,1) = (gx-9).*(4-gx);\n            PopCon(:,2) = (gx-3.61).*(3.24-gx);\n            Population  = SOLUTION(X,PopObj,PopCon,varargin{2:end});\n            obj.FE      = obj.FE + length(Population);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R = UniformPoint(N,3);\n            R = 1.7057*R./repmat(sqrt(sum(R.^2,2)),1,3);\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            a = linspace(0,pi/2,10)';\n            R = {sin(a)*cos(a')*1.7057,sin(a)*sin(a')*1.7057,cos(a)*ones(size(a'))*1.7057};\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/LIR-CMOP/LIRCMOP13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5702786018899336}}
{"text": "function [ gradientParams, SigmaInvs, CholDecomps, Sigmas, bs, allXresp] = gradientCCNF( params, num_alpha, numBeta, sizeTheta, lambda_a, lambda_b, lambda_th, Precalc_Bs, x, y, Precalc_yBys, Precalc_Bs_flat, constant, num_seqs)\n%gradientCCNF Summary of this function goes here\n%   Detailed explanation goes here\n    \n    % pick out the relevant terms (unpack)\n    alphas_init = params(1:num_alpha);\n    betasInit = params(num_alpha+1:num_alpha+numBeta);\n    thetasInit = reshape(params(num_alpha+numBeta+1:end), sizeTheta);\n            \n    % Compute the response from the neural layers        \n    allXresp = 1./(1 + exp(-thetasInit * x));\n    Xt = x;\n            \n    bs = 2*alphas_init' * allXresp;\n        \n    % This is precalculated for the next step and is basically the\n    % feedforward step of the neural net\n    Z_precalc = 2 * (allXresp .* (1-allXresp));\n    \n    % These are the outputs weighted by the alphas (see eq TODO\n    db2_precalc =  bsxfun(@times, Z_precalc, alphas_init);    \n        \n    num_feats = sizeTheta(2);    \n\n    if(constant)       \n                \n        seq_length = size(x,2)/num_seqs;        \n\n        % As the similarities are the same across all series we can reuse our\n        % Sigma and SigmaInv calculations\n        \n        I = eye(seq_length);\n        [SigmaInv] = CalcSigmaCCNFflat(alphas_init, betasInit, seq_length, Precalc_Bs_flat{1}, I, zeros(seq_length));\n        CholDecomp=chol(SigmaInv);\n\n        % This is a faster way of inverting a symmetric matrix\n        Sigma=CholDecomp\\(CholDecomp'\\I);\n        Sigma_trace = trace(Sigma);\n            \n        % mu values associated with each time step\n        mus = Sigma * reshape(bs, seq_length, num_seqs);\n\n        % difference between actual and prediction (error)\n        diff = (y - mus);\n               \n        db_precalc_mult = bsxfun(@times, db2_precalc, diff(:)');\n \n        % Equation 46 from the appendix\n        gradientThetasT = Xt * db_precalc_mult';\n\n        % Reshape into the correct format\n        gradientThetasT = gradientThetasT(:)';\n        \n        gradientThetasT = reshape(gradientThetasT, sizeTheta(2), sizeTheta(1))';\n        gradientThetasT = gradientThetasT(:);\n        \n        % Some useful precalculations\n        \n        % for every sequence get a dot product with itself\n        yy = dot(y,y);\n        \n        % same goes for the mu\n        mumu = dot(mus,mus);\n\n        % calculating the derivative of L with respect to alpha_k (Equation 27)       \n        % gradientAlphas =  (-yq'*yq +(2*yq'*D')' -2 * D * mu + sum(mu.^2) + trace(Sigma));\n        % allXresp is D\n        gradient_alphas_add = -sum(yy) + sum(mumu) + num_seqs * Sigma_trace;\n        gradient_alphas = 2 * allXresp * (y(:) - mus(:)) + gradient_alphas_add;\n        \n        gradient_betas = zeros(numBeta, 1);\n        \n        % calculating the derivative of log(L) with respect to the betas\n        for k=1:numBeta\n\n            % From Equation 38 (and 39 for gamma)\n            % gradient = -yq'*B^(k)*yq + mu'*B^(k)*mu + Vec(Sigma)'*vec(B^(k)\n\n            % We precalculate B^(k) (equation 30), as it does not change\n            % over the course of optimisation\n            B_k = Precalc_Bs{1}{k};\n\n            % precalculated -yq'*B_k*yq can be used as well as it does not\n            % change (stored in Precalc_yBys)\n            yq_B_k_yq = sum(Precalc_yBys(:,k));\n\n            % A vectorised version of mu'*B^(k)*mu \n            B_k_mu = B_k*mus;\n            mu_B_k_mu = mus(:)' * B_k_mu(:);\n            \n            % Vec(Sigma)*Vec(B^(k)) can be computed as follows:\n            partition_term = num_seqs * Sigma(:)'*B_k(:);\n            \n            % Equation 38 and 39 basically\n            dLdb = yq_B_k_yq + mu_B_k_mu + partition_term; \n\n            gradient_betas(k) = dLdb;\n        end        \n        \n        gradientParams = [gradient_alphas;gradient_betas;gradientThetasT];            \n        \n        SigmaInvs = SigmaInv;\n        CholDecomps = CholDecomp;\n        Sigmas = Sigma;\n        \n        \n    else \n        \n        SigmaInvs = cell(num_seqs, 1);\n        CholDecomps = cell(num_seqs, 1);\n        Sigmas = cell(num_seqs, 1);\n        gradients = zeros(num_seqs, numel(params));        \n        \n        a_precalc = zeros(sizeTheta(2)*sizeTheta(1), size(allXresp,2));\n\n        for i=1:size(db2_precalc,1)\n            a_precalc((i-1)*num_feats+1:i*num_feats,:) = bsxfun(@times, Xt, db2_precalc(i,:));\n        end        \n        \n        % y can either be in cell format (diff length seqs.) or in matrix\n        %, same length seqs\n        beg_ind = 1;        \n        \n        if(iscell(y))\n            end_ind = numel(y{1});\n            y_cell = true;\n        else\n            end_ind = size(y,1);\n            y_cell = false;\n        end\n        \n        % Go through every sequence summing the gradients\n        for q = 1 : num_seqs\n\n            currResp = allXresp(:,beg_ind:end_ind);\n            currB = bs(beg_ind:end_ind)';\n\n            PrecalcB = Precalc_Bs{q};\n            PrecalcBFlat = Precalc_Bs_flat{q};\n\n            if(y_cell)\n                yq = y{q};\n            else\n                yq = y(:,q);\n            end\n            \n            xq = x(2:end, beg_ind:end_ind);\n\n            % Used for equation 46 computation\n            a_precalc_curr = a_precalc(:,beg_ind:end_ind);\n\n            precalc_eye = eye(numel(yq));\n            precalc_zeros = zeros(numel(yq));\n\n            [ gradientsAlphas, gradientsBetas, gradientsThetas, SigmaInv, CholDecomp, Sigma ] = gradientCCNF_per_seq(alphas_init, betasInit, thetasInit, PrecalcB, xq, yq, currResp, currB, Precalc_yBys(q, :), PrecalcBFlat, a_precalc_curr, precalc_eye, precalc_zeros);\n            \n            gradients(q,:) = [gradientsAlphas; gradientsBetas; gradientsThetas(:)];\n            SigmaInvs{q} = SigmaInv;\n            CholDecomps{q} = CholDecomp;\n            Sigmas{q} = Sigma;\n\n            % Update the references to sequence start/end\n            if(q ~= num_seqs)\n                beg_ind = end_ind + 1;\n                if(iscell(y))\n                    end_ind = end_ind + numel(y{q+1});\n                else\n                    end_ind = end_ind + size(y,1);\n                end\n            end\n            \n        end\n        \n        gradientParams = sum(gradients,1)';\n        \n    end\n    \n    % Add the regularisation term\n    regAlpha = alphas_init * lambda_a;\n    regBeta = betasInit * lambda_b;\n    regTheta = thetasInit * lambda_th;\n    \n    \n    gradientParams = gradientParams - [regAlpha; regBeta; regTheta(:)];\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/gradientCCNF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5702744454433234}}
{"text": "% Copyright 2019, The MathWorks, Inc.\n%% animateRotorPosition\n%\n% This script will run a Simulink model of a BLDC that is energized in\n% one coil and animate the movement of the rotor. Once the animation figure\n% is rendered, there is a 5 second pause before the animation begins.\n\nclose all\nclear\n\n% Below parameters are defined in the Simulink model\n% Sample time\n% Ts = 2e-5;\n% Number of pole pairs\n% p = 1; \n% Initial rotor angle in degrees\n% th0 = 0;\n% Sector \n% sector = 6;\n\nmdl = 'Modeling_commutation_logic.slx';\nopen_system(mdl);\n\nsim(mdl)\ntry\n    \n    %\n    r = 1.2;\n    theta = linspace(0,2*pi);\n    x = cos(theta);\n    y = sin(theta);\n    \n    x1 = 0.8*cos(theta);\n    y1 = 0.8*sin(theta);\n    \n    xa = cos(0);\n    ya = sin(0);\n    \n    xb = cos(2*pi/3);\n    yb = sin(2*pi/3);\n    \n    xc = cos(-2*pi/3);\n    yc = sin(-2*pi/3);\n    \n    xat = r*cos(0);\n    yat = r*sin(0);\n    \n    xbt = r*cos(2*pi/3);\n    ybt = r*sin(2*pi/3);\n    \n    xct = r*cos(-2*pi/3);\n    yct = r*sin(-2*pi/3);\n    \n    hf = figure(1);h = plot(x,y,'k-',[0 xa],[0 ya],'k-',[0 xb],[0 yb],'k-',[0 xc],[0  yc],'k-',xa,ya,'ko',xb,yb,'ko',xc,yc,'ko',x1,y1,'k-');grid\n    \n    set(hf,'Color',[1 1 1])\n    \n    ha = gca;\n    \n    \n    set(ha,'Visible','off')\n    \n    ht1 = text(xat,yat,'A');\n    ht2 = text(xbt,ybt,'B');\n    ht3 = text(xct,yct,'C');\n    \n    set(ht1,'FontSize',14);\n    set(ht2,'FontSize',14);\n    set(ht3,'FontSize',14);\n    \n    \n    axis([-1.2 1.2 -1.2 1.2])\n    axis equal\n    \n    set(h(5),'MarkerSize',20)\n    set(h(6),'MarkerSize',20)\n    set(h(7),'MarkerSize',20)\n    \n    switch_pattern = switchPattern.signals.values(1:40:end,:);\n    \n    init_switch_pattern = num2str(switch_pattern(1,:));\n    \n    \n    switch init_switch_pattern\n        \n        case num2str([1 0 0 0 0 1])\n            \n            set(h(5),'MarkerFaceColor',[1 0 0])\n            set(h(7),'MarkerFaceColor',[0 0 1])\n            set(h(6),'MarkerFaceColor',[1 1 1])\n            \n        case num2str([0 0 1 0 0 1])\n            \n            set(h(6),'MarkerFaceColor',[1 0 0])\n            set(h(7),'MarkerFaceColor',[0 0 1])\n            set(h(5),'MarkerFaceColor',[1 1 1])\n            \n        case num2str([0 1 1 0 0 0])\n            \n            set(h(5),'MarkerFaceColor',[0 0 1])\n            set(h(6),'MarkerFaceColor',[1 0 0])\n            set(h(7),'MarkerFaceColor',[1 1 1])\n            \n        case num2str([0 1 0 0 1 0])\n            \n            set(h(5),'MarkerFaceColor',[0 0 1])\n            set(h(7),'MarkerFaceColor',[1 0 0])\n            set(h(6),'MarkerFaceColor',[1 1 1])\n            \n        case num2str([0 0 0 1 1 0])\n            \n            set(h(6),'MarkerFaceColor',[0 0 1])\n            set(h(7),'MarkerFaceColor',[1 0 0])\n            set(h(5),'MarkerFaceColor',[1 1 1])\n            \n        case num2str([1 0 0 1 0 0])\n            \n            set(h(5),'MarkerFaceColor',[1 0 0])\n            set(h(6),'MarkerFaceColor',[0 0 1])\n            set(h(7),'MarkerFaceColor',[1 1 1])\n            \n    end\n    \n    \n    l1 = 0.7;\n    ro = thetaSim.signals.values(1)*pi/180-pi/2;\n    \n    xr1 = l1*cos(ro);\n    yr1 = l1*sin(ro);\n    xr2 = -l1*cos(ro);\n    yr2 = -l1*sin(ro);\n    \n    hold on,hl1 = plot([xr1 xr2],[yr1 yr2],'m-');\n    \n    \n    set(hl1,'LineWidth',3)\n    \n    hpr = plot(xr2,yr2,'ko');\n    hpb = plot(xr1,yr1,'ko');\n    \n    \n    set(hpr,'MarkerSize',20)\n    set(hpb,'MarkerSize',20)\n    set(hpr,'MarkerFaceColor',[1 0 0])\n    set(hpb,'MarkerFaceColor',[0 0 1])\n    \n    \n    pause\n    \n    ro1 = thetaSim.signals.values(1:40:end)-90;\n    \n    for l = 1:numel(ro1)\n        \n        switch_pattern1 = num2str(switch_pattern(l,:));\n        ro = ro1(l)*pi/180;\n        \n        \n        xr1 = l1*cos(ro);\n        yr1 = l1*sin(ro);\n        xr2 = -l1*cos(ro);\n        yr2 = -l1*sin(ro);\n        \n        set(hpr,'XData',xr2);\n        set(hpr,'YData',yr2);\n        set(hpb,'XData',xr1);\n        set(hpb,'YData',yr1);\n        \n        set(hl1,'XData',[xr1 xr2]);\n        set(hl1,'YData',[yr1 yr2]);\n        \n        switch switch_pattern1\n            \n            case num2str([1 0 0 0 0 1])\n                \n                set(h(5),'MarkerFaceColor',[1 0 0])\n                set(h(6),'MarkerFaceColor',[1 1 1])\n                set(h(7),'MarkerFaceColor',[0 0 1])\n                \n            case num2str([0 0 1 0 0 1])\n                \n                set(h(6),'MarkerFaceColor',[1 0 0])\n                set(h(7),'MarkerFaceColor',[0 0 1])\n                set(h(5),'MarkerFaceColor',[1 1 1])\n                \n            case num2str([0 1 1 0 0 0])\n                \n                set(h(5),'MarkerFaceColor',[0 0 1])\n                set(h(6),'MarkerFaceColor',[1 0 0])\n                set(h(7),'MarkerFaceColor',[1 1 1])\n                \n            case num2str([0 1 0 0 1 0])\n                \n                set(h(5),'MarkerFaceColor',[0 0 1])\n                set(h(7),'MarkerFaceColor',[1 0 0])\n                set(h(6),'MarkerFaceColor',[1 1 1])\n                \n            case num2str([0 0 0 1 1 0])\n                \n                set(h(6),'MarkerFaceColor',[0 0 1])\n                set(h(7),'MarkerFaceColor',[1 0 0])\n                set(h(5),'MarkerFaceColor',[1 1 1])\n                \n            case num2str([1 0 0 1 0 0])\n                \n                set(h(5),'MarkerFaceColor',[1 0 0])\n                set(h(6),'MarkerFaceColor',[0 0 1])\n                set(h(7),'MarkerFaceColor',[1 1 1])\n                \n                \n        end\n        \n        drawnow\n        \n    end\ncatch\n    \n    disp(\"The animation was closed before the end of the simulated data\")\n    \nend\n\n\n", "meta": {"author": "mathworks", "repo": "Design-motor-controllers-with-Simscape-Electrical", "sha": "307832a100418f6e9241f2a5cc0f01b9c171ba41", "save_path": "github-repos/MATLAB/mathworks-Design-motor-controllers-with-Simscape-Electrical", "path": "github-repos/MATLAB/mathworks-Design-motor-controllers-with-Simscape-Electrical/Design-motor-controllers-with-Simscape-Electrical-307832a100418f6e9241f2a5cc0f01b9c171ba41/3 Modeling commutation logic/animateRotorPosition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5702744370753173}}
{"text": "function pi_values_test ( )\n\n%*****************************************************************************80\n%\n%% PI_VALUES_TEST demonstrates the use of PI_VALUES.\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  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'PI_VALUES_TEST:\\n' );\n  fprintf ( 1, '  PI_VALUES returns values of\\n' );\n  fprintf ( 1, '  the PI function.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '     N         PI(N)\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, n, fn ] = pi_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fprintf ( 1, '  %8d  %10d\\n', n, fn )\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/pi_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.5702744319735362}}
{"text": "function M = stiefelstackedfactory(m, d, k)\n% Stiefel(k, d)^m, represented as matrices of size m*d-by-k.\n%\n% function M = stiefelstackedfactory(m, d, k)\n%\n% Points on this manifold are matrices Y of size n x k, with n = m*d.\n% Y is thought of as m matrices of size d x k each, stacked on top of each\n% other. Call them Y1, ..., Ym. Each Yi is an orthonormal matrix, that is,\n% its d rows are unit norm and are orthogonal to each other. Thus, this\n% geometry is a product of Stiefel manifolds.\n% \n% To easily transform matrices Y to 3D arrays Y3 of size d x k x m such\n% that each slice Y3(:, :, i) corresponds to one of the matrices Yi, use\n% the functions\n% \n%    Y3 = M.to3D(Y)   and   Y = M.to2D(Y3).\n%\n% The ambient space R^(nxk) is endowed with the usual inner product\n% <A, B> = trace(A'*B). This inner product is restricted to the tangent\n% spaces of the present manifold, thus making it a Riemannian submanifold\n% of the Euclidean space R^(nxk). Tangent vectors are represented as\n% matrices of the same size as Y, and can likewise be converted to 3D\n% arrays and back using to3D() and to2D().\n%\n% In dealing with this geometry, especially when dealing with the 3D array\n% representations of points and tangent vectors, the tools multiprod,\n% multitransp, multitrace, multiscale etc. available in Manopt are often\n% useful.\n%\n% See also: stiefelfactory obliquefactory multiprod multitransp\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, May 4, 2015.\n% Contributors: \n% Change log: \n\n    assert(k >= d, 'k must be at least as large as d.');\n\n    n = m*d;\n    \n    M.name = @() sprintf('Manifold of %d orthonormal matrices of size %dx%d, stacked', m, d, k);\n    \n    M.dim = @() m*(k*d - .5*d*(d+1));\n    \n    M.size = @() [m, d, k];\n    \n    M.inner = @(x, d1, d2) d1(:).'*d2(:);\n    \n    M.norm = @(x, d) norm(d(:));\n    \n    M.dist = @(x, y) error('stiefelstackedfactory.dist not implemented yet.');\n    \n    M.typicaldist = @() sqrt(M.dim());\n\n    % Convert a dxkxm matrix to an nxk matrix\n    M.to2D = @to2D;\n    function A2 = to2D(A3)\n        A2 = reshape(multitransp(A3), [k, m*d])';\n    end\n\n    % Convert an nxk matrix to a dxkxm matrix\n    M.to3D = @to3D;\n    function A3 = to3D(A2)\n        A3 = multitransp(reshape(A2', [k, d, m]));\n    end\n\n    % Given 2 3D matrices A and B of size dxkxm, returns a 3D matrix C of\n    % size dxdxm such that each slice C(:, :, i) is the symmetric part of\n    % the product A(:, :, i) * B(:, :, i)'. The name is short for\n    % \"symmetric-block-diagonal\", because if A and B were transformed to\n    % their 2D equivalents via to2D, then the output would contain the\n    % symmetric parts of the diagonal blocks of A*B'.\n    M.symbdiag = @symbdiag;\n    function C = symbdiag(A, B)\n        C = multisym(multiprod(A, multitransp(B)));\n    end\n    \n    % Orthogonal projection from the ambient space R^(nxk) to the tangent\n    % space at X.\n    M.proj = @projection;\n    function Zt = projection(Y, Z)\n        Y3 = to3D(Y);\n        Z3 = to3D(Z);\n        Lambda = symbdiag(Y3, Z3);\n        Zt3 = Z3 - multiprod(Lambda, Y3);\n        Zt = to2D(Zt3);\n    end    \n    \n    M.tangent = M.proj;\n    \n    M.egrad2rgrad = M.proj;\n    \n    M.ehess2rhess = @ehess2rhess;\n    function rhess = ehess2rhess(Y, egrad, ehess, Ydot)\n        Y3 = to3D(Y);\n        Ydot3 = to3D(Ydot);\n        egrad3 = to3D(egrad);\n        C = symbdiag(Y3, egrad3);\n        CYdot = to2D(multiprod(C, Ydot3));\n        rhess = projection(Y, ehess - CYdot);\n    end\n    \n    M.retr = @retraction;\n    function Y = retraction(Y, U, t)\n        if nargin < 3\n            t = 1.0;\n        end\n        Y = Y + t*U;\n        Y3 = to3D(Y);\n        for i = 1 : m\n            % Orthonormalize the rows of Y3(:, :, i):\n            [u, s, v] = svd(Y3(:, :, i), 'econ'); %#ok<ASGLU>\n            Y3(:, :, i) = u*v';\n            % Alternatively, one could also use qr_unique as retraction.\n        end\n        Y = to2D(Y3);\n    end\n    \n    M.exp = @exponential;\n    function Y = exponential(Y, U, t)\n        if nargin == 2\n            t = 1;\n        end\n        tU3 = multitransp(to3D(t*U));\n        Y3 = multitransp(to3D(Y));\n        % From a formula by Ross Lippert, Example 5.4.2 in AMS08.\n        for i = 1 : m\n            X = Y3(:, :, i);\n            Z = tU3(:, :, i);\n            Y3(:, :, i) = [X, Z] * ...\n                          expm([  X'*Z , -Z'*Z ; eye(d) , X'*Z]) * ...\n                          [ expm(-X'*Z) ; zeros(d) ];\n            % We may loose orthonormality here. Just to be sure:\n            [u, s, v] = svd(Y3(:, :, i), 'econ'); %#ok<ASGLU>\n            Y3(:, :, i) = u*v';\n        end\n        Y = to2D(multitransp(Y3));\n    end\n\n    M.hash = @(Y) ['z' hashmd5(Y(:))];\n    \n    M.rand = @random;\n    function Y = random()\n        Y3 = zeros(d, k, m);\n        for i = 1 : m\n            [Q, unused] = qr(randn(k, d), 0); %#ok<ASGLU>\n            Y3(:, :, i) = Q';\n        end\n        Y = to2D(Y3);\n    end\n    \n    M.randvec = @randomvec;\n    function U = randomvec(Y)\n        U = projection(Y, randn(n, k));\n        U = U / M.norm(Y, U);\n    end\n    \n    M.lincomb = @matrixlincomb;\n    \n    M.zerovec = @(x) zeros(n, k);\n    \n    M.transp = @(x1, x2, u) projection(x2, u);\n    \n    M.vec = @(x, u_mat) u_mat(:);\n    M.mat = @(x, u_vec) reshape(u_vec, [n, k]);\n    M.vecmatareisometries = @() true;\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/stiefel/stiefelstackedfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5702744264629925}}
{"text": "function MeshStat = fem_meshstats(FemFile)\n% FEM_MESHSTATS: Computes and display FEM mesh volume (tetrahedral only).\n%\n% INPUTS:\n%    - FemFile : Relative file path to a Braistorm tetrahedral FEM mesh\n% OUTPUTS: \n%    - MeshStat : Mtlab structure that contains all FEM mesh stqtistics (edge length, elem volum and mesh quality)\n%\n% DEPENDENCIES:\n%    This function require the iso2mesh toolbox\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: Takfarinas Medani, Francois Tadel, 2023\n\n% Install/load iso2mesh plugin\nisInteractive = 1;\n[isInstalled, errInstall] = bst_plugin('Install', 'iso2mesh', isInteractive);\nif ~isInstalled\n    error('Plugin \"iso2mesh\" not available.');\nend\n\n% Get data in database\nbst_progress('start', 'Mesh volume', 'Loading file...');\nFemFullFile = file_fullpath(FemFile);\nfemmat = load(FemFullFile);\n% Check type of mesh: accept only tetrahedral\nif (size(femmat.Elements,2) ~= 4)\n    error('This menu is available for tetrahedral meshes only.');\nend\n% Display results in figures if no variable in output\nisDisplay = (nargout == 0);\nhFig = [];\n\n% Convert to millimeter for convenience\nfemmat.Vertices = 1000 .* femmat.Vertices;\n\n% Loop over the tissues\nTissueID = unique(femmat.Tissue);\nfor iTissue = 1:length(TissueID)\n    iTissueID = find(femmat.Tissue == TissueID(iTissue));\n\n    % 1. Edges length\n    bst_progress('text', sprintf('Computing edges length...  [%d/%d]', iTissue, length(TissueID)));\n    Edges = meshedge(femmat.Elements(iTissueID,:));\n    n1 = femmat.Vertices(Edges(:,1),:);\n    n2 = femmat.Vertices(Edges(:,2),:);\n    EdgeLength = sqrt((n1(:,1)- n2(:,1)).^2 + (n1(:,2)- n2(:,2)).^2 + (n1(:,3)- n2(:,3)).^2);\n    \n    tstat.EdgeLengthMax = max(EdgeLength);\n    tstat.EdgeLengthMin = min(EdgeLength);\n    tstat.EdgeLengthStd = std(EdgeLength);\n    tstat.EdgeLengthMean = mean(EdgeLength);\n    tstat.EdgeLengthRMS = rms(EdgeLength);\n\n    % 2. Mesh quality: Joe-Liu mesh quality metric (0-1)\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    bst_progress('text', sprintf('Computing mesh quality...  [%d/%d]', iTissue, length(TissueID)));\n    quality = 100 .*meshquality(femmat.Vertices, femmat.Elements(iTissueID,:));\n    tstat.MeshQualityMax = max(quality);\n    tstat.MeshQualityMin = min(quality);\n    tstat.MeshQualityStd = std(quality);\n    tstat.MeshQualityMean = mean(quality);\n\n    % 3. Volume of elem\n    bst_progress('text', sprintf('Computing volume of elements...  [%d/%d]', iTissue, length(TissueID)));\n    voli = elemvolume(femmat.Vertices, femmat.Elements(iTissueID,:));\n    tstat.MeshVolumeMax = max(voli);\n    tstat.MeshVolumeMin = min(voli);\n    tstat.MeshVolumeStd = std(voli);\n    tstat.MeshVolumeMean = mean(voli);\n    tstat.MeshVolumeSum = sum(voli);\n\n    MeshStat.(femmat.TissueLabels{iTissue}) = tstat;\n\n    % Visualization\n    if isDisplay\n        bst_progress('text', sprintf('Visualisation... [%d/%d]', iTissue, length(TissueID)));\n        hFig(end+1) = figure('Name', ['Mesh stat: ' femmat.TissueLabels{iTissue}], 'NumberTitle', 'off');\n        \n        nbins = 30;\n        subplot(3,1,1)\n        histogram(EdgeLength,nbins);\n        xlabel(sprintf('Edge length (mm):   mean=%1.2f | std=%1.2f | min=%1.2f | max=%1.2f', tstat.EdgeLengthMean, tstat.EdgeLengthStd, tstat.EdgeLengthMin, tstat.EdgeLengthMax))\n        drawnow\n\n        subplot(3,1,2)\n        histogram(quality,nbins);\n        xlabel(sprintf('Mesh quality (%%):   mean=%1.2f | std=%1.2f | min=%1.2f | max=%1.2f', tstat.MeshQualityMean, tstat.MeshQualityStd, tstat.MeshQualityMin, tstat.MeshQualityMax))\n        drawnow\n\n        subplot(3,1,3)\n        histogram(voli,nbins);\n        xlabel(sprintf('Element volume (mm3):   mean=%1.2f | std=%1.2f | min=%1.2f | max=%1.2f | sum=%1.2f', tstat.MeshVolumeMean, tstat.MeshVolumeStd, tstat.MeshVolumeMin, tstat.MeshVolumeMax, tstat.MeshVolumeSum))\n        drawnow\n    end\nend\n\n% For all the full Model\n% 1. Edges length\nbst_progress('text', 'Computing edges length...');\nEdges = meshedge(femmat.Elements);\nn1 = femmat.Vertices(Edges(:,1),:);\nn2 = femmat.Vertices(Edges(:,2),:);\nEdgeLength = sqrt((n1(:,1)- n2(:,1)).^2 + (n1(:,2)- n2(:,2)).^2 + (n1(:,3)- n2(:,3)).^2);\n\nMeshStat.FullModel.EdgeLengthMax = max(EdgeLength);\nMeshStat.FullModel.EdgeLengthMin = min(EdgeLength);\nMeshStat.FullModel.EdgeLengthStd = std(EdgeLength);\nMeshStat.FullModel.EdgeLengthMean = mean(EdgeLength);\nMeshStat.FullModel.EdgeLengthRMS = rms(EdgeLength);\n\n% 2. Mesh quality: Joe-Liu mesh quality metric (0-100)\nbst_progress('text', 'Computing mesh quality...');\nquality = 100 .* meshquality(femmat.Vertices, femmat.Elements);\nMeshStat.FullModel.MeshQualityMax = max(quality);\nMeshStat.FullModel.MeshQualityMin = min(quality);\nMeshStat.FullModel.MeshQualityStd = std(quality);\nMeshStat.FullModel.MeshQualityMean = mean(quality);\n\n% 3. Volume of elem\nbst_progress('text', 'Computing volume of elements...');\nvoli = elemvolume(femmat.Vertices, femmat.Elements);\nMeshStat.FullModel.MeshVolumeMax = max(voli);\nMeshStat.FullModel.MeshVolumeMin = min(voli);\nMeshStat.FullModel.MeshVolumeStd = std(voli);\nMeshStat.FullModel.MeshVolumeMean = mean(voli);\nMeshStat.FullModel.MeshVolumeSum = sum(voli);\n\n% Visualization\nif isDisplay\n    bst_progress('text', 'Visualisation...');\n    hFig(end+1) = figure('Name', 'Mesh stat: all tissues combined', 'NumberTitle', 'off');\n    \n    nbins = 30;\n    subplot(3,1,1)\n    histogram(EdgeLength,nbins);\n    xlabel(sprintf('Edge length (mm):   mean=%1.2f | std=%1.2f | min=%1.2f | max=%1.2f', MeshStat.FullModel.EdgeLengthMean, MeshStat.FullModel.EdgeLengthStd, MeshStat.FullModel.EdgeLengthMin, MeshStat.FullModel.EdgeLengthMax))\n    drawnow\n\n    subplot(3,1,2)\n    histogram(quality,nbins);\n    xlabel(sprintf('Mesh quality (%%):   mean=%1.2f | std=%1.2f | min=%1.2f | max=%1.2f', MeshStat.FullModel.MeshQualityMean, MeshStat.FullModel.MeshQualityStd, MeshStat.FullModel.MeshQualityMin, MeshStat.FullModel.MeshQualityMax))\n    drawnow\n    \n    subplot(3,1,3)\n    histogram(voli,nbins);\n    xlabel(sprintf('Element volume (mm3):   mean=%1.2f | std=%1.2f | min=%1.2f | max=%1.2f | sum=%1.2f', MeshStat.FullModel.MeshVolumeMean, MeshStat.FullModel.MeshVolumeStd, MeshStat.FullModel.MeshVolumeMin, MeshStat.FullModel.MeshVolumeMax, MeshStat.FullModel.MeshVolumeSum))\n\n    % Close all the figures at once\n    set(hFig, 'DeleteFcn', @(h,ev)delete(setdiff(hFig,h)));\nend\n\nbst_progress('stop');\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/fem_meshstats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5702744264629925}}
{"text": "clear('pi');\ny           = load('data/M3_21.dat')';\nairline     = ssm_airline;\nairline     = estimate(y, airline, 0.1);\ntheta       = -airline.param(1);\nTheta12     = (-airline.param(2))^(1/12);\nzetavar     = airline.param(3);\n\nparam0  = [theta+Theta12 -theta*Theta12 Theta12 Theta12 zetavar];\nresult4 = zeros(31, 6);\nn       = 1;\n% 4-5-1\nfor i = 1 : 6\n    genair          = ssm_genair(4, 5, i);\n    [genair logL]   = estimate(y, genair, param0, [], 'fmin', 'simplex', 'disp', 'off');\n    result4(n, :)   = [roots([1 -genair.param(1:2)])' genair.param(3:4) reallog(genair.param(5))/2 -2*logL-13*reallog(2*pi)+2*4];\n    n               = n + 1;\nend\n% 4-4-2\nfor i = 1 : 5\n    for j = i+1 : 6\n        genair          = ssm_genair(4, 4, [i j]);\n        [genair logL]   = estimate(y, genair, param0, [], 'fmin', 'simplex', 'disp', 'off');\n        result4(n, :)   = [roots([1 -genair.param(1:2)])' genair.param(3:4) reallog(genair.param(5))/2 -2*logL-13*reallog(2*pi)+2*4];\n        n               = n + 1;\n    end\nend\n% 4-3-3\nfor i = 2 : 5\n    for j = i+1 : 6\n        genair          = ssm_genair(4, 3, [1 i j]);\n        [genair logL]   = estimate(y, genair, param0, [], 'fmin', 'simplex', 'disp', 'off');\n        result4(n, :)   = [roots([1 -genair.param(1:2)])' genair.param(3:4) reallog(genair.param(5))/2 -2*logL-13*reallog(2*pi)+2*4];\n        n               = n + 1;\n    end\nend\nfline   = '%.5f\\t\\t%.5f\\t\\t%.5f\\t\\t%.5f\\t\\t%.5f\\t\\t%.5f\\n';\nfprintf(1, fline, result4');\n\nparam0  = [theta Theta12 Theta12 zetavar];\nresult3 = zeros(41, 5);\nn       = 1;\n% 3-5-1\nfor i = 1 : 6\n    genair          = ssm_genair(3, 5, i);\n    [genair logL]   = estimate(y, genair, param0, [], 'fmin', 'simplex', 'disp', 'off');\n    result3(n, :)   = [genair.param(1:3) reallog(genair.param(4))/2 -2*logL-13*reallog(2*pi)+2*3];\n    n               = n + 1;\nend\n% 3-4-2\nfor i = 1 : 5\n    for j = i+1 : 6\n        genair          = ssm_genair(3, 4, [i j]);\n        [genair logL]   = estimate(y, genair, param0, [], 'fmin', 'simplex', 'disp', 'off');\n        result3(n, :)   = [genair.param(1:3) reallog(genair.param(4))/2 -2*logL-13*reallog(2*pi)+2*3];\n        n               = n + 1;\n    end\nend\n% 3-3-3\nfor i = 1 : 4\n    for j = i+1 : 5\n        for k = j+1 : 6\n            genair          = ssm_genair(3, 3, [i j k]);\n            [genair logL]   = estimate(y, genair, param0, [], 'fmin', 'simplex', 'disp', 'off');\n            result3(n, :)   = [genair.param(1:3) reallog(genair.param(4))/2 -2*logL-13*reallog(2*pi)+2*3];\n            n               = n + 1;\n        end\n    end\nend\nfline   = '%.5f\\t\\t%.5f\\t\\t%.5f\\t\\t%.5f\\t\\t%.5f\\n';\nfprintf(1, fline, result3');\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_gmaic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5702744264629925}}
{"text": "function [mv1, mv2, mv3] = specificIntMeanCurvDetails(img, varargin)\n%SPECIFICINTMEANCURVDETAILS Ohser's Integral of Mean Curvature with details\n%\n%   this version is just for debugging.\n%   It allows to extact contribution from each directions.\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 16/02/2005.\n%\n\n%   HISTORY \n\nimg = img~=0;\n\ndelta = [1 1 1];\n\n% square faces of the unit cell\nkr = [...\n    1 2 3 4;...\n    1 2 5 6;...\n    1 3 5 7;...\n    1 2 7 8;...\n    3 5 4 6;...\n    1 6 3 8;...\n    2 4 5 7;...\n    2 3 6 7;...\n    1 5 3 8];\n\n% triangle faces of the unit cell\nkt = [...\n    1 7 6;...\n    2 5 8;...\n    4 7 6;...\n    3 5 8;...\n    2 3 8;...\n    4 1 7;...\n    2 3 5;...\n    4 1 6];\n\n    \n% unit surface for each cell\nc1 = 0.045778;\nc2 = 0.036981;\nc3 = 0.035196;\nc = [c1 c1 c1   c2 c2 c2   c2 c2 c2   c3 c3 c3 c3];\n\n% distances between pixels\nd1 = delta(1);\nd2 = delta(2);\nd3 = delta(3);\nd12  = sqrt(delta(1)*delta(1) + delta(2)*delta(2));\nd13  = sqrt(delta(1)*delta(1) + delta(3)*delta(3));\nd23  = sqrt(delta(2)*delta(2) + delta(3)*delta(3));\ns = (d12 + d23 + d13)/2;\na123 = 2*sqrt(s*(s-d12)*(s-d13)*(s-d23));\n\na = [d1*d2 d1*d3 d2*d3   d3*d12 d3*d12 d2*d13 d2*d13 d1*d23 d1*d23  a123 a123 a123 a123];\n\n% compute gray-tone histogram of the image\nh = grayHist(img);\n\nmv1 = 0;\nmv2 = 0;\nmv3 = 0;\n\n% for each type of configuration\nfor l=1:256\n\n    v = l-1;\n    b(1) = bitand(v,1)~=0;\n    b(2) = bitand(v,2)~=0;\n    b(3) = bitand(v,4)~=0;\n    b(4) = bitand(v,8)~=0;\n    b(5) = bitand(v,16)~=0;\n    b(6) = bitand(v,32)~=0;\n    b(7) = bitand(v,64)~=0;\n    b(8) = bitand(v,128)~=0;\n    \n    % for each square face\n    for nu=1:3        \n        \n        b1 = b(kr(nu, 1));\n        b2 = b(kr(nu, 2));\n        b3 = b(kr(nu, 3));\n        b4 = b(kr(nu, 4));\n\n        s = sum([b1 b2 b3 b4]);\n        if s==1\n            mv1 = mv1 + h(l)*c(nu)/4/a(nu);\n        elseif s==3\n            mv1 = mv1 - h(l)*c(nu)/4/a(nu);\n        end\n    end\n    \n    % for each square diagonal face\n    for nu = 4:9\n        \n        b1 = b(kr(nu, 1));\n        b2 = b(kr(nu, 2));\n        b3 = b(kr(nu, 3));\n        b4 = b(kr(nu, 4));\n\n        s = sum([b1 b2 b3 b4]);\n        if s==1\n            mv2 = mv2 + h(l)*c(nu)/4/a(nu);\n        elseif s==3\n            mv2 = mv2 - h(l)*c(nu)/4/a(nu);\n        end\n    end\n\n    \n    % for each triangular face\n    for nu=10:13\n        \n        b1 = b(kt(nu-9, 1));\n        b2 = b(kt(nu-9, 2));\n        b3 = b(kt(nu-9, 3));\n        b4 = b(kt(nu-5, 1));\n        b5 = b(kt(nu-5, 2));\n        b6 = b(kt(nu-5, 3));\n\n        s1 = sum([b1 b2 b3]);\n        s2 = sum([b4 b5 b6]);\n        if s1==1\n            mv3 = mv3 + h(l)*c(nu)/3/a(nu);\n        end\n        if s2==2\n            mv3 = mv3 - h(l)*c(nu)/3/a(nu);\n        end\n    end\nend\n\n\n%imc = 4*pi*mv/sum(h(:));\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMinkowski/specificIntMeanCurvDetails.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.57027442115683}}
{"text": "\ndomain = [-1,1,-1,1,-1,1];\n% bm = 1; bp = 100;\n% rx = 1; ry = 0.075; rz = 3;\n% pde = elli3DorthocircIntf(bm,bp,rx,ry,rz);\n%intf = @(x,y,z) x.^2+y.^2+z.^2-1;epsm = 8.85*10^(-3)*2;\nepsp = 8.85*10^(-3);\nsigm = 1;\nsigp = 0.01;\nmum = (4*pi)*3;\nmup = (4*pi);\nx0=0; y0=0; z0=-0.3; r1=0.2; r2=pi/5; omega = 1; a = omega*sqrt(epsp*mup); b= 150; intPt = -1;\npde = TorusTimeInitial3(mum,mup,sigm,sigp,epsm,epsp,omega,x0,y0,z0,r1,r2,a,b,intPt);\n\nfimplicit3(pde.intf,domain)\nmaterial metal\n\ncolormap(jet)\n\n%%%%%%%%%%%%%%%%%%%%%%%\nnx = 10;  h=(domain(2) - domain(1))/nx;\nny = nx;\nnz = nx;\n\nmesh = genMesh3D(domain, nx, ny, nz);\nmesh = enrichMesh3D(mesh,2); % Mesh detail level = 1 (for IFE).\nmesh = genIntfMesh3D(mesh,pde.intf);\nmeshI = genIVmesh(mesh);\n\nmdpt = (mesh.p(mesh.t(:,1),:) + mesh.p(mesh.t(:,2),:) +...\n    mesh.p(mesh.t(:,3),:) + mesh.p(mesh.t(:,4),:))/4;\ntidshow = find(mdpt(:,2)>0);\ntetramesh(mesh.t(tidshow,:),mesh.p,'FaceAlpha',0)\nhold on\ntrisurf(meshI.iface,meshI.node(:,1),meshI.node(:,2),meshI.node(:,3)) %'edgecolor','none'\nbox on\n%axis off\naxis equal\nset(gca,'XTick',[],'YTick',[],'ZTick',[])\n\nview(50,30)", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/PlotInterf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5702718573402273}}
{"text": "function [u,p,info] =  tripreMaxwellsaddle(A,G,f,g,node,elem,bdFlag,M,grad,option)\n%% tripreMaxwellsaddle solve the Maxwell system with divgence free condition,\n%\n%         [A  G] [u]  = [f]               \n%         [G' O] [p]  = [g]               \n%\n% where  G = M_e*grad with the mass matrix for the edge element Me.\n%\n% This system can be rewritten as \n%         [A+G*DMinv*G'       G] [u]  = f +G*DMinv*g0\n%         [G'                 O] [p]  = g0\n%\n% where DMinv is the inverse of the diagonal matrix of the mass. Then\n%\n%  [A+G*DMinv*G'  G] [I    grad]                = [Abar   O  ]\n%  [G'            O] [0  -Dminv*grad'*Me*grad ] = [G'     Ap]\n%\n%  We solve the system by GMRES with  the preconditioner\n%\n%       [I   grad                ]  [Abar O   ]^{-1}\n%       [O  -Dminv*grad'*M_e*grad]  [G'   A_p ]\n%\n% where we compute the inverse Abar by mgHodgeLapE and Ap by mg. \n%\n% Created by Long chen and Jie Zhou on Aug,2015.\n\n\nNf = length(f); \nNg = length(g);\nt = cputime;\n\n%% Parameters\nif ~exist('option','var'), option = []; end\nNdof = Nf + Ng; \noption = mgoptions(option,Ndof);    % parameters\nx0 = option.x0; \ntol = option.tol; \nmaxIt = option.solvermaxit; \nprintlevel = option.printlevel; \nd = size(node,2);\n\n%% Set up auxiliary matrices\nif d == 2\n    area = simplexvolume(node,elem);\n    Mvlump = accumarray([elem(:,1);elem(:,2);elem(:,3)],[area;area;area]/3,...\n                        [max(elem(:)),1]);\nelseif d == 3\n    volume = abs(simplexvolume(node,elem)); % uniform refine in 3D is not orientation presereved\n    Mvlump = accumarray([elem(:,1);elem(:,2);elem(:,3);elem(:,4)],...\n                        [volume;volume;volume;volume]/4,[max(elem(:)),1]);    \nend\nDMinv = spdiags(1./Mvlump(option.isFreeNode),0,Ng,Ng);\nf = f + G*(DMinv*g);  % add second equation to the first one\nAbar = A + G*DMinv*G'; % Hodge Laplacian\nAp = grad'*M*grad;    % scalar Laplacian\n\n%% Set up matrices for multigrid\nsetupOption.solver = 'NO';\nsetupOption.isFreeEdge = option.isFreeEdge;\nsetupOption.freeDof = option.isFreeNode;\n[~,~,Ai_N,Bi_N,BBi_N,Res_N,Pro_N] = mg(Ap,g,elem,setupOption);\n[x,info,Ai,Bi,BBi,Res,Pro] = mgHodgeLapE(Abar,f,node,elem,bdFlag,setupOption); %#ok<*ASGLU>\n\n%% Form a big matrix equation\nbigA = [Abar G; G' sparse(Ng,Ng)];\nbigF = [f; g];\n\n%% Preconditioned GMRES\n% options for V-cycle of Schur complement\nif strcmp(option.solver,'CG') % change default set up in mgoption \n   option.solver = 'Vcycle';\nend\nif isfield(option,'Vit')\n   option.solvermaxIt = option.Vit;\nelse\n   option.solvermaxIt = 1; \nend\noption.setupflag = false;\noption.x0 = zeros(Nf,1);\noption.printlevel = 0;\nApmgoption.printlevel = 0;\nApmgoption.printlevel = 0;\nApmgoption.setupflag = false;\nApmgoption.maxIt     = 1;\n% minres for the saddle point system\n[x,flag,stopErr,itStep,err] = gmres(bigA,bigF,20,tol,maxIt,@tripre,[],x0);\nitStep = (itStep(1)-1)*20 + itStep(2); % total iteration\nu = x(1:Nf);\np = x(Nf+1:end);\n\n%% Output\ntime = cputime - t;\nif printlevel >= 1\n    fprintf('Triangular Preconditioned GMRES \\n');\n    fprintf('#dof: %8.0u,  #nnz: %8.0u, V-cycle: %2.0u, iter: %2.0u,   err = %8.2e,   time = %4.2g s\\n',...\n                 Ndof, nnz(bigA), option.solvermaxIt, itStep, stopErr, time)\nend\nif (flag == 1) && (printlevel>0)\n   fprintf('NOTE: the iterative method does not converge! \\n');    \nend\ninfo = struct('solverTime',time,'itStep',itStep,'error',err,'flag',flag,'stopErr',stopErr);\n  \n%% Preconditioner   \n    function e  = tripre(r)\n        r1 = r(1:Nf);\n        r2 = r(Nf+1:end);\n        e1 = mgHodgeLapE(Abar,r1,node,elem,bdFlag,option,Ai,Bi,BBi,Res,Pro); \n        e2 = mg(Ap,r2-G'*e1,elem,Apmgoption,Ai_N,Bi_N,BBi_N,Res_N,Pro_N);\n        e  = [e1 + grad*e2; -DMinv*(Ap*e2)];\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/solver/tripreMaxwellsaddle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.570271848201915}}
{"text": "function x = nsctrec(y, dfilt, pfilt)\n% NSCTREC   Nonsubsampled Contourlet Reconstruction\n%\n%\tx = nsscrec(y, [dfilt, pfilt] )\n%\n% INPUT:\n%   y:  a cell vector of length length(nlevs) + 1, where except y{1} is \n%       the lowpass subband, each cell corresponds to one pyramidal\n%       level and is a cell vector that contains bandpass directional\n%       subbands from the DFB at that level.\n%   dfilt:  \n%       a string, filter name for the directional decomposition step.\n%       It is optional with default value 'dmaxflat7'. See dfilters.m for all\n%       available filters.\n%   pfilt:  \n%       a string, filter name for the pyramidal decomposition step.\n%       It is optional with default value 'maxflat'. See atrousfilters.m for \n%       all available filters. \n%\n% OUTPUT:\n%   x:      \n%       a matrix, reconstructed image\n%\n% See also: ATROUSFILTERS, DFILTERS, NSCTDEC, NSFBREC, NSDFBREC\n\n%\n% HISTORY:\n%     02/17/04 Created by Jianping Zhou.\n%     08/07/04 Modified by Jianping Zhou. Incorporte the fast implementation \n%              of convolution algorithm by Jason Laska.\n%     08/30/04 Modified by Arthur. L. Cunha, added more pyramid filters.\n%     10/17/04 Modified by Arthur. L. Cunha, replaced periodic with symmetric extension\n%     01/24/05 Modified by Jianping Zhou, changed function names and corrected a bug. \n%     10/31/05 Modified by Arthur L Cunha, corrected a bug in the pyramid decomposition (a wrong index)\n\n\n% Check input\nif ~exist('dfilt', 'var')\n    dfilt = 'dmaxflat7' ;\nend;\n\nif ~exist('pfilt', 'var')\n    pfilt = 'maxflat' ; \nend;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Get fan filters, parallelogram filters, and pyramid filters\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Get the directional filters for the critically sampled DFB.\nfilters = cell(4) ;\n[h1, h2] = dfilters(dfilt, 'r');\n% A scale is required for the nonsubsampled case.\nh1 = h1./sqrt(2) ;\nh2 = h2./sqrt(2) ;\n\n% Generate the first-level fan filters by modulations.\nfilters{1} = modulate2(h1, 'c');\nfilters{2} = modulate2(h2, 'c'); \n\n% Obtain the parallelogram filters from the diamond filters\n[filters{3}, filters{4}] = parafilters( h1, h2 ) ;\n\n% Currently only one filter by Arthur Cunha\n% It has been normalized.\n[h1, h2, g1, g2] = atrousfilters(pfilt) ; \n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Nonsubsampled Contourlet transform with tree structure filter banks\n% Nonsubsampled pyramids make multiresolution decomposition.\n% Nonsubsampled directional filter banks make directional decomposition.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nn = length(y) - 1;\nxlo = y{1};\nnIndex = n-1;\nfor i=1:n\n    \n    % Process the detail subbands\n    if iscell( y{i+1} )\n        % Nonsubsampled DFB reconstruction\n        xhi = nsdfbrec( y{i+1}, filters ); \n    else\n        % No DFB decomposition, copy directly\n        xhi = y{i+1};\n    end\n                 \n    % Nonsubsampled Pyramid reconstruction\n    x = nsfbrec(xlo, xhi, g1, g2, nIndex);            \n        \n    % Prepare for the next level\n    xlo = x ;\n    nIndex = nIndex -1;     \nend", "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/nsct_toolbox/nsctrec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5702718445348115}}
{"text": "%% autoEncoder class\n%\n% Copyright (c) 2018-present, Mahmoud Afifi\n% York University, Canada\n% mafifi@eecs.yorku.ca | m.3afifi@gmail.com\n%\n% This source code is licensed under the license found in the\n% LICENSE file in the root directory of this source tree.\n% All rights reserved.\n%\n% Please cite the following work if this program is used:\n% Mahmoud Afifi, Brian Price, Scott Cohen, and Michael S. Brown, \n% \"When color constancy goes wrong: Correcting improperly white-balanced \n% images\", CVPR 2019.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%\n\nclassdef autoEnc\n    properties\n        weights\n        bias\n    end\n    methods\n        function feature = encode(obj,hist)\n            feature = (obj.sigmf(obj.weights * reshape(hist,[],1) + obj.bias,[1,0]))';\n        end\n        function y = sigmf(obj, x, params)\n            a = cast(params(1),'like',x);\n            c = cast(params(2),'like',x);\n            y = 1./(1 + exp(-a*(x-c)));\n            \n        end\n    end\nend", "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/classes/autoEnc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5702718398283771}}
{"text": "%% FUNCTION Least_msmtfl_capL1\n%   Multi-Stage Multi-Task Feature Learning\n%\n%% OBJECTIVE\n%   min_W ||XW - Y||_F^2 + lambda*\\sum_i \\min{||W^i||_1,theta}\n%\n%   It's a nonconvex optimization problem, which can be relaxed into a Multi-Stage Convex optimization:\n%   min_W ||XW - Y||_F^2 + \\sum_i{gamma_i*||W^i||_1}\n%\n%% INPUT\n%   X: {n * d} * t - input matrix\n%   Y: {n * 1} * t - output matrix\n%   lambda: regularized parameter (vector)\n%   theta: theresholding paramter\n%\n%   (Optional)\n%   opts.lFlag: estimate the upper bound of Lipschitz constant if nonzero, zero otherwise \n%\n%% OUTPUT\n%   W: output weight\n%   fun: function values\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 pubtolwlished 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 <http://www.gnu.org/licenses/>.\n%\n%   Copyright (C) 2011 - 2012 Jiayu Zhou, Pinghua Gong 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 Dec 18, 2012.\n%\n%\n%% RELATED PAPERS\n%\n% [1] Pinghua Gong, Jieping Ye, Changshui Zhang. Multi-Stage Multi-Task \n%     Feature Learning. The 26th Annual Conference on Neural Information \n%     Processing Systems (NIPS 2012), Lake Tahoe, Nevada, USA, \n%     December 3-6, 2012.\n%\n%% RELATED FUNCTIONS\n%  init_opts, combine_input (utils)\n\nfunction [W,funcVal] = Least_msmtfl_capL1(X, Y, lambda, theta, opts)\n\nif nargin <4\n    error('\\n Inputs: X, Y, and lambda1, and lambda2 should be specified!\\n');\nend\nif nargin <5\n    opts = [];\nend\n\n% initialize options.\nopts=init_opts(opts);\n\n% initial Lipschiz constant. \nif isfield(opts, 'lFlag')\n    lFlag = opts.lFlag;\nelse\n    lFlag = false;\nend\n\ntask_num = length(X);\n[X, y, ~, samplesize] = combine_input(X, Y);\ndimension = size(X, 2);\n\n% initialize a starting point\nif opts.init==2\n    W0 = zeros(dimension, task_num);\nelseif opts.init == 0\n    W0 = randn(dimension, task_num);\nelse\n    if isfield(opts,'W0')\n        W0=opts.W0;\n        if (nnz(size(W0)-[dimension, task_num]))\n            error('\\n Check the input .P0');\n        end\n    else\n        W0=randn(dimension, task_num);\n    end\nend\n\n% Set an array to save the objective value\nfuncVal = [];\n\nW = W0;\n\n[d,m] = size(W); % d: dimension, m: the number of tasks\nX = diagonalize(X,samplesize);\nXtX = X'*X; Xty = X'*y;\n\nL1norm = max(sum(abs(X),1)); Linfnorm = max(sum(abs(X),2));\n\nif lFlag\n    % Upper bound for largest eigenvalue of Hessian matrix\n    L = 2*min([L1norm*Linfnorm; size(X,1)*Linfnorm*Linfnorm; size(X,2)*L1norm*L1norm; size(X,1)*size(X,2)*max(abs(X(:)))]);\nelse\n    % Lower bound for largest eigenvalue of Hessian matrix\n    L = 2*max(L1norm*L1norm/size(X,1),Linfnorm*Linfnorm/size(X,2));\nend\n% Initial function value\nfuncVal = cat(1, funcVal, norm(X*W(:) - y)^2 + lambda*(sum(min(sum(abs(W),2),theta))));\n\ntolw = 1e-5; % precision for inner iterations. \n\nfor iter = 1:opts.maxIter\n    if iter == 1\n        weight = lambda*ones(d,m);\n    else\n        weight = lambda*(repmat(sum(abs(W),2) < theta,1,m));\n    end\n    [W,~,iterw] = wLassomtl(X,y,XtX,Xty,weight,W,tolw,100,L,lFlag);\n    \n\n    if iterw == 1\n        tolw = tolw/4;\n    end\n    \n    funcVal = cat(1, funcVal, norm(X*W(:) - y)^2 + lambda*(sum(min(sum(abs(W),2),theta))));\n    \n    % stopping condition\n    switch(opts.tFlag)\n        case 0\n            if iter>=2\n                if (abs( funcVal(end) - funcVal(end-1) ) <= opts.tol)\n                    break;\n                end\n            end\n        case 1\n            if iter>=2\n                if (abs( funcVal(end) - funcVal(end-1) ) <=...\n                        opts.tol* funcVal(end-1))\n                    break;\n                end\n            end\n        case 2\n            if ( funcVal(end)<= opts.tol)\n                break;\n            end\n        case 3\n            if iter>=opts.maxIter\n                break;\n            end\n    end\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/Least_msmtfl_capL1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5702718387890469}}
{"text": "function [doy, year] = mydatedoy (epoch, year)\n    if (nargin < 2),  year = [];  end\n    if (size(epoch,2) == 1)\n        % epoch is in mydatenum format\n        num = epoch;\n        vec = mydatevec(num);\n    else\n        % epoch is in mydatevec format\n        vec = epoch;\n        num = mydatenum(vec);\n    end\n    clear epoch\n\n    %% now define the epoch corresponding to the beginning to that year:\n    if isempty(year),  year = vec(:,1);  end\n    if ischar(year) && any(strcmpi(year, {'median','fixed'}))\n        year = median(vec(:,1));\n    end\n    vec0 = zeros(size(vec));\n    vec0(:,1) = year;\n    num0 = mydatenum(vec0);\n\n    %%\n    doy = (num - num0) ./ (3600 .* 24);\nend\n\n%!test\n%! d = [2000 1 1 0 0 0];\n%! doy_correct = 1;\n%! doy_answer = mydatedoy(mydatenum(d));\n%! myassert (doy_answer, doy_correct);\n\n%!test\n%! d = [2000 1 30 0 0 0];\n%! doy_correct = 30;\n%! doy_answer = mydatedoy(mydatenum(d));\n%! myassert (doy_answer, doy_correct);\n\n%!test\n%! d = [2000 2 1 0 0 0];\n%! doy_correct = 32;\n%! doy_answer = mydatedoy(mydatenum(d));\n%! myassert (doy_answer, doy_correct);\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/31065-mydate/mydate/mydate/mydatedoy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5702205055716247}}
{"text": "function [Ain,Cin,bin,fin] = sparse_NMF_initialization(Y,K,options) %beta,eta,X0,err_thr,max_iter)\n\nT = size(Y,ndims(Y));\nif ~ismatrix(Y)\n    Y = reshape(Y,numel(Y)/T,T);\nend\n\ndefoptions = CNMFSetParms;\nif nargin < 3 || isempty(options); options = defoptions; end\nif ~isfield(options,'snmf_max_iter'); options.snmf_max_iter = defoptions.snmf_max_iter; end\n    max_iter = options.snmf_max_iter;\nif ~isfield(options,'err_thr'); options.err_thr = defoptions.err_thr; end\n    err_thr = defoptions.err_thr;\nif ~isfield(options,'eta'); options.eta = defoptions.eta; end\n    eta = options.eta*max(Y(:))^2;\nif ~isfield(options,'beta'); options.beta = defoptions.beta; end\n    beta = options.beta;\nif ~isfield(options,'nb'), options.nb = defoptions.nb; end \n    nb = options.nb;\n    \nC = rand(K,T);\n\nrepeat = 1;\niter = 1;\nobj_ = 1e-10;\n\nv = ver;\nflag_optim = any(strcmp('Optimization Toolbox', {v.Name})); % check if optimization toolbox is present\nif flag_optim\n    if verLessThan('optim','6.3')\n        min_options = optimset('Algorithm','interior-point','GradObj','On','Display','Off');\n    else\n        min_options = optimoptions('fmincon','Algorithm','interior-point','GradObj','On','Display','Off');\n    end\nend\n\n% remove median\nmedY = median(Y, 2);\nY = bsxfun(@minus, Y, medY);\n\nwhile (iter <= max_iter) && repeat\n    A = max((Y*C')*pinv(C*C'+beta*ones(K,K)),0);\n    C = max((A'*A + eta*eye(K))\\(A'*Y),0);\n    \n    ff = find(sum(C,2)==0);\n    if ~isempty(ff)\n        A(:,ff) = [];\n        C(ff,:) = [];\n        K = K - length(ff);\n    end\n    \n    iter = iter + 1;\n    if mod(iter,10) == 0;\n        A = threshold_components(A,options);\n        nC = sum(C.^2,2);\n        AA = A'*A;\n        mine = @(e) min_e(e,beta,eta,nC,A,AA);\n        \n        e = (eta*nC./(beta*A'*sum(A,2))).^(1/4);\n        if flag_optim\n            e = fmincon(mine,max(e,1e-4),[],[],[],[],1e-4*ones(K,1),[],[],min_options);\n        end\n        C = diag(e)\\C;\n        A = A*diag(e);\n        fprintf('%i out of maximum %i iterations done \\n',iter,max_iter);\n    end\n    obj = norm(Y - A*C,'fro')^2 + eta*norm(C,'fro')^2 + beta*norm(sum(A,2))^2;\n    repeat = abs(obj - obj_) > err_thr*obj_;\n    obj_ = obj;\nend\n\nfprintf('Algorithm converged after %i iterations. \\n',iter-1);\n\n[Ain,Cin] = order_components(A,C);\n[bin,fin] = nnmf(max(Y - Ain*Cin + repmat(medY,1,T),0),nb);\n\n    function [f,grad] = min_e(e,beta,eta,nC,A,AA)\n        f = eta*norm(sqrt(nC)./e)^2 + beta*norm(A*e)^2;\n        grad = -2*eta*nC./(e.^3) + 2*beta*AA*e;\n    end\n\n\n    function [A_or,C_or] = order_components(A,C)\n        nA = sqrt(sum(A.^2));\n        nr = length(nA);\n        A = A/spdiags(nA(:),0,nr,nr);\n        mA = max(A);\n        C = spdiags(nA(:),0,nr,nr)*C;\n        nC2 = sqrt(sum(C.^2,2));\n        mC = max(C,[],2);\n        [~,srt] = sort(mC.*mA'./nC2,'descend');\n        A_or = A(:,srt);\n        C_or = C(srt,:);\n    end\n\nend", "meta": {"author": "zhoupc", "repo": "CNMF_E", "sha": "ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f", "save_path": "github-repos/MATLAB/zhoupc-CNMF_E", "path": "github-repos/MATLAB/zhoupc-CNMF_E/CNMF_E-ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f/ca_source_extraction/utilities/sparse_NMF_initialization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5701495578015441}}
{"text": "%DEMO_DERIVATIVEOBS  Regression problem demonstration with derivative \n%                    observations\n%\n%  Description\n%    The regression problem consist of a data with one input variable,\n%    two output variables with Gaussian noise; observations and \n%    derivative observations. The constructed model is full GP with\n%    Gaussian likelihood.\n%\n%    The covariance matrix K includes now also covariances between\n%    derivative observations and between derivative and latent\n%    observations. With derivative observations, the K matrix is a\n%    block matrix with following blocks:\n%\n%        K = [K_ll K_Dl'; K_Dl K_DD]\n%\n%    Where D refers to derivative and l to latent observation and\n%       K_ll = k(x_i, x_j | th)\n%       K_Dl = d k(x_i, x_j | th) / dx_i\n%       K_DD = d^2 k(x_i, x_j | th) / dx_i dx_j\n%\n%    To include derivative observations in the inference:\n%\n%       - provide partial derivative observations in the\n%       observation vector after output observations\n%       y=[y;dy_1;...;dy_n]; for ex. if size(x)=[10 2] ->\n%       size(y)=[30 1]\n%\n%       - gp_set(gp, 'derivobs', 'on')\n%\n%   The demo is organised in two parts:\n%     1) data analysis without derivative observations\n%     2) data analysis with derivative observations\n%\n%  See also  DEMO_REGRESSION1\n%\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\ntp=9;                                  %number of training points -1\nx=[-2:4/tp:2]';\ny=sin(x).*cos(x).^2;                   % The underlying process\ndy=cos(x).^3 - 2*sin(x).^2.*cos(x);    % Derivative of the process\nns=0.06;                               % noise standard deviation\n\n% Add noise\ny=y + ns*randn(size(y));\n% derivative observations are also noisy\ndy=dy + ns*randn(size(dy));           \n% observation vector with derivative observations\ny2=[y;dy];\n\n% test points\nxt=[-3:0.05:3]';\nnt=length(xt);\n\n%========================================================\n% PART 1 GP model without derivative obs\n%========================================================\ndisp('GP model without derivative obs')\n\n% Covariance function\npl = prior_t();\npm = prior_sqrtt();\ngpcf = gpcf_sexp('lengthScale', 0.5, 'magnSigma2', .5, ...\n                 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\n% Use default Gaussian likelihood\ngp = gp_set('cf', gpcf);\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% Do the prediction\n[Eft, Varft] = gp_pred(gp, x, y, xt);\n\n% PLOT THE DATA\n\nfigure\n%m=shadedErrorBar(p,Eft(1:size(xt)),2*sqrt(Varft(1:size(xt))),{'k','lineWidth',2});\nsubplot(2,1,1)\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(1:length(x)), 'ro','markerSize',7,'MarkerFaceColor','r');\nhold on\nh=plot(xt,sin(xt).*cos(xt).^2,'b--','lineWidth',2);\n%legend([m.mainLine m.patch h hav],'prediction','95%','f(x)','observations');\nlegend([m m95 h hav],'prediction','95%','f(x)','observations');\ntitle('GP without derivative observations')\nxlabel('input x')\nylabel('output y')\n\n%========================================================\n% PART 2 GP model with derivative obs\n%========================================================\ndisp('GP model with derivative obs')\n\n% Option derivobs set so that the derivatives are in use\ngp = gp_set('cf', gpcf, 'derivobs', 'on');\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,y2,'opt',opt);\n% Do the prediction\n[Eft2, Varft2] = gp_pred(gp, x, y2, xt);\n% Use predictions for function values only\nEft2=Eft2(1:nt);Varft2=Varft2(1:nt);\n\n% PLOT THE DATA\n% plot lines indicating the derivative\n\nsubplot(2,1,2)\nm=plot(xt,Eft2,'k','lineWidth',2);\nhold on\nplot(xt,Eft2+2*sqrt(Varft2),'k--')\nhold on\nm95=plot(xt,Eft2-2*sqrt(Varft2),'k--');\nhold on\nhav=plot(x, y(1:length(x)), 'ro','markerSize',7,'MarkerFaceColor','r');\nhold on\nh=plot(xt,sin(xt).*cos(xt).^2,'b--','lineWidth',2);\n\nxlabel('input x')\nylabel('output y')\ntitle('GP with derivative observations')\n\ni1=0;\na=0.1;\nddx=zeros(2*length(x),1);\nddy=zeros(2*length(x),1);\nfor i=1:length(x)\n  i1=i1+1;\n  ddx(i1)=x(i)-a;\n  ddy(i1)=y(i)-a*dy(i);\n  i1=i1+1;\n  ddx(i1)=x(i)+a;\n  ddy(i1)=y(i)+a*dy(i);\nend\n\nfor i=1:2:length(ddx)\n  hold on\n  dhav=plot(ddx(i:i+1), ddy(i:i+1),'r','lineWidth',2);\nend\nlegend([m m95 h hav dhav],'prediction','95%','f(x)','observations','der. obs.');\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_derivativeobs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430604060731, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5701221346554084}}
{"text": "function [d] = triangle2distance(tri, pos, s, maxinitdist)\n\n% TRIANGLE2DISTANCE computes the geodesic distance (across the edges) on a\n% mesh, using Dijkstra's algorithm. The Dijkstra code is an efficient\n% vectorized version of a function from MIT's graphtool toolbox, operating\n% on an adjacency matrix.\n%\n% Use as\n%   d = triangle2distance(tri, pos, s)\n%\n% Input arguments:\n%   tri = Mx3 matrix describing the triangles\n%   pos = Nx3 matrix describing the position of the vertices\n%   s   = (can be empty), scalar or vector with indices for the points for\n%         which the distance (to all other points) will be computed. If\n%         empty or not defined, all points will be considered.\n%\n% Output argument:\n%   d   = Nxnumel(s) distance matrix\n\n% Copyright (C) 2015, 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 <http://www.gnu.org/licenses/>.\n%\n% $Id:$\n\nadj = triangle2connectivity(tri, pos);\nn   = length(adj);\nif nargin<3 || isempty(s)\n  s  = 1:n;\nend\nif nargin<4\n  maxinitdist = inf;\nend\nns = length(s);\n\n\nd    = inf*ones(n,ns); % distance s-all nodes\nfor k = 1:ns\n  d(s(k),k) = 0; % s-s distance\nend\n\nfor k = 1:ns\n  if mod(k,10)==0,\n    fprintf('computing distance between node %d and nodes 1:%d\\n', s(k), n);\n  end\n  T = 1:n;    % node set with shortest paths not found\n  \n  if isfinite(maxinitdist)\n    initd = sqrt(sum((pos-pos(s(k),:)).^2,2));\n    T(initd>=maxinitdist) = [];\n  end\n  \n  %while ~isempty(T) %%% a for-loop goes ~10% faster, and we know how often\n  %we need to iterate\n  for m = 1:n\n    if mod(m,1000)==0,\n      fprintf('looping across vertices %d/%d\\n', m, n);\n    end\n    [dmin,ind] = min(d(T,k));\n    \n    adj_ = adj(T,T(ind));\n    d_   = d(T,k);\n    \n    % logic: shrink the distance if there's an edge (adj_>0) AND if it's\n    % shorter to travel through this edge\n    criterion = adj_ > 0 & d_ > d(T(ind),k)+adj_;\n    d(T(criterion),k) = d(T(ind),k) + adj_(criterion);\n    \n    T(ind) = [];\n  end\nend\n\n% the below code is from MIT's graphtool toolbox. the above code that\n% computes the distance based on an adjacency matrix is taken from there,\n% but the vectorized functionality is ~10 times as fast.\n\n\n% Implements a simple version of the Dijkstra shortest path algorithm\n% Returns the distance from a single vertex to all others, doesn't save the path\n% INPUTS: adjacency matrix (adj), start node (s)\n% OUTPUTS: shortest path length from start node to all other nodes\n% Note: works with a weighted/directed matrix\n% GB, Last Updated: December 13, 2004\n\n% Copyright (c) 2011, Massachusetts Institute of Technology.\n% All rights reserved.\n% Redistribution and use in source and binary forms, with or without modification, \n% are permitted provided that the following conditions are met:\n%\n%    Redistributions of source code must retain the above copyright notice, this list\n%    of conditions and the following disclaimer.\n%    Redistributions in binary form must reproduce the above copyright notice, this list \n%    of conditions and the following disclaimer in the documentation and/or other materials \n%    provided with the distribution.\n%    Neither the name of the Massachusetts Institute of Technology nor the names of its \n%    contributors may be used to endorse or promote products derived from this software without \n%    specific prior written permission.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR \n% IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \n% FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR \n% CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL \n% DAMAGES (INCLUDING, 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 LIABILITY, WHETHER \n% IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF \n% THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n% function d = simple_dijkstra(adj,s)\n% \n% n=length(adj);\n% d = inf*ones(1,n); % distance s-all nodes\n% d(s) = 0;    % s-s distance\n% T = 1:n;    % node set with shortest paths not found\n% \n% while not(isempty(T))\n%     [dmin,ind] = min(d(T));\n%     for j=1:length(T)\n%         if adj(T(ind),T(j))>0 & d(T(j))>d(T(ind))+adj(T(ind),T(j))\n%             d(T(j))=d(T(ind))+adj(T(ind),T(j));\n%         end\n%     end \n%     T = setdiff(T,T(ind));\n%     \n% end\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/private/triangle2distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5701221342533452}}
{"text": "function [y, dh_struct] = findgrad(X_struct, f, e, varargin)\n\n[X_vec, X_template] = struct2vector(X_struct);\n\n[y] = feval(f, X_struct, varargin{:});\n\ndh = nan(length(X_vec),1) ;\n\nfor j = 1:length(X_vec)\n  \n  dx = zeros(length(X_vec),1);\n  dx(j) = dx(j) + e;\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  dh(j) = (y2 - y1)/(2*e);\nend\n\ndh_struct = vector2struct(dh, X_template);", "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/findgrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5701221321884291}}
{"text": "function [SeqR1s,SeqR5s]=MADAll(fea_Train,gnd_Train,fea_Test,gnd_Test,testDims,wgts)\n%Nearest neighbor classifier with MAD measure and symmetric matching\n\nnTrain = size(fea_Train,1);\nnTest = size(fea_Test,1);\nnDim=length(testDims);%number of feature dimensions to test\nSeqR1s=zeros(nDim,1);%Rank 1 recognition rate based on matching gait sequences\nSeqR5s=zeros(nDim,1);%Rank 5 recognition rate based on matching gait sequences\n\nfor iDim=1:nDim\n    Dim=testDims(iDim);\n    feaTrn=fea_Train(:,1:Dim);\n    feaTst=fea_Test(:,1:Dim);\n    DMat=MAD(feaTrn,feaTst, wgts);%This is the MAD distance matrix\n    [SeqR1s(iDim,1),SeqR5s(iDim,1)]=SeqDist(DMat,gnd_Train,gnd_Test);\nend\n\n%Calculate matching scores between each training/test sample pair\nfunction D = MAD(feaTrn, feaTst, wgts)\nif size(wgts,2)==1, wgts=wgts';end\n[numTst,p] = size(feaTst);\nnumTrn = size(feaTrn,1);\nwgts=wgts(1:p);\nD = zeros(numTst,numTrn);\nfor i=1:numTst\n    for j=1:numTrn\n        A=feaTst(i,:);\n        B=feaTrn(j,:);\n        % the following two lines calculate the MAD between A and B        \n        dist=sum(sum(sum(A.*B./wgts)));\n        D(i,j)=-dist/(norm(A(:))*norm(B(:)));    \n    end\nend\n\n%The recognition rate between two sequences\nfunction [SeqR1,SeqR5]=SeqDist(DMat,gnd_Train,gnd_Test)\ntrnSeqs=unique(gnd_Train);\nnumTrnSeq=length(trnSeqs);\n\ntstSeqs=unique(gnd_Test);\nnumTstSeq=length(tstSeqs);\n\nSeqDMat=zeros(numTstSeq,numTrnSeq);\nfor i=1:numTstSeq\n    idxs_i=find(gnd_Test==tstSeqs(i));\n    iMat=DMat(idxs_i,:);\n    for j=1:numTrnSeq\n        idxs_j=find(gnd_Train==trnSeqs(j));\n        jMat=iMat(:,idxs_j);\n        SeqDMat(i,j)=mean(min(jMat,[],1))+mean(min(jMat,[],2));\n    end\nend\n[minDs,minIdxs]=min(SeqDMat, [], 2);%Minimum distance implies best match\nIDs=trnSeqs(minIdxs);\nSeqR1=sum(IDs==tstSeqs)/numTstSeq;%Rank 1\n\n[stDs,stIdxs]=sort(SeqDMat,2);\nIDs=trnSeqs(stIdxs(:,1:5));\ntstSeqs5=repmat(tstSeqs,1,5);\nSeqR5=sum(sum(IDs==tstSeqs5))/numTstSeq;%Rank 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/26168-multilinear-principal-component-analysis-mpca/MPCACodes/MADAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757313, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5701221231792395}}
{"text": "function beta = lars(X, y, method, stop, useGram, Gram, Cardi, bSparse, trace)\n% This function is provided at\n% http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=3897\n% I have made some small modifications  -- Deng Cai, Feb/2008\n\n% LARS  The LARS algorithm for performing LAR or LASSO.\n%    BETA = LARS(X, Y) performs least angle regression on the variables in\n%    X to approximate the response Y. Variables X are assumed to be\n%    normalized (zero mean, unit length), the response Y is assumed to be\n%    centered.\n%    BETA = LARS(X, Y, METHOD), where METHOD is either 'LARS' or 'LASSO'\n%    determines whether least angle regression or lasso regression should\n%    be performed.\n%    BETA = LARS(X, Y, METHOD, STOP) with nonzero STOP will perform least\n%    angle or lasso regression with early stopping. If STOP is negative,\n%    STOP is an integer that determines the desired number of variables. If\n%    STOP is positive, it corresponds to an upper bound on the L1-norm of\n%    the BETA coefficients.\n%    BETA = LARS(X, Y, METHOD, STOP, USEGRAM) specifies whether the Gram\n%    matrix X'X should be calculated (USEGRAM = 1) or not (USEGRAM = 0).\n%    Calculation of the Gram matrix is suitable for low-dimensional\n%    problems. By default, the Gram matrix is calculated.\n%    BETA = LARS(X, Y, METHOD, STOP, USEGRAM, GRAM) makes it possible to\n%    supply a pre-computed Gram matrix. Set USEGRAM to 1 to enable. If no\n%    Gram matrix is available, exclude argument or set GRAM = [].\n%    BETA = LARS(X, Y, METHOD, STOP, USEGRAM, GRAM, TRACE) with nonzero\n%    TRACE will print the adding and subtracting of variables as all\n%    LARS/lasso solutions are found.\n%    Returns BETA where each row contains the predictor coefficients of\n%    one iteration. A suitable row is chosen using e.g. cross-validation,\n%    possibly including interpolation to achieve sub-iteration accuracy.\n%\n% Author: Karl Skoglund, IMM, DTU, kas@imm.dtu.dk\n% Reference: 'Least Angle Regression' by Bradley Efron et al, 2003.\n\n%% Input checking\n% Set default values.\nif nargin < 9\n    trace = 0;\nend\nif nargin < 8\n    bSparse = 1;\nend\nif nargin < 7\n    Cardi = [];\nend\nif nargin < 6\n    Gram = [];\nend\nif nargin < 5\n    useGram = 0;\nend\nif nargin < 4\n    stop = 0;\nend\nif nargin < 3\n    method = 'lasso';\nend\nif strcmpi(method, 'lasso')\n    lasso = 1;\nelse\n    lasso = 0;\nend\n\nif isempty(X)\n    error('The code has been updated. Please input the X');\nend\n\n\n%% LARS variable setup\n[n p] = size(X);\n% nvars = min(n-1,p); %\nnvars = p; %\n\nmaxk = 512*nvars; % Maximum number of iterations\n\nif isempty(Cardi)\n    if stop == 0\n        if bSparse\n            beta = sparse(p,2*nvars);\n        else\n            beta = zeros(p,2*nvars);\n        end\n    elseif stop < 0\n        if bSparse\n            beta = sparse(p,2*round(-stop));\n        else\n            beta = zeros(p,2*round(-stop));\n        end\n    else\n        if bSparse\n            beta = sparse(p,100);\n        else\n            beta = zeros(p,100);\n        end\n    end\nelse\n    Cardi = unique(Cardi);\n    Cardi(Cardi>nvars) = [];\n    stop = -max(Cardi);\n    if bSparse\n        beta = sparse(p,length(Cardi));\n    else\n        beta = zeros(p,length(Cardi));\n    end\n    betak = zeros(p,1);\nend\n\nmu = zeros(n, 1); % current \"position\" as LARS travels towards lsq solution\nI = 1:p; % inactive set\nA = []; % active set\n\n% Calculate Gram matrix if necessary\nif isempty(Gram) && useGram\n    error('The code has been updated. Please input the Gram');\n%     clear Gram;\n%     global Gram;\n    %   Gram = X'*X; % Precomputation of the Gram matrix. Fast but memory consuming.\nend\n\nif ~useGram\n    R = []; % Cholesky factorization R'R = X'X where R is upper triangular\nend\n\n\nlassocond = 0; % LASSO condition boolean\nstopcond = 0; % Early stopping condition boolean\nk = 0; % Iteration count\nvars = 0; % Current number of variables\n\nif trace\n    disp(sprintf('Step\\tAdded\\tDropped\\t\\tActive set size'));\nend\n\n% TimeLoop = zeros(2*nvars,1);\ntmpT = cputime;\n\n%% LARS main loop\nwhile vars < nvars && ~stopcond && k < maxk\n    k = k + 1;\n    c = X'*(y - mu);\n    [C j] = max(abs(c(I)));\n    j = I(j);\n\n    if ~lassocond % if a variable has been dropped, do one iteration with this configuration (don't add new one right away)\n        if ~useGram\n            diag_k = X(:,j)'*X(:,j); % diagonal element k in X'X matrix\n            if isempty(R)\n                R = sqrt(diag_k);\n            else\n                col_k = X(:,j)'*X(:,A); % elements of column k in X'X matrix\n                R_k = R'\\col_k'; % R'R_k = (X'X)_k, solve for R_k\n                R_kk = sqrt(diag_k - R_k'*R_k); % norm(x'x) = norm(R'*R), find last element by exclusion\n                R = [R R_k; [zeros(1,size(R,2)) R_kk]]; % update R\n            end\n        end\n        A = [A j];\n        I(I == j) = [];\n        vars = vars + 1;\n        if trace\n            disp(sprintf('%d\\t\\t%d\\t\\t\\t\\t\\t%d', k, j, vars));\n        end\n    end\n\n    s = sign(c(A)); % get the signs of the correlations\n\n    if useGram\n        if vars <= 200\n            R = chol(Gram(A,A));\n        elseif lassocond\n            if (rJ <= 200) & vars <= 1000\n                R = chol(Gram(A,A));\n            else\n                R(:,rJ) = []; % remove column j\n                tmpn = size(R,2);\n                for tmpk = rJ:tmpn\n                    tmpp = tmpk:tmpk+1;\n                    [G,R(tmpp,tmpk)] = planerot(R(tmpp,tmpk)); % remove extra element in column\n                    if tmpk < tmpn\n                        R(tmpp,tmpk+1:tmpn) = G*R(tmpp,tmpk+1:tmpn); % adjust rest of row\n                    end\n                end\n                R(end,:) = []; % remove zero'ed out row\n            end\n        else\n            R_k = R'\\Gram(A(1:end-1),j);\n            R_kk = sqrt(Gram(j,j)-R_k'*R_k);\n            R = [R R_k; [zeros(1,size(R,2)) R_kk]]; % update R\n        end\n        GA1 = R\\(R'\\s);\n        AA = 1/sqrt(sum(GA1.*s));\n        w = AA*GA1;\n    else\n        GA1 = R\\(R'\\s);\n        AA = 1/sqrt(sum(GA1.*s));\n        w = AA*GA1;\n    end\n    u = X(:,A)*w; % equiangular direction (unit vector)\n\n    if vars == nvars % if all variables active, go all the way to the lsq solution\n        gamma = C/AA;\n    else\n        a = X'*u; % correlation between each variable and eqiangular vector\n        temp = [(C - c(I))./(AA - a(I)); (C + c(I))./(AA + a(I))];\n        gamma = min([temp(temp > 0); C/AA]);\n    end\n\n    % LASSO modification\n    if lasso\n        lassocond = 0;\n        if isempty(Cardi)\n            temp = -beta(A,k)./w;\n        else\n            temp = -betak(A)./w;\n        end\n        [gamma_tilde] = min([temp(temp > 0); gamma]);\n        j = find(temp == gamma_tilde);\n        if gamma_tilde < gamma,\n            gamma = gamma_tilde;\n            lassocond = 1;\n        end\n    end\n\n    mu = mu + gamma*u;\n    if isempty(Cardi)\n        if size(beta,2) < k+1\n            if bSparse\n                beta = [beta sparse(p,size(beta,1))];\n            else\n                beta = [beta zeros(p,size(beta,1))];\n            end\n        end\n        beta(A,k+1) = beta(A,k) + gamma*w;\n    else\n        tmpbetak = betak(A) + gamma*w;\n        betak = zeros(p,1);\n        betak(A) = tmpbetak;\n        idx = find(Cardi==vars);\n        if ~isempty(idx)\n            beta(:,idx) = betak;\n        end\n    end\n\n    % Early stopping at specified bound on L1 norm of beta\n    if isempty(Cardi)\n        if stop > 0\n            t2 = sum(abs(beta(:,k+1)));\n            if t2 >= stop\n                t1 = sum(abs(beta(:,k)));\n                s = (stop - t1)/(t2 - t1); % interpolation factor 0 < s < 1\n                beta(:,k+1) = beta(:,k) + s*(beta(:,k+1) - beta(:,k));\n                stopcond = 1;\n            end\n        end\n    end\n\n    % If LASSO condition satisfied, drop variable from active set\n    if lassocond == 1\n        if ~useGram\n            R(:,j) = []; % remove column j\n            tmpn = size(R,2);\n            for tmpk = j:tmpn\n                tmpp = tmpk:tmpk+1;\n                [G,R(tmpp,tmpk)] = planerot(R(tmpp,tmpk)); % remove extra element in column\n                if tmpk < tmpn\n                    R(tmpp,tmpk+1:tmpn) = G*R(tmpp,tmpk+1:tmpn); % adjust rest of row\n                end\n            end\n            R(end,:) = []; % remove zero'ed out row\n        end\n        rJ = j;\n        I = [I A(j)];\n        A(j) = [];\n        vars = vars - 1;\n        if trace\n            disp(sprintf('%d\\t\\t\\t\\t%d\\t\\t\\t%d', k, j, vars));\n        end\n    end\n\n    % Early stopping at specified number of variables\n    if stop < 0\n        stopcond = vars >= -stop;\n    end\n    \n%     TimeLoop(k) = cputime - tmpT;\n%     tmpT = cputime;\n    \n%     if vars < 1000\n%         if mod(vars,500) == 0\n%             tmpT = cputime - tmpT;\n%             disp(['LARS: ',num2str(vars),' features selected. Time: ',num2str(tmpT)]);\n%             tmpT = cputime;\n%         end\n%     elseif vars < 2000\n%         if mod(vars,200) == 0\n%             tmpT = cputime - tmpT;\n%             disp(['LARS: ',num2str(vars),' features selected. Time: ',num2str(tmpT)]);\n%             tmpT = cputime;\n%         end\n%     elseif vars < 3000\n%         if mod(vars,100) == 0\n%             tmpT = cputime - tmpT;\n%             disp(['LARS: ',num2str(vars),' features selected. Time: ',num2str(tmpT)]);\n%             tmpT = cputime;\n%         end\n%     else\n%         if mod(vars,50) == 0\n%             tmpT = cputime - tmpT;\n%             disp(['LARS: ',num2str(vars),' features selected. Time: ',num2str(tmpT)]);\n%             tmpT = cputime;\n%         end\n%     end        \nend\n\nif isempty(Cardi)\n    % trim beta\n    if size(beta,2) > k+1\n        beta(:,k+2:end) = [];\n    end\nend\n\nif k == maxk\n    disp('LARS warning: Forced exit. Maximum number of iteration reached.');\nend\n\n%% To do\n%\n% There is a modification that turns least angle regression into stagewise\n% (epsilon) regression. This has not been implemented.\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/Tools/lars.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.570122114974176}}
{"text": "function ll = mlpLogLikelihood(model)\n\n% MLPLOGLIKELIHOOD Multi-layer perceptron log likelihood.\n% FORMAT\n% DESC computes the log likelihood of a multi-layer perceptron\n% model. For single hidden layer models this is done by wrapping \n% the mlperr command. \n% ARG model : the model structure for computing the log likelihood.\n% RETURN ll : the model log likelihood.\n%\n% SEEALSO : modelLogLikeihood, mlperr\n%\n% COPYRIGHT : Neil D. Lawrence, 2006, 2007\n\n% MLTOOLS\n\n\nif length(model.hiddenDim) == 1\n  ll = -mlperr(model, model.X, model.y);\nelse\n  Y = mlpOut(model, model.X);\n  ll = -0.5*sum(sum((model.Y - Y).^2));\nend\n\nll = ll - size(model.X, 1)/2*log(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/mltools/mlpLogLikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461008, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5701156253066653}}
{"text": "% Test size bounds with varying mesh gradation rates.\nclearvars; clc;\n\naddpath('..')\naddpath(genpath('../utilities/'))\naddpath(genpath('../datasets/'))\naddpath(genpath('../m_map/'))\n\nRESO_TOL = 95; %percentage of resolution in bounds\n\nbbox = [166 176;\t\t% lon_min lon_max\n    -48 -40]; \t\t% lat_min lat_max\nmin_el    = 1e3;  \t\t% minimum resolution in meters.\nmax_el    = 100e3; \t\t% maximum resolution in meters.\nmax_el_ns = 5e3;        % maximum resolution nearshore in meters.\ngrade     = [0.15; 0.25; 0.35]; \t\t% mesh grade in decimal percent.\nR         = 3;    \t\t% number of elements to resolve feature width.\ncoastline = 'GSHHS_f_L1';\ngdat = geodata('shp',coastline,'bbox',bbox,'h0',min_el);\n\nfor i = 1 : 3 % for each grade\n    fh = edgefx('geodata',gdat,...\n        'fs',R,'max_el_ns',max_el_ns,...\n        'max_el',max_el,'g',grade(i));\n    mshopts = meshgen('ef',fh,'bou',gdat,'plot_on',0,'nscreen',5,'proj','trans');\n    mshopts = mshopts.build;\n    m1 = mshopts.grd;\n    \n    [bars,barlen] = GetBarLengths(m1,0);\n    % sort bar lengths in descending order\n    [barlen,IA] = sort(barlen,'descend');\n    bars = bars(IA,:);\n    % get the minimum bar length for each node\n    [B1,IB] = unique(bars(:,1),'last');\n    [B2,IC] = unique(bars(:,2),'last');\n    d1 = NaN*m1.p(:,1); d2 = NaN*m1.p(:,1);\n    d1(B1) = barlen(IB); d2(B2) = barlen(IC);\n    reso = min(d1,d2);\n   \n    reso_in_bounds = 100*sum(reso > min_el & reso < max_el)/length(reso); \n    if reso_in_bounds < RESO_TOL\n        error(['Resolution bounds does not match for grade ' num2str(grade(i)) ...\n               '. Got ' num2str(reso_in_bounds) '% of vertices with resolution in bounds']); \n        exit(1)\n    end\n    disp(['Passed for ' num2str(grade(i)) '. ' ...\n          num2str(reso_in_bounds) '% of vertices have resolution in bounds']); \nend\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/Tests/TestEleSizes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5701156171561842}}
{"text": "function [amppts1,timepts,okflag] = ISM_RIRpow_approx(aa,room,cc,timepts,rt_type,rt_val)\n%ISM_RIRpow_approx  Approximation of ISM RIR power (Lehmann & Johansson's method)\n%\n% [P_VEC,T_VEC,OK_FLAG] = ISM_RIRpow_approx(ALPHA,ROOM,C,T_VEC,RT_TYPE,RT_VAL)\n% \n% This function returns the predicted values of RIR power in P_VEC (as\n% would result from ISM simulations) estimated by means of the EDC\n% approximation method described in: \"Prediction of energy decay in room\n% impulse responses simulated with an image-source model\", J. Acoust. Soc.\n% Am., vol. 124(1), pp. 269-277, July 2008. The values of P_VEC are\n% computed for the time points given as input in T_VEC (in sec), which is\n% assumed to contain increasing values of time. The vector T_VEC (and\n% corresponding vector P_VEC) will be cropped if the numerical computation\n% limits are reached for the higher time values in T_VEC (for which NaNs\n% are generated in P_VEC), in which case the output parameter OK_FLAG will\n% be set to 0 (1 otherwise).\n%\n% The environmental setting is defined via the following input parameters:\n%\n%    ALPHA: 1-by-6 vector, corresponding to each wall's absorption \n%           coefficient: [x1 x2 y1 y2 z1 z2]. Index 1 indicates wall closest\n%           to the origin. E.g.: [0.5 0.5 0.45 0.87 0.84 0.32].\n%  RT_TYPE: character string, measure of reverberation time used for the \n%           definition of the coefficients in ALPHA. Set to either 'T60' or\n%           'T20'. \n%   RT_VAL: scalar, value of the reverberation time (in seconds) defined by\n%           RT_TYPE. E.g.: 0.25.\n%     ROOM: 1-by-3 vector, indicating the rectangular room dimensions \n%           (in m): [x_length y_length z_length]. E.g.: [4 4 3].\n%        C: scalar (in m/s), propagation speed of sound waves. E.g.: 343. \n\n% Release date: November 2009\n% Author: Eric A. Lehmann, Perth, Australia (www.eric-lehmann.com)\n%\n% Copyright (C) 2009 Eric A. Lehmann\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 <http://www.gnu.org/licenses/>.\n\nnumradpts = length(timepts);\nradpts = cc * timepts;              % radius values corresponding to time points\n\nbxx = ( sqrt(1-aa(1))*sqrt(1-aa(2)) )^(1/room(1));\nbyy = ( sqrt(1-aa(3))*sqrt(1-aa(4)) )^(1/room(2));\nbzz = ( sqrt(1-aa(5))*sqrt(1-aa(6)) )^(1/room(3));\n\nif bxx==byy && byy==bzz,\n    intcase = 1;\nelseif bxx==byy && bxx~=bzz,\n    intcase = 2;\nelseif byy==bzz && bzz~=bxx,\n    if bzz<bxx,     % coordinate swap x<->z\n        foo = bxx; bxx = bzz; bzz = foo;\n        intcase = 2;\n    else\n        intcase = 3;\n    end\nelseif bxx==bzz && bzz~=byy,\n    if bzz<byy,     % coordinate swap y<->z\n        foo = byy; byy = bzz; bzz = foo;\n        intcase = 2;\n    else\n        intcase = 4;\n    end\nelse\n    intcase = 5;\n    if bxx>bzz && bxx>byy,      % coordinate swap x<->z\n        foo = bxx; bxx = bzz; bzz = foo;\n    elseif byy>bzz && byy>bxx,\t% coordinate swap y<->z\n        foo = byy; byy = bzz; bzz = foo;\n    end\nend\n\namppts1 = zeros(1,numradpts);\nfor ss=1:numradpts,    % compute amplitude/energy estimates\n    Bx = bxx^(radpts(ss)); Bx(Bx==0) = eps;\n    By = byy^(radpts(ss)); By(By==0) = eps;\n    Bz = bzz^(radpts(ss)); Bz(Bz==0) = eps;\n    switch intcase\n        case 1\n            int2 = Bx;\n        case 2\n            int2 = (Bx-Bz) / log(Bx/Bz);\n        case 3\n            n1 = log(Bz/Bx);\n            int2 = Bz*( expint(n1) + log(n1) + 0.5772156649 ) / n1;\n        case 4\n            n1 = log(Bz/By);\n            int2 = Bz*( expint(n1) + log(n1) + 0.5772156649 ) / n1;\n        otherwise\n            n1 = log(Bz/By);\n            n2 = log(Bz/Bx);\n            int2 = Bz*(log(n1/n2) + expint(n1) - expint(n2)) / log(Bx/By);\n    end\n    amppts1(ss) = int2/radpts(ss);      % 'propto' really...\nend\n\nokflag = 1;\nfoo = find(isnan(amppts1),1);\nif ~isempty(foo),\n    amppts1 = amppts1(1:foo-1);\n    timepts = timepts(1:foo-1);\n    okflag = 0;\nend\n\nif nargin==6,\n    switch lower(rt_type)  % offset correction\n        case 't60', sl = exp(3.05*exp(-1.85*rt_val));\n        case 't20', sl = exp(3.52*exp(-7.49*rt_val));\n    end\n    amppts1 = amppts1 ./ exp(sl*(timepts-timepts(1)));\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/array/imageRIR/Lehmann/ISM_RIRpow_approx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5701156115888477}}
{"text": "close all;\nclear all;\nclc;\n%rng('default');\n% Create the directory for storing images\n[status_code,message,message_id] = mkdir('bin');\n\n% Signal space \nN = 1000;\n% Number of measurements\nM = 200;\nK = 50;\n\nomp_success = 0;\nmc_omp_success = 0;\nfor nt=1:100\n    % Sensing matrix\n    Phi = spx.dict.simple.gaussian_dict(M, N);\n    % Construct the signal generator.\n    gen  = spx.data.synthetic.SparseSignalGenerator(N, K);\n    % Generate bi-uniform signals\n    x = gen.gaussian;\n    % Measurement vectors\n    y = Phi.apply(x);\n\n\n    % OMP solver instance\n    solver = spx.pursuit.single.OrthogonalMatchingPursuit(Phi, K);\n    % Solve the sparse recovery problem\n    omp_result = solver.solve(y);\n    % Solution vector\n    z = omp_result.z;\n    omp_stats = spx.commons.sparse.recovery_performance(Phi, K, y, x, z);\n    %fprintf('OMP\\n');\n    %spx.commons.sparse.print_recovery_performance(omp_stats);\n\n\n\n    % MC-OMP solver instance\n    solver = spx.pursuit.single.MC_OMP(Phi, K);\n    %solver.BranchingFactor = 4;\n    %solver.MaxCandidatesToRetain = 8;\n    % Solve the sparse recovery problem\n    mcomp_result = solver.solve(y);\n    % Solution vector\n    z = mcomp_result.z;\n    mcomp_stats = spx.commons.sparse.recovery_performance(Phi, K, y, x, z);\n    %fprintf('MC-OMP\\n');\n    %spx.commons.sparse.print_recovery_performance(mcomp_stats);\n\n    fprintf('K=%d, Trial: %d, OMP: %s, MC-OMP: %s\\n', ...\n        K, nt, spx.io.true_false_short(omp_stats.success), ...\n        spx.io.true_false_short(mcomp_stats.success));\n    omp_success = omp_success  + omp_stats.success;\n    mc_omp_success = mc_omp_success  + mcomp_stats.success;\nend\nfprintf('TOTAL: OMP : %d, MC-OMP: %d\\n', omp_success, mc_omp_success);\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/mc_omp/ex_mc_omp_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5701155978710302}}
{"text": "% sin_x.m: This m-file calculates and plots the \n% function sin(x) for 0 <= x <= 6.\nx = 0:0.1:6;\ny = sin(x);\nplot(x,y);\n ", "meta": {"author": "101Hub", "repo": "Matlab101", "sha": "07273f68f1147a110443aeb121fa10962234f298", "save_path": "github-repos/MATLAB/101Hub-Matlab101", "path": "github-repos/MATLAB/101Hub-Matlab101/Matlab101-07273f68f1147a110443aeb121fa10962234f298/assets/\u300aMatlab\u7f16\u7a0b\u300b\u6e90\u7801/chap2/sin_x.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.570115593105788}}
{"text": "function rowMatrix = computeRowsOfToeplitzHankelMatrix(rowNumber,...\n        nColumns, crossCorrelationVectors, hankelMatrixIsAdded, dcIsIncluded)\n%     if rowNumber == 1\n%         toeplitzRows = crossCorrelationVectors(1:nColumns,:);\n%     else\n%         toeplitzRows = ...\n%             [flip(crossCorrelationVectors(2:rowNumber,:),1);...\n%             crossCorrelationVectors(1:nColumns-rowNumber+1,:)];\n%     end\n% modified by Liming Shi for fast computation in MATLAB                    \n    toeplitzRows=crossCorrelationVectors(rowNumber:-1:1,:);\n    \n    \n    \n    if dcIsIncluded && hankelMatrixIsAdded\n        hankelOffset = 1;\n    else\n        hankelOffset = 3;\n    end\n    \n    hankelRows = crossCorrelationVectors((0:nColumns-1)+...\n                                         hankelOffset+rowNumber-1,:);\n\n    if hankelMatrixIsAdded\n        rowMatrix = toeplitzRows + hankelRows;\n    else\n        rowMatrix = toeplitzRows - hankelRows;\n    end\n\nend\n", "meta": {"author": "LimingShi", "repo": "Bayesian-Pitch-Tracking-Using-Harmonic-model", "sha": "ad9a3fcfe60d2e97a635a92c2076ff1978ae3697", "save_path": "github-repos/MATLAB/LimingShi-Bayesian-Pitch-Tracking-Using-Harmonic-model", "path": "github-repos/MATLAB/LimingShi-Bayesian-Pitch-Tracking-Using-Harmonic-model/Bayesian-Pitch-Tracking-Using-Harmonic-model-ad9a3fcfe60d2e97a635a92c2076ff1978ae3697/BF0NLS_MATLAB/private/computeRowsOfToeplitzHankelMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5700549388668487}}
{"text": "function f = spp_scale_features(f, feat_norm_mean)\n% My initial experiments were conducted on features with an average norm\n% very close to 20. Using those features, I determined a good range of SVM\n% C values to cross-validate over. Features from different layers end up\n% have very different norms. We rescale all features to have an average norm\n% of 20 (why 20? simply so that I can use the range of C values found in my \n% initial experiments), to make the same search range for C reasonable \n% regardless of whether these are pool5, fc6, or fc7 features. This strategy\n% seems to work well. In practice, the optimal value for C ends up being the\n% same across all features.\ntarget_norm = 20;\nf = f .* (target_norm / feat_norm_mean);\n", "meta": {"author": "ShaoqingRen", "repo": "SPP_net", "sha": "ca9675907f8af6c02773571bc91147b3a2ddfcc1", "save_path": "github-repos/MATLAB/ShaoqingRen-SPP_net", "path": "github-repos/MATLAB/ShaoqingRen-SPP_net/SPP_net-ca9675907f8af6c02773571bc91147b3a2ddfcc1/spp_scale_features.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5700549337574938}}
{"text": "function kernel = create_kernel(kernel_type, pars, nMax, lb, ub, bound_pars)\n%% create convolution kernel\n%% inputs:\n%   kernel_type: string, convolution kernel type. now support {'exp',\n%       'exp2', 'vector'}\n%   pars: parameters for the selected kernel type\n%   nMax: length of the kernel\n%   lb:     lower bound for each parameter\n%   ub:     upper bound for each parameter\n%   bound_pars: logical variable, bound the parameters or not {1, 0}\n%% outputs\n%   kernel: struct variable\n\n%% Author: Pengcheng Zhou, Carnegie Mellon University, 2016\n\n%% kernel size \nif ~exist('nMax', 'var') || isempty(nMax)\n    nMax = 50;\nend\nkernel.nMax = nMax; \n\n%% initialize kernel \nif ~exist('kernel_type', 'var') || isempty(kernel_type)\n    kernel_type = 'exp2'; \nend\nif strcmpi(kernel_type, 'exp')\n    % single exponential function: ~ exp(-t/tau)\n    kernel.type = 'exp';\n    % parameter\n    if ~exist('pars', 'var') || isempty(pars)\n        kernel.pars = [5, .1];\n    else\n        kernel = kernel.pars; \n    end    \n    % function handle \n    kernel.fhandle = @(pars, t) exp(-t/pars) * (1-exp(-1/pars)) ...\n        / (1-exp(-nMax/pars)); \nelseif strcmpi(kernel_type, 'vector')\n    % single vector \n    kernel.type = 'vector'; \n    % parameter \n    if ~exist('pars', 'var') || isempty(pars)\n        kernel.pars = exp(-(1:nMax)/10); \n    else\n        kernel.pars = pars; \n    end\n    % function handle \n    kernel.fhandle = @(pars, t) pars/sum(pars); \nelse\n    % differencing of two exponential function:\n    % ~  exp(-t/tau_d)-exp(-t/tau_r)\n    kernel.type = 'exp2';\n    \n    % parameters\n    if ~exist('pars', 'var') || isempty(pars)\n        kernel.pars = [10, 1];\n    else\n        kernel.pars = pars; \n    end\n    % function handle \n    kernel.fhandle = @(pars, t) (exp(-t/pars(1)) - exp(-t/pars(2)))  ...\n        /( (1-exp(-nMax/pars(1)))/(1-exp(-1/pars(1))) ...\n        - (1-exp(-nMax/pars(2)))/(1-exp(-1/pars(2))));\nend\n\n% lower and upper bounds for parameters \nif ~exist('lb', 'var') || isempty(lb)\n    kernel.lb = 0.5*kernel.pars;\nelse\n    kernel.lb = lb; \nend\nif ~exist('ub', 'var') || isempty(ub)\n    kernel.ub = 2*kernel.pars;\nelse\n    kernel.ub = ub; \nend\n\n% bound the parameters of not \nif ~exist('bound_pars', 'var')||isempty(bound_pars)\n    kernel.bound_pars = false; \nelse\n    kernel.bound_pars = bound_pars; \nend", "meta": {"author": "zhoupc", "repo": "CNMF_E", "sha": "ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f", "save_path": "github-repos/MATLAB/zhoupc-CNMF_E", "path": "github-repos/MATLAB/zhoupc-CNMF_E/CNMF_E-ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f/OASIS_matlab/packages/oasis_kernel/create_kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5700549337574937}}
{"text": "function tests = LineFeatureTest\n    tests = functiontests(localfunctions)\n    clc\nend\n\nfunction setupOnce(tc)\n    im = testpattern('squares', 256, 256, 128);\n    im = irotate(im, -0.3);\n    edges = icanny(im);\n    \n    tc.TestData.edges = edges;\nend\n\nfunction teardownOnce(tc)\n    close all\nend\n\nfunction constructor_test(tc)\n    \n    % create Hough object\n    h = Hough(tc.TestData.edges);\n    tc.verifyClass(h, 'Hough');\n    \n    s = char(h);\n    tc.verifyClass(s, 'char');\n    \n    h.display;\n    h.show();\nend\n\nfunction simple_test(tc)\n    % check accumulators are correct size\n    im = [0 0 0; 0 1 0; 0 0 0];\n    h = Hough(im, 'nbins', [6 5]);\n    tc.verifyEqual( size(h.A), [5 6]);\n    \n    h = Hough(im, 'nbins', 4);\n    tc.verifyEqual( size(h.A), [5 4]);\n\n    % simple example with 2 edge points\n    edge = [\n        0 0 0\n        0 1 1\n        0 0 0];\n    out = [\n        0     0     0     0\n        2     0     0     0\n        0     2     0     0\n        0     0     2     1\n        0     0     0     1\n     ];\n    h = Hough(edge, 'nbins', 4)\n    tc.verifyEqual(h.A, out);\n\n     % test vote weighting\n     h = Hough(edge*2, 'nbins', 4);\n     tc.verifyEqual( h.A, out*2);\n     \n     h = Hough(edge*2, 'nbins', 4, 'equal');\n     tc.verifyEqual( h.A, out);\n     \n     % test xy input mode\n     h = Hough([2 2; 2 3]', 'nbins', 4, 'points', [3 3]);\n     tc.verifyEqual( h.A, out);\n     \n     % test xy input mode with weights\n     h = Hough([2 2 5; 2 3 5]', 'nbins', 4, 'points', [3 3]);\n     tc.verifyEqual( h.A, out*5);\n\n     % test point, rather than image, mode\n%      h=Hough([2 3; 2 2], 'points', 'nbins', 4)\n%      tc.verifyEqual( h.A, out);\nend\n\nfunction square_test(tc)\n    edges = tc.TestData.edges;\n\n    h = Hough(edges);\n    \n    % create LineFeature objects\n    lines = h.lines();\n    tc.verifyClass(lines, 'LineFeature');\n    \n    tc.verifyEqual(numel(lines), 11);\n    tc.verifyTrue( isempty(lines.length) );\n    tc.verifyEqual( length(lines.theta), 11);\n    tc.verifyEqual( length(lines.rho), 11);\n    tc.verifyEqual( length(lines.strength), 11);\n    \n    s = char(lines);\n    tc.verifyClass(s, 'char');\n    tc.verifyEqual( size(s,1), 11);\n    \n\nend\n\nfunction show_test(tc)\n    h = Hough(tc.TestData.edges);\n    \n    clf\n    h.show();\n    a = gca;\n    tc.verifyNotEmpty(a.Children);\n    tc.verifyNumElements(a.Children, 1);\n    tc.verifyMatches(a.Children.Type, 'image')\n\nend\n\nfunction plot_test(tc)\n    h = Hough(tc.TestData.edges);\n    clf\n    h.plot('b');\n    \n    a = gca;\n    tc.verifyNotEmpty(a.Children);\n    tc.verifyNumElements(a.Children, 11);\n    tc.verifyTrue(all( strcmp({a.Children.Type}, 'line') ) )\nend\n\n\n\nfunction square_suppress_test(tc)\n    edges = tc.TestData.edges;\n    \n    % create new Hough and lines with non-local maxima suppression\n    h = Hough(edges, 'suppress', 5);\n    tc.verifyClass(h, 'Hough');\n    \n    lines = h.lines();\n    tc.verifyClass(lines, 'LineFeature');\n    tc.verifyEqual(numel(lines), 4);\n    \n    s = char(lines);\n    tc.verifyClass(s, 'char');\n    tc.verifyEqual(size(s,1), 4);\n    \n\n    % test line support\n    lines = lines.seglength(edges);\n    tc.verifyClass(lines, 'LineFeature');\n    tc.verifyEqual(numel(lines), 4);\n    \n    tc.verifyEqual( numel(lines), 4);\n    tc.verifyEqual( length(lines.theta), 4);\n    tc.verifyEqual( length(lines.rho), 4);\n    tc.verifyEqual( length(lines.length), 4);\n    tc.verifyEqual( length(lines.strength), 4);\nend", "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/unit_test/LineFeatureTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5700549325888327}}
{"text": "classdef TirePolynomial < VehicleDynamicsLateral.Tire\n    % TirePolynomial Polynomial tire model\n    %\n    % It inherits methods from Tire.\n\n    methods\n        % Constructor\n        function self = TirePolynomial()\n            self.k1 = 115000;\n            self.k2 = 560000;\n        end\n\n        function p = PlotTire(self)\n            % Returns the handle of the curve\n            alpha = (0:0.1:15)*pi/180;\n            Fy = - self.Characteristic(alpha);\n            p = plot(alpha*180/pi,Fy);\n            grid on; box on;\n            xlabel('Slip angle [deg]')\n            ylabel('Lateral force [N]')\n        end\n\n        function Fy = Characteristic(self, alpha, varargin)\n            % Lateral force\n            Fy = - (self.k1 * alpha - self.k2 * alpha.^3);\n        end\n    end\n\n    properties\n        k1 % 1st polynomial coefficient, cornering stiffness [N/rad]\n        k2 % 2nd polynomial coefficient [N/rad^3]\n    end\nend\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/+VehicleDynamicsLateral/@TirePolynomial/TirePolynomial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5700549223701233}}
{"text": "function r = gamrand(a, b, varargin);\n%GAMRAND Random matrices from gamma distribution.\n%\n%   R = GAMRAND(A,B) returns a matrix of random numbers chosen   \n%   from the gamma distribution with parameters A and B.\n%   The size of R is the common size of A and B if both are matrices.\n%   If either parameter is a scalar, the size of R is the size of the other\n%   parameter. Alternatively, R = GAMRAND(A,B,M,N) returns an M by N matrix. \n% \n%   Note: Parameterization as in (Neal, 1996).\n%      A is mean of the distribution\n%      B is degrees of freedom\n%\n%\tSee also INVGAMRAND\n%\n% Copyright (c) 1999 Aki Vehtari\n\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\nerror('No mex-file for this architecture. See Matlab help and convert.m in ./linuxCsource or ./winCsource for help.')\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/gamrand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5700549212014618}}
{"text": "function [ indx_extract, n, indx ] = r8vec_indexed_heap_d_extract ( n, a, indx )\n\n%*****************************************************************************80\n%\n%% R8VEC_INDEXED_HEAP_D_EXTRACT: extract from heap descending indexed R8VEC.\n%\n%  Discussion:\n%\n%    An R8VEC is a vector of R8's.\n%\n%    An indexed R8VEC is an R8VEC of data values, and an R8VEC of N indices,\n%    each referencing an entry of the data vector.\n%\n%    The routine finds the maximum value in the heap, returns that value to the\n%    user, deletes that value from the heap, and restores the heap to its\n%    proper form.\n%\n%    Note that the argument N must be a variable, which will be decremented\n%    before return, and that INDX will hold one less value on output than it\n%    held on input.\n%\n%    This is one of three functions needed to model a priority queue.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    17 August 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Thomas Cormen, Charles Leiserson, Ronald Rivest,\n%    Introduction to Algorithms,\n%    MIT Press, 2001,\n%    ISBN: 0262032937,\n%    LC: QA76.C662.\n%\n%  Parameters:\n%\n%    Input, integer N, the number of items in the index vector.\n%\n%    Input, real A(*), the data vector.\n%\n%    Input, integer INDX(N), the index vector.\n%\n%    Output, integer INDX_EXTRACT, the index in A of the item of\n%    maximum value, which has now been removed from the heap.\n%\n%    Output, integer N, the number of items in the revised index vector.\n%\n%    Output, integer INDX(N), the revised index vector.\n%\n  if ( n < 1 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8VEC_INDEXED_HEAP_D_EXTRACT - Fatal error!\\n' );\n    fprintf ( 1, '  The heap is empty.\\n' );\n    error ( 'R8VEC_INDEXED_HEAP_D_EXTRACT - Fatal error!' )\n  end\n%\n%  Get the index of the maximum value.\n%\n  indx_extract = indx(1);\n\n  if ( n == 1 )\n    n = 0;\n    indx = [];\n    return\n  end\n%\n%  Shift the last index down.\n%\n  indx(1) = indx(n);\n%\n%  Restore the heap structure.\n%\n  n = n - 1;\n  indx = r8vec_indexed_heap_d ( n, a, indx );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_indexed_heap_d_extract.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.5700549192311153}}
{"text": "function [dag,best_score] = learn_struct_hc(data, nodesizes, seeddag, varargin)\n%\n% LEARN_STRUCT_HC(data,seeddag) learns a structure of Bayesian net by Hill Climbing.\n% dag = learn_struct_hc(data, nodesizes, seeddag)\n%\n% dag: the final structurre matrix\n% Data : training data, data(i,m) is the m obsevation of node i\n% Nodesizes: the size array of different nodes\n% seeddag: given seed Dag for hill climbing, optional\n%\n% by Gang Li @ Deakin University (gli73@hotmail.com)\n\n[N ncases] = size(data);\nif (nargin < 3 ) \n    seeddag = zeros(N,N); % mk_rnd_dag(N); %call BNT function\nelseif ~acyclic(seeddag)\n    seeddag = mk_rnd_dag(N); %zeros(N,N);\nend;\n\n% set default params\nscoring_fn = 'bic';\nverbose  = 'yes';\n\n% get params\nargs = varargin;\nnargs = length(args);\nif length(args) > 0\n    if isstr(args{1})\n    \tfor i = 1:2:nargs\n    \t\tswitch args{i}\n    \t\tcase 'scoring_fn', scoring_fn = args{i+1};\n    \t\tcase 'verbose',  verbose  = strcmp(args{i+1},'yes');\n    \t\tend;\n    \tend;\n    end;\nend;\n\ndone = 0;\nbest_score = score_dags(data,nodesizes, {seeddag},'scoring_fn',scoring_fn);\nwhile ~done\n    [dags,op,nodes] = mk_nbrs_of_dag(seeddag);\n    nbrs = length(dags);\n    scores = score_dags(data, nodesizes, dags,'scoring_fn',scoring_fn);\n    max_score = max(scores);\n    new = find(scores == max_score );\n    if ~isempty(new) & (max_score > best_score)\n        p = sample_discrete(normalise(ones(1, length(new))));\n        best_score = max_score;\n        seeddag = dags{new(p)};\n    else\n        done = 1;\n    end;\nend;\n\ndag = seeddag;\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/learning/learn_struct_hc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5700549172607684}}
{"text": "function [ypred]=knn(xapp,yapp,valY,X,k)\n\n%\n% knn implementation\n%\n% USE : [ypred]=knn(xapp,yapp,valY,X,k)\n%\n% Vincent Guigue 08/01/03\n\n% check nargin\n\nif nargin<4\n  error('too few argumemnts');\nelseif nargin<5\n  k=3;\nelse\n  if mod(k,2)==0\n    error('k must be odd');\n  end\nend\n\nif size(xapp,2)~=size(X,2)\n  error('dimension incompatibility');\nend\n\n\nndim = size(xapp,2);\nnptxapp = size(xapp,1);\nnptX = size(X,1);\n\n% distance de X a xapp :\nmat1 =  repmat(xapp, nptX,1);\n%mat21 = reshape(X',1,nptX*ndim)\nmat22 = repmat(X,1,nptxapp)';\nmat2 = reshape(mat22 ,ndim, nptxapp*nptX)';\ndistance = mat1 - mat2 ;\n\ndistance = sum(distance.^2,2);\ndistance = reshape(distance,nptxapp,nptX);\n[val kppv] = sort(distance,1);\n\n% bilan sur les k premieres lignes\nkppv = reshape(kppv(1:k,:),k*nptX,1);\nYkppv = yapp(kppv,1);\nYkppv = reshape(Ykppv,k,nptX);\n\n% trouver le plus de reponses identique par colonne\n\nvote = [];\nfor i=1:nptX\n  for j=1:length(valY)\n    vote(j,i)=size(find(Ykppv(:,i)==valY(j)),1);\n  end\nend\n\n[val ind]=max(vote,[],1);\nypred = valY(ind);", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/misc/knn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5700549121514136}}
{"text": "function [M,P] = ghkf_predict(M,P,f,Q,f_param,p)\n% GHKF_PREDICT - Gauss-Hermite Kalman filter prediction step\n%\n% Syntax:\n%   [M,P] = GHKF_PREDICT(M,P,[f,Q,f_param,p])\n%\n% In:\n%   M - Nx1 mean state estimate of previous step\n%   P - NxN state covariance of previous step\n%   f - Dynamic model function as a matrix A defining\n%       linear function f(x) = A*x, inline function,\n%       function handle or name of function in\n%       form f(x,param)                   (optional, default eye())\n%   Q - Process noise of discrete model   (optional, default zero)\n%   f_param - Parameters of f               (optional, default empty)\n%   p - Degree of approximation (number of quadrature points)\n%\n% Out:\n%   M - Updated state mean\n%   P - Updated state covariance\n%\n% Description:\n%   Perform additive form Gauss-Hermite Kalman Filter prediction step.\n%\n%   Function f(.) should be such that it can be given a\n%   DxN matrix of N sigma Dx1 points and it returns \n%   the corresponding predictions for each sigma\n%   point. \n%\n% See also:\n%   GHKF_UPDATE, GHRTS_SMOOTH, GH_TRANSFORM\n\n% History:\n%   Aug 5,  2010 - Renamed from 'gh_predict' to 'ghkf_predict' (asolin)\n\n% Copyright (C) 2009 Hartikainen, S\u00e4rkk\u00e4, Solin\n%\n% $Id: gh_predict.m,v 1.2 2009/07/01 06:34:40 ssarkka Exp $\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\n  %\n  % Check which arguments are there\n  %\n  if nargin < 2\n    error('Too few arguments');\n  end\n  if nargin < 3\n    f = [];\n  end\n  if nargin < 4\n    Q = [];\n  end\n  if nargin < 5\n    f_param = [];\n  end\n  if nargin < 6\n     p = []; \n  end\n\n  %\n  % Apply defaults\n  %\n  if isempty(f)\n    f = eye(size(M,1));\n  end\n  if isempty(Q)\n    Q = zeros(size(M,1));\n  end\n  if isempty(p)\n    p = 10;\n  end\n  \n  %\n  % Do transform and add process noise\n  %\n  tr_param = {p};\n  [M,P] = gh_transform(M,P,f,f_param,tr_param);\n  P = P + Q;\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/ghkf_predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5700549121514136}}
{"text": "function [reg_min,G,reg_param,minG] = gcv(U,s,b,method)\n%GCV Plot the GCV function and find its minimum.\n%\n% [reg_min,G,reg_param] = gcv(U,s,b,method)\n% [reg_min,G,reg_param] = gcv(U,sm,b,method)  ,  sm = [sigma,mu]\n%\n% Plots the GCV-function\n%          || A*x - b ||^2\n%    G = -------------------\n%        (trace(I - A*A_I)^2\n% as a function of the regularization parameter reg_param.\n% Here, A_I is a matrix which produces the regularized solution.\n%\n% The following methods are allowed:\n%    method = 'Tikh' : Tikhonov regularization   (solid line )\n%    method = 'tsvd' : truncated SVD or GSVD     (o markers  )\n%    method = 'dsvd' : damped SVD or GSVD        (dotted line)\n% If method is not specified, 'Tikh' is default.\n%\n% If any output arguments are specified, then the minimum of G is\n% identified and the corresponding reg. parameter reg_min is returned.\n\n% Per Christian Hansen, IMM, Dec. 16, 2003.\n\n% Reference: G. Wahba, \"Spline Models for Observational Data\",\n% SIAM, 1990.\n\n% Set defaults.\nif (nargin==3), method='Tikh'; end  % Default method.\nnpoints = 200;                      % Number of points on the curve.\nsmin_ratio = 16*eps;                % Smallest regularization parameter.\n\n% Initialization.\n[m,n] = size(U); [p,ps] = size(s);\nbeta = U'*b; beta2 = norm(b)^2 - norm(beta)^2;\nif (ps==2)\n  s = s(p:-1:1,1)./s(p:-1:1,2); beta = beta(p:-1:1);\nend\nif (nargout > 0), find_min = 1; else find_min = 0; end\n\nif (strncmp(method,'Tikh',4) | strncmp(method,'tikh',4))\n\n  % Vector of regularization parameters.\n  reg_param = zeros(npoints,1); G = reg_param; s2 = s.^2;\n  reg_param(npoints) = max([s(p),s(1)*smin_ratio]);\n  ratio = (s(1)/reg_param(npoints))^(1/(npoints-1));\n  for i=npoints-1:-1:1, reg_param(i) = ratio*reg_param(i+1); end\n\n  % Intrinsic residual.\n  delta0 = 0;\n  if (m > n && beta2 > 0), delta0 = beta2; end\n\n  % Vector of GCV-function values.\n  for i=1:npoints\n    G(i) = gcvfun(reg_param(i),s2,beta(1:p),delta0,m-n);\n  end \n\n  if nargout == 0\n      % Plot GCV function.\n      loglog(reg_param,G,'-'), xlabel('\\lambda'), ylabel('G(\\lambda)')\n      title('GCV function')\n  end\n\n  % Find minimum, if requested.\n  if (find_min)\n    [minG,minGi] = min(G); % Initial guess.\n    reg_min = fminbnd('gcvfun',...\n      reg_param(min(minGi+1,npoints)),reg_param(max(minGi-1,1)),...\n      optimset('Display','off'),s2,beta(1:p),delta0,m-n); % Minimizer.\n    minG = gcvfun(reg_min,s2,beta(1:p),delta0,m-n); % Minimum of GCV function.\n    if nargout == 0\n        ax = axis;\n        HoldState = ishold; hold on;\n        loglog(reg_min,minG,'*r',[reg_min,reg_min],[minG/1000,minG],':r')\n        title(['GCV function, minimum at \\lambda = ',num2str(reg_min)])\n        axis(ax)\n        if (~HoldState), hold off; end\n    end\n  end\n\nelseif (strncmp(method,'tsvd',4) | strncmp(method,'tgsv',4))\n   \n  % Vector of GCV-function values.\n  rho2(p-1) = abs(beta(p))^2;\n  if (m > n & beta2 > 0), rho2(p-1) = rho2(p-1) + beta2; end\n  for k=p-2:-1:1, rho2(k) = rho2(k+1) + abs(beta(k+1))^2; end\n  G = zeros(p-1,1);\n  for k=1:p-1\n    G(k) = rho2(k)/(m - k + (n - p))^2;\n  end\n  reg_param = (1:p-1)';\n\n  % Plot GCV function.\n  semilogy(reg_param,G,'o'), xlabel('k'), ylabel('G(k)')\n  title('GCV function')\n\n  % Find minimum, if requested.\n  if (find_min)\n    [minG,reg_min] = min(G);\n    ax = axis;\n    HoldState = ishold; hold on;\n    semilogy(reg_min,minG,'*r',[reg_min,reg_min],[minG/1000,minG],':r')\n    title(['GCV function, minimum at k = ',num2str(reg_min)])\n    axis(ax);\n    if (~HoldState), hold off; end\n  end\n\nelseif (strncmp(method,'dsvd',4) | strncmp(method,'dgsv',4))\n\n  % Vector of regularization parameters.\n  reg_param = zeros(npoints,1); G = reg_param;\n  reg_param(npoints) = max([s(p),s(1)*smin_ratio]);\n  ratio = (s(1)/reg_param(npoints))^(1/(npoints-1));\n  for i=npoints-1:-1:1, reg_param(i) = ratio*reg_param(i+1); end\n\n  % Intrinsic residual.\n  delta0 = 0;\n  if (m > n & beta2 > 0), delta0 = beta2; end\n\n  % Vector of GCV-function values.\n  for i=1:npoints\n    G(i) = gcvfun(reg_param(i),s,beta(1:p),delta0,m-n,1);\n  end\n\n  % Plot GCV function.\n  loglog(reg_param,G,':'), xlabel('\\lambda'), ylabel('G(\\lambda)')\n  title('GCV function')\n\n  % Find minimum, if requested.\n  if (find_min)\n    [minG,minGi] = min(G); % Initial guess.\n    reg_min = fminbnd('gcvfun',...\n      reg_param(min(minGi+1,npoints)),reg_param(max(minGi-1,1)),...\n      optimset('Display','off'),s,beta(1:p),delta0,m-n,1); % Minimizer.\n    minG = gcvfun(reg_min,s,beta(1:p),delta0,m-n,1); % Minimum of GCV function.\n    ax = axis;\n    HoldState = ishold; hold on;\n    loglog(reg_min,minG,'*r',[reg_min,reg_min],[minG/1000,minG],':r')\n    title(['GCV function, minimum at \\lambda = ',num2str(reg_min)])\n    axis(ax)\n    if (~HoldState), hold off; end\n  end\n\nelseif (strncmp(method,'mtsv',4) | strncmp(method,'ttls',4))\n\n  error('The MTSVD and TTLS methods are not supported')\n\nelse\n  error('Illegal method')\nend", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/external/regu/regu/gcv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5698966415599349}}
{"text": "function [ a, seed ] = r8sp_random ( m, n, nz_num, row, col, seed )\n\n%*****************************************************************************80\n%\n%% R8SP_RANDOM sets a random R8SP matrix.\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%  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 M, N, the number of rows and columns of the matrix.\n%\n%    Input, integer NZ_NUM, the number of nonzero elements in the matrix.\n%\n%    Input, integer ROW(NZ_NUM), COL(NZ_NUM), the row and column indices\n%    of the nonzero elements.\n%\n%    Input, integer SEED, a seed for the random number generator.\n%\n%    Output, real A(NZ_NUM), the nonzero elements of the matrix.\n%\n%    Output, integer SEED, an updated seed for the random number generator.\n%\n  [ a, seed ] = r8vec_uniform_01 ( nz_num, seed );\n\n  return\nend\n", "meta": {"author": "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/r8sp_random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5698709037499168}}
{"text": "function T = CreateDatabase(TrainDatabasePath)\n% Align a set of face images (the training set T1, T2, ... , TM )\n%\n% Description: This function reshapes all 2D images of the training database\n% into 1D column vectors. Then, it puts these 1D column vectors in a row to \n% construct 2D matrix 'T'. Each column of 'T' 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.\n%  \n% \n% Argument:     TrainDatabasePath      - Path of the training database\n%\n% Returns:      T                      - A 2D matrix, containing all 1D image vectors.\n%                                        The length of 1D column vectors is MN and 'T' will be a MNxP 2D matrix.\n%\n% See also: STRCMP, STRCAT, RESHAPE\n\n% Original version by Amir Hossein Omidvarnia, October 2007\n%                     Email: aomidvar@ece.ut.ac.ir                  \n\n%%%%%%%%%%%%%%%%%%%%%%%% File management\nTrainFiles = dir(TrainDatabasePath);\nTrain_Number = 0;\n\nfor i = 1:size(TrainFiles,1)\n    if not(strcmp(TrainFiles(i).name,'.')|strcmp(TrainFiles(i).name,'..')|strcmp(TrainFiles(i).name,'Thumbs.db'))\n        Train_Number = Train_Number + 1; % Number of all images in the training database\n    end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%% Construction of 2D matrix from 1D image vectors\nT = [];\nfor i = 1 : Train_Number\n    \n    % I have chosen the name of each image in databases as a corresponding\n    % number. However, it is not mandatory!\n    str = int2str(i);\n    str = strcat('\\',str,'.jpg');\n    str = strcat(TrainDatabasePath,str);\n    \n    img = imread(str);\n    img = rgb2gray(img);\n    \n    [irow icol] = size(img);\n   \n    temp = reshape(img',irow*icol,1);   % Reshaping 2D images into 1D image vectors\n    T = [T temp]; % 'T' grows after each turn                    \nend\n\nT = double(T);", "meta": {"author": "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/CreateDatabase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5698708997346182}}
{"text": "%CREATECONCENTRICSPHERESTESTSET  Creates test set\n%\n%     [samples, responses] = cv.createConcentricSpheresTestSet(nsamples, nfeatures, nclasses)\n%\n% ## Input\n% * __nsamples__ returned samples count.\n% * __nfeatures__ returned features count.\n% * __nclasses__ number of classes.\n%\n% ## Output\n% * __samples__ returned samples array `nsamples-by-nfeatures`.\n% * __sampClasses__ corresponding classes labels `nsamples-by-1`.\n%\n% See also: cv.randMVNormal, cv.randGaussMixture\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/createConcentricSpheresTestSet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5698708996364233}}
{"text": "function linpack_s_test03 ( )\n\n%*****************************************************************************80\n%\n%% TEST03 tests SCHUD.\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  p = 20;\n  ldr = p;\n  nz = 1;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST03\\n' );\n  fprintf ( 1, '  For single precision, general storage,\\n' );\n  fprintf ( 1, '  SCHUD updates a Cholesky decomposition.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  In this example, we use SCHUD to solve a\\n' );\n  fprintf ( 1, '  least squares problem R * b = z.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The number of equations is P = %d\\n', p );\n%\n%  Initialize.\n%\n  r(1:p,1:p) = 0.0;\n  z(1:p,1:nz) = 0.0;\n  for i = 1 : p\n    x(i) = i;\n  end\n%\n%  Use SCHUD to form R, Z and RHO by adding X and Y a row at a time.\n%  X is a row of the least squares matrix and Y the right hand side.\n%\n  seed = 123456789;\n\n  for i = 1 : p\n    [ row, seed ] = r4mat_uniform_01 ( 1, p, seed );\n    y(1) = row(1:p) * x(1:p)';\n    rho(1) = 0.0;\n    [ r, z, rho, c, s ] = schud ( r, ldr, p, row, z, p, nz, y, rho );\n  end\n%\n%  Generate the least squares solution, b = inverse ( R ) * Z.\n%\n  for j = 1 : nz\n\n    b(1:p,1) = z(1:p,j);\n    job = 01;\n\n    [ b, info ] = strsl ( r, ldr, p, b, job );\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Solution vector # %d\\n', j );\n    fprintf ( 1, '  (Should be (1,2,3...,n))\\n' );\n    fprintf ( 1, '\\n' );\n\n    for i = 1 : p\n      if ( i <= 5 | p-5 < i )\n        fprintf ( 1, '  %6d  %14f\\n', i, b(i,1) );\n      end\n      if ( i == 5 )\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/linpack_s/linpack_s_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.7577943822145997, "lm_q1q2_score": 0.5698708953265393}}
{"text": "function x = bin2hex(BinStr)\n\n% BIN2HEX (BinStr,...output)\n%\n% Converts binary strings of any length to hexadecimal pairs. Adds leading\n% zeros if there is not an even number of hex bits.\n%\n% Now also supports cell array inputs.\n%\n%\n% Author: Richard Medlock 2001\n\n% Check to see what the input is:\n\nif iscell(BinStr)\n    \n    NCells = length(BinStr)\n    \n    for C = 1:NCells\n        \n        Str = BinStr{C};\n        \n        x{C} = doconvert(Str);\n        \n    end\n    \nelseif ~ischar(BinStr)\n    \n    error('Input must be a string or character or cell array.')\n    \nelse\n    \n    x = doconvert(BinStr);\n    \nend\n        \n        \n%-----------------------------------------------    \nfunction out = doconvert(BinStr)\n    \n\nBits = length(BinStr);\nWords = Bits/4;\nWholeWords = floor(Words);\nPartWords = Words-WholeWords;\n\nwhile PartWords > 0\n\n    BinStr = ['0' BinStr];   \n    Bits = length(BinStr);\n    Words = Bits/4;\n    WholeWords = floor(Words);\n    PartWords = Words-WholeWords;\n    \nend\n\n% For each WORD (4-bits), convert it to HEX based on the following rules:\n\nWords = length(BinStr)/4;\n\nHEXi = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};\n\nHexStr = [];\n\nfor W = 1:Words\n    \n    %For each word, convert it first to decimal:\n    \n    P = (W*4)-3;\n    \n    Word = BinStr(P:P+3);\n    DEC = bin2dec(Word);\n    HEX = HEXi{DEC+1};\n    \n    HexStr = [HexStr HEX];\n   \nend\n\nLHex = length(HexStr); %If the Hex String has an odd number of bits, add 0 to the front.\n\nif isodd(LHex)\n    \n    HexStr = ['0' HexStr];\n    \nend\n\nout = HexStr;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1975-bin2hex/bin2hex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5698708913112412}}
{"text": "function [ b, info ] = cgtsl ( n, c, d, e, b )\n\n%*****************************************************************************80\n%\n%% CGTSL solves a complex general tridiagonal system.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    29 April 2007\n%\n%  Author:\n%\n%    MATLAB version by John Burkardt\n%\n%  Reference:\n%\n%    Jack Dongarra, Cleve Moler, Jim Bunch and 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%  \n%  Parameters:\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Input, complex C(N); the subdiagonal of the matrix in entries C(2:N). \n%\n%    Input, complex D(N); the diagonal of the tridiagonal matrix.\n%\n%    Input, complex E(N), the superdiagonal of the matrix in entries E(1:N-1).\n%\n%    Input, complex B(N), the right hand side.\n%\n%    Output, complex B(N).  the solution.\n%\n%    Output, integer INFO.\n%    0, normal value.\n%    K, if the K-th element of the diagonal becomes exactly zero.  The \n%    subroutine returns when this is detected.\n%\n  info = 0;\n  c(1) = d(1);\n\n  if ( 1 <= n-1 )\n\n    d(1) = e(1);\n    e(1) = 0.0;\n    e(n) = 0.0;\n\n    for k = 1 : n-1\n\n      if ( cabs1 ( c(k) ) <= cabs1 ( c(k+1) ) )\n\n        t      = b(k);\n        b(k)   = b(k+1);\n        b(k+1) = t;\n\n        t      = c(k);\n        c(k)   = c(k+1);\n        c(k+1) = t;\n\n        t      = d(k);\n        d(k)   = d(k+1);\n        d(k+1) = t;\n\n        t      = e(k);\n        e(k)   = e(k+1);\n        e(k+1) = t;\n\n      end\n\n      if ( cabs1 ( c(k) ) == 0.0 )\n        info = k;\n        return\n      end\n\n      t = -c(k+1) / c(k);\n      c(k+1) = d(k+1) + t * d(k);\n      d(k+1) = e(k+1) + t * e(k);\n      e(k+1) = 0.0;\n      b(k+1) = b(k+1) + t * b(k);\n\n    end\n\n  end\n\n  if ( cabs1 ( c(n) ) == 0.0 )\n    info = n;\n    return\n  end\n%\n%  Back solve.\n%\n  b(n) = b(n) / c(n);\n\n  if ( 1 < n )\n\n    b(n-1) = ( b(n-1) - d(n-1) * b(n) ) / c(n-1);\n\n    for k = n-2 : -1 : 1\n      b(k) = ( b(k) - d(k) * b(k+1) - e(k) * b(k+2) ) / c(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/linpack_c/cgtsl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5698708870995526}}
{"text": "function [dat] = ft_preproc_derivative(dat, order)\n\n% FT_PREPROC_DERIVATIVE computes the temporal Nth order derivative of the\n% data\n%\n% Use as\n%   [dat] = ft_preproc_derivative(dat, order)\n% where\n%   dat        data matrix (Nchans X Ntime)\n%   order      number representing the Nth derivative (default = 1)\n%\n% See also PREPROC\n\n% Copyright (C) 2008, 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 <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\n% set the defaults if options are not specified\nif nargin<2 || isempty(order)\n  order = 1;\nend\n\n% preprocessing fails on channels that contain NaN\nif any(isnan(dat(:)))\n  ft_warning('FieldTrip:dataContainsNaN', 'data contains NaN values');\nend\n\n% compute the derivative\nfor i=1:order\n  dat = gradient(dat);\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/preproc/ft_preproc_derivative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5698570766203713}}
{"text": "m = 100;\nn = 1000;\nk = 12;\nA = spx.dict.simple.gaussian_dict(m, n);\ngen = spx.data.synthetic.SparseSignalGenerator(n, k);\n% create a sparse vector\nx =  gen.biGaussian();\nb = A*x;\nA  = double(A);\nresult = spx.fast.omp(A, b, k, 1e-12);\ncmpare = spx.commons.SparseSignalsComparison(x, result, k);\ncmpare.summarize();\n\n% we now run both algorithms 100 times\ntic;\nfor i=1:1000\n    result = spx.fast.omp(A, b, k, 1e-12);\nend\nelapsed_time1 = toc;\nfprintf('Time taken %0.4f seconds\\n', elapsed_time1);\n\ntic;\nfor i=1:1000\n    result = spx.pursuit.single.omp_chol(A, b, k, 1e-12);\nend\nelapsed_time2 = toc;\nfprintf('Time taken %0.4f seconds\\n', elapsed_time2);\n\nimprovement_factor = elapsed_time2 / elapsed_time1;\nfprintf('improvement_factor: %0.2f \\n', improvement_factor);\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/fast/demo_compare_speed_omp_chol_mex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5698544226563419}}
{"text": "function [mGal] = cmps22mGal(cmps2)\n% Convert acceleration from centimeters per square centimeter to milligalileos\n% Chad A. Greene 2012\nmGal = cmps2*1e+3; \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/35258-unit-converters/unit_converters/cmps22mGal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504228, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5698544069758071}}
{"text": " function [xs, ni] = tml_sps(x, Gt, yi, bi, ri, niter, pixmax, curv)\n%function [xs, ni] = tml_sps(x, Gt, yi, bi, ri, niter, pixmax, curv)\n%\tOne iteration of the ML-SPS algorithm for transmission Poisson problem\n%\t(separable paraboloidal surrogates)\n%\tmodel: Y_i ~ Poisson(b_i exp(-[G x]_i) + r_i)\n%\tInput\n%\t\tx\t[np,1]\tinitial guess\n%\t\tGt\t\ttranspose of system matrix\n%\t\tyi\t\ttransmission sinogram\n%\t\tbi\t\tblank scan factors\n%\t\tri\t\tbackground (randoms, scatter, crosstalk, etc)\n%\t\tbi,ri:\t\toptional (can use empty matrices)\n%\t\tyi,bi,ri\tmust have identical dimensions\n%\t\tpixmax\t\tupper constraint for pixel values\n%\t\t\tcan be scalar (e.g. 'inf') or an array the size of x\n%\t\tcurv\t\t'oc' for erdogan's optimal curvatures\n%\t\t\t\t'pc' for erdogan's fast precomputed curvatures,\n%\t\t\t\t\twhich usually gives faster convergence,\n%\t\t\t\t\tbut can be nonmonotone\n%\t\t\t\t'nr' newton curvatures, can be nonmonotone\n%\tOutput\n%\t\tx [np,niter]\tupdated image vectors each iteration\n%\n%\tfix: the really slick way to do this would be to use\n%\tthe fast precomputed denominator and just backtrack to the monotone\n%\tversion on those rare occasions when it goes downhill\n%\n%\tCopyright 2000-3-01\tJeff Fessler\tThe University of Michigan\n\nif nargin < 3, ir_usage, end\n\n[nb, na] = size(yi);\n\nif (nargin < 4 || isempty(bi))\n\tbi = ones(size(yi));\nend\nif (nargin < 5 || isempty(ri))\n\tri = zeros(size(yi));\nend\nif (nargin < 6 || isempty(niter))\n\tniter = 2;\nend\nif (nargin < 7 || isempty(pixmax))\n\tpixmax = inf;\nend\nif (nargin < 8 || isempty(curv))\n\tcurv = 'oc';\nend\n\ntrl_check(yi, bi, ri);\n\n\tgi = sum(Gt)';\t% g_i = sum_j g_ij\n\n\tif strcmp(curv, 'pc')\n\t\tni = trl_curvature_pre(yi, bi, ri);\t% precomputed\n\t\tdenom = Gt * (gi .* ni(:));\n\telseif strcmp(curv, 'nr')\n\t\twarning 'newton curvatures can be non-monotone'\n\telseif ~strcmp(curv, 'oc')\n\t\terror 'curv not implemented'\n\tend\n\nxs = zeros(length(x), niter);\nx = max(x,0);\nx = min(x,pixmax);\nxs(:,1) = x;\n\n%\n%\tloop over iterations\n%\nfor ii=2:niter\n\tli = reshape(Gt' * x, size(yi));\t% l=G*x \"line integrals\"\n\tbel = bi .* exp(-li);\n\tyb = bel + ri;\t\t\t% predicted measurement means \n\n\tdothi = (1 - yi ./ yb) .* bel;\n\n\tif strcmp(curv, 'oc')\n\t\t%\toptimal curvatures (for ensured monotone increase)\n\t\tni = trl_curvature(yi, bi, ri, li, 'oc');\n\t\tdenom = Gt * (gi .* ni(:));\n\telseif strcmp(curv, 'nr')\n\t\tni = (1 - ri.*yi./yb.^2) .* bel;\n\t\tdenom = Gt * (gi .* ni(:));\n\tend\n\n\tx = x + (Gt * dothi(:)) ./ denom;\t% there's the update!\n\tx = max(x,0);\t\t\t\t% enforce nonnegativity\n\tx = min(x,pixmax);\t\t\t% enforce upper bound constraint\n\n\txs(:,ii) = x;\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/transmission/arch/tml_sps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5698544007575707}}
{"text": "function value = zsign1 ( z1, z2 )\n\n%*****************************************************************************80\n%\n%% ZSIGN1 is a complex transfer-of-sign function.\n%\n%  Discussion:\n%\n%    The L1 norm is used.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    09 May 2006\n%\n%  Author:\n%\n%    MATLAB version by John Burkardt\n%\n%  Parameters:\n%\n%    Input, complex Z1, Z2, the arguments.\n%\n%    Output, complex VALUE,  a complex value, with the magnitude of\n%    Z1, and the argument of Z2.\n%\n  if ( zabs1 ( z2 ) == 0.0 )\n    value = 0.0;\n  else\n    value = zabs1 ( z1 ) * ( z2 / zabs1 ( z2 ) );\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/blas0/zsign1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.5697936816323615}}
{"text": "function ShowImage(data, height, width, nRow, nColumn, reverse)\n\n[p, m] = size(data);\nif width * height ~= p\n    error('<EigFace>: incorrect width or height.\\n');\nend\n\nif nColumn * nRow > m\n    error('<EigFace>: incorrect column number or row number.\\n');\nend\n\nlineW = 1;\nhoriW = lineW;\nvertW = lineW;\n% scaling data\ndata = data/max(data(:));\ncanvH = height*nRow+horiW*(nRow+1);\ncanvW = width*nColumn+vertW*(nColumn+1);\n\n% construct canvas\ncanvColor = .5;\nif reverse\n    canvColor = 1-canvColor;\nend\nY = canvColor*ones(canvH,canvW);\n\n% draw the datas\nvertProb = lineW;\nfor i=1:nRow\n    horiProb = lineW;\n    for j=1:nColumn\n        if reverse\n            Y(vertProb+(1:height),  horiProb+(1:width)) = 1-reshape(data(:,(i-1)*nColumn+j),[height,width]);\n        else\n            Y(vertProb+(1:height),  horiProb+(1:width)) = reshape(data(:,(i-1)*nColumn+j),[height,width]);\n        end\n        % draw dashed line\n        if j~=nColumn\n            Y(vertProb+(1:floor(height/3):height), horiProb+width+1) = ~canvColor;\n        end\n        if i~=nRow\n            Y(vertProb+height+1, horiProb+(1:floor(width/3):width)) = ~canvColor;\n        end\n        % move horizontal probe\n        horiProb = horiProb+width+vertW;\n    end\n    % move vertical probe\n    vertProb = vertProb+height+horiW;\nend \n\n% rescaling\nY = Y*255;\n\n% show the image\nimagesc(Y);\ncolormap(gray);\naxis image off;", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/nmf/ManhNMF/ShowImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5697936733071345}}
{"text": "%% Copyright (C) 2003 Willem J. Atsma\n%% Copyright (C) 2014-2016, 2019 Colin B. Macdonald\n%%\n%% This program is free software; you can redistribute it and/or\n%% modify it under the terms of the GNU General Public\n%% License as published by the Free Software Foundation;\n%% either version 3, or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied\n%% warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n%% PURPOSE.  See the GNU General Public License for more\n%% details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.  If not,\n%% see <http://www.gnu.org/licenses/>.\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @deftypemethod  @@sym {@var{doublec} =} sym2poly (@var{p})\n%% @deftypemethodx @@sym {@var{c} =} sym2poly (@var{p}, @var{x})\n%% Return vector of coefficients of a symbolic polynomial.\n%%\n%% In the two-input form, the second argument @var{x} specifies the free\n%% variable; in this case this function returns a row vector @var{c} of\n%% symbolic expressions. The coefficients correspond to decreasing exponent\n%% of the free variable.  Example:\n%% @example\n%% @group\n%% syms x y\n%% sym2poly(2*x^2 + 3*x - pi, x)\n%%    @result{} (sym) [2  3  -\u03c0]  (1\u00d73 matrix)\n%% sym2poly(x^2 + y*x, x)\n%%    @result{} (sym) [1  y  0]  (1\u00d73 matrix)\n%% @end group\n%% @end example\n%%\n%% @strong{Warning}: Using the single-argument form, the coefficient vector\n%% @var{c} is a plain numeric vector (double).  This is for compatibility\n%% with the Matlab Symbolic Math Toolbox.\n%% We suggest making this clear in your code by explicitly casting to @code{double},\n%% as in:\n%% @example\n%% @group\n%% syms x\n%% @c doctest: +SKIP_IF(compare_versions (OCTAVE_VERSION(), '6.0.0', '<'))\n%% double(sym2poly(pi*x^3 + 3*x/2 + exp(sym(1))))\n%%    @result{}     3.1416      0   1.5000   2.7183\n%% @end group\n%% @end example\n%% You may prefer specifying @var{X} or using @code{coeffs}:\n%% @example\n%% @group\n%% coeffs(pi*x^3 + 3*x/2 + exp(sym(1)), 'all')\n%%    @result{} (sym) [\u03c0  0  3/2  \u212f]  (1\u00d74 matrix)\n%% @end group\n%% @end example\n%%\n%% If @var{p} is not a polynomial the result has no warranty.  SymPy can\n%% certainly deal with more general concepts of polynomial but we do not\n%% yet expose all of that here.\n%%\n%% @seealso{poly2sym, @@sym/coeffs, polyval, roots}\n%% @end deftypemethod\n\n%% Created: 18 April 2003\n%% Changed: 25 April 2003\n%%    Removed the use of differentiate to get to coefficients - round-off\n%%     errors cause problems. Now using newly created sumterms().\n%% Changed: 6 May 2003\n%%    Removed the attempt to use ldegree(), degree() and coeff() - results\n%%     with these are inconsistent.\n%% Changed: 16 April 2014\n%%    Used the comment header and tests in OctSymPy, but rewrote\n%%    the body (by Colin Macdonald).\n\nfunction c = sym2poly(p, x)\n\n  if ~(isscalar(p))\n    error ('sym2poly: works for scalar input only');\n  end\n\n  if (nargin == 1)\n    ss = findsymbols(p);\n    if (length (ss) >= 2)\n      error ('sym2poly: input has more than one symbol: not clear what you want me to do')\n    elseif (length (ss) == 1)\n      x = ss{1};\n    else\n      x = sym('x');\n    end\n    convert_to_double = true;\n  elseif (nargin == 2)\n    convert_to_double = false;\n  else\n    print_usage ();\n  end\n\n  cmd = { 'f = _ins[0]'\n          'x = _ins[1]'\n          'p = Poly.from_expr(f,x)'\n          'return p.all_coeffs(),' };\n\n  c2 = pycall_sympy__ (cmd, sym(p), sym(x));\n  if (isempty(c2))\n    error ('sym2poly: empty python output, can this happen?  A bug.')\n  end\n\n  % FIXME: should be able to convert c2 to array faster than array\n  % expansion!  Particularly in the case where we just convert to\n  % double anyway!\n  c = sym([]);\n  for j = 1:numel(c2)\n    % Bug #17\n    %c(j) = c2{j};\n    idx.type = '()'; idx.subs = {j};\n    c = subsasgn(c, idx, c2{j});\n  end\n\n  if (convert_to_double)\n    c = double(c);\n  end\n\nend\n\n\n%!shared x,y,a,b,c\n%! syms x y a b c\n%!assert (isequal (sym2poly (x^2 + 3*x - 4), [1 3 -4]))\n%!assert (isequal (sym2poly (x^6 - x^3), [1 0 0 -1 0 0 0]))\n%!assert (isequal (sym2poly (x^2 + 3*x - 4, x), [1 3 -4]))\n%!assert (norm (sym2poly (pi*x^2 + exp(sym(1))) - [pi 0 exp(1)]) < 10*eps)\n%% types\n%!assert (isa (sym2poly (x^2 + 3*x - 4), 'double'))\n%!assert (isa (sym2poly (x^2 + 3*x - 4, x), 'sym'))\n%% tests with other vars\n%!assert (isequal (sym2poly (x^2+y*x, x), [sym(1) y sym(0)]))\n%!assert (isequal (sym2poly (x^2+y*x, y), [x x^2]))\n%% inverse relationship\n%!assert (isequal (sym2poly (poly2sym ([a b c], x), x), [a b c]))\n%!assert (isequal (poly2sym (sym2poly(a*x^2 + c, x), x), a*x^2 + c))\n%!assert (isequal (sym2poly (poly2sym ([1 2 3])), [1 2 3]))\n\n%!error <more than one symbol>\n%! % too many symbols for single-input\n%! p = a*x^2 + 2;\n%! c = sym2poly (p);\n\n%!assert (isequal (sym2poly (sym(5)), sym(5)))\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/sym2poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.7826624840223699, "lm_q1q2_score": 0.5697590731480522}}
{"text": "function n = ndims(t)\n%NDIMS Number of dimensions of a sparse tensor.\n%\n%   NDIMS(T) returns the number of dimensions of sparse tensor T.  \n%\n%   Examples:\n%   T = sptenrand([3 2 2],5); \n%   ndims(T) %<-- should return 3\n%\n%   See also SPTENSOR.\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\n\nn = size(t.size,2);\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/@sptensor/ndims.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.5697590657672075}}
{"text": "function pass = test_size(pref)\n%TEST_SIZE     Test the SIZE method of the CHEBMATRIX class\n%%\n% Create some CHEBMATRIX objects and check their sizes:\nx = chebfun(@(x) x);\nD = operatorBlock.diff();\nS = functionalBlock.sum();\n\nff = chebmatrix([x, x, x]);\nA = [[D, D, D]; [S, S, S]];\nB = [[D x]; [S 1]];\n\npass(1) = all(size(ff) == [1 3]);\npass(2) = all(size(ff') == [3 1]);\npass(3) = all(size(A) == [2 3]);\npass(4) = all(size(A') == [3 2]);\npass(5) = all(size(B) == [2 2]);\npass(6) = all(size(B) == [2 2]);\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/tests/chebmatrix/test_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5697590648386139}}
{"text": "function calc_prob\n\n\n%%\n\nnGames = 50; % number of games\nbet = 100; % units: escudos\n\npwin = 0.8; % probability of winning\nploss = 1 - pwin; % loosing probability\n\nrate = 0.25;  % paying bet (what the house pays). This will be the average of\n% bet payment with multiple bets\n\nearnings =  ( (rate * win) -  ploss) * bet * nGames", "meta": {"author": "Lisandro79", "repo": "BeatTheBookie", "sha": "7add209d0d097af0f8b714e388cf05849db7f969", "save_path": "github-repos/MATLAB/Lisandro79-BeatTheBookie", "path": "github-repos/MATLAB/Lisandro79-BeatTheBookie/BeatTheBookie-7add209d0d097af0f8b714e388cf05849db7f969/src/aux_files/calc_prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5697581725202969}}
{"text": "function [satp] = satposin(t,eph)\n%  SATPOSIN   Calculation of X,Y,Z coordinates in an INERTIAL\n%\t      reference frame at time t for given ephemeris eph\n\n% Written by Kai Borre\n% November 15, 1996\n\n   GM = 3.986008e14;\t\t% earth's universal gravitational parameter\n\t\t\t\t% m^3/s^2\n\n   %  Units are either seconds, meters, or radians\n   %  Assigning the local variables to eph\n   svprn   =   eph(1);\n   af2\t   =   eph(2);\n   M0\t   =   eph(3);\n   roota   =   eph(4);\n   deltan  =   eph(5);\n   ecc\t   =   eph(6);\n   omega   =   eph(7);\n   cuc\t   =   eph(8);\n   cus\t   =   eph(9);\n   crc\t   =  eph(10);\n   crs\t   =  eph(11);\n   i0\t   =  eph(12);\n   idot    =  eph(13);\n   cic\t   =  eph(14);\n   cis\t   =  eph(15);\n   Omega0  =  eph(16);\n   Omegadot=  eph(17);\n   toe\t   =  eph(18);\n   af0\t   =  eph(19);\n   af1\t   =  eph(20);\n   t0c\t   =  eph(21);\n\n   % Procedure for coordinate calculation\n   A = roota*roota;\n   t = check_t(t-t0c);\n   n0 = sqrt(GM/A^3);\n   n = n0+deltan;\n   M = M0+n*t;\n   M = rem(M,2*pi);\n   E = M;\n   E_old = E+.001;\n   while abs(E-E_old) >= 1.e-12\n      E_old = E;\n      E = M+ecc*sin(E);\n   end\n   v = atan2(sqrt(1-ecc^2)*sin(E), cos(E)-ecc);\n   phi = v+omega;\n   phi = rem(phi,2*pi);\n   u = phi\t\t      + cuc*cos(2*phi)+cus*sin(2*phi);\n   r = A*(1-ecc*cos(E))       + crc*cos(2*phi)+crs*sin(2*phi);\n   i = i0+idot*t\t      + cic*cos(2*phi)+cis*sin(2*phi);\n   Omega = Omega0+Omegadot*t;\n   x1 = cos(u)*r;\n   y1 = sin(u)*r;\n   satp(1,1) = x1*cos(Omega)-y1*cos(i)*sin(Omega);\n   satp(2,1) = x1*sin(Omega)+y1*cos(i)*cos(Omega);\n   satp(3,1) = y1*sin(i);\n\n%%%%%%%%% end satposin.m %%%%%%%%%\n\u001a", "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/satposin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.5697147661025241}}
{"text": "function [logbf] = spm_mlm_posthoc (mlm,c,a)\n% Post-hoc model comparison of multivariate linear models\n% FORMAT [logbf] = spm_mlm_posthoc (mlm,c,a)\n%\n% mlm          MLM data structure - see spm_mlm_bayes.m\n%              This contains eg. the [p x d] posterior mean regression  \n%              coefficient matrix mlm.wmean. \n%\n% c            [k x p*d] contrast matrix defining k-dimensional subspace\n% a            hypothesized value (zeros(k,1) by default)\n%\n% The contrast matrix and hypothesized value define the reduced model. \n% The contrast is applied to the vectorised parameters w = vec(mlm.wmean)\n%             \n% The Bayes Factor in favour of the alternative hypothesis over the null\n% is computed using a Savage-Dickey ratio (the probability of the\n% hypothesized value under the prior versus its probability under the\n% posterior)\n%\n% bf = p(c*w=a|mlm)/p(c*w=a|Y,mlm)              \n%\n% logbf        Log Bayes Factor\n%___________________________________________________________________________\n% Copyright (C) 2011 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: spm_mlm_posthoc.m 4651 2012-02-09 16:03:39Z will $\n\nwpost=mlm.wmean(:);\n\npost_mean=c*wpost;\nk=size(post_mean,1);\nprior_mean=zeros(k,1);\n\npost_cov=c*mlm.wcov*c';\n\n% Get prior covariance matrix\nprec_prior=size(mlm.wcov,1);\nfor g=1:mlm.prior.groups,\n    prec_prior=prec_prior+mlm.prior.group(g).mean_alpha*mlm.prior.group(g).index;\nend\nw_prior_cov=diag(1./prec_prior);\nprior_cov=c*w_prior_cov*c';\n\nif nargin < 3 | isempty (a)\n    a=zeros(k,1);\nend\n\n% Enforce symmetry - to avoid numerical issues\nprior_cov=(prior_cov+prior_cov')/2;\npost_cov=(post_cov+post_cov')/2;\n\n% For now just use spm_mvNpdf. This can be made more efficient !\nprior_prob=spm_mvNpdf(a,prior_mean,prior_cov);\npost_prob=spm_mvNpdf(a,post_mean,post_cov);\n\nlogbf=log(prior_prob)-log(post_prob);", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mlm/spm_mlm_posthoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.569714764572851}}
{"text": "%GAUSSM Trainable mapping, mixture of Gaussians (MoG) density estimate\n%\n%  W = GAUSSM(A,K,R,S,M)\n%  W = A*GAUSSM([],K,R,S,M)\n%  W = A*GAUSSM(K,R,S,M)\n%\n% INPUT\n%   A     Dataset\n%   K     Number of Gaussians per class\n%   R,S,M Regularization parameters, 0 <= R,S <= 1, see QDC\n%\n% OUTPUT\n%   W     Mixture of Gaussians density estimate\n%\n% DESCRIPTION\n% Estimation of a PDF by the dataset A by a mixture of Gaussians procedure.\n% Use is made of EMCLUST(A,QDC,K). Unlabeled objects are neglected, unless\n% A is entirely unlabeled or double. Then all objects are used. If A is a\n% multi-class crisp labeled dataset the densities are estimated class by\n% class and then weighted and combined according their prior probabilities.\n% Use +A instead of A to obtain a single set of Gaussians. In all cases,\n% just single density estimator W is returned.\n%\n% Note that it is necessary to set the label type of A to soft labels\n% (A = LABTYPE(A,'soft') in order to use the traditional EM algorithm\n% based on posterior probabilities instead of using crisp labels.\n% \n% The mapping W may be applied to a new dataset B using DENSITY = B*W.\n%\n%  W = A*GAUSSM\n%\n% uses a single Gaussian per class (K=1) and no regularisation. If\n% regulariisation is desired, also K should be supplied.\n%\n% EXAMPLE\n% a = gendatb;\n% w = a*gaussm(2);\n% scatterd(a)\n% plotm(w)\n%\n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% DATASETS, MAPPINGS, QDC, MOGC, EMCLUST, PLOTM, TESTC\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: gaussm.m,v 1.8 2009/02/02 21:57:39 duin Exp $\n\nfunction w = gaussm(varargin)\n\n  mapname = 'Mixture of Gaussians';\n\targin = shiftargin(varargin,'scalar');\n  argin = setdefaults(argin,[],1,0,0,[]);\n  if mapping_task(argin,'definition')\n    w = define_mapping(argin,'untrained');\n    w = setname(w,mapname);\n  else\n    [a,n,r,s,dim] = deal(argin{:});\n\t\n    if isa(a,'prdataset')\n      labname = getname(a);\n    else\n      labname = '';\n    end\n    \n    if ((~isdataset(a) && ~isdatafile(a)) || ...\n        (getsize(a,3) ~= 1 && islabtype(a,'crisp')))\n      % this handles the multiclass situation\n      w = mclassm(a,prmapping(mfilename,n),'weight');\n      w = setlabels(w,labname);\n      w = setname(w,mapname);\n      \n    else\n      % here we have a single class\n      [m,k] = getsize(a);\n      if n == 1\n        % just one Gaussian, esitmate it\n        [U,G] = meancov(a);\n        res.mean = +U;\n        res.cov  = G;\n        res.prior= 1;\n        w = normal_map(res,labname,k,1);\n      else\n        % multiple Gaussians, run EM\n        [e,v] = emclust(a,qdc([],r,s,dim),n);\t\n        ncomp0 = size(v.data.mean,1);\t\n        iter = 0;\n        while (ncomp0 ~= n & iter < 5)   % repeat until exactly n components are found\n          [e,v1] = emclust(a,qdc([],r,s,m),n);\t\t\t\t\n          ncomp1 = size(v1.data.mean,1);\n          if ncomp1 > ncomp0\n            v = v1;\n            ncomp0 = ncomp1;\n          end\n          iter = iter + 1;\n        end\n        res = v.data;\n        res.nlab = ones(n,1); % defines that all Gaussian components have to be\n                              % combined into a single class.\n        w = prmapping('normal_map','trained',res,labname,k,1);\n      end\n      w = setname(w,mapname);\n      \n    end\n    \n  end\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/gaussm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5696786905400278}}
{"text": "function ns = count_squares_fisheye_distorted(I,x1,y1,x2,y2,win, fg, cg, kg);\n\n[ny,nx] = size(I);\n\nif ((x1-win <= 0) || (x1+win >= nx) || (y1-win <= 0) || (y1+win >= ny) || ...\n        (x2-win <= 0) || (x2+win >= nx) || (y2-win <= 0) || (y2+win >= ny))\n    ns = -1;\n    return;\nend;\n\n\nif ((x1 - x2)^2+(y1-y2)^2) <  win,\n    ns = -1;\n    return;\nend;\n\nnX = round(sqrt((x1-x2)^2 + (y1-y2)^2));\nalpha_x = (0:nX)/nX;\n\npt1n = normalize_pixel_fisheye([x1;y1]-1,fg,cg,kg,0);\npt2n = normalize_pixel_fisheye([x2;y2]-1,fg,cg,kg,0);\n\nptsn = repmat(pt1n,[1 nX+1]) + (pt2n - pt1n)*alpha_x;\n\npts = apply_fisheye_distortion(ptsn,kg);\npts(1,:) = fg(1)*pts(1,:) + cg(1);\npts(2,:) = fg(2)*pts(2,:) + cg(2);\n\n% Check that the curve is within the image:\ngood_line = (min(pts(1,:))-win > 0) && (max(pts(1,:))+win < (nx-1)) && ...\n    (min(pts(2,:))-win > 0) && (max(pts(2,:))+win <(ny-1));\n\nif ~good_line,\n    ns = -1;\n    return;\nend;\n\n% Deviate the trajectory orthogonally:\nlambda = [y1 - y2 ; x2 - x1];\nlambda = lambda / sqrt(sum(lambda.^2));\n\nNp = size(pts,2);\nxs_mat = ones(2*win + 1,1)*pts(1,:);\nys_mat = ones(2*win + 1,1)*pts(2,:);\nwin_mat = (-win:win)'*ones(1,Np);\nxs_mat2 = round(xs_mat - win_mat * lambda(1));\nys_mat2 = round(ys_mat - win_mat * lambda(2));\nind_mat = (xs_mat2) * ny + ys_mat2 + 1;\nima_patch = zeros(2*win + 1,Np);\nima_patch(:) = I(ind_mat(:));\n\nfiltk = [ones(win,Np);zeros(1,Np);-ones(win,Np)];\nout_f = sum(filtk.*ima_patch);\nout_f_f = conv2(out_f,[1/4 1/2 1/4],'same');\nout_f_f = out_f_f(win+1:end-win);\nns = length(find(((out_f_f(2:end)>=0)&(out_f_f(1:end-1)<0)) | ((out_f_f(2:end)<=0)&(out_f_f(1:end-1)>0))))+1;\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/count_squares_fisheye_distorted.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5696786848983716}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\n\nfunction phi = cf_merton(u,lnS,T,r,d,sigma,a,b,lambda)\n% characteristic function for the Merton model\n    phi = exp(cf_black(u,lnS,T,r,d,sigma) ...\n        + cf_lognormjump(u,a,b,lambda,T));\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/36966-risk-neutral-densities-for-financial-models/cf_merton.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5696786812296161}}
{"text": "% computes the pose vector v from a homogeneous transform A\nfunction v=t2v(A)\n  v = [A(1:2,3); atan2(A(2,1),A(1,1))];\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/tools/t2v.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276224, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5696786766532335}}
{"text": "function model = mogUpdateCovariance(model)\n\n% MOGUPDATECOVARIANCE Update the covariances of an MOG model.\n% FORMAT\n% DESC updates the covariance matrices of a mixtures of\n% Gaussians model. The implementation currently uses an\n% eigenvalue based update.\n% ARG model : the model which is to be updated.\n% RETURN model : the model with updated covariances.\n%\n% SEEALSO : mogCreate, mogUpdateMean, mogEstep\n%\n% COPYRIGHT : Neil D. Lawrence, 2006\n\n% MLTOOLS\n\nfor i = 1:model.m\n\n  centredY = model.Y - repmat(model.mean(i,:), model.N, 1);\n  centredY = centredY.*repmat(sqrt(model.posterior(:,i)), 1, model.d);\n  switch model.covtype\n    case 'ppca'\n     C = (centredY'*centredY+0.001*eye(model.d))/sum(model.posterior(:, i)+.001);\n     [vec, val] = eig(C);\n     val = diag(val);\n     [val, ind] = sort(val);\n     ind = ind(end:-1:1);\n     val = val(end:-1:1);\n     vec = vec(:, ind(1:model.q));\n     sigma2 = mean(val(model.q+1:end));\n     if sigma2<eps\n       sigma2 = eps;\n     end\n     lambda = val(1:model.q) - sigma2;\n     %[sigma2, eigVec, lambda] = ppca(C, model.q);\n     if length(lambda) ~= model.q\n       % Something's wrong here ...\n       sigma2 = 1e-6;\n       warning('Not enough eigenvalues extracted.')\n       lambdaTemp = lambda;\n       lambda = zeros(model.q, 1);\n       lambda(1:length(lambdaTemp)) = lambdaTemp;\n     end \n    \n     model.sigma2(i) = sigma2;\n     model.W{i} = vec*diag(sqrt(lambda));\n     model.U{i} = sqrt(sigma2)*eye(model.d);\n     for j = 1:model.q\n       model.U{i} = cholupdate(model.U{i}, model.W{i}(:, j));\n     end\n   case 'spherical'\n    model.sigma2(i) = sum(sum(centredY.*centredY))/(model.d*sum(model.posterior(:, i)));\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/mltools/mogUpdateCovariance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5696786629240842}}
{"text": "function [connectivity, pValues, freq] = bst_granger_spectral(X, Y, Fs, order, inputs)\n% BST_GRANGER_SPECTRAL  Granger causality at each frequency between any two\n%                       signals.\n%\n% Inputs:\n%   X                 - first set of signals, one signal per row\n%                       [X: A x N or A x N x T matrix]\n%   Y                 - second set of signals, one signal per row\n%                       [Y: B x N or B x N x T matrix]\n%                       (default: Y = X)\n%   Fs                - sampling rate (we assume uniform sampling rate)\n%                       [FS: scalar, FS > freq(end)*2]\n%   order             - maximum order of autogressive model\n%                       [p: integer > 1, default 10]\n%   inputs            - structure of parameters:\n%   |-freq            - frequencies of interest if desired\n%   |-freqResolution  - maximum freq resolution in Hz, to limit NFFT\n%   |                   [DF: double, default [] (i.e. no limit)]\n%   |-nTrials         - # of trials in concantenated signal\n%   |-flagFPE         - if true, optimize order for autoregression\n%   |                   if false (default), use same order in autoregression\n%   |-standardize     - if true (default), remove mean from each signal\n%   |                   if false, assume signal has already been detrended\n%\n% Outputs:\n%   connectivity      - A x B matrix of spectral Granger causalities from\n%                       source to sink. For each signal pair (a,b) we calculate\n%\n%                                        S_{sink} (f)\n%                  ------------------------------------------------------------\n%                  S_{sink}(f) - |H_{sink, source} (f)|^2 sigma_{source | sink}\n%\n%                       with S_{sink}(f) as the power spectral density of a @ f\n%                            H_{sink, source}(f) as the transfer function @ f\n%                            sigma_{source | sink} as the conditional variance\n%                             of the residual at b given the residual at a,\n%                             calculated using the residual covariance.\n%                       By default, GC(a,a) = 0 if Y is empty.\n%                       [C: MX x MY x NF matrix]\n%   pValues           - parametric p-value for corresponding spectral Granger\n%                       causality in mean estimate\n%                       [P: MX x MY x NF matrix]\n%   freq              - frequencies corresponding to the previous two metrics\n%                       [F: NF x 1 vector]\n%\n% See also BST_GRANGER, BST_COHERENCE_MVAR.\n%\n% Call:\n%   connectivity = bst_granger_spectral(X, Y, 200, 10, inputs); % general call\n%   connectivity = bst_granger_spectral(X, [], 200, 30, inputs); % every pair\n%   connectivity = bst_granger_spectral(X, [], 200, 30, inputs); % more variance\n% Parameter examples:\n%   inputs.freq           = 0:0.1:100; % specify desired frequencies\n%   inputs.freqResolution = 0.1; % have a high-point FFT\n%   inputs.nTrials        = 9; % use trial-average covariances in AR estimation\n%   inputs.flagFPE        = true; % use AR model with best information criteria\n\n% Note: for those following Chicharro2012, I have used the equivalence\n%                       sigma_{xx}^(xy) |H_{xx}^(xy) (w)|^2\n%                                       =\n%                S_{xx}(w) - sigma_{yy}^(xy) |H_{xy}^(xy) (w)|^2\n% which follows Geweke1982 instead. As Chicharro notes, it may be better to use his\n% formulation because it separates out instantaneous causality I think.\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: Sergul Aydore & Syed Ashrafulla, 2012\n\n% reformat to a 2D matrix if necessary, and pull out # of trials\nif ndims(X) == 3\n  inputs.nTrials = size(X,3);\n  X = reshape(X, size(X, 1), []);\nelseif ~isfield(inputs, 'nTrials')\n  inputs.nTrials = 1;\nend\n\n% lengths of things\nnSamples = size(X, 2);\nnTimes = nSamples / inputs.nTrials;\n\n% standardization: zero mean & unit variance, remove linear & quadratic trends as well\nif isfield(inputs, 'standardize') && inputs.standardize\n  detrender = [ ...\n    ones(1, nTimes); ... % constant trend in data\n    linspace(-1, 1, nTimes); ... % linear trend in data\n    3/2 * linspace(-1, 1, nTimes).^2 - 1/2 ... % quadratic trend in data\n  ];\n  \n  % detrend X\n  for iTrial = 1:inputs.nTrials\n    X(:, (iTrial-1)*nTimes + (1:nTimes)) = X(:, (iTrial-1)*nTimes + (1:nTimes)) - ( X(:, (iTrial-1)*nTimes + (1:nTimes)) / detrender ) * detrender;\n    X(:, (iTrial-1)*nTimes + (1:nTimes)) = diag( sqrt(sum(X(:, (iTrial-1)*nTimes + (1:nTimes)).^2, 2)) ) \\ X(:, (iTrial-1)*nTimes + (1:nTimes));\n  end\n  \n  % detrend Y only if it is not empty\n  if ~isempty(Y)\n    Y = reshape(Y, size(Y, 1), []); % reshape to 2D matrix first\n    for iTrial = 1:inputs.nTrials\n      Y(:, (iTrial-1)*nTimes + (1:nTimes)) = Y(:, (iTrial-1)*nTimes + (1:nTimes)) - ( Y(:, (iTrial-1)*nTimes + (1:nTimes)) / detrender ) * detrender;\n      Y(:, (iTrial-1)*nTimes + (1:nTimes)) = diag( sqrt(sum(Y(:, (iTrial-1)*nTimes + (1:nTimes)).^2, 2)) ) \\ Y(:, (iTrial-1)*nTimes + (1:nTimes));\n    end\n  end\nend\n\n% number of FFT bins required\nif ~isfield(inputs, 'freq') || isempty(inputs.freq) % frequencies of interest are not defined\n  if isfield(inputs, 'freqResolution') && ~isempty(inputs.freqResolution) && (size(X,2) > round(Fs / inputs.freqResolution))\n    nFFT = 2^nextpow2( round(Fs / inputs.freqResolution) );\n  else % use a default frequency resolution of 1Hz to mirror the standard frequency resolution in bst_coherence_welch.m\n    nFFT = 2^nextpow2( round(Fs / 1) );\n  end\nelseif numel(inputs.freq) == 1\n  nFFT = inputs.freq;\nelse\n  nFFT = 2^nextpow2(max( length(inputs.freq)-1, (Fs/2) / min(diff( sort(inputs.freq(:)) )) )) * 2;\nend\n\n% default: Order 10 used in BrainStorm\nif isempty(order)\n  order = 10;\nend\n\n% default: Single-trial\nif ~isfield(inputs, 'nTrials') || isempty(inputs.nTrials)\n  inputs.nTrials = 1;\nend\n\n% default: do not optimize model order\nif ~isfield(inputs, 'flagFPE') || isempty(inputs.flagFPE)\n  inputs.flagFPE = false;\nend\n\n%% Differentiate between auto-causality and cross-causality for speed\n\nif isempty(Y) % auto-causality between signals in X, so we can halve the number of models to estimate\n  \n  % preallocate the spectral causality matrix\n  connectivity = zeros(size(X, 1), size(X, 1), nFFT/2); \n  \n  % iterate over all pairs of sinks & sources\n  for iX = 1:size(X, 1)\n    for iY = iX+1 : size(X, 1) % to avoid auto-causality\n      \n        % two-variate model for given source\n        [transfers, noiseCovariance, order] = bst_mvar([X(iX, :); X(iY, :)], order, inputs.nTrials, inputs.flagFPE);\n        \n        % spectra and power of forward system\n        [spectra, freq, forward] = bst_granger_spectral_spectrum(transfers, noiseCovariance, nFFT, Fs);\n\n        % Geweke-Granger spectral causality from source to sink\n        unrestricted = abs(spectra(1, 1, :)); restriction = forward(1, 2, :); % S_{sink}(f) and |H_{sink, source} (f)|^2, w/ abs to get rid of 1e-16 imag part\n        residualVariance = noiseCovariance(2,2) - noiseCovariance(2, 1) / noiseCovariance(1, 1) * noiseCovariance(1, 2); % partial variance of source\n        restricted = abs(unrestricted) - abs(restriction).^2 * residualVariance; % S_{sink} (f) - |H_{sink, source} (f)|^2 sigma_{source | sink}\n        connectivity(iX, iY, abs(restricted) > 1e-60) = unrestricted(abs(restricted) > 1e-60) ./ restricted(abs(restricted) > 1e-60) - 1;% Geweke-Granger\n        % sigma_{source | sink} = partial covariance which is the formula above (sigma_{source} - rho_{source, sink} / sigma_{sink} * rho_{sink, source})\n\n        % Geweke-Granger spectral causality from sink back to source (to halve the # of MVAR fittings)\n        unrestricted = abs(spectra(2, 2, :)); restriction = forward(2, 1, :); % S_{source}(f) and |H_{source, sink} (f)|^2, w/ abs to get rid of 1e-16 imag part\n        residualVariance = noiseCovariance(1,1) - noiseCovariance(1, 2) / noiseCovariance(2, 2) * noiseCovariance(2, 1); % partial variance of sink\n        restricted = abs(unrestricted) - abs(restriction).^2 * residualVariance; % S_{source} (f) - |H_{source, sink} (f)|^2 sigma_{sink | source}\n        connectivity(iY, iX, abs(restricted) > 1e-60) = unrestricted(abs(restricted) > 1e-60) ./ restricted(abs(restricted) > 1e-60) - 1; % Geweke-Granger\n        % sigma_{sink | source} = partial covariance which is the formula above (sigma_{sink} - rho_{sink, source} / sigma_{source} * rho_{source, sink})\n        \n    end\n    \n    % diagonal will equal the maximum of all inflows and outflows for iX, specific to each frequency\n    connectivity(iX, iX, :) = max( max(connectivity(iX, :, :), [], 2), max(connectivity(:, iX, :), [], 1) );\n    \n  end\n\nelse % we have to use all pairs of signals\n  \n  % preallocate the spectral causality matrix\n  connectivity = zeros(size(X, 1), size(Y, 1), nFFT/2); \n  duplicates = zeros(0, 2);\n  \n  % iterate over all pairs of sinks & sources\n  for iX = 1:size(X, 1)\n    for iY = 1:size(Y, 1)\n      \n      if max(abs(X(iX, :) - Y(iY, :))) > eps % by default, if X(sink) = Y(source), the causality is 0 everywhere\n\n        % 2-variate model for given source\n        [transfers, noiseCovariance, order] = bst_mvar([X(iX, :); Y(iY, :)], order, inputs.nTrials, inputs.flagFPE);\n\n        % spectra and power of forward system\n        [spectra, freq, forward] = bst_granger_spectral_spectrum(transfers, noiseCovariance, nFFT, Fs);\n        spectra = abs(spectra(1, 1, :)); % limit to the autospectrum of the sink S_{sink} (f) and take absolute value to rid the 1e-16 imaginary part\n        forward = forward(1, 2, :); % limit to the cross-transfer from source to sink H_{sink, source} (f)\n        \n        % partial covariance of residual\n        residualVariance = noiseCovariance(2,2) - noiseCovariance(2,1) / noiseCovariance(1, 1) * noiseCovariance(1, 2);\n        % sigma_{source | sink} = partial covariance which is the formula above (sigma_{source} - rho_{source, sink} / sigma_{sink} * rho_{sink, source})\n\n        % Geweke-Granger spectral causality from source to sink\n        restricted = spectra - abs(forward).^2 * residualVariance; % S_{sink} (f) - |H_{sink, source} (f)|^2 sigma_{source | sink}\n        connectivity(iX, iY, abs(restricted) > 1e-60) = spectra(abs(restricted) > 1e-60) ./ restricted(abs(restricted) > 1e-60) - 1; % Geweke-Granger\n\n      else % save duplicates to modify later\n        \n        duplicates(end+1, :) = [iX iY]; %#ok<AGROW>\n        \n      end\n      \n    end\n  end\n  \n  % for duplicate indices, set the causality value to the maximum of all inflows for iX and outflows for iY\n  for iDuplicate = 1:size(duplicates, 1)\n    connectivity(duplicates(iDuplicate, 1), duplicates(iDuplicate, 2), :) = max( ...\n      max(connectivity(duplicates(iDuplicate, 1), :, :), [], 2), ...\n      max(connectivity(:, duplicates(iDuplicate, 2), :), [], 1) ...\n      );\n  end\n  \n  \nend\n\n%% Interpolate to desired frequencies & perform statistics if desired\nif isfield(inputs, 'freq') && ~isempty(inputs.freq) && numel(inputs.freq) > 1\n  connectivity = permute(interp1(freq, permute(connectivity, [3 1 2]), inputs.freq), [2 3 1]);\n  % pValues = permute(interp1(freq, permute(pValues, [3 1 2]), inputs.freq), [2 3 1]);\n  freq = inputs.freq;\nend\n\npValues = NaN; % no parametric p-values for now\n\nend\n\n%% ======================================================== estimation for multivariate autoregression ========================================================\nfunction [spectra, freq, forward] = bst_granger_spectral_spectrum(transfers, noiseCovariance, nFFT, Fs)\n% BST_MVAR_SPECTRUM     Calculate the parametric spectra of a bivariate system\n%                       with given MVAR coefficients & an estimate of the\n%                       covariance matrix of the innovation (i.e. noise)\n%                       process.\n%\n% Inputs:\n%   transfers         - transfer matrices in AR process\n%                       [A: 2 x 2P matrix, P = order]\n%   noiseCovariance   - variance of residuals\n%                       [C: 2 x 2 matrix]\n%   nFFT              - number of FFT bins to calculate spectra\n%                       [NF: positive number, usually power of 2]\n%   Fs                - sampling frequency of data\n%                       [FS: double, FS > freq(end)*2]\n%\n% Outputs:\n%   spectra           - cross-spectrum between each pair of variables\n%                       [S: 2 x 2 x NF/2 matrix]\n%   freq              - frequencies used based on # of FFT bins\n%                       [F: NF/2 x 1 matrix]\n%   forward           - forward transform in frequency from source to sink\n%                       [H: 2 x 2 x NF/2 matrix]\n%   --> all outputs have length NF/2, ignoring frequenices past Fs/2\n%\n% Call:\n%   spectra = bst_mvar_spectrum(transfers, C, 512, 200); % basic\n%   spectra = bst_mvar_spectrum(transfers, C, 2048, 200); % add FFT interp\n%   [spectra, freq] = bst_mvar_spectrum(transfers, C, 512, 200); % grab freqs\n%   [~, ~, forward] = bst_mvar_spectrum(transfers, C, 64, 200); % causality\n\n% Notes:\n% The DTFT we want is\n% H = I - sum_p C_p e^{-j 2 pi f/Fs p} = sum_p D_p e^{-j 2 pi f/Fs (p-1)} where D_1 = 1 and D_p = -C_{p-1} for p > 1\n% MatLab's FFT provides\n% G = sum_n x_n e^{-j 2 pi (k-1)/N (n-1)}\n% so the matching is p = n and (k-1)/N = f/Fs, after vectorizing H.\n\n% frequencies to estimate cross-spectra\nfreq = Fs/2*linspace(0, 1, nFFT/2 + 1);\nfreq(end) = [];\n\n%% Inverse of transfer function in frequency\n% Inverse transfer means the transfer function from the sources to the innovations. We calculate this at each frequency.\n% The inverse transfer from source a to innovation b is\n%                1 - \\sum_{n=1}^N a_{ab} [n] e^{-j2pi * f * n}\n\ninverse = fft(reshape([eye(2) -transfers], 4, [])', nFFT); % reshape so we can do a vector FFT quickly\ninverse = inverse(1:nFFT/2, :); % restrict to the first symmetric half of the spectrum\n\n%% Forward transfer in autoregressive model\n\n% pieces of 2x2 inverse\nforward = zeros(2, 2, nFFT/2); % an important caveat is that I did not reshape inverse earlier;\nforward(1,1,:) = inverse(:,4); forward(1,2,:) = -inverse(:,3); % as a result, we have a column-wise index mapping: 4 = (2,2) and 3 = (1,2)\nforward(2,1,:) = -inverse(:,2); forward(2,2,:) = inverse(:,1); % in addition, 2 = (2,1) and 1 = (1,1). then these elements fit the 2x2 matrix inverse\ndetInverse = inverse(:,1).*inverse(:,4) - inverse(:,3).*inverse(:,2); % the same thing happens here, using the indexing to avoid a reshape() call\n\n% normalization by determinant to get inverse\nforward = bst_bsxfun(@rdivide, forward, reshape(detInverse, [1 1 length(freq)])); % complete the inversion by dividing by frequency-dependent determinant\n\n%% Cross-spectrum from forward model\n% The forward transfer is the inverse of the inverse transfer at each frequency f. Denoted H(f), the power spectral density is then HH' at each frequency.\n\n% the loop that we won't use\n% for idxFreq = 1:nFFT\n%   spectra(:, :, idxFreq) = H(:,:,idxFreq) * noiseCovariance * H(:,:,idxFreq)';\n% end\n\n% formula for the matrix multiplication\nspectra(1,1,:) = ... % 1,1 element is H_11 C_11 H_11^* + H_12 C_12 H_11^* + H_11 C_12 H_12^* + H_12 C_22 H_12^* (and I combine the middle two into 2 Re{.})\n  noiseCovariance(1,1) * forward(1,1,:) .* conj(forward(1,1,:)) ...\n  + noiseCovariance(1,2) * real(forward(1,2,:) .* conj(forward(1,1,:))) * 2 ...\n  + noiseCovariance(2,2) * forward(1,2,:) .* conj(forward(1,2,:));\nspectra(1,2,:) = ... % 1,2 element is H_11 C_11 H_21^* + H_12 C_12 H_21^* + H_11 C_12 H_22^* + H_12 C_22 H_22^*\n  noiseCovariance(1,1) * forward(2,1,:) .* conj(forward(1,1,:)) ...\n  + noiseCovariance(1,2) * forward(2,2,:) .* conj(forward(1,1,:)) ...\n  + noiseCovariance(1,2) * forward(2,1,:) .* conj(forward(1,2,:)) ...\n  + noiseCovariance(2,2) * forward(1,2,:) .* conj(forward(1,2,:));\nspectra(2,1,:) = conj(spectra(1,2,:)); % for speed, force the 2,1 element to be the conjugate of the 1,2 element so we have conjugate symmetry\nspectra(2,2,:) = ... % 2,2 element is H_21 C_11 H_21^* + H_22 C_12 H_21^* + H_21 C_12 H_22^* + H_22 C_22 H_22^* (and I combine the middle two into 2 Re{.})\n  noiseCovariance(1,1) * forward(2,1,:) .* conj(forward(2,1,:)) ...\n  + noiseCovariance(1,2) * real(forward(2,2,:) .* conj(forward(2,1,:))) * 2 ...\n  + noiseCovariance(2,2) * forward(2,2,:) .* conj(forward(2,2,:));\n\n%% Normalize for sampling rate, and truncate if necessary\n\n% normalization\nforward = forward / sqrt(Fs);\nspectra = spectra / Fs;\n\n%% Confidence intervals\n% taken from Kay, pp 194-195\n% alpha = 1 - ci;\n% original = -sqrt(2) * erfcinv( 2 * ( 1 - alpha/2) );\n% lower = abs(spectra) * (1 - sqrt(2 * order / nTimes) * original);\n% upper = abs(spectra) * (1 + sqrt(2 * order / nTimes) * original);\n\nend %% <== FUNCTION END", "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/connectivity/bst_granger_spectral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5696786571247827}}
{"text": "function Y = sladdvec(X, v, d)\n%SLADDVEC adds a vector to columns or rows of a matrix\n%\n% $ Syntax $\n%   - Y = sladdvec(X, v, d)\n%   - Y = sladdvec(X, v)\n%\n% $ Arguments $\n%   - X:        The original matrix\n%   - v:        The addend vector\n%   - d:        The dimension along which the vector is to add\n%   - Y:        The resultant matrix\n%\n% $ Description $\n%   - Y = sladdvec(X, v, d) selects the most efficienct way to add a \n%     vector v to every column/row of X. If d == 1, then v should be \n%     a column vector, and is added to each column of X, if d == 2,\n%     then v should be a row vector, and is added to each row of X.\n%\n%   - Y = sladdvec(X, v) will automatically determine d according to\n%     the shape of v.\n%\n% $ Remarks $\n%   - The implementation simply wraps the mex function vecop_core.\n%\n% $ History $\n%   - Created by Dahua Lin, on Sep 10, 2006\n%\n\nif nargin < 3\n    if size(v, 2) == 1\n        d = 1;\n    else\n        d = 2;\n    end\nend\n\nY = vecop_core(X, v, d, 1);  % 1 is the opcode of addition in vecop_core\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/core/sladdvec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.5696650191689137}}
{"text": "function [bcx,bcy] = specific_flow(xbd,ybd)\n%regcavity_flow   Reference problem 5.3 default inflow condition \n%   [bcx,bcy] = specific_flow(xbd,ybd);\n%   input\n%          xbd          x coordinate vector\n%          ybd          y coordinate vector \n%\n%   specifies regularized cavity flow boundary condition\n%   IFISS function: DJS; 6 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nbcx=0*xbd; bcy=0*xbd;\nk=find(ybd==1 & xbd>-1 & xbd<1); bcx(k)=(1-xbd(k).*xbd(k)).*(1+xbd(k).*xbd(k));\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/stokes_flow/test_problems/regcavity_flow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5696650102546761}}
{"text": "% THE DIAGNOSTIC TOOLS (in the diag-folder):\n%\n% Covergence diagnostics\n%   PSRF     - Potential Scale Reduction Factor\n%   CPSRF    - Cumulative Potential Scale Reduction Factor\n%   MPSRF    - Multivariate Potential Scale Reduction Factor\n%   CMPSRF   - Cumulative Multivariate Potential Scale Reduction Factor\n%   IPSRF    - Interval-based Potential Scale Reduction Factor\n%   CIPSRF   - Cumulative Interval-based Potential Scale Reduction Factor\n%   KSSTAT   - Kolmogorov-Smirnov goodness-of-fit hypothesis test\n%   HAIR     - Brooks' hairiness convergence diagnostic\n%   CUSUM    - Yu-Mykland convergence diagnostic for MCMC\n%   SCORE    - Calculate score-function convergence diagnostic\n%   GBINIT   - Initial iterations for Gibbs iteration diagnostic\n%   GBITER   - Estimate number of additional Gibbs iterations\n%\n% Time series analysis\n%   ACORR      - Estimate autocorrelation function of time series\n%   ACORRTIME  - Estimate autocorrelation evolution of time series (simple)\n%   GEYER_ICSE - Compute autocorrelation time tau using Geyer's\n%                initial convex sequence estimator\n%                (requires Optimization toolbox) \n%   GEYER_IMSE - Compute autocorrelation time tau using Geyer's\n%                initial monotone sequence estimator\n%\n% Kernel density estimation etc.:\n%   KERNEL1  - 1D Kernel density estimation of data\n%   KERNELS  - Kernel density estimation of independent components of data\n%   KERNELP  - 1D Kernel density estimation, with automatic kernel width\n%   NDHIST   - Normalized histogram of N-dimensional data\n%   HPDI     - Estimates the Bayesian HPD intervals\n%\n% Manipulation of MCMC chains\n%   THIN     - Delete burn-in and thin MCMC-chains\n%   JOIN     - Join similar structures of arrays to one structure of arrays\n%   BATCH    - Batch MCMC sample chain and evaluate mean/median of batches\n%\n% Misc:\n%   CUSTATS   - Calculate cumulative statistics of data\n%   BBPRCTILE - Bayesian bootstrap percentile\n%   GRADCHEK  - Checks a user-defined gradient function using finite\n%               differences.\n%   DERIVATIVECHECK - Compare user-supplied derivatives to\n%                     finite-differencing derivatives.\n%\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/diag/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.5696650065337279}}
{"text": "function determ = wilk04_determinant ( )\n\n%*****************************************************************************80\n%\n%% WILK04_DETERMINANT returns the determinant of the WILK04 matrix.\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%  Parameters:\n%\n%    Output, real DETERM, the determinant.\n%\n  determ = 0.9143E-04 * 0.7156E-04 * 0.9504E-04 * 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_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.5696650059447913}}
{"text": "function plot_fourier_approx(ai, n, m, normalized, color, line_width)\n\n% This function will plot the fourier approximation, given a chain code (ai), \n% number of harmonic elements (n), and number of points for reconstruction (m). \n% Normalization can be applied by setting \"normalized = 1\".\n\n    if (nargin < 5)\n        color = 'b';\n        line_width = 2;\n    end\n    \n    if (nargin < 6)\n        line_width = 2;\n    end\n\n    % Do Fourier approximatoin\n    k = size(ai, 2);\n    x_ = fourier_approx(ai, n, m, normalized);\n\n    % Make it closed contour\n    x = [x_; x_(1,1) x_(1,2)];\n             \n    plot(x(:,1), x(:,2), color, 'linewidth', line_width);\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/32800-elliptic-fourier-for-shape-analysis/plot_fourier_approx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5696649985028944}}
{"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% - initialize\n%     data:            Hands,           see setup2DhandData, level = 5;\n%     visualization:   viewImage2D,     see viewImage.m\n%     interpolation:   splineInter,   see inter.m\n%     distance:        SSD,             see distance.m\n%     regularizer:     mfElastic,       see regularizer.m\n% - initialize FAIR plots\n% - run optimization\n%     NPIR:            Non-Parametric Image Registration, Trust-Region\n% ===============================================================================\n\nclear; close all; help(mfilename)\n\nsetup2DhandData\nlevel = 5; omega = ML{level}.omega; m = ML{level}.m;\nimgModel('reset','imgModel','splineInter','regularizer','moments','theta',0.01);\ndistance('reset','distance','SSD');\nregularizer('reset','regularizer','mfElastic','alpha',1000,'mu',1,'lambda',0);\n\n[T,R] = imgModel('coefficients',ML{level}.T,ML{level}.R,omega);\nxc    = getStaggeredGrid(omega,m); % starting guess and reference for regularization\nRc    = imgModel(R,omega,center(xc,m)); \n\n% - initialize FAIR plots\nFAIRplots('set','mode','TR-mf','fig',1);\nFAIRplots('init',struct('Tc',T,'Rc',R,'omega',omega,'m',m)); \n\n% - run Non-Parametric Image Registration (Gauss-Newton)\nfctn = @(yc) NPIRobjFctn(T,Rc,omega,m,xc,yc);  fctn([]);\nyc = TrustRegion(fctn,xc,'Plots',@FAIRplots);\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/E9_Hands_NPIRmf_TR_nopre.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.5695203123641623}}
{"text": "function [D,S,C] = signed_distance_direction(P,V,F)\n  % SIGNED_DISTANCE_DIRECTION Compute a direction which decreases signed\n  % distance with respect to an input mesh (V,F) at a set of points P.\n  %\n  % [D,S,C] = signed_distance_direction(P,V,F)\n  %\n  % Inputs:\n  %   P  #P by dim list of query points\n  %   V  #V by dim list of mesh vertex positions\n  %   F  #F by dim+1 list of mesh indices into V\n  % Outputs:\n  %   D  #P by dim list of normalized directions\n  %   S  #P signed distances\n  %   C  #P by dim list of closest points\n  %\n\n  dim = size(F,2);\n  switch dim\n  case 2 \n    % Facets are really edges\n    E = F;\n    % O(n*m) too slow...\n    [T,sqrD] = project_to_lines(P,V(E(:,1),:),V(E(:,2),:),'Segments',true);\n    % snap to line segment\n    [~,J] = min(sqrD,[],2);\n    T = T(sub2ind(size(T),1:size(P,1),J'))';\n    C = V(E(J,1),:) + bsxfun(@times,T,(V(E(J,2),:)-V(E(J,1),:)));\n    s = -2*(winding_number(V,E,P))+1;\n    vec = C-P;\n    % signed distance direction\n    D = bsxfun(@times,s,normalizerow(vec));\n    % signed distance\n    S = s.*normrow(D);\n  case 3 \n    [S,I,C,N] = signed_distance(P,V,F,'SignedDistanceType','pseudonormal');\n    D = normalizerow(C-P);\n    D = bsxfun(@times,sign(S),D);\n    min_dist = 1e-5;\n    too_close = abs(S) < min_dist;\n    % Normals always point outside regardless of the eval point.\n    D(too_close,:) = -N(too_close,:);\n  end\n\n  %% Find closest points\n  %[sqrD,I,C] = point_mesh_squared_distance(P,V,F);\n  %% Compute barycentric coordinates on closest faces\n  %B = barycentric_coordinates(C,V(F(I,1),:),V(F(I,2),:),V(F(I,3),:));\n  %% Direction to closest point\n  %D = normalizerow(C-P);\n  %% Determine which are too close to trust\n  %min_sqr_dist = 1e-10;\n  %too_close = sqrD < min_sqr_dist;\n  %% Determine if closest point is on vertex, edge, or face AND too clost to\n  %% trust direction.\n  %epsilon = 1e-15;\n  %on_face = (sum(B<=epsilon,2)==0) & too_close;\n  %on_edge = (sum(B<=epsilon,2)==1) & too_close;\n  %on_vertex = (sum(B<=epsilon,2)==2) & too_close;\n  %% Determine which vertex or edge of that face\n  %[~,which_vertex] = find(B(on_vertex,:)>epsilon);\n  %[~,which_edge] = find(B(on_edge,:)<=epsilon);\n  %% Compute normals for faces, vertices and edges\n  %% Q: Are area normals OK?\n  %% H: [B\u00e6rentzen 2002/2005] suggests angle weighting.\n  %N_face = normalizerow(normals(V,F));\n  %N_vertex = per_vertex_normals(V,F);\n  %% map to corners\n  %N_vertex = N_vertex(F,:);\n  %[N_edge,E,EMAP] = per_edge_normals(V,F);\n  %% map to directed edges\n  %N_edge = N_edge(EMAP,:);\n  %% This is an expensive way to find out if inside/outside a closed mesh\n  %w = winding_number(V,F,P);\n  %% Flip sign for interior points\n  %S = (1-2*w);\n  %D = bsxfun(@times,S,D);\n  %% Use inverse normals for those that are too close\n  %if any(on_vertex)\n  %  D(on_vertex,:) = ...\n  %    -N_vertex(sub2ind(size(F),I(on_vertex),which_vertex),:);\n  %end\n  %if any(on_edge)\n  %  D(on_edge,:) = -N_edge(sub2ind(size(F),I(on_edge),which_edge),:);\n  %end\n  %if any(on_face)\n  %  D(on_face,:) = -N_face(I(on_face),:);\n  %end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/signed_distance_direction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5695127086549376}}
{"text": "function [fProbability_] = callback_LogLikelihoodA1A2Value(fAValues, caCatalogs, mControl, fBValue)\n% function [fProbability] = callback_LogLikelihoodAValue(fAValue, caCatalogs, mControl)\n% -------------------------------------------------------------------------------------\n% Helper callback-function for calc_MaxLikelihoodA.m\n%   Computes the negative log-likelihood sum of a given a- and fixed b-value for a\n%   set of given catalogs\n%\n% Input parameters:\n%   fAValue        a-value\n%   caCatalogs      Cell array containing the set of catalogs\n%   mControl        Controlmatrix containing informations about the single catalogs\n%                   mControl(n,:) contains information about caCatalogs{n}\n%                   Column 1: Starting time of catalog\n%                   Column 2: Magnitude of completeness\n%                   Column 3: Starting magnitude bin\n%                   Column 4: Magnitude bin stepsize (must be 0.1)\n%   fBValue         Fixed b-value\n%\n% Output parameters:\n%   fProbability    Negative log-likelihood of the given a- and b-value for the set of given catalogs\n%\n% Danijel Schorlemmer\n% July 5, 2002\n\n% Init variable\nglobal fProbability;\nvProbabilities = [];\n\n[nRow_, nColumn_] = size(mControl);\nfTotalLength_ = mControl(nRow_,6)-mControl(1,1);\n\n\n% Loop over all catalogs\nfor nCnt_ = 1:length(caCatalogs)\n  % Extract catalog from cell array\n  mCatalog_ = caCatalogs{nCnt_};\n  % Determine maximum magnitude of catalog\n  fMaxMag_ = max(mCatalog_(:,6));\n  % Set up vector of available magnitude bins\n  vCnt_ = (mControl(nCnt_,2):mControl(nCnt_,4):(fMaxMag_+mControl(nCnt_,4)))'; % Add one more magnitude bin for later use of diff()\n  % Compute lengths of periods and ajust thea-value\n  fTimeLength_ = mControl(nCnt_,6) - mControl(nCnt_,1);\n  fTimeRatio_ = fTimeLength_/fTotalLength_;\n  % Compute the cumulative FMD\n  if mControl(nCnt_,5) == 1;  % this is activity rate 1\n      fA_ = fAValues(1) + log10(fTimeRatio_);\n      vNumber_ = 10.^(fA_ - (fBValue * vCnt_));\n  elseif  mControl(nCnt_,5) == 2;  % this is activity rate 1\n      fA_ = fAValues(2) + log10(fTimeRatio_);\n      vNumber_ = 10.^(fA_ - (fBValue * vCnt_));\n  end\n  % Determine the number of events in each magnitude bin\n  mPredictionFMD_ = -diff(vNumber_);\n  % Create the FMD for the period of observation\n  vObservedFMD_ = histogram(mCatalog_(:,6), mControl(nCnt_,2):mControl(nCnt_,4):fMaxMag_);\n  % Calculate the likelihoods for both of the models\n  vProb_ = calc_log10poisspdf(vObservedFMD_', mPredictionFMD_);\n  % Return the values (multiply by -1 to return the lowest value for the highest probability\n  vProbabilities = [vProbabilities; sum(vProb_)];\nend\n% Sum the probabilities for all given catalogs\nfProbability_ = (-1) * sum(vProbabilities);\n\nfProbability = fProbability_;\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/callback_LogLikelihoodA1A2Value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5695127013474062}}
{"text": "% Fig. 5.28  Feedback Control of Dynamic Systems, 6e \n%             Franklin, Powell, Emami\n% script for LEFT side of Figure 5.28.  Use fig5_28b to see RIGHT side.\n\n\nclf\nn=[1 2]; \nd=conv([1 1 0],[1 13]);\nnc=91*[1 .05];\ndc=[1 .01];\nnol=conv([0 0 n],nc);\ndol=conv(d,dc);\n rlocus(nol,dol); \n hold on\n title('Fig.5.28a Root locus for lead plus lag')\n axis([-20 4 -9 9])\n z=0:.1:.9;\n wn=2:2:19;\n sgrid(z, wn)\n dcl=nol+dol;\n r=roots(dcl);\n plot(r,'*')\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_28.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5694923996936755}}
{"text": "function [PDR, deltaHD, deltaSEN, deltaPRO, deltaCOL, CBR] = CV2XMode4(beta,lambda,Pt,S,B);\n\n% CV2XMode4 is the main script of the implementation of the analytical \n% models of the communication performance of C-V2X or LTE-V Mode 4 \n% described in the following paper:\n% \n%    Manuel Gonzalez-Mart\u00edn, 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% The paper presents analytical models for the average PDR (Packet Delivery Ratio) as a \n% function of the distance between transmitter and receiver, and for the four different \n% types of transmission errors that can be encountered in C-V2X or LTE-V Mode 4. The models \n% have been validated for a wide range of transmission parameters and traffic densities by \n% comparing the results obtained with the analytical models to those obtained with a C-V2X \n% or LTE-V Mode 4 simulator implemented by the authors over the Veins simulation platform.\n%\n% CV2XMode4.m is the main script you have to run to get the PDR curve as a function of the \n% distance for a given set of parameters, and the probability of each of the four \n% transmission errors. \n%\n% The resulting figures are compared with simulations when the same configuration \n% is available in the ./simulations folder.\n%\n% The resulting figures are stored in the ./fig folder.\n%\n% Input parameters:\n%    beta: traffic density in veh/m. Values tested: 0.1, 0.2 and 0.3.\n%    lambda: packet transmission frequency in Hz. Values tested: 10 and 20.\n%    Pt: transmission power in dBm. Values tested: 20 and 23.\n%    S: number of sub-channels. Values tested: 2 and 4.\n%    B: packet size in bytes. Values tested: 190.\n%\n% Output metrics:\n%    PDR: Packet Delivery Ratio for different Tx-Rx distances \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%    deltaCOL: probability of packet loss due to packet collisions for different Tx-Rx distances\n%    CBR: Channel Busy Ratio between 0 and 1\n%\n% Overall code structure:\n%     CV2XMode4.m\n%         |---->   CV2XMode4_common.m   ----> get_PL_SH.m, get_SINRdistribution.m, get_BLER.m\n%         |---->   CV2XMode4_Step2.m    ----> get_PL_SH.m, get_SINRdistribution.m, get_BLER.m\n%         |---->   CV2XMode4_Step3.m    ----> get_PL_SH.m, get_SINRdistribution.m, get_BLER.m\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    disp('=========================================================')\n    disp('Input parameters:')\n    fprintf('  beta   = %f veh/m \\n', beta)\n    fprintf('  lambda = %d Hz \\n', lambda)\n    fprintf('  Pt     = %d dBm \\n', Pt)\n    fprintf('  S      = %d subchannels \\n', S)\n    fprintf('  B      = %d bytes \\n', B)\n    \n    distance = [0:25:500];  % Tx-Rx distances to evaluate (m)\n\n    Psen = -90.5;               % Sensing threshold (dBm)\n\n    step_dB = 0.1;              % Discrete steps to compute the PDF of the SNR and SINR (dB)\n\n    % Calculate the number of RBs that are needed to transmit each message\n    % and the coding used based on the number of sub-channels and packet size:\n    switch B\n        case 190\n            switch S\n                case 4\n                    coding = 1;   % Used to identify the BLER vs SINR curve to be used (190 Bytes, QPSK r=0.7, Vr = 280 km/h)\n                    RBs = 10;     % Number of RBs needed to transmit the DATA field of each message \n                case 2\n                    coding = 2;   % Used to identify the BLER vs SINR curve to be used (190 Bytes, QPSK r=0.5, Vr = 280 km/h)\n                    RBs = 12;     % Number of RBs needed to transmit the DATA field of each message\n            end\n    end\n\n    noise = -95 - 10*log10(50/RBs);     % 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\n    % Calculate errors associated to HD, SEN and PRO:\n    [ deltaHD_pre , deltaSEN_pre , deltaPRO_pre ] = CV2XMode4_common( lambda , Pt , distance, Psen , step_dB , noise , coding ); \n            \n    % Calculate probability of collision considering only Step 2 and CBR:\n    [ deltaCOL2_pre , CBR ] = CV2XMode4_Step2( beta , lambda , Pt , S , distance , Psen , step_dB , noise , coding , deltaPRO_pre );    \n\n    % Calculate weighting factor alpha using equation (22):\n    if CBR < 0.2\n        alpha = 0;\n    elseif CBR <= 0.7\n        alpha = 2*CBR - 0.4;\n    else\n        alpha = 1;\n    end\n    \n    % Calculate probability of collision considering only Step 3:\n    if alpha < 1             \n         [ deltaCOL3_pre ] = CV2XMode4_Step3( beta , lambda , Pt , S , distance , Psen , step_dB , noise , coding , deltaPRO_pre );        \n    else\n        deltaCOL3_pre = 0;\n    end\n      \n    % Calculate final probabilities for each type of error: \n    deltaHD   = deltaHD_pre;                               % Equation (6.1)\n    deltaSEN  = deltaSEN_pre .* (1 - deltaHD);             % Equation (6.2)\n    deltaPRO  = deltaPRO_pre .* (1 - deltaHD_pre) .* (1 - deltaSEN_pre);  % Equation (6.3)\n    deltaCOL2 = deltaCOL2_pre .* (1 - deltaHD_pre) .* (1 - deltaSEN_pre) .* (1 - deltaPRO_pre); % Equation (6.4)\n    deltaCOL3 = deltaCOL3_pre .* (1 - deltaHD_pre) .* (1 - deltaSEN_pre) .* (1 - deltaPRO_pre); % Equation (6.5)\n    deltaCOL = alpha*deltaCOL2 + (1-alpha)*deltaCOL3; % Equation (21)\n    \n    % Calculate PDR:\n    PDR = 1 - deltaHD - deltaSEN - deltaPRO - deltaCOL; % Equation (6)      \n    \n    % Presentation of the obtained results:    \n\n    % Load simulation results (if available):\n    simulation_path = [pwd '\\simulations\\' num2str(S) 'subchannels\\'  num2str(Pt) 'dBm'];    \n    sim_file = [ simulation_path '\\FALLOS_LOS_D2D_' num2str(beta*1000) 'vehpkm_16Alg_' num2str(1/lambda) 's_' num2str(8*B) 'bit.fig' ];\n    fig_name = ['CV2XMode4_beta' num2str(beta) '-lambda' num2str(lambda) '-Pt' num2str(Pt) '-S' num2str(S) '-B' num2str(B)];\n\n    if exist(sim_file,'file')==2        \n        open(sim_file)\n        lh = findall(gca, 'type', 'line');\n        X = get(lh,'xdata'); \n        Y = get(lh,'ydata'); \n        deltaHD_sim = Y{5};\n        deltaSEN_sim = Y{1};\n        deltaPRO_sim = Y{4};\n        deltaCOL_sim = Y{3};\n        close\n        \n        figure; hold on; grid on; box on\n        plot(distance , deltaHD_sim/100,'b-','LineWidth',2)\n        plot(distance , deltaSEN_sim/100,'m-','LineWidth',2)\n        plot(distance , deltaPRO_sim/100,'r-','LineWidth',2)\n        plot(distance , deltaCOL_sim/100,'k-','LineWidth',2)        \n        \n    else        \n        figure; hold on; grid on; box on        \n    end\n\n    % Plot errors:\n    ylabel('Error probability')\n    xlabel('Distance [m]')\n    plot(distance , deltaHD,'b--','LineWidth',2)\n    plot(distance , deltaSEN,'m--','LineWidth',2)\n    plot(distance , deltaPRO,'r--','LineWidth',2)\n    plot(distance , deltaCOL,'k--','LineWidth',2)\n    ylim([0 1])\n    \n    if exist(sim_file,'file')==2\n        legend('\\delta_{HD} Simulation','\\delta_{SEN} Simulation','\\delta_{PRO} Simulation','\\delta_{COL} Simulation','\\delta_{HD} Analytical','\\delta_{SEN} Analytical','\\delta_{PRO} Analytical','\\delta_{COL} Analytical','Location','northwest')\n    else\n        legend('\\delta_{HD} Analytical','\\delta_{SEN} Analytical','\\delta_{PRO} Analytical','\\delta_{COL} Analytical','Location','northwest')\n    end    \n    hgsave(['fig/' fig_name '_errors.fig'])    \n\n\n    % Plot PDR:\n    figure; hold on; grid on; box on\n    if exist(sim_file,'file')==2\n        PDR_sim = (100 - deltaHD_sim - deltaSEN_sim - deltaPRO_sim - deltaCOL_sim)/100;           \n        plot(distance,PDR_sim,'b-','LineWidth',2)        \n        plot(distance,PDR,'b--','LineWidth',2)        \n        legend('PDR Simulation','PDR Analytical')\n    else\n        plot(distance,PDR,'--')\n        legend('PDR Analytical')\n    end       \n    ylim([0 1])    \n    ylabel('PDR')\n    xlabel('Distance [m]')\n    hgsave(['fig/' fig_name '_PDR.fig'])    \n\n    fprintf('Channel load: CBR = %.2f, alpha = %f \\n',CBR, alpha)\n    \n    if exist(sim_file,'file')==2        \n        MAD_HD  = mean( abs(deltaHD*100 - deltaHD_sim) );    % Equation (35)\n        MAD_SEN = mean( abs(deltaSEN*100 - deltaSEN_sim) );  % Equation (35)\n        MAD_PRO = mean( abs(deltaPRO*100 - deltaPRO_sim) );  % Equation (35)\n        MAD_COL = mean( abs(deltaCOL*100 - deltaCOL_sim) );  % Equation (35)\n        MAD     = mean( abs(PDR - PDR_sim) * 100 );          % Equation (35)\n        \n        disp('Mean Absolute Deviation results : ')\n        fprintf('PDR \\tHD  \\tSEN \\tPRO \\tCOL \\n')\n        fprintf('%.2f\\t%.2f\\t%.2f\\t%.2f\\t%.2f \\n', MAD, MAD_HD, MAD_SEN, MAD_PRO, MAD_COL)\n    end\n    \n    disp('=========================================================')\n\n    \n\n return\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.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5694923825680178}}
{"text": "% RES = pointOp(IM, LUT, ORIGIN, INCREMENT, WARNINGS)\n%\n% Apply a point operation, specified by lookup table LUT, to image IM.\n% LUT must be a row or column vector, and is assumed to contain\n% (equi-spaced) samples of the function.  ORIGIN specifies the\n% abscissa associated with the first sample, and INCREMENT specifies the\n% spacing between samples.  Between-sample values are estimated via\n% linear interpolation.  If WARNINGS is non-zero, the function prints\n% a warning whenever the lookup table is extrapolated.\n%\n% This function is much faster than MatLab's interp1, and allows\n% extrapolation beyond the lookup table domain.  The drawbacks are\n% that the lookup table must be equi-spaced, and the interpolation is\n% linear.\n\n% Eero Simoncelli, 8/96.\n\nfunction res = pointOp(im, lut, origin, increment, warnings)\n\n%% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD)\n\nfprintf(1,'WARNING: You should compile the MEX version of \"pointOp.c\",\\n         found in the MEX subdirectory of matlabPyrTools, and put it in your matlab path.  It is MUCH faster.\\n');\n\nX = origin + increment*[0:size(lut(:),1)-1];\nY = lut(:);\n\nres = reshape(interp1(X, Y, im(:), 'linear', 'extrap'),size(im));\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/pointOp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5694923744427777}}
{"text": "function [qp,QP_ep] = epose2qpose(ep)\n\n% EPOSE2QPOSE  Euler-specified to quaternion-specified pose conversion.\n%\n%   QP = EPOSE2QPOSE(EP) returns a full 7-pose QP=[X;Q] from a full 6-pose\n%   QE=[X;E], where X is 3D opsition and Q and E are 3D orientations.\n%\n%   [QP,Jep] = EPOSE2QPOSE(...) returns also the Jacobian matrix\n%\n%   See also QPOSE2EPOSE, EULERANGLES, QUATERNION, FRAME.\n\n%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nif any(size(ep) ~= [6,1])\n    warning('Input Euler-pose should be a column 6-vector')\nend\n\nqp            = zeros(7,1);  % empty quaternion pose\nqp(1:3)       = ep(1:3);     % position copy\nP             = eye(3);      % Jacobian of copy function\n[qp(4:7),Q_e] = e2q(ep(4:6));% orientation and Jacobian\n\nQP_ep         = [P zeros(3);zeros(4,3) Q_e]; % Full Jacobian\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 <http://www.gnu.org/licenses/>.\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/epose2qpose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5694827159121273}}
{"text": "function varargout = dblquad(varargin)\n%DBLQUAD   Complete definite integral of SPHEREFUN. \n%   I = DBLQUAD(F, a, b, c, d), returns the definite integral of a SPHEREFUN over\n%   the region [a, b, c, d].\n% \n%   This function is a wrapper for quad2d.\n%\n% See also SPHEREFUN/QUAD2D, SPHEREFUN/INTEGRAL2, SPHEREFUN/SUM2.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n[varargout{1:nargout}] = dblquad@separableApprox(varargin{:});\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/@spherefun/dblquad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5694827106956752}}
{"text": "function [lab,q] = psdeig(x,K)\n% [lab,q] = psdeig(x,K)\n%\n% PSDEIG  Computes spectral coefficients of x w.r.t. K\n%   Arguments \"q\" is optional - without it's considerably faster.\n%   FLOPS indication: 1.3 nk^3 versus 9.0 nk^3 for nk=500,\n%                     1.5 nk^3        9.8 nk^3 for nk=50.\n%\n% **********  INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi\n\n% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n%   Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n%   CRL, McMaster University, Canada.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\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 Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n\nKs = K.s;\nif isempty(Ks),\n    lab = [];\n    return\nend\nKq  = Ks .* Ks;\nnr  = K.rsdpN;\nnc  = length(Ks);\nN   = sum(Kq) + sum(Kq(nr+1:end));\nxi  = length(x) - N;\nei  = 0;\nlab = zeros(sum(Ks),1);\nneedv = nargout > 1;\nif needv,\n    q = zeros(N,1);\n    vi = 0;\nend\nfor i = 1 : nc,\n    ki = Ks(i);\n    qi = Kq(i);\n    XX = x(xi+1:xi+qi); \n    xi = xi+qi;\n    if i > nr,\n        XX = XX + 1i*x(xi+1:xi+qi); \n        xi = xi+qi;\n    end\n    XX = reshape(XX,ki,ki);\n    XX = XX + XX';\n    try\n        if needv,\n            [QQ,DD] = eig(XX);\n            DD = diag(DD);\n        else\n            DD = eig(XX);\n        end\n    catch\n        % If eig() fails to converge, fall back onto svd(). This costs\n        % more, so we don't want to use it every time.\n        [QQ,DD,VV] = svd(XX);\n        DD = diag(DD).*sign(real(sum(conj(QQ).*VV)'));\n    end\n    lab(ei+1:ei+ki) = 0.5*DD;\n    ei = ei + ki;\n    if needv,\n        q(vi+1:vi+qi) = real(QQ);\n        vi = vi + qi;\n        if i > nr,\n            q(vi+1:vi+qi) = imag(QQ);\n            vi = vi + qi;\n        end\n    end\nend\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/sedumi/psdeig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5694827098765481}}
{"text": "function channels = EPW(N, beta)\nm = log2(N);\nchannels = zeros(N, 1);\nfor i = 0 : N - 1\n    bin_seq_str = dec2bin(i, m);\n    bin_seq = zeros(m, 1);\n    for j = 1 : m\n        if bin_seq_str(j) == '1'\n            bin_seq(j) = 1;\n        end\n    end\n    bin_seq = bin_seq(m : -1 : 1);\n    sum = 0;\n    for j = 1 : m\n        if m >= 9\n            sum = sum + bin_seq(j) * (beta^(j - 1) + 0.221 * 0.9889^(j - 1) - bin_seq(9) * 0.0371 * 0.5759^(j - 1) - bin_seq(8) * 0.047 * 0.4433^(j - 1));\n        else\n            if m == 8\n                sum = sum + bin_seq(j) * (beta^(j - 1) + 0.221 * 0.9889^(j - 1) - bin_seq(8) * 0.047 * 0.4433^(j - 1));\n            else\n                sum = sum + bin_seq(j) * (beta^(j - 1) + 0.221 * 0.9889^(j - 1));\n            end\n        end\n    end\n    channels(i + 1) = sum;\nend\nend", "meta": {"author": "YuYongRun", "repo": "PolarCodeDecodersInMatlab", "sha": "f1b512d10bf057e83f18685ea012d242bdaaf6ac", "save_path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab", "path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab/PolarCodeDecodersInMatlab-f1b512d10bf057e83f18685ea012d242bdaaf6ac/PolarFastSCL/PolarizaedChannelsPartialOrder/EPW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5694793855596187}}
{"text": "% Pattern Recognition Tools (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% Version 5.1.1 14-May-2014\n%\n%Datasets and Mappings (just most important routines)\n%---------------------\n%prdataset      - Define dataset from datamatrix and labels\n%datasets       - List information on datasets (just help, no command)\n%prdatafile     - Define dataset from directory of object files \n%datafiles      - List information on datafiles (just help, no command)\n%cat2data       - Create categorical dataset\n%classnames     - Retrieve names of classes\n%classsizes     - Retrieve sizes of classes\n%feat2lab       - Label dataset by one of its features and remove this feature\n%gencirc        - Generation of a one-class circular dataset\n%genclass       - Generate class frequency distribution\n%genlab         - Generate dataset labels\n%getlab         - Retrieve object labels from datasets and mappings\n%getnlab        - Retrieve nummeric object labels from dataset\n%setfeatlab     - Set feature labels in dataset\n%getfeatlab     - Get feature labels in dataset\n%getfeat        - Retrieve feature labels from datasets and mappings\n%setdat         - Change data in dataset for classifier output\n%setdata        - Change data in dataset or mapping\n%getdata        - Retrieve data from dataset or mapping\n%setlabels      - Change labels of dataset or mapping\n%getlabels      - Retrieve labels from a dataset\n%setprior       - Reset class prior probabilities of dataset\n%getprior       - Retrieve class prior probabilities from dataset\n%addlabels      - Add additional labelling\n%changelablist  - Change current active labeling\n%misval         - Fix missing values in a dataset\n%multi_labeling - List information on multi-labeling (help only)\n%prmapping      - Define and retrieve mapping and classifier from data\n%mappings       - List information on mappings (just help, no command)\n%renumlab       - Convert labels to numbers\n%matchlab       - Match different labelings\n%prarff         - Convert ARFF file (WEKA) to PRTools dataset\n%remclass       - Remove a class from a dataset\n%seldat         - Retrieve a part of a dataset\n%selclass       - Retrieve a class from a dataset \n%\n%Data Generation (more in prdatasets)\n%---------------\n%circles3d   - Create a dataset containing 2 circles in 3 dimensions\n%lines5d     - Create a dataset containing 3 lines in 5 dimensions\n%gendat      - Random sampling of datasets for training and testing\n%gensubsets  - Generation of a consistent series of subsets of a dataset\n%gendatgauss - Generation of multivariate Gaussian distributed data\n%gendatb     - Generation of banana shaped classes\n%gendatc     - Generation of circular classes\n%gendatd     - Generation of two difficult classes\n%gendath     - Generation of Highleyman classes\n%gendati     - Generation of random windows from images\n%gendatk     - Nearest neighbour data generation\n%gendatl     - Generation of Lithuanian classes\n%gendatm     - Generation of 8 2d classes\n%gendatp     - Parzen density data generation\n%gendatr     - Generate regression dataset from data and target values\n%gendats     - Generation of two Gaussian distributed classes\n%gendatw     - Sample dataset by given weigths\n%gendatv     - Generation of a very large dataset\n%gentrunk    - Generation of Trunk's example\n%prdata      - Read data from file\n%seldat      - Select classes / features / objects from dataset\n%spirals     - Generation of a two-class spiral dataset\n%getwindows  - Get pixel feature vectors around given pixels in image dataset\n%prdataset   - Read existing dataset from file\n%prdatasets  - Overview and download of standard datasets\n%\n%Datafiles\n%---------\n%prdatafile     - Define datafile from set of files in directory\n%createdatafile - Save datafile, store intermediate result as raw datafile\n%savedatafile   - Save datafile, store intermediate result as mature datafile\n%filtm          - Mapping for arbitrary processing of a datafile\n%prdatafiles    - Overview and download of standard datafiles\n%\n%Linear and Quadratic Classifiers (*operate on datasets and datafiles)\n%--------------------------------\n%fisherc     - Minimum least square linear classifier\n%ldc         - Normal densities based linear (muli-class) classifier\n%loglc       - Logistic linear classifier\n%nmc         - Nearest mean linear classifier\n%nmsc        - Scaled nearest mean linear classifier\n%quadrc      - Quadratic classifier\n%qdc         - Normal densities based quadratic (multi-class) classifier\n%udc         - Uncorrelated normal densities based quadratic classifier\n%klldc       - Linear classifier based on KL expansion of common cov matrix\n%pcldc       - Linear classifier based on PCA expansion on the joint data\n%polyc       - Add polynomial features and run arbitrary classifier\n%subsc       - Subspace classifier\n%statslinc   - Linear classifier from the Stats toolbox\n% \n%classc      - Converts a mapping into a classifier\n%labeld      - Find labels of objects by classification\n%logdens     - Convert density estimates to log-densities for more accuracy\n%rejectc     - Creates reject version of exisiting classifier\n%testc       - General error estimation routine for trained classifiers\n%\n%Other Classifiers \n%-----------------\n%knnc        - k-nearest neighbour classifier (find k, build classifier)\n%testk       - Error estimation for k-nearest neighbour rule\n%edicon      - Edit and condense training sets\n%statsknnc   - k-nearest neighbour classifier from the Stats toolbox\n%\n%weakc       - Weak classifier\n%stumpc      - Decision stump classifier\n%adaboostc   - ADABoost classifier\n%\n%parzenc     - Parzen classifier\n%parzendc    - Parzen density based classifier\n%testp       - Error estimation for Parzen classifier\n%\n%treec       - Construct binary decision tree classifier\n%dtc         - Decision tree classifier, rewritten, also for nominal features\n%statsdtc    - Decision tree classifier from the Stats toolbox\n%randomforestc - Breiman's random forest classifier\n%naivebc     - Naive Bayes classifier\n%statsnbc    - Naive Bayes classifier from the Stats toolbox\n%bpxnc       - Feed forward neural network classifier by backpropagation\n%lmnc        - Feed forward neural network by Levenberg-Marquardt rule\n%neurc       - Automatic neural network classifier\n%perlc       - Linear perceptron \n%rbnc        - Radial basis neural network classifier\n%rnnc        - Random neural network classifier\n%ffnc        - Feed-forward neural net classifier back-end routine\n%bagc        - Feature set classifier, e.g. for multiple-instance learning\n%\n%fdsc        - Feature based dissimilarity space classifier\n%mdsc        - Manhatten distance feature based dissimilarity space classifier\n%vpc         - Voted perceptron classifier\n%drbmc       - Discriminative restricted Boltzmann machine classifier\n%\n%libsvc      - Support vector classifier by LIBSVM\n%nulibsvc    - Support vector classifier by LIBSVM\n%svc         - Support vector classifier\n%svo         - Support vector optimizer\n%nusvc       - Support vector classifier\n%nusvo       - Support vector optimizer\n%rbsvc       - Radial basis SV classifier\n%kernelc     - General kernel/dissimilarity based classification\n%\n%Normal Density Based Classification\n%-----------------------------------\n%distmaha    - Mahalanobis distance\n%meancov     - Estimation of means and covariance matrices from multiclass data\n%nbayesc     - Bayes classifier for given normal densities\n%ldc         - Normal densities based linear (muli-class) classifier\n%qdc         - Normal densities based quadratic (multi-class) classifier\n%udc         - Uncorrelated normal densities based quadratic classifier\n%mogc        - Mixture of gaussians classification\n%testn       - Error estimate of discriminant on normal distributions\n%\n%Feature Selection\n%-----------------\n%feateval    - Evaluation of a feature set\n%featrank    - Ranking of individual feature permormances\n%featsel     - Feature Selection\n%featselb    - Backward feature selection\n%featself    - Forward feature selection\n%featsellr   - Plus-l-takeaway-r feature selection\n%featseli    - Feature selection on individual performance\n%featselm    - Feature selection map, general routine for feature selection\n%featselo    - Branch and bound feature selection\n%featselp    - Floating forward feature selection\n%featselv    - Selection of varying features\n%\n%Classifiers and tests (general)\n%-------------------------------\n%bayesc      - Bayes classifier by combining density estimates\n%classim     - Classify image using a given classifier\n%classc      - Convert mapping to classifier\n%labeld      - Find labels of objects by classification\n%cleval      - Classifier evaluation (learning curve)\n%clevalb     - Classifier evaluation (learning curve), bootstrap version\n%clevalf     - Classifier evaluation (feature size curve)\n%clevals     - Classifier evaluation (feature /learning curve), bootstrap\n%confmat     - Computation of confusion matrix\n%costm       - Cost mapping, classification using costs\n%prcrossval  - Crossvalidation \n%cnormc      - Normalisation of classifiers\n%disperror   - Display error matrix with information on classifiers and datasets\n%labelim     - Construct image of labeled pixels\n%logdens     - Convert density estimates to log-densities for more accuracy\n%loso        - Leave_one_set_out crossvalidation\n%mclassc     - Computation of multi-class classifier from 2-class discriminants\n%regoptc     - Optimisation of regularisation and complexity parameters\n%reject      - Compute error-reject trade-off curve\n%prroc       - Receiver-operator curve (ROC)\n%shiftop     - Shift operating point of classifier\n%testc       - General error estimation routine for trained classifiers\n%testd       - Error of dataset applied to given classifier\n%testauc     - Estimate error as area under the ROC\n%\n%Mappings\n%--------\n%affine      - Construct affine (linear) mapping from parameters\n%bhatm       - Two-class Bhattacharryya mapping\n%cmapm       - Compute some special maps\n%datasetm    - Mapping conversion dataset\n%disnorm     - Normalization of a dissimilarity matrix\n%featselm    - Feature selection map, general routine for feature selection\n%fisherm     - Fisher mapping\n%chernoffm   - Chernoff mapping\n%invsigm     - Inverse sigmoid map\n%filtm       - Arbitrary operation on datafiles/datasets, object by object\n%mapm        - Arbitrary mapping operation on doubles and datasets\n%gaussm      - Mixture of Gaussians density estimation\n%kernelm     - Kernel mapping\n%klm         - Decorrelation and Karhunen Loeve mapping (PCA)\n%klms        - Scaled version of klm, useful for prewhitening\n%knnm        - k-Nearest neighbor density estimation\n%mclassm     - Computation of mapping from multi-class dataset\n%prmap       - General routine for computing and executing mappings\n%mappingtools - Macro defining some mappings\n%nlfisherm   - Nonlinear Fisher mapping\n%normm       - Object normalization map\n%parzenm     - Parzen density estimation\n%parzenml    - Optimization of smoothing parameter in Parzen density estimation.\n%pcam        - Principal Component Analysis\n%pcaklm      - Backend routine for PC and KL mappings\n%proxm       - Proximity mapping and kernel construction\n%reducm      - Reduce to minimal space mapping\n%remoutl     - Remove outliers\n%rejectm     - Creates rejecting mapping\n%scalem      - Compute scaling data\n%sigm        - Simoid mapping\n%spatm       - Augment image dataset with spatial label information\n%tsnem       - tSNE mapping\n%sammonm     - Multi-dimensional scaling by Sammon mapping\n%userkernel  - User supplied kernel definition\n%\n%gtm         - Fit a Generative Topographic Mapping (GTM) by EM\n%plotgtm     - Plot a Generative Topographic Mapping in 2D\n%som         - Simple routine computing a Self-Organizing Map (SOM)\n%prplotsom   - Plot a Self-Organizing Map in 2D\n%\n%Classifier combiners\n%--------------------\n%averagec    - Combining linear classifiers by averaging coefficients\n%baggingc    - Bootstrapping and aggregation of classifiers\n%dcsc        - Dynamic Classifier Selecting Combiner\n%modselc     - Model Selection Combiner (Static selection)\n%rsscc       - Random subspace combining classifier\n%votec       - Voting classifier combiner\n%wvotec      - Weighted voting classifier combiner\n%maxc        - Maximum classifier combiner\n%minc        - Minimum classifier combiner\n%meanc       - Mean classifier combiner\n%medianc     - Median classifier combiner\n%mlrc        - Muli-response linear regression combiner\n%naivebcc    - Naive Bayes classifier combiner\n%perc        - Percentile combiner\n%prodc       - Product classifier combiner\n%traincc     - Train combining classifier\n%fixedcc     - Fixed combiner construction, back end\n%parsc       - Parse classifier or map\n%rejectc     - Creates reject version of exisiting classifier\n%parallel    - Parallel combining of classifiers\n%bagcc       - Feature set combining classifier\n%stacked     - Stacked combining of classifiers\n%sequential  - Sequential combining of classifiers\n%\n%\n%Regression\n%----------\n%linearr     - Linear regression\n%ridger      - Ridge regression\n%lassor      - LASSO\n%svmr        - Support vector regression\n%ksmoothr    - Kernel smoother\n%knnr        - k-nearest neighbor regression\n%pinvr       - Pseudo-inverse regression\n%plsr        - Partial least squares regression\n%plsm        - Partial least squares mapping\n%gpr         - Gaussian Process regression\n%\n%testr       - Mean squared regression error\n%rsquared    - R^2-statistic\n%\n%Handling images in datasets and datafiles\n%-----------------------------------------\n%data2im     - Convert dataset to image\n%getobjsize  - Retrieve image size of feature images in datasets\n%getfeatsize - Retrieve image size of object images in datasets\n%obj2feat    - Transform object images to feature images in dataset\n%feat2obj    - Transform feature images to object images in dataset\n%im2feat     - Convert image to feature in dataset\n%im2obj      - Convert image to object in dataset\n%imsize      - Retrieve size of specific image in datafile\n%im_patch    - Find / generate patches in object images\n%band2obj    - Convert image bands to objects in dataset\n%bandsel     - Select image bands in dataset or datafile\n%selectim    - Select image in multi-band object image dataset/datafile\n%show        - Display objects in datasets, datafiles and mappings\n%im_dbr      - Image Database Retrieval GUI\n%\n%Operations on images in datasets and datafiles\n%----------------------------------------------\n%classim     - Classify image using a given classifier\n%doublem     - Convert datafile images into double\n%filtim      - Image operation on objects in datafiles/datasets\n%spatm       - Augment image dataset with spatial label information\n%im_box            - Bounding box\n%im_center         - Center image\n%im_fft            - FFT transform (and more)\n%im_gauss          - Gaussian filtering by Matlab\n%im_gray           - Multi-band to gray-value conversion\n%im_hist_equalize  - Histogram equalization\n%im_invert         - Invert image\n%im_label          - Labeling binary images\n%im_norm           - Normalize images w.r.t. mean and variance\n%im_resize         - Resize images\n%im_rotate         - Rotate images\n%im_scale          - Scale images\n%im_select_blob    - Select largest blob\n%im_stretch        - Contrast stretching of images\n%im_threshold      - Threshold images\n%im_unif           - Uniform filtering\n%\n%Feature extraction from images in datasets and datafiles\n%--------------------------------------------------------\n%histm         - Convert images to histograms. Trains the bin positions\n%im_hist       - Convert images to histograms for fixed bin positions\n%im_harris     - Find Harris points in images\n%im_moments    - Computes moments as features from object images\n%im_mean       - Computes center of gravity\n%im_measure    - Computes some measurements\n%im_profile    - Computes image profiles\n%im_skel_meas  - Skeleton measurements\n%im_stat       - Compute some simple statistics\n%\n%Clustering and distances\n%------------------------\n%distm       - Distance matrix between two data sets\n%emclust     - Expectation - maximization clustering\n%proxm       - Proximity mapping and kernel construction\n%hclust      - Hierarchical clustering\n%kcentres    - k-centres clustering\n%prkmeans    - k-means clustering\n%modeseek    - Clustering by modeseeking\n%\n%mds         - Non-linear mapping by multi-dimensional scaling (Sammon)\n%mds_cs      - Linear mapping by classical scaling\n%mds_init    - Initialisation of multi-dimensional scaling\n%mds_stress  - Dissimilarity of distance matrices\n%\n%Plotting\n%--------\n%gridsize    - Set gridsize used in the PRTools plot commands\n%plotc       - Plot discriminant function for two features\n%plote       - Plot error curves\n%plotf       - Plot feature distribution\n%plotm       - Plot mapping\n%ploto       - Plot object functions\n%plotr       - Plot regression functions\n%plotdg      - Plot dendrgram (see hclust)\n%scatterd    - Scatterplot\n%scatterdui  - Scatterplot scatterplot with feature selection\n%scattern    - Simple, unannotated scatterplot, no axes.\n%scatterr    - Scatter regression dataset\n%\n%Various tests and support routines\n%----------------------------------\n%cdats              - Support routine for checking datasets\n%concatm            - Concatenate cell array of mappings or datasets ({} --> [])\n%iscomdset          - Test on compatible datasets\n%isdataim           - Test on image dataset\n%isdataset          - Test on dataset\n%isfeatim           - Test on feature image dataset\n%ismapping          - Test on mapping\n%isobjim            - Test on object image dataset\n%issequential       - Test on sequential mapping\n%isstacked          - Test on stacked mapping\n%isparallel         - Test on parallel mapping\n%issym              - Test on symmetric matrix\n%isvaldset          - Test on valid dataset\n%isvaldfile         - Test on valid datafile\n%matchlablist       - Match entries of label lists\n%mapex              - Train and execute mapping on the same dataset\n%labcmp             - Compare two label lists and find the differences\n%nlabcmp            - Compare two label lists and count the differences\n%testdatasize       - Check datasize and convert datafile to dataset\n%define_mapping     - Define empty mapping\n%mapping_task       - Check mapping task\n%trained_mapping    - Defined trained mapping\n%trained_classifier - Define trained classifier\n%setdefaults        - Substitute defaults\n%shiftargin         - Conditional shift of input arguments\n%prload             - Load prtools4 mat-files and convert to prtools5\n%prtools4to5        - Convert prtools4 directory to prtools5\n%\n%Examples\n%--------\n%prex_cleval     - learning curves\n%prex_combining  - classifier combining\n%prex_confmat    - confusion matrix, scatterplot and gridsize\n%prex_datafile   - datafile usage\n%prex_datasets   - standard datasets\n%prex_density    - Various density plots\n%prex_eigenfaces - Use of images and eigenfaces\n%prex_matchlab   - K-means clustering and matching labels\n%prex_mcplot     - Multi-class classifier plot\n%prex_plotc      - Dataset scatter and classifier plot\n%prex_mds        - Multi-dimensional scaling and visualisation\n%prex_som        - Training a SelfOrganizing Maps\n%prex_spatm      - Spatial smoothing of image classification\n%prex_cost       - Cost matrices and rejection\n%prex_logdens    - Density based classifier improvement\n%prex_soft       - Soft label example\n%prex_regr       - Regression example\n%\n%prdownload  - low level routine for retrieving datasets\n%prglobal    - set / list all globals and settings\n%prversion   - returns version information on PRTools\n%prwaitbar   - report PRTools progress by single waitbar\n%prwarning   - control PRTools warning level\n%prmemory    - controol PRTools large dataset handling\n%prtver      - prtools version back end\n%typp        - list prtools routine nicely\n%\n%--- <a href=\"http://37steps.com/prtools\">PRTools Guide</a> ---\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", "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/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5694655876293755}}
{"text": "function [dnum_bin, counts_per_bin, sum_per_bin, smallest_per_bin, biggest_per_bin, median_per_bin, std_per_bin, median_time_interval] = bin_irregular(dnum, data, binsize, snum, enum, stepsize)\n% BIN_IRREGULAR bin an irregularly-sampled timeseries (like earthquake origin times).\n%\n%    Usage:\n%      [dnum_bin, counts_per_bin, sum_per_bin, smallest_per_bin, biggest_per_bin, median_per_bin, std_per_bin, median_time_interval] = bin_irregular(dnum, data, binsize, snum, enum, [stepsize])\n%\n%    INPUTS:\n%      dnum            - irregular spaced date vector in datenum format\n%      data            - data values corresponding to dnum samples\n%      binsize         - binsize (in days) to use for output series\n%      snum            - start datenum (first centre used for output data)\n%      enum            - end datenum (last centre used for output data)\n%      stepsize        - (optional) Normally bins do not overlap. But if stepsize is set to a value smaller than binsize, bins will overlap.\n%\n%    OUTPUTS:\n%      dnum_bin        \t- regular space date vector (centres of bins)\n%      counts_per_bin  \t- number of values per bin\n%      sum_per_bin     \t- sum of all values in each bin\n%      smallest_per_bin \t- smallest data value in each bin\n%      biggest_per_bin \t- biggest data value in each bin\n%      median_per_bin  \t- median value in each bin\n%      std_per_bin     \t- standard deviation of all values in each bin\n%      median_time_interval - median time interval between values in each bin\n%\n%    See also: \n\n% AUTHOR: Glenn Thompson\n% $Date$\n% $Revision$\nl1=length(dnum);\nl2=length(data);\ndnum_bin = [];\ncounts_per_bin = [];\nsum_per_bin = [];\nsmallest_per_bin = [];\nbiggest_per_bin = [];\nmedian_per_bin = [];\nstd_per_bin = [];\nmedian_time_interval = [];\n\nif (l1==l2) \n    dnum_bin = snum+binsize/2 : stepsize : enum-binsize/2; % centres of the bins\n    for c=1:length(dnum_bin)\n\tbinstart = dnum_bin(c) - binsize/2; % start of this bin\n\tbinend = dnum_bin(c) + binsize/2;   % end of this bin\n\ti = find(dnum >= binstart & dnum < binend);\n\tif length(i)>0\n\t\td = data(i);\n\t\tthisdnum = dnum(i);\n\t\tcounts_per_bin(c) = length(d);\n\t\tsum_per_bin(c)=nansum(d);\n\t\tmedian_per_bin(c)=nanmedian(d);\n\t\tstd_per_bin(c) = std(d);\n        \tsmallest_per_bin(c)=min(d);\n        \tbiggest_per_bin(c)=max(d);\n\t\tmedian_time_interval(c)=median(thisdnum(2:end)-thisdnum(1:end-1));\n\telse\n\t\tcounts_per_bin(c) = 0;\n\t\tsum_per_bin(c) = 0;\n\t\tstd_per_bin(c) = 0;\n\t\tmedian_per_bin(c) = NaN;\n\t\tsmallest_per_bin(c)=NaN;\n\t\tbiggest_per_bin(c)=NaN;\n\tend\n    end\nelse\n    disp('Could not bin - vector lengths dont match');\nend\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/core/+Catalog/+binning/bin_irregular.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5694655844335034}}
{"text": "function img = discreteCurve(varargin)\n%DISCRETECURVE Discretize a planar curve\n%\n%   IMG = discreteCurve(DIM, CURVE, WIDTH)\n%   DIM is the size of image, with the format [x0 dx x1;y0 dy y1]\n%   CURVE is a series of points describing the curve\n%   WIDTH is the max distance between pixel centers and points of the\n%   curve.\n%\n%   IMG = discreteCurve(LX, LY, ...);\n%   Specifes the pixels coordinates with the two row vectors LX and LY.\n%\n%   Example\n%   % creates a ring\n%   circle = circleAsPolygon([25 25 15], 120);\n%   img = discreteCurve([1 1 50;1 1 50], circle, 3);\n%   imshow(img);\n%\n%   See Also\n%   imShapes, discretePolyline, discretePolygon\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2007-03-19\n% Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n%   HISTORY\n%   19/06/2007: update doc\n%   04/03/2009: use meshgrid\n%   29/05/2009: use more possibilities for specifying grid\n\n% compute coordinate of image voxels\n[lx, ly, varargin] = parseGridArgs(varargin{:});\n[x, y]   = meshgrid(lx, ly);\n\n% get polyline vertex coordinates\ncurve = varargin{1};\nvarargin(1) = [];\n\n% determines width of the polyline\nwidth = 2;\nif ~isempty(varargin)\n    width = varargin{1};\nend\n\ntry\n    % try with vectorized version (greedy !!!)\n    dist = reshape(minDistancePoints([x(:) y(:)], curve), size(x));\ncatch\n    % if not enough memory, use loop instead\n    dist = zeros(size(x));\n    for i = 1:length(lx)\n        dist(:, i) = minDistancePoints([x(:,i) y(:,i)], curve);\n    end        \nend\n\n% create image : simple threshold over 2 dimensions\nimg = abs(dist) < width;\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/imShapes/discreteCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5694655844335033}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Find the start time offset based on the cyclic prefix\n%\n% This method is immune to the issues that plague the ZC sequences (frequency offset causes a time shift in the\n% correlation results)\n%\n% It's best to provide this function an upsampled copy of the burst to help fix any fractional time offset that might be\n% present\n%\n% @param samples Complex IQ samples that make up the full burst\n% @param sample_rate Sample rate (in Hz) of the provided samples\n% @return start_offset Sample index that the burst starts at (first sample of the first cyclic prefix)\nfunction [start_offset] = find_sto_cp(samples, sample_rate)\n    [long_cp_len, short_cp_len] = get_cyclic_prefix_lengths(sample_rate);\n    fft_size = get_fft_size(sample_rate);\n    cyclic_prefix_length_schedule = [...\n        long_cp_len, ...\n        short_cp_len, ...\n        short_cp_len, ...\n        short_cp_len, ...\n        short_cp_len, ...\n        short_cp_len, ...\n        short_cp_len, ...\n        short_cp_len, ...\n        long_cp_len];\n    num_ofdm_symbols = length(cyclic_prefix_length_schedule);\n\n    full_burst_len = sum(cyclic_prefix_length_schedule) + (fft_size * num_ofdm_symbols);\n    num_tests = length(samples) - full_burst_len;\n    scores_cp_sto = zeros(1, num_tests);\n\n    for idx=1:num_tests\n        offset = idx;\n        scores = zeros(1, num_ofdm_symbols);\n    \n        % Extract and correlate the samples that each cyclic prefix is expected\n        % to be at\n        for cp_idx=1:num_ofdm_symbols\n            cp_len = cyclic_prefix_length_schedule(cp_idx);\n    \n            % Extract the full OFDM symbol including cyclic prefix\n            window = samples(offset:offset + fft_size + cp_len - 1);\n    \n            % Extract the cyclic prefix and the final samples of the symbol\n            left = window(1:cp_len);\n            right = window(end - cp_len + 1:end);\n    \n            % Correlate the two windows\n            scores(cp_idx) = abs(xcorr(left, right, 0));\n    \n            % Move the sample pointer forward by the full symbol size\n            offset = offset + cp_len + fft_size;\n        end\n    \n        % In the real DroneID the first OFDM symbol needs to be ignored since\n        % it isn't always present.  So, just average the correlation scores of\n        % all but the first element\n        scores_cp_sto(idx) = sum(scores(2:end)) / (length(scores) - 1);\n\n    end\n\n    % Find the index of the highest score\n    [~, start_offset] = max(scores_cp_sto);\nend\n\n", "meta": {"author": "proto17", "repo": "dji_droneid", "sha": "6ecbd20bdb1babbe2481a3870221553a10cdfe21", "save_path": "github-repos/MATLAB/proto17-dji_droneid", "path": "github-repos/MATLAB/proto17-dji_droneid/dji_droneid-6ecbd20bdb1babbe2481a3870221553a10cdfe21/matlab/updated_scripts/find_sto_cp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5693858107532851}}
{"text": "function varargout = transformPoint3d(pts, transfo, varargin)\n%TRANSFORMPOINT3D Transform a point with a 3D affine transform.\n%\n%   PT2 = transformPoint3d(PT1, TRANS);\n%   PT2 = transformPoint3d(X1, Y1, Z1, TRANS);\n%   where PT1 has the form [xp yp zp], and TRANS is a 3-by-3, 3-by-4, or\n%   4-by-4 matrix, returns the point transformed according to the affine\n%   transform specified by TRANS.\n%\n%   The function accepts transforms given using the following formats:\n%   [a b c]   ,   [a b c j] , or [a b c j]\n%   [d e f]       [d e f k]      [d e f k]\n%   [g h i]       [g h i l]      [g h i l]\n%                                [0 0 0 1]\n%\n%   PT2 = transformPoint3d(PT1, TRANS) \n%   also work when PT1 is a N-by-3-by-M-by-P-by-ETC array of double. In\n%   this case, PT2 has the same size as PT1.\n%\n%   PT2 = transformPoint3d(X1, Y1, Z1, TRANS);\n%   also work when X1, Y1 and Z1 are 3 arrays with the same size. In this\n%   case, PT2 will be a 1-by-3 cell containing {X Y Z} outputs of size(X1).\n%\n%   [X2, Y2, Z2] = transformPoint3d(...);\n%   returns the result in 3 different arrays the same size as the input.\n%   This form can be useful when used with functions like meshgrid or warp.\n%   \n%   MESH2 = transformPoint3d(MESH, TRANS) \n%   transforms the field 'vertices' of the struct MESH and returns the same\n%   struct with the transformed vertices.\n%   (It is recommended to use the function 'transformMesh', within the\n%   \"meshes3d\" module). \n%\n%   See also \n%     points3d, transforms3d, transformMesh, createTranslation3d\n%     createRotationOx, createRotationOy, createRotationOz, createScaling\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2005-02-10\n% Copyright 2005-2022 INRA - TPV URPOI - BIA IMASTE\n\n%% Parse input arguments\n\n% Check special case: if first argument is a struct with a field named\n% 'vertices', then the output will be the same struct, but with the\n% transformed vertices.\nif nargin == 2 && isstruct(pts) && isfield(pts, 'vertices')\n    mesh = pts;\n    mesh.vertices = transformPoint3d(mesh.vertices, transfo);\n    varargout = {mesh};\n    return;\nend\n\n% Parse x, y, and z coordinates of input points from input arguments\nif nargin == 2\n    % Point coordinates are given in a single N-by-3-by-M-by-etc argument.\n    % Preallocate x, y, and z to size N-by-1-by-M-by-etc, then fill them in\n    dim = size(pts);\n    dim(2) = 1;\n    [x, y, z] = deal(zeros(dim, class(pts)));\n    x(:) = pts(:,1,:);\n    y(:) = pts(:,2,:);\n    z(:) = pts(:,3,:);\n    \nelseif nargin == 4\n    % Point coordinates are given in 3 different arrays\n    x = pts;\n    y = transfo;\n    z = varargin{1};\n    transfo = varargin{2};\n    dim = size(x);\n    \nelse\n    error('MatGeom:geom3d:WrongInputArgumentNumber', ...\n        'Requires number of input arguments to be either 2 or 4');\nend\n\n\n%% Process transformation matrix\n\n% extract the linear and the translation parts of the matrix\nlinear = transfo(1:3, 1:3)';\ntrans = [0 0 0];\nif size(transfo, 2) > 3\n    trans = transfo(1:3, 4)';\nend\n\n\n%% Main processing\n\n% convert coordinates\ntry\n    % vectorial processing, if there is enough memory.\n    % same as: \n    % res = (transfo * [x(:) y(:) z(:) ones(NP, 1)]')';\n    res = bsxfun(@plus, [x(:) y(:) z(:)] * linear, trans);\n    \n    % Back-fill x,y,z with new result (saves calling costly reshape())\n    x(:) = res(:,1);\n    y(:) = res(:,2);\n    z(:) = res(:,3);\n    \ncatch ME\n    disp(ME.message)\n    % process each point one by one, writing in existing array\n    NP = numel(x);\n    for i = 1:NP\n        res = [x(i) y(i) z(i)] * linear + trans;\n        x(i) = res(1);\n        y(i) = res(2);\n        z(i) = res(3);\n    end\nend\n\n% process output arguments\nif nargout <= 1\n    % results are stored in a unique array\n    if length(dim) > 2 && dim(2) > 1\n        warning('geom3d:shapeMismatch',...\n            'Shape mismatch: Non-vector xyz input should have multiple x,y,z output arguments. Cell {x,y,z} returned instead.')\n        varargout{1} = {x,y,z};\n    else\n        varargout{1} = [x y z];\n    end\n    \nelseif nargout == 3\n    % results are returned in three array with same size.\n    varargout = {x, y, z};\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/transformPoint3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5693857891779918}}
{"text": "function s = addrice(s)\n%ADDRICE Add the Rician distribution.\n\n%   Copyright 1993-2004 The MathWorks, Inc.\n%   $Revision: 1.1.6.10 $  $Date: 2004/02/01 22:10:34 $\n\nj = length(s) + 1;\ns(j).name = 'Rician';\ns(j).code = 'rician';\ns(j).pnames = {'s' 'sigma'};\ns(j).pdescription = {'noncentrality' 'scale'};\ns(j).prequired = [false false];\ns(j).fitfunc = @ricefit;\ns(j).likefunc = @ricelike;\ns(j).cdffunc = @ricecdf;\ns(j).pdffunc = @ricepdf;\ns(j).invfunc = @riceinv;\ns(j).statfunc = @ricestat;\ns(j).loginvfunc = [];\ns(j).logcdffunc = [];\ns(j).hasconfbounds = false;\ns(j).censoring = true;\ns(j).paramvec = true;\ns(j).support = [0 Inf];\ns(j).closedbound = [false false];\ns(j).iscontinuous = true;\ns(j).islocscale = false;\ns(j).uselogpp = false;\n\n\n% ==== Rician distribution functions ====\n\n% these distribution functions do not yet handle arrays of parameters\n\nfunction y = ricepdf(x,s,sigma)\n%RICEPDF Rician probability density function (pdf).\ns(s < 0) = NaN;\nsigma(sigma <= 0) = NaN;\n\nx(x<0) = 0;\nsigsq = sigma.^2;\nexpon = (x.^2 + s.^2)./(2.*sigsq);\ny = (x./sigsq) .* exp(-expon) .* besseli(0, x.*s./sigsq);\ny(expon > (log(realmax(class(x)))-1)) = 0; % fix up 0*Inf\n\n\nfunction p = ricecdf(x,s,sigma)\n%RICECDF Rician cumulative distribution function (cdf).\ns(s < 0) = NaN;\nsigma(sigma <= 0) = NaN;\n\nx(x<0) = 0;\np = ncx2cdf((x./sigma).^2, 2, (s./sigma).^2);\n\n\nfunction x = riceinv(p,s,sigma)\n%RICEINV Inverse of the Rician cumulative distribution function (cdf).\ns(s < 0) = NaN;\nsigma(sigma <= 0) = NaN;\n\nx = sigma .* sqrt(ncx2inv(p, 2, (s./sigma).^2));\n\n\nfunction r = ricernd(s,sigma,varargin)\n%RICERND Random arrays from the Rician distribution.\ns(s < 0) = NaN;\nsigma(sigma <= 0) = NaN;\n\n[err, sizeOut] = statsizechk(2,s,sigma,varargin{:});\nif err > 0\n    error('stats:ricernd:InconsistentSizes','Size information is inconsistent.');\nend\n\nr = sigma .* sqrt(ncx2rnd(2, (s./sigma).^2, sizeOut));\n\n\nfunction [m,v] = ricestat(s,sigma)\n%RICESTAT Mean and variance for the Rician distribution.\ns(s < 0) = NaN;\nsigma(sigma <= 0) = NaN;\n\nt = .5 .* (s./sigma).^2;\nm = sigma.*sqrt(.5.*pi).*exp(-.5.*t) .* ((1+t).*besseli(0,.5.*t) + t.*besseli(1,.5.*t));\nv = 2.*sigma.^2 + s.^2 - m.^2;\n\n\nfunction [nlogL,acov] = ricelike(params,data,cens,freq)\n%RICELIKE Negative log-likelihood for the Rician distribution.\nif nargin < 4 || isempty(freq), freq = ones(size(data)); end\nif nargin < 3 || isempty(cens), cens = zeros(size(data)); end\n\nnlogL = rice_nloglf(params, data, cens, freq);\nif nargout > 1\n    acov = mlecov(params, data, 'nloglf',@rice_nloglf, 'cens',cens, 'freq',freq);\nend\n\n\n% ==== Rician fitting functions ====\n\nfunction [phat,pci] = ricefit(x,alpha,cens,freq,opts)\n%NAKAFIT Parameter estimates and confidence intervals for Rician data.\n\nif nargin < 2 || isempty(alpha), alpha = .05; end\nif nargin < 3 || isempty(cens), cens = zeros(size(x)); end\nif nargin < 4 || isempty(freq), freq = ones(size(x)); end\nif nargin < 5, opts = []; end\n\nif any(x <= 0)\n    error('stats:ricefit:BadData','The data in X must be positive');\nend\n\n% Moment estimators of the uncensored data as starting point\n% E[x.^2] = s.^2 + 2.*sigma.^2\n% E[x.^4] = s.^4 + 8.*s.^2.*sigma.^2 + 8.*sigma.^4\nxsqunc = x(cens == 0).^2;\nmeanxsq = mean(xsqunc); meanx4th = mean(xsqunc);\nif meanxsq.^2 < meanx4th && meanx4th < 2.*meanxsq.^2\n    s4th = 2.*meanxsq.^2 - meanx4th;\n    ssq = sqrt(s4th);\n    sigsq = .5.*(meanxsq - ssq);\n    start = [sqrt(ssq) sqrt(sigsq)];\nelse\n    start = cast([1 1],class(x));\nend\n\n% The default options include turning fminsearch's display off.  This\n% function gives its own warning/error messages, and the caller can turn\n% display on to get the text output from fminsearch if desired.\noptions = statset(statset('ricefit'), opts);\ntolBnd = options.TolBnd;\noptions = optimset(options);\n\n% Maximize the log-likelihood with respect to s and sigma.\n[phat,nll,err,output] = ...\n    fminsearch(@rice_nloglf, start, options, x, cens, freq, tolBnd);\nif (err == 0)\n    % fminsearch may print its own output text; in any case give something\n    % more statistical here, controllable via warning IDs.\n    if output.funcCount >= options.MaxFunEvals\n        wmsg = 'Maximum likelihood estimation did not converge.  Function evaluation limit exceeded.';\n    else\n        wmsg = 'Maximum likelihood estimation did not converge.  Iteration limit exceeded.';\n    end\n    warning('stats:ricefit:IterOrEvalLimit',wmsg);\nelseif (err < 0)\n    error('stats:ricefit:NoSolution',...\n          'Unable to reach a maximum likelihood solution.');\nend\n\n% Compute CIs using a normal approximation for phat.\nif nargout > 1\n    acov = mlecov(phat, x, 'nloglf',@rice_nloglf, 'cens',cens, 'freq',freq);\n    probs = [alpha/2; 1-alpha/2];\n    se = sqrt(diag(acov))';\n    pci = norminv([probs probs], [phat; phat], [se; se]);\nend\n\n\nfunction nll = rice_nloglf(parms, x, cens, freq, tolBnd)\n%RICE_NLOGLF Objective function for Rician maximum likelihood.\ns = parms(1);\nsigma = parms(2);\nsigsq = sigma.^2;\n\n% Restrict sigma to the open interval (0, Inf).\nif nargin > 4\n    if s < tolBnd || sigma < tolBnd\n        nll = Inf;\n        return\n    end\nend\n\nbess0 = besseli(0, x.*s./sigsq);\nrsq = (x.^2 + s.^2)./(2.*sigsq);\nL = -rsq + log(bess0) + log(x./sigsq);\nncen = sum(freq.*cens);\nif ncen > 0\n    cen = (cens == 1);\n    xcen = x(cen);\n    L(cen) = log(marcumq(s./sigma,xcen./sigma));\nend\nnll = -sum(freq .* L);\n\n% Don't have derivatives of the Marcum's Q, so can't compute an analytic\n% gradient with censoring.\n%\n% if nargout > 1\n%     dlogbess0 = besseli(1, x.*s./sigsq) ./ bess0;\n%     dL1 = (-s + dlogbess0.*x) ./ sigsq;\n%     dL2 = (rsq - 1 - dlogbess0.*x.*s./sigsq) ./ sigma;\n%     if ncen > 0\n% %         dL1(cen) = ;\n% %         dL2(cen) = ;\n%     end\n%     ngrad = -[sum(freq .* dL1) sum(freq .* dL2)];\n% end\n\n\nfunction Q = marcumq(a,b)\n% Q = MARCUMQ(A,B) returns Marcum's \"Q\" function.\n\nif isa(a,'single') || isa(b,'single')\n   Q = repmat(single(NaN), size(a));\nelse\n   Q = repmat(NaN, size(a));\nend\nQ(a~=Inf & b==0) = 1;\nQ(a~=Inf & b==Inf) = 0;\nQ(a==Inf & b~=Inf) = 1;\nz = (isnan(Q) & a==0 & b~=Inf);\nif (any(z))\n   Q(z) = exp((-b(z).^2)./2);\nend\n\nz = isnan(Q) & ~isnan(a) & ~isnan(b);\nif (any(z(:)))\n%    aa = (a(z).^2)./2;\n   aa = (a.^2)./2;\n   bb = (b(z).^2)./2;\n\n   d = exp(-aa);\n   h = d;\n   f = bb.*exp(-bb);\n   k = 1;\n   delta = f .* h;\n   sum = delta;\n   j = (delta > sum.*eps(class(delta)));\n   while any(j)\n      d = aa.*d./k;\n      h = h + d;\n      f = bb.*f./(k+1);\n      delta = f .* h;\n      sum(j) = sum(j) + delta(j);\n      j = (delta > sum.*eps(class(delta)));\n      k = k + 1;\n   end\n   Q(z) = 1 - sum;\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/SpatialLayout_shrink/spatiallayoutcode/GeometricContext/geomContext_src_07_02_08/src/tools/weightedstats/private/addrice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594355, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5693857864095896}}
{"text": "function X = FDDL_updateX(Y, Y_range, D, D_range, X, opts)\n    % X = argmin_X 0.5\\|Yhat - Dhat X\\| + \n    %    + 0.5*lambda2(\\sum (normF2(Xi - Mi) - normF2(Mi - M)) + normF2(X) + normF2(X0 - M0))\n    %    + lambda1*norm1(X)\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%        \n    %% ================== block: test module ==========================\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    if nargin == 0     \n        addpath('../utils');\n        addpath('../sparse_coding');\n        tic\n        d       = 30;\n        N       = 7;\n        k       = 5;\n        C       = 3 ;\n        Y       = normc(rand(d,N*C));\n        D       = normc(rand(d,k*C));\n        Y_range = N* (0:C);\n        D_range = k* (0:C);\n        X       = randn(size(D,2), size(Y,2));\n\n        opts.k0       = k0;\n        opts.lambda1  = 0.01;\n        opts.lambda2  = 0.002;\n        opts.lambda3  = 0.1;\n        opts.max_iter = 250;\n        opts.show     = true;        \n        opts.check_grad = true;\n        opts          = initOpts(opts); % other attributes\n    end\n    \n    lambda1  = opts.lambda1;\n    lambda2  = opts.lambda2;\n    DtD      = D'*D;\n    D_0      = buildMhat(DtD, D_range, D_range);\n    Dhat     = D_0 + 2*opts.lambda2*eye(size(D_0,1));\n    DtY     = D'*Y;\n    Y_0     = buildMhat(DtY, D_range, Y_range);\n    %% cost w.r.t. X, X0, not includeing norm1 terms\n    function cost = calc_f(X)        \n        cost = 0.5*(normF2(Y - D*X) + ...\n                    FDDL_fidelity(Y, Y_range, D, D_range, X)) + ...       \n               0.5*opts.lambda2* (FDDL_discriminative(X, Y_range));\n    end \n    %% Total cose \n    function cost = calc_F(X)\n        cost = calc_f(X) + lambda1*norm1(X);\n    end \n    %%\n    %% Gradient for FISTA \n    function g = grad(X)\n        g       = Dhat*X - Y_0 + buildM_2Mbar(X, Y_range, lambda2);\n    end\n    %% check gradient\n    if opts.check_grad &&~check_grad(@calc_f, @grad, X)\n        fprintf('Check gradient or cost again!\\n')\n        pause\n    end       \n    %% ========= Main FISTA ==============================\n    optsXX0          = opts;\n    optsXX0.max_iter = 300;\n    L = max(eig(Dhat)) + 6*lambda2;  \n    X      = fista(@grad, X, L, opts.lambda1, opts, @calc_F);\n    %%\n    if nargin == 0   \n        fprintf('done, press any key to see results\\n');\n        pause;\n    end\nend \n\n", "meta": {"author": "tiepvupsu", "repo": "DICTOL", "sha": "1a0361aa35c32d70525d06910d0e9b87997ff246", "save_path": "github-repos/MATLAB/tiepvupsu-DICTOL", "path": "github-repos/MATLAB/tiepvupsu-DICTOL/DICTOL-1a0361aa35c32d70525d06910d0e9b87997ff246/LRSDL_FDDL/FDDL_updateX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5693857827460178}}
{"text": "function g = rbfbkp(net, x, z, n2, deltas)\n%RBFBKP\tBackpropagate gradient of error function for RBF network.\n%\n%\tDescription\n%\tG = RBFBKP(NET, X, Z, N2, DELTAS) takes a network data structure NET\n%\ttogether with a matrix X of input vectors, a matrix  Z of hidden unit\n%\tactivations, a matrix N2 of the squared distances between centres and\n%\tinputs, and a matrix DELTAS of the  gradient of the error function\n%\twith respect to the values of the output units (i.e. the summed\n%\tinputs to the output units, before the activation function is\n%\tapplied). The return value is the gradient G of the error function\n%\twith respect to the network weights. Each row of X corresponds to one\n%\tinput vector.\n%\n%\tThis function is provided so that the common backpropagation\n%\talgorithm can be used by RBF network models to compute gradients for\n%\tthe output values (in RBFDERIV) as well as standard error functions.\n%\n%\tSee also\n%\tRBF, RBFGRAD, RBFDERIV\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n% Evaluate second-layer gradients.\ngw2 = z'*deltas;\ngb2 = sum(deltas);\n\n% Evaluate hidden unit gradients\ndelhid = deltas*net.w2';\n\ngc = zeros(net.nhidden, net.nin);\nndata = size(x, 1);\nt1 = ones(ndata, 1);\nt2 = ones(1, net.nin);\n% Switch on activation function type\nswitch net.actfn\n      \ncase 'gaussian' % Gaussian\n   delhid = (delhid.*z);\n   % A loop seems essential, so do it with the shortest index vector\n   if (net.nin < net.nhidden)\n      for i = 1:net.nin\n         gc(:,i) = (sum(((x(:,i)*ones(1, net.nhidden)) - ...\n            (ones(ndata, 1)*(net.c(:,i)'))).*delhid, 1)./net.wi)';\n      end\n   else\n      for i = 1:net.nhidden\n         gc(i,:) = sum((x - (t1*(net.c(i,:)))./net.wi(i)).*(delhid(:,i)*t2), 1);\n      end\n   end\n   gwi = sum((n2.*delhid)./(2.*(ones(ndata, 1)*(net.wi.^2))), 1);\n   \ncase 'tps'\t% Thin plate spline activation function\n   delhid = delhid.*(1+log(n2+(n2==0)));\n   for i = 1:net.nhidden\n      gc(i,:) = sum(2.*((t1*(net.c(i,:)) - x)).*(delhid(:,i)*t2), 1);\n   end\n   % widths are not adjustable in this model\n   gwi = [];\ncase 'r4logr' % r^4 log r activation function\n   delhid = delhid.*(n2.*(1+2.*log(n2+(n2==0))));\n   for i = 1:net.nhidden\n      gc(i,:) = sum(2.*((t1*(net.c(i,:)) - x)).*(delhid(:,i)*t2), 1);\n   end\n   % widths are not adjustable in this model\n   gwi = [];\notherwise\n   error('Unknown activation function in rbfgrad')\nend\n   \ng = [gc(:)', gwi, gw2(:)', gb2];\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/rbfbkp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5693344490296725}}
{"text": "function I = randpermNK(N,K) \n% N is the number of trials/subjects\n% K is the number of groups\nif K==1\n    I = cell(1);\n    I{1} = randperm(N); \n    return; \nend\nnp=(N-mod(N,K))/K; % number of elements per group\n[~,idx]=sort(rand(N,1));\ni=1;\nj=1;\nI={};\nwhile 1\n    I{j}=idx(i:i+np-1,1);\n    if N-(i+np)+1 < np\n        I{j} = [I{j}; idx(i+np:end,1)];\n        break\n    end\n    i=i+np;\n    j=j+1;\nend\nend ", "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/randpermNK.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.569253474811422}}
{"text": "function C = PruneTree(C)\n\n% Logic:\n% Start with a clique, scan through its neighbors. If you find a neighbor\n% such that it is a superset of the clique you started with, then you know\n% that you can prune the tree. For instance, let's take the following\n% clique tree:\n% ABE -- AB ---AD\n% Let's say we started with AB. We scan through its neighbors and find that\n% AB is a subset of ABE. So we cut off the edges connected to AB and add an\n% edge between ABE and all of AB's other neighbors. This maintains the\n% running intersection property and gives us a more compact clique tree\n% which looks like: ABE -- AD.\n%\n% Copyright (C) Daphne Koller, Stanford University, 2012\n\ntoRemove = [];\n\nfor i=1:length(C.nodes)\n    \n    if ismember(i,toRemove), continue, end;\n    neighborsI = find(C.edges(i,:));\n    \n    for c = 1: length(neighborsI),\n        \n        j = neighborsI(c);\n        assert(i ~= j);\n        \n        if ismember(j,toRemove), continue, end;\n        \n        if (sum(ismember(C.nodes{i}, C.nodes{j})) == length(C.nodes{i}))\n            \n            for nk = neighborsI\n                \n                % find neighbors and connect with that.\n                if length(intersect(C.nodes{i}, C.nodes{nk})) == length(C.nodes{i})\n                    C.edges(setdiff(neighborsI,[nk]),nk) = 1;\n                    C.edges(nk,setdiff(neighborsI,[nk])) = 1;\n                    break;\n                end\n            end\n            \n            % kill the edges for the clique that is to be removed.\n            C.edges(i,:) = 0;\n            C.edges(:,i) = 0;\n            toRemove = [i toRemove];\n\n        end\n    end\nend\n\ntoKeep = setdiff(1:length(C.nodes),toRemove);\n\nC.nodes(toRemove) = [];\n\nif isfield(C, 'edges')\n    C.edges = C.edges(toKeep,toKeep);\nelse\n    C.edges = [];\nend\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/4.Exact Inference/PruneTree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5692534738306416}}
{"text": "function h = drawPoint3d(varargin)\n%DRAWPOINT3D Draw 3D point on the current axis.\n%\n%   drawPoint3d(X, Y, Z) \n%   will draw points defined by coordinates X, Y and Z. \n%   X, Y and Z are N*1 array, with N being number of points to be drawn.\n%   \n%   drawPoint3d(COORD) packs coordinates in a single [N*3] array.\n%\n%   drawPoint3d(..., OPT) will draw each point with given option. OPT is a \n%   string compatible with 'plot' model.\n%\n%   drawPoint3d(AX,...) plots into AX instead of GCA.\n%\n%   H = drawPoint3d(...) returns a handle H to the line object\n%\n%   Example\n%     % generate points on a 3D circle\n%     pts = circleToPolygon([40 30 20], 120);\n%     mat = eulerAnglesToRotation3d([30 20 10]);\n%     pts3d = transformPoint3d([pts zeros(120,1)],mat);\n%     figure; drawPoint3d(pts3d, 'b.');\n%     view(3); axis equal;\n%\n%   See also\n%     points3d, clipPoints3d, drawPoint\n%\n\n% ---------\n% Author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 18/02/2005.\n%\n%   HISTORY\n%   04/01/2007: remove unused variables, and enhance support for plot\n%       options\n%   12/02/2010 does not clip points anymore\n%   12/01/2018 added axes handle input\n%\n\nif numel(varargin{1}) == 1 && ishghandle(varargin{1}, 'axes')\n    hAx = varargin{1};\n    varargin(1)=[];\nelse\n    hAx = gca;\nend\n\nif length(varargin) == 1 && size(varargin{1}, 2) == 3\n    % points are given as one single array with 3 columns\n    px = varargin{1}(:,1);\n    py = varargin{1}(:,2);\n    pz = varargin{1}(:,3);\n    varargin = {};\nelseif length(varargin) == 2 && size(varargin{1}, 2) == 3\n    % points are given as one single array with 3 columns\n    px = varargin{1}(:,1);\n    py = varargin{1}(:,2);\n    pz = varargin{1}(:,3);\n    varargin = varargin(2);\nelseif length(varargin) >= 3 && size(varargin{1}, 2) == 3\n    % points are given as one single array with 3 columns\n    px = varargin{1}(:,1);\n    py = varargin{1}(:,2);\n    pz = varargin{1}(:,3);\n    varargin = varargin(2:end);\nelseif length(varargin) == 3 && numel(varargin{1})==numel(varargin{2}) && numel(varargin{1})==numel(varargin{3})\n    % points are given as 3 columns with equal lengths\n    px = varargin{1};\n    py = varargin{2};\n    pz = varargin{3};\n    varargin = {};\nelseif length(varargin) > 3\n    % points are given as 3 columns with equal lengths\n    px = varargin{1};\n    py = varargin{2};\n    pz = varargin{3};\n    varargin = varargin(4:end);\nelse\n    error('wrong number of arguments in drawPoint3d');\nend\n\n% default draw style: no line, marker is 'o'\nif length(varargin) ~= 1\n    varargin = ['linestyle', 'none', 'marker', 'o', varargin];\nend\n\n% plot only points inside the axis.\nhh = plot3(hAx, px, py, pz, varargin{:});\n\nif nargout > 0\n    h = hh;\nend\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/drawPoint3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.56925346942268}}
{"text": "% FindInl    find inliers in joint image matrix\n%\t\t\t by pairwise epipolar geometry\n%\n% function IdMatIn = findinl(Ws,IdMat,tol)\n% Ws ... 3MxN joint image matrix\n% IdMat ... MxN ... 0 -> no point detected\n%                   1 -> point detected\n% tol ... [pixels] tolerance for the epipolar geometry\n%         the point are accpted as outliers only if they\n%         are closer to the epipolar line than tol\n\n% $Author: svoboda $\n% $Revision: 2.1 $\n% $Id: findinl.m,v 2.1 2003/07/30 10:28:29 svoboda Exp $\n% $State: Exp $\n\nfunction IdMatIn = findinl(Ws,IdMat,tol)\n\nNoCams = size(IdMat,1);\n\n% fill the array of structures not_used denoted as 0\n% allocate the array of structures for used\nfor i=1:NoCams,\n  not_used(i).pts = sum(IdMat(i,:));\n  used(i).pts\t  = -1;\nend\n\n% allocate IdMat for outliers\nIdMatIn = zeros(size(IdMat));\n\nwhile (sum([not_used.pts])>1-NoCams),\n  [buff, id.cam_max]  = max([not_used.pts]);\n  used\t   = add(used, id.cam_max, not_used(id.cam_max).pts);\n  not_used = remove(not_used, id.cam_max);\n  Mask\t   = repmat(IdMat(id.cam_max,:),NoCams,1);\n  Corresp  = Mask & IdMat;\n  Corresp(id.cam_max,:) = 0;\n  [buff, id.cam_to_pair] = max(sum(Corresp')); % find the camera with most correspondences\n  idx.corr_to_pair = find(sum(IdMat([id.cam_max,id.cam_to_pair],:))==2);\n  % used\t   = add(used, id.cam_to_pair, not_used(id.cam_to_pair).pts);\n  % not_used = remove(not_used, id.cam_to_pair);\n  if size(idx.corr_to_pair,2)<8,\n\terror('Not enough points to compute epipolar geometry in RANSAC validation')\n  end\n  Wspair   = [];\n  Wspair   = Ws(id.cam_max*3-2:id.cam_max*3, idx.corr_to_pair);\n  Wspair   = [Wspair; Ws(id.cam_to_pair*3-2:id.cam_to_pair*3, idx.corr_to_pair)];\n  % id\n  [F, inls] = rEG(Wspair,tol,tol,0.99);\n  IdMatIn(id.cam_max, idx.corr_to_pair(inls)) = 1;\n  IdMat(id.cam_max, :)\t\t\t\t\t\t  = 0;\n  IdMat(id.cam_max, idx.corr_to_pair(inls))\t  = 1;\nend\n\nfunction list = add(list, id, value)\nlist(id).pts = value;\nreturn\n\nfunction list = remove(list, id)\nlist(id).pts = -1;\nreturn\n", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamSelfCal/CoreFunctions/findinl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5692468572472238}}
{"text": "function w = ymdf_to_weekday_gregorian ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_WEEKDAY_GREGORIAN returns the weekday of a Gregorian YMDF date.\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%  Parameters:\n%\n%    Input, integer Y, M, D, real F, the YMDF date.\n%\n%    Output, integer W, is the week day number of the date, with\n%    1 for Sunday, through 7 for Saturday.\n%\n  jed = ymdf_to_jed_gregorian ( y, m, d, f );\n\n  [ w, f2 ] = jed_to_weekday ( jed );\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_gregorian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.5692468551965669}}
{"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%==============================================================================\n%\n% Tutorial for FAIR: Examples for grid generation\n%\n%==============================================================================\n\nomega = [0,6,0,4,0,8]\nm     = [3,2,2]\nxc    = getCellCenteredGrid(omega(1:2),m(1));        xc = reshape(xc,1,[])\nxc    = getCellCenteredGrid(omega(1:4),m(1:2));      xc = reshape(xc,[m(1:2),2])\nxc    = getCellCenteredGrid(omega(1:6),m(1:3));      xc = reshape(xc,[m(1:3),3])\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/E3_getCellCenteredGrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5692468432445972}}
{"text": "function [Nm] = cal2Nm(cal)\n% Convert energy or work from calories to newtons-meters.\n% Note: these calories are different from the capitalized Calories found on\n% American cereal boxes.  American consumers are to healthy to eat a\n% 250,000 calorie candy bar.  \n% Chad A. Greene 2012\nNm = cal*4.1868;", "meta": {"author": "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/cal2Nm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5692468359601698}}
{"text": " function subplot_stack(x, ys, str_title, colors)\n%function subplot_stack(x, ys, str_title, colors)\n% a tight stack of subplots to show L signal components\n% in\n%\tx\t[N,1]\n%\tys\t[N,L]\t\tor ?\n\nif nargin == 1 && streq(x, 'test'), subplot_stack_test, return, end\nif nargin < 2, ir_usage, end\nif ~isvar('colors') || isempty(colors), colors = {'c', 'y'}; end\nif ~isvar('str_title') || isempty(str_title)\n\tstr_title = '';\nend\n\nif ~iscell(ys)\n\tys = {ys};\nend\nL = size(ys{1},2);\n\napos = get(gca, 'position'); % current axes position\nfor ll=1:L\n%\tpos = [0.1 0.1+0.8/L*(L-ll) 0.8 0.8/L];\n\tpos = [apos(1) apos(2)+apos(4)/L*(L-ll) apos(3) apos(4)/L];\n\tsubplot('position', pos) % l b w h\n\tfor ip=1:length(ys)\n\t\tplot(\tx, real(ys{ip}(:,ll)), colors{1+2*(ip-1)}, ...\n\t\t\tx, imag(ys{ip}(:,ll)), colors{2+2*(ip-1)})\n\t\tif ip == 1, hold on, end\n\tend\n\thold off\n\taxis tight\n\tytick(0), set(gca, 'yticklabel', '')\n\tfontsize = 10;\n\tfontweight = 'normal';\n\ttexts(1.02, 0.8, sprintf('%d.', ll), ...\n\t\t'fontsize', fontsize, 'fontweight', fontweight)\n\n\tif ll==1, title(str_title), end\n\tif ll<L\n\t\txtick off\n\tend\nend\n\nfunction subplot_stack_test\nx = linspace(0,1,101)';\ny = exp(2i*pi*x*[1:5]);\nif im\n\tclf, subplot(121)\n\tsubplot_stack(x, y)\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/graph/subplot_stack.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.569232892769136}}
{"text": "I = vl_test_pattern(1) ;\nur = 1:size(I,2) ;\nvr = 1:size(I,1) ;\n\n[u,v] = meshgrid(ur(1:5:end),vr(1:5:end)) ;\n\nf = [u(:)';v(:)'] ;\nK = size(f,2) ;\nf = [f ; 2 * ones(1,K) ; 0 * ones(1,K)] ;\n\nf = vl_sift(single(I), 'frames', f, 'orientations') ;\n\n%f = diag([1 1 6 1]) * f ;\n\nfigure(1) ; clf ;\nimagesc(I) ; colormap gray ; hold on ;\nvl_plotframe(f,'color','k','linewidth',3) ;\nvl_plotframe(f,'color','y','linewidth',2) ; axis equal ; axis off ;\n\nvl_demo_print('sift_or') ;\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/demo/vl_demo_sift_or.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5692328923969894}}
{"text": "function [] = bandfiltering(z_grid,x_res,y_res,spatial_bands,save_path,ifg_based_correction,n_degree_butterworth,norm_filter_flag)\n% function that computes the band pass filtered data usigng 2D FFT and a\n% butterwurth function. Make sure the input data is on a regular grid and\n% has no NaN values. There is no output passed in this function. Instead\n% the bandfiltered data is saved for each dataset individually, e.g.\n% 'dataset_1.mat' for the first dataset and increasing for the others. \n% input:\n% z_grid                    The data specified as a grid, i.e. a matrix.\n%                           Additonal datasets can be specified by \n%                           increasing the third dimention.\n% x_res                     The resolution in x-direction in m of the grid\n% y_res                     The resolution in y-direction in m of the grid\n% spatial_bands             The spatial band that need to be filtered in m, \n%                           specified as a 2 column matrix [lower upper].\n%                           Multiple band filters can be specified by \n%                           increasing the number or rows. \n% Optional inputs:\n% save_path                 The path were the output data will be saved. default\n%                           is the current directory\n% n_degree_butterworth      The degree of the butterwurth filter, by\n%                           default this is set to be 3.\n% norm_filter_flag          Normalisation of the butterwurth filter is done\n%                           by default. This is to scope with the issue\n%                           when the extremes of the bandfitler are too\n%                           close to eachother causing only a partial\n%                           amplitude passing in the selected band.\n% \n%     Copyright (C) 2015  Bekaert David - University of Leeds\n%     Email: eedpsb@leeds.ac.uk or davidbekaert.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 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 along\n%     with this program; if not, write to the Free Software Foundation, Inc.,\n%     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n%\n% By Bekaert David - December 2012\n% modifications:\n% DB\t02/2013\t\tInclude the save_path variable\n% DB    03/2013     Include warnings for edge effects and to large spatial\n%                   bandfilters.\n% DB    03/2013     Include 1D filtering to cope with limitation of narrow \n%                   datasets  \n% DB    05/2013     Include option to crop out a region\n\n% optional inputs for checking results:\n% figure properties\nfontsize = 15;\nplot_figures = 0;          % plot the figures for the n_plot_dataset dataset\nsave_fig =0;                % when 1 save figures in the figures folder in tha aps_p folder.\nn_plot_dataset=1;           % plot the figures for this band dataset. \n                            % Topography is first then the interferograms\ncheck_flag = 0;             % some additional figures being generated when turn on\nmirror_flag = 1;            % when 1, mirror the dataset such filtering effects\n                            % are reduced. The mirror is based on the\n                            % largest spatial filter wavelength.\n                            \nmax_perc_mirror_2D = 100;    % filtersize with respect to the dataset spatial \n                            % dimension in percentage till what 2D\n                            % filtering is allowed. When larger 1D\n                            % filtering is performed in the larger\n                            % dimension of X or Y. \n\n                            \nwarning_flag_perc = 10;     % Output a warning when more no mirroring is done,\n                            % and the percentage of half the filter length \n                            % with respect to the maximum dimension is mirrored.\n                            \nwarning_mirror_flag_perc = 50;  \n                            % Output a warning when more than this percentage \n                            % with respect to the maximum dimension is mirrored.\n                            % Mirroring is done by half the maximum filter size.\n\n                            \n% getting the data from the parms_aps file\ncrop_flag = getparm_aps('crop_flag');\n % setting the function defaults\nif nargin<6\n    ifg_based_correction='n';\nend\nif nargin<7\n    n_degree_butterworth = [];\nend\nif nargin<8\n    norm_filter_flag = [];\nend\nif isempty(n_degree_butterworth)==1\n   n_degree_butterworth=3; \nend\nif isempty(norm_filter_flag)==1\n   norm_filter_flag=1; \nend\nif nargin<5 || isempty(save_path)==1\n   save_path = './';\nend\nfprintf(['***Bandfiltering***\\n'])\nfprintf(['Using butterworth filter degree: ' num2str(n_degree_butterworth) '\\n'])\nif norm_filter_flag==1\n    fprintf(['Normalise the butterworth filter. \\n'])\nend\n\nnorm_filter_flag=0\nn_degree_butterworth = 10                                            \n% number of datasets\nn_datasets = size(z_grid,3);\nn_band_filters = size(spatial_bands,1);\nif strcmp(ifg_based_correction,'y')\n    h_ifg_number = n_datasets/2;\nelse\n    h_ifg_number=1;\nend                            \n                            \nif size(spatial_bands,1)==1 && size(spatial_bands,2)==2 && spatial_bands(1,1)==0 && spatial_bands(1,2)==inf\n    % this is a band filter of the whole image\n        for k=1:n_datasets\n\n            if k<=h_ifg_number && h_ifg_number~=1\n                % these are interferograms\n                save_name = ['bandfilter_regular_hgt_ifg_' num2str(k) '.mat'];\n            elseif k<=h_ifg_number && h_ifg_number==1\n                % these are the heights\n                save_name = 'bandfilter_regular_hgt.mat';\n            else\n                % thse are interferograms\n                 save_name = ['bandfilter_regular_ifg_' num2str(k-h_ifg_number) '.mat'];\n            end\n            data_band_out(:,:) = z_grid(:,:,k);\n            clear data_band\n            \n            dimension_filter=NaN;\n            % saving the bandfiltered data for eacht dataset seperately\n            save([save_path, filesep, save_name],'data_band_out','x_res','y_res','spatial_bands','dimension_filter')\n            clear data_band_out \n        end\nelse\n\n    % Starting the bandfiltering code\n    if plot_figures==1   \n        if n_plot_dataset<=h_ifg_number && h_ifg_number~=1\n            % thse are interferograms\n            save_folder_str=['aps_p' filesep 'fig_bandfilter_hgt_ifg' num2str(n_plot_dataset)];\n        elseif n_plot_dataset<=h_ifg_number && h_ifg_number==1\n            % these are the heights\n            save_folder_str=['aps_p' filesep 'fig_bandfilter_hgt'];\n        else\n            % these are interferograms\n            save_folder_str=['aps_p' filesep 'fig_bandfilter_ifg_' num2str(n_plot_dataset-h_ifg_number)];\n        end\n\n    %     if n_plot_dataset==1\n    %         save_folder_str=['aps_p' filesep 'fig_bandfilter_hgt'];\n    %     else\n    %         save_folder_str=['aps_p' filesep 'fig_bandfilter_ifg_' num2str(n_plot_dataset-1)];\n    %     end\n        if exist(save_folder_str,'dir')~=7\n           mkdir(save_folder_str) \n        end\n    end\n\n    % original gridsize\n    data_rows_or = size(z_grid,1);\n    data_columns_or = size(z_grid,2);\n\n    % investigate in the percentage of padding that is being performed\n    % below the percentage of the maximum band filter with respect to the dimension is computed\n    x_samples_overlap = ceil(max(spatial_bands,[],2)./x_res/2);\n    x_perc_overlap = x_samples_overlap./data_columns_or*100;\n    y_samples_overlap = ceil(max(spatial_bands,[],2)./y_res/2);\n    y_perc_overlap = y_samples_overlap./data_rows_or*100;\n\n    % output a warning in case the padding is to big or when the the filter\n    % effect hit the warning percentage as set at the start of the code.\n    if mirror_flag==1\n       warning_perc = warning_mirror_flag_perc ;\n    else\n       warning_perc = warning_flag_perc ;    \n    end\n    ix_x = find(x_perc_overlap>warning_perc);\n    ix_y = find(y_perc_overlap>warning_perc);\n    ix = intersect(ix_x,ix_y);\n    clear ix_x ix_y\n    if isempty(ix)~=1 \n        new_linestr = repmat('\\n',length(ix),1);        \n        outputstr = [num2str(spatial_bands(ix,:)) new_linestr];\n        if mirror_flag==1\n            fprintf(['***Warning: The following band filters are mirrored about ',num2str(warning_perc),' perc of the maximum dimension: \\n'])\n            for kk=1:size(outputstr,1)\n                fprintf(outputstr(kk,:)) ;\n            end\n            clear outputstr kk\n            fprintf(['This migth introduce arctifacts. \\n'])\n            fprintf(['It is recommended to limit to smaller spatial bandwidths. \\n'])\n\n        else\n            fprintf(['***Warning: The following band filters are above ',num2str(warning_perc),' perc of the maximum dimension: \\n'])\n            for kk=1:size(outputstr,1)\n                fprintf(outputstr(kk,:)) ;\n            end\n            clear outputstr kk\n            fprintf(['Likely edge effects are introduced. \\n'])\n            fprintf(['Turn the mirror flag on and/or limit to smaller spatial bandwidths. \\n\\n'])\n        end\n    end\n    clear ix\n\n    % output information on which bandfilters are replaced by a 1D filter to\n    % reduce edge effects from a limiting dimension\n    % x/y_perc_overlap represents the maximum bandfilter size with respect to\n    % the x/y dimension given as a percentage\n    ix_x = find(x_perc_overlap>max_perc_mirror_2D);\n    ix_y = find(y_perc_overlap>max_perc_mirror_2D);\n    \n    if isempty(ix_x)~=1 || isempty(ix_y)~=1\n        x_n_cases = length(ix_x);\n        y_n_cases = length(ix_y);\n        if x_n_cases>y_n_cases\n             fprintf(['X-direction appears limited for band filtering. \\n']) \n             fprintf(['1D (Y-direction) band filtering is performed for the following bands: \\n']) \n             new_linestr = repmat('\\n',length(ix_x),1);\n             outputstr = [num2str(spatial_bands(ix_x,:)) new_linestr];\n             for kk=1:size(outputstr,1)\n                 fprintf(outputstr(kk,:)) ;\n             end\n\n             % setting the variables for the 1D filtering\n             filter_1D_Y = 1;\n             filter_1D_X = 0;\n             ix_1D_filter = ix_x;\n             clear outputstr new_linestr kk ix_y ix_x\n\n        elseif y_n_cases>x_n_cases\n             fprintf(['Y-direction appears limited for band filtering. \\n']) \n             fprintf(['1D (X-direction) band filtering is performed for the following bands: \\n']) \n             new_linestr = repmat('\\n',length(ix_y),1);\n             outputstr = [num2str(spatial_bands(ix_y,:)) new_linestr];\n             for kk=1:size(outputstr,1)\n                 fprintf(outputstr(kk,:)) ;\n             end                  \n\n             % setting the variables for the 1D filtering\n             filter_1D_Y = 0;\n             filter_1D_X = 1;\n             ix_1D_filter = ix_y;\n             clear outputstr new_linestr kk ix_x ix_y\n\n        else\n             fprintf(['Both dataset appears as limited for band filtering. \\n']) \n             fprintf(['2D band filtering is performed, but check the following bands: \\n']) \n             new_linestr = repmat('\\n',length(ix_y),1);\n             outputstr = [num2str(spatial_bands(ix_y,:)) new_linestr];\n             for kk=1:size(outputstr,1)\n                 fprintf(outputstr(kk,:)) ;\n             end   \n\n             % setting the variables for the 1D filtering\n             filter_1D_Y = 0;\n             filter_1D_X = 0;\n             ix_1D_filter = [];\n             clear outputstr new_linestr kk ix_x ix_y\n        end\n    else\n         filter_1D_Y = 0;\n         filter_1D_X = 0;\n         ix_1D_filter = [];\n    end\n\n\n    if plot_figures==1\n        data_original_image = z_grid(:,:,n_plot_dataset);\n    end\n\n\n    % mirror the edges of the grid to reduce filter effects at the edges\n    % get the maximum size of the spatial filters\n    if mirror_flag == 1\n        fprintf('Perform mirroring to reduce filtering effects on edges \\n')\n        fprintf('By half the maximum filter length at each edge. \\n')\n\n        % maximum spatial wavelength\n        max_band = max(max(spatial_bands));\n        if max_band == inf\n           max_band = 100000;        % extend the grid to a maximum of 100 km in case one goes to infinite \n        end\n        n_mirror_x = ceil(max_band./x_res*1.5);\n        n_mirror_y = ceil(max_band./y_res*1.5);\n\n        for k=1:n_datasets\n            % padding the grid symmetric \n            z_grid_new(:,:,k) = padarray(z_grid(:,:,k),[n_mirror_y n_mirror_x],'symmetric');\n            % plotting an intermediate figure when requested\n            if plot_figures==1 && k==n_plot_dataset\n                h1= figure('name','Data symmetric padded for largest filter');\n                imagesc(z_grid_new(:,:,k))\n                axis equal\n                axis tight\n\n                % saving of the figure when requested\n                if save_fig==1\n                    fig_save_name = [save_folder_str filesep 'original_data_mirrored.eps'];\n                    set(h1,'PaperPositionMode','auto')\n                    print(h1,'-depsc','-r150',fig_save_name)\n                    clear fig_save_name\n                    close(h1)\n                end\n                clear h1 \n            end\n        end\n        clear z_grid\n        z_grid = z_grid_new;\n    else\n       fprintf('No mirroring performed. Filter artifacts will become more persistent for larger wavelengths! \\n') \n    end\n\n\n    % size of the dataset\n    data_rows = size(z_grid,1);\n    data_columns = size(z_grid,2);\n\n    % Sampling frequency follows from the resolution\n    fs_rows = 1/y_res;          % rows sampling frequency [1/m]\n    fs_columns = 1/x_res;   \t% columns sampling frequency [1/m]\n\n    % rows and columns of the data such they are a power of 2\n    % this will speed up the fft and will autmoatically padd \n    % the data matrix with zeros where needed\n    data_rows_new = 2.^nextpow2(data_rows);\n    data_columns_new = 2.^nextpow2(data_columns);\n\n    if plot_figures==1\n        if mirror_flag==1\n            % computation of the axis extremes based on the resolution given\n            X_lims_fig = [0 data_columns_or*x_res];     % axis limits in [m]\n            Y_lims_fig = [0 data_rows_or*y_res];        % axis limits in [m] \n        else\n            X_lims_fig = [0 data_columns*x_res];        % axis limits in [m]\n            Y_lims_fig = [0 data_rows*y_res];           % axis limits in [m] \n        end\n        % computation of the axis extremes based on the resolution given \n        % Asummed to be symmetric padded. In case no padding is done, this will\n        % be equal to the orginal dataset\n        X_lims_fig_syix_1D_filterm = [0 data_columns*x_res];        % axis limits in [m]\n        Y_lims_fig_sym = [0 data_rows*y_res];           % axis limits in [m]\n    end\n\n\n    % Loop over each dataset. Invert to the freq domain once and reinvert for\n    % each bandfilter. i.e. There will be a loop over the different\n    % bandfilters. For each dataset the data is being saved in a matfile.\n    for k=1:n_datasets\n        if k==n_plot_dataset && plot_figures==1\n            plot_fig_flag = 1;\n        else\n            plot_fig_flag = 0;\n        end\n\n        fprintf(['Progress: ' num2str(k) '/' num2str(n_datasets) ,' done \\n'])\n        % when chosen visualise the dataset\n        if plot_fig_flag==1\n            h1 = figure('name','Original image');\n            imagesc(X_lims_fig,Y_lims_fig,data_original_image)\n            cc = colorbar;\n            axis xy\n            axis equal\n            axis tight\n            set(gca,'fontsize',fontsize)\n            xlabel('Distance [m]','fontsize',fontsize)\n            ylabel('Distance [m]','fontsize',fontsize)\n            title('Original image','fontsize',fontsize)\n            colorlimits = get(cc,'YLim');\n\n            % saving of the figure when requested\n            if save_fig==1\n                fig_save_name = [save_folder_str filesep 'input.eps'];\n                set(h1,'PaperPositionMode','auto')\n                print(h1,'-depsc','-r150',fig_save_name)\n                clear fig_save_name\n                close(h1)\n            end\n            clear h1 \n\n\n        end\n\n        % converting to the frequency domain by FFT\n        data_freq_complex = fft2(z_grid(:,:,k),data_rows_new,data_columns_new);\t\n\n        % shifting the spectrum around zero freq\n        % matlab shifts with 1 pixel off for even number columns and rows\n        data_freq_complex = fftshift(data_freq_complex);\n        data_freq_complex_new = [data_freq_complex  data_freq_complex(:,1)];\n        data_freq_complex_new = [data_freq_complex_new ; data_freq_complex_new(1,:)];\n        clear data_freq_complex\n\n        % Frequency domain: sampling resolution follows from the Nyquist requency (spampling freq/samples)\n        % freq resolution of the bins in the freq domain\n        fs_rows = 1/data_rows_new*1/y_res;\t\t\n        fs_columns = 1/data_columns_new*1/x_res;\n\n        % Computing the frequencies for the axis in the freq domain figures.\n        freq_rows_fig_vector = [-(data_rows_new-1)/2-0.5:1:(data_rows_new-1)/2+0.5].*fs_rows;\n        freq_columns_fig_vector= [-(data_columns_new-1)/2-0.5:1:(data_columns_new-1)/2+0.5].*fs_columns;\n\n        if plot_fig_flag==1  && check_flag==1\n            figure('name','Spectrum centralised around zero freq')\n            imagesc(freq_columns_fig_vector,freq_rows_fig_vector,abs(data_freq_complex_new))\n            xlabel('Xfreq [1/m]','fontsize',fontsize)\n            ylabel('Yfreq [1/m]','fontsize',fontsize)\n            title('Spectrum centralised around zero freq','fontsize',fontsize)\n            colorbar\n            set(gca,'fontsize',fontsize)\n            axis equal\n            axis tight\n\n            figure('name','Phase centralised around zero freq')\n            imagesc(freq_columns_fig_vector,freq_rows_fig_vector,angle(data_freq_complex_new))\n            xlabel('Xfreq [1/m]','fontsize',fontsize)\n            ylabel('Yfreq [1/m]','fontsize',fontsize)\n            title('Phase centralised around zero freq','fontsize',fontsize)\n            colorbar\n            set(gca,'fontsize',fontsize)\n            axis equal\n            axis tight\n        end\n\n\n\n        %% Computing the grid of frequencies\n        freq_rows_fig_matrix = repmat(freq_rows_fig_vector',1,data_columns_new+1);\n        freq_columns_fig_matrix = repmat(freq_columns_fig_vector,data_rows_new+1,1);\n        % Set the frequencies for 1D or 2D filtering\n        if filter_1D_X==1 \n            % 1D X-direction filter\n            freq_fig_matrix_1D = freq_columns_fig_matrix;\n            if plot_fig_flag==1 && check_flag==1\n                figure('name','Frequency grid 1D X-direction filter')\n                imagesc(freq_fig_matrix_1D)\n                xlabel('X','fontsize',fontsize)\n                ylabel('Y','fontsize',fontsize)\n                cc = colorbar;\n                set(gca,'fontsize',fontsize)\n                xlabel(cc,'Freq [1/m]','fontsize',fontsize)\n            end\n        elseif filter_1D_Y==1\n            % 1D Y-direction filter\n            freq_fig_matrix_1D = freq_rows_fig_matrix;\n            if plot_fig_flag==1 && check_flag==1\n                figure('name','Frequency grid 1D Y-direction filter')\n                imagesc(freq_fig_matrix_1D)\n                xlabel('X','fontsize',fontsize)\n                ylabel('Y','fontsize',fontsize)\n                cc = colorbar;\n                set(gca,'fontsize',fontsize)\n                xlabel(cc,'Freq [1/m]','fontsize',fontsize)\n            end\n        end\n        % 2D filter\n        freq_fig_matrix_2D = sqrt(freq_rows_fig_matrix.^2+freq_columns_fig_matrix.^2);\n        if plot_fig_flag==1 && check_flag==1\n            figure('name','Frequency grid')\n            imagesc(freq_fig_matrix_2D)\n            xlabel('X','fontsize',fontsize)\n            ylabel('Y','fontsize',fontsize)\n            cc = colorbar;\n            set(gca,'fontsize',fontsize)\n            xlabel(cc,'Freq [1/m]','fontsize',fontsize)\n        end\n\n\n        %% Loop over the different bandfilters\n        % initialisation of the output data_band variable\n        % This is after the symmetric padding has been removed again.\n        data_band_out = NaN([data_rows_or data_columns_or n_band_filters]);\n        dimension_filter = NaN([n_band_filters 1]);\n        for kk=1:n_band_filters\n            % output to the screen\n            fprintf(['Spatial bandfilter: ',num2str(spatial_bands(kk,1)), '\\t - ',num2str(spatial_bands(kk,2)),' \\t m \\t'])\n\n            % convert spatial wavelength band to spatial frequency band\n            f_band = 1./sort(spatial_bands(kk,:));\t% frequency band [1/m]\n\n\n            % Checking if the band filter is set as 1D or 2D filter\n            filter_1D = find(kk==ix_1D_filter);\n            if isempty(filter_1D)~=1\n                % do 1D filtering\n                % computing the function of the bandfilter\n                H_low = 1./(1+(freq_fig_matrix_1D./f_band(1)).^(2*n_degree_butterworth));\n                H_high = 1./(1+(freq_fig_matrix_1D./f_band(2)).^(2*n_degree_butterworth));\n                dimension_filter(kk) = 1;\n                fprintf(['(1D filter)\\n'])\n            else\n                % do 2D filtering\n                % computing the function of the bandfilter\n                H_low = 1./(1+(freq_fig_matrix_2D./f_band(1)).^(2*n_degree_butterworth));\n                H_high = 1./(1+(freq_fig_matrix_2D./f_band(2)).^(2*n_degree_butterworth));\n                dimension_filter(kk) = 2;\n                fprintf(['(2D filter)\\n'])\n            end\n\n            % Correct for the case of a filter having inf in its range\n            ix_center_spectrum = (size(H_high)-1)./2+1;\n            if isnan(H_high(ix_center_spectrum(1),ix_center_spectrum(2)))\n                H_high(ix_center_spectrum(1),ix_center_spectrum(2))=0;\n            end\n            if isnan(H_low(ix_center_spectrum(1),ix_center_spectrum(2)))\n                H_low(ix_center_spectrum(1),ix_center_spectrum(2))=0;\n            end\n            % Computing the band pass filter\n            H_Butterworth =  (H_low - H_high);\n            H_Butterworth_norm = H_Butterworth./max(max(H_Butterworth));\n\n            % plotting when requested\n            if plot_fig_flag==1\n                % plotting the filter around zero for the rows\n                h1 = figure('name','Rows freq filter');\n                subplot(4,1,1)\n                plot(freq_rows_fig_vector,H_low(:,ix_center_spectrum(2)),'b.-')\n                ylim([0 1])\n                title(['freq : ' num2str(f_band(1)) ])\n                subplot(4,1,2)\n                plot(freq_rows_fig_vector,H_high(:,ix_center_spectrum(2)),'b.-')\n                ylim([0 1]) \n                title(['freq : ' num2str(f_band(2)) ])\n                subplot(4,1,3)\n                plot(freq_rows_fig_vector,H_Butterworth(:,ix_center_spectrum(2)),'b.-')\n                ylim([0 1])\n                title(['Band freq' ])\n                subplot(4,1,4)\n                plot(freq_rows_fig_vector,H_Butterworth_norm(:,ix_center_spectrum(2)),'b.-')\n                ylim([0 1])\n                title(['Norm band freq' ])\n\n                % saving of the figure when requested\n                if save_fig==1\n                    fig_save_name = [save_folder_str filesep 'bandfilter_' num2str(spatial_bands(kk,1)) '_'  num2str(spatial_bands(kk,2)) 'm.eps'];\n                    set(h1,'PaperPositionMode','auto')\n                    print(h1,'-depsc','-r150',fig_save_name)\n                    clear fig_save_name\n                    close(h1)\n                end\n                clear h1 \n\n            end\n\n            if norm_filter_flag ==1 \n                H_Butterworth = H_Butterworth_norm;\n            end\n\n            % multiplying filter in frequency domain.\n            % data_freq_complex_new = real(data_freq_complex_new).*H_Butterworth+1i.*angle(data_freq_complex_new);\n            data_freq_complex_new_band = data_freq_complex_new.*H_Butterworth;\n            if plot_fig_flag==1  && check_flag==1\n                figure('name','New spectrum centralised around zero freq')\n                imagesc(freq_columns_fig_vector,freq_rows_fig_vector,abs(data_freq_complex_new_band))\n                xlabel('Xfreq [1/m]','fontsize',fontsize)\n                ylabel('Yfreq [1/m]','fontsize',fontsize)\n                title('Spectrum centralised around zero freq','fontsize',fontsize)\n                colorbar\n                set(gca,'fontsize',fontsize)\n                axis equal\n                axis tight\n\n                figure('name','New phase centralised around zero freq')\n                imagesc(freq_columns_fig_vector,freq_rows_fig_vector,angle(data_freq_complex_new_band))\n                xlabel('Xfreq [1/m]','fontsize',fontsize)\n                ylabel('Yfreq [1/m]','fontsize',fontsize)\n                title('Phase centralised around zero freq','fontsize',fontsize)\n                colorbar\n                set(gca,'fontsize',fontsize)\n                axis equal\n                axis tight\n            end\n\n            % Shifting the spectrum such the center frequency is at the top left corner\n            data_freq_complex_new_band(:,end) = [];\n            data_freq_complex_new_band(end,:) = [];\n            data_freq_complex_new_band = ifftshift(data_freq_complex_new_band);\n\n            % Inverting back to the spatial domain\n            data_band = ifft2(data_freq_complex_new_band,data_rows_new,data_columns_new);\n\n            % Removing the padded region introduced when putting the number of lines and rows 2^n\n            if data_rows-data_rows_new<0\t\t\t% for the rows\n                data_band(data_rows+1:end,:)=[];\n            end\n            if data_columns-data_columns_new<0\t\t% for the columns\n                data_band(:,data_columns+1:end)=[];\n            end\n\n            % Keeping only the real part\n            data_band = real(data_band);\n\n            % removing any mirrored image from the data\n            if mirror_flag == 1\n                data_band_or = data_band;\n                data_band([1:n_mirror_y],:)=[];\n                data_band([end-n_mirror_y+1:end],:)=[];\n                data_band(:,[1:n_mirror_x])=[];\n                data_band(:,[end-n_mirror_x+1:end])=[];\n            end\n\n\n            % plotting the final results when requested\n            if plot_fig_flag==1\n                h1= figure('name','output image');\n                imagesc(X_lims_fig,Y_lims_fig,data_band)  \n                % limit the colorbar to 95% bounds\n                data_sorted = sort(reshape(data_band,[],1));\n                ix = round([0.025 0.975].*length(data_sorted));\n                colorlimits = [data_sorted(ix)];    \n                caxis(colorlimits)\n                colorbar\n                set(gca,'fontsize',fontsize)\n                xlabel('Distance [m]','fontsize',fontsize)\n                ylabel('Distance [m]','fontsize',fontsize)\n                title(['Band filter: ' , num2str(spatial_bands(kk,1)) ,' -- ' ,num2str(spatial_bands(kk,2)),' m'],'fontsize',fontsize)\n                axis equal\n                axis tight\n                axis xy\n\n                % saving of the figure when requested\n                if save_fig==1\n                    fig_save_name = [save_folder_str filesep 'output_' num2str(spatial_bands(kk,1)) '_'  num2str(spatial_bands(kk,2)) 'm.eps'];\n                    set(h1,'PaperPositionMode','auto')\n                    print(h1,'-depsc','-r150',fig_save_name)\n                    clear fig_save_name\n                    close(h1)\n                end\n                clear h1 \n\n\n\n            end\n\n            % Storing the output data \n            data_band_out(:,:,kk) = data_band;\n            clear data_band\n        end\n\n\n\n        if k<=h_ifg_number && h_ifg_number~=1\n            % thse are interferograms\n            save_name = ['bandfilter_regular_hgt_ifg_' num2str(k) '.mat'];\n        elseif k<=h_ifg_number && h_ifg_number==1\n            % these are the heights\n            save_name = 'bandfilter_regular_hgt.mat';\n        else\n            % thse are interferograms\n             save_name = ['bandfilter_regular_ifg_' num2str(k-h_ifg_number) '.mat'];\n        end\n\n\n        % saving the bandfiltered data for eacht dataset seperately\n        save([save_path, filesep, save_name],'data_band_out','x_res','y_res','spatial_bands','n_degree_butterworth','norm_filter_flag','dimension_filter')\n        clear data_band_out \n    end\nend\n\n\n\n\n\n", "meta": {"author": "dbekaert", "repo": "TRAIN", "sha": "6c93feb95ae95eaf4c8468e89ec0b8325eac946f", "save_path": "github-repos/MATLAB/dbekaert-TRAIN", "path": "github-repos/MATLAB/dbekaert-TRAIN/TRAIN-6c93feb95ae95eaf4c8468e89ec0b8325eac946f/matlab/bandfiltering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5690311134680428}}
{"text": "function batch = propagate_batch(model, batch, layer)\n% propagate the batch from the bottom to the layer specified.\n% also works for layer == 2.\n\nglobal kConv_forward2;\nglobal kConv_forward_c;\n\nfor l = 2 : layer - 1\n    if l == 2\n        stride = model.layers{l}.stride;\n        hidden_presigmoid = myConvolve2(kConv_forward2, batch, model.layers{l}.w, stride, 'forward');\n        hidden_presigmoid = bsxfun(@plus, hidden_presigmoid, permute(model.layers{l}.c, [2,3,4,5,1]));\n        batch = 1 ./ (1 + exp(-hidden_presigmoid));\n    elseif strcmp(model.layers{l}.type, 'convolution')\n        stride = model.layers{l}.stride;\n        hidden_presigmoid = myConvolve(kConv_forward_c, batch, model.layers{l}.w, stride, 'forward');\n        hidden_presigmoid = bsxfun(@plus, hidden_presigmoid, permute(model.layers{l}.c, [2,3,4,5,1]));\n        batch = 1 ./ (1 + exp(-hidden_presigmoid));\n    else\n        batch_size = size(batch,1);\n        batch = reshape(batch, batch_size, []);\n        hidden_presigmoid = bsxfun(@plus, ...\n            batch * model.layers{l}.w, model.layers{l}.c);\n        batch = 1 ./ ( 1 + exp(- hidden_presigmoid) );\n    end\nend\n", "meta": {"author": "zhirongw", "repo": "3DShapeNets", "sha": "6a6cc71a9231051866092c94486ae967ac533d34", "save_path": "github-repos/MATLAB/zhirongw-3DShapeNets", "path": "github-repos/MATLAB/zhirongw-3DShapeNets/3DShapeNets-6a6cc71a9231051866092c94486ae967ac533d34/util/propagate_batch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.5690311039485021}}
{"text": "function mv=v_roteucode(m)\n%V_ROTEUCODE decodes a string specifying a rotation axis sequence\n%     M(n)     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  [radians]\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% Outputs:\n%\n%     mv(7,k)    where k-1 is the number of non-control characters in the input string m\n%                    mv(1,j) = Code for the j'th rotation: 1,2,3 for x,y,z rotation and 4 to 12 for the fixed rotations listed above.\n%                              All entries are in the range [1,12] except for mv(1,k)=0.\n%                    mv(2,j) = index into euler angle array for x,y,z rotations. mv(2,k) gives total number of euler angles needed\n%                    mv(3,j) = rotation class before rotation j. mv(3,k) is the final rotation class and equals 52 for arbitrary rotations.\n%                    mv(4,j) = index into a vectorized matrix of the entry that becomes non-zero after rotation j\n%                    mv(5,j) = index into a vectorized matrix of the other changing element in the same column\n%                    mv(6,j) = +-1 = sign of the sine term affecting entry mv(4,j). For mv(1,j) in [1,3], mv(6,j)=0 if the rotation is unnecessary\n%                    mv(7,j) = +-1 = sign of entry mv(5,j) before rotation j if known\n%                Special entries:\n%                    mv(7,k) = -1 to invert the rotation (i.e. transpose the matrix) or +1 otherwise\n%                    mv(4,k) = scale factor for euler angles: +-1 or +-pi/180\n%      \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\n%      Copyright (C) Mike Brookes 2007-2020\n%      Version: $Id: v_roteucode.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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\npersistent mes trmap zel mch mvch  jch nch\nif isempty(mes)     % setup fixed arrays and initialize cache of mode strings\n    nch=5;          % size of cache\n    mch=cell(nch,1); % cache of input character strings\n    mvch=cell(nch,1);  % cache of output mv codes\n    flefch=zeros(nch,2);  % cache of output flef codes\n    jch=(1:nch); % cache usage order jch(1) is the most recent, jch(nch) the oldest\n    for i=1:nch\n        mch{i}='';\n        mvch{i}=[0;0;1;1;0;0;1];\n    end\n    mes=[1:3 10:12 7:9 4:6]; % sign reversal look-up table\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % The trmap and zel arrays contain information about each of 52 different  %\n    % patterns of -1,0,+1 that may exist in a rotation matrix as follows:      %\n    %                                                                          %\n    %   1-3 : identity matrix rows in order: 123, 231, 312                     %\n    %   4-6 : negated identity matrix rows in order: 132, 213, 321             %\n    %   7-12: As 1-6 but with rows 2,3 negated                                 %\n    %  13-18: As 1-6 but with rows 1,3 negated                                 %\n    %  19-24: As 1-6 but with rows 1,2 negated                                 %\n    %  25-33: +1 in position (i-24) and 0's in remainder of this row and col   %\n    %  34-42: -1 in position (i-24) and 0's in remainder of this row and col   %\n    %  43-51: 0 in position (i-42)                                             %\n    %  52: no special symmetry                                                 %\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % trmap(i,j) gives the pattern that i is transformed into by rotation j    %\n    % where j=1:3 corresponds to x,y,z and j=4:12 corresponds to the 9         %\n    % multiples of 90 degree rotations listed in the main comments.            %\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    trmap=[ 25 29 33 16 24 11  7 13 19 22 12 17;\n        28 32 27 17 22 12  8 14 20 23 10 18;\n        31 26 30 18 23 10  9 15 21 24 11 16;\n        34 41 39 13 20  9 10 16 22 19  8 15;\n        37 35 42 14 21  7 11 17 23 20  9 13;\n        40 38 36 15 19  8 12 18 24 21  7 14;\n        25 38 42 22  6 23  1 19 13 16 18  5;\n        28 41 36 23  4 24  2 20 14 17 16  6;\n        31 35 39 24  5 22  3 21 15 18 17  4;\n        34 32 30 19  2 21  4 22 16 13 14  3;\n        37 26 33 20  3 19  5 23 17 14 15  1;\n        40 29 27 21  1 20  6 24 18 15 13  2;\n        34 29 42 10 12  5 19  1  7  4 24 23;\n        37 32 36 11 10  6 20  2  8  5 22 24;\n        40 26 39 12 11  4 21  3  9  6 23 22;\n        25 41 30  7  8  3 22  4 10  1 20 21;\n        28 35 33  8  9  1 23  5 11  2 21 19;\n        31 38 27  9  7  2 24  6 12  3 19 20;\n        34 38 33  4 18 17 13  7  1 10  6 11;\n        37 41 27  5 16 18 14  8  2 11  4 12;\n        40 35 30  6 17 16 15  9  3 12  5 10;\n        25 32 39  1 14 15 16 10  4  7  2  9;\n        28 26 42  2 15 13 17 11  5  8  3  7;\n        31 29 36  3 13 14 18 12  6  9  1  8;\n        25 44 45 25 36 26 25 34 34 25 27 35;\n        43 26 45 27 26 34 35 26 35 36 26 25;\n        43 44 27 35 25 27 36 36 27 26 34 27;\n        28 47 48 28 39 29 28 37 37 28 30 38;\n        46 29 48 30 29 37 38 29 38 39 29 28;\n        46 47 30 38 28 30 39 39 30 29 37 30;\n        31 50 51 31 42 32 31 40 40 31 33 41;\n        49 32 51 33 32 40 41 32 41 42 32 31;\n        49 50 33 41 31 33 42 42 33 32 40 33;\n        34 44 45 34 27 35 34 25 25 34 36 26;\n        43 35 45 36 35 25 26 35 26 27 35 34;\n        43 44 36 26 34 36 27 27 36 35 25 36;\n        37 47 48 37 30 38 37 28 28 37 39 29;\n        46 38 48 39 38 28 29 38 29 30 38 37;\n        46 47 39 29 37 39 30 30 39 38 28 39;\n        40 50 51 40 33 41 40 31 31 40 42 32;\n        49 41 51 42 41 31 32 41 32 33 41 40;\n        49 50 42 32 40 42 33 33 42 41 31 42;\n        43 52 52 43 45 44 43 43 43 43 45 44;\n        52 44 52 45 44 43 44 44 44 45 44 43;\n        52 52 45 44 43 45 45 45 45 44 43 45;\n        46 52 52 46 48 47 46 46 46 46 48 47;\n        52 47 52 48 47 46 47 47 47 48 47 46;\n        52 52 48 47 46 48 48 48 48 47 46 48;\n        49 52 52 49 51 50 49 49 49 49 51 50;\n        52 50 52 51 50 49 50 50 50 51 50 49;\n        52 52 51 50 49 51 51 51 51 50 49 51;\n        52 52 52 52 52 52 52 52 52 52 52 52];\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Each Euler angle is chosen so that the inverse rotation forces a specific element  %\n    % of the rotation matrix to zero. zel(k,j,i) gives information about which element   %\n    % ceases to be zero when a rotation around axis j is applied to pattern i.           %\n    %    k=1 gives the index into a vectorized matrix of the entry that becomes non-zero %\n    %    k=2 gives the index of the other element in the same column that changes        %\n    %    k=3 gives the sign of the sine term affecting the first of these entries        %\n    %    k=4 gives the sign of the initial value of the second of these entries if known %\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    zel=reshape([  6  5  1  1  3  1 -1  1  2  1  1  1;\n        2  3 -1  1  1  3  1  1  5  4  1  1;\n        3  2  1  1  4  6  1  1  1  2 -1  1;\n        5  6 -1 -1  3  1 -1 -1  2  1  1 -1;\n        3  2  1 -1  6  4 -1 -1  1  2 -1 -1;\n        2  3 -1 -1  1  3  1 -1  4  5 -1 -1;\n        6  5  1 -1  3  1 -1  1  2  1  1  1;\n        2  3 -1 -1  1  3  1 -1  5  4  1  1;\n        3  2  1 -1  4  6  1 -1  1  2 -1 -1;\n        5  6 -1  1  3  1 -1 -1  2  1  1 -1;\n        3  2  1  1  6  4 -1 -1  1  2 -1  1;\n        2  3 -1  1  1  3  1  1  4  5 -1  1;\n        6  5  1  1  3  1 -1 -1  2  1  1 -1;\n        2  3 -1 -1  1  3  1 -1  5  4  1 -1;\n        3  2  1  1  4  6  1 -1  1  2 -1  1;\n        5  6 -1  1  3  1 -1  1  2  1  1  1;\n        3  2  1 -1  6  4 -1  1  1  2 -1 -1;\n        2  3 -1  1  1  3  1  1  4  5 -1 -1;\n        6  5  1 -1  3  1 -1 -1  2  1  1 -1;\n        2  3 -1  1  1  3  1  1  5  4  1 -1;\n        3  2  1 -1  4  6  1  1  1  2 -1 -1;\n        5  6 -1 -1  3  1 -1  1  2  1  1  1;\n        3  2  1  1  6  4 -1  1  1  2 -1  1;\n        2  3 -1 -1  1  3  1 -1  4  5 -1  1;\n        0  0  0  0  3  1 -1  1  2  1  1  1;\n        3  2  1  1  0  0  0  0  1  2 -1  1;\n        2  3 -1  1  1  3  1  1  0  0  0  0;\n        0  0  0  0  6  4 -1  1  5  4  1  1;\n        6  5  1  1  0  0  0  0  4  5 -1  1;\n        5  6 -1  1  4  6  1  1  0  0  0  0;\n        0  0  0  0  9  7 -1  1  8  7  1  1;\n        9  8  1  1  0  0  0  0  7  8 -1  1;\n        8  9 -1  1  7  9  1  1  0  0  0  0;\n        0  0  0  0  3  1 -1 -1  2  1  1 -1;\n        3  2  1 -1  0  0  0  0  1  2 -1 -1;\n        2  3 -1 -1  1  3  1 -1  0  0  0  0;\n        0  0  0  0  6  4 -1 -1  5  4  1 -1;\n        6  5  1 -1  0  0  0  0  4  5 -1 -1;\n        5  6 -1 -1  4  6  1 -1  0  0  0  0;\n        0  0  0  0  9  7 -1 -1  8  7  1 -1;\n        9  8  1 -1  0  0  0  0  7  8 -1 -1;\n        8  9 -1 -1  7  9  1 -1  0  0  0  0;\n        0  0  0  0  1  3  1  1  1  2 -1  1;\n        2  3 -1  1  0  0  0  0  2  1  1  1;\n        3  2  1  1  3  1 -1  1  0  0  0  0;\n        0  0  0  0  4  6  1  1  4  5 -1  1;\n        5  6 -1  1  0  0  0  0  5  4  1  1;\n        6  5  1  1  6  4 -1  1  0  0  0  0;\n        0  0  0  0  7  9  1  1  7  8 -1  1;\n        8  9 -1  1  0  0  0  0  8  7  1  1;\n        9  8  1  1  9  7 -1  1  0  0  0  0;\n        0  0  0  0  0  0  0  0  0  0  0  0]',4,3,52);\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Convert the m string\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ~ischar(m) % lecacy call with integer m argument\n    m=char(m+'w'); % convert to characters\nend\nich=find(strcmp(m,mch),1);      % check if already in the cache\nif isempty(ich)                 % not yet in the cache\n    mm=m-'w';                   % convert to integers with x -> 1\n    mi=mm>=-31 & mm<=-29;       % find characters XYZ\n    mm(mi)=mm(mi)+32;           % convert XYZ to xyz (for compatibility)\n    mi=mm>=-70 & mm<=-62;       % find digits 1:9\n    mm(mi)=mm(mi)+74;           % convert to 4:12\n    mi=mm<=0;                   % select control characters\n    mc=mm(mi);                  % controls\n    mm=mm(~mi);                 % rotations\n    ef=1;                       % angle scale factor\n    es=1;                       % angle sign\n    fl=1;                       % default to no rotation matrix tranposing\n    for i=1:length(mc)\n        switch mc(i)\n            case -5             % 'r' = radians\n            case -19            % 'd' = degrees\n                ef=pi/180;      % scale factor to convert to radians\n            case -37            % 'R' = negated radians\n                ef=-1;\n            case -51            % 'D' = negated degrees\n                ef=-pi/180;      % scale factor to convert to radians\n            case -8             % 'o' = object-extrinsic\n            case -40            % 'O' = object-intrinsic\n                fl=-1;\n                es=-1;\n            case -22            % 'a' = axes-extrinsic\n                fl=-1;\n            case -54            % 'A' = axes-intrinsic\n                es=-1;\n            otherwise\n                error('Invalid character: %s',mc(i)+'w')\n        end\n    end\n    ef=ef*es;               % change sign of scale factor if necessary\n    if es<0\n        mm=mes(mm);         % sign-reverse: interchage 4,5,6 with 10,11,12\n    end\n    nm=length(mm);\n    mv=zeros(7,nm+1);\n    mv(1,:)=[mm 0];\n    mv(2,:)=cumsum([mm<=3 0]);      % index into euler angle array\n    mv(3,1)=1; % initial pattern is the identity matrix\n    for i=1:nm                % loop for each rotation\n        mmi=mm(i); % rotation code\n        mv(3,i+1)=trmap(mv(3,i),mmi); % pattern ID after rotation\n        if mmi<4\n            mv(4:7,i)=zel(:,mmi,mv(3,i)); % information about which matrix elements change from zero\n        end\n    end\n    mv(end)=fl;\n    mv(end-3)=ef;\n    % now save in the cache\n    ich=jch(nch);       % find oldest cache entry\n    mch{ich}=m;                 % save input string\n    mvch{ich}=mv;               % save parameters\n    jch=[ich jch(1:nch-1)];     % age all the other cache entries\nelse                            % already in the cache\n    kch=find(jch==ich,1);       % find existing ich entry\n    jch(1:kch)=[ich jch(1:kch-1)];\n    mv=mvch{ich};               % retrieve from cache\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_roteucode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5690310986481375}}
{"text": "function C = train_HLDA(XTr, YTr, nSegments, varargin)\n% TRAIN_HLDA - Hierarchical linear discriminant analysis \n%\n%Synopsis:\n%   C = train_HLDA(XTr, YTr, nSegments, varargin)\n%\n%Arguments:\n%   XTR: DOUBLE [TxNxM] - Data matrix, with T temporal features, N\n%                           N spatial features, and M \n%                           training points/examples. \n%   YTR: INT [CxM]      - Class membership labels of points in X_TR. C by M \n%                           matrix of training labels, with C representing \n%                           the number of classes and M the number of \n%                           training examples/points.\n%                           YTR(i,j)==1 if the point j belongs to class i.\n%   nSegments: INT      - the number of non-overlapping segments the interval\n%                           should be separated in  \n%   OPT: PROPLIST       - Structure or property/value list of optional\n%                           properties. Options are also passed to clsutil_shrinkage.\n%     'Regression'  - BOOL (default 0): If true, the top level classifier is\n%                           a logistic regression classifier. \n%     'nChannels'   - INT (default 0): Used when using 'crossvalidation' in order to \n%                           reconstruct the 2D feature matrix to its original 3D\n%                           [T x Ch x N] shape.\n%Returns:\n%   C: STRUCT           - Structure containing the trained classifiers for\n%                           each segment and the final top level\n%                           classifier. The structure C includes the fields:\n%       'seg': STRUCT []      - contains a trained LDA classifier for each segment\n%       'final': STRUCT       - the final top-level LDA classifier\n%       'nChannels': INT      - (optional) the number of channels in the training data\n%Description:\n%   train_HLDA trains a hierarchical LDA classifier given training data,\n%   labels and a number of segments. Either LDA (default) or logistic regression \n%   is used as a top-level classifier.\n%\n%   References:Gerson, A.D., Parra, L.C., Sajda, P.: Cortically coupled \n%   computer vision for rapid image search. IEEE Transactions on Neural \n%   Systems and Rehabilitation Engineering 14, 174\u2013179 (2006).\n\n%\n%\n%Examples:\n%   train_HLDA(XTr, YTr, nSegments)\n%   train_HLDA(XTr, YTr, nSegments, 'Regression', 1, 'nChannels', 64)\n%   \n%See also:\n%   APPLY_HLDA\n\n\nprops= {'Regression'      0                             'BOOL'\n        'nChannels'       0                             'INT'\n       };\n\n\nopt= opt_proplistToStruct(varargin{:});\n[opt, isdefault]= opt_setDefaults(opt, props);\nopt_checkProplist(opt, props);\n\n% validate argument types\nmisc_checkType(XTr, 'DOUBLE');\n\nif opt.nChannels ~= 0\n  misc_checkType(XTr, 'DOUBLE[- -]');\nend\n\nmisc_checkType(YTr, 'DOUBLE[2 -]');\nmisc_checkType(nSegments, 'INT');\n\ndims = size(XTr);\n\n% make data matrix 3D if it has been tranformed to 2D for crossvalidation\nif (length(size(XTr)) == 2) && opt.nChannels > 0\n  XTr = reshape(XTr, [], opt.nChannels, dims(2));\nend\n\ndims = size(XTr);\n\n%boundary indices between segments\nseg_idx = round(linspace(0, dims(1), nSegments+1));\n\nseg_scores = zeros(nSegments, dims(end));\n\nfor i = 1:nSegments\n    if length(size(XTr)) > 2\n      seg = XTr(seg_idx(i) + 1 : seg_idx(i + 1), :, :); % i-th segment of X\n      seg = reshape(seg, [], dims(end));\n    else\n      seg = XTr(seg_idx(i) + 1 : seg_idx(i + 1), :); % i-th segment of X\n    end\n    %train LDA classifier for this segment\n    seg_LDA = train_RLDAshrink(seg, YTr, 'Scaling', 1);\n    C.seg(i) = seg_LDA; \n    seg_scores(i,:) = apply_separatingHyperplane(seg_LDA, seg); %get classifier scores for segment\nend\n\nif opt.Regression\n    %logistic regression as top-level classifier\n    C.final.B = mnrfit(seg_scores', YTr');\nelse\n    %LDA as top-level classifier\n    C.final = train_RLDAshrink(seg_scores, YTr, 'Scaling', 1);\nend\n\n% add number of channels to classifier so they can be used in the apply function\nif opt.nChannels > 0\n  C.nChannels = opt.nChannels;\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_HLDA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.5690310857752189}}
{"text": "% Mseq Toolbox \n% Vesion 1.0 10-28-2001\n% written by Giedrius Buracas, \n% SNL-B, Salk Institute\n% \n% \n% Purpose:\n%\n%  Allows to evaluate estimation efficiency of m-sequence and \n%  rando-sequence based experimental designs for event-related \n%  fMRI experiments\n%\n% Sequence generation \n%\n%  balancedRnd\t\tGenerates random sequences, with either\n%\t\t\toverlaping or non-overlaping events\n%\t\t\tEqual numbers of events of each type is assumed \n%\n%  mseq\t\t\tGenerates binary, ternary, or five level\n%\t\t\tm-sequences. A unique feature of this code is that \n%\t\t\tmany m-sequences of given parameters\n%\t\t\tcan be generated\n%\n%  cycorr\t\tgenerates a cyclical autocorrelation\n%\t\t\tfunction of a given sequence. This is\n%\t\t\tthe fastest way to test whether a given sequence \n%\t\t\tis an m-sequence\n%\n%  m2bin\t\tconverts a binary m-sequence [-1,1] to\n%\t\t\ta sequence of [0,1]\n% \n%  bin2m\t\tconverts a sequence of [0,1] to [-1,1]\n%\n% Calculation of estimation efficiency\n%  \n%  makeEventMtrx\tgenerates an event matrix from a matrix of\n%\t\t\t[0,1] whose each column gives timing for\n%\t\t\teach event type\n%\n%  efficiencyOFexpDesigns2 script that compares estimation \n%\t\t\tefficiency of random and m-seuence-based\n%\t\t\texperimental designs. In this case\n%\t\t\tsimultaneously occuring events are permitted\n%\t\t\t(overlaping events)\n%\n%  effOFexpDesignsNoOverlap script that compares estimation \n%\t\t\tefficiency of random and m-seuence-based\n%\t\t\texperimental designs. In this case\n%\t\t\tsimultaneously occuring events are not permitted\n%\t\t\t(non-overlaping events)\n%\n%\n%  efficiencyOFexpDesignsCorrMtrx script that compares estimation \n%\t\t\tefficiency of random and m-seuence-based\n%\t\t\texperimental designs. \n%\t\t\tEfficiency is calculated with and without\n%\t\t\tfMRI noise \n%\n%\n%\n%\n \n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/OptimizeDesign11/M-sequence/mseq/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5689977795403216}}
{"text": "function a = svm(hyper) \n%=============================================================================\n% SVM Support Vector Machine object             \n%=============================================================================  \n% a=svm(hyperParam) \n%\n% Generates a svm object with given hyperparameters.\n%\n%\n%   Hyperparameters (with defaults)\n%   child=kernel         -- the kernel is stored as a member called \"child\"\n%   C=Inf                -- the soft margin C parameter\n%   ridge=1e-13          -- a ridge on the kernel\n%   balanced_ridge=0     -- for unbalanced data\n%   nu = 0               -- Schoelkopf's nu svm parameter\n%   optimizer='default'  -- other choices={andre,quadprog,svmlight,\n%                                          libsvm,svmtorch(linux only)}\n%                           For \"libsvm\" optimizer you can specify the used cache size\n%                           by the global variable \"libsvm_cachesize\".\n%   alpha_cutoff=-1;     -- keep alphas with abs(a_i)>alpha_cutoff\n%                           default keeps all alphas, another\n%                           reasonable choice is e.g alpha_cutoff=1e-5 to remove\n%                           zero alphas (i.e non-SVs) to speed up computations.\n% \n%   Model\n%    alpha               -- the weights\n%    b0                  -- the threshold\n%    Xsv                 -- the Support Vectors\n%\n% Methods:\n%  train, test, get_w \n%\n% Example:\n%\n%  d=gen(spiral({'m=200','n=2','noise=0.35'}));\n%  [r,a]=train(cv(svm({kernel('rbf',1),'optimizer=\"andre\"'})),d)\n%  plot(a{1})\n%\n%=============================================================================\n% Reference : A Tutorial on Support Vector Machines for Pattern Recognition  \n% Author    : Christopher J. C. Burges\n% Link      : http://citeseer.ist.psu.edu/burges98tutorial.html\n%=============================================================================\n\n  %<<------hyperparam initialisation------------->> \n  a.child=kernel;\n  a.C=Inf;\n  a.ridge=1e-13;  \n  a.balanced_ridge=0;\n  a.nu = 0;\n  a.optimizer='default';\n  a.alpha_cutoff=-1;\n  \n  \n  % <<-------------model----------------->> \n  a.alpha=[];\n  a.b0=0;\n  a.Xsv=[];\n  a.nob=0;\n  \n  algoType=algorithm('svm');\n  a= class(a,'svm',algoType);\n\n  a.algorithm.alias={'kern','child'}; % kernel aliases\n  \n if nargin==1,\n    eval_hyper;\n end;\n\n\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/pat/@svm/svm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5689977692287755}}
{"text": "function check = extreme_values_check ( a, b )\n\n%*****************************************************************************80\n%\n%% EXTREME_VALUES_CHECK checks the parameters of the Extreme Values CDF.\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, logical CHECK, is true if the parameters are legal.\n%\n  if ( b <= 0.0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'EXTREME_VALUES_CHECK - Fatal error!\\n' );\n    fprintf ( 1, '  B <= 0.\\n' );\n    check = 0;\n    return\n  end\n\n  check = 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/prob/extreme_values_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.5689977661353031}}
{"text": "function pass = test_feval(pref)\n% Test CHEBFUN3/FEVAL\n\nif ( nargin == 0)\n    pref = chebfunpref; \nend\ntol = 100*pref.cheb3Prefs.chebfun3eps;\n\nseedRNG(42);\n\nf = chebfun3t(@(x,y,z) x, [-1 2 -pi/2 pi -3 1]); \npass(1) = abs(f(0,0,0)) < tol*f.vscale;\n\npass(2) = abs(f(pi/6,pi/12,-1)-pi/6) < tol*f.vscale;  \n\nf = chebfun3t(@(x,y,z) y, [-1 2 -pi/2 pi -3 1]); \npass(3) = abs(f(0,0,0)) < tol;\n\npass(4) = abs(f(pi/6,pi/12,-1)-pi/12) < tol*f.vscale;\n\nf = chebfun3t(@(x,y,z) z, [-1 2 -pi/2 pi -3 1]); \npass(5) = abs(f(0,0,0)) < tol;\n\npass(6) = abs(f(pi/6,pi/12,-1)+1) < tol*f.vscale;\n\n% some harder tests. \nf = @(x,y,z) cos(x) + sin(x.*y) + sin(z.*x);\ng = chebfun3t(f);\npts = 2*rand(3,1) - 1;\npass(7) = abs(f(pts(1),pts(2),pts(3)) - g(pts(1),pts(2),pts(3))) < ...\n    tol*g.vscale;\n\n% Are we evaluating on arrays correctly?\nr = rand(10,1); \ns = rand(10,1); \nt = rand(10,1); \n[rr, ss, tt]=meshgrid(r,s,t);\npass(8) = max(abs((f(r,s,t) - g(r,s,t)))) < tol*g.vscale;\n\npass(9) = max(max(max(abs(f(rr,ss,tt) - g(rr,ss,tt))))) < tol*g.vscale;\n\n% Does this work off [-1,1]^2\ng = chebfun3t(f,[-pi/6 pi/2 -pi/12 sqrt(3) -3 1]); % strange domain. \nr = 0.126986816293506; s = 0.632359246225410; t = 0.351283361405006;\n% three fixed random number in domain.\npass(10) = abs(f(r,s,t) - g(r,s,t))<tol*g.vscale;\n\n% Are we evaluating on arrays correctly\npass(11) = abs(f(r,s,t) - g(r,s,t)) < tol*g.vscale;\n\npass(12) = max(max(max(abs(f(rr,ss,tt) - g(rr,ss,tt))))) < tol*g.vscale;\n\n% vector inputs\nff = @(x,y,z) sin(pi*(x+y+z));\nf = chebfun3t(ff);\nxx = linspace(-1, 1, 100)';\nyy = linspace(-1, 1, 100)';\nzz = linspace(-1, 1, 100)';\nF = f(xx,yy,zz);\nFF = ff(xx,yy,zz);\npass(13) = norm(F(:) - FF(:)) < 100*tol;\n\n% random vector inputs\nff = @(x,y,z) sin(pi*(x+y+z));\nf = chebfun3t(ff);\nxx = rand(100, 1);\nyy = rand(100, 1);\nzz = rand(100, 1);\nF = f(xx,yy,zz);\nFF = ff(xx,yy,zz);\npass(14) = norm(F - FF) < 100*tol;\n\n% meshgrid\nff = @(x,y,z) sin(pi*(x+y+z));\nf = chebfun3t(ff);\n[xx, yy, zz] = meshgrid(linspace(-1, 1, 100));\nF = f(xx,yy,zz);\nFF = ff(xx,yy,zz);\npass(15) = norm(F(:) - FF(:)) < 100*tol;\n\n% ndgrid\nff = @(x,y,z) sin(pi*(x+y+z));\nf = chebfun3t(ff);\n[xx, yy, zz] = ndgrid(linspace(-1, 1, 100));\nF = f(xx,yy,zz);\nFF = ff(xx,yy,zz);\npass(16) = norm(F(:) - FF(:)) < 100*tol;\n\n% random tensor inputs\nff = @(x,y,z) sin(pi*(x+y+z));\nf = chebfun3t(ff);\nxx = rand(10, 20, 30);\nyy = rand(10, 20, 30);\nzz = rand(10, 20, 30);\nF = f(xx,yy,zz);\nFF = ff(xx,yy,zz);\npass(17) = norm(F(:) - FF(:)) < 100*tol;\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun3t/test_feval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5689977630418306}}
{"text": "%%******************************************************************\n%% randlowranksdp.m : creates random feasible SDP problems where the \n%%                constraint matrices are low-rank matrices of the \n%%                form V*diag(d)*V'. \n%%\n%% [blk2,At2,C,b,blk,At] = randlowranksdp(n,m1,m2,r);\n%%\n%% blk2,At2: data with low-rank structure coded.\n%% blk, At:  data without taking low-rank structure into account.\n%%\n%% n = size of the sdp variable\n%% m1 = number of general constraints\n%% m2 = number of low-rank constraints\n%% r = rank of each constraint matrix. \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 [blk2,At2,C,b,blk,At] = randlowranksdp(n,m1,m2,r)\n\n  blk = cell(1,2);\n  if (m1 > 0) \n     [blk,At0,C,b0] = randsdp(n,[],[],m1);\n  else \n     b0 = []; At0 = cell(1);\n  end\n  if (m2 > 0)\n     if (nargout > 4)\n        [blk2,At2,C,b2,blk,At1] = randlowranksdpfun(n,m2,r);\n     else\n        [blk2,At2,C,b2] = randlowranksdpfun(n,m2,r);\n     end\n  else \n     b2 = []; At1 = cell(1); blk2 = blk; \n  end\n  b = [b0; b2];\n  if (nargout > 4)\n     At{1} = [At0{1}, At1{1}];\n  end\n  At2{1,1} = At0{1}; \n%%******************************************************************\n%%******************************************************************\n  function [blk2,At2,C,b,blk,At] = randlowranksdpfun(n,m,r)\n\n  randn('state',0);\n\n  blk{1,1} = 's'; blk{1,2} = n; \n  blk2{1,1} = 's'; blk2{1,2} = n; blk2{1,3} = r*ones(1,m); \n  %%\n  %% construct data with low rank structure\n  %%\n  At2 = cell(1,3); \n  b = zeros(m,1); \n  X0 = randn(n); X0 = X0*X0'; X0 = 0.5*(X0+X0');\n  ss = [0,cumsum(blk2{1,3})];\n  V = randn(n,m*r);  \n  dd = [];\n  for k = 1:length(blk2{1,3})\n     idx = [ss(k)+1 : ss(k+1)];\n     len = blk2{1,3}(k);\n     Dk = randn(len,len); Dk = 0.5*(Dk+Dk');\n     [ii,jj,vv] = find(Dk);\n     numnz = length(ii);\n     dd = [dd; k*ones(numnz,1),ii,jj,vv]; %% each row has the form [constr,i,j,val]\n     tmp1 = X0*V(:,idx); \n     tmp2 = V(:,idx)*Dk;\n     b(k) = sum(sum(tmp1.*tmp2));\n  end\n  At2{1,2} = V; At2{1,3} = dd;\n  Z0 = X0; \n  y0 = randn(m,1);\n  Aty = At2{1,2}*spdiags(mexexpand(blk2{1,3},y0),0,r*m,r*m)*At2{1,2}';\n  C{1} = Z0 + norm(Aty,'fro')*speye(n,n) + Aty; \n  C{1} = 0.5*(C{1}+C{1}');\n  %%\n  %% construct data without exploiting low rank structure\n  %%\n  if (nargout > 4)\n     idxD = [0; find(diff(dd(:,1))); size(dd,1)];\n     for k = 1:m\n        idx = [ss(k)+1 : ss(k+1)];\n        Vk = At2{1,2}(:,idx);\n        len = blk2{1,3}(k);\n        idx2 = [idxD(k)+1:idxD(k+1)];\n        Dk = spconvert([dd(idx2,2:4); len,len,0]);\n        A{k} = Vk*Dk*Vk';\n     end\n     At = svec(blk,A);\n  end\n%%******************************************************************\n", "meta": {"author": "shamilmamedov", "repo": "dynamic_calibration", "sha": "11af40e7deb758ec080a175fed8fcdd6c99aca29", "save_path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration", "path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration/dynamic_calibration-11af40e7deb758ec080a175fed8fcdd6c99aca29/utils/SDPT3-4.0/Examples/randlowranksdp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.5689977620106583}}
{"text": "function [w, infos] = hb(problem, in_options)\n% Heavy Ball algorithm.\n%\n% Inputs:\n%       problem     function (cost/grad/hess)\n%       in_options  options\n% Output:\n%       w           solution of w\n%       infos       information\n%\n% This file is part of GDLibrary and SGDLibrary.\n%\n% Created by H.Kasai on Oct. 28, 2020\n\n\n    % set dimensions and samples\n    d = problem.dim;\n    n = problem.samples;     \n    \n    % set local options \n    local_options = [];\n    local_options.step_alg = 'backtracking';\n    local_options.beta = 0.01;    \n\n    % merge options\n    options = mergeOptions(get_default_options(d), local_options);   \n    options = mergeOptions(options, in_options);     \n\n    % initialise\n    iter = 0;\n    grad_calc_count = 0;\n    w = options.w_init;\n    w_old = w;\n    prev_step = options.step_init;\n    \n    % for stepsize\n    if strcmp(options.step_alg, 'fix') || strcmp(options.step_alg, 'no_change')\n        if isprop(problem, 'L')\n            if problem.L > 0\n                if isprop(problem, 'mu')\n                    if problem.mu > 0\n                        % This casse is L-smooth and mu-strongly convex.\n                        cn = problem.L/problem.mu;\n                        options.step_init = 4/(sqrt(problem.L)+sqrt(problem.mu))^2;\n                        options.beta = ( (sqrt(cn)-1)/(sqrt(cn)+1) )^2;                        \n                    else\n                        % This casse is L-smooth\n                        options.step_init = 1/problem.L; \n                    end\n                else\n                    % This casse is L-smooth\n                    options.step_init = 1/problem.L; \n                end\n            else\n                options.step_alg = 'backtracking';\n            end\n        end\n    end\n\n    % initialize by BB step-size \n    if strcmp(options.step_init_alg, 'bb_init')\n        options.step_init = bb_init(problem, w);\n    end    \n    \n    % store first infos\n    clear infos;    \n    [infos, f_val, optgap, grad, gnorm] = store_infos(problem, w, options, [], iter, grad_calc_count, 0);\n    grad_old = grad;\n    \n    % display info\n    if options.verbose\n        fprintf('HB: Iter = %03d, cost = %.24e, gnorm = %.4e, optgap = %.4e\\n', iter, f_val, gnorm, optgap);\n    end  \n    \n    % set start time\n    start_time = tic();      \n\n    % main loop\n    while (optgap > options.tol_optgap) && (gnorm > options.tol_gnorm) && (iter < options.max_epoch)  \n        \n        options.iter = iter;\n        [step, ~] = options.linesearchfun(options.step_alg, problem, w, w_old, grad, grad_old, prev_step, options);   \n\n        prev_step = step;\n        w_w_old_diff = w - w_old;\n        w_old = w;\n  \n        % update w\n        w = w - step * grad + options.beta * w_w_old_diff;            \n\n        % proximal operator\n        if ismethod(problem, 'prox')            \n            w = problem.prox(w, step);\n        end\n        \n        % store gradient\n        grad_old = grad;\n\n        % measure elapsed time\n        elapsed_time = toc(start_time);  \n        \n        % count gradient evaluations\n        grad_calc_count = grad_calc_count + n;  \n        \n        % update iter        \n        iter = iter + 1;        \n        \n        % store infos\n        [infos, f_val, optgap, grad, gnorm] = store_infos(problem, w, options, infos, iter, grad_calc_count, elapsed_time);        \n\n        % display infos\n        if options.verbose\n            fprintf('HB: Iter = %03d, cost = %.24e, gnorm = %.4e, optgap = %.4e\\n', iter, f_val, gnorm, optgap);\n        end        \n    end\n    \n    if gnorm < options.tol_gnorm\n        fprintf('Gradient norm tolerance reached: tol_gnorm = %g\\n', options.tol_gnorm);\n    elseif optgap < options.tol_optgap\n        fprintf('Optimality gap tolerance reached: tol_optgap = %g\\n', options.tol_optgap);        \n    elseif iter == options.max_epoch\n        fprintf('Max iter reached: max_epoch = %g\\n', options.max_epoch);\n    end    \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/gd_solver/hb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936435, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5689977578860576}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   Q = INVERSEKINEMATIC_PA_10_6DOF(robot, T)\t\n%   Solves the inverse kinematic problem for the MITSUBISHI PA-10 robot\n%   where:\n%   robot stores the robot parameters.\n%   T is an homogeneous transform that specifies the position/orientation\n%   of the end effector.\n%\n%   A call to Q=INVERSEKINEMATIC_PA_10_6DOF returns 8 possible solutions, thus,\n%   Q is a 6x8 matrix where each column stores 6 feasible joint values.\n%\n%   \n%   Example code:\n%\n%   robot=load_robot('MISUBISHI', 'pa-10');\n%   q = [0 0 0 0 0 0];\t\n%   T = directkinematic(robot, q);\n%   %Call the inversekinematic for this robot\n%   qinv = inversekinematic(robot, T);\n%   check that all of them are feasible solutions!\n%   and every Ti equals T\n%   for i=1:8,\n%        Ti = directkinematic( robot, qinv(:,i))\n%   end\n%\tSee also DIRECTKINEMATIC.\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 <http://www.gnu.org/licenses/>.\nfunction q = inversekinematic_pa_10_6DOF(robot, T)\n\n%initialize, eight possible solutions\nq=zeros(6,8);\n\n%theta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\n%alpha = eval(robot.DH.alpha);\n\n%L1=d(1);\n%L2=a(2);\n%L3=d(4);\nL6=d(6);\n\n%T= [ nx ox ax Px;\n%     ny oy ay Py;\n%     nz oz az Pz];\nPx=T(1,4);\nPy=T(2,4);\nPz=T(3,4);\n\n%Calculamos la posici\ufffdn de la mu\ufffdeca. W es el tercer vector en el extremo\n%del brazo\nW = T(1:3,3);\n%Pm: posici\ufffdn de la mu\ufffdeca\nPm = [Px Py Pz]' - L6*W; \n\n%first joint, two possible solutions admited: \n% if q(1) is a solution, then q(1) + pi is also a solution\nq1=atan2(Pm(2), Pm(1));\n\n\n%solve for q2\nq2_1=solve_for_theta2(robot, [q1 0 0 0 0 0 0], Pm);\n\nq2_2=solve_for_theta2(robot, [q1+pi 0 0 0 0 0 0], Pm);\n\n%solve for q3\nq3_1=solve_for_theta3(robot, [q1 0 0 0 0 0 0], Pm);\n\nq3_2=solve_for_theta3(robot, [q1+pi 0 0 0 0 0 0], Pm);\n\n\n%the next matrix doubles each column. For each two columns, two different\n%configurations for theta4, theta5 and theta6 will be computed. These\n%configurations are generally referred as wrist up and wrist down solution\nq = [q1         q1         q1        q1       q1+pi   q1+pi   q1+pi   q1+pi;   \n     q2_1(1)    q2_1(1)    q2_1(2)   q2_1(2)  q2_2(1) q2_2(1) q2_2(2) q2_2(2);\n     q3_1(1)    q3_1(1)    q3_1(2)   q3_1(2)  q3_2(1) q3_2(1) q3_2(2) q3_2(2);\n     0          0          0         0         0      0       0       0;\n     0          0          0         0         0      0       0       0;\n     0          0          0         0         0      0       0       0];\n\n%leave only the real part of the solutions\nq=real(q);\n\n\n%normalize q to [-pi, pi]\nq(1,:) = normalize(q(1,:));\nq(2,:) = normalize(q(2,:));\nq(3,:) = normalize(q(3,:));\n\n% solve for the last three joints\n% for any of the possible combinations (theta1, theta2, theta3)\nfor i=1:2:size(q,2),\n    qtemp = solve_spherical_wrist_pa_10(robot, q(:,i), T, 1); %wrist up\n    qtemp(4:6)=normalize(qtemp(4:6));\n    q(:,i)=qtemp;\n    \n    qtemp = solve_spherical_wrist_pa_10(robot, q(:,i), T, -1); %wrist down\n    qtemp(4:6)=normalize(qtemp(4:6));\n    q(:,i+1)=qtemp;\nend\n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% solve for second joint theta2, two different\n% solutions are returned, corresponding\n% to elbow up and down solution\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction q2 = solve_for_theta2(robot, q, Pm)\n\n%Evaluate the parameters\ntheta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n%See geometry\nL2=a(2);\nL3=d(4);\n\n%given q1 is known, compute first DH transformation\nT01=dh(robot, q, 1);\n\n%Express Pm in the reference system 1, for convenience\np1 = inv(T01)*[Pm; 1];\n\nr = sqrt(p1(1)^2 + p1(2)^2);\n\nbeta = atan2(p1(2), p1(1));\ngamma = (acos((L2^2+r^2-L3^2)/(2*r*L2)));\nif ~isreal(gamma)\n    disp('WARNING:inversekinematic_pa_10: the point is not reachable for this configuration, imaginary solutions'); \n    %gamma = real(gamma);\nend\n%return two possible solutions\n%elbow up and elbow down\n%the order here is important and is coordinated with the function\n%solve_for_theta3\nq2(1) = beta + gamma-pi/2; %elbow up\nq2(2) = beta - gamma-pi/2; %elbow down\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% solve for third joint theta3, two different\n% solutions are returned, corresponding\n% to elbow up and down solution\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction q3 = solve_for_theta3(robot, q, Pm)\n\n%Evaluate the parameters\n%theta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\n%alpha = eval(robot.DH.alpha);\n\n%See geometry\nL2=a(2);\nL3=d(4);\n\n%given q1 is known, compute first DH transformation\nT01=dh(robot, q, 1);\n\n%Express Pm in the reference system 1, for convenience\np1 = inv(T01)*[Pm; 1];\n\nr = sqrt(p1(1)^2 + p1(2)^2);\n\neta = acos((L2^2 + L3^2 - r^2)/(2*L2*L3));\n\nif ~isreal(eta)\n   disp('WARNING:inversekinematic_pa_10: the point is not reachable for this configuration, imaginary solutions'); \n   %eta = real(eta);\nend\n%return two possible solutions\n%elbow up and elbow down solutions\n%the order here is important\nq3(1) = -pi + eta;\nq3(2) = -eta + pi;\n\n\n% Solve the special case of this spherical wrist\n% For wrists that whose reference systems have been placed as in the\n% ABB IRB 140--> use solve_spherical_wrist2\n% For wrists with the same orientation as in the KUKA KR30_jet\n%--> use solve_spherical_wrist\nfunction q = solve_spherical_wrist_pa_10(robot, q, T, wrist)\n\n\n% T is the noa matrix defining the position/orientation of the end\n% effector's reference system\nvx6=T(1:3,1);\nvz5=T(1:3,3); % The vector a z6=T(1:3,3) is coincident with z5\n\n% Obtain the position and orientation of the system 3\n% using the already computed joints q1, q2 and q3\nT01=dh(robot, q, 1);\nT12=dh(robot, q, 2);\nT23=dh(robot, q, 3);\nT03=T01*T12*T23;\n\nvx3=T03(1:3,1);\nvy3=T03(1:3,2);\nvz3=T03(1:3,3);\n\n% find z4 normal to the plane formed by z3 and a\nvz4=cross(vz3, vz5);\t% end effector's vector a: T(1:3,3)\n\n% in case of degenerate solution,\n% when vz3 and vz6 are parallel--> then z4=0 0 0, choose q(4)=0 as solution\nif norm(vz4) <= 0.00000001\n    if wrist == 1 %wrist up\n        q(4)=0;\n    else\n        q(4)=-pi; %wrist down\n    end\nelse\n    %this is the normal and most frequent solution\n    cosq4=wrist*dot(vy3,vz4);\n    sinq4=wrist*dot(-vx3,vz4);\n    q(4)=atan2(sinq4, cosq4);\nend\n%propagate the value of q(4) to compute the system 4\nT34=dh(robot, q, 4);\nT04=T03*T34;\nvx4=T04(1:3,1);\nvy4=T04(1:3,2);\n\n% solve for q5\ncosq5=dot(-vy4,vz5);\nsinq5=dot(vx4,vz5);\nq(5)=atan2(sinq5, cosq5);\n\n%propagate now q(5) to compute T05\nT45=dh(robot, q, 5);\nT05=T04*T45;\nvx5=T05(1:3,1);\nvy5=T05(1:3,2);\n\n% solve for q6\ncosq6=dot(vx6,vx5);\nsinq6=dot(vx6,vy5);\nq(6)=atan2(sinq6, cosq6);\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/robots/MITSUBISHI/PA-10/inversekinematic_pa_10_6DOF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5689977568548853}}
{"text": "classdef OFA < ALGORITHM\n% <single> <real/integer> <large/none> <constrained/none>\n% Optimal foraging algorithm\n\n%------------------------------- Reference --------------------------------\n% G. Zhu and W. Zhang, Optimal foraging algorithm for global optimization,\n% Applied Soft Computing, 2017, 51: 294-313.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Generate random population\n            Population = Problem.Initialization();\n            [~,rank]   = sort(FitnessSingle(Population));\n            Population = Population(rank);\n            \n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                PopDec     = Population.decs;\n                OffDec     = PopDec + Problem.FE./Problem.maxFE.*(rand(size(PopDec))-rand(size(PopDec))).*(PopDec-PopDec([end,floor(unifrnd(ones(1,end-1),2:end))],:));\n                Offspring  = Problem.Evaluation(OffDec);\n                lambda     = rand(Problem.N,1);\n                replace    = lambda.*FitnessSingle(Offspring)./(1+lambda*ceil(Problem.FE/Problem.N)) < FitnessSingle(Population)/ceil(Problem.FE/Problem.N);\n                Population(replace) = Offspring(replace);\n                [~,rank]   = sort(FitnessSingle(Population));\n                Population = Population(rank);\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/Algorithms/Single-objective optimization/OFA/OFA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.568990076209051}}
{"text": "function [cpulse, verbose] = tapas_physio_get_oxy_pulses_filtered(c, t, ...\n            dt120, verbose)\n% Determines peaks of pulse oximeter data after Gaussian and high pass\n% filtering, thresholding and assuming maximum heart rate (minimum peak\n% distance)\n%\n%   [cpulse, verbose] = tapas_physio_get_oxy_pulses_filtered(c, t, ...\n%            dt120, verbose);\n%\n% IN\n%   c               [nSamples, 1] raw pulse oximeter samples\n%   t               [nSamples, 1] time vector corresponding to samples (in seconds)\n%   dt120           number of samples corresponding to a heart rate of 120 beats\n%                   per minutes, i.e. number of samples acquiredi 0.5 seconds\n%   verbose         Substructure of PhysIO, holding verbose.level and\n%                   verbose.fig_handles with plotted figure handles\n%                   debugging plots for thresholding are only provided, if verbose.level >=2\n%\n% OUT\n%   cpulse          time points (seconds) of detected cardiac pulses\n%   (heartbeat events, e.g. R-peaks)\n%   verbose         Substructure of PhysIO, augmentedy by the additional\n%                   figure handles created during this function\n%\n% EXAMPLE\n%   tapas_physio_get_oxy_pulses_filtered\n%\n%   See also\n\n% Author: Lars Kasper\n% Created: 2014-08-03\n% Copyright (C) 2014 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.\n%\n% This file is part of the TAPAS PhysIO 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 <http://www.gnu.org/licenses/>.\n\ndt = t(2) - t(1);\nc = c-mean(c); c = c./max(c); % normalize time series\n\n% smooth noisy pulse oximetry data to detect peaks\nw = tapas_physio_gausswin(2*floor(dt120/2)+1, 1);  % Odd number of samples\nsc = tapas_physio_conv(c, w, 'symmetric');\nsc = sc-mean(sc); sc = sc./max(sc); % normalize time series\n\n% Highpass filter to remove drifts\ncutoff = 1/dt; %1 seconds/per sampling units\nforder = 2;\n[b,a] = butter(forder,2/cutoff, 'high');\nsc =filter(b,a, sc);\nsc = sc./max(sc);\n\n[tmp, cpulse] = tapas_physio_findpeaks(sc, 'minpeakheight',...\n    thresh_cardiac.min, 'minpeakdistance', dt120);\n\nif verbose.level >=2 % visualise influence of smoothing on peak detection\n    verbose.fig_handles(end+1) = tapas_physio_get_default_fig_params();\n    set(gcf, 'Name', 'Preproc: PPU-OXY: Tresholding Maxima for Heart Beat Detection');\n    [tmp, cpulse2] = tapas_physio_findpeaks(c,'minpeakheight',thresh_cardiac.min,'minpeakdistance', dt120);\n    plot(t, c, 'k');\n    hold all;\n    plot(t, sc, 'r', 'LineWidth', 2);\n    hold all\n    hold all;stem(t(cpulse2),c(cpulse2), 'k--');\n    hold all;stem(t(cpulse),sc(cpulse), 'm', 'LineWidth', 2);\n    plot(t, repmat(thresh_cardiac.min, length(t),1),'g-');\n    legend('Raw PPU time series', 'Smoothed PPU Time Series', ...\n        'Detected Heartbeats in Raw Time Series', ...\n        'Detected Heartbeats in Smoothed Time Series', ...\n        'Threshold (Min) for Heartbeat Detection');\nend\n\ncpulse = t(cpulse);\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/PhysIO/code/preproc/tapas_physio_get_oxy_pulses_filtered.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5689900748056907}}
{"text": "function [y] = spm_gx_hdm(x,u,P,M)\n% Simulated BOLD response to input.\n% FORMAT [y] = spm_gx_hdm(x,u,P,M)\n% y    - BOLD response (%)\n% x    - state vector     (see spm_fx_fmri)\n% P    - Parameter vector (see spm_fx_fmri)\n%__________________________________________________________________________\n%\n% This function implements the BOLD signal model described in: \n%\n% Stephan KE, Weiskopf N, Drysdale PM, Robinson PA, Friston KJ (2007)\n% Comparing hemodynamic models with DCM. NeuroImage 38: 387-401.\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston & Klaas Enno Stephan\n% $Id: spm_gx_hdm.m 6856 2016-08-10 17:55:05Z karl $\n\n\n% biophysical constants for 1.5 T: \n%==========================================================================\n\n% hemodynamic parameters\n%--------------------------------------------------------------------------\n%   H(1) - signal decay                                   d(ds/dt)/ds)\n%   H(2) - autoregulation                                 d(ds/dt)/df)\n%   H(3) - transit time                                   (t0)\n%   H(4) - exponent for Fout(v)                           (alpha)\n%   H(5) - resting oxygen extraction                      (E0)\n%   H(6) - ratio of intra- to extra-vascular components   (epsilon)\n%--------------------------------------------------------------------------\nif isstruct(P)\n    H     = [0.64 0.32 2.00 0.32 0.4];\n    for i = 1:numel(P.decay)\n        H(6)   = P.epsilon;\n        y(i,1) = spm_gx_hdm(x(i,:),u(i),H,M);\n    end\n    return\nend\n\n\n% echo time (seconds)\n%--------------------------------------------------------------------------\ntry\n    TE = M(1).TE;\ncatch\n    TE = 0.04;\nend\n\n% resting venous volume\n%--------------------------------------------------------------------------\nV0    = 100*0.08;                                \n\n% slope r0 of intravascular relaxation rate R_iv as a function of oxygen \n% saturation Y:  R_iv = r0*[(1-Y)-(1-Y0)]\n%--------------------------------------------------------------------------\nr0    = 25;\n\n% frequency offset at the outer surface of magnetized vessels\n%--------------------------------------------------------------------------\nnu0   = 40.3;\n\n% region-specific resting oxygen extraction fractions\n%-------------------------------------------------------------------------- \nE0    = P(5); \n\n% region-specific ratios of intra- to extravascular components of\n% the gradient echo signal (prior mean = 1, log-normally distributed \n% scaling factor)\n%--------------------------------------------------------------------------\nepsi  = exp(P(6));\n \n% coefficients in BOLD signal model\n%--------------------------------------------------------------------------\nk1    = 4.3.*nu0.*E0.*TE;\nk2    = epsi.*r0.*E0.*TE;\nk3    = 1 - epsi;\n \n% exponentiation of hemodynamic state variables\n%--------------------------------------------------------------------------\nx     = exp(x); \n\n% BOLD signal\n%--------------------------------------------------------------------------\nv     = x(3);\nq     = x(4);\ny     = V0*(k1.*(1 - q) + k2.*(1 - (q./v)) + k3.*(1 - v)); \n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_gx_hdm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.568990071760383}}
{"text": "function varargout = gallerysphere(name)\n%CHEB.GALLERYSPHERE   Spherefun example functions.\n%   F = CHEB.GALLERYSPHERE(NAME) returns a spherefun corresponding to NAME.\n%   See the listing below for available names.\n%\n%   For example,  plot(cheb.gallerysphere('football')) plots the classic\n%   icosahedral pattern of the Addias Telestar football (or soccer ball for\n%   Americans).  For details of how each function is constructed try \n%   'type +cheb/gallerysphere' or 'edit cheb.gallerysphere'.\n%\n%   [F,FA] = CHEB.GALLERYSPHERE(NAME) also returns the anonymous function\n%   FA used to define the function. Some gallery functions are generated by\n%   operations beyond the usual Spherefun constructor, so FA in those cases\n%   is equal to F.\n%\n%   CHEB.GALLERYSPHERE with no input argument returns a function chosen at\n%   random from the gallery.\n%\n%   CHEB.GALLERYSPHERE with no output argument creates a plot of the selected\n%   function.\n%\n%   Available names:\n%\n%   deathstar   A function resembling the surface of the Death Star.\n%   gaussian    Gaussian function on the sphere centered at Gauss's birth place.\n%   geomag      Radial component of the International Geomagnetic Reference\n%               field from the IGRF-12 model for 2015.\n%   football    Icosahedral pattern found on a traditional soccer ball.\n%   jet         A zonal jet stream over the mid-latitudes of the northern hemisphere.\n%   moire       Moire pattern from waves generated at two point sources.\n%   neamtu      Function created by Mike Neamtu for testing various spline\n%               interpolation methods on the sphere (see Alfeld, Neamtu,\n%               Schumaker, J. Comput. Appl. Math. 1996).\n%   peaks       Peaks like function on the sphere taken from the geopeaks\n%               function in the MATLAB mapping toolbox.\n%   randn       Random linear combination of all real spherical harmonics \n%               of exact degree 40.  The coefficients are generated from a \n%               i.i.d. Gaussian (normal) distribution with std=1.\n%   reprodkern  Reproducing kernel for spherical harmonics of degree 10\n%               centered at (x,y,z) = (-1/sqrt(3),-1/sqrt(3),1/sqrt(3)).\n%   soccerball  Same as football, but for the American users.\n%   stripes     Alternating striped pattern.\n%   vortices    Two antipodal vortices taken from  Nair, Cote, and \n%               Staniforth (1999).\n%   :)          A function to make you happy\n%\n%   Gallery functions are subject to change in future releases of Chebfun.\n%\n% See also CHEB.GALLERY, CHEB.GALLERYTRIG, CHEB.GALLERY2, CHEB.GALLERY3, CHEB.GALLERYDISK.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% If the user did not supply an input, return a function chosen at random\n% from the gallery.\nif ( nargin == 0 )\n    names = {'football','jet','soccerball','deathstar', 'vortices'...\n        'gaussian','reprodkern','geomag','peaks','neamtu','randn',...\n        'moire','stripes',':)'};\n    name = names{randi(length(names))};\nend\n\ntype=1;                  % Default plotting type\naddEarthPlot = 0;        % Flag on whether or not to plot the earth (1=yes)\nviewAngle = [-37.5 30];  % Default viewing angle\nclrmap = parula(64);     % Default colormap\nclraxis = [];            % Color axis for the colormap; empty means use default\n\n% The main switch statement.\nswitch lower(name)    \n    % The classic football (or soccerball) pattern\n    case {'football','soccerball'}\n        f = spherefun.sphharm(6,0) + sqrt(14/11)*spherefun.sphharm(6,5);\n        fa = f;\n        cntrlvl = -[0.25 0.25];\n        type = 3;\n        \n    % A function resembling the surface of the Death Star\n    case 'deathstar'\n        fa = @(x,y,z) -(exp(-30*((y+sqrt(3)/2).^2 + x.^2 + (z-1/2).^2)) + exp(-100*z.^2));\n        f = spherefun(fa);\n        type = 1;\n        clrmap = flipud(jet);\n        viewAngle = [-35 8];\n        \n    % Two diametrically oposed vortices taken from\n    % R. D. Nair, J. Cote, A. Staniforth, Cascade interpolation for \n    % semi-Lagrangian advection over the sphere, Quart. J. Roy. Meteor. \n    % Soc. 125 (1999) 1445-1468\n    case 'vortices'\n        rho = @(th) 3*(sin(th)); w = @(th) (3*sqrt(2)/2*sech(rho(th)).^2.*tanh(rho(th)))./(rho(th)+eps);\n        fa = @(lam,th) -tanh(rho(th)/5.*sin(lam-20*w(th)));\n        f = spherefun(fa);\n        cntrlvl = [0 0];\n        type = 3;\n        clrmap = jet;\n        \n    % A simple Gaussian\n    case 'gaussian'\n        % Coordinates of Braunschweig, where Gauss was born;\n        coords = [10.516667 52.266667]/180*pi;\n        [xc,yc,zc] = sph2cart(coords(1),coords(2),1);\n        fa = @(x,y,z,xc,yc,zc) exp(-20*((x-xc).^2 + (y-yc).^2 + (z-zc).^2));\n        f = spherefun(@(x,y,z) fa(x,y,z,xc,yc,zc));\n        addEarthPlot = 1;\n        viewAngle = [80 15];\n        \n    % The reproducing kernel for all spherical harmonics of degree 20\n    case 'reprodkern'\n        [lam0,th0] = cart2sph(-1/sqrt(3),-1/sqrt(3),1/sqrt(3));\n        f = spherefun(@(lam,th) sphRPK(lam,th,lam0,pi/2-th0,20));\n        fa = f;\n        viewAngle = [-50 5];        \n        \n    % The IGRF-12 geomagnetic field\n    case 'geomag'\n        % Spherical harmonic coefficients for the IGRF-12 2015 Geomagnetic\n        % Model; see http://www.ngdc.noaa.gov/IAGA/vmod/igrf.html\n        c = [-29442.0, -1501.0, 4797.1, -2445.1, 3012.9, -2845.6, 1676.7,...\n            -641.9, 1350.7, -2352.3, -115.3, 1225.6, 244.9, 582.0, -538.4,...\n            907.6, 813.7, 283.3, 120.4, -188.7, -334.9, 180.9, 70.4, -329.5,...\n            -232.6, 360.1, 47.3, 192.4, 197.0, -140.9, -119.3, -157.5, 16.0,...\n            4.1, 100.2, 70.0, 67.7, -20.8, 72.7, 33.2, -129.9, 58.9, -28.9,...\n            -66.7, 13.2, 7.3, -70.9, 62.6, 81.6, -76.1, -54.1, -6.8, -19.5,...\n            51.8, 5.7, 15.0, 24.4, 9.4, 3.4, -2.8, -27.4, 6.8, -2.2, 24.2, 8.8,...\n            10.1, -16.9, -18.3, -3.2, 13.3, -20.6, -14.6, 13.4, 16.2, 11.7,...\n            5.7, -15.9, -9.1, -2.0, 2.1, 5.4, 8.8, -21.6, 3.1, 10.8, -3.3, 11.8,...\n            0.7, -6.8, -13.3, -6.9, -0.1, 7.8, 8.7, 1.0, -9.1, -4.0, -10.5, 8.4,...\n            -1.9, -6.3, 3.2, 0.1, -0.4, 0.5, 4.6, -0.5, 4.4, 1.8, -7.9, -0.7,...\n            -0.6, 2.1, -4.2, 2.4, -2.8, -1.8, -1.2, -3.6, -8.7, 3.1, -1.5, -0.1,...\n            -2.3, 2.0, 2.0, -0.7, -0.8, -1.1, 0.6, 0.8, -0.7, -0.2, 0.2, -2.2,...\n            1.7, -1.4, -0.2, -2.5, 0.4, -2.0, 3.5, -2.4, -1.9, -0.2, -1.1, 0.4,...\n            0.4, 1.2, 1.9, -0.8, -2.2, 0.9, 0.3, 0.1, 0.7, 0.5, -0.1, -0.3, 0.3,...\n            -0.4, 0.2, 0.2, -0.9, -0.9, -0.1, 0.0, 0.7, 0.0, -0.9, -0.9, 0.4,...\n            0.4, 0.5, 1.6, -0.5, -0.5, 1.0, -1.2, -0.2, -0.1, 0.8, 0.4, -0.1,...\n            -0.1, 0.3, 0.4, 0.1, 0.5, 0.5, -0.3, -0.4, -0.4, -0.3, -0.8];\n        % Compute the vertical component of the magnetic field\n        f = 0*spherefun.sphharm(0,0);\n        k = 1;\n        for l=1:13\n            f = f + -((l+1))*sqrt(4*pi/(2*l+1))*c(k)*spherefun.sphharm(l,0);\n            k = k + 1;\n            for m=1:l\n                f = f - (-1)^m*((l+1))*sqrt(4*pi/(2*l+1))*...\n                        (c(k)*spherefun.sphharm(l,m) + ...\n                        c(k+1)*spherefun.sphharm(l,-m));        \n                k = k + 2;\n            end\n        end\n        fa = f;\n        type = 3;\n        addEarthPlot = 1;\n        cntrlvl = -60000:5000:60000;\n        \n    % A \"peaks-like\" function for the sphere\n    case 'peaks'\n        fa = @(x,y,z) 8*(1-x).^2.*exp(-4*(x - 0.059).^2 - 2*(y + 0.337).^2 - 2*(z + 0.940).^2) - ...\n            30*(z/10 - x.^3 - y.^5) .* exp(-3*(x - 0.250).^2 - 2*(y - 0.433).^2 - 3*(z - 0.866).^2) + ...\n            (20*y - 8*z.^3) .* exp(-2*(x + 0.696).^2 - 3*(y + 0.123).^2 - 2*(z - 0.707).^2) + ...\n            (7*y - 10*x + 10*z.^3) .* exp(-3*(x - 0.296).^2 - 3*(y + 0.814).^2 - 3*(z + 0.5).^2);\n        f = spherefun(fa);\n        \n    % A function developed by Mike Neamtu of Vanderbilt University to test\n    % approximation schemes on the sphere.\n    case 'neamtu'\n        fa = @(x,y,z) 1 + x.^8 + exp(2*y.^3) + exp(2*z.^2) + 10*x.*y.*z;\n        f = spherefun(fa);\n        \n    % A Guassian random function on the sphere suggested by Dmitry Belyaev\n    % at Oxford.\n    case 'randn'\n        % Compute a random spherefun\n        f = randnfunsphere(0.079,'monochromatic');\n        fa = f;\n        type = 4;\n        clrmap = gray(2);\n        % Set the color axis so that the transition from white to black is\n        % exactly at the value zero.\n        minmax = minandmax2est(f);\n        clraxis = [-1 1]*max(abs(minmax));\n\n    % An interesting Moire pattern generated by two sources on the sphere\n    case 'moire'\n        % Centers of the beacons\n        boise = [-116.237651 43.613739]*pi/180;\n        oxford = [-1.257778 51.751944]*pi/180;\n        % ithaca = [-76.5 42.443333]*pi/180;\n        % stellenbosh = [18.86 -33.92]*pi/180;\n        [xb,yb,zb] = sph2cart(boise(1),boise(2),1);\n        [xo,yo,zo] = sph2cart(oxford(1),oxford(2),1);\n        % Pick the number of oscillations and make each of the \"waves\" \n        % vanish at the anti-podal points from their centers.\n        omega = besselroots(0,30); omega = omega(end)/2;\n        % Use a combination of the J0 bessel functions centered at Boise\n        % and Oxford to generate the Moire pattern.\n        fa = @(x,y,z,omega) 2 + besselj(0,omega*sqrt((x-xb).^2+(y-yb).^2+(z-zb).^2)) + ...\n            2 + besselj(0,omega*sqrt((x-xo).^2+(y-yo).^2+(z-zo).^2));\n        f = spherefun(@(x,y,z) fa(x,y,z,omega));\n        type = 1;\n        addEarthPlot = 1;\n        viewAngle = [32 8];\n        \n    % A zipper-like stripe pattern for the sphere    \n    case 'stripes'\n        fa = @(x,y,z) (1 + cos(10*pi*x)).*exp(-exp(-20*z)) + (1 - cos(10*pi*x)).*exp(-exp(20*z));\n        f = spherefun(fa);\n        type = 3;\n        cntrlvl = [1 1];\n        viewAngle = [-36 8];\n        clrmap = hot;\n        \n    % A zonal jet stream in the mid-latitudes of the northern hemisphere.\n    case 'jet'\n        fa = spherefun(@(lam,th) sin(th-(pi/4+0.01*cos(12*lam))).*exp(-300*(1-cos(th-(pi/4+0.01*cos(12*lam))))));\n        f = spherefun(fa);\n        type = 1;\n        clrmap = jet;\n        viewAngle = [32 8];\n        addEarthPlot = 1;\n        \n    % A smiley face emoticon\n    case ':)'\n        fa = @(x,y,z) exp(-20*(4*(x+cos(pi/6)*sin(pi/4)).^2 + 4*(y+sin(pi/6)*sin(pi/4)).^2 + (z-cos(pi/4)).^2)) + ...\n                      exp(-20*(4*(x+cos(-pi/6)*sin(pi/4)).^2 + 4*(y+sin(-pi/6)*sin(pi/4)).^2 + (z-cos(pi/4)).^2)) + ...\n                   9*exp(-100*((x + 1).^2 - x.*z + (z - 1/2).^2 - 1/10).^2);\n        f = spherefun(fa);\n        viewAngle = [-75 20];\n        \n    otherwise\n        error('CHEB:GALLERYSPHERE:unknown:unknownFunction', ...\n            'Unknown function.')\nend\n\n% Only return something if there is an output argument.\nif ( nargout > 0 )\n    varargout = {f, fa};\n    return;\nend\n\nptitle = [name ', rank = ' num2str(length(f))];\n% Determine the type of plot to make\nif type==1\n    % Plot the function with a grid\n    surf(f,'grid','k-')\n    axis off, title(ptitle)\nelseif type==2\n    contour(f)\n    axis off, title(ptitle)\nelseif type==3\n    plot(f), hold on\n    contour(f,cntrlvl,'k-'), hold off\n    axis off, title(ptitle)\nelse\n    plot(f)\n    axis off, title(ptitle)\nend\n\nview(viewAngle);\ncolormap(clrmap);\n\n% Set the color axis if required.\nif ( ~isempty(clraxis) )\n    caxis(clraxis);\nend\n\nif ( addEarthPlot )\n    hold on, spherefun.plotEarth('w-'), hold off\nend\n\nend\n\nfunction f = sphRPK(lam,th,lam0,th0,deg)\n%SPHRPK  Reproducing kernel for the spherical harmonics of a given degree.\n%   F = SPHRPK(LAM,TH,LAM0,TH0,DEG) is the reproducing kernel centered at\n%   (LAM0,TH0) for the space of spherical harmonics of degree DEG.\n\nt = cos(lam).*sin(th).*cos(lam0).*sin(th0) + sin(lam).*sin(th).*sin(lam0).*sin(th0) + cos(th).*cos(th0);\npl = legpoly(0:deg,[-1,1]);\n[m,n] = size(t);\nt = t(:);\nc = ones(length(t),1)*((2*(0:deg)+1)/4/pi);\nf = reshape(sum(c.*pl(t),2),m,n);\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/+cheb/gallerysphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5689707347039484}}
{"text": "function res = difonzo(Y,x,z,ta,sc,type,f)\n% PURPOSE: Multivariate temporal disaggregation with transversal constraint\n% ----------------------------------------------------------------------------------\n% SYNTAX: res = difonzo(Y,x,z,ta,sc,type,f);\n% ----------------------------------------------------------------------------------\n% OUTPUT: res: a structure\n%         res.meth  = 'Multivariate Di Fonzo';\n%         res.N     = Number of low frequency data\n%         res.n     = Number of high frequency data\n%         res.pred  = Number of extrapolations\n%         res.ta    = Type of disaggregation\n%         res.sc     = Frequency conversion\n%         res.type  = Model for high frequency innovations\n%         res.beta  = Model parameters \n%         res.y     = High frequency estimate\n%         res.d_y   = High frequency estimate: std. deviation\n%         res.z     = High frequency constraint\n%         res.et    = Elapsed time\n% ----------------------------------------------------------------------------------\n% INPUT: Y: NxM  ---> M series of low frequency data with N observations\n%        x: nxm  ---> m series of high frequency data with n observations, m>=M see (*)\n%        z: nzx1 ---> high frequency transversal constraint with nz obs.\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: model for the high frequency innvations\n%            type=0 ---> multivariate white noise\n%            type=1 ---> multivariate random walk\n% (*) Optional:\n%        f: 1xM ---> Set the number of high frequency indicators linked to\n%                    each low frequency variable. If f is explicitly included,\n%                    the high frequency indicators should be placed in \n%                    consecutive columns\n% ----------------------------------------------------------------------------------\n% NOTE: Extrapolation is automatically performed when n>sN. \n%       If n=nz>sN restricted extrapolation is applied.\n%       Finally, if n>nz>sN extrapolation is perfomed in constrained\n%       form in the first nz-sN observatons and in free form in \n%       the last n-nz observations.\n% ----------------------------------------------------------------------------------\n% LIBRARY: aggreg, dif, vec, desvec\n% ----------------------------------------------------------------------------------\n% SEE ALSO: denton, rossi, mtd_print, mtd_plot\n% ----------------------------------------------------------------------------------\n% REFERENCE: Di Fonzo, T.(1990)\"The estimation of M disaggregate time \n% series when contemporaneous and temporal aggregates are known\", Review \n% of Economics and Statistics, vol. 72, n. 1, p. 178-182.\n\n% written by:\n%  Enrique M. Quilis\n%  Macroeconomic Research Department\n%  Ministry of Economy and Competitiveness\n%  <enrique.quilis@mineco.es>\n\n% Version 3.0 [August 2006]\n\n% ----------------------------------------------------------------------------------\n\nt0 = clock;\n\n%--------------------------------------------------------\n%       Preliminary checking\n\n[N,M] = size(Y);\n[n,m] = size(x);\n[nz,mz] = size(z);\n\nif ((M > m) | (n < sc*N) | (mz ~= 1) | (nz > n) | (nz < sc*N))\n   error (' *** INCORRECT DIMENSIONS *** ');\nelse\n   % Number of extrapolations\n   h1 = n - nz;\n   h2 = n - sc*N;\n   clear nz mz;\nend\n\n%--------------------------------------------------------\n%       Checking of \"ta\"\n\nif (ta < 1) | (ta > 4)\n    error (' *** INCORRECT TA OPTION *** ');\nend\n\n%--------------------------------------------------------\n%       Checking of \"sc\"\n\nif (sc ~= 3) & (sc ~= 4) & (sc ~= 12)\n    error (' *** INCORRECT FREQUENCY CONVERSION (sc) *** ');\nend\n\n%--------------------------------------------------------\n%       Checking of \"type\"\n\nif (type < 0) | (type > 1)\n    error (' *** INCORRECT TYPE OPTION *** ');\nend\n\n%--------------------------------------------------------\n%       Checking (and definition) of vector f \n\nif (nargin == 6)\n    f = ones(1,M);\nend\n\nif ( (f < 1) | (sum(f) ~= m) | (length(f) ~= M))\n   error (' *** IMPROPER ASSIGNMENT OF INDICATORS IN f VECTOR *** ');\nend\n\n%--------------------------------------------------------\n%  **** CONSTRAINT MATRICES ***\n%--------------------------------------------------------\n% Required:\n%              H1 ---> transversal\n%              H2 ---> longitudinal\n%\n%---------------------------------------------------------------\n%       Generate H1: (n-h1) x nM\n\nH1 = kron(ones(1,M),[eye(n-h1) zeros(n-h1,h1)]);\n\n%---------------------------------------------------------------\n%       Generate H2: NM x nM.\n%\n% Generation of aggregation matrix C\n\nC = aggreg(ta,N,sc);\nC = [C zeros(N,h2)];\n\nH2 = kron(eye(M),C);\n\n%---------------------------------------------------------------\n%       Generate H: (n-h1+NM) x nM.\n%\n%       H = [ H1\n%             H2 ]\n\nH = [H1\n   H2];\n\n%--------------------------------------------------------\n%  **** PREPARING DATA MATRICES ***\n%--------------------------------------------------------\n% Required:\n%               x_diag\n%               Y_big,  Y_e\n%               X_diag, X_e\n\n%--------------------------------------------------------\n%       Generate x_diag: nM x M+m\n%\n% It is a diagonal matrix formed by the high frequency\n% indicators, including a vector of ones for the intercept\n%\n%       x_diag = [ x1 0  0  ... 0\n%                  0  x2 0  ... 0\n%                  0  0  x3 ... 0\n%                  ..............\n%                  0  0  0  ... xM ]\n%\n% It is made by means of a recursion.\n\nac(1)=f(1);                             % Initialization of the recursion\nx_diag = [ones(n,1) x(:,1:ac(1))];\n\nj=2;\nwhile (j <= M)\n   xaux = [ones(n,1) x(:,ac(j-1)+1:ac(j-1)+f(j))];\n   [a2,b2] = size(xaux);\n   [a1,b1] = size(x_diag);\n   x_diag = [ x_diag         zeros(a1,b2) \n              zeros(a2,b1)   xaux ];\n   ac(j) = ac(j-1) + f(j);\n   j = j + 1;\nend\nclear xaux;\n\n%--------------------------------------------------------\n%       Generate X_diag: NM x M+m\n%\n% Low frequency analog of x_diag. It is the result of\n% applying the temporal aggregator H2 to x_diag.\n\nX_diag = H2 * x_diag;\n\n%--------------------------------------------------------\n%       Generate X_e: (n-h1+NM) x M+m\n%\n%\n% It is the result of applying the complete aggregator H\n% (temporal as well as transversal). \n% Lower part of X_e is X_diag.\n\nX_e = H * x_diag;\n\n%--------------------------------------------------------\n%       Generate Y_big: NM x 1\n%\n% It is column vector containing all the observations on the\n% low frequency series according to: Y_big = [Y1 Y2 ... YM]'\n% Formally: Y_big = vec(Y)\n\nY_big = vec(Y);\n\n%--------------------------------------------------------\n%       Generate Y_e: (n-h1+NM) x 1\n%\n% It is column vector containing the transversal constraint\n% and all the observations on the low frequency series\n% according to: Y_e = [ z Y1 Y2 ... YM]' = [z Y_big]'\n\nY_e = [ z\n      Y_big];\n\n%--------------------------------------------------------\n%  **** PRELIMINARY ESTIMATION OF SIGMA ***\n%--------------------------------------------------------\n% The method of di Fonzo requires the previous estimation of VCV\n% matrix SIGMA for the (implied) low frequency model. This\n% preliminary estimation is performed by means of estimating, equation \n% by equation, the model. Formally, this is equivalent to estimate an \n% unrelated SURE model. Computationally, this is also the applied procedure.\n\nBETA = (X_diag' * X_diag) \\ (X_diag' * Y_big); % OLS estimator\nU_big = Y_big - X_diag * BETA;                 % Residuals in vec format\n\n% Residuals (columnwise) U: NxM\n\nU = desvec(U_big,M);\n\n% Preliminary estimation of SIGMA\n\nSIGMA = cov(U,1);\n\n%--------------------------------------------------------\n%  **** APPLYING DI FONZO PROCEDURE ***\n%--------------------------------------------------------\n\n%--------------------------------------------------------\n%       High frequency VCV matrix v: nM x nM\n\nswitch type\ncase 0 % White noise\n   v = kron(SIGMA,eye(n));\ncase 1 % Random walk, with U(0)=0\n   D = dif(1,n);\n   DDi = inv(D'*D);\n   v = kron(SIGMA,DDi);\nend;\n\n%--------------------------------------------------------\n%       Low frequency VCV matrix V: (n-h1+NM) x (n-h1+NM)\n%       and its generalized inverse \n\nV = H * v * H';\nVi = pinv(V);      % Moore-Penrose generalized inverse \n\n%--------------------------------------------------------\n%       Generation of distribution filter L: nM x (n-h1+NM)\n\nL = v * H' * Vi;\n\n%--------------------------------------------------------\n%\t     GLS estimation of beta in a SURE context\n\nbeta = (X_e' * Vi * X_e) \\ (X_e' * Vi * Y_e);\n\nU_e = Y_e - X_e * beta;\n\n%--------------------------------------------------------\n%       Estimation of high frequency series\n\ny_big = x_diag * beta + L * U_e;\n\n% Series y columnwise y: nxM\n\ny = desvec(y_big,M);\n\n%--------------------------------------------------------\n%       VCV matrix of estimations y: nM x nM\n\nsigma_y = (eye(n*M) - L*H)*v + ...\n   (x_diag - L*X_e)*inv(X_e'*Vi*X_e)*(x_diag - L*X_e)';\n\n% Vector format of std. dev.\n\nd_y_big = sqrt(diag(sigma_y));\n\n% Std. dev. series in column format dt_y: n x M\n\nd_y = desvec(d_y_big,M);\n\n% -----------------------------------------------------------------------\n% Loading the structure\n% -----------------------------------------------------------------------\n% Basic parameters \n\nres.meth = 'Multivariate Di Fonzo';\nres.N = N;\nres.n = n;\nres.pred = h2;\nres.ta= ta;\nres.sc = sc;\nres.type = type;\n\n% -----------------------------------------------------------------------\n% Parameters\n\nres.beta=beta;\n\n% -----------------------------------------------------------------------\n% Series\n\nres.y   = y;\nres.d_y = d_y;\nres.z   = z;\n\n% -----------------------------------------------------------------------\n% Elapsed time\n\nres.et        = etime(clock,t0);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39770-temporal-disaggregation-library/difonzo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5688936425393608}}
{"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 y = psabr_4_2(a, b, r, n, f, k, t,m, mu, nu, l, u)\n% sabr prices using an admissible region kl <= k <= ku where sabr is used\n% for 0 <= k <= kl    we use a put pricing function \n%           f(x) = x^mu exp(a + bx + cx^2)\n% for ku < k < +infty we use a call pricing function \n%           f(x) = x^(-nu) exp(a + bx^(-1) + cx(-2)\n% a big range (small kl and big ku) guarantee that the prices are in line\n% with the observed calls and puts\n%\n% this is the preferred version of the density for computations\n%\n\neps = 1e-004;                              % .1 bp                           \n\ns = @(x) psabr(a, b, r, n, f, x, t);\nindex = find(s(k)>0,1,'first');\n\nif (isempty(index) || index ==1)\n   kl = l *f;\nelse  \n    kl = max(l * f,k(index)+(f-k(index))/m);% lower strike level  \nend\ns1 = s(kl-eps);                          % for calc of derivatives\ns2 = s(kl);                              % for calc of derivatives\ns3 = s(kl+eps);                          % for calc of derivatives\n\nV1 = log(s2);                            % log density\n\nU2 = (s3-s1)/(2*eps);                    % derivative of density\nV2 = U2/s2;                              % derivative of log density\n\nU3 = (s3-2*s2+s1)/eps^2;                 % second derivative of density\nV3 = U3/s2 - V2^2;                       % second derivative of log density\n\n% fix mu and solve \n%       V1 = mu log kl + a + b kl + c kl^2\n%       V2 = mu / kl + b + 2c kl\n%       V3 = - mu / kl^2 + 2c\n\n%mu = 1.5;                               % controls the left tails\ncl = .5*(V3+mu/kl^2); \nbl = V2-mu/kl - 2*cl*kl; \nal = V1 - mu * log(kl) - bl*kl - cl*kl^2;\n\n% upper strike level (the bigger the strike level the better fit the call\n% prices to Hagan formula!)\nku = u * f;                                \ns = @(x) psabr(a, b, r, n, f, x, t);        % sabr price (1) for calls\ns1 = s(ku-eps);                             % for calc of derivatives\ns2 = s(ku);                                 % for calc of derivatives\ns3 = s(ku+eps);                             % for calc of derivatives\n\nV1 = log(s2);                               % log call price\n\nU2 = (s3-s1)/(2*eps);                       % derivative of  density\nV2 = U2/s2;                                 % derivative of log density                                   \n\nU3 = (s3-2*s2+s1)/eps^2;                    % second derivative of density\nV3 = U3/s2 - (U2/s2)^2;                     % second derivative of density\n\n% fix nu and solve\n%       V1 = -nu log ku + a + b/ku + c/ku^2\n%       V2 = -nu / ku - b / ku^2 - 2c/ku^3    \n%       V3 = nu / ku^2 + 2 b / ku^3 - 6 c / ku^4\n\ncu = (-1.5*nu / ku + .5*V3 * ku - V2)*ku^3/5;  \nbu = -ku^2*(V2 + nu/ku +2*cu/ku^3); \nau = V1 + nu * log(ku) - bu / ku - cu / ku^2; \n\n    yl = real(k(k<kl).^mu .* exp(al + bl .* k(k<kl) + cl * k(k<kl).^2));\n    ym = real(psabr(a,b,r,n,f,k((kl<=k)&(k<=ku)),t));                \n    yu = real(k(k>ku).^(-nu) .* exp(au+bu./k(k>ku)+cu./k(k>ku).^2));  \n    \n\ny = [yl ym yu];                            % output\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/38322-the-sabr-model-densities-and-mc/Densities_Prices_MC/psabr_4_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5688936343469954}}
{"text": "function [mg] = slug2mg(slug)\n% Convert units of mass from slugs to milligrams. \n% Chad A. Greene 2012\nmg = slug*14.5939*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/slug2mg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5688936315271673}}
{"text": "% Get vertex coordinates for the patch type 'P'\n% [C, N, S, W, E] = HealpixGetPatchVertexCoordsP(n, i, j, INFO)\n%\n% Parameters\n% n : grid resolution\n% i : ring index\n% j : intra-ring index\n% INFO : intermediate information (output of HealpixSelectPatchClass())\n% C : intra-patch coordinates\n% N : coordinates for north vertex\n% S : coordinates for south vertex\n% W : coordinates for west vertex\n% E : coordinates for east vertex\n\nfunction [C, N, S, W, E] = HealpixGetPatchVertexCoordsP(n, i, j, INFO)\n\n% gradient of the border\ngrad = INFO.polar_part;\n\ndecimal_i = INFO.decimal_i_n;\nint_i = INFO.int_i_n;\n\nint_j = fix(j - grad * decimal_i);\ndecimal_j = j - int_j;\nif int_j == 0\n    int_j = 4 * int_i;\nend\n\nif decimal_j > (grad + 1) * decimal_i\n    north_i = int_i - 1;\n    south_i = int_i + 1;\n    north_int_j = mod(int_j - grad - 1, 4 * north_i) + 1;\n    south_int_j = mod(int_j + (grad + 1) - 1, 4 * south_i) + 1;\n    east_int_j = mod(int_j + 1 - 1, 4 * int_i) + 1;\n    \n    N = [north_i, north_int_j];\n    S = [south_i, south_int_j];\n    W = [int_i  , int_j];\n    E = [int_i  , east_int_j];\n\n    offset_j = (grad + 0.5) * decimal_i;\n    C = [decimal_i, decimal_j - offset_j - 0.5];\nelse\n    curnt_i = int_i + 1;\n    south_i = int_i + 2;\n    if south_i > n\n        south_i = n;\n    end\n    west_int_j = mod(int_j + grad - 1, 4 * curnt_i) + 1;\n    east_int_j = mod(int_j + grad + 1 - 1, 4 * curnt_i) + 1;\n    south_int_j = mod(west_int_j + (grad + 1) - 1, 4 * south_i) + 1;\n    \n    N = [int_i    , int_j];\n    S = [int_i + 2, south_int_j];\n    W = [int_i + 1, west_int_j];\n    E = [int_i + 1, east_int_j];\n\n    offset_j = (grad + 0.5) * (1 - decimal_i);\n    C = [decimal_i - 1, decimal_j + offset_j - (grad + 0.5)];\nend\n\nif INFO.is_south_pole\n    TMP = N;\n    N = S;\n    S = TMP;\n    N(1) = 4 * n - N(1);\n    S(1) = 4 * n - S(1);\n    W(1) = 4 * n - W(1);\n    E(1) = 4 * n - E(1);\n    C(1) = -C(1);\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/extern/HealpixLib/HealpixGetPatchVertexCoordsP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.6757646140788308, "lm_q1q2_score": 0.5688759863182784}}
{"text": "function [w,run] = train_mis(x,w,lambda)\n% Modified iterative scaling\n% x is premultiplied by y\n\n% Written by Thomas P Minka\n\nif nargin < 3\n  lambda = 0;\nend\nif lambda > 0\n  error('must have lambda = 0')\nend\n[d,n] = size(x);\nflops(0);\nstep = 1/max(sum(abs(x),1));\n\ni1 = (x > 0);\nx1 = abs(x).*i1;\nx2 = abs(x).*(1-i1);\nflops(flops + 3*d*n);\nif nargout > 1\n  run.w = [];\n  run.flops = [];\n  run.e = [];\nend\nfor iter = 1:10000\n  old_w = w;\n  % s1 = 1-sigma\n  s1 = 1./(1+exp(w'*x));\n  delta = (x1*s1')./(x2*s1');\n  w = w + step*0.5*log(delta);\n  if iter == 1\n    % same for every iteration\n    % use spmul because x1,x2 have structural zeros\n    fl = flops_mul(w',x)+n*(flops_exp+2) + ...\n\tflops_spmul(x1,s1')+flops_spmul(x2,s1')+d + ...\n\td*(flops_exp+2);\n  end\n  flops(flops + fl);\n  \n  if nargout > 1 & rem(iter,100) == 1\n    run.w(:,end+1) = w;\n    run.flops(end+1) = flops;\n    run.e(end+1) = logProb(x,w) -0.5*lambda*w'*w;\n  end\n  if rem(iter,1000) == 0\n    fprintf('MIS iter %d\\n', iter)\n  end\n  \n  if max(abs(w - old_w)) < 1e-6\n    break\n  end\nend\nif iter == 10000\n  warning('not enough iters')\nend\nif nargout > 1\n  figure(2)\n  plot(run.e)\nend\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/train_mis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5688759699608972}}
{"text": "function error=matlab2tsai_error(X,camera,uv_d,xy_matlab_N)\n\n% JMM Montiel. Sept 2005\n%\n% Error between the Tsia undistortion model and the\n%   Swaminathan model\n% Input \n%   k1      -Swaminathan distortion model\n%   camera  -Camera parameters. camera.k1 is irrelevant\n%   uv_d    -Distorted point coordinates\n%   uv_u    -Undistorted coordinates according to Tsai model\n\nk1=X(1);\nk2=X(2);\nf=X(3);\ncx = X(4);\ncy = X(5);\n\ncamera.f = f;\ncamera.Cx = cx;\ncamera.Cy = cy;\ncamera.k1 = k1;\ncamera.k2 = k2;\n\nxy_tsai_N = undistort_and_normalize_fm( uv_d, camera );\nif(1) \n    cla;\n    plot(xy_matlab_N(1,:),xy_matlab_N(2,:),'+r');\n    hold on\n    plot(xy_tsai_N(1,:),xy_tsai_N(2,:),'+g');\n    xlabel('red, matlab.    green Tsai with 1 radial distorion parameter')\nend\nerror=[xy_tsai_N(1,:)-xy_matlab_N(1,:);xy_tsai_N(2,:)-xy_matlab_N(2,:)];", "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/matlab2tsai_error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5688759617822066}}
{"text": "function [Y,W,SetupStruc] = Process_ICA_Sawada(s,Transfer,SetupStruc)\nK = SetupStruc.ICA_Sawada.K;\nhop = SetupStruc.ICA_Sawada.hop;\nwin = hanning(K,'periodic');\nwin = win/sqrt(sum(win(1:hop:K).^2));\nSetupStruc.ICA_Sawada.win = win;  % Preserve 'win' in 'SetupStruc'\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nN = size(s,2);\nfor i = 1:N\n    X(:,:,i) = fft(enframe(s(:,i),win,hop)');\nend\nframe_N = size(X,2);\nK_m = K/2+1;\nNum = size(Transfer,3);\nY = zeros((frame_N-1)*hop+K,Num);\nY_f = zeros(size(X,1),size(X,2),Num);\nY_P = zeros(frame_N,Num,K_m);\n%%%%%%%%%%%%%%%%%%%%%%%%%% Obtain processing matrix 'W'\ntheta = 10^-4;\nW = zeros(Num,N,K_m);\nA = zeros(1001,K/2)-1; %%%% Show the decrease of non-linear correlation, ICA max iterations 1000\nfor i = 2:K_m\n    X_f = permute(X(i,:,:),[3 2 1]);\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %%% PCA and ICA processing\n    [E,D] = PCA(X_f,1,Num);\n    V = sqrt(D)\\E';\n    X_f = V*X_f;\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%     Steer = permute(Transfer(i,:,:),[2 3 1]);\n%     Ori = V*Steer;\n%     if rcond(Ori)<theta\n%         Ori = Ori+eye(Num)*min(diag(Ori));\n%     end\n%     [Y_,W_ICA,A] = FDICA(X_f,inv(Ori),A,i);  %%% 'A', 'i' record the decrease for observation    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    [Y_,W_ICA,A] = FDICA(X_f,eye(Num),A,i);  %%% 'A', 'i' record the decrease for observation      \n    W(:,:,i) = W_ICA*V;\n    Y_P(:,:,i) = Y_.';\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Process the ambiguity of permutation and amplitude\nP = Permu_Sawada(W,Y_P,SetupStruc,'all');  %%%% Options: 'DOA','cor', 'all'\nfor i = 2:K_m\n    W(:,:,i) = P(:,:,i)*W(:,:,i);\n    Y_ = permute(Y_P(:,:,i),[2 1 3]);\n    Y_ = P(:,:,i)*Y_;\n    Y_f(i,:,:) = Y_.';\n    if(i~=K_m)\n        Y_f(K+2-i,:,:) = Y_';\n    end\nend  \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Recover signals\nif(K/hop==2)\n    win = ones(K,1);\nend\nfor i = 1:Num\n    Y(:,i) = overlapadd(real(ifft(Y_f(:,:,i)))',win,hop);\nend\nreturn;", "meta": {"author": "KyleZhang1118", "repo": "Voice-Separation-and-Enhancement", "sha": "77d16c120356dbbca3ee768d293df5d743d343ad", "save_path": "github-repos/MATLAB/KyleZhang1118-Voice-Separation-and-Enhancement", "path": "github-repos/MATLAB/KyleZhang1118-Voice-Separation-and-Enhancement/Voice-Separation-and-Enhancement-77d16c120356dbbca3ee768d293df5d743d343ad/Process_ICA_Sawada.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5688759564188857}}
{"text": "function recall = Recall(SEG, GT)  \n    % SEG, GT are the binary segmentation and ground truth areas, respectively.  \n    % recall  \n    recall = double(sum(uint8(SEG(:) & GT(:)))) / double(sum(uint8(GT(:))));  \nend  ", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/benchmarks/Recall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5688054976824307}}
{"text": "function r8vec_index_delete_dupes_test ( )\n\n%*****************************************************************************80\n%\n%% R8VEC_INDEX_DELETE_DUPES_TEST tests R8VEC_INDEX_DELETE_DUPES.\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_max = 25;\n  n = 0;\n  x = [];\n  indx = [];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8VEC_INDEX_DELETE_DUPES_TEST\\n' );\n  fprintf ( 1, '  R8VEC_INDEX_DELETE_DUPES deletes duplicates.\\n' );\n  fprintf ( 1, '\\n' );\n\n  xval = 8.0;\n  [ n, x, indx ] = r8vec_index_insert ( n, x, indx, xval );\n\n  xval = 7.0;\n  [ n, x, indx ] = r8vec_index_insert ( n, x, indx, xval );\n\n  seed = 123456789;\n\n  for i = 1 : 20\n    [ xval, seed ] = r8_uniform_ab ( 0.0, 20.0, seed );\n    xval = round ( xval );\n    fprintf ( 1, '  %f\\n', xval );\n    [ n, x, indx ] = r8vec_index_insert ( n, x, indx, xval );\n  end\n\n  xval = 7.0;\n  [ n, x, indx ] = r8vec_index_insert ( n, x, indx, xval );\n\n  xval = 8.0;\n  [ n, x, indx ] = r8vec_index_insert ( n, x, indx, xval );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Indexed list of entries:\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  I  INDX(I)  X(I)  X(INDX(I))\\n' );\n  fprintf ( 1, '\\n' );\n  for i = 1 : n\n    fprintf ( 1, '  %3d  %3d  %9f  %9f\\n', i, indx(i), x(i), x(indx(i)) );\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Call R8VEC_INDEX_DELETE_DUPES to delete duplicates:\\n' );\n\n  [ n, x, indx ] = r8vec_index_delete_dupes ( n, x, indx );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Indexed list of unique entries:\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  I  INDX(I)  X(I)\\n' );\n  fprintf ( 1, '\\n' );\n  for i = 1 : n\n    fprintf ( 1, '  %3d  %3d  %9f\\n', i, indx(i), x(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/r8lib/r8vec_index_delete_dupes_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.5688054889361759}}
{"text": "function plot_spreads(treedata,fig,lw,rel)\n\n% Plots the spreads as a polar plot with different height layers presented\n% with different colors. Inputs \"fig\" and \"lw\" define the figure number and\n% the line width. Input Rel = 1 specifies relative spreads, i.e. the\n% maximum spread is one, otherwise use the actual values.\n\nif nargin == 2\n    lw = 1;\n    rel = 1;\nelseif nargin == 3\n    rel = 1;\nend\n\nspreads = treedata.spreads;\nfigure(fig)\nn = size(spreads,1);\ncol = zeros(n,3);\ncol(:,1) = (0:1/n:(n-1)/n)';\ncol(:,3) = (1:-1/n:1/n)';\nd = max(max(spreads));\nD = [spreads(1,end) spreads(1,:)];\nif rel\n    polarplot(D/d,'-','Color',col(1,:),'Linewidth',lw)\nelse\n    polarplot(D,'-','Color',col(1,:),'Linewidth',lw)\nend\nhold on\nfor i = 1:n\n    D = [spreads(i,end) spreads(i,:)];\n    if rel\n        polarplot(D/d,'-','Color',col(i,:),'Linewidth',lw)\n    else\n        polarplot(D,'-','Color',col(i,:),'Linewidth',lw)\n    end\nend\nhold off\nif rel\n    rlim([0 1])\nelse\n    rlim([0 d])\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/plotting/plot_spreads.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5688054866506375}}
{"text": "clear all; close all; clc\n\n\n%% folder setup\nisSaveFig = 1;\nisPlotFig = 1;\n\noutputDir = GetOutputDataDir;\n\n\nClusterIDs = [2,1]; % init; can overrride\nprct_const = 2; % init; can overrride\n\n\n\n%% init\n\nhfig = figure;\nInitializeAppData(hfig);\nResetDisplayParams(hfig);\n\nsetappdata(hfig,'isMotorseed',1);\n\n%%\nIM_scatter = cell(2,18); % L and R\n\nIM_maps = cell(5,18);\n% IM_Xonly = cell(n_reg,18);\n% IM_Yonly = cell(n_reg,18);\n% IM_XY = cell(n_reg,18);\n% IM_X = cell(n_reg,18);\n% IM_Y = cell(n_reg,18);\n\ncaseID = 1;\nswitch caseID\n    case 1\n        load(fullfile(outputDir,'4D_SM_betas.mat'));\n        M_reg_name = {'2x2motormaps'};\n        range_fish = GetFishRange;% init; can overrride\n    case 2\n        load(fullfile(outputDir,'4D_SM_stimrangePT_betas.mat'));\n        M_reg_name = {'2x2motormaps_PT'};\n        range_fish = 6:18;\n    case 3\n        load(fullfile(outputDir,'4D_SM_stimrangeOMR_betas.mat'));\n        M_reg_name = {'2x2motormaps_OMR'};\n        range_fish = 8:18;\n    case 4\n        load(fullfile(outputDir,'4D_SM_stimrangelooming_betas.mat'));\n        M_reg_name = {'2x2motormaps_looming'};\n        range_fish = [9:15,17:18];\n    case 5\n        load(fullfile(outputDir,'4D_SM_stimrangeDF_betas.mat'));\n        M_reg_name = {'2x2motormaps_DF'};\n        range_fish = [12:15,17:18];\nend\n%% run fish\nfor i_fish = range_fish\n    \n    cIX_all = LoadSingleFishDefault(i_fish,hfig,ClusterIDs,[],0);\n    \n    %% main loop for left/right motor\n    M_pass = cell(5,2);\n    \n    for i_lr = 1:2\n        %% scatter plot with 4D components\n        % loaded betas for this fish for the combo data (including both stim)\n        betas = Betas{i_lr,i_fish};\n        % set up plot dimensions\n        X = betas(:,1);%b3;%b1;\n        Y = betas(:,2);\n        %                 Y = sqrt(b2.^2+b3.^2);%b2;\n        Xname = 'motor res.';\n        Yname = 'motor avr.';\n        \n        numcell = length(X);\n        \n        A = X;\n        topN = round(prct_const/100*numcell); % top x% cutoff\n        [~,IX] = sort(A,'descend');\n        thresA = A(IX(topN));\n        \n        B = Y;\n        topN = round(prct_const/100*numcell);\n        [~,IX] = sort(B,'descend');\n        thresB = B(IX(topN));\n        \n        IX_passX = find(A>=thresA);\n        IX_passY = find(B>=thresB);\n        IX_passXonly = setdiff(IX_passX,IX_passY);\n        IX_passYonly = setdiff(IX_passY,IX_passX);%find(B>=thresB);%\n        IX_passXY = intersect(IX_passX,IX_passY);\n        IX_pass = union(IX_passX,IX_passY);\n        IX_fail = intersect(find(A<thresA),find(B<thresB));%find(A<thresA);\n        \n        % get min/max\n        x0 = min(X(IX_pass));\n        x1 = max(X(IX_pass));\n        y0 = min(Y(IX_pass));\n        y1 = max(Y(IX_pass));\n        \n        gIX_in = (1:length(X))';\n        \n        M_pass{1,i_lr} = IX_passX;\n        M_pass{2,i_lr} = IX_passY;\n        M_pass{3,i_lr} = IX_passXonly;\n        M_pass{4,i_lr} = IX_passYonly;\n        M_pass{5,i_lr} = IX_passXY;\n        %         PassX_2{i_lr} = IX_passX;\n        %         PassY_2{i_lr} = IX_passY;\n        %         PassXonly_2{i_lr} = IX_passXonly;\n        %         PassYonly_2{i_lr} = IX_passYonly;\n        %         PassXY_2{i_lr} = IX_passXY;\n        \n        %% scatter plot\n        clrX = [0.3,0.8,0];\n        clrY = [0.9,0.2,0.9];\n        clrXY = [0,0.3,0.9];\n        clr_fail = [0.5,0.5,0.5];\n        \n        h = figure('Position',[500,100,300,250]); hold on\n        scatter(X,Y,1,clr_fail,'filled')\n        \n        scatter(X(IX_passXonly),Y(IX_passXonly),1,clrX);%,'filled');\n        scatter(X(IX_passYonly),Y(IX_passYonly),1,clrY);%,'filled');\n        scatter(X(IX_passXY),Y(IX_passXY),1,clrXY);%[1,0.5,0.5]);%,'filled');\n        \n        plot([x0,x1],[thresB,thresB],'k--');\n        plot([thresA,thresA],[y0,y1],'k--');\n        \n        xlabel(Xname);ylabel(Yname);\n        axis equal\n        %         set(gca,'XTick',0:0.5:1,'YTick',-0.5:0.5:1);\n        axis tight\n        %% save bubble plot\n        IM_scatter{i_lr,i_fish} = print('-RGBImage');\n        close(h)\n        \n        \n    end\n    \n    %% component anat map\n    setappdata(hfig,'clrmap_name','hsv_old');\n    for i_map = 1:5\n        cIX12 = M_pass(i_map,:);\n        cIX = vertcat(cIX12{1},cIX12{2});\n        gIX = vertcat(ones(size(cIX12{1})),2*ones(size(cIX12{2})));\n        I = LoadCurrentFishForAnatPlot(hfig,cIX,gIX);\n        [h,~,im] = DrawCellsOnAnat(I);\n        close(h);\n        IM_maps{i_map,i_fish} = im;\n        \n        \n        %export code - added by Joe and Misha\n        cIX_abs = I.absIX(I.cIX); %is referencing through absIX correct?\n        M_xyz = I.CellXYZ(cIX_abs,:);\n        % Determine size from anat sizes, apparently yxz\n        siz_ = [size(I.anat_yx,1), size(I.anat_yx,2), size(I.anat_zx,1)];\n        func_map=zeros(siz_(1),siz_(2),siz_(3));\n        anat_map=zeros(siz_(1),siz_(2),siz_(3));\n        for i=1:size(M_xyz,1),func_map(M_xyz(i,1),M_xyz(i,2),M_xyz(i,3))=1;end\n        for i=1:size(I.CellXYZ,1),anat_map(I.CellXYZ(i,1),I.CellXYZ(i,2),I.CellXYZ(i,3))=1;end\n        eval(['save export_fig3_fish' num2str(i_fish) '_case' num2str(caseID) '_mapnum' num2str(i_map) ' func_map anat_map'])\n        %mapnums are above threshold for  X, Y, onlyX, onlyY, X and Y \n        \n    end\n    \nend\n\n\n%% save as tiff stack\nM_lr = {'-L','-R'};\n\nM_comp_names = {'passX','passY','passXonly','passYonly','passXY'};\nn_reg = 1;\nfor i_set = 1:n_reg\n    range_im = range_fish;%M_fishrange_im{i_set};\n    \n    for i_lr = 1:2\n        tiffdir = fullfile(outputDir,[M_reg_name{i_set},M_lr{i_lr},'_scatter_allfish.tiff']);\n        IM = IM_scatter(i_lr,range_im);\n        SaveImToTiffStack(IM,tiffdir);\n    end\n    \n    for i_map = 1:5\n        tiffdir = fullfile(outputDir,[M_reg_name{i_set},'_',M_comp_names{i_map},'_anat_allfish.tiff']);\n        IM = IM_maps(i_map,range_im);\n        SaveImToTiffStack(IM,tiffdir);\n    end\nend\n\n%% Average Plot\n% M_k_scale = {1,1.5,1};\n% M_k_contrast = {1.2,1.5,1.2};\n\nfor i_set = 1:n_reg\n    range_im = range_fish;%M_fishrange_im{i_set};%[1:3,5:7];%[1:3,5:18];\n    \n    for i_map = 1:5\n        %%\n        IM = IM_maps(i_map,range_im);%IM_2(i_lr,range_im);\n        \n        % adjust params for visualization\n        k_scale = 0.5;%1/1.5;%M_k_scale{i_set};\n        k_contrast = 1;%M_k_contrast{i_set};\n        \n        [h_anat,im_avr] = AverageAnatPlot(IM,k_contrast,k_scale);\n        \n        tiffdir = fullfile(outputDir,[M_reg_name{i_set},'_',M_comp_names{i_map},'_anat_avr.tiff']);\n        imwrite(im_avr, tiffdir, 'compression','none','writemode','overwrite');\n    end\nend\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/figure scripts/SensoryMotor/fig3_2x2motormap_from_scatterplot_setdiff_intersect_exportedit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5688054866506375}}
{"text": "classdef MOCMA < ALGORITHM\n% <multi> <real/integer>\n% Multi-objective covariance matrix adaptation evolution strategy\n\n%------------------------------- Reference --------------------------------\n% C. Igel, N. Hansen, and S. Roth, Covariance matrix adaptation for multi-\n% objective optimization, Evolutionary computation, 2007, 15(1): 1-28.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Generate the initial individuals in CMA-ES\n            Population = Problem.Initialization();\n            ptarget    = 1/5.5;\n            a          = struct('x',num2cell(Population.decs,2)','psucc',ptarget,'sigma',0.5,'pc',0,'C',eye(Problem.D),'Individual',num2cell(Population));\n\n            %% Optimization\n            while Algorithm.NotTerminated([a.Individual])\n                % Generate new individuals\n                for k = 1 : Problem.N\n                    a1(k)            = a(k);\n                    a1(k).x          = mvnrnd(a(k).x,a(k).sigma^2*a(k).C,1);\n                    a1(k).Individual = Problem.Evaluation(a1(k).x);\n                end\n\n                % Update the fitness of each individual\n                Q           = [a,a1];\n                Population  = [Q.Individual];\n                % Penalized fitness for handling box constraints\n                PopObj      = Population.objs + repmat(1e-6*sum((cat(1,Q.x)-Population.decs).^2,2),1,Problem.M);\n                % Calculate the fitness of each individual\n                FrontNo     = NDSort(PopObj,inf);\n                CrowdDis    = CrowdingDistance(PopObj,FrontNo);\n                [~,rank]    = sortrows([FrontNo;-CrowdDis]');\n                [~,fitness] = sort(rank);\n\n                % Update the CMA models\n                for k = 1 : Problem.N\n                    a(k)  = updateStepSize(a(k),fitness(Problem.N+k)<fitness(k),ptarget);\n                    a1(k) = updateStepSize(a1(k),fitness(Problem.N+k)<fitness(k),ptarget);\n                    a1(k) = updateCovariance(a1(k),(a1(k).x-a(k).x)/a(k).sigma);\n                end\n\n                % Individuals for next generation\n                Q = [a,a1];\n                a = Q(rank(1:Problem.N));\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/Algorithms/Multi-objective optimization/MO-CMA/MOCMA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.56875391661493}}
{"text": "% Create sample waypoint data for trajectory generation\n% NOTE: Modify this script with your own rigid body tree and \n%       trajectory reference points\n%       (We recommend saving a copy of this file)\n%\n% Copyright 2019 The MathWorks, Inc.\n\n%% Common parameters\n% Rigid Body Tree information\nload gen3\nload gen3positions\neeName = 'Gripper';\nnumJoints = numel(gen3.homeConfiguration);\nikInitGuess = gen3.homeConfiguration;\n\n% Maximum number of waypoints (for Simulink)\nmaxWaypoints = 20;\n\n% Positions (X Y Z)\nwaypoints = toolPositionHome' + ... \n            [0 0 0.2 ; -0.1 0.2 0.4 ; -0.2 0 0.1 ; -0.1 -0.2 0.4 ; 0 0 0.2]';\n         \n% Euler Angles (Z Y X) relative to the home orientation       \norientations = [0     0    0;\n                pi/8  0    0; \n                0    pi/2  0;\n               -pi/8  0    0;\n                0     0    0]';   \n            \n% Array of waypoint times\nwaypointTimes = 0:4:16;\n\n% Trajectory sample time\nts = 0.2;\ntrajTimes = 0:ts:waypointTimes(end);\n\n%% Additional parameters\n\n% Boundary conditions (for polynomial trajectories)\n% Velocity (cubic and quintic)\nwaypointVels = 0.1 *[ 0  1  0;\n                     -1  0  0;\n                      0 -1  0;\n                      1  0  0;\n                      0  1  0]';\n\n% Acceleration (quintic only)\nwaypointAccels = zeros(size(waypointVels));\n\n% Acceleration times (trapezoidal only)\nwaypointAccelTimes = diff(waypointTimes)/4;\n", "meta": {"author": "mathworks-robotics", "repo": "trajectory-planning-robot-manipulators", "sha": "e7ee8775b5ace44b5da5455b6aee9c4d8cbf0b4e", "save_path": "github-repos/MATLAB/mathworks-robotics-trajectory-planning-robot-manipulators", "path": "github-repos/MATLAB/mathworks-robotics-trajectory-planning-robot-manipulators/trajectory-planning-robot-manipulators-e7ee8775b5ace44b5da5455b6aee9c4d8cbf0b4e/utilities/createWaypointData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5687539162835002}}
{"text": "classdef SubPixel_Conv < dagnn.ElementWise\n%%% Sub-pixel convolution layer %%%\n%\n% Performs sub-pixel convolution or pixel shuffle as specified in [1].\n% From an input of size [H, W, C, N] stored in inputs{1}, this layer\n% produces the output of size [scale*H, scale*W, C/(scale*scale), N] in outputs{1}.\n% *Back-propagation (backward function) implemented*\n%\n% [1] Wenzhe Shi et al. \"Real-Time Single Image and Video Super-Resolution\n% Using an Efficient Sub-Pixel Convolutional Neural Network\", CVPR, 2016.\n\n  properties\n    scale = 2;\n  end\n\n  methods\n    function outputs = forward(obj, inputs, params)\n        input = inputs{1};\n        output=gpuArray(zeros(size(input, 1)*obj.scale, size(input, 2)*obj.scale, size(input, 3)/obj.scale/obj.scale, size(input, 4)));\n        for channel = 1:size(input, 3)\n            ch = floor((channel-1)/obj.scale/obj.scale)+1;\n            c = mod(channel,obj.scale*obj.scale);\n            if c == 0, c = obj.scale*obj.scale; end\n            q = floor((c-1)/obj.scale)+1;\n            r = mod(c, obj.scale);\n            if r == 0, r = obj.scale; end          \n            output(q:obj.scale:end, r:obj.scale:end, ch, :) = input(:, :, channel, :);\n        end\n        outputs{1} = gpuArray(single(output));\n    end\n\n    function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)\n        output = derOutputs{1};\n        input = gpuArray(zeros(size(output, 1)/obj.scale, size(output, 2)/obj.scale, size(output, 3)*obj.scale*obj.scale, size(output, 4)));\n        for channel = 1:size(input, 3)\n            ch = floor((channel-1)/obj.scale/obj.scale)+1;\n            c = mod(channel,obj.scale*obj.scale);\n            if c == 0, c = obj.scale*obj.scale; end\n            q = floor((c-1)/obj.scale)+1;\n            r = mod(c, obj.scale);\n            if r == 0, r = obj.scale; end            \n            input(:, :, channel, :) = output(q:obj.scale:end, r:obj.scale:end, ch, :);\n        end\n      derInputs{1} = gpuArray(single(input));\n      derParams = {} ;\n    end\n\n    function obj = SubPixel_Conv(varargin)\n      obj.load(varargin) ;\n      obj.scale = obj.scale;\n    end\n  end\nend\n", "meta": {"author": "sooyekim", "repo": "Deep-SR-ITM", "sha": "139ca3b8b236e599a4361dc0797a0ff0b3c67665", "save_path": "github-repos/MATLAB/sooyekim-Deep-SR-ITM", "path": "github-repos/MATLAB/sooyekim-Deep-SR-ITM/Deep-SR-ITM-139ca3b8b236e599a4361dc0797a0ff0b3c67665/+dagnn/SubPixel_Conv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5687539113923206}}
{"text": "% Evaluates hamming kNN classifier using 1 upto K nearest neighbors for prediction\n\nfunction [acc acc2] = eval_hammknn(data, W, K, nonlinearity)\n\nNtraining = data.Ntraining;\nXtraining = data.Xtraining;\nLtraining = double(data.Ltraining);\n\nNtest = data.Ntest;\nXtest = data.Xtest;\nLtest = double(data.Ltest);\n\nif (~iscell(W))\n  B1 = W * Xtraining;\n  B2 = W * Xtest;\nelse\n  resp1 = compute_NN_output(W, Xtraining, nonlinearity);\n  B1 = resp1{end};\n  resp2 = compute_NN_output(W, Xtest, nonlinearity);\n  B2 = resp2{end};\nend\n\nB1 = logical(single(B1 > 0));\nB1 = compactbit(B1);\n\nB2 = logical(single(B2 > 0));\nB2 = compactbit(B2);\n\n[nw1 n1] = size(B1);\n[nw2 n2] = size(B2);\nnb = nw1*8;\n\nif (nw1 ~= nw2)\n  error('nw1 ~= nw2\\n');\nend\n\nif ~exist('K', 'var')\n  K = 3;\nend\n\n% Assuming there are only 10 labels\n% TODO: change if you have more labels\nnlabels = 10;\n\n[ret ret2] = hammknn_mex(nlabels, B1, uint32(Ltraining), B2, uint32(Ltest), n1, nb, K);\n\nacc = double(ret) / Ntest;\nacc2 = double(ret2) / Ntraining;\n", "meta": {"author": "norouzi", "repo": "hdml", "sha": "78e01180fc2494db31f04a9f4653456a8bfb8ba0", "save_path": "github-repos/MATLAB/norouzi-hdml", "path": "github-repos/MATLAB/norouzi-hdml/hdml-78e01180fc2494db31f04a9f4653456a8bfb8ba0/utils/eval_hammknn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.568753910729461}}
{"text": "function [yd3] = l2yd3(l)\n% Convert volume from liters to cubic yards. \n% Chad Greene 2012\nyd3 = l*0.0013079506193;", "meta": {"author": "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/l2yd3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5687539058382814}}
{"text": "function [ml] = likelihood(hyp, inf, mean, cov, lik, input, target)\n% Calculates the negative log marginal likelihood. \n%\n%% Syntax\n%  ml = likelihood(hyp, inf, mean, cov, lik, input, target)\n%\n%% Description\n% Function for calculating the negative log marginal likelihood of given\n% hyperparameters, covariance function and data. If more sets of\n% hyperparameters are given it outputs a vector of calculated negative log\n% marginal likelihoods.\n%\n% Based on the work of C.E.Rasmussen. \n% \n% Input: \n% * hyp    ... the hyperparameter struct(s), row vector of structs\n% * inf    ... the function specifying the inference method \n% * mean   ... the prior mean function\n% * cov    ... the prior covariance function\n% * lik    ... the likelihood function\n% * input  ... the input part of the training data,  NxD matrix\n% * target ... the output part of the training data (ie. target), Nx1 vector\n%\n% Output:\n% * ml     ... the negative log marginal likelihood(s), vector\n%\n% See Also:\n% gpx, minimize, covFunction, gp_initial\n%\n% Examples:\n% gp_initial.m\n%%\n\nif nargin < 7 % input validation\n  error('Too few parameters are given.'); % \nend\n\nml=zeros(size(hyp)); % allocate\n\nfor i = 1 : size(hyp,2)\n  try\n    \n    mlt = gp(hyp(i), inf, mean, cov, lik, input, target);\n  catch\n    mlt = +Inf;\n  end\n\n  % stability\n  if (~isfinite(mlt) || isnan(mlt) || ~isreal(mlt))\n    mlt = +Inf;\n  end\n  ml(i) = mlt;\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/likelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5687538999528127}}
{"text": "function bow2 = mydatesow_aux (epoch2)\n    % beginning of day:\n    epoch2_vec = mydatevec(epoch2);\n    bod2_vec = epoch2_vec;  bod2_vec(:,4:6) = 0;\n    bod2 = mydatenum(bod2_vec);\n\n    % beginning of week:\n    %weekday(datenum(bod2_vec))-1  % DEBUG\n    bow2 = bod2 - (weekday(datenum(bod2_vec))-1)*24*3600;\nend\n\n%!test\n%! % mydatesow_aux()\n%! test('mydatesow')\n%! test('mydatesowi')\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/31065-mydate/mydate/mydate/mydatesow_aux.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5686839969170525}}
{"text": "function [Y, X] = svmlread(fname)\n% SVMLREAD - Read a data file generated by SVM light\n% \n%   Y = SVMLREAD(FNAME)\n%   FNAME gives the name of an output file generated by SVM light. It\n%   may contain predicted labels, coefficients alpha, or an input\n%   (example) file with class values and features. From this file the\n%   data in the first column (class labels or alphas) is extrated and\n%   returned in Y.\n%   [Y, X] = SVMLREAD(FNAME), where FNAME is the name of an input file\n%   with class values and features, returns both the vector of class\n%   labels Y and the matrix of examples X. Each line of X corresponds to\n%   a line in the file.\n%   Attention: this may take a while...\n%\n%   See also SVML, SVM_LEARN, SVM_CLASSIFY, SVMLOPT, SVMLWRITE\n%\n\n% \n% Copyright (c) by Anton Schwaighofer (2001)\n% $Revision: 1.6 $ $Date: 2002/02/19 12:26:07 $\n% mailto:anton.schwaighofer@gmx.net\n% \n% This program is released unter the GNU General Public License.\n% \n\nerror(nargchk(1, 1, nargin));\n\nX = [];\nY = [];\n\nf = fopen(fname, 'rt');\nif (f<0),\n  error(sprintf('Unable to open file %s', fname));\nend\n\ni = 0;\n% fprintf('Scanning ');\nwhile ~feof(f),\n  s = fgetl(f);\n  [Yi, count, errmsg, nextind] = sscanf(s, '%f', 1);\n  % read the class label resp. anything else that is in the first column\n  if (count==1),\n    i = i+1;\n    Y(i,1) = Yi;\n    [Xi, count] = sscanf(s(nextind:end), ' %i:%f');\n    % scan for the feature:value pairs\n    if (rem(count,2)==0) & (count~=0),\n      % if they really come in pairs, then accept\n      ind = 2:2:count;\n      if isempty(X),\n        maxCol = max(Xi(ind-1));\n        approxSparsity = (count/2)/maxCol;\n        % a rough estimate of the sparsity, based on the first line of\n        % data\n        if approxSparsity>0.5,\n          approxSparsity = 1;\n          X = zeros(maxCol, 1000);\n        else\n          X = spalloc(maxCol, 1000, round(1000*maxCol*approxSparsity));\n          % allocate for 1000 data points (lines) beforehand\n          % We store everything *columnwise* and transpose afterwards,\n          % this greatly improves performance\n        end\n      end\n      X(Xi(ind-1),i) = Xi(ind);\n%       if (rem(i,100)==0),\n%         fprintf(' %i', i);\n%       end\n    end\n  end\nend\n% fprintf(' done.\\n');\nif ~isempty(X),\n  X = X(:,1:i)';\n  sparsity = length(find(X))/prod(size(X));\n  if sparsity<0.5,\n    X = sparse(X);\n    % remove any surplus lines & convert to sparse a second time for\n    % optimal memory usage\n  end\nend\n\nfclose(f);\n\n", "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/svml-master/svmlread.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5686839899576056}}
{"text": "function [U,S,output] = lmlra_nls(T,U0,S0,options)\n%LMLRA_NLS LMLRA by nonlinear least squares.\n%   [U,S,output] = lmlra_nls(T,U0,S0) computes the factor matrices U{1},\n%   ..., U{N} and core tensor S belonging to a low multilinear rank\n%   approximation of the N-th order tensor T by minimizing \n%   0.5*frob(T-lmlragen(U,S))^2. Each term U{r} is a cell array of N factor\n%   matrices U{r}{n}, followed by a core tensor U{r}{N+1}. The algorithm is\n%   initialized with the factor matrices U0{n} and core tensor S0. The\n%   structure output returns additional information:\n%\n%      output.Name  - The name of the selected algorithm.\n%      output.<...> - The output of the selected algorithm.\n%\n%   lmlra_nls(T,U0,S0,options) may be used to set the following options:\n%\n%      options.Algorithm =   - The desired optimization method.\n%      [@nls_gncgs| ...\n%       {@nls_gndl}|@nls_lm]\n%      options.M =           - The preconditioner to use when\n%      [{'block-Jacobi'}|...   options.LargeScale is true.\n%       false]\n%      options.<...>         - Parameters passed to the selected method,\n%                              e.g., options.TolFun, options.TolX and\n%                              options.PlaneSearchOptions. See also help\n%                              [options.Algorithm].\n%\n%   See also lmlra_minf.\n\n%   Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n%            Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)\n%            Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)\n%\n%   References:\n%   [1] L. Sorber, M. Van Barel, L. De Lathauwer, \"Structured data fusion,\"\n%       ESAT-SISTA Internal Report 13-177, KU Leuven, 2013.\n%   [2] L. Sorber, M. Van Barel, L. De Lathauwer, \"Unconstrained\n%       optimization of real functions in complex variables,\" SIAM J. Opt.,\n%       Vol. 22, No. 3, 2012, pp. 879-898.\n\n% Forward problem to btd_nls as a one-term BTD.\nif nargin < 4, options = struct; end\n[U,output] = btd_nls(T,{[U0(:).',S0]},options);\nS = U{1}{end};\nU = U{1}(1:end-1);\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/lmlra_nls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5686839827692778}}
{"text": "function [ a ] = e_qgreedy(Q,s,epsilon )\n%E_QGREEDY \n%\n% input -------------------------------------------------------------------\n%\n%       o Q       : (num_states x num_actions), Q-value table\n%\n%       o s       : (1 x 1), current state index\n%   \n%       o epsilon : (1 x 1), exploration noise [0,1]\n%\n\nactions = size(Q,2);\nif (rand()>epsilon) \n    [~,a] = max(Q(s,:));\nelse\n    a = randi(actions);\nend\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/reinforcement_learning/policies/e_qgreedy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833737577157, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5686367843935576}}
{"text": "%ISCONTOURCONVEX  Tests a contour convexity\n%\n%     status = cv.isContourConvex(contour)\n%\n% ## Input\n% * __contour__ Input vector of 2D points, stored in numeric array\n%   (Nx2/Nx1x2/1xNx2) or cell array of 2-element vectors (`{[x,y], ...}`).\n%\n% ## Output\n% * __status__ Output logical value.\n%\n% The function tests whether the input contour is convex or not. The contour\n% must be simple, that is, without self-intersections. Otherwise, the function\n% output is undefined.\n%\n% See also: cv.convexityDefects\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/isContourConvex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.5686367837078292}}
{"text": "function result = clara(x,kclus,vtype,stdize,metric,nsamp,sampsize)\n\n%CLARA is the 'Clustering Large Applications' clustering algorithm.\n% It returns a list representing a clustering of the data\n% into kclus clusters following the clara algorithm which is\n% designed for large data sets.\n%\n%The algorithm is fully described in:\n%   Kaufman, L. and Rousseeuw, P.J. (1990),\n%   \"Finding groups in data: An introduction to cluster analysis\",\n%   Wiley-Interscience: New York (Series in Applied Probability and\n%   Statistics), ISBN 0-471-87876-6.\n%\n% Required input arguments:\n%       x : Data matrix (rows = observations, columns = variables)\n%   kclus : The number of desired clusters\n%   vtype : Variable type vector (length equals number of variables)\n%           Possible values are 1  Asymmetric binary variable (0/1)\n%                               2  Nominal variable (includes symmetric binary)\n%                               3  Ordinal variable\n%                               4  Interval variable\n%\n% Optional input arguments:\n%     stdize : standardise the variables given by the x-matrix\n%              Possible values are 0 : no standardisation (default)\n%                                  1 : standardisation by the mean\n%                                  2 : standardisation by the median\n%     metric : Metric to be used \n%              Possible values are 'eucli' Euclidian (all interval variables, default)\n%                                  'manha' Manhattan\n%                                  'mixed' Mixed (not all interval variables, default)\n%      nsamp : Number of samples to be drawn from the data set\n%   sampsize : Number of observations in each sample (should be higher\n%              than the number of clusters and lower than the number of\n%              observations)\n%\n% I/O:\n%   result=clara(x,kclus,vtype,'eucli',5,40+2*kclus)\n%\n% Example (subtracted from the referenced book)\n%   load obj200.mat\n%   result=clara(obj200,3,[4 4]);\n%\n% The output of CLARA is a structure containing:\n%   result.dysobs     : dissimilarities for each observation with the medoids\n%   result.metric     : metric used\n%   result.number     : number of observations\n%   result.idmed      : Id of medoid observations\n%   result.ncluv      : A vector with length equal to the number of observations,\n%                       giving for each observation the number of the cluster to\n%                       which it belongs\n%   result.obj        : Objective function for the best subsample\n%   result.clusinf    : Matrix, each row gives numerical information for\n%                       one cluster. These are the cardinality of the cluster\n%                       (number of observations), the maximal and average\n%                       dissimilarity between the observations in the cluster\n%                       and the cluster's medoid, the diameter of the cluster\n%                       (maximal dissimilarity between two observations of the\n%                       cluster), and the separation of the cluster (minimal\n%                       dissimilarity between an observation of the cluster\n%                       and an observation of another cluster).\n%   result.sylinf     : Matrix based on the best subsample, with for each\n%                       observation i of this subsample the cluster to\n%                       which i belongs, as well as the neighbor cluster of i\n%                       (the cluster, not containing i, for which the average\n%                       dissimilarity between its observations and i is minimal),\n%                       and the silhouette width of i.\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 (May 2006)\n\n%Checking and filling out the inputs\nif (nargin<3)\n    error('Three input arguments required')\nelseif (nargin<4)\n    stdize = 0;\n    if (sum(vtype)~=4*size(x,2))\n        metric = 'mixed';\n    else\n        metric = 'eucli';\n    end\n    nsamp=5;\n    sampsize=40+2*kclus;\nelseif (nargin<5)\n    if (sum(vtype)~=4*size(x,2))\n        metric = 'mixed';\n    else\n        metric = 'eucli';\n    end\n    nsamp=5;\n    sampsize=40+2*kclus;\nelseif (nargin<6)\n    nsamp=5;\n    sampsize=40+2*kclus;\nelseif (nargin<7)\n    sampsize=40+2*kclus;\nend\n\n%Standardization\nif (stdize==1)\n    x = ((x - repmat(mean(x),size(x,1),1))./(repmat(std(x),size(x,1),1)));\nelseif (stdize==2)\n    x = ((x - repmat(median(x),size(x,1),1))./(repmat(mad(x),size(x,1),1)));\nend\n\n%Actual calculations\nobj = Inf;\nfor i=1:nsamp\n    sampindex = randperm(size(x,1));\n    restemp = pam(x(sampindex(1:sampsize),:),kclus,vtype,metric);\n    if (restemp.obj(1)<obj)\n        obj = restemp.obj(1);\n        idmed = sampindex(restemp.idmed);\n    end\nend\n\n%Calculating some extra dissimilarities for output\nfor i=1:size(x,1)\n    for j=1:kclus\n        distemp = daisy(x([i idmed(j)],:),vtype,metric);\n        disv(i,j) = distemp.disv(1);\n    end\n    [zz,clu(i)] = min(disv(i,:));\nend\nmindisv=[];\nfor j=1:kclus\n    clusinf(j,1) = length(find(clu==j));\n    clusinf(j,2) = max(disv(find(clu==j),j));\n    clusinf(j,3) = mean(disv(find(clu==j),j));\nend\nfor i=1:kclus\n    for j=1:kclus\n        distemp = daisy(x([idmed(i) idmed(j)],:),vtype,metric);\n        mindisv = [mindisv distemp.disv(1)];\n    end\nend\nclusinf(:,4) = clusinf(:,2)/min(mindisv(mindisv~=0));\n\n%Putting things together\nresult = struct('dysobs',disv,'metric',metric,'number',size(x,1),...\n    'idmed',idmed,'ncluv',clu,'obj',obj,'clusinf',clusinf,...\n    'sylinf',restemp.sylinf,'x',x);\n\n\n\n\n\n\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/LIBRA/clara.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5686367830221005}}
{"text": "function varargout = clipPoints3d(points, shape, varargin)\n%CLIPPOINTS3D Clip a set of points by a box or other 3d shapes.\n%\n%   CLIP = clipPoints3d(POINTS, BOX);\n%   Returns the set of points which are located inside of the box BOX.\n%\n%   [CLIP, IND] = clipPoints3d(POINTS, BOX);\n%   Also returns the indices of clipped points.\n%   \n%   ... = clipPoints3d(..., 'shape', 'sphere') Specify the shape.\n%   Default is 'box'. But it is also possible to use 'sphere' or 'plane'.\n%   \n%   ... = clipPoints3d(..., 'inside', false) returns the set of  \n%   points outside the shape instead of inside.\n%\n%   See also \n%   points3d, boxes3d, spheres\n%\n\n% ------\n% Author: David Legland, oqilipo\n% E-mail: david.legland@inra.fr\n% Created: 2008-10-13, using Matlab 7.4.0.287 (R2007a)\n% Copyright 2008-2022 INRA - BIA Nantes - MIAJ Jouy-en-Josas\n\nparser = inputParser;\nvalidStrings = {'box', 'sphere', 'plane'};\naddParameter(parser, 'shape', 'box', @(x) any(validatestring(x, validStrings)));\naddParameter(parser, 'inside', true, @islogical);\nparse(parser,varargin{:});\n\nswitch parser.Results.shape\n    case 'box'\n        LI = clipPointsByBox(points, shape);\n    case 'plane'\n        LI = clipPointsByPlane(points, shape);\n    case 'sphere'\n        LI = clipPointsBySphere(points, shape);\nend\n\nif parser.Results.inside\n    % keep points inside the shape\n    ind = find(LI);\nelse\n    % keep points outside the shape\n    ind = find(~LI);\nend\npoints = points(ind, :);\n\n% process output arguments\nvarargout{1} = points;\nif nargout == 2\n    varargout{2} = ind;\nend\n\n    function LI = clipPointsByBox(points, box)\n        % get bounding box limits\n        xmin = box(1);\n        xmax = box(2);\n        ymin = box(3);\n        ymax = box(4);\n        zmin = box(5);\n        zmax = box(6);\n        \n        % compute indices of points inside visible area\n        xOk = points(:,1) >= xmin & points(:,1) <= xmax;\n        yOk = points(:,2) >= ymin & points(:,2) <= ymax;\n        zOk = points(:,3) >= zmin & points(:,3) <= zmax;\n        \n        LI = xOk & yOk & zOk;\n    end\n\n    function LI = clipPointsByPlane(points, plane)\n        % points inside and on the surface of the sphere\n        LI = isBelowPlane(points, plane);\n    end\n\n    function LI = clipPointsBySphere(points, sphere)\n        % points inside and on the surface of the sphere\n        LI = distancePoints3d(points, sphere(1:3)) <= sphere(4);\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/geom3d/clipPoints3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5686367830221005}}
{"text": "function errorbar_width(h, x, interval)\n% Work with errorbar.m: Adjust the width of errorbar\n%\n% :Usage:\n% ::\n%\n%    errorbar_width(h, x, interval)\n%\n% :Inputs:\n%\n%   **h:**\n%        errorbar graphic handle\n%\n%   **x:**\n%        vector x, which is used in errorbar\n%\n%   **interval:**\n%        e.g., [-.1 .1] or [0 0] \n%\n% :Examples: you can see this output in \n% http://wagerlab.colorado.edu/wiki/doku.php/help/core/figure_gallery\n% ::\n%\n%    x = 1:5; % x values\n%    y = [32 40 55 84 130]; % mean\n%    e = [6 6 6 6 6]; % standard error of the mean\n%\n%    create_figure(y_axis);\n%    set(gcf, 'Position', [1   512   268   194]);\n%    col = [0.3333    0.6588    1.0000];\n%    markercol = col-.2;\n%\n%    h = errorbar(x, y, e, 'o', 'color', 'k', 'linewidth', 1.5, 'markersize', 7, 'markerfacecolor', col);\n%    hold on;\n%    sepplot(x, y, .75, 'color', col, 'linewidth', 2);\n%    errorbar_width(h, x, [0 0]); % here\n%\n%    set(gca, 'xlim', [.5 5.5], 'linewidth', 1.5);\n%\n%    try\n%       pagesetup(gcf);\n%       saveas(gcf, 'example.pdf');\n%    catch\n%       pagesetup(gcf);\n%       saveas(gcf, 'example.pdf');\n%    end\n%\n% ..\n%    Copyright (C) 2014  Wani Woo\n% ..\n\nxdata = [];\nfor i = x\n    xdata = [xdata repmat(i,1,2) NaN (repmat(i,1,2) + interval) NaN (repmat(i,1,2) + interval) NaN];\nend\n\nhh = get(h, 'children'); set(hh(2), 'XData', xdata);\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/Visualization_functions/errorbar_width.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5686367830221005}}
{"text": "function a = r8bb_set ( n1, n2, ml, mu, a, i, j, value )\n\n%*****************************************************************************80\n%\n%% R8BB_SET sets an entry of a R8BB matrix.\n%\n%  Discussion:\n%\n%    The R8BB storage format is for a border banded matrix.  Such a\n%    matrix has the logical form:\n%\n%      A1 | A2\n%      ---+---\n%      A3 | A4\n%\n%    with A1 a (usually large) N1 by N1 banded matrix, while A2, A3 and A4\n%    are dense rectangular matrices of orders N1 by N2, N2 by N1, and N2 by N2,\n%    respectively.\n%\n%    A should be defined as a vector.  The user must then store\n%    the entries of the four blocks of the matrix into the vector A.\n%    Each block is stored by columns.\n%\n%    A1, the banded portion of the matrix, is stored in\n%    the first (2*ML+MU+1)*N1 entries of A, using standard LINPACK\n%    general band format.  The reason for the factor of 2 in front of\n%    ML is to allocate space that may be required if pivoting occurs.\n%\n%    The following formulas should be used to determine how to store\n%    the entry corresponding to row I and column J in the original matrix:\n%\n%    Entries of A1:\n%\n%      1 <= I <= N1, 1 <= J <= N1, (J-I) <= MU and (I-J) <= ML.\n%\n%      Store the I, J entry into location\n%      (I-J+ML+MU+1)+(J-1)*(2*ML+MU+1).\n%\n%    Entries of A2:\n%\n%      1 <= I <= N1, N1+1 <= J <= N1+N2.\n%\n%      Store the I, J entry into location\n%      (2*ML+MU+1)*N1+(J-N1-1)*N1+I.\n%\n%    Entries of A3:\n%\n%      N1+1 <= I <= N1+N2, 1 <= J <= n1.\n%\n%      Store the I, J entry into location\n%      (2*ML+MU+1)*N1+N1*N2+(J-1)*N2+(I-N1).\n%\n%    Entries of A4:\n%\n%      N1+1 <= I <= N1+N2, N1+1 <= J <= N1+N2\n%\n%      Store the I, J entry into location\n%      (2*ML+MU+1)*N1+N1*N2+(J-1)*N2+(I-N1).\n%      (same formula used for A3).\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    05 March 2005\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N1, N2, the order of the banded and dense blocks.\n%    N1 and N2 must be nonnegative, and at least one must be positive.\n%\n%    Input, integer ML, MU, the lower and upper bandwidths.\n%    ML and MU must be nonnegative, and no greater than N1-1.\n%\n%    Input, real A((2*ML+MU+1)*N1+2*N1*N2+N2*N2), the R8BB matrix.\n%\n%    Input, integer I, J, the row and column of the entry to be set.\n%\n%    Input, real VALUE, the value to be assigned to the (I,J) entry.\n%\n%    Output, real A((2*ML+MU+1)*N1+2*N1*N2+N2*N2), the updated R8BB matrix.\n%\n  if ( i <= 0 | n1+n2 < i )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8BB_SET - Fatal error!\\n' );\n    fprintf ( 1, 'R8BB_SET - Illegal value of row index I = %d\\n', i );\n    error ( 'R8BB_SET - Fatal error!' );\n  end\n\n  if ( j <= 0 | n1+n2 < j )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8BB_SET - Fatal error!\\n' );\n    fprintf ( 1, 'R8BB_SET - Illegal value of column index J = %d\\n', j );\n    error ( 'R8BB_SET - Fatal error!' );\n  end\n%\n%  The A1 block of the matrix.\n%\n%  Check for out of band problems.\n%\n%  Normally, we would check the condition MU < (J-I), but the storage\n%  format requires extra entries be set aside in case of pivoting, which\n%  means that the condition becomes MU+ML < (J-I).\n%\n  if ( i <= n1 & j <= n1 )\n    if ( mu+ml < (j-i) | ml < (i-j) )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'R8BB_SET - Warning!\\n' );\n      fprintf ( 1, 'R8BB_SET - Unable to set entry A(%d,%d).\\n', i, j );\n      error ( 'R8BB_SET - Warning!' );\n    else\n      ij = (i-j+ml+mu+1)+(j-1)*(2*ml+mu+1);\n    end\n%\n%  The A2 block of the matrix.\n%\n  elseif ( i <= n1 & n1 < j )\n    ij = (2*ml+mu+1)*n1+(j-n1-1)*n1+i;\n%\n%  The A3 and A4 blocks of the matrix.\n%\n  elseif ( n1 < i )\n    ij = (2*ml+mu+1)*n1+n2*n1+(j-1)*n2+(i-n1);\n  end\n\n  a(ij) = 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/linplus/r8bb_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5686367830221005}}
{"text": "function coord_w = minc_voxel2world(coord_v,mat,opt);\n% Convert coordinates in the voxel space into coordinates in the world\n% space. \n%\n% SYNTAX:\n% COORD_W = MINC_VOXEL2WORLD(COORD_V,MAT,OPT)\n%\n% _________________________________________________________________________\n% INPUTS:\n%\n% COORD_V\n%       (matrix N*3) each row is a vector of 3D coordinates in voxel space.\n%\n% MAT\n%       (matrix 4*4) an affine transformation from voxel to world\n%       coordinates. See the help of NIAK_READ_VOL for more infos. It is \n%       generally the HDR.INFO.MAT field of the header of a volume file.\n%\n% OPT\n%       (structure, optional) with the following fields :\n%\n%       FLAG_ZERO\n%           (boolean, default false) if FLAG_ZERO is true, voxel \n%           coordinates start from 1 (default behaviour in matlab), \n%           otherwise they start from 0 (default behaviour in C/C++ or \n%           MINC).\n%\n% _________________________________________________________________________\n% OUTPUTS:\n%\n% COORD_W\n%       (matrix N*3) each row is a vector of 3D coordinates in world space.\n%\n% _________________________________________________________________________\n% SEE ALSO:\n% MINC_READ, MINC_WRITE, MINC_VOXEL2WORLD, MINC_WORLD2VOXEL\n%\n% _________________________________________________________________________\n% COMMENTS:\n%\n% Copyright (c) Pierre Bellec, Centre de recherche de l'institut de\n% g\u00e9riatrie de Montr\u00e9al, D\u00e9partement d'informatique et de recherche\n% op\u00e9rationnelle, Universit\u00e9 de Montr\u00e9al, 2013.\n% See licensing information in the code.\n% Keywords : affine transformation, coordinates\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.\nif nargin < 3\n    flag_zero = false;\nelse\n    if isfield(opt,'flag_zero')\n        flag_zero = opt.flag_zero;\n    else\n        flag_zero = false;\n    end\nend\nif flag_zero\n    coord_w = [coord_v ones([size(coord_v,1) 1])]*(mat');\nelse\n    coord_w = [coord_v-1 ones([size(coord_v,1) 1])]*(mat');\nend\ncoord_w = coord_w(:,1:3);", "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/mominc/minc_voxel2world.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5686101460420999}}
{"text": "function [U,Sigma,V,numiter,out]  = SVT(n,Omega,b,tau,delta,maxiter,tol,EPS)\n% [U,Sigma,V,numiter,output]  = SVT(n,Omega,b,tau,delta,maxiter,tol,EPS)\n%\n% Finds the minimum of   tau ||X||_* + .5 || X ||_F^2 \n%\n% subject to P_Omega(X) = P_Omega(M)\n%\n% using linear Bregman iterations\n%\n% Usage:  [U,S,V,numiter]  = SVT(n,Omega,b,delta,maxiter,tol)\n%\n% Inputs:\n%\n%   n - size of the matrix X assumed n(1) by n(2). If n is a single integer, it\n% is understood that n(1) = n(2). \n%\n%   Omega - set of observed entries.  Should be linearly indexed.\n%\n%   b - data vector of the form M(Omega)\n%\n%   tau - parameter defining the objective functional \n%\n%   delta - step size.  Choose delta less than 2 to be safe but\n%       conservative; choose delta closer to n(1)*n(2)/length(Omega)\n%       to be riskier (i.e. algorithm may diverge)\n%\n%   maxiter - maximum number of iterations\n%\n%   tol - stopping criteria (default: 1e-4)\n%\n%   EPS - noise constraint.  This relaxes the constraints, so that they\n%       are now of the form | X(i,j) - M(i,j) | <= EPS,\n%       for all indices (i,j) in omega.  Default: 0\n%\n% Outputs: matrix X stored in SVD format X = U*diag(S)*V'\n% \n%   U - n1xr left singular vectors \n% \n%   S - rx1 singular values\n%\n%   V - n2xr right singular vectors \n%\n%   numiter - number of iterations to achieve convergence\n%\n%   output - a structure with data from each iteration.  Includes:\n%       output.nuclearNorm  - nuclear norm of current iterate\n%       output.rank         - rank of current iterate\n%       output.time         - time taken for one iteraration\n%       output.residual     - the relative residual, norm(x-b)/norm(b)\n% Description: \n% Reference:\n%\n%    Cai, Candes and Shen\n%    A singular value thresholding algorithm for matrix completion\n%    Submitted for publication, October 2008.\n%\n%    See also more general code as part of the TFOCS package,\n%    available at tfocs.stanford.edu as of November 2010.\n%\n% Written by: Emmanuel Candes\n% Email: emmanuel@acm.caltech.edu\n% Created: October 2008\n% Efficient mex-file and PROPACK version: Stephen Becker, Nov 2008\n% Modified: Stephen Becker, March 2009\n% Modified: Stephen Becker, May 2009  works with complex numbers\n% Modified: Farshad Harirchi and Stephen Becker, April 2011, fixing a bug.\n\nglobal VERBOSE\nif isempty(VERBOSE)\n    % -- feel free to change these 'verbosity' parameters\n    % VERBOSE = false;\n    VERBOSE = 1;    % a little bit of output\n    % VERBOSE = 2;    % even more output\nend\n\ntime1 = cputime;\nif nargin < 8 || isempty(EPS)\n    EPS = false;\nend\nif nargin < 7 || isempty(tol)\n    tol = 1e-4;\nend\nif nargin < 6 || isempty(maxiter)\n    maxiter = 500;\nend\n    \nif length(n) == 1,\n    n1 = n(1); n2 = n1;\nelseif length(n) == 2,\n    n1 = n(1); n2 = n(2);\nend\nif n1*n2 < 100*100, SMALLSCALE = true; else SMALLSCALE = false; end\n\nm = length(Omega); [temp,indx] = sort(Omega); \n% simpler: sort b also\nincre = 5; \nnormb = norm(b);\n\n[i, j] = ind2sub([n1,n2], Omega);\nUSE_SLOW_UPDATE     = false;\nif EPS\n    % with inequality constraints, should take delta = delta/sqrt(2) at\n    % least, or delta = delta/2\n    delta = delta/sqrt(2);\n%     delta = delta/2; tau = 2*tau;\n%     y1 = max(b-EPS,0); y2 = max(-b-EPS,0); % doesn't work well\n    y1 = max(b,0); y2 = max(-b,0);\n    Y = sparse(i,j,y1-y2,n1,n2,m);\n    normProjM = normest(Y,1e-2);\n    k0 = ceil(tau/(delta*normProjM));\n    y1 = k0*delta*y1;\n    y2 = k0*delta*y2;\n    try\n        updateSparse(Y,y1-y2,indx);\n    catch\n        l = lasterror;\n        if strcmpi( l.identifier, 'MATLAB:UndefinedFunction')\n            % mex file not installed, so do this instead:\n            [indx_i,indx_j,s] = find(Y);\n            Y = updateSparse_slow(Y,y1-y2,indx,indx_i,indx_j);\n            USE_SLOW_UPDATE     = true;\n        else\n            % some other error (unexpected)\n            rethrow(lasterror)\n        end\n    end\nelse\n    Y = sparse(i,j,b,n1,n2,m);\n    normProjM = normest(Y,1e-2);\n    k0 = ceil(tau/(delta*normProjM));\n    normb = norm(b);\n    y = k0*delta*b; % kicking by k0 steps\n    try\n        updateSparse(Y,y,indx);\n    catch\n        l = lasterror;\n        if strcmpi( l.identifier, 'MATLAB:UndefinedFunction')\n            % mex file not installed, so do this instead:\n            [indx_i,indx_j,s] = find(Y);\n            Y = updateSparse_slow(Y,y,indx,indx_i,indx_j);\n            USE_SLOW_UPDATE     = true;\n        else\n            % some other error (unexpected)\n            rethrow(lasterror)\n        end\n    end\n    \nend\nr = 0;\n\nout.residual = zeros(maxiter,1);\nout.rank= zeros(maxiter,1);\nout.time = zeros(maxiter,1);\nout.nuclearNorm = zeros(maxiter,1);\n\n% What the best way to multiply a sparse matrix?\n[forwardType, transposeType] = findBestMultiply(Y,.2);\n\n\nif VERBOSE==1, fprintf('\\nIteration:   '); end\nfor k = 1:maxiter,\n    if VERBOSE==1, fprintf('\\b\\b\\b\\b%4d',k);  end\n    s = r + 1;\n    \n    rInc = 4;  % make this larger for more accuracy\n    %if tol < 1e-4  && relRes < 1e-1\n    %rInc = rInc + max( round(log10( abs(1e-1/relRes) )), 5 );\n    %end\n    s = min( [r + rInc, n1, n2] );\n\n    if SMALLSCALE\n        [U,Sigma,V] = svd(full(Y),'econ');\n    else\n        % Make routines for multiplying by a sparse matrix\n        Yt = Y';\n        switch forwardType\n            case 1, Yforward = @(x) Y*x;\n            case 2, Yforward = @(x) Yt'*x;\n            case 3, Yforward = @(x) smvp(Y,x);\n        end\n        switch transposeType\n            case 1, Ytranspose = @(x) Yt*x;\n            case 2, Ytranspose = @(x) Y'*x;\n            case 3, Ytranspose = @(x) smvp(Yt,x);\n        end\n        OK = 0;\n        while ~OK\n            opts = [];\n            if ~isreal(b), opts.eta = 1e-16; end\n            [U,Sigma,V] = lansvd(Yforward,Ytranspose,n1,n2,s,'L',opts);\n            %[U,Sigma,V] = lansvd(Y,s,'L');\n            OK = (Sigma(s,s) <= tau) || ( s == min(n1,n2) );\n            s = min(s + incre, min(n1,n2));\n        end\n    end\n   \n    sigma = diag(Sigma); r = sum(sigma > tau);\n    U = U(:,1:r); V = V(:,1:r); sigma = sigma(1:r) - tau; Sigma = diag(sigma);\n    \n    x = XonOmega(U*diag(sigma),V,Omega);\n    eTime = cputime - time1;\n    if VERBOSE == 2\n        fprintf('iteration %4d, rank is %2d, rel. residual is %.1e\\n',k,r,norm(x-b)/normb);\n    end\n    relRes = norm(x-b)/normb;\n    out.residual(k) = relRes;\n    out.time(k) = eTime;\n    out.rank(k) = r;\n    out.nuclearNorm(k) = sum(sigma);\n\n    time1 = cputime;\n    \n    if (relRes < tol)\n        break\n    end\n    if EPS && norm(x-b,'inf') < 2*EPS\n        break\n    end\n    if (norm(x-b)/normb > 1e5)\n        disp('Divergence!');\n        break\n    end\n    \n    if EPS\n        y1 = max( y1 + delta*( -(x-b) - EPS), 0 );\n        y2 = max( y2 + delta*(  (x-b) - EPS), 0 );\n        if USE_SLOW_UPDATE\n            % mex file not installed, so do this instead:\n            Y = updateSparse_slow(Y,y1-y2,indx,indx_i,indx_j);\n        else\n            updateSparse(Y,y1-y2,indx);\n        end\n    else\n        y = y + delta*(b-x);\n        if USE_SLOW_UPDATE\n            % mex file not installed, so do this instead:\n            Y = updateSparse_slow(Y,y,indx,indx_i,indx_j);\n        else\n            updateSparse(Y,y,indx);\n        end\n    end\nend\n\nif VERBOSE==1, fprintf('\\n'); end\nnumiter = k;\nout.residual = out.residual(1:k,:);\nout.time = out.time(1:k,:);\nout.rank= out.rank(1:k,:);\nout.nuclearNorm= out.nuclearNorm(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/algorithms/mc/SVT/SVT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.56861012475462}}
{"text": "function varargout = drawCuboid(cuboid, varargin)\n%DRAWCUBOID Draw a 3D cuboid, eventually rotated.\n%\n%   drawCuboid(CUBOID)\n%   Displays a 3D cuboid on current axis. CUBOID is given by:\n%   [XC YC ZC L W D YAW PITCH ROLL],\n%   where (XC, YC, ZC) is the cuboid center, L, W and H are the lengths of\n%   the cuboid main axes, and YAW PITCH ROLL are Euler angles representing\n%   the cuboid orientation, in degrees. \n%\n%   If cuboid is axis-aligned, it can be specified using only center and\n%   side lengths:\n%   CUBOID = [XC YC ZC L W H]\n%\n%   Example\n%   % Draw a basic rotated cuboid\n%     figure; hold on;\n%     drawCuboid([10 20 30   90 40 10   10 20 30], 'FaceColor', 'g');\n%     axis equal;\n%     view(3);\n%\n%     % Draw three \"borromean\" cuboids\n%     figure; hold on;\n%     drawCuboid([10 20 30 90 50 10], 'FaceColor', 'r');\n%     drawCuboid([10 20 30 50 10 90], 'FaceColor', 'g');\n%     drawCuboid([10 20 30 10 90 50], 'FaceColor', 'b');\n%     view(3); axis equal;\n%     set(gcf, 'renderer', 'opengl')\n%\n%   See also\n%   meshes3d, polyhedra, createCube, drawEllipsoid, drawCube\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-06-29,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\nphi   = 0;\ntheta = 0;\npsi   = 0;\n\n%% Parses the input \nif nargin == 0\n    % no input: assumes cuboid with default shape\n    xc = 0;\tyc = 0; zc = 0;\n    a = 5; b = 4; c = 3;\n\nelse\n    % one argument: parses elements\n    xc  = cuboid(:,1);\n    yc  = cuboid(:,2);\n    zc  = cuboid(:,3);\n    a   = cuboid(:,4);\n    b   = cuboid(:,5);\n    c   = cuboid(:,6);\n    if size(cuboid, 2) >= 9\n        k   = pi / 180;\n        phi   = cuboid(:,7) * k;\n        theta = cuboid(:,8) * k;\n        psi   = cuboid(:,9) * k;\n    end\nend\n\n\n%% Compute cuboid coordinates\n\n% create unit centered cube\n[v, f] = createCube;\nv = bsxfun(@minus, v, mean(v, 1));\n\n% convert unit basis to ellipsoid basis\nsca     = createScaling3d(a, b, c);\nrotZ    = createRotationOz(phi);\nrotY    = createRotationOy(theta);\nrotX    = createRotationOx(psi);\ntra     = createTranslation3d([xc yc zc]);\n\n% concatenate transforms\ntrans   = tra * rotZ * rotY * rotX * sca;\n\n% transform mesh vertices\n[x, y, z] = transformPoint3d(v, trans);\n\n\n%% Process output\nif nargout == 0\n    % no output: draw the cuboid\n    drawMesh([x y z], f, varargin{:});\n    \nelseif nargout == 1\n    % one output: draw the cuboid and return handle \n    varargout{1} = drawMesh([x y z], f, varargin{:});\n    \nelseif nargout == 3\n    % 3 outputs: return computed coordinates\n    varargout{1} = x; \n    varargout{2} = y; \n    varargout{3} = z; \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/geom3d/drawCuboid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938799869521, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5686101126837734}}
{"text": "%########################################################################\n%\n%\t- PPGI Toolbox - \n%   A MATLAB toolbox for Photoplethysmography Imaging (PPGI)\n%\n% Author   : Christian S. Pilz\n% Company  : The Nature of Space of Time\n% Date     : 07.05.2019\n%\n% Contact  : cpi@partofthestars.com\n% Web Page : www.partofthestars.com\n%\n% Version  : beta0.1\n%\n%########################################################################\n%\n%\ttest_spherical_mean.m:\n%\n% Description:\n%\n%   test of the spherical mean feature extraction on given sample rgb data\n%\n% \nclear all;\nclose all;\n\nload('./../media/data/example_data.mat');\n\nif ~exist('skin_pixels')\n    disp('error: no skin pixels available. execute test_skin.m first!');\n    return; \nend\n\nspm=spherical_mean();\n\nfor f=1:size(skin_pixels,2)\n    f\n    [signal(f,:) ssr]=spm.get(skin_pixels{f});\nend\n\nfs=25;\nlow_frequency=0.5;\nhigh_frequency=2.5;\nbpf=bandpass_filter(fs,low_frequency,high_frequency);\nsignal_filtered=bpf.get(signal);\n\n[pearson, rmse, snr, snr_var, bpm] = ground_truth_stats.get(ppg,signal_filtered(:,1),fs);\n", "meta": {"author": "partofthestars", "repo": "PPGI-Toolbox", "sha": "b7a7945561ccd98bf66ca629ac6d1b4bf4f0ac34", "save_path": "github-repos/MATLAB/partofthestars-PPGI-Toolbox", "path": "github-repos/MATLAB/partofthestars-PPGI-Toolbox/PPGI-Toolbox-b7a7945561ccd98bf66ca629ac6d1b4bf4f0ac34/tests/test_spherical_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5686101073619034}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Jellyfish Example Courtesy of Alexander P. Hoover, PhD\n%\n% Converted from IBAMR: 1/16/2018 by NAB.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Make_Jelly_Geometry()\n\nclose all;\nclear all;\nL = 8;                              % height of computational domain (m) for keeping desired resolution\nLh = 10;                            % actual height of computational domain (m) (MATCHES INPUT2D)\nLw = 3;                             % width of computational domain (m) (MATCHES INPUT2D)\nN = 768;                            % number of Cartesian grid meshwidths at the finest level of the AMR grid\ndx = L/N;                           % Cartesian mesh width (m)\nds = dx/2;\n \na=.5;                               % bell radius (semi-minor axis, horizontal axis, note width=2a)\nb=.75;                              % bell semi-major axis \nd=-0.25;\nfactor_a=.8;\n \nF=1e5; %5e0\n \ntheta=zeros(1000,1);\ntheta_lim=asin(d/b);\ntheta_test=pi/2;\n \nx_points=zeros(1000,1);\nz_points=zeros(1000,1);\nid_points=zeros(1000,1);\noffset = 0;\n \nkappa_spring = 1e7; %1e5               % spring constant (Newton)\nkappa_beam = 2.5e5; %1e5    %5e3              % beam stiffness constant (Newton m^2)\n%kappa_beam_flexible = kappa_beam/5;   % beam stiffness constant (Newton m^2)\nkappa_target = kappa_spring;           % target point penalty spring constant (Newton)\n \nc=0;\nwhile(theta_test<(pi-theta_lim))\n    c=c+1;\n    theta(c)=theta_test;\n     \n    x_points(c)=a*cos(theta(c));\n    z_points(c)=b*sin(theta(c));\n    id_points(c)=c-1;\n     \n    theta_test=ds/((a*sin(theta(c)))^(2)+(b*cos(theta(c)))^(2))^(.5)+theta(c);\n     \nend\n \nc_stiff=c;\n \n \nnpts=2*c-1;\nnpts_wing=floor(npts/2);\nnpts_musc=floor(npts_wing/4);\n \nfor j=(c+1):(npts)\n    x_points(j)=-1*x_points(j-c+1);\n    z_points(j)=z_points(j-c+1);\n    id_points(j)=j-1;\nend\n \n\nmesh_name = 'jelly';\nxShift = 1.5;\nyShift = 2;\n \nx_points=x_points(1:npts)+xShift;\nz_points=z_points(1:npts)+yShift;\nit_points=id_points(1:npts);\n \nplot(x_points(:),z_points(:),'*'); hold on;\naxis([0 8 0 8])\n\n% Lag Pts to Mess up Flow At Edge\nxBlock = ds:4*ds:Lw-ds;\nyBlock = (Lh-5*ds)*ones(1,length(xBlock))+ds;\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Print .vertex information\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nvertex_fid = fopen([mesh_name num2str(N) '.vertex'], 'w');\n \n    fprintf(vertex_fid, '%d\\n', npts + npts_musc*2 + length(xBlock));\n    lag_ct = 0;\n    \n    %\n    % bell\n    %\n    for j=1:npts\n        fprintf(vertex_fid, '%1.16e %1.16e\\n', x_points(j), z_points(j));\n        lag_ct = lag_ct + 1;\n    end\n \n    %\n    % muscles\n    %\n    for s = 1:npts_musc\n        fprintf(vertex_fid, '%1.16e %1.16e\\n', x_points(npts_wing+1-npts_musc+s), z_points(npts_wing+1-npts_musc+s));\n        plot(x_points(npts_wing+1-npts_musc+s),z_points(npts_wing+1-npts_musc+s),'r*'); hold on;\n        lag_ct = lag_ct + 1;\n    end\n    for s = 1:npts_musc\n        fprintf(vertex_fid, '%1.16e %1.16e\\n', x_points(npts-npts_musc+s), z_points(npts-npts_musc+s));\n        plot(x_points(npts-npts_musc+s),z_points(npts-npts_musc+s),'r*'); hold on;\n        lag_ct = lag_ct + 1;\n    end\n    \n    for ii=1:length(xBlock)\n        fprintf(vertex_fid, '%1.16e %1.16e\\n', xBlock(ii), yBlock(ii));\n    end\n\nfclose(vertex_fid);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Print .spring information\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nspring_fid = fopen([mesh_name num2str(N) '.spring'], 'w');\n    \n    npts_spring_type1=npts-1;\n \n    fprintf(spring_fid, '%d\\n', npts-1 + npts_musc);\n \n    fprintf('\\nNumber of springs before muscles: %d \\n\\n',npts-1)\n    \n    factor = 1;%ds^2/ds;\n    \n    %\n    % bell\n    %\n    for s = 1:c-1\n        resting=sqrt((x_points(s)-x_points(s+1))^(2)+(z_points(s)-z_points(s+1))^(2));\n        fprintf(spring_fid, '%d %d %1.16e %1.16e %d\\n', id_points(s)+1, id_points(s+1)+1, kappa_spring*ds/(ds^2)*factor, resting, 1);\n    end\n    for s = c+1:npts-1\n        resting=sqrt((x_points(s)-x_points(s+1))^(2)+(z_points(s)-z_points(s+1))^(2));\n        fprintf(spring_fid, '%d %d %1.16e %1.16e %d\\n', id_points(s)+1, id_points(s+1)+1, kappa_spring*ds/(ds^2)*factor, resting, 1);\n    end\n    resting=sqrt((x_points(1)-x_points(c+1))^(2)+(z_points(1)-z_points(c+1))^(2));\n    fprintf(spring_fid, '%d %d %1.16e %1.16e %d\\n', id_points(1)+1, id_points(c+1)+1, kappa_spring*ds/(ds^2)*factor, resting, 1);\n\n    %\n    % muscles\n    %\n    for s = 1:npts_musc\n        fprintf(spring_fid, '%d %d %1.16e %1.16e %d\\n',npts+s-1+1, npts+s+npts_musc-1+1, F, 0, 1);\n    end\n \n \n    fclose(spring_fid);\n \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Print .nonInv_beam information\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nbeam_fid = fopen([mesh_name num2str(N) '.nonInv_beam'], 'w');\n \n    fprintf(beam_fid, '%d\\n', npts-2);\n\n    factor=1;% = (ds^4)/ds;\n    \n    for s = 2:c-1\n        C1 = x_points(s-1)+x_points(s+1)-2*x_points(s);\n        C2 = z_points(s-1)+z_points(s+1)-2*z_points(s);\n        fprintf(beam_fid, '%d %d %d %1.16e %1.16e %1.16e\\n', id_points(s-1)+1, id_points(s)+1, id_points(s+1)+1, kappa_beam*ds/(ds^4)*factor, C1, C2);\n    end\n    for s = c+2:npts-1\n        C1 = x_points(s-1)+x_points(s+1)-2*x_points(s);\n        C2 = z_points(s-1)+z_points(s+1)-2*z_points(s);\n        fprintf(beam_fid, '%d %d %d %1.16e %1.16e %1.16e\\n', id_points(s-1)+1, id_points(s)+1, id_points(s+1)+1, kappa_beam*ds/(ds^4)*factor, C1, C2);\n    end\n\n    C1 = x_points(c+2)+x_points(1)-2*x_points(c+1);\n    C2 = z_points(c+2)+z_points(1)-2*z_points(c+1);\n    fprintf(beam_fid, '%d %d %d %1.16e %1.16e %1.16e\\n', id_points(c+2)+1, id_points(c+1)+1, id_points(1)+1, kappa_beam*ds/(ds^4)*factor, C1, C2);\n\n    C1 = x_points(c+1)+x_points(2)-2*x_points(1);\n    C2 = z_points(c+1)+z_points(2)-2*z_points(1);\n    fprintf(beam_fid, '%d %d %d %1.16e %1.16e %1.16e\\n', id_points(c+1)+1, id_points(1)+1, id_points(2)+1, kappa_beam*ds/(ds^4)*factor, C1, C2);\n\n \n    fclose(beam_fid);\n \n    \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   \n%\n% PRINT TARGET POINTS!!!\n%\n% print target points (flow blocker along edge)\nk_Target = 2.5e6;\nnBefore = lag_ct; % Counts pts in jellyfish for bookkeeping for .target file\nstruct_name = ['jelly' num2str(N)];\nprint_Lagrangian_Target_Pts(xBlock,k_Target,struct_name,nBefore)    \n    \n    \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints TARGET points to a file called 'struct_name'.target\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Target_Pts(xLag,k_Target,struct_name,nBefore)\n\n    N = length(xLag);\n    Nstart = nBefore+1;\n    Nend = nBefore+N;\n\n    target_fid = fopen([struct_name '.target'], 'w');\n\n    fprintf(target_fid, '%d\\n', N );\n\n    %Loops over all Lagrangian Pts.\n    for s = Nstart:Nend\n        fprintf(target_fid, '%d %1.16e\\n', s, k_Target);\n    end\n\n    fclose(target_fid); ", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Examples_Education/Convergence/Jellyfish/Simulation_Skeletons/Re37pt5/Res_768_960x288/Make_Jelly_Geometry.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5686101015643307}}
{"text": "% Conduct a binary search\n% \n% binSearch: Conducts a binary search and continues until the score is\n% close enough to the target. An upper limit should be set on the number of\n% iterations\n%\n%     [SearchPoint, Step, ReLoop] = iosr.auditory.binSearch(Score, ...\n%       TargetScore, ...\n%       CloseEnough, ...\n%       NextSearchPointa, ...\n%       Step, ...\n%       LoopCount, ...\n%       MaxLoops);\n% end\n%\n% inputs:\n% - Score: the test value\n% - Target: the 'finished' test value\n% - CloseEnough: the distance from the Target at which it is acceptable to\n% discontinue the binary search\n% - SearchPoint: the next work input value to try\n% - Step: the distance which the SearchPoint can move by\n% - LoopCount: a counter for the number of iterations completed so far\n% - MaxLoops: The upper limit on the number of iterations allowed\n%\n% outputs:\n% - SearchPoint: the next work input value you should try\n% - Step: the distance which can be stepped on the NEXT iteration. You\n%   should store this value.\n% - ReLoop: If this flag is set to 0, the upper level while loop will be\n%   terminated\n%\n%\n% example: you wish to use an audibility model to find the level at which\n% you can be 50% confident of detecting the signal (-+ 1%). You choose to\n% start with an input level of 20dB and take no more than 10 steps of\n% 40,20,10 dB etc.\n%\n% You would implement this in the following way:\n%\n% TargetPercent = 0.5;\n% CloseEnough = 0.01;\n% Signal Level = 40;\n% Step = 40;\n% MaxLoops = 10;\n% LoopCount = 0;\n%\n% while ReLoop = 1\n%\n%   LoopCount = LoopCount + 1;\n%\n%   Percent = RunAudibilityModel(SignalLevel)\n%\n%   [SignalLevel Step ReLoop] = iosr.auditory.binSearch(Percent, ...\n%       TargetPercent, ...\n%       CloseEnough, ...\n%       SignalLevel, ...\n%       Step, ...\n%       LoopCount, ...\n%       MaxLoops);\n%\n% end\n% \n\n%   Copyright 2016 University of Surrey.\n\nfunction [SearchPoint, Step, ReLoop] = binSearch(Score, Target, CloseEnough, SearchPoint, Step, LoopCount, MaxLoops)\n\n% input tests\n% test input types\nassert(isnumeric(Score) ... \n    &isnumeric(Target) ...\n    &isnumeric(CloseEnough) ...\n    &isnumeric(SearchPoint) ...\n    &isnumeric(Step) ...\n    &isnumeric(LoopCount) ...\n    &isnumeric(MaxLoops),'input arguments must be numeric!');\n\n\n% Define next search point\nif Score > Target\n    SearchPoint = SearchPoint - Step;\nelse\n    SearchPoint = SearchPoint + Step;\nend\n\n% half the distance of the next step\nStep = Step / 2;\n\n% if we got close enough to our taget, or it was the last iteration\nif (abs((Score-Target))<CloseEnough)||(LoopCount>=MaxLoops)\n    ReLoop = 0;\nelse\n    ReLoop = 1;\nend\n\nend\n", "meta": {"author": "IoSR-Surrey", "repo": "MatlabToolbox", "sha": "4bff1bb2da7c95de0ce2713e7c710a0afa70c705", "save_path": "github-repos/MATLAB/IoSR-Surrey-MatlabToolbox", "path": "github-repos/MATLAB/IoSR-Surrey-MatlabToolbox/MatlabToolbox-4bff1bb2da7c95de0ce2713e7c710a0afa70c705/+iosr/+auditory/binSearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481138, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5686031451156398}}
{"text": "function [s, err_mse, iter_time]=greed_omp_pinv(x,A,m,varargin)\n% greed_omp_pinv: Orthogonal Matching Pursuit algorithm based on matlab\n% pinv solution. Use not recommended, provided for reference only!\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Usage\n% [s, err_mse, iter_time]=greed_omp_pinv(x,P,m,'option_name','option_value')\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input\n%   Mandatory:\n%               x   Observation vector to be decomposed\n%               P   Either:\n%                       1) An nxm matrix (n must be dimension of x)\n%                       2) A function handle (type \"help function_format\" \n%                          for more information)\n%                          Also requires specification of P_trans option.\n%                       3) An object handle (type \"help object_format\" for \n%                          more information)\n%               m   length of s \n%\n%   Possible additional options:\n%   (specify as many as you want using 'option_name','option_value' pairs)\n%   See below for explanation of options:\n%__________________________________________________________________________\n%   option_name    |     available option_values                | default\n%--------------------------------------------------------------------------\n%   stopCrit       | M, corr, mse, mse_change                   | M\n%   stopTol        | number (see below)                         | n/4\n%   P_trans        | function_handle (see below)                | \n%   maxIter        | positive integer (see below)               | n\n%   verbose        | true, false                                | false\n%   start_val      | vector of length m                         | zeros\n%\n%   Available stopping criteria :\n%               M           -   Extracts exactly M = stopTol elements.\n%               corr        -   Stops when maximum correlation between\n%                               residual and atoms is below stopTol value.\n%               mse         -   Stops when mean squared error of residual \n%                               is below stopTol value.\n%               mse_change  -   Stops when the change in the mean squared \n%                               error falls below stopTol value.\n%\n%   stopTol: Value for stopping criterion.\n%\n%   P_trans: If P is a function handle, then P_trans has to be specified and \n%            must be a function handle. \n%\n%   maxIter: Maximum of allowed iterations.\n%\n%   verbose: Logical value to allow algorithm progress to be displayed.\n%\n%   start_val: Allows algorithms to start from partial solution.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Outputs\n%    s              Solution vector \n%    err_mse        Vector containing mse of approximation error for each \n%                   iteration\n%    iter_time      Vector containing times for each iteration\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Description\n%   greed_omp_pinv performs a greedy signal decomposition. \n%   In each iteration a new element is selected depending on the inner\n%   product between the current residual and columns in P.\n%   The non-zero elements of s are approximated by orthogonally projecting \n%   x onto the selected elements in each iteration.\n%   This implementation uses matlab's pinv command to calculate the required \n%   projection. This is very slow and only works for small matrices. It is \n%   therefore only provided for reference.\n%   \n% See Also\n%   greed_qr, greed_omp_chol, greed_omp_cg, greed_omp_cgp, \n%   greed_omp_linsolve, greed_gp, greed_nomp\n%\n% Copyright (c) 2007 Thomas Blumensath\n%\n% The University of Edinburgh\n% Email: thomas.blumensath@ed.ac.uk\n% Comments and bug reports welcome\n%\n% This file is part of sparsity Version 0.1\n% Created: April 2007\n%\n% Part of this toolbox was developed with the support of EPSRC Grant\n% D000246/1\n%\n% Please read COPYRIGHT.m for terms and conditions.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                    Default values and initialisation\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n[n1 n2]=size(x);\nif n2 == 1\n    n=n1;\nelseif n1 == 1\n    x=x';\n    n=n2;\nelse\n   display('x must be a vector.');\n   return\nend\n    \nsigsize     = x'*x/n;\ninitial_given=0;\nerr_mse     = [];\niter_time   = [];\nSTOPCRIT    = 'M';\nSTOPTOL     = ceil(n/4);\nMAXITER     = n;\nverbose     = false;\ns_initial   = zeros(m,1);\nvectnfact   = ones(m,1);\n\nif verbose\n   display('Initialising...') \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                           Output variables\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nswitch nargout \n    case 3\n        comp_err=true;\n        comp_time=true;\n    case 2 \n        comp_err=true;\n        comp_time=false;\n    case 1\n        comp_err=false;\n        comp_time=false;\n    case 0\n        error('Please assign output variable.')\n    otherwise\n        error('Too many output arguments specified')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                       Look through options\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Put option into nice format\nOptions={};\nOS=nargin-3;\nc=1;\nfor i=1:OS\n    if isa(varargin{i},'cell')\n        CellSize=length(varargin{i});\n        ThisCell=varargin{i};\n        for j=1:CellSize\n            Options{c}=ThisCell{j};\n            c=c+1;\n        end\n    else\n        Options{c}=varargin{i};\n        c=c+1;\n    end\nend\nOS=length(Options);\nif rem(OS,2)\n   error('Something is wrong with argument name and argument value pairs.') \nend\n\nfor i=1:2:OS\n   switch Options{i}\n        case {'stopCrit'}\n            if (strmatch(Options{i+1},{'M'; 'corr'; 'mse'; 'mse_change'},'exact'));\n                STOPCRIT    = Options{i+1};  \n            else error('stopCrit must be char string [M, corr, mse, mse_change]. Exiting.'); end \n        case {'stopTol'}\n            if isa(Options{i+1},'numeric') ; STOPTOL     = Options{i+1};   \n            else error('stopTol must be number. Exiting.'); end\n        case {'P_trans'} \n            if isa(Options{i+1},'function_handle'); Pt = Options{i+1};   \n            else error('P_trans must be function _handle. Exiting.'); end\n        case {'maxIter'}\n            if isa(Options{i+1},'numeric'); MAXITER     = Options{i+1};             \n            else error('maxIter must be a number. Exiting.'); end\n        case {'verbose'}\n            if isa(Options{i+1},'logical'); verbose     = Options{i+1};   \n            else error('verbose must be a logical. Exiting.'); end \n        case {'vecNormFac'}\n            if isa(Options{i+1},'numeric')& length(Options{i+1}) == m , vectnfact = Options{i+1};   \n            else error('verbose must be a logical. Exiting.'); end \n        case {'start_val'}\n            if isa(Options{i+1},'numeric') & length(Options{i+1}) == m ;\n                s_initial     = Options{i+1};   \n                initial_given=1;\n            else error('start_val must be a vector of length m. Exiting.'); end\n        otherwise\n            error('Unrecognised option. Exiting.') \n   end\nend\n\n\n\nif strcmp(STOPCRIT,'M') \n    maxM=STOPTOL;\nelse\n    maxM=MAXITER;\nend\n\nif nargout >=2\n    err_mse = zeros(maxM,1);\nend\nif nargout ==3\n    iter_time = zeros(maxM,1);\nend\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                        Make P and Pt functions\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif          isa(A,'float')      P =@(z) A*z;  Pt =@(z) A'*z;\nelseif      isobject(A)         P =@(z) A*z;  Pt =@(z) A'*z;\nelseif      isa(A,'function_handle') \n    try\n        if          isa(Pt,'function_handle'); P=A;\n        else        error('If P is a function handle, Pt also needs to be a function handle. Exiting.'); end\n    catch error('If P is a function handle, Pt needs to be specified. Exiting.'); end\nelse        error('P is of unsupported type. Use matrix, function_handle or object. Exiting.'); end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                        Do we start from zero or not?\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif initial_given ==1;\n    IN          = find(s_initial);\n    s=zeros(m,1);\n    if isa(A,'function_handle') || isobject(A)\n         Pmat=zeros(n,length(IN));\n         for i=1:length(IN)\n             mask=zeros(m,1);\n             mask(IN(i))=1;\n             Pmat(:,i)=P(mask);\n         end\n         s(IN)=pinv(Pmat)*x;\n     else\n         s(IN)=pinv(A(:,IN))*x;\n     end\n    Residual    = x-P(s);\n    oldERR      = Residual'*Residual/n;\n    \nelse\n    IN          = [];\n    Residual    = x;\n    s           = s_initial;\n    sigsize     = x'*x/n;\n    oldERR      = sigsize;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                 Random Check to see if dictionary is normalised \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%         mask=zeros(m,1);\n%         mask(ceil(rand*m))=1;\n%         nP=norm(P(mask));\n%         if abs(1-nP)>1e-3;\n%             display('Dictionary appears not to have unit norm columns.')\n%         end\n        \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                        Main algorithm\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif verbose\n   display('Main iterations...') \nend\ntic\nt=0;\nDR=Pt(Residual).*vectnfact;\ndone = 0;\niter=1;\nwhile ~done\n     DR(IN)=0;\n     [v I]=max(abs(DR));\n     IN=[IN I];\n     if isa(A,'function_handle') || isobject(A)\n         Pmat=zeros(n,length(IN));\n         for i=1:length(IN)\n             mask=zeros(m,1);\n             mask(IN(i))=1;\n             Pmat(:,i)=P(mask);\n         end\n         s(IN)=pinv(Pmat)*x;\n     else\n         s(IN)=pinv(A(:,IN))*x;\n     end\n         Residual=x-P(s);\n         DR=Pt(Residual).*vectnfact;\n\n \n     \n    ERR=Residual'*Residual/n;\n     if comp_err\n         err_mse(iter)=ERR;\n     end\n     \n     if comp_time\n         iter_time(iter)=toc;\n     end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                        Are we done yet?\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n     \n     if strcmp(STOPCRIT,'M')\n         if iter >= STOPTOL\n             done =1;\n         elseif verbose && toc-t>10\n            display(sprintf('Iteration %i. --- %i iterations to go',iter ,STOPTOL-iter)) \n            t=toc;\n         end\n    elseif strcmp(STOPCRIT,'mse')\n         if comp_err\n            if err_mse(iter)<STOPTOL;\n                done = 1; \n            elseif verbose && toc-t>10\n                display(sprintf('Iteration %i. --- %i mse',iter ,err_mse(iter))) \n                t=toc;\n            end\n         else\n             if ERR<STOPTOL;\n                done = 1; \n             elseif verbose && toc-t>10\n                display(sprintf('Iteration %i. --- %i mse',iter ,ERR)) \n                t=toc;\n             end\n         end\n     elseif strcmp(STOPCRIT,'mse_change') && iter >=2\n         if comp_err && iter >=2\n              if ((err_mse(iter-1)-err_mse(iter))/sigsize <STOPTOL);\n                done = 1; \n             elseif verbose && toc-t>10\n                display(sprintf('Iteration %i. --- %i mse change',iter ,(err_mse(iter-1)-err_mse(iter))/sigsize )) \n                t=toc;\n             end\n         else\n             if ((oldERR - ERR)/sigsize < STOPTOL);\n                done = 1; \n             elseif verbose && toc-t>10\n                display(sprintf('Iteration %i. --- %i mse change',iter ,(oldERR - ERR)/sigsize)) \n                t=toc;\n             end\n         end\n     elseif strcmp(STOPCRIT,'corr') \n          if max(abs(DR)) < STOPTOL;\n             done = 1; \n          elseif verbose && toc-t>10\n                display(sprintf('Iteration %i. --- %i corr',iter ,max(abs(DR)))) \n                t=toc;\n          end\n     end\n     \n    % Also stop if residual gets too small or maxIter reached\n     if comp_err\n         if err_mse(iter)<1e-16\n             display('Stopping. Exact signal representation found!')\n             done=1;\n         end\n     else\n\n\n         if iter>1\n             if ERR<1e-16\n                 display('Stopping. Exact signal representation found!')\n                 done=1;\n             end\n         end\n     end\n\n     if iter >= MAXITER\n         display('Stopping. Maximum number of iterations reached!')\n         done = 1; \n     end\n     \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                    If not done, take another round\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n   \n     if ~done\n        iter=iter+1;\n        oldERR=ERR;\n     end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                  Only return as many elements as iterations\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargout >=2\n    err_mse = err_mse(1:iter);\nend\nif nargout ==3\n    iter_time = iter_time(1:iter);\nend\n\nif verbose\n   display('Done') \nend\n\n% Change history\n%\n% 8 of Februray: Algo does no longer stop if dictionary is not normaliesd.\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/thirdparty/sparsify/private/greed_omp_pinv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5686031303391326}}
{"text": "function data=nDexample(cx,N,n,seedi)\nrand('seed',seedi);\nmu = rand(cx,n)*10;\nx=[];\nC=[];\nfor i=1:cx\n    r=[];\n    dum=rand(n,n)-0.5+diag(rand(n,1))+diag(ones(n,1))/3;\n    R=dum*dum';\n %   R=eye(n)/3;\n    for j=1:N\n         r(j,:) = randn(1,size(R,1)) * R + mu(i,:);\n    end  \n    C=[C;ones(N,1)*i];\n    x=[x;r];\nend\n%plot(x(:,1),x(:,2),'.');\ndata=[x];\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/7486-clustering-toolbox/Demos/PCAexample/nDexample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5685289626703771}}
{"text": "function tree(objectorder,heights)\n\n%TREE creates a tree in which the leaves represent\n%   objects.  The vertical coordinate of the junction\n%   of two branches is the dissimilarity between the\n%   corresponding clusters (maximal 30 objects allowed).\n%\n% The algorithm is fully described in:\n%   Kaufman, L. and Rousseeuw, P.J. (1990),\n%   \"Finding groups in data: An introduction to cluster analysis\",\n%   Wiley-Interscience: New York (Series in Applied Probability and\n%   Statistics), ISBN 0-471-87876-6.\n%\n% Required input arguments:\n%   objectorder :  order of objects\n%   heights     : diameter of cluster before dividing it\n%                 (=length of banner)\n%\n% I/O:\n%   tree(objectorder,heights)\n%\n% Example (subtracted from the referenced book)\n%   load agricul.mat\n%   result = diana(agricul,[4 4],0,0,1);\n%   tree(result.objectorder,result.heights)\n%\n% The output of TREE is a figure containing the\n%   agglomerative (agnes) or divise (diana) tree.\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 Wai Yan Kong (May 2006)\n% Last Revision: 28/09/2006\n\n\nclf reset\nwhitebg([1 1 1]);\n\nif (nargin<2)\n    error('Two input arguments required')\nelseif (nargin>2)\n    error('Too many input arguments')\nend\n\nif(size(objectorder,2)~=size(heights,2)+1)\n    error('Missing values in objectorder or heights')\nend\n\nHeights=H(heights);\n\nnumber=size(objectorder,2);\n\nif (number>30)\n    error('Only 30 objects allowed')\nend\n\n%midden=[];\nmiddle(1)=0;\nMaxi=0;\nMini=0;\nPrevMID=middle(1);\nlengt=[]; %length\nhigh=[]; %height\nindices=[];\nL=[];\n\n[maxim,index]=max(Heights);\nif(1<=index-1)\n    [Prevmax,Previndex]=max(Heights(1:(index-1)));\nelse\n    Prevmax=maxim;\n    Previndex=index;\nend\nif(index+1<=number-1)\n    [Postmax,Postindex]=max(Heights((index+1):(number-1)));\n    Postindex=Postindex+index+1-1;\nelse\n    Postmax=maxim;\n    Postindex=index;\nend\n\nif(Postindex+1<=number-1)\n    [Post2max,Post2index]=max(Heights(Postindex+1:number-1));\n    Post2index=Post2index+Postindex+1-1;\nelse\n    Post2max=Postmax;\n    Post2index=Postindex;\nend\n\nif(Postindex+1<=Post2index-1)\n    [Betweenmax,Betweenindex]=max(Heights(index+1:Postindex-1));\n    Betweenindex=Betweenindex+index+1-1;\nelse\n    Betweenmax=Postmax;\n    Betweenindex=Postindex;\nend\n\nL=cat(2,L,maxim);\n\nhigh=cat(2,high,[Post2max,Postmax,Betweenmax,maxim,Prevmax]);\nindices=cat(2,indices,[Post2index,Postindex,Betweenindex,index,Previndex]);\n\nM=0;\nextra=number/2;\nlengt(1)=Postindex-Previndex+extra+2;\nPrevLEN=lengt(1);\nrectangle('Position',[middle(1)-(lengt(1)/2),maxim,lengt(1),0.0001]);\n\nNbanFirst=1;\nk=1;\nbranch=0;\nover=0;\nElement=0;\nSpecial=0;\nSpec=0;\nSp=0;\nS=0;\nww=0;\nif(maxim<20)\n    extrawaystick=0.8;\n    extrawaytext=1.5;\nelse\n    extrawaytext=0;\n    extrawaystick=0;\nend\n\nright=0;\ndirect11=0;\ndirect111=0;\nrighttree=0;\nif(index==1)\n    direct1=1;\nelse\n    direct1=0;\nend\n\nLast=size(lengt,2);\nLastM=size(middle,2);\nLastL=size(lengt,2);\n\nwhile(k<=number)\n    w=0;\n    LastH=size(high,2);\n    if((high(LastH)~=high(LastH-1)) & Element==0)\n        while(branch==0)\n            S=0;\n            w=w+1;\n            ww=ww+1;\n\n            if(over==0)\n                middle=cat(2,middle,middle(LastM)-(lengt(LastL)/2));\n            end\n\n            if(righttree==1)\n                middle=cat(2,middle,middle(LastM)-(lengt(LastL)/2));\n                righttree=0;\n            end\n\n            if(Sp==1)\n                LastM=size(middle,2);\n                LastL=size(lengt,2);\n                middle(LastM)=middle(LastM)+lengt(LastL)/2;\n                Sp=0;\n                S=1;\n            end\n            LastM=size(middle,2);\n\n            Output=maxim-Prevmax;\n            rectangle('Position',[middle(LastM),Prevmax,0.0001,Output]);\n\n            if(Betweenmax==Postmax | over==0)\n                Post2max=Postmax;\n                Post2index=Postindex;\n            end\n\n            if((Betweenmax==Postmax | over==0) & (right~=1 | over==0))\n                Postmax=maxim;\n                Postindex=index;\n            end\n\n            maxim=Prevmax;\n            index=Previndex;\n\n            if(NbanFirst<=(index-1))\n                [Prevmax,Previndex]=max(Heights(NbanFirst:(index-1)));\n                Previndex=Previndex+NbanFirst-1;\n            else\n                Prevmax=maxim;\n                Previndex=index;\n            end\n\n            if(index+1<=Postindex-1)\n                [Betweenmax,Betweenindex]=max(Heights(index+1:Postindex-1));\n                Betweenindex=Betweenindex+index+1-1;\n            else\n                Betweenmax=Postmax;\n                Betweenindex=Postindex;\n            end\n\n            if(right==1 & over~=0)\n                high=cat(2,high,[Prevmax Prevmax]);\n                indices=cat(2,indices,[Previndex Previndex]);\n            else\n                high=cat(2,high,Prevmax);\n                indices=cat(2,indices,Previndex);\n            end\n\n            if(Postindex-Previndex<=0)\n                lengt=cat(2,lengt,1);\n            else\n                if(Postindex-Previndex-direct111>0)\n                    if(ww==1)\n                        lengt=cat(2,lengt,Postindex-Previndex-direct111+2);\n                    else\n                        lengt=cat(2,lengt,Postindex-Previndex-direct111);\n                    end\n                else\n                    if(ww==1)\n                        lengt=cat(2,lengt,Postindex-Previndex+2);\n                    else\n                        lengt=cat(2,lengt,Postindex-Previndex);\n                    end\n                end\n            end\n            L=cat(2,L,maxim);\n\n            if(direct111~=0)\n                direct111=0;\n            end\n\n            LastH=size(high,2);\n            LastL=size(lengt,2);\n            LastM=size(middle,2);\n\n\n            rectangle('Position',[middle(LastM)-(lengt(LastL)/2),maxim,lengt(LastL),0.0001]);\n\n            if(over~=0)\n                over=0;\n            end\n\n            if(right~=0)\n                right=0;\n            end\n\n            if(NbanFirst==index)\n                branch=1;\n            end\n        end\n\n        rectangle('Position',[middle(LastM)-(lengt(LastL)/2),maxim-1+extrawaystick,0.0001,1-extrawaystick]);\n        if(objectorder(k)>10)\n\n            text(middle(LastM)-(lengt(LastL)/2)-0.25,maxim-2.0+extrawaytext,num2str(double(objectorder(k))));\n            T=middle(LastM)-(lengt(LastL)/2-0.25);\n        else\n\n            text(middle(LastM)-(lengt(LastL)/2)-0.1,maxim-2.0+extrawaytext,num2str(double(objectorder(k))));\n            T=middle(LastM)-(lengt(LastL)/2-0.1);\n        end\n\n        Maxi=max(Maxi,T);\n        Mini=min(Mini,T);\n\n        if(Betweenmax~=Postmax)\n            high=high(1:LastH-2);\n            indices=indices(1:LastH-2);\n\n            Prevmax=Betweenmax;\n            Previndex=Betweenindex;\n\n            high=cat(2,high,Prevmax);\n            indices=cat(2,indices,Previndex);\n            LastH=size(high,2);\n\n            LastL=size(lengt,2);\n            middle(LastM)=middle(LastM)+lengt(LastL)/2;\n            over=1;\n        end\n        direct1=0;\n        Special=0;\n        Spec=0;\n    else\n        if(Special==1)\n            Special=0;\n            Spec=1;\n        end\n\n        if(Sp==1)\n            Sp=0;\n        end\n\n        if(S==1)\n            S=2;\n        end\n\n        direct111=0;\n        LastH=size(high,2);\n        LastM=size(middle,2);\n        LastL=size(lengt,2);\n\n        if(direct1==0)\n\n            rectangle('Position',[middle(LastM)+(lengt(LastL)/2),high(LastH)-1+extrawaystick,0.0001,1-extrawaystick]);\n\n            text(middle(LastM)+lengt(LastL)/2-0.1,high(LastH)-2.0+extrawaytext,num2str(double(objectorder(k))));\n\n            T=middle(LastM)+lengt(LastL)/2-0.1;\n            Maxi=max(Maxi,T);\n            Mini=min(Mini,T);\n        else\n\n            rectangle('Position',[middle(LastM)-(lengt(LastL)/2),high(LastH)-1+extrawaystick,0.0001,1-extrawaystick]);\n\n            text(middle(LastM)-lengt(LastL)/2-0.1,high(LastH)-2.0+extrawaytext,num2str(double(objectorder(k))));\n\n            T=middle(LastM)-lengt(LastL)/2-0.1;\n            Maxi=max(Maxi,T);\n            Mini=min(Mini,T);\n            direct1=0;\n            direct11=1;\n        end\n\n        if(high(LastH-1)==high(LastH))\n            high=high(1:LastH-2);\n            indices=indices(1:LastH-2);\n        else\n            high=high(1:LastH-1);\n            indices=indices(1:LastH-1);\n        end\n        LastH=size(high,2);\n\n        maxim=high(LastH);\n        index=indices(LastH);\n\n        if(LastH-1>=1)\n            Postmax=high(LastH-1);\n            Postindex=indices(LastH-1);\n        end\n\n        if(LastH-2>=1)\n            Post2max=high(LastH-2);\n            Post2index=indices(LastH-2);\n        end\n\n        if(index+1<=Postindex-1)\n            [Betweenmax,Betweenindex]=max(Heights(index+1:Postindex-1));\n            Betweenindex=Betweenindex+index+1-1;\n        else\n            Betweenmax=Postmax;\n            Betweenindex=Postindex;\n        end\n\n        if(Betweenmax~=Postmax)\n            Prevmax=Betweenmax;\n            Previndex=Betweenindex;\n        else\n            Prevmax=maxim;\n            Previndex=index;\n        end\n\n        if(high(LastH)>high(LastH-1))\n            righttree=1;\n        end\n\n        high(LastH)=Prevmax;\n        indices(LastH)=Previndex;\n\n        LastM=size(middle,2);\n        LastL=size(lengt,2);\n        Last=size(L,2);\n\n        if(LastM-1>=1)\n            middle=middle(1:LastM-1);\n        end\n\n        if(LastL-1>=1)\n            lengt=lengt(1:LastL-1);\n        end\n\n        if(Last-1>=1)\n            L=L(1:Last-1);\n        end\n\n        LastM=size(middle,2);\n        LastL=size(lengt,2);\n        Last=size(L,2);\n\n        if(Last>0)\n            while(maxim>L(Last))\n                lengt=lengt(1:Last-1);\n                L=L(1:Last-1);\n                Last=size(L,2);\n            end\n        end\n        LastL=size(lengt,2);\n\n        middle(LastM)=middle(LastM)+(lengt(LastL)/2);\n\n        if(Betweenmax~=Postmax)\n            Element=0;\n        else\n            Element=1;\n            middle(LastM)=middle(LastM)-(lengt(LastL)/2);\n        end\n\n        if(righttree==1 | direct11==1)\n            if(Spec==1)\n                Sp=1;\n            end\n\n            PrevMAX=L(1);\n            [maxim,index]=max(Heights(NbanFirst+1:number-1));\n            index=index+NbanFirst+1-1;\n\n            if(NbanFirst+1<=index-1)\n                [Prevmax,Previndex]=max(Heights(NbanFirst+1:index-1));\n                Previndex=Previndex+NbanFirst+1-1;\n            else\n                Prevmax=maxim;\n                Previndex=index;\n            end\n\n            if(index+1<=number-1)\n                [Postmax,Postindex]=max(Heights(index+1:number-1));\n                Postindex=Postindex+index+1-1;\n            else\n                Postmax=maxim;\n                Postindex=index;\n            end\n\n            if(index+1<=Postindex-1)\n                [Betweenmax,Betweenindex]=max(Heights(index+1:Postindex-1));\n                Betweenindex=Betweenindex+index+1-1;\n            else\n                Betweenmax=Postmax;\n                Betweenindex=Postindex;\n            end\n\n            if(Postindex+1<=number-1)\n                [Post2max,Post2index]=max(Heights(Postindex+1:number-1));\n                Post2index=Post2index+Postindex+1-1;\n            else\n                Post2max=Postmax;\n                Post2index=Postindex;\n            end\n\n\n            rectangle('Position',[PrevMID+(PrevLEN/2),maxim,0.0001,PrevMAX-maxim]);\n\n            LastM=size(middle,2);\n            LastMID=PrevMID+(PrevLEN/2);\n            PrevMID=LastMID;\n            middle=[];\n            middle(1)=LastMID;\n            LastM=size(middle,2);\n\n            high=[];\n            indices=[];\n            high=cat(2,high,[Post2max,Postmax,Betweenmax,maxim,Prevmax]);\n\n            indices=cat(2,indices,[Post2index,Postindex,Betweenindex,index,Previndex]);\n            LastH=size(high,2);\n\n            L=[];\n            L=cat(2,L,maxim);\n            Last=size(L,2);\n            lengt=[];\n            if(Postindex>Previndex)\n                if(M<extra)\n                    M=M+1;\n                end\n                lengt(1)=Postindex-Previndex+(extra-M);\n\n                rectangle('Position',[LastMID-lengt(1)/2,maxim,lengt(1),0.0001]);\n                direct1=1;\n            elseif(Postindex<=Previndex & Betweenmax==Postmax)\n                lengt(1)=1;\n                rectangle('Position',[LastMID-1/2,maxim,1,0.0001]);\n                %%%%%%%\n\n                rectangle('Position',[LastMID-1/2,maxim-1+extrawaystick,0.0001,1-extrawaystick]);\n                if(objectorder(k+1)>10)\n\n                    text(LastMID-1/2-0.25,maxim-2.0+extrawaytext,num2str(double(objectorder(k+1))));\n                    Mini=min(Mini,LastMID-1/2-0.25);\n                else\n\n                    text(LastMID-1/2-0.1,maxim-2.0+extrawaytext,num2str(double(objectorder(k+1))));\n                    Mini=min(Mini,LastMID-1/2-0.1);\n                end\n\n                rectangle('Position',[LastMID+1/2,maxim-1+extrawaystick,0.0001,1-extrawaystick]);\n\n                text(LastMID+1/2-0.1,maxim-2.0+extrawaytext,num2str(double(objectorder(k+2))));\n                Maxi=max(Maxi,LastMID+1/2-0.1);\n\n                k=k+2;\n            end\n            PrevLEN=lengt(1);\n            LastL=size(lengt,2);\n\n            if(Element==1)\n                Element=0;\n            end\n\n            if(direct11==1)\n                if(NbanFirst+1<index)\n                    middle=cat(2,middle,middle(LastM)-lengt(LastL)/2);\n                    LastM=size(middle,2);\n                    direct111=1;\n                    over=1;\n                end\n                direct11=0;\n            end\n\n            Special=1;\n            PrevMAX=maxim;\n        end\n        if(S==2 && k+1==number)\n\n            rectangle('Position',[LastMID+lengt(1)/2,PrevMAX-1+extrawaystick,0.0001,1-extrawaystick]);\n\n            text(LastMID+lengt(1)/2-0.1,PrevMAX-2.0+extrawaytext,num2str(double(objectorder(k+1))));\n            Maxi=max(Maxi,LastMID+lengt(1)/2-0.1);\n            Mini=min(Mini,LastMID+lengt(1)/2-0.1);\n            k=k+1;\n        end\n        over=1;\n    end\n    branch=0;\n\n\n    k=k+1;\n    NbanFirst=NbanFirst+1;\n\n\nend\naxis([Mini-1,Maxi+1,min(Heights)-5,max(Heights)+1]);\nXT=[];\nset(gca,'XTick',XT);\nset(gca,'XTickLabel',[]);\n\n%---\nfunction res=H(vector)\n\nlengt=size(vector,2);\nNvector=vector;\ni=1;\nfor i=1:lengt\n    for j=i+1:lengt\n        if (vector(i)==vector(j))\n            Nvector(j)=vector(j)+i*0.0001;\n            i=i+1;\n        end\n    end\nend\nres=Nvector;\n\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/LIBRA/tree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.568528951976034}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Program to reconstruct Phantom-Head Model using Algebraic    %%%%%%%%%\n%%%% Reconstruction Method.                                               %\n%%%%     This code is implemented By :                                   %%                                                    %%\n%%%%     AUTHOR: SAYEDALI A SHAIKH,                                     %%%\n%%%%     M.Tech.(CSE)                                                  %%%%\n%%%%     BVBCET,HUBLI-580031, E-mail Id:sayedalishaikh@gmail.com      %%%%%\n%%%%     Date: 28/08/2009                                       %%%%%%%%%%%\n% % %   Guided by: Mr Shrinivas D Desai                         %%%%%%%%%%%\n%%%     Associate Prof, Dept of ISE, BVBCET Hubli - 580031      %%%%%%%%%%%\n%%%%    sd_desai@bvb.edu    9845275066                          %%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%Call Function Inputs To Enter Following Parameters\n[size1,rotation,incr,s]=inputart();\n%Orginal Image\nI=phantom(size1);\n[r1,c1]=size(I);\nfigure,imshow(I);\ntitle('Original Phantom-Head Model Image ');\n\n%Guessed Image\nG=zeros(size(I));\n[r2,c2]=size(G);\nG2=zeros(size(G));\n\n% Call Function To Pad The Original Image\n[r3,c3,padIMG]=padO(I);\n%figure,imshow(padIMG);\nT1=padIMG;\n\n% Call Function To Pad The Guessed Image\n[r4,c4,padGIMG]=padG(G);\n%figure,imshow(padGIMG);\nT2=padGIMG;\n\n% Calculate The Correction Factor\n%Call Function To Choose The Denomenator Value w.r.t Angle and Increment\n\n[z]=chooseart(rotation,incr);\nz1=0;\nz2=incr;\nT3=T2;\nTHETA=0:incr:rotation;\ns1=length(THETA);\nfor a=1:s1,\n    org1=imrotate(T1,z1,'bilinear','crop');\n% Call Function To Calculate The Row Sum and Column Sum for Original Image\n    [rsumO,csumO]=calc_sum(org1,r3,z);\n% Call Function To Calculate The Row Sum and Column Sum for Guessed Image\n    [rsumG,csumG,padGIMG]=corr_factor(T2,r4,rsumO,csumO,r3,c3,s,z);\n    %figure,imshow(padGIMG);\n    G2=padGIMG;\n    %figure,imshow(G2);\n    T3=T3+G2;\n    figure,imshow(T3);\n    T3=imrotate(T3,z2,'bilinear','crop');\n    z1=z1+incr;\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/41709-reconstruction-of-image-from-projections-by-algebraic-reconstruction-technique/ARTCode/art2408.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5685289468920126}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\nfunction phiJump = cf_lognormjump(u,a,b,lambda,T)\n% log characteristic function for lognormal jumps \n    phiJump = lambda*T*(-a*u*1i + (exp(u*1i*log(1.0+a) ...\n        +0.5*b*b*u*1i.*(u*1i-1.0))-1.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/36966-risk-neutral-densities-for-financial-models/cf_lognormjump.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5685289361976693}}
{"text": "function [Im_DN,D_] = Denoise(Im_N,Sigma,K,n,Algo)\n% INPUT ARGUMENTS : Im_N - the noisy image (gray-level scale)\n%                   Sigma - the s.d. of the noise (assume to be white Gaussian).\n%                   K - the number of atoms in the representing dictionary.\n%                   n - Block Size n x n \n%% Data Stuff\nReduce_DC = 1;\n[N1,N2] = size(Im_N);\nC = 1.15;                       % Taken from the Paper Elad 06\nE_T = C*Sigma;                  % Required Average target Error in OMP\nif Sigma > 5\n    noIt = 10;\nelse\n    noIt = 5;\nend\nMaxTPatches = 62001;\n\n%% DCT Dictionary Creation\n% D_DCT = Dict_DCT(n,K);\nif Reduce_DC\n    D_DCT = odctdict(n^2,K+1);\n    D_DCT = D_DCT(:,2:end);\nelse\n    D_DCT = odctdict(n^2,K);\nend\n%% Block Patches to Columns\nfprintf('Learning Dictionary using %s\\n',Algo);\nif(prod([N1,N2]-n+1)> MaxTPatches)\n    randPermutation =  randperm(prod([N1,N2]-n+1));\n    selectedBlocks = randPermutation(1:MaxTPatches);\n\n    Y = zeros(n^2,MaxTPatches);\n    for i = 1:MaxTPatches\n        [row,col] = ind2sub(size(Im_N)-n+1,selectedBlocks(i));\n        currBlock = Im_N(row:row+n-1,col:col+n-1);\n        Y(:,i) = currBlock(:);\n    end\nelse\n    Y = im2col(Im_N,[n,n],'sliding');       % Signal Y with patches as Columns\nend\n\n%% Reducing DC component\nif (Reduce_DC)\n    vecOfMeans = mean(Y);\n    Y = Y-ones(size(Y,1),1)*vecOfMeans;\nend\n\n%% Data Whitening\n% Y = Data_Whiten(Y,1);\n\n%% Going into Dictionary Learning Algo for Training\nD_ = normc(D_DCT);\nfor it = 1:noIt \n    W = omp2(D_,Y,D_'*D_,(n*E_T));    %\n    switch lower(Algo)\n        case 'ksvd'\n            [D_,W] = Optimize_K_SVD(Y,D_,W);\n        case 's1'\n            alpha = .37;    \n            [D_,W] = Optimize_S1(Y,D_,W,alpha);\n        case 's1svd'\n            alpha = 100;    gamma = 1;\n            [D_,W] = Optimize_S1SVD(Y,D_,W,alpha,gamma);        \n        otherwise\n            error('Invalid Learning Method Specified');\n            break;\n    end\n    D_ = I_clearDictionary(D_,W,Y);\n    disp(['Iteration # ',num2str(it),' With average number of Coefficients = ',num2str(nnz(W)/size(W,2))])\nend \n\n%% DEnoising with the Trained Dictionary\ndisp('Denoising with the Trained Dictionary')\nY = im2col(Im_N,[n,n],'sliding'); \nif (Reduce_DC)\n    vecOfMeans = mean(Y);\n    Y = Y-ones(size(Y,1),1)*vecOfMeans;\nend\nCoefs = omp2(D_,Y,D_'*D_,(n*E_T));\nif (Reduce_DC)\n    Y = D_*Coefs + ones(size(Y,1),1) * vecOfMeans;\nelse\n    Y = D_*Coefs;\nend\n\n%% Generation and Averaging of The signal from Y (columns)\ncount = 1;\nWeight= zeros(N1,N2);\nIMout = zeros(N1,N2);\nidx = 1:size(Y,2);\n[rows,cols] = ind2sub(size(Im_N)-n+1,idx);\nfor i  = 1:length(cols)\n    col = cols(i); row = rows(i);\n    Y_ = reshape(Y(:,count),[n,n]);\n    IMout(row:row+n-1,col:col+n-1) = IMout(row:row+n-1,col:col+n-1)+Y_;\n    Weight(row:row+n-1,col:col+n-1) = Weight(row:row+n-1,col:col+n-1)+ones(n);\n    count = count+1;\nend;\nIm_DN = (Im_N+0.034*Sigma*IMout)./(1+0.034*Sigma*Weight);\n\nend\n\n%% KSVD implementation for Elad 2006\nfunction [D_,W] = Optimize_K_SVD(Y1,D_,W)\n    R = Y1 - D_*W;\n    for k=1:size(D_,2)\n        I = find(W(k,:));\n        Ri = R(:,I) + D_(:,k)*W(k,I);\n        [U,S,V] = svds(Ri,1,'L');\n        D_(:,k) = U;\n        W(k,I) = S*V';\n        R(:,I) = Ri - D_(:,k)*W(k,I);\n    end     \nend\n\n%% S1 implementation\nfunction [D,W] = Optimize_S1(Y,D,W,alpha)\n    Ek = Y - D * W;\n    for k = 1:size(D,2)       \n        Eki = Ek + D(:,k)*W(k,:);\n        for j = 1:2\n            G = D(:,k)'*Eki;   g = std(G);  G = G./g; % std = 1\n            %alpha2 = std(G)*alpha;\n            W(k,:) = g.*sign(G).*max(0,abs(G)-alpha);\n            D(:,k) = (Eki * W(k,:)')/norm(Eki * W(k,:)');\n        end\n%         nnz(W(k,:))\n        Ek = Eki - D(:,k)*W(k,:);\n    end\nend\n\n%% S1 WIth SVD Dictionary Update Stage\nfunction [D,W] = Optimize_S1SVD(Y,D,W,alpha,gamma)\n    Ek = Y - D * W;\n    for k = 1:size(D,2)       \n        Eki = Ek + D(:,k)*W(k,:);\n        % SVD\n%         [D(:,k),s,v] = svds(Eki,1,'L');\n%         W(k,:) = s*v';\n        % Power Iteration\n        for i = 1:5\n            W(k,:) = D(:,k)'*Eki;\n            D(:,k) = Eki*W(k,:)';    D(:,k) = D(:,k)/norm(D(:,k));  \n        end\n        for j = 1:2     \n            G = D(:,k)'*Eki;  g=1; %g = std(G);  G = G./g;    \n            alpha2 = std(G)*alpha;\n            W(k,:) = g.* sign(G).*max(0,(abs(G) - g.* alpha2./(abs(W(k,:)))));  %.^gamma\n            D(:,k) = Eki*W(k,:)'/norm(Eki*W(k,:)');\n        end\n%             nnz(W(k,:))\n        Ek = Eki - D(:,k)*W(k,:);\n    end\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u53bb\u566a\u7b97\u6cd5/S1SVDImageDenoising-master/Denoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571775, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5685289331293586}}
{"text": "function [ffun,flag] = limgrad(edge,elen,ffun,dfdx,imax)\n%LIMGRAD impose \"gradient-limits\" on a function defined over \n%an undirected graph.\n%   [FNEW] = LIMGRAD(EDGE,ELEN,FFUN,DFDX,ITER) computes a\n%   \"gradient-limited\" function FNEW on the undirected graph\n%   {EDGE,ELEN}, where EDGE is an NE-by-2 array of edge ind-\n%   ices, and ELEN is an NE-by-1 array of edge lengths. \n%   Gradients are limited over the graph edges, such that\n%\n%       ABS(FNEW(N2)-FNEW(N1)) <= ELEN(II) * DFDX,\n%\n%   where N1=EDGE(II,1) and N2=EDGE(II,2) are the two nodes \n%   in the II-TH edge. An iterative algorithm is used, swee-\n%   ping over an \"active-set\" of graph edges until converge-\n%   nce is achieved. A maximum of IMAX iterations are done.\n%\n%   [FNEW,FLAG] = LIMGRAD(...) also returns a boolean FLAG,\n%   with FLAG=TRUE denoting convergence. \n%\n%   See also LIMHFN2\n\n%   Darren Engwirda : 2017 --\n%   Email           : engwirda@mit.edu\n%   Last updated    : 18/04/2017\n\n%---------------------------------------------- basic checks    \n    if ( ~isnumeric(edge) || ...\n         ~isnumeric(elen) || ...\n         ~isnumeric(ffun) || ...\n         ~isnumeric(dfdx) || ...\n         ~isnumeric(imax) )\n        error('limgrad:incorrectInputClass' , ...\n            'Incorrect input class.') ;\n    end\n%---------------------------------------------- basic checks\n    if (ndims(edge) ~= +2 || ...\n        ndims(elen)  > +2 || ...\n        ndims(ffun)  > +2 || ...\n        numel(dfdx) ~= +1 || ...\n        numel(imax) ~= +1 )\n        error('limgrad:incorrectDimensions' , ...\n            'Incorrect input dimensions.');\n    end\n    if (size(edge,2) < +2 || ...\n        size(elen,2)~= +1 || ...\n        size(ffun,2)~= +1 || ...\n        size(edge,1)~= size(elen,1) )\n        error('limgrad:incorrectDimensions' , ...\n            'Incorrect input dimensions.');\n    end\n    \n    nnod = size(ffun,1) ;\n\n%---------------------------------------------- basic checks\n    if (dfdx < +0. || imax < +0)\n        error('limgrad:invalidInputArgument', ...\n            'Invalid input parameter.');\n    end\n    if (min(min(edge(:,1:2))) < +1 || ...\n            max(max(edge(:,1:2))) > nnod )\n        error('limgrad:invalidInputArgument', ...\n            'Invalid EDGE input array.') ;\n    end\n\n%-- IVEC(NPTR(II,1):NPTR(II,2)) are edges adj. to II-TH node\n    nvec = [edge(:,1); edge(:,2)];\n    ivec = [(1:size(edge,1))'; ...\n            (1:size(edge,1))'] ;\n\n   [nvec,pidx] = sort (nvec) ;\n    ivec       = ivec (pidx) ;\n    \n    mark = false(nnod,1) ;\n    mark(edge(:,1)) = true ;\n    mark(edge(:,2)) = true ;\n    \n    idxx = find(diff(nvec) > +0) ;\n    \n    nptr = zeros(nnod,2) ;\n    nptr(:,2) = -1 ;\n    nptr(mark,1) = [+1; idxx+1];\n    nptr(mark,2) = [idxx; nnod];\n    \n%----------------------------- ASET=ITER if node is \"active\"\n    aset = zeros(size(ffun,1),1) ;\n    \n%----------------------------- exhaustive 'til all satisfied \n    ftol = min(ffun) * sqrt(eps) ;\n    \n    for iter = +1 : imax\n    \n    %------------------------- find \"active\" nodes this pass\n        aidx = find(aset == iter - 1) ;\n        \n        if (isempty(aidx)), break; end\n      \n    %------------------------- reorder => better convergence\n       [~,idxx] = sort(ffun(aidx)) ;\n        \n        aidx = aidx(idxx);\n       \n    %------------------------- visit adj. edges and set DFDX\n        for ipos = 1 : length(aidx)\n            npos = aidx(ipos) ;\n            for jpos = nptr(npos,1) ...\n                     : nptr(npos,2)\n                \n                epos = ivec(jpos,1) ;\n                \n                nod1 = edge(epos,1) ;\n                nod2 = edge(epos,2) ;\n\n            %----------------- calc. limits about min.-value\n                if (ffun(nod1) > ffun(nod2))\n                \n                fun1 = ffun(nod2) ...\n                     + elen(epos) * dfdx ;\n                \n                if (ffun(nod1) > fun1+ftol)\n                    ffun(nod1) = fun1;\n                    aset(nod1) = iter;\n                end\n\n                else\n                \n                fun2 = ffun(nod1) ...\n                     + elen(epos) * dfdx ;\n                    \n                if (ffun(nod2) > fun2+ftol)\n                    ffun(nod2) = fun2;\n                    aset(nod2) = iter;\n                end\n                \n                end\n                 \n            end\n        end\n        \n    end\n     \n    flag = (iter < imax) ;\n    \nend\n\n\n\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/limgrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5685289255033257}}
{"text": "function imResult = blendMode_LinearDodge(A, B, offsetW, offsetH)\n%% Linear Dodge blending mode: simply sums the values in the two layers. \n%   Blending with white gives white. Blending with black does not change \n%   the image.  \n% \n% Input:\n%       A       -       Base Image\n%       B       -       Top Image\n%   offsetW     -   move picture B horizontally in respect to the top-left\n%                   corner of picture A. Default value = 1.\n%   offsetH     -   move picture B vertically in respect to the top-left\n%                   corner of picture A. Default value = 1.\n%\n% Output:\n%       imResult    -   Result of the blending, having the same size of the\n%                       Base Image A.\n% \n\n%% Check Input\na = size(A);\nb = size(B);\nblendMode_checkInput(nargin, a, b, func2str(@blendMode_LinearDodge));\n\nif nargin < 3\n    offsetW = 1;\n    offsetH = 1;\nend\n\nif nargin < 4\n    offsetH = 1;\nend\n\n%% Implementation\nimResult = A;\n\nif (((offsetW ~= 1) || (offsetH ~= 1)) || (sum(a == b) ~= length(a)))\n    [A, B] = blendMode_ResizeImages(A, B, a, b, offsetW, offsetH);\nend\n\nC = blendMode_Add(A, B, offsetW, offsetH);\n\nif (((offsetW ~= 1) || (offsetH ~= 1)) || (sum(a == b) ~= length(a)))\n    imResult = blendMode_CreateResult(imResult, C, offsetW, offsetH);\nelse\n    imResult = C;\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/43122-blend-images/blendModes/blendMode_LinearDodge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5684943189785584}}
{"text": "% @Author: aaronmishkin\n% @Date:   2018-06-07T19:03:42-07:00\n% @Email:  amishkin@cs.ubc.ca\n% @Last modified by:   aaronmishkin\n% @Last modified time: 2018-07-26T13:09:11-07:00\n\n\n\nfunction [y, X, y_te, X_te] = get_data_log_reg(name, seed)\n%name: name of a dataset\n%seed: seed used for creating a train/test set\n%y (y_te): labels for a train (test) set\n%X (X_te): features for a train (test) set\n%Note: for classification problems, we use 0-1 encoding in labels.\nswitch name\ncase 'murphy_synth'\n    setSeed(seed)\n    N=30;\n    D=2;\n    mu1=[ones(N,1) 5*ones(N,1)];\n    mu2=[-5*ones(N,1) 1*ones(N,1)];\n    class1_std = 1;\n    class2_std = 1.1;\n    X = [class1_std*randn(N,2)+mu1;2*class2_std*randn(N,2)+mu2];\n    y = [ones(N,1);zeros(N,1)];\n    y = 2*y-1;\n    % Set the test set to the be same as the training set.\n    X_te = X; y_te = y;\ncase 'synth'\n  setSeed(seed);\n  N = 5000;\n  D = 2;\n  s2 = .01;\n  X = randn(N,D);\n  D = D + 1;\n  w = [0.1; -1; +1];\n  eta = [ones(N,1) X]*w + s2*randn(N,1);\n  y = sign(eta);\n  [X, y, X_te, y_te] = split_data(y, X, 0.5);\n\ncase {'a2a','a3a','a4a','a5a','a6a','a7a'}\n    setSeed(seed);\n  load(name);\n  [N,D] = size(X);\n  X = [ones(N,1) X];\n  [N_te,D] = size(X_te);\n  X_te = [ones(N_te,1) X_te];\n  y = (y+1)/2;\n  y_te = (y_te+1)/2;\n  assert ( length(unique(abs(y))) == 2)\n  assert ( length(unique(abs(2*y-1))) == 1)\n\ncase {'svmguide3'}\n    setSeed(seed);\n  load(name);\n  [N,D] = size(X);\n  X = [ones(N,1) X];\n  [N_te,D] = size(X_te);\n  X_te = [ones(N_te,1) X_te];\n  y = (y+1)/2;\n  y_te = (y_te+1)/2;\n  assert ( length(unique(abs(y))) == 2)\n  assert ( length(unique(abs(2*y-1))) == 1)\n\ncase 'svmguide1'\n    setSeed(seed);\n  load(name);\n  [N,D] = size(X);\n  X = [ones(N,1) X];\n  [N_te,D] = size(X_te);\n  X_te = [ones(N_te,1) X_te];\n  assert ( length(unique(abs(y))) == 2)\n  assert ( length(unique(abs(2*y-1))) == 1)\n\ncase 'a1a'\n    setSeed(seed);\n  load(name);\n  [N,D] = size(X);\n  X = [ones(N,1) X zeros(N,4)];\n  [N_te,D] = size(X_te);\n  X_te = [ones(N_te,1) X_te];\n  y = (y+1)/2;\n  y_te = (y_te+1)/2;\n  assert ( length(unique(abs(y))) == 2)\n  assert ( length(unique(abs(2*y-1))) == 1)\n\ncase {'colon-cancer'}\n  load(name);\n  [N,D] = size(X);\n  X = [ones(N,1) X];\n  y = (y+1)/2;\n  setSeed(seed);\n  [X, y, X_te, y_te] = split_data(y, X, 0.5);\n\ncase {'duke'}\n  load(name);\n  [N,D] = size(X);\n  X = [ones(N,1) full(X)];\n  y = (y+1)/2;\n  setSeed(seed);\n  [X, y, X_te, y_te] = split_data(y, X, 0.5);\n\ncase {'leukemia'}\n    setSeed(seed);\n  load(name);\n  [N,D] = size(X);\n  X = [ones(N,1) X];\n  [N_te,D] = size(X_te);\n  X_te = [ones(N_te,1) X_te];\n  y = (y+1)/2;\n  y_te = (y_te+1)/2;\n  assert ( length(unique(abs(y))) == 2)\n  assert ( length(unique(abs(2*y-1))) == 1)\n\ncase {'gisette_scale'}\n  load(name);\n  X = [X; X_te];\n  y = [y; y_te];\n  [N,D] = size(X);\n  X = [ones(N,1) full(X)];\n  y = (y+1)/2;\n  unique(y)\n  setSeed(seed);\n  [X, y, X_te, y_te] = split_data(y, X, 0.5);\n\ncase {'covtype_binary_scale'}\n  load(name);\n  [N,D] = size(X);\n  X = [ones(N,1) full(X)];\n  y = y-1;\n  setSeed(seed);\n  [X, y, X_te, y_te] = split_data(y, X, 0.5);\n  assert ( length(unique(abs(y))) == 2)\n  assert ( length(unique(abs(2*y-1))) == 1)\n\ncase {'SUSY'}\n  load('SUSY.amat','-mat');\n  [N,D] = size(X);\n  X = [ones(N,1) full(X)];\n  setSeed(seed);\n  [X, y, X_te, y_te] = split_data(y, X, 0.5);\n  assert ( length(unique(abs(y))) == 2)\n  assert ( length(unique(abs(2*y-1))) == 1)\n\ncase {'australian_scale', 'diabetes_scale'}\n  load(name);\n  [N,D] = size(X);\n  X = [ones(N,1) full(X)];\n  y = (y+1)/2;\n  setSeed(seed);\n  [X, y, X_te, y_te] = split_data(y, X, 0.5);\n  assert ( length(unique(abs(y))) == 2)\n  assert ( length(unique(abs(2*y-1))) == 1)\n\ncase {'breast_cancer_scale'}\n    setSeed(seed);\n  load(name);\n  [N,D] = size(X);\n  X = [ones(N,1) full(X)];\n  y = (y-2)/2;\n  [X, y, X_te, y_te] = split_data(y, X, 0.5);\n  assert ( length(unique(abs(y))) == 2)\n  assert ( length(unique(abs(2*y-1))) == 1)\n\n\ncase 'usps_3vs5'\n  setSeed(seed);\n  load('usps_resampled');\n  y = ([train_labels test_labels] + 1)/2; % 1540 obs\n  X = ([train_patterns test_patterns]);\n  y = sum(bsxfun(@times, y, [0:9]'));\n  idx = find(or((y==3), (y==5)));\n  y = y(idx);\n  y = (y==5);\n  X = X(:,idx);\n  X = X'; % 1540x256\n  [N,D] = size(X);\n  y = y(:); % in 0/1 encoding\n  X = [ones(N,1) full(X)];\n  [X, y, X_te, y_te] = split_data(y, X, 0.5);\n%\n%   y = 2*y - 1;\n%   y_te = 2*y_te - 1;\n%\n\notherwise\n  error('no such name');\nend\nend\n\nfunction [XTr, yTr, XTe, yTe] = split_data(y, X, prop)\n\n  N = size(y,1);\n\tidx = randperm(N);\n  Ntr = floor(prop * N);\n\tidxTr = idx(1:Ntr);\n\tidxTe = idx(Ntr+1:end);\n  XTr = X(idxTr,:);\n  yTr = y(idxTr);\n  XTe = X(idxTe,:);\n  yTe = y(idxTe);\nend\n", "meta": {"author": "emtiyaz", "repo": "vadam", "sha": "d8ea6bdc82ac8765b873578660e1d9ba95c701d4", "save_path": "github-repos/MATLAB/emtiyaz-vadam", "path": "github-repos/MATLAB/emtiyaz-vadam/vadam-d8ea6bdc82ac8765b873578660e1d9ba95c701d4/matlab/lib/log_reg/get_data_log_reg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5684943072646451}}
{"text": "function C = DiagCorr(a,b)\n% e.g. dim of A: nFrames*nCells, like in Matlab 'corr' function\nAn=bsxfun(@minus,a,mean(a,1));\nBn=bsxfun(@minus,b,mean(b,1));\nAn=bsxfun(@times,An,1./sqrt(sum(An.^2,1)));\nBn=bsxfun(@times,Bn,1./sqrt(sum(Bn.^2,1)));\nC=sum(An.*Bn,1);\nend", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/helper functions/DiagCorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5684821903206536}}
{"text": "function [ zsl_accuracy, Y_hit5 ] = zsl_el( S_est, S_te_gt, param)\n% ZSL_EL calculates zero-shot classification accuracy\n%\n% INPUT: \n%    S_est: estimated semantic labels\n%    S_te_gt: ground truth semantic labels\n%    param: other parameters\n%\n% Output:  \n%    zsl_accuracy: zero-shot classification accuracy (per-sample)\n\ndist     =  1 - (pdist2(S_est, NormalizeFea(S_te_gt')', 'cosine'));\nY_hit5   = zeros(size(dist,1),param.HITK);\nfor i    = 1:size(dist,1)\n    [~, I] = sort(dist(i,:),'descend');\n    Y_hit5(i,:) = param.testclasses_id(I(1:param.HITK));    \nend\n\nn = 0;\nfor i  = 1:size(dist,1)\n    if ismember(param.test_labels(i),Y_hit5(i,:))\n        n = n + 1;\n    end\nend\nzsl_accuracy = n/size(dist,1);\n\nend\n\n", "meta": {"author": "Elyorcv", "repo": "SAE", "sha": "b5620ba1c02e23f7d02c741a974f0839df53ed39", "save_path": "github-repos/MATLAB/Elyorcv-SAE", "path": "github-repos/MATLAB/Elyorcv-SAE/SAE-b5620ba1c02e23f7d02c741a974f0839df53ed39/library/zsl_el.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5684821781618794}}
{"text": "function dataout=modeWPE_NLMS_BSS(nummics, numrefs, datain)\n%\n% Perform wpe, nlms, and bss.\n% nummics:              no. of mic channels\n% numrefs:              no. of reference channels\n% datain:               input data\n% dataout:              output data\n%\n\nfs=16000;\n\n%% perform wpe\naddpath('wpe_v1.33');\n\nmic=datain(:, 1:2);\nref=datain(:, 3);\n\ncfgs='wpe_v1.33/settings/local.m';\nearly=wpe(mic, cfgs); \n\n%% perform nlms\naddpath('Speex-AEC-matlab-master');\n\n%    Usage: \n%\n%       speex_mdf_out = speex_mdf(Fs, u, d, filter_length, frame_size, dbg_var_name);\n%       \n%       Fs                  sample rate\n%       u                   speaker signal, column vector in range [-1; 1]\n%       d                   microphone signal, column vector in range [-1; 1]\n%       filter_length       typically 250ms, i.e. 4096 @ 16k FS \n%                           must be a power of 2\n%       frame_size          typically 8ms, i.e. 128 @ 16k Fs \n%                           must be a power of 2\n%       dbg_var_name        internal state variable name to trace. \n%                           Default: 'st.leak_estimate'.\n%\n%    Jonathan Rouach <jonr@waves.com>\n%    \nfilter_length=512;\nframe_size=256;\nnearend1=speex_mdf(fs, ref, early(:, 1), filter_length, frame_size);\nnearend2=speex_mdf(fs, ref, early(:, 2), filter_length, frame_size);\nnearend=[nearend1.e, nearend2.e];\n\n%% perform stft\naddpath('stft2');\n% fft size\nfftsize=512;\nstftshift=fftsize/2;\n\nM=nummics;\nN=M;\n\nXtf=cell(M, 1);\nfor m=1:M\n    Xtf{m}=stft(nearend(:, m), stftshift, fftsize, false);\nend\n[K, T]=size(Xtf{1});\n\nYtf=cell(M, 1);\nfor m=1:M\n    Ytf{m}=zeros(K, T);\nend\n\n%% params\n% forgetting factor for bss\nBF_FORGET=0.999;\n% the shape parameter of the source prior\nGAMMA=0.2;\n%\n% used to keep stable\n%\nVAR_BIAS=0.01;\nSTABLE_EPS=1e-3;\nBF_DIAGLOAD=1e-6;\n\n%% space for bss\n% the weighted correlation matrices\nC1=cell(K, 1);\nC2=cell(K, 1);\nfor k=1:K\n    C1{k}=STABLE_EPS*eye(M, M);\n    C2{k}=STABLE_EPS*eye(M, M);\nend\n\n% demixing matrices\nDemix=cell(K, 1);\nfor k=1:K\n    Demix{k}=eye(N, M);\nend\n\n%% perform bss\nfor tau=1:T\n    %% perform bss\n    Bssout=zeros(K, M);\n    \n    %\n    % calculate nonlinearity\n    %\n    phi1=0;\n    phi2=0;\n    \n    for k=1:K\n        x=zeros(M, 1);\n        for m=1:M\n            x(m)=Xtf{m}(k, tau);\n        end\n        \n        y=Demix{k}*x;\n        % output data\n        Bssout(k, :)=y.';\n        \n        phi1=phi1+abs(y(1))^2;\n        phi2=phi2+abs(y(2))^2;\n    end\n    \n    phi1=(1-BF_FORGET)*(phi1+VAR_BIAS)^((GAMMA-2)/2);\n    phi2=(1-BF_FORGET)*(phi2+VAR_BIAS)^((GAMMA-2)/2);\n    \n    % update the demixing matrices\n    for k=1:K\n        %\n        % accumulate the weighted correlation\n        %\n        x=zeros(M, 1);\n        for m=1:M\n            x(m)=Xtf{m}(k, tau);\n        end\n        \n        C1{k}=BF_FORGET*C1{k}+phi1*(x*x');\n        C2{k}=BF_FORGET*C2{k}+phi2*(x*x');\n        \n        %\n        % solve gev problem\n        %\n        [Ev, Ed]=eig(C2{k}+BF_DIAGLOAD*eye(M, M), C1{k}+BF_DIAGLOAD*eye(M, M));\n        if Ed(1, 1)>=Ed(2, 2)\n            e1=Ev(:, 1);\n            e2=Ev(:, 2);\n        else \n            e1=Ev(:, 2);\n            e2=Ev(:, 1);\n        end\n    \n        D=[e1'; e2'];\n        \n        %\n        % solve the scaling ambiguity\n        %\n        A=inv(D);\n        \n        if abs(A(1, 1))>=abs(A(2, 1))\n            a1=A(1, 1);\n        else\n            a1=A(2, 1);\n        end\n        \n        if abs(A(2, 2))>=abs(A(1, 2))\n            a2=A(2, 2);\n        else\n            a2=A(1, 2);\n        end\n        \n        D=diag([a1; a2])*D;\n        Demix{k}=D;\n    end\n    \n    for m=1:M\n        Ytf{m}(:, tau)=Bssout(:, m);\n    end\nend\n\n%% perform istft and output signal\ndataout=zeros(dataLength(T, stftshift, fftsize ), N);\nfor n=1:N\n    dataout(:, n)=istft(Ytf{n}, stftshift, false);\nend\n\nend\n", "meta": {"author": "nay0648", "repo": "unified2021", "sha": "006d3d99da7c0f9c535994ef58355ef36a83d510", "save_path": "github-repos/MATLAB/nay0648-unified2021", "path": "github-repos/MATLAB/nay0648-unified2021/unified2021-006d3d99da7c0f9c535994ef58355ef36a83d510/Experiment/modeWPE_NLMS_BSS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.568472158575055}}
{"text": "domain = [-1,1,-1,1,-1,1];\nbc = [1,1,1,1,1,1]; % Dirichelet BC\n\nload('BoxTorusMesh.mat')\n% epsm = 8.85*10^(-5)*5;\n% epsp = 8.85*10^(-5);\n% sigm = 100;\n% sigp = 1;\n% mum = (4*pi);\n% mup = (4*pi)*2;\n% x0=0; y0=0; z0=-0.3; r1=0.2; r2=pi/5; omega = 20; stre = 1;\n% pde = TorusTime1(mum,mup,sigm,sigp,epsm,epsp,omega,stre,x0,y0,z0,r1,r2);\n% TEND = 0.1;\nepsm = 8.854*10^(-2);\nepsp = 8.854*10^(-3);\nsigm = 10;%100;\nsigp = 1;%1;\nmum = 4*pi*5;\nmup = 4*pi;\nx0=0; y0=0; z0=-0.3; r1=0.2; r2=pi/5; omega = 1; a = omega*sqrt(epsp*mup); b= 120; intPt = -1;\npde = TorusTimeInitial3(mum,mup,sigm,sigp,epsm,epsp,omega,x0,y0,z0,r1,r2,a,b,intPt);\nTEND = 0.8;\nInitCond = 1;\nBDCond = 1;\n\nnx = 64;  h=(domain(2) - domain(1))/nx;\nny = nx;\nnz = nx;\n    \nNtime = ceil(TEND/sqrt(8.854*10^(-3)*4*pi*2))*5*nx;%ceil(sqrt(nx));\ndeltaT = TEND/Ntime;\nmesh = enrichMesh3D(mesh,0);\nfem = genNedFEM3D(mesh,bc);\nbm = epsm/deltaT^2 + sigm/(2*deltaT);\nbp = epsp/deltaT^2 + sigp/(2*deltaT);\nam = mum^(-1); ap = mup^(-1);\n\nS = globMatrixNedFit3D(am,ap,1,mesh,fem,fem);\nMe = globMatrixNedFit3D(epsm,epsp,0,mesh,fem,fem);\nMs = globMatrixNedFit3D(sigm,sigp,0,mesh,fem,fem);\nAtotal = Me/deltaT^2 + Ms/(2*deltaT) + S/2;\n\nNdof = size(mesh.e,1);\nbdidx = zeros(Ndof,1);\nisBdEdge = true(Ndof,1);\nisBdEdge(fem.mapper) = false;\nbdidx(isBdEdge) = 1;\nTbd = spdiags(bdidx,0,Ndof,Ndof);\nT = spdiags(1-bdidx,0,Ndof,Ndof);\nA = T*Atotal*T + Tbd;\n\nif InitCond == 0\n    uppre = zeros(size(mesh.e,1),1);\n    upre = zeros(size(mesh.e,1),1);\nelseif InitCond ~=0\n    tu1 = sum(feval(pde.E1,fem.gex,fem.gey,fem.gez,0).*fem.gew,2);\n    tu2 = sum(feval(pde.E2,fem.gex,fem.gey,fem.gez,0).*fem.gew,2);\n    tu3 = sum(feval(pde.E3,fem.gex,fem.gey,fem.gez,0).*fem.gew,2);\n    tgt = mesh.p(mesh.e(:,2),:) - mesh.p(mesh.e(:,1),:);\n    tgt = tgt./sum(tgt.^2,2).^(1/2);\n    uppre = tu1.*tgt(:,1) + tu2.*tgt(:,2) + tu3.*tgt(:,3);\n    tu1 = sum(feval(pde.Et1,fem.gex,fem.gey,fem.gez,0).*fem.gew,2);\n    tu2 = sum(feval(pde.Et2,fem.gex,fem.gey,fem.gez,0).*fem.gew,2);\n    tu3 = sum(feval(pde.Et3,fem.gex,fem.gey,fem.gez,0).*fem.gew,2);\n    upretmp = tu1.*tgt(:,1) + tu2.*tgt(:,2) + tu3.*tgt(:,3);\n    upre = uppre + deltaT*upretmp;\nend\n\nUHfit =zeros(size(mesh.e,1),ceil(Ntime/10)+2);\nNumStep = 0;\nCurrentT = 0;\nSaveCount = 0;\n\ntID1 = (mesh.tLoc == 1);\ntID2 = (mesh.tLoc == 2);\ne1tmp = unique(reshape(mesh.t_e(tID1,:),[],1));\ne2tmp = unique(reshape(mesh.t_e(tID2,:),[],1));\neInt = intersect(e1tmp,e2tmp);\neid1 = setdiff(e1tmp,eInt);\neid2 = setdiff(e2tmp,eInt);\nalpha = am*ones(size(mesh.e,1),1);\nalpha(eid2) = ap;\nalpha(eInt) = (am+ap)/2;\nbeta = bm*ones(size(mesh.e,1),1);\nbeta(eid2) = bp;\nbeta(eInt) = (bm+bp)/2;\nNEdof = size(A,1);\n\nwhile CurrentT < TEND\n    \n    NumStep = NumStep + 1;\n    CurrentT = CurrentT + deltaT;\n    fm1Current = @(x,y,z) pde.fm1(x,y,z,CurrentT);\n    fm2Current = @(x,y,z) pde.fm2(x,y,z,CurrentT);\n    fm3Current = @(x,y,z) pde.fm3(x,y,z,CurrentT);\n    fp1Current = @(x,y,z) pde.fp1(x,y,z,CurrentT);\n    fp2Current = @(x,y,z) pde.fp2(x,y,z,CurrentT);\n    fp3Current = @(x,y,z) pde.fp3(x,y,z,CurrentT);\n    rhsF1 = globNedFitRHS3D(fm1Current,fp1Current, mesh, fem, 0, 1);\n    rhsF2 = globNedFitRHS3D(fm2Current,fp2Current, mesh, fem, 0, 2);\n    rhsF3 = globNedFitRHS3D(fm3Current,fp3Current, mesh, fem, 0, 3);\n    rhsFCurrent = rhsF1 + rhsF2 + rhsF3;\n    \n    if BDCond == 0\n        tuCurrent = zeros(size(mesh.e,1),1);\n    elseif BDCond ~= 0\n        exactu1Current = @(x,y,z) pde.E1(x,y,z,CurrentT);\n        exactu2Current = @(x,y,z) pde.E2(x,y,z,CurrentT);\n        exactu3Current = @(x,y,z) pde.E3(x,y,z,CurrentT);\n        tu1 = sum(feval(exactu1Current,fem.gex,fem.gey,fem.gez).*fem.gew,2);\n        tu2 = sum(feval(exactu2Current,fem.gex,fem.gey,fem.gez).*fem.gew,2);\n        tu3 = sum(feval(exactu3Current,fem.gex,fem.gey,fem.gez).*fem.gew,2);\n        tgt = mesh.p(mesh.e(:,2),:) - mesh.p(mesh.e(:,1),:);\n        tgt = tgt./sum(tgt.^2,2).^(1/2);\n        tuCurrent = tu1.*tgt(:,1) + tu2.*tgt(:,2) + tu3.*tgt(:,3);\n    end\n    \n    ub = tuCurrent;\n    ub(fem.mapper) = 0;\n    rhsB = Atotal*ub;\n    JCurrent = rhsFCurrent - rhsB;\n    %JCurrent(isBdEdge) = tuCurrent(isBdEdge);\n    \n    fcurrent = Me*(2*upre - uppre)/deltaT^2 + Ms*uppre/(2*deltaT) - S*uppre/2 + JCurrent;\n    fcurrent(isBdEdge) = tuCurrent(isBdEdge);\n    \n    option.outsolver = 'cg';\n    option.alpha = alpha;\n    option.beta = beta;\n    option.solver = 'amg';\n    edge = mesh.e;\n    option.smoother = 'BD';\n    option.blklevel = 0;\n    option.blkId = NEdof;\n    [x,info] = amgMaxwellinterface2(A,fcurrent,mesh.p,edge,option);\n    uppre = upre;\n    upre = x;\n    \n    if mod(NumStep,40) == 0\n        UHfit(:,SaveCount+1) = uppre;\n        UHfit(:,SaveCount+2) = upre;\n        SaveCount = SaveCount+2;\n        save('UHfit1','UHfit','-v7.3');\n        disp('save data')\n    end\n    \nend\n\nsave('UHfit1','UHfit'); ", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/MaxwellSolverFit1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.568427903376281}}
{"text": "function out = IN_AutoMutualInfo(y,timeDelay,estMethod,extraParam)\n% IN_AutoMutualInfo     Time-series automutual information\n%\n%---INPUTS:\n%\n% y: input time series (column vector)\n%\n% timeDelay: time lag for automutual information calculation\n%\n% estMethod: the estimation method used to compute the mutual information:\n%           (*) 'gaussian'\n%           (*) 'kernel'\n%           (*) 'kraskov1'\n%           (*) 'kraskov2'\n%\n% cf. Kraskov, A., Stoegbauer, H., Grassberger, P., Estimating mutual\n% information: http://dx.doi.org/10.1103/PhysRevE.69.066138\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,\n% <http://www.benfulcher.com>\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 <http://www.gnu.org/licenses/>.\n% ------------------------------------------------------------------------------\n\n% ------------------------------------------------------------------------------\n% Check inputs:\n% ------------------------------------------------------------------------------\nif nargin < 2 || isempty(timeDelay)\n    timeDelay = 1;\nend\nif ischar(timeDelay) && ismember(timeDelay,{'ac','tau'})\n    timeDelay = CO_FirstCrossing(y,'ac',0,'discrete');\nend\n\nif nargin < 3 || isempty(estMethod)\n    estMethod = 'kernel';\nend\n\nif nargin < 4\n    extraParam = [];\nend\n\nN = length(y);\ndoPlot = false; % plot outputs to screen\nminSamples = 5; % minimum 5 samples to compute a mutual information (could make higher?)\n\n% Ensure y is a column vector\nif size(y,2) > size(y,1)\n    warning('Please input a column vector for y')\n    y = y';\nend\n\n% ------------------------------------------------------------------------------\n% Loop over time delays if a vector\nnumTimeDelays = length(timeDelay);\namis = nan(numTimeDelays,1);\n\nif numTimeDelays > 1\n    timeDelay = sort(timeDelay);\nend\n\n% Initialize miCalc object (needs to be reinitialized within the loop for kraskov):\nif ~strcmp(estMethod,'gaussian')\n    miCalc = IN_Initialize_MI(estMethod,extraParam,false); % NO ADDED NOISE!\nend\n\nfor k = 1:numTimeDelays\n\n    % Check enough samples to compute an automutual information\n    if timeDelay(k) > N - minSamples\n        % Time series is too short -- keep the remaining values as NaNs\n        break\n    end\n\n    % Form the time-delay vectors y1 and y2\n    y1 = y(1:end-timeDelay(k));\n    y2 = y(1+timeDelay(k):end);\n\n    if strcmp(estMethod,'gaussian')\n        r = corr(y1,y2,'type','Pearson');\n        amis(k) = -0.5*log(1 - r^2);\n    else\n        % Reinitialize for Kraskov:\n        miCalc.initialise(1,1);\n\n        % Set observations to time-delayed versions of the time series:\n        miCalc.setObservations(y1,y2);\n\n        % Compute:\n        amis(k) = miCalc.computeAverageLocalOfObservations();\n    end\n\n    % Plot:\n    if doPlot\n        plot(y1,y2,'.k')\n        title(sprintf('ami = %.3f',amis(k)))\n        pause(0.1)\n    end\nend\n\nif any(isnan(amis))\n    warning(['Time series (N=%u) is too short for automutual information calculations',...\n                ' up to lags of %u'],N,max(timeDelay))\nend\n\nif doPlot\n    plot(amis,'-k')\nend\n\n%-------------------------------------------------------------------------------\n% Outputs:\n%-------------------------------------------------------------------------------\nif numTimeDelays == 1\n    out = amis; % a scalar\nelse\n    % A structure\n    for k = 1:numTimeDelays\n        out.(sprintf('ami%u',timeDelay(k))) = amis(k);\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/Operations/IN_AutoMutualInfo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5684010708266296}}
{"text": "% Function that optimizes Pose given an initial solution of the rotation only\n%\n% IMPORTANT: THIS FUNCTION ONLY DEALS WITH THE ORTHOGRAPHIC CASE RIGHT NOW\n%\n% This function optimizes the pose estimation of one camera with respect to\n% another given only the 2 corresponding views.  The data is supposed to be\n% centered and only the rotation has to be estimated. I it is here \n% performed using simple gradient descent.\n%\n% The following code explains how the code to compute the\n% error/gradient/hessian was created using matlab symbolic toolbox.\n%\n% Vincent's Structure From Motion Toolbox      Version 3.0\n% Copyright (C) 2008-2011 Vincent Rabaud.  [vrabaud-at-cs.ucsd.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the GPL [see external/gpl.txt]\n\n%%%%%  Infimum in TSFM   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nsyms a b c cc d dd real\n\nR = [ a^2+b^2-c^2-d^2 2*b*c-2*a*d 2*a*c+2*b*d; ...\n 2*a*d+2*b*c a^2-b^2+c^2-d^2 2*c*d-2*a*b; ...\n 2*b*d-2*a*c 2*a*b+2*c*d a^2-b^2-c^2+d^2 ]/(a^2+b^2+c^2+d^2);\nR = R(1:2,:);\ndRa = simple(diff(R,a));\ndRb = simple(diff(R,b));\ndRc = simple(diff(R,c));\ndRd = simple(diff(R,d));\nRtR = R'*R;\nRtdRa = R'*simple(diff(R,a));\nRtdRb = R'*simple(diff(R,b));\nRtdRc = R'*simple(diff(R,c));\nRtdRd = R'*simple(diff(R,d));\n\n\n%%%%%  Rest of the code    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nl = [ R(:); RtR(:) ]\nl = [ R(:); dRa(:); dRb(:); dRc(:); dRd(:); RtR(:); RtdRa(:); RtdRb(:); RtdRc(:); RtdRd(:) ];\nl = simple( l );\n\nmaple restart;\ncom = 'res := [ ';\nk = 1;\nfor j = 1 : 6\n  com = [ com 'r[' num2str(j) ']=' char(l(k)) ', '];\n  k = k + 1;\nend\nkk=1\nfor i = 1 : 4\n  for j = 1 : 6\n\tcom = [ com 'dR[' num2str(kk) ']=' char(l(k)) ', '];\n\tk = k + 1;\n\tkk = kk + 1;\n  end\nend\nfor j = 1 : 9\n  com = [ com 'rtR[' num2str(j) ']=' char(l(k)) ', '];\n  k = k + 1;\nend\nkk = 1;\nfor i = 1 : 4\n  for j = 1 : 9\n    com = [ com 'rtDR[' num2str(kk) ']=' char(l(k)) ', '];\n\tk = k + 1;\n\tkk = kk + 1;\n\tend\nend\ncom = [ com(1:end-2) '];' ];\n\n%%%%%  Below is the code to generate C-code    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Mupad try, but it sucks ...\n%  reset(symengine);\n%  out = evalin(symengine, [ 'opts := generate::optimize([R=expr(' char(Rp') ') ]);' ] );\n%  \n%  out = evalin(symengine, [ 'opts := generate::optimize([R=expr(' char(Rp') '), dR=expr(' char(l(:,3:10)) '), ddR=expr(' char(l(:,11:end)) ')]);' ] );\n%  evalin(symengine, [ ':=rhs(opts[-1]);' ] );\n%  \n%  \n%  \n%  out = [ char(evalin(symengine, [ 'generate::C(opts[1..-2]);' ] )) ...\n%    char( evalin(symengine, [ 'generate::C(rhs(opts[-1]))' ] )) ];\n%  out = strrep( out, '\"', '' );\n%  out = strrep( out, [ var '[0][' ], [ var '[' ] );\n\n\n\n\n%%% now, save your crazy array into the res variable\nmaple( com );\n\n%  %%% cost of the assigments with no optimization\n%  maple('codegen[cost](res)')\n%  % maple( 'opt1 := [codegen[optimize](l)]' );\n%  %%% cost of the assigment with the normal optimization\n%  in = [ 'l:=' char( l ) ]; maple( in ); maple('codegen[cost](codegen[optimize](l))')\n\n%%% code for better optimization and corresponding cost\nmaple( 'opt2 := [codegen[optimize](res,tryhard)]' );\nmaple('codegen[cost](opt2)')\n\n%%% Convert to C code\nout = maple( 'codegen[C](opt2)' );\n\n%%% clean the C code and convert it to Matlab code (replace [] by ()\nout = strrep( out, ';   ', ';\\n' );\nout = strrep( out, '~', '' );\n\ntout = ''\nexisting = cell(1,0);\ntmp = regexp( out,'(t\\d*)', 'tokens' )\nfor i = 1 : length(tmp)\n  ii = tmp(i);\n  ii = ii{1}{1};\n  doExist = false;\n  for j = 1 : size(existing,2)\n    if strcmp(existing{j},ii)\n\t  doExist = true;\n\t  break;\n\tend\n  end\n  if ~doExist\n    existing{1,end+1} = ii;\n    tout = [ tout, ', ', ii ];\n  end\nend\nout = [ 'double ', tout(2:end), ';\\n', out ];\nfprintf(out)\n\nwhile 1\n  tok = regexp( out,'\\[(\\d*)\\]\\[(\\d*)\\]', 'tokens' );\n  tokStart = regexp( out,'\\[(\\d*)\\]\\[(\\d*)\\]', 'start' );\n  tokEnd = regexp( out,'\\[(\\d*)\\]\\[(\\d*)\\]', 'end' );\n\n  if isempty(tok); break; end\n\n  out = [ out( 1:tokStart(1)-1 ) '(' num2str(str2double(tok{1}{1})+1) ...\n      ',' num2str(str2double(tok{1}{2})+1) ')' out( tokEnd(1)+1 : end ) ];\nend\n\nfprintf( out );\n", "meta": {"author": "vrabaud", "repo": "sfm_toolbox", "sha": "7ce933b31b71292eddabb40bacfd619720fa221d", "save_path": "github-repos/MATLAB/vrabaud-sfm_toolbox", "path": "github-repos/MATLAB/vrabaud-sfm_toolbox/sfm_toolbox-7ce933b31b71292eddabb40bacfd619720fa221d/sfm/private/refineExteriorOrientationMake.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5684010657320984}}
{"text": "function lA = shortAxis(grains,varargin)\n% short axis of a grain \n%\n% the long axis is the direction of the smallest\n% <grain2d.principalComponents.html,principal component> of a grain\n%\n% Syntax\n%   sA = grains.shortAxis\n%\n% Input\n%  grains - @grain2d\n%\n% Output\n%  sA - @vector3d direction of the shortest elongation\n%\n% See also\n% grain2d/principalComponents\n\nomega = principalComponents(grains);\n\nlA = vector3d.byPolar(pi/2,omega+pi/2,'antipodal');\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/EBSDAnalysis/@grain2d/shortAxis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5684010542976343}}
{"text": "% Load original BFM\nload('01_MorphableModel.mat');\n\n% Load modified FW expression model\nload('3DDFA_Release/Matlab/Model_Expression.mat');\n\n% Load FW to BFM mapping\nload('util/map_tddfa_to_basel.mat');\n% Fix zero-based indexing\nmap_tddfa_to_basel=map_tddfa_to_basel+1;\n\nmodel.shapePC = zeros(3*53490,10);\nfor i=1:5\nmodel.shapePC(:,i) = shapePC(:,i).*shapeEV(i);\nend\n\n%% Extrapolate expressions to mouth interior via Laplace-Beltrami\nvertices = double(reshape(shapeMU,3,53490)');\n[L,~]=LaplaceBeltrami(vertices',tl');\n% Selection matrix for BFM vertices to FW\nS = sparse(1:length(map_tddfa_to_basel),double(map_tddfa_to_basel),ones(length(map_tddfa_to_basel),1),length(map_tddfa_to_basel),53490);\nfor i=1:5\n    expression = ([L; S]\\[L*vertices; S*vertices+reshape(w_exp(:,i),3,53215)'])-vertices;\n    expression = expression';\n    model.shapePC(:,i+5) = expression(:);\nend\n%% Load UV coordinates and resample model\nload('util/BFM_UV.mat');\n[ newmodel ] = resampleModel( shapeMU,model.shapePC,[],tl,UV,112 );\nnewmodel.shapeMU=newmodel.shapeMU./1000;\nnewmodel.shapePC=newmodel.shapePC./1000;\nsave model.mat -struct newmodel\n%% Generate random mesh\nclear FV\nFV.faces = newmodel.faces;\nalpha = randn(10,1);\nFV.vertices = reshape(newmodel.shapeMU+newmodel.shapePC*alpha,3,112^2)';\nfigure; patch(FV, 'FaceColor', [1 1 1], 'EdgeColor', 'none', 'FaceLighting', 'phong'); axis equal; light; axis tight", "meta": {"author": "anilbas", "repo": "3DMMasSTN", "sha": "c6562b5fda5c2f742a27dc1b4a7ff15ec5e83837", "save_path": "github-repos/MATLAB/anilbas-3DMMasSTN", "path": "github-repos/MATLAB/anilbas-3DMMasSTN/3DMMasSTN-c6562b5fda5c2f742a27dc1b4a7ff15ec5e83837/prepareModel/prepareExpressionBFM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5683750893095673}}
{"text": "  function  Quaternion = madgwickAHRS( Gyroscope, Accelerometer, Magnetometer, quaternion_l,Beta,SamplePeriod)\n            q = quaternion_l; % short name local variable for readability\n            % Normalise accelerometer measurement\n            if(norm(Accelerometer) == 0), return; end\t% handle NaN\n            Accelerometer = Accelerometer / norm(Accelerometer);\t% normalise magnitude\n\n            % Normalise magnetometer measurement\n            if(norm(Magnetometer) == 0), return; end\t% handle NaN\n            Magnetometer = Magnetometer / norm(Magnetometer);\t% normalise magnitude\n\n            % Reference direction of Earth's magnetic feild\n            h = quaternProd(q, quaternProd([0 Magnetometer], quaternConj(q)));\n            b = [0 norm([h(2) h(3)]) 0 h(4)];\n\n            % Gradient decent algorithm corrective step\n            F = [-2*(q(2)*q(4) - q(1)*q(3)) - Accelerometer(1)\n                -2*(q(1)*q(2) + q(3)*q(4)) - Accelerometer(2)\n                -2*(0.5 - q(2)^2 - q(3)^2) - Accelerometer(3)\n                ((2*b(2)*(0.5 - q(3)^2 - q(4)^2) + 2*b(4)*(q(2)*q(4) - q(1)*q(3))) - Magnetometer(1))\n                ((2*b(2)*(q(2)*q(3) - q(1)*q(4)) + 2*b(4)*(q(1)*q(2) + q(3)*q(4))) - Magnetometer(2))\n                ((2*b(2)*(q(1)*q(3) + q(2)*q(4)) + 2*b(4)*(0.5 - q(2)^2 - q(3)^2)) - Magnetometer(3))];\n            J = [2*q(3),                 \t-2*q(4),                    2*q(1),                         -2*q(2)\n                -2*q(2),                 \t-2*q(1),                    \t-2*q(4),                         -2*q(3)\n                0,                         4*q(2),                    4*q(3),                         0\n               -2*b(4)*q(3),               2*b(4)*q(4),               -4*b(2)*q(3)-2*b(4)*q(1),       -4*b(2)*q(4)+2*b(4)*q(2)\n                -2*b(2)*q(4)+2*b(4)*q(2),\t2*b(2)*q(3)+2*b(4)*q(1),\t2*b(2)*q(2)+2*b(4)*q(4),       -2*b(2)*q(1)+2*b(4)*q(3)\n                2*b(2)*q(3),                2*b(2)*q(4)-4*b(4)*q(2),\t2*b(2)*q(1)-4*b(4)*q(3),        2*b(2)*q(2)];\n            step = (J'*F);\n            step = step / norm(step);\t% normalise step magnitude\n\n            % Compute rate of change of quaternion\n            qDot = 0.5 * quaternProd(q, [0 Gyroscope]) - Beta * step';\n\n            % Integrate to yield quaternion\n            q = q + qDot * SamplePeriod;\n            Quaternion = q / norm(q); % normalise quaternion          \n        end", "meta": {"author": "yuzhou42", "repo": "GPS-INS-Integrated-Navigation", "sha": "624c8e59facd33d275c24698d10c45b54be99ff2", "save_path": "github-repos/MATLAB/yuzhou42-GPS-INS-Integrated-Navigation", "path": "github-repos/MATLAB/yuzhou42-GPS-INS-Integrated-Navigation/GPS-INS-Integrated-Navigation-624c8e59facd33d275c24698d10c45b54be99ff2/madgwickAHRS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5683750809563619}}
{"text": "%% Calculate geodesic error curves\nclear all; close all; clc\n\naddpath(genpath('./'))\naddpath(genpath('./../Tools/'))\n\nmesh_0 = load('./faust_synthetic/shapes/tr_reg_080'); %Choose the indices of the test pair\nmesh_1 = load('./faust_synthetic/shapes/tr_reg_087'); %Choose the indices of the test pair\n\nX = load('./Results/test_faust_synthetic/080_087.mat'); %Choose the indices of the test pair\n[~, matches] = max(squeeze(X.softCorr),[],1);\n\nD_model = load('.\\faust_synthetic\\distance_matrix\\tr_reg_087.mat'); %Choose the indices of the test pair\nD_model = D_model.D;\n\ngt_matches = 1:6890;\nerrs = calc_geo_err(matches, gt_matches, D_model);\ncurve = calc_err_curve(errs, 0:0.001:1.0)/100;\nplot(0:0.001:1.0, curve); set(gca, 'xlim', [0 0.1]); set(gca, 'ylim', [0 1])\n\nxlabel('Geodeisc error')\nylabel('Correspondence Accuracy %')", "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/Learning Correspondence of Synthetic Shapes/calculate_geodesic_error_synthetic_faust_test_results.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5683750794010755}}
{"text": "function [w]=ADMM_solve_w(params,use_sz,model_w,h_f)\n    \n    w = gpuArray(params.w_init*single(ones(use_sz)));\n    q = w;\n    m = w;\n    \n    mu    = 1;\n    betha = 10;\n    mumax = 10000;\n    i = 1;\n    params.admm_iterations=2;\n    T = prod(use_sz);\n    h=T*real(ifft2(h_f));\n%     hw=bsxfun(@times,h,model_w);\n    hw=h;\n    Hh=sum(hw.^2,3);\n%     Hh=sum(real(bsxfun(@times,h_f(:),conj(h_f(:)))));\n    \n    %   ADMM\n    while (i <= params.admm_iterations)\n        %   solve for w- please refer to the paper for more details\n      %  w = (q-m)/(1+(params.admm_lambda1/mu)*Hh);\n        w = bsxfun(@rdivide,(q-m),(1+(params.admm_lambda1/mu)*Hh));\n        %   solve for q\n        q=(params.admm_lambda2*model_w + mu*(w+m))/(params.admm_lambda2 + mu);\n        \n        %   update m\n        m = m + (w - q);\n        \n        %   update mu- betha = 10.\n        mu = min(betha * mu, mumax);\n        i = i+1;\n               \n    end\n    \n\n\nend", "meta": {"author": "Daikenan", "repo": "ASRCF", "sha": "5dedd83105a547be97ec4d914154439cbfd6ee9b", "save_path": "github-repos/MATLAB/Daikenan-ASRCF", "path": "github-repos/MATLAB/Daikenan-ASRCF/ASRCF-5dedd83105a547be97ec4d914154439cbfd6ee9b/implementation/ADMM_solve_w.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.6406358548398982, "lm_q1q2_score": 0.5683750771351027}}
{"text": "function hmm = hmmrotatepca(hmm,Gamma,XXGXX)\n\nfor k = 1:length(hmm.state)\n\n    % Orthogonalize W to the standard PCA subspace\n    W = hmm.state(k).W.Mu_W;\n    %[W,~] = svd(hmm.state(k).W.Mu_W,'econ');\n    \n%     % Enforce a sign convention on the coefficients:\n%     % the largest element in each column will have a positive sign.\n    [~,maxind] = max(abs(W), [], 1);\n    [d1, d2] = size(W);\n    colsign = sign(W(maxind + (0:d1:(d2-1)*d1)));\n    W = bsxfun(@times, W, colsign);\n    hmm.state(k).W.Mu_W = W;\n    \n    % recompute covariance of W\n    v = hmm.Omega.Gam_rate / hmm.Omega.Gam_shape;\n    SW = XXGXX{k} * W / sum(Gamma(:,k));\n    M = W'*W+v*eye(size(W,2));\n    iS_W = v*eye(size(W,2))+M\\W'*SW; S_W = inv(iS_W);\n    for n = 1:size(hmm.state(k).W.iS_W,1)\n        hmm.state(k).W.iS_W(n,:,:) = iS_W;\n        hmm.state(k).W.S_W(n,:,:) = S_W;\n    end\n    \nend\n\n", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/train/hmmrotatepca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5683375982600655}}
{"text": "%   TTeMPS Toolbox. \n%   Michael Steinlechner, 2013-2016\n%   Questions and contact: michael.steinlechner@epfl.ch\n%   BSD 2-clause license, see LICENSE.txt\n\nfunction [xR, residuum, gradnorm, cost, times] = RiemannPrecondSteep( L, F, X0, Lh, Ph, opts )\n% L is the actual operator\n%    needs a apply(L, X) interface but can be anything\n% Lh is the operator that represents the (inexact) Euclidean Hessian\n%    needs a apply(L, X) interface but can be anything\n% Ph is the preconditioner for Lh; should be a TTeMPS_op_laplace operator\n%\n% When L is Laplace+perturbation, taking Lh and Ph both the Laplacian works\n% well.\n\nt_start = tic();\n% set default opts\nif ~exist( 'opts', 'var');       opts = struct();     end\nif ~isfield( opts, 'maxiter');   opts.maxiter = 500;  end\nif ~isfield( opts, 'tol');       opts.tol = 1e-16;     end\nif ~isfield( opts, 'safe_norm');       opts.safe_norm = false;     end\n\nd = X0.order;\nn = X0.size;\n\n\n\n[xL, xR, G] = gauge_matrices( X0 );\n\n%xL = orthogonalize(X, d);\n%xR = orthogonalize(X, 1);\n\ncost = zeros(opts.maxiter, 1);\nresiduum = zeros(opts.maxiter, 1);\ngradnorm = zeros(opts.maxiter, 1);\ntimes = zeros(opts.maxiter, 1);\nnormRHS = norm(F);\n\nfor i = 1:opts.maxiter\n    \n    g = euclid_grad( L, xR, F );\n    \n    cost(i) = cost_function_res( xR, g );\n    residuum(i) = norm(g, opts.safe_norm) / normRHS;\n    times(i) = toc(t_start);\n    \n    % test for stopping criterion\n    if abs(residuum(i)) < opts.tol\n        sprintf( 'Current residual: %g', residuum(i))\n        residuum = residuum(1:i);\n        cost = cost(1:i);\n        times = times(1:i);\n        sprintf( 'RiemannLinsolve CONVERGED after %i iterations', i )\n        break\n    end\n    \n    grad = TTeMPS_tangent_orth( xL, xR, g );\n    gradnorm(i) = norm( grad );\n    \n    sprintf('steepest descent step %i', i)\n    %P_grad = solvePrecond( L, P, grad, xL, xR, opts );\n    P_grad = solvePrecond_noSaddle( Lh, Ph, grad, xL, xR, opts, G );      \n        \n       \n        \n    %check_precond_laplace(P, grad, P_grad)\n    %eta = -P_grad;       \n    \n    %line search\n    alpha = linesearch_linearized( L, P_grad, g )\n    %alpha = linesearch_linearized2( L, P_grad, grad )\n    %alpha = -1;\n    xR = tangentAdd(  P_grad, alpha, true );\n    \n    [xL, G] = left_orth_with_gauge( xR );\n    %xL = orthogonalize( X, d );\n    %xR = orthogonalize( X, 1 );\nend\n\nend\n\nfunction res = cost_function( L, X, F )\nres = 0.5*innerprod( X, apply(L, X) ) - innerprod( X, F );\nend\nfunction res = cost_function_res( X, res )\nres = 0.5*innerprod( X, res );\nend\n\nfunction res = euclid_grad( L, X, F )\nres = apply(L, X) - F;\nend\n\nfunction alpha = linesearch_linearized( L, xi, g )\neta = tangent_to_TTeMPS( xi );\nalpha = -innerprod( eta, g );\nalpha = alpha / innerprod( eta, apply(L, eta) );\nend\n\nfunction alpha = linesearch_linearized2( L, xi, grad )\nalpha = -innerprod( xi, grad );\neta = tangent_to_TTeMPS( xi );\nalpha = alpha / innerprod( eta, apply(L, eta) );\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/algorithms/linearsystem/RiemannPrecondSteep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5683062359931792}}
{"text": "function H = hypot(f, g, pref)\n%HYPOT   Robust computation of the square root of the sum of squares.\n%   H = HYPOT(F, G) returns SQRT(ABS(F).^2 + ABS(G).^2) for two CHEBFUN objects\n%   F and G (or a CHEBFUN and a double) carefully computed to avoid underflow\n%   and overflow.\n%\n% Example:\n%       f = chebfun(@(x) 3*[1e300*x 1e-300*x]);\n%       g = chebfun(@(x) 4*[1e300*x 1e-300*x]);\n%       % h1 = sqrt(f.^2 + g.^2) % This will fail because of overflow\n%       h2 = hypot(f, g)\n%\n% See also ABS, NORM, SQRT.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Grab some preferences:\nif ( nargin < 3 )\n    pref = chebfunpref();\nend\n\n% Insert breaks at the roots:\nif ( isa(f, 'chebfun') )\n    f = addBreaksAtRoots(f, pref);\nend\nif ( isa(g, 'chebfun') )\n    g = addBreaksAtRoots(g, pref);\nend\n\n% Call compose:\nH = compose(f, @hypot, g, pref);\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/hypot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5683062314149362}}
{"text": "close all\nclear all\npath(path,'..\\..\\..\\FUZZCLUST')\n%the data\nload motorcycle.txt\ndata.X = motorcycle(:,[1 2]);\n\n[N,n]=size(data.X);\n\n%data normalization\ndata = clust_normalize(data,'range');\nplot(data.X(:,1),data.X(:,2),'.')\nhold on\n%parameters\nparam.c=4;\nparam.vis=1;\nparam.val=2;\n%clustering\nresult=kmedoid(data,param);\n%validation\nresult = validity(result,data,param);\nresult.validity", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/7486-clustering-toolbox/Demos/clusteringexamples/motorcycle/Kmedoidcall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5683062300470563}}
{"text": "function coords = makeSmoothCoords(c)\n\ncoords = [];\nii = 1;coordsInd = 1; \nbuff = 10;\nwhile ii<size(c,2)\n    n = c(2,ii);\n    if n>100\n        x = c(1,ii+1:ii+n);\n        y = c(2,ii+1:ii+n);\n        x = [x(end-buff:end) x x(1:buff)]; % buffer makes ends meet\n        y = [y(end-buff:end) y y(1:buff)];\n        x = smooth(x,25,'loess');\n        y = smooth(y,25,'loess');\n        x = [x(buff+1:end-buff-1);x(buff+1)];\n        y = [y(buff+1:end-buff-1);y(buff+1)];\n        coords(coordsInd).x = x;\n        coords(coordsInd).y = y;\n        coordsInd = coordsInd+1;                                        \n        \n    end\n    ii = ii+n+1;\nend", "meta": {"author": "cortex-lab", "repo": "allenCCF", "sha": "0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0", "save_path": "github-repos/MATLAB/cortex-lab-allenCCF", "path": "github-repos/MATLAB/cortex-lab-allenCCF/allenCCF-0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0/Browsing Functions/makeSmoothCoords.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5683062254688135}}
{"text": "function infsup(c)\n%INFSUP       Display of interval taylor in infsup notation\n%\n%   infsup(c)\n%\n\n% written  05/21/09     S.M. Rump\n% modified 08/26/12     S.M. Rump  global variables removed\n% modified 10/07/12     S.M. Rump  complete redesign\n%\n\n  INTLAB_TAYLOR_ORDER = getappdata(0,'INTLAB_TAYLOR_ORDER');\n\n  loose = strcmp(get(0,'FormatSpacing'),'loose');\n\n  name = inputname(1);\n  if isempty(name)                    % happens for display(taylorinit(random))\n    name = 'ans';\n  end\n\n  numvar = size(c.t,1)-1;\n  if numvar~=INTLAB_TAYLOR_ORDER\n    warning('**** number of dependent variables and partial derivatives do not coincide')\n  end\n\n  INTLAB_INTVAL_DISPLAY = getappdata(0,'INTLAB_INTVAL_DISPLAY');\n  setappdata(0,'INTLAB_INTVAL_DISPLAY','DisplayInfsup');\n  display(c,name)\n  setappdata(0,'INTLAB_INTVAL_DISPLAY',INTLAB_INTVAL_DISPLAY);\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/@taylor/infsup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5682517316796699}}
{"text": "% RANGE = showSpyr (PYR, INDICES, RANGE, GAP, LEVEL_SCALE_FACTOR)\n% \n% Display a steerable pyramid, specified by PYR and INDICES\n% (see buildSpyr), in the current figure.  The highpass band is not shown.\n% \n% RANGE is a 2-vector specifying the values that map to black and\n% white, respectively.  These values are scaled by\n% LEVEL_SCALE_FACTOR^(lev-1) for bands at each level.  Passing a value\n% of 'auto1' sets RANGE to the min and max values of MATRIX.  'auto2'\n% sets RANGE to 3 standard deviations below and above 0.0.  In both of\n% these cases, the lowpass band is independently scaled.  A value of\n% 'indep1' sets the range of each subband independently, as in a call\n% to showIm(subband,'auto1').  Similarly, 'indep2' causes each subband\n% to be scaled independently as if by showIm(subband,'indep2').\n% The default value for RANGE is 'auto2'.\n% \n% GAP (optional, default=1) specifies the gap in pixels to leave\n% between subbands.  \n% \n% LEVEL_SCALE_FACTOR indicates the relative scaling between pyramid\n% levels.  This should be set to the sum of the kernel taps of the\n% lowpass filter used to construct the pyramid (default is 2, which is \n% correct for L2-normalized filters.\n\n% Eero Simoncelli, 2/97.\n\nfunction [range] = showSpyr(pyr, pind, range, gap, scale);\n\nnbands = spyrNumBands(pind);\n\n%------------------------------------------------------------\n%% OPTIONAL ARGS:\n\nif (exist('range') ~= 1)  \n  range = 'auto2';\nend\n\t\t\nif (exist('gap') ~= 1)\n  gap = 1;\nend\n\nif (exist('scale') ~= 1)\n  scale = 2;\nend\n\n%------------------------------------------------------------\n\nht = spyrHt(pind);\nnind = size(pind,1);\n\n%% Auto range calculations:\nif strcmp(range,'auto1')\n  range = ones(nind,1);\n  band = spyrHigh(pyr,pind);\n  [mn,mx] = range2(band);\n  for lnum = 1:ht\n    for bnum = 1:nbands\n      band = spyrBand(pyr,pind,lnum,bnum)/(scale^(lnum-1));\n      range((lnum-1)*nbands+bnum+1) = scale^(lnum-1);\n      [bmn,bmx] = range2(band);\n      mn = min(mn, bmn);\n      mx = max(mx, bmx);\n    end    \n  end\n  range = range * [mn mx]; \t\t% outer product\n  band = pyrLow(pyr,pind);\n  [mn,mx] = range2(band);\n  range(nind,:) = [mn, mx];\n\nelseif strcmp(range,'indep1')\n  range = zeros(nind,2);\n  for bnum = 1:nind\n    band = pyrBand(pyr,pind,bnum);\n    [mn,mx] = range2(band);\n    range(bnum,:) =  [mn mx];\n  end\n\nelseif strcmp(range,'auto2')\n  range = ones(nind,1);\n  band = spyrHigh(pyr,pind);\n  sqsum = sum(sum(band.^2));  numpixels = prod(size(band));\n  for lnum = 1:ht\n    for bnum = 1:nbands\n      band = spyrBand(pyr,pind,lnum,bnum)/(scale^(lnum-1));\n      sqsum = sqsum + sum(sum(band.^2));\n      numpixels = numpixels + prod(size(band));\n      range((lnum-1)*nbands+bnum+1) = scale^(lnum-1);\n    end    \n  end\n  stdev = sqrt(sqsum/(numpixels-1));\n  range = range * [ -3*stdev 3*stdev ]; % outer product\n  band = pyrLow(pyr,pind);\n  av = mean2(band);   stdev = sqrt(var2(band));\n  range(nind,:) = [av-2*stdev,av+2*stdev];\n\nelseif strcmp(range,'indep2')\n  range = zeros(nind,2);\n  for bnum = 1:(nind-1)\n    band = pyrBand(pyr,pind,bnum);\n    stdev = sqrt(var2(band));\n    range(bnum,:) =  [ -3*stdev 3*stdev ];\n  end\n  band = pyrLow(pyr,pind);\n  av = mean2(band);   stdev = sqrt(var2(band));\n  range(nind,:) = [av-2*stdev,av+2*stdev];\n  \nelseif isstr(range)\n  error(sprintf('Bad RANGE argument: %s',range))\n  \nelseif ((size(range,1) == 1) & (size(range,2) == 2))\n  scales = scale.^[0:(ht-1)];\n  scales = ones(nbands,1) * scales;   %outer product\n  scales = [1; scales(:); scale^ht];  %tack on highpass and lowpass\n  range = scales * range;\t\t% outer product\n  band = pyrLow(pyr,pind);\n  range(nind,:) = range(nind,:) + mean2(band) - mean(range(nind,:));\n\nend\n\n% CLEAR FIGURE:\nclf;\n\ncolormap(gray);\ncmap = get(gcf,'Colormap');\nnshades = size(cmap,1);\n\n%  Find background color index:\nclr = get(gcf,'Color');\nbg = 1;\ndist = norm(cmap(bg,:)-clr);\nfor n = 1:nshades\n  ndist = norm(cmap(n,:)-clr);\n  if (ndist < dist)\n    dist = ndist;\n    bg = n;\n  end\nend  \n\n%% Compute positions of subbands:\nllpos = ones(nind,2);\n\nif (nbands == 2)\n  ncols = 1;  nrows = 2;\nelse\n  ncols = ceil((nbands+1)/2);   nrows = ceil(nbands/2);\nend\nrelpos = [ (1-nrows):0, zeros(1,(ncols-1)); ...\n           zeros(1,nrows), -1:-1:(1-ncols) ]';\nif (nbands > 1)\n  mvpos = [-1 -1];\nelse\n  mvpos = [0 -1];\nend\nbasepos = [0 0];\n\nfor lnum = 1:ht\n  ind1 = (lnum-1)*nbands + 2;\n  sz = pind(ind1,:)+gap;\n  basepos = basepos + mvpos .* sz;\n  if (nbands < 5)\t\t\t% to align edges...\n    sz = sz + gap*(ht-lnum+1);\n  end\n  llpos(ind1:ind1+nbands-1,:) = relpos * diag(sz) + ones(nbands,1)*basepos;\nend\n\n% lowpass band\nsz = pind(nind-1,:)+gap;\nbasepos = basepos + mvpos .* sz;\nllpos(nind,:) = basepos;\n\n%% Make position list positive, and allocate appropriate image:\nllpos = llpos - ones(nind,1)*min(llpos) + 1;\nllpos(1,:) = [1 1];\nurpos = llpos + pind - 1;\nd_im = bg + zeros(max(urpos));\n\n%% Paste bands into image, (im-r1)*(nshades-1)/(r2-r1) + 1.5 \nfor bnum=2:nind\n  mult = (nshades-1) / (range(bnum,2)-range(bnum,1));\n  d_im(llpos(bnum,1):urpos(bnum,1), llpos(bnum,2):urpos(bnum,2)) = ...\n      mult*pyrBand(pyr,pind,bnum) + (1.5-mult*range(bnum,1));\nend\n  \nhh = image(d_im);\naxis('off');\npixelAxes(size(d_im),'full');\nset(hh,'UserData',range);\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/showSpyr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5682517271250874}}
{"text": "function gf=gradloglikGaPExp(x, varargin)\n% f=loglikGaP(x, varargin)\n% complete log likellihood of the GaP model \n% Vxt = varargin{1};      %data\n% sigpsf = varargin{2};  %std deviation of the PSF gaussian approx\n% alpha = varargin{3}; %parameters of the Gamma prior on the blinking\n% beta = varargin{4}; %parameters of the Gamma prior on the blinking\n% peval = varargin{5}; %parameters\n% x(1:end-2*peval.ncomp) is Hkt\n\nVxt = varargin{1};      %data\nsigpsf = varargin{2};  %std deviation of the PSF gaussian approx\nalpha = varargin{3}; %parameters of the Gamma prior on the blinking\nbeta = varargin{4}; %parameters of the Gamma prior on the blinking\npeval = varargin{5}; %parameters\n\n[Hkt_r, cx, cy, Wxk] = loglikGaPreadparam(x,varargin);\n\nHkt=exp(Hkt_r); %nonnegativity constrains\n[Wxkbg,Hktbg]=addbg(Wxk, Hkt, peval.bg);\n\nP=Wxkbg*Hktbg; %current approximation\n\n%linear grasdient shifted by cx\nxxvc = lineargrad([peval.nx, peval.ny, peval.ncomp], cx, 'xx'); \nyyvc = lineargrad([peval.nx, peval.ny, peval.ncomp], cy, 'yy');\n\n% dW/dcx:\nWxtcx=1/sigpsf^2*xxvc.*Wxk; \n% dW/dcy:\nWxtcy=1/sigpsf^2*yyvc.*Wxk;\n\n% d(log(L))/dHkt:\n% gfHkt=(alpha-1)*1./Hkt - 1/beta + Wxk'*(Vxt./P)-1;\ngfHkt= Hkt.*((Wxk'*(Vxt./P)-1)-(alpha-1)./Hkt - ones(size(Hkt))*1/beta); %without background (->not Wxkgb) and d(log(L)/dcx)\n% d(log(L))/dcx:\ngfcx=diag(Wxtcx'*(Vxt./P-ones(peval.nx*peval.ny, peval.nt))*Hkt');\n% d(log(L))/dcy:\ngfcy=diag(Wxtcy'*(Vxt./P-ones(peval.nx*peval.ny, peval.nt))*Hkt'); \n\ngf = [reshape(gfHkt,1,peval.nt*peval.ncomp), gfcx', gfcy'];\n% gf = [reshape(gfHkt,1,peval.nt*peval.ncomp)];\n% gf = [gfcx', gfcy'];\ngf=-gf; %conjugate gradient is minimizing!\nend\n\nfunction xxvc = lineargrad(sizevec, cx, dir)\nswitch dir\n    case 'xx'\n        xxp=double(xx(sizevec, 'corner')); %linear function - pixels\n    case 'yy'\n        xxp=double(yy(sizevec, 'corner')); %linear function - pixels\n    otherwise \n        error('Wrong dir')        \nend    \nxxv=reshape(xxp,sizevec(1)*sizevec(2),sizevec(3)); %linear function - vector\nxxvc=xxv-repmat(cx,sizevec(1)*sizevec(2),1);\nend", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/conjgradfunctions/gradloglikGaPExpPriorH.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5682025776237024}}
{"text": "classdef FDA3 < PROBLEM\n% <multi> <real> <large/none> <dynamic>\n% Benchmark dynamic MOP proposed by Farina, Deb, and Amato\n% taut --- 10 --- Number of generations for static optimization\n% nt   --- 10 --- Number of distinct steps\n\n%------------------------------- Reference --------------------------------\n% M. Farina, K. Deb, and P. Amato, Dynamic multiobjective optimization\n% problems: Test cases, approximations, and applications, IEEE Transactions\n% on Evolutionary Computation, 2004, 8(5): 425-442.\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        taut;       % Number of generations for static optimization\n        nt;         % Number of distinct steps\n        Optimums;   % Point sets on all Pareto fronts\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            [obj.taut,obj.nt] = obj.ParameterSet(10,10);\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 10; end\n            obj.lower    = [0,-ones(1,obj.D-1)];\n            obj.upper    = [1, ones(1,obj.D-1)];\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Evaluate solutions\n        function Population = Evaluation(obj,varargin)\n            PopDec     = obj.CalDec(varargin{1});\n            PopObj     = obj.CalObj(PopDec);\n            PopCon     = obj.CalCon(PopDec);\n            % Attach the current number of function evaluations to solutions\n            Population = SOLUTION(PopDec,PopObj,PopCon,zeros(size(PopDec,1),1)+obj.FE);\n            obj.FE     = obj.FE + length(Population);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            t = floor(obj.FE/obj.N/obj.taut)/obj.nt;\n            PopObj(:,1) = PopDec(:,1).^(10.^(2*sin(0.5*pi*t)));\n            G = abs(sin(0.5*pi*t));\n            g = 1 + G + sum((PopDec(:,2:end)-G).^2,2);\n            h = 1 - (PopObj(:,1)./g).^0.5;\n            PopObj(:,2) = g.*h;\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            % Generate point sets on all Pareto fronts\n            t = floor(0:obj.maxFE/obj.N/obj.taut)/obj.nt;\n            G = abs(sin(0.5.*pi.*t));\n            G = unique(round(G*1e6)/1e6);\n            x = linspace(0,1,N)';\n            obj.Optimums = {};\n            for i = 1 : length(G)\n                g = 1 + G(i);\n                obj.Optimums(i,:) = {G(i),[x,g*(1-sqrt(x/g))]};\n            end\n            % Combine all point sets\n            R = cat(1,obj.Optimums{:,2});\n        end\n        %% Calculate the metric value\n        function score = CalMetric(obj,metName,Population)\n            t      = floor(Population.adds/obj.N/obj.taut)/obj.nt;\n            G      = abs(sin(0.5.*pi.*t));\n            G      = round(G*1e6)/1e6;\n            change = [0;find(G(1:end-1)~=G(2:end));length(G)];\n            Scores = zeros(1,length(change)-1);\n            allG   = cell2mat(obj.Optimums(:,1));\n            for i = 1 : length(change)-1\n                subPop    = Population(change(i)+1:change(i+1));\n                Scores(i) = feval(metName,subPop,obj.Optimums{find(G(change(i)+1)==allG,1),2});\n            end\n            score = mean(Scores);\n        end\n        %% Display a population in the objective space\n        function DrawObj(obj,Population)\n            t      = floor(Population.adds/obj.N/obj.taut)/obj.nt;\n            G      = abs(sin(0.5.*pi.*t));\n            G      = round(G*1e6)/1e6;\n            change = [0;find(G(1:end-1)~=G(2:end));length(G)];\n            allG   = cell2mat(obj.Optimums(:,1));\n            tempStream = RandStream('mlfg6331_64','Seed',2);\n            for i = 1 : length(change)-1\n                color = rand(tempStream,1,3);\n                Draw(Population(change(i)+1:change(i+1)).objs,'o','MarkerSize',5,'Marker','o','Markerfacecolor',sqrt(color),'Markeredgecolor',color,{'\\it f\\rm_1','\\it f\\rm_2',[]});\n                Draw(obj.Optimums{find(G(change(i)+1)==allG,1),2},'-','LineWidth',1,'Color',color);\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/FDA/FDA3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5682025751498968}}
{"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 y = sprice_a(a, b, r, n, f, k, t,cp)\n% sabr prices using the risk neutral density psabr \n% and integrating this density with respect to the payoff\n\nnl = length(k);\ny = ones(1,nl);\nif (cp == 1)\n    % call\n    for j = 1:nl\n    F = @(x) (x-k(j)) .* psabr(a, b, r, n, f, x, t);\n    y(j) = quad(F,k(j),1);  \n    end\nelse\n    % put\n    for j = 1:nl\n    F = @(x) (k(j)-x) .* psabr(a, b, r, n, f, x, t);\n    y(j) = quad(F,0.0001,k(j));  \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/38322-the-sabr-model-densities-and-mc/Densities_Prices_MC/sprice_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5682025726760912}}
{"text": "function test_symm_clustering()\n%\n% demonstration file for NMFLibrary.\n%\n% This file illustrates how to use this library. \n% This demonstrates Symm-ANLS algorithm and Symm-Newton algorithm.\n%\n% This file is part of NMFLibrary.\n%\n% Created by H.Kasai on Jun. 26, 2019\n\n    clc;\n    clear;\n    close all;\n\n    %% generate synthetic data of (mxn) matrix\n    if 1\n        input = importdata('../../data/ORL.mat'); \n        M = input.data;\n        gnd = input.label;\n    else\n        input = importdata('../../data/COIL20.mat'); \n        M = (input.TrainSet.X)';\n        gnd = (input.TrainSet.y)';\n    end\n    clear input;\n\n\n    V = calcu_similarity_matrix(M);\n    rank = length(unique(gnd)); \n    \n    \n    %W_init = 2 * full(sqrt(mean(mean(V)) / rank)) * rand(m, rank);\n    %W_init = rand(m, rank);\n    %options.x_init.W = W_init;\n    %options.x_init.H = (options.x_init.W)';    \n    \n\n    lambda = 0.66;  \n\n   \n    \n    %% initialize rank to be factorized\n    options.verbose = 2;\n    options.max_epoch = 100;\n    options.calc_symmetry = true;\n    options.calc_clustering_acc = true;\n    options.clustering_gnd = gnd;\n    options.clustering_classnum = rank;\n    %options.clustering_eval_num = 10;\n    %options.init_alg = 'symm_mean';\n\n\n    %% perform factroization\n    % Symm-ANLS\n    options.alpha = lambda;\n    [w_symm_anls, infos_symm_anls] = symm_anls(V, rank, options);\n    % Symm-Newton\n    [w_symm_newton, infos_symm_newton] = symm_newton(V, rank, options);\n    % Symm-Hals\n    options.lambda = lambda;\n    [w_symm_halsacc, infos_symm_halsacc] = symm_halsacc(V, rank, options);      \n    \n    \n    %% plot\n    display_graph('epoch','cost', {'Symm-ANLS', 'Symm-Newton', 'Symm-HALS'}, ...\n        {w_symm_anls, w_symm_newton, w_symm_halsacc}, {infos_symm_anls, infos_symm_newton, infos_symm_halsacc});\n    display_graph('time','cost', {'Symm-ANLS', 'Symm-Newton', 'Symm-HALS'}, ...\n        {w_symm_anls, w_symm_newton, w_symm_halsacc}, {infos_symm_anls, infos_symm_newton, infos_symm_halsacc});\n    \n    %% symmetry\n    display_graph('epoch','symmetry', {'Symm-ANLS', 'Symm-Newton', 'Symm-HALS'}, ...\n        {w_symm_anls, w_symm_newton, w_symm_halsacc}, {infos_symm_anls, infos_symm_newton, infos_symm_halsacc});    \n    \n    %% clustering\n    display_graph('epoch','clustering_acc', {'Symm-ANLS', 'Symm-Newton', 'Symm-HALS'}, ...\n        {w_symm_anls, w_symm_newton, w_symm_halsacc}, {infos_symm_anls, infos_symm_newton, infos_symm_halsacc});  \n    display_graph('epoch','clustering_nmi', {'Symm-ANLS', 'Symm-Newton', 'Symm-HALS'}, ...\n        {w_symm_anls, w_symm_newton, w_symm_halsacc}, {infos_symm_anls, infos_symm_newton, infos_symm_halsacc}); \n    display_graph('epoch','clustering_purity', {'Symm-ANLS', 'Symm-Newton', 'Symm-HALS'}, ...\n        {w_symm_anls, w_symm_newton, w_symm_halsacc}, {infos_symm_anls, infos_symm_newton, infos_symm_halsacc});     \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/symmetric/test/test_symm_clustering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5682025719578464}}
{"text": "function b = chpsl ( ap, n, ipvt, b )\n\n%*****************************************************************************80\n%\n%% CHPSL solves a complex hermitian system factored by CHPFA.\n%\n%  Discussion:\n%\n%    A division by zero may occur if CHPCO set RCOND to 0.0\n%    or CHPFA set INFO nonzero.\n%\n%    To compute\n%\n%      inverse ( A ) * C\n%\n%    where C is a matrix with P columns\n%\n%      call chpfa(ap,n,ipvt,info)\n%\n%      if ( info == 0 )\n%        do j = 1, p\n%          call chpsl(ap,n,ipvt,c(1,j))\n%        end do\n%      end\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 May 2007\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, complex AP(N*(N+1)/2), the output from CHPFA.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Input, integer IPVT(N), the pivot vector from CHPFA.\n%\n%    Input, complex B(N), the right hand side.\n%\n%    Output, complex B(N), the solution.\n%\n\n%\n%  Loop backward applying the transformations and inverse ( D ) to B.\n%\n  k = n;\n  ik = ( n * ( n - 1 ) ) / 2;\n\n  while ( 0 < k )\n\n    kk = ik + k;\n%\n%  1 x 1 pivot block.\n%\n    if ( 0 <= ipvt(k) )\n\n      if ( k ~= 1 )\n\n        kp = ipvt(k);\n\n        if ( kp ~= k )\n          t     = b(k);\n          b(k)  = b(kp);\n          b(kp) = t;\n        end\n\n        b(1:k-1) = b(1:k-1) + b(k) * ap(ik+1:ik+k-1);\n\n      end\n%\n%  Apply D inverse.\n%\n      b(k) = b(k) / ap(kk);\n      k = k - 1;\n      ik = ik - k;\n\n    else\n%\n%  2 x 2 pivot block.\n%\n      ikm1 = ik - ( k - 1 );\n\n      if ( k ~= 2 )\n\n        kp = abs ( ipvt(k) );\n\n        if ( kp ~= k - 1 )\n          t      = b(k-1);\n          b(k-1) = b(kp);\n          b(kp)  = t;\n        end\n\n        b(1:k-2) = b(1:k-2) + b(k)   * ap(ik+1:ik+k-2);\n        b(1:k-2) = b(1:k-2) + b(k-1) * ap(ikm1+1:ikm1+k-2);\n\n      end\n%\n%  Apply D inverse.\n%\n      km1k = ik + k - 1;\n      kk = ik + k;\n      ak = ap(kk) / conj ( ap(km1k) );\n      km1km1 = ikm1 + k - 1;\n      akm1 = ap(km1km1) / ap(km1k);\n      bk = b(k) / conj ( ap(km1k) );\n      bkm1 = b(k-1) / ap(km1k);\n      denom = ak * akm1 - 1.0;\n      b(k) = ( akm1 * bk - bkm1 ) / denom;\n      b(k-1) = ( ak * bkm1 - bk ) / denom;\n      k = k - 2;\n      ik = ik - ( k + 1 ) - k;\n\n    end\n\n  end\n%\n%  Loop forward applying the transformations.\n%\n  k = 1;\n  ik = 0;\n\n  while ( k <= n )\n%\n%  1 x 1 pivot block.\n%\n    if ( 0 <= ipvt(k) )\n\n      if ( k ~= 1 )\n\n        b(k) = b(k) + conj ( ap(ik+1:ik+k-1) ) * transpose ( b(1:k-1) );\n        kp = ipvt(k);\n\n        if ( kp ~= k )\n          t     = b(k);\n          b(k)  = b(kp);\n          b(kp) = t;\n        end\n\n      end\n\n      ik = ik + k;\n      k = k + 1;\n%\n%  2 x 2 pivot block.\n%\n    else\n\n      if ( k ~= 1 )\n\n        b(k) = b(k) + conj ( ap(ik+1:ik+k-1) ) * transpose ( b(1:k-1) );\n        ikp1 = ik + k;\n        b(k+1) = b(k+1) ...\n          + conj ( ap(ikp1+1:ikp1+k-1) ) * transpose ( b(1:k-1) );\n        kp = abs ( ipvt(k) );\n\n        if ( kp ~= k )\n          t     = b(k);\n          b(k)  = b(kp);\n          b(kp) = t;\n        end\n\n      end\n\n      ik = ik + k + k + 1;\n      k = k + 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/linpack_c/chpsl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5682025634991117}}
{"text": "close all\nclear all\nclc\n\n%Specify start and end points\nstart_point = [100;40]\nend_point = [55;40]\n\n%Specify external boundaries\nexternal_boundaries = [0,0;60,0;60,45;45,45;45,59;75.5,40;106,59;106,45;91,45;91,0;151,0;151,105;50,105;0,60];\n\n%Let the external boundaries form a closed polygon for graphical\n%visualization purposes\nexternal_boundaries_draw = external_boundaries;\nexternal_boundaries_draw(size(external_boundaries,1)+1,:) = external_boundaries_draw(1,:);\n\nhold on\naxis equal\n\n%Plot the boundaries, starting points and end points\nplot(external_boundaries_draw(:,1), external_boundaries_draw(:,2), 'Color', 'black')\nplot(start_point(1), start_point(2), 'X', 'Color', 'green')\nplot(start_point(1), start_point(2), 'O', 'Color', 'green')\nplot(end_point(1), end_point(2), 'X', 'Color', 'red')\nplot(end_point(1), end_point(2), 'O', 'Color', 'red')\n\ntic\nwaypoint_coordinates = pathfinder(start_point, end_point, external_boundaries)\ntoc\n\n%Plot the chosen path\nplot(waypoint_coordinates(:,1), waypoint_coordinates(:,2), 'Color', 'blue')", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/33141-shortest-path-identification-with-obstacle-avoidance/pathfinder_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5682025563967678}}
{"text": "% Fig. 5.18   Feedback Control of Dynamic Systems, 6e \n%             Franklin, Powell, Emami\n%\nclf\n np=1;\ndp=[1 .2 6.6*6.6+.1*.1 0 0];\nnc=[1 1];\ndc=[1 12];\nnol=conv(np,nc);\ndol=conv(dp,dc);\nrlocus(nol,dol)\ntitle(' Fig. 5.18 Root locus for noncollocated system')\naxis([-15, 5, -7.5, 7.5])\nz=0:.1:.9;\n wn=2:2:14;\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_18.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5682025507309117}}
{"text": "function imgRec = BoschettiDec(name)\n%\n%\n%       imgRec = BoschettiDec(name)\n%\n%       Input:\n%           -name: the prefix of the compressed HDR images using Boschetti\n%           et al. method.\n%\n%\n%     Copyright (C) 2012  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 <http://www.gnu.org/licenses/>.\n%\n\n%Read metadata\ninfo = imfinfo([name, '_bos_RGB.jp2']);\ndecoded = sscanf(cell2mat(info.Comments), '%g', 3);\nnBit = decoded(1);\nmaxE = decoded(2);\nminE = decoded(3);\n\nmaxVal = 2^nBit - 1;\n\n%Reading and Decoding Eq\nEqDec = double(imread([name, '_bos_E.jp2'])) / maxVal;\nEDec = EqDec * (maxE - minE) + minE;\nmult = 2.^EDec;\n\n%Decoding RGB\nRGBDec = double(imread([name, '_bos_RGB.jp2'])) / maxVal;\n\n%Reconstruction\nimgRec = zeros(size(RGBDec));\nfor i=1:size(imgRec, 3)\n    imgRec(:,:,i) = (RGBDec(:,:,i)) .* mult;\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/Compression/BoschettiDec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5682025457833002}}
{"text": "function [P,model] = chrrParseModel(model)\n% Parse a COBRA model into the right format for the CHRR sampler\n%\n% USAGE:\n%\n%      [P,model] = chrrParseModel(model);\n%\n% We are trying to sample uniformly at random from the points v that satisfy:\n%\n% .. math::\n%                     Sv = b\\\\\n%             ~~ l_b \\leq v \\leq u_b\n%\n% INPUTS:\n%    model:    COBRA model structure with fields:\n%\n%               * .S - The `m x n` stoichiometric matrix\n%               * .lb - `n x 1` lower bounds on fluxes\n%               * .ub - `n x 1` upper bounds on fluxes\n%\n% OPTIONAL INPUTS:\n%               * .C - 'k x n' matrix of additional inequality constraints\n%               * .d - 'k x 1' rhs of the above constraints\n%               * .dsense - 'k x 1' the sense of the above constraints ('L' or 'G')\n%\n% OUTPUTS:\n%    P:        A structure with fields:\n%\n%               * .A_eq - Equality constraint matrix (`model.S`)\n%               * .b_eq - Right hand side of equality constraints (`model.b`)\n%               * .A - Inequality constraint matrix (`[I_n 0; 0 -I_n]`)\n%               * .b - Right hand side of inequality constraints (`[lb; -ub]`)\n%\n% .. Authors:\n%       - Ben Cousins and Hulda Haraldsd\u00f3ttir, 10/2016\n%       - Ben Cousins, 12/2017, Moved objective function handling to preprocess function\n%       - Ben Cousins, 05/2019, Added support for C,d inequalities.\n\ndim = length(model.lb);\n\nP.A = [eye(dim); -eye(dim)];\nP.b = [model.ub; -model.lb]; \n\nif isfield(model,'C') && isfield(model,'d')\n   for i=1:size(model.C,1)\n      if model.dsense(i)=='G'\n          % convert constraint to <=\n          model.C(i,:) = model.C(i,:)*-1;\n          model.d(i) = model.d(i)*-1;\n      elseif model.dsense{i}=='E'\n          error('Equality constraints not supported in C,d fields.');\n      end\n   end\n   P.A = [P.A; model.C];\n   P.b = [P.b; model.d];\nend\n\nP.A_eq = model.S;\nP.b_eq = model.b;\n\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/sampling/CHRR/chrrParseModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162772, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.5682025457833}}
{"text": "function [yu,dyudtheta] = u_GaussianBumps(Theta,u,inF)\n\n% input function for free-form deterministic DCM\n\nspread = exp(Theta(1));\nscale = exp(Theta(inF.indscale));\ncentres = exp(Theta(inF.indcentres));\nn = length(centres);\nyu = 0;\ndyudtheta = zeros(size(Theta));\nfor i=1:n\n   dt = centres(i)-u;\n   bump = scale(i)*exp(-0.5*dt.^2./spread);\n   dyudtheta(1) = ...\n       dyudtheta(1) + scale(i)*dt^2./(2*spread*exp(dt^2/(2*spread)));\n   dyudtheta(inF.indscale(i)) = bump;\n   dyudtheta(inF.indcentres(i)) = ...\n       -scale(i)*centres(i)*dt./(spread*exp(dt^2/(2*spread)));\n   yu = yu + bump;\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/modules/DCM/u_GaussianBumps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5681110999832643}}
{"text": "function runSimSCFDMA()\n\nSP.FFTsize = 512;\nSP.inputBlockSize = 16;\nSP.CPsize = 20;\n%SP.subband = 15;\nSP.subband = 0;\n\nSP.SNR = [0:2:20];\nSP.numRun = 10^5;\n\n% TS 25.104\npedAchannel = [1 10^(-9.7/20) 10^(-22.8/20)];\npedAchannel = pedAchannel/sqrt(sum(pedAchannel.^2));\nvehAchannel = [1 0 10^(-1/20) 0 10^(-9/20) 10^(-10/20) 0 0 0 10^(-15/20) 0 0 0 10^(-20/20)];\nvehAchannel = vehAchannel/sqrt(sum(vehAchannel.^2));\nidenChannel = 1;\n\nSP.channel = idenChannel;\n%SP.channel = pedAchannel;\n%SP.channel = vehAchannel;\n\nSP.equalizerType ='ZERO';\n%SP.equalizerType ='MMSE';\n\n[SER_ifdma SER_lfdma] = scfdma(SP);\n\nsave scfdma_awgn\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/20454-simple-single-carrier-fdma-sc-fdma-simulator/scfdma/runSimSCFDMA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5681110938378215}}
{"text": "function W = SimGraph_NearestNeighbors(M, k, Type, sigma)\n% SIMGRAPH_NEARESTNEIGHBORS Returns kNN similarity graph\n%   Returns adjacency matrix for an k-Nearest Neighbors \n%   similarity graph\n%\n%   'M' - A d-by-n matrix containing n d-dimensional data points\n%   'k' - Number of neighbors\n%   'Type' - Type if kNN Graph\n%      1 - Normal\n%      2 - Mutual\n%   'sigma' - Parameter for Gaussian similarity function. Set\n%      this to 0 for an unweighted graph. Default is 1.\n%\n%   Author: Ingo Buerk\n%   Year  : 2011/2012\n%   Bachelor Thesis\n\nif nargin < 3\n   ME = MException('InvalidCall:NotEnoughArguments', ...\n       'Function called with too few arguments');\n   throw(ME);\nend\n\nif ~any(Type == (1:2))\n   ME = MException('InvalidCall:UnknownType', ...\n       'Unknown similarity graph type');\n   throw(ME);\nend\n\nn = size(M, 2);\n\n% Preallocate memory\nindi = zeros(1, k * n);\nindj = zeros(1, k * n);\ninds = zeros(1, k * n);\n\nfor ii = 1:n\n    % Compute i-th column of distance matrix\n    dist = distEuclidean(repmat(M(:, ii), 1, n), M);\n    \n    % Sort row by distance\n    [s, O] = sort(dist, 'ascend');\n    \n    % Save indices and value of the k \n    indi(1, (ii-1)*k+1:ii*k) = ii;\n    indj(1, (ii-1)*k+1:ii*k) = O(1:k);\n    inds(1, (ii-1)*k+1:ii*k) = s(1:k);\nend\n\n% Create sparse matrix\nW = sparse(indi, indj, inds, n, n);\n\nclear indi indj inds dist s O;\n\n% Construct either normal or mutual graph\nif Type == 1\n    % Normal\n    W = max(W, W');\nelse\n    % Mutual\n    W = min(W, W');\nend\n\nif nargin < 4 || isempty(sigma)\n    sigma = 1;\nend\n\n% Unweighted graph\nif sigma == 0\n    W = (W ~= 0);\n    \n% Gaussian similarity function\nelseif isnumeric(sigma)\n    W = spfun(@(W) (simGaussian(W, sigma)), W);\n    \nelse\n    ME = MException('InvalidArgument:NotANumber', ...\n        'Parameter epsilon is not numeric');\n    throw(ME);\nend\n\nend", "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/spectralClustering/files/SimilarityGraph/SimGraph_NearestNeighbors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.5680706589174279}}
{"text": "function vscl = vscale(f) \n%VSCALE   Vertical scale of a CHEBFUN3. \n%   VSCL = VSCALE(F) returns the vertical scale of a CHEBFUN3 object F as\n%   determined by evaluating F on a coarse tensor-product grid. \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% [TODO]: Should this also be taking the maximum along the edges when we are\n% evaluating at 1st kind grids. \n\n% If f is an empty CHEBFUN3, VSCL = 0: \nif ( isempty(f) ) \n    vscl = 0; \n    return\nend\n\ntechCol = get(f.cols.funs{1}, 'tech');\n\n% Get the degree of the CHEBFUN3:\n[m, n, p] = length(f);\n\n% If F is of low degree, then oversample: \nm = min(max(m, 9), 41); \nn = min(max(n, 9), 41); \np = min(max(p, 9), 41); % cannot afford to go over 41x41x41. \n\n% Calculate values on a tensor grid: \ndom = f.domain;\nx = mypoints(m, dom(1:2), techCol);\ny = mypoints(n, dom(3:4), techCol);\nz = mypoints(p, dom(5:6), techCol);\n[xx, yy, zz] = ndgrid(x, y, z);\nvals = feval(f, xx, yy, zz); \n\n% Take the absolute maximum: \nvscl = max(abs(vals(:)));\n\nend\n\n%%\nfunction x = mypoints(n, dom, tech)\n% Get the sample points that correspond to the right grid for a particular\n% technology.\n\n% What tech am I based on?:\nif ( isa(tech(), 'chebtech2') )    \n    x = chebpts(n, dom, 2);\nelseif ( isa(tech(), 'chebtech1') )    \n    x = chebpts(n, dom, 1);\nelseif ( isa(tech(), 'trigtech') )\n    x = trigpts(n, dom);\nelse\n    error('CHEBFUN:CHEBFUN3:vscale:mypoints:techType', ...\n        'Unrecognized technology');\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/@chebfun3/vscale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.5680706446249849}}
{"text": "function [f,J] = spm_fx_lfp(x,u,P,M)\n% state equations for a neural mass model of erps\n% FORMAT [f,J] = spm_fx_lfp(x,u,P,M)\n% x      - state vector\n%   x(:,1)  - voltage (spiny stellate cells)\n%   x(:,2)  - voltage (pyramidal cells)         +ve\n%   x(:,3)  - voltage (pyramidal cells)         -ve\n%   x(:,4)  - current (spiny stellate cells)    +ve \n%   x(:,5)  - current (pyramidal cells)         +ve\n%   x(:,6)  - current (pyramidal cells)         -ve\n%   x(:,7)  - voltage (inhibitory interneurons) +ve\n%   x(:,8)  - current (inhibitory interneurons) +ve\n%   x(:,9)  - voltage (pyramidal cells)\n%   x(:,10) - voltage (inhibitory interneurons) -ve\n%   x(:,11) - current (inhibitory interneurons) -ve\n%   x(:,12) - voltage (inhibitory interneurons)\n%\n%   x(:,13) - slow potassium conductance\n%\n% f    = dx(t)/dt  = f(x(t))\n% J    = df/dx\n%\n% Fixed parameter scaling [Defaults]\n%\n%  E = [32 16 4];             % extrinsic rates (forward, backward, lateral)\n%  G = [1 1 1/2 1/2 1/8]*128; % intrinsic rates (g1, g2, g3, g4, g5)\n%  D = [2 16];                % propagation delays (intrinsic, extrinsic)\n%  H = [4 32];                % receptor densities (excitatory, inhibitory)\n%  T = [4 16];                % synaptic constants (excitatory, inhibitory)\n%  R = [2 1];                 % parameters of static nonlinearity\n%\n%__________________________________________________________________________\n%\n% This is a simplified version of spm_fx_erp\n%\n% David O, Friston KJ (2003) A neural mass model for MEG/EEG: coupling and\n% neuronal dynamics. NeuroImage 20: 1743-1755\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_fx_lfp.m 5369 2013-03-28 20:09:27Z karl $\n\n% check if intrinsic connections are free parameters\n%--------------------------------------------------------------------------\ntry, P.H; catch, P.H = 0; end\n\n% get dimensions and configure state variables\n%--------------------------------------------------------------------------\nx    = spm_unvec(x,M.x);       % neuronal states\nn    = size(x,1);              % number of sources\ns    = size(x,2);              % number of states\n\n% [default] fixed parameters\n%--------------------------------------------------------------------------\nE    = [32 16 4];              % extrinsic rates (forward, backward, lateral)\nG    = [1 1 1/2 1/2 1/32]*128; % intrinsic rates (g1, g2 g3, g4)\nD    = [2 4];                  % propagation delays (intrinsic, extrinsic)\nH    = [8 32];                 % receptor densities (excitatory, inhibitory)\nT    = [4 16];                 % synaptic constants (excitatory, inhibitory)\nR    = [1 2];                  % parameters of static nonlinearity\n\n% [specified] fixed parameters\n%--------------------------------------------------------------------------\nif isfield(M,'pF')\n    try, E  = M.pF.E; end\n    try, G  = M.pF.H; end\n    try, D  = M.pF.D; end\n    try, H  = M.pF.G; end\n    try, T  = M.pF.T; end\n    try, R  = M.pF.R; end\nend\n\n% exponential transform to ensure positivity constraints\n%--------------------------------------------------------------------------\nA{1} = exp(P.A{1})*E(1);\nA{2} = exp(P.A{2})*E(2);\nA{3} = exp(P.A{3})*E(3);\nC    = exp(P.C);\nG    = exp(P.H)*diag(G);\n \n% intrinsic connectivity and parameters\n%--------------------------------------------------------------------------\nTe   = T(1)/1000*exp(P.T(:,1));      % excitatory time constants\nTi   = T(2)/1000*exp(P.T(:,2));      % inhibitory time constants\nTk   = 512/1000;                     % slow potassium\nHe   = H(1)*exp(P.G);                % excitatory receptor density\nHi   = H(2);                         % inhibitory receptor density\n\n\n% pre-synaptic inputs: s(V) with threshold adaptation\n%--------------------------------------------------------------------------\nR      = R.*exp(P.R);\nx      = x';\nX      = x;\nX(1,:) = X(1,:) - X(13,:);\nS      = 1./(1 + exp(-R(1)*(X - R(2)))) - 1./(1 + exp(R(1)*R(2)));\ndSdx   = R(1)*exp(-R(1)*(max(X,-128) - R(2)))./(1 + exp(-R(1)*(X - R(2)))).^2;\n \n% input\n%==========================================================================\nif isfield(M,'u')\n    \n    % endogenous input\n    %----------------------------------------------------------------------\n    U = u(:)*32;\n    \nelse\n    % exogenous input\n    %----------------------------------------------------------------------\n    U = C*u(:);\nend\n\n\n% State: f(x) and Jacobian dfdx\n%==========================================================================\n \n% NB: activity-dependent reduction in inhibitory effective time-constant\n%--------------------------------------------------------------------------\nTi    = 4/1000 + Ti;\n \n% intrinsic coupling\n%--------------------------------------------------------------------------\nfor i = 1:n\n \n    % synaptic dynamics - dfdx\n    %----------------------------------------------------------------------\n    ke    = -2/Te(i);\n    ki    = -2/Ti(i);\n    Ke    = -1/(Te(i)^2);\n    Ki    = -1/(Ti(i)^2);\n    dfdx  = [0   0   0   1   0   0   0   0   0   0   0   0   0\n             0   0   0   0   1   0   0   0   0   0   0   0   0\n             0   0   0   0   0   1   0   0   0   0   0   0   0\n             Ke  0   0   ke  0   0   0   0   0   0   0   0   0\n             0   Ke  0   0   ke  0   0   0   0   0   0   0   0\n             0   0   Ki  0   0   ki  0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   1   0   0   0   0   0\n             0   0   0   0   0   0  Ke   ke  0   0   0   0   0\n             0   0   0   0   1   -1  0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   1   0   0\n             0   0   0   0   0   0   0   0   0  Ki   ki  0   0\n             0   0   0   0   0   0   0   1   0   0  -1   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0  -1/Tk];\n         \n    % intrinsic afferents - dfdS\n    %----------------------------------------------------------------------\n    Ke    = He(i)/Te(i);\n    Ki    = Hi/Ti(i);\n    \n    j1    = Ke*G(i,1);\n    j2    = Ke*G(i,2);\n    j3    = Ke*G(i,3);\n    j4    = Ki*G(i,4);\n    j5    = Ki*G(i,5);\n    dfdS  = [0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   j1  0   0   0   0\n             j2  0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   j4  0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   j3  0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0  j5   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n            4/Tk 0   0   0   0   0   0   0   0   0   0   0   0];\n     \n    % motion and Jacobian\n    %----------------------------------------------------------------------\n    dsdx       = diag(dSdx(:,i));\n    dsdx(1,13) = -dsdx(1,1);\n    dfdu       = sparse(4,1,Ke,s,1);\n    \n    F{i}       = dfdx*x(:,i) + dfdS*S(:,i) + dfdu*U(i);\n    J{i,i}     = dfdx + dfdS*dsdx;\n    \n    % extrinsic afferents \n    %----------------------------------------------------------------------\n    for j = 1:n, if i ~= j\n    \n    k1    = Ke*(A{1}(i,j) + A{3}(i,j));\n    k2    = Ke*(A{2}(i,j) + A{3}(i,j));\n    k3    = Ki*(A{2}(i,j) + A{3}(i,j));\n    dfdS  = [0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   k1  0   0   0   0\n             0   0   0   0   0   0   0   0   k2  0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   k3  0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0\n             0   0   0   0   0   0   0   0   0   0   0   0   0];\n         \n    % motion and Jacobian\n    %----------------------------------------------------------------------\n    F{i}   = F{i} + dfdS*S(:,j);\n    J{i,j} = dfdS*diag(dSdx(:,j));\n    \n    end, end\nend\n \n% construct motion and Jacobian\n%--------------------------------------------------------------------------\nfor i = 1:n\n    k      = (1:n:s*n) + (i - 1);\n    f(k,1) = F{i};\n    for j  = 1:n\n        l         = [1:n:s*n] + (j - 1);\n        dfdx(k,l) = J{i,j};\n    end    \nend\n \n% extrinsic and intrinsic delays\n%--------------------------------------------------------------------------\nDe = D(2).*exp(P.D)/1000;\nDi = D(1).*exp(P.I)/1000;\nDe = (eye(n,n) - 1).*De;\nDi = (eye(s,s) - 1)*Di;\nDe = kron(ones(s,s),De);\nDi = kron(Di,eye(n,n));\n \nD  = Di + De;\n \n% Implement: dx(t)/dt = f(x(t + d)) = inv(1 - D.*dfdx)*f(x(t))\n%--------------------------------------------------------------------------\nD  = spm_inv(speye(n*s,n*s) - D.*dfdx);\nf  = D*f;\nJ  = D*dfdx;\n \nreturn\n \n% Equations of motion\n%==========================================================================\n \n% Supragranular layer (inhibitory interneurons): depolarizing current\n%--------------------------------------------------------------------------\nf(:,7)  = x(:,8);\nf(:,8)  = (He.*((A{2} + A{3})*S(:,9) + G(:,3).*S(:,9)) ...\n           - 2*x(:,8) - x(:,7)./Te)./Te;\n      \n% Supragranular layer (inhibitory interneurons): hyperpolarizing current\n%--------------------------------------------------------------------------\nf(:,10) = x(:,11);\nf(:,11) = (Hi*G(:,5).*S(:,12) ...\n           - 2*x(:,11) - x(:,10)./Ti)./Ti;\n \n% Granular layer (spiny stellate cells): depolarizing current\n%--------------------------------------------------------------------------\nf(:,1)  = x(:,4);\nf(:,4)  = (He.*((A{1} + A{3})*S(:,9) + G(:,1).*S(:,9) + U) ...\n           - 2*x(:,4) - x(:,1)./Te)./Te;\n       \n% Infra-granular layer (pyramidal cells): depolarizing current\n%--------------------------------------------------------------------------\nf(:,2)  = x(:,5);\nf(:,5)  = (He.*((A{2} + A{3})*S(:,9) + G(:,2).*S(:,1)) ...\n           - 2*x(:,5) - x(:,2)./Te)./Te;\n \n% Infra-granular layer (pyramidal cells): hyperpolarizing current\n%--------------------------------------------------------------------------\nf(:,3)  = x(:,6);\nf(:,6)  = (Hi*G(:,4).*S(:,12) ...\n           - 2*x(:,6) - x(:,3)./Ti)./Ti;\n \n% Surpa and Infra-granular layer (pyramidal cells): Voltage\n%--------------------------------------------------------------------------\nf(:,9)  = x(:,5) - x(:,6);\nf(:,12) = x(:,8) - x(:,11);\n \n% Granular layer (spiny stellate cells): hyperpolarizing current\n%--------------------------------------------------------------------------\nf(:,13) = (4*S(:,1) - x(:,13))./Tk;\n \n% Jacobian for delays (evaluate numerically for simplicity)\n%==========================================================================\ndfdx = spm_diff('spm_fx_lfp',x,u,P,1,1);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/Neural_Models/spm_fx_lfp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.5680067491850476}}
{"text": "function check = exponential_check ( a, b )\n\n%*****************************************************************************80\n%\n%% EXPONENTIAL_CHECK checks the parameters of the Exponential CDF.\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 parameter of the PDF.\n%    0.0 < B.\n%\n  if ( b <= 0.0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'EXPONENTIAL_CHECK - Fatal error!\\n' );\n    fprintf ( 1, '  B <= 0.0\\n' );\n    check = 0;\n    return\n  end\n\n  check = 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/prob/exponential_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.5678925522425423}}
{"text": "function [u,s,U_r,U_s,U_pk,U_pd,U_l]  = projAhmPntIntoPinHoleOnRob(Rf, Sf, Spk, Spd, l)\n\n% PROJAHMPNTINTOPINHOLEONROB Project Ahm pnt into pinhole on robot.\n%    [U,S] = PROJAHMPNTINTOPINHOLEONROB(RF, SF, SPK, SPD, L) projects 3D\n%    anchored homogeneous points into a pin-hole camera mounted on a robot,\n%    providing also the non-measurable depth. The input parameters are:\n%       RF : robot frame\n%       SF : pin-hole sensor frame in robot\n%       SPK: pin-hole intrinsic parameters [u0 v0 au av]'\n%       SPD: radial distortion parameters [K2 K4 K6 ...]'\n%       L  : 3D anchored homog. point [x y z vx vy vz rho]'\n%    The output parameters are:\n%       U  : 2D pixel [u v]'\n%       S  : non-measurable depth\n%\n%    The function accepts an ahm points matrix L = [L1 ... Ln] as input.\n%    In this case, it returns a pixels matrix U = [U1 ... Un] and a depths\n%    row-vector S = [S1 ... Sn].\n%\n%    [U,S,U_R,U_S,U_K,U_D,U_L] = ... gives also the jacobians of the\n%    observation U wrt all input parameters. Note that this only works for\n%    single points.\n%\n%    See also PINHOLE, TOFRAME, PROJEUCPNTINTOPINHOLEONROB.\n\n%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n\nif nargout <= 2  % No Jacobians requested\n\n    p     = ahm2euc(l);\n    [u,s] = projEucPntIntoPinHoleOnRob(Rf, Sf, Spk, Spd, p);\n\nelse            % Jacobians requested\n\n    if size(l,2) == 1\n        \n        % function calls\n        [p,P_l]                     = ahm2euc(l);\n        [u,s,U_r,U_s,U_pk,U_pd,U_p] = projEucPntIntoPinHoleOnRob(Rf, Sf, Spk, Spd, p);\n\n        % chain rule\n        U_l = U_p*P_l;\n\n    else\n        error('??? Jacobians not available for multiple AHM points.')\n\n    end\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 <http://www.gnu.org/licenses/>.\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/projAhmPntIntoPinHoleOnRob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5678925357423341}}
{"text": "classdef CI_HS < PROBLEM\n% <single> <real> <large/none> <multitask>\n% Multitasking problem (Griewank function + Rastrigin function)\n% SubD --- 50,50 --- Number of decision variables of each task\n\n%------------------------------- Reference --------------------------------\n% K. K. Bali, Y. Ong, A. Gupta, and P. S. Tan, Multifactorial evolutionary\n% algorithm with online transfer parameter estimation: MFEA-II, IEEE\n% Transactions on Evolutionary Computation, 2020, 24(1): 69-83.\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        SubD;   % Number of decision variables of each task\n        L1;   \t% Low bounds of the first task\n        L2;   \t% Low bounds of the second task\n        U1;   \t% Upper bounds of the first task\n        U2;   \t% Upper bounds of the second task\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.SubD     = obj.ParameterSet([50,50]);\n            obj.M        = 1;\n            obj.D        = max(obj.SubD) + 1;\n            obj.L1       = zeros(1,obj.SubD(1)) - 600;\n            obj.U1       = zeros(1,obj.SubD(1)) + 600;\n            obj.L2       = zeros(1,obj.SubD(2)) - 5.12;\n            obj.U2       = zeros(1,obj.SubD(2)) + 5.12;\n            obj.lower    = [zeros(1,obj.D-1),1];\n            obj.upper    = [ones(1,obj.D-1),length(obj.SubD)];\n            obj.encoding = [ones(1,obj.D-1),2];\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            PopObj = zeros(size(PopDec,1),1);\n            for i = 1 : size(PopDec,1)\n                if PopDec(i,end) == 1       % Task 1\n                    x1 = obj.L1 + PopDec(i,1:obj.SubD(1)).*(obj.U1-obj.L1);\n                    PopObj(i) = 1/4000*sum(x1.^2,2) - prod(cos(x1./sqrt(repmat(1:size(x1,2),size(x1,1),1))),2) + 1;\n                elseif PopDec(i,end) == 2   % Task 2\n                    x2 = obj.L2 + PopDec(i,1:obj.SubD(2)).*(obj.U2-obj.L2);\n                    PopObj(i) = sum(x2.^2-10*cos(2*pi*x2)+10,2);\n                end\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/Single-objective optimization/Multitasking SOPs/CI_HS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126792, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5678925326941159}}
{"text": "% read a g2o data file describing a 2D SLAM instance\nfunction graph = read_graph(filename)\n\nfid = fopen(filename, 'r');\n\ngraph = struct (\n  'x', [],\n  'edges', [],\n  'idLookup', struct\n);\n\ndisp('Parsing File');\nwhile true\n  ln = fgetl(fid);\n  if (ln == -1)\n    break;\n  end\n  tokens = strsplit(ln, ' ', true);\n  double_tokens = str2double(tokens);\n\n  tk = 2;\n  if (strcmp(tokens(1), 'VERTEX_SE2') != 0)\n    id = int32(double_tokens(tk++));\n    values = double_tokens(tk:tk+2)'; tk += 3;\n    graph.idLookup = setfield(graph.idLookup, num2str(id), struct('offset', length(graph.x), 'dimension', length(values)));\n    graph.x = [graph.x; values];\n  elseif (strcmp(tokens(1), 'VERTEX_XY') != 0)\n    id = int32(double_tokens(tk++));\n    values = double_tokens(tk:tk+1)'; tk += 2;\n    graph.idLookup = setfield(graph.idLookup, num2str(id), struct('offset', length(graph.x), 'dimension', length(values)));\n    graph.x = [graph.x; values];\n  elseif (strcmp(tokens(1), 'EDGE_SE2') != 0)\n    fromId = int32(double_tokens(tk++));\n    toId = int32(double_tokens(tk++));\n    measurement = double_tokens(tk:tk+2)'; tk += 3;\n    uppertri = double_tokens(tk:tk+5)'; tk += 6;\n    information = [uppertri(1), uppertri(2), uppertri(3);\n                   uppertri(2), uppertri(4), uppertri(5);\n                   uppertri(3), uppertri(5), uppertri(6)];\n    graph.edges = [graph.edges; struct(\n      'type', 'P',\n      'from', fromId,\n      'to', toId,\n      'measurement', measurement,\n      'information', information)];\n  elseif (strcmp(tokens(1), 'EDGE_SE2_XY') != 0)\n    fromId = int32(double_tokens(tk++));\n    toId = int32(double_tokens(tk++));\n    measurement = double_tokens(tk:tk+1)'; tk += 2;\n    uppertri = double_tokens(tk:tk+2)'; tk += 3;\n    information = [uppertri(1), uppertri(2); uppertri(2), uppertri(3)];\n    graph.edges = [graph.edges; struct(\n      'type', 'L',\n      'from', fromId,\n      'to', toId,\n      'measurement', measurement,\n      'information', information)];\n  end\n\nend\n\n% setup the index into the state vector\ndisp('Preparing helper structs');\nfor eid = 1:length(graph.edges)\n  graph.edges(eid).fromIdx = getfield(graph.idLookup, num2str(graph.edges(eid).from)).offset + 1;\n  graph.edges(eid).toIdx = getfield(graph.idLookup, num2str(graph.edges(eid).to)).offset + 1;\nend\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/tools/read_graph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101079, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.567892523549461}}
{"text": "function d = NormL1NN_dual(x,weights)\n% Dual of non-negative L1 gauge function\n\nx(x < 0) = 0;\nd = norm(x./weights,inf);\n", "meta": {"author": "mpf", "repo": "spgl1", "sha": "361a5980667288857e4f4f84c53b536ddfac1d53", "save_path": "github-repos/MATLAB/mpf-spgl1", "path": "github-repos/MATLAB/mpf-spgl1/spgl1-361a5980667288857e4f4f84c53b536ddfac1d53/NormL1NN_dual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.5678171593255558}}
{"text": "function F  = obj_actuator_freq_resp_param(x,amplitude_40, frequency_40, amplitude_100, frequency_100)\n% Computes objective function for determination of basic parameters of\n% the proportional valve actuator that match the required frequency\n% response. The frequency response of a nonlinear system is obtained by \n% using frestimate.  The required and actual frequency responses are\n% compared. \n% Copyright 2010 MathWorks, Inc.\n\n% Manufacturer's characterstic\n%RefFR_100_Frq =     [7 10 20 30 40 43 50 54];\n%RefFR_100_Phs = -1*[25 35 59 75 87 90 96 100];\n%RefFR_40_Frq =     [7 10 20 30 40 50 57 70];\n%RefFR_40_Phs = -1*[21 30 50 63 75 85 90 100];\n\nmodel = 'actuator_freq_resp';\nload_system(model);\n\nassignin('base','act_gain', x(1));\nassignin('base','time_const', x(2));\nassignin('base','act_saturation', x(3));\n\n% Computing phase angle at current values of variable parameters\n\n% Determine inputs and outputs\nios = getlinio(model);\n\n% Generate input at test frequencies\nin100 = frest.Sinestream(...\n   'Frequency',frequency_100, ...\n   'Amplitude', amplitude_100*ones(size(frequency_100)), ...\n   'SimulationOrder', 'Sequential', ... \n   'FreqUnits', 'Hz');\n\nin40 = frest.Sinestream(...\n   'Frequency',frequency_40, ...\n   'Amplitude', amplitude_40*ones(size(frequency_40)), ...\n   'SimulationOrder', 'Sequential', ... \n   'FreqUnits', 'Hz');\n\n% Test model, determine phase\nsys100 = frestimate(model,ios,in100);\nR100 = sys100.ResponseData(:);\nLag = angle(R100)/pi*180; \nphase_100_20 = Lag(1); phase_100_43 = Lag(2);\n\n% Test model, determine phase\nsys40 = frestimate(model,ios,in40);\nR40 = sys40.ResponseData(:);\nLag = angle(R40)/pi*180; \nphase_40_20 = Lag(1); phase_40_57 = Lag(2);\n\n% Calculate difference from manufacturer's characteristic\nF = (phase_100_20 + 59)^2 + (phase_100_43 + 90)^2 + ...\n    (phase_40_20 + 50)^2 + (phase_40_57 + 90)^2; \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/27260-hydraulic-valve-parameters-from-data-sheets-and-experimental-data/Valve_Params_SH/Ex8_Prop_Servo_Freq_Resp_Direct/SH_freq_resp/obj_actuator_freq_resp_param.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5678171516651792}}
{"text": "function [D,D1ols,q,C]=irfiv_ols_for_bootstrap_GK(txt,names,IVrotate,betadraw,n,Xdraw,Ydraw,k,p,enddate,startdate,cut1,cut2,cut3,cut4)\n%% Copyright Ben Schumann\n% function [D, gamma]=bear.irfiv_ols(names, betahat,sigmahat, n,X,Y,k,p,enddate,startdate)\n% instrumental variable identification in an OLS setting\n% inputs:  - matrix 'betahat': vec(OLS estimates of the reduced form)\n%          - matrix 'sigmahat': vec(OLS estimates of sigma)\n%          - matrix 'X': Independend Variable\n%          - matrix 'Y': Dependend Variable\n%          - matrix 'IV': Rotated IV from wild bootstrap\n%          - integer 'IRFperiods': number of periods for IRFs\n%          - integer 'n': number of endogenous variables in the VAR model (defined p 7 of technical guide)\n%          - integer 'm': number of exogenous variables in the VAR model (defined p 7 of technical guide)\n%          - integer 'p': number of lags included in the model (defined p 7 of technical guide)\n%          - integer 'k': number of coefficients to estimate for each equation in the BVAR model (defined p 7 of technical guide)\n%          - integer 'T': number of observations\n%          - string  'stardate': VAR startdate\n%          - string  'enddate': VAR enddate\n% outputs: - matrix 'D': record of the accepted draws for the structural matrix D\n%          - matrix 'gamma': record of the draws for the structural disturbances variance-covariance matrix gamma\nIV = IVrotate; \n%% Preparation for first stage regression\n%get reduced form residuals\nbeta = betadraw;\nB    = reshape(beta,k,n);\nEPS  = Ydraw-Xdraw*B;\n\n[EPSIV,IVcut] = bear.cut_EPS_IV_GK_new(txt, names, EPS, IV, cut1, cut2, cut3, cut4, startdate, enddate, p);\n\n%% Imposing the covariance restrictions \n%E_1 = EPSIV'*IVcut/length(IVcut);\n%E11 = E_1(1,:);\n%E21 = E_1(2:end,:);\n%Mu = E21*E11^(-1); %relative impulse vector\n%% normalize to a one standard deviation shock\nsigmahatIV=(1/(length(EPSIV)-k))*(EPSIV'*EPSIV); \n\n%get the gamma vector\n%partition the reduced form VCV\n%Sigma11 = sigmahatIV(1,1);\n%Sigma12 = sigmahatIV(1,2:end);\n%Sigma21 = sigmahatIV(2:end,1);   \n%Sigma22 = sigmahatIV(2:end,2:end); \n\n%Gamma = Sigma22 + Mu*Sigma11*Mu' - Sigma21*Mu' - Mu*Sigma21'; %%%%%Gamma ouput is not used after this\n%get b12 as in Michelle Piffers notes\n%b12b12t = (Sigma21-Mu*Sigma11)'*Gamma^(-1)*(Sigma21-Mu*Sigma11);\n%b11b11t = Sigma11 - b12b12t;\n% b11 = chol(bear.nspd(b11b11t)); %%this is the scaling vector \n\n%% first stage regression (this results in the same vector as Mu)\n\n%step 2: Regress the first reduced form shock on the instrument\nShock = EPSIV(:,1);\n[nobs , ~] = size(IVcut);\nXX = [ones(nobs,1) IVcut];\n[~, nvar] = size(XX);\n%get OLS estimate\nXpXi = (XX'*XX)\\eye(nvar);\nbetaIV=XpXi*(XX'*Shock);\n%get predicted value\nIVpred = XX*betaIV;\n\n%% second stage regression\n%step 3: Regress the other reduced form shocks on the predicted value\nImpactIRFIV = zeros(n,1);\nImpactIRFIV(1,1) = 1;\n\nfor hh=2:n\nShock = EPSIV(:,hh);\n[nobs,~]= size(IVpred);\nIVpredtemp = [ones(nobs,1) IVpred];\n[~,nvar] = size(IVpredtemp);\nIVpIVi = (IVpredtemp'*IVpredtemp)\\eye(nvar);\nbetaIV2=IVpIVi*(IVpredtemp'*Shock);\nImpactIRFIV(hh,1) = betaIV2(2,1); %should be equal to Mu from 2:end\nend\n\n\n% step 5: Create the structural matrix and only fill the first column as\n% this is the only one identified\nD=zeros(n,n);\n% Step 6: Replace the first Column in the Cholesky Decomposition by \n%the structural impact matrix computed above\n%%another way to retrieve b11 (the scalar that scales the IRF to be a 1sdt Shock) is simply\nC=chol(bear.nspd(sigmahatIV),'lower');\nb=ImpactIRFIV;\n%%Recover the vector q that maps the first column of C into b such that Cq=b;\nq = C\\b;\n%%b11 is the euclidian length of q\nb11q = 1/norm(q);\n\n%\nD(1:end,1) = ImpactIRFIV*b11q;\nD1ols = ImpactIRFIV*b11q; % for the IRFt6 TakeOLS option\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/irfiv_ols_for_bootstrap_GK.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5678171373055487}}
{"text": "function [ f,qualMeasOut] = PCSD(proj,geo,angles,maxiter,varargin)\n%PCSD solves the reconstruction problem using projection-controlled steepest descent method\n%\n%   PCSD(PROJ,GEO,ALPHA,NITER) solves the reconstruction problem using\n%   the projection data PROJ taken over ALPHA angles, corresponding to the\n%   geometry described in GEO, using NITER iterations.\n%\n%   PCSD(PROJ,GEO,ALPHA,NITER,OPT,VAL,...) uses options and values for solving. The\n%   possible options in OPT are:\n%\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%\n%       'init':    Describes diferent initialization techniques.\n%                   \u2022  'none'     : Initializes the image to zeros (default)\n%                   \u2022  'FDK'      : intializes image to FDK reconstrucition\n%\n%   'TViter':      Defines the amount of TV iterations performed per SART\n%                  iteration. Default is 20\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%   'Verbose'      1 or 0. Default is 1. Gives information about the\n%                  progress of the algorithm.\n% 'redundancy_weighting': true or false. Default is true. Applies data\n%                         redundancy weighting to projections in the update step\n%                         (relevant for offset detector geometry)\n%  'groundTruth'  an image as grounf truth, to be used if quality measures\n%                 are requested, to plot their change w.r.t. this known\n%                 data.\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 and Manasavee Lohvithee\n%--------------------------------------------------------------------------\n\n%% parse inputs\n[beta,beta_red,f,ng,verbose,epsilon,QualMeasOpts,nonneg,gpuids,redundancy_weights,gt]=parse_inputs(proj,geo,angles,varargin);\n\nmeasurequality=~isempty(QualMeasOpts) | ~any(isnan(gt(:)));\nif ~any(isnan(gt(:)))\n    QualMeasOpts{end+1}='error_norm';\n    res_prev=gt;\n    clear gt\nend\nif nargout<2 && measurequality\n    warning(\"Image metrics requested but none catched as output. Call the algorithm with 3 outputs to store them\")\n    measurequality=false;\nend\nqualMeasOut=zeros(length(QualMeasOpts),niter);\n\n% does detector rotation exists?\nif ~isfield(geo,'rotDetector')\n    geo.rotDetector=[0;0;0];\nend\n\n%% Create weigthing matrices for the SART step\n% the reason we do this, instead of calling the SART fucntion is not to\n% recompute the weigths every AwASD-POCS iteration, thus effectively doubling\n% the computational time\n% Projection weigth, W\n\ngeoaux=geo;\ngeoaux.sVoxel([1 2])=geo.sVoxel([1 2])*1.1; % a Bit bigger, to avoid numerical division by zero (small number)\ngeoaux.sVoxel(3)=max(geo.sDetector(2),geo.sVoxel(3)); % make sure lines are not cropped. One is for when image is bigger than detector and viceversa\ngeoaux.nVoxel=[2,2,2]'; % accurate enough?\ngeoaux.dVoxel=geoaux.sVoxel./geoaux.nVoxel;\nW=Ax(ones(geoaux.nVoxel','single'),geoaux,angles,'Siddon','gpuids',gpuids);\nW(W<min(geo.dVoxel)/4)=Inf;\nW=1./W;\n\n% Compute V\nV=computeV(geo,angles,num2cell(angles),num2cell(1:length(angles)),'gpuids',gpuids);\n\nif redundancy_weights\n    % Data redundancy weighting, W_r implemented using Wang weighting\n    % reference: https://iopscience.iop.org/article/10.1088/1361-6560/ac16bc\n    \n    num_frames = size(proj,3);\n    W_r = redundancy_weighting(geo);\n    W_r = repmat(W_r,[1,1,num_frames]);\n    % disp('Size of redundancy weighting matrix');\n    % disp(size(W_r));\n    W = W.*W_r; % include redundancy weighting in W\nend\n\n%Initialize image.\n%f=zeros(geo.nVoxel','single');\n\niter=0;\noffOrigin=geo.offOrigin;\noffDetector=geo.offDetector;\nrotDetector=geo.rotDetector;\nstop_criteria=0;\nDSD=geo.DSD;\nDSO=geo.DSO;\n%%\nwhile ~stop_criteria %POCS\n    % If quality is going to be measured, then we need to save previous image\n    if measurequality && ~strcmp(QualMeasOpts,'error_norm')\n        res_prev = f; % only store if necesary\n    end\n    if (iter==0 && verbose==1);tic;end\n    iter=iter+1;\n    \n    %Estimation error in the projection domain\n    est_proj=Ax(f,geo,angles,'interpolated','gpuids',gpuids);\n    delta_p=im3Dnorm(est_proj-proj,'L2');\n    \n    %Enforcing ART along all projections if squared delta_p > epsilon\n    if (delta_p^2)>epsilon\n        for jj=1:size(angles,2)\n            if size(offOrigin,2)==size(angles,2)\n                geo.offOrigin=offOrigin(:,jj);\n            end\n            if size(offDetector,2)==size(angles,2)\n                geo.offDetector=offDetector(:,jj);\n            end\n            if size(rotDetector,2)==size(angles,2)\n                geo.rotDetector=rotDetector(:,jj);\n            end\n            if size(DSD,2)==size(angles,2)\n                geo.DSD=DSD(jj);\n            end\n            if size(DSO,2)==size(angles,2)\n                geo.DSO=DSO(jj);\n            end\n            f=f+beta* bsxfun(@times,1./V(:,:,jj),Atb(W(:,:,jj).*(proj(:,:,jj)-Ax(f,geo,angles(:,jj),'gpuids',gpuids)),geo,angles(:,jj),'gpuids',gpuids));\n            \n        end\n    end\n    \n    %Non-negativity projection on all pixels\n    if nonneg\n        f=max(f,0);\n    end\n    \n    geo.offDetector=offDetector;\n    geo.offOrigin=offOrigin;\n    geo.DSD=DSD;\n    geo.DSO=DSO;\n    geo.rotDetector=rotDetector;\n    if measurequality\n        qualMeasOut(:,iter)=Measure_Quality(res_prev,f,QualMeasOpts);\n    end\n    \n    % Compute L2 error of actual image. Ax-b\n    dd=im3Dnorm(Ax(f,geo,angles,'gpuids',gpuids)-proj,'L2');\n    % Compute change in the image after last SART iteration\n    dp_vec=(f-f0);\n    \n    if iter==1\n        step=1;\n    else\n        step=delta_p/delta_p_first;\n    end\n    f0=f;\n    %  TV MINIMIZATION\n    % =========================================================================\n    %  Call GPU to minimize TV\n    f=minimizeTV(f0,step,ng,'gpuids',gpuids);    %   This is the MATLAB CODE, the functions are sill in the library, but CUDA is used nowadays\n    %                                             for ii=1:ng\n    %                                                 %delta=-0.00038 for thorax phantom\n    %                                                 df=weighted_gradientTVnorm(f,delta);\n    %                                                 df=df./im3Dnorm(df,'L2');\n    %                                                 f=f-(step.*df);\n    %                                             end\n    \n    % Compute change by TV min\n    dg_vec=(f-f0);\n    \n    if iter==1\n        delta_p_first=im3Dnorm((Ax(f0,geo,angles,'interpolated','gpuids',gpuids))-proj,'L2');\n    end\n    \n    % Reduce SART step\n    beta=beta*beta_red;\n    \n    % Check convergence criteria\n    % ==========================================================================\n    \n    %Define c_alpha as in equation 21 in the journal\n    c=dot(dg_vec(:),dp_vec(:))/(norm(dg_vec(:),2)*norm(dp_vec(:),2));\n    %This c is examined to see if it is close to -1.0\n    \n    if (c<-0.99 && dd<=epsilon) || beta<0.005|| iter>maxiter\n        if verbose\n            disp(['Stopping criteria met']);\n            disp(['   c    = ' num2str(c)]);\n            disp(['   beta = ' num2str(beta)]);\n            disp(['   iter = ' num2str(iter)]);\n        end\n        stop_criteria=true;\n    end\n    \n    if (iter==1 && verbose==1)\n        expected_time=toc*maxiter;\n        disp('PCSD');\n        disp(['Expected duration  :    ',secs2hms(expected_time)]);\n        disp(['Expected finish time:    ',datestr(datetime('now')+seconds(expected_time))]);\n        disp('');\n    end\n    \nend\nend\n\n\nfunction [beta,beta_red,f0,ng,verbose,epsilon,QualMeasOpts,nonneg,gpuids,redundancy_weights]=parse_inputs(proj,geo,angles,argin)\nopts=     {'lambda','lambda_red','init','tviter','verbose','maxl2err','qualmeas','nonneg','gpuids','redundancy_weighting'};\ndefaults=ones(length(opts),1);\n% Check inputs\nnVarargs = length(argin);\nif mod(nVarargs,2)\n    error('CBCT:PCSD:InvalidInput','Invalid number of inputs')\nend\n\n% check if option has been passed as input\nfor ii=1:2:nVarargs\n    ind=find(ismember(opts,lower(argin{ii})));\n    if ~isempty(ind)\n        defaults(ind)=0;\n    else\n        error('CBCT:PCSD:InvalidInput',['Optional parameter \"' argin{ii} '\" does not exist' ]);\n    end\nend\n\nfor ii=1:length(opts)\n    opt=opts{ii};\n    default=defaults(ii);\n    % if one option isnot default, then extract value from input\n    if default==0\n        ind=double.empty(0,1);jj=1;\n        while isempty(ind)\n            ind=find(isequal(opt,lower(argin{jj})));\n            jj=jj+1;\n        end\n        if isempty(ind)\n            error('CBCT:PCSD:InvalidInput',['Optional parameter \"' argin{jj} '\" does not exist' ]);\n        end\n        val=argin{jj};\n    end\n    % parse inputs\n    switch opt\n        % Verbose\n        %  =========================================================================\n        case 'verbose'\n            if default\n                verbose=1;\n            else\n                verbose=val;\n            end\n            if ~is2014bOrNewer\n                warning('Verbose mode not available for older versions than MATLAB R2014b');\n                verbose=false;\n            end\n        % Lambda\n        %  =========================================================================\n        case 'lambda'\n            if default\n                beta=1;\n            else\n                if length(val)>1 || ~isnumeric( val)\n                    error('TIGRE:PCSD:InvalidInput','Invalid lambda')\n                end\n                beta=val;\n            end\n        % Lambda reduction\n        %  =========================================================================\n        case 'lambda_red'\n            if default\n                beta_red=0.99;\n            else\n                if length(val)>1 || ~isnumeric( val)\n                    error('TIGRE:PCSD:InvalidInput','Invalid lambda')\n                end\n                beta_red=val;\n            end\n        % Initial image\n        %  =========================================================================\n        case 'init'\n            if default || strcmp(val,'none')\n                f0=zeros(geo.nVoxel','single');\n\n            else\n                if strcmp(val,'FDK')\n                    f0=FDK(proj, geo, angles);\n                else\n                    error('TIGRE:PCSD:InvalidInput','Invalid init')\n                end\n            end\n        % Number of iterations of TV\n        %  =========================================================================\n        case 'tviter'\n            if default\n                ng=20;\n            else\n                ng=val;\n            end\n        %  Maximum L2 error to have a \"good image\"\n        %  =========================================================================\n        case 'maxl2err'\n            if default\n                epsilon=im3Dnorm(FDK(proj,geo,angles))*0.2; %heuristic\n            else\n                epsilon=val;\n            end\n        %Image Quality Measure\n        %  =========================================================================\n        case 'qualmeas'\n            if default\n                QualMeasOpts={};\n            else\n                if iscellstr(val)\n                    QualMeasOpts=val;\n                else\n                    error('TIGRE:PCSD:InvalidInput','Invalid quality measurement parameters');\n                end\n            end\n        %  Non negative\n        %  =========================================================================\n        case 'nonneg'\n            if default\n                nonneg=true;\n            else\n                nonneg=val;\n            end\n        %  GPU Ids\n        %  =========================================================================\n        case 'gpuids'\n            if default\n                gpuids = GpuIds();\n            else\n                gpuids = val;\n            end\n        case 'redundancy_weighting'\n            if default\n                redundancy_weights = true;\n            else\n                redundancy_weights = val;\n            end\n        otherwise\n            error('TIGRE:PCSD:InvalidInput',['Invalid input name:', num2str(opt),'\\n No such option in PCSD()']);\n            \n    end\nend\n\nend\n", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Algorithms/PCSD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.567815674259939}}
{"text": "function s = imMin(img, varargin)\n%IMMIN Minimum value of a grayscale image, or of each color component\n%\n%   S = imMin(IMG)\n%   Computes the minimum value of pixels in image IMG. If image is grayscale\n%   image, the result is a scalar. If image is a color image, the result is\n%   1-by-3 row vector, each componenent corresponding to one color of the\n%   image.\n%\n%   S = imMin(IMG, MASK)\n%   Computes the minimum value only in the area specified by MASK.\n%\n%   S = imMin(..., 'color', COL)\n%   Forces the function to consider the image as color (if COL is TRUE) or\n%   as grascale (if COL is FALSE). This can be useful for vector image with\n%   more than 3 color components. \n%\n%\n%   Example\n%   % apply to cameraman image\n%   img = imread('cameraman.tif');\n%   imMin(img)\n%   ans =\n%       253\n%\n%   % apply to a RGB image\n%   img = imread('peppers.png');\n%   imMin(img)\n%   ans =\n%       255   255   255\n%\n%   See also\n%   imMax, imMedian, imMean\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-07-30,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n\n%% Process input arguments\n\n% detect if image is color\ncolor = isColorImage(img);\n\n% check if user specified 'color' option\nif length(varargin)>1\n    var = varargin{end-1};\n    if ischar(var)\n        if strcmpi(var, 'color')\n            color = varargin{end};\n            varargin(end-1:end) = [];\n        end\n    end\nend\n\n\n%% Process color image\n\nif color\n    % If image is color, process each band separately\n\n    % compute image size and dimension (including color dimension)\n    dim = size(img);\n    nd = length(dim);\n    \n    % create idnexing structure\n    inds = cell(1, nd);\n    for i=1:nd\n        inds{i} = 1:dim(i);\n    end\n    \n    % iterate on colors\n    nc = dim(3);\n    s = zeros(1, nc);\n    for i=1:nc\n        % modify the indexing structure to work on the i-th component\n        inds{3} = i;\n        s(i) = imMin(img(inds{:}), varargin{:});\n    end\n    \n    return;\nend\n\n\n%% process grayscale image\n\nif isempty(varargin)\n    % compute min over all image\n    s = min(img(:));\nelse\n    % use first argument as mask\n    s = min(img(varargin{1}));\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/imMin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5678156724994367}}
{"text": "function\tW = get_estimated_weight2(Model,parm,wmode);\n% Return Full Weight matrix from 'Model'\n%  W = get_estimated_weight2(Model,parm);\n%  W = get_estimated_weight2(Model,parm,wmode);\n% --- input\n% Model.W : Weight matrix for active input [Ydim x Nactive]\n% Model.ix_act : active input index\n% parm.Dtau\n% parm.M_all\n% parm.xnorm\n% parm.ynorm\n%  In the default mode, normalization constants, xnorm and ynorm\n%  are scaled back into the weight matrix 'W' : weight for original input\n%  If wmode is given and wmode = 0, \n%  no scale normalization is done: weight for normalized input\n%  \n% --- output\n% W : Weight matrix : 3D-array [Ydim x Xdim x Dtau)]\n% W(n,m,:) : temporal weight for n-th output & m-th input data\n% Dtau : time embedding dim\n% Ydim : Output space dim\n% Xdim : Input space dim\n%\n% 2008-5-20 Masa-aki Sato\n\nif isfield(parm,'Dtau')\n\tDtau  = parm.Dtau;\nelse\n\tDtau  = 1;\nend\n\nM_all = Model.M_all;\nYdim  = size(Model.W,1);\nXdim  = M_all/Dtau;\n\nif isfield(Model,'ix_act')\n\t% Active index\n\tix_act = Model.ix_act;\n\n\tW = zeros(Ydim ,M_all);\n\tW(:,ix_act) = Model.W;\nelse\n\tW =  Model.W;\nend\n\nif ~exist('wmode','var') || wmode~=0,\n\tif length(parm.xmean) == Xdim,\n\t\tparm.xmean = repmat(parm.xmean ,[Dtau 1]);\n\t\tparm.xnorm = repmat(parm.xnorm ,[Dtau 1]);\n\tend\n\t\n\t% Scale back by normalization factor\n\tif isfield(parm,'xnorm') & isfield(parm,'ynorm')\n\t\tW = (parm.ynorm(:)*(1./parm.xnorm(:)')) .* W;\n\tend\nend\n\nW = reshape( W, [Ydim, Xdim, Dtau]);\n", "meta": {"author": "KamitaniLab", "repo": "GenericObjectDecoding", "sha": "c98f24370668109fd9978bc8b43a33bd43926f47", "save_path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding", "path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding/GenericObjectDecoding-c98f24370668109fd9978bc8b43a33bd43926f47/code/matlab/lib/SPR_2009_12_17/get_estimated_weight2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5677763438082104}}
{"text": "function [cst,cstJac] = autoGen_cst_footVel(q1p,q2p,q4p,q5p,q1m,q2m,q4m,q5m,dq1p,dq2p,dq4p,dq5p,dq1m,dq2m,dq4m,dq5m,l1,l2,l4,l5)\n%AUTOGEN_CST_FOOTVEL\n%    [CST,CSTJAC] = AUTOGEN_CST_FOOTVEL(Q1P,Q2P,Q4P,Q5P,Q1M,Q2M,Q4M,Q5M,DQ1P,DQ2P,DQ4P,DQ5P,DQ1M,DQ2M,DQ4M,DQ5M,L1,L2,L4,L5)\n\n%    This function was generated by the Symbolic Math Toolbox version 6.2.\n%    22-Oct-2015 19:14:34\n\nt2 = sin(q1p);\nt3 = sin(q2p);\nt4 = sin(q4p);\nt5 = sin(q5p);\nt6 = sin(q1m);\nt7 = sin(q2m);\nt8 = sin(q4m);\nt9 = sin(q5m);\ncst = [dq1p.*l1.*t2+dq2p.*l2.*t3-dq4p.*l4.*t4-dq5p.*l5.*t5;-dq1m.*l1.*t6-dq2m.*l2.*t7+dq4m.*l4.*t8+dq5m.*l5.*t9];\nif nargout > 1\n    cstJac = reshape([0.0,0.0,dq1p.*l1.*cos(q1p),0.0,dq2p.*l2.*cos(q2p),0.0,0.0,0.0,-dq4p.*l4.*cos(q4p),0.0,-dq5p.*l5.*cos(q5p),0.0,l1.*t2,0.0,l2.*t3,0.0,0.0,0.0,-l4.*t4,0.0,-l5.*t5,0.0,0.0,0.0,0.0,-dq1m.*l1.*cos(q1m),0.0,-dq2m.*l2.*cos(q2m),0.0,0.0,0.0,dq4m.*l4.*cos(q4m),0.0,dq5m.*l5.*cos(q5m),0.0,-l1.*t6,0.0,-l2.*t7,0.0,0.0,0.0,l4.*t8,0.0,l5.*t9],[2, 22]);\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_cst_footVel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.567776341401497}}
{"text": "function sol = gsp_regression_tik(G ,M, y , tau, param )\n%GSP_REGRESSION_TIK Regression using graph and Tikhonov\n%   Usage: sol = gsp_regression_tik(G ,M, y , tau );\n%          sol = gsp_regression_tik(G ,M, y , tau, param );\n%\n%   Input parameters:\n%       G   : Graph\n%       M   : Mask (to determine with label is known)\n%       y   : label (total size of the problem)\n%       tau : regularization parameter (weight for tv)\n%       param : optional structure of parameters\n%\n%   Output parameters:\n%       sol : Solution of the problem\n%\n%   This function solve the following problem\n%\n%   .. argmin_x  || M x - y ||_2^2 + tau || nabla_G x ||_2^2\n%\n%   If tau is set to zero, then the following problem is solved\n%\n%   ..  argmin_x   || nabla_G x ||_2^2    s. t.  M x - y = 0\n%\n%   For the las problem, this function can compute an exact solution if\n%   *param.exact* is activated. It will be efficient if the number of\n%   unlabelled points is low.\n%\n%   Additional parameters\n%   ---------------------\n%\n%   * *param.verbose* : Verbosity of the iterative algorithm\n%   * *param.maxit* : maximum number of iteration for PCG\n%\n%   This function uses the UNLocBoX. \n%\n%   See also: gsp_classification_tik gsp_regression_tv\n%\n\n% Author: Nathanael Perraudin\n% Date  : 24 July 2015\n% Testing: test_graph_ml\n\n\n\n%% Optional parameters\n\nif nargin<5\n    param = struct;\nend\n\nif nargin<4\n    tau = 0;\nend\n\n\n\nif ~isfield(param,'verbose'), param.verbose = 1; end\nif ~isfield(param,'tol'), param.tol = 1e-6; end\nif ~isfield(param,'maxit'), param.maxit = 200; end\n% if ~isfield(param,'direct'), param.direct = (tau==0); end\n% if ~isfield(param,'exact'), param.exact = (numel(M)-nnz(M))<1000; end\n\nif tau==0\n    if param.verbose\n        fprintf('Using direct solution \\n')\n    end\n    if (numel(M) == size(M,1)) || (numel(M) == size(M,2))\n        indl = find(M);\n        indu = find(1-M);        \n    else   \n        error('I cannot handle this case yet');\n    end\n    Luu = (G.L(indu,indu));\n    Wul = - G.L(indu,indl);\n    tmp = (Wul * y(indl,:));\n%     if ~param.exact\n%         if ~isfield(param,'order'), param.order = 30; end\n%         Gtemp.L = Luu;\n%         Gtemp.N = size(Luu,1);\n% %        Gtemp = gsp_estimate_lmax(Gtemp);\n% %         cheb_coeffs = gsp_cheby_coeff(Gtemp, @(x) pinv_n(x,1e-8),...\n% %         param.order, param.order +1);\n% %         solt = gsp_cheby_op(Gtemp, cheb_coeffs, tmp);\n%         paramt.method = 'lanczos';\n%         paramt.order = param.order;\n%         solt = gsp_filter_analysis(Gtemp, @(x) pinv_n(x,1e-8),tmp,paramt);\n% \n%     else\n%        solt = pinv(full(Luu)) * tmp;\n         solt = Luu \\ tmp;\n%     end\n    sol = y;\n    sol(indu,:) = solt;\n    return\nelse\n\n\n    %% prepare the graph\n    if ~isfield(G,'lmax')\n        G = gsp_estimate_lmax(G);\n    end\n\n    %% set the \n    % setting the function f2 (see unlocbox for help)\n\n    Mop =@(x) bsxfun(@times,M,x);\n\n%     fg.grad = @(x) 2*Mop(Mop(x)-y);\n%     fg.eval = @(x) norm(Mop(x)-y)^2;\n%     fg.beta = 2;\n% %     paramtik.verbose = param.verbose -1;\n% %     ftik.prox = @(x,T) gsp_prox_tik(x,tau * T,G,paramtik);\n%     ftik.eval = @(x) tau* sum(gsp_norm_tik(G,x));\n%     ftik.grad = @(x) 2 * G.L * x;\n%     ftik.beta = 2 * G.lmax;\n    \n% \n% \n% else\n% %     param_b2.verbose = param.verbose -1;\n% %     param_b2.y = y;\n% %     param_b2.A = @(x) M.*x;\n% %     param_b2.At = @(x) M.*x;\n% %     param_b2.tight = param.tight;\n% %     param_b2.epsilon = 0;\n% %     fproj.prox = @(x,T) proj_b2(x,T,param_b2);\n% %     fproj.eval = @(x) eps;\n% \n%     fproj.prox = @(x,T) x - Mop(x) + Mop(y);\n%     fproj.eval = @(x) eps;\n%     ftik.eval = @(x) sum(gsp_norm_tik(G,x));   \n%     Ltmp = G.L + G.L';\n%     ftik.grad = @(x) Ltmp*x;\n%     ftik.beta = 2*G.lmax;\n% end\n\n% %% solve the problem\n% \n% % setting different parameter for the simulation\n% paramsolver = param;\n% \n% if tau > 0\n%     sol = forward_backward(y,ftik,fg,paramsolver);\n% else\n%     sol = forward_backward(y,fproj,ftik,paramsolver);\n% end\n\n% sol = sol(logical(1-M));\n% \n% sol = reshape(sol,[],size(M,2));\n\n    A = @(z)  vec ( Mop(reshape(z,[],size(y,2))) ...\n        +  tau * G.L * reshape(z,[],size(y,2)));\n    b =  vec(Mop(y));        \n    sol = pcg(A,b,param.tol,param.maxit,[],[],b);\n    sol = reshape(sol,[],size(y,2));\nend\n\nend\n\n\n% function r =  pinv_n(x,t)\n% \n% r = double(abs(x)>t) .* 1./x;\n% \n% end\n\n\n%   * *param.direct* : Direct computation of the exact solution (only for\n%     $\\tau = 0$). (Default tau==0)\n%   * *param.exact* : Exact computation of the exact solution (only for\n%     $\\tau = 0$ and param.direct = 0). (Default: (numel(M)-nnz(M))<1000 )", "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/graph_ml/gsp_regression_tik.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5677763365880703}}
{"text": "function[lstms,all_h_t,all_c_t]=Forward(batch,parameter,isTraining)%Forward\n    N=size(batch.Word,1);\n    zeroState=zeroMatrix([parameter.hidden,N]);\n    if isTraining==1\n        T=batch.MaxLen;\n    else\n        T=batch.MaxLenSource;\n    end\n    all_h_t=cell(parameter.layer_num,T);\n    all_c_t=cell(parameter.layer_num,T);\n    lstms = cell(parameter.layer_num,T);\n\n    for ll=1:parameter.layer_num\n        for tt=1:T\n            all_h_t{ll,tt}=zeroMatrix([parameter.hidden,N]);\n            all_c_t{ll,tt}=zeroMatrix([parameter.hidden,N]);\n        end\n    end\n    for t=1:T\n        for ll=1:parameter.layer_num\n            if t<batch.MaxLenSource+1;\n                W=parameter.W_S{ll};\n            else\n                W=parameter.W_T{ll};\n            end\n            if t==1\n                h_t_1=zeroState;\n                c_t_1 =zeroState;\n            else\n                c_t_1 = all_c_t{ll, t-1};\n                h_t_1 = all_h_t{ll, t-1};\n            end\n            if ll==1\n                x_t=parameter.vect(:,batch.Word(:,t));\n            else\n                x_t=all_h_t{ll-1,t};\n            end\n            x_t(:,batch.Delete{t})=0;\n            h_t_1(:,batch.Delete{t})=0;\n            c_t_1(:,batch.Delete{t})=0;\n            [lstms{ll, t},all_h_t{ll, t},all_c_t{ll, t}]=lstmUnit(W,parameter,x_t,h_t_1,c_t_1,ll,t,isTraining);%LSTM unit calculation\n        end\n    end\nend\n\n\n", "meta": {"author": "jiweil", "repo": "Hierarchical-Neural-Autoencoder", "sha": "2cea5c0b687e6d3dfb20dee4bec97aec6b57a95f", "save_path": "github-repos/MATLAB/jiweil-Hierarchical-Neural-Autoencoder", "path": "github-repos/MATLAB/jiweil-Hierarchical-Neural-Autoencoder/Hierarchical-Neural-Autoencoder-2cea5c0b687e6d3dfb20dee4bec97aec6b57a95f/Standard_LSTM/Forward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5677763308674492}}
{"text": "%% FUNCTION Least_TGL\n% L21 Joint Feature Learning with Least Squares Loss.\n%\n%% OBJECTIVE\n% argmin_W { sum_i^t (0.5 * norm (Y{i} - X{i}' * W(:, i))^2)\n%            + opts.rho_L2 * \\|W\\|_2^2 + rho1 * \\|W\\|_{2,1} }\n%\n%% INPUT\n% X: {n * d} * t - input matrix\n% Y: {n * 1} * t - output matrix\n% rho1: L2,1-norm group Lasso parameter.\n% optional:\n%   opts.rho_L2: L2-norm parameter (default = 0).\n%\n%% OUTPUT\n% W: model: d * t\n% funcVal: function value vector.\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 <http://www.gnu.org/licenses/>.\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 June 3, 2012.\n%\n%% RELATED PAPERS\n%\n%   [1] Evgeniou, A. and Pontil, M. Multi-task feature learning, NIPS 2007.\n%   [2] Liu, J. and Ye, J. Efficient L1/Lq Norm Regularization, Technical\n%       Report, 2010.\n%\n%% RELATED FUNCTIONS\n%  Least_L21, init_opts\n\n%% Code starts here\nfunction [W, funcVal] = Least_L21(X, Y, rho1, opts)\n\nif nargin <3\n    error('\\n Inputs: X, Y, rho1, should be specified!\\n');\nend\nX = multi_transpose(X);\n\nif nargin <4\n    opts = [];\nend\n\n% initialize options.\nopts=init_opts(opts);\n\nif isfield(opts, 'rho_L2')\n    rho_L2 = opts.rho_L2;\nelse\n    rho_L2 = 0;\nend\n\ntask_num  = length (X);\ndimension = size(X{1}, 1);\nfuncVal = [];\n\n% initialize a starting point\nif isfield(opts,'W0')\n    W0=opts.W0;\n    if (nnz(size(W0)-[dimension, task_num]))\n        error('\\n Check the input .W0');\n    end\nelseif opts.init==2\n    W0 = zeros(dimension, task_num);\nelseif opts.init == 0\n    XY = cell(task_num, 1);\n    W0_prep = [];\n    for t_idx = 1: task_num\n        XY{t_idx} = X{t_idx}*Y{t_idx};\n        W0_prep = cat(2, W0_prep, XY{t_idx});\n    end\n    W0 = W0_prep;\nend\n\nbFlag=0; % this flag tests whether the gradient step only changes a little\n\n\nWz= W0;\nWz_old = W0;\n\nt = 1;\nt_old = 0;\n\niter = 0;\ngamma = 1;\ngamma_inc = 2;\n\nwhile iter < opts.maxIter\n    alpha = (t_old - 1) /t;\n    \n    Ws = (1 + alpha) * Wz - alpha * Wz_old;\n    \n    % compute function value and gradients of the search point\n    gWs  = gradVal_eval(Ws);\n    Fs   = funVal_eval (Ws);\n    \n    while true\n        Wzp = FGLasso_projection(Ws - gWs/gamma, rho1 / gamma);\n        Fzp = funVal_eval  (Wzp);\n        \n        delta_Wzp = Wzp - Ws;\n        r_sum = norm(delta_Wzp, 'fro')^2;\n        %         Fzp_gamma = Fs + trace(delta_Wzp' * gWs)...\n        %             + gamma/2 * norm(delta_Wzp, 'fro')^2;\n        Fzp_gamma = Fs + sum(sum(delta_Wzp.* gWs))...\n            + gamma/2 * norm(delta_Wzp, 'fro')^2;\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        if (Fzp <= Fzp_gamma)\n            break;\n        else\n            gamma = gamma * gamma_inc;\n        end\n    end\n    \n    Wz_old = Wz;\n    Wz = Wzp;\n    \n    funcVal = cat(1, funcVal, Fzp + nonsmooth_eval(Wz, rho1));\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    % test stop condition.\n    switch(opts.tFlag)\n        case 0\n            if iter>=2\n                if (abs( funcVal(end) - funcVal(end-1) ) <= opts.tol)\n                    break;\n                end\n            end\n        case 1\n            if iter>=2\n                if (abs( funcVal(end) - funcVal(end-1) ) <=...\n                        opts.tol* funcVal(end-1))\n                    break;\n                end\n            end\n        case 2\n            if ( funcVal(end)<= opts.tol)\n                break;\n            end\n        case 3\n            if iter>=opts.maxIter\n                break;\n            end\n    end\n    \n    iter = iter + 1;\n    t_old = t;\n    t = 0.5 * (1 + (1+ 4 * t^2)^0.5);\n    \nend\n\nW = Wzp;\n\n% private functions\n\n    function [X] = FGLasso_projection (D, lambda )\n        % l2.1 norm projection.\n        X = repmat(max(0, 1 - lambda./sqrt(sum(D.^2,2))),1,size(D,2)).*D;\n    end\n\n% smooth part gradient.\n    function [grad_W] = gradVal_eval(W)\n        if opts.pFlag\n            grad_W = zeros(zeros(W));\n            parfor i = 1:task_num\n                grad_W (i, :) = X{i}*(X{i}' * W(:,i)-Y{i});\n            end\n        else\n            grad_W = [];\n            for i = 1:task_num\n                grad_W = cat(2, grad_W, X{i}*(X{i}' * W(:,i)-Y{i}) );\n            end\n        end\n        grad_W = grad_W+ rho_L2 * 2 * W;\n    end\n\n% smooth part function value.\n    function [funcVal] = funVal_eval (W)\n        funcVal = 0;\n        if opts.pFlag\n            parfor i = 1: task_num\n                funcVal = funcVal + 0.5 * norm (Y{i} - X{i}' * W(:, i))^2;\n            end\n        else\n            for i = 1: task_num\n                funcVal = funcVal + 0.5 * norm (Y{i} - X{i}' * W(:, i))^2;\n            end\n        end\n        funcVal = funcVal + rho_L2 * norm(W,'fro')^2;\n    end\n\n    function [non_smooth_value] = nonsmooth_eval(W, rho_1)\n        non_smooth_value = 0;\n        if opts.pFlag\n            parfor i = 1 : size(W, 1)\n                w = W(i, :);\n                non_smooth_value = non_smooth_value ...\n                    + rho_1 * norm(w, 2);\n            end\n        else\n            for i = 1 : size(W, 1)\n                w = W(i, :);\n                non_smooth_value = non_smooth_value ...\n                    + rho_1 * norm(w, 2);\n            end\n        end\n    end\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/joint_feature_learning/Least_L21.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5677763299602551}}
{"text": "function [ uvcoord ] = uv2coords( uv, width, height, planeID )\n%UV2COORDS Summary of this function goes here\n%   Detailed explanation goes here\nif ~exist('planeID','var')\n    planeID = 1;\nend\nif planeID~=1\n    uv = xyz2uvN(uv2xyzN(uv, planeID), 1);\nend\n\nuvcoord = zeros(size(uv,1),2);\nuvcoord(:,1) = min(round((uv(:,1)+pi)/2/pi*width+0.5), width);\nuvcoord(:,2) = min(round((pi/2-uv(:,2))/pi*height+0.5), height);\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/BasicFuncPano/uv2coords.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5677763260540222}}
{"text": "f=[-2; -3; 5];\na=[-2,5,-1;1,3,1]; b=[-10;12];\naeq=[1,1,1];\nbeq=7;\n[x,y]=linprog(f,a,b,aeq,beq,zeros(3,1));\nx, y=-y\n", "meta": {"author": "Eurus-Holmes", "repo": "Mathematical_Modeling", "sha": "cb9dd53af84ffbd455ec62ab89886351e0ec98d9", "save_path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling", "path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling/Mathematical_Modeling-cb9dd53af84ffbd455ec62ab89886351e0ec98d9/Mathematical_Modeling_Algorithms_and_Applications_Second_Edition_Procedures_and_Data/01\u7b2c1\u7ae0/ex1_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5677501840356685}}
{"text": "addpath tensorIO_matlab\n\nclear\n\nclf\n\ntensors = readTensors('outTSDF.tensor');\n\n    \ntsdf = tensors(1).value;\n\n\n%% visualization\n%{\n\nfor i=1:size(tsdf,3)\n    imagesc((tsdf(end:-1:1,end:-1:1,i))',[0 1]); axis equal; axis tight; colorbar\n    title(i);\n    pause(0.1);\nend\n\n%return;\n\nfor i=1:size(tsdf,2)\n    imagesc((reshape(tsdf(:,i,:), [size(tsdf,1) size(tsdf,3)])),[0 1]); axis equal; axis tight; colorbar\n    pause(0.1);\n    title(i);\nend\n\n\nfor i=1:size(tsdf,1)\n    imagesc((reshape(tsdf(i,end:-1:1,:), [size(tsdf,2) size(tsdf,3)])),[0 1]); axis equal; axis tight; colorbar\n    title(i);\n    pause(0.1);\nend\n%}\n\n\n%% meshing\ndisp('isosurfacing...');\ntic;\nfv = isosurface(tsdf,0);\ntoc;\n% visualizaiton\n%{\nfigure(3);\np = patch(fv);\np.FaceColor = 'red';\np.EdgeColor = 'none';\ndaspect([1,1,1])\nview(3); axis tight\ncamlight \nlighting gouraud\n%}\n\nunit = 0.0005;\n\nfv.vertices = fv.vertices * unit;\n\nfv.vertices(:,1) = fv.vertices(:,1) - mean(fv.vertices(:,1));\nfv.vertices(:,2) = fv.vertices(:,2) - mean(fv.vertices(:,2));\nfv.vertices(:,3) = fv.vertices(:,3) - mean(fv.vertices(:,3));\n\nmesh2off('isosurface.off', fv.faces,fv.vertices);\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/pose2mesh/GPUFusion/getMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5677059479336514}}
{"text": "function pl = plot(sT,varargin)\n\n% find all edges given by vertex i and vertex j\n[i,j] = find(sT.A_V);\n\n% we have each edge twice -> take only that one with vi > vj\nind = i>j; i = i(ind); j = j(ind);\n\n% interpolate between the vertices\n% and add a nan at the end\nN = 20; % number of interpolation points\n\n% the interpolation matrix\ninterpM = [linspace(0,1,N).',linspace(1,0,N).';nan,nan];\n\n% interpolate the vertices\nV = sT.vertices(:);\npl = interpM * [V(i),V(j)].';\n\n%\nline(pl)\n\nif check_option(varargin,'labeled') && size(sT.T,1)<500\n  id = 1:size(sT.T,1);\n  hold on\n  text(sT.midPoints,cellfun(@int2str,vec2cell(id),'UniformOutput',false));\n  hold off\nend\n\nif check_option(varargin,'labelV') && size(sT.T,1)<500\n  id = 1:length(sT.vertices);\n  hold on\n  text(sT.vertices,cellfun(@int2str,vec2cell(id),'UniformOutput',false),'color','red');\n  hold off\nend\n\n\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@S2Triangulation/plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720203, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5677059264202077}}
{"text": "function line_cvt_lloyd_test04 ( )\n\n%*****************************************************************************80\n%\n%% LINE_CVT_LLOYD_TEST04 tests the constrained computation.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    28 July 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'LINE_CVT_LLOYD_TEST04:\\n' );\n  fprintf ( 1, '  Test the constrained computation.\\n' );\n  fprintf ( 1, '  SORT the initial points before use.\\n' );\n\n  n = 25;\n  a = 0.0;\n  b = 1.0;\n  it_num = 200;\n  x = a + ( b - a ) * rand ( n, 1 );\n  x = sort ( x );\n  header = 'test04';\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Use %d points in the interval [%g,%g]\\n', n, a, b );\n  fprintf ( 1, '  Take %d iterations.\\n', it_num );\n  fprintf ( 1, '  Call this calculation \"%s\"\\n', header );\n  fprintf ( 1, '  Expect a uniform spacing of %g\\n', ( b - a ) / n );\n\n  x = line_ccvt_lloyd ( n, a, b, it_num, header, 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/line_cvt_lloyd/line_cvt_lloyd_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5677055663907483}}
{"text": "function tests = test_dictionary_comparison\n  tests = functiontests(localfunctions);\nend\n\n\nfunction test_1(testCase)\n    d = spx.dict.simple.dirac_fourier_mtx(16);\n    ratio = spx.dict.comparison.matching_atoms_ratio(d, d);\n    verifyEqual(testCase, ratio, 1);\n    % Let's mess up with one of the atoms\n    d2 = d;\n    d2(1:4, 1) = 1/2;\n    ratio = spx.dict.comparison.matching_atoms_ratio(d, d2);\n    verifyEqual(testCase, ratio, 31/32);\n    d2(2:5, 2) = 1/2;\n    ratio = spx.dict.comparison.matching_atoms_ratio(d, d2);\n    verifyEqual(testCase, ratio, 30/32);\nend\n\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/library/tests/dict/test_dictionary_comparison.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5677055622441687}}
{"text": "function [costunit, selectedf] = choosefactory(factorycap,factholdcost,transcost,setupcost,factory,trkcap,salespoint,selectedsp);\n                                        \n    costPerUnitValues = inf(1,length(factorycap));\n    \n    \n\n    for i = 1:length(factorycap)\n        if (factory{i}(1,2)>=salespoint{selectedsp}(1,2))\n            costPerUnitValues(1,i) = transcost(i,selectedsp) / trkcap + ( ( factorycap(i) - salespoint{selectedsp}(1,2) ) / factorycap(i) ) * factholdcost(i);\n        elseif(factory{i}(1,1)==0 && (factorycap(i)+factory{i}(1,2))>=salespoint{selectedsp}(1,2))\n            costPerUnitValues(1,i) = (setupcost(i) * (1 - factory{i}(1,1))) / salespoint{selectedsp}(1,2) + transcost(i,selectedsp) / trkcap + ( ( factorycap(i) - salespoint{selectedsp}(1,2) ) / factorycap(i) ) * factholdcost(i);\n        end\n            \n    end;\n    \n    [costunit,selectedf] = min(costPerUnitValues);\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/27882-applying-greedy-algorithm-and-local-search-in-a-supply-chain-distribution-problem/Greedy_SC/choosefactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5676948115570564}}
{"text": "function [node,elem] = interfaceUniformrefine(node,elem,interfaceEdge,phi)\n\n\n%% Construct data structure\ntotalEdge = uint32(sort([elem(:,[2,3]); elem(:,[3,1]); elem(:,[1,2])],2));\n[edge, ~, j] = unique(totalEdge,'rows');\nN = size(node,1); NT = size(elem,1); NE = size(edge,1);\nelem2edge = uint32(reshape(j,NT,3));\n\nisInterfaceNode = false(N,1);\nisInterfaceNode(interfaceEdge(:)) = true;\n\n%% Add new nodes: middle points of all edges\ntmpNode = (node(edge(:,1),:)+node(edge(:,2),:))/2; \nisNewInterfaceNode = isInterfaceNode(edge(:,1)) & isInterfaceNode(edge(:,2));\na = node(edge(isNewInterfaceNode,1),:) - tmpNode(isNewInterfaceNode,:);\nb = node(edge(isNewInterfaceNode,2),:) - tmpNode(isNewInterfaceNode,:);\na = tmpNode(isNewInterfaceNode,:) + [-a(:,2), a(:,1)];\nb = tmpNode(isNewInterfaceNode,:) + [-b(:,2), b(:,1)];\ntmpNode(isNewInterfaceNode,:) = findintersectbisect(phi,a,b);\nnode(N+1:N+NE,:) = tmpNode;\n\nedge2newNode = uint32((N+1:N+NE)');\n\n%% Refine each triangle into four triangles as follows\n%     3\n%    / \\\n%   5 - 4\n%  / \\ / \\\n% 1 - 6 - 2\nt = 1:NT;\np(t,1:3) = elem(t,1:3);\np(t,4:6) = edge2newNode(elem2edge(t,1:3));\nelem(t,:) = [p(t,1), p(t,6), p(t,5)];\nelem(NT+1:2*NT,:) = [p(t,6), p(t,2), p(t,4)];\nelem(2*NT+1:3*NT,:) = [p(t,5), p(t,4), p(t,3)];\nelem(3*NT+1:4*NT,:) = [p(t,4), p(t,5), p(t,6)];\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/interfacemesh/interfaceUniformrefine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5676915159819117}}
{"text": "function p = subsasgn(p,s,r)\n%SUBSASGN     Implements subscripted assignment for polynomials\n%\n%  p(i) = r\n%\n%For univariate polynomials p, p(i) is the coefficient of x^i, 0<=i<=degree(p).\n%  For i>degree(p), p(i):=0. Similarly, p(i:j) is the vector of coefficients\n%  [ p(i) p(i+1) ... p(j) ], or, p(:) is the (row) vector of all coefficients\n%  of p, the same as vector(p) for univariate polynomials. Especially, \n%  p(i) = [] of p(i:j) = [] cancels the i-th or i..j-th coefficient, respectively.\n%\n%For multivariate polynomials p in k variables x_1..x_k, p(i) is the\n%  coefficient of x_1^i, i.e. a polynomial in k-1 variables.\n%  Similarly, p(i,[],j) or p(i,:,j) is the coefficient polynomial of\n%  x1^i*x3^j. Indices i,j,... must be single indices, no range.\n%Note that access to coefficients refers to the current order p.v of\n%  variables of p. To change this order, see permvars.\n%For example, for a polynomial in three variables p.v={'x','y','z'},\n%  p(1,0,3) is the coefficient of x*z^3 (a constant), where p(1,[],3)\n%  if the coefficient of x*z^3, a univariate polynomial in y.\n%\n%Polynomial evaluation is denoted by p{x}, computing the value of p at x.\n%  This is the same as polyval(p,x).\n%For univariate polynomials, x may be a vector or matrix yielding the vector\n%  or matrix of polynomial values evaluated at the corresponding coefficients.\n%For multivariate polynomials, x is a vector of values of the variables.\n%  For x being a matrix, the result is the (column) vector of p{x(i,:)}.\n%\n%Moreover, p.mid, p.rad, p.inf, p.sup give access to the midpoint, radius,\n%  infimum and supremum of p, respectively.\n%\n%Finally, p.e, p.c and p.v give access to the arrays of exponents, coefficients\n%  and variables of p, such that polynom(p.e,p.c,p.v) is again p. Single variables\n%  are accessed by p.v{i}.\n%\n%In the univariate case,  p == polynom(p.c,p.v)  [ degree is length(p.c)+1 ].\n%In the multivariate case,  p == polynom(p.e,p.c,p.v)  [ p.e is (sparse) exponent set ].\n%\n\n% written  11/20/97     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 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  while 1\n    if ~isa(p,'polynom')\n      p = subsasgn(p,s(1),r);\n    elseif strcmp(s(1).type,'()')     % index reference p(i)\n      if size(p.e,2)==1               % univariate polynomial\n        if length(s(1).subs)>1\n          error('invalid call: more than one index')\n        end\n        if isequal(s(1).subs{1},':')\n          p.c(:) = typeadj(r,typeof(p.c));\n        else\n          n1 = length(p.c);\n          index = n1-s(1).subs{1};     % index vector, p(0) constant term, etc.\n          if ~isreal(index) | ~isequal(index,round(index))\n            error('index must be integer')\n          end\n          if any(index>n1)             % index negative\n            error('index out of range')\n          end\n          if ( length(r)>1 ) & ( length(index)~=length(r) )\n            error('length of arguments do not match, invalid assignment')\n          end          \n          if isa(r,'intval') & ~isa(p.c,'intval')\n            p.c = intval(p.c);\n          end\n          m = min(index);\n          if isempty(r)\n            r = 0;\n          end\n          if m<=0                      % index greater than degree\n            p.c = [zeros(1,-m+1) p.c];\n            p.c(index-m+1) = r;\n          else\n            p.c(index) = r;\n          end\n        end\n        m = min(find(p.c~=0));\n        if isempty(m)                  % zero polynomial\n          p.c = typeadj(0,typeof(p.c));\n        elseif m>1                     % leading coefficients zero\n          p.c = p.c(m:length(p.c));    % Matlab bug: ..end does not work for user-defined data types\n        end\n        p.e = length(p.c)-1;\n      else                             % multivariate polynomial\n        k = size(p.e,2);               % number of variables\n        if length(s(1).subs)>k\n          error('too many indices')\n        end\n        exponents = zeros(1,k);\n        for i=1:length(s(1).subs)\n          if isempty(s(1).subs{i}) | isequal(s(1).subs{i},':')\n            error('Only integer indices allowed in multivariate polynomial assignment')\n          end\n          exponents(i) = s(1).subs{i};\n        end \n        I = all( ( p.e == repmat(exponents,size(p.e,1),1) ) , 2 );\n        if any(I)                     % coefficient does occur\n          if r==0\n            p.e(I,:) = [];\n            p.c(I) = [];\n          else\n            p.c(I) = r;\n          end      \n        else                          % coefficient does not occur\n          if r~=0\n            p.e = [p.e ; exponents];\n            if isa(r,'intval')\n              p.c = intval(p.c);\n            end\n            p.c = [p.c ; r];\n          end\n        end\n        p = normalize(p);\n      end\n    elseif strcmp(s(1).type,'.')      % polynomial access to .v\n      if strcmp(s(1).subs,'v')\n        if ischar(p.v)                % univariate p\n          if ~ischar(r)\n            error('variable of univariate polynomial must be string')\n          else\n            p.v = r;\n          end\n        else                          % multivariate p\n          if ( length(s)==2 ) & ( s(2).type=='{}' )\n            if s(2).subs{1}>length(p.v)\n              error('index of variable too large')\n            end\n            if ~ischar(r)\n              error('variable name must be string')\n            end\n            I = find(strcmp(p.v,r));\n            if ~isempty(I) & ( I~=s(2).subs{1} )\n              error('duplicate variable name not allowed')\n            end\n            p.v{s(2).subs{1}} = r;  \n            if rndold\n              setround(rndold)\n            end\n            return\n          elseif ~iscell(r)\n            error('variables of multivariate polynomials must be cell array of strings')\n          else\n            if length(r)~=length(p.v)\n              error('number of variables does not match')\n            else\n              p.v = r;\n            end\n          end\n        end\n      else\n        error('invalid reference for polynomial')\n      end\n    else\n      error('invalid index reference for polynomial')\n    end\n    if length(s)==1  \n      if rndold\n        setround(rndold)\n      end\n      return\n    end\n    error('invalid call of polynom/subsasgn')\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/polynom/@polynom/subsasgn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.567654077936942}}
{"text": "function hh = quiver5(varargin)\n% Slightly modified version of quiver3 function that plot arrows with\n% true 3D arrow heads\n% Bertrand Dano 05-12-08\n%QUIVER5 3-D quiver plot.\n%   QUIVER5(X,Y,Z,U,V,W) plots velocity vectors as arrows with components\n%   (u,v,w) at the points (x,y,z).  The matrices X,Y,Z,U,V,W must all be\n%   the same size and contain the corresponding position and velocity\n%   components.  QUIVER3 automatically scales the arrows to fit.\n%\n%   QUIVER5(Z,U,V,W) plots velocity vectors at the equally spaced\n%   surface points specified by the matrix Z.\n%\n%   QUIVER5(Z,U,V,W,S) or QUIVER3(X,Y,Z,U,V,W,S) automatically\n%   scales the arrows to fit and then stretches them by S.\n%   Use S=0 to plot the arrows without the automatic scaling.\n%\n%   QUIVER5(...,LINESPEC) uses the plot linestyle specified for\n%   the velocity vectors.  Any marker in LINESPEC is drawn at the base\n%   instead of an arrow on the tip.  Use a marker of '.' to specify\n%   no marker at all.  See PLOT for other possibilities.\n%\n%   QUIVER5(...,'filled') fills any markers specified.\n%\n%   H = QUIVER3(...) returns a vector of line handles.\n%\n%   Example:\n%       [x,y] = meshgrid(-2:.2:2,-1:.15:1);\n%       z = x .* exp(-x.^2 - y.^2);\n%       [u,v,w] = surfnorm(x,y,z);\n%       quiver5(x,y,z,u,v,w); \n%       axis vis3d; rotate3d on\n%\n%   See also QUIVER, PLOT, PLOT3, SCATTER.\n%   Clay M. Thompson 3-3-94\n%   Copyright 1984-2002 The MathWorks, Inc. \n%   $Revision: 1.23 $  $Date: 2002/06/05 20:05:16 $\n% Arrow head parameters\nalpha = 0.33; % Size of arrow head relative to the length of the vector\nbeta = 0.33;  % Width of the base of the arrow head relative to the length\nautoscale = 1; % Autoscale if ~= 0 then scale by this.\nplotarrows = 1;\nfilled = 0;\nls = '-';\nms = '';\ncol = '';\nnin = nargin;\n% Parse the string inputs\nwhile isstr(varargin{nin}),\n  vv = varargin{nin};\n  if ~isempty(vv) & strcmp(lower(vv(1)),'f')\n    filled = 1;\n    nin = nin-1;\n  else\n    [l,c,m,msg] = colstyle(vv);\n    if ~isempty(msg), \n      error(sprintf('Unknown option \"%s\".',vv));\n    end\n    if ~isempty(l), ls = l; end\n    if ~isempty(c), col = c; end\n    if ~isempty(m), ms = m; plotarrows = 0; end\n    if isequal(m,'.'), ms = ''; end % Don't plot '.'\n    nin = nin-1;\n  end\nend\nerror(nargchk(4,7,nin));\n% Check numeric input arguments\nif nin<6, % quiver3(z,u,v,w) or quiver3(z,u,v,w,s)\n  [msg,x,y,z] = xyzchk(varargin{1});\n  u = varargin{2};\n  v = varargin{3};\n  w = varargin{4};\nelse % quiver3(x,y,z,u,v,w) or quiver3(x,y,z,u,v,w,s)\n  [msg,x,y,z] = xyzchk(varargin{1:3});\n  u = varargin{4};\n  v = varargin{5};\n  w = varargin{6};\nend\nif ~isempty(msg), error(msg); end\n% Scalar expand u,v,w.\nif prod(size(u))==1, u = u(ones(size(x))); end\nif prod(size(v))==1, v = v(ones(size(u))); end\nif prod(size(w))==1, w = w(ones(size(v))); end\n% Check sizes\nif ~isequal(size(x),size(y),size(z),size(u),size(v),size(w))\n  error('The sizes of X,Y,Z,U,V, and W must all be the same.');\nend\n% Get autoscale value if present\nif nin==5 | nin==7, % quiver3(z,u,v,w,s) or quiver3(x,y,z,u,v,w,s)\n  autoscale = varargin{nin};\nend\nif length(autoscale)>1,\n  error('S must be a scalar.');\nend\nif autoscale,\n  % Base autoscale value on average spacing in the x and y\n  % directions.  Estimate number of points in each direction as\n  % either the size of the input arrays or the effective square\n  % spacing if x and y are vectors.\n  if min(size(x))==1, n=sqrt(prod(size(x))); m=n; else [m,n]=size(x); end\n  delx = diff([min(x(:)) max(x(:))])/n; \n  dely = diff([min(y(:)) max(y(:))])/m;\n  delz = diff([min(z(:)) max(y(:))])/max(m,n);\n  del = sqrt(delx.^2 + dely.^2 + delz.^2);\n  if del>0\n    len = sqrt((u/del).^2 + (v/del).^2 + (w/del).^2);\n    maxlen = max(len(:));\n  else\n    maxlen = 0;\n  end\n  \n  if maxlen>0\n    autoscale = autoscale*0.9 / maxlen;\n  else\n    autoscale = autoscale*0.9;\n  end\n  u = u*autoscale; v = v*autoscale; w = w*autoscale;\nend\nax = newplot;\nnext = lower(get(ax,'NextPlot'));\nhold_state = ishold;\n% Make velocity vectors\nx = x(:).'; y = y(:).'; z = z(:).';\nu = u(:).'; v = v(:).'; w = w(:).';\nuu = [x;x+u;repmat(NaN,size(u))];\nvv = [y;y+v;repmat(NaN,size(u))];\nww = [z;z+w;repmat(NaN,size(u))];\nh1 = plot3(uu(:),vv(:),ww(:),[col ls]);\nif plotarrows,\n  beta = beta * sqrt(u.*u + v.*v + w.*w) ./ (sqrt(u.*u + v.*v) + eps);\n  uv=sqrt(u.*u + v.*v);\n  % Make arrow heads and plot them\n  hu = [x+u; x+u-alpha*(u+beta.*(v+eps)); ...\n             x+u-alpha*(u-beta.*(v+eps)); ...\n        x+u; x+u-alpha*u; x+u-alpha*u; x+u;...\n        repmat(NaN,size(u))];\n  hv = [y+v; y+v-alpha*(v-beta.*(u+eps)); ...\n             y+v-alpha*(v+beta.*(u+eps)); ... \n        y+v; y+v-alpha*v; y+v-alpha*v; y+v;...\n        repmat(NaN,size(v))];\n  hw = [z+w; z+w-alpha*w; z+w-alpha*w; ... \n        z+w; z+w-alpha*(w+beta.*(uv+eps)); ... \n             z+w-alpha*(w-beta.*(uv+eps)); z+w; ... \n        repmat(NaN,size(w))];\n  hold on\n  h2 = plot3(hu(:),hv(:),hw(:),[col ls]);\nelse\n  h2 = [];\nend\nif ~isempty(ms), % Plot marker on base\n  hu = x; hv = y; hw = z;\n  hold on\n  h3 = plot3(hu(:),hv(:),hw(:),[col ms]);\n  if filled, set(h3,'markerfacecolor',get(h1,'color')); end\nelse\n  h3 = [];\nend\nif ~hold_state, hold off, view(3); grid on, set(ax,'NextPlot',next); end\nif nargout>0, hh = [h1;h2;h3]; end", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/quiver5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.5676540736921477}}
{"text": "function [L1,L1_l,L1_x1] = reanchorPlucker(L0,x1)\n\n% REANCHORPLUCKER  Plucker to anchored Plucker line conversion\n%   REANCHORPLUCKER(L,X) reanchors the anchored Plucker line L to the point X.\n%\n%   [L1,L1_l,L1_x] = REANCHORPLUCKER(L,X) returns the Jacobians.\n\n%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n\nx0 = L0(1:3);\nn0 = L0(4:6);\nv0 = L0(7:9);\n\nL1 = [x1; n0 + cross((x0-x1),v0); v0];\n\nif nargout > 1\n\n    Z33 = zeros(3);\n    I33 = eye(3);\n\n    L1_l = [...\n        Z33      Z33    Z33\n        -hat(v0) I33 hat(x0-x1)\n        Z33      Z33    I33];\n    \n    L1_x1 = [...\n        I33\n        hat(v0)\n        Z33];\n    \nend\n\nreturn\n\n%%\nsyms t1 t2 t3 x1 x2 x3 a b c d n1 n2 n3 v1 v2 v3 y1 y2 y3 real\n\nL0 = [x1;x2;x3;n1;n2;n3;v1;v2;v3];\ny = [y1;y2;y3];\n\n[L1,L1_l,L1_y] = reanchorPlucker(L0,y);\n\nsimplify(L1_l - jacobian(L1,L0))\nsimplify(L1_y - jacobian(L1,y))\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 <http://www.gnu.org/licenses/>.\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/reanchorPlucker.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5676540693000505}}
{"text": "%% ODE_POOL uses the MATLABPOOL command to run the ODE code.\n%\n%  Discussion:\n%\n%    Output printed by the function appears directly on the screen.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    21 March 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n\n%\n%  Initialize the k and b ranges.\n%\n  bVals = 0.1 : 0.05 : 5;\n  kVals = 1.5 : 0.05 : 5;\n%\n%  Begin the parameter sweep.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'ODE_POOL\\n' );\n  fprintf ( 1, '  Sweep through sets of values of parameters B and K,\\n' );\n  fprintf ( 1, '  computing the solution of the ODE corresponding to each set.\\n' );\n  fprintf ( 1, '  For each solution X(T), determine the maximum value over time.\\n' );\n  fprintf ( 1, '  Construct a contour plot of XMAX(B,K).\\n' );\n  fprintf ( 1, '  Use the PARFOR command to carry out these computations in parallel.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of K values = %d\\n', length ( kVals ) );\n  fprintf ( 1, '  Number of B values = %d\\n', length ( bVals ) );\n  fprintf ( 1, '  Number of times the ODE must be solved = %d\\n', ...\n    length ( kVals ) * length ( bVals ) );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Begin computation\\n' );\n\n  matlabpool open local 4\n%\n%  Solve the ODE for every pair of K and B values and return the maximum\n%  value over the time interval.\n%\n  tic\n  peakVals = ode_fun ( bVals, kVals );\n  toc\n\n  matlabpool close\n%\n%  Now display am image of the data.\n%\n  ode_display ( bVals, kVals, peakVals );\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/ode_sweep_parfor/ode_pool.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.5676540654971638}}
{"text": " function [xs, info] = qpwls_pcg1(x, A, W, yi, C, varargin)\n%function [xs, info] = qpwls_pcg1(x, A, W, yi, C, [options])\n%|\n%| quadratic penalized weighted least squares (QPWLS) via\n%| preconditioned conjugate gradients (PCG) algorithm\n%| cost(x) = (y-Ax)'W(y-Ax) / 2 + x'C'Cx / 2\n%|\n%| in\n%|\tx\t[np 1]\t\tinitial estimate\n%|\tA\t[nd np]\t\tsystem matrix\n%|\tW\t[nd nd]\t\tdata weighting matrix, usually Gdiag(wi)\n%|\tyi\t[nd 1]\t\tnoisy data\n%|\tC\t[nc np]\t\tpenalty 'differencing matrix' (0 for unregularized)\n%|\n%| options\n%|\tniter\t\t\t# total iterations (default: 1)\n%|\t\t\t\t\t(max # if tol used)\n%|\tisave\t[]\t\tlist of iterations to archive (default: 'last')\n%|\tuserfun\t@\t\tuser defined function handle (see default below)\n%|\t\t\t\t\ttaking arguments (x, userarg{:})\n%|\tuserarg {}\t\tuser arguments to userfun (default {})\n%|\tprecon\t[np np]\t\tpreconditioner (matrix or object) (or 1)\n%|\tdircheck 0|1\t\tcheck descent direction? (default: 1)\n%|\t\t\t\tset to 0 to save time, if you dare...\n%|\tstop_diff_tol\t\tstop iterations if norm(xnew-xold)/norm(xnew)\n%|\t\t\t\tis less than this unitless value.  default: 0\n%|\tstop_diff_norm\t\tuse norm(.,type) for stop rule\n%|\t\t\t\tchoices: 1 | 2 (default) | inf\n%|\tstop_grad_tol\t\tstop if norm(grad) / y'W y < tol; default: 0\n%|\tstop_grad_norm\t\twhich norm(grad) to use.  default: 2\n%|\tchat\t0|1\t\tverbosity (default 0)\n%|\n%| out\n%|\txs\t[np niter]\testimates each iteration\n%|\tinfo\t[niter 3]\tgamma, step size, time each iteration\n%|\n%| Copyright Jan 1998, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(x, 'test'), qpwls_pcg1_test0, return, end\nif nargin < 5, ir_usage, end\n\n% defaults\narg.precon = 1;\narg.niter = 1;\narg.isave = [];\narg.userfun = @userfun_default;\narg.userarg = {};\narg.key = 1;\narg.dircheck = true; % default is to check descent direction\narg.stop_diff_tol = 0;\narg.stop_diff_norm = 2;\narg.stop_grad_tol = 0;\narg.stop_grad_norm = 2;\narg.chat = 0;\n\narg = vararg_pair(arg, varargin, 'subs', ...\n{'stop_threshold', 'stop_diff_tol'; 'stop_norm_type', 'stop_diff_norm'});\n\narg.isave = iter_saver(arg.isave, arg.niter);\nif arg.stop_diff_tol\n\tnorm_diff = @(x) norm(x, arg.stop_diff_norm);\nend\nif arg.stop_grad_tol\n\tnorm_grad = @(g) norm(g, arg.stop_grad_norm) / reale(yi' * (W * yi));\nend\n\nif ~isreal(yi) && ~isequal(arg.precon, 1)\n\tpersistent warned\n\tif isempty(warned), warned = 0; end\n\tif ~warned\n\t\twarning 'not 100% sure about the complex preconditioned case'\n\t\twarned = 1;\n\tend\nend\n\ncpu etic\nif isempty(x), x = zeros(ncol(A),1); end\n\nx = x(:);\nnp = length(x);\nxs = zeros(np, length(arg.isave), 'single');\nif any(arg.isave == 0)\n\txs(:, arg.isave == 0) = single(x);\nend\n\n%info = zeros(arg.niter, ?); % trick: do not initialize because size may change\n\n% initialize projections\nticker(mfilename, 1, arg.niter)\nAx = A * x;\nCx = C * x;\n\n% iterate\nfor iter = 1:arg.niter\n\tticker(mfilename, iter, arg.niter)\n\n\t% (negative) gradient\n\tngrad = A' * (W * (yi-Ax)) - C' * Cx;\n\n\tif arg.stop_grad_tol && norm_grad(ngrad) < arg.stop_grad_tol\n\t\tif arg.chat\n\t\t\tprintm('stop at iteration %d with grad %g < %g', ...\n\t\t\t\titer, norm_grad(ngrad), arg.stop_grad_tol)\n\t\tend\n\t\tif isequal(arg.isave, arg.niter) % saving last iterate only?\n\t\t\txs = single(x); % save 'final' iterate\n\t\telse % saving many iterates?\n\t\t\txs(:, arg.isave > iter) = []; % clear out unused\n\t\tend\n\treturn\n\tend\n\n\t% preconditioned gradient\n\tpregrad = arg.precon * ngrad;\n\n\t% search direction\n\tnewinprod = ngrad' * pregrad;\n\t% fix: should i take the real part?\n\tnewinprod = reale(newinprod, 'warn', 'inprod');\n\tif iter == 1\n\t\tddir = pregrad;\n\t\tgamma = 0;\n\telse\n\t\tif oldinprod == 0\n\t\t\twarn 'inprod=0. going nowhere!'\n\t\t\tgamma = 0;\n\t\telse\n\t\t\tgamma = newinprod / oldinprod;\t% Fletcher-Reeves\n%\t\t\tgamma = (newinprod - oldgrad' * pregrad) / oldinprod;\n\t\tend\n\t\tddir = pregrad + gamma * ddir;\n\tend\n\toldgrad = ngrad;\n\toldinprod = newinprod;\n\n\t% check if descent direction\n\tif arg.dircheck && real(ddir' * ngrad) < 0\n\t\twarn 'wrong direction; try using stop_grad_tol'\n\t\tratio = norm(ngrad(:), arg.stop_grad_norm) / (yi'*W*yi);\n\t\tpr ratio % see how small it is\n\t\tif arg.key, keyboard, end\n\tend\n\n\t% step size in search direction\n\tAdir = A * ddir;\n\tCdir = C * ddir;\n\n\tdenom = Adir'*(W*Adir) + Cdir'*Cdir;\n\tdenom = reale(denom, 'error', 'denom');\n\tif denom == 0\n\t\twarning 'found exact solution??? step=0 now!?'\n\t\tstep = 0;\n\telse\n\t\tstep = (ddir' * ngrad) / denom;\n%\t\tstep = reale(step, 'warn', 'step');\n\t\tstep = real(step); % real step sizes seems only logical\n\tend\n\n\tif step < 0\n\t\twarning 'downhill?'\n\t\tif arg.key, keyboard, end\n\tend\n\n\t% update\n\tAx = Ax + step * Adir;\n\tCx = Cx + step * Cdir;\n\tx = x + step * ddir;\n\n\tif any(arg.isave == iter)\n\t\txs(:, arg.isave == iter) = single(x);\n\tend\n\tinfo(iter,:) = arg.userfun(x, arg.userarg{:});\n\n\t% check norm(xnew-xold) / norm(xnew) vs threshold\n\tif arg.stop_diff_tol && ...\n\t\tnorm_diff(step * ddir) / norm_diff(x) < arg.stop_diff_tol\n\t\tif arg.chat\n\t\t\tratio = norm_diff(step * ddir) / norm_diff(x);\n\t\t\tprintm('stop at iteration %d with diff %g < %g', ...\n\t\t\t\titer, ratio, arg.stop_diff_tol)\n\t\tend\n\t\tif isequal(arg.isave, arg.niter) % saving last iterate only?\n\t\t\txs = single(x); % save the 'final' iterate\n\t\telse % saving many iterates?\n\t\t\txs(:, arg.isave > iter) = []; % clear out unused\n\t\tend\n\treturn\n\tend\nend\n\n\n% default user function.\n% using this evalin('caller', ...) trick, one can compute anything of interest\nfunction out = userfun_default(x, varargin)\ngamma = evalin('caller', 'gamma');\nstep = evalin('caller', 'step');\nout = [gamma step cpu('etoc')];\n\n\n% qpwls_pcg1_test0()\nfunction qpwls_pcg1_test0\nmask = true([8 7]); mask(1) = false;\nA = Gblur(mask, 'psf', ones(3)/9);\ntmp = ones(size(mask));\nA = Gdiag(tmp(mask), 'mask', mask);\nxtrue = zeros(size(mask), 'single');\nxtrue(end/2, round(end/2)) = 1;\ny = A * xtrue(mask);\nbeta = 2^-7;\nbeta = 2^-2;\nR = Reg1(mask, 'beta', beta, 'order', 1);\nqpwls_psf(A, R.C, 1, mask, 1, 'loop', 0);\nhess = full(A' * A + R.C' * R.C);\nxhat = hess \\ (A' * y);\nxhat = embed(xhat, mask);\npr fwhm2(xhat)\nim clf, im(xhat)\n\n% user functions for tracking time and distance to a reference image\nf.userfun = @(x, xref) [cpu('etoc') norm(x(:) - xref(:))];\nf.userarg = {xhat(mask)}; % reference image just for testing\n\nxinit = 0 * mask;\nxpcg = qpwls_pcg1(xinit(mask(:)), A, 1, y, R.C, 'niter', 100, ...\n\t'userfun', f.userfun, 'userarg', f.userarg, ...\n        'stop_grad_tol', 1e-8, 'stop_grad_norm', 2, ...\n        'stop_diff_tol', 0e-6, 'stop_diff_norm', 2, 'chat', 1);\nxpcg = embed(xpcg, mask);\n\nim plc 2 2\nim(1, xtrue)\nim(2, xhat)\nim(3, xpcg)\nim(4, xpcg - xhat)\nequivs(xpcg, xhat)\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/wls/qpwls_pcg1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.5675511246730353}}
{"text": "function g = gammaEval(j, k, LR, N, dim, nVars)\n%GAMMAEVAL   Evaluate a gamma-function.\n%   g = GAMMAEVAL(L, LR, N, DIM, NVARS) evaluates the gamma-function (J, K) with\n%   the contour LR, N grid points, in dimension DIM and with NVARS variables.\n%\n% See also EXPINTEG/GAMMAFUN.\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 a function handle to the phi function of index L:\ng = expinteg.gammaFun(j, k);\n\n% Evaluate it with a contour integral:\ng = mean(feval(g, LR), 2);\n\n% Reshape it when nVars>1 or/and dim>1:\ng = reshape(g, nVars*N, N^(dim>1), N^(dim>2));\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@expinteg/gammaEval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5674624951721737}}
{"text": "function Population = EnvironmentalSelection(Population,N)\n% The environmental selection of CMOPSO\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    %% Non-dominated sorting\n    [FrontNo,MaxFNo] = NDSort(Population.objs,N);\n    Next = false(1,length(FrontNo));\n    Next(FrontNo<MaxFNo) = true;\n    \n    PopObj = Population.objs;\n    fmax   = max(PopObj(FrontNo==1,:),[],1);\n    fmin   = min(PopObj(FrontNo==1,:),[],1);\n    PopObj = (PopObj-repmat(fmin,size(PopObj,1),1))./repmat(fmax-fmin,size(PopObj,1),1);\n\n    %% Select the solutions in the last front\n    Last = find(FrontNo==MaxFNo);\n    del  = Truncation(PopObj(Last,:),length(Last)-N+sum(Next));\n    Next(Last(~del)) = true;\n    % Population for next generation\n    Population = Population(Next);\nend\n\nfunction Del = Truncation(PopObj,K)\n% Select part of the solutions by truncation\n\n    N = size(PopObj,1);\n    \n    %% Truncation\n    Distance = pdist2(PopObj,PopObj);\n    Distance(logical(eye(length(Distance)))) = inf;\n    Del = false(1,N);\n    while sum(Del) < K\n        Remain   = find(~Del);\n        Temp     = sort(Distance(Remain,Remain),2);\n        [~,Rank] = sortrows(Temp);\n        Del(Remain(Rank(1))) = true;\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/CMOPSO/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5674624842680596}}
{"text": "function [relativearea, name] = objectareas(D)\n\n\nk = 0;\nfor i = 1:length(D);\n    if isfield(D(i).annotation, 'object')\n        Nobjects = length(D(i).annotation.object);\n\n        nrows = D(i).annotation.imagesize.nrows;\n        ncols = D(i).annotation.imagesize.ncols;\n        \n        for n = 1:Nobjects\n            [X,Y] = getLMpolygon(D(i).annotation.object(n).polygon);\n\n            area = polyarea(X,Y); % ignores intersections\n            \n            k = k+1;\n            relativearea(k) = area/(nrows*ncols);\n            name{k} = D(i).annotation.object(n).name;\n        end\n    end\nend\n", "meta": {"author": "CSAILVision", "repo": "LabelMeToolbox", "sha": "b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2", "save_path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox", "path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox/LabelMeToolbox-b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2/main/objectareas.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5674624841428008}}
{"text": "\n% Test whether it is necessary to rotate VB PCA\nfunction nc2010_publish_datasets\n\nn = 200;\nm = 50;\nd = 10;\n\nncomps = 30;\n\nrandn('state', 1);\nrand('state', 1);\n\n% Generate multivariate normal data\ndisp('Using weak subspace')\neigs = (1 + [d:-1:1 zeros(1,m-d)]) .^ 2\ndatastring = 'weak';\nplot_eigenvalues(eigs, datastring);\n\ndisp('Using strong subspace')\neigs = ([5*ones(1,d) 1*ones(1,m-d)]) .^ 2\ndatastring = 'strong';\nplot_eigenvalues(eigs, datastring);\n\ndisp('Using no subspace')\neigs = (m:-1:1) .^ 2\ndatastring = 'no';\nplot_eigenvalues(eigs, datastring);\n\n\nfunction plot_eigenvalues(eigs, datastring)\n\nfilename = sprintf(['/home/jluttine/papers/neurocomputing2010/' ...\n                    'fig_eigenvalues_dataset=%s'], datastring);\n\nfigure\nplot(sqrt(eigs), 'k-');\nset(gcf, 'units', 'centimeters', 'paperunits', 'centimeters');\npos = get(gcf, 'position');\nset(gcf, 'position', [pos(1:2), 6,4]);\npos = get(gcf, 'paperposition');\nset(gcf, 'paperposition', [pos(1:2),6,4])\n\nylim([0, max(sqrt(eigs))+1]);\nxlim([1, length(eigs)]);\n\n%ylabel('standard deviation')\n\nprint(gcf, '-depsc2', filename);\n\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/publications/neurocomputing2010/nc2010_publish_datasets.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5674624840801707}}
{"text": "% Digital Video Stabilization and Rolling Shutter Correction using Gyroscopes\n% Copyright (C) 2011 Alexandre Karpenko\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% 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 <http://www.gnu.org/licenses/>.\n\nfunction [dth, theta] = frame_rotations_non_lin(gyro, gyro_time, frame_time, t0, ts)\n% computes the delta in theta between frame times, as well as the shear\n% at frame time\ndgt = diff(gyro_time);\ntheta = ((gyro(1:end-1,:) + gyro(2:end,:)) / 2) .* dgt(:,[1 1 1]);\ntheta = [0 0 0; cumsum(theta, 1)];\n\nsigma2 = 4000;\ngauss = exp(-(-120:120).^2 / sigma2);\ngauss = gauss ./ sum(gauss);\ngyro(:,1) = gyro(:,1) - conv(gyro(:,1), gauss, 'same');\ngyro(:,2) = gyro(:,2) - conv(gyro(:,2), gauss, 'same');\ngyro(:,3) = gyro(:,3) - conv(gyro(:,3), gauss, 'same');\nth = ((gyro(1:end-1,:) + gyro(2:end,:)) / 2) .* dgt(:,[1 1 1]);\nth = [0 0 0; cumsum(th, 1)];\ndth = diff(lininterp(gyro_time + t0 + ts/2, th, frame_time));\n", "meta": {"author": "alex-golts", "repo": "Video-Stabilization", "sha": "03455a8bb589cb8fcb1e6900cf59bc3d8cc24078", "save_path": "github-repos/MATLAB/alex-golts-Video-Stabilization", "path": "github-repos/MATLAB/alex-golts-Video-Stabilization/Video-Stabilization-03455a8bb589cb8fcb1e6900cf59bc3d8cc24078/frame_rotations_non_lin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.567442627198944}}
{"text": "function dUpsilon = lfmvpGradientUpsilonMatrix(gamma, sigma2, t1, ...\n    t2, mode, upsilon)\n\n% LFMVPGRADIENTUPSILONMATRIX Gradient upsilon matrix vel. pos.\n% FORMAT\n% DESC computes the gradient of 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 upsilon : precomputation of the upsilon matrix.\n% ARG mode : operation mode, according to the derivative (mode 0,\n% derivative wrt t1, mode 1 derivative wrt t2)\n% RETURN upsilon : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n%\n% SEEALSO : lfmvpComputeUpsilonMatrix.m\n\n% KERN\n\nsigma = sqrt(sigma2);\n\nif nargin<6\n    upsilon = lfmComputeUpsilonMatrix(gamma, sigma2, t1, t2);\n    if nargin <5\n        mode =0;\n    end\nend\n\nif mode ==0\n    dUpsilon = -upsilon - gamma*lfmGradientUpsilonMatrix(gamma, sigma2, t1, t2);\nelse\n    dUpsilon = upsilon + gamma*lfmGradientUpsilonMatrix(gamma, sigma2, t1, t2) ...\n        - (2/(sqrt(pi)*sigma))*(t1.*exp(-gamma*t1))*(exp(-(t2.^2)/sigma2)).';\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/lfmvpGradientUpsilonMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5674426219123685}}
{"text": "function y=comb(x)\n\n% This function is used to create all possible combinations\n% of Input Term Nodes Outputs to be fed into the Rule Nodes.\n% Each combination is fed to a single rule neuron responsible\n% for the processing of this specific combination.\n\n[rows columns] = size(x);\n\ny = zeros(columns^rows,rows);\n\nfor i=1:rows\n   \n    if i<=rows-1\n   \n      j=1; \n   \n      for m=0:columns^(rows-i):(columns^rows - columns^(rows-i))      \n               \n        if j<=columns  \n         \n             for l=1:columns^(rows-i)\n                      y(m+l,i) = x(i,j);\n             end\n         \n         else\n         \n            j=1;\n             for l=1:columns^(rows-i)\n                     y(m+l,i) = x(i,j);\n             end\n\n         end\n      \n         j = j + 1;     \n      \n      end  \n   \n    elseif i==rows\n      \n        for m=0:columns:(columns^rows - columns)\n            \n            j=1; \n            for l=1:columns \n                y(m+l,i) = x(i,j);\n                j=j+1; \n            end\n        end\n   \n    end    % end of \"if i\" loop.\n    \nend      % end of \" for i\" loop.\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43021-recurrent-fuzzy-neural-network-rfnn-library-for-simulink/S-functions/comb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5674426219123685}}
{"text": "function dat= func_powerspectrum (data, band, varargin)\n% func_powerspectrum :\n% This function calculates the power spectrum\n%\n% Example:\n%      dat= func_powerspectrum(dat, [8 15], {'win',[];'step',100})\n% \n% Input:\n%      dat  - data structure of continuous or epoched data\n%      band - frequency band\n%\n% Options:\n%      win  - window for FFT, default ones(dat.fs, 1)\n%      N    - window width for FFT -> square window, default dat.fs\n%      step - step for window (= # of overlapping samples), default N/2\n%      db_scaled - boolean, if true values are db scaled (10*log10),\n%                  default true\n% Retuns:\n%     dat - Data structure of power specturm result\n%%\n% data\ndat=data;\nban=band;\nopt=opt_cellToStruct(varargin{:});\nepo=struct('win',[],'N',[],'step',[],'scale',[]);\n\nif isempty(dat)\n    warning('Warning! data is empty');\nend\nif isempty(ban)\n    warning('Band is not exist.');\nend\n\nif ~isfield(opt,'win') \n   epo.win=dat.fs;\nelse\n    epo.win=opt.win;\nend\n\nif ~isfield(opt,'N')\n   epo.N=dat.fs;\nelse\n    epo.N=opt.N;\nend\n\nif ~isfield(opt,'step')\n   epo.step=dat.fs/2;\nelse\n   epo.N=opt.N;\nend\n\nif ~isfield(opt,'scale')\n   epo.scale='db';\nelse\n    epo.scale=opt.scale;\nend\n\n[T, nEvents , nChans]= size(dat.x);\n\nif length(epo.win)==1\n    if epo.win>T\n        warning('window legth is higher than signal')\n    end\n    epo.win=ones(epo.win,1);\nend\nN=length(epo.win);\nnormwin=norm(epo.win);\nFreq=(0:N)/2*dat.fs/N;\n\n%%\nXX= zeros(N, nChans*nEvents);\nnWindows= 1 + max(0, floor((T-N)/epo.step));\niv= 1:min(N, T);\nWin= repmat(epo.win(:), [1 nChans*nEvents]);\nbInd= band(1): ban(2);\n\n%%calculate file\n\nswitch(lower(epo.scale)),\n    case 'db',\n        for iw= 1:nWindows,\n            XX= XX + abs(fft(dat.x(iv,:).*Win, N)).^2;\n            iv= iv + epo.step;\n        end\n        XX = XX/(nWindows*normwin^2);\n        dat.x= reshape( 10*log10( XX(bInd,:)+eps ), [length(bInd), nChans, nEvents]);\n        dat.yUnit= 'dB';\n    case 'power',\n        for iw= 1:nWindows,\n            XX= XX + abs(fft(dat.x(iv,:).*Win, N).^2);\n            iv= iv + epo.step;\n        end\n        dat.x= reshape(XX(bInd,:)/(nWindows*normwin^2), [length(bInd), nChans, nEvents]);\n        dat.yUnit= 'power';\nend\n\n\n\nend\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/BMI_modules/Functions/func_powerspectrum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6791786991753929, "lm_q1q2_score": 0.5674426219123683}}
{"text": "function [y1]=rs(y1,T,f2)\n% [y2] = rs(y1, T) resamples y1 to the target sampling rate y2 using T\n% [y2] = rs(y1, f1, f2) resamples y1 with f1 to the target sampling rate f2 \n%\n% RS does not require overlap data. \n%\n% see also: SOPEN, SREAD, SCLOSE, MAT2SEL, SAVE2TXT, SAVE2BKR\n%\n% Reference(s):\n\n%\t$Revision: 1.2 $\n%\t$Id: rs.m 2202 2009-10-27 12:06:45Z schloegl $\n%\tCopyright (C) 1997-2004 by Alois Schloegl \n%\ta.schloegl@ieee.org\t\n%    \tThis is part of the BIOSIG-toolbox http://biosig.sf.net/\n\n% This library is free software; you can redistribute it and/or\n% modify it under the terms of the GNU Library General Public\n% License as published by the Free Software Foundation; either\n% Version 2 of the License, or (at your option) any later version.\n%\n% This library 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 GNU\n% Library General Public License for more details.\n%\n% You should have received a copy of the GNU Library General Public\n% License along with this library; if not, write to the\n% Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n% Boston, MA  02111-1307, USA.\n\nif nargin==3,\n        f1=T;\n        if f1==f2\n                return;\n        elseif f1>f2\n                D=f1/f2;\n                [yr,yc]=size(y1);\n                LEN=yr/D;\n\t\ty2=zeros(yr*f2/f1,yc);\n                for k=0:LEN-1\n                        y2(k+1,:)=sum(y1(k*D+(1:D),:),1)/D;\n                end;\n\t\ty1=y2;\n        else %f1<f2\n\t\ty1=y1(ceil((1:size(y1,1)*f2/f1)/f2*f1),:);                \n        end;\n        \nelseif nargin==2,\n        [f1,f2]=size(T);\n        if f1==f2,\n                return;\n        end;\n        [yr,yc]=size(y1);\n        LEN=yr/f1;\n\ty2=zeros(yr*f2/f1,yc);\n        for k=0:LEN-1\n                y2(k*f2+(1:f2),:)=T'*y1(k*f1+(1:f1),:);\n        end;\n\ty1=y2;\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/external/biosig-partial/t250_ArtifactPreProcessingQualityControl/rs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5674426138436366}}
{"text": "% sideways motion of center of rotation\nfunction [data,units] = compute_dv_cor(trx,n)\n\nflies = trx.exp2flies{n};\nnflies = numel(flies);\ndata = cell(1,nflies);\nfor i = 1:nflies,\n  fly = flies(i);\n  \n  if trx(fly).nframes < 2,\n    data{i} = [];\n  else\n    % center of rotation\n    [x_cor_curr,y_cor_curr,x_cor_next,y_cor_next] = rfrac2center(trx,fly,[trx(fly).corfrac_maj;trx(fly).corfrac_min]);\n    % change in center of rotation\n    dx_cor = x_cor_next - x_cor_curr;\n    dy_cor = y_cor_next - y_cor_curr;      \n    % forward motion of center of rotation\n    data{i} = (dx_cor.*cos(trx(fly).theta_mm(1:end-1)+pi/2) + dy_cor.*sin(trx(fly).theta_mm(1:end-1)+pi/2))./trx(fly).dt;\n\n  end\n\nend\nunits = parseunits('mm/s');\n\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/compute_dv_cor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.567431595384813}}
{"text": "function bnet_miss = gener_MAR_net(bnet_orig, base_proba)\n% function bnet_miss = gener_MAR_net(bnet_orig, base_proba)\n% \n%   bnet_orig : a bnet\n%   base_proba :  a probability for value to be missing\n%\n%   bnet_miss : a bnet that could be used in gener_data_from_bnet_miss function\n%               to generate incomplete MAR dataset\n%\n% Francois.Olivier.C.H@gmail.com\n\n%%%%%%%%%%%% INIT\nif nargin<2, error('Not enougth arguments'); end\n\n% cr\u00e9ation du r\u00e9seau\ndag = bnet_orig.dag;\nN = size(dag,2);\nns = bnet_orig.node_sizes;\n\n  ns_miss = zeros(1,3*N);\n  ns_miss(1:N) = ns;\n  ns_miss(N+1:2*N) = 2*ones(1,N); % 1= node i-N present, 2= node i-N missing\n  ns_miss(2*N+1:3*N) = ns+1; % 1:ns, absent\n\n  dag_miss = zeros(3*N,3*N);\n  dag_miss(1:N,1:N) = dag;\n%  dag_miss(2*N+1:3*N,N+1:2*N)=mk_rnd_dag(N,N-ceil(rand*N/2)); \n  lim = 1+(rand>.4)+(rand>.65)+(rand>.9);\n  dag_miss(2*N+1:3*N,N+1:2*N)=mk_rnd_dag(N,lim); \n\n  for i=1:N, dag_miss(i,2*N+i)=1; dag_miss(N+i,2*N+i)=1; dag_miss(2*N+i,i)=0; dag_miss(2*N+i,N+i)=0; end\n\n  bnet_miss = mk_bnet(dag_miss, ns_miss);\n  CPT = CPT_from_bnet(bnet_orig, 0);\n  for i=1:N\n    bnet_miss.CPD{i} = tabular_CPD (bnet_miss, i, CPT{i});\n  end\n\n  % CPD of nodes M\n  for i=1:N,\n     if find(bnet_miss.order==i)<find(bnet_miss.order==N+i),\n        CPT_M=[];\n        for j=1:ns_miss(i), for l=1:ns_miss(N+i), for k=1:ns_miss(2*N+i),\n          CPT_M=[CPT_M (((j==k)&(l==1))|((k==ns_miss(2*N+i))&(l==2)))];\n        end, end, end\n     else \n        CPT_M=[];\n        for k=1:ns_miss(2*N+i), for l=1:ns_miss(N+i), for j=1:ns_miss(i), \n          CPT_M=[CPT_M (((j==k)&(l==1))|((k==ns_miss(2*N+i))&(l==2)))];\n        end, end, end\n     end\n     bnet_miss.CPD{2*N+i} = tabular_CPD (bnet_miss, 2*N+i, CPT_M);\n  end\n\n%%%%%%%%%%%% Base probability of missing value\np = base_proba;\n for i=1:N\n  fam = find(dag_miss(:,N+i)==1)';\n  semisize = prod(ns_miss(fam)); % as node N+i is binary to say i is present or missing\n  CPT = zeros(1,2*semisize);\n  CPT(1:semisize) = 1-p;\n  CPT(semisize+1:2*semisize) = p;\n  bnet_miss.CPD{N+i} = tabular_CPD (bnet_miss, N+i, CPT);\n end\n\n   BETA = gener_discrete_dist(N, base_proba);\n\n   order=[];\n   missdagtmp = bnet_miss.dag; %(N+1:2*N,N+1:2*N);\n   unprocessed = 1:N;\n   while ~isempty(unprocessed)\n     npar=[];\n     for i=N+1:2*N, npar(end+1)=length(parents(missdagtmp,i));end,  % to be verifie from here\n     [npar, ord] = sort(npar);\n     while ~ismember(ord(1),unprocessed)\n       ord=ord(2:end);\n     end\n     order = [order, ord(1)];\n     missdagtmp(ord(1),:)=0;\n     unprocessed = mysetdiff(unprocessed,ord(1));\n   end\n\n%%%%%%%%%%%% Update CPT with MCAR process\nfor i=1:length(BETA)\n  fam_miss = find(dag_miss(:,N+order(i))==1)';\n  p=BETA(i);\n  semisize = prod(ns_miss(fam_miss));\n\n  if isempty(fam_miss),\n        CPT = zeros(1,2*semisize);\n        CPT(1:semisize) = 1-p;\n        CPT(semisize+1:2*semisize) = p;\n        bnet_miss.CPD{N+order(i)} = tabular_CPD (bnet_miss, N+order(i), CPT);\n  else\n\n        MUi1k = gener_discrete_dist(semisize, p);\n        CPT = zeros(1,2*semisize);\n        CPT(1:semisize) = 1-MUi1k;\n        CPT(semisize+1:2*semisize) = MUi1k;\n        bnet_miss.CPD{N+order(i)} = tabular_CPD (bnet_miss, N+order(i), CPT);\n\n  end\n\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/misc/gener_MAR_net.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.5674315792893108}}
{"text": "function [ calmars ] = calmar( cumReturns, mdds, frequency )\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This file is part of OLPS: http://OLPS.stevenhoi.org/\n% Original authors: Bin LI, Doyen Sahoo\n% Contributors: Steven Hoi\n% Change log: \n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    [r c] = size(cumReturns);\n    calmars = zeros(1,c);\n    den = 252/frequency;\n    Y = r/den;\n    annualisedReturns = ((cumReturns(r,:)./cumReturns(1,:)) .^ (1/Y)) - 1;\n    calmars = annualisedReturns ./ mdds;\nend\n\n", "meta": {"author": "OLPS", "repo": "OLPS", "sha": "9120783cd59a7966b0f78e2b5668030a4378b8af", "save_path": "github-repos/MATLAB/OLPS-OLPS", "path": "github-repos/MATLAB/OLPS-OLPS/OLPS-9120783cd59a7966b0f78e2b5668030a4378b8af/GUI/lib/calmar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5674070286757897}}
{"text": "function signal = flt_delayembed(varargin)\n% Apply delay embedding to epoched data.\n% Signal = flt_delayembed(Signal,NumLags)\n%\n% Delay embedding is essentially appending to each multi-channel samples the subsequent k\n% multi-channel samples, and thereby multiplies the number of channels by k. Delay embedding is a\n% practical tool to extend linear spatial models (e.g., spatial filters or independent components)\n% to linear spatio-temporal (and therefore implicitly spatio-spectral) models, just by applying\n% those models to delay-embedded data. As a result, approaches that can learn optimal spatial\n% filters (finding sources of interest) can be repurposed to learning optimal spatio-spectral\n% filters (jointly finding sources and frequencies of interest).\n%\n% The tradeoff associated with delay-embedding is that the complexity of the models increases and\n% they become harder to estimate, which might require more data or better\n% constraints, priors, or regularization.\n%\n% In:\n%   Signal : Epoched data set to be processed\n%   \n%   NumLags : the number of lags that shall be used for delay-embedding (default: 1)\n%\n%   IncludeIntermediates : Include intermediate lags. If this is set to false, only the 0''th and\n%                          the N''th lag will be embedded. (default: true)\n%\n% Out:\n%   Signal : the processed signal; will have more channels\n%\n% Notes:\n%   The temporal filters that can be designed for a small number of lags are often limited to \n%   high-frequency responses; the frequency range can often be extended without increasing model\n%   complexity by first resampling the data to the lowest acceptable sampling rate (e.g., 60 Hz).\n%\n%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n%                                2013-11-17\n\n% flt_delayembed_version<1.00> -- for the cache\n\nif ~exp_beginfun('filter') return; end\n\n% requires epoched data, works best on spatially filtered data\ndeclare_properties('name','DelayEmbedding', 'depends','set_makepos', 'follows',{'flt_project','flt_window'}, 'independent_channels',false, 'independent_trials',true);\n\n% declare arguments\narg_define(varargin,...\n    arg_norep({'signal','Signal'}), ...\n    arg({'numlags','NumLags'}, 1, uint32([1 1 20 1000]), 'Number of lags. For delay-embedding.'), ...\n    arg({'includeIntermediates','IncludeIntermediates'}, true, [], 'Include intermediate lags. If this is set to false, only the 0''th and the N''th lag will be embedded.'));\n\nfor k=quickif(includeIntermediates,0:numlags,[0 numlags])\n    tmp{k+1} = signal.data(:,k+(1:end-numlags),:); end\nsignal.data = cat(1,tmp{:});\n[signal.nbchan,signal.pnts,signal.trials] = size(signal.data);\nsignal.chanlocs = struct('labels', cellfun(@num2str,num2cell(1:signal.nbchan),'UniformOutput',false));\n\nexp_endfun;\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/filters/flt_delayembed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5673967205104239}}
{"text": "function [fusion,w0] = qfuser_v5(w,scores,wfuse)\n\nif nargin==0\n    test_this();\n    return;\nend\n\n\n% block 1\nf1 = linear_fuser([],scores.scores);\nw1 = wfuse;\n[whead,wtail] = splitvec_fh(length(w1));\nf1 = f1(whead);\n\n% block 2\nmodelQ = scores.modelQ;\n[q,n1] = size(modelQ);\nmodelQ = [modelQ;ones(1,n1)];\nsegQ = scores.segQ;\n[q2,n2] = size(segQ);\nsegQ = [segQ;ones(1,n2)];\nassert(q==q2);\nq = q + 1;\n\nwq = q*(q+1)/2;\nf2 = AWB_fh(modelQ',segQ,tril_to_symm_fh(q,wtail));\nw2 = zeros(wq,1);\n\n% assemble\nfusion = sum_of_functions(w,[1,1],f1,f2);\nw0 = [w1;w2];\n\n\n\n\nend\n\n\nfunction test_this()\n\nm = 5;\nk = 2;\nn1 = 4;\nn2 = 5;\n\nscores.sindx = [1,2,3];\nscores.qindx = [4,5];\n\nscores.scores = randn(m,n1*n2);\nscores.modelQ = randn(k,n1);\nscores.segQ = randn(k,n2);\n\nwfuse = [1,2,3,4]';\n\n[fusion,w0] = qfuser_v4([],scores,wfuse);\n\n%test_MV2DF(fusion,w0);\n\n[fusion(w0),linear_fuser(wfuse,scores.scores(scores.sindx,:))]\n\n%fusion(w0)\n\n\nend\n", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/tDCF_v1/bosaris_toolkit.1.06/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/qfuser_v5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5673774337701708}}
{"text": "%Leave One Out Cross Validation with Nearest Neighbor Classifier\n%>\n%> @param FeatureMatrix: features (dimension iNumFeatures x iNumObservations)\n%> @param ClassIdx: vector with class indices (length iNumObservations, starting from 0)\n%>\n%> @retval Acc overall accuracy after Cross-Validation\n% ======================================================================\nfunction [Acc, conf_mat] = ToolLooCrossVal(FeatureMatrix, ClassIdx)\n \n    % initialize\n    TP = 0;\n    \n    conf_mat = zeros(length(unique(ClassIdx)));\n    \n    % loop over observations\n    for o = 1:size(FeatureMatrix, 2)\n        % remove current observation from 'training set'\n        v_train = [FeatureMatrix(:, 1:o-1) FeatureMatrix(:, o+1:end)]';\n        C_train = [ClassIdx(1:o-1) ClassIdx(:, o+1:end)]';\n        \n        % compute result of Nearest Neighbor Classifier given the traindata\n        res = ToolSimpleKnn(FeatureMatrix(:, o)', v_train, C_train, 1);\n        \n        conf_mat(ClassIdx(o)+1, res+1) = conf_mat(ClassIdx(o)+1, res+1) + 1;     \n        \n        % if result is correct increment number of true positives\n        if (res == ClassIdx(o))\n            TP = TP+1;\n        end\n    end\n \n    % compute overall (micro) accuracy\n    Acc = TP / length(ClassIdx);\nend\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/ToolLooCrossVal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5673774335087803}}
{"text": "function [ output_args ] = bz_LFPPowerDist( LFP,varargin )\n% bz_LFPPowerDist(LFP) calculates the power distribution of an LFP signal.\n%   NOTE: THIS FUNCTION IS UNDER DEVELOPMENT. Feel free to chip in.\n\n%\n%INPUTS\n%   LFP     [nt x 1] vector of the LFP signal -or- basename\n%   (optional)\n%   sf          sampling frequency of the LFP (default 1250Hz)\n%   int         restrict analysis to specific time intervals \n%   spectype    'wavelet' or 'FFT'\n%   frange      [lowf highf]\n%   nfreqs      number of frequencies to look at\n%   SHOWFIG     true/false (default: false)\n%   figfolder   folder to save output figures\n%   \n%% DEV\n%datasetfolder = '/Users/dlevenstein/Dropbox/Research/Datasets/BWData/';\n%figfolder = '/Users/dlevenstein/Dropbox/Research/Current Projects/misc/PowerDistribution/';\n%recname = '20140526_277um';\n\n%load(fullfile(datasetfolder,recname,[recname,'_LFP.mat']))\n%load(fullfile(datasetfolder,recname,[recname,'_SleepScore.mat']))\n%%\nsf = 1250;\n%int = StateIntervals.NREMpacket;\n\n%LFP = LFP.CTX;\n%LFP = NormToInt(LFP,int,sf,'modZ');\n\nspectype = 'FFT';\n\n%%\nwarning('This function is still under development. No promises')\n\n\nfrange = [1 128];\nnfreqs = 100;\n\nswitch spectype\n    case 'FFT'\n        freqlist = logspace(log10(frange(1)),log10(frange(2)),nfreqs);\n        window = 1;\n        noverlap = 0.8;\n        window = window*sf;\n        noverlap = noverlap*sf;\n        [spec,freqs,t_FFT] = spectrogram(LFP,window,noverlap,freqlist,sf);\n        spec = abs(spec)';\n        \n        [~,inintIDX] = RestrictInts(t_FFT',int);\n        intspec = spec(inintIDX,:);\n    case 'wavelet'\n        downsamplefactor = 2;\n        sf_down = sf./downsamplefactor;\n        intLFP = IsolateEpochs2(downsample(LFP,2),int,0,sf_down);\n        ncyc = 5;\n        [freqlist,t,intspec] = bz_WaveSpec(intLFP,frange,nfreqs,ncyc,1/sf_down,'log');\n        intspec = cat(2,intspec{:});\n        intspec = abs(intspec)';\nend\n\n    \n%%\nnumpowerbins = 200;\n\n%minpower = min(intspec(:)); maxpower = max(intspec(:));\nswitch spectype\n    case 'FFT'\n        minpower = 0.5;maxpower = 2.85e3;\n    case 'wavelet'\n        minpower = -2;maxpower = 2;\nend\n\npowerbins = linspace(log10(minpower),log10(maxpower),numpowerbins);\n[powerdist_mean] = hist(log10(intspec),powerbins);\n\n%%\nfigure\n%subplot(2,2,1)\nimagesc(log2(freqlist),powerbins,powerdist_mean)\naxis xy\nLogScale('x',2)\n\n%%\nalldists = {'birnbaumsaunders','exponential','extreme value','gamma',...\n    'generalized extreme value','generalized pareto','inverse gaussian',...\n    'logistic','loglogistic','lognormal','nakagami','normal','rayleigh',...\n    'rician','tlocationscale','weibull'};\n\n%Distirbutions were removed that consistently showed bad fit to cortical\n%LFP data during NREM\ntestdists = {'gamma','loglogistic','lognormal',...\n    'rayleigh','weibull'};\n\nshowexamples = [];\n\nD = {};PF = {};bestfit={};\nfor ff = 1:nfreqs\n    ff\n    if ismember(ff,showexamples)\n        [distfits] = allfitdist(intspec(:,ff),'PDF');\n    else\n        [distfits] = allfitdist(intspec(:,ff));\n    end\n    \n    %Keep only the distributions tested\n    distnames = {distfits(:).DistName};\n    keepdists = ismember(distnames,testdists);\n    distfits = distfits(keepdists);\n    \n    %Check the best and worst-fitting distribution\n    bestfit{ff} = distfits(1).DistName;\n    worstfit{ff} = distfits(end).DistName;\n    \n    %Sort alphabetically\n    distnames = {distfits(:).DistName};\n    [distnames,sortdist] = sort(distnames);\n  \n    D{ff} = distfits(sortdist);\nend\n\n%%\nAICs = cellfun(@(X) [X(:).AIC],D,'UniformOutput',false);\nAICs = cat(1,AICs{:});\n\nndists = length(distnames);\nbestfitmat = zeros(nfreqs,ndists);\nfor nn = 1:ndists\n    bestfitmat(:,nn) = nn.*strcmp(distnames{nn},bestfit);\nend\nbestfitmat(bestfitmat==0)=nan;\n%%\nfigure\nsubplot(2,2,1)\n    imagesc(log2(freqlist),powerbins,powerdist_mean)\n    axis xy\n    LogScale('x',2);LogScale('y',10)\n    xlabel('f (Hz)')\n    ylabel('Power (AU)')\n    title([spectype,' Power Distribution'])\n    \nsubplot(4,2,5)\n    plot(log2(freqlist),log10(AICs),'LineWidth',1)\n\n    legend(distnames,'location','southwest')\n    axis tight\n    LogScale('x',2);%LogScale('y',10)\n    xlabel('f (Hz)')\n    box off\n    ylabel('log(AIC)')\n    \nsubplot(6,2,11)\n        plot(log2(freqlist),bestfitmat,'.','markersize',20)\n        set(gca,'YTick',1:ndists)\n        set(gca,'YTickLabels',distnames)\n    LogScale('x',2);%LogScale('y',10)\n    xlabel('f (Hz)')\n    box off\n    \n    NiceSave('LFPPowerDist',figfolder,recname)\n\n\n\nend\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/analysis/lfp/bz_LFPPowerDist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5673774287523535}}
{"text": "function [error_x, error_y, fex, fey, ae] = stokespost_q1q1_p(q1q1sol,jmpx,jmpy,els,xy,ev)\n%stokespost_q1q1_p  computes Poisson error estimator for Q1-Q1 \n%   [err_x, err_y, fex, fey, ae] = stokespost_q1p0_p(q1q1sol,jmpx,jmpy,els,xy,ev);\n%   input\n%          q1q1sol        Q1-Q1 flow solution\n%          jmpx, jmpy     component elementwise edge stress jumps\n%          els            elementwise edge lengths\n%          xy             vertex coordinate vector  \n%          ev             element mapping matrix\n%   output\n%          err_x, err_y   component of velocity elementwise error estimate\n%          fex, fey       component elementwise rhs vectors\n%          ae             elementwise Poisson problem matrices\n%\n%   IFISS function: DJS; 8 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n      fprintf('computing local error estimator... ')\n      x=xy(:,1); y=xy(:,2);nvtx=length(x);\n      nel=length(ev(:,1));\n      error_x=zeros(nel,1);  error_y=zeros(nel,1);\n      psol=q1q1sol(2*nvtx+1:end);\n%\n% set up 3x3 Gauss points\n      gpt=sqrt(0.6); \n      s(1) = -gpt; t(1) = -gpt; wt(1)=25/81;\n      s(2) =  gpt; t(2) = -gpt; wt(2)=25/81;\n      s(3) =  gpt; t(3) =  gpt; wt(3)=25/81; \n      s(4) = -gpt; t(4) =  gpt; wt(4)=25/81;\n      s(5) =  0.0; t(5) = -gpt; wt(5)=40/81;\n      s(6) =  gpt; t(6) =  0.0; wt(6)=40/81;\n      s(7) =  0.0; t(7) =  gpt; wt(7)=40/81; \n      s(8) = -gpt; t(8) =  0.0; wt(8)=40/81;\n      s(9) =  0.0; t(9) =  0.0; wt(9)=64/81;\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        psol_v(:,ivtx) = psol(ev(:,ivtx));\n\t\tend\n        \n        ae = zeros(nel,5,5); elerrx=zeros(5,nel);  elerry=zeros(5,nel);\n        fex = zeros(nel,5); fey = zeros(nel,5);\n% loop over Gauss points\n         for igpt = 1:9\n         sigpt=s(igpt);\n         tigpt=t(igpt);\n         wght=wt(igpt);\n% evaluate derivatives etc\n         [jac_v,invjac_v,phi_v,dphidx_v,dphidy_v] = deriv(sigpt,tigpt,xl_v,yl_v);\n         [psi_v,dpsidx_v,dpsidy_v] = qderiv(sigpt,tigpt,xl_v,yl_v);\n         \n            for j = 1:5\n               for i = 1:5\n               ae(:,i,j) = ae(:,i,j)+wght*dpsidx_v(:,i+4).*dpsidx_v(:,j+4).*invjac_v(:);\n               ae(:,i,j) = ae(:,i,j)+wght*dpsidy_v(:,i+4).*dpsidy_v(:,j+4).*invjac_v(:);\n               end\n               for ss=1:4\n               fex(:,j) = fex(:,j)-wght*dphidx_v(:,ss).*psol_v(:,ss).*psi_v(:,j+4);\n               fey(:,j) = fey(:,j)-wght*dphidy_v(:,ss).*psol_v(:,ss).*psi_v(:,j+4);\n               end\n            end\n% end of Gauss point loop\n         end         \n%\n% include edge jumps (evaluated at the midpoint)\n         for ee = 1:4\n         fex(:,ee) = fex(:,ee) - jmpx(:,ee) .* els(:,ee)*(1/3);\n         fey(:,ee) = fey(:,ee) - jmpy(:,ee) .* els(:,ee)*(1/3);\n         end\n%\n% solve for local estimate\n         for ielem = 1:nel\n\t\t elerrx(:,ielem) = squeeze(ae(ielem,1:5,1:5))\\(fex(ielem,1:5)'); \n\t\t elerry(:,ielem) = squeeze(ae(ielem,1:5,1:5))\\(fey(ielem,1:5)'); \n\t     end\n%%\n         for ivtx=1:5, \n\t     error_x(:) = error_x(:) + fex(:,ivtx) .* elerrx(ivtx,:)';\n\t\t error_y(:) = error_y(:) + fey(:,ivtx) .* elerry(ivtx,:)';\n         end\n%%\t \n         fprintf('done.\\n')\t   \n\t\t 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/stokes_flow/stokespost_q1q1_p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5673774282295736}}
{"text": "% DEMOIL1 Oil data with fully independent training conditional.\n\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'oil';\nexperimentNo = 7;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('fitc');\noptions.optimiser = 'scg';\nlatentDim = 2;\nd = size(Y, 2);\noptions.kern = {'gibbs', 'bias', 'white'};\nmodel = fgplvmCreate(latentDim, d, Y, options);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\ncapName = dataSetName;;\ncapName(1) = upper(capName(1));\nsave(['dem' capName num2str(experimentNo) '.mat'], 'model');\n\nif exist('printDiagram') & printDiagram\n  fgplvmPrintPlot(model, lbls, capName, experimentNo);\nend\n\n\n% Load the results and display dynamically.\nfgplvmResultsDynamic(dataSetName, experimentNo, 'vector')\n\n% compute the nearest neighbours errors in latent space.\nerrors = fgplvmNearestNeighbour(model, lbls);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demOil7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5673774197879821}}
{"text": "function keep = newtonpolytope(exponent_m,exponent_p)\n%NEWTONPOLYTOPE  Internal function to remove monimials in SOS programs using Newton polytope\n\n% WARNING : THIS CODE SUCKS AND IS ONLY USED AS A BACK UP PLAN \n% IF EVERYTHING ELSE FAILS (CRASHING LP SOLVERS ETC)\n\n% *************************************\n% TRY TO CALCULATE CONVEX HULL\n% *************************************\ntry\n    cnvhull = convhulln(full(exponent_p));\ncatch\n    keep = 1:size(exponent_m,1);\n    return\nend\n\n% ***************************************\n% GET THE UNIQUE POINTS OF IN CONVEX HULL\n% ***************************************\nunique_points = unique(cnvhull);\n\n% ***************************************\n% CALCULATE A POINT IN INTERIOR\n% ***************************************\np_c = sum(exponent_p(unique_points,:),1)'/length(unique_points);\n\n% ***************************************\n% CALCULATE HYPER-PLANES Ai^T(x-bi)=0\n% ***************************************\nj = 1;\nA = [];\nfor i = 1:size(cnvhull,1)\n    X = exponent_p(cnvhull(i,:),:)';\n    y = X(:,1);\n    dX = X(:,2:end)-repmat(X(:,1),1,size(X,2)-1);\n    Atemp = null(full(dX'));\n    % Is this a full-dimensional facet\n    if size(Atemp,2)==1\n        direction = (p_c-y)'*Atemp;\n        if direction > 0\n           A{j}=-Atemp;\n       else\n           A{j}=Atemp;\n       end\n        b{j}=y;  \n        j=j+1;\n    end\nend\n\n% ***************************************\n% CHECK IF MONOMIAL IS IN NEWTON POLYTOPE\n% ***************************************\nif ~isempty(A)\n    keep = [];\n    for j = 1:size(exponent_m,1)\n        inside = 1;\n        y = exponent_m(j,:)';\n        if isempty(findrows(exponent_p,y)) % Numerically safe on border\n            i = 1;\n            while inside & (i<=length(A))\n                inside = inside & ((A{i}'*(y-b{i}))<=1e-9);\n                i = i+1;\n            end\n        end\n        if inside\n            keep = [keep j];\n        end\n    end\nelse\n    keep = 1:size(exponent_m,1);\nend\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/sos/newtonpolytope.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5673774065899645}}
{"text": "function res = project_t(pts, H)\n%% apply projective transformation H on points pts\n%% pts, n x 2\n%% H, 3 x 3\n%% res, n x 2\n\npts = [pts, ones(size(pts, 1), 1)];\nres = H * pts';\nres = [ res(1,:)./res(3,:); res(2,:)./res(3,:) ];\nres = res';\n", "meta": {"author": "flyers", "repo": "drone-tracking", "sha": "c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad", "save_path": "github-repos/MATLAB/flyers-drone-tracking", "path": "github-repos/MATLAB/flyers-drone-tracking/drone-tracking-c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad/util/project_t.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5673678429432738}}
{"text": "function plot_R_cov(Sigma_R_stat, cov_R, Rs)\nLies = dcm2Lie(Rs).';\nmean_Lie = mean(Lies, 2);\ncolors = linspecer(3);\nsubplot(2, 2, 1);\nplot_cov_linestyle(Sigma_R_stat, {'--', 3, colors(1, :)}, cov_R, {'-', 2, colors(3, :)}, Lies, mean_Lie, '.', 1, 2, 3, 10.5);\nxlabel('$\\xi_1$', 'Interpreter', 'LaTeX', 'FontSize', 15);\nylabel('$\\xi_2$', 'Interpreter', 'LaTeX', 'FontSize', 15);\n\nsubplot(2, 2, 2);\nplot_cov_linestyle(Sigma_R_stat, {'--', 3, colors(1, :)}, cov_R, {'-', 2, colors(3, :)}, Lies, mean_Lie, '.', 1, 3, 3, 10.5);\nxlabel('$\\xi_1$', 'Interpreter', 'LaTeX', 'FontSize', 15);\nylabel('$\\xi_3$', 'Interpreter', 'LaTeX', 'FontSize', 15);\n\nsubplot(2, 2, 4);\nplot_cov_linestyle(Sigma_R_stat, {'--', 3, colors(1, :)}, cov_R, {'-', 2, colors(3, :)}, Lies, mean_Lie, '.', 2, 3, 3, 10.5);\nxlabel('$\\xi_2$', 'Interpreter', 'LaTeX', 'FontSize', 15);\nylabel('$\\xi_3$', 'Interpreter', 'LaTeX', 'FontSize', 15);\n\nlegend({'Stat Covariance', 'Data Points', 'Nguyen et al. Covariance'}, 'Interpreter', 'LaTeX', 'FontSize', 15);\n\nSigma_Lie_stat = covx(Lies.', Lies.')\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/utils/plot_R_cov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5673678418358544}}
{"text": "function out = normest(f)\n%NORMEST   Estimate the norm of a SINGFUN.\n%   NORMEST(F) returns the NORMEST of the smooth part of a SINGFUN F. Since the \n%   function value of a SINGFUN is infinite at -1 and 1 in most of the cases due\n%   to the pole(s), NORMEST turn the estimated norm of the smooth part of F.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\n% Call NORMEST() of the smooth part:\nout = normest(f.smoothPart);\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/@singfun/normest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.5673678366948507}}
{"text": "function e = prtRvUtilDiscreteEntropy(q)\n% DISCRETEENTROPY\n\n\n\n\n\n\n\ne = q.*log(q);\ne(q==0) = 0;\ne = sum(e(:));\n\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/rv/util/prtRvUtilDiscreteEntropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5673678337686847}}
{"text": "% Script to reproduce the experiments leading to the results provided in the\n% Table 2 of the paper \"Deep Scattering Spectrum\" by J. And\u00e9n and S. Mallat.\n\n% Delta-Delta-MFCCs for window size 370 ms\n\nrun_name = 'DSS_Table2_GTZAN_mfcc_370ms';\n\nN = 5*2^17;\n\nsrc = gtzan_src('/path/to/gtzan');\n\nfilt1_opt.wavelet_type = {'gabor','morlet'};\nfilt1_opt.Q = [8 2];\nfilt1_opt.J = T_to_J(8192,filt1_opt);\nfilt1_opt.boundary = 'symm';\n\nsc1_opt.M = 1;\n\nfilters = filter_bank(N, filt1_opt);\n\nfeatures = {@(x)(feval(@(x)([x; circshift(x,[0 +1]); circshift(x,[0 -1])]), ...\n\tformat_scat(log_scat(spec_freq_average(x,filters,sc1_opt)))))};\n\ndb = prepare_database(src,features);\ndb.features = single(db.features);\ndb = svm_calc_kernel(db,'gaussian','square',1:2:size(db.features,2));\n\nrs = RandStream.create('mt19937ar','Seed',floor(pi*1e9));\nRandStream.setGlobalStream(rs);\n[train_set{1}, test_set{1}] = create_partition([src.objects.class], 0.9);\nfor k = 2:10\n\t[train_set{k}, test_set{k}] = ...\n\t\tnext_fold([src.objects.class], train_set{k-1}, test_set{k-1});\nend\n\noptt.kernel_type = 'gaussian';\noptt.C = 2.^[0:4:8];\noptt.gamma = 2.^[-16:4:-8];\noptt.search_depth = 3;\noptt.full_test_kernel = 1;\n\nfor k = 1:10\n\t[dev_err_grid,C_grid,gamma_grid] = ...\n\t\tsvm_adaptive_param_search(db,train_set{k},[],optt);\n\n\t[dev_err(k),ind] = min(mean(dev_err_grid{end},2));\n\tC(k) = C_grid{end}(ind);\n\tgamma(k) = gamma_grid{end}(ind);\n\n\toptt1 = optt;\n\toptt1.C = C(k);\n\toptt1.gamma = gamma(k);\n\n\tmodel = svm_train(db,train_set{k},optt1);\n\tlabels(:,k) = svm_test(db,model,test_set{k});\n\terr(k) = classif_err(labels(:,k),test_set{k},db.src);\n\n\tfprintf('dev err = %f, test err = %f\\n',dev_err(k),err(k));\n\n\tsave([run_name '.mat'],'labels','dev_err','err','C','gamma');\nend\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_Table2_GTZAN_mfcc_370ms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5673332644051282}}
{"text": "function FR = FbApply2d( I, FB, shape, show )\n% Applies each of the filters in the filterbank FB to the image I.\n%\n% To apply to a stack of images:\n%  IFS = fevalArrays( images, @FbApply2d, FB, 'valid' );\n%\n% USAGE\n%  FR = FbApply2d( I, FB, [shape], [show] )\n%\n% INPUTS\n%  I       - 2D input array\n%  FB      - filterbank - MxNxK set of K filters each of size MxN\n%  shape   - ['full'] option for conv2 'full', 'same', 'valid'\n%  show    - [0] first figure to use for optional display\n%\n% OUTPUTS\n%  FR      - 3D set of filtered images\n%\n% EXAMPLE\n%  load trees;  X=imresize(X,.5);  load FbDoG.mat;\n%  FR = FbApply2d( X, FB, 'same', 1 );\n%\n% See also CONV2, FBMAKE\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<3 || isempty(shape)); shape = 'full'; end\nif( nargin<4 || isempty(show)); show=0; end\n\nnd=ndims(I);  ndf=ndims(FB);  nf=size(FB,3);\nif( nd~=2  ); error('I must be an MxN array'); end\nif( ndf~=2 && ndf~=3 ); error('FB must be an MxN or MxNxK array'); end\nif( ~isa(I,'double')); I = double(I); end\n\n% apply each filter to image\nif( ndf==2 )\n  FR = conv2( I, FB, shape );\nelse\n  FR = repmat( conv2(I,FB(:,:,1),shape), [1 1 nf] );\n  for i=2:nf; FR(:,:,i)=conv2(I,FB(:,:,i),shape); end\nend\n\n% optionally display\nif( show )\n  figure(show); im(I);\n  figure(show+1); montage2(FB,struct('extraInfo',1));\n  figure(show+2); montage2(FR,struct('extraInfo',1));\nend\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SketchTokens-master/toolbox/filters/FbApply2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5673287699694007}}
{"text": "clc;\nclose all;\nclearvars;\n\nn = 800000;\nk = 100;\ntrials = 100;\n\nsort_elapsed = 0;\nquickselect_elapsed = 0;\nfor i=1:trials\n    data = -randperm(n);\n    tstart = tic;\n    sort(data);\n    sort_elapsed = sort_elapsed + toc(tstart);\n    tstart = tic;\n    y = spx.fast.quickselect(data, k);\n    quickselect_elapsed = quickselect_elapsed + toc(tstart);\n    fprintf('%d  %d\\n', y(k), sum (y(1:k) < -k));\nend\n\n\nt1 = sort_elapsed;\nt2 = quickselect_elapsed;\ngain_x = t1 / t2;\n\nfprintf('Sort: %.2f sec, quickselect: %.2f sec, Gain: %.2f\\n', t1, t2, gain_x);\n\n\n\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/experiments/quickselect/quickselect_vs_sort_speed_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5673287672718541}}
{"text": "function [zPred, PzPred,otherInfo]=cubKalMeasPred(xPred,PPred,zDim,h,xi,w,innovTrans,measAvgFun,stateDiffTrans,stateTrans)\n%%CUBKALMEASPRED Perform the measurement prediction part of the measurement\n%           update step of the cubature Kalman filter with additive\n%           measurement noise. The function cubKalUpdateWithPred can be\n%           used to complete the measurement update. Separating the\n%           measurement prediction step from the rest of the update step\n%           can make the creation of multiple measurement association\n%           hypotheses from a single target prediction more efficient.\n%           The full measurement update function is cubKalUpdate.\n%\n%INPUTS: xPred The xDimXnumComp predicted target states.\n%        PPred The xDimXxDimXnumComp predicted state covariance matrices. \n%         zDim The dimensionality of the output of h.\n%            h A function handle for the measurement function that takes\n%              the state as its argument.\n%           xi An xDimXnumCubPoints matrix of cubature points. If this\n%              and the next parameter are omitted or empty matrices are\n%              passed, then fifthOrderCubPoints(xDim) is used. It is \n%              suggested that xi and w be provided to avoid needless\n%              recomputation of the cubature points.\n%            w A numCubPointsX1 vector of the weights associated with the\n%              cubature points.\n%   innovTrans An optional function handle that computes and optionally\n%              transforms the value of the difference between the\n%              observation and any predicted points. This is called as\n%              innovTrans(a,b) and the default if omitted or an empty\n%              matrix is passed is @(a,b)bsxfun(@minus,a,b). This must be\n%              able to handle sets of values. For a zDimX1 measurement,\n%              either of the inputs could be zDimXN in size while one of\n%              the inputs could be zDimX1 in size.  This only needs to be\n%              supplied when a measurement difference must be restricted\n%              to a certain range. For example, the innovation between two\n%              angles will be 2*pi if one angle is zero and the other\n%              2*pi, even though they are the same direction. In such an\n%              instance, a function handle to the\n%              wrapRange(bsxfun(@minus,a,b),-pi,pi) function with the\n%              appropriate parameters should be passed for innovTrans.\n%   measAvgFun An optional function handle that, when given N measurement\n%              values with weights, produces the weighted average. This\n%              function only has to be provided if the domain of the\n%              measurement is not linear. For example, when averaging\n%              angular values, then the function meanAng should be used.\n% stateDiffTrans An optional function handle that takes an xDimXN matrix of\n%              N differences between states and transforms them however\n%              might be necessary. If not transformation is necessary, this\n%              parameter can be omitted or an empty matrix passed.\n%   stateTrans An optional function that takes a state estimate and\n%              transforms it. This is useful if one wishes the elements of\n%              the state to be bound to a certain domain. For example, if\n%              an element of the state is an angle, one might generally\n%              want to bind it to the region +/-pi.\n%\n%OUTPUTS: zPred The zDimXnumComp measurement predictions from the filter.\n%        PzPred The zDimXzDimXnumComp covariance matrices associated with\n%               zPred.\n%     otherInfo A structure containing members of intermediate results of\n%               this function that can be passed to cubKalUpdateWithPred\n%               when updating with a measurement.\n%\n%The mathematics behind the cubature Kalman filter are described in more\n%detail in Section IX of [1] and in [2]. See the comments to cubKalUpdate\n%for more information.\n%\n%EXAMPLE:\n%With this example, we demonstrate that one gets the same result using\n%cubKalUpdate in one step as with using cubKalMeasPred followed by\n%cubKalUpdateWithPred.\n% xPred=[1e3;-2e3;100;200];\n% h=@(x)([sum(x.^2);x(1)-x(4)^(3/2)]);\n% PPred=[28,   3.5,    6,  8.5;\n%      3.5,    23,  8.5,   11;\n%        6,   8.5,   18, 13.5;\n%      8.5,    11, 13.5,   13];\n% z=1e6*[5.050000548964568;\n%       -0.001829553054023];\n% zDim=size(z,1);\n% R=eye(zDim,zDim);%Measurement covariance matrix.\n% %The update in one step.\n% [xUpdate,PUpdate,innov,Pzz,W]=cubKalUpdate(xPred,PPred,z,R,h);\n% %The update in two steps.\n% [zPred, PzPred,otherInfo]=cubKalMeasPred(xPred,PPred,zDim,h);\n% [xUpdate1,PUpdate1,innov1,Pzz1,W1]=cubKalUpdateWithPred(z,R,zPred,PzPred,otherInfo);\n% %One will see that the one and two step updates agree.\n% max(abs([xUpdate1-xUpdate;PUpdate1(:)-PUpdate(:);innov1(:)-innov;Pzz1(:)-Pzz(:);W1(:)-W(:)]))\n%\n%REFERENCES:\n%[1] D. F. Crouse , \"Basic tracking using nonlinear 3D monostatic and\n%    bistatic measurements,\" IEEE Aerospace and Electronic Systems Magazine,\n%    vol. 29, no. 8, Part II, pp. 4-53, Aug. 2014.\n%[2] I. Arasaratnam and S. Haykin, \"Cubature Kalman filters,\" IEEE\n%    Transactions on Automatic Control, vol. 54, no. 6, pp. 1254-1269,\n%    Jun. 2009.\n%\n%June 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n    xDim=size(xPred,1);\n    numComp=size(xPred,2);\n\n    if(nargin<5||isempty(xi))\n        [xi,w]=fifthOrderCubPoints(xDim);\n    end\n\n    if(nargin<7||isempty(innovTrans))\n        %The function just returns the input.\n        innovTrans=@(a,b)bsxfun(@minus,a,b);\n    end\n    \n    if(nargin<8||isempty(measAvgFun))\n        measAvgFun=@(zPoints,w)calcMixtureMoments(zPoints,w);\n    end\n\n    if(nargin<9||isempty(stateDiffTrans))\n        stateDiffTrans=@(x)x; \n    end\n    \n    if(nargin<10||isempty(stateTrans))\n        stateTrans=@(x)x; \n    end\n\n    numCubPoints=size(xi,2);\n    \n    zPred=zeros(zDim,numComp);\n    PzPred=zeros(zDim,zDim,numComp);\n    xPredCenPoints=zeros(xDim,numCubPoints,numComp);\n    zPredCenPoints=zeros(zDim,numCubPoints,numComp);\n    Pxz=zeros(xDim,zDim,numComp);\n    \n    for k=1:numComp\n        %cholSemiDef is used instead of chol in case a positive semi-definite\n        %covariance matrix is passed.\n        SPred=cholSemiDef(PPred,'lower');\n        %Predicted cubature state points\n        xPredPoints=stateTrans(transformCubPoints(xi,xPred,SPred));\n\n        %Predicted cubature measurement points\n        zPredPoints=zeros(zDim,numCubPoints);\n        for curP=1:numCubPoints\n            zPredPoints(:,curP)=h(xPredPoints(:,curP));\n        end\n\n        %Measurement prediction.\n        zPred=measAvgFun(zPredPoints,w);\n\n        %Centered, predicted cubature measurement points, transformed as\n        %necessary to keep the values within a desired range.\n        zPredCenPoints(:,:,k)=innovTrans(zPredPoints,zPred);\n        xPredCenPoints(:,:,k)=stateDiffTrans(bsxfun(@minus,xPredPoints,xPred));\n        for curP=1:numCubPoints\n            diff=zPredCenPoints(:,curP);\n            PzPred(:,:,k)=PzPred(:,:,k)+w(curP)*(diff*diff');\n            Pxz(:,:,k)=Pxz(:,:,k)+w(curP)*xPredCenPoints(:,curP)*diff';\n        end\n        %Pxz is not needed for the measurement prediction, but we compute it\n        %here, so that it need not be recomputed again and again if\n        %cubKalUpdateWithPred is called for multiple measurements.\n    end\n    \n    otherInfo.innovTrans=innovTrans;\n    otherInfo.stateDiffTrans=stateDiffTrans;\n    otherInfo.stateTrans=stateTrans;\n    otherInfo.xPredCenPoints=xPredCenPoints;\n    otherInfo.zPredCenPoints=zPredCenPoints;\n    otherInfo.xPred=xPred;\n    otherInfo.w=w;\n    otherInfo.Pxz=Pxz;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Estimation/Measurement_Update/Update_Parts/Filter_Measurement_Prediction/cubKalMeasPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5673164307940199}}
{"text": "%{\nAuthors:\nJonatas Lopes de Paiva\nClaudio Fabiano Motta Toledo\nHelio Pedrini\n\n%}\n\nfunction g = mutation(img)\n\nr = randi(3);\n\nswitch r\n    \n    case 1\n        tmp = double(img);\n        rate = 0.7 + 0.6*rand;\n        i = rate*tmp;\n        i = floor(i + 0.5);\n    case 2\n        t = getFilterSize(2);\n        sigma = rand * 5 + 0.05;\n        h = fspecial('gaussian', t, sigma);\n    case 3\n        t = getFilterSize(2);\n        h = fspecial('average', t);        \n        \nend\n\nif (r ==2 || r == 3)\n    i = imfilter(img, h);\nend\n\ng = uint8(i);\n\nend\n\nfunction s = getFilterSize(maxSize)\nn = randi(maxSize);\n\ns = 2*n+1;\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u53bb\u566a\u7b97\u6cd5/hga_image_denoising-master/code/mutation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5673164140074924}}
{"text": "function [nstate] = tapas_sampler_mixedlinear_gibbs_node(data, model, ...\n    inference, state, node)\n%% Samples from a linear multivariate model with fixed and random effects\n% and a diagonal covariance matrix.\n%\n% Input \n%\n% Output\n%\n% This level assumes only and unknown mean with known variance for some the\n% the elements. The input matrix is required to be simple a weighting of \n% prior and mean. \n%\n\n% aponteeduardo@gmail.com\n% copyright (C) 2016\n%\n\nnstate = state;\n\n% Number of subjects and number of chains\n[ns, nc] = size(state.graph{node - 1}.y);\n\n% Number of parameters\nnp = size(state.graph{node}.y{1}.mu, 2);\n\n% Number of regressors\nnr = size(state.graph{node}.y{1}.mu, 1);\n\n% First store the values somewhere\n\nfor i = 1:nc\n    % Get all the parameters at a given temperature\n    iy = state.graph{node - 1}.y{i}.mu;\n    \n    % Get the grouping of the random variables.\n    x = state.graph{node - 1}.u.x;\n    \n    % The number of groups is equal to size(x, 2). The ones in a column\n    % encode membership to a code. size(x, 1) should be np;\n\n    % Number of groups\n    ng = size(x, 2); \n    \n    for j = 1:ng\n        % Group \n        gv = logical(x(:, j));\n        ngv = sum(gv);\n        % Group mean\n        gmu = sum(iy(gv, :), 1) .* state.graph{node - 1}.y{i}.pe;\n        gmu = gmu + state.graph{node + 1}.y{i}.pe(j, :) .* ...\n            state.graph{node + 1}.y{i}.mu(j, :); % 1 x np\n\n        % Group precision\n        gpe = ngv * state.graph{node - 1}.y{i}.pe + ...\n            state.graph{node + 1}.y{i}.pe(j, :);\n\n        % Sample using Gibbs\n        gmu = gmu./gpe;\n        gmu = gmu + sqrt(1./ gpe) .* randn(1, np);\n\n        % Replicate for all the correspondign regressors.\n        nstate.graph{node}.y{i}.mu(gv, :) = repmat(gmu, ngv, 1);\n    end\nend\n\n% Don't need it\n%nstate.llh{node} = model.graph{node}.llh(nstate.graph{node}, ...\n%    nstate.graph{node + 1}, model.graph{node}.htheta);\n%\n%nstate.llh{node - 1} = model.graph{node - 1}.llh(...\n%    nstate.graph{node - 1}, nstate.graph{node}, model.graph{node - 1}.htheta);\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/tools/ti/linear/tapas_sampler_mixedlinear_gibbs_node.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5673164086406565}}
{"text": "function [MPa] = dynpcm22MPa(dynpcm2)\n% Convert pressure from dynes per square centimeter to megapascals\n% Chad Greene 2012\nMPa = dynpcm2*1.00000e-7;", "meta": {"author": "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/dynpcm22MPa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5673164082976462}}
{"text": "function [tt] = move_tt_block(tt, spos, epos, eps)\n%Performs a bubble movement of a block inside a train\n%   [TT] = MOVE_TT_BLOCK(TT, SPOS, EPOS, EPOS) Performs the bubble movement\n%   of the SPOS-th block to the position EPOS, the intermediate blocks\n%   shift to the vacant places, i.e. by (-1) if spos<eps, and +1,\n%   otherwise. Requires truncation with the L2-norm accuracy EPSs\n%\n%\n% TT-Toolbox 2.2, 2009-2012\n%\n%This is TT Toolbox, written by Ivan Oseledets et. al.\n%Institute of Numerical Mathematics, Moscow, Russia\n%webpage: http://spring.inm.ras.ru/osel\n%\n%For all questions, bugs and suggestions please mail\n%ivan.oseledets@gmail.com\n%---------------------------\n\nif (spos==epos)\n    return;\nend;\n\nd = tt.d;\nn = tt.n;\nr = tt.r;\n\n% QR to spos\nfor i=1:spos-1\n    cr = reshape(tt{i}, r(i)*n(i), r(i+1));\n    [cr, rv]=qr(cr, 0);\n    cr2 = reshape(tt{i+1}, r(i+1), n(i+1)*r(i+2));\n    cr2 = rv*cr2;\n    r(i+1) = size(cr, 2);\n    tt{i} = reshape(cr, r(i), n(i), r(i+1));\n    tt{i+1} = reshape(cr2, r(i+1), n(i+1), r(i+2));\nend;\nfor i=d:-1:spos+1\n    cr = reshape(tt{i}, r(i), n(i)*r(i+1));\n    [cr, rv]=qr(cr.', 0);\n    cr2 = reshape(tt{i-1}, r(i-1)*n(i-1), r(i));\n    cr2 = cr2*(rv.');\n    r(i) = size(cr, 2);\n    tt{i} = reshape(cr.', r(i), n(i), r(i+1));\n    tt{i-1} = reshape(cr2, r(i-1), n(i-1), r(i));\nend;\n\n% Now, start permutation\nif (spos<epos) % From left to right  \n    for i=spos:epos-1\n        cr1 = reshape(tt{i}, r(i)*n(i), r(i+1));\n        cr2 = reshape(tt{i+1}, r(i+1), n(i+1)*r(i+2));\n        cr = cr1*cr2;\n        cr = reshape(cr, r(i), n(i), n(i+1), r(i+2));\n        cr = permute(cr, [1, 3, 2, 4]);\n        tempvar = n(i); n(i) = n(i+1); n(i+1) = tempvar;\n        cr = reshape(cr, r(i)*n(i), n(i+1)*r(i+2));\n        [u,s,v]=svd(cr, 'econ');\n        s = diag(s);\n        nrm = norm(s);\n        r(i+1) = my_chop2(s, eps*nrm/sqrt(d-1));\n        tt{i} = reshape(u(:,1:r(i+1)), r(i), n(i), r(i+1));\n        v = diag(s(1:r(i+1)))*(v(:,1:r(i+1))');\n        tt{i+1} = reshape(v, r(i+1), n(i+1), r(i+2));\n    end;\nend;\n\nif (epos<spos) % From right  to left\n    for i=spos:-1:epos+1\n        cr1 = reshape(tt{i}, r(i), n(i)*r(i+1));\n        cr2 = reshape(tt{i-1}, r(i-1)*n(i-1), r(i));\n        cr = cr2*cr1;\n        cr = reshape(cr, r(i-1), n(i-1), n(i), r(i+1));\n        cr = permute(cr, [1, 3, 2, 4]);\n        tempvar = n(i); n(i) = n(i-1); n(i-1) = tempvar;\n        cr = reshape(cr, r(i-1)*n(i-1), n(i)*r(i+1));\n        [u,s,v]=svd(cr, 'econ');\n        s = diag(s);\n        nrm = norm(s);\n        r(i) = my_chop2(s, eps*nrm/sqrt(d-1));\n        tt{i} = reshape(v(:,1:r(i))', r(i), n(i), r(i+1));\n        u = u(:,1:r(i))*diag(s(1:r(i)));\n        tt{i-1} = reshape(u, r(i-1), n(i-1), r(i));\n    end;\nend;\n\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/core/move_tt_block.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430311279742, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5673164025877999}}
{"text": "function [ varargout ] = TrimmedICP(Md, MovData, RefData, Tf0, MaxIter,TrMin,TrMax,lamda)\nif nargin == 0\n    clc; close all;\n    %load ../../StanfordData/bunny;\n    RefData = rand(3, 100); %bunny{1}';\n    MovData = rand(3, 100);% bunny{2}';\n    Md = createns(RefData');\n    Tf0 = [eye(3) zeros(3, 1)]; \n    MaxIter = 50; \n    TrMin = 0.35; \n    TrMax = 1.0; \n    lamda = 2.0; \nend\nDim = size(MovData, 1); \nPreMSE= 10^5;   CurMSE= 10^6;  Iter = 1; \nRelErr = 1.0;\nR0 = Tf0(1:Dim, 1:Dim); \nT0 = Tf0(1:Dim, end); \nTf = [R0 T0; zeros(1, Dim) 1 ]; \nfor Iter = 1 : 1 : MaxIter       % (abs(CurMSE-PreMSE)>10^(-9))   % this threshold is sensitive to resolutions....for bunny, this value should be 1e-12.\n    TData = Loc2Glo(MovData, Tf(1:Dim, 1:Dim)', Tf(1:Dim, end) );\n    [corr,TD] = knnsearch( Md,TData(1:Dim, :)');\n    SortTD2 = sortrows(TD.^2); % Sort the correspongding points\n    minTDIndex = floor(TrMin*length(TD)); % Get minimum index of TD\n    maxTDIndex = ceil(TrMax*length(TD)); % Get maxmum index of TD    \n    TDIndex = [minTDIndex : maxTDIndex]';\n    mTr = TDIndex./length(TD);\n    mCumTD2 = cumsum(SortTD2);\n    mMSE = mCumTD2(minTDIndex : maxTDIndex)./TDIndex;\n    mPhi = ObjectiveFunction(mMSE, mTr);  \n    PreMSE=CurMSE;\n    [CurMSE, nIndex] = min(mPhi);    \n    Trim = mTr(nIndex); % Update Tr for next step    \n    corr(:,2) = [1 : length(corr)]';\n    % Sort the corresponding points\n    corrTD = [corr, TD];\n    SortCorrTD = sortrows(corrTD, 3);\n    \n    TrLength = floor(Trim*size(SortCorrTD,1)); % The number of corresponding points after trimming\n    TCorr = SortCorrTD(1:TrLength, 1:2);     % Trim the corresponding points according to overlap parameter Tr\n    % Register MData with TData\n    dM = RegFun(RefData(:, TCorr(:, 1)), TData(:, TCorr(:, 2)) ); \n    % dM = reg(RefData, TData, TCorr);\n    Tf = dM * Tf; \n    % [M, TCorr, scan] = CalRtPhi(model, data, SortCorrTD, Trim);\n    Err = [norm(dM(1:Dim, 1:Dim)-eye(Dim)) norm(dM(1:Dim, end))];\n    if max(Err) <= 1e-5\n        break;\n    end\n    RelErr = (PreMSE - CurMSE) / abs(PreMSE); \n    if abs(RelErr) <= 1e-3\n        break; \n    end\nend\nIS_SHOW = 0;\nif IS_SHOW\n    Res = CalRes(MovData); \n    h = figure; \n    ICP_PlotFun(MovData, RefData, Tf, Res, h); \n    title('Trimmed ICP');\nend;\nif nargout == 1\n    varargout{1} = Tf; \nend\nif nargout == 2 \n    varargout{1} = Tf(1:Dim, 1:Dim); \n    varargout{2} = Tf(1:Dim, end); \nend\nbTest = 1; \n\nend\n\n%%%%%%%%%%%%%%%%%%%%Integrated Function%%%%%%%%%%%%%%%%%%%%\n% %% Calculate R,t,Phi based on current overlap parameter\n% function [M,TCorr,TData] = CalRtPhi(Model, scan, SortCorrTD,Tr)\n% \n% TrLength = floor(Tr*size(SortCorrTD,1)); % The number of corresponding points after trimming\n% TCorr = SortCorrTD(1:TrLength, 1:2);     % Trim the corresponding points according to overlap parameter Tr\n% % Register MData with TData\n% [M] = reg(Model(1:3,:), scan(1:3,:), TCorr);\n% % To obtain the transformation data\n% TData = M*scan;\n% \n% end\n% \n% function [M,TCorr,TData] = CalRtPhi(Model, scan, SortCorrTD,Tr)\n% \n% TrLength = floor(Tr*size(SortCorrTD,1)); % The number of corresponding points after trimming\n% TCorr = SortCorrTD(1:TrLength, 1:2);     % Trim the corresponding points according to overlap parameter Tr\n% % Register MData with TData\n% [M] = reg(Model(1:3,:), scan(1:3,:), TCorr);\n% % To obtain the transformation data\n% TData = M*scan;\n% \n% end\n%%%%%%%%%%%%%%% Calculate the registration matrix %%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%% T(TData)->MData %%%%%%%%%%%%%%%%%%%%%%%%%\n% SVD solution\nfunction [M] = reg(Model, Data, corr)\n\nn = length(corr); \nM = Model(:,corr(:,1)); \nmm = mean(M,2);\nS = Data(:,corr(:,2));\nms = mean(S,2); \nSshifted = [S(1,:)-ms(1); S(2,:)-ms(2); S(3,:)-ms(3)];\nMshifted = [M(1,:)-mm(1); M(2,:)-mm(2); M(3,:)-mm(3)];\nK = Sshifted*Mshifted';\nK = K/n;\n[U A V] = svd(K);\nR1 = V*U';\nif det(R1)<0\n    B = eye(3);\n    B(3,3) = det(V*U');\n    R1 = V*B*U';\nend\nt1 = mm - R1*ms;\nM=[];\nM(1:3,1:3)=R1;\nM(1:3,4)=t1;\nM(4,:)=[0,0,0,1];\nend\n\nfunction [Phi] = ObjectiveFunction(MSE, TrB)\nlamga= 2;\nPhi = MSE./((TrB).^((1+lamga)));\nend\n\n\n", "meta": {"author": "DrGabor", "repo": "LiDAR", "sha": "707ca635db955cf00d833578ad1236f0790cdf98", "save_path": "github-repos/MATLAB/DrGabor-LiDAR", "path": "github-repos/MATLAB/DrGabor-LiDAR/LiDAR-707ca635db955cf00d833578ad1236f0790cdf98/CommonFunctions/TrimmedICP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5673164025877998}}
{"text": "function [Rot,v,x,PosAmers,P] = iekfPropagation(dt,Rot,v,x,omega_b,a_b,...\n    PosAmers,P,omega,acc,Q,g)\nNbAmers = size(PosAmers,2);\n\n% state propagation\nRot = Rot*expSO3((omega-omega_b)*dt);\nv = v+(Rot*(acc-a_b)+g)*dt;\nx = x+v*dt;\n\n% covariance propagation\nF = eye(size(P));\nF(4:6,1:3) = vecto(g)*dt;\nF(7:9,1:3) = vecto(g)*dt*dt;\nF(7:9,4:6) = eye(3)*dt;\nF(1:3,10:12) = -Rot*dt;\nF(4:6,10:12) = -vecto(v)*Rot*dt;\nF(7:9,10:12) = -vecto(x)*Rot*dt;\nfor i = 1:NbAmers\n    posAmers_i = PosAmers(:,i);\n    F(13+3*i:15+3*i,10:12) = -vecto(posAmers_i)*Rot*dt;\nend\nF(4:6,13:15) = -Rot*dt;\nF(7:9,13:15) = -Rot*dt*dt;\n\nG = zeros(size(P,1),size(Q,1));\nG(1:3,1:3) = Rot;\nG(4:6,1:3) = vecto(v)*Rot;\nG(7:9,1:3) = vecto(x)*Rot;\nG(4:6,4:6) = Rot;\nG(7:9,4:6) = Rot*dt;\nG(10:15,7:12) = eye(6);\nG(1:3,7:9) = Rot*dt;\nG(4:6,7:9) = vecto(v)*Rot*dt*dt;\nG(7:9,7:9) = vecto(x)*Rot*dt*dt*dt;\nG(4:6,10:12) = Rot*dt*dt;\nG(7:9,10:12) = Rot*dt*dt*dt;\n\nP = F*P*F' + G*(Q*dt)*G'*dt;\nend\n", "meta": {"author": "mbrossar", "repo": "FUSION2018", "sha": "ff97d009d80151b2ce2b2c62ffe792a90e1ed7de", "save_path": "github-repos/MATLAB/mbrossar-FUSION2018", "path": "github-repos/MATLAB/mbrossar-FUSION2018/FUSION2018-ff97d009d80151b2ce2b2c62ffe792a90e1ed7de/filters/iekfPropagation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.5672621309013909}}
{"text": "function layer = genNetworkLSTM(para)\nif isfield(para, 'LastActivation4MSE')==0\n    para.LastActivation4MSE = 'linear';\nend\n\nlayer{1}.name = 'Input';        % this is an input layer\nlayer{end}.inputIdx = 1;    % specifies the index of GCC in Visible_tr\nlayer{end}.dim = [1 1]*double(para.inputDim);             % [input dim; output dim];\n\nif isfield(para, 'ProjectionSize') &&  ~isempty(para.ProjectionSize) && para.ProjectionSize>0\n    layer{end+1}.name = 'Affine';\n    layer{end}.prev = -1;\n    layer{end}.W = [];\n    layer{end}.b = [];\n    layer{end}.dim = [para.ProjectionSize layer{end-1}.dim(1)];\n    layer{end}.update = 1;\nend\n\nfor i=1:length(para.hiddenLayerSizeLSTM)\n    layer{end+1}.name = 'LSTM';\n    layer{end}.prev = -1;   % this is the index of GCC features in Visible_tr; It is the offset to be added to current layer index\n    layer{end}.W = []; % to be initialized randomly or by pretraining\n    layer{end}.b = [];\n    layer{end}.usePastState = para.usePastState(i);\n    layer{end}.dim = [para.hiddenLayerSizeLSTM(i) layer{end-1}.dim(1)];\n    layer{end}.update = 1;\n    \n    if isfield(para, 'useAffineBtwLSTM') && para.useAffineBtwLSTM && i<length(para.hiddenLayerSizeLSTM)\n        layer{end+1}.name = 'Affine';\n        layer{end}.prev = -1;\n        layer{end}.W = [];\n        layer{end}.b = [];\n        layer{end}.dim = [1 1] * layer{end-1}.dim(1);\n        layer{end}.update = 1;\n    end\nend\n\nlayer2 = genNetworkFeedForward_v2(layer{end}.dim(1), para.hiddenLayerSizeFF, para.outputDim, para.costFn, para.LastActivation4MSE);\n\nlayer = [layer layer2(2:end)];\n\nif isfield(para, 'labelDelay')\n    layer{end}.labelDelay = para.labelDelay;\nend\nif isfield(para, 'costFrameSelection');\n    layer{end}.costFrameSelection = para.costFrameSelection;\nend\n\nlayer = FinishLayer(layer);\nend\n\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/prototypes/genNetworkLSTM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5672518496295862}}
{"text": "function y = log(x)\n%LOG          Implements  log(x)  for intervals\n%\n%   y = log(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, following N.C. Boersken:\n%                                  Komplexe Kreis-Standardfunktionen,\n%                                  Freiburger Intervallberichte 78/2,\n%                                  NaN input, sparse input, log(0),\n%                                  major revision, improved accuracy\n% modified 12/06/99                branch cut with warning\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 12/04/05     S.M. Rump  'realstdfctsexcptnignore' added and some\n%                                     improvements, tocmplx replaced by cintval,\n%                                     extreme values for approximate part\n% modified 09/06/07     S.M. Rump  approximate std fcts removed\n% modified 10/23/07     S.M. Rump  complex numbers\n% modified 09/28/08     S.M. Rump  check for rounding to nearest improved\n% modified 10/20/08     S.M. Rump  check for zero omitted, improved performance\n% modified 10/18/08     S.M. Rump  StdFctsException ignore/NaN\n% modified 08/26/12     S.M. Rump  global variables removed\n% modified 10/13/12     S.M. Rump  INTLAB_INTVAL_STDFCTS\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 x.complex\n    if issparse(x.mid)\n      x.mid = full(x.mid);\n      x.rad = full(x.rad);\n    end\n    y = x;\n\n%   y.mid = log(x.mid);\n%   y.rad = - log( 1 - x.rad./abs(x.mid) );\n\n    INTLAB_STDFCTS_PI = getappdata(0,'INTLAB_STDFCTS_PI');\n\n    xmidre = real(x.mid);\n    xmidim = imag(x.mid);\n    Xmidim = intval(xmidim);\n    Mim = atan(Xmidim./xmidre);      % -pi/2 <= Mim <= pi/2\n\n    % special treatment of imaginary axis\n    index = ( xmidre==0 );\n    if any(index(:))\n      Mim.inf(index) = INTLAB_STDFCTS_PI.PI2INF;          % pi/2\n      Mim.sup(index) = INTLAB_STDFCTS_PI.PI2SUP;\n      indexneg = index & ( xmidim<0 );\n      if any(indexneg(:))\n        Mim.inf(indexneg) = -INTLAB_STDFCTS_PI.PI2SUP;    % -pi/2\n        Mim.sup(indexneg) = -INTLAB_STDFCTS_PI.PI2INF;\n      end\n    end\n\n    index = ( xmidre < 0 );\n    if any(index(:))\n      % correct to atan2:  -pi <= Mim <= pi\n      Pi = infsup( INTLAB_STDFCTS_PI.PIINF, ...\n                   INTLAB_STDFCTS_PI.PISUP );\n      signxmidim = sign(xmidim(index));\n      corr = Pi.*(signxmidim+(signxmidim==0));\n      Mim.inf(index) = Mim.inf(index) + corr.inf;\n      Mim.sup(index) = Mim.sup(index) + corr.sup;\n    end\n\n    % x.mid = r*exp(j*phi)  ==>  log(x.mid) = log(r) + j*phi\n    R = abs(x.mid);\n    Mreinf = log_rnd(R,-1);\n    Mresup = log_rnd(R,1);\n\n    setround(1)\n    mre = Mreinf + 0.5*(Mresup-Mreinf);\n    mim = Mim.inf + 0.5*(Mim.sup-Mim.inf);\n    y.mid = mre + j*mim;\n    mrad = abs( mre-Mreinf + j*(mim-Mim.inf) );\n    % log(R)  in  mre + j*mim +/- mrad\n\n    wng = warning;\n    warning off\n    % x.rad < R ,  otherwise zero interval\n    y.rad = log_rnd( -( x.rad./R - 1 ) , -1);\n    warning(wng);\n    y.rad = -y.rad + mrad;\n    setround(0)\n\n    % special treatment of branch cut\n    index0 = ( R <= x.rad );               % zero interval\n    index = ( ~index0 ) & ...\n            (   ( ( xmidre<0 ) & ( xmidim>=0 ) & ( x.rad>xmidim ) ) ...\n              | ( ( xmidre<0 ) & ( xmidim<0 ) & ( x.rad>=-xmidim ) ) ...\n            );\n    if any(index(:))\n      warning('Complex Log: Input interval intersects with branch cut')\n    end\n\n    if any(index0(:))\n      y.mid(index0) = complex(NaN,NaN);\n      y.rad(index0) = NaN;\n    end\n  \n    if rndold\n      setround(rndold)\n    end\n    \n    return\n  end\n\n  if issparse(x.inf)\n    x.inf = full(x.inf);\n    x.sup = full(x.sup);\n  end\n  % input x real and full\n  % real range of definition:  [0,inf]\n  INTLAB_STDFCTS_EXCPTN = getappdata(0,'INTLAB_STDFCTS_EXCPTN');\n  index = ( x.inf<0 );                  % (partially) exceptional indices\n  if any(index(:))                      % handle input out-of-range\n    if INTLAB_STDFCTS_EXCPTN<=1  % out-of-range input handled as complex\n      if INTLAB_STDFCTS_EXCPTN==1\n        warning('LOG: Real interval input out of range changed to be complex')\n      end\n      y = x;\n      %VVVV  y(index) = log(cintval(x(index)));\n      s.type = '()'; s.subs = {index}; y = subsasgn(y,s,log(cintval(subsref(x,s))));\n      %AAAA  Matlab bug fix\n      index = ~index;\n      if any(index(:))\n        %VVVV  y(index) = log(x(index));\n        s.type = '()'; s.subs = {index}; y = subsasgn(y,s,log(subsref(x,s)));\n        %AAAA  Matlab bug fix\n      end\n      if rndold\n        setround(rndold)\n      end\n      return\n    end\n    setappdata(0,'INTLAB_STDFCTS_EXCPTN_',1);\n    if INTLAB_STDFCTS_EXCPTN==3    % ignore input out of range (ignore-mode)\n      x.inf(index) = realmin*eps;;        % completely exceptional indices treated below\n      indexneg = index & ( x.sup<0);      % completely exceptional indices\n    end\n  else\n    indexneg = [];                        % make sure indexneg is not undefined\n  end\n\n  % input x real and full\n  y = x;\n  wng = warning;\n  warning off\n  \n  % treat non-exceptional cases\n  y.inf = log_rnd(x.inf,-1);\n  y.sup = log_rnd(x.sup,1);\n\n  if INTLAB_STDFCTS_EXCPTN==3      % ignore input out of range (ignore-mode)\n    if ~isempty(find(indexneg))           % completely exceptional arguments to NaN\n      y.inf(indexneg) = NaN;\n      y.sup(indexneg) = NaN;\n    end\n  else                                    % any input out of range to NaN (NaN-mode)\n    if ~isempty(find(index))              % exceptional arguments to NaN\n      y.inf(index) = NaN;\n      y.sup(index) = NaN;\n    end\n  end\n\n  warning(wng)\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/log.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.56725184385499}}
{"text": "impts=zeros(yw*exf,xw*exf);\nn_rendered=0;\nweight=str2double(get(handles.weight,'String'));\nsize_fac=str2double(get(handles.size_fac_edit,'String'));\n\nfor i=nstart:nend\n    if xc(i)>=1 && yc(i)>=1 && xc(i)<xw*exf && yc(i)<yw*exf && N(i)>0\n      wide=ceil(size_fac*lppix(i)*1.5+1);\n%       if wide>20 \n%           wide=20;\n%       end\n      if xc(i)-wide>=1 && xc(i)+wide<xw*exf && yc(i)-wide>=1 && yc(i)+wide<yw*exf\n        n_rendered=n_rendered+1;\n        for j=xc(i)-wide:xc(i)+wide\n          for k=yc(i)-wide:yc(i)+wide\n            dx=double(j)-xf(i);\n            dy=double(k)-yf(i);\n            int=pi*lp2pix(i)*size_fac;\n            a=exp(-2*(dx*dx+dy*dy)/(size_fac*size_fac*lp2pix(i)))*N(i)*weight/int;\n            impts(k,j)=impts(k,j)+a;\n          end\n        end\n      end\n    end\n    waitbarxmod(i/nend,w); %update\nend\n\nthresh=impts*0+1;\nimpts=thresh.*(impts>thresh)+impts.*(impts<=thresh);\nclear thresh;", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/TGgui070708/render_func.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5672518344919703}}
{"text": "clear all; close all; clear classes; clc;\n\n%% Set flags.\ninspect_only = false;\n\n%% Create shapes.\na = 420;  % lattice constant\nt = 1;  % slab thickness\nr = 0.29*a;  % hole radius\n\nad = 25;  % divider for a\ntd = 10;  % divider for t\ndd = 10;  % divider for d = 2*r\n\nmx = 20.5;\nmy = 7.5;\nslab_yn = Box([-mx*a mx*a; -my*a -0.5*a; 0 t], [a/ad, a/ad, t]);\nslab_yp = Box([-mx*a mx*a; 0.5*a my*a; 0 t], [a/ad, a/ad, t]);\n\nrod = CircularCylinder(Axis.z, t, [0 0 t/2], r, [2*r/dd, 2*r/dd, t]);\n\n%% Solve the system.\ngray = [0.5 0.5 0.5];  % [r g b]\nsrc_loc = 2*a;\n[E, H, obj_array, src_array, J] = maxwell_run(...\n\t'OSC', 1e-9, 1550, ...\n\t'DOM', {'Johnson/Ag', gray}, [-mx*a mx*a; -my*a my*a; 0 t], [a/ad a/ad t], BC.p, [10*a 2*a 0], ...\n\t'OBJ', ...\n\t\t{'vacuum', 'w', 1}, Box([-mx*a mx*a; -a/2 a/2; 0 t]), ...\n\t'SRCJ', PointSrc(Axis.z, [src_loc, 0, 0.5]), ...\n\tinspect_only);\n\n%% Visualize the solution.\nif ~inspect_only\n\tfigure;\n\tclear opts\n% \topts.withgrid = true;\n\topts.withobjsrc = false;\n\topts.withabs = true;\n\topts.withpml = false;\n\topts.phase = pi/2;\n\tvis2d(E{Axis.z}, Axis.z, 0.5, obj_array, src_array, opts)\n\t%%\n\tvis2d(H{Axis.y}, Axis.z, 0.5, obj_array, src_array, opts)\n\t\n\t%%\n\tflux_loc = 3*a;\n\tpower_right = powerflux_patch(E, H, Axis.x, src_loc + flux_loc);\n\tpower_left = -powerflux_patch(E, H, Axis.x, src_loc - flux_loc);\n\tfprintf('power:\\n');\n\tfprintf('right = %s\\n', num2str(power_right));\n\tfprintf('left = %s\\n', num2str(power_left));\n\tfprintf('error = %s%%\\n',num2str((power_left-power_right)/power_right*100));\n\t\n\t%%\n\tSx = poynting(Axis.x, E{Axis.y}, E{Axis.z}, H{Axis.y}, H{Axis.z}, Axis.y, 0);\n\t[array, l] = Sx.data_original;\n\tplot(l{2}, abs(array))\n\tmx*a - 10*a\nend\n", "meta": {"author": "wsshin", "repo": "maxwellfdfd", "sha": "f7d583813781694c8a6f0533a91f56c2a78a9ee5", "save_path": "github-repos/MATLAB/wsshin-maxwellfdfd", "path": "github-repos/MATLAB/wsshin-maxwellfdfd/maxwellfdfd-f7d583813781694c8a6f0533a91f56c2a78a9ee5/example/2d/mdm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5672518299650421}}
{"text": "function result = CRA_enterFunc(alpha,beta,gamma,lambda,numK,maxIter,flag,inputPath)\n\n    %% ======================================================================\n    %%STEP 1: load the data\n    fprintf('start load the data...\\n');\n    [TrainData, TestData, TrainLabel, TestLabel, numX, numS] = CRA_loadData(inputPath);\n\n    numM = size(TrainData,1);                % input data feature dimensions\n    \n    %% ======================================================================\n    %%STEP 2: Initialize the parameter\n    fprintf('start initialize the parameter...\\n');\n    theta = CRA_initialize(numK, numM, numS, numX,TrainData,TrainLabel,TestData);    % Randomly initialize the parameters  \n\n    %% ======================================================================\n    %%STEP 3: Training the parameters W1 W2 b1 b2 C\n    fprintf('start training the parameter...\\n');\n    [opttheta, cost] = CRA_Train(numM,numK,numS,numX,maxIter,alpha,beta,gamma,lambda,TrainData,TestData,TrainLabel,theta);\n    \n    %% ======================================================================\n    %%STEP4: get parameters W1 W2 W11 W22 b1 b2 b11 b22 after training\n    fprintf('get the parameter...\\n');\n    W1 = reshape(opttheta(1:numK*numM), numK, numM);\n    b1 = opttheta(2*numK*numM+1:2*numK*numM+numK);\n    C = reshape(opttheta(2*numK*numM+numK+numM+1:end), numS, numK);\n    \n    %% ======================================================================\n    %%STEP4: Testing\n    fprintf('testing the model...\\n');\n    hiddeninputs_train = sigmoid(W1 * TrainData + b1 * ones(1, size(TrainData,2)));\n    hiddeninputs_test = sigmoid(W1 * TestData + b1 * ones(1, size(TestData,2)));\n    if flag == 1\n        predict = CRA_test(hiddeninputs_train, hiddeninputs_test, TrainLabel, TestLabel, numX, numS, C);\n    else\n        predict = CRA_test_LR(hiddeninputs_train, hiddeninputs_test, TrainLabel, TestLabel, numX, numS);\n    end\n    result=predict;\n    clear hiddeninputs_train hiddeninputs_test\nend", "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/CRA_enterFunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5672518298104602}}
{"text": "\n\n% hessMultdalgl - function that computes H*x for DAL with grouped\n%                 L1 regularization\n%\n% Copyright(c) 2009 Ryota Tomioka\n% This software is distributed under the MIT license. See license.txt\n\nfunction yy = hessMultdalgl(xx, A, eta, Hinfo)\n\nyy = Hinfo.hloss*xx;\nif ~isempty(Hinfo.precomp)\n    % general case\n    for p=Hinfo.precomp\n        % project & reshape xx's for all spans\n        xk = reshape(p.AJ'*xx,[],numel(p.jj));\n        % dot product between vn's and xk's, scale by ff's and multiply by vn's (also add xk*(1-ff))\n        tmp = bsxfun(@times,p.vn,sum(p.vn.*xk).*p.ff) + bsxfun(@times,xk,p.omff);\n        % block-diagonalize tmp\n        bd = sparse(p.idxu,p.idxv,tmp,numel(xk),numel(p.jj));\n        % map through AJ again, sum and multiply by eta(1), add results to yy\n        yy = yy + sum(p.AJ*bd,2)*eta(1);\n    end\nelse\n    % very sparse case\n    blks =Hinfo.blks;\n    hloss=Hinfo.hloss;\n    I    =Hinfo.I;\n    vv   =Hinfo.vv;\n    nm   =Hinfo.nm;\n    lambda=Hinfo.lambda;\n    for kk=1:length(I)\n        jj=I(kk);\n        J=Hinfo.blkival{jj};\n        vn=vv(J)/nm(jj);        \n        ff=lambda/nm(jj);\n        AJ=A.slice(J);\n        xk=AJ'*xx;\n        yy = yy + eta(1)*(AJ*((1-ff)*xk + ff*(vn'*xk)*vn));\n    end\nend\n\nB=Hinfo.B;\nif ~isempty(B)\n  yy = yy + eta(2)*(B*(B'*xx));\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/dal_ver1.05/hessMultdalgl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.567251828717374}}
{"text": " function [xs, ni] = eml_sps(x, Gt, yi, ci, ri, niter, curv)\n%function [xs, ni] = eml_sps(x, Gt, yi, ci, ri, niter, curv)\n%\tOne iteration of the ML-SPS algorithm for emission Poisson problem\n%\t(separable paraboloidal surrogates)\n%\tmodel: Y_i ~ Poisson(c_i [G x]_i + r_i)\t\tWITH r_i > 0 REQUIRED!\n%\tin:\n%\t\tGt\ttranspose of system matrix\n%\t\tsee em_fbp.m for model, G, yi, ci, ri\n%\tout:\n%\t\tx [np,niter]\tupdated image vectors each iteration\n%\n%\tCopyright Mar 2000, Jeff Fessler, The University of Michigan\n\nif nargin < 3, ir_usage, end\n\n[nb, na] = size(yi);\n\nif ~isvar('ci') || isempty(ci)\n\tci = ones(size(yi));\nend\nif ~isvar('ri') || isempty(ri)\n\tri = zeros(size(yi));\nend\nif ~isvar('niter') || isempty(niter)\n\tniter = 1;\nend\n\neml_check(yi, ci, ri)\n\n\tgi = sum(Gt)';\t% g_i = sum_j g_ij\n\nxs = zeros(numel(x), niter);\nxs(:,1) = x(:);\n%\n%\tloop over iterations\n%\nfor ii=2:niter\n\tli = reshape(Gt' * x(:), size(yi));\t% l=G*x \"line integrals\"\n\tyb = ci .* li + ri;\t\t\t% predicted measurement means \n\n\t%\tcurvatures\n\tni = eml_curvature(yi, ci, ri, li, yb, curv);\n\n\tdothi = ci .* (yi ./ yb - 1);  \n\n\tx = x + (Gt * dothi(:)) ./ (Gt * (gi .* ni(:)));\n\tx = max(x,0);\n\n\txs(:,ii) = x;\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/emission/arch/eml_sps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5672518193543534}}
{"text": "function degree = dunavant_degree ( rule )\n\n%*****************************************************************************80\n%\n%% DUNAVANT_DEGREE returns the degree of a Dunavant rule for the triangle.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    11 December 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    David Dunavant,\n%    High Degree Efficient Symmetrical Gaussian Quadrature Rules\n%    for the Triangle, \n%    International Journal for Numerical Methods in Engineering,\n%    Volume 21, 1985, pages 1129-1148.\n%\n%    James Lyness, Dennis Jespersen,\n%    Moderate Degree Symmetric Quadrature Rules for the Triangle,\n%    Journal of the Institute of Mathematics and its Applications,\n%    Volume 15, Number 1, February 1975, pages 19-32.\n%\n%  Parameters:\n%\n%    Input, integer RULE, the index of the rule.\n%\n%    Output, integer DEGREE, the polynomial degree of exactness of\n%    the rule.\n%\n  if ( 1 <= rule & rule <= 20 )\n    degree = rule;\n  else\n\n    degree = -1;\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'DUNAVANT_DEGREE - Fatal error!\\n' );\n    fprintf ( 1, '  Illegal RULE = %d\\n', rule );\n    error ( 'DUNAVANT_DEGREE - 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/triangle_dunavant_rule/dunavant_degree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.5671909163066643}}
{"text": "function rhs_spiral_test ( )\n\n%*****************************************************************************80\n%\n%% RHS_SPIRAL_TEST samples the right hand side at the initial time.\n%\n%  Location:\n%\n%    http://people.sc.fsu.edu/~jburkardt/m_src/navier_stokes_2d_exact/rhs_spiral_test.m\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 January 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  nu = 1.0;\n  rho = 1.0;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'RHS_SPIRAL_TEST\\n' );\n  fprintf ( 1, '  Spiral Flow:\\n' );\n  fprintf ( 1, '  Sample the Navier-Stokes right hand sides\\n' );\n  fprintf ( 1, '  at the initial time T = 0, using the unit square.\\n' );\n  fprintf ( 1, '  Kinematic viscosity NU = %g\\n', nu );\n  fprintf ( 1, '  Fluid density RHO = %g\\n', rho );\n\n  n = 1000;\n  xy_lo = 0.0;\n  xy_hi = 1.0;\n  seed = 123456789;\n  [ x, seed ] = r8vec_uniform_ab ( n, xy_lo, xy_hi, seed );\n  [ y, seed ] = r8vec_uniform_ab ( n, xy_lo, xy_hi, seed );\n  t = 0.0;\n\n  [ f, g, h ] = rhs_spiral ( nu, rho, n, x, y, t );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '           Minimum       Maximum\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  F:  %14.6g  %14.6g\\n', min ( f ), max ( f ) );\n  fprintf ( 1, '  G:  %14.6g  %14.6g\\n', min ( g ), max ( g ) );\n  fprintf ( 1, '  H:  %14.6g  %14.6g\\n', min ( h ), max ( 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/navier_stokes_2d_exact/rhs_spiral_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.5671909163066643}}
{"text": "% DEMO of subplot Vs subplot_tight\nfunc_hndl={@subplot;@subplot_tight};\ndir_file=dir('*.jpg');\nfor p=1:length(dir_file)\n   img=imread(dir_file(p).name);\n   for func_ind=1:length(func_hndl)\n      figure(func_ind)\n      func_hndl{func_ind}(3,3,p);\n      imshow(img);\n   end\nend\npeaks_data=peaks(50);\nfor func_ind=1:length(func_hndl);\n   figure(func_ind)\n   func_hndl{func_ind}(3,3,[8,9]);\n   surf(peaks_data);\n   axis tight;\n   xlabel('x');\n   ylabel('y');\n   zlabel('z');\n   title('Peaks Plot','FontSize', 14);\nend\nset(1,'Name','Matlab SUBPLOT');\nset(2,'Name','Our subplot_tight');\nset(1:2,'MenuBar','none')", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/30884-controllable-tight-subplot/subplot_tight/demo_subplot_tight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.567190913239204}}
{"text": "function c = tmat_mxm ( a, b )\n\n%*****************************************************************************80\n%\n%% TMAT_MXM multiplies two geometric transformation matrices.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    21 February 2005\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Foley, van Dam, Feiner, Hughes,\n%    Computer Graphics, Principles and Practice,\n%    Addison Wesley, Second Edition, 1990.\n%\n%  Parameters:\n%\n%    Input, real A(4,4), the first geometric transformation matrix.\n%\n%    Input, real B(4,4), the second geometric transformation\n%    matrix.\n%\n%    Output, real C(4,4), the product A * B.\n%\n  c(1:4,1:4) = a(1:4,1:4) * b(1:4,1:4);\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/tmat_mxm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936537604179, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5671909075226833}}
{"text": "function [samecost, sameassignment] = testassignment\n%TESTASSIGNMENT  Test and compare assignment algorithms.\n%\t\t[SAMECOST, SAMEASSIGNMENT] = TESTASSIGN randomly generates distance\n%\t\tmatrices and solves the assignment problem using different algorithms.\n%\t\tEdit the header of this file to change the simulation parameters.\n%\n%\t\t<a href=\"assignment.html\">assignment.html</a>  <a href=\"http://www.mathworks.com/matlabcentral/fileexchange/6543\">File Exchange</a>  <a href=\"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=EVW2A4G2HBVAU\">Donate via PayPal</a>\n%\n%\t\tMarkus Buehren\n%\t\tLast modified 05.07.2011\n%\n%\t\tSee also ASSIGNMENTOPTIMAL, ASSIGNMENTSUBOPTIMAL1,\n%\t\tASSIGNMENTSUBOPTIMAL2, ASSIGNMENTALLPOSSIBLE.\n\n% simulation time in seconds\ntestTime = 20;       \n\n% maximum matrix dimensions\nmaxOrders = [15, 25];  \n\n% If infAllowed in set to false, only distance matrices without infinite \n%\tcosts are used\ninfAllowed = true;     \n\n% If the product of the dimensions of the distance matrix is smaller than\n% maxDimProduct, the assignment function computing all possible assignments\n% is used as reference. Set this to inf to use always or to 0 to never use.\nmaxDimProduct = 30; \n\n% set recurstion limit\nrecursionLimit = get(0,'RecursionLimit');\nset(0, 'RecursionLimit', 1000);\n\n% use profiler or not\nuseProfiler = true;\n\n% start profiler\nif useProfiler\n\tprofile clear\n\tprofile on\nend\n\n% initialize\nstartTime = clock;\nnassign = 0;\nh = waitbar(0, 'Please wait', 'Name', mfilename);\n\nwhile 1\n\tfor dim1 = 1:maxOrders(1)\n\t\tfor dim2 = 1:maxOrders(2)\n\t\t\t\n\t\t\tif ~infAllowed\n\t\t\t\t\n\t\t\t\t% generate distMatrix without infinite elements\n\t\t\t\tdistMatrix = rand(dim1,dim2);\n\t\t\t\t\n\t\t\telse\n\t\t\t\t\n\t\t\t\tif rand(1) < 0.5\n\t\t\t\t\t% generate distMatrix with some infinite elements\n\t\t\t\t\tdistMatrix = rand(dim1,dim2);\n\t\t\t\t\t\n\t\t\t\t\tif rand(1) < 0.5\n\t\t\t\t\t\t% set some elements to inf\t\t\t\t\t\n\t\t\t\t\t\tdistMatrix(rand(dim1,dim2) > rand(1)) = inf;\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\telse\n\t\t\t\t\t\n\t\t\t\t\t% generate distMatrix with many infinite elements\n\t\t\t\t\tdistMatrix = repmat(inf, dim1, dim2);\n\t\t\t\t\t\n\t\t\t\t\tif rand(1) < 0.5\n\t\t\t\t\t\tfor row=1:dim1\n\t\t\t\t\t\t\tif rand(1) < 0.8\n\t\t\t\t\t\t\t\t% set one element per row to finite number\n\t\t\t\t\t\t\t\tdistMatrix(row, 1+floor(dim2*rand(1))) = rand(1);\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tif rand(1) < 0.3\n\t\t\t\t\t\t\t\t% set another element per row to finite number\n\t\t\t\t\t\t\t\tdistMatrix(row, 1+floor(dim2*rand(1))) = rand(1);\n\t\t\t\t\t\t\tend\t\t\t\t\t\t\n\t\t\t\t\t\tend\t\t\n\t\t\t\t\telse\n\t\t\t\t\t\tfor col=1:dim2\n\t\t\t\t\t\t\tif rand(1) < 0.8\n\t\t\t\t\t\t\t\t% set one element per column to finite number\n\t\t\t\t\t\t\t\tdistMatrix(1+floor(dim1*rand(1)), col) = rand(1);\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tif rand(1) < 0.3\n\t\t\t\t\t\t\t\t% set another element per column to finite number\n\t\t\t\t\t\t\t\tdistMatrix(1+floor(dim1*rand(1)), col) = rand(1);\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\t\t\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\t% quantize distMatrix\n\t\t\tif rand(1) < 0.3\n\t\t\t\tdistMatrix = round(max(10, 1000*rand(1)^2)*distMatrix);\n\t\t\tend\t\t\t\n\t\t\t\n\t\t\t% transpose distMatrix\n\t\t\tif rand(1) < 0.5\n\t\t\t\tdistMatrix = distMatrix';\n\t\t\tend\n\t\t\t\n\t\t\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t\t\t[assignmentCell{1}, costCell{1}] = assignmentoptimal    (distMatrix); %#ok\n\t\t\t[assignmentCell{2}, costCell{2}] = assignmentsuboptimal1(distMatrix); %#ok\n\t\t\t[assignmentCell{3}, costCell{3}] = assignmentsuboptimal2(distMatrix); %#ok\n\t\t\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\t\t\t% if dimensions are moderate, compute all possible solutions\n\t\t\tif dim1 * dim2 < maxDimProduct\n\t\t\t\t[assignment, cost] = assignmentallpossible(distMatrix);\n\t\t\telse\n\t\t\t\tassignment = assignmentCell{1};\n\t\t\t\tcost       = costCell{1};\n\t\t\tend\n\t\t\t\n\t\t\t% count trial runs\n\t\t\tnassign = nassign + 1;\n\t\t\t\n\t\t\tif ~exist('samecost', 'var')\n\t\t\t\tM = length(costCell);\n\t\t\t\tsamecost        = zeros(M,1);\n\t\t\t\tsameassignment = zeros(M,1);\t\t\t\t\n\t\t\tend\t\n\t\t\t\n\t\t\t% compute penalty for non-assignments\n\t\t\tfiniteIndex = isfinite(distMatrix);\n\t\t\tpenalty = max(max(distMatrix(finiteIndex))) * dim1 * dim2;\n\t\t\tif ~isempty(penalty)\n\t\t\t\tcost = cost + length(find(~assignment)) * penalty;\n\t\t\tend\n\t\t\t\n\t\t\tfor m=1:M\n\t\t\t\t\n\t\t\t\t% penalize non-assignments\n\t\t\t\tif ~isempty(penalty)\n\t\t\t\t\tcostCell{m} = costCell{m} + length(find(~assignmentCell{m})) * penalty; %#ok\n\t\t\t\tend\t\t\t\t\n\t\t\t\t\n\t\t\t\t% compare costs\n\t\t\t\tif costCell{m} <= cost + 100*eps\n\t\t\t\t\tsamecost(m) = samecost(m) + 1;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t% compare assignments\n\t\t\t\tif all(assignmentCell{m} == assignment)\n\t\t\t\t\tsameassignment(m) = sameassignment(m) + 1;\n\t\t\t\tend\n\t\t\t\t\n\t\t\tend\n\t\tend\n\t\t% set waitbar\n\t\tcurTime = etime(clock, startTime);\n\t\twaitbar(curTime/testTime, h);\n\tend\n\t\n\t% stop after given time\n\tif curTime > testTime\n\t\tbreak\n\tend\nend\nclose(h);\n\n% scale counters\nsamecost       = samecost/nassign;\nsameassignment = sameassignment/nassign;\n\nif useProfiler\n\tprofile off\n\tprofile report\nend\n\n% reset recurstion limit\nset(0, 'RecursionLimit', recursionLimit);\n", "meta": {"author": "yuxng", "repo": "MDP_Tracking", "sha": "2f452a1f7204b6e3344925b8eaf39db1c7eecf2c", "save_path": "github-repos/MATLAB/yuxng-MDP_Tracking", "path": "github-repos/MATLAB/yuxng-MDP_Tracking/MDP_Tracking-2f452a1f7204b6e3344925b8eaf39db1c7eecf2c/3rd_party/Hungarian/testassignment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5671909040137135}}
{"text": "function [mGal] = uGal2mGal(uGal)\n% Convert acceleration from microgals to milligals. \n% Chad A. Greene 2012\nmGal = uGal*1e-3; \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/35258-unit-converters/unit_converters/uGal2mGal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5671889062041762}}
{"text": "function map2ecefTrafo(obj, mstruct, varargin)\n% MAP2ECEFTRAFO Coordinate transformation from ecef to map coordinates.\n%\n% Example: definition of mstruct for UTM33N\n% mstruct       = defaultm('utm');\n% mstruct.zone  = '33n';\n% mstruct.geoid = referenceEllipsoid('GRS 80');\n% mstruct       = defaultm(mstruct);\n\n% Input parsing ----------------------------------------------------------------\n\np = inputParser;\np.addRequired( 'mstruct');\np.parse(mstruct, varargin{:});\np = p.Results;\n% Clear required inputs to avoid confusion\nclear mstruct\n\n% Start ------------------------------------------------------------------------\n\nprocHierarchy = {'POINTCLOUD' 'MAP2ECEFTRAFO'};\nmsg('S', procHierarchy);\nmsg('I', procHierarchy, sprintf('Point cloud label = ''%s''', obj.label));\n\n% Conversion to ecef coordinates -----------------------------------------------\n\n[lat, lon, hEll] = minvtran(p.mstruct, obj.X(:,1), obj.X(:,2), obj.X(:,3)); % lat, lon in degrees!\n\n[xEcef, yEcef, zEcef] = geodetic2ecef(lat*pi/180, lon*pi/180, hEll, p.mstruct.geoid); % lat, lon in radian!\n\n% Update coordinates -----------------------------------------------------------\n\nobj.X = [xEcef yEcef zEcef];\nobj.info;\n\n% End --------------------------------------------------------------------------\n\nmsg('E', procHierarchy);\n\nend", "meta": {"author": "pglira", "repo": "Point_cloud_tools_for_Matlab", "sha": "4768f45e7d3527c52e911eb0450c31ca19b58f72", "save_path": "github-repos/MATLAB/pglira-Point_cloud_tools_for_Matlab", "path": "github-repos/MATLAB/pglira-Point_cloud_tools_for_Matlab/Point_cloud_tools_for_Matlab-4768f45e7d3527c52e911eb0450c31ca19b58f72/classes/@pointCloud/map2ecefTrafo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5671888903275417}}
{"text": "function [CRLB,J]=getEstimatorMinMSEBound(RInv,stateJacob,statJacob,biasVec,biasJacob,numMeasDims,checkPosDef)\n%%GETESTIMATORMINMSEBOUND This evaluates a generalization of the Cramer-Rao\n%       lower bound (CRLB) specifically for the case where measurements are\n%       corrupted with multivariate Gaussian noise. The measurement model\n%       is z=h(x)+w, where x is the (deterministic) state, h is the\n%       (possible nonlinear) measurement function and w is zero-mean\n%       Gaussian noise with covariance matrix R. h can vary between\n%       measurements that are being fused. This offers a lower bound on the\n%       mean-squared error of a biased multivariate statistic. The\n%       statistic is just a transformation of the state, so zStat=f(x).\n%       Biased means that if T(x) is the estimator, then the expecttation\n%       E{T(x)-f(x)}=b(x), where b(x) is the bias. If one doesn't know the\n%       bias and its gradient, omitting those terms provides a lower bound\n%       on the covariance matrix of an unbiased statistic. If the statistic\n%       Jacobian is omitted, then the bound is directly on the state x.\n%       The bias term can be useful when one already has an estimator with\n%       a known or approximated bias and they want to approximate its\n%       accuracy with the MSE matrix bound rather than analytically\n%       evaluating its true MSE.\n% \n%INPUTS: RInv The zDimXzDimXnumMeas set of inverse covariance matrices\n%          associated with the multivariate Gaussian noise corrupting each\n%          of the numMeas measurements. If the dimensionality of the\n%          measurements varies, then zDim is the maximum\n%          dimensionality of any measurement and then numMeasDims is\n%          required so that if sel=1:numMeasDims(k), then RInv(sel,sel,k)\n%          is the submatrix used for the kth measurement.\n% stateJacob The zDimXxDimXnumMeas Jacobian matrices of derivatives of the\n%          measurement function h taken with respect to the elements of\n%          the target state for every measurement. If a single zDimXxDim\n%          matrix is passed, then it is assumed that this is the same for\n%          all numMeas measurement. If the dimensionality of the\n%          measurements varies, then zDim is the maximum\n%          dimensionality of any measurement and then numMeasDims is\n%          required so that if sel=1:numMeasDims(k), then\n%          stateJacob(sel,:,k) is the submatrix used for the kth\n%          measurement.\n% statJacob The statDimXxDim matrix of derivatives of the the statistic\n%          function f(x) taken with respect to the state x. If this is\n%          omitted or an empty matrix is passed, then an xDimXxDim identity\n%          matrix is used, which is the same as h(x)=x.\n%  biasVec A statDimX1 vector, if provided. This is the bias of the assumed\n%          estimator of the statistics. If this value and the next value\n%          are omitted or empty matrices are provided, then the CRLB for an\n%          unbiased statistic is computed.\n% biasJacob A statDimXxDim matrix of derivatives of the estimator bias b(x)\n%          taken with respect to the state x. If this is provided, then\n%          biasVec must be provided. If omitted or an empty matrix is\n%          passed, then this is assumed to be 0.\n% numMeasDims If all measurement shave the same dimensionality , then this\n%          input should be omitted or an empty matrix passed. Otherwise,\n%          this is a length numMeas vector that specified how many\n%          dimensions each measurement has.\n% checkPosDef If this is true, then a check is performed as to whether the\n%          Fisher information matrix in the algorithm is full rank.\n%          If it is not, then the CRLB matrix will be returned empty and no\n%          attempt will be made to invert it. The default if omitted or an\n%          empty matrix is passed is false.\n%\n%OUTPUTS: CRLB The statDimXstatDim CRLB matrix or, if the FIM was singular,\n%              and checkPosDef is true, an empty matrix.\n%            J The Fisher infromation matrix that went into computing CRLB.\n%\n%A simple derivation of the standard multivariate CRLB is derived in [1].\n%If in the derivation there, one replaces the difference T_k(x)-x_k (the\n%difference of the best estimator of the kth component of x and the state)\n%with T_k(x)-f_k(x), where f_k(x) is the kth component of a desired\n%statistic and thus T_k(x) becomes an estimator of a component of a\n%statistic, then one will derive the CRLB of a statistic instead of just of\n%the state. In the scalar case, this was already in Rao's original paper in\n%[2].\n%\n%To consider a biased statistic, one then replaces the assumption in the\n%paper of a zero expected value: E{T_k(x)-x_k}=0 with\n%E{T_k(x)-f_k(x)}=b_k(x). The rest of the derivation in [1] is pretty much\n%the same, making sure that one is evaluating Cov{Z} and not just E{Z*Z'}.\n%Completing the derivation just using E{Z*Z'} and not Cov{Z} will lead one\n%to have a lower bound that is smaller by a bias*bias' term. \n%\n%Note that is is possible for a biased estimator to have a lower MSE than\n%an unbiased estimator. One such example is given in [3].\n%\n%EXAMPLE 1:\n%This is a simple example, where z=x+w with w having the identity matrix as\n%the covariance matrix. We take x to be 2X1. We want to estimate\n%f(x)=x'*x. The assumed biased estimator is T(z)=z'*z+sum(z)/100. (Note\n%that even T(z)=z'*z is biased, but we choose to make the bias non-\n%constant). The bias in 2D can be found to be b(x)=2+sum(x)/100.\n%The analytic mean squared error in 2D is\n%MSE=(80002+40001*x(1)^2+2*x(1)*(400+x(2))+x(2)*(800+40001*x(2)))/10000\n%We plot the MSE and the CRLB for a fixed x(1), while varying x(2). One can\n%see a reasonably good level of agreement, though the bound is not tight.\n% MSE=@(x)(80002+40001*x(1)^2+2*x(1)*(400+x(2))+x(2)*(800+40001*x(2)))/10000;\n% biasVec=@(x)(2+sum(x)/100);\n% biasJacob=@(x)[1/100,1/100];\n% statJacob=@(x)2*x';\n% stateJacob=eye(2,2);\n% RInv=eye(2,2);\n% numPts=200;\n% x1=-1/2;\n% x2=linspace(-5,5,numPts);\n% MSEVal=zeros(1,numPts);\n% CRLB=zeros(1,numPts);\n% for curPt=1:numPts\n%     xCur=[x1;x2(curPt)];\n%     MSEVal(curPt)=MSE(xCur);\n%     CRLB(curPt)=getEstimatorMinMSEBound(RInv,stateJacob,statJacob(xCur),biasVec(xCur),biasJacob(xCur));\n% end\n% figure(1)\n% clf\n% hold on\n% plot(x2,MSEVal,'-b','linewidth',2)\n% plot(x2,CRLB,'--k','linewidth',2)\n% legend('Actual MSE','CRLB','location','north')\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n%    Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%[2] C. R. Rao, \"Information and the accuray attainable in the estimation\n%    of statistical parameters,\" Bulletin of the Calcutta Mathematical\n%    Society, vol. 37, no. 3, pp. 81-91, 1945.\n%[3] P. Stoica and R. L. Moses, \"On biased estimators and the unbiased\n%    Cram\u00e9r-Rao lower bound,\" Signal Processing, vol. 21, no. 4, pp. 349-\n%    350, Dec. 1990.\n%\n%November 2022 David F.Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumMeas=size(RInv,3);\nxDim=size(stateJacob,2);\nstatDim=size(statJacob,1);\n\nif(nargin<7||isempty(checkPosDef))\n    checkPosDef=false;\nend\n\nif(nargin<6)\n    numMeasDims=[];\nend\n\nif(nargin<5||isempty(biasJacob))\n    biasJacob=zeros(statDim,xDim);\nend\n\nif(nargin<4||isempty(biasVec))\n    biasVec=zeros(statDim,1);\nend\n\nif(nargin<3||isempty(statJacob))\n    statJacob=eye(xDim,xDim);\nend\n\nif(numMeas>1&&size(stateJacob,3)==1)\n    stateJacob=repmat(stateJacob,[1,1,numMeas]);\nend\n\n%First get the FIM\nJ=zeros(xDim,xDim);\nif(isempty(numMeasDims))\n    %If all measurements are zDim in size\n    for k=1:numMeas\n        J=J+stateJacob(:,:,k)'*RInv(:,:,k)*stateJacob(:,:,k);\n    end\nelse\n    for k=1:numMeas\n        zDimCur=numMeasDims(k);\n        sel=1:zDimCur;\n        J=J+stateJacob(sel,:,k)'*RInv(sel,sel,k)*stateJacob(sel,:,k);\n    end\nend\n\nif(checkPosDef)\n    %Check whether or not J is positive definite.\n    if(matrixRank(J)<xDim)\n        CRLB=[];\n        return;\n    end\nend\n\nCRLB=(statJacob+biasJacob)*inv(J)*(statJacob+biasJacob)'+biasVec*biasVec';\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/getEstimatorMinMSEBound.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.567188884730444}}
{"text": "function  prices = SABR_EurBarAmer_func(call, M, T, S0, Kvec, r, CTMCParams, ModParams, contract_type, L)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% About: Pricing Function for European, American, and Barrier Options using\n% double Layer CTMC approximation for SABR\n%\n% Models Supported: SABR\n% Returns: price of contract (for vector of strikes)\n% Author: Justin Lars Kirkby\n%\n% References:  (1) General Valuation Framework for SABR and Stochastic Local Volatility\n%                   Models. SIAM J. Financial Mathematics, 2018. (w/ Z. Cui\n%                   and D. Nguyen)\n%\n% ----------------------\n% Contract/Model Params \n% ----------------------\n% call = 1 for call option, else Put\n% contract_type = type of contact: % 1 = European, 2 = American, 3 = Down and Out Barrier\n% Kvec  = strike vector\n% S0 = initinal underlying value\n% r   = interest rate (e.g. 0.05)\n% T   = time remaining until maturity (in years, e.g. T=1)\n% ModParams = model parameters: .v0, .alpha, .beta, .rho\n% L =  For barrier contract, this is the barrier\n%\n% ----------------------\n% Numerical (CTMC) Params \n% ----------------------\n% CTMCParams: .m_0 = grid/state size for variance process\n%             .N = grid/state stize for underlying\n%             .gridMult_v = grid non-uniformity multiplier (for variance)\n%             .gridMult_s = grid non-uniformity multiplier (for underlying)\n%             .gamma = Grid width param for variance grid\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nm_0        = CTMCParams.m_0;\nN          = CTMCParams.N;\ngridMult_v = CTMCParams.gridMult_v;\ngridMult_s = CTMCParams.gridMult_s;  %Grid mult param for S \ngamma      = CTMCParams.gamma;          %Grid width param for variance grid\n\ngridMethod_v = 5;   %%% ALWAYS use 5 for this one (puts v0 on grid)\ngridMethod_s = 4;   %%% 5 puts S_0 on grid, but 4 seems better (requires interpolation)\n\nv0    = ModParams.v0;\nalpha = ModParams.alpha;\nbeta  = ModParams.beta;\nrho   = ModParams.rho;\n\n%%%%%%%%%%%%%%%%%%%%%%\n%%%   Set Asset Grid bounds\n%%%%%%%%%%%%%%%%%%%%%%\nif S0 < 0.5\n    ls = .01*S0;   %lower bound in asset Grid (S_t) space\nelse\n    ls = 0.001*S0;\nend\n\nus = max(4.5*S0, S0 + 10*(v0*(S0)^beta)*sqrt(T));  %upper bound in asset Grid (S_t) space\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%   Step 1: Variance Grid / Generators\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndt = T/M;\nt = sqrt(T)/2;    %NOTE: this is different than we used to use... \n\nmu_func = @(u) 0*u;\nsig_func = @(u) alpha*u;\nmu_H = v0;\nsig2_H = v0^2*(exp(alpha^2*t) - 1); \n\nlx = max(0.0001,mu_H - gamma*sqrt(sig2_H));\nux = mu_H + gamma*sqrt(sig2_H);  \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%   Step 1: Variance Grid / Generators\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ncenter_v = v0;\n[Q,v] = General_Q_Matrix_Newest(m_0,mu_func,sig_func,lx,ux,gridMethod_v,center_v, gridMult_v);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%   Step 2: Asset Grid / Grid For Xtilde\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ng = @(s) (s ).^(1-beta)/(1-beta); \ninvOneBet = 1/(1-beta);\n\ncenter_s = S0;   %center of asset grid (e.g. center points around the strike)\nmanualPoint_s = center_s;  %manually places S0 on grid\nXgrid = g(getNonUniformGrid(N, ls, us, gridMethod_s, center_s, manualPoint_s, gridMult_s)) - rho/alpha*v0;  %Grid for Xtilde\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%   Step 3: Generators (for Xtilde process)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nNm = N*m_0;\nG = zeros(Nm, Nm);  %Big Generator matrix\nI = eye(N,N);\n\nPayoff = zeros(Nm, 1);  %Terminal payoff\nsqrtRho = sqrt(1-rho^2);\n\nfor j = 1:m_0 %loop through rows of big G matrix\n    %%%%%%%%%%\n    % Step(1): Find G_j (generator with v(j) fixed)\n    %%%%%%%%%%\n    nu_j = v(j);   \n    muX_func_nu  = @(x) -.5*beta*(nu_j)^2.*((1-beta)*(x + rho*nu_j/alpha)).^(-1) ;  %Drift function of Xtilde with v(j) fixed\n    sigX_func_nu = @(x) sqrtRho*nu_j*[x>-100];  %Constant function for each fixed variance state\n\n    Gnu = getGenerator_Q_MatrixOnly(Xgrid, muX_func_nu, sigX_func_nu, gridMethod_v);\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %%% FORCE absorbing vs reflecting\n    Gnu(1,1) = 0; Gnu(1,2) =0;\n    %Gnu(N,N) = 0; Gnu(N,N-1) = 0;\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \n    %%%%%%%%%%\n    % Step(2): Populate the Generator matrix (recall it is block tridiagonal,\n    %%%%%%%%%%\n    for k = max(1,j-1):min(m_0,j+1)  %%% NOTE: we skip the ones that are known to be zeros (matrix is block tridiagonal)\n        lamjk = Q(j,k);\n        if j==k  %diagonal block element of G matrix\n            G((j-1)*N + 1:j*N, (k-1)*N + 1:k*N ) = Gnu + lamjk*I; \n        else\n            G((j-1)*N + 1:j*N, (k-1)*N + 1:k*N ) = lamjk*I;   \n        end\n    end \nend\n\n%%%% Find bracketing variance gridpoint\nk_0 = 2;  \nwhile v0 >= v(k_0) && k_0 < m_0\n    k_0 = k_0+1;\nend\nk_0 = k_0 - 1;  %left bracketing point:  v(k_0) <= v0 < v(k_0 +1)\n\n%%%% Find bracketing Xtilde gridpoint\nx0 = g(S0) - rho*v0/alpha;  %initial value on Xtilde grid for (S_0, v0)\nj_0 = 2;\nwhile x0 >= Xgrid(j_0) && j_0 < N\n    j_0 = j_0+1;\nend\nj_0 = j_0 - 1;  %left bracketing point:   Xtilde(j_0) <= x0 < Xtilde(j_0 +1)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% VALUE : using recursive method\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nP = expm(G*dt);   %transition matrix of one dimensional CTMC\ninitialIndex = (k_0-1)*N + j_0;  %index corresponding to initial conditions\n\nprices = zeros(length(Kvec),1);\n\nfor k = 1:length(Kvec)\n    K = Kvec(k);\n    %%% Calculate Payoff\n    if call == 1 \n        for j = 1:m_0\n            Payoff((j-1)*N +1:j*N) = max(0, ((1-beta)*(max(0,Xgrid + rho*v(j)/alpha) )).^invOneBet - K) ;  %Portion of payoff corresponding to v(j)\n        end\n    else \n       for j = 1:m_0\n            Payoff((j-1)*N +1:j*N) = max(0, K - ((1-beta)*(max(0,Xgrid + rho*v(j)/alpha) )).^invOneBet );  %Portion of payoff corresponding to v(j)\n       end\n    end\n    %%% Now Price\n    if contract_type == 3  % Down and out for now\n        %determine which states remain alive\n        alive = zeros(Nm,1);\n        for j = 1:m_0\n            cons = g(L) - v(j)*rho/alpha;\n            alive((j-1)*N +1:j*N) = (Xgrid > cons);\n        end\n        pVec = alive.*Payoff;\n        for m = M-1:-1:0\n            pVec = exp(-r*dt)*alive.*(P*pVec);     \n        end\n    else %% either American or European\n        pVec = exp(-r*dt)*(P*Payoff);  %initialize the value (at last period)\n        if contract_type == 2\n            for m = M-2:-1:0\n                pVec = exp(-r*dt)*(P*pVec);  %continuation value\n                pVec = max(pVec, Payoff);   %max of continuation and intrinsic value\n            end\n        elseif contract_type == 1\n            for m = M-2:-1:0\n                pVec = exp(-r*dt)*(P*pVec);  %continuation value\n            end\n        end\n    end\n    \n    if gridMethod_s == 5  %Both v0 and x0 are on grid  (we assume v0 is a member of vol grid, ie as long as gridMethod_v = 5)\n        prices(k) = pVec(initialIndex);    \n    elseif gridMethod_s == 4 %x0 is not on grid (though we assume v0 is, ie as long as gridMethod_v = 5)\n        price1 = pVec(initialIndex);    %corresponds to j_0  \n        price2 = pVec(initialIndex+1);  %corresponds to j_0 + 1\n        prices(k) = price1 + (price2 - price1)*(x0 - Xgrid(j_0))/(Xgrid(j_0+1) - Xgrid(j_0));  %LINEAR INTERPOLATION\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/PROJ/SABR/European_American_Barrier/SABR_EurBarAmer_func.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5671448203550159}}
{"text": "function [A,B,C,D] = vibsBlockOperator(omega,U,sigma,u,cL,cT,rhoS,c0,rho0,f)\n%+========================================================================+\n%|                                                                        |\n%|                 OPENVIBS - LIBRARY FOR VIBRO-ACOUSTIC                  |\n%|           openVibs is part of the GYPSILAB toolbox for Matlab          |\n%|                                                                        |\n%| COPYRIGHT : Matthieu Aussal, Marc Bakry (c) 2017-2019.                 |\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%|             marc.bakry@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       : vibsBlockOperator.m                           |\n%|    #    |   VERSION    : 0.55                                          |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal & Marc Bakry                  |\n%|  ( # )  |   CREATION   : 14.03.2019                                    |\n%|  / 0 \\  |   LAST MODIF :                                               |\n%| ( === ) |   SYNOPSIS   :                                               |\n%|  `---'  |                                                              |\n%+========================================================================+\n\n% Constants\nmu     = rhoS*cT^2;\nlambda = rhoS*(cL^2 - 2*cT^2);\nw      = 2*pi*f;\nk      = w/c0;  \n\n% Dimension \nn = size(omega.msh.elt,2)-1;\n\n% Green kernel function\nif (n == 2)\n    Gxy         = @(X,Y) femGreenKernel(X,Y,'[H0(kr)]',k);\n    gradyGxy{1} = @(X,Y) femGreenKernel(X,Y,'grady[H0(kr)]1',k);\n    gradyGxy{2} = @(X,Y) femGreenKernel(X,Y,'grady[H0(kr)]2',k);\n    gradyGxy{3} = @(X,Y) femGreenKernel(X,Y,'grady[H0(kr)]3',k);\n    G0          = '[log(r)]';\n    gradyG0     = 'grady[log(r)]';    \n    cteGxy      = 1i/4;\n    cteG0       = -1/(2*pi);\n    \nelseif (n == 3)\n    Gxy         = @(X,Y) femGreenKernel(X,Y,'[exp(ikr)/r]',k);\n    gradyGxy{1} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]1',k);\n    gradyGxy{2} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]2',k);\n    gradyGxy{3} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]3',k);\n    G0          = '[1/r]';\n    gradyG0     = 'grady[1/r]';    \n    cteGxy      =  1/(4*pi);\n    cteG0       =  1/(4*pi);\n    \nelse\n    error('vibsNeumannBW.m : unavailable case.')\nend\n    \n% Coupling coeff for Brackage-Werner simulation\nbeta = 1i*k;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%% ELASTO-ELASTO (A11) %%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Initialization\nA = cell(n,n);\n\n% Static part\nGG = integral(omega,grad(U),grad(U));\nfor i = 1:n\n    for j = 1:n        \n        % Operator div(U):div(U)\n        DD = integral(omega,grad(U,i),grad(U,j));\n        \n        % Operator e(U):e(U)\n        EE = integral(omega,grad(U,j),grad(U,i));\n        if (i==j)\n            EE = EE + GG;\n        end\n        \n        % Summation\n        A{i,j} = lambda.*DD + mu.*EE;\n    end\nend\n\n% Dynamic part\nif (f ~= 0)\n    Id = integral(omega,U,U);\n    for i = 1:n\n       A{i,i} = A{i,i} - (rhoS*w^2) .* Id; \n    end\nend\n\n% Final form (sparse)\nA = cell2mat(A);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%% ELASTO-ACOUSTIC (A12) %%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Coupling to FEM\nB = cell(n,1);\nfor i = 1:n\n    % Collocation mass operator\n    Id = integral(sigma,ntimes(U,i),u);\n    \n    % Collocation boundary operator\n    S = cteGxy .* integral(sigma,sigma,ntimes(U,i),Gxy,u) + ...\n        cteG0  .* regularize(sigma,sigma,ntimes(U,i),G0,u);\n    \n    % Collocation boundary operator\n    D = cteGxy .* integral(sigma,sigma,ntimes(U,i),gradyGxy,ntimes(u)) + ...\n        cteG0  .* regularize(sigma,sigma,ntimes(U,i),gradyG0,ntimes(u));\n    \n    % Final operator Brackage-Werner : [1i*k*beta*S - (Id/2 + D)]\n    B{i} = beta.*S - (0.5*Id + D);\nend\n\n% Final form (full matrix)\nB = cell2mat(B);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%% ELASTO-ACOUSTIC (A21) %%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Initialization\nC = cell(1,n);\n\n% Coupling FEM \nfor i = 1:n\n    C{i} = (rho0*w^2) .* integral(sigma,u,ntimes(U,i));\nend\n\n% Final format (sparse)\nC = cell2mat(C);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%% ACOUSTIC-ACOUSTIC (A22) %%%%%%%%%%%%%%%%%%%%%%%%\n\n% Finite element mass matrix\nId = integral(sigma,u,u);\n\n% Finite element boundary operator\nH  = cteGxy .* (k^2 * integral(sigma,sigma,ntimes(u),Gxy,ntimes(u)) ...\n    - integral(sigma,sigma,nxgrad(u),Gxy,nxgrad(u)));\nHr = cteG0  .* (k^2 * regularize(sigma,sigma,ntimes(u),G0,ntimes(u)) ...\n    - regularize(sigma,sigma,nxgrad(u),G0,nxgrad(u)));\n\n% Finite element boundary operator\nD  = cteGxy .* integral(sigma,sigma,u,gradyGxy,ntimes(u));\nDr = cteG0  .* regularize(sigma,sigma,u,gradyG0,ntimes(u));\n\n% Final operator Brackage-Werner : - [1i*k*beta*(-Id/2 + Dt) - H]\nD = - (beta.*(-0.5*Id + (D+Dr).') - (H+Hr));\nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/nonRegressionTest/vibroAcoustic/vibsBlockOperator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5671308038095386}}
{"text": "function traveltime(dbName,varargin)\n\n%TRAVELTIME make travel time plots.\n% TRAVELTIME(dbName) creates travel time plots for database dbName. The top\n% plot for P and S plots ditance vs. traveltime in seconds adjusted by a\n% velocity reduction.\n%\n% TRAVELTIME(dbName,[Vp Vs]) use the specified velocities to reduce the\n% times on the travel time plots. The default values are Vp = 7 and Vs = 4.\n%\n% see also ttimes.dbload\n \n\n% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks\n% $Date$\n% $Revision$ \n\n\n% GET ARGUMENTS\nif length(varargin)==1\n    VpVs = varargin{1};\nelse\n    VpVs = [7 4];\nend\n\n\n\n% LOAD DATABASE\n[origin,site,arrival,ray] = ttimes.dbload(dbName);\n\n\n\n% TRAVEL TIME PLOTS\nfigure('Position',[0 0 1100 850],'Color','w');\nset(gcf,'DefaultAxesFontSize',14);\nset(gcf,'DefaultAxesLineWidth',0.25);\n\n\n% P WAVES\nf = find(strcmp(arrival.iphase,'P'));\nh1 = subplot(2,2,1);\nscatter(ray.flatDist(f),arrival.travelTime(f)-ray.flatDist(f)/VpVs(1),30,ray.originDepth(f),'filled','MarkerEdgeColor','k');\nhold on; box on; grid on;\nxlabel('Distance (km)');\nylabel(['Traveltime - distance/' num2str(VpVs(1)) 'km/s (s)']);\ntitle('P wave travel times');\nxlim1 = get(gca,'xlim');\nylim1 = get(gca,'ylim');\n%\nh3 = subplot(2,2,3);\nscatter(ray.flatDist(f),arrival.timeres(f),30,ray.originDepth(f),'filled','MarkerEdgeColor','k');\nhold on; box on; grid on;\nxlabel('Distance (km)');\nylabel('Time residual (s)');\ntitle('P wave travel time residuals');\nxlim3 = get(gca,'xlim');\nylim3 = get(gca,'ylim');\n\n\n% S WAVES\nf = find(strcmp(arrival.iphase,'S'));\nh2 = subplot(2,2,2);\nscatter(ray.flatDist(f),arrival.travelTime(f)-ray.flatDist(f)/VpVs(2),30,ray.originDepth(f),'filled','MarkerEdgeColor','k');\nhold on; box on; grid on;\nxlabel('Distance (km)');\nylabel(['Traveltime - distance/' num2str(VpVs(2)) 'km/s (s)']);\ntitle('S wave travel times');\nxlim2 = get(gca,'xlim');\nylim2 = get(gca,'ylim');\n%\nh4 = subplot(2,2,4);\nscatter(ray.flatDist(f),arrival.timeres(f),30,ray.originDepth(f),'filled','MarkerEdgeColor','k');\nhold on; box on; grid on;\nxlabel('Distance (km)');\nylabel('Time residual (s)');\ntitle('S wave travel time residuals');\nxlim4 = get(gca,'xlim');\nylim4 = get(gca,'ylim');\n%\nh = colorbar('Location','east');\ncmap = hot;\n%colormap(flipud(cmap));\ncolormap(cmap);\nposition = get(h,'Position');\nposition(3) = position(3)/2;\nposition(4) = position(4)/2;\nset(h,'Position',position);\nset(h,'YDir','reverse');\nset(h,'FontSize',9);\nhh = get(h,'YLabel');\nset(hh,'String','Depth (km)');\n%\nxLim = [0 max(ray.flatDist)];\nyLim12 = [ min([ylim1 ylim2]) max([ylim1 ylim2])];\nyLim34 = [ min([ylim3 ylim4]) max([ylim3 ylim4])];\nset(h1,'xlim',xLim,'ylim',yLim12);\nset(h2,'xlim',xLim,'ylim',yLim12);\nset(h3,'xlim',xLim,'ylim',yLim34);\nset(h4,'xlim',xLim,'ylim',yLim34);\n%\nset(gcf, 'paperorientation', 'landscape');\nset(gcf, 'paperposition', [.5 .5 10 7.5] );\nprint(gcf, '-dpsc2', 'FIG_tt_curve.ps');\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/contributed_antelope/traveltime_and_ray_coverage/+ttimes/tt_curve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117812622842, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.567082501113288}}
{"text": "function DEM_demo_EM\n% Dual estimation of parameters and hyperparameters; under known causes:\n% This demo focuses on conditional parameter estimation with DEM and\n% provides a comparative evaluation using EM.  This proceeds by removing\n% uncertainly about the input so that the D-step can be discounted.\n\n \n% get basic convolution model\n%==========================================================================\nM       = spm_DEM_M('convolution model');\n \n% free parameters\n%--------------------------------------------------------------------------\nP       = M(1).pE;                            % true parameters\nip      = [2 5];                              % free parameters\npE      = spm_vec(P);\npE(ip)  = 0;\nnp      = length(pE);\npE      = spm_unvec(pE,P);\npC      = sparse(ip,ip,exp(8),np,np);\nM(1).pE = pE;\nM(1).pC = pC;\n \n% free hyperparameters\n%--------------------------------------------------------------------------\nM(1).Q  = {speye(M(1).l,M(1).l)};\nM(1).R  = {speye(M(1).n,M(1).n)};\n\n% level 2\n%--------------------------------------------------------------------------\nM(2).l  = 1;                                  % inputs\nM(2).V  = exp(16);                            % very precise causes\n \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,{P},{8,32},{32});\n\n\n% invert model\n%==========================================================================\nDEM.U   = U;\nDEM     = spm_DEM(DEM);\n\n% overlay true values\n%--------------------------------------------------------------------------\nspm_DEM_qU(DEM.qU,DEM.pU)\n\n\n% EM: spm_nlsi_GN\n%==========================================================================\nG.f   =  inline('P.f*x + P.h*u','x','u','P','M');\nG.g   =  inline('P.g*x','x','u','P','M');\nG.m   =  DEM.M(1).m;\nG.n   =  DEM.M(1).n;\nG.l   =  DEM.M(1).l;\nG.x   =  DEM.M(1).x;\nG.pE  =  DEM.M(1).pE;\nG.pC  =  DEM.M(1).pC;\nG.hE  = -DEM.M(1).hE;\n \n% exogenous inputs\n%--------------------------------------------------------------------------\nGU.u  = U';\nGU.dt = 1;\n \n% data and serial correlations\n%--------------------------------------------------------------------------\nt     = ((1:N) - 1);\nK     = toeplitz(exp(-t.^2/(2*M(1).E.s^2)));\nQ     = K*K';\n \nGY.y  = DEM.Y';\nGY.X0 = DEM.X';\nGY.dt = 1;\nGY.Q  = {kron(speye(G.l,G.l),Q)};\n \n \n% EM with a Gauss-Newton-like optimization of free energy\n%==========================================================================\n[Ep,Cp,Eh,F] = spm_nlsi_GN(G,GU,GY);\n \n% parameters\n%--------------------------------------------------------------------------\nip    = [2 5];\nqP    = spm_vec(DEM.qP.P);\nqP    = qP(ip);\ntP    = spm_vec(DEM.pP.P);\ntP    = tP(ip);\npP    = spm_vec(DEM.M(1).pE);\npP    = pP(ip);\neP    = spm_vec(Ep);\neP    = eP(ip);\n \nspm_figure('GetWin','DEM');\nsubplot(2,2,4)\nbar([tP qP eP])\naxis square\nlegend('true','DEM','EM')\ntitle('parameters','FontSize',16)\n \ncq    = 1.64*sqrt(diag(DEM.qP.C(ip,ip)));\nce    = 1.64*sqrt(diag(Cp(ip,ip)));\nhold on\nfor i = 1:length(qP)\n    plot([i i],       qP(i) + [-1 1]*cq(i),'LineWidth',8,'color','r')\n    plot([i i] + 1/4, eP(i) + [-1 1]*ce(i),'LineWidth',8,'color','r')\nend\nhold off\n \n\nreturn\n\n\n% repeat for several realizations\n%==========================================================================\nclear QP EP QH EH\nfor i = 1:8\n \n    % generate new data and DEM\n    %----------------------------------------------------------------------\n    DEM     = spm_DEM_generate(M,U,{P},{8,32},{32});\n    DEM.U   = U;\n    DEM     = spm_DEM(DEM);\n \n    % EM\n    %----------------------------------------------------------------------\n    GY.y  = DEM.Y';\n    [Ep,Cp,Eh,F] = spm_nlsi_GN(G,GU,GY);\n \n    % retain parameter estimates\n    %----------------------------------------------------------------------\n    qP      = spm_vec(DEM.qP.P);\n    qP      = qP(ip);\n    eP      = spm_vec(Ep);\n    eP      = eP(ip);\n \n    QP(:,i) = qP;\n    EP(:,i) = eP;\n \n    QH(i) = DEM.qH.h{1}(1);\n    EH(i) = Eh(1);\nend\n \nspm_figure('GetWin','Figure 1');\n\nsubplot(2,1,1)\nbar(tP,'FaceColor',[1 1 1]*.9,'EdgeColor',[1 1 1]*.9)\nhold on\nplot([1 2] - 1/8,EP,'r.',[1 2] + 1/4,QP,'k.','Markersize',16)\nhold off\naxis square\nset(gca,'XLim',[0 3])\nlegend('true','EM','DEM')\ntitle('conditional estimates','FontSize',16)\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_EM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5670824987343519}}
{"text": "function u = tapas_datagen_categorical\n% This function generates categorical input data for the hgf_categorical model\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2015 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or <http://www.gnu.org/licenses/>.\n\n% First set of outcomes\nu = mnrnd(1, [0.8, 0.1, 0.1], 64);\n\n% Second set of outcomes\nu = [u; mnrnd(1, [1/3, 1/3, 1/3], 64)];\n\n% Third set of outcomes\nu = [u; mnrnd(1, [0.1, 0.1, 0.8], 64)];\n\n% Add next set of outcomes (...or don't)\n\n% Turn u into a single column of natural numbers indicating outcome category\nu = sum(u*diag([1 2 3]),2);\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_datagen_categorical.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.567082493976479}}
{"text": "function [ a_lu, pivot, rcond, z ] = r8ge_co ( n, a )\n\n%*****************************************************************************80\n%\n%% R8GE_CO factors a R8GE matrix and estimates its condition number.\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%    For the system A * X = B, relative perturbations in A and B\n%    of size EPSILON may cause relative perturbations in X of size\n%    EPSILON/RCOND.\n%\n%    If RCOND is so small that the logical expression\n%      1.0E+00 + rcond == 1.0E+00\n%    is true, then A may be singular to working precision.  In particular,\n%    RCOND is zero if exact singularity is detected or the estimate\n%    underflows.\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%    Original FORTRAN77 version by Dongarra, Bunch, Moler, Stewart.\n%    MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Dongarra, Bunch, Moler, Stewart,\n%    LINPACK User's Guide,\n%    SIAM, 1979\n%\n%  Parameters:\n%\n%    Input, integer N, the order of the matrix A.\n%\n%    Input, real A(N,N), a matrix to be factored.\n%\n%    Output, real A_LU(N,N), the LU factorization of the matrix.\n%\n%    Output, integer PIVOT(N), the pivot indices.\n%\n%    Output, real RCOND, an estimate of the reciprocal condition number of A.\n%\n%    Output, real Z(N), a work vector whose contents are usually unimportant.\n%    If A is close to a singular matrix, then Z is an approximate null vector\n%    in the sense that\n%      norm ( A * Z ) = RCOND * norm ( A ) * norm ( Z ).\n%\n\n%\n%  Compute the L1 norm of A.\n%\n  anorm = 0.0E+00;\n  for j = 1 : n\n    anorm = max ( anorm, sum ( abs ( a(1:n,j) ) ) );\n  end\n%\n%  Compute the LU factorization.\n%\n  [ a, pivot, info ] = r8ge_fa ( n, a );\n%\n%  RCOND = 1 / ( norm(A) * (estimate of norm(inverse(A))) )\n%\n%  estimate of norm(inverse(A)) = norm(Z) / norm(Y)\n%\n%  where\n%    A * Z = Y\n%  and\n%    A' * Y = E\n%\n%  The components of E are chosen to cause maximum local growth in the\n%  elements of W, where U'*W = E.  The vectors are frequently rescaled\n%  to avoid overflow.\n%\n%  Solve U' * W = E.\n%\n  ek = 1.0;\n  z(1:n) = 0.0;\n\n  for k = 1 : n\n\n    if ( z(k) ~= 0.0 )\n      ek = - r8_sign ( z(k) ) * abs ( ek );\n    end\n\n    if ( abs ( a(k,k) ) < abs ( ek - z(k) ) )\n      s = abs ( a(k,k) ) / abs ( ek - z(k) );\n      z(1:n) = s * z(1:n);\n      ek = s * ek;\n    end\n\n    wk = ek - z(k);\n    wkm = -ek - z(k);\n    s = abs ( wk );\n    sm = abs ( wkm );\n\n    if ( a(k,k) ~= 0.0 )\n      wk = wk / a(k,k);\n      wkm = wkm / a(k,k);\n    else\n      wk = 1.0;\n      wkm = 1.0;\n    end\n\n    if ( k + 1 <= n )\n\n      for j = k + 1 : n\n        sm = sm + abs ( z(j) + wkm * a(k,j) );\n        z(j) = z(j) + wk * a(k,j);\n        s = s + abs ( z(j) );\n      end\n\n      if ( s < sm )\n        t = wkm - wk;\n        wk = wkm;\n        z(k+1:n) = z(k+1:n) + t * a(k,k+1:n);\n      end\n\n    end\n\n    z(k) = wk;\n\n  end\n\n  t = sum ( abs ( z(1:n) ) );\n  z(1:n) = z(1:n) / t;\n%\n%  Solve L' * Y = W\n%\n  for k = n : -1 : 1\n\n    z(k) = z(k) + a(k+1:n,k)' * z(k+1:n)';\n\n    t = abs ( z(k) );\n\n    if ( 1.0E+00 < t )\n      z(1:n) = z(1:n) / t;\n    end\n\n    l = pivot(k);\n\n    t = z(l);\n    z(l) = z(k);\n    z(k) = t;\n\n  end\n\n  z(1:n) = z(1:n) / sum ( abs ( z(1:n) ) );\n\n  ynorm = 1.0E+00;\n%\n%  Solve L * V = Y.\n%\n  for k = 1 : n\n\n    l = pivot(k);\n\n    t = z(l);\n    z(l) = z(k);\n    z(k) = t;\n\n    z(k+1:n) = z(k+1:n) + t * a(k+1:n,k)';\n\n    if ( 1.0E+00 < abs ( z(k) ) )\n      ynorm = ynorm / abs ( z(k) );\n      z(1:n) = z(1:n) / abs ( z(k) );\n    end\n\n  end\n\n  s = sum ( abs ( z(1:n) ) );\n  z(1:n) = z(1:n) / s;\n  ynorm = ynorm / s;\n%\n%  Solve U * Z = V.\n%\n  for k = n : -1 : 1\n\n    if ( abs ( a(k,k) ) < abs ( z(k) ) )\n      s = abs ( a(k,k) ) / abs ( z(k) );\n      z(1:n) = s * z(1:n);\n      ynorm = s * ynorm;\n    end\n\n    if ( a(k,k) ~= 0.0E+00 )\n      z(k) = z(k) / a(k,k);\n    else\n      z(k) = 1.0E+00;\n    end\n\n    z(1:k-1) = z(1:k-1) - z(k) * a(1:k-1,k)';\n\n  end\n%\n%  Normalize Z in the L1 norm.\n%\n  s = 1.0E+00 / sum ( abs ( z(1:n) ) );\n  z(1:n) = s * z(1:n);\n  ynorm = s * ynorm;\n\n  if ( anorm ~= 0.0E+00 )\n    rcond = ynorm / anorm;\n  else\n    rcond = 0.0E+00;\n  end\n\n  return\nend\n", "meta": {"author": "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_co.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5670677681296624}}
{"text": "function [X,mP,spmP] = tor_get_physio(varargin)\n% :Usage:\n% ::\n%\n%     [X,mP,spmP] = tor_get_physio([mP],[spmP],[nvoxels],[doortho])\n% arguments are optional, but you must enter them in this order.\n%\n% Tor Wager 10/21/02\n%\n% Get nuisance covariates likely to be related to physiological noise and head motion\n% The algorithm:\n%\n% The program extracts raw/preprocessed image data from the ventricles (CSF space), as\n% defined by a mask denoting which voxels are CSF for that subject.  \n% Either all voxels or a randomly selected subset [nvoxels] is subjected to\n% principal components analysis, to determine regular patters of drift over time\n% and across voxels.  Those patterns are expected to be related to global signal drift,\n% head movement, and physiological noise, and are assumed to be UNrelated to the task\n% of interest, by virtue of the fact that they occur in the ventricles.\n% \n% PCA is done twice on the timeseries' of CSF voxels.  The first time, PCA is done\n% on the sums of squared values (not the correlations) of voxel timeserieses across\n% the entire experiment, mean-centered based on the whole experiment.  Most of the\n% coherent variation in this case is expected to be due to head movement and changes\n% in shims/gradients/etc. from run to run.  The SS values are used because we want to\n% weight the voxels with the highest variation most heavily, as they are presumably\n% picking up most of this signal.  The first 3 eigenvariates (canonical timeseries)\n% are saved.\n%\n% Following, a separate, second PCA is done on the correlation matrix of data\n% within each session.  Session data for each voxel are mean-centered and scaled\n% relative to the session (variance of each voxel = 1).  We do this because \n% physiological noise-related signals may produce periodic signals of different\n% magnitudes in different voxels, and we want to extract the most coherent signals\n% we can within each session.  So these eigenvariates are expected to reflect\n% primarily noise related to physiology (heart rate, respiration).  Up to 5 eigenvariates\n% for each session are saved (nothing with eigenvalue < 1 is saved).\n%\n% Next, the CSF-related nuisance covariates (eigenvariates from PCA) are combined\n% with existing nuisance covariates and intercept columns from the existing \n% design matrix (SPMcfg xX).  The proportion of variance in each predictor of interest\n% explained by this nuisance basis set is calculated using regression, and the\n% nuisance covariates are orthogonalized with respect to each predictor of interest.\n% There are good and bad results of this step.  The bad is that any signal that \n% tracks the predictors is attributed to the task, not to noise, even if it's actually\n% caused by physiological artifact.  So the orthogonalized basis set does not\n% protect you from physiology or movement-related false positives.  However,\n% the nuisance covariates are also unlikely to reduce power in estimating you effects\n% of interest.  More importantly, it avoids false positives created when one \n% predictor (A) is more highly correlated with the nuisance covariates than another\n% (B).  In practice, betas for A will tend to be smaller than B, given the same\n% actual response to both, and a random effects analysis on A-B will produce\n% false positive activations.  Orthogonalization of the nuisance set precludes this.\n%\n% :Inputs:\n%\n%   **mP:**\n%        CSF mask image file.  *_seg3.img output from SPM is appropriate\n%        should be in same space and have same dims as functionals\n%        but automatic reslicing is done if necessary.\n%\n%   **spmP:**\n%        name (full path name preferred) of SPMcfg.mat file to use\n%        This contains the design matrix and raw/preproc image file names to use.\n% \n%   **nvoxels:**\n%        Number of CSF voxels to use in PCA analysis\n%        More than 100 can be very slow and memory intensive.\n%        Fewer than 100 voxels loads a different way, and may be slower.\n%        Best is probably between 100 - 1000.  800 runs pretty fast.\n%\n%   **doortho:**\n%        Orthogonalize nuisance covariates with respect to regs of interest\n%        This assumes that any signal that covaries with the task is, in fact,\n%        due to the task, so it gives you some bias towards finding positive results.\n%        However, the alternative is that nuisance covariates may soak up variance\n%        related to the task, and you'll miss activations.\n%        In addition, if some regressors are more colinear with the nuisance set,\n%        you can create false \"activations\" when comparing these regressors to other\n%        ones.  This problem exists whether or not we choose to model nuisance \n%        covariates.  One solution is to use the ortho when doing random effects analyses,\n%        as the sign and magnitude of nuisance-related activations would not be expected to be\n%        the same across subjects unless the variance was really task-related.\n%        Default is 1, or \"yes, do orthogonalization.\"\n%\n% for functions called, see this .m file.\n%\n% :Examples:\n% ::\n%\n%    % get filenames for SPMcfg files and CSF mask for each subject\n%    cd C:\\Tor_Documents\\CurrentExperiments\\intext2\\RESULTS\\model1\n%    spmP = get_filename('sub*','SPMcfg.mat');\n%    cd C:\\Tor_Documents\\CurrentExperiments\\intext2\\\n%    mP = get_filename('sub*','anatomy/nscalped_f*seg3.img');\n%    % Now run:\n%    for i = 1:size(mP,1)  \n%        tor_get_physio(mP(i,:),spmP(i,:),300);  % 300 voxels\n%        pause(10); close all\n%    end\n\n% :Functions called:\n%   - spm functions: spm_get, etc.\n%   - timeseries2.m\t(for < 100 voxels)\n%   - read_hdr.m\t(big-little endian dependent; validate for your data)\n%   - timeseries3.m\t(for > 100 voxels; uses SPM's image reading)\n%   - reslice_imgs.m\n%   - mask2voxel.m \t(only if ind2sub.m from Matlab is not found)\n\n\nCSFprob = .95;      % this is the value a voxel in the mask img must have to be considered\n                    % an 'on' value.\n                    % if using SPM segmentation output (e.g., *_seg3) for the mask,\n                    % this is something like the prob. of being in CSF\n                    % low thresholds will result in HUGE eigenvalue problems\n                    % and memory difficulties.\n\nmypwd = pwd;\nt1 = clock;\n\n% ----------------------------------------------------------------------------------\n% * set up input arguments\n% ----------------------------------------------------------------------------------\n\nif length(varargin) > 0\n    mP = varargin{1};\nelse\n    % mask filename\n    mP = spm_get(1,'*img','Select CSF mask for this subject.');\nend\nif isempty(mP), mP = spm_get(1,'*img','Select CSF mask for this subject.');, end\n\nif length(varargin) > 1    \n    spmP = varargin{2};\nelse\n    spmP = spm_get(Inf,'SPMcfg.mat','Choose SPMcfg.mat file for this subject or Done to skip.');\nend\n\nif length(varargin) > 2, srand = varargin{3};, else, srand = 0;, end\n\nif length(varargin) > 3, doortho = varargin{4};, else, doortho = 1;, end\n\n% ----------------------------------------------------------------------------------\n% * cd to SPM results directory so we can write output file there\n% ----------------------------------------------------------------------------------\nd = fileparts(spmP);\neval(['cd ' d])\n\ndiary physio_nuisance_covariates.out\n\n% ----------------------------------------------------------------------------------\n% * load SPMcfg.mat file, which contains all relevant info except mask image\n% ----------------------------------------------------------------------------------\n\n        load(spmP)\n        nsess = length(Sess);\n        P = str2mat(VY.fname);\n\tif ~(exist(deblank(P(1,:))) == 2)\n\t\tdisp(['Looking for: ' P(1,:)])\n\t\tdisp(['Can''t find original img files!! Please specify.'])\n\t\tP = spm_get(Inf,'*.img','Select raw image files.');\n\t\tVY = spm_vol(P);\n\t\tdisp(['VY has been modified!!! Using: ' P(1,:)])\n\tend\n        for i = 1:length(Sess), nimgs(i) = size(Sess{i}.row,2);,end\n        \n%  [nsess] = spm_input_ui('Enter number of runs, or 0 to choose SPM.mat file [recommended]',.1,'i',[],1);\n\n\n% ----------------------------------------------------------------------------------\n% * reslice the CSF mask if necessary, to be in space of functionals!\n% ----------------------------------------------------------------------------------\n\nmV = spm_vol(mP);\npV = spm_vol(P(1,:));\nif any(mV.dim(1:3) - pV.dim(1:3)) | any(any(pV.mat(1:3,1:3) - mV.mat(1:3,1:3)))\n    [d f e] = fileparts(mP); reslice_imgs(P(1,:),mP,0);\n    mP = fullfile(d,['r' f e]);\n    disp(['Resliced mask to space of functionals: ' mP])\n    mV = spm_vol(mP);\nend\n\n% ----------------------------------------------------------------------------------\n% * load and check mask\n% ----------------------------------------------------------------------------------\n\nmv = spm_read_vols(mV); mv = mv > CSFprob;\nfprintf(1,'\\nCSF mask has %3.0f voxels out of %3.0f total.\\t',sum(mv(:)),prod(size(mv)))\ntry\n    % if we have the right toolbox...\n    [x y z] = ind2sub(size(mv),find(mv)); [XYZ] = [x y z];\ncatch\n    disp('elmat toolbox function ind2sub not found; using SLOWER version mask2voxel.m')\n    XYZ = mask2voxel(mv);\nend\n\ntmp = sum(sum(mv)); \nif ~findobj('Tag','Graphics'), spm fmri; figure(findobj('Tag','Graphics'));,end\nif ~findobj('Tag','Interactive'), spm fmri;,end\n%imagesc(mv(:,:,find(tmp == max(tmp)))); colormap gray; warning off; title([mP]), warning on,;drawnow\nspm_check_registration(str2mat(mP,P(1,:)));\n\nif sum(tmp) > 100, \n    disp(['More than 100 CSF voxels in mask - this may be computationally intensive!'])\n    % if srand is not entered as an input argument, prompt.\n    if ~srand, \n        figure(findobj('Tag','Interactive'))\n        srand = spm_input_ui('Enter n vox to use, or 0 for all',.1,'i',[],1);, \n    end\n    if srand > sum(tmp), \n\tdisp(['More voxels requested than available at threshold ' num2str(CSFprob) ': using ' num2str(max(tmp))])\n\tsrand = sum(tmp);\n    end\n\nelse\n    srand = 0;\nend\n\nif srand\n    wh = rand(size(XYZ,1),1) * size(XYZ,1);\n    wh2 = sort(wh); wh2 = wh2(1:srand);\n    for i = 1:srand, XYZ2(i,:) = XYZ(find(wh == wh2(i)),:);, end\n    XYZ = XYZ2;\nend\n\n% ----------------------------------------------------------------------------------\n% * Load images and mask with CSF\n% ----------------------------------------------------------------------------------\n% M1 is unscaled timeseries over all sessions; eigs computed over whole experiment\n% M2 is timeseries scaled within each session; (cell array)\n%   eigs are computed within session\n\nfprintf(1,'\\nEigenvariates based on %3.0f voxels \\t',size(XYZ,1))\nfprintf(1,'\\nLoading volumes, extracting voxels, and scaling \\t')\n\nwh = [0 cumsum(nimgs)];\nM1 = [];\nM2 = [];\n\nif size(XYZ,1) < 101\n    % this is super slow for large n!\n    ts = timeseries2('multi',P,struct('coords',XYZ));\n    M1 = ts.indiv;\n    \n    % adjust M2 to mean 0 var 1\n    for j = 1:size(M1,2)\n        for i = 1:nsess\n            ind = wh(i)+1:wh(i+1);\n            M2{i}(:,j) = (M1(ind,j) - mean(M1(ind,j))) ./ std(M1(ind,j));\n        end\n    end\n    \n    \n    \nelse\n    \n\n\nfor i = 1:nsess\n    subP = P(wh(i)+1:wh(i+1),:);\n    fprintf(1,'.')\n    ts = timeseries3(XYZ,subP);\n    \n    % save 2 matrices, one for session-mean centered and scaled and one uncentered (until overall mean is known)\n    M1 = [M1;ts.all_data];\n    \n    for j = 1:size(ts.all_data,2)\n        % center and scale to variance = 1\n        ts.all_data(:,j) = (ts.all_data(:,j) - mean(ts.all_data(:,j))) ./ std(ts.all_data(:,j));\n    end\n    M2{i} = [ts.all_data];\nend\n\nend\n\nfprintf(1,'Done.\\n')\n\n% ----------------------------------------------------------------------------------\n% * Mean-center first (unscaled) timeseries and check for NaN or Inf values\n% ----------------------------------------------------------------------------------\nfor i = 1:size(M1,2)\n    M1(:,i) = M1(:,i) - mean(M1(:,i));\nend\n\nex = any(isnan(M1) | isinf(M1)) | all(M1 == 0);\nif any(ex)\n\tdisp(['WARNING! NaN or Inf values for ' num2str(sum(ex)) ' voxels in timeseries!!  Mis-registration of funct and anatomy?'])\n\tM1(:,find(ex)) = [];\nend\n\nfigure;imagesc(M1); title('Overall timeseries (y) for all voxels (x)')\n\n\n% ----------------------------------------------------------------------------------\n% * Find Principal Components overall\n% ----------------------------------------------------------------------------------\nfprintf(1,'\\nPrincipal components overall ') \n[eigvec,eigval] = eig(M1'*M1);\neigvec = eigvec(:,end-2:end);\nX = M1 * eigvec;\nfor i = 1:size(X,2), X(:,i) = (X(:,i) - mean(X(:,i))) ./ std(X(:,i));, end\nfigure;subplot 221; plot(eigvec); title('Weights on original variables (=voxels) == eigenvectors')\nsubplot 222; plot(X),title('Components (X * v)')\nlegend({'Comp 3' 'Comp 2' 'Comp 1'},0)\n    subplot 223; bar(diag(eigval));, title('Scree plot for eigenvalues')\n    \n    xx = abs(fft(X)); xxx = (1:size(xx,1)) ./ (xX.RT * size(xx,1));\n    subplot 224; plot(xxx(1:round(length(xx)./2)),xx(1:round(length(xx)./2),:));, title('FFT of components')\n    xlabel('Frequency (Hz)')\ndrawnow\n\n% ----------------------------------------------------------------------------------\n% * Find Principal Components for each session\n% ----------------------------------------------------------------------------------\nwh = [0 cumsum(nimgs)];\n\nfor i = 1:nsess\n    fprintf(1,'\\nPrincipal components for session %1.0f',i) \n\n    ex = any(isnan(M2{i}) | isinf(M2{i}));\n    if any(ex)\t\n\tdisp('')\n\tdisp(['WARNING! NaN or Inf values for ' num2str(sum(ex)) ' voxels in sess ' num2str(i) '!!  Mis-registration of funct and anatomy?'])\n\tM2{i}(:,find(ex)) = [];\n    end\n\n    [eigvec,eigval] = eig(corrcoef(M2{i}));\n    fprintf(1,'\\t%3.0f eigenvalues > 1\\t',sum(diag(eigval) > 1))\n        \n    num2save = min(sum(diag(eigval)>1),5);    % save at most 5 eigenvalues from this session\n    eigvec = eigvec(:,end-num2save+1:end);\n    X2 = M2{i} * eigvec;\n    for j = 1:size(X2,2), X2(:,j) = (X2(:,j) - mean(X2(:,j))) ./ std(X2(:,j));, end\n    \n    figure;subplot 221; plot(eigvec); title(['Weights (eigenvectors) for session ' num2str(i)])\n    subplot 222; plot(X2),title('Components (X * v)')\n    subplot 223; bar(diag(eigval));, title('Scree plot for eigenvalues')\n    \n    xx = abs(fft(X2)); xxx = (1:size(xx,1)) ./ (xX.RT * size(xx,1));\n    subplot 224; plot(xxx(1:round(length(xx)./2)),xx(1:round(length(xx)./2),:));, title('FFT of components')\n    xlabel('Frequency (Hz)')\n    \n    drawnow\n    \n    % pad with zeros to get in the right session\n    zbef = zeros(wh(i),size(X2,2));\n    X2 = [zbef; X2];\n    zaft = zeros(size(X,1) - size(X2,1),size(X2,2));\n    X2 = [X2; zaft];\n    \n    X = [X X2];\nend\n    \nX(:,end+1:end+length(xX.iB)) = xX.X(:,xX.iB); % add the nuisance covariates already in xX\n\n\n\n% ----------------------------------------------------------------------------------\n% * Correlate / Regress design vectors on components\n% ----------------------------------------------------------------------------------\npx = X * pinv(X);\nfprintf(1,'\\n Variation in predictors explained by nuisance covariates before orthogonalization')\nfprintf(1,'\\n Differences among predictors could create false activations without orthogonalization.')\n\nfor i = 1:length(xX.iC)\n    r = xX.X(:,xX.iC(i)) - px * xX.X(:,xX.iC(i));       % residuals\n    pve = 1 - ((r' * r) ./ (xX.X(:,xX.iC(i))' * xX.X(:,xX.iC(i)))); % percentage of variance explained\n    fprintf(1,'\\n%s\\t%3.2f%%',xX.Xnames{xX.iC(i)},100*pve)\nend\n\n\n\n% ----------------------------------------------------------------------------------\n% * Orthogonalize components (?) \n% This isn't a good idea from the standpoint of misattributing noise variance to signal\n% but it will prevent artifactual activations based on differential correlations with\n% nuisance subspace among conditions.  Lesser of two evils?\n% ----------------------------------------------------------------------------------\n\nif doortho\n\tfprintf(1,'\\n Orthogonalizing nuisance covariates wrt model and scaling')\n\tmX = xX.X(xX.iC); mX(:,end+1) = 1;\n\tpx = mX * pinv(mX);\n\n\tfor i = 1:size(X,2)\n    \tX(:,i) = X(:,i) - px * X(:,i);                      % residuals\n    \tif ~(std(X(:,i)) == 0)\n    \t\tX(:,i) = (X(:,i) - mean(X(:,i))) ./ std(X(:,i));    % re-scale\n    \tend\n\tend\n\n\tfigure; imagesc(X); colormap gray; title('Found and orthogonalized nuisance covariates')\n\tXn = X; save Nuisance_covariates Xn\nelse\n\tfigure; imagesc(X); colormap gray; title('Found nuisance covariates')\n\tXn = X; save Nuisance_covariates_ortho Xn\nend\n\n\n\n% modify SPMcfg.mat\n% just don't do this, it gets messy.  \n% Better to just add them by loading Nuisance_covariates\n% and entering as user-spec regressors.\n% add_nuisance_to_SPMcfg(Xn);\n\n\nfprintf(1,'\\n Total running time is %3.2f s.\\n',etime(clock,t1))\neval(['cd ' mypwd])\n\ndiary off\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/diagnostics/tor_get_physio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5670629296324481}}
{"text": "function varargout = drawPolyhedron(nodes, faces, varargin)\n%DRAWPOLYHEDRON Draw polyhedron defined by vertices and faces\n%\n%   drawPolyhedron(NODES, FACES)\n%   Draws the polyhedron defined by vertices NODES and the faces FACES. \n%   NODES is a NV-by-3 array containing coordinates of vertices, and FACES\n%   is either a NF-by3 or NF-by-4 array containing indices of vertices of\n%   the triangular or rectangular faces.\n%   FACES can also be a cell array, in the content of each cell is an array\n%   of indices to the nodes of the current face. Faces can have different\n%   number of vertices.\n%   \n%   H = drawPolyhedron(...);\n%   Also returns a handle to the created patche.\n%\n%   Example:\n%   [n f] = createSoccerBall;\n%   drawPolyhedron(n, f);\n%\n%   See also:\n%   polyhedra, drawMesh, drawPolygon\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 10/02/2005.\n%\n\n%   HISTORY\n%   07/11/2005 update doc.\n%   04/01/2007 typo\n%   18/01/2007 add support for 2D polyhedra (\"nodes\" is N-by-2 array), and\n%       make 'cnodes' a list of points instead of a list of indices\n%   14/08/2007 add comment, add support for NaN in faces (complex polygons)\n%   14/09/2007 rename as drawPolyhedron\n%   16/10/2008 better support for colors\n%   27/07/2010 copy to 'drawMesh'\n\n\n%% Initialisations\n\n\n% process input arguments\nswitch length(varargin)\n    case 0 \n        % default color is red\n        varargin = {'facecolor', [1 0 0]};\n    case 1\n        % use argument as color for faces\n        varargin = {'facecolor', varargin{1}};\n    otherwise\n        % otherwise do nothing\nend\n\n% overwrites on current figure\nhold on;\n\n% if nodes are 2D points, add a z=0 coordinate\nif size(nodes, 2) == 2\n    nodes(1,3) = 0;\nend\n\n\n%% main loop : for each face\n\nif iscell(faces)\n    % array FACES is a cell array\n    h = zeros(length(faces(:)), 1);\n\n    for f = 1:length(faces(:))\n        % get nodes of the cell\n        face = faces{f};\n\n        if sum(isnan(face))~=0\n            % Special processing in case of multiple polygonal face.\n            % each polygonal loop is separated by a NaN.\n            \n            % find indices of loops breaks\n            inds = find(isnan(face));\n            \n            % replace NaNs by index of first vertex of each polygon\n            face(inds(2:end))   = face(inds(1:end-1)+1);\n            face(inds(1))       = face(1);\n            face(length(face)+1)= face(inds(end)+1);            \n        end\n        \n        % draw current face\n        cnodes  = nodes(face, :);\n        h(f)    = patch(cnodes(:, 1), cnodes(:, 2), cnodes(:, 3), [1 0 0]);\n    end\n\nelse\n    % array FACES is a NC*NV indices array, with NV : number of vertices of\n    % each face, and NC number of faces\n    h = zeros(size(faces, 1), 1);\n    for f = 1:size(faces, 1)\n        % get nodes of the cell\n        cnodes = nodes(faces(f,:)', :);\n        h(f) = patch(cnodes(:, 1), cnodes(:, 2), cnodes(:, 3), [1 0 0]);\n    end\nend\n\n% set up drawing options\nif ~isempty(varargin)\n    set(h, varargin{:});\nend\n\n% format output parameters\nif nargout > 0\n    varargout = {h};\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/meshes3d/drawPolyhedron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.5669337911582258}}
{"text": "%% Copyright (C) 2014, 2016, 2019 Colin B. Macdonald\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see <http://www.gnu.org/licenses/>.\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defmethod  @@sym repmat (@var{A}, @var{n}, @var{m})\n%% @defmethodx @@sym repmat (@var{A}, [@var{n} @var{m}])\n%% Build symbolic block matrices.\n%%\n%% Examples:\n%% @example\n%% @group\n%% repmat([1 2 sym(pi)], 2, 3)\n%%   @result{} (sym 2\u00d79 matrix)\n%%       \u23a11  2  \u03c0  1  2  \u03c0  1  2  \u03c0\u23a4\n%%       \u23a2                         \u23a5\n%%       \u23a31  2  \u03c0  1  2  \u03c0  1  2  \u03c0\u23a6\n%%\n%% repmat(sym(pi), [1 3])\n%%   @result{} (sym) [\u03c0  \u03c0  \u03c0]  (1\u00d73 matrix)\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/vertcat, @@sym/horzcat}\n%% @end defmethod\n\n\nfunction B = repmat(A, n, m)\n\n  if (nargin == 2)\n    m = n(2);\n    n = n(1);\n  elseif (nargin == 3)\n    % no-op\n  else\n    print_usage ();\n  end\n\n  cmd = { '(A, n, m) = _ins'\n          'if n == 0 or m == 0:'\n          '    return sp.Matrix(n, m, [])'\n          'if A is None or not A.is_Matrix:'\n          '    A = sp.Matrix([A])'\n          'L = [A]*m'\n          'B = sp.Matrix.hstack(*L)'\n          'L = [B]*n'\n          'B = sp.Matrix.vstack(*L)'\n          'return B' };\n\n  B = pycall_sympy__ (cmd, sym(A), int32(n), int32(m));\n\nend\n\n\n%!test\n%! % simple\n%! syms x\n%! A = [x x x; x x x];\n%! assert (isequal (repmat(x, 2, 3), A))\n\n%!test\n%! % block cf double\n%! A = [1 2 3; 4 5 6];\n%! B = sym(A);\n%! C = repmat(A, 2, 3);\n%! D = repmat(B, 2, 3);\n%! assert (isequal (C, D))\n\n%!test\n%! % empty\n%! A = repmat(sym([]), 2, 3);\n%! assert (isempty(A));\n%! assert (isequal (size(A), [0 0]))\n\n%!test\n%! % more empties\n%! A = repmat(sym(pi), [0 0]);\n%! assert (isequal (size(A), [0 0]))\n%! A = repmat(sym(pi), [0 3]);\n%! assert (isequal (size(A), [0 3]))\n%! A = repmat(sym(pi), [2 0]);\n%! assert (isequal (size(A), [2 0]))\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/repmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.5669337794534043}}
{"text": "function DEM_demo_ALAP\n% This demonstration is essentially the same as DEM_demo_LAP - however\n% here, we compare two generalised filtering schemes that are implemented\n% very differently: the first integrates the generative process in\n% parallel with the inversion, while the standard spm_LAP scheme inverts a\n% model given pre-generated data. The advantage of generating and modelling\n% data  contemporaneously is that it allows the inversion scheme to couple\n% back to the generative process through action (see active inference\n% schemes): spm_ALAP.\n%__________________________________________________________________________\n% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: DEM_demo_ALAP.m 7679 2019-10-24 15:54:07Z spm $\n \n% get basic convolution model\n%==========================================================================\nM       = spm_DEM_M('convolution model');\n\n% gradient functions for speed (not implemented here)\n%--------------------------------------------------------------------------\n% M(1).fx = inline('P.f','x','v','P');\n% M(1).fv = inline('P.h','x','v','P');\n% M(1).gx = inline('P.g','x','v','P');\n% M(1).gv = inline('sparse(4,1)','x','v','P');\n\nM(1).E.nN = 8;                                 % number of E steps\nM(1).E.nE = 8;                                 % number of E steps\nM(1).E.nD = 1;                                 % number of time steps\nM(1).E.s  = 1;                                 % smoothness\nG(1).E.s  = 1;                                 % smoothness\nM(1).E.d  = 2;                                 % order\nM(1).E.n  = 6;                                 % order\n\n \n% free parameters\n%--------------------------------------------------------------------------\nP       = M(1).pE;                             % true parameters\nip      = [1 2 5 9];                           % free parameters\npE      = spm_vec(P);\nnp      = length(pE);\npE(ip)  = 0;\npE      = spm_unvec(pE,P);\npC      = sparse(ip,ip,exp(4),np,np);\nM(1).pE = pE;\nM(1).pC = pC;\n \n% free hyperparameters\n%--------------------------------------------------------------------------\nM(1).Q  = {speye(M(1).l,M(1).l)};\nM(1).R  = {speye(M(1).n,M(1).n)};\nM(1).hE = 8;\nM(1).gE = 6;\nM(1).hC = 1/4;\nM(1).gC = 1/4;\n \n% generative process\n%==========================================================================\nG(1).f  = M(1).f;\nG(1).g  = M(1).g;\nG(1).x  = M(1).x;\nG(1).V  = exp(8);\nG(1).W  = exp(6);\nG(1).pE = P;\n\nG(2).v  = 0;\nG(2).V  = exp(16);\n\n\n% hidden cause\n%-------------------------------------------------------------------------- \nN      = 32;\nU      = exp(-((1:N) - 12).^2/(2.^2));\n\n% invert\n%==========================================================================\nDEM.M  = M;\nDEM.G  = G;\nDEM.C  = U;\n\n% generate and filter responses\n%-------------------------------------------------------------------------- \nLAP    = spm_ALAP(DEM);\n\n% filter generated responses\n%-------------------------------------------------------------------------- \nDEM.Y  = LAP.Y;\nDEM.pU = LAP.pU;\nDEM.pP = LAP.pP;\nDEM    = spm_LAP(DEM);\n\n \n% Show results for LAP (standard scheme)\n%==========================================================================\nspm_figure('GetWin','Figure 1: Generalised filtering - standard scheme');\n \n% overlay true values\n%--------------------------------------------------------------------------\nspm_DEM_qU(DEM.qU,DEM.pU)\n \n% parameters\n%--------------------------------------------------------------------------\nqP    = spm_vec(DEM.qP.P);\nqP    = qP(ip);\ntP    = spm_vec(DEM.pP.P);\ntP    = tP(ip);\n \nsubplot(2,2,4)\nbar([tP qP])\naxis square\nlegend('true','GF - standard')\ntitle('parameters','FontSize',16)\n \ncq    = 1.64*sqrt(diag(DEM.qP.C(ip,ip)));\nfor i = 1:length(qP),hold on\n    plot([i i] + 1/8,qP(i) + [-1 1]*cq(i),'LineWidth',4,'color','r')\nend, hold off\n \n \n% Show results for ALAP (parallel scheme)\n%==========================================================================\nspm_figure('GetWin','Figure 2: Generalised filtering - parallel scheme');\n \n% overlay true values\n%--------------------------------------------------------------------------\nspm_DEM_qU(LAP.qU,LAP.pU)\n \n% parameters\n%--------------------------------------------------------------------------\nqP    = spm_vec(LAP.qP.P);\nqP    = qP(ip);\ntP    = spm_vec(LAP.pP.P);\ntP    = tP(ip);\n \nsubplot(2,2,4)\nbar([tP qP])\naxis square\nlegend('true','GF - parallel')\ntitle('parameters','FontSize',16)\n \ncq    = 1.64*sqrt(diag(LAP.qP.C(ip,ip)));\nfor i = 1:length(qP),hold on\n    plot([i i] + 1/8,qP(i) + [-1 1]*cq(i),'LineWidth',4,'color','r')\nend, hold off\n \n% Compare\n%==========================================================================\nspm_figure('GetWin','Figure 3: Comparison of integration schemes');\n \n% hyperparameters\n%--------------------------------------------------------------------------\nqL    = spm_vec({LAP.qH.h LAP.qH.g});\nqD    = spm_vec({DEM.qH.h DEM.qH.g});\nvL    = spm_vec({LAP.qH.V LAP.qH.W});\nvD    = spm_vec({DEM.qH.V DEM.qH.W});\nqh    = log([G(1).V; G(1).W]);\n \n \nsubplot(2,2,1)\nbar([qh qL qD])\naxis square\nlegend('true','parallel','standard')\ntitle('log-precisions','FontSize',16)\n \ncq    = 1.64*sqrt(vL);\nfor i = 1:length(qL),hold on\n    plot([i i] + 0,qL(i) + [-1 1]*cq(i),'LineWidth',4,'color','r')\nend, hold off\n \ncq    = 1.64*sqrt(vD);\nfor i = 1:length(qD),hold on\n    plot([i i] + 1/4,qD(i) + [-1 1]*cq(i),'LineWidth',4,'color','r')\nend, hold off\n \n% Log-evidence\n%--------------------------------------------------------------------------\nsubplot(2,2,2)\nnL   = length(LAP.F);\nnD   = length(DEM.F);\nplot(1:nL,LAP.F,1:nD,DEM.F)\naxis square\nlegend('parallel (F)','standard (F)')\ntitle('log-evidence ','FontSize',16)\nxlabel('iteration','FontSize',12)\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_ALAP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5669337700321295}}
{"text": "X=randn(64,200);\nY=randn(200,20000)';\n\ntic\nXYt=mexCalcXYt(X,Y);\nt=toc;\nfprintf('mex-file time: %fs\\n',t);\n\n\ntic\nXYt2=X*Y';\nt=toc;\nfprintf('matlab-file time: %fs\\n',t);\n\nsum((XYt(:)-XYt2(:)).^2)\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/AMICO/SPAMS/test_release/test_CalcXYt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5668983999886105}}
{"text": "function imgOut = ConvertXYZtoIPT(img, inverse)\n%\n%       imgOut = ConvertXYZtoIPT(img, inverse)\n%\n%\n%        Input:\n%           -img: image to convert from XYZ to IPT or from IPT to XYZ.\n%           -inverse: takes as values 0 or 1. If it is set to 1 the\n%                     transformation from XYZ to IPT is applied, otherwise\n%                     the transformation from IPT to XYZ.\n%\n%        Output:\n%           -imgOut: converted image in XYZ or IPT.\n%\n%     Copyright (C) 2011  Francesco Banterle\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n% \n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n%\n\nif(inverse == 0)   \n    imgLMS = ConvertXYZtoLMS(img, 0);\n    \n    imgOut = ConvertLMStoIPT(imgLMS, 0);\n    \nelse\n    imgLMS = ConvertLMStoIPT(img, 1);\n    \n    imgOut = ConvertXYZtoLMS(imgLMS, 1);\nend\n            \nend\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/ColorSpace/ConvertXYZtoIPT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5668983899836473}}
{"text": "classdef SOP_F23 < PROBLEM\n% <single> <real> <expensive/none>\n% Shekel's family\n\n%------------------------------- Reference --------------------------------\n% X. Yao, Y. Liu, and G. Lin, Evolutionary programming made faster, IEEE\n% Transactions on Evolutionary Computation, 1999, 3(2): 82-102.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 1;\n            obj.D = 4;\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = zeros(1,obj.D) + 10;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            a = [4 4 4 4;1 1 1 1;8 8 8 8;6 6 6 6;3 7 3 7;2 9 2 9;5 5 3 3;8 1 8 1;6 2 6 2;7 3.6 7 3.6];\n            c = [0.1;0.2;0.2;0.4;0.4;0.6;0.3;0.7;0.5;0.5];\n            PopObj = zeros(size(PopDec,1),1);\n            for i = 1 : size(PopDec,1)\n                PopObj(i) = -sum(1./(sum((repmat(PopDec(i,:),10,1)-a).^2,2)+c));\n            end\n        end\n        %% Generate the minimum objective value\n        function R = GetOptimum(obj,N)\n            R = -10.54;\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/Single-objective optimization/Simple SOPs/SOP_F23.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7057850340255385, "lm_q1q2_score": 0.5668680451901766}}
{"text": "function [modes, weights,centerId] = calcComponents(SO3F,varargin)\n% heuristic to find modal orientations\n%\n% Syntax\n%   [modes, volume] = calcComponents(SO3F)\n%   [modes, volume, centerId] = calcComponents(SO3F,'seed',ori)\n%\n% Input\n%  SO3F - @SO3Fun \n%  ori - initial list of @orientation\n%\n% Output\n%  modes     - modal @orientation\n%  volume    - volume of the component\n%  centerId  - list of ids to which each initial ori converged to\n%\n% Options\n%  resolution - search-grid resolution\n%  angle      - maximum component width used for volume computation\n%  exact      - do not dismiss very small modes at the end\n%\n% See also\n% SO3Fun/max\n\n% extract options\nmaxIter = get_option(varargin,'maxIter',100);\nres = get_option(varargin,'resolution',0.05*degree);\nomega = 1.5.^(-7:1:4) * degree;\nomega(omega<res) = [];\nomega = [0,omega];\ntol = get_option(varargin,'tolerance',0.5*degree);\nmaxAngle = get_option(varargin,{'radius','angle'},inf);\n\n% initial seed\nif check_option(varargin,'seed')\n  seed = reshape(get_option(varargin,'seed'),[],1);\n  weights = get_option(varargin,'weights',SO3F.eval(seed));\nelseif isa(SO3F,'SO3FunRBF')\n  seed = SO3F.center;\n  weights = SO3F.weights; \nelse\n  seed = equispacedSO3Grid(SO3F.CS,SO3F.SS,'resolution',2.5*degree);\n  weights = ones(length(seed),1) ./ length(seed);\nend\nid = weights>0;\nseed = reshape(seed(id),[],1);\nweights = weights(id);\nweights = weights ./ sum(weights);\n\ncenterId = 1:length(seed);\nmodes = seed;\n\n% join orientations if possible\n%[modes,~,id2] = unique(modes,'tolerance',tol);\n%centerId = id2(centerId);\n%weights = accumarray(id2,weights);\n\nfinished = false(size(modes));\n\nG = SO3F.grad;\n\nfor k = 1:maxIter\n  progress(k,maxIter,' finding ODF components: ');\n\n  % gradient\n  g = normalize(G.eval(modes(~finished)),1);\n  \n  % prepare for linesearch\n  line_ori = exp(repmat(modes(~finished),1,length(omega)),g * omega);\n  \n  % evaluate along lines\n  line_v = SO3F.eval(line_ori);\n  \n  % take the maximum\n  [v_max(~finished),id] = max(line_v,[],2);\n    \n  % update orientions\n  modes(~finished) = line_ori(sub2ind(size(line_ori),(1:length(g)).',id));\n  \n  %nnz(id>1)\n  if all(id == 1), break; end\n\n  % join orientations if possible\n  [~,~,id2] = unique(modes,'tolerance',tol);\n\n  modes = modes(maxVote(id2,v_max(~finished)));\n\n  centerId = id2(centerId);\n  finished = accumarray(id2,finished,[],@any);\n  if maxAngle == inf, weights = accumarray(id2,weights); end\n  length(modes);\n\nend\n\n% accumulate only weights that are sufficiently close to the centers\nif maxAngle < inf\n  inRadius = angle(seed,modes(centerId))<maxAngle;\n  weights = accumarray(centerId(inRadius), weights(inRadius));\nend\n\n% sort components according to volume\n[weights,id] = sort(weights,'descend');\nmodes = modes(id);\niid(id) = 1:length(id);\ncenterId = iid(centerId);\n\nif ~check_option(varargin,'exact')\n  id = weights > min([0.01, numSym(SO3F.CS) * maxAngle^3 ./ 8*pi^2,0.5 * max(weights)]);  \n  weights = weights(id);\n  modes = modes(id);\n  ids = 1:length(id);\n  centerId(ismember(centerId,ids(~id))) = 0;\nend\n  \n% weights = [2 1 5 3 4] -> [1 2 3 4 5]\n% id -> [2 1 5 3 4]\n% centerId = 3 -> 5 \nend\n\nfunction test\n% testing code\n \ncs = crystalSymmetry('432');\ncs2 = specimenSymmetry;\ncenter = orientation.rand(5,cs,cs2);\nodf = unimodalODF(center,'halfwidth',5*degree)\nori = discreteSample(odf,2000);\nodf2 = calcDensity(ori,'noFourier','exact','halfwidth',2.5*degree)\n\n\ncs2 = crystalSymmetry('432')\ncenter = orientation.rand(5,cs,cs2);\nodf = unimodalODF(center,'halfwidth',2.5*degree)\nori = discreteSample(odf,1000);\nodf2 = calcDensity(ori,'noFourier','exact','halfwidth',3*degree)\n\n\n[modes,vol,cId] = odf2.calcComponents;\n\nfor i = 1:length(modes)\n  plot(ori(cId==i),'axisAngle')\n  hold on\n  plot(modes(i),'MarkerFaceColor','k','MarkerSize',10)\nend\nhold off\n\nmin(angle_outer(modes,center) ./ degree)\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/SO3Fun/@SO3Fun/calcComponents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.566868038539819}}
{"text": "function vl_structuredNetwork_pairwiseModel_test_derivative\n%vl_structuredNetwork_pairwiseModel_test_derivative tests vl_structuredNetwork_pairwiseModel\n\n% create the following file from the variables of cnn_train_pairwiseModel.m right before the call of vl_structuredNetwork_pairwiseModel.m\nload( 'vl_structuredNetwork_pairwiseModel_test_derivative.mat', 'net', 'im', 'gradients', 'labels', 'one' );\ntestEps = 1e-3;\n\nfprintf('Computing the gradient ... ');\ntStart = tic;\n[lossValue, gradients, predictions] = vl_structuredNetwork_pairwiseModel(net, im, gradients, labels, one, ...\n    'conserveMemory', true, ...\n    'sync', true, ...\n    'disableDropout', true ) ;\nfprintf( '%f\\n', toc(tStart) );\n\nmaxGroupTests = 100;\nrng(1);\n\n% test derivatives\nfor iLayer = length( net.layers ) : -1 : 1\n    if ~isequal( net.layers{iLayer}.type, 'conv' )\n        continue;\n    end\n    fprintf('Layer %d: %s\\n', iLayer, net.layers{iLayer}.name);\n    \n    empiricalDerivative = zeros( numel(gradients{ iLayer }.dzdw{2}), 1, 'like', gradients{ iLayer }.dzdw{2});\n    fprintf('Number of bias derivatives: %d\\n', numel(empiricalDerivative));\n    \n    randOrder = randperm(numel(empiricalDerivative));\n    numTests = min( numel(empiricalDerivative), maxGroupTests);\n    for iValueIndex = 1 : numTests\n        if mod(iValueIndex, 1000) == 0\n            fprintf('Derivative #%d\\n', iValueIndex);\n        end\n        iValue = randOrder(iValueIndex);\n        \n        initValue = net.layers{iLayer}.weights{2}(iValue);\n        net.layers{iLayer}.weights{2}(iValue) = initValue + testEps;\n        \n        [lossValue_test, ~, predictions_test] = vl_structuredNetwork_pairwiseModel(net, im, gradients, labels, [], ...\n            'conserveMemory', true, ...\n            'sync', true, ...\n            'disableDropout', true) ;\n        \n        empiricalDerivative(iValue) = sum(lossValue_test - lossValue) / testEps;\n        \n        net.layers{iLayer}.weights{2}(iValue) = initValue;\n    end\n    \n    testIndices = randOrder(1 : numTests);\n    emphiricalGradient = empiricalDerivative(testIndices);\n    computedGradient = gradients{ iLayer }.dzdw{2}(testIndices);\n    derivativeError = gather( norm(emphiricalGradient(:) - computedGradient(:)) / norm(computedGradient(:)) );\n    \n    fprintf('Relative error of bias derivatives: %f\\n', derivativeError );\n    fprintf('Norm of tested derivatives: %f\\n', norm(computedGradient(:)) );\n    \n    \n    \n    empiricalDerivative = zeros( numel(gradients{ iLayer }.dzdw{1}), 1, 'like', gradients{ iLayer }.dzdw{1});\n    fprintf('Number of filter derivatives: %d\\n', numel(empiricalDerivative));\n    \n    randOrder = randperm(numel(empiricalDerivative));\n    numTests = min( numel(empiricalDerivative), maxGroupTests);\n    for iValueIndex = 1 : numTests\n        if mod(iValueIndex, 1000) == 0\n            fprintf('Derivative #%d\\n', iValueIndex);\n        end\n        \n        iValue = randOrder(iValueIndex);\n        \n        initValue = net.layers{iLayer}.weights{1}(iValue);\n        net.layers{iLayer}.weights{1}(iValue) = initValue + testEps;\n        \n        [lossValue_test, ~, predictions_test] = vl_structuredNetwork_pairwiseModel(net, im, gradients, labels, [], ...\n            'conserveMemory', true, ...\n            'sync', true, ...\n            'disableDropout', true) ;\n        \n        empiricalDerivative(iValue) = sum(lossValue_test - lossValue) / testEps;\n        \n        net.layers{iLayer}.weights{1}(iValue) = initValue;\n    end\n    \n    testIndices = randOrder(1 : numTests);\n    emphiricalGradient = empiricalDerivative(testIndices);\n    computedGradient = gradients{ iLayer }.dzdw{1}(testIndices);\n    derivativeError = gather( norm(emphiricalGradient(:) - computedGradient(:)) / norm(computedGradient(:)) );\n    \n    fprintf('Relative error of filter derivatives: %f\\n', derivativeError );\n    fprintf('Norm of tested derivatives: %f\\n', norm(computedGradient(:)) );\n    \nend\n\n\nend\n\n", "meta": {"author": "aosokin", "repo": "cnn_head_detection", "sha": "80624e7a25c62f7b504fa6f4d830136beb66eec8", "save_path": "github-repos/MATLAB/aosokin-cnn_head_detection", "path": "github-repos/MATLAB/aosokin-cnn_head_detection/cnn_head_detection-80624e7a25c62f7b504fa6f4d830136beb66eec8/pairwiseModel/vl_structuredNetwork_pairwiseModel_test_derivative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5668680352492506}}
{"text": "function PlotMesh(coordinates,nodes)\n%--------------------------------------------------------------------------\n% Code written by : Siva Srinivas Kolukula                                |\n%                   Senior Research Fellow                                |\n%                   Structural Mechanics Laboratory                       |\n%                   Indira Gandhi Center for Atomic Research              |\n%                   India                                                 |\n% E-mail : allwayzitzme@gmail.com                                         |\n%          http://sites.google.com/site/kolukulasivasrinivas/             |    \n%--------------------------------------------------------------------------\n%--------------------------------------------------------------------------\n% Purpose:\n%         To plot the Finite Element Method Mesh\n% Synopsis :\n%           PlotMesh(coordinates,nodes)\n% Variable Description:\n%           coordinates - The nodal coordinates of the mesh\n%           -----> coordinates = [node X Y] \n%           nodes - The nodal connectivity of the elements\n%           -----> nodes = [node1 node2......]    \n%--------------------------------------------------------------------------\n\nnel = length(nodes) ;                  % number of elements\nnnode = length(coordinates) ;          % total number of nodes in system\nnnel = size(nodes,2);                % number of nodes per element\n% \n% Initialization of the required matrices\nX = zeros(nnel,nel) ;\nY = zeros(nnel,nel) ;\n\nfor iel=1:nel   \n     for i=1:nnel\n     nd(i)=nodes(iel,i);         % extract connected node for (iel)-th element\n     X(i,iel)=coordinates(nd(i),1);    % extract x value of the node\n     Y(i,iel)=coordinates(nd(i),2);    % extract y value of the node\n     end\nend\n    \n% Plotting the FEM mesh, diaplay Node numbers and Element numbers\n     f1 = figure ;\n     set(f1,'name','Mesh','numbertitle','off','Color','w') ;\n     fill(X,Y,'w')\n     \n     title('Finite Element Mesh') ;\n     axis off ;\n     \n% To disply the node numbers     \n%      k = nodes(:,1:end);\n%      nd = k' ;\n%     for i = 1:nel\n%         text(X(:,i),Y(:,i),int2str(nd(:,i)),'fontsize',8,'color','k');\n%         text(sum(X(:,i))/4,sum(Y(:,i))/4,int2str(i),'fontsize',10,'color','r') ;\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/32029-plate-bending/Plate Bending/PlotMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5667911450561777}}
{"text": "function varargout=lomb(varargin)\n%\n% [Pxx,F]=lomb(x,dcOffset,smooth)\n%\n%    Wrapper to WFDB LOMB:\n%         http://www.physionet.org/physiotools/wag/lomb-1.htm\n%\n% Transforms a real-valued time series 'x' into a power spectrum 'X', using a \n% technique known as the Lomb periodogram. The input is a Nx2 matrix containing \n% a sampled time series, presented as two columns of numbers (the sample times \n% in the first column and the sample values in the second). The intervals between \n% consecutive samples need not be uniform.  \n%\n%Input Parameters:\n% x    \n%       Nx2 vector of doubles. First column is sample time index (in\n%       seconds), and second column is the sample value of the signal at\n%       that time.\n%\n% dcOffset (Optional)\n%       Booelan. If present add constant to input samples ( x(:,2) ), such that the mean\n%       values of the time series is zero (default=1).\n%\n% smooth   (Optional)\n%       Boolean String specifying the if the output should be smoothed (default =1).\n% \n%\n%Output Parameters:\n%\n%Pxx \n%       Mx1 Double. Estimated power spectrum.\n%\n%F \n%       Mx1 Double. Frequency of the estimated power spectrum (Hz).\n%\n%\n% CITING CREDIT: To credit this function, please cite the following paper at your work:\n%\n%Moody, G.B.\n%    Spectral analysis of heart rate without resampling. Computers in Cardiology 1993, pp. 715-718 (IEEE Computer Society Press, 1993). http://www.physionet.org/physiotools/lomb/lomb.html . \n%\n%\n%Additional References:\n%Lomb, N.R.\n%    Least-squares frequency analysis of unequally spaced data. Astrophysics and Space Science 39:447-462 (1976). \n%Press, W.H, and Rybicki, G.B.\n%    Fast algorithm for spectral analysis of unevenly sampled data. Astrophysical J. 338:277-280 (1989). \n%Press, W.H. Teukolsky, S.A., Vetterling, W.T., and Flannery, B.P.\n%    Numerical Recipes in C: the Art of Scientific Computing, pp. 575-584 (Cambridge Univ. Press, 1992). \n%Moody, G.B.\n%    Spectral analysis of heart rate without resampling. Computers in Cardiology 1993, pp. 715-718 (IEEE Computer Society Press, 1993). http://www.physionet.org/physiotools/lomb/lomb.html . \n%\n%\n%\n% MATLAB wrapper written by Ikaro Silva, 2013\n% Last Modified: -\n% Version 1.0\n% Since 0.9.0 \n%\n%\n% %Example: Heart Rate Spectral Analysis:\n% [tm, signal]=rdsamp('mitdb/100',1);\n% [ann]=rdann('mitdb/100','atr');\n% [Pxx,F]=lomb([tm(ann) signal(ann)]);\n% plot(F,Pxx);grid on;hold on\n%\n% See also RDANN, TACH, SQRS, WQRS\n\n%endOfHelp\n\npersistent javaWfdbExec\nif(isempty(javaWfdbExec))\n    javaWfdbExec=getWfdbClass('lomb');\nend\n\n%Set default pararamter values\n%[Pxx,F]\ninputs={'x','dcOffset','smooth'};\ndcOffset=1;\nsmooth=1;\nfor n=1:nargin\n    if(~isempty(varargin{n}))\n        eval([inputs{n} '=varargin{n};'])\n    end\nend\n\nwfdb_argument={'-P'};\n\nif(dcOffset)\n     wfdb_argument{end+1}='-z';\nend\nif(smooth)\n     wfdb_argument{end+1}='-s';\nend\n\nwfdb_argument{end+1}='-';\ndel=repmat([' '],size(x(:,1)));\ndata=[num2str(x(:,1)) del num2str(x(:,2))];\njavaWfdbExec.setArguments(wfdb_argument);\npxx=char(javaWfdbExec.execWithStandardInput(cellstr(data)));\npxx=sscanf(pxx(2:end-1), '%f %f,');\n\nvarargout{1}=pxx(2:2:end);\nvarargout{2}=pxx(1:2:end);\n\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/Sleep_ECG/lomb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.566791142503403}}
{"text": "function w = wave2gray(c, s, scale, border)\n%WAVE2GRAY Display wavelet decomposition coefficients.\n%   W = WAVE2GRAY(C, S, SCALE, BORDER) displays and returns a\n%   wavelet coefficient image.\n%\n%   EXAMPLES:\n%     wave2gray(c, s);                      Display w/defaults.\n%     foo = wave2gray(c, s);                Display and return.\n%     foo = wave2gray(c, s, 4);             Magnify the details.\n%     foo = wave2gray(c, s, -4);            Magnify absolute values.\n%     foo = wave2gray(c, s, 1, 'append');   Keep border values.\n%\n%   INPUTS/OUTPUTS:\n%     [C, S] is a wavelet decomposition vector and bookkeeping\n%     matrix.\n%\n%     SCALE       Detail coefficient scaling\n%     ----------------------------------------------------------\n%     0 or 1      Maximum range (default)\n%     2,3...      Magnify default by the scale factor\n%     -1, -2...   Magnify absolute values by abs(scale)\n%     \n%     BORDER      Border between wavelet decompositions\n%     ----------------------------------------------------------\n%     'absorb'    Border replaces image (default)\n%     'append'    Border increases width of image\n%     \n%     Image W:   ------- ------ ------------ -------------------\n%                |      |      |            |\n%                | a(n) | h(n) |            |\n%                |      |      |            |\n%                ------- ------     h(n-1)  |\n%                |      |      |            |\n%                | v(n) | d(n) |            |        h(n-2)\n%                |      |      |            |\n%                ------- ------ ------------\n%                |             |            |        \n%                |    v(n-1)   |   d(n-1)   |\n%                |             |            |\n%                -------------- ------------ -------------------\n%                |                          |\n%                |          v(n-2)          |        d(n-2) \n%                |                          |\n%     \n%     Here, n denotes the decomposition step scale and a, h, v, d are\n%     approximation, horizontal, vertical, and diagonal detail\n%     coefficients, respectively.\n\n%   Copyright 2002-2004 R. C. Gonzalez, R. E. Woods, & S. L. Eddins\n%   Digital Image Processing Using MATLAB, Prentice-Hall, 2004\n%   $Revision: 1.6 $  $Date: 2003/11/21 15:01:44 $\n\n% Check input arguments for reasonableness.\nerror(nargchk(2, 4, nargin));\n \nif (ndims(c) ~= 2) | (size(c, 1) ~= 1)\n  error('C must be a row vector.');   end\n  \nif (ndims(s) ~= 2) | ~isreal(s) | ~isnumeric(s) | (size(s,2) ~= 2)\n  error('S must be a real, numeric two-column array.');   end\n  \nelements = prod(s, 2);\nif (length(c) < elements(end)) | ...\n      ~(elements(1) + 3 * sum(elements(2:end - 1)) >= elements(end))\n   error(['[C S] must be a standard wavelet ' ...\n          'decomposition structure.']); \nend\n\nif (nargin > 2) & (~isreal(scale) | ~isnumeric(scale))\n   error('SCALE must be a real, numeric scalar.'); \nend\n \nif (nargin > 3) & (~ischar(border))\n  error('BORDER must be character string.');  \nend\n\nif nargin == 2 \n   scale = 1;  % Default scale. \nend          \n\nif nargin < 4 \n   border = 'absorb';  % Default border.\nend   \n  \n% Scale coefficients and determine pad fill.\nabsflag = scale < 0;\nscale = abs(scale);   \nif scale == 0 \n   scale = 1; \nend\n\n[cd, w] = wavecut('a', c, s);   w = mat2gray(w);\ncdx = max(abs(cd(:))) / scale;\nif absflag \n   cd = mat2gray(abs(cd), [0, cdx]);   fill = 0;\nelse \n   cd = mat2gray(cd, [-cdx, cdx]);   fill = 0.5;   \nend\n  \n% Build gray image one decomposition at a time.\nfor i = size(s, 1) - 2:-1:1\n   ws = size(w);\n   \n   h = wavecopy('h', cd, s, i);\n   pad = ws - size(h);     frontporch = round(pad / 2);\n   h = padarray(h, frontporch, fill, 'pre');\n   h = padarray(h, pad - frontporch, fill, 'post');\n   \n   v = wavecopy('v', cd, s, i);\n   pad = ws - size(v);     frontporch = round(pad / 2);\n   v = padarray(v, frontporch, fill, 'pre');\n   v = padarray(v, pad - frontporch, fill, 'post');\n   \n   d = wavecopy('d', cd, s, i);\n   pad = ws - size(d);     frontporch = round(pad / 2);\n   d = padarray(d, frontporch, fill, 'pre');\n   d = padarray(d, pad - frontporch, fill, 'post');\n   \n   % Add 1 pixel white border.\n   switch lower(border)\n   case 'append'\n      w = padarray(w, [1 1], 1, 'post');    \n      h = padarray(h, [1 0], 1, 'post');\n      v = padarray(v, [0 1], 1, 'post');\n   case 'absorb'\n      w(:, end) = 1;   w(end, :) = 1;   \n      h(end, :) = 1;   v(:, end) = 1;\n   otherwise\n      error('Unrecognized BORDER parameter.');\n   end\n   \n   w = [w h; v d];                 % Concatenate coefs.\nend\n\nif nargout == 0 \n   imshow(w);                      % Display result.\nend", "meta": {"author": "61--", "repo": "weiyanmin", "sha": "e15a7789602ec65c7ce1972bd905826ff4851435", "save_path": "github-repos/MATLAB/61---weiyanmin", "path": "github-repos/MATLAB/61---weiyanmin/weiyanmin-e15a7789602ec65c7ce1972bd905826ff4851435/Matlab/wave2gray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.5667911367294484}}
{"text": "function [ X, Y ] = plot_fun ( )\n\n%*****************************************************************************80\n%\n%% PLOT_FUN demonstrates MATLAB's SPMD command for parallel programming.\n%\n%  Discussion:\n%\n%    Each worker computes X and Y data for a portion of a sine curve.\n%\n%    The client patches the composite data into numeric arrays and\n%    returns that as the function output.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    27 March 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Output, real X(N,100), Y(N,100), the data, stored as N vectors.\n%\n\n%\n%  Set a list of colors that will be cycled through with each\n%  plot command.\n%\n  spmd\n    a = 2 * pi * ( labindex - 1 ) / numlabs;\n    b = 2 * pi *   labindex       / numlabs;\n    x = linspace ( a, b, 100 );\n    y = sin ( x );\n    fprintf ( 1, '  Lab %d works on [%f,%f].\\n', labindex, a, b );\n  end\n%\n%  Copy the composite data from the workers, and\n%  convert it into numeric arrays.\n%\n%  (Only client data can be returned as output arguments!)\n%\n  n = matlabpool ( 'size' );\n\n  X = [];\n  Y = [];\n\n  for i = 1 : n\n    X = [ X; x{i} ];\n    Y = [ Y; y{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/plot_spmd/plot_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5667911356557215}}
{"text": "function determ = pds_random_determinant ( n, key )\n\n%*****************************************************************************80\n%\n%% PDS_RANDOM_DETERMINANT returns the determinant of the PDS_RANDOM matrix.\n%\n%  Discussion:\n%\n%    This routine will only work properly if the SAME value of SEED\n%    is input that was input to PDS_RANDOM.\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, integer N, the order of A.\n%\n%    Input, integer KEY, a positive value that selects the data.\n%\n%    Output, real DETERM, the determinant.\n%\n  seed = key;\n  [ lambda, seed ] = r8vec_uniform_01 ( n, seed );\n\n  determ = prod ( lambda(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/pds_random_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5667911237024907}}
{"text": "%Question No:5\n%IDEAL LOW-PASS FILTER\n\nfunction idealfilter(X,P)\nf=imread(X);\n[M,N]=size(f);\nF=fft2(double(f));\nu=0:(M-1);\nv=0:(N-1);\nidx=find(u>M/2);\nu(idx)=u(idx)-M;\nidy=find(v>N/2);\nv(idy)=v(idy)-N;\n[V,U]=meshgrid(v,u);\nD=sqrt(U.^2+V.^2);\nH=double(D<=P);\nG=H.*F;\ng=real(ifft2(double(G)));\nimshow(f),figure,imshow(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/13586-ideal-low-pass-filter/idealfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5667395962240757}}
{"text": "function [ts_smooth] = circ_smoothTS(varargin)\n% USAGE\n% [ts_smooth] = circ_smoothTS(varargin)\n%\n% Given a timeseries input of circular data, this function smooths over the\n% desired number of bins and returns a circularly smooth timeseries\n%\n% INPUTS\n%   \n%   ts         a time series of circular data\n%   nBins      integer number of bins you would like to smooth over\n%   method     string argument that determines the smoothing method,\n%              options are 'median', 'mean' [default: 'median']\n%   exclude    vector of values in ts to exclude from smoothing (can be\n%              used to exclude 0 values)\n%\n% OUTPUTS\n%\n%   ts_smooth  a time series vector of smoothed circular data\n%\n% HELP\n%\n% Written by David Tingley, 2017\n% TODO error handling when nBins > 1/2 ts\n\np = inputParser;\naddRequired(p,'ts',@isvector);\naddRequired(p,'nBins',@isnumeric);\naddParameter(p,'method','median',@isstr)\naddParameter(p,'exclude',[],@isvector);\n\nparse(p,varargin{:});\n\nts = p.Results.ts;\nif size(ts,1) == 1;\n    ts = ts';\nend\n\nnBins = p.Results.nBins;\nmethod = p.Results.method;\nexclude = p.Results.exclude;\n\nif length(exclude) == length(ts)\n   ts_smooth = ts;\n   return\nend\nif nBins == 1\n    ts_smooth = ts;\n    return\nend\n\nif ~isempty(exclude)\n    list = find(ts==exclude);\n    ts(list) = nan;\nend\n\nexclude = find(isnan(ts));\nkeep = find(~isnan(ts));\n\nf = find(diff(keep)<nBins);\nff = find(diff(keep)>=nBins);\nif ~isempty(ff)\n    ff(end+1) = length(keep);  % include last ts \nend\nif length(keep) == 0\n    ts(isnan(ts))=0;\n    ts_smooth = ts;\n    return\nend\n\nts_smooth = zeros(length(ts),1);\n\nfor i =1:length(ff)  % populate list with single spikes that occur sparsely\n    if keep(ff(i))>ceil(nBins/2) & keep(ff(i))+ceil(nBins/2) < length(ts) % prevents negative indices from being added\n        ts_smooth(keep(ff(i))-ceil(nBins/2):keep(ff(i))+ceil(nBins/2)) = ts(keep(ff(i)));\n    elseif keep(ff(i))+ceil(nBins/2) < length(ts) \n        ts_smooth(1:keep(ff(i))+ceil(nBins/2)) = ts(keep(ff(i)));    \n    elseif keep(ff(i))>ceil(nBins/2) \n        ts_smooth(keep(ff(i))-ceil(nBins/2):end) = ts(keep(ff(i)));\n    end\nend \n\nfor i=1:length(f) % populate list with spikes that occur within smoothing window\n    ind = (keep(f(i))-ceil(nBins/2):keep(f(i))+ceil(nBins/2));\n    ind(ind<1) = [];\n    ind(ind>length(ts)) = [];\n    keep = [keep; ind'];\n%     if keep(f(i)) > ceil(nBins/2) & keep(f(i)+1)+ceil(nBins/2) < length(ts) % prevents negative indices from being added\n%         keep = [keep; [keep(f(i))-ceil(nBins/2):keep(f(i)+1)+ceil(nBins/2)]'];\n%     elseif ~(keep(f(i)) > ceil(nBins/2)) &  keep(f(i)+1)+ceil(nBins/2) < length(ts) \n%         keep = [keep; [ceil(nBins/2) + 1:keep(f(i)+1)+ceil(nBins/2)]'];    \n%     elseif keep(f(i)) > ceil(nBins/2) & ~(keep(f(i)+1)+ceil(nBins/2) < length(ts))\n%         keep = [keep; [keep(f(i))-ceil(nBins/2):length(ts)- ceil(nBins/2)]'];    \n%     end\nend\n\nkeep = sort(unique(keep));\n% keep(keep>0)=[];\n\n%% start smoothing\nfor ii = 1:length(keep)\n    i = keep(ii);\n    ind = (i-ceil(nBins/2):i+ceil(nBins/2));\n    ind(ind<1) = [];\n    ind(ind>length(ts)) = [];\n    [loc] = ~ismember(ind,exclude);\n    \n%     if ~isempty(loc) & sum(loc) > 0\n        \n        if strcmp(method,'median')\n                ts_smooth(i) = circ_median(ts(ind(loc)));\n        elseif strcmp(method,'mean')\n                ts_smooth(i) = circ_mean(ts(ind(loc)));\n        elseif strcmp(method,'gaussian')\n                g = gauss(length(ind),1)';\n                ts_smooth(i) = circ_mean(ts(ind(loc)),g(loc));\n%                 ts_smooth(i) = circ_mean(ts(ind(loc)));\n        elseif strcmp(method,'interp')\n                error('interp not implented yet...')\n        else\n                error('couldnt find smoothing method')\n        end\n%     else\n%         ts_smooth(ind) = ts(i);    \n%     end\n    \nend\n\nts_smooth(isnan(ts_smooth)) = 0;\n% there's a lot of indexing going on, so let's double check the returned\n% time series didn't change length...\nif length(ts_smooth) ~= length(ts)\n   error('output TS is the wrong length!') \nend\n\n\n\n\n\n\n\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/CircularStats/circ_smoothTS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650247, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5667395879731457}}
{"text": "% SP_L2_ERROR: Evaluate the error in L^2 norm.\n%\n%   errl2 = sp_l2_error (space, msh, u, uex)\n%\n% INPUT:\n%\n%   space: object defining the space of discrete functions (see sp_vector)\n%   msh:   object defining the domain partition and the quadrature rule (see msh_cartesian)\n%   u:     vector of dof weights\n%   uex:   function handle to evaluate the exact solution\n%\n% OUTPUT:\n%\n%     errl2:  error in L^2 norm\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 Octave; see the file COPYING.  If not, see\n% <http://www.gnu.org/licenses/>.\n\nfunction errl2 = sp_l2_error (space, msh, u, uex)\n\n  if (numel(u) ~= space.ndof)\n    error ('Wrong size of the vector of degrees of freedom')\n  end\n\n  errl2 = 0;\n  \n  for iel = 1:msh.nel_dir(1)\n    msh_col = msh_evaluate_col (msh, iel);\n    sp_col  = sp_evaluate_col (space, msh_col, 'value', true, 'gradient', false);\n    \n    errl2 = errl2 + (sp_l2_error (sp_col, msh_col, u, uex)).^2;\n  end\n  \n  errl2 = sqrt (errl2);\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_vector/sp_l2_error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5667395849698923}}
{"text": "function pde = LinearFun2HM(am,ap,bm,bp,kappa,r,x0,y0,z0)\n%% USAGE: polynomial solution for Poisson equation\n%  Last Modified: 02/21/2020 by Xu Zhang\n\n%% PDE Structure\npde = struct('intf',@intf,...\n    'exactu1',@exactu1,'exactu2',@exactu2,'exactu3',@exactu3,...\n    'um1',@um1,'um2',@um2,'um3',@um3,'up1',@up1,'up2',@up2,'up3',@up3,...\n    'Dxu',@Dxu,'Dxum',@Dxum,'Dxup',@Dxup,'Dyu',@Dyu,...\n    'Dyum',@Dyum,'Dyup',@Dyup,'Dzu',@Dzu,'Dzum',@Dzum,'Dzup',@Dzup,...\n    'f1',@f1,'f2',@f2,'f3',@f3,...\n    'fm1',@fm1,'fm2',@fm2,'fm3',@fm3,...\n    'fp1',@fp1,'fp2',@fp2,'fp3',@fp3,...\n    'A',@A,'Am',@Am,'Ap',@Ap,'one',@one,...\n    'B',@B,'Bm',@Bm,'Bp',@Bp);\n\npde.bm = bm;\npde.bp = bp;\npde.am = am;\npde.ap = ap;\npde.kappa = kappa;\n%% interface function\n    function u = intf(x,y,z)\n        u = ((x-x0).^2 + (y-y0).^2 + (z-z0).^2).^(1/2)/r-1;\n    end\n\n%% exact solution\n    function u = exactu1(x,y,z)\n        u = um1(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = up1(x(id),y(id),z(id));\n    end\n    function u = exactu2(x,y,z)\n        u = um2(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = up2(x(id),y(id),z(id));\n    end\n    function u = exactu3(x,y,z)\n        u = um3(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = up3(x(id),y(id),z(id));\n    end\n    function u = um1(x,y,z)\n        u = 2*(x-x0)/bm;\n    end\n    function u = um2(x,y,z)\n        u = 2*(y-y0)/bm;\n    end\n    function u = um3(x,y,z)\n        u = 2*(z-z0)/bm;\n    end\n    function u = up1(x,y,z)\n        u = 2*(x-x0)/bp;\n    end\n    function u = up2(x,y,z)\n        u = 2*(y-y0)/bp;\n    end\n    function u = up3(x,y,z)\n        u = 2*(z-z0)/bp;\n    end\n\n%% Boundary Function\n    function u = gD1(x,y,z)\n        u = exactu1(x,y,z);\n    end\n    function u = gD2(x,y,z)\n        u = exactu2(x,y,z);\n    end\n    function u = gD3(x,y,z)\n        u = exactu3(x,y,z);\n    end\n%% Derivative of the exact solution\n    function u = Dxu(x,y,z)\n        u = Dxum(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Dxup(x(id),y(id),z(id));\n    end\n    function u = Dyu(x,y,z)\n        u = Dyum(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Dyup(x(id),y(id),z(id));\n    end\n    function u = Dzu(x,y,z)\n        u = Dzum(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Dzup(x(id),y(id),z(id));\n    end\n    function u = Dxum(x,y,z)\n        u = zeros(size(x));\n    end\n    function u = Dyum(x,y,z)\n        u = zeros(size(x));\n    end\n    function u = Dzum(x,y,z)\n        u = zeros(size(x));\n    end\n    function u = Dxup(x,y,z)\n        u = zeros(size(x));\n    end\n    function u = Dyup(x,y,z)\n        u = zeros(size(x));\n    end\n    function u = Dzup(x,y,z)\n        u = zeros(size(x));\n    end\n\n    function u = Duker(x,y,z)\n        u = zeros(size(x));\n    end\n\n%% right hand side function\n    function u = f1(x,y,z)\n        u = fm1(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = fp1(x(id),y(id),z(id));\n    end\n    function u = f2(x,y,z)\n        u = fm2(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = fp2(x(id),y(id),z(id));\n    end\n    function u = f3(x,y,z)\n        u = fm3(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = fp3(x(id),y(id),z(id));\n    end\n\n    function u = fm1(x,y,z)\n        u = -2*(x-x0)*kappa;\n    end\n    function u = fm2(x,y,z)\n        u = -2*(y-y0)*kappa;\n    end\n    function u = fm3(x,y,z)\n        u = -2*(z-z0)*kappa;\n    end\n    function u = fp1(x,y,z)\n        u = -2*(x-x0)*kappa;\n    end\n    function u = fp2(x,y,z)\n        u = -2*(y-y0)*kappa;\n    end\n    function u = fp3(x,y,z)\n        u = -2*(z-z0)*kappa;\n    end\n\n%% Diffusion coefficient function\n    function u = A(x,y,z)\n        u = Am(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Ap(x(id),y(id),z(id));\n    end\n    function u = Am(x,y,z)\n        u = am*ones(size(x));\n    end\n    function u = Ap(x,y,z)\n        u = ap*ones(size(x));\n    end\n%% Mass coefficient function\n    function u = B(x,y,z)\n        u = Bm(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Bp(x(id),y(id),z(id));\n    end\n    function u = Bm(x,y,z)\n        u = bm*ones(size(x));\n    end\n    function u = Bp(x,y,z)\n        u = bp*ones(size(x));\n    end\n\n%% Other function\n    function u = one(x,y,z)\n        u = ones(size(x));\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/research/IVEM/ExampleFun/LinearFun2HM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5667309766237095}}
{"text": "function [X, info] = IRirn(A, b, varargin)\n% IRirn Least squares solver with 1-norm penalization term\n%\n% options  = IRirn('defaults')\n% [X,info] = IRirn(A,b)\n% [X,info] = IRirn(A,b,K)\n% [X,info] = IRirn(A,b,options)\n% [X,info] = IRirn(A,b,K,options)\n%\n% Iteratively reweighted norm algorithm for computing a 1-norm penalized \n% solution. \n%\n% IRirn is a simplified driver for IRrestart, which uses an inner-outer \n% iteration scheme. Semi-convergent or hybrid iterative solvers are used \n% in the inner iterations, using one of the iterative methods in IRtools \n% (e.g., IRhybrid_lsqr). In the case of IRirn, the 1-norm penalization \n% is updated at each outer iteration. \n%\n% The regularization parameter and number of inner iterations influence\n% the behavior and convergence of the outer iterations.\n%\n% With 'defaults' as input returns the default options.  Otherwise outputs\n% the iterates specified in K, using max(K) as MaxIter, and using all other\n% default options.  With options as input: uses the user-specified options\n% and all the other default options.\n%\n% Inputs:\n%  A : either (a) a full or sparse matrix\n%             (b) a matrix object that performs the matrix*vector operation\n%             (c) user-defined function handle\n%  b : right-hand side vector\n%  K : (optional) integer vector that specifies which (total) iterates are \n%      returned in X; the maximum number of iterations is assumed to be max(K)\n%      [ positive integer | vector of positive components ]\n%  options : structure with the following fields (optional)\n%      x0            - initial guess for the iterations; default = zero vector\n%                      [ array | {'none'} ]\n%      MaxIterIn     - maximum number of inner iterations\n%      MaxIterOut    - maximum number of outer iterations\n%      x_true        - true solution; allows us to returns error norms with\n%                      respect to x_true at each iteration\n%                      [ array | {'none'} ]\n%      RegParam      - a value or a method to find the regularization used\n%                      in the inner iterations: \n%                      [ non-negative scalar | {'gcv'} | 'discrep' ]\n%                      This also determines which stopping rule is used for\n%                      the inner iterations.\n%                      If 'gcv' is chosen, the inner iteration is stopped\n%                        when the GCV function minimum stabilizes or increases \n%                        within a certain window of iterations (see 'stopGCV',\n%                        'FlatTol' and 'MinTol').\n%                      If 'discrep' is chosen, and NoiseLevel is provided,\n%                        then the discrepancy principle is used as stopping\n%                        criterion (see 'NoiseLevel' and 'eta').\n%      stopGCV       - stopping criterion for the inner iterations when\n%                      GCV is used\n%                      [ GCVvalues | {'resflat'} ]\n%      FlatTol       - tolerance for detecting flatness (stabilization)\n%                      in the GCV function as a stopping criterion for the\n%                      inner iterations\n%                      [ {10^-6} | non-negative scalar ]\n%      MinTol        - window of iterations: if the GCV minimum continues\n%                      to increase over this window, then the inner\n%                      iterations are stopped\n%                      [ {3} | positive integer ]\n%      RegMatrix     - priorconditioner for the inner iterations\n%                      [ {'identity'} | square nonsingular matrix | \n%                        function handle ]\n%      NoiseLevel    - norm of noise in rhs divided by norm of rhs (must be\n%                      assigned if RegParam is 'discrep')\n%                      [ {'none'} | nonnegative scalar ]\n%      eta           - safety factor for the discrepancy principle\n%                      [ {1.01} | scalar greater than (and close to) 1 ]\n%      RegParam0     - first regularization parameter, used only on the \n%                      very first iteration (needed if RegParam is 'discrep')\n%                      [ {1} | positive scalar ]\n%      stopOut       - stopping criterion for the outer iterations;\n%                      [ {'xstab'} | 'Lxstab' | 'regPstab' ]\n%      inSolver      - solver to be employed during the inner iterations\n%                      [ 'gmres' | {'lsqr'} | 'fgmres' | 'cgls']\n%      adaptConstr   - approximate constraint or regularization to be\n%                      incorporated\n%                      [ {'sp'} | 'spnn' | 'none' ]\n%      nonnegativity - may be used to also impose nonnegativity\n%                      (similarly to 'spnn')\n%                      [ 'on' | {'off'} ]\n%      IterBar       - shows the progress of the outer iterations\n%                      [ {'on'} | 'off' ]\n%      NoStopIn      - specifies whether the inner iterations should\n%                      proceed after a stopping criterion has been satisfied\n%                      [ 'on' | {'off'} ]\n%      NoStopOut     - specifies whether the outer iterations should\n%                      proceed after a stopping criterion has been satisfied\n%                      [ 'on' | {'off'} ]\n%      verbosity     - switch on or off the \"verbosity\" of the function\n%                      [ {'on'} | 'off' ]\n% Note: the options structure can be created using the function IRset.\n%\n% Outputs:\n%   X : computed solutions, stored column-wise (at the iterations listed in K)\n%   info: structure with the following fields:\n%      its          - number of the last computed iteration\n%      saved_iterations - iteration numbers of iterates stored in X \n%      StopFlag_in  - string that describes the inner stopping condition:\n%                       * Stopping criterion of the inner iterations is\n%                         never satisfied\n%                       * Stopping criterion is satisfied at least once\n%                         during the inner iterations\n%      StopFlag_out - string that describes the outer stopping condition;\n%                     depending on the inputs it can be one of the following:\n%                       * Outer stopping criterion is never satisfied\n%                       * Diagonal weighting matrix is numerically zero\n%                       * Solution stabilizes\n%                       * Transformed solution stabilizes\n%                       * Tegularization parameter stabilizes\n%      Rnrm     - relative residual norms at each iteration\n%      Xnrm     - solution norms at each iteration\n%      Enrm     - relative error norms (requires x_true) at each iteration\n%      Xout     - approximate solutions at the end of each inner cycle,\n%                 stored column-wise\n%      itsInOut - 3-column matrix whose the columns store\n%                   1. outer iteration count\n%                   2. inner iteration count (i.e., for each cycle)\n%                   3. total iteration count\n%      StopReg  - struct containing information about the solution that\n%                 satisfies the stopping criterion.  Fields:\n%                   It   : iteration where the stopping criterion is satisfied\n%                   X    : solution satisfying the stopping criterion\n%                   Enrm : the corresponding relative error (requires x_true)\n%      BestReg  - struct containing information about the solution that\n%                 minimizes Enrm (requires x_true). Fields:\n%                   It   : iteration where the minimum is attained\n%                   X    : best solution\n%                   Enrm : best relative error\n%\n% See also: IRell1, IRhtv, IRhybrid_fgmres, IRrestart, IRget, IRset\n\n% Silvia Gazzola, University of Bath\n% Per Christian Hansen, Technical University of Denmark\n% James G. Nagy, Emory University\n% April, 2018.\n\n% This file is part of the IR Tools package and is distributed under the \n% 3-Clause BSD License. A separate license file should be provided as part \n% of the package.\n\n% Set default values for options.\ndefaultopt = struct('x0', 'none', 'MaxIterIn', 30 , 'MaxIterOut', 20 , ...\n    'RegParam', 'gcv', 'stopGCV', 'resflat', ...\n    'resflatTol', 0.05, 'GCVflatTol', 10^-6, 'GCVminTol', 3,...\n    'x_true', 'none', 'IterBar', 'on', 'NoStop', 'off', 'NoStopIn', 'off',...\n    'NoStopOut', 'off', 'stopOut', 'xstab', 'stabOut', 1e-6, 'thr0', 1e-10, ...\n    'NoiseLevel', 'none', 'eta', 1.01, 'RegParam0', 1, 'inSolver', 'lsqr', ...\n    'adaptConstr', 'sp', 'nonnegativity', 'off', 'verbosity', 'off',...\n    'SparsityTrans', 'none', 'wname', 'db1', 'wlevels', 2, 'warmrestart', 'on');\n  \n% If input is 'defaults,' return the default options in X.\nif nargin==1 && nargout <= 1 && isequal(A,'defaults')\n    X = defaultopt;\n    return;\nend\n\n% Check for acceptable number of optional input arguments.\nswitch length(varargin)\n    case 0 \n        K = []; options = [];\n    case 1\n        if isa(varargin{1}, 'double')\n            K = varargin{1}; options = [];\n        else\n            K = []; options = varargin{1};\n        end\n    case 2\n        if isa(varargin{1}, 'double')\n            K = varargin{1}; options = varargin{2};\n        else\n            K = varargin{2}; options = varargin{1};\n        end\n    otherwise\n        error('Too many input parameters')\nend\n\nif isempty(options)\n    options = defaultopt;\nend\n\noptions = IRset(defaultopt, options);\nnn       = IRget(options, 'nonnegativity', [], 'fast');\ninSolver = IRget(options, 'inSolver',      [], 'fast');\n\nif strcmp(nn, 'on')\n    nn = 1;\n    options.adaptConstr = 'spnn';\nelse\n    nn = 0;\nend\n\nif strcmp(inSolver, 'fgmres') && ~nn\n    warning(['With options.inSolver = ''fgmres'' and options.nonnegativity = ''off'' ',...\n        'it is more appropriate to use IRhybrid_fgmeres than to use IRirn.'])\nend\n\n% Call IRrestart with the specified options.\n% Note that nonnegativity is specified via options.adaptConstr.\noptions = rmfield(options, 'nonnegativity');\n[X, info] = IRrestart(A, b, K, options);", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/IRcodes/IRirn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5667309766237094}}
{"text": "% Gianni Schena  July 2005, schena@units.it\n% Lattice Boltzmann LBE, geometry: D2Q9, model: BGK\n% Application to permeability in porous media \n\nRestart=false % to restart from an earlier convergence\nlogical(Restart);\n\nif Restart==false;\nclose all, clear all % start from scratch and clean ...\nRestart=false;\n% type of channel geometry ; \n% one of the flollowing flags == true\nPois_test=true, % no obstacles in the 2D channel\n% porous systems\nobs_regolare=false % \nobs_irregolare=false % \ntic\n%   IN\n% |vvvv|    + y\n% |vvvv|     ^\n% |vvvv|     | -> + x\n%  OUT\n\n% Pores in 2D : Wet and Dry locations (Wet ==1 , Dry ==0 )\nwXh_Dry=[3,1];wXh_Wet=[3,4];\n\nif obs_regolare, % with internal obstacles \n    \nA=repmat([zeros(wXh_Dry),ones(wXh_Wet)],[1,3]);A=[A,zeros(wXh_Dry)];\nB=ones(size(A)); \nC=[A;B]  ; D=repmat(C,4,1);\nD=[B;D]\nend\n\nif obs_irregolare, % with int obstacles \nA1=repmat([zeros(wXh_Dry),ones(wXh_Wet)],[1,3]); \nA1=[A1,zeros(wXh_Dry)]  ;\nB=ones(size(A1)); \nC1=repmat([ones(wXh_Wet),zeros(wXh_Dry)],[1,3]); C1=[C1,ones(wXh_Dry)];\nE=[A1;B;C1;B]; \nD=repmat(E,2,1);\nD=[B;D]\nend\n\nif ~Pois_test\nfigure,imshow(D,[]) \nChannel2D=D;\nLen_Channel_2D=size(Channel2D,1); % Length\nWidth=size(Channel2D,2); % should not be hod\nChannel_2D_half_Width=Width/2,\nend\n\n% test without obstacles (i.e. 2D channel & no obstacles)\n\nif Pois_test\n%over-writes the definition of the pore space\nclear Channel2D\nLen_Channel_2D=36, % lunghezza canale 2d\nChannel_2D_half_Width=8; Width=Channel_2D_half_Width*2;\nChannel2D=ones(Len_Channel_2D,Width); % define wet area\n%Channel2D(6:12,6:8)=0; % put fluid obstacle\nimshow(Channel2D,[]);\nend\n\n[Nr Mc]=size(Channel2D); % Number rows and Munber columns\n\n% porosity\nporosity=nnz(Channel2D==1)/(Nr*Mc)\n\n\n% FLUID PROPERTIES\n% physical properties\ncs2=1/3; % \ncP_visco=0.5; % [cP] 1 CP Dinamic water viscosity 20 C\ndensity=1.; % fluid density \nLky_visco=cP_visco/density; % lattice kinematic viscosity \nomega=(Lky_visco/cs2+0.5).^-1; %  omega: relaxation frequency\n%Lky_visco=cs2*(1/omega - 0.5) , % lattice kinematic viscosity\n%dPdL= Pressure / dL;% External pressure gradient [atm/cm]\n\nuy_fin_max=-0.2; \n%dPdL = abs( 2*Lky_visco*uy_fin_max/(Channel_2D_half_Width.^2) ); \ndPdL=-0.0125;\nuy_fin_max=dPdL*(Channel_2D_half_Width.^2)/(2*Lky_visco); % Poiseuille Gradient;\n% max poiseuille final  velocity on the flow profile\nuy0=-0.001; ux0=0.0001; %  linear vel .. inizialization\n\n% \n% uy_fin_max=-0.2; % max poiseuille final  velocity on the flow profile\n% omega=0.5, cs2=1/3; % omega: relaxation frequency\n% Lky_visco=cs2*(1/omega - 0.5) , % lattice kinematic viscosity\n% dPdL = abs( 2*Lky_visco*uy_fin_max/(Channel_2D_half_Width.^2) ); % Poiseuille Gradient;\n% \n\nuyf_av=uy_fin_max*(2/3);; % average fluid velocity on the profile\n\nx_profile=([-Channel_2D_half_Width:+Channel_2D_half_Width-1]+0.5);\nuy_analy_profile=uy_fin_max.*(1-  ( x_profile /Channel_2D_half_Width).^2 ); % analytical velocity profile\n\nav_vel_t=1.e+10; % inizialization (t=0)\n%PixelSize= 5; % [Microns]\n%dL=(Nr*PixelSize*1.0E-4); % sample hight [cm]\n\n\n%\n% EXPERIMENTAL SET-UP\n% inlet and outlet buffers\ninb=2, oub=2; % inlet and outlet buffers thickness\n% add fluid at the inlet (top) and outlet (down)\ninlet=ones(inb,Mc); outlet=ones(oub,Mc);\nChannel2D=[ [inlet]; Channel2D ;[outlet] ] ; % add flux in and down (E to W)\n[Nr Mc]=size(Channel2D); % update size\n% boundaries related to the experimental set up\nwb=2; % wall thickness\nChannel2D=[zeros(Nr,wb), Channel2D , zeros(Nr,wb)]; % add walls (no fluid leak)\n[Nr Mc]=size(Channel2D); % update size\nuy_analy_profile=[zeros(1,wb), uy_analy_profile, zeros(1,wb) ] ; % take into account walls\nx_pro_fig=[[x_profile(1)-[wb:-1:1]], [x_profile, [1:wb]+x_profile(end)] ];\n\n% Figure plots analytical parabolic profile\nfigure(20), plot(x_pro_fig,uy_analy_profile,'-'), grid on,\ntitle('Analytical parab. profile for Poiseuille planar flow in a channel')\n\n\n% VISUALIZE PORE SPACE & FLUID OSTACLES & MEDIAL AXIS\nfigure, imshow(Channel2D); title('Vassel geometry');\nChannel2D=logical(Channel2D);\n% obstacles for Bounce Back ( in front of the grain)\nObstacles=bwperim(Channel2D,8); % perimeter of the grains for bounce back Bound.Cond.\nborder=logical(ones(Nr,Mc));\nborder([1:inb,Nr-oub:Nr],[wb+2:Mc-wb-1])=0;\nObstacles=Obstacles.*(border);\nfigure, imshow(Obstacles); title(' Fluid obstacles (in the fluid)' );\n% \nMedial_axis=bwmorph(Channel2D,'thin',Inf); %\nfigure, imshow(Medial_axis); title('Medial axis');\nfigure(10) % used to visualize evolution of rho\nfigure(11) % used to visualize ux\nfigure(12) % used to visualize uy (i.e. top -> down)\n\n% INDICES\n% Wet locations etc.\n[iabw1 jabw1]=find(Channel2D==1); % indices i,j, of active lattice locations i.e. pore\nlena=length(iabw1); % number of active location i.e. of pore space lattice cells\nija= (jabw1-1)*Nr+iabw1; % equivalent single index (i,j)->> ija for active locations\n% absolute (single index) position of the obstacles in for bounce back in Channel2D\n% Obstacles \n[iobs jobs]=find(Obstacles);lenobs=length(iobs); ijobs= (jobs-1)*Nr+iobs; % as above\n% Medial axis of the pore space\n[ima jma]=find(Medial_axis); lenma=length(ima);  ijma= (jma-1)*Nr+ima; % as above\n% Internal wet locations : wet & ~obstables\n% (i.e. internal wet lattice location non in contact with dray locations)\n[iawint jawint]=find(( Channel2D==1 & ~Obstacles)); % indices i,j, of active lattice locations\nlenwint=length(iawint); % number of internal (i.e. not border) wet locations\nijaint= (jawint-1)*Nr+iawint; % equivalent singl\nNxM=Nr*Mc;\n\n% DIRECTIONS: E N W S NE NW SW SE ZERO (ZERO:Rest Particle)\n%    y^\n%  6 2 5           ^         NW  N  NE\n%  3 9 1 ... +x-> +y         W   RP  E\n%  7 4 8                     SW  S  SE\n%   -y\n% x & y components of velocities , +x is to est , +y is to nord\nEast=1; North=2; West=3; South=4; NE=5; NW=6; SW=7; SE=8; RP=9;\nN_c=9 ; % number of directions\n% versors D2Q9\nC_x=[1 0 -1  0 1 -1 -1  1 0]; \nC_y=[0 1  0 -1 1  1 -1 -1 0]; C=[C_x;C_y]\n\n% BOUNCE BACK SCHEME\n% after collision the fluid elements densities f are sent back to the\n% lattice node they come from with opposite direction\n% indices opposite to 1:8 for fast inversion after bounce\nic_op = [3 4 1 2 7 8 5 6]; %   i.e. 4 is opposite to 2 etc.\n\n% PERIODIC BOUNDARY CONDITIONS - reinjection rules\nyi2=[Nr , 1:Nr , 1]; % this definition allows implemening Period Bound Cond\n%yi2=[1, Nr , 2:Nr-1 , 1,Nr]; % re-inj the second last to as first\n% directional weights (density weights)\nw0=16/36. ; w1=4/36. ; w2=1/36.;\nW=[ w1 w1 w1 w1 w2 w2 w2 w2 w0];\n%c constants (sound speed related)\ncs2=1/3; cs2x2=2*cs2; cs4x2=2*cs2.^2;\nf1=1/cs2; f2=1/cs2x2; f3=1/cs4x2;\nf1=3., f2=4.5; f3=1.5; % coef. of the f equil.\n\n% declarative statemets\nf=zeros(Nr,Mc,N_c); % array of fluid density distribution\nfeq=zeros(Nr,Mc,N_c); % f at equilibrium\nrho=ones(Nr,Mc); % macro-scopic density\ntemp1=zeros(Nr,Mc);\nux=zeros(Nr,Mc);   uy=zeros(Nr,Mc); uyout=zeros(Nr,Mc);  % dimensionless velocities\nuxsq=zeros(Nr,Mc); uysq=zeros(Nr,Mc);   usq=zeros(Nr,Mc);  % higher degree velocities\n\n% initialization arrays : start values in the wet area\nfor ia=1:lena % stat values in the active cells only ; 0 outside\n    i=iabw1(ia);  j=jabw1(ia);\n    f(i,j,:)=1/9; % uniform density distribution for a start\nend\nuy(ija)=uy0; ux(ija)=ux0; % initialize fluid velocities\nrho(ija)=density;\n\n% EXTERNAL (Body) FORCES e.g. inlet pressure or inlet-outlet gradient\n% directions: E N W S NE NW SW SE ZERO\nforce = -dPdL*(1/6)*1*[0 -1 0 1 -1 -1 1  1  0]'; %;\n%...                   E  N E S NE NW SW SE RP ...\n% the pressure pushes the fluid down i.e. N to S\n\n% While .. MAIN TIME EVOLUTION LOOP\nStopFlag=false; % i.e. logical(0)\nMax_Iter=3000; % max allowed number of iteration\nCheck_Iter=1; Output_Every=20; % frequency of check & output\nCur_Iter=0; % current iteration counter inizialization\ntoler=1.0e-8; % tollerance to declare convegence\nCond_path=[]; % recording values of the convergence criterium\ndensity_path=[]; % recording aver. density values for convergence\nend % ends if restart\n\nif(Restart==true)\n StopFlag=false;  Max_Iter=Max_Iter+3000; toler=1.0e-12; \nend\n\n\nwhile(~StopFlag)\n    Cur_Iter=Cur_Iter+1 % iteration counter update\n\n    % density and moments\n    rho=sum(f,3); % density\n\n    if Cur_Iter >1 % use inizialization ux uy to start\n        % Moments ... Note:C_x(9)=C_y(9)=0\n        ux=zeros(Nr,Mc); uy=zeros(Nr,Mc);\n        for ic=1:N_c-1;\n            ux = ux + C_x(ic).*f(:,:,ic) ; uy = uy + C_y(ic).*f(:,:,ic)  ;\n        end\n       % uy=f(:,:,2) +f(:,:,5)+f(:,:,6)-f(:,:,4)-f(:,:,7)-f(:,:,8); % in short !\n       % ux=f(:,:,1) +f(:,:,5)+f(:,:,8)-f(:,:,3)-f(:,:,6)-f(:,:,7); % in short !\n    end\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    ux(ija)=ux(ija)./rho(ija); uy(ija)=uy(ija)./rho(ija);\n    uxsq(ija)=ux(ija).^2; uysq(ija)=uy(ija).^2; \n    usq(ija)=uxsq(ija)+uysq(ija); %\n\n    % weighted densities : rest particle, principal axis, diagonals\n    rt0 = w0.*rho; rt1 = w1.*rho; rt2 = w2.*rho;\n    \n    % Equilibrium distribution\n    % main  directions ( + cross)\n    feq(ija)= rt1(ija) .*(1 +f1*ux(ija) +f2*uxsq(ija) -f3*usq(ija));\n    feq(ija+NxM*(2-1))= rt1(ija) .*(1 +f1*uy(ija) +f2*uysq(ija) -f3*usq(ija));\n    feq(ija+NxM*(3-1))= rt1(ija) .*(1 -f1*ux(ija) +f2*uxsq(ija) -f3*usq(ija));\n    %feq(ija+NxM*(3)=f(ija)-2*rt1(ija)*f1.*ux(ija); % much faster... !!\n    feq(ija+NxM*(4-1))= rt1(ija) .*(1 -f1*uy(ija) +f2*uysq(ija) -f3*usq(ija));\n    \n    % diagonals (X diagonals) (ic-1)\n    feq(ija+NxM*(5-1))= rt2(ija) .*(1 +f1*(+ux(ija)+uy(ija)) +f2*(+ux(ija)+uy(ija)).^2 -f3.*usq(ija));\n    feq(ija+NxM*(6-1))= rt2(ija) .*(1 +f1*(-ux(ija)+uy(ija)) +f2*(-ux(ija)+uy(ija)).^2 -f3.*usq(ija));\n    feq(ija+NxM*(7-1))= rt2(ija) .*(1 +f1*(-ux(ija)-uy(ija)) +f2*(-ux(ija)-uy(ija)).^2 -f3.*usq(ija));\n    feq(ija+NxM*(8-1))= rt2(ija) .*(1 +f1*(+ux(ija)-uy(ija)) +f2*(+ux(ija)-uy(ija)).^2 -f3.*usq(ija));\n    % rest particle (.) ic=9\n    feq(ija+NxM*(9-1))= rt0(ija) .*(1 - f3*usq(ija));\n\n    %Collision (between fluid elements)omega=relaxation frequency\n    f=(1.-omega).*f + omega.*feq;\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %add external body force due to the pressure gradient prop. to dPdL\n    for ic=1:N_c;%-1\n        for ia=1:lena\n            i=iabw1(ia);  j=jabw1(ia);\n            % if Obstacles(i,j)==0 % the i,j is not aderent to the boundaries\n            % if ( f(i,j,ic) + force(ic) ) >0; %! avoid negative distributions\n            %i=1 ;% force only on the first row !\n            f(i,j,ic)= f(i,j,ic) + force(ic);\n            % end\n            % end\n        end\n    end\n\n   \n\n    % % STREAM\n    % Forward Propagation step & % Bounce Back (collision fluid with obstacles)\n    %f(:,:,9) = f(:,:,9); % Rest element do not move\n   \n    feq = f; % temp storage of f in feq\n        for ic=1:1:N_c-1, % select velocity layer\n\n        ic2=ic_op(ic); % selects the layer of the velocity opposite to ic for BB\n        temp1=feq(:,:,ic); %\n\n        % from wet location that are NOT on the border to other wet locations\n        for ia=1:1:lenwint % number of internal (i.e. not border) wet locations\n            i=iawint(ia);  j=jawint(ia);  % so that we care for the wet space only !\n            i2 = i+C_y(ic); j2 = j+C_x(ic); % Expected final locations to move\n            i2=yi2(i2+1); % i2 corrected for PBC when necessary (flow out re-fed to inlet)\n            % i.e the new position (i2,j2) is sure another wet location\n            % therefore normal propagation from (i,j) to (i2,j2) on layer ic\n            f(i2,j2,ic)=temp1(i,j); % see circshift(..) fnct for circularly shifts\n        end ; % i and j single loop\n\n\n        % from wet locations that ARE on the border of obstacles\n        for ia=1:1:lenobs % wet border locations\n            i=iobs(ia);  j=jobs(ia);  % so that we care for the wet space only !\n            i2 = i+C_y(ic); j2 = j+C_x(ic); % Expected final locations to move\n            i2=yi2(i2+1); % i2 corrected for PBC\n\n            if( Channel2D(i2,j2) ==0 ) % i.e the new position (i2,j2) is dry\n                f(i,j,ic2) =temp1(i,j); % invert direction: bounce-back in the opposite direction ic2\n            else % otherwise, normal propagation from (i,j) to (i2,j2) on layer ic\n                f(i2,j2,ic)=temp1(i,j); % see circshift(..) fnct for circularly shifts\n            end ; % b.b. and propagations\n\n        end ; % i and j single loop\n        % special treatment for Corners\n        %   f(1,wb+1,ic)=temp1(Nr,Mc-wb);      f(1,Mc-wb,ic)=temp1(Nr,wb+1);\n        %   f(Nr,wb+1,ic)=temp1(1,Mc-wb);      f(Nr,Mc-wb,ic)=temp1(1,wb+1);\n\n    end ; %  for ic direction\n\n    % ends of Forward Propagation step &  Bounce Back Sections\n\n    % re-calculate  uy as uyout for convergence\n    rho=sum(f,3); % density\n    % check velocity\n    uyout= zeros(Nr,Mc);\n    for ic=1:N_c-1;\n        uyout= uyout + C_y(ic).*f(:,:,ic) ; % flow dim.less velocity out\n    end\n   % uyout(ija)=uyout(ija)./rho(ija); % from momentum to velocity\n\n    % Convergence check on velocity values\n    if (mod(Cur_Iter,Check_Iter)==0) ; % check for convergence every 'Check_Iter' iterations\n\n        % variables monitored\n        % mean density and\n        vect=rho(ija); vect=vect(:); \n        cur_density=mean(vect);\n        % mean 'interstitial' velocity\n        % uy(ija)=uy(ija)/rho(ija); ?\n        vect=uy(ija); av_vel_int= mean(vect)  ; % seepage velocity (in the wet area)\n        % on the whole cross-sectional area of flow (wet + dry)\n        av_vel_int=av_vel_int*porosity, % av. vel. on the wet + dry area\n        %av_vel_int=mean2(uy),\n        av_vel_tp1 = av_vel_int; \n        Condition=abs( abs(av_vel_t/av_vel_tp1 )-1), % should --> 0\n\n        Cond_path=[Cond_path, Condition]; % records the convergence path (value)\n        density_path=[density_path, cur_density];\n        %\n        av_vel_t=av_vel_tp1; % time t & t+1 \n\n        if (Condition < toler) | (Cur_Iter > Max_Iter)\n            StopFlag=true;\n            display( 'Stop iteration: Convergence met or iteration exeeding the max allowed' )\n            display( ['Current iteration: ',num2str(Cur_Iter),...\n                ' Max Number of iter: ',num2str(Max_Iter)] )\n            break % Terminate execution of WHILE .. exit the time evolution loop.\n\n        end    % if(Condition < toler\n\n    end\n\n    if (mod(Cur_Iter,Output_Every)==0) ;  % Output from loop every ...\n        %if (Cur_Iter>60) ;  % Output from loop every ...\n\n        rho=sum(f,3); % density\n        figure(10); imshow(rho,[0.1 0.9]); title(' rho'); % visualize density evolution\n        figure(11); imshow(ux,[ ]); title(' ux' ); % visualize fluid velocity horizontal\n        figure(12); imshow(-uy,[ ]); title(' uy' ); % visualize fluid velocity down\n        figure(14), imshow(-uyout,[]), title('uyout'); % vis vel flow out\n        up=2; % linear section to visualize up from the lower row\n        figure(15), hold off, feather(ux(Nr-up,:),uy(Nr-up,:)),\n        figure(15), hold on , plot(uy_analy_profile,'r-')\n        title('Analytical vs LB calculated, fluid velocity parabolic profile')\n        pause(3); % time given to visualize properly\n\n    end % every\n\n\n   % pause(1);\n\n    \nend %  End main time Evolution Loop\n\n% Output & Draw after the end of the time evolution\n\nfigure, plot(Cond_path(2:end)); title('convergence path')\n%figure, plot(density_path(2:end)); title('density convergence path')\nfigure, plot( [uy(Nr-up,:)-uy_analy_profile] ); title('difference : LB - Analytical solution')\n\ntoc\n\n% Permeability K\n\nK_Darcy_Porous_Sys= (av_vel_int*porosity)/dPdL*Lky_visco ,\n\nK_Analy_2D_Channel=(Width^2)/12\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/LBM/LBGK_D2Q9_poiseuille_channel2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5667309600626007}}
{"text": "%MEDIANBLUR  Blurs an image using the median filter\n%\n%     dst = cv.medianBlur(src)\n%     dst = cv.medianBlur(src, 'OptionName',optionValue, ...)\n%\n% ## Input\n% * __src__ Input 1-, 3-, or 4-channel image. When `KSize` is 3 or 5, the\n%   image type should be `uint8`, `uint16`, or `single`. For larger aperture\n%   sizes, it can only be `uint8`.\n%\n% ## Output\n% * __dst__ Destination array of the same size and type as `src`.\n%\n% ## Options\n% * __KSize__ Aperture linear size. It must be odd and greater than 1, for\n%   example 3, 5, 7 ... default 5\n%\n% The function smooths an image using the median filter with the\n% `KSize x KSize` aperture. Each channel of a multi-channel image is\n% processed independently.\n%\n% Note: The median filter uses `BorderType=Replicate` internally to cope with\n% border pixels. See cv.copyMakeBorder.\n%\n% See also: cv.bilateralFilter, cv.blur, cv.boxFilter, cv.GaussianBlur,\n%  medfilt2\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/medianBlur.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.5667309584621046}}
{"text": "function plotpoint(i,x1,y1,Color)\n\n\n%x1=[source dest]--in x axis\n%y1=[source dest]--in y axis\n\n   %Color='r';\n  % N=1000;\n       \n\n\n \n \n    if abs(x1(1)-x1(2))>=abs(y1(1)-y1(2))\n\n    \n     if x1(1)<=x1(2)\n        %x=x1(1):x1(2);\n        x=x1(1)+i;\n        p=1;\n     else\n        %x=x1(1):-1:x1(2);    \n        x=x1(1)-i;\n        p=0;\n     end   \n             if ((p==1 && x<=x1(2)) || (p==0 && x>=x1(2)))\n                 \n                %%\n                Radius=i;%sqrt((abs(i))^2 + (abs(i))^2);\n                plotcircle(x1(1),y1(1),Radius,Color)\n                %%\n                 \n                 \n                y=(((x-x1(1))./((x1(2)-x1(1)))).*((y1(2)-y1(1))))+y1(1);\n\n\n                plot(x,y,'.','LineWidth',1,...\n                    'MarkerEdgeColor','k',...\n                    'MarkerFaceColor','y',...\n                    'MarkerSize',8);\n                hold on\n\n             %   plot(x1,y1,'^r')\n\n             end \n    else\n\n      if y1(1)<=y1(2)\n        %x=x1(1):x1(2);\n        y=y1(1)+i;\n        p=1;\n      else\n        %x=x1(1):-1:x1(2);    \n        y=y1(1)-i;\n        p=0;\n      end   \n    \n          if ((p==1 && y<=y1(2)) || (p==0 && y>=y1(2)))\n                x=(((y-y1(1))./((y1(2)-y1(1)))).*((x1(2)-x1(1))))+x1(1);\n\n                %%\n                Radius=i;%sqrt((abs(i))^2 + (abs(i))^2);\n                plotcircle(x1(1),y1(1),Radius,Color)\n          \n                \n                %%\n                plot(x,y,'.','LineWidth',1,...\n                    'MarkerEdgeColor','k',...\n                    'MarkerFaceColor','y',...\n                    'MarkerSize',8);\n                hold on\n\n              %  plot(x1,y1,'^r')\n\n          end   \n    end\n\n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43355-mobility-wsn-animator/MobiltyWSN/plotpoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6992544085240402, "lm_q1q2_score": 0.566730949903476}}
{"text": "% main box sizes:\na=2;\nb=1;\n\nNb=5; % number of boxes\n\n% random boxes sizes:\n% mab=mean([a b]);\n% aa=0.05*mab+0.3*mab*rand(1,Nb);\n% bb=0.05*mab+0.3*mab*rand(1,Nb);\n\nmrg=0.95; % for margine\naa=[1    1     1     0.5  0.5];\nbb=[1    0.25  0.25  0.5  0.5];\naa=aa*mrg;\nbb=bb*mrg;\n\nm2=min([aa bb]/2); % smallest half-size\nAA=aa.*bb; % boxes areas\n\npenalty=0.2*a*b;\nnac=0.8; % negative area coefficient\n\n\nN=5000; % population size\nng=20000; % number of generations\npmpe=0.1; % places exchange mutation probability\npmbj=0.02; % big gauss jump\npmsj=0.04; % small gauss jump\npmrr=0.1; % random rotation\npmvi=0.1; % random visible/invisible\npmne=0.2; % move to nearest adge\n\nfigure;\n%ha1=axes;\nha1=subplot(2,1,1);\nplot([0 a a 0 0], [0 0 b b 0],'b-');\nxlim([-0.1*a 1.1*a]);\nylim([-0.1*b 1.1*b]);\nset(ha1,'NextPlot','add');\nht=title(ha1,'start');\nha2=subplot(2,1,2);\ndrawnow;\n\n\nset_cl; % set color table cl to plot boxes with different colors\n\n\n\n% random initial population:\nG=zeros(N,4*Nb);\nGch=zeros(N,4*Nb); % children\nfor Nc=1:N % for each individual\n    G1=zeros(4,Nb); % one individual\n    % G1(1,i)=1 if i-box is visible\n    % G1(2,i)=1 if i-box is rotated at 90 degrees\n    % G1(3,i) - x-coordinate of i-box center\n    % G1(4,i) - y-coordinate of i-box center\n\n    G1(1,:)=double(rand(1,Nb)<0.2);\n    G1(2,:)=double(rand(1,Nb)<0.5);\n    \n    G1(3,:)=m2+(a-m2)*rand(1,Nb);\n    G1(4,:)=m2+(b-m2)*rand(1,Nb);\n    \n    \n    G(Nc,:)=(G1(:))'; % (G1(:))' converts matrix to row-vector\nend\n\nhi=imagesc(G,'parent',ha2);\ndrawnow;\n\n\n\nGpr1=zeros(4,Nb);\nGpr2=zeros(4,Nb); % two parents\nGch1=zeros(4,Nb);\nGch2=zeros(4,Nb); % two children\nfor ngc=1:ng % generations counting\n    % find fitnesses:\n    fitnesses=zeros(N,1);\n    for Nc=1:N % for each individual\n        G1(:)=(G(Nc,:))';\n        vis=G1(1,:);\n        ind=find(vis);\n        L=length(ind);\n        if L>0\n            % only visible:\n            rot=G1(2,ind);\n            x=G1(3,ind);\n            y=G1(4,ind);\n            if L==1\n                aaa=aa(ind);\n                bbb=bb(ind);\n                if rot\n                    tmp=aaa;\n                    aaa=bbb;\n                    bbb=tmp;\n                end\n                A0=AA(ind); % box area\n                x1=max([x-aaa/2  0]);\n                y1=max([y-bbb/2  0]);\n                x2=min([x+aaa/2  a]);\n                y2=min([y+bbb/2  b]);\n                % x1 - x2,  y1 - y2 is box (part of current box) that inside main box\n                if (x1>=x2)||(y1>=y2)\n                    A=0; % box that inside main box area\n                else\n                    A=(x2-x1)*(y2-y1); % box that inside main box area\n                end\n                %if A<A0 % if not fully inside main box\n                if (aaa/2<=x)&&(x<=a-aaa/2)&&(bbb/2<=y)&&(y<=b-bbb/2) % if filly inside\n                    fitness=A;\n                else\n                    fitness=A-nac*(A0-A)-penalty;\n                end\n                    \n            else\n                fitness=0;\n                ispen=false; % true if penality\n                \n                % check cross with main box:\n                % add boxes arreas and strong subtract out areas:\n                for n=1:L % for each box\n                    ind1=ind(n);\n                    aaa=aa(ind1);\n                    bbb=bb(ind1);\n                    if rot(n)\n                        tmp=aaa;\n                        aaa=bbb;\n                        bbb=tmp;\n                    end\n                    A0=AA(ind1); % box area\n                    x1=max([x(n)-aaa/2  0]);\n                    y1=max([y(n)-bbb/2  0]);\n                    x2=min([x(n)+aaa/2  a]);\n                    y2=min([y(n)+bbb/2  b]);\n                    % x1 - x2,  y1 - y2 is box (part of current box) that inside main box\n                    if (x1>=x2)||(y1>=y2)\n                        A=0; % box that inside main box area\n                    else\n                        A=(x2-x1)*(y2-y1); % box that inside main box area\n                    end\n                    %if A<A0 % if not fully inside main box\n                        %fitness=fitness + A-nac*(A0-A);\n                        %ispen=true; % penality\n                    %else\n                        %fitness=fitness + A;\n                    %end\n                    \n                    if (aaa/2<=x(n))&&(x(n)<=a-aaa/2)&&(bbb/2<=y(n))&&(y(n)<=b-bbb/2) % if filly inside\n                        fitness=fitness + A;\n                    else\n                        fitness=fitness + A-nac*(A0-A);\n                        ispen=true; % penality\n                    end\n                    \n                end\n                \n                % for each pair of boxes:\n                for n1=1:L-1\n                    ind1=ind(n1);\n                    aaa1=aa(ind1);\n                    bbb1=bb(ind1);\n                    if rot(n1)\n                        tmp=aaa1;\n                        aaa1=bbb1;\n                        bbb1=tmp;\n                    end\n                    A1=AA(ind1);\n                    x1=x(n1);\n                    y1=y(n1); % position of 1st box of pair\n                    for n2=n1+1:L\n                        ind2=ind(n2);\n                        aaa2=aa(ind2);\n                        bbb2=bb(ind2);\n                        if rot(n2)\n                            tmp=aaa2;\n                            aaa2=bbb2;\n                            bbb2=tmp;\n                        end\n                        A2=AA(ind2);\n                        x2=x(n2);\n                        y2=y(n2); % position of 2nd box of pair\n                        dx=abs(x1-x2);\n                        dy=abs(y1-y2); % distancies\n                        a12=(aaa1/2+aaa2/2);\n                        b12=(bbb1/2+bbb2/2);\n                        if (dx<a12)&&(dy<b12) % if cross\n                            ispen=true;\n                            Ac=(a12-dx)*(b12-dy); % area of cross\n                            fitness=fitness-Ac-Ac; % becuse area of n1 and n2 was added fully\n                            fitness=fitness-2*nac*Ac;\n                        end\n\n                    end\n                end\n                \n                if ispen\n                    fitness=fitness-penalty;\n                end\n        \n            end\n        else\n            fitness=0;\n        end\n        fitnesses(Nc)=fitness;\n    end\n    \n    [fb bi]=max(fitnesses); % best\n    \n    % plot best:\n    G1(:)=(G(bi,:))';\n    Gb=G(bi,:); % best\n    if mod(ngc,10)==0\n        cla(ha1);\n        Atmp=0;\n        for Nbc=1:Nb\n            vis1=G1(1,Nbc);\n            if vis1\n                rot1=G1(2,Nbc);\n                aaa=aa(Nbc);\n                bbb=bb(Nbc);\n                if rot1\n                    tmp=aaa;\n                    aaa=bbb;\n                    bbb=tmp;\n                end\n                x=G1(3,Nbc);\n                y=G1(4,Nbc);\n                plot([x-aaa/2  x+aaa/2  x+aaa/2  x-aaa/2  x-aaa/2],...\n                     [y-bbb/2  y-bbb/2  y+bbb/2  y+bbb/2  y-bbb/2],...\n                     '-','color',cl(Nbc,:),...\n                     'parent',ha1);\n                hold on;\n                Atmp=Atmp+aaa*bbb;\n            end\n        end\n        plot([0 a a 0 0], [0 0 b b 0],'b-','parent',ha1);\n        xlim(ha1,[-0.1*a 1.1*a]);\n        ylim(ha1,[-0.1*b 1.1*b]);\n        \n        set(hi,'Cdata',G);\n        \n        nvb=length(find(G1(1,:))); % number of visible boxes\n        \n        set(ht,'string',[' generation: ' num2str(ngc)  ', boxes: ' num2str(nvb) ', area: ' num2str(fb)]);\n        \n        drawnow;\n    end\n    \n    \n    % prepare for crossover, selection:\n    fmn=min(fitnesses);\n    fst=std(fitnesses);\n    if fst<1e-7\n        fst=1e-7;\n    end\n    fmn1=fmn-0.01*fst; % little low then minimum\n    P=fitnesses-fmn1; % positive values\n    p=P/sum(P); % probabilities\n    ii=roulette_wheel_indexes(N,p);\n    Gp=G(ii,:); % parents\n    \n    % crossover:\n    for n=1:2:N\n        pr1=Gp(n,:);\n        pr2=Gp(n+1,:); % two parents\n        % in matrix form:\n        Gpr1(:)=pr1'; \n        Gpr2(:)=pr2';\n        \n        for Nbc=1:Nb\n            \n            % visibility:\n            if rand<0.5\n                Gch1(1,Nbc)=Gpr1(1,Nbc);\n            else\n                Gch1(1,Nbc)=Gpr2(1,Nbc);\n            end\n            if rand<0.5\n                Gch2(1,Nbc)=Gpr1(1,Nbc);\n            else\n                Gch2(1,Nbc)=Gpr2(1,Nbc);\n            end\n            \n            % rotation:\n            if rand<0.5\n                Gch1(2,Nbc)=Gpr1(2,Nbc);\n            else\n                Gch1(2,Nbc)=Gpr2(2,Nbc);\n            end\n            if rand<0.5\n                Gch2(2,Nbc)=Gpr1(2,Nbc);\n            else\n                Gch2(2,Nbc)=Gpr2(2,Nbc);\n            end\n            \n            % position:\n            % child 1:\n            %i3=ceil(3*rand);\n            %i3=roulette_wheel_indexes(1,[0.2 0.4 0.4]);\n            i3=1+ceil(2*rand);\n            switch i3\n                case 1 % get mean position\n                    Gch1(3,Nbc)=(Gpr1(3,Nbc)+Gpr2(3,Nbc))/2;\n                    Gch1(4,Nbc)=(Gpr1(4,Nbc)+Gpr2(4,Nbc))/2;\n                case 2 %get position of parent 1\n                    Gch1(3,Nbc)=Gpr1(3,Nbc);\n                    Gch1(4,Nbc)=Gpr1(4,Nbc);\n                case 3 %get position of parent 2\n                    Gch1(3,Nbc)=Gpr2(3,Nbc);\n                    Gch1(4,Nbc)=Gpr2(4,Nbc);\n            end\n            % child 2:\n            %i3=ceil(3*rand);\n            %i3=roulette_wheel_indexes(1,[0.2 0.4 0.4]);\n            i3=1+ceil(2*rand);\n            switch i3\n                case 1 % get mean position\n                    Gch2(3,Nbc)=(Gpr1(3,Nbc)+Gpr2(3,Nbc))/2;\n                    Gch2(4,Nbc)=(Gpr1(4,Nbc)+Gpr2(4,Nbc))/2;\n                case 2 %get position of parent 1\n                    Gch2(3,Nbc)=Gpr1(3,Nbc);\n                    Gch2(4,Nbc)=Gpr1(4,Nbc);\n                case 3 %get position of parent 2\n                    Gch2(3,Nbc)=Gpr2(3,Nbc);\n                    Gch2(4,Nbc)=Gpr2(4,Nbc);\n            end\n            \n            \n        end\n        ch1=(Gch1(:))';\n        ch2=(Gch2(:))';\n        Gch(n,:)=ch1;\n        Gch(n+1,:)=ch2;\n        \n        \n    end\n    G=Gch; % now children\n    \n    % mutations:\n    % places exchange\n    for Nc=1:N % for each individual\n        if rand<pmpe\n            G1(:)=(G(Nc,:))';\n            ir1=ceil(Nb*rand);\n            ir2=ceil(Nb*rand);\n            tmp1=G1(3:4,ir1);\n            G1(3:4,ir1)=G1(3:4,ir2);\n            G1(3:4,ir2)=tmp1;\n            G(Nc,:)=(G1(:))';\n        end\n    end\n    \n    % big gauss jump:\n    for Nc=1:N % for each individual\n        if rand<pmbj\n            G1(:)=(G(Nc,:))';\n            ir=ceil(Nb*rand);\n            G1(3:4,ir)=G1(3:4,ir)+[0.05*a*randn;\n                                   0.05*b*randn];\n            G(Nc,:)=(G1(:))';\n        end\n    end\n    \n    % small gauss jump:\n    for Nc=1:N % for each individual\n        if rand<pmsj\n            G1(:)=(G(Nc,:))';\n            ir=ceil(Nb*rand);\n            G1(3:4,ir)=G1(3:4,ir)+[0.005*a*randn;\n                                   0.005*b*randn];\n            G(Nc,:)=(G1(:))';\n        end\n    end\n    \n    % random rotation:\n    for Nc=1:N % for each individual\n        if rand<pmrr\n            G1(:)=(G(Nc,:))';\n            ir=ceil(Nb*rand);\n            G1(2,ir)=double(rand<0.5);\n            G(Nc,:)=(G1(:))';\n        end\n    end\n    \n    % random visible/invisible:\n    for Nc=1:N % for each individual\n        if rand<pmvi\n            G1(:)=(G(Nc,:))';\n            ir=ceil(Nb*rand);\n            G1(1,ir)=double(rand<0.5);\n            G(Nc,:)=(G1(:))';\n        end\n    end\n    \n    % move to nearest edge:\n    for Nc=1:N % for each individual\n        if rand<pmne\n            G1(:)=(G(Nc,:))';\n            ir=ceil(Nb*rand); % random small box\n            rv=find((G1(1,:))&((1:Nb)~=Nc)); % find rest visible\n            if rand<0.5\n                % to veritcile edge\n                eax=[G1(3,rv)-aa(rv)/2  G1(3,rv)+aa(rv)/2  0  a]; % edge xs\n                deax=[(G1(3,ir)-aa(ir)/2) - eax  (G1(3,ir)+aa(ir)/2) - eax]; % distancies\n                [dmn indm]=min(abs(deax));\n                G1(3,ir)=G1(3,ir)-deax(indm);\n            else\n                % to horizontal edge\n                eay=[G1(4,rv)-bb(rv)/2  G1(4,rv)+bb(rv)/2  0  b]; % edge ys\n                deay=[(G1(4,ir)-bb(ir)/2) - eay  (G1(4,ir)+bb(ir)/2) - eay]; % distancies\n                [dmn indm]=min(abs(deay));\n                G1(4,ir)=G1(4,ir)-deay(indm);\n            end\n        end\n    end\n    \n    \n    \n    % ellitism:\n    G(1,:)=Gb;\n    \n\n    \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/31789-2d-bin-packing-problem-with-genetic-algorithm/ga_2d_box_packing_test_task.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5667309435014918}}
{"text": "% Test of subdivision of a base polyhedron.\n\nmesh_types = {'tetra','oct','ico'};\nnmesh = length(mesh_types);\nnsub = 3;\n\nclf;\nfor i=1:nmesh\n    mesh_type = mesh_types{i};\n    [vertex,face] = compute_base_mesh(mesh_type);\n    for s=0:nsub\n        subplot(nmesh,nsub+1,s+1+(nsub+1)*(i-1));\n        plot_mesh(vertex,face);\n        lighting flat;\n        if s~=nsub     \n\t\t\toptions.spherical = 1;\n            options.relaxation = 3;\n            [vertex,face] = perform_mesh_subdivision(vertex,face,1,options);\n        end\n    end\nend\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_wavelet_meshes/tests/test_subdivision_polyhedra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581097540518, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5666933182776065}}
{"text": "function plotprmm(catalogObject)\n    %CATALOG.PLOTPRMM Plot the peak rate and maximum magnitude of a\n    %set of events\n    figure\n    symsize = get_symsize(catalogObject);   \n    t=catalogObject.gettimerange();\n    days = t(2) - t(1);\n    if all(isnan(catalogObject.mag))\n        warning('No magnitude data to plot');\n    else\n\n        % plot magnitudes\n        subplot(2,1,1), scatter(catalogObject.otime, catalogObject.mag, symsize);\n        %stem(catalogObject.otime, catalogObject.mag);\n        set(gca, 'XLim', [floor(t(1)) ceil(t(2))]);\n        datetick('x');\n        xlabel('Date');\n        ylabel('Magnitude');\n        grid on;\n\n        % put 'MM' label by max mag event\n        [mm, mmi] = max(catalogObject.mag);\n        text(catalogObject.otime(mmi), catalogObject.mag(mmi), 'MM','color','r');\n        disp(sprintf('MM=%.1f occurs at %.1f%% of time series',mm,100*(catalogObject.otime(mmi) - t(1))/days));\n\n        % plot event rate in 100 equal bins\n        \n        binsize = days/100;\n        erobj = catalogObject.eventrate('binsize',binsize);\n        %erobj = catalogObject.eventrate();\n        subplot(2,1,2),plot(erobj.time, erobj.counts);\n        set(gca, 'XLim', [floor(t(1)) ceil(t(2))]);\n        datetick('x');\n        xlabel('Date');\n        ylabel('Event Rate');\n        grid on; \n\n        % put 'PR' label by peak-rate\n        [pr, pri] = max(erobj.counts);\n        text(erobj.time(pri), erobj.counts(pri), 'PR','color','r');               \n        disp(sprintf('PR=%d occurs at %.1f%% of time series',pr,100*(erobj.time(pri) - erobj.snum)/(erobj.enum-erobj.snum)));\n    end\nend\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/core/@Catalog/plotprmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581194449494, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5666933105996361}}
{"text": "%% spmax\n% Below is a demonstration of the features of the |spmax| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[maxVal,maxInd]=spmax(A,B,dim,nanflag,logicRelevant,nanOut);|\n\n%% Description \n% This function is like the max function but is designed for sparse arrays.\n% In particular it allows one to \"ignore zeros\" in the determination of the\n% maxima. \n\n%% Examples \n%\n\n%%\n% Create example matrix\ni=[2 1 1 2  2 3  3 4 4 5  5 5 6 6 7 8];\nj=[1 1 2 3  4 5  6 7 8 9 10 11 12 13 13 13];\ns=[-1 3 1 2 -1 1 -2 5 5 -1 0 2 3 10 11 NaN];\nsiz=max([i(:);j(:)]+1)*ones(1,2);\nA=sparse(i,j,s,siz(1),siz(2),numel(s));\nA=A+A';\n\nfull(A) % View matrix\n\nL=sparse(i,j,1,siz(1),siz(2),numel(s));\nlogicRelevant=(L+L')>0;\n\n%%\n% Compute maxima allong a certain direction (while omit nan is default)\n\namaxRows=spmax(A,[],1);\nfull(amaxRows)\n\namaxColumns=spmax(A,[],2);\nfull(amaxColumns)\n\n%%\n% Including nans\n\namaxRows=spmax(A,[],1,'includenan');\nfull(amaxRows)\n\namaxColumns=spmax(A,[],2,'includenan');\nfull(amaxColumns)\n\n%%\n% Computing maxima across all desired relevant entries (including\n% \"relevant/real zeros\") \n\namaxRows=spmax(A,[],1,'omitnan',logicRelevant);\nfull(amaxRows)\n\namaxColumns=spmax(A,[],2,'omitnan',logicRelevant);\nfull(amaxColumns)\n\n%%\n% Computin maxima across all desired relevant entries and output NaN where\n% the sparse array only contains \"non-relevant or non-real\" zeros. \n\nnanOut=1;\n\namaxRows=spmax(A,[],1,'omitnan',logicRelevant,nanOut);\nfull(amaxRows)\n\namaxColumns=spmax(A,[],2,'omitnan',logicRelevant,nanOut);\nfull(amaxColumns)\n\n%%\n% \n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_spmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.566693306515391}}
{"text": "function [u,v]=pow2cep(m,c,mode)\n%CEP2POW convert cepstral means and variances to the power domain\n% Inputs:\n%    m: vector giving means in the power domain\n%    c: covariance matrix in the power domain\n% mode: 'c'  pow=exp(irdct(cep))   [default]\n%       'f'  pow=exp(rsfft(cep)/n)  [fft length even]\n%       'fo' pow=exp(rsfft(cep)/n)  [fft length odd]\n%       'i'  pow=exp(cep)           [ no transformation ]\n%\n% Outputs:\n%    u: row vector giving the cepstral means with u(1) the 0'th cepstral coefficient\n%    v: cepstral covariance matrix\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: pow2cep.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\nif nargin<3 mode='c'; end\nif min(size(c))==1\n   v=diag(c);\nend\nm=m(:)';        % force to be a row vector\nq=log(1+c./(m'*m));\np=log(m)-0.5*diag(q)';\nif any(mode=='f')\n   n=2*length(m)-2;\n   if any(mode=='o')\n      n=n+1;\n   end\n   u=rsfft(p,n);\n   v=rsfft(rsfft(q,n)',n);\nelseif any(mode=='i')\n    u=p;\n    v=q;\nelse\n   u=rdct(p);\n   v=rdct(rdct(q)');\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/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/pow2cep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523327, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5666306992237267}}
{"text": "function plotCPs(CPs)\n% DESCRIPTION\n% Plot Contribution Plots\n%\n%    plotCPs(CPs)\n%\n% INPUT\n%   CPs         Contribution Plots\n%\n% Created on 18th April 2019, by Kepeng Qiu.\n%-------------------------------------------------------------%\n\n%\nfigure\ntemp = mean(abs(CPs),1);\nbar(temp/sum(temp,2));\n\n% Axis settings\ntgca = 16;  % font size\ntfont = 'Helvetica'; % font type\n% tfont = 'Arial'; % font type\n% set(gca,'yscale','log')\nset(gca,'FontSize',tgca,'FontName',tfont)\n\n% legend settings\ntlegend = tgca*0.9;\nlegend({'Contribution Plots'},'FontSize',tlegend , ... \n    'FontWeight','normal','FontName',tfont)\n\n% label settings\ntlabel = tgca*1.1; \nxlabel('Variable','FontSize',tlabel,'FontWeight','normal', ... \n    'FontName',tfont,'Color','k')\nylabel('CPs','FontSize',tlabel,'FontWeight','normal', ... \n    'FontName',tfont,'Color','k')\n\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u7279\u5f81\u63d0\u53d6\u7b97\u6cd5/Kernel-Principal-Component-Analysis-KPCA-master/func/plotCPs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5666253963071416}}
{"text": "function [ a, b ] = p06_ab ( m )\n\n%*****************************************************************************80\n%\n%% P06_AB returns bounds for problem 6.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 February 2012\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, integer M, the spatial dimension.\n%\n%    Output, real A(M,1), B(M,1), lower and upper bounds.\n%\n  a(1:m,1) = 0.0;\n  b(1:m,1) = 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_opt_con/p06_ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.5666253924543193}}
{"text": "  function ss = outer_sum(xx,yy)\n%|function ss = outer_sum(xx,yy)\n%|\n%| compute an \"outer sum\" x + y'\n%| that is analogous to the \"outer product\" x * y'\n%|\n%| in\n%|\txx\t[nx 1]\n%|\tyy\t[1 ny]\n%|\t\tmore generally: xx [(dim)] + yy [L,1] -> xx [(dim) LL]\n%| out\n%|\tss [nx ny]\tss(i,j) = xx(i) + yy(j)\n%|\n%| Copyright 2001, Jeff Fessler, University of Michigan\n\nif ~nargin, ir_usage, end\nif streq(xx, 'test'), outer_sum_test, return, end\n\n% for 1D vectors, allow rows or cols for backward compatibility\nif ndims(xx) == 2 && min(size(xx)) == 1 && ndims(yy) == 2 && min(size(yy)) == 1\n\tnx = length(xx);\n\tny = length(yy);\n\txx = repmat(xx(:), [1 ny]);\n\tyy = repmat(yy(:)', [nx 1]);\n\tss = xx + yy;\nreturn\nend\n\n%if size(xx,1) == 1\n%\twarn 'xx is a row vector? are you sure?'\n%end\n\n% otherwise, xx is not a vector, but yy must be\n\nxdim = size(xx);\nydim = size(yy);\nif ndims(yy) ~= 2 || min(size(yy)) ~= 1\n\terror 'yy must be a vector'\nend\nsdim = [xdim length(yy)];\nxo = repmat(xx, [ones(1, length(xdim)) length(yy)]); % [xdim] -> [xdim ny]\nyo = repmat(yy(:), [1 xdim]); yo = permute(yo, [2 3 1]);\n% yo = repmat(yy(:)', [xdim 1 1]); % not sure how to make this work.\nss = xo + yo;\n\nfunction outer_sum_test\n%xx = [1:4];\n%yy = [0:10:50];\n%pr outer_sum(xx,yy)\npr 'outer_sum([1:4], [0:10:50])'\nxx = outer_sum([1:4], [0:10:50]);\npr 'outer_sum(xx, [100 200])'\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/outer_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5666253873274263}}
{"text": "function superima = QLsuperimage(C, S, iscale)\n%------------------------------------------------------------------------------\n% Creates an image that goes with a multiresolutiondecomposition that has been\n% made in the way of LISQ. The superimage, that is an image that comprises\n% all levels, is constructed as a rectangular gridfunction.\n%\n% C        is a one-dimensional array that contains the coefficients of the\n%          Quincunx Lifting Scheme (LISQ) decompositions.\n% S        is the bookkeeping vector\n% iscale   optional inputparameter\n%          1 show superimage as is (default)\n%          2 show superimage after removal of outliers\n%          3 show superimage after enhancement of contrast using\n%            histogram equalisation (if available)\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw <Paul.de.Zeeuw@cwi.nl>  http://homepages.cwi.nl/~pauldz/\n% Last Revision: November 24, 2003.\n%  2003 Stichting CWI, Amsterdam\n%------------------------------------------------------------------------------\n if nargin == 3\n   iopt = iscale;\n elseif nargin == 2\n   iopt = 1;\n else\n   error(' QLsuperimage - number of arguments should be either 2 or 3 ');\n end\n%\n [nS, mS] = size(S);\n if mS ~= 6\n   error(' QLsuperimage - unexpected dimensions of bookkeeping vector ');\n end\nlevels = S(nS,1);\nif mod(levels, 2) == 1\n  error('  QLsuperimage - only an even number of levels is accepted ');\nelseif levels < 1\n  superima = [];\nelse\n%\n% Firstly, we determine the dimensions of the superimage to be and create the\n% necessary space (see LISQ/storeR.m and LISQ/QLiftRec2Nevill.m)\n%\n  [Detail10, Detail01] = retrieveQ1001(1, 'd', C, S);\n  sizeR = size(Detail10) + size(Detail01);\n  n  = sizeR(1); m = sizeR(2);\n  nH = round((n+m+1.999)/2)+round((m+0.999)/2);\n  nm = round((n+m+1.999)/2)+1;\n  nV = 1;\n  levels = S(nS,1);\n  for k = 1:2:levels\n    nV = nV + nm;\n    nm = round((nm+0.999)/2);\n  end\n  Approx = retrieveR(levels, 'a', C, S);\n  [nl, ml] = size(Approx); nV = nV + nl;\n  superima = ones(nV, nH);\n%\n% Secondly, we fill the superimage with all subsequent detail coefficients \n% Put the details at the rotated quincunx grid (level 1)\n  background=max(max(max(Detail10)), max(max(Detail01)));\n  RotaDet=rota1001fill(Detail10, Detail01, background);\n  clear Detail10 Detail01;\n%-----intermezzo---begin--\n  hgram=ones(1,64);\n  hgram(64)=round(31.5*(n/m+m/n))+1;\n% hgram is a histogram that is desired to be matched by the image after\n% its values have been transformed by histeq, see the documentation of\n% histeq() in the Matlab Image Processing Toolbox.\n% Due to the rotation of the quincunx grid to make it visible, there\n% is a substantial area for padding with one colour (white or nearly\n% white). Here follows an overview of the quantities of pixels involved\n% at the rotated quincunx grid (asymptotically):\n%  Let n and m be the dimensions of the original image.\n%\n%                               2\n%                      ( n + m )\n%  Grand total:         -------\n%                          4\n%\n%                         n m\n%  Used pixels:           ---\n%                          2\n%\n%                        2    2\n%                       n  + m\n%  Pixels for padding:  --------\n%                          4\n%\n%                            2    2\n%                  n m      n  + m                 n   m\n%  Used:padding =  ---   :  -------  = 63 : 31.5*( - + - )\n%                   2          4                   m   n\n%\n%-----intermezzo---end----\n  [nl, ml] = size(RotaDet);\n  OrigV=1; OrigH=1;\n  superima(OrigV:(OrigV+nl-1), OrigH:(OrigH+ml-1)) = imequi(RotaDet,iopt,hgram);\n  Detail11 = retrieveR(2, 'd', C, S);\n  OrigV=1; OrigH=ml+1;\n  [nr, mr] = size(Detail11);\n  superima(OrigV:(OrigV+nr-1), OrigH:(OrigH+mr-1)) = imequi(Detail11,iopt);\n% Now the other levels, if any\n  OrigV=OrigV+nl; OrigH=1;\n  for k = 3:2:levels\n%   Put the details at the rotated quincunx grid\n    [Detail10, Detail01] = retrieveQ1001(k, 'd', C, S);\n    background=max([max(max(Detail10))  max(max(Detail01))]);\n    RotaDet = rota1001fill(Detail10, Detail01, background);\n    clear Detail10 Detail01;\n    [nl, ml] = size(RotaDet);\n    superima(OrigV:(OrigV+nl-1), OrigH:(OrigH+ml-1)) = imequi(RotaDet,iopt,hgram);\n    Detail11 = retrieveR(k+1, 'd', C, S);\n    OrigH=ml+1;\n    [nr, mr] = size(Detail11);\n    superima(OrigV:(OrigV+nr-1), OrigH:(OrigH+mr-1)) = imequi(Detail11,iopt);\n    clear Detail11;\n    OrigV=OrigV+nl; OrigH=1;\n  end\n% Thirdly, we fill the superimage with approximation coefficients.\n  [nl, ml] = size(Approx);\n  superima(OrigV:(OrigV+nl-1), OrigH:(OrigH+ml-1)) = imequi(Approx,iopt);\nend\n%------------------------------------------------------------------------------\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/QLsuperimage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5666253712791015}}
{"text": "function [C, S] = QLiftDec2MaxMin(X, N)\n%-----------------------------------------------------------------------------\n% QLiftDec2MaxMin\n% Multilevel 2-D decomposition by the lifting scheme and using quincunx grids\n%\n% The MaxMin scheme has been proposed by Heijmans and Goutsias, see e.g.\n%    H.J.A.M. Heijmans, J. Goutsias,\n%    Multiresolution signal decomposition schemes.\n%    Part 2: morphological wavelets.\n%    CWI Report PNA-R9905, Amsterdam, 1999.\n%    http://repository.cwi.nl:8888/cwi_repository/docs/IV/04/04625D.pdf\n%\n% Calls for: QLmaxlev,\n%            storeQ1001, storeR,\n%            getcolor01, getcolor10, getcolor00, getcolor11,\n%            putcolor01, putcolor10, putcolor00, putcolor11.        \n% See also: QLiftRec2MaxMin\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw <Paul.de.Zeeuw@cwi.nl>  http://homepages.cwi.nl/~pauldz/\n% Last Revision: May 16, 2002.\n% (c) 1999-2002 Stichting CWI, Amsterdam\n%-----------------------------------------------------------------------------\n%Firstly, check input data\n%\nif  isempty(X)\n  error(' QLiftDec2MaxMin - empty matrix ');\nelse\n  if mod(N, 2) == 1\n    error(' QLiftDec2MaxMin - only an even number of levels is accepted ');\n  end\n  if QLmaxlev(size(X), 'maxmin') < N \n    error(' QLiftDec2MaxMin - too many levels requested ');\n  end\n  if N < 2\n    disp([' QLiftDec2MaxMin - WARNING too few levels requested ' ...\n          '-> empty decomposition ']);\n  end\nend\n%\n%Secondly, start decomposition\n%\nO = X; % For the sake of efficient use of memory this could be improved upon.\n% We descend to coarser grids, integer lev indicates number of scale.\nC = []; S = [];\n\nfor lev=1:2:N\n%\n   [nO, mO] = size(O);\n   if ( nO < 3 ) || ( mO < 3)\n     error(' QLiftDec2MaxMin - too many levels ');\n   end\n   minO = min(min(O));\n   maxO = max(max(O));\n   cmin = minO-(maxO-minO);\n   cmax = maxO+(maxO-minO);\n%\n%  The Lifting Scheme proceeds from a rectangular grid\n%  towards a quincunx grid.\n%\n%  Stage: predict\n   A00 =getcolor00(O);\n   A11 =getcolor11(O);\n%  Quincunx grid Q0011 is the union of the values at .00 and .11: \"even slots\"\n%  Quincunx grid Q1001 is the union of the values at .10 and .01: \"odd slots\"\n   Q1001D01 = getcolor01(O) - synA01max(A11, A00, cmin);                % Y1\n   Q1001D10 = getcolor10(O) - synA10max(A11, A00, cmin);                % Y1\n%  At this point the union (quincunx) of Q1001D01 & Q1001D10\n%  contains the DETAILS of O.\n%\n%  For the inverse transform Q1001D01 and Q1001D10 have to be stored:\n   [C, S] = storeQ1001( Q1001D10, Q1001D01, lev, 'd', C, S);\n%\n%  Stage: update\n   Q0011A00 = A00 + ...\n        max(zeros(size(A00)), synA00max(Q1001D10, Q1001D01, cmin));     % X1\n   clear A00;\n   Q0011A11 = A11 + ...\n        max(zeros(size(A11)), synA11max(Q1001D10, Q1001D01, cmin));     % X1\n   clear A11 Q1001D10 Q1001D01;   \n%  At this point the union (quincunx) of Q0011A00 & Q0011A11\n%  contains the updated APPROXIMATION of O, the DETAILS of O\n%  were in the union (quincunx) of Q1001D01 & Q1001D10 (see above).\n%\n%  The Lifting Scheme proceeds by a subsequent step from quincunx\n%  to rectangular grid.\n%\n%  Q0011 is split into the 11 colour with the \"odd slots\" and \n%  the 00 colour with the \"even slots\".\n%\n%  Stage: predict\n   DETAIL11 = Q0011A11 - synA11Qmin(Q0011A00, size(Q0011A11), cmax);        % Y2\n   clear Q0011A11;\n%  Stage: update\n   APPROX00 = Q0011A00 + ...\n     min(zeros(size(Q0011A00)), synA00Qmin(DETAIL11, size(Q0011A00), cmax));% X2\n%\n%  DETAIL11 presents the detail gridfunction w.r.t. Q0011\n%  APPROX00 now represents the updated version of the approximation of Q0011\n%\n%  For the inverse transform DETAIL11 has to be stored:\n   [C, S] = storeR( DETAIL11, lev+1, 'd', C, S);\n   clear Q0011A00 DETAIL11;     \n% \n%  At this point gridfunction DETAIL11 containing the DETAILS has been stored,\n%  gridfunction APPROX00 contains the updated APPROXIMATION, on the (down-\n%  sampled) rectangular grid and has to be stored as well if at the highest\n%  scale.\n%  Note that APPROX00 is downsampled onto a rectangular grid with dimensions of \n%  half size of the original O.\n   if lev+1 >= N\n     [C, S] = storeR(APPROX00, lev+1, 'a', C, S);\n%    It is obligatory that at least at one scale the Approximation has to be\n%    stored or else the scheme cannot be inverted.\n     clear APPROX00;\n%    In the Lifting Scheme all scales have now been processed!\n   else\n%    We proceed to the next scale.\n     O = APPROX00; clear APPROX00;\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/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/QLiftDec2MaxMin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.56650746064162}}
{"text": "function [slice] = spm_vb_taylor_R(Y,slice)\n% Get Taylor series approximation to posterior correlation matrices\n% FORMAT [slice] = spm_vb_taylor_R(Y,slice)\n%\n% Y        - data\n% slice    - VB-GLMAR data structure\n%\n% See paper VB3.\n%__________________________________________________________________________\n% Copyright (C) 2005-2014 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: spm_vb_taylor_R.m 6079 2014-06-30 18:25:37Z spm $\n\n% Get mean hyperparameter values\nh0 = [];\nif slice.p > 0\n    if size(slice.ap_mean,2)==1\n        % Single voxel in slice\n        a      = slice.ap_mean';\n        a_cov  = slice.a_cov{1};\n    else\n        a      = mean(slice.ap_mean');\n        a_covs = cat(3,slice.a_cov{:});\n        a_cov  = mean(a_covs,3);\n    end\n    slice.mean.a     = a;\n    slice.mean.a_cov = a_cov;\n    h0 = a';\nend\nslice.mean.b = mean(slice.b');\n\nlambda = mean(slice.mean_lambda);\nslice.mean.lambda = lambda;\nh0 = [h0;lambda];\n\nR = spm_vb_get_R(slice,h0);\nslice.mean.R = R;\n\ndelta = 0.0001;\n% Get first order Taylor terms about slice\n% mean values of a and lambda\nfor i=1:length(h0)\n    h    = h0;\n    h(i) = h(i)-delta;\n    \n    [R1] = spm_vb_get_R(slice,h);\n    \n    h    = h0;\n    h(i) = h(i) + delta;\n    % Loop over hyperparameters\n    R2   = spm_vb_get_R(slice,h);\n    \n    dR(:,:,i) = (R2-R1) / (2*delta);\nend\nslice.mean.h0 = h0;\nslice.mean.dR = dR;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_vb_taylor_R.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5665074565270448}}
{"text": "function [fYr, nMn, nDay, nHr, nMin, nSec]=decyear2mat(fDy)\n    % Calculate decimal year format to matrix with columns year, month, day, hour, minute, and second.\n    % [fYr, nMn, nDay, nHr, nMin, nSec] = decyear2mat(fDy)\n    % ------------------------------------------------------------------------------------------------\n    % Calculate decimal year format (from zmap-function decyear, i.e. 1998.734)\n    % to matrix with columns year, month, day, hour, minute, and second.\n    % This function was programmed because datevec.m does not work with decimal\n    % year input format\n    %\n    % Input parameters:\n    %   fDy     Decimal year (like 1998.2515) as vector or float\n    %\n    % Output parameters:\n    %   fYr     decimal year\n    %   nMn     month\n    %   nDay    day\n    %   nHr     hour\n    %   nMin    minute\n    %   nSec    second\n    %\n    % Example [fYr, nMn, nDay, nHr, nMin, nSec]=decyear2mat(decyear([1989 12 31 10 35 44.3]))\n    %\n    % Thomas van Stiphout\n    % Mai 9, 2007\n    \n    disp('~/zmap/src/decyear2mat.m')\n    \n    % save year in decimal format\n    fYr=fDy;\n    % define leap years\n    bLeapYr = rem(fix(fDy),4) == 0 & rem(fix(fDy),100) ~= 0 | rem(fix(fDy),400) == 0 ;\n    \n    % loop over each date\n    for i=1:size(bLeapYr,1)\n        if bLeapYr(i) % for leap years\n            mDay=[0,31,60,91,121,152,182,213,244,274,305,335]'; %leapyear\n            nMn(i)=sum(mDay<rem(fDy(i),1).*366); % calculate year\n            nDay(i)=ceil(rem(fDy(i),1).*366)-mDay(nMn(i)); % calculate days\n            nHr(i)=rem(fDy(i),1).*366.*24-(mDay(nMn(i))+nDay(i)-1).*24;\n            nMin(i)=rem(nHr(i),1).*60;\n            nHr(i)=fix(nHr(i)); % hours\n            nSec(i)=rem(nMin(i),1).*60; % seconds\n            nMin(i)=fix(nMin(i)); % minutes\n            \n        else\n            mDay= [0,31,59,90,120,151,181,212,243,273,304,334]';%cumulative days in one year\n            nMn(i)=sum(mDay<rem(fDy(i),1)*365);\n            nDay(i)=ceil(rem(fDy(i),1)*365)-mDay(nMn(i));\n            nHr(i)=rem(fDy(i),1)*365*24-(mDay(nMn(i))+nDay(i)-1)*24;\n            nMin(i)=rem(nHr(i),1)*60;\n            nHr(i)=fix(nHr(i));\n            nSec(i)=rem(nMin(i),1)*60;\n            nMin(i)=fix(nMin(i));\n        end\n    end\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/decyear2mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5665074525000844}}
{"text": "% I think this script was written before understanding that rudder derivatives\n% are readily available from Tornado (?).\n% Compute the first order derivative of all coefficients with respect to\n% elevator (horizontal stabilizer rudder) deflection at different alphas. Yields\n% derivative of coefficients per radian.\n% Tornado\\T135_export has to be in the path\n% See also solverloop5.m line 312 on how to to a sweep over rudder deflections.\n\n% @\n% Copyright (C) 2017 Jonas Ruesch\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 <http://www.gnu.org/licenses/>.\n% \n% @\n\ncurrDir = pwd;\ncd(fileparts(which(mfilename)));\nscriptDir = pwd;\n\n% Load the geometry and the initial state\nload('../aircraft/ExperimentalCarrier.mat')\nload('../aircraft/State_1.5alpha_12.5ms.mat')\n\n% Must run in tornado root directory for loading airfoil profile later\ncd('F:\\svn\\dev\\matlab\\tornado\\T135_export')\n\n% Alpha range\nalphaStart = -10/180*pi;\nalphaEnd = 20/180*pi;\nnumAlphas = 31; % must be > 1\n\nresultsPos = [];\nresultsNeg = [];\nsettings=config('startup');        \n\n%lattictype=1; %Standard VLM\nlattictype=0;%Tornado freestream following wake VLM\n\nalphaStep = (alphaEnd - alphaStart)/(numAlphas-1);\nalpha = zeros(numAlphas,1);\nCXdr = zeros(numAlphas, 1);\nCYdr = zeros(numAlphas, 1);\nCZdr = zeros(numAlphas, 1);\nCldr = zeros(numAlphas, 1);\nCmdr = zeros(numAlphas, 1);\nCndr = zeros(numAlphas, 1);\n\n[n,m]=find(geo.flapped');\nresetdelta=geo.flap_vector;\npositiveFlap = 1*pi/180; % in radian\nnegativeFlap = -1*pi/180; % in radian\nflapDiff = positiveFlap - negativeFlap;\nrudder = 1; % the first rudder is on the horizontal stabilizer in ExperimentalCarrier geometry.\n\n%% loop over alphas\nfor alphaIndex=1:numAlphas\n    \n    % Modify state\n    alphaCurrent = alphaStart + (alphaIndex-1)*alphaStep;\n    state.alpha = alphaCurrent;\n    alpha(alphaIndex) = alphaCurrent;\n    state.betha = 0.0;\n    \n    %% Positive Flap \n    % Modify geometry\n    geo.flap_vector(m(rudder),n(rudder))=positiveFlap;\n    % Regenerate lattice.\n    [lattice,ref]=fLattice_setup2(geo,state,lattictype);\n    % Compute the solution\n    [resultsPos]=solver9(resultsPos,state,geo,lattice,ref);\n    [resultsPos]=coeff_create3(resultsPos,lattice,state,ref,geo);\n    \n    %% Negative Flap\n    % Modify geometry\n    geo.flap_vector(m(rudder),n(rudder))=negativeFlap;\n    % Regenerate lattice.\n    [lattice,ref]=fLattice_setup2(geo,state,lattictype);\n    % Compute the solution\n    [resultsNeg]=solver9(resultsNeg,state,geo,lattice,ref);\n    [resultsNeg]=coeff_create3(resultsNeg,lattice,state,ref,geo);\n    \n    %% Derivative\n    \n    CXdr(alphaIndex, 1) = (resultsPos.CX - resultsNeg.CX)/flapDiff;\n    CYdr(alphaIndex, 1) = (resultsPos.CY - resultsNeg.CY)/flapDiff;\n    CZdr(alphaIndex, 1) = (resultsPos.CZ - resultsNeg.CZ)/flapDiff;\n    Cldr(alphaIndex, 1) = (resultsPos.Cl - resultsNeg.Cl)/flapDiff;\n    Cmdr(alphaIndex, 1) = (resultsPos.Cm - resultsNeg.Cm)/flapDiff;\n    Cndr(alphaIndex, 1) = (resultsPos.Cn - resultsNeg.Cn)/flapDiff;\n    \n    %% Output \n    disp(['alpha ' num2str(alphaCurrent*180/pi) ' deg']);\nend\n\ngeo.flap_vector=resetdelta;\n\ncd(currDir);\n\nsave\n\nalphaDegrees = alpha*180/pi;\n\nfigure(23);\nsubplot(2,3,1);\nplot(alphaDegrees,CXdr);\ntitle('CXdr (longitudinal)');\nxlabel('alpha');\nzlabel('longitudinal coefficient derivative');\n\nsubplot(2,3,2);\nplot(alphaDegrees,CYdr);\ntitle('CYdr (lateral)');\nxlabel('alpha');\nzlabel('lateral coefficient derivative');\n\nsubplot(2,3,3);\nplot(alphaDegrees, CZdr);\ntitle('CZdr (lift)');\nxlabel('alpha');\nzlabel('lift force coefficient derivative');\n\nsubplot(2,3,4);\nplot(alphaDegrees, Cldr);\ntitle('Cldr (roll)');\nxlabel('alpha');\nzlabel('roll moment coefficient derivative');\n\nsubplot(2,3,5);\nplot(alphaDegrees, Cmdr);\ntitle('Cmdr (pitch)');\nxlabel('alpha');\nzlabel('pitch moment coefficient derivative');\n\nsubplot(2,3,6);\nplot(alphaDegrees, Cndr);\ntitle('Cndr (yaw)');\nxlabel('alpha');\nzlabel('yaw moment coefficient derivative');\n\n\n    ", "meta": {"author": "jrgenerative", "repo": "fixed-wing-sim", "sha": "53fd5b616a2bd296f37f1f105617c606c2f63066", "save_path": "github-repos/MATLAB/jrgenerative-fixed-wing-sim", "path": "github-repos/MATLAB/jrgenerative-fixed-wing-sim/fixed-wing-sim-53fd5b616a2bd296f37f1f105617c606c2f63066/ExperimentalCarrierSimulink/code/unused/mainSweepElevatorCoeffDiffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5665074516596463}}
{"text": "function rhs = globNedFitRHS3D(fm,fp, mesh, fem, dind, vind)\n\n%% USAGE: generate global load vector on a tetrahedral mesh\n%\n% INPUTS:\n% fun --- the load function from PDE (pde.f)\n% mesh --- a struct data contains mesh information.\n% fem --- global DoF for test function space\n% dind --- derivative info for test function\n%            d = [0,0,0]: function value\n%            d = [1,0,0]: Dx value\n%            d = [0,1,0]: Dy value\n%            d = [0,0,1]: Dz value\n%\n% OUTPUTS:\n% rhs --- global rhs vector\n\n% Last Modified: 08/07/2020 by Xu Zhang\n\n%% 1. RHS on non-interface elements\ndof = fem.ldof;  nloc = dof; nt = length(mesh.t);\nA = fem.area; gw = fem.gw; gx = fem.gx; gy = fem.gy; gz = fem.gz;\nX = zeros(nloc*nt, 1);\n\nfeEvalBas = @EvalNed1Bas3D;\n\nf = feval(fm,gx,gy,gz);\ntId2 = (mesh.tLoc == 2);\nf(tId2,:) = feval(fp,gx(tId2,:),gy(tId2,:),gz(tId2,:));\nind = 0;\nI = reshape(fem.g2ldof,nloc*nt,1);\nfor i = 1:dof\n    ibas = feEvalBas(fem.bas, ':', gx, gy, gz, i, dind, vind);\n    X(ind+1:ind+nt) = A.*sum((ibas.*f).*gw',2).*fem.t_e_orit(:,i);\n    ind = ind + nt;\nend\nrhs = sparse(I,1,X,length(fem.gdof),1);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/globNedFitRHS3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5665074509068225}}
{"text": "function result = convolutionalPropagation(edges, edgeWeights, fixedVertices, ...\n                    fixedDists,areaWeights,kernel,kernelTranspose,entropyLimit)\n\nne = size(edges,1);\nnv = max(edges(:));\nn = size(fixedDists,1);\n\n% Initialize marginals\nvv = ones(n,ne);\nww = ones(n,ne);\nd = zeros(n,ne);\n\nresult = ones(n,nv);\nresult(:,fixedVertices) = fixedDists;\n\n% For convenience, a binary array\nisBoundary = zeros(nv,1);\nisBoundary(fixedVertices) = 1;\n\n% For each vertex compute his incoming and outgoing edges\nincomingEdges = cell(nv,1);\noutgoingEdges = cell(nv,1);\n\nfor i=1:ne\n    e1 = edges(i,1);\n    e2 = edges(i,2);\n    outgoingEdges{e1} = [outgoingEdges{e1} i];\n    incomingEdges{e2} = [incomingEdges{e2} i];\nend\n\n% No reason to project a distribution whose neighbors haven't been projected\nqueue = zeros(nv,1);\nqueue(fixedVertices) = 1;\n\nprojectEntropy = 0;\n\nfor j=1:1000\n    toVisit = find(queue);\n    \n%     if mod(j,2)==0\n%         toVisit = toVisit(end:-1:1); % reverse order each time for fun\n%     end\n%     toVisit = toVisit(randperm(length(toVisit))); % to avoid bias\n    \n    % Reset queue\n    queue = zeros(nv,1);\n    queue(fixedVertices) = 1;\n    \n    oldResult = result;\n    \n    for k=1:length(toVisit)\n        v = toVisit(k);\n        \n        if isBoundary(v)\n            p = result(:,v);\n            \n            for i=1:length(outgoingEdges{v}) %(v,w)\n                e = outgoingEdges{v}(i);\n                ww(:,e) = p ./ kernelTranspose(vv(:,e).*areaWeights);\n            end\n             \n            for i=1:length(incomingEdges{v}) %(w,v)\n                e = incomingEdges{v}(i);\n                vv(:,e) = p ./ kernel(ww(:,e).*areaWeights);\n            end\n        else % not boundary\n            omega = sum(edgeWeights(outgoingEdges{v}))+sum(edgeWeights(incomingEdges{v}));\n            p = ones(n,1);\n            \n            for i=1:length(outgoingEdges{v}) %(v,w)\n                e = outgoingEdges{v}(i);\n                d(:,e) = ww(:,e).*kernelTranspose(vv(:,e).*areaWeights);\n                d(:,e) = max(d(:,e),1e-10);\n                p = p .* d(:,e).^(edgeWeights(e)/omega);\n            end\n            \n            for i=1:length(incomingEdges{v}) %(w,v)\n                e = incomingEdges{v}(i);\n                d(:,e) = vv(:,e).*kernel(ww(:,e).*areaWeights);\n                d(:,e) = max(d(:,e),0);\n                p = p .* d(:,e).^(edgeWeights(e)/omega);\n            end\n            \n            entropy = -sum(p.*log(p).*areaWeights);\n            if nargin == 8 && entropy > entropyLimit && projectEntropy\n                try % just ignore projection if it fails\n                    fn = @(x) full(-sum(x*areaWeights.*((p.^x).*log(p))) - entropyLimit);\n                    options = optimset('Display','none','tolfun',1e-6,'tolx',1e-6);\n                    a = fzero(fn,[0 10],options);\n                    p = p.^a;\n                end\n            end\n            \n            result(:,v) = p;\n            \n            for i=1:length(outgoingEdges{v}) %(v,w)\n                e = outgoingEdges{v}(i);\n                ww(:,e) = ww(:,e) .* p ./ d(:,e);\n            end\n            \n            for i=1:length(incomingEdges{v}) %(w,v)\n                e = incomingEdges{v}(i);\n                vv(:,e) = vv(:,e) .* p ./ d(:,e);\n            end\n        end\n        \n        queue(edges(incomingEdges{v},:)) = 1;\n        queue(edges(outgoingEdges{v},:)) = 1;\n        queue(v) = 1;\n    end\n    \n%     subplot(1,2,1);\n%     imagesc(log(max(result,1e-20)));\n%     colorbar;\n%     title(sprintf('Iteration %d, log scale',j));\n%     axis off;\n%     \n%     subplot(1,2,2)\n%     imagesc(result);\n%     colorbar;\n%     title(sprintf('Iteration %d, result',j));\n%     axis off;\n%     \n%     drawnow;\n    \n    change = sum(sum(bsxfun(@times,areaWeights,abs(result-oldResult))))/nv;\n    change = full(change);\n    \n    fprintf('Iteration %d:  %g\\n', j, change);\n    \n    if ~projectEntropy && change < 1e-3 && length(toVisit) == nv % was -3\n        fprintf('Starting to project entropy.\\n');\n        projectEntropy = 1;\n    elseif change < 1e-5 && j > 5 && projectEntropy\n        return\n    end\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/convolutional_wasserstein/convolutionalPropagation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.566507446792248}}
{"text": "function feat = poly2featuresOnly(u, v, imsize, v0, yc, f)\n\nimh = imsize(1);\nimw = imsize(2);\n\nif isempty(f)\n    f = 1.38; %S*max(size(im)) / imh;\nend\n\nu = u(:)'; \nv = v(:)';\n\n[tmp, ind] = min(u);\nu = [u(ind:end)  u(1:ind-1)];\nv = [v(ind:end)  v(1:ind-1)];\n\nu = (u - imw/2) ./ imh;\nv = 1 - (v ./ imh);\n\n[v1, ind1] = min(v); % lowest point on object in image\n\n[footx, footz] = computeGroundPosition([min(u) max(u)], [v1 v1], v0, yc, f);\nfootz(2) = footz(1) + footx(2)-footx(1);\n\n[cx, cz] = computeGroundPosition(u, v, v0, yc, f);\n\ndata.u = (u*imh+imw/2)';\ndata.v = ((1-v)*imh)';\ndata.x3d = cx;\ndata.z3d = cz;\ndata.foot = [footx footz];\n\nfeat = contactdata2features(data);\n\n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [x, z] = computeGroundPosition(u, v, v0, yc, f)\n\nz = yc*f./max((v0-v), 0.001);\nx = u.*z./f;\n    ", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/iccv07Final/src/poly2featuresOnly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5663801018721666}}
{"text": "function [W,CovW,X,CovX,R] = rotate_to_pca(W,CovW,X,CovX,weightsWW)\n% [W,CovW,X,CovX,R] = rotate_to_pca(W,CovW,X,CovX,weightsW)\n\n% Dimensionalities\n[M,D] = size(W);\n[D,N] = size(X);\n\n% Convert cell covariance matrices to arrays\ncellW = false;\nif iscell(CovW)\n  CovW = covcell_to_covarray(CovW);\n  cellW = true;\nend\n\ncellX = false;\nif iscell(CovX)\n  CovX = covcell_to_covarray(CovX);\n  cellX = true;\nend\n\nif nargin < 5 || isempty(weightsWW)\n  weightsWW = ones(M,1);\nelse\n  weightsWW = weightsWW(:) .* ones(M,1);\nend\n\n%% Find mixing rotation Xpca = R * Xgp\n\nR = 1;\n    \n% 1) Whiten <XX'>\n\nXX = X * X' + sum(CovX,3);\n[V,A] = svd(XX/N);\nR = diag(sqrt(1./diag(A))) * V';\n% Rotate W\nW = W / R;\nfor i=1:rows(W)\n  CovW(:,:,i) = R' \\ CovW(:,:,i) / R;\nend\n\n% 2) Orthogonalise weighted <W'W>\n\n% Evaluate weighted second moment\nWW = W' * diag(weightsWW) * W;\nfor m=1:M\n  WW = WW + weightsWW(m) * CovW(:,:,m);\nend\n\n% Diagonalise it\n[V,D] = svd(WW);\nR = V' * R;\n\n% Rotate W\nW = W * V;\nfor m=1:M\n  CovW(:,:,m) = V' * CovW(:,:,m) * V;\nend\n\n% $$$ % Debug the rotation!\n% $$$ weights2 = cosd(data.coordinates(2,:));\n% $$$ WW = W' * diag(weights2) * W;\n% $$$ for m=1:M\n% $$$   WW = WW + weights2(m) * CovW(:,:,m);\n% $$$ end\n% $$$ XX = R * (X*X'+sum(CovX,3)) * R';\n% $$$ WW(1:10,1:10)\n% $$$ XX(1:10,1:10) / size(X,2)\n\n\n% Rotate X to PCA\nX = R * X;\nfor n=1:N\n  CovX(:,:,n) = R * CovX(:,:,n) * R';\nend\n\n% Convert back to cells\nif cellW\n  CovW = covarray_to_covcell(CovW);\nend\nif cellX\n  CovX = covarray_to_covcell(CovX);\nend", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/pca/rotate_to_pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5663684360060762}}
{"text": "function [obj_out, varargout] = image_math(obj1, varargin)\n% Perform simple mathematical and boolean operations on image objects\n%\n% :Usage:\n% ::\n%\n%    obj_out = image_math(obj1, [optional inputs, e.g., a 2nd object, keywords])\n%\n% For objects: Type methods(object_name) for a list of special commands\n%              Type help object_name.method_name for help on specific\n%              methods.\n%\n% :Inputs:\n%\n%   **obj1:**\n%        An image_vector object\n%\n% :Optional Inputs:\n%\n%   **obj2:**\n%        An additional image_vector object\n%   **{'add', 'plus'}:**\n%        Keyword to perform image-wise addition of images in obj1\n%                              and obj2.  Assumes these are paired/matched objects.\n%   **{'subtract', 'minus'}:**\n%        Keyword to perform image-wise subtraction of images\n%                              in obj1 and obj2\n%   **{'cat', 'concatenate'}:**\n%        Concatenate obj1 and obj2 image-wise.  Requires same\n%                              number of voxels in both image sets.  Returns effects\n%                              codes of 1, -1 in obj_out.Y.\n%   **{'power'}:**\n%        Keyword to raise data to power element-wise; obj.dat = obj.dat.^b;\n%                              Followed by exponent to apply (b)\n%\n%   **{'rmssd'}:**\n%        Keyword to perform root-mean-square successive differences.\n%        Meaningful if image series is a timeseries.\n%\n%        [obj, rmssd, wh_outliers] = image_math(obj, 'rmssd');\n%        Does not affect object.\n%\n% :Outputs:\n%\n%   **obj_out:**\n%        The result - an image_vector object\n%\n% ..\n%     Author and copyright information:\n%\n%     Copyright (C) 2015  Tor Wager\n%\n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n%\n%     This program is distributed in the hope that it will be useful,\n%     but WITHOUT ANY WARRANTY; without even the implied warranty of\n%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%     GNU General Public License for more details.\n%\n%     You should have received a copy of the GNU General Public License\n%     along with this program.  If not, see <http://www.gnu.org/licenses/>.\n% ..\n\n% ..\n% DEFAULTS AND INPUTS\n% ..\n\nkeyword = '';  % initalize optional variables to default values here.\n% keyword. should enter one...\nobj2 = [];\nmy_exponent = [];\n\n% optional inputs with default values\n% -----------------------------------\n\nfor i = 1:length(varargin)\n    if ischar(varargin{i})\n        switch varargin{i}\n            \n            case {'add', 'plus'}, keyword = 'plus'; varargin{i} = [];\n            case {'subtract', 'minus'}, keyword = 'minus'; varargin{i} = [];\n            case {'cat', 'concatenate'}, keyword = 'cat'; varargin{i} = [];\n                \n            case 'power', keyword = 'power'; varargin{i+1} = my_exponent;\n                %case 'basistype', basistype = varargin{i+1}; varargin{i+1} = [];\n               \n            case 'rmssd', keyword = 'rmssd'; varargin{i} = [];\n                \n            otherwise, warning(['Unknown input string option:' varargin{i}]);\n        end\n        \n    elseif isa(varargin{i}, 'image_vector')\n        \n        obj2 = varargin{i}; varargin{i} = [];\n        \n    end\nend\n\n% -------------------------------------------------------------------------\n% DATA CHECKS\n% -------------------------------------------------------------------------\n\nswitch keyword\n    \n    case ''\n        disp('Nothing to do.')\n        return\n        \n    case 'power'\n        %Check if image_vector object\n        if ~isa(obj1,'image_vector') \n            error('Input Data is not an image_vector object')\n        end \n        \n    case {'plus', 'minus', 'cat'}\n        n1 = size(obj1.dat, 2);\n        n2 = size(obj2.dat, 2);\n        \n        y1 = ones(n1, 1);\n        y2 = ones(n2, 1);\n        \n        %Check if image_vector object\n        if ~isa(obj1,'image_vector') || ~isa(obj2,'image_vector')\n            error('Input Data is not an image_vector object')\n        end\n        \n        %Check number of rows\n        if size(obj1.dat,1) ~= size(obj2.dat,1)\n            % Voxel list mismatch\n            % Try to fix\n            \n            obj1 = replace_empty(obj1);\n            obj2 = replace_empty(obj2);\n            \n            if size(obj1.dat,1) ~= size(obj2.dat,1)\n                % If still different, give a warning and resample.\n                \n                warning('Image_math: Objects being operated on do not appear to be in the same space. Resampling 2nd object, but proceed with caution!!');\n                \n                obj2 = resample_space(obj2, obj1);\n            end\n            \n            %error('number of voxels is different between objects.')\n        end\n        \n        if strcmp(keyword, 'cat')\n            % we are done\n    \n        else\n            \n            % The rest is for plus/minus, which assume paired images\n            \n            %Check number of columns\n            if n1 ~= n2\n                error('Sizes of objects do not match.');\n            end\n            \n        end\n        \n    case 'rmssd'\n        \n    otherwise\n        warning(['Unknown keyword:' keyword]);\n        return\n        \nend % keyword ; data checks\n\n\n% -------------------------------------------------------------------------\n% RUN OPERATION\n% -------------------------------------------------------------------------\n\nswitch keyword\n    \n    case ''\n        disp('Nothing to do.')\n        return\n        \n    case 'plus'\n        \n        obj_out = obj1;\n        obj_out.dat = obj_out.dat + obj2.dat;\n        obj_out.history{end+1} = 'Image-wise addition operation by image_math';\n        obj_out.dat_descrip = cell(1, 3);\n        obj_out.dat_descrip{1} = 'Names of images added in next cells, 1st set plus 2nd';\n        obj_out.dat_descrip{2} = obj1.fullpath;\n        obj_out.dat_descrip{3} = obj2.fullpath;\n        obj_out.image_names = [];\n        obj_out.fullpath = [];\n        obj_out.files_exist = false;\n        \n    case 'minus'\n        \n        obj_out = obj1;\n        obj_out.dat = obj_out.dat - obj2.dat;\n        obj_out.history{end+1} = 'Image-wise subtraction operation by image_math';\n        obj_out.dat_descrip = cell(1, 3);\n        obj_out.dat_descrip{1} = 'Names of images subtracted in next cells, 1st set minus 2nd';\n        obj_out.dat_descrip{2} = obj1.fullpath;\n        obj_out.dat_descrip{3} = obj2.fullpath;\n        obj_out.image_names = [];\n        obj_out.fullpath = [];\n        obj_out.files_exist = false;\n        \n    case 'cat'\n        \n        obj_out = obj1;\n        obj_out.dat = [obj_out.dat obj2.dat];\n        obj_out.history{end+1} = 'Image-wise concatenation operation by image_math';\n        obj_out.image_names = char(obj1.image_names, obj2.image_names);\n        obj_out.fullpath = char(obj1.fullpath, obj2.fullpath);\n        if isfield(obj_out, 'Y')\n            obj_out.Y = [y1; -y2];\n            obj_out.Y_descrip = 'Effects codes for image set A (1) and B (-1) added by image_math';\n        end\n    case 'power'\n        obj_out = obj1;\n        obj_out.dat = obj_out.dat .^ my_exponent;\n        obj_out.history{end+1} = sprintf('Raised to %3.0f element-wise by image_math', my_exponent);\n\n    case 'rmssd'\n        \n        obj_out = obj1;\n        \n        sdiffs = diff(obj1.dat')';\n        sdiffs = [mean(sdiffs, 2) sdiffs]; % keep in image order\n        rmssd = ( mean(sdiffs .^ 2) ) .^ .5; % rmssd - root mean square successive diffs\n        \n        % avoid first time point being very different and influencing distribution and plots.\n        rmssd(1) = median(rmssd);\n        \n        % z-scores of rmssd\n        wh_outliers = scale(rmssd) > 3;\n        \n        varargout{1} = rmssd;\n        varargout{2} = wh_outliers;\n\n    otherwise\n        warning(['Unknown keyword:' keyword]);\n        return\n        \nend % switch keyword; operation\n\n\nend % main function\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_vector/image_math.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6442250928250376, "lm_q1q2_score": 0.5663684079056583}}
{"text": "%Charge Neutrality Equation\n%Assuming that the material contains only one type of dopant\n%NA (Acceptor)\nfunction F = neutralp(Nv,Nc,NA,Ev,Ec,Ea,Efp,k,T,gA)\nF = Nv*((exp(-((Ev-Efp)/(k*T)))+3*sqrt(pi/2)*((((Ev-Efp)/(k*T))+2.13)+((abs(((Ev-Efp)/(k*T))-2.13)).^2.4+9.6).^(5/12)).^(-3/2)).^-1)-Nc*((exp(-((Efp-Ec)/(k*T)))+3*sqrt(pi/2)*((((Efp-Ec)/(k*T))+2.13)+((abs(((Efp-Ec)/(k*T))-2.13)).^2.4+9.6).^(5/12)).^(-3/2)).^-1)-(NA/(1+gA*exp((Ea-Efp)/(k*T))));", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25088-fermi-level/Fermi Level/neutralp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5663254074721761}}
{"text": "%% This file is the PDE simulation file of SINDy-PI discovered Belousov-Zhabotinsky reaction.\n% Coded By: K\n% Last Updated: 2019/09/19\n%%\nfunction [rhs,x_t,z_t,s_t,u_t,x,z,s,u,x_x,z_x,s_x,u_x,x_y,z_y,s_y,u_y,x_xx,z_xx,s_xx,u_xx,x_yy,z_yy,s_yy,u_yy,x_lap,z_lap,s_lap,u_lap]=...\n    BZ_Reaction_SINDy_PI_PDE(t,xzsut,Kx,Kxx,Ky,Kyy,K22,n,N,NeedDev)\n\n% Calculate u and v terms\nxt=reshape((xzsut(1:N)),n,n);\nzt=reshape((xzsut((N+1):(2*N))),n,n);\nst=reshape((xzsut(2*N+1:3*N)),n,n);\nut=reshape((xzsut((3*N+1):(4*N))),n,n);\n\nx=real(ifft2(xt));\nz=real(ifft2(zt));\ns=real(ifft2(st));\nu=real(ifft2(ut));\n\n% Reaction Terms (You need to manully code up the equation discovered by DL-SINDy)\nxtrhs=reshape((fft2(  (0.24667*x + 0.33333*s + 0.5*z + 3.3333*x.*s - 5.0*x.*z + 2.1333*x.^2 - 3.3333*x.^3)./(x + 0.1)  )),N,1);\nztrhs=reshape((fft2(  x + 0.4*u - 1.3*z  )),N,1);\nstrhs=reshape((fft2(  0.17333*x-0.66667*s  )),N,1);\nutrhs=reshape((fft2(  100*z-133.33*u  )),N,1);\n\nrhs=[-K22.*xzsut(1:N)+xtrhs\n     -0.1*K22.*xzsut(N+1:2*N)+ztrhs\n     -K22.*xzsut(2*N+1:3*N)+strhs\n     -K22.*xzsut(3*N+1:4*N)+utrhs\n     ];\n\n % If you don't need to extract the value, don't run the following code to\n % speed up\nif NeedDev==1\n    % Get the derivative you want\n    x_x=real(ifft2(reshape((1j*Kx).*xzsut(1:N),n,n)));\n    z_x=real(ifft2(reshape((1j*Kx).*xzsut(N+1:2*N),n,n)));\n    s_x=real(ifft2(reshape((1j*Kx).*xzsut(2*N+1:3*N),n,n)));\n    u_x=real(ifft2(reshape((1j*Kx).*xzsut(3*N+1:4*N),n,n)));\n    %\n    x_y=real(ifft2(reshape((1j*Ky).*xzsut(1:N),n,n)));\n    z_y=real(ifft2(reshape((1j*Ky).*xzsut(N+1:2*N),n,n)));\n    s_y=real(ifft2(reshape((1j*Ky).*xzsut(2*N+1:3*N),n,n)));\n    u_y=real(ifft2(reshape((1j*Ky).*xzsut(3*N+1:4*N),n,n)));\n    %\n    x_xx=real(ifft2(reshape((1j*Kxx).^2.*xzsut(1:N),n,n)));\n    z_xx=real(ifft2(reshape((1j*Kxx).^2.*xzsut(N+1:2*N),n,n)));\n    s_xx=real(ifft2(reshape((1j*Kxx).^2.*xzsut(2*N+1:3*N),n,n)));\n    u_xx=real(ifft2(reshape((1j*Kxx).^2.*xzsut(3*N+1:4*N),n,n)));\n    %\n    x_yy=real(ifft2(reshape((1j*Kyy).^2.*xzsut(1:N),n,n)));\n    z_yy=real(ifft2(reshape((1j*Kyy).^2.*xzsut(N+1:2*N),n,n)));\n    s_yy=real(ifft2(reshape((1j*Kyy).^2.*xzsut(2*N+1:3*N),n,n)));\n    u_yy=real(ifft2(reshape((1j*Kyy).^2.*xzsut(3*N+1:4*N),n,n)));\n    %\n    x_t=real(ifft2(reshape(rhs(1:N),n,n)));\n    z_t=real(ifft2(reshape(rhs(N+1:2*N),n,n)));\n    s_t=real(ifft2(reshape(rhs(2*N+1:3*N),n,n)));\n    u_t=real(ifft2(reshape(rhs(3*N+1:4*N),n,n)));\n    %\n    x_lap=real(ifft2(reshape(-K22.*xzsut(1:N),n,n)));\n    z_lap=real(ifft2(reshape(-K22.*xzsut(N+1:2*N),n,n)));\n    s_lap=real(ifft2(reshape(-K22.*xzsut(2*N+1:3*N),n,n)));\n    u_lap=real(ifft2(reshape(-K22.*xzsut(3*N+1:4*N),n,n)));\n    \n    \nend\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\n\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Implicit-PDE/BZ_Reaction/BZ_Reaction_SINDy_PI_PDE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5662864127085717}}
{"text": "function r82row_order_type_test ( )\n\n%*****************************************************************************80\n%\n%% R82ROW_ORDER_TYPE_TEST tests R82ROW_ORDER_TYPE.\n%\n%  Discussion:\n%\n%    An R82ROW is a (2,N) array of R8's.\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 = 4;\n  test_num = 10;\n  seed = 123456789;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R82ROW_ORDER_TYPE_TEST\\n' );\n  fprintf ( 1, '  R82ROW_ORDER_TYPE classifies an R8VEC as\\n' );\n  fprintf ( 1, '  -1: no order\\n' );\n  fprintf ( 1, '   0: all equal;\\n' );\n  fprintf ( 1, '   1: ascending;\\n' );\n  fprintf ( 1, '   2: strictly ascending;\\n' );\n  fprintf ( 1, '   3: descending;\\n' );\n  fprintf ( 1, '   4: strictly descending.\\n' );\n  fprintf ( 1, '\\n' );\n\n  for test = 1 : test_num\n\n    [ x, seed ] = r8mat_uniform_01 ( 2, n, seed );\n\n    x(1:2,1:n) = round ( 3.0 * x(1:2,1:n) );\n\n    order = r82row_order_type ( n, x );\n\n    string = sprintf ( '  Order type = %d\\n', order );\n\n    r82row_print ( n, x, string );\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_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.566286411169206}}
{"text": "function options = reg_fine_rigid(rgb1, I1, wl, options)\n%REG_FINE_RIGID Summary of this function goes here\n%   Detailed explanation goes here\n\nt_start = tic;\n% optimize the objective function by block coordinate descent\noptions = reg_fine_rigid_internal(rgb1, I1, wl, options);\n\ndisp(['Elapsed time for fine-scale rigid registration is ',num2str(toc(t_start))]);\n\nfunction options = reg_fine_rigid_internal(rgb1, I1, wl, options)\nI = double(rgb1) / 255;\n\nlast_pos = NaN(1,6);\n\nfor iter = 1:20\n    try\n        t_start_iter = tic;\n        \n        % optimize w.r.t. degree, t, s\n        [degree, t, s] = optimize_wrt_T_s(I, I1, wl, options);\n        options.degree = degree;\n        options.t = t;\n        options.s = s;\n        \n        % optimize w.r.t. lambda\n        sigma = optimize_wrt_sigma(I, I1, options);\n        options.sigma = sigma;\n        \n        % check convergence\n        if all([degree,t,s,sigma] == last_pos)\n            disp(['Iteration ends at ',num2str(iter)]);\n            break;\n        else\n            last_pos = [degree,t,s,sigma];\n        end\n        disp(['Iteration ',num2str(iter),' lasts ',num2str(toc(t_start_iter))]);\n    catch err\n        if strcmp(err.identifier, 'Registration:DerivativeBoundary')\n            disp(['Stop optimization since boundary touch when ', ...\n                'calculating derivatives']);\n            break;\n        else\n            throw(err);\n        end\n    end\nend\n\n    \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_fine_rigid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.566286410767992}}
{"text": "function a = dirichlet_fit_s_simple(data,a)\n% DIRICHLET_FIT_S_SIMPLE   Initial guess for Dirichlet precision.\n% \n% DIRICHLET_FIT_S_SIMPLE(data,a) returns an initial guess for the Dirichlet\n% parameter vector A, by scaling the input A.\n\nbar_p = mean(log(data));\nm = a/sum(a);\nbar_p = sum(m.*bar_p);\ns = 1/(sum(m.*log(m)) - bar_p);\ns = s*(length(m)-1)/2;\na = s*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/fastfit/dirichlet_fit_s_simple.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5662863952064713}}
{"text": "function r8vec_sorted_split_test ( )\n\n%*****************************************************************************80\n%\n%% R8VEC_SORTED_SPLIT_TEST tests R8VEC_SORTED_SPLIT.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 February 2003\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 25;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8VEC_SORTED_SPLIT_TEST\\n' );\n  fprintf ( 1, '  R8VEC_SORTED_SPLIT splits a sorted vector into\\n' );\n  fprintf ( 1, '  entries less than and greater than a\\n' );\n  fprintf ( 1, '  splitting value.\\n' );\n\n  b = 0.0;\n  c = 10.0;\n  seed = 123456789;\n\n  [ a, seed ] = r8vec_uniform_ab ( n, b, c, seed );\n\n  a(1:n) = round ( a(1:n) ) / 2.0;\n\n  a = r8vec_sort_heap_a ( n, a );\n\n  split = 0.5 * ( a(1) + a(n) );\n\n  r8vec_print ( n, a, '  The sorted array:' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Splitting value is %f\\n', split );\n\n  [ i_lt, i_gt ] = r8vec_sorted_split ( n, a, split );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Lower index I_LT = %d\\n', i_lt );\n  fprintf ( 1, '  Upper index I_GT = %d\\n', i_gt );\n\n  return\nend\n", "meta": {"author": "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_sorted_split_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.5662863900192975}}
{"text": "function sparse_count_test08 ( dim_min, dim_max, level_max_min, ...\n  level_max_max )\n\n%*****************************************************************************80\n%\n%% SPARSE_COUNT_TEST08 tests OWN_E_SIZE.\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%  Parameters:\n%\n%    Input, integer DIM_MIN, the minimum spatial dimension to consider.\n%\n%    Input, integer DIM_MAX, the maximum spatial dimension to consider.\n%\n%    Input, integer LEVEL_MAX_MIN, the minimum value of LEVEL_MAX to consider.\n%\n%    Input, integer LEVEL_MAX_MAX, the maximum value of LEVEL_MAX to consider.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'SPARSE_COUNT_TEST08\\n' );\n  fprintf ( 1, '  OWN_E_SIZE returns the number of\\n' );\n  fprintf ( 1, '  distinct points in an OWN_E sparse grid made from \\n' );\n  fprintf ( 1, '  product grids formed from open weakly nested \\n' );\n  fprintf ( 1, '  quadrature rules with exponential growth, including:\\n' );\n  fprintf ( 1, '  * GGH_E, the Generalized Gauss-Hermite Exponential Growth Family;\\n' );\n  fprintf ( 1, '  * GH_E, the Gauss-Hermite Exponential Growth Family;\\n' );\n  fprintf ( 1, '  * LG_E, the Gauss-Legendre Exponential Growth Family;\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '   DIM: ' );\n\n  for dim_num = dim_min : dim_max\n    fprintf ( 1, '  %10d', dim_num );\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '   LEVEL_MAX\\n' );\n  fprintf ( 1, '\\n' );\n\n  for level_max = level_max_min : level_max_max\n    fprintf ( 1, '    %4d', level_max );\n    for dim_num = dim_min : dim_max\n      point_num = own_e_size ( dim_num, level_max );\n      fprintf ( 1, '  %10d', point_num );\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_count/sparse_count_test08.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.566265822584836}}
{"text": "function [dcenter,i0,i1,j0,j1] = dcenter_pair(trx,fly1,fly2)\n% modified AR 3/8/2018 add i0,i1,j0,j1 to output \n% initialize\ndcenter = nan(1,trx(fly1).nframes);\n\n% get start and end frames of overlap\nt0 = max(trx(fly1).firstframe,trx(fly2).firstframe);\nt1 = min(trx(fly1).endframe,trx(fly2).endframe);\ni0 = nan;\ni1 = nan; \nj0 = nan;\nj1 = nan;\n% no overlap\nif t1 < t0, \n  return;\nend\n  \n% indices for these frames\ni0 = t0 + trx(fly1).off;\ni1 = t1 + trx(fly1).off;\nj0 = t0 + trx(fly2).off;\nj1 = t1 + trx(fly2).off;\n\n% centroid distance\ndx = trx(fly2).x_mm(j0:j1)-trx(fly1).x_mm(i0:i1);\ndy = trx(fly2).y_mm(j0:j1)-trx(fly1).y_mm(i0:i1);\nz = sqrt(dx.^2 + dy.^2);\ndcenter(i0:i1) = z;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/dcenter_pair.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5662256829291531}}
{"text": "function [OfConstraint, OfAll] = determineFluxValuesOnBoundary(model, solution)\n% This function determines the number of reactions in the flux distributions that are on\n% the boundaries\n%\n% [OfConstraint, OfAll] = determineFluxValuesOnBoundary(model, solution)\n%\n% INPUT\n% model         Model structure\n% solution      Solution structure\n% \n% OUTPUT \n% OfConstraint  Fraction of flux values that are on the lower and upper bounds\n%               of all constrained reactions (assuming a minimum infinity\n%               of -1,000,000 and a  maximum infinity of 1,000,000\n% OfAll         Fraction of flux values that are on the lower and upper bounds\n%               of all reactions in the model\n% \n% Ines Thiele, December 2018\n%\n%\n%\nminInf = -1000000;\nmaxInf = 1000000;\n% find reactions that have flux values on upper bound \nI = find(abs(solution.full)>1e-6);\n% find all non-zero and non-inf bounds\nJ = find(abs(model.ub)~=0);\nJi = find(abs(model.ub)<=abs(minInf));\nIJ = intersect(I,J);\nIJ = intersect(IJ,Ji);\nUsedub = model.ub(IJ);\nUsedF = solution.full(IJ);\nUsedR = model.rxns(IJ);\nOnUB= length(find(abs(Usedub-UsedF)<1e-5));\n\n% find reactions that have flux values on lower bound \nI = find(abs(solution.full)>1e-6);\n% find all non-zero and non-inf bounds\nJ = find(abs(model.lb)~=0);\nJi = find(abs(model.lb)<=abs(maxInf));\nIJ = intersect(I,J);\nIJ = intersect(IJ,Ji);\nUsedlb = model.lb(IJ);\nUsedF = solution.full(IJ);\nUsedR = model.rxns(IJ);\nOnLB= length(find(abs(Usedlb-UsedF)<1e-5));\n\n% constraint reactions\nminConstraints = length(intersect(find(model.lb>minInf),find(model.lb)));\nmaxConstraints =length(intersect(find(model.ub<maxInf),find(model.ub)));\nPercentageConstraintRxns_model = (minConstraints + maxConstraints)*100/length(model.ub);\n%percentage of all reactions\nOfAll = (OnLB+OnUB)/length(model.rxns);\nOfConstraint = (OnLB+OnUB)/(minConstraints + maxConstraints);\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/wholeBody/PSCMToolbox/determineFluxValuesOnBoundary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.566202936512151}}
{"text": "%% This file is the main file of using the SINDy-PI method to\n% infer the Single Pendulum on Cart Model.\n%\n% Date: 2019/07/26\n% Coded By: K\n\n%% Close all, clear all, clc\nclose all;clear all; clc;\ndir\nset(0,'defaulttextInterpreter','latex')\n[status,message,messageid] = mkdir('Results');\naddpath('Function');  \n%% Simulate the budworm population growth and gather the simulation data\n\n%Define the model parameters\nM=1;m=1;L=1;g=9.81;\n\n% Define noise level and add gaussian noise to the data\nnoise=0.02;\n\n% Define whehter you have control, if you have it, please define it\nControl=1;\n\n%Define whether you want to shuffel the final data\nShuffle=0;\n\n% Peform simulation\nstate0=[0.3;0;1;0];state0_test=[0.1;0;0.3;0];\ndt=0.001;T=16;T_test=2;\ntspan=0:dt:T;tspan_test=0:dt:T_test;\nu=-0.2+0.5*sin(6*(tspan'));\nu_test=-1+1*sin((tspan_test'))+3*sin(2*(tspan_test'));\n[dData,Data]=Get_Sim_Data(@(t,y,u)SinglePendulum_ODE(t,y,u,M,m,L,g),state0,u,tspan,noise,Control,Shuffle);\ndData(:,1)=Data(:,3);dData(:,2)=Data(:,4);\n[dData_test,Data_test]=Get_Sim_Data(@(t,y,u)SinglePendulum_ODE(t,y,u,M,m,L,g),state0_test,u_test,tspan_test,noise,Control,Shuffle);\ndData_test(:,1)=Data_test(:,3);dData_test(:,2)=Data_test(:,4);\n%% Plot the simulation data\n% close all\n% HorizontalRange=5*L;\n% VerticalRange=2.5*L;\n% displayrate=1;\n% cartoonOffLineAcce(Data(:,2),Data(:,1),L,HorizontalRange,VerticalRange,displayrate)\n%%\n% figure(1)\n% plot(tspan,Data(:,1))\n% title('Theta')\n% grid on\n% %\n% figure(2)\n% plot(tspan,Data(:,2))\n% title('Position')\n% grid on\n% %\n% figure(3)\n% plot(tspan,Data(:,3))\n% title('dTheta')\n% grid on\n% %\n% figure(4)\n% plot(tspan,Data(:,4))\n% title('Velocity')\n% grid on\n% %\n% figure(5)\n% plot(tspan,u,'linewidth',3,'color','black')\n% box('off')\n% axis('on')\n\n%% Now perform sparse regression of non-linear dynamics\n\n% Get the number of states we have\n[dtat_length,n_state]=size(Data);\n\n% Define the control input(Should be zero in our example)\nn_control=1;\n\n% Choose whether you want to display actual ODE or not\ndisp_actual_ode=1;\n\n% If the ODEs you want to display is the actual underlyting dynamics of the\n% system, please set actual as 1\nactual=1;\n\n% Print the actual ODE we try to discover\ndigits(4)\nz_vars=sym('z',[1,n_state]);\nu_vars=sym('u',[1,n_control]);\nd_vars=sym('dz',[1,n_state]);\nODEsP=SinglePendulum_ODE(0,z_vars,u_vars,M,m,L,g);\nfprintf('The actual ODE of the system is/are :\\n')\nfor i=1:n_state\n    fprintf(strcat(char(d_vars(1,i)),'=',char(ODEsP(i,1)),'\\n'));\nend\n\n% The implicit ODE has the following form:\n% dz1=z3\n% dz2=z4\n% dz3=((981*sin(z1))/50 + u1*cos(z1) + z3^2*cos(z1)*sin(z1))/(cos(z1)^2 - 2)\n% dz4=-(u1 + z3^2*sin(z1) + (981*cos(z1)*sin(z1))/100)/(cos(z1)^2 - 2)\n\n% Create symbolic states\ndz=sym('dz',[n_state,1]);\nz=sym('z',[n_state,1]);\nuc=sym('u',[n_control,1]);\n\n% Now we first create the parameters of the function right hand side\nHighest_Poly_Order_Guess=1;\nHighest_Trig_Order_Guess=2;\nHighest_U_Order_Guess=0;\n\n% Then create the right hand side library parameters\nHighest_Poly_Order=2;\nHighest_Trig_Order=2;\nHighest_U_Order=0;\nHighest_dPoly_Order=1;\n\n%% Define parameters for the sparese regression\nlam=[1e-4;5e-4;1e-3;2e-3;3e-3;4e-3;5e-3;6e-3;7e-3;8e-3;9e-3;1e-2;2e-2;3e-2;4e-2;5e-2;...\n    6e-2;7e-2;8e-2;9e-2;1e-1;2e-1;3e-1;4e-1;5e-1;6e-1;7e-1;8e-1;9e-1;1;1.5;2;2.5;3;3.5;4;4.5;5;...\n    6;7;8;9;10;20;30;40;50;100;200];\n\n\nN_iter=20;\ndisp=0;\nLibPoly=[1;1;0;0];\nLibTrig=[0;0;3;4];\n%\nGuessPoly=[1;1;0;0];\nGuessTrig=[0;0;1;1];\n\n% Normalize the library?\nNormalizeLib=0;\n\n% Define a cell matrix to store the variable\nXi_Final=cell(n_state,1);\nScore_Final=cell(n_state,1);\n\nfor iter=1:n_state\n    % Change the library base on what equation you want to work on\n    Highest_Poly_Order=LibPoly(iter);\n    Highest_Poly_Order_Guess=GuessPoly(iter);\n    Highest_Trig_Order=LibTrig(iter);\n    Highest_Trig_Order_Guess=GuessTrig(iter);\n    \n    fprintf('Calculating the %i expression \\n',iter)\n    \n    % According to the previous parameter generate the left hand side guess\n    [LHS_Data,LHS_Sym]=GuessLib(Data,dData(:,iter),iter,u,Highest_Poly_Order_Guess,Highest_Trig_Order_Guess,Highest_U_Order_Guess);\n    \n    %Generate the corresponding data\n    [SINDy_Data,SINDy_Struct]=SINDyLib(Data,dData(:,iter),iter,u,Highest_Poly_Order,Highest_Trig_Order,Highest_U_Order,Highest_dPoly_Order);\n    \n    % Run the for loop and try all the left hand guess\n    for i=1:length(LHS_Sym)\n        fprintf('\\n\\t\\t Testing the left hand side as %s... \\n',cell2sym(LHS_Sym(1,i)))\n        \n        % Exclude the guess from SINDy-PI library\n        [RHS_Data,RHS_Struct]=ExcludeGuess(SINDy_Data,SINDy_Struct,LHS_Sym{i});\n        \n        if iter==1\n            Xi=cell(length(LHS_Sym),length(lam));\n            Score=zeros(length(LHS_Sym),length(lam));\n            ODE=cell(length(LHS_Sym),length(lam));\n        end\n        \n        % Define dummy variables for parfor\n        LHS_Sym_Dum=LHS_Sym{i};\n        LHS_Data_Dum=LHS_Data(:,i);\n        dz_Dum=dz(iter);\n        dData_test_dum=dData_test(:,iter);\n        for j=1:length(lam)\n            fprintf('\\n\\t\\t Testing the lambda as %d... \\n',lam(j,1))\n            % Perform the sparse regression problem\n            [Xi{i,j},ODE{i,j}]=sparsifyDynamics(RHS_Data,LHS_Data_Dum,LHS_Sym_Dum,lam(j,1),N_iter,RHS_Struct,disp,NormalizeLib);\n            \n            % Perform sybolic calculation and solve for dX\n            Eqn=LHS_Sym_Dum==ODE{i,j};\n            digits(4)\n            ODE_Guess=simplify(vpa(solve(Eqn,dz_Dum)));\n            % Store the result of each valuation\n            try\n                ODEs(i,j)=ODE_Guess;\n                func=matlabFunction(ODEs(i,j),'Vars',{z,uc});\n                funcVal=func(Data_test',u_test')';\n                Score(i,j)=norm(dData_test_dum-funcVal)/norm(dData_test(:,iter));\n            catch\n                ODEs(i,j)=0;\n                Score(i,j)=NaN;\n            end\n        end\n    end\n    \n    % Calculate the minimum score\n    [minVal,minIndex]=min(Score,[],2);\n    [minVal2,minIndex2]=min(minVal);\n    \n    % Store the best ODE approximation\n    ODE_Best(iter,1)=ODEs(minIndex2,minIndex(minIndex2));\n    \n    % Print the result\n    fprintf('\\n \\tThe SINDy-PI discovered Best ODE for %i equation is:\\n',iter)\n    digits(4)\n    fprintf(strcat(char(dz(iter)),'=',char(simplify(ODE_Best(iter,1))),'\\n'));\n    \n    % Save this result\n    Xi_Final{iter,1}=Xi;\n    Score_Final{iter,1}=Score;\n    \n    % Plot the score\n    figure(iter)\n    hold on\n    for k=1:length(LHS_Sym)\n        plot(lam,Score(k,:),'color',[1 iter*0.2 iter*0.25],'linewidth',2.5)\n        scatter(lam,Score(k,:),100,'MarkerFaceColor',[1 iter*0.2 iter*0.25],'MarkerEdgeColor',[0 0 0],'linewidth',2.5)\n        set(gca,'XScale','log')\n    end\n    \nend\n\n\n%% Now generate the ODE function file and test the accuracy of the\n% identified system\nNoise=0;\n\n% Now generate this best guess ODE\nGenerate_ODE_RHS(ODE_Best(:,1),n_state,n_control);\n\n% Simulate the system with the SINDy-PI identified ODE\n%state0_test=[0.5;0.1;0.1;-0.1];\nstate0_test=[pi;0;0;0];\nu_test=-0.5+0.2*sin((tspan_test'))+0.3*sin(2*(tspan_test'));\nLHS_Sym=0;\n[dData_test,Data_test]=Get_Sim_Data(@(t,y,u)SinglePendulum_ODE(t,y,u,M,m,L,g),state0_test,u_test,tspan_test,Noise,Control,Shuffle);\n[d_Data_Es,Data_Es]=Get_Sim_Data(@(t,y,u)Sindy_ODE_RHS(t,y,u),state0_test,u_test,tspan_test,Noise,Control,Shuffle);\n\n%% Print the Result\ndisp_best=1;\nif disp_best==1\n    fprintf('The SINDy-PI discovered Best ODE is:\\n')\n    digits(4)\n    for i=1:n_state\n        fprintf(strcat(char(dz(i)),'=',char(simplify(ODE_Best(i,1))),'\\n'));\n    end\nend\n%% Save the result\nFile_Name=strcat('Results/Noise_Level_',num2str(noise),'.mat');\nsave(File_Name,'Xi_Final','Score_Final','ODE_Best','state0_test',...\n    'u_test','dData_test','Data_test','d_Data_Es','Data_Es','tspan_test')\n\n%% Plot the simulation data\nclose all\n% Create the new directory to save the plot\n[fld_status, fld_msg, fld_msgID]=mkdir('Figures');\n%\nfigure(1)\nplot(tspan_test,Data_test(:,1),'linewidth',4.5,'Color','black')\nhold on\nplot(tspan_test,Data_Es(:,1),'linewidth',4.5,'linestyle','--','color','blue')\n% legend('Actual Dynamics','Best Model')\n% title('Validation','FontSize',24)\n% xlabel('Time $(t)$','FontSize', 24)\n% ylabel('$\\theta(t)$','FontSize', 24)\nset(gca,'FontSize',34);\ngrid on\nh = gca; \nset(gca,'xticklabel',[])\nset(gcf,'Position',[100 100 600 400]); \nset(gcf,'PaperPositionMode','auto');\nbox('on')\n%print('-depsc2', '-loose', 'Figures/SinglePendulum_Thetat1.eps');\n\n%\nfigure(2)\nplot(tspan_test,Data_test(:,2),'linewidth',4.5,'Color','black')\nhold on\nplot(tspan_test,Data_Es(:,2),'linewidth',4.5,'linestyle','--','color','blue')\n% legend('Actual Dynamics','Best Model')\n% title('Validation','FontSize',18)\n% xlabel('Time $(t)$','FontSize', 18)\n% ylabel('$x(t)$','FontSize', 18)\nset(gca,'FontSize',34);\ngrid on\n%h = gca; h.XAxis.Visible = 'off';\nset(gcf,'Position',[100 100 600 400]); \nset(gcf,'PaperPositionMode','auto');\nbox('on')\nprint('-depsc2', '-loose', 'Figures/SinglePendulum_x.eps');\n\n%%\nfigure(3)\nplot(tspan_test,Data_test(:,3),'linewidth',2,'Color','green')\nhold on\nplot(tspan_test,Data_Es(:,3),'linewidth',2,'linestyle','--','color','blue')\nlegend('Actual Dynamics','Best Model')\ntitle('Validation','FontSize',18)\nxlabel('Time $(t)$','FontSize', 18)\nylabel('$\\dot{\\theta}(t)$','FontSize', 18)\nset(gca,'FontSize',18);\ngrid on\n\nset(gcf,'Position',[100 100 600 400]); \nset(gcf,'PaperPositionMode','auto');\nprint('-depsc2', '-loose', 'Figures/SinglePendulum_dThetat.eps');\n\n%%\nfigure(4)\nplot(tspan_test,Data_test(:,4),'linewidth',2,'Color','green')\nhold on\nplot(tspan_test,Data_Es(:,4),'linewidth',2,'linestyle','--','color','blue')\nlegend('Actual Dynamics','Best Model')\ntitle('Validation','FontSize',18)\nxlabel('Time $(t)$','FontSize', 18)\nylabel('$\\dot{x}(t)$','FontSize', 18)\nset(gca,'FontSize',18);\ngrid on\n\nset(gcf,'Position',[100 100 600 400]); \nset(gcf,'PaperPositionMode','auto');\nprint('-depsc2', '-loose', 'Figures/SinglePendulum_dx.eps');\n\n%\nfigure(5)\nplot(Data_test(:,1),Data_test(:,3),'linewidth',2,'Color','green')\nhold on\nplot(Data_Es(:,1),Data_Es(:,3),'linewidth',2,'linestyle','--','color','blue')\nlegend('Actual Dynamics','Best Model')\ntitle('Validation','FontSize',18)\nxlabel('$\\theta(t)$','FontSize', 18)\nylabel('$\\dot{\\theta}(t)$','FontSize', 18)\nset(gca,'FontSize',18);\ngrid on\n\nset(gcf,'Position',[100 100 600 400]); \nset(gcf,'PaperPositionMode','auto');\nprint('-depsc2', '-loose', 'Figures/SinglePendulum_theta_vs_dtheta.eps');\n\n%\nfigure(6)\nplot(Data_test(:,2),Data_test(:,4),'linewidth',2,'Color','green')\nhold on\nplot(Data_Es(:,2),Data_Es(:,4),'linewidth',2,'linestyle','--','color','blue')\nlegend('Actual Dynamics','Best Model')\ntitle('Validation','FontSize',18)\nxlabel('$x(t)$','FontSize', 18)\nylabel('$\\dot{x}(t)$','FontSize', 18)\nset(gca,'FontSize',18);\ngrid on\n\nset(gcf,'Position',[100 100 600 400]); \nset(gcf,'PaperPositionMode','auto');\nprint('-depsc2', '-loose', 'Figures/SinglePendulum_x_vs_dx.eps');\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/SinglePendulumOnCart/SinglePendulum_Main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311906630568, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5662029305936668}}
{"text": "function rswVector = rotateVectorFromEciToRsw(eciVector, rVect, vVect)\n    R = normVector(rVect);\n    W = normVector(crossARH(rVect, vVect));\n    S = normVector(crossARH(W,R));\n    \n    ECI2RSWRotMat = [R,S,W];\n    \n    rswVector = ECI2RSWRotMat \\ eciVector;\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/astrodynamics/rotateVectorFromEciToRsw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5661667283213183}}
{"text": "clc\nclear all\nbb=8; % block size\nK=256; % number of atoms in the dictionary\nimg =imread('Test_Fig2_Missing.png');\n\n[N,M,dim]=size(img);\nimg = double(img);\n%Compute mask and extracting its patches\nMask = double(~(img(:,:,1)==0));\nblkMask=im2col(Mask,[bb,bb],'sliding');  % distinct  sliding\nimg_yuv = rgb2ycbcr(uint8(img));\nimg_inpaint_yuv = zeros(size(img_yuv));\n% Interpolation CbCr Componet\nimg_inpaint_yuv(:,:,2) = Interpolation(double(img_yuv(:,:,2)),~Mask); \nimg_inpaint_yuv(:,:,3) = Interpolation(double(img_yuv(:,:,3)),~Mask);\nIMin0 = double(img_yuv(:,:,1)); \n\nload Dict\nload Coeff\n\n% Creating the output image\nimag_Y=ImageRecover(IMin0,Dict,Coeff); \nimag_Y=max(min(imag_Y,255),0);\n\nimg_inpaint_yuv(:,:,1) = imag_Y; \nimg_inpaint_rgb = ycbcr2rgb(uint8(img_inpaint_yuv));\nimshow(uint8(img_inpaint_rgb))\nimwrite(img_inpaint_rgb,strcat('KSVD_Result_','iter_25','.png'),'png')", "meta": {"author": "chongyangtao", "repo": "Color-Image-Inpainting", "sha": "3cda955558504cd8c78cf1aca55bd7f98f178b3a", "save_path": "github-repos/MATLAB/chongyangtao-Color-Image-Inpainting", "path": "github-repos/MATLAB/chongyangtao-Color-Image-Inpainting/Color-Image-Inpainting-3cda955558504cd8c78cf1aca55bd7f98f178b3a/test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5661667240738909}}
{"text": "function outputImage = ifft(this, applicationDimension)\n% IFFT (including IFFT-shift and normalization) using image2k\n%\n%   Y = MrImage()\n%   Y.ifft(applicationDimension)\n%\n% This is a method of class MrImage.\n%\n% IN\n%\n% OUT\n%\n% EXAMPLE\n%   Y = MrImage();\n%   Y.ifft(4); % convert each voxel's time series to frequency space by\n%               applying iFFT to 4th dimension\n%   Y.ifft('2D') % slice-wise iFFT for transversal slices\n%   Y.ifft([1 2]) % slice-wise iFFT, same as previous\n%   Y.ifft([2 3]) % slice-wise iFFT, but for sagittal slices (dim 2 and 3 = 1\n%                %  slice)\n%   Y.ifft('3D') % volume-wise iFFT\n%   Y.ifft([1 2 3]) % volume-wise iFFT, same as previous\n%   Y.ifft([1 2 4]) % volume-wise iFFT, but for time series of a k-space\n%                  % voxel, acquired in a 2D k-space\n%            \n%\n%   See also MrImage MrImage.image2k\n\n% Author:   Saskia Bollmann & Lars Kasper\n% Created:  2015-12-12\n% Copyright (C) 2015 Institute for Biomedical Engineering\n%                    University of Zurich and ETH Zurich\n%\n% This file is part of the TAPAS UniQC Toolbox, which is released\n% under the terms of the GNU General Public License (GPL), version 3. \n% 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).\n% For further details, see the file COPYING or\n%  <http://www.gnu.org/licenses/>.\n\noutputImage = image2k(this, applicationDimension);", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrDataNd/ifft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.566033942223481}}
{"text": "function res = vg_method_train(X, Y, args)\n\n% Variational Garrote: performs linear regression with L0-norm penalty (Spike and Slab model)\n%   See file test_vg.m for an example of use\n%\n% required parameters (n input dimension, p samples)\n%   X     : n x p (training set, input)\n%   Y     : 1 x s (training set, output)\n%\n% args: optional parameters (default)\n%   method      : method for optimization 'dual' or 'regression' for fixed gamma ('dual')\n%   maxiter     : maximum number of iterations for optimization for fixed gamma (1e4)\n%   max_sum_m   : increases gamma values until sum(m)=max_sum_m  (n/2)\n%   beta_max    : increases gamma values until beta=beta_max (1e3)\n%   n_gamma     : number of gamma values to scan (50)\n%   dmmin       : convergence threshold for mean field error (1e-12)\n%   valset      : part of the training set used for validation (0.1*p)\n\n%----------------\n% REQUIRED PARAMS\n\nn = size(X,1);\n\n%----------------\n% OPTIONAL PARAMS\n\n% method for optimization {dual or regression} for fixed gamma\nif ~isfield(args, 'method') method='dual'; else method=args.method; end\n\n% maximum number of iterations for optimization for fixed gamma\nif ~isfield(args, 'maxiter') maxiter=1e4; else maxiter=args.maxiter; end\n\n% increases gamma values until sum(m)=max_sum_m\nif ~isfield(args, 'max_sum_m') max_sum_m=n/2; else max_sum_m=args.max_sum_m; end\n\n% increases gamma values until beta=beta_max\nif ~isfield(args, 'beta_max') beta_max=1e3; else beta_max=args.beta_max; end\n\n% number of gamma values to scan\nif ~isfield(args, 'n_gamma') n_gamma=50; else n_gamma=args.n_gamma; end\n\n% convergence threshold for mean field error\nif ~isfield(args, 'dmmin') dmmin=1e-12; else dmmin=args.dmmin; end\n\n% part of the training set used for validation (default 0.1*p)\nif ~isfield(args, 'valset') valset=ceil(.25*n); else valset=args.valset; end\n\n% randomly split training and validation datasets\ndataok = false;\nnits = 1;\np = size(X,2)-valset;\npv = valset;\nwhile ~dataok && nits < 10\n    it = randperm(size(X,2));\n    xv = X(:,it(1:valset));\n    yv = Y(:,it(1:valset));\n    x = X(:,it(valset+1:end));\n    y = Y(:,it(valset+1:end));\n    \n    % normalize training\n    x=x-mean(x,2)*ones(1,p);\n    dx=sqrt(1/p*sum(x.^2,2));\n    x=x./(dx*ones(1,p));\n    y=y-mean(y);\n    \n    % normalize validation\n    xv=xv-mean(xv,2)*ones(1,pv);\n    dxv=sqrt(1/pv*sum(xv.^2,2));\n    xv=xv./(dxv*ones(1,pv));\n    yv=yv-mean(yv);\n    \n    dataok = ~any(isnan(x(:))) && ~any(isnan(xv(:)));\n    nits=nits+1;\nend\nif nits==10\n    error('VG Error: Increase training set size');\nend\n\n%----------------\n% compute garrote solution for range of gammas\n% first from gamma_min to gamma_max and then in\n% a second pass from gamma_max to gamma_min.\n\n% C is input data covariance matrix.\nif strcmp(method, 'regression')\n    if n<=1500,\t\n        C=x*x'/p;\n    end;\nend\n\n% b is input output covariance\nb=x*y'/p;\n\n% sigma is output variance\nsigmay=y*y'/p;\n\n% set gamma range (min, max and step size)\ndelta=1e-8;\n[b2sort,isort]=sort(b.^2,'descend');\nbsort=b(isort);\ngamma_min=log(delta*sigmay/p/max(abs(b)));\neps_gamma=0.001;\ngamma_max=eps_gamma*gamma_min;\ngamma_all =linspace(gamma_min,gamma_max,n_gamma);\n\n% initial step size of mean field update\neta0=1; %e-2;\n% initial step size for change in w in dual.m\neta_w0=0.02;\n\n% input data variance\nchi_ii=1/p*sum(x.^2,2);\nif sum(abs(chi_ii-1)>1e-10),\n    fprintf('input design matrix is not normalized\\n');\n    pause\nend;\n\nlg=n_gamma;\nkl_all=inf(lg,2);\nv_all=inf(lg,2,n);\nm_all=inf(lg,2,n);\nbeta_all=inf(lg,2);\nv_mf_all=inf(lg,n);\nm_mf_all=inf(lg,n);\niter_all=inf(lg,2);\nbeta_mf_all=inf(1,lg);\nerror_mf_all=inf(1,lg);\nerrorv_mf_all=inf(1,lg);\nm=zeros(1,n);\n\n% the estimated inverse noise variance beta is initialized as the\n% output variance\nbeta=1/sigmay;\ni=0;\n\n% for gamma is gamma_min to gamma_max, or when some criteria are\n% satisfied\nwhile (beta<beta_max)&&(i<n_gamma)&&(sum(m)<max_sum_m),\n\ti=i+1;\n\tgamma=gamma_all(i);\n    eval(method);\n\tv_all(i,1,:)=v;\n\tm_all(i,1,:)=m;\n\tbeta_all(i,1)=beta;\n\titer_all(i,1)=iter;\n\tkl_all(i,1)=kl1;\n\tfprintf('gamma = %f beta = %f sum(m) = %f iter = %d kl = %f\\n',gamma,beta,sum(m),iter,kl1);\nend;\n\nif beta>=beta_max\n fprintf('-----------------------------------------------------------\\n');\n fprintf('beta > beta_max (%.3f > %.3f)\\n', beta, beta_max);\n if i>1\n    m = squeeze(m_all(i-1,1,:))'; \n end\nend\nif sum(m)>=max_sum_m\n fprintf('-----------------------------------------------------------\\n');\n fprintf('sum(m) > max_sum_m (%.3f > %.3f)\\n', sum(m), max_sum_m);\nend\n\n% for gamma is current gamma decreasing to gamma_min \nimax=i-1;\nfor i=imax:-1:1,\n\tgamma=gamma_all(i);\n    eval(method);\n\tv_all(i,2,:)=v;\n\tm_all(i,2,:)=m;\n\tbeta_all(i,2)=beta;\n\titer_all(i,2)=iter;\n\tkl_all(i,2)=kl1;\n\tfprintf('gamma = %f beta = %f sum(m) = %f iter = %d kl = %f\\n',gamma,beta,sum(m),iter,kl1);\nend;\n\n% select for each gamma from these two solutions the one with lowest KL \n[klmin, imin]=min(kl_all,[],2);\nfor i=1:imax,\n\tv_mf_all(i,:)=squeeze(v_all(i,imin(i),:))';\n\tm_mf_all(i,:)=squeeze(m_all(i,imin(i),:))';\n\tbeta_mf_all(i)=beta_all(i,imin(i));\n\terror_mf_all(i)=1/p*sum((y-v_mf_all(i,:)*x).^2,2);\n\terrorv_mf_all(i)=1/pv*sum((yv-v_mf_all(i,:)*xv).^2,2);\nend;\n\n% select the gamma that optimizes the validation error (errorv_mf_all)\n[minerrorv i]=min(errorv_mf_all(1:imax));\n\nres.gamma_mf=gamma_all(i);\nres.v_mf=v_mf_all(i,:);\nres.m_mf=m_mf_all(i,:);\nres.n_mf1=sum(res.m_mf>0.5);\n\nres.error_mf=error_mf_all(i);\nres.errorv_mf=errorv_mf_all(i);\nres.beta_mf=beta_mf_all(i);\n\nif (res.beta_mf==beta_max)\n\tfprintf('beta_max too small: beta_mf %6.4f, beta_max %6.4f\\n', beta_mf(iruns),beta_max);\n\tpause\nend;\nif (res.gamma_mf==gamma_min)\n\tfprintf('gamma at minimum range boundary\\n');\nend;\nif (res.gamma_mf==gamma_max)\n\tfprintf('gamma at maxium range boundary\\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/vg/vg_method_train.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5660339203186584}}
{"text": "classdef CEC2017_F13 < PROBLEM\n% <single> <real> <constrained>\n% CEC'2017 constrained optimization benchmark problem\n\n%------------------------------- Reference --------------------------------\n% G. Wu, R. Mallipeddi, and P. N. Suganthan, Problem definitions and\n% evaluation criteria for the CEC 2017 competition on constrained real-\n% parameter optimization, National University of Defense Technology, China,\n% 2016.\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        O;  % Optimal decision vector\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2017.mat'),'Data');\n            obj.O = Data{12}.o;\n            obj.M = 1;\n            if isempty(obj.D); obj.D = 10; end\n            obj.D = min(obj.D,length(obj.O));\n            obj.lower    = zeros(1,obj.D) - 100;\n            obj.upper    = zeros(1,obj.D) + 100;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            Y = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopObj = sum(100*(Y(:,1:end-1).^2-Y(:,2:end)).^2+(Y(:,1:end-1)-1).^2,2);\n        end\n        %% Calculate constraint violations\n        function PopCon = CalCon(obj,PopDec)\n            Y = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopCon(:,1) = sum(Y.^2-10*cos(2*pi*Y)+10,2) - 100;\n            PopCon(:,2) = sum(Y,2) - 2*size(Y,2);\n            PopCon(:,3) = 5 - sum(Y,2);\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/Single-objective optimization/CEC 2017/CEC2017_F13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5660339203186584}}
{"text": "function test_pull1602\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_specest_irasa ft_freqanalysis\n\n% simulate data\ntime = (1:2000)/1000;\nfor rpt = 1:20\n  if false\n    % We do not have that many concurrent licenses of the DSP Systems toolbox (https://nl.mathworks.com/products/dsp-system.html)\n    % which was used in the initial version of this script. Therefore this test script does not use the DSP toolbox by default.\n    dspobj = dsp.ColoredNoise('Color', 'pink', 'SamplesPerFrame', length(time));\n    signal = dspobj()';\n  else\n    % integrate over time to create pink noise with 1/f power spectrum\n    signal = cumsum(randn(1,length(time)));\n  end\n  \n  % add line noise\n  data.trial{1,rpt}     = signal + cos(2*pi*50*time) + cos(2*pi*100*time);\n  data.time{1,rpt}      = time;\n  data.label{1}         = 'chan';\n  data.trialinfo(rpt,1) = rpt;\nend\n\n% using unfiltered data\ncfg = [];\ncfg.method  = 'irasa';\ncfg.output  = 'original';\ncfg.pad     = 'nextpow2';\nfreq = ft_freqanalysis(cfg, data);\n\ncfg.output = 'fractal';\nfreqI = ft_freqanalysis(cfg, data);\n\n% what happens if we use bandpassfiltered data?\ncfg2            = [];\ncfg2.bpfilter   = 'yes';\ncfg2.bpfilttype = 'firws';\ncfg2.bpfreq     = [60 150];\ndatafilt1 = ft_preprocessing(cfg2, data);\n\ncfg2.bpfilter   = 'no';\ncfg2.hpfilter   = 'yes';\ncfg2.hpfreq     = 60;\ncfg2.hpfilttype = 'firws';\ndatafilt2 = ft_preprocessing(cfg2, data);\n\ncfg2.bpfilter   = 'no';\ncfg2.hpfilter   = 'no';\ncfg2.dftfilter  = 'yes'; % notch filter to filter out line noise\ncfg2.dftfreq    = [50 100];\ndatafilt3 = ft_preprocessing(cfg2, data);\n\ncfg.output = 'original';\nfreqfilt1  = ft_freqanalysis(cfg, datafilt1);\nfreqfilt2 = ft_freqanalysis(cfg, datafilt2);\nfreqfilt3 = ft_freqanalysis(cfg, datafilt3);\n\ncfg.output = 'fractal';\nfreqfiltI = ft_freqanalysis(cfg, datafilt1);\nfreqfiltI2 = ft_freqanalysis(cfg, datafilt2);\nfreqfiltI3 = ft_freqanalysis(cfg, datafilt3);\n\nallpow = [\n  freq.powspctrm\n  freqfilt1.powspctrm\n  freqfilt2.powspctrm\n  freqfilt3.powspctrm\n  freqI.powspctrm\n  freqfiltI.powspctrm\n  freqfiltI2.powspctrm\n  freqfiltI3.powspctrm\n  ];\n\nfigure;\nsemilogy(freq.freq, allpow);\nlegend({\n  'orig-unfilterd'\n  'orig-bpfiltered'\n  'orig-hpfiltered'\n  'orig-dftfiltered'\n  'frac-unfiltered'\n  'frac-bpfiltered'\n  'frac-hpfiltered'\n  'frac-dftfiltered'\n  });\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_pull1602.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.6757646010190477, "lm_q1q2_score": 0.5660339175883002}}
{"text": "function varargout = symmetrise(m,varargin)\n% symmetrcially equivalent directions and its multiple\n%\n% Syntax\n%   mSym = symmetrise(m)\n%\n%   % include antipodal symmetry\n%   mSym = symmetrise(m,'antipodal')\n%\n%   % exclude antipodal symmetry\n%   mSym = symmetrise(m,'noAntipodal')\n%\n%   % every symmetrically equivalent direction only once \n%   [mSym,l,sym] = symmetrise(m,'unique')\n%\n%   % every symmetrically equivalent axis only once \n%   [mSym,l,sym] = symmetrise(v,S,'unique','noAntipodal')\n%\n% Input\n%  v - @Miller\n%\n% Output\n%  mSym - sym * m  @Miller\n%  l    - multiplicity of the crystal directions\n%  sym  - @rotation\n%\n% Flags\n%  antipodal   - include <VectorsAxes.html antipodal symmetry>\n%  noAntipodal - do not include antipodal symmetry (without option unique)\n%  noAntipodal - do not remove antipodal vectors (with option unique)\n%  unique      - only return distinct axes or directions (noAntipodal)\n%\n\n[varargout{1:nargout}] = symmetrise@vector3d(m,m.CS,varargin{:});\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/symmetrise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5660339148490908}}
{"text": "% HIV system\n% System identification: (Delay)DMDc\n\n\nclear all, close all, clc\nfigpath = '../FIGURES/HIV/'; mkdir(figpath)\ndatapath = '../DATA/HIV/'; mkdir(datapath)\naddpath('../utils');\n\nSystemModel = 'HIV';\n\n% Model type selected based on DATA_ENSEMBLE and  Ndelay\n%% Generate Data\nInputSignalType = 'prbs';\nNvar = 5;\nNdelay = 1;  % Choose 1 for DMDc, and 10 for DelayDMDc in paper\nDATA_ENSEMBLE = 0; % Choose 0 to reproduce results in paper\n\n%%\nif DATA_ENSEMBLE == 1 % ONLY FOR Ndelay = 1 implemented\n    ModelName = 'DMDc';\n    getTrainingData_Ensemble\n    \n    %% Reshape\n    X = x(1:end-1,:,:);         % Array of snapshots\n    Xp = x(2:end,:,:);          % time-shifted Array\n    U = u(1:end-1,:,:);         % Array of inputs\n    M = size(X,1);\n    n = size(X,2);\n    \n    % Reorganize data from array to time-state matrix\n    X_tmp = zeros(Nvar,Nic*M);\n    Xp_tmp = zeros(Nvar,Nic*M);\n    U_tmp = zeros(1,Nic*M);\n    for iIC = 1:Nic\n        for i = 1:Nvar\n            X_tmp(i,(iIC-1)*M+1:iIC*M) = X(:,i,iIC);\n            Xp_tmp(i,(iIC-1)*M+1:iIC*M) = Xp(:,i,iIC);\n        end\n        U_tmp(1,(iIC-1)*M+1:iIC*M) = U(:,1,iIC);\n    end\n    X = X_tmp; Xp = Xp_tmp; U = U_tmp;\n    clear X_tmp Xp_tmp U_tmp\n    M = size(X,2);\n    \n    %% Construct data matrices // Mean-correction\n    xmean = zeros(1,5); %mean(X,2)';%xref; \n    X   = X - repmat(xmean',[1 M]);\n    Xp  = Xp - repmat(xmean',[1 M]);\n    \n    r1 = size(X,1); r2 = size(Xp,1);\n    [sysmodel_DMDc,Psi,Psi_p] = DelayDMDc_MV(zeros(5,1),U,r1,r2,dt,size(X,1),size(U,1),2,X,Xp);\n    \n    Nt = length(t)-1;\n    \n    %% Validation over training phase\n    xDMDc_Valid = zeros(size(X));\n    for iIC = 1:Nic\n        [xDMDc,~] = lsim(sysmodel_DMDc,squeeze(u(1:Nt,1,iIC)),t(1:Nt),x0_ensemble(iIC,:));\n        xDMDc = xDMDc + repmat(xmean,[Nt 1]);\n        xDMDc_Valid(1:5,(iIC-1)*Nt+1:iIC*Nt) = xDMDc';\n        disp(['PROGRESS: ',num2str(100*iIC/Nic),'%'])\n    end\n    %%\n    figure, hold on, box on\n    plot(X','-k','LineWidth',2)\n    plot(xDMDc_Valid','--','LineWidth',2)\nelse\n    \n    getTrainingData\n    %% DMDc: B = unknown  and with time delay coordinates\n    Ndelay = 1; % 1 for DMDc, 10 for DelayDMDc in paper  \n    if Ndelay == 1\n        ModelName = 'DMDc';\n    elseif Ndelay>1\n        ModelName = 'DelayDMDc';\n    end\n    \n    % Construct data matrices\n    Hu = getHankelMatrix_MV(u,Ndelay);\n    xmean = xref; %zeros(1,Nvar);%xref;%mean(x);%xref; %mean(x);\n    X   = x - repmat(xmean,[T 1]);\n    Hx  = getHankelMatrix_MV(X,Ndelay);\n    numOutputs = size(Hx,1); numInputs = size(Hu,1); numVar = 5;\n    r1 = size(Hx,1); r2 = size(Hx,1);\n    [sysmodel_DMDc,U,Up] = DelayDMDc_MV(Hx,Hu,size(Hx,1),size(Hx,1),dt,size(Hx,1),size(Hu,1),2);\n    \n    Nt = length(t)-Ndelay+1;\n    %% Validation over training phase\n    [xDMDc,~] = lsim(sysmodel_DMDc,Hu',tspan(1:Nt),Hx(:,1));\n    xDMDc = xDMDc(:,end-Nvar+1:end);\n    xDMDc = xDMDc + repmat(xmean,[Nt 1]);\n    \n    %% Show prediction over training stage\n    clear ph\n    figure,box on,\n    ccolors = get(gca,'colororder');\n    ccolors_valid = [ccolors(1,:)-[0 0.2 0.2];\n        ccolors(2,:)-[0.1 0.2 0.09];\n        ccolors(3,:)-[0.1 0.2 0.09];\n        ccolors(4,:)-[0.1 0.1 0.2];\n        ccolors(5,:)-[0.1 0.2 0.09]];\n    for i = 1:Nvar\n        ph(i) = semilogy(tspan,x(:,i),'-','Color',ccolors(i,:),'LineWidth',1); hold on\n    end\n    for i = 1:Nvar\n        ph(Nvar+i) = semilogy(tspan(Ndelay:Nt+Ndelay-1),xDMDc(:,i),'--','Color',ccolors_valid(i,:),'LineWidth',2);\n    end\n    xlabel('Time')\n    ylabel('xi')\n    legend(ph([1,6]),'True',ModelName)\n    set(gca,'LineWidth',1, 'FontSize',14)\n    set(gcf,'Position',[100 100 300 200])\n    set(gcf,'PaperPositionMode','auto')\n    print('-depsc2', '-loose', '-cmyk', [figpath,'EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'.eps']);\n    \nend\n%% Save Data & Model\nModel.name = ModelName;\nModel.sys = sysmodel_DMDc;\nModel.Ndelay = Ndelay;\nModel.dt = dt;\nModel.xmean = xmean;\nsave(fullfile(datapath,['EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'.mat']),'Model')", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/EX_HIV_THERAPY/EX_HIV_SI_DelayDMDc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5660339121275831}}
{"text": "function [Dx, Vx, mean_suv, max_suv, min_suv, Slope]=analyze_ivh(structNum, scanSet, plot_flag)\n% IVH analysis\nglobal planC\nindexS=planC{end};\noptS.IVHBinWidth=0.05;\n[scansV, volsV] = getIVH(structNum, scanSet, planC);\n[scanBinsV, volsHistV] = doseHist(scansV, volsV, optS.IVHBinWidth);\ncumVolsV = cumsum(volsHistV);\ncumVols2V  = cumVolsV(end) - cumVolsV;  %cumVolsV is the cumulative volume lt that corresponding scan\n% calculate stats\nmean_suv= calc_meanDose(scanBinsV, volsHistV);\nmax_suv=  calc_maxDose(scanBinsV, volsHistV);\nmin_suv=  calc_minDose(scanBinsV, volsHistV);\nD50 = calc_Dx(scanBinsV, volsHistV,50)\n\nSlope=calc_Slope(scanBinsV, volsHistV, D50, 0);\n\nrange = max_suv-min_suv;\nparam = [10:10:90];\nfor i=1:length(param)\n    per=param(i)*range/100+min_suv; % ith percentile\n    Dx(i)= calc_Dx(scanBinsV, volsHistV,param(i));\n    Vx(i)= calc_Vx(scanBinsV, volsHistV,per,1);\nend\n\n%including that scan bin.\n% if plot_flag\n% %     if ~isempty(planC{indexS.scan}(scanSet).scanOffset)\n% %         h = plot([0, scanBinsV - planC{indexS.scan}(scanSet).scanOffset], [1, cumVols2V/cumVolsV(end)]);\n% %     else\n% %        h = plot([0, scanBinsV], [1, cumVols2V/cumVolsV(end)]);\n% %     end\n% end\n\nreturn\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/heterogenity_metrics/analyze_ivh1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5660339039011046}}
{"text": "function [in] = um2in(um)\n% Convert length from micrometers (or microns) to inches.\n% Chad A. Greene 2012\nin = um/25400;", "meta": {"author": "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/um2in.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5660176674033482}}
{"text": "function [xL,xR] = click_stereo(NUMBER_OF_POINTS,IL,IR,R,T,fc_right,cc_right,kc_right,alpha_c_right,fc_left,cc_left,kc_left,alpha_c_left);\n\n\nfigure(1);\nimage(IL);\n\nfigure(2);\nimage(IR);\n\n[ny,nx] = size(IL);\n\nxL = [];\nxR = [];\n\nfor kk = 1:NUMBER_OF_POINTS,\n    \n    figure(1);\n    hold on;\n    x = ginput(1);\n    plot(x(1),x(2),'g.');\n    hold off;\n    x = x'-1;\n    \n    xL = [xL x];\n    \n    [epipole] = compute_epipole(x,R,T,fc_right,cc_right,kc_right,alpha_c_right,fc_left,cc_left,kc_left,alpha_c_left);\n\n    figure(2);\n    hold on;\n    h = plot(epipole(1,:)+1,epipole(2,:)+1,'r.','markersize',1);\n    hold off;\n  \n    x2 = ginput(1);\n    x2 = x2' - 1;\n    \n    NN = size(epipole,2);\n    d = sum((epipole - repmat(x2,1,NN)).^2);\n    [junk,indmin] = min(d);\n    \n    x2 = epipole(:,indmin);\n    \n    xR = [xR x2];\n    \n    delete(h);\n    \n    figure(2);\n    hold on;\n    plot(x2(1)+1,x2(2)+1,'g.');\n    drawnow;\n    hold off;\n    \nend;\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/click_stereo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5660176636962541}}
{"text": "function bnet = fgraph_to_bnet(fg)\n% FGRAPH_TO_BNET Convert a factor graph to a Bayes net\n% bnet = fgraph_to_bnet(fg)\n%\n% We assume all factors are tabular_CPD.\n% We create 1 dummy observed node for every factor.\n\nN = fg.nvars + fg.nfactors;\nvnodes = 1:fg.nvars;\nfnodes = fg.nvars+1:N;\ndag = zeros(N);\nfor x=1:fg.nvars\n  dag(x, fnodes(fg.dep{x})) = 1;\nend\nns = [fg.node_sizes ones(1, fg.nfactors)];\ndiscrete = [fg.dnodes fnodes];\nbnet = mk_bnet(dag, ns, 'discrete', discrete);\nfor x=1:fg.nvars\n  bnet.CPD{x} = tabular_CPD(bnet, x, 'CPT', 'unif');\nend\nev = cell(1, fg.nvars); % no evidence\nfor i=1:fg.nfactors\n  f = fnodes(i);\n  e = fg.equiv_class(i);\n  pot = convert_to_pot(fg.factors{e}, 'd', fg.dom{i}, ev);\n  m = pot_to_marginal(pot);\n  bnet.CPD{f} = tabular_CPD(bnet, f, 'CPT', m.T);\nend\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/general/fgraph_to_bnet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5659860840285089}}
{"text": "classdef CEC2010_F13 < PROBLEM\n% <single> <real> <constrained>\n% CEC'2010 constrained optimization benchmark problem\n\n%------------------------------- Reference --------------------------------\n% R. Mallipeddi and P. N. Suganthan, Problem definitions and evaluation\n% criteria for the CEC 2010 competition on constrained real-parameter\n% optimization, Nanyang Technological University, Singapore, 2010.\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        O;  % Optimal decision vector\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2010.mat'),'Data');\n            obj.O = Data{13};\n            obj.M = 1;\n            if isempty(obj.D); obj.D = 10; end\n            obj.D = min(obj.D,length(obj.O));\n            obj.lower    = zeros(1,obj.D) - 500;\n            obj.upper    = zeros(1,obj.D) + 500;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopObj = mean(-Z.*sin(sqrt(abs(Z))),2);\n        end\n        %% Calculate constraint violations\n        function PopCon = CalCon(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopCon(:,1) = -50 + mean(Z.^2,2)/100;\n            PopCon(:,2) = 50*mean(sin(pi*Z/50),2);\n            PopCon(:,3) = 75 - 50*(sum((Z.^2/4000),2)-prod((cos(Z./repmat(sqrt(1:size(Z,2)),size(Z,1),1))),2)+1);\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/Single-objective optimization/CEC 2010/CEC2010_F13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5659860760243969}}
{"text": "function [model] = USRtrain(fea, options)\n% USRtrain: Training Unsupervised Spectral Regression Model\n%\n%       [model] = USRtrain(fea, options)\n% \n%             Input:\n%\n%               fea     - data matrix. Each row is a data point. \n%           options     - Struct value in Matlab. The fields in options\n%                         that can be set:\n%\n%                      W       -  Affinity matrix. You can either call\n%                                 \"constructW\" to construct the W, or\n%                                 construct it by yourself.\n%                                 If W is not provided, USRtrain will\n%                                 build a k-NN graph with Heat kernel\n%                                 weight, where k is a prameter.\n%                                 \n%                      k       -  The parameter for k-NN graph (Default is 5)\n%                                 If W is provided, this k will be ignored.\n%               \n%                  ReducedDim  -  The number of reduced dimensions. \n%                                 Default ReducedDim = 30.\n%\n%                  ReguType    -  'Ridge': L2-norm regularizer (default)\n%                                 'Lasso': L1-norm regularizer\n%                  ReguAlpha   -  regularization paramter for L2-norm regularizer \n%                                 Default 0.1\n%                  ReguGamma   -  regularization paramter for L1-norm regularizer \n%                                 Default 0.05\n%                  LASSOway    -  'LARs': use LARs to solve the LASSO\n%                                 problem. You need to specify the\n%                                 cardinality requirement in LassoCardi.\n%                                 'SLEP': use SLEP to solve the LASSO\n%                                 problem. Please see http://www.public.asu.edu/~jye02/Software/SLEP/ \n%                                  for details on SLEP. (The Default)\n%               \n%                 bCenter = 0 | 1  whether to center the data. (In some\n%                                  cases, e.g., text categorization, The\n%                                  data is very spase, centering the data\n%                                  will destroy the sparsity and consume\n%                                  too much memory. In this case, bCenter\n%                                  should be set to 0)  \n%                                   Default: 1\n%\n%\n%             Output:\n%               model   -  used for USRtest.m\n% \n%\n%    Examples:\n%\n%       \n%\n% See also SR, SR_caller\n%\n%Reference:\n%\n%   [1] Deng Cai, Xiaofei He, Wei Vivian Zhang, Jiawei Han, \"Regularized\n%   Locality Preserving Indexing via Spectral Regression\", Proc. 2007 ACM\n%   Int. Conf. on Information and Knowledge Management (CIKM'07), Lisboa,\n%   Portugal, Nov. 2007.\n%\n%   [2] 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 --Jan/2012\n%   version 2.0 --December/2011\n%   version 1.0 --May/2006 \n%\n%   Written by Deng Cai (dengcai AT gmail.com)\n%\n\nif ~exist('options','var')\n    options = [];\nend\n\nbCenter = 1;\nif isfield(options,'bCenter')\n    bCenter = options.bCenter;\nend\n\nk = 5;\nif isfield(options,'k')\n    k = options.k;\nend\n\nReducedDim = 30;\nif isfield(options,'ReducedDim')\n    ReducedDim = options.ReducedDim;\nend\n\n\nif ~isfield(options,'ReguType')\n    options.ReguType = 'Ridge';\nend\n\nLARs = false;\nswitch lower(options.ReguType)\n    case {lower('Ridge')}\n        if ~isfield(options,'ReguAlpha')\n            options.ReguAlpha = 0.1;\n        end\n    case {lower('Lasso')}\n        if isfield(options,'ReguAlpha') && options.ReguAlpha > 0\n            options.RidgeAlpha = options.ReguAlpha;\n            options.ReguType = 'RidgeLasso';\n        end\n        if isfield(options,'ReguGamma') \n            options.ReguAlpha = options.ReguGamma;\n        else\n            options.ReguAlpha = 0.05;\n        end\n        if ~isfield(options,'LASSOway')\n            options.LASSOway = 'SLEP';\n        end\n        \n        if strcmpi(options.LASSOway,'LARs')\n            LARs = true;\n            if ~isfield(options,'LassoCardi')\n                options.LassoCardi = 10:10:50;\n            end\n        end\n    otherwise\n        error('ReguType does not exist!');\nend\n\n\nnSmp=size(fea,1);\n% Graph construction\nif isfield(options,'W')\n    W = options.W;\nelse\n    Woptions.k = k;\n    if nSmp > 3000\n        tmpD = EuDist2(fea(randsample(nSmp,3000),:));\n    else\n        tmpD = EuDist2(fea);\n    end\n    Woptions.t = mean(mean(tmpD));\n    W = constructW(fea,Woptions);\nend\n\n% Respnse generation\nY = Eigenmap(W,ReducedDim);\n\n% Projection learning\nif bCenter\n    sampleMean = mean(fea);\n    fea = (fea - repmat(sampleMean,nSmp,1));\nend\n\n[model.projection, LassoCardi] = SR(options, Y, fea);\n\nmodel.LARs = LARs;\nmodel.LassoCardi = LassoCardi;\n\n\nmodel.TYPE = 'USR';\nmodel.options = options;\n\n\n\n\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/SubspaceLearning/USRtrain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5659860733563595}}
{"text": "function y = aprod( mode, m, n, x, iw, rw )\n% This is the simplest example for testing  LSQR.\n% :math:`A = rw`.\n% If `mode = 1`, `aprod` computes :math:`y = A x`.\n% Ff `mode = 2`, `aprod` computes :math:`y = A^T x`.\n% for some matrix  `A`.\n\nif mode == 1,\n   y = rw*x;\nelse\n   y = rw'*x;\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/subspaces/lsqr/aprod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5659860680202845}}
{"text": "function [ offspring ] = DE_transfer(Problem, Population1, Population2, popsize)\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 Kangjia Qiao\n\n    Fm  = [0.6,0.8,1.0];\n    CRm = [0.1,0.2,1.0];\n\n    index = randi([1,length(Fm)],popsize,1);\n    F     = Fm(index);\n    F     = F';\n    index = randi([1,length(CRm)],popsize,1);\n    CR    = CRm(index);\n    CR    = CR';\n\n    index =randi(Problem.N, popsize,1);\n\n    permutation = randperm(Problem.N);\n\n    array = permutation(1:popsize);\n\n    pop1 = Population1(array).decs;\n    pop2 = Population2.decs;\n\n    vi = pop2(index,:);\n\n\n    mask  = rand(popsize, Problem.D) > CR(:, ones(1, Problem.D)); % mask is used to indicate which elements of ui comes from the parent\n    rows  = (1 : popsize)'; cols = floor(rand(popsize, 1) * Problem.D)+1; % choose one position where the element of ui doesn't come from the parent\n    jrand = sub2ind([popsize Problem.D], rows, cols); mask(jrand) = false;\n    u     = vi; u(mask) = pop1(mask);\n\n    offspring = Problem.Evaluation(u);\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/URCMO/DE_transfer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.565986056966264}}
{"text": "function res = vl_ffdnet_matlab(net, input)\n\n%% If you did not install the matconvnet package, you can use this for testing.\n\nglobal sigmas;\nn = numel(net.layers);\nres = struct('x', cell(1,n+1));\nres(1).x = input;\n\nfor i = 1 : n\n    l = net.layers{i};\n    switch l.type\n        \n        case 'conv'\n            disp(['Processing ... ',int2str(i),'/',int2str(n)]);\n            for noutmaps = 1 : size(l.weights{1},4)\n                z = zeros(size(res(i).x,1),size(res(i).x,2),'single');\n                for ninmaps = 1 : size(res(i).x,3)\n                    z = z + convn(res(i).x(:,:,ninmaps), rot90(l.weights{1}(:,:,ninmaps,noutmaps),2),'same'); % 180 degree rotation for kernel\n                end\n                res(i+1).x(:,:,noutmaps) = z + l.weights{2}(noutmaps);\n            end\n            \n        case 'relu'\n            res(i+1).x = max(res(i).x,0);\n            \n        case 'concat'\n            if size(sigmas,1)~=size(res(i).x,1)\n                sigmaMap   = bsxfun(@times,ones(size(res(i).x,1),size(res(i).x,2),1,size(res(i).x,4),'single'),permute(sigmas,[3 4 1 2]));\n                res(i+1).x = cat(3,res(i).x,sigmaMap);\n            else\n                res(i+1).x = cat(3,res(i).x,sigmaMap);\n            end\n            \n        case 'SubP'\n            res(i+1).x = vl_nnSubP(res(i).x, [],'scale',l.scale);\n            \n    end\n    res(i).x = [];\nend\n\nend\n", "meta": {"author": "cszn", "repo": "DnCNN", "sha": "e93b27812d3ff523a3a79d19e5e50d233d7a8d0a", "save_path": "github-repos/MATLAB/cszn-DnCNN", "path": "github-repos/MATLAB/cszn-DnCNN/DnCNN-e93b27812d3ff523a3a79d19e5e50d233d7a8d0a/utilities/vl_ffdnet_matlab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5659860514392535}}
{"text": "function X = mat(x,n)\n% Y = MAT(x,n)   or   Y = MAT(x)     (the 2nd argument is optional)\n%   Given a vector of length n^2, this produces the n x n matrix\n%   Y such that x = vec(Y).  In other words, x contains the columns of the\n%   matrix Y, stacked below each other.\n%\n% See also vec.\n\n% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n%   Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n%   CRL, McMaster University, Canada.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\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 Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n%\n\nif nargin < 2\n    n = floor(sqrt(length(x)));\n    if (n*n) ~= length(x)\n        error('Argument X has to be a square matrix')\n    end\nend\nX = reshape(x,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/sedumi/mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.805632207648114, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5659808410784555}}
{"text": "function [train,B, A] = generate_data(n, d, num_atoms, active_size)\nB = cell(num_atoms,1);\nfor i=1:num_atoms\n    x=randn(d)-rand(d); b=x'*x/d+eye(d)*1e-2; B{i}=b/trace(b);\nend\ntrain = cell(n,1); A = zeros(num_atoms, n); \nfor t=1:n\n    p=rand(active_size,1);\n    idx = randperm(num_atoms, active_size);\n    A(idx, t) = p;\n    \n    X = zeros(d);\n    for s=1:active_size\n        X = X + p(s)*B{idx(s)};\n    end\n    train{t} = X;\nend\nend\n", "meta": {"author": "hiroyuki-kasai", "repo": "ClassifierToolbox", "sha": "63aa78304a8ac10c432840c45d63170ea2bbabb0", "save_path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox", "path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox/ClassifierToolbox-63aa78304a8ac10c432840c45d63170ea2bbabb0/lib/Riemannian_DL_SC_SPD/generate_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5659808360608682}}
{"text": "function c = tapas_ehgf_binary_pu_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the Hierarchical Gaussian Filter (HGF)\n% for binary inputs in the *presence* of perceptual uncertainty.\n%\n% The HGF is the model introduced in \n%\n% Mathys C, Daunizeau J, Friston, KJ, and Stephan KE. (2011). A Bayesian foundation\n% for individual learning under uncertainty. Frontiers in Human Neuroscience, 5:39.\n%\n% The binary HGF model has since been augmented with a positive factor kappa1 which\n% scales the second level with respect to the first, i.e., the relation between the\n% first and second level is\n%\n% p(x1=1|x2) = s(kappa1*x2), where s(.) is the logistic sigmoid.\n%\n% By default, kappa1 is fixed to 1, leading exactly to the model introduced in\n% Mathys et al. (2011).\n%\n% This file refers to BINARY inputs (Eqs 1-3 in Mathys et al., (2011));\n% for continuous inputs, refer to tapas_hgf_config.\n%\n% This file refers to UNCERTAIN inputs (Eqs 45-47 in Mathys et al., (2011));\n% for inputs without uncertainty, refer to tapas_hgf_binary_config.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% The HGF configuration consists of the priors of parameters and initial values. All priors are\n% Gaussian in the space where the quantity they refer to is estimated. They are specified by their\n% sufficient statistics: mean and variance (NOT standard deviation).\n% \n% Quantities are estimated in their native space if they are unbounded (e.g., the omegas). They are\n% estimated in log-space if they have a natural lower bound at zero (e.g., the sigmas).\n% \n% Parameters can be fixed (i.e., set to a fixed value) by setting the variance of their prior to\n% zero. Aside from being useful for model comparison, the need for this arises whenever the scale\n% and origin at the j-th level are arbitrary. This is the case if the observation model does not\n% contain the representations mu_j and sigma_j. A choice of scale and origin is then implied by\n% fixing the initial value mu_j_0 of mu_j and either kappa_j-1 or omega_j-1.\n%\n% Fitted trajectories can be plotted by using the command\n%\n% >> tapas_hgf_binary_plotTraj(est)\n% \n% where est is the stucture returned by tapas_fitModel. This structure contains the estimated\n% perceptual parameters in est.p_prc and the estimated trajectories of the agent's\n% representations (cf. Mathys et al., 2011). Their meanings are:\n%              \n%         est.p_prc.mu_0       row vector of initial values of mu (in ascending order of levels)\n%         est.p_prc.sa_0       row vector of initial values of sigma (in ascending order of levels)\n%         est.p_prc.rho        row vector of rhos (representing drift; in ascending order of levels)\n%         est.p_prc.ka         row vector of kappas (in ascending order of levels)\n%         est.p_prc.om         row vector of omegas (in ascending order of levels)\n%         est.p_prc.al         scalar alpha (perceptual uncertainty)\n%         est.p_prc.eta0       scalar eta0 (mean of first input category)\n%         est.p_prc.eta1       scalar eta1 (mean of second input category)\n%\n% Note that the first entry in all of the row vectors will be NaN because, at the first level,\n% these parameters are either determined by the second level (mu_0 and sa_0) or undefined (rho,\n% kappa, and omega).\n%\n%         est.traj.mu          mu (rows: trials, columns: levels)\n%         est.traj.sa          sigma (rows: trials, columns: levels)\n%         est.traj.muhat       prediction of mu (rows: trials, columns: levels)\n%         est.traj.sahat       precisions of predictions (rows: trials, columns: levels)\n%         est.traj.v           inferred variance of random walk (rows: trials, columns: levels)\n%         est.traj.w           weighting factors (rows: trials, columns: levels)\n%         est.traj.da          volatility prediction errors  (rows: trials, columns: levels)\n%         est.traj.ud          updates with respect to prediction  (rows: trials, columns: levels)\n%         est.traj.psi         precision weights on prediction errors  (rows: trials, columns: levels)\n%         est.traj.epsi        precision-weighted prediction errors  (rows: trials, columns: levels)\n%         est.traj.wt          full weights on prediction errors (at the first level,\n%                                  this is the learning rate) (rows: trials, columns: levels)\n%\n% Note that in the absence of sensory uncertainty (which is the assumption here), the first\n% column of mu, corresponding to the first level, will be equal to the inputs. Likewise, the\n% first column of sa will be 0 always.\n%\n% Tips:\n% - When analyzing a new dataset, take your inputs u and use\n%\n%   >> est = tapas_fitModel([], u, 'tapas_hgf_binary_pu_config', 'tapas_bayes_optimal_binary_config');\n%\n%   to determine the Bayes optimal perceptual parameters (given your current priors as defined in\n%   this file here, so choose them wide and loose to let the inputs influence the result). You can\n%   then use the optimal parameters as your new prior means for the perceptual parameters.\n%\n% - When analyzing a new dataset, take your inputs u and use\n%\n% - If you get an error saying that the prior means are in a region where model assumptions are\n%   violated, lower the prior means of the omegas, starting with the highest level and proceeding\n%   downwards.\n%\n% - Alternatives are lowering the prior means of the kappas, if they are not fixed, or adjusting\n%   the values of the kappas or omegas, if any of them are fixed.\n%\n% - If the log-model evidence cannot be calculated because the Hessian poses problems, look at\n%   est.optim.H and fix the parameters that lead to NaNs.\n%\n% - Your guide to all these adjustments is the log-model evidence (LME). Whenever the LME increases\n%   by at least 3 across datasets, the adjustment was a good idea and can be justified by just this:\n%   the LME increased, so you had a better model.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2017 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 <http://www.gnu.org/licenses/>.\n\n\n% Config structure\nc = struct;\n\n% Model name\nc.model = 'ehgf_binary_pu';\n\n% Number of levels (minimum: 3)\nc.n_levels = 3;\n\n% Input intervals\n% If input intervals are irregular, the last column of the input\n% matrix u has to contain the interval between inputs k-1 and k\n% in the k-th row, and this flag has to be set to true\nc.irregular_intervals = false;\n\n% Sufficient statistics of Gaussian parameter priors\n\n% Initial mus and sigmas\n% Format: row vectors of length n_levels\n% For all but the first two levels, this is usually best\n% kept fixed to 1 (determines origin on x_i-scale). The \n% first level is NaN because it is determined by the second,\n% and the second implies neutrality between outcomes when it\n% is centered at 0.\nc.mu_0mu = [NaN, 0, 1];\nc.mu_0sa = [NaN, 0, 0];\n\nc.logsa_0mu = [NaN,   log(0.1), log(1)];\nc.logsa_0sa = [NaN,          0,      0];\n\n% Rhos\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\n% Fix this to zero to turn off drift.\nc.rhomu = [NaN, 0, 0];\nc.rhosa = [NaN, 0, 0];\n\n% Kappas\n% Format: row vector of length n_levels-1.\n% Fixing log(kappa1) to log(1) leads to the original HGF model.\n% Higher log(kappas) should be fixed (preferably to log(1)) if the\n% observation model does not use mu_i+1 (kappa then determines the\n% scaling of x_i+1).\nc.logkamu = [log(1), log(1)];\nc.logkasa = [     0,      0];\n\n% Omegas\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\nc.ommu = [NaN,  -3,  -6];\nc.omsa = [NaN, 4^2, 4^2];\n\n% Alpha\n% Format: scalar.\nc.logalmu = log(0.5);\nc.logalsa = 1;\n\n% Eta0\n% Format: scalar.\nc.eta0mu = 0;\nc.eta0sa = 0;\n\n% Eta1\n% Format: scalar.\nc.eta1mu = 1;\nc.eta1sa = 0;\n\n% Gather prior settings in vectors\nc.priormus = [\n    c.mu_0mu,...\n    c.logsa_0mu,...\n    c.rhomu,...\n    c.logkamu,...\n    c.ommu,...\n    c.logalmu,...\n    c.eta0mu,...\n    c.eta1mu,...\n         ];\n\nc.priorsas = [\n    c.mu_0sa,...\n    c.logsa_0sa,...\n    c.rhosa,...\n    c.logkasa,...\n    c.omsa,...\n    c.logalsa,...\n    c.eta0sa,...\n    c.eta1sa,...\n         ];\n\n% Check whether we have the right number of priors\nexpectedLength = 3*c.n_levels+2*(c.n_levels-1)+4;\nif length([c.priormus, c.priorsas]) ~= 2*expectedLength;\n    error('tapas:hgf:PriorDefNotMatchingLevels', 'Prior definition does not match number of levels.')\nend\n\n% Model function handle\nc.prc_fun = @tapas_ehgf_binary_pu;\n\n% Handle to function that transforms perceptual parameters to their native space\n% from the space they are estimated in\nc.transp_prc_fun = @tapas_ehgf_binary_pu_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_ehgf_binary_pu_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5659808295038538}}
{"text": "function labels = grLabel(nodes, edges)\n%GRLABEL Associate a label to each connected component of the graph\n%\n%   LABELS = grLabel(NODES, EDGES)\n%   Returns an array with as many rows as the array NODES, containing index\n%   number of each connected component of the graph. If the graph is\n%   totally connected, returns an array of 1.\n%\n%   Example\n%       nodes = rand(6, 2);\n%       edges = [1 2;1 3;4 6];\n%       labels = grLabel(nodes, edges);\n%   labels =\n%       1\n%       1\n%       1\n%       2\n%       3\n%       2   \n%\n%   See also\n%   getNeighborNodes\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2007-08-14,    using Matlab 7.4.0.287 (R2007a)\n% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\n\n% init\nNn = size(nodes, 1);\nlabels = (1:Nn)';\n\n% iteration until stability\nmodif = true;\nwhile modif\n    modif = false;\n    \n    % compute the minimum label in the neighborhood of each node\n    for i = 1:Nn\n        neigh = grAdjacentNodes(edges, i);\n        neighLabels = labels([i;neigh]);\n        \n        % check for a modification\n        if length(unique(neighLabels)) > 1\n            modif = true;\n        end\n        \n        % put new labels\n        labels(ismember(labels, neighLabels)) = min(neighLabels);\n    end\nend\n\n% renumbering to have fewer labels\nlabels2 = unique(labels);\nfor i = 1:length(labels2)\n    labels(labels == labels2(i)) = i;\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/grLabel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.5659808263251725}}
{"text": "% This is an example of using this software to train a binary \n% decision tree classifier, and use this classifier to classify \n% testing data. \n\n% Copyright (C) 2012 Quan Wang <wangq10@rpi.edu>, \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\nclear;clc;close all;\n\n%% settings\nDepth=5; % maximal depth of decision tree\nSplits=100; % number of candidate thresholds at each node\nMinNode=10; % minimal size of a non-leaf node\n\n%% training\nload TrainingData.mat;\n\ntic;\nT=create01Tree(X,Y,Depth,Splits,MinNode);\nt1=toc;\n\nclear X Y;\n\n%% testing\nload TestingData.mat;\n\ntic;\ny=[];\nfor i=1:size(X,1)\n    x=X(i,:);\n    y(i,1)=decide01Tree(x,T);\nend\nt2=toc;\n\n%% evaluation\nerrorRate=sum(abs(y-Y))/max(size(Y));\nfprintf('Error rate = %.4f\\n',errorRate);\nfprintf('Training time = %.4f seconds\\n',t1);\nfprintf('Testing time = %.4f seconds\\n',t2);", "meta": {"author": "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/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7025300449389327, "lm_q1q2_score": 0.5659808244862666}}
{"text": "function [ cx, cy ] = cswap ( n, cx, incx, cy, incy )\n\n%*****************************************************************************80\n%\n%% CSWAP interchanges two complex vectors.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 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 swap.\n%\n%    Input, integer INCX, the increment between successive entries of CX.\n%\n%    Input, complex CY(*), one of the vectors to swap.\n%\n%    Input, integer INCY, the increment between successive elements of CY.\n%\n%    Output, complex CX(*), the input vector CX, with some elements swapped.\n%\n%    Input, integer INCX, the increment between successive entries of CX.\n%\n%    Output, complex CY(*), the input vector CY, with some elements swapped.\n%\n  temp                    = cx(1:incx:1+(n-1)*incx);\n  cx(1:incx:1+(n-1)*incx) = cy(1:incy:1+(n-1)*incy);\n  cy(1:incy:1+(n-1)*incy) = 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/blas1_c/cswap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.565980823046665}}
{"text": "classdef trigspec < coeffsDiscretization\n%TRIGSPEC    Fourier spectral method in coefficient space.\n%   TRIGSPEC is an implementation of OPDISCRETIZATION that implements a\n%   Fourier spectral method in coefficient space.\n%\n% See also TRIGCOLLOC.\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    %% CLASS PROPERTIES:\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    properties ( Access = public )\n        coeffs        % Coefficients of the operator.\n        outputSpace   % The range of the operator.\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% CLASS CONSTRUCTOR:\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    methods ( Access = public, Static = false )\n        \n        function disc = trigspec(varargin)\n            disc = disc@coeffsDiscretization(varargin{:});\n            % No dimension adjustment are required for TRIGSPEC.\n            disc.dimAdjust = 0;\n            disc.projOrder = 0;\n        end\n        \n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% STATIC METHODS:\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    methods ( Access = public, Static = true )\n        \n        function tech = returnTech()\n            %RETURNTECH    Return the appropriate tech to use for TRIGSPEC.\n            tech = @trigtech;\n        end\n        \n        % Differentiation matrices for TRIGSPEC.\n        D = diffmat(N, m, flag)\n        \n        % Multiplication matrices for TRIGSPEC.\n        D = multmat(N, f)\n        \n    end\n    \nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@trigspec/trigspec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812552, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.565980822946839}}
{"text": "% KM_DEMO_AKCCA Demonstration of Alternating Kernel Canonical Correlation\n% Analysis algorithm for blind equalization of single-input multiple-output\n% Wiener systems.\n%\n% Author: Steven Van Vaerenbergh (steven *at* gtas.dicom.unican.es), 2011.\n%\n% The algorithm in this file is based on the following publication:\n% S. Van Vaerenbergh, J. Via and I. Santamaria, \"Blind Identification of \n% SIMO Wiener Systems based on Kernel Canonical Correlation Analysis\", \n% accepted for publication in IEEE Transactions on Signal Processing, 2013.\n%\n% This file is part of the Kernel Methods Toolbox for MATLAB.\n% https://github.com/steven2358/kmbox\n\nclose all\nclear\nrs = 1; % seed for random generator\nrng('default')\nrng(rs)\n\nfprintf('\\nAlternating kernel CCA for blind equalization of ')\nfprintf('SIMO Wiener systems.\\n');\n\n%% SETUP PARAMETERS\npars_setup.model_num = 30244; % source model, see generate_data.m\npars_setup.model_L = 5; % channel length\npars_setup.data_type = 'gaussian'; % bits, gaussian\npars_setup.data_N = 256; % number of data points\npars_setup.data_SNR = 20; % signal-to-noise ratio\npars_setup.zf_k = 15; % number of observations to estimate zero-forcing equalizers\npars_setup.p = 4; % number of branches in SIMO Wiener system\npars_setup.verbose = false;\n\n%% ALT-KCCA PARAMETERS\npars = pars_setup; % copy some setup parameters\npars.it_max = 100; % maximum number of iterations\npars.it_stop = 1E-10; % stop iteration if change in cost is smaller than this\npars.kernel.type = 'gauss'; % kernel type\npars.kernel.par = @(x) km_silverman(x); % kernel parameter, either a scalar or a function to determine it\npars.m = 1E-8; % number of KPCA autovectors / precision of ICD, or fraction of discarded signal energy\npars.reg = 1E-5; % regularization\npars.decomp = 'ICD'; % ICD or KPCA\npars.identical_nonlin = 0;\t% boolean indicating common nonlinearity for each channel\n\n%% PROGRAM\ntic\n\nN = pars_setup.data_N; p = pars_setup.p; SNR = pars_setup.data_SNR;\n% GENERATE DATA\nswitch pars_setup.data_type,\n    case 'gaussian'\n        s = randn(N,1); s = s-mean(s); % source signal\n    case 'bits'\n        s = 2*round(rand(N,1))-1; % source signal\nend\ny = cell(p,1); x = cell(p,1); sigpow = 0;\nf = @(x) tanh(0.8*x)+0.1*x; % nonlinearity\nB1 = [0.6172   -0.8601    2.1383    0.4269   -1.3153\n    0.6247    0.1532    0.9686   -0.5820   -0.4584\n    0.3373   -0.1888   -1.4263    0.8060   -0.1740\n    -0.0349   -0.6264   -0.2486    1.1975    1.2195\n    -3.2957    0.9985   -0.3768    0.6139   -1.2011]/1.5; % linear filter\nB = cell(p,1);\nfor i=1:p, % simulate Wiener system\n    B{i} = B1(:,i);\n    y{i} = filter(B{i},1,s);\n    x{i} = f(y{i});\n    sigpow = sigpow + x{i}'*x{i}/p/N;\nend\nnoisepow = 10^(-SNR/10)*sigpow;\nfor i=1:p, x{i} = x{i} + sqrt(noisepow)*randn(N,1); end % add noise\ndata.s = s; data.B = B; data.y = y; data.x = x;\n\n%% AKCCA algorithm\n[vars,eval] = km_akcca(pars,data);\n\ntoc\n%% OUTPUT\n\n% calculate MSE or BER\nswitch pars_setup.data_type\n    case 'gaussian'\n        % scale signals and compare\n        s1 = s(vars.ind_s); s2 = eval.s_est;\n        s1_norm = s1/norm(s1); sc = s1_norm'*s2/(s2'*s2);\n        err_vec = s1_norm - sc*s2;\n        \n        MSE = err_vec'*err_vec;\n        sc = sc*norm(s1);\n        \n        fprintf('MSE = %.2f dB\\n',10*log10(MSE));\n    case 'bits'\n        sc = 1;\n        fprintf('BER = %.4f\\n',eval.finalresult);\nend\n\nN = pars_setup.data_N;\n\n% draw estimates of nonlinearities\nfigure\nfor i=1:p\n    subplot(1,p,i); hold all\n    xi = vars.x{i};\n    y_est = vars.y_est{i};\n    sci = y{i}'*y_est/(y_est'*y_est);\n    \n    plot(xi,data.y{i},'.b')\n    plot(xi,sci*y_est,'.r');\n    legend(sprintf('x%d vs true, unknown y%d',i),sprintf('x%d vs estimated y%d',i))\n    xlabel('x')\nend\n\n% draw estimates of linear filters\nfigure\nfor i=1:p\n    subplot(1,p,i); hold all\n    stem(B{i},'ob','LineWidth',2,'MarkerSize',8);\n    stem(vars.h{i}*norm(B{i})/norm(vars.h{i}),'xr','LineWidth',2,...\n        'LineStyle','none','MarkerSize',10);\n\n    xlabel('l');ylabel(sprintf('h_%d',i));\n    legend({'real channel','estimated channel'})\nend\n\n% draw equalization result\nfigure; hold all\nplot(s(vars.ind_s))\nplot(sc*eval.s_est);\nlegend('source signal','recovered signal')\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_akcca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5659808214074111}}
{"text": "function pred_label=SpatialJSRC(feat, train_data, train_label, sp_label, block_size, param)\n% Classification of superpixels with joint sparse representation\n% Input:\n%    feat: extracted img features, nr*nc*nd where nd is the number of feature channel\n%    dict: the dictionary\n%    dict_label: the label of dictionary atoms\n%    sp_label: the label of superpixels, nr*nc\n%    block_size: the size for block-wise processing\n%    param: parameter for sparse representation\n%            param.L (optional, maximum number of elements in each decomposition, \n%               min(m,p) by default)\n%            param.eps (optional, threshold on the squared l2-norm of the residual,\n%               0 by default\n%            param.lambda (optional, penalty parameter, 0 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%   2016-10-20, jlfeng\n\n[nr,nc,~]=size(feat);\nsp_label=reshape(sp_label,[nr*nc 1]);\n[group_label,sortidx]=sort(sp_label);\nfeat_sort=VectorIndexing3D(feat,sortidx);\nidx_group_start=zeros(length(unique(group_label)),1);\nidx_group_start(2:end)=int32(find(diff(group_label)~=0));\n\nnum_sp=length(idx_group_start);\nnum_block=ceil(num_sp/block_size);\ndisp('Block-wise classification strategy is used. ');\ndisp(['Number of Blocks: ', num2str(num_block)]);\npause(0.05)\npred_label_sort=zeros(nr*nc,1);\nfor nn=1:num_block\n    disp(['Processing block ',num2str(nn)]);tic\n    idxstart=(nn-1)*block_size;\n    idxend=min(nn*block_size-1,num_sp-1);\n    idx_block=(group_label>=idxstart)&(group_label<=idxend);\n    test_data=feat_sort(:,idx_block);\n    idx_group_start_block=idx_group_start(idxstart+1:idxend+1);\n    idx_group_start_block=idx_group_start_block-idx_group_start_block(1);\n    pred_label_block=JSRClassifier(train_data,train_label,test_data,idx_group_start_block,param);\n    pred_label_sort(idx_block)=pred_label_block;\nend\npred_label=zeros(nr*nc,1);\npred_label(sortidx)=pred_label_sort;\npred_label=reshape(pred_label,[Nx Ny]);\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u7c7b\u7b97\u6cd5/HSI-Classification-master/sr_clf/SpatialJSRC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5659808163898242}}
{"text": "function SO3F = rotate_outer(SO3F,rot,varargin)\n% rotate a function on SO(3)\n%\n% Syntax\n%   SO3F = SO3F.rotate_outer(rot)\n%\n% Input\n%  SO3F - @SO3FunHarmonic\n%  rot  - @rotation\n%\n% Output \n%  SO3F - @SO3FunHarmonic\n%\n    \nL = SO3F.bandwidth;\nD = WignerD(rot,'bandwidth',L);\n\nfor l = 0:L\n  SO3F.fhat(deg2dim(l)+1:deg2dim(l+1)) = ...\n    reshape(SO3F.fhat(deg2dim(l)+1:deg2dim(l+1)),2*l+1,2*l+1) * ...\n    reshape(D(deg2dim(l)+1:deg2dim(l+1)),2*l+1,2*l+1).' ;\nend\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/SO3Fun/@SO3FunHarmonic/rotate_outer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5659763200463047}}
{"text": "function [y,L] = midwt(x,h,L);\n%    [x,L] = midwt(y,h,L);\n% \n%    Function computes the inverse discrete wavelet transform x for a 1D or\n%    2D input signal y using the scaling filter h.\n%\n%    Input:\n%\ty : finite length 1D or 2D input signal (implicitly periodized)\n%           (see function mdwt to find the structure of y)\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 inverse DWT is returned for maximal possible\n%           L.\n%\n%    Output:\n%       x : periodic reconstructed signal\n%       L : number of decomposition levels\n%\n%    1D Example:\n%       xin = makesig('LinChirp',8);\n%       h = daubcqf(4,'min');\n%       L = 1;\n%       [y,L] = mdwt(xin,h,L);\n%       [x,L] = midwt(y,h,L)\n%\n%    1D Example's  output:\n%\n%       x = 0.0491 0.1951 0.4276 0.7071 0.9415 0.9808 0.6716 0.0000\n%       L = 1\n%\n%    See also: mdwt, mrdwt, mirdwt\n%\n\n%\n%\n%File Name: midwt.m\n%Last Modification Date: 08/07/95\t15:13:52\n%Current Version: midwt.m\t2.4\n%File Creation Date: Wed Oct 19 10:51:58 1994\n%Author: Markus Lang  <lang@jazz.rice.edu>\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:52:33 CDT 1995\n%Rebecca Hindman <hindman@ece.rice.edu>\n%Added L to function line so that it can be displayed as an output\n% \n%Thu Mar  2 13:07:11 CDT 2000\n%Ramesh Neelamani<neelsh@ece.rice.edu>\n%Revamped the help file\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_WaveletRice/midwt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5659763198349641}}
{"text": "function score =dmapMetricRel(dmap1,gtdmap,mask)\n    \n    dmap1(isinf(dmap1)) = nan;\n    gtdmap(isinf(gtdmap)) = nan;\n    mask = logical(mask);\n    x = dmap1(mask);\n    y = gtdmap(mask);\n    nanMask = ~isnan(y); % Keep points present in gt depth    \n    x = x(nanMask); y = y(nanMask);\n    x(isnan(x)) = median(x(~isnan(x)));    \n    b = median(x-y);    \n    score = abs(x-y-b)./y;\n    score = mean(score);    \nend\n", "meta": {"author": "akar43", "repo": "CategoryShapes", "sha": "55c9dab2293bcaceaaa3bf5fea782fdbf930fadb", "save_path": "github-repos/MATLAB/akar43-CategoryShapes", "path": "github-repos/MATLAB/akar43-CategoryShapes/CategoryShapes-55c9dab2293bcaceaaa3bf5fea782fdbf930fadb/evaluation/dmapMetricRel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5659763036006925}}
{"text": "function [ x, y ] = p06_dat ( data_num )\n\n%*****************************************************************************80\n%\n%% P06_DAT returns the data vector for problem 6.\n%\n%  Discussion:\n%\n%    The X data is equally spaced.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    12 August 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer DATA_NUM, the number of data points.\n%\n%    Output, real X(DATA_NUM,1), the abscissa data.\n%\n%    Output, real Y(DATA_NUM,1), the ordinate data.\n%\n  x = zeros ( data_num, 1 );\n  y = zeros ( data_num, 1 );\n\n  num_int = 5;\n\n  n = 1;\n  x(n,1) = 0.0;\n  y(n,1) = 0.0;\n\n  for i = 1 : num_int\n\n    for j = 1 : i\n      n = n + 1;\n      x(n,1) = ( i - 1 ) + 0.5 * j /i;\n      y(n,1) = j / i;\n    end\n\n    for j = 1 : i\n      n = n + 1;\n      x(n,1) = i - 1 + 0.5 + 0.5 * j / i;\n      y(n,1) = 1.0 - j / 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/test_approx/p06_dat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.5659296994535538}}
{"text": "function [gps_week, gps_sow, gps_dow] = date2gps(date)\n\n% SYNTAX:\n%   [gps_week, gps_sow, gps_dow] = date2gps(date);\n%\n% INPUT:\n%   date = date [year, month, day, hour, min, sec]\n%\n% OUTPUT:\n%   gps_week = GPS week\n%   gps_sow  = GPS seconds of week\n%   gps_dow  = GPS day of week\n%\n% DESCRIPTION:\n%   Conversion from calendar date to GPS time.\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 <http://www.gnu.org/licenses/>.\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\ngps_start_datenum = 723186; %This is datenum([1980,1,6,0,0,0])\n\n%number of days since the beginning of GPS time\n%deltat   = (datenum([date(:,1), date(:,2), date(:,3)]) - gps_start_datenum);\n% hack: datenummmx is faster cause it does not check argins\ndeltat   = (datenummx(date(:,1:3)) - gps_start_datenum);\n\ngps_week = floor(deltat/7);            %GPS week\ngps_dow  = floor(deltat - gps_week*7); %GPS day of week\ngps_sow  = (deltat - gps_week*7)*86400;\ngps_sow = gps_sow + date(:,4)*3600 + date(:,5)*60 + date(:,6); %GPS seconds of week\n\n% %alternative way, using the Julian day\n% jd = date2jd(date);\n% [gps_week, gps_dow, gps_sow] = jd2gps(jd);\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/time/date2gps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.565929687936283}}
{"text": "% GENERATE_RANDOM_OPTIONS Create random options according to some\n% delimiters\n%\n% Usage\n%\toptions = GENERATE_RANDOM_OPTIONS(white_list,type,values)\n%\n% Input\n%    white_list (cell): the white-list corresponding to the name of the\n%    field of the options\n%    type (cell of string): the type of the variable that one should\n%    expect. 'c' continuous, 'i' integer, 'd' discrete\n%    values (cell of cell): the corresponding values to a given type.\n%\n% Output\n%    filt_for_disp (numerical): displayed (real) image.\n%\n% Description\n%    For continous and integer, one excepts some interval given by \n%    {{s},{e}} where s is the first extremity of the interval and e the\n%    end.\n%    When the value is discrete, a value of the corresponding cell of\n%    values is chosen.\n%\n% Example: If white_list = {'filter_type', 'precision', 'Q', 'J', 'L',\n%   'sigma_phi','sigma_psi','xi_psi', 'slant_psi'};\n%   type = {'d', 'i', 'i', 'i', 'i', 'c', 'c', 'c', 'c'}\n%   values = { {'morlet','gabor'}, {0,1}, {1,10}, {1,10}, \n%   {1,10}, {0,50}, {0,30}, {0,30}, {0,10} };\n%\n%   then GENERATE_RANDOM_OPTIONS(white_list,type,values) is for instance\n% \n%     filter_type: 'morlet'\n%       precision: 0\n%               Q: 3\n%               J: 8\n%               L: 9\n%       sigma_phi: 25.7629\n%       sigma_psi: 26.1973\n%          xi_psi: 1.8308\n%       slant_psi: 8.2580\n% \n% See also\n%   CHECK_OPTIONS_WHITE_LIST\n\n\nfunction options=generate_random_options(white_list,type,values)\n\nassert(length(white_list)==length(type));\nassert(length(white_list)==length(values));\n\noptions=struct;\n\nfor i=1:length(white_list)\n   switch type{i}\n       case 'c'  % continuous\n           r=values{i}{1}+rand*(values{i}{2}-values{i}{1});\n           options=setfield(options,white_list{i},r);\n       case 'i'  % integer\n           r=floor(values{i}{1}+rand*(1+values{i}{2}-values{i}{1}-1));\n           options=setfield(options,white_list{i},r);\n       case 'd'  % discrete\n           s=ceil(rand*(length(values{i})));\n           options=setfield(options,white_list{i},values{i}{s});\n   end\nend\nend", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/unittest/generate_random_options.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5659296860364005}}
{"text": "b = ones(size(A,1),1);\ntol = 1e-6; maxit = 100;\n% tic; L1 = chol(A,'lower'); toc;\n% fprintf('\\n Incomplete chol decomposition');\n% tic; \n% L1 = ichol(A); \n% toc;\n% fprintf('\\n ichol as Preconditioner');\n% tic;\n% [x1,fl1,rr1,it1,rv1] = pcg(A,b,tol,maxit,@(x)icholpre(x,A,L1,L1'));\n% toc;\n% fprintf('#dof: %8.0u,  iter: %2.0u\\n',size(A,1), it1)\n% semilogy(0:it1,rv1./norm(b),'r.');\n% \nfprintf('\\n Approximate chol decomposition');\ntic;\n[L2,p,Ac] = achol(A); \ntoc;\nfprintf('\\n Achol as Preconditioner');\ntic;\nAp = A(p,p);\n[x2,fl2,rr2,it2,rv2] = pcg(A,b,tol,maxit,@(r)acholpre(r,Ap,L2,L2',p,Ac));\ntoc;\nfprintf('#dof: %8.0u,  iter: %2.0u\\n',size(A,1), it2)\nsemilogy(0:it2,rv2./norm(b),'b.');\nhold 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/iFEM/doc/testachol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6513548782017746, "lm_q1q2_score": 0.5659145545904412}}
{"text": "function [P,X] = vgg_PX_from_6pts_3img(x1,x2,x3)\n% vgg_PX_from_6pts_3img  Computes camera matrices and world points \n% from 6 points across 3 images.\n%\n%   [P,X] = vgg_PX_from_6pts_3img(x), where\n%      x ... double(3,6,3) or cell{3} of double(3,6), 6 homogeneous points in 3 images\n%      P ... double(3,4,3), P(:,:,k) is k-th camera matrix\n%      X ... double(4,6), homogeneous world points\n%   There are 0 to 3 solutions for (P,X). Solutions are pruned by requirement that\n%   scalars s in all projective equations s*x==P*X are positive.\n%   In case of multiple solutions, P and X have one dimension\n%   more such that P(:,:,:,n) and X(:,:,n) is the n-th solution.\n%\n%   Also the form [P,X] = vgg_PX_from_6pts_3img(x1,x2,x3) is accepted.\n\n% Algorithm in Hartley-Zisserman, Alg 19.1 page 493 in 1st edition,\n%                                 Alg 20.1 page 511 in 2nd edition\n% Coded by werner@robots.ox.ac.uk, Nov 2002.\n\nif nargin==3\n  x = cat(3,x1,x2,x3);\nelse\n  if iscell(x1)\n    x = cat(3,x1{:});\n  else\n    x = x1;\n  end\nend\nif any(size(x)~=[3 6 3])\n  error('Wrong size of input points.');\nend\n\nfor k = 1:3\n  % Find homographies H_k mapping first 4 pts in each image to standard projective basis.\n  % Now, x(:,1:4,k) = H(:,:,k)*[eye(3) [1;1;1]].\n  H(:,:,k) = H_from_4x(x(:,3:6,k));\n  \n  % Form transformed points xs(:,1:2,k)\n  xs(:,:,k) = inv(H(:,:,k))*x(:,:,k);\nend\n\n% Compute dual fundamental matrix\nFd = Fdual_from_x(xs(:,1:2,:));\n\n% Retrieve (non-dual) cameras P and world points X from (each solution for) dual fund. matrix.\nP = [];\nX = [];\nfor i = 1:size(Fd,3)\n  \n  % Compute canonical Xi and Pi\n  Xi = X_from_Fdual(Fd(:,:,i));\n  Pi = P_from_Xx_canonical(Xi,xs);\n  \n  % return from canonical to original image bases\n  for k = 1:3\n    Pi(:,:,k) = H(:,:,k)*Pi(:,:,k);\n  end\n  \n  % Compute signs of P and X, if possible. If impossible, Pi==Xi==[].\n  [Pi,Xi] = vgg_signsPX_from_x(Pi,Xi,x);\n  if isempty(Pi), continue, end\n  %for k = 1:3, Pi(:,:,k)*Xi ./ x(:,:,k), end  % test code\n\n  P = cat(4,P,Pi);\n  X = cat(3,X,Xi);\n\nend\n\nreturn\n\n\n%%%%%%%%%%%%%%%% auxiliary functions\n\n\n% Solve for dual fundamental matrix.\nfunction F = Fdual_from_x(x)\n\n% Linear step. After that,\n% for k=1:3 and i=1:2, it is x(:,1,k)'*F_i*x(:,2,k)==0.\nA = [];\nfor k = 1:3\n  x1 = x(1,1,k);  y1 = x(2,1,k);  z1 = x(3,1,k);\n  x2 = x(1,2,k);  y2 = x(2,2,k);  z2 = x(3,2,k);\n  A = [A; [x1*y2-z1*y2,...\n           x1*z2-z1*y2,...\n           y1*x2-z1*y2,...\n           y1*z2-z1*y2,...\n           z1*x2-z1*y2] ];\nend\n[u,s,v] = svd(A,0);\nv1 = v(:,end-1);\nv2 = v(:,end);\nFF{1} = [0 v1(1:2)'; v1(3) 0 v1(4); v1(5) -sum(v1) 0];\nFF{2} = [0 v2(1:2)'; v2(3) 0 v2(4); v2(5) -sum(v2) 0];\n\n% Non-linear step. Find linear combination of F_i having zero determinant.\n% Dual fund. matrix is now  F = a*FF{1} + (1-a)*FF{2}, for each element of a.\na = vgg_singF_from_FF(FF);\nfor i = 1:length(a)\n  F(:,:,i) = a(i)*FF{1} + (1-a(i))*FF{2};\nend\nreturn\n\n\n% Given dual fundamental matrix Fd, computes cameras P and world points X such that\n% for each k, P(:,:,k)*X ~ x(:,:,k).\nfunction X = X_from_Fdual(Fd)\n\n% Retrieve second dual camera matrix Pd2.\n% It is done by considering Fdual in form\n%[0 b*(d-c) -c*(d-b)\n% -a*(d-c) 0 c*(d-a)\n% a*(d-b) -b*(d-a) 0].\n\nFd_aux = reshape( Fd([4 7 1 2 1 8 1 3 6]), [3 3] );\n[u,s,v] = svd(Fd_aux,0);\nABC = v(:,3); % It is a:b:c = A:B:C\n[u,s,v] = svd(Fd',0);\nKLM = v(:,3); % It is K:L:M = ((d-a):(d-b):(d-c)\n\nG = [0 -ABC(3) ABC(2) 0\n     ABC(3) 0 -ABC(1) 0\n     -ABC(2) ABC(1) 0 0\n     KLM(2) -KLM(1) 0 KLM(1)-KLM(2)\n     0 KLM(3) -KLM(2) KLM(2)-KLM(3)\n     -KLM(3) 0 KLM(1) KLM(3)-KLM(1) ];\n[u,s,v] = svd(G,0);\nabcd = v(:,end);\n\n% The test code:\n%Pd1 = [eye(3) [1;1;1]];\n%Pd2 = [diag(abcd(1:3)) [1;1;1]*abcd(4)];\n%vgg_F_from_P(Pd1,Pd2) ./ Fd\n\n% Retrieve 6 world points X(:,1:6)\nX = [ abcd [1;1;1;1] eye(4) ];\n\nreturn\n\n\n% Computes camera P from world points X and image points x, everything in canonical form.\nfunction P = P_from_Xx_canonical(X,x)\nX = X(:,1);\nfor k = 1:3\n  A = [contreps(x(:,1,k))*[X(1) 0 0 X(4)\n                           0 X(2) 0 X(4)\n                           0 0 X(3) X(4)]\n       contreps(x(:,2,k))*[eye(3) [1;1;1]]];\n  [u,s,v] = svd(A,0);\n  a = v(:,end);\n  P(:,:,k) = [a(1) 0 0 a(4)\n              0 a(2) 0 a(4)\n              0 0 a(3) a(4)];\nend\nreturn\n\n\n% A bit faster vgg_contreps.\nfunction X = contreps(x)\nX = [0 x(3) -x(2)\n     -x(3) 0 x(1)\n     x(2) -x(1) 0];\nreturn\n\n\n% H_from_4x  Having four point matches, the homography relating them is given by\n% H = H_from_4x(x2)*inv(H_from_4x(x1)).\nfunction H = H_from_4x(x)\nH = x(:,1:3) * diag(inv(x(:,1:3))*x(:,4));\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% Test code:\nP = randn(3,4,3); X = randn(4,6);\nfor k = 1:3, x(:,:,k) = P(:,:,k)*X; end\n[Pn,Xn] = vgg_PX_from_6pts_3img(x);\n\n% check image points x predicted up to scale\nfor k=1:3, Pn(:,:,k)*Xn(:,:) ./ x(:,:,k), end\n\n", "meta": {"author": "jmmanley", "repo": "VGG-Multiple-View-Geometry", "sha": "f114712de03082bb97229eaf2a65981908b64127", "save_path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry", "path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry/VGG-Multiple-View-Geometry-f114712de03082bb97229eaf2a65981908b64127/vgg_multiview/vgg_PX_from_6pts_3img.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5659145443439134}}
{"text": "%  switching_divided_difference_filter - filter for nonlinear regime-swiching models\n% \n%  ::\n% \n% \n%    [loglik,Incr,retcode,Filters]=switching_divided_difference_filter(...\n%     syst,y,U,z,options)\n% \n%  Args:\n% \n%     - **syst** [struct]: structure containing:\n% \n%           - **PAI00** [vector]: initial probability distributions of regimes\n% \n%           - **a** [cell]: initial conditions in each regime\n% \n%           - **Qfunc** [function handle]: transition matrix generator\n% \n%           - **ff** [function handle]: ft=ff(rt,xt,et), where rt is the\n%           regime, xt is the vector of state variables and et the vector of\n%           shocks\n% \n%           - **P** [cell]: initial covariance matrix of the states in each\n%           regime\n% \n%           - **H** [cell]: Measurement error covariance matrices in each regime\n% \n%           - **SIGeta** [cell]: Covariance matrix of structural shocks.\n% \n%     - **y** [matrix]: ny x T matrix of data\n% \n%     - **U** [[]|matrix]: ndx x T matrix of exogenous data\n% \n%     - **z** [function handle|logical|vector]: linear connection of the\n%     observables to the state.\n% \n%     - **include_in_likelihood** [logical]: selector of increments to include\n%     in the likelihood calculation\n% \n%     - **options** [struct]: structure with various options\n% \n%  Returns:\n%     :\n% \n%     - **loglik** [scalar]: log likelihood\n% \n%     - **Incr** [vector]: increments of elements going into the likelihood\n% \n%     - **retcode** [{0}|integer]: flag for problems.\n% \n%     - **Filters** [struct]: Filtered, updated and smoothed variables\n% \n%  Note:\n% \n%  Example:\n% \n%     See also:\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/switching_divided_difference_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5659145384056228}}
{"text": "function [b,R,se]=drxlr_wfit(y,x,w,p)\n%DREX subfunction \n%Written by Issam El Naqa 2003-2005\n%Extracted for generalized use 2005, AJH\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the DREES development team.\n% \n% This file is part of the Dose Response Explorer System (DREES).\n% \n% DREES development has been led by:  Issam El Naqa, Aditya Apte, Gita Suneja, and Joseph O. Deasy.\n% \n% DREES has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% DREES is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of DREES 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% DREES is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with DREES.  If not, see <http://www.gnu.org/licenses/>.\n\nsw = sqrt(w);\n[r c] = size(x);\nyw = y .* sw;\nxw = x .* sw(:,ones(1,c));\n[Q,R]=qr(xw,0);\nb = R\\(Q'*yw);\nRI = R\\eye(p);\nC = RI * RI';\nse = sqrt(max(eps,diag(C)));\nreturn", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/MultivariableModeling/LogisticRegression/drxlr_wfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5659145310700485}}
{"text": "function [nrm] = lognrm(tt)\n%Frobenius norm of the TT-tensor\n%   [NRM]=LOGNRM(TT) Computes log10 of the Frobenius norm of a tensor\n%\n%\n% TT-Toolbox 2.2, 2009-2012\n%\n%This is TT Toolbox, written by Ivan Oseledets et al.\n%Institute of Numerical Mathematics, Moscow, Russia\n%webpage: http://spring.inm.ras.ru/osel\n%\n%For all questions, bugs and suggestions please mail\n%ivan.oseledets@gmail.com\n%---------------------------\n\nd=tt.d;\nn=tt.n;\nr=tt.r;\npos=tt.ps;\ncr=tt.core;\npos1=1;\nnrm=zeros(d,1);\ncore0=cr(1:r(1)*n(1)*r(2));\n%Orthogonalization from left-to-tight\nfor i=1:d-1\n   core0=reshape(core0,[r(i)*n(i),r(i+1)]);\n   [core0,ru]=qr(core0,0); nrm(i)=norm(ru,'fro');\n   nrm(i)=max(nrm(i),1e-308);\n   ru=ru./nrm(i);\n   core1=cr(pos(i+1):pos(i+2)-1);\n   core1=reshape(core1,[r(i+1),n(i+1)*r(i+2)]);\n   core1=ru*core1;\n   r(i+1)=size(core0,2);\n   cr(pos1:pos1-1+r(i)*n(i)*r(i+1))=core0(:);\n   cr(pos1+r(i)*n(i)*r(i+1):pos1+r(i)*n(i)*r(i+1)+r(i+1)*n(i+1)*r(i+2)-1)=core1(:);\n   core0=core1;\n   pos1=pos1+r(i)*n(i)*r(i+1);\nend\npos1=pos1+r(d)*n(d)*r(d+1)-1;\nnrm(d)=norm(core0(:));\nnrm=sum(log10(nrm));\nreturn\nend", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/@tt_tensor/lognrm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5658342137011313}}
{"text": "function [g1, g2] = rbfinfwhiteXwhiteKernGradient(rbfKern, whiteKern, t1, varargin)\n\n% RBFINFWHITEXWHITEKERNGRADIENT Compute gradient between the RBF-WHITE kernel\n% (with integration limits between minus infinity and infinity) and the\n% WHITE kernel.\n% FORMAT\n% DESC computes the gradient of an objective function with respect to cross\n% kernel terms between RBF-WHITE and WHITE kernels for the multiple output\n% kernel. \n% ARG rbfKern : the kernel structure associated with the RBF-WHITE\n% kernel.\n% ARG whiteKern : the kernel structure associated with the WHITE\n% kernel.\n% ARG t1 : inputs for which kernel is to be computed.\n% ARG covGrad : gradient of the objective function with respect to\n% the elements of the cross kernel matrix.\n% RETURN g1 : gradient of objective function with respect to kernel\n% parameters of RBF-WHITE kernel.\n% RETURN g2 : gradient of objective function with respect to kernel\n% parameters of WHITE kernel.\n%\n% FORMAT\n% DESC computes the gradient of an objective function with respect\n% to cross kernel terms between RBF-WHITE and WHITE kernels for\n% the multiple output kernel. \n% ARG rbfKern : the kernel structure associated with the RBF-WHITE\n% kernel.\n% ARG whiteKern : the kernel structure associated with the WHITE\n% kernel.\n% ARG t1 : row inputs for which kernel is to be computed.\n% ARG t2 : column inputs for which kernel is to be computed.\n% ARG covGrad : gradient of the objective function with respect to\n% the elements of the cross kernel matrix.\n% RETURN g1 : gradient of objective function with respect to kernel\n% parameters of RBF-WHITE kernel.\n% RETURN g2 : gradient of objective function with respect to kernel\n% parameters of WHITE kernel.\n%\n% SEEALSO : multiKernParamInit, multiKernCompute, rbfinfwhiteKernParamInit,\n% whiteKernParamInit\n%\n% COPYRIGHT : David Luengo, 2009\n\n% KERN\n\n\nif nargin < 5\n    t2 = t1;\nelse\n    t2 = varargin{1};\nend\ncovGrad = varargin{end};\n\nif size(t1, 2) > 1 | size(t2, 2) > 1\n  error('Input can only have one column');\nend\nif rbfKern.variance ~= whiteKern.variance\n  error('Kernels cannot be cross combined if they have different variances.')\nend\n\ng1 = zeros(1, 2);\ng2 = 0; % The only parameter of the WHITE kernel (its variance) is already\n        % accounted for in g1\n\n% Parameters required for further computations\nvariance = rbfKern.variance;\ninvWidth = rbfKern.inverseWidth;\n\nT1 = repmat(t1, 1, size(t2, 1));\nT2 = repmat(t2.', size(t1, 1), 1);\ndeltaT = T1 - T2;\n\nK = exp(-0.5*invWidth*(deltaT.^2));\n\n% Gradient w.r.t. the inverse width\ng1(1) = (0.5*variance/sqrt(2*pi)) ...\n    * sum(sum((1/sqrt(invWidth)-sqrt(invWidth)*(deltaT.^2)) .* K .* covGrad));\n\n% Gradient w.r.t. sigma_r^2\ng1(2) = sqrt(invWidth/(2*pi)) * sum(sum(K .* covGrad));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/rbfinfwhiteXwhiteKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5658342055195027}}
{"text": "%% plot array map & compute eastings and northings\nif make_figures\n    disp('Plotting array map')\n    close all\n    cols = 'rwbggg';\n    for c=1:length(lat)\n        chan = get(w(c),'channel');;\n        plot(easting(c),northing(c),'o','MarkerFaceColor',cols(c),'MarkerSize',10)\n        hold on\n        quiver(easting(c),northing(c),-easting(c)/100,-northing(c)/100,0); % /100 just gives arrow length\n        text(easting(c)+1,northing(c),chan(1:3));\n    end\n    grid on\n    quiver(440,1325,wind_speed*sin(deg2rad(wind_direction)), wind_speed*cos(deg2rad(wind_direction)) ,0,'k');\n    text(440,1325,'wind')\n    hold off\n    title('Beach House array position relative to SLC40');\n    xlabel('metres east');\n    ylabel('metres north');\n    axis equal;\n    outfile = sprintf('%s/arraymap.png',figureOutDirectory);\n    feval('print', '-dpng', outfile); \n    close\nend", "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/eventMap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5658341973378738}}
{"text": "function [footPrint, nPix]= get_footprint(xs, Ly, Lx, ops)\n\n\n[Mmax, imax] = max(xs, [], 2);\n\nyp = rem(imax-1, Ly) + 1;\nxp = ceil(imax/Ly);\n\nNk = size(xs,1);\nfootPrint = zeros(Nk, 1);\nnPix = zeros(Nk, 1);\n\nd = ops.diameter;\nXS = repmat([-d*2:d*2], 4*d+1, 1);\nYS = XS';\n\nds = (XS.^2 + YS.^2).^.5;\n\nfor j = 1:Nk\n    yp1 = yp(j) + YS;\n    xp1 = xp(j) + XS;\n    \n    badi = (yp1<1) | (yp1>Ly) | (xp1<1) | (xp1>Lx);\n    yp1 = yp1(~badi);\n    xp1 = xp1(~badi);\n    allds = ds(~badi);\n    \n    ind = xs(j, yp1 + (xp1-1) * Ly) > Mmax(j)/2;\n    \n    footPrint(j) = mean(allds(ind));\n    nPix(j) = numel(allds);\nend\n\nend", "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/cellDetection/get_footprint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.5658341917541443}}
{"text": "function [tinyImage, colorHist, param] = LMcolor(D, HOMEIMAGES, param)\n%\n% [tinyImage, colorHist, param] = LMcolor(D, HOMEIMAGES, param);\n%\n% param.tinySize\n% param.colorHist.imagesize\n% param.colotHist.\n%\n% Use transformations from \"color indexing\", Swain & Ballard, IJCV 91\n%\n%   wb = (r+g+b)/3\n%   rg = r - g\n%   by = b-r/2-g/2\n\n\nif nargin<3\n    % Default parameters\n    param.tinySize = [16 16];\n    param.colorHist.imagesize = [256 256];\n    param.colorHist.nbins = [8 16 16];\n    param.colorHist.margins.wb = [0 255];\n    param.colorHist.margins.rg = [-255 255];\n    param.colorHist.margins.by = [-255 255];\nend\n\n% Precompute filter transfert functions (only need to do this once, unless\n% image size is changes):\nNfeatures = prod(param.colorHist.nbins);\n\nif isstruct(D)\n    % [gist, param] = LMcolor(D, HOMEIMAGES, param);\n    Nscenes = length(D);\n    typeD = 1;\nend\nif iscell(D)\n    % [gist, param] = LMcolor(filename, HOMEIMAGES, param);\n    Nscenes = length(D);\n    typeD = 2;\nend\nif isnumeric(D)\n    % [gist, param] = LMcolor(img, HOMEIMAGES, param);\n    Nscenes = size(D,4);\n    typeD = 3;\nend\n\n% Loop: Compute gist features for all scenes\ntinyImage = zeros([param.tinySize 3 Nscenes], 'single');\ncolorHist = zeros([Nscenes Nfeatures], 'single');\nfor n = 1:Nscenes\n    disp([n Nscenes])\n    \n    % load image\n    try\n        switch typeD\n            case 1\n                img = LMimread(D, n, HOMEIMAGES);\n            case 2\n                img = imread(fullfile(HOMEIMAGES, D{n}));\n            case 3\n                img = D(:,:,:,n);\n        end\n    catch\n        disp(D(n).annotation.folder)\n        disp(D(n).annotation.filename)\n        rethrow(lasterror)\n    end\n    \n    % resize and crop image to make it square\n    tiny = imresizecrop(img, param.tinySize+2, 'bilinear');\n    tinyImage(:,:,:,n) = tiny(2:end-1, 2:end-1,:);\n    \n    subplot(211)\n    imagesc(img); axis('off'); axis('equal')\n    subplot(212)\n    imagesc(tiny); axis('on'); axis('equal')\n    \n    % resize and crop image to make it square\n    img = single(imresizecrop(img, param.imagesize, 'bilinear'));\n    \n    %   wb = (r+g+b)/3\n    %   rg = r - g\n    %   by = b-r/2-g/2\n    wb = mean(img,3);\n    rg = img(:,:,1)-img(:,:,2);\n    by = img(:,:,3)-img(:,:,1)/2-img(:,:,2)/2;\n    \n    wb = (wb(:)-param.colorHist.margins.wb(1))/(param.colorHist.margins.wb(2)-param.colorHist.margins.wb(1));\n    rg = (rg(:)-param.colorHist.margins.rg(1))/(param.colorHist.margins.rg(2)-param.colorHist.margins.rg(1));\n    by = (by(:)-param.colorHist.margins.by(1))/(param.colorHist.margins.by(2)-param.colorHist.margins.by(1));\n    \n    wb = fix(wb*param.colorHist.nbins(1));\n    rg = fix(rg*param.colorHist.nbins(2));\n    by = fix(by*param.colorHist.nbins(3));\n    \n    wb = min(max(0,wb), param.colorHist.nbins(1)-1);\n    rg = min(max(0,rg), param.colorHist.nbins(2)-1);\n    by = min(max(0,by), param.colorHist.nbins(3)-1);\n    \n    h = by + rg*param.colorHist.nbins(3) + wb*param.colorHist.nbins(3)*param.colorHist.nbins(2);\n    H = hist(h, [0:Nfeatures-1]);\n    \n    % store\n    colorHist(n,:) = H;\n    drawnow\nend\n\n", "meta": {"author": "CSAILVision", "repo": "LabelMeToolbox", "sha": "b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2", "save_path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox", "path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox/LabelMeToolbox-b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2/features/LMcolor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5658341865583456}}
{"text": "function planC = calculateGRE(baseScanNum,movScanNum,planC)\n% function planC = calculateGRE(baseScanNum,movScanNum,planC)\n%\n% APA, 03/21/2017\n\nif ~exist('planC','var')\n    global planC\nend\nindexS = planC{end};\n\n% Absolute Difference between two scans\nsiz = size(planC{indexS.scan}(baseScanNum).scanArray);\nbaseMask3M = logical(maskByThresh3D(planC{indexS.scan}(baseScanNum).scanArray));\nmovMask3M = logical(maskByThresh3D(planC{indexS.scan}(movScanNum).scanArray));\nsA1 = zeros(siz,'single');\nmeanSa1 = mean(single(planC{indexS.scan}(baseScanNum).scanArray(baseMask3M)));\nsdSa1 = std(single(planC{indexS.scan}(baseScanNum).scanArray(baseMask3M)));\nsA1(baseMask3M) = (single(planC{indexS.scan}(baseScanNum).scanArray(baseMask3M)) - meanSa1)/sdSa1;\nsA2 = zeros(siz,'single');\nmeanSa2 = mean(single(planC{indexS.scan}(movScanNum).scanArray(movMask3M)));\nsdSa2 = std(single(planC{indexS.scan}(movScanNum).scanArray(movMask3M)));\nsA2(movMask3M) = (single(planC{indexS.scan}(movScanNum).scanArray(movMask3M)) - meanSa2)/sdSa2;\ndiff3M = abs(sA1 - sA2);\n\n% Window size\nslcWindow = 5;\nrowWindow = 5;\ncolWindow = 5;\n\n% Number of levels for histogram\nnumLevels = 16;\n% Create initial imM with dimension of slcWindow\nimM = [];\nfor slc = 1:slcWindow\n    imTmpM = im2col(diff3M(:,:,slc),[rowWindow colWindow],'sliding');\n    imM = [imM;imTmpM];\nend\n\nnumNeighbors = rowWindow*colWindow;\nnumSlcs = size(diff3M,3);\nnumRows = size(diff3M,1);\nnumCols = size(diff3M,2);\nentropy3M = zeros(siz,'single');\nmean3M = zeros(siz,'single');\nvar3M = zeros(siz,'single');\nfor slc = 1:numSlcs\n    disp(['-------------------', num2str(slc)])\n    if slc > floor(slcWindow/2) && slc <= (numSlcs-floor(slcWindow/2))\n        imM(1:numNeighbors,:) = [];\n        imTmpM = im2col(diff3M(:,:,slc),[rowWindow colWindow],'sliding');\n        imM = [imM;imTmpM];\n    end\n    countsM = hist(imM,numLevels);\n    countsM = countsM/numNeighbors/colWindow;\n    entrpy2M = col2im(-sum(countsM.*log2(countsM+eps)),[rowWindow colWindow],[numRows numCols],'sliding');\n    mean2M = col2im(mean(imM),[rowWindow colWindow],[numRows numCols],'sliding');\n    var2M = col2im(var(imM),[rowWindow colWindow],[numRows numCols],'sliding');\n    for i = 1:floor(slcWindow/2)\n        entrpy2M = [entrpy2M(:,1), entrpy2M, entrpy2M(:,end)];\n        entrpy2M = [entrpy2M(1,:); entrpy2M; entrpy2M(end,:)];\n        mean2M = [mean2M(:,1), mean2M, mean2M(:,end)];\n        mean2M = [mean2M(1,:); mean2M; mean2M(end,:)];\n        var2M = [var2M(:,1), var2M, var2M(:,end)];\n        var2M = [var2M(1,:); var2M; var2M(end,:)];\n    end\n    entropy3M(:,:,slc) = entrpy2M;\n    mean3M(:,:,slc) = mean2M;\n    var3M(:,:,slc) = var2M;\nend\n\ngre3M = entropy3M/median(entropy3M(baseMask3M)) + mean3M/median(mean3M(baseMask3M)) + var3M/median(var3M(baseMask3M));\ngre3M = gre3M / 3;\n\n% \n% showIMDose(diff3M,'Diff',1);\n% showIMDose(entropy3M,'Entropy',1);\n% showIMDose(mean3M,'Mean',1);\n% showIMDose(var3M,'Variance',1);\n% showIMDose(gre3M,'GRE',1);\n\nregister = 'UniformCT';  %Currently only option supported.  Dose has the same shape as the uniformized CT scan.\ndoseError = [];\ndoseEdition = 'Generalized Registration Error';\noverWrite = 'no';  %Overwrite the last CERR dose?\nif ~exist('assocScanNum','var')\n    assocScanNum = 1;\nend\nfractionGroupID = 'GRE';\nassocScanUID = planC{indexS.scan}(assocScanNum).scanUID;\ndescription = '';\nplanC = dose2CERR(gre3M,doseError,fractionGroupID,doseEdition,description,register,[],overWrite,assocScanUID,planC);\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/calculateGRE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5658313526166149}}
{"text": "function IOU = IOU_with_GT(estimate, ground_truth)\n    % strip off NaNs used to maintain all groundtruth in same matrix\n    ground_truth = ground_truth(~isnan(ground_truth));\n    % axis-aligned rectangle format\n    if numel(ground_truth)==4\n        if sum(estimate)==0\n            IOU = 0;\n        else\n            IOU = bboxOverlapRatio(estimate, ground_truth);\n        end\n    else\n        % rotated bounding box format (VOT)\n        warning off;\n        e_x = [estimate(1) estimate(1)+estimate(3) estimate(1)+estimate(3) estimate(1)];\n        e_y = [estimate(2) estimate(2) estimate(2)+estimate(4) estimate(2)+estimate(4)];\n        gt_x = ground_truth(1:2:7);\n        gt_y = ground_truth(2:2:8);\n        [intersection_x, intersection_y] = polybool('intersection',e_x,e_y,gt_x,gt_y);\n        [union_x, union_y] = polybool('union',e_x,e_y,gt_x,gt_y);\n\n        interseaction_area = polyarea(intersection_x, intersection_y);\n        union_area = polyarea(union_x, union_y);\n\n        IOU = interseaction_area / union_area;\n        if isnan(IOU)\n            IOU = 0;\n        end\n    end\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/IOU_with_GT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5658118695333325}}
{"text": "function res = reduce(im,bfilt)\n%\n% function res = reduce(im,bfilt)\n%\n% Separable convolution and subsampling by a factor of two\n% im: input image\n% bfilt: convolution kernel (vector).  \n%       Default is: [.0625 .25 .375 .25 .0625]'\n% res: result image\n%\n% res is 1/2 the size of im.  Fills NaNs for invalid pixels near\n% edges.\n\nif ~exist('bfilt')\n  bfilt=[.0625 .25 .375 .25 .0625]';\nend\n\n% Use standard Matlab convolution routines instead for ease of\n% distribution, and to set edge values to NaNs\nbsize = floor(length(bfilt)/2);\ntmp1 = conv2sep(im,bfilt,bfilt,'valid');\ntmp2 = NaN*ones(size(im));\ntmp2(1+bsize:size(im,1)-bsize,1+bsize:size(im,2)-bsize)=tmp1;\nres = tmp2(1:2:size(im,1),1:2:size(im,2));\n\nreturn;\n\n%%%%%%%%%\n% Debug %\n%%%%%%%%%\n\nfoo=pgmRead('einstein.pgm');\nbar=reduce(foo);\nbar=replaceValue(bar,NaN,0);\ndisplayImage(bar);\n\nin=ones(7,7)\nres=reduce(in)\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/utilities/reduce.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5658118695333324}}
{"text": "function [f, fval] = test(varargin)\n\n% Images\nif nargin == 0\n    A = imread('pout.tif');\n    B = imread('cameraman.tif');\nelseif nargin == 2\n    A = varargin{1};\n    B = varargin{2};\n    if ischar(A)\n        A = imread(A);\n    end;\n    if ischar(B)\n        B = imread(B);\n    end;\nend;\n\n% Histograms\nnbins = 10;\n[ca ha] = imhist(A, nbins);\n[cb hb] = imhist(B, nbins);\n\n% Features\nf1 = ha;\nf2 = hb;\n\n% Weights\nw1 = ca / sum(ca);\nw2 = cb / sum(cb);\n\n% Earth Mover's Distance\n[f, fval] = emd(f1, f2, w1, w2, @gdf);\n\n% Results\nwtext = sprintf('fval = %f', fval);\nfigure('Name', wtext);\nsubplot(121);imshow(A);title('first image');\nsubplot(122);imshow(B);title('second image');\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/22962-the-earth-movers-distance/emd-2005-02/test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5658118637642915}}
{"text": "%DEMO_PASSGP Demonstration of PASS-GP method for GP classification\n%\n%  Description\n%    Here we demonstrate PASS-GP method for Gaussian Processes\n%    classification. Data used is 2-dimensional toy data with Gaussian\n%    bumbs defining classes. We demonstrate with both fixed and not fixed\n%    sizes of active set for PASS-GP.\n%\n%    PASS-GP uses a predictive active set selection method by Henao &\n%    Winther (2012) to select a subset of training data to be used for\n%    inference in classification problems.\n%\n%  Reference:\n%    Ricardo Henao & Ole Winther (2012). Predictive active set selection\n%    methods for Gaussian processes. Neurocomputing 80 (2012), 10-18.\n%\n%  See also PASSGP\n%\n% Copyright (c) 2013 Ville Tolvanen\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 toy data\nprevstream=setrandstream(0);\n[x1,x2]=meshgrid(-5:0.1:5,-5:0.1:5);\nx=[x1(:) x2(:)]; x=x(randperm(size(x,1),3000),:);\ny=2.*mnorm_pdf(x, [0 0], [0.5 0;0 0.5]) + mnorm_pdf(x, [3 3], [0.5 0;0 0.5]) + mnorm_pdf(x, [-3 -3], [0.5 0;0 0.5]);\ny=y+mnorm_pdf(x, [3 -3], [0.5 0;0 0.5])+mnorm_pdf(x, [-3 3], [0.5 0;0 0.5]);\ny=y+0.03.*randn(size(y,1),1);\ny(y>0.15)=1; y(y<=0.15)=-1;\n\n[xt1, xt2]=meshgrid(-5:0.23:5,-5:0.23:5);\nxt=[xt1(:) xt2(:)];\nyt=ones(size(xt,1),1);\n\n[n, nin] = size(x);\n\n% Define covariance and likelihood functions and create the model\ngpcf = gpcf_sexp();\nlik=lik_probit();\ngp=gp_set('lik', lik, 'cf', gpcf, 'jitterSigma2', 1e-6);\n\nopt=optimset('TolX',1e-3,'TolFun',1e-3,'display','on');\nw0=gp_pak(gp);\n\n% fPASS-GP with fixed size of 800 points in active set and data divided to\n% 10 subsets with 4 sweeps over data\nstart=tic;[gp, indA]=passgp(gp, x, y, 'opt', opt, 'npass', 4, 'ninit', 800, 'nsub', 10, 'display', 'on', 'fixed', 'on', 'pexc', 0.1, 'optimn', 2);time=toc(start);\ntt=time;\n[Eft, Varft, lpyt, Eyt, Varyt]=gp_pred(gp, x(indA,:), y(indA,:), xt, 'yt', yt);\nfigure, [cc,hh]=contour(reshape(xt(:,1),size(xt1,1), size(xt1,1)), reshape(xt(:,2),size(xt1,1), size(xt1,1)), reshape(exp(lpyt),size(xt1,1), size(xt1,1)), [0.1 0.9]);\nclabel(cc,hh); title('Pr(y==1) (fpass-gp)')\nparam=gp_pak(gp);\n\n% PASS-GP with inclusion threshold 0.65, deletion threshold 0.99, intial\n% size of 400 points in active set and 3 sweeps over data.\ngp=gp_unpak(gp,w0);\nstart=tic;[gp, indA2]=passgp(gp, x, y, 'opt', opt, 'pinc', 0.65, 'pdel', 0.99, 'npass', 3, 'ninit', 400, 'nsub', 10, 'display', 'on', 'optimn', 2);time=toc(start);\ntt2=time;\n[Eft2, Varft2, lpyt2, Eyt2, Varyt2]=gp_pred(gp, x(indA2,:), y(indA2,:), xt, 'yt', yt);\nfigure, [cc,hh]=contour(reshape(xt(:,1),size(xt1,1), size(xt1,1)), reshape(xt(:,2),size(xt1,1), size(xt1,1)), reshape(exp(lpyt2),size(xt1,1), size(xt1,1)), [0.1 0.9]);\nclabel(cc,hh); title('Pr(y==1) (pass-gp)')\nparam2=gp_pak(gp);\n\n% Full Gaussian process for comparison\ngp=gp_unpak(gp,w0);\nopt.Display='iter';\nstart=tic;gp=gp_optim(gp,x,y,'opt',opt);tt3=toc;\n[Eft3, Varft3, lpyt3, Eyt3, Varyt3]=gp_pred(gp, x, y, xt, 'yt', yt);\nfigure, [cc,hh]=contour(reshape(xt(:,1),size(xt1,1), size(xt1,1)), reshape(xt(:,2),size(xt1,1), size(xt1,1)), reshape(exp(lpyt3),size(xt1,1), size(xt1,1)), [0.1 0.9]);\nclabel(cc,hh); title('Pr(y==1) (full gp)')\n\n% Display some statistics\nmlpd_fpassgp=mean(mean(lpyt,2))\ntime_fpassgp=mean(tt)\nmlpd_passgp=mean(mean(lpyt2,2))\ntime_passgp=mean(tt2)\nmlpd_full=mean(lpyt3)\ntime_full=tt3\n\n% Plot data and active sets for both methods\nfigure(4), subplot(1,2,1),  plot(x(y==1,1),x(y==1,2),'or',x(y==-1,1),x(y==-1,2),'ob'); \nhold all; plot(x(indA,1), x(indA,2), '.k'); title('Data and active set (fpass-gp)')\nlegend('y=1', 'y=-1', 'Active set for fpass-gp');\nsubplot(1,2,2),  plot(x(y==1,1),x(y==1,2),'or',x(y==-1,1),x(y==-1,2),'ob'); \nhold all; plot(x(indA2,1), x(indA2,2), '.k'); title('Data and active set (pass-gp)')\nlegend('y=1', 'y=-1', 'Active set for pass-gp');\nsetrandstream(prevstream);\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_passgp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5657217718705839}}
{"text": "function [  ] = DP_save_rows( cutCostsFile, cut_num,  search_k, saveFileAddress )\n%DP_SAVE_ROWS Summary of this function goes here\n%   Detailed explanation goes here\n\n    file_t = fopen(cutCostsFile);\n    cut_costs = fscanf(file_t, '%d');\n    fclose(file_t);\n    \n    % get the initial averaging-cut\n    \n    cut_length = length(cut_costs) / cut_num;\n    \n    for i = 1:cut_num-1\n       initial_cuts(i,:) = floor(i*cut_length); \n    end\n    \n    % start Dynamic Programming\n    % find the best/min value in the domain near cut_points as initial\n    % values\n    \n    best_values = [];\n    best_cuts = [];\n    search_domain_start = floor(cut_length / search_k);\n    search_domain_finish = floor(cut_length / search_k);\n    \n    sum_best_value = 0;\n    \n    for i = 1:length(initial_cuts)\n        \n        start = initial_cuts(i,:)-search_domain_start;\n        finish = initial_cuts(i,:)+search_domain_finish;\n        \n        if start <= 0\n            start = 1;\n            search_domain_start = initial_cuts(i,:) - start;\n        end\n        \n        if finish > length(cut_costs)-1\n            finish  = length(cut_costs)-1;\n            search_domain_finish = finish - initial_cuts(i,:);\n        end\n        \n        domain = cut_costs(start:finish,:);\n        \n        % observe the minimum\n%         [min_value, min_cut] = min(domain);\n        % obserbe the maximum\n        [min_value, min_cut] = max(domain);\n        \n        best_values(i,:) = min_value;\n        \n        if min_cut < initial_cuts(i,:)\n            best_cuts(i,:) = initial_cuts(i,:) + (min_cut - search_domain_start - 1);\n        else\n            best_cuts(i,:) = initial_cuts(i,:) + (min_cut - search_domain_finish - 1);\n        end\n        \n        if i > 1 && best_cuts(i,:) == best_cuts(i-1,:)\n            best_cuts(i,:) = best_cuts(i,:) + 1;\n            best_values(i,:) = domain(min_cut + 1);\n        end\n        \n        sum_best_value = sum_best_value + best_values(i,:);\n        \n    end\n    \n    dlmwrite(saveFileAddress, best_cuts);\n    sum_best_value\n    \nend\n\n", "meta": {"author": "HuanYin94", "repo": "map_compression", "sha": "3c126a5cc832bf51f0c313c6ad8aa58a2930312c", "save_path": "github-repos/MATLAB/HuanYin94-map_compression", "path": "github-repos/MATLAB/HuanYin94-map_compression/map_compression-3c126a5cc832bf51f0c313c6ad8aa58a2930312c/gurobi/before/graph_cut/DP_cut/DP_save_rows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5657217643765768}}
{"text": "function polygon_properties_test07 ( )\n\n%*****************************************************************************80\n%\n%% POLYGON_PROPERTIES_TEST07 tests POLYGON_EXPAND;\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    07 May 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 4;\n  v = [ ...\n    1.0, 1.0; ...\n    5.0, 1.0; ...\n    2.0, 4.0; ...\n    1.0, 3.0 ]';\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'POLYGON_PROPERTIES_TEST07\\n' );\n  fprintf ( 1, '  For a polygon:\\n' );\n  fprintf ( 1, '  POLYGON_EXPAND \"expands\" it by an amount H.\\n' );\n\n  h = 0.5;\n\n  r8mat_transpose_print ( 2, n, v, '  The polygon vertices:' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The expansion amount H = %g\\n', h );\n\n  w = polygon_expand ( n, v, h );\n\n  r8mat_transpose_print ( 2, n, w, '  The expanded polygon:' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polygon_properties/polygon_properties_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.5657217635894712}}
{"text": "function a=update_a(dvec,n,alpha)\n% a=update_a(dvec,n, alpha)\n% Computes update for a_ki (KxI) in variational approximation (Buntine & Jakulin\n% DCA 2006)\n% dvec: data - each column is one image (J x I)\n% n: (J x K x I)\n% alpha, beta: parameters of the Gamma distribution for latent h (1xK each)\n% J=#pixels\n% K=#components\n% I=#images.\n\n[j,k,i]=size(n);\n\ndvec_reshaped = reshape(dvec,j,1,i); % (Jx1xI)\natmp = sum(bsxfun(@times,dvec_reshaped,n),1); % (1xKxI)\na=bsxfun(@plus, squeeze(atmp), alpha'); % (KxI)", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/variational/update_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.565579810667994}}
{"text": "% op_CSIRemoveLipids.m\n%\n% Removes lipids from CSI data using L2 regularization. This minimizes the\n% equation norm(x - x_0, 2) + beta * norm(W'x, 2)\n%\n% INPUT:\n% MRSIStruct        = MRSI structure used in FID-A\n% lipidComponents   = number of lipid spectra in the lipid basis\n% lineWidthRange    = range of linewidth used for building lipid basis\n% ppmRange          = ppm range used in building lipid basis\n% beta              = regularization term\n% plotBasis         = plot basis spectra\n%                                                                                                                                                                                                                                                                          \n%\n% OUTPUT:\n% MRSIStruct        = MRSI structure with lipids removed\n\nfunction [MRSIStruct] = op_CSIRemoveLipids(MRSIStruct, basisArguments, plottingArguments) \n    arguments\n        MRSIStruct (1, 1) struct\n        basisArguments.lipidComponenets (1, 1) double = 1000\n        basisArguments.lineWidthRange (1, 2) double = [1 80]\n        basisArguments.lipidPPMRange (1, 2) double = [0.3 1.9000]\n        basisArguments.beta (1, 1) double = 1e-4\n        plottingArguments.plotBasis (1, 1) logical = false\n    end\n    % extract arguments from name value pairs\n    lipidComponents = basisArguments.lipidComponenets;\n    lineWidthRange = basisArguments.lineWidthRange;\n    lipidPPMRange = basisArguments.lipidPPMRange;\n    beta = basisArguments.beta;\n\n    spectraSize = getSizeFromDimensions(MRSIStruct, {'t'});\n\n    % calculate lipid basis used for L2 regularization\n    lipidBasis = createLipipBasis(MRSIStruct, lipidComponents, lineWidthRange, lipidPPMRange);\n    if(plottingArguments.plotBasis)\n        figure\n        plot(MRSIStruct.ppm, flip(real(lipidBasis),1));\n    end\n    % calculate solution from the basis\n    L2Solution = inv(eye(spectraSize) + beta * (lipidBasis * lipidBasis'));\n    \n    [MRSIStruct, prevPermute, prevShape] = reshapeDimensions(MRSIStruct, {'t'});\n    data = getData(MRSIStruct);\n    \n    data = L2Solution * data;\n    MRSIStruct = setData(MRSIStruct, data);\n    MRSIStruct = reshapeBack(MRSIStruct, prevPermute, prevShape);\nend\n\n% calculate lipid basis\nfunction lipidBasis = createLipipBasis(MRSIStruct, lipidComponents, lineWidthRange, lipidPPMRange)\n    spectralWidth = getSpectralWidth(MRSIStruct);\n\n    spectralPoints = getSizeFromDimensions(MRSIStruct, {'t'});\n    fidBasis = zeros(spectralPoints, lipidComponents);\n    \n    lipidStructure = load('Lip.mat', 'sysLip');\n    lipidStructure = lipidStructure.sysLip;\n    \n    for iSpectra = 1:lipidComponents\n        \n        fidBasis(:, iSpectra) = getRandomLipidFids(spectralPoints, spectralWidth, ...\n                                                  lineWidthRange, lipidPPMRange, ...\n                                                  lipidStructure);\n    end\n    lipidBasis = fftshift(fft(fidBasis, [], 1), 1);\nend\n\n% calculate the single lipid spectra for the basis\nfunction lipidFids = getRandomLipidFids(spectralPoints, spectralWidth, lineWidth, ...\n                                        lipidPPMRange, lipidSystem)\n    [randomLineWidth, randomPPM] = getRandomLineWidthandPPM(lineWidth, lipidPPMRange);\n    lipidSystem.shifts = randomPPM;\n\n    simulatedSignal = sim_onepulse(spectralPoints, spectralWidth, 3, randomLineWidth, lipidSystem);\n    simulatedSignal = op_complexConj(simulatedSignal);\n    simulatedSignal = addRandomPhase(simulatedSignal);\n    %simulatedSignal = scaleSpectra(simulatedSignal, randomPPM, lipidPPMRange);\n    lipidFids = simulatedSignal.fids;\nend\n\n\n% pick a random number from lower bounds and upper bounds\nfunction randomNumber = randomNumberInRange(lowerBounds, upperBounds)\n    difference = upperBounds - lowerBounds;\n    randomNumber = lowerBounds + difference * rand(1);\nend\n                \nfunction simulatedSignal = addRandomPhase(simulatedSignal)\n    sepctralPhase = randomNumberInRange(-180, 180);\n    simulatedSignal = op_addphase(simulatedSignal, sepctralPhase, 0, 4.65, 1);\nend\n\n% scale spectra based on a normal distribution. Signal near the center of lipid\n% range will be scaled high and signal near the edges scaled lower.\nfunction simulatedSignal = scaleSpectra(simulatedSignal, lipidPPM, lipidRange)\n    normalProbability = normpdf(lipidPPM, mean(lipidRange), diff(lipidRange)/4);\n    simulatedSignal = op_ampScale(simulatedSignal, normalProbability);\n    simulatedSignal = op_ampScale(simulatedSignal, 10);\n\nend\n\nfunction [randomLineWidth, randomPPM] = getRandomLineWidthandPPM(lineWidth, lipidPPMRange)\n    randomLineWidth = randomNumberInRange(lineWidth(1), lineWidth(2));\n    randomPPM = randomNumberInRange(lipidPPMRange(1), lipidPPMRange(2));\nend\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/processingTools/MRSI/op_CSIRemoveLipids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579722, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5655798030815208}}
{"text": "function pcut = addSinCosCuts(p)\n\npcut = p;\nif ~isempty(p.evalMap) \n    sin_ = [];\n    cos_ = [];\n    for i = 1:length(p.evalMap)\n        if isequal(p.evalMap{i}.fcn,'sin')\n            sin_ = [sin_;p.evalMap{i}.variableIndex p.evalMap{i}.computes];\n        elseif isequal(p.evalMap{i}.fcn,'cos')\n            cos_ = [cos_;p.evalMap{i}.variableIndex p.evalMap{i}.computes];\n        end\n    end\n    if ~isempty(sin_) && ~isempty(cos_) && ~isempty(intersect(sin_(:,1),cos_(:,1)))\n        for i = 1:size(sin_,1)\n            j = find(sin_(i,1)==cos_(:,1));\n            if ~isempty(j)\n                k1 = sin_(i,2);\n                k2 = cos_(j,2);\n                k3 = sin_(i,1);\n                % x_k1 and x_k2 rpresent sin and cos of x_k3\n                                                                 \n                % Construct the SOCP model for 1 >= x_k1^2 + x_k2^2\n                % i.e. norm([x_k1;x_k2]) <= 1\n                % i.e. [1;x_k1;x_k2] in socp cone\n                if 0\n                    F_structemp = spalloc(3,length(p.c)+1,5);\n                    F_structemp(:,1) = [1;0;0];\n                    F_structemp(2,1+k1) = 1;\n                    F_structemp(3,1+k2) = 1;\n                    K.f = 0;\n                    K.l = 0;\n                    K.s = 0;\n                    K.e = 0;\n                    K.q = 3;\n                    localModel1 = createNumericalModel(F_structemp,K);\n                    pcut = mergeNumericalModels(pcut,localModel1);    \n                end\n                \n                % We also add simple linear cuts, in case the lower bound\n                % solver doesn't support socps. FIX ME: Decide globally,\n                % but make sure it is consistent with stand-alone envelope\n                % y <= sqrt(2)-x, y>=-sqrt(2)+x, \n                % y <= sqrt(2)+x, y>=-sqrt(2)-x\n                % sqrt(2)-x-y, sqrt(2)+x-y, sqrt(2)-x+y, sqrt(2)+x+y\n                F_structemp = spalloc(4,length(p.c)+1,5);\n                F_structemp(:,1) = sqrt(2)*[1;1;1;1];\n                F_structemp(1,1+k1) = -1;\n                F_structemp(1,1+k2) = -1;\n                F_structemp(2,1+k1) = 1;\n                F_structemp(2,1+k2) = -1;\n                F_structemp(3,1+k1) = -1;\n                F_structemp(3,1+k2) = 1;\n                F_structemp(4,1+k1) = 1;\n                F_structemp(4,1+k2) = 1;\n                K.f = 0;\n                K.l = 4;\n                K.s = 0;\n                K.e = 0;\n                K.q = 0;\n                localModel2 = createNumericalModel(F_structemp,K);                               \n                pcut = mergeNumericalModels(pcut,localModel2);    \n            end\n        end\n    end    \nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/addSinCosCuts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5655798005526963}}
{"text": "% Find out how big the cliques are in an HHMM as a function of depth\n% (This is how we get the complexity bound of O(D K^{1.5D}).)\n\nif 0\nQsize = [];\nFsize = [];\nNclqs = [];\nend\n\nds = 1:15;\n\nfor d = ds\n  allQ = 1;\n  [intra, inter, Qnodes, Fnodes, Onode] = mk_hhmm_topo(d, allQ);\n  \n  N = length(intra);\n  ns = 2*ones(1,N);\n  \n  bnet = mk_dbn(intra, inter, ns);\n  for i=1:N\n    bnet.CPD{i} = tabular_CPD(bnet, i);\n  end\n  \n  if 0\n    T = 5;\n    dag = unroll_dbn_topology(intra, inter, T);\n    engine = jtree_unrolled_dbn_inf_engine(bnet, T, 'constrained', 1);\n    S = struct(engine);\n    S1 = struct(S.sub_engine);\n  end\n  \n  engine = jtree_dbn_inf_engine(bnet);\n  S = struct(engine);\n  J = S.jtree_struct;\n  \n  ss = 2*d+1;\n  Qnodes2 = Qnodes + ss;\n  QQnodes = [Qnodes Qnodes2];\n  \n  % find out how many Q nodes in each clique, and how many F nodes\n  C = length(J.cliques);\n  Nclqs(d) = 0;\n  for c=1:C\n    Qsize(c,d) = length(myintersect(J.cliques{c}, QQnodes));\n    Fsize(c,d) = length(myintersect(J.cliques{c}, Fnodes));\n    if length(J.cliques{c}) > 1 % exclude observed leaves\n      Nclqs(d) = Nclqs(d) + 1;\n    end\n  end\n  %pred_max_Qsize(d) = ceil(d+(d+1)/2);\n  pred_max_Qsize(d) = ceil(1.5*d);\n  \n  fprintf('d=%d\\n', d);\n  %fprintf('D=%d, max F = %d. max Q = %d, pred max Q = %d\\n', ...\n\t%  D, max(Fsize), max(Qsize), ceil(D+(D+1)/2));\n\t     \n  %histc(Qsize,1:max(Qsize)) % how many of each size?\nend % next d\n\n\nQ = 2;\npred_mass = ds.*(Q.^ds) + Q.^(ceil(1.5 * ds))\npred_mass2 = Q.^(ceil(1.5 * ds))\n\nfor d=ds\n  mass(d) = 0;\n  for c=1:C\n    mass(d) = mass(d) + Q^Qsize(c,d);\n  end\nend\n    \n\nif 0\n%plot(ds, max(Qsize), 'o-',  ds, pred_max_Qsize, '*--');\n%plot(ds, max(Qsize), 'o-',  ds, 1.5*ds, '*--');\n%plot(ds, mass, 'o-',  ds, pred_mass, '*--');\nD = 15;\n%plot(ds(1:D), mass(1:D), 'bo-',  ds(1:D), pred_mass(1:D), 'g*--', ds(1:D), pred_mass2(1:D), 'k+-.');\nplot(ds(1:D), log(mass(1:D)), 'bo-',  ds(1:D), log(pred_mass(1:D)), 'g*--', ds(1:D), log(pred_mass2(1:D)), 'k+-.');\n\ngrid on\nxlabel('depth of hierarchy')\ntitle('max num Q nodes in any clique vs. depth')\nlegend('actual', 'predicted')\n\n%previewfig(gcf, 'width', 3, 'height', 1.5, 'color', 'bw');\n%exportfig(gcf, '/home/cs/murphyk/WP/ConferencePapers/HHMM/clqsize2.eps', ...\n%          'width', 3, 'height', 1.5, 'color', 'bw');   \n\nend\n\n\nif 0\nfor d=ds\n  effnumclqs(d) = length(find(Qsize(:,d)>0));\nend\nds = 1:10;\nQs = 2:10;\nmaxC = size(Qsize, 1);\ncost = [];\ncost_bound = [];\nfor qi=1:length(Qs)\n  Q = Qs(qi);\n  for d=ds\n    cost(d,qi) = 0;\n    for c=1:maxC\n      if length(Qsize(c,d) > 0) % this clique contains Q nodes\n\tcost(d,qi) = cost(d,qi) + Q^Qsize(c,d)*2^Fsize(c,d);\n      end\n    end\n    %cost_bound(d,qi) = effnumclqs(d) * 8 * Q^(max(Qsize(:,d)));\n    cost_bound(d,qi) = (effnumclqs(d)*8) + Q^(max(Qsize(:,d)));\n  end\nend\n\nqi=2; plot(ds, cost(:,qi), 'o-',  ds, cost_bound(:,qi), '*--');\nend\n\n\nif 0\n% convert numbers in cliques into names\nfor d=1:D\n  Fdecode(Fnodes(d)) = d;\nend\nfor c=8:15\n  clqs = J.cliques{c};\n  fprintf('clique %d: ', c);\n  for k=clqs\n    if myismember(k, Qnodes)\n      fprintf('Q%d ', k)\n    elseif myismember(k, Fnodes)\n      fprintf('F%d ', Fdecode(k))\n    elseif isequal(k, Onode)\n      fprintf('O ')\n    elseif myismember(k, Qnodes2)\n      fprintf('Q%d* ', k-ss)\n    else\n      error(['unrecognized node ' k])\n    end\n  end\n  fprintf('\\n');\nend\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/dynamic/HHMM/hhmm_jtree_clqs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5655797999706423}}
{"text": "% Prabhakar. S\n% AE 110 Lab Assignment\n% Satellite Tracking Program\n% Satellite:  NOAA 12\n% Program Name elaz : Elevation-Azimuth being called by the program sts\n\n% Orbital Elements ready for degree to radians conversion!\n% Two Line Elements and the Epoch Data are obtained from the GUI Interface\n\nload variables.mat; % Loading the variables from the GUI Interface sts\nI2 = yoe;\t\t% Year of epoch\nJ2 = moe;\t\t\t% Month of epoch\n%h2 = hoe;       % Hour of epoch\n%m2 = mioe;       % Minute of epoch\n%K2 = doe + hoe/24 + mioe/(24*60);\t\t% Day of epoch\nK2=doe;\nzero=0; % For printing a single digit month or day preceeded by a zero.\n%ut=.08235372;\n%frac=.08235372; % fraction of the day from the TLE\n\n% This calculation is to find the Julian Date,\n% JD Fortran code written by Fliegel and Van Flandern [1968]\n% Handout by Dr. P\n\nJD = (367*I2 - (fix(7*(I2 + fix((J2 + 9)/12))/4)) + fix((275*J2)/9) + K2 + 1721013.5 + frac);\n\n%JD = (K2 - 32075 + round(1461 * (I2 + 4800 + (J2 -14)/12)/4 ...\n%+ 367* (J2 - 2 - (J2 - 14)/12*12)/12 - 3*((I2 + 4900 + (J2 - 14)/12)/100)/4)) ;\n% fprintf('\\n Two Line Elements Data - 28 Dec 2000, Time 11:30:00\\n');\n% fprintf(' The Julian Date is %f',JD);\n\n% Propagation begins\nI = yoe;\t\t\t\t\t\t\t\t% Year\nJ = moe;\t\t\t\t\t\t\t\t% Month\n%h = hoe;   \t\t\t\t   \t\t% Hour\n%m = mioe;     \t\t\t\t \t\t% Minute\n%K = doe + hoe/24 + mioe/(24*60);\t% Day\nK=doe;\n\nJD0 = (367*I - (fix(7*(I + fix((J + 9)/12))/4)) + fix((275*J)/9) + K + 1721013.5 + frac);\n\n%JD0 = (K - 32075 + round(1461 * (I + 4800 + (J -14)/12)/4 ...\n%+ 367 * (J - 2 - (J - 14)/12*12)/12 - 3*((I + 4900 + (J - 14)/12)/100)/4)) ;\n\nI3 = yoe;\t\t\t\t\t\t\t% Year\nJ3 = moe;\t\t\t\t\t\t\t% Month\n%h3 = hoe;       \t\t\t\t\t% Hour\n%m3 = mioe;       \t\t\t\t% Minute\n%K3 = (doe+pro) + h3/24 + m3/(24*60);\t% Day\nK3 = (doe+pro);\n\nJD1 = (367*I3 - (fix(7*(I3 + fix((J3 + 9)/12))/4)) + fix((275*J3)/9) + K3 + 1721013.5 + frac);\n\n%JD1 = K3 - 32075 + round(1461 * (I3 + 4800 + (J3 -14)/12)/4 ...\n%  + 367 * (J3 - 2 - (J3 - 14)/12*12)/12 - 3*((I3 + 4900 + (J3 - 14)/12)/100)/4);\n% Propagation ends here.\n\n% Propagation step Size\nstep = 5/(24*60); % right now for every 5 minutes\nj=1;\n\n\nfprintf('\\n\\t\\t\\t SATELLITE    TRACKING    SYSTEM  \\n');\nfprintf(' ---------------------------------------------------------------------------');\nfprintf('\\n\t\t\t\t             G r e g o r i a n   D a t e \\n');\nfprintf(' ---------------------------------------------------------------------------');\nfprintf('\\n  Julian Date      Azimuth     Elevation  Month/Day/Year Hour:Minute:Seconds\\n');\nfprintf(' ---------------------------------------------------------------------------');\n\nwhile JD0<JD1;   \n   \n% Declaring variables and initializing values \n\ndegtorad = pi/180;\t\t% Radians conversion factor\ni = incl*degtorad;\t\t% Inclination\nCapOmega = raan*degtorad;\t\t% Right Ascension of the Ascending Node - denoted by symbol Capital Omega\necc = e;\t\t\t\t\t% Eccentricity\nSmallOmega = aop*degtorad;\t\t\t\t\t\t% Argument of Periapsis - denoted by  small Omega \nMo = ma * degtorad;\t\t% Initial Mean anomaly\nn = revs;\t   \t\t% Mean Motion (revs/day)\nGP = 3.986e5;\t\t\t\t% Gravitational parameter - denoted by nu\na = 24000;\t\t\t\t\t% Semi-major Axis\n% a = (GP/n^2)^(1/3);\n% fprintf('Semi-major axis is computed to be :\\n',a);\n\nLatitude = 0 * degtorad;\nLongitude = 280 * degtorad;\t\nL = ((90*degtorad) - Latitude);\t\t\t\n\nWe = 6.300388097;\t\t% Angular velocity of planet Earth\nperturb = 98.9246096453622 * degtorad; % Perturbation due to the Oblateness \ntq = 2448621.5; % JD for \nQg = perturb + We * (JD0 - tq);\nQ = Qg + Longitude;\n\ntp = JD - Mo/n;\nM = n * (JD0 - tp);\n\nE = M;\t\t\t\t          \t\t% Use M for the first value of E\n\tf=M-E+ecc*sin(E);\t\t\t \t\t% Kepler's Equation\n\twhile abs(f)>0.00000001; \t\t% Loop for Kepler's equation begins\n\t\tf=M-E+ecc*sin(E);\t\t\t \t%\t\n\t\tfd=-1+ecc*cos(E);\t\t\t \t% \n\t\tE=E-f/fd;\t\t\t\t\t\t%\n\tend;\t\t\t\t\t\t\t \t\t% loop for Kepler's eqn ends here!\n\n\n% Computing true anomaly and radius\n\nTA=2*atan((((1+ecc)/(1-ecc))^0.5)*tan(E/2));\n    if TA<0;\n    \t  TA=2*pi+TA;\n    end;\n\nr=a*(1-ecc*cos(E)); % radius\n\n\n% Coordinate transformations\n\nadot = (-(3/2) * n * 1.0827e-3 * (6378.14/a)^2 * cos(i))/(1-ecc^2)^2;\nA = CapOmega + adot * (JD0 - JD);\nSmallOmega = SmallOmega + adot * (JD0 - JD);\n\nRseu = [0; 0; 6378.14];\nTxyz = [ cos(A) -sin(A) 0; sin(A) cos(A) 0; 0 0 1 ] * [ 1 0 0; 0 cos(i) -sin(i); 0 sin(i) cos(i)] * ...\n   [ cos(SmallOmega) -sin(SmallOmega) 0; sin(SmallOmega) cos(SmallOmega) 0; 0 0 1 ];\nTseu = [ cos(L) 0 -sin(L); 0 1 0; sin(L) 0 cos(L)] * [ cos(Q) sin(Q) 0; -sin(Q) cos(Q) 0; 0 0 1];\nruvw = [ (r * cos(TA)); (r * sin(TA)); 0 ];\nPseu = Tseu*(Txyz*ruvw) - Rseu;\nP = (Pseu(1)^2 + Pseu(2)^2 + Pseu(3)^2)^0.5;\n\nEl = (asin ( Pseu(3)/P ))/degtorad;\nAz = (atan2 ( Pseu(2), -Pseu(1)))/degtorad;\n\tif Az < 0;\n   \tAz = 360 + Az;\n   end;\n   \n%Loop begins here  %if El>0;\n\t\t\narray(j,1) = JD0;\narray(j,3) = Az;\narray(j,4) = El;\n%array(j,5) = cat(year,month,day);\nj = j+1;\n% loop ends here\n\nJD0 = JD0 + step;\n\t\t\t% Gregorian Date from Julian Date \n\t\t\t% This calculation is valid for any Julian Day Number including negative JDN and \n\t\t\t% produces a Gregorian date (or possibly a proleptic Gregorian date)\n\n\t\t\tZ = floor(JD0 - 1721118.5); % JD0 is the Julian Date in propagation \n\t\t\tR = (JD0 - 1721118.5 - Z);  % R is the fractional part of JD0\n\t\t\tG = (Z - .25);  \n\t\t\tA = (floor(G / 36524.25));  % Calculate the value of A which is the number of full centuries\n\t\t\tB = (A - (A / 4)); % The value of B is this number of days minus a constant\n\t\t\tyear = (floor((B+G) / 365.25)); % Calculate the value of Y, the year in a calendar whose years start on March 1\n\t\t\tC = (B + Z - floor(365.25 * year));  % Day count\n         month = (fix((5 * C + 456) / 153));  % Month\n         UT = (C - fix((153 * month - 457) / 5) + R); % Calculation for UTC\n         day = floor(UT);  % Gregorian Day\n                    \n\t\t\t\t\t\tif month > 12; \n\t\t      \t\t\tyear = year + 1 ;\n\t\t      \t\t\tmonth = month - 12; \n                  end; \n                  UT = UT - floor(UT);\n         UT = UT*24;\n         hr = floor(UT);   %  hour\n         UT = UT-floor(UT);\n\t      UT =UT* 60;\n\t      min = floor(UT);  % minute\n   \t   UT =UT- floor(UT);\n      \tUT =UT* 60;\n         secs = round(UT); % seconds \n         if secs==60;\n            min=min+1;\n            secs=0;\n         end;\n         % Gregorian Date conversion algorithm ends here\n         \n         % computations for printintg two digits in case year,month,day,min and secs is < 10\n         % (i.e) to print third month, 3 as 03 and day 5 as 05 etc..\n         ZERO=int2str(zero);\n\t\t\tMIN=int2str(min); % converting minute into a string\n\t\t\tif min <10;\n\t\t  \t\t\t MinNew=strcat(ZERO,MIN);\n                  min=MinNew;\n               else;\n                  min=MIN;\n               end;\n               \n         \tDAY=int2str(day); % converting DAY into a string\n\t\t\t\t if day <10;\n\t\t  \t\t\t\t DayNew=strcat(ZERO,DAY);\n                   day=DayNew;\n                else;\n                  day=DAY;\n         \t end;\n          HR=int2str(hr); % converting Hour into a string\n\t\t\t\t\tif hr <10;\n\t\t  \t\t\t\t HrNew=strcat(ZERO,HR);\n                   hr=HrNew;\n               else;\n                 \t hr=HR;\n\t\t          end;\n                \n                MONTH=int2str(month); % converting month into a string\n\t\t\t\t\t\tif month <10;\n\t\t\t  \t\t\t\t MonthNew=strcat(ZERO,MONTH);\n   \t                month=MonthNew;\n            \t   else\n         \t         month=MONTH;\n                  end;\n                  \n                 SECS=int2str(secs); % converting seconds into a string\n\t\t\t\t\t\tif secs <10;\n\t\t\t  \t\t\t\t SecsNew=strcat(ZERO,SECS);\n   \t                secs=SecsNew;\n            \t   else\n         \t         secs=SECS;\n\t\t\t         end;\n\n         % computations for printing two digits ends here!\n             \n         if El>0; \n            fprintf('\\n %f | %f | %f |  %s/%s/%4d  |  %s:%s:%s  |',JD0, Az, El, month,day,year, hr,min,secs);\n            %plot(El,Az);\n         end;   \nend;\nfprintf('\\n ---------------------------------------------------------------------------\\n');\nfprintf('\\n\\t\\t\\t       End of Output\\!!! \\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/982-gui-based-satellite-tracking-system/elaz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5655797949129934}}
{"text": "function [x] = tt_meshgrid(varargin)\n%Analogue of the meshgrid function for the TT-format\n%   X = TT_MESHGRID(A,B,C,...) Computes the meshgrid based on \"1d\"\n%       representations \n%   X = TT_MESHGRID(A) Computes the meshgrid based on the cell array A of\n%       the representations\n%   X = TT_MESHGRID(T,D) Computes the d-dimensional meshgrid, using T as a\n%       one-dimensional grid\nif ( numel(varargin) == 2 )\n    if ( ismatrix(varargin{2}) )\n        d = varargin{2};\n        t = varargin{1};\n        z = cell(d,1);\n        for i = 1:d\n            z{i} = t;\n        end\n    else\n        z = varargin{1};\n    end\nelse\n    z = varargin{1}; \nend\nif ~iscell(z)\n    z = varargin;\nend\nd = numel(z);\nx = cell(d,1);\ne = cell(d,1);\nfor i = 1:d\n    e{i} = tt_ones(size(z{i}));\nend\nfor i = 1:d\n    v = z{i};\n    for j = i-1:-1:1\n        v = kron(e{j},v);\n    end\n    for j = i+1:d\n        v = kron(v,e{j});\n    end\n    x{i} = v;\nend\nend", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/core/tt_meshgrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5655797943309393}}
{"text": "%% MTEX check calcEBSD and calcODF\n% check for the dependency between the number of sample\n% orientations and the error between the estimated and the \n% true ODF\n\nfor i = 1:5\n\n  ebsd = discreteSample(SantaFe,10^i);\n\n  odf = calcODF(ebsd);\n\n  e(i) = calcError(odf,SantaFe,'resolution',2.5*degree);\n  \nend\n\nplot(e)\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_ebsd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5655797892732903}}
{"text": "function g = gaussianPriorGradient(prior, x)\n\n% GAUSSIANPRIORGRADIENT Gradient wrt x of the log Gaussian prior.\n\n% PRIOR\n\n% Compute gradient of prior\ng = -prior.precision*x;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/prior/gaussianPriorGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5655797785759383}}
{"text": " function[M1,M2,M3] = integrate_vf(k,w,f,v)\n      M1   = (k*sum(v .* w .* f));    % Number density\n      M2   = (k*sum((v .^2 ) .* w .* f));   % Macrospic moment in x\n      M3   = (k*sum(1/2*( v .*abs(v).^2 ).* w .* f)); % Energy Density\n end", "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/integrate_vf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.5655776917259042}}
{"text": "%  Figure 10.27      Feedback Control of Dynamic Systems, 5e\n%                        Franklin, Powell, Emami\n%\n%  fig10_27.m is a script to generate Fig. 10.27, the      \n%  step response of the collocated\n%  design for the satellite with PD compensation\nclf;\nm=[1, .1]; k0=[0, .091] ; d0=[0, .0036]; k1=[0, .4];\n[f,g,h,j]=twomass(m,k0,d0); [f1,g,h,j] = twomass(m,k1,d0);\nh1=[0, 0, 1, 0];\n\nnc1=0.25*[2, 1];\ndc1=[1/40, 1];\n\n[ac,bc,cc,dc]=tf2ss(nc1, dc1);\n[aol,bol,col,dol]= series(ac, bc,cc,dc,f,g,h1,j);\n[acl]=aol-bol*col;\nccl2=[0*cc h]\n[aol1,bol1,col1,dol1] = series(ac,bc,cc,dc,f1,g,h1,j);\nacl1=aol1-bol1*col1;\nt=0:.3:50;\nsys1=ss(acl,bol,col,dol);\nstep(sys1,t);\nhold on; \ngrid;\nsys2=ss(acl1,bol1,col1,dol1);\nstep(sys2,t);\ntitle('Closed-loop step response for D_5(s)G_{co}(s).')\n", "meta": {"author": "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_27.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5655743370775058}}
{"text": "function tone=note(keynum, dur)\n\nfs=11025;\ntt = 0:(1/fs):dur;\n\n%  This generates white noise for whatever duration specified..  good snare\n%  sound with the right envelope, but matlab developed timing problems with this.  I'll probably\n%  try to get these running sometime after lab\n if keynum == 2\n     tone=rand(1,length(tt));\n     return;\n end\n\n%generates rests\nif keynum == 0 \n%for kk = 1:length(tt)\n    tone([1:length(tt)]) = 0;\n    %end\nreturn;\nend\n\n\n%adding these octaves rounded out the sound.  \nfreq=440*2^((keynum-49)/12);\nfreq3=freq*3;\nfreq5=freq*5;\nfreq9=freq*9;\nfreq7=freq*7;\ntone1 = .75*sin(2*pi*freq*tt);\n tone3 = .65*sin(2*pi*freq3*tt);\n tone5=.5*sin(2*pi*freq5*tt);\n tone9 = .222*sin(2*pi*freq9*tt);\n tone7 = .12*sin(2*pi*freq7*tt);\n tone12= 1*sin(2*pi*freq*12*tt);\n\ntone=tone1+tone3+tone5+tone7+tone9;%+tone12;\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/8442-theme-from-super-mario-brothers-song/note.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5655743309939018}}
{"text": "function calpak_test336 ( )\n\n%*****************************************************************************80\n%\n%% CALPAK_TEST336 tests MONTH_LENGTH_EG_CIVIL.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    26 March 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n_test = 2\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CALPAK_TEST336\\n' );\n  fprintf ( 1, '  For the Egyptian Civil calendar,\\n' );\n  fprintf ( 1, '  MONTH_LENGTH_EG_CIVIL returns month lengths.\\n' );\n\n  y_test(1) = 3;\n  y_test(2) = 4;\n\n  for i_test = 1 : n_test\n\n    y = y_test(i_test);\n    sy = y_to_s_eg_civil ( y );\n    months = year_length_months_eg_civil ( y );\n    days = year_length_eg_civil ( y );\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  %d\\n', y );\n    fprintf ( 1, '  %s\\n', sy );\n    fprintf ( 1, '  Year length in months = %d\\n', months );\n    fprintf ( 1, '  Year length in days = %d\\n', days );\n    fprintf ( 1, '\\n' );\n\n    for m = 1 : months\n      month_name = month_to_month_name_eg_civil ( m );\n      fprintf ( 1, '  %10s  %2d\\n', month_name, month_length_eg_civil ( y, m ) );\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/calpak/calpak_test336.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.5655643707290924}}
{"text": "function [ a, info ] = dpofa ( a, lda, n )\n\n%*****************************************************************************80\n%\n%% DPOFA factors a real symmetric positive definite matrix.\n%\n%  Discussion:\n%\n%    DPOFA is usually called by DPOCO, but it can be called\n%    directly with a saving in time if RCOND is not needed.\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%    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, real A(LDA,N), the symmetric matrix to be  factored.  Only the \n%    diagonal and upper triangle are used.\n%\n%    Input, integer LDA, the leading dimension of the array A.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Output, real A(LDA,N), an upper triangular matrix R so that A = R'*R\n%    where R' is the transpose.  The strict lower triangle is unaltered.\n%    If INFO /= 0, the factorization is not complete.\n%\n%    Output, integer INFO, error flag.\n%    0, for normal return.\n%    K, signals an error condition.  The leading minor of order K is not \n%    positive definite.\n%\n  for j = 1 : n\n\n    s = 0.0;\n\n    for k = 1 : j-1\n      t = a(k,j) - ddot ( k-1, a(1:k-1,k), 1, a(1:k-1,j), 1 );\n      t = t / a(k,k);\n      a(k,j) = t;\n      s = s + t * t;\n    end\n\n    s = a(j,j) - s;\n\n    if ( s <= 0.0 )\n      info = j;\n      return\n    end\n\n    a(j,j) = sqrt ( s );\n\n  end\n\n  info = 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/linpack_d/dpofa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5655643689637729}}
{"text": "function hand_plot ( )\n\n%*****************************************************************************80\n%\n%% HAND_PLOT plots the hand data.\n%\n%  Discussion:\n%\n%     This program assumes that the file 'HAND_NODES.TXT' is available.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    13 April 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Cleve Moler,\n%    Numerical Computing with MATLAB,\n%    SIAM, 2004,\n%    ISBN13: 978-0-898716-60-3,\n%    LC: QA297.M625. \n%\n\n%\n%  Read the data.\n%\n  xy = load ( 'hand_nodes.txt' );\n%\n%  Make XY an array of column vectors.\n%\n  xy = xy';\n%\n%  Repeat the first column at the end so the polygon closes.\n%\n  xy = [ xy, [ xy(:,1) ] ];\n%\n%  Clear the graphics frame.\n%\n  clf\n\n  plot ( xy(1,:), xy(2,:), 'Color', 'r', 'LineWidth', 2 );\n  hold on;\n  plot ( xy(1,:), xy(2,:), 'b.', 'MarkerSize', 15 );\n  axis equal\n  grid on\n  title ( 'Hand data and straight line interpolant' )\n\n  hold off\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hand_data/hand_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239957834734, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.5655643593706412}}
{"text": "function [d pred] = dag_sp(A,u,varargin)\n% DAG_SP Compute the weighted single source shortest path problem.\n%\n% The DAG shortest path algorithm for the single source shortest path\n% problem only works on directed acyclic-graphs (DAGs).  \n%\n% If the graph is not a DAG, the results are undefined.  In the future, the\n% function may throw an error if the graph is not a DAG.\n%\n% See the shortest_paths function for calling information.  This function \n% just calls shortest_paths(...,struct('algname','dag'));\n%\n% This algorithm works on weighted directed acyclic graphs.\n% The runtime is O(V+E)\n%\n% ... = clustering_coefficients(A,...) takes a set of\n% key-value pairs or an options structure.  See set_matlab_bgl_options\n% for the standard options. \n%    There are no additional options for this function.\n%\n% Example:\n%    load graphs/kt-3-7.mat\n%    dag_sp(A,1)\n%\n% See also SHORTEST_PATHS\n\n% David Gleich\n% Copyright, Stanford University, 2006-2008\n\n%% History\n%  2006-04-23: Initial version\n%  2008-10-07: Changed options parsing\n%%\n\nalgname = 'dag';\nif ~isempty(varargin), \n    options = merge_options(struct(),varargin{:}); \n    options.algname= algname;\nelse options = struct('algname',algname); \nend\n\n[d pred] = shortest_paths(A,u,options);\n\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/matlab_bgl/dag_sp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5655643545740752}}
{"text": "function c=ref_gdgt(f,g,a,M,c_t,c_f,c_w)\n%REF_GDGT  Reference generalized DGT\n%   Usage:  c=ref_dgtiv(f,g,a,M,c_t,c_f,c_w);\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\nN=L/a;\n\nF=zeros(L,M*N);\n\nl=(0:L-1).';\n\nfor n=0:N-1\t   \n  for m=0:M-1\n    F(:,M*n+m+1)=exp(2*pi*i*(m+c_f)*(l+c_t)/M).*circshift(g,n*a+c_w);\n  end;\nend;\n\nc=F'*f;\n\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_gdgt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5655392202833124}}
{"text": "% Copyright 2014 Jason Heeris, jason.heeris@gmail.com\n% \n% This file is part of the gammatone toolkit, and is licensed under the 3-clause\n% BSD license: https://github.com/detly/gammatone/blob/master/COPYING\nfunction test_gammatonegram()\n    % Need:\n    %  wave\n    %  fs\n    %  window_time\n    %  hop_time\n    %  channels\n    %  f_min\n    %  f_max\n    \n    % Need to mock out:\n    %  make_erb_filters output (elide)\n    %  centre_freqs (elide)\n    %  erb_filterbank (depends on X, SR, N, FMIN)\n    \n    % Ensure reproducible tests\n    rand('state', [3 1 4 1 5 9 2 7]);\n    \n    gammatonegram_inputs = {\n        'sawtooth_01', sawtooth(2*pi*10100*[0:22050 - 1]'/22050, 0.5), 22050, 0.025, 0.010, 64, 50; ...\n        'sin220_01'  , sin(2*pi*220*[0:4800 - 1]'/48000), 48000, 0.01, 0.01, 64, 50; ...\n        'sin220_02'  , sin(2*pi*220*[0:4800 - 1]'/48000), 48000, 0.025, 0.01, 32, 50; ...\n        'rand_01'    , rand([1, 4410 - 1]), 44100, 0.02, 0.015, 128, 500; ...\n        'rand_02'    , rand([1, 9600 - 1]), 96000, 0.01, 0.005, 256, 20; ...\n        'rand_03'    , rand([1, 4800 - 1]), 48000, 0.01, 0.010, 256, 20; ...\n    };\n    \n    % Mocked intermediate results for unit testing\n    gammatonegram_mocks = {};\n    \n    % Actual results\n    gammatonegram_results = {};\n    \n    for tnum=1:size(gammatonegram_inputs)(1)\n        [name, wave, fs, twin, thop, chs, fmin] = deal(gammatonegram_inputs{tnum,:});\n        res = gammatonegram( ...\n                  wave, ...\n                  fs, ...\n                  twin, ...\n                  thop, ...\n                  chs, ...\n                  fmin, ...\n                  0, % fmax is ignored\n                  0 % Don't use FFT method\n              );\n    \n        % This is for mocking the output of the equivalent Python functions\n        nwin     = round(twin * fs);    \n        hopsamps = round(thop * fs);\n        f_coefs  = flipud(MakeERBFilters(fs, chs, fmin));\n        x_f      = ERBFilterBank(wave, f_coefs);\n        x_e      = [x_f .^ 2];\n        x_e_cols = size(x_e, 2);\n        ncols    = 1 + floor((x_e_cols - nwin) / hopsamps);\n       \n        % Mock out the ERB filter functions too\n        fcoefs = flipud(MakeERBFilters(fs, chs, fmin));\n        erb_fb_output = ERBFilterBank(wave, fcoefs);\n    \n        gammatonegram_mocks(tnum, :) = { ...\n            erb_fb_output, ...\n            x_e_cols ...\n        };\n    \n        gammatonegram_results(tnum, :) = { ...\n            res, ...\n            nwin, ...\n            hopsamps, ...\n            ncols ...\n        };\n    \n    end;\n    \n    results_file = fullfile('..', 'tests', 'data', 'test_gammatonegram_data.mat');\n    save(results_file, 'gammatonegram_inputs', 'gammatonegram_mocks', 'gammatonegram_results');\nend;\n", "meta": {"author": "detly", "repo": "gammatone", "sha": "0626328ef7c31d3b33214db2fdcd52e8601eb4c5", "save_path": "github-repos/MATLAB/detly-gammatone", "path": "github-repos/MATLAB/detly-gammatone/gammatone-0626328ef7c31d3b33214db2fdcd52e8601eb4c5/test_generation/test_gammatonegram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.565539214366141}}
{"text": "function c = long2intval(C)\n%LONG2INTVAL  Conversion long to intval (with correct rounding)\n%\n%  c = long2intval(C)\n%\n\n% written  12/30/98     S.M. Rump\n% modfied  02/09/00     S.M. Rump  rounding unchanged after use\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 07/31/05     S.M. Rump  header corrected\n% modified 11/20/05     S.M. Rump  fast check for rounding to nearest\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  e = 1e-30;\n  if 1+e==1-e                           % fast check for rounding to nearest\n    rndold = 0;\n  else\n    rndold = getround;\n    setround(0)\n  end\n\n  INTLAB_LONG_BETA = getappdata(0,'INTLAB_LONG_BETA');\n  INTLAB_LONG_LOGBETA = getappdata(0,'INTLAB_LONG_LOGBETA');\n  INTLAB_LONG_ERROR = getappdata(0,'INTLAB_LONG_ERROR');\n\n  % extra treatment of zero component\n  indexzero = ( C.exponent==-inf );\n\n  n = size(C.mantissa,1);\n  % take maximum first 80 bits\n  precC = size(C.mantissa,2);\n  p = min( precC , ceil(80/INTLAB_LONG_LOGBETA)+1 );\n  if INTLAB_LONG_ERROR\n    if p<precC\n      C.error = errorupdate( 1 , C.error , 0 , ...\n                  1 , any(C.mantissa(:,p+1:precC)~=0,2) , C.exponent-precC );\n    end\n    Cerr = C.error.mant .* INTLAB_LONG_BETA.^(C.error.exp-C.exponent+p);\n  else\n    Cerr = 0;\n  end\n\n  factor = ( INTLAB_LONG_BETA.^(-p:-1) )';\n  exppos = ( C.exponent>=0 );\n  expneg = ~exppos;\n  E = floor( 600/INTLAB_LONG_LOGBETA );\n  F = INTLAB_LONG_BETA ^ E;\n\n  Cmantp = C.mantissa(:,p);\n  setround(-1)\n  C.mantissa(:,p) = Cmantp - Cerr;\n  cinf = C.mantissa(:,p:-1:1) * factor ;\n  if any(exppos)\n    cinf(exppos) = ( cinf(exppos)*F ) .* ...\n                      ( INTLAB_LONG_BETA.^(C.exponent(exppos)-E) );\n  end\n  if any(expneg)\n    cinf(expneg) = ( cinf(expneg)/F ) .* ...\n                      ( INTLAB_LONG_BETA.^(C.exponent(expneg)+E) );\n  end\n\n  setround(1)\n  C.mantissa(:,p) = Cmantp + Cerr;\n  csup = C.mantissa(:,p:-1:1) * factor ;\n  if any(exppos)\n    csup(exppos) = ( csup(exppos)*F ) .* ...\n                      ( INTLAB_LONG_BETA.^(C.exponent(exppos)-E) );\n  end\n  if any(expneg)\n    csup(expneg) = ( csup(expneg)/F ) .* ...\n                      ( INTLAB_LONG_BETA.^(C.exponent(expneg)+E) );\n  end\n  if INTLAB_LONG_ERROR & any(indexzero)\n    csup(indexzero) = C.error.mant(indexzero) .* ...\n                        INTLAB_LONG_BETA.^C.error.exp(indexzero);\n    cinf(indexzero) = - csup(indexzero);\n  end\n\n  c = hull( C.sign.*cinf , C.sign.*csup );\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/long/@long/long2intval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5655392137420969}}
{"text": "function [ft3] = m32ft3(m3)\n% Convert volume from cubic meters to cubic feet. \n% Chad Greene 2012\nft3 = m3*35.314666721;", "meta": {"author": "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/m32ft3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5655392096970566}}
{"text": "function [Rsp,U,V]=standardUVBeamPattern(T,xyPoints,normVals,Sigma,lineParams,bounds,numPoints)\n%%STANDARDUVBEAMPATTERN Compute the beam pattern of a tapered array as a\n%                       function of direction given in terms of direction\n%                       cosines for a narrowband linear or planar array.\n%                       The beam pattern is just the sum of all of the\n%                       tapered elements taken for signals in different\n%                       directions. This function can output the response\n%                       over all (-1,+1) u-v values or in a rectangular\n%                       subset. It can also output a linear cut across the\n%                       values.\n%\n%INPUTS: T The numSubarraysXnumElements tapering matrix of the array. If\n%          there are no subarrays, then this can be a numElementsX1\n%          vector of weights for every element. The weights can be complex,\n%          which means that difference beams can be formed and steering can\n%          be taken into account. If an empty matrix is passed, then it is\n%          assumed that no tapering is used so T will be a 1XnumElements\n%          vector of all ones.\n% xyPoints A 1XNumDim or 2XnumDim matrix of the [x;y] locations of the\n%          points in the linear or planar array. The units of the distances\n%          are in terms of wavelengths for the narrowband model.\n% normVals This indicates how the sum beam value should be normalized.\n%          Possible values are:\n%          'ArrayGain' Return the ratio of the output power to the noise\n%                      power. This is the default if this parameter is\n%                      omitted or an empty matrix is passed.\n%          'NormPowGain' Return the power of the output normalized such\n%                        that the highest value is 1.\n%          'AbsPowGain' Return the power of the output. This assumes that\n%                       the tapering matrix contains the true gain or loss\n%                       values for the tapering and is thus not scaled by\n%                       any constant value.\n%          'NormRealVal' Display the normalized real component of the\n%                       output value. It is normalized such that the\n%                       largest absolute value is one. Note that this is\n%                       not squared, so it corresponds to an output\n%                       voltage, not a power.\n%           'RawOutput' Provide the raw sum beam output.\n%   Sigma If the array gain is desired (normVals='ArrayGain'), then this\n%         parameter is used. This is the numElsXnumEls covariance matrix of\n%         the noise at the individual elements in the array. If this\n%         parameter is omitted or an empty matrix is passed, then the\n%         identity matrix will be used.\n% lineParams If xyPoints is a 2XnumDims set of points (for a planar array),\n%         then if this parameter is provided and is not an empty matrix,\n%         Rsp will be a 1D cut across u and v values rather than all u and\n%         v values. The equation for the line along with the beam pattern\n%         will be evaluated is v=lineParams.intercept+lineParams.slope*u if\n%         the value lineParams.vIndep=false or the vIndep component of\n%         lineParams is omitted. Otherwise, the line is\n%         u=lineParams.intercept+lineParams.slope*v .\n%  bounds A 2X1 (or 1X2) or a 4X1 (or 1X4) vector with the bounds in u and\n%         v of the plot. For 1-dimensional plots, which are the case if\n%         xyPoints is 1XnumDim or lineParams is provided and xyPoints is\n%         2XnumDim, then bounds=[minVal;maxVal] for the independent\n%         variable. For two-dimensional plots, then\n%         bounds=[minU;maxU;minV;maxV]. If this parameter is omitted or an\n%         empty matrix is passed, then [-1;1;-1;1] is used to go over all\n%         possible values in u and v (or just u for a 1D plot).\n% numPoints A parameter determining the size of the output matrix. For 1D\n%         plots, Rsp is numPointsX1. For 2D plots, Rsp is\n%         numPointsXnumPoints. If this parameter is omitted or an empty\n%         matrix is passed, then a default of numPoints=125 points is used.\n%\n%OUTPUTS: Rsp The array beam pattern over the selected region, normalized\n%             as specified. The value in entry Rsp(i,j) corresponds to the\n%             U and V values U(i,j) and V(i,j). For a 1D response for a\n%             linear array, Rsp(i) corresponds to U(i) and if xyPoints is\n%             2XnumDims, V(i) is the corresponding v value. The value of\n%             Rsp for points outside of the visible region (u^2+v^2>1)\n%             is set to zero.\n%           U A matrix of points corresponding to the u values of the\n%             responses in Rsp.\n%           V A matrix of points corresponding to the v values of the\n%             responses in Rsp. For 1D responses,\n%\n%The idea of a beam pattern for a narrowband array is discussed in Chapter\n%2.2 of [1]. The array gain is discussed in Chapter 2.6.2.\n%\n%EXAMPLE 1:\n%Here, we find the array gain beam pattern of a 20 element 1D linear array\n%with Taylor tapering and half-wavelength element spacing. When consdiering\n%the array gain, it does not matter that the elements are not provided\n%centered about the origin. However, the points must be centered to get the\n%proper tapering values from the TaylorLinearTapering function.\n% xPoints=0:0.5:9.5;\n% xPoints=xPoints-mean(xPoints);\n% nBar=3;\n% sidelobedB=-25;\n% T=TaylorLinearTapering(nBar,sidelobedB,xPoints).';\n% [Rsp,U]=standardUVBeamPattern(T,xPoints);\n% figure(1)\n% clf\n% plot(U,10*log10(Rsp),'linewidth',2)\n% axis([-1 1 -30 15])\n% axis square\n% h1=xlabel('u');\n% h2=ylabel('Array Gain');\n% title('Array Power Gain in Decibels')\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%In this example, we plot the normalized power gain of a 2D hexagonal array\n%without any tapering.\n% xyPoints=getShaped2DLattice([7;14],'hexagonal');\n% [Rsp,U,V]=standardUVBeamPattern([],xyPoints,'NormPowGain');\n% figure(2)\n% clf\n% surface(U,V,10*log10(Rsp),'EdgeColor','None')\n% axis([-1 1 -1 1 -40 0])\n% caxis([-40 0])\n% colormap(jet(256))\n% colorbar()\n% view(45,45)\n% light()\n% h1=xlabel('u');\n% h2=ylabel('v');\n% h3=zlabel('Array Gain');\n% title('Array Power Gain in Decibels')\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% set(h3,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%EXAMPLES 3:\n%In this example, we plot the difference pattern of a circular array.\n%First, we plot the normalized real value of the pattern (the pattern is\n%real anyway so this is not an issue) in 2D and then we take 1D cuts of it\n%in two different directions. Bayliss tapering are used to obtain the\n%difference pattern.\n% xyPoints=getShaped2DLattice([30;30],'circular');\n% sidelobedB=-30;\n% N=17;\n% T=BaylissTapering(sidelobedB,N,xyPoints).';\n% [Rsp,U,V]=standardUVBeamPattern(T,xyPoints,'NormRealVal');\n% figure(3)\n% clf\n% surface(U,V,Rsp,'EdgeColor','None')\n% axis([-1 1 -1 1 -1 1])\n% caxis([-1 1])\n% colormap(jet(256))\n% colorbar()\n% view(45,10)\n% light()\n% h1=xlabel('u');\n% h2=ylabel('v');\n% h3=zlabel('Real Response');\n% title('Array Difference  Beam Pattern')\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% set(h3,'FontSize',14,'FontWeight','bold','FontName','Times')\n% \n% %Now, we take a cut along to v=0 line.\n% lineParams=[];\n% lineParams.intercept=0;\n% lineParams.slope=0;\n% lineParams.vIndep=false;\n% \n% [Rsp,U]=standardUVBeamPattern(T,xyPoints,'NormRealVal',[],lineParams);\n% figure(4)\n% clf\n% plot(U,Rsp,'linewidth',2)\n% h1=xlabel('u');\n% h2=ylabel('Real Response');\n% title('Array Difference Beam Pattern')\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% %And here we take a cut along the u=0 line.\n% lineParams.vIndep=true;\n% \n% [Rsp,~,V]=standardUVBeamPattern(T,xyPoints,'NormRealVal',[],lineParams);\n% figure(5)\n% clf\n% plot(V,Rsp,'linewidth',2)\n% h1=xlabel('v');\n% h2=ylabel('Real Response');\n% title('Array Difference Beam Pattern')\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 4:\n%This is an example of using elements of a circular array with a fixed\n%Taylor tapering that have been broken into subarrays. We then try to form\n%the best approximation to a Bayliss difference pattern modifying only the\n%subarray outputs. We also demonstrate how steering can be used to move the\n%difference beam away from the center of the array.\n% xyPoints=getShaped2DLattice([30;30],'circular');\n% numEls=size(xyPoints,2);\n% %Fixed element-level tapering.\n% sidelobedB=-30;\n% nBar=4;\n% g=TaylorTapering(nBar,sidelobedB,xyPoints);\n% %It is assumed the disjoint subarrays can be formed (no adjacency matrix\n% %used).\n% numLevels=3;\n% N=17;\n% T=double(findBaylissSubarrays(xyPoints,numLevels,sidelobedB,N));\n% %We now apply the tapering to the matrix\n% T=bsxfun(@times,T,g.');\n% \n% %The desired element-level tapering\n% g=BaylissTapering(sidelobedB,N,xyPoints);\n% \n% %Next, we try to find the best subarray weights to approximate the desired\n% %tapering. We specifically add a null at the boresight.\n% g=findSubarrayWeights(T,g,ones(numEls,1));\n% \n% %Apply the tapering to the elements\n% T=bsxfun(@times,g,T);\n% \n% %We also steer the array off boresight to u0. This is element-level\n% %steering.\n% u0=[-0.5;0.5];\n% D=diag(exp(1j*2*pi*sum(bsxfun(@times,xyPoints,u0),1)));\n% T=T*D;\n% \n% [Rsp,U,V]=standardUVBeamPattern(T,xyPoints,'NormRealVal');\n% figure(3)\n% clf\n% surface(U,V,Rsp,'EdgeColor','None')\n% axis([-1 1 -1 1 -1 1])\n% caxis([-1 1])\n% colormap(jet(256))\n% colorbar()\n% view(45,10)\n% light()\n% h1=xlabel('u');\n% h2=ylabel('v');\n% h3=zlabel('Real Response');\n% title('Array Difference  Beam Pattern')\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% set(h3,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%REFERENCES:\n%[1] H. L. Van Trees, Optimum Array Processing. New York: Wiley-\n%    Interscience, 2002.\n%\n%August 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDim=size(xyPoints,1);\nnumEls=size(xyPoints,2);\n\nif(isempty(T))\n   T=ones(1,numEls);\nend\n\nif(nargin<7||isempty(numPoints))\n   numPoints=125; \nend\n\nif(nargin<6||isempty(bounds))\n    if(numDim==1)\n        bounds=[-1;1];\n    else\n        bounds=[-1;1;-1;1];\n    end\nend\n\nif(nargin<5||isempty(lineParams))\n    if(numDim>1)    \n        %If a 2D plot is desired.\n        uVals=linspace(bounds(1),bounds(2),numPoints);\n        vVals=linspace(bounds(3),bounds(4),numPoints);\n        [U,V]=meshgrid(uVals,vVals);\n        Rsp=zeros(numPoints,numPoints);\n        \n        if(isvector(T))\n            for curVal=1:(numPoints*numPoints)\n                u=[U(curVal);V(curVal)];\n                if(u'*u>1)\n                    continue;\n                end\n\n                Rsp(curVal)=T*exp(-1j*2*pi*sum(bsxfun(@times,xyPoints,u),1)).';\n            end\n        else\n            for curVal=1:(numPoints*numPoints)\n                u=[U(curVal);V(curVal)];\n                if(u'*u>1)\n                    continue;\n                end\n\n                Rsp(curVal)=sum(sum(T*exp(-1j*2*pi*sum(bsxfun(@times,xyPoints,u),1)).'));\n            end\n        end\n    else\n        %If a 1D plot is required.\n        U=linspace(bounds(1),bounds(2),numPoints)';\n        V=[];\n        \n        if(isvector(T))\n            Rsp=zeros(numPoints,1);\n            for curVal=1:numPoints\n                if(abs(U(curVal))>1)\n                    continue;\n                end\n\n                Rsp(curVal)=T*exp(-1j*2*pi*xyPoints*U(curVal)).';\n            end\n        else\n            Rsp=zeros(numPoints,1);\n            for curVal=1:numPoints\n                if(abs(U(curVal))>1)\n                    continue;\n                end\n\n                Rsp(curVal)=sum(T*exp(-1j*2*pi*xyPoints*U(curVal)).');\n            end\n        end\n    end\nelse\n    %If a 1D cut across the 2D surface is desired. The\n    slope=lineParams.slope;\n    intercept=lineParams.intercept;\n    if(isfield(lineParams,'vIndep'))\n        vIndep=lineParams.vIndep;\n    else\n        vIndep=false;\n    end\n    \n    if(vIndep==false)\n        %The independent variable is u.\n        U=linspace(bounds(1),bounds(2),numPoints)';\n        V=zeros(numPoints,1);\n        Rsp=zeros(numPoints,1);\n        \n        if(isvector(T))\n            for curVal=1:numPoints\n                V(curVal)=intercept+slope*U(curVal);\n                uVec=[U(curVal);V(curVal)];\n\n                if(uVec'*uVec>1)\n                    continue;\n                end\n\n                Rsp(curVal)=T*exp(-1j*2*pi*sum(bsxfun(@times,xyPoints,uVec),1)).';\n            end\n        else\n            for curVal=1:numPoints\n                V(curVal)=intercept+slope*U(curVal);\n                uVec=[U(curVal);V(curVal)];\n\n                if(uVec'*uVec>1)\n                    continue;\n                end\n\n                Rsp(curVal)=sum(sum(T*exp(-1j*2*pi*sum(bsxfun(@times,xyPoints,uVec),1)).'));\n            end\n        end\n    else\n        %The independent variable is v.\n        V=linspace(bounds(1),bounds(2),numPoints)';\n        U=zeros(numPoints,1);\n        Rsp=zeros(numPoints,1);\n        \n        if(isvector(T))\n             for curVal=1:numPoints\n                U(curVal)=intercept+slope*V(curVal);\n                uVec=[U(curVal);V(curVal)];\n\n                if(uVec'*uVec>1)\n                    continue;\n                end\n\n                Rsp(curVal)=T*exp(-1j*2*pi*sum(bsxfun(@times,xyPoints,uVec),1)).';\n            end\n        else\n            for curVal=1:numPoints\n                U(curVal)=intercept+slope*V(curVal);\n                uVec=[U(curVal);V(curVal)];\n\n                if(uVec'*uVec>1)\n                    continue;\n                end\n\n                Rsp(curVal)=sum(sum(T*exp(-1j*2*pi*sum(bsxfun(@times,xyPoints,uVec),1)).'));\n            end\n        end\n    end\nend\n\nif(nargin<3||isempty(normVals))\n    normVals='ArrayGain';\nend\n\nswitch(normVals)\n    case 'ArrayGain'%Array power gain versus spatially white noise.\n        if(nargin<4||isempty(Sigma))\n           Sigma=eye(numEls,numEls);\n        end\n        \n        if(isvector(T))\n            Rsp=abs(Rsp).^2/sum(T*Sigma*T');\n        else\n        \n            numSubarrays=size(T,1);\n            e=ones(numSubarrays,1);\n            %The sum sums up all of the subarray outputs.\n            Rsp=abs(Rsp).^2/sum(e'*T*Sigma*T'*e);\n        end\n    case 'NormPowGain'%Normalized absolute array power gain\n        Rsp=abs(Rsp);\n        Rsp=(Rsp/max(Rsp(:))).^2;%Make it relative to the peak.\n    case 'AbsPowGain'\n        Rsp=abs(Rsp)^2;\n    case 'NormRealVal'%Display the real component of the response.\n        Rsp=real(Rsp);\n        Rsp=Rsp/max(Rsp(:));%Make it relative to the peak.\n    case 'RawOutput'\n    otherwise\n        error('Unknown plot type requested')\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/standardUVBeamPattern.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5655392031558417}}
{"text": "function Y = variantMultiply( psfMatData, X, padsize );\n%\n%           Y = variantMultiply( psfMatData, X, padsize );\n%\n%  This function computes the multiplication of a spatially variant\n%  point spread function (PSF) times an image:\n%                y = A*x\n%\n%  Here we assume A is made up of a several space invariant PSFs, and \n%  use piece-wise constant interpolation of them to define the spatially\n%  variant PSF.  That is, A has the form:\n%\n%       A = D1*A1 + D2*A2 + ... + Dp*Ap\n%\n%  Input:\n%   psfMatData  -  cell array containing the matrix data of each of the\n%                  individual PSFs.  This matrix data is usuall computed\n%                  from onePsfMatrix.m\n%            X  -  array containing the image to which the psfMatrix\n%                  is to be multiplied.\n%\n%  Output:\n%            Y  -  contains the result after PSF multiplication.\n%\n\n%  J. Nagy 1/7/02\n\nimsize = size( X ) - 2*padsize;\n\n%\n%  We partition the image domain into regions of equal sizes, \n%  according to the number of PSFs we have ...\n%\nnregions = size(psfMatData);\nrsize = ceil(imsize ./ nregions);\n\n%\n%  In order for this to be consistent for 2-D and 3-D images, we need to make\n%  sure there is a third dimension ...\n%\nif length(imsize) == 1\n  imsize = [imsize, 1, 1];\n  rsize = [rsize, 1, 1];\n  nregions = [nregions, 1, 1];\n  padsize = [padsize, 0, 0];\nelseif length(imsize) == 2\n  imsize = [imsize, 1];\n  rsize = [rsize, 1];\n  nregions = [nregions, 1];\n  padsize = [padsize, 0];\nend\n\n%\n%  Coding the rest of this will be easier if all of the image subregions\n%  have the same dimensions.  If it's not, we pad with a few zeros to make\n%  it so ...\n%\npadsize1 = rsize .* nregions - imsize;\nif any( padsize1 < 0 )\n  error('Something is wrong here ...')\nend\nX = padarray(X, padsize1, 'post');\n\n%\n%  Now we get information about beginning and ending indices of subregions\n%  so we can \"put\" and \"get\" subregions correctly ...\n%\n[RIidx, RJidx, RKidx] = region_indices( nregions, rsize );\n[EIidx, EJidx, EKidx] = eregion_indices( RIidx, RJidx, RKidx, 2*padsize );\n\n%\n%  Now loop over all the subregions ...\n%\nY = zeros(imsize);\nfor k = 1:nregions(3)\n  for j = 1:nregions(2)\n    for i = 1:nregions(1)\n      Xt = X(EIidx(i,1):EIidx(i,2), EJidx(j,1):EJidx(j,2), EKidx(k,1):EKidx(k,2));\n      Yt = invariantMultiply( psfMatData{i,j,k}, Xt, padsize(1:length(size(X))) );\n      Y(RIidx(i,1):RIidx(i,2), RJidx(j,1):RJidx(j,2), RKidx(k,1):RKidx(k,2)) = Yt;\n    end\n  end\nend\n\nY = Y(1:imsize(1), 1:imsize(2), 1:imsize(3));\n\n\n", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/Extra/prblur_tools/@psfMatrix/private/variantMultiply.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5655392031558416}}
{"text": "function f = circconv(f, g)\n%CONV   Circular convolution of TRIGTECH objects.\n%   H = CIRCCONV(F, G) produces the convolution of TRIGTECH objects F and G:\n%                     - \n%                    /\n%           H(x) =   |    F(t) G(x-t) dt,  x in [-pi, pi]\n%                    /\n%                   -\n%   Note that CIRCCONV only supports smooth periodic functions on [-pi,pi].\n%\n%   Example:\n%     f = trigtech(@(x) exp(cos(40*pi*x))); \n%     g = trigtech(@(x) exp(-(20*x).^2);\n%     h = circconv(f,g);\n%     plot(h);\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% Return empty for an empty input:\nif ( isempty(f) || isempty(g) )\n    f = trigtech();\n    return\nend\n\n% No support for array-valued trigtech objects:\nif ( (size(f, 2) > 1) || (size(g, 2) > 1) )\n    error('CHEBFUN:TRIGTECH:conv:array', ...\n        'No support for array-valued TRIGTECH objects.');\nend\n\n% Get the sizes of the TRIGTECH objects\nnf = size(f.coeffs, 1);\nng = size(g.coeffs, 1);\n\n% Make the TRIGTECH objects the same length.\nif ( nf > ng )\n    % Increase the length of g (via PROLONG):\n    g = prolong(g, nf);\nelseif ( nf < ng )\n    % Increase the length of f (via PROLONG):\n    f = prolong(f, ng);\nend\nn = size(f.coeffs,1);\n\n% Convolution is just multiplication of the Fourier coefficients.\n% Shift g horizontally to -1.\ng = circshift(g,-1);\nf.values = 2/n*ifft(fft(f.values).*fft(g.values));\nf.coeffs = f.vals2coeffs(f.values);\n\n% TODO:  Why do we simplify twice?  (Once here and once below.)\nf = simplify(f);\n\nf.ishappy = f.ishappy && g.ishappy;\nf.isReal = f.isReal && g.isReal;  % Are you real happy though?\n\nf.values(:,f.isReal) = real(f.values(:,f.isReal));\n\nif ( f.ishappy )\n    f = simplify(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/@trigtech/circconv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5655229069132801}}
{"text": "classdef BT8 < PROBLEM\n% <multi> <real> <large/none>\n% Benchmark MOP with bias feature\n\n%------------------------------- Reference --------------------------------\n% H. Li, Q. Zhang, and J. Deng, Biased multiobjective optimization and\n% decomposition algorithm, IEEE Transactions on Cybernetics, 2017, 47(1):\n% 52-66.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            [N,D] = size(X);\n            I1    = 2 : 2 : D;\n            I2    = 3 : 2 : D;\n            Y     = X - repmat(X(:,1),1,D).^(0.5+1.5*repmat(0:D-1,N,1)/(D-1));\n            DY    = Y.^2 + (1-exp(-Y.^2/1e-3))/5;\n            PopObj(:,1) = X(:,1)         + sum(4*DY(:,I1).^2-cos(8*pi*DY(:,I1))+1,2);\n            PopObj(:,2) = 1-sqrt(X(:,1)) + sum(4*DY(:,I2).^2-cos(8*pi*DY(:,I2))+1,2);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - R(:,1).^0.5;\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R = obj.GetOptimum(100);\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/BT/BT8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.7549149813536516, "lm_q1q2_score": 0.5654971679780942}}
{"text": "function [ know, x ] = p18_sol ( n )\n\n%*****************************************************************************80\n%\n%% P18_SOL returns the solution for problem 18.\n%\n%  Discussion:\n%\n%    The solution values are taken from Brent.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 February 2002\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the order of the problem.  This value\n%    is only needed for those problems with variable N.\n%\n%    Output, integer KNOW.\n%    If KNOW is 0, then the solution is not known.\n%    If KNOW is positive, then the solution is known, and is returned in X.\n%\n%    Output, real X(N), the solution, if known.\n%\n  if ( n == 2 )\n    know = 1;\n    x = [ 0.2113249, 0.7886751 ]';\n  elseif ( n == 4 )\n    know = 1;\n    x = [ 0.1026728, 0.4062037, 0.5937963, 0.8973272 ]';\n  elseif ( n == 6 )\n    know = 1;\n    x = [ 0.066877, 0.288741, 0.366682, 0.633318, ...\n      0.711259, 0.933123 ]';\n  elseif ( n == 8 )\n    know = 1;\n    x = [ 0.043153, 0.193091, 0.266329, 0.500000, ...\n      0.500000, 0.733671, 0.806910, 0.956847 ]';\n  else\n    know = 0;\n    x = zeros ( 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/test_opt/p18_sol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.5654971638476448}}
{"text": "function [lm lm_avg] = rcu_ach(n, delta, epsil, plow, pup);\n% Compute RCU achievability bound. \n% lm returns the bound valid for maximal probability of error\n% lm_avg is for the average\n%\n% This is not a vectorized version, because the function is really slow.\n% You can speed it up significantly if you provide a bracket plow, pup for the value of logm.\n% For example, a smart idea is to set \n% plow = gallager_ach(n, delta, epsil) and pup = converse(n,delta,epsil);\n\nif nargin < 5\n\tplow = 0;\n\tpup = n;\nend\n\neps_test = precise_rand(n, delta, pup);\nif(eps_test < epsil)\n\tdisp(sprintf([\t'-- achiev_prand(n = %d, delta = %g, epsil = %g): eps_test = %g\\n'...\n\t\t\t'        This is a bug? precise_rand() contradicts converse ?!?!'], ...\n\t\t\tn, delta, epsil, eps_test));\n\terror('achiev_prand');\n\tlm_avg = 0; lm = 0;\n\treturn;\nend\n\neps_test = precise_rand(n, delta, plow);\nif(eps_test > epsil)\n\tdisp(sprintf([\t'-- achiev_prand(n = %d, delta = %g, epsil = %g): eps_test = %g\\n'...\n\t\t\t'        Can not find lower bound for precise_rand() !!!!'], ...\n\t\t\tn, delta, epsil, eps_test));\n\t%error('achiev_prand');\n\tlm_avg = 0; lm = 0;\n\treturn;\nend\n\n% Take into account that we are computing AVERAGE prob. of error,\n% and so we need a random linear code trick to go to maximum => log M must be integer\nwhile floor(plow) < floor(pup);\n\tptest = (plow + pup)/2;\n\teps_test = precise_rand(n, delta, ptest);\n\tif(eps_test > epsil)\n\t\tpup = ptest;\n\telse\n\t\tplow = ptest;\n\t\t% This is not needed as we stop on floor-test\n\t\t%if  (epsil-eps_test)< 1e-2*epsil\n\t\t%\tbreak;\n\t\t%end\n\tend\nend\nlm_avg = plow;\nlm = floor(plow);\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/rcu_ach.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.56549716345478}}
{"text": "function plotc(x,y,v,marker)\n%FUNCTION PLOTC(X,Y,V,'MARKER') plots the values of v colour coded\n% at the positions specified by x and y, and v (z-axis) in a 3-D axis\n% system. A colourbar is added on the right side of the figure.\n%\n% The colorbar strectches from the minimum value of v to its\n% maximum in 9 steps (10 values).\n%\n% The last argument is optional to define the marker being used. The\n% default is a point. To use a different marker (such as circles, ...) send\n% its symbol to the function (which must be enclosed in '; see example).\n%\n% The plot is actually a 3D plot but the orientation of the axis is set\n% such that it appears to be a plane 2D plot. However, you can toggle\n% between 2D and 3D view either by using the command 'view(3)' (for 3D\n% view) or 'view(2)' (for 2D), or by interactively rotating the axis\n% system.\n%\n% Example:\n% Define three vectors\n%    x=1:10;y=1:10;p=randn(10,1);\n%    plotc(x,y,p)\n%\n%    x=randn(100,1);\n%    y=2*x+randn(100,1);\n%    p=randn(100,1);\n%    plotc(x,y,p,'d')\n%    view(3)\n%\n% Uli Theune, University of Alberta, 2004\n% modified by Stephanie Contardo, British OCeanographic Data Centre, 2006\n%\n\ndelete(gca)\nif nargin <4\n    marker='.';\nend\n\nmap=colormap;\nmiv=min(v);\nmav=max(v);\nclrstep = (mav-miv)/size(map,1) ;\n% Plot the points\nhold on\nfor nc=1:size(map,1)\n    iv = find(v>miv+(nc-1)*clrstep & v<=miv+nc*clrstep) ;\n    plot3(x(iv),y(iv),v(iv),marker,'color',map(nc,:),'markerfacecolor',map(nc,:))\nend\nhold off\n\n% Re-format the colorbar\nh=colorbar;\n\nset(h,'ylim',[1 length(map)]);\nyal=linspace(1,length(map),10);\nset(h,'ytick',yal);\n% Create the yticklabels\nytl=linspace(miv,mav,10);\ns=char(10,4);\nfor i=1:10\n    if min(abs(ytl)) >= 0.001\n        B=sprintf('%-4.3f',ytl(i));\n    else\n        B=sprintf('%-3.1E',ytl(i));\n    end\n    s(i,1:length(B))=B;\nend\nset(h,'yticklabel',s);\ngrid on\nview(2)\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/14014-color-coded-2d-scatterplot/plotclr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.5654971551938817}}
{"text": "% GSPBOX - Graphs\n%\n%  Specific graphs\n%    gsp_swiss_roll              -  Create swiss roll graph\n%    gsp_david_sensor_network    -  Create the sensor newtwork from david\n%    gsp_ring                    -  Create the ring graph\n%    gsp_path                    -  Create the path graph\n%    gsp_airfoil                 -  Create the airfoil graph\n%    gsp_comet                   -  Create the comet graph\n%    gsp_erdos_renyi             -  Create a erdos renyi graph\n%    gsp_minnesota               -  Create Minnesota road graph\n%    gsp_low_stretch_tree        -  Create a low stretch tree graph\n%    gsp_sensor                  -  Create a random sensor graph\n%    gsp_random_regular          -  Create a random regular graph\n%    gsp_random_ring             -  Create a random ring graph\n%    gsp_full_connected          -  Create a fully connected graph\n%    gsp_nn_graph                -  Create a nearest neighbors graph\n%    gsp_rmse_mv_graph           -  Create a nearest neighbors graph with missing values\n%    gsp_sphere                  -  Create a spherical-shaped graph\n%    gsp_cube                    -  Create a cubical-shaped graph\n%    gsp_2dgrid                  -  Create a 2d-grid graph\n%    gsp_torus                   -  Create a torus graph\n%    gsp_logo                    -  Create a GSP logo graph\n%    gsp_community               -  Create a community graph\n%    gsp_bunny                   -  Create a bunny graph\n%    gsp_spiral                  -  Create a spiral graph\n%    gsp_stochastic_block_graph  -  Create a graph with the stochastic block model\n%\n%  Hypergraphs\n%    gsp_nn_hypergraph           -  Create an hyper nearest neighbor graph\n%    gsp_hypergraph              -  Create an hypergraph\n%\n%  Utils\n%    gsp_graph_default_parameters-  Initialise all parameters for a graph\n%    gsp_graph_default_plotting_parameters-  Initialise all plotting parameters for a graph\n%    gsp_graph                   -  Create a graph from a weight matrix\n%    gsp_update_weights          -  Update the weights of a graph\n%    gsp_update_coordinates      -  Update the coordinate of a graph\n%    gsp_components              -  Cuts non connected graph into several connected ones\n%    gsp_subgraph                -  Create a subgraph\n%    gsp_graph_product           -  Compute graph product between two graphs\n%    gsp_line_graph              -  Create the Line Graph (or edge-to-vertex dual graph) of a graph\n%    gsp_jtv_graph               -  Add time information to the graph structure\n%\n%\n%  For help, bug reports, suggestions etc. please send email to\n%  gspbox 'dash' support 'at' groupes 'dot' epfl 'dot' ch\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/graphs/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5654971510634325}}
{"text": "function Wop = normalize_standardize_threshold_wavelet_factory_1d(N,filter_options,scat_options,epsilon)\n\nif nargin <4\n    epsilon =2^(-20);\nend\n\nfilters = filter_bank(N, filter_options);\n\nren_op=@(X)(func_output(...\n            @renorm_wavelet_layer_1d,[1,2],X,epsilon));\n        \nstd_op= @(X,m)(func_output(...\n            @standardize_wavelet_layer_1d,[1,2],X,scat_options.sigmas{m+1}));\n\n\tfor m = 0:scat_options.M\n\t\tfilt_ind = min(numel(filters), m+1);\n        if m<scat_options.M\n\t\tWop{m+1} = @(X)(threshold_wavelet_layer_1d(...\n            std_op(...\n            ren_op(func_output(@wavelet_layer_1d,[1,2],X,...\n            filters{filt_ind},scat_options)),m),scat_options.threshold));\n        else \n        Wop{m+1} = @(X)(threshold_wavelet_layer_1d(...\n                      ren_op(func_output(@wavelet_layer_1d,[1,2],X,...\n            filters{filt_ind},scat_options)),scat_options.threshold));\n\tend\n\nend\n\n\n\n\n   \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/normalize_standardize_threshold_wavelet_factory_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5654306202864444}}
{"text": "function L = probitNoiseLikelihood(noise, mu, varsigma, y)\n\n\n% PROBITNOISELIKELIHOOD Likelihood of the data under the PROBIT noise model.\n% FORMAT\n% DESC returns the likelihood of a data set under the  probit based classification 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 : probitNoiseParamInit, probitNoiseLogLikelihood, noiseLikelihood\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005\n\n% NOISE\n\n\nD = size(y, 2);\nfor i = 1:D\n  mu(:, i) = mu(:, i) + noise.bias(i);\nend\nL = cumGaussian((y.*mu)./(sqrt(noise.sigma2+varsigma)));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/noise/probitNoiseLikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5654306086556063}}
{"text": "function [ a, seed ] = r8vec_uniform ( n, b, c, seed )\n\n%*****************************************************************************80\n%\n%% R8VEC_UNIFORM returns a scaled pseudorandom R8VEC.\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 N, the number of entries in the vector.\n%\n%    Input, real B, C, the range of the pseudorandom values.\n%\n%    Input, integer SEED, a seed for the random number generator.\n%\n%    Output, real A(N), the vector of pseudorandom values.\n%\n%    Output, integer SEED, an updated seed for the random number generator.\n%\n  if ( seed == 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8VEC_UNIFORM - Fatal error!\\n' );\n    fprintf ( 1, '  Input SEED = 0!\\n' );\n    error ( 'R8VEC_UNIFORM - Fatal error!' );\n  end\n\n  r = zeros ( n, 1 );\n\n  for i = 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 + 2147483647;\n    end\n\n    a(i) = b + ( c - b ) * seed * 4.656612875E-10;\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/r8vec_uniform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5654199329921936}}
{"text": "classdef IMMOEA_F7 < PROBLEM\n% <multi> <real> <large/none>\n% Benchmark MOP for testing IM-MOEA\n\n%------------------------------- Reference --------------------------------\n% R. Cheng, Y. Jin, K. Narukawa, and B. Sendhoff, A multiobjective\n% evolutionary algorithm using Gaussian process-based inverse modeling,\n% IEEE Transactions on Evolutionary Computation, 2015, 19(6): 838-856.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            t = X(:,2:obj.D).^(1./(1+3*repmat(2:obj.D,size(X,1),1)/obj.D)) - repmat(X(:,1),1,obj.D-1);\n            g = 1 + 9*mean(t.^2,2);\n            PopObj(:,1) = 1 - exp(-4*X(:,1)).*sin(6*pi*X(:,1)).^6;\n            PopObj(:,2) = g.*(1-(PopObj(:,1)./g).^2);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            minf1  = min(1-exp(-4*(0:1e-6:1)).*(sin(6*pi*(0:1e-6:1))).^6);\n            R(:,1) = linspace(minf1,1,N)';\n            R(:,2) = 1 - R(:,1).^2;\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R = obj.GetOptimum(100);\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/MOPs with variable linkages/IMMOEA_F7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.5654199250258661}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D \n% shape modeling and analysis toolkit. \n% It is a software package developed at Shenlab in Center for Neuroimaging, \n% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)\n% It is available to the scientific community as copyright freeware \n% under the terms of the GNU General Public Licence.\n% \n% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University\n% \n% This file is part of SPHARM-MAT.\n% \n% SPHARM-MAT is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% SPHARM-MAT is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with SPHARM-MAT. If not, see <http://www.gnu.org/licenses/>.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% ============================================\n% utl_signmatrix\n%\n% Goal: create signmatrix\n% max_d is max degree\n%\n% Li Shen \n% 01/14/2007 - create\n\nfunction utl_sgm(max_d)\nglobal sgm;\n\nfor d=1:max_d\n    n = 2*d+1;\n    M = (-1).^(1:n^2);\n    sgm{d} = reshape(M,n,n);\nend\n   \nreturn;\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SpharmToolbox/code/utl_sgm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.5654199164703304}}
{"text": "function [varargout]=cunique(A)\n\n% function [A_uni,ind1,ind2,Ac]=cunique(A)\n%-------------------------------------------------------------------------\n%This function is similar to MATLAB's unique function. There are three\n%differences: 1) An additional 4th optional output is available providing\n%the count, or number of occurances, for each element in the input array.\n%2) The 2nd output mathces the size of the first input, 3) The 3rd output\n%is reshaped to be the size of the input variable. \n%\n% See also: unique\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n%\n% 2018/03/21: Created\n%-------------------------------------------------------------------------\n\n%%\n\n[A_uni,ind1,ind2]=unique(A);\n\nvarargout{1}=A_uni;\nvarargout{2}=reshape(ind1,size(A_uni));\nvarargout{3}=reshape(ind2,size(A));\n\nif nargout==4\n    [subInd] = ind2subn(size(A_uni),ind2);\n    Ac=accumarray(subInd,ones(numel(ind2),1),size(A_uni));\n    Ac=reshape(Ac(ind2),size(A));\n    varargout{4}=Ac;\nend\n", "meta": {"author": "MultiDIC", "repo": "MultiDIC", "sha": "d363c3ea74673e58df275d4a4c8e528ef5472acb", "save_path": "github-repos/MATLAB/MultiDIC-MultiDIC", "path": "github-repos/MATLAB/MultiDIC-MultiDIC/MultiDIC-d363c3ea74673e58df275d4a4c8e528ef5472acb/lib_ext/GIBBON/lib/cunique.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.5654199123889653}}
{"text": "function bf = cubic_spline_fourier(f, a)\n\n% The continuous Fourier transform of a cubic spline kernel.\n\nbf = -(- 12*a + 12*exp(-pi*f*2i) + 12*exp(pi*f*2i) + 6*a*exp(-pi*f*4i) + ...\n    6*a*exp(pi*f*4i) + f.*(pi*exp(-pi*f*2i)*12i) - f.*(pi*exp(pi*f*2i)*12i) + ...\n    a*f.*(pi*exp(-pi*f*2i)*16i) - a*f.*(pi*exp(pi*f*2i)*16i) + ...\n    a*f.*(pi*exp(-pi*f*4i)*4i) - a*f.*(pi*exp(pi*f*4i)*4i) - 24)./(16*f.^4*pi^4);\n\nbf(f == 0) = 1;", "meta": {"author": "martin-danelljan", "repo": "ECO", "sha": "27e8ae565cd63ec14bafcaad8b5b993bec8f3e69", "save_path": "github-repos/MATLAB/martin-danelljan-ECO", "path": "github-repos/MATLAB/martin-danelljan-ECO/ECO-27e8ae565cd63ec14bafcaad8b5b993bec8f3e69/implementation/fourier_tools/cubic_spline_fourier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5653651583684827}}
{"text": "function ip = inner_product_cdcf(xf, yf)\n\n% Computes the inner product between two filters.\n\nip_cell = cellfun(@(xf, yf) real(2*(xf(:)' * yf(:)) - reshape(xf(:,end,:), [], 1, 1)' * reshape(yf(:,end,:), [], 1, 1)), xf, yf, 'uniformoutput', false');\nip = sum(cell2mat(ip_cell));\n\n% ip_cell = cellfun(@(xf, yf) real(xf(:)' * yf(:)), xf, yf, 'uniformoutput', false');\n% ip = sum(cell2mat(ip_cell));", "meta": {"author": "martin-danelljan", "repo": "Continuous-ConvOp", "sha": "a79708be1f6f8bd8ec5489281cb37b164bebea83", "save_path": "github-repos/MATLAB/martin-danelljan-Continuous-ConvOp", "path": "github-repos/MATLAB/martin-danelljan-Continuous-ConvOp/Continuous-ConvOp-a79708be1f6f8bd8ec5489281cb37b164bebea83/implementation/inner_product_cdcf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5652925749893603}}
{"text": "function Y = multiherm(X)\n% Returns the Hermitian parts of the matrices in the 3D matrix X\n%\n% function Y = multiherm(X)\n%\n% Y is a 3D matrix the same size as X. Each slice Y(:, :, i) is the\n% Hermitian part of the slice X(:, :, i).\n%\n% See also: multiprod multitransp multihconj multiscale multiskew\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Hiroyuki Sato, April 27, 2015.\n% Contributors: \n% Change log: \n\n    Y = .5*(X + multihconj(X));\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/multiherm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5652912388645971}}
{"text": "\n\n%\n% read_eccen_patch.m\n%\n% Original Author: Bruce Fischl\n% CVS Revision Info:\n%    $Author: nicks $\n%    $Date: 2011/03/02 00:04:12 $\n%    $Revision: 1.3 $\n%\n% Copyright \u00a9 2011 The General Hospital Corporation (Boston, MA) \"MGH\"\n%\n% Terms and conditions for use, reproduction, distribution and contribution\n% are found in the 'FreeSurfer Software License Agreement' contained\n% in the file 'LICENSE' found in the FreeSurfer distribution, and here:\n%\n% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense\n%\n% Reporting: freesurfer@nmr.mgh.harvard.edu\n%\n\n\n\n% Should run 'left or right' scripts to set up fname_* variable,s\n% and set nfig so that plotting starts in the right location.\nfclose('all');\nfid=fopen(fname_patch,'rt');\ns = fgetl(fid);\ns = fgetl(fid);\n[poly,count] = sscanf(s,'%d');\nnumvert = poly(1);\nnumquad = poly(2);\nvertex_coordinates = zeros(3,1);\nface_index = zeros(4,1);\nvertx_list = zeros(numvert,3);\nface_list = zeros(numquad,5);\ntic;\nfor vert = 1:1:(numvert),\n    s = fgetl(fid);\n    vertx = sscanf(s,'%d');\n    s = fgetl(fid);\n    vertx_coordinates = sscanf(s,'%f');\n    vertx_list(vert,:) = [vertx_coordinates(1:2)' vertx];\nend;\ntoc\ntic;\nfor face = 1:1:(numquad),\n    s = fgetl(fid);\n    facenum = sscanf(s,'%d');\n    s = fgetl(fid);\n    face_vertx = sscanf(s,'%d');\n    face_list(face,:) = [face_vertx' facenum];\nend;\ntoc\nfclose(fid);\nfull_vertx=zeros(max(max(vertx_list))+1,3);\nfull_vertx(vertx_list(:,3)+1,1)=vertx_list(:,1);\nfull_vertx(vertx_list(:,3)+1,2)=vertx_list(:,2);\nmesh_real=File2Var(fname_real);\nvertx_values=zeros(max(max(vertx_list))+1,1);\nvertx_values(vertx_list(:,3)+1)=mesh_real(:,5);\nmesh_imag=File2Var(fname_imag);\nvertx_complex=zeros(max(max(vertx_list))+1,1);\nvertx_complex(vertx_list(:,3)+1)=mesh_imag(:,5);\nv_complex = vertx_values(:,1) + i*vertx_complex;\n%v_phase=angle(v_complex');\n\nstrpwd=pwd;\n%subplot(4,3,nfig+1);\nfigure;\ntitle([strpwd((length(strpwd)-25):length(strpwd)) ' ' fname_real]);\np_eccen_handle=patch('Vertices',full_vertx,'Faces',face_list(:,1:4)+1,'FaceVertexCData',angle(v_complex),'FaceColor','interp','EdgeColor','none');\n%colormap(rgb(256));\ncolorbar;\n%tic; t_unwrap=unwrap(angle(v_complex)); toc\n\nshort_complex = mesh_real(:,5) + (i*mesh_imag(:,5));\nshort_unwrap=angle(short_complex);\n[zmat_eccen,xvec,yvec]=ffgrid(vertx_list(:,1),vertx_list(:,2),short_unwrap,1.0,1.0);\nfigure;\ntitle([strpwd((length(strpwd)-25):length(strpwd)) ' ' fname_real]);\n%subplot(4,3,nfig+2);\nimagesc(xvec,yvec,zmat_eccen);\naxis xy;\n%colormap(rgb(64));\ncolorbar;\n%subplot(4,3,nfig+3);\nfigure;\ntitle([strpwd((length(strpwd)-25):length(strpwd)) ' ' fname_real]);\ncontour(xvec,yvec,zmat_eccen,20);\n%figure;\n\n%ffgrid(vertx_list(:,1),vertx_list(:,2),short_unwrap,0.75,0.75); \n[zmat_imag_eccen,xvec,yvec]=ffgrid(vertx_list(:,1),vertx_list(:,2),mesh_imag(:,5),1.0,1.0);\n[zmat_real_eccen,xvec,yvec]=ffgrid(vertx_list(:,1),vertx_list(:,2),mesh_real(:,5),1.0,1.0);\nsmooth_filt = fspecial('average',3);\nzmat_eccen_cplx = zmat_real_eccen + (i*zmat_imag_eccen);\nzmat_imag_smooth = zmat_imag_eccen;\nzmat_real_smooth = zmat_real_eccen;\nmaxiter=2;\nfor niter=1:maxiter,\n  zmat_imag_smooth = filter2(smooth_filt,zmat_imag_smooth);\n  zmat_real_smooth = filter2(smooth_filt,zmat_real_smooth);\nend;\nzmat_smooth_eccen = angle(zmat_real_smooth + (i*zmat_imag_smooth));\nzmat_smooth_eccen_cplx = zmat_real_smooth + (i*zmat_imag_smooth);\n%subplot(4,3,nfig+5);\nfigure;\ntitle([strpwd((length(strpwd)-25):length(strpwd)) ' ' fname_real]);\nimagesc(xvec,yvec,zmat_smooth_eccen); axis xy;\nfigure;\n%subplot(4,3,nfig+6);\ntitle([strpwd((length(strpwd)-25):length(strpwd)) ' ' fname_real]);\nimcontour(xvec,yvec,zmat_smooth_eccen_cplx,20);\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/read_eccen_patch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5652912221462716}}
{"text": "function [Ppad, center_pad] = padIm(P, dim, center)\n%PADPSF Pad an array P with zeros to make it bigger.\n%\n%      Ppad = padIm(PSF, dim);\n%\n%  Pad P with zeros to make it an m-by-n array. \n%\n%  Input:\n%        P  Array (matrix)\n%      dim  Desired dimension of padded array.  \n%             If dim is a scalar, then n = m.\n%  Optional Input:\n%    center integer array of two values indicating location of \"center\"\n%           of P. This is used for PSFs\n%\n%  Output:\n%        P  Padded m-by-n array.\n\n% Reference: See Chapter 4, \n%            \"Deblurring Images - Matrices, Spectra, and Filtering\"\n%            by P. C. Hansen, J. G. Nagy, and D. P. O'Leary,\n%            SIAM, Philadelphia, 2006.\n\n%\n% Set default parameters.\n%\nswitch nargin\n    case 1\n        error('Need desired dimension of padded array')\n    case 3\n        if length(center) == 1\n            error('center should be a vector with two integers')\n        else\n            ci = center(1); cj = center(2);\n        end\nend\nif length(dim) == 1\n    m = dim; n = dim;\nelse\n    m = dim(1); n = dim(2);\nend\n%\n% Pad the with zeros.\n%\n[mp, np] = size(P);\nPpad = zeros(m, n);\nputidx = fix((size(Ppad) - size(P))/2) + 1;\nPpad(putidx(1):putidx(1)+mp-1, putidx(2):putidx(2)+np-1) = P;\n\nif nargin == 3\n    center_pad = [ci+putidx(1)-1, cj+putidx(2)-1];\nelse\n    center_pad = [];\nend\n\n", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/Extra/prblur_tools/padIm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5652912221462715}}
{"text": "function [Aver,p,ip] = hor_to_ver(Ahor)\n%hor_to_ver   reorder matrix from horizontal to vertical \n%   [Aver,p,ip] = hor_to_ver(Ahor)\n%   input\n%          Ahor    matrix from horizontal ordering of square grid \n%   output\n%          Aver    matrix from vertical ordering of square grid\n%          p       horizontal to vertical permutation, xv = x(ip)\n%          ip      vertical to horizontal permutation, y = yv(p)\n%\n%   IFISS function: HCE; 28 February 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n\n%To multiply a vector x by Aver:  \n%   xv = x(ip), yv = Aver*xv, y = yv(p);\n\nN = length(Ahor);\nn = sqrt(N);\np  = zeros(N,1);\nip = zeros(N,1);\n\nfor j=1:n,\n   for i=1:n,\n      hor = (j-1)*n+i;\n      ver = (i-1)*n+j;\n      ip(ver) = hor;\n      p(hor) = ver;\n   end\nend\n\nAver = Ahor(ip,ip);", "meta": {"author": "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/ch4_code/hor_to_ver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5652912140816386}}
{"text": "function B = transform_image_V1_V3(I, corners, interporation)\n\n% B = transform_image3(I, corners, interporation)\n% calculate the transformation matrix for each area\n\nB = nan(256,256);\n\nif notDefined('interporation'), interporation = [];  end;\n\n% V3v\ninput_points = corners{4};\n% base_points =  [40 20;40 35; 80 35; 80 20];\nbase_points =  [30 80; 15 80; 15 40; 30 40];\nudata = [1 201];  vdata = [1 201];  % input coordinate system\ntform = maketform('projective',input_points, base_points);\n[tmp,xdata,ydata] = imtransform(I,tform,interporation,'udata',udata,...\n                                                'vdata',vdata,...\n                                                'xdata',udata,...\n                                                'ydata',vdata,...\n                                                'size',size(I),...\n                                                'fill',256);\nB(round(20/200*256):round(100/200*256), round(10/200*256):round(30/200*256))=tmp(round(20/200*256):round(100/200*256),round(10/200*256):round(30/200*256));\n\n% V2v\ninput_points = corners{2};\n% base_points =  [40 50;40 35; 80 35; 80 50];\nbase_points =  [30 80; 45 80; 45 40; 30 40];\nudata = [1 201];  vdata = [1 201];  % input coordinate system\ntform = maketform('projective',input_points, base_points);\n[tmp,xdata,ydata] = imtransform(I,tform,interporation,'udata',udata,...\n                                                'vdata',vdata,...\n                                                'xdata',udata,...\n                                                'ydata',vdata,...\n                                                'size',size(I),...\n                                                'fill',256);\nB(round(20/200*256):round(100/200*256), round(30/200*256):round(45/200*256))=tmp(round(20/200*256):round(100/200*256),round(30/200*256):round(45/200*256));\n\n% V1\ninput_points = corners{1};\n% base_points =  [40 50;40 65; 80 65; 80 50];\nbase_points =  [75 80; 45 80; 45 40; 75 40];\nudata = [1 201];  vdata = [1 201];  % input coordinate system\ntform = maketform('projective',input_points, base_points);\n[tmp,xdata,ydata] = imtransform(I,tform,interporation,'udata',udata,...\n                                                'vdata',vdata,...\n                                                'xdata',udata,...\n                                                'ydata',vdata,...\n                                                'size',size(I),...\n                                                'fill',256);\nB(round(20/200*256):round(100/200*256), round(45/200*256):round(75/200*256))=tmp(round(20/200*256):round(100/200*256),round(45/200*256):round(75/200*256));\n\n% V2d\ninput_points = corners{3};\n% base_points =  [40 80;40 65; 80 65; 80 80];\nbase_points =  [75 80; 90 80; 90 40; 75 40];\n% input_points = [corners{2};mean(corners{2}(2:3,:)); mean(corners{2})];\n% % base_points =  [40 80;40 65; 80 65; 80 80];\n% base_points =  [90 80; 75 80; 75 40; 90 40; 75 60; 82.5 60];\nudata = [1 201];  vdata = [1 201];  % input coordinate system\ntform = maketform('projective',input_points, base_points);\n[tmp,xdata,ydata] = imtransform(I,tform,interporation,'udata',udata,...\n                                                'vdata',vdata,...\n                                                'xdata',udata,...\n                                                'ydata',vdata,...\n                                                'size',size(I),...\n                                                'fill',256);\nB(round(20/200*256):round(100/200*256), round(75/200*256):round(90/200*256))=tmp(round(20/200*256):round(100/200*256),round(75/200*256):round(90/200*256));\n                                            \n% V3d\ninput_points = corners{5};\n% base_points =  [40 80;40 65; 80 65; 80 80];\nbase_points =  [105 80; 90 80; 90 40; 105 40];\n% input_points = [corners{2};mean(corners{2}(2:3,:)); mean(corners{2})];\n% % base_points =  [40 80;40 65; 80 65; 80 80];\n% base_points =  [90 80; 75 80; 75 40; 90 40; 75 60; 82.5 60];\nudata = [1 201];  vdata = [1 201];  % input coordinate system\ntform = maketform('projective',input_points, base_points);\n[tmp,xdata,ydata] = imtransform(I,tform,interporation,'udata',udata,...\n                                                'vdata',vdata,...\n                                                'xdata',udata,...\n                                                'ydata',vdata,...\n                                                'size',size(I),...\n                                                'fill',256);\nB(round(20/200*256):round(100/200*256), round(90/200*256):round(110/200*256))=tmp(round(20/200*256):round(100/200*256),round(90/200*256):round(110/200*256));\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/Atlas/transform_image_V1_V3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225574, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.5652244063919535}}
{"text": "% dallrgl - DAL with logistic loss and grouped L1 regularization\n%\n% Overview:\n%  Solves the optimization problem:\n%   [xx,bias] = argmin sum(log(1+exp(-yy.*(A*x+bias)))) + lambda*||x||_G1\n%  where\n%   ||x||_G1 = sum(sqrt(sum(xx(Ii).^2)))\n%   (Ii is the index-set of the i-th group\n%\n% Syntax:\n%  [xx,bias,status]=dallrgl(xx0, bias0, A, yy, lambda, <opt>)\n%\n% Inputs:\n%  xx0    : initial solution ([nn,1] with opt.blks or [ns nc] with\n%           ns*nc=nn for nc groups of size ns)\n%  bias0  : initial bias (set [] if bias term is unnecessary)\n%  A      : the design matrix A ([mm,nn]) or a cell array {fA, fAT, mm, nn}\n%           where fA and fAT are function handles to the functions that\n%           return A*x and A'*x, respectively, and mm and nn are the\n%           numbers of rows and columns of A.\n%  yy     : the target label vector (-1 or +1) ([mm,1])\n%  lambda : the regularization constant\n%  <opt>  : list of 'fieldname1', value1, 'filedname2', value2, ...\n%   blks     : vector that contains the size of the groups. \n%              sum(opt.blks)=nn. If omitted, opt.blks = [ns,..., ns]\n%              and length(opt.blks)=nc, where nc is the number of groups.\n%   stopcond : stopping condition, which can be\n%              'pdg'  : Use relative primal dual gap (default)\n%              'fval' : Use the objective function value\n%           (see dal.m for other options)\n% Outputs:\n%  xx     : the final solution ([nn,1])\n%  bias   : the final bias term (scalar)\n%  status : various status values\n%\n% Example:\n% m = 1024; n = [64 64]; k = round(0.1*n(1)); A=randn(m,prod(n));\n% w0=randsparse(n,k); yy=sign(A*w0(:)+0.01*randn(m,1));\n% lambda=0.1*max(sqrt(sum(reshape(A'*yy/2,n).^2)));\n% [ww,bias,stat]=dallrgl(zeros(n), 0, A, yy, lambda);\n%\n% Copyright(c) 2009 Ryota Tomioka\n% This software is distributed under the MIT license. See license.txt\n\nfunction [ww,bias,status]=dallrgl(ww, bias, A, yy, lambda, varargin)\n\nopt=propertylist2struct(varargin{:});\nopt=set_defaults(opt,'solver','cg',...\n                     'stopcond','pdg',...\n                     'blks',[]);\n\nif ~isequal(unique_bc(yy), [-1;1])\n  error('yy must be a column vector of -1''s and 1''s');\nend\n\nif isempty(opt.blks)\n  opt.blks=size(ww,1)*ones(1,size(ww,2));\n  ww = ww(:);\nend\n\nprob.floss    = struct('p',@loss_lrp,'d',@loss_lrd,'args',{{yy}});\nprob.fspec    = @gl_spec;\nprob.dnorm    = @gl_dnorm;\nprob.obj      = @objdalgl;\nprob.softth   = @gl_softth;\nprob.stopcond = opt.stopcond;\nprob.ll       = min(0,yy);\nprob.uu       = max(0,yy);\nprob.Ac       =[];\nprob.bc       =[];\nprob.info     = struct('blks',opt.blks);\n\nif isequal(opt.solver,'cg')\n  prob.hessMult = @hessMultdalgl;\nend\n\nif isequal(opt.stopcond,'fval')\n  opt.feval = 1;\nend\n\nif isnumeric(A)\n  A = A(:,:);\n  [mm,nn]=size(A);\n  At=A';\n  fA = struct('times',@(x)A*x,...\n              'Ttimes',@(x)At*x,...\n              'slice', @(I)A(:,I));\n  clear At;\nelseif iscell(A)\n  mm = A{3};\n  nn = A{4};\n  fAslice = @(I)fA(sparse(I,1:length(I),ones(length(I),1), nn, length(I)));\n  fA = struct('times',A{1},...\n              'Ttimes',A{2},...\n              'slice',fAslice);\nelse\n  error('A must be either numeric or cell {@(x)A*x, @(y)(A''*y), mm, nn}');\nend\n\nprob.mm       = mm;\nprob.nn       = nn;\n\nif isempty(bias)\n  B = [];\nelse\n  B = ones(mm,1);\nend\n\n[ww,bias,status]=dal(prob,ww,bias,fA,B,lambda,opt);\n\n\nif all(opt.blks==opt.blks(1))\n  ns=opt.blks(1);\n  nc=length(ww)/ns;\n  ww=reshape(ww, [ns,nc]);\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/dal_ver1.05/dallrgl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5652243843855479}}
{"text": "function y = m_fp_amg(x_it,aparams,qparams)\n%m_fp_amg     AMG iterated pressure convection-diffusion preconditioner\n%   y = m_fp_amg(x_it,aparams,qparams);\n%   input\n%          x_it         operand for preconditioning operator\n%          aparams      structure defining coefficient matrix\n%          mparams      structure defining preconditioning matrix\n%   output\n%          y            result of preconditioning operation\n%\n%   calls FEMLAB function amgsol \n%   Global array variables AMGLOBA and AMGLOBF define the\n%   amg data for amgsol for Ap and F respectively\n%\n%   IFISS function: DJS; 23 April 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage\n\nglobal AMGLOBA\nglobal AMGLOBF\n\nnv = length(aparams.F);\nnu = nv/2;\nnp = size(aparams.B,1);\n\nrv=x_it(1:nv); rp=x_it(nv+1:nv+np);\n\n%% pressure solve\nnv = length(aparams.F);\nnu = nv/2;\nnp = size(aparams.B,1);\n\nrv=x_it(1:nv); rp=x_it(nv+1:nv+np);\n%% pressure solve\nif qparams.domain==1,\n   n_null = qparams.n_null;\n   minor = [1:n_null-1,n_null+1:np]';\n   yp = zeros(np,1);\n   yp(minor) =  amgsol(rp(minor),AMGLOBA);\n   zp = -qparams.Mp\\(qparams.Fp*yp);\nelse\n   zp = -(qparams.Mp)\\((qparams.Fp)*((qparams.Ap)\\rp));\nend\n\n%% velocity solve\nrv = rv-(aparams.B')*zp;\nzv = amgsol(rv,AMGLOBF);\ny = [zv;zp];\n", "meta": {"author": "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/m_fp_amg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5652243836123175}}
{"text": "% MANIPULATOR TRAJECTORY GENERATION\n% Generates combined transform (rotation and translation) trajectories \n% using custom time scaling from a separate trajectory.\n%\n% Copyright 2019 The MathWorks, Inc.\n\n%% Setup\nclear, clc, close all\n\n% Define waypoint information\ncreateWaypointData;\n\n% Define IK\nik = inverseKinematics('RigidBodyTree',gen3);\nikWeights = [1 1 1 1 1 1];\nikInitGuess = gen3.homeConfiguration;\n\n% Set up plot\nplotMode = 2; % 0 = None, 1 = Trajectory, 2 = Coordinate Frames\nshow(gen3,gen3.homeConfiguration,'Frames','off','PreservePlot',false);\nxlim([-1 1]), ylim([-1 1]), zlim([0 1.2])\nhold on\nif plotMode == 1\n    hTraj = plot3(waypoints(1,1),waypoints(2,1),waypoints(3,1),'b.-');\nend\nplot3(waypoints(1,:),waypoints(2,:),waypoints(3,:),'ro','LineWidth',2);\n\n%% Generate and follow trajectory\n% Loop through segments one at a time\ntrajType = 'trap';\nnumWaypoints = size(waypoints,2);\nfor w = 1:numWaypoints-1\n        \n    % Get the initial and final transforms and times for the segment\n    T0 = trvec2tform(waypoints(:,w)') * eul2tform(orientations(:,w)');\n    Tf = trvec2tform(waypoints(:,w+1)') * eul2tform(orientations(:,w+1)');\n    timeInterval = waypointTimes(w:w+1);\n    trajTimes = timeInterval(1):ts:timeInterval(2);\n    \n    % Generate time scaling trajectory for the segment on the range [0 1]\n    switch trajType\n        case 'trap'\n            [s,sd,sdd] = trapveltraj([0 1],numel(trajTimes), ... \n                                     'EndTime',diff(timeInterval));\n        case 'cubic'\n            [s,sd,sdd] = cubicpolytraj([0 1],timeInterval,trajTimes);\n        case 'quintic'\n            [s,sd,sdd] = quinticpolytraj([0 1],timeInterval,trajTimes);\n        otherwise\n            error('Invalid trajectory type! Use ''trap'', ''cubic'', or ''quintic''');\n    end\n    \n    % Find the transforms from trajectory generation\n    [T,vel,acc] = transformtraj(T0,Tf,timeInterval,trajTimes, ... \n                                'TimeScaling',[s;sd;sdd]);  \n       \n    % Trajectory visualization for the segment\n    if plotMode == 1\n        eePos = tform2trvec(T);\n        set(hTraj,'xdata',eePos(:,1),'ydata',eePos(:,2),'zdata',eePos(:,3));\n    elseif plotMode == 2\n        plotTransforms(tform2trvec(T),tform2quat(T),'FrameSize',0.05)\n    end\n    \n    % Trajectory following for the segment\n    for idx = 1:numel(trajTimes) \n        % Solve IK\n        tgtPose = T(:,:,idx);\n        [config,info] = ik(eeName,tgtPose,ikWeights,ikInitGuess);\n        ikInitGuess = config;\n\n        % Show the robot\n        show(gen3,config,'Frames','off','PreservePlot',false);\n        title(['Trajectory at t = ' num2str(trajTimes(idx))])\n        drawnow\n    end\n    \nend", "meta": {"author": "mathworks-robotics", "repo": "trajectory-planning-robot-manipulators", "sha": "e7ee8775b5ace44b5da5455b6aee9c4d8cbf0b4e", "save_path": "github-repos/MATLAB/mathworks-robotics-trajectory-planning-robot-manipulators", "path": "github-repos/MATLAB/mathworks-robotics-trajectory-planning-robot-manipulators/trajectory-planning-robot-manipulators-e7ee8775b5ace44b5da5455b6aee9c4d8cbf0b4e/matlab/manipTrajTransformTimeScaling.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.565224375315419}}
{"text": "% script that demonstrates use of 2d scattering\n\nclear; close all;\nx = uiuc_sample;\nfilt_opt.J = 7;\nfilt_opt.L = 8;\nscat_opt.oversampling = 0;\n[Wop, filters] = wavelet_factory_2d(size(x), filt_opt, scat_opt);\n\n%%\nprofile on;\ntic;\n[Sx, Ux] = scat(x, Wop);\ntoc;\nprofile off;\nprofile viewer;", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/test/core/test_scat_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5651766533159538}}
{"text": "function p_homo = homogenize(p,y);\n%HOMOGENIZE Homogenize polynomial\n%\n% f = homogenize(p,x)\n\ndeg   = degree(p);\ndeg_y = degree(y);\nif rem(deg,deg_y)~=0\n    error('The degree of the homogenizer is not an even fraction of deg(p).');\nend\n\nif 0\n    error('The homogenizer must be homogenious.');\nend\n\np_variables = getvariables(p);\np_homo = getbasematrix(p,0)*y^(deg/deg_y);\nfor i = 1:length(p_variables);\n    monom = recover(p_variables(i));\n    if degree(monom)<deg\n        power = (deg-(degree(monom)))/deg_y;\n        p_homo = p_homo + getbasematrix(p,p_variables(i))*monom*y^power;\n    else\n       p_homo = p_homo + getbasematrix(p,p_variables(i))*monom;\n   end;\nend\n% Reset info about conic terms\np_homo.conicinfo = [0 0];  ", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/extras/@ncvar/homogenize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169631, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5651570885112744}}
{"text": "function [gal] = km32gal(km3)\n% Convert volume from cubic kilometers to US liquid gallons. \n% Chad Greene 2012\ngal = km3*264172052360;", "meta": {"author": "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/km32gal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5651570816101569}}
{"text": "function guv = evaluate_log_posterior_grad(this, uv)\n%EVALUATE_LOG_POSTERIOR computes the gradient of the log-posterior\n%   (negative energy) wrt the flow fields UV \n%   Actually only proportional to the log posterior since the variance of neither the\n%   spatial nor the data terms is considered\n%\n%   This is a member function of the class 'hs_optical_flow'. \n%\n%   Author: Deqing Sun, Department of Computer Science, Brown University\n%   Contact: dqsun@cs.brown.edu\n%   $Date: 2007-11-30 $\n%   $Revision: $\n%\n% Copyright 2007-2010, Brown University, Providence, RI. USA\n% \n%                          All Rights Reserved\n% \n% All commercial use of this software, whether direct or indirect, is\n% strictly prohibited including, without limitation, incorporation into in\n% a commercial product, use in a commercial service, or production of other\n% artifacts for commercial purposes.     \n%\n% Permission to use, copy, modify, and distribute this software and its\n% documentation for research purposes is hereby granted without fee,\n% provided that the above copyright notice appears in all copies and that\n% both that copyright notice and this permission notice appear in\n% supporting documentation, and that the name of the author and Brown\n% University not be used in advertising or publicity pertaining to\n% distribution of the software without specific, written prior permission.        \n%\n% For commercial uses contact the Technology Venture Office of Brown University\n% \n% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO\n% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n% FITNESS FOR ANY PARTICULAR PURPOSE.  IN NO EVENT SHALL THE AUTHOR OR\n% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n% THIS SOFTWARE. \n\n% Spatial term\nS       = this.spatial_filters;\ngu1     = zeros(size(uv,1), size(uv,2));\ngv1     = gu1;\n\nfor i = 1:length(S)\n\n    u_ = conv2(uv(:,:,1), S{i}, 'valid');\n    v_ = conv2(uv(:,:,2), S{i}, 'valid');\n\n    Si = reshape(S{i}(end:-1:1), size(S{i}));\n    \n    if isa(this.rho_spatial_u{i}, 'robust_function')        \n        u_ = -reshape(deriv(this.rho_spatial_u{i}, u_(:)), size(u_));                \n        v_ = -reshape(deriv(this.rho_spatial_v{i}, v_(:)), size(v_));                        \n    elseif isa(this.rho_spatial_u{i}, 'gsm_density')\n        u_ = reshape(evaluate_log_grad(this.rho_spatial_u{i}, u_(:)'), size(u_));                \n        v_ = reshape(evaluate_log_grad(this.rho_spatial_v{i}, v_(:)'), size(v_));                        \n    else\n        error('evaluate_log_posterior: unknown rho function!');\n    end;\n    \n    gu1 = gu1+conv2(u_, Si, 'full');\n    gv1 = gv1+conv2(v_, Si, 'full');    \nend;\n\ngu2     = zeros(size(uv,1), size(uv,2));\ngv2     = gu2;\n\n% Data term\n[It Ix Iy] = partial_deriv(this.images, uv, this.interpolation_method);    \n    \nif isa(this.rho_data, 'robust_function')\n    temp   = -reshape(deriv(this.rho_data, It(:)), size(It));\n    \nelseif isa(this.rho_data, 'gsm_density')    \n    temp   = reshape(evaluate_log_grad(this.rho_data, It(:)'), size(It));\nelse\n    error('evaluate_log_posterior: unknown rho function!');\nend;\n\ngu2     = temp.*Ix;\ngv2     = temp.*Iy;\n\nguv = cat(3, gu2+this.lambda*gu1, gv2+this.lambda*gv1);\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/spaceTime/optflow_deqing/@hs_optical_flow/evaluate_log_posterior_grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5651570711441097}}
{"text": "% RESAMPLE_SCAT Resample a scattering transform.\n%\n% Usages\n%    S = RESAMPLE_SCAT(S, res, preserve_energy)\n%\n% Input\n%    S (cell): A scattering transform.\n%    res (int): The desired resolution.\n%    preserve_energy (bool, optional): If set, renormalizes each resampled\n%       coefficient so that its energy (sum of squares) remains the same.\n%\n% Output\n%    S (cell): The scattering transform with each coefficient resampled to\n%       resolution res.\n%\n% Description\n%    Each coefficient in S is resampled to have the proper resolution. If the\n%    desired resolution is finer, the signal will be interpolated. If the \n%    resolution is coarser, it will be downsampled.\n%\n% See also\n%    LOG_SCAT\n\nfunction S = resample_scat(S, res, preserve_energy)\n\tif nargin < 3\n\t\tpreserve_energy = true;\n\tend\n\n\tif iscell(S)\n\t\tfor m = 0:length(S)-1\n\t\t\tS{m+1} = resample_scat(S{m+1}, res, preserve_energy); % self-call\n        end\n\t\treturn;\n    end\n\t\n\tfor p1 = 1:length(S.signal)\n\t\tres1 = 0;\n\t\tif isfield(S.meta,'resolution')\n\t\t\tres1 = S.meta.resolution(p1);\n\t\tend\n\t\tsz_orig = size(S.signal{p1});\n\t\tS.signal{p1} = interpft(S.signal{p1}, 2^(-res+res1)*size(S.signal{p1},1));\n\t\tsz_new = sz_orig;\n\t\tsz_new(1) = sz_orig(1)*2^(-res+res1);\n\t\tS.signal{p1} = reshape(S.signal{p1}, sz_new);\n\t\tif preserve_energy\n\t\t\tS.signal{p1} = S.signal{p1}*2^(-(-res+res1)/2);\n\t\tend\n\t\tS.meta.resolution(p1) = res;\n\tend\nend\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/scatutils/resample_scat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920211198871, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5651164404149723}}
{"text": "function [kPa] = Torr2kPa(Torr)\n% Convert pressure from torr to kilopascals\n% Chad Greene 2012\nkPa = Torr*.133322;", "meta": {"author": "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/Torr2kPa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5651164386566734}}
{"text": "\nfunction A = sim_genVARModelFromEq(expr,morder)\n% \n% Generate VAR model coefficient matrix from text-based system of equations\n% The model can then be realized using the tvarsim() function modified from \n% ARfit [2].\n% If the expr specification requests time-varying coefficients, then this\n% function will return inline function placeholders for coefficients, which\n% can be evaluated to actual coefficient matrices by sim_genTVARcoeffs().\n%\n% Inputs:\n%\n%   expr:       A cell vector containing each equation as a string (one\n%               equation per cell element). See Examples for format.\n%   morder:     The model order\n% \n% Outputs:\n%\n%   A:          VAR[p] model coefficients in format A=[A1,A2, ... Ap] where\n%               p = morder. Ai is the M x M coefficient matrix for lag i.\n%\n% Example1: generate a static VAR[3] model from a (text-based) system of equations\n%\n% expr = { ...\n%     'x1(t) = 0.9*x1(t-1)  + 0.3*x2(t-2)  + e1(t)' ...\n%     'x2(t) = 1.3*x2(t-1)  + -0.8*x2(t-2) + e2(t)' ...\n%     'x3(t) = 0.3*x1(t-2)  + 0.6*x2(t-1)  + e3(t)' ...\n%     'x4(t) = -0.7*x4(t-3) + -0.7*x1(t-3) + 0.3*x5(t-3) + e4(t)' ...\n%     'x5(t) = 1*x5(t-1)    + -0.4*x5(t-2) + 0.3*x4(t-2) + e5(t)' ...\n%     };\n% A = sim_genVARModelFromEq(expr,3)\n% A =\n%     0.9000         0         0         0         0         0    0.3000         0         0         0         0         0         0         0         0\n%          0    1.3000         0         0         0         0   -0.8000         0         0         0         0         0         0         0         0\n%          0    0.6000         0         0         0    0.3000         0         0         0         0         0         0         0         0         0\n%          0         0         0         0         0         0         0         0         0         0   -0.7000         0         0   -0.7000    0.3000\n%          0         0         0         0    1.0000         0         0         0    0.3000   -0.4000         0         0         0         0         0\n%\n% % Now generate some data from the model (this requires arsim.m or tvarsim.m)\n%\n% M   = size(A,1);        % number of variables\n% Nl  = 1000;             % length of each trial\n% Nr  = 100;              % number of trials\n% C = eye(M);             % specify the covariance matrix\n% data = zeros(M,Nl,Nr);  \n% for tr=1:Nr             % simulate data from VAR model\n%    data(:,:,tr) = arsim(zeros(1,M),A,C,Nl)';\n% end\n% eegplot(data,'srate',1); % visualize the simulated data\n%\n%\n% Example 2: generate a time-varying VAR[2] model\n% \n%\n% See Also: tvarsim(), est_fitMVAR(), sim_genTVARcoeffs()\n%\n% References:\n%\n% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):\n%   Theoretical Handbook and User Manual. Section 6.5.1 \n%   Available at: http://www.sccn.ucsd.edu/wiki/Sift\n% [2] Schneider T, Neumaier A (2001) Algorithm 808: ARfit---a matlab package\n%   for the estimation of parameters and eigenmodes of multivariate \n%   autoregressive models. ACM Transactions on Mathematical Software 27:58-65\n%   http://www.gps.caltech.edu/~tapio/arfit/\n%\n% Author: Tim Mullen 2010, SCCN/INC, UCSD. \n% Email:  tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n\nNvars = length(expr);\n\nif nargin>1\n    % create cell array of zeros\n    A = repmat({0},Nvars,Nvars*morder);\nend\n\nfnstr ='{[\\S]+}';\n\nfor i = 1:Nvars\n    eq = expr{i};\n    \n    % Identify all inline functions\n    % Specifically, we extract any string f(x) encapsulated by \n    % curly-brackets '{f(x)}'\n    [matchstr] = regexp(eq,'{[\\S]+}','match');\n    \n    % replace each function with an identifier '$i' designating that the\n    % ith equation will go here\n    for fi=1:length(matchstr)\n        eq = strtrim(strrep(eq,matchstr{fi},sprintf('$%d',fi)));\n    end\n    \n    % remove all whitespace\n    eq(isspace(eq))=[];\n%     \n%     for fi=1:length(matchstr)\n%         eq = [eq(1:matchstart(fi)-1) sprintf('$%d',fi) eq(matchend(fi)+1:end)];\n%     end\n    \n    terms = regexp(eq,'([=+*])','split');\n    \n    row = str2double(regexp(terms{1},'(\\d+)','match'));\n    for k = 2:2:length(terms)-1\n        vars = regexp(terms{k+1},'(\\d+)','match');\n        vars = str2num(char(vars));\n        col = vars(1)+(vars(2)-1)*Nvars;\n        \n        if strcmpi(terms{k}(1),'$')\n            % term is a function expression\n            A{row,col} = matchstr{str2double(terms{k}(2))}(2:end-1);\n        elseif ~isnan(str2double(terms{k}))\n            % term is a number\n            A{row,col} = str2double(terms{k});\n        else\n            % term is an expression to be directly evaluated\n            A{row,col} = eval(terms{k});\n        end\n    end\nend\n\n% if A is all numeric, convert to standard array\nif all(cellfun(@(x)isnumeric(x),A))\n    A = cell2mat(A);\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/sim/sim_genVARModelFromEq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519376, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5651164352999716}}
{"text": "function A = four_corners(m,n)\n%FOUR_CORNERS Construct a m x n sparse matrix with ones in each of its four\n%corners.\n%\n% t = four_corners(m,n);\n%\n% Inputs:\n%  m,n  the dimension of the matrix requested\n% Outputs:\n%  A  the sparse matrix with ones in their four corners\n%\n\nA = sparse(m,n);\nA(1,1) = 1;\nA(m,1) = 1;\nA(1,n) = 1;\nA(m,n) = 1;\n\nend\n\n", "meta": {"author": "odedstein", "repo": "sgi-introduction-course", "sha": "52278fc3b3dab52febb110a1a09d770f46b5e417", "save_path": "github-repos/MATLAB/odedstein-sgi-introduction-course", "path": "github-repos/MATLAB/odedstein-sgi-introduction-course/sgi-introduction-course-52278fc3b3dab52febb110a1a09d770f46b5e417/010_sparse_matrices/solution/four_corners.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.5651164253098145}}
{"text": "function u=dimsplit(fflux,gflux,u0,x,y,T,nstep)\n%%\n%  Solves the equation u_t + fflux(u)_x  + gflux(u)_y = 0 by operator\n%  splitting.  u0 and a must the size of x.\n%\n%  Output is a matrix of size [length(x),((T/dt)+1)] . \n%\n\n%% Initial setup\nh=path;\npath(h,'../Example2_5');\nNt=nstep;\ndt=T/Nt;\ndx=x(2)-x(1); m=length(x);\ndy=y(2)-y(1); n=length(y);\nu=zeros(m,n,Nt+1);\nu(:,:,1)=u0;\n\n%% Dimensional splitting\n%  uses the LxF method in each direction.\nfor i=1:Nt,\n\tu1=LxF(fflux,u(:,:,i),dt,dx,1,'periodic');      % Conservation in x-dir\n\tu(:,:,i+1)=LxF(gflux,u1,dt,dy,2,'periodic');    % Conservation in y-dir\nend;\n\npath(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/OperatorSplitting/Chapter2/Example2_7/dimsplit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5651164170779565}}
{"text": "%ESTIMATERIGIDTRANSFORM  Computes an optimal affine transformation between two 2D point sets\n%\n%     M = cv.estimateRigidTransform(src, dst)\n%     M = cv.estimateRigidTransform(src, dst, 'OptionName', optionValue, ...)\n%\n% ## Input\n% * __src__ First input 2D point set stored in a cell array of 2-element\n%   vectors `{[x,y], ...}`, or first image (8-bit numeric array, 1- or\n%   3-channels).\n% * __dst__ Second input 2D point set of the same size and the same type as\n%   `src`, or second image (8-bit numeric array, 1- or 3-channels).\n%\n% ## Output\n% * __M__ output 2x3 affine transformation `[A|b]` matrix (see below).\n%\n% ## Options\n% * __FullAffine__ If true, the function finds an optimal affine transformation\n%   with no additional resrictions (6 degrees of freedom). Otherwise, the\n%   class of transformations to choose from is limited to combinations of\n%   translation, rotation, and uniform scaling (4 degrees of freedom).\n%   default false\n%\n% The function finds an optimal affine transform `[A|b]` (a 2x3 floating-point\n% matrix) that approximates best the affine transformation between:\n%\n% * Two point sets\n% * Two raster images. In this case, the function first finds some features in\n%   the `src` image and finds the corresponding features in `dst` image. After\n%   that, the problem is reduced to the first case.\n%\n% In case of point sets, the problem is formulated as follows: you need to\n% find a 2x2 matrix `A` and 2x1 vector `b` so that:\n%\n%     [A*|b*] = argmin_{[A|b]} sum_{i}(|| dst{i} - A*src{i}' - b ||^2)\n%\n% where `src{i}` and `dst{i}` are the i-th points in `src` and `dst`,\n% respectively. `[A|b]` can be either arbitrary (when `FullAffine=true`) or\n% have a form of:\n%\n%     [ a11, a12, b1;\n%      -a12, a11, b2 ]\n%\n% when `FullAffine=false`.\n%\n% See also: cv.estimateAffine2D, cv.estimateAffinePartial2D,\n%  cv.getAffineTransform, cv.getPerspectiveTransform, cv.findHomography,\n%  imregtform\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/estimateRigidTransform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5651111119918312}}
{"text": "function a = band(a,p,q)\n%BAND         Extract band from matrix a, lower bandwidth p, upper bandwidth q\n%   if parameter q is omitted, q:=p\n%\n%   c = band(a,p,q)\n%\n\n% written  09/28/01     S.M. Rump\n% modified 04/04/04     S.M. Rump  set round to nearest for safety\n%                                    improved performance\n% modified 04/06/05     S.M. Rump  rounding unchanged\n%\n\n  if nargin<3\n    q = p;\n  end\n\n  a = tril(triu(a,-p),q);\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/slope/@slope/band.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5651111068308089}}
{"text": "function [ edge_data, node_num2 ] = tet_mesh_order4_to_order10_size ( ...\n  tetra_num, tetra_node1, node_num1 )\n\n%*****************************************************************************80\n%\n%% TET_MESH_ORDER4_TO_ORDER10_SIZE sizes a quadratic tet mesh from a linear one.\n%\n%  Discussion:\n%\n%    A quadratic (10 node) tet mesh can be derived from a linear\n%    (4 node) tet mesh by interpolating nodes at the midpoint of\n%    every edge of the mesh.\n%\n%    The mesh is described indirectly, as the sum of individual\n%    tetrahedrons.  A single physical edge may be a logical edge of\n%    any number of tetrahedrons.  It is important, however, that a\n%    new node be created exactly once for each edge, assigned an index,\n%    and associated with every tetrahedron that shares this edge.\n%\n%    This routine handles that problem.\n%\n%    The primary amount of work occurs in sorting a list of 6 * TETRA_NUM\n%    data items, one item for every edge of every tetrahedron.  Each\n%    data item records, for a given tetrahedron edge, the global indices\n%    of the two endpoints, the local indices of the two endpoints,\n%    and the index of the tetrahedron.\n%\n%    Through careful sorting, it is possible to arrange this data in\n%    a way that allows the proper generation of the interpolated nodes.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 November 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer TETRA_NUM, the number of tetrahedrons in the\n%    linear mesh.\n%\n%    Input, integer TETRA_NODE1(4,TETRA_NUM), the nodes that make up\n%    each tetrahedron in the linear mesh.\n%\n%    Input, integer NODE_NUM1, the number of nodes for the linear mesh.\n%\n%    Output, integer EDGE_DATA(5,6*TETRA_NUM), edge data.\n%\n%    Output, integer NODE_NUM2, the number of nodes for the quadratic mesh.\n%\n\n%\n%  Step 1.\n%  From the list of nodes for tetrahedron T, of the form: (I,J,K,L)\n%  construct the six edge relations:\n%\n%    (I,J,1,2,T)\n%    (I,K,1,3,T)\n%    (I,L,1,4,T)\n%    (J,K,2,3,T)\n%    (J,L,2,4,T)\n%    (K,L,3,4,T)\n%\n%  In order to make matching easier, we reorder each pair of nodes\n%  into ascending order.\n%\n  for tetra = 1 : tetra_num\n\n    i = tetra_node1(1,tetra);\n    j = tetra_node1(2,tetra);\n    k = tetra_node1(3,tetra);\n    l = tetra_node1(4,tetra);\n\n    [ a, b ] = i4i4_sort_a ( i, j );\n\n    edge_data(1:5,6*(tetra-1)+1) = [ a, b, 1, 2, tetra ]';\n\n    [ a, b ] = i4i4_sort_a ( i, k );\n\n    edge_data(1:5,6*(tetra-1)+2) = [ a, b, 1, 3, tetra ]';\n\n    [ a, b ] = i4i4_sort_a ( i, l );\n\n    edge_data(1:5,6*(tetra-1)+3) = [ a, b, 1, 4, tetra ]';\n\n    [ a, b ] = i4i4_sort_a ( j, k );\n\n    edge_data(1:5,6*(tetra-1)+4) = [ a, b, 2, 3, tetra ]';\n\n    [ a, b ] = i4i4_sort_a ( j, l );\n\n    edge_data(1:5,6*(tetra-1)+5) = [ a, b, 2, 4, tetra ]';\n\n    [ a, b ] = i4i4_sort_a ( k, l );\n\n    edge_data(1:5,6*(tetra-1)+6) = [ a, b, 3, 4, tetra ]';\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:2; the routine we call here\n%  sorts on the full column but that won't hurt us.\n%\n%  What we need is to find all cases where tetrahedrons share an edge.\n%  By sorting the columns of the EDGE_DATA array, we will put shared edges\n%  next to each other.\n%\n  edge_data = i4col_sort_a ( 5, 6*tetra_num, edge_data );\n%\n%  Step 3. All the tetrahedrons which share an edge show up as consecutive\n%  columns with identical first two entries.  Figure out how many new\n%  nodes there are, and allocate space for their coordinates.\n%\n  node_num2 = node_num1;\n\n  n1_old = -1;\n  n2_old = -1;\n\n  for edge = 1 : 6 * tetra_num\n    n1 = edge_data(1,edge);\n    n2 = edge_data(2,edge);\n    if ( n1 ~= n1_old | n2 ~= n2_old )\n      node_num2 = node_num2 + 1;\n      n1_old = n1;\n      n2_old = n2;\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_order4_to_order10_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.5651110996493107}}
{"text": "\nclassdef (Abstract) FilterClass\n    % FilterClass:  Methods for filtering data which can be inherited by other models\n    % Options:\n    %   Smoothing Filter\n    %     Type                 Type of filter\n    %                              - gaussian\n    %                              - median\n    %                              - spline\n    %                              - polynomial\n    %     Dimension            In which dimensions to apply the filter\n    %                               -2D\n    %                               -3D\n    %     size(x,y,z)          Extent of filter in # of voxels\n    %                               For gaussian, it's FWHM\n    %                               For median, it's number of voxels\n    %     order                Order of the polynomial fitting and the 'amount of smoothness' for spline fitting\n    \n    properties\n        % Model options\n        buttons ={'PANEL','Smoothing filter',6,...\n            'Type',{'polynomial','gaussian','median','spline'},...\n            'Dimension',{'3D','2D'},...\n            'size x',3,...\n            'size y',3,...\n            'size z',3,...\n            'order',6};\n        options = struct(); % structure filled by the buttons. Leave empty in the code\n    end\n    \n    methods\n        % Constructor\n        function obj = FilterClass()\n        end\n\n        function  obj = UpdateFields(obj)\n            % Disable/enable some options --> Add ### to the button\n            % Name you want to disable\n            disablelist = {'size x','size y','size z','order'};\n            switch  obj.options.Smoothingfilter_Dimension\n                case {'2D'}\n                    disable = [false false true true];\n                    obj.options.Smoothingfilter_sizez=0;\n                otherwise\n                    disable = [false false false true];\n            end\n            % for spline, only 1 value for the amount of smoothness  (user 'order' field) and 3D\n            if strcmp(obj.options.Smoothingfilter_Type,{'spline'})\n                disable = [true true true false];\n            end\n            % for polynomial, now polynomial fitting works for both 2D and\n            % 3D cases\n            if strcmp(obj.options.Smoothingfilter_Type,{'polynomial'})\n                disable = [true true true false];\n                \n            end\n            \n            for ll = 1:length(disablelist)\n                indtodisable = find(strcmp(obj.buttons,disablelist{ll}) | strcmp(obj.buttons,['##' disablelist{ll}]));\n                if disable(ll)\n                    obj.buttons{indtodisable} = ['##' disablelist{ll}];\n                else\n                    obj.buttons{indtodisable} = [disablelist{ll}];\n                end\n            end\n        end\n        \n        \n        function FitResult = fit(obj,data,size)\n            switch obj.options.Smoothingfilter_Type\n                case {'gaussian'}\n                    FitResult.Filtered=obj.gaussFilt(data.Raw,size); %smoothed\n                case {'median'}\n                    FitResult.Filtered=obj.medianFilt(data.Raw,size); %smoothed\n                case {'spline'}\n                    FitResult.Filtered=obj.splineFilt(data.Raw,obj.options.Smoothingfilter_order); %smoothed\n                case {'polynomial'}\n                    FitResult.Filtered=obj.polyFilt(data,obj.options.Smoothingfilter_order); %smoothed\n            end\n        end\n        % Gaussian filter\n        function filtered = gaussFilt(obj,data,fwhm)\n            % Apply a Gaussian filter (2D or 3D)\n            % fwhm is a 2 or 3-element vector of positive numbers\n            sigmaPixels = fwhm2sigma(fwhm); %Full width half max of desired gaussian kernel (in #voxels) converted to sigma of Gaussian\n            if(sigmaPixels(3)==0 || strcmp(obj.options.Smoothingfilter_Dimension,'2D')) %for the 2D case\n                filtered = imgaussfilt(data,sigmaPixels(1:2));\n            else\n                filtered = imgaussfilt3(data,sigmaPixels);\n                \n            end\n        end\n        \n        %Median filter\n        function filtered =medianFilt(obj,data,s)\n            % Apply a median filter (2D or 3D)\n            % s is a 3-element vector of positive numbers (voxels)\n            if(s(3)==0 || strcmp(obj.options.Smoothingfilter_Dimension,'2D')) %for the 2D case, if the volume is 3D, have to do each slice separately\n                if(ndims(data)==2)\n                    filtered = medfilt2(data,s(1:2));\n                else\n                    filtered=zeros(size(data));\n                    for i=1:size(data,3)\n                        filtered(:,:,i)=medfilt2(data(:,:,i),s(1:2));\n                    end\n                end\n            else\n                filtered = medfilt3(data,s);\n            end\n        end\n        \n        %Spline filter\n        function filtered =splineFilt(obj,data,S)\n            % Apply a spline filter (2D or 3D)\n            s=S(1); %just 1 values for the smoothness\n            if(strcmp(obj.options.Smoothingfilter_Dimension,'2D')) %if want 2D smoothing\n                if(ndims(data)==2) %if a 2D volume\n                    filtered = smoothn(data,s);\n                else %if a 3D volume, do each slice separately\n                    filtered=zeros(size(data));\n                    for i=1:size(data,3)\n                        filtered(:,:,i)=smoothn(data(:,:,i),s);\n                    end\n                end\n            else\n                filtered = smoothn(data,s);\n            end\n            \n            %filtered = smoothn(data,'robust');\n        end\n        \n        %% Polynomial filter\n        % for the fitting to work better, a mask should be provided, it's\n        % one of the rare methods that needs to know what the mask was and\n        % only fir in there\n        function filtered=polyFilt(obj,data,order)\n            % Apply a polynomial fit of the specified order (in 2D)\n            if(ndims(data.Raw)==2) %if a 2D volume\n                if isfield(data,'Mask') && (~isempty(data.Mask))\n                    filtered = poly_fit(data.Raw,order,data.Mask);\n                else\n                    filtered = poly_fit(data.Raw,order);\n                end\n                % if a 3D volume, use 2D or 3D fit according to the selection of dimension:\n                % 1. Perform each slice separately in 2D poly fit; OR\n                % 2. Perform 3D poly fit\n            else\n                filtered=zeros(size(data.Raw));\n                if strcmp(obj.options.Smoothingfilter_Dimension,'2D')\n                    for i = 1:size(data.Raw,3)\n                        if isfield(data,'Mask') && (~isempty(data.Mask))\n                            filtered(:,:,i) = poly_fit(data.Raw(:,:,i),order,data.Mask(:,:,i));\n                        else\n                            filtered(:,:,i) = poly_fit(data.Raw(:,:,i),order);\n                        end\n                    end\n                    \n                elseif isfield(data,'Mask') && (~isempty(data.Mask))\n                    filtered = polyfit_3D(data.Raw,order,data.Mask);\n                else\n                    filtered = polyfit_3D(data.Raw,order);\n                end\n            end\n        end\n        \n    end\n    \n    \n    \nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Common/FilterClass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.56510508928275}}
{"text": "function Main()\n% This program is a stand-alone toy example of radiation treatment planning\n% (RTP) optimization for a brain tumor case.\n%     The program generates a toy patient head model using scaled and shifted\n% ellipsoids and p-norm sublevel sets to represent all the volumes of\n% interest (VOIs), including skin, eyes, optic nerves, brain stem, a tumor\n% and artificial \"shell\" around the tumor. These VOI sublevel sets are then\n% discretized into PointClouds, by retaining the points in a discrete 3-D\n% grid of volume elements (voxels) that lie in the 1-sublevel set of the \n% VOI's p-norm model.\n%     Then we compute candidate beam directions by firing beams at random \n% points on the tumor surface from a set of about 150 nodes, located \n% uniformly in a spherical region of radius 80cm from the patient's head.\n%     Then we compute the dose vectors associated with each beam in each of\n% the VOIs, by evaluating a dose function in a cylindrical region around each\n% beam direction. The dose function is a crude model of the roll-off with\n% depth, and radial diffusion or scatter. For each candidate beam, this \n% rolloff/scatter function is evaluated for each voxel in each VOI. Thus\n% each beam results in a column of the patient dose matrix.\n% Finally, we set the min and max dosages for each VOI.\n%     We then pass the dose matrices and min and max specs to one of two\n% solvers (CPLEX or ADMM), which find the optimal set of beams and\n% intensities (beam weights) for this patient case. This is the optimal\n% \"plan\". The optimization formulation is based on a problem from the\n% Stanford EE364b final exam from 2011, by Stephen Boyd and Eric Chu.\n%     Then we visualize the optimal plan by plotting the dose levels for \n% all the voxels of each VOI, and the dose volume histograms.\n%     The program consists of this Main() function and several \"classes\":\n% (1) Patient: cell array of VOIs, names, etc\n% (2) VOI: p-norm model and associated point cloud and boundary, dose specs\n% (3) Beams: beam heads,tails,dose vector computation + nodes + collimators\n% (4) Model: p-norm models and gradients\n% (5) Point Cloud & 3-D geometry functions\n% (6) Optimizer functions: CPLEX wrapper and ADMM solver (ala EE364b)\n%\n% Reference: \n% H. Hindi, \"A Tutorial on Optimization Methods for Cancer Radiation\n% Treatment Planning,\" Proc. American Contr. Conf, 2013.\n%\n% Written by Haitham Hindi, 2012/01/18\n%\n% DISCLAIMER: This code is intended for algorithm research purposes\n% only!! Author makes no claims as to the realism, accuracy, or correctness \n% of ANY part of this code, including (but not limited to): \n% patient anatomy and dimensions; plan safety; beam weights,doses,physics;\n% dose units, dose specs; plan quality, evaluation metrics. The author is\n% an engineer with no medical training whatsoever! This code is supplied\n% as-is, with no guarantee of correctness, and the author accepts no \n% responsibility for any damage or false conclusions from the use of this\n% code. Of course, we would appreciate hearing about any bugs you might find.\n\n    clear, clc, close all\n    rng('default');\n    rng(2);\n\n    %====================================================\n    % data for patient and beams\n    %====================================================\n    % patient specs\n    PatientName     = 'Toy Brain Tumor Case';\n    PatientThetaxyz = [pi/2;0;0];\n    PatientOffset   = [0;0;0];\n    PatientAxLims   = [-15 15];\n\n    % VOI specs (VOIs are scaled shifted p-norm sublevel sets)\n    Target=1;Shell=2;BrStm=3;EyeL=4;EyeR=5;OptNrvL=6;OptNrvR=7;Skin=8;\n    VoxSizeSkin      = 1;\n    VoxSizeOrgans    = 0.2;%0.15%0.113;\n    SampFactorSkin   = 1;\n    SampFactorOrgans = 1;\n    VOINames      ={'Target','Shell','BrStm','EyeL','EyeR','OptNrvL','OptNrvR','Skin'};\n    dmaxs         =[50      , 25    ,20     , 20   , 20   , 20      , 20      , 30];\n    dmins         =[40      , 0     , 0     ,  0   ,  0   ,  0      ,  0      ,  0];\n    VOINumbers    =[ 1,       2,      3,      4,     5,     6,        7,        8];\n    VOITypes      ={'v',     's',    'v',    'v',   'v',   'v',      'v',      's'};\n    VOIColors     ={'k',     'r',    'g',    'b',   'b',   'c',      'c',      'y'};\n    VOILineStyles ={'-',     '-',    '-',    '-',   '--',  '-',      '--',     '-'};\n    VOIVoxSizes   =[VoxSizeOrgans*ones(7,1);VoxSizeSkin];\n    VOISampFactors=[SampFactorOrgans*ones(7,1);SampFactorSkin];\n    VOIxyzScales  =[1.2*[1;1;1],1.56*[1;1;1],[1.5;1.5;6],1.7*[1;1;1],1.7*[1;1;1],[0.7;4;0.7],[0.7;4;0.7],[11;11;11]];\n    VOIpNorms     =[2;  2;  3;  2;  2;  2;  2;  3];\n    VOIThetaxyz   =[[0;0;0],[0;0;0],[-pi/8;0;0],[0;0;0],[0;0;0],[pi/6;-pi/6;0],[pi/6;pi/6;0],[0;0;0]];\n    VOIOffsets    =[[3;-3;0],[3;-3;0],[0;-3;-5],[-4;8;4],[4;8;4],[-2;3;2],[2;3;2],[0;0;0]];\n    VOIHistBins   = 0:max(dmaxs)/50:1.4*max(dmaxs);\n\n    % beam specs\n    NPtsSphereParam = 7%8%18\n    NodeLocs = GetPointsOnUnitSphere1000(NPtsSphereParam);\n    NodeLocs = NodeLocs(find(NodeLocs(:,3)>=-0.6),:);% remove bottom (can't go under patient)\n    NodeLocs = NodeLocs(find(NodeLocs(:,2)<= 0.6),:);% remove front  (can't go through patient)\n    NodeLocs = 80*NodeLocs;% scale to 80cm radius\n    NNodes = size(NodeLocs,1)\n    NodesAxLims = 85*[-1 1 -1 1 -1 1];\n    Collimators = [5; 7.5; 10; 12.5; 15; 20; 25];%; 30; 35; 40; 50; 60];\n    Collimators = Collimators/10; % scale to cm\n    NCollimators= length(Collimators);\n    NBeamlets = 5;\n    NPtsPerAx = 50;\n    AxLength = 15;\n\n    %====================================================\n    % create patient and beams, solve optimization problem, visualize results\n    %====================================================\n    % get patient\n    disp(['Computing patient model...'])\n    Patient = PatientCreate();\n    Patient = PatientInit(Patient,PatientName,PatientAxLims,...\n                          VOINames,VOINumbers,VOITypes,VOIColors,VOILineStyles,...\n                          VOIVoxSizes,VOISampFactors,VOIHistBins,...\n                          VOIxyzScales,VOIpNorms,VOIThetaxyz,VOIOffsets);\n    Patient = PatientRotateTranslate(Patient,PatientThetaxyz,PatientOffset);\n\n    figure\n    PatientPlot(Patient)\n\n    % get beams\n    disp(['Computing beam directions...'])\n    Beams = BeamsCreate();\n    Beams = BeamsInit(Beams,NodeLocs,NodesAxLims,Collimators,NBeamlets,Patient.VOIs{Skin}.Model.f,Patient.VOIs{Target}.PointCloudBdy);\n\n    PlotDoseMapAxialRolloffAndRadialDiffusion(Collimators);\n    PlotPatientBeamDirectionsAndNodes(Patient,Beams);\n    %figure,hold on\n    %PatientPlot(Patient)\n    %[GridPts,AxPts] = GetGridPts(NPtsPerAx,AxLength);\n    %PlotFewRandomBeamDoseMaps(Beams.Tails,Beams.Heads,Beams.Widths,3,GridPts)\n\n    % compute dose matrices of all VOIs and set upper and lower bounds\n    Patient = PatientPrepareForOptimization(Patient,Beams,dmins,dmaxs);\n\n    % construct the Linear Program matrices and solve for optimal beam\n    % weights using CLEX or ADMM\n    Patient = PatientApplyOptimization(Patient);\n\n    % plot optimal beam weights, constraints, and dose volume histograms\n    PatientEvaluate(Patient);\n\nreturn\n\n%====================================================\n% Patient Class: mainly cell array of VOIs, names, axis limits\n%====================================================\nfunction Patient = PatientCreate()\n    Patient.Name     = [];\n    Patient.VOINames = [];\n    Patient.NumVOIs  = [];\n    Patient.VOIs     = [];\n    Patient.AxLims   = [];\n    Patient.xBeamWeights = [];\nreturn\n\nfunction Patient = PatientInit(Patient,PatientName,PatientAxLims,...\n                               VOINames,VOINumbers,VOITypes,VOIColors,VOILineStyles,...\n                               VOIVoxSizes,VOISampFactors,VOIHistBins,...\n                               VOIxyzScales,VOIpNorms,VOIThetaxyz,VOIOffsets)\n    Patient.Name = PatientName;\n    Patient.VOINames = VOINames;\n    Patient.NumVOIs =length(VOINames);\n    Patient.VOIs = {};\n    for i=1:Patient.NumVOIs\n        Modi            = ModelInit(ModelCreate(),VOIxyzScales(:,i),VOIpNorms(i));\n        VOIi            = VOIInit(VOICreate(),VOINames{i},VOINumbers(i),VOITypes{i},VOIColors{i},VOILineStyles{i},VOIVoxSizes(i),VOISampFactors(i),Modi,VOIHistBins);\n        Patient.VOIs{i} = VOIRotateTranslate(VOIi,VOIThetaxyz(:,i),VOIOffsets(:,i));\n    end\n    Patient.AxLims = PatientAxLims;\nreturn\n\nfunction Patient = PatientPrepareForOptimization(Patient,Beams,dmins,dmaxs)\n    for i=1:Patient.NumVOIs\n        Patient.VOIs{i} = VOIGetDoseAMatrix(Patient.VOIs{i},Beams);\n        Patient.VOIs{i} = VOISetDoseMinMax(Patient.VOIs{i},dmins(i),dmaxs(i));\n    end\nreturn\n\nfunction Patient = PatientApplyOptimization(Patient)\n    % construct LP matrices\n    A    = [];dmin = [];dmax = [];\n    for i=1:Patient.NumVOIs\n        A    = [A;Patient.VOIs{i}.ADose];\n        dmin = [dmin;Patient.VOIs{i}.DoseMin];\n        dmax = [dmax;Patient.VOIs{i}.DoseMax];\n    end\n    \n    % compute optimal beam weights\n    %%%Patient.xBeamWeights = OptimizeBeamsCPLEX(A,dmin,dmax);\n    Patient.xBeamWeights = OptimizeBeamsADMM(A,dmin,dmax);\n    \n    % compute resulting dose on each VOI\n    for i=1:Patient.NumVOIs\n        Patient.VOIs{i} = VOIGetDose(Patient.VOIs{i},Patient.xBeamWeights);\n    end\nreturn\n\nfunction PatientEvaluate(Patient)\n    figure,stem(Patient.xBeamWeights),title('Beam Weights')\n    figure,PatientPlotConstraints(Patient);\n    figure,PatientPlotDVH(Patient);\nreturn\n\nfunction Patient = PatientRotateTranslate(Patient,Thetaxyz,Offset)\n    for i=1:Patient.NumVOIs\n        Patient.VOIs{i} = VOIRotateTranslate(Patient.VOIs{i},Thetaxyz,Offset);\n    end\nreturn\n\nfunction Patient = PatientAffineTransform(Patient,A,b)\n    for i=1:Patient.NumVOIs\n        Patient.VOIs{i} = VOIAffineTransform(Patient.VOIs{i},A,b);\n    end\nreturn\n\nfunction PatientPlot(Patient)\n    hold on\n    for i=1:Patient.NumVOIs\n        VOIPlot(Patient.VOIs{i},Patient.AxLims);\n    end\n    title(Patient.Name),legend(Patient.VOINames)\n    xlabel('x'),ylabel('y'),zlabel('z')\n    view(127.5,30)\n    %view(3)\nreturn\n\nfunction PatientPlotConstraints(Patient)\n    nPlotsPerCol = ceil(Patient.NumVOIs/2);\n    for i=1:Patient.NumVOIs\n        subplot(nPlotsPerCol,2,i),VOIPlotMinMaxConstraints(Patient.VOIs{i});\n    end\nreturn\n\nfunction PatientPlotDVH(Patient)\n    hold on,title('DVHs'),grid on, axis([0,max(Patient.VOIs{1}.DVHBins),0,1.1])\n    for i=1:Patient.NumVOIs\n        [DVHi,Histi] = GetDVH(Patient.VOIs{i}.Dose,Patient.VOIs{i}.DVHBins);\n        plot(Patient.VOIs{i}.DVHBins,DVHi,Patient.VOIs{i}.Color);\n    end\n    legend(Patient.VOINames)\nreturn\n\nfunction PlotPatientBeamDirectionsAndNodes(Patient,Beams)\n    figure,hold on\n    PatientPlot(Patient)\n    PlotNodes(Beams.NodeLocs,Beams.NodesAxLims);\n    PlotBeams(Beams.Tails0,Beams.Heads,1);\n    figure,hold on\n    PatientPlot(Patient)\n    PlotBeams(Beams.Tails,Beams.Heads,1);\nreturn\n\n%====================================================\n% VOI Class: has name etc, point cloud model, point cloud, dose matrix, dose specs\n%====================================================\nfunction VOI = VOICreate()\n    VOI.Name          = [];\n    VOI.Number        = [];\n    VOI.Type          = [];\n    VOI.Color         = [];\n    VOI.LineStyle     = [];\n    VOI.VoxSize       = [];\n    VOI.SubSampFactor = [];\n    VOI.Model         = [];\n    VOI.PointCloud    = [];\n    VOI.PointCloudBdy = [];\n    VOI.ADose         = [];\n    VOI.DoseMin       = [];\n    VOI.DoseMax       = [];\n    VOI.Dose          = [];\n    VOI.DVHBins       = [];\nreturn\n\nfunction VOI = VOIInit(VOI,Name,Number,Type,Color,LineStyle,VoxSize,SubSampFactor,Model,HistBins)\n    VOI.Name          = Name;\n    VOI.Number        = Number;\n    VOI.Type          = Type;\n    VOI.Color         = Color;\n    VOI.LineStyle     = LineStyle;\n    VOI.VoxSize       = VoxSize;\n    VOI.SubSampFactor = SubSampFactor;    \n    VOI.Model         = Model;\n    VOI.PointCloud    = ModelToPointCloud(Model,VoxSize,SubSampFactor);\n    VOI.PointCloudBdy = ModelToPointCloudBdy(Model,VoxSize,SubSampFactor);\n    VOI.ADose         = [];\n    VOI.DoseMin       = [];\n    VOI.DoseMax       = [];\n    VOI.Dose          = [];\n    VOI.DVHBins       = HistBins;\nreturn\n\nfunction VOI = VOIAffineTransform(VOI,A,b)\n    VOI.Model         = ModelAffineTransform(VOI.Model,A,b);\n    VOI.PointCloud    = PointCloudAffineTransform(VOI.PointCloud,A,b);\n    VOI.PointCloudBdy = PointCloudAffineTransform(VOI.PointCloudBdy,A,b);\nreturn\n\nfunction VOI = VOIRotateTranslate(VOI,Thetaxyz,Offset)\n    VOI.Model         = ModelRotateTranslate(VOI.Model,Thetaxyz,Offset);\n    VOI.PointCloud    = PointCloudRotateTranslate(VOI.PointCloud,Thetaxyz,Offset);\n    VOI.PointCloudBdy = PointCloudRotateTranslate(VOI.PointCloudBdy,Thetaxyz,Offset);\nreturn\n\nfunction VOIPlot(VOI,AxisLimits)\n    Symbol = ['.',VOI.Color];\n    PlotCloud(VOI.PointCloudBdy,Symbol,AxisLimits);\nreturn\n\nfunction VOI = VOIGetDoseAMatrix(VOI,Beams)\n    if VOI.Type =='v' % full volume\n        VOI.ADose = GetBeamDosageVectors8(Beams.Tails,Beams.Heads,Beams.Widths,VOI.PointCloud);\n    else              % boundary shell\n        VOI.ADose = GetBeamDosageVectors8(Beams.Tails,Beams.Heads,Beams.Widths,VOI.PointCloudBdy);\n    end\n    disp(['NPts-',VOI.Name,'=',num2str(size(VOI.ADose,1))])\nreturn\n\nfunction VOI = VOISetDoseMinMax(VOI,dmin,dmax)\n    if VOI.Type =='v' % full volume\n        NPtsVOI = size(VOI.PointCloud,1);\n    else              % boundary shell\n        NPtsVOI = size(VOI.PointCloudBdy,1);\n    end\n    VOI.DoseMin = dmin*ones(NPtsVOI,1);\n    VOI.DoseMax = dmax*ones(NPtsVOI,1);\nreturn\n\nfunction VOI = VOIGetDose(VOI,xBeamWeights)\n    VOI.Dose = VOI.ADose*xBeamWeights;\nreturn\n\nfunction VOIPlotMinMaxConstraints(VOI)\n    nVox = length(VOI.DoseMin);\n    vox  = 1:nVox;\n    plot(vox,VOI.Dose,'*b',...\n         vox,VOI.DoseMin,'--r',...\n         vox,VOI.DoseMax,'--r')\n    axis([0 nVox  0  1.2*max(VOI.DoseMax) ])\n    legend(VOI.Name)\n    xlabel('voxels'),ylabel('dose')\nreturn\n\nfunction [DVH,Hist] = GetDVH(DosageProfile,Bins);\n    Hist = hist(DosageProfile,Bins);\n    Hist = Hist/sum(Hist);\n    HistCum = cumsum(Hist);\n    DVH = 1-HistCum;\n    DVH = [1;DVH(1:(length(DVH)-1))'];\nreturn\n\n%====================================================\n% Beam Class: has beams, nodes, collimators, dose computation\n%====================================================\nfunction Beams = BeamsCreate()\n    Beams.NodeLocs    = [];\n    Beams.NodesAxLims = [];\n    Beams.Collimators = [];\n    Beams.NBeamlets   = [];\n    Beams.Tails0= [];\n    Beams.Tails = [];\n    Beams.Heads = [];\n    Beams.Widths= [];\n    Beams.Nodes = []; \nreturn\n\nfunction Beams = BeamsInit(Beams,NodeLocs,NodesAxLims,Collimators,NBeamlets,SkinModelf,BdyTarget)\n    Beams.NodeLocs    = NodeLocs;\n    Beams.NodesAxLims = NodesAxLims;\n    Beams.Collimators = Collimators;\n    Beams.NBeamlets   = NBeamlets;\n    [BeamTails,BeamHeads,BeamTails0,BeamWidths,BeamNodes] = GetBeamDirections3(SkinModelf,BdyTarget,NodeLocs,Collimators,NBeamlets);\n    Beams.Tails0= BeamTails0;\n    Beams.Tails = BeamTails;\n    Beams.Heads = BeamHeads;\n    Beams.Widths= BeamWidths;\n    Beams.Nodes = BeamNodes;     \nreturn\n\nfunction [BeamTails,BeamHeads,BeamTails0,BeamWidths,BeamNodes] = GetBeamDirections3(SkinModelf,BdyTarget,NodeLocs,Collimators,NBeamlets)\n% compute candidate beam directions by firing from each Node, NBeamlets for each collimator size, onto random points on the target boundary\n% also calculate the point of entry into the patient (skin) boundary\n    NNodes = size(NodeLocs,1);\n    NColls = length(Collimators);\n    NBdyTar = size(BdyTarget,1);\n    NBisections = 10;\n    BeamTails0= zeros(NColls*NNodes*NBeamlets,3);\n    BeamTails = zeros(NColls*NNodes*NBeamlets,3);\n    BeamHeads = zeros(NColls*NNodes*NBeamlets,3);\n    BeamWidths= zeros(NColls*NNodes*NBeamlets,1);\n    BeamNodes = zeros(NColls*NNodes*NBeamlets,1);\n    % for each node\n    for i=1:NNodes\n        % make that node the tail for all collimators and beamlets\n        ii     = (i-1)*NColls*NBeamlets; \n        iiPlus = ii +  NColls*NBeamlets;\n        BeamTails0(ii+1:iiPlus,:) = repmat(NodeLocs(i,:),NColls*NBeamlets,1);\n        BeamNodes(ii+1:iiPlus,:)  = repmat(i,NColls*NBeamlets,1);\n        % for each collimator size\n        for j=1:NColls\n            % get NBeamlets random heads on target boundary\n            jj     = (j-1)*NBeamlets;\n            jjPlus = jj  + NBeamlets;\n            BeamHeads(ii+jj+1:ii+jjPlus,:) = BdyTarget(GetRandomIndecesNoRepetition(NBeamlets,NBdyTar),:);\n            BeamWidths(ii+jj+1:ii+jjPlus,:)= repmat(Collimators(j),NBeamlets,1);\n            % for each beamlet\n            for k=1:NBeamlets\n                % compute intersection with patient surface\n                BeamTails(ii+jj+k,:) = IntersectionSegmentLevelset(SkinModelf,BeamTails0(ii+jj+k,:),BeamHeads(ii+jj+k,:),NBisections);\n            end\n        end\n    end\nreturn\n\nfunction DosageVecs = GetBeamDosageVectors8(Tails,Heads,Widths,PointCloud)%,Collimators)\n% compute beam dose matrix on the given PointCloud, and quantizes it to accuracy 1e-3\n    NBeams     = size(Tails,1);\n    NPts       = size(PointCloud,1);\n    DosageVecs = zeros(NPts,NBeams);\n    disp(['Computing fake beam dosage vectors...'])\n    tic\n    for j=1:NBeams\n        BeamRadius = Widths(j)/2;\n        [DistOnRay,DistToRay]   = ComputeDistancesOnAxisAndToAxis(PointCloud,Tails(j,:)',Heads(j,:)');\n        [DistOnRaySelect,DistToRaySelect,SelectIdx] = SelectPositiveOnAxisFiniteOffAxis(DistOnRay,DistToRay);\n        DosageVecs(SelectIdx,j) = ComputeFakeBeamRolloffAndDiffusion(DistOnRaySelect,DistToRaySelect,BeamRadius);\n    end\n    DosageVecs = 1e-3 * round(1e3*DosageVecs); % quantize to 1e-3 accuracy, anything smaller gets set to zero\n    toc\nreturn\n\nfunction DoseVector = ComputeFakeBeamRolloffAndDiffusion(DistOnRay,DistToRay,BeamRadius,BeamDiffusionSigma)\n% for single beam, compute fake dose vector as:\n% - on-axis build-up then roll-off\n% - radial diffusion that broadens a bit with distance along beam direction\n    if nargin < 4, BeamDiffusionSigma = 0.2;end\n    % [build up then roll off] .* [convolve(rect_aperture,gaussian) = difference of erf's]\n    DoseVector =  (DistOnRay+0.02).^(1/8) .* exp(-(DistOnRay+0.02)/15).*... \n                  (  erf( (DistToRay+BeamRadius)./(BeamDiffusionSigma*(1+0.025*DistOnRay)) ) - ... \n                     erf( (DistToRay-BeamRadius)./(BeamDiffusionSigma*(1+0.025*DistOnRay)) )   );\nreturn\n\nfunction [DistOnRay,DistToRay] = ComputeDistancesOnAxisAndToAxis(PointCloud,tail,head)\n% vectorized computation of cylindrical coordinates along beam direction, for all points in VOI PointCloud,\n% used for calculation of VOI dose vector\n    NPts        = size(PointCloud,1);\n    x0              = tail;\n    u0              = ComputeUnitVector(head,tail);\n    PointCloudShift = PointCloud-repmat(x0',NPts,1);            \n    DistOnRay       = PointCloudShift*u0;\n    DistToRay       = sqrt( sum(  (PointCloudShift - DistOnRay*u0').^2  ,2)  );\nreturn\n\nfunction [DistOnRaySelect,DistToRaySelect,SelectIdx] = SelectPositiveOnAxisFiniteOffAxis(DistOnRay,DistToRay)\n% keep only points in the positive direction of the beam from the tail0 and\n% with distance no more than 5cm from the axis (since largest collimator is 6cm diameter = 3cm radius)\n    SelectIdx       = find( (DistOnRay > 0) & (DistToRay <=5) );\n    DistOnRaySelect = DistOnRay(SelectIdx);\n    DistToRaySelect = DistToRay(SelectIdx);\nreturn\n\nfunction u = ComputeUnitVector(head,tail)\n    u = (head-tail);\n    u = u/norm(u);\nreturn\n\nfunction IndexRand = GetRandomIndecesNoRepetition(NumSamples,NumTotal)\n% gets NumSamples random indexes from index set {1,...,NumTotal}, with no repetition\n    IndexPerm = randperm(NumTotal);\n    IndexRand = IndexPerm(1:NumSamples);\nreturn\n\nfunction PointOfInt = IntersectionSegmentLevelset(LevelSetf,tail,head,NBisections)\n% finds approximate intersection of segment with levelset of f using bisection\n% assumes head is inside level set and tail is outside; crashes if not.\n    if LevelSetf(tail(:)) <=1, error('tail already inside sublevel set!'),end\n    if LevelSetf(head(:)) > 1, error('head is not inside sublevel set!'),end\n    for r=1:NBisections\n        PointOfInt = 0.5*(tail+head);\n        % if PointOfInt inside the 1-level set\n        if LevelSetf(PointOfInt(:)) <=1 \n            head = PointOfInt; % move away from target\n        else\n            tail = PointOfInt; % move toward target\n        end\n    end\nreturn\n\nfunction PlotDoseMapAxialRolloffAndRadialDiffusion(Collimators)\n% plot first the roll off of beam intensity along the center of a beam\n% then plot a matrix of plots showing the roll off from the axis for all collimators\n    BeamRadius  = 0.75/2;\n    DistOnRay=0:0.1:50;\n    DistToRay=0;\n    DoseVector = ComputeFakeBeamRolloffAndDiffusion(DistOnRay,DistToRay,BeamRadius);\n    figure\n    plot(DistOnRay,DoseVector),grid\n    title('On axis beam roll off')\n    xlabel('on axis distance [cm]'),ylabel('normalized intensity')\n\n    DistOnRay=0:5:40;\n    DistToRay=0:0.1:8;\n    NColl = length(Collimators);\n    figure, \n    for j=1:NColl\n        Collj = Collimators(j);\n        subplot(4,3,j)\n        hold on\n        for i=1:length(DistOnRay)\n            DoseVector = ComputeFakeBeamRolloffAndDiffusion(DistOnRay(i),DistToRay,Collj/2);\n            plot(DistToRay,DoseVector), grid on\n        end\n        title(['Radial roll off ',num2str(Collj/2),'cm radius beam'])\n        xlabel('off axis distance [cm]'),ylabel('normalized intensity')\n    end\nreturn\n\nfunction PlotBeams(BeamTails,BeamHeads,LineWidth)\n% plots dotted lines as the directions of the beams (not the full dose vectors)\n    if nargin<3, LineWidth=4; end\n    for i=1:size(BeamTails,1)\n        h = plot3([BeamTails(i,1);BeamHeads(i,1)],...\n              [BeamTails(i,2);BeamHeads(i,2)],...\n              [BeamTails(i,3);BeamHeads(i,3)]);\n        %set(h,'LineWidth',4);\n        set(h,'LineWidth',LineWidth,'LineStyle',':');\n    end\nreturn\n\nfunction PlotFewRandomBeamDoseMaps(Tails,Heads,Widths,nBeamsToPlot,GridPts)\n% plot few random beams over the points GridPts - rarely do more than 3-5 \n% beams because can be really slow for a 100x100x100 grid\n    NBeams      = length(Widths);\n    Select      = GetRandomIndecesNoRepetition(nBeamsToPlot,NBeams);\n    TailsSelect = Tails(Select,:);\n    HeadsSelect = Heads(Select,:);\n    WidthsSelect= Widths(Select,:)\n    DosageVecs  = GetBeamDosageVectors8(TailsSelect,HeadsSelect,WidthsSelect,GridPts);\n    DosageVecsThresh = 0.01;\n    PlotDosageVecs2(DosageVecs,GridPts,DosageVecsThresh);\nreturn\n\nfunction PlotDosageVecs2(DosageVecs,GridPts,DosageVecsThresh)\n% plot the DosageVecs on the grid GridPoints, plotting only values greater\n% than DosageVecsThresh\n    if nargin < 3, DosageVecsThresh = 0;end\n    NDosageVecs = size(DosageVecs,2);\n    disp(['Plotting beam dosage vectors...'])\n    for j=1:NDosageVecs\n        iThresh = find(DosageVecs(:,j) > DosageVecsThresh);\n        scatter3(GridPts(iThresh,1),GridPts(iThresh,2),GridPts(iThresh,3),3,DosageVecs(iThresh,j),'filled');\n    end\nreturn\n\nfunction PlotNodes(NodeLocs,NodesAxLims)\n    hold on\n    plot3(NodeLocs(:,1),NodeLocs(:,2),NodeLocs(:,3),'r.'), grid on\n    xlabel('x'),ylabel('y'),zlabel('z')\n    axis(NodesAxLims)\n    %view(3)\nreturn\n\n%====================================================\n% Model Class: for generating point clouds as sublevel sets of scaled/shifted p-norms (1 < p < Inf)\n%====================================================\nfunction Model = ModelCreate()\n    Model.f = [];\n    Model.fGrad    = [];\n    Model.AxLims = [];\nreturn\n\nfunction Model = ModelInit(Model,xyzScale,p)\n    A            = diag(1./xyzScale);\n    Model.f      = @(x) norm(A*x,p); % scaled p-norm (where 1 < p < Inf)\n    Model.fGrad  = @(x) A*(sum((A*x).^p))^((1/p)-1)*(A*x).^(p-1); % grad of scaled p-norm\n    Model.AxLims = [xyzScale(1)*[-1 1] xyzScale(2)*[-1 1] xyzScale(3)*[-1 1]]; % range for plotting\nreturn\n\nfunction PointCloud = ModelToPointCloud(Model,VoxSize,SubSampFactor)\n    PointCloud = PointCloudFromf(Model.f,Model.AxLims,VoxSize);\nreturn\n\nfunction PointCloudBdy = ModelToPointCloudBdy(Model,VoxSize,SubSampFactor)\n    PointCloud    = PointCloudFromf(Model.f,Model.AxLims,VoxSize);\n    PointCloudBdy = PointCloudBdyFromfAndfGrad(Model.f,Model.fGrad,PointCloud,VoxSize,SubSampFactor);\nreturn\n\nfunction Model = ModelRotateTranslate(Model,Thetaxyz,Offset)\n    RotMtx = AnglesToRotMtx(Thetaxyz);\n    Model  = ModelAffineTransform(Model,RotMtx,Offset);\nreturn\n\nfunction Model = ModelAffineTransform(Model,A,b)\n    Model.f      = fAffineTransform(Model.f,A,b);\n    Model.fGrad  = fGradAffineTransform(Model.fGrad,A,b);\n    Model.AxLims = AxLimsAffineTransform(Model.AxLims,A,b);\nreturn\n\n%====================================================\n% Point Cloud 3D geometry stuff\n%====================================================\nfunction [GridPts,AxPts] = GetGridPts(NPtsPerAx,AxLength)\n    %AxPts = linspace(0,AxLength,NPtsPerAx);\n    AxPts = linspace(-AxLength,AxLength,NPtsPerAx);\n    [X,Y,Z] = meshgrid(AxPts,AxPts,AxPts);\n    GridPts = [X(:),Y(:),Z(:)];\nreturn\n\nfunction [Cloud,nPtsCloud] = PointCloudFromf(f,AxLim,VoxSize)\n% returns point cloud of 1-sublevel set of f, sampled over a box specified\n% by AxLim, with granularity VoxSize\n    xMin=AxLim(1);xMax=AxLim(2);yMin=AxLim(3);yMax=AxLim(4);zMin=AxLim(5);zMax=AxLim(6);\n    [X,Y,Z] = meshgrid([xMin:VoxSize:xMax],[yMin:VoxSize:yMax],[zMin:VoxSize:zMax]);\n    GridPts = [X(:),Y(:),Z(:)];\n    nPts    = size(GridPts,1);\n    InOrOut = zeros(nPts,1);\n    for i=1:nPts\n        InOrOut(i) = ( f(GridPts(i,:)') <= 1);\n    end\n    IndexCloudPts = find(InOrOut > 0);\n    Cloud         = GridPts(IndexCloudPts,:);\n    nPtsCloud     = length(IndexCloudPts);\nreturn\n\nfunction [CloudBdy,nPtsCloudBdy] = PointCloudBdyFromfAndfGrad(f,fGrad,Cloud,VoxSize,SubSampFactor)\n% returns boundary points of point cloud of 1-sublevel set of f, \n% assumed to be differentiable with gradient fGrad, also assumed\n% be computed with granularity VoxSize, and will be downsampled by factor SubSampFactor\n    if nargin < 4, VoxSize = 0.1;end\n    if nargin < 5, SubSampFactor = 1; end\n    n       = size(Cloud,1);\n    InOrOut = zeros(n,1);\n    for i=1:SubSampFactor:n\n        xi = Cloud(i,:)';\n        InOrOut(i) = ( abs(f(xi)-1)  <=  norm(fGrad(xi))*VoxSize );% point on shell\n    end\n    IndexBdyPts = find( InOrOut > 0 );\n    CloudBdy    = Cloud(IndexBdyPts,:);\n    nPtsCloudBdy= size(CloudBdy,1);\nreturn\n\nfunction f = fAffineTransform(f,A,b)\n% update f so that its 1-sublevel set S is transformed to A*S+b\n    AInv = inv(A);\n    f = @(x) f(AInv*(x-b));\nreturn\n\nfunction fGrad = fGradAffineTransform(fGrad,A,b)\n% update fGrad to correspond to the f whose 1-sublevel set S is transformed to A*S+b\n    AInv = inv(A);\n    fGrad = @(x) AInv'*fGrad(AInv*(x-b));\nreturn\n\nfunction AxLims = AxLimsAffineTransform(AxLims,A,b)\n    Vertices = AxLimsToVertices(AxLims);\n    Vertices = PointCloudAffineTransform(Vertices,A,b);\n    AxLims   = AxLimsFromVertices(Vertices);\nreturn\n\nfunction AxLims = AxLimsFromVertices(Vertices)\n% computes box around set of Vertices sorted row-wise [x1';x2';...;xN'];\n    Dimensions = size(Vertices,2);\n    AxLims = zeros(1,2*Dimensions);\n    for i=1:Dimensions\n        AxLims(2*i)  = max(Vertices(:,i));\n        AxLims(2*i-1)= min(Vertices(:,i));\n    end\nreturn\n\nfunction Vertices = AxLimsToVertices(AxLims)\n    Vertices = GenerateVertices([],0,AxLims);\nreturn\n\nfunction V = GenerateVertices(V,i,AxLims)\n% computes Vertices sorted row-wise [x1';x2';...;xN'] from Matlab axis limits AxLims, \n% via recursively doubling up the coordinates matrix, backwards from N to 1,\n% adding new coordinate column each step.\n    n = length(AxLims)/2;\n    i = i+1;\n    if i <= n\n        V = [AxLims(2*(n-i+1))  *ones(2^(i-1),1),V;\n             AxLims(2*(n-i+1)-1)*ones(2^(i-1),1),V];\n        V = GenerateVertices(V,i,AxLims);\n    else\n        V = V;\n    end\nreturn\n\nfunction Cloud = PointCloudAffineTransform(Cloud,A,b)\n% Apply A*x+b to each point in Cloud\n% Assumes points stored in Cloud row-wise [x1';x2';...;xN'];\n    nPtsCloud = size(Cloud,1);\n    Cloud     = Cloud*A' + repmat(b(:)',nPtsCloud,1);\nreturn\n\nfunction Cloud = PointCloudRotateTranslate(Cloud,Thetaxyz,Offset)\n% Apply rotation (Thetaxyz) and Offset to each point in Cloud\n% Assumes points stored in Cloud row-wise [x1';x2';...;xN'];\n    RotMtx = AnglesToRotMtx(Thetaxyz);\n    Cloud = PointCloudAffineTransform(Cloud,RotMtx,Offset(:));\nreturn\n\n\nfunction [RotMtx,Rx,Ry,Rz] = AnglesToRotMtx(Thetaxyz)\n% Rotation about x, y, and z axes - in that order!\n    cx = cos(Thetaxyz(1)); sx = sin(Thetaxyz(1));\n    cy = cos(Thetaxyz(2)); sy = sin(Thetaxyz(2));\n    cz = cos(Thetaxyz(3)); sz = sin(Thetaxyz(3));\n    Rx  = [1    0   0;\n           0    cx -sx;\n           0    sx  cx];\n    Ry  = [cy   0   sy;\n           0    1   0;\n          -sy   0   cy];\n    Rz  = [cz  -sz  0;\n           sz   cz  0;\n           0    0   1];\n    RotMtx = Rz*Ry*Rx;\nreturn\n\nfunction PlotCloud(CloudGridPts,Symbol,AxPts)\n    plot3(CloudGridPts(:,1),CloudGridPts(:,2),CloudGridPts(:,3),Symbol);\n    AxMin = min(AxPts); AxMax = max(AxPts);\n    axis([AxMin,AxMax,AxMin,AxMax,AxMin,AxMax])\n    grid on\nreturn\n\nfunction Points = GetPointsOnUnitSphere1000(N)\n% get evenly distributed 1000 points on UNIT sphere\n% taken off the web\n    if nargin <1\n        N=14;\n    end\n    Beta = 0.5*pi/N;\n    Points = [];\n    % line segment length\n    A = 2*sin(Beta/2);\n    % endcap\n    Points = [Points;[0 0 1]];\n    Points = [Points;[0 0 -1]];\n    % rings\n    for i=1:N\n      R = sin(i*Beta);\n      Z = cos(i*Beta);\n      M = round(R*2*pi/A);\n      for j=0:M-1\n          Alpha = j/M * 2 * pi;\n          X = cos(Alpha)*R;\n          Y = sin(Alpha)*R;\n          Points = [Points;[X Y Z]];\n          if i~=N\n              Points = [Points;[X Y -Z]];\n          end\n      end\n    end\nreturn\n\n%====================================================\n% Optimization functions: CPLEX and ADMM\n%====================================================\nfunction xBmWtsStar = OptimizeBeamsCPLEX(AAll,dMin,dMax);\n% solve using CPLEX\n%        minimize   sum pos(d - dmax)  + sum pos(dmin - d)\n%        such that  A x =  d\n%                     x >= 0\n% where pos(x) is the positive part of x, taken componentwise\n%         pos(x) = max(x,0) \n%\n    NVoxAll  = size(AAll,1)\n    NBeams   = size(AAll,2)\n    INVoxAll = speye(NVoxAll);\n    ZNVoxAll = sparse(NVoxAll,NVoxAll);\n    ZNVoxAllNBeams = sparse(NVoxAll,NBeams);\n    AEq = [AAll, -INVoxAll, ZNVoxAll];\n    AEq = sparse(AEq);\n    bEq = [zeros(NVoxAll,1)];\n    AIneq = [ZNVoxAllNBeams, -INVoxAll, -INVoxAll; \n             ZNVoxAllNBeams,  INVoxAll, -INVoxAll];\n    AIneq = sparse(AIneq);\n    bIneq = [-dMin;dMax];\n    lb = zeros(NBeams+NVoxAll+NVoxAll,1);\n    ub = [300*ones(NBeams,1);1e6*ones(2*NVoxAll,1)];\n    cLP = [zeros(NBeams,1);zeros(NVoxAll,1);ones(NVoxAll,1)];\n    disp('Solving optimization with CPLEX ...')\n    tic\n    options = cplexoptimset('Simplex','on');\n    [xStar,Obj,exitflag,output,lambda] = ...\n    cplexlp(cLP',AIneq,bIneq,AEq,bEq,lb,ub,[],options); %, x0);\n    exitflag = exitflag\n    xBmWtsStar = xStar(1:NBeams);\n    fstar = Obj\n    toc\nreturn\n\nfunction xBmWtsStar = OptimizeBeamsADMM(AAll,dMin,dMax);\n% solve using ADMM following Stanford EE364b final exam problem (Boyd&Chu)\n%        minimize   sum pos(d - dmax)  + sum pos(dmin - d)\n%        such that  A x =  d\n%                     x >= 0\n% where pos(x) is the positive part of x, taken componentwise\n%         pos(x) = max(x,0) \n%\n    tic\n    disp(' ')\n    NVoxAll  = size(AAll,1)\n    NBeams   = size(AAll,2)\n    disp('doing ADMM as in EE364b 2011 Final (Stephen Boyd, Eric Chu)')\n    disp('computing pseudo-inverse of [A;I]...')\n    tic\n    AAllI    = [AAll;eye(NBeams)];\n    %AAllIPinv = pinv(AAllI);\n    Delta = pinv(speye(NBeams)+AAll'*AAll);\n    save('Delta','Delta');\n    %load Delta\n    toc\n    ud  = zeros(NVoxAll,1);\n    ux  = zeros(NBeams,1);\n    dose = zeros(NVoxAll,1);\n    xBm  = zeros(NBeams,1);\n    z    = zeros(NBeams,1);\n    zOld = z;\n    disp('doing ADMM iterations')\n    MaxIters = 300\n    rho     = 1.25;%0.5\n    mu      = 10;%1.5\n    tauIncr = 2;%1.1\n    tauDecr = 1/tauIncr;\n    rNorm = zeros(MaxIters,1);\n    sNorm = zeros(MaxIters,1);\n    rhos  = zeros(MaxIters,1);\n    for i=1:MaxIters\n                \n        % do ADMM update\n        AAllzOld = AAll*zOld;\n        dose = DoubleHingeProx(dMin,dMax,rho,AAllzOld-(ud/rho));\n        xBm  = min(max(z-(ux/rho),0),300);\n        z    = Delta*(  AAll'*(dose+(ud/rho))  +  (xBm+(ux/rho))  );\n        AAllz= AAll*z;\n        ux   = ux + rho*(xBm-z);\n        ud   = ud + rho*(dose-AAllz);\n        \n        % compute primal and dual residuals for stopping criterion and rho updating\n        r        = [dose;xBm] - [AAllz;z];\n        s        = rho*([AAllz-AAllzOld;z-zOld]);\n        rNorm(i) = norm(r,2);\n        sNorm(i) = norm(s,2);\n        \n        % update z\n        zOld = z;\n        \n        % \"adaptive\" rho update (doesn't always work ==> safer to switch off)\n        rhos(i) = rho;\n%         if     (rNorm(i) > mu*sNorm(i))\n%             rho = tauIncr*rho\n%         elseif (rNorm(i) < (1/mu)*sNorm(i))\n%             rho = tauDecr*rho\n%         end\n\n    end\n    disp('done!')\n    xBmWtsStar = xBm;\n    toc\n\n    figure\n    subplot(3,1,1),plot(1:MaxIters,log10(rNorm)),grid,ylabel('log10(rNorm)')\n    subplot(3,1,2),plot(1:MaxIters,log10(sNorm)),grid,ylabel('log10(sNorm)')\n    subplot(3,1,3),plot(1:MaxIters,log10(rhos)),grid,ylabel('log10(rho)')\nreturn\n\nfunction xProx = DoubleHingeProx(aa,bb,rho,x)\n    if min(bb-aa)<0, error('xMin > xMax!'),end\n    xProx = 1/rho + x - max(x-(aa-1/rho),0) + max(x-aa,0) - max(x-bb,0) + max(x-(bb+1/rho),0);\nreturn\n\nfunction xProx = DoubleHingeProx2(aa,bb,rho,x)\n    if min(bb-aa)<0, error('xMin > xMax!'),end\n    xTemp = SoftThresh(1/2/rho,x-(aa-1/2/rho)) + aa;\n    xProx = SoftThresh(1/2/rho,xTemp-(bb+1/2/rho))+bb;\nreturn\n    \nfunction xST = SoftThresh(k,x)\n    if min(k) <= 0, error('k <=0'),end\n    xST = max(x-k,0) - max(-x-k,0);\nreturn\n\nfunction y = DoubleHinge(xMin,xMax,x)\n    if min(xMax-xMin)<0, error('xMin > xMax!'),end\n    y = max(xMin-x,0) + max(x-xMax,0);\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/42558-radiation-treatment-planning-optimization-toy-example/RadiationTreatmentPlanningOptimizationToyEg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5651050790514548}}
{"text": "function d=dsphere(p,xc,yc,zc,r)\n\n%   Copyright (C) 2004-2006 Per-Olof Persson. See COPYRIGHT.TXT for details.\n\nd=sqrt((p(:,1)-xc).^2+(p(:,2)-yc).^2+(p(:,3)-zc).^2)-r;\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/mesh/distmeshModified/dsphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5651050661523276}}
{"text": "%% Setting of the problem\nglobal s\npde = fracLapdata9;\n% pde = checkboarddata;\npde.L = 1;\noption.maxIt = 4;\noption.maxN = 1e6;\noption.elemType = 'P1P2';\noption.solver = 'mg';\noption.gNquadorder = 4;\noption.tol = 1e-6;\n[node,elem] = squaremesh([-1 1 -1 1],0.5);\nbdFlag = setboundary(node,elem,'Dirichlet');\n\n%% s = 0.2\ns = 0.2;\nfemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.4\ns = 0.4;\nfemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.6\ns = 0.6;\nfemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.8\ns = 0.8;\nfemfracLap(node,elem,pde,bdFlag,option);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fracLaplacian/femratefracLapP1P2cf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033682, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5651050602207411}}
{"text": "% Image construction from overlapping patches\nfunction [result] = overlap_add(patches, img_size, grid)\n\nresult = zeros(img_size);\nweight = zeros(img_size);\n \nfor i = 1:size(grid, 3)\n    patch = reshape(patches(:, i), size(grid, 1), size(grid, 2));\n    result(grid(:, :, i)) = result(grid(:, :, i)) + patch;\n    weight(grid(:, :, i)) = weight(grid(:, :, i)) + 1;\nend\n\nI = logical(weight);\nresult(I) = result(I) ./ weight(I);\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/Aplus/overlap_add.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5648813436947573}}
{"text": "function a = dec2bin(d)\ni=1;\na=zeros(1,65535);\nwhile d >= 2\n    r=rem(d,2);\n    if r==1\n        a(i)=1;\n    else\n        a(i)=0;\n    end\n    i=i+1;\n    d=floor(d/2);\nend\nif d == 2\n    a(i) = 0;\nelse\n    a(i) = 1;\nend\nx=[a(16) a(15) a(14) a(13) a(12) a(11) a(10) a(9) a(8) a(7) a(6) a(5) a(4) a(3) a(2) a(1)];", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/38439-implementation-of-rsa-algorithm/RSA/dec2bin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7217431943271998, "lm_q1q2_score": 0.5648813176395379}}
{"text": "function i4row_sort2_d_test ( )\n\n%*****************************************************************************80\n%\n%% I4ROW_SORT2_D_TEST tests I4ROW_SORT2_D;\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 6;\n  n = 4;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'I4ROW_SORT2_D_TEST\\n' );\n  fprintf ( 1, '  For a rectangular integer matrix:\\n' );\n  fprintf ( 1, '  I4ROW_SORT2_D sorts the elements of the rows.\\n' );\n \n  seed = 123456789;\n\n  for i = 1 : m\n    for j = 1 : n\n      a(i,j) = 10 * i + j;\n    end\n  end\n\n  i4mat_print ( m, n, a, '  The original matrix:' );\n\n  [ a, seed ] = i4mat_perm2_uniform ( m, n, a, seed );\n\n  i4mat_print ( m, n, a, '  The matrix, permuted by I4MAT_PERM2_UNIFORM:' );\n\n  a = i4row_sort_d ( m, n, a );\n\n  i4mat_print ( m, n, a, '  The row-sorted matrix:' );\n\n  a = i4row_sort2_d ( m, n, a );\n\n  i4mat_print ( m, n, a, '  The element-sorted row-sorted matrix:' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/i4lib/i4row_sort2_d_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.5648796267554079}}
{"text": "% test_remove_vertex_from_tri.m\n\n% Author: Ramon Casero <rcasero@gmail.com>\n% Copyright \u00a9 2013 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% <http://www.gnu.org/licenses/>.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Remove opposite vertices from a cube\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% create a surface mesh that is a cube\nx = [\n    0 0 0\n    0 0 1\n    0 1 0\n    0 1 1\n    1 0 0\n    1 0 1\n    1 1 0\n    1 1 1\n    ];\n\ntri = [\n    1     3     5\n    2     1     5\n    2     3     1\n    4     3     2\n    6     2     5\n    4     2     6\n    7     6     5\n    3     7     5\n    4     7     3\n    8     6     7\n    4     8     7\n    4     6     8\n    ];\n\n% plot mesh\nhold off\ntrisurf(tri, x(:,1), x(:,2), x(:,3), ones(1, size(x, 1)))\naxis equal\n\n% vertices to remove\nidx = [2 7];\n\n% plot vertices that are going to be removed\nhold on\nplot3(x(idx, 1), x(idx, 2), x(idx, 3), 'ro')\n\n% remove vertices\n[tri2, x2] = remove_vertex_from_tri(tri, x, idx);\n\n% plot result\nhold off\ntrisurf(tri2, x2(:,1), x2(:,2), x2(:,3), ones(1, size(x2, 1)))\nhold on\nplot3(x(idx, 1), x(idx, 2), x(idx, 3), 'ro')\naxis equal\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Remove neighbour vertices from a cube\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% create a surface mesh that is a cube\nx = [\n    0 0 0\n    0 0 1\n    0 1 0\n    0 1 1\n    1 0 0\n    1 0 1\n    1 1 0\n    1 1 1\n    ];\n\ntri = [\n    1     3     5\n    2     1     5\n    2     3     1\n    4     3     2\n    6     2     5\n    4     2     6\n    7     6     5\n    3     7     5\n    4     7     3\n    8     6     7\n    4     8     7\n    4     6     8\n    ];\n\n% plot mesh\nhold off\ntrisurf(tri, x(:,1), x(:,2), x(:,3), ones(1, size(x, 1)))\naxis equal\n\n% vertices to remove\nidx = [1 2];\n\n% plot vertices that are going to be removed\nhold on\nplot3(x(idx, 1), x(idx, 2), x(idx, 3), 'ro')\n\n% remove vertices\n[tri2, x2] = remove_vertex_from_tri(tri, x, idx);\n\n% plot result\nhold off\ntrisurf(tri2, x2(:,1), x2(:,2), x2(:,3), ones(1, size(x2, 1)))\nhold on\nplot3(x(idx, 1), x(idx, 2), x(idx, 3), 'ro')\naxis equal\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_remove_vertex_from_tri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5648796095464163}}
{"text": "function pass = test_sample( ) \n% Test spherefun sample() command \n\ntol = 100*chebfunpref().cheb2Prefs.chebfun2eps;\n\n% Function to test\nf = spherefun(@(x,y,z) sin(pi*x.*y));\n\n% Ensure the matrix of sampled values is correct.\n[m,n] = length(f);\n[nn,mm] = size(sample(f));\npass(1) = (m == mm) && (n == nn);\n\n% Sample on fixed grids of various sizes to make sure the right size output\n% is given.\nm = 120; \nn = 121;\n[nn,mm] = size(sample(f, m, n));\npass(2) = (m == mm) && (n == nn);\n\nm = 121; \nn = 120;\n[nn,mm] = size(sample(f, m, n));\npass(3) = (m == mm) && (n == nn);\n\n% Check samples are correct.\n% m and n even\nm = 30; \nn = 20;\n[lam,th] = meshgrid(trigpts(m, [-pi, pi]), linspace(0, pi, n));\nF = f(lam, th);\nG = sample(f, m, n);\npass(4) = norm(F(:) - G(:), inf) < tol;\n[U, D, V] = sample(f, m, n);\nG = U * D * V.';\npass(5) = norm(F(:) - G(:), inf) < tol;\n\n% m even and n odd\nm = 30; \nn = 21;\n[lam, th] = meshgrid(trigpts(m, [-pi, pi]), linspace(0, pi, n));\nF = f(lam, th);\nG = sample(f, m, n);\npass(6) = norm(F(:) - G(:), inf) < tol;\n[U, D, V] = sample(f, m, n);\nG = U * D * V.';\npass(7) = norm(F(:) - G(:), inf) < tol;\n\n% m odd and n even\nm = 31; \nn = 20;\n[lam, th] = meshgrid(trigpts(m, [-pi, pi]), linspace(0, pi, n));\nF = f(lam, th);\nG = sample(f, m, n);\npass(8) = norm(F(:) - G(:), inf) < tol;\n[U, D, V] = sample(f, m, n);\nG = U * D * V.';\npass(9) = norm(F(:) - G(:), inf) < tol;\n\n% m odd and n odd\nm = 31; \nn= 21;\n[lam, th] = meshgrid(trigpts(m, [-pi, pi]), linspace(0, pi, n));\nF = f(lam, th);\nG = sample(f, m, n);\npass(10) = norm(F(:) - G(:), inf) < tol;\n[U, D, V] = sample(f, m, n);\nG = U * D * V.';\npass(11) = norm(F(:) - G(:), inf) < tol;\n\n% Sample should return all ones for the function 1.\nf = spherefun(@(x,y,z) 1 + 0*x);\nF = sample(f, 128, 128);\npass(12) = norm(F(:) - 1, inf) < tol;\n\n% Check that errors are caught\ntry\n    F = sample(f, 0, 20);\n    pass(13) = false;\ncatch ME\n    pass(13) = strcmp(ME.identifier, 'CHEBFUN:SPHEREFUN:sample:inputs');\nend\n\ntry\n    F = sample(f, 20, 0);\n    pass(14) = false;\ncatch ME\n    pass(14) = strcmp(ME.identifier, 'CHEBFUN:SPHEREFUN:sample:inputs');\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/spherefun/test_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5648755909107265}}
{"text": "function ui = ic_spike ( x )\n\n%*****************************************************************************80\n%\n%% IC_SPIKE evaluates the initial condition for a spike function.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 April 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X(*), the node coordinates.\n%\n%    Output, real UI(*), the value of the initial condition at each node.\n%\n  ui = max ( 1.0 - 3.0 * abs ( x ), 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/burgers_time_viscous/ic_spike.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.5648755822032779}}
{"text": "function prod = tensor_array_innerprod( X1, X2 )\n\nprod = 0;\nN = length(X1);\nfor i = 1:N\n    prod = prod + innerprod(X1{i},X2{i});\nend\n\nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/td/RLRT/utils/tensor_array_innerprod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5648755791003103}}
{"text": "function f = rcnn_scale_features(f, feat_norm_mean)\n% My initial experiments were conducted on features with an average norm\n% very close to 20. Using those features, I determined a good range of SVM\n% C values to cross-validate over. Features from different layers end up\n% have very different norms. We rescale all features to have an average norm\n% of 20 (why 20? simply so that I can use the range of C values found in my \n% initial experiments), to make the same search range for C reasonable \n% regardless of whether these are pool5, fc6, or fc7 features. This strategy\n% seems to work well. In practice, the optimal value for C ends up being the\n% same across all features.\ntarget_norm = 20;\nf = f .* (target_norm / feat_norm_mean);\n", "meta": {"author": "rbgirshick", "repo": "rcnn", "sha": "43b0334e96e9e910bc45c94902a093b5a6f35d0a", "save_path": "github-repos/MATLAB/rbgirshick-rcnn", "path": "github-repos/MATLAB/rbgirshick-rcnn/rcnn-43b0334e96e9e910bc45c94902a093b5a6f35d0a/rcnn_scale_features.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5648755791003103}}
{"text": "function [D]=logic2levelset(varargin)\n\n% function [D]=logic2levelset(logicInside,voxelSize,voxelSizeResample)\n% ------------------------------------------------------------------------\n% This function converts the logic image logicInside to a level set image.\n% The level set image intensities define the distance of the voxels to the\n% boundaries of the logic image. \n% \n% \n% Change log: \n% \n% ------------------------------------------------------------------------\n%%\n\nswitch nargin\n    case 1\n        logicInside=varargin{1};\n        voxelSize=[];\n        voxelSizeResample=[];\n    case 2\n        logicInside=varargin{1};\n        voxelSize=varargin{2};\n        voxelSizeResample=[];\n    case 3\n        logicInside=varargin{1};\n        voxelSize=varargin{2};\n        voxelSizeResample=varargin{3};\nend\n\nif isempty(voxelSize)\n    voxelSize=ones(1,3);\nend\n\nif isempty(voxelSizeResample)\n    voxelSizeResample=mean(voxelSize);\nend\n\nif numel(voxelSizeResample)==1\n    voxelSizeResample=voxelSizeResample*ones(1,3);\nend\n\n%%\n\nsiz=size(logicInside);\n%Resample input image isotropically (isotropic voxels)\nif ~max(voxelSize-voxelSizeResample)< max(eps(voxelSize))\n    resampleOn=1;    \n    [logicInside]=imageResample(logicInside,voxelSize,voxelSizeResample);\n    logicInside=logicInside>0; %Forces logic and fixes potential NaN's\n    scaleFactor=voxelSizeResample(1);\nelse\n    resampleOn=0;\n    scaleFactor=voxelSize(1);\nend\nlogicInside=logicInside>0; %Force to be a logic (in case resampling altered it)\n\n%Remove interior from logic\ntry    \n    logicOn = bwmorph3(logicInside,'remove'); %New in R2018a\ncatch\n    logicOn=logicRemoveInterior(logicInside); %GIBBON alterative\nend\n\n%Do distance transform on isotropic image\nD = double(bwdist(logicOn,'euclidean')); %Compute distance\nD(logicInside)=-D(logicInside); %Negate distance inside\nD=D.*scaleFactor; %Scale by voxel size\n\nif resampleOn==1    \n    sizNew=size(D); %Size of distance data in resampled state\n    [J,I,K]=meshgrid(1:1:siz(2),1:1:siz(1),1:1:siz(3)); %Image coordinate grid of original image\n    [X,Y,Z]=im2cart(I,J,K,voxelSize); %Spatial coordinate of original image grid\n    [I,J,K]=cart2im(X,Y,Z,voxelSizeResample); %Image coordinates of original grid in resampled image\n    I=round(I); J=round(J); K=round(K); %Rounding \n    IND=reshape(sub2indn(sizNew,[I(:) J(:) K(:)],1),size(I)); %Convert to linear indices\n    D=D(IND); %Override D to be data sampled at original image points\nend\n\n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/logic2levelset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5648755791003103}}
{"text": "% EKF/UKF toolbox for Matlab 7.x\n% Version 1.3, August 12, 2011\n%\n% Copyright (C) 2005-2011 Simo S\ufffdrkk\ufffd, <simo.sarkka@hut.fi>\n%               2007-2011 Jouni Hartikainen <jmjharti@cc.hut.fi>\n%               2010-2011 Arno Solin <arno.solin@tkk.fi>\n% History:      \n%   12.08.2011 JH & AS & SS Updated to version 1.3\n%   04.09.2007 JH & SS Updated for version 1.1\n%   06.08.2007 JH Updated for version 1.0\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%\n% Kalman filtering\n%   KF_PREDICT    Perform Kalman Filter prediction step\n%   KF_UPDATE     Kalman Filter update step\n%   KF_LHOOD      Kalman Filter measurement likelihood\n%   RTS_SMOOTH    Rauch-Tung-Striebel Smoother\n%   TF_SMOOTH     Smoother based on combination of two Kalman filters\n%\n% Extended Kalman filtering\n%   EKF_PREDICT1  1st order Extended Kalman Filter prediction step\n%   EKF_UPDATE1   1st order Extended Kalman Filter update step\n%   EKF_PREDICT2  2nd order Extended Kalman Filter prediction step\n%   EKF_UPDATE2   2nd order Extended Kalman Filter update step\n%   ERTS_SMOOTH1  1st order Extended RTS Smoother\n%   ETF_SMOOTH1   Smoother based on two 1. order extended Kalman filters           \n%\n% Nonlinear transform based filtering\n%   UT_WEIGHTS    Generate weights for sigma points using the summation form\n%   UT_MWEIGTS    Generate weights for sigma points using the matrix form\n%   UT_SIGMAS     Generate Sigma Points for Unscented Transformation\n%   UT_TRANSFORM  Makes the Unscented Transformation of x and y\n%   UKF_PREDICT1  Nonaugmented UKF prediction step\n%   UKF_UPDATE1   Nonaugmented UKF update step\n%   UKF_PREDICT2  Augmented (state and process noise) UKF prediction step \n%   UKF_UPDATE2   Augmented (state and measurement noise) UKF update step \n%   UKF_PREDICT3  Augmented (state, process and measurement noise) UKF prediction step\n%   UKF_UPDATE3   Augmented (state, process and measurement noise) UKF update step\n%   URTS_SMOOTH1  Nonaugmented unscented RTS-smoother\n%   URTS_SMOOTH2  Augmented unscented RTS-smoother\n%   UTF_SMOOTH    Smoother based on combination of two unscented Kalman filters\n%   GH_TRANSFORM  Gauss-Hermite transform of random variables\n%   GHKF_PREDICT  Gauss-Hermite Kalman filter prediction step\n%   GHKF_UPDATE   Gauss-Hermite Kalman filter update step\n%   GHRTS_SMOOTH  Additive form Gauss-Hermite Rauch-Tung-Striebel smoother\n%   CKF_TRANSFORM Cubature Kalman filter transform of random variables\n%   CKF_PREDICT   Cubature Kalman filter prediction step\n%   CKF_UPDATE    Cubature Kalman filter update step\n%   CRTS_SMOOTH - Additive form cubature Rauch-Tung-Striebel smoother\n%\n% Multiple Model Filtering\n%   IMM_PREDICT   IMM filter prediction step\n%   IMM_UPDATE    IMM filter update step\n%   IMM_SMOOTH    IMM smoothing\n%   EIMM_PREDICT  IMM-EKF filter prediction step\n%   EIMM_UPDATE   IMM-EKF filter update step\n%   EIMM_SMOOTH   IMM-EKF smoothing\n%   UIMM_PREDICT  IMM-UKF filter prediction step\n%   UIMM_UPDATE   IMM-UKF filter update step\n%   UIMM_SMOOTH   IMM-UKF smoothing\n%\n%\n% Misc.\n%   GAUSS_PDF     Multivariate Gaussian PDF\n%   GAUSS_RND     Multivariate Gaussian random variables\n%   LTI_INT       Integrate LTI ODE with Gaussian Noise\n%   LTI_DISC      Discretize LTI ODE with Gaussian Noise\n%   RK4           Runge-Kutta integration\n%   DER_CHECK     Check derivatives using finite differences\n%   SCHOL         Positive semidefinite matrix Cholesky factorization\n%   RESAMPSTR     Stratified resampling\n%\n% /DEMOS/ \n%\n%   /KF_CWPA_DEMO/             \n%      KF_CWPA_DEMO       CWPA model demonstration with Kalman filter\n%\n%   /EKF_SINE_DEMO/          \n%      EKF_SINE_F         Dynamic model function (needed by the augmented UKF)\n%      EKF_SINE_H         Measurement model function\n%      EKF_SINE_DH_DX     1st order derivative of the measurement model\n%      EKF_SINE_D2H_DX2   2nd order derivative of the measurement model\n%      EKF_SINE_DEMO      Random Sine Signal demonstration\n%\n%   /UNGM_DEMO/           \n%      UNGM_F             Dynamic model function\n%      UNGM_DF_DX         1st order derivative of the dynamic model\n%      UNGM_D2F_DX2       2nd order derivative of the dynamic model (not used)\n%      UNGM_H             Measurement model function\n%      UNGM_DH_DX         1st order derivative of the measurement model\n%      UNGM_D2H_DX2       2nd order derivative of the measurement model (not used)\n%      UNGM_DEMO          UNGM model demonstration\n%\n%   /BOT_DEMO/            \n%      BOT_H              Measurement model function\n%      BOT_DH_DX          1st order derivative of the measurement model \n%      BOT_D2H_DX2        2nd order derivative of the measurement model  \n%      BOT_DEMO_ALL       BOT demo with EKF and UKF\n%      EKFS_BOT_DEMO      BOT demo with EKF\n%      UKFS_BOT_DEMO      BOT demo with UKF\n%      GHKFS_BOT_DEMO     BOT demo with GHKF\n%      CKFS_BOT_DEMO      BOT demo with CKF\n%\n%   /REENTRY_DEMO/        \n%      REENTRY_F          Dynamic model function\n%      REENTRY_DF         Derivative of the dynamic model\n%      REENTRY_H          Measurement model function\n%      REENTRY_DH         Derivative of the measurement model\n%      REENTRY_IF         Inverse prediction of the dynamic model\n%      REENTRY_COND       Generates condition numbers for simulation data\n%      MAKE_REENTRY_DATA  Generates the simulation data for reentry dynamics \n%      REENTRY_DEMO       Reentry Vehicle Tracking demonstration\n%  \n%   /IMM_DEMO/\n%      IMM_DEMO           Tracking a Target with Simple Manouvers demonstration\n%\n%   /EIMM_DEMO/\n%      F_TURN             Dynamic model function for the coordinated turn model\n%      F_TURN_DX          Jacobian of the coordinated turn model's dynamic model\n%      F_TURN_INV         Inverse dynamics of the coordinated turn model\n%      CT_DEMO            Coordinated Turn Model demonstration\n%      BOT_H              Measurement model function\n%      BOT_DH_DX          1st order derivative of the measurement model \n%      BOT_D2H_DX2        2nd order derivative of the measurement model  \n%      BOTM_DEMO          Bearings Only Tracking of a Manouvering Target Demonstration\n%\n% Demos currently included in the toolbox, but not documented:\n%\n% /KF_SINE_DEMO/           \n%      KF_SINE_DEMO       Sine signal demonstration with Kalman filter\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/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5648755672898941}}
{"text": "function [forecast_estimates]=olsforecast(data_endo_a,data_exo_p,Fperiods,betahat,Bhat,sigmahat,n,m,p,k,const,Fband)\n\n\n\n% function [forecast_estimates]=olsforecast(data_endo_a,data_exo_p,Fperiods,betahat,Bhat,sigmahat,n,m,p,k,const,Fband)\n% computes unconditional forecast values (point estimates and confidence bands) for the OLS VAR model\n% inputs:  - matrix 'data_endo_a': matrix of pre-forecast endogenous data\n%          - matrix 'data_exo_p': predicted values for the exogenous variables over the forecast periods\n%          - integer 'Fperiods': number of forecast periods\n%          - vector 'betahat': OLS VAR coefficients in vectorised form (defined in 1.1.15)\n%          - matrix 'Bhat': OLS VAR coefficients, in non vectorised form (defined in 1.1.9)\n%          - matrix 'sigmahat': OLS VAR variance-covariance matrix of residuals (defined in 1.1.10)\n%          - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)\n%          - integer 'm': number of exogenous variables in the BVAR model (defined p 7 of technical guide)\n%          - integer 'p': number of lags included in the model (defined p 7 of technical guide)\n%          - integer 'k': number of coefficients to estimate for each equation in the BVAR model (defined p 7 of technical guide)\n%          - integer 'const': 0-1 value to determine if a constant is included in the model\n%          - scalar 'Fband': confidence level for forecasts\n% outputs: - cell 'forecast_estimates': lower bound, point estimates, and upper bound for the unconditional forecasts \n\n\n\n% this function implements the chain rule of forecast, desibed p38 of the technical guide\n\n\n% point estimates for forecasts are obtained using the chain rule for forecast in Lutkepohl (1991), equation (2.2.3) p 29\n% approximate confidence interval are obtained from Lutkepohl (1991), formula (3.5.15) p 89, based on the sample mean squared error matrix (2.2.10)\n\n\n% generate the matrix of predicted exogenous variables\n% if the constant has been retained, augment the matrices of exogenous with a column of ones:\nif const==1\ndata_exo_p=[ones(Fperiods,1) data_exo_p];\n% if no constant was included, do nothing\nelse\nend\n\n\n\n% then generate the point estimates\n% recover the lagged endogenous required to produce the forecasts\ntemp=data_endo_a(end-p+1:end,:);\n% repeat the process for periods T+1 to T+h\nfor ii=1:Fperiods\n% Define the matrix of regressors X by using lagX on temp; retain only the last row of the matrix\n   % if no exogenous variable is present at all in the model (neither constant nor other exogenous), define X from the endogenous variables only\n   if isempty(data_exo_p)\n   X=bear.lagx(temp,p-1);\n   X=X(end,:);\n   % if there are exogenous vaiables, concatenate them next to the endogenous\n   else\n   X=bear.lagx(temp,p-1);\n   X=[X(end,:) data_exo_p(ii,:)];\n   end\n% obtain predicted value for T+ii\nyp=X*Bhat;\n% concatenate the transpose of yp to the top of temp\ntemp=[temp;yp];\n% repeat until values are obtained for T+h\nend\n\n\n\n% finally, generate the confidence bands\n% this requires to estimate the forecast error matrix sigmaf for each forecast period\n% to do so, it is first necessary to obtain irfs\n[irfmatrix,~]=bear.irfsim(betahat,eye(n),n,m,p,k,Fperiods);\n% then initiate sigmaf for period 1\nsigmaf(:,:,1)=irfmatrix(:,:,1)*sigmahat*irfmatrix(:,:,1)';\n% and increment for each forecast period\nfor ii=2:Fperiods\nsigmaf(:,:,ii)=sigmaf(:,:,ii-1)+irfmatrix(:,:,ii)*sigmahat*irfmatrix(:,:,ii)';\nend\n% with the sigmaf series, it is possible to compute the confidence intervals\n% first compute the percentile of the normal distribution corresponding to size of the confidence interval\nc_low=norminv((1-Fband)/2,0,1);\nc_high=norminv(Fband+(1-Fband)/2,0,1);\n\n\n\n\n% finally, create and fill the forecast_estimates cell\nforecast_estimates=cell(n,1);\nfor ii=1:n\n% record forecast, point estimate\nforecast_estimates{ii,1}(2,:)=temp(p+1:end,ii)';\n   % then loop over forecast periods\n   for jj=1:Fperiods\n   % record forecast, lower bound\n   forecast_estimates{ii,1}(1,jj)=forecast_estimates{ii,1}(2,jj)+c_low*sigmaf(ii,ii,jj)^0.5;\n   % record forecast, upper bound\n   forecast_estimates{ii,1}(3,jj)=forecast_estimates{ii,1}(2,jj)+c_high*sigmaf(ii,ii,jj)^0.5;\n   end\nend\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/olsforecast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5647695384598319}}
{"text": "function [fusion,w0] = qfuser_v6(w,scores,wfuse)\n\nif nargin==0\n    test_this();\n    return;\nend\n\n\n% block 1\nf1 = linear_fuser([],scores.scores);\nw1 = wfuse;\n[whead,wtail] = splitvec_fh(length(w1));\nf1 = f1(whead);\n\n% block 2\nmodelQ = scores.modelQ;\n[q,n1] = size(modelQ);\nmodelQ = [modelQ;ones(1,n1)];\nsegQ = scores.segQ;\n[q2,n2] = size(segQ);\nsegQ = [segQ;ones(1,n2)];\nassert(q==q2);\nq = q + 1;\n\nwq = q*(q+1)/2;\nr = AWB_fh(modelQ',segQ,tril_to_symm_fh(q));\n[whead,wtail] = splitvec_fh(wq,wtail);\nr = r(whead);\nw2 = zeros(wq,1);w2(end) = -5;\n\n\n% block 3\ns = AWB_fh(modelQ',segQ,tril_to_symm_fh(q,wtail));\nw3 = w2;\n\n\n\n% assemble\nrs = stack([],r,s);\nfusion = scalibration_fh(stack(w,f1,rs));\nw0 = [w1;w2;w3];\n\n\n\n\nend\n\n\nfunction test_this()\n\nm = 3;\nk = 2;\nn1 = 4;\nn2 = 5;\n\nscores.scores = randn(m,n1*n2);\nscores.modelQ = randn(k,n1);\nscores.segQ = randn(k,n2);\n\nwfuse = [1,2,3,4]';\n\n[fusion,w0] = qfuser_v6([],scores,wfuse);\n\ntest_MV2DF(fusion,w0);\n\n[fusion(w0),linear_fuser(wfuse,scores.scores)]\n\n%fusion(w0)\n\n\nend\n", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/tDCF_v1/bosaris_toolkit.1.06/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/qfuser_v6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5647695307877248}}
{"text": "%****************************************************\n% Function to calculate sub-band energy(SBC) parameters \n% from enframed signal\n% modifided on 17 jan 2008\n% *********sarikaya paper algorithm***********\n% fs samapling rate 8000\n%   frame size used 192 \n%s signal\n%\n%\n%***************************************************\nfunction feature= sbc_2(s,fs)\n\n\nframes=enframe(s,hamming(192),192);\nno_offrames=size(frames);\nno_of_frames=no_offrames(:,1);\nfeature=zeros(no_of_frames,12);\nenergy=zeros(24,1);\n\n\nfe_frame=0;  % This counter is used to avoid frames with no energy is a sub band\n\nf=statusbar('Extracting SBC Feature');% Creates status bar\n\nfor i=1:no_of_frames\n    energy=ones(24);\n    \n    f=statusbar((i/no_of_frames),f);% updates status bar\n    [coef,len]=wavedec(frames(i,:),6,'db3');\n    s_no=cumsum(len);\n    \n    %% next two gives the last node in wavelet pacet\n \n    energy(1)=en(coef(1:s_no(1)));\n   \n\n    energy(2)=en(coef((s_no(1)+1):s_no(2)));\n   % coef((s_no(1)+1):s_no(2))\n            %refer diagram in sarikaya paper\n            [coef1,len1]=wavedec(coef(s_no(2):s_no(3)),1,'db3');\n            len1=cumsum(len1);\n                energy(3)=en(coef1(1:len1(1)) );\n                energy(4)=en(coef1((len1(1)+1):len1(2)));\n            \n                    [coef2,len2]=wavedec(coef((s_no(3)+1):s_no(4)),2,'db3');\n                        len2=cumsum(len2);\n                        energy(5)=en(coef2(1:len2(1)));\n                        \n                        energy(6)=en(coef2( (len2(1)+1):len2(2) ) );\n                            [coef3,len3]=wavedec(coef2((len2(2)+1):len2(3)),1,'db3');\n                            len3=cumsum(len3);\n                                    energy(7)=en(coef3(1:len3(1)));\n                                    energy(8)=en(coef3((len3(1)+1):len3(2)));\n                                    \n                % all nodes at level six are over\n                \n           [coef4,len4]=wavedec(coef(s_no(4):s_no(5)),2,'db3');      \n            len4=cumsum(len4);\n                        energy(9)=en(coef4(1:len4(1)));\n                        energy(10)=en(coef4((len4(1)+1):len4(2)));\n                          \n                        [coef5,len5]=wavedec(coef4((len4(2)+1):len4(3)),1,'db3');\n                        len5=cumsum(len5);\n                                    energy(11)=en(coef5(1:len5(1)));\n                                    energy(12)=en(coef5((len5(1)+1):len5(2)));\n                                    \n                                \n            [coef7,len7]=wavedec(coef(s_no(5):s_no(6)),3,'db3');\n            len7=cumsum(len7);\n                       energy(13)=en(coef7(1:len7(1)));\n                       energy(14)=en(coef7((len7(1)+1):len7(2)));\n                          \n                        [coef8,len8]=wavedec(coef7((len7(2)+1):len7(3)),1,'db3');\n                        len8=cumsum(len8);\n                           energy(15)=en(coef8(1:len8(1)));\n                           energy(16)=en(coef8((len8(1)+1):len8(2)));\n                                    \n             [coef9,len9]=wavedec(coef7((len7(3)+1):len7(4)),2,'db3');\n              len9=cumsum(len9);  \n                        energy(17)=en(coef9(1:len9(1)));\n                        energy(18)=en(coef9((len9(1)+1):len9(2)));\n                                     \n                 energy(19)=en(coef9((len9(2)+1):len9(3)));\n                 \n  [coef10,len10]=wavedec(coef((s_no(6)+1):s_no(7)),3,'db3');   \n  len10=cumsum(len10);\n  \n           energy(20)=en(coef10(1:len10(1)));\n           energy(21)=en(coef10((len10(1)+1):len10(2)));\n           energy(22)=en(coef10((len10(2)+1):len10(3)));\n           \n     [coef11,len11]=wavedec(coef10((len(3)+1):len10(4)),1,'db3'); \n     len11=cumsum(len11);\n            energy(23)=en(coef11(1:len11(1)));\n            energy(24)=en(coef11((len11(1)+1):len11(2)));\n\n            \n            \n           \n% Taking 12 filter bank equalent\n%\n%f=rdct(feature); function not woring\n% 19 jan DCT modified file in dessai cmtr \nif all(energy>0)\n  fe_frame=fe_frame+1;  \n    log_en=log(energy.*1E+06);\n\n   for j=1:12\n   for k=1:24\n            \n        feature(fe_frame,j)=feature(fe_frame,j)+log_en(k)*cos((j*(k-0.5)*pi)/24);\n   end\n   end\n % feature=abs(feature); this needs to be checked\nend\nend\n delete(statusbar)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22372-wavelet-subband-coding-for-speaker-recognition/sbc/sbc_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338727, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5647695298263339}}
{"text": "classdef GrEA < ALGORITHM\n% <many> <real/integer/label/binary/permutation>\n% Grid-based evolutionary algorithm\n% div --- --- The number of divisions in each objective\n\n%------------------------------- Reference --------------------------------\n% S. Yang, M. Li, X. Liu, and J. Zheng, A grid-based evolutionary algorithm\n% for many-objective optimization, IEEE Transactions on Evolutionary\n% Computation, 2013, 17(5): 721-736.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Parameter setting\n            Div = [0 45 15 10 9 9 8 8 10 12];\n            div = Algorithm.ParameterSet(Div(min(Problem.M,10)));\n\n            %% Generate random population\n            Population = Problem.Initialization();\n\n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                MatingPool = MatingSelection(Population.objs,div);\n                Offspring  = OperatorGA(Problem,Population(MatingPool));    \n                Population = EnvironmentalSelection([Population,Offspring],Problem.N,div);\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/Algorithms/Multi-objective optimization/GrEA/GrEA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5647695221732425}}
{"text": "function [clusters,subclusters] = cluster_princomp(clusters,varargin)\n% function [clusters,subclusters] = cluster_princomp(clusters,[behavioral score vector],[corr flag],[plotflag],[locflag])\n% \n% ALSO TRY: subcluster_montage(subclusters{1}) % to plot the output\n%\n% clusters is structure of clusters from tor_extract_rois.m\n% behavioral vector is row vector of behavioral or other scores to correlate\n% corr flag:  *1 = work on correlations among voxels, 2 = work on covariance\n% plotflag:   *1 = yes, 0 = no.  plots.\n% locflag:    1 yes, *0 no; add XYZ voxel locations (scaled) to data submitted to clustering\n%             pushes voxels closer in space to be classified in the same cluster\n%\n% try this to test the program on random data:\n% cl(1).all_data = randn(23,30);cl(1).numVox = 30;cl = cluster_princomp(cl,EXPT.behavior,1,1);\n% cl(1).all_data(:,1:10) = cl(1).all_data(:,1:10) + 10; cl = cluster_princomp(cl,EXPT.behavior,1,1);\n% cl(1).all_data(:,25:30) = cl(1).all_data(:,25:30) + repmat((EXPT.behavior .* 3)',1,6);\n% cl(1).all_data(:,21:24) = cl(1).all_data(:,21:24) + repmat((1:23)',1,4);\n% cl = cluster_princomp(cl,EXPT.behavior,1,1);\n% mean-center everything now:\n% cl.PCA = []; cl.all_data - cl.all_data - repmat(mean(cl.all_data),size(cl.all_data,1),1);\n% cl = cluster_princomp(cl,EXPT.behavior,1,1);\n% add another correlated group:\n% cl.all_data(:,1:5) = cl.all_data(:,1:5) + repmat(rand(23,1)*5,1,5);\n% cl = cluster_princomp(cl,EXPT.behavior,1,1);\n%\n% if component scores are used and correlated with behavior, this means that the subjects\n% tend to show the behavioral effect who also show the pattern associated with comp. x.  \n% this may mean high on a number of voxels, or high on some and low on others.  \n% the weights may be used to interpret what the components mean, and this can be done\n% graphically.  \n%\n% t-tests on component scores have ambiguous interpretations, because a high t-score\n% may indicate negative values or close-to-zero values on some voxels.\n% a component could have the interpretation, \"high on this component means high on V1\n% and low on V2.\"  \n%\n% classifying voxels is done using cluster analysis (hierarchical, centroid linkage)\n% on the voxels (observations) using the PCA weights (eigenvectors) as variables.\n% This lets the clustering algorithm work in the reduced variable space with dimensionality\n% equal to the number of components.  \n% The max number of clusters is restricted based on the gradient of the eigenvalues in the PCA\n% maxclusters = 1 + the number of eigenvalues with gradient at least 20% of the initial drop \n% from 1 to 2 eigenvalues.\n% \n% Requires clustering library in Matlab.\n% Robust option also uses the robust PCA algorithm RAPCA,\n% created by:\n% Hubert, M., Rousseeuw, P.J., Verboven, S. (2002),\n%  \"A fast method for robust principal components with applications to chemometrics\", by Mia Hubert, Peter J. Rousseeuw, \n%  Chemometrics and Intelligent Laboratory Systems, 60, 101-111.\n%\n%\n\ncorrflag = 1; plotflag = 1; robustflag = 1; locflag = 0;\nif length(varargin) > 1, corrflag = varargin{2};, end\nif length(varargin) > 2, plotflag = varargin{3};, end\nif length(varargin) > 3, locflag = varargin{4};, end\n\nfor i = 1:length(clusters)\n    subclusters{i} = []; clusters(i).PCA = [];\n    \n    % check for NaNs and remove those voxels\n    tst = any(isnan(clusters(i).all_data),1);\n    clusters(i).all_data(:,tst) = [];\n    clusters(i).XYZ(:,tst) = [];\n    clusters(i).XYZmm(:,tst) = [];\n    clusters(i).Z(:,tst) = [];\n    if any(tst),disp(['Warning! Removed ' num2str(sum(tst)) ' voxels with NaN values.']),end\n    \n    a = clusters(i).all_data;\n    \n    % scale here, because robust pca doesn't use correlations, does it?\n    % but robust PCA seems to be unaffected by scale changes on some variables\n    if corrflag, a = scale(a);,end\n        \n    % if we choose to add the XYZ flag to add locations to clustering criteria\n    if locflag,\n        wfactor = round(size(a,1) ./ 3);                       % weight for loc; higher = more weight on location\n        xyztmp = repmat(scale(clusters(i).XYZ')',wfactor,1);   % scale to make comparable to img values,\n                                                                % but multiply by weighting factor\n        a = [a; xyztmp];\n    end\n    \n \n    if size(a,2) > 2    % must have 3 voxels to try clustering\n    \n    % -------------------------------------------------------------------------------\n    % * All the real work is done here.  Compute pc's \n    % -------------------------------------------------------------------------------\n    \n    if ~robustflag\n        [clusters(i).PCA.pcomps,clusters(i).PCA.weights,clusters(i).PCA.eigval,clusters(i).PCA.class] = pc(a,corrflag);\n        \n        % automatically pick number of clusters, based on gradient in eigenvalues\n        g = abs(gradient(clusters(i).PCA.eigval));\n        maxclusters = sum(g > g(1).*.2) + 1;    \n    else\n        \n        % pick number of dimensions by hand\n        disp(' ')\n        disp([num2str(clusters(i).numVox) ' voxels in main cluster'])\n        fprintf(1,'%3.2f Observations on %3.2f voxels\\n',size(a,1),size(a,2))\n        fprintf(1,'Save at least 2 eigenvectors to do clustering');\n        % doing this on a' means voxels are observations, conditions/subj scores are variables\n        % we'll use the scores, which has voxels as rows and components as columns, to classify\n        out = rapca(a');\n        clusters(i).PCA.pcomps = out.T;\n        clusters(i).PCA.weights = out.P;\n        clusters(i).PCA.eigval = out.L;\n        maxclusters = length(out.L);\n    end\n\n    % -------------------------------------------------------------------------------\n    % * All the real work is done here.  Classify\n    % -------------------------------------------------------------------------------\n    \n    if size(clusters(1).all_data,1) > 12,\n        disp('More than 12 dimensions (observations per voxel) in original data - using eigenvectors to classify')\n        close all; try, pack, catch, end\n        % we pick the number of CLASSES separately by hand, because # components not a good indicator\n        % of how many classes there are\n        clusters(i).PCA.class = docluster(out.T',[],plotflag);\n    else\n        clusters(i).PCA.class = docluster(out.T',[],plotflag);\n    end\n    \n    % clean up if using locflag\n    clusters(i).PCA.locflag = locflag;\n    if locflag,\n        clusters(i).PCA.pcomps = clusters(i).PCA.pcomps(1:size(clusters(i).all_data,1),:);\n        %clusters(i).PCA.weights = clusters(i).PCA.weights(1:size(clusters(i).all_data,1),:);\n        %clusters(i).PCA.avgs = clusters(i).PCA.avgs(1:size(clusters(i).all_data,1),:);\n    end\n\n    \n    % -------------------------------------------------------------------------------\n    % for each group, separate into contiguous clusters\n    % -------------------------------------------------------------------------------\n        \n    grps = unique(clusters(i).PCA.class(clusters(i).PCA.class~=0)); % values are component of origin\n    for j = 1:length(grps),\n        wh = find(clusters(i).PCA.class==grps(j));\n        XYZ = clusters(i).XYZ(:,wh);\n        cl_index = spm_clusters(XYZ) ./ 100;\n        clusters(i).PCA.class(wh) = clusters(i).PCA.class(wh) + cl_index;\n    end\n    ngrps = length(unique(clusters(i).PCA.class));\n    fprintf(1,'%3.0f contiguous clusters separated by class',ngrps)\n    \n    % -------------------------------------------------------------------------------\n    % average within classes / contiguous regions\n    % -------------------------------------------------------------------------------\n    \n    grps = unique(clusters(i).PCA.class(clusters(i).PCA.class~=0)); % values are component of origin\n    for j = 1:length(grps), \n        clusters(i).PCA.avgs(:,j) = mean(a(:,find(clusters(i).PCA.class==grps(j))),2);, \n        freq(j) = sum(clusters(i).PCA.class == grps(j));    \n    end\n    \n    disp(['Cluster ' num2str(i) ', ' num2str(clusters(i).numVox) ' voxels: ' num2str(size(clusters(i).PCA.pcomps,2)) ' components'])\n    fprintf(1,'\\tMean\\tEigval\\tcorrel\\t')\n    \n    % -------------------------------------------------------------------------------\n    % * display each component and correlation with behavior\n    % -------------------------------------------------------------------------------\n    \n    for j = 1:size(clusters(i).PCA.pcomps,2)\n        \n        %[H,P,CI,STATS] = TTEST(clusters(i).PCA.pcomps(:,j),0,.05,0);\n        % skip the t-test.  t-tests on component scores don't make a lot of sense.\n        fprintf(1,'\\n\\t%3.3f\\t%3.3f\\t',mean(clusters(i).PCA.pcomps(:,j)),clusters(i).PCA.eigval(j))\n    \n        if length(varargin) > 0\n            if ~isempty(varargin{1})\n                co = corrcoef(clusters(i).PCA.pcomps(:,j),varargin{1});\n                co = co(1,2);\n                fprintf(1,'%3.3f\\t',co)\n            end\n        end\n          \n    end\n    fprintf(1,'\\n')\n    \n    % -------------------------------------------------------------------------------\n    % * display classification info\n    % -------------------------------------------------------------------------------\n    disp(['Classified into ' num2str(ngrps) ' groups:'])\n    fprintf(1,'\\tClass\\tVoxels\\tMean\\tt\\tp\\tcorrect. p\\tcorrel\\t')\n    \n    % for each component, test mean value and correlation with behavior\n    for j = 1:length(grps)\n        \n        [H,P,CI,STATS] = TTEST(clusters(i).PCA.avgs(:,j),0,.05,0);\n        fprintf(1,'\\n\\t%3.0f\\t%3.0f\\t%3.3f\\t%3.3f\\t%3.3f\\t%3.3f\\t',j,freq(j),mean(clusters(i).PCA.avgs(:,j)),STATS.tstat,P,P .* size(clusters(i).PCA.avgs,2))\n    \n        if length(varargin) > 0\n            if ~isempty(varargin{1})\n                co = corrcoef(clusters(i).PCA.avgs(:,j),varargin{1});\n                co = co(1,2);\n                fprintf(1,'%3.3f\\t',co)\n            end\n        end\n          \n    end\n    fprintf(1,'\\n')\n    \n    % -------------------------------------------------------------------------------\n    % * Plot, if requested\n    % -------------------------------------------------------------------------------\n    \n    if plotflag,\n        figure('Color','w'), subplot(1,3,1), imagesc(a), title(['Cl ' num2str(i) ': Data']), xlabel('Voxels'),ylabel('Subjects')\n        subplot(1,3,2), imagesc(clusters(i).PCA.weights'), title(['Weights (eigenvectors)']), xlabel('Voxels'),ylabel('Eigenvectors')\n        subplot(1,3,3), imagesc(clusters(i).PCA.pcomps), title(['Component scores (predictions)']), xlabel('Voxels'),ylabel('Subjects')\n        \n        a = [clusters(i).PCA.class' a']; a=sortrows(a,1); a = a(:,2:end)';\n        figure;subplot 131; imagesc(a),title(['Cl ' num2str(i) ':Data sorted by class']), xlabel('Class'),ylabel('Subjects'),\n        xlab = [sort(clusters(i).PCA.class(clusters(i).PCA.class~=0)) clusters(i).PCA.class(clusters(i).PCA.class==0)]; \n        set(gca,'XTick',1:length(clusters(i).PCA.class)); set(gca,'XTickLabel',xlab)\n        subplot 132; imagesc(clusters(i).PCA.avgs),title('Class averages'), xlabel('Class'),ylabel('Subjects'),\n        subplot 133; if length(varargin) > 0, if ~isempty(varargin{1}), imagesc(varargin{1}'), title('Behavior'),end,end\n        \n    end\n\n    else    \n        disp(['Cluster ' num2str(i) ' has less than 3 voxels.'])\n        clusters(i).PCA.class = ones(1,clusters(i).numVox);\n        clusters(i).PCA.avgs = clusters(i).timeseries;\n        grps = 1;\n        if ~isfield(clusters,'correl'), clusters(1).correl = [];, end\n    end\n    \n    \n    % -------------------------------------------------------------------------------\n    % * separate into subclusters, based on class membership\n    % -------------------------------------------------------------------------------\n\n    if ~isfield(clusters,'correl'), clusters(i).correl = [];, end\n    disp('Recomputing correlations and z-scores and saving in subclusters')\n    if ~isfield(clusters,'XYZ'), clusters(i).XYZ = ones(3,size(clusters(i).all_data,2));, end\n    if ~isfield(clusters,'Z'), clusters(i).Z = ones(1,size(clusters(i).XYZ,2));, end\n    clear subc\n    \n    for j = 1:length(grps)\n        \n        try\n            subc(j) = clusters(i);\n        catch\n            warning('clusters does not have all required fields.'); break\n        end\n        \n        wh = find(clusters(i).PCA.class == grps(j));\n        \n        if length(varargin) > 0\n            if ~isempty(varargin{1})\n                co = corrcoef(clusters(i).PCA.avgs(:,j),varargin{1});\n                subc(j).correl = co(1,2);\n            end\n        end\n                 \n        if isfield(subc(j),'title'), subc(j).title = [subc(j).title '_SUBCL_' num2str(j)];, end\n        if isfield(subc(j),'name'), subc(j).name = [subc(j).name '_SUBCL_' num2str(j)];, end\n        if isfield(subc(j),'numVox'), subc(j).numVox = length(wh);, end\n        if isfield(subc(j),'Z'), subc(j).Z = subc(j).Z(wh);, end\n        if isfield(subc(j),'XYZmm'), subc(j).XYZmm = subc(j).XYZmm(:,wh);, end\n        if isfield(subc(j),'XYZ'), subc(j).XYZ = subc(j).XYZ(:,wh);, end\n        \n        if isfield(subc(j),'timeseries'), subc(j).timeseries = nanmean(subc(j).all_data(:,wh)')';, end\n        %if isfield(subc(j),'snr'), subc(j).snr = subc(j).snr(wh);, end\n        if isfield(subc(j),'center'), subc(j).center = center_of_mass(subc(j).XYZ,subc(j).Z);, end\n        if isfield(subc(j),'mm_center'), subc(j).mm_center = center_of_mass(subc(j).XYZmm,subc(j).Z);, end\n        \n        if isfield(subc(j),'all_data'), \n            subc(j).all_data = subc(j).all_data(:,wh);, \n            for k = 1:size(subc(j).all_data,2)\n                [H,P,CI,STATS] = ttest(subc(j).all_data(:,k),0,.05,0);\n                subc(j).Z(k) = spm_t2z(STATS.tstat,STATS.df);\n            end\n        end\n            \n            \n    end\n    \n    subclusters{i} = subc;\n   \n    \nend\n\n\nreturn\n\n\n\nfunction [b,v,d,class] = pc(a,corrflag)\n% a is original matrix, b is principal components, v is eigenvectors \n% (weights on columns, which = weights on voxels)\n% class is classification of voxels into groups based on component loadings\n\nif corrflag, [v,d]=eig(corrcoef(a));, else, [v,d]=eig(cov(a));,end\nb = (pinv(v) * a')' ./ repmat((diag(d)').^.5,size(a,1),1);\n% i made this up: think of rptating each subject's scores (in cols of a')\n% by the rotation matrix pinv(v), and normalizing by the sqrt of the eigenvalues\n% pinv(v) and v are rotation matrices because det = 1, no shearing or dilation\n%\n% this appears to work to give scores as well\n% both methods (above,below) are scaled versions of the splus factor scores\n% the problem is that doing it two different ways in splus flips the signs\n% of some components and not others (gui vs cmd line).\n\n%X = a; R = corrcoef(a); A = v * (d^.5); B = inv(R) * A;\n%scores = X * B;\n% X is data, A is factor loading matrix, B is factor score coeff matrix\n% this method, from the text, and the one giving b above produce identical results\n\nA = v * (d^.5);\n\nb = fliplr(b); v = fliplr(v); A = fliplr(A); %scores = fliplr(scores);\n\nnum = min(10,sum(diag(d) >= 1));\nb = b(:,1:num); v = v(:,1:num); A = A(:,1:num); \norigd = diag(d);\nd = diag(d)'; d= fliplr(d); d = d(1:num);\n\nif num == 0, warning('No eigenvalues above 1!');, origd, class = [];\n    \nelse\n    % classify each voxel into a group based on loading\n    % use A, which re-introduces the comp variance, because we\n    % want relationships with more variance to count more.\n    % This just doesn't work so hot.  See docluster, below.\n    \n    %wh = A' == repmat(max(A'),size(A,2),1);\n    %for i = 1:size(wh,2), tmp = find(wh(:,i));, class(i) = tmp(1); end\n    %class(max(A') < .3) = 0;\n    \nend\n\n\n%figure;plot(b,'r'),hold on;plot(a,'k'), hold on; plot(mean(a,2),'g--'),legend({'eig' 'orig' 'avg'})\n\nreturn\n\n\n\nfunction class = docluster(a,maxclusters,doplot)\n\n    Y = pdist(a','euclid');     % transpose so the voxels are observations, eigenvectors the variables\n    Z = linkage(Y,'complete');\n    if maxclusters > 1\n        class = cluster(Z,maxclusters)';\n        \n        if doplot, \n            dendrogram(Z,0); title('Dendrogram for clustering')\n        end\n    \n    else\n        dendrogram(Z,0); title('Dendrogram for clustering')\n        set(gcf,'Position',[10   601   800   500])\n        maxclusters = input('Pick number of classes to save: ');\n        \n        if maxclusters == 1,\n            class = ones(1,size(a,2));\n        else\n            class = cluster(Z,maxclusters)';\n        end\n        \n    end\n    \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/Cluster_contig_region_tools/Cluster-based_multivar_tools/cluster_princomp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5647479644623615}}
{"text": "function r = cot(a)\n%COT          Hessian (elementwise) cotangent\n%\n\n% written  04/04/04     S.M. Rump\n% modified 04/06/05     S.M. Rump  rounding unchanged\n% modified 09/28/08     S.M. Rump  check for rounding to nearest improved\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  e = 1e-30;\n  if 1+e==1-e                           % fast check for rounding to nearest\n    rndold = 0;\n  else\n    rndold = getround;\n    setround(0)\n  end\n\n  K = prod(size(a.x));\n  if K==1                   % scalar hessian\n    \n    r.x = cot(a.x);\n    f = -1 - sqr(r.x);\n    r.dx = f * a.dx;\n    r.hx = f * ( a.hx - reshape( (r.x*a.dx) * a.dx.' , size(a.hx) ) );\n    \n  else                      % matrix hessian\n    \n    N = getappdata(0,'INTLAB_HESSIAN_NUMVAR');\n    N2 = N^2;\n    \n    r.x = cot(full(a.x));\n    if issparse(a.hx)               % input sparse\n      \n      ax = (-1) - sqr(full(r.x(:)));\n      sizeax = length(ax);\n      [ia,ja,sa] = find(a.dx);\n      % check for emptyness: cures Matlab bug\n      % a=sparse([],[],[],2,1), [i,j,s]=find(a), s(i).*s(:)  yields error\n      if isempty(ia)\n        r.dx = sparse([],[],[],N,sizeax);\n        r.hx = sparse([],[],[],N2,sizeax);\n      else\n        adx1 = -r.x(:);\n        if isa(a.x,'intval')          % sparse intval\n          rdx = times(ax(ja),sa(:),0);\n          adx1 = times(adx1(ja),sa(:),0);\n          if rdx.complex\n            r.dx = intval( sparse(ia,ja,rdx.mid,N,sizeax) , sparse(ia,ja,rdx.rad,N,sizeax) , 'midrad' );\n          else\n            r.dx = intval( sparse(ia,ja,rdx.inf,N,sizeax) , sparse(ia,ja,rdx.sup,N,sizeax) , 'infsup' );\n          end\n          if adx1.complex\n            adx1 = intval( sparse(ia,ja,adx1.mid,N,sizeax) , sparse(ia,ja,adx1.rad,N,sizeax) , 'midrad' );\n          else\n            adx1 = intval( sparse(ia,ja,adx1.inf,N,sizeax) , sparse(ia,ja,adx1.sup,N,sizeax) , 'infsup' );\n          end\n        else                          % sparse point  \n          r.dx = sparse(ia,ja,ax(ja).*sa(:),N,sizeax);        \n          adx1 = sparse(ia,ja,adx1(ja).*sa(:),N,sizeax);        \n        end                           \n        r.hx = adx2rhx(N,sizeax,adx1,r.dx);\n      end\n      [ia,ja,sa] = find(a.hx);      % sparse point or intval\n      % check for emptyness: cures Matlab bug\n      % a=sparse([],[],[],2,1), [i,j,s]=find(a), s(i).*s(:)  yields error\n      if ~isempty(ia)\n        if isa(a.x,'intval')\n          rhx = times(ax(ja),sa(:),0);\n          if rhx.complex\n            r.hx = r.hx + intval( sparse(ia,ja,rhx.mid,N2,sizeax) , sparse(ia,ja,rhx.rad,N2,sizeax) , 'midrad' );\n          else\n            r.hx = r.hx + intval( sparse(ia,ja,rhx.inf,N2,sizeax) , sparse(ia,ja,rhx.sup,N2,sizeax) , 'infsup' );\n          end\n        else\n          r.hx = r.hx + sparse(ia,ja,ax(ja).*sa(:),N2,sizeax);\n        end\n      end\n      \n    else                            % input full\n      \n      r.x = cot(a.x);\n      rx = r.x(:).';\n      f = -1 - sqr(rx);\n      f = f(ones(N*N,1),:);\n      r.dx = a.dx .* f(1:N,:);\n      adx = repmat(rx,N,1) .* a.dx;\n      r.hx = f .* ( a.hx - adx(repmat(1:N,N,1),:) .* a.dx(repmat(1:N,1,N),:) );\n      \n    end\n    \n  end\n  \n  r = class(r,'hessian');\n  \n  if rndold\n    setround(rndold)\n  end\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/hessian/@hessian/cot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5647479549643023}}
{"text": "function gX = ratquadKernGradX(kern, X, X2)\n\n% RATQUADKERNGRADX Gradient of RATQUAD kernel with respect to input locations.\n% FORMAT\n% DESC computes the gradident of the rational quadratic\n% kernel with respect to the input positions where both the row\n% positions and column positions are provided separately.\n% ARG kern : kernel structure for which gradients are being\n% computed.\n% ARG x1 : row locations against which gradients are being computed.\n% ARG x2 : column locations against which gradients are being computed.\n% RETURN g : the returned gradients. The gradients are returned in\n% a matrix which is numData2 x numInputs x numData1. Where numData1 is\n% the number of data points in X1, numData2 is the number of data\n% points in X2 and numInputs is the number of input\n% dimensions in X.\n%\n% SEEALSO ratquadKernParamInit, kernGradX, ratquadKernDiagGradX\n%\n% COPYRIGHT : Neil D. Lawrence, 2006\n\n% KERN\n\ngX = zeros(size(X2, 1), size(X2, 2), size(X, 1));\nfor i = 1:size(X, 1);\n  gX(:, :, i) = ratquadKernGradXpoint(kern, X(i, :), X2);\nend\n  \n\nfunction gX = ratquadKernGradXpoint(kern, x, X2)\n\n% RATQUADKERNGRADXPOINT Gradient with respect to one point of x.\n\ngX = zeros(size(X2));\nn2 = dist2(X2, x);\nwi2 = (.5/(kern.lengthScale*kern.lengthScale*kern.alpha));\nratquadPart = kern.variance*(1+n2*wi2).^-(kern.alpha+1)/(kern.lengthScale*kern.lengthScale);\nfor i = 1:size(x, 2)\n  gX(:, i) =(X2(:, i) - x(i)).*ratquadPart;\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/ratquadKernGradX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5647479541185956}}
{"text": "function [rVect, vVect] = getStateAtTime(bodyInfo, time, gmu)\n%getStateAtTime Summary of this function goes here\n%   Detailed explanation goes here\n    if(isstruct(bodyInfo) || (isprop(bodyInfo,'propTypeEnum') && bodyInfo.propTypeEnum == BodyPropagationTypeEnum.TwoBody) || (numel(time) == 1 && time == bodyInfo.epoch))\n        numTimes = length(time);\n\n        oneArray = (zeros(1, numTimes)+1);\n\n        sma = bodyInfo.sma * oneArray;\n        ecc = bodyInfo.ecc * oneArray;\n        inc = AngleZero2Pi(deg2rad(bodyInfo.inc)) * oneArray;\n        raan = AngleZero2Pi(deg2rad(bodyInfo.raan)) * oneArray;\n        argp = AngleZero2Pi(deg2rad(bodyInfo.arg)) * oneArray;\n        M0 = deg2rad(bodyInfo.mean) * oneArray; \n\n        n = computeMeanMotion(sma, gmu);\n        deltaT = time - bodyInfo.epoch;\n        M = (M0(:) + n(:).*deltaT(:))';\n        tru = computeTrueAnomFromMean(M, ecc);\n\n        if(length(tru) > 1)\n            [rVect, vVect] = vect_getStatefromKepler(sma, ecc, inc, raan, argp, tru, gmu, true); \n        else\n            [rVect, vVect] = getStatefromKepler_Alg(sma, ecc, inc, raan, argp, tru, gmu);\n%             [rVect, vVect] = vect_getStatefromKepler(sma, ecc, inc, raan, argp, tru, gmu, true); \n        end\n        \n    elseif(bodyInfo.propTypeEnum == BodyPropagationTypeEnum.Numerical)\n        [rVect, vVect] = bodyInfo.numIntStateCache.getCachedBodyStateAtTime(time);\n        \n    else\n        error('Unknown celestial body prop sim type.');\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/astrodynamics/getStateAtTime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5647479510349934}}
{"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%==============================================================================\n%\n% Tutorial for FAIR: various distances and Multi-Level Parametric Image Registration\n%\n%   - data                 PETCT, Omega=(0,140)x(0,151), level=4:7, m=[128,128]\n%   - viewer               viewImage2D\n%   - interpolation        splineInter\n%   - distance             {'SSD','NCC','MI','NGF'}\n%   - transformation       affine2D\n% see also E7_PETCT_MLPIR_ext\n%==============================================================================\n\nclear, close all, help(mfilename);\nsetup2DPETCTData;                                         % load data\n\n% a list of distance measures to be used\nDM = {'SSD','NCC','MI','NGF'};\n\nOPTpara = FAIRcell2struct(optPara('PIR-GN'));\n\nfor dm = 1:length(DM), % run over all distance measures\n\n  % initialize interpolation, using a smooth representation (theta=1e0) \n  imgModel('reset','imgModel','splineInter','regularizer','moments','theta',1e0);\n\n  % initialize transformation, create initial guess and reference for stopping\n  trafo('reset','trafo','affine2D'); wStop = trafo('w0'); w0 = wStop;\n\n  % initialize distance and display options\n  distance('reset','distance',DM{dm}); distance('disp')\n  \n  % run MLPIR using sufficient amount of details (level=5)\n  wSmooth =  MLPIR(ML,'minLevel',5,'plotIter',0,'plotMLiter',0);\n\n  % refine interpolation (theta=1e-3)\n  imgModel('reset','imgModel','splineInter','regularizer','moments','theta',1e-3);\n  level = length(ML); omega = ML{level}.omega; m = ML{level}.m;\n  [T,R] = imgModel('coefficients',ML{level}.T,ML{level}.R,omega);\n  \n  % start PIR, using the result from the smooth problem as starting guess\n  \n  % initialize plots\n  FAIRplots('set','mode','PIR');\n  FAIRplots('init',struct('Tc',T,'Rc',R,'omega',omega,'m',m));\n\n  % optimize\n  xc = getCellCenteredGrid(omega,m);   \n  Rc = imgModel(R,omega,xc);\n  fctn = @(wc) PIRobjFctn(T,Rc,omega,m,0,[],[],xc,wc); fctn([]);\n  [wc,his] = GaussNewton(fctn,w0,OPTpara{:});\n\n  % visualize results\n  yc = trafo(wc,xc);\n  R0 = imgModel(R,omega,xc);\n  T0 = imgModel(T,omega,xc);\n  Tc = imgModel(T,omega,yc);\n\n  figure(11); clf;\n  viewImage(T0,omega,m,'axis','off'); hold on;\n  plotGrid(yc,omega,m,'spacing',ceil(m/32),'linewidth',2,'color','w');\n\n  figure(12); clf;\n  overlayImage2D(Tc,R0,omega,m); axis off;\nend;\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/E7_PETCT_MLPIR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949104, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5647479415369346}}
{"text": "function [equality center] = doquality(Xcx,X)\n% :Usage:\n% ::\n%\n%     [equality] = doquality(Xcx,X)\n%\n% :Inputs:\n%\n%   **Xcx:**\n%        binary indicator matrix of cluster assignments, \n%\n%   **X:**\n%        stimulus coordinates in group space\n%\n%        also: takes group spaces with zeros;\n\n\nif size(Xcx>1);    \n    for i = 1:size(Xcx,2)    % for each class\n        tmp = mean(X(find(Xcx(:,i)),:),1);     % get center of this class\n        center(i,:) = tmp;    \n        % dist of all points in X from each center\n        % number of cols of X is the number of dimensions; sums squared\n        % vals across dims, takes sqrt to get Euclidean distance in N-d\n        % space\n        d(:,i) = sum((repmat(tmp,size(X,1),1) - X).^2,2).^0.5;\n    end\n    \n    % rows of d are objects, columns are classes, values are dist from\n    % class center\n    for i=1:size(d,1)                   % i is the object (point)\n        \n        myclass = find(Xcx(i,:)==1);    % index of which class it is\n        \n        edist(i) = d(i,myclass);        %distance to center of own class\n        \n        otherclass = find(Xcx(i,:)==0);     % indices of columns for other classes\n        \n        otherdist(i) = min(d(i,otherclass));  %distance to center of cluster\n        \n    end\n\n    % for each point, quality is distance to nearest neighbor - dist to own\n    % cl / mak of those two\n    equality = (otherdist - edist) ./ max([edist;otherdist]);\n    \nelse\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/doquality.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.6261241842048093, "lm_q1q2_score": 0.5647143544121288}}
{"text": "function sensor_out=la_sen(acc, gyro, gyro_der, sen_la, sen_or, sen_typ)\nnsen=size(sen_typ,1);\nsensor_out=zeros(nsen,1);\nfor in=1:nsen;\n    %lever arm\n    Csm=sen_or(:,:,in);\n    la=sen_la(:,in);\n    \n    %Acceleration\n    acc_sen=Csm'*(acc+cross(gyro,cross(gyro,la))+cross(gyro_der,la));\n\n    %Rotation rate\n    gyro_sen=Csm'*gyro;\n\n    if (sen_typ(in)==1)\n        sensor_out(in)=acc_sen(1);\n    elseif (sen_typ(in)==2)\n        sensor_out(in)=gyro_sen(1);\n    end\nend", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/INS/la_sen_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206686206198, "lm_q2_score": 0.6261241632752916, "lm_q1q2_score": 0.5647143239807771}}
{"text": "function [imgPyr, maskPyr, scaleImgPyr] = sc_create_pyramid(img, mask, optS)\n\n% SC_CREAT_IMG_PYRAMID\n%\n% Create image pyramid with linear or log scale for coarse to fine image\n% completion\n%\n% Input:\n%   - img:  input image with hole\n%   - mask: Hole mask\n%   - optS: options\n% Output:\n%   - imgPyr:      Image pyramid\n%   - maskPyr:     Mask pyramid\n%   - scaleImgPyr: Image dimensions in each level\n\n% Image size in the high-resolution image\n[imgHeight, imgWidth, nCh] = size(img);\nimg = sc_init_coarsest_level(img, logical(mask));\n\n% =========================================================================\n% Create pyramid: scale\n% =========================================================================\nscaleImgPyr = sc_create_scale_pyramid(imgHeight, imgWidth, optS);\n\n% =========================================================================\n% Create pyramid: mask\n% =========================================================================\nmaskPyr = sc_create_image_pyramid(mask, scaleImgPyr, 'mask', optS); \n\n% =========================================================================\n% Create pyramid: image\n% =========================================================================\nimgPyr = sc_create_image_pyramid(img, scaleImgPyr, 'image', optS); \n\n% =========================================================================\n% Recover image boundary \n% =========================================================================\n\n% nCh = 3;\n% for iLvl = 1: optS.numPyrLvl\n%     maskCur  = maskPyr{iLvl};\n%     bdRegion = maskCur < 0.99 & maskCur > 0.1;\n%     bdRegionC = bdRegion(:,:,ones(nCh,1));\n%     \n%     imgCur   = imgPyr{iLvl};\n%     imgCurBd = bsxfun(@rdivide, imgCur, maskCur);\n%     imgCur(bdRegionC) = imgCurBd(bdRegionC);\n%     imgPyr{iLvl} = imgCur;\n% end\n\n\n% Initialize the coarsest level\nimgPyr{optS.numPyrLvl} = sc_init_coarsest_level(imgPyr{optS.numPyrLvl}, maskPyr{optS.numPyrLvl});\n\n% Convert to single type\nimgPyr = cellfun(@im2single, imgPyr, 'UniformOutput', false);\n\nend\n\nfunction img = sc_init_coarsest_level(img, mask)\n\n% Get the inital solution\n[~, idMap] = bwdist(~mask, 'euclidean');\n\n% Intepolate only in the interior to avoid dark values near the image borders\nmaskInt = mask;\nmaskInt(1,:) = 0;   maskInt(end,:) = 0;\nmaskInt(:,1) = 0;   maskInt(:,end) = 0;\n\nfor ch = 1: 3\n    imgCh = img(:,:,ch);\n    imgCh = imgCh(idMap);\n    img(:,:,ch) = roifill(imgCh, maskInt);\nend\n\nend\n\nfunction imgPyr = sc_create_image_pyramid(img, scaleImgPyr, imageType, optS)\n\n% h = fspecial('gaussian', 5, 1);\n\n% Initialize image pyramid\nimgPyr  = cell(optS.numPyrLvl, 1);\n\n% The finest level\nimgPyr{1} = img;\n\n%\nfor iLvl = 2: optS.numPyrLvl\n    imgHCurLvl = scaleImgPyr{iLvl}.imgSize(1);\n    imgWCurLvl = scaleImgPyr{iLvl}.imgSize(2);\n    \n    % Previous layer\n    imgCur = imgPyr{iLvl - 1};\n\n    % Anti-alising by blurring\n%     imgCur   = imfilter(imgCur, h, 'same', 'replicate', 'conv');\n      \n    % Resampling\n    imgPyr{iLvl} = imresize(imgCur,  [imgHCurLvl, imgWCurLvl], optS.resampleKernel);\nend\n\n\nif(strcmp(imageType, 'mask'))\n    % Convert resampled masks into logical type\n    for iLvl = 1: optS.numPyrLvl\n        imgPyr{iLvl} = imgPyr{iLvl} > 0.5;\n    end\nend\n\nend\n\nfunction scaleImgPyr = sc_create_scale_pyramid(imgHeight, imgWidth, optS)\n\n% Compute the coarsest image scale\nimgSizeMin   = min(imgHeight, imgWidth);\ncoarestScale = optS.coarestImgSize/imgSizeMin;\n\n% Compute the scale in each layer in the image pyramid\nif(optS.useLogScale)      % use log scale\n    scalePyr = 2.^linspace(0, log2(coarestScale), optS.numPyrLvl);\nelse                      % use linear scale\n    scalePyr = linspace(1, coarestScale, optS.numPyrLvl);\nend\n\n% Image size in each layer\nimgHPyr = round(imgHeight *scalePyr);\nimgWPyr = round(imgWidth  *scalePyr);\n\n% Initialize scales\nscaleImgPyr = cell(optS.numPyrLvl, 1);\n\n% Finest level\nscaleImgPyr{1}.imgScale = 1;\nscaleImgPyr{1}.imgSize = [imgHeight, imgWidth];\n\n% Downsampled images\nfor k = 2: optS.numPyrLvl\n    scaleImgPyr{k}.imgScale = scalePyr(k);\n    scaleImgPyr{k}.imgSize  = [imgHPyr(k), imgWPyr(k)];\nend\n\nend", "meta": {"author": "jbhuang0604", "repo": "StructCompletion", "sha": "25668dea193801140fafe0a722ccb1e955509ec4", "save_path": "github-repos/MATLAB/jbhuang0604-StructCompletion", "path": "github-repos/MATLAB/jbhuang0604-StructCompletion/StructCompletion-25668dea193801140fafe0a722ccb1e955509ec4/source/sc_create_pyramid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5646642657502482}}
{"text": "% TOEPLITZ_BLOCK - Constructs a block-Toeplitz matrix.\n%\n%   Y = TOEPLITZ_BLOCK(X)\n%\n% X = [X_1, X_2, X_3, ..., X_N]\n%\n% Y = [X_1 X_2 X_3 ... X_N\n%      X_2 X_1 X_2 ... ...\n%      X_3 X_2 X_1 ... ...\n%      ... ... ... ... ...\n%      X_N ... X_3 X_2 X_1]\n\n\nfunction Y = toeplitz_block(X)\n\n[M,N] = size(X);\n\nif mod(N,M) ~= 0\n  error('The number of columns must be a multiple of the number of rows.')\nend\n\nD = N/M;\n\nif issparse(X)\n  t = cputime();\n  \n  nonzeros = zeros(D,1);\n  i = cell(D,1);\n  j = cell(D,1);\n  v = cell(D,1);\n  [i{1},j{1},v{1}] = find(X(:,1:M));\n  nonzeros(1) = D*length(v{1});\n  for d=2:D\n    k = (d-1)*M+1;\n    l = d*M;\n    [i{d},j{d},v{d}] = find(X(:,k:l));\n    nonzeros(d) = 2 * (D-d+1) * length(v{d});\n  end\n  nzs = sum(nonzeros);\n  \n  \n  %time = cputime() - t, t = cputime();\n  \n  I = zeros(nzs,1);\n  J = zeros(nzs,1);\n  values = zeros(nzs,1);\n  \n  %time = cputime() - t, t = cputime();\n\n  z = 1;\n  for d2=1:D\n    for d1=1:D\n      ind = abs(d1-d2) + 1;\n      jnd = z:(z+length(v{ind})-1);\n      I(jnd) = i{ind} + (d1-1)*M;\n      J(jnd) = j{ind} + (d2-1)*M;\n      values(jnd) = v{ind};\n      z = z + length(v{ind});\n    end\n  end\n\n  %time = cputime() - t, t = cputime();\n  \n  Y = sparse(I,J,values,N,N,nzs);\n  \n  %time = cputime() - t, t = cputime();\n  \n\nelse\n  \n  Y = zeros(N,N);\n  for i=1:D\n    for j=1:D\n      ind = abs(i-j) + 1;\n      k = (i-1)*M+1;\n      l = (j-1)*M+1;\n      m = (ind-1)*M+1;\n      Y(k:(k+M-1),l:(l+M-1)) = X(:,m:(m+M-1));\n    end\n  end\n  \nend\n\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/toeplitz_block.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5645968209631618}}
{"text": "function edge = lineToEdge3d(line)\n%LINETOEDGE3D Convert a 3D straight line to a 3D finite edge.\n%\n%   EDGE = lineToEdge3d(LINE)\n%   Returns the edge with same origin as the line LINE, and with second\n%   extremity corresponding to the addition of line origin and direction.\n%   LINE is represented as [X0 Y0 Z0  DX DY DZ]\n%   EDGE is represented as [X1 Y1 Z1  X2 Y2 Z2]\n%\n%   Example\n%     line = [3 4 5  1 2 3];\n%     edge = lineToEdge3d(line)\n%     edge =\n%          3   4   5   4   6   8\n%\n%   See also \n%     lines3d, edges3d, edgeToLine3d\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2019-05-07, using Matlab 9.6.0.1072779 (R2019a)\n% Copyright 2019-2022 INRA - Cepia Software Platform\n\nedge = [line(:, 1:3) line(:,1:3)+line(:,4:6)];\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/lineToEdge3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.5645968147246005}}
{"text": "% resample the set of particles.\n% A particle has a probability proportional to its weight to get\n% selected. A good option for such a resampling method is the so-called low\n% variance sampling, Probabilistic Robotics pg. 109\nfunction newParticles = resample(particles)\n\nnumParticles = length(particles);\n\nw = [particles.weight];\n\n% normalize the weight\nw = w / sum(w);\n\n% consider number of effective particles, to decide whether to resample or not\nuseNeff = false;\n%useNeff = true;\nif useNeff\n  neff = 1. / sum(w.^2);\n  neff\n  if neff > 0.5*numParticles\n    newParticles = particles;\n    for i = 1:numParticles\n      newParticles(i).weight = w(i);\n    end\n    return;\n  end\nend\n\nnewParticles = struct;\n\n% TODO: implement the low variance re-sampling\n\n% the cummulative sum\ncs = cumsum(w);\nweightSum = cs(length(cs));\n\n% initialize the step and the current position on the roulette wheel\nstep = weightSum / numParticles;\nposition = unifrnd(0, weightSum);\nidx = 1;\n\n% walk along the wheel to select the particles\nfor i = 1:numParticles\n  position += step;\n  if (position > weightSum)\n    position -= weightSum;\n    idx = 1;\n  end\n  while (position > cs(idx))\n    idx++;\n  end\n  newParticles(i) = particles(idx);\n  newParticles(i).weight = 1/numParticles;\nend\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/tools/resample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888481, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5645902156369845}}
{"text": "function T = slgbfe(X, G, Gc, dy, fm, varargin)\n%SLGBFE Performs Graph-based Feature Extraction Learning\n%\n% $ Syntax $\n%   - T = slgbfe(X, G, Gc, dy, fm, ...)\n%\n% $ Arguments $\n%   - X:        The sample matrix \n%   - G:        The graph to be optimized\n%   - Gc:       The constraint graph\n%   - dy:       The dimension of feature space\n%   - fm:       The formulation type\n%   - T:        The learned transform matrix (dx x dy)\n%               the transform is done by y = T' * x\n%\n% $ Description $\n%   - T = slgbfe(X, G, Gc, dy, fm, ...) performs graph-based feature \n%     extraction learning. It is to solve the following optimization.\n%       \n%       min/max  T'X M(G) X'T,    s.t. T'X M(Gc) X'T = I\n%\n%     The concrete formulation depends on the formulation type given in\n%     fm = {fg, fc}. For fg, it has the following three types:\n%       - 'minW':   do minimization with M(G) = W\n%       - 'maxW':   do maximization with M(G) = W\n%       - 'minL':   do minimization with M(G) = L = D - W\n%       - 'maxL':   do maximization with M(G) = L = D - W\n%     For fc, it has the following three types:\n%       - 'O':      constraint T be orthogonal: T'*T = I (ignore Gc)\n%       - 'I':      constraint T'* X * X' * T = I (ignore Gc)\n%       - 'WC':     constraint with M(Gc) = W of Gc\n%       - 'LC':     constraint with M(Gc) = L of Gc: D - W\n%     In the aforementioned formulation, W is the adjacency matrix, while\n%     L is the Laplacian matrix. When Gc is ignored (as in 'O' and 'I'),\n%     you can just input Gc as [].\n%\n%     You can further specify the following properties to control the \n%     learning process:\n%       - 'whparams':  The parameters for doing whitening of M(Gc), please\n%                      refer to the function slwhiten_from_cov. The params \n%                      are given in a cell array as {method, ...}. \n%                      default = {}\n%       - 'skip':      The number of components to be skipped. default = 0\n%\n% $ Remarks $\n%   - The implementation is based on slgembed.\n%\n%   - The function will not centralize the samples, if it is needed please\n%     centralize them before invoking.\n%\n% $ History $\n%   - Created by Dahua Lin, on Sep 17, 2006\n%\n\n%% parse and verify input arguments\n\nif nargin < 5\n    raise_lackinput('slgbfe', 5);\nend\n\nif ~isnumeric(X) || ndims(X) ~= 2\n    error('sltoolbox:invalidarg', 'X should be a 2D numeric matrix');\nend\nn = size(X, 2);\n\nif ~iscell(fm) || length(fm) ~= 2\n    error('sltoolbox:invalidarg', 'fm should be a length-2 cell array');\nend\nfg = fm{1};\nfc = fm{2};\n\ngi = slgraphinfo(G, {[n, n]});\nW = sladjmat(G, ...\n    'valtype', 'numeric', ...\n    'sparse', strcmp(gi.form, 'adjmat') && issparse(G));\n\nif strcmp(fc, 'WC') || strcmp(fc, 'LC')\n    if isempty(Gc)\n        error('sltoolbox:invalidarg', ...\n            'When fc is WC or LC, Gc should not be empty');\n    end\n    slgraphinfo(Gc, {'adjmat', [n, n]});\n    if isnumeric(Gc)\n        Wc = Gc;\n    else\n        Wc = double(Gc);\n    end\nelse\n    Wc = [];\nend\n\n\nopts.whparams = {};\nopts.skip = 0;\nopts = slparseprops(opts, varargin{:});\n\n\n%% Construct problem\n\n% enforce symmetry\nW = (W + W') * (1/2);\nif ~isempty(Wc)\n    Wc = (Wc + Wc') * (1/2);\nend\n\n% construct re-formulated G: R\nswitch fg\n    case 'maxW'\n        R = X * W * X';\n        rfg = 'maxW';\n    case 'minW'\n        R = X * W * X';\n        rfg = 'minW';\n    case 'maxL'\n        R = X * make_Lmat(W) * X';\n        rfg = 'maxW';\n    case 'minL'\n        R = X * make_Lmat(W) * X';\n        rfg = 'minW';\n    otherwise\n        error('sltoolbox:invalidarg', 'Invalid fg name: %s', fg);\nend    \n\n% construct re-formulated Gc: Rc\nswitch fc\n    case 'O'\n        Rc = [];\n        rfc = 'I';\n    case 'I'\n        Rc = X * X';\n        rfc = 'WC';\n    case 'WC'\n        Rc = X * Wc * X';\n        rfc = 'WC';\n    case 'LC'\n        Rc = X * make_Lmat(Wc) * X';\n        rfc = 'WC';\n    otherwise\n        error('sltoolbox:invalidarg', 'Invalid fc name: %s', fc);\nend\n\n\n%% solve problem\n\nY = slgembed(R, Rc, dy, {rfg, rfc}, ...\n    'inv', opts.whparams, ...\n    'skip', opts.skip);                 \nT = Y';\n\n\n%% Computational routines\n\nfunction L = make_Lmat(W)\n\nvD = sum(W, 1)';\nif issparse(vD)\n    vD = full(vD);\nend\n\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\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/slgbfe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888481, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5645902101813675}}
{"text": "% Downsampling procedure.\n%\n% Arguments:\n%   'I': image\n%   downsampling filter 'filter', should be a 2D separable filter.\n%   'border_mode' should be 'circular', 'symmetric', or 'replicate'. See 'imfilter'.\n%   subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional)\n%\n% tom.mertens@gmail.com, August 2007\n% sam.hasinoff@gmail.com, March 2011  [handle subwindows, reweighted boundaries]\n%\n\nfunction [R,subwindow_child] = downsample(I, filter, subwindow)\n\nr = size(I,1);\nc = size(I,2);\nif ~exist('subwindow','var')\n    subwindow = [1 r 1 c];\nend\nsubwindow_child = child_window(subwindow);\n\nborder_mode = 'reweighted';\n%border_mode = 'symmetric';\n\nswitch border_mode\n    case 'reweighted'       \n        % low pass, convolve with 2D separable filter\n        R = imfilter(I,filter);\n        \n        % reweight, brute force weights from 1's in valid image positions\n        Z = imfilter(ones(size(I)),filter);        \n        R = R./Z;\n        \n    otherwise\n        % low pass, convolve with 2D separable filter\n        R = imfilter(I,filter,border_mode);        \nend\n\n% decimate\nreven = mod(subwindow(1),2)==0;\nceven = mod(subwindow(3),2)==0;\nR = R(1+reven:2:r, 1+ceven:2:c, :);\n\nend", "meta": {"author": "drakeguan", "repo": "cp11fall_project1", "sha": "2660afb11290960a1b798b9b61e20f0393aad578", "save_path": "github-repos/MATLAB/drakeguan-cp11fall_project1", "path": "github-repos/MATLAB/drakeguan-cp11fall_project1/cp11fall_project1-2660afb11290960a1b798b9b61e20f0393aad578/localLaplacian/downsample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5645902047257504}}
{"text": "function adpcm_y = adpcm_encoder(raw_y)\n\n% This m-file is based on the app note: AN643, Adaptive differential pulse\n% code modulation using PICmicro microcontrollers, Microchip Technology\n% Inc. The app note is avaialbe from www.microchip.com\n% Example:  Y = wavread('test.wav');\n%           y = adpcm_encoder(Y);\n%           YY = adpcm_decode(y);\n\nIndexTable = [-1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8];\n         \nStepSizeTable = [7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767];\n\nprevsample = 0;\nprevindex = 1;\n\nNs = length(raw_y);\nn = 1;\n\nraw_y = 32767 * raw_y;          % 16-bit operation\n\nwhile (n <= Ns)\n    predsample = prevsample;\n    index = previndex;\n    step = StepSizeTable(index);\n\n    diff = raw_y(n) - predsample;\n    if (diff >= 0)\n        code = 0;\n    else\n        code = 8;\n        diff = -diff;\n    end\n\n    tempstep = step;\n    if (diff >= tempstep)\n        code = bitor(code, 4);\n        diff = diff - tempstep;\n    end\n    tempstep = bitshift(tempstep, -1);\n    if (diff >= tempstep)\n        code = bitor(code, 2);\n        diff = diff - tempstep;\n    end\n    tempstep = bitshift(tempstep, -1);\n    if (diff >= tempstep)\n        code = bitor(code, 1);\n    end\n\n    diffq = bitshift(step, -3);\n    if (bitand(code, 4))\n        diffq = diffq + step;\n    end\n    if (bitand(code, 2))\n        diffq = diffq + bitshift(step, -1);\n    end\n    if (bitand(code, 1))\n        diffq = diffq + bitshift(step, -2);\n    end\n\n    if (bitand(code, 8))\n        predsample = predsample - diffq;\n    else\n        predsample = predsample + diffq;\n    end\n\n    if (predsample > 32767)\n        predsample = 32767;\n    elseif (predsample < -32768)\n        predsample = -32768;\n    end\n\n    index = index + IndexTable(code+1);\n\n    if (index < 1)\n        index = 1;\n    end\n    if (index > 89)\n        index = 89;\n    end\n\n    prevsample = predsample;\n    previndex = index;\n\n    adpcm_y(n) = bitand(code, 15);\n    %adpcm_y(n) = code;\n    n = n + 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/6480-adpcm-encoder-and-decoder/adpcm_encoder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5645901964212399}}
{"text": "function y = acot(x)\n%ACOT         Implements  acot(x)  for intervals\n%\n%   y = acot(x)\n%\n%interval standard function implementation\n%\n\n% written  10/16/98     S.M. Rump\n% modified 06/24/99     S.M. Rump  complex allowed, sparse input,\n%                                  major revision, improved accuracy\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  improved performance\n% modified 10/20/08     S.M. Rump  check for zero\n% modified 08/26/12     S.M. Rump  global variables removed\n% modified 10/13/12     S.M. Rump  INTLAB_INTVAL_STDFCTS\n%\n\n  index = ( x==0 );\n  y = atan(1./x);\n  \n  if ~isempty(find(index))                    % treat zero indices\n    INTLAB_STDFCTS_PI = getappdata(0,'INTLAB_STDFCTS_PI');\n    PI2 = intval(INTLAB_STDFCTS_PI.PI2INF,INTLAB_STDFCTS_PI.PI2SUP,'infsup');\n    %VVVV  y(index) = PI2;\n    s.type = '()'; s.subs = {index}; y = subsasgn(y,s,PI2);\n    %AAAA  Matlab bug fix\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/acot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5645901880360049}}
{"text": "function [ a, b ] = p26_lim ( dim_num )\n\n%*****************************************************************************80\n%\n%% P26_LIM returns the integration limits for problem 26.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    19 March 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer DIM_NUM, the dimension of the argument.\n%\n%    Output, real A(DIM_NUM), B(DIM_NUM), the lower and upper\n%    limits of integration.\n%\n  a(1:dim_num) = 0.0;\n  b(1:dim_num) = 1.0;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/p26_lim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.5645901868133675}}
{"text": "% Test gmux.\n% The following model, where Y is a gmux node,\n% and M is set to 1, should be equivalent to X1 -> Y\n%\n% X1 Xn M\n% \\ |  /\n%   Y\n\nn = 3;\nN = n+2;\nXs = 1:n;\nM = n+1; \nY = n+2;\ndag = zeros(N,N);\ndag([Xs M], Y)=1; \n\ndnodes = M;\nns = zeros(1, N);\nsz = 2;\nns(Xs) = sz;\nns(M) = n;\nns(Y) = sz;\n\nbnet = mk_bnet(dag, ns, 'discrete', M, 'observed', [M Y]);\n\npsz = ns(Xs(1));\nselfsz = ns(Y);\n\nW = randn(selfsz, psz);\nmu = randn(selfsz, 1);\nSigma = eye(selfsz, selfsz);\n\nbnet.CPD{M} = root_CPD(bnet, M);\nfor i=Xs(:)'\n  bnet.CPD{i} = gaussian_CPD(bnet, i, 'mean', zeros(psz, 1), 'cov', eye(psz, psz));\nend\nbnet.CPD{Y} = gmux_CPD(bnet, Y, 'mean', mu, 'weights', W, 'cov', Sigma);\n  \nevidence = cell(1,N);\nyval = randn(selfsz, 1);\nevidence{Y} = yval;\nm = 2;\n%notm = not(m-1)+1; % only valid for n=2\nnotm = mysetdiff(1:n, m);\nevidence{M} = m;\n\nengines = {};\nengines{end+1} = jtree_inf_engine(bnet);\nengines{end+1} = pearl_inf_engine(bnet, 'protocol', 'parallel');\n\nfor e=1:length(engines)\n  engines{e} = enter_evidence(engines{e}, evidence);\n  mXm{e} = marginal_nodes(engines{e}, Xs(m));\n\n  % Since M=m, only Xm was updated.\n  % Hence the posterior on Xnotm should equal the prior.\n  for i=notm(:)'\n    mXnotm = marginal_nodes(engines{e}, Xs(i));\n    assert(approxeq(mXnotm.mu, zeros(psz,1)))\n    assert(approxeq(mXnotm.Sigma, eye(psz, psz)))\n  end\nend\n\n% Check that all engines give the same posterior\nfor e=2:length(engines)\n  assert(approxeq(mXm{e}.mu, mXm{1}.mu))\n  assert(approxeq(mXm{e}.Sigma, mXm{1}.Sigma))\nend\n\n\n% Compute the correct posterior by building Xm -> Y\n\nN = 2;\ndag = zeros(N,N);\ndag(1, 2)=1;\nns = [psz selfsz];\nbnet = mk_bnet(dag, ns, 'discrete', [], 'observed', 2);\n\nbnet.CPD{1} = gaussian_CPD(bnet, 1, 'mean', zeros(psz, 1), 'cov', eye(psz, psz));\nbnet.CPD{2} = gaussian_CPD(bnet, 2, 'mean', mu, 'cov', Sigma, 'weights', W);\n\njengine  = jtree_inf_engine(bnet);\nevidence = {[], yval};\njengine = enter_evidence(jengine, evidence); % apply Bayes rule to invert the arc\nmX = marginal_nodes(jengine, 1);\n\nfor e=1:length(engines)\n  assert(approxeq(mX.mu, mXm{e}.mu))\n  assert(approxeq(mX.Sigma, mXm{e}.Sigma))\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/static/Belprop/gmux1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5645901825803881}}
{"text": "y               = load('data/purse.dat')';\nmodel           = [ssm_poisson ssm_llm];\nrandn('state', [1105946959; 3715058465]);\n[model logL]    = estimate(y, model, exp(-6), [], 'fmin', 'bfgs', 'disp', 'iter');\nfprintf(1, 'Loglikelihood: %g\\nEta variance: %g\\n', logL, model.param);\n\n[alpha irr]     = fastsmo(y, model);\nfigure('Name', 'Purse data w/ poisson analysis');\nplot(y, 'r:', 'DisplayName', 'Purse data'), hold all, plot(alpha, 'b', 'DisplayName', 'Estimated signal'), hold off; legend('show');\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_purse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5645797706167716}}
{"text": "% LORENZ system\n% System identification: DelayDMDc\n\nclear all, close all, clc\nfigpath = '../FIGURES/LORENZ/';\ndatapath = '../DATA/LORENZ/';\naddpath('../utils');\n\nSystemModel = 'LORENZ';\n\n%% Generate Data\nInputSignalType = 'sphs';%prbs; chirp; noise; sine2; sphs; mixed\nNdelay = 1;\nONLY_TRAINING_LENGTH = 1;\ngetTrainingData\n\nNt = length(tspan)-1;\n\n%% DMDc: B = unknown  and with time delay coordinates\nModelNumber = 2; % or 2\nxrefs = [xref1,xref2];\n\nif Ndelay == 1\n    ModelName = 'DMDc';\nelseif Ndelay>1\n    ModelName = 'DelayDMDc';\nend\n\nHu = getHankelMatrix_MV(u',1);\nfor i = 1:ModelNumber\n    xmean{i} = xrefs(:,i)'; %mean(x);\n    X   = x - repmat(xmean{i},[T 1]);\n    Hx  = getHankelMatrix_MV(X,1);\n    numOutputs = size(Hx,1); numInputs = size(Hu,1); numVar = 3;\n    r1 = size(Hx,1); r2 = size(Hx,1);\n    [sysmodel_DMDc{i},U,Up] = DelayDMDc_MV(Hx,Hu,size(Hx,1),size(Hx,1),dt,size(Hx,1),size(Hu,1),2);\nend\n%% Prediction over training phase\nfor i = 1:ModelNumber\n    [xDMDc{i},~] = lsim(sysmodel_DMDc{i},Hu',tspan(1:end),x(1,:)'-xmean{i}');\n    xDMDc{i} = xDMDc{i} + repmat(xmean{i},[length(tspan) 1]);\nend\n\n%% Show validation\nfor i = 1:ModelNumber\n    clear ph\n    figure,box on,\n    ccolors = get(gca,'colororder');\n    ph(1) = plot(tspan,x(:,1),'-','Color',ccolors(1,:),'LineWidth',1); hold on\n    ph(2) = plot(tspan,x(:,2),'-','Color',ccolors(2,:),'LineWidth',1);\n    ph(3) = plot(tspan(Ndelay:Nt+Ndelay),xDMDc{i}(:,1),'--','Color',ccolors(1,:)-[0 0.2 0.2],'LineWidth',2);\n    ph(4) = plot(tspan(Ndelay:Nt+Ndelay),xDMDc{i}(:,2),'--','Color',ccolors(2,:)-[0.1 0.2 0.09],'LineWidth',2);\n    xlim([0 (length(tspan)-1)*dt]), ylim([-25 50])\n    xlabel('Time')\n    ylabel('Population size')\n    % legend('Prey (True)','Predator (True)', 'Prey (DMDc)','Predator (DMDc)')\n    legend(ph([1,3]),'True',ModelName)\n    set(gca,'LineWidth',1, 'FontSize',14)\n    set(gcf,'Position',[100 100 300 200])\n    set(gcf,'PaperPositionMode','auto')\n    print('-depsc2', '-loose', '-cmyk', [figpath,'EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'_M',i,'.eps']);\nend\n%% Prediction\n% Reference\ntspanV   = [10:dt:20];\nxA      = xv;\ntA      = tv;\n\n% Model\nfor i = 1:ModelNumber\n    if Ndelay == 1\n        x0      = [x(end,1:3)];\n        Hunew   = [u(end),uv(1:end)];\n        [xBm{i},tB] = lsim(sysmodel_DMDc{i},Hunew,tspanV,[x0-[xmean{i}]]');\n    elseif Ndelay > 1\n        x0      = [x(end-Ndelay+1,1:3),x(end,1:3)];\n        Hunew   = [ u(end-Ndelay+1:end),uv(1:end-Ndelay);\n            u(end),uv(1:end-1)];\n        [xBm,tB] = lsim(sysmodel_DMDc,Hunew,tspanV,[x0-[xmean]]');\n        xBm = xBm(:,4:6); xBm = xBm + repmat(xmean,[size(xBm,1) 1]);\n    end\n    \n    xBm{i} = xBm{i} + repmat(xmean{i},[length(tB) 1]);\nend\n%% Show training and prediction\nxB = xBm{1};\nVIZ_SI_Validation\n\nxB = xBm{2};\nVIZ_SI_Validation\n\n%% Save Data\nModel.name = 'DelayDMDc';\nModel.sys = sysmodel_DMDc;\nModel.Ndelay = Ndelay;\nModel.xmean = xmean;\nModel.xrefs = xrefs;\nModel.dt = dt;\nsave(fullfile(datapath,['EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'.mat']),'Model')", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/EX_LORENZ/EX_LORENZ_SI_DelayDMDc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.564579765463713}}
{"text": "classdef CEC2010_F16 < PROBLEM\n% <single> <real> <constrained>\n% CEC'2010 constrained optimization benchmark problem\n\n%------------------------------- Reference --------------------------------\n% R. Mallipeddi and P. N. Suganthan, Problem definitions and evaluation\n% criteria for the CEC 2010 competition on constrained real-parameter\n% optimization, Nanyang Technological University, Singapore, 2010.\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        O;  % Optimal decision vector\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2010.mat'),'Data');\n            obj.O = Data{16};\n            obj.M = 1;\n            if isempty(obj.D); obj.D = 10; end\n            obj.D = min(obj.D,length(obj.O));\n            obj.lower    = zeros(1,obj.D) - 10;\n            obj.upper    = zeros(1,obj.D) + 10;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopObj = sum((Z.^2/4000),2) - prod((cos(Z./repmat(sqrt(1:size(Z,2)),size(Z,1),1))),2) + 1;\n        end\n        %% Calculate constraint violations\n        function PopCon = CalCon(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopCon(:,1) = sum((Z.^2-100*cos(pi*Z)+10),2);\n            PopCon(:,2) = prod(Z,2);\n            PopCon(:,3) = abs(sum((Z.*sin(sqrt(abs(Z)))),2)) - 1e-4;\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/Single-objective optimization/CEC 2010/CEC2010_F16.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5645797653436404}}
{"text": "function [zs] = ssampler(z,op1,sc)\n% PURPOSE: Systematic sampling of a high-frequency time series\n% ------------------------------------------------------------\n% SYNTAX: zs = ssampler(z,op1,sc)\n% ------------------------------------------------------------\n% OUTPUT: zs: nx1 sampled time series\n% ------------------------------------------------------------\n% INPUT:  z: nx1 ---> vector of high frequency data\n%         op1: type of temporal aggregation \n%         op1=1 ---> sum (flow)\n%         op1=2 ---> average (index)\n%         op1=3 ---> last element (stock) ---> interpolation\n%         op1=4 ---> first element (stock) ---> interpolation\n%         sc: number of high frequency data points \n%            for each low frequency data points\n% ------------------------------------------------------------\n% LIBRARY: copylow, temporal_agg\n% ------------------------------------------------------------\n\n% written by:\n%  Enrique M. Quilis\n%  Macroeconomic Research Department\n%  Ministry of Economy and Competitiveness\n%  <enrique.quilis@mineco.es>\n\n% Version 1.0 [May 2009]\n\naux = temporal_agg(z,op1,sc);\nzs = copylow(aux,3,sc);\n", "meta": {"author": "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/ssampler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5644946543572713}}
{"text": "function f=comp_inonsepdgtreal_quinqux(coef,g,a,M,do_timeinv)\n%COMP_INONSEPDGTREAL_QUINQUX  Compute Inverse discrete Gabor transform\n%   Usage:  f=inonsepdgt(c,g,a,M);\n%\n%   Input parameters:\n%         c     : Array of coefficients.\n%         g     : Window function.\n%         a     : Length of time shift.\n%         M     : Number of channels\n%         do_timeinv : Do a time invariant phase ?\n%   Output parameters:\n%         f     : Signal.\n%\n%\n%   This is a computational subroutine, do not call it directly.\n\n%   AUTHOR : Nicki Holighaus and Peter L. S\u00f8ndergaard\n%   TESTING: TEST_NONSEPDGT\n%   REFERENCE: OK\n\n% Check input paramameters.\n\n\nM2=size(coef,1);\nN=size(coef,2);\nW=size(coef,3);\nL=N*a;\n\ncoef2=zeros(M,N,W,assert_classname(coef,g));\n\ncoef2(1:M2,:,:)=coef;\nif rem(M,2)==0\n    coef2(M2+1:M,1:2:N-1,:)=conj(coef(M2-1:-1:2,1:2:N-1,:));\n    coef2(M2:M,2:2:N  ,:)  =conj(coef(M2-1:-1:1,2:2:N,:));\nelse\n    coef2(M2+1:M,1:2:N-1,:)=conj(coef(M2:-1:2,1:2:N-1,:));\n    coef2(M2+1:M,2:2:N  ,:)=conj(coef(M2-1:-1:1,2:2:N,:));\nend;\n\ncoef=coef2;\n\nlt=[1 2];\nmwin=comp_nonsepwin2multi(g,a,M,lt,L);\n\n% phase factor correction (backwards), for more information see \n% analysis routine\n\nE = exp(2*pi*i*a*kron(0:N/2-1,ones(1,2)).*...\n        rem(kron(ones(1,N/2), 0:2-1),2)/M);\n\ncoef = bsxfun(@times,coef,E);\n\n% simple algorithm: split into sublattices and add the result from eacg\n% sublattice.\nf=zeros(L,W,assert_classname(coef,g));\nfor ii=0:2-1\n    % Extract sublattice\n    sub=coef(:,ii+1:2:end,:);\n    f=f+comp_idgt(sub,mwin(:,ii+1),2*a,[0 1],0,0);  \nend;\n    \n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_inonsepdgtreal_quinqux.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5644946486758255}}
{"text": "function out = MF_armax(y, orders, pTrain, numSteps)\n% MF_armax  Statistics on a fitted ARMA model.\n%\n% Uses the functions iddata, armax, aic, and predict from Matlab's System\n% Identification Toolbox\n%\n%---INPUTS:\n%\n% y, the input time series\n%\n% orders, a two-vector for p and q, the AR and MA components of the model,\n%           respectively\n%\n% pTrain, the proportion of data to train the model on (the remainder is used\n%           for testing)\n%\n% numSteps, number of steps to predict into the future for testing the model.\n%\n%\n%---OUTPUTS: include the fitted AR and MA coefficients, the goodness of fit in\n% the training data, and statistics on the residuals from using the fitted model\n% to predict the testing data.\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,\n% <http://www.benfulcher.com>\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 <http://www.gnu.org/licenses/>.\n% ------------------------------------------------------------------------------\n\n% ------------------------------------------------------------------------------\n%% Check that a System Identification Toolbox license is available:\n% ------------------------------------------------------------------------------\nBF_CheckToolbox('identification_toolbox')\n\n% ------------------------------------------------------------------------------\n%% Prepare Inputs\n% ------------------------------------------------------------------------------\n% (1) y, the time series as a column vector\nif size(y,2) > size(y,1)\n   y = y'; % ensure a column vector\nend\nN = length(y); % number of samples\n% Convert y to time series object\ny = iddata(y,[],1);\n\n% orders; vector specifying the AR and MA components\nif nargin < 2 || isempty(orders)\n    orders = [3, 3]; % AR3, MA3\nend\nif nargin < 3 || isempty(pTrain)\n    pTrain = 0.8; % train on 80% of the data\nend\n% if nargin < 4 || isempty(trainmode)\n%     trainmode = 'first'; % trains on first pTrain proportion of the data.\n% end\nif nargin < 4 || isempty(numSteps)\n    numSteps = 1; % one-step-ahead predictions\nend\n\n% ------------------------------------------------------------------------------\n%% Fit the model\n% ------------------------------------------------------------------------------\n\n% Uses the System Identification Toolbox function armax\nm = armax(y, orders);\n\n% ------------------------------------------------------------------------------\n%% Statistics on model\n% ------------------------------------------------------------------------------\n\nc_ar = m.a; % AR coefficients\nc_ma = m.c; % MA coefficients\nda = m.da; % must be uncertainties in AR coeffs\ndc = m.dc; % must uncertainties in MA coeffs\n\n% Make these outputs\nif length(c_ar) > 1\n    for i = 2:length(c_ar)\n        out.(sprintf('AR_%u',i-1)) = c_ar(i);\n    end\nend\nif length(c_ma) > 1\n    for i = 2:length(c_ma)\n        out.(sprintf('MA_%u',i-1)) = c_ma(i);\n    end\nend\n\nif isempty(da)\n    out.maxda = NaN;\nelse\n    out.maxda = max(da);\nend\nif isempty(dc)\n    out.maxdc = NaN;\nelse\n    out.maxdc = max(dc);\nend\n\n% ------------------------------------------------------------------------------\n% Fit statistics\n% ------------------------------------------------------------------------------\n\n% These three measures are basically equivalent -- default hctsa library\n% only records fpe.\nout.noisevar = m.NoiseVariance; % covariance matrix of noise source\n% covmat = m.CovarianceMatrix; % covariance matrix for parameter vector\n% parameters = m.ParameterVector; % parameter vector for model: initial values, I'd say...\nout.lossfn = m.EstimationInfo.LossFcn;\nout.fpe = m.EstimationInfo.FPE; % Final prediction error of model\n\n% out.lastimprovement = m.EstimationInfo.LastImprovement; % Last improvement made in iteration\nout.aic = aic(m); % ~ log(fpe)\n\n% ------------------------------------------------------------------------------\n%% Prediction\n% ------------------------------------------------------------------------------\n\n% Select first portion of data for estimation\n% This could be any portion, actually... Maybe could look at robustness of\n% model to different training sets...\nytrain = y(1:floor(pTrain*N));\n% ytest = y;\nytest = y(floor(pTrain*N):end); % overlap\n\n% Train the model on just this portion\nmp = armax(ytrain, orders);\n\n% Compute step-ahead predictions\n% Maybe look at trends across different prediction horizons...\nyp = predict(mp, ytest, numSteps, 'init', 'e'); % across whole dataset\n\nmresiduals = ytest.y - yp.y;\n\n% ------------------------------------------------------------------------------\n% Get statistics on residuals\n% ------------------------------------------------------------------------------\nresidout = MF_ResidualAnalysis(mresiduals);\n\n% Convert these to local outputs in quick loop\n% Note that default hctsa library does not include rmse field, which is highly\n% correlated with the stde field\nfields = fieldnames(residout);\nfor k = 1:length(fields);\n    out.(fields{k}) = residout.(fields{k});\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/MF_armax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5644946486758254}}
{"text": "function class_out = force_membership_wc(f_in, class_in, f_out, par)\n% class = function force_membership_wc(f_in, class_in, f_out, par)\n% Given classified points, try to classify new points via template matching\n%\n% f_in:          features of classified points  (# input spikes x n_features)\n% class_in:      classification of those points\n% f_out:         features of points to be classified (nspk x n_features)\n% par        environment variables, of which the following are\n%                required: \n%                    o par.template_sdnum - max radius of cluster,\n%                                                   in std devs.\n%                    o par.template_k     - # of nearest neighbors\n%                    o par.template_k_min - min # of nn for vote\n%                    o par.template_type  - nn, center, ml, mahal\n\nnspk = size(f_out,1);\nclass_out = zeros(1,size(f_out,1));\nswitch par.template_type\n    case 'nn'\n        sdnum = par.template_sdnum;\n        k     = par.template_k;\n        k_min = par.template_k_min;\n        sd    = sqrt(sum(var(f_in,1)))*ones(1,size(f_in,1));\n        for i=1:nspk,\n            nn = nearest_neighbor(f_out(i,:),f_in,sdnum*sd,Inf*ones(size(f_in)),Inf,k);\n            if( nn )\n                winner = mode(class_in(nn));\n                if nnz(class_in(nn)==winner)<k_min\n                    class_out(i) = 0;\n                else\n                    class_out(i) = winner;\n                end\n            else\n                class_out(i) = 0;\n            end\n        end\n      \n    case 'center'\n        [centers, sd, pd] = build_templates(class_in,f_in); % we are going to ignore pd\n        sdnum = par.template_sdnum;\n        for i=1:nspk,\n            class_out(i) = nearest_neighbor(f_out(i,:),centers,sdnum*sd);        \n        end\n        \n    case 'ml'\n        [mu inv_sigma] = fit_gaussian(f_in,class_in);\n        for i=1:nspk,\n            class_out(i) = ML_gaussian(f_out(i,:),mu,inv_sigma);\n        end\n    case 'mahal'\n        classes = unique(class_in);\n        mdistance = zeros(length(classes), nspk);\n        maxdist   = zeros(1, length(classes));\n        for ci = 1:length(classes)\n           i = classes(ci);\n           mdistance(i,:) = mahal(f_out, f_in(class_in ==i, :));\n           maxdist(i) = sqrt(mean(mahal(f_in(class_in ==i, :), f_in(class_in ==i, :))));\n        end\n        sdnum = par.template_sdnum;\n        for i = 1:nspk\n             [d winner] = min(mdistance(:,i));\n             if sqrt(d) < sdnum*maxdist(winner)\n                 class_out(i) = classes(winner);\n             end\n        end\n        \n        \n    otherwise\n        sprintf('force_membership(): <%s> is not a known template type.\\n',par.template_type);\n        \nend", "meta": {"author": "csn-le", "repo": "wave_clus", "sha": "3cbc9e7a747353dde2b97984eef48bbbd7991928", "save_path": "github-repos/MATLAB/csn-le-wave_clus", "path": "github-repos/MATLAB/csn-le-wave_clus/wave_clus-3cbc9e7a747353dde2b97984eef48bbbd7991928/Batch_files/Force_files/force_membership_wc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5644946483916369}}
{"text": "function r = erf(a)\n%ERF          Hessian (elementwise) error function\n%\n\n% written  31/05/13     S.M. Rump\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  a.x = full(a.x);\n  K = prod(size(a.x));\n  % factorLB <= 2/sqrt(pi) <= factorUB\n  INTLAB_STDFCTS_ERF = getappdata(0,'INTLAB_STDFCTS_ERF');\n  factorLB = INTLAB_STDFCTS_ERF.TWO_SQRTPIINF;  % round to nearest\n  factorUB = INTLAB_STDFCTS_ERF.TWO_SQRTPISUP;  % ~ 1.12\n\n  if K==1                   % scalar hessian\n    \n    ax = exp(-a.x(:).^2);\n    if isa(a.x,'intval')\n        ax = intval(factorLB,factorUB,'infsup') * ax;\n    else\n      ax = factorLB * ax;\n    end\n    r.x = erf(a.x);\n    r.dx = ax * a.dx;\n    r.hx = ax * ( a.hx - reshape( (a.x.*a.dx) * a.dx.' , size(a.hx) ) );\n    \n  else                      % matrix hessian\n    \n    N = getappdata(0,'INTLAB_HESSIAN_NUMVAR');\n    N2 = N^2;\n    \n    r.x = erf(a.x);\n    a.x = a.x(:);\n    if issparse(a.hx)               % input sparse\n      \n      ax = exp(-a.x.^2);\n      if isa(a.x,'intval')\n        ax = intval(factorLB,factorUB,'infsup') * ax;\n      else\n        ax = factorLB * ax;\n      end\n      sizeax = length(ax);\n      [ia,ja,sa] = find(a.dx);\n      % check for emptyness: cures Matlab bug\n      % a=sparse([],[],[],2,1), [i,j,s]=find(a), s(i).*s(:)  yields error\n      if isempty(ia)\n        r.dx = sparse([],[],[],N,sizeax);\n        r.hx = a.hx;\n      else\n        if isa(a.x,'intval')          % sparse intval\n          rdx = times(ax(ja),sa(:),0);\n          adx1 = times(a.x(ja),sa(:),0);\n          r.dx = intval( sparse(ia,ja,rdx.inf,N,sizeax) , sparse(ia,ja,rdx.sup,N,sizeax) , 'infsup' );\n          rdx = intval(sparse(ia,ja,adx1.inf,N,sizeax),sparse(ia,ja,adx1.sup,N,sizeax),'infsup');\n        else                          % sparse point  \n          r.dx = sparse(ia,ja,ax(ja).*sa(:),N,sizeax); \n          rdx = sparse(ia,ja,a.x(ja).*sa(:),N,sizeax);\n        end\n        r.hx = a.hx - adx2rhx(N,sizeax,rdx,a.dx);\n      end\n      [ia,ja,sa] = find(r.hx);        % sparse point or intval\n      % check for emptyness: cures Matlab bug\n      % a=sparse([],[],[],2,1), [i,j,s]=find(a), s(i).*s(:)  yields error\n      if ~isempty(ia)\n        if isa(ax,'intval')\n          rhx = times(ax(ja),sa(:),0);\n          r.hx = sparse(ia,ja,intval(rhx.inf,rhx.sup,'infsup'),N2,sizeax);\n        else\n          r.hx = sparse(ia,ja,ax(ja).*sa(:),N2,sizeax);\n        end\n      end\n      \n    else                            % input full\n      \n      if isa(a.x,'intval')\n        ax = intval(factorLB,factorUB,'infsup') * exp((-((a.x).').^2));\n      else\n        ax = factorLB * exp((-((a.x).').^2));\n      end\n      ax = ax(ones(N*N,1),:);\n      r.dx = a.dx .* ax(1:N,:);\n      adx = repmat(a.x(:).',N,1) .* a.dx;\n      r.hx = ( a.hx - adx(repmat(1:N,N,1),:) .* a.dx(repmat(1:N,1,N),:) ) .* ax;\n      \n    end\n    \n  end\n  \n  r = class(r,'hessian');\n  \n  if rndold\n    setround(rndold)\n  end\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/hessian/@hessian/erf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5644647706703954}}
{"text": "function [FF,I] = orient_outward(V,F,C)\n  % ORIENT_OUTWARD Use a simple heuristic to maintain or flip each\n  % manifold/orientable patch of a mesh. Assumes that independent patches have\n  % already been oriented consistently up to sign.\n  % \n  % [FF,I] = orient_outward(V,F,C)\n  %\n  % Inputs:\n  %   V  #V by 3 list of vertex positions\n  %   F  #F by 3 list of triangle indices\n  %   C  #F list of component ids\n  % Outputs:\n  %   FF  #F by 3 list of new, potentially flipped triangle indices\n  %   I  #C list of bools whether patch was flipped\n  %\n  % See also: bfs_orient, manifold_patches\n  %\n  [FF,C] = bfs_orient(F);\n  I = false(max(C),1);\n  for c = 1:max(C)\n    N = normalizerow(normals(V,FF(C==c,:)));\n    A = doublearea(V,FF(C==c,:));\n    BC = barycenter(V,FF(C==c,:));\n    BCmean = A'*BC/sum(A);\n    BC = bsxfun(@minus,BC,BCmean);\n    ndot = sum(bsxfun(@times,A,sum(N.*BC,2)));\n    if ndot<0\n      FF(C==c,:) = fliplr(FF(C==c,:));\n      I(c) = true;\n    else\n      I(c) = false;\n    end\n  end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/orient_outward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5644647700341753}}
{"text": "function y = sinc(x)\n\ny = pi * x;\n\nsel = abs(y) > 1e-15;\n\ny(sel) = sin(y(sel)) ./ y(sel);\ny(~sel) = 1;", "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/Surfacelet/sinc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5644647598480733}}
{"text": "function pb = plot_scatter_patch(X,r,col,a)\n%PLOT_SCATTER_PATCH Summary of this function goes here\n%   Detailed explanation goes here\n\n   \nt= 0:pi/100:2*pi;\n\npb = zeros(size(X,1),1);\n\nfor i=1:size(X,1)\n    pb(i)=patch( (r(i)*sin(t)+ X(i,1)) , (r(i)*cos(t)+X(i,2)) ,col,'MarkerEdgeColor','none');\n    alpha(pb(i),a);\nend\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/functions/plot_functions/gmm_plot/plotGaussians/plot_scatter_patch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5643183451524}}
{"text": "% FindInl    find inliers in joint image matrix\n%\t\t\t by pairwise epipolar geometry\n%\n% function IdMatIn = findinl(Ws,IdMat,tol)\n% Ws ... 3MxN joint image matrix\n% IdMat ... MxN ... 0 -> no point detected\n%                   1 -> point detected\n% tol ... [pixels] tolerance for the epipolar geometry\n%         the point are accpted as outliers only if they\n%         are closer to the epipolar line than tol\n\n% $Author: svoboda $\n% $Revision: 2.0 $\n% $Id: findinl.m,v 2.0 2003/06/19 12:07:09 svoboda Exp $\n% $State: Exp $\n\nfunction IdMatIn = findinl(Ws,IdMat,tol)\n\nNoCams = size(IdMat,1);\n\n% fill the array of structures not_used denoted as 0\n% allocate the array of structures for used\nfor i=1:NoCams,\n  not_used(i).pts = sum(IdMat(i,:));\n  used(i).pts\t  = -1;\nend\n\n% allocate IdMat for outliers\nIdMatIn = zeros(size(IdMat));\n\nwhile (sum([not_used.pts])>1-NoCams),\n  [buff, id.cam_max]  = max([not_used.pts]);\n  used\t   = add(used, id.cam_max, not_used(id.cam_max).pts);\n  not_used = remove(not_used, id.cam_max);\n  Mask\t   = repmat(IdMat(id.cam_max,:),NoCams,1);\n  Corresp  = Mask & IdMat;\n  Corresp(id.cam_max,:) = 0;\n  [buff, id.cam_to_pair] = max(sum(Corresp')); % find the camera with most correspondences\n  idx.corr_to_pair = find(sum(IdMat([id.cam_max,id.cam_to_pair],:))==2);\n  % used\t   = add(used, id.cam_to_pair, not_used(id.cam_to_pair).pts);\n  % not_used = remove(not_used, id.cam_to_pair);\n  if size(idx.corr_to_pair,2)<8,\n\terror('Not enough points to compute epipolar geometry in RANSAC validation')\n  end\n  Wspair   = [];\n  Wspair   = Ws(id.cam_max*3-2:id.cam_max*3, idx.corr_to_pair);\n  Wspair   = [Wspair; Ws(id.cam_to_pair*3-2:id.cam_to_pair*3, idx.corr_to_pair)];\n  % id\n  [F, inls] = rEG(Wspair,tol,tol,0.99);\n  IdMatIn(id.cam_max, idx.corr_to_pair(inls)) = 1;\n  IdMat(id.cam_max, :)\t\t\t\t\t\t  = 0;\n  IdMat(id.cam_max, idx.corr_to_pair(inls))\t  = 1;\nend\n\nfunction list = add(list, id, value)\nlist(id).pts = value;\nreturn\n\nfunction list = remove(list, id)\nlist(id).pts = -1;\nreturn", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamValidation/CoreFunctions/findinl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5643183426637195}}
{"text": "function [x,resvec,state] = pcg_ccot(A,b,opts,M1,M2,ip,x0,state)\n\n% This is a modified version of Matlab's pcg function, that performs \n% preconditioned conjugate gradient.\n\n\n% tol = opts.tol;\nmaxit = opts.maxit;\n\nif ~isfield(opts, 'init_forget_factor')\n    opts.init_forget_factor = 1;\nend\n\nif opts.debug\n    n2b = sqrt(ip(b,b)); % Norm of rhs vector, b\nend\n\nexistM1 = ((nargin >= 4) && ~isempty(M1));\nexistM2 = ((nargin >= 5) && ~isempty(M2));\n\nx = x0;\n\n% Load the CG state\np = [];\nrho = 1;\nr_prev = [];\nload_state = nargin > 7 && ~isempty(state) && opts.init_forget_factor > 0;\nif load_state\n    if isfield(state, 'p')\n        p = state.p;\n    end\n    if isfield(state, 'rho') && ~isempty(state.rho)\n        rho = state.rho / opts.init_forget_factor;\n    end\n    if isfield(state, 'r_prev') && ~opts.CG_use_FR\n        r_prev = state.r_prev;\n    end\nend\n\n% Set up for the method\nstate.flag = 1;\n\n% r = cellfun(@minus, b, iterapp('mtimes',afun,atype,afcnstr,x,varargin{:}), 'uniformoutput', false);\nr = cellfun(@minus, b, A(x), 'uniformoutput', false);\n\nif opts.debug\n    normr = sqrt(ip(r,r));                   % Norm of residual\n    normr_act = normr;\nend\n\n\nif opts.debug\n    resvec = zeros(maxit+1,1);         % Preallocate vector for norm of residuals\n    resvec(1,:) = normr;               % resvec(1) = norm(b-A*x0)\nelse\n    resvec = [];\n    relres = [];\nend\n\n% loop over maxit iterations (unless convergence or failure)\n\nfor ii = 1 : maxit\n    if existM1\n        y = M1(r);\n    else % no preconditioner\n        y = r;\n    end\n    \n    if existM2\n        z = M2(y);\n    else % no preconditioner\n        z = y;\n    end\n    \n    rho1 = rho;\n    rho = ip(r, z);\n    if ((rho == 0) || isinf(rho))\n        state.flag = 4;\n        break\n    end\n    \n    if (ii == 1 && isempty(p))\n        p = z;\n    else\n        if opts.CG_use_FR\n            % Use Fletcher-Reeves\n            beta = rho / rho1;\n        else\n            % Use Polak-Ribiere\n            rho2 = ip(r_prev, z);\n            beta = (rho - rho2) / rho1;\n        end\n        if ((beta == 0) || isinf(beta))\n            state.flag = 4;\n            break\n        end\n        beta = max(0, beta);\n        p = cellfun(@(z,p) z + beta * p, z, p, 'uniformoutput', false);\n    end\n    \n    q = A(p);\n    pq = ip(p, q);\n    if ((pq <= 0) || isinf(pq))\n        state.flag = 4;\n        break\n    else\n        if opts.CG_standard_alpha\n            alpha = rho / pq;\n        else\n            alpha = ip(p, r) / pq;\n        end\n    end\n    if isinf(alpha)\n        state.flag = 4;\n        break\n    end\n    \n    % Save old r if not using FR formula for beta\n    if ~opts.CG_use_FR\n        r_prev = r;\n    end\n    \n    % form new iterate\n    x = cellfun(@(x,p) x + alpha * p, x, p, 'uniformoutput', false);\n    \n    if ii < maxit || opts.debug\n        r = cellfun(@(r,q) r - alpha * q, r, q, 'uniformoutput', false);\n    end\n    \n    if opts.debug\n        normr = sqrt(ip(r,r));\n        normr_act = normr;\n        resvec(ii+1,1) = normr;\n    end\nend\n\niter = ii;\nif opts.debug\n    relres = normr_act / n2b;\nend\n\n% truncate the zeros from resvec\nif opts.debug\n    if ((state.flag <= 1) || (state.flag == 3))\n        resvec = resvec(1:ii+1,:);\n    else\n        resvec = resvec(1:ii,:);\n    end\nend\n\n% Save the state\nif nargout > 2\n    state.p = p;\n    state.rho = rho;\n    if ~opts.CG_use_FR\n        state.r_prev = r_prev;\n    end\nend", "meta": {"author": "martin-danelljan", "repo": "ECO", "sha": "27e8ae565cd63ec14bafcaad8b5b993bec8f3e69", "save_path": "github-repos/MATLAB/martin-danelljan-ECO", "path": "github-repos/MATLAB/martin-danelljan-ECO/ECO-27e8ae565cd63ec14bafcaad8b5b993bec8f3e69/implementation/training/pcg_ccot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5643183401750387}}
{"text": "function s = ndf(f)\n%NDF   Number of degrees of freedom (parameters) needed to represent a \n%   CHEBFUN3 object.\n%\n% See also CHEBFUN3T/NDF.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% NDF(f) = sum of modal ranks multiplied with length of the corresponding \n% factor quasimatrix plus number of entries in the core tensor.\n\nif ( isempty(f) )\n    s = 0;\nelse\n    [r1, r2, r3] = rank(f);\n    [m, n, p] = length(f);\n    s = dot([r1, r2, r3], [m, n, p]) + numel(f.core);\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/@chebfun3/ndf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5643183354423602}}
{"text": "X=randn(64,200000);\nA=sprand(200,200000,0.05);\n\ntic\nXAt=mexCalcXAt(X,A);\nt=toc;\nfprintf('mex-file time: %fs\\n',t);\n\ntic\nXAt2=X*A';\nt=toc;\nfprintf('mex-file time: %fs\\n',t);\n\nsum((XAt(:)-XAt2(:)).^2)\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/AMICO/SPAMS/test_release/test_CalcXAt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5642917618997543}}
{"text": "% needs ops.RegFile, ops.xrange, ops.yrange, ops.NavgFramesSVD\n% Ly, Lx are the size of each frame. nimgbatch: the number of frames loaded per batch\n% nt0 is the number of timepoints to bin over. If a sixth argument is\n% present, it does not subtract the mean of each batch. \nfunction mov = loadAndBin(ops, Ly, Lx, nimgbatch, nt0, clustModel)\n\nix = 0;\nfid = fopen(ops.RegFile, 'r');\nmov = zeros(numel(ops.yrange), numel(ops.xrange), ops.NavgFramesSVD, 'single');\nij = 0;\nwhile 1\n    % load frames\n    data = fread(fid,  Ly*Lx*nimgbatch, '*int16');\n    if isempty(data)\n        break;\n    end\n    data = single(data);\n    data = reshape(data, Ly, Lx, []);\n    \n    % ignore bad frames\n    badi = ops.badframes(ix + [1:size(data,3)]);\n%     data(:,:, badi) = [];\n    \n    % subtract off the mean of this batch\n    if nargin<=5\n        data = bsxfun(@minus, data, mean(data,3));\n    end\n    %     data = bsxfun(@minus, data, ops.mimg1);\n    \n    nSlices = nt0*floor(size(data,3)/nt0);\n    if nSlices~=size(data,3)\n        data = data(:,:, 1:nSlices);\n    end\n    \n    % bin data\n    data = reshape(data, Ly, Lx, nt0, []);\n    davg = squeeze(mean(data,3));\n    \n    mov(:,:,ix + (1:size(davg,3))) = davg(ops.yrange, ops.xrange, :);\n    \n    ix = ix + size(davg,3);\n    ij = ij + 1;\nend\nfclose(fid);\n\nmov = mov(:, :, 1:ix);\n", "meta": {"author": "cortex-lab", "repo": "Suite2P", "sha": "c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5", "save_path": "github-repos/MATLAB/cortex-lab-Suite2P", "path": "github-repos/MATLAB/cortex-lab-Suite2P/Suite2P-c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5/svd/loadAndBin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5642917618997543}}
{"text": "% DEMOIL2 Oil data with fully independent training conditional, and MLP back constraints.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'oil';\nexperimentNo = 2;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('fitc');\noptions.optimiser = 'scg';\noptions.back = 'mlp';\noptions.backOptions = mlpOptions;\nlatentDim = 2;\nd = size(Y, 2);\n\nmodel = fgplvmCreate(latentDim, d, Y, options);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\ncapName = dataSetName;;\ncapName(1) = upper(capName(1));\nsave(['dem' capName num2str(experimentNo) '.mat'], 'model');\n\nif exist('printDiagram') & printDiagram\n  fgplvmPrintPlot(model, lbls, capName, experimentNo);\nend\n\n% Load the results and display dynamically.\nfgplvmResultsDynamic(dataSetName, experimentNo, 'vector')\n\n% compute the nearest neighbours errors in latent space.\nerrors = fgplvmNearestNeighbour(model, lbls);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demOil2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5642917560713078}}
{"text": "function [R, G, B] = lab2rgb(L, a, b)\n%LAB2RGB Convert an image from CIELAB to RGB\n%\n% function [R, G, B] = Lab2RGB(L, a, b)\n% function [R, G, B] = Lab2RGB(I)\n% function I = Lab2RGB(...)\n%\n% Lab2RGB takes L, a, and b double matrices, or an M x N x 3 double\n% image, and returns an image in the RGB color space.  Values for L are in\n% the range [0,100] while a* and b* are roughly in the range [-110,110].\n% If 3 outputs are specified, the values will be returned as doubles in the\n% range [0,1], otherwise the values will be uint8s in the range [0,255].\n%\n% This transform is based on ITU-R Recommendation BT.709 using the D65\n% white point reference. The error in transforming RGB -> Lab -> RGB is\n% approximately 10^-5.  \n%\n% See also RGB2LAB. \n\n% By Mark Ruzon from C code by Yossi Rubner, 23 September 1997.\n% Updated for MATLAB 5 28 January 1998.\n% Fixed a bug in conversion back to uint8 9 September 1999.\n% Updated for MATLAB 7 30 March 2009.\n\nif nargin == 1\n  b = L(:,:,3);\n  a = L(:,:,2);\n  L = L(:,:,1);\nend\n\n% Thresholds\nT1 = 0.008856;\nT2 = 0.206893;\n\n[M, N] = size(L);\ns = M * N;\nL = reshape(L, 1, s);\na = reshape(a, 1, s);\nb = reshape(b, 1, s);\n\n% Compute Y\nfY = ((L + 16) / 116) .^ 3;\nYT = uint8(fY > T1);\nfY = uint8(~YT) .* (L / 903.3) + YT .* fY;\nY = fY;\n\n% Alter fY slightly for further calculations\nfY = uint8(double(YT) .* (double(fY) .^ (1/3)) + double(~YT) .* (7.787 .* double(fY) + 16/116));\n\n% Compute X\nfX = a / 500 + fY;\nXT = fX > T2;\nX = uint8((double(XT) .* (double(fX) .^ 3) + double(~XT) .* ((double(fX) - 16/116) / 7.787)));\n\n% Compute Z\nfZ = fY - b / 200;\nZT = fZ > T2;\nZ = uint8((double(ZT) .* (double(fZ) .^ 3) + double(~ZT) .* ((double(fZ) - 16/116) / 7.787)));\n\n% Normalize for D65 white point\nX = X * 0.950456;\nZ = Z * 1.088754;\n\n% XYZ to RGB\nMAT = [ 3.240479 -1.537150 -0.498535;\n       -0.969256  1.875992  0.041556;\n        0.055648 -0.204043  1.057311];\n\nRGB = max(min(uint8(MAT * double([X; Y; Z])), 1), 0);\n\nR = reshape(RGB(1,:), M, N);\nG = reshape(RGB(2,:), M, N);\nB = reshape(RGB(3,:), M, N); \n\nif nargout < 2\n  R = uint8(round(cat(3,R,G,B) * 255));\nend\n", "meta": {"author": "kittenish", "repo": "Image-Shadow-Detection-and-Removal", "sha": "03de533b7ba1104a2551b0b670e7210d9c114b1e", "save_path": "github-repos/MATLAB/kittenish-Image-Shadow-Detection-and-Removal", "path": "github-repos/MATLAB/kittenish-Image-Shadow-Detection-and-Removal/Image-Shadow-Detection-and-Removal-03de533b7ba1104a2551b0b670e7210d9c114b1e/src/etract_feature/lab2rgb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.564291739566416}}
{"text": "function out = Solve_Optimal(M,b1,b2,lambda)\n\n[m, n]=size(b1);\n\nsmallNum = 0.000001;\n\na = abs(imfilter(b2,ones(7)/(sum(sum(ones(7)))),'replicate'));\nA = 1./(a + smallNum);\n\nA = A(:);\nA = sparse(1:1:m*n,1:1:m*n,A(1:1:m*n)',m*n,m*n);\n\nII=sparse(1:1:m*n,1:1:m*n,ones(1,m*n),m*n,m*n);\n\ndenominator=2*II+lambda*(A+A');\n\nnumerator=2*M(:)+lambda*(A+A')*b1(:);\n\nout=denominator\\numerator;\nout=reshape(out,m,n);\n\n\nend", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/VSMWLS/Solve_Optimal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5642702010773839}}
{"text": "function calpak_test686 ( )\n\n%*****************************************************************************80\n%\n%% CALPAK_TEST686 tests YJF_TO_YMDF_JULIAN and YMDF_TO_YJF_JULIAN.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    19 April 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CALPAK_TEST686\\n' );\n  fprintf ( 1, '  For the Julian calendar,\\n' );\n  fprintf ( 1, '  YJF_TO_YMDF_JULIAN: YJF => YMDF\\n' );\n  fprintf ( 1, '  YMDF_TO_YJF_JULIAN: YMDF => YJF\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  YMDF(in)         YJF        YMDF(out)\\n' );\n  fprintf ( 1, '\\n' );\n\n  jed_epoch = epoch_to_jed_julian ( );\n\n  i = 0;\n\n  while ( 1 )\n \n    i = i + 1;\n    jed1 = jed_test ( i );\n\n    if ( jed1 < 0.0 )\n      break\n    end\n\n    if ( jed_epoch <= jed1 )\n\n      [ y1, m1, d1, f1 ] = jed_to_ymdf_julian ( jed1 );\n\n      s1 = ymdf_to_s_julian ( y1, m1, d1, f1 );\n\n      [ y2, j2, f2 ] = ymdf_to_yjf_julian ( y1, m1, d1, f1 );\n\n      s2 = yjf_to_s_julian ( y2, j2, f2 );\n\n      [ y3, m3, d3, f3 ] = yjf_to_ymdf_julian ( y2, j2, f2 );\n\n      s3 = ymdf_to_s_julian ( y3, m3, d3, f3 );\n\n      fprintf ( 1, '  %10s  %10s  %10s\\n', s1, s2, s3 );\n\n    end\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/calpak/calpak_test686.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5642628104550451}}
{"text": "function [sz]=tt_qsize(tt,s)\n\n% For a QTT decomposition _tt_,\n% k-th core of which is indexed by\n% i^{k}_{1} ,..., i^{k}_{s},\n% k=1,...,d,\n% returns the array of mode lengths\n% sz = [n^{1}_{1} ,..., n^{1}_{s};\n%                 ,...,\n%       n^{d}_{1} ,..., n^{d}_{s}]\n%\n% April 26, 2011\n% Vladimir Kazeev\n% vladimir.kazeev@gmail.com\n% INM RAS\n% Moscow, Russia\n%\n\nd=size(tt,1);\nsz=zeros(d,s);\n\nfor k=1:d\n\tszk=size(tt{k});\n\tszk=[szk,ones(1,s)];\n\tsz(k,1:s)=szk(1:s);\nend\n\nreturn\nend", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/core/tt_qsize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5642628027815294}}
{"text": "function [g_phi1,g_Phi,g_phi2] = grad_phi(odf,ori)\n% discrete derivatives with respect to Euler angles\n\n[phi1,Phi,phi2] = Euler(ori,'nfft');\n\ndelta = 0.05 * degree;\nori = orientation.byEuler(phi1 + [-1 1] * delta,Phi,phi2,ori.CS,'nfft');\n\ng_phi1 = diff(odf.eval(ori))/delta/2;\n\nori = orientation.byEuler(phi1,Phi + [-1 1] * delta,phi2,ori.CS,'nfft');\n\ng_Phi = diff(odf.eval(ori))/delta/2;\n\nori = orientation.byEuler(phi1,Phi,phi2 + [-1 1] * delta,ori.CS,'nfft');\n\ng_phi2 = diff(odf.eval(ori))/delta/2;\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/tests/grad_phi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5642537266332518}}
{"text": "% fig2i HungarianCV matrix plot\n\ni_fish = 6;\n[cIX1,gIX1] = LoadCluster_Direct(i_fish,4,5);\n[cIX2,gIX2] = LoadCluster_Direct(i_fish,4,6);\n\n% [score,im1] = HungarianCV(cIX1,cIX2,gIX1,gIX2,isPlotFig);\n[score,im1] = HungarianCV(cIX2,cIX1,gIX2,gIX1);\n\n%%\nfigure;\n% subplot(1,2,1)\n% imagesc(-im1)\n% colormap(bluewhitered)\n% axis equal; axis tight;axis xy\n% \n% subplot(1,2,2)\nimagesc(-log(im1))\n% colormap(bluewhitered)\naxis equal; axis tight;%axis xy\ncolormap('gray')\nylabel('clusters (1st half)')\nxlabel('clusters (2nd half)')\ntitle('Cross-Val: # of cells overlap')\ntext(size(im1,1)/4,size(im1,2)/20,'score = 0.69');\n\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/figure scripts/arc (summer 2016)/fig2i_CV_matrix_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5642537266332517}}
{"text": "function D = driving_function_mono_wfs_ls(x0,nx0,xs,f,conf)\n%DRIVING_FUNCTION_MONO_WFS_LS driving signal for a line source in WFS\n%\n%   Usage: D = driving_function_mono_wfs_ls(x0,nx0,xs,nxs,f,conf)\n%\n%   Input parameters:\n%       x0          - position of the secondary sources / m [nx3]\n%       xs          - position and orientation of virtual line source / m [nx3]\n%                     or [nx6]\n%       f           - frequency of the monochromatic source / Hz\n%       conf        - configuration struct (see SFS_config)\n%\n%   Output parameters:\n%       D           - driving function signal [nx1]\n%\n%   DRIVING_FUNCTION_MONO_WFS_LS(x0,nx0,xs,f,src,conf) returns WFS driving\n%   signals for the given secondary sources, the virtual line source position,\n%   its orientation xs(:,4:6), which is parallel to the line source, and the\n%   frequency f. If no explicit orientation is given, [0 0 1] is assumed.\n%\n%   See also: driving_function_mono_wfs, driving_function_imp_wfs_ps\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 = 5;\nnargmax = 5;\nnarginchk(nargmin,nargmax);\nisargmatrix(x0,nx0,xs);\nisargpositivescalar(f);\nisargstruct(conf);\n\n\n%% ===== Configuration ==================================================\nxref = conf.xref;\nc = conf.c;\ndimension = conf.dimension;\ndriving_functions = conf.driving_functions;\n\n\n%% ===== Computation ====================================================\n% Calculate the driving function in time-frequency domain\n\nomega = 2*pi*f;\n[xs,nxs] = get_position_and_orientation_ls(xs,conf);\n\nif strcmp('2D',dimension)\n\n    % === 2-Dimensional ==================================================\n\n    switch driving_functions\n    case 'default'\n        % --- SFS Toolbox ------------------------------------------------\n        % D using a line source\n        %\n        %              iw (x0-xs) nx0   (2)/ w         \\\n        % D(x0,w) =  - -- -----------  H1  | - |x0-xs| |\n        %              2c   |x0-xs|        \\ c         /\n        %\n        % https://sfs.rtfd.io/en/3.2/d_wfs/#equation-fd-wfs-line\n        %\n        % r = |x0-xs|\n        r = vector_norm(x0-xs,2);\n        % Driving signal\n        D = -1i.*omega./(2.*c) ...\n            .* vector_product(x0-xs,nx0,2) ./ r ...\n            .* besselh(1,2,omega./c.*r);\n        %\n    otherwise\n        error(['%s: %s, this type of driving function is not implemented ', ...\n            'for a line source.'],upper(mfilename),driving_functions);\n    end\n\n\nelseif strcmp('2.5D',dimension)\n\n    % === 2.5-Dimensional ================================================\n\n    % Reference point\n    xref = repmat(xref,[size(x0,1) 1]);\n\n    switch driving_functions\n    case 'default'\n        % --- SFS Toolbox ------------------------------------------------\n        % 2.5D correction factor\n        %        ______________\n        % g0 = \\| 2pi |xref-x0|\n        %\n        g0 = sqrt(2*pi*vector_norm(xref-x0,2));\n        %\n        % D_2.5D using a line source\n        %                         ___\n        %                   g0   |i w  (x0-xs) nx0   (2)/ w         \\\n        % D_2.5D(x0,w) =  - -- _ |---  -----------  H1  | - |x0-xs| |\n        %                   2   \\| c    |x0-xs|         \\ c         /\n        %\n        % https://sfs.rtfd.io/en/3.2/d_wfs/#equation-fd-wfs-line-25d\n        %\n        % r = |x0-xs|\n        r = vector_norm(x0-xs,2);\n        % Driving signal\n        D = -g0./2 .* sqrt(i.*omega./c) ...\n            .* vector_product(x0-xs,nx0,2) ./ r ...\n            .* besselh(1,2,omega./c.*r);\n        %\n    otherwise\n        error(['%s: %s, this type of driving function is not implemented ', ...\n            'for a 2.5D line source.'],upper(mfilename),driving_functions);\n    end\n\nelseif strcmp('3D',dimension)\n\n    % === 3-Dimensional ==================================================\n\n    switch driving_functions\n    case 'default'\n        % --- SFS Toolbox ------------------------------------------------\n        % D using a line source\n        %\n        %              iw   v nx0    (2)/ w     \\\n        % D(x0,w) =  - -- --------  H1  | - |v| | ,\n        %              2c   |v|         \\ c     /\n        %\n        % where v = x0-xs - <x0-xs,nxs > nxs,\n        % and |nxs| = 1.\n        %\n        % https://sfs.rtfd.io/en/3.2/d_wfs/#equation-fd-wfs-line\n        %\n        % v = (I - nxs'nxs)(x0-xs)\n        % r = |v|\n        nxs = nxs(1,:);\n        v = (x0 - xs)*(eye(3) - nxs'*nxs);\n        r = vector_norm(v,2);\n        % Driving signal\n        D = -1i*omega/(2*c) .* vector_product(v,nx0,2) ./ r .* ...\n            besselh(1,2,omega/c.*r);\n        %\n    otherwise\n        error(['%s: %s, this type of driving function is not implemented ', ...\n            'for a line source.'],upper(mfilename),driving_functions);\n    end\n\nelse\n    error('%s: the dimension %s is unknown.',upper(mfilename),dimension);\nend\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_monochromatic/driving_functions_mono/driving_function_mono_wfs_ls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5642537166286999}}
{"text": "function [axes,mult] = elements(cs,multiplicity)\n% extract symmetry elements by multiplicity\n%\n% Syntax\n%\n%   axes = elements(cs,multiplicity) % rotational axes with fixed multiplicity\n%   [axes,multiplicity] = elements(cs) % all rotational axes with multiplicity\n%\n% Input\n%  cs - @crystalSymmetry\n%  multiplicity - double\n%\n% Output\n%  axes - rotational axes vector3d\n%  multiplicity - double\n%\n\nrot = cs.rot(cs.rot.angle>1*degree);\naxes =  rot.axis;\nmult = round(2*pi ./ rot.angle);\n[axes, ~, id] = unique(axes,'tolerance',1e-3,'antipodal');\nmult = accumarray(id,mult,[],@max);\n\naxes = [axes;-axes];\nmult = [mult;mult];\n\nif nargin == 2\n  axes = axes(mult == multiplicity);\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@symmetry/elements.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.564246711154292}}
{"text": "function [align] = planarmove(in,config)\n% planarmove ... alignment under assumption of planar motion\n%\n% [align] = planarmove(in,config)\n% in, cam, config ... see the main GOCAL script\n%\n% align ... structures aligned wit the specified world frame\n%\n% $Id: planarmove.m,v 1.2 2005/05/20 15:31:31 svoboda Exp $\n\n% fit a plane to the reconstructed points and estimate normal\n\nplane.n = planefit(in.Xe(1:3,:)');\n\nnew.n = [0,0,1]'; % align the xy plane horizontally\n\nrotaxis = cross(plane.n,new.n);\nrotangle = acos( (plane.n'*new.n)/norm(plane.n)*norm(new.n) );\n\nR = nfi2r(rotaxis,rotangle);\ns = 3;\nt = [0,0,1]' - s*R*mean(in.Xe(1:3,:)')';\n\nalign.simT.s = s;\nalign.simT.R = R;\nalign.simT.t = t;\n\n[align.P, align.X]\t\t\t\t\t\t\t= align3d(in.Pe,in.Xe,align.simT);\n% save aligned data\nif 1 % SAVE_STEPHI | SAVE_PGUHA\n\t[align.Cst,align.Rot] = savecalpar(align.P,config);\nend\ndrawscene(align.X,align.Cst',align.Rot,61,'cloud','Graphical Output Validation: Aligned data, TopView',config.cal.cams2use);\n\nset(gca,'CameraTarget',[0,0,1]);\nset(gca,'CameraPosition',[0,0,2]);\n\nfigure(61),\n% print -depsc graphevalaligned.eps\neval(['print -depsc ', config.paths.data, 'topview.eps'])\n\ndrawscene(align.X,align.Cst',align.Rot,62,'cloud','Graphical Output Validation: Aligned data, SideView',config.cal.cams2use);\n\nset(gca,'CameraTarget',[0,0,0.9]);\nset(gca,'CameraPosition',[2,0,0.9]);\n\nfigure(62),\n% print -depsc graphevalaligned.eps\neval(['print -depsc ', config.paths.data, 'sideview.eps'])\n\nreturn\n\n\n", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamSelfCal/LocalAlignments/planarmove.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5642466999014724}}
{"text": "function gmm_12 = product_gmm(gmm_1,gmm_2,mrf)\n%PRODUCT_GMM takes the product between two GMMs\n\nK1 = size(gmm_1.Priors,2);\n\nk = 1;\n\nfor i=1:K1\n    \n    I = find(mrf.A(i,:));\n    \n    if ~isempty(I)\n        \n        jl = [mrf.Aj_index(i,I,1)' mrf.Aj_index(i,I,2)'];\n        \n        for j=1:size(jl,1)\n            \n                [Mu,Sigma] = product_gauss(gmm_1.Mu(:,i),gmm_1.Sigma(:,:,i),gmm_2.Mu(:,jl(2)),gmm_2.Sigma(:,:,jl(2)));\n                gmm_12.Mu(:,k) = Mu;\n                gmm_12.Sigma(:,:,k) = Sigma;\n                k = k + 1;\n        end\n        \n    end\nend\n\nK = size(gmm_12.Mu,2);\ngmm_12.Priors = ones(1,K)./K;\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/GMMfunctions/GaussianProduct/product_gmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.564246694788366}}
{"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%==============================================================================\n%\n% Tutorial for FAIR: various distances versus rotation angle\n%\n%   - data                 xrays of hands, Omega=(0,20)x(0,25), level=6, m=[128,128]\n%   - viewer               viewImage2D\n%   - interpolation        splineInter\n%   - distance             {'SSD','NCC','MI','NGF'}\n%   - transformation       rotation2D\n% see also E7_Hands_distance_rotation\n%==============================================================================\n\nclear, close all, help(mfilename);\n\n% setup data\nsetup2DPETCTData; level = 6; omega = ML{level}.omega; m = ML{level}.m; \n\nDM = {'SSD','NCC','MImex','NGFdot'};\n\n\nstr = @(w) sprintf('T(y(%s^o))',num2str(w*180/pi));\nvariable = @(k)['DM',DM{k}];\n\ntheta = [0,10];\n\nfor q=1:length(theta),\n    fprintf('============== %s ====================\\n\\n',...\n      sprintf('theta=%s',num2str(theta(q))));\n  \n    % initialize interpolation [spline] and troansformation [rotation]\n    imgModel('reset','imgModel','splineInter','regularizer','moments','theta',theta(q));\n    [T,R] = imgModel('coefficients',ML{level}.T,ML{level}.R,omega);\n    X  = getCellCenteredGrid(omega,m);\n    Rc = imgModel(R,omega,X);\n    center = (omega(2:2:end)-omega(1:2:end))'/2;\n    trafo('reset','trafo','rotation2D','c',center);\n    trafo('w0');\n\n    % run loo over the following distance measures\n    edge = 10;\n    filename = fullfile(FAIRpath,'temp',...\n      sprintf('%s-%s-theta=%s.mat',mfilename,'rot',num2str(theta(q))));\n    if ~exist(filename,'file'),\n      w = pi/2*linspace(-1,1,101)';\n      save(filename,'w','DM');\n    else\n      clear DM*\n      load(filename)\n    end;\n\n\n    for k=1:length(DM),\n      var = whos('-file',filename);\n      j = find(strcmp({var(:).name},variable(k))==1);\n\n      if isempty(j),\n        fprintf('============== %s ====================\\n\\n',variable(k))\n        disp([variable(k),'=dm;']);\n        dm = zeros(size(w));\n        for j=1:length(w),\n          Y = trafo(w(j),X(:));\n          Tc = imgModel(T,omega,Y);\n          dm(j) = feval(DM{k},Tc,Rc,omega,m,'edge',edge);\n          if j == 1,\n            figure(k); clf;\n            subplot(1,3,1); viewImage(Rc,omega,m); title('reference');\n            subplot(1,3,2); ph = viewImage(Tc,omega,m); th = title(str(w(j)));\n            subplot(1,3,3); rh = plot(w(j),dm(j),'r.','markersize',20);\n            axis([w(1),w(end),-inf,inf]); hold on;      title(DM{k})\n            axis('auto y')\n          else\n            set(ph,'cdata',reshape(Tc,m)'); set(th,'string',str(w(j)));\n            subplot(1,3,3); set(rh,'visible','off');\n            plot(w(1:j),dm(1:j),'k-','linewidth',2);\n            rh = plot(w(j),dm(j),'r.','markersize',20);    pause(1/100)\n          end;\n          fprintf('.'); if ~rem(j,50) || j==length(w), fprintf('\\n'); end;\n        end;\n        eval([variable(k),'=dm;']);\n        save(filename,'-append',variable(k));\n        fprintf('============== %s done ===============\\n\\n',variable(k))\n      end;\n    end;\n\n    Name = @(k) sprintf('%s-theta=%s',DM{k},num2str(theta(q)));\n    for k=1:4,\n      eval(['dm=',variable(k),';']);\n      dm = dm(1:length(w));\n      [wOpt,j] = min(dm);\n      FAIRfigure(k);\n      ph = plot(w,dm,'-',w(j),dm(j),'*');\n      set(ph,'linewidth',2,'color','k','markersize',20);\n      set(gca,'fontsize',30);\n      a = max(dm)-0.2*(max(dm)-min(dm));\n      th = text(w(j),a,['$w^*=',num2str(w(j)),'$']);\n      set(th,'fontsize',30,'interpreter','latex','horizontalalignment','center');\n    end;\n    fprintf('=====================================================================\\n');\n    \nend;\nreturn\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/E7_Hands_distance_rotation_ext.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5642466942750625}}
{"text": "function [sos] = sosmatrixineq(sos,fM,option)\n% SOSMATRIXINEQ --- Creates a SOS constraint from a matrix inequality\n% constraint\n%\n% [SOSP] = sosmatrixineq(SOSP,fM)\n%\n% SOSP is the sum of squares program.\n% fM is a polynomial matrix used to generate the polynomial inequality y'fMy>0\n\n% This file is part of SOSTOOLS - Sum of Squares Toolbox ver 3.00.\n%\n% Copyright (C)2002, 2004, 2013  A. Papachristodoulou (1), J. Anderson (1),\n%                                G. Valmorbida (1), S. Prajna (2),\n%                                P. Seiler (3), P. A. Parrilo (4)\n% (1) Department of Engineering Science, University of Oxford, Oxford, U.K.\n% (2) Control and Dynamical Systems - California Institute of Technology,\n%     Pasadena, CA 91125, USA.\n% (3) Aerospace and Engineering Mechanics Department, University of\n%     Minnesota, Minneapolis, MN 55455-0153, USA.\n% (4) Laboratory for Information and Decision Systems, M.I.T.,\n%     Massachusetts, MA 02139-4307\n%\n% Send bug reports and feedback to: sostools@cds.caltech.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n\n% AP - 16/4/2013\n% JA - 6/6/2013\n\nif nargin<3\n    option='quadraticMineq';%sets the default: asks for sos expression v'M(x)v\nend\n\n[n,m] = size(fM);\n\nif n~=m\n    disp('ERROR: Matrix fM in inequality fM>0 must be square.');\n    return\nend\n\n\nif isfield(sos,'symvartable')\n    % Original Code\n\n    if strcmp(option,'quadraticMineq')\n\n        %creates the vector of variables Mvar to generate the quadratic expression\n        %M_var'*fM*Mvar\n        if n>sos.varmat.count\n            s1 = 'syms ';\n            for i=sos.varmat.count+1:n\n                s1 = strcat(s1,sprintf(' Mvar_%d',i));\n            end\n            %eval(expression) evaluates the MATLAB code in the string expression.\n            eval(s1);\n            \n            \n            Mvar = sym(zeros(n-sos.varmat.count,1));\n            for i=sos.varmat.count+1:n\n                Mvar(i) = eval(['Mvar_',int2str(i)]);\n            end\n            \n            %updates the vartable in the sos program\n            sos.varmat.symvartable = [sos.varmat.symvartable; Mvar];\n            Mvarctable = sym2chartable(Mvar);\n            if sos.varmat.count==0\n                sos.varmat.vartable = [Mvarctable(1:end)];\n            else\n                sos.varmat.vartable = [sos.varmat.vartable(1:end-1),',',Mvarctable(2:end)];\n            end\n            sos.varmat.count = n;\n        end\n        \n        varMconst = sos.varmat.symvartable(1:n);\n        \n        %create the sosconstraint using the sparse multipartite option since it is\n        %homogeneous in varMconst\n        sos = sosineq(sos,varMconst.'*fM*varMconst,'sparsemultipartite',{sos.symvartable,varMconst}); %GV&JA 6/12/2013\n    \n    elseif strcmp(option,'Mineq')\n        sos = sosineq(sos,fM); %GV&JA 10/01/2013\n    end\nelse\n    if strcmp(option,'quadraticMineq')\n    % Multipoly Code: PJS 9/9/2013\n    if n>sos.varmat.count\n        Mvar = polynomial(zeros(n-sos.varmat.count,1));\n        for i=sos.varmat.count+1:n\n            Mvar(i) = pvar(['Mvar_' int2str(i)]);\n        end\n              \n        %updates the vartable in the sos program\n        sos.varmat.vartable = [sos.varmat.vartable; Mvar];\n        sos.varmat.count = n;\n    end    \n    \n    %create the sosconstraint using the sparse multipartite option since it is\n    %homogeneous in varMconst\n    sos = sosineq(sos,Mvar.'*fM*Mvar,'sparsemultipartite',{sos.vartable,Mvar}); % PJS 9/9/2013\n    \n    elseif strcmp(option,'Mineq')\n        sos = sosineq(sos,fM); %GV&JA 10/01/2013\n    end\n    \nend\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SOSTOOLS.300/SOSTOOLS.300/sosmatrixineq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5642466896752591}}
{"text": "function K = covSM(Q, hyp, x, z, i)\n\n% Gaussian Spectral Mixture covariance function. The covariance function \n% parametrization depends on the sign of Q.\n%\n% Let t(Dx1) be an offset vector in dataspace e.g. t = x_i - z_j. Then w(DxP)\n% are the weights and m(Dx|Q|) = 1/p, v(Dx|Q|) = (2*pi*ell)^-2 are spectral\n% means (frequencies) and variances, where p is the period and ell the length\n% scale of the Gabor function h(t2v,tm) given by the expression\n%   h(t2v,tm) = exp(-2*pi^2*t2v).*cos(2*pi*tm)\n%\n% Then, the two covariances are obtained as follows:\n%\n% SM, spectral mixture:  Q>0 => P = 1\n%   k(x_i,z_j) = w'*h(v'*(t.*t),m'*t)\n%\n% SMP, spectral mixture product: Q<0 => P = D\n%   k(x_i,z_j) = prod(w'*h(T*T*v,T*m)), T = diag(t)\n%\n% The hyperparameters are:\n%\n% hyp = [ log(w(:))\n%         log(m(:))\n%         log(sqrt(v(:))) ]\n%\n% For more help on design of covariance functions, try \"help covFunctions\".\n%\n% Note that the spectral density H(s) = F[ h(t) ] of covGaboriso is given by\n% H(s) = N(s|m,v)/2 + N(s|-m,v)/2 where m=1/p is the mean and v=(2*pi*ell)^-2\n% is the variance of a symmetric Gaussian mixture. Hence the covGaboriso\n% covariance forms a basis for the class of stationary covariances since a\n% weighted sum of covGaboriso covariances corresponds to an isotropic\n% location-scale mixture of a symmetric Gaussian mixture in the spectral domain.\n%\n% Internally, covSM constructs a weighted sum of products of 1d covGaboriso\n% covariances using covMask, covProd, covScale and covSum.\n%\n% For more details, see \n% 1) Gaussian Process Kernels for Pattern Discovery and Extrapolation,\n% ICML, 2013, by Andrew Gordon Wilson and Ryan Prescott Adams.\n% 2) GPatt: Fast Multidimensional Pattern Extrapolation with Gaussian \n% Processes, arXiv 1310.5288, 2013, by Andrew Gordon Wilson, Elad Gilboa, \n% Arye Nehorai and John P. Cunningham, and\n% http://mlg.eng.cam.ac.uk/andrew/pattern\n%\n% For Q>0, covSM corresponds to Eq. 12 in Ref (1)\n% For Q<0, covSM corresponds to Eq. 14 in Ref (2) (but w here = w^2 in (14))\n%\n% Copyright (c) by Andrew Gordon Wilson and Hannes Nickisch, 2014-09-24.\n%\n% See also COVFUNCTIONS.M, COVGABORISO.M, COVGABORARD.M.\n\nsmp = Q<0; Q = abs(Q);                    % switch between covSM and covSMP mode\nif nargin<3                                            % report no of parameters\n  if smp, K = '3*D*'; else K = '(1+2*D)*'; end, K = [K,sprintf('%d',Q)]; return\nend\nif nargin<4, z = []; end                                   % make sure, z exists\n\nD = size(x,2); P = smp*D+(1-smp);                   % dimensionality, P=D or P=1\nlw = reshape(hyp(         1:P*Q) ,P,Q);                    % log mixture weights\nlm = reshape(hyp(P*Q+    (1:D*Q)),D,Q);                     % log spectral means\nls = reshape(hyp(P*Q+D*Q+(1:D*Q)),D,Q);       % log spectral standard deviations\n\n% In the following, we construct nested cell arrays to finally obtain either\nif smp % 1) the product of weighted sums of 1d covGabor covariance functions or\n  fac = cell(1,D);\n  for d=1:D\n    add = cell(1,Q); % a) addends for weighted sum of univariate Gabor functions\n    for q=1:Q, add{q} = {'covScale',{'covMask',{d,{'covGaboriso'}}}}; end\n    fac{d} = {'covSum',add};                       % b) combine addends into sum\n  end\n  cov = {'covProd',fac};                       % c) combine factors into product\nelse   % 2) the weighted sum of multivariate covGaborard covariance functions.\n                                  % weighted sum of multivariate Gabor functions\n  add = cell(1,Q); for q=1:Q, add{q} = {'covScale',{'covGaborard'}};  end\n  cov = {'covSum',add};                                       % combine into sum\nend\nif smp      % assemble hyp; covGabor is parametrised using -ls-log(2*pi) and -lm\n  hyp = [lw(:)'/2; -ls(:)'-log(2*pi); -lm(:)'];\nelse\n  hyp = [lw/2;     -ls-log(2*pi);     -lm    ];\nend\n\nif nargin<5                                       % evaluation of the covariance\n  K = feval(cov{:},hyp(:),x,z);\nelse\n  % We compute the indices j in the new hyperparameter vector hyp. The\n  % correction constants c are needed because some hyperparameters in hyp are\n  % powers of hyperparameters accepted by covSM.\n  if i<=P*Q                                               % derivatives w.r.t. w\n    c =  0.5;\n    if smp, j = 1+3*(i-1); else j = 1+(i-1)*(2*D+1); end\n  elseif i<=(P+  D)*Q                                     % derivatives w.r.t. m\n    c = -1.0; j = i- P   *Q; [j1,j2] = ind2sub([D,Q],j);\n    if smp, j = 3+3*(j-1); else j = 1+j1+D+(j2-1)*(2*D+1); end\n  elseif i<=(P+2*D)*Q                                     % derivatives w.r.t. v\n    c = -1.0; j = i-(P+D)*Q; [j1,j2] = ind2sub([D,Q],j);\n    if smp, j = 2+3*(j-1); else j = 1+j1+  (j2-1)*(2*D+1); end\n  else\n    error('Unknown hyperparameter')\n  end\n  K = c*feval(cov{:},hyp(:),x,z,j);\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/covSM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5642466784224395}}
{"text": "function [ x, y, z, w ] = ld1730 ( )\n\n%*****************************************************************************80\n%\n%% LD1730 computes the 1730 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(1730,1);\n  y = zeros(1730,1);\n  z = zeros(1730,1);\n  w = zeros(1730,1);\n  a = 0.0;\n  b = 0.0;\n  v = 0.6309049437420976E-04;\n  [ n, x, y, z, w ] = gen_oh ( 1, n, a, b, v, x, y, z, w );\n  v = 0.6398287705571748E-03;\n  [ n, x, y, z, w ] = gen_oh ( 2, n, a, b, v, x, y, z, w );\n  v = 0.6357185073530720E-03;\n  [ n, x, y, z, w ] = gen_oh ( 3, n, a, b, v, x, y, z, w );\n  a = 0.2860923126194662E-01;\n  v = 0.2221207162188168E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.7142556767711522E-01;\n  v = 0.3475784022286848E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.1209199540995559;\n  v = 0.4350742443589804E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.1738673106594379;\n  v = 0.4978569136522127E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.2284645438467734;\n  v = 0.5435036221998053E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.2834807671701512;\n  v = 0.5765913388219542E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.3379680145467339;\n  v = 0.6001200359226003E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.3911355454819537;\n  v = 0.6162178172717512E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.4422860353001403;\n  v = 0.6265218152438485E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.4907781568726057;\n  v = 0.6323987160974212E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.5360006153211468;\n  v = 0.6350767851540569E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6142105973596603;\n  v = 0.6354362775297107E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6459300387977504;\n  v = 0.6352302462706235E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6718056125089225;\n  v = 0.6358117881417972E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6910888533186254;\n  v = 0.6373101590310117E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.7030467416823252;\n  v = 0.6390428961368665E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.8354951166354646E-01;\n  v = 0.3186913449946576E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.2050143009099486;\n  v = 0.4678028558591711E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.3370208290706637;\n  v = 0.5538829697598626E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.4689051484233963;\n  v = 0.6044475907190476E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.5939400424557334;\n  v = 0.6313575103509012E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.1394983311832261;\n  b = 0.4097581162050343E-01;\n  v = 0.4078626431855630E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.1967999180485014;\n  b = 0.8851987391293348E-01;\n  v = 0.4759933057812725E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2546183732548967;\n  b = 0.1397680182969819;\n  v = 0.5268151186413440E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3121281074713875;\n  b = 0.1929452542226526;\n  v = 0.5643048560507316E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3685981078502492;\n  b = 0.2467898337061562;\n  v = 0.5914501076613073E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4233760321547856;\n  b = 0.3003104124785409;\n  v = 0.6104561257874195E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4758671236059246;\n  b = 0.3526684328175033;\n  v = 0.6230252860707806E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5255178579796463;\n  b = 0.4031134861145713;\n  v = 0.6305618761760796E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5718025633734589;\n  b = 0.4509426448342351;\n  v = 0.6343092767597889E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2686927772723415;\n  b = 0.4711322502423248E-01;\n  v = 0.5176268945737826E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3306006819904809;\n  b = 0.9784487303942695E-01;\n  v = 0.5564840313313692E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3904906850594983;\n  b = 0.1505395810025273;\n  v = 0.5856426671038980E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4479957951904390;\n  b = 0.2039728156296050;\n  v = 0.6066386925777091E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5027076848919780;\n  b = 0.2571529941121107;\n  v = 0.6208824962234458E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5542087392260217;\n  b = 0.3092191375815670;\n  v = 0.6296314297822907E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6020850887375187;\n  b = 0.3593807506130276;\n  v = 0.6340423756791859E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4019851409179594;\n  b = 0.5063389934378671E-01;\n  v = 0.5829627677107342E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4635614567449800;\n  b = 0.1032422269160612;\n  v = 0.6048693376081110E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5215860931591575;\n  b = 0.1566322094006254;\n  v = 0.6202362317732461E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5758202499099271;\n  b = 0.2098082827491099;\n  v = 0.6299005328403779E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6259893683876795;\n  b = 0.2618824114553391;\n  v = 0.6347722390609353E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5313795124811891;\n  b = 0.5263245019338556E-01;\n  v = 0.6203778981238834E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5893317955931995;\n  b = 0.1061059730982005;\n  v = 0.6308414671239979E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6426246321215801;\n  b = 0.1594171564034221;\n  v = 0.6362706466959498E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6511904367376113;\n  b = 0.5354789536565540E-01;\n  v = 0.6375414170333233E-03;\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/ld1730.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5642217201815027}}
{"text": "function y=rotqrvec(q,x)\n%ROTQRVEC applies a quaternion rotation ot a vector array y=[q,x]\n%\n% Inputs:   q(4,1)    quaternion rotation (possibly unnormalized)\n%           x(3n,...) array of 3D column vectors\n%\n% Outputs:  y(3n,...) array of 3D column vectors\n\n%      Copyright (C) Mike Brookes 2011-2012\n%      Version: $Id: rotqrvec.m 1640 2012-03-16 07:43:08Z 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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ns=size(x);\ny=reshape(rotqr2ro(q)*reshape(x,3,[]),s);", "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/rotqrvec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5642168415377019}}
{"text": "%-------------------------These are the input parameters----------------%\nInput_Depth     = 'Ballet40.yuv';       %This is the input depth video\nOutput_Depth    = 'Output_Ballet.yuv';  %Give a name to the output file\nColor           = 'Ballet.yuv';         %Corresponding color video\nWidth           = 1024;                 %Width in pixels\nHeight          = 768;                  %Height in pixels\nFrame_Num       = 1;                    %Number of Frames to process\n%------------------------End of the Input Parameters--------------------%\n\n%-------------------------Key Performance Parameters--------------------%\nw               = 15;                   %Half width of the kernel (odd)\nsigma_range     = 0.025                 %Standard Deviation of the range \n                                        %filter, change this suitably.\n%------------------------End of key perf. parameters--------------------%\n\n\nsigma = [3*w sigma_range]; % bilateral filter standard deviations\n\n% Apply Joint Bilateral Filter\nfilename_in = Input_Depth;\nfid_in = fopen(filename_in, 'rb');\n[Yd, Ud, Vd] = yuv_import(filename_in,[Width Height],Frame_Num);\nfclose(fid_in);\n\nfilename_in = Color;\nfid_in = fopen(filename_in, 'rb');\n[Yc, Uc, Vc] = yuv_import(filename_in,[Width Height],Frame_Num);\nfclose(fid_in);\n\nfid = fopen(Output_Depth, 'w');\n\nfor s = 1:Frame_Num,\n    Ad = Yd{s};\n    Ac = Yc{s};\n    Ax = jbfilter2(double(Ad)/255,double(Ac)/255,w,sigma);\n    image = round(Ax*255);\n    FramesOut.Luma = image;\n    FramesOut.Chroma1 = Ud{s};\n    FramesOut.Chroma2 = Vd{s};\n    figure, imshow(uint8(FramesOut.Luma));\n    fwrite(fid, FramesOut.Luma', 'uint8');\n    fwrite(fid, FramesOut.Chroma1', 'uint8');\n    fwrite(fid, FramesOut.Chroma2', 'uint8');\nend\n\nfclose(fid);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28430-align-depth-images-with-corresponding-color-images/Align_Depth_Maps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.5642168380277133}}
{"text": "% 3D Lattice Boltzmann (BGK) model of a fluid.\n% D3Q19 model. At each timestep, particle densities propagate\n% outwards in the directions indicated in the figure. An\n% equivalent 'equilibrium' density is found, and the densities\n% relax towards that state, in a proportion governed by omega.\n%               Iain Haslam, March 2006.\nnx=12;ny=nx;nz=nx; omega=1.0; density=1.0;t1=1/3; t2=1/18; t3=1/36;\nF=repmat(density/19,[nx ny nz 19]); FEQ=F; matsize=nx*ny*nz;\nCI=[0:matsize:matsize*19];\nBOUND=zeros(nx,ny,nz);\nfor i=1:nx, for j=1:ny, for k=1:nz\n\tBOUND(i,j,k)=((i-5)^2+(j-6)^2+(k-7)^2)<6;\nend, end, end\nBOUND(:,:,1)=1;BOUND(:,1,:)=1;\nON=find(BOUND); %matrix offset of each Occupied Node\nTO_REFLECT=[ON+CI(2) ON+CI(3) ON+CI(4) ON+CI(5)\tON+CI(6) ON+CI(7) ON+CI(8) ...\n  ON+CI(9) ON+CI(10) ON+CI(11) ON+CI(12) ON+CI(13) ON+CI(14) ON+CI(15) ... \n  ON+CI(16) ON+CI(17) ON+CI(18) ON+CI(19)];\nREFLECTED=[ON+CI(3) ON+CI(2) ON+CI(5) ON+CI(4) ON+CI(7) ON+CI(6) ON+CI(11) ...\n  ON+CI(10) ON+CI(9) ON+CI(8) ON+CI(15) ON+CI(14) ON+CI(13) ON+CI(12) ...\n  ON+CI(19) ON+CI(18) ON+CI(17) ON+CI(16)];\navu=1; prevavu=1; ts=0; deltaU=1e-7; numactivenodes=sum(sum(sum(1-BOUND)));\nwhile (ts<4000 & 1e-10<abs((prevavu-avu)/avu)) | ts<100\n\t% Propagate\n\t%nearest-neighbours\n\tF(:,:,:,2)=F(:,:,[nz 1:nz-1],2);\n\tF(:,:,:,3)=F(:,:,[2:nz 1],3);\n\tF(:,:,:,4)=F(:,[ny 1:ny-1],:,4);\n\tF(:,:,:,5)=F(:,[2:ny 1],:,5);\t\n\tF(:,:,:,6)=F([nx 1:nx-1],:,:,6);\n\tF(:,:,:,7)=F([2:nx 1],:,:,7);\t\n\t%next-nearest neighbours\n\tF(:,:,:,8)= F([nx 1:nx-1],[ny 1:ny-1],:,8);\n\tF(:,:,:,9)= F([nx 1:nx-1],[2:ny 1],:,9);\n\tF(:,:,:,10)=F([2:nx 1],[ny 1:ny-1],:,10);\n\tF(:,:,:,11)=F([2:nx 1],[2:ny 1],:,11);\t\n\tF(:,:,:,12)=F([nx 1:nx-1],:,[nz 1:nz-1],12);\n\tF(:,:,:,13)=F([nx 1:nx-1],:,[2:nz 1],13);\n\tF(:,:,:,14)=F([2:nx 1],:,[nz 1:nz-1],14);\n\tF(:,:,:,15)=F([2:nx 1],:,[2:nz 1],15);\n\tF(:,:,:,16)=F(:,[ny 1:ny-1],[nz 1:nz-1],16);\n\tF(:,:,:,17)=F(:,[ny 1:ny-1],[2:nz 1],17);\n\tF(:,:,:,18)=F(:,[2:ny 1],[nz 1:nz-1],18);\n\tF(:,:,:,19)=F(:,[2:ny 1],[2:nz 1],19);\n\tBOUNCEDBACK=F(TO_REFLECT); %Densities bouncing back at next timestep\n\t% Relax; calculate equilibrium state (FEQ) with equivalent speed and density to F \n\tDENSITY = sum(F,4);\n\tUX=(sum(F(:,:,:,[6 8 9 12 13]),4)-sum(F(:,:,:,[7 10 11 14 15]),4))./DENSITY;\n\tUY=(sum(F(:,:,:,[4 8 10 16 17]),4)-sum(F(:,:,:,[5 9 11 18 19]),4))./DENSITY;\n\tUZ=(sum(F(:,:,:,[2 12 14 16 18]),4)-sum(F(:,:,:,[3 13 15 17 19]),4))./DENSITY;\n\tUX(1,:,:)=UX(1,:,:)+deltaU; %Increase inlet pressure\n\tUX(ON)=0; UY(ON)=0; UZ(ON)=0; DENSITY(ON)=0; U_SQU=UX.^2+UY.^2+UZ.^2;\n\tU8=UX+UY;U9=UX-UY;U10=-UX+UY;U11=-U8;U12=UX+UZ;U13=UX-UZ;\n\tU14=-U13;U15=-U12;U16=UY+UZ;U17=UY-UZ;U18=-U17;U19=-U16;\n\t% Calculate equilibrium distribution: stationary\n\tFEQ(:,:,:,1)=t1*DENSITY.*(1-3*U_SQU/2);\n\t% nearest-neighbours\n\tFEQ(:,:,:,2)=t2*DENSITY.*(1 + 3*UZ + 9/2*UZ.^2 - 3/2*U_SQU);\n\tFEQ(:,:,:,3)=t2*DENSITY.*(1 - 3*UZ + 9/2*UZ.^2 - 3/2*U_SQU);\n\tFEQ(:,:,:,4)=t2*DENSITY.*(1 + 3*UY + 9/2*UY.^2 - 3/2*U_SQU);\n\tFEQ(:,:,:,5)=t2*DENSITY.*(1 - 3*UY + 9/2*UY.^2 - 3/2*U_SQU);\n\tFEQ(:,:,:,6)=t2*DENSITY.*(1 + 3*UX + 9/2*UX.^2 - 3/2*U_SQU);\n\tFEQ(:,:,:,7)=t2*DENSITY.*(1 - 3*UX + 9/2*UX.^2 - 3/2*U_SQU);\n\t% next-nearest neighbours\n\tFEQ(:,:,:,8) =t3*DENSITY.*(1 + 3*U8  + 9/2*(U8).^2  - 3*U_SQU/2);\n\tFEQ(:,:,:,9) =t3*DENSITY.*(1 + 3*U9  + 9/2*(U9).^2  - 3*U_SQU/2);\n\tFEQ(:,:,:,10)=t3*DENSITY.*(1 + 3*U10 + 9/2*(U10).^2 - 3*U_SQU/2);\n\tFEQ(:,:,:,11)=t3*DENSITY.*(1 + 3*U11 + 9/2*(U11).^2 - 3*U_SQU/2);\n\tFEQ(:,:,:,12)=t3*DENSITY.*(1 + 3*U12 + 9/2*(U12).^2 - 3*U_SQU/2);\n\tFEQ(:,:,:,13)=t3*DENSITY.*(1 + 3*U13 + 9/2*(U13).^2 - 3*U_SQU/2);\n\tFEQ(:,:,:,14)=t3*DENSITY.*(1 + 3*U14 + 9/2*(U14).^2 - 3*U_SQU/2);\n\tFEQ(:,:,:,15)=t3*DENSITY.*(1 + 3*U15 + 9/2*(U15).^2 - 3*U_SQU/2);\n\tFEQ(:,:,:,16)=t3*DENSITY.*(1 + 3*U16 + 9/2*(U16).^2 - 3*U_SQU/2);\n\tFEQ(:,:,:,17)=t3*DENSITY.*(1 + 3*U17 + 9/2*(U17).^2 - 3*U_SQU/2);\n\tFEQ(:,:,:,18)=t3*DENSITY.*(1 + 3*U18 + 9/2*(U18).^2 - 3*U_SQU/2);\n\tFEQ(:,:,:,19)=t3*DENSITY.*(1 + 3*U19 + 9/2*(U19).^2 - 3*U_SQU/2);\n\tF=omega*FEQ+(1-omega)*F;\n\tF(REFLECTED)=BOUNCEDBACK;\n\tprevavu=avu;avu=sum(sum(sum(UX)))/numactivenodes; ts=ts+1;\nend\nfigure;zcut=5;colormap(gray(2));image(2-BOUND(:,:,5));hold on;\n%Thanks to Thomas Wagner for correcting the transposed results plots\nquiver(UY(:,:,zcut),UX(:,:,zcut));xlabel('y');ylabel('x');\ntitle(['Flow field at z=',num2str(zcut),', after ',num2str(ts),'\\deltat']);\nfigure;ycut=5;colormap(gray(2));image(2-squeeze(BOUND(:,ycut,:)));hold on;\nquiver(squeeze(UZ(:,ycut,:)),squeeze(UX(:,ycut,:)));xlabel('z');ylabel('x');\ntitle(['Flow field at y=',num2str(ycut),', after ',num2str(ts),'\\deltat']);\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/LBM/lbm3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5642168171089175}}
{"text": "function cvx_optval = det_rootn( X )\n\n%DET_ROOTN   Internal cvx version.\n\nerror( nargchk( 1, 1, nargin ) );\nn = size( X, 1 );\nif ndims( X ) > 2,\n\n    error( 'N-D arrays are not supported.' );\n\nelseif size( X, 2 ) ~= n,\n\n    error( 'Matrix must be square.' );\n\nelseif nnz( X ) <= n && nnz( diag( X ) ) == nnz( X ),\n\n    cvx_optval = geo_mean( diag( X ) );\n\nelseif cvx_isconstant( X ),\n\n    cvx_optval = cvx( det_rootn( cvx_constant( X ) ) );\n\nelseif isreal( X ),\n\n    cvx_begin\n        variable Z(n,n) lower_triangular\n        D = diag( Z );\n        maximize( geo_mean( D ) );\n        subject to\n            [ diag( D ), Z' ; Z, X ] == semidefinite(2*n);\n    cvx_end\n\nelse\n\n    cvx_begin\n        variable Z(n,n) lower_triangular complex\n        D = diag( Z );\n        maximize( geo_mean( real( D ) ) );\n        subject to\n            [ diag( D ), Z' ; Z, X ] == hermitian_semidefinite(2*n);\n    cvx_end\n\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/@cvx/det_rootn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5642039763081378}}
{"text": "function [y]=fun(v,x)\ny0=v(1);\nA=v(2);\nw=v(3);\nx0=v(4);\ny=y0+(2*A/pi).*(w./(4*(x-x0).^2+w.^2));\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13648-lorentzian-fit/fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.5642039697588027}}
{"text": "function imgOut = VanHaterenTMO(img, pupil_area)\n%\n%\n%        imgOut = VanHaterenTMO(img, pupil_area)\n%\n%\n%        Input:\n%           -img: input HDR image\n%           -pupil_area:\n%\n%        Output:\n%           -imgOut: tone mapped image\n%\n%     This is the stable version of the Van Hateren 2006 algorithm, this is\n%     not suitable for HDR videos.\n% \n%     Copyright (C) 2010-17  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 <http://www.gnu.org/licenses/>.\n%\n%     The paper describing this technique is:\n%     \"Encoding of High Dynamic Range Video with a Model of Human Cones\"\n% \t  by J. Hans Van Hateren\n%     in ACM Transaction on Graphics 2006\n%\n\ncheck13Color(img);\n\ncheckNegative(img);\n\nif(~exist('pupil_area', 'var'))\n    pupil_area = -1.0;\nend\n\nif(pupil_area <= 0.0)\n    pupil_area = 10; %fixed pupil area 10 mm^2\nend\n\nk_beta = 1.6e-4; % td/ms\na_C = 9e-2;\nC_beta = 2.8e-3; % 1/ms\n\n%Calculate Ios,max\npolIosMax = [a_C, 1, 0, 0, 0, -1 / C_beta];\nmaxIos = max(real(roots(polIosMax)));\n\n%Luminance channel\nLori = lum(img);\n\n%conversion from cd/m^2 to trolands (tr)\nL = Lori * pupil_area;\n\n%Range reduction\ntmpI = - 1 ./ (C_beta + k_beta * L);\n[r, c] = size(L);\nn = r * c;\nIos = zeros(size(tmpI));\nbase = [a_C, 1, 0, 0, 0];\n\nfor i = 1:n\n    tmp = [base, tmpI(i)];\n    Ios(i) = max(real(roots(tmp)));\nend\n\nLd = ClampImg(1 - Ios / maxIos, 0, 1);\n\n%Changing luminance\nimgOut = ChangeLuminance(img, Lori, Ld);\n\nwarning('The image does not require gamma correction.');\n\nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/Tmo/VanHaterenTMO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5642039655816212}}
{"text": "function [gcjLat, gcjLng]  = bd2gcj(bdLat, bdLng)\n    gcjLat = bdLat;\n    gcjLng = bdLng;\n    \n    x_pi = pi * 3000.0 / 180.0;\n    inChina = ~outOfChina(bdLat, bdLng);\n    if ~any(inChina),return;end\n    \n    x = bdLng(inChina) - 0.0065;\n    y = bdLat(inChina) - 0.006;\n    \n    z = hypot(x, y) - 0.00002 * sin(y * x_pi);\n    theta = atan2(y, x) - 0.000003 * cos(x * x_pi);\n    gcjLng(inChina) = z.*cos(theta);\n    gcjLat(inChina) = z.*sin(theta);\n\nend", "meta": {"author": "googollee", "repo": "eviltransform", "sha": "b911c066225716822e4a5b2cab475edcc6cf11a2", "save_path": "github-repos/MATLAB/googollee-eviltransform", "path": "github-repos/MATLAB/googollee-eviltransform/eviltransform-b911c066225716822e4a5b2cab475edcc6cf11a2/matlab/bd2gcj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.564174513691395}}
{"text": "function agm_values_test ( )\n\n%*****************************************************************************80\n%\n%% AGM_VALUE_TEST demonstrates the use of AGM_VALUES.\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  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'AGM_VALUE_TEST:\\n' );\n  fprintf ( 1, '  AGM_VALUES stores values of \\n' );\n  fprintf ( 1, '  the arithmetic geometric mean function.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '      A           B         AGM(A,B)\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, a, b, fx ] = agm_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fprintf ( 1, '  %12f  %12f  %24.16f\\n', a, b, 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/agm_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.5641368266801529}}
{"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%==============================================================================\n% \n% Tutorial for FAIR:  Landmark Based Registration, affine transformation\n%\n% - load data (see setup2DhandData)\n% - setup  viewer (viewImage2D), imgModelpolator (splineimgModel), \n% - setup landmarks (LM)\n% - run affine\n%==============================================================================\n\nclear, close all, help(mfilename)\n\n%% setup hand data\nsetup2DhandData\n\nif FAIRinput(mfilename,'set new landmarks ? ',0),\n  [LM,fig] = getLandmarks(dataT,dataR,omega,m);\n  close(fig);\nend;\n\nomegaT = omega(1,:);\nomegaR = omega(end,:);\nxT = getCellCenteredGrid(omegaT,m);\nxR = getCellCenteredGrid(omegaR,m);\nTc = imgModel(dataT,omegaT,xT);\nRc = imgModel(dataR,omegaR,xR);\n\n%% visualize data\nFAIRfigure(1,'figname',mfilename); clf; \nsubplot(1,3,1); viewImage(Tc,omegaT,m); hold on;\nph = plotLM(LM(:,1:2),'numbering','on','color','r');\nset(ph,'linewidth',2,'markersize',20);\ntitle(sprintf('%s','T&LM'),'fontsize',20);\n\nsubplot(1,3,2); viewImage(Rc,omegaR,m); hold on;\nph = plotLM(LM(:,3:4),'numbering','on','color','g','marker','+');\nset(ph,'linewidth',2,'markersize',20);\ntitle(sprintf('%s','R&LM'),'fontsize',20);\n\n%% compute landmark based registration\n[yc,LM] = LMreg('linear',LM(:,1:4),xR);\nTLM = imgModel(dataT,omegaT,yc);\n\nsubplot(1,3,3); cla; viewImage(TLM,omegaR,m); hold on;\nph = plotLM(LM(:,3:4),'numbering','off','color','g','marker','+');\nqh = plotLM(LM(:,7:8),'numbering','off','color','m','marker','x');\nrh = plot(LM(:,[3,7])',LM(:,[4,8])','m-','linewidth',3);\nset([ph;qh;rh],'linewidth',2,'markersize',20);\ntitle(sprintf('%s','T(y^{affine})&LM'),'fontsize',20);\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/E5_2D_affine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5641368120037293}}
{"text": "function [varargout] = DES(input64,mode,key)\n%DES: Data Encryption Standard\n% Encrypt/Decrypt a 64-bit message using a 64-bit key using the Feistel Network\n% -------------------------------------------------------------------------\n% Inputs: \n%        input64 = a 64-bit message \n%           mode = either 'ENC' encryption or 'DEC' decryption (default 'ENC')\n%            key = a 56/64-bit key (optional under 'ENC', but mandatory under 'DEC')\n% Outputs:\n%   varargout{1} = output64, a 64-bit message after encryption/decryption\n%   varargout{2} = a 64-bit key, if a 64-bit key is not provided as an input\n% -------------------------------------------------------------------------\n% Demos:\n%   plaintext = round(rand(1,64));\n%   [ciphertext,key] = DES(plaintext);       % Encryption syntex 1\n%   [ciphertext1,key] = DES(plaintext,'ENC'); % Encryption syntex 2\n%   deciphertext1 = DES(ciphertext1,'DEC',key);% Decryption syntex\n% \n%   key56 = round(rand(1,56));\n%   [ciphertext2,key64] = DES(plaintext,'ENC',key56);% Encryption syntex 3 (56-bit key)\n%   deciphertext2 = DES(ciphertext2,'DEC',key64);     % Decryption syntex   (64-bit key)\n%   ciphertext3 = DES(plaintext,'ENC',key64);       % Encryption syntex 3 (64-bit key)\n%   deciphertext3 = DES(ciphertext3,'DEC',key56);     % Decryption syntex   (56-bit key)\n%   \n%   % plot results\n%   subplot(4,2,1),plot(plaintext),ylim([-.5,1.5]),xlim([1,64]),title('plaintext')\n%   subplot(4,2,2),plot(ciphertext),ylim([-.5,1.5]),xlim([1,64]),title('ciphertext')\n%   subplot(4,2,3),plot(deciphertext1),ylim([-.5,1.5]),xlim([1,64]),title('deciphertext1')\n%   subplot(4,2,4),plot(ciphertext1),ylim([-.5,1.5]),xlim([1,64]),title('ciphertext1')\n%   subplot(4,2,5),plot(deciphertext2),ylim([-.5,1.5]),xlim([1,64]),title('deciphertext2')\n%   subplot(4,2,6),plot(ciphertext2),ylim([-.5,1.5]),xlim([1,64]),title('ciphertext2')\n%   subplot(4,2,7),plot(deciphertext3),ylim([-.5,1.5]),xlim([1,64]),title('deciphertext3')\n%   subplot(4,2,8),plot(ciphertext3),ylim([-.5,1.5]),xlim([1,64]),title('ciphertext3')\n% -------------------------------------------------------------------------\n% NOTE: \n% 1. If a 64-bit key is provided, then its bit parities will be checked. If\n%    a 56-bit key is provided, then it is automatically added 8 partity\n%    checking bits. However, the 8 parity bits are never used in\n%    DES encryption/decryption process. They are included just for the \n%    completeness of a DES implementation. \n% 2. Cipher modes are not provided in this simple script. If you are \n%    interested or do not know what does cipher modes mean, please go to page\n%    http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation\n%    for details. Please keep in mind that selecting an inappropriate working\n%    mode may extremely weaken the security of your messages.\n% 3. A general description of DES can be found at its wiki page:\n%    http://en.wikipedia.org/wiki/Data_Encryption_Standard\n%    The detailed cryptographical primitives can be found under the page:\n%    http://en.wikipedia.org/wiki/DES_supplementary_material\n%    If you want to speed-up the DES code here, you can simply store these\n%    primitives in memory and call them when you need. \n% -------------------------------------------------------------------------\n% By Yue (Rex) Wu\n% ECE Dept @ Tufts Univ.\n% 08/18/2012\n% If you find bugs, please email me via ywu03@ece.tufts.edu\n% -------------------------------------------------------------------------\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                           0. Initialization                           %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% 0.1 check input\nerror(nargchk(1,3,nargin));\nswitch nargin\n    case 1\n        mode = 'ENC';\n        K = round(rand(8,7));\n        K(:,8) = mod(sum(K,2),2); % note these eight bits of key are never used in encryption\n        K = reshape(K',1,64);\n        varargout{2} = K;\n    case 2\n        switch mode\n            case 'ENC'\n                K = round(rand(8,7));\n                K(:,8) = mod(sum(K,2),2); % note these eight bits of key are never used in encryption\n                K = reshape(K',1,64);\n                varargout{2} = K;\n            case 'DEC'\n                error('Key has to be provided in decryption mode (DEC)')\n            otherwise \n                error('WRONG working mode!!! Select either encrtyption mode: ENC or decryption mode: DEC !!!')\n        end\n    case 3 \n        if isempty(setdiff(unique(key),[0,1])) % check provided key type\n            if numel(key) == 64  % check provided key parity\n                keyParityCheck = @(k) (sum(mod(sum(reshape(k,8,8)),2))==0);\n                if keyParityCheck(key) == 1\n                    K = key(:)';\n                else\n                    error('Key parity check FAILED!!!')\n                end\n            elseif numel(key) == 56 % add parity bits\n                K = reshape(key,7,8)';\n                K(:,8) = mod(sum(K,2),2); % note these eight bits of key are never used in encryption\n                K = reshape(K',1,64);\n                varargout{2} = K;\n                display('Key parity bits added')\n            else\n                error('Key has to be either 56 or 64-bit long!!!')\n            end\n        else\n            error('Key has to be binary!!!')\n        end\nend\n        \n% 0.2 check message length and type\nif numel(input64) == 64 && isempty(setdiff(unique(input64),[0,1]))\n    P = input64;\nelse\n    error('Message has to be a 64-bit message!!!')\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                   1. Cryptographical primitives                       %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% 1.1 define splitting function\nHALF_L = @(message) message(1:32);\nHALF_R = @(message) message(33:64);\n% 1.2 define expansion function\nEF = @(halfMessage) [halfMessage([32,4:4:28])',(reshape(halfMessage,4,8))',halfMessage([5:4:29,1])'];\n% 1.3 define key mixing (KM)\nKM = @(expandedHalfMessage,rK) xor(expandedHalfMessage,reshape(rK,6,8)');\n% 1.4 define eight substitution tables\n% input: 0\t1   2   3   4   5   6   7   8   9   10  11  12  13  14  15\nst{1} = [14\t4\t13\t1\t2\t15\t11\t8\t3\t10\t6\t12\t5\t9\t0\t7;...\n         0  15\t7\t4\t14\t2\t13\t1\t10\t6\t12\t11\t9\t5\t3\t8;...\n         4\t1\t14\t8\t13\t6\t2\t11\t15\t12\t9\t7\t3\t10\t5\t0;...\n         15\t12\t8\t2\t4\t9\t1\t7\t5\t11\t3\t14\t10\t0\t6\t13];\nst{2} = [15\t1\t8\t14\t6\t11\t3\t4\t9\t7\t2\t13\t12\t0\t5\t10;...\n    \t3\t13\t4\t7\t15\t2\t8\t14\t12\t0\t1\t10\t6\t9\t11\t5;...\n\t\t0\t14\t7\t11\t10\t4\t13\t1\t5\t8\t12\t6\t9\t3\t2\t15;...\n\t\t13\t8\t10\t1\t3\t15\t4\t2\t11\t6\t7\t12\t0\t5\t14\t9];\nst{3} = [10\t0\t9\t14\t6\t3\t15\t5\t1\t13\t12\t7\t11\t4\t2\t8;...\n\t\t13\t7\t0\t9\t3\t4\t6\t10\t2\t8\t5\t14\t12\t11\t15\t1;...\n\t\t13\t6\t4\t9\t8\t15\t3\t0\t11\t1\t2\t12\t5\t10\t14\t7;...\n\t\t1\t10\t13\t0\t6\t9\t8\t7\t4\t15\t14\t3\t11\t5\t2\t12];\nst{4} = [7\t13\t14\t3\t0\t6\t9\t10\t1\t2\t8\t5\t11\t12\t4\t15;...\n\t\t13\t8\t11\t5\t6\t15\t0\t3\t4\t7\t2\t12\t1\t10\t14\t9;...\n\t\t10\t6\t9\t0\t12\t11\t7\t13\t15\t1\t3\t14\t5\t2\t8\t4;...\n\t\t3\t15\t0\t6\t10\t1\t13\t8\t9\t4\t5\t11\t12\t7\t2\t14];\nst{5} = [2\t12\t4\t1\t7\t10\t11\t6\t8\t5\t3\t15\t13\t0\t14\t9;...\n\t\t14\t11\t2\t12\t4\t7\t13\t1\t5\t0\t15\t10\t3\t9\t8\t6;...\n\t\t4\t2\t1\t11\t10\t13\t7\t8\t15\t9\t12\t5\t6\t3\t0\t14;...\n\t\t11\t8\t12\t7\t1\t14\t2\t13\t6\t15\t0\t9\t10\t4\t5\t3];\nst{6} = [12\t1\t10\t15\t9\t2\t6\t8\t0\t13\t3\t4\t14\t7\t5\t11;...\n\t\t10\t15\t4\t2\t7\t12\t9\t5\t6\t1\t13\t14\t0\t11\t3\t8;...\n\t\t9\t14\t15\t5\t2\t8\t12\t3\t7\t0\t4\t10\t1\t13\t11\t6;...\n\t\t4\t3\t2\t12\t9\t5\t15\t10\t11\t14\t1\t7\t6\t0\t8\t13];\nst{7} = [4\t11\t2\t14\t15\t0\t8\t13\t3\t12\t9\t7\t5\t10\t6\t1;...\n\t\t13\t0\t11\t7\t4\t9\t1\t10\t14\t3\t5\t12\t2\t15\t8\t6;...\n\t\t1\t4\t11\t13\t12\t3\t7\t14\t10\t15\t6\t8\t0\t5\t9\t2;...\n\t\t6\t11\t13\t8\t1\t4\t10\t7\t9\t5\t0\t15\t14\t2\t3\t12];\nst{8} = [13\t2\t8\t4\t6\t15\t11\t1\t10\t9\t3\t14\t5\t0\t12\t7;...\n\t\t1\t15\t13\t8\t10\t3\t7\t4\t12\t5\t6\t11\t0\t14\t9\t2;...\n\t\t7\t11\t4\t1\t9\t12\t14\t2\t0\t6\t10\t13\t15\t3\t5\t8;...\n\t\t2\t1\t14\t7\t4\t10\t8\t13\t15\t12\t9\t0\t3\t5\t6\t11];\n% the eight binary s-boxes\nfor i = 1:8\n    ST{i} = mat2cell(blkproc(st{i},[1,1],@(x) de2bi(x,4,'left-msb')),ones(1,4),ones(1,16)*4);\nend\n% 1.5 define subsitution function (SBOX)\nSUBS = @(expandedHalfMessage,blkNo) ST{blkNo}{bi2de(expandedHalfMessage(blkNo,[1,6]),'left-msb')+1,bi2de(expandedHalfMessage(blkNo,[2:5]),'left-msb')+1};\nSBOX = @(expandedHalfMessage) [SUBS(expandedHalfMessage,1);SUBS(expandedHalfMessage,2);...\n                               SUBS(expandedHalfMessage,3);SUBS(expandedHalfMessage,4);...\n                               SUBS(expandedHalfMessage,5);SUBS(expandedHalfMessage,6);...\n                               SUBS(expandedHalfMessage,7);SUBS(expandedHalfMessage,8)];\n% 1.6 define permutation function (PBOX)\nPBOX = @(halfMessage) halfMessage([16  7 20 21  29 12 28 17 ... \n                                    1 15 23 26   5 18 31 10 ...\n                                    2  8 24 14  32 27  3  9 ...\n                                   19 13 30  6  22 11  4  25]);\n% 1.7 define initial permutation (IP)\nIP = @(message) message([58\t50\t42\t34\t26\t18\t10\t2 ...\n                        60\t52\t44\t36\t28\t20\t12\t4 ...\n                        62\t54\t46\t38\t30\t22\t14\t6 ...\n                        64\t56\t48\t40\t32\t24\t16\t8 ...\n                        57\t49\t41\t33\t25\t17\t9\t1 ...\n                        59\t51\t43\t35\t27\t19\t11\t3 ...\n                        61\t53\t45\t37\t29\t21\t13\t5 ...\n                        63\t55\t47\t39\t31\t23\t15\t7]);\n% 1.8 define final permutation (FP)\nFP = @(message) message([40\t8\t48\t16\t56\t24\t64\t32 ...\n                        39\t7\t47\t15\t55\t23\t63\t31 ...\n                        38\t6\t46\t14\t54\t22\t62\t30 ...\n                        37\t5\t45\t13\t53\t21\t61\t29 ...\n                        36\t4\t44\t12\t52\t20\t60\t28 ...\n                        35\t3\t43\t11\t51\t19\t59\t27 ...\n                        34\t2\t42\t10\t50\t18\t58\t26 ...\n                        33\t1\t41\t9\t49\t17\t57\t25]);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                           2. key schedule                             %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% 2.1 define permuted choice 1 (PC1)\nPC1L = @(key64) key64([57\t49\t41\t33\t25\t17\t9 ...\n                    1\t58\t50\t42\t34\t26\t18 ...\n                    10\t2\t59\t51\t43\t35\t27 ...\n                    19\t11\t3\t60\t52\t44\t36]);\nPC1R = @(key64) key64([63\t55\t47\t39\t31\t23\t15 ...\n                    7\t62\t54\t46\t38\t30\t22 ... \n                    14\t6\t61\t53\t45\t37\t29 ...\n                    21\t13\t5\t28\t20\t12\t4]);\n% 2.2 define permuted choice 2 (PC2)\nPC2 = @(key56) key56([14 17\t11\t24\t1\t5\t3\t28 ...\n                     15\t6\t21\t10\t23\t19\t12\t4 ...\n                     26\t8\t16\t7\t27\t20\t13\t2 ...\n                     41\t52\t31\t37\t47\t55\t30\t40 ...\n                     51\t45\t33\t48\t44\t49\t39\t56 ...\n                     34\t53\t46\t42\t50\t36\t29\t32]);\n% 2.3 define rotations in key-schedule (RK)\n% round# 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6\n   RK = [1 1 2 2 2 2 2 2 1 2 2 2 2 2 2 1];\n% 2.4 define key shift function (KS)\nKS = @(key28,s) [key28(s+1:end),key28(1:s)];    \n% 2.5 define sub-keys for each round\nleftHKey = PC1L(K); % 28-bit half key\nrightHKey = PC1R(K);% 28-bit half key\nfor i = 1:16\n    leftHKey = KS(leftHKey,RK(i));\n    rightHKey = KS(rightHKey,RK(i));\n    key56 = [leftHKey ,rightHKey];\n    subKeys(i,:) = PC2(key56(:));\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                           3. DES main loop                            %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% 3.1 initial permutation\nC = IP(P);       \nswitch mode\n    case 'ENC' % if encryption, split 64 message to two halves\n        L{1} = HALF_L(C); % left-half 32-bit\n        R{1} = HALF_R(C); % right-half 32-bit\n    case 'DEC' % if decryption, swapping two halves\n        L{1} = HALF_R(C);\n        R{1} = HALF_L(C);       \nend\n% 3.2 cipher round 1 to 16\nfor i = 1:16\n     L{i+1} = R{i}; % half key: 32-bit\n     expended_R = EF(R{i}); % expended half key: 32-bit to 48-bit\n     switch mode\n        case 'ENC' % if encryption, apply sub-keys in the original order\n            mixed_R = KM(expended_R,subKeys(i,:)); % mixed with sub-key: 48-bit\n        case 'DEC' % if decryption, apply sub-keys in the reverse order\n            mixed_R = KM(expended_R,subKeys(16-i+1,:)); % mixed with sub-key: 48-bit\n     end\n     substituted_R = SBOX(mixed_R); % substitution: 48-bit to 32-bit\n     permuted_R = PBOX(reshape(substituted_R',1,32)); % permutation: 32-bit\n     R{i+1} = xor(L{i},permuted_R); % Feistel function: 32-bit\nend\n% 3.3 final permutation\nswitch mode\n    case 'ENC'\n        C = [L{end},R{end}]; \n    case 'DEC'\n        C = [R{end},L{end}];\nend\noutput64 = FP(C);\nvarargout{1} = output64;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                                   END                                 %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37847-data-encryption-standard-des/DES.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5640595564967514}}
{"text": "function [ gc_sum, gc_avg, gc_std  ] = gcFeature( gc, indicator, coor2D_indi )\n%GCFEATURE Summary of this function goes here\n%   Detailed explanation goes here\nif size(indicator,1) ~= size(coor2D_indi,1)\n    fprintf('Warning: indicator and coor mismatch!\\n');\nend\n% vector_num = size(indicator,1);\ndata_num = size(indicator, 2);\n\ngc_sum = zeros( data_num, 11);\ngc_avg = zeros( data_num, 11);\ngc_std = zeros( data_num, 11);\n\n[sH, sW, ~] = size(gc);\n% feature = zeros(data_num, 100);\n\ngc = cat(3, gc, sum(gc(:,:,1:4),3), max(gc(:,:,1:4),[],3), sum(gc(:,:,1:6),3), max(gc(:,:,1:6),[],3));\nfor did = 1:data_num\n    vector_valid = indicator(:,did);\n    if ~any(vector_valid)\n        continue;\n    end\n    cood_ind = coor2D_indi(vector_valid);    \n    loc_orit = zeros(length(cood_ind),11);\n    for k = 1:11\n        loc_orit(:,k) = gc(cood_ind+(k-1)*sW*sH);\n    end\n    \n    gc_sum(did,:) = sum(loc_orit, 1);\n    gc_avg(did,:) = gc_sum(did,:)./length(cood_ind);\n    gc_std(did,:) = std(loc_orit, 1);\nend\n\nend\n\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/DDSampling/gcFeature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5640595450139179}}
{"text": "% tutorial2_spikehistcoupledGLM.m\n%\n% This is an interactive tutorial designed to walk you through the steps of\n% fitting an autoregressive Poisson GLM (i.e., a spiking GLM with\n% spike-history) and a multivariate autoregressive Poisson GLM (i.e., a\n% GLM with spike-history AND coupling between neurons).\n%\n% Data: from Uzzell & Chichilnisky 2004; see README file for details. \n%\n% Last updated: Mar 10, 2020 (JW Pillow)\n\n% Instructions: Execute each section below separately using cmd-enter.\n% For detailed suggestions on how to interact with this tutorial, see\n% header material in tutorial1_PoissonGLM.m\n\n%% ====  1. Load the raw data ============\n\n% ------------------------------------------------------------------------\n% Be sure to unzip the data file data_RGCs.zip\n% (http://pillowlab.princeton.edu/data/data_RGCs.zip) and place it in \n% this directory before running the tutorial.  \n% ------------------------------------------------------------------------\n% (Data from Uzzell & Chichilnisky 2004):\ndatdir = 'data_RGCs/';  % directory where stimulus lives\nload([datdir, 'Stim']);    % stimulus (temporal binary white noise)\nload([datdir,'stimtimes']); % stim frame times in seconds (if desired)\nload([datdir, 'SpTimes']); % load spike times (in units of stim frames)\nncells = length(SpTimes);  % number of neurons (4 for this dataset).\n% Neurons #1-2 are OFF, #3-4 are ON.\n% -------------------------------------------------------------------------\n\n% Compute some basic statistics on the stimulus\ndtStim = (stimtimes(2)-stimtimes(1)); % time bin size for stimulus (s)\nnT = size(Stim,1); % number of time bins in stimulus\n\n% See tutorial 1 for some code to visualize the raw data!\n\n%% ==== 2. Bin the spike trains =========================\n%\n% For now we will assume we want to use the same time bin size as the time\n% bins used for the stimulus. Later, though, we'll wish to vary this.\ntbins = (.5:nT)*dtStim; % time bin centers for spike train binnning\nsps = zeros(nT,ncells);\nfor jj = 1:ncells\n    sps(:,jj) = hist(SpTimes{jj},tbins)';  % binned spike train\nend\n\n% Let's just visualize the spike-train auto and cross-correlations\n% (Comment out this part if desired!)\nclf;\nnlags = 30; % number of time-lags to use \nfor ii = 1:ncells\n    for jj = ii:ncells\n        % Compute cross-correlation of neuron i with neuron j\n        xc = xcorr(sps(:,ii),sps(:,jj),nlags,'unbiased');\n\n        % remove center-bin correlation for auto-correlations (for ease of viz)\n        if ii==jj, xc(nlags+1) = 0;\n        end\n        \n        % Make plot\n        subplot(ncells,ncells,(ii-1)*ncells+jj);\n        plot((-nlags:nlags)*dtStim,xc,'.-','markersize',20); \n        axis tight; drawnow;\n        title(sprintf('cells (%d,%d)',ii,jj)); axis tight;\n    end\nend\nxlabel('time shift (s)');\n\n%% ==== 3. Build design matrix: single-neuron GLM with spike-history =========\n\n% Pick the cell to focus on (for now).\ncellnum = 3;  % 1-2: OFF, 3-4: ON\n\n% Set the number of time bins of stimulus to use for predicting spikes\nntfilt = 25;  % Try varying this, to see how performance changes!\n% Set number of time bins of auto-regressive spike-history to use\nnthist = 20;\n\n% Build stimulus design matrix (using 'hankel');\npaddedStim = [zeros(ntfilt-1,1); Stim]; % pad early bins of stimulus with zero\nXstim = hankel(paddedStim(1:end-ntfilt+1), Stim(end-ntfilt+1:end));\n\n% Build spike-history design matrix\npaddedSps = [zeros(nthist,1); sps(1:end-1,cellnum)];\n% SUPER important: note that this doesn't include the spike count for the\n% bin we're predicting? The spike train is shifted by one bin (back in\n% time) relative to the stimulus design matrix\nXsp = hankel(paddedSps(1:end-nthist+1), paddedSps(end-nthist+1:end));\n\n% Combine these into a single design matrix\nXdsgn = [Xstim,Xsp];\n\n% Let's visualize the design matrix just to see what it looks like\nsubplot(1,10,1:9); \nimagesc(1:(ntfilt+nthist), 1:50, Xdsgn(1:50,:));\nxlabel('regressor');\nylabel('time bin of response');\ntitle('design matrix (including stim and spike history)');\nsubplot(1,10,10); \nimagesc(sps(1:50,cellnum));\nset(gca,'yticklabel', []); \ntitle('spike count');\n\n% The left part of the design matrix has the stimulus values, the right\n% part has the spike-history values.  The image on the right is the spike\n% count to be predicted.  Note that the spike-history portion of the design\n% matrix had better be shifted so that we aren't allowed to use the spike\n% count on this time bin to predict itself!\n\n%% === 4. fit single-neuron GLM with spike-history ==================\n\n% First fit GLM with no spike-history\nfprintf('Now fitting basic Poisson GLM...\\n');\npGLMwts0 = glmfit(Xstim,sps(:,cellnum),'poisson'); % assumes 'log' link and 'constant'='on'.\npGLMconst0 = pGLMwts0(1);\npGLMfilt0 = pGLMwts0(2:end);\n\n% Then fit GLM with spike history (now use Xdsgn design matrix instead of Xstim)\nfprintf('Now fitting Poisson GLM with spike-history...\\n');\npGLMwts1 = glmfit(Xdsgn,sps(:,cellnum),'poisson');\npGLMconst1 = pGLMwts1(1);\npGLMfilt1 = pGLMwts1(2:1+ntfilt);\npGLMhistfilt1 = pGLMwts1(ntfilt+2:end);\n\n%%  Make plots comparing filters\nttk = (-ntfilt+1:0)*dtStim; % time bins for stim filter\ntth = (-nthist:-1)*dtStim; % time bins for spike-history filter\n\nclf; subplot(221); % Plot stim filters\nh = plot(ttk,ttk*0,'k--',ttk,pGLMfilt0, 'o-',ttk,pGLMfilt1,'o-','linewidth',2);\nlegend(h(2:3), 'GLM', 'sphist-GLM','location','northwest');axis tight;\ntitle('stimulus filters'); ylabel('weight');\nxlabel('time before spike (s)');\n\nsubplot(222); % Plot spike history filter\ncolr = get(h(3),'color');\nh = plot(tth,tth*0,'k--',tth,pGLMhistfilt1, 'o-');\nset(h(2), 'color', colr, 'linewidth', 2); \ntitle('spike history filter'); \nxlabel('time before spike (s)');\nylabel('weight'); axis tight;\n\n%% Plot predicted rate out of the two models\n\n% Compute predicted spike rate on training data\nratepred0 = exp(pGLMconst0 + Xstim*pGLMfilt0);\nratepred1 = exp(pGLMconst1 + Xdsgn*pGLMwts1(2:end));\n\n% Make plot\niiplot = 1:60; ttplot = iiplot*dtStim;\nsubplot(212);\nstem(ttplot,sps(iiplot,cellnum), 'k'); hold on;\nplot(ttplot,ratepred0(iiplot),ttplot,ratepred1(iiplot), 'linewidth', 2);\nhold off;  axis tight;\nlegend('spikes', 'GLM', 'hist-GLM');\nxlabel('time (s)');\ntitle('spikes and rate predictions');\nylabel('spike count / bin');\n\n%% === 5. fit coupled GLM for multiple-neuron responses ==================\n\n% First step: build design matrix containing spike history for all neurons\n\nXspall = zeros(nT,nthist,ncells); % allocate space\n% Loop over neurons to build design matrix, exactly as above\nfor jj = 1:ncells\n    paddedSps = [zeros(nthist,1); sps(1:end-1,jj)];\n    Xspall(:,:,jj) = hankel(paddedSps(1:end-nthist+1),paddedSps(end-nthist+1:end));\nend\n\n% Reshape it to be a single matrix\nXspall = reshape(Xspall,nT,[]);\nXdsgn2 = [Xstim, Xspall]; % full design matrix (with all 4 neuron spike hist)\n\nclf; % Let's visualize 50 time bins of full design matrix\nimagesc(1:1:(ntfilt+nthist*ncells), 1:50, Xdsgn2(1:50,:));\ntitle('design matrix (stim and 4 neurons spike history)');\nxlabel('regressor');\nylabel('time bin of response');\n\n%% Fit the model (stim filter, sphist filter, coupling filters) for one neuron \n\nfprintf('Now fitting Poisson GLM with spike-history and coupling...\\n');\n\npGLMwts2 = glmfit(Xdsgn2,sps(:,cellnum),'poisson');\npGLMconst2 = pGLMwts2(1);\npGLMfilt2 = pGLMwts2(2:1+ntfilt);\npGLMhistfilts2 = pGLMwts2(ntfilt+2:end);\npGLMhistfilts2 = reshape(pGLMhistfilts2,nthist,ncells);\n\n% So far all we've done is fit incoming stimulus and coupling filters for\n% one neuron.  To fit a full population model, redo the above for each cell\n% (i.e., to get incoming filters for 'cellnum' = 1, 2, 3, and 4 in turn).  \n\n\n%% Plot the fitted filters and rate prediction\n\nclf; subplot(221); % Plot stim filters\nh = plot(ttk,ttk*0,'k--',ttk,pGLMfilt0, 'o-',ttk,pGLMfilt1,...\n    ttk,pGLMfilt2,'o-','linewidth',2); axis tight; \nlegend(h(2:4), 'GLM', 'sphist-GLM','coupled-GLM', 'location','northwest');\ntitle(['stimulus filter: cell ' num2str(cellnum)]); ylabel('weight'); \nxlabel('time before spike (s)');\n\nsubplot(222); % Plot spike history filter\ncolr = get(h(3),'color');\nh = plot(tth,tth*0,'k--',tth,pGLMhistfilts2,'linewidth',2);\nlegend(h(2:end),'from 1', 'from 2', 'from 3', 'from 4', 'location', 'northwest');\ntitle(['coupling filters: into cell ' num2str(cellnum)]); axis tight;\nxlabel('time before spike (s)');\nylabel('weight');\n\n% Compute predicted spike rate on training data\nratepred2 = exp(pGLMconst2 + Xdsgn2*pGLMwts2(2:end));\n\n% Make plot\niiplot = 1:60; ttplot = iiplot*dtStim;\nsubplot(212);\nstem(ttplot,sps(iiplot,cellnum), 'k'); hold on;\nplot(ttplot,ratepred0(iiplot),ttplot,ratepred1(iiplot),...\n    ttplot,ratepred2(iiplot), 'linewidth', 2);\nhold off;  axis tight;\nlegend('spikes', 'GLM', 'sphist-GLM', 'coupled-GLM', 'location', 'northwest');\nxlabel('time (s)');\ntitle('spikes and rate predictions');\nylabel('spike count / bin');\n\n%% 6. Model comparison: log-likelihoood and AIC\n\n% Let's compute loglikelihood (single-spike information) and AIC to see how\n% much we gain by adding each of these filter types in turn:\n\nLL_stimGLM = sps(:,cellnum)'*log(ratepred0) - sum(ratepred0);\nLL_histGLM = sps(:,cellnum)'*log(ratepred1) - sum(ratepred1);\nLL_coupledGLM = sps(:,cellnum)'*log(ratepred2) - sum(ratepred2);\n\n% log-likelihood for homogeneous Poisson model\nnsp = sum(sps(:,cellnum));\nratepred_const = nsp/nT;  % mean number of spikes / bin\nLL0 = nsp*log(ratepred_const) - nT*sum(ratepred_const);\n\n% Report single-spike information (bits / sp)\nSSinfo_stimGLM = (LL_stimGLM - LL0)/nsp/log(2);\nSSinfo_histGLM = (LL_histGLM - LL0)/nsp/log(2);\nSSinfo_coupledGLM = (LL_coupledGLM - LL0)/nsp/log(2);\n\nfprintf('\\n empirical single-spike information:\\n ---------------------- \\n');\nfprintf('stim-GLM: %.2f bits/sp\\n',SSinfo_stimGLM);\nfprintf('hist-GLM: %.2f bits/sp\\n',SSinfo_histGLM);\nfprintf('coupled-GLM: %.2f bits/sp\\n',SSinfo_coupledGLM);\n\n% Compute AIC\nAIC0 = -2*LL_stimGLM + 2*(1+ntfilt); \nAIC1 = -2*LL_histGLM + 2*(1+ntfilt+nthist);\nAIC2 = -2*LL_coupledGLM + 2*(1+ntfilt+ncells*nthist);\nAICmin = min([AIC0,AIC1,AIC2]); % the minimum of these\n\nfprintf('\\n AIC comparison (smaller is better):\\n ---------------------- \\n');\nfprintf('stim-GLM: %.1f\\n',AIC0-AICmin);\nfprintf('hist-GLM: %.1f\\n',AIC1-AICmin);\nfprintf('coupled-GLM: %.1f\\n',AIC2-AICmin);\n\n% These are whopping differencess! Clearly coupling has a big impact in\n% terms of log-likelihood, though the jump from stimulus-only to\n% own-spike-history is greater than the jump from spike-history to\n% full coupling.\n\n\n%% Advanced exercises:\n% --------------------\n% 1. Write code to simulate spike trains from the fitted spike-history GLM.\n% Simulate a raster of repeated responses from the stim-only GLM and\n% compare to raster from the spike-history GLM\n\n% 2. Write code to simulate the 4-neuron population-coupled GLM. There are\n% now 16 spike-coupling filters (including self-coupling), since each\n% neuron has 4 incoming coupling filters (its own spike history coupling\n% filter plus coupling from three other neurons.  How does a raster of\n% responses from this model compare to the two single-neuron models?\n\n% 3. Compute a non-parametric estimate of the spiking nonlinearity for each\n% neuron. How close does it look to exponential now that we have added\n% spike history? Rerun your simulations using different non-parametric\n% nonlinearity for each neuron. How much improvement do you see in terms of\n% log-likelihood, AIC, or PSTH % variance accounted for (R^2) when you\n% simulate repeated responses?\n", "meta": {"author": "pillowlab", "repo": "GLMspiketraintutorial", "sha": "97c6bc396d6b07545616099c3ad8a91a09167193", "save_path": "github-repos/MATLAB/pillowlab-GLMspiketraintutorial", "path": "github-repos/MATLAB/pillowlab-GLMspiketraintutorial/GLMspiketraintutorial-97c6bc396d6b07545616099c3ad8a91a09167193/tutorial2_spikehistcoupledGLM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5640595437531382}}
{"text": "function [ x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var ]...\n  = lsqr( m, n, A, b, damp, atol, btol, conlim, itnlim, show )\n%\n%        [ x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var ]...\n% = lsqr( m, n, A, b, damp, atol, btol, conlim, itnlim, show );\n%\n% LSQR solves  Ax = b  or  min ||b - Ax||_2  if damp = 0,\n% or   min || (b)  -  (  A   )x ||   otherwise.\n%          || (0)     (damp I)  ||2\n% A  is an m by n matrix defined or a function handle of aprod( mode,x ),\n% that performs the matrix-vector operations.\n% If mode = 1,   aprod  must return  y = Ax   without altering x.\n% If mode = 2,   aprod  must return  y = A'x  without altering x.\n\n%-----------------------------------------------------------------------\n% LSQR uses an iterative (conjugate-gradient-like) method.\n% For further information, see \n% 1. C. C. Paige and M. A. Saunders (1982a).\n%    LSQR: An algorithm for sparse linear equations and sparse least squares,\n%    ACM TOMS 8(1), 43-71.\n% 2. C. C. Paige and M. A. Saunders (1982b).\n%    Algorithm 583.  LSQR: Sparse linear equations and least squares problems,\n%    ACM TOMS 8(2), 195-209.\n% 3. M. A. Saunders (1995).  Solution of sparse rectangular systems using\n%    LSQR and CRAIG, BIT 35, 588-604.\n%\n% Input parameters:\n% atol, btol  are stopping tolerances.  If both are 1.0e-9 (say),\n%             the final residual norm should be accurate to about 9 digits.\n%             (The final x will usually have fewer correct digits,\n%             depending on cond(A) and the size of damp.)\n% conlim      is also a stopping tolerance.  lsqr terminates if an estimate\n%             of cond(A) exceeds conlim.  For compatible systems Ax = b,\n%             conlim could be as large as 1.0e+12 (say).  For least-squares\n%             problems, conlim should be less than 1.0e+8.\n%             Maximum precision can be obtained by setting\n%             atol = btol = conlim = zero, but the number of iterations\n%             may then be excessive.\n% itnlim      is an explicit limit on iterations (for safety).\n% show = 1    gives an iteration log,\n% show = 0    suppresses output.\n%\n% Output parameters:\n% x           is the final solution.\n% istop       gives the reason for termination.\n% istop       = 1 means x is an approximate solution to Ax = b.\n%             = 2 means x approximately solves the least-squares problem.\n% r1norm      = norm(r), where r = b - Ax.\n% r2norm      = sqrt( norm(r)^2  +  damp^2 * norm(x)^2 )\n%             = r1norm if damp = 0.\n% anorm       = estimate of Frobenius norm of Abar = [  A   ].\n%                                                    [damp*I]\n% acond       = estimate of cond(Abar).\n% arnorm      = estimate of norm(A'*r - damp^2*x).\n% xnorm       = norm(x).\n% var         (if present) estimates all diagonals of (A'A)^{-1} (if damp=0)\n%             or more generally (A'A + damp^2*I)^{-1}.\n%             This is well defined if A has full column rank or damp > 0.\n%             (Not sure what var means if rank(A) < n and damp = 0.)\n%             \n%\n%        1990: Derived from Fortran 77 version of LSQR.\n% 22 May 1992: bbnorm was used incorrectly.  Replaced by anorm.\n% 26 Oct 1992: More input and output parameters added.\n% 01 Sep 1994: Matrix-vector routine is now a parameter 'aprodname'.\n%              Print log reformatted.\n% 14 Jun 1997: show  added to allow printing or not.\n% 30 Jun 1997: var   added as an optional output parameter.\n% 07 Aug 2002: Output parameter rnorm replaced by r1norm and r2norm.\n%              Michael Saunders, Systems Optimization Laboratory,\n%              Dept of MS&E, Stanford University.\n% 03 Jul 2007: Modified 'aprodname' to A, which can either be an m by n\n%              matrix, or a function handle.\n%              Ewout van den Berg, University of British Columbia\n% 03 Jul 2007: Modified 'test2' condition, omitted 'test1'.\n%              Ewout van den Berg, University of British Columbia\n%-----------------------------------------------------------------------\n\n%     Initialize.\n\nmsg=['The exact solution is  x = 0                              '\n     'Ax - b is small enough, given atol, btol                  '\n     'The least-squares solution is good enough, given atol     '\n     'The estimate of cond(Abar) has exceeded conlim            '\n     'Ax - b is small enough for this machine                   '\n     'The least-squares solution is good enough for this machine'\n     'Cond(Abar) seems to be too large for this machine         '\n     'The iteration limit has been reached                      '];\n\nwantvar= nargout >= 6;\nif wantvar, var = zeros(n,1); end\n\nif show\n   disp(' ')\n   disp('LSQR            Least-squares solution of  Ax = b')\n   str1 = sprintf('The matrix A has %8g rows  and %8g cols', m, n);\n   str2 = sprintf('damp = %20.14e    wantvar = %8g', damp,wantvar);\n   str3 = sprintf('atol = %8.2e                 conlim = %8.2e', atol, conlim);\n   str4 = sprintf('btol = %8.2e                 itnlim = %8g'  , btol, itnlim);\n   disp(str1);   disp(str2);   disp(str3);   disp(str4);\nend\n\nitn    = 0;\t\t istop  = 0;        nstop  = 0;\nctol   = 0;\t\t if conlim > 0, ctol = 1/conlim; end;\nanorm  = 0;\t\t acond  = 0;\ndampsq = damp^2; ddnorm = 0;        res2   = 0;\nxnorm  = 0;\t     xxnorm = 0;        z      = 0;\ncs2    = -1;     sn2    = 0;\n\n% Set up the first vectors u and v for the bidiagonalization.\n\n% These satisfy  beta*u = b,  alfa*v = A'u.\n\nu      = b(1:m);\tx    = zeros(n,1);\nalfa   = 0;\t\tbeta = norm( u );\nif beta > 0\n   u = (1/beta) * u;\tv = Aprod(u,2);\n   alfa = norm( v );\nend\nif alfa > 0\n   v = (1/alfa) * v;    w = v;\nend\n\narnorm = alfa * beta;\nif arnorm == 0\n   if show, disp(msg(1,:)); end\n   return\nend\narnorm0= arnorm;\n\nrhobar = alfa;\t\tphibar = beta;\t\tbnorm  = beta;\nrnorm  = beta;\nr1norm = rnorm;\nr2norm = rnorm;\nhead1  = '   Itn      x(1)       r1norm     r2norm ';\nhead2  = ' Compatible   LS      Norm A   Cond A';\n\nif show\n   disp(' ')\n   disp([head1 head2])\n   test1  = 1;\t\ttest2  = alfa / beta;\n   str1   = sprintf( '%6g %12.5e',        itn,   x(1) );\n   str2   = sprintf( ' %10.3e %10.3e', r1norm, r2norm );\n   str3   = sprintf( '  %8.1e %8.1e',   test1,  test2 );\n   disp([str1 str2 str3])\nend\n\n%------------------------------------------------------------------\n%     Main iteration loop.\n%------------------------------------------------------------------\nwhile itn < itnlim\n      itn = itn + 1;\n%     Perform the next step of the bidiagonalization to obtain the\n%     next  beta, u, alfa, v.  These satisfy the relations\n%                beta*u  =  a*v   -  alfa*u,\n%                alfa*v  =  A'*u  -  beta*v.\n\n      u    = Aprod(v,1)  -  alfa*u;\n      beta = norm( u );\n      if beta > 0\n         u     = (1/beta) * u;\n         anorm = norm([anorm alfa beta damp]);\n         v     = Aprod(u, 2)  -  beta*v;\n         alfa  = norm( v );\n         if alfa > 0,  v = (1/alfa) * v; end\n      end\n\n%     Use a plane rotation to eliminate the damping parameter.\n%     This alters the diagonal (rhobar) of the lower-bidiagonal matrix.\n\n      rhobar1 = norm([rhobar damp]);\n      cs1     = rhobar / rhobar1;\n      sn1     = damp   / rhobar1;\n      psi     = sn1 * phibar;\n      phibar  = cs1 * phibar;\n\n%     Use a plane rotation to eliminate the subdiagonal element (beta)\n%     of the lower-bidiagonal matrix, giving an upper-bidiagonal matrix.\n\n      rho     = norm([rhobar1 beta]);\n      cs      =   rhobar1/ rho;\n      sn      =   beta   / rho;\n      theta   =   sn * alfa;\n      rhobar  = - cs * alfa;\n      phi     =   cs * phibar;\n      phibar  =   sn * phibar;\n      tau     =   sn * phi;\n\n%     Update x and w.\n\n      t1      =   phi  /rho;\n      t2      = - theta/rho;\n      dk      =   (1/rho)*w;\n\n      x       = x      +  t1*w;\n      w       = v      +  t2*w;\n      ddnorm  = ddnorm +  norm(dk)^2;\n      if wantvar, var = var  +  dk.*dk; end\n\n%     Use a plane rotation on the right to eliminate the\n%     super-diagonal element (theta) of the upper-bidiagonal matrix.\n%     Then use the result to estimate  norm(x).\n\n      delta   =   sn2 * rho;\n      gambar  = - cs2 * rho;\n      rhs     =   phi  -  delta * z;\n      zbar    =   rhs / gambar;\n      xnorm   =   sqrt(xxnorm + zbar^2);\n      gamma   =   norm([gambar theta]);\n      cs2     =   gambar / gamma;\n      sn2     =   theta  / gamma;\n      z       =   rhs    / gamma;\n      xxnorm  =   xxnorm  +  z^2;\n\n%     Test for convergence.\n%     First, estimate the condition of the matrix  Abar,\n%     and the norms of  rbar  and  Abar'rbar.\n\n      acond   =   anorm * sqrt( ddnorm );\n      res1    =   phibar^2;\n      res2    =   res2  +  psi^2;\n      rnorm   =   sqrt( res1 + res2 );\n      arnorm  =   alfa * abs( tau );\n\n%     07 Aug 2002:\n%     Distinguish between\n%        r1norm = ||b - Ax|| and\n%        r2norm = rnorm in current code\n%               = sqrt(r1norm^2 + damp^2*||x||^2).\n%        Estimate r1norm from\n%        r1norm = sqrt(r2norm^2 - damp^2*||x||^2).\n%     Although there is cancellation, it might be accurate enough.\n\n      r1sq    =   rnorm^2  -  dampsq * xxnorm;\n      r1norm  =   sqrt( abs(r1sq) );   if r1sq < 0, r1norm = - r1norm; end\n      r2norm  =   rnorm;\n\n%     Now use these norms to estimate certain other quantities,\n%     some of which will be small near a solution.\n\n      test1   =   rnorm / bnorm;\n      test2   =   arnorm / arnorm0;\n%     test2   =   arnorm/( anorm * rnorm );\n      test3   =       1 / acond;\n      t1      =   test1 / (1    +  anorm * xnorm / bnorm);\n      rtol    =   btol  +  atol *  anorm * xnorm / bnorm;\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      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 <=  2*ctol  , prnt = 1; end\n      if test2 <= 10*atol  , prnt = 1; end\n%     if test1 <= 10*rtol  , prnt = 1; end\n      if istop ~=  0       , prnt = 1; end\n\n      if prnt == 1\n         if show\n            str1 = sprintf( '%6g %12.5e',        itn,   x(1) );\n            str2 = sprintf( ' %10.3e %10.3e', r1norm, r2norm );\n            str3 = sprintf( '  %8.1e %8.1e',   test1,  test2 );\n            str4 = sprintf( ' %8.1e %8.1e',    anorm,  acond );\n            disp([str1 str2 str3 str4])\n         end\n      end\n      if istop > 0, break, end\nend\n\n%     End of iteration loop.\n%     Print the stopping condition.\n\nif show\n   disp(' ')\n   disp('LSQR finished')\n   disp(msg(istop+1,:))\n   disp(' ')\n   str1 = sprintf( 'istop =%8g   r1norm =%8.1e',   istop, r1norm );\n   str2 = sprintf( 'anorm =%8.1e   arnorm =%8.1e', anorm, arnorm );\n   str3 = sprintf( 'itn   =%8g   r2norm =%8.1e',     itn, r2norm );\n   str4 = sprintf( 'acond =%8.1e   xnorm  =%8.1e', acond, xnorm  );\n   disp([str1 '   ' str2])\n   disp([str3 '   ' str4])\n   disp(' ')\nend\n\n%-----------------------------------------------------------------------\n% End of lsqr.m\n%-----------------------------------------------------------------------\n\n\n\nfunction z = Aprod(x,mode)\n   if mode == 1\n      if isnumeric(A), z = A*x;\n      else             z = A(x,1);\n      end\n   else\n      if isnumeric(A), z = (x'*A)';\n      else             z = A(x,2);\n      end\n   end\nend % function Aprod\n\nend\n", "meta": {"author": "mpf", "repo": "spgl1", "sha": "361a5980667288857e4f4f84c53b536ddfac1d53", "save_path": "github-repos/MATLAB/mpf-spgl1", "path": "github-repos/MATLAB/mpf-spgl1/spgl1-361a5980667288857e4f4f84c53b536ddfac1d53/private/lsqr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5640595399028906}}
{"text": "function [x,g,j,gg] = v_kmeans(d,k,x0,l)\n%V_KMEANS Vector quantisation using K-means algorithm [X,ESQ,J]=(D,K,X0,L)\n%\n%  Inputs:\n%\n%    D(N,P)  contains N data vectors of dimension P\n%    K       is number of centres required\n%    X0(K,P) are the initial centres (optional)\n%     \n%      or alternatively\n%\n%    X0      gives the initialization method\n%            'f'   pick K random elements of D as the initial centres [default]\n%            'p'   randomly divide D into K sets and choose the centroids\n%    L       gives max number of iterations (use 0 if you just want to calculate G and J)\n%\n%  Outputs:\n%\n%    X(K,P)  is output row vectors (omitted if L=0)\n%    G       is mean square error\n%    J(N)    indicates which centre each data vector belongs to\n%    GG(L)   gives the mean square error at the start of each iteration (omitted if L=0)\n%\n% It is often a good idea to scale the input data so that it has equal variance in each\n% dimension before calling V_KMEANS.\n\n%  Originally based on a routine by Chuck Anderson, anderson@cs.colostate.edu, 1996\n\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: v_kmeans.m 4497 2014-04-23 10:28:55Z 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\nmemsize=voicebox('memsize'); \n[n,p] = size(d);\nnb=min(n,max(1,floor(memsize/(8*p*k))));    % block size for testing data points\nnl=ceil(n/nb);                  % number of blocks\nif nargin<4\n    l=300;                  % very large max iteration count\n    if nargin<3\n        x0='f';             % use 'f' initialization mode\n    end\nend\nif ischar(x0)\n    if k<n\n        if any(x0)=='p'                  % Initialize using a random partition\n            ix=ceil(rand(1,n)*k);       % allocate to random clusters\n            ix(rnsubset(k,n))=1:k;      % but force at least one point per cluster\n            x=zeros(k,p);\n            for i=1:k\n                x(i,:)=mean(d(ix==i,:),1);\n            end\n        else                                % Forgy initialization: choose k random points [default] \n            x=d(rnsubset(k,n),:);         % sample k centres without replacement\n        end\n    else\n        x=d(mod((1:k)-1,n)+1,:);    % just include all points several times\n    end\nelse\n    x=x0;\nend\nm=zeros(n,1);           % minimum distance to a centre\nj=zeros(n,1);           % index of closest centre\ngg=zeros(l,1);\nwp=ones(1,p);\nkk=1:p;\nkk=kk(ones(n,1),:);\nkk=kk(:);\n\nif l>0\n    for ll=1:l                 % loop until x==y causes a break\n        \n        % find closest centre to each data point [m(:),j(:)] = distance, index\n        \n        ix=1;\n        jx=n-nl*nb;\n        for il=1:nl\n            jx=jx+nb;        % increment upper limit\n            ii=ix:jx;\n            z = disteusq(d(ii,:),x,'x');\n            [m(ii),j(ii)] = min(z,[],2);\n            ix=jx+1;\n        end\n        y = x;              % save old centre list\n        \n        % calculate new centres as the mean of their assigned data values (or zero for unused centres)\n        \n        nd=full(sparse(j,1,1,k,1));         % number of points allocated to each centre\n        md=max(nd,1);                       % remove zeros\n        jj=j(:,wp);\n        x=full(sparse(jj(:),kk,d(:),k,p))./md(:,wp);    % calculate the new means \n        fx=find(nd==0);\n        \n        % if any centres are unused, assign them to data values that are not exactly on centres\n        % choose randomly if there are more such points than needed\n        \n        if ~isempty(fx)\n            q=find(m~=0);\n            if length(q)<=length(fx)\n                x(fx(1:length(q)),:)=d(q,:);\n            else\n                if length(fx)>1\n                    [rr,ri]=sort(rand(length(q),1));\n                    x(fx,:)=d(q(ri(1:length(fx))),:);\n                else\n                    x(fx,:) = d(q(ceil(rand(1)*length(q))),:);\n                end\n            end\n        end\n        \n        % quit if the centres are unchanged\n        \n        gg(ll)=sum(m,1);\n        if x==y\n            break\n        end\n    end\n    gg=gg(1:ll)/n;\n%     ll % *** DEBUG ***\n%     gg' % *** DEBUG ***\n    g=gg(end);\nelse            % if l==0 then just calculate G and J (but rename as X and G)\n    ix=1;\n    jx=n-nl*nb;\n    for il=1:nl\n        jx=jx+nb;        % increment upper limit\n        ii=ix:jx;\n        z = disteusq(d(ii,:),x,'x');\n        [m(ii),j(ii)] = min(z,[],2);\n        ix=jx+1;\n    end\n    x=sum(m,1)/n;\n    g=j;\nend\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/v_kmeans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5640595386421111}}
{"text": "% eeg_interp_sph_sline_test - script to test eeg_interp_sph_spline\n%\n\nclear\n\np = eeg_toolbox_defaults;\n\np.volt.path = 'e:\\matlab\\eeg_toolbox\\eeg_example_data\\';\np.volt.file = 'eeg_124ch_simulatedEMSE.txt'; % (400 rows x 125 columns)\np.volt.type = 'ascii';\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% load electrode co-ordinates\n\np = elec_open(p);\np.elec.plot = 1;\n\nx = p.elec.data.x;\ny = p.elec.data.y;\nz = p.elec.data.z;\n\n% % create spherical electrode positions\n% r = 10\n% fprintf('...generating spherical interpolation points\\n');\n% [x,y,z] = elec_sphere_points(16,24,r);\n% \n% p.elec.data.x = x;\n% p.elec.data.y = y;\n% p.elec.data.z = z;\n% \n% p.elec.data.Xsp = x;\n% p.elec.data.Ysp = y;\n% p.elec.data.Zsp = z;\n% p.elec.data.Rsp = [r r r];\n% \n% p.elec.n = 337;\n%elec_plot(p)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% create simulated potential data\n\np.volt.sampleHz = 1000;\np.volt.sampleMsec = 1;\np.volt.sampleTime = 1 * p.volt.sampleMsec;\np.volt.samplePoint = 1;\np.volt.epochStart = 0;\np.volt.epochEnd = 1;\n\np.volt.var = [];\np.volt.timeArray = 0:1:10;\np.volt.points = 10;\np.volt.channels = length(x);\np.volt.epochStart = 0;\np.volt.epochEnd = 10;\np.volt.sweeps = 1;\np.volt.peaks = [];\n\np.volt.data = repmat(p.elec.data.x',10,1);\n\nV = p.volt.data(p.volt.samplePoint,:);\n\np.clickTimePoint = 0;\np = eeg_contours_engine(p);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% spherical spline interpolation\n\nFV = eeg_interp_sph_spline(V,[x y z]);\n\np.elec.n = length(FV.vertices);\np.elec.data.x = FV.vertices(:,1);\np.elec.data.y = FV.vertices(:,2);\np.elec.data.z = FV.vertices(:,3);\np.elec.data.Xsp = FV.vertices(:,1);\np.elec.data.Ysp = FV.vertices(:,2);\np.elec.data.Zsp = FV.vertices(:,3);\n\np.volt.data = repmat(FV.Cdata,10,1);\n\np.volt.file = 'spherical spline interpolation';\n\np = eeg_contours_engine(p);\n\n\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% scd interpolation\n\nFV = eeg_interp_sph_spline_scd(V,[x y z]);\n\np.elec.n = length(FV.vertices);\np.elec.data.x = FV.vertices(:,1);\np.elec.data.y = FV.vertices(:,2);\np.elec.data.z = FV.vertices(:,3);\np.elec.data.Xsp = FV.vertices(:,1);\np.elec.data.Ysp = FV.vertices(:,2);\np.elec.data.Zsp = FV.vertices(:,3);\n\np.volt.data = repmat(FV.Cdata,10,1);\n\np.volt.file = 'spherical spline scd interpolation';\n\np = eeg_contours_engine(p);\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/eeg_interp_sph_spline_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.564059533531084}}
{"text": "function [M,P,K,MU,S,LH] = ghkf_update(M,P,Y,h,R,h_param,p)\n% GHKF_UPDATE - Gauss-Hermite Kalman filter update step\n%\n% Syntax:\n%   [M,P,K,MU,S,LH] = GHKF_UPDATE(M,P,Y,h,R,param,p)\n%\n% In:\n%   M  - Mean state estimate after prediction step\n%   P  - State covariance after prediction step\n%   Y  - Measurement vector.\n%   h  - Measurement model function as a matrix H defining\n%        linear function h(x) = H*x, inline function,\n%        function handle or name of function in\n%        form h(x,param)\n%   R  - Measurement covariance\n%   h_param - Parameters of h\n%   p  - Degree of approximation (number of quadrature points)\n%\n% Out:\n%   M  - Updated state mean\n%   P  - Updated state covariance\n%   K  - Computed Kalman gain\n%   MU - Predictive mean of Y\n%   S  - Predictive covariance Y\n%   LH - Predictive probability (likelihood) of measurement.\n%   \n% Description:\n%   Perform additive form Gauss-Hermite Kalman filter (GHKF)\n%   measurement update step. Assumes additive measurement\n%   noise.\n%\n%   Function h(.) should be such that it can be given a\n%   DxN matrix of N sigma Dx1 points and it returns \n%   the corresponding measurements for each sigma\n%   point. This function should also make sure that\n%   the returned sigma points are compatible such that\n%   there are no 2pi jumps in angles etc.\n%\n% Example:\n%   h = inline('atan2(x(2,:)-s(2),x(1,:)-s(1))','x','s');\n%   [M2,P2] = ghkf_update(M1,P1,Y,h,R,S);\n%\n% See also:\n%   GHKF_PREDICT, GHRTS_SMOOTH, GH_TRANSFORM\n\n% History:\n%   Jun 18, 2009 - Initial version  \n%   May 24, 2010 - Fixed parameter input and description (asolin)\n%   Aug 5,  2010 - Renamed from 'gh_update' to 'ghkf_update' (asolin)\n\n% Copyright (C) 2009 Hartikainen, S\u00e4rkk\u00e4, Solin\n%\n% $Id: gh_update.m,v 1.2 2009/07/01 06:34:41 ssarkka Exp $\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\n  %\n  % Check that all arguments are there\n  %\n  if nargin < 5\n     error('Too few arguments');\n  end\n  if nargin < 6\n     h_param = [];\n  end\n  if nargin < 7\n     p = []; \n  end\n  if isempty(p)\n     p = 3;\n  end\n\n  %\n  % Do the transform and make the update\n  %\n  tr_param = {p};\n  [MU,S,C,X] = gh_transform(M,P,h,h_param,tr_param);\n  S = S + R;\n  K = C / S;\n  M = M + K * (Y - MU);\n  P = P - K * S * K';\n  \n  if nargout > 5\n    LH = gauss_pdf(Y,MU,S);\n  end\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/ghkf_update.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.564059525898497}}
{"text": "function [ weights CompMat fuzzyTFN ] = FuzzyAHP( CompMat )\n%FUZZYAHP Fuzzy AHP\n%   Fuzzy AHP selection algorithm\n%\n% AUTHOR:\n%           F. Ozgur CATAK\n% CREATED:\n%           October, 2011\n\n% fuzzy tfn and inverse fuzzy tfn constants\nfuzzyTFN = {[1     1     1  ] \t[1      1    1  ]\n            [1/2   3/4   1  ] \t[1      4/3  2  ]\n            [2/3   1     3/2] \t[2/3    1    3/2]\n            [1     3/2   2  ] \t[1/2    2/3  1  ]\n            [3/2   2     5/2] \t[2/5    1/2  2/3]\n            [2     5/2   3  ] \t[1/3    2/5  1/2]\n            [5/2   3     7/2] \t[2/7    1/3  2/5]\n            [3     7/2   4  ] \t[1/4    2/7  1/3]\n            [7/2   4     9/2] \t[2/9    1/4  2/7]};\n\nfuzzyCompMatCell={};\n\n%%\n% convert ordinal numbers to\n% triangular fuzzy number using fuzzyTFN matrix\n[m n] = size(CompMat);\n\nfor i=1:m\n    for j=i+1:m\n       CompMat(j,i) = 1 / CompMat(i,j); \n    end\nend\n\nfor i=1:m\n    for j=1:n\n        criteria = CompMat(i,j);\n        if criteria >= 1\n           fuzzyCompMatCell{i,j} = fuzzyTFN{ criteria ,1 };\n        else\n           fuzzyCompMatCell{i,j} = fuzzyTFN{ round(criteria^-1) ,2 };\n        end\n    end\nend\n\n%%\n% find sum of every l,m,u values for triangular fuzzy number\nfor i=1:m\n    vec = [fuzzyCompMatCell{i,:}];\n    mExtendAnalysis{1,i} = sum(reshape(vec,3,[])');\nend\n\nvec = [mExtendAnalysis{1,:}];\nmExtendAnalysisSum = sum(reshape(vec,3,[])');\n\nfor i=1:m\n    vec = [mExtendAnalysis{1,i}];\n    for j=1:3\n        val = mExtendAnalysisSum(1,j);\n        %valSum(1,j) = val*vec(1,j);\n        valSum(1,j) = (vec(1,j))*(1/val);\n    end\n    mExtendAnalysis{1,i} = valSum;\nend\n\n%%\n% degree of possibility calculation\n%              /---\n%              | 1    if m2>=m1\n%              |\n%              | 0    if l1>=l2\n% V(M2>=M1) = <\n%              |     l1-u2\n%              | --------------- otherwise\n%              | (m1-u2)-(m1-l1)\n%              \\---\ndegreeOfPossibility = zeros(m*(m-1),3);\nrowIndex = 1;\nfor i=1:m\n    for j=1:m\n        if i~=j\n            degreeOfPossibility(rowIndex,[1 2]) = [i j];\n            M1 = mExtendAnalysis{1,i};\n            M2 = mExtendAnalysis{1,j};\n            if M1(1,2) >= M2(1,2)\n                degreeOfPossibility(rowIndex,3) = 1;\n            elseif M2(1,1) >= M1(1,3)\n                degreeOfPossibility(rowIndex,3) = 0;\n            else\n                degreeOfPossibility(rowIndex,3) = (M2(1,1)-M1(1,3))/((M1(1,2)-M1(1,3))-(M2(1,2)-M2(1,1)));\n            end\n            rowIndex = rowIndex + 1;\n        end\n    end\nend\n%%\n% normalized weight calculation\nweights = zeros(1,m);\nfor i=1:m,\n    weights(1,i) = min(degreeOfPossibility([find(degreeOfPossibility(:,1) == i)], [3]));\nend\nweights = weights/sum(weights);\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/33406-fuzzy-ahp/FuzzyAHP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5639801926711776}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   PARAMETERS Returns a data structure containing the parameters of an example serial arm\n%\n%   Author: Arturo Gil. Universidad Miguel Hernandez de Elche. \n%   email: arturo.gil@umh.es date:   20/11/2013\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 <http://www.gnu.org/licenses/>.\nfunction robot = parameters()\n\nrobot.name= 'Serial example';\n\nrobot.DH.theta= '[ ]';\nrobot.DH.d='[]';\nrobot.DH.a='[]';\nrobot.DH.alpha= '[]';\n\nrobot.J=[];\n\nrobot.inversekinematic_fn = 'inversekinematic(robot, T)';\n\n%number of degrees of freedom\nrobot.DOF = 6;\n\n%rotational: 0, translational: 1\nrobot.kind=['R' 'R' 'R' 'R' 'R' 'R'];\n\n%minimum and maximum rotation angle in rad\nrobot.maxangle =[deg2rad(-165) deg2rad(165); %Axis 1, minimum, maximum\n                deg2rad(-110) deg2rad(110); %Axis 2, minimum, maximum\n                deg2rad(-110) deg2rad(70); %Axis 3\n                deg2rad(-160) deg2rad(160); %Axis 4: \n                deg2rad(-120) deg2rad(120); %Axis 5\n                deg2rad(-400) deg2rad(400)]; %Axis 6: \n\n%maximum absolute speed of each joint rad/s or m/s\nrobot.velmax = [deg2rad(250); %Axis 1, rad/s\n                deg2rad(90); %Axis 2, rad/s\n                deg2rad(90); %Axis 3, rad/s\n                deg2rad(150); %Axis 4, rad/s\n                deg2rad(120); %Axis 5, rad/s\n                deg2rad(190)];%Axis 6, rad/s\n\nrobot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time\n            % end effectors maximum velocity\nrobot.linear_velmax = 1.0; %m/s, unavailable from datasheet\n\n%base reference system \nrobot.T0 = eye(4);\n\n%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION\n%position, velocity and acceleration\nrobot=init_sim_variables(robot);\nrobot.path = pwd;\n\n% GRAPHICS\nrobot.graphical.has_graphics=1;\nrobot.graphical.color = [255 102 51]./255;\n%for transparency\nrobot.graphical.draw_transparent=0;\n%draw DH systems\nrobot.graphical.draw_axes=1;\n%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for\n%bigger robots\nrobot.graphical.axes_scale=1;\n%adjust for a default view of the robot\nrobot.axis=[-1 1 -1 1 0 1.5];\n%read graphics files\nrobot = read_graphics(robot);\n\n%DYNAMICS\nrobot.has_dynamics=0;\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/serial/parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5639801807166553}}
{"text": "function [hPa] = MPa2hPa(MPa)\n% Convert pressure from megapascals to hectopascals.\n% Chad Greene 2012\nhPa = MPa*10000.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/35258-unit-converters/unit_converters/MPa2hPa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5639801740406682}}
{"text": "%% Setting of the problem\nglobal s\npde = fracLapdata9;\n% pde = checkboarddata;\npde.L = 1;\noption.maxIt = 4;\noption.maxN = 1e6;\noption.elemType = 'P1P1';\noption.solver = 'mg';\noption.gNquadorder = 4;\noption.tol = 1e-6;\n[node,elem] = squaremesh([-1 1 -1 1],0.5);\nbdFlag = setboundary(node,elem,'Dirichlet');\n\n%% s = 0.2\ns = 0.2;\nfemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.4\ns = 0.4;\nfemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.6\ns = 0.6;\nfemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.8\ns = 0.8;\nfemfracLap(node,elem,pde,bdFlag,option);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fracLaplacian/femratefracLapP1P1cf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597275123281, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5639713633788246}}
{"text": "function d = dell2nose_pair(trx,fly1,fly2,istry)\n\nnsamples = 20;\n\n% initialize\nd = nan(1,trx(fly1).nframes);\n\n% get start and end frames of overlap\nt0 = max(trx(fly1).firstframe,trx(fly2).firstframe);\nt1 = min(trx(fly1).endframe,trx(fly2).endframe);\n  \n% no overlap\nif t1 < t0, \n  return;\nend\n\n% position of nose2\nxnose = trx(fly2).x_mm + 2*trx(fly2).a_mm.*cos(trx(fly2).theta_mm);\nynose = trx(fly2).y_mm + 2*trx(fly2).a_mm.*sin(trx(fly2).theta_mm);\n\n% ellipse 1\nx_mm1 = trx(fly1).x_mm;\ny_mm1 = trx(fly1).y_mm;\na_mm1 = trx(fly1).a_mm;\nb_mm1 = trx(fly1).b_mm;\ntheta_mm1 = trx(fly1).theta_mm;\n\noff1 = trx(fly1).off;\noff2 = trx(fly2).off;\n\nif nargin < 4,\n  tstry = t0:t1;\nelse\n  tstry = istry(:)' - off1;\nend\n\nfor t = tstry,\n  i = t + off1;\n  j = t + off2;\n  d(i) = ellipsedist_hack(x_mm1(i),y_mm1(i),...\n    2*a_mm1(i),2*b_mm1(i),theta_mm1(i),...\n    xnose(j),ynose(j),nsamples);\nend", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/dell2nose_pair.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.563971357459138}}
{"text": "function [KGain,XNEW,PT1,PT2,PT3,YNEW] = MSMTUPDT(Xinew1,Xinew2,Xinew3,Yinew1,Yinew2,Yinew3,Xbark,Ybark,Pbark,Wco,Wci,Wcin,XNEW,VTt);\n\nPYbarkYbark1 = Wco*(Yinew1 - Ybark)*(Yinew1 - Ybark)';\nPYbarkYbark2 = Wci*(Yinew2 - Ybark)*(Yinew2 - Ybark)';\nPYbarkYbark3 = Wcin*(Yinew3 - Ybark)*(Yinew3 - Ybark)';\n\nPXbarkYbark1 = Wco*(Xinew1 - Xbark)*(Yinew1 - Ybark)';\nPXbarkYbark2 = Wci*(Xinew2 - Xbark)*(Yinew2 - Ybark)';\nPXbarkYbark3 = Wcin*(Xinew3 - Xbark)*(Yinew3 - Ybark)';\n\nDENUP = sum(sum(PYbarkYbark1) + sum(PYbarkYbark2) + sum(PYbarkYbark3));\nNUMUP = sum(sum(PXbarkYbark1) + sum(PXbarkYbark2) + sum(PXbarkYbark3));\n\nKGain = NUMUP/DENUP;\n\nYNEW = (sin(XNEW)).^2 + exp(VTt);\nXNEW = Xbark + KGain*(YNEW - Ybark);\n\nPT1 = Pbark - KGain*PYbarkYbark1*KGain;\nPT2 = Pbark - KGain*PYbarkYbark2*KGain;\nPT3 = Pbark - KGain*PYbarkYbark3*KGain;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/11145-unscented-kalman-filter/MSMTUPDT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5639418113515244}}
{"text": "function [J, Ybus, Yf, Yt] = makeJac(baseMVA, bus, branch, gen, fullJac)\n%MAKEJAC  Forms the power flow Jacobian.\n%   J = MAKEJAC(MPC)\n%   J = MAKEJAC(MPC, FULLJAC)\n%   J = MAKEJAC(BASEMVA, BUS, BRANCH, GEN)\n%   J = MAKEJAC(BASEMVA, BUS, BRANCH, GEN, FULLJAC)\n%   [J, YBUS, YF, YT] = MAKEJAC(MPC)\n%\n%   Returns the power flow Jacobian and, optionally, the system admittance\n%   matrices. Inputs can be a MATPOWER case struct or individual BASEMVA,\n%   BUS, BRANCH and GEN values. Bus numbers must be consecutive beginning\n%   at 1 (i.e. internal ordering). If the FULLJAC argument is present and\n%   true, it returns the full Jacobian (sensitivities of all bus injections\n%   w.r.t all voltage angles/magnitudes) as opposed to the reduced version\n%   used in the Newton power flow updates. The units for all quantities are\n%   in per unit with radians for voltage angles.\n%\n%   Note: This function builds the Jacobian from scratch, rebuilding the\n%         YBUS matrix in the process. You probably don't want to use this\n%         in performance critical code.\n%\n%   See also MAKEYBUS, EXT2INT\n\n%   MATPOWER\n%   Copyright (c) 1996-2017, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\nif nargin < 4\n    mpc     = baseMVA;\n    if nargin > 1\n        fullJac = bus;\n    else\n        fullJac = 0;\n    end\n    baseMVA = mpc.baseMVA;\n    bus     = mpc.bus;\n    branch  = mpc.branch;\n    gen     = mpc.gen;\nelseif nargin < 5\n    fullJac = 0;\nend\n\n%% define named indices into bus, gen, branch matrices\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n\n%% build Ybus\n[Ybus, Yf, Yt] = makeYbus(baseMVA, bus, branch);\n\n%% extract voltage\nV = bus(:, VM) .* exp(1j * pi/180 * bus(:, VA));\n\n%% make sure we use generator setpoint voltage for PV and slack buses\non = find(gen(:, GEN_STATUS) > 0);      %% which generators are on?\ngbus = gen(on, GEN_BUS);                %% what buses are they at?\nk = find(bus(gbus, BUS_TYPE) == PV | bus(gbus, BUS_TYPE) == REF);\nV(gbus(k)) = gen(on(k), VG) ./ abs(V(gbus(k))).* V(gbus(k));\n\n%% build Jacobian\n[dSbus_dVa, dSbus_dVm] = dSbus_dV(Ybus, V);\nif fullJac\n    j11 = real(dSbus_dVa);\n    j12 = real(dSbus_dVm);\n    j21 = imag(dSbus_dVa);\n    j22 = imag(dSbus_dVm);\nelse\n    %% get bus index lists of each type of bus\n    [ref, pv, pq] = bustypes(bus, gen);\n\n    j11 = real(dSbus_dVa([pv; pq], [pv; pq]));\n    j12 = real(dSbus_dVm([pv; pq], pq));\n    j21 = imag(dSbus_dVa(pq, [pv; pq]));\n    j22 = imag(dSbus_dVm(pq, pq));\nend\n\nJ = [   j11 j12;\n        j21 j22;    ];\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/makeJac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5639270505498796}}
{"text": "function y = vl_nnglobalpool(x, varargin)\n%VL_NNGLOBALPOOL CNN global poolinng.\n%   Y = VL_NNGLOBALPOOL(X) applies the pooling operator to all\n%   spatial locations of the data X. X is a SINGLE array of dimension \n%   H x W x C x N where (H,W) are the height and width of the map stack, \n%   C is the number of feature channels and N the number of of images \n%   in the batch.\n%\n%   DZDX = VL_NNGLOBALPOOL(X, POOL, DZDY) computes the derivatives of the\n%   block projected onto DZDY. DZDX and DZDY have the same dimensions\n%   as X and Y respectively.\n%\n%   VL_NNGLOBALPOOL(..., 'option', value, ...) takes the following option:\n%\n%   `method`:: 'avg'\n%     Specify method of pooling. It can be either 'max' (retain max value\n%     over all spatial locations per channel) or 'avg' (compute the average\n%     value over all spatial locations per channel).\n%\n%   The output a is a SINGLE array of dimensions 1 x 1 x C x N.\n%\n%   The derivative DZDY has the same dimension of the output Y and\n%   The derivative DZDX has the same dimension as the input X.\n%\n% Copyright (C) 2016 Samuel Albanie and Andrea Vedaldi\n% Licensed under The MIT License [see LICENSE.md for details]\n\n  opts.method = 'avg' ;\n  [opts, dzdy] = vl_argparsepos(opts, varargin) ;\n\n  if nargin <= 1 || isempty(dzdy)\n    switch opts.method\n      case 'avg', y = mean(mean(x, 1), 2) ;\n      case 'max', y = max(max(x, [], 1), [], 2) ;\n      otherwise, error('Pooling method %s not recognized', opts.method) ;            \n    end\n  else\n    base = 1 / (size(x,1) * size(x,2)) * ones(size(x), 'like', x) ;\n    y = bsxfun(@times, base, dzdy{1}) ;\n  end\n", "meta": {"author": "ShuaiBai623", "repo": "MFT", "sha": "8762f8cdf494ce0b1a1c3d431660c5c8fd91744a", "save_path": "github-repos/MATLAB/ShuaiBai623-MFT", "path": "github-repos/MATLAB/ShuaiBai623-MFT/MFT-8762f8cdf494ce0b1a1c3d431660c5c8fd91744a/external_libs/matconvnet/contrib/mcnExtraLayers/matlab/vl_nnglobalpool.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.5639270374036492}}
{"text": "function [n,edges,nbedges,xechan] = hist_ic(x,crit)\n\n%HIST_IC  optimal Histogram based on IC information criterion\n%\n%   [N,EDGES,NBEDGES,XECHAN] = HIST-IC(X,CRIT) \n%\tbins the elements of X into an optimal number of bins according\n%\tto a cost function based on Akaike's Criterion.\n%\n%\n%   CRIT = 1 | 2 | 3  (choose one of the 3 possible criterium)  (default 3)\n%          4          (returns the initial histogram instead of the optimal one) \n%\n%\n%   N = cell array containing the distribution of each column of X\n%   (or a vector if X is a column vector)\n%   EDGES = cell array containing the bin edges of each column of X\n%   (or a vector if X is a column vector)\n%   NBEDGES = vector containing the number of bin edges for each column of X\n%   (or a number if X is a column vector)\n%   XECHAN = discretized version of X\n%\n%   Ref : O. Colot et al., Information Criteria and Abrupt Changes in\n%         Probability Laws, Signal Processing VII: Theory and Applications\n%\t  pp.1855-18858, September 1994\n%\n%   F. El-Matouat, O. Colot 2000 (first version)\n%   Revised 01-06-2001 by Ph. Leray - philippe.leray@univ-nantes.fr\n%\n%\n%   Things to do :\n%\t* Call criteron by a name ('aic','xxx', ...) instead of a number\n%\n\n\nif nargin == 0\n    error('Requires one or two arguments.')\nend\n\nif nargin == 1\n    crit = 3;\nend;\n\nif min(size(x))==1, x = x(:); end\n\nif isstr(x)\n    error('Input argument must be numeric.')\nend\n\nif isempty(x),\n\terror('No elements to count')\nend\n\n\n[nb_l,nb_c]=size(x);\n\n% Outputs declaration\nxechan=zeros(nb_l,nb_c);\n\nedges=cell(nb_c,1);\n% Local variables\nmaxi = max(x);\nmini = min(x);\n\n%% Erreur ? ancien code :\n%% nb_clas_ini=2*round(sqrt(nb_l)-1);\t% article Fatima\n\nnb_clas_ini=round(2*sqrt(nb_l)-1);\t\n\npas_ini=(maxi-mini)/nb_clas_ini;\t% initial step\n\nfor j=1:nb_c,\n\n\t% optimal histogram for each column of X\n\thisto_ini =hist(x(:,j),nb_clas_ini);\t\t% initial histogram\n\n\tif (crit~=4)\n\t\t[hist_opt,pas_opt]=hist1_ic(histo_ini,nb_l,pas_ini(j),nb_clas_ini,crit);\n\telse\n\t\tfprintf('Histo initial\\n');\n\t\thist_opt=histo_ini;\n\t\tpas_opt=ones(1,nb_clas_ini)*pas_ini(j);\n\tend;\n\tnbedges(j)=size(hist_opt,2);\n\tedges{j}=mini(j)+cumsum(pas_opt(1:nbedges(j)-1)); %+1e-7;\n        [n{j} xechan(:,j)]=histc(x(:,j),[-inf edges{j} inf]);\n\tn{j}=n{j}(1:end-1);\nend\n\nif (nb_c==1)\n\tn=n{1}; edges=edges{1};\nend\n\n\n% ============================== subfunctions\n\nfunction [hist_opt,step_opt]=hist1_ic(histo,nb,step_ini,m,critere);\n\n%HIST1_IC  optimal Histogram based on IC information criterion\n%\n%   [HIST_OPT, STEP_OPT] = HIST1_IC(HISTO, NB, STEP_INI, NBSTEP_INI, CRIT) \n%       fusion of an 1D histogramme (HISTO) according to an IC criterion (CRIT)\n%\n%   This function is mainly an internal function used by HIST_IC\n%\n%   Ref : O. Colot et al., Information Criteria and Abrupt Changes in\n%         Probability Laws, Signal Processing VII: Theory and Applications\n%         pp.1855-18858, September 1994\n%\n%   F. El-Matouat, O. Colot 2000 (first version)\n%   Revised 11-06-2001 by Ph. Leray\n%\n%\n%   Things to do :\n%       * Call criteron by a name ('aic','xxx', ...) instead of a number\n%\n\n\naic=[];\naic2=[];\t\n\n% Initialisation\nhistt=histo;\nteta = histt/nb;\npas = step_ini*ones(1,m);\n\n% Calcul de l'ensemble des histogrammes optimaux\n\nfor z=1:m\n\n\t% Calcul de AIC pour l'union entre hist(indice,u) et hist(indice,u+1)\n\taic2 = [aic2 cal_aic(nb,teta,pas,m+1-z,critere)];\n\n\tif (z~=m)\n\t\t% Calcul des couples de classes adjacentes \n\t\tif critere==1\t\t\t\n\t\t\tpenalite=(2*(m-z)-1)/nb;\n\t\telseif critere==2\n\t\t\tpenalite=(m-z-1)*(1+log(nb))/nb;\n\t\telse\n\t\t\tpenalite=(m-z)*(1+log(log(nb)))/nb;\n\t\tend\n \t\taic=cla_adj(nb,teta,pas,step_ini,m-z+1,histt,penalite,aic);\n\t\t% Recherche de la valeur min du crit\ufffdre pour les classes adjacentes\n\t\t[min_aic classe]=min(aic(1:(m-z)));\n\n\t\n\t\t% Fusion de hist(classe) et hist(classe+1)\n\t\tnb_pas1=pas(classe)/step_ini;\n\t\tnb_pas2=pas(classe+1)/step_ini;\n\n\t\tess=round( nb_pas1*histt(classe)+nb_pas2*histt(classe+1) );\n\t\tteta(classe)=ess / nb;\t\t\t\n\t\thistt(classe)=ess / (nb_pas1+nb_pas2);\n\t\tpas(classe)=pas(classe)+pas(classe+1);\n\n\n\t\t% Cr\ufffdation du nouvel histogramme\n\t\titemp = setdiff(1:m+1-z,classe+1);\n\t\thistt = histt(itemp);\n\t\tpas = pas(itemp);\n\t\tteta = teta(itemp);\n\tend\nend\n\n% Recherche du crit\ufffdre minimun AIC\n[min_AIC fusion]=min(aic2(1:m));\n\n% Initialisation de histo\nhistt=histo;\nteta = histt/nb;\npas = step_ini*ones(1,m);\n\n% Calcul de l'histogramme optimal\n\t\t\nfor z=1:fusion-1\n\n\t% Calcul des couples de classes adjacentes \n\tif critere==1\t\t\t\n\t\tpenalite=(2*(m-1)-1)/nb;\n\telseif critere==2\n\t\tpenalite=(m-2)*(1+log(nb))/nb;\n\telse\n\t\tpenalite=(m-1)*(1+log(log(nb)))/nb;\n\tend\n\n\taic=cla_adj(nb,teta,pas,step_ini,m,histt,penalite,aic);\n\n\n\t% Recherche de la valeur min du crit\ufffdre pour les classes adjacentes\n\t[min_aic classe]=min(aic(1:m-1));\n\t\t\t\n\t% Fusion de hist(indice,classe) et hist(indice,classe+1)\n\n\tnb_pas1=pas(classe)/step_ini;\n\tnb_pas2=pas(classe+1)/step_ini;\n\t\n\tteta(classe)=(round(nb_pas1*histt(classe)+nb_pas2*histt(classe+1)))/nb;\n\thistt(classe)=(nb_pas1*histt(classe)+nb_pas2*histt(classe+1))/(nb_pas1+nb_pas2);\n\tpas(classe)=pas(classe)+pas(classe+1);\n\n\t% Cr\ufffdation du nouvel histogramme\n\t\t\t\t\n\titemp=setdiff(1:m,classe+1);\n\thistt = histt(itemp);\n\tpas = pas(itemp);\n\tteta = teta(itemp);\n\t%aic=zeros(1,m-1);\n\t\t\t\t\n\tm=m-1;\nend\nhist_opt=histt;\nstep_opt=pas;\n\n\n%=====================================================\n% Calcul du Critere pour l'ensemble des classes\n\nfunction akaike=cal_aic(size_ech,teta,pas,m,critere);\n\n\nif critere==1\n\ta=(2*m-1)/size_ech;\nelseif critere==2\n\ta=(m-1)*(1+log(size_ech))/size_ech;\nelse\n\ta=m*(1+log(log(size_ech)))/size_ech;\nend\n\nindu = find(teta);\nakaike = a - 2*sum(teta(indu).*log(teta(indu)./pas(indu)));\n\n\n%=====================================================\n% Cla_adj.m\n% aic=cla_adj(taille,indice,teta,pas,pas_ini,m,hist,penalite,aic)\n% taille=nombre d'\ufffdl\ufffdments dans chacune des hypotheses; \n% indice=numero de la classe;\n% Calcul du critere de Akaike pour l'histogramme totale avec \n% fusion de deux classes adjacentes u et (u+1).\n\nfunction aic=cla_adj(size_ech,teta,pas,pas_ini,m,hist,penalite,aic);\n\n\nfor u=1:m-1\n\n\tcumul=0;\n\n\t% This loop is faster than a sum of a vectorised computation !\n\tfor x=1:m\t\t\t\n\t\tif x~=u & x~=u+1 & teta(x)~=0\n\t\t\tcumul=cumul+teta(x)*log(teta(x)/pas(x));\n\t\tend\t\t\t\n\tend\n\t\t\t\t\n\t\t\t\t\t\t\t\t\n\tnb_pas1=pas(u)/pas_ini;\n\tnb_pas2=pas(u+1)/pas_ini;\n\n\tb=( round(nb_pas1*hist(u)+nb_pas2*hist(u+1) ) ) / size_ech;\n\n\tif b~=0\n\t\tc=2*b*log( b / ( pas(u) + pas(u+1) ) );\n\telse\n\t\tc=0;\n\tend\n\n\taic(u)=penalite-2*cumul-c;\t\t\t\t\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/misc/hist_ic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5638776989500983}}
{"text": "%FASTHOUGHTRANSFORM  Calculates 2D Fast Hough transform of an image\n%\n%     dst = cv.FastHoughTransform(src)\n%     dst = cv.FastHoughTransform(src, 'OptionName',optionValue, ...)\n%\n% ## Input\n% * __src__ The source (input) image.\n%\n% ## Output\n% * __dst__ The destination image, result of transformation.\n%\n% ## Options\n% * __DDepth__ The depth of destination image. Default `int32`.\n% * __Op__ The operation to be applied. This specifies binary operations, that\n%   is such ones which involve two operands. Formally, a binary operation `f`\n%   on a set `S` is a binary relation that maps elements of the Cartesian\n%   product `SxS` to `S`: `f: SxS -> S`. Default 'Addition'. One of\n%   * __Minimum__ Binary minimum operation. The constant specifies the binary\n%     minimum operation `f` that is defined as follows: `f(x, y) = min(x, y)`.\n%   * __Maximum__ Binary maximum operation. The constant specifies the binary\n%     maximum operation `f` that is defined as follows: `f(x, y) = max(x, y)`.\n%   * __Addition__ Binary addition operation. The constant specifies the binary\n%     addition operation `f` that is defined as follows: `f(x, y) = x + y`.\n%   * __Average__ Binary average operation. The constant specifies the binary\n%     average operation `f` that is defined as follows: `f(x, y) = (x + y)/2`.\n% * __AngleRange__ The part of Hough space to calculate. Each member specifies\n%   primarily direction of lines (horizontal or vertical) and the direction of\n%   angle changes. Direction of angle changes is from multiples of 90 to odd\n%   multiples of 45. The image considered to be written top-down and\n%   left-to-right. Angles are started from vertical line and go clockwise.\n%   Separate quarters and halves are written in orientation they should be in\n%   full Hough space. Default `ARO_315_135`. One of:\n%   * **ARO_0_45** Vertical primarily direction and clockwise angle changes.\n%   * **ARO_45_90** Horizontal primarily direction and counterclockwise angle\n%     changes.\n%   * **ARO_90_135** Horizontal primarily direction and clockwise angle\n%     changes.\n%   * **ARO_315_0** Vertical primarily direction and counterclockwise angle\n%     changes.\n%   * **ARO_315_45** Vertical primarily direction.\n%   * **ARO_45_135** Horizontal primarily direction.\n%   * **ARO_315_135** Full set of directions.\n%   * **ARO_CTR_HOR** `90 +/- atan(0.5)`, interval approximately from `64.5`\n%     to `116.5` degrees. It is used for calculating Fast Hough Transform for\n%     images skewed by `atan(0.5)`.\n%   * **ARO_CTR_VER** `0 +/- atan(0.5)`, interval approximately from `333.5`\n%     (`-26.5`) to `26.5` degrees. It is used for calculating Fast Hough\n%     Transform for images skewed by `atan(0.5)`.\n% * __MakeSkew__ Specifies to do or not to do skewing of Hough transform\n%   image. The enum specifies to do or not to do skewing of Hough transform\n%   image so it would be no cycling in Hough transform image through borders\n%   of image. Default 'Deskew'. One of:\n%   * __Raw__ Use raw cyclic image.\n%   * __Deskew__ Prepare deskewed image.\n%\n% The function calculates the fast Hough transform for full, half or quarter\n% range of angles.\n%\n% See also: cv.HoughPoint2Line, cv.HoughLines, hough, houghlines, houghpeaks\n%\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/+cv/FastHoughTransform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.5638776921571468}}
{"text": "function s32 = i4_to_s32 ( i4 )\n\n%*****************************************************************************80\n%\n%% I4_TO_S32 converts an I4 to an S32.\n%\n%  Discussion:\n%\n%    An I4 is a 32 bit integer.\n%\n%    An S32 is a 32 character string.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    11 June 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer I4, the integer to be coded.\n%\n%    Output, string S32, the string.\n%\n  s32 = [];\n\n  i4_copy = abs ( i4 );\n%\n%  Binary digits:\n%\n  for i = 32 : -1 : 2\n\n    if ( mod ( i4_copy, i4_two ) == 1 )\n      s32 = strcat ( '1', s32 );\n    else\n      s32 = strcat ( '0', s32 );\n    end\n\n    i4_copy = floor ( i4_copy / 2 );\n\n  end\n%\n%  Sign bit\n%\n  s32 = strcat ( '0', s32 );\n%\n%  If original number was negative, then reverse all bits.\n%\n  if ( i4 < 0 )\n    for i = 1 : 32\n      if ( s32(i) == '0' )\n        s32(i) = '1';\n      else\n        s32(i) = '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/chrpak/i4_to_s32.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.5638776868025713}}
{"text": "function bpab_test ( )\n\n%*****************************************************************************80\n%\n%% BPAB_TEST tests BPAB.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    19 October 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 10;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'BPAB_TEST\\n' );\n  fprintf ( 1, '  BPAB evaluates Bernstein polynomials.\\n' );\n  fprintf ( 1, '\\n' );\n\n  x = 0.3;\n  a = 0.0;\n  b = 1.0;\n  bern = bpab ( n, x, a, b );\n \n  fprintf ( 1, '  The Bernstein polynomials of degree %d\\n', n );\n  fprintf ( 1, '  based on the interval from %f\\n', a );\n  fprintf ( 1, '  to %f\\n', b );\n  fprintf ( 1, '  evaluated at X = %f\\n', x );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '   I        Bern(I,X)\\n' );\n  fprintf ( 1, '\\n' );\n  \n  for i = 0 : n\n    fprintf ( 1, '  %2d  %12f\\n', i, bern(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/bpab_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.5638776868025712}}
{"text": "function days = month_length_common ( y, m )\n\n%*****************************************************************************80\n%\n%% MONTH_LENGTH_COMMON returns the number of days in a Common month.\n%\n%  Discussion:\n%\n%    The \"common\" calendar is meant to be the calendar which is Julian up to\n%    day JED = 2299160, and Gregorian from day JED = 2299161 and after.\n%\n%    The routine knows that February has 28 days, except in leap years,\n%    when it has 29.\n%\n%    In the Common calendar, October 1582 had only 21 days\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 June 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer Y, the year in which the month occurred.\n%\n%    Input, integer M, the number of the month.\n%\n%    Output, integer DAYS, the number of days\n%    in the month.\n%\n  mdays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];\n%\n%  Check the input.\n%\n  [ y2, m2, ierror ] = ym_check_common ( y, m );\n\n  if ( ierror ~= 0 )\n    days = 0;\n    return\n  end\n%\n%  Take care of the special case.\n%\n  if ( y2 == 1582 )\n    if ( m2 == 10 )\n      days = 21;\n      return\n    end\n  end\n%\n%  Get the number of days in the month.\n%\n  days = mdays(m2);\n%\n%  If necessary, add 1 day for February 29.\n%\n  if ( m2 == 2 && year_is_leap_common ( y2 ) )\n    days = days + 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/month_length_common.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5638776868025711}}
{"text": "% VL_LBP  Local Binary Patterns\n%   F = VL_LBP(IM, CELLSIZE) computes the Local Binary Pattern (LBP)\n%   features for image I.\n%\n%   IM is divided in cells of size CELLSIZE. F is a three-dimensional\n%   array containing one histograms of quantized LBP features per\n%   cell. The witdh of F is FLOOR(WIDTH/CELLSIZE), where WIDTH is the\n%   width of the image. The same for the height. The third dimension\n%   is 58.\n%\n%   See also: <a href=\"matlab:vl_help('lbp')\">LBP</a>, VL_LBPFLIPLR(),\n%   VL_HELP().\n\n% Copyright (C) 2013 Andrea Vedaldi.\n% Copyright (C) 2010-11 Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n", "meta": {"author": "yihui-he", "repo": "panorama", "sha": "0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b", "save_path": "github-repos/MATLAB/yihui-he-panorama", "path": "github-repos/MATLAB/yihui-he-panorama/panorama-0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b/lib/vlfeat-0.9.20/toolbox/misc/vl_lbp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833737577159, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5638776837977155}}
{"text": "function CrowdDis = CrowdingDistance(PopObj,FrontNo)\n%CrowdingDistance - Calculate the crowding distances of solutions front\n%by front.\n%\n%   CD = CrowdingDistance(F) calculates the crowding distances of solutions\n%   according to their objective values in F.\n%\n%   CD = CrowdingDistance(F,FrontNo) calculates the crowding distances of\n%   solutions in each non-dominated front, where FrontNo is the front\n%   numbers of solutions.\n%\n%   Example:\n%       CrowdDis = CrowdingDistance(PopObj,FrontNo)\n\n%------------------------------- Reference --------------------------------\n% S. Kukkonen and K. Deb, Improved pruning of non-dominated solutions based\n% on crowding distance for bi-objective optimization problems, Proceedings\n% of the IEEE Congress on Evolutionary Computation, 2006, 1179-1186.\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    [N,M] = size(PopObj);\n    if nargin < 2\n        FrontNo = ones(1,N);\n    end\n    CrowdDis = zeros(1,N);\n    Fronts   = setdiff(unique(FrontNo),inf);\n    for f = 1 : length(Fronts)\n        Front = find(FrontNo==Fronts(f));\n        Fmax  = max(PopObj(Front,:),[],1);\n        Fmin  = min(PopObj(Front,:),[],1);\n        for i = 1 : M\n            [~,Rank] = sortrows(PopObj(Front,i));\n            CrowdDis(Front(Rank(1)))   = inf;\n            CrowdDis(Front(Rank(end))) = inf;\n            for j = 2 : length(Front)-1\n                CrowdDis(Front(Rank(j))) = CrowdDis(Front(Rank(j)))+(PopObj(Front(Rank(j+1)),i)-PopObj(Front(Rank(j-1)),i))/(Fmax(i)-Fmin(i));\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/Algorithms/Utility functions/CrowdingDistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.5638776822312355}}
{"text": "%FIGURE_Critical_Angle\n\nMoI = logspace(-3,0,100);\nMu = [0,0.05,0.1,0.5,1,5,10,inf];\nP.m = 1;\nP.g = 1;\nP.L = 1;\n\nData = cell(length(Mu),0);\nfor i=1:length(Mu)\n    Data(i).idxF = false(size(MoI));\n    Data(i).idxB = false(size(MoI));\n    Data(i).fail = false(size(MoI));\n    Data(i).th = zeros(size(MoI));\n    P.u = Mu(i);\n    disp(['Running u = ' num2str(P.u)]);\n    for j=1:length(MoI)\n        P.I = MoI(j);\n        C = ToppleFromRest(P);\n        if ~isempty(C.th)\n            if strcmp(C.exit,'SlipForwards')\n               Data(i).idxF(j) = true; \n            elseif strcmp(C.exit,'SlipBackwards')\n                Data(i).idxB(j) = true;\n            end\n            Data(i).th(j) = C.th;\n        else\n            Data(i).fail(j) = true; \n        end\n    end\nend\n\nstyle = {'k--','b--','r--','m--','g--',...\n    'k-','b-','r-','m-','g-'...\n    'k:','b:','r:','m:','g:'};\nLINEWIDTH = 3;\nFontSize.Title = 16;\nFontSize.label = 12;\nnames = cell(1,length(Mu));\nfor i=1:length(Mu)\n    names{i} = num2str(['u = ' num2str(Mu(i))]);\nend\n\nfigH = figure(400); clf;\nset(figH,'Name','CriticalAngleLim','NumberTitle','off')\nIDX = false(2,length(Mu));\nfor i=1:length(Mu)\n    sty = style{mod(i-1,length(style))+1};\n    idx = Data(i).idxB;  IDX(1,i) = sum(idx)~=0;\n    subplot(2,1,1);  hold on;\n    semilogx(MoI(idx),Data(i).th(idx)*180/pi,sty,'LineWidth',LINEWIDTH);\n    idx = Data(i).idxF;  IDX(2,i) = sum(idx)~=0;\n    subplot(2,1,2);  hold on;\n    semilogx(MoI(idx),Data(i).th(idx)*180/pi,sty,'LineWidth',LINEWIDTH);\nend\n\nsubplot(2,1,1); \n title('Backwards Slip (falling forward)','FontSize',FontSize.Title)\n    xlabel('Moment of Inertia','FontSize',FontSize.label)\n    ylabel('Critical Angle (deg)','FontSize',FontSize.label)\n    legend(names(IDX(1,:)),'Location','NorthEast');\n    set(gca,'Xscale','log')\n    \n    subplot(2,1,2); \n title('Forwards Slip (falling forward)','FontSize',FontSize.Title)\n    xlabel('Moment of Inertia','FontSize',FontSize.label)\n    ylabel('Critical Angle (deg)','FontSize',FontSize.label)\n    legend(names(IDX(2,:)),'Location','NorthWest');\n    set(gca,'Xscale','log')\n\nsave('DATA_Critical_Fall.mat','Data');\nsave2pdf('../WriteUp/Figures/Critical_Fall.pdf',figH,600);\n\n\n%Later on, compute the acceleration of the tip at the onset of sliding.\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/toppling_stick/FIGURE_Critical_Angle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.563877674655044}}
{"text": "function test_sep\n%TEST_SEP test cs_sep, and compare with Gilbert's meshpart vtxsep\n% (requires MESHPART).\n%\n% Example:\n%   test_sep\n%\n% See also: testall\n\n%   Copyright 2006-2007, Timothy A. Davis.\n%   http://www.cise.ufl.edu/research/sparse\n\n\nclear functions\n\nindex = UFget ;\n[ignore f] = sort (max (index.nrows, index.ncols)) ;\n\nclf\n\nfor k = 1:length(f)\n    \n    i = f (k) ;\n    Prob = UFget (i) ;\n    disp (Prob) ;\n    A = spones (Prob.A) ;\n    [m n] = size (A) ;\n    if (m ~= n)\n        A = A'*A ;\n    end\n\n    A = A|A' ;\n\n    p = symrcm (A) ;\n\n    n = size (A,1) ;\n    n2 = fix (n/2) ;\n    a = p (1:n2) ;\n    b = p ((n2+1):n) ;\n\n    clf\n\n    subplot (2,3,1) ; spy (A) ;\n    subplot (2,3,2) ; spy (A (p,p)) ;\n\n    hold on\n    plot ([.5 n2+.5 n2+.5 .5 .5], [.5 .5 n2+.5 n2+.5 .5], 'r', 'LineWidth', 2) ;\n    hold off\n\n    subplot (2,3,3) ; spy (A (a,b)) ; title ('edge sep') ;\n    subplot (2,3,6) ; cs_dmspy (A (a,b)) ; title ('node sep') ;\n\n    [s as bs] = vtxsep (A,a,b) ;                                        %#ok\n    [s2 a2 b2] = cs_sep (A,a,b) ;\n\n    p2 = [a2 b2 s2] ;\n    B = A (p2,p2) ;\n    subplot (2,3,5) ; spy (B) ;\n    hold on\n\n    px = [s2 a2 b2] ;\n    if (any (sort (px) ~= 1:n))\n        px      %#ok\n        n       %#ok\n        error ('!') ;\n    end\n\n    na = length (a2) ;\n    nb = length (b2) ;\n    ns = length (s2) ;                                                  %#ok\n\n    nab = na + nb ;\n\n    plot ([.5 na+.5 na+.5 .5 .5], [.5 .5 na+.5 na+.5 .5], 'r', 'LineWidth', 2) ;\n\n    plot ([na nab nab na na]+0.5, [na na nab nab na]+0.5, 'r', 'LineWidth', 2) ;\n\n    plot ([.5 nab+.5 nab+.5 .5 .5], [.5 .5 nab+.5 nab+.5 .5], 'g', 'LineWidth', 1) ;\n\n    hold off\n\n    nz1 = nnz (A (a2,b2)) ;\n    if (nz1 ~= 0)\n        nz1     %#ok\n        error ('!') ;\n    end\n\n    nz2 = nnz (A (a2,b2)) ;\n    if (nz2 ~= 0)\n        nz2     %#ok\n        error ('!') ;\n    end\n\n    if (length (s) ~= length (s2))\n        fprintf ('lengths differ: %d %d\\n', length (s), length (s2)) ;\n    end\n\n    drawnow\n    % pause\n\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/SuiteSparse/CXSparse/MATLAB/Test/test_sep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5637048915146801}}
{"text": "function [ less, equal, more ] = r8r8r8vec_index_search ( n, x, y, z, ...\n  indx, xval, yval, zval )\n\n%*****************************************************************************80\n%\n%% R8R8R8VEC_INDEX_SEARCH searches for an R8R8R8 value in an indexed sorted list.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 May 2005\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the size of the current list.\n%\n%    Input, real X(N), Y(N), Z(N), the list.\n%\n%    Input, integer INDX(N), the sort index of the list.\n%\n%    Input, real XVAL, YVAL, ZVAL, the value to be sought.\n%\n%    Output, integer LESS, EQUAL, MORE, the indexes in INDX of the\n%    entries of X that are just less than, equal to, and just greater\n%    than XVAL.  If XVAL does not occur in X, then EQUAL is zero.\n%    If XVAL is the minimum entry of X, then LESS is 0.  If XVAL\n%    is the greatest entry of X, then MORE is N+1.\n%\n  if ( n <= 0 )\n    less = 0;\n    equal = 0;\n    more = 0;\n    return\n  end\n\n  lo = 1;\n  hi = n;\n\n  xlo = x(indx(lo));\n  ylo = y(indx(lo));\n  zlo = z(indx(lo));\n\n  xhi = x(indx(hi));\n  yhi = y(indx(hi));\n  zhi = z(indx(hi));\n\n  compare = r8r8r8_compare ( xval, yval, zval, xlo, ylo, zlo );\n\n  if ( compare == -1 )\n    less = 0;\n    equal = 0;\n    more = 1;\n    return\n  elseif ( compare == 0 )\n    less = 0;\n    equal = 1;\n    more = 2;\n    return\n  end \n\n  compare = r8r8r8_compare ( xval, yval, zval, xhi, yhi, zhi );\n\n  if ( compare == 1 )\n    less = n;\n    equal = 0;\n    more = n + 1;\n    return\n  elseif ( compare == 0 )\n    less = n - 1;\n    equal = n;\n    more = n + 1;\n    return\n  end \n\n  while ( 1 )\n\n    if ( lo + 1 == hi )\n      less = lo;\n      equal = 0;\n      more = hi;\n      return\n    end\n\n    mid = round ( ( lo + hi ) / 2 );\n    xmid = x(indx(mid));\n    ymid = y(indx(mid));\n    zmid = z(indx(mid));\n\n    compare = r8r8r8_compare ( xval, yval, zval, xmid, ymid, zmid );\n\n    if ( compare == 0 )\n      equal = mid;\n      less = equal - 1;\n      more = equal + 1;\n      return\n    elseif ( compare == -1 )\n      hi = mid;\n    elseif ( compare == +1 )\n      lo = mid;\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/r8r8r8vec_index_search.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.5637048772638984}}
{"text": "function order = strong_elim_order(G, node_sizes, partial_order)\n% STRONG_ELIM_ORDER Find an elimination order to produce a strongly triangulated graph.\n% order = strong_elim_order(moral_graph, node_sizes, partial_order)\n% \n% partial_order(i,j)=1 if we must marginalize i *after* j\n% (so i will be nearer the strong root).\n% e.g., if j is a decision node and i is its information set:\n%   we cannot maximize j if we have marginalized out some of i\n% e.g., if j is a continuous child and i is its discrete parent:\n%   we want to integrate out the cts nodes before the discrete ones,\n%   so that the marginal is strong.\n%\n% For details, see\n% - Jensen, Jensen and Dittmer, \"From influence diagrams to junction trees\", UAI 94.\n% - Lauritzen, \"Propgation of probabilities, means, and variances in mixed graphical\n%   association models\", JASA 87(420):1098--1108, 1992.\n%\n% On p369 of the Jensen paper, they state \"the reverse of the elimination order must be some\n% extension of [the partial order] to a total order\".\n% We make no attempt to find the best such total ordering, in the sense of minimizing the weight\n% of the resulting cliques.\n\n% Example from the Jensen paper:\n% Let us number the nodes in Fig 1 from top to bottom, left to right,\n% so a=1,b=2,D1=3,c=4,...,l=14,j=15,k=16.\n% The elimination ordering they propose on p370 is [14 15 16 11 12 1 4 5 10 8 13 9 7 6 3 2];\n\nif 0\n  total_order = topological_sort(partial_order);\n  order = total_order(end:-1:1); % no attempt to find an optimal constrained ordering!\n  return;\nend\n\n% The following implementation is due to Ilya Shpitser and seems to give wrong\n% results on cg1\n\nn = length(G);\nMG = G; % copy the original graph\nuneliminated = ones(1,n);\norder = zeros(1,n);\n\nfor i=1:n\n  roots = [];\n  k = 1;\n  for j=1:n\n    if sum(partial_order(j,:)) == 0\n      roots(k) = j;\n      k = k + 1;\n    end\n  end\n  U = find(uneliminated);\n  valid = myintersect(U, roots);\n  % Choose the best node from the set of valid candidates\n  score1 = zeros(1,length(valid));\n  score2 = zeros(1,length(valid));\n  for j=1:length(valid)\n    k = valid(j);\n    ns = myintersect(neighbors(G, k), U);\n    l = length(ns);\n    M = MG(ns,ns);\n    score1(j) = l^2 - sum(M(:)); % num. added edges\n    score2(j) = prod(node_sizes([k ns])); % weight of clique\n  end\n  j1s = find(score1==min(score1));\n  j = j1s(argmin(score2(j1s)));\n  k = valid(j);\n  uneliminated(k) = 0;\n  order(i) = k;\n  ns = myintersect(neighbors(G, k), U);\n  if ~isempty(ns)\n    G(ns,ns) = 1;\n    G = setdiag(G,0);\n  end\n  partial_order(:,k) = 0;\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/graph/strong_elim_order.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5637048748276978}}
{"text": "function [dataout] = mmse_det(ch_and_rx)\n% mmse_det  User-defined function for MMSE detector.\n% Input: 'ch_and_rx'\n%    - first elements are MIMO parameters (STBC, Nss, etc.)\n%    - next 16*NST elements are channel estimates.\n%    - next (NSTS+1)*NST elements are reference training symbols.\n%    - next (NSTS+1)*NST elements are received training symbols.\n%    - remaining x*NST elements are received data symbols.\n% Output: 'detout'\n%    - x*NST elements are MMSE detector outputs.\n%    - x*NST elements are Viterbi metric weights.\nglobal PER_snr snr_idx ch_type;\n\n% Initialize vectors\nClk = ch_and_rx(1);\nSTBC = ch_and_rx(2);\nNss  = ch_and_rx(3);\nNsts = Nss + STBC;\nNltf = Nsts;\nif (Nsts==3) % use 4 TRN symbols for NSTS=3\n   Nltf = 4;\nend\n\nNrx  = ch_and_rx(4);\nch_est  = ch_and_rx(4+(1:16*56));\nref_trn = ch_and_rx(4+16*56+(1:4*56*(Nltf)));\nrx_trn  = ch_and_rx(4+16*56+4*56*(Nltf)+(1:4*56*(Nltf)));\nrx_data = ch_and_rx((5+16*56+2*4*56*(Nltf)):end);\n\n%%%% Form channel matrix\nidx = 0;\nH = zeros(4,4,56);\nfor c=1:4\n    for r=1:4\n        H(r,c,:) = ch_est(idx+(1:56));\n        idx=idx+56;\n    end\nend\nH = H(1:Nrx,1:Nsts,:);  %% channel matrix is Nrx x Nsts\n\n%%%% Train data symbols...\nidx = 0;\nnsymtrn = (length(ref_trn)/4/56);\ntrnRef = zeros(Nrx,56,nsymtrn);\nfor n=1:nsymtrn\n    for m=1:Nsts\n        trnRef(m,:,n) = ref_trn(idx+(m-1)*56+(1:56));\n        trnRx(m,:,n)  =  rx_trn(idx+(m-1)*56+(1:56));\n    end\n    idx=idx+4*56;\nend\n\n%%%% Rx data symbols...\nidx = 0;\nnsymdata = (length(rx_data)/4/56);\nrdata = zeros(4,56,nsymdata);\nfor n=1:nsymdata\n    for m=1:Nrx\n        rdata(m,:,n) = rx_data(idx+(m-1)*56+(1:56));\n    end\n    idx=idx+4*56;\nend\n\n%%%%\n%%%% STBC or MMSE detection...\n%%%%\nif (STBC)    \n    %%%% Form space-time decoding matrices\n    for k=1:56\n        if (STBC==1 && Nss==1)\n            % Heff matrix (assumes channel stationary for 2 symbols)\n            Heff(:,:,k) = [      H(1,1,k)      -H(1,2,k); ...  \n                            conj(H(1,2,k)) conj(H(1,1,k)) ];  \n        elseif (STBC==1 && Nss==2)\n            % Heff matrix (assumes channel stationary for 2 symbols)\n            Heff(:,:,k) = [      H(1,1,k)      -H(1,2,k)       H(1,3,k)              0;  ...  \n                            conj(H(1,2,k)) conj(H(1,1,k))             0  conj(H(1,3,k)); ...  \n                                 H(2,1,k)      -H(2,2,k)       H(2,3,k)              0;  ...\n                            conj(H(2,2,k)) conj(H(2,1,k))             0  conj(H(2,3,k)) ];  \n        elseif (STBC==1 && Nss==3)\n            % Heff matrix (assumes channel stationary for 2 symbols)\n            Heff(:,:,k) = [      H(1,1,k)      -H(1,2,k)       H(1,3,k)              0        H(1,4,k)              0;  ...  \n                            conj(H(1,2,k)) conj(H(1,1,k))             0  conj(H(1,3,k))              0  conj(H(1,4,k)); ...  \n                                 H(2,1,k)      -H(2,2,k)       H(2,3,k)              0        H(2,4,k)              0;  ...\n                            conj(H(2,2,k)) conj(H(2,1,k))             0  conj(H(2,3,k))              0  conj(H(2,4,k)); ...  \n                                 H(3,1,k)      -H(3,2,k)       H(3,3,k)              0        H(3,4,k)              0;  ...\n                            conj(H(3,2,k)) conj(H(3,1,k))             0  conj(H(3,3,k))              0  conj(H(3,4,k)) ];  \n        elseif (STBC==2 && Nss==2)\n            % Heff matrix (assumes channel stationary for 2 symbols)\n            Heff(:,:,k) = [      H(1,1,k)      -H(1,2,k)       H(1,3,k)      -H(1,4,k);  ...  \n                            conj(H(1,2,k)) conj(H(1,1,k)) conj(H(1,4,k)) conj(H(1,3,k)); ...\n                                 H(2,1,k)      -H(2,2,k)       H(2,3,k)      -H(2,4,k);  ...\n                            conj(H(2,2,k)) conj(H(2,1,k)) conj(H(2,4,k)) conj(H(2,3,k)) ];  \n        end\n    end\n\n    %%%% Compute noise power...\n    N_o = 0;\n    for k=1:56\n        He = Heff(:,:,k);\n        N_o = N_o + (1/56)*sum(sum(He.*conj(He)))/Nrx;     % Signal power\n    end\n    snr_val = PER_snr(snr_idx);\n    N_o = N_o * 10^(-snr_val/10);     % Adjust by SNR\n    \n    %%%% Compute space-time detector coeff's\n    C = zeros(Nss*2,Nss*2,56);\n    for k=1:56\n        %%%% MMSE coeff's\n        He = Heff(:,:,k);\n        C(:,:,k) = inv(He'*He + N_o*eye(Nss*2))*He';\n    end\n    \n    %%%% Compute space-time decoding outputs, Viterbi metric weights\n    idx = 0;\n    detout = zeros(4*56*nsymdata,1);\n    metout = zeros(4*56*nsymdata,1);\n    for n=1:2:nsymdata\n        for k=1:56\n            if (STBC==1 && Nss==1)\n                % MMSE detector outputs\n                detset = C(:,:,k) * [ rdata(1,k,n); ...\n                                      conj(rdata(1,k,n+1)) ];\n                detout(k+idx+0*56) = detset(1);         % first symbol in time, ss1\n                detout(k+idx+4*56) = conj(detset(2));   % second symbol in time, ss1\n                % Viterbi metric weights\n                metset = eps+abs(1-diag(C(:,:,k)*Heff(:,:,k)));\n                metout(k+idx+0*56) = 1/metset(1);\n                metout(k+idx+4*56) = 1/metset(2);\n            elseif (STBC==1 && Nss==2)\n                % MMSE detector outputs\n                detset = C(:,:,k) * [ rdata(1,k,n); ...\n                                      conj(rdata(1,k,n+1)); ...\n                                      rdata(2,k,n); ...\n                                      conj(rdata(2,k,n+1)) ];\n                detout(k+idx+0*56) = detset(1);         % first symbol in time, ss1\n                detout(k+idx+4*56) = conj(detset(2));   % second symbol in time, ss1\n                detout(k+idx+1*56) = detset(3);         % first symbol in time, ss2\n                detout(k+idx+5*56) = conj(detset(4));   % second symbol in time, ss2\n                % Viterbi metric weights\n                metset = eps+abs(1-diag(C(:,:,k)*Heff(:,:,k)));\n                metout(k+idx+0*56) = 1/metset(1);\n                metout(k+idx+4*56) = 1/metset(2);\n                metout(k+idx+1*56) = 1/metset(3);\n                metout(k+idx+5*56) = 1/metset(4);\n            elseif (STBC==1 && Nss==3)\n                % MMSE detector outputs\n                detset = C(:,:,k) * [ rdata(1,k,n); ...\n                                      conj(rdata(1,k,n+1)); ...\n                                      rdata(2,k,n); ...\n                                      conj(rdata(2,k,n+1)); ...\n                                      rdata(3,k,n); ...\n                                      conj(rdata(3,k,n+1)) ];\n                detout(k+idx+0*56) = detset(1);         % first symbol in time, ss1\n                detout(k+idx+4*56) = conj(detset(2));   % second symbol in time, ss1\n                detout(k+idx+1*56) = detset(3);         % first symbol in time, ss2\n                detout(k+idx+5*56) = conj(detset(4));   % second symbol in time, ss2\n                detout(k+idx+2*56) = detset(5);         % first symbol in time, ss3\n                detout(k+idx+6*56) = conj(detset(6));   % second symbol in time, ss3\n                % Viterbi metric weights\n                metset = eps+abs(1-diag(C(:,:,k)*Heff(:,:,k)));\n                metout(k+idx+0*56) = 1/metset(1);\n                metout(k+idx+4*56) = 1/metset(2);\n                metout(k+idx+1*56) = 1/metset(3);\n                metout(k+idx+5*56) = 1/metset(4);\n                metout(k+idx+2*56) = 1/metset(5);\n                metout(k+idx+6*56) = 1/metset(6);\n            elseif (STBC==2 && Nss==2)\n                % MMSE detector outputs\n                detset = C(:,:,k) * [ rdata(1,k,n); ...\n                                      conj(rdata(1,k,n+1)); ...\n                                      rdata(2,k,n); ...\n                                      conj(rdata(2,k,n+1)) ];\n                detout(k+idx+0*56) = detset(1);         % first symbol in time, ss1\n                detout(k+idx+4*56) = conj(detset(2));   % second symbol in time, ss1\n                detout(k+idx+1*56) = detset(3);         % first symbol in time, ss2\n                detout(k+idx+5*56) = conj(detset(4));   % second symbol in time, ss2\n                % Viterbi metric weights\n                metset = eps+abs(1-diag(C(:,:,k)*Heff(:,:,k)));\n                metout(k+idx+0*56) = 1/metset(1);\n                metout(k+idx+4*56) = 1/metset(2);\n                metout(k+idx+1*56) = 1/metset(3);\n                metout(k+idx+5*56) = 1/metset(4);\n            end\n        end\n        idx=idx+8*56;\n    end\n\nelse\n\n    %%%% Compute noise power...\n    N_o = 0;\n    for k=1:56\n        He = H(:,:,k);\n        N_o = N_o + (1/56)*sum(sum(He.*conj(He)))/Nrx;     % Signal power\n    end\n    snr_val = PER_snr(snr_idx);\n    N_o = N_o * 10^(-snr_val/10);     % Adjust by SNR\n    \n    %%%%% MMSE linear detector (no STBC)\n    C = zeros(Nsts,Nrx,56);\n    for k=1:56\n        %%%% MMSE coeff's\n        He = H(:,:,k);\n        C(:,:,k) = inv(He'*He + N_o*eye(Nrx)) * He';        \n    end\n\n    %%%% MMSE detector outputs, Viterbi metric weights\n    idx = 0;\n    detset = zeros(4,1);\n    detout = zeros(4*56*nsymdata,1);\n    metset = eps+zeros(4,1);\n    metout = zeros(4*56*nsymdata,1);\n    for n=1:nsymdata\n        for k=1:56\n            % MMSE detector outputs\n            detset(1:Nsts) = C(:,:,k)*rdata(1:Nrx,k,n);\n            detout(k+idx+0*56) = detset(1);\n            detout(k+idx+1*56) = detset(2);\n            detout(k+idx+2*56) = detset(3);\n            detout(k+idx+3*56) = detset(4);\n            % Viterbi metric weights\n            metset(1:Nsts) = eps+abs(1-diag(C(:,:,k)*H(:,:,k)));\n            metout(k+idx+0*56) = 1/metset(1);\n            metout(k+idx+1*56) = 1/metset(2);\n            metout(k+idx+2*56) = 1/metset(3);\n            metout(k+idx+3*56) = 1/metset(4);\n        end\n        idx=idx+4*56;\n    end\n    \nend\n\n% Adjust metric scaling range (0 - least confident, 7 - most confident)\n% (based on use of 4-bit data, soft decisions, for Viterbi module) \nmax_metout = max(metout(find(metout<1e14)));\nlog_metout = log(metout + 1e-6);\nlog_max_metout = log(max_metout + 1e-6);\nmetout = floor(7.99 * log_metout/log_max_metout);\nmetout = (metout >= 7).*7 + (metout < 7).*metout;\n\n\n% MMSE module output\ndataout = [detout; metout];\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26232-ieee-802-11n-wlan-file-update/w11n_jointprop/wlan/mmse_det.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029117, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5635679220037211}}
{"text": "function pde = Helmholtzdata3\n%% HELMHOTLZDATA4 trigonometric  data for PML Helmholtz equation\n% -laplace u -k^2 u = f;\n% The Intresting domain is [0,1]^2; The computing domain including the PML\n%domain is [-0.1,1.1]^2;\n% boundary condition\n% u =0 on the PML boundary; \n% Created by Jie Zhou.\n% The data come from\n% Advances in Iterative Methods and Preconditioners for the Helmholtz Equation\n% Copyright (C)  Long Chen. See COPYRIGHT.txt for details.\n\npde = struct('f',@f,'k2',@k2,'g_D',@g_D,'d',@d);\n\n    % load data (right hand side function)\n    function rhs =  f(p)\n\n      x = p(:,1); y = p(:,2);\n     k0 = size(p,1);\n    rhs = zeros(k0,1);\n     ii = find(abs(x-0.5)<=1.0e-2&abs(y-0.5)<=1.0e-2);\n    rhs(ii) = 10000;\n    end\n\n\n\n    function PMLp = d(p)\n    global omegal k  c\n    c = 340;\n    omegal = k*340;\n          i = sqrt(-1);\n          x = p(:,1); y = p(:,2);\n      size0 = size(x,1);\n     sigma1 = ones(size0,1);\n     sigma2 = ones(size0,1);\n    index = find((x<0)|(x>1)|(y>1)|(y<0)); \n    sigma1(index) = x(index);\n    sigma2(index) = y(index);\n    \n    s1 = 1 + sigma1/((i)*omegal);\n    s2 = 1 + sigma2/((i)*omegal);\n    \n    PMLp = [s2./s1 s1./s2];\n    end\n    function s =  g_D(p)\n    s = zeros(size(p,1),1);\n    end\n    function wavenumber = k2(p)\n    global k omegal  c\n    omegal = k*340;\n          i = sqrt(-1);\n          x = p(:,1); y = p(:,2);\n      size0 = size(x,1);\n     sigma1 = ones(size0,1);\n     sigma2 = ones(size0,1);\n    index = find((x<0)|(x>1)|(y>1)|(y<0)); \n    sigma1(index) = x(index);\n    sigma2(index) = y(index);\n    \n    s1 = 1 + sigma1/((i)*omegal);\n    s2 = 1 + sigma2/((i)*omegal);\n    wavenumber = k.^2.*s1.*s2;\n    end\n\n\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/data/Helmholtzdata3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5635679152127809}}
{"text": "function h = max2(f, g, dims)\n%MAX2   Maximum value of a CHEBFUN3 in two directions.\n%   MAX2(F) returns a 1D CHEBFUN representing the maximum of the CHEBFUN3 \n%   object F along the y and z directions, i.e, \n%                                          MAX2(F) = @(z) max(F( :, :, z)).\n%\n%   MAX2(F, [], dims) returns a CHEBFUN representing the maximum of F along\n%   the dimensions DIMS, where DIMS = [1, 2] means along the x and y \n%   directions, etc.\n%\n%   WARNING: This function is not always accurate to the expected precision.\n% \n%   For the global maximum use MAX3.\n%\n% See also CHEBFUN3/MAX and CHEBFUN3/MAX3.\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    error('CHEBFUN:CHEBFUN3:max2:input', 'CHEBFUN3 is empty');\nend\n\n% Default to max2 of one chebfun3:\nif ( nargin < 2 )\n    g = []; \nend\n\n% Default to maximum along the x and y directions:\nif ( nargin < 3 )\n    dims = [1, 2];\nend\n\n% Do not allow max(F, G): \nif ( nargin > 1 && ~isempty(g) )\n    error('CHEBFUN:CHEBFUN3:max2:twoCHEBFUN3Inputs', ...\n        'Unable to maximize two CHEBFUN3 objects.');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% We have no idea how to achieve this in an efficient way. This\n% is an attempt to return a result, but typically it won't be accurate to \n% more than 4-5 digits. \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ndom = f.domain;\nn = 129;\nif ( all(dims == [1, 2]) || all(dims == [2, 1]) )\n    vals = sample(f, n, n, n);\n    temp = chebfun3.unfold(vals, [3]);\n    h = chebfun(max(temp, [], 2), dom(5:6), 'splitting', 'on');\n    h = simplify(h);\nelseif ( all(dims == [1, 3]) || all(dims == [3, 1]) )\n    vals = sample(f, n, n, n);\n    temp = chebfun3.unfold(vals, [2]);\n    h = chebfun(max(temp, [], 2), dom(3:4), 'splitting', 'on');\n    h = simplify(h);\nelseif ( all(dims == [2, 3]) || all(dims == [3, 2]) )\n    vals = sample(f, n, n, n);  \n    temp = chebfun3.unfold(vals, [1]);\n    h = chebfun(max(temp, [], 2), dom(1:2), 'splitting', 'on');\n    h = simplify(h);\nelseif ( dims == 0 )\n    error('CHEBFUN:CHEBFUN3:max2:dims', ...\n        'Dimension arguments must be two positive integer scalars within indexing range.')\nelse\n   % return the CHEBFUN3. This is analogous to that MAX() command in\n   % MATLAB.\n   h = 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/@chebfun3/max2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5635586847085012}}
{"text": "function [f,s] = is_planar(V,epsilon)\n  % IS_PLANAR Return whether the 3D mesh is planar\n  % \n  % [f,s] = is_planar(V)\n  % [f,s] = is_planar(V,epsilon)\n  %\n  % Inputs:\n  %   V  #V x 3 matrix of vertex coordinates\n  %   epsilon  optional parameter used as threshold for smallest eigen value of\n  %     pca, {1e-10}\n  % Outputs:\n  %   f  flag whether mesh is planar\n  %   s  smallest principle component variance\n  %\n  %\n\n\n  if ~exist('epsilon','var')\n    epsilon = 1e-10;\n  end\n\n\n  if size(V,2) == 2 \n    f = true;\n    s = 0;\n    return;\n  end\n\n  % This seems to have changed during matlab. For large V this is\n  % infeasible.\n  [c,l] = pcacov(V);\n\n  s = min(l);\n\n\n  f = s < epsilon;\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/is_planar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5635586733624743}}
{"text": "function ll = robOneDynamicsLogLikelihood(model)\n\n% ROBONEDYNAMICSLOGLIKELIHOOD Give the log likelihood of the robot one dynamics part.\n\n% FGPLVM\n\nthetaDiff = model.theta(2:end)-model.theta(1:end-1);\nwhile any(thetaDiff>pi)\n  ind = find(thetaDiff>pi);\n  thetaDiff(ind) = thetaDiff(ind) - 2*pi;\nend\nwhile any(thetaDiff<-pi)\n  ind = find(thetaDiff<-pi);\n  thetaDiff(ind) = thetaDiff(ind) + 2*pi;\nend\n\nlogLikeTheta = log(2*pi*model.sigma2)...\n    +(thetaDiff.*thetaDiff)/model.sigma2;\nlikeTheta = exp(-0.5*logLikeTheta)*model.mixTheta;\nlikeTheta = likeTheta + (1-model.mixTheta)/(2*pi);\nll = sum(log(likeTheta));\n\n\nlogLikeR1 = model.a*log(model.b) - gammaln(model.a) ...\n    +(model.a-1)*log(model.r) - model.b*model.r + log(model.mixR);\nlogLikeR2 = log(model.b) - model.b*model.r + log(1-model.mixR);\n\nlogLikeR1(find(logLikeR1<-316))=-316;\nlogLikeR2(find(logLikeR2<-316))=-316;\n\nind = find(logLikeR1>logLikeR2);\nlogLikeR(ind) = log(1+exp(logLikeR2(ind))./exp(logLikeR1(ind)))+logLikeR1(ind);\n\nind2 = find(logLikeR1<=logLikeR2);\nlogLikeR(ind2) = log(1+exp(logLikeR1(ind2))./exp(logLikeR2(ind2)))+logLikeR2(ind2);\n\nll = ll + sum(logLikeR);\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/robOneDynamicsLogLikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5635156891750129}}
{"text": "% LSADM (Goldfarb et al. 2010)\n% process_video('RPCA', 'LSADM', 'dataset/demo.avi', 'output/demo_LSADM.avi');\nopts.D = M;\nopts.mu = norm(M)/1.25;\n[n1,n2] = size(M);\nopts.Xs = M;\nopts.Ys = M;\nopts.n1 = n1;\nopts.n2 = n2;\nopts.sigma = 1e-6;\nopts.maxitr = 500;\nopts.rho = 1/sqrt(n1);\nopts.eta_mu = 2/3;\nopts.eta_sigma = 2/3;\nopts.muf = 1e-6;\nopts.sigmaf = 1e-6;\nopts.epsilon = 1e-7;\nopts.sv = 100;\nout_ALM = ALM_SADAL_smoothed(opts.D,opts);\nL = out_ALM.X;\nS = out_ALM.Y;", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/LSADM/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5635156883249507}}
{"text": "\nfunction Q_gpfa = test_gpfa(seed)\n\nif nargin >= 1\n  randn('state', seed);\n  rand('state', seed);\nend\n\n%\n% Generate some data\n%\n\nD = 3;\n\nin_x = 1:200;\nN_x = length(in_x);\nX = zeros(D,N_x);\nX(1,:) = in_x/N_x;%sin(2*pi*in_w/10);\nX(2,:) = cos(2*pi*in_x/7);\nX(3,:) = randn(N_x,1);\n\nin_w = 1:100;\nN_w = length(in_w);\nW = zeros(D,N_w);\nW(1,:) = cos(2*pi*in_w/20);\nW(2,:) = cos(2*pi*in_w/10);\nW(3,:) = randn(N_w,1);\n\ns = 0.5;\nY_noiseless = W'*X;\nY = Y_noiseless + s*randn(N_w,N_x);\n\nImv = (rand(size(Y)) < 0.4);\nImv(:,15) = true;\nY(Imv) = NaN;\n\n%\n% GP module for X\n%\n\nN_p = 10;\npseudo_x = linspace(min(in_x),max(in_x), N_p);\nis_pseudo_x = false(D,1);\n\nD2_xx = sq_dist(in_x);\nD2_pp = sq_dist(pseudo_x);\nD2_px = sq_dist(pseudo_x, in_x);\n\n% Covariance functions\ncovfunc = @(D2) gp_cov_se(D2);\ncovfunc_x = cell(D,1);\n% $$$ covfunc_x{1} = gp_cov_jitter(gp_cov_se(D2_xx));\ncovfunc_x{1} = gp_cov_pseudo(gp_cov_jitter(gp_cov_se(D2_pp)), ...\n                             gp_cov_se(D2_px), ...\n                             gp_cov_se(diag(D2_xx)));\nis_pseudo_x(1) = true;\ntheta_x{1} = 30;\n\ncovfunc_x{2} = gp_cov_jitter(covfunc(D2_xx));\ntheta_x{2} = 3;\n\ncovfunc_x{3} = gp_cov_jitter(gp_cov_pp(sqrt(D2_xx),1));\ntheta_x{3} = 1.1;\n\n% $$$ figure\n% $$$ imagesc(covfunc_x{1}(theta_x{1}));\n% $$$ figure\n% $$$ imagesc(covfunc_x{2}(theta_x{2}));\n% $$$ return\n\n\n%\n% GP module for W\n%\n\nD2_ww = sq_dist(in_w);\n\n% Covariance functions\ncovfunc_w = cell(D,1);\ncovfunc_w{1} = gp_cov_scale(gp_cov_jitter(gp_cov_se(D2_ww)));\ntheta_w{1} = [1; 3];\ncovfunc_w{2} = gp_cov_scale(gp_cov_jitter(gp_cov_se(D2_ww)));\ntheta_w{2} = [1; 2];\ncovfunc_w{3} = gp_cov_scale(gp_cov_jitter(gp_cov_pp(sqrt(D2_ww),1)));\ntheta_w{3} = [1; 1.1];\n\n\n%\n% Isotropic noise module\n%\n\n%noise_module = noise_module_fixed(1/s^2 * ones(N_w, N_x));\nnoise_module = noise_module_isotropic(N_w, N_x, 1e-3, 1e-3, 'init', 100);\n\n%\n% VB inference\n%\n\n%\n% TODO:\n%\n% - pseudo inputs\n%\n% - put the noise to Q(W)\n%\n% - test more components\n%\n% - rotation, optimize the hyperparameters jointly?\n%\n% - weighted noise\n%\n\n%\n% GPFA\n%\n\n% GP modules with component-wise factorization\n\n% NOTES:\n%\n% The algorithm can be quite sensitive to hyperparameter initialization and\n% update schedule. Also, it seems that it's best to do rotations rarely and\n% after the hyperparameters have been updated at least once. The rotations\n% in GPFA are approximately optimized, so some problems can be caused by\n% that. So it might be a good idea NOT to use rotations..\n\n% Update only the smooth components at the beginning\nmaxiter = 30;\nupdate_schedule = cell(maxiter,1);\nupdate_schedule(:) = {1:D};\nupdate_schedule(1:10) = {1};\n%update_schedule(6:10) = {1:2};\n\nX_module = factor_module_gp_factorized(N_x, covfunc_x, theta_x, ...\n                                       'is_pseudo', is_pseudo_x, ...\n                                       'update_hyperparameters', [5:5:1000], ...\n                                       'update_schedule', {update_schedule});\nW_module = factor_module_gp_factorized(N_w, covfunc_w, theta_w, ...\n                                       'update_hyperparameters', [5:5:1000], ...\n                                       'update_schedule', {update_schedule});\n\nQ_gpfa = vbfa(D, Y, W_module, X_module, noise_module, ...\n              'maxiter', maxiter, ...\n              'update_noise', 1, ...\n              'rotate', false, ...\n              'rotation_checkgrad', false);\n\n\nfigure\nplot(Q_gpfa.loglikelihood)\n\n%\n% PCA\n%\n\nX_module = factor_module_iid(D, N_x);\nW_module = factor_module_ard(D, N_w);\n\nQ_pca = vbfa(D, Y, W_module, X_module, noise_module, ...\n         'maxiter', 30, ...\n         'update_noise', 1, ...\n         'rotate', 1);\n\n\n%\n% Results\n%\n\nhax = tsplot(X);\ntitle(hax(1), 'True X');\nhax = tsplot(W);\ntitle(hax(1), 'True W');\n\nhax = tsplot(Q_gpfa.X);\ntitle(hax(1), 'GPFA X');\nhax = tsplot(Q_gpfa.W);\ntitle(hax(1), 'GPFA W');\n\nhax = tsplot(Q_pca.X);\ntitle(hax(1), 'PCA X');\nhax = tsplot(Q_pca.W);\ntitle(hax(1), 'PCA W');\n\nYh_gpfa = Q_gpfa.W'*Q_gpfa.X;\nYh_pca = Q_pca.W'*Q_pca.X;\nhax = tsplot([Y_noiseless(:,15)';\n              Yh_gpfa(:,15)';\n              Yh_pca(:,15)']);\ntitle(hax(1), 'Reconstructions of observations');\n\n\n% Comparison\n%noise_std_gpfa = Q_gpfa.Tau(1)^(-0.5);\n%noise_std_pca = Q_pca.Tau(1)^(-0.5);\nrecon_error_gpfa = rmse(Y_noiseless, Yh_gpfa)\nrecon_error_pca = rmse(Y_noiseless, Yh_pca)\ntest_error_gpfa = rmse(Y_noiseless(Imv), Yh_gpfa(Imv))\ntest_error_pca = rmse(Y_noiseless(Imv), Yh_pca(Imv))\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gppca/test_gpfa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5635073836171326}}
{"text": "%mmcfindls(lambda,mu,c)\n%   This function finds the average system size\n%   for an M/M/c queueing system.\n\nfunction out = mmcfindls(lambda,mu,c)\n\npc = lambda/mu;\nlq = mmcfindlq(lambda,mu,c);\n\nls = lq + pc;\n\nout = ls;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1250-queueing-systems-toolbox/mmcfindls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5635073778806546}}
{"text": "function [MPa] = inH2O2MPa(inH2O)\n% Convert pressure from inches of water column at 4 degrees to megapascals\n% Chad Greene 2012\nMPa = inH2O*0.000249089;", "meta": {"author": "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/inH2O2MPa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5635073730390326}}
{"text": "function [bor,F0,F1] = spm_BMS_bor(L,posterior,priors,C)\n% Compute Bayes Omnibus Risk\n% FORMAT [bor,F0,F1] = spm_BMS_bor(L,posterior,priors,C)\n%\n% L         Log model evidence table (models x  subjects)\n% posterior .a model counts, .r model-subject probs\n% priors    .a model counts\n% C         if this field is specified then BOR under family prior \n%           is computed, otherwise BOR under model prior is computed.\n%           C(k,f) = 1 if model k belongs to family f (0 otherwise)\n%\n% REFERENCES:\n%\n% Rigoux, L, Stephan, KE, Friston, KJ and Daunizeau, J. (2014)\n% Bayesian model selection for group studies - Revisited. \n% NeuroImage 84:971-85. doi: 10.1016/j.neuroimage.2013.08.065\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_BMS_bor.m 6444 2015-05-21 11:15:48Z guillaume $\n\n\nif nargin < 4\n    options.families = 0;\n    % Evidence of null (equal model freqs)\n    F0 = FE_null(L,options); \nelse\n    options.families = 1;\n    options.C = C;\n    % Evidence of null (equal model freqs) under family prior\n    [tmp,F0] = FE_null(L,options); \nend\n\n% Evidence of alternative\nF1 = FE(L,posterior,priors); \n\n% Implied by Eq 5 (see also p39) in Rigoux et al.\n% See also, last equation in Appendix 2\nbor = 1/(1+exp(F1-F0)); \n\n\nfunction [F,ELJ,Sqf,Sqm] = FE(L,posterior,priors)\n% derives the free energy for the current approximate posterior\n% This routine has been copied from the VBA_groupBMC function\n% of the VBA toolbox http://code.google.com/p/mbb-vb-toolbox/ \n% and was written by Lionel Rigoux and J. Daunizeau\n%\n% See equation A.20 in Rigoux et al. (should be F1 on LHS)\n\n[K,n] = size(L);\na0 = sum(posterior.a);\nElogr = psi(posterior.a) - psi(sum(posterior.a));\nSqf = sum(gammaln(posterior.a)) - gammaln(a0) - sum((posterior.a-1).*Elogr);\nSqm = 0;\nfor i=1:n\n    Sqm = Sqm - sum(posterior.r(:,i).*log(posterior.r(:,i)+eps));\nend\nELJ = gammaln(sum(priors.a)) - sum(gammaln(priors.a)) + sum((priors.a-1).*Elogr);\nfor i=1:n\n    for k=1:K\n        ELJ = ELJ + posterior.r(k,i).*(Elogr(k)+L(k,i));\n    end\nend\nF = ELJ + Sqf + Sqm;\n\n\nfunction [F0m,F0f] = FE_null (L,options)\n% Free energy of the 'null' (H0: equal frequencies)\n%\n% F0m       Evidence for null (ie. equal probs) over models \n% F0f       Evidence for null (ie. equal probs) over families\n%\n% This routine derives from the VBA_groupBMC function\n% of the VBA toolbox http://code.google.com/p/mbb-vb-toolbox/ \n% written by Lionel Rigoux and J. Daunizeau\n%\n% See Equation A.17 in Rigoux et al.\n\n[K,n] = size(L);\nif options.families\n    f0 = options.C*sum(options.C,1)'.^-1/size(options.C,2);\n    F0f = 0;\nelse\n    F0f = [];\nend\nF0m = 0;\nfor i=1:n\n    tmp = L(:,i) - max(L(:,i));\n    g = exp(tmp)./sum(exp(tmp));\n    for k=1:K\n        F0m = F0m + g(k).*(L(k,i)-log(K)-log(g(k)+eps));\n        if options.families\n            F0f = F0f + g(k).*(L(k,i)-log(g(k)+eps)+log(f0(k)));\n        end\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/spm_BMS_bor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5635073730390325}}
{"text": "function varargout=wt(d,varargin)\n%% Continous Wavelet Transform\n% Creates a figure of wavelet power in units of\n% normalized variance.\n%\n% USAGE: [wave,period,scale,coi,sig95]=wt(d[,params])\n%\n% d: a time series\n% wave: the wavelet transform of d\n% period: a vector of \"Fourier\" periods associated with wave\n% scale: a vector of wavelet scales associated with wave\n% coi: the cone of influence\n%\n% Settings: Pad: pad the time series with zeros?\n% .         Dj: Octaves per scale (default: '1/12')\n% .         S0: Minimum scale\n% .         J1: Total number of scales\n% .         Mother: Mother wavelet (default 'morlet')\n% .         MaxScale: An easier way of specifying J1\n% .         MakeFigure: Make a figure or simply return the output.\n% .         BlackandWhite: Create black and white figures\n% .         AR1: the ar1 coefficient of the series\n% .              (default='auto' using a naive ar1 estimator. See ar1nv.m)\n%\n% Settings can also be specified using abbreviations. e.g. ms=MaxScale.\n% For detailed help on some parameters type help wavelet.\n%\n%\n% Example:\n%      wt([0:200;sin(0:200)],'dj',1/20,'bw','maxscale',32)\n%\n% (C) Aslak Grinsted 2002-2014\n%\n% http://www.glaciology.net/wavelet-coherence\n\n% -------------------------------------------------------------------------\n%The MIT License (MIT)\n%\n%Copyright (c) 2014 Aslak Grinsted\n%\n%Permission is hereby granted, free of charge, to any person obtaining a copy\n%of this software and associated documentation files (the \"Software\"), to deal\n%in the Software without restriction, including without limitation the rights\n%to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n%copies of the Software, and to permit persons to whom the Software is\n%furnished to do so, subject to the following conditions:\n%\n%The above copyright notice and this permission notice shall be included in\n%all copies or substantial portions of the Software.\n%\n%THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n%IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n%FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n%AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n%LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n%OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n%THE SOFTWARE.\n%---------------------------------------------------------------------------\n\n\n% ------validate and reformat timeseries.\n[d,dt]=formatts(d);\n\nn=size(d,1);\nsigma2=var(d(:,2));\n\n%----------default arguments for the wavelet transform-----------\nArgs=struct('Pad',1,...      % pad the time series with zeroes (recommended)\n    'Dj',1/12, ...    % this will do 12 sub-octaves per octave\n    'S0',2*dt,...    % this says start at a scale of 2 years\n    'J1',[],...\n    'Mother','Morlet', ...\n    'MaxScale',[],...   %a more simple way to specify J1\n    'MakeFigure',(nargout==0),...\n    'AR1','auto');\nArgs=parseArgs(varargin,Args,{'BlackandWhite'});\nif isempty(Args.J1)\n    if isempty(Args.MaxScale)\n        Args.MaxScale=(n*.17)*2*dt; %automaxscale\n    end\n    Args.J1=round(log2(Args.MaxScale/Args.S0)/Args.Dj);\nend\n\nif strcmpi(Args.AR1,'auto')\n    Args.AR1=ar1nv(d(:,2));\n\n    if any(isnan(Args.AR1))\n        error('Automatic AR1 estimation failed. Specify it manually (use arcov or arburg).')\n    end\nend\n\n\n\n%----------------::::::::---------- Analyze: ---------:::::::::::::-----------------\n\n\n[wave,period,scale,coi] = wavelet(d(:,2),dt,Args.Pad,Args.Dj,Args.S0,Args.J1,Args.Mother);\n\nt=d(:,1);\npower = (abs(wave)).^2 ;        % compute wavelet power spectrum\nsignif = wave_signif(1.0,dt,scale,0,Args.AR1,-1,-1,Args.Mother);\nsig95 = (signif')*(ones(1,n));  % expand signif --> (J+1)x(N) array\nsig95 = power ./ (sigma2*sig95);\nYticks = 2.^(fix(log2(min(period))):fix(log2(max(period))));\n\nif Args.MakeFigure\n    H=imagesc(t,log2(period),log2(abs(power/sigma2)));%#ok,log2(levels));  %*** or use 'contourfill'\n    %logpow=log2(abs(power/sigma2));\n    %[c,H]=contourf(t,log2(period),logpow,[min(logpow(:)):.25:max(logpow(:))]);\n    %set(H,'linestyle','none')\n\n    clim=get(gca,'clim'); %center color limits around log2(1)=0\n    clim=[-1 1]*max(clim(2),3);\n    set(gca,'clim',clim)\n\n    HCB=colorbar;\n    set(HCB,'ytick',-7:7);\n    barylbls=rats(2.^(get(HCB,'ytick')'));\n    barylbls([1 end],:)=' ';\n    barylbls(:,all(barylbls==' ',1))=[];\n    set(HCB,'yticklabel',barylbls);\n\n\n    set(gca,'YLim',log2([min(period),max(period)]), ...\n        'YDir','reverse', ...\n        'YTick',log2(Yticks(:)), ...\n        'YTickLabel',num2str(Yticks'), ...\n        'layer','top')\n    %xlabel('Time')\n    ylabel('Period')\n    hold on\n\n\n\n    [c,h] = contour(t,log2(period),sig95,[1 1],'k'); %#ok\n    set(h,'linewidth',2)\n    %plot(t,log2(coi),'k','linewidth',3)\n    tt=[t([1 1])-dt*.5;t;t([end end])+dt*.5];\n    hcoi=fill(tt,log2([period([end 1]) coi period([1 end])]),'w');\n    set(hcoi,'alphadatamapping','direct','facealpha',.5)\n\n    hold off\n    set(gca,'box','on','layer','top');\nend\nvarargout={wave,period,scale,coi,sig95};\nvarargout=varargout(1:nargout);\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/wt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.56344157714095}}
{"text": "function imResult = blendMode_Lighten(A, B, offsetW, offsetH)\n%% Lighten blending mode: compares the color information for each pixel of\n%   the base and the blend color and applies the lighter color as the \n%   result.\n%   Any pixels in the base image that are darker than the blend color are \n%   replaced, and pixels that are lighter are left unchanged. No part of  \n%   the image will become darker. \n% \n% Input:\n%       A       -       Base Image\n%       B       -       Top Image\n%   offsetW     -   move picture B horizontally in respect to the top-left\n%                   corner of picture A. Default value = 1.\n%   offsetH     -   move picture B vertically in respect to the top-left\n%                   corner of picture A. Default value = 1.\n%\n% Output:\n%       imResult    -   Result of the blending, having the same size of the\n%                       Base Image A.\n% \n\n%% Check Input\na = size(A);\nb = size(B);\nblendMode_checkInput(nargin, a, b, func2str(@blendMode_Lighten));\n\nif nargin < 3\n    offsetW = 1;\n    offsetH = 1;\nend\n\nif nargin < 4\n    offsetH = 1;\nend\n\n%% Implementation\nimResult = A;\n\nif (((offsetW ~= 1) || (offsetH ~= 1)) || (sum(a == b) ~= length(a)))\n    [A, B] = blendMode_ResizeImages(A, B, a, b, offsetW, offsetH);\nend\n\nind = B > A;\nC = abs(ind - 1) .* A + ind .* B;\n\nif (((offsetW ~= 1) || (offsetH ~= 1)) || (sum(a == b) ~= length(a)))\n    imResult = blendMode_CreateResult(imResult, C, offsetW, offsetH);\nelse\n    imResult = C;\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/43122-blend-images/blendModes/blendMode_Lighten.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5634415742817894}}
{"text": "function [Y, optinf] = bpdn(D, S, lambda, opt)\n\n% bpdn -- Basis Pursuit DeNoising\n%\n%         argmin_x (1/2)||D*x - s||_2^2 + lambda*||x||_1\n%\n%         The solution of the BPDN problem (see chen-1998-atomic) is\n%         computed using the ADMM approach (see boyd-2010-distributed).\n%\n% Usage:\n%       [Y, optinf] = bpdn(D, S, lambda, opt)\n%\n% Input:\n%       D           Dictionary matrix\n%       S           Signal vector (or matrix)\n%       lambda      Regularization parameter\n%       opt         Options/algorithm parameters structure (see below)\n%\n% Output:\n%       Y           Dictionary coefficient vector (or matrix)\n%       optinf      Details of optimisation\n%\n%\n% Options structure fields:\n%   Verbose           Flag determining whether iteration status is displayed.\n%                     Fields are iteration number, functional value,\n%                     data fidelity term, l1 regularisation term, and\n%                     primal and dual residuals (see Sec. 3.3 of\n%                     boyd-2010-distributed). The value of rho is also\n%                     displayed if options request that it is automatically\n%                     adjusted.\n%   MaxMainIter       Maximum main iterations\n%   AbsStopTol        Absolute convergence tolerance (see Sec. 3.3.1 of\n%                     boyd-2010-distributed)\n%   RelStopTol        Relative convergence tolerance (see Sec. 3.3.1 of\n%                     boyd-2010-distributed)\n%   L1Weight          Weighting array for coefficients in l1 norm of X\n%   Y0                Initial value for Y\n%   U0                Initial value for U\n%   rho               ADMM penalty parameter\n%   AutoRho           Flag determining whether rho is automatically updated\n%                     (see Sec. 3.4.1 of boyd-2010-distributed)\n%   AutoRhoPeriod     Iteration period on which rho is updated\n%   RhoRsdlRatio      Primal/dual residual ratio in rho update test\n%   RhoScaling        Multiplier applied to rho when updated\n%   AutoRhoScaling    Flag determining whether RhoScaling value is\n%                     adaptively determined (see wohlberg-2015-adaptive). If\n%                     enabled, RhoScaling specifies a maximum allowed\n%                     multiplier instead of a fixed multiplier.\n%   RhoRsdlTarget     Residual ratio targeted by auto rho update policy.\n%   StdResiduals      Flag determining whether standard residual definitions\n%                     (see Sec 3.3 of boyd-2010-distributed) are used instead\n%                     of normalised residuals (see wohlberg-2015-adaptive)\n%   RelaxParam        Relaxation parameter (see Sec. 3.4.3 of\n%                     boyd-2010-distributed)\n%   NonNegCoef        Flag indicating whether solution should be forced to\n%                     be non-negative\n%   AuxVarObj         Flag determining whether objective function is computed\n%                     using the auxiliary (split) variable\n%\n%\n% Author: Brendt Wohlberg <brendt@lanl.gov>  Modified: 2015-07-23\n%\n% This file is part of the SPORCO library. Details of the copyright\n% and user license can be found in the 'License' file distributed with\n% the library.\n\n\nif nargin < 4,\n  opt = [];\nend\ncheckopt(opt, defaultopts([]));\nopt = defaultopts(opt);\n\n% Default lambda is 1/10 times the lambda value beyond which the\n% solution is a zero vector\nif nargin < 3 | isempty(lambda),\n  lambda = 0.1*max(vec(abs(D'*S)));\nend\n\n% Set up status display for verbose operation\nhstr = 'Itn   Fnc       DFid      l1        r         s      ';\nsfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e';\nnsep = 54;\nif opt.AutoRho,\n  hstr = [hstr '   rho   '];\n  sfms = [sfms ' %9.2e'];\n  nsep = nsep + 10;\nend\nif opt.Verbose && opt.MaxMainIter > 0,\n  disp(hstr);\n  disp(char('-' * ones(1,nsep)));\nend\n\n% Start timer\ntstart = tic;\n\n% Set up algorithm parameters and initialise variables\nrho = opt.rho;\nif isempty(rho), rho = 50*lambda+1; end;\n[Nr, Nc] = size(D);\nNm = size(S,2);\nNx = Nc*Nm;\nDTS = D'*S;\n[luL, luU] = factorise(D, rho);\noptinf = struct('itstat', [], 'opt', opt);\nr = Inf;\ns = Inf;\nepri = 0;\nedua = 0;\n\n% Initialise main working variables\nX = [];\nif isempty(opt.Y0),\n  Y = zeros(Nc,Nm);\nelse\n  Y = opt.Y0;\nend\nYprv = Y;\nif isempty(opt.U0),\n  if isempty(opt.Y0),\n    U = zeros(Nc,Nm);\n  else\n    U = (lambda/rho)*sign(Y);\n  end\nelse\n  U = opt.U0;\nend\n\n% Main loop\nk = 1;\nwhile k <= opt.MaxMainIter && (r > epri | s > edua),\n\n  % Solve X subproblem\n  X = linsolve(D, rho, luL, luU, DTS + rho*(Y - U));\n\n  % See pg. 21 of boyd-2010-distributed\n  if opt.RelaxParam == 1,\n    Xr = X;\n  else\n    Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;\n  end\n\n  % Solve Y subproblem\n  Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);\n  if opt.NonNegCoef,\n    Y(Y < 0) = 0;\n  end\n\n  % Update dual variable\n  U = U + Xr - Y;\n\n  % Objective function and convergence measures\n  if opt.AuxVarObj,\n    Jdf = sum(vec(abs(D*Y - S).^2))/2;\n    Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));\n  else\n    Jdf = sum(vec(abs(D*X - S).^2))/2;\n    Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X))));\n  end\n  Jfn = Jdf + lambda*Jl1;\n\n  nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));\n  if opt.StdResiduals,\n    % See pp. 19-20 of boyd-2010-distributed\n    r = norm(vec(X - Y));\n    s = norm(vec(rho*(Yprv - Y)));\n    epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;\n    edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;\n  else\n    % See wohlberg-2015-adaptive\n    r = norm(vec(X - Y))/max(nX,nY);\n    s = norm(vec(Yprv - Y))/nU;\n    epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;\n    edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;\n  end\n\n  % Record and display iteration details\n  tk = toc(tstart);\n  optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 r s epri edua rho tk]];\n  if opt.Verbose,\n    if opt.AutoRho,\n      disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s, rho));\n    else\n      disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s));\n    end\n  end\n\n  % See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed\n  if opt.AutoRho,\n    if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,\n      if opt.AutoRhoScaling,\n        rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));\n        if rhomlt < 1, rhomlt = 1/rhomlt; end\n        if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end\n      else\n        rhomlt = opt.RhoScaling;\n      end\n      rsf = 1;\n      if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end\n      if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end\n      rho = rsf*rho;\n      U = U/rsf;\n      if rsf ~= 1,\n        [luL, luU] = factorise(D, rho);\n      end\n    end\n  end\n\n  Yprv = Y;\n  k = k + 1;\n\nend\n\n% Record run time and working variables\noptinf.runtime = toc(tstart);\noptinf.X = X;\noptinf.Y = Y;\noptinf.U = U;\noptinf.lambda = lambda;\noptinf.rho = rho;\n\n% End status display for verbose operation\nif opt.Verbose && opt.MaxMainIter > 0,\n  disp(char('-' * ones(1,nsep)));\nend\n\nreturn\n\n\nfunction u = vec(v)\n\n  u = v(:);\n\nreturn\n\n\nfunction u = shrink(v, lambda)\n\n  if isscalar(lambda),\n    u = sign(v).*max(0, abs(v) - lambda);\n  else\n    u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));\n  end\n\nreturn\n\n\nfunction [L,U] = factorise(A, c)\n\n  [N,M] = size(A);\n  % If N < M it is cheaper to factorise A*A' + cI and then use the\n  % matrix inversion lemma to compute the inverse of A'*A + cI\n  if N >= M,\n    [L,U] = lu(A'*A + c*eye(M,M));\n  else\n    [L,U] = lu(A*A' + c*eye(N,N));\n  end\n\nreturn\n\n\nfunction x = linsolve(A, c, L, U, b)\n\n  [N,M] = size(A);\n  if N >= M,\n    x = U \\ (L \\ b);\n  else\n    x = (b - A'*(U \\ (L \\ (A*b))))/c;\n  end\n\nreturn\n\n\nfunction opt = defaultopts(opt)\n\n  if ~isfield(opt,'Verbose'),\n    opt.Verbose = 0;\n  end\n  if ~isfield(opt,'MaxMainIter'),\n    opt.MaxMainIter = 1000;\n  end\n  if ~isfield(opt,'AbsStopTol'),\n    opt.AbsStopTol = 0;\n  end\n  if ~isfield(opt,'RelStopTol'),\n    opt.RelStopTol = 1e-4;\n  end\n  if ~isfield(opt,'L1Weight'),\n    opt.L1Weight = 1;\n  end\n  if ~isfield(opt,'Y0'),\n    opt.Y0 = [];\n  end\n  if ~isfield(opt,'U0'),\n    opt.U0 = [];\n  end\n  if ~isfield(opt,'rho'),\n    opt.rho = [];\n  end\n  if ~isfield(opt,'AutoRho'),\n    opt.AutoRho = 1;\n  end\n  if ~isfield(opt,'AutoRhoPeriod'),\n    opt.AutoRhoPeriod = 10;\n  end\n  if ~isfield(opt,'RhoRsdlRatio'),\n    opt.RhoRsdlRatio = 1.2;\n  end\n  if ~isfield(opt,'RhoScaling'),\n    opt.RhoScaling = 100;\n  end\n  if ~isfield(opt,'AutoRhoScaling'),\n    opt.AutoRhoScaling = 1;\n  end\n  if ~isfield(opt,'RhoRsdlTarget'),\n    opt.RhoRsdlTarget = 1;\n  end\n  if ~isfield(opt,'StdResiduals'),\n    opt.StdResiduals = 0;\n  end\n  if ~isfield(opt,'RelaxParam'),\n    opt.RelaxParam = 1.8;\n  end\n  if ~isfield(opt,'NonNegCoef'),\n    opt.NonNegCoef = 0;\n  end\n  if ~isfield(opt,'AuxVarObj'),\n    opt.AuxVarObj = 1;\n  end\n\nreturn\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/ConvSR_Image_Fusion_Codes/sporco/SparseCode/bpdn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5634415725210081}}
{"text": "function a = p03_a ( m, n )\n\n%*****************************************************************************80\n%\n%% P03_A returns the matrix A for problem 3.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    16 April 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Cleve Moler,\n%    Numerical Computing with MATLAB,\n%    SIAM, 2004,\n%    ISBN13: 978-0-898716-60-3,\n%    LC: QA297.M625,\n%    ebook: http://www.mathworks.com/moler/chapters.html\n%\n%  Parameters:\n%\n%    Input, integer M, the number of equations.\n%\n%    Input, integer N, the number of variables.\n%\n%    Output, real A(M,N), the matrix.\n%\n  a = [  1.0,  2.0,  3.0; ...\n         4.0,  5.0,  6.0; ...\n         7.0,  8.0,  9.0; ...\n        10.0, 11.0, 12.0; ...\n        13.0, 14.0, 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_ls/p03_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5634415604219642}}
{"text": "function lambda = pei_eigenvalues ( alpha, n )\n\n%*****************************************************************************80\n%\n%% PEI_EIGENVALUES returns the eigenvalues of the PEI 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, real ALPHA, the scalar that defines the Pei matrix.  A\n%    typical value of ALPHA is 1.0.\n%\n%    Input, integer N, the order of A.\n%\n%    Output, real LAMBDA(N,1), the eigenvalues.\n%\n  lambda = zeros ( n, 1 );\n\n  lambda(1:n-1,1) = alpha;\n  lambda(n,1) = alpha + n;\n\n  return\nend\n", "meta": {"author": "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/pei_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.5633482822284823}}
{"text": "function y = ExtendArray(x,s,fill)\n\n%ExtendArray - Extend existing array to a given (larger) size.\n%\n%  USAGE\n%\n%    y = ExtendArray(x,s)\n%\n%    x              input array\n%    s              output size, must have the same number of dimensions as x\n%    fill           optional value for new elements (default: nan)\n%\n\n% Copyright (C) 2013 by Micha\u00ebl Zugaro\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\n% Check inputs\nif nargin < 2,\n\terror('Incorrect number of parameters (type ''help <a href=\"matlab:help ExtendArray\">ExtendArray</a>'' for details).');\nend\ncurrentSize = size(x);\nif length(currentSize) ~= length(s),\n\terror('Array and size do not have the same number of dimensions (type ''help <a href=\"matlab:help ExtendArray\">ExtendArray</a>'' for details).');\nend\n\n% Create extended array, fill with requested value\nif nargin < 3,\n\ty = nan(s);\nelse\n\tif ~isscalar(fill),\n\t\terror('Incorrect fill value (type ''help <a href=\"matlab:help ExtendArray\">ExtendArray</a>'' for details).');\n\tend\n\tswitch(fill),\n\t\tcase 0,\n\t\t\ty = zeros(s);\n\t\tcase 1,\n\t\t\ty = ones(s);\n\t\tcase inf,\n\t\t\ty = inf(s);\n\t\totherwise,\n\t\t\ty = fill*ones(s);\n\tend\nend\n\n% Copy old array into new array\nindices = arrayfun(@(x) 1:x,currentSize,'uniformoutput',0);\ny(indices{:}) = 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/FMAToolbox/General/ExtendArray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.5633482805343526}}
{"text": "function i4_gcd_test ( )\n\n%*****************************************************************************80\n%\n%% I4_GCD_TEST tests I4_GCD.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  test_num = 7;\n\n  i_test = [ 36, 49, 0, 12, 36, 1, 91 ];\n  j_test = [ 30, -7, 71, 12, 49, 42, 28 ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'I4_GCD_TEST\\n' );\n  fprintf ( 1, '  I4_GCD computes the greatest common factor\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '     I     J   I4_GCD\\n' );\n  fprintf ( 1, '\\n' );\n \n  for test = 1 : test_num\n    i = i_test(test);\n    j = j_test(test);\n    fprintf ( 1, '  %6d  %6d  %6d\\n', i, j, i4_gcd ( i, 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/i4lib/i4_gcd_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.563348273757833}}
{"text": "function [mm] = um2mm(um)\n% Convert length from micrometers (or microns) to millimeters.\n% Chad A. Greene 2012\nmm = um*0.001;", "meta": {"author": "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/um2mm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5633482672668911}}
{"text": "classdef MaF14 < PROBLEM\n% <multi/many> <real> <large/none>\n% LSMOP3\n\n%------------------------------- Reference --------------------------------\n% R. Cheng, M. Li, Y. Tian, X. Zhang, S. Yang, Y. Jin, and X. Yao, A\n% benchmark test suite for evolutionary many-objective optimization,\n% Complex & Intelligent Systems, 2017, 3(1): 67-81.\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        sublen;\t% Number of variables in each subcomponent\n        len;    % Cumulative sum of lengths of variable groups\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            % Parameter setting\n            if isempty(obj.M); obj.M = 3; end\n            if isempty(obj.D); obj.D = 20*obj.M; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = [ones(1,obj.M-1),10.*ones(1,obj.D-obj.M+1)];\n            obj.encoding = ones(1,obj.D);\n            % Calculate the number of variables in each subcomponent\n            nk = 2;\n            c  = 3.8*0.1*(1-0.1);\n            for i = 1 : obj.M-1\n                c = [c,3.8.*c(end).*(1-c(end))];\n            end\n            obj.sublen = floor(c./sum(c).*(obj.D-obj.M+1)/nk);\n            obj.len    = [0,cumsum(obj.sublen*nk)];\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            [N,D] = size(PopDec);\n            M     = obj.M;\n            nk    = 2;\n            PopDec(:,M:D) = (1+repmat((M:D)./D,N,1)).*PopDec(:,M:D) - repmat(PopDec(:,1)*10,1,D-M+1);\n            G = zeros(N,M);\n            for i = 1 : 2 : M\n                for j = 1 : nk\n                    G(:,i) = G(:,i) + Rastrigin(PopDec(:,obj.len(i)+M-1+(j-1)*obj.sublen(i)+1:obj.len(i)+M-1+j*obj.sublen(i)));\n                end\n            end\n            for i = 2 : 2 : M\n                for j = 1 : nk\n                    G(:,i) = G(:,i) + Rosenbrock(PopDec(:,obj.len(i)+M-1+(j-1)*obj.sublen(i)+1:obj.len(i)+M-1+j*obj.sublen(i)));\n                end\n            end\n            G      = G./repmat(obj.sublen,N,1)./nk;\n            PopObj = (1+G).*fliplr(cumprod([ones(N,1),PopDec(:,1:M-1)],2)).*[ones(N,1),1-PopDec(:,M-1:-1:1)];\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R = UniformPoint(N,obj.M);\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,1,10)';\n                R = {a*a',a*(1-a'),(1-a)*ones(size(a'))};\n            else\n                R = [];\n            end\n        end\n    end\nend\n\nfunction f = Rastrigin(x)\n    f = sum(x.^2-10.*cos(2.*pi.*x)+10,2);\nend\n\nfunction f = Rosenbrock(x)\n    f = sum(100.*(x(:,1:size(x,2)-1).^2-x(:,2:size(x,2))).^2+(x(:,1:size(x,2)-1)-1).^2,2);\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/MaF/MaF14.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5633482672668911}}
{"text": "function f = crowding_distance(x,problem)\n% This function calculates the crowding distance\n\n%\n%  Copyright (c) 2009, Aravind Seshadri\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,M] = size(x);\nswitch problem\n    case 1\n        M = 2;\n        V = 6;\n    case 2\n        M = 3;\n        V = 12;\nend\n\n% Crowding distance for each front\nfor i = 1 : length(F(front).f)\n    y(i,:) = x(F(front).f(i),:);\nend\nfor i = 1 : M\n    [sorted(i).individual,sorted(i).index] = sort(y(:,V + i));\n    distance(sorted(i).index(1)).individual = Inf;\n    distance(sorted(i).index(length(sorted(i).index))).individual = Inf;\nend\n\n[num,len] = size(y);\n% Initialize all the distance of individuals as zero.\nfor i = 1 : M\n    for j = 2 : num - 1\n        distance(j).individual = 0;\n    end\n    objective(i).range = ...\n                sorted(i).individual(length(sorted(i).individual)) - ...\n                sorted(i).individual(1);\n        % Maximum and minimum objectives value for the ith objective\nend \n% Caluclate the crowding distance for front one.\nfor i = 1 : M\n    for j = 2 : num - 1\n        distance(j).individual = distance(j).individual + ...\n            (sorted(i).individual(j + 1) - sorted(i).individual(j - 1))/...\n            objective(i).range;\n        y(sorted(i).index(j),M + V + 2) = distance(j).individual;\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/10351-multi-objective-optimizaion-using-evolutionary-algorithm/MOEA-NSGA-II/crowding_distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5633482654299724}}
{"text": "function x = r8bb_sl ( n1, n2, ml, mu, a_lu, pivot, b )\n\n%*****************************************************************************80\n%\n%% R8BB_SL solves a R8BB system factored by R8BB_FA.\n%\n%  Discussion:\n%\n%    Note that in C++ and FORTRAN, we can look at A as an abstract\n%    vector, but then look at parts of A as storing a two dimensional\n%    array.  MATLAB assigns an inherent dimensionality to a data object,\n%    and gets very unhappy when you try to manipulate the data yourself.\n%    This means that the MATLAB implementation of this routine requires\n%    the use of temporary 2D arrays.\n%\n%    The R8BB storage format is for a border banded matrix.  Such a\n%    matrix has the logical form:\n%\n%      A1 | A2\n%      ---+---\n%      A3 | A4\n%\n%    with A1 a (usually large) N1 by N1 banded matrix, while A2, A3 and A4\n%    are dense rectangular matrices of orders N1 by N2, N2 by N1, and N2 by N2,\n%    respectively.\n%\n%    A should be defined as a vector.  The user must then store\n%    the entries of the four blocks of the matrix into the vector A.\n%    Each block is stored by columns.\n%\n%    A1, the banded portion of the matrix, is stored in\n%    the first (2*ML+MU+1)*N1 entries of A, using standard LINPACK\n%    general band format.  The reason for the factor of 2 in front of\n%    ML is to allocate space that may be required if pivoting occurs.\n%\n%    The following formulas should be used to determine how to store\n%    the entry corresponding to row I and column J in the original matrix:\n%\n%    Entries of A1:\n%\n%      1 <= I <= N1, 1 <= J <= N1, (J-I) <= MU and (I-J) <= ML.\n%\n%      Store the I, J entry into location\n%      (I-J+ML+MU+1)+(J-1)*(2*ML+MU+1).\n%\n%    Entries of A2:\n%\n%      1 <= I <= N1, N1+1 <= J <= N1+N2.\n%\n%      Store the I, J entry into location\n%      (2*ML+MU+1)*N1+(J-N1-1)*N1+I.\n%\n%    Entries of A3:\n%\n%      N1+1 <= I <= N1+N2, 1 <= J <= N1.\n%\n%      Store the I, J entry into location\n%      (2*ML+MU+1)*N1+N1*N2+(J-1)*N2+(I-N1).\n%\n%    Entries of A4:\n%\n%      N1+1 <= I <= N1+N2, N1+1 <= J <= N1+N2\n%\n%      Store the I, J entry into location\n%      (2*ML+MU+1)*N1+N1*N2+(J-1)*N2+(I-N1).\n%      (same formula used for A3).\n%\n%    The linear system A * x = b is decomposable into the block system:\n%\n%      ( A1 A2 ) * (X1) = (B1)\n%      ( A3 A4 )   (X2)   (B2)\n%\n%    All the arguments except B are input quantities only, which are\n%    not changed by the routine.  They should have exactly the same values\n%    they had on exit from R8BB_FA.\n%\n%    If more than one right hand side is to be solved, with the same matrix,\n%    R8BB_SL should be called repeatedly.  However, R8BB_FA only needs to be\n%    called once to create the factorization.\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, integer N1, N2, the order of the banded and dense blocks.\n%    N1 and N2 must be nonnegative, and at least one must be positive.\n%\n%    Input, integer ML, MU, the lower and upper bandwidths.\n%    ML and MU must be nonnegative and no greater than N1-1.\n%\n%    Input, real A_LU( (2*ML+MU+1)*N1 + 2*N1*N2 + N2*N2), the factor information\n%    computed by R8BB_FA.\n%\n%    Input, integer PIVOT(N1+N2), the pivoting information from R8BB_FA.\n%\n%    Input, real B(N1+N2), the right hand side of the linear system.\n%\n%    Output, real X(N1+N2), the solution.\n%\n  nband = (2*ml+mu+1)*n1;\n%\n%  Set B1 := inverse(A1) * B1.\n%  Copy the banded matrix out of A_LU and into A1_LU.\n%\n  if ( 0 < n1 )\n\n    a1_lu(1:2*ml+mu+1,1:n1) = r8vec_to_r8gb ( n1, n1, ml, mu, a_lu(1:nband) );\n\n    job = 0;\n\n    x(1:n1) = r8gb_sl ( n1, ml, mu, a1_lu, pivot, b, job );\n\n  end\n%\n%  Modify the right hand side of the second linear subsystem.\n%  Set B2 := B2 - A3*B1.\n%\n  for i = 1 : n2\n    for j = 1 : n1\n      ij = nband + n1*n2 + (j-1)*n2 + i;\n      b(n1+i) = b(n1+i) - a_lu(ij) * x(j);\n    end\n  end\n%\n%  Set B2 := inverse(A4) * B2.\n%  Copy the dense matrix out of A_LU and into A4_LU.\n%\n  if ( 0 < n2 )\n\n    a4_lu(1:n2,1:n2) = r8vec_to_r8ge ( ...\n      n2, n2, a_lu(nband+2*n1*n2+1:nband+2*n1*n2+n2*n2) );\n\n    job = 0;\n    x(n1+1:n1+n2) = r8ge_sl ( n2, a4_lu, pivot(n1+1:n1+n2), b(n1+1:n1+n2), job );\n\n  end\n%\n%  Modify the first subsolution.\n%  Set B1 := B1 + A2*B2.\n%\n  for i = 1 : n1\n    for j = 1 : n2\n      ij = nband + (j-1)*n1 + i;\n      x(i) = x(i) + a_lu(ij) * x(n1+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/r8bb_sl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5633418764188298}}
{"text": "% [descriptors, locs] = sift(img)\n%\n% This function returns IMAGE's SIFT keypoints.\n%   Input parameters:\n%     img: the image.\n%\n%   Returned:\n%     descriptors: a K-by-128 matrix, where each row gives an invariant\n%         descriptor for one of the K keypoints.  The descriptor is a vector\n%         of 128 values normalized to unit length.\n%     locs: K-by-4 matrix, in which each row has the 4 values for a\n%         keypoint location (row, column, scale, orientation).  The \n%         orientation is in the range [-PI, PI] radians.\n%\n% Credits: Thanks for initial version of this program to D. Alvaro and \n%          J.J. Guerrero, Universidad de Zaragoza (modified by D. Lowe)\n\nfunction [descriptors, locs] = sift(img)\n\n% If you have the Image Processing Toolbox, you can uncomment the following\n%   lines to allow input of color images, which will be converted to grayscale.\nif isrgb(img)\n   img = rgb2gray(img);\nend\n\n[rows, cols] = size(img); \n\n% Convert into PGM imagefile, readable by \"keypoints\" executable\nf = fopen('tmp.pgm', 'w');\nif f == -1\n    error('Could not create file tmp.pgm.');\nend\nfprintf(f, 'P5\\n%d\\n%d\\n255\\n', cols, rows);\nfwrite(f, img', 'uint8');\nfclose(f);\n\n% Call keypoints executable\nif isunix\n    command = '!./sift ';\nelse\n    command = '!siftWin32 ';\nend\ncommand = [command ' <tmp.pgm >tmp.key'];\neval(command);\n\n% Open tmp.key and check its header\ng = fopen('tmp.key', 'r');\nif g == -1\n    error('Could not open file tmp.key.');\nend\n[header, count] = fscanf(g, '%d %d', [1 2]);\nif count ~= 2\n    error('Invalid keypoint file beginning.');\nend\nnum = header(1);\nlen = header(2);\nif len ~= 128\n    error('Keypoint descriptor length invalid (should be 128).');\nend\n\n% Creates the two output matrices (use known size for efficiency)\nlocs = double(zeros(num, 4));\ndescriptors = double(zeros(num, 128));\n\n% Parse tmp.key\nfor i = 1:num\n    [vector, count] = fscanf(g, '%f %f %f %f', [1 4]); %row col scale ori\n    if count ~= 4\n        error('Invalid keypoint file format');\n    end\n    locs(i, :) = vector(1, :);\n    \n    [descrip, count] = fscanf(g, '%d', [1 len]);\n    if (count ~= 128)\n        error('Invalid keypoint file value.');\n    end\n    % Normalize each input vector to unit length\n    descrip = descrip / sqrt(sum(descrip.^2));\n    descriptors(i, :) = descrip(1, :);\nend\nfclose(g);\n\ndelete('tmp.pgm');\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/30849-image-mosaic-using-sift/sift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5633418698923881}}
{"text": "function kern = linard2KernParamInit(kern)\n\n% LINARD2KERNPARAMINIT LINARD2 kernel parameter initialisation.\n% The automatic relevance determination version of the linear\n% kernel (LINARD2) is the simple inner product kernel with feature\n% selection applied.\n%\n% k(x_i, x_j) = x_i'*A* x_j\n%\n% where A is a diagonal matrix of values constrained to positve. These\n% parameters are stored in the field 'inputScales'.\n%\n% SEEALSO : linKernParamInit, rbfardKernParamInit\n%\n% FORMAT\n% DESC initialises the automatic relevance determination linear\n%  kernel structure with some default parameters.\n% ARG kern : the kernel structure which requires initialisation.\n% RETURN kern : the kernel structure with the default parameters placed in.\n%\n% SEEALSO : kernCreate, kernParamInit\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006\n%\n% COPYRIGHT : Michalis K. Titsias, 2009\n\n% KERN\n\n% These parameters are restricted to positive\nkern.inputScales = 0.999*ones(1, kern.inputDimension);\nkern.nParams = kern.inputDimension;\n\nkern.transforms(1).index = [1:kern.nParams];\nkern.transforms(1).type = optimiDefaultConstraint('positive');\n\nkern.isStationary = false;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/linard2KernParamInit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.563341869892388}}
{"text": "function [ehat,v_e,etahat,v_eta] = VBA_getNoise(posterior,out)\n% returns the Laplace approximation to the innovations posterior density\n% function [ehat,v_e,etahat,v_eta] = VBA_getNoise(posterior)\n% This may be useful if one is interested in recovering, e.g., the state\n% noise that enters and perturbs the system. In particular, posterior\n% covariances are attached to state noise, which means that statistical\n% inference can be performed in the usual way...\n% IN:\n%   - posterior/out: output structures of VBA_NLStateSpaceModel.m\n% OUT:\n%   - ehat/etahat: the 1st-order moment of the posterior density on the\n%   measurement (resp. state) noise\n%   - v_e/v_eta: the second-order moment of the posterior density on the\n%   measurement (resp. state) noise\n\ndim = out.dim;\noptions = out.options;\nu = out.u;\ny = out.y;\n\nehat = zeros(dim.p,dim.n_t);\nv_e = cell(1,dim.n_t);\netahat = zeros(dim.n,dim.n_t);\nv_eta = cell(1,dim.n_t);\n\n% initial condition\nif dim.n > 0\n    [fx,dfdx,dfdp] = VBA_evalFun('f',posterior.muX0,posterior.muTheta,u(:,1),options,dim,1);\n    etahat(:,1) = posterior.muX(:,1) - fx;\n    if isinf(posterior.a_alpha) && isequal(posterior.b_alpha,0)\n        v_eta{1} = zeros(dim.n,dim.n);\n    else\n        v_eta{1} = posterior.SigmaX.current{1} ...\n            + dfdx'*posterior.SigmaX0*dfdx;\n        if dim.n_theta > 0\n            v_eta{1} = v_eta{1} + dfdp'*posterior.SigmaTheta*dfdp;\n        end\n    end\nend\n[gx,dgdx,dgdp] = VBA_evalFun('g',posterior.muX(:,1),posterior.muPhi,u(:,1),options,dim,1);\nehat(:,1) = y(:,1) - gx;\nv_e{1} = zeros(dim.p,dim.p);\nif dim.n > 0\n    v_e{1} = dgdx'*posterior.SigmaX.current{1}*dgdx;\nend\nif dim.n_phi > 0\n    v_e{1} = v_e{1} + dgdp'*posterior.SigmaPhi*dgdp;\nend\n\n% loop over time samples\nfor t = 2:dim.n_t\n    if dim.n > 0\n        [fx,dfdx,dfdp] = VBA_evalFun('f',posterior.muX(:,t-1),posterior.muTheta,u(:,t),options,dim,t);\n        etahat(:,t) = posterior.muX(:,t) - fx;\n        if isinf(posterior.a_alpha) && isequal(posterior.b_alpha,0)\n            v_eta{t} = zeros(dim.n,dim.n);\n        else\n            P = [-dfdx',eye(dim.n)];\n            jointCov = ...\n                [ posterior.SigmaX.current{t}  posterior.SigmaX.inter{t-1}'\n                posterior.SigmaX.inter{t-1}  posterior.SigmaX.current{t-1} ];\n            v_eta{t} = P*jointCov*P';\n            if dim.n_theta > 0\n                v_eta{t} = v_eta{t} + dfdp'*posterior.SigmaTheta*dfdp;\n            end\n        end\n    end\n    [gx,dgdx,dgdp] = VBA_evalFun('g',posterior.muX(:,t),posterior.muPhi,u(:,t),options,dim,t);\n    ehat(:,t) = y(:,t) - gx;\n    v_e{t} = zeros(dim.p,dim.p);\n    if dim.n > 0\n        v_e{t} = dgdx'*posterior.SigmaX.current{t}*dgdx;\n    end\n    if dim.n_phi > 0\n        v_e{t} = v_e{t} + dgdp'*posterior.SigmaPhi*dgdp;\n    end\nend\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/VBA_getNoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478256, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5633418684151322}}
{"text": "\nfunction [R,current_eps]=DT_USTM(snrdB,T,L,Mt,Mr,epsilon,prec,filename)\n%\n% Function to compute the DT lower bound for a Rayleigh block-fading\n% channel with no CSI at transmitter and receiver. The bound assumes that\n% USTM is chosen as input distribution \n% snrdB: SNR in dB\n% Mt: number of transmit antennas \n% Mr: number of receive antennas (Mt<=Mr); \n% T: size of coherence interval \n% L: number of independent coherence intervals; L*T is the blocklength\n% epsilon: maximal block error probability\n% prec: it controls the number of samples for the Monte Carlo simulation; Note nsamples=2^prec; One should have nsamples>> 100 x 1/epsilon\n% filename: data file where the samples of the information density are saved for possible future refinements. \n%\n% The outputs of the program are\n% R: R^*(T*L,current_eps,snrdB)\n% current_eps: actual upper bound on the maximal error probability \n%\n%-------------------------------------------------------------------\n%                       SET-UP PARAMETERS\n%-------------------------------------------------------------------\n\nSAVE=0; % if this flag is active the samples of the information density are saved for possibe further refinemes\nMAT=0; % save with .mat extension\n\nK = 2^prec; % number of monte carlo simulations (it should be at least 100 x 1/epsilon)\nrho = 10.^(snrdB/10); % SNR in linear scale\n\n%-------------------------------------------------------------------\n%                       MONTE CARLO SIMULATION\n%-------------------------------------------------------------------\nI = zeros(K,1); %allocate for the montecarlo runs\n%-------------------------------------------------------------------\n%                       CONSTANTS\n%-------------------------------------------------------------------\nrho_tilde = T*rho/Mt; \nD= [sqrt(1+rho_tilde)*eye(Mt), zeros(Mt,T-Mt);\n    zeros(T-Mt,Mt), eye(T-Mt)]; % D matrix (covariance matrix of equivalent noise)\n\nlambda=1+rho_tilde;\nlambda1=1/lambda;\nlambda2=rho_tilde*lambda1;\nc2 = logComplexGammaRatio(Mt,Mr,T); %gamma constant\nc1 = Mt*(T-Mt)*log(lambda2); % SNR constant\nconst = c1+c2;\n\nnoise_norm=sqrt(.5);\n\n\n%-------------------------------------------------------------------\n%                       MONTE CARLO\n%-------------------------------------------------------------------\n\nfor k = 1:K %do K montecarlo runs\n        i_L = 0;   \n        Z = (randn(T,Mr,L)+1i*randn(T,Mr,L))*noise_norm;\n        for l = 1:L %Create each realization\n            Sigma = svd(D*Z(:,:,l)).^2;    \n            if (Mt==1)\n                M = createMalt(Mt,Mr,T,Sigma,lambda2); %create  matrix\n                logdetM=log(det(M))+Sigma(1)*lambda2-(T-Mr)*log(Sigma(1)); \n                partial_sum=sum(Sigma)-logdetM;\n            elseif Mr >= Mt\n                M = createM_rx_larger(Mt,Mr,T,Sigma,lambda2);\n                logdetM=logdet(M);\n                logdetSigma = (T-Mr)*sum(log(Sigma));% compute logdet(Sigma^(T-M))\n                partial_sum=lambda1*sum(Sigma) - logdetM +logdetSigma;\n            else\n                logdetM = createM_tx_larger(Mt, Mr, T, Sigma, lambda2); %already in log domain\n                logdetSigma = (T-Mr)*sum(log(Sigma));% compute logdet(Sigma^(T-M))\n                const2 = sum(gammaln(T-((Mt+1):T)+1)) - sum(gammaln(1:(T-Mr)));\n                partial_sum = sum(Sigma) -logdetM + logdetSigma - const2;\n            end            \n            \n            vanderTerm = det(vander(Sigma)); %get the determinant of the vandermode matrix\n            TraceZ=real(trace(Z(:,:,l)'*Z(:,:,l)));\n            \n            i_temp = const- TraceZ  +partial_sum + log(vanderTerm);  %Information density for time l (i(x_l, y_l)\n            i_L = i_L + i_temp; %add it to the total i_L \n        end\n\n        I(k) =  i_L; %put all computations on a pile to compute the average later\n        \nend\n\n \n\n\nif (SAVE==1) \n  if (MAT==1)\n    save(filename,'I')\n  else\n    save(filename,'I','-ascii','-append')\n  end\nend\n\n\n\n%---------------------------------------\n%   START SEARCHING FOR THE RATE\n%---------------------------------------  \n\nI=sort(I);\n\nKcurrent=length(I); % redefine K to account for append\n\ncurrent_prec=floor(log2(Kcurrent)); % actual precision\n\nK=2^(current_prec); % round off K to avoid search errors\n\n\nstep=K/2;\nindex=step;\n\nonevec=ones(K,1);\n\nwhile(step>1),\n    \n   th=I(index);\n   \n   current_eps=sum(exp(-max(0,I-th)))/K;\n   \n   step=step/2;\n   \n   if current_eps> epsilon,\n       \n       index=index-step;\n       \n   else\n       \n       index=index+step;\n       \n   end\n   \nend\n\ncurrent_eps=sum(exp(-max(0,I-I(index))))/K;\n\nif (I(index)>500),\n\n  R=I(index)/(L*T*log(2));\n  \nelse\n\n  R=log2(exp(I(index))+1)/(L*T); % factor 2 removed from DT bound to account for max error probability\n\nend\n\nend\n\n\nfunction val = logComplexGammaRatio(Mt,Mr,T)\n    k=T-Mt+1:1:T;\n    val = -sum(gammaln(k));\n    r=1:1:Mt;\n    val=val+sum(gammaln(r));\nend\n\n\n\n\nfunction M = createMalt(Mt,Mr,T,Sigma,lambda)\nM = nan(Mr,Mr); %(l is the row, k is the column)\nfor l = 1:Mr\n    for k=1:Mt\n        M(l,k)= exp((Mt-k)*log(Sigma(l)) + log(gammainc(lambda*Sigma(l),T+k-Mt-Mr)) + lambda*(Sigma(l)-Sigma(1)) + (T-Mr)*log(Sigma(1)/Sigma(l)));\n    end\n    \n    for k=Mt+1:1:Mr\n        M(l,k)= Sigma(l)^(Mr-k);\n    end\nend\nend\n\nfunction M = createM_rx_larger(Mt,Mr,T,Sigma,lambda)\nM = nan(Mr,Mr); %(l is the row, k is the column)\nP=Mr;\n\nfor l = 1:Mr\n    for k=1:Mt\n        M(l,k)=(Sigma(l)^(Mt-k))*gammainc(lambda*Sigma(l),T+k-Mt-P);\n    end\n    \n    for k=Mt+1:Mr\n        M(l,k)=exp((T-k)*log(Sigma(l)) -Sigma(l)*lambda); % case Mt<Mr\n    end\nend\n\nend\n\nfunction C = createM_tx_larger(M,N,T,Sigma,lambda)\ninf_flag = 0;\nA = zeros(max(M,N), max(M,N));\n\nfor i = 1:M\n    for j = 1:M\n        if j <= N\n            if Sigma(j) == 0 && M-i == 0\n                A(i,j) = exp(lambda*Sigma(j) + log(gammainc(Sigma(j)*lambda, T-N-M+i-1)));\n            else\n                if (T-N-M+i-1) > 0\n                    A(i,j) = exp((M-i)*log(Sigma(j))  + lambda*Sigma(j) + log(gammainc(Sigma(j)*lambda, T-N-M+i-1)));\n                else\n                    A(i,j) = exp((M-i)*log(Sigma(j))  + lambda*Sigma(j));\n                end\n            end\n            if isinf(A(i,j)) == 1\n                inf_flag = 1;\n                break;\n            end\n            %A(i,j) = exp((M-i)*log(lambda(j))  + gammaln(T-M) +  log(gammainc(lambda(j)*p, T+i-2*M)));\n        else\n            A(i,j) = exp((T-j-(M-i))*log(lambda) + sum(log(T-j-(0:(M-i-1)))));\n            %A(i,j) = exp((T-j-(M-i))*log(p)  + sum(log(T-j-(0:(M-i-1)))));\n        end\n    end\n    if inf_flag == 1\n        break;\n    end\nend\nif inf_flag == 1\n    for i = 1:M\n        for j = 1:M\n            if j <= N\n                if (T-N-M+i-1) > 0\n                    A(i,j) = exp((M-i)*log(Sigma(j))  +  log(gammainc(Sigma(j)*lambda, (T-N-M+i-1))));\n                else\n                    A(i,j) = exp((M-i)*log(Sigma(j)));\n                end\n            else\n                A(i,j) = exp((T-j-(M-i))*log(lambda)  + sum(log(T-j-(0:(M-i-1)))));\n            end\n        end\n    end\nend\n\nif inf_flag == 0\n    C = logdet(A);\nelse\n    C = logdet(A) + lambda*sum(Sigma);\nend\nend\n\nfunction v = logdet(A, op)\n\nassert(isfloat(A) && ndims(A) == 2 && size(A,1) == size(A,2), ...\n    'logdet:invalidarg', ...\n    'A should be a square matrix of double or single class.');\n\nif nargin < 2\n    use_chol = 0;\nelse\n    assert(strcmpi(op, 'chol'), ...\n        'logdet:invalidarg', ...\n        'The second argument can only be a string ''chol'' if it is specified.');\n    use_chol = 1;\nend\n\n%% computation\n\nif use_chol\n    v = 2 * sum(log(diag(chol(A))));\nelse\n    [L, U, P] = lu(A);\n    du = diag(U);\n    c = det(P) * prod(sign(du));\n    v = log(c) + sum(log(abs(du)));\nend\nend\n\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/rayleigh-block-fading-no-csi/DT_USTM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5633418648432018}}
{"text": "function [accuracy,predictlabel,elapse] = CSRKDApredict(fea, gnd, model)\n% SRKDApredict: Spectral Regression Kernel Discriminant Analysis Prediction\n%               SRKDApredict use SRKDA as a classifier. It used the nearest\n%               center rule in the SRKDA subspace for classification.\n%\n%       [predictlabel,accuracy,elapse] = SRKDApredict(fea, gnd, model);\n% \n%             Input:\n%\n%               fea     - data matrix. Each row is a data point. \n%               gnd     - Label vector of fea.\n%             model     - model trained by SRKDAtrain.m \n%\n%             Output:\n%             \n%            accuracy   - classification accuracy\n%         predictlabel  - predict label for fea\n%             elapse    - running time.\n%\n%    Examples:\n%\n%\n% See also SRKDAtrain, KSR, KSR_caller\n%\n%Reference:\n%\n%   [1] Deng Cai, Xiaofei He, and Jiawei Han. \"Speed Up Kernel Discriminant\n%   Analysis\", The VLDB Journal, vol. 20, no. 1, pp. 21-33, January, 2011.\n%\n%   [2] Deng Cai, Xiaofei He and Jiawei Han, \"SRDA: An Efficient Algorithm for\n%   Large Scale Discriminant Analysis\" IEEE Transactions on Knowledge and\n%   Data Engineering, vol. 20, no. 1, pp. 1-12, January, 2008.  \n%\n%   [3] V. Sindhwani, P. Niyogi, M. Belkin, \"Beyond  the  Point  Cloud:  from\n%   Transductive  to  Semi-supervised  Learning\", ICML 2005.\n%\n%   version 2.0 --December/2011\n%   version 1.0 --May/2006 \n%\n%   Written by Deng Cai (dengcai AT gmail.com)\n%\n\nMAX_MATRIX_SIZE = 8000; % You can change this number based on your memory.\n\n\n\nnTrain = size(model.Landmark,1);\nnTest = size(fea,1);\nnBlock = ceil(MAX_MATRIX_SIZE*MAX_MATRIX_SIZE/nTrain);\nEmbed_Test = zeros(nTest,size(model.projection,2));\nfor i = 1:ceil(nTest/nBlock)\n    if i == ceil(nTest/nBlock)\n        smpIdx = (i-1)*nBlock+1:nTest;\n    else\n        smpIdx = (i-1)*nBlock+1:i*nBlock;\n    end\n    KTest= constructKernel(fea(smpIdx,:),model.Landmark,model.options);\n    Embed_Test(smpIdx,:) = KTest*model.projection;\n    clear KTest;\nend\n\nD = EuDist2(Embed_Test,model.ClassCenter,0);\n[dump, idx] = min(D,[],2);\npredictlabel = model.ClassLabel(idx);\n\naccuracy = 1 - length(find(predictlabel-gnd))/nTest;\n\n\n\n\n\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/SubspaceLearning/CSRKDApredict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5633418648432017}}
{"text": "function value = givens_condition ( n )\n\n%*****************************************************************************80\n%\n%% GIVENS_CONDITION returns the L1 condition of the GIVENS matrix.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 April 2015\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 L1 condition.\n%\n  a_norm = n * n;\n\n  if ( n == 1 )\n    b_norm = 1.0;\n  else\n    b_norm = 2.0;\n  end\n\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/givens_condition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5632715081252349}}
{"text": "function [ n_data, x, fx ] = sqrt_values ( n_data )\n\n%*****************************************************************************80\n%\n%% SQRT_VALUES returns some values of the square root function.\n%\n%  Discussion:\n%\n%    SQRT(X) = positive real number Y such that Y * Y = X.\n%\n%    In Mathematica, the function can be evaluated by:\n%\n%      Sqrt[x]\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    19 September 2004\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Milton Abramowitz and Irene Stegun,\n%    Handbook of Mathematical Functions,\n%    US Department of Commerce, 1964.\n%\n%    Stephen Wolfram,\n%    The Mathematica Book,\n%    Fourth Edition,\n%    Wolfram Media / Cambridge University Press, 1999.\n%\n%  Parameters:\n%\n%    Input/output, integer N_DATA.  The user sets N_DATA to 0 before the\n%    first call.  On each call, the routine increments N_DATA by 1, and\n%    returns the corresponding data; when there is no more data, the\n%    output value of N_DATA will be 0 again.\n%\n%    Output, real X, the argument of the function.\n%\n%    Output real FX, the value of the function.\n%\n  n_max = 14;\n\n  fx_vec = [ ...\n     0.0000000000000000E+00, ...      \n     0.9000000040950000E-04, ...\n     0.3000000000000000E+00, ...\n     0.3162277660168379E+00, ...\n     0.6324555320336759E+00, ...\n     0.1000000000000000E+01, ...\n     0.1414213562373095E+01, ...\n     0.1732050807568877E+01, ...\n     0.1772453850905516E+01, ...\n     0.4358898943540674E+01, ...\n     0.5385164807134504E+01, ...\n     0.8426149773176359E+01, ...\n     0.9848857801796105E+01, ...\n     0.1111111106055556E+05 ];\n\n  x_vec = [ ...\n     0.0000000000000000E+00, ...\n     0.8100000073710001E-08, ...\n     0.9000000000000000E-01, ...\n     0.1000000000000000E+00, ...\n     0.4000000000000000E+00, ...\n     0.1000000000000000E+01, ... \n     0.2000000000000000E+01, ...\n     0.3000000000000000E+01, ...\n     0.3141592653589793E+01, ...\n     0.1900000000000000E+02, ...\n     0.2900000000000000E+02, ...\n     0.7100000000000000E+02, ...\n     0.9700000000000000E+02, ...\n     0.1234567890000000E+09 ];\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/sqrt_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.5632715081252347}}
{"text": "function varargout = ellipseAsPolygon(ellipse, N)\n%ELLIPSEASPOLYGON Convert an ellipse into a series of points.\n%\n%   Deprecated, use ellipseToPolygon instead.\n%\n%   P = ellipseAsPolygon(ELL, N);\n%   converts ELL given as [x0 y0 a b] or [x0 y0 a b theta] into a polygon\n%   with N edges. The result P is (N+1)-by-2 array containing coordinates\n%   of the N+1 vertices of the polygon.\n%   The resulting polygon is closed, i.e. the last point is the same as the\n%   first one.\n%\n%   P = ellipseAsPolygon(ELL);\n%   Use a default number of edges equal to 72. This result in one piont for\n%   each 5 degrees.\n%   \n%   [X Y] = ellipseAsPolygon(...);\n%   Return the coordinates o fvertices in two separate arrays.\n%\n%   See also:\n%   ellipses2d, circleAsPolygon, rectAsPolygon, drawEllipse\n\n% ------\n% Author: David Legland \n% e-mail: david.legland@inrae.fr\n% Created: 2005-04-06\n% Copyright 2005 INRA - TPV URPOI - BIA IMASTE\n\nwarning('matGeom:deprecated', ...\n    'function \"ellipseAsCurve\" is deprecated, use \"ellipseToPolygon\" instead');\n\n% format output\nif nargout <= 1\n    varargout = {ellipseToPolygon(ellipse, N)};\nelse\n    [x, y] = ellipseToPolygon(ellipse, N);\n    varargout = {x, y};\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/deprecated/geom2d/ellipseAsPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5632715041583626}}
{"text": "% Measure PSS correlations in the presence of a frequency offset.\n%n_id_2=0;\n\n% Copyright 2012 Evrytania LLC (http://www.evrytania.com)\n%\n% Written by James Peroulas <james@evrytania.com>\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Affero 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 Affero General Public License for more details.\n%\n% You should have received a copy of the GNU Affero General Public License\n% along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nfreq_off_set=linspace(-30e3,30e3,1001);\ntime_off_set=-3000:3000;\n\nn_freqs=length(freq_off_set);\nn_times=length(time_off_set);\n\npss_td=NaN(3,144+2048+0*2048);\nfor n_id_2=0:2\n  pss_freq=pss(n_id_2);\n  pss_freq=[0 pss_freq(32:end) zeros(1,2048-73+5+5) pss_freq(1:31)];\n  pss_td(n_id_2+1,145:end)=[idft(pss_freq)*sqrt(2048/62) zeros(1,0*2048)];\n  pss_td(n_id_2+1,1:144)=pss_td(n_id_2+1,end-143:end);\n  pss_td(n_id_2+1,:)=pss_td(n_id_2+1,:)/sqrt(sigpower(pss_td(n_id_2+1,:)));\nend\n\n% Frequency domain correlations\nfigure(1);\nlog_xc_freq=NaN(3,n_freqs);\nfor n_id_2=0:2\n  for t=1:n_freqs\n    freq=freq_off_set(t);\n    log_xc_freq(n_id_2+1,t)=sum(conj(pss_td(n_id_2+1,:)).*fshift(pss_td(n_id_2+1,:),freq/(fs_lte/2)))/(2048+144);\n  end\nend\nplot(freq_off_set,db20(abs(transpose(log_xc_freq))));\n%ylim([-20 5]);\ndrawnow;\nzgo;\n\n% Time domain auto correlations\npss_td_ext=[pss_td zeros(3,(2048+144)*2)];\nlog_xc_td=NaN(3,n_times);\nfigure(2);\nfor n_id_2=0:2\n  for t=1:n_times\n    to=time_off_set(t);\n    log_xc_td(n_id_2+1,t)=sum(conj(pss_td_ext(n_id_2+1,:)).*tshift(pss_td_ext(n_id_2+1,:),to))/(2048+144);\n  end\nend\nplot(time_off_set,db20(abs(transpose(log_xc_td))));\n%ylim([-50 5]);\ndrawnow;\nzgo;\n\n% Time domain cross correlations\nlog_xc_td_cross=NaN(3,n_times);\nlog_xc_td_cross_max16=NaN(3,n_times);\nfigure(3);\nxc_set=[1 2;1 3;2 3]-1;\nfor k=1:3\n  n_id_2_1=xc_set(k,1);\n  n_id_2_2=xc_set(k,2);\n  for t=1:n_times\n    to=time_off_set(t);\n    log_xc_td_cross(k,t)=sum(conj(pss_td_ext(n_id_2_1+1,:)).*tshift(pss_td_ext(n_id_2_2+1,:),to))/(2048+144);\n  end\n  for t=1:n_times\n    log_xc_td_cross_max16(k,t)=max(log_xc_td_cross(k,max([t-32 1]):min([t+80 n_times])));\n  end\nend\nplot(time_off_set,db20(abs(transpose(log_xc_td_cross))), ...\ntime_off_set,db20(abs(transpose(log_xc_td_cross_max16))));\nlegend('0 1','0 2','2 3','location','se');\n%ylim([-50 5]);\ndrawnow;\nzgo;\n\n\n", "meta": {"author": "JiaoXianjun", "repo": "rtl-sdr-LTE", "sha": "037a25f164f17b1a1d82e2eb02285550f50af9b9", "save_path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE", "path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE/rtl-sdr-LTE-037a25f164f17b1a1d82e2eb02285550f50af9b9/matlab/pss_foff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.563212934954891}}
{"text": "%%%% Create animation for a 2-link serial chain manipiulator\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\nfunction [aviobj]= CREATE_ANIME_1(aviobj,T,th1,x2,y2,th2,h)\n\nglobal l1 lc1 l2 lc2\nfigure(h)\nZ0=[0 0]; %%% Point of suspension\nfor i=1:length(T)\n    \n    c1=cos(th1(i));\n    c2=cos(th2(i));\n    s1=sin(th1(i));\n    s2=sin(th2(i));\n    %%% Plotting Link - 1\n    Z1= Z0 + [l1*c1, l1*s1];% Coordinate of the hanging end link 1\n    plot([Z0(1),Z1(1)],[Z0(2),Z1(2)],'b','linewidth',4);\n    hold on\n    Z1m= Z0 + [lc1*c1, lc1*s1];% Coordinate of the CM of link 1\n    plot(Z1m(1), Z1m(2),'r*'); %Plots mid point\n    plot(Z0(1),Z0(2),'k*'); % Plots point of suspension\n    \n    %%% Plotting Link - 2\n    Z2m = [x2(i), y2(i)];% Coordinate of the CM of link 2\n    Z2l = Z2m - [lc2*c2, lc2*s2]; % Coordinate of source-end of link - 2\n    Z2r = Z2m + [(l2-lc2)*c2, (l2-lc2)*s2]; % Coordinate of effector-end of link-2 \n    plot([Z2l(1),Z2r(1)],[Z2l(2),Z2r(2)],'m','linewidth',4);\n    plot(Z2m(1), Z2m(2),'r*'); %Plots mid point\n    xlim([-4,4]);\n    ylim([-4,4]);\n%     title('Midterm Animation');\n    xlabel('X-axis');\n    ylabel('Y-axis');\n    grid on\n    hold off\n    pause(0.01);     %Stop execution for 0.01 to make animation visible\n    frame= getframe(gcf);   %Step 2: Grab the frame\n    aviobj = addframe(aviobj,frame); % Step 3: Add frame to avi object\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/24246-dynamic-control-of-two-link-manipulator-with-redundant-coordinates/2 Link Dynamic Control/Code/CREATE_ANIME_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.5631685424591193}}
{"text": "function test_stepsize_alg_demo()\n% demonstration file for original stepsize algorithm.\n%\n% This file illustrates how to set user's own stepsize algorithm in case of linear\n% regression problem. This demonstrates SGD and SVRG algorithms.\n%\n% This file is part of SGDLibrary.\n%\n% Created by H.Kasai on Sep. 25, 2017\n\n\n    clc;\n    clear;\n    close all;\n\n    %% generate synthetic data        \n    % set number of dimensions\n    d = 10;\n    % set number of samples    \n    n = 1000;\n    % generate data\n    data = logistic_regression_data_generator(n, d);\n        \n    \n    %% define problem definitions\n    problem = logistic_regression(data.x_train, data.y_train, data.x_test, data.y_test); \n    \n    \n    %% perform algorithms SGD and SVRG \n    options.w_init = data.w_init;    \n    options.step_init = 0.01;  \n    options.verbose = 2;\n    \n    options.step_alg = 'fix';\n    [w_sgd_fix, info_sgd_fix] = sgd(problem, options); \n    \n    options.step_alg = 'decay';\n    [w_sgd_decay, info_sgd_decay] = sgd(problem, options);      \n    \n    options.step_alg = 'decay-2';\n    [w_sgd_decay2, info_sgd_decay2] = sgd(problem, options);       \n    \n    options.stepsizefun = @my_stepalg;  % set my_stepalg (user-defined stepsize algorithm)\n    [w_sgd_my, info_sgd_my] = sgd(problem, options);      \n    \n    \n    %% display cost/optimality gap vs number of gradient evaluations\n    display_graph('grad_calc_count','cost', {'SGD (fix)','SGD (decay)', 'SGD (decay-2)', 'SGD (My stepsize algorithm)'}, ...\n            {w_sgd_fix, w_sgd_decay w_sgd_decay2, w_sgd_my}, {info_sgd_fix, info_sgd_decay, info_sgd_decay2, info_sgd_my});\n\nend\n\n    \n%% define user-defined stepsize algorithm\nfunction step = my_stepalg(iter, options)\n    step = options.step_init / (10 + iter*0.5);\nend     \n\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/sgd_test/test_stepsize_alg_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.5631685383940054}}
{"text": "function tetrahedron_arbq_rule_test02 ( degree, n, header )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_ARBQ_RULE_TEST02 gets a rule and writes it to a file.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU GPL license.\n%\n%  Modified:\n%\n%    08 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 <= 15.\n%\n%    Input, integer N, the number of nodes to be used by the rule.\n%\n%    Input, string HEADER, an identifier for the filenames.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TETRAHEDRON_ARBQ_RULE_TEST02\\n' );\n  fprintf ( 1, '  Get a quadrature rule for the tetrahedron.\\n' );\n  fprintf ( 1, '  Then write it to a file.\\n' );\n  fprintf ( 1, '  Polynomial exactness degree DEGREE = %d\\n', degree );\n%\n%  Retrieve a symmetric quadrature rule.\n%\n  [ x, w ] = tetrahedron_arbq ( degree, n );\n%\n%  Write the points and weights to a file.\n%\n  rule_filename = strcat ( header, '.txt' );\n\n  rule_unit = fopen ( rule_filename, 'wt' );\n  for i = 1 : n\n    fprintf ( rule_unit, '%g  %g  %g  %g\\n', x(1,i), x(2,i), x(3,i), w(i) );\n  end\n  fclose ( rule_unit );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Quadrature rule written to file \"%s\"\\n', rule_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/tetrahedron_arbq_rule/tetrahedron_arbq_rule_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.74316801430083, "lm_q1q2_score": 0.5631685381485205}}
{"text": "function [x,state] = struct_ctranspose(z,task)\n%STRUCT_CTRANSPOSE Complex conjugate transpose.\n%   [x,state] = struct_ctranspose(z) computes x as the complex conjugate\n%   transpose of z. The structure state stores information which is reused\n%   in computing the right and left Jacobian-vector products.\n%\n%   struct_ctranspose(z,task) computes the right or left Jacobian-vector\n%   product of this transformation, depending on the structure task. Use\n%   the structure state and add the field 'r' of the same shape as z or the\n%   field 'l' of the same shape as x to obtain the structure task for\n%   computing the right and left Jacobian-vector products\n%   \n%      (dF(:)/dz(:).')*task.r(:) and\n%      (dF(:)/dz(:).')'*task.l(:) + conj((dF(:)/dconj(z(:)).')'*task.l(:)),\n%\n%   respectively. Here, F(z) represents this transormation, (:) signifies\n%   vectorization and the derivative w.r.t. z (conj(z)) is a partial\n%   derivative which treats conj(z) (z) as constant. The output has the\n%   same shape as x or z for the right and left Jacobian-vector products,\n%   respectively.\n%   \n%   See also struct_conj, struct_transpose.\n\n%   Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n%            Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)\n%            Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)\n%\n%   References:\n%   [1] L. Sorber, M. Van Barel, L. De Lathauwer, \"Structured data fusion,\"\n%       ESAT-SISTA Internal Report 13-177, KU Leuven, 2013.\n\nif nargin < 2, task = []; end\nstate = [];\n\nif isempty(task) || (isempty(task.l) && isempty(task.r))\n    x = z';\nelseif ~isempty(task.r)\n    if ~isreal(z) || ~isreal(task.r)\n        error('struct_ctranspose:nonanalytic',['Nonanalytic objective ' ...\n            'functions are currently not supported in sdf_nls, please ' ...\n            'use sdf_minf instead.']);\n    end\n    x = task.r.';\nelseif ~isempty(task.l)\n    x = task.l';\nend\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+tensorlab/struct_ctranspose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5631685338379218}}
{"text": "function rf=v_lpcaa2rf(aa)\n%V_LPCAA2RF LPC: Convert vocal tract areas to reflection coefficients RF=(AA)\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: v_lpcaa2rf.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,p2]=size(aa);\nrf = (aa(:,2:p2)-aa(:,1:p2-1))./(aa(:,2:p2)+aa(:,1:p2-1));", "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_lpcaa2rf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5631584696149349}}
{"text": "function mColormap = gui_Colormap_HSVCut(nSize)\n\n% If size is not specified, set it to 256\nif nargin < 1\n  nSize = 256;\nend\n\nnTmpSize = floor(nSize/0.85);\nmColormap = hsv(nTmpSize);\nmColormap = mColormap(1:nSize,:);\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/danijel/gui/gui_Colormap_HSVCut.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5631584696149349}}
{"text": "function [sys,x0,str,ts]=NL_PID_3fal(t,x,u,flag,r0,h0,r1,h1,h,Bet,A,D)\nswitch flag,\n    case 0,\n        [sys,x0,str,ts]=mdlInitializeSizes(h);\n    case 2,\n        sys=mdlUpdates(x,u,r0,r1,h0,h1,h);\n    case 3,\n        sys=mdlOutputs(x,Bet,A,D);\n    case 4,\n        sys=mdlGetTimeOfNextVarHit(t,h);\n    case {1,9},\n        sys=[];\n    otherwise \n        error(['Unhandled flag=',num2str(flag)]);\nend\nfunction [sys,x0,str,ts]=mdlInitializeSizes(h)\n    sizes=simsizes;\n    sizes.NumContStates=0;\n    sizes.NumDiscStates=5;\n    sizes.NumOutputs=2;\n    sizes.NumInputs=2;\n    sizes.DirFeedthrough=1;\n    sizes.NumSampleTimes=1;\n    sys=simsizes(sizes);\n    x0=[0;0;0;0;0];\n    str=[];\n    ts=[h 0];  \nfunction sys=mdlUpdates(x,u,r0,r1,h0,h1,h)\n    fh0=fhan(x(1)-u(1),x(2),r0,h0);\n    x(1)=x(1)+h*x(2);\n    x(2)=x(2)+h*fh0;\n    fh1=fhan(x(3)-u(2),x(4),r1,h1);\n    x(3)=x(3)+h*x(4);\n    x(4)=x(4)+h*fh1;\n    x(5)=x(5)+h*(x(1)-x(3));\n    sys=x;\nfunction sys=mdlOutputs(x,Bet,A,D)   \n    sys(1)=Bet(1)*fal(x(5),A(1),D)+Bet(2)*fal(x(1)-x(3),A(2),D)+Bet(3)*fal(x(2)-x(4),A(3),D);    \n    sys(2)=x(1);\nfunction sys=mdlGetTimeOfNextVarHit(t,h)\n    sys=t+h;\nfunction y=fhan(x1,x2,r,h)\nd=r*h;\nd0=h*d;\ny=x1+h*x2;\na0=sqrt(d^2+8*r*abs(y));\nif abs(y)>d0\n    a=x2+(a0-d)*sign(y)/2;\nelse\n    a=x2+y/h;\nend\n\nif abs(a)>d\n    y=-r*sign(a);\nelse \n    y=-r*a/d;\nend \nfunction f=fal(e,a,d)\n    if abs(e)<d\n        f=e*d^(a-1);\n    else f=(abs(e))^a*sign(e);\n    end\n    \n    \n\n", "meta": {"author": "TianfaYao", "repo": "ADRC", "sha": "6f1f96ebda1684c44af4dec4214b4880f4aa8cec", "save_path": "github-repos/MATLAB/TianfaYao-ADRC", "path": "github-repos/MATLAB/TianfaYao-ADRC/ADRC-6f1f96ebda1684c44af4dec4214b4880f4aa8cec/\u8d3a\u5e86\u6bd5\u4e1a\u8bba\u6587ADRC\u5168\u96c6\u5305\u4ec5\u7528\u4e8e\u5185\u90e8\u5171\u4eab\u4e0d\u8981\u5916\u4f20/MyLibrary/NL_PID_3fal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5631584641643473}}
{"text": "function Lms = kappabeta_ach(Ns, epsil, P, hack)\n%\n% Compute achievability (lower) bound for log M. This is just a glue between kappa() and betaq_up_v2()\n%\n\nif (nargin < 4) || isempty(hack)\n\thack = 1;\nend\n\n\ntaus = linspace(0,1,40).*epsil; taus = taus(3:end-2);\n\nLms = [];\n\nfor n = Ns;\n\tdisp(sprintf('kappabeta_ach(): n = %d', n));\n\ttemp_lbs = []; \n\tfor tau = taus; \n\t\ttemp_lb = log2(kappa_inf(tau, P)) - betaq_up_v2(1-epsil+tau, n, P); \n\t\ttemp_lbs = [temp_lbs temp_lb]; \n\tend;\n\t[bb ind] = max(temp_lbs);\n\ttau = taus(ind);\n\tif (hack) \n\t\tkap = log2(kappa_inf(tau, P));\n\telse\n\t\tkap = log2(kappa(tau, n, P));\n\tend\n\tclb = kap - betaq_up_v2(1 - epsil + tau, n, P);\n\n\tLms = [Lms clb];\n\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/awgn/kappabeta_ach.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5631584477637736}}
{"text": "% This is a simplest implementation of the proposed RIFT algorithm. In this implementation,...\n% rotation invariance part and corner point detection are not included.\n\nclc;clear;close all;\nwarning('off')\n\naddpath sar-optical   % type of multi-modal data\n\nstr1='pair1.jpg';   % image pair\nstr2='pair2.jpg';\nim1 = im2uint8(imread(str1));\nim2 = im2uint8(imread(str2));\n\nif size(im1,3)==1\n    temp=im1;\n    im1(:,:,1)=temp;\n    im1(:,:,2)=temp;\n    im1(:,:,3)=temp;\nend\n\nif size(im2,3)==1\n    temp=im2;\n    im2(:,:,1)=temp;\n    im2(:,:,2)=temp;\n    im2(:,:,3)=temp;\nend\n\ndisp('RIFT feature detection and description')\n% RIFT feature detection and description\n[des_m1,des_m2] = RIFT_no_rotation_invariance(im1,im2,4,6,96);\n\ndisp('nearest matching')\n% nearest matching\n[indexPairs,matchmetric] = matchFeatures(des_m1.des,des_m2.des,'MaxRatio',1,'MatchThreshold', 100);\nmatchedPoints1 = des_m1.kps(indexPairs(:, 1), :);\nmatchedPoints2 = des_m2.kps(indexPairs(:, 2), :);\n[matchedPoints2,IA]=unique(matchedPoints2,'rows');\nmatchedPoints1=matchedPoints1(IA,:);\n\ndisp('outlier removal')\n%outlier removal\nH=FSC(matchedPoints1,matchedPoints2,'affine',2);\nY_=H*[matchedPoints1';ones(1,size(matchedPoints1,1))];\nY_(1,:)=Y_(1,:)./Y_(3,:);\nY_(2,:)=Y_(2,:)./Y_(3,:);\nE=sqrt(sum((Y_(1:2,:)-matchedPoints2').^2));\ninliersIndex=E<3;\ncleanedPoints1 = matchedPoints1(inliersIndex, :);\ncleanedPoints2 = matchedPoints2(inliersIndex, :);\n\ndisp('Show matches')\n% Show results\nfigure; showMatchedFeatures(im1, im2, cleanedPoints1, cleanedPoints2, 'montage');\n\ndisp('registration result')\n% registration\nimage_fusion(im2,im1,double(H));\n", "meta": {"author": "LJY-RS", "repo": "RIFT-multimodal-image-matching", "sha": "7ea830e2f13cc3c226f975fe9e98b7666a8f26fb", "save_path": "github-repos/MATLAB/LJY-RS-RIFT-multimodal-image-matching", "path": "github-repos/MATLAB/LJY-RS-RIFT-multimodal-image-matching/RIFT-multimodal-image-matching-7ea830e2f13cc3c226f975fe9e98b7666a8f26fb/RIFT_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5631584477149637}}
{"text": "function [Q, R] = gson(X)\n% Gram-Schmidt orthonormalization which produces the same result as [Q,R]=qr(X,0)\n% Written by Mo Chen (sth4nth@gmail.com).\n[d,n] = size(X);\nm = min(d,n);\nR = zeros(m,n);\nQ = zeros(d,0);\nfor i = 1:m\n    R(1:i-1,i) = Q'*X(:,i);\n    v = X(:,i)-Q*R(1:i-1,i);\n    R(i,i) = norm(v);\n    Q(:,i) = v/R(i,i);\nend\nR(:,m+1:n) = Q'*X(:,m+1:n);", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/common/gson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324611869563, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5631312793009073}}
{"text": "% Calculate channel taps based on the 4th or 6th OFDM symbol (both are ZC sequences)\n%\n% There is almost certainly a better way to do this, but this gets the job done\n%\n% @param zc_seq Frequency domain ZC sequence from OFDM symbol number 4 or 6 (all FFT bins, no cyclic prefix)\n% @param sample_rate Sample rate (in Hz) of `zc_seq`\n% @param symbol_idx Which symbol (must be 4 or 6) is in the `zc_seq` vector\n% @return taps Result of dividing `zc_seq` into a golden reference copy of the selected ZC sequence\nfunction [taps] = calculate_channel(zc_seq, sample_rate, symbol_idx)\n    assert(symbol_idx == 4 || symbol_idx == 6, \"Symbol index must be 4 or 6\");\n    fft_size = get_fft_size(sample_rate);\n    \n    % The golden reference needs to be in the frequency domain\n    gold_seq = fftshift(fft(reshape(create_zc(fft_size, symbol_idx), size(zc_seq))));\n    \n%     figure(400);\n%     subplot(1, 2, 1);\n%     plot(abs(gold_seq).^2)\n%     subplot(1, 2, 2);\n%     plot(abs(zc_seq).^2)\n\n    taps = gold_seq ./ zc_seq;\nend", "meta": {"author": "proto17", "repo": "dji_droneid", "sha": "6ecbd20bdb1babbe2481a3870221553a10cdfe21", "save_path": "github-repos/MATLAB/proto17-dji_droneid", "path": "github-repos/MATLAB/proto17-dji_droneid/dji_droneid-6ecbd20bdb1babbe2481a3870221553a10cdfe21/matlab/updated_scripts/calculate_channel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5631312793009072}}
{"text": "function lik = lik_binomial(varargin)\n%LIK_BINOMIAL  Create a Binomial likelihood structure \n%\n%  Description\n%    LIK = LIK_BINOMIAL creates Binomial likelihood structure.\n%\n%    The likelihood is defined as follows:\n%                  __ n\n%      p(y|f, z) = || i=1 [ p_i^(y_i)*(1-p_i)^(z_i-y_i)) * \n%                           gamma(z_i+1)/(gamma(y_i+1)*gamma(z_i-y_i+1))]\n%    where p_i = exp(f_i)/ (1+exp(f_i)) is the succes probability,\n%    which is a function of the latent variable f_i and z is a\n%    vector of numbers of trials. \n%\n%    When using Binomial likelihood you need to give the vector z\n%    as an extra parameter to each function that requires y also. \n%    For example, you should call gpla_e as follows\n%      gpla_e(w, gp, x, y, 'z', z)\n%\n%  See also\n%    GP_SET, LIK_*\n%\n\n% Copyright (c) 2009-2010 Jaakko Riihim\ufffdki & Jarno Vanhatalo\n% Copyright (c) 2010-2011 Aki Vehtari\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n  ip=inputParser;\n  ip.FunctionName = 'LIK_BINOMIAL';\n  ip.addOptional('lik', [], @isstruct);\n  ip.parse(varargin{:});\n  lik=ip.Results.lik;\n\n  if isempty(lik)\n    init=true;\n    lik.type = 'Binomial';\n  else\n    if ~isfield(lik,'type') || ~isequal(lik.type,'Binomial')\n      error('First argument does not seem to be a valid likelihood function structure')\n    end\n    init=false;\n  end\n\n  if init\n    % Set the function handles to the subfunctions\n    lik.fh.pak = @lik_binomial_pak;\n    lik.fh.unpak = @lik_binomial_unpak;\n    lik.fh.ll = @lik_binomial_ll;\n    lik.fh.llg = @lik_binomial_llg;    \n    lik.fh.llg2 = @lik_binomial_llg2;\n    lik.fh.llg3 = @lik_binomial_llg3;\n    lik.fh.tiltedMoments = @lik_binomial_tiltedMoments;\n    lik.fh.predy = @lik_binomial_predy;\n    lik.fh.predprcty = @lik_binomial_predprcty;\n    lik.fh.invlink = @lik_binomial_invlink;\n    lik.fh.recappend = @lik_binomial_recappend;\n  end\n\nend\n\nfunction [w,s] = lik_binomial_pak(lik)\n%LIK_BINOMIAL_PAK  Combine likelihood parameters into one vector.\n%\n%  Description \n%    W = LIK_BINOMIAL_PAK(LIK) takes a likelihood structure LIK\n%    and returns an empty verctor W. If Binomial likelihood had\n%    parameters this would combine them into a single row vector\n%    W (see e.g. likelih_negbin). This is a mandatory subfunction \n%    used for example in energy and gradient computations.\n%\n%  See also\n%    LIK_NEGBIN_UNPAK, GP_PAK\n\n  w = []; s = {};\nend\n\n\nfunction [lik, w] = lik_binomial_unpak(lik, w)\n%LIK_BINOMIAL_UNPAK  Extract likelihood parameters from the vector.\n%\n%  Description\n%    W = LIK_BINOMIAL_UNPAK(W, LIK) Doesn't do anything.\n% \n%    If Binomial likelihood had parameters this would extracts\n%    them parameters from the vector W to the LIK structure. \n%    This is a mandatory subfunction used for example in energy \n%    and gradient computations.\n%\n%  See also\n%    LIK_BINOMIAL_PAK, GP_UNPAK\n\n  lik=lik;\n  w=w;\n  \nend\n\n\n\nfunction ll = lik_binomial_ll(lik, y, f, z)\n%LIK_BINOMIAL_LL  Log likelihood\n%\n%  Description\n%    LL = LIK_BINOMIAL_LL(LIK, Y, F, Z) takes a likelihood\n%    structure LIK, succes counts Y, numbers of trials Z, and\n%    latent values F. Returns the log likelihood, log p(y|f,z).\n%    This subfunction is needed when using Laplace approximation\n%    or MCMC for inference with non-Gaussian likelihoods. This \n%    subfunction is also used in information criteria (DIC, WAIC)\n%    computations.\n%\n%  See also\n%    LIK_BINOMIAL_LLG, LIK_BINOMIAL_LLG3, LIK_BINOMIAL_LLG2, GPLA_E\n  \n  if isempty(z)\n    error(['lik_binomial -> lik_binomial_ll: missing z!'... \n           'Binomial likelihood needs the expected number of   '...\n           'occurrences as an extra input z. See, for         '...\n           'example, lik_binomial and gpla_e.             ']);\n  end\n  \n  expf = exp(f);\n  p = expf ./ (1+expf);\n  N = z;\n  ll =  sum(gammaln(N+1)-gammaln(y+1)-gammaln(N-y+1)+y.*log(p)+(N-y).*log(1-p));\nend\n\n\nfunction llg = lik_binomial_llg(lik, y, f, param, z)\n%LIK_BINOMIAL_LLG    Gradient of the log likelihood\n%\n%  Description \n%    LLG = LIK_BINOMIAL_LLG(LIK, Y, F, PARAM) takes a likelihood\n%    structure LIK, succes counts Y, numbers of trials Z and\n%    latent values F. Returns the gradient of the log likelihood\n%    with respect to PARAM. At the moment PARAM can be 'param' or\n%    'latent'. This subfunction is needed when using Laplace \n%    approximation or MCMC for inference with non-Gaussian \n%    likelihoods.\n%\n%  See also\n%    LIK_BINOMIAL_LL, LIK_BINOMIAL_LLG2, LIK_BINOMIAL_LLG3, GPLA_E\n\n  if isempty(z)\n    error(['lik_binomial -> lik_binomial_llg: missing z!'... \n           'Binomial likelihood needs the expected number of   '...\n           'occurrences as an extra input z. See, for         '...\n           'example, lik_binomial and gpla_e.             ']);\n  end\n  \n  switch param\n    case 'latent'\n      expf = exp(f);\n      N = z;\n      \n      llg = y./(1+expf) - (N-y).*expf./(1+expf);\n  end\nend\n\n\nfunction llg2 = lik_binomial_llg2(lik, y, f, param, z)\n%LIK_BINOMIAL_LLG2  Second gradients of the log likelihood\n%\n%  Description        \n%    LLG2 = LIK_BINOMIAL_LLG2(LIK, Y, F, PARAM) takes a\n%    likelihood structure LIK, succes counts Y, numbers of trials\n%    Z, and latent values F. Returns the Hessian of the log\n%    likelihood with respect to PARAM. At the moment PARAM can be\n%    only 'latent'. G2 is a vector with diagonal elements of the\n%    Hessian matrix (off diagonals are zero). This subfunction\n%    is needed when using Laplace approximation or EP for inference \n%    with non-Gaussian likelihoods.\n%\n%  See also\n%    LIK_BINOMIAL_LL, LIK_BINOMIAL_LLG, LIK_BINOMIAL_LLG3, GPLA_E\n\n  if isempty(z)\n    error(['lik_binomial -> lik_binomial_llg2: missing z!'... \n           'Binomial likelihood needs the expected number of    '...\n           'occurrences as an extra input z. See, for          '...\n           'example, lik_binomial and gpla_e.              ']);\n  end\n  \n  switch param\n    case 'latent'\n      expf = exp(f);\n      N = z;\n\n      llg2 = -N.*expf./(1+expf).^2;\n  end\nend\n\n\nfunction llg3 = lik_binomial_llg3(lik, y, f, param, z)\n%LIK_BINOMIAL_LLG3  Third gradients of the log likelihood\n%\n%  Description\n%    LLG3 = LIK_BINOMIAL_LLG3(LIK, Y, F, PARAM) takes a\n%    likelihood structure LIK, succes counts Y, numbers of trials\n%    Z and latent values F and returns the third gradients of the\n%    log likelihood with respect to PARAM. At the moment PARAM\n%    can be only 'latent'. G3 is a vector with third gradients.\n%    This subfunction is needed when using Laplace appoximation \n%    for inference with non-Gaussian likelihoods.\n%\n%  See also\n%    LIK_BINOMIAL_LL, LIK_BINOMIAL_LLG, LIK_BINOMIAL_LLG2, GPLA_E, GPLA_G\n  \n  if isempty(z)\n    error(['lik_binomial -> lik_binomial_llg3: missing z!'... \n           'Binomial likelihood needs the expected number of    '...\n           'occurrences as an extra input z. See, for          '...\n           'example, lik_binomial and gpla_e.              ']);\n  end\n  \n  switch param\n    case 'latent'\n      expf = exp(f);\n      N = z;\n      llg3 = N.*(expf.*(expf-1))./(1+expf).^3;\n  end\nend\n\nfunction [logM_0, m_1, sigm2hati1] = lik_binomial_tiltedMoments(lik, y, i1, sigm2_i, myy_i, z)\n%LIK_BINOMIAL_TILTEDMOMENTS  Returns the marginal moments for EP algorithm\n%\n%  Description\n%    [M_0, M_1, M2] = LIK_BINOMIAL_TILTEDMOMENTS(LIK, Y, I, S2,\n%    MYY, Z) takes a likelihood structure LIK, succes counts Y,\n%    numbers of trials Z, index I and cavity variance S2 and mean\n%    MYY. Returns the zeroth moment M_0, mean M_1 and variance\n%    M_2 of the posterior marginal (see Rasmussen and Williams\n%    (2006): Gaussian processes for Machine Learning, page 55).\n%    This subfunction is needed when using EP for inference with\n%    non-Gaussian likelihoods.\n%\n%  See also\n%    GPEP_E\n  \n%  if isempty(z)\n%    error(['lik_binomial -> lik_binomial_tiltedMoments: missing z!'... \n%           'Binomial likelihood needs the expected number of               '...\n%           'occurrences as an extra input z. See, for                     '...\n%           'example, lik_binomial and gpla_e.                         ']);\n%  end\n  \n  yy = y(i1);\n  N = z(i1);\n  logM_0=zeros(size(yy));\n  m_1=zeros(size(yy));\n  sigm2hati1=zeros(size(yy));  \n  \n  for i=1:length(i1)\n    % Create function handle for the function to be integrated\n    % (likelihood * cavity) and useful integration limits\n    [tf,minf,maxf]=init_binomial_norm(yy(i),myy_i(i),sigm2_i(i),N(i));\n    \n    % Integrate with quadrature\n    RTOL = 1.e-6;\n    ATOL = 1.e-10;\n    [m_0, m_1(i), m_2] = quad_moments(tf,minf, maxf, RTOL, ATOL);\n    sigm2hati1(i) = m_2 - m_1(i).^2;\n    \n    % If the second central moment is less than cavity variance\n    % integrate more precisely. Theoretically for log-concave\n    % likelihood should be sigm2hati1 < sigm2_i.\n    if sigm2hati1(i) >= sigm2_i(i)\n      ATOL = ATOL.^2;\n      RTOL = RTOL.^2;\n      [m_0, m_1(i), m_2] = quad_moments(tf, minf, maxf, RTOL, ATOL);\n      sigm2hati1 = m_2 - m_1(i).^2;\n      %    if sigm2hati1 >= sigm2_i\n      %      error('lik_binomial_tilted_moments: sigm2hati1 >= sigm2_i');\n      %    end\n    end\n    logM_0(i) = log(m_0);\n  end\nend\n\n\nfunction [lpy, Ey, Vary] = lik_binomial_predy(lik, Ef, Varf, yt, zt)\n%LIK_BINOMIAL_PREDY  Returns the predictive mean, variance and density of y\n%\n%  Description         \n%    [LPY] = LIK_BINOMIAL_PREDY(LIK, EF, VARF YT, ZT)\n%    Returns logarithm of the predictive density PY of YT, that is \n%        p(yt | y, zt) = \\int p(yt | f, zt) p(f|y) df.\n%    This requires also the succes counts YT, numbers of trials ZT.\n%    This subfunction is needed when computing posterior predictive \n%    distributions for future observations.\n%\n%    [LPY, EY, VARY] = LIK_BINOMIAL_PREDY(LIK, EF, VARF) takes a\n%    likelihood structure LIK, posterior mean EF and posterior\n%    Variance VARF of the latent variable and returns the\n%    posterior predictive mean EY and variance VARY of the\n%    observations related to the latent variables. This subfunction \n%    is needed when computing posterior predictive distributions for \n%    future observations.\n%        \n%\n%  See also \n%    GPEP_PRED, GPLA_PRED, GPMC_PRED\n\n  if isempty(zt)\n    error(['lik_binomial -> lik_binomial_predy: missing z!'... \n           'Binomial likelihood needs the expected number of       '...\n           'occurrences as an extra input z. See, for             '...\n           'example, lik_binomial and gpla_e.                 ']);\n  end\n  \n  if nargout > 1\n    nt=length(Ef);\n    Ey=zeros(nt,1);\n    EVary = zeros(nt,1);\n    VarEy = zeros(nt,1);\n    for i1=1:nt\n      ci = sqrt(Varf(i1));\n      F  = @(x)zt(i1)./(1+exp(-x)).*norm_pdf(x,Ef(i1),sqrt(Varf(i1)));\n      Ey(i1) = quadgk(F,Ef(i1)-6*ci,Ef(i1)+6*ci);\n      \n      F2  = @(x)zt(i1)./(1+exp(-x)).*(1-1./(1+exp(-x))).*norm_pdf(x,Ef(i1),sqrt(Varf(i1)));\n      EVary(i1) = quadgk(F2,Ef(i1)-6*ci,Ef(i1)+6*ci);\n      \n      F3  = @(x)(zt(i1)./(1+exp(-x))).^2.*norm_pdf(x,Ef(i1),sqrt(Varf(i1)));\n      VarEy(i1) = quadgk(F3,Ef(i1)-6*ci,Ef(i1)+6*ci) - Ey(i1).^2;\n    end\n    Vary = EVary+VarEy;\n  end\n  \n  nt=length(yt);\n  lpy=zeros(nt,1);\n  for i1=1:nt\n    ci = sqrt(Varf(i1));\n    F  = @(x)exp(gammaln(zt(i1)+1)-gammaln(yt(i1)+1)-gammaln(zt(i1)-yt(i1)+1) + yt(i1).*log(1./(1+exp(-x))) + (zt(i1)-yt(i1)).*log(1-(1./(1+exp(-x))))).*norm_pdf(x,Ef(i1),sqrt(Varf(i1)));\n    lpy(i1) = log(quadgk(F,Ef(i1)-6*ci,Ef(i1)+6*ci));\n  end\n  \nend\n\nfunction prctys = lik_binomial_predprcty(lik, Ef, Varf, zt, prcty)\n%LIK_BINOMIAL_PREDPRCTY  Returns the percentiled of predictive density of y\n%\n%  Description         \n%    PRCTY = LIK_BINOMIAL_PREDPRCTY(LIK, EF, VARF YT, ZT)\n%    Returns percentiles of the predictive density PY of YT, that is \n%    This requires also the succes counts YT, numbers of trials ZT. This\n%    subfunction is needed when using function gp_predprcty.\n%\n%  See also \n%    GP_PREDPCTY\n\n  if isempty(zt)\n    error(['lik_binomial -> lik_binomial_predprcty: missing z!'... \n           'Binomial likelihood needs the expected number of       '...\n           'occurrences as an extra input z. See, for             '...\n           'example, lik_binomial and gpla_e.                 ']);\n  end\n  \n  opt=optimset('TolX',.5,'Display','off');\n  nt=size(Ef,1);\n  prctys = zeros(nt,numel(prcty));\n  prcty=prcty/100;\n  for i1=1:nt\n    ci = sqrt(Varf(i1));\n    for i2=1:numel(prcty)\n      a=floor(fminbnd(@(a) (quadgk(@(f) binocdf(a,zt(i1),logitinv(f)).*norm_pdf(f,Ef(i1),ci),Ef(i1)-6*ci,Ef(i1)+6*ci,'AbsTol',1e-4)-prcty(i2)).^2,binoinv(prcty(i2),zt(i1),logitinv(Ef(i1)-1.96*ci)),binoinv(prcty(i2),zt(i1),logitinv(Ef(i1)+1.96*ci)),opt));\n      if quadgk(@(f) binocdf(a,zt(i1),logitinv(f)).*norm_pdf(f,Ef(i1),ci),Ef(i1)-6*ci,Ef(i1)+6*ci,'AbsTol',1e-4)<prcty(i2)\n        a=a+1;\n      end\n      prctys(i1,i2)=a;\n    end\n  end\nend\n\nfunction [df,minf,maxf] = init_binomial_norm(yy,myy_i,sigm2_i,N)\n%INIT_LOGIT_NORM\n%\n%  Description\n%    Return function handle to a function evaluating Binomial *\n%    Gaussian which is used for evaluating (likelihood * cavity)\n%    or (likelihood * posterior) Return also useful limits for\n%    integration. This is private function for lik_binomial. This\n%    subfunction is needed by subfunctions tiltedMoments and predy.\n%  \n% See also\n%   LIK_BINOMIAL_TILTEDMOMENTS, LIK_BINOMIAL_PREDY\n  \n% avoid repetitive evaluation of constant part\n  ldconst = gammaln(N+1)-gammaln(yy+1)-gammaln(N-yy+1) - log(sigm2_i)/2 - log(2*pi)/2;\n%   ldconst = log(factorial(N)/(factorial(yy)*factorial(N-yy))-log(sigm2_i)/2 -log(2*pi)/2;\n  \n % Create function handle for the function to be integrated\n  df = @binomial_norm;\n % use log to avoid underflow, and derivates for faster search\n  ld = @log_binomial_norm;\n  ldg = @log_binomial_norm_g;\n  ldg2 = @log_binomial_norm_g2;\n  \n  % Set the limits for integration\n  % Binomial likelihood is log-concave so the binomial_norm\n  % function is unimodal, which makes things easier\n  if yy==0 || yy==N\n    % with yy==0 or yy==N the mode of the likelihood is not defined\n    % use the mode of the Gaussian (cavity or posterior) as a first guess\n    modef = myy_i;\n  else\n    % use precision weighted mean of the Gaussian approximation of the\n    % binomial likelihood and Gaussian\n    mean_app = log(yy./(N-yy));\n    ld0=1/(1+exp(-mean_app));\n    ld1=(1-ld0)*ld0;\n    ld2=ld0-3*ld0^2+2*ld0^3;\n    var_app=inv(-( yy*(ld2*ld0-ld1^2)/ld0^2 + (N-yy)*(ld2*(ld0-1)-ld1^2)/(ld0-1)^2 ));\n    \n    modef = (myy_i/sigm2_i + mean_app/var_app)/(1/sigm2_i + 1/var_app);\n%     sigm_app = sqrt((1/sigm2_i + 1/var_app)^-1);\n  end\n  % find the mode of the integrand using Newton iterations\n  % few iterations is enough, since the first guess in the right direction\n  niter=3;       % number of Newton iterations\n  mindelta=1e-6; % tolerance in stopping Newton iterations\n  for ni=1:niter\n      g = ldg(modef);\n      h = ldg2(modef);\n      delta=-g/h;\n      modef=modef+delta;\n      if abs(delta)<mindelta\n          break\n      end\n  end\n  % integrand limits based on Gaussian approximation at mode\n  modes=sqrt(-1/h);\n  minf=modef-4*modes;\n  maxf=modef+4*modes;\n  modeld=ld(modef);\n  iter=0;\n  % check that density at end points is low enough\n  lddiff=12; % min difference in log-density between mode and end-points\n  minld=ld(minf);\n  step=1;\n  while minld>(modeld-lddiff)\n    minf=minf-step*modes;\n    minld=ld(minf);\n    iter=iter+1;\n    step=step*2;\n    if iter>100\n      error(['lik_negbin -> init_negbin_norm: ' ...\n             'integration interval minimun not found ' ...\n             'even after looking hard!'])\n    end\n  end\n  maxld=ld(maxf);\n  step=1;\n  while maxld>(modeld-lddiff)\n    maxf=maxf+step*modes;\n    maxld=ld(maxf);\n    iter=iter+1;\n    step=step*2;\n    if iter>100\n      error(['lik_negbin -> init_negbin_norm: ' ...\n             'integration interval maximun not found ' ...\n             'even after looking hard!'])\n    end\n  end\n  \n  \n  function integrand = binomial_norm(f)\n  % Logit * Gaussian\n    integrand = exp(ldconst + yy*log(1./(1.+exp(-f)))+(N-yy)*log(1-1./(1.+exp(-f)))...\n                   - 0.5 * (f-myy_i).^2./sigm2_i);\n%     integrand = exp(ldconst ...\n%                     +yy*log(x)+(N-yy)*log(1-x) ...\n%                     -0.5*(f-myy_i).^2./sigm2_i);\n    integrand(isnan(integrand))=0;\n  end\n  \n  function log_int = log_binomial_norm(f)\n  % log(Binomial * Gaussian)\n  % log_binomial_norm is used to avoid underflow when searching\n  % integration interval\n  \n    log_int = ldconst + yy*log(1./(1.+exp(-f)))+(N-yy)*log(1-1./(1.+exp(-f)))...\n                   - 0.5 * (f-myy_i).^2./sigm2_i;\n%     log_int = ldconst ...\n%               -log(1+exp(-yy.*f)) ...\n%               -0.5*(f-myy_i).^2./sigm2_i;\n  end\n  \n  function g = log_binomial_norm_g(f)\n  % d/df log(Binomial * Gaussian)\n  % derivative of log_logit_norm\n    g = -(f-myy_i)./sigm2_i - exp(-f).*(N-yy)./((1+exp(-f)).^2.*(1-1./(1+exp(-f)))) ...\n        + exp(-f).*yy./(1+exp(-f));\n%     g = yy./(exp(f*yy)+1)...\n%         + (myy_i - f)./sigm2_i;\n  end\n  \n  function g2 = log_binomial_norm_g2(f)\n  % d^2/df^2 log(Binomial * Gaussian)\n  % second derivate of log_logit_norm\n    g2 = - (1+exp(2.*f)+exp(f).*(2+N*sigm2_i)./((1+exp(f))^2*sigm2_i));\n%     a=exp(f*yy);\n%     g2 = -a*(yy./(a+1)).^2 ...\n%          -1/sigm2_i;\n  end\n  \nend\n\nfunction p = lik_binomial_invlink(lik, f, z)\n%LIK_BINOMIAL_INVLINK  Returns values of inverse link function\n%             \n%  Description \n%    P = LIK_BINOMIAL_INVLINK(LIK, F) takes a likelihood structure LIK and\n%    latent values F and returns the values of inverse link function P.\n%    This subfunction is needed when using gp_predprctmu. \n%\n%     See also\n%     LIK_BINOMIAL_LL, LIK_BINOMIAL_PREDY\n  \n  p = logitinv(f);\nend\n\nfunction reclik = lik_binomial_recappend(reclik, ri, lik)\n%RECAPPEND  Append the parameters to the record\n%\n%  Description \n%    RECLIK = GPCF_BINOMIAL_RECAPPEND(RECLIK, RI, LIK) takes a\n%    likelihood record structure RECLIK, record index RI and\n%    likelihood structure LIK with the current MCMC samples of\n%    the parameters. Returns RECLIK which contains all the old\n%    samples and the current samples from LIK. This subfunction \n%    is needed when using MCMC sampling (gp_mc).\n% \n%  See also\n%    GP_MC\n  \n  if nargin == 2\n    reclik.type = 'Binomial';\n\n    % Set the function handles\n    reclik.fh.pak = @lik_binomial_pak;\n    reclik.fh.unpak = @lik_binomial_unpak;\n    reclik.fh.ll = @lik_binomial_ll;\n    reclik.fh.llg = @lik_binomial_llg;    \n    reclik.fh.llg2 = @lik_binomial_llg2;\n    reclik.fh.llg3 = @lik_binomial_llg3;\n    reclik.fh.tiltedMoments = @lik_binomial_tiltedMoments;\n    reclik.fh.invlink = @lik_binomial_invlink;\n    reclik.fh.predprcty = @lik_binomial_predprcty;\n    reclik.fh.predy = @lik_binomial_predy;\n    reclik.fh.recappend = @likelih_binomial_recappend;\n    return\n  end\n\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/lik_binomial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246077301781, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5631312765036576}}
{"text": "function a = sin(a)\n%SIN          Gradient sine sin(a)\n%\n\n% written  10/16/98     S.M. Rump\n% modified 10/14/00     S.M. Rump  use Tony's trick\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/28/08     S.M. Rump  check for rounding to nearest improved\n% modified 10/08/08     S.M. Rump  improved sparse multiplication: not using intval data type\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  e = 1e-30;\n  if 1+e==1-e                           % fast check for rounding to nearest\n    rndold = 0;\n  else\n    rndold = getround;\n    setround(0)\n  end\n\n  N = getappdata(0,'INTLAB_GRADIENT_NUMVAR');\n\n  % use full(a.x(:)): cures Matlab V6.0 bug\n  % a=7; i=[1 1]; x=a(i), b=sparse(a); y=b(i)  yields row vector x but column vector y\n  % ax is full anyway\n  ax = cos(full(a.x(:)));\n  a.x = sin(a.x);\n  if issparse(a.dx)\n    sizeax = size(a.dx,1);\n    [ia,ja,sa] = find(a.dx);\n    if isa(a.x,'intval')\n      adx = times(ax(ia),sa,0);\n      if adx.complex\n        a.dx = intval( sparse(ia,ja,adx.mid,sizeax,N) , sparse(ia,ja,adx.rad,sizeax,N) , 'midrad' );\n      else\n        a.dx = intval( sparse(ia,ja,adx.inf,sizeax,N) , sparse(ia,ja,adx.sup,sizeax,N) , 'infsup' );\n      end\n    else\n      a.dx = sparse(ia,ja,ax(ia).*sa,sizeax,N);\n    end\n  else\n    a.dx = a.dx .* ax(:,ones(1,N));\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/gradient/@gradient/sin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5631312737064077}}
{"text": "function C = encode(p,R)\n%\n% Compute vector of transmit costs for each stage of the KD-tree\n%\n\nN = getNpts(p);  bw = getBW(p,1);\nif (size(p.bandwidth,2) > 2*N)\n  error('Encoding of variable bandwidths not yet supported...');\nend;\nif (any( abs(getWeights(p) - 1/N) > 2*eps )) \n  error('Encoding of variable weights not yet supported...'); \nend;\nC = zeros(1,2*N); C(1) = 2*getDim(p)*R;\t\t% Root node...\n\nfor i=1:N-1,            % calc costs of splitting each node; 1/2 cost to each side\n if (~isLeaf(i,N))\n  mu0 = p.means(:,i);\t\t\t\t% get means of parent, children\n  mu1 = p.means(:, double(p.leftch(i))+1);\n  mu2 = p.means(:, double(p.rightch(i))+1);\n  sig0= sqrt( p.bandwidth(:,i) );\t\t% and bw's of parent, children\n  sig1= sqrt( p.bandwidth(:,double(p.leftch(i))+1) );\n  sig2= sqrt( p.bandwidth(:,double(p.rightch(i))+1) );\n  sig0UB = sqrt(max( sig0.^2 - bw.^2, 2^-R));\t% don't round down too far...\n\n  [tmp,splitDim] = max( sig0UB );\t\t% which dimension are we splitting on...\n  %[tmp,splitDim2] = max( abs(mu0-mu1) + abs(mu0-mu2) );\n  %if (splitDim ~= splitDim2) warning('Disagreement?'); end;\n\n  % COMPUTE COST OF SENDING MEANS\n  muMax = max(mu1,mu2); sigDiff = sig0.^2 - (mu1.^2 + mu2.^2 - mu0.^2);\n  for j=splitDim,\n    costMu = gauss( muMax(j), mu0(j), sig0UB(j).^2 ,1,R );\n  end;\n  for j = [1:splitDim-1,splitDim+1:getDim(p)];\n    costMu = costMu + gauss2( mu1(j), mu0(j), 1*sig0UB(j).^2 ,1,R );\n  end;\n  \n  % COMPUTE COST OF SENDING VARIANCES\n  if (isLeaf(p.leftch(i),N) && isLeaf(p.rightch(i),N)), costSig = 0; costMu = 0;\n  elseif (isLeaf(p.leftch(i),N) || isLeaf(p.rightch(i),N)), costSig = 0;\n  else\n    for j=splitDim,\n      costSig = gauss2( sig1(j).^2 , sig0(j).^2/2, sig0(j).^2/4, 1, R);\n    end; \n    for j = [1:splitDim-1,splitDim+1:getDim(p)]\n      costSig = costSig + gauss2( sig1(j).^2 , sig0(j).^2, sig0(j).^2/2, 1, R);\n    end;\n  end;\n\n  %[costMu,costSig]\n  C(double(p.leftch(i))+1) = .5 * (C(i) + costMu + costSig);\n  C(double(p.rightch(i))+1) = .5 * (C(i) + costMu + costSig);\n end;\nend;\n\nfunction v = gauss(x,mu,sig2,sigOut2,R)\t\t% SIMPLE 1-SIDED GAUSSIAN\n  v = R-log2(  2*1/sqrt(2*pi*sig2) .* exp(-(x-mu).^2 ./(2*sig2)) );\n\n%function v = gauss(x,mu,sig2,sigOut2,R)\t% 1-SIDED W/ OUTLIER PROCESS\n%  v = R-log2(  2*1/sqrt(2*pi*sig2) .* exp(-(x-mu).^2 ./(2*sig2)) ); + ...\n%               1/sqrt(2*pi*sig2) .* exp(-(x-mu).^2 ./(2*sigOut2)) );\n\nfunction v = gauss2(x,mu,sig2,sigOut2,R)\t% SIMPLE 2-SIDED GAUSSIAN\n  v = R-log2(  1/sqrt(2*pi*sig2) .* exp(-(x-mu).^2 ./(2*sig2)) );\n\n%function v = gauss2(x,mu,sig2,sigOut2,R)\t% 2-SIDED W/ OUTLIER PROCESS\n%  v = R-log2(  1/sqrt(2*pi*sig2) .* exp(-(x-mu).^2 ./(2*sig2))  + ...\n%               1/sqrt(2*pi*sig2) .* exp(-(x-mu).^2 ./(2*sigOut2)) );\n\nfunction b = isLeaf(ind,N)\n  ind = double(ind);\n  if (ind <= 0 || ind > 2*N) b = 0;\n  elseif (ind <= N-1) b = 0;\n  else b = 1;\n  end;\n\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/encode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5631025002704863}}
{"text": "classdef TestSequentialLaminateTestedWithNumerics < handle\n\n    properties (Access = private)\n        microFile = 'RVE_Square_Triangle_FineFine';\n        fileOutputName = 'SeqLaminate';\n    end\n\n    properties (Access = protected)\n        LaminateDirection\n        Theta\n        FractionVolume\n       \n        StiffTensor\n        WeakTensor\n        MaterialValues\n       \n        MixtureCh\n        Rank2Ch\n        NumericalCh\n        SeqLamCh\n        \n        FiberDirection\n    end\n\n    methods (Access = public)\n\n        function hasPassed = hasPassed(obj) \n            ChNum   = obj.NumericalCh.getValue();\n            ChSL    = obj.SeqLamCh.getValue();\n            ChMix   = obj.MixtureCh.getValue();\n            ChRank  = obj.Rank2Ch.getValue();\n            firstCondition  = obj.relativeNorm(ChSL,ChNum)   < 1e-2;\n            secondCondition = obj.relativeNorm(ChMix,ChNum)  < 1e-3;\n            thirdCondition  = obj.relativeNorm(ChRank,ChNum) < 1e-10;\n            hasPassed = firstCondition & secondCondition & thirdCondition;\n        end\n\n    end\n\n    methods (Access = protected)\n\n        function compute(obj)\n            obj.init();\n            obj.computeNumericallyChForLaminate();\n            obj.loadFractionVolume()\n            obj.computeWeakAndStiffTensorsFromNumericalHomogenizerData();\n            obj.computeSequentialLaminateTensor();\n            obj.computeRank2HomogenizerTensor();\n            obj.computeMixtureTheoryTensor();\n        end\n\n    end\n    \n    methods (Access = private)\n                \n        function init(obj)\n           obj.loadLaminateDirection()\n           obj.loadFiberDirection()\n        end\n        \n        function computeNumericallyChForLaminate(obj)\n           d = obj.createNumericalHomogenizerDataBase();\n           homog = NumericalHomogenizer(d);\n           homog.compute();\n           obj.NumericalCh    = obj.rotateCh(homog);\n           obj.MaterialValues = homog.matValues;\n           obj.FractionVolume = homog.cellVariables.volume;\n        end\n        \n        function d = createNumericalHomogenizerDataBase(obj)\n            nDB = NumericalHomogenizerDataBase(obj.microFile);\n            d = nDB.dataBase;\n            d.outFileName = obj.fileOutputName;\n            d.hasToCaptureImage = false;\n        end\n        \n        function loadFractionVolume(obj)\n           obj.Theta = obj.FractionVolume;\n        end\n        \n        function computeWeakAndStiffTensorsFromNumericalHomogenizerData(obj)\n            E1  = obj.MaterialValues.E_plus;\n            nu1 = obj.MaterialValues.nu_plus;\n            E0  = obj.MaterialValues.E_minus;\n            nu0 = obj.MaterialValues.nu_minus;\n            obj.StiffTensor = IsotropicConstitutiveTensor(E1,nu1);\n            obj.WeakTensor  = IsotropicConstitutiveTensor(E0,nu0);\n        end\n        \n        function computeSequentialLaminateTensor(obj)\n            C0 = obj.WeakTensor;\n            C1 = obj.StiffTensor;\n            dir{1} = obj.LaminateDirection;\n            m1 = 1;\n            SeqHomog = VoigtHomogPlaneStressHomogenizer(C0,C1,dir,m1,obj.Theta);\n            obj.SeqLamCh  = SeqHomog.getPlaneStressHomogenizedTensor();\n        end\n        \n        function computeRank2HomogenizerTensor(obj)\n            C0 = obj.WeakTensor;\n            C1 = obj.StiffTensor;\n            dir{1} = obj.LaminateDirection;\n            m1 = 1;\n            SeqHomog = VoigtPlaneStressHomogHomogenizer(C0,C1,dir,m1,obj.Theta);\n            obj.Rank2Ch  = SeqHomog.getPlaneStressHomogenizedTensor();\n        end\n        \n        function computeMixtureTheoryTensor(obj)\n            C1 = obj.StiffTensor;\n            C0 = obj.WeakTensor;\n            d = [0 0 1];\n            dir = Vector3D;\n            dir.setValue(d);\n            dir.normalize();\n            angle = -acos(dot(obj.FiberDirection.getValue(),[1 0 0]));\n            vFrac = obj.Theta;\n            homogenizer = MixtureTheoryHomogenizer(C1,C0,dir,angle,vFrac);\n            obj.MixtureCh = homogenizer.Ch;\n        end\n        \n        function Ch = rotateCh(obj,homog)\n            dir = obj.FiberDirection;\n            r = ChRotatorForFiberHomogenizer();\n            Ch = r.rotate(dir,homog.cellVariables.Ch());\n        end\n       \n    end\n    \n    methods (Access = private, Static)\n        \n        function relNorm = relativeNorm(A,B)\n            relNorm = norm(A - B)/norm(B);\n        end\n\n    end\n   \n    methods (Abstract,Access = protected)\n        loadLaminateDirection(obj)\n        loadFiberDirection(obj)\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/tests/Source/HomogenizationTests/TestSequentialLaminateTestedWithNumerics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5631024795075151}}
{"text": "function CSPFilter = spatial_filtering( x_flt, oldSMC, numPatterns, verbose )\n\nif verbose == 1\n%     fprintf( '\\tSpatial Filtering...\\n\\t\\t' );\nend\n\nCSPFilter = cell( 1, oldSMC.numBands );\nfor i=1:oldSMC.numBands\n    if verbose == 1\n        if mod(i, 5) == 0\n%             fprintf( '%d', i );\n        else\n%             fprintf( '.' );\n        end\n        if mod(i, 100) == 0\n%             fprintf( '\\n' );\n        end\n    end\n    \n    D1 = x_flt{1, i};\n    D2 = x_flt{2, i};\n    [W, D] = myTrainCSP( D1, D2 );\n    CSPFilter{i}.W = W( :, [1:numPatterns, end-numPatterns+1:end] );\n    Dd = diag(D);\n    CSPFilter{i}.D = Dd([1:numPatterns, end-numPatterns+1:end]);\nend\n% fprintf( '\\n' );\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/GigaScience/function_MI/bssfo/original/spatial_filtering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5630805525640655}}
{"text": "function [parameters, ll, ht, VCV, scores, diagnostics] = matrix_garch(data,dataAsym,p,o,q,startingvals,options)\n% Estimation of symmetric and asymmetric MATRIX multivariate GARCH models \n%\n% USAGE:\n%  [PARAMETERS,LL,HT,VCV,SCORES,DIAGNOSTICS] = matrix_garch(DATA,DATAASYM,P,O,Q,STARTINGVALS,OPTIONS)\n%\n% INPUTS:\n%   DATA         - A T by K matrix of zero mean residuals -OR-\n%                    K by K by T array of covariance estimators (e.g. realized covariance)\n%   DATAASYM     - [OPTIONAL] K by K by T array of asymmetric covariance\n%                    estimators (e.g. RC scaled by indicator functions)\n%   P            - Positive, scalar integer representing the number of lags of the innovation process\n%   O            - Non-negative scalar integer representing the number of asymmetric lags to include\n%   Q            - Non-negative scalar integer representing the number of lags of conditional covariance\n%   STARTINGVALS - [OPTIONAL] INCOMPLETE\n%   OPTIONS      - [OPTIONAL] Options to use in the optimization (fminunc)\n%\n% OUTPUTS:\n%   PARAMETERS   - K(K+1)/2*(1+P+O+Q) by 1 vector of parameters of the form\n%                    [vech(C)' vech(A(1))' ... vech(A(P))' vech(G(1))' ...\n%                    vech(G(O))' vech(B(1))' ... vech(B(Q))']'\n%   LL           - The log likelihood at the optimum\n%   HT           - A [K K T] dimension matrix of conditional covariances\n%   VCV          - A numParams^2 square matrix of robust parameter covariances (A^(-1)*B*A^(-1)*t^(-1))\n%   SCORES       - A T by numParams matrix of individual scores\n%   DIAGNOSTICS  - Structure containing some diagnostic information\n%\n% COMMENTS:\n%    The conditional variance, H(t), of a MATRIX GARCH is modeled as follows:\n%\n%      H(t) = CC' + A(1)A(1)'.*r_{t-1}'*r_{t-1} + ... + A(P)A(P)'.*r_{t-P}'*r_{t-P}\n%                 + G(1)G(1)'.*n_{t-1}'*n_{t-1} + ... + G(O)G(O)'.*n_{t-P}'*n_{t-P}\n%                  + B(1)B(1)'.*H(t-1) +...+ B(Q)B(Q)'.*H(t-q)\n%\n%    where n_{t} = r_{t} .* (r_{t}<0).  If using realized measures, the\n%    RM_{t-1} replaces r_{t-1}'*r_{t-1}, and the asymmetric version\n%    replaces n_{t-1}'*n_{t-1}\n%\n% EXAMPLES:\n%     % Estimation of a symmetric MATRIX GARCH(1,0,1) model\n%     parameters = matrix_garch(data,[],1,0,1);\n%     % Estimation of an asymmetric MATRIX GARCH(1,0,1) model\n%     parameters = matrix_garch(data,[],1,1,1);\n%     % Estimation of a symmetric MATRIX GARCH(1,0,1) model using realized covariacne\n%     data = RC % K by K by T 3D of realized covariacne\n%     parameters = matrix_garch(RC,[],1,0,1);\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3    Date: 10/28/2009\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Argument Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch nargin\n    case 3\n        o=0;\n        q=0;\n        startingvals=[];\n        options = [];\n    case 4\n        q=0;\n        startingvals=[];\n        options = [];\n    case 5\n        startingvals=[];\n        options = [];\n    case 6\n        options = [];\n    case 7\n    otherwise\n        error('Between 2 and 6 arguments required.')\nend\n\n%data should be TxK, T>K\nif ndims(data)==2\n    [t,k]=size(data);\n    if ~isempty(dataAsym)\n        error('If DATA is a T by K matrix, DATAASYM must be empty.');\n    end\n    temp = zeros(k,k,t);\n    dataAsym = zeros(k,k,t);\n    for i=1:t\n        temp(:,:,i) = data(i,:)'*data(i,:);\n        dataAsym(:,:,i) = (data(i,:).*(data(i,:)<0))'*(data(i,:).*(data(i,:)<0));\n    end\n    data = temp;\nelseif ndims(data)==3\n    [k,m,t] = size(data);\n    if m~=k\n        error('DATA must be K by K by T is a 3D array.');\n    end\n    if ~isempty(dataAsym)\n        if ndims(dataAsym)~=3\n            error('DATAASYM must be a 3D array with the same dimensions as DATA');\n        end\n        [k2,m2,t2]=size(dataAsym);\n        if any([k m t]~=[k2 m2 t2])\n            error('DATAASYM must be a 3D array with the same dimensions as DATA');\n        end\n    end\nend\nk2 = k*(k+1)/2;\nif min(t,k)<2 || t<k\n    error('DATA must be a T by K matrix or a K by K by T 3D array, T>K>1');\nend\n\n%p, o, q much be non-negative scalars\nif length(p)>1 || any(p<1) || floor(p)~=p\n    error('P must be a positive scalar');\nend\nif isempty(o)\n    o = 0;\nend\nif length(o)>1 || any(o<0) || floor(o)~=o\n    error('O must be a non-negative scalar');\nend\nif o>0 && isempty(dataAsym)\n    error('DATAASYM must be non-empty if O>0.')\nend\n\nif isempty(q)\n    q = 0;\nend\nif length(q)>1 || any(q<0) || floor(q)~=q\n    error('Q must be a non-negative scalar');\nend\n\n% Startingvals must have (k*(k+1)/2)(1+p+o+q) parameters\nif  ~isempty(startingvals)\n    if size(startingvals,2)>size(startingvals,1)\n        startingvals = startingvals';\n    end\n    if length(startingvals)<(p+o+q)\n        error('STARTINGVALS should be a P+O+Q by 1 vector');\n    end\n    % Only validate if provided\n    % FIXME: Fix Validation\n    % TODO: Fix Validation\n    kappa = 2;\n    A=startingvals(1:p);\n    G=startingvals(p+1:p+o);\n    B=startingvals(p+o+1:p+o+q);\n    if (sum(A)+sum(G)/kappa+sum(B))>=.999998\n        error('Weighted sum of STATINGVALUES must be less than 1. See Comments.');\n    end\n    if any(A<0) || any(B<0) || any(G<0)\n        error('STARTINGVALS must all be nonnegative.');\n    end\nend\n\n%Make sure options is a valid option structure\nif isempty(options)\n    options=optimset('fminunc');\n    options.Display='iter';\n    options.Diagnostics='on';\n    options.LargeScale='off';\n    options.MaxFunEvals = 1000*k2*(1+p+o+q);\nend\ntry\n    optimset(options);\ncatch ME\n    error('OPTIONS is not a valid options structure');\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Argument Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Compute the backCast\nbackCast = zeros(k);\nbackCastAsym = zeros(k);\ntau = max(ceil(sqrt(t)),k);\nweights = .06 * .94.^(0:tau);\nweights = weights / sum(weights);\nfor i=1:tau\n    backCast = backCast + weights(i) * data(:,:,i);\n    if o>0\n        backCastAsym = backCastAsym + weights(i) * dataAsym(:,:,i);\n    end\nend\n\n%Get starting values from scalar_vt_vech\nif isempty(startingvals)\n    startingOptions=optimset('fminunc');\n    startingOptions.Display='off';\n    startingOptions.Diagnostics='off';\n    startingOptions.LargeScale='off';\n    startingOptions.TolX = 1e-4;\n    startingOptions.TolFun = 1e-4;\n    [scalarVechStartingvals,~,~,~,~,~,diagnostics] = scalar_vt_vech(data,dataAsym,p,o,q,[],[],startingOptions);\n    CpC = diagnostics.intercept;\n    \n    startingvals = zeros(k2 * (1+p+o+q),1);\n    startingvals(1:k2) = chol2vec(chol(CpC)');\n    index = k2;\n    for i=1:(p+o+q)\n        matrixParameters = scalarVechStartingvals(i)*(.02*eye(k) + .98*ones(k));\n        startingvals(index+1:index+k2) = chol2vec(chol(matrixParameters)');\n        index = index + k2;\n    end\nend\n\n\nwarning('off','MATLAB:illConditionedMatrix')\nll0 = matrix_garch_likelihood(startingvals,data,dataAsym,p,o,q,backCast,backCastAsym);\n[parameters,ll,exitflag,output]=fminunc('matrix_garch_likelihood',startingvals,options,data,dataAsym,p,o,q,backCast,backCastAsym);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Estimation Robustification\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif exitflag<=0 &&  ll<ll0\n    %Did not converge, but function improved\n    options.MaxFunEvals=4*100*(p+q);\n    options.MaxIter=2*100*(p+q);\n    parameters=fminunc('matrix_garch_likelihood',parameters,options,data,dataAsym,p,o,q,backCast,backCastAsym);\nend\nwarning('on','MATLAB:illConditionedMatrix')\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Estimation Robustification\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargout>1\n    [ll,lls,ht]=matrix_garch_likelihood(parameters,data,dataAsym,p,o,q,backCast,backCastAsym);\n    ll=-ll;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Compute the VCV\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargout>3\n    [VCV,A,B,scores]=robustvcv('matrix_garch_likelihood',parameters,0,data,dataAsym,p,o,q,backCast,backCastAsym);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Compute the VCV\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndiagnostics = [];\ndiagnostics.EXITFLAG=exitflag;\ndiagnostics.ITERATIONS=output.iterations;\ndiagnostics.FUNCCOUNT=output.funcCount;\ndiagnostics.MESSAGE=output.message;\nparameterMatrices = zeros(k,k,1+p+o+q);\nindex = 0;\nfor i=1:(1+p+o+1)\n    temp = vec2chol(parameters(index+1:index+k2));\n    parameterMatrices(:,:,i) = temp*temp';\n    index=index+k2;\nend\ndiagnostics.C = parameterMatrices(:,:,1);\ndiagnostics.A = parameterMatrices(:,:,2:p+1);\nif o>0\n    diagnostics.G = parameterMatrices(:,:,p+2:p+o+1);\nelse\n    diagnostics.G = [];\nend\n\nif q>0\n    diagnostics.B = parameterMatrices(:,:,p+o+2:p+o+q+1);\nelse\n    diagnostics.B = [];\nend\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/multivariate/matrix_garch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5630805523161909}}
{"text": "classdef nnspnorm < nntest\n  methods (Test)\n   function basic(test)\n      h = 13 ;\n      w = 17 ;\n      d = 4 ;\n      n = 5 ;\n      param = [3, 3, 0.1, 0.75] ;\n      x = test.randn(h,w,d,n,'single') ;\n      y = vl_nnspnorm(x, param) ;\n      dzdy = test.rand(h, w, d, n) ;\n      dzdx = vl_nnspnorm(x, param, dzdy) ;\n      test.der(@(x) vl_nnspnorm(x,param), x, dzdy, dzdx, test.range * 1e-3) ;\n    end\n  end\nend\n", "meta": {"author": "willard-yuan", "repo": "cnn-for-image-retrieval", "sha": "2e3e8ab76e2c971314be55b5ae44e02884003261", "save_path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval/cnn-for-image-retrieval-2e3e8ab76e2c971314be55b5ae44e02884003261/matconvnet-1.0-beta17/matlab/xtest/suite/nnspnorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5630805363901452}}
{"text": "% MatrixUser, a multi-dimensional matrix analysis software package\n% https://sourceforge.net/projects/matrixuser/\n% \n% The MatrixUser is a matrix analysis software package developed under Matlab\n% Graphical User Interface Developing Environment (GUIDE). It features \n% functions that are designed and optimized for working with multi-dimensional\n% matrix under Matlab. These functions typically includes functions for \n% multi-dimensional matrix display, matrix (image stack) analysis and matrix \n% processing.\n%\n% Author:\n%   Fang Liu <leoliuf@gmail.com>\n%   University of Wisconsin-Madison\n%   Aug-30-2014\n\n\n\nfunction MU_funcSharpen(Temp,Event,handles)\nhandles=guidata(handles.MU_matrix_display);\n\nchoice = questdlg('Apply to all slices?','All Slices','No','Yes','No');\nif isempty(choice)\n    warndlg('Image sharpening is cancelled.');\n    return;\nend\n% Handle response\nH =  fspecial('unsharp');\nswitch choice\n    case 'No'\n        handles.TMatrix(:,:,handles.V.Slice) = imfilter(handles.BMatrix,H,'replicate');\n    case 'Yes'\n        if length(handles.V.DimSize)>2\n            for i= 1: handles.V.DimSize(3)\n                handles.TMatrix(:,:,i) = imfilter(handles.TMatrix(:,:,i),H,'replicate');\n                MU_update_waitbar(handles.Progress_axes,i,handles.V.DimSize(3));\n            end\n        else\n            handles.TMatrix = imfilter(handles.BMatrix,H,'replicate');\n        end\nend\n\nMergeM=get(handles.Matrix_name_edit,'String');\nset(handles.Matrix_name_edit,'String',[MergeM '_shp']);\n\n% update current display matrix\nhandles=MU_update_image(handles.Matrix_display_axes,{handles.TMatrix,handles.Mask},handles,0);\nguidata(handles.MU_matrix_display, handles);\n\nend", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/External/MatrixUser2.2/Src/FuncLib/MU_funcSharpen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5630411452306626}}
{"text": "addpath('./scripts'); \n%% figures \ngam = .8; \nT = 25; \nnoise = .2; \nseed = 3; \n[y, ~, trueSpikes] = gen_data(gam, noise, T, 1, 0.1, [], 1, seed); \n\nfig2_demo_deconvolveAR1(y, gam, 0.4, false, trueSpikes); \n\n%% video \ngam = .8; \nT = 130; \nnoise = .2; \nseed = 3; \n[y, truth, trueSpikes] = gen_data(gam, noise, T, 1, 0.1, [], 1, seed); \nfig2_demo_deconvolveAR1(y, gam, 0.4, true, trueSpikes); \n", "meta": {"author": "zhoupc", "repo": "CNMF_E", "sha": "ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f", "save_path": "github-repos/MATLAB/zhoupc-CNMF_E", "path": "github-repos/MATLAB/zhoupc-CNMF_E/CNMF_E-ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f/OASIS_matlab/examples/Paper/fig2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5630411259157635}}
{"text": "classdef CEC2020_F4 < PROBLEM\n% <single> <real>\n% Expanded Rosenbrock's plus Griewangk's function\n\n%------------------------------- Reference --------------------------------\n% C .T. Yue, K. V. Price, P. N. Suganthan, J. J. Liang, M. Z. Ali, B. Y.\n% Qu, N. H. Awad, and P. P Biswas, Problem definitions and evaluation\n% criteria for the CEC 2020 special session and competition on single\n% objective bound constrained numerical optimization, Zhengzhou University,\n% China and Nanyang Technological University, Singapore, 2019.\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        O;      % Optimal decision vector\n        Mat;\t% Rotation matrix\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2020.mat'),'Data');\n            obj.O = Data{4}.o;\n            obj.M = 1;\n            if isempty(obj.D) || obj.D < 10\n                obj.D   = 5;\n                obj.Mat = Data{4}.M_5;\n            elseif obj.D < 15\n                obj.D   = 10;\n                obj.Mat = Data{4}.M_10;\n            elseif obj.D < 20\n                obj.D   = 15;\n                obj.Mat = Data{4}.M_15;\n            else\n                obj.D   = 20;\n                obj.Mat = Data{4}.M_20;\n            end\n            obj.lower    = zeros(1,obj.D) - 100;\n            obj.upper    = zeros(1,obj.D) + 100;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            Y = 0.05*Z*obj.Mat';\n            Z = Y + 1;\n            temp   = 100*(Z.^2-Z(:,[2:end,1])).^2 + (Z-1).^2;\n            PopObj = 1900 + sum(temp.^2/4000-cos(temp)+1,2);\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/Single-objective optimization/CEC 2020/CEC2020_F4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.563026025895122}}
{"text": "function i4mat_max_test ( )\n\n%*****************************************************************************80\n%\n%% I4MAT_MAX_TEST tests I4MAT_MAX.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    18 October 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 5;\n  n = 7;\n  b = 0;\n  c = 10;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'I4MAT_MAX_TEST\\n' );\n  fprintf ( 1, '  I4MAT_MAX returns the maximum;\\n' );\n \n  seed = 123456789;\n\n  [ a, seed ] = i4mat_uniform_ab ( m, n, b, c, seed );\n \n  i4mat_print ( m, n, a, '  Random array:' );\n \n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Maximum entry = %d', i4mat_max ( m, n, a ) );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/i4lib/i4mat_max_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.5630260207378132}}
{"text": "function x = line_cvt_lloyd ( n, a, b, it_num, header, x )\n\n%*****************************************************************************80\n%\n%% LINE_CVT_LLOYD carries out the Lloyd algorithm.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    28 July 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the number of generators.\n%\n%    Input, real A, B, the left and right endpoints.\n%\n%    Input, integer IT_NUM, the number of iterations to take.\n%\n%    Input, string HEADER, an identifying string.\n%\n%    Input, real X(N), the initial point locations.\n%\n%    Output, real X(N), the final point locations.\n%\n  x = x(:);\n%\n%  Print the initial generators.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Initial generators:\\n' );\n  fprintf ( 1, '\\n' );\n  for k = 1 : n\n    fprintf ( 1, '  %4d  %f\\n', k, x(k,1) );\n  end\n%\n%  Initialize the plotting arrays.\n%\n  step = 1 : it_num;\n  e = nan ( it_num, 1 );\n  xm = nan ( it_num, 1 );\n\n  for it = 1 : it_num\n\n    x_plot ( 1:n, it ) = x(1:n,1);\n\n    x_new = line_cvt_lloyd_step ( n, a, b, x );\n\n    e(it) = line_cvt_energy ( n, a, b, x );\n    e(it) = max ( e(it), eps );\n%\n%  Display the energy.\n%\n    figure ( 1 )\n    plot ( step, log ( e ), 'm-*' )\n    title ( 'Log (Energy)' )\n    xlabel ( 'Step' )\n    ylabel ( 'Energy' )\n    grid\n%\n%  Compute the generator motion.\n%\n    xm(it,1) = sum ( ( x_new(:) - x(:) ).^2 ) / n;\n%\n%  Display the generator motion.\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 generators.\n%\n    x(1:n,1) = x_new(1:n,1);\n    \n  end\n\n  x_plot(1:n,it_num+1) = x(1:n,1);\n%\n%  Print the current generators.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Current generators:\\n' );\n  fprintf ( 1, '\\n' );\n  for k = 1 : n\n    fprintf ( 1, '  %4d  %f\\n', k, x(k,1) );\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%  Save the plots.\n%\n  figure ( 1 )\n  filename = strcat ( header, '_energy.png' );\n  print ( '-dpng', filename );\n  figure ( 2 )\n  filename = strcat ( header, '_motion.png' );\n  print ( '-dpng', filename );\n  figure ( 3 )\n  filename = strcat ( header, '_evolution.png' );\n  print ( '-dpng', 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/line_cvt_lloyd/line_cvt_lloyd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760727, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.5630140988446044}}
{"text": "function c = tapas_softmax_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the softmax observation model for multinomial responses\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\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 <http://www.gnu.org/licenses/>.\n\n% Config structure\nc = struct;\n\n% Is the decision based on predictions or posteriors? Comment as appropriate.\nc.predorpost = 1; % Predictions\n%c.predorpost = 2; % Posteriors\n\n% Model name\nc.model = 'softmax';\n\n% Sufficient statistics of Gaussian parameter priors\n\n% Beta\nc.logbemu = log(1);\nc.logbesa = 4^2;\n\n% Gather prior settings in vectors\nc.priormus = [\n    c.logbemu,...\n         ];\n\nc.priorsas = [\n    c.logbesa,...\n         ];\n\n% Model filehandle\nc.obs_fun = @tapas_softmax;\n\n% Handle to function that transforms observation parameters to their native space\n% from the space they are estimated in\nc.transp_obs_fun = @tapas_softmax_transp;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_softmax_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.562997586914683}}
{"text": "function [xout,yout] = coords2normfig(x,y,h)\n\nif ~exist('h','var')\n  h = gca;\nend\n\nif ~strcmpi(get(h,'type'),'axes'),\n  error('Handle must correspond to an axis');\nend\n\nxax  = get(h,'xlim');\nyax = get(h,'ylim');\n\npos = get(h,'position');\n\nxout = (x - pos(1))/pos(3)*(xax(2)-xax(1)+1) + xax(1);\nyout = (y - pos(2))/pos(4)*(yax(2)-yax(1)+1) + yax(1);\n\nyisreversed = strcmpi(get(h,'ydir'),'reverse');\nxisreversed = strcmpi(get(h,'xdir'),'reverse');\nif xisreversed,\n  xout = (1-(x - xax(1))/(xax(2)-xax(1)))*pos(3) + pos(1);\nelse\n  xout = (x - xax(1))/(xax(2)-xax(1))*pos(3) + pos(1);\nend\nif yisreversed,\n  yout = (1-(y - yax(1))/(yax(2)-yax(1)))*pos(4) + pos(2);\nelse\n  yout = (y - yax(1))/(yax(2)-yax(1))*pos(4) + pos(2);\nend\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/coords2normfig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5629975761487958}}
{"text": "clear; close all; clc;\n\n\n% Datasets = {'TUM', 'KITTI', 'Tanks_and_Temples', 'CPC'};\nDatasets = {'TUM'};\n\nMethods = {'SIFT-RT-RANSAC'};\n\nErrors = cell(length(Methods),length(Datasets));\nInlier_rates = cell(length(Methods),length(Datasets));\nNumbers = cell(length(Methods),length(Datasets));\nfor d = 1 : length(Datasets) \n    dataset = Datasets{d};\n    for m = 1 : length(Methods)\n        method = Methods{m};\n        \n        results_dir = ['../Results/' dataset '/'];\n        filename = [results_dir method '.mat'];\n        Results = importdata(filename);        \n        \n        Error = -ones(length(Results), 1);\n        Inlier_rate = -ones(length(Results), 2);\n        Number =  zeros(length(Results), 2);\n        \n        for idx = 1 : length(Results)\n            \n            if Results{idx}.status ~=0\n                Results{idx}.sgd_error = -1;\n                Results{idx}.inlier_rate = [0,0];\n                continue;\n            end\n          \n            F1 = Results{idx}.F_gt;\n            F2 = Results{idx}.F_hat;\n            size1 = Results{idx}.size_l;\n            size2 = Results{idx}.size_r;\n            X1 = Results{idx}.X_l';\n            X2 = Results{idx}.X_r';\n            inliers = Results{idx}.inliers;\n\n            if isfield(Results{idx}, 'sgd_error') ~= 1 || Results{idx}.sgd_error < 0\n                Results{idx}.sgd_error = ComputeNormlizedSGD(F1, F2, size1, size2);            \n            end\n            Error(idx) = Results{idx}.sgd_error; \n            \n            if isfield(Results{idx}, 'inlier_rate') ~= 1 || isempty(Results{idx}.inlier_rate) == 1\n                Results{idx}.inlier_rate = ComputeInlierRate(F1, X1, X2, inliers, size1, size2, 0.003);     \n            end\n            Inlier_rate(idx,:) = Results{idx}.inlier_rate;\n            Number(idx,:) = [length(Results{idx}.inliers), sum(Results{idx}.inliers)];\n        end\n        \n        save(filename, 'Results');\n        \n        mask = Error < 0;\n        Error(mask) = [];\n        Errors{m, d} = Error;\n        Inlier_rate(mask,:) = [];\n        Inlier_rates{m, d} = Inlier_rate;\n        Number(mask, :) = [];\n        Numbers{m, d} = Number;        \n    end\nend\n\n\n% Recall---(Error)\nnum_pairs = 1000;\nX = linspace(0,0.2,20);\nfor d = 1 : length(Datasets)\n    dataset = Datasets{d};\n    Y = zeros(length(Methods), length(X));\n    for m = 1 : length(Methods)\n       method = Methods{m};\n       for t = 1 : length(X)\n           Y(m, t) = sum(Errors{m,d} < X(t)) / num_pairs;\n       end\n    end\n    figure;\n    h = plot(X,Y,'linewidth',3);\n    ylim([0 1]);\n    legend(h, Methods, 'Location', 'SouthEast');\n    title(dataset);\n    xlabel('NSGD Threshold');\n    ylabel('Recall');\nend\n\nthreshold = 0.05;\nfor d = 1 : length(Datasets) \n    dataset = Datasets{d};\n    disp(['Dataset : ' dataset]);\n    disp('method recall inlier_rate_before inlier_rate_after');\n  \n    for m = 1 : length(Methods)\n       method = Methods{m};\n       \n       recall = sum(Errors{m,d} < threshold) / num_pairs;\n\n       [meanInlierRate] = mean(Inlier_rates{m,d});\n       before_rate = meanInlierRate(1);\n       after_rate = meanInlierRate(2);\n       \n       fprintf(sprintf('%s %f %f %f\\n', method, recall, before_rate, after_rate));\n    end \nend\n\n", "meta": {"author": "JiawangBian", "repo": "FM-Bench", "sha": "9373129b14504b4228dda526fd99dcb083bcef3a", "save_path": "github-repos/MATLAB/JiawangBian-FM-Bench", "path": "github-repos/MATLAB/JiawangBian-FM-Bench/FM-Bench-9373129b14504b4228dda526fd99dcb083bcef3a/Evaluation/Evaluate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.562997570408449}}
{"text": "% DEMROBOTWIRELESSFGPLVM3 Wireless Robot data from University of Washington with dynamics and no back constraints.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'robotWireless';\nexperimentNo = 3;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('ftc');\n\nlatentDim = 2;\nd = size(Y, 2);\n\nmodel = fgplvmCreate(latentDim, d, Y, options);\n\n% Add dynamics model.\noptions = gpOptions('ftc');\noptions.kern = kernCreate(model.X, {'rbf', 'white'});\noptions.kern.comp{1}.inverseWidth = 0.2;\n% This gives signal to noise of 0.1:1e-3 or 100:1.\noptions.kern.comp{1}.variance = 0.1^2;\noptions.kern.comp{2}.variance = 1e-3^2;\nmodel = fgplvmAddDynamics(model, 'gp', options);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\nmodelWriteResult(model, dataSetName, experimentNo);\n\nif exist('printDiagram') & printDiagram\n  lvmPrintPlot(model, lbls, dataSetName, experimentNo);\nend\n\n\n% Load the results and display dynamically.\nlvmResultsDynamic(model.type, dataSetName, experimentNo, 'vector')\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demRobotWirelessFgplvm3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5629892752473828}}
{"text": "function [YY,XX] = EKLMNFTR1(Ap,Xint_v,Uk,Qu,Vk,Qv,C,n,Wk,W,V);\n\nAp(2,:) = 0;\n\nfor ii = 1:1:length(Ap)-1\n    Ap(ii+1,ii) = 1;\nend\n\ninx = 1;\nUUk = [Uk(inx); 0; 0; 0; 0];\nPPk = (Xint_v*Xint_v');\nVVk = [Vk(inx); 0; 0; 0; 0];\nQv = V*V';\n\nfor ii = 1:1:length(Xint_v)\n\nXKk(ii,1) = Xint_v(ii)^2;                                             % FIRST STEP\n\nend\n\nPPk = Ap*PPk*Ap';                                                   % SECOND STEP\n\nKk = PPk*C'*inv( (C*PPk*C') + (V*Qv*V') );                          % THIRD STEP\n\nfor ii = 1:1:length(Xint_v)\n\nXUPK(ii,1) = XKk(ii)^2 + UUk(ii);                                     % UPPER EQUATIONS.\n\nZk(ii,1) = cos(XUPK(ii)) +  VVk(ii);                                  % UPPER EQUATIONS.\n\nend\n\nfor ii = 1:1:length(XKk)\n\nXBARk(ii,1) = XKk(ii) + Kk(ii)*(Zk(ii) - (cos(XKk(ii)))) ;            % FOURTH STEP\n\nend\n\nII = eye(5,5);\n\nPk = ( II -  Kk*C)*PPk;                                             % FIFTH STEP\n\n%--------------------------------------------------------------------------\n%--------------------------------------------------------------------------\n\nfor ii = 1:1:n\n\nUUk = [Uk(ii+1); 0; 0; 0; 0];\nPPk = XBARk*XBARk';\nVVk = [Vk(ii+1); 0; 0; 0; 0];\n\nXKk = exp(-XBARk);                                                % FIRST STEP\n\nPPkM = Ap*PPk*Ap';                                                 % SECOND STEP\n\nKk = PPkM*C'*inv( (C*PPkM*C') + (V*Qv*V') );                      % THIRD STEP\n\nfor nn = 1:1:length(XBARk)\n\nXUPK(nn) = exp(-XKk(nn)) + UUk(nn);                              % UPPER EQUATIONS.\n\nZk(nn) = cos(XUPK(nn)) +  VVk(nn);                               % UPPER EQUATIONS.\n\nend\n\nfor in = 1:1:length(XUPK)\n\nXNEW(in) = XBARk(in) + Kk(in)*(Zk(in) - cos(XBARk(in)));           % FOURTH STEP\n\nend\n\nII = eye(5,5);\n\nPk = (II -  Kk*C)*PPkM;                                            % FIFTH STEP\n\nXBARk = XNEW;\n\nOUTX(ii) = XBARk(1,1);\nOUTY(ii) = Zk(1,1);\n\nend\n\nYY = OUTY;\nXX = OUTX;\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/11144-extended-kalman-filter-example/EKLMNFTR1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.562989254248299}}
{"text": "function [jrt, jst]=jacprojRTS(j, i, rt, xyz, r0, a)\n% symbolic projection function Jacobian\n% code automatically generated with maple\n\n  qr0=r0(j*4+1:(j+1)*4);\n\n  t1 = (rt(1) ^ 2);\n  t2 = (rt(2) ^ 2);\n  t3 = (rt(3) ^ 2);\n  t5 = sqrt((1 - t1 - t2 - t3));\n  t6 = 0.1e1 / t5;\n  t7 = t6 * qr0(2);\n  t9 = -t7 * rt(1) + qr0(1);\n  t11 = t6 * qr0(3);\n  t13 = -t11 * rt(1) - qr0(4);\n  t15 = t6 * qr0(4);\n  t17 = -t15 * rt(1) + qr0(3);\n  t19 = -t9 * xyz(1) - t13 * xyz(2) - t17 * xyz(3);\n  t24 = -t5 * qr0(2) - qr0(1) * rt(1) - rt(2) * qr0(4) + rt(3) * qr0(3);\n  t31 = t5 * qr0(3) + qr0(1) * rt(2) + rt(3) * qr0(2) - rt(1) * qr0(4);\n  t37 = t5 * qr0(4) + qr0(1) * rt(3) + rt(1) * qr0(3) - rt(2) * qr0(2);\n  t39 = t24 * xyz(1) - t31 * xyz(2) - t37 * xyz(3);\n  t41 = t6 * qr0(1);\n  t43 = -t41 * rt(1) - qr0(2);\n  t48 = t5 * qr0(1) - rt(1) * qr0(2) - rt(2) * qr0(3) - rt(3) * qr0(4);\n  t52 = t48 * xyz(1) + t31 * xyz(3) - t37 * xyz(2);\n  t57 = t43 * xyz(1) + t13 * xyz(3) - t17 * xyz(2);\n  t62 = t43 * xyz(2) + t17 * xyz(1) - t9 * xyz(3);\n  t67 = t48 * xyz(2) + t37 * xyz(1) + t24 * xyz(3);\n  t72 = t43 * xyz(3) + t9 * xyz(2) - t13 * xyz(1);\n  t77 = t48 * xyz(3) - t24 * xyz(2) - t31 * xyz(1);\n  t89 = -t19 * t31 - t39 * t13 + t43 * t67 + t48 * t62 + t72 * t24 - t77 * t9 + t57 * t37 + t52 * t17;\n  t99 = -t19 * t37 - t39 * t17 + t43 * t77 + t48 * t72 - t57 * t31 - t52 * t13 - t62 * t24 + t67 * t9;\n  t106 = -t39 * t37 + t48 * t77 - t52 * t31 - t67 * t24 + rt(6);\n  t107 = 0.1e1 / t106;\n  t119 = -t39 * t31 + t48 * t67 + t77 * t24 + t52 * t37 + rt(5);\n  t123 = t106 ^ 2;\n  t124 = 0.1e1 / t123;\n  t125 = (a(1) * (t39 * t24 + t48 * t52 - t67 * t37 + t77 * t31 + rt(4)) + a(2) * t119 + a(3) * t106) * t124;\n  t129 = -t7 * rt(2) + qr0(4);\n  t132 = -t11 * rt(2) + qr0(1);\n  t135 = -t15 * rt(2) - qr0(2);\n  t137 = -t129 * xyz(1) - t132 * xyz(2) - t135 * xyz(3);\n  t141 = -t41 * rt(2) - qr0(3);\n  t146 = t141 * xyz(1) + t132 * xyz(3) - t135 * xyz(2);\n  t151 = t141 * xyz(2) + t135 * xyz(1) - t129 * xyz(3);\n  t157 = t141 * xyz(3) + t129 * xyz(2) - t132 * xyz(1);\n  t170 = -t137 * t31 - t39 * t132 + t141 * t67 + t48 * t151 + t157 * t24 - t77 * t129 + t146 * t37 + t52 * t135;\n  t180 = -t137 * t37 - t39 * t135 + t141 * t77 + t48 * t157 - t146 * t31 - t52 * t132 - t151 * t24 + t67 * t129;\n  t187 = -t7 * rt(3) - qr0(3);\n  t190 = -t11 * rt(3) + qr0(2);\n  t193 = -t15 * rt(3) + qr0(1);\n  t195 = -t187 * xyz(1) - t190 * xyz(2) - t193 * xyz(3);\n  t199 = -t41 * rt(3) - qr0(4);\n  t204 = t199 * xyz(1) + t190 * xyz(3) - t193 * xyz(2);\n  t209 = t199 * xyz(2) + t193 * xyz(1) - t187 * xyz(3);\n  t215 = t199 * xyz(3) + t187 * xyz(2) - t190 * xyz(1);\n  t228 = -t195 * t31 - t39 * t190 + t199 * t67 + t48 * t209 + t215 * t24 - t77 * t187 + t204 * t37 + t52 * t193;\n  t238 = -t195 * t37 - t39 * t193 + t199 * t77 + t48 * t215 - t204 * t31 - t52 * t190 - t209 * t24 + t67 * t187;\n  t255 = (a(4) * t119 + a(5) * t106) * t124;\n  jrt(1) = (a(1) * (t19 * t24 - t39 * t9 + t43 * t52 + t48 * t57 - t62 * t37 - t67 * t17 + t72 * t31 + t77 * t13) + a(2) * t89 + a(3) * t99) * t107 - t125 * t99;\n  jrt(2) = (a(1) * (t137 * t24 - t39 * t129 + t141 * t52 + t48 * t146 - t151 * t37 - t67 * t135 + t157 * t31 + t77 * t132) + a(2) * t170 + a(3) * t180) * t107 - t125 * t180;\n  jrt(3) = (a(1) * (t195 * t24 - t39 * t187 + t199 * t52 + t48 * t204 - t209 * t37 - t67 * t193 + t215 * t31 + t77 * t190) + a(2) * t228 + a(3) * t238) * t107 - t125 * t238;\n  jrt(4) = a(1) * t107;\n  jrt(5) = a(2) * t107;\n  jrt(6) = a(3) * t107 - t125;\n  jrt(7) = (a(4) * t89 + a(5) * t99) * t107 - t255 * t99;\n  jrt(8) = (a(4) * t170 + a(5) * t180) * t107 - t255 * t180;\n  jrt(9) = (a(4) * t228 + a(5) * t238) * t107 - t255 * t238;\n  jrt(10) = 0.0e0;\n  jrt(11) = a(4) * t107;\n  jrt(12) = a(5) * t107 - t255;\n\n  t1 = (rt(1) ^ 2);\n  t2 = (rt(2) ^ 2);\n  t3 = (rt(3) ^ 2);\n  t5 = sqrt((1 - t1 - t2 - t3));\n  t10 = -t5 * qr0(2) - qr0(1) * rt(1) - rt(2) * qr0(4) + rt(3) * qr0(3);\n  t11 = t10 ^ 2;\n  t16 = t5 * qr0(1) - rt(1) * qr0(2) - rt(2) * qr0(3) - rt(3) * qr0(4);\n  t17 = t16 ^ 2;\n  t22 = t5 * qr0(4) + qr0(1) * rt(3) + rt(1) * qr0(3) - rt(2) * qr0(2);\n  t28 = -t5 * qr0(3) - qr0(1) * rt(2) - rt(3) * qr0(2) + rt(1) * qr0(4);\n  t29 = t28 ^ 2;\n  t32 = t10 * t28;\n  t35 = -t16 * t22;\n  t36 = 0.2e1 * t32 + t16 * t22 - t35;\n  t38 = -t10 * t22;\n  t39 = t16 * t28;\n  t42 = t38 + 0.2e1 * t39 - t10 * t22;\n  t48 = t10 * xyz(1) + t28 * xyz(2) - t22 * xyz(3);\n  t53 = t16 * xyz(3) - t10 * xyz(2) + t28 * xyz(1);\n  t58 = t16 * xyz(1) - t28 * xyz(3) - t22 * xyz(2);\n  t63 = t16 * xyz(2) + t22 * xyz(1) + t10 * xyz(3);\n  t65 = -t48 * t22 + t16 * t53 + t58 * t28 - t63 * t10 + rt(6);\n  t66 = 0.1e1 / t65;\n  t78 = t48 * t28 + t16 * t63 + t53 * t10 + t58 * t22 + rt(5);\n  t82 = t65 ^ 2;\n  t83 = 0.1e1 / t82;\n  t84 = (a(1) * (t48 * t10 + t16 * t58 - t63 * t22 - t53 * t28 + rt(4)) + a(2) * t78 + a(3) * t65) * t83;\n  t92 = t22 ^ 2;\n  t93 = t29 + t17 - t10 ^ 2 - t92;\n  t95 = -t28 * t22;\n  t98 = t16 * t10;\n  t99 = 0.2e1 * t95 - t16 * t10 - t98;\n  t111 = t95 + 0.2e1 * t98 - t28 * t22;\n  t114 = t92 + t17 - t28 ^ 2 - t11;\n  t127 = (a(4) * t78 + a(5) * t65) * t83;\n  jst(1) = (a(1) * (t11 + t17 - t22 ^ 2 - t29) + a(2) * t36 + a(3) * t42) * t66 - t84 * t42;\n  jst(2) = (a(1) * (t32 + 0.2e1 * t35 + t10 * t28) + a(2) * t93 + a(3) * t99) * t66 - t84 * t99;\n  jst(3) = (a(1) * (0.2e1 * t38 - t16 * t28 - t39) + a(2) * t111 + a(3) * t114) * t66 - t84 * t114;\n  jst(4) = (a(4) * t36 + a(5) * t42) * t66 - t127 * t42;\n  jst(5) = (a(4) * t93 + a(5) * t99) * t66 - t127 * t99;\n  jst(6) = (a(4) * t111 + a(5) * t114) * t66 - t127 * t114;\n", "meta": {"author": "vrabaud", "repo": "sfm_toolbox", "sha": "7ce933b31b71292eddabb40bacfd619720fa221d", "save_path": "github-repos/MATLAB/vrabaud-sfm_toolbox", "path": "github-repos/MATLAB/vrabaud-sfm_toolbox/sfm_toolbox-7ce933b31b71292eddabb40bacfd619720fa221d/external/sba/matlab/jacprojRTS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993888, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5629670285280662}}
{"text": "function engine = kalman_inf_engine(bnet)\n% KALMAN_INF_ENGINE Inference engine for Linear-Gaussian state-space models.\n% engine = kalman_inf_engine(bnet)\n%\n% 'onodes' specifies which nodes are observed; these must be leaves.\n% The remaining nodes are all hidden. All nodes must have linear-Gaussian CPDs.\n% The hidden nodes must be persistent, i.e., they must have children in\n% the next time slice. In addition, they may not have any children within the current slice,\n% except to the observed leaves. In other words, the topology must be isomorphic to a standard LDS.\n%\n% There are many derivations of the filtering and smoothing equations for Linear Dynamical\n% Systems in the literature. I particularly like the following\n% - \"From HMMs to LDSs\", T. Minka, MIT Tech Report, (no date), available from\n%    ftp://vismod.www.media.mit.edu/pub/tpminka/papers/minka-lds-tut.ps.gz\n\n[engine.trans_mat, engine.trans_cov, engine.obs_mat, engine.obs_cov, engine.init_state, engine.init_cov] = ...\n    dbn_to_lds(bnet);\n\n% This is where we will store the results between enter_evidence and marginal_nodes\nengine.one_slice_marginal = [];\nengine.two_slice_marginal = [];\n\nengine = class(engine, 'kalman_inf_engine', inf_engine(bnet));\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/inference/dynamic/@kalman_inf_engine/kalman_inf_engine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5629616274940294}}
{"text": "% @Author: aaronmishkin\n% @Date:   2018-07-26T13:13:16-07:00\n% @Email:  amishkin@cs.ubc.ca\n% @Last modified by:   aaronmishkin\n% @Last modified time: 2018-07-26T13:22:15-07:00\n\n% Load the toy example experiment data.\nfile_name = strcat('./toy_example_experiment_data.mat');\nload(file_name)\n\n\nmethod = {'Vadam', 'VOGN-1'}\ncolors = [0 0.8 0.5; 0 0 1; 1 0 0];\nf = figure('Position', [50,50,1000,715]); clf;\n% exact post\ncontourf(w1,w2,reshape(post,[n,n]),5);\ncbh=colorbar;\ncolormap(gray);\nhold on\n% map estimate\nh(1) = plot(wmap(1),wmap(2),'+','color', 'k', 'MarkerSize',7, 'linewidth', 8, 'markersize', 7);\nh(2) = plot_gaussian_ellipsoid(w_exact_vi, C_exact_vi, 1);\nset(h(2), 'color', 0*[1 1 1], 'linestyle', '-.', 'linewidth', 12);\n\nfor m = 1:length(method)\n    plot(w_all(1,t,m), w_all(2,t,m), 'or', 'color', colors(m,:), 'linewidth', 8, 'markerfacecolor', colors(m,:), 'markersize', 5);\n    h(m+2) = plot_gaussian_ellipsoid(w_all(:,t,m), Sigma_all(:,:,t,m), 1);\n    set(h(m+2), 'color', colors(m,:), 'linewidth', 12);\nend\n% mf-exact\naxis([0 20 0 12]);\nplot(w_exact_vi(1), w_exact_vi(2), 'o', 'color', 0*[1 1 1], 'linewidth', 8, 'markerfacecolor', 0*[1 1 1], 'markersize', 5);\n      t = maxIters;\n\nhl = legend(h, {'MAP', 'VI-Exact', 'Vadam', 'VOGN-1'}, 'location', 'northwest');\nhx = xlabel('\\theta_1');\nhy = ylabel('\\theta_2');\nset(gca, 'fontsize', 24);\nset([hx,hy], 'fontsize', 24, 'fontname', 'helvetica');\nset(hl, 'fontsize', 24, 'fontname', 'helvetica');\nset(gca, 'xtick', [0:5:20], 'ytick', [0:5:10], 'tickdir', 'out');\nset(cbh,'YTick',[0:1e-3:5e-3])\n\nh = gcf;\n\nf.Position(3) = 1000;\nf.Position(4) = 800;\n\n\naxesObjs = get(h, 'Children');  %axes handles\ndataObjs = get(axesObjs, 'Children'); %handles to low-level graphics objects in axes\n\ncell_obj = dataObjs(3, 1);\ncell_obj = cell_obj{1};\n\nvogn_dot = cell_obj(3);\nvogn_line = cell_obj(2);\n\nvadam_dot = cell_obj(5);\nvadam_line = cell_obj(4);\n\nvi_dot = cell_obj(1);\nvi_line = cell_obj(6);\nmap_dot = cell_obj(7);\n\nlinewidth = 12;\n\nset(vogn_dot,'color', 'b')\nset(vogn_line,'color', 'b')\nset(vogn_line,'linewidth', linewidth)\n\nset(vadam_dot, 'color', 'r')\nset(vadam_line,'color', 'r')\nset(vadam_line,'linewidth', linewidth)\n\nset(vi_dot,'color', [0, 1.0, 0])\nset(vi_line,'color', [0, 1.0, 0])\nset(vi_line,'linewidth', linewidth)\n\nset(map_dot, 'markerSize', 22)\nset(map_dot, 'color', 'black')\n\n%%%%\nfontsize = 30;\nax = gca;\nset(ax, 'fontsize', fontsize);\n\nax.XLim = [0, 20];\nax.YLim = [0, 11];\nax.XLabel.String = 'Weight 1';\nax.YLabel.String = 'Weight 2';\n%%%\nhLegend = findobj(gcf, 'Type', 'Legend');\nhLegend.FontSize = 30;\n%set(ax, 'LooseInset', get(ax, 'TightInset'));\n\nhLegend.String{2} = 'MF-Exact';\n\ngrid off\n\n\nset(f,'Units','Inches');\npos = get(f,'Position');\nset(f,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3), pos(4)])\n\n\nsavefig('figures/figure_two_a.fig')\nsaveas(f, 'figures/figure_two_a.pdf')\nclose all\n", "meta": {"author": "emtiyaz", "repo": "vadam", "sha": "d8ea6bdc82ac8765b873578660e1d9ba95c701d4", "save_path": "github-repos/MATLAB/emtiyaz-vadam", "path": "github-repos/MATLAB/emtiyaz-vadam/vadam-d8ea6bdc82ac8765b873578660e1d9ba95c701d4/matlab/plotting/make_fig_two_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5629545860555868}}
{"text": "function [VecTot, TOT, time] = rmt(P, Vec, Mat)\n%rmt returns a matrix containing the best models for all the paths of the Replacement Method.\n%TOT contains all the relative results showing the evolution of the method.\n%\n%           \n%\t   Input: \n%             P             Property vector\n%             Vec           Initial descriptors vector\n%             Mat           Descriptors matrix with descriptors pool\n%             \n%\n%     Returns:\n%          \n%            VecTot           vector containing the best model for all the\n%                               paths of the Replacement Method\n%            TOT               contains all the relative results\n%                               showing the evolution of the method. \n%           \n% Andrew G. Mercader, Pablo R. Duchowicz\n% INIFTA, La Plata, Argentina\n% Created: 5 March 2007\n\n\nTOT=[];\nVecTot=[];\ntime=cputime;\nwarning off\n\n[k_v,n_v]=size(Vec);\n\nfor k=1:n_v\n\nSr=rms(P,Vec,Mat);\nTOT(k).A(1,:)=[Sr,Vec];\n\nVecA=rmsr(P, Vec, Mat, k);\nPo(1)=k;\nVecI=VecA;\nif n_v==1\n    VecTot=[1,VecI];\n    TOT=VecI;\n    time=cputime-time\n    return\nend\nVecI(1)=[];\nCOEF=rmder(P,VecI,Mat);\nCOER=COEF;\nCOER(Po)=[];\npos=find(COEF==max(COER));\nPo(2)=pos;\nTOT(k).A(2,:)=VecA;\nfor i=2:n_v;\n    VecA=rmsr(P, VecI, Mat, pos);\n    VecI=VecA;\n    TOT(k).A(i+1,:)=VecA;\n    VecI(1)=[];\n    COEF=rmder(P,VecI,Mat);\n    if i==n_v\n        Po=[];\n        break\n    end\n    COER=COEF;\n    COER(Po)=[];\n    pos=find(COEF==max(COER));\n    Po(i+1)=pos;\nend    \n\nfor j=1:2;\nCOER=COEF;\nCOER(Po)=[];\npos=find(COEF==max(COER));\nPo(1)=pos;\nfor i=1:n_v;\n    VecA=rmsr(P, VecI, Mat, pos);\n    VecI=VecA;\n    TOT(k).A(i+(j*n_v),:)=VecA;\n    VecI(1)=[];\n    COEF=rmder(P,VecI,Mat);\n    if i==n_v\n        Po=[];\n        break\n    end\n    COER=COEF;\n    COER(Po)=[];\n    pos=find(COEF==max(COER));\n    Po(i+1)=pos;\nend    \nend\n\nfor j=3:100;\nCOER=COEF;\nCOER(Po)=[];\npos=find(COEF==max(COER));\nPo(1)=pos;\n    for i=1:n_v;\n    VecA=rmsr(P, VecI, Mat, pos);\n    VecI=VecA;\n    TOT(k).A(i+(j*n_v),:)=VecA;\n    VecI(1)=[];\n    COEF=rmder(P,VecI,Mat);\n    if i==n_v \n        Po=[];\n        break\n    end\n    COER=COEF;\n    COER(Po)=[];\n    pos=find(COEF==max(COER));\n    Po(i+1)=pos;\n    end  \n   if TOT(k).A(i+(j*n_v),:)==TOT(k).A(i+(j*n_v)-(2*n_v),:)\n        Po=[];\n        break\n   end\n\nend\nVecP=find(TOT(k).A==min(TOT(k).A(:,1)));\nVecTot(k,:)=[k,TOT(k).A(VecP(1),:)];\nVecTot=sortrows(VecTot,2);\nend\ntime=cputime-time\nwarning on\n\n% % End of rmt\n% \u001a", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/19578-qsarqspr-search-algorithms-toolbox/rmt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5629545813871741}}
{"text": "function timer_tictoc_test04 ( )\n\n%*****************************************************************************80\n%\n%% TEST04 times the 2D nearest neighbor problem.\n%\n%  Discussion:\n%\n%    For the MATLAB implementation of this test, the unvectorized\n%    test limits had to be DRASTICALLY reduced.  But then I noticed\n%    that some kind of MATLAB cleverness causes all the loops \n%    after the first cycle to be computed in almost no time.\n%    This test will have to be rethought.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    16 June 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n_log_min = 10;\n  n_log_max = 18;\n  n_min = 2^n_log_min;\n  n_max = 2^n_log_max;\n  n_rep = 5;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST04\\n' );\n  fprintf ( 1, '  Time the 2D nearest neighbor problem.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Given X(2,N) and Y(2),\\n' );\n  fprintf ( 1, '    find X(2,*) closest to Y(2).\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '    for i = 1 : n\\n' );\n  fprintf ( 1, '      if distance ( x(2,i), y ) < minimum so far\\n' );\n  fprintf ( 1, '        x_min = x(2,i)\\n' );\n  fprintf ( 1, '    end\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Data vectors will be of minimum size %d\\n', n_min );\n  fprintf ( 1, '  Data vectors will be of maximum size %d\\n', n_max );\n  fprintf ( 1, '  Number of repetitions of the operation: %d\\n', n_rep );\n\n  x = rand (2,n_max);\n  y = rand(1,2);\n\n  for i_rep = 1 : n_rep\n\n    for n_log = n_log_min : n_log_max\n\n      n = 2^n_log;\n\n      tic;\n\n      dist_min = r8_huge ( );\n      i_min = 0;\n      for i = 1 : n\n        dist_i = sum ( ( x(1:2,i) - y(1:2)' ).^2 );\n        if ( dist_i < dist_min )\n          dist_min = dist_i;\n          i_min = i;\n        end\n      end\n\n      delta(n_log,i_rep) = toc;\n\n    end\n\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST04 Results:\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'Vector Size  Rep #1        Rep #2        Rep #3        ' );\n  fprintf ( 1, 'Rep #4        Rep #5\\n' );\n  fprintf ( 1, '\\n' );\n  for n_log = n_log_min : n_log_max\n    n = 2^n_log;\n    fprintf ( 1, '%10d', n );\n    for j = 1 : n_rep\n      fprintf ( 1, '%14f', delta(n_log,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/timer/timer_tictoc_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5629545720503489}}
{"text": "% Copyright (C) 1993-2014, by Joern Malzahn\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\n%%begin\n\n%% Getting started with symbolics and code generation\n% This is a brief example about how we can derive symbolic robot model \n% expressions and how we can generate robot specific functions as well as \n% real-time capable Simulink blocks using the |CodeGenerator| class. The\n% example uses a reduced version of the Puma 560 arm with the first 3\n% links.\n%\n% A requirement for this demo is that we have the Mathworks Symbolic Toolbox\n% installed besides the Robotics Toolbox.\n%\n\n%% Instantiate a |CodeGenerator| class object\n% We start off with the instantiation of a |CodeGenerator| class object.\n% First, we load the |SerialLink| object for which we intend to generate\n% code.\nmdl_planar3\n\n%%\n% After that, we find a |SerialLink| object named p3 in the workspace. This\n% object is used to instantiate the CodeGenerator.\ncGen = CodeGenerator(p3)\n\n%% Code generation \n% By default |CodeGenerator| class objects are configured to generate:\n%\n% * symbolic expressions\n% * m-code \n% * Simulink blocks\n%\n% and they document the CodeGeneration progress on the Matlab console. \n% We may modify this behaviour by passing extra arguments to the\n% |CodeGenerator| constructor. (Type |help CodeGenerator| for details)\n%\n% Now let's generate code for the forward kinematics of our reduced Puma\n% 560.\nsymExp = cGen.genfkine\n\n%%\n% The text output to the console may be disabled \ncGen.verbose = false;\n%\n% or logged to disk by specifying a log file name\ncGen.logfile = 'roblog.txt'\n\n%%\n% The output variable |symExp| now contains the symbolic expression for the\n% forward kinematics. This expression is the same as would be obtained by\n% the following code.\nsymp3 = p3.sym;\nq = symp3.gencoords;\nsymExpDir = symp3.fkine(q)\n\n% So we have basically two ways for deriving symbolic expressions using the\n% Robotics Toolbox.\n\n%%\n% The difference is that in addition the functional output the symbolic\n% expression has now been saved to disk along with the generated m-code and\n% Simulink blocks. The storage directory is given in |cGen.basepath|, which\n% we now add to our search path.\naddpath(cGen.basepath)\nls(cGen.basepath)\n%%\n% The m-code is contained in a specialized robot class.\nls(cGen.robjpath)\n\n%% Using the generated m-code\n% The |mdl_puma560_3| robot definition script defines some special joint\n% configurations:\n%\n% * qz         zero joint angle configuration\n% * qr         vertical 'READY' configuration\n% * qstretch   arm is stretched out in the X direction\n% * qn         arm is at a nominal non-singular configuration\n%\n% The use of the symbolic expressions and generated code will be\n% exemplified in the following based on the zero joint angle configuration.\n%\n% \nqz\n%%\n% With the generic version of the fkine function from the |SerialLink| \n% class we would compute the forward kinematics as follows:\ntic; Tz1 = p3.fkine(qz); t1 = toc\n%% \n% In order to use the generated robot specific m-functions we add them to\n% the search path and instantiate a new robot object.\naddpath(cGen.basepath)\nspecRob = eval(cGen.getrobfname)\ntic; Tz2 = specRob.fkine(qz); t2 = toc\n\n%% Speedup\n% The specialized robot version of fkine runs a little faster\n% because it only performs the computations necessary for the specific robot.\n% The speedup of the generated robot specific m-code becomes even more appearent if we \n% repeat the comparison of the execution times for dynamics\n% functions such as:\n%\n% * gravload -> cGen.gengravload\n% * inertia  -> cGen.geninertia\n% * coriolis -> cGen.gencoriolis\n% * invdyn   -> cGen.geninvdyn\n%\n% This way the specialized m-code can be used to decrease simulation times.\n%\n%%\n% We obtain the exact solution without floating point notation if we use\n% the symbolic expression as follows:\ntic; Tz1 = subs(symExp, {'q1', 'q2', 'q3'},qz); toc\n%%\n% This is however more time consuming. Most probably we might use the\n% symbolic expressions for algorithm development, controller design, \n% stability proofs as well as analysis, system identification or teaching. \n%\n% It is also possible to get the symbolic expressions for the homogenous\n% transformations of up to each individual joint. This has been found to be\n% useful for example for during derivation of analytical inverse kinematics\n% solutions. See the documentation of genfkine for details.\n%\n\n%% C-Code generation\n% Since Release 9.9 the RTB is able to also generate ready to use C-code.\n% You can enable C-code generation by activating the CodeGenerator property\n% flag |cGen.genccode|:\ncGen.genccode = true;\n%% \n% Now all higher level generator methods (|cGen.genfkine|, |cGen.geninvdyn|\n% etc. ...) also produce .c and .h files. They are written to the directory \n% specified by the |cGen.ccodepath| property. You can use the C-files in \n% your projects outside the MATLAB world. The header files are documented\n% and compatible with Doxygen.\n%\n% Instead of using the higher level generator methods, you can also\n% directly call the C-code generation routine for the model code of your\n% choice. In the following we complement the previously generated m-functions \n% for the forward kinematics by their C-equivalent:\ncGen.genccodefkine;\ndisp('Generated C-headers:')\nls(fullfile(cGen.ccodepath,'include'))\ndisp('Generated C-definitions:')\nls(fullfile(cGen.ccodepath,'src'))\n\n%% Generating C-MEX functions\n% We can use the generated C-code outside the MATLAB world and use it in\n% arbitrary C-applications. In addition we can also benefit from it inside\n% the MATLAB world by means of C-MEX functions. The automated generation of \n% C-MEX functions is controlled by the CodeGenerator flag properties\n% |cGen.genmex| and |cGen.compilemex|: \ncGen.genmex = true;\n%% \n% Now all higher level generator methods (|cGen.genfkine|, |cGen.geninvdyn|\n% etc. ...) also produce C-MEX files. The MEX files are stored in the class \n% directory |cGen.robjpath| of the specialized robot object also incorporating the \n% m-functions we generated before.\n%%\n% By default the flag compilemex is active. This means that the \n% CodeGenerator always compiles the generated MEX function after generation.\n% We require an installed C-compiler and our MATLAB MEX environment being\n% configured properly. See the MATLAB documentation ond MEX files for\n% details. In order to proceed with this demo in the case where we do not\n% have this prerequisites, we now deactivate the automatic generation:\ncGen.compilemex = false;\n%%\n% Nevhertheless, we can create the C-MEX code for the forward kinematics \n% and inspect the |cGen.robjpath| directory:\ncGen.genmexfkine\ndisp('Robot object directory with new MEX source file fkine.c:')\nls(cGen.robjpath)\n%%\n% The readily compiled MEX functions will shadow the previously generated\n% m-functions. The function calls as such remain identical. Using the\n% specialized robot object with MEX files we experience an additional and \n% substantial computation speed up compared to the robot specific m-code \n% as well as the generic rne functions (both, m and MEX version). \n% \n\n%% Inheritance\n% Even though we have not yet generated robot specific code for |SerialLink|\n% metods other than |fkine|, we can still use all functionality of\n% |SerialLink| objects with our new specialized robot object which inherits\n% from |SerialLink|.\nJ01 = p3.jacob0(qz)\nJ02 = specRob.jacob0(qz)\n\n%% A look at the generated Simulink blocks\n% The Simulink blocks are stored in a Simulink library file. By opening the\n% generated Simulink library we can investigate the already optimized robot \n% specific code within the blocks.\n% The usage of these blocks is also accompanied with a noticable speedup \n% compared to the blocks based on generic |SerialLink| objects.\neval(cGen.slib);\nsnapnow;\n%%\n% Beyond the speedup for simulations all blocks in the generated library\n% may be directly compiled for real-time operating systems such as xPC-Target or\n% dSpace systems for model based control of real hardware setups.\n% This way we avoid tedious and error prone reimplementation of the model \n% on the target hardware.\n%\n\nbdclose(cGen.slib);\n\n%% Further information\n% For further information on symbolics and code generation see the\n% documentation of the |SerialLink| and |CodeGenerator| class.\n%\n% All generated functions come with their own description headers so that information\n% about their usage can be found by typing |help funname|.\n%\n% A list of all available methods provide by the |CodeGenerator| class can be\n% displayed.\nmethods CodeGenerator\n\n%%\n% The same applies to the configurable properties:\nproperties CodeGenerator\n\n%% Cleanup\n% If we whish to clean our disk from all the generated code, we can simply\n% remove it from the search path\nrmpath(cGen.basepath)\n%%\n% and purge everything.\ncGen.purge(1)\nsnapnow\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/codegen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929053683038, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5629545710730729}}
{"text": "\nfunction DoManualShim\n\nglobal VCtl\nglobal VObj\nglobal VMag\n\nif ~isfield(VCtl,'Sh_X2_Y2')\n    warndlg('Please load Shim tab. Manual Shimming was not performed!');\n    return;\nend\n\nMxdims=size(VObj.Rho);\n[xgrid,ygrid,zgrid]=meshgrid((-(Mxdims(2)-1)/2)*VObj.XDimRes:VObj.XDimRes:((Mxdims(2)-1)/2)*VObj.XDimRes,...\n                            (-(Mxdims(1)-1)/2)*VObj.YDimRes:VObj.YDimRes:((Mxdims(1)-1)/2)*VObj.YDimRes,...\n                            (-(Mxdims(3)-1)/2)*VObj.ZDimRes:VObj.ZDimRes:((Mxdims(3)-1)/2)*VObj.ZDimRes);\n\nB0ShimField = VCtl.Sh_X .* xgrid + ...\n              VCtl.Sh_Y .* ygrid + ...\n              VCtl.Sh_Z .* zgrid + ...\n              VCtl.Sh_ZX.* zgrid .* xgrid + ...\n              VCtl.Sh_ZY.* zgrid .* ygrid + ...\n              VCtl.Sh_Z2.* zgrid .^ 2 + ...\n              VCtl.Sh_XYZ.* xgrid .* ygrid .* zgrid+ ...\n              VCtl.Sh_X2_Y2.* (xgrid .* ygrid) .^ 2;\n          \nVMag.dB0 = VMag.dB0 + B0ShimField;\n\nend", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/Src/Main/DoManualShim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5629542037193512}}
{"text": "function [s] = ADEM_sample_image(V,o,R)\n% samples a (memory mapped) image at displacement o\n% FORMAT [s] = ADEM_sample_image(V,o,R)\n% FORMAT [s] = ADEM_sample_image(o,h)\n%\n% V - a structure array containing image volume information\n% o - coordinates of foveal sampling:\n%   o(1) - oculomotor angle\n%   o(2) - oculomotor angle\n% R - retinal modulation (n x n)\n%\n% or\n%\n% o - coordinates of foveal sampling\n% h - vector of coefficients weighting images in STIM.H{:}\n%\n% s - sensory sample (n x n)\n% \n% requires a global variable with the following fields:\n% STIM.R = contrast modulation matrix that defines resolution\n% STIM.W = width of foveal sampling of an image   (default: 1/6)\n% STIM.P = image position in retinal  coordinates (default: [0;0])\n% STIM.B = basis functions or receptive fields    (default: 1)\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: ADEM_sample_image.m 6932 2016-11-16 12:11:01Z karl $\n\n\n% retinotopic predictions\n%--------------------------------------------------------------------------\nglobal STIM\nif nargin < 3\n    s     = 0;\n    for i = 1:numel(o)\n        s = s + o(i)*ADEM_sample_image(STIM.H{i},V,STIM.R);\n    end\n    return\nend\n\n% preliminaries\n%--------------------------------------------------------------------------\nif ~isfield(STIM,'R'), STIM.R = ones(64,64); end\nif ~isfield(STIM,'W'), STIM.W = 1/6;         end\nif ~isfield(STIM,'P'), STIM.P = [0;0];       end\nif ~isfield(STIM,'B'), STIM.B = 1;           end\nif ~isfield(STIM,'A'), STIM.A = 512;         end\n\n% retinotopic sampling\n%--------------------------------------------------------------------------\ndim = size(R);\ndx  = V.dim(1)/dim(1)*STIM.W;\n\ni   = dx*((1:dim(1)) - dim(1)/2) + V.dim(1)/2  + (o(1) + STIM.P(1))*16;\nj   = dx*((1:dim(2)) - dim(2)/2) + V.dim(2)/2  + (o(2) + STIM.P(2))*16;\nx   = kron(ones(1,dim(2)),i);\ny   = kron(j,ones(1,dim(1)));\nz   = ones(1,dim(1)*dim(2));\n\nx   = min(max(x,1),V.dim(1));\ny   = min(max(y,1),V.dim(2));\n\ns   = spm_sample_vol(V,x,y,z,-2); s(~s) = 1;\ns   = reshape(s,dim(1),dim(2)).*R;\ns   = STIM.B'*s*STIM.B;\n\n% eccentricity attenuation\n%--------------------------------------------------------------------------\ns   = s*exp(-o'*o/STIM.A);\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/ADEM_sample_image.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5628990458277643}}
{"text": "classdef MOEADDE < ALGORITHM\n% <multi/many> <real/integer>\n% MOEA/D based on differential evolution\n% delta --- 0.9 --- The probability of choosing parents locally\n% nr    ---   2 --- Maximum number of solutions replaced by each offspring\n\n%------------------------------- Reference --------------------------------\n% H. Li and Q. Zhang, Multiobjective optimization problems with complicated\n% Pareto sets, MOEA/D and NSGA-II, IEEE Transactions on Evolutionary\n% Computation, 2009, 13(2): 284-302.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Parameter setting\n            [delta,nr] = Algorithm.ParameterSet(0.9,2);\n\n            %% Generate the weight vectors\n            [W,Problem.N] = UniformPoint(Problem.N,Problem.M);\n            T = ceil(Problem.N/10);\n\n            %% Detect the neighbours of each solution\n            B = pdist2(W,W);\n            [~,B] = sort(B,2);\n            B = B(:,1:T);\n\n            %% Generate random population\n            Population = Problem.Initialization();\n            Z = min(Population.objs,[],1);\n\n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                % For each solution\n                for i = 1 : Problem.N\n                    % Choose the parents\n                    if rand < delta\n                        P = B(i,randperm(end));\n                    else\n                        P = randperm(Problem.N);\n                    end\n\n                    % Generate an offspring\n                    Offspring = OperatorDE(Problem,Population(i),Population(P(1)),Population(P(2)));\n\n                    % Update the ideal point\n                    Z = min(Z,Offspring.obj);\n\n                    % Update the solutions in P by Tchebycheff approach\n                    g_old = max(abs(Population(P).objs-repmat(Z,length(P),1)).*W(P,:),[],2);\n                    g_new = max(repmat(abs(Offspring.obj-Z),length(P),1).*W(P,:),[],2);\n                    Population(P(find(g_old>=g_new,nr))) = Offspring;\n                end\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/Algorithms/Multi-objective optimization/MOEA-D-DE/MOEADDE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924674, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5628990380744952}}
{"text": "function output = SSIM(Reference, Clean, Target)\n\nsim_sum=0;\n\n[m1,n1] = size(Reference);\n[m2,n2] = size(Target);\n[m3,n3] = size(Clean);\n\nr=[m1;m2;m3;];\nc=[n1/3;n2/3;n3/3;];\n\nrows=min(r);\ncols=min(c);\nfor i=1:3\n\n    x1=(Reference(1:rows,1:cols,i));\n    y=(Target(1:rows,1:cols,i));\n    x2=(Clean(1:rows,1:cols,i));\n       \n    avg = (x1 + x2)/2;\n    \n    [ssimval, ~] = ssim(y,avg);\n\n    sim_sum = sim_sum + ssimval;\n         \nend\n\noutput = sim_sum/3;\n", "meta": {"author": "lbasek", "repo": "image-denoising-benchmark", "sha": "9d753198d715b7628c8e7d9259dfa5c219d033ea", "save_path": "github-repos/MATLAB/lbasek-image-denoising-benchmark", "path": "github-repos/MATLAB/lbasek-image-denoising-benchmark/image-denoising-benchmark-9d753198d715b7628c8e7d9259dfa5c219d033ea/algoritms/matlab/SSIM/SSIM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5628990298771004}}
{"text": "%   getBox:  Given the current state, returns a number from 1 to 162\n%             designating the region of the state space encompassing the current state.\n%             Returns a value of -1 if a failure state is encountered.\n\nfunction box = getBox3(theta,thetaDot,x,xDot)\ntheta = rad2deg(theta);\nthetaDot = rad2deg(thetaDot);\nif (x < -1 || x > 1  || theta < -8 || theta > 8)     \n    box = -1;\nelse\n\n\nif (theta<-1&&theta>=-8)\n\tthetaBucket = 1;\nelseif (theta<0&&theta>=-1)\n\tthetaBucket = 2;\nelseif (theta<1&&theta>=0)\t% zero included\n\tthetaBucket = 3;\nelseif (theta<8&&theta>=1)\n\tthetaBucket = 4;\nend\n\nif (x<-0.8&&x>=-1)\n\txBucket = 1;\nelseif (x<=0.8&&x>=-0.8)\n\txBucket = 2;\nelseif (x<=1&&x>0.8)\n\txBucket = 3;\nend\n\nif (xDot<-0.5)\n\txDotBucket = 1;\nelseif (xDot>=-0.5&&xDot<=0.5)\n\txDotBucket = 2;\nelse\n\txDotBucket = 3;\nend\n\nif (thetaDot<-50)\n\tthetaDotBucket = 1;\nelseif (thetaDot>=-50&&thetaDot<=50)\n\tthetaDotBucket = 2;\nelse\n\tthetaDotBucket = 3;\nend\n\nbox = sub2ind([4,3,3,3],thetaBucket, thetaDotBucket,xBucket,xDotBucket);\nend\nreturn;", "meta": {"author": "savinay95n", "repo": "Reinforcement-learning-Algorithms-and-Dynamic-Programming", "sha": "ab531f4c5856e20800c64932a06d246c91c7f62c", "save_path": "github-repos/MATLAB/savinay95n-Reinforcement-learning-Algorithms-and-Dynamic-Programming", "path": "github-repos/MATLAB/savinay95n-Reinforcement-learning-Algorithms-and-Dynamic-Programming/Reinforcement-learning-Algorithms-and-Dynamic-Programming-ab531f4c5856e20800c64932a06d246c91c7f62c/getBox3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5628990242641287}}
{"text": "function [week, sow] = time2weektow(time)\n\n% SYNTAX:\n%   [week, sow] = time2weektow(time);\n%\n% INPUT:\n%   time = GPS time (continuous since 6-1-1980)\n%\n% OUTPUT:\n%   week = GPS week\n%   sow  = GPS seconds-of-week\n%\n% DESCRIPTION:\n%   Conversion from GPS time in continuous format (similar to datenum) to\n%   GPS time in week, seconds-of-week.\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 <http://www.gnu.org/licenses/>.\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\nsec_in_week = 7*86400;\n\nsow  = rem(time, sec_in_week);\nweek = (time - sow) / sec_in_week;\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/time/time2weektow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5628990186511572}}
{"text": "function [im, kspFull] = pocs( ksp, iter, watchProgress )\n%Partial-Fourier Reconstruction with POCS\n%\n% [im, kspFull] = pocs( kspIn, iter, watchProgr )\n%\n% === Input ===\n%\n%   kspIn:      Reduced Cartesian MRI Data-Set\n%               Any dimension may be reduced,\n%               but only one reduction dim. is allowed due to Physics/Math.\n%\n%               Allowed shapes for kspIn are...\n%                 ... Ny x Nx\n%                 ... Nc x Ny x Nx\n%                 ... Nc x Ny x Nx x Nz\n%\n%               With Nc == number of receive Channels / Coils.\n%\n%               kspIn can either be a zero-padded array, so the partial Fourier property is obvious.\n%               Or kspIn can be the measured data only, then we try to find k-space centre automagically\n%               and create a zero-padded array with the full size, first.\n%               Errors are however more likely to occur in the latter case.\n%\n%\n%   iter:       No. of iterations\n%   (optional)  default: iter = 20\n%               Try on your own if larger iter improves your results!\n%\n%   watchProgr: true/false; Whether the progress of the reconstruction should\n%   (optional)  be monitored in an image window.\n%               In 3D data, only the central partition will be shown.\n%\n%\n% === Output ===\n%\n%   im:         Reconstructed Images (channels not combined)\n%\n%   kspFull:    Reconstructed full k-space data\n%\n%\n%\n% === About the code ===\n%\n%   (1) We find out whether input data is\n%       a) already zero-filled or\n%       b) the pure asymmetric dataset, only\n%\n%       If b) is true, we zero-fill the data ourselves, which means we have to\n%       determine the dimension first, in which the partial Fourier reduction was done.\n%       We therefor find the position of the max. intensity in k-space which should\n%       be identical to k-space centre. If the k-space centre is different from the\n%       centre of the matrix, we know the partial Fourier dimension.\n%       We then enlarge the matrix to its desired full size and fill the new part\n%       with zeros.\n%       If a) was true, finding the partial Fourier dimension is easy:\n%       It is the dimension with all the zeros. :-)\n%\n%   (2) We create one low resolution image per channel/coil:\n%\n%       We need a symmetrically sampled part around the central k-space. Think of a\n%       small stripe of phase encoding lines in the central k-space.\n%       We only use these symmetric data (setting the rest zero) to reconstruct\n%       low-resolution images. In order to avoid Gibbs-Ringing, a Hamming-filter\n%       with the width of the stripe is multiplied with the data.\n%       Additionally, all the fully sampled dimensions get a Hamming filter, too,\n%       since we increase SNR, reduce further Gibbs-ringing and do not lose much\n%       resolution.\n%\n%   (3) The phase of the low-resolution images is saved\n%\n%       POCS uses the fact that k-space data of real objects (no imaginary part)\n%       have a point symmetry:\n%           S(-k)  =  S*(k)      with k = (kx, ky, kz)\n%       Our MRI objects are always complex, but we assume that phase variations\n%       are due to coil sensitivities and B0-inhomgeneities,\n%       which are both slowly varying (no high res. required).\n%       Small-scale phase pertubations will decrease the reconstruction quality.\n%\n%   (4) Reference phase is applied in image space\n%\n%       We...\n%       ... transform our zero-filled data to image space (IFFT)\n%       ... remove the phase --> abs(image)\n%       ... set the phase of our reference phase map --> image .* exp(1i.*phase)\n%       ... transform back to k-space (FFT)\n%       ... re-insert the measured data (self-consistency!)\n%       ... goto \"We...\"\n%\n%       Iterating through the above steps fills the missing k-space points\n%       with reasonable values.\n%       If the phase varies slowly and there is no aliasing, this works very well.\n%\n% Aliasing artifacts are very challenging for POCS.\n% So try to prevent aliasing in the first place (sufficient Field of View).\n\n% =========================================================================\n% Original code by Martin Blaimer\n% * changed by Uvo Hoelscher\n% * changed by Michael V\u00f6lker\n%        -- auto-detect PF dimension\n%        -- auto-find centre point/line/partition\n%        -- accept zerofilled or \"pure\" data\n%        -- for multichannel or plain 2D data (single-channel)\n%        -- 2D and 3D\n%        -- error handling\n%        -- comments, comments, comments\n%        -- added option to monitor progress\n%        -- moved code to seperate functions\n%        -- smooth transition between acquired signal and\n%           reconstructed data\n%\n% Problems? Suggestions?\n%  --> michael.voelker@mr-bavaria.de\n% =========================================================================\n\n    % ( ===================================================================\n    % Input Handling\n    %\n        if ~exist( 'ksp', 'var' ) || isempty(ksp) || ~isnumeric(ksp)\n            error('pocs:input', 'First input must be Cartesian k-space data.')\n        end\n        if ~exist('iter','var') || isempty(iter) || numel(iter) ~= 1 || ~isnumeric(iter)\n            iter = 20;\n        end\n        if ~exist('watchProgress','var')  || isempty(watchProgress) ||  numel(watchProgress) ~= 1 || ~isfinite(watchProgress)\n            watchProgress = false;\n        else\n            watchProgress = logical( watchProgress );\n        end\n\n        Ndim = ndims( ksp );\n\n        if Ndim > 4 || Ndim < 2\n            error('pocs:shape','First input ''kspace'' should have one of these shapes:\\n\\n\\t... Ny x Nx\\n\\t... Nc x Ny x Nx\\n\\t... Nc x Ny x Nx x Nz')\n        end\n        if Ndim == 2    % Ny x Nx\n            ksp = reshape( ksp, [1 size(ksp)] );    %  1 x Ny x Nx  --> now we have one channel...\n            wasAddedCoilDim = true;\n            Ndim = 3;\n        else\n            wasAddedCoilDim = false;\n        end\n\n        % read the properties of the data\n        sz   = size( ksp );\n        sz   = sz(2:end);           % the (k-)spatial size of the array (i.e. without channels)\n        prec = class( ksp );        % single or double precision?\n    % ) ===================================================================\n\n    % First: Check the sampling pattern (which parts of input are actually data?)\n    smplPtrn = reshape( sum(abs(ksp),1) ~= 0, sz);        % Ny x Nx x Nz\n\n\n    % ( ===================================================================\n    % If input data is not yet zero-filled, do it here\n    %\n        if nnz(smplPtrn) == numel(smplPtrn)     % only the sampled data were passed / |N|umber of |N|on |Z|ero elements\n\n            [ ksp, pfDim, isUpper, isLower, Nsmp ] = zerofillPFdim( ksp, wasAddedCoilDim );\n\n            sz = size( ksp );\n            sz = sz(2:end);     % ignore channels\n        else\n            [ pfDim, isUpper, isLower, Nsmp ] = detectPFdim( smplPtrn, wasAddedCoilDim );\n        end\n        clear  smplPtrn\n    % ) ===================================================================\n\n\n    if numel(sz) < 3\n        sz(3) = 1;\n    end\n    Ny = sz(1);\n    Nx = sz(2);\n    Nz = sz(3);\n\n\n    % ( ===================================================================\n    % Handle ugly problems.\n    %\n        if ~isUpper && ~isLower\n            error('pocs:UnknownErrorFound', 'I thought we are partial Fourier, but things seem to make no sense... :-(')\n        end\n    % ) ===================================================================\n\n\n\n    % =====================================================================\n    %\n    %        We can now be sure to operate with zero-padded data.\n    %\n    % =====================================================================\n\n\n\n    % initialize a cell of subscripts\n    subs = { ':', ':', ':', ':' };      % all channels / all Ny / all Nx / all Nz\n\n    % If the first entries are zero-filled (instead of the trailing ones),\n    % flip the entries so we can treat them as if we pf'ed the first half of kspace.\n    if isLower\n        subs{pfDim+1} = sz(pfDim):-1:1;     % ...esreveR\n        ksp           = ksp(subs{:});       % !ecaps-k si sihT\n        subs{pfDim+1} = 1:sz(pfDim);        % lalala, we didn't do anything...\n    end\n\n    % Find out which point is in the centre and which indices belong to the\n    % symmetrically sampled part of k-space.\n    [ centreLine, idxSym ] = findSymSampled( ksp, pfDim, Nsmp );\n\n    szSym = numel( idxSym );                % 2 * (Nsmp - centreLine) + 1\n\n    if isUpper\n        fprintf('Using %g points around point %g\\n', szSym,    centreLine    );\n    else\n        fprintf('Using %g points around point %g\\n', szSym, sz(pfDim)-centreLine+1 );\n    end\n\n    % ( ===================================================================\n    % build up a symmetric low-pass filter\n    %\n    filter = cast( 1, prec );\n    for d = 1:Ndim-1\n\n        reshRule = ones(1,Ndim);    % how the filter will be reshaped\n\n        if d ~= pfDim   % Each standard dimension gets a simple low-pass filter\n\n            filt1D = hamming( sz(d), 'periodic'  );\n\n        else            % our partial Fourier dimension gets an extra nice filter\n\n            % create a narrow filter and remove everything else\n            filt1D          = zeros(sz(d), 1, prec);            % full-size filter\n            tmp             = hann( szSym + 2, 'symmetric' );   % a very narrow window\n            filt1D(idxSym)  = tmp(2:end-1);                     % cut out the zeros at the edges (we have data there!)\n\n            % take a look:\n            %figure, plot(filt1D)\n        end\n\n        % reshape the filter according to the dimension it represents\n        reshRule(d+1) = sz(d);\n\n        filt1D = reshape( filt1D, reshRule );\n        filter = bsxfun( @times, filter, filt1D );      % iteratively build up a multidimensional filter\n    end\n    % ) ===================================================================\n\n    % Apply the low-pass filter\n    kspLowRes = bsxfun( @times, filter, ksp);\n    clear  filt1D  filter  reshRule  idxSym\n\n\n    % ( ===================================================================\n    % prerequisites prior to the iteration loop\n    %\n    %  Set everything up here, do computations that you don't have\n    %  to do in the loop, remove no longer needed variables...\n    %\n        % fftshift everything once before and after for-looping\n        %  => less overhead during iteration\n        ksp       = cmshiftnd(       ksp, [0  sz/2] );\n        kspLowRes = cmshiftnd( kspLowRes, [0  sz/2] );\n\n        % reorder arrays such that the fft-dimensions come first\n        % => faster memory access\n        ksp       = permute(       ksp, [2 3 4 1] );      % Ny x Nx x Nz x Nc\n        kspLowRes = permute( kspLowRes, [2 3 4 1] );      %\n        subs      = { subs{2}, subs{3}, subs{4}, subs{1} };\n\n        % calc. initial image and the reference phase map\n        im        =  fft( fft( fft( conj(ksp), [], 1), [], 2), [], 3);  % im's phase is wrong now, but we only want it's abs() to be correct\n        phase     = ifft(ifft(ifft( kspLowRes, [], 1), [], 2), [], 3);\n        phase     = exp(1i * angle(phase));\n\n        % We use a trick in the loop to avoid using ifft (fft is faster).\n        % We only need to calculate the factor 1/N ourselves, with N = prod(sz)\n        phase = phase ./ prod(sz);      % 1/N is absorbed inside the phase array, once\n        \n        % create image with calculated phasemap from low res image\n        im = abs(im) .* phase;\n\n        % In the loop, we want to know where we have to copy the\n        % measured data to, so we set the subscript of the pf dimension\n        % accordingly.\n        % We have to do this due to the ifftshift'ing above.\n        tmp         = false( 1, sz(pfDim));\n        tmp(1:Nsmp) = true;\n        subs{pfDim} = find(ifftshift(tmp));\n\n        % release RAM\n        clear  tmp  kspLowRes\n\n        % only keep the acquired data in memory\n        ksp = ksp(subs{:});\n    % ) ===================================================================\n\n    % Helpers for pretty-printing:\n    % Such a mess for such beautiful output!\n    b = repmat('=',1,80);\n    progress_str = 'starting POCS loop...';\n    fprintf( '%s\\n%s\\n%s   %s', b, b(1), b(1), progress_str )\n    edging = sprintf( '\\n%s\\n%s', b(1), b );\n    fprintf( edging )\n\n\n    % ( ===================================================================\n    % iterative reconstruction POCS\n    %\n    tic\n    for ii = double(~watchProgress) : iter\n\n        if ii > 0\n\n            % Fourier transform the image to k-space\n            im = fft(fft(fft(  im  ,[],1),[],2),[],3);      % \"im\" is a really bad variable name now\n                                                            % but we save a lot of RAM with this\n            % Data Consistency:\n            % insert original data where we have them\n            im(subs{:}) = ksp;                              % \"im\" is still our reconstructed k-space signal\n\n            % Fourier transform into image domain\n            im = conj( im );\n            im = fft(fft(fft(  im  ,[],1),[],2),[],3);      % Now, \"im\" is an image again.\n\n            % create image with calculated phasemap from low res image\n            im = abs(im) .* phase;\n\n            prevLength = numel(progress_str) + numel(edging);\n            t = toc;\n            ETA = (t./ii) * iter  - t;\n            progress_str = sprintf( 'Iteration %g/%g, in %g s,  ETA: %g s...', ii, iter, t, ETA );\n\n            fprintf([repmat('\\b',1,prevLength) '%s' '%s'], progress_str, edging );\n\n        end % if ii > 0\n\n        % a rough way to monitor the progress\n        %\n        if watchProgress\n            tmp = ifftshift(sqrt(sum(abs(im(:,:,1,:).^2),4)));      % due to fftshift(), the 1st partition is the central one\n            maxRange = sort( tmp(:), 'descend' );\n            maxRange = maxRange( ceil(0.05 * numel(maxRange)) );    % ignore the \"hottest\" 5%\n\n            if ~exist('pic','var')\n                pic = [tmp tmp zeros(size(tmp),prec)];\n                diffScale = 1;\n            else\n                delta = abs( pic(:,Nx+(1:Nx)) - tmp );\n                diffScale = 0.5 * maxRange / median( delta(:) );\n                pic(:,  Nx+(1:Nx)) = tmp;\n                pic(:,2*Nx+(1:Nx)) = diffScale * delta;\n                clear delta\n            end\n\n            figure(999)\n            imagesc( pic, [0    maxRange ] )\n            title(sprintf('\\\\bfiteration %g\\ninitial     |    current     |     abs(previous - current) \u00d7 %g', ii, diffScale ))\n            axis image\n            colormap(gray(256))\n            drawnow\n            clear tmp\n\n            %if Nz == 1          % little pause for 2D (too fast otherwise)\n            %    pause(2 / iter)\n            %end\n        end\n\n    end % for ii = 1:iter\n    fprintf([repmat('\\b',1, numel(progress_str) + numel(edging)) 'POCS done! (%g s)' '%s\\n\\n'], t, edging );\n    % ) ===================================================================\n\n    clear  phase  pic\n\n    % ( ===================================================================\n    % The main part is over. Time for some thoughts.\n    %\n    % We began with a dataset that had fewer data samples than would be\n    % necessary for an unambiguous image reconstruction. As a consequence,\n    % an infinite number of images corresponds to the acquired data.\n    % The above iteration picks that single image whose abs() fits the data\n    % AND whose phase corresponds to the low-resolution phase, obtained\n    % using the symmetric part of the data.\n    %\n    % Viewed in k-space, there is almost always a severe edge at the border\n    % between acquired and interpolated data, which is due to imperfections\n    % in the assumptions made.\n    % Namely, phase often has some high frequency components which cannot be\n    % accounted for in the low-resolution map. Additionally, there is noise\n    % and we may have changing contrast or trajectory errors in our MRI\n    % sequence.\n    %\n    %         ^\n    %         | A A A A A A A A   \\\n    %         | A A A A A A A A\n    %         | A A A A A A A A     acquired signal\n    %      k2 | A A A A A A A A\n    %         | A A A A A A A A   /\n    %         | I I I I I I I I   \\\n    %         | I I I I I I I I     interpolated data\n    %         | I I I I I I I I   /\n    %         ----------------->\n    %                 k1\n    %\n    % Empirically, it should be wise to create a smoother transition from\n    % the acquired part of the signal to the interpolated data.\n    %\n        Ntrans = floor( (szSym-1)/3 );      % width of the transition zone\n\n        % Create subscripts where we intend to keep the measured data, only.\n        tmp                 = false( 1, sz(pfDim));\n        tmp(1:Nsmp-Ntrans)  = true;\n        subsPure            = subs;\n        subsPure{pfDim}     = find(ifftshift(tmp));\n\n        % Create subscripts where we want to have a smooth transition between\n        % measured and phase-corrected data.\n        subsTrans           = subs;\n        subsTrans{pfDim}    = setdiff( subs{pfDim}, subsPure{pfDim} );\n\n        % build a filter for the transition:\n        tmp         = hann( 2*Ntrans+3, 'symmetric');\n        filterTrans = tmp( Ntrans+3 : end-1 );\n        filterTrans = reshape( filterTrans, [ ones(1,pfDim-1)  Ntrans  1] );\n\n        % Seperate data in unfiltered part and transition zone.\n        tmp = zeros( size(im), prec );\n        tmp(subs{:}) = ksp;\n        kspPure  = tmp(subsPure{:});\n        kspTrans = tmp(subsTrans{:});\n        clear  tmp  ksp\n\n        im = fft(fft(fft(  im  ,[],1),[],2),[],3);      % \"im\" becomes k-space signal, again\n\n        im(subsPure{:}) = kspPure;                      % strict data consistency for Nsmp-Ntrans samples\n        im(subsTrans{:}) =  bsxfun( @times,   filterTrans,  kspTrans         )     ...\n                          + bsxfun( @times, 1-filterTrans,  im(subsTrans{:}) );\n    \n        clear  subsPure  subsTrans  filterTrans  kspPure  kspTrans\n        \n        if nargout > 1\n            kspFull = im;\n        else\n            kspFull = double.empty([sz 0]);     % kspFull exists, but no memory required\n        end\n\n        im = ifft(ifft(ifft(  im  ,[],1),[],2),[],3);   % \"im\" is an image, again\n    % ) ===================================================================\n\n\n    % ( ===================================================================\n    % Undo the prerequisites (--> postrequisites???)\n    %\n        % undo the permutations\n        im      = permute(      im, [4 1 2 3] );\n        kspFull = permute( kspFull, [4 1 2 3] );\n        subs    = { subs{4}, subs{1}, subs{2}, subs{3} };\n\n        % undo the fftshifts\n        im      = cmshiftnd(      im, [0  sz/2] );\n        kspFull = cmshiftnd( kspFull, [0  sz/2] );\n\n        % undo flipping\n        if isLower\n            subs{pfDim+1} = sz(pfDim):-1:1;\n            im            = im(subs{:});\n            kspFull       = kspFull(subs{:});\n        end\n    % ) ===================================================================\n\n    if wasAddedCoilDim                              % we initially reshaped a simple 2D raw data matrix to be of size 1 x Ny x Nx\n        im      = reshape(      im, Ny, Nx, [] );\n        kspFull = reshape( kspFull, Ny, Nx, [] );\n    end\n\nend     % of pocs()\n\n\n\n\n\n\n% =========================================================================\n%                                                                         =\n%                      SWAPPED CODE                                       =\n%                                                                         =\n% =========================================================================\n\n\n\n\n\n\nfunction [ ksp, pfDim, isUpper, isLower, Nsmp ] = zerofillPFdim( ksp, wasAddedCoilDim )\n    % Only the acquired data were passed and we have to find the asymmetric\n    % dimension. Then we increase the size along this dimension and pad with 0.\n\n    Ndim    = ndims( ksp ) - 1;     % one dimension was for the channels\n    sz      = size(  ksp );\n    sz      = sz(  2:end );         % ignore channel dimension\n    Nc      = size(  ksp, 1 );\n    prec    = class( ksp );\n\n    % init some helper variables\n    pfDim    = 0;               % partial Fourier reduction dimension\n    isUpper  = false;\n    isLower  = false;\n    isPartialFourier = false(Ndim,1);\n\n    % ( ===============================================================\n    % autodetect the Partial Fourier dimension\n    %\n    for d = 1:Ndim\n\n        centre = floor( sz(d)/2 ) + 1;\n\n        tmp = squeeze( sum(abs(ksp),1) );\n        for d2 = 1:Ndim\n            if d2 ~= d\n                tmp = max(tmp,[],d2);       % keep only the maximum of non-partial data points\n            end\n        end\n        [ dummy, maxPos(d) ] = max( tmp(:) );   %#ok <-- don't use \"~\", for compatibility\n\n        if abs(maxPos(d) - centre) >= 2      % significant asymmetry ==> partial Fourier acquisition\n\n            isPartialFourier(d) = true;\n            pfDim = d;\n            Nsmp = sz(d);\n\n            isUpper = maxPos(d) > centre;   % Did we sample the upper matrix part, so the lower part is missing...\n            isLower = maxPos(d) < centre;   % ... or are the first data points missing (e.g. asymmetric echo)?\n        end\n    end % for d = 1:Ndim\n    %\n    % ) ===== (PF dim detection) ======================================\n\n\n    switch nnz(isPartialFourier)    % |N|umber of |N|on |Z|ero elements\n        case 0\n            error( 'pocs:NoPfDim', 'No partial Fourier dimension found.' )\n        case 1\n            fprintf( 'Found partial Fourier along array dimension %d\\n', pfDim + ~wasAddedCoilDim )\n        otherwise\n            error( 'pocs:TooManyPfDims', 'Partial Fourier only allowed in 1 dimension, but %g were found!', nnz(isPartialFourier) )\n    end\n\n    if pfDim == 0   % our init value above\n        error('zerofillPF:NoPF','No partial Fourier property found!')\n    end\n\n    % initialize a cell of subscripts\n    subs = { ':', ':', ':', ':' };      % all channels / all Ny / all Nx / all Nz\n\n    c = maxPos(pfDim);\n\n    if isUpper\n\n        sz(pfDim) = 2 * (c - mod(c,2));         % determine the blown-up size we want to achieve\n        subs{pfDim+1} = 1:Nsmp;\n\n    elseif  isLower\n\n        sz(pfDim) = 2 * (Nsmp - c + 1);\n        c = floor( sz(pfDim)/2 ) + 1;\n        sz(pfDim) = sz(pfDim) + 2*~mod(c,2);    % A hack for Stefan's data... keep an eye on this!\n        subs{pfDim+1} = (1:Nsmp) + (sz(pfDim)-Nsmp);\n\n    else\n        error( 'zerofillPF:PFdimNotClassified', 'Could not tell how partial Fourier was implemented.' )\n    end\n\n    % do the zerofilling\n    tmp = zeros( [Nc sz], prec );\n    tmp(subs{:}) = ksp;\n    ksp = tmp;\n\nend % of zerofillPFdim()\n\nfunction [ pfDim, isUpper, isLower, Nsmp ] = detectPFdim( smplPtrn, wasAddedCoilDim )\n    % User passed already zero-padded data. This was nice, now it's easy\n    % to find the partial Fourier dimension!\n\n    Ndim = ndims( smplPtrn );\n    sz = size( smplPtrn );\n\n    % init some helper variables\n    pfDim    = 0;               % partial Fourier reduction dimension\n    isUpper  = false;\n    isLower  = false;\n    isPartialFourier = false( Ndim, 1 );\n\n    % ( ===============================================================\n    % Determine if this is a zerofilled partial Fourier measurement\n    % and along which dimension the data is reduced.\n    %\n    % smplPtrn in Partial Fourier looks like this:\n    %\n    %     ^\n    %     | 1 1 1 1 1 1 1 1     --->  sampling pattern is the same\n    %     | 1 1 1 1 1 1 1 1           for all k1 points\n    %     | 1 1 1 1 1 1 1 1\n    %  k2 | 1 1 1 1 1 1 1 1             i.e. for programming:\n    %     | 1 1 1 1 1 1 1 1             smplPtrn == repmat( smplPtrn(:,1,1), [1 Nx Nz] )\n    %     | O O O O O 0 0 0\n    %     | O O O O O 0 0 0\n    %     | O O O O O 0 0 0\n    %      ----------------->\n    %           k1\n    %\n    for d = 1:Ndim\n\n        subs = { ones(1,sz(d)),     ... % initialize a cell of subscripts we might be interested in\n                 ones(1,sz(d)),     ...\n                 ones(1,sz(d))  };\n        subs{d} = 1:sz(d);              % we ask for all entries in the d'th dimension\n\n        idx_d = sub2ind( sz, subs{:} ); % convert to linear array indices\n\n        oneCol = smplPtrn( idx_d );     % one column of the d'th dimension\n\n        % create a rule how to reshape oneCol\n        reshRule = ones(1,Ndim);\n        reshRule(d) = sz(d);                    % e.g. reshRule = [   1   1 128 ]\n        oneCol = reshape( oneCol, reshRule);\n\n        % create a rule how to replicate oneCol\n        repRule = sz;\n        repRule(d) = 1;                         % e.g. repRule  = [ 256 256   1 ]\n\n        % Check if we get the sampling pattern again\n        % just by replicating oneCol along the other dimensions\n        isPartialFourier(d) = isequal( smplPtrn, repmat( oneCol, repRule ) );\n\n        if isPartialFourier(d)\n            pfDim = d;\n            Nsmp  = nnz( oneCol );      % how many fully sampled lines do we have?\n\n            % Sampled upper or lower part of k-space matrix?\n            isUpper = isequal( oneCol(:).', [ true( 1,Nsmp)          false(1,sz(d)-Nsmp)    ]);\n            isLower = isequal( oneCol(:).', [ false(1,sz(d)-Nsmp)    true( 1,Nsmp)          ]);\n        end\n    end\n    % ) ===============================================================\n\n    switch nnz(isPartialFourier)    % |N|umber of |N|on |Z|ero elements\n        case 0\n            error( 'pocs:NoPfDim', 'No partial Fourier dimension found.' )\n        case 1\n            fprintf( 'Found partial Fourier along array dimension %d\\n', pfDim + ~wasAddedCoilDim )\n        otherwise\n            error( 'pocs:TooManyPfDims', 'Partial Fourier only allowed in 1 dimension!' )\n    end\n\nend % of detectPFdim()\n\nfunction [ centreLine, idxSym ] = findSymSampled( ksp, pfDim, Nsmp )\n\n    Ndim = ndims( ksp ) - 1;    % one for channels\n    sz = size( ksp );\n    sz = sz(2:end);\n\n    % autodetect the central k-space line\n    %if ~exist('centreLine', 'var') || isempty(centreLine)\n        tmp = squeeze( sum(abs(ksp),1) );\n        for d = 1:Ndim\n           if d ~= pfDim\n               tmp = max(tmp,[],d);     % keep only the maximum of non-partial data points\n           end\n        end\n        [ dummy, centreLine] = max( tmp(:) );   %#ok the central line has the max intensity\n    %end\n\n    % calculate the size of the symmetric part and the full dataset\n    startSym = centreLine - (Nsmp - centreLine);    % start of our symmetric sampling\n    endSym   = centreLine + (Nsmp - centreLine);    % end of symmetric part\n    idxSym   = startSym : endSym;\n\n    if any(idxSym < 1)    ||   any(idxSym > sz(pfDim))\n       error( 'pocs:BadDataProperty' , 'Symmetric part of k-space out of bounds.\\nThe maximum k-space intensity is at index %g whereas it should be centred => near %g.\\nThe way, zerofilling was done is probably wrong.\\nCheck your input k-space.', centreLine, round(sz(pfDim)/2) )\n    end\n\nend % of findSymmetricSampled()\n\nfunction x = cmshiftnd( x, shifts)\n%Function to circularly shift N-D arrays\n\n    if nargin < 2 || all(shifts(:) == 0)\n       return                       % no shift\n    end\n\n    sz      = size( x );\n    numDims = ndims(x);             % number of dimensions\n    idx = cell(1, numDims);         % creates cell array of empty matrices,\n                                    % one cell for each dimension\n\n    for k = 1:numDims\n\n        m = sz(k);\n        p = ceil(shifts(k));\n\n        if p < 0\n            p = m + p;\n        end\n\n        idx{k} = [p+1:m  1:p];\n    end\n\n    % Use comma-separated list syntax for N-D indexing.\n    x = x(idx{:});\n\nend % of cmshiftnd()\n\n% Avoid the need for the signal toolbox and implement\n% hamming() and hann() manually:\n%\nfunction w = hamming( N, symFlag )\n%Hamming window\n%\n% w = hamming(L) returns an L-point symmetric Hamming window in the column vector w.\n% L should be a positive integer.\n%\n%  The coefficients of a Hamming window are computed from the following equation:\n%\n%       w(n) = 0.54  +  0.46 * cos(2*pi*n/N),   0 <= n <= N\n%\n%\n% w = hamming( L, 'symFlag') returns an L-point Hamming window using the window sampling\n% specified by 'symFlag', which can be either 'periodic'  or 'symmetric' (the default).\n% The 'periodic' flag is useful for DFT/FFT purposes, such as in spectral analysis.\n% The DFT/FFT contains an implicit periodic extension and the periodic flag enables a signal\n% windowed with a periodic window to have perfect periodic extension.\n% When 'periodic' is specified, hamming computes a length L+1 window and returns the first L points.\n% When using windows for filter design, the 'symmetric' flag should be used.\n%\n% --> http://www.mathworks.de/de/help/signal/ref/hamming.html\n% --> https://de.wikipedia.org/wiki/Hamming-Fenster\n\n% implemented by Michael.Voelker@mr-bavaria.de, 2012\n\n    if ~exist( 'N', 'var' ) || isempty(N) || numel(N) ~= 1 || ~isnumeric(N)  || ~isfinite(N) || N < 1 || floor(N) ~= N\n        error( 'hamming:badSize', 'Window lenght must be a positive integer.' )\n    end\n    if ~exist( 'symFlag', 'var' ) || isempty(symFlag)\n        symFlag = 'symmetric';\n    end\n\n    if N == 1\n        w = 1;\n        return\n    end\n\n    switch symFlag\n        case 'symmetric'\n            L = N-1;\n        case 'periodic'\n            L = N;\n        otherwise\n            error('hamming:symFlag', 'Unknown symmetry flag. Try ''symmetric'' (default) or ''periodic''.')\n    end\n\n    w = (0:N-1) - L/2;\n    w = 0.54  +  0.46 * cos(2*pi * w(:)./L);\n\nend % of hamming()\n\n\nfunction w = hann( N, symFlag )\n%von-Hann (Hanning) window\n%\n% w = hann(L) returns an L-point symmetric Hann window in the column vector w.\n% L must be a positive integer.\n%\n% The coefficients of a Hann window are computed from the following equation:\n%\n%      w(n) = 0.5 * (1 + cos(2*pi*n/N)),   0 <= n <= N\n%\n% The window length is L = N+1.\n%\n% w = hann(L,'sflag') returns an L-point Hann window using the window sampling specified by 'sflag',\n% which can be either 'periodic' or 'symmetric' (the default). The 'periodic' flag is useful for DFT/FFT purposes,\n% such as in spectral analysis.\n% The DFT/FFT contains an implicit periodic extension and the periodic flag enables a signal windowed\n% with a periodic window to have perfect periodic extension.\n% When 'periodic' is specified, hann computes a length L+1 window and returns the first L points.\n% When using windows for filter design, the 'symmetric' flag should be used.\n%\n% --> http://www.mathworks.de/de/help/signal/ref/hann.html\n% --> https://de.wikipedia.org/wiki/Hann-Fenster\n\n% implemented by Michael.Voelker@mr-bavaria.de, 2012\n\n    if ~exist( 'N', 'var' ) || isempty(N) || numel(N) ~= 1 || ~isnumeric(N)  || ~isfinite(N) || N < 1 || floor(N) ~= N\n        error( 'hann:badSize', 'Window lenght must be a positive integer.' )\n    end\n    if ~exist( 'symFlag', 'var' ) || isempty(symFlag)\n        symFlag = 'symmetric';\n    end\n\n    if N == 1\n        w = 1;\n        return\n    end\n\n    switch symFlag\n        case 'symmetric'\n            L = N-1;\n        case 'periodic'\n            L = N;\n        otherwise\n            error('hann:symFlag', 'Unknown symmetry flag. Try ''symmetric'' (default) or ''periodic''.')\n    end\n\n    w = (0:N-1) - L/2;\n    w = 0.5 * ( 1 + cos(2*pi * w(:)./L) );\n\nend % of hann()\n", "meta": {"author": "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.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5628990165108589}}
{"text": "function[total_cost,grad]=softmax(result,docbatch,parameter)\n    total_cost=0;\n    grad.soft_W=zeroMatrix(size(parameter.soft_W));\n    step_size=1;\n    num_word=0;\n    N=size(docbatch.target_sen_matrix,1);\n    zeroState=zeroMatrix([parameter.hidden,N]);\n    for ll=1:parameter.layer_num\n        grad.source_h{ll,1}=zeroState;\n        grad.source_c{ll,1}=zeroState;\n        for sen_tt=1:length(result.Target_sen)-1\n            grad.target_sen_h{ll,sen_tt}=zeroState;\n            grad.target_sen_c{ll,sen_tt}=zeroState;\n        end\n    end\n    for sen_tt=1:length(result.Target_sen)\n        Word_List=docbatch.target_word{sen_tt}.Word;\n        Word_Mask=docbatch.target_word{sen_tt}.Mask;\n        num_word=num_word+length(find(Word_Mask==1));\n        N=size(Word_List,1);\n        T=size(Word_List,2);\n        target_sen=result.Target_sen{sen_tt};\n        N_examples=size(Word_List,1)*size(Word_List,2);\n        predict_Words=reshape(Word_List,1,N_examples);\n        mask=reshape(Word_Mask,1,N_examples);\n        h_t=[];\n        if sen_tt==1\n            h_t=[h_t,result.source_sen{parameter.layer_num,1}];\n        else\n            dim=size(result.h_t_target_sen);\n            h_t=[h_t,result.h_t_target_sen{dim(1),sen_tt-1}];\n        end\n        dim=size(target_sen.h_t_target_word);\n        h_t=[h_t,[target_sen.h_t_target_word{parameter.layer_num,1:dim(2)-1}]];\n        [cost,grad_softmax_h]=batchSoftmax(h_t,mask,predict_Words,parameter);\n        total_cost=total_cost+cost;\n        grad.soft_W=grad.soft_W+grad_softmax_h.soft_W;\n        if sen_tt==1\n            grad.source_h{parameter.layer_num,1}=grad_softmax_h.h(:,1:N);\n        else \n            grad.target_sen_h{parameter.layer_num,sen_tt-1}=grad_softmax_h.h(:,1:N);\n        end\n        for i=1:T-1\n            grad.ht{sen_tt}{1,i}=grad_softmax_h.h(:,N*i+1:N*(i+1));\n        end\n    end\n    total_cost=total_cost/N;\n    grad.soft_W=grad.soft_W/N;\n    clear predict_Words; clear mask;\n    clear grad_softmax_h;\nend\n\nfunction[cost,softmax_grad]=batchSoftmax(h_t,mask,predict_Words,parameter)\n    unmaskedIds=find(mask==1);\n    scores=parameter.soft_W*h_t;\n    mx = max(scores,[],1);\n    scores=bsxfun(@minus,scores,mx);\n    scores=exp(scores);\n    norms = sum(scores, 1);\n    if length(find(mask==0))==0\n        scores=bsxfun(@rdivide, scores, norms);\n    else\n        scores=bsxfun(@times,scores, mask./norms); \n    end\n    scoreIndices = sub2ind(size(scores),predict_Words(unmaskedIds),unmaskedIds);\n    cost=sum(-log(scores(scoreIndices)));\n    scores(scoreIndices) =scores(scoreIndices) - 1;\n    softmax_grad.soft_W=scores*h_t';  %(N_word*examples)*(examples*diemsnion)=N_word*diemsnion;\n    softmax_grad.h=(scores'*parameter.soft_W)';%(diemsnion*N_word)*(N_word*examples)=dimension*examples\n    clear scores;\n    clear norms;\nend\n", "meta": {"author": "jiweil", "repo": "Hierarchical-Neural-Autoencoder", "sha": "2cea5c0b687e6d3dfb20dee4bec97aec6b57a95f", "save_path": "github-repos/MATLAB/jiweil-Hierarchical-Neural-Autoencoder", "path": "github-repos/MATLAB/jiweil-Hierarchical-Neural-Autoencoder/Hierarchical-Neural-Autoencoder-2cea5c0b687e6d3dfb20dee4bec97aec6b57a95f/hier_LSTM_Attention/softmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5628244285552491}}
{"text": "function inds = meshBoundaryVertexIndices(varargin)\n%MESHBOUNDARYVERTEXINDICES Indices of boundary vertices of a mesh.\n%\n%   INDS = meshBoundaryVertexIndices(V, F)\n%   INDS = meshBoundaryVertexIndices(V, E, F)\n%\n%   Example\n%     % create centered icosahedron\n%     [v, f] = createIcosahedron;\n%     v(:,3) = v(:,3) - mean(v(:,3));\n%     % convert to simili-sphere\n%     [v2, f2] = subdivideMesh(v, f, 3);\n%     v3 = normalizeVector3d(v2);\n%     % clip with plane\n%     plane = createPlane([0 0 0], [-1 -2 3]);\n%     [vc, fc] = clipMeshVertices(v3, f2, plane, 'shape', 'plane');\n%     figure; drawMesh(vc, fc); axis equal; view(3);\n%     % draw boundary vertices\n%     inds = meshBoundaryVertexIndices(vc, fc);\n%     hold on; drawPoint3d(vc(inds,:), 'k*');\n%\n%   See also \n%     meshes3d, meshBoundary, meshBoundaryEdgeIndices, meshEdgeFaces\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2019-05-01, using Matlab 8.6.0.267246 (R2015b)\n% Copyright 2019-2022 INRA - Cepia Software Platform\n\n[vertices, edges, faces] = parseMeshData(varargin{:});\n\n% Compute edge-vertex map if not specified\nif isempty(edges)\n    edges = meshEdges(vertices, faces);\nend\n\n% compute edges to faces map\nedgeFaces = meshEdgeFaces(vertices, edges, faces);\n\nborderEdges = sum(edgeFaces == 0, 2) > 0;\n\ninds = edges(borderEdges, :);\ninds = unique(inds(:));\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/meshBoundaryVertexIndices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.5628082874553956}}
{"text": "function linpack_z_test18 ( )\n\n%*****************************************************************************80\n%\n%% TEST18 tests ZPBDI.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 June 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 3;\n  m = 1;\n  lda = m+1;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST18\\n' );\n  fprintf ( 1, '  For a double precision complex (C)\\n' );\n  fprintf ( 1, '  positive definite hermitian band matrix (PB),\\n' );\n  fprintf ( 1, '  ZPBDI computes the determinant as\\n' );\n  fprintf ( 1, '    det = MANTISSA * 10**EXPONENT\\n' );\n  fprintf ( 1, '\\n' );\n%\n%  Set the value of the superdiagonal and diagonal.\n%\n  a(1,1) = complex ( 0.0000,  0.0000 );\n  a(1,2) = complex ( 2.1341, -0.2147 );\n  a(1,3) = complex ( 2.0905,  1.1505 );\n\n  a(2,1) = complex ( 4.5281,  0.0000 );\n  a(2,2) = complex ( 5.0371,  0.0000 );\n  a(2,3) = complex ( 4.7638,  0.0000 );\n\n  [ a, info ] = zpbfa ( a, lda, n, m );\n\n  if ( info ~= 0 )\n    fprintf ( 1, '  Error!  ZPBFA returns INFO = %d\\n', info );\n    return\n  end\n\n  det = zpbdi ( a, lda, n, m );\n\n  fprintf ( 1, '  Determinant = %f * 10^(%f)\\n', det(1), det(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_z/linpack_z_test18.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.5628082843714289}}
{"text": "% em_test_setup.m\n%\n% create sample image, system matrix, and sinograms for examples\n% and testing of Poisson emission maximum likelihood (ML) algorithms\n% creates: ig sg xtrue G proj ci ytrue ri yi\n%\n% Copyright Jan 1998, Jeff Fessler, University of Michigan\n\n% true emission image\nif ~isvar('xtrue'), printm 'xtrue'\n\tif ~isvar('ig')\n\t\tig = image_geom('nx', 64, 'ny', 60, 'fov', 500);\n\tend\n\txtrue = read_zubal_emis('nx', ig.nx, 'ny', ig.ny);\n\tmumap = read_zubal_attn('nx', ig.nx, 'ny', ig.ny);\n\tim plc 2 3\n\tim(1, xtrue, 'emission image'), cbar\n\tim(2, mumap, 'attenuation map'), cbar\n\n\t% reconstruction mask (which pixels do we estimate?)\n\tig.mask = ig.circ(220, 180) > 0;\n\tim(3, ig.mask + xtrue, 'support mask + xtrue')\nend\n\n\n% system matrix G\nif ~isvar('G'), printm 'system'\n\tsg = sino_geom('par', 'nb', ig.nx+2, 'na', ig.ny*3/2, ...\n\t\t'dr', 528 / (ig.nx+2));\n\n\t% simple strip-integral system model\n\tG = Gtomo2_strip(sg, ig, 'single', 1);\n\n\tif isvar('f.wtf') && has_mex_jf\n\t\tif exist(f.wtf), delete(f.wtf), end\n\t\twtf_write(f.wtf, G, ig.nx, ig.ny, sg.nb, sg.na);\n\tend\n\tif isvar('f.wtr') && has_mex_jf && has_aspire\n\t\tif exist(f.wtr), delete(f.wtr), end\n\t\tos_run(sprintf('wt -chat 0 col2row %s %s', f.wtr, f.wtf))\n\tend\nend\n\n\n% noisy measurements\nif ~isvar('yi'), printm 'data yi'\n\tproj = G * xtrue;\n\tli = G * mumap;\n\tprintm('Maximum line integral = %g', max(li(:)))\n\tif ~isvar('f.count'), f.count = 1e5; end\n\t% detector efficiency variations per CTI 931 PET scanner\n\tci = exp(0.3 * randn(size(proj)));\n\tci = ci .* exp(-li);\n\tci = f.count / sum(ci(:) .* proj(:)) * ci;\n\tci = dsingle(ci);\n\tytrue = ci .* proj;\n\tif ~isvar('f.randpercent')\n\t\tf.randpercent = 10;\n\tend\n\tri = f.randpercent / 100 * mean(ytrue(:)) * sg.ones;\n\tri = dsingle(ri);\n\trng(0)\n\tyi = poisson(ytrue + ri);\n\n\tim(4, ytrue, 'ytrue: true projections'), cbar\n\tim(5, yi, 'yi: noisy projections'), cbar\n\tclear ytrue proj\nend\n\n% FBP reconstruction\nif ~isvar('xfbp'), printm 'fbp'\n\txfbp = em_fbp(sg, ig, yi, ci, ri);\n\txfbp = max(xfbp, 0);\n\tim(6, xfbp, 'FBP Reconstruction'), cbar\nend\n\n% save to files if needed\nif isvar('f.yi')\n\tfld_write(f.yi, yi, 'check', 0)\nend\nif isvar('f.ci')\n\tfld_write(f.ci, ci, 'check', 0)\nend\nif isvar('f.ri')\n\tfld_write(f.ri, ri, 'check', 0)\nend\nif isvar('f.mask')\n\tfld_write(f.mask, ig.mask, 'check', 0)\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/emission/em_test_setup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5626153725275723}}
{"text": "function [ll,lls,Ht] = gogarch_likelihood(parameters,data,p,q,gjrType,P,L,isOgarch,isInference)\n% Log-likelihood for use in estimation GOGARCH and OGARCH models\n%\n% USAGE:\n%  [LL,LLS,HT] = gogarch_likelihood(PARAMETERS,DATA,P,Q,GJRTYPE,P,L,ISOGARCH,ISINFERNCE)\n%\n% INPUTS:\n%   PARAMETERS - K*(K-1)/2 + sum(P) + sum(Q) by 1 vector of parameters (only sum(P) + sum(Q) if ISOGARCH)\n%   DATA       - K by K by Tarray of data (either realized measures or outer-products of daily data)\n%   P          - K by 1 vector of positive, scalar integer representing the number of symmetric innovations\n%   Q          - K by 1 vector of non-negative, scalar integer representing the number of conditional covariance lags\n%   GJRTYPE    - K by 1 vector containing either 1 (TARCH/AVGARCH) or 2 (GJRGARCH/GARCH/ARCH)\n%   P          - Eigenvector of unconditional covariance matrix of the data\n%   L          - Diagonal matrix containing the eigenvalues of unconditional covariance matrix of the data\n%   ISOGARCH   - Boolean indicating that the model is OGARCH (otherwise GOGARCH)\n%   ISINFERNCE - Boolean indicating the likelihood is being used for inference, so that the first\n%                  K(K+1)/2 parameters are ivech(S)\n%\n% OUTPUTS:\n%   LL         - The log likelihood computed at PARAMETERS\n%   LLS        - T by 1 vector of log-likelihoods\n%   HT         - K by K by T vector of conditional covariances\n%\n% COMMENTS:\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 4/15/2012\n\n[k,~,T] = size(data);\nif size(parameters,1)>size(parameters,2)\n    parameters = parameters';\nend\n\noffset = 0;\nif isInference\n    S =  ivech(parameters(1:k*(k+1)/2));\n    [P,L] = eig(S);\n    P = P';\n    offset = offset + k*(k+1)/2;\nend\n\nif ~isOgarch\n    phi = parameters(offset + (1:k*(k-1)/2));\n    U = phi2u(phi);\n    offset = offset + k*(k-1)/2;\nelse\n    U = eye(k);\nend\nZ = P*L^(0.5)*U;\nZinv = U'*L^(-0.5)*P';\nstdData = zeros(k,k,T);\nfor t=1:T\n    stdData(:,:,t) = Zinv*data(:,:,t)*Zinv';\nend\n% Univariate GARCH models\nV = zeros(T,k);\nw = .06 * .94.^(0:sqrt(T));\nw = w/sum(w);\nlikData = zeros(T,k);\nfor i=1:k\n    count = p(i) + q(i);\n    volParameters = parameters(offset + (1:count));\n    volParameters = max(volParameters,0);\n    volParameters = [1-sum(volParameters) volParameters]; %#ok<AGROW>\n    offset = offset + count;\n    likData(:,i) = squeeze(stdData(i,i,:));\n    volData = sqrt(likData(:,i));\n    backCast = w*volData(1:length(w)).^2;\n    v = tarch_core_simple(volData,volParameters,backCast,0,p(i),0,q(i),gjrType(i));\n    V(:,i) = v;\nend\n\nlikConst = k*log(2*pi);\nlogdetZZp = log(det(Z*Z'));\nlls = 0.5*(likConst + logdetZZp + sum(log(V),2) + sum(likData./V,2));\nll = sum(lls);\n\nif ~isreal(ll) || isnan(ll) || isinf(ll)\n    ll = 1e7;\nend\n\nif nargout>2\n    Ht = zeros(k,k,T);\n    for t=1:T\n        Ht(:,:,t) = Z*diag(V(t,:))*Z';\n    end\nend", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/multivariate/gogarch_likelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5626153706494842}}
{"text": "function varargout = chebyball(F)\n%CHEBYBALL Computes Chebyshev ball of a constraint object\n%\n% If two outputs are requested, the numerical data is returned\n% [xc,R] = chebyball(F)\n%\n% If three outputs are requrested, the symbolic model (x-xc)'(x-xc)<R^2 is\n% appended\n% [xc,R,C] = chebyball(F)\n%\n% If only one output is requested, only the symbolic constraint is returned\n% C = chebyball(F)\n\nswitch nargout\n    case 0\n        f = chebyball(lmi(F))\n    case 1\n        [f] = chebyball(lmi(F));\n        varargout{1} = f;\n    case 2\n        [xc,R] = chebyball(lmi(F));\n        varargout{1} = xc;\n        varargout{2} = R;\n    case 3\n        [xc,R,f] = chebyball(lmi(F));\n        varargout{1} = xc;\n        varargout{2} = R;\n        varargout{3} = f;\n    otherwise\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/extras/@constraint/chebyball.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5626153693745202}}
{"text": "function [H_t] = shift_t(H,t)\n\n% Shifts the matrix H by t spots to the right\n% Use a negative t to shift to the left\n% To be used with the convolutive NMF algorithms\n\n[K,N] = size(H);\n\nif t>0\n      H_trunc = H(:,1:N-t);\n      H_t = [zeros(K,t)+eps,H_trunc];\n    \nelseif t<0\n      H_trunc = H(:,-t+1:end);\n      H_t = [H_trunc,zeros(K,-t)+eps];\nelse\n      H_t = H;\nend\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/convolutive/convolutive_auxiliary/shift_t.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7341195385342972, "lm_q1q2_score": 0.5625511356440303}}
{"text": "function [i_min,i_max,j_min,j_max,lew] = get_lew(img,smap_b)\n% cut a local window from the original img, and also return \n% lew's coordinates in the original img\n\n    [all_i,all_j] = find(smap_b~=0);\n    rescale = 0.2;\n    i_min = round(min(all_i)*(1-rescale));   \n    i_max = round(max(all_i)*(1+rescale));    \n    j_min = round(min(all_j)*(1-rescale));   \n    j_max = round(max(all_j)*(1+rescale)); \n    \n    img_size = size(img(:,:,1));\n    [i_min,i_max,j_min,j_max] = handle_cross_boundary(i_min,i_max,j_min,j_max,img_size);\n    lew = img(i_min:i_max,j_min:j_max,:);\nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/AirportDetection-master/grsl/funcs/get_lew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5625511356440301}}
{"text": "function [precision,recall] = evaluate(NAME,boundingBoxes, threshold)\ntmpName = extractBefore(NAME,'.jpg');\nPATH_REAL = \"Data/\" + tmpName + \".txt\";\nfileID = fopen(PATH_REAL{1},'r');\nformatSpec = ' %d ';\nBoundingData = fscanf(fileID,formatSpec);\n\n[realObjectCount,~] = size(BoundingData);\nrealObjectCount = (realObjectCount - 1)/4;\ncorrectObjects  = 0;\n[~,detectedCount] = size(boundingBoxes);\n\nfor i=1:detectedCount\n    ourBox = boundingBoxes{1,i};\n    topX = ourBox(1,1);\n    topY = ourBox(1,2);\n    lowX = ourBox(1,3);\n    lowY = ourBox(1,4);\n    for b=1:realObjectCount\n        rtopX = BoundingData(1 + (4*(b-1)),1);\n        rtopY = BoundingData(2 + (4*(b-1)),1);\n        rlowX = BoundingData(3 + (4*(b-1)),1);\n        rlowY = BoundingData(4 + (4*(b-1)),1);\n        width = 0;\n        if lowX > topX\n            width =  lowX-topX;\n        else\n             width =  topX-lowX;\n        end\n        height = 0;\n        if lowY > topY\n            height =  lowY-topY ;\n        else\n             height =  topY-lowY;\n        end\n        \n        realWidth = 0;\n        if rlowX > rtopX\n            realWidth =  rlowX-rtopX;\n        else\n             realWidth =  rtopX-rlowX;\n        end\n        realHeight = 0;\n        if rlowY > rtopY\n            realHeight =   rlowY-rtopY ;\n        else\n             realHeight =  rtopY-rlowY;\n        end\n        \n        ourBox  = [ topX,   topY, width ,height  ];\n        realBox = [ rtopX, rtopY,realWidth ,realHeight];\n        overlapRatio = bboxOverlapRatio(ourBox,realBox);\n        if overlapRatio > threshold\n            correctObjects = correctObjects + 1;\n            break;\n        end\n    end\nend\n\n\nrecall = correctObjects /realObjectCount ;\nprecision = correctObjects /detectedCount ;\nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u8bc6\u522b\u7b97\u6cd5/Object Recognition based on super pixel/evaluate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5625511233501278}}
{"text": "function fx1 = p00_fx1 ( prob, x )\n\n%*****************************************************************************80\n%\n%% P00_FX1: first derivative of a function specified by problem number.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 January 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer PROB, the number of the problem.\n%\n%    Input, real X, the point at which F is to be evaluated.\n%\n%    Output, real FX1, the first derivative of the function at X.\n%\n  if ( prob == 1 )\n    fx1 = p01_fx1 ( x );\n  elseif ( prob == 2 )\n    fx1 = p02_fx1 ( x );\n  elseif ( prob == 3 )\n    fx1 = p03_fx1 ( x );\n  elseif ( prob == 4 )\n    fx1 = p04_fx1 ( x );\n  elseif ( prob == 5 )\n    fx1 = p05_fx1 ( x );\n  elseif ( prob == 6 )\n    fx1 = p06_fx1 ( x );\n  elseif ( prob == 7 )\n    fx1 = p07_fx1 ( x );\n  elseif ( prob == 8 )\n    fx1 = p08_fx1 ( x );\n  elseif ( prob == 9 )\n    fx1 = p09_fx1 ( x );\n  elseif ( prob == 10 )\n    fx1 = p10_fx1 ( x );\n  elseif ( prob == 11 )\n    fx1 = p11_fx1 ( x );\n  elseif ( prob == 12 )\n    fx1 = p12_fx1 ( x );\n  elseif ( prob == 13 )\n    fx1 = p13_fx1 ( x );\n  elseif ( prob == 14 )\n    fx1 = p14_fx1 ( x );\n  elseif ( prob == 15 )\n    fx1 = p15_fx1 ( x );\n  elseif ( prob == 16 )\n    fx1 = p16_fx1 ( x );\n  elseif ( prob == 17 )\n    fx1 = p17_fx1 ( x );\n  elseif ( prob == 18 )\n    fx1 = p18_fx1 ( x );\n  elseif ( prob == 19 )\n    fx1 = p19_fx1 ( x );\n  else\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'P00_FX1 - Fatal error!\\n' );\n    fprintf ( 1, '  Illegal problem number = %d\\n', prob );\n    error ( 'P00_FX1 - 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/test_zero/p00_fx1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.5625511188925539}}
{"text": "%% Image Processing for Microchannel Flow experiment\n% Prototype code:\n% Using images taken in the experiment:\n%\n% 1st image fluid flow: 20 mu L/min\n% 2st image fluid flow: 10 mu L/min\n%\n% Microchannel 1: 1808.bmp & 1813.bmp\n% Microchannel 2: 1824.bmp & 1828.bmp\n% Microchannel 3: 1834.bmp & 1838.bmp\n% Microchannel 4: 1843.bmp & 1847.bmp\n% Microchannel 5: 1855.bmp & 1860.bmp\n\ntarget = {'1808.bmp' '1813.bmp'...\n    '1824.bmp' '1828.bmp' ...\n    '1834.bmp' '1838.bmp' ...\n    '1843.bmp' '1847.bmp' ...\n    '1855.bmp' '1860.bmp'};\n%or \nnumber = [1808 1813 1824 1828 1834 1838 1843 1847 1855 1860];\n\n%Pix_value = [0.31 0.31 0.31 0.31 0.31 0.31 0.31 0.31 0.31 0.31];\n\n%% Load images\nname = strcat(num2str(number(1)),'.bmp');\nimage = imread(name);\n\n%% Apply filter\nh = fspecial('unsharp');\nimage2 = imfilter(image,h); % apply X filter \n\n%% Convert to gray scale\nimage3 = rgb2gray(image); % conver Original to gray scales\nimage4 = rgb2gray(image2); % conver Filtered to gray scales\n\n%% Create image negative\n% Original Gray\nimage5 = double(image3);\nscale_image = 1/max(image5(:)); % scale_image = 1/255\nneg_image5 = 1-image5*scale_image;\n\n% Filtered Gray\nimage6 = double(image4);\nscale_image = 1/max(image6(:)); % scale_image = 1/255\nneg_image6 = 1-image6*scale_image;\n\n%% Remove values below an specific Pix_value\nPix_value = 0.31;\n\n[n,m,p] = size(neg_image5);\nfor k = 1:p\n    for j = 1:n;\n        for i = 1:m;\n            if neg_image5(j,i,k) >= Pix_value\n                neg_image5(j,i,k) = 0;\n            else\n                % do nothing\n            end\n        end\n    end\nend\n[n,m,p] = size(neg_image6);\nfor k = 1:p\n    for j = 1:n;\n        for i = 1:m;\n            if neg_image6(j,i,k) >= Pix_value\n                neg_image6(j,i,k) = 0;\n            else\n                % do nothing\n            end\n        end\n    end\nend\n\n%% Plot pictures\nfigure(1); \nsubplot(2,3,1); imshow(image); title('Original');\nsubplot(2,3,4); imshow(image2); title('Filtered Image');\nsubplot(2,3,2); imshow(image3); title('Gray Image with filter');\nsubplot(2,3,5); imshow(image4); title('Gray Image with out filter');\nsubplot(2,3,3); imshow(neg_image5); title('Original, filtered an processed');\nsubplot(2,3,6); imshow(neg_image6); title('negative of the filtered and processed');\n\n%% Save gray_imageX\nname2 = strcat(num2str(number(1)),'_gray.bmp');\nimwrite(image4,name2,'bmp');\n\n%% Save neg_imageX\nname2 = strcat(num2str(number(1)),'_neg.bmp');\nimwrite(neg_image6,name2,'bmp');\n\n%% Compute Mixing Index\nI = neg_image6;      % Use values in neg_image6 for the difusion analysis.\nI_mean = mean(I(:)); % Find the average of the image intensity values.\nx = find(I);         % find indices of non-zero values.\nN = length(x);       % Total number of non-zero values.\n\nMix_index = 1-(1/I_mean)*sqrt(sum(sum((I - I_mean).^2))/N);\n\n% Now that I sure what I want to do I'll create a function to evaluate\n% automatically data picture.", "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/Microchannel/microchannel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5625102081619904}}
{"text": "function idx = getNearest(data, centers,trans)\n% idx = getNearest(data, centers)\n%\n% Gets indices of centers closest (in Euclidean space) to each data point\n%\n% data(ndata, nvars)\n% centers(ncenters, nvars)\n% idx(ndata, 1)\n\n% dist(a, b) = ||a-b|| = sum(a.^2) - 2*a*b' + sum(b.^2) for 1xnvars vectors\n% a and b.  \n\nif(~exist('trans','var'))\n    centers = centers';\nend\ncenterssq = sum(centers.^2, 1);\n    \ndistmat = repmat(centerssq, [size(data,1) 1]);\ndistmat = distmat - 2*data * centers;\n\n[dist, idx] = min(distmat, [], 2);\n\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/features/getNearest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5625101964927289}}
{"text": "function tests = test_ft_connectivity_mutualinformation\n\n% MEM 1gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_connectivity_mutualinformation\n\nif nargout\n  % assume that this is called by RUNTESTS\n  tests = functiontests(localfunctions);\nelse\n  % assume that this is called from the command line\n  func = localfunctions;\n  for i=1:numel(func)\n    fprintf('evaluating %s\\n', func2str(func{i}));\n    feval(func{i});\n  end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction test_chan_time(testCase)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nnchan  = 6;\nntime  = 100000;\ndat    = randn(nchan, ntime);\n\n%   histmethod = The way that histograms are generated from the data. Possible values\n%                are 'eqpop' (default), 'eqspace', 'ceqspace', 'gseqspace'.\n%                See the help of the 'binr' function in the ibtb toolbox for more information.\n%   numbin     = scalar value. The number of bins used to create the histograms needed for\n%                the entropy computations\n%   opts       = structure that is passed on to the 'information' function in the ibtb\n%                toolbox. See the help of that function for more information.\n%   refindx    = scalar value or 'all'. The channel that is used as 'reference channel'.\n\nresult = {};\nresult{end+1} = ft_connectivity_mutualinformation(dat, 'method', 'ibtb', 'histmethod', 'eqpop'    , 'numbin', 5);\nresult{end+1} = ft_connectivity_mutualinformation(dat, 'method', 'ibtb', 'histmethod', 'eqspace'  , 'numbin', 5);\nresult{end+1} = ft_connectivity_mutualinformation(dat, 'method', 'ibtb', 'histmethod', 'ceqspace' , 'numbin', 5);\nresult{end+1} = ft_connectivity_mutualinformation(dat, 'method', 'ibtb', 'histmethod', 'gseqspace', 'numbin', 5);\nresult{end+1} = ft_connectivity_mutualinformation(dat, 'method', 'ibtb', 'histmethod', 'eqpop'    , 'numbin', 50);\nresult{end+1} = ft_connectivity_mutualinformation(dat, 'method', 'ibtb', 'histmethod', 'eqspace'  , 'numbin', 50);\nresult{end+1} = ft_connectivity_mutualinformation(dat, 'method', 'ibtb', 'histmethod', 'ceqspace' , 'numbin', 50);\nresult{end+1} = ft_connectivity_mutualinformation(dat, 'method', 'ibtb', 'histmethod', 'gseqspace', 'numbin', 50);\nresult{end+1} = ft_connectivity_mutualinformation(dat, 'method', 'gcmi');\n\n% all iterations were done with (slightly) different options, hence the results should not be equal\nfor i=1:numel(result)\n  for j=(i+1):numel(result)\n    assert(~isequaln(result{i}, result{j}), 'the results %d and %d should not be equal', i, j);\n  end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_ft_connectivity_mutualinformation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7025300449389327, "lm_q1q2_score": 0.5625101882147148}}
{"text": "function varargout = resolutionmerge(varargin)\n% RESOLUTIONMERGE M-file for resolutionmerge.fig\n%      \n% GUI for improving resolution of lower resolution image using higher\n% resolution image using RGB-to-HSI conversion.\n% Images have to be spatially registered.\n%\n% Monochromatic (gray scale) low resolution image is converged to colored\n% image by false color mapping to \"hot\" color scheme. This RGB image is\n% then converted to Hue, Saturation and Value (HSV) image. Value component is replaced\n% by higher resolution image and the resulting HSV image is converted back to\n% RGB. This RGB merged image converted to gray scale is a merged image with\n% improved spatial resolution.\n% \n% To run, type:\n% >> resolutionmerge\n%\n% Can work with any type of color or monochromatic image. If images are colored\n% they are converted to gray scale first and then merged.\n% To load variables from matlab file, the file should contain variables\n% LOWRES and HIGHRES\n%\n% created by K.Artyushkova\n% February 2010\n%\n% \n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name',       mfilename, ...\n                   'gui_Singleton',  gui_Singleton, ...\n                   'gui_OpeningFcn', @resolutionmerge_OpeningFcn, ...\n                   'gui_OutputFcn',  @resolutionmerge_OutputFcn, ...\n                   'gui_LayoutFcn',  [] , ...\n                   'gui_Callback',   []);\nif nargin && ischar(varargin{1})\n    gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n    gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before resolutionmerge is made visible.\nfunction resolutionmerge_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject    handle to figure\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n% varargin   command line arguments to resolutionmerge (see VARARGIN)\n\n% Choose default command line output for resolutionmerge\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes resolutionmerge wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = resolutionmerge_OutputFcn(hObject, eventdata, handles) \n% varargout  cell array for returning output args (see VARARGOUT);\n% hObject    handle to figure\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n%% Input section \n% --------------------------------------------------------------------\nfunction load_low_res_1_Callback(hObject, eventdata, handles)\n% hObject    handle to load_low_res_1 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n[filename, pathname]=uigetfile('*.*','Open low resolution image');\ncd(pathname)\n[N,M]=size(filename);\nimage=imread(char(filename));\n[n,m,p]=size(image);\nif p==3\n    lowres=rgb2gray(image);\nelse\n    lowres=image;\nend\naxes(handles.axes1)\nhandles.lowres=lowres;\niptsetpref('ImshowAxesVisible', 'on')\nimagesc(uint8(lowres)), colormap(gray)\nguidata(hObject,handles)\n    \n\n% --------------------------------------------------------------------\nfunction open_lowres_Callback(hObject, eventdata, handles)\n% hObject    handle to open_lowres (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n[filename, pathname]=uigetfile('*.mat','Open low resolution image. Image should be saved in variable LOWRES');\ncd(pathname)\nD=load (filename, 'lowres');\nimage=D.lowres;\n[n,m,p]=size(image);\nif p==3\n    lowres=rgb2gray(image);\nelse\n    lowres=image;\nend\naxes(handles.axes1)\nhandles.lowres=lowres;\niptsetpref('ImshowAxesVisible', 'on')\nimagesc(uint8(lowres)), colormap(gray)\nguidata(hObject,handles)\n\n% --------------------------------------------------------------------\nfunction load_highres_Callback(hObject, eventdata, handles)\n% hObject    handle to load_highres (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n[filename, pathname]=uigetfile('*.*','Open high resolution image');\ncd(pathname)\n[N,M]=size(filename);\nimage=imread(char(filename));\n[n,m,p]=size(image);\nif p==3\n    highres=rgb2gray(image);\nelse\n    highres=image;\nend\naxes(handles.axes2)\nhandles.highres=highres;\niptsetpref('ImshowAxesVisible', 'on')\nimagesc(uint8(highres)), colormap(gray)\nguidata(hObject,handles)\n    \n% --------------------------------------------------------------------\nfunction Open_highres_Callback(hObject, eventdata, handles)\n% hObject    handle to Open_highres (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n[filename, pathname]=uigetfile('*.mat','Open high resolution image. Image should be saved in variable LOWRES');\ncd(pathname)\nD=load (filename, 'highres');\nimage=D.highres;\n[n,m,p]=size(image);\nif p==3\n    highres=rgb2gray(image);\nelse\n    highres=image;\nend\naxes(handles.axes2) \nhandles.highres=highres;\niptsetpref('ImshowAxesVisible', 'on')\nimagesc(uint8(highres)), colormap(gray)\nguidata(hObject,handles)\n\n\n% --------------------------------------------------------------------\nfunction Untitled_1_Callback(hObject, eventdata, handles)\n% hObject    handle to Untitled_1 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n%% Main algorithm\n% --- Executes on button press in Merge_resolution.\nfunction Merge_resolution_Callback(hObject, eventdata, handles)\n% hObject    handle to Merge_resolution (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\nlowres=handles.lowres;\nhighres=handles.highres;\nmap=hot(256);\nR=ind2rgb(lowres,map);\naxes(handles.axes3) \niptsetpref('ImshowAxesVisible', 'on')\nimagesc(R), colormap(hot)\nHSV=rgb2hsv(R);\nHSV_sub=HSV;\nHSV_sub(:,:,3)=highres;\nmerged=hsv2rgb(HSV_sub);\nmerged=uint8(merged);\nmergedG=rgb2gray(merged);\naxes(handles.axes4) \niptsetpref('ImshowAxesVisible', 'on')\nimagesc(uint8(mergedG)), colormap(gray)\nhandles.merged=merged;\nhandles.mergedG=mergedG;\nguidata(hObject, handles);\n\n\n% --- Executes on button press in displaycolor.\nfunction displaycolor_Callback(hObject, eventdata, handles)\n% hObject    handle to displaycolor (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of displaycolor\nmerged=handles.merged;\naxes(handles.axes4) \niptsetpref('ImshowAxesVisible', 'on')\nimagesc(uint8(merged))\n\n% --- Executes on button press in disp_grayscale.\nfunction disp_grayscale_Callback(hObject, eventdata, handles)\n% hObject    handle to disp_grayscale (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of disp_grayscale\nmergedG=handles.mergedG;\naxes(handles.axes4) \niptsetpref('ImshowAxesVisible', 'on')\nimagesc(uint8(mergedG)), colormap(gray)\n\n\n% --------------------------------------------------------------------\nfunction Untitled_2_Callback(hObject, eventdata, handles)\n% hObject    handle to Untitled_2 (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\n\n%% Output section\n% --------------------------------------------------------------------\nfunction save_mat_Callback(hObject, eventdata, handles)\n% hObject    handle to save_mat (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\nmergedG=handles.mergedG;\nmerged=handles.merged;\ndatapath = uigetdir;\ncd(datapath)\n[filename, pathname] = uiputfile('*.mat', 'save merged image into mat file');\nsave(filename, 'merged','mergedG')\n\n% --------------------------------------------------------------------\nfunction save_tiff_Callback(hObject, eventdata, handles)\n% hObject    handle to save_tiff (see GCBO)\n% eventdata  reserved - to be defined in a future version of MATLAB\n% handles    structure with handles and user data (see GUIDATA)\nmergedG=handles.mergedG;\nmerged=handles.merged;\ndatapath = uigetdir;\ncd(datapath)\nimwrite(uint8(mergedG),'mergedG.tiff','tiff')\nimwrite(uint8(merged),'merged.tiff','tiff')\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/26714-image-fusion-resolution-merge-improve-spatial-resolution/resolutionmerge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5624168686511866}}
{"text": "function Inds = sllabelinds(labels, labelset)\n%SLLABELINDS Extract indices corresponding to specified labels\n%\n% $ Syntax $\n%   - Inds = sllabelinds(labels, labelset)\n%\n% $ Arguments $\n%   - labels:       The labels of samples\n%   - labelset:     The set of labels whose indices to be extracted\n%   - Inds:         The cell array of indices extracted for labelset\n%\n% $ Description $\n%   - Inds = sllabelinds(labels, labelset) extracts the indices \n%     corresponding to the labels specified in labelset. Suppose the\n%     labelset is given by [l1, l2, ...], then Inds would be like\n%     {[i11, i12, ...], [i21, i22, ...], ...}, where [i11, i12, ...] is\n%     a row vector of indices corresponding to l1, so that \n%     labels(i11) = labels(i12) = ... = l1.\n%   \n% $ History $\n%   - Created by Dahua Lin, on Aug 31, 2006\n%\n\n%% parse and verify input\n\nif ~isvector(labels) || ~isnumeric(labels)\n    error('sltoolbox:invalidarg', ...\n        'labels should be a numeric vector');\nend\n\nif size(labels, 1) ~= 1\n    labels = labels(:)';\nend\n\n%% re-arrange\n\n[labels, si] = sort(labels, 2, 'ascend');\n[nums, labelfound] = slcount(labels);\n[sinds, einds] = slnums2bounds(nums);\n[sfound, smap] = ismember(labelset, labelfound);\n\n%% extract\n\nc = length(labelset);\nInds = cell(1, c);\nfor i = 1 : c\n    if sfound(i)\n        mi = smap(i);\n        curinds = si(sinds(mi):einds(mi));\n        Inds{i} = curinds;\n    else\n        Inds{i} = [];\n    end\nend\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/utils/sllabelinds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.5624168665034538}}
{"text": "function y = qinvjmul(labx,frmx,b,K)\n% y = qinvjmul(labx,frmx,b,K)\n%\n% QINVJMUL  Inverse of Jordan multiply for Lorentz blocks\n%\n% **********  INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi\n\n% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n%   Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n%   CRL, McMaster University, Canada.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\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 Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n\nlorN = length(K.q);\nif lorN == 0\n    y = zeros(0,1);\n    return\nend\nif length(labx) > 2*lorN\n    labx = labx(K.l+1:K.l+2*lorN);\nend\ndetx = labx(1:lorN) .* labx(lorN+1:end);\nx = qframeit(labx,frmx,K);\nix = K.mainblks;\nif length(b) == ix(3)-ix(1);   % lorentz only ?\n    ix = (1-ix(1)) + ix;\nend\n% ------------------------------------------------------------\n% Let y1(k) = xk'Jbk/(sqrt2*detxk)\n% ------------------------------------------------------------\ny1 = x(1:lorN).*b(ix(1):ix(2)-1) - ddot(x(lorN+1:end),b,K.qblkstart);\ny1 = y1./(sqrt(2)*detx);\n% ------------------------------------------------------------\n% Let y2[k] = (sqrt2/x1)*b2[k] - (y1/x1) * x2[k]\n% ------------------------------------------------------------\ny = [y1; qblkmul(sqrt(2)./x(1:lorN),b,K.qblkstart)...\n    - qblkmul(y1./x(1:lorN),x(lorN+1:end),K.qblkstart)];", "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/sedumi/qinvjmul.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5624168613654552}}
{"text": "function [L,S,errHist] = solver_RPCA_constrained(AY,lambda_S, tau, A_cell, opts)\n% [L,S,errHist] = solver_RPCA_constrained(Y,lambda_S, tau, A_cell, opts)\n% Solves the problem\n%   minimize_{L,S} .5|| L + S - Y ||_F^2 \n%   subject to \n%   if opts.sum = true\n%       (1)  ||L||_* + lambda_S ||S||_1 <= tau\n%   if opts.max = true \n%       (2) max(  ||L||_* , lambda_S ||S||_1 ) <= tau\n%\n%   if opts.max and opts.sum are false and tau is a negative number, then\n%   we solve the problem:\n%       minimize_{L,S} .5|| L + S - Y ||_F^2  + abs(tau)*( ||L||_* + lambda_S ||S||_1 )\n%   (but see solver_RPCA_Lagrangian.m for a simpler interface)\n%\n%   or if A_cell is provided, where A_cell = {A, At}\n%   (A is a function handle, At is a function handle to the transpose of A)\n%   then\n%\n%   minimize_{L,S} .5|| A(L + S) - Y ||_F^2 \n%       subject to ...\n%   (here, Y usually represents A(Y); if Y is not the same size\n%    as A(L), then we will automatically set Y <-- A(Y) )\n%\n%   errHist(:,1) is a record of the residual\n%   errHist(:,2) is a record of the full objective (that is, .5*resid^2 )\n%   errHist(:,3) is the output of opts.errFcn if provided\n%\n% opts is a structure with options:\n%   opts.sum, opts.max  (as described above)\n%   opts.L0         initial guess for L (default is 0)\n%   opts.S0         initial guess for S (default is 0)\n%   opts.size       [n1,n2] where L and S are n1 x n2 matrices. The size is automatically\n%       determined in most cases, but when providing a linear operator\n%       it may be necessary to provide an explicit size.\n%   opts.tol        sets stopping tolerance\n%   opts.maxIts     sets maximum number of iterations\n%   opts.printEvery will print information this many iterations\n%   opts.displayTime will print out timing information (default is true for large problems)\n%   opts.errFcn     a function of (L,S) that records information\n%   opts.trueObj    if provided, this will be subtracted from errHist(2,:)\n%   opts.Lip        Lipschitz constant, i.e., 2*spectralNorm(A)^2\n%                       by default, assume 2 (e.g., good if A = P_Omega)\n%   opts.FISTA      whether to use FISTA or not. By default, true\n%     opts.restart  how often to restart FISTA; set to -Inf to make it automatic\n%   opts.BB         whether to use the Barzilai-Borwein spectral steplength\n%     opts.BB_type  which BB stepsize to take. Default is 1, the larger step\n%     opts.BB_split whether to calculate stepslengths for S and L independently.\n%       Default is false, which is recommended.\n%   opts.quasiNewton  uses quasi-Newton-like Gauss-Seidel scheme.\n%                     Only available in \"max\" mode\n%     opts.quasiNewton_stepsize     stepsize length. Default is .8*(2/Lip)\n%     opts.quasinewton_SLS          whether to take S-L-S sequence (default is true)\n%                                   otherwise, takes a L-S Gauss-Seidel sequence\n%   opts.SVDstyle   controls what type of SVD is performed.\n%       1 = full svd using matlab's \"svd\". Best for small problems\n%       2 = partial svd using matlab's \"svds\". Not recommended.\n%       3 = partial svd using PROPACK, if installed. Better than option 2, worse than 4\n%       4 = partial svd using randomized linear algebra, following\n%           the Halko/Tropp/Martinnson \"Structure in Randomness\" paper\n%       in option 4, there are additional options:\n%       opts.SVDwarmstart   whether to \"warm-start\" the algorithm\n%       opts.SVDnPower  number of power iterations (default is 2 unless warm start)\n%       opts.SVDoffset  oversampling, e.g., \"rho\" in Tropp's paper. Default is 5\n%\n%   opts.L1L2      instead of using l1 penalty, e.g., norm(S(:),1), we can\n%       also use block norm penalties, such as (if opts.L1L2 = 'rows')\n%       the sum of the l2-norm of rows (i.e., l1-norm of rows),\n%       or if opts.L1L2='cols', the sum of the l2-norms of colimns.\n%       By default, or if opts.L1L2 = [] or false, then uses usual l1 norm.\n%       [Feature added April 17 2015]\n%\n%  Features that may be added later: [email developers if these are\n%    important to you]\n%       - Allow Huber loss function.\n%\n% Stephen Becker, March 6 2014. Edited March 14 2014, April 2015. \n%   stephen.becker@colorad.edu\n% See also solver_RPCA_Lagrangian.m, solver_RPCA_SPGL1.m\n\n\n% todo: allow S >= 0 constraints, since this is easy\n% todo: allow Huber loss function\n\nerror(nargchk(3,5,nargin,'struct'));\nif nargin < 5, opts = []; end\n% == PROCESS OPTIONS ==\nfunction out = setOpts( field, default )\n    if ~isfield( opts, field )\n        opts.(field)    = default;\n    end\n    out = opts.(field);\n    opts    = rmfield( opts, field ); % so we can do a check later\nend\n\nif nargin < 4 || isempty(A_cell)\n    A   = @(X) X(:);\n    [n1,n2] = size(AY);\n    At  = @(x) reshape(x,n1,n2);\n    \n    if ~iscell(tau)\n        AY  = A(AY);\n    end\n    % The factor of 2 is since we are in both L and S \nelse\n    A   = A_cell{1};\n    At  = A_cell{2};\n    % Y could be either Y or A(Y)\n    if size(AY,2) > 1\n        % AY is a vector, so it is probably Y and not AY\n        disp('Changing Y to A(Y)');\n        AY = A(AY);\n        [n1,n2] = size(AY); % April 24 '14\n    else\n        % April 24, '14: we need to know the (n1,n2)\n        sz      = setOpts('size',[] );\n        if isempty(sz)\n            error('Cannot determine the size of the variables; please specify opts.size=[n1,n2]');\n        end\n        n1 = sz(1);\n        n2 = sz(2);\n    end\n    %[n1,n2] = size(AY); % comment out April 24 '14\nend\nnormAY =    norm(AY(:));\n\nvec = @(X) X(:);\n\n% Some problem sizes. Feel free to tweak. Mainly affect the defaults\nSMALL   = ( n1*n2 <= 50^2 );\nMEDIUM  = ( n1*n2 <= 200^2 ) && ~SMALL;\nLARGE   = ( n1*n2 <= 1000^2 ) && ~SMALL && ~MEDIUM;\nHUGE    = ( n1*n2 > 1000^2 );\n\n\n% -- PROCESS OPTIONS -- (some defaults depend on problem size )\ntol     = setOpts('tol',1e-6*(SMALL | MEDIUM) + 1e-4*LARGE + 1e-3*HUGE );\nmaxIts  = setOpts('maxIts', 1e3*(SMALL | MEDIUM ) + 400*LARGE + 200*HUGE );\nprintEvery  = setOpts('printEvery',100*SMALL + 50*MEDIUM + 5*LARGE + 1*HUGE);\nerrFcn      = setOpts('errFcn', [] );\nLip         = setOpts('Lip', 2 );\nrestart     = setOpts('restart',-Inf);\ntrueObj     = setOpts('trueObj',0);\nsumProject  = setOpts('sum', false );\nmaxProject  = setOpts('max', false );\n\nif tau < 0\n\tLagrangian = true;\n\tif sumProject || maxProject\n\t\terror('in Lagrangian mode (when tau<0 significies lambda=|tau|), turn off sum/maxProject');\n\tend\n\tlambda = abs(tau);\n\ttau = []; % help us track down bugs\nelse\n\tLagrangian = false;\n\tif (sumProject && maxProject) || (~sumProject && ~maxProject), error('must choose either \"sum\" or \"max\" type projection'); end\nend\n\nQUASINEWTON = setOpts('quasiNewton', maxProject || Lagrangian );\nFISTA       = setOpts('FISTA',~QUASINEWTON);\nBB          = setOpts('BB',~QUASINEWTON);\n% Note: BB with FISTA is sometimesm not so good\nif BB && FISTA, warning('solver_RPCA:convergence','Convergence not guaranteed with FISTA if opts.BB=true'); end\nBB_split    = setOpts('BB_split',false);\nBB_type     = setOpts('BB_type',1); % 1 or 2\nstepsizeQN  = setOpts('quasiNewton_stepsize', .8*2/Lip );\nS_L_S       = setOpts('quasiNewton_SLS', true );\ndisplayTime = setOpts('displayTime',LARGE | HUGE );\nSVDstyle    = setOpts('SVDstyle', 1*SMALL + 4*(~SMALL) ); % 1 is full SVD\n% and even finer tuning (only matter if SVDstyle==4)\nSVDwarmstart= setOpts('SVDwarmstart', true );\nSVDnPower   = setOpts('SVDnPower', 1 + ~SVDwarmstart ); % number of power iteratiosn\nSVDoffset   = setOpts('SVDoffset', 5 );\nSVDopts = struct('SVDstyle', SVDstyle,'warmstart',SVDwarmstart,...\n    'nPower',SVDnPower,'offset',SVDoffset );\n\nif QUASINEWTON \n    if sumProject\n        error('Can not run quasi-Newton mode when in \"sum\" formulation. Please change to \"max\"');\n    elseif FISTA\n        error('Can not run quasi-Newton with FISTA');\n    elseif BB\n        error('Can not run quasi-Newton with BB');\n    end\nend\n\n% April 17 2015\nL1L2        = setOpts('L1L2',0);\nif isempty(L1L2), L1L2=0; end\nif L1L2,\n    if ~isempty(strfind(lower(L1L2),'row')),  L1L2 = 'rows';\n    elseif ~isempty(strfind(lower(L1L2),'col')),  L1L2 = 'cols';\n        % so col, COL, cols, columns, etc. all acceptable\n    else\n        error('unrecognized option for L1L2: should be row or column or 0');\n    end\nend\n\nprojNuclear(); % remove any persistent variables\nif maxProject\n    project = @(L,S,varargin) projectMax(L1L2,tau,lambda_S,SVDopts, L,S);\nelseif sumProject\n    if any(L1L2), error('with opts.sum=true, need opts.L1L2=0'); end\n    project = @(L,S,varargin) projectSum(tau,lambda_S,L,S);\nelseif Lagrangian\n    project = @(L,S,varargin) projectMax(L1L2,lambda,lambda*lambda_S,SVDopts, L,S, varargin{:});\nend\n\nL           = setOpts('L0',zeros(n1,n2) );\nS           = setOpts('S0',zeros(n1,n2) );\n\n% Check for extra options that were not processed\nif ~isempty( fieldnames(opts ) )\n    disp( 'warning, found extra guys in opts');\n    disp( opts )\n    error('Found unprocessed options in \"opts\"');\nend\n\nstepsize    = 1/Lip;\nerrHist     = zeros(maxIts, 2 + ~isempty(errFcn) );\nGrad        = 0;\nif FISTA || BB || QUASINEWTON\n    L_old   = L;\n    S_old   = S;\nend\nL_fista     = L;\nS_fista     = S;\nBREAK   = false;\nkk      = 0; % counter for FISTA\ntimeRef = tic;\nfor k = 1:maxIts\n    % Gradient in (L,S) (at the fista point) is (R,R) where...\n    R   = A(L_fista + S_fista) - AY;\n    Grad_old    = Grad;\n    Grad        = At(R);\n    \n    objL        = Inf;\n    if QUASINEWTON\n%         stepsizeQN  = 1 - min(0.1, 1/k );\n%         stepsizeQN = 1 - .3/sqrt(k);\n        \n        if S_L_S\n            % we solve for S, update L, then re-update S\n            % Exploits the fact that projection for S is faster\n            dL      = L - L_old;\n            S_old   = S;\n            [~,S_temp]   = project( [], S - stepsizeQN*( Grad + dL ), stepsizeQN ); % take small step...\n            \n            dS      = S_temp - S_old;\n            L_old   = L;\n            [L,~,rnk,objL]   = project( L - stepsizeQN*( Grad + dS ), [], stepsizeQN );\n            \n            dL      = L - L_old;\n            [~,S]   = project( [], S - stepsizeQN*( Grad + dL ) , stepsizeQN);\n        else\n            % Gauss-Seidel update, starting with L, then S\n            % Changing order seemed to not work as well\n            dS      = S - S_old;\n            L_old   = L;\n            [L,~,rnk,objL]   = project( L - stepsizeQN*( Grad + dS ), [] , stepsizeQN);\n            dL      = L - L_old;\n            S_old   = S;\n            [~,S]   = project( [], S - stepsizeQN*( Grad + dL ) , stepsizeQN);\n        end\n%         stepsizeQN = (1+3*stepsizeQN)/4;\n    else\n        if BB && k > 1\n            [stepsizeL, stepsizeS]  = compute_BB_stepsize( Grad, Grad_old, L, L_old, S, S_old, BB_split, BB_type);\n            if isnan(stepsizeL) || isnan(stepsizeS)\n                fprintf(2,'Warning: no BB stepsize possible since iterates have not changed!\\n');\n                [stepsizeL, stepsizeS]   = deal( stepsize );\n            end\n        else\n            [stepsizeL, stepsizeS]   = deal( stepsize );\n        end\n        \n        % Now compute proximity step\n        if FISTA || BB\n            L_old   = L;\n            S_old   = S;\n        end\n        L           = L_fista - stepsizeL*Grad;\n        S           = S_fista - stepsizeS*Grad;\n        if any(isnan(L(:))) || any(isnan(S(:))), fprintf(2,'DEBUG!\\n'); keyboard; end\n        [L,S,rnk,objL]   = project( L, S, stepsizeL, stepsizeS);\n        if any(isnan(L(:))) || any(isnan(S(:))), fprintf(2,'DEBUG!\\n'); keyboard; end\n    end\n    \n    \n    DO_RESTART = false;\n    if FISTA\n        if k>1 && restart > 0 && ~isinf(restart) && ~mod(kk,restart)\n            kk = 0;\n            DO_RESTART  = true;\n        elseif restart==-Inf && kk > 5\n            % In this case, we restart if the function has significantly increased\n            if (errHist(k-1,2)-errHist(k-5,2)) > 1e-8*abs(errHist(k-5,2))\n                DO_RESTART = true;\n                kk = 0;\n            end\n        end\n        L_fista = L + kk/(kk+3)*( L - L_old );\n        S_fista = S + kk/(kk+3)*( S - S_old );\n        kk      = kk + 1;\n    else\n        L_fista = L;\n        S_fista = S;\n    end\n\n    \n%     res          = norm(R(:)); % this is for L_fista, not L\n    R            = A(L + S) - AY;\n    % sometimes we already have R pre-computed, so if this turns out to \n    %   be a signficant computational cost we can make fancier code...\n    res          = norm(R(:));\n    errHist(k,1) = res;\n    errHist(k,2) = 1/2*(res^2); % + lambda_L*objL + lambda_S*objS;\n    if Lagrangian\n        errHist(k,2) = errHist(k,2) + lambda*objL;\n        if any(L1L2)\n            if strcmpi(L1L2,'rows')\n                errHist(k,2) = errHist(k,2) + lambda*lambda_S*sum( sqrt( sum(S.^2,2) ) );\n            else\n                errHist(k,2) = errHist(k,2) + lambda*lambda_S*sum( sqrt( sum(S.^2,1) ) );\n            end\n        else\n            errHist(k,2) = errHist(k,2) + lambda*lambda_S*norm(S(:),1);\n        end\n    end\n    if k > 1 && abs(diff(errHist(k-1:k,1)))/res < tol\n        BREAK = true;\n    end\n    PRINT   = ~mod(k,printEvery) | BREAK | DO_RESTART;\n    if PRINT\n        fprintf('Iter %4d, rel. residual %.2e, objective %.2e', k, res/normAY, errHist(k,2) -trueObj);\n    end\n    if ~isempty(errFcn)\n        err     = errFcn(L,S);\n        errHist(k,3)    = err;\n        if PRINT, fprintf(', err %.2e', err ); end\n    end\n    if ~isempty(rnk) && PRINT, fprintf(', rank(L) %3d', rnk ); end\n    if PRINT\n        fprintf(', sparsity(S) %5.1f%%', 100*nnz(S)/numel(S) );\n    end\n    if displayTime && PRINT\n        tm = toc( timeRef ); timeRef = tic;\n        fprintf(', time %.1f s', tm );\n    end\n    if DO_RESTART, fprintf(' [restarted FISTA]'); end\n    if PRINT, fprintf('\\n'); end\n    if BREAK\n        fprintf('Reached stopping criteria (based on change in residual)\\n');\n        break;\n    end\nend\nif BREAK\n    errHist = errHist(1:k,:); \nelse\n    fprintf('Reached maximum number of allowed iterations\\n');\nend\n\nend\n\n% subfunctions for projection\nfunction [L,S,rnk,nuclearNorm] = projectMax( L1L2, tau, lambda_S,SVDopts, L, S , stepsize, stepsizeS)\n if nargin >= 7 && ~isempty(stepsize)\n     % we compute proximity, not projection\n     tauL \t= -abs( tau*stepsize );\n     if nargin < 8 || isempty( stepsizeS ), stepsizeS = stepsize; end\n     tauS \t= -abs( lambda_S*stepsizeS );\n else\n     tauL \t= abs(tau);\n     tauS \t= abs(tau/lambda_S );\n end\n \n % We project separately, so very easy\n if ~isempty(L)\n     [L,rnk,nuclearNorm]  = projNuclear(tauL, L,SVDopts);\n     if tauL > 0\n         % we did projection, so this should be feasible\n         nuclearNorm = 0;\n     end\n else\n     rnk = [];\n     nuclearNorm = 0;\n end\n \n if ~isempty(S)\n     if tauS > 0\n         if ~any(L1L2)\n             % use the l1 norm\n             projS  = project_l1(tauS);\n         elseif strcmpi(L1L2,'rows')\n             projS  = project_l1l2(tauS,true);\n         elseif strcmpi(L1L2,'cols')\n             projS  = project_l1l2(tauS,false);\n         else\n             error('bad value for L1L2: should be [], ''rows'' or ''cols'' ');\n         end\n         S  = projS( S );\n     else\n         if ~any(L1L2)\n             % use the l1 norm\n             % simple prox\n             S = sign(S).*max(0, abs(S) - abs(tauS));\n         elseif strcmpi(L1L2,'rows')\n             projS  = prox_l1l2(abs(tauS));\n             S      = projS(S,1);\n         elseif strcmpi(L1L2,'cols')\n             projS  = prox_l1l2(abs(tauS));\n             S      = projS(S',1)';\n         else\n             error('bad value for L1L2: should be [], ''rows'' or ''cols'' ');\n         end\n         \n     end\n end\nend\n\nfunction [X,rEst,nrm] = projNuclear( tau, X, SVDopts )\n % Input must be a matrix, not a vector\n % Computes either the proximity operator of the nuclear norm (if tau<0)\n % or projection onto the nuclear norm ball of radius tau (if tau>0)\n \n persistent oldRank Vold iteration\n if nargin==0, oldRank=[]; Vold = []; iteration = 0; return; end\n if isempty(oldRank), rEst = 10;\n else, rEst = oldRank + 2;\n end\n if isempty(iteration), iteration = 0; end\n iteration   = iteration + 1;\n [n1,n2]     = size(X);\n minN       = min( [n1,n2] ); % could set smaller to make nonconvex\n % For the first few iterations, we constrain rankMax\n switch iteration\n     case 1\n         rankMax     = round(minN/4);\n     case 2\n         rankMax     = round(minN/2);\n     otherwise\n         rankMax     = minN;\n end\n \n style = SVDopts.SVDstyle;\n if tau==0, X=0*X; return; end\n \n switch style\n     case 1\n         % full SVD\n         [U,S,V] = svd(X,'econ');\n         s   = diag(S);\n         if tau < 0 % we do prox\n             s = max( 0, s - abs(tau) );\n         else\n             s = project_simplex( tau, s );\n         end\n         tt      = s > 0;\n         rEst    = nnz(tt);\n         U       = U(:,tt);\n         S       = diag(s(tt));\n         V       = V(:,tt);\n         nrm     = sum(s(tt));\n     case {2,3,4}\n         % 2: use Matlab's sparse SVD\n         % 3: use PROPACK\n         % 4: use Joel Tropp's randomized SVD\n         if style==2\n             opts = struct('tol',1e-4);\n             if rankMax==1, opts.tol = min(opts.tol,1e-6); end % important!\n             svdFcn = @(X,rEst)svds(X,rEst,'L',opts);\n         elseif style==3\n             opts = struct('tol',1e-4,'eta',eps);\n             opts.delta = 10*opts.eta;\n             % set eta to eps, but not 0 otherwise reorth is very slow\n             if rankMax==1, opts.tol = min(opts.tol,1e-6); end % important!\n             svdFcn = @(X,rEst)lansvd(X,rEst,'L',opts);\n         elseif style == 4\n             opts = [];\n             if isfield(SVDopts,'nPower') && ~isempty( SVDopts.nPower )\n                 nPower = SVDopts.nPower;\n             else\n                 nPower = 2;\n             end\n             if isfield(SVDopts,'offset') && ~isempty( SVDopts.offset )\n                 offset = SVDopts.offset;\n             else\n                 offset = 5;\n             end\n             if isfield( SVDopts, 'warmstart' ) && SVDopts.warmstart==true ...\n                     && ~isempty(Vold)\n                 opts = struct( 'warmStart', Vold );\n             end\n             ell     = @(r) min([r+offset,n1,n2]); % number of samples to take\n             svdFcn = @(X,rEst)randomizedSVD(X,rEst,ell(rEst),nPower,[],opts );\n         end\n         \n         ok  = false;\n         while ~ok\n             rEst    = min( [rEst,rankMax] );\n             [U,S,V] = svdFcn(X,rEst);\n             s       = diag(S);\n             if tau < 0\n                 % we are doing prox\n                 lambda = abs(tau);\n             else\n                 lambda  = findTau(s,tau);\n             end\n             ok      = ( min(s) < lambda ) || (rEst == rankMax);\n             if ok, break; end\n             rEst    = 2*rEst;\n         end\n         rEst = min( length(find(s>lambda)), rankMax );\n         S   = diag( s(1:rEst) - lambda );\n         U   = U(:,1:rEst);\n         V   = V(:,1:rEst);\n         nrm = sum( s(1:rEst) - lambda );\n     otherwise\n         error('bad value for SVDstyle');\n end\n if isempty(U)\n     X = 0*X;\n else\n     X = U*S*V';\n end\n oldRank = size(U,2);\n if isfield( SVDopts, 'warmstart' ) && SVDopts.warmstart==true\n     Vold = V;\n end\nend\n\nfunction x = project_simplex( q, x )\n % projects onto the constraints sum(x)=q and x >= 0\n % Update: projects onto sum(x) <= q and x >= 0\n\n x     = x.*( x > 0 ); % March 11 '14\n % March 11, fixing bug: we want to project onto the volume, not\n %   the actual simplex (surface)\n if sum(x) <= q, return; end\n if q==0, x = 0*x; return; end\n \n s     = sort( x, 'descend' );\n if q < eps(s(1))\n     % eps(x) is the distance from abs(x) to the next larger\n     %   floating point number, i.e., in floating point arithmetic,\n     %   x + eps(x)/2 = x\n     % eps(1) is about 2.2e-16\n     \n     error('Input is scaled so large compared to q that accurate computations are difficult');\n     % since then cs(1) = s(1) - q is  not even guaranteed to be\n     % smaller than q !\n end\n cs    = ( cumsum(s) - q ) ./ ( 1 : numel(s) )';\n ndx   = nnz( s > cs );\n x     = max( x - cs(ndx), 0 );\nend\n\nfunction tau = findTau( s, lambda )\n % Returns the shrinkage value necessary to shrink the vector s\n %   so that it is in the lambda scaled simplex\n %   Usually, s is the diagonal part of an SVD\n if all(s==0)||lambda==0, tau=0; return; end\n if numel(s)>length(s), error('s should be a vector, not a matrix'); end\n if ~issorted(flipud(s)), s = sort(s, 'descend'); end\n if any( s < 0 ), error('s should be non-negative'); end\n \n % project onto the simplex of radius lambda (not tau)\n % and use this to find \"tau\" (the shrinkage amount)\n % If we know s_i > tau for i = 1, ..., k, then\n %   tau = ( sum(s(1:k)) - lambda )/k\n % But we don't know k, so find it:\n cs  = (cumsum(s) - abs(lambda) )./(1:length(s))';\n ndx = nnz( s > cs ); % >= 1 as long as lambda > 0\n tau = max(0,cs(ndx));\n % We want to make sure we project onto sum(sigma) <= lambda\n %   and not sum(sigma) == lambda, so do not allow negative tau\n \nend\n\n\nfunction [L,S,rnk,nuclearNorm] = projectSum( tau, lambda_S, L, S )\n  [m,n]           = size(L);\n  [U,Sigma,V]     = svd(L,'econ');\n  s       = diag(Sigma);\n  wts     = [ ones(length(s),1); lambda_S*ones(m*n,1) ];\n  proj    = project_l1(tau,wts);\n  sS      = proj( [s;vec(S)] );\n  sProj   = sS(1:length(s));\n  S       = reshape( sS(length(s)+1:end), m, n );\n  L       = U*diag(sProj)*V';\n  rnk     = nnz( sProj );\n  nuclearNorm = sum(sProj);\nend\n\n\nfunction [stepsizeL, stepsizeS]  = compute_BB_stepsize( ...\n    Grad, Grad_old, L, L_old, S, S_old, BB_split, BB_type)\n\n  if ~BB_split\n      % we take a Barzilai-Borwein stepsize in the full variable\n      yk  = Grad(:) - Grad_old(:);\n      yk  = [yk;yk]; % to account for both variables\n      sk  = [L(:) - L_old(:); S(:) - S_old(:) ];\n      if BB_type == 1\n          % Default. The bigger stepsize\n          stepsize    = norm(sk)^2/(sk'*yk);\n      elseif BB_type == 2\n          stepsize    = sk'*yk/(norm(yk)^2);\n      end\n      [stepsizeL, stepsizeS] = deal( stepsize );\n      \n  elseif BB_split\n      % treat L and S variables separately\n      % Doesn't seem to work well.\n      yk  = Grad(:) - Grad_old(:);\n      skL  = L(:) - L_old(:);\n      skS  = S(:) - S_old(:);\n      if BB_type == 1\n          % Default. The bigger stepsize\n          stepsizeL   = norm(skL)^2/(skL'*yk);\n          stepsizeS   = norm(skS)^2/(skS'*yk);\n      elseif BB_type == 2\n          stepsizeL   = skL'*yk/(norm(yk)^2);\n          stepsizeS   = skS'*yk/(norm(yk)^2);\n      end\n  end\nend\n\n\nfunction op = project_l1( q , d)\n%PROJECT_L1   Projection onto the scaled 1-norm ball.\n%    OP = PROJECT_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 = PROJECT_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% Note: theoretically, this can be done in O(n)\n%   but in practice, worst-case O(n) median sorts are slow\n%   and instead average-case O(n) median sorts are used.\n%   But in matlab, the median is no faster than sort\n%   (the sort is probably quicksort, O(n log n) expected, with\n%    good constants, but O(n^2) worst-case).\n%   So, we use the naive implementation with the sort, since\n%   that is, in practice, the fastest.\n\n if nargin == 0,\n     q = 1;\n elseif ~isnumeric( q ) || ~isreal( q ) || numel( q ) ~= 1 || q <= 0,\n     error( 'Argument must be positive.' );\n end\n if 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{:} );\n else\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{:} );\n end\n \n % This is modified from TFOCS, Nov 26 2013, Stephen Becker\n % Note: removing \"v\" (value) output from TFOCS code\n %   Also removing extraneous inputs\n    function x = proj_l1_q( q, x, varargin )\n        myReshape   = @(x) x; % do nothing\n        if size(x,2) > 1\n            if ndims(x) > 2, error('You must modify this code to deal with tensors'); end\n            myReshape     = @(y) reshape( y, size(x,1), size(x,2) );\n            x   = x(:); % make it into a vector\n        end\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\n        x   = myReshape(x);\n    end\n\n% Allows scaling. Added Feb 21 2014\n    function x = proj_l1_q_d( q, d,  x, varargin )\n        myReshape   = @(x) x; % do nothing\n        if size(x,2) > 1\n            if ndims(x) > 2, error('You must modify this code to deal with tensors'); end\n            myReshape     = @(y) reshape( y, size(x,1), size(x,2) );\n            x   = x(:); % make it into a vector\n        end\n        [goodInd,j,xOverD] = find( x./ d );\n        [lambdas,srt]      = sort(abs(xOverD),'descend');\n        s   = abs(x(goodInd).*d(goodInd));\n        s   = s(srt);\n        dd  = d(goodInd).^2;\n        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\n        x   = myReshape(x);\n    end\n\n\nend\n\n\n\n% Copied from TFOCS, April 17 2015\nfunction op = project_l1l2( q, rowNorms )\n%PROJ_L1L2    L1-L2 block norm: sum of L2 norms of rows.\n%    OP = PROJ_L1L2( q ) implements the constraint set\n%        {X | sum_{i=1:m} norm(X(i,:),2) <= 1 }\n%    where X is a m x n matrix.  If n = 1, this is equivalent\n%    to PROJ_L1. If m=1, this is equivalent to PROJ_L2\n%\n%    Q is optional; if omitted, Q=1 is assumed. But if Q is supplied,\n%    then it must be positive and real and a scalar.\n%\n%   OP = PROJ_L1L2( q, rowNorms )\n%     will either do the sum of the l2-norms of rows if rowNorms=true\n%       (the default), or the sum of the l2-norms of columns if\n%       rowNorms = false.\n%\n%   Known issues: doesn't yet work with complex-valued data.\n%       Should be easy to fix, so email developers if this is\n%       needed for your problem.\n%\n% Dual: prox_linfl2.m [not yet available]\n% See also prox_l1l2.m, proj_l1.m, proj_l2.m\n\n    if nargin == 0 || isempty(q),\n        q = 1;\n    elseif ~isnumeric( q ) || ~isreal( q ) || any(q <= 0) ||numel(q)>1,\n        error( 'Argument must be positive and a scalar.' );\n    end\n    \n    if nargin<2 || isempty(rowNorms)\n        rowNorms = true;\n    end\n    \n    if rowNorms\n        op = @(x,varargin)prox_f_rows(q,x);\n    else\n        op = @(x,varargin)prox_f_cols(q,x);\n    end\n\n    function X = prox_f_rows(tau,X) \n        nrms    = sqrt( sum( X.^2, 2 ) );\n        % When we include a row of x, corresponding to row y of Y,\n        % its contribution is norm(y)-lambda\n        % So we have sum_{i=1}^m max(0, norm(y_0)-lambda)\n        % So, basically project nrms onto the l1 ball...\n        s      = sort( nrms, 'descend' );\n        cs     = cumsum(s);\n        \n        ndx    = find( cs - (1:numel(s))' .* [ s(2:end) ; 0 ] >= tau+2*eps(tau), 1 ); % For stability\n        \n        if ~isempty( ndx )\n            thresh = ( cs(ndx) - tau ) / ndx;\n            % Apply to relevant rows\n            d   = max( 0, 1-thresh./nrms );\n            m   = size(X,1);\n            X   = spdiags( d, 0, m, m )*X;\n        end\n    end\n\n    function X = prox_f_cols(tau,X) \n        nrms    = sqrt( sum( X.^2, 1 ) ).';\n        s      = sort( nrms, 'descend' );\n        cs     = cumsum(s);\n        \n        ndx    = find( cs - (1:numel(s))' .* [ s(2:end) ; 0 ] >= tau+2*eps(tau), 1 ); % For stability\n        \n        if ~isempty( ndx )\n            thresh = ( cs(ndx) - tau ) / ndx;\n            d   = max( 0, 1-thresh./nrms );\n            n   = size(X,2);\n            X   = X*spdiags( d, 0, n,n );\n        end\n    end\n\nend % end projection_l1l2.m\n\n\n\n% Copied from TRFOCS April 17 2015\nfunction op = prox_l1l2( q )\n%PROX_L1L2    L1-L2 block norm: sum of L2 norms of rows.\n%    OP = PROX_L1L2( q ) implements the nonsmooth function\n%        OP(X) = q * sum_{i=1:m} norm(X(i,:),2)\n%    where X is a m x n matrix.  If n = 1, this is equivalent\n%    to PROX_L1\n%    Q is optional; if omitted, Q=1 is assumed. But if Q is supplied,\n%    then it must be positive and real.\n%    If Q is a vector, it must be m x 1, and in this case,\n%    the weighted norm OP(X) = sum_{i} Q(i)*norm(X(i,:),2)\n%    is calculated.\n%\n% Dual: proj_linfl2.m\n% See also proj_linfl2.m, proj_l1l2.m\n\n    if nargin == 0,\n        q = 1;\n    elseif ~isnumeric( q ) || ~isreal( q ) || any(q <= 0),\n        error( 'Argument must be positive.' );\n    end\n    op = @(x,t)prox_f(q,x,t);\n    \n    function x = prox_f(q,x,t)\n        if nargin < 3,\n            error( 'Not enough arguments.' );\n        end\n        v = sqrt( sum(x.^2,2) );\n        s = 1 - 1 ./ max( v ./ ( t .* q ), 1 );\n        m = length(s);\n        x = spdiags(s,0,m,m)*x;\n    end\n\nend\n", "meta": {"author": "stephenbeckr", "repo": "fastRPCA", "sha": "44dfee56f142ebffe5a7003578868e84bd4330b7", "save_path": "github-repos/MATLAB/stephenbeckr-fastRPCA", "path": "github-repos/MATLAB/stephenbeckr-fastRPCA/fastRPCA-44dfee56f142ebffe5a7003578868e84bd4330b7/solvers/solver_RPCA_constrained.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126792, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5624053891797706}}
{"text": "function cvx_optpnt = exponential( sx )\n\n%EXPONENTIAL   Exponential cone.\n%   EXPONENTIAL, called with no arguments, creates three scalar variables X,\n%   Y, and Z and constraints them to lie in an exponetial cone. That is,\n%   given the declaration\n%       variables x y z\n%       {x,y,z} == exp_cone\n%   constraints the variables to satisfy\n%       y*exp(x/y) <= z\n%       y > 0\n%   The inequality form does not obey the disciplined convex programming\n%   ruleset, but a function EXP_P has been created to represent this\n%   computation; so the set declaration above is equivalent to\n%       EXP_P(X,Y) <= Z\n%   EXP_CONE(SX), where SX is a size vector, creates three array variables\n%   X, Y, and Z, each of size SX, which are constrained elementwise to\n%   satisfy EXP_P(X,Y) <= Z. If SX is empty, then SX=[1,1] is assumed.\n\ncvx_expert_check( 'exponential' );\nnarginchk(0,1);\n\n%\n% Check size vector\n%\n\nif nargin == 0 || isempty( sx ),\n    sx = [1,1]; %#ok\nelse\n    [ temp, sx ] = cvx_check_dimlist( sx, true ); %#ok\n    if ~temp,\n        error( 'First argument must be a dimension vector.' );\n    end\nend\n\n\n%\n% Build the cone\n%\n\ncvx_begin set\n    variables x( sx ) y( sx ) z( sx )\n    [ tx, dummy ] = find( cvx_basis( x ) ); %#ok\n    [ ty, dummy ] = find( cvx_basis( y ) ); %#ok\n    [ tz, dummy ] = find( cvx_basis( z ) ); %#ok\n    newnonl( cvx_problem, 'exponential', [ tx(:)' ; ty(:)' ; tz(:)' ] );\n    cvx___.canslack( tx ) = false;\n    cvx___.canslack( ty ) = false;\ncvx_end\n\ncvx_optpnt = cvxtuple( struct( 'x', x, 'y', y, 'z', z ) );\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/exponential.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5624053861610051}}
{"text": "% Make the following HHMM\n%\n%     LH                  RH\n%    /                      \\\n%   /                        \\\n%  LR -> UD -> RL -> DU       RL -> UD -> LR -> DU\n%   \\\n%    \\\n%     Q1 -> Q2\n%\n% where level 1 is fully interconnected (not shown)\n% level 2 is left-right\n% and each model at level 3 is a 2 state LR shared HMM \n\nQsizes = [2 4 2];\nD = 3;\n\n% LEVEL 1\n\nstartprob1 = 'ergodic';\ntransprob1 = 'ergodic';\n\n\n% LEVEL 2\n\nstartprob = zeros(2, 4);\n%        Q1  Q2\nstartprob(1, 1) = 1;\nstartprob(2, 3) = 1;\n\ntransprob = zeros(2, 4, 4);\ntransprob(1,:,:) = [0 1 0 0\n\t\t    0 0 1 0\n\t\t    0 0 0 1\n\t\t    0 0 0 1];\ntransprob(2,:,:) = [0 0 0 1\n\t\t    1 0 0 0\n\t\t    0 1 0 0\n\t\t    0 0 0 1];\n\nQ2args = {'startprob', startprob, 'transprob', transprob};\n\n% always terminate in state 4 (default)\n% F2args\n\n% LEVEL 3\n\n% Defaults are fine: always start in state 1, left-right model, finish in state 2\n\n\n% OBS LEVEl\n\nchars = ['L', 'l', 'U', 'u', 'R', 'r', 'D', 'd'];\nOsize = length(chars);\n\nobsprob = zeros([4 2 Osize]);\n%       Q2 Q3 O\nobsprob(1, 1, find(chars == 'L')) =  1.0;\nobsprob(1, 2, find(chars == 'l')) =  1.0;\n\nobsprob(2, 1, find(chars == 'U')) =  1.0;\nobsprob(2, 2, find(chars == 'u')) =  1.0;\n\nobsprob(3, 1, find(chars == 'R')) =  1.0;\nobsprob(3, 2, find(chars == 'r')) =  1.0;\n\nobsprob(4, 1, find(chars == 'D')) =  1.0;\nobsprob(4, 2, find(chars == 'd')) =  1.0;\n\nOargs = {'CPT', obsprob};\n\n\nbnet = mk_hhmm3('Qsizes', Qsizes, 'Osize', Osize', 'discrete_obs', 1, 'Oargs', Oargs, 'Q1args', Q1args, 'Q2args', Q2args);\n\nT = 20;\nusecell = 0;\nevidence = sample_dbn(bnet, T, usecell);      \n%chars(evidence(end,:))\n\nQ1 = 1; Q2 = 2; Q3 = 3; F3 = 4; F2 = 5; obs = 6;\nQnodes = [Q1 Q2 Q3]; Fnodes = [F2 F3];\n\npretty_print_hhmm_parse(evidence, Qnodes, Fnodes, obs, chars);\n\neclass = bnet.equiv_class;\nS=struct(bnet.CPD{eclass(Q2,2)})\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/dynamic/HHMM/Old/mk_arrow_alpha_hhmm3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5624053853872707}}
{"text": "function st_io_test03 ( )\n\n%*****************************************************************************80\n%\n%% ST_IO_TEST03 tests ST_SORT_A.\n%\n%  Discussion:\n%\n%    The matrix is:\n%\n%      11  12   0   0  15\n%      21  22   0   0   0\n%       0   0  33   0  35\n%       0   0   0  44   0\n%      51   0  53   0  55\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    23 July 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 5;\n  n = 5;\n  nst = 11;\n  ast = [ 51.0, 12.0, 11.0, 33.0, 15.0, 53.0, 55.0, 22.0, 35.0, 44.0, 21.0 ]';\n  ist = [ 5, 1, 1, 3, 1, 5, 5, 2, 3, 4, 2 ];\n  jst = [ 1, 2, 1, 3, 5, 3, 5, 2, 5, 4, 1 ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'ST_IO_TEST03\\n' );\n  fprintf ( 1, '  ST_SORT_A sorts an ST matrix by columns.\\n' );\n\n  i_min = min ( ist );\n  i_max = max ( ist );\n  j_min = min ( jst );\n  j_max = max ( jst );\n\n  st_header_print ( i_min, i_max, j_min, j_max, m, n, nst );\n\n  st_print ( m, n, nst, ist, jst, ast, '  Matrix data before sorting:' );\n\n  [ ist, jst, ast ] = st_sort_a ( m, n, nst, ist, jst, ast );\n\n  st_print ( m, n, nst, ist, jst, ast, '  Matrix data after sorting:' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/st_io/st_io_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.5624053808972082}}
{"text": "function r8_cscd_test ( )\n\n%*****************************************************************************80\n%\n%% R8_CSCD_TEST tests R8_CSCD.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    12 January 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8_CSCD_TEST\\n' );\n  fprintf ( 1, '  R8_CSCD computes the cosecant of an angle\\n' );\n  fprintf ( 1, '  given in degrees.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  ANGLE    R8_CSCD(ANGLE)\\n' );\n  fprintf ( 1, '\\n' );\n \n  for i = 0 : 15 : 360\n    angle = i;\n    if ( mod ( i, 180 ) == 0 )\n      fprintf ( 1, '  %8.2f    Undefined\\n', angle );\n    else\n      fprintf ( 1, '  %8.2f  %14.6g\\n', angle, r8_cscd ( 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/r8lib/r8_cscd_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.5624053779165276}}
{"text": "function Pe = bit_channel_upgrading_procedure(W, z, miu)\nN = length(z);\nif N == 1\n    Pe = 0.5 * sum(min(W));\n    disp(['Bit index = ' num2str(z) '  ML detection Bit Error rate = ' num2str(Pe)])\nelse\n    W_up = get_W_up(W);\n    W_up = LR_sort(W_up);\n    W_up_after_erasure_symbol_merge = erasure_symbol_merge(W_up);\n    W_up_after_merge = upgrading_merge(W_up_after_erasure_symbol_merge, miu);\n    Pe1 = bit_channel_upgrading_procedure(W_up_after_merge, z(1 : N/2), miu);\n\n    W_down= get_W_down(W);\n    W_down = LR_sort(W_down);\n    W_down_after_erasure_symbol_merge = erasure_symbol_merge(W_down);\n    W_down_after_merge = upgrading_merge(W_down_after_erasure_symbol_merge, miu);\n    Pe2 = bit_channel_upgrading_procedure(W_down_after_merge, z(N/2 + 1 : end), miu);\n\n    Pe = [Pe1 Pe2];\nend\nend\n\n% function Pe = bit_channel_upgrading_procedure(W, z, miu)\n% N = length(z);\n% m = round(log2(N));\n% Pe = zeros(N, 1);\n% for k = N - 7 : N - 1\n%     char_bin_expansion = dec2bin(k, m);\n%     W_tmp = W;\n%     for i_level = 1 : m\n%         if char_bin_expansion(i_level) == '0'\n%             W_up = get_W_up(W_tmp);\n%             W_up = LR_sort(W_up);\n%             W_up_after_erasure_symbol_merge = erasure_symbol_merge(W_up);\n%             W_tmp = upgrading_merge(W_up_after_erasure_symbol_merge, miu);\n%         else\n%             W_down = get_W_down(W_tmp);\n%             W_down = LR_sort(W_down);\n%             W_down_after_erasure_symbol_merge = erasure_symbol_merge(W_down);\n%             W_tmp = upgrading_merge(W_down_after_erasure_symbol_merge, miu);\n%         end\n%     end\n%     Pe(k + 1) = 0.5 * sum(min(W_tmp));\n%     disp(['Bit index = ' num2str(k + 1) ' ML detection Bit Error rate = ' num2str(Pe(k + 1))])\n% end\n% end\n\n\n\n\n", "meta": {"author": "YuYongRun", "repo": "PolarCodeDecodersInMatlab", "sha": "f1b512d10bf057e83f18685ea012d242bdaaf6ac", "save_path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab", "path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab/PolarCodeDecodersInMatlab-f1b512d10bf057e83f18685ea012d242bdaaf6ac/PolarFastSCL/HowToConstructPolarCode/UpgradingConstruction/bit_channel_upgrading_procedure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5624053756334111}}
{"text": "function [l] = qt2l(qt)\n% Convert volume from US liquid quarts to liters. \n% Chad Greene 2012\nl = qt*0.946352946;", "meta": {"author": "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/qt2l.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5624053756334111}}
{"text": "classdef TP10 < PROBLEM\n% <multi> <real> <large/none> <constrained> <robust>\n% Test problem for robust multi-objective optimization\n% delta --- 0.05 --- Maximum disturbance degree\n% H     ---   50 --- Number of disturbances\n\n%------------------------------- Reference --------------------------------\n% A. Gaspar-Cunha, J. Ferreira, and G. Recio, Evolutionary robustness\n% analysis for multi-objective optimization: benchmark problems, Structural\n% and Multidisciplinary Optimization, 2014, 49: 771-793.\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        delta;      % Maximum disturbance degree\n        H;          % Number of disturbances\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            [obj.delta,obj.H] = obj.ParameterSet(0.05,50);\n            obj.M = 2;\n            obj.D = 3;\n            obj.lower    = [0,0,1];\n            obj.upper    = [10,10,3];\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(~,PopDec)\n            PopObj(:,1) = PopDec(:,1).*sqrt(16+PopDec(:,3).^2) + PopDec(:,2).*sqrt(1+PopDec(:,3).^2);\n            PopObj(:,2) = 20*sqrt(16+PopDec(:,3).^2)./PopDec(:,1)./PopDec(:,3);\n        end\n        %% Calculate constraint violations\n        function PopCon = CalCon(obj,PopDec)\n            PopCon(:,1) = 20*sqrt(16+PopDec(:,3).^2) - 100*PopDec(:,1).*PopDec(:,3);\n            PopCon(:,2) = 80*sqrt(1+PopDec(:,3).^2) - 100*PopDec(:,2).*PopDec(:,3);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R = [100,100];\n        end\n        %% Calculate the metric value\n        function score = CalMetric(obj,metName,Population)\n            switch metName\n                case {'Mean_IGD','Mean_HV','Worst_IGD','Worst_HV'}\n                    score = feval(metName,Population,obj);\n                otherwise\n                    score = feval(metName,Population,obj.optimum);\n            end\n        end\n        %% Perturb solutions multiple times\n        function PopX = Perturb(obj,PopDec,N)\n            if nargin < 3; N = obj.H; end\n            Delta = repmat(obj.delta.*(obj.upper-obj.lower),N*size(PopDec,1),1);\n            w     = UniformPoint(N,obj.D,'Latin');\n            Dec   = 2*Delta.*w(reshape(repmat(1:end,size(PopDec,1),1),1,[]),:) + repmat(PopDec,N,1) - Delta;\n            Dec   = obj.CalDec(Dec);\n            PopX  = SOLUTION(Dec,obj.CalObj(Dec),obj.CalCon(Dec));\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/TP/TP10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5624053695958802}}
{"text": "function [gal] = ft32gal(ft3)\n% Convert volume from cubic feet to US liquid gallons. \n% Chad Greene 2012\ngal = ft3*7.4805194805;", "meta": {"author": "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/ft32gal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5623811122301873}}
{"text": "% EX_STOKES_BIFURCATION_RT_MP: data file for Stokes problem in a pipe with a bifurcation.\n\n% 1) PHYSICAL DATA OF THE PROBLEM\nproblem_data  = struct ();\n\n% Physical domain, defined as NURBS map given in a text file\nproblem_data.geo_name = 'geo_bifurcation_mp.txt';\n\n% Type of boundary conditions for each side of the domain\nproblem_data.drchlt_sides = 1:3;\nproblem_data.nmnn_sides = [];\n\n% Physical parameters\nproblem_data.viscosity = @(x, y) ones (size (x));\n\n% Force term\nproblem_data.f  = @(x, y) zeros ([2, size(x)]);\n\n% Boundary terms\nproblem_data.h  = @test_stokes_bifurcation_mp_h_drchlt;\n\n% 2) CHOICE OF THE DISCRETIZATION PARAMETERS\nmethod_data = struct ();\n\nmethod_data.element_name = 'rt';     % Element type for discretization\n\nmethod_data.degree       = [3 3];  % Degree of the splines\nmethod_data.regularity   = [2 2];  % Regularity of the splines\nmethod_data.nsub         = [5 5];  % Number of subdivisions\nmethod_data.nquad        = [5 5];  % Points for the Gaussian quadrature rule\nmethod_data.Cpen = 10 * (method_data.degree(1)+1);\n\n% 3) CALL TO THE SOLVER\n[geometry, msh, space_v, vel, space_p, press] = mp_solve_stokes_div_conforming (problem_data, method_data);\n\n\n% 4) POST-PROCESSING\n% 4.1) EXPORT TO PARAVIEW\noutput_file  = 'bifurcation_2d_rt_mp_deg3_reg2_sub5';\nvtk_pts = {linspace(0, 1, 20), linspace(0, 1, 20)};\n\nfprintf ('results being saved in: %s_vel.pvd and %s_press.pvd\\n', output_file, output_file)\nsp_to_vtk (vel, space_v, geometry, vtk_pts, sprintf ('%s_vel', output_file), {'velocity', 'divergence'}, {'value', 'divergence'})\nsp_to_vtk (press, space_p, geometry, vtk_pts, sprintf ('%s_press', output_file), 'pressure')\n\n%!test\n%! problem_data  = struct ();\n%! problem_data.geo_name = 'geo_bifurcation_mp.txt';\n%! problem_data.drchlt_sides = 1:3;\n%! problem_data.nmnn_sides = [];\n%! problem_data.viscosity = @(x, y) ones (size (x));\n%! problem_data.f  = @(x, y) zeros ([2, size(x)]);\n%! problem_data.h  = @test_stokes_bifurcation_mp_h_drchlt;\n%! method_data = struct ();\n%! method_data.element_name = 'rt';     % Element type for discretization\n%! method_data.degree       = [3 3];  % Degree of the splines\n%! method_data.regularity   = [2 2];  % Regularity of the splines\n%! method_data.nsub         = [5 5];  % Number of subdivisions\n%! method_data.nquad        = [5 5];  % Points for the Gaussian quadrature rule\n%! method_data.Cpen = 10 * (method_data.degree(1)+1);\n%! [geometry, msh, space_v, vel, space_p, press] = mp_solve_stokes_div_conforming (problem_data, method_data);\n%! assert (msh.nel, 100)\n%! assert (space_v.ndof, 552)\n%! assert (space_p.ndof, 256)\n%! for iptc = 1:4\n%!   div = sp_eval (vel(space_v.gnum{iptc}) .* space_v.dofs_ornt{iptc}', space_v.sp_patch{iptc}, geometry(iptc), [20 20], 'divergence');\n%!   assert (max (abs (div(:))) < 1e-12)\n%! end\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/fluid/ex_stokes_bifurcation_2d_rt_mp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5623811108923181}}
{"text": "function [qx,qP,qD,xhist] = spm_pf(M,y,U)\n% Particle Filtering for dynamic models\n% FORMAT [qx,qP,qD,xhist] = spm_pf(M,y)\n% M - model specification structure\n% y - output or data (N x T)\n% U - exogenous input\n%\n% M(1).x                            % initial states\n% M(1).f  = inline(f,'x','v','P')   % state equation\n% M(1).g  = inline(g,'x','v','P')   % observer equation\n% M(1).pE                           % parameters\n% M(1).V                            % observation noise precision\n%\n% M(2).v                            % initial process noise\n% M(2).V                            % process noise precision\n%\n% qx - conditional expectation of states\n% qP - {1 x T} conditional covariance of states\n% qD - full sample\n%__________________________________________________________________________\n% See notes at the end of this script for details and a demo.  This routine\n% is based on:\n%\n% var der Merwe R, Doucet A, de Freitas N and Wan E (2000). The\n% unscented particle filter.  Technical Report CUED/F-INFENG/TR 380\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_pf.m 1143 2008-02-07 19:33:33Z spm $\n\n\n% check model specification\n%--------------------------------------------------------------------------\nM  = spm_DEM_M_set(M);\ndt = M(1).E.dt;\nif length(M) ~=2\n    errordlg('spm_pf requires a two-level model')\n    return\nend\n\n% INITIALISATION:\n%==========================================================================\nT    = length(y);                          % number of time points\nn    = M(2).l;                             % number of innovations\nN    = 200;                                % number of particles.\n    \n% precision of measurement noise\n%--------------------------------------------------------------------------\nR    = M(1).V;\nfor i = 1:length(M(1).Q)\n    R = R + M(1).Q{i}*exp(M(1).h(i));\nend\nP  = M(1).pE;                              % parameters\nQ  = M(2).V.^-.5;                          % root covariance of innovations\nv  = kron(ones(1,N),M(2).v);               % innovations\nx  = kron(ones(1,N),M(1).x);               % hidden states\nv  = v + 128*Q*randn(size(v));\n\n% inputs\n%--------------------------------------------------------------------------\nif nargin < 3\n    U = sparse(n,T);\nend\n\nfor t = 1:T\n\n    % PREDICTION STEP: with the (8x) transition prior as proposal\n    %----------------------------------------------------------------------\n    for i = 1:N\n        v(:,i)     = 8*Q*randn(n,1) + U(:,t);\n        f          = M(1).f(x(:,i),v(:,i),P);\n        dfdx       = spm_diff(M(1).f,x(:,i),v(:,i),P,1);\n        xPred(:,i) = x(:,i) + spm_dx(dfdx,f,dt);\n    end\n\n    % EVALUATE IMPORTANCE WEIGHTS: and normalise\n    %----------------------------------------------------------------------\n    for i = 1:N\n        yPred  = M(1).g(xPred(:,i),v(:,i),P);\n        ePred  = yPred - y(:,t);\n        w(i)   = ePred'*R*ePred;\n    end\n    w   = w - min(w);\n    w   = exp(-w/2);\n    w   = w/sum(w);\n\n    % SELECTION STEP: multinomial resampling.\n    %----------------------------------------------------------------------    \n    x   = xPred(:,multinomial(1:N,w));\n\n    % report and record moments\n    %----------------------------------------------------------------------\n    qx(:,t)  = mean(x,2);\n    qP{t}    = cov(x');\n    qX(:,t)  = x(:);\n    fprintf('PF: time-step = %i : %i\\n',t,T);\nend\n\n% sample density\n%==========================================================================\nif nargout > 3\n    xhist = linspace(min(qX(:)),max(qX(:)),32);\n    for i = 1:T\n        q = hist(qX(:,i),xhist);\n        qD(:,i) = q(:);\n    end\nend\n\nreturn\n\nfunction I = multinomial(inIndex,q);\n%==========================================================================\n% PURPOSE : Performs the resampling stage of the SIR\n%           in order(number of samples) steps.\n% INPUTS  : - inIndex = Input particle indices.\n%           - q       = Normalised importance ratios.\n% OUTPUTS : - I = Resampled indices.\n% AUTHORS : Arnaud Doucet and Nando de Freitas\n\n% MULTINOMIAL SAMPLING:\n% generate S ordered random variables uniformly distributed in [0,1]\n% high speed Niclas Bergman Procedure\n%--------------------------------------------------------------------------\nq        = q(:);\nS        = length(q);  % S = Number of particles.\nN_babies = zeros(1,S);\ncumDist  = cumsum(q');\n\nu = fliplr(cumprod(rand(1,S).^(1./(S:-1:1))));\nj = 1;\nfor i = 1:S\n    while (u(1,i) > cumDist(1,j))\n        j = j + 1;\n    end\n    N_babies(1,j) = N_babies(1,j) + 1;\nend;\n\n% COPY RESAMPLED TRAJECTORIES:\n%--------------------------------------------------------------------------\nindex = 1;\nfor i = 1:S\n    if (N_babies(1,i)>0)\n        for j=index:index+N_babies(1,i)-1\n            I(j) = inIndex(i);\n        end;\n    end;\n    index = index + N_babies(1,i);\nend\n\nreturn\n%==========================================================================\n\n% notes and demo:\n%==========================================================================\n% The code below generates a nonlinear, non-Gaussian problem (S) comprising\n% a model S.M and data S.Y (c.f. van der Merwe et al 2000))\n%\n% The model is   f(x) = dxdt\n%                     = 1 + sin(0.04*pi*t) - log(2)*x + n\n%                y    = g(x)\n%                     = (x.^2)/5  : if t < 30\n%                       -2 + x/2  : otherwise\n% i.e. the output nonlinearity becomes linear after 30 time steps.  In this\n% implementation time is modelled as an auxiliary state variable.  n is\n% the process noise, which is modelled as a log-normal variate.  e is\n% Gaussian observation noise.\n\n% model specification\n%--------------------------------------------------------------------------\nf       = '[1; (1 + sin(P(2)*pi*x(1)) - P(1)*x(2) + exp(v))]';\ng       = '(x(1) > 30)*(-2 + x(2)/2) + ~(x(1) > 30)*(x(2).^2)/5';\nM(1).x  = [1; 1];                  % initial states\nM(1).f  = inline(f,'x','v','P');   % state equation\nM(1).g  = inline(g,'x','v','P');   % observer equation\nM(1).pE = [log(2) 0.04];           % parameters\nM(1).V  = exp(4);                  % observation noise precision\n\nM(2).v  = 0;                       % initial process log(noise)\nM(2).V  = 2.4;                     % process log(noise) precision\n\n% generate data (output)\n%--------------------------------------------------------------------------\nT       = 60;                      % number of time points\nS       = spm_DEM_generate(M,T);\n\n% Particle filtering\n%--------------------------------------------------------------------------\npf_x    = spm_pf(M,S.Y);\n\n% plot results\n%--------------------------------------------------------------------------\nx       = S.pU.x{1};\nplot([1:T],x(2,:),[1:T],pf_x(2,:))\nlegend({'true','PF'})\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_pf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5623811057964997}}
{"text": "function [i,j] = xy2ind(ebsd,x,y)\n% convert x,y coordinates into indeces of ebsd\n%\n% Syntax\n%\n%   ind = xy2ind(ebsd,x,y)\n%   ebsd(ind)\n%\n%   [i,j] = ind = xy2ind(ebsd,x,y)\n%   ebsd(i,j)\n%\n% Input\n%  ebsd - @EBSDsquare\n%  x,y  - spatial coordinates\n%\n% Output\n%  ind  - index to @EBSDsquare\n%  i,j  - indeces to @EBSDsquare\n%\n\nif nargin == 2\n  y = x(:,2);\n  x = x(:,1);\nend\n\ni = 1+round((y - ebsd.prop.y(1))./ebsd.dy);\nj = 1+round((x - ebsd.prop.x(1))./ebsd.dx);\n\nif nargout == 1, i = sub2ind(size(ebsd),i,j); end\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/EBSDAnalysis/@EBSDsquare/xy2ind.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5623810980249423}}
{"text": "function [fx,dfdx,dfdp] = f_DCMwHRFext(Xt,Theta,ut,inF) % \n% DCM for fMRI evolution function (including Balloon model)\n% function [fx,dF_dX,dF_dTheta] = f_DCMwHRF(Xt,Theta,ut,inF)\n% This function evaluates the evolution function DCM for fMRI, including\n% the Balloon HRF model.\n\n\nut = ut(inF.confounds.indu);\nnx = length(Xt);\nnr = length(inF.r);\n\n%- hidden states evolution\nxn = Xt(inF.n5);\nif ~isfield(inF,'fast')\n    [fxh,dfdxh,dfdph] = f_HRF3(Xt(1:nx-nr),Theta,xn,inF);\nelse\n    fxh = zeros(nx-nr,1);\n    dfdxh = zeros(nx-nr,nx-nr);\n    dfdph = zeros(length(Theta),nx-nr);\nend\n\n[fxn,dfdxn,dfdpn] = f_dcm4fmri(Xt(inF.n5),Theta,ut,inF);\n[fxr,dfdxr,dfdpr] = f_dcm_extension(Xt([inF.n5 inF.r]),Theta,ut,inF);\n\n%== Reshape flow field and gradients\n%- flow\nfx = zeros(nx,1);\nfx(1:nx-nr) = fxh ;\nfx(inF.n5) = fxn ;\nfx(inF.r) = fxr ;\n\n%- jacobian\ndfdx = zeros(nx,nx);\ndfdx(1:nx-nr,1:nx-nr) = dfdxh ;\ndfdx(inF.n5,inF.n5) = dfdxn;\ndfdx([inF.n5 inF.r],inF.r) = dfdxr ; \n\n%- wrt parameters\ndfdp = zeros(length(Theta),nx);\ndfdp(:,1:nx-nr) = dfdph ;\ndfdp(:,inF.n5) = dfdp(:,inF.n5)+dfdpn ;\ndfdp(:,inF.r) = dfdpr ;\n\n\n\nend\n\n\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_DCMwHRFext.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5623743369549059}}
{"text": "function varargout = coeffs2( f, m, n )\n%COEFFS2   Double Fourier coefficients of a SPHEREFUN. \n% \n%   X = COEFFS2( F ) returns the 2D Fourier modes of the spherefun, viewed\n%   as a doubly periodic function. \n% \n%   [C, D, R] = COEFFS2( F ) returns a low rank approximation to the 2D\n%   Fourier modes.\n% \n%   X = COEFFS2(F, M, N) returns bivariate coefficients with N Fourier \n%   modes in latitude and M Fourier modes in longitude. \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    varargout = {}; \n    return\nend\n\n% Calculate the CDR decomposition: \n[C, D, R] = cdr(f); \n\nif ( nargin == 1 )\n    % Find the  coefficients of each slice: \n    U = C.coeffs; \n    R = R.coeffs;\nelse\n    if ( nargin == 2 )\n        n = m;\n    end\n    % Find the coefficients of each slice:\n    U = trigtech.alias(C.coeffs, n); \n    R = trigtech.alias(R.coeffs, m);\nend\n\n% Prepare the output. Keep in low rank form if nargin > 1.\nif ( nargout <= 1 ) \n    varargout = { U*D*R.' };\nelseif ( nargout <= 3 )\n    varargout = { U, D, R };\nelse\n    error('SPHEREFUN:COEFFS:NARGOUT',...\n            'Too many output arguments')\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/@spherefun/coeffs2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5623743323757758}}
{"text": "function data = imgSTD(img)\n    data = struct('intensity',[],'red',[],'green',[],'blue',[],'mean_range',[],'std_range',[],'mean_std',[],'std_std',[],'mean_entropy',[]);\n    dim = size(img,1) / 4;\n    for j = 1:4\n        xend = j*dim;\n        xstart = xend - 3;\n        for m = 1:4\n            \n            intensity = [];\n            red = [];\n            green = [];\n            blue = [];\n            mean_range = [];\n            std_range = [];\n            mean_std = [];\n            std_std = [];\n            mean_entropy = [];\n            \n            yend = m*dim;\n            ystart = yend - dim + 1;\n            for k = xstart:xend\n                for l = ystart:yend\n                    intensity = [intensity img{k,l}.intensity];\n                    red = [red img{k,l}.red];\n                    green = [green img{k,l}.green];\n                    blue = [blue img{k,l}.blue];\n                    mean_range = [mean_range img{k,l}.mean_range];\n                    std_range = [std_range img{k,l}.std_range];\n                    mean_std = [mean_std img{k,l}.mean_std];\n                    std_std = [std_std img{k,l}.std_std];\n                    mean_entropy = [mean_entropy img{k,l}.mean_entropy];\n                end\n            end\n            data.intensity = [data.intensity std(intensity)];\n            data.red = [data.red std(red)];\n            data.green = [data.green std(green)];\n            data.blue = [data.blue std(blue)];\n            data.mean_range = [data.mean_range std(mean_range)];\n            data.std_range = [data.std_range std(std_range)];\n            data.mean_std = [data.mean_std std(mean_std)];\n            data.std_std = [data.std_std std(std_std)];\n            data.mean_entropy = [data.mean_entropy std(mean_entropy)];\n        end\n    end\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u8bc6\u522b\u7b97\u6cd5/Ghost-Target-master/imgSTD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5623743311115923}}
{"text": "function [ output_args ] = gmm_hu(I,M,options)\n%GMM_HU Summary of this function goes here\n%   Detailed explanation goes here\nbeta1 = 1e4;\nbeta2 = 0; % 2e4\neta = 0.05;\n\nrho1 = 1e4;\n\nif isstruct(options)\n    arg_set = fieldnames(options);\n    for i = 1:length(arg_set)\n        eval([arg_set{i},'=options.',arg_set{i},';']);\n    end\nend\n\nnames = cell(1,M);\nfor i = 1:M\n    names{i} = ['endmember ',num2str(i)];\nend\n\n%% initialize parameters\n[Y,~,rows,cols] = reshape_hsi(I,[]);\n[N,B] = size(Y);\n\nbeta1 = beta1*B/M;\nbeta2 = beta2*B/M;\nrho1 = rho1*N/M^2;\n\nif beta1 < 1e-9\n    beta1 = 1e-9;\nend\n\n[W,Neighbors] = image2graph(I,eta,1e-9);\n\nD = diag(sum(W,2));\nL = D - W;\nL = sparse(L);\nKL = L - beta2/beta1*speye(N);\n\nW = ones(M,M);\nD = diag(sum(W,2));\nH = D - W;\n\n[mu_jk,sigma_jk,w_jk,K,A] = gmm_init(I,M);\n\n%% Create all the k indices\n% K = [1 2 3 1];\nK_inds  = cell(1,M);\nfor j = 1:M\n    K_inds{j} = (1:K(j));\nend\nK_all = cartprod(K_inds{:});\nK1 = size(K_all,1);\n\n\n%% iterate by MM (EM)\nw_k = w_jk2w_k(w_jk,K_all);\n\nsigma = Y_noise;\n\nI_B = eye(B);\n\ndelta_t0 = 1e-12;\n\ndelta_t_mu = delta_t0;\ndelta_t_sigma = delta_t0;\ndelta_t_A = delta_t0;\n\nder_mu0 = mu_jk;\nder_sigma0 = sigma_jk;\nder_A0 = zeros(N,M);\nfor j = 1:length(der_mu0)\n    der_mu0{j}(:,:) = 0;\n    der_sigma0{j}(:,:,:) = 0;\nend\n\ns = [];\ns.N = N;\ns.B = B;\ns.K1 = K1;\ns.sigma = sigma;\ns.K_all = K_all;\ns.Y = Y;\ns.beta1 = beta1;\ns.KL = KL;\n\ns.A = A;\ns.mu_jk = mu_jk;\ns.sigma_jk = sigma_jk;\ns.w_k = w_k;\n\nIs = (1:N*B);\nIs = repmat(reshape(Is, [B,1,N]), 1, B);\nIs = Is(:);\n\nJs = (1:N*B);\nJs = repmat(reshape(Js, [1,B,N]), B, 1);\nJs = Js(:);\n\ns.Is = Is;\ns.Js = Js;\n\nmax_iter = 200;\neval_totals = zeros(max_iter, 1);\neval_Ns = zeros(max_iter, 1);\neval_As = zeros(max_iter, 1);\neval_Rs = zeros(max_iter, 1);\n\nfor iter = 1:200    \n    %% E step\n    % update gamma_nk\n    \n    N_nk = calc_gaussians(A, sigma, mu_jk, sigma_jk, K_all, Y, s);\n    \n    gamma_nk = (ones(N,1)*w_k) .* N_nk;\n    gamma_nk = gamma_nk ./ repmat(sum(gamma_nk,2), 1, K1);\n    s.gamma_nk = gamma_nk;\n    \n    %% M step\n    % update w_k\n    w_k = sum(gamma_nk, 1) / N;\n    s.w_k = w_k;\n    \n    delta_t = delta_t0;\n    disp('Process M step optimization.');\n    \n\n    % update mu\n    der_mu = calc_der_mu(A, sigma, mu_jk, sigma_jk, K_all, gamma_nk, Y);\n    s.der_mu = der_mu;\n    delta_t_mu = calc_time_step_adaptive(@eval_obj_fun_mu, @update_mu, ...\n        mu_jk, s, delta_t_mu, delta_t0);\n    mu_jk = update_mu(mu_jk, s, delta_t_mu);\n    s.mu_jk = mu_jk;\n\n    % update sigma\n    der_sigma = calc_der_sigma(A, sigma, mu_jk, sigma_jk, K_all, gamma_nk, Y);\n    s.der_sigma = der_sigma;\n    delta_t_sigma = calc_time_step_adaptive(@eval_obj_fun_sigma, @update_sigma, ...\n        sigma_jk, s, delta_t_sigma, delta_t0);\n    sigma_jk = update_sigma(sigma_jk, s, delta_t_sigma);\n    s.sigma_jk = sigma_jk;\n\n    % update A\n    der_A = calc_der_A(A, sigma, mu_jk, sigma_jk, K_all, gamma_nk, Y, KL, beta1);\n    s.der_A = der_A;\n    delta_t_A = calc_time_step_adaptive(@eval_obj_fun_A, @update_A, ...\n        A, s, delta_t_A, delta_t0);\n    A = update_A(A, s, delta_t_A);\n    s.A = A;\n    \n    if mod(iter,40) == 0\n        endmember_scatter_plot_end_var(Y,w_jk,mu_jk,sigma_jk,names);\n        set(gcf,'name',['Scatter plot of iteration ',num2str(iter)]);\n        show_abundances(A,size(I,1),size(I,2));\n        set(gcf,'name',['Abundances of iteration ',num2str(iter)]);\n        pause(0.01);\n    end\n    \n    [eval_total, eval_N, eval_A, eval_R] = calc_obj_fun(A, ...\n        sigma, mu_jk, sigma_jk, K_all, Y, KL, beta1, w_k, s);\n    eval_totals(iter) = eval_total;\n    eval_Ns(iter) = eval_N;\n    eval_As(iter) = eval_A;\n    eval_Rs(iter) = eval_R;\n    \n    disp(['EM iteration ', num2str(iter)]);\n\nend\n\nw_jk = w_k2w_jk(w_k, K_all);\n\nshow_abundances(A,size(I,1),size(I,2));\nfigure('name', 'Total objective function value vs iteration number');\nplot(eval_totals);\n\nfigure('name', 'Data fidelity term value vs iteration number');\nplot(eval_Ns);\n\nfigure('name', 'Abundance smoothness term value vs iteration number');\nplot(eval_As);\n\nfigure('name', 'Endmembers clossness term value vs iteration number');\nplot(eval_Rs);\n\n\nfunction [eval_total, eval_N, eval_A, eval_R] = calc_obj_fun(A, ...\n    sigma, mu_jk, sigma_jk, K_all, Y, KL, beta1, w_k, options)\nN = size(A,1);\n\nN_nk = calc_gaussians(A, sigma, mu_jk, sigma_jk, K_all, Y, options);\neval_N = -sum(log(sum((ones(N,1)*w_k) .* N_nk, 2)));\neval_A = (beta1/2)*trace(A'*KL*A);\neval_R = 0;\neval_total = eval_N + eval_A + eval_R;\n\n\nfunction N_nk = calc_gaussians(A, sigma, mu_jk, sigma_jk, K_all, Y, options)\n[N,B] = size(Y);\nK1 = size(K_all,1);\n\n[mu_nk,sigma_nk] = calc_mu_sigma_nk(A, sigma, mu_jk, sigma_jk, K_all);\n% old implementation\n\n% N_nk1 = zeros(N,K1);\n% for n = 1:N\n%     for k = 1:K1\n%         y_n_mu_nk = Y(n,:)'-mu_nk(:,:,n,k);\n%         N_nk1(n,k) = det(sigma_nk(:,:,n,k))^(-1/2) * ...\n%             exp(-0.5 * y_n_mu_nk' * (sigma_nk(:,:,n,k) \\ y_n_mu_nk));\n%     end\n% end\n% N_nk1 = N_nk1 / (2*pi)^(B/2);\n    \n% new implementation\n\nN_nk = zeros(N,K1);\nfor k = 1:K1\n    y = logmvn(Y, mu_nk(:,:,k), sigma_nk(:,:,:,k), options);\n    N_nk(:,k) = exp(y);\nend \n\n% norm(N_nk - N_nk1) / norm(N_nk)\n\n\nfunction val = eval_obj_fun_mu(params, options)\nmu_jk = params;\n\nA = options.A;\nsigma = options.sigma;\n% mu_jk = options.mu_jk;\nsigma_jk = options.sigma_jk;\nK_all = options.K_all;\ngamma_nk = options.gamma_nk;\nY = options.Y;\nrho1 = options.rho1;\nw_k = options.w_k;\n% beta1 = options.beta1;\n% KL = options.KL;\nH = options.H;\n\n[N,B] = size(Y);\nK1 = size(K_all,1);\n[mu_nk,sigma_nk] = calc_mu_sigma_nk(A, sigma, mu_jk, sigma_jk, K_all);\n\n\nval2 = zeros(1,K1);\nfor k = 1:K1\n    Y1 = (Y - mu_nk(:,:,k))';\n    Y2 = Y1 .* repmat(gamma_nk(:,k)', B, 1);\n    sigma_k = block_diag(sigma_nk(:,:,:,k), options);\n    val2(k) = Y1(:)' * (sigma_k \\ Y2(:));\nend\nval = sum(sum(0.5 * val2));\n\n% tic\n% N_nk = zeros(N,K1);\n% for k = 1:K1\n%     N_nk(:,k) = logmvn(Y, reshape(mu_nk(:,:,:,k),B,N)', sigma_nk(:,:,:,k), options);\n% end \n% \n% val3 = -sum(sum(0.5 * gamma_nk .* N_nk));\n% toc\n\nval_mu = 0;\n[mu_all,sigma_all] = calc_mu_sigma_all(mu_jk, sigma_jk, K_all);\nfor k = 1:K1\n    val_mu = val_mu + w_k(k) * trace(mu_all(:,:,k) * H * mu_all(:,:,k)');\nend\nval_mu = rho1 / 2 * val_mu;\n\nval = val + val_mu;\n\n\nfunction val = eval_obj_fun_sigma(params, s)\nsigma_jk = params;\n\nA = s.A;\nsigma = s.sigma;\nmu_jk = s.mu_jk;\n% sigma_jk = options.sigma_jk;\nK_all = s.K_all;\ngamma_nk = s.gamma_nk;\nY = s.Y;\n% beta1 = options.beta1;\n% KL = options.KL;\n\nN = size(A,1);\nK1 = size(K_all,1);\n\n[mu_nk,sigma_nk] = calc_mu_sigma_nk(A, sigma, mu_jk, sigma_jk, K_all);\n% val1 = zeros(N,K1);\n% for n = 1:N\n%     for k = 1:K1\n%         y_n_mu_nk = Y(n,:)' - mu_nk(:,:,n,k);\n%         val1(n,k) = log(det(sigma_nk(:,:,n,k))) + y_n_mu_nk' * (sigma_nk(:,:,n,k) \\ y_n_mu_nk);\n%     end\n% end\n% \n% val = sum(sum(0.5 * gamma_nk .* val1));\n\nN_nk = zeros(N,K1);\nfor k = 1:K1\n    N_nk(:,k) = logmvn(Y, mu_nk(:,:,k), sigma_nk(:,:,:,k), s);\nend \n\nval = -sum(sum(0.5 * gamma_nk .* N_nk));\n\n\n\nfunction val = eval_obj_fun_A(params, options)\nA = params;\n\n% A = options.A;\nsigma = options.sigma;\nmu_jk = options.mu_jk;\nsigma_jk = options.sigma_jk;\nK_all = options.K_all;\ngamma_nk = options.gamma_nk;\nY = options.Y;\nbeta1 = options.beta1;\nKL = options.KL;\n\nN = size(A,1);\nK1 = size(K_all,1);\n[mu_nk,sigma_nk] = calc_mu_sigma_nk(A, sigma, mu_jk, sigma_jk, K_all);\n% val1 = zeros(N,K1);\n% for n = 1:N\n%     for k = 1:K1\n%         y_n_mu_nk = Y(n,:)' - mu_nk(:,:,n,k);\n%         val1(n,k) = log(det(sigma_nk(:,:,n,k))) + y_n_mu_nk' * (sigma_nk(:,:,n,k) \\ y_n_mu_nk);\n%     end\n% end\n\n% val = sum(sum(0.5 * gamma_nk .* val1)) + beta1/2 * trace(A'*KL*A);\n\nN_nk = zeros(N,K1);\nfor k = 1:K1\n    N_nk(:,k) = logmvn(Y, mu_nk(:,:,k), sigma_nk(:,:,:,k), options);\nend \n\nval = -sum(sum(0.5 * gamma_nk .* N_nk)) + beta1/2 * trace(A'*KL*A);\n\n\n\n\nfunction der_mu = calc_der_mu(A, sigma, mu_jk, sigma_jk, K_all, gamma_nk, Y)\n[N,M] = size(A);\nB = size(mu_jk{1},2);\nK1 = size(K_all,1);\nK = max(K_all,[],1);\n\n[mu_nk,sigma_nk] = calc_mu_sigma_nk(A, sigma, mu_jk, sigma_jk, K_all);\nlambda_nk = calc_lambda_nk(gamma_nk,mu_nk,sigma_nk,Y);\n\n% calculate der_mu\n% tic\n% der_mu = mu_jk;\n% for j = 1:M\n%     for k = 1:K(j)\n%         lambda_sum = sum(lambda_nk(:,:,K_all(:,j)==k), 3);\n%         lambda_alpha = repmat(A(:,j), [1,B]);\n%         der_mu{j}(k,:) = -sum(lambda_sum .* lambda_alpha, 1);\n%     end\n% end\n% toc\n\n% tic\nder_mu = mu_jk;\ntemp = zeros(M,B,K1);\nfor k = 1:K1\n    temp(:,:,k) = A' * lambda_nk(:,:,k);\nend\n\nfor j = 1:M\n    for k = 1:K(j)\n        der_mu{j}(k,:) = -sum(temp(j,:,K_all(:,j)==k), 3)';\n    end\nend\n% toc\n\n% mdif(der_mu{1},der_mu1{1});\n\nfunction der_sigma = calc_der_sigma(A, sigma, mu_jk, sigma_jk, K_all, gamma_nk, Y)\n[N,M] = size(A);\n[~,B] = size(Y);\nK = max(K_all,[],1);\nK1 = size(K_all,1);\n\n[mu_nk,sigma_nk,prec] = calc_mu_sigma_prec(A, sigma, mu_jk, sigma_jk, K_all);\n[lambda_nk,psi_nk] = calc_lambda_psi_nk(gamma_nk,mu_nk,sigma_nk,prec,Y);\n\n% calculate der_mu, der_sigma, der_A\n% tic\n% der_sigma1 = sigma_jk;\n% for j = 1:M\n%     for k = 1:K(j)\n%         psi_sum = sum(psi_nk(:,:,:,K_all(:,j)==k), 4);\n%         psi_alpha = reshape(repmat(A(:,j)'.^2, [B*B,1]), [B,B,N]);\n%         der_sigma1{j}(:,:,k) = -sum(psi_sum .* psi_alpha, 3);        \n%     end\n% end\n% toc\n\n% tic\npsi_k = reshape(psi_nk, [B*B,N,K1]);\nder_sigma = sigma_jk;\ntemp = zeros(M,B*B,K1);\nfor k = 1:K1\n    temp(:,:,k) = (A.^2)' * psi_k(:,:,k)';\nend\n\nfor j = 1:M\n    for k = 1:K(j)\n        der_sigma{j}(:,:,k) = reshape(-sum(temp(j,:,K_all(:,j)==k), 3)', B, B);\n    end\nend\n% toc\n\n% disp('');\n\nfunction lambda_nk = calc_lambda_nk(gamma_nk,mu_nk,sigma_nk,Y)\n[N,B,K1] = size(mu_nk);\n\n% tic\n% lambda_nk1 = zeros(N,B,K1);\n% for n = 1:N\n%     for k = 1:K1\n%         lambda_nk1(n,:,k) = gamma_nk(n,k) * ...\n%             (sigma_nk(:,:,n,k) \\ (Y(n,:)' - mu_nk(n,:,k)'));\n%     end\n% end\n% toc\n\n% tic\nlambda_nk = zeros(N,B,K1);\nfor k = 1:K1\n    Y1 = Y - mu_nk(:,:,k);\n    Y1 = Y1';\n    Y2 = Y1 .* repmat(gamma_nk(:,k)', B, 1);\n    sigma_k = block_diag(sigma_nk(:,:,:,k));\n    lambda_nk(:,:,k) = reshape(sigma_k \\ Y2(:), [B,N])';\nend\n% toc\n\nfunction [lambda_nk,psi_nk] = calc_lambda_psi_nk(A, sigma, mu_jk, ...\n    sigma_jk, K_all, gamma_nk, Y)\n[mu_nk,sigma_nk,prec] = calc_mu_sigma_prec(A, sigma, mu_jk, sigma_jk, K_all);\n\n[N,B,K1] = size(mu_nk);\n\n% tic\n% lambda_nk1 = zeros(N,B,K1);\n% psi_nk1 = zeros(B,B,N,K1);\n% \n% for k = 1:K1\n%     Y1 = Y - mu_nk(:,:,k);\n%     for n = 1:N\n%         sigma_y_n_mu_nk = prec(:,:,n,k) * Y1(n,:)';\n%         lambda_nk1(n,:,k) = gamma_nk(n,k) * sigma_y_n_mu_nk;\n%         psi_nk1(:,:,n,k) = 0.5 * gamma_nk(n,k) * ( ...\n%             sigma_y_n_mu_nk * sigma_y_n_mu_nk' - prec(:,:,n,k));\n%     end\n% end\n% toc\n\n% tic\nlambda_nk = zeros(N,B,K1);\npsi_nk = zeros(B,B,N,K1);\n\nfor k = 1:K1\n    Y1 = Y - mu_nk(:,:,k);\n    sigma_y_n_mu_nk = multiprod(prec(:,:,:,k), Y1', [1 2], [1]);\n    lambda_nk(:,:,k) = (repmat(gamma_nk(:,k)', B, 1) .* sigma_y_n_mu_nk)';\n    \n    tmp1 = reshape(sigma_y_n_mu_nk, [B 1 N]);\n    tmp2 = reshape(sigma_y_n_mu_nk, [1 B N]);\n    tmp3 = multiprod(tmp1, tmp2, [1 2], [1 2]) - prec(:,:,:,k);\n    psi_nk(:,:,:,k) = 0.5 * multiprod(reshape(gamma_nk(:,k), [1 1 N]), tmp3);\nend\n% toc\n% mdiff(lambda_nk,lambda_nk1);\n% mdiff(psi_nk,psi_nk1);\n\n\nfunction der_A = calc_der_A(A, sigma, mu_jk, sigma_jk, K_all, gamma_nk, ...\n    Y, KL, beta1)\n[N,K1] = size(gamma_nk);\nM = length(mu_jk);\nB = size(mu_jk{1},2);\n\n[mu_nk,sigma_nk,prec] = calc_mu_sigma_prec(A, sigma, mu_jk, sigma_jk, K_all);\n[lambda_nk,psi_nk] = calc_lambda_psi_nk(gamma_nk,mu_nk,sigma_nk,prec,Y);\n\n\n% calculate der_mu, der_sigma, der_A\n% tic\n% \n% der_A1 = zeros(N,M);\n% for n = 1:N\n%     for j = 1:M\n%         for k = 1:K1\n%             der_A1(n,j) = der_A1(n,j) - sum(lambda_nk(n,:,k) .* mu_jk{j}(K_all(k,j),:)) ...\n%                 - 2 * A(n,j) * sum(sum(psi_nk(:,:,n,k) .* sigma_jk{j}(:,:,K_all(k,j))));\n%         end\n%     end\n% end\n% toc\n\n% tic\n[mu_all,sigma_all] = calc_mu_sigma_all(mu_jk, sigma_jk, K_all);\npsi_k = reshape(psi_nk, [B*B,N,K1]);\n\nder_A = zeros(N,M);\ntemp1 = zeros(N,M);\nfor k = 1:K1\n    der_A = der_A - lambda_nk(:,:,k) * mu_all(:,:,k);\n    temp1 = temp1 - psi_k(:,:,k)' * sigma_all(:,:,k);\nend\nder_A = der_A + 2 * A .* temp1;\n% toc\n\nder_A = der_A + beta1 * KL * A;\n\n\nfunction mu_jk_new = update_mu(mu_jk, options, delta_t)\nder_mu = options.der_mu;\n\nmu_jk_new = mu_jk;\n\nfor j = 1:length(mu_jk)\n    mu_jk_new{j} = mu_jk{j} - delta_t * der_mu{j};\nend\n\nfunction sigma_jk_new = update_sigma(sigma_jk, options, delta_t)\nder_sigma = options.der_sigma;\n\nsigma_jk_new = sigma_jk;\n\nfor j = 1:length(sigma_jk)\n    sigma_jk_new{j} = sigma_jk{j} - delta_t * der_sigma{j};\n%     sigma_jk_new{j} = sigma_jk{j};\n    for k = 1:size(sigma_jk{j},3)\n        cov_mat = sigma_jk_new{j}(:,:,k);\n        [V,D] = eig((cov_mat + cov_mat')/2);\n        d = diag(D);\n        if (min(d) < 0)\n            disp('There is a negative eigenvalue in the updated sigma_jk');\n            d(d<0) = 1e-6 * max(abs(d));\n            D = diag(d);\n        end\n        sigma_jk_new{j}(:,:,k) = V*D*V';\n    end\nend\n\nfunction A_new = update_A(A, options, delta_t)\nder_A = options.der_A;\n\nA_new = A - delta_t * der_A;\nA_new = project_to_simplex(A_new);\n\nfunction [mu_nk,sigma_nk] = calc_mu_sigma_nk(A, sigma, mu_jk, sigma_jk, K_all)\n[N,M] = size(A);\nK1 = size(K_all,1);\nB = size(mu_jk{1},2);\n\n[mu_all,sigma_all] = calc_mu_sigma_all(mu_jk, sigma_jk, K_all);\n\nsigma2_I = sigma^2 * eye(B);\n\n% old implementation\n% mu_nk1 = zeros(B,1,N,K1);\n% sigma_nk1 = zeros(B,B,N,K1);\n% for n = 1:N\n%     for k = 1:K1\n%         mu_nk1(:,:,n,k) = mu_all(:,:,k) * A(n,:)';\n%         sigma_nk1(:,:,n,k) = reshape(sigma_all(:,:,k) * (A(n,:).^2)', B, B) + sigma2_I;\n%     end\n% end\n\n% new implementation is 10 times faster\nmu_nk = zeros(N,B,K1);\nsigma_nk = zeros(B*B,N,K1);\nfor k = 1:K1\n    mu_nk(:,:,k) = A * mu_all(:,:,k)';\n    sigma_nk(:,:,k) = sigma_all(:,:,k) * (A.^2)' + repmat(sigma2_I(:),1,N);\nend\n% mu_nk = reshape(mu_nk,[B,1,N,K1]); \nsigma_nk = reshape(sigma_nk,[B,B,N,K1]);\n\nfunction [mu_all,sigma_all] = calc_mu_sigma_all(mu_jk, sigma_jk, K_all)\n[~,B] = size(mu_jk{1});\n[K1,M] = size(K_all);\n\nmu_all = zeros(B,M,K1);\nsigma_all = zeros(B*B,M,K1);\nfor i = 1:K1\n    for j = 1:M\n        mu_all(:,j,i) = mu_jk{j}(K_all(i,j),:)';\n        sigma_all(:,j,i) = reshape(sigma_jk{j}(:,:,K_all(i,j)), B*B, 1);\n    end\nend\n\n\nfunction [mu_nk,sigma_nk,prec] = calc_mu_sigma_prec(A, sigma, mu_jk, sigma_jk, K_all)\n[mu_nk,sigma_nk] = calc_mu_sigma_nk(A, sigma, mu_jk, sigma_jk, K_all);\n% [N,B,K1] = size(mu_nk);\n% tic\n% prec1 = zeros(size(sigma_nk));\n% for n = 1:N\n%     for k = 1:K1\n%         prec1(:,:,n,k) = inv(sigma_nk(:,:,n,k));\n%     end\n% end\n% toc\n% \n% tic\nprec = multinv(sigma_nk);\n% toc\n% \n% mdiff(prec,prec1);\n\n% tic\n% prec1 = cell(1,K1);\n% for k = 1:K1\n%     sigma_k = block_diag(sigma_nk(:,:,:,k), options);\n%     R = chol(sigma_k);\n%     S = inv(R);\n%     prec1{k} = S*S';\n% end\n% \n% prec2 = zeros(B,B,N,K1);\n% for k = 1:K1\n%     [~,~,S] = find(prec1{k});\n%     prec2(:,:,:,k) = reshape(S, [B,B,N]);\n% end\n% \n% toc\n% \n% mdif(prec,prec2)\n\n\nfunction w_k = w_jk2w_k(w_jk, K_all)\nw_k = ones(1, size(K_all,1));\nfor i = 1:size(K_all,1)\n    k = K_all(i,:);\n    for j = 1:length(w_jk)\n        w_k(i) = w_k(i)*w_jk{j}(k(j));\n    end\nend\n\nfunction w_jk = w_k2w_jk(w_k, K_all)\nM = size(K_all,2);\nw_jk = cell(1,M);\nK = zeros(1,M);\nfor j = 1:M\n    K(j) = max(K_all(:,j));\n    w_jk{j} = zeros(1,K(j));\nend\n\nfor j = 1:M\n    for l = 1:K(j)\n        w = w_k(K_all(:,j)==l);\n        w_jk{j}(l) = sum(w);\n    end\nend\n\n%% obsolete\nfunction delta_t = calc_time_step(A, sigma, mu_jk, sigma_jk, K_all, ...\n    gamma_nk, Y, delta_t, delta_t0, der_mu, der_sigma, der_A, beta1, KL)\nval_ori = eval_obj_fun_M(A, sigma, mu_jk, sigma_jk, K_all, gamma_nk, Y, beta1, KL);\n[mu_jk_new, sigma_jk_new, A_new] = update_params(mu_jk, sigma_jk, A, der_mu, der_sigma, der_A, delta_t);\nval_new = eval_obj_fun_M(A_new, sigma, mu_jk_new, sigma_jk_new, K_all, gamma_nk, Y, beta1, KL);\n\nif val_new < val_ori\n    val_old = val_new;\n    while 1\n        delta_t = delta_t * 10;\n        [mu_jk_new, sigma_jk_new, A_new] = update_params(mu_jk, sigma_jk, A, ...\n            der_mu, der_sigma, der_A, delta_t);\n        val = eval_obj_fun_M(A_new, sigma, mu_jk_new, sigma_jk_new, K_all, gamma_nk, Y, beta1, KL);\n        if val < val_old\n            val_old = val;\n        else\n            delta_t = delta_t / 10;\n            break;\n        end\n    end\nelse\n    while delta_t > delta_t0\n        delta_t = delta_t / 10;\n        [mu_jk_new, sigma_jk_new, A_new] = update_params(mu_jk, sigma_jk, A, ...\n            der_mu, der_sigma, der_A, delta_t);\n        val = eval_obj_fun_M(A_new, sigma, mu_jk_new, sigma_jk_new, K_all, gamma_nk, Y, beta1, KL);\n        if val < val_ori\n            break;\n        end\n    end\nend\n\n\nfunction [mu_jk_new, sigma_jk_new, A_new] = update_params(mu_jk, sigma_jk, A, ...\n    der_mu, der_sigma, der_A, delta_t)\nmu_jk_new = mu_jk;\nsigma_jk_new = sigma_jk;\n\nfor j = 1:length(mu_jk)\n    mu_jk_new{j} = mu_jk{j} - delta_t * der_mu{j};\n    sigma_jk_new{j} = sigma_jk{j} - delta_t * der_sigma{j};\n%     sigma_jk_new{j} = sigma_jk{j};\n    for k = 1:size(sigma_jk{j},3)\n        cov_mat = sigma_jk_new{j}(:,:,k);\n        [V,D] = eig((cov_mat + cov_mat')/2);\n        d = diag(D);\n        if (min(d) < 0)\n            disp('There is a negative eigenvalue in the updated sigma_jk');\n            d(d<0) = 1e-6 * max(abs(d));\n            D = diag(d);\n        end\n        sigma_jk_new{j}(:,:,k) = V*D*V';\n    end\nend\n\nA_new = A - delta_t * der_A;\nA_new = project_to_simplex(A_new);\n\n\nfunction val = eval_obj_fun_M(A, sigma, mu_jk, sigma_jk, K_all, gamma_nk, Y, beta1, KL)\nN = size(A,1);\nK1 = size(K_all,1);\n[mu_nk,sigma_nk] = calc_mu_sigma_nk(A, sigma, mu_jk, sigma_jk, K_all);\nval1 = zeros(N,K1);\nfor n = 1:N\n    for k = 1:K1\n        y_n_mu_nk = Y(n,:)' - mu_nk(:,:,n,k);\n        val1(n,k) = log(det(sigma_nk(:,:,n,k))) + y_n_mu_nk' * (sigma_nk(:,:,n,k) \\ y_n_mu_nk);\n    end\nend\n\nval = sum(sum(0.5 * gamma_nk .* val1)) + beta1/2 * trace(A'*KL*A);\n\n\nfunction [der_mu, der_sigma, der_A] = calc_derivatives(A, sigma, mu_jk, ...\n    sigma_jk, K_all, gamma_nk, Y, beta1, KL)\n[N,M] = size(A);\nB = size(mu_jk{1},2);\nK1 = size(K_all,1);\nK = max(K_all,[],1);\n\nder_mu = mu_jk;\nder_sigma = sigma_jk;\n\n[mu_nk,sigma_nk,prec] = calc_mu_sigma_prec(A, sigma, mu_jk, sigma_jk, K_all);\n\nlambda_nk = zeros(B,1,N,K1);\npsi_nk = zeros(B,B,N,K1);\nder_A = zeros(N,M);\nfor n = 1:N\n    for k = 1:K1\n        sigma_y_n_mu_nk = prec(:,:,n,k) * (Y(n,:)' - mu_nk(:,:,n,k));\n        lambda_nk(:,:,n,k) = gamma_nk(n,k) * sigma_y_n_mu_nk;\n        psi_nk(:,:,n,k) = 0.5 * gamma_nk(n,k) * ( ...\n            sigma_y_n_mu_nk * sigma_y_n_mu_nk' - prec(:,:,n,k));\n    end\nend\n% calculate der_mu, der_sigma, der_A\nfor j = 1:M\n    for k = 1:K(j)\n        lambda_sum = sum(lambda_nk(:,:,:,K_all(:,j)==k), 4);\n        lambda_alpha = reshape(repmat(A(:,j)', [B,1]), [B,1,N]);\n        der_mu{j}(k,:) = -sum(lambda_sum .* lambda_alpha, 3);\n\n        psi_sum = sum(psi_nk(:,:,:,K_all(:,j)==k), 4);\n        psi_alpha = reshape(repmat(A(:,j)'.^2, [B*B,1]), [B,B,N]);\n        der_sigma{j}(:,:,k) = -sum(psi_sum .* psi_alpha, 3);        \n    end\nend\n\nfor n = 1:N\n    for j = 1:M\n        for k = 1:K1\n            der_A(n,j) = der_A(n,j) - sum(lambda_nk(:,:,n,k) .* mu_jk{j}(K_all(k,j),:)') ...\n                - 2 * A(n,j) * sum(sum(psi_nk(:,:,n,k) .* sigma_jk{j}(:,:,K_all(k,j))));\n        end\n    end\nend\nder_A = der_A + beta1 * KL * A;\n\n\nfunction [der_mu, der_sigma] = calc_derivative_sigma(A, sigma, mu_jk, sigma_jk, K_all, gamma_nk, Y)\n[N,M] = size(A);\nB = size(mu_jk{1},2);\nK1 = size(K_all,1);\nK = max(K_all,[],1);\n\nder_mu = mu_jk;\nder_sigma = sigma_jk;\n\nfor j = 1:M\n    der_mu{j} = zeros(size(der_mu{j}));\nend\n\n[mu_nk,sigma_nk,prec] = calc_mu_sigma_prec(A, sigma, mu_jk, sigma_jk, K_all);\n\npsi_nk = zeros(B,B,N,K1);\nfor n = 1:N\n    for k = 1:K1\n        sigma_y_n_mu_nk = prec(:,:,n,k) * (Y(n,:)' - mu_nk(:,:,n,k));\n        psi_nk(:,:,n,k) = 0.5 * gamma_nk(n,k) * ( ...\n            sigma_y_n_mu_nk * sigma_y_n_mu_nk' - prec(:,:,n,k));\n    end\nend\n% calculate der_sigma\nfor j = 1:M\n    for k = 1:K(j)\n        psi_sum = sum(psi_nk(:,:,:,K_all(:,j)==k), 4);\n        psi_alpha = reshape(repmat(A(:,j)'.^2, [B*B,1]), [B,B,N]);\n        der_sigma{j}(:,:,k) = -sum(psi_sum .* psi_alpha, 3);\n        \n%         temp = zeros(B,B);\n%         for n = 1:N\n%             for k1 = 1:K1\n%                 if k == K_all(k1,j)\n%                     temp = temp - A(n,j)^2 * psi_nk(:,:,n,k1);\n%                 end\n%             end\n%         end\n    end\nend\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/GMM/gmm_hu_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5623743242428971}}
{"text": "function [odf,alpha] = calcFEMODF(pf,varargin)\n% PDF to ODF inversion\n%\n% *calcFEMODF* is one of the main function of the MTEX toolbox.\n% It estimates an ODF from given Polefigure intensities by\n% <PoleFigure2ODF.html fitting an ODF that consists of a large number of unimodal ODFs to the data>.\n% It does so by minimizing a least squares functional. The command\n% *calcODF* supports <PoleFigure2ODFGhostCorrection.html automatic ghost correction> and\n% <PoleFigureDubna.html the zero range method>.\n% The function *calcFEMODF* has several options to control convergence,\n% resolution, smoothing, etc. See below for a complete description.\n%\n%\n% Input\n%  pf - @PoleFigure\n%\n% Options\n%  resolution     - localization grid for the ansatz fucntions (default = 3/2 resolution(pf))\n%  iterMax        - maximum number of iterations (default = 11)\n%  regularisation - weighting coefficient lambda (default = 0)\n%\n% Flags\n%  zeroRange         - apply zero range method (default = )\n%  noGhostCorrection - omit ghost correction\n%\n% Output\n%  odf    - reconstructed @FEMODF\n%  alpha  - scaling factors, calculated during reconstruction\n%\n% See also\n% PoleFigure2odf ODF_demo PoleFigureSimulation_demo\n% PoleFigure.load ImportPoleFigureData examples_index\n\ntic\nvdisp('------ MTEX -- PDF to ODF inversion ------------------',varargin{:})\n\n% ------------------- get input--------------------------------------------\n\nCS = pf.CS; SS = pf.SS;\n\n% generate FEM discretization of orientation space\nres = get_option(varargin,'resolution',pf.resolution);\n%ori = equispacedSO3Grid(CS,SS,'resolution',min(res,10*degree));\n%DSO3 = DelaunaySO3(ori);\nDSO3 = varargin{1};\n\n% zero range method - TODO\n%if check_option(varargin,'zero_range'), S3G = zero_range(pf,S3G,varargin{:});end\n\nvdisp('Setting up matrices',varargin{:});\n% compute matrices\nfor ipf = 1:length(pf)  \n  h = pf(ipf).h;\n  vdisp(char(h),varargin{:});\n  M{ipf} = sparse(length(pf(ipf).r),length(DSO3));\n  for ih = 1:length(h)\n    M{ipf} = M{ipf} + pf(ipf).c(ih) .* DSO3.pdfMatrix(h(ih),pf(ipf).r,varargin{:});\n  end\n  \n  b{ipf} = pf(ipf).intensities(:);\nend\n\nM = vertcat(M{:});\nb = vertcat(b{:});\n\nvdisp(['starting solver'],varargin{:});\nvdisp(['matrix is ' sizestr(M) ],varargin{:});\n% solve the linear system of equation\nc = lsqnonneg(M,b);\n%c = M \\ b;\n\n\n% set up FEMODF\nodf = femODF(DSO3,'weights',c);\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/PoleFigureAnalysis/@PoleFigure/calcFEMODF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5623743181607807}}
{"text": "function [KE, PE] = energy(q,dq,p)\n%[KE, PE] = energy(q,dq,p)\n%\n% This function computes the mechanical energy for the five-link biped\n%\n% INPUTS:\n%   q = [5,n] = configuration\n%   dq = [5,n] = rates\n%   p = parameter struct\n%\n% OUTPUTS:\n%   Fx = [1,n] = horizontal contact force acting on robot\n%   Fy = [1,n] = vertical contact force acting on robot\n%\n\n[KE, PE] = autoGen_energy(...\n q(1,:),q(2,:),q(3,:),q(4,:),q(5,:),...\n    dq(1,:),dq(2,:),dq(3,:),dq(4,:),dq(5,:),...\n    p.m1, p.m2, p.m3, p.m4, p.m5, p.I1, p.I2, p.I3, p.I4, p.I5, p.l1, p.l2, p.l3, p.l4, p.c1, p.c2, p.c3, p.c4, p.c5, p.g);\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/fiveLinkBiped/energy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5622638965956133}}
{"text": "% @author: Maziar Raissi\n\nfunction params_list = KDV()\n% quantile(params_list,[0.025 0.25 0.50 0.75 0.975])\nclc; close all;\n\nplt = 1;\nsave_plt = 0;\n\naddpath ..\naddpath ../Utilities\naddpath ../Kernels/KDV\naddpath ../Utilities/export_fig\n\nfunction CleanupFun()\n    rmpath ..\n    rmpath ../Utilities\n    rmpath ../Kernels/KDV\n    rmpath ../Utilities/export_fig\nend\n\nfinishup = onCleanup(@() CleanupFun());\n\nrng('default')\n\nset(0,'defaulttextinterpreter','latex')\n\n%% Load Data\nload('../Data/kdv.mat', 'usol', 't', 'x')\nu_star = real(usol); % 512x201\nt_star = t; % 201x1\nx_star = x';   % 512x1\nN_star = size(x_star,1);\nnsteps = size(t_star,1)-1;\n\nif plt ==1\n    figure(1);\n    plot_surface(t_star, x_star, u_star, '$t$', '$x$', '$u(t,x)$');\n    view(3)\n\n    drawnow()\nend\n    \n%% Setup\nnoise = 0.00;\nu_data = u_star + noise*std(u_star(:))*randn(size(u_star));\n\nN0 = 111;\nN1 = 109;\n%% Optimize model\nparams_list = zeros(nsteps,2);\nhyp = [log([1.0 1.0]) 0.0 0.0 -4.0];\nidx1 = randsample(N_star, N0);\nstep = 1;\nfor i = 1:step:nsteps\n    dt = t_star(i+step) - t_star(i);\n    \n    idx0 = idx1;\n    x0 = x_star(idx0,:);\n    u0 = u_data(idx0,i);\n    \n    idx1 = randsample(N_star,N1);\n    x1 = x_star(idx1,:);\n    u1 = u_data(idx1,i+step);\n    \n    model = HPM(x1, u1, x0, u0, dt, hyp);\n    model = model.train(50);\n    \n    hyp = model.hyp;\n    params_list(i,:) = hyp(3:4);\n    \n    [pred_n_star, var_n_star] = model.predict(x_star);\n    var_n_star = abs(diag(var_n_star));\n    \n    error = norm(pred_n_star - u_star(:,i+step))/norm(u_star(:,i+step));\n    \n    fprintf(1,'=========================\\n');\n    fprintf(1,'Step: %d, Time = %.2f\\n\\nNLML = %.2f, Error = %.2e\\n\\n', i, ...\n        t_star(i+step), model.NLML, error);\n       \n    str = sprintf('%.2f  ', params_list(i,:));\n    fprintf('Parameters: %s\\n\\n', str)\n    \n    str = sprintf('%.2f  ', median(params_list(1:step:i,:),1));\n    fprintf('Median: %s\\n', str)\n    fprintf(1,'=========================\\n\\n');\n    \n    if plt == 1\n        if ~exist('fig','var')\n            fig = figure(2);\n        end\n        set(fig,'units','normalized','outerposition',[0 0 1 1])\n        clf\n        \n        subplot(3,1,1);\n        tit = sprintf('Time: %.2f\\n%d training points', t_star(i), N0);\n        plot_data_1D(x_star, u_star(:,i), x0, u0, '$x$', '$u(t,x)$', tit);\n        \n        \n        subplot(3,1,2);\n        tit = sprintf('Time: %.2f\\n%d training points', t_star(i+step), N1);\n        plot_data_1D(x_star, u_star(:,i+step), x1, u1, '$x$', '$u(t,x)$', tit);\n        \n        \n        subplot(3,1,3);\n        plot_prediction_1D(x_star, u_star(:,i+step), pred_n_star, var_n_star, ...\n            '$x$', '$u(t,x)$', tit);\n        \n        drawnow;\n    end    \n    \nend\n\nif save_plt == 1\n    export_fig ./Figures/KDV.png -r300\nend\n\nend", "meta": {"author": "maziarraissi", "repo": "HPM", "sha": "21a7429cceb55d5ab688256db75ac360e2d8a925", "save_path": "github-repos/MATLAB/maziarraissi-HPM", "path": "github-repos/MATLAB/maziarraissi-HPM/HPM-21a7429cceb55d5ab688256db75ac360e2d8a925/Sensitivity_Analysis/KDV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5622427094717733}}
{"text": "function F = normalizePivots(F)\n%NORMALIZEPIVOTS   Scale rows and cols of a SEPARABLEAPPROX so that all pivots are 1.\n%\n% Additionally, the norm of the kth row and column will be the same.\n\n% Copyright 2017 by The University of Oxford and The Chebfun2 Developers.\n% See http://www.chebfun.org/ for Chebfun2 information.\n\n% TODO: Document\n% TODO: is this useful?\n\nF = normalizeRowsAndCols(F);\n\nd = F.pivotValues(:).';\ns = sign(d);\nsqrtp = sqrt(abs(d));\nF.cols = F.cols./(s.*sqrtp);\nF.rows = F.rows./sqrtp;\nF.pivotValues = ones(1, length(d));\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/@separableApprox/normalizePivots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5622427049653537}}
{"text": "\nswitch method\n    case{1} % TVD 0(h^2)\n        % Using discrete ordinate method (discrete and constant velocity\n        % values in phase-space domain)\n        a = v(:,1);        \n        % Load initial condition\n        f = f0;\n%            for tsteps = time\n               f_eq = f_equilibrium_1d(r,ux,v,t,theta);\n                % initialize variables\n                 u_next = zeros(1,nx);\n                 u_eq = zeros(1,nx);\n                 u = zeros(1,nx);\n                 for i = 1:nv\n                      % load subcase\n                      u_eq(:) = f_eq(i,:);\n                      u(:) = f(i,:);\n                      % Compute the smoothness factors, r(j), from data, u(j).\n                       [r] = theta1d(u,a(i));\n                        % Compute the Flux Limiter\n                       [phi] = fluxlimiter1d(r,1); % using limiter = 1\n                       % Compute TVD Fluxes\n                       [F_left,F_right] = TVDflux1d(u,a(i),dtdx,phi);\n                       % Compute next time step\n                        u_next = u - dtdx*(F_right - F_left) ...\n                        + (dt/r_time)*(u_eq-u);\n                        % BC\n                        u_next(1) = u_next(2);\n                        u_next(nx) = u_next(nx-1);\n                        % UPDATE info\n                         u = u_next;                \n                        % Going back to f\n                         f(i,:) = u(:);                         \n                 end\n                   % Compute macroscopic moments\n                   [n,j_x,E] = macromoments1d(k,w,f,v);\n            \n                   % UPDATE macroscopic properties \n                    % (here lies a paralellizing computing chalenge)\n                   [r,ux,t,p,yun] = macroproperties1d(n,j_x,E,nx,nv,theta);\n%                         [p,yun] = macroproperties1d(n,j_x,E,nx,nv,theta);\n%            end\n           case{2} % WENO k = 3 i.e. O(h^5) \n    otherwise\n          error('Order must be between 1 and 2');  \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/Coupled/codeA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5622349733091403}}
{"text": "%%*********************************************************************\n%% gdcomp: Compute gd = 1/td in Equation (15) of FOT's paper.\n%%\n%% [gd,info,blk2,At2,C2,b2] = gdcomp(blk,At,C,b,OPTIONS);\n%%\n%%*********************************************************************\n\n  function [gd,info,blk2,At2,C2,b2] = gdcomp(blk,At,C,b,OPTIONS);\n\n  if (nargin == 4)\n     OPTIONS = sqlparameters; \n     OPTIONS.vers = 1; \n     OPTIONS.printlevel = 3; \n  end\n  if ~iscell(C); tmp = C; clear C; C{1} = tmp; end\n%%\n  m = length(b); \n  blk2 = blk;\n  At2 = cell(size(blk,1),1); \n  C2 = cell(size(blk,1),1); \n  b2 = [zeros(m,1); 1; 0]; \n%%\n%% \n%%\n  for p = 1:size(blk,1)\n     pblk = blk(p,:); \n     n = sum(pblk{2}); \n     if strcmp(pblk{1},'s')\n        C2{p,1} = sparse(n,n); \n     else\n        C2{p,1} = zeros(n,1);\n     end\n  end\n%%\n%% New multipliers in dual problem: tt, theta.\n%% [v; tt; theta].\n%%\n   ss = 0; cc = 0; aa = zeros(1,m); \n   exist_ublk = 0; \n   for p = 1:size(blk,1)\n      pblk = blk(p,:); \n      n = sum(pblk{2}); \n      if strcmp(pblk{1},'s')\n         At2{p} = [At{p}, svec(pblk,speye(n,n),1), -svec(pblk,C{p},1)]; \n         ss = ss + n; \n         cc = cc + trace(C{p}); \n         aa = aa + svec(pblk,speye(n),1)'*At{p}; \n      elseif strcmp(pblk{1},'q')\n         eq = zeros(n,1); \n         idx1 = 1+[0,cumsum(pblk{2})]; \n         idx1 = idx1(1:length(idx1)-1);          \n         eq(idx1) = ones(length(idx1),1);\n         At2{p} = [At{p}, 2*sparse(eq), -sparse(C{p})];          \n         ss = ss + 2*length(pblk{2}); \n         cc = cc + sum(C{p}(idx1)); \n         aa = aa + eq'*At{p}; \n      elseif strcmp(pblk{1},'l')\n         el = ones(n,1); \n         At2{p} = [At{p}, sparse(el), -sparse(C{p})]; \n         ss = ss + n;\n         cc = cc + el'*C{p}; \n         aa = aa + el'*At{p}; \n      elseif strcmp(pblk{1},'u')\n         At2{p} = [At{p}, sparse(n,1), -sparse(C{p})]; \n         exist_ublk = 1; \n      end\n   end\n%%\n%% 3 additional inequality constraints in dual problem.\n%%\n   alp = max(1,sqrt(sum(abs(aa)))); \n   numblk = size(blk,1); \n   blk2{numblk+1,1} = 'l'; blk2{numblk+1,2} = 3; \n   C2{numblk+1,1}  = [1; alp; 0]; \n   At2{numblk+1,1} = [-aa,        0,   cc; \n\t\t     zeros(1,m),  0,   alp;\n\t\t     zeros(1,m), alp, -alp];\n%%\n%% Solve SDP\n%%\n   OPTIONS.gaptol = 1e-10;\n   [obj,X,y,Z,info] = HSDsqlp(blk2,At2,C2,b2,OPTIONS); \n   gd = 1/abs(obj(2));\n   err = max([info.gap/(1+mean(abs(obj))), info.pinfeas, info.dinfeas]);\n   if (OPTIONS.printlevel)\n      fprintf('\\n ******** gd = %3.1e, err = %3.1e\\n',gd,err); \n      if (err > 1e-6);\n         fprintf('\\n----------------------------------------------------')\n         fprintf('\\n gd problem is not solved to sufficient accuracy');\n         fprintf('\\n----------------------------------------------------\\n')\n      end\n   end\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/Solver/Oldmfiles/gdcompold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5622310988404657}}
{"text": "function [gK_uf, gK_ff] = gpsimCandidateCovGrads(model, M)\n\n% GPSIMCANDIDATECOVGRADS Sparse objective function gradients wrt Covariance function.\n% FORMAT\n% DESC gives the gradients of the log likelihood with respect to the\n% components of the posterior covariance.\n% ARG model : the model for which the gradients are to be computed.\n% ARG M : The training data for which the computation is to be made\n% RETURN gK_uf : the gradient of the likelihood with respect to the\n% elements of K_uf.\n% RETURN gK_ff : the gradient of the likelihood with respect to K_ff\n% \n% COPYRIGHT : Neil D. Lawrence, 2007\n%\n% SEEALSO : gpsimCreate, gpsimAddCandidate, gpsimCandidateLogLikeGradient\n\n% SHEFFIELDML\n%E = model.candidate.K_uf*M;\nE = model.candidate.K_uf*model.candidate.invK*M;\nEET = E*E';\nAinvE = model.candidate.Ainv*E;\n%AinvEET = model.candidate.Ainv*EET;\ndiagK_fuAinvEMT = sum(model.candidate.K_uf.*(model.candidate.Ainv*E*M'), 1)';\nK_fuAinvEMT = model.candidate.K_uf'*model.candidate.Ainv*E*M';\nAinvEETAinv = AinvE*AinvE';\nK_ufdAinvplusAinvEETAinvK_fu = model.candidate.K_uf'*(model.candidate.Ainv ...\n                                                  + AinvEETAinv)*model.candidate.K_uf;\ninvK_uuK_uf = model.invK*model.candidate.K_uf;\ninvK_uuK_ufDinv = invK_uuK_uf*model.candidate.invK;\nMMT = M*M';\nQ = -model.candidate.K + MMT ...\n    + K_ufdAinvplusAinvEETAinvK_fu...\n    -K_fuAinvEMT - K_fuAinvEMT';\n%gK_uu = 0.5*((model.invK ...\n%              -model.candidate.Ainv) - AinvEETAinv ...\n%             + invK_uuK_ufDinv*Q*invK_uuK_ufDinv');\ngK_uf = -invK_uuK_ufDinv*Q*model.candidate.invK ...      \n        -model.candidate.Ainv*model.candidate.K_uf*model.candidate.invK ...\n        -AinvEETAinv*model.candidate.K_uf*model.candidate.invK ...\n        +model.candidate.Ainv*E*M'*model.candidate.invK;\ngK_ff = 0.5*model.candidate.invK*Q*model.candidate.invK;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gpsim/gpsimCandidateCovGrads.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5621430978710851}}
{"text": "function p = JDDLDR_UP3(X,pi,ZA,ZB,D,C,gamma1,gamma2,MaxIteration_num)\n% X: original training data\n\nbeta = 0.001;\nA  = [];\nfor ci = 1:size(C,2)\n    A = [A D(ci).M*C(ci).M];\nend\n  \nS = gamma1*ZA*ZA'+gamma2*ZB*ZB';\n% S = gamma1*ZA*ZA';\np = pi;\nnumcomps = size(p,2);\n\niter_num_sub= 1;\nphi1 = X*X';\nphi2 = 2*X*A';\n  \nwhile iter_num_sub<MaxIteration_num % subject iteration for updating p, iteration ends when the contiguous function get close enough or reach teh max_iteration\n    phi = (X-p*A)*(X-p*A)';\n%     phi = eye(size(phi));\n    [U,V] = eig(phi-S); p1 = U(:,1:numcomps);\n      sum(sum(abs(p+beta*(p1-p) - p)));\n      p = p+beta*(p1-p);\n%     p = p1;\n%     clear U V W phi\n    iter_num_sub=iter_num_sub+1;\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/JDDLDR_PR/utilities/JDDLDR_UP3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5621430959559008}}
{"text": "% correlate frames with each other\n% sort frames by correlations \n% take mean image as mean over most correlated frames\n\nfunction mimg = pick_reg_init(data)\n%%\ndd = bsxfun(@minus, data, mean(mean(data,1),2));\n\n% WHITENING???\n% for i = 1:size(data,3)\n%    d0 = dd(:,:,i); \n%    fd0 = fft2(d0);\n%    dd(:,:,i) = real(ifft2(fd0./abs(fd0)));\n% end\n\ndd = reshape(dd, [], size(dd,ndims(dd)));\n\nCC = dd'*dd;\nCC = CC./(diag(CC) * diag(CC)').^.5;\n\n% CC = corrcoef(dd);\n\n[CCsort, isort] = sort(CC, 2, 'descend');\nnc = size(CCsort,2);\nbestCC = mean(CCsort(:, 1:min(nc,20)), 2);\n[~, imax] = max(bestCC);\n\nmimg = mean(data(:,:,isort(imax, 1:min(nc,20))), 3);\nend\n", "meta": {"author": "cortex-lab", "repo": "Suite2P", "sha": "c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5", "save_path": "github-repos/MATLAB/cortex-lab-Suite2P", "path": "github-repos/MATLAB/cortex-lab-Suite2P/Suite2P-c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5/preRegistration/pick_reg_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5621337287784801}}
{"text": "function yFiltM = applyRecursGaussFilter(xM,coeffS,dim)\n% function yFiltM = applyRecursGaussFilter(xM,coeffS,dim)\n%\n% This function applies recursive filter of order 4 to xM along the passed dim.\n% coeffS is struture with filter coefficients. \n% For example for LoG filter:\n%     scan3M: 3D scanArray (for example, planC{indexS.scan}.scanArray - ctOffset).\n%     pixelSizeV = [1,1,3]; % voxel size\n%     sigmaVal = 3; % sigma\n%     dim = 1; % filter along rows\n%     derivativeOrder = 'zero';\n%     coeffS.sigmad = sigmaVal / pixelSizeV(dim);\n%     coeffS = setGaussOrder(coeffS,derivativeOrder);\n%     filt3M = applyRecursGaussFilter(scan3M,coeffS,dim);\n%\n% APA, 6/12/2018\n\nykPlusM = zeros(size(xM));\nykMinusM = zeros(size(xM));\n\nswitch dim\n    case 1\n        \n        % Causal\n        ykPlusM(1,:,:) = coeffS.N0 * xM(1,:,:) + coeffS.N1 * xM(1,:,:) + coeffS.N2 * xM(1,:,:)...\n            + coeffS.N3 * xM(1,:,:);\n        ykPlusM(2,:,:) = coeffS.N0 * xM(2,:,:) + coeffS.N1 * xM(1,:,:) + coeffS.N2 * xM(1,:,:)...\n            + coeffS.N3 * xM(1,:,:);\n        ykPlusM(3,:,:) = coeffS.N0 * xM(3,:,:) + coeffS.N1 * xM(2,:,:) + coeffS.N2 * xM(1,:,:)...\n            + coeffS.N3 * xM(1,:,:);\n        ykPlusM(4,:,:) = coeffS.N0 * xM(4,:,:) + coeffS.N1 * xM(3,:,:) + coeffS.N2 * xM(2,:,:)...\n            + coeffS.N3 * xM(1,:,:);\n        \n        ykPlusM(1,:,:) = ykPlusM(1,:,:) - coeffS.BN1 * xM(1,:,:) - coeffS.BN2 * xM(1,:,:) - coeffS.BN3 * xM(1,:,:)...\n            - coeffS.BN4 * xM(1,:,:);\n        ykPlusM(2,:,:) = ykPlusM(2,:,:) + -coeffS.D1 * ykPlusM(1,:,:) - coeffS.BN2 * xM(1,:,:) - coeffS.BN3 * xM(1,:,:)...\n            - coeffS.BN4 * xM(1,:,:);\n        ykPlusM(3,:,:) = ykPlusM(3,:,:)  + -coeffS.D1 * ykPlusM(1,:,:) -+ coeffS.D2 * ykPlusM(2,:,:) - coeffS.BN3 * xM(1,:,:)...\n            - coeffS.BN4 * xM(1,:,:);\n        ykPlusM(4,:,:) = ykPlusM(4,:,:) + -coeffS.D1 * ykPlusM(1,:,:) -+ coeffS.D2 * ykPlusM(2,:,:) -+ coeffS.D3 * ykPlusM(3,:,:)...\n            - coeffS.BN4 * xM(1,:,:);\n        \n        for ind = 5:size(xM,dim)\n            ykPlusM(ind,:,:) = coeffS.N0 * xM(ind,:,:) + coeffS.N1 * xM(ind-1,:,:) + coeffS.N2 * xM(ind-2,:,:)...\n                + coeffS.N3 * xM(ind-3,:,:) -+ coeffS.D1 * ykPlusM(ind-1,:,:) -+ coeffS.D2 * ykPlusM(ind-2,:,:) ...\n                -+ coeffS.D3 * ykPlusM(ind-3,:,:) -+ coeffS.D4 * ykPlusM(ind-4,:,:);\n        end\n        \n        % Anticausal\n        ykMinusM(end,:,:) = coeffS.M1 * xM(end,:,:) + coeffS.M2 * xM(end,:,:) + coeffS.M3 * xM(end,:,:)...\n            + coeffS.M4 * xM(end,:,:);\n        ykMinusM(end-1,:,:) = coeffS.M1 * xM(end,:,:) + coeffS.M2 * xM(end,:,:) + coeffS.M3 * xM(end,:,:)...\n            + coeffS.M4 * xM(end,:,:);\n        ykMinusM(end-2,:,:) = coeffS.M1 * xM(end-1,:,:) + coeffS.M2 * xM(end-1,:,:) + coeffS.M3 * xM(end,:,:)...\n            + coeffS.M4 * xM(end,:,:);\n        ykMinusM(end-3,:,:) = coeffS.M1 * xM(end-2,:,:) + coeffS.M2 * xM(end-2,:,:) + coeffS.M3 * xM(end-1,:,:)...\n            + coeffS.M4 * xM(end,:,:);\n        \n        ykMinusM(end,:,:) = ykMinusM(end,:,:) - coeffS.BM1 * xM(end,:,:) - coeffS.BM2 * xM(end,:,:) - coeffS.BM3 * xM(end,:,:)...\n            - coeffS.BM4 * xM(end,:,:);\n        ykMinusM(end-1,:,:) = ykMinusM(end-1,:,:) + -coeffS.D1 * ykMinusM(end,:,:) - coeffS.BM2 * xM(end,:,:) - coeffS.BM3 * xM(end,:,:)...\n            - coeffS.BM4 * xM(end,:,:);\n        ykMinusM(end-2,:,:) = ykMinusM(end-2,:,:) + -coeffS.D1 * ykMinusM(end-1,:,:) +- coeffS.D2 * ykMinusM(end,:,:) - coeffS.BM3 * xM(end,:,:)...\n            - coeffS.BM4 * xM(end,:,:);\n        ykMinusM(end-3,:,:) = ykMinusM(end-3,:,:) + -coeffS.D1 * ykMinusM(end-2,:,:) +- coeffS.D2 * ykMinusM(end-1,:,:) +- coeffS.D3 * ykMinusM(end,:,:)...\n            - coeffS.BM4 * xM(end,:,:);\n        \n        for ind = size(xM,1)-4:-1:1\n            ykMinusM(ind,:,:) = coeffS.M1 * xM(ind+1,:,:) + coeffS.M2 * xM(ind+2,:,:) + coeffS.M3 * xM(ind+3,:,:)...\n                + coeffS.M4 * xM(ind+4,:,:) - coeffS.D1 * ykMinusM(ind+1,:,:) - coeffS.D2 * ykMinusM(ind+2,:,:) ...\n                - coeffS.D3 * ykMinusM(ind+3,:,:) - coeffS.D4 * ykMinusM(ind+4,:,:);\n        end\n        \n    case 2\n\n        % Causal\n        ykPlusM(:,1,:) = coeffS.N0 * xM(:,1,:) + coeffS.N1 * xM(:,1,:) + coeffS.N2 * xM(:,1,:)...\n            + coeffS.N3 * xM(:,1,:);\n        ykPlusM(:,2,:) = coeffS.N0 * xM(:,2,:) + coeffS.N1 * xM(:,1,:) + coeffS.N2 * xM(:,1,:)...\n            + coeffS.N3 * xM(:,1,:);\n        ykPlusM(:,3,:) = coeffS.N0 * xM(:,3,:) + coeffS.N1 * xM(:,2,:) + coeffS.N2 * xM(:,1,:)...\n            + coeffS.N3 * xM(:,1,:);\n        ykPlusM(:,4,:) = coeffS.N0 * xM(:,4,:) + coeffS.N1 * xM(:,3,:) + coeffS.N2 * xM(:,2,:)...\n            + coeffS.N3 * xM(:,1,:);\n        \n        ykPlusM(:,1,:) = ykPlusM(:,1,:) - coeffS.BN1 * xM(:,1,:) - coeffS.BN2 * xM(:,1,:) - coeffS.BN3 * xM(:,1,:)...\n            - coeffS.BN4 * xM(:,1,:);\n        ykPlusM(:,2,:) = ykPlusM(:,2,:) + -coeffS.D1 * ykPlusM(:,1,:) - coeffS.BN2 * xM(:,1,:) - coeffS.BN3 * xM(:,1,:)...\n            - coeffS.BN4 * xM(:,1,:);\n        ykPlusM(:,3,:) = ykPlusM(:,3,:) + -coeffS.D1 * ykPlusM(:,2,:) -+ coeffS.D2 * ykPlusM(:,1,:) - coeffS.BN3 * xM(:,1,:)...\n            - coeffS.BN4 * xM(:,1,:);\n        ykPlusM(:,4,:) = ykPlusM(:,4,:) + -coeffS.D1 * ykPlusM(:,3,:) -+ coeffS.D2 * ykPlusM(:,2,:) -+ coeffS.D3 * ykPlusM(:,1,:)...\n            - coeffS.BN4 * xM(:,1,:);\n        \n        for ind = 5:size(xM,dim)\n            ykPlusM(:,ind,:) = coeffS.N0 * xM(:,ind,:) + coeffS.N1 * xM(:,ind-1,:) + coeffS.N2 * xM(:,ind-2,:)...\n                + coeffS.N3 * xM(:,ind-3,:) -+ coeffS.D1 * ykPlusM(:,ind-1,:) -+ coeffS.D2 * ykPlusM(:,ind-2,:) ...\n                -+ coeffS.D3 * ykPlusM(:,ind-3,:) -+ coeffS.D4 * ykPlusM(:,ind-4,:);\n        end\n        \n        % Anticausal\n        ykMinusM(:,end,:) = coeffS.M1 * xM(:,end,:) + coeffS.M2 * xM(:,end,:) + coeffS.M3 * xM(:,end,:)...\n            + coeffS.M4 * xM(:,end,:);\n        ykMinusM(:,end-1,:) = coeffS.M1 * xM(:,end,:) + coeffS.M2 * xM(:,end,:) + coeffS.M3 * xM(:,end,:)...\n            + coeffS.M4 * xM(:,end,:);\n        ykMinusM(:,end-2,:) = coeffS.M1 * xM(:,end-1,:) + coeffS.M2 * xM(:,end-1,:) + coeffS.M3 * xM(:,end,:)...\n            + coeffS.M4 * xM(:,end,:);\n        ykMinusM(:,end-3,:) = coeffS.M1 * xM(:,end-2,:) + coeffS.M2 * xM(:,end-2,:) + coeffS.M3 * xM(:,end-1,:)...\n            + coeffS.M4 * xM(:,end,:);\n        \n        ykMinusM(:,end,:) = ykMinusM(:,end,:) - coeffS.BM1 * xM(:,end,:) - coeffS.BM2 * xM(:,end,:) - coeffS.BM3 * xM(:,end,:)...\n            - coeffS.BM4 * xM(:,end,:);\n        ykMinusM(:,end-1,:) = ykMinusM(:,end-1,:) + -coeffS.D1 * ykMinusM(:,end,:) - coeffS.BM2 * xM(:,end,:) - coeffS.BM3 * xM(:,end,:)...\n            - coeffS.BM4 * xM(:,end,:);\n        ykMinusM(:,end-2,:) = ykMinusM(:,end-2,:) + -coeffS.D1 * ykMinusM(:,end-1,:) +- coeffS.D2 * ykMinusM(:,end,:) - coeffS.BM3 * xM(:,end,:)...\n            - coeffS.BM4 * xM(:,end,:);\n        ykMinusM(:,end-3,:) = ykMinusM(:,end-3,:) + -coeffS.D1 * ykMinusM(:,end-2,:) +- coeffS.D2 * ykMinusM(:,end-1,:) +- coeffS.D3 * ykMinusM(:,end,:)...\n            - coeffS.BM4 * xM(:,end,:);\n        \n        for ind = size(xM,dim)-4:-1:1\n            ykMinusM(:,ind,:) = coeffS.M1 * xM(:,ind+1,:) + coeffS.M2 * xM(:,ind+2,:) + coeffS.M3 * xM(:,ind+3,:)...\n                + coeffS.M4 * xM(:,ind+4,:) - coeffS.D1 * ykMinusM(:,ind+1,:) - coeffS.D2 * ykMinusM(:,ind+2,:) ...\n                - coeffS.D3 * ykMinusM(:,ind+3,:) - coeffS.D4 * ykMinusM(:,ind+4,:);\n        end\n\n        \n    case 3\n        \n        % Causal\n        ykPlusM(:,:,1) = coeffS.N0 * xM(:,:,1) + coeffS.N1 * xM(:,:,1) + coeffS.N2 * xM(:,:,1)...\n            + coeffS.N3 * xM(:,:,1);\n        ykPlusM(:,:,2) = coeffS.N0 * xM(:,:,2) + coeffS.N1 * xM(:,:,1) + coeffS.N2 * xM(:,:,1)...\n            + coeffS.N3 * xM(:,:,1);\n        ykPlusM(:,:,3) = coeffS.N0 * xM(:,:,3) + coeffS.N1 * xM(:,:,2) + coeffS.N2 * xM(:,:,1)...\n            + coeffS.N3 * xM(:,:,1);\n        ykPlusM(:,:,4) = coeffS.N0 * xM(:,:,4) + coeffS.N1 * xM(:,:,3) + coeffS.N2 * xM(:,:,2)...\n            + coeffS.N3 * xM(:,:,1);\n        \n        ykPlusM(:,:,1) = ykPlusM(:,:,1) - coeffS.BN1 * xM(:,:,1) - coeffS.BN2 * xM(:,:,1) - coeffS.BN3 * xM(:,:,1)...\n            - coeffS.BN4 * xM(:,:,1);\n        ykPlusM(:,:,2) = ykPlusM(:,:,2) + -coeffS.D1 * ykPlusM(:,:,1) - coeffS.BN2 * xM(:,:,1) - coeffS.BN3 * xM(:,:,1)...\n            - coeffS.BN4 * xM(:,:,1);\n        ykPlusM(:,:,3) = ykPlusM(:,:,3) + -coeffS.D1 * ykPlusM(:,:,1) -+ coeffS.D2 * ykPlusM(:,:,2) - coeffS.BN3 * xM(:,:,1)...\n            - coeffS.BN4 * xM(:,:,1);\n        ykPlusM(:,:,4) = ykPlusM(:,:,4) + -coeffS.D1 * ykPlusM(:,:,1) -+ coeffS.D2 * ykPlusM(:,:,2) -+ coeffS.D3 * ykPlusM(:,:,3)...\n            - coeffS.BN4 * xM(:,:,1);\n        \n        for ind = 5:size(xM,dim)\n            ykPlusM(:,:,ind) = coeffS.N0 * xM(:,:,ind) + coeffS.N1 * xM(:,:,ind-1) + coeffS.N2 * xM(:,:,ind-2)...\n                + coeffS.N3 * xM(:,:,ind-3) -+ coeffS.D1 * ykPlusM(:,:,ind-1) -+ coeffS.D2 * ykPlusM(:,:,ind-2) ...\n                -+ coeffS.D3 * ykPlusM(:,:,ind-3) -+ coeffS.D4 * ykPlusM(:,:,ind-4);\n        end\n        \n        % Anticausal\n        ykMinusM(:,:,end) = coeffS.M1 * xM(:,:,end) + coeffS.M2 * xM(:,:,end) + coeffS.M3 * xM(:,:,end)...\n            + coeffS.M4 * xM(:,:,end);\n        ykMinusM(:,:,end-1) = coeffS.M1 * xM(:,:,end) + coeffS.M2 * xM(:,:,end) + coeffS.M3 * xM(:,:,end)...\n            + coeffS.M4 * xM(:,:,end);\n        ykMinusM(:,:,end-2) = coeffS.M1 * xM(:,:,end-1) + coeffS.M2 * xM(:,:,end-1) + coeffS.M3 * xM(:,:,end)...\n            + coeffS.M4 * xM(:,:,end);\n        ykMinusM(:,:,end-3) = coeffS.M1 * xM(:,:,end-2) + coeffS.M2 * xM(:,:,end-2) + coeffS.M3 * xM(:,:,end-1)...\n            + coeffS.M4 * xM(:,:,end);\n        \n        ykMinusM(:,:,end) = ykMinusM(:,:,end) - coeffS.BM1 * xM(:,:,end) - coeffS.BM2 * xM(:,:,end) - coeffS.BM3 * xM(:,:,end)...\n            - coeffS.BM4 * xM(:,:,end);\n        ykMinusM(:,:,end-1) = ykMinusM(:,:,end-1) + -coeffS.D1 * ykMinusM(:,:,end) - coeffS.BM2 * xM(:,:,end) - coeffS.BM3 * xM(:,:,end)...\n            - coeffS.BM4 * xM(:,:,end);\n        ykMinusM(:,:,end-2) = ykMinusM(:,:,end-2) + -coeffS.D1 * ykMinusM(:,:,end-1) +- coeffS.D2 * ykMinusM(:,:,end) - coeffS.BM3 * xM(:,:,end)...\n            - coeffS.BM4 * xM(:,:,end);\n        ykMinusM(:,:,end-3) = ykMinusM(:,:,end-3) + -coeffS.D1 * ykMinusM(:,:,end-2) +- coeffS.D2 * ykMinusM(:,:,end-1) +- coeffS.D3 * ykMinusM(:,:,end)...\n            - coeffS.BM4 * xM(:,:,end);\n        \n        for ind = size(xM,dim)-4:-1:1\n            ykMinusM(:,:,ind) = coeffS.M1 * xM(:,:,ind+1) + coeffS.M2 * xM(:,:,ind+2) + coeffS.M3 * xM(:,:,ind+3)...\n                + coeffS.M4 * xM(:,:,ind+4) - coeffS.D1 * ykMinusM(:,:,ind+1) - coeffS.D2 * ykMinusM(:,:,ind+2) ...\n                - coeffS.D3 * ykMinusM(:,:,ind+3) - coeffS.D4 * ykMinusM(:,:,ind+4);\n        end\n        \n\n\nend\n\n\nyFiltM = ykPlusM + ykMinusM;\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/recursiveFilters/applyRecursGaussFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5621337148190044}}
{"text": "function X = sigm(P)\n    X = 1./(1+exp(-P));\nend", "meta": {"author": "rasmusbergpalm", "repo": "DeepLearnToolbox", "sha": "5df2801f2196a2afddb7a87f800e63e153c34995", "save_path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox", "path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox/DeepLearnToolbox-5df2801f2196a2afddb7a87f800e63e153c34995/util/sigm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5619880803451744}}
{"text": "function Dist = bst_surfdist(Points, Vertices, Faces)\n% BST_SURFDIST: Compute the distances between points and a surface.\n%\n% USAGE:  Dist = bst_surfdist(Points, Vertices, Faces)\n%\n% DESCRIPTION:\n%     Exact distance computation, which checks all 3 sets of distances: points\n%     to vertices, points to edges, and points to faces, keeping the smallest\n%     for each point.\n%\n% INPUTS:\n%    - Points   : [Qx3] double matrix, points to compare to the mesh defined by Vertices/Faces\n%    - Vertices : [Mx3] double matrix\n%    - Faces    : [Nx3] double matrix\n%\n% OUTPUTS:\n%    - Dist     : [Qx1] final distance between points and mesh\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: Marc Lalancette, 2022\n\n% TODO: A bit slow, look for alternatives\n% This seems similar: https://www.mathworks.com/matlabcentral/fileexchange/52882-point2trimesh-distance-between-point-and-triangulated-surface\nEpsilon = 1e-9; % nanometer\nnP = size(Points, 1);\nnF = size(Faces, 1);\n\n% Prepare surface quantities, independent of points\n% (In bst_meshfit, this can be done only once before iterative fitting.)\n% Edges as indices\nEdges = unique(sort([Faces(:,[1,2]); Faces(:,[2,3]); Faces(:,[3,1])], 2), 'rows');\n% Edge direction \"doubly normalized\" so that later projection should be between 0 and 1.\nEdgeDir = Vertices(Edges(:,2),:) - Vertices(Edges(:,1),:);\nEdgeL = sqrt(sum(EdgeDir.^2, 2));\nEdgeDir = bsxfun(@rdivide, EdgeDir, EdgeL);\n% Edges as vectors\nEdgesV = zeros(nF, 3, 3);\nEdgesV(:,:,1) = Vertices(Faces(:,2),:) - Vertices(Faces(:,1),:);\nEdgesV(:,:,2) = Vertices(Faces(:,3),:) - Vertices(Faces(:,2),:);\nEdgesV(:,:,3) = Vertices(Faces(:,1),:) - Vertices(Faces(:,3),:);\n% First edge to second edge: counter clockwise = up\nFaceNormals = cross(EdgesV(:,:,1), EdgesV(:,:,2));\n%FaceArea = sqrt(sum(FaceNormals.^2, 2));\nFaceNormals = bsxfun(@rdivide, FaceNormals, sqrt(sum(FaceNormals.^2, 2)));\n% Perpendicular vectors to edges, pointing inside triangular face.\nfor e = 3:-1:1\n    EdgeTriNormals(:,:,e) = cross(FaceNormals, EdgesV(:,:,e));\nend\nFaceVertices = zeros(nF, 3, 3);\nFaceVertices(:,:,1) = Vertices(Faces(:,1),:);\nFaceVertices(:,:,2) = Vertices(Faces(:,2),:);\nFaceVertices(:,:,3) = Vertices(Faces(:,3),:);\n\n\n% Check distance to vertices\nif license('test','statistics_toolbox')\n    DistVert = pdist2(Vertices, Points, 'euclidean', 'Smallest', 1)';\nelse\n    DistVert = zeros(nP, 1);\n    for iP = 1:nP\n        % Find closest surface vertex.\n        DistVert(iP) = sqrt(min(sum(bsxfun(@minus, Points(iP, :), Vertices).^2, 2)));\n    end\nend\n% Check distance to faces\nDistFace = inf(nP, 1);\nfor iP = 1:nP\n    % Considered M\u00f6ller and Trumbore 1997, Ray-Triangle Intersection (https://stackoverflow.com/questions/42740765/intersection-between-line-and-triangle-in-3d), but this is simpler still.\n    % Vectors from triangle vertices to point.\n    Pyramid = bsxfun(@minus, Points(iP, :), FaceVertices);\n    % Does the point project inside each face?\n    InFace = all(sum(Pyramid .* EdgeTriNormals, 2) > -Epsilon, 3);\n    if any(InFace)\n        DistFace(iP) = min(abs(sum(Pyramid(InFace,:,1) .* FaceNormals(InFace,:), 2)));\n    end\nend\n% Check distance to edges\nDistEdge = inf(nP, 1);\nfor iP = 1:nP\n    % Vector from first edge vertex to point.\n    Pyramid = bsxfun(@minus, Points(iP, :), Vertices(Edges(:, 1), :));\n    Projection = sum(Pyramid .* EdgeDir, 2);\n    InEdge = Projection > -Epsilon & Projection < (EdgeL + Epsilon);\n    if any(InEdge)\n        DistEdge(iP) = sqrt(min(sum((Pyramid(InEdge,:) - bsxfun(@times, Projection(InEdge), EdgeDir(InEdge,:))).^2, 2)));\n    end\nend\n\nDist = min([DistVert, DistEdge, DistFace], [], 2);\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/toolbox/math/bst_surfdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.561988074841736}}
{"text": "function pass = test_abs( ) \n% Test abs in SPHEREFUN \n\ntol = 1000*chebfunpref().cheb2Prefs.chebfun2eps;\n\nf = spherefun(@(x,y,z) -(x.^2 + y.^2 + z.^2));\npass(1) = norm(abs(f) + f, inf) < tol;\n\nend ", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/spherefun/test_abs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5619443462737024}}
{"text": "function varargout = implies(varargin)\n%IMPLIES Logical implication\n%\n% IMPLIES(X,Y) creates a mixed integer representation of\n% the constraint X --> Y, i.e. Y is true if X is true.\n%\n% Syntax\n%   F = implies(X,Y,tol)\n%\n% Input\n%   X : binary SDPVAR variable or a constraint\n%   Y : binary SDPVAR variable or a constraint\n%  tol: Optional threshhold for defining zero (see NOTE)\n%\n% Output\n%   F : SET object\n%\n% Examples\n%\n%  binvar X Y; F = implies(X,Y);\n%  binvar X;sdpvar Y; F = [implies(X,Y>=5), -10 <= Y <= 100];\n%  binvar X;Y=sdpvar(3,1); F = [implies(X,[sum(Y);Y(2)]>=[5;0]), -1<= Y <= 10];\n%\n% Note\n%\n%  All variables in the expressions have to be explicitly bounded somewhere\n%  in the model (implicit constraints are not sufficients such as [Y <= Z,...,Z<= 10]\n%\n%  Using implies with X non-binary is highly sensitive numerically.\n%  The problem comes from the definition of 0 in a floating-point\n%  environment, and precision in the solver. To account for this,\n%  the user can supply a third argument to define a dead-zone around\n%  zero, i.e Implies(X<=0,Y) will be replaced with IMPLIES(X<=-tol,Y)\n%  Note, you typically need to tweak this number for your\n%  application/solver. By default, YALMIP uses tol = 0, which means you\n%  easily can get garbage... A positive number means YALMIP is cautious in\n%  terms of activating the condition, while a negative number means YALMIP\n%  will be aggressive  in activating the condition. \n%\n%   See also @SDPVAR/AND, @SDPVAR/OR, IFF\n\n% There are some cases to take care of...\n%\n% X --> Y     binary/binary :                     Implemented\n% X --> Y     binary/(LP,equality,sdp)            Implemented\n% X --> Y     (LP,equality,sdp)/binary            Not implemented\n% X --> Y     (LP,equality,sdp)/(LP,equality,sdp) Not implemented\n\nX = varargin{1};\nY = varargin{2};\n\nif isempty(X)\n    varargout{1} = [];\nend\n\nswitch class(X)\n\n    case {'sdpvar','constraint','lmi'}      \n   \n        if nargin > 2\n            if ~isa(varargin{3},'double')\n                error('Third argument in IMPLIES should be a numerical value (tolerance)');\n            end\n        end\n        varargout{1} = setupMeta(lmi([]), mfilename,varargin{:});\n        \n    case 'char'        \n        varargout{1} = implies_internal(varargin{3:end});\n        \n    case 'logical'\n        if length(X)==1\n            if X\n                varargout{1} = Y;\n            else\n                varargout{1} = [];\n            end\n        else\n            if length(X) == length(Y)\n                i = find(X);\n                if isempty(i)\n                    varargout{1} = [];\n                else\n                    varargout{1} = Y(i);\n                end\n            else\n                error('Size mismatch in input arguments');\n            end\n        end\nend\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/implies.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5619443452882841}}
{"text": "function test_failed=test_idft\nLr=[1, 19, 20];\n\n\ntest_failed=0;\n\ndisp(' ===============  TEST_IDFT ==============');\n\nfor jj=1:length(Lr)\n  L=Lr(jj);\n    for n = 1:2\n    \n    if (n==1)\n       type = 'complex';\n       c=tester_crand(L,1);\n    elseif (n==2)\n       type = 'real';\n       c=tester_rand(L,1);      \n    end\n    \n    f1=idft(c);\n    f2=ref_idft(c);\n    \n    res=norm(f1-f2);\n    [test_failed,fail]=ltfatdiditfail(res,test_failed);        \n    s=sprintf('IDFT %6s  L:%3i %0.5g %s',type,L,res,fail);\n    disp(s);\n    end\n  end;\nend;\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/testing/test_idft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5619443225043456}}
{"text": "function [Population,FrontNo,CrowdDis] = EnvironmentalSelection(Population,N,Psi)\n% The environmental selection of NSGA-II-conflict\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    Selected = zeros(1,N);\n    FrontNo  = zeros(1,N);\n    CrowdDis = zeros(1,N);\n    PopObj   = Population.objs;\n    for i = 1 : length(Psi)\n        index = (i-1)*ceil(N/length(Psi))+1 : min(N,i*ceil(N/length(Psi)));\n        [Selected(index),FrontNo(index),CrowdDis(index)] = SubSelection(PopObj(:,Psi{i}),length(index));\n    end\n    Population = Population(Selected);\nend\n\nfunction [Next,FrontNo,CrowdDis] = SubSelection(PopObj,N)\n% Environmental selection based on only several objectives\n\n    %% Non-dominated sorting\n    [FrontNo,MaxFNo] = NDSort(PopObj,N);\n    Next = FrontNo < MaxFNo;\n    \n    %% Calculate the crowding distance of each solution\n    CrowdDis = CrowdingDistance(PopObj,FrontNo);\n    \n    %% Select the solutions in the last front based on their crowding distances\n    Last     = find(FrontNo==MaxFNo);\n    [~,Rank] = sort(CrowdDis(Last),'descend');\n    Next(Last(Rank(1:N-sum(Next)))) = true;\n    \n    %% Population for next generation\n    Next     = find(Next);\n    FrontNo  = FrontNo(Next);\n    CrowdDis = CrowdDis(Next);\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/NSGA-II-conflict/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5618831290208797}}
{"text": "function high_card_simulation_test02 ( )\n\n%*****************************************************************************80\n%\n%% HIGH_CARD_SIMULATION_TEST02 plots the results for a deck of 100 cards.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 March 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n  deck_size = 100;\n  trial_num = 1000;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'HIGH_CARD_SIMULATION_TEST02\\n' );\n  fprintf ( 1, '  Using %d cards and %d trials, compute the chances of\\n', deck_size, trial_num );\n  fprintf ( 1, '  picking the high card with a skip of 0 through 99.\\n' );\n\n  p = zeros ( deck_size, 1 );\n\n  for skip_num = 0 : deck_size - 1\n\n    p(skip_num+1) = high_card_simulation ( deck_size, skip_num, trial_num );\n\n  end\n\n  plot ( 0:deck_size-1, p, 'b', 'Linewidth', 2 )\n  grid on\n  title ( 'Estiamted chance of winning per given skip number' )\n  xlabel ( 'Number of cards to skip before choice' )\n  ylabel ( 'Chance of correct choice.' )\n\n  print ( '-dpng', 'high_card_simulation_test02.png' )\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Data plotted in \"high_card_simulation_test02.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/high_card_simulation/high_card_simulation_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5618831077142284}}
{"text": "function [ abd, rcond, info ] = cpbco ( abd, lda, n, m )\n\n%*****************************************************************************80\n%\n%% CPBCO factors a complex hermitian positive definite band matrix.\n%\n%  Discussion:\n%\n%    The routine also estimates the condition number of the matrix.\n%\n%    If RCOND is not needed, CPBFA is slightly faster.\n%\n%    To solve A*X = B, follow CPBCO by CPBSL.\n%\n%    To compute inverse(A)*C, follow CPBCO by CPBSL.\n%\n%    To compute determinant(A), follow CPBCO by CPBDI.\n%\n%  Band storage:\n%\n%    If A is a hermitian positive definite band matrix,\n%    the following program segment will set up the input.\n%\n%      m = (band width above diagonal)\n%      do j = 1, n\n%        i1 = max ( 1, j-m )\n%        do i = i1, j\n%          k = i-j+m+1\n%          abd(k,j) = a(i,j)\n%        end\n%      end\n%\n%    This uses M+1 rows of A, except for the M by M\n%    upper left triangle, which is ignored.\n%\n%  Example:\n%\n%    If the original matrix is\n%\n%      11 12 13  0  0  0\n%      12 22 23 24  0  0\n%      13 23 33 34 35  0\n%       0 24 34 44 45 46\n%       0  0 35 45 55 56\n%       0  0  0 46 56 66\n%\n%    then N = 6, M = 2 and ABD should contain\n%\n%       *  * 13 24 35 46\n%       * 12 23 34 45 56\n%      11 22 33 44 55 66\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 May 2007\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/output, complex ABD(LDA,N); on input, the matrix to be factored.\n%    The columns of the upper triangle are stored in the columns of ABD,\n%    and the diagonals of the upper triangle are stored in the rows of ABD.\n%\n%    Input, integer LDA, the leading dimension of ABD.\n%    LDA must be at least M+1.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Input, integer M, the number of diagonals above the main diagonal.\n%    0 <= M < N.\n%\n%    Output, complex ABD(LDA,N);an upper triangular matrix R, stored in band\n%    form, so that A = hermitian(R) * R.  If INFO ~= 0, the factorization \n%    is not complete.\n%\n%    Output, real RCOND, an estimate of the reciprocal condition of\n%    the matrix.  For the system A*X = B, relative perturbations in A and B\n%    of size EPSILON may cause relative perturbations in X of size\n%    (EPSILON/RCOND).  If RCOND is so small that the logical expression\n%      1.0 + RCOND == 1.0\n%    is true, then A may be singular to working precision.  In particular,\n%    RCOND is zero if exact singularity is detected or the estimate underflows.\n%\n%    Output, integer INFO.\n%    0, for normal return.\n%    K, signals an error condition.  The leading minor of order K is not\n%    positive definite.\n%\n%  Local parameters:\n%\n%    Local, complex Z(N), a work vector whose contents are usually\n%    unimportant.  If A is singular to working precision, then Z is\n%    an approximate null vector in the sense that\n%    norm ( A * Z ) = RCOND * norm ( A ) * norm ( Z ).\n%    If INFO ~= 0, Z is unchanged.\n%\n\n%\n%  Find the norm of A.\n%\n  for j = 1 : n\n\n    l = min ( j, m + 1 );\n    mu = max ( m + 2 - j, 1 );\n    z(j) = scasum ( l, abd(mu:mu+l-1,j), 1 );\n    k = j - l;\n\n    for i = mu : m\n      k = k + 1;\n      z(k) = real ( z(k) ) + cabs1 ( abd(i,j) );\n    end\n\n  end\n\n  anorm = 0.0;\n  for j = 1 : n\n    anorm = max ( anorm, real ( z(j) ) );\n  end\n%\n%  Factor.\n%\n  [ abd, info ] = cpbfa ( abd, lda, n, m );\n\n  if ( info ~= 0 )\n    return\n  end\n%\n%  RCOND = 1/(norm(A)*(estimate of norm(inverse(A)))).\n%\n%  Estimate = norm(Z)/norm(Y) where A*Z = Y and A*Y = E.\n%\n%  The components of E are chosen to cause maximum local\n%  growth in the elements of W where hermitian(R)*W = E.\n%\n%  The vectors are frequently rescaled to avoid overflow.\n%\n%  Solve hermitian(R)*W = E.\n%\n  ek = 1.0;\n  z(1:n) = 0.0;\n\n  for k = 1 : n\n\n    if ( cabs1 ( z(k) ) ~= 0.0 )\n      ek = csign1 ( ek, -z(k) );\n    end\n\n    if ( real ( abd(m+1,k) ) < cabs1 ( ek - z(k) ) )\n      s = real ( abd(m+1,k) ) / cabs1 ( ek - z(k) );\n      z(1:n) = z(1:n) * s;\n      ek = s * ek;\n    end\n\n    wk = ek - z(k);\n    wkm = - ek - z(k);\n    s = cabs1 ( wk );\n    sm = cabs1 ( wkm );\n    wk = wk / abd(m+1,k);\n    wkm = wkm / abd(m+1,k);\n    j2 = min ( k + m, n );\n    i = m + 1;\n\n    if ( k+1 <= j2 )\n\n      for j = k+1 : j2\n        i = i - 1;\n        sm = sm + cabs1 ( z(j) + wkm * conj ( abd(i,j) ) );\n        z(j) = z(j) + wk * conj ( abd(i,j) );\n        s = s + cabs1 ( z(j) );\n      end\n\n      if ( s < sm )\n        t = wkm - wk;\n        wk = wkm;\n        i = m + 1;\n        for j = k+1 : j2\n          i = i - 1;\n          z(j) = z(j) + t * conj ( abd(i,j) );\n        end\n      end\n\n    end\n\n    z(k) = wk;\n\n  end\n\n  s = 1.0 / scasum ( n, z, 1 );\n  z(1:n) = z(1:n) * s;\n%\n%  Solve R * Y = W.\n%\n  for k = n : -1 : 1\n\n    if ( real ( abd(m+1,k) ) < cabs1 ( z(k) ) )\n      s = real ( abd(m+1,k) ) / cabs1 ( z(k) );\n      z(1:n) = z(1:n) * s;\n    end\n\n    z(k) = z(k) / abd(m+1,k);\n    lm = min ( k - 1, m );\n    la = m + 1 - lm;\n    lb = k - lm;\n    t = -z(k);\n    z(lb:lb+lm-1) = z(lb:lb+lm-1) + t * transpose ( abd(la:la+lm-1,k) );\n\n  end\n\n  s = 1.0 / scasum ( n, z, 1 );\n  z(1:n) = z(1:n) * s;\n  ynorm = 1.0;\n%\n%  Solve hermitian(R)*V = Y.\n%\n  for k = 1 : n\n\n    lm = min ( k - 1, m );\n    la = m + 1 - lm;\n    lb = k - lm;\n    z(k) = z(k) - abd(la:la+lm-1,k)' * transpose ( z(lb:lb+lm-1) );\n\n    if ( real ( abd(m+1,k) ) < cabs1 ( z(k) ) )\n      s = real ( abd(m+1,k) ) / cabs1 ( z(k) );\n      z(1:n) = z(1:n) * s;\n      ynorm = s * ynorm;\n    end\n\n    z(k) = z(k) / abd(m+1,k);\n\n  end\n\n  s = 1.0 / scasum ( n, z, 1 );\n  z(1:n) = z(1:n) * s;\n  ynorm = s * ynorm;\n%\n%  Solve R * Z = W.\n%\n  for k = n : -1 : 1\n\n    if ( real ( abd(m+1,k) ) < cabs1 ( z(k) ) )\n      s = real ( abd(m+1,k) ) / cabs1 ( z(k) );\n      z(1:n) = z(1:n) * s;\n      ynorm = s * ynorm;\n    end\n\n    z(k) = z(k) / abd(m+1,k);\n    lm = min ( k - 1, m );\n    la = m + 1 - lm;\n    lb = k - lm;\n    t = -z(k);\n    z(lb:lb+lm-1) = z(lb:lb+lm-1) + t * transpose ( abd(la:la+lm-1,k) );\n\n  end\n%\n%  Make ZNORM = 1.\n%\n  s = 1.0 / scasum ( n, z, 1 );\n  z(1:n) = z(1:n) * s;\n  ynorm = s * ynorm;\n\n  if ( anorm ~= 0.0 )\n    rcond = ynorm / anorm;\n  else\n    rcond = 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/linpack_c/cpbco.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5618286123915345}}
{"text": "function tet_mesh_test006 ( )\n\n%*****************************************************************************80\n%\n%% TET_MESH_TEST006 tests TET_MESH_TET_NEIGHBORS.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    19 August 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  tet_order = 4;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TET_MESH_TEST006\\n' );\n  fprintf ( 1, '  TET_MESH_TET_NEIGHBORS computes the 4 neighboring\\n' );\n  fprintf ( 1, '  tetrahedrons of each tetrahedron in a tet mesh.\\n' );\n  fprintf ( 1, '  containing a point.\\n' );\n%\n%  Set up the example tetrahedron mesh.\n%\n  [ node_num, tet_num ] = tet_mesh_order4_example_size ( );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  This mesh has tetrahedron order %d\\n', tet_order );\n  fprintf ( 1, '  The number of tetrahedrons is   %d\\n', tet_num );\n\n  [ node_xyz, tet_node ] = tet_mesh_order4_example_set ( node_num, tet_num );\n%\n%  Print the tets.\n%\n  i4mat_transpose_print_some ( tet_order, tet_num, tet_node, ...\n    1, 1, tet_order, 10, '  First 10 Tets:' );\n%\n%  The TET_NEIGHBOR array is needed by TET_MESH_DELAUNAY_SEARCH.\n%\n  tet_neighbor = tet_mesh_neighbor_tets ( tet_order, tet_num, tet_node );\n\n  i4mat_transpose_print_some ( 4, tet_num, tet_neighbor, ...\n    1, 1, 4, 10, '  First 10 Tet Neighbors:' );\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/tet_mesh/tet_mesh_test006.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.5618285992670192}}
{"text": " function x = dtft_adj_arrayfun(X, omega, Nd, n_shift, usearrayfun)\n%function x = dtft_adj(X, omega, Nd, n_shift, usecellfun)\n%|\n%| Compute adjoint of d-dim DTFT for spectrum X at frequency locations omega\n%|\n%| in\n%|\tX\t[M L]\t\tdD DTFT values\n%|\tomega\t[M d]\t\tfrequency locations (radians)\n%|\tn_shift [d 1]\t\tuse [0:N-1]-n_shift (default [0 ... 0])\n%|\tusearrayfun\t\t\t1 to reduce memory use (slower)\n%| out\n%|\tx\t[(Nd) L]\tsignal values\n%|\n%| Requires enough memory to store M * (*Nd) size matrices. (For testing only.)\n%|\n%| Copyright 2003-4-13, Jeff Fessler, University of Michigan\n%| Revised 2013-3-22, Daniel Weller, University of Michigan\n\n% if no arguments, then run a simple test\nif nargin < 2\n\thelp(mfilename)\n\tNd = [4 6 5]; Nd = [50 20 10];\n\tn_shift = [2 1 3]; \n\tn_shift = 0*[2 1 3]; n_shift = [20 10 4];\n\t% test with uniform frequency locations:\n\to1 = 2*pi*[0:(Nd(1)-1)]'/Nd(1);\n\to2 = 2*pi*[0:(Nd(2)-1)]'/Nd(2);\n\to3 = 2*pi*[0:(Nd(3)-1)]'/Nd(3);\n\t[o1 o2 o3] = ndgrid(o1, o2, o3);\n\tX = o1 + o2 - o3; % test spectrum\n\tom = [o1(:) o2(:) o3(:)];\n\ttd = tic(); xd = dtft_adj(X(:), om, Nd, n_shift); td = toc(td);\n\ttl = tic(); xl = dtft_adj(X(:), om, Nd, n_shift, 1); tl = toc(tl);\n\tprintm('loop max %% difference = %g (te = %g/%g)', max_percent_diff(xl,xd), tl, td)\n\ttc = tic(); xc = dtft_adj_arrayfun(X(:), om, Nd, n_shift, 1); tc = toc(tc);\n\tprintm('arrayfun max %% difference = %g (te = %g/%g)', max_percent_diff(xc,xd), tc, td)\n\tXp = X .* reshape(exp(-1i * om * n_shift(:)), size(X));\n\txf = ifftn(Xp) * prod(Nd);\n\tprintm('ifft max %% difference = %g', max_percent_diff(xf,xd))\nreturn\nend\n\nif ~isvar('n_shift') || isempty(n_shift), n_shift = zeros(size(Nd)); end\nif ~isvar('usearrayfun') || isempty(usearrayfun), usearrayfun = 0; end\n\n% if length(Nd) == 1\n%\tnn{1} = [0:(Nd(1)-1)] - n_shift(1);\n% elseif length(Nd) == 2\n%\tnn{1} = [0:(Nd(1)-1)] - n_shift(1);\n%\tnn{2} = [0:(Nd(2)-1)] - n_shift(2);\n%\t[nn{1} nn{2}] = ndgrid(nn{1}, nn{2});\n% elseif length(Nd) == 3\n%\tnn{1} = [0:(Nd(1)-1)] - n_shift(1);\n%\tnn{2} = [0:(Nd(2)-1)] - n_shift(2);\n%\tnn{3} = [0:(Nd(3)-1)] - n_shift(3);\n%\t[nn{1} nn{2} nn{3}] = ndgrid(nn{1}, nn{2}, nn{3});\n% else\n%\t'only 1D-3D done'\n% end\ndd = size(omega,2);\nNd(end+1:dd) = 1;\nn_shift(end+1:dd) = 0;\n\nnn = cell(1,dd);\nfor id=1:dd % fixed: dd\n\tnn{id} = (0:(Nd(id)-1))-n_shift(id);\nend\n[nn{:}] = ndgrid(nn{:}); % fixed: dd\nnn = cellfun(@(x) col(x),nn,'UniformOutput',false);\nnn = cat(2,nn{:}); % [*Nd dd]\nomega = omega.'; % [dd M]\n\nif usearrayfun\n    x = arrayfun(@(n) exp(1i.*(nn(n,:)*omega)) * X,1:prod(Nd),'UniformOutput',false);\n    x = cat(1,x{:});\nelse\n    x = exp(1i.*(nn*omega)) * X;\nend\nx = reshape(x, [Nd ncol(X)]); % [Nd L]\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/archive/dtft_adj_arrayfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5618285909073867}}
{"text": "classdef SymmetricFourthOrder3DVoigtTensor <  AbstractTensor ...\n                                              & FourthOrderDescriptor ...\n                                              & VoigtRepresentation ...\n                                              & Elasticity3dDescriptor\n    \n                                          \n    methods (Access = public)\n        \n        function obj = SymmetricFourthOrder3DVoigtTensor()\n        end\n        \n        function createRandomTensor(obj)\n            obj.createRandomTensor@AbstractTensor();\n            obj.makeSymmetrization();\n        end\n    end\n    \n    methods (Access = protected)\n        \n        function makeSymmetrization(obj)\n            t = obj.getValue;\n            ts = 0.5*(t + t');\n            obj.setValue(ts);\n        end\n        \n        function loadTensorSize(obj)\n            obj.tensorSize = [6,6];\n        end\n    end\n    \nend\n\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Homogenization/Sources/Tensors/TensorSubClasses/SymmetricFourthOrder/SymmetricFourthOrder3DVoigtTensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5617478202231109}}
{"text": "function c = times(a,b)\n% implements e .* c and c .* e\n%\n% Description\n% If |e| is a matrix of embeddings and |c| is a matrix of coefficients \n% then |e .* c| is again a matrix of embeddings defined by\n% \n% $$ [\\mathrm{e .* c}]_{j\\ell} = mathrm{e}_{j\\ell} \\mathrm{c}_{j \\ell}$$\n%\n% Syntax\n%   out = e .* c\n%   out = c .* e\n%   out = e1 .* e2\n%\n% Input\n%  e, e1, e2 - @embedding\n%  c - double\n%\n% Output\n%  out- @embedding\n%\n\nif isa(a,'embedding')\n  \n  if isa(b,'embedding')\n\n    for i = 1:length(a.u), a.u{i} = a.u{i} .* b.u{i}; end\n    \n  else\n    for i = 1:length(a.u), a.u{i} = a.u{i} .* b; end\n  end\n  c = a;\n  \nelse\n  \n  for i = 1:length(b.u), b.u{i} = a .* b.u{i}; end\n  c = b;\n  \nend\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@embedding/times.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5617478117136957}}
{"text": "%  INTERNAL FUNCTION: generate candidates for optimization\n% \n%  ::\n% \n%    [x,f,viol,funevals]=generate_candidates(objective,lb,ub,n,...\n%        restrictions,penalty,varargin)\n% \n%  Args:\n%     - **objective** [function_handle]: objective to minimize\n%     - **lb** [vector]: lower bound of the search space\n%     - **ub** [vector]: upper bound of the search space\n%     - **n** [integer]: number of candidates to generate\n%     - **max_trials** [integer]: number of trials after which the procedure\n%       crashes\n%     - **restrictions** [empty|function_handle]: function evaluating the\n%       violations\n%     - **opt** [struct]: structure with fields\n% \n%       - **restrictions_in_objective** [true|false]:\n%       - **returns_retcode** [true|false]:\n%       - **restrictions_same_weights** [true|{false}]:\n%       - **allow_restrictions_violations** [true|{false}]:\n% \n%     - **penalty** [numeric]: value functions exceeding this value in\n%       absolute value are assigned this value\n%     - **varargin** []: additional input arguments for the objective function\n% \n%  Returns:\n%     :\n% \n%     - **x** [d x n matrix]: parameter vectors\n%     - **f** [row vector]: value function for each parameter vector\n%     - **viol** [row vector]: violation penalty for each parameter vector\n%     - **funevals** [integer]: number of function evaluations\n% \n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/m/+utils/+optim/generate_candidates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5617220716681337}}
{"text": "function cleanClass = cleanSingletonWhitePoints(class);\n%\n%Author:  RFD, BW\n%Date:\n%Purpose:\n%   Remove singleton white matter points from each plane\n%\n\n% Mask will find points that are singletons\nmask = -1*ones(3,3);\nmask(2,2) = 1;\n\n%\nim = class.data;\nimSize = size(im);\ncleanIm = im;\n\n%\n\nchanges = [];\nfor ii=1:imSize(1);\n    curSlice = squeeze(cleanIm(ii,:,:));\n    tst = conv2(curSlice,mask,'same');\n    changes = [changes, sum(sum(tst > 0))];\n    curSlice(tst > 0) = class.type.unknown;\n    cleanIm(ii,:,:) = curSlice;\nend\nchanges, sum(changes)\n\nchanges = [];\nfor ii=1:imSize(2);\n    curSlice = squeeze(cleanIm(:,ii,:));\n    tst = conv2(curSlice,mask,'same');\n    changes = [changes, sum(sum(tst > 0))];\n    curSlice(tst > 0) = class.type.unknown;\n    cleanIm(:,ii,:) = curSlice;\nend\nchanges, sum(changes)\n\nchanges = [];\nfor ii=1:imSize(3);\n    curSlice = squeeze(cleanIm(:,:,ii));\n    tst = conv2(curSlice,mask,'same');\n    changes = [changes, sum(sum(tst > 0))];\n    curSlice(tst > 0) = class.type.unknown;\n    cleanIm(:,:,ii) = curSlice;\nend\nchanges, sum(changes)\n\n% Assign results to returned structure\ncleanClass = class;\ncleanClass.data = cleanIm;\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/MrGray/topology/removeWhiteMatterSingletons.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5617220661370739}}
{"text": "classdef LogarithmNode < GraphNode\n    properties\n        const = 1e-2;\n    end\n    \n    methods\n        function obj = LogarithmNode(dimOut, const)\n            obj = obj@GraphNode('Logarithm',dimOut);\n            if nargin>=2\n                obj.const = const;\n            end\n        end\n        \n        function obj = forward(obj,prev_layers)\n            obj = obj.preprocessingForward(prev_layers);\n            input = prev_layers{1}.a;\n            [D,T,N] = size(input);\n            \n            if strcmpi(class(gather(input(1))), 'single')\n                obj.const = single(obj.const);\n            end\n            \n            if N==1\n                obj.a = log(input+obj.const);\n            else\n                if obj.variableLength\n                    input = obj.PadShortTrajectory(input, 0);\n                    if sum(input(:)+obj.const<=0)\n                        fprintf('error: input to log is negative');\n                    end\n                    obj.a = log(input+obj.const);\n                else\n                    obj.a = log(input+obj.const);\n                end\n            end\n            obj = forward@GraphNode(obj, prev_layers);\n        end\n        \n        function obj = backward(obj,prev_layers, future_layers)\n            future_grad = obj.GetFutureGrad(future_layers);\n            input = prev_layers{1}.a;\n            obj.grad{1} = 1./(input+obj.const).*future_grad;\n        end\n    end\nend", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/graph_obj/nodes/LogarithmNode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5617220661142289}}
{"text": "function mori = parents(mori)\n% variants of an orientation relationship\n%\n% Syntax\n%   \n%   ori_parents = ori_child * inv(mori.parents)\n%\n% Input\n%  mori - child to parent @orientation relationship\n%  ori_child - child orientation\n%\n% Output\n%  ori_parents - all possible parent @orientation\n%\n% Example\n%   % parent symmetry\n%   cs_fcc = crystalSymmetry('m-3m', [3.6599 3.6599 3.6599], 'mineral', 'Iron fcc');\n%\n%   % child symmetry\n%   cs_bcc = crystalSymmetry('m-3m', [2.866 2.866 2.866], 'mineral', 'Iron bcc')\n%\n%   % define a bcc child orientation\n%   ori_bcc = orientation.goss(cs_bcc)\n%\n%   % define Nishiyama Wassermann fcc to bcc orientation relation ship\n%   NW = orientation.NishiyamaWassermann (cs_fcc,cs_bcc)\n%\n%   % compute a fcc parent orientation related to the bcc child orientation\n%   ori_fcc = ori_bcc * NW\n%\n%   % compute all symmetrically possible parent orientations\n%   ori_fcc = unique(ori_bcc.symmetrise * NW)\n%\n%   % same using the function parents\n%   ori_fcc2 = ori_bcc * NW.parents\n%\n% See also\n% orientation/variants\n%\n\n% store child symmetry\nCS_child = mori.SS;\n\n% symmetrise only with respect to child symmetry\nmori = CS_child * mori;\n\n% ignore all variants symmetrically equivalent \n% with respect to the parent symmetry\nmori.SS = crystalSymmetry('1');\nmori = unique(mori);\nmori.SS = CS_child;\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/@orientation/parents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5617220551434867}}
{"text": "function pass = test_divide(pref)\n% Test contour\n\nif ( nargin == 0) \n    pref = chebfunpref; \nend\ntol = 1000*pref.cheb3Prefs.chebfun3eps;\n\nf = chebfun3(@(x,y,z) cos(x.*y.*z)); \ng = chebfun3(@(x,y,z) cos(x.*y.*z)./2); \n\npass(1) = norm( f./2 - g ) < tol;\n\npass(2) = norm( f/2 - g ) < tol;\n\npass(3) = norm( 2.\\f - g ) < tol;\n\npass(4) = norm( 2\\f - g ) < tol;\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun3/test_divide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5617220551434866}}
{"text": "clear\nclc\n\nA0=imread('cam.jpg');\n% chk=[1 1 1 3 1 1 2 1 1 2 3 2 2 2 1 1 1 2 3 1 1 4 1 3 2 1 1,...\n%     1 1 1 1 1 2 1 2 2 3 1 1 2 1 2 3 2 1 4 1 1 1 1 3 2 2 2 2,...\n%     1 1 1 1]; % for cam1\n% chk=[1 1 1 3 1 1 2 1 1 2 3 2 1 2 2 1 1 2 3 3 1 2 1 3 2, ...\n%     1 1 1 1 1 1 1 3 2 1 1 2 2 2 1 2 2 2 1 1 1 3 2 1 1 3 2, ...\n%     1 2 3 1 1 1 1]; % for cam\n% chk=[1 1 1 3 1 1 2 1 1 2 3 1 1 1 4 1 1 2 3 1 1 4 1 1, ...\n%     1 1 4 1 1 1 1 1 1 1 1 4 1 3 1 2 3 2 1 1 1 1 3 2 2,...\n%     2 2 1 3 2 1 1 1 1 1]; % for cam3\n% chk=[1 1 1 1 3 1 2 3 1 2 1 1 1 2 3 3 2 1 1 2 1 3 1 3 2 1,...\n%     1 1 1 1 1 1 2 2 2 1 1 1 3 2 1 1 3 2 1 3 1 2 3 1 1 2 1,...\n%     2 1 3 1 1 1]; % for cambook3\nA0=rgb2gray(A0);\n% A=A0([90:330],[1:604]); % for cam1\nA=A0([99+30:99+260],[71:608]); % for cam\n% A=A0([182:389],[1:600]); % for cam3\n% A=A0([193:349],[1:504]); % for cambook3\nreturn\nfigure(1), imshow(A)%, return\n\nnSeg=10;\nwSeg=floor(size(A,1)/nSeg);\n\nfor i=1:nSeg\n\n    At=A((i-1)*wSeg+1:i*wSeg,:);\n    %figure(2), imshow(At)\n\n    gsv(i,:)=255-mean(double(At),1);\n    x=[1:length(gsv(i,:))]; g=gsv(i,:);\n    [gw,xw]=movAvg(g,1);\n    %figure(3), plot(x,gsv(i,:),xw,gw)\n\n    dgw=diffScheme(gw);\n    [pk1,loc1]=peakDetect(dgw,20,5);\n    % sub-pixel edge detection\n    for i1=1:length(loc1)\n        [X1(i1),P1(i1)]=subPx(dgw(loc1(i1)-5:loc1(i1)+5),...\n            xw(loc1(i1)-5:loc1(i1)+5),...\n            dgw(loc1(i1)),100);\n        %g=dgw(loc1(i)-5:loc1(i)+20); gMax=dgw(loc1(i)); save subPxData.mat g gMax\n    end\n    [pk2,loc2]=peakDetect(-dgw,20,5);\n    for i1=1:length(loc2)\n        [X2(i1),P2(i1)]=subPx(-dgw(loc2(i1)-5:loc2(i1)+5),...\n            xw(loc2(i1)-5:loc2(i1)+5),...\n            -dgw(loc2(i1)),100);\n    end\n    P2=-P2;\n    \n    if length(loc1)~=length(loc2)\n        disp('oops! ... left edge & right edge don''t match!!');\n    end\n    %figure(4), plot(xw,dgw,'.k-',xw(loc1),dgw(loc1),'o',...\n    %    xw(loc2),dgw(loc2),'o',X1,P1,'o',X2,P2,'o')\n\n    % black gap\n    bGap=X2-X1;\n    % white gap\n    wGap=-X2(1:end-1)+X1(2:end);\n\n    % discretizing barcodes\n    %figure(5), subplot(2,1,1), plot(sort(bGap),'ok')\n    %subplot(2,1,2), plot(sort(wGap),'or'), pause(0.1)\n    \n    % working on white gaps\n    [wGap2,wid]=sort(wGap);\n    dwGap2=wGap2(2:end)-wGap2(1:end-1);\n    [wGap21,dwid]=sort(dwGap2);\n    bound(1:3)=sort(dwid(end:-1:end-2)+1);\n    clear wGap21 dwid\n    s1=mean(wGap2(1:bound(1)-1));\n    s2=mean(wGap2(bound(1):bound(2)-1));\n    s3=mean(wGap2(bound(2):bound(3)-1));\n    s4=mean(wGap2(bound(3):end));\n    if s4/s1 <3.5 % 4 is not present\n        if s2/s1>1.5\n            S1=wid(1:bound(1)-1); % s1 and s2 are exclusive\n            if s3/s2<1.2 % s2 and s3 are same\n                S2=wid(bound(1):bound(3)-1);\n                S3=wid(bound(3):end);\n            else % s2 and s3 are separate\n                S2=wid(bound(1):bound(2)-1);\n                S3=wid(bound(2):end);\n            end\n        else\n            S1=wid(1:bound(2)-1); % s1 and s2 are inclusive\n            S2=wid(bound(2)-1:bound(3));\n            S3=wid(bound(3)-1:end);\n        end\n        S4=[];\n    else % 4 is present\n        S1=wid(1:bound(1)-1);\n        S2=wid(bound(1):bound(2)-1);\n        S3=wid(bound(2):bound(3)-1);\n        S4=wid(bound(3):end);\n    end\n    %figure(6),plot(wGap(S1),'o'),hold on,plot(wGap(S2),'.'),plot(wGap(S3),'x'),hold off\n    wGap3(S1)=1; \n    wGap3(S2)=2;\n    wGap3(S3)=3;\n    if ~isempty('S4'), wGap3(S4)=4; end\n\n    % working on black gaps\n    [bGap2,bid]=sort(bGap);\n    dbGap2=bGap2(2:end)-bGap2(1:end-1);\n    [bGap21,dbid]=sort(dbGap2);\n    bound(1:3)=sort(dbid(end:-1:end-2)+1);\n    clear bGap21 dbid\n    t1=mean(bGap2(1:bound(1)-1));\n    t2=mean(bGap2(bound(1):bound(2)-1));\n    t3=mean(bGap2(bound(2):bound(3)-1));\n    t4=mean(bGap2(bound(3):end));\n    if t4/t1 <3.5 % 4 is not present\n        if t2/t1>1.5\n            T1=bid(1:bound(1)-1); % t1 and t2 are exclusive\n            if t3/t2<1.2 % t2 and t3 are same\n                T2=bid(bound(1):bound(3)-1);\n                T3=bid(bound(3):end);\n            else % t2 and t3 are separate\n                T2=bid(bound(1):bound(2)-1);\n                T3=bid(bound(2):end);\n            end\n        else\n            T1=bid(1:bound(2)-1); % t1 and t2 are inclusive\n            T2=bid(bound(2)-1:bound(3));\n            T3=bid(bound(3)-1:end);\n        end\n        T4=[];\n    else % 4 is present\n        T1=bid(1:bound(1)-1);\n        T2=bid(bound(1):bound(2)-1);\n        T3=bid(bound(2):bound(3)-1);\n        T4=bid(bound(3):end);\n    end\n    %figure(7),plot(bGap(T1),'o'),hold on,plot(bGap(T2),'.'),plot(bGap(T3),'x'),hold off\n    bGap3(T1)=1;\n    bGap3(T2)=2;\n    bGap3(T3)=3;\n    if ~isempty('T4'), bGap3(T4)=4; end\n    \n    %wGap3=round(wGap/mean(wGap2(1:10)));\n    %bGap3=round(bGap/mean(bGap2(1:10)));\n\n    I(i).gap=zeros(length(bGap)+length(wGap),1);\n    I(i).gap(1:2:end)=bGap3;\n    I(i).gap(2:2:end)=wGap3;\n\n    %disp(['segment: ',num2str(i),' | errors: ',num2str(sum((I(i).gap'-chk)~=0))])\n    if i==1\n        G=I(i).gap;\n    else\n        for j=1:length(I(i).gap)\n            G(j)=G(j)+I(i).gap(j);\n        end\n    end\n\nend\n\nG=round(G/nSeg);\nbarcode=barcodeEAN13(G);\n%reading_error=sum(sum(G'-chk))", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31727-barcode-reader/barCodeCam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6688802735722127, "lm_q1q2_score": 0.5616814913900054}}
{"text": "function [newVal,newUnitStr,oldUnitStr] = unitConvert(oldVal,valueType,oldUnitStr,newUnitStr)\n% [newVal,newUnitStr,oldUnitStr] = unitConvert(oldVal,valType,oldUnitStr)\n%\n% Value types:\n%  'length' - recognized units: 'nm', 'um', 'mm', 'cm'\n%  'time'   - recognized units: 'usec', 'msec', 'sec'\n%\n% Adapted from isetbio unitConvert \n%\n% Examples\n%\n% newVal = unitConvert(1500,'time','ms' ,'s')\n% newVal = unitConvert(1,'length','cm' ,'mm')\n\n% Switch on value type\nswitch (valueType)\n    case 'length'\n        % Length\n        \n        % Factor from old to default\n        switch oldUnitStr\n            case 'm'\n                oldConversionFactor = 1;\n            case 'nm'\n                oldConversionFactor = 1e-9;\n            case 'um'\n                oldConversionFactor = 1e-6;\n            case 'mm'\n                oldConversionFactor = 1e-3;\n            case 'cm'\n                oldConversionFactor = 1e-2;\n            otherwise\n                error('Bad units %s passed for type %s',oldUnitStr,valueType);\n        end\n        \n         % Factor from old to default\n        switch newUnitStr\n            case 'm'\n                newConversionFactor = 1;\n            case 'nm'\n                newConversionFactor = 1e9;\n            case 'um'\n                newConversionFactor = 1e6;\n            case 'mm'\n                newConversionFactor = 1e3;\n            case 'cm'\n                newConversionFactor = 1e2;\n            otherwise\n                error('Bad units %s passed for type %s',oldUnitStr,valueType);\n        end\n        \n\n    case 'time'\n        % Time\n        \n        % Factor from old to default\n        switch oldUnitStr\n            case {'s' 'sec' 'seconds'}\n                oldConversionFactor = 1;\n            case {'ms' 'msec' 'milliseconds'}\n                oldConversionFactor = 1e-3;\n            otherwise\n                error('Bad units %s passed for type %s',oldUnitStr,valueType);\n        end\n        \n         % Factor from old to default\n        switch newUnitStr\n            case {'s' 'sec' 'seconds'}\n                newConversionFactor = 1;\n            case {'ms' 'msec' 'milliseconds'}\n                newConversionFactor = 1e3;\n            otherwise\n                error('Bad units %s passed for type %s',oldUnitStr,valueType);\n        end\n        \n    otherwise\n        error('Unknown value type passed');\nend\n\n% Convert\nnewVal = oldConversionFactor*newConversionFactor*oldVal;\n\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/unitConvert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5616814803045058}}
{"text": "function [ r, z, c, s ] = schex ( r, ldr, p, k, l, z, ldz, nz, job )\n\n%*****************************************************************************80\n%\n%% SCHEX updates the Cholesky factorization of a positive definite matrix.\n%\n%  Discussion:\n%\n%    The factorization has the form\n%\n%      A = R' * R\n%\n%    where A is a positive definite matrix of order P.\n%\n%    The updating involves diagonal permutations of the form\n%\n%      E' * A * E\n%\n%    where E is a permutation matrix.  Specifically, given\n%    an upper triangular matrix R and a permutation matrix\n%    E (which is specified by K, L, and JOB), SCHEX determines\n%    an orthogonal matrix U such that\n%\n%      U * R * E = RR,\n%\n%    where RR is upper triangular.  At the user's option, the\n%    transformation U will be multiplied into the array Z.\n%    If A = X'*X, so that R is the triangular part of the\n%    QR factorization of X, then RR is the triangular part of the\n%    QR factorization of X*E, that is, X with its columns permuted.\n%\n%    For a less terse description of what SCHEX does and how\n%    it may be applied, see the LINPACK guide.\n%\n%    The matrix Q is determined as the product U(L-K)*...*U(1)\n%    of plane rotations of the form\n%\n%      (    C(I)       S(I) )\n%      (                    ),\n%      (   -S(I)       C(I) )\n%\n%    where C(I) is real, the rows these rotations operate on\n%    are described below.\n%\n%    There are two types of permutations, which are determined\n%    by the value of JOB.\n%\n%    1, right circular shift.  The columns are rearranged in the order:\n%\n%         1,...,K-1,L,K,K+1,...,L-1,L+1,...,P.\n%\n%       U is the product of L-K rotations U(I), where U(I)\n%       acts in the (L-I,L-I+1)-plane.\n%\n%    2, left circular shift: the columns are rearranged in the order\n%\n%         1,...,K-1,K+1,K+2,...,L,K,L+1,...,P.\n%\n%       U is the product of L-K rotations U(I), where U(I)\n%       acts in the (K+I-1,K+I)-plane.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    09 November 2006\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, real R(LDR,P), the upper triangular factor that is to be updated.  \n%    Elements of R below the diagonal are not referenced.\n%\n%    Input, integer LDR, the leading dimension of the array R.\n%    LDR must be at least P.\n%\n%    Input, integer P, the order of the matrix R.\n%\n%    Input, integer K, the first column to be permuted.\n%\n%    Input, integer L, the last column to be permuted.\n%    L must be strictly greater than K.\n%\n%    Input, real Z(LDZ,NZ), an array of NZ P-vectors into\n%    which the transformation U is multiplied.  Z is not referenced if NZ = 0.\n%\n%    Input, integer LDZ, the leading dimension of the array Z.\n%    LDZ must be at least P.\n%\n%    Input, integer NZ, the number of columns of the matrix Z.\n%\n%    Input, integer JOB, determines the type of permutation.\n%    1, right circular shift.\n%    2, left circular shift.\n%\n%    Output, real R(LDR,P), the updated upper triangular factor.\n%\n%    Output real Z(LDZ,NZ), the updated array of vectors.\n%\n%    Output, real C(P), S(P), the cosines and sines of the\n%    transforming rotations.\n%\n\n%\n%  Initialize\n%\n  lmk = l - k;\n  lm1 = l - 1;\n%\n%  Right circular shift.\n%\n  if ( job == 1 )\n%\n%  Reorder the columns.\n%\n    for i = 1 : l\n      ii = l - i + 1;\n      s(i) = r(ii,l);\n    end\n\n    for jj = k : lm1\n      j = lm1 - jj + k;\n      for i = 1 : j\n        r(i,j+1) = r(i,j);\n      end\n      r(j+1,j+1) = 0.0;\n    end\n\n    for i = 1 : k-1\n      ii = l - i + 1;\n      r(i,k) = s(ii);\n    end\n%\n%  Calculate the rotations.\n%\n    t = s(1);\n    for i = 1 : lmk\n      [ c(i), s(i), s(i+1), t ] = srotg ( s(i+1), t );\n      t = s(i+1);\n    end\n\n    r(k,k) = t;\n\n    for j = k+1 : p\n      il = max ( 1, l-j+1 );\n      for ii = il : lmk\n        i = l - ii;\n        t = c(ii) * r(i,j) + s(ii) * r(i+1,j);\n        r(i+1,j) = c(ii) * r(i+1,j) - s(ii) * r(i,j);\n        r(i,j) = t;\n      end\n    end\n%\n%  If required, apply the transformations to Z.\n%\n    for j = 1 : nz\n      for ii = 1 : lmk\n        i = l - ii;\n        t = c(ii) * z(i,j) + s(ii) * z(i+1,j);\n        z(i+1,j) = c(ii) * z(i+1,j) - s(ii) * z(i,j);\n        z(i,j) = t;\n      end\n    end\n%\n%  Left circular shift.\n%\n  else\n%\n%  Reorder the columns.\n%\n    for i = 1 : k\n      ii = lmk + i;\n      s(ii) = r(i,k);\n    end\n\n    for j = k : lm1\n      for i = 1 : j;\n        r(i,j) = r(i,j+1);\n      end\n      jj = j - k + 1;\n      s(jj) = r(j+1,j+1);\n    end\n\n    for i = 1 : k\n      ii = lmk + i;\n      r(i,l) = s(ii);\n    end\n\n    r(k+1:l,l) = 0.0;\n%\n%  Reduction loop.\n%\n    for j = k : p\n%\n%  Apply the rotations.\n%\n      if ( j ~= k )\n\n        iu = min ( j-1, l-1 );\n\n        for i = k : iu\n          ii = i - k + 1;\n          t = c(ii) * r(i,j) + s(ii) * r(i+1,j);\n          r(i+1,j) = c(ii) * r(i+1,j) - s(ii) * r(i,j);\n          r(i,j) = t;\n        end\n\n      end\n\n      if ( j < l )\n        jj = j - k + 1;\n        t = s(jj);\n        [ c(jj), s(jj), r(j,j), t ] = srotg ( r(j,j), t );\n      end\n\n    end\n%\n%  Apply the rotations to Z.\n%\n    for j = 1 : nz\n      for i = k : lm1\n        ii = i - k + 1;\n        t = c(ii) * z(i,j) + s(ii) * z(i+1,j);\n        z(i+1,j) = c(ii) * z(i+1,j) - s(ii) * z(i,j);\n        z(i,j) = t;\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/linpack_s/schex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938816, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5616814803045057}}
{"text": "function [rstat]=AddIMUErr(finam, fonam, fenam, nrow, act_row, errdefs, tem_mod, rstat)\n\n%randomize\nif (rstat(1)~=0)\n    randn('state',rstat);\nelse\n    rstat=randn('state');\nend\n\nif isempty(tem_mod) %if no tem_mod is specified, use constant temp=0.\n    tem_mod.A=1;\n    tem_mod.B=0;\n    tem_mod.u=0;\nend\n\n%input data\nfimu=fopen(finam,'rb');\nimu_inp=fread(fimu,[nrow inf],'double');\nfclose(fimu);\nimu_inp=imu_inp(act_row,:);\n\nndat=size(imu_inp,2);\n\n%output files\nfeimu=fopen(fonam,'wb');\nferr=fopen(fenam,'wb');\n\nif (isempty(errdefs))   %do not add error\n     out=[0:ndat-1;zeros(1,ndat);imu_inp];\n     fwrite(feimu,out,'double');\nelse    %generate and add errors\n    %Generate the system model for the TI imu errors\n    [Ati, Bti, Cti, Dti, sPti]=imu_modTI_v000(errdefs);\n    nst_ti=size(Ati,1);\n    st_ti=sPti*randn(nst_ti,1);\n\n    tem=0;\n    tem_dif=0;\n    [Atv, Btv, Ctv, sPtv]=imu_modTV_v000(errdefs, tem_dif, tem, 1);\n    if (~isempty(Atv))\n        nst_tv=size(Atv,1);\n        st_tv=sPtv*randn(nst_tv,1);\n    else\n        nst_tv=0;\n    end\n\n    %add errors\n    nsen=size(Cti,1);\n    if (nst_tv==0) %only ti part\n        for in=1:ndat\n            imu_out=imu_inp(:,in)+Cti*st_ti+Dti*randn(nsen,1);\n            fwrite(ferr,[in-1;st_ti],'double');\n            fwrite(feimu,[in-1;tem;imu_out],'double');\n\n            %new error values\n            tem=tem_mod.A*tem+tem_mod.B*randn(1)+tem_mod.u;\n            st_ti=Ati*st_ti+Bti*randn(nst_ti,1);\n        end\n    else    %both ti and tv parts are generated\n        for in=1:ndat\n            imu_out=imu_inp(:,in)+Cti*st_ti+Dti*randn(nsen,1)+Ctv*st_tv;\n            fwrite(ferr,[in-1;st_ti;st_tv],'double');\n            fwrite(feimu,[in-1;tem;imu_out],'double');\n\n            %new error values\n            sr_a=tem_mod.A*tem+tem_mod.B*randn(1)+tem_mod.u;\n            tem_dif=sr_a-tem;\n            tem=sr_a;\n            [Atv, Btv, Ctv]=imu_modTV_v000(errdefs, tem_dif, tem, 0);\n            st_tv=Atv*st_tv+Btv*randn(nst_tv,1);\n            st_ti=Ati*st_ti+Bti*randn(nst_ti,1);\n        end\n    end\nend\nfclose(feimu);\nfclose(ferr);\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/OldVersions/AddIMUErr_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5616642407942389}}
{"text": "classdef MultiObjectiveEGO < ALGORITHM\n% <multi> <real/integer> <constrained/none> <expensive>\n% Multi-objective efficient global optimization\n% alpha --- 0.7 --- portion of samples for Kriging construction\n% num_k ---   5 --- number of infill points per iteration\n% H     ---  21 --- number of reference directions\n\n%------------------------------- Reference --------------------------------\n% R. Hussein, K. Deb, A Generative Kriging Surrogate Model for Constrained \n% and Unconstrained Multi-objective Optimization, in: Proc. Genet. Evol. \n% Comput. Conf. 2016, Denver, 2016, 573-580. \n%--------------------------------------------------------------------------\n\n% This function is written by Youwei He (email: 1554748356@qq.com)\n\n    methods\n        function main(Algorithm,Problem)\n            %% Parameter setting\n            [alpha,num_k,H] = Algorithm.ParameterSet(0.7,5,21);\n            % parameter for AASF in equation (10)\n            rho = 1e-3;\n            %% Generate the initial design points\n            % number of design variables\n            D = Problem.D;\n            % number of initial design points 11*D-1\n            N = Problem.N;\n            %% step1-1: generate initial design points using Latin Hypercube sampling\n            PopDec = repmat(Problem.upper-Problem.lower,N,1).*UniformPoint(N,D,'Latin') ...\n                +repmat(Problem.lower,N,1);\n            %% step1-2: evaluate initial design points\n            Population = Problem.Evaluation(PopDec);\n\n            %% step 2: Generate the reference direction set\n            [R,N_R] = UniformPoint(H,Problem.M);\n            R = R./sqrt(sum(R.^2,2));\n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                %% step 2 diversity_preserver procedure: neighborhood approach\n                i_direction = linspace(1,N_R,N_R);\n                for i = i_direction\n                    for j = 1 : num_k\n                        Algorithm.NotTerminated(Population);\n                        PopDecT = Population.decs;\n                        PopObjT = Population.objs;\n                        PopConT = Population.cons;% cons>=0: meet constraints\n                        num_con = size(PopConT,2);\n                        N_Pop=length(PopDecT(:,1));\n                        % determine whether the problem is constrained or not\n                        if all(all(PopConT==0)) && N_Pop==1\n                            constrained=1;\n                        else\n                            constrained=0;\n                        end\n                        %% step 3: Points_Selector procedure\n                        normW = sqrt(sum(R(i,:).^2,2));\n                        normP = sqrt(sum(PopObjT.^2,2));\n                        CosineP = sum((PopObjT).*R(i,:),2)./normP./normW;\n                        % orthogonal distance of each point to the given reference direction\n                        distB = normP.*sqrt(1-CosineP.^2);\n                        [~,indx] = sort(distB);\n                        N = ceil(alpha*N_Pop);\n                        PopObj = PopObjT(indx(1:N),:);\n                        PopDec = PopDecT(indx(1:N),:);\n                        PopCon = PopConT(indx(1:N),:);\n                        %% step 4-1\n                        index = sum(PopCon >= 0, 2) == num_con;% feasible solutions\n                        PopCon(index,:)=0;\n                        PopCon(~index,:)=-PopCon(~index,:);     \n                        PopObjScaled = (PopObj-repmat(min(PopObj),N,1))./(repmat(max(PopObj),N,1)-repmat(min(PopObj),N,1));  \n                        if constrained\n                            PopConScaled = (PopCon-repmat(min(PopCon),N,1))./(repmat(max(PopCon),N,1)-repmat(min(PopCon),N,1));\n                        end\n                        %% step 4-2\n                        PopSmetric = zeros(N,1);\n                        PopSmetricT = PopObjScaled(index,:)./repmat(R(i,:),sum(index),1);\n                        PopSmetric(index,:)=max(PopSmetricT,[],2)+rho*sum(PopSmetricT,2);\n                        if constrained\n                            ASF_max = max(PopSmetric(index,1));\n                            PopSmetric(~index,:) = ASF_max.*ones(sum(~index),1) + sum(PopConScaled(~index,:),2);\n                        end\n                        %% step 4-3\n                        kriging_obj= dacefit(PopDec,PopSmetric,'regpoly0','corrgauss',1*ones(1,D),0.001*ones(1,D),1000*ones(1,D));\n                        f_min = min(PopSmetric);\n                        %% step 5: Optimization\n                        infill_criterion = @(x)Infill_Standard_EI(x, kriging_obj, f_min);\n                        best_x=rGA(infill_criterion,Problem);\n                        % infill point too close (not used in the paper, \n                        % but this happens sometimes especially for low dimensional problem)\n                        if min(sqrt(sum((PopDecT-best_x).^2,2)))<1E-8\n                            best_x = rGA(@(x)Infill_Maximal_Distance(x, PopDecT),Problem);\n                        end\n                        Population = [Population,Problem.Evaluation(best_x)];\n                    end   \n                end  \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/Algorithms/Multi-objective optimization/MultiObjectiveEGO/MultiObjectiveEGO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5616642142051305}}
{"text": "function [signal, state] = flt_dynamicloreta(varargin)\n% Return the current source density for a given head model and data using\n% the cortically-constrained LORETA (low resolution electrical\n% tomographic analysis) with a Bayesian update scheme for hyperparameters.\n% The reconstructed CSD time-series (or source potential maps) will be \n% stored in signal.srcpot. This matrix has dimension [num_voxels x num_samples].\n% \n% Author: Tim Mullen, Jan 2013, SCCN/INC/UCSD\n%         Alejandro Ojeda, Jan 2013, SCCN/INC/UCSD\n%         Christian Kothe, Jan 2013, SCCN/INC/UCSD\n\n\nif ~exp_beginfun('filter'), return; end\n\ndeclare_properties('name','Dynamic LORETA', 'experimental',true, 'independent_channels',false, 'independent_trials',false);\n\narg_define(varargin, ...\n    arg_norep({'signal','Signal'}), ...\n    arg_nogui({'K','ForwardModel'},[],[],'Forward model (matrix)','shape','matrix'), ...\n    arg_nogui({'L','LaplacianOperator'},[],[],'Laplacian operator. Sparse matrix of N sources x N sources, this is matrix is used as the square root of the precision matrix of the sources.'), ...\n    arg_sub({'options','LoretaOptions'},{},...\n        { ...\n        arg({'maxTol','MaxTolerance'},1e-12,[0 Inf],'Tolerance for hyperparameter update loop','cat','Loreta Options'), ...\n        arg({'maxIter','MaxIterations'},100,[1 Inf],'Maximum iterations for hyperparameter update loop','cat','Loreta Options'), ...\n        arg({'gridSize','GridSize'},100,[1 Inf],'Lambda grid size.'), ...\n        arg({'history','TrackHistory'},false,[],'Track history for hyperparameters'), ...\n        arg({'verbose','VerboseOutput'},false,[],'Verbosity','cat','Loreta Options'), ...\n        arg({'initNoiseFactor','InitialNoiseFactor'},0.001,[0 Inf],'Fraction of noise level. Used for initializing alpha parameter','cat','Loreta Options') ...\n        arg({'block_size','BlockSize'},5, [], 'Block granularity for processing. The inverse operator will be updated using blocks of this many samples. This assumes that the inverse solution is spatially stationary over this many samples.'), ...\n        arg({'skipFactor','SkipFactor'},0,[0 Inf],'Number of blocks to skip'), ...\n        arg({'maxblocks','MaxBlocks'},Inf,[0 Inf],'Maximum number of blocks'), ...\n        arg({'standardize','Standardize'},'all',{'none','channels','all'},'Rescale data to unit variance. If ''channels'', standardization is carried out across channels for each time point. If ''all'' each data sample is normalized by the standard deviation taken over all data.'), ...\n        arg({'useGPU','UseGPU'},false,[],'Use GPU to accelerate computation.'), ...\n        },'Additional options for Loreta function'), ...\n    arg({'verb','Verbosity'},false,[],'Verbose output'), ...\n    arg_nogui({'state','State'},[],[],'State object. When provided, hyperparameters will be estimated adaptively from prior state'));\nif verb\n    fprintf('Estimating current source density using cLORETA (%s)\\n',mfilename); \nend\n\n[nchs, npnts, ntrs] = size(signal.data);\nif isempty(block_size) || block_size > npnts\n    block_size = npnts;\nend\nnumsplits    = floor(npnts/block_size);\n\n% if necessary, cast to double-precision\nif ~strcmpi(class(signal.data),'double')\n    signal.data = double(signal.data);\nend\n    \n% normData the data\nif ~strcmpi(normData,'none')\n    switch normData\n        case 'channels'\n            scale = std(signal.data,[],1);\n        case 'time'\n            scale = std(signal.data,[],2);\n        case 'all'\n            scale = std(signal.data(:));\n    end\n    signal.data = bsxfun(@rdivide,signal.data,scale);\n%     scale = std(signal.data(:));\n%     signal.data = signal.data./scale;\nend\n\nif isempty(state) || ~isfield(state,'iLV') || isempty(state.iLV)\n    if verb\n        fprintf('...computing SVD of LFM.\\n');\n    end\n    % mode is offline or we are initializing online filter\n    % perform one-time SVD for faster computation.\n    [U,S,V]      = svd(K/L,'econ');\n    state.iLV    = L\\V;\n    state.s2     = diag(S).^2; %s^2\n    state.Ut     = U';\n    state.sigma2 = repmat({options.sigma2},1,ntrs);\n    state.tau2   = repmat({options.tau2},1,ntrs);\nend\n \nif npnts == 0\n    % no data\n    signal.srcpot    = [];\n    state.srcweights = [];\n    exp_endfun; return;\nend\n\nsignal.srcpot    = zeros([size(K,2), npnts, ntrs]);\nstate.srcweights = zeros(size(L,1),nchs);\nsum_srcweights   = zeros(size(L,1),nchs);\nsignal.loretaHistory = struct([]);\n\nif verb\n    fprintf('...assuming %d stationary blocks of length %d\\n',numsplits,block_size);\nend\n\n\n% loop over all trials\nfor tr=1:ntrs\n    if verb\n        fprintf('\\nTrial (%d\\%d).',tr,ntrs);\n    end\n    k = 0;\n    % loop over sub-blocks and estimate CSD for each block\n    for i=0:skipFactor+1:numsplits-1\n        if verb\n            if i+1 >= floor(numsplits*(k+1)/10)\n                k = k + 1;\n                fprintf('%0.3g%%...',round((i/numsplits)*100));\n            end\n        end\n        range = 1+floor(i*npnts/numsplits) : min(npnts,floor((i+1)*npnts/numsplits));\n        % call (dynamic bayesian) loreta estimator\n        [signal.srcpot(:,range,tr), state.sigma2{tr}, state.tau2{tr}, state.srcweights, tmpHist] ...\n            = dynamicLoreta( signal.data(:,range,tr), state.Ut, state.s2, state.iLV,...\n                             state.sigma2{tr}, state.tau2{tr}, options);\n        if ~isempty(tmpHist)\n            signal.loretaHistory{tr} = [signal.loretaHistory{tr},tmpHist]; \n        end\n\n        if skipFactor > 0\n            % estimate CSD for samples between blocks using current inverse operator\n            range = 1+floor((i+1)*npnts/numsplits) : min(npnts,floor((i+skipFactor+1)*npnts/numsplits));\n            signal.srcpot(:,range,tr) = state.srcweights*signal.data(:,range,tr);\n        end\n        \n        % running sum\n        sum_srcweights = sum_srcweights + state.srcweights;\n    end\nend\n\n\nif numsplits > 1\n    % store the mean inverse operator over all splits          \n    state.srcweights = sum_srcweights/(numsplits*ntrs);\nend\n\nif ~strcmpi(normData,'none')\n    % recale data to original units\n%     signal.srcpot     = signal.srcpot*scale;\n%     state.srcweights  = state.srcweights/scale;\n    signal.srcpot = bsxfun(@times,signal.srcpot,scale);\n%     signal.srcpot = bsxfun(@rdivide,signal.srcpot,std(signal.srcpot,[],1));\n%     state.srcweights  = bsxfun(@times,state.srcweights,scale'); %state.srcweights/mean(scale);\nend\n\nif verb\n    fprintf('done.\\n');\nend\n    \nexp_endfun;\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/filters/in_development/flt_dynamicloreta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5616642127610102}}
{"text": "function L = nodesInLen(nodeNo,inLen,doNoExt,wt)\n%NODESINLEN Length of the node input signal\n%   Usage:  L = nodesInLen(nodeNo,inLen,doExt,treeStruct);\n%\n%   Input parameters:\n%         nodeNo     : Node index.\n%         inLen      : Filter thee input signal length.\n%         doNoExt    : Expansive representation indicator.\n%         wt         : Structure containing description of the filter tree.\n%\n%   Output parameters:\n%         Lin        : Length of the node input signal \n%\n%   `nodesInLen(nodeNo,inLen,doExt,treeStruct)` return length of the input\n%   signal of the node `nodeNo`. For definition of the structure see `wfbinit`.\n%\n%   See also: wfbtinit\n%\n\nL = zeros(numel(nodeNo),1);\nfor nn=1:length(nodeNo)\n    subPat = [];\n    filtLenPat = [];\n    tmpNodeNo = nodeNo(nn);\n\n    while(wt.parents(tmpNodeNo))\n       parentNo = wt.parents(tmpNodeNo);\n       tmpIdx = find(wt.children{parentNo}==tmpNodeNo);\n       subPat(end+1) = wt.nodes{parentNo}.a(tmpIdx);\n       filtLenPat(end+1) = length(wt.nodes{parentNo}.g{tmpIdx}.h);\n       tmpNodeNo=parentNo;\n    end\n\n    subPat = subPat(end:-1:1);\n    filtLenPat = filtLenPat(end:-1:1);\n\n    L(nn) = inLen;\n    if(~doNoExt)\n        for ii=1:length(subPat)\n            L(nn) = floor((L(nn)+filtLenPat(ii)-1)/subPat(ii));\n        end\n    else\n        for ii=1:length(subPat)\n            L(nn) = ceil(L(nn)/subPat(ii)); \n        end\n    end\nend\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/wavelets/wfbtmanip/nodesInLen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5616570668587774}}
{"text": "function ar=lpczz2ar(zz)\n%LPCZZ2AR Convert z-place poles to ar coefficients AR=(ZZ)\n% The complex poles must occur in complex conjugate pairs\n% but the order is unimportant.\n\n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: lpczz2ar.m 713 2011-10-16 14:45:43Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[nf,p]=size(zz);\nar=zeros(nf,p+1);\nfor k=1:nf\n  ar(k,:)=real(poly(zz(k,:)));\nend\n\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/lpczz2ar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6757646140788308, "lm_q1q2_score": 0.5616570609802787}}
{"text": "function model = expvarMeanCreate(inputDim, outputDim, options)\n\n% EXPVARMEANCREATE Creates an the mean function for the EXP kernel.\n% FORMAT\n% DESC creates a model for returning the first moment of an\n% 'exponentiated Gaussian process'. If the output of a Gaussian\n% process is exponentiated the resulting process is no longer\n% Gaussian. However, it can be approximated by a Gaussian process\n% by matching its first and second moments. This function returns\n% the mean of that approximating process for a given kernel\n% (specified in the options vector). It should be used in tandem\n% with the EXP kernel for approximating these Gaussian processes.\n% ARG inputDimension : dimension of input to function.\n% ARG outputDim : dimension of output from mean function data.\n% ARG options : options structure. The structure contains the type\n% of kernel that the function is based on. A set of default options \n% are given by the file expvarMeanOptions.\n% RETURN model : model structure containing the mapping.\n% \n% COPYRIGHT : Neil D. Lawrence, 2005, 2006\n%\n% SEEALSO : expvarMeanOptions\n\n% SHEFFIELDML\n\nmodel.type = 'expvarMean';\nif isstruct(options.kern) \n  model.kern = options.kern;\nelse\n  model.kern = kernCreate(inputDim, options.kern);\nend\nmodel.q = inputDim;\nmodel.d = outputDim;\nmodel.numParams = model.kern.nParams;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gpsim/expvarMeanCreate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5616570449240688}}
{"text": "% \n% Usage:   [val [paths]]=mexEvalPathCoding(U,DAG,param);\n%\n% Name: mexEvalPathCoding\n%\n% Description: mexEvalPathCoding evaluate the path coding penalies \n%         of http://arxiv.org/abs/1204.4539 and provides a path \n%         decomposition of a vector W.\n%\n%         Given an input matrix U=[u^1,\\ldots,u^n], \n%\n%\n% Inputs: U:  double p x n matrix   (input signals)\n%               m is the signal size\n%         DAG:  struct\n%               with three fields, weights, start_weights, stop_weights\n%         for a graph with |V| nodes and |E| arcs,\n%         DAG.weights: sparse double |V| x |V| matrix. Adjacency\n%               matrix. The non-zero entries represent costs on arcs\n%               linking two nodes.\n%         DAG.start_weights: dense double |V| vector. Represent the costs\n%               of starting a path from a specific node.\n%         DAG.stop_weights: dense double |V| vector. Represent the costs\n%               of ending a path at a specific node.\n%\n%         if param.regul='graph-path-l0', non-convex penalty\n%         if param.regul='graph-path-conv', convex penalty\n%\n%         param: struct\n%               param.regul (choice of regularization, see above)\n%               param.verbose (optional, verbosity level, false by default)\n%               param.precision (optional, by default a very large integer.\n%                 It returns approximate proximal operator by choosing a small integer,\n%                 for example, 100 or 1000.\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 1 x n vector (values of the objective function)\n%         paths: optional, double sparse p x k matrix. selected paths for the \n%                first column of U\n%\n% Author: Julien Mairal, 2012\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/mexEvalPathCoding.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5616570442472312}}
{"text": "function [u, V, exitflag, output] = snd_solveOptimalControlProblem (snd,  varargin)\n%UNTITLED2 Summary of this function goes here\n%   solves the optimal control problem of the\n\n    % Set control and linear bounds\n    A = [];\n    b = [];\n    Aeq = [];\n    beq = [];\n    lb = [];\n    ub = [];\n    for k=1:snd.horizon %Aggregation\n        [Anew, bnew, Aeqnew, beqnew, lbnew, ubnew] = ...\n               snd.l_constraints( k, snd.net_load, snd.battery, snd.u0_ref);\n        A = blkdiag(A,Anew);\n        b = [b, bnew];\n        Aeq = blkdiag(Aeq,Aeqnew);\n        beq = [beq, beqnew];\n        lb = [lb, lbnew];\n        ub = [ub, ubnew];\n    end\n    \n    % Solve optimization problem\n    [u, V, exitflag, output] = fmincon( @(u) snd.costfunction( snd, u ), ...\n        snd.u0, A, b, Aeq, beq, lb, ub, ...\n        @(u) snd.nonlinearconstraints(snd, u ), snd.option);\nend\n\n", "meta": {"author": "juchengquan", "repo": "Two_Layer_EMS", "sha": "48864a80e10fe32e566181ebd5e2394ab2c6e1a7", "save_path": "github-repos/MATLAB/juchengquan-Two_Layer_EMS", "path": "github-repos/MATLAB/juchengquan-Two_Layer_EMS/Two_Layer_EMS-48864a80e10fe32e566181ebd5e2394ab2c6e1a7/solve/snd_solveOptimalControlProblem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110368115783, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.5616399579807292}}
{"text": "function [means,stats] = weighted_reg(Y,varargin)\n% Calculate weighted average using weighted linear least squares\n% See examples below for usage\n%\n% :Model:\n%\n%   Y_i = 1*Ypop + noise\n%\n% :Inputs:\n%\n%   **Y:**\n%        data matrix (nsub x T)\n%\n%   **w:**\n%        weights\n%\n%   **varY:**\n%        variance of data at each time point (nsub x T) + var between\n%\n% :Outputs:\n%\n%   **Ymean:**\n%        weighted mean of each column of Y\n%\n%   **dfe:**\n%        error degrees of freedom, adjusted for inequality of variance\n%        (Sattherwaite) and pooled across data columns\n%\n% Extended output in stats structure:\n%\n%   **stats.t:**\n%        t-values for weighted t-test\n%\n%   **stats.p:**\n%        2-tailed p-values for weighted t-test\n%\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%      - sqrt(v) is the standard error of the mean (or grp difference)\n%\n%\n%   **stats.fits:**\n%        fits  for each group (Ymean by group), low contrast weight group then high\n%        Fastest if no stats are asked for.\n%\n% Computation time:\n% For FULL stats report\n%  - Triples from 500 -> 1000 columns of Y, continues to increase\n%\n% For mean/dfe only, fast for full dataset (many columns of Y)\n%\n% :Examples:\n% ::\n%\n%    % Basic multivariate stats for 1000 columns of dat, no weighting\n%    % Multivariate covariances are meaningful if cols of Y are organized, e.g., timeseries\n%    [means,stats] = weighted_reg(dat(:,1:1000));\n%\n%    % The same, but return univariate stats only (good for large Y)\n%    [means,stats] = weighted_reg(dat,'uni');\n%\n% ..\n%    NOTE: TOR CHANGED INPUT TO ASSUME THAT WE SHOULD ENTER VARWI + VARBETWEEN\n% ..\n\n\n% ..\n%    Set up arguments\n% ..\n\nif nargin == 0, error('Must at least enter data as 1st argument.'); end\n\ndomultivariate = 1;     % multivariate covariance est for Y\ndobtwn = 0;             % between-subjects contrast\n\nbcon = []; Ydiff = []; w = []; varY = [];\n\nfor i = 1:length(varargin)\n    arg = varargin{i};\n    if ischar(arg)\n        switch lower(arg)\n            case 'w', w = varargin{i+1};\n            case 'btwn', bcon = contrast_code(varargin{i+1}); \n            case 'vary', varY = varargin{i+1};\n            case 'uni', domultivariate = 0;\n        end\n    end\nend\n\n[m,n] = size(Y);\n\n% fill in missing inputs with default values\n\nif ~is_entered(w), w = ones(m,1);  end\nif ~is_entered(varY), varY = ones(m,1); end\nif is_entered(bcon), dobtwn = 1; end\n\n% --------------------------------------\n% * Weights and computational steps\n% --------------------------------------\n\nW = diag(w);                    % Weight matrix\n\nX = repmat(1,m,1);              % Design matrix - 1 column of all ones to calculate average\n% and, separately, use bcon if that's entered\n\ninvxwx = inv(X'*W*X);\nhat = invxwx * X'* W;         % hat matrix\n\n% Between-observations, if entered\n% ----------------------------------------\nif dobtwn\n    invxwx_diff = inv(bcon'*W*bcon);\n    hatdiff = invxwx_diff*bcon'*W;\nelse\n    hatdiff = [];\nend\n\n% --------------------------------------\n% * Means and contrast\n% --------------------------------------\n\nYmean = hat*Y;\n\n% Output: weighted population mean\nmeans.Ymean = Ymean;\n\n% Between-observation contrast, if entered\n% ----------------------------------------\nif dobtwn\n\n    Ydiff = hatdiff*Y;\n\n    % for output; fits for each group; low then high\n    grpfits = repmat(Ymean,2,1) + repmat(sort(unique(bcon)),1,n) .* repmat(Ydiff,2,1);\n\n    means.Ydiff = Ydiff;\n    means.grpmeans = grpfits;\nend\n\n\nif nargout == 1, return, end\n\n\n\n% --------------------------------------\n% * Residuals\n% --------------------------------------\n\ne = Y - repmat(Ymean,m,1);         % residuals\n\nif dobtwn\n\n    % fitted values depending on group\n    fits = repmat(Ymean,m,1) + repmat(bcon,1,n) .* repmat(Ydiff,m,1);\n    ediff = Y - fits;\nend\n\n% --------------------------------------\n% * Degrees of freedom\n% --------------------------------------\n\n[dfe,dfediff] = get_dfe(m,n,X,hat,varY,dobtwn,hatdiff,bcon);\n\n\n\nif ~domultivariate\n    % ======================================\n    %\n    %\n    % Univariate stats: MSE, t, and p-values\n    %\n    %\n    % ======================================\n\n    % --------------------------------------\n    % * Mean squared error\n    % --------------------------------------\n    % Loop version of MSE: avoids out of memory errors for large voxel sets\n    MSE = zeros(1,n); for i=1:n, MSE(i) = e(:,i)'*W*e(:,i); end, MSE = MSE/dfe;\n    v = invxwx * MSE;       % variances for mean\n\n    if dobtwn\n        MSEdiff = zeros(1,n);\n        for i=1:n, MSEdiff(i) = ediff(:,i)'*W*ediff(:,i); end, MSEdiff = MSEdiff/dfediff;\n        vdiff = invxwx_diff * MSEdiff;       % variances for mean\n    end\n\n\n\n    % output\n    stats.descrip1 = 'Univariate stats for test against zero:';\n    stats.v = v;\n    stats.v_descrip = 'V = ste^2; variance of mean estimate';\n    stats.t = Ymean ./ sqrt(v);\n    stats.p = 2 * ( 1 - tcdf(abs(stats.t),dfe) );\n    stats.dfe = dfe;\n\n    if dobtwn\n        stats.descrip2 = 'Univariate stats for between-case contrast:';\n        stats.bcon = bcon;\n        stats.vdiff = vdiff;\n        stats.tdiff = fits ./ sqrt(v);\n        stats.pdiff = 2 * ( 1 - tcdf(abs(stats.tdiff),dfediff) );\n        stats.dfediff = dfediff;\n    end\n\n\n\n\nelse\n    % ======================================\n    %\n    %\n    % Multivariate stats: MSE, cov(Y), r(Y)\n    % Useful for simulating t-values under dependence\n    %\n    % ======================================\n\n    % --------------------------------------\n    % * Mean squared error\n    % --------------------------------------\n\n    % additional output: covariance matrix for Ymean and zdiff across time\n    % (columns)\n    % and correlation matrix for Ymean and zdiff\n    % used in Monte Carlo simulations for controlling false positives\n    % across columns\n\n    MSE = (e'*W*e)/dfe;             % Mean square error\n\n    if dobtwn\n        MSEdiff = (ediff'*W*ediff)/dfediff;\n    end\n\n\n    % --------------------------------------\n    % * Estimated covariance and correlation\n    %   Estimated between-subjects variance (v)\n    % --------------------------------------\n\n    xy = invxwx * MSE;           % Covariance matrix for Ymean;\n\n    xy = 0.5*(xy+xy');              % Remove rounding error\n\n    if dobtwn\n        xydiff = inv(bcon'*W*bcon)*MSEdiff;           % Covariance matrix for Ymean;\n        xydiff = 0.5*(xydiff+xydiff');\n    end\n\n    v = diag(xy);                   % Variance for Ymean\n\n    if dobtwn\n        vdiff = diag(xydiff);\n    end\n\n    r = xy./sqrt(v*v');             % Correlation matrix for Ymean\n\n    if dobtwn\n        rdiff = xydiff./sqrt(vdiff*vdiff');         % Correlation matrix for Ymean\n    end\n\n    stats.descrip1 = 'Multivariate stats for test against zero:';\n    stats.r = r;\n    stats.v = v;\n    stats.xy = xy;\n\n    stats.dfe = dfe;\n    stats.t = Ymean ./ sqrt(v');\n    stats.p = 2 * ( 1 - tcdf(abs(stats.t),dfe) );\n\n    if dobtwn\n        stats.descrip2 = 'Univariate stats for between-case contrast:';\n        stats.rdiff = rdiff;\n        stats.vdiff = vdiff;\n        stats.xydiff = xydiff;\n\n        stats.dfediff = dfediff;\n        \n        stats.tdiff = Ydiff ./ sqrt(vdiff');\n        stats.p = 2 * ( 1 - tcdf(abs(stats.tdiff),dfediff) );\n    end\nend\n\n\nreturn\n\n\n\n\n\n\n\n\nfunction [dfe,dfediff] = get_dfe(m,n,X,hat,varY,dobtwn,hatdiff,bcon)\n\ndfediff = [];\n\n% Set up residual-forming matrix\n% --------------------------------------\ndfe_v = zeros(n,1);\nR = eye(m) - X*hat;    % residual inducing matrix\n\n% contrast, if entered\nif dobtwn\n    dfe_vdiff = zeros(n,1);\n    Rdiff = eye(m) - bcon * hatdiff;\nend\n\n% Calculate effective degrees of freedom\n% --------------------------------------\n\nhave_unique_vars = size(varY,2) == n;\n\nif ~have_unique_vars\n\n    % Only one (pooled?) vector of variance estimates\n    % --------------------------------------\n    V = diag(varY(:,1));\n    dfe = (trace(R*V)^2)/trace(R*V*R*V);       % Satherwaite approximation\n    if dobtwn, dfediff = (trace(Rdiff*V)^2)/trace(Rdiff*V*Rdiff*V); end\nelse\n    % Variance estimates for each data vector\n    % --------------------------------------\n    for i=1:n,\n\n        % make diagonal matrix of variances\n        V = diag(varY(:,i));\n\n        dfe_v(i) = (trace(R*V)^2)/trace(R*V*R*V);       % Satherwaite approximation\n\n        if dobtwn\n            dfe_vdiff(i) = (trace(Rdiff*V)^2)/trace(Rdiff*V*Rdiff*V);\n        end\n\n    end\n\n    dfe = mean(dfe_v);               % Calculate average df over all columns (pool over data vectors)\n    if dobtwn\n        dfediff = mean(dfe_vdiff);\n    end\n\nend\n\nreturn\n\n\n\n\n\nfunction bool = is_entered(x)\n\nbool = exist('x','var') && ~isempty(x);\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.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5616399404366824}}
{"text": "function denu=tide_oload(tut,odisp)\n\nD2R=pi/180;\nargs=[1.40519E-4, 2.0,-2.0, 0.0, 0.00;  % M2 \n      1.45444E-4, 0.0, 0.0, 0.0, 0.00;  % S2 \n      1.37880E-4, 2.0,-3.0, 1.0, 0.00;  % N2 \n      1.45842E-4, 2.0, 0.0, 0.0, 0.00;  % K2 \n      0.72921E-4, 1.0, 0.0, 0.0, 0.25;  % K1 \n      0.67598E-4, 1.0,-2.0, 0.0,-0.25;  % O1 \n      0.72523E-4,-1.0, 0.0, 0.0,-0.25;  % P1 \n      0.64959E-4, 1.0,-3.0, 1.0,-0.25;  % Q1 \n      0.53234E-5, 0.0, 2.0, 0.0, 0.00;  % Mf \n      0.26392E-5, 0.0, 1.0,-1.0, 0.00;  % Mm \n      0.03982E-5, 2.0, 0.0, 0.0, 0.00];  % Ssa \nep1975=[1975,1,1,0,0,0];\ndp=zeros(3,1);\n\n%angular argument\nep=time2epoch(tut);\nfday=ep(4)*3600.0+ep(5)*60.0+ep(6);\nep(4)=0;ep(5)=0;ep(6)=0.0;\ndays=timediff(epoch2time(ep),epoch2time(ep1975))/86400.0+1.0;\nt=(27392.500528+1.000000035*days)/36525.0;\nt2=t*t; t3=t2*t;\na(1)=fday;\na(2)=(279.69668+36000.768930485*t+3.03E-4*t2)*D2R;% H0 \na(3)=(270.434358+481267.88314137*t-0.001133*t2+1.9E-6*t3)*D2R;% S0 \na(4)=(334.329653+4069.0340329577*t-0.010325*t2-1.2E-5*t3)*D2R;% P0 \na(5)=2.0*pi;\n\n%dispalcements by 11 constituents\nfor i=1:11\n    ang=0;\n    for j=1:5\n        ang=ang+a(j)*args(i,j);\n    end\n    for j=1:3\n        dp(j)=dp(j)+odisp(i,j)*cos(ang-odisp(i,j+3)*D2R);\n    end\nend\n\ndenu(1)=-dp(2);\ndenu(2)=-dp(3);\ndenu(3)=dp(1);\n\nreturn\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/tides/tide_oload.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5616399386257968}}
{"text": "function Y = invariantMultiply( psfMatData, X, padsize );\n%\n%           Y = invariantMultiply( psfMatData, X, padsize );\n%\n%  This function computes the multiplication of a spatially invariant\n%  point spread function (PSF) times an image (i.e., convolution):\n%                y = A*x\n%\n%  Here we assume A is made up of a single PSF whose extent may be\n%  (much) smaller than the image.\n%\n%  Input:\n%   psfMatData  -  complex array containing the matrix data, usually\n%                  computed from onePsfMatrix.m\n%            X  -  array containing the image to which the psfMatrix\n%                  is to be multiplied.\n%\n%  Output:\n%            Y  -  contains the result after PSF multiplication.\n%\n\n%  J. Nagy  1/7/02\n\nimsize = size( X ) - 2*padsize;\n\n%\n%  In order for this to be consistent for 2-D and 3-D images, we need to make \n%  sure there is a third dimension ...\n%\nif length(imsize) == 1\n  imsize = [imsize, 1, 1];\n  padsize = [padsize, 0, 0];\nelseif length(imsize) == 2\n  imsize = [imsize, 1];\n  padsize = [padsize, 0];\nend\n \n%\n%  partition_info computes number of subregions, and their sizes\n%\n[nregions, rsize] = partition_info(imsize, padsize);\n\n%\n%  Coding the rest of this will be easier if all of the image subregions\n%  have the same dimensions.  If it's not, we pad with a few zeros to make\n%  it so ...\n%\npadsize1 = rsize .* nregions - imsize;\nif any( padsize1 < 0 )\n  error('Something is wrong here ...')\nend\nX = padarray(X, padsize1, 'post');\n\nY = zeros( size(X) );\n\n%\n%  Now we get information about beginning and ending indices of subregions\n%  so we can \"put\" and \"get\" subregions correctly ...\n%\n[RIidx, RJidx, RKidx] = region_indices( nregions, rsize );\n[EIidx, EJidx, EKidx] = eregion_indices( RIidx, RJidx, RKidx, 2*padsize );\nTidx = [padsize+1; padsize+rsize];\n\n%\n%  Now loop over all the subregions ...\n%\nfor k = 1:nregions(3)\n  for j = 1:nregions(2)\n    for i = 1:nregions(1)\n      Xt = X(EIidx(i,1):EIidx(i,2), EJidx(j,1):EJidx(j,2), EKidx(k,1):EKidx(k,2));\n\n      Yt = multiplyOneRegion( psfMatData, Xt );\n      \n      Y(RIidx(i,1):RIidx(i,2), RJidx(j,1):RJidx(j,2), RKidx(k,1):RKidx(k,2)) = ...\n           Yt(Tidx(1,1):Tidx(2,1), Tidx(1,2):Tidx(2,2), Tidx(1,3):Tidx(2,3));\n    end\n  end\nend\n\n\nY = Y(1:imsize(1), 1:imsize(2), 1:imsize(3));\n\n\n", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/Extra/prblur_tools/@psfMatrix/private/invariantMultiply.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.561622839603711}}
{"text": "function [cm] = km2cm(km)\n% Convert length from kilometers to centimeters.\n% Chad A. Greene 2012\ncm = km*100000;", "meta": {"author": "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/km2cm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5616228330148889}}
{"text": "function airy_bi_values_test ( )\n\n%*****************************************************************************80\n%\n%% AIRY_BI_VALUES_TEST demonstrates the use of AIRY_BI_VALUES.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    13 April 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'AIRY_BI_VALUES_TEST:\\n' );\n  fprintf ( 1, '  AIRY_BI_VALUES stores values of \\n' );\n  fprintf ( 1, '  the Airy function Bi(X).\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '      X           Bi(X)\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x, bi ] = airy_bi_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fprintf ( 1, '  %12f  %24.16f\\n', x, bi );\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/airy_bi_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.8031737869342624, "lm_q1q2_score": 0.5616228113247311}}
{"text": "%[2006]-\"A GA-based feature selection and parameters optimization for\n%support vector machines\"\n\n% (9/12/2020)\n\nfunction GA = jGeneticAlgorithmTour(feat,label,opts)\n% Parameters \nCR        = 0.8;   % crossover rate\nMR        = 0.01;  % mutation rate\nTour_size = 3;     % tournament size\n\nif isfield(opts,'N'), N = opts.N; end\nif isfield(opts,'T'), max_Iter = opts.T; end\nif isfield(opts,'CR'), CR = opts.CR; end\nif isfield(opts,'MR'), MR = opts.MR; end\nif isfield(opts,'Ts'), Tour_size = opts.Ts; end\n\n% Objective function\nfun = @jFitnessFunction; \n% Number of dimensions\ndim = size(feat,2);\n% Initial \nX   = jInitialization(N,dim); \n% Fitness \nfit  = zeros(1,N); \nfitG = inf; \nfor i = 1:N\n  fit(i) = fun(feat,label,X(i,:),opts);\n  % Best update\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;\n% Generations\nwhile t <= max_Iter\n  % Preparation  \n  Xc1   = zeros(1,dim);\n  Xc2   = zeros(1,dim); \n  fitC1 = ones(1,1);\n  fitC2 = ones(1,1);\n  z     = 1;\n  for i = 1:N\n    if rand() < CR\n      % Select two parents \n      k1 = jTournamentSelection(fit,Tour_size,N);\n      k2 = jTournamentSelection(fit,Tour_size,N);\n      % Store parents \n      P1 = X(k1,:); \n      P2 = X(k2,:);\n      % Single point crossover\n      ind = randi([1, dim - 1]);\n      % Crossover between two parents\n      Xc1(z,:) = [P1(1:ind), P2(ind + 1:dim)]; \n      Xc2(z,:) = [P2(1:ind), P1(ind + 1:dim)]; \n      % Mutation\n      for d = 1:dim\n        % First child\n        if rand() < MR\n          Xc1(z,d) = 1 - Xc1(z,d);\n        end\n        % Second child\n        if rand() < MR\n          Xc2(z,d) = 1 - Xc2(z,d);\n        end        \n      end\n      % Fitness\n      fitC1(1,z) = fun(feat,label,Xc1(z,:),opts);\n      fitC2(1,z) = fun(feat,label,Xc2(z,:),opts);\n      z = z + 1;\n    end\n  end\n  % Merge population\n  XX = [X; Xc1; Xc2];\n  FF = [fit, fitC1, fitC2]; \n  % Select N best solution \n  [FF, idx] = sort(FF,'ascend');\n  X         = XX(idx(1:N),:);\n  fit       = FF(1:N);\n  % Best agent\n  if fit(1) < fitG\n    fitG = fit(1);\n    Xgb  = X(1,:);\n  end\n  % Save\n  curve(t) = fitG; \n  fprintf('\\nGeneration %d Best (GA Tournament)= %f',t,curve(t))\n  t = t + 1;\nend\n% Select features based on selected index\nPos   = 1:dim;\nSf    = Pos(Xgb == 1); \nsFeat = feat(:,Sf); \n% Store results\nGA.sf = Sf; \nGA.ff = sFeat; \nGA.nf = length(Sf);\nGA.c  = curve; \nGA.f  = feat;\nGA.l  = label;\nend\n\n\n%// Tournament Selection //\nfunction Index = jTournamentSelection(fit,Tour_size,N)\n% Random positions based on position & Tournament Size\nTour_idx  = randsample(N,Tour_size);\n% Select ftiness value based on position selected by tournament \nTour_fit  = fit(Tour_idx); \n% Get position of best ftiness value (win tournament)\n[~, idx]  = min(Tour_fit);\n% Store the position\nIndex     = Tour_idx(idx);\nend\n\n\nfunction X = jInitialization(N,dim)\n% Initialize X vectors\nX = zeros(N,dim);\nfor i = 1:N\n  for d = 1:dim \n    if rand() > 0.5\n      X(i,d) = 1;\n    end\n  end\nend\nend\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/jGeneticAlgorithmTour.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.561622811324731}}
{"text": "function [Btuph] = hpe2Btuph(hpe)\n% Convert power from electric horsepower to British \n% thermal units per hour. \n% Chad A. Greene 2012\nBtuph = hpe*2545.457658313;", "meta": {"author": "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/hpe2Btuph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5615635841497204}}
{"text": "function [y,sy,st] = spm_mci_sens_init (R,P,M,U)\n% Compute sensitivity to initial state \n% FORMAT [y,sy,st] = spm_mci_sens_init (R,P,M,U)\n%\n% R         Initial state\n% P         Parameters\n% M         Model structure\n% U         Inputs  [Nin x N]\n%     \n% y         Outputs     [N x Nout]\n% sy        Output Sensitivity, dy/dP [N x Nout x Nparams]\n% st        Status flag (0 for OK, -1 for problem)\n%           ... evaluated at the N time points in M.t\n%\n% M.f       Flow function dx/dt=f(x,u,P,M)\n% M.g       Observation function y=g(x,u,P,M)\n%\n% This function uses Matlab's ODE suite \n%\n% B. Sengupta, K. Friston and W. Penny (2014) Efficient Gradient\n% Computation for Dynamical Models. Neuroimage,98, 521-527. \n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny and Biswa Sengupta\n% $Id: spm_mci_sens_init.m 6697 2016-01-27 14:57:28Z spm $\n\ny=[];sy=[];x=[];sx=[];\nst=0;\n\n% Tolerances for ode15s \ntry, tol.rel=M.reltol; catch, tol.rel=1e-2; end\ntry, tol.abs=M.abstol; catch, tol.abs=1e-4; end\n\nif isempty(U)\n    U=zeros(1,M.N);\nend\n\ninit_t=0;\nfinal_t=M.T;\ninit_state=R;\n\n% parameters for the integrator\noptions = odeset('AbsTol',tol.abs,'RelTol',tol.rel);\n\n% Allocate matrices\nx=zeros(M.N,M.n);\ny=zeros(M.N,M.l);\nsx=zeros(M.N,M.n,M.n);\nsy=zeros(M.N,M.l,M.n);\n\n% initialise state-sensitivites\nNx=length(M.x0);\nNp=length(P);\nS0=eye(M.n);\ninit_sens = S0(:);\n\n% Use Klopfenstein-Shampine integrator from Matlab's ODE suite\n[T,V] = ode15s(@(t,v) int_states_init(t,v,U,P,M),[init_t final_t], [init_state; init_sens], options);\n\n% T     Times\n% V     States and sensitivities\n\n% Extract states\nxm=V(:,1:Nx);\n\n% Interpolate states to times M.t\nx=interp1q(T,xm,M.t);\n\n% Interpolate state sensitivities to times M.t\nsxm=interp1q(T,V(:,Nx+1:end),M.t);\n%sx=reshape(sxm,length(M.t),Nx,Np);\n% Updated Sep 13 2014\nsx=reshape(sxm,length(M.t),Nx,Nx);\n\n% When computing output sensitivities, assume dydx=L, ie not a\n% function of x. Generalise later\n[tmp,L]=feval(M.g,M.x0,U(:,1),P,M);\n\n% Compute output and output sensitivity\nfor n=1:M.N,\n    yout = feval (M.g,x(n,:)',U(:,n),P,M);\n    y(n,:) = yout'; \n    sy(n,:,:)=L*squeeze(sx(n,:,:));\nend\n\nend\n\n%--------------------------------------------------------------------------\nfunction DvDt = int_states_init (t,v,U,P,M)\n% Integrate states and sensitivities to initial conditions\n\nNx=length(M.x0);\nNt=Nx+Nx*Nx;  \n\nstate_ind=1:Nx;\nsens_ind=Nx+1:Nt;\n\n% Find nearest time point for which we have pre-computed input\nif isempty(U)\n    ut=[];\nelse\n    [tmp,ind]=min(abs(t-M.t));\n    ut=U(:,ind);\nend\n\n% initialise state matrix\nDvDt = zeros(Nt,1);\n\n% Flow\nDvDt(1:Nx)=feval(M.f,v(state_ind),ut,P,M);\n\nif isfield(M,'dfdx')\n    Fx = feval(M.dfdx,v(1:Nx),ut,P,M);\nelse\n    Fx = spm_diff(M.f,v(1:Nx),ut,P,M,1);\nend\n    \nSx_old = v(sens_ind);\nSx_old = reshape(Sx_old,Nx,Nx);\n\n% Compute change in sensitivity from old - note absence of Fp term\nSx = Fx*Sx_old;\n\n% Sensitivities\nDvDt(sens_ind)=Sx(:);\n\nend\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/mci/gradients/spm_mci_sens_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5615367169393796}}
{"text": "function [err,XYZdic] = AFNI_Index2XYZcontinuous (Indx, Info, CoordCode)\n%\n%   [err,XYZdic] = AFNI_Index2XYZcontinuous (Indx, Info, [CoordCode])\n%\n%Purpose:\n%   Change from voxel XYZindex (called Voxel Coords in AFNI) to XYZ in mm\n%   The mm and voxel coordinates refer to the values displayed\n%   on the top left corner of AFNI controller.\n%   CoordCode is the one you'd set from the Coord Order plugin\n%\n%\n%Input Parameters:\n%   Indx an Mx3 matrix or an  Mx1 vector containing the voxel indices to be\n%        transformed to voxel coordinates.  (indices start at 0)\n%   Info is the output of BrikInfo\n%   CoordCode is an optional parameter used to specify the coordinates system of the output\n%      if empty or not specified, the default is 'RAI'. The code can be either a string or a vector\n%      of numbers (see AFNI_CoordChange for more on that)\n%\n%Output Parameters:\n%   err : 0 No Problem\n%       : 1 Mucho Problems\n%   XYZdic : The continuous coordinates corresponding to Indx\n%       The coordnate system output is in RAI (DICOM)\n%       unless otherwise specified by CoordCode\n%\n%\n%Key Terms:\n%\n%More Info :\n%   BrikInfo\n%   Test_AFNI_Index2XYZcontinuous\n%   AFNI_XYZcontinuous2Index\n%   Test_AFNI_XYZcontinuous2Index\n%\n% You can also go from index to XYZ using the header field IJK_TO_DICOM_REAL\n%  For instance, say you have voxel indices 12, 2, 4 (matlab indexing 13, 3, 5)\n%  to go from AFNI index to AFNI DICOM RAI you can do:\n%     M = [reshape(Info.IJK_TO_DICOM_REAL, 4, 3)' ; 0 0 0 1];\n%     I = [12 2 4 1]';\n%     X = M*I;\n%     To go from AFNI DICOM RAI to AFNI indices:\n%     I = inv(M)*X;\n%\n%     Author : Ziad Saad\n%     Date : Tue Sep 5 21:48:06 PDT 2000           Latest Modification: Feb 18 04\n%     LBC/NIMH/ National Institutes of Health, Bethesda Maryland\n\n\n%Define the function name for easy referencing\nFuncName = 'AFNI_Index2XYZcontinuous';\n\n%Debug Flag\nDBG = 1;\n\nChangeCoord = 0;\nif (nargin == 3)\n\tif (~isempty(CoordCode)),\n\t\tChangeCoord = 1;\n\tend\nend\n\n\n%initailize return variables\nerr = 1;\nXYZmm = [];\n\n%make sure Indx is the right size\nswitch size(Indx,2),\n\tcase 1, %change 1D index to XYZ index\n\t\t[err, Indx] = AfniIndex2AfniXYZ (Indx, Info.DATASET_DIMENSIONS(1), Info.DATASET_DIMENSIONS(2))\n\tcase 3, %OK\n\totherwise,\n\t\terr = ErrEval(FuncName,'Err_Bad dimension for Indx');\n\t\treturn\nend\n\nXYZmm = Indx;\n\n\t%The equations that would change the indices to coordinate system result in a coordinate system that\n\t% may be any permutation of RAI (like IRA or AIR or IAR or RIA or ARI) so one only needs to find the\n\t%dimension permutation needed to bring the final result to RAI.\n\n\t%determine the ordering map to go from any permutation of RAI to RAI\n\t\t%[maploc(1),jnk] = find(Info.Orientation == 'R');\n\t\t%[maploc(2),jnk] = find(Info.Orientation == 'A');\n\t\t%[maploc(3),jnk] = find(Info.Orientation == 'I');\n\t\n\t%pre - Wed May 23 18:20:56 PDT 2001 - WRONG !\n\t\t%XYZmm(:, maploc(1)) = Info.ORIGIN(1) + Indx(:,1) .* Info.DELTA(1);\n\t\t%XYZmm(:, maploc(2)) = Info.ORIGIN(2) + Indx(:,2) .* Info.DELTA(2);\n\t\t%XYZmm(:, maploc(3)) = Info.ORIGIN(3) + Indx(:,3) .* Info.DELTA(3);\n\n\t%post - Wed May 23 18:20:56 PDT 2001 - WRONG!\n\t\t%XYZmm(:, 1) = Info.ORIGIN(maploc(1)) + Indx(:,maploc(1)) .* Info.DELTA(maploc(1));\n\t\t%XYZmm(:, 2) = Info.ORIGIN(maploc(2)) + Indx(:,maploc(2)) .* Info.DELTA(maploc(2));\n\t\t%XYZmm(:, 3) = Info.ORIGIN(maploc(3)) + Indx(:,maploc(3)) .* Info.DELTA(maploc(3));\n\t\n   %Feb 18 04, back to the original\n      XYZmm(:, 1) = Info.ORIGIN(1) + Indx(:,1) .* Info.DELTA(1);\n\t\tXYZmm(:, 2) = Info.ORIGIN(2) + Indx(:,2) .* Info.DELTA(2);\n\t\tXYZmm(:, 3) = Info.ORIGIN(3) + Indx(:,3) .* Info.DELTA(3);\n      %Now this is in the axis orientation which is Info.Orientation(:,1)' called 3dmm in thd_coords.c\n      [err,XYZdic, map] = THD_3dmm_to_dicomm (Info, XYZmm);\n\nif (ChangeCoord),\n\t[err, maplocation, mapsign, XYZdic] = AFNI_CoordChange ('RAI', CoordCode, XYZdic);\nend\n\nerr = 0;\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/afni/AFNI_Index2XYZcontinuous.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5615367169393795}}
{"text": "function W = weightingscheme(cases,wfct,varargin)\n\n%\n% INTERNAL FUNCTION\n%\n\n% Copyright (c) 2011,  KULeuven-ESAT-SCD, License & help @ http://www.esat.kuleuven.be/sista/lssvmlab\n\nswitch wfct\n    \n    case {'WHuber','whuber'}\n        b = varargin{1};\n        cases = abs(cases);\n        temp = 1;\n        W = temp.*(cases<b) + temp.*(cases>=b).*(b./cases);\n        \n    case {'WLogistic','wlogistic'}\n        W = tanh(cases)./cases;\n        \n    case {'WHampel','whampel'}\n       cases = abs(cases);\n       % defaults for c1 and c2\n       c1=2.5; c2=3; \n       %[c1,c2] = adaptweight(cases);\n       dc = c2-c1;\n       temp = 1; \n       W = temp.*(cases<=c1) + ...\n           temp.*(cases<=c2 & cases>c1).*((c2-cases)./dc) + ...\n           temp.*(cases>c2).*10e-8;\n       \n    case {'WMyriad','wmyriad'}\n        %K = 0.5*iqr(cases);\n        K = varargin{1};\n        W = K^2./(K^2+cases.^2);  \nend", "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/weightingscheme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5615367113399924}}
{"text": "function [xn] = normalize(x_kk,fc,cc,kc,alpha_c)\n\n%normalize\n%\n%[xn] = normalize(x_kk,fc,cc,kc,alpha_c)\n%\n%Computes the normalized coordinates xn given the pixel coordinates x_kk\n%and the intrinsic camera parameters fc, cc and kc.\n%\n%INPUT: x_kk: Feature locations on the images\n%       fc: Camera focal length\n%       cc: Principal point coordinates\n%       kc: Distortion coefficients\n%       alpha_c: Skew coefficient\n%\n%OUTPUT: xn: Normalized feature locations on the image plane (a 2XN matrix)\n%\n%Important functions called within that program:\n%\n%comp_distortion_oulu: undistort pixel coordinates.\n\nif nargin < 5,\n   alpha_c = 0;\n   if nargin < 4;\n      kc = [0;0;0;0;0];\n      if nargin < 3;\n         cc = [0;0];\n         if nargin < 2,\n            fc = [1;1];\n         end;\n      end;\n   end;\nend;\n\n\n% First: Subtract principal point, and divide by the focal length:\nx_distort = [(x_kk(1,:) - cc(1))/fc(1);(x_kk(2,:) - cc(2))/fc(2)];\n\n% Second: undo skew\nx_distort(1,:) = x_distort(1,:) - alpha_c * x_distort(2,:);\n\nif norm(kc) ~= 0,\n\t% Third: Compensate for lens distortion:\n\t% xn = comp_distortion_oulu(x_distort,kc); \n  xn = undistort(x_distort, kc);\nelse\n   xn = x_distort;\nend;\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/depthImproveStructureIO/normalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.561485047120306}}
{"text": "function rf=lpcla2rf(la)\n%LPCLA2RF Convert log areas to reflection coefficients RF=(LA)\n\n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: lpcla2rf.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[nf,p2]=size(la);\nrf=-tanh((la(:,1:p2-1)-la(:,2:p2))/2);\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/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/lpcla2rf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5614850417518239}}
{"text": "function f = perform_wavortho_transf(f,Jmin,dir,options)\n\n% perform_wavortho_transf - compute orthogonal wavelet transform\n%\n%   fw = perform_wavortho_transf(f,Jmin,dir,options);\n%\n%   You can give the filter in options.h.\n%\n%   Works in arbitrary dimension.\n%\n%   Copyright (c) 2009 Gabriel Peyre\n\noptions.null = 0;\nh = getoptions(options,'h', compute_wavelet_filter('Daubechies',4) );\ng = [0 h(length(h):-1:2)] .* (-1).^(1:length(h));\n\nn = size(f,1); \nJmax = log2(n)-1; \n\nif dir==1\n    %%% FORWARD %%%\n    for j=Jmax:-1:Jmin\n        sel = 1:2^(j+1);\n        a = subselect(f,sel);\n        for d=1:nb_dims(f)\n            a = cat(d, subsampling(cconv(a,h,d),d), subsampling(cconv(a,g,d),d) );\n        end\n        f = subassign(f,sel,a);\n    end\nelse\n    %%% FORWARD %%%\n    for j=Jmin:Jmax\n        sel = 1:2^(j+1);\n        a = subselect(f,sel);\n        for d=1:nb_dims(f)\n            w = subselectdim(a,2^j+1:2^(j+1),d);\n            a = subselectdim(a,1:2^j,d);\n            a = cconv(upsampling(a,d),reverse(h),d) + cconv(upsampling(w,d),reverse(g),d);\n        end\n        f = subassign(f,sel,a);\n    end    \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction f = subselect(f,sel)\nswitch nb_dims(f)\n    case 1\n        f = f(sel);\n    case 2\n        f = f(sel,sel);\n    case 3\n        f = f(sel,sel,sel);\n    case 4\n        f = f(sel,sel,sel,sel);\n    case 5\n        f = f(sel,sel,sel,sel,sel);\n    case 6\n        f = f(sel,sel,sel,sel,sel,sel);\n    case 7\n        f = f(sel,sel,sel,sel,sel,sel,sel);\n    case 8\n        f = f(sel,sel,sel,sel,sel,sel,sel,sel);\n    otherwise\n        error('Not implemented');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction f = subselectdim(f,sel,d)\nswitch d\n    case 1\n        f = f(sel,:,:,:,:,:,:,:);\n    case 2\n        f = f(:,sel,:,:,:,:,:,:);\n    case 3\n        f = f(:,:,sel,:,:,:,:,:);\n    case 4\n        f = f(:,:,:,sel,:,:,:,:);\n    case 5\n        f = f(:,:,:,:,sel,:,:,:);\n    case 6\n        f = f(:,:,:,:,:,sel,:,:);\n    case 7\n        f = f(:,:,:,:,:,:,sel,:);\n    case 8\n        f = f(:,:,:,:,:,:,:,sel);\n    otherwise\n        error('Not implemented');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction f = subassign(f,sel,g)\nswitch nb_dims(f)\n    case 1\n        f(sel) = g;\n    case 2\n        f(sel,sel) = g;\n    case 3\n        f(sel,sel,sel) = g;\n    case 4\n        f(sel,sel,sel,sel) = g;\n    case 5\n        f(sel,sel,sel,sel,sel) = g;\n    case 6\n        f(sel,sel,sel,sel,sel,sel) = g;\n    case 7\n        f(sel,sel,sel,sel,sel,sel,sel) = g;\n    case 8\n        f(sel,sel,sel,sel,sel,sel,sel,sel) = g;\n    otherwise\n        error('Not implemented');\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_optim/toolbox/perform_wavortho_transf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5614850408898753}}
{"text": "function [rar,yclean] = spm_rar (Z,p,m,verbose)\n% Bayesian autoregressive modelling with zero-mean Gaussian mixture noise\n% function [rar,yclean] = spm_rar (Z,p,m,verbose)\n%\n% Z          [N x 1] vector of data points\n% p          Number of AR coefficients\n% m          Number of mixture components (default=2)\n% verbose    0/1 to printout inner workings (default=0)\n%\n% rar        Returned model \n% yclean     'Clean' data (ie. with outlier errors removed)\n%\n% -------------------------------------------------------\n% The fields in rar are:\n%\n% p                The number of AR coefficients\n% m                The number of components\n% fm               The negative free energy\n%\n%                  In the field priors:\n% lambda_0         Dirichlet parameters for mixing coeffs\n% b_0,c_0          Gamma parameters for precisions\n%\n%                  In the field posts:\n% lambda           Dirichlet parameters  for mixing coeffs\n% b,c              Gamma parameters for precisions\n% a_mean           AR parameters (posterior mean)\n% a_cov            AR parameters (posterior cov)\n% b_alpha,c_alpha  Gamma parameters for weight precisions\n%\n%                  Mean posterior values:\n% pi               mixing coefficients (lambda/sum(lambda))\n% variances        variances (1./(b.*c))\n%\n% gamma            the responsibilities of each noise component\n%\n% For details of algorithm see:\n%\n% S.J. Roberts and W.D. Penny. Variational Bayes for Generalised Autoregressive \n% models. IEEE Transactions on Signal Processing, 50(9):2245-2257, 2002\n%___________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: spm_rar.m 1276 2008-03-28 18:29:19Z guillaume $\n\nif nargin < 3 | isempty(m)\n    m=2;\nend\n\nif nargin < 4 | isempty(verbose)\n  verbose=0;\nend\n\nif (m==1)\n  rar=spm_ar(Z,p);\n  return;\nend\n\nN=length(Z);\n\n% Initialise AR coefficients to maximum likelihood solution\nZ=Z(:);\ny=Z(p+1:end);\nfor i=1:p,\n    x(:,i)=Z(p-i+1:end-i);\nend\nx=-x;\ny2=y.^2;\nxt=x';\nN=size(x,1);\nwun=ones(N,1);\n\na_mean = pinv(x)*y;\ny_pred = x*a_mean;\nerr=y-y_pred;\nv=mean((y-y_pred).^2);\na_cov = v*inv(x'*x);\n\n% Set mixing priors\nlambda_0=5;\n\n% Setting to these values gives updates for mean_alpha\n% v. close to evidence framework \nbishop_prior=1;\nif bishop_prior\n  b_alpha_prior=1000;\n  c_alpha_prior=0.001;\n  b_0=1000;\n  c_0=0.001;\nend\nmean_alpha_prior=b_alpha_prior*c_alpha_prior;\n\n% Cluster on absolute difference from mean\nzmix=spm_kmeans1(abs(err-mean(err)),m);\n% Posterior for mixers\nlambda=100*zmix.pi;\nzmean=[zmix.m].^2;\n% Posterior for precisions\nvar_precision=1/std(zmean)^2;\nfor s=1:m,\n      % Set so that b*c=precision and  b^2*c=var_precision\n      precision=1/zmean(s);\n      b(s)=var_precision/precision;\n      c(s)=(precision^2)/var_precision;\nend\n\n% Initialise weight precision posterior\nE_w=a_mean'*a_mean;\nb_alpha=0.5*E_w+0.5*trace(a_cov)+(1/b_alpha_prior);\nb_alpha=1/b_alpha;\nc_alpha=0.5*p+c_alpha_prior;\nmean_alpha=b_alpha*c_alpha;\n\nif verbose\n  disp('Init');\n  disp('AR Coefficients');\n  a_mean(:)'\n  for s=1:m, \n    disp(sprintf('State %d mix=%1.2f var=%1.2f',s,lambda(s)/sum(lambda),1/(b(s)*c(s))));\n  end\nend\n\nlik=[];\ntol=0.0001;\nmax_loops=32;\nWLOOPS=5;\nfor loops=1:max_loops,\n    \n    % E-step\n    lambda_tot=sum(lambda);\n    ypred=x*a_mean;\n    ypred2=ypred.^2;\n    y_err=sum(xt.*(a_cov*xt));\n    tv=y2-2*ypred.*y+y_err'+ypred2;\n    tv=tv';\n    for s=1:m,\n        log_tilde_pi(s)=psi(lambda(s))-psi(lambda_tot);\n        log_tilde_beta(s)=psi(c(s))+log(b(s));\n        tilde_pi(s)=exp(log_tilde_pi(s));\n        tilde_beta(s)=exp(log_tilde_beta(s));\n        mean_beta(s)=c(s)*b(s);\n        tilde_var(s,:)=tv;\n        gamma(s,:)=tilde_pi(s)*(tilde_beta(s)^0.5)*exp(-0.5*mean_beta(s)*tv);\n    end\n    gamma_n=sum(gamma);\n    for s=1:m,\n        if mean(gamma_n) > eps\n            % If component still exists\n            gamma(s,:)=gamma(s,:)./gamma_n;\n        end\n    end\n    \n    % M-step\n    % Part I\n    for s=1:m,\n        pi_bar(s)=mean(gamma(s,:));\n        N_bar(s)=N*pi_bar(s);\n        mean_bar(s)=mean(gamma(s,:)'.*y);\n        dg=diag(gamma(s,:));\n        x_bar(s,:)=mean(dg*x);\n        var_bar_mu(s)=mean(gamma(s,:).*tilde_var(s,:));\n    end\n    \n    % CALCULATE THE FREE ENERGY\n    avg_likelihood=sum(N_bar.*(log_tilde_pi+0.5*log_tilde_beta));\n    fit=-0.5*N*sum(mean_beta.*var_bar_mu);\n    % Ensure that 0 log 0 = 0\n    ent_s=sum(sum(-gamma.*log(gamma+eps)));\n    avg_likelihood=avg_likelihood+fit+ent_s;\n    lambda_p=lambda_0*ones(1,m);\n    kl_dir=spm_kl_dirichlet(lambda,lambda_p,log_tilde_pi);\n    kl_gamm=0;\n    for s=1:m,\n        kl_gamm=kl_gamm+spm_kl_gamma(b(s),c(s),b_0,c_0);\n    end\n    kl_weights=spm_kl_normal(a_mean,a_cov,zeros(1,p),(1/mean_alpha)*eye(p));\n    kl_alpha=spm_kl_gamma(b_alpha,c_alpha,b_alpha_prior,c_alpha_prior);\n    fm= avg_likelihood - kl_dir - kl_gamm - kl_weights - kl_alpha;\n    \n    % Convergence criterion\n    oldlik=lik;\n    lik=fm;\n    \n    if (mod(loops-1,WLOOPS)==0)\n        if (loops>1)\n            if abs((lik-oldlik)/lik) < tol\n                break;\n            end\n        end\n    end\n    \n    % M-Step: Part II\n    for s=1:m,\n        % Mixers\n        lambda(s)=N_bar(s)+lambda_0;\n        % Precisions\n        b(s)=1/(0.5*N*var_bar_mu(s)+1/b_0);\n        c(s)=0.5*N_bar(s)+c_0;\n        mean_beta(s)=c(s)*b(s);\n    end\n    \n    if mod(loops,WLOOPS)==0\n        % Weight precisions\n        E_w=0.5*a_mean'*a_mean;\n        b_alpha=E_w+0.5*trace(a_cov)+(1/b_alpha_prior);\n        b_alpha=1/b_alpha;\n        c_alpha=0.5*p+c_alpha_prior;\n        mean_alpha=b_alpha*c_alpha;\n        \n        % AR coefficients\n        cc=zeros(p,p);\n        cw=zeros(p,1);\n        for s=1:m,\n            dg=diag(gamma(s,:));\n            cc=cc+mean_beta(s)*x'*dg*x;\n            cw=cw+mean_beta(s)*x'*dg*y;\n        end\n        cc=cc+mean_alpha*eye(p);\n        a_cov=inv(cc);\n        a_mean=a_cov*cw;\n    end\n    \n    if verbose\n        disp(sprintf('It=%d, L_AV =%1.2f, KL Mix=%1.2f, KL Prec=%1.2f, KL-AR=%1.2f, KL-alpha=%1.2f, Fm=%1.2f',loops,avg_likelihood,kl_dir,kl_gamm,kl_weights,kl_alpha,fm));\n    end\n    \nend\n\n% Put variables into data structure\nrar.posts.a_mean=a_mean;\nrar.posts.a_cov=a_cov;\nrar.m=m;\nrar.fm=fm;\nrar.priors.lambda_0=lambda_0;\nrar.priors.c_0=c_0;\nrar.priors.b_0=b_0;\n\nfor k=1:m,\n  rar.posts.lambda(k)=lambda(k);\nend\n\nfor k=1:m,\n  rar.posts.c(k)=c(k);\n  rar.posts.b(k)=b(k);\nend\n\nfor k=1:m,\n  rar.pi(k)=lambda(k)/sum(lambda);\nend\nrar.variances=1./(b.*c);\n\n% Pre-pad gamma with zeros to get original length time series\nrar.gamma=[zeros(m,p),gamma];\n\n% Get 'clean' data\nif m > 1\n    [tmp,outlier_class]=min(rar.pi);\n    e=y-ypred;\n    outlier_error=gamma(outlier_class,:)'.*e;\n    yclean=ypred+e-outlier_error;\n    yclean=[Z(1:p);yclean];  % Pre-padding\nelse\n    yclean=Z;\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/toolbox/spectral/spm_rar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5614850350904187}}
{"text": "classdef OptimizerAugmentedLagrangian < Optimizer\n\n    properties (GetAccess = public, SetAccess = protected)\n        type = 'Augmented Lagrangian';\n    end\n\n    properties (Access = private)\n        tau\n        lineSearchTrials\n        lineSearch\n        costOld\n        upperBound\n        lowerBound\n        tol = 1e-8\n        nX\n        nConstr\n        hasConverged\n        acceptableStep\n        oldDesignVariable\n        oldCost\n        incrementalScheme\n        hasFinished\n        mOld\n        meritNew\n        penalty\n        meritGradient\n\n        globalCost\n        globalConstraint\n        globalCostGradient\n        globalMerit\n        globalLineSearch\n        globalDual\n        globalDesignVar\n    end\n\n    methods (Access = public) \n        \n        function obj = OptimizerAugmentedLagrangian(cParams)\n            obj.initOptimizer(cParams);\n            obj.init(cParams);\n            obj.outputFunction.monitoring.create(cParams);\n            obj.createPrimalUpdater(cParams);\n            obj.createDualUpdater(cParams);\n            obj.prepareFirstIter();\n        end\n\n        function obj = solveProblem(obj)\n            obj.hasConverged = false;\n            obj.cost.computeFunctionAndGradient();\n            obj.constraint.computeFunctionAndGradient();\n%             obj.saveVariablesForAnalysis();\n            obj.hasFinished = 0;\n            obj.printOptimizerVariable();\n            while ~obj.hasFinished\n%             while ~obj.hasConverged\n                obj.update();\n                obj.updateIterInfo();\n                obj.updateMonitoring();\n                obj.checkConvergence();\n                obj.printOptimizerVariable();\n%                 obj.saveVariablesForAnalysis();\n            end\n        end\n\n    end\n\n    methods(Access = private)\n\n        function init(obj,cParams)\n            obj.upperBound             = cParams.uncOptimizerSettings.ub;\n            obj.lowerBound             = cParams.uncOptimizerSettings.lb;\n            obj.cost                   = cParams.cost;\n            obj.constraint             = cParams.constraint;\n            obj.nConstr                = cParams.constraint.nSF;\n            obj.designVariable         = cParams.designVar;\n            obj.dualVariable           = cParams.dualVariable;\n            obj.incrementalScheme      = cParams.incrementalScheme;\n            obj.nX                     = length(obj.designVariable.value);\n            obj.maxIter                = cParams.maxIter;\n            obj.hasConverged           = false;\n            obj.nIter                  = 0;\n        end\n\n        function prepareFirstIter(obj)\n            obj.cost.computeFunctionAndGradient();\n            obj.costOld = obj.cost.value;\n            obj.designVariable.updateOld();\n            obj.dualVariable.value = zeros(obj.nConstr,1);\n            obj.penalty            = 10;\n        end\n\n        function obj = update(obj)\n            x0 = obj.designVariable.value;\n            obj.designVariable.update(x0);\n            obj.saveOldValues(x0);\n            obj.mOld = obj.computeMeritFunction(x0);\n            obj.calculateInitialStep();\n            obj.acceptableStep   = false;\n            obj.lineSearchTrials = 0;\n            obj.computeMeritGradient();\n            while ~obj.acceptableStep\n                x = obj.updatePrimal();\n                obj.checkStep(x,x0);\n            end\n            obj.updateOldValues(x);\n        end\n\n        function displayIter(obj,x)\n            m = obj.designVariable.mesh;\n            bm = m.createBoundaryMesh();\n            s.backgroundMesh = m;\n            s.boundaryMesh   = bm;\n            um = UnfittedMesh(s);\n            um.compute(x);\n            figure()\n            um.plot();\n        end\n\n        function obj = calculateInitialStep(obj)\n            obj.cost.computeFunctionAndGradient();\n            obj.constraint.computeFunctionAndGradient();\n            x       = obj.designVariable.value;\n            l       = obj.dualVariable.value;\n            DJ      = obj.cost.gradient;\n            Dg      = obj.constraint.gradient;\n            g       = obj.constraint.value;\n            p       = obj.penalty;\n            DmF     = DJ + Dg*(l + p*g);\n            if obj.nIter == 0\n                factor = 1;\n                obj.primalUpdater.computeFirstStepLength(DmF,x,factor);\n            else\n                factor = 1.05;\n                obj.primalUpdater.increaseStepLength(factor);\n            end\n        end\n\n        function x = updatePrimal(obj)\n            x   = obj.designVariable.value;\n            g   = obj.meritGradient;\n            x   = obj.primalUpdater.update(g,x);\n        end\n\n        function computeMeritGradient(obj)\n            Dh    = obj.constraint.gradient;\n            DJ    = obj.cost.gradient;\n            l     = obj.dualVariable.value;\n            p     = obj.penalty;\n            gPlus = obj.defineConstraintValue();\n            g     = (DJ + Dh*(l + p*gPlus));\n            obj.meritGradient = g;\n        end\n\n        function mF = computeMeritFunction(obj,x)\n            obj.designVariable.update(x)\n            obj.cost.computeFunctionAndGradient();\n            obj.constraint.computeFunctionAndGradient();\n            J      = obj.cost.value;\n            gPlus  = obj.defineConstraintValue();\n            l      = obj.dualVariable.value;\n            rho    = obj.penalty;\n            mF     = J + l'*gPlus + 0.5*rho*(gPlus'*gPlus);\n        end\n\n        function c = defineConstraintValue(obj)\n            c   = obj.constraint.value;\n            l   = obj.dualVariable.value;\n            rho = obj.penalty;\n            for i = 1:obj.nConstr\n                switch obj.constraintCase{i}\n                    case 'EQUALITY'\n                        \n                    case 'INEQUALITY'\n                        c(i) = max(c(i),-l/rho);\n                end\n            end\n        end\n\n        function checkStep(obj,x,x0)\n            mNew = obj.computeMeritFunction(x);\n            if mNew < obj.mOld\n                obj.acceptableStep = true;\n                obj.dualUpdater.updatePenalty(obj.penalty);\n                obj.dualUpdater.update();\n                obj.meritNew = mNew;\n            elseif obj.primalUpdater.isTooSmall()\n%                 error('Convergence could not be achieved (step length too small)')\n                warning('Convergence could not be achieved (step length too small)')\n                obj.acceptableStep = true;\n                obj.meritNew = mNew; % Provisional value\n            else\n                obj.primalUpdater.decreaseStepLength();\n                obj.designVariable.update(x0);\n                obj.lineSearchTrials = obj.lineSearchTrials + 1;\n            end\n        end\n\n        function obj = saveOldValues(obj,x)\n            obj.designVariable.update(x);\n            obj.cost.computeFunctionAndGradient();\n            obj.constraint.computeFunctionAndGradient();\n            obj.oldCost            = obj.cost.value;\n            obj.oldDesignVariable  = x;\n        end\n\n        function obj = updateOldValues(obj,x)\n            obj.designVariable.update(x);\n            obj.cost.computeFunctionAndGradient();\n            obj.constraint.computeFunctionAndGradient();\n        end\n\n        function obj = checkConvergence(obj)\n           if abs(obj.meritNew - obj.mOld) < obj.tol && obj.checkConstraint()\n               obj.hasConverged = true;\n           else\n               \n           end\n\n        end\n\n        function obj = updateMonitoring(obj)\n            s.nIter            = obj.nIter;\n            s.tau              = obj.primalUpdater.tau;\n            s.lineSearch       = obj.lineSearch;\n            s.lineSearchTrials = obj.lineSearchTrials;\n            s.oldCost          = obj.oldCost;\n            s.hasFinished      = obj.hasFinished;\n            s.meritNew         = obj.meritNew;\n            obj.outputFunction.monitoring.compute(s);\n        end\n\n        function updateIterInfo(obj)\n            obj.increaseIter();\n            obj.updateStatus();\n        end\n\n        function increaseIter(obj)\n            obj.nIter = obj.nIter + 1;\n        end\n\n        function updateStatus(obj)\n            obj.hasFinished = obj.hasConverged || obj.hasExceededStepIterations();\n        end\n\n        function itHas = hasExceededStepIterations(obj)\n            iStep = obj.incrementalScheme.iStep;\n            nStep = obj.incrementalScheme.nSteps;\n            itHas = obj.nIter >= obj.maxIter*(iStep/nStep);\n        end\n\n        function saveVariablesForAnalysis(obj)\n            i                           = obj.nIter + 1;\n            obj.globalCost(i)           = obj.cost.value;\n            obj.globalConstraint(:,i)   = obj.constraint.value;\n            obj.globalCostGradient(i)   = norm(obj.cost.gradient);\n            obj.globalMerit(i)          = obj.meritNew;\n            obj.globalLineSearch(i)     = obj.primalUpdater.tau;\n            obj.globalDual(:,i)         = obj.dualVariable.value;\n            obj.globalDesignVar(:,i)    = obj.designVariable.value;\n            if obj.hasConverged\n                c = obj.globalCost;\n                h = obj.globalConstraint;\n                g = obj.globalCostGradient;\n                m = obj.globalMerit;\n                t = obj.globalLineSearch;\n                d = obj.globalDual;\n                v = obj.globalDesignVar;\n                save('name.mat',\"c\",\"g\",\"h\",\"d\",\"v\");\n            end\n        end\n\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/AugmentedLagrangian/OptimizerAugmentedLagrangian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5614850243534548}}
{"text": "function chebyshev_polynomial_test16 ( )\n\n%*****************************************************************************80\n%\n%% CHEBYSHEV_POLYNOMIAL_TEST16 tests W_POLYNOMIAL.\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, 'CHEBYSHEV_POLYNOMIAL_TEST16:\\n' );\n  fprintf ( 1, '  W_POLYNOMIAL_VALUES stores values of\\n' );\n  fprintf ( 1, '  the Chebyshev polynomials.\\n' );\n  fprintf ( 1, '  W_POLYNOMIAL evaluates the polynomial.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '                        Tabulated                 Computed\\n' );\n  fprintf ( 1, '     N        X           W(n,x)                    W(n,x)                     Error\\n' );\n\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, n, x, fx1 ] = w_polynomial_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fx2_vec = w_polynomial ( 1, n, x );\n    fx2 = fx2_vec(1,n+1);\n    e = fx1 - fx2;\n\n    fprintf ( 1, '  %4d  %12f  %24.16e  %24.16e  %8.2g\\n', n, x, fx1, fx2, 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/chebyshev_polynomial/chebyshev_polynomial_test16.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.5614724791454826}}
{"text": "function stroud_test045 ( )\n\n%*****************************************************************************80\n%\n%% TEST045 tests BALL_UNIT_VOLUME_3D.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    06 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 3;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST045\\n' );\n  fprintf ( 1, '  In 3 dimensions:\\n' );\n  fprintf ( 1, '  BALL_UNIT_VOLUME_3D gets the volume of the unit ball.\\n' );\n  fprintf ( 1, '  BALL_UNIT_VOLUME_ND will be called for comparison.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  N    Volume    Method\\n' );\n  fprintf ( 1, '\\n' );\n\n  fprintf ( 1, '  %1d  %12f  %s\\n', n, ball_unit_volume_3d ( ), ...\n    'BALL_UNIT_VOLUME_3D' );\n\n  fprintf ( 1, '  %1d  %12f  %s\\n', n, ball_unit_volume_nd ( n ), ...\n    'BALL_UNIT_VOLUME_ND' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/stroud_test045.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.5613717083059782}}
{"text": "function [pvec, pstruct] = tapas_hgf_ar1_transp(r, ptrans)\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 <http://www.gnu.org/licenses/>.\n\n\npvec    = NaN(1,length(ptrans));\npstruct = struct;\n\nl = r.c_prc.n_levels;\n\npvec(1:l)         = ptrans(1:l);                           % mu_0\npstruct.mu_0      = pvec(1:l);\npvec(l+1:2*l)     = exp(ptrans(l+1:2*l));                  % sa_0\npstruct.sa_0      = pvec(l+1:2*l);\npvec(2*l+1:3*l)   = tapas_sgm(ptrans(2*l+1:3*l),1);        % phi\npstruct.phi       = pvec(2*l+1:3*l);\npvec(3*l+1:4*l)   = ptrans(3*l+1:4*l);                     % m\npstruct.m         = pvec(3*l+1:4*l);\npvec(4*l+1:5*l-1) = exp(ptrans(4*l+1:5*l-1));              % ka\npstruct.ka        = pvec(4*l+1:5*l-1);\npvec(5*l:6*l-1)   = ptrans(5*l:6*l-1);                     % om\npstruct.om        = pvec(5*l:6*l-1);\npvec(6*l)         = exp(ptrans(6*l));                      % al\npstruct.al        = pvec(6*l);\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_ar1_transp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5613717071066892}}
{"text": "function rr = ARS(rel_data, wins, up)\n%ARS calculates the power spectral density of a signal using\n% auto-regressive modelling, and finds the RR\n%\n%\t            ARS(option, up)\n%\n%\tInputs:\n%       rel_data    .t  vector of times\n%                   .v  vector of resp Sig values\n%                   .fs sampling freq\n%       up              universal parameters structure\n%       wins        .t  vector of start times\n%\n%\tOutputs:\n%       rr          .t  vector of times of estimated RRs\n%                   .v  vector of estimated RRs\n%                   .f  vector of freqs of power spectrum\n%                   .p  vector of powers of power spectrum\n%\n\n%% Setup\ndownsample_freq = up.paramSet.ar_resample_freq;    % it would be worth changing this - it changes the answer (try 1 Hz e.g.)\ntrue_fs = rel_data.fs;\n\n%% Cycle through windows\nrr.t = mean([wins.t_start(:)' ; wins.t_end(:)']); rr.t = rr.t(:);\nrr.v = nan(length(rr.t),1);\nrr.p = cell(length(wins.t_start),1);\nrr.f = cell(length(wins.t_start),1);\n\nfor win_no = 1 : length(wins.t_start)\n    \n    % extract relevant data\n    rel_els = find(rel_data.t >= wins.t_start(win_no) & rel_data.t < wins.t_end(win_no));\n    data.v = rel_data.v(rel_els);\n    data.t = rel_data.t(rel_els);\n    \n    good_els = ~isnan(data.v);\n    data.v = data.v(good_els);\n    data.t = data.t(good_els);\n    \n    % Downsample\n    data.filt.t = downsample(data.t, true_fs/downsample_freq);\n    data.filt.v = decimate(data.v, true_fs/downsample_freq);\n    data.filt.v = detrend(data.filt.v);\n    \n    data.filt.v = data.filt.v(:);\n    data.filt.t = data.filt.t(:);\n    \n    % AR modelling\n    [Yy,Xx]=pburg(data.filt.v,up.paramSet.ar_model_order,[],downsample_freq);\n    data.freqs=Xx;\n    data.power=Yy;\n    \n    % Find spectral peak\n    [rr.v(win_no), rr.f{win_no}, rr.p{win_no}] = find_spectral_peak(data, up);\n    \n    clear data\n    \nend\n\nend", "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/estimate_rr/ARS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5612892566845692}}
{"text": "%% Housekeeping\nclose all\nclc\n%% load RISE before proceeding if you have not done so already\n\n%% read the models and their calibrations\nsw0=rise('usmodel','solve_linear',true);\n\n%% solve the model\nsw=solve(sw0,'solver','mn');\n\n%% print results\nsw.print_solution()\n\n%% print solution for a subset of variables only\nsw.print_solution({'a','b','c','cf','dc','dinve','dw','dy'})\n\n%% compute regime-specific impulse responses\nmyirfs0=irf(sw,'irf_periods',20);\n\n%% compute generalized impulse responses\nmyirfs1=irf(sw,'irf_periods',20,'irf_type','girf');\n\n%% plot the impulse responses\nclose all\nvar_list={'dc','dinve','dw','dy','lab','pinf','r'};\nfigure('name','Impulse responses to a wage markup shock');\nfor ii=1:numel(var_list)\n    subplot(3,3,ii)\n\tv=var_list{ii};\n\taggregate=[myirfs0.ew.(v),myirfs1.ew.(v)];\n    plot(aggregate,'linewidth',2);\n    title(var_list{ii})\n    if ii==1\n        legend(aggregate.varnames)\n    end\n    axis tight\nend\n\n", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/MarkovSwitching/SmetsWouters/howto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5612892515982627}}
{"text": "function H = cross(F, G)\n%CROSS   Vector cross product.\n%   CROSS(F, G) returns a SPHEREFUNV representing the 3D cross product of\n%   the SPHEREFUNV objects F and G.\n%\n%   See also SPHEREFUNV/DOT.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% [TODO]: Implement the following option\n%   CROSS(F, G, 'n') returns a SPHEREFUN representing the normal component\n%   of the cross product of the SPHEREFUNV objects F and G.  \n%   For two vector fields tangent to the sphere, the cross product is a\n%   a vector that points in the normal direction.  CROSS returns a \n%   SPHEREFUN object representing the component in the normal (radial)\n%   direction.  Mathematically, this is N dot (F x G), where N is the\n%   normal to the sphere.\n\n% Empty check: \nif ( isempty(F) || isempty(G) )\n    H = spherefunv;\n    return\nend\n\n% Get the components: \nFc = F.components; \nGc = G.components; \n\n% Do cross: \nH = [ Fc{2} .* Gc{3} - Fc{3} .* Gc{2} ; ...\n      Fc{3} .* Gc{1} - Fc{1} .* Gc{3} ; ...\n      Fc{1} .* Gc{2} - Fc{2} .* Gc{1} ];\n  \nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@spherefunv/cross.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095495, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.5612892357703886}}
{"text": "% plots a basic tire model given via the vector PacParam \nfunction plotTireModel(PacParam, alpha_data, F_data)\n  figure; \n  grid on; hold on; \n  if(nargin > 2)\n    % if tire model data is available, plot it\n    scatter(alpha_data, F_data, 10); \n    alphaMax = max(alpha_data); \n    alphaMin = min(alpha_data); \n  else\n    alphaMax = 0.5; \n    alphaMin = -0.5;\n  end\n  alpha_sample = alphaMin:0.002:alphaMax; \n  FyF = PacParam(3).*sin(PacParam(2).*atan(PacParam(1).*alpha_sample - PacParam(4).*(PacParam(1).*alpha_sample - atan(PacParam(1).*alpha_sample)))); \n  scatter(alpha_sample, FyF, 'LineWidth', 2); \n  xlabel('Side slip angle in rad'); \n  ylabel('Tire force in N'); \n  ylim([-6000, 6000]); \n  hold on; \n  plot(alpha_sample, PacParam(3).*sin(PacParam(2).*atan(PacParam(1).*alpha_sample))); \n  legend('Detailed Model', 'Simple Model for Control'); \nend", "meta": {"author": "TUMFTM", "repo": "mod_vehicle_dynamics_control", "sha": "48b12705b72740b0c1574b0da2eab66fe0c75127", "save_path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control", "path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control/mod_vehicle_dynamics_control-48b12705b72740b0c1574b0da2eab66fe0c75127/scripts/plotTireModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.6150878625719088, "lm_q1q2_score": 0.5612284047519112}}
{"text": "function [beta, bo] = svm_multi_predK(X,Y,C,K)\n% SVM_MULTI_PREDK\n%\n% Support Vector Multi Classification\n%\n% USAGE: [beta, bo] = svm_multi_pred(X,Y,C,K)\n%\n% PARAMETERS:  X      - (m,d) matrix of m Training inputs in R^d\n%\n%              Y      - m vector of m Training targets in {1,..,Q}\n%\n%              C      - Trade-off between regularization and empirical error \n%\n%              K      - (m,m) Gram matrix\n%\n%              beta   - (m,Q) Coefficients matrix of the expansion of\n%                       the vectors w_i over the x_p's\n%                       w_i = \\sum_p beta(p,i)x_p\n%\n%              bo     - (Q,1) bias terms\n%\n% SUBROUTINES: svm_multi_init.m -> initialization of the optimization problem\n%             squadsolve.m          -> optimization \n%             compute_kernel.m -> computation of the gram matrix\n%\n% DESCRIPTION:\n%\n%              This procedure is the implementation of a multiclass SVM corresponding to \n%              the following problem\n%\n%              \\min_{w_i,w_j} \\sum_{i\\neq j} \\|w_i - w_j\\|^2 + C\\sum_{p,j} \\xi_{pj}\n%\n%              subject to :\n%               for all p=1,..,m   ( w_{c(p)} - w_j ).x_p + b_{c(p)} - b_j \\geq 1 - \\xi_{pj}\n%                                  \\xi_{pj} \\geq 0\n%\n%      where:  m is the number of training points\n%              Q is the number of classes\n%              i and j are indices between 1 and Q\n%              p is an index between 1 and m\n%              w.x is the dot product between w and x\n%\n%              To solve this problem, a direct approach is used. All the gram matrix K (K_{i,j} =x_i.x_j)\n%              is computed before beginning the optimization. The memory cost is thus proportionnal to Q^2*m^2.\n%              The solution is not approximated but is provided by a quadratic programming method implemented in\n%              squadsolve.m. Instead of minimizing the primal objective function, we maximize the dual. Its \n%              formulation is not given here.\n%\n%              \n% ERRORS AND BUGS:\n%              It is recommended not to use this code for large problems: unless your computer has a huge memory,\n%              the procedure will stop with the message: 'memory exhausted'. Use the code msvm_fw.m or chunk_msvm.m\n%              instead. Sometimes, the bias may not be computable because the term 'bias_eps' (see below) is too large.\n%              In that case, decrease 'bias_eps' and it should work. In all cases, the program will output the bias and\n%              try to give the best solution. \n%              \n% EXAMPLE OF USE:\n%\n%      > [beta,bo] = svm_multi_pred(inputs,targets,10,K);\n%\n%       -> solve the multiclass optimization problem for a learning set S = \\cup_i {(inputs(i,:),targets(i))}\n%          with C=10, and with the gram matrix K.\n%\n% Description of variables:\n%\n%      kernel = 0,1,2 (integer)    -> type of kernel\n%      m              (integer)    -> number of input points\n%      Q              (integer)    -> number of classes\n%      bias_eps       (real)       -> precision for the computation of the bias\n%      reg_eps        (real)       -> to avoid ill conditionning, a diagonal matrix\n%                                     is added to the hessian of the minimization problem,\n%                                     reg_eps scales this diagonal matrix. (usual < 10^(-6))\n%      A              ((Q,Q*m) matrix) -> equality constraint matrix \n%      H            ((Q*m,Q*m) matrix) -> hessian of the objective function\n%      c               (Q*m vector)    -> linear part of the objectif function\n%      alpha           (Q*m vector)    -> variables of the optimization problem\n%      constraints     (Q*m vector)    -> store 1-(w_{c(p)} - w_j).x_p\n%      beta            ((m,Q) matrix)  -> vector w_i is computed as w_i = sum_p beta_{pi} x_p\n%      b               ((Q,Q) matrix)  -> store the differences between bias: b(i,j) = b_i - b_j\n% Avoid warning messages\nwarning off;\ndisp('Optimizing...');\n% Test if nargin is correct\nif (nargin < 2) | (nargin > 6),\nhelp svm_multi_pred;\nelse\n  \n% Init\n empty_list_elements_ok = 1;\n m = size(X,1);\n Q = max(Y);\n if (nargin<3),\n     C=Inf;\n end;  \n if (C==Inf)\n    tol = 1e-5;\n  else\n    tol = C*1e-6;\n end;\n bias_eps=10^(-8)/C;\n reg_eps = 10^(-6);\n sv_eps=10^(-6);    \n% Message\n % disp(sprintf('\\nMulti Support Vector Classification\\n'));\n % disp(sprintf('-----------------------------------\\n'));\n   \n% Set up the parameters for the Optimisation problem\n%disp(sprintf('Initialization...\\n'));\n[H,A,c]=svm_multi_init(Y,K);\n% Add small amount of zero order regularization to\n% avoid problems when Hessian is badly conditioned.\nH = 1/(2*Q^2)*H+reg_eps*eye(size(H));% the problem is to minimize (1/4Q^2)x'Hx - c.x\nc = -c;\n% Some variables are irrelevant. Consider only relevant variables\nmul = Q*(0:m-1);\nindx = mul' + Y;\ns1 = (1:Q*m);\ns2 = (indx);\nindx = setdiff(s1,s2)';\nclear s1;clear s2;clear mul;\n% Solve the optimization problem\n% the solution is stored in alpha\n%disp(sprintf('Begin the optimization ...\\n'));\nbo = zeros(size(A,1),1);\n[x1,y] = quadsolve(H(indx,indx),c(indx),A(:,indx),bo,C);\nx1=x1(1:length(indx));\nobj = 0.5*x1'*(H(indx,indx)-reg_eps*eye(length(indx)))*x1 + c(indx)'*x1;\nclear H;clear c;\nalpha = zeros(Q*m,1);\nalpha(indx)=x1;\nclear x1;\n% Output the objective value\n%disp(sprintf('Final objective function: %f \\n',-obj));\n% if the alpha's are all greater than C then, C can be considered as infinite\n% (for the computation of the bias)\nif (max(abs(alpha)) < C*0.95)\n    C==Inf;\nend;\n% Compute the number of support vector\n% Can be removed if not desired\nM = max(alpha);\nnsv=0;\nfor i=1:m,\n  if ~(isempty(find(alpha(Q*(i-1)+1:Q*i)>100*eps)))\n    nsv = nsv+1;\n  end;\nend;\n%disp(sprintf('Support vectors : %d (%3.1f)\\n',nsv,100*nsv/(m)));\n% Compute the coefficients beta_ip of the vector w_i = sum_p beta_ip x_p\n% clean alpha\nbeta=zeros(m,Q);\nnotvoid = find(alpha>=100*eps);\nalpha_tmp=zeros(Q*m,1);\nalpha_tmp(notvoid) = alpha(notvoid);\nalpha=alpha_tmp;\nclear notvoid;clear alpha_tmp;\n% compute beta\nfor i =1:Q,\n for p=1:m,\n  tmp=0;\n  if (i==Y(p))\n   tmp = tmp + sum(alpha((p-1)*Q + 1: (p-1)*Q + Q))/Q;\n  end;\n  beta(p,i) = tmp - alpha((p-1)*Q + i)/Q;\n end;\nend;\n% Computation of the bias\n%disp(sprintf('\\n Computation of the bias........\\n'));\n% Computation of the outputs 1-(w_{c(i)} - w_j).x_i\nerrorcache = zeros(Q*m,1);\nfor p=1:m,\n  for i=1:Q,\n    temp = ((beta(:,Y(p))-beta(:,i))'*K(:,p));\n    errorcache((p-1)*Q+i)=temp;\n  end;\nend;     \n \n  % Computation of the output 1-(w_Y(p)-w_i).x_p\n  constraints=1-errorcache;\n   if C==Inf,\n     b=-Inf*ones(Q,Q);\n     for i=1:m,\n         for k=1:Q,\n            b(Y(i),k) = max([b(Y(i),k),(constraints(Q*(i-1)+k) - 0.05)]);             \n         end;\n     end;\n     for k=1:Q,\n         b(k,k)=0;\n         b(k,find(b(k,:)==-Inf))=0;\n     end;\n   end; %if C>max(alpha),\n%%% For finite C\nif C<Inf,\n% computation of alpha_bias\n  % here: computing of the bias that minimize the \\sum_{ip} \\xi_{pi}\n  % subject to linear constraints:\n  % (w_{c(p)} - w_i).x_p + b_{c(p)} - b_i >= 1 - \\xi_{pi}\n  % \\xi_{pi}\n  % This is a linear program whose dual is easy to compute. It can be\n  % solved with the slinearsolve method.\n  alpha_bias=zeros(Q*m,1);\n  c_un = ones(Q*m,1);\n  [alpha_bias(indx)] = slinearsolve(errorcache(indx)-c_un(indx),A(1:(Q-1),indx),zeros(Q-1,1),1);\n \n  \n  \n  % clean alpha_bias\n  tmp = 0:m-1;\n  tmp = tmp*Q;\n  tmp = tmp + Y';\n  alpha_bias(tmp)=0;\n  \n  \n  % if problem, consider the alpha instead\n  if (flag~=1)\n    alpha_bias=alpha;\n  end;\n  \n  \n  \n  b=zeros(Q,Q); % matrix of the difference b_i-b_j  \n  % Computation of the output 1-(w_Y(p)-w_i).x_p\n  constraints=1-errorcache;\n  \n  % consider the alpha_ip s.t. 0 < alpha_bias_ip < 1\n  % here, i consider alpha_new, because i compute the bias\n  % that minimize the l_1 error of the current solution\n  % and not of the optimal.\n  if C == Inf,\n    Cm =1;\n  else\n    Cm=C;\n  end;\n  if (flag~=1)\n   indice_fix = find(alpha_bias < C*(1-bias_eps) & alpha_bias > Cm*bias_eps);\n  else\n   indice_fix = find(alpha_bias < (1-bias_eps) & alpha_bias > bias_eps);\n  end;\n  \n  % if there are no such alpha -> problem\n  if isempty(indice_fix)\n    disp('WARNING : Unable to compute the bias, use another method\\n');      \n  end;\n  % the bias are computed by averaging \n  % the matrix 'compteur' counts when  b_i-b_j is computed\n  compteur=zeros(Q,Q);\n  for ind=indice_fix',\n    % find the index Q and p corresponding to ind\n    indQ = rem(ind,Q);\n    if (indQ==0), indQ=Q;end;\n    indp = (ind-indQ)/Q;\n    compteur(Y(indp+1),indQ)=compteur(Y(indp+1),indQ)+1;\n    b(Y(indp+1),indQ) = b(Y(indp+1),indQ) + constraints(ind);\n  end;\n  % average by dividing by compteur\n  for i=1:Q,\n    b(i,i) = 0;\n    for j=1:Q,\n      if (compteur(i,j))\n       b(i,j)=b(i,j)/compteur(i,j);\n      end;\n    end;\n  end;\n  end; %if C...,\n  clear indice_fix;clear constraints;\n  \n  \n  % transform b in order to be symetric\n  for i=1:Q,\n    for j=i+1:Q,\n      if (b(i,j)==0)\n        b(i,j)=-b(j,i);\n      end;\n      if (b(j,i)==0)\n        b(j,i)=-b(i,j);\n      end;                       \n    end;\n  end;\n  \n  % average between both symetric elements\n  if C==Inf,\n   for i=1:Q,\n    for j=i+1:Q,\n        b(i,j)=max(b(i,j),-b(j,i));\n        b(j,i)=-b(i,j);\n    end;\n  end; \n  else,\n  for i=1:Q,\n    for j=i+1:Q,\n        b(i,j)=(b(i,j)-b(j,i))/2;\n        b(j,i)=-b(i,j);\n    end;\n  end;\n  end;\n  \n  \n  % compute the values of b_i s.t. sum_i b_i = 0\n  ok=0;% ok > 0, if computation is possible otherwise ok=0\n  b_guess = zeros(Q,1); % if no computation is possible still give a guess\n  bo = zeros(Q,1); % the bias vector\n  for i=1:Q,\n    z = find(b(i,:)~=0);\n    if (length(z)==Q-1)\n      ok=ok+1;\n      temp = sum(b(i,:))/Q;\n      for j=1:Q,\n        bo(j) =bo(j)+temp-b(i,j);\n      end;\n    else\n      %disp(sprintf('Warning : bias %d -> problem... %d\\n',i,length(z)));\n      if length(z),\n        b_guess(i) = sum(b(i,:))/length(z);\n      end;\n      for j=1:length(z),\n        b_guess(z(j)) =b_guess(i) -b(i,z(j));\n      end;\n    end;                \n  end;\n  \n  if ~ok\n    % then one should compute the bias with another method\n    disp('WARNING : Problem with the bias, use another method');\n    bo=b_guess;\n  else\n    bo =bo/ok;\n  end;\n  \nend; %if nargin...\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/Optimization/svm_multi_predK.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5612047158316272}}
{"text": "function [mmHg] = ftH2O2mmHg(ftH2O)\n% Convert pressure from feet of water column at 4 degrees to millimeters of\n% mercury at 0 degrees C\n% Chad Greene 2012\nmmHg = ftH2O*22.4198;", "meta": {"author": "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/ftH2O2mmHg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5612047052135896}}
{"text": "%BZreaction animation\n%Belousov-Zhabotinsky Reaction animation\n%This MATLAB code is converted from Processing code available in this link\n%http://www.aac.bartlett.ucl.ac.uk/processing/samples/bzr.pdf\n\n%version 2. Corrected the drift of pixels as suggested\n%           by Jonh.\n\nxres=75; %x resolution\nyres=75; %y resolution\n\na=rand(xres,yres,2);\nb=rand(xres,yres,2);\nc=rand(xres,yres,2);\nc_a = zeros(xres,yres);\nc_b = zeros(xres,yres);\nc_c = zeros(xres,yres);\np = 1;\nq = 2;\nimg=zeros(xres,yres,3);\n\nfor k=1:100\n         c_a = 0*c_a;\n         c_b = 0*c_b;\n         c_c = 0*c_c;\n         for m=1:xres\n            for n=1:yres\n               for mm = m:m+2\n                  for nn = n:n+2\n                    c_a(m,n) =c_a(m,n)+ a( mod(mm+xres,xres)+1 ,mod(nn+yres,yres)+1 ,p);\n                    c_b(m,n) =c_b(m,n)+ b( mod(mm+xres,xres)+1 ,mod(nn+yres,yres)+1 ,p);\n                    c_c(m,n) =c_c(m,n)+ c( mod(mm+xres,xres)+1 ,mod(nn+yres,yres)+1 ,p);\n                  end\n               end\n            end\n         end\n\n        %correction of pixel drift  \n        c_a = circshift(c_a,[2 2]);\n        c_b = circshift(c_b,[2 2]);\n        c_c = circshift(c_c,[2 2]);\n\n        c_a =c_a/ 9.0;\n        c_b =c_b/ 9.0;\n        c_c =c_c/ 9.0;\n        \n        a(:,:,q) = double(uint8(255*(c_a + c_a .* (c_b - c_c))))/255;\n        b(:,:,q) = double(uint8(255*(c_b + c_b .* (c_c - c_a))))/255;\n        c(:,:,q) = double(uint8(255*(c_c + c_c .* (c_a - c_b))))/255;\n        \n        img(:,:,1)=c(:,:,q);\n        img(:,:,2)=b(:,:,q);\n        img(:,:,3)=a(:,:,q);\n   \n        if  p == 1\n          p = 2; q = 1;\n        else \n          p = 1; q = 2;\n        end\n\n        image(uint8(255*hsv2rgb(img)))\n        axis equal off\n        drawnow\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/24058-animations/BZanimation3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5612047039359346}}
{"text": "function [M,Id] = compute_texture_patchwork(H,n, options)\n\n% compute_texture_patchwork - mix several textures\n%\n%   M = compute_texture_patchwork(H,n,options);\n%\n%   H can be a cell array of textures or a (n,n,3) matrix.\n%   Handles up to 5 textures.\n%\n%   To generate a random partition, set options.patchwork_mode='random'.\n%\n%   Copyright (c) 2006 Gabriel Peyre\n\nif not(iscell(H))\n    H1 = H; H = {};\n    for i=1:size(H1,3)\n        H{i} = H1(:,:,i);\n    end\nend\n\noptions.null = 0;\nmode = getoptions(options, 'patchwork_mode', 'deterministic');\n\nif nargin<2\n    n = size(H{1},1);\nend\n\n\n\np = length(H); % number of textures\n\nif strcmp(mode, 'random')\n        \n    sigma = getoptions(options, 'patchwork_sigma', 60);\n    J = floor(log2(p));\n    A = ones(n);\n    for j=0:J-1\n        B = A;\n        for k=1:2^j\n            I = find(B==k);\n            U = perform_blurring(randn(n),sigma,options);\n            s = median(U(I));\n            I1 = find( (B==k) & (U>s) );\n            I2 = find( (B==k) & (U<=s) );\n            A(I1) = 2*k-1;\n            A(I2) = 2*k;\n        end\n    end\n    \n    M = zeros(n);\n    Id = zeros(n);\n    for i=1:p\n        B = H{i};\n        if size(B,1)<n\n            B = perform_image_extension(B,n);\n        end\n        B = B(1:n,1:n);\n        M(A==i) = B(A==i);\n        Id(A==i) = i;\n    end\n    return;\n\nend\n\nm = min(size(H{1},1),n);\n\nM = zeros(n);\nM(1:m,1:m) = H{1}(1:m,1:m);\nId = ones(n);\n\nif p==2\n    M(end/2+1:end,:) = H{2}(end-n/2+1:end,:);\n    Id(end/2+1:end,:) = 2;\n    return;\nend\n\nif p>1\n    M(1:end/2,end/2+1:end) = H{2}(1:1:n/2,1:n/2);\n    Id(1:end/2,end/2+1:end) = 2;\nend\nif p>2\n    M(end/2+1:end,1:end/2) = H{3}(1:1:n/2,1:n/2);\n    Id(end/2+1:end,1:end/2) = 3;\nend\nif p>3\n    M(end/2+1:end,end/2+1:end) = H{4}(1:1:n/2,1:n/2);\n    Id(end/2+1:end,end/2+1:end) = 4;\nend\nif p>4\n    r = 1;\n    A = H{5}(1:1:n/2,1:n/2);\n    x = linspace(-1,1,n/2)';\n    [Y,X] = meshgrid(x,x);\n    J = find( X.^2 + Y.^2 <= r^2 );\n    x  = [ones(n/4,1)*Inf; x; ones(n/4,1)*Inf];\n    [Y,X] = meshgrid(x,x);\n    I = find( X.^2 + Y.^2 <= r^2 );\n    M(I) = A(J);\n    Id(I) = 5;\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_image/compute_texture_patchwork.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5612047005433973}}
{"text": "function [SIG,BAK,OVL]= comp_fwseg_variant(cleanFile, enhancedFile);\n\n% ----------------------------------------------------------------------\n%      Frequency-variant fwSNRseg Objective Speech Quality Measure\n%\n%   This function implements the frequency-variant fwSNRseg measure [1]\n%   (see also Chap. 10, Eq. 10.24)\n%\n%\n%   Usage:  [sig,bak,ovl]=comp_fwseg_variant(cleanFile.wav, enhancedFile.wav)\n%           \n%         cleanFile.wav - clean input file in .wav format\n%         enhancedFile  - enhanced output file in .wav format\n%         sig           - predicted rating [1-5] of speech distortion\n%         bak           - predicted rating [1-5] of noise distortion\n%         ovl           - predicted rating [1-5] of overall quality\n%\n%\n%  Example call:  [s,b,o] =comp_fwseg_variant('sp04.wav','enhanced.wav')\n%\n%  \n%  References:\n%     [1] S. R. Quackenbush, T. P. Barnwell, and M. A. Clements,\n%\t    Objective Measures of Speech Quality.  Prentice Hall\n%\t    Advanced Reference Series, Englewood Cliffs, NJ, 1988,\n%\t    ISBN: 0-13-629056-6.\n%\n%   Author: Philipos C. Loizou \n%  (critical-band filtering routines were written by Bryan Pellom & John Hansen)\n%\n% Copyright (c) 2006 by Philipos C. Loizou\n% $Revision: 0.0 $  $Date: 10/09/2006 $\n% ----------------------------------------------------------------------\n\nif nargin~=2\n    fprintf('USAGE: [sig,bak,ovl]=comp_fwseg_variant(cleanFile.wav, enhancedFile.wav)\\n');\n    fprintf('For more help, type: help comp_fwseg_variant\\n\\n');\n    return;\nend\n\n\n[data1, Srate1]= audioread(cleanFile);\n[data2, Srate2]= audioread(enhancedFile);\n% if ( Srate1~= Srate2) | ( Nbits1~= Nbits2)\n%     error( 'The two files do not match!\\n');\n% end\n\nlen= min( length( data1), length( data2));\ndata1= data1( 1: len)+eps;\ndata2= data2( 1: len)+eps;\n\nwss_dist_matrix= fwseg( data1, data2,Srate1);\nwss_dist=mean(wss_dist_matrix);\n\n% initialize  coefficients obtained from multiple linear\n% regression analysis\n%\nb_sig=[0.021,-0.028,0.088,-0.031,0.048,-0.049,0.065,0.009,0.011,0.033,...\n    -0.040,-0.002,0.041,-0.007,0.033,0.018,-0.007,0.044,-0.001,0.021,...\n    -0.002,0.017,-0.03,0.073,0.043];\nb_ovl=[-0.003,-0.026,0.066,-0.036,0.038,-0.023,0.037,0.022,0.014,0.009,...\n    -0.03,0.004,0.044,-0.005,0.017,0.018,-0.001,0.051,0.009,0.011,...\n    0.011,-0.002,-0.021,0.043,0.031];\nb_bak=[-0.03,-0.022,0.03,-0.048,0.034,0.002,0.006,0.037,0.017,-0.016,-0.008,...\n    0.019,0.024,-0.002,0.01,0.03,-0.018,0.046,0.022,0.005,0.03,-0.028,...\n    -0.028,0.019,0.005];\n\nSIG=0.567+sum(b_sig.*wss_dist);\nSIG=max(1,SIG); SIG=min(5, SIG); % limit values to [1, 5]\n\nBAK=1.013+sum(b_bak.*wss_dist);\nBAK=max(1,BAK); BAK=min(5, BAK); % limit values to [1, 5]\n\nOVL=0.446+sum(b_ovl.*wss_dist);\nOVL=max(1,OVL); OVL=min(5, OVL); % limit values to [1, 5]\n\n\n% ----------------------------------------------------------------------\n\nfunction distortion = fwseg(clean_speech, processed_speech,sample_rate)\n\n\n% ----------------------------------------------------------------------\n% Check the length of the clean and processed speech.  Must be the same.\n% ----------------------------------------------------------------------\n\nclean_length      = length(clean_speech);\nprocessed_length  = length(processed_speech);\n\nif (clean_length ~= processed_length)\n  disp('Error: Files  must have same length.');\n  return\nend\n\n\n\n% ----------------------------------------------------------------------\n% Global Variables\n% ----------------------------------------------------------------------\n\n\nwinlength   = round(30*sample_rate/1000); \t   % window length in samples\nskiprate    = floor(winlength/4);\t\t   % window skip in samples\nmax_freq    = sample_rate/2;\t   % maximum bandwidth\nnum_crit    = 25;\t\t   % number of critical bands\n\nn_fft       = 2^nextpow2(2*winlength);\nn_fftby2    = n_fft/2;\t\t   % FFT size/2\n\n% ----------------------------------------------------------------------\n% Critical Band Filter Definitions (Center Frequency and Bandwidths in Hz)\n% ----------------------------------------------------------------------\n\ncent_freq(1)  = 50.0000;   bandwidth(1)  = 70.0000;\ncent_freq(2)  = 120.000;   bandwidth(2)  = 70.0000;\ncent_freq(3)  = 190.000;   bandwidth(3)  = 70.0000;\ncent_freq(4)  = 260.000;   bandwidth(4)  = 70.0000;\ncent_freq(5)  = 330.000;   bandwidth(5)  = 70.0000;\ncent_freq(6)  = 400.000;   bandwidth(6)  = 70.0000;\ncent_freq(7)  = 470.000;   bandwidth(7)  = 70.0000;\ncent_freq(8)  = 540.000;   bandwidth(8)  = 77.3724;\ncent_freq(9)  = 617.372;   bandwidth(9)  = 86.0056;\ncent_freq(10) = 703.378;   bandwidth(10) = 95.3398;\ncent_freq(11) = 798.717;   bandwidth(11) = 105.411;\ncent_freq(12) = 904.128;   bandwidth(12) = 116.256;\ncent_freq(13) = 1020.38;   bandwidth(13) = 127.914;\ncent_freq(14) = 1148.30;   bandwidth(14) = 140.423;\ncent_freq(15) = 1288.72;   bandwidth(15) = 153.823;\ncent_freq(16) = 1442.54;   bandwidth(16) = 168.154;\ncent_freq(17) = 1610.70;   bandwidth(17) = 183.457;\ncent_freq(18) = 1794.16;   bandwidth(18) = 199.776;\ncent_freq(19) = 1993.93;   bandwidth(19) = 217.153;\ncent_freq(20) = 2211.08;   bandwidth(20) = 235.631;\ncent_freq(21) = 2446.71;   bandwidth(21) = 255.255;\ncent_freq(22) = 2701.97;   bandwidth(22) = 276.072;\ncent_freq(23) = 2978.04;   bandwidth(23) = 298.126;\ncent_freq(24) = 3276.17;   bandwidth(24) = 321.465;\ncent_freq(25) = 3597.63;   bandwidth(25) = 346.136;\n\n\nbw_min      = bandwidth (1);\t   % minimum critical bandwidth\n\n\n% ----------------------------------------------------------------------\n% Set up the critical band filters.  Note here that Gaussianly shaped\n% filters are used.  Also, the sum of the filter weights are equivalent\n% for each critical band filter.  Filter less than -30 dB and set to\n% zero.\n% ----------------------------------------------------------------------\n\nmin_factor = exp (-30.0 / (2.0 * 2.303));       % -30 dB point of filter\n\nfor i = 1:num_crit\n  f0 = (cent_freq (i) / max_freq) * (n_fftby2);\n  all_f0(i) = floor(f0);\n  bw = (bandwidth (i) / max_freq) * (n_fftby2);\n  norm_factor = log(bw_min) - log(bandwidth(i));\n  j = 0:1:n_fftby2-1;\n  crit_filter(i,:) = exp (-11 *(((j - floor(f0)) ./bw).^2) + norm_factor);\n  crit_filter(i,:) = crit_filter(i,:).*(crit_filter(i,:) > min_factor);  \nend   \n\n% ----------------------------------------------------------------------\n% For each frame of input speech, calculate the Weighted Spectral\n% Slope Measure\n% ----------------------------------------------------------------------\n\nnum_frames = floor(clean_length/skiprate-(winlength/skiprate)); % number of frames\nstart      = 1;\t\t\t\t\t% starting sample\nwindow     = 0.5*(1 - cos(2*pi*(1:winlength)'/(winlength+1)));\n\ndistortion=zeros(num_frames,num_crit);\nfor frame_count = 1:num_frames\n\n   % ----------------------------------------------------------\n   % (1) Get the Frames for the test and reference speech. \n   %     Multiply by Hanning Window.\n   % ----------------------------------------------------------\n\n   clean_frame = clean_speech(start:start+winlength-1);\n   processed_frame = processed_speech(start:start+winlength-1);\n   clean_frame = clean_frame.*window;\n   processed_frame = processed_frame.*window;\n\n   % ----------------------------------------------------------\n   % (2) Compute the magnitude Spectrum of Clean and Processed\n   % ----------------------------------------------------------\n\n    \n       clean_spec     = abs(fft(clean_frame,n_fft));\n       processed_spec = abs(fft(processed_frame,n_fft));\n       \n       % normalize so that spectra have unit area ----\n        clean_spec=clean_spec/sum(clean_spec(1:n_fftby2));\n        processed_spec=processed_spec/sum(processed_spec(1:n_fftby2));\n\n   % ----------------------------------------------------------\n   % (3) Compute Filterbank Output Energies (in dB scale)\n   % ----------------------------------------------------------\n \n   clean_energy=zeros(1,num_crit);\n   processed_energy=zeros(1,num_crit);\n   error_energy=zeros(1,num_crit);\n   \n   for i = 1:num_crit\n      clean_energy(i) = sum(clean_spec(1:n_fftby2) ...\n\t\t            .*crit_filter(i,:)');\n      processed_energy(i) = sum(processed_spec(1:n_fftby2) ...\n\t\t\t        .*crit_filter(i,:)');\n      error_energy(i)=max((clean_energy(i)-processed_energy(i))^2,eps);\n   end\n   \n\n   SNRlog=10*log10((clean_energy.^2)./error_energy);\n   \n   distortion(frame_count,:)=min(max(SNRlog,-10),35);\n      \n   start = start + skiprate;\n     \nend\n\n", "meta": {"author": "anicolson", "repo": "DeepXi", "sha": "a0acd9688e1087fdde581191be2216ed93d416f9", "save_path": "github-repos/MATLAB/anicolson-DeepXi", "path": "github-repos/MATLAB/anicolson-DeepXi/DeepXi-a0acd9688e1087fdde581191be2216ed93d416f9/demand_voice_bank_objective_scoring/comp_fwseg_variant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5612046986269159}}
{"text": "%% GSA_GetSy: calculate the Sobol' sensitivity indices\n%\n% Usage:\n%   [S eS pro] = GSA_GetSy(pro, iset, verbose)\n%\n% Inputs:\n%    pro                project structure\n%    iset               cell array or array of inputs of the considered set, they can be selected\n%                       by index (1,2,3 ...) or by name ('in1','x',..) or\n%                       mixed\n%    verbose            if not empty, it shows the time (in hours) for\n%                       finishing\n%\n% Output:\n%    S                  sensitivity coefficient\n%    eS                 error of sensitivity coefficient\n%    pro                project structure\n%\n% ------------------------------------------------------------------------\n% See also\n%\n% Author : Flavio Cannavo'\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\n% Release: 1.0\n% Date   : 15-02-2011\n%\n% History:\n% 1.0  15-04-2011  Added verbose parameter\n% 1.0  15-01-2011  First release.\n%%\n\nfunction [S eS pro] = GSA_GetSy(pro, iset, verbose)\n\n\nif ~exist('verbose','var')\n    verbose = 0;\nelse\n    verbose = ~isempty(verbose) && verbose;\nend\n\nindex = fnc_SelectInput(pro, iset);\n\nif isempty(index)\n    S = 0;\n    eS = 0;\nelse\n    S = 0;\n    eS = 0;\n    n = length(index);\n    L = 2^n;\n    \n    if verbose\n        tic\n    end\n    for i=1:(L-1)\n        ii = fnc_GetInputs(i);\n        si = fnc_GetIndex(index(ii));\n        if isnan(pro.GSA.GSI(si))\n            \n            %-------\n            if isnan(pro.GSA.Di(si))\n                \n                ixi = fnc_GetInputs(si);\n                s = length(ixi);\n                l = 2^s - 1;\n                \n                %======\n                if isnan(pro.GSA.Dmi(si))\n                    n = length(pro.Inputs.pdfs);\n                    N = size(pro.SampleSets.E,1);\n                    H = pro.SampleSets.E(:,:);\n                    cii = fnc_GetComplementayInputs(si, n);\n                    H(:,cii) = pro.SampleSets.T(:,cii);\n                    ff = nan(N,1);\n                    \n                    for j=1:N\n                        ff(j) = pro.GSA.fE(j)*(pro.Model.handle(H(j,:))-pro.GSA.mfE);\n                    end\n                    \n                    pro.GSA.Dmi(si)  = nanmean(ff);\n                    pro.GSA.eDmi(si) = 0.6745*sqrt((nanmean(ff.^2) - pro.GSA.Dmi(si)^2)/sum(~isnan(ff)));\n                end\n                %=======\n                \n                Di = pro.GSA.Dmi(si);\n                eDi = pro.GSA.eDmi(si)^2;\n                \n                for j=1:(l-1)\n                    sii = fnc_GetInputs(j);\n                    k = fnc_GetIndex(ixi(sii));\n                    s_r = s - length(sii);\n                    Di = Di + pro.GSA.Dmi(k)*((-1)^s_r);\n                    eDi = eDi + pro.GSA.eDmi(k)^2;\n                end\n                \n                pro.GSA.Di(si) = Di + (pro.GSA.f0^2)*((-1)^s);\n                pro.GSA.eDi(si) = sqrt(eDi + 2*(pro.GSA.ef0^2));\n                \n                \n            end\n            %------\n            pro.GSA.GSI(si) = pro.GSA.Di(si)/pro.GSA.D;\n            pro.GSA.eGSI(si) = pro.GSA.GSI(si)*pro.GSA.eDi(si)/pro.GSA.D;\n        end\n        S = S + pro.GSA.GSI(si);\n        eS = eS + pro.GSA.eGSI(si);\n        \n        if verbose\n            timelapse = toc;\n            disp(timelapse*(L-1-i)/i/60/60);\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/40759-global-sensitivity-analysis-toolbox/GSAT/GSA_GetSy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5612046826998595}}
{"text": "\nfunction a = spiral(hyper) \n\n%=================================================================================\n% TOY SPIRAL data generation object\n%================================================================================= \n% A=spiral(H) returns a spiral toy data object initialized with hyperparameters H. \n%\n% This generates 2 spirals with 4*m points per spiral, where 1*m points are\n% points on two perfect spiral and 3*m points are some additive noise on\n% the first quarter.\n% \n% \n% Hyperparameters, and their defaults\n%  n=1           --  a parameter :-) play to explore\n%  m=50          --  number of used points per winding\n% \n% Model\n%\n% Methods:\n%  generate,train,test\n%  Example :  \n%   d=gen(spiral({'n=1','m=50'}));\n%   [r s0]=train(svm(kernel('rbf',1)),d)\n%   plot(s0,[ -20 20 -20 20]);\n%=================================================================================\n% Reference : \n% Author    : \n% Link      : \n%=================================================================================\n  \n  a.m=50;\n  a.n=2;\n  a.noise=1;\n  \n  \n  p=algorithm('spiral');\n  a= class(a,'spiral',p);\n  \n  if nargin==1\n    eval_hyper;\n  end  \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/basic/@spiral/spiral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5611899732220428}}
{"text": "classdef MMF7 < PROBLEM\n% <multi> <real> <multimodal>\n% Multi-modal multi-objective test function\n\n%------------------------------- Reference --------------------------------\n% C. Yue, B. Qu, and J. Liang, A multi-objective particle swarm optimizer\n% using ring topology for solving multimodal multiobjective Problems, IEEE\n% Transactions on Evolutionary Computation, 2018, 22(5): 805-817.\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        POS;    % Pareto optimal set for IGDX calculation\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            obj.D = 2;\n            obj.lower    = [1,-1];\n            obj.upper    = [3,1];\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            PopObj(:,1) = abs(X(:,1)-2);\n            PopObj(:,2) = 1 - sqrt(PopObj(:,1)) + (X(:,2)-(0.3.*(PopObj(:,1).^2).*cos(24.*pi.*PopObj(:,1)+4.*pi)+0.6.*PopObj(:,1)).*sin(6.*pi.*PopObj(:,1)+pi)).^2;\n        end\n        %% Generate Pareto optimal solutions\n        function R = GetOptimum(obj,N)\n            % Generate points in Pareto optimal set\n            obj.POS(:,1) = linspace(1,3,N)';\n            obj.POS(:,2) = (0.3*(obj.POS(:,1)-2).^2.*cos(24*pi*abs(obj.POS(:,1)-2)+4*pi)+0.6*abs(obj.POS(:,1)-2)).*sin(6*pi*abs(obj.POS(:,1)-2)+pi);\n            % Generate points on Pareto front\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - sqrt(R(:,1));\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R(:,1) = linspace(0,1,100)';\n            R(:,2) = 1 - sqrt(R(:,1));\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            temp   = PopDec(:,1) <= 2;\n            Draw(Population(temp).objs,'o','MarkerSize',6,'Marker','o','Markerfacecolor',[1 .5 .5],'Markeredgecolor',[1 .2 .2],{'\\it f\\rm_1','\\it f\\rm_2',[]});\n            Draw(Population(~temp).objs+0.1,'o','MarkerSize',6,'Marker','o','Markerfacecolor',[.5 .5 1],'Markeredgecolor',[.2 .2 1]);\n            Draw(obj.PF,'-','LineWidth',1,'Color',[1 .2 .2]);\n            Draw(obj.PF+0.1,'-','LineWidth',1,'Color',[.2 .2 1]);\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/MMF/MMF7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5611899613155926}}
{"text": "function [P]=tesSmoothPosNeg(TES,V,IND_V,cPar)\n\n%% CONTROL PARAMETERS\n\nif isfield(cPar,'LambdaSmooth')\n    LambdaSmooth=cPar.LambdaSmooth;\nelse\n    LambdaSmooth=0.5; %DEFAULT\nend\n\nif isfield(cPar,'n')\n    nMax=cPar.n;\nelse\n    nMax=1; %DEFAULT\nend\n\nif isfield(cPar,'RigidConstraints')\n    indRigid=cPar.RigidConstraints;\nelse\n    indRigid=[]; %DEFAULT\nend\n\nif isfield(cPar,'Tolerance')\n    SSQD_Tol=cPar.Tolerance;\nelse\n    SSQD_Tol=[]; %DEFAULT\nend\n\n\n%%\n\nif isempty(IND_V)\n    [~,IND_V]=patchIND(TES,V);\nend\nlogicValid=IND_V>0;\n\nnDims=size(V,2); %Number of dimensions\n\nVP=NaN(size(IND_V,1),size(IND_V,2),nDims);\n\nP=V;\nPP=V; \nQ=V;\nif ~isempty(SSQD_Tol)\n    SSQD_old=[];\n    SSQD_ratio=0;\nend\n\nfor qIter=1:nMax;   \n        \n    %% SIMPLE LAPLACIAN SMOOTHENING\n    \n    %Loop for all dimensions\n    for qDim=1:1:nDims\n        Xp=VP(:,:,qDim);\n        Xp(logicValid)=P(IND_V(logicValid),qDim);\n        Xp=gnanmean(Xp,2);       \n        PP(:,qDim)=Xp;\n    end\n    \n    %Switch sign every iteration to partialy avoid shrinkage\n    if iseven(qIter)\n        wFac=1;        \n    else\n        wFac=1;\n    end\n    \n    P=P+wFac.*LambdaSmooth.*(PP-P);\n    \n    %%\n        \n    %Put back constrained points\n    if ~isempty(indRigid)\n       P(indRigid,:)=V(indRigid,:);\n    end\n    \n    if ~isempty(SSQD_Tol)\n        %Compute sum of squared differences with respect to previous iteration\n        SSQD_new=gnansum((P(:)-Q(:)).^2);\n        if ~isempty(SSQD_old)\n            SSQD_ratio=SSQD_new./SSQD_old;            \n        end\n        \n        %Store current metrics\n        Q=P;\n        SSQD_old=SSQD_new;        \n        if abs(1-SSQD_ratio)<=SSQD_Tol\n           break %STOP SMOOTHING LOOP IF TOLERANCE IS REACHED \n        end\n    end\n    \nend\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/tesSmoothPosNeg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5611899516898949}}
{"text": "function enter_eul_angs(varargin)\n% update because euler angles were changed\nglobal ts rhs lr rhs1 lr1 xs xst ys yst zs zst ks phi theta psi rad deg x y z gamma delta alpha  vna vnat N Nt sxyz sav sN arcR arcth arctxtR phia1 phia2 phiat sa thetaa1 thetaa2 thetaat psia1 psia2 psiat gammaa1 gammaa2 gammaat saa  deltaa1 deltaa2 deltaat arcvsh alphaa1 alphaa2 alphaat arcR1 arcth1 arctxtR1\n\nnaner=false;\n\nphin=str2num(get(phi,'String'));\nif length(phin)==0\n    naner=true;\nend\n\nthetan=str2num(get(theta,'String'));\nif length(thetan)==0\n    naner=true;\nend\n\npsin=str2num(get(psi,'String'));\nif length(psin)==0\n    naner=true;\nend\n\nif naner\n    nan_error;\nelse\n\n    if get(deg,'Value')\n        phin=pi*phin/180;\n        thetan=pi*thetan/180;\n        psin=pi*psin/180;\n    end\n    \n    an=ea_bounding(phin,thetan,psin); % correct angles\n    if an(1)\n        phin=an(2);\n        thetan=an(3);\n        psin=an(4);\n        if get(deg,'Value')\n            set(phi,'String',num2str(180*phin/pi));\n            set(theta,'String',num2str(180*thetan/pi));\n            set(psi,'String',num2str(180*psin/pi));\n        else\n            set(phi,'String',num2str(phin));\n            set(theta,'String',num2str(thetan));\n            set(psi,'String',num2str(psin));\n        end\n    end\n\n    Ms=matrices(phin,thetan,psin);\n    M=Ms{1}*Ms{2}*Ms{3};\n\n    als=0.5; % transparensy of xyz\n    lcs=[0.4 0.4 0.4]; %labels color\n    \n    if get(sxyz,'value')\n        % x\n        xsv=M*[1;0;0];\n        xsv1=ks*xsv;\n        %xs=arrowa(0,0,0,xsv1(1),xsv1(2),xsv1(3),rhs1*0.8,lr1*0.8,[1 0 0],als,hpar);\n        arrow_update(xs,0,0,0,xsv1(1),xsv1(2),xsv1(3),rhs1*0.8,lr1*0.8);\n        %xst=text('parent',hpar,'position',xsv1+ts*xsv,'string','x','HorizontalAlignment','center','VerticalAlignment','middle','color',lcs);\n        set(xst,'position',xsv1+ts*xsv);\n\n        % y\n        ysv=M*[0;1;0];\n        ysv1=ks*ysv;\n        %ys=arrowa(0,0,0,ysv1(1),ysv1(2),ysv1(3),rhs1*0.8,lr1*0.8,[0 1 0],als,hpar);\n        arrow_update(ys,0,0,0,ysv1(1),ysv1(2),ysv1(3),rhs1*0.8,lr1*0.8);\n        %yst=text('parent',hpar,'position',ysv1+ts*ysv,'string','y','HorizontalAlignment','center','VerticalAlignment','middle','color',lcs);\n        set(yst,'position',ysv1+ts*ysv);\n\n        % z\n        zsv=M*[0;0;1];\n        zsv1=ks*zsv;\n        %zs=arrowa(0,0,0,zsv1(1),zsv1(2),zsv1(3),rhs1*0.8,lr1*0.8,[0 0 1],als,hpar);\n        arrow_update(zs,0,0,0,zsv1(1),zsv1(2),zsv1(3),rhs1*0.8,lr1*0.8);\n        %zst=text('parent',hpar,'position',zsv1+ts*zsv,'string','z','HorizontalAlignment','center','VerticalAlignment','middle','color',lcs);\n        set(zst,'position',zsv1+ts*zsv);\n        \n        arrow_visible_off_on(xs,true);\n        set(xst,'visible','on');\n\n        arrow_visible_off_on(ys,true);\n        set(yst,'visible','on');\n\n        arrow_visible_off_on(zs,true);\n        set(zst,'visible','on');\n        \n    else\n        \n        arrow_visible_off_on(xs,false);\n        set(xst,'visible','off');\n\n        arrow_visible_off_on(ys,false);\n        set(yst,'visible','off');\n\n        arrow_visible_off_on(zs,false);\n        set(zst,'visible','off');\n        \n    end\n    \n    if (nargin>=1)&&varargin{1}\n        vn(1,1)=str2num(get(x,'string'));\n        vn(2,1)=str2num(get(y,'string'));\n        vn(3,1)=str2num(get(z,'string'));\n        gamman=varargin{2};\n        deltan=varargin{3};\n        alphan=varargin{4};\n    else\n        % axis v\n        axan=euler2axan(phin,thetan,psin,M);\n        % {{gamma,delta,alpha},v}\n        gda=axan{1};\n        gamman=gda{1};\n        deltan=gda{2};\n        alphan=gda{3};\n        vn=axan{2};\n        if get(deg,'Value')\n            set(gamma,'string',num2str(180*gamman/pi));\n            set(delta,'string',num2str(180*deltan/pi));\n            set(alpha,'string',num2str(180*alphan/pi));\n        else\n            set(gamma,'string',num2str(gamman));\n            set(delta,'string',num2str(deltan));\n            set(alpha,'string',num2str(alphan));\n        end\n\n        set(x,'string',num2str(vn(1)));\n        set(y,'string',num2str(vn(2)));\n        set(z,'string',num2str(vn(3)));\n    end\n    \n    \n    if get(sav,'value')\n        vn1=ks*vn;\n        %vna=arrow(0,0,0,vn(1),vn(2),vn(3),rhs1*0.8,lr1*0.8,[0.9 0.2 1],hpar);\n        arrow_update(vna,0,0,0,vn(1),vn(2),vn(3),rhs1*0.8,lr1*0.8);\n        %vnat=text('parent',hpar,'position',vn+ts*vn1,'string','v','HorizontalAlignment','center','VerticalAlignment','middle','color',lcs);\n        set(vnat,'position',vn+ts*vn1);\n        \n        arrow_visible_off_on(vna,true);\n        set(vnat,'visible','on');\n    else\n        arrow_visible_off_on(vna,false);\n        set(vnat,'visible','off');\n    end\n    \n    % line of nodes\n    if get(sN,'value')\n        Nv=Ms{1}*[1;0;0];\n        Nv1=ks*Nv;\n        %N=arrow(0,0,0,Nv(1),Nv(2),Nv(3),rhs1*0.8,lr1*0.8,[0.4 0.4 4],hpar);\n        arrow_update(N,-Nv(1),-Nv(2),-Nv(3),2*Nv(1),2*Nv(2),2*Nv(3),rhs1*0.8,lr1*0.8);\n        %Nt=text('parent',hpar,'position',Nv+ts*Nv1,'string','N','HorizontalAlignment','center','VerticalAlignment','middle','color',lcs);\n        set(Nt,'position',Nv+ts*Nv1);\n        \n        arrow_visible_off_on(N,true);\n        set(Nt,'visible','on');\n        \n    else\n        \n        arrow_visible_off_on(N,false);\n        set(Nt,'visible','off');\n        \n    end\n    \n    \n    \n    \n    % angles:\n    if get(sa,'value')\n        % phi:\n        an=arc_data(phin,arcR,arcth,arctxtR);\n        Ml=an{1};\n        Mt=an{2};\n        txv=an{3};\n        %phia1=plot3(Ml(1,:),Ml(2,:),zeros(1,length(Ml(1,:))),'-k','parent',hpar);\n        set(phia1,'XData',Ml(1,:),'YData',Ml(2,:),'ZData',zeros(1,length(Ml(1,:))));\n        %phia2=plot3(Mt(1,:),Mt(2,:),zeros(1,length(Mt(1,:))),'-k','parent',hpar);\n        set(phia2,'XData',Mt(1,:),'YData',Mt(2,:),'ZData',zeros(1,length(Mt(1,:))));\n        %phiat=text('parent',hpar,'position',[txv 0],'string','\\phi','HorizontalAlignment','center','VerticalAlignment','middle','color',lcs);\n        set(phiat,'position',[txv 0]);\n        \n        set(phia1,'visible','on');\n        set(phia2,'visible','on');\n        set(phiat,'visible','on');\n        \n        % theta:\n        an=arc_data(thetan,arcR,arcth,arctxtR);\n        Ml1=an{1};\n        Ml=Ms{1}*[zeros(1,length(Ml1(1,:))); -Ml1(2,:); Ml1(1,:)];\n        Mt1=an{2};\n        Mt=Ms{1}*[zeros(1,length(Mt1(1,:))); -Mt1(2,:); Mt1(1,:)];\n        txv1=an{3};\n        txv=Ms{1}*[0; -txv1(2); txv1(1)];\n        %thetaa1=plot3(Ml(1,:),Ml(2,:),Ml(3,:),'-k','parent',hpar);\n        set(thetaa1,'XData',Ml(1,:),'YData',Ml(2,:),'ZData',Ml(3,:));\n        %thetaa2=plot3(Mt(1,:),Mt(2,:),Mt(3,:),'-k','parent',hpar);\n        set(thetaa2,'XData',Mt(1,:),'YData',Mt(2,:),'ZData',Mt(3,:));\n        %thetaat=text('parent',hpar,'position',txv,'string','\\theta','HorizontalAlignment','center','VerticalAlignment','middle','color',lcs);\n        set(thetaat,'position',txv);\n        \n        set(thetaa1,'visible','on');\n        set(thetaa2,'visible','on');\n        set(thetaat,'visible','on');\n        \n        \n        % psi:\n        an=arc_data(psin,arcR,arcth,arctxtR);\n        Ml1=an{1};\n        Ml=Ms{1}*Ms{2}*[Ml1(1,:); Ml1(2,:); zeros(1,length(Ml1(1,:)))];\n        Mt1=an{2};\n        Mt=Ms{1}*Ms{2}*[Mt1(1,:); Mt1(2,:); zeros(1,length(Mt1(1,:)))];\n        txv1=an{3};\n        txv=Ms{1}*Ms{2}*[txv1(1); txv1(2); 0];\n        %psia1=plot3(Ml(1,:),Ml(2,:),Ml(3,:),'-k','parent',hpar);\n        set(psia1,'XData',Ml(1,:),'YData',Ml(2,:),'ZData',Ml(3,:));\n        %psia2=plot3(Mt(1,:),Mt(2,:),Mt(3,:),'-k','parent',hpar);\n        set(psia2,'XData',Mt(1,:),'YData',Mt(2,:),'ZData',Mt(3,:));\n        %psiat=text('parent',hpar,'position',txv,'string','\\psi','HorizontalAlignment','center','VerticalAlignment','middle','color',lcs);\n        set(psiat,'position',txv);\n        \n        set(psia1,'visible','on');\n        set(psia2,'visible','on');\n        set(psiat,'visible','on');\n        \n        \n        \n        \n    else\n        set(phia1,'visible','off');\n        set(phia2,'visible','off');\n        set(phiat,'visible','off');\n        \n        set(thetaa1,'visible','off');\n        set(thetaa2,'visible','off');\n        set(thetaat,'visible','off');\n        \n        set(psia1,'visible','off');\n        set(psia2,'visible','off');\n        set(psiat,'visible','off');\n    end\n    \n    \n    % axis-angle angles\n    if get(saa,'value')\n        % gamma:\n        an=arc_data(gamman,arcR,arcth,arctxtR);\n        Ml=an{1};\n        Mt=an{2};\n        txv=an{3};\n        %gammaa1=plot3(Ml(1,:),Ml(2,:),zeros(1,length(Ml(1,:))),'-k','parent',hpar);\n        set(gammaa1,'XData',Ml(1,:),'YData',Ml(2,:),'ZData',zeros(1,length(Ml(1,:))));\n        %gammaa2=plot3(Mt(1,:),Mt(2,:),zeros(1,length(Mt(1,:))),'-k','parent',hpar);\n        set(gammaa2,'XData',Mt(1,:),'YData',Mt(2,:),'ZData',zeros(1,length(Mt(1,:))));\n        %gammaat=text('parent',hpar,'position',[txv 0],'string','\\gamma','HorizontalAlignment','center','VerticalAlignment','middle','color',lcs);\n        set(gammaat,'position',[txv 0]);\n        \n        set(gammaa1,'visible','on');\n        set(gammaa2,'visible','on');\n        set(gammaat,'visible','on');\n        \n        % delta:\n        an=arc_data(deltan,arcR,arcth,arctxtR);\n        csgm=cos(gamman);\n        sngm=sin(gamman);\n        Mrot=[csgm, -sngm, 0;\n              sngm, csgm,  0;\n              0,    0,     1];\n        Ml1=an{1};\n        Ml=Mrot*[Ml1(1,:); zeros(1,length(Ml1(1,:))); Ml1(2,:)];\n        Mt1=an{2};\n        Mt=Mrot*[Mt1(1,:); zeros(1,length(Mt1(1,:))); Mt1(2,:)];\n        txv1=an{3};\n        txv=Mrot*[txv1(1); 0; txv1(2)];\n        %deltaa1=plot3(Ml(1,:),Ml(2,:),Ml(3,:),'-k','parent',hpar);\n        set(deltaa1,'XData',Ml(1,:),'YData',Ml(2,:),'ZData',Ml(3,:));\n        %deltaa2=plot3(Mt(1,:),Mt(2,:),Mt(3,:),'-k','parent',hpar);\n        set(deltaa2,'XData',Mt(1,:),'YData',Mt(2,:),'ZData',Mt(3,:));\n        %deltaat=text('parent',hpar,'position',txv,'string','\\delta','HorizontalAlignment','center','VerticalAlignment','middle','color',lcs);\n        set(deltaat,'position',txv);\n        \n        set(deltaa1,'visible','on');\n        set(deltaa2,'visible','on');\n        set(deltaat,'visible','on');\n        \n        \n        an=arc_data(alphan,arcR1,arcth1,arctxtR1);\n        csdl=cos(deltan);\n        sndl=sin(deltan);\n        Mrot1=[csdl, 0,  -sndl;\n               0,    1,  0    ;\n               sndl, 0,  csdl ];\n        Ml1=an{1};\n        Ml=Mrot*Mrot1*[zeros(1,length(Ml1(1,:))); -Ml1(2,:); Ml1(1,:)];\n        Mt1=an{2};\n        Mt=Mrot*Mrot1*[zeros(1,length(Mt1(1,:))); -Mt1(2,:); Mt1(1,:)];\n        txv1=an{3};\n        txv=Mrot*Mrot1*[0; -txv1(2); txv1(1)];\n        %alphaa1=plot3(Ml(1,:)+vn(1)*arcvsh,Ml(2,:)+vn(2)*arcvsh,Ml(3,:)+vn(3)*arcvsh,'-k','parent',hpar);\n        set(alphaa1,'XData',Ml(1,:)+vn(1)*arcvsh,'YData',Ml(2,:)+vn(2)*arcvsh,'ZData',Ml(3,:)+vn(3)*arcvsh);\n        %alphaa2=plot3(Mt(1,:)+vn(1)*arcvsh,Mt(2,:)+vn(2)*arcvsh,Mt(3,:)+vn(3)*arcvsh,'-k','parent',hpar);\n        set(alphaa2,'XData',Mt(1,:)+vn(1)*arcvsh,'YData',Mt(2,:)+vn(2)*arcvsh,'ZData',Mt(3,:)+vn(3)*arcvsh);\n        %alphaat=text('parent',hpar,'position',txv+vn*arcvsh,'string','\\alpha','HorizontalAlignment','center','VerticalAlignment','middle','color',lcs);\n        set(alphaat,'position',txv+vn*arcvsh);\n        \n        set(alphaa1,'visible','on');\n        set(alphaa2,'visible','on');\n        set(alphaat,'visible','on');\n    else\n        set(gammaa1,'visible','off');\n        set(gammaa2,'visible','off');\n        set(gammaat,'visible','off');\n        \n        set(deltaa1,'visible','off');\n        set(deltaa2,'visible','off');\n        set(deltaat,'visible','off');\n        \n        set(alphaa1,'visible','off');\n        set(alphaa2,'visible','off');\n        set(alphaat,'visible','off');\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/24067-eular-angles-gui/euler_files/enter_eul_angs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5611899468770462}}
{"text": "% this program is designed to induce yearly variability for the data after\n% induced monthly variability by FFT using a simple linear relationship\n\nfunction [yearly_corrected_precip]=yearly_precip_correction(monthly_corrected_precip)\n% load the yearly precipitation after FFT\nload('Pnew_precip');\nP_FFT=Pnew_precip';\n\nload(monthly_corrected_precip);\n\nn=length(P_FFT); % years\nm=length(monthly_corrected_precip);  % days\n\n% calculate yearly precip \n% the fourth column of Y is precip\nj=1;\nZ=zeros(n,1);\nfor i=1:365:m\n    Z(j,1)=sum(monthly_corrected_precip(i:i+365-1,4));\n    %Z(j,1)=sum(gP(i:i+365-1,1));\n    j=j+1;\nend\n\n% calculate the ratio of yearly precip between those after FFT and\n% generated by weather generator\nfor i=1:n\n    P_ratio(i,1)=P_FFT(i,1)/Z(i,1);\nend\n \n% extend the yearly precip ratio to daily scale,the data in each\n% year are the same\nP_extent=zeros(m,1);\nj=1;\nfor i=1:365:m\n    P_extent(i:i+365-1,1)=P_ratio(j,1);\n    j=j+1;\nend\n\n% adjust the daily precip generated by WG using above ratios\nP_adjust=zeros(size(monthly_corrected_precip));\nP_adjust(:,1:3)=monthly_corrected_precip(:,1:3);\nfor i=1:m\n    P_adjust(i,4)=monthly_corrected_precip(i,4)*P_extent(i,1);\nend\nyearly_corrected_precip=P_adjust;\n\nmm=find(yearly_corrected_precip(:,4)<0);\nyearly_corrected_precip(mm,4)=0;\n\nsave('yearly_corrected_precip','yearly_corrected_precip')\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/29136-stochastic-weather-generator-weagets/WeaGETS/yearly_precip_correction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5611671130711725}}
{"text": "function obj = EVD_wbmethod(obj)\n\nglobal H W_mopt Nk Nt Nr  Ns Vn ifVFD n;\nt1 = clock;\nj = 0;\nw = zeros(Nk,1);\nv = zeros(Nk,1);\n%init\nif (ifVFD)\n    W_equal = W_mopt;\nelse\n    W_equal = exp( 1i*unifrnd(0,2*pi,Nr,Ns,Nk) );\nend\nV_equal = zeros(Nt,Ns,Nk);\nH_equal = zeros(Ns,Ns,Nk);\nm_mse = zeros(Nk,1);\nfor i = 1:Nk\n    w(i) = trace(W_equal(:,:,i)'*W_equal(:,:,i));\nend\n\nH1 = zeros(Nt,Ns,Nk);\nH2 = zeros(Nr,Ns,Nk);\ntrigger = 1;\nm_MSE_new = 100;\n\n%limit the iterations number by i<10\nwhile ( trigger > 1e-4 && j<10)\n    \n    Vn1 = Vn * w;\n    for i = 1: Nk\n        H1(:,:,i) = H(:,:,i)'*W_equal(:,:,i);\n    end\n    [V_RF,V_U] = EVD_method(H1,Vn1);\n    \n    for i = 1:Nk\n        V_equal(:,:,i) = V_RF * V_U(:,:,i);\n        v(i) = trace(V_equal(:,:,i)'*V_equal(:,:,i));\n        H2(:,:,i) = H(:,:,i)*V_equal(:,:,i);\n    end\n    Vn2 = Vn * v;\n    [W_RF,W_B] = EVD_method(H2,Vn2);\n    \n    m_MSE_old = m_MSE_new;\n    \n    for k = 1:Nk\n        W_equal(:,:,k) = W_RF * W_B(:,:,k);\n        w(k) = trace(W_equal(:,:,k)'*W_equal(:,:,k));\n        H_equal(:,:,k) = W_equal(:,:,k)'*H2(:,:,k);\n        m_mse(k) = trace(H_equal(:,:,k) * H_equal(:,:,k)' - H_equal(:,:,k) - H_equal(:,:,k)')...\n            + Vn * v(k) * w(k);\n    end\n    m_MSE_new = sum(m_mse)/Nk;\n    trigger = m_MSE_old - m_MSE_new;\n    j = j + 1;\n    obj.modmse(j,n) = m_MSE_new + Ns;\nend\n\nfor i = 1:Nk\n    V_B(:,:,i)= V_U(:,:,i) /sqrt(v(i));\nend\n\nt2 = clock;\nruntime  = etime(t2,t1);\nobj.V_B = V_B;\nobj.W_B = W_B;\nobj.V_RF = V_RF;\nobj.W_RF = W_RF;\nobj.runtime = obj.runtime + runtime;\nobj = get_wbmetric(obj);\n\n", "meta": {"author": "Zzhaoxingyu", "repo": "hybrid-beamforming-for-three-scenes", "sha": "396ae70db7dd464a65458f274a65aa113ed73c8b", "save_path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes", "path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes/hybrid-beamforming-for-three-scenes-396ae70db7dd464a65458f274a65aa113ed73c8b/broadband/Alogorithms/EVD/EVD_wbmethod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.561167110838834}}
{"text": "function g = mlpOutputGrad(model, X)\n\n% MLPOUTPUTGRAD Evaluate derivatives of mlp model outputs with respect to parameters.\n% FORMAT\n% DESC evaluates the derivates of a multi-layer perceptron's\n% outputs with respect to the parameters of the multi-layer\n% perceptron. Currently it simply wraps the NETLAB mlpderiv\n% function.\n% ARG model : the model for which the derivatives are to be\n% computed.\n% ARG X : the input data locations where the gradients are to be\n% computed.\n% RETURN g : the gradient of the outputs of the multi-layer\n% perceptron with respect to each of the parameters. The size of\n% the matrix is number of data x number of parameters x number of\n% outputs of the model.\n%\n% SEEALSO : mlpCreate, mlpderiv\n%\n% COPYRIGHT : Neil D. Lawrence, 2006\n\n% MLTOOLS\n\nif length(model.hiddenDim) == 1\n  g = mlpderiv(model, X);\nelse\n  \n  [Y, G, A] = mlpOut(model, X);\n  gw = cell(1, length(model.w));\n  for i = 1:length(gw)\n    gw{i} = zeros(size(model.w{i}));\n  end   \n  for i = 1:length(G);\n    WdG{i} = (1-G{i}.*G{i})*w{i};\n  end\n  for k = 1:model.outputDim\n    gw{end}(:, k) = Z{end}(:, k);\n    gb{end} = 1;\n    for i = length(model.w)-1:-1:1\n      %gw{i} = \n      error('Not yet implemented');\n    end\n  end\n\n% Evaluate second-layer gradients.\ngw2 = z'*deltas;\ngb2 = sum(deltas, 1);\n\n% Now do the backpropagation.\ndelhid = deltas*net.w2';\ndelhid = delhid.*(1.0 - z.*z);\n\n% Finally, evaluate the first-layer gradients.\ngw1 = x'*delhid;\ngb1 = sum(delhid, 1);\n\ng = [gw1(:)', gb1, gw2(:)', gb2];\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/mlpOutputGrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5611670933465237}}
{"text": "function [ y, m, d, f ] = jed_to_ymdf_roman ( jed )\n\n%*****************************************************************************80\n%\n%% JED_TO_YMDF_ROMAN converts a JED to a Roman YMDF date.\n%\n%  Discussion:\n%\n%    The Roman calendar used here is artificial.  It is assumed to begin\n%    on the Julian calendar date 1 January 753 BC, and to be simply a\n%    copy of the Julian calendar, shifted by 753 years.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 July 2012\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,\n%    the YMDF date.\n%\n  [ y, m, d, f ] = jed_to_ymdf_julian ( jed );\n\n  y = y_julian_to_roman ( 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_roman.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.5611059213156774}}
{"text": "function [mSynCat] = create_syncat(mCatalog,nCdf,fMu,fSigma, fMinMagIn,bPlot)\n% function [mSynCat] = create_syncat(mCatalog,nCdf,fMu,fSigma,fMinMagIn,bPlot);\n% --------------------------------------------------\n% Creates a synthetic catalog for the part below Mc with a Normal CDF.\n% Usage:\n% Before using this function, create a defined synthetic catalog according\n% to a power-law behavior. It's assumed that the smallest magnitude bin is\n% the bin of the magnitude of completeness. If fMu, fSigma and fMinMagIn are\n% missing, enter interactively.\n%\n% Incoming variable:\n% mCatalog : EQ catalog\n% nCdf : Choice of cumulative distribution function\n%        1 : Normal cumulative distribution function\n%        2 : Lognormal cumulative distribution function\n%        3 : Weibull CDF\n%\n% fMu    : Mu of Normal / Lognormal CDF\n% fSigma : Sigma of Normal / Lognormal CDF\n% fMinMagIn : Minimum magnitude for synthetic catalog\n% bPlot : Plot historgram, 0 =no plot, 1 = plot\n% Output:\n% mSynCat : Synthetic catalog\n% mCat : Catalog of events below Mc\n%\n% Authour: J. Woessner, j.woessner@sed.ethz.ch\n% last update: 10.07.04\n\n% Initialize\nmCat = [];\n\nif ~exist('bPlot','var')\n    bPlot = 0;\nend\n\n% Check for input values\nif nargin < 3\n    % Calculate probablities for Normal CDF\n    prompt = {'Enter mu:','Enter sigma:','Minimum magnitude:'};\n    dlg_title = 'Parameters for normal CDF';\n    num_lines= 1;\n    def     = {'0.8','0.4','0'};\n    answer  = inputdlg(prompt,dlg_title,num_lines,def);\n    fMu = str2double(answer(1));\n    fSigma = str2double(answer(2));\n    fMinMagIn = str2double(answer(3));\nend\n\n% Calculate FMD\n[mFMDC, mFMD] = calc_FMD(mCatalog);\n\n% Find first bin (Mc bin) with data\nvSel = (max(mFMD(2,:)) == mFMD(2,:));\nfN_Mc = mFMD(2,vSel);\n\nfMinBin = mFMD(1,vSel);\nvMagstep = fMinMagIn:0.1:fMinBin-0.1;\n\n% Choose CDF\nswitch nCdf\n    case 1\n        vProb = normcdf(vMagstep,fMu, fSigma);\n    case 2\n        vProb = logncdf(vMagstep,fMu,fSigma);\n    case 3\n        vProb = wblcdf(vMagstep,fMu,fSigma);\n    otherwise\n        disp('Check nCdf parameter!');\n        return;\nend\n\nvProb = vProb';\nvMagstep = vMagstep';\n\n% Calculate number of EQs in bins\nvN = round(vProb(:,1)*fN_Mc);\nmData = [vMagstep vN];\nvMag = [];\nnCount=1;\nfor nMag=fMinMagIn:0.1:fMinBin-0.1\n    %fM = repmat(nMag,mData(floor(abs(nMag)*10+1),2),1);\n    fM = repmat(nMag,mData(nCount,2),1);\n    vMag = [vMag; fM];\n    nCount=nCount+1;\nend\n\n% Choose appropriate number of events from the catalog, change magnitudes\n% and add to original catalog\nvInd = round(rand(length(vMag),1)*length(mCatalog(:,1)));\n% Avoid zeros\nvIndice = find(vInd == 0);\nvInd(vIndice) = vInd(vIndice)+1;\n\nfor n=1:length(vInd)\n    mCat = [mCat; mCatalog(vInd(n),:)];\nend\n%mCat = mCatalog(vSel,:);\n%mCat = mCatalog(1:length(vMag),:);\nmCat(:,6) = vMag;\nmSynCat = [mCat;mCatalog];\n\nif (exist('bPlot','var') & bPlot == 1)\n    %Plot result\n    fMaxMag = max(mCatalog(:,6));\n    figure_w_normalized_uicontrolunits('tag','maghist');\n    histogram(mSynCat(:,6),fMinMagIn:0.1:fMaxMag);\n    xlabel('Magnitude');\n    ylabel('Frequency');\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/jochen/Scriptlab/create_syncat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5610948543870385}}
{"text": "function Wrot = whiteningLocal(CC, yc, xc, nRange)\n\nWrot = zeros(size(CC,1), size(CC,1));\nfor j = 1:size(CC,1)\n    ds          = (xc - xc(j)).^2 + (yc - yc(j)).^2;\n    [~, ilocal] = sort(ds, 'ascend');\n    ilocal      = ilocal(1:nRange);\n    \n    [E, D]      = svd(CC(ilocal, ilocal));\n    D           = diag(D);\n    eps         = 1e-6;\n    wrot0       = E * diag(1./(D + eps).^.5) * E';\n    Wrot(ilocal, j)  = wrot0(:,1);\nend", "meta": {"author": "cortex-lab", "repo": "KiloSort", "sha": "cd040da1963dd760da98b54c811b3fd441d54e79", "save_path": "github-repos/MATLAB/cortex-lab-KiloSort", "path": "github-repos/MATLAB/cortex-lab-KiloSort/KiloSort-cd040da1963dd760da98b54c811b3fd441d54e79/preProcess/whiteningLocal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5610605443420719}}
{"text": "function rs = surrogate2(s)\n\n%tstoolbox/@signal/surrogate2\n%   Syntax:\n%     * rs = surrogate2(s)\n%\n%   create surrogate data for a scalar time series\n%   see : James Theiler et al.'Using Surrogate Data to Detect Nonlinearity\n%   in Time Series', APPENDIX : ALGORITHM II\n%\n% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt\n\nnarginchk(1,1);\n\nc = surrogate2(s.core); \t\t% call real working routine for parent core object\nrs = signal(c, s);\t\t\t\t% special constructor calling syntax for working routines\n\nrs = addhistory(rs,  ['Surrogated with Theiler Algorithm II'] );\nrs = addcommandlines(rs, 's = surrogate2(s');\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/surrogate2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5610286717563525}}
{"text": "%% RISE Tutorial by Dr. Tao Zha\n%% housekeeping\nclear\nclose all\nclc\n%% Instructions\n% - Please run this file block by block and make sure you read the\n% comments in each block to understand what it does. If there is anything\n% you do not understand, ask questions to the instructor or to your\n% neighbor\n% - to run a particular block, click on the block and then on your keyboard\n% press CTRL+Enter\n%% add the paths to RISE, the data and the models\nsetpaths=true;\nif setpaths\n    addpath Models % folder with the models\n    addpath Data % folder containing the data\nend\n%% Bring in some data and transform them into RISE's time series format (ts)\n\ntmp=load('Data/data_nk3eq_8501_1301');  %qdatae\ndataList={\n    'X','output gap  y_t (log GDP_t - log GDPPotential_t)'\n    'PAI','PCE core inflation pi_t (log P_t - log P_{t-1})'\n    'R','FFR R_t log(1+ffr/400)  (quarterly rate already)'\n    };\nmydata=struct();\nstartdate='1985Q1';\nfor id=1:size(dataList,1)\n    % we just give the start date, RISE automatically understand that we\n    % are dealing with quarterly data by the format startdate\n    mydata.(dataList{id,1})=ts(startdate,... start date\n        tmp.qdatae(:,id+1),... the data\n        dataList{id,2});\nend\n\n%% plot your data, compute basic statistics and look at both carefully\nvarlist=fieldnames(mydata);\nfigure('name','US data')\nnvars=numel(varlist);\nfor id=1:nvars\n    subplot(nvars,1,id)\n    dd=mydata.(varlist{id});\n    plot(dd,'linewidth',2)\n    title(mydata.(varlist{id}).varnames)\n    fprintf('%s:: mean %0.3f  stdev %0.3f\\n',mydata.(varlist{id}).varnames{1},mean(dd),std(dd));\nend\n[~,tmp]=sup_label(['US data ',mydata.(varlist{id}).start,':', mydata.(varlist{id}).finish],'t');\nset(tmp,'fontsize',15)\n\n%% Read the model(s)\n\nmodel_names={'volatilityOnly','policyOnly','volatilityPolicySame',...\n    'volatilityPolicyIndependent'};\nnmodels=numel(model_names);\nestim_models=cell(1,nmodels);\n\n% rather than putting all the models in the same vector as we did earlier,\n% we put them in a cell array. If we put them in the same vector and call\n% the estimation function, RISE will think that we want to estimate a\n% pareto-type of model. But this is not what we want to do and is probably\n% beyond the scope of these lectures.\n\n% we loop through the different models using the information in the labels\nfor imod=1:nmodels \n    % replace \"for\" by \"parfor\" if you want to use parallel computation\n    estim_models{imod}=rise(model_names{imod},... % name of the file to read\n        'saveas',true,... % write the expanded model to disk with the default name\n        'data',mydata... % we may assign the data now or later\n        );\n    % a model with multiple files inserted can be difficult to read. The\n    % expanded model could be useful for understanding what RISE does and\n    % for debugging purposes. The expanded model contains all the details\n    % of the individual files (without the comments)\nend\n\n%% We estimate the models or filter them directly\nclose all,clc\n% if we have the parallel computing toolbox, we can estimate all models in\n% one go\nfiltration=cell{1,nmodels};\nfor imod=1:nmodels \n    % replace \"for\" by \"parfor\" if you want to use parallel computation\n    disp('*--------------------------------------------------------------*')\n    disp(['*---------Estimation of ',model_names{imod},' model-----------*'])\n    disp('*--------------------------------------------------------------*')\n    [estim_models{imod},filtration{imod}]=estimate(estim_models{imod},'optimizer','fmincon');\nend\n\n%% plot the smoothed probabilities\n% we plot the low response (coef_2) and the high volatility (vol_2) regimes\nmystates={'coef_2','vol_2'};\nmylabels={'low monetary policy response regime','High volatility regime'};\nfor imod=1:nmodels\n    mytitle=['smoothed probabilities for ',model_names{imod},' model'];\n    thisstates=mystates;\n    thislabels=mylabels;\n    discard=false(1,numel(thisstates));\n    for ii=1:numel(thisstates)\n        discard(ii)=~ismember(thisstates{ii},estim_models{imod}.markov_chains.state_names);\n    end\n    thisstates=thisstates(~discard);\n    thislabels=thislabels(~discard);\n    nstates=numel(thisstates);\n    figure('name',mytitle)\n    for istate=1:nstates\n        subplot(nstates,1,istate)\n        plot(filtration{imod}.smoothed_state_probabilities.(thisstates{istate}),...\n            'linewidth',2)\n        title([thislabels{istate},'(chain ',thisstates{istate}(1:end-2),' state ',thisstates{istate}(end),')'])\n    end\n    [junk,tmp]=sup_label(mytitle,'t');\n    set(tmp,'fontsize',15)\n    orient tall    \nend\n\n", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/TaoZha/Tutorials/DSGE/Tutorial2/howto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5610286633643217}}
{"text": "function [ps,ix] = dpsimplify(p,tol)\n\n% Recursive Douglas-Peucker Polyline Simplification, Simplify\n%\n% [ps,ix] = dpsimplify(p,tol)\n%\n% dpsimplify uses the recursive Douglas-Peucker line simplification \n% algorithm to reduce the number of vertices in a piecewise linear curve \n% according to a specified tolerance. The algorithm is also know as\n% Iterative Endpoint Fit. It works also for polylines and polygons\n% in higher dimensions.\n%\n% In case of nans (missing vertex coordinates) dpsimplify assumes that \n% nans separate polylines. As such, dpsimplify treats each line\n% separately.\n%\n% For additional information on the algorithm follow this link\n% http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm\n%\n% Input arguments\n%\n%     p     polyline n*d matrix with n vertices in d \n%           dimensions.\n%     tol   tolerance (maximal euclidean distance allowed \n%           between the new line and a vertex)\n%\n% Output arguments\n%\n%     ps    simplified line\n%     ix    linear index of the vertices retained in p (ps = p(ix))\n%\n% Examples\n%\n% 1. Simplify line \n%\n%     tol    = 1;\n%     x      = 1:0.1:8*pi;\n%     y      = sin(x) + randn(size(x))*0.1;\n%     p      = [x' y'];\n%     ps     = dpsimplify(p,tol);\n%\n%     plot(p(:,1),p(:,2),'k')\n%     hold on\n%     plot(ps(:,1),ps(:,2),'r','LineWidth',2);\n%     legend('original polyline','simplified')\n%\n% 2. Reduce polyline so that only knickpoints remain by \n%    choosing a very low tolerance\n%\n%     p = [(1:10)' [1 2 3 2 4 6 7 8 5 2]'];\n%     p2 = dpsimplify(p,eps);\n%     plot(p(:,1),p(:,2),'k+--')\n%     hold on\n%     plot(p2(:,1),p2(:,2),'ro','MarkerSize',10);\n%     legend('original line','knickpoints')\n%\n% 3. Simplify a 3d-curve\n% \n%     x = sin(1:0.01:20)'; \n%     y = cos(1:0.01:20)'; \n%     z = x.*y.*(1:0.01:20)';\n%     ps = dpsimplify([x y z],0.1);\n%     plot3(x,y,z);\n%     hold on\n%     plot3(ps(:,1),ps(:,2),ps(:,3),'k*-');\n%\n%\n%\n% Author: Wolfgang Schwanghart, Markus Greim, 13. July, 2010.\n% w.schwanghart[at]unibas.ch\n\n\nif nargin == 0\n    help dpsimplify\n    return\nend\n\nif nargin ~= 2\n    error('wrong number of input arguments')\nend\n\n% error checking\nif ~isscalar(tol)\n    error('tol must be a scalar')\nend\n\n\n\n% nr of dimensions\nnrvertices    = size(p,1); \ndims    = size(p,2);\n\n% anonymous function for starting point and end point comparision\n% compare = @(a,b) (a+eps >= b && a <= b) || ...\n%                 (a-eps <= b && a >= b);\n% now in simplifyrec()       for GNU/Octave compatibility\n\n% __________________________________\n% what happens, when there are NaNs?\n% NaNs divide polylines.\nInan      = any(isnan(p),2);\n% any NaN at all?\nInanp     = any(Inan);\n\n% if there is only one vertex\nif nrvertices == 1 || isempty(p);\n    ps = p;\n    ix = 1;\n\n% if there are two \nelseif nrvertices == 2 && ~Inanp;\n    % when the line has no vertices (except end and start point of the line\n    % check if the distance between both is less than the tolerance. If so\n    % return the center\n    if dims == 2;\n        d    = hypot(p(1,1)-p(2,1),p(1,2)-p(2,2));\n    else\n        d    = sqrt(sum((p(1,:)-p(2,:)).^2));\n    end\n    \n    if d <= tol;\n        ps = sum(p,1)/2;\n        ix = 1;\n    else\n        ps = p;\n        ix = [1;2];\n    end\n    \nelseif Inanp;\n    \n    % case: there are nans in the p array\n    % --> find start and end indices of contiguous non-nan data\n    Inan = ~Inan;\n    sIX = strfind(Inan',[0 1])' + 1; \n    eIX = strfind(Inan',[1 0])'; \n \n    if Inan(end)==true;\n        eIX = [eIX;nrvertices];\n    end\n    \n    if Inan(1);\n        sIX = [1;sIX];\n    end\n    \n    % calculate length of non-nan components\n    lIX = eIX-sIX+1;   \n    % put each component into a single cell\n    c   = mat2cell(p(Inan,:),lIX,dims);\n    \n    % now call dpsimplify again via cellfun. \n    if nargout == 2;\n        [ps,ix]   = cellfun(@(x) dpsimplify(x,tol),c,'uniformoutput',false);\n        ix        = cellfun(@(x,six) x+six-1,ix,num2cell(sIX),'uniformoutput',false);\n    else\n        ps   = cellfun(@(x) dpsimplify(x,tol),c,'uniformoutput',false);\n    end\n    \n    % write the data from a cell array to a matrix\n    ps = cellfun(@(x) [x;nan(1,dims)],ps,'uniformoutput',false);    \n    ps = cell2mat(ps);\n    ps(end,:) = [];\n    \n    % ix wanted? write ix to a matrix, too.\n    if nargout == 2;\n        ix = cell2mat(ix);\n    end\n    \n       \nelse\n    \n\n% if there are no nans than start the recursive algorithm\nixe     = size(p,1);\nixs     = 1;\n\n% logical vector for the vertices to be retained\nI   = true(ixe,1);\n\n% call recursive function\n[p,I]   = simplifyrec(p,tol,ixs,ixe, dims, I);\nps  = p(I,:);\n\n% if desired return the index of retained vertices\nif nargout == 2;\n    ix  = find(I);\nend\n\nend\nend\n% _________________________________________________________\nfunction [p,I]  = simplifyrec(p,tol,ixs,ixe, dims, I);\n    \nmycompare = @(a,b) (a+eps >= b && a <= b) || ...\n                 (a-eps <= b && a >= b);\n                 \n       \n    \n    % check if startpoint and endpoint are the same \n    % better comparison needed which included a tolerance eps\n    \n    c1 = num2cell(p(ixs,:));\n    c2 = num2cell(p(ixe,:));   \n    \n    % same start and endpoint with tolerance\n    sameSE = all(cell2mat(cellfun(mycompare,c1(:),c2(:),'UniformOutput',false)));\n\n    \n    if sameSE; \n        % calculate the shortest distance of all vertices between ixs and\n        % ixe to ixs only\n        if dims == 2;\n            d    = hypot(p(ixs,1)-p(ixs+1:ixe-1,1),p(ixs,2)-p(ixs+1:ixe-1,2));\n        else\n            d    = sqrt(sum(bsxfun(@minus,p(ixs,:),p(ixs+1:ixe-1,:)).^2,2));\n        end\n    else    \n        % calculate shortest distance of all points to the line from ixs to ixe\n        % subtract starting point from other locations\n        pt = bsxfun(@minus,p(ixs+1:ixe,:),p(ixs,:));\n\n        % end point\n        a = pt(end,:)';\n\n        beta = (a' * pt')./(a'*a);\n        b    = pt-bsxfun(@times,beta,a)';\n        if dims == 2;\n            % if line in 2D use the numerical more robust hypot function\n            d    = hypot(b(:,1),b(:,2));\n        else\n            d    = sqrt(sum(b.^2,2));\n        end\n    end\n    \n    % identify maximum distance and get the linear index of its location\n    [dmax,ixc] = max(d);\n    ixc  = ixs + ixc; \n    \n    % if the maximum distance is smaller than the tolerance remove vertices\n    % between ixs and ixe\n    if dmax <= tol;\n        if ixs ~= ixe-1;\n            I(ixs+1:ixe-1) = false;\n        end\n    % if not, call simplifyrec for the segments between ixs and ixc (ixc\n    % and ixe)\n    else   \n        [p,I]   = simplifyrec(p,tol,ixs,ixc, dims, I);\n        [p,I]   = simplifyrec(p,tol,ixc,ixe, dims, I);\n\n    end\n\nend\n% end\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21132-line-simplification/dpsimplify_octave.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.5610286631679128}}
{"text": "%PLOTF Plot feature distribution, special version\n% \n%   h = PLOTF(A,N)\n% \n% Produces 1-D density plots for all the features in dataset A. The \n% densities are estimated using PARZENML. N is the number of \n% feature density plots on a row. \n% \n% See also DATASETS, PARZENML\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: plotf.m,v 1.6 2009/11/13 08:54:18 davidt Exp $\n\nfunction h_out = plotf(a,n,z)\n  %DXD make a standard setting for n, I'm getting crazy!\n  if nargin<2\n    n = 1;\n  end\n\n\t\t\n  if ~isdataset(a)\n    a = prdataset(a,1); % solves a lot of problems\n  end\n  [m,k,c] = getsize(a);\n\n\t% Define the color for each of the classes:\n  if c == 1\n    clrmap = [0 0 1];\n\telseif c == 2\n\t\tclrmap = [0 0 1; 1 0 0];\n\telse\n\t\tclrmap = hsv(c);\n\tend\n\n\t% Make subplots for each feature, so a grid of p x q subplots is\n\t% defined\n\th = [];\n\tif k >= n\n\t\tp = ceil(k/n); q = n;\n\telse\n\t\tp = k; q = 1;\n  end\n\n  if isempty(getfeatlab(a))\n    a = setfeatlab(a,[1:k]');\n  end\n  % Get the feature names\n  feats = getfeatlab(a,'string');\n\t%DXD what happens here?!\n  %RD If feature labels are scalars to single characters it might be\n  %nicer to put 'Feature ' in front of it.\n\tif size(feats,2) == 1\n\t\tfeats = [repmat('Feature ',size(feats,1),1) feats];\n\tend\n\tif isempty(feats)\n\t\tfeats = num2str((1:k)');\n\tend\n\n\t% Make the plot for each of the features:\n\tfor j = 1:k\n\t\tb = a(:,j);\n\t\ts = zeros(1,c);\n\t\td = zeros(121,c);\n\t\tbb = [-0.10:0.01:1.10]' * (max(b)-min(b)) + min(b);\n\t\tex = 0;\n\t\t% Make a density estimate of each of the classes:\n\t\tfor i = 1:c\n\t\t\tI = findnlab(a,i);\n\t\t\tD = +distm(bb,b(I,:));\n      if nargin < 3\n        s(i) = parzenml(b(I,:));\n      else\n        s(i) = z(i);\n      end\n\t\t\t% Compute the density function\n\t\t\td(:,i) = sum(exp(-D/(s(i).^2)),2)./(length(I)*s(i));;\n\t\tend\n\t\t% Create the subplots with the correct sizes:\n    if p==1 && q==1\n      % avoid subplots in case of single plot\n      plot(bb,zeros(size(bb)),'w.');\n      hold on;\n    else\n      subplot(p,q,j)\n      plot(bb,zeros(size(bb)),'w.');\n      hold on\n    end\n\t\th = [];\n\t\t% Scatter the data and plot the density functions for each of the\n\t\t% classes:\n\t\tfor i = 1:c\n\t\t\tI = findnlab(a,i);\n\t\t\thh = plot(b(I),zeros(size(b(I))),'x',bb,+d(:,i));\n\t\t\tset(hh,'color',clrmap(i,:));\n\t\t\th = [h;hh];\n\t\tend\n\t\tlegend(h(1:2:end)',num2str(getlablist(a))); %does not work properly\n\t\ttitle([getname(a) ': ' feats(j,:)]);\n\t\tV = axis;\n\t\taxis([bb(1) bb(end) V(3) V(4)]);\n\t\tset(gca,'xtick',[]);\n\t\tset(gca,'ytick',[]);\n\t\txlabel(feats(j,:));\n\t\thold off\n\tend\n\n\t% The last details to take care of:\n\tif k == 1, title(''); end\n\tif nargout > 0\n\t\th_out = h;\n\tend\n\n\treturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/plotf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5610286631679128}}
{"text": "function color_plot(x,colors,varargin)\n% COLOR_PLOT    Scatterplot with colored points.\n% color_plot(x) makes a scatterplot of x(:,1) versus x(:,2) with points colored\n% according to quantiles of x(:,3).\n% color_plot(x,n) specifies the number of color quantiles (default 4).\n% color_plot(x,colors) specifies an RGB matrix of colors (the number of rows\n% determines the number of quantiles).  The default is YlGnBu_colors.\n% color_plot(...,'ColorBar',1) adds a color bar with tick marks from the\n% quantile values.\n%\n% Example:\n%   xy = ndgridmat(linspace(-12,12,20),linspace(-12,12,20));\n%   z = sin(sqrt(xy(:,1).^2 + xy(:,2).^2));\n%   color_plot([xy z]);\n%\n% See also YlGnBu_colors.\n\n% Written by Tom Minka and Charles Sutton\n\nargs = makestruct(varargin);\ndefault_args = struct('ColorBar',0,'MarkerSize',6);\nargs = setfields(default_args,args);\n\nif nargin < 2\n  colors = 4;\nend\nif length(colors) == 1\n  nlevels = colors;\n  colors = YlGnBu_colors(nlevels);\nelse\n  nlevels = rows(colors);\nend\n% color groups\n[c,q] = cut_quantile(x(:,3),nlevels);\nfor lev = 1:nlevels\n  i = find(c == lev);\n  plot(x(i,1),x(i,2),'o','Color',colors(lev,:),'MarkerFaceColor',colors(lev,:),'MarkerSize',args.MarkerSize);\n  hold on\nend\nhold off\n\ncolormap(colors);\n\nif args.ColorBar \n  caxis ([0,1]);\n  \n  cTickLbls = cell(numel(q), 1);\n  for i = 1:length(q)\n      cTickLbls{i} = num2str(q(i), '%11.2g');\n  end\n  \n  colorbar('YTick', linspace(0,1,nlevels+1), 'YTickLabel', cTickLbls);\nend\n\nset(gca,'Color','none')\n", "meta": {"author": "tminka", "repo": "lightspeed", "sha": "e65560c5aa3aae947a62dd662a6444cdfa96fc4f", "save_path": "github-repos/MATLAB/tminka-lightspeed", "path": "github-repos/MATLAB/tminka-lightspeed/lightspeed-e65560c5aa3aae947a62dd662a6444cdfa96fc4f/graphics/color_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5610286549722908}}
{"text": "function [germs, germPaths] = centroidalVoronoi2d(germs, poly, varargin)\n%CENTROIDALVORONOI2D Centroidal Voronoi tesselation within a polygon.\n%\n%   PTS = centroidalVoronoi2d(NPTS, POLY)\n%   Generate points in a polygon based on centroidal voronoi tesselation.\n%   Centroidal germs can be computed by using the Llyod's algorithm:\n%   1) initial germs are chosen at random within polygon\n%   2) voronoi polygon of the germs is computed\n%   3) the centroids of each domain are computed, and used as germs of the\n%   next iteration\n%\n%   [PTS, PATHLIST] = centroidalVoronoi2d(NPTS, POLY)\n%   Also returns the path of each germs at each iteration. The result\n%   PATHLIST is a cell array with as many cells as the number of germs,\n%   containing in each cell the successive positions of the germ.\n%\n%   PTS = centroidalVoronoi2d(.., PARAM, VALUE)\n%   Specify one or several optional arguments. PARAM can be one of:\n%   * 'nIter'   specifies the number of iterations of the algorithm\n%       (default is 50)\n%   * 'verbose' display iteration number. Default is false.\n%\n%   Example\n%     poly = ellipseToPolygon([50 50 40 30 20], 200);\n%     nGerms = 100;\n%     germs = centroidalVoronoi2d(nGerms, poly);\n%     figure; hold on;\n%     drawPolygon(poly, 'k');\n%     drawPoint(germs, 'bo');\n%     axis equal; axis([0 100 10 90]);\n%     % extract regions of the CVD\n%     box = polygonBounds(poly);\n%     [n, e] = boundedVoronoi2d(box, germs);\n%     [n2, e2] = clipGraphPolygon(n, e, poly);\n%     drawGraphEdges(n2, e2, 'b');\n%\n%   See also \n%   graphs, boundedVoronoi2d, centroidalVoronoi2d_MC\n%\n%   Rewritten from programs found in\n%   http://people.scs.fsu.edu/~burkardt/m_src/cvt/cvt.html\n%\n%   Reference:\n%    Qiang Du, Vance Faber, and Max Gunzburger,\n%    Centroidal Voronoi Tessellations: Applications and Algorithms,\n%    SIAM Review, Volume 41, 1999, pages 637-676.\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2012-02-23, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012-2022 INRA - Cepia Software Platform\n\n%% Parse input arguments\n\n% Number of germs\nif isscalar(germs)\n    nGerms = germs;\n    germs = [];\nelse\n    nGerms = size(germs, 1);\nend\n\n% Number of iterations\nnIter = 50;\n\nverbose = false;\n\nkeepPaths = nargout > 1;\n\nwhile length(varargin) > 1\n    paramName = varargin{1};\n    switch lower(paramName)\n        case 'verbose'\n            verbose = varargin{2};\n        case 'niter'\n            nIter = varargin{2};\n            \n        otherwise\n            error(['Unknown parameter name: ' paramName]);\n    end\n\n    varargin(1:2) = [];\nend\n\n\n%% Initialisations\n\n% bounding box of polygon\nbbox = polygonBounds(poly);\n\n% init germs if needed\nif isempty(germs)\n    germs = generatePointsInPoly(nGerms);\nend\ngermIters = cell(nIter, 1);\n\n\n%% Iteration of the Lloyd algorithm\n\nfor i = 1:nIter\n     if verbose\n        disp(sprintf('Iteration: %d/%d', i, nIter)); %#ok<DSPS>\n    end\n    \n    if keepPaths\n        germIters{i} = germs;\n    end\n    \n    % Compute Clipped Voronoi diagram of germs\n    if verbose\n        disp('  compute Voronoi Diagram');\n    end\n    [n, e, f] = boundedVoronoi2d(bbox, germs);\n    [n2, e2, f2] = clipMesh2dPolygon(n, e, f, poly); %#ok<ASGLU>\n\n    % update the position of each germ\n    if verbose\n        disp('  compute centroids');\n    end\n    for iGerm = 1:nGerms\n        polygon = n2(f2{iGerm}, :);\n        germs(iGerm,:) = polygonCentroid(polygon);\n    end\n    \nend\n\n\n%% Evenutally compute germs trajectories\n\nif nargout > 1\n    % init\n    germPaths = cell(nGerms, 1);\n    path = zeros(nIter+1, 2);\n    \n    % Iteration on germs\n    for i = 1:nGerms\n        \n        % create path corresponding to germ\n        for j = 1:nIter\n            pts = germIters{j};\n            path(j,:) = pts(i,:);\n        end\n        path(nIter+1, :) = germs(i,:);\n        \n        germPaths{i} = path;\n    end\nend\n\nfunction pts = generatePointsInPoly(nPts)\n    % extreme coordinates\n    xmin = bbox(1);  xmax = bbox(2);\n    ymin = bbox(3);  ymax = bbox(4);\n    \n    % compute size of box\n    dx = xmax - xmin;\n    dy = ymax - ymin;\n    \n    % allocate memory for result\n    pts = zeros(nPts, 2);\n\n    % iterate until all points have been sampled within the polygon\n    ind = (1:nPts)';\n    while ~isempty(ind)\n        NI = length(ind);\n        x = rand(NI, 1) * dx + xmin;\n        y = rand(NI, 1) * dy + ymin;\n        pts(ind, :) = [x y];\n        \n        ind = ind(~polygonContains(poly, pts(ind, :)));\n    end\nend\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/graphs/centroidalVoronoi2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.7217432122827969, "lm_q1q2_score": 0.5610108912643559}}
{"text": "function c8_log_test ( )\n\n%*****************************************************************************80\n%\n%% C8_LOG_TEST tests C8_LOG.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    12 February 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  seed = 123456678;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'C8_LOG_TEST\\n' );\n  fprintf ( 1, '  C8_LOG computes the logarithm of a C8.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ...\n    '       C1=C8_UNIFORM_01          C2=C8_LOG(C1)             C3=C8_EXP(C2))\\n' );\n  fprintf ( 1, '     ---------------------     ---------------------     ---------------------\\n' );\n  fprintf ( 1, '\\n' );\n\n  for test = 1 : 10\n \n    [ c1, seed ] = c8_uniform_01 ( seed );\n    c2 = c8_log ( c1 );\n    c3 = c8_exp ( c2 );\n\n    fprintf ( 1, '  (%12f  %12f)  (%12f  %12f)  (%12f  %12f)\\n', ...\n      real ( c1 ), imag ( c1 ), real ( c2 ), imag ( c2 ), real ( c3 ), imag ( c3 ) );\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_log_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.561010889406605}}
{"text": "function visualize_adv(W, horiz, n_rows, n_cols, do_sort, borders)\n\nif (nargin < 2)\n    horiz = 0;\nend\n\nif (nargin < 5)\n    do_sort = 0;\nend\n\nif (do_sort == 1)\n    Wnorms = sum(W.^2,1);\n    [B,IX] = sort(Wnorms,'descend');\n    W = W(:,IX);\nend\n\n% how many pixels for borders?\nif (nargin < 6)\n    borders = 1;\nend\n\nfprintf('Visualizing patches\\n');\n[ndim,nunits]=size(W);\nnpix = floor(sqrt(ndim)+0.999);\nnpix2 = floor(sqrt(nunits)+0.999);\nminW=min(W(:));\nmaxW=max(W(:));\n\nif (nargin < 4)\n    n_rows = npix2;\n    n_cols = npix2;\nend\n\n%bigpic = -(minW+maxW)/2*ones(((npix+borders)*npix2+borders));\n%bigpic = -(minW+maxW)/2*ones(((n_rows+borders)*npix2+borders), ((n_cols+borders)*npix2+borders));\nbigpic = -(minW+maxW)/2*ones(((npix+borders)*n_rows+borders), ((npix+borders)*n_cols+borders));\n%if (nunits/npix2<=npix2-1),\n%    bigpic = bigpic(:,1:(npix+borders)*(npix2-1)+borders);\n%end;\nidx = 0;\nfor i=1:n_rows\n    for j=1:n_cols\n        idx = idx + 1;\n\n        if idx > nunits\n            break;\n        end\n\n        if (horiz)\n            bigpic((i-1)*(npix+borders)+borders+1:(i-1)*(npix+borders)+borders+npix,...\n                (j-1)*(npix+borders)+borders+1:(j-1)*(npix+borders)+borders+npix)...\n                = reshape(W(:,idx),npix,npix)';\n        else\n            bigpic((i-1)*(npix+borders)+borders+1:(i-1)*(npix+borders)+borders+npix,...\n                (j-1)*(npix+borders)+borders+1:(j-1)*(npix+borders)+borders+npix)...\n                = reshape(W(:,idx),npix,npix);\n        end\n    end\nend;\nimagesc(bigpic);\ncolormap(gray);\naxis off;\naxis equal;\nfprintf('done.\\n');\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/visualize_adv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5610108819597672}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\nfunction result = cvalue(x1, x2, a, b, N, V, ...\n                        model, t, r, q, varargin)\n\nNstrike = length(x1);\n\nexp2 = exp( 1i .* repmat((1:N)',1,Nstrike) * diag((x2 - a) ./ (b - a)) .* pi );    % init\nexp1 = exp( 1i .* repmat((1:N)',1,Nstrike) * diag((x1 - a) ./ (b - a)) .* pi );    % init\n\nm = zeros(3*N-1, Nstrike);                                        % init base\n\nm(N,:) = 1i * pi * (x2 - x1) ./ (b - a);\nm(N+1:2*N,:) = 1 ./ repmat((1:N)',1,Nstrike) .* ( exp2 - exp1 );\nm(1:N-1,:) = - conj(flipud(m(N+1:2*N-1, :)));\nm(2*N+1:3*N-1,:) = ( exp2(1:N-1,:) * diag(exp2(N, :)) - exp1(1:N-1,:) ...\n    * diag(exp1(N,:)) ) ./ ( repmat((N+1:2*N-1)',1,Nstrike) );\n\nGrid_j = (0:N-1)';                                          % fix grid\n\n% compute u values\nu = exp(feval(@CF, model,pi*repmat(Grid_j,1,Nstrike)*diag(1./(b-a)), t,r,q,varargin{:})) .* V;\nu(1,:) = 0.5*u(1,:);\n\nm_s = [m(N:-1:1, :); zeros(1,Nstrike); m(2*N-1:-1:N+1, :)];\nu_s = [u; zeros(N, Nstrike)];\nm_c = m(3*N-1:-1:N, :);\n\nshortCut = 1;\n\n% apply fft five times\nif shortCut == 1\n    zeta = -ones(2*N, Nstrike);\n    zeta(2 .* (1:N)' - 1,:) = 1;\n\n    fft_u_s = fft(u_s);\n    xi_s = ifft((fft(m_s)) .* fft_u_s);\n    xi_c = ifft((fft(m_c)) .* (zeta .* fft_u_s));\n\n    result = exp(-r * t) / pi .* imag( xi_s(1:N,:) + flipud(xi_c(1:N,:)) );\nelse   \n    M_c = zeros(N, N);\n    M_s = zeros(N, N);\n    \n    result = zeros(N,Nstrike);\n    \n    for k = 1:Nstrike\n        for n = 0:N-1\n            M_c(:, n+1) = m(N+n:2*N-1+n,k);\n            M_s(:, n+1) = m(N+n:-1:1+n,k);\n        end\n\n        result(:,k) = exp(-r*t) / pi .* imag((M_c + M_s) * u(:,k));\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/37617-cos-method-multiple-strikes-bermudan-greeks/Cos_Method_Bermudan_Mult_Strikes/cvalue.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5609406508391035}}
{"text": "close all;\n% function F = discriminative_texture_feature(I_TEXT,theta,verbose,colored,include_intensity,tau_diff,steps_diff,sigma_diff)\n\nZ = imread('zebra.bmp');\nfigure; imagesc(Z); set(gcf,'Name','original image');\n% Z0 = discriminative_texture_feature(double(Z),6,[1 2],0,0,1,500,0); % \n\nZ1 = discriminative_texture_feature(double(Z),0,[1 2],0,1,1,500,0); % this takes a lot of time!, compare to p 64 of Thomas Brox's Phd Thesis\nZ2 = discriminative_texture_feature(double(Z));% this is a rasonable approximation(depending on the application) to the previous one while being much faster\n\nF = imread('frog.bmp');\nfigure; imagesc(F); set(gcf,'Name','original image');\n% F0 = discriminative_texture_feature(double(F),6,[1 2],0,0,1,500,0); % \nF1 = discriminative_texture_feature(double(F),0,[1 2],0,1,1,1000,0); % this takes a lot of time!, compare to p 65 of Thomas Brox's Phd Thesis\n\nF2 = discriminative_texture_feature(double(F),2,[2],0,1,10,100,0.5); % this is a rasonable approximation(depending on the application to the previous one while being much faster\n\n[sy sx d] = size(Z);\nfigure;colormap gray;\nsubplot(2,3,1); imagesc(Z); title('original image');\nfor i = 1 :5, subplot(2,3,i+1); imagesc(reshape(Z1(i,:),[sy sx])); title(sprintf('F%d',i)); 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/27618-sparse-set-of-features-for-texture-discrimination/test_discriminative_texture.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5609406451287547}}
{"text": "function pascal_to_i4_test ( )\n\n%*****************************************************************************80\n%\n%% PASCAL_TO_I4_TEST tests PASCAL_TO_I4.\n%\n%  Location:\n%\n%    http://people.sc.fsu.edu/~jburkardt/m_src/triangle_integrals/pascal_to_i4.m\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    13 April 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'PASCAL_TO_I4_TEST\\n' );\n  fprintf ( 1, '  PASCAL_TO_I4 converts Pascal triangle indices to a\\n' );\n  fprintf ( 1, '  linear index.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '     I     J =>    K\\n' );\n  fprintf ( 1, '\\n' );\n\n  for d = 0 : 4\n    for i = d : -1 : 0\n      j = d - i;\n      k = pascal_to_i4 ( i, j );\n      fprintf ( 1, '  %4d  %4d    %4d\\n', i, j, k );\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/triangle_integrals/pascal_to_i4_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.5609406369434519}}
{"text": "%load('BoxTorusMesh.mat')\n%meshFit = mesh;\nuh = UHfit(:,22);\nmeshFit = enrichMesh3D(meshFit,0);\nbc = [1,1,1,1,1,1];\nfemFit = genNedFEM3D(meshFit,bc);\nng = 1;\nX1 = meshFit.p(meshFit.t(:,1),:); X2 = meshFit.p(meshFit.t(:,2),:); \nX3 = meshFit.p(meshFit.t(:,3),:); X4 = meshFit.p(meshFit.t(:,4),:); \ngw = gaussWtetra(ng);\n[gx,gy,gz] = gaussPtetra(X1,X2,X3,X4,ng);\nfeEvalBas = @EvalNed1Bas3D;\n\nuhK = uh(femFit.g2ldof); \nuK1 = 0; uK2 = 0; uK3 = 0;\nfor i = 1:6\n    uK1 = uK1 + uhK(:,i).*feEvalBas(femFit.bas, ':', gx, gy, gz, i, 0, 1).*femFit.t_e_orit(:,i);\n    uK2 = uK2 + uhK(:,i).*feEvalBas(femFit.bas, ':', gx, gy, gz, i, 0, 2).*femFit.t_e_orit(:,i);\n    uK3 = uK3 + uhK(:,i).*feEvalBas(femFit.bas, ':', gx, gy, gz, i, 0, 3).*femFit.t_e_orit(:,i);\nend\n\nVhfit = [uK1,uK2,uK3];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%% separate evaluation\ndomain = [-1,1,-1,1,-1,1];\nnx = 64;\nny = nx;\nnz = nx;\nmesh = genMesh3D(domain, nx, ny, nz);\nmesh = enrichMesh3D(mesh,2);\ntol = 10^(-12);\nzCut = -0.3125;\nfp1 = mesh.p(mesh.f(:,1),:);\nfp2 = mesh.p(mesh.f(:,2),:);\nfp3 = mesh.p(mesh.f(:,3),:);\nfZid = (abs(fp1(:,3)-zCut)<tol).*(abs(fp2(:,3)-zCut)<tol).*(abs(fp3(:,3)-zCut)<tol);\nfZid = find(fZid==1);\nfmpt = (fp1(fZid,:)+fp2(fZid,:)+fp3(fZid,:))/3;\n\nfMallfit = (meshFit.p(meshFit.t(:,1),:)+meshFit.p(meshFit.t(:,2),:)+...\n    meshFit.p(meshFit.t(:,3),:)+meshFit.p(meshFit.t(:,4),:))/4;\n\ntic\n[tr,tj]=findtria(meshFit.p,meshFit.t,fmpt);\ntoc\n\nVhCut = [uK1(tj),uK2(tj),uK3(tj)];\n\nfmptPlan = fmpt(:,1:2);\nzDT = delaunay(fmptPlan);\n\n\n%%%%% trisulf plot\ntrisurf(zDT,fmptPlan(:,1),fmptPlan(:,2),VhCut(:,1));\nshading interp\n\n%%%%% vector field plot\nquiver3(fmpt(:,1),fmpt(:,2),fmpt(:,3),VhCut(:,1),VhCut(:,2),VhCut(:,3))\n\n%%%%%% contour plot\ntricontour(fmptPlan,zDT,VhCut(:,1),10)\n\ntid1 = find(mesh.tLoc==1);\ntid1 = tid1(1:50:end);\nfmpt1 = fMall(tid1,:);\n[tr,tj]=findtria(meshFit.p,meshFit.t,fmpt1);\nVh1 = Vhfit(tj,:);\nquiver5(fmpt1(:,1),fmpt1(:,2),fmpt1(:,3),...\n    Vh1(:,1),Vh1(:,2),Vh1(:,3),5,'filled');\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/PlotGenerateVectorFieldFit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5609406327539825}}
{"text": "function test_tutorial_natmeg2014_timefrequency\n\n% WALLTIME 00:30:00\n% MEM 4gb\n% DEPENDENCY\n\n% this script executes the MATLAB content from\n% http://www.fieldtriptoolbox.org/tutorial/natmeg2014/timefrequency\n%\n% it corresponds to the wiki version of 7 October 2014\n\nclear all\nclose all\n\ncd(dccnpath('/home/common/matlab/fieldtrip/data/ftp/workshop/natmeg2014'));\n\ncfg = [];\ncfg.dataset = 'oddball1_mc_downsampled.fif';\ncfg.channel = 'MEG';\n\n% define trials based on responses\ncfg.trialdef.prestim       = 1.5;\ncfg.trialdef.poststim      = 2.0;\ncfg.trialdef.stim_triggers = [1 2];\ncfg.trialdef.rsp_triggers  = [256 4096];\ncfg.trialfun               = 'trialfun_oddball_responselocked';\ncfg                        = ft_definetrial(cfg);\n\n% preprocess MEG data\ncfg.continuous             = 'yes';\ncfg.demean                 = 'yes';\ncfg.dftfilter              = 'yes';\ncfg.dftfreq                = [50 100];\n\ndata_MEG_responselocked    = ft_preprocessing(cfg);\n\ncfg              = [];\ncfg.output       = 'pow';\ncfg.channel      = 'all';\ncfg.method       = 'mtmconvol';\ncfg.taper        = 'hanning';\ncfg.toi          = [-1 : 0.10 : 1.5];\ncfg.foi          = 1:40;\ncfg.t_ftimwin    = ones(size(cfg.foi)) * 0.5;\n\ncfg.trials       = find(data_MEG_responselocked.trialinfo(:,1) == 256);\nTFR_left_MEG     = ft_freqanalysis(cfg, data_MEG_responselocked);\n\ncfg.trials       = find(data_MEG_responselocked.trialinfo(:,1) == 4096);\nTFR_right_MEG    = ft_freqanalysis(cfg, data_MEG_responselocked);\n\ncfg = [];\ncfg.baseline     = [-0.5 -0.1];\ncfg.baselinetype = 'absolute';\ncfg.zlim         = [-2e-26 2e-26];\ncfg.showlabels   = 'yes';\ncfg.layout       = 'neuromag306mag.lay';\ncfg.channel      = 'MEG*1';\n\nfigure;\nft_multiplotTFR(cfg, TFR_left_MEG);\n\ncfg = [];\ncfg.baseline     = [-0.5 -0.1];\ncfg.baselinetype = 'absolute';\ncfg.maskstyle    = 'saturation';\ncfg.zlim         = [-1e-26 1e-26];\ncfg.channel      = 'MEG1041';\n\nfigure;\nft_singleplotTFR(cfg, TFR_left_MEG);\n\ncfg = [];\ncfg.baseline     = [-0.5 -0.1];\ncfg.baselinetype = 'absolute';\ncfg.xlim         = [0.4 0.8];\ncfg.zlim         = [-4e-27 4e-27];\ncfg.ylim         = [15 25];\ncfg.marker       = 'on';\ncfg.layout       = 'neuromag306mag.lay';\ncfg.channel      = 'MEG*1';\n\nfigure;\nft_topoplotTFR(cfg, TFR_left_MEG);\n\ncfg = [];\ncfg.baseline     = [-0.5 -0.1];\ncfg.baselinetype = 'absolute';\ncfg.xlim         = [0.4 0.8];\ncfg.zlim         = [-4e-27 4e-27];\ncfg.ylim         = [15 25];\ncfg.marker       = 'on';\ncfg.layout       = 'neuromag306mag.lay';\ncfg.channel      = 'MEG*1';\n\nfigure;\nft_topoplotTFR(cfg, TFR_right_MEG);\n\ncfg = [];\ncfg.parameter = 'powspctrm';\ncfg.operation = '(x1-x2)/(x1+x2)';\n\nTFR_diff_MEG = ft_math(cfg, TFR_right_MEG, TFR_left_MEG);\n\ncfg = [];\ncfg.xlim         = [0.4 0.8];\ncfg.zlim         = [-0.4 0.4];\ncfg.ylim         = [15 25];\ncfg.marker       = 'on';\ncfg.layout       = 'neuromag306mag.lay';\ncfg.channel      = 'MEG*1';\n\nfigure;\nft_topoplotTFR(cfg, TFR_diff_MEG);\n\ncfg = [];\ncfg.dataset = 'oddball1_mc_downsampled.fif';\n\n% define trials based on responses\ncfg.trialdef.prestim       = 1.5;\ncfg.trialdef.poststim      = 2.0;\ncfg.trialdef.stim_triggers = [1 2];\ncfg.trialdef.rsp_triggers  = [256 4096];\ncfg.trialfun               = 'trialfun_oddball_responselocked';\ncfg                        = ft_definetrial(cfg);\n\n% preprocess EEG data\ncfg.channel                = 'EEG';\ncfg.continuous             = 'yes';\ncfg.demean                 = 'yes';\ncfg.dftfilter              = 'yes';\ncfg.dftfreq                = [50 100];\n\ndata_EEG_responselocked    = ft_preprocessing(cfg);\n\nif false\n  % skip the interactive section\n  % select bad channels\n  cfg = [];\n  cfg.metric  = 'var';\n  temp        = ft_rejectvisual(cfg, data_EEG_responselocked);\n  % with this little trick we get the names of the selected channels\n  badchannels = setdiff(data_EEG_responselocked.label,temp.label);\nelse\n  badchannels = {\n    'EEG001'\n    'EEG002'\n    'EEG003'\n    'EEG004'\n    'EEG005'\n    'EEG006'\n    'EEG007'\n    'EEG008'\n    'EEG015'\n    'EEG016'\n    'EEG017'\n    'EEG097'\n    'EEG098'\n    'EEG099'\n    'EEG100'\n    'EEG101'\n    'EEG102'\n    'EEG111'\n    'EEG112'};\nend\n\n% determine neighbours structure\ncfg            = [];\ncfg.method     = 'triangulation';\ncfg.senstype   = 'EEG'; % Our data still contains information from the MEG channels, we want to make sure ft_prepare_neighbours does not get confused\nneighbours_EEG = ft_prepare_neighbours(cfg, data_EEG_responselocked);\n\n% plotting neighbours\ncfg            = [];\ncfg.neighbours = neighbours_EEG;\ncfg.senstype   = 'EEG';\nft_neighbourplot(cfg, data_EEG_responselocked);\n\n% fix channels\ncfg = [];\ncfg.method                    = 'spline';\ncfg.neighbours                = neighbours_EEG;\ncfg.badchannel                = badchannels;\ncfg.senstype                  = 'EEG';\ndata_clean_EEG_responselocked = ft_channelrepair(cfg, data_EEG_responselocked);\n\n\ncfg = [];\ncfg.reref                  = 'yes';\ncfg.refchannel             = 'all';\ndata_clean_EEG_responselocked = ft_preprocessing(cfg, data_clean_EEG_responselocked);\n\ncfg              = [];\ncfg.output       = 'pow';\ncfg.channel      = 'all';\ncfg.method       = 'mtmconvol';\ncfg.taper        = 'hanning';\ncfg.toi          = [-1 : 0.10 : 1.5];\ncfg.foi          = 1:40;\ncfg.t_ftimwin    = ones(size(cfg.foi)) * 0.5;\n\ncfg.trials       = find(data_clean_EEG_responselocked .trialinfo(:,1) == 256);\nTFR_left_EEG     = ft_freqanalysis(cfg, data_clean_EEG_responselocked );\n\ncfg.trials       = find(data_clean_EEG_responselocked .trialinfo(:,1) == 4096);\nTFR_right_EEG    = ft_freqanalysis(cfg, data_clean_EEG_responselocked );\n\ncfg = [];\ncfg.baseline     = [-0.5 -0.1];\ncfg.baselinetype = 'absolute';\ncfg.xlim         = [0.5 1.0];\ncfg.zlim         = [-4e-12 4e-12];\ncfg.ylim         = [15 25];\ncfg.marker       = 'on';\ncfg.layout       = 'natmeg_customized_eeg1005.lay';\n\nfigure;\nft_topoplotTFR(cfg, TFR_left_EEG);\n\ncfg = [];\ncfg.baseline     = [-0.5 -0.1];\ncfg.baselinetype = 'relchange';\ncfg.ylim         = [15 25];\ncfg.xlim         = [0.5 1.0];\ncfg.zlim         = [-1.2 1.2];\ncfg.layout       = 'natmeg_customized_eeg1005.lay';\n\nfigure;\nft_topoplotTFR(cfg, TFR_left_EEG);\n\ncfg = [];\ncfg.parameter    = 'powspctrm';\ncfg.operation    = '(x1-x2)/(x1+x2)';\nTFR_diff_EEG = ft_math(cfg, TFR_right_EEG, TFR_left_EEG);\n\nif false\n  % skip the interactive section\n  % if ft_math didn't work, then just do it by hand - its exactly the same:\n  TFR_diff_EEG = TFR_right_EEG;\n  TFR_diff_EEG.powspctrm = (TFR_right_EEG.powspctrm - TFR_left_EEG.powspctrm) ./ (TFR_right_EEG.powspctrm + TFR_left_EEG.powspctrm);\nend\n\ncfg = [];\ncfg.xlim         = [0.4 0.8];\ncfg.ylim         = [15 25];\ncfg.zlim         = [-0.2 0.2];\ncfg.marker       = 'on';\ncfg.layout       = 'natmeg_customized_eeg1005.lay';\n\nfigure;\nft_topoplotTFR(cfg, TFR_diff_EEG);\n\ncfg = [];\ncfg.baseline     = [-0.5 -0.1];\ncfg.baselinetype = 'absolute';\ncfg.xlim         = [0.4 0.8];\ncfg.ylim         = [15 25];\ncfg.zlim         = [-1e-24 1e-24];\ncfg.marker       = 'on';\ncfg.layout       = 'neuromag306planar.lay';\n\nfigure;\nft_topoplotTFR(cfg, TFR_left_MEG);\n\nTFR_left_MEG_comb  = ft_combineplanar([],TFR_left_MEG);\nTFR_right_MEG_comb = ft_combineplanar([],TFR_right_MEG);\n\ncfg = [];\ncfg.baseline     = [-0.5 -0.1];\ncfg.baselinetype = 'absolute';\ncfg.xlim         = [0.4 0.8];\ncfg.ylim         = [15 25];\ncfg.zlim         = [-4e-24 4e-24];\ncfg.marker       = 'on';\ncfg.layout       = 'neuromag306cmb.lay';\n\nfigure;\nft_topoplotTFR(cfg, TFR_left_MEG_comb);\n\ncfg = [];\ncfg.parameter = 'powspctrm';\ncfg.operation = '(x1-x2)/(x1+x2)';\n\nTFR_diff_MEG_comb = ft_math(cfg, TFR_right_MEG_comb, TFR_left_MEG_comb);\n\ncfg = [];\ncfg.baseline     = [-0.5 -0.1];\ncfg.baselinetype = 'absolute';\ncfg.xlim         = [0.4 0.8];\ncfg.ylim         = [15 25];\ncfg.zlim         = [-0.3 0.3];\ncfg.marker       = 'on';\ncfg.layout       = 'neuromag306cmb.lay';\n\nfigure;\nft_topoplotTFR(cfg, TFR_diff_MEG_comb);\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_natmeg2014_timefrequency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.5608999696582414}}
{"text": "function A = repmatmatch(a,B)\n%Replicate and tile an array to match the size of a given N-D array\n% \n% Syntax:\tA = repmatmatch(a,B)\n% \n% Inputs: \n% \ta - Input array to tile\n% \tB - N-D array to match the size of\n% \n% Outputs: \n% \tA - The replicated and tiled copy of input 'a'\n% \n% Example: \n% \ta = [1 2 3];\n% \tB = rand(2,3);\n% \tA = repmatmatch(a,B);\n% \n% See also: repmat\n\n% Author: Jacob Donley\n% University of Wollongong\n% Email: jrd089@uowmail.edu.au\n% Copyright: Jacob Donley 2017\n% Date: 28 August 2017 \n% Version: 0.1 (28 August 2017)\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\naSz = size(a);\nBSz = size(B);\n\nif any(rem(BSz ./ aSz,1))\n    error(['The size of each dimension of ''a'' should match ''B'' ' ...\n       'or be evenly divisible by the corresponding dimension of ''B''.'])\nend\n\nA = repmat(a, BSz ./ aSz);\n\nend\n", "meta": {"author": "jtkim-kaist", "repo": "Speech-enhancement", "sha": "84f1a3c1273fb4952522b911dd62cbb4476a534d", "save_path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement", "path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement/Speech-enhancement-84f1a3c1273fb4952522b911dd62cbb4476a534d/SE/lib/sub_lib/SoundZone_Tools-master/SoundZone_Tools-master/repmatmatch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.5608999659040406}}
{"text": "function [slug] = lbm2slug(lbm)\n% convert mass from pounds-mass to slugs.\nslug = lbm/32.17405;", "meta": {"author": "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/lbm2slug.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5608606163262797}}
{"text": "function [out,Xt,str,ts] = rfnn_mimo_scatter(t,Xt,u,flag,itaVector,alphaVector, NumInVars,NumInTerms,NumOutVars,x0,T)\n\n% This program is an implementation of the on-line RFNN (MIMO) system.\n% The structure of the network is determined by the user.\n% The input space is partitiond using the scatter-type method.\n% All parameters of the network are estimated by Gradient Descent (GD)\n% through error backpropagation. \n\n    ninp = NumInVars;\n    nout = NumOutVars;\n   ninps = ninp+nout+1;  % number of inputs to sfunction [ x y LE ]\n   NumRules = NumInTerms;  % Scatter-Type Input Space Partitioning.\n       ns = 4*NumInVars*NumInTerms + NumOutVars*NumRules;\n     nds = 3*NumInVars*NumInTerms + NumOutVars*NumRules;\n     % Learning Rates\n     ita1 = itaVector(1); ita2 = itaVector(2);\n     ita3 = itaVector(3); ita4 = itaVector(4);\n     % Momentum Constants.\n     alpha1 = alphaVector(1); alpha2 = alphaVector(2); \n     alpha3 = alphaVector(3); alpha4 = alphaVector(4);\n%  ----------------------- % initial informations --------------\nif abs(flag)==0\n\n    out = [0,ns+nds,nout+ns+nds,ninps,0,1,1];    % states, outputs, inputs, ?, df, #ts\n    str = [];                                 % API block consistency\n     ts = T;                                  % sample time\n    Xt = x0;\n%  ----------------------- % state derivatives -----------------\nelseif abs(flag) == 2\n   \n          x = u(1:ninp);\n          e = u(ninp+1:ninp+nout);\n   learning = u(ninp+nout+1);\n\nif learning == 1 \n  \n   % Unroll the states:  \n   off=1;\n   off_end=NumInVars*NumInTerms;\n   mean2=reshape(Xt(off:off_end),NumInVars,NumInTerms);  \n   \n   off=off_end+1;\n   off_end=off + NumInVars*NumInTerms-1;\n   sigma2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off+NumInVars*NumInTerms-1;\n   Theta2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off + NumOutVars*NumRules-1;\n   W = reshape(Xt(off:off_end),NumOutVars,NumRules);\n      \n   off=off_end+1;\n   off_end=off+NumInVars*NumInTerms-1;\n   Out2 = reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   % Unroll the differential states:\n   off=off_end+1;\n   off_end=off + NumInVars*NumInTerms-1;\n   dmean2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off + NumInVars*NumInTerms-1;\n   dsigma2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off + NumInVars*NumInTerms-1;\n   dTheta2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off + NumOutVars*NumRules-1;\n   dW = reshape(Xt(off:off_end),NumOutVars,NumRules);\n      \n      \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                                                    FEEDFORWARD OPERATION                                                      %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% LAYER 2 - INPUT TERM NODES\n  Out2_pr = Out2;\n  In2 = x*ones(1,NumInTerms) + Out2_pr.*Theta2;\n  Out2 = exp(-((In2-mean2)./sigma2).^2);\n \n% LAYER 3 - RULE (PRODUCT) NODES\n precond = Out2.';\n Out3 = prod(precond,2);\n \n%%%%%%%%%%%% END OF NETWORK FUNCTIONALITY SECTION %%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\t\t\t \t\t\t\t\t                 PARAMETER LEARNING SECTION\t                       \t\t\t                %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% BACKWARD PASS. Error Backpropagation\n% LAYER 3\ndelta3 = e.'*W;\n\n% LAYER 2\nThetaE = zeros(NumInVars,NumInTerms);  \nfor i=1:NumInVars\n     for j=1:NumInTerms\n   \t\t  ThetaE(i,j) = (Out3(j)/Out2(i,j))*delta3(j);\n     end \n end\n              \n% LAYER 2 PARAMETER ADJUSTMENT BY GRADIENT DESCENT.  \ndeltamean2  =  2*ThetaE.*Out2.*(In2-mean2)./((sigma2).^2);\ndeltasigma2 =  2*ThetaE.*Out2.*((In2-mean2).^2)./(sigma2.^3);\ndeltaTheta2 = -2*ThetaE.*Out2.*(In2-mean2).*Out2_pr./sigma2.^2; \n\ndmean2 = ita2*deltamean2 + alpha2*dmean2;\n mean2  = mean2 + dmean2;\n\ndsigma2 = ita3*deltasigma2 + alpha3*dsigma2;\n  sigma2 = sigma2 + dsigma2;\n\ndTheta2 = ita4*deltaTheta2 + alpha4*dTheta2;\n Theta2  = Theta2 + dTheta2;\n\n% LAYER 4 PARAMETER ADJUSTMENT\n deltaW = e*Out3.';\n dW = ita1*deltaW + alpha1*dW;\n  W = W + dW;\n\n%%%%%%%%%%%   END OF PARAMETER LEARNING PROCESS %%%%%%%%%\n% State Vector Storage.\n% Xt = [mean2 sigma2 Theta2 W Out2 dmean2 dsigma2 dTheta2 dW];\n\nXt = [ reshape(mean2,NumInVars*NumInTerms,1);\n          reshape(sigma2,NumInVars*NumInTerms,1);\n          reshape(Theta2,NumInVars*NumInTerms,1);\n          reshape(W,NumOutVars*NumRules,1);\n          reshape(Out2,NumInVars*NumInTerms,1);\n          reshape(dmean2,NumInVars*NumInTerms,1);\n          reshape(dsigma2,NumInVars*NumInTerms,1);\n          reshape(dTheta2,NumInVars*NumInTerms,1);\n          reshape(dW,NumOutVars*NumRules,1);];\nend\n\nout=Xt;\n\n%  ----------------------- % outputs -------------------------\nelseif flag == 3\n   \n  % Unpack the network's parameters first...\n   off=1;\n   off_end=NumInVars*NumInTerms;\n   mean2=reshape(Xt(off:off_end),NumInVars,NumInTerms);  \n   \n   off=off_end+1;\n   off_end=off + NumInVars*NumInTerms-1;\n   sigma2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off+NumInVars*NumInTerms-1;\n   Theta2 =reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off + NumOutVars*NumRules - 1;\n   W = reshape(Xt(off:off_end),NumOutVars,NumRules);\n   \n   off=off_end+1;\n   off_end=off+NumInVars*NumInTerms-1;\n   Out2 = reshape(Xt(off:off_end),NumInVars,NumInTerms);\n         \n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  %                                                       FEEDFORWARD OPERATION                                                       %\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % LAYER 2 - INPUT TERM NODES\n   x = u(1:ninp);\n  \n Out2_pr = Out2;\n In2 = x*ones(1,NumInTerms) + Out2_pr.*Theta2;\n Out2 = exp(-((In2-mean2)./sigma2).^2);\n \n% LAYER 3 - RULE (PRODUCT) NODES\nprecond = Out2.';\n Out3 = prod(precond,2);\n \n % LAYER 4 \n  outact = W*Out3;\n\n  % Block Outputs Vector Formation.\n   out=[outact;Xt];            \n     \nelse\n   out=[];\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/43021-recurrent-fuzzy-neural-network-rfnn-library-for-simulink/S-functions/rfnn_mimo_scatter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5608606103795203}}
{"text": "function [V_hat, lam_hat] = cpf_predictor(V, lam, z, step, pv, pq)\n%CPF_PREDICTOR  Performs the predictor step for the continuation power flow\n%   [V_HAT, LAM_HAT] = CPF_PREDICTOR(V, LAM, Z, STEP, PV, PQ)\n%\n%   Computes a prediction (approximation) to the next solution of the\n%   continuation power flow using a normalized tangent predictor.\n%\n%   Inputs:\n%       V : complex bus voltage vector at current solution\n%       LAM : scalar lambda value at current solution\n%       Z : normalized tangent prediction vector from previous step\n%       STEP : continuation step length\n%       PV : vector of indices of PV buses\n%       PQ : vector of indices of PQ buses\n%\n%   Outputs:\n%       V_HAT : predicted complex bus voltage vector\n%       LAM_HAT : predicted lambda continuation parameter\n\n%   MATPOWER\n%   Copyright (c) 1996-2016, Power Systems Engineering Research Center (PSERC)\n%   by Shrirang Abhyankar, Argonne National Laboratory\n%   and Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n%% sizes\nnb = length(V);\n\nVa = angle(V);\nVm = abs(V);\nVa_hat = Va;\nVm_hat = Vm;\n\n%% prediction for next step\nVa_hat([pv; pq]) = Va([pv; pq]) + step * z([pv; pq]);\nVm_hat([pq])     = Vm([pq])     + step * z([nb+pq]);\nlam_hat = lam + step * z(2*nb+1);\nV_hat = Vm_hat .* exp(1j * Va_hat);\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/cpf_predictor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5608147768714575}}
{"text": "% this simple exampe shows the general principles of geodesic toolbox\n% Danil Kirsanov, 09/2007 \n\nglobal geodesic_library;                \ngeodesic_library = 'geodesic_debug';      %\"release\" is faster and \"debug\" does additional checks\nrand('state', 0);                         %comment this statement if you want to produce random mesh every time\n\nN = 300;                                  %number of points in a mesh\n[vertices,faces] = create_hedgehog_mesh(N, 0.1);   %create \"noisy sphere\" mesh; \"vertices\" contains 3D vertex coordinates; \"faces\" contains vertex id's for every triangle\n%[vertices,faces] = create_flat_triangular_mesh(0.1, 0); N = length(vertices);  %rectangular mesh for sanity check\n\nmesh = geodesic_new_mesh(vertices,faces);         %initilize new mesh\nalgorithm = geodesic_new_algorithm(mesh, 'exact');      %initialize new geodesic algorithm\n\nvertex_id = 1;                             %create a single source at vertex #1\nsource_points = {geodesic_create_surface_point('vertex',vertex_id,vertices(vertex_id,:))};\n\ngeodesic_propagate(algorithm, source_points);   %propagation stage of the algorithm (the most time-consuming)\n\nvertex_id = N;                              %create a single destination at vertex #N\ndestination = geodesic_create_surface_point('vertex',vertex_id,vertices(vertex_id,:));\npath = geodesic_trace_back(algorithm, destination);     %find a shortest path from source to destination\n\ndistances = zeros(N,1);              %find distances to all vertices of the mesh (actual pathes are not computed)\n\n[source_id, distances] = geodesic_distance_and_source(algorithm);     %find distances to all vertices of the mesh; in this example we have a single source, so source_id is always equal to 1\n\ngeodesic_delete;                            %delete all meshes and algorithms\n\n%-----------------plotting------------------------\nhold off;\ncolormap('default');\ntrisurf(faces,vertices(:,1),vertices(:,2),vertices(:,3),distances, 'FaceColor', 'interp', 'EdgeColor', 'k');       %plot the mesh\ndaspect([1 1 1]);\n\nhold on;\nplot3(source_points{1}.x, source_points{1}.y, source_points{1}.z, 'or', 'MarkerSize',3);    %plot sources\n\nplot3(destination.x, destination.y, destination.z, 'ok', 'MarkerSize',3);       %plot destination \n[x,y,z] = extract_coordinates_from_path(path);                                  %prepare path data for plotting\nh = plot3(x*1.001,y*1.001,z*1.001,'k-','LineWidth',2);    %plot path\nlegend(h,'geodesic curve');", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/18168-exact-geodesic-for-triangular-meshes/example1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5608147733206642}}
{"text": "% All Pass Filter Sensitivities, RSS & WCA\n% File: c:\\M_files\\short_updates\\allpassrss.m\n% Circuit function: G4.m\n% updated 11/16/06\n% \nclear;clc\nK=1e3;u=1e-6;\nR1=626.25;R2=22.55*K;R3=25.05*K;R4=225.45*K;\nC1=0.1*u;C2=C1;\nNom=[R1 R2 R3 R4 C1 C2]; % vector of nominal component values\nBF=450;LF=550;NP=101; % linear freq sweep\nF=linspace(BF,LF,NP);\n% Form symmetric tolerance array T\nTr=0.01;Tc=0.05;\n%\nT=[-Tr -Tr -Tr -Tr -Tc -Tc;Tr Tr Tr Tr Tc Tc];\nNc=size(T,2); % Nc = number of components\n% For assymetric tolerances if present\nMr=1+(T(2,:)+T(1,:))/2;\nTv=(T(2,:)-T(1,:))./(2*Mr); % Used only in RSS \nNav=Nom.*Mr; % Shift components to average value if\n% tolerances are assymetric.  Mr = all 1's if symmetric.\n%\n[An,Bn,Dn,En,I]=G4(Nom); % Nominal SS arrays\n%\ndpf=0.0001; % derivative perturbation factor\nrd=180/pi; % convert radians to degrees\n%\n% Q & R perturbation vectors are sequenced below:\n% Reset; Q = [1 1 1 1 1]; R = [1 1 1 1 1]\n% p = 1; Q = [1.0001 1 1 1 1];R = [0.9999 1 1 1 1];\n% p = 2; Q = [1 1.0001 1 1 1];R = [1 0.9999 1 1 1]; \n% and so forth up to p = Nc.\n%\nQ=1+dpf;R=1-dpf;\n%\nfor i=1:NP % Begin frequency sweep\n   Qx=ones(1,Nc);Rx=ones(1,Nc); % Reset perturbation vectors\n   s=2*pi*F(i)*j;\n   Vo(i)=rd*angle(Dn*((s*I-An)\\Bn)+En); % Nominal output\n   for p=1:Nc % Begin component loop\n      Qx(p)=Q;Rx(p)=R;\n      if p > 1;Qx(p-1)=1;Rx(p-1)=1;end; % Reset previous\n% Perturbate components forward with Q = 1+dpf   \n      [A,B,D,E]=G4(Nom.*Qx);\n      Vr=rd*angle(D*((s*I-A)\\B)+E);\n% Perturbate components backward with R = 1-dpf\n      [A,B,D,E]=G4(Nom.*Rx);\n      Vb=rd*angle(D*((s*I-A)\\B)+E);\n      %\n      Sen(i,p)=(Vr-Vb)/(2*Vo(i)*dpf); % Centered difference approximation\n      %\n      % For EVA\n      %\n      if Sen(i,p) > 0\n         Lo(p)=1+T(1,p);Hi(p)=1+T(2,p);\n      else\n         Lo(p)=1+T(2,p);Hi(p)=1+T(1,p);\n      end\n   end % end component loop\n   %\n   % Get EVA VL and EVA VH\n   %\n   [A,B,D,E]=G4(Nom.*Lo);\n   VL(i)=rd*angle(D*((s*I-A)\\B)+E);\n   [A,B,D,E]=G4(Nom.*Hi);\n   VH(i)=rd*angle(D*((s*I-A)\\B)+E);\n   %\n   % Get RSS using norm function\n   %\n   STn=norm(Sen(i,:).*Tv);\n   Vrss1(i)=Vo(i)*(1-STn);Vrss2(i)=Vo(i)*(1+STn);\nend % close frequency sweep loop i\n%\nsubplot(2,2,1)\nh=plot(F,Sen(:,5),'r',F,Sen(:,6),'b');\nset(h,'LineWidth',2);\ngrid on\naxis auto\nset(gca,'FontSize',8)\n%xlabel('Freq (Hz)');\nylabel('%/%')\ntitle('C Sensitivities')\nlegend('C1','C2',0);\n%\nsubplot(2,2,2)\nh=plot(F,Sen(:,1),'k',F,Sen(:,2),'r',F,Sen(:,3),'b',F,Sen(:,4),'g');\nset(h,'LineWidth',2);\ngrid on\naxis auto\nset(gca,'FontSize',8)\n%xlabel('Freq (Hz)');\nylabel('%/%')\ntitle('R Sensitivities')\nlegend('R1','R2','R3','R4',0);\n%\nsubplot(2,2,4)\nm=plot(F,VL,'b',F,VH,'r',F,Vo,'k--');\nset(m,'LineWidth',2)\ngrid on\naxis auto\nset(gca,'FontSize',8)\n%axis([BF LF 30 180])\n%YT=linspace(30,180,6);\n%set(gca,'ytick',YT);\nxlabel('Freq (Hz)');\nylabel('Degrees')\ntitle('EVA')\nlegend('EVLo','EVHi','Nom',0)\n%\nsubplot(2,2,3)\nm=plot(F,Vrss1,'b',F,Vrss2,'r',F,Vo,'k--');\nset(m,'LineWidth',2)\ngrid on\naxis auto\nset(gca,'FontSize',8)\n%axis([BF LF 30 180])\n%YT=linspace(30,180,6);\n%set(gca,'ytick',YT);\nxlabel('Freq (Hz)');\nylabel('Degrees')\ntitle('RSS')\nlegend('RSSLo','RSSHi','Nom',0)\n%\nfigure(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/2435-shortcut-state-space-circuit-analysis/Matlab_Files/allpassrss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5608147663736384}}
{"text": "classdef CEC2010_F18 < PROBLEM\n% <single> <real> <constrained>\n% CEC'2010 constrained optimization benchmark problem\n\n%------------------------------- Reference --------------------------------\n% R. Mallipeddi and P. N. Suganthan, Problem definitions and evaluation\n% criteria for the CEC 2010 competition on constrained real-parameter\n% optimization, Nanyang Technological University, Singapore, 2010.\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        O;  % Optimal decision vector\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2010.mat'),'Data');\n            obj.O = Data{18};\n            obj.M = 1;\n            if isempty(obj.D); obj.D = 10; end\n            obj.D = min(obj.D,length(obj.O));\n            obj.lower    = zeros(1,obj.D) - 50;\n            obj.upper    = zeros(1,obj.D) + 50;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopObj = sum((Z(:,1:end-1)-Z(:,2:end)).^2,2);\n        end\n        %% Calculate constraint violations\n        function PopCon = CalCon(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopCon(:,1) = mean((-Z.*sin(sqrt(abs(Z)))),2);\n            PopCon(:,3) = abs(mean((-Z.*sin(sqrt(abs(Z)))),2)) - 1e-4;\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/Single-objective optimization/CEC 2010/CEC2010_F18.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385543, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5608147589248028}}
{"text": "function y = tapas_condhalluc_obs2_sim(r, infStates, p)\n% Simulates responses according to the condhalluc_obs model\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.\n\n% Get parameters\nbe = p(1);\nnu = p(2);\n\n% Prediction trajectory\nmu1hat = infStates(:,1,1);\n\n% Get true-positive rate corresponding to stimuli\ntp = r.u(:,2);\n\n% Update belief using precision-weighted prediction error\n% with nu the generalized precision\nx = mu1hat + 1/(1 + nu)*(tp - mu1hat);\n\n% Apply the logistic sigmoid to the inferred beliefs\nprob = tapas_sgm(be.*(2.*x-1),1);\n\n% Initialize random number generator\nif isnan(r.c_sim.seed)\n    rng('shuffle');\nelse\n    rng(r.c_sim.seed);\nend\n\n% Simulate\ny = binornd(1, prob);\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_condhalluc_obs2_sim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.560814755875819}}
{"text": "function [c, ceq, cGrad, ceqGrad] = pathConstraint(x)\n% [c, ceq, cGrad, ceqGrad] = pathConstraint(x)\n%\n% This function implements a simple path constraint to keep the knee joint\n% of the robot from hyer-extending.\n%\n\nq1 = x(1,:);\nq2 = x(2,:);\nq4 = x(4,:);\nq5 = x(5,:);\n\nc = [...\n    q1-q2;    %Stance knee joint limit\n    q5-q4];   %Swing knee joint limit\n\nceq = [];\n\nif nargout == 4 %Analytic gradients\n    % Gradients with respect to:\n    % [t,q1,q2,q3,q4,q5,dq1,dq2,dq3,dq4,dq5,u1,u2,u3,u4,u5] = 1+5+5+5\n    nCst = 2;   %stance leg ; swing leg\n    nGrad = 16;  %time, angles, rates, torques\n    nTime = size(x,2);\n    cGrad = zeros(nCst,nGrad,nTime);\n    cGrad(1,3,:) = -1;  % cst stance wrt q2\n    cGrad(1,2,:) = 1; % cst stance wrt q1\n    cGrad(2,5,:) = -1;  % cst swing wrt q4\n    cGrad(2,6,:) = 1; % cst swing wrt q5\n    \n    ceqGrad = [];\nend\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/fiveLinkBiped/pathConstraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5608147550267605}}
{"text": "function params = get_default_truck_trailer_params()\nparams.velocity = -1;\nparams.truckWheelbase = 3.0;\nparams.trailerWheelbase = 11.0;\nparams.feedbackGain = local_get_default_k();\nparams.forwardGain = local_get_fwd_k();\n\n% for control\nparams.Q = [1 0 0\n     0 1 0\n     0 0 1];\nparams.R = 100;\nparams.noiseLevel = 100;\nparams.forwardTarget = [20, 2, 0.3];\n\n% for viz\nparams.truckWidth         =  3;\nparams.truckMargin        = 1;\nparams.trailerWidth       = 2.8;\nparams.trailerMarginFront = 1;\nparams.trailerMarginBack  = 3;\nparams.tireLen   = 1.2;\nparams.tireWidth = 0.3;\nend\n\n\n%%\nfunction K = local_get_default_k()\n% offLinePolicyIteration\nD1 = 3.0;     % trailer wheelbase\nD2 = 6.0;   % tractor wheelbase\nA = [  0    -1     0;\n       0     0     0;\n       0     0    1/D2];\nB = [0;\n    -1/D1;\n    1/D1];\nQ = [1 0 0\n     0 1 0\n     0 0 1];\nR = 1000;\n[~, ~, K] = care(A,B,Q,R)\nend\n\n%%\nfunction K = local_get_fwd_k()\n% offLinePolicyIteration\nD1 = 3.0;     % trailer wheelbase\nD2 = 6.0;   % tractor wheelbase\nA = [  0     1;\n       0     0];\nB = [0;\n     1/D1];\nQ = [1 0\n     0 1];\nR = 1000;\n[~, ~, K] = care(A,B,Q,R);\nK = [K 0];\nend\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/Extra_Examples/truck_trailer/get_default_truck_trailer_params.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5608147497778508}}
{"text": "function [l] = cl2l(cl)\n% Convert volume from centiliters to liters. \n% Chad Greene 2012\nl = cl*0.01;", "meta": {"author": "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/cl2l.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5607502194652093}}
{"text": "function [xPred, SPred]=sqrtDiscEKFPred(xPrev,SPrev,f,FJacob,SQ)\n%SQRTDISCEKFPRED Perform the discrete-time prediction step that comes with \n%                the square-root implementation of the first-order Extended\n%                Kalman Filter (EKF).\n%\n%INPUTS: xPrev The xDim X 1 state estimate at the previous time-step.\n%        SPrev The xDim X xDim lower-triangular square root of the  state\n%              covariance matrix at the previous time-step.\n%            f A function handle for the state transition function that\n%              takes the state as its parameter.\n%       FJacob A function handle for calculating the xDim X xDim state\n%              transition matrix. If an empty matrix is passed, then FJacob\n%              will be found using numerical differentiation  via the\n%              numDiff function with default parameters.\n%           SQ The xDimX xDim lower-triangular square root of the  process\n%              noise covariance matrix.\n%\n%OUTPUTS: xPred The xDim X 1 predicted state estimate.\n%         SPred The xDim X xDim lower-triangular square root of the\n%               predicted state covariance estimate.\n%\n%The first-order EKF is summarized in Figure 10.3.3-1 in Chapter 10.3.3 of\n%[1].\n%\n%The partial derivatives in the Jacobian matrix returned by the function\n%FJacob are ordered\n%[dF/dx(1), dF/dx(2),...,dF/dx(xDim)]\n%That is, column i consists of partial derivatives with respect to element\n%i of the x vector.\n%\n%The mathematics behind the specific square root implementation used here\n%are described in [2].\n%\n%REFERENCES:\n%[1] Y. Bar-Shalom, X. R. Li, and T. Kirubarajan, Estimation with\n%    Applications to Tracking and Navigation. New York: John Wiley and\n%    Sons, Inc, 2001.\n%[2] David F. Crouse , \"Basic tracking using nonlinear 3D monostatic and\n%    bistatic measurements,\" IEEE Aerospace and Electronic Systems \n%    Magazine, vol. 29, no. 8, Part II, pp. 4-53, Aug. 2014.\n%\n%March 2015, David Karnick, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nxDim=size(xPrev,1);\nif(isempty(FJacob))\n    FJacob=@(x)numDiff(x,f,xDim);\nend\n\nxPred=f(xPrev);\nF=FJacob(xPrev);\nSPred=tria([F*SPrev,SQ]);\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Estimation/State_Propagation/Discrete_Time/sqrtDiscEKFPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5607502194652092}}
{"text": "function f = initialize_variables(N, M, V, min_range, max_range)\n\n%% function f = initialize_variables(N, M, V, min_range, max_range) \n% This function initializes the chromosomes. Each chromosome has the\n% following at this stage\n%       * set of decision variables\n%       * objective function values\n% \n% where,\n% N - Population size\n% M - Number of objective functions\n% V - Number of decision variables\n% min_range - A vector of decimal values which indicate the minimum value\n% for each decision variable.\n% max_range - Vector of maximum possible values for decision variables.\n\n%  Copyright (c) 2009, Aravind Seshadri\n%  All rights reserved.\n%\n\nmin = min_range;\nmax = max_range;\n\n% K is the total number of array elements. For ease of computation decision\n% variables and objective functions are concatenated to form a single\n% array. For crossover and mutation only the decision variables are used\n% while for selection, only the objective variable are utilized.\n\nK = M + V;\n\n%% Initialize each chromosome\n% For each chromosome perform the following (N is the population size)\nf = zeros(N,K); % modified by zzb\nfor i = 1 : N\n    % Initialize the decision variables based on the minimum and maximum\n    % possible values. V is the number of decision variable. A random\n    % number is picked between the minimum and maximum possible values for\n    % the each decision variable.\n    for j = 1 : V\n        f(i,j) = min(j) + (max(j) - min(j))*rand(1);\n    end\n    % For ease of computation and handling data the chromosome also has the\n    % vlaue of the objective function concatenated at the end. The elements\n    % V + 1 to K has the objective function valued. \n    % The function evaluate_objective takes one chromosome at a time,\n    % infact only the decision variables are passed to the function along\n    % with information about the number of objective functions which are\n    % processed and returns the value for the objective functions. These\n    % values are now stored at the end of the chromosome itself.\n    f(i,V + 1: K) = evaluate_objective(f(i,1:V), M);\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/\u7f8e\u8d5bA\u9898\u5e38\u89c1\u4ee3\u7801/\u591a\u76ee\u6807\u5feb\u901f\u975e\u652f\u914d\u6392\u5e8f\u9057\u4f20\u7b97\u6cd5\u4f18\u5316\u4ee3\u7801/initialize_variables.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5607502045515611}}
{"text": "function [N,x0] = affine_null_space(A,b,varargin)\n  % Given a system Ax = b, determine a matrix N spanning the right null space\n  % of A and a feasible solution x0 so that:\n  %\n  %     A * (N * y + x0) = b  for any y\n  %\n  % Inputs:\n  %   A  m by n (sparse) matrix. \n  %   b  m by #b right-hand side\n  %   Options:\n  %     'Tol'  followed by tolerance for determine rank (what's considered\n  %       zero?)\n  %     'Method'  followed by either:\n  %        {'qr'}  use QR decomposition of A' (robust, best understood, slowest)\n  %        'luq'  use LUQ decomposition \n  %        'rq'  use QR decomposition of A (good when m << n)\n  %        'svd'  use SVD decompostion (only use for small/dense matrices)\n  %        'rrlu'  simplifed version of LUQ (**broken**)\n  % Outputs:\n  %   N  n by #N matrix spanning null space, where #N = m - rowrank(A)\n  %   x0 n by #b, so that columns are feasible solutions\n  % \n\n  tol = [];\n  method = 'qr';\n  % default values\n  % Map of parameter names to variable names\n  params_to_variables = containers.Map( ...\n    {'Method','Tol'},{'method','tol'});\n  v = 1;\n  while v <= numel(varargin)\n    param_name = varargin{v};\n    if isKey(params_to_variables,param_name)\n      assert(v+1<=numel(varargin));\n      v = v+1;\n      % Trick: use feval on anonymous function to use assignin to this workspace\n      feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n    else\n      error('Unsupported parameter: %s',varargin{v});\n    end\n    v=v+1;\n  end\n  if nargin<2 || isempty(b)\n    b = zeros(size(A,1),1);\n  end\n\n  if isempty(tol)\n    tol = max(max(size(A)) * norm(A,1) * eps,100*eps);\n  end\n\n  switch method\n  case 'luq'\n    %% Special sparse LUQ decomposition\n    %tol\n    %[L,U,Q] = luq(A,1,tol);\n    %% Rank\n    %nc = find(any(abs(U)>tol,2),1,'last');\n    %nc\n    %if isempty(nc)\n    %  nc = 0;\n    %  m = size(A,1)-nc;\n    %  if nargout>=2\n    %    x0 = ones(m,1);\n    %  end\n    %  N = speye(size(A,1),m);\n    %else\n    %  if nargout>=2\n    %    y0 = U(1:nc,1:nc)\\(speye(nc,size(L,1))*(L\\b));\n    %    x0 = Q\\[y0;zeros(size(Q,1)-nc,size(b,2))];\n    %  end\n    %  QQ = Q^-1;\n    %  N = QQ(:,nc+1:end);\n    %end\n    %%big = max(abs(N));\n    %%if big > 0\n    %%  N = N/big;\n    %%end\n\n    % FAR MORE ACCURATE THAN luq(A,...); see doc of spspaces (L is more accurate\n    % than Q)\n    [L,U,Q] = luq(A',0,tol);\n    % this looks gross but somehow doesn't destroy sparsity\n    LL = L^-1;\n    S = max(abs(U),[],2);\n    if ~isempty(S)\n      J = find(S<=tol);\n    else\n      J = (1:size(S,1))';\n    end    \n    N = LL(J,:)';\n    nc = find(any(abs(U)>tol,2),1,'last');\n    Unc = U(1:nc,1:nc);\n    Lnc = L(:,1:nc);\n    %x0 = A'*(((A')'*A')\\b);\n    %x0 = L*U*Q*((Q'*U'*L'*L*U*Q)\\b);\n    %x0 = L*U*(((U'*L'*L*U)\\(Q'\\b)));\n    %x0 = Lnc*Unc*(((Unc'*Lnc'*Lnc*Unc)\\(Q'\\b)));\n    %x0 = Lnc*(((Lnc'*Lnc)\\(Unc'\\(Q'\\b))));\n    x0 = LL'*(speye(size(L,2),size(Unc,1))*(Unc'\\(Q'\\b)));\n  case 'rrlu'\n    % \"Strong rank revealing LU factorizations\" [Miranian & Gu 2002]\n    % https://math.berkeley.edu/~luiza/RRLU.pdf\n    %\n    % Seems there is a typo. They write: \"Nr = [-A11\\A12;I_{m-k,n-k}]\" But so\n    % that A*Nr makes sense, I think it should be \"Nr = [-A11\\A12;I_{n-k,n-k}]\"\n    %\n    %\n    m = size(A,1);\n    n = size(A,2);\n    [L,U,P,Q] = lu(sparse(A),tol);\n\n    NZ = find((any(abs(U)>tol,2)));\n    % LUQ just checks the diagonal:\n    NZluq = find(abs(diag(U))>tol);\n    if ~isempty(setxor(NZ,NZluq))\n      size(NZ)\n      size(NZluq)\n      warning('Not handling non-zero bottom right corner (use luq)');\n    end\n\n    Z = find(~(any(abs(U)>tol,2)));\n    R = sparse((1:size(U,1))',[NZ;Z],1);\n\n    C = blkdiag(R',speye(size(U,2)-size(R,2)));\n    % L U               = P A Q\n    % L R' R U C C'     = P A Q\n    % L R' R U C        = P A Q C \n    % L R' [U11 U12; 0] = P A Q C \n    %\n    % let M = [-U11\\U12;I]\n    %\n    % [U11 U12] M = 0\n    %\n    % L R' [U11 U12] M = P A Q C M\n    % L R' 0           = P A Q C M\n    %\n    % Implies\n    %\n    % N = Q C M --> A N = 0\n    %\n    UU = R*U*C;\n    nc = sum((any(abs(UU)>tol,2)));\n    U11 = UU(1:nc,1:nc);\n    U12 = UU(1:nc,nc+1:end);\n    M = [-U11\\U12;speye(size(U12,2),size(U12,2))];\n    N = Q*C*M;\n\n    % We have:\n    %\n    % L R' [U11 U12; 0] = P A Q C \n    %\n    % A x = b\n    % Let x = Q C y\n    % P A Q C y = P b\n    % L R' [U11 U12; 0] y = P b\n    % Assume: (L R') is invertible:\n    % [U11 U12; 0] y = (L R')\\(P b)\n    % [U11 U12; 0] y = [b1;b2];\n    % Invertible iff b2 = 0\n    % [U11 U12; 0] y = [b1;0];\n    % y = [U11\\b1;y2] for any y2\n    % And might as well set y2 to 0\n    % y = [U11\\b1; 0]\n    % \n    LL = L*R';\n    bb = LL\\(P*b);\n    y = [U11\\(bb(1:nc,:));zeros(size(U,2)-nc,size(bb,2))];\n    x0 = Q*C*y;\n\n  case 'qr'\n    [Q,R,E] = qr(A');\n    % Rank of A\n    nc = find(any(abs(R)>tol,2),1,'last');\n    % Q = [Q\u2081,N]\n    Q1 = Q(:,1:nc);\n    % A possibly non-unique solution\n    if nargout>=2\n      x0 = Q1*(R(1:nc,1:nc)'\\(E(:,1:nc)'*(b)));\n    end\n    N = Q(:,nc+1:end);\n  case 'rq'\n    % http://mathoverflow.net/a/253997/23064\n    [Q,R,E] = qr(A);\n    nc = find(any(abs(R)>tol,2),1,'last');\n    R1 = R(1:nc,1:nc);\n    R2 = R(1:nc,nc+1:end);\n    n = size(A,2);\n    N = E*[-(R1\\R2);speye(n-nc,n-nc)];\n    %assert(nargout <= 1 && 'x0 not supported for rq');\n    b1 = Q(:,1:nc)'*b;\n    x0 = E*[R1\\b1;zeros(size(E,2)-size(R1,1),size(b1,2))];\n  case 'svd'\n    [U,S,V] = svd(full(A));\n    % Carefully extract diagonal of S\n    Sdiag = S(sub2ind(size(S),1:min(size(S)),1:min(size(S))));\n    Z = abs(Sdiag)<tol;\n    N = V(:,setdiff(1:end,find(~Z)));\n    Sdiag(Z) = 0;\n    Sdiag(~Z) = 1./Sdiag(~Z);\n    % Place back into S without changing size of S\n    S(sub2ind(size(S),1:min(size(S)),1:min(size(S)))) = Sdiag;\n    Apinv = V*S'*U';\n    x0 = Apinv * b;\n  end\n  % Zap anything below tolerance\n  %N(abs(N) < tol) = 0\n  [NI,NJ,NV] = find(N);\n  N = sparse(NI,NJ,(abs(NV)>tol).*NV,size(N,1),size(N,2));\n  \n  %assert(max(abs(A*(N*rand(size(N,2),size(b,2)) + x0) - b)) < 1e-10, ...\n  %  'Should span solutions to A x = b');\n  if nargout>1 && ~(all(all(abs(A*x0-b)<tol)))\n    % Should check that constraint right-hand sides are compatible:\n    %   [Q,R,E] = qr(A'); \n    %   rank_A = find(any(abs(R)>tol,2),1,'last');\n    %   [Q,R,E] = qr([A b]'); \n    %   rank_Ab = find(any(abs(R)>tol,2),1,'last');\n    %   assert(rank_Ab <= rank_A);\n    % \n    warning('MATLAB:singularMatrix', ...\n      'A*x0 ~= b, this may mean that  A*x = b is impossible to satisfy');\n  end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/matrix/affine_null_space.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5607501910610267}}
{"text": "% Clear and close everything\nclear all;\nclose all;\n\n% Add paths needed\naddpath('functions/matGeom/geom3d/')\naddpath('functions/lips/')\n\n\n% Load our data from file\npath = '../input/floorplan_spencer_small.txt';\nplanes2d = load_2dplanedata(path);\n\n% Convert to polygons with a height of 8ft\nheight = 8;\nplanes3d = planes2dtopolygons3d(planes2d, height);\n\n\n% Plot the polyons (uses geom3d function)\nfigure;\nfor ii=1:size(planes3d,2)\n\tdrawPolygon3d(planes3d{ii}(:,1),planes3d{ii}(:,2),planes3d{ii}(:,3),'b');\n    hold on;\nend\ndrawCoordinates3d([0,0,0],[0,0,0],10)\naxis equal\nxlabel('x-direction (ft)')\nylabel('y-direction (ft)')\nzlabel('z-direction (ft)')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/plot_3d_walls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5607198463144688}}
{"text": "function [c,s] = wavefast(x,n,varargin)\n%WAVEFAST Computes the FWT of a '3-D extended' 2-D array.\n%   [C, L] = WAVEFAST(X, N, LP, HP, EXTMODE) computes 'PAGES' 2D N-level\n%   FWTs of a 'ROWS x COLUMNS x PAGES' matrix X with respect to\n%   decomposition filters LP and HP and boundary extension mode EXTMODE.\n%\n%   [C, L] = WAVEFAST(X, N, WNAME, EXTMODE) performs the same operation\n%   but fetches filters LP and HP for wavelet WNAME using WAVEFILTER.\n%\n%   Scale parameter N must be less than or equal to log2 of the maximum\n%   image dimension.  Filters LP and HP must be even. If EXTMODE = 'SYM'\n%   (the default), X is symmetrically extended; if X = [c1 c2 c3 ... cn]\n%   (in 1D), then its symmetric extension would be [... c3 c2 c1 c1 c2\n%   c3 ... cn cn cn-1 cn-2 ...]. If EXTMODE = 'PER', X is periodically\n%   extended to [... cn-1 cn c1 c2 c3 ... cn c1 c2 ...].\n%\n%   OUTPUTS:\n%     Vector C is a coefficient decomposition vector:\n%\n%      C = [ a1(n)...ak(n) h1(n)...hk(n) v1(n)...vk(n)\n%            d1(n)...dk(n) h1(n-1)... d1(1)...dk(1) ]\n%\n%     where ai, hi, vi, and di for i = 0,1,...k are columnwise vectors\n%     containing approximation, horizontal, vertical, and diagonal\n%     coefficient matrices, respectively, and k is the number of pages\n%     in the 3-D extended array X. C has 3n + 1 sections where n is the\n%     number of wavelet decompositions.\n%\n%     Matrix S is an [(n+2) x 2] bookkeeping matrix if k = 1; else it is\n%     [(n+2) x 3]:\n%\n%      S = [ sa(n, :); sd(n, :); sd(n-1, :); ... ; sd(1, :); sx ]\n%\n%     where sa and sd are approximation and detail size entries.\n%\n%   See also WAVEBACK and WAVEFILTER.\n%\n%   Copyright 2002-2020 Gatesmark\n%\n%   This function, and other functions in the DIPUM Toolbox, are based \n%   on the theoretical and practical foundations established in the \n%   book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark \n%   Press, 2020.\n%\n%   Book website: http://www.imageprocessingplace.com\n%   License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt\n\n% Check the input arguments for reasonableness.\nextmode = 'SYM';\nif ischar(varargin{1})\n   [lp,hp] = wavefilter(varargin{1},'d');\n   if nargin > 3\n      extmode = varargin{2};\n   end\nelse\n   lp = varargin{1};   hp = varargin{2};\n   if nargin > 4\n      extmode = varargin{3};\n   end\nend\n\n% Get the filter length, 'lp', input array size, 'sx', and number of\n% pages, 'pages', in extended 2-D array x.\nfl = length(lp);       sx = size(x);        pages = size(x,3);\n\nif ((~ismatrix(x)) && (ndims(x) ~= 3)) || (min(sx) < 2) ...\n      || ~isreal(x) || ~isnumeric(x)\n   error('X must be a real, numeric 2-D or 3-D matrix.');\nend\n\nif (~ismatrix(lp)) || ~isreal(lp) || ~isnumeric(lp) ...\n      || (~ismatrix(hp)) || ~isreal(hp) || ~isnumeric(hp) ...\n      || (fl ~= length(hp)) || rem(fl,2) ~= 0\n   error(['LP and HP must be even and equal length real, ' ...\n      'numeric filter vectors.']);\nend\n\nif ~isreal(n) || ~isnumeric(n) || (n < 1) || (n > log2(max(sx)))\n   error(['N must be a real scalar between 1 and ' ...\n      'log2(max(size((X))).']);\nend\n\n% Init the starting output data structures and initial approximation.\nc = [];        s = sx(1:2);\napp = cell(pages, 1);\nfor i = 1:pages\n   app{i} = double(x(:,:,i));\nend\n\n% For each decomposition ...\nfor i = 1:n\n   % Extend the approximation.\n   [app,keep] = extend(app,fl,pages,extmode);\n   \n   % Convolve rows with HP and downsample. Then convolve columns\n   % with HP and LP to get the diagonal and vertical coefficients.\n   rows = convolve(app,hp,'row',fl,keep,pages,extmode);\n   coefs = convolve(rows,hp,'col',fl,keep,pages,extmode);\n   c = addcoefs(c,coefs,pages);\n   s = [size(coefs{1}); s];\n   coefs = convolve(rows,lp,'col',fl,keep,pages,extmode);\n   c = addcoefs(c,coefs,pages);\n   \n   % Convolve rows with LP and downsample. Then convolve columns\n   % with HP and LP to get the horizontal and next approximation\n   % coeffcients.\n   rows = convolve(app,lp,'row',fl,keep,pages,extmode);\n   coefs = convolve(rows,hp,'col',fl,keep,pages,extmode);\n   c = addcoefs(c,coefs,pages);\n   app = convolve(rows,lp,'col',fl,keep,pages,extmode);\nend\n\n% Append the final approximation structures.\nc = addcoefs(c,app,pages);\ns = [size(app{1}); s];\nif ~ismatrix(x)\n   s(:,3) = size(x,3);\nend\n\n%----------------------------------------------------------------------%\nfunction nc = addcoefs(c,x,pages)\n% Add 'pages' array coefficients to the wavelet decomposition vector.\n\nnc = c;\nfor i = pages:-1:1\n   nc = [x{i}(:)' nc];\nend\n\n%----------------------------------------------------------------------%\nfunction [y,keep] = extend(x,fl,pages,extmode)\n% Extend the 'pages' arrays of x in both dimensions and return\n% 'keep' to determine the number of coefficients to keep after\n% convolution and downsampling.\n\ny = cell(pages,1);\nfor i = 1:pages\n   if strcmpi(extmode,'SYM')\n      keep = floor((fl + size(x{i}) - 1) / 2);\n      y{i} = padarray(x{i},[(fl - 1) (fl - 1)],'symmetric','both');\n   elseif strcmpi(extmode,'PER')\n      keep = size(x{i});\n      y{i} = padarray(x{i},[fl/2 fl/2],'circular','both');\n   else\n      error('Invalid extension mode!');\n   end\nend\n\n%----------------------------------------------------------------------%\nfunction y = convolve(x,h,type,fl,keep,pages,extmode)\n% For the 'pages' 2-D arrays in x, convolve the rows or columns with\n% h, downsample, and extract the section defined by 'keep'.\n\ny = cell(pages,1);\nfor i = 1:pages\n   if strcmp(type,'row')\n      if strcmpi(extmode, 'SYM')\n         y{i} = conv2(x{i},h);\n         y{i} = y{i}(:,1:2:end);\n         y{i} = y{i}(:,fl / 2 + 1:fl / 2 + keep(2));\n      else\n         y{i} = conv2(x{i},h,'valid');\n         y{i} = y{i}(:, 2:2:2 * ceil(keep(2) / 2));\n      end\n   else\n      if strcmpi(extmode,'SYM')\n         y{i} = conv2(x{i},h');\n         y{i} = y{i}(1:2:end,:);\n         y{i} = y{i}(fl / 2 + 1:fl / 2 + keep(1), :);\n      else\n         y{i} = conv2(x{i},h','valid');\n         y{i} = y{i}(2:2:2 * ceil(keep(1) / 2),:);\n      end\n   end\nend\n", "meta": {"author": "dipum", "repo": "dipum-toolbox", "sha": "9ce653c4c0c4b7c56e46194c24bf152db4ab6832", "save_path": "github-repos/MATLAB/dipum-dipum-toolbox", "path": "github-repos/MATLAB/dipum-dipum-toolbox/dipum-toolbox-9ce653c4c0c4b7c56e46194c24bf152db4ab6832/dipum/wavefast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146849, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5606864353321064}}
{"text": "classdef nninterp < nntest\n  methods (Test)\n\n    function basicShrink(test)\n      zoom = 1 ;\n      shrink = 3 ;\n      batchSize = 10 ;\n      x = test.randn([5 5 3 batchSize]) ;\n      y = vl_nninterp(x, shrink, zoom) ;\n\n      % check derivatives with numerical approximation\n      dzdy = test.randn(size(y)) ;\n      dzdx = vl_nninterp(x, shrink, zoom, dzdy) ;\n      test.der(@(x) vl_nninterp(x, shrink, zoom), x, dzdy, dzdx, 1e-3*test.range) ;\n    end\n\n    function basicShrinkZoom(test)\n      zoom = 4 ;\n      shrink = 3 ;\n      batchSize = 10 ;\n      padBeg = 2 ;\n      padEnd = 1 ;\n      pad = {'padBeg', padBeg, 'padEnd', padEnd} ;\n      x = test.randn([5 5 3 batchSize]) ;\n      y = vl_nninterp(x, shrink, zoom, pad{:}) ;\n\n      % check derivatives with numerical approximation\n      dzdy = test.randn(size(y)) ;\n      dzdx = vl_nninterp(x, shrink, zoom, dzdy, pad{:}) ;\n      test.der(@(x) vl_nninterp(x, shrink, zoom, pad{:}), ...\n                               x, dzdy, dzdx, 1e-3*test.range) ;\n    end\n\n  end\nend\n", "meta": {"author": "ShuaiBai623", "repo": "MFT", "sha": "8762f8cdf494ce0b1a1c3d431660c5c8fd91744a", "save_path": "github-repos/MATLAB/ShuaiBai623-MFT", "path": "github-repos/MATLAB/ShuaiBai623-MFT/MFT-8762f8cdf494ce0b1a1c3d431660c5c8fd91744a/external_libs/matconvnet/contrib/mcnExtraLayers/matlab/xtest/suite/nninterp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5606864353321063}}
{"text": "% function Figure2A()\n\n%% Stragegy implementation with Historical closing odds\n% Comparison of the returns of our strategy vs a random bet strategy\n% at clossing odds\n\n% comment the next 3 lines if using Matlab\n% warning(\"off\")\n% pkg load statistics\n% pkg load nan\n\n% clear all\ndbstop if error\naddpath('./aux_files/')\naddpath('./aux_plot/')\naddpath('./strategies/')\n\n%% Parameters\ndat_dir = '../data/';\nfile_name = 'closing_odds.csv';\nbet = 50; % money on each bet\nmarg = 0.05; % margin odds above the mean.\nnSamps = 2000; % number of returns to calculate (with replacement) for the random strategy\nrand('seed',1) % use always the same seed to get same results\nrunStrategies = 1; % 1: run both strategies, 0: load results from disk\n\n%% Run strategies\n\nfid = fopen([dat_dir file_name], 'r');\n% 1. match_table_id: unique identifier of the game\n% 2. league of the game\n% 3. match date\n% 4. home team\n% 5. 90-minute score of home team\n% 6. away team\n% 7. 90-minute score of away team\n% 8. average closing odds home win\n% 9. average closing odds draw\n% 10. average closing odds away win\n% 11. maximum offered closing odds home win\n% 12. maximum offered closing odds draw\n% 13. maximum offered closing odds away win\n% 14. name of bookmaker offering maximum closing odds for home win\n% 15. name of bookmaker offering maximum closing odds for draw\n% 16. name of bookmaker offering maximum closing odds for away win\n% 17. number of available closing odds for home win\n% 18. number of available closing odds for draw\n% 19. number of available closing odds for away win\nC = textscan(fid, '%s %s %s %s %f %s %f %f %f %f %f %f %f %s %s %s %f %f %f', 'delimiter', ',');\nfclose(fid);\n\ndat = [C{5} C{7} C{8} C{9} C{10} C{11} C{12} C{13} C{17} C{18} C{19}];\n\nif runStrategies\n    \n    %% Implement Our Strategy\n    s1 = beatTheBookie(dat, bet, marg);\n    s1.name = 'BeatTheBookies';\n    fprintf('Finished running \"beatTheBookie\"\\n')\n    \n    % Proportion of Home, Draw or away for games selected by our strategy.\n    s1.pHome = mean(s1.ids == 1);\n    s1.pDraw = mean(s1.ids == 2);\n    s1.pAway = mean(s1.ids == 3);\n    \n    %% Implement Random bet strategy\n    nGamesStrategy = length(s1.money) -1; % number of games that were selected for the historical betting\n    s2 = randomBetStrategy(dat, nSamps, nGamesStrategy, bet , s1);\n    s2.name = 'RandomStrategy';\n    fprintf('Finished running \"random Strategy\"\\n')\n    \n    save([dat_dir 'returns_HistoricalClosingOdds'], 's1', 's2', 'bet')\n    \nelse\n    %% Or load pre-calculated results from disk\n    load([dat_dir 'returns_HistoricalClosingOdds.mat']);\n    \nend\n\n%% Mean closing odds and Expected accuracy\n\n% Compute descriptive stats\nmS1 = mean(s1.mean_odds);\nmS2 = mean(s2.mean_odds(:));\nstdS1 = std(s1.mean_odds);\nstdS2 = std(s2.mean_odds(:));\n\n% These are are the intercepts obtained in the regression analysis of\n% Figure 1 (see Figure1.m)\noffsets = [-0.034, -0.057, -0.037];\n\n% Calculate Expected Accuracy of our strategy\ns1_prob = [ ( 1 ./ s1.mean_odds(s1.ids==1 )) + offsets(1) , (1 ./ s1.mean_odds(s1.ids==2)) + offsets(2), ...\n    (1 ./ s1.mean_odds(s1.ids==3)) + offsets(3)];\ns1_accuracy = mean(s1.accuracy);\ns1_expectedAccuracy = mean(s1_prob);\n\n% Calculate Expected Accuracy of Random bet Strategy\nfor m = 1 : size(s2.mean_odds, 1)\n    \n    oddsHome = s2.mean_odds(m, s2.ids(m,:)==1);\n    oddsDraw = s2.mean_odds(m, s2.ids(m,:)==2);\n    oddsAway = s2.mean_odds(m, s2.ids(m,:)==3);\n    s2_prob = [ ( 1 ./ oddsHome) + offsets(1), (1 ./ oddsDraw) + offsets(2), ...\n            (1 ./ oddsAway) + offsets(3)];\n    s2_expectedAccuracies(m) = mean(s2_prob); \n    \nend\ns2_accuracy = mean(mean(s2.accuracy,2));\ns2_expectedAccuracy = mean(s2_expectedAccuracies);\n\nrandomStrategyMean = nanmean(s2.money(:,end));\nrandomStrategyStd = nanstd(s2.money(:,end));\n\ndelta_sigma = (s1.money(end) - randomStrategyMean) / randomStrategyStd; % distance to the mean in standard deviations\n\np = normcdf(s1.money(end),randomStrategyMean,randomStrategyStd);\n% percentage of z values expected to lie above z\u03c3.  CI = (\u2212z\u03c3, z\u03c3)\nprop = (1 - p);\nfraction = 1 / prop; % expressed as fraction\n\nclc\nfprintf('Mean odds of our strategy: %2.3f (STD=%2.3f) \\nMean Odds Random Bet Strategy: %2.3f (STD= %2.3f) \\n', ...\n    mS1, stdS1, mS2, stdS2);\n\nfprintf('Beat The Bookie statistics:\\n');\nfprintf('# of bets: %2.0f \\n Return: %2.4f\\n Profit: %2.0f\\n Expected Accuracy: %2.1f\\n Accuracy: %2.2f \\n',length(s1.money)-1, ...\n    s1.money(end)/((length(s1.money)-1) * bet),s1.money(end), s1_expectedAccuracy * 100, s1_accuracy * 100);\n\nfprintf('Random bet strategy statistics:\\n');\nfprintf('# of bets: %2.0f \\n Return: %2.4f\\n Profit: %2.0f\\n STD: %2.4f\\n Expected Accuracy: %2.1f\\n Accuracy: %2.2f \\n',length(s2.money), ...\n    randomStrategyMean/((length(s2.money)-1)*bet), randomStrategyMean, randomStrategyStd, s2_expectedAccuracy * 100, s2_accuracy * 100);\n\n\n%% Figure 2A: Compare \"Beat the bookie\" with the Random Bet Strategy\nf1 = figure(1); clf;\nset(gcf, 'Position', [0 0 1200 800], 'InvertHardCopy', 'on', 'PaperPositionMode', 'auto')\nhold on\n\n% Random strategy\np3 = plot(mean(s2.money), 'r', 'LineWidth', 3);\np1 = plot(s2.money', '-r', 'LineWidth', 3);\nfor m = 1 : length(p1)\n    p1(m).Color(4) = 0.01;\nend\n\n% Beat the bookie\np2= plot(s1.money, 'b', 'LineWidth', 3);\np2.Color(4) = 0.8;\n\nxlabel('Game Number')\nylabel('Returns [U$D]')\nfontSize = 16;\nset(gca, 'FontSize', fontSize)\nlegend([p2, p3], 'Our Strategy', 'Random Bet Strategy', 'Location', 'SouthWest')\nlegend boxoff\n\n% Change color of line back to black without affecting the legend\np3 = plot(mean(s2.money), 'k', 'LineWidth', 3);\np3.Color(4) = 0.7;\n\nset(gca, 'YTick', -200000:50000:150000, 'YTickLabel', {-200000 -150000 -100000 -50000 0 50000 100000 150000})\nset(gca, 'XTick', 0:10000:60000, 'XTickLabel', {0 10000 20000 30000 40000 50000 60000})\n\nxlim([0 80000])\nylim([-180000 125000])\nset(gca, 'FontSize', fontSize)\n\n% Draw curly brace\ndrawbrace([length(s1.money)-1 s1.money(end)], [length(s1.money)-1 randomStrategyMean], 20, 'Color', 'k', 'LineWidth', 2);\n\ntit = sprintf('%2.2f', delta_sigma);\nht = text(62000, 15000, [tit ' \\sigma']);\nset(ht,'Rotation',270)\nset(ht,'FontSize',20)\n\n% Draw histogram inset\naxes('position', [0.71 0.20 0.22 0.3]);\n\nfinal_returns = s2.money(:,end);\n[counts,bins] = hist(final_returns, 30); %# get counts and bin locations\nh = barh(bins,counts);\nh.FaceColor = [1.0 0 0];\nset(gca,'visible','off');\n\nprint(f1, '-dpng', '../figures/Figure2A.png')\nprint(f1, '-depsc', '../figures/Figure2A.eps')\n\n", "meta": {"author": "Lisandro79", "repo": "BeatTheBookie", "sha": "7add209d0d097af0f8b714e388cf05849db7f969", "save_path": "github-repos/MATLAB/Lisandro79-BeatTheBookie", "path": "github-repos/MATLAB/Lisandro79-BeatTheBookie/BeatTheBookie-7add209d0d097af0f8b714e388cf05849db7f969/src/Figure2A.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5606864288364284}}
{"text": "% OP_GRADSYMV_N_U: assemble the matrix A = [a(i,j)], a(i,j) = (epsilon (gradsym v n)_j, u_i), with n the normal vector.\n%\n%   mat = op_gradsymv_n_u (spu, spv, msh, epsilon);\n%   [rows, cols, values] = op_gradsymv_n_u (spu, spv, msh, epsilon);\n%\n% INPUT:\n%\n%   spu:   structure representing the space of trial functions (see sp_scalar/sp_evaluate_col)\n%   spv:   structure representing the space of test functions (see sp_scalar/sp_evaluate_col)\n%   msh:   structure containing the domain partition and the quadrature rule for the boundary, \n%           since it must contain the normal vector (see msh_cartesian/msh_eval_boundary_side)\n%   epsilon: coefficient\n%\n% OUTPUT:\n%\n%   mat:    assembled matrix\n%   rows:   row indices of the nonzero entries\n%   cols:   column indices of the nonzero entries\n%   values: values of the nonzero entries\n% \n% Copyright (C) 2014 Adriano Cortes\n% Copyright (C) 2014, 2017, 2020 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 <http://www.gnu.org/licenses/>.\n\nfunction varargout = op_gradsymv_n_u (spu, spv, msh, coeff)\n\n  gradv = reshape (spv.shape_function_gradients, spv.ncomp, [], ...\n\t\t   msh.nqn, spv.nsh_max, msh.nel);\n\n  ndim = size (gradv, 2);\n\n  shpu = reshape (spu.shape_functions, spu.ncomp, msh.nqn, spu.nsh_max, msh.nel);\n\n  rows = zeros (msh.nel * spu.nsh_max * spv.nsh_max, 1);\n  cols = zeros (msh.nel * spu.nsh_max * spv.nsh_max, 1);\n  values = zeros (msh.nel * spu.nsh_max * spv.nsh_max, 1);\n\n  jacdet_weights = msh.jacdet .* msh.quad_weights .* coeff;\n  \n  ncounter = 0;\n  for iel = 1:msh.nel\n    if (all (msh.jacdet(:,iel)))\n      gradv_iel = gradv(:,:,:,:,iel);\n      normal_iel = reshape (msh.normal(:,:,iel), [1, ndim, msh.nqn]);\n      %Symmetrize gradv\n      gradv_iel = 0.5*(gradv_iel + permute (gradv_iel, [2 1 3 4]));\n\n      gradv_n = reshape (sum (bsxfun (@times, gradv_iel, normal_iel), 2), spv.ncomp, msh.nqn, spv.nsh_max, 1);\n      shpu_iel = reshape (shpu(:, :, :, iel), spu.ncomp, msh.nqn, 1, spu.nsh_max);\n\n      jacdet_iel = reshape (jacdet_weights(:,iel), [1,msh.nqn,1,1]);\n\n      gradv_n_times_jw = bsxfun (@times, jacdet_iel, gradv_n);\n      tmp1 = sum (bsxfun (@times, gradv_n_times_jw, shpu_iel), 1);\n      elementary_values = reshape (sum (tmp1, 2), spv.nsh_max, spu.nsh_max);\n      \n      [rows_loc, cols_loc] = ndgrid (spv.connectivity(:,iel), spu.connectivity(:,iel));\n      indices = rows_loc & cols_loc;\n      rows(ncounter+(1:spu.nsh(iel)*spv.nsh(iel))) = rows_loc(indices);\n      cols(ncounter+(1:spu.nsh(iel)*spv.nsh(iel))) = cols_loc(indices);\n      values(ncounter+(1:spu.nsh(iel)*spv.nsh(iel))) = elementary_values(indices);\n      ncounter = ncounter + spu.nsh(iel)*spv.nsh(iel);\n      \n    else\n      warning ('geopdes:jacdet_zero_at_quad_node', 'op_gradv_n_u: singular map in element number %d', iel)\n    end\n  end\n  \n\n  if (nargout == 1 || nargout == 0)\n    varargout{1} = sparse (rows, cols, values, spv.ndof, spu.ndof);\n  elseif (nargout == 3)\n    varargout{1} = rows;\n    varargout{2} = cols;\n    varargout{3} = values;\n  else\n    error ('op_gradv_n_u: wrong number of output arguments')\n  end\n  \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/operators/op_gradsymv_n_u.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5606864186755028}}
{"text": "function [NC,NE] = snap_points_to_close_edges(C,E,epsilon)\n  % SNAP_POINTS_TO_CLOSE_EDGES snap points to edges closer than a given epsilon\n  % breaking that edge into two edges and updating given the edge list.\n  %\n  % [NC,NE] = snap_points_to_close_edges(C,E)\n  % [NC,NE] = snap_points_to_close_edges(C,E,epsilon)\n  % \n  % Inputs:\n  %   C  #C by dim list of point positions\n  %   E  #E by 2 list of edges\n  %   epsilon  minium distance allowed after collapses are complete, default is to\n  %     use fraction of maximum edge length\n  % Outputs:\n  %   NC  #NC by dim list of new point positions\n  %   NE  #NE by 2 list of new edges\n  %\n  % Example:\n  %   %% Break edges\n  %   % point position list\n  %   C = [1,0;-1,0;0,1;eps,eps;0,-1;1,1;-1,-1];\n  %   % edge list\n  %   E = [1 2; 3 4; 4 5;6 7];\n  %   % plot original\n  %   subplot(1,2,1);\n  %   plot([C(E(:,1),1) C(E(:,2),1)]',[C(E(:,1),2) C(E(:,2),2)]', ... \n  %     '-','LineWidth',1);\n  %   % break edges at close points\n  %   [NC,NE] = snap_points_to_close_edges(C,E,0.2);\n  %   % plot result\n  %   subplot(1,2,2);\n  %   plot([NC(NE(:,1),1) NC(NE(:,2),1)]',[NC(NE(:,1),2) NC(NE(:,2),2)]', ...\n  %     '-','LineWidth',1);\n\n  if ~exist('epsilon','var') || isempty(epsilon)\n    if size(E,2) == 2\n      EE = E;\n    else\n      EE = edges(F);\n    end\n    % maximum edge length\n    maxD = max(sqrt(sum((C(EE(:,1),:) - C(EE(:,2),:)).^2,2)));\n    epsilon = maxD/100;\n  end\n\n  % avoid sqrts\n  sqr_eps = epsilon.^2;\n\n  % make room for outputs\n  NC = C;\n  NE = E;\n\n  % set previous count to phony value to enter while loop\n  prev_count = size(NE,1)+1;\n\n  % Continue edge break iterations until we're no longer breaking anything\n  while prev_count ~= size(NE,1)\n    prev_count = size(NE,1);\n    % compute projection of each point to each line segment\n    [T,sqrD] = project_to_lines(NC,NC(NE(:,1),:),NC(NE(:,2),:));\n    % each vertex seen by each edge\n    NCNE = repmat(NC,[1 1 size(NE,1)]);\n    % edge start positions\n    S = NC(NE(:,1),:);\n    % edge destination positions\n    D = NC(NE(:,2),:);\n    % distance of each point to each edge start\n    sqrDS = ...\n      squeeze(sum((NCNE - permute(repmat(S,[1 1 size(NC,1)]),[3 2 1])).^2,2));\n    % distance of each point to each edge dest\n    sqrDD = ...\n      squeeze(sum((NCNE - permute(repmat(D,[1 1 size(NC,1)]),[3 2 1])).^2,2));\n    % replace distances to edges when point is closest to start or dest endpoints\n    % respectively\n    sqrD(T<0) = sqrDS(T<0);\n    sqrD(T>1) = sqrDD(T>1);\n    % inf-out self-distances\n    sqrD( ...\n      sub2ind(size(sqrD),[NE(:,1);NE(:,2)],[1:size(NE,1) 1:size(NE,1)]')) = inf;\n    % for each edge find the closest point\n    [minD,break_q] = min(sqrD);\n    % mask telling whether closest point for each edge is close enough\n    close = minD<sqr_eps;\n    % don't let edges consider breaking at far points\n    break_q(~close) = -1;\n    % each edge claims a closest point, find edges which claim their closest\n    % point \"first\"\n    [~,first] = unique(break_q,'first');\n    % default is to not break an edge\n    break_e = false(1,size(NE,1));\n    % only break first edge to claim closest point\n    break_e(first) = true;\n    % only break edges at close points\n    break_e = break_e & close;\n    % new edges are: old edges, first parts of broken edges, second parts of\n    % broken edges\n    NE = [ ...\n      NE(~break_e,:) ; ...\n      NE(break_e,1) break_q(break_e)'; ...\n      break_q(break_e)' NE(break_e,2)];\n  end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/snap_points_to_close_edges.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5606864172602875}}
{"text": "function [ x, y, z, w ] = ld5294 ( )\n\n%*****************************************************************************80;\n%\n%% LD5294 computes the 5294 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(5294,1);\n  y = zeros(5294,1);\n  z = zeros(5294,1);\n  w = zeros(5294,1);\n  a = 0.0;\n  b = 0.0;\n  v = 0.9080510764308163E-04;\n  [ n, x, y, z, w ] = gen_oh ( 1, n, a, b, v, x, y, z, w );\n  v = 0.2084824361987793E-03;\n  [ n, x, y, z, w ] = gen_oh ( 3, n, a, b, v, x, y, z, w );\n  a = 0.2303261686261450E-01;\n  v = 0.5011105657239616E-04;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.3757208620162394E-01;\n  v = 0.5942520409683854E-04;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.5821912033821852E-01;\n  v = 0.9564394826109721E-04;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.8403127529194872E-01;\n  v = 0.1185530657126338E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.1122927798060578;\n  v = 0.1364510114230331E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.1420125319192987;\n  v = 0.1505828825605415E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.1726396437341978;\n  v = 0.1619298749867023E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.2038170058115696;\n  v = 0.1712450504267789E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.2352849892876508;\n  v = 0.1789891098164999E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.2668363354312461;\n  v = 0.1854474955629795E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.2982941279900452;\n  v = 0.1908148636673661E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.3295002922087076;\n  v = 0.1952377405281833E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.3603094918363593;\n  v = 0.1988349254282232E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.3905857895173920;\n  v = 0.2017079807160050E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.4202005758160837;\n  v = 0.2039473082709094E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.4490310061597227;\n  v = 0.2056360279288953E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.4769586160311491;\n  v = 0.2068525823066865E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.5038679887049750;\n  v = 0.2076724877534488E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.5296454286519961;\n  v = 0.2081694278237885E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.5541776207164850;\n  v = 0.2084157631219326E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.5990467321921213;\n  v = 0.2084381531128593E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6191467096294587;\n  v = 0.2083476277129307E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6375251212901849;\n  v = 0.2082686194459732E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6540514381131168;\n  v = 0.2082475686112415E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6685899064391510;\n  v = 0.2083139860289915E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6810013009681648;\n  v = 0.2084745561831237E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6911469578730340;\n  v = 0.2087091313375890E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.6988956915141736;\n  v = 0.2089718413297697E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.7041335794868720;\n  v = 0.2092003303479793E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.7067754398018567;\n  v = 0.2093336148263241E-03;\n  [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n  a = 0.3840368707853623E-01;\n  v = 0.7591708117365267E-04;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.9835485954117399E-01;\n  v = 0.1083383968169186E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.1665774947612998;\n  v = 0.1403019395292510E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.2405702335362910;\n  v = 0.1615970179286436E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.3165270770189046;\n  v = 0.1771144187504911E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.3927386145645443;\n  v = 0.1887760022988168E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.4678825918374656;\n  v = 0.1973474670768214E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.5408022024266935;\n  v = 0.2033787661234659E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.6104967445752438;\n  v = 0.2072343626517331E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.6760910702685738;\n  v = 0.2091177834226918E-03;\n  [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n  a = 0.6655644120217392E-01;\n  b = 0.1936508874588424E-01;\n  v = 0.9316684484675566E-04;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.9446246161270182E-01;\n  b = 0.4252442002115869E-01;\n  v = 0.1116193688682976E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.1242651925452509;\n  b = 0.6806529315354374E-01;\n  v = 0.1298623551559414E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.1553438064846751;\n  b = 0.9560957491205369E-01;\n  v = 0.1450236832456426E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.1871137110542670;\n  b = 0.1245931657452888;\n  v = 0.1572719958149914E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2192612628836257;\n  b = 0.1545385828778978;\n  v = 0.1673234785867195E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2515682807206955;\n  b = 0.1851004249723368;\n  v = 0.1756860118725188E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2838535866287290;\n  b = 0.2160182608272384;\n  v = 0.1826776290439367E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3159578817528521;\n  b = 0.2470799012277111;\n  v = 0.1885116347992865E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3477370882791392;\n  b = 0.2781014208986402;\n  v = 0.1933457860170574E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3790576960890540;\n  b = 0.3089172523515731;\n  v = 0.1973060671902064E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4097938317810200;\n  b = 0.3393750055472244;\n  v = 0.2004987099616311E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4398256572859637;\n  b = 0.3693322470987730;\n  v = 0.2030170909281499E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4690384114718480;\n  b = 0.3986541005609877;\n  v = 0.2049461460119080E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4973216048301053;\n  b = 0.4272112491408562;\n  v = 0.2063653565200186E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5245681526132446;\n  b = 0.4548781735309936;\n  v = 0.2073507927381027E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5506733911803888;\n  b = 0.4815315355023251;\n  v = 0.2079764593256122E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5755339829522475;\n  b = 0.5070486445801855;\n  v = 0.2083150534968778E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.1305472386056362;\n  b = 0.2284970375722366E-01;\n  v = 0.1262715121590664E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.1637327908216477;\n  b = 0.4812254338288384E-01;\n  v = 0.1414386128545972E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.1972734634149637;\n  b = 0.7531734457511935E-01;\n  v = 0.1538740401313898E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2308694653110130;\n  b = 0.1039043639882017;\n  v = 0.1642434942331432E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2643899218338160;\n  b = 0.1334526587117626;\n  v = 0.1729790609237496E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2977171599622171;\n  b = 0.1636414868936382;\n  v = 0.1803505190260828E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3307293903032310;\n  b = 0.1942195406166568;\n  v = 0.1865475350079657E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3633069198219073;\n  b = 0.2249752879943753;\n  v = 0.1917182669679069E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3953346955922727;\n  b = 0.2557218821820032;\n  v = 0.1959851709034382E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4267018394184914;\n  b = 0.2862897925213193;\n  v = 0.1994529548117882E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4573009622571704;\n  b = 0.3165224536636518;\n  v = 0.2022138911146548E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4870279559856109;\n  b = 0.3462730221636496;\n  v = 0.2043518024208592E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5157819581450322;\n  b = 0.3754016870282835;\n  v = 0.2059450313018110E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5434651666465393;\n  b = 0.4037733784993613;\n  v = 0.2070685715318472E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5699823887764627;\n  b = 0.4312557784139123;\n  v = 0.2077955310694373E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5952403350947741;\n  b = 0.4577175367122110;\n  v = 0.2081980387824712E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2025152599210369;\n  b = 0.2520253617719557E-01;\n  v = 0.1521318610377956E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2381066653274425;\n  b = 0.5223254506119000E-01;\n  v = 0.1622772720185755E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2732823383651612;\n  b = 0.8060669688588620E-01;\n  v = 0.1710498139420709E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3080137692611118;\n  b = 0.1099335754081255;\n  v = 0.1785911149448736E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3422405614587601;\n  b = 0.1399120955959857;\n  v = 0.1850125313687736E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3758808773890420;\n  b = 0.1702977801651705;\n  v = 0.1904229703933298E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4088458383438932;\n  b = 0.2008799256601680;\n  v = 0.1949259956121987E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4410450550841152;\n  b = 0.2314703052180836;\n  v = 0.1986161545363960E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4723879420561312;\n  b = 0.2618972111375892;\n  v = 0.2015790585641370E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5027843561874343;\n  b = 0.2920013195600270;\n  v = 0.2038934198707418E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5321453674452458;\n  b = 0.3216322555190551;\n  v = 0.2056334060538251E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5603839113834030;\n  b = 0.3506456615934198;\n  v = 0.2068705959462289E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5874150706875146;\n  b = 0.3789007181306267;\n  v = 0.2076753906106002E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6131559381660038;\n  b = 0.4062580170572782;\n  v = 0.2081179391734803E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.2778497016394506;\n  b = 0.2696271276876226E-01;\n  v = 0.1700345216228943E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3143733562261912;\n  b = 0.5523469316960465E-01;\n  v = 0.1774906779990410E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3501485810261827;\n  b = 0.8445193201626464E-01;\n  v = 0.1839659377002642E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3851430322303653;\n  b = 0.1143263119336083;\n  v = 0.1894987462975169E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4193013979470415;\n  b = 0.1446177898344475;\n  v = 0.1941548809452595E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4525585960458567;\n  b = 0.1751165438438091;\n  v = 0.1980078427252384E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4848447779622947;\n  b = 0.2056338306745660;\n  v = 0.2011296284744488E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5160871208276894;\n  b = 0.2359965487229226;\n  v = 0.2035888456966776E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5462112185696926;\n  b = 0.2660430223139146;\n  v = 0.2054516325352142E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5751425068101757;\n  b = 0.2956193664498032;\n  v = 0.2067831033092635E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6028073872853596;\n  b = 0.3245763905312779;\n  v = 0.2076485320284876E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6291338275278409;\n  b = 0.3527670026206972;\n  v = 0.2081141439525255E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3541797528439391;\n  b = 0.2823853479435550E-01;\n  v = 0.1834383015469222E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.3908234972074657;\n  b = 0.5741296374713106E-01;\n  v = 0.1889540591777677E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4264408450107590;\n  b = 0.8724646633650199E-01;\n  v = 0.1936677023597375E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4609949666553286;\n  b = 0.1175034422915616;\n  v = 0.1976176495066504E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4944389496536006;\n  b = 0.1479755652628428;\n  v = 0.2008536004560983E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5267194884346086;\n  b = 0.1784740659484352;\n  v = 0.2034280351712291E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5577787810220990;\n  b = 0.2088245700431244;\n  v = 0.2053944466027758E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5875563763536670;\n  b = 0.2388628136570763;\n  v = 0.2068077642882360E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6159910016391269;\n  b = 0.2684308928769185;\n  v = 0.2077250949661599E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6430219602956268;\n  b = 0.2973740761960252;\n  v = 0.2082062440705320E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4300647036213646;\n  b = 0.2916399920493977E-01;\n  v = 0.1934374486546626E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.4661486308935531;\n  b = 0.5898803024755659E-01;\n  v = 0.1974107010484300E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5009658555287261;\n  b = 0.8924162698525409E-01;\n  v = 0.2007129290388658E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5344824270447704;\n  b = 0.1197185199637321;\n  v = 0.2033736947471293E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5666575997416371;\n  b = 0.1502300756161382;\n  v = 0.2054287125902493E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5974457471404752;\n  b = 0.1806004191913564;\n  v = 0.2069184936818894E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6267984444116886;\n  b = 0.2106621764786252;\n  v = 0.2078883689808782E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6546664713575417;\n  b = 0.2402526932671914;\n  v = 0.2083886366116359E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5042711004437253;\n  b = 0.2982529203607657E-01;\n  v = 0.2006593275470817E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5392127456774380;\n  b = 0.6008728062339922E-01;\n  v = 0.2033728426135397E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5726819437668618;\n  b = 0.9058227674571398E-01;\n  v = 0.2055008781377608E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6046469254207278;\n  b = 0.1211219235803400;\n  v = 0.2070651783518502E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6350716157434952;\n  b = 0.1515286404791580;\n  v = 0.2080953335094320E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6639177679185454;\n  b = 0.1816314681255552;\n  v = 0.2086284998988521E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.5757276040972253;\n  b = 0.3026991752575440E-01;\n  v = 0.2055549387644668E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6090265823139755;\n  b = 0.6078402297870770E-01;\n  v = 0.2071871850267654E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6406735344387661;\n  b = 0.9135459984176636E-01;\n  v = 0.2082856600431965E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6706397927793709;\n  b = 0.1218024155966590;\n  v = 0.2088705858819358E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6435019674426665;\n  b = 0.3052608357660639E-01;\n  v = 0.2083995867536322E-03;\n  [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n  a = 0.6747218676375681;\n  b = 0.6112185773983089E-01;\n  v = 0.2090509712889637E-03;\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/ld5294.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5606087724537004}}
{"text": "function [imgs, interpolated] = scaleup_Zeyde(conf, imgs)\n\n% Super-Resolution Iteration\nfor j = 1:conf.level\n    fprintf('Scale-Up Zeyde et al. #%d', j);\n    midres = resize(imgs, conf.upsample_factor, conf.interpolate_kernel);\n    interpolated = resize(imgs, conf.scale, conf.interpolate_kernel);\n    \n    for i = 1:numel(midres)\n        features = collect(conf, {midres{i}}, conf.upsample_factor, conf.filters);\n        features = double(features);\n        % Encode features using OMP algorithm      \n\n        coeffs = omp(double(conf.dict_lores), conf.V_pca' * features, [], 3);                        \n\n        % Reconstruct using patches' dictionary\n        patches = conf.dict_hires * full(coeffs); \n        \n        % Add low frequencies to each reconstructed patch\n        patches = patches + collect(conf, {interpolated{i}}, conf.scale, {});\n\n        % Combine all patches into one image\n        img_size = size(imgs{i}) * conf.scale;\n        grid = sampling_grid(img_size, ...\n            conf.window, conf.overlap, conf.border, conf.scale);\n        result = overlap_add(patches, img_size, grid);\n        imgs{i} = result; % for the next iteration\n        fprintf('.');\n    end\nend\nfprintf('\\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/Aplus/methods/scaleup_Zeyde.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787538, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.5605431713778969}}
{"text": "function [feat,idxs_bbox_pair,cb1,cb2] = get_spatial_features_diff_img_dx_dy(boxes,idxs_bbox_pair,rot_offset,scores,class_id,bVis,lab)\n\nif (nargin < 3)\n    rot_offset = 0;\nend\n\nif (nargin < 6)\n    bVis = false;\nend\n\nif (nargin < 7)\n    lab = ones(size(boxes,1),1);\nend\n\ncb1 = [mean(boxes(idxs_bbox_pair(:,1),[1 3]),2) mean(boxes(idxs_bbox_pair(:,1),[2 4]),2)];\ncb2 = [mean(boxes(idxs_bbox_pair(:,2),[1 3]),2) mean(boxes(idxs_bbox_pair(:,2),[2 4]),2)];\n\ndeltaX = abs(cb1(:,1)-cb2(:,1));\ndeltaY = abs(cb1(:,2)-cb2(:,2));\nangle = atan2(deltaY,deltaX);\nangle = angle - rot_offset;\nangle = wrapMinusPiPifast(angle);\n\n% feat = cat(2,dist,angle,scores(idxs_bbox_pair(:,1),:),scores(idxs_bbox_pair(:,2),:));\nfeat = cat(2,deltaX,deltaY,angle,scores(idxs_bbox_pair(:,1),:),scores(idxs_bbox_pair(:,2),:));\n\nif (bVis)\n    idxs = 1:min(size(cb1,1),100);\n%     figure(100);clf; \n        \n    plot(cb1(idxs,1),cb1(idxs,2),'b+','MarkerSize',10);\n    plot(cb2(idxs,1),cb2(idxs,2),'g+','MarkerSize',10);\n    \n    for i = 1:length(idxs)\n        if (lab(idxs(i)) == 1)\n            plot([cb1(idxs(i),1); cb2(idxs(i),1)],[cb1(idxs(i),2); cb2(idxs(i),2)],'r-','lineWidth',1);\n        else\n            plot([cb1(idxs(i),1); cb2(idxs(i),1)],[cb1(idxs(i),2); cb2(idxs(i),2)],'b-','lineWidth',1);\n        end\n    end\n    \n    legendName = {['pidx ' num2str(class_id(1)) '-' num2str(class_id(2))]};\n    legend(legendName);\nend", "meta": {"author": "eldar", "repo": "deepcut", "sha": "096e2d174ddf2fbdc61458d9e7e6c6e897eac16c", "save_path": "github-repos/MATLAB/eldar-deepcut", "path": "github-repos/MATLAB/eldar-deepcut/deepcut-096e2d174ddf2fbdc61458d9e7e6c6e897eac16c/lib/pose/get_spatial_features_diff_img_dx_dy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5605011384933136}}
{"text": "function a = downshift_inverse ( n )\n\n%*****************************************************************************80\n%\n%% DOWNSHIFT_INVERSE returns the inverse of the DOWNSHIFT matrix.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    19 October 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 A(N,N), the inverse.\n%\n  a = upshift ( 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/downshift_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.5605011297457365}}
{"text": "function distmap = test_breadth_first_search(A,u)\n\ndistmap = ipdouble(zeros(size(A,1),1));\ndistmap(u) = 0;\n    \n    function on_tree_edge(ei,u,v)\n        distmap(v) = distmap(u)+1;\n    end\n\nbreadth_first_search(A,u,struct('tree_edge',@on_tree_edge));\n\ndistmap = double(distmap);\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/matlab_bgl/test/test_breadth_first_search.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5605011217740266}}
{"text": "function im = drawlineonimage(im,x,y,color)\n\nif ~exist('color'),\n  color = lines(1);\nend\n\nif max(im(:)) > 1,\n  color = color*255;\nend\n\nnpts = length(x);\nif ndims(im) < 3,\n  im = repmat(im,[1,1,3]);\nend\n\n[nr,nc,three] = size(im);\nim = mat2cell(im,nr,nc,ones(1,3));\n\nfor i = 1:npts-1,\n  \n  dx = x(i+1) - x(i);\n  dy = y(i+1) - y(i);\n  m = dy / dx;\n  dx = abs(dx); dy = abs(dy);\n  if dx > dy,\n    xcurr = linspace(x(i),x(i+1),dx);\n    ycurr = y(i) + m*(xcurr-x(i));\n  else,\n    ycurr = linspace(y(i),y(i+1),dy);\n    xcurr = x(i) + (ycurr - y(i))/m;\n  end\n  for rx = 1:2, \n    if rx == 1,\n      roundx = floor(xcurr);\n    else,\n      roundx = ceil(xcurr);\n    end\n    dx = xcurr - roundx;\n    for ry = 1:2,\n      if ry == 1,\n        roundy = floor(ycurr);\n      else,\n        roundy = ceil(ycurr);\n      end\n      dy = ycurr - roundy;\n      w = max(0,sqrt(dx.^2 + dy.^2) - (sqrt(2) - 1));\n      for c = 1:3,\n        im{c}(sub2ind([nr,nc],roundy,roundx)) = im{c}(sub2ind([nr,nc],roundy,roundx)).*w + ...\n            color(c)*(1-w);\n      end\n    end\n  end\nend\n\nim = cell2mat(im);\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/drawlineonimage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5605011169134136}}
{"text": "function value = p32_exact ( dim_num )\n\n%*****************************************************************************80\n%\n%% P32_EXACT returns the exact integral for problem 32.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 June 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer DIM_NUM, the spatial dimension.\n%\n%    Output, real VALUE, the exact value of the integral.\n%\n  c = [];\n  c = p32_r8vec ( 'G', 'C', dim_num, c );\n\n  z = [];\n  z = p32_r8vec ( 'G', 'Z', dim_num, z );\n\n  [ a, b ] = p32_lim ( dim_num );\n\n  value = 1.0;\n\n  for i = 1 : dim_num\n\n    if ( z(i) <= a(i) )\n\n      value = value * 0.0;\n\n    elseif ( z(i) <= b(i) )\n\n      if ( c(i) == 0.0 )\n        value = value * ( z(i) - a(i) );\n      else\n        value = value * ( exp ( c(i) * z(i) ) - exp ( c(i) * a(i) ) ) / c(i);\n      end\n\n    else\n\n      if ( c(i) == 0.0 )\n        value = value * ( b(i) - a(i) );\n      else\n        value = value * ( exp ( c(i) * z(i) ) - exp ( c(i) * a(i) ) ) / c(i);\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/quadrature_test/p32_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7185944046238982, "lm_q1q2_score": 0.5604985411190341}}
{"text": "function fem2d_pack_test20 ( )\n\n%*****************************************************************************80\n%\n%% TEST20 tests SPHERE_GRID_Q9.\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_order = 9;\n  nelemx = 3;\n  nelemy = 4;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST20\\n' );\n  fprintf ( 1, '  SPHERE_GRID_Q9_ELEMENT sets up a grid of\\n' );\n  fprintf ( 1, '    Q9 quadrilaterals on a sphere.\\n' );\n  fprintf ( 1, '  SPHERE_GRID_Q9_ELEMENT_NUM returns the number\\n' );\n  fprintf ( 1, '    of elements in the grid\\n' );\n  fprintf ( 1, '  SPHERE_GRID_Q9_NODE_NUM returns the number\\n' );\n  fprintf ( 1, '    of nodes in the grid.\\n' );\n  fprintf ( 1, '  SPHERE_GRID_Q9_NODE_XYZ returns the coordinates\\n' );\n  fprintf ( 1, '    of nodes in the grid.\\n' );\n\n  element_num = sphere_grid_q9_element_num ( nelemx, nelemy );\n  node_num = sphere_grid_q9_node_num ( nelemx, nelemy );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Expected number of nodes =    %d\\n', node_num );\n  fprintf ( 1, '  Expected number of elements = %d\\n', element_num );\n\n  element_node = sphere_grid_q9_element ( nelemx, nelemy );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The elements and their nodes:\\n' );\n  fprintf ( 1, '\\n' );\n\n  for element = 1 : element_num\n    fprintf ( 1, '%4d  ', element );\n    for order = 1 : element_order\n      fprintf ( 1, '%4d', element_node(order,element) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n\n  node_xyz = sphere_grid_q9_node_xyz ( nelemx, nelemy );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The node coordinates:\\n' );\n  fprintf ( 1, '\\n' );\n\n  for node = 1 : node_num\n    fprintf ( 1, '  %4d  %12f  %12f  %12f\\n', node, node_xyz(1:3,node) );\n  end\n%\n%  Write the elements and nodes to files.\n%\n  r8mat_write ( 'sphere_q9_nodes.txt', 3, node_num, node_xyz );\n\n  i4mat_write ( 'sphere_q9_elements.txt', element_order, element_num, ...\n    element_node );\n\n  return\nend\n", "meta": {"author": "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_test20.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.5604985317177469}}
{"text": "function [ x, y, z ] = image_fun ( )\n\n%*****************************************************************************80\n%\n%% IMAGE_FUN processes an image using SPMD.\n%\n%  Discussion:\n%\n%    Only 3 SPMD workers should be allocated, one each for the\n%    R, G, and B components of the image.\n%\n%    The image \"balloons.tif\" is read in by the client, and distributed.\n%    This RGB image is stored as a (:,:,3) array, and by default, is\n%    distributed by the last dimension.  That means the first three workers\n%    get the R, G and B arrays and if there are more workers they get nothing.\n%\n%    Each worker applies the MEDFILT2 operation to its data.\n%\n%    The client then assembles the filtered R, G, and B data back into\n%    a (:,:,3) array and returns that as the output argument.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    28 March 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Output, uint8 X(:,:,3), the RGB data for the original image.\n%\n%    Output, uint8 Y(:,:,3), the RGB data for the noisy image.\n%\n%    Output, uint8 Z(:,:,3), the RGB data for the filtered image.\n%\n\n%\n%  Read an image X.\n%  This happens to be a color image, and is stored as 480x640x3 array.\n%\n  x = imread ( 'balloons.tif' );\n%\n%  Create an image Y by adding \"salt and pepper\" noise to X.\n%\n  y = imnoise ( x, 'salt & pepper', 0.30 );\n%\n%  Make YD, a distributed version of Y, by copying a separate\n%  portion of Y to each worker.\n%\n  yd = distributed ( y );\n%\n%  Each worker creates YL, a name for its portion of the array.\n%  It then applies the median filter to YL, using a 3x3 block of\n%  data around each pixel.\n%\n  spmd\n    yl = getLocalPart ( yd );\n    yl = medfilt2 ( yl, [ 3 3 ] );\n  end\n%\n%  The client retrieves the data from each worker.\n%  Assuming three workers were used, and the data was divided by\n%  the last dimension (R,G,B), then the three pieces are\n%  tacked together as follows:\n%\n  z        = yl{1};\n  z(:,:,2) = yl{2};\n  z(:,:,3) = yl{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_denoise_spmd/image_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5604985196670366}}
{"text": "function image = autoCropImage(image)\n% input an image\n% output an image with white space removed\n% assuming the top left pixel is the background color that you don't want\n\nmask = mean(image,3);\nmask = mask == mask(1,1);\nisGood1 = find(any(~mask,1));\nisGood2 = find(any(~mask,2));\nimage = image(min(isGood2):max(isGood2),min(isGood1):max(isGood1), :);", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/autoCropImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5604924165227773}}
{"text": "function varargout = crossentropy(varargin)\n% CROSSENTROPY\n%\n% y = CROSSENTROPY(x,y)\n%\n% Computes/declares cross entropy -sum(x.*log(y))\n%\n% See also ENTROPY, KULLBACKLEIBLER\n\nswitch class(varargin{1})\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 crossentropy')\n            end\n        end\n        \n        varargout{1} = yalmip('define','crossentropy_internal',[varargin{1};varargin{2}]);\n            \n    otherwise\n        error('SDPVAR/CROSSENTROPY called with CHAR argument?');\nend\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/YALMIP/@sdpvar/crossentropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5604924146249525}}
{"text": "clear all; close all; clc; rng('default');\n\n% Ambient space dimensions\nD = 50;\n% subspace dimension\nK = 8;\n% Angle between subspaces A-B and B-C.\nthetas = [4:2:40]; % in degree\nnt  = numel(thetas);\n% Number of points per subspace\nng_values = [4:2:60];\nnng = numel(ng_values);\nSNRs = [15, 25 35];\nnsnrs = numel(SNRs);\nTrials = 400;\n\naverage_fmeasures = zeros(nt, nsnrs, nng);\naverage_precisions = zeros(nt, nsnrs, nng);\naverage_recalls = zeros(nt, nsnrs, nng);\naverage_clustering_ratios = zeros(nt, nsnrs, nng);\n\nfor t=1:nt\n    theta = thetas(t);\n    for sn=1:nsnrs\n        SNR = SNRs(sn);\n        for i=1:nng\n            Ng = ng_values(i);\n            fmeasures = zeros(1, Trials);\n            precisions = zeros(1, Trials);\n            recalls = zeros(1, Trials);\n            clustering_ratios = zeros(1, Trials);\n            for s=1:Trials\n                if mod(s, 1) == 0\n                    fprintf('Theta: %d, SNR: %d dB,  Signals per subspace: %d, Trial: %d\\n', theta, SNR, Ng, s);\n                end\n                result = SimulateSSCOMP_3Spaces(D, K, Ng, theta, SNR);\n                cmpr = result.comparison;\n                fmeasures(s) = cmpr.fMeasure;\n                precisions(s) = cmpr.precision;\n                recalls(s) = cmpr.recall;\n                clustering_ratios(s) = cmpr.clusteringRatio;\n            end\n            average_fmeasures(t, sn, i) = mean(fmeasures);\n            average_precisions(t, sn, i) = mean(precisions);\n            average_recalls(t, sn, i) = mean(recalls);\n            average_clustering_ratios(t, sn, i) = mean(clustering_ratios);\n        end\n    end\nend\nsave(sprintf('bin/phase_transition_theta_signals_K=%d.mat',  K));\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/clustering/sparse_subspace_clustering/ssc_omp/bench_phase_transition_theta_signals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5604924049935175}}
{"text": "function y = cf_RN_NIG( u,r,T,alpha,beta,delta)\n%\n%  \nasq = alpha^2;\nbsq = beta^2;\ntemp = sqrt(asq-bsq);\ny = -delta*(sqrt(asq - (beta +1i*u).^2) - temp);  %Psi_s\nRNmu = r + delta*(sqrt(asq - (beta+1)^2)-temp);\ny = exp(T*(1i*u*RNmu + y));\n\nend\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/PROJ/LEVY/RN_CHF/cf_RN_NIG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5604924040446051}}
{"text": "function axesLabelsAlign3D\n% Note: This function is taken from internet.\n%Author: M Arthington\n%Date: 02/05/2010\n%Set the x and y axis labels of the current axes to be aligned to\n%the orientation of the axes.\n%This is intended to be used when the rotate3d command has been used.\n[az,el] = view;\nRaz = [cosd(az) sind(az) 0;-sind(az) cosd(az) 0;0 0 1];\nRel = [1 0 0;0 cosd(el) -sind(el);0 sind(el) cosd(el)];\n%Calculate current orientation of x and y axes in view coordinates\nxax = Rel*Raz*[1;0;0];yax = Rel*Raz*[0;1;0];\n%Project x and y into current viewing plane\nn1=cross(xax,[0;1;0]);x = cross([0;1;0],n1);\nn1=cross(yax,[0;1;0]);y = cross([0;1;0],n1);\n%If the view will show this label, orientate it to be aligned with the \n%axis direction. Otherwise set its rotation to 0 (default).\nif any(x)\n\tset(get(gca,'xlabel'),'rotation',atand(x(3)/x(1)));\nelse\n\tset(get(gca,'xlabel'),'rotation',0);\nend\nif any(y)\n\tset(get(gca,'ylabel'),'rotation',atand(y(3)/y(1)));\nelse\n\tset(get(gca,'ylabel'),'rotation',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/34985-monte-carlo-simulation-of-three-dimensional-grain-growth-code-version-no-1-basic/Monte Carlo Simulation Q-state Potts model 3D square-lattice - microstructure/axesLabelsAlign3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5604923838328217}}
{"text": "function [muX, SXX] = marginalize_gaussian(mu, Sigma, X, Y, ns)\n% MARGINALIZE_GAUSSIAN Compute Pr(X) from Pr(X,Y) where X and Y are jointly Gaussian.\n% [muX, SXX] = marginalize_gaussian(mu, Sigma, X, Y, ns)\n\n[muX, muY, SXX, SXY, SYX, SYY] = partition_matrix_vec(mu, Sigma, X, Y, ns);\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/dmlt/external/murphy/KPMstats/marginalize_gaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5604906247058092}}
{"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%==============================================================================\n%\n% Tutorial for FAIR: derivative check (use data from E3_splineInterpolation2D)\n%\n%==============================================================================\n\n\n% setup test data\ndataT = flipud([1,2,3,4;1,2,3,4;4,4,4,4])'; \nm     = size(dataT); \nomega = [0,m(1),0,m(2)]; \nB     = @(i) spdiags(ones(m(i),1)*[1,4,1],[-1:1],m(i),m(i));\nT     = B(1)\\dataT/B(2);\nxf    = reshape(getCellCenteredGrid(omega,10*m),[],2);\n\nfctn = @(x) splineInter(T,omega,x);\nfigure(1); clf;\n[fig,ph,th] = checkDerivative(fctn,xf(:),'fig',1);\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/E3_checkDerivative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5604906224545227}}
{"text": "function [voxel] = spm_vb_get_Ab(Y,slice)\n% Get A and b quantities - average prediction errors from AR model\n% FORMAT [voxel] = spm_vb_get_Ab(Y,slice)\n% \n% Y      - [T x N] time series\n% slice  - data structure (see spm_vb_glmar)\n% \n% voxel(n).A  \n% voxel(n).b\n%\n% The above quantities are estimated using pre-computed\n% cross-covariance matrices\n%__________________________________________________________________________\n% Copyright (C) 2005-2014 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny and Nelson Trujillo-Barreto\n% $Id: spm_vb_get_Ab.m 6079 2014-06-30 18:25:37Z spm $\n\nk = slice.k;\nN = slice.N;\n    \nfor n=1:N\n    % Equation 63 of paper VB1 but implemented \n    % efficiently using cross-covariance method described in paper VB3\n    if isfield(slice.I,'A2_tilde')\n        A2_tilde  = slice.I.A2_tilde(:,:,n);\n    else\n        A2_tilde  = reshape(slice.I.S*slice.a2{n}(:),k,k);\n    end\n    if isfield(slice.I,'A3a_tilde')\n        A3a_tilde = slice.I.A3a_tilde(:,:,n);\n    else\n        A3a_tilde = -reshape(slice.I.R1*slice.ap_mean(:,n),k,k);\n    end\n    voxel(n).A    = slice.I.xtx+A2_tilde+A3a_tilde+A3a_tilde';\n    \n    % Equation 64 of paper VB1 but implemented \n    % efficiently using cross-covariance method described in paper VB3\n    b2_tilde   = -slice.I.rxy(:,:,n)'*slice.ap_mean(:,n);\n    b3_tilde   = -slice.I.Gxy(:,:,n)'*slice.ap_mean(:,n);\n    b4_tilde   = slice.I.D(:,:,n)*slice.a2{n}(:);\n    voxel(n).b = slice.I.gxy(:,n)+b2_tilde+b3_tilde+b4_tilde;\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_vb_get_Ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5604906143200853}}
{"text": "function [dLdp,iCpY,L] = mci_linsqr_deriv (P,M,U,Y)\n% Gradient of likelihood for linear regression\n% FORMAT [dLdp,iCpY,L] = mci_linsqr_deriv (P,M,U,Y)\n%\n% P         parameters\n% M         model\n% U         inputs\n% Y         data\n%\n% dLdp      gradient of log joint\n% iCpY      curvature (Fisher Information)\n% L         log joint\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: mci_linsqr_deriv.m 6548 2015-09-11 12:39:47Z will $\n\nG = mci_linsqr_gen (P,M,U);\nif isstruct(Y)\n    e = Y.y-G;\nelse\n    e = Y-G;\nend\nX = U.X;\n\nN=size(X,1);\ndydp=2*(ones(N,1)*P').*X;\n\n%dydp = spm_diff(M.IS,P,M,U,1);\n\ndLdp=dydp'*M.iCe*e;\ndLdp=dLdp';\n\niCpY=dydp'*M.iCe*dydp;\n\nif nargout > 2\n    L=mci_linsqr_like (P,M,U,Y);\nend", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/models/linsqr/mci_linsqr_deriv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5604906070563558}}
{"text": "\n\nclear all; close all;\nbw=imread('cameraman.tif');\nse=strel('ball', 5, 5);\nbw2=imdilate(bw, se);\nfigure;\nsubplot(121);  imshow(bw);\nsubplot(122);  imshow(bw2);\n\n", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/\u300aMATLAB\u56fe\u50cf\u5904\u7406\u300b\u6e90\u6587\u4ef6/\u672c\u4e66\u6e90\u6587\u4ef6/chap12/chap12_5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5604883481789056}}
{"text": "function test_issue1198\n\n% WALLTIME 00:10:00\n% MEM 2gb\n% DEPENDENCY ft_sourceanalysis ft_sourcedescriptives ft_sourceplot\n\n%%\n% http://www.fieldtriptoolbox.org/example/testing_bem_created_leadfields/\n\n% Create a spherical volume conductor of radius 100, conductivity 1 and center [0,0,0]\nvol   = [];\nvol.r = 100;\nvol.c = 1;\nvol.o = [0 0 0];\nvol.unit = 'mm';\n\n% Create a set of electrodes on the upper half of the sphere\n[X, Y, Z] = sphere(10);\npos = unique([X(:) Y(:) Z(:)], 'rows');\npos = pos(pos(:,3)>=0,:);\n\nelec = [];\nelec.elecpos = vol.r * pos;\nelec.label = {};\nnelec = size(pos,1);\nfor ii = 1:nelec\n  elec.label{ii} = sprintf('vertex%03d', ii);\nend\n\n% Define positions of dipoles (along z axis)\nzp = linspace(0,100,50)';\npos = [zeros(size(zp)) zeros(size(zp)) zp];\n\n% Define the corresponding spatial grid\ncfg = [];\ncfg.inwardshift = 5;\ncfg.sourcemodel.pos = pos;\ncfg.headmodel = vol;\ncfg.elec = elec;\nsourcemodel = ft_prepare_sourcemodel(cfg);\n\n% construct a dense triangulated mesh\n[X, Y, Z] = sphere(100);\npos = unique([X(:) Y(:) Z(:)], 'rows');\nmesh.pos = pos*100;\nmesh.tri = convhulln(mesh.pos);\n\nvertic = [50 80 100 200 2000];\nfor ll=1:length(vertic)\n  cfg = [];\n  cfg.method = 'dipoli';\n  cfg.conductivity  = 1;\n  cfg.numvertices = vertic(ll);\n  cfg.isolatedsource = false;\n  volbem{ll} = ft_prepare_headmodel(cfg, mesh);\nend\n\n% calculate BEM leadfield\nfor ll=1:length(vertic)\n  cfg = [];\n  cfg.sourcemodel = sourcemodel;\n  cfg.headmodel = volbem{ll};\n  cfg.elec = elec;\n  leadfieldBEM{ll} = ft_prepare_leadfield(cfg);\nend\n\n% calculate theoretical single sphere leadfield\ncfg = [];\ncfg.grid = sourcemodel;\ncfg.headmodel = vol;\ncfg.elec = elec;\nleadfieldSphere = ft_prepare_leadfield(cfg);\n\n\n%%\n% http://www.fieldtriptoolbox.org/example/compute_forward_simulated_data_and_apply_a_beamformer_scan/\n\n% This example script shows you how to create some simulated channel-level\n% MEG data with a single dipole at a specified location in the head.\n% Subsequently it does a beamformer source reconstruction to localize that\n% source.\n\n% create an array with some magnetometers at 12cm distance from the origin\n[X, Y, Z] = sphere(10);\npos = unique([X(:) Y(:) Z(:)], 'rows');\npos = pos(pos(:,3)>=0,:);\ngrad = [];\ngrad.coilpos = 12*pos;\ngrad.coilori = pos; % in the outward direction\n% grad.tra = eye(length(pos)); % each coils contributes exactly to one channel\nfor i=1:length(pos)\n  grad.label{i} = sprintf('chan%03d', i);\nend\n\n% create a spherical volume conductor with 10cm radius\nvol.r = 10;\nvol.o = [0 0 0];\n\n% note that beamformer scanning will be done with a 1cm grid, so you should\n% not put the dipole on a position that will not be covered by a grid\n% location later\ncfg = [];\ncfg.headmodel = vol;\ncfg.grad = grad;\ncfg.dip.pos = [0 0 4];    % you can vary the location, here the dipole is along the z-axis\ncfg.dip.mom = [1 0 0]';   % the dipole points along the x-axis\ncfg.relnoise = 10;\ncfg.ntrials = 20;\ndata = ft_dipolesimulation(cfg);\n\n% compute the data covariance matrix, which will capture the activity of\n% the simulated dipole\ncfg = [];\ncfg.covariance = 'yes';\ntimelock = ft_timelockanalysis(cfg, data);\n\n% do the beamformer source reconstuction on a 1 cm grid\ncfg = [];\ncfg.headmodel = vol;\ncfg.grad = grad;\ncfg.resolution = 1;\ncfg.method = 'lcmv';\ncfg.lcmv.projectnoise = 'yes'; % needed for neural activity index\nsource = ft_sourceanalysis(cfg, timelock);\n\n% compute the neural activity index, i.e. projected power divided by\n% projected noise\ncfg = [];\ncfg.powmethod = 'none'; % keep the power as estimated from the data covariance, i.e. the induced power\nsource_nai = ft_sourcedescriptives(cfg, source);\n\ncfg = [];\ncfg.method = 'ortho';\ncfg.funparameter = 'nai';\ncfg.funcolorlim = [1.4 1.5];  % the voxel in the center of the volume conductor messes up the autoscaling\nft_sourceplot(cfg, source_nai);\n\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_issue1198.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5603140151382536}}
{"text": "% -------------------------------------------------------------------------\n%   Description:\n%       Demo script to calculate the BT scores\n%       This script reproduces the results of Figure 5 in our paper.\n%\n%   Citation: \n%       A Comparative Study for Single Image Blind Deblurring\n%       Wei-Sheng Lai, Jia-Bin Huang, Zhe Hu, Narendra Ahuja, and Ming-Hsuan Yang\n%       IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016\n%\n%   Contact:\n%       Wei-Sheng Lai\n%       wlai24@ucmerced.edu\n%       University of California, Merced\n% -------------------------------------------------------------------------\n\n%% input dataset and attribute\ndataset = 'real';\n% dataset = 'uniform';\n% dataset = 'nonuniform';\n\nattribute = 'all';\n% attribute = 'manmade';\n% attribute = 'natural';\n% attribute = 'people';\n% attribute = 'saturated';\n% attribute = 'text';\n\n\n%% Load list\nlist_filename = fullfile('list', 'method.txt');\nmethod = load_list(list_filename);\n\nattr_filename = fullfile('attributes', sprintf('%s_%s.txt', dataset, attribute));\nfprintf('Load %s\\n', attr_filename);\nattr_list = dlmread(attr_filename);\n\nnum_img = length(attr_list);\nnum_method = 14;\n\n\n%% load votes\nvote_filename = fullfile('votes', sprintf('votes_%s_balance_%s.csv', dataset, attribute));\nfprintf('Load %s\\n', vote_filename);\nM = csvread(vote_filename, 1, 0); % offset the first row to skip header\n\n\n%% build winning matrix\nscore_matrix = zeros(num_img, num_method);\n\nfor i = 1:num_img\n    \n    row = find(M(:, 1) == attr_list(i));\n    \n    % convert M to winning matrix\n    C = construct_winning_matrix(M(row, :), num_method);\n        \n    % compute BT scores\n    score = BT_EM_exp(C);\n    \n    % avoid Nan and Inf when compute mean\n    s = score;\n    s = s(s == s); % remove NaN\n    s = s(s ~= Inf); % remove Inf\n    \n    % normalize to zero mean\n    score = score - mean(s);\n    score_matrix(i, :) = score';\n    \nend\n\n\n%% compute mean scores for each method\nmethod_score = zeros(num_method, 1);\nfor i = 1:num_method\n    s = score_matrix(:, i);\n    s = s(s == s); % remove NaN\n    s = s(s ~= Inf); % remove Inf\n    method_score(i) = mean(s);\nend\n\n%% sort methods by mean scores\n[~, order] = sort(method_score, 'descend');\n\n\n%% plot cumulative frequency\n[color, marker, line_style] = color_spec;\n\nfigure; hold on;\nselect_method = order(1:14);\nlegend_cmd = 'legend(';\n\nx = -5:0.5:10;\nfor i = 1:length(select_method)\n    m = select_method(i);\n    s = score_matrix(:, m);\n    s = s(s == s); % remove NaN\n    s = s(s ~= Inf);  % remove Inf\n    \n    y = histc(s, x);\n    z = cumsum(y)/sum(y);\n    h = plot(x, z, 'LineWidth', 2);\n    h.Color = color{m};\n    h.LineStyle = line_style{m};\n    \n    legend_cmd = sprintf('%s method{%d}', legend_cmd, select_method(i));\n    if( i < length(select_method) )\n        legend_cmd = sprintf('%s, ', legend_cmd);\n    end\nend\nlegend_cmd = sprintf('%s);', legend_cmd);\nl = eval(legend_cmd);\nl.FontSize = 16;\nl.Location = 'southeast';\n\nif( strcmp(attribute, 'manmade') )\n    title(sprintf('%s (man-made)', dataset));\nelse\n    title(sprintf('%s (%s)', dataset, attribute));\nend\nxlabel('B-T Scores');\nylabel('Cumulative Frequency');\n\nh = gca;\nh.FontName = 'Times New Roman';\nh.FontSize = 24;\n\nhold off;\n\n%% save results\n\n% filename = sprintf('bt_cdf_%s_%s.pdf', dataset, attribute);\n% saveas(h, filename);\n% fprintf('Save %s\\n', filename);\n", "meta": {"author": "phoenix104104", "repo": "cvpr16_deblur_study", "sha": "d8751a80fd905fc0fceaf442cd6f85f0084a2570", "save_path": "github-repos/MATLAB/phoenix104104-cvpr16_deblur_study", "path": "github-repos/MATLAB/phoenix104104-cvpr16_deblur_study/cvpr16_deblur_study-d8751a80fd905fc0fceaf442cd6f85f0084a2570/demo_bt_ranking.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5603140078867597}}
{"text": "% TEST_CUBE_G_NMNN: data function for Neumann boundary condition.\n\nfunction g = test_cube_g_nmnn (x, y, z, ind)\n  switch ind\n    case 1\n      g = -exp (x + z) .* sin (y);\n    case 2\n      g = exp (x + z) .* sin (y);\n    case 3\n      g = -exp (x + z) .* cos (y);\n    case 4\n      g = exp (x + z) .* cos (y);\n    case 5\n      g = -exp (x + z) .* sin (y);\n    case 6\n      g = exp (x + z) .* sin (y);\n    otherwise\n      error ('test_cube_g_nmnn: unknown reference number');\n  end\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/examples/base/data_files/test_cube_g_nmnn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5602705520764169}}
{"text": "function test_suite = test_crossvalidate\n% tests for test_crossvalidate\n%\n% #   For CoSMoMVPA's copyright information and license terms,   #\n% #   see the COPYING file distributed with CoSMoMVPA.           #\n    try % assignment of 'localfunctions' is necessary in Matlab >= 2016\n        test_functions=localfunctions();\n    catch % no problem; early Matlab versions can use initTestSuite fine\n    end\n    initTestSuite;\n\n\nfunction test_crossvalidate_basics\n    classifier=@cosmo_classify_nn;\n    randint=@()ceil(rand()*5+5);\n\n    ds=cosmo_synthetic_dataset('ntargets',randint(),...\n                               'nchunks',randint(),...\n                               'nreps',randint(),...\n                               'seed',0);    % random data\n    nsamples=size(ds.samples,1);\n    nfolds=randint();\n\n    partitions=struct();\n    partitions.train_indices=cell(nfolds,1);\n    partitions.test_indices=cell(nfolds,1);\n\n    train_size=ceil(nsamples*(rand()*.5+.25));\n\n    pred=NaN(nsamples,nfolds);\n\n    for fold=1:nfolds\n        all_idx=randperm(nsamples);\n        train_idx=all_idx(1:train_size);\n        test_idx=all_idx((train_size+1):end);\n\n        partitions.train_indices{fold}=train_idx;\n        partitions.test_indices{fold}=test_idx;\n\n        pred(test_idx,fold)=classifier(ds.samples(train_idx,:),...\n                                        ds.sa.targets(train_idx),...\n                                        ds.samples(test_idx,:));\n    end\n\n    pred_msk=~isnan(pred);\n    is_correct=bsxfun(@eq,ds.sa.targets,pred) & pred_msk;\n    acc=sum(is_correct(:))/sum(pred_msk(:));\n\n    opt=struct();\n    opt.check_partitions=false;\n\n    [res_pred,res_acc]=cosmo_crossvalidate(ds,classifier,partitions,opt);\n    assertEqual(res_pred,pred);\n    assertElementsAlmostEqual(res_acc,acc);\n\n\n\n\n\n\n\n\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/tests/test_crossvalidate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514084, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.56027054938826}}
{"text": "% Function used in production of clique trees\n%\n% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n\nfunction [newF C E] = EliminateVar(F, C, E, Z)\n\nuseFactors = [];\nscope = [];\n\nfor i=1:length(F)\n    if any(F(i).var == Z)\n        useFactors = [useFactors i];\n        scope = union(scope, F(i).var);\n    end\nend\n\n% update edge map\n% These represent the induced edges for the VE graph.\nfor i=1:length(scope)\n    for j=1:length(scope)\n        \n        if i~=j\n            E(scope(i),scope(j)) = 1;\n            E(scope(j),scope(i)) = 1;\n        end\n    end\nend\n\nE(Z,:) = 0;\nE(:,Z) = 0;\n\n\nnonUseFactors = setdiff(1:length(F),[useFactors]);\n\nfor i=1:length(nonUseFactors)\n    newF(i) = F(nonUseFactors(i));\n    newmap(nonUseFactors(i)) = i;\nend\n\nnewFactor = struct('var', [], 'card', [], 'val', []);\nfor i=1:length(useFactors)\n    newFactor = FactorProduct(newFactor,F(useFactors(i)));\nend\n\nnewFactor = FactorMarginalization(newFactor,Z);\nnewF(length(nonUseFactors)+1) = newFactor;\n\nnewC = length(C.nodes)+1;\nC.nodes{newC} = scope;\nC.factorInds(newC) = length(nonUseFactors)+1;\nfor i=1:newC-1\n    if ismember(C.factorInds(i), useFactors)\n        C.edges(i,newC) = 1;\n        C.edges(newC,i) = 1;\n        C.factorInds(i) = 0;\n    else\n        if C.factorInds(i) ~= 0\n            C.factorInds(i) = newmap(C.factorInds(i));\n        end\n    end\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/7.CRF Learning for OCR/EliminateVar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.560270546510337}}
{"text": "function a = r8col_swap ( m, n, a, i, j )\n\n%*****************************************************************************80\n%\n%% R8COL_SWAP swaps columns I and J of an R8COL.\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, real 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, real 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, 'R8COL_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 ( 'R8COL_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\n", "meta": {"author": "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/r8col_swap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.5602705411340236}}
{"text": "function SO3F = inv(SO3F)      \n% Define the inverse function $g$ of an SO3Fun $f$ by $g(R^{-1}) = f(R)$\n% for all rotations $R\\in SO(3)$.\n%\n% Syntax\n%   SO3F = inv(F)\n%\n% Input\n%  F - @SO3Fun\n%\n% Output\n%  SO3F - @SO3FunHarmonic\n%  \n\nSO3F = SO3FunHarmonic(SO3F);\nSO3F = inv(SO3F);\n\n% or alternative use:\n% SO3F = SO3FunHandle(@(r) SO3F.eval(inv(r)),SO3F.SS,SO3F.CS);\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3Fun/inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5602674756465243}}
{"text": "function img = image_cap_quant(img, k, klower)\n    for i = 1 : size(img, 5)\n        tmp = img(:,:,:,:, i);\n        sorted = sort(tmp(:), 'ascend');\n        thrval = sorted(round(k * end));\n        tmp(tmp > thrval) = thrval;\n        \n        thrval = sorted(round(klower * end));\n        tmp(tmp < thrval) = thrval;\n        \n        img(:,:,:,:, i) = tmp;\n    end\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/image_cap_quant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5602674646951211}}
{"text": "classdef WheelEncoder < handle\n    \n% Copyright (C) 2013, Georgia Tech Research Corporation\n% see the LICENSE file included with this software\n\n    properties\n        type\n        \n        radius\n        length\n        ticks_per_rev\n        \n        ticks\n        \n        total_distance\n    end\n    \n    methods\n        function obj = WheelEncoder(type, radius, length, ticks_per_rev)\n            obj.radius = radius;\n            obj.length = length;\n            obj.type = type;\n            obj.ticks_per_rev = ticks_per_rev;\n            obj.ticks = 0;\n            obj.total_distance = 0;\n        end\n        \n        function update_ticks(obj, wheel_velocity, dt)\n            obj.ticks = obj.ticks + obj.distance_to_ticks(wheel_velocity*dt);\n        end\n        \n        function reset_ticks(obj)\n            obj.ticks = 0;\n        end\n        \n        function ticks = distance_to_ticks(obj, distance)\n            obj.total_distance = obj.total_distance + distance;\n            ticks = round((obj.total_distance*obj.ticks_per_rev)/(2*pi));\n            obj.total_distance = obj.total_distance - obj.ticks_to_distance(ticks);\n        end\n        \n        function distance = ticks_to_distance(obj, ticks)\n            distance = (ticks*2*pi)/obj.ticks_per_rev;\n        end\n    end\nend\n\n", "meta": {"author": "jdelacroix", "repo": "simiam", "sha": "cd67b5b97d6781d32333c0a33a51cfd5116640a9", "save_path": "github-repos/MATLAB/jdelacroix-simiam", "path": "github-repos/MATLAB/jdelacroix-simiam/simiam-cd67b5b97d6781d32333c0a33a51cfd5116640a9/+simiam/+robot/+sensor/WheelEncoder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.560267459272514}}
{"text": "function varargout = integral2(varargin)\n%INTEGRAL2  Double integral of a DISKFUN over its domain.\n%   I = INTEGRAL2(F) returns a value representing the double integral of a\n%   DISKFUN.\n%\n%\n%   I = INTEGRAL2(F, [a b c d]) integrates F in polar coordinates\n%   over the region [a b] x [c d], where a and b are angular values \n%   in the interval [-pi  pi], and  c and d are radial values in the \n%   interval [0 1].\n%\n% See also DISKFUN/INTEGRAL, DISKFUN/SUM2, DISKFUN/QUAD2D.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n[varargout{1:nargout}] = quad2d(varargin{:});\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/@diskfun/integral2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5602674590601359}}
{"text": "%JC 7/16/08-sim_qpsk_video\n%I thought some might be interested in this m-file, since we live in a \n%world of data,text,audio and video.\n%User has the option of using Data or an image(Lena1.bmp) to determine BER/SER for\n%M=2,4 or 8 PSK.\n%User also has the option of using Gray coding or no Gray coding.\n%Viewing a still image file thru a channel with AWGN added gives an intuitive insight into the\n%degradation of video at different levels of SNR. Running the image takes\n%approx 8 minutes. The program showes, for (M=2,4), the image is reproduced\n%(without errors) at approx. 10dB and M=8 requires approx 14 dB which\n%agrees with theory. The bandwidth efficiency for M=2 is 1(bit/sec/Hz), M=4\n%is 2(bits/sec/Hz), and M=8 is 3(bits/sec/Hz). Therefore M=4 and M=8 are good \n%choices for band limited channels. I restructered this program from one\n%written by\n%Chen Zhifeng\n%4/28/2007\n%Search WEB for \"Performance Analysis of Channel Estimation and\n%Equalization in Slow Fading Channels\"\n%--------------------------------------------------------------------------\nclose all;\nclear all;\nclc;\n%--------------------------------------------------------------------------\n%Set parameters\n%--------------------------------------------------------------------------\n%randn('state',0);%keeps noise characteristics the same on reruns\n%rand('state',0)%keeps intergers same on rerun\n%Holding all values constant, shows a slight improvement on BER @minus5dB when using Gray\n%coding and shows a slight degredation @plus 9dB. Is this valid according to theory?\n%An interesting test would be to see the results with FEC(with and without Gray coding) if\n%you have the Communications Toolbox(I don't) and also to test these\n%results against it. Also,\n%I challenge someone to write an easy to understand m-file Viterbi decoder\n%that can be used in conjunction with the convolutional encoder m-file\n%under JC files in author index. This would be helpful to many folks,\n%including myself.\nMax_dB =10  % input SNR in dB\nmodtype = 'psk'\nM=8                    %M-ary\ngray_encode = 1;      %1=yes 0=no\nNdata = 1000000;      %limit to 1000000 samples for matlab processing\nTest_image = 1;       %1=yes 0=no\nImage_name = 'Lena1.bmp' %color photo Lena1  im 128x128x3 uint8 array\n                          %M=4   128x128x3x4=196608\nk=log2(M);\nebn0=10.^(Max_dB/10);\n%--------------------------------------------------------------------------\n%produce Data or load image\n%--------------------------------------------------------------------------\n%use this method because the program may transmit data from file, such as a image\nData=My_randint(1,Ndata,0,3);%produce intergers from 0 to 3(QPSK-M=4)-Change for M=2,8\n%Data=My_randint(1,Ndata,0,1);%M=8\n%Data=My_randint(1,Ndata,0,1);%M=2\n%use Data=randint(1,Ndata,M); if you have this function(Communications Toolbox) \nif Test_image    \n    im = imread('Lena1.bmp');\n    disp('Fig 1 showing original image before AWGN added');\n    image(im);\n    drawnow\n    [Data, row_im, col_im, third_im] = image2data(im, M);\nend\nNdata = length(Data);\nTransmit = Data;\ndatalen = length(Transmit);\n%--------------------------------------------------------------------------\n%encode-Gray or no Gray\n%--------------------------------------------------------------------------\nif gray_encode\n    % Create Gray encoding and decoding arrays-flip(2=3)and(3=2 for M=4)\n    grayencod = bitxor(0:M-1, floor((0:M-1)/2));\n    [dummy graydecod] = sort(grayencod); graydecod = graydecod - 1;\n\n    % Gray encode symbols\n    Transmit_gray = grayencod(Transmit+1);\nend\n%--------------------------------------------------------------------------\n%Modulation\n%--------------------------------------------------------------------------\nif gray_encode\n    step=2*pi/M;\n    S=exp(j*Transmit_gray.*step);\nelse %no Gray encode\n    step=2*pi/M;\n    S=exp(j*Transmit.*step);\nend      \n%-----------------------------------------------------------------------           \n%uniform the noise power by 1/var=SNR=Es/(N0/2)=2*k*ebn0       \nstd=(1/2/k./ebn0).^0.5;\n%-----------------------------------------------------------------------\n%-----------------------------------------------------------------------\n%add AWGN\n%-----------------------------------------------------------------------\nZ = std*( randn(1,datalen)+j*randn(1,datalen) );\nR=S+Z;\n%-------------------------------------------------------------------------\n%demodulation\n%-------------------------------------------------------------------------\nstep=2*pi/M;\nRphase = atan2(imag(R), real(R));%1 radian=57.296 degrees\n%Sphase = atan2(imag(S), real(S));%for testing only\nReceive = Rphase/step;%error is made if noise causes phase to fall outside +-45 degrees for M=4\n                      \nReceive = round(Receive);\nReceive = mod(Receive,M);           \nif gray_encode  \n% Gray decode message\nReceive = graydecod(Receive+1);%Received image or data\nend\n                      \nne=sum(Data~=Receive)%number of errors\nBER=ne/Ndata%bit error rate\nSER=ne/Ndata/k\n           \nif Test_image \n   ima = data2image(Receive, row_im, col_im, third_im, M);\n   ima = uint8(ima);\n   imwrite(ima,'Received_image.bmp');\n   disp(' ');\n   disp('Fig 2 received image(after AWGN added) is saved as Received_image.bmp in the same directory');\n   disp(' ');\n   figure\n   image(ima);\n   drawnow                           \nend\n\n%INFO-The analytical expressions and references used in berawgn, bercoding, berfading, and\n%BERTool are found in the Communications Toolbox documentation.\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/20746-qpskvideo/QPSK_VIDEO/sim_qpsk_video.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5602674538499064}}
{"text": "function ua = diagonal_pointer_cr ( n, nz_num, ia, ja )\n\n%*****************************************************************************80\n%\n%% DIAGONAL_POINTER_CR finds diagonal entries in a sparse compressed row matrix.\n%\n%  Discussion:\n%\n%    The matrix A is assumed to be stored in compressed row format.  Only\n%    the nonzero entries of A are stored.  The vector JA stores the\n%    column index of the nonzero value.  The nonzero values are sorted\n%    by row, and the compressed row vector IA then has the property that\n%    the entries in A and JA that correspond to row I occur in indices\n%    IA[I] through IA[I+1]-1.\n%\n%    The array UA can be used to locate the diagonal elements of the matrix.\n%\n%    It is assumed that every row of the matrix includes a diagonal element,\n%    and that the elements of each row have been ascending sorted.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%   \n%  Modified:\n%\n%    25 March 2008\n%\n%  Author:\n%\n%    Original C version by Lili Ju\n%    MATLAB version by John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the order of the system.\n%\n%    Input, integer NZ_NUM, the number of nonzeros.\n%\n%    Input, integer IA(N+1), JA(NZ_NUM), the row and column indices\n%    of the matrix values.  The row vector has been compressed.  On output,\n%    the order of the entries of JA may have changed because of the sorting.\n%\n%    Output, integer UA(N), the index of the diagonal element of each row.\n%\n  ua(1:n) = -1;\n\n  for i = 1 : n\n    for j = ia(i) : ia(i+1) - 1\n      if ( ja(j) == i ) \n        ua(i) = 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/mgmres/diagonal_pointer_cr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.5602055454294572}}
{"text": "function grid_level = index_level_own ( level, level_max, dim_num, ...\n  point_num, grid_index, grid_base )\n\n%*****************************************************************************80\n%\n%% INDEX_LEVEL_OWN: determine first level at which given index is generated.\n%\n%  Discussion:\n%\n%    We are constructing a sparse grid based on a 1D OWN rule (Gauss Legendre\n%    or Gauss Hermite).  The grid is built up of product grids,\n%    with a characteristic LEVEL.\n%\n%    We are concerned with identifying points in this product grid which\n%    have actually been generated previously, on a lower value of LEVEL.\n%\n%    This routine determines the lowest value of LEVEL at which each of\n%    the input points would be generated.\n%\n%    In 1D, given LEVEL, the number of points is ORDER = 2**(LEVEL+1) + 1,\n%    (except that LEVEL = 0 implies ORDER = 1%), the BASE is (ORDER-1)/2,\n%    and the point INDEX values range from -BASE to +BASE.\n%\n%    The values of INDEX and BASE allow us to determine the abstract\n%    properties of the point.  In particular, if INDEX is 0, the corresponding\n%    abscissa is 0, the special \"nested\" value we need to take care of.\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 LEVEL, the level at which these points were\n%    generated.  LEVEL_MIN <= LEVEL <= LEVEL_MAX.\n%\n%    Input, integer LEVEL_MAX, the maximum level.\n%\n%    Input, integer DIM_NUM, the spatial dimension.\n%\n%    Input, integer POINT_NUM, the number of points to be tested.\n%\n%    Input, integer GRID_INDEX(DIM_NUM,POINT_NUM), the indices of the\n%    points to be tested.\n%\n%    Input, integer GRID_BASE(DIM_NUM), the \"base\", which is essentially\n%    the denominator of the index.\n%\n%    Output, integer GRID_LEVEL(POINT_NUM), the value of LEVEL at\n%    which the point would first be generated.  This will be the same as\n%    the input value of LEVEL, unless the point has an INDEX of 0 and\n%    a corresponding BASE that is NOT zero.\n%\n  if ( dim_num == 1 )\n    level_min = level_max;\n  else\n    level_min = 0;\n  end\n%\n%  If a point has a DIM-th component whose INDEX is 0, then the\n%  value of LEVEL at which this point would first be generated is\n%  less than LEVEL, unless the DIM-th component of GRID_BASE is 0.\n%\n  for point = 1 : point_num\n\n    grid_level(point) = max ( level, level_min );\n\n    for dim = 1 : dim_num\n      if ( grid_index(dim,point) == 0 )\n        grid_level(point) = max ( grid_level(point) - grid_base(dim), level_min );\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/sandia_sparse/index_level_own.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5602055427041585}}
{"text": "\n\nx = [-117.6 -115.6 -115.6 -117.6 -117.6]\ny = [35.5 35.5 33.5 33.5 35.5]\n\n%create a rectangular grid\nxvect=[min(x):dx:max(x)];\nyvect=[min(y):dy:max(y)];\ngx = xvect;\ngy= yvect;\ntmpgri=zeros((length(xvect)*length(yvect)),2);\nn=0;\nfor i=1:length(xvect)\n    for j=1:length(yvect)\n        n=n+1;\n        tmpgri(n,:)=[xvect(i) yvect(j)];\n    end\nend\n%extract all gridpoints in chosen polygon\nXI=tmpgri(:,1);\nYI=tmpgri(:,2);\n\n    ll = polygon_filter(x,y, XI, YI, 'inside');\n%grid points in polygon\nnewgri=tmpgri(ll,:);\n\n% plot the grid points\nfigure_w_normalized_uicontrolunits(map)\npl = plot(newgri(:,1),newgri(:,2),'+k','era','normal');\nset(pl,'MarkerSize',8,'LineWidth',1)\ndrawnow\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/pvals/haz_selgp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5601675139002873}}
{"text": "function [ data ] = vis_wcf( label_list, obb_list )\n\nlinewidth = 2;\ncorlist = {[1,0.5,0.5,0.3],[0.5,0.7843,0.5,0.3],[0.5,0.5,1,0.3],[1,0.5,0,0.3],[0.1961,0.7843,1,0.3]};\n\nfront = [0,0,1];\nup = [0,1,0];\naxes = [1,0,0];\n\nobblist = [obb_list(1:6,:);zeros(3,size(obb_list,2));obb_list(7:9,:)];\nobblist(8,:) = 1;\n\nfor i = 1:length(label_list)\n    if(i<3)\n        % skip the visualization of floor and ceiling\n        continue\n    end\n    p = obblist(:,i);\n    \n    center = p(1:3);\n    lengths = p(10:12);\n    \n    dir_1 = p(4:6);\n    dir_2 = p(7:9);\n    dir_1 = dir_1/norm(dir_1);\n    dir_2 = dir_2/norm(dir_2);\n    dir_3 = cross(dir_1,dir_2);\n    dir_3 = dir_3/norm(dir_3); \n    d1 = 0.5*lengths(1)*dir_1;\n    d2 = 0.5*lengths(2)*dir_2;\n    d3 = 0.5*lengths(3)*dir_3;\n\n    cornerpoints(1,:) = center-d1-d2-d3;\n    cornerpoints(2,:) = center+d1-d2-d3;\n    cornerpoints(3,:) = center-d1-d2+d3;\n    cornerpoints(4,:) = center+d1-d2+d3;\n    cornerpoints(:,1) = 1 - cornerpoints(:,1);\n    \n    cor = corlist{mod(i-1,length(corlist))+1};\n    plot([cornerpoints(1,1),cornerpoints(2,1)],[cornerpoints(1,3),cornerpoints(2,3)],'Color',cor(1:3),'linewidth',linewidth);\n    hold on\n    plot([cornerpoints(2,1),cornerpoints(4,1)],[cornerpoints(2,3),cornerpoints(4,3)],'Color',cor(1:3),'linewidth',linewidth);\n    plot([cornerpoints(4,1),cornerpoints(3,1)],[cornerpoints(4,3),cornerpoints(3,3)],'Color',cor(1:3),'linewidth',linewidth);\n    plot([cornerpoints(3,1),cornerpoints(1,1)],[cornerpoints(3,3),cornerpoints(1,3)],'Color',cor(1:3),'linewidth',linewidth);\n\t\n\tlabel = label_list{i};\n\tmin_x = min(cornerpoints(:,1));\n\tmax_z = max(cornerpoints(:,3));\n\tt = text(min_x+0.01,max_z-0.02,[label]);\n\tt.BackgroundColor = cor;\n\tt.FontSize = 8;\nend\n\naxis equal\naxis off\nfig = gcf;\nfig.PaperUnits = 'points';\nfig.PaperPosition = [0 0 224 224];%168 %108\n\nf=getframe(gcf);\ndata=f.cdata;\n\nend", "meta": {"author": "ManyiLi12345", "repo": "GRAINS", "sha": "7806359dada1283a110886d4b634fdedf6963e63", "save_path": "github-repos/MATLAB/ManyiLi12345-GRAINS", "path": "github-repos/MATLAB/ManyiLi12345-GRAINS/GRAINS-7806359dada1283a110886d4b634fdedf6963e63/vistools/vis_wcf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5601675033731365}}
{"text": "function u = fem2d_bvp_quadratic ( nx, ny, a, c, f, x, y )\n\n%*****************************************************************************80\n%\n%% FEM2D_BVP_QUADRATIC solves boundary value problem on a rectangle.\n%\n%  Discussion:\n%\n%    The program uses the finite element method, with piecewise quadratic basis\n%    functions to solve a 2D boundary value problem over a rectangle.\n%\n%    The following differential equation is imposed inside the region:\n%\n%      - d/dx a(x,y) du/dx - d/dy a(x,y) du/dy + c(x,y) * u(x,y) = f(x,y)\n%\n%    where a(x,y), c(x,y), and f(x,y) are given functions.\n%\n%    On the boundary, the solution is constrained to have the value 0.\n%\n%    The finite element method will use a regular grid of NX nodes in X, and \n%    NY nodes in Y.  Both NX and NY must be odd.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    23 June 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer NX, NY, the number of X and Y grid values.\n%    NX and NY must be odd and at least 3.\n%\n%    Input, function A(X,Y), evaluates a(x,y);\n%\n%    Input, function C(X,Y), evaluates c(x,y);\n%\n%    Input, function F(X,Y), evaluates f(x,y);\n%\n%    Input, real X(NX), Y(NY), the mesh points.\n%\n%    Output, real U(NX,NY), the finite element coefficients, which are also\n%    the value of the computed solution at the mesh points.\n%\n\n%\n%  Quadrature definitions.\n%\n  quad_num = 3;\n  abscissa(1) = -0.774596669241483377035853079956;\n  abscissa(2) = 0.000000000000000000000000000000;\n  abscissa(3) = 0.774596669241483377035853079956;\n  weight(1) = 0.555555555555555555555555555556;\n  weight(2) = 0.888888888888888888888888888889;\n  weight(3) = 0.555555555555555555555555555556;\n%\n%  Make room for the matrix A and right hand side b.\n%\n  mn = nx * ny;\n  A = zeros ( mn, mn );\n  b = zeros ( mn, 1 );\n%\n%  Compute the matrix entries by integrating over each element.\n%\n  ex_num = ( nx - 1 ) / 2;\n  ey_num = ( ny - 1 ) / 2;\n\n  for ex = 1 : ex_num\n\n    w = 2 * ex - 1;\n    cc = 2 * ex;\n    e = 2 * ex + 1;\n\n    xx(1) = x(w);\n    xx(2) = x(cc);\n    xx(3) = x(e);\n\n    for ey = 1 : ey_num\n\n      s = 2 * ey - 1;\n      mm = 2 * ey;\n      n = 2 * ey + 1;\n\n      yy(1) = y(s);\n      yy(2) = y(mm);\n      yy(3) = y(n);\n%\n%  Node indices\n%\n%  7  8  9   wn cn en\n%  4  5  6   wm cm em\n%  1  2  3   ws cs es\n%\n      node(1) = ( 2 * ey - 2 ) * nx + ( ex - 1 ) * 2 + 1;\n      node(2) = ( 2 * ey - 2 ) * nx + ( ex - 1 ) * 2 + 2;\n      node(3) = ( 2 * ey - 2 ) * nx + ( ex - 1 ) * 2 + 3;\n      node(4) = ( 2 * ey - 1 ) * nx + ( ex - 1 ) * 2 + 1;\n      node(5) = ( 2 * ey - 1 ) * nx + ( ex - 1 ) * 2 + 2;\n      node(6) = ( 2 * ey - 1 ) * nx + ( ex - 1 ) * 2 + 3;\n      node(7) = ( 2 * ey     ) * nx + ( ex - 1 ) * 2 + 1;\n      node(8) = ( 2 * ey     ) * nx + ( ex - 1 ) * 2 + 2;\n      node(9) = ( 2 * ey     ) * nx + ( ex - 1 ) * 2 + 3;\n\n      for qx = 1 : quad_num\n\n        xq = ( ( 1.0 - abscissa(qx) ) * xx(1)   ...\n             + ( 1.0 + abscissa(qx) ) * xx(3) ) ...\n               / 2.0;\n\n        for qy = 1 : quad_num\n\n          yq = ( ( 1.0 - abscissa(qy) ) * yy(1)   ...\n               + ( 1.0 + abscissa(qy) ) * yy(3) ) ...\n                 / 2.0;\n\n          wq = weight(qx) * ( xx(3) - xx(1) ) / 2.0 ...\n             * weight(qy) * ( yy(3) - yy(1) ) / 2.0;\n%\n%  Need to AUTOMATE THIS PROCEDURE.\n%\n%         v(1) =  ( xq - x(2) ) / ( x(1) - x(2) ) ...\n%               * ( xq - x(3) ) / ( x(1) - x(3) ) ...\n%               * ( yq - y(2) ) / ( y(1) - y(2) ) ...\n%               * ( yq - y(3) ) / ( y(1) - y(3) );\n\n%         vx(1) =           1.0 / ( x(1) - x(2) )  ...\n%               * ( xq - x(3) ) / ( x(1) - x(3) ) ...\n%               * ( yq - y(2) ) / ( y(1) - y(2) ) ...\n%               * ( yq - y(3) ) / ( y(1) - y(3) ) ...\n%               + ( xq - x(2) ) / ( x(1) - x(2) ) ...\n%               *           1.0 / ( x(1) - x(3) ) ...\n%               * ( yq - y(2) ) / ( y(1) - y(2) ) ...\n%               * ( yq - y(3) ) / ( y(1) - y(3) );\n\n%         vy(1) = ( xq - x(2) ) / ( x(1) - x(2) ) ...\n%               * ( xq - x(3) ) / ( x(1) - x(3) ) ...\n%               *          1.0  / ( y(1) - y(2) ) ...\n%               * ( yq - y(3) ) / ( y(1) - y(3) ) ...\n%               + ( xq - x(2) ) / ( x(1) - x(2) ) ...\n%               * ( xq - x(3) ) / ( x(1) - x(3) ) ...\n%               * ( yq - y(2) ) / ( y(1) - y(2) ) ...\n%               *           1.0 / ( y(1) - y(3) );\n\n          v = ones ( 9, 1 );\n          vx = zeros ( 9, 1 );\n          vy = zeros ( 9, 1 );\n\n          k = 0;\n\n          for jl = 1 : 3\n            for il = 1 : 3\n\n              k = k + 1;\n\n              for il2 = 1 : 3\n                if ( il2 ~= il )\n                  v(k) = v(k) * ( xq - xx(il2) ) / ( xx(il) - xx(il2) );\n                  t = 1.0 / ( xx(il) - xx(il2 ) );\n                  for il3 = 1 : 3\n                    if ( il3 ~= il & il3 ~= il2 )\n                      t = t * ( xq - xx(il3) ) / ( xx(il) - xx(il3) );\n                    end\n                  end\n                  for jl2 = 1 : 3\n                    if ( jl2 ~= jl )\n                      t = t * ( yq - yy(jl2) ) / ( yy(jl) - yy(jl2) );\n                    end\n                  end\n                  vx(k) = vx(k) + t;\n                end\n              end\n\n              for jl2 = 1 : 3\n                if ( jl2 ~= jl )\n                  v(k) = v(k) * ( yq - yy(jl2) ) / ( yy(jl) - yy(jl2) );\n                  t = 1.0 / ( yy(jl) - yy(jl2 ) );\n                  for il2 = 1 : 3\n                    if ( il2 ~= il )\n                      t = t * ( xq - xx(il2) ) / ( xx(il) - xx(il2) );\n                    end\n                  end\n                  for jl3 = 1 : 3\n                    if ( jl3 ~= jl & jl3 ~= jl2 )\n                      t = t * ( yq - yy(jl3) ) / ( yy(jl) - yy(jl3) );\n                    end\n                  end\n                  vy(k) = vy(k) + t;\n                end\n              end\n\n            end\n          end\n\n          aq = a ( xq, yq );\n          cq = c ( xq, yq );\n          fq = f ( xq, yq );\n\n          for i = 1 : 9\n            ii = node(i);\n            for j = 1 : 9\n              jj = node(j);\n              A(ii,jj) = A(ii,jj) + wq * ( vx(i) * aq * vx(j) ...\n                                         + vy(i) * aq * vy(j) ...\n                                         + v(i)  * cq * v(j) );\n            end\n            b(ii) = b(ii) + wq * ( v(i) * fq );\n          end\n \n        end\n      end \n    end\n  end\n%\n%  Where a node is on the boundary, \n%  replace the finite element equation by a boundary condition.\n%\n  k = 0;\n  for y = 1 : ny\n    for x = 1 : nx\n      k = k + 1;\n      if ( x == 1 | x == nx | y == 1 | y == ny )\n        A(k,1:mn) = 0.0;\n        A(1:mn,k) = 0.0;\n        A(k,k) = 1.0;\n        b(k) = 0.0;\n      end\n    end\n  end\n\n  if ( 0 )\n    spy ( A );\n    pause\n  end\n%\n%  Solve the linear system.\n%\n  u = A \\ b;\n%\n%  Make the vector U into a matrix.\n%  Hope that of the various possible reorderings, you and MATLAB agree.\n%\n%    U(matrix)   U(vector)\n%   ----------  ----------\n%    U11 U12  =>  U11\n%    U21 U22      U21\n%                 U12\n%                 U22\n%\n  u = reshape ( u, nx, ny );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_bvp_quadratic/fem2d_bvp_quadratic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5601675030745262}}
{"text": "function [ a, rcond, z, info ] = dpoco ( a, lda, n )\n\n%*****************************************************************************80\n%\n%% DPOCO factors a real symmetric positive definite matrix and estimates its condition.\n%\n%  Discussion:\n%\n%    If RCOND is not needed, DPOFA is slightly faster.\n%\n%    To solve A*X = B, follow DPOCO by DPOSL.\n%\n%    To compute inverse(A)*C, follow DPOCO by DPOSL.\n%\n%    To compute determinant(A), follow DPOCO by DPODI.\n%\n%    To compute inverse(A), follow DPOCO by DPODI.\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%    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, real A(LDA,N), the symmetric matrix to be factored.  Only the \n%    diagonal and upper triangle are used.\n%\n%    Input, integer LDA, the leading dimension of the array A.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Output, real A(LDA,N), an upper triangular matrix R so that A = R'*R \n%    where R' is the transpose.  The strict lower triangle is unaltered.\n%    If INFO /= 0, the factorization is not complete.\n%\n%    Output, real RCOND, an estimate of the reciprocal \n%    condition of A.  For the system A*X = B, relative perturbations in \n%    A and B of size EPSILON may cause relative perturbations in X of \n%    size EPSILON/RCOND.  If RCOND is so small that the logical expression\n%      1.0 + RCOND == 1.0\n%    is true, then A may be singular to working precision.  In particular,  \n%    RCOND is zero if exact singularity is detected or the estimate underflows.\n%\n%    Output, real Z(N), a work vector whose contents are usually\n%    unimportant.  If A is close to a singular matrix, then Z is an \n%    approximate null vector in the sense that\n%      norm(A*Z) = RCOND * norm(A) * norm(Z).\n%    If INFO /= 0, Z is unchanged.\n%\n%    Output, integer INFO, error flag.\n%    0, for normal return.\n%    K, signals an error condition.  The leading minor of order K is not \n%    positive definite.\n%\n\n%\n%  Find norm of A using only upper half.\n%\n  for j = 1 : n\n    z(j) = dasum ( j, a(1:j,j), 1 );\n    for i = 1 : j-1\n      z(i) = z(i) + abs ( a(i,j) );\n    end\n  end\n\n  anorm = max ( z(1:n) );\n%\n%  Factor.\n%\n  [ a, info ] = dpofa ( a, lda, n );\n\n  if ( info ~= 0 )\n    return\n  end\n%\n%  RCOND = 1/(norm(A)*(estimate of norm(inverse(A)))).\n%\n%  Estimate = norm(Z)/norm(Y) where A*Z = Y and A*Y = E.\n%\n%  The components of E are chosen to cause maximum local\n%  growth in the elements of W where R'*W = E.\n%\n%  The vectors are frequently rescaled to avoid overflow.\n%\n%  Solve R' * W = E.\n%\n  ek = 1.0;\n  z(1:n) = 0.0;\n\n  for k = 1 : n\n\n    if ( z(k) ~= 0.0 )\n      ek = - abs ( ek ) * r8_sign ( z(k) );\n    end\n\n    if ( a(k,k) < abs ( ek - z(k) ) )\n      s = a(k,k) / abs ( ek - z(k) );\n      z(1:n) = s * z(1:n);\n      ek = s * ek;\n    end\n\n    wk = ek - z(k);\n    wkm = -ek - z(k);\n    s = abs ( wk );\n    sm = abs ( wkm );\n    wk = wk / a(k,k);\n    wkm = wkm / a(k,k);\n\n    if ( k + 1 <= n )\n\n      for j = k+1 : n\n        sm = sm + abs ( z(j) + wkm * a(k,j) );\n        z(j) = z(j) + wk * a(k,j);\n        s = s + abs ( z(j) );\n      end\n\n      if ( s < sm )\n        t = wkm - wk;\n        wk = wkm;\n        z(k+1:n) = z(k+1:n) + t * a(k,k+1:n);\n      end\n\n    end\n\n    z(k) = wk;\n\n  end\n\n  z(1:n) = z(1:n) / dasum ( n, z(1:n), 1 );\n%\n%  Solve R * Y = W.\n%\n  for k = n : -1 : 1\n\n    if ( a(k,k) < abs ( z(k) ) )\n      s = a(k,k) / abs ( z(k) );\n      z(1:n) = s * z(1:n);\n    end\n\n    z(k) = z(k) / a(k,k);\n    t = -z(k);\n    z(1:k-1) = daxpy ( k-1, t, a(1:k-1,k)', 1, z(1:k-1), 1 );\n\n  end\n\n  z(1:n) = z(1:n) / dasum ( n, z(1:n), 1 );\n  ynorm = 1.0;\n%\n%  Solve R' * V = Y.\n%\n  for k = 1 : n\n\n    z(k) = z(k) - ddot ( k-1, a(1:k-1,k), 1, z(1:k-1), 1 );\n\n    if ( a(k,k) < abs ( z(k) ) )\n      s = a(k,k) / abs ( z(k) );\n      z(1:n) = s * z(1:n);\n      ynorm = s * ynorm;\n    end\n\n    z(k) = z(k) / a(k,k);\n\n  end\n\n  s = 1.0 / dasum ( n, z(1:n), 1 );\n  z(1:n) = s * z(1:n);\n  ynorm = s * ynorm;\n%\n%  Solve R * Z = V.\n%\n  for k = n : -1 : 1\n\n    if ( a(k,k) < abs ( z(k) ) )\n      s = a(k,k) / abs ( z(k) );\n      z(1:n) = s * z(1:n);\n      ynorm = s * ynorm;\n    end\n\n    z(k) = z(k) / a(k,k);\n    t = -z(k);\n    z(1:k-1) = daxpy ( k-1, t, a(1:k-1,k)', 1, z(1:k-1), 1 );\n\n  end\n%\n%  Make ZNORM = 1.0.\n%\n  s = 1.0 / dasum ( n, z(1:n), 1 );\n  z(1:n) = s * z(1:n);\n  ynorm = s * ynorm;\n\n  if ( anorm ~= 0.0 )\n    rcond = ynorm / anorm;\n  else\n    rcond = 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/linpack_d/dpoco.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5601674922487649}}
{"text": "function [points2d,z3] = project3dPtsTo2d(points3d, K, Rtilt, trans, crop)\n% project 3D point cloud in world coordinate to x-y 2D plane. Provided by\n% Shuran Song\n% points3d: point cloud in camera coordinate\n% K: camera intrinsic\n% Rtilt, trans: camera extrinsic\n% crop: assume it be 1\n\n    %% inverse of get_aligned_point_cloud\n    points3d = bsxfun(@plus, Rtilt * points3d', trans)';\n    \n    %% inverse rgb_plane2rgb_world\n    if isempty(K)\n        camera_params;\n    else\n        cx_rgb = K(1,3); cy_rgb = K(2,3);  \n        fx_rgb = K(1,1); fy_rgb = K(2,2);\n    end    \n    % Make the original consistent with the camera location:\n    x3 = points3d(:,1);\n    y3 = -points3d(:,2); % when doing projection or depth->3d, always flip y dimension.\n    z3 = points3d(:,3);\n    \n    xx = x3 * fx_rgb ./ z3 + cx_rgb;\n    yy = y3 * fy_rgb ./ z3 + cy_rgb;\n    \n    if ~exist('crop','var')||isempty(crop)\n        xx = xx - 41 + 1;\n        yy = yy - 45 + 1;\n    else\n        xx = xx - crop(2) + 1;\n        yy = yy - crop(1) + 1;\n    end\n    points2d = [xx yy];\nend", "meta": {"author": "zhirongw", "repo": "3DShapeNets", "sha": "6a6cc71a9231051866092c94486ae967ac533d34", "save_path": "github-repos/MATLAB/zhirongw-3DShapeNets", "path": "github-repos/MATLAB/zhirongw-3DShapeNets/3DShapeNets-6a6cc71a9231051866092c94486ae967ac533d34/3D/project3dPtsTo2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5601674922487647}}
{"text": "clear all\n\nNsamples = 41500;\nEulerSaved = zeros(Nsamples, 3);\n\ndt = 0.01;\n\nfor k = 1:Nsamples\n  [p q r] = GetGyro();   \n  [phi theta psi] = EulerGyro(p, q, r, dt); \n  \n  EulerSaved(k, :) = [ phi theta psi ];\nend \n\n\nPhiSaved   = EulerSaved(:, 1) * 180/pi;\nThetaSaved = EulerSaved(:, 2) * 180/pi;\nPsiSaved   = EulerSaved(:, 3) * 180/pi;\n\nt = 0:dt:Nsamples*dt-dt;\n\nfigure\nplot(t, PhiSaved)\n\nfigure\nplot(t, ThetaSaved)\n\nfigure\nplot(t, PsiSaved)", "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/TestEulerGyro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5601596851718642}}
{"text": "function [lo, hi] = afb(x, af)\n\n% Analysis filter bank\n%\n% USAGE:\n%    [lo, hi] = afb(x, af)\n% INPUT:\n%    x - N-point vector, where\n%            1) N is even\n%            2) N >= length(af)\n%    af - analysis filters\n%    af(:, 1) - lowpass filter (even length)\n%    af(:, 2) - highpass filter (even length)\n% OUTPUT:\n%    lo - Low frequecy output\n%    hi - High frequency output\n% EXAMPLE:\n%    [af, sf] = farras;\n%    x = rand(1,64);\n%    [lo, hi] = afb(x, af);\n%    y = sfb(lo, hi, 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\nN = length(x);\nL = length(af)/2;\nx = cshift(x,-L);\n\n% lowpass filter\nlo = upfirdn(x, af(:,1), 1, 2);\nlo(1:L) = lo(N/2+[1:L]) + lo(1:L);\nlo = lo(1:N/2);\n\n% highpass filter\nhi = upfirdn(x, af(:,2), 1, 2);\nhi(1:L) = hi(N/2+[1:L]) + hi(1:L);\nhi = hi(1:N/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/DTCWT/afb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.5601596736960398}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\nfunction result = xstar(ival, cp, a, b, iter, Grid_k, ...\n    model, V, t, r, q, strike, varargin)\n\ncfvals = exp(feval(@CF, model, pi * Grid_k * diag(1./ (b-a)), t,r,q,varargin{:}));\n\nx = ival;\neps = 1e-6;\n\nfor n = 1:iter  \n    exp_t = exp( 1i * pi * Grid_k * diag((x - a) ./ (b - a)) );\n    vec = real( cfvals .* exp_t ) .* V;\n    vec(1,:) = 0.5*vec(1,:);\n    \n    g = (exp(-r * t) * sum(vec, 1)') ...\n            - cp .* strike .* (exp(x) - 1);\n    \n    vec = imag(cfvals .* Grid_k .* exp_t) .* V;\n    vec(1,:) = 0.5*vec(1,:);\n    \n    dg = - exp(-r * t) .* pi ./ (b - a) .* sum(vec, 1)' - cp .* strike .* exp(x);\n    \n    x = x - (g ./ dg);\n    if abs(g) < eps\n        break;\n    end\nend\n\nresult = x;\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/37617-cos-method-multiple-strikes-bermudan-greeks/Cos_Method_Bermudan_Mult_Strikes/xstar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5601596637427759}}
{"text": "%  anova2rm_cell() - compute F-values in cell array using repeated measure\n%                    ANOVA.\n%\n% Usage:\n%    >> [FC FR FI dfc dfr dfi] = anova2rm_cell( data );\n%\n% Inputs:\n%   data       = data consisting of PAIRED arrays to be compared. The last \n%                dimension of the data array is used to compute ANOVA.\n% Outputs:\n%   FC   - F-value for columns.\n%   FR   - F-value for rows.\n%   FI   - F-value for interaction.\n%   dfc  - degree of freedom for columns.\n%   dfr  - degree of freedom for rows.\n%   dfi  - degree of freedom for interaction.\n%\n% Note: this function is inspired from rm_anova available at \n%       http://www.mathworks.se/matlabcentral/fileexchange/6874-two-way-rep\n%       eated-measures-anova\n%       It allows for fast computation of about 20 thousands ANOVA per\n%       second. It is different from anova2_cell which mimics the ANOVA\n%       fonction from the Matlab statistical toolbox. This function\n%       computes true repeated measure ANOVA.\n%\n% Example:\n%   a = { rand(1,10) rand(1,10) rand(1,10); rand(1,10) rand(1,10) rand(1,10) }\n%   [FC FR FI dfc dfr dfi] = anova2rm_cell(a)\n%   signifC = 1-fcdf(FC, dfc(1), dfc(2))\n%   signifR = 1-fcdf(FR, dfr(1), dfr(2))\n%   signifI = 1-fcdf(FI, dfi(1), dfi(2))\n%\n%   % for comparison \n%   z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2;\n%   rm_anova2(  [ a{1,1}';a{1,2}';a{1,3}';a{2,1}';a{2,2}';a{2,3}' ], ...\n%               repmat([1:10]', [6 1]), [o;o;o;z;z;z], [z;o;t;z;o;t], {'a','b'})\n%\n%   c = { rand(200,400,10) rand(200,400,10); ...\n%         rand(200,400,10) rand(200,400,10)};\n%   [FC FR FI dfc dfr dfi] = anova2rm_cell(c) % computes 200x400 ANOVAs\n%\n% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2010\n\n% Copyright (C) Arnaud Delorme\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction [fA fB fAB dfApair dfBpair dfABpair] = anova2rm_cell(data)\n\n% compute all means and all std\n% -----------------------------\na = size(data,1);\nb = size(data,2);\nnd = myndims( data{1} );\nn  = size( data{1} ,nd);\n\n% only for paired stats\n% ---------------------\nif nd == 1\n    AB = zeros(a,b,'single');\n    AS = zeros(a,n,'single');\n    BS = zeros(b,n,'single');\n    sq = single(0);\n    for ind1 = 1:a\n        for ind2 = 1:b\n            AB(ind1,ind2) = sum(data{ind1,ind2});\n            AS(ind1,:)    = AS(ind1,:) + data{ind1,ind2}';\n            BS(ind2,:)    = BS(ind2,:) + data{ind1,ind2}';\n            sq            = sq + sum(data{ind1,ind2}.^2);\n        end;\n    end;\n    dimA = 2;\n    dimB = 1;\nelseif nd == 2\n    AB = zeros(size(data{1},1),a,b,'single');\n    AS = zeros(size(data{1},1),a,n,'single');\n    BS = zeros(size(data{1},1),b,n,'single');\n    sq = zeros(size(data{1},1),1,'single');\n    for ind1 = 1:a\n        for ind2 = 1:b\n            AB(:,ind1,ind2) = sum(data{ind1,ind2},nd);\n            AS(:,ind1,:)    = AS(:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),1,n);\n            BS(:,ind2,:)    = BS(:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),1,n);\n            sq              = sq + sum(data{ind1,ind2}.^2,nd);\n        end;\n    end;\n    dimA = 3;\n    dimB = 2;\nelseif nd == 3\n    AB = zeros(size(data{1},1),size(data{1},2),a,b,'single');\n    AS = zeros(size(data{1},1),size(data{1},2),a,n,'single');\n    BS = zeros(size(data{1},1),size(data{1},2),b,n,'single');\n    sq = zeros(size(data{1},1),size(data{1},2),'single');\n    for ind1 = 1:a\n        for ind2 = 1:b\n            AB(:,:,ind1,ind2) = sum(data{ind1,ind2},nd);\n            AS(:,:,ind1,:)    = AS(:,:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),1,n);\n            BS(:,:,ind2,:)    = BS(:,:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),1,n);\n            sq                = sq + sum(data{ind1,ind2}.^2,nd);\n        end;\n    end;\n    dimA = 4;\n    dimB = 3;\nelseif nd == 4\n    AB = zeros(size(data{1},1),size(data{1},2),size(data{1},3),a,b,'single');\n    AS = zeros(size(data{1},1),size(data{1},2),size(data{1},3),a,n,'single');\n    BS = zeros(size(data{1},1),size(data{1},2),size(data{1},3),b,n,'single');\n    sq = zeros(size(data{1},1),size(data{1},2),size(data{1},3),'single');\n    for ind1 = 1:a\n        for ind2 = 1:b\n            AB(:,:,:,ind1,ind2) = sum(data{ind1,ind2},nd);\n            AS(:,:,:,ind1,:)    = AS(:,:,:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),size(data{1},3),1,n);\n            BS(:,:,:,ind2,:)    = BS(:,:,:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),size(data{1},3),1,n);\n            sq                = sq + sum(data{ind1,ind2}.^2,nd);\n        end;\n    end;\n    dimA = 5;\n    dimB = 4;\nend;\n\nA = sum(AB,dimA); % sum across columns, so result is ax1 column vector\nB = sum(AB,dimB); % sum across rows, so result is 1xb row vector\nS = sum(AS,dimB); % sum across columns, so result is 1xs row vector\nT = sum(sum(A,dimB),dimA); % could sum either A or B or S, choice is arbitrary\n\n% degrees of freedom\ndfA = a-1;\ndfB = b-1;\ndfAB = (a-1)*(b-1);\ndfS = n-1;\ndfAS = (a-1)*(n-1);\ndfBS = (b-1)*(n-1);\ndfABS = (a-1)*(b-1)*(n-1);\n\n% bracket terms (expected value)\nexpA  = sum(A.^2,dimB)./(b*n);\nexpB  = sum(B.^2,dimA)./(a*n);\nexpAB = sum(sum(AB.^2,dimA),dimB)./n;\nexpS  = sum(S.^2,dimA)./(a*b);\nexpAS = sum(sum(AS.^2,dimB),dimA)./b;\nexpBS = sum(sum(BS.^2,dimB),dimA)./a;\nexpY  = sq; %sum(Y.^2);\nexpT  = T.^2 / (a*b*n);\n\n% sums of squares\nssA   = expA - expT;\nssB   = expB - expT;\nssAB  = expAB - expA - expB + expT;\nssS   = expS - expT;\nssAS  = expAS - expA - expS + expT;\nssBS  = expBS - expB - expS + expT;\nssABS = expY - expAB - expAS - expBS + expA + expB + expS - expT;\nssTot = expY - expT;\n\n% mean squares\nmsA   = ssA / dfA;\nmsB   = ssB / dfB;\nmsAB  = ssAB / dfAB;\nmsS   = ssS / dfS;\nmsAS  = ssAS / dfAS;\nmsBS  = ssBS / dfBS;\nmsABS = ssABS / dfABS;\n\n% f statistic\nfA = msA ./ msAS;\nfB = msB ./ msBS;\nfAB = msAB ./ msABS; \ndfApair  = [dfA dfAS];\ndfBpair  = [dfB dfBS];\ndfABpair = [dfAB dfABS];\n\nfunction val = myndims(a)\n    if ndims(a) > 2\n        val = ndims(a);\n    else\n        if size(a,1) == 1,\n            val = 2;\n        elseif size(a,2) == 1,\n            val = 1;\n        else\n            val = 2;\n        end;\n    end;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/statistics/anova2rm_cell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5601596607976922}}
{"text": "\n\n% ALIGNK  calculate kernel alignment\n%\n% [X]=ALIGNK(K1,K2) calculates alignment between kernels K1 and K2.\n\nfunction [x]=alignk(ik,ok)\n\nx=sum(sum( ik .* ok)) / sqrt(sum(sum(ik.^2)) * sum(sum(ok.^2)) );", "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/alignk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.560043571853577}}
{"text": "% Demo for distributed (locally multivariate) HRF\n\n\nclose all\nclear variables\n\n\n% Choose basic settings for simulations\nTR          = 3;                    % sampling time interval (in sec)\nn_t         = 60/TR;                % number of time samples (over 40 sec)\ndeltat      = 5e-2;                 % micro-time resolution\ndecim       = max([1,round(TR./deltat)]);\nu           = zeros(1,n_t*decim);         % input\nu(1,1)      = 1e0;\nf_fname     = @f_HRF2;               % Ballon model evolution function\ng_fname     = @g_HRF_distributed;               % Balloon model observation function\ndisp('Extracting HRF params...')\n[theta,phi] = get_HRFparams(TR,deltat);\ndisp('Done.')\nalpha       = Inf;                  % simulated state noise precision\nsigma       = 1e6;                  % simulated data noise precision\n\n% spatial observation parameters\ninG.ind_hrf = 1:length(phi);\ninG.n_reg = 1;\ninG.n_phi = 4;\ninG.B = randn(15,inG.n_phi);\nphi = [ phi\n        1\n        2\n        -1\n        -2  ];\ninG.ind_profile{1} = inG.ind_hrf(end)+1:length(phi);\n\n\n% Build priors for model inversion\npriors.muX0         = [0;0;0;0];\npriors.SigmaX0      = 0e0*eye(4);\npriors.muTheta      = 0.1*ones(length(theta),1);\npriors.SigmaTheta   = 1e0*eye(length(theta));\npriors.muPhi        = 0*ones(length(phi),1);\npriors.SigmaPhi     = 1e0*eye(length(phi));\npriors.SigmaPhi(1)  = 0;\npriors.a_alpha      = Inf;%1e6;\npriors.b_alpha      = 0;%1e2;\npriors.a_sigma      = 1e0;\npriors.b_sigma      = 1e0;\n\n% Build options and dim structures for model inversion\noptions.priors      = priors;\noptions.inF.deltat  = deltat;\noptions.inF.fullDCM = 0;\noptions.inF.linearized = 0;\noptions.inG.TE      = 0.04;\noptions.decim       = decim;\noptions.microU      = 1;\noptions.inG         = inG;\ndim.n_theta         = length(theta);\ndim.n_phi           = length(phi);\ndim.n               = 4;\n% options.checkGrads = 1;\n\n% Simulate time series of hidden states and observations\n[y,x,x0,eta,e]   = VBA_simulate (n_t,f_fname,g_fname,theta,phi,u,alpha,sigma,options);\n\n% Display simulated time series\ndisplaySimulations(y,x,eta,e);\n% disp('--paused--')\n% pause\n\n\n\n\n% Call inversion routine\n% [posterior,out] = VBA_onlineWrapper(y,u,f_fname,g_fname,dim,options);\n[posterior,out] = VBA_NLStateSpaceModel(y,u,f_fname,g_fname,dim,options);\n\n% Display inference results\ndisplayResults(posterior,out,y,x,x0,theta,phi,alpha,sigma)\n\n% Make predictions\ntry\n    options = out.options;\n    [xs,ys,xhat,vx,yhat,vy] = VBA_comparePredictions(n_t,theta,phi,u,alpha,sigma,options,posterior,dim);\ncatch\n    disp('------!!Unable to form predictions!!------')\nend\n\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/4_neural/demo_HRF_distributed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5600435678056817}}
{"text": "function Gc=leadlagc(G,Wc,Gam_c,Kv,key)\nG=tf(G); [Gai,Pha]=bode(G,Wc);\nPhi_c=sin((Gam_c-Pha-180)*pi/180);\nden=G.den{1}; a=den(length(den):-1:1);\nii=find(abs(a)<=0); num=G.num{1}; \nG_n=num(length(num));\nif length(ii)>0\n   if ii(1)>1, a=a(ii(1)+1);\n   else, a=a(ii(1)+1); end\nelse, a=a(1); end;\nalpha=sqrt((1-Phi_c)/(1+Phi_c));\nZc=alpha*Wc; Pc=Wc/alpha;\nKc=sqrt((Wc*Wc+Pc*Pc)/(Wc*Wc+Zc*Zc))/Gai;\nK1=G_n*Kc*alpha/a;\nif nargin==4, key=1;\n   if Phi_c<0, key=2;\n   else, if K1<Kv, key=3; end, end\nend\nswitch key\n   case 1, Gc=tf([1 Zc]*Kc,[1 Pc]);\n   case 2\n      Kc=1/Gai; K1=G_n*Kc/a;\n      Gc=tf([1 0.1*Wc],[1 K1*Gcn(2)/Kv]); \n   case 3\n      Zc2=Wc*0.1; Pc2=K1*Zc2/Kv;\n      Gcn=Kc*conv([1 Zc],[1,Zc2]);\n      Gcd=conv([1 Pc],[1,Pc2]); \n      Gc=tf(Gcn,Gcd);\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/2302-feedback-control-systems/xue/leadlagc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5599652251516686}}
{"text": "classdef LineSegment < handle\n    properties               \n        p1_;         \n        p2_;        \n        R_;\n        obs_;        \n        ellipsoid_;  \n        polyhedron_;\n        local_bbox_; % Bounding Box of map\n        epsilon_;   \n    end\n    methods                  \n        function obj = LineSegment(p1, p2)   \n            obj.p1_ = p1;\n            obj.p2_ = p2;\n            obj.epsilon_ = 1e-10;\n        end\n\n        function dilate(obj, radius)\n            obj.find_ellipsoid(radius);  \n            obj.find_polyhedron();       \n            obj.add_local_bbox(obj.polyhedron_); \t\t\t\t\n        end\n\n        function set_local_bbox(obj, local_bbox)\n            obj.local_bbox_ = local_bbox;\t\t\t\t\n        end\t\t\n\n        function set_obs(obj, obs)\n            Vs = Polyhedron();\n            obj.add_local_bbox(Vs);\t\t\n            obj.obs_ = Vs.points_inside(obs);\t\n        end\t\t\n\n        function add_local_bbox(obj, Vs)\n            r = norm(obj.p2_ - obj.p1_)/2;  \n            dir = (obj.p2_ - obj.p1_)/norm(obj.p2_ - obj.p1_);\n            dir_h = [dir(2) -dir(1) 0];\n            if(norm(dir_h) == 0)\n                    dir_h = [-1 0 0];  \n            end\n            dir_h = dir_h/norm(dir_h);\n\n            % along x\n            pp1 = obj.p1_ + dir_h*(r);\n            pp2 = obj.p1_ - dir_h*(r);\n            Vs.add(Hyperplane(pp1, dir_h));\n            Vs.add(Hyperplane(pp2, -dir_h));\n\n            % along y\t\t\n            pp3 = obj.p2_ + dir*(r);\n            pp4 = obj.p1_ - dir*(r);\n            Vs.add(Hyperplane(pp3, dir));\n            Vs.add(Hyperplane(pp4, -dir));\t\t\n\n            % along z, \n            dir_v = [0 0 0];\t\n            dir_v(1) =  dir(2) * dir_h(3) - dir(3) * dir_h(2);\n            dir_v(2) =  dir(3) * dir_h(1) - dir(1) * dir_h(3); \n            dir_v(3) =  dir(1) * dir_h(2) - dir(2) * dir_h(1); \n            pp5 = obj.p1_ + dir_v*(r);\n            pp6 = obj.p1_ - dir_v*(r);\n            Vs.add(Hyperplane(pp5, dir_v));\n            Vs.add(Hyperplane(pp6, -dir_v));\n        end\n\n        % 3D \n        function find_ellipsoid(obj, offset_x)\n            f = norm(obj.p1_ - obj.p2_)/2;  \n            C = [f 0 0; 0 f 0; 0 0 f];\n            % f is the radius of the ellipse, the initialized ellipse is a circle\n            % C =  [f  0  0]\t\n            %      [0  f  0]\n            %      [0  0  f]\n            \n            % h = (R^T)*x, (1 0 0)^T = R^T*(p2_ - p1_)  => (p2_ - p1_) = R*(1 0 0)^T\n            Ri = rotationMatrix([1 0 0]', (obj.p2_ - obj.p1_)');\n            C = Ri * C * (Ri');\n            axes = [f f f];\n            obj.R_ = Ri;\n\n            E = Ellipsoid(C, (obj.p1_ + obj.p2_)/2 ); \n\n            obs = E.points_inside(obj.obs_);\n            obs_inside = obs;\n\n            % decide short axes-1\n            while (~isempty(obs_inside))\n                cp = E.closest_point(obs_inside);\n                rcp = (Ri')*(cp - E.d_)';   \n\n                % Generate a new ellipse\n                if(abs(rcp(1)) < axes(1)) \n                    newy = sqrt((rcp(2))^2 + (rcp(3))^2);\n                    axes(2) = newy / sqrt(1 - (rcp(1)/axes(1))^2);\n                end\n                \n                new_C = [axes(1) 0 0; 0 axes(2) 0; 0 0 axes(2)];\n                E.setC(Ri * new_C * (Ri'));\n                \n                % Delete all the points outside the new ellipse\n                obs_new = [];\n                [len, ~] = size(obs_inside);\n                for i = 1 : len\n                % constexpr decimal_t epsilon_ = 1e-10; \n                    if(1 - E.dist(obs_inside(i,:)) > obj.epsilon_ )\n                        obs_new = [obs_new; obs_inside(i,:)];\n                    end\n                end\n                obs_inside = obs_new;\n            end\n\n            % decide short axes-2\n            C = [axes(1) 0 0; 0 axes(2) 0; 0 0 axes(3)];\n            E.setC(Ri * C * (Ri'));\n            \n            obs_inside = E.points_inside(obs);\n            while (~isempty(obs_inside))\n                cp = E.closest_point(obs_inside);\n                rcp = (Ri')*(cp - E.d_)';\n                dd = sqrt( 1 - (rcp(1)/axes(1))^2 - (rcp(2)/axes(2))^2 );\n                if(dd > obj.epsilon_)\n                    axes(3) = abs(rcp(3)) / dd;\n                end\n                \n                new_C = [axes(1) 0 0; 0 axes(2) 0; 0 0 axes(3)];\n                E.setC(Ri * new_C * (Ri'));\n                \n                % Delete all the points outside the new ellipse\n                obs_new = [];\n                [len, ~] = size(obs_inside);\n                for i = 1 : len\n                % constexpr decimal_t epsilon_ = 1e-10; \n                    if(1 - E.dist(obs_inside(i,:)) > obj.epsilon_ )\n                        obs_new = [obs_new; obs_inside(i,:)];\n                    end\n                end\n                obs_inside = obs_new;\n            end\n            \n            E.axes_ = axes;\n            obj.ellipsoid_ = E;\n            \n        end\n\n        function find_polyhedron(obj)\n            Vs = Polyhedron();\n            obs_remain = obj.obs_;\n            while(length(obs_remain))\n                plane = obj.ellipsoid_.closest_hyperplane(obs_remain);\n                Vs.add(plane);\n                obs_tmp = [];\n                [len, ~] = size(obs_remain);\n                for i = 1 : len\n                    p = obs_remain(i,:);\n                    if(plane.signed_dist(p) < 0)\n                        obs_tmp = [obs_tmp; p];\n                    end\n                end\n                obs_remain = obs_tmp;\n            end\n            obj.polyhedron_ = Vs;\n        end\n    end\nend\n", "meta": {"author": "LenaShengzhen", "repo": "AerialRobotics", "sha": "b3fe62f2df62cb91e8b5a53791868f9848c74005", "save_path": "github-repos/MATLAB/LenaShengzhen-AerialRobotics", "path": "github-repos/MATLAB/LenaShengzhen-AerialRobotics/AerialRobotics-b3fe62f2df62cb91e8b5a53791868f9848c74005/Motion_Planning/3Safe_Flight_Corridors/LineSegment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857831, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5599652251516685}}
{"text": "function R1f = computeR1(Param, R1obs)\n\nkf  = Param.kf;\nF  = Param.F;\nR1r = Param.R1r;\n\nR1f = R1obs - kf*(R1r - R1obs) / (R1r - R1obs + kf/F);\n\nend", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Common/sim/computeR1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5599652191545047}}
{"text": "function z = Parabola(x)\n    z = sum(x.^2);\nend", "meta": {"author": "TheAlgorithms", "repo": "MATLAB-Octave", "sha": "e150b77ad256de46c1ce3815c3d7945ac4fc28dc", "save_path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave", "path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave/MATLAB-Octave-e150b77ad256de46c1ce3815c3d7945ac4fc28dc/algorithms/Particle_Swarm_Optimization/Polynomial Minimization/Parabola.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5599652125430747}}
{"text": "function [fn, FnVar, FnGrad, FnGradCov, constraint, ConstraintCov, ConstraintGrad, ConstraintGradCov] = Contamination(x, runlength, seed, ~)\n% function [fn, FnVar, FnGrad, FnGradCov, constraint, ConstraintCov, ConstraintGrad, ConstraintGradCov] = Contamination(x, runlength, seed, other);\n% x is a vector containing binary var for yes/no to prevention efforts done\n% at the stage\n% runlength is the number of independent generations of simulated time\n% seed is the index of the substreams to use (integer >= 1)\n% other is not used\n% Returns cost of prevention treatment, constraint, and ConstraintCov\n% If contraints not satisfied,\n% prints comparison between probabilities that the contamination fractions are within\n% the thresholds versus the probabilities (1-epsilon) that need to be exceeded for each stage.\n%\n%Note: RandStream.setGlobalStream(stream) can only be used for Matlab\n%versions 2011 and later\n%For earlier versions, use the method RandStream.setDefaultStream(stream)\n%\n%   *************************************************************\n%   ***            Code written by Danielle Lertola           ***\n%   ***          dcl96@cornell.edu    June 25th, 2012         ***\n%   ***     Note for future update:  Example parameters need  ***\n%   ***                              to be more reasonable.   ***\n%   ***            Edited by Jennifer Shih                    ***\n%   ***          jls493@cornell.edu    June 18th, 2014        ***\n%   *************************************************************\n%\n% Last updated Jun 18, 2014\n\n\nFnVar=NaN; \nFnGrad = NaN;\nFnGradCov = NaN;\nConstraintGrad = NaN;\nConstraintGradCov = NaN;\n\nn=length(x);\nif (length(x)~=n) ||(sum(x>ones(n,1))>0) || (sum(x<zeros(n,1))>0) || (runlength <= 0) || (seed <= 0) || (round(seed) ~= seed),\n    fprintf('\\nx has %u elements, elements of x are binary, \\nrunlength should be positive and real, seed should be a positive integer.\\n',n);\n    fn = NaN;\n    constraint = NaN;\n    ConstraintCov = NaN;\nelse % main simulation\n    %% *********************PARAMETERS*********************\n    nGen=runlength;          %number of independent generations\n    u=x;                     %prevention binary decision variable\n    X=zeros(n,nGen);         %fraction contaminated at each stage for each generation\n    epsilon=.05*ones(n,1);   %error probability\n    p=.1*ones(n,1);          %proportion limit\n    cost=ones(n,1);          %cost for prevention at stage i\n    %Beta parameters for initial contamination, contamination rate,\n    %restoration rate\n    initialAlpha=1;\n    initialBeta=30;\n    contamAlpha=1;\n    contamBeta=17/3;\n    restoreAlpha=1;\n    restoreBeta=3/7;\n    \n    %% GENERATE RANDOM NUMBER STREAMS\n    % Generate new streams for\n    [InitialStream, ContaminationStream, RestorationStream] = RandStream.create('mrg32k3a', 'NumStreams', 3);\n    % Set the substream to the \"seed\"\n    InitialStream.Substream = seed;\n    ContaminationStream.Substream = seed;\n    RestorationStream.Substream = seed;\n\n    %% Generate initial fraction of contamination\n    OldStream = RandStream.setGlobalStream(InitialStream); % Temporarily store old stream, for versions 2011 and later\n    %OldStream = RandStream.setDefaultStream(InitialStream);%for versions 2010 and earlier\n    % Generate initial fraction of contamination for stage 1 for each\n    % generation\n    initialX=betarnd(initialAlpha,initialBeta,1,nGen);\n    \n    %% Generate rates of contamination\n    RandStream.setGlobalStream(ContaminationStream); %for Matlab versions 2011 and later\n    %RandStream.setDefaultStream(ContaminationStream); % for versions 2010 and earlier\n    \n    % Generate rates of contamination for each stage and generation\n    Lambda=betarnd(contamAlpha,contamBeta,n,nGen);\n    \n    %% Generate rates of restoration\n    RandStream.setGlobalStream(RestorationStream); %for Matlab versions 2011 and later\n    %RandStream.setDefaultStream(RestorationStream); %for Matlab versions 2010 and earlier\n    % Generate rates of restoration for each stage and generation\n    Gamma=betarnd(restoreAlpha,restoreBeta,n,nGen);\n    \n    RandStream.setGlobalStream(OldStream);                   % Restore old random number stream\n    %RandStream.setDefaultStream(OldStream); %for versions 2010 and earlier\n    %% Determinating fraction of contamination at each stage\n    X(1,:)=Lambda(1,:)*(1-u(1)).*(1-initialX) + (1-Gamma(1,:)*u(1)).*initialX;\n    for i= 2:n\n        X(i,:)=Lambda(i,:)*(1-u(i)).*(1-X(i-1,:)) + (1-Gamma(i,:)*u(i)).*X(i-1,:);\n    end\n\n    %mu=mean(X,2);\n    %sigma=std(X,0,2);\n    limit=1-epsilon;\n    %prob=normcdf(p,mu,sigma);\n    %cost of contamination control\n    fn=sum(cost.*u);\n    %if sum(limit>=prob)==0,\n    %    fprintf('\\nGiven starting solution all contamination fractions are less than the threshold with probability > (1-epsilon)');\n    %    fprintf('\\nSuccessful with cost %4.2f.\\n',sum(cost.*u));\n    %else\n    %    string=['\\nGiven starting solution the probability that the contamination fractions \\n'...\n    %            'are less than the threshold is <= (1-epsilon) for at least one stage.\\n' ...\n    %            'Therefore the constraints are not satisfied.\\n\\n'...\n    %            'Column 1 contains the probability that the contamination fractions are less than the threshold.\\n' ...\n    %            'Column 1 must be greater than column 2 (1-epsilon) for each stage in order for the constraint to be satsified.\\n'];\n    %    fprintf(string);\n    %    results=[prob limit]\n    %end\n    %checking probability that Xi is <=pi is less than 1-eps\n    con=zeros(n,runlength); %matrix of if Xi<pi for each trial and i\n    for j=1:runlength\n        con(:,j)= (X(:,j)<=p); \n    end\n    con=con';\n    le=sum(sum(con,2)==n);\n    constraint=zeros(1,n);\n    for k=1:n\n        constraint(k)=(sum(con(:,k))/runlength)-limit(k);\n    end\n    ConstraintCov=cov(con); \n\nend\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/ContStudy/Contamination.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5599652044444787}}
{"text": "% test the main formulation \n\naddpath('../MALSAR/c_files/largescale_ops/');\naddpath('../MALSAR/functions/pacifier/');\n\nclear; clc;\nrng(1985)\nn = 12;\nk = 40;\nd = 1000;\nt_min = 150;\nt_max = 200;\ndensity = 0.001;\n\nX0 = cell(n, 1); \nfor i = 1 : n\n    X0{i} = sprand(d, t_min + randi(t_max-t_min, 1), density);\nend\n\nreg_l1 = 1e-10;\nreg_l2 = 1e-10;\n\nreg_smooth = 10;\n\n[ U1, V1, Ss1, fv1 ] = pacifier_iba( X0, k+5, reg_l1, reg_l2, reg_smooth);\n[ U2, V2, Ss2, fv2 ] = pacifier_sba( X0, k+5, reg_l1, reg_l2, reg_smooth);\n\nfigure\nplot(fv1)\ntitle('Pacifier IBA Objective Value')\n\nfigure\nplot(fv2)\ntitle('Pacifier SBA Objective Value')", "meta": {"author": "jiayuzhou", "repo": "MALSAR", "sha": "fb9751594983df020ddc4f7e4a40520ee7c37989", "save_path": "github-repos/MATLAB/jiayuzhou-MALSAR", "path": "github-repos/MATLAB/jiayuzhou-MALSAR/MALSAR-fb9751594983df020ddc4f7e4a40520ee7c37989/examples/example_pacifier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.559959570658019}}
{"text": "% TEST_THICK_RING_G_NMNN: data function for Neumann boundary condition.\n\nfunction g = test_thick_ring_g_nmnn (x, y, z, ind)\n  [theta, r] = cart2pol (x, y);\n  switch ind\n    case 1\n      g = -cos (theta) .* exp (x) .* cos (z) .* (sin (x.*y) + y .* cos (x.*y)) -...\n            sin (theta) .* x .* exp (x) .* cos (x.*y) .* cos (z);\n    case 2\n      g = cos (theta) .* exp (x) .* cos (z) .* (sin (x.*y) + y .* cos (x.*y)) +...\n            sin (theta) .* x .* exp (x) .* cos (x.*y) .* cos (z);\n    case 3\n      g = -x .* exp (x) .* cos (x.*y) .* cos (z);\n    case 4\n      g = -exp (x) .* cos (z) .* (sin (x.*y) + y .* cos (x.*y));\n    case 5\n      g = exp (x) .* sin (x.*y) .* sin (z);\n    case 6\n      g = -exp (x) .* sin (x.*y) .* sin (z);\n    otherwise\n      error ('g_nmnn: unknown reference number');\n  end\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/examples/base/data_files/test_thick_ring_g_nmnn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5599595584226502}}
{"text": "kNum = length(prunedStates);\n\nif kNum > 0\n    p_I_G_est = zeros(3,kNum);\n    p_I_G_imu = zeros(3, kNum);\n    kPlot = zeros(1,kNum);\n\n    for k=1:kNum\n        state_k = prunedStates{k}.state_k;\n\n        C_CG = quatToRotMat(prunedStates{k}.q_CG);\n        C_CI = quatToRotMat(camera.q_CI);\n        p_I_G_est(:,k) = prunedStates{k}.p_C_G - C_CG' * C_CI * camera.p_C_I;\n        p_I_G_imu(:,k) = msckfState_imuOnly{state_k}.imuState.p_I_G;\n\n        kPlot(k) = state_k;\n    end\n\n    figure(1); clf; hold on;\n    plot3(p_I_G_est(1,:),p_I_G_est(2,:),p_I_G_est(3,:),'-b');\n    plot3(p_I_G_imu(1,:),p_I_G_imu(2,:),p_I_G_imu(3,:),'-r');\n    plot3(r_i_vk_i(1,kPlot),r_i_vk_i(2,kPlot),r_i_vk_i(3,kPlot),'-g');\n%     if ~isempty(map)\n%         scatter3(map(1,:),map(2,:),map(3,:),'or');\n%     end\n    xlabel('x');ylabel('y');zlabel('z');\n    legend('MSCKF','IMU integration','Ground Truth');\n%     legend('MSCKF','IMU integration');\n    grid on;\n    \n    drawnow;\nend", "meta": {"author": "yuzhou42", "repo": "MSCKF", "sha": "d95d90c85b24f27001bd0ecdce8739b6e602b6df", "save_path": "github-repos/MATLAB/yuzhou42-MSCKF", "path": "github-repos/MATLAB/yuzhou42-MSCKF/MSCKF-d95d90c85b24f27001bd0ecdce8739b6e602b6df/msckf/plot_traj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5599595545523234}}
{"text": "function [L, U] = factor(A, rho)\n    [m, n] = size(A);\n    if m >= n   % assuming this case is more serious in my application\n       L = chol(A'*A + rho*eye(size(A,2)), 'lower');\n    else\n       L = chol(speye(m) + 1/rho*(A*A'), 'lower');\n    end\n\n    U = L';\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u7c7b\u7b97\u6cd5/multimodal_dictionary_learning-master/factor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5599595545523233}}
{"text": "function [F] = mci_nmm_r2p2_dfdp (x,u,P,M)\n% Parameter Jacobian for two region, two parameter NMM\n% FORMAT [F] = mci_nmm_r2p2_dfdp (x,u,P,M)\n%\n% x         State\n% u         Inputs\n% P         Parameters\n% M         Model structure\n%\n% F         F(i,j) = df(x)_i/dp_j\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny and Biswa Sengupta\n% $Id: mci_nmm_r2p2_dfdp.m 6548 2015-09-11 12:39:47Z will $\n\n% 18 state variables, 2 parameters\nF=zeros(18,2);\n\ncurr_P=M.can_P; % Canonical parameter set\n\nw21=P(1);\nw12=P(2);\n\n% 2 free parameters\ncurr_P.A{1}(2,1)=P(1); % Forward connection, w_21\ncurr_P.A{2}(1,2)=P(2); % Backward connection, w_12\n\nP=curr_P;\n\n% default parameters \nE = [1 1/2 1/8]*32;         % extrinsic rates (forward, backward, lateral)\nD = [2 16];                 % propogation delays (intrinsic, extrinsic)\nH = [4 32];                 % receptor densities (excitatory, inhibitory)\nT = [8 16];                 % synaptic constants (excitatory, inhibitory)\nR = [2 1]/3;                % parameters of static nonlinearity\n\n% neuronal states into matrix form; x(r,:) for region r\nx = spm_unvec(x,M.x);       \n% extrinsic delays\nDe = D(2).*exp(P.D)/1000;                \n\n% delayed pyramidal cell activity\npyr_ext = presynaptic (x(:,9)-De*(x(:,5)-x(:,6)),P,R);  \n\nTe    = T(1)/1000*exp(P.T(:,1));         % excitatory time constants\nHe    = H(1)*exp(P.G(:,1));              % excitatory receptor density\n\nHeTe=He/Te;\n\n% Effect of forward connection on region 2 stellate cells\nF(8,1)=HeTe*pyr_ext(1)*E(1)*w21*exp(w12); \n% Effect of backward connection on region 1 pyramidal cells\nF(9,2)=HeTe*pyr_ext(2)*E(2)*w12*exp(w12); \n% Effect of backward connection on region 1 inhibitory cells\nF(15,2)=HeTe*pyr_ext(2)*E(2)*w12*exp(w12); \nend\n\nfunction [S] = presynaptic (x,P,R)\n\n% pre-synaptic inputs: s(V)\n%--------------------------------------------------------------------------\nR     = R.*exp(P.S);\nS     = 1./(1 + exp(-R(1)*(x - R(2)))) - 1./(1 + exp(R(1)*R(2)));\n\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/mci/models/nmm/mci_nmm_r2p2_dfdp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5599595506819962}}
{"text": "function D = prtDistanceHamming(x,y)\n\n\n\n\n\n\n\n\n[x,y] = prtUtilDistanceParseInputs(x,y);\n\nx = logical(x);\ny = logical(y);\n\n%%\n%tic\n%D2 = sum(bsxfun(@xor,reshape(x,[size(x,1),1,size(x,2)]),reshape(y,[1,size(y,1),size(y,2)])),3);\n%toc\n%%\nD = zeros(size(x,1),size(y,1));\n%tic\nfor iY = 1:size(y,1)\n    D(:,iY) = sum(bsxfun(@xor,x,y(iY,:)),2);\nend\n%toc\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/distance/prtDistanceHamming.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5599569898887147}}
{"text": "function [V, converged, i] = gausspf(Ybus, Sbus, V0, ref, pv, pq, mpopt)\n%GAUSSPF  Solves the power flow using a Gauss-Seidel method.\n%   [V, CONVERGED, I] = GAUSSPF(YBUS, SBUS, V0, REF, PV, PQ, MPOPT)\n%   solves for bus voltages given the full system admittance matrix (for\n%   all buses), the complex bus power injection vector (for all buses),\n%   the initial vector of complex bus voltages, and column vectors with\n%   the lists of bus indices for the swing bus, PV buses, and PQ buses,\n%   respectively. The bus voltage vector contains the set point for\n%   generator (including ref bus) buses, and the reference angle of the\n%   swing bus, as well as an initial guess for remaining magnitudes and\n%   angles. MPOPT is a MATPOWER options struct which can be used to \n%   set the termination tolerance, maximum number of iterations, and \n%   output options (see MPOPTION for details). Uses default options\n%   if this parameter is not given. Returns the final complex voltages,\n%   a flag which indicates whether it converged or not, and the number\n%   of iterations performed.\n%\n%   See also RUNPF.\n\n%   MATPOWER\n%   Copyright (c) 1996-2016, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%   and Alberto Borghetti, University of Bologna, Italy\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n%% default arguments\nif nargin < 7\n    mpopt = mpoption;\nend\n\n%% options\ntol     = mpopt.pf.tol;\nmax_it  = mpopt.pf.gs.max_it;\n\n%% initialize\nconverged = 0;\ni = 0;\nV = V0;\nVm = abs(V);\n\n%% set up indexing for updating V\nnpv = length(pv);\nnpq = length(pq);\n\n%% evaluate F(x0)\nmis = V .* conj(Ybus * V) - Sbus;\nF = [   real(mis([pv; pq]));\n        imag(mis(pq))   ];\n\n%% check tolerance\nnormF = norm(F, inf);\nif mpopt.verbose > 1\n    fprintf('\\n it    max P & Q mismatch (p.u.)');\n    fprintf('\\n----  ---------------------------');\n    fprintf('\\n%3d        %10.3e', i, normF);\nend\nif normF < tol\n    converged = 1;\n    if mpopt.verbose > 1\n        fprintf('\\nConverged!\\n');\n    end\nend\n\n%% do Gauss-Seidel iterations\nwhile (~converged && i < max_it)\n    %% update iteration counter\n    i = i + 1;\n\n    %% update voltage\n    %% at PQ buses\n    for k = pq(1:npq)'\n        V(k) =  V(k) + (conj(Sbus(k) / V(k)) - Ybus(k,:) * V ) / Ybus(k,k);\n    end\n\n    %% at PV buses\n    if npv\n        for k = pv(1:npv)'\n            Sbus(k) = real(Sbus(k)) + 1j * imag( V(k) .* conj(Ybus(k,:) * V));\n            V(k) =  V(k) + (conj(Sbus(k) / V(k)) - Ybus(k,:) * V ) / Ybus(k,k);\n%           V(k) = Vm(k) * V(k) / abs(V(k));\n        end\n        V(pv) = Vm(pv) .* V(pv) ./ abs(V(pv));\n    end\n\n    %% evalute F(x)\n    mis = V .* conj(Ybus * V) - Sbus;\n    F = [   real(mis(pv));\n            real(mis(pq));\n            imag(mis(pq))   ];\n\n    %% check for convergence\n    normF = norm(F, inf);\n    if mpopt.verbose > 1\n        fprintf('\\n%3d        %10.3e', i, normF);\n    end\n    if normF < tol\n        converged = 1;\n        if mpopt.verbose\n            fprintf('\\nGauss-Seidel power flow converged in %d iterations.\\n', i);\n        end\n    end\nend\n\nif mpopt.verbose\n    if ~converged\n        fprintf('\\nGauss-Seidel power flow did not converge in %d iterations.\\n', i);\n    end\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/gausspf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5599569850397359}}
{"text": "function pass = test_times(pref)\n\nif ( nargin == 0 )\n    pref = cheboppref();\nend\n\ndom = [-1, 1];\ndiffOp = operatorBlock.diff(dom);\nV = chebpoly(1:6);\nA = linop(diffOp);\nAV = A*V;\n\nB = linop(2*diffOp);\nBV = B*V;\n\nerr(1) = norm(2*AV - BV);\ntol = 1e-14;\npass(1) = err < tol;\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/linop/test_times.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5599569840299496}}
{"text": "% MCMCSUMM - Summary Statistics \n% Copyright (c) 1998, Harvard University. Full copyright in the file Copyright\n%\n%   [S] = mcmcsumm(A) \n%\n% A = r x c x s array of s samples of an r x c matrix of parameters\n%\n% S = structure containing returned values (mean, median, etc.)\n%   select components with S.mean, S.median, etc.\n%\n% Note: all summary statistics are marginal, there are no multivariate\n%   summaries at this time.\n%\n% These routines use the last dimension of an array as the\n% sample index.  So an array with dimension (nr,nc,ns) \n% will be a collection of ns samples of an nr by nc matrix of \n% parameters.  An array with dimension (nr,nc) will\n% be nc samples of an nr-vector of parameters.\n% When the summary statistics are calculated, the last dimension\n% is dropped.  \n% \n% See also: MCMCTRACE, MCMCLT\n%\n\nfunction [S] = mcmcsumm(A) \n\nif isnan(A),\n S.mean = NaN;\n S.min = NaN;\n S.max = NaN;\n S.std = NaN;\n S.sorted = NaN;\n S.median = NaN;\n S.meanvec = NaN;\n S.cov = NaN;\n S.acf= NaN;\n S.acf10max = NaN;\n S.acf10med = NaN;\n S.gr2 = NaN ;\n S.gr2max = NaN ;\nelse\n\ndd = size(A) ;\nll = length(dd) ;\nif (ll==2),\n  aa = reshape(A, [dd(1),1,dd(2)]) ;\nelse\n  aa = A ;\nend\n\n[nr,nc,ns] = size(aa) ;\n\nmaxlag = min(100,ns-1) ;\n\nZ = zeros(nr,nc,ns) ;\nS = struct('mean',Z) ;\n\nS.mean = mean(aa,3) ;\nS.min = min(aa,[],3) ;\nS.max = max(aa,[],3) ;\nS.std = std(aa,0,3) ;\nS.sorted = NaN*zeros(nr,nc,ns) ;\nS.median = NaN*zeros(nr,nc) ;\n\ntmpvec = reshape(S.mean, nr*nc, 1) ;\nsel = ~isnan(tmpvec) ;\nS.meanvec = tmpvec(sel,:) ;\n\naavec = reshape(aa, nr*nc, ns) ;\naavec = aavec(sel,:) ;\n\nif nr>0 & nc>0 & ns>0,  \n% then there's something to work with\n\nS.cov = cov(aavec') ;\n\nfor ir = 1:nr,\nfor ic = 1:nc,\n  xx = reshape(aa(ir,ic,:),1,ns) ;\n  S.sorted(ir,ic,:) = sort(xx) ;\n  S.median(ir,ic) = median(xx) ;\n  xx0 = xx - mean(xx) ;\n  if S.max(ir,ic)-S.min(ir,ic) < .0000000001,\n    xc = NaN * zeros(1,2*maxlag+1) ;\n  else\n    xc = xcorr(xx0,xx0,maxlag,'coeff'); \n  end \n  S.acf(ir,ic,:) = [xc(maxlag+(1:(maxlag+1)))] ;\n  S.acf1 = S.acf(:,:,2) ;\nend \nend \n\nif ns>10,\n  S.acf10 = S.acf(:,:,11) ;\n  tmpacf = reshape(S.acf10,1,nr*nc) ;\n  if any(~isnan(tmpacf)),\n    tmpacf = tmpacf(~isnan(tmpacf)) ;\n    S.acf10max = max(max( tmpacf )) ;\n    S.acf10med = median(median( tmpacf )) ;\n  else\n    S.acf10max = NaN ;\n    S.acf10med = NaN ;\n  end\nelse\n  S.acf10 = NaN*S.acf(:,:,1) ;\n  S.acf10max = NaN ;\n  S.acf10med = NaN ;\nend\n\nelse \n  % one of nr nc ns == 0\n  S.sorted(:,:,:) = A ;\n  S.median = A(:,:,1) ;\n  S.acf10max = NaN ;\n  S.acf10med = NaN ;\n  S.acf = NaN * zeros(nr,nc,maxlag+1) ;\n  S.acf1 = S.acf(:,:,2) ;\n  S.acf10 = S.acf(:,:,11) ;\n  S.cov = A(:,:,1) ;\nend\n\nS.gr2 = mcmcgr(A,2) ;\nS.gr2max = max(max(S.gr2)) ;\n\nend\n% end of NaN branch\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/198-mcmc/mcmc/mcmcsumm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.5599569776662902}}
{"text": "%% Analyzing Investment Strategies with CVaR Portfolio Optimization in MATLAB - Reality\n%\n% Robert Taylor\n% The MathWorks, Inc.\n\n% Copyright (C) 2012 The MathWorks, Inc.\n\n%% Introduction\n\n% This script illustates the simulation of a single realization for both uncovered and covered-call\n% positions on a common underlying stock price realization obtained from the file\n% |BuyWriteTestData.mat|.\n\n%% Generate a Single Realization for Uncovered and Covered-Call Scenarios\n\n% Example:\n%\tAssume data are sampled at 30-minute intervals over 22 days. Assume that a \"year\" is 252 days,\n%\tthat a \"day\" is from 09:30 to 14:00, and that a \"period\" is 30 minutes. Consequently, a \"day\"\n%\tcomprises 13 \"periods\" with 1 + 22*13 samples and the investment period is 22/252 years. Note\n%\tthat the extra sample is the initial price.\n%\n%\tX(1)\t\t\t\t40\t\t\tinitial price of stock\n%\tnumel(X)\t\t\t1 + 22*13\tinitial price plus 13 30-minute periods in a day for 22 days\n%\tT\t\t\t\t\t22/252\t\tinvestment period has 22 days with 252 days in a year\n%\tvolatility\t\t\t0.35\t\t35% volatility\n%\n%\tinitial_equity\t\t1000000\t\t$1 million initial equity invested in stock (25000 shares)\n%\tdistribution\t\t0.10\t\t10% per year distribution\n%\n%\toption_expiration\t45/252\t\toption expiration in 45 days\n%\trisk_free_rate\t\t0.0015\t\t0.15% risk-free rate\n%\tstrike_cushion\t\t0.05\t\t5% strike price \"cushion\"\n%\texercise_likelihood 0.2\t\t\tprobability of exercise if stock price >= strike price\n\n%\tstock_cost\t\t\t0.06\t\t5 c/share txcost + 1 c/share spread\n%\toption_cost\t\t\t0.20\t\t20 c/option contract\n\n%\tconfirmation_delay\t2\t\t\t1 hour delay to confirm option assignment\n%\treinvestment_delay\t1*13\t\t1 day to reinvest after confirmation of assignment\n%\tsettlement_delay\t3*13\t\t3 days to settle after reinvestment\n\n% fund details\n\ndistribution = 0.10;\n\n% initial number of shares invested in stock\n\ninitial_holdings = 25000;\t\t\t% initial number of shares\n\n% investment period\n%\tperiodicity is 30-minute periods, 13 periods in a day, 252 days in a year\n\nT = 22/252;\t\t\t\t\t\t\t% duration of investment period is 22 days\nN = 22*13;\t\t\t\t\t\t\t% 22 days x 13 30-minute periods in a day\n\n% stock information\n\nload BuyWriteTestData X\t\t\t\t% realization of asset total return prices X\n\ninitial_price = X(1);\t\t\t\t% initial price\nmu = 0.10;\t\t\t\t\t\t\t% stock drift\nvolatility = 0.35;\t\t\t\t\t% stock volatility\n\ninitial_equity = initial_holdings*initial_price;\n\n% option information\n\ncontract_expiration = 45/252;\t\t% option contract expiration (45 days)\nnext_contract_expiration = 112/252;\t% next option contract expiration (112 days)\nrisk_free_rate = 0.0015;\t\t\t% risk-free rate\nstrike_cushion = 0.05;\t\t\t\t% strike price \"cushion\"\n% exercise_likelihood = NaN;\t\t% period probability of exercise if stock price >= strike price\nexercise_likelihood = 0.9;\t\t\t% period probability of exercise if stock price >= strike price\n\n% costs/frictions\n\nstock_cost = 0.06;\t\t\t\t\t% 5 c/share txcost + 1 c/share spread\ncontract_cost = 0.20;\t\t\t\t% 20 c/option contract + 2 c/option contract spread\n\n% delays\n\nconfirmation_delay = 2;\t\t\t\t% 1 hour delay to confirm option assignment\nreinvestment_delay = 1*13;\t\t\t% 1 day to reinvest after confirmation of assignment\nsettlement_delay = 3*13;\t\t\t% 3 days to settle after reinvestment\n\nno_reinvestment = false;\t\t\t% true if reinvestment not allowed in an investment period\n% no_reinvestment = true;\t\t\t% true if reinvestment not allowed in an investment period\ncovered_vs_uncovered = false;\n\n% simulate scenarios\n\n[rU, WU, CU, HU] = uncovered_engine(X, T, ...\n\tinitial_equity, distribution, risk_free_rate, stock_cost);\n\n[rC, WC, CC, HC, KC] = covered_engine(X, T, mu, volatility, ...\n\tinitial_equity, distribution, no_reinvestment, covered_vs_uncovered, ...\n\tstrike_cushion, contract_expiration, next_contract_expiration, risk_free_rate, ...\n\tstock_cost, contract_cost, exercise_likelihood, ...\n\tconfirmation_delay, reinvestment_delay, settlement_delay);\n\nfprintf('Scenario total returns ...\\n');\nfprintf('  Uncovered  %10.4f  Total return for uncovered strategy\\n',rU);\nfprintf('  Covered    %10.4f  Total return for covered strategy\\n',rC);\n\nfprintf('Mean of total returns ...\\n');\nfprintf('  Uncovered  %10.4f\\n',N*mean(tick2ret(WU)));\nfprintf('  Covered    %10.4f\\n',N*mean(tick2ret(WC)));\n\nfprintf('Standard deviation of total returns ...\\n');\nfprintf('  Uncovered  %10.4f\\n',sqrt(N)*std(tick2ret(WU)));\nfprintf('  Covered    %10.4f\\n',sqrt(N)*std(tick2ret(WC)));\n\nfprintf('Maximum drawdown of total returns ...\\n');\nfprintf('  Uncovered  %10.4f\\n',maxdrawdown(WU));\nfprintf('  Covered    %10.4f\\n',maxdrawdown(WC));\n\n%% Plot Results\n\nt = linspace(0, T*252, N+1);\n\nsubplot(2,2,1);\nplot(t, [WC/WC(1), WU/WU(1)]);\ntitle('\\bfTotal Wealth');\nxlabel('Day');\nylabel('Dollars (Millions)');\nh = legend('Covered', 'Uncovered', 'Location', 'SouthEast');\nset(h, 'FontSize', 7, 'Box', 'off');\n\nsubplot(2,2,2);\nplot(t, 1.0e-6*CC);\ntitle('\\bfCash');\nxlabel('Day');\nylabel('Dollars (Millions)');\n\nsubplot(2,2,3);\nplot(t, 1.0e-3*HC);\ntitle('\\bfShares');\nxlabel('Day');\nylabel('Shares (Thousands)');\n\nsubplot(2,2,4);\nplot(t, KC);\ntitle('\\bfStrike Price');\nxlabel('Day');\nylabel('Dollars');\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39449-analyzing-investment-strategies-with-cvar-portfolio-optimization/cvarwebinar_reality.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5599569733222061}}
{"text": "function [nstate] = tapas_mh_mc3_hier_node_sample(data, model, ...\n    inference, state, node)\n%% Samples for a particular node assuming there is a function for it. \n%\n%\n% This works as the conditional independency of the level allows one to sample\n% without worrying about the values in other nodes.\n%\n% aponteeduardo@gmail.com\n% copyright (C) 2016\n%\n\nnstate = state;\n\n% Theta is a data object\ntheta = inference.mh_sampler{node}.propose_sample(data, model, inference, ...\n    state, node);\n\ny = state.graph{node - 1};\n\nnllh = model.graph{node - 1}.llh(y, theta, model.graph{node-  1}.htheta);\nnlpp = model.graph{node}.llh(theta, state.graph{node + 1}, ...\n    model.graph{node}.htheta);\n\n[v] = inference.mh_sampler{node}.ar_rule(state.llh{node - 1}, ...\n    state.llh{node}, nllh, nlpp, 0, model.graph{node - 1}.htheta.T);\n\nnstate.graph{node}.y(:, v) = theta.y(:, v);\nnstate.llh{node - 1}(:, v) = nllh(:, v);\nnstate.llh{node}(:, v) = nlpp(:, v);\n\nnstate.nsample = state.nsample + 1;\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/tools/ti/tapas_mh_mc3_hier_sample_node.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5599569674634408}}
{"text": "function [beta_gibbs F_gibbs L_gibbs phi_gibbs sigma_gibbs lambda_t_gibbs sigma_t_gibbs sbar]=stvol3gibbs(Xbart,Xt,yt,B0,phi0,alpha0,delta0,f0,upsilon0,betahat,sigmahat,gamma,G,I_o,omega,T,n,k,It,Bu,pick,pickf)\n\n\n\n\n% preliminary elements for the algorithm\n% compute the product G'*I_gamma*G (to speed up computations of deltabar)\nGIG=G'*I_o*G;\n% compute alphabar\nalphabar=T+alpha0;\n\n\n\n% initiate the Gibbs sampler\n% initiate the counting of iterations\ncount=1;\npickcount=1;\n% initiate the record matrices and cells\nbeta_gibbs=[];\nF_gibbs=[];\nL_gibbs=[];\nphi_gibbs=[];\nsigma_gibbs=[];\nlambda_t_gibbs={};\nsigma_t_gibbs={};\n\n\n\n% step 1: determine initial values for the algorithm\n\n% initial value for beta\nbeta=betahat;\nB=reshape(beta,k,n);\n% initial value for f_2,...,f_n\n% obtain the triangular factorisation of sigmahat\n[Fhat Lambdahat]=bear.triangf(sigmahat);\n% obtain the initial value for F\nF=Fhat;\n% obtain the inverse of Fhat\n[invFhat]=bear.invltod(Fhat,n);\n% create the cell storing the different vectors of invF\nFinv=cell(n,1);\n% store the vectors\nfor ii=2:n\nFinv{ii,1}=invFhat(ii,1:ii-1);\nend\n% initial values for L\nL=zeros(T,1);\n% initial values for phi\nphi=1;\n\n\n\n% step 2: determine the sbar values and Lambda\nsbar=diag(Lambdahat);\nLambda=sparse(diag(sbar));\n% then determine sigma^(0)\nsigma=F*Lambda*F';\n\n\n% step 3: recover the series of initial values for lambda_1,...,lambda_T and sigma_1,...,sigma_T\nlambda_t=repmat(diag(sbar),1,1,T);\nsigma_t=repmat(sigmahat,1,1,T);\n\nhbar = bear.parfor_progressbar(It,'Progress of the Gibbs sampler');  %create the progress bar\n\n\n% run the Gibbs sampler\nwhile count<=It\n\n   hbar.iterate(1);   % update progress by one iteration\n\n\n% step 4: draw beta from its conditional posterior\n% first compute the summations required for omegabar and betabar\nsumm1=zeros(k,k);\nsumm2=zeros(k,n);\n   % run the summation\n   for jj=1:T\n   prodt=Xt{jj,1}'*exp(-L(jj,1));\n   summ1=summ1+prodt*Xt{jj,1};\n   summ2=summ2+prodt*yt(:,:,jj)';\n   end\n% then obtain the inverse of phi0\ninvphi0=diag(1./diag(phi0));\n% obtain the inverse of phibar\ninvphibar=summ1+invphi0;\n% recover phibar\nC=chol(bear.nspd(invphibar),'Lower')';\ninvC=C\\speye(k);\nphibar=invC*invC';\n% recover Bbar\nBbar=phibar*(summ2+invphi0*B0);\n% draw B from its posterior\nB=bear.matrixndraw(Bbar,sigma,phibar,k,n);\n% finally recover beta by vectorising\nbeta=B(:);\n\n\n% step 5: draw the series f_2,...,f_n from their conditional posteriors\n   % recover first the residuals\n   for jj=1:T\n   epst(:,:,jj)=yt(:,:,jj)-Xbart{jj,1}*beta;\n   end\n   % then draw the vectors in turn\n   for jj=2:n\n   % first compute the summations required for upsilonbar and fbar\n   summ1=zeros(jj-1,jj-1);\n   summ2=zeros(jj-1,1);\n      % run the summation\n      for kk=1:T\n      prodt=epst(1:jj-1,1,kk)*exp(-L(kk,1));\n      summ1=summ1+prodt*epst(1:jj-1,1,kk)';\n      summ2=summ2+prodt*epst(jj,1,kk)';\n      end\n   summ1=(1/sbar(jj,1))*summ1;\n   summ2=(-1/sbar(jj,1))*summ2;\n   % then obtain the inverse of upsilon0\n   invupsilon0=diag(1./diag(upsilon0{jj,1}));\n   % obtain upsilonbar\n   invupsilonbar=summ1+invupsilon0;\n   C=chol(bear.nspd(invupsilonbar));\n   invC=C\\speye(jj-1);\n   upsilonbar=full(invC*invC');\n   % recover fbar\n   fbar=upsilonbar*(summ2+invupsilon0*f0{jj,1});\n   % finally draw f_i^(-1)\n   Finv{jj,1}=fbar+chol(bear.nspd(upsilonbar),'lower')*randn(jj-1,1);\n   end\n% recover the inverse of F\ninvF=eye(n);\n   for jj=2:n\n   invF(jj,1:jj-1)=Finv{jj,1};\n   end\n% eventually recover F\nF=bear.invltod(invF,n);\n% update sigma\nsigma=F*Lambda*F';\n\n\n% step 6: draw phi from its conditional posterior\n% estimate deltabar\ndeltabar=L'*GIG*L+delta0;\n% draw the value phi_i\nphi=bear.igrandn(alphabar/2,deltabar/2);\n\n\n% step 7: draw the series lambda_t from their conditional posteriors, t=1,...,T\n   % consider periods in turn\n   for kk=1:T\n   % a candidate value will be drawn from N(lambdabar,phibar)\n   % the definitions of lambdabar and phibar varies with the period, thus define them first\n      % if the period is the first period\n      if kk==1\n      lambdabar=(gamma*L(2,1))/(1/omega+gamma^2);\n      phibar=phi/(1/omega+gamma^2);\n      % if the period is the final period\n      elseif kk==T\n      lambdabar=gamma*L(T-1,1);\n      phibar=phi;\n      % if the period is any period in-between\n      else\n      lambdabar=(gamma/(1+gamma^2))*(L(kk-1,1)+L(kk+1,1));\n      phibar=phi/(1+gamma^2);\n      end\n   % now draw the candidate\n   cand=lambdabar+phibar^0.5*randn;\n   % compute the acceptance probability\n   prob=bear.mhprob3(cand,L(kk,1),sbar,epst(:,1,kk),Finv,n);\n   % draw a uniform random number\n   draw=rand;\n      % keep the candidate if the draw value is lower than the prob\n      if draw<=prob\n      L(kk,1)=cand;\n      % if not, just keep the former value\n      end\n   end\n% then recover the series of matrices lambda_t and sigma_t\nfor kk=1:T\nlambda_t(:,:,kk)=exp(L(kk,1))*diag(sbar);\nsigma_t(:,:,kk)=F*lambda_t(:,:,kk)*F';\nend\n\n\n\n\n% record phase\n   % if the burn-in sample phase is not yet over\n   if count<=Bu\n   % simply add 1 to the iteration count\n   count=count+1;\n   % on the other hand, if the burn-in sample phase is over\n   elseif count>Bu\n   % adding one iteration to the count will depend on wether post-burn selection applies\n      % if there is no post burn selection\n      if pick==0\n      % record the results\n      beta_gibbs(:,count-Bu)=beta;\n      F_gibbs(:,:,count-Bu)=F;\n      L_gibbs(:,:,count-Bu)=L;\n      phi_gibbs(count-Bu,1)=phi;\n      sigma_gibbs(:,count-Bu)=sigma(:);\n         for jj=1:T\n         lambda_t_gibbs{jj,1}(:,:,count-Bu)=lambda_t(:,:,jj);\n         sigma_t_gibbs{jj,1}(:,:,count-Bu)=sigma_t(:,:,jj);\n         end  \n      % then add one to the count\n      count=count+1;\n      % if there is post burn selection, only one draw over 'fpick' draws will be retained\n      elseif pick==1\n         % if the iteration does not correspond to fpick, don't record the results, don't increase the regular count, but do increase pickcount by 1, and do record the acceptance rate of the Metropolis-Hastings step\n         if pickcount~=pickf\n         pickcount=pickcount+1;\n         % on the other hand, if the iteration does correspond to fpick\n         elseif pickcount==pickf\n         % do record the results\n         beta_gibbs(:,count-Bu)=beta;\n         F_gibbs(:,:,count-Bu)=F;\n         L_gibbs(:,:,count-Bu)=L;\n         phi_gibbs(count-Bu,1)=phi;\n         sigma_gibbs(:,count-Bu)=sigma(:);\n            for jj=1:T\n            lambda_t_gibbs{jj,1}(:,:,count-Bu)=lambda_t(:,:,jj);\n            sigma_t_gibbs{jj,1}(:,:,count-Bu)=sigma_t(:,:,jj);\n            end\n         % then increase the regular count by 1 and re-initialise pickcount\n         count=count+1;\n         pickcount=1;\n         end\n      end\n   end\n\n\nend\n\n\nclose(hbar);   %close progress bar\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/stvol3gibbs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5599486668320672}}
{"text": "% The observation function:\n%               \n%               function [F] = g_CaBBI(Xt,Phi,I_inp,inG)\n%\n% this function maps [Ca2+] kinetics to fluorescence observations (F) \n% through a non-linear saturating function\n\n\nfunction [F] = g_CaBBI(Xt,Phi,I_inp,inG)\n\nind = inG.ind;                 \nCa = Xt(ind);                        % [Ca2+] kinetics\nd_F =  Phi(1);                       % offset parameter\nKd =  200;                           % dissociation constant\nscale = inG.k_F0*exp(Phi(2));        % scale paraemeter\nF =  scale*(Ca/(Ca + Kd)) + d_F;     % nonlinear mapping from [Ca2+] to F\n\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/demos/_models/g_CaBBI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5599486565485587}}
{"text": "classdef CEC2017_F2 < PROBLEM\n% <single> <real> <constrained>\n% CEC'2017 constrained optimization benchmark problem\n\n%------------------------------- Reference --------------------------------\n% G. Wu, R. Mallipeddi, and P. N. Suganthan, Problem definitions and\n% evaluation criteria for the CEC 2017 competition on constrained real-\n% parameter optimization, National University of Defense Technology, China,\n% 2016.\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        O;      % Optimal decision vector\n        Mat;\t% Rotation matrix\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2017.mat'),'Data');\n            obj.O = Data{2}.o;\n            obj.M = 1;\n            if isempty(obj.D) || obj.D < 30\n                obj.D   = 10;\n                obj.Mat = Data{2}.M_10;\n            elseif obj.D < 50\n                obj.D   = 30;\n                obj.Mat = Data{2}.M_30;\n            elseif obj.D < 100\n                obj.D   = 50;\n                obj.Mat = Data{2}.M_50;\n            else\n                obj.D   = 100;\n                obj.Mat = Data{2}.M_100;\n            end\n            obj.lower    = zeros(1,obj.D) - 100;\n            obj.upper    = zeros(1,obj.D) + 100;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopObj = sum(cumsum(Z,2).^2,2);\n        end\n        %% Calculate constraint violations\n        function PopCon = CalCon(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            Y = Z*obj.Mat';\n            PopCon = sum(Y.^2-5000*cos(0.1*pi*Y)-4000,2);\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/Single-objective optimization/CEC 2017/CEC2017_F2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5599486504068063}}
{"text": "function [curImage,phImage] = mrThreshPhVol(samp,sampSize,volco,volph,volume,sagSize,numSlices,x,y,dataRange)\n%\n%\n% PURPOSE:\n%   Compute an image whose pixel values show the best phase angle of\n%   the time series at each image point.\n%   \n%\n% AUTHOR:  Engel\n%\n%\n\n% Variable Declarations\nthr = [];\t\t\t% Vector of 1s and 0s.  1 means co > thresh\n\t\t\t\t% 0 means co <= thresh.  \nglobal interpflag volslicut volslimin1 volslimax1;\n\nif isempty(volco)\n   disp ('Correlation data is not available.');\n   return\nend\n\nif (interpflag)\n\tsinIm = mrExtractImgVol(sin(volph),sagSize,dataRange(2)-dataRange(1)+1,samp,dataRange);\n\tcosIm = mrExtractImgVol(cos(volph),sagSize,dataRange(2)-dataRange(1)+1,samp,dataRange);\n\tphImage = atan2(sinIm,cosIm);\nelse\n\tphImage = mrExtractImgVol(volph,sagSize,dataRange(2)-dataRange(1)+1,samp,dataRange);\nend\nphImage = phImage;\n\ncurImage = mrExtractImgVol(volume,sagSize,numSlices,samp);\n\nco = mrExtractImgVol(volco,sagSize,dataRange(2)-dataRange(1)+1,samp,dataRange);\n\ncutoff = get(volslicut,'value');\ndisp(['Cutoff = ',num2str(cutoff)]);\nthr = co > cutoff;\ncurImage(thr) = -((phImage(thr)+pi)/(2*pi)*110);\t%Scale negatives for colors\n\nmyShowImageVol(curImage,sampSize,max(curImage)*get(volslimin1,'value'),max(curImage)*get(volslimax1,'value'),x,y);\n\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/mrAlign/volume/mrThreshPhVol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5599486401232975}}
{"text": "function [mPerc, mProb] =calc_zlta(mCat0,mCat1,mCat2,fTstart,fT,fTw,nTbin,nN)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Example: mLTA=calc_zlta(mCat00,mCat20,params.fTstart, fT,fTw,nTbin, nN);\n%\n% This function calculates the rate changes (z-value) of earthquake\n% occurrencs between two periods. This function calculates rate changes for\n% all the grid nodes together. Input is either a single vector or a whole\n% matrix columnswise only with dates (not the whole catalog). Output is the\n% z(lta)- and its probability value for each grid point.\n%\n% Author: van Stiphout, Thomas\n% Email: vanstiphout@sed.ethz.ch\n% Created: 7. Aug. 2007\n% Changed: 14. Aug.2007\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Variables:\n% mCat0          Catalog complete (only origin time)\n% mCat1          Catalog period 1 (vector or matrix with yrs in column)\n% mCat2          Catalog period 2 (vector or matrix with yrs in column)\n% fTstart        Begin of time period 1\n% fT             Date for which rate change is calculated\n% fTw            Length of Time window of second period\n% nTbin          Length of Time steps for histogram\n% nN             Sampling volume\n%\n% Output:\n% mLTA           Scalar or vector with beta values for each input column\n% mProb          Scalar or vector with probability for beta values for each\n%                input column. The probability is either calculated based\n%                on a synthetic catalog or a real-like catalog.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% disp('~/zmap/src/thomas/seismicrates/calc_zlta.m');\n% probability calculation based on synthetic catalogs.\n% Synthetic catalogs either based catalog with uniform rates (o) or according to\n% complete catalog (1)\nbSyn=logical(0);\n\n% calculate histogram for different time periods\n% nSteps=floor((fT-fTstart)/(nTbin/365));\n% vR1=histc(mCat1,  fTstart:(nTbin/365):fTstart+nSteps*(nTbin/365)  );\nvR1=histc(mCat1,fTstart : nTbin/365 : fT-fTw,1);\nvR1=vR1(1:end-1,:);\n\n% vR1=histc(mCat1,fTimeStart:fTimeSteps/365:fTimeCut+fTimeWindow);\nvR2=histc(mCat2,fT-fTw : nTbin/365:fT,1);\nvR2=vR2(1:end-1,:);\n\n\n% calculate the mean rate for different periods\nmean1=mean(vR1);\nmean2=mean(vR2);\n\n\nvar1 = var(vR1);\nvar2 = var(vR2);\n\nif isempty(vR1)\n    disp('Warning - Time Period 1 is without any event');\nelseif isempty(vR2)\n    disp('Warning - Time Period 2 is without any event');\nend\n\n% create synthetic catalogs to extimate significance level\n% reset random number generator\nrand('state',sum(100*clock));\nif bSyn\n    vPos=ceil(rand(nN,1000).*size(mCat0,1));\n    mSyn1=mCat0(vPos);\n else\n    mSyn1=rand(nN,1000)*(fT-fTstart)+fTstart;\nend\n% apply histogram to synthetic catalog\nvS1=histc(mSyn1,fTstart : nTbin/365 : fT-fTw,1);\nvS1=vS1(1:end-1,:);\nvS2=histc(mSyn1,fT-fTw : nTbin/365:fT,1);\nvS2=vS2(1:end-1,:);\n% calculate the mean rate for different periods in synthetic catalog\nmSynMean1=mean(vS1);\nmSynMean2=mean(vS2);\n% calculate z(lta) values for synthetic catalog\nmSynPerc=(mSynMean2./mSynMean1.*100)-100;\n% calculate values for normal distribution\n% [jbt(i), jbp(i)]=jbtest(mSynLTA);\n% llt(i)=lillietest(mSynLTA);\n[mu,s] = normfit(mSynPerc);\n\n% z(lta)\nmPerc=(mean2./mean1.*100)-100;\n% calculate the probability of z(lta)-values\n[mProb] = 1-normpdf(mPerc,mu,s);\n% figure;plot(mLTA,mProb,'.');\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/thomas/seismicrates/calc_perc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5599461752392538}}
{"text": "function [regression_label] = fast_rcnn_bbox_transform(ex_boxes, gt_boxes)\n% [regression_label] = fast_rcnn_bbox_transform(ex_boxes, gt_boxes)\n% --------------------------------------------------------\n% Fast R-CNN\n% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)\n% Copyright (c) 2015, Shaoqing Ren\n% Licensed under The MIT License [see LICENSE for details]\n% --------------------------------------------------------\n\n    ex_widths = ex_boxes(:, 3) - ex_boxes(:, 1) + 1;\n    ex_heights = ex_boxes(:, 4) - ex_boxes(:, 2) + 1;\n    ex_ctr_x = ex_boxes(:, 1) + 0.5 * (ex_widths - 1);\n    ex_ctr_y = ex_boxes(:, 2) + 0.5 * (ex_heights - 1);\n    \n    gt_widths = gt_boxes(:, 3) - gt_boxes(:, 1) + 1;\n    gt_heights = gt_boxes(:, 4) - gt_boxes(:, 2) + 1;\n    gt_ctr_x = gt_boxes(:, 1) + 0.5 * (gt_widths - 1);\n    gt_ctr_y = gt_boxes(:, 2) + 0.5 * (gt_heights - 1);\n    \n    targets_dx = (gt_ctr_x - ex_ctr_x) ./ (ex_widths+eps);\n    targets_dy = (gt_ctr_y - ex_ctr_y) ./ (ex_heights+eps);\n    targets_dw = log(gt_widths ./ ex_widths);\n    targets_dh = log(gt_heights ./ ex_heights);\n    \n    regression_label = [targets_dx, targets_dy, targets_dw, targets_dh];\nend", "meta": {"author": "ShaoqingRen", "repo": "faster_rcnn", "sha": "49ad0990512a5d6e34f56e3c6596eb5fbf22f651", "save_path": "github-repos/MATLAB/ShaoqingRen-faster_rcnn", "path": "github-repos/MATLAB/ShaoqingRen-faster_rcnn/faster_rcnn-49ad0990512a5d6e34f56e3c6596eb5fbf22f651/functions/fast_rcnn/fast_rcnn_bbox_transform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5599461647373926}}
{"text": "function blas1_s_test09 ( )\n\n%*****************************************************************************80\n%\n%% TEST09 tests SROT.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    09 May 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 6;\n\n  for i = 1 : n\n    x(i) = i;\n  end\n\n  for i = 1 : n\n    y(i) = i * i - 12;\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST09\\n' );\n  fprintf ( 1, '  SROT carries out a Givens rotation.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  X and Y\\n' );\n  fprintf ( 1, '\\n' );\n  for i = 1 : n\n    fprintf ( 1, '  %6d  %12f  %12f\\n', i, x(i), y(i) );\n  end\n\n  c = 0.5;\n  s = sqrt ( 1.0 - c * c );\n  [ x, y ] = srot ( n, x, 1, y, 1, c, s );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  SROT ( N, X, 1, Y, 1, %f, %f )\\n', c, s );\n  fprintf ( 1, '\\n' );\n  for i = 1 : n\n    fprintf ( 1, '  %6d  %12f  %12f\\n', i, x(i), y(i) );\n  end\n\n  for i = 1 : n\n    x(i) = i;\n  end\n\n  for i = 1 : n\n    y(i) = i * i - 12;\n  end\n\n  c = x(1) / sqrt ( x(1) * x(1) + y(1) * y(1) );\n  s = y(1) / sqrt ( x(1) * x(1) + y(1) * y(1) );\n  [ x, y ] = srot ( n, x, 1, y, 1, c, s );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  SROT ( N, X, 1, Y, 1, %f, %f )\\n', c, s );\n  fprintf ( 1, '\\n' );\n  for i = 1 : n\n    fprintf ( 1, '  %6d  %12f  %12f\\n', i, x(i), y(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/blas1_s/blas1_s_test09.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5599355216691027}}
{"text": "function cvt_test02 ( )\n\n%*****************************************************************************80\n%\n%% CVT_TEST02 repeats test 1, but uses twice as many iterations.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    08 November 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST02\\n' );\n  fprintf ( 1, '  CVT computes a Centroidal Voronoi Tessellation.\\n' );\n  fprintf ( 1, '  Repeat test 1, but with twice the number of iterations.\\n' );\n\n  dim_num = 2;\n  n = 10;\n  batch = 1000;\n  init = 0;\n  init_string = 'uniform';\n  it_max = 80;\n  it_fixed = 1;\n  sample = 0;\n  sample_num = 10000;\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  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_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5599355216691027}}
{"text": "function a = reduce_rows(a);\n% function a = reduce_rows(a);\n% reduction of inequalities of the form A*x <= b where a = [A,b] due to redundancies\n%   Input:  a ... matrix of size m x n\n%   Output: a ... matrix of size ... x n\n%   (c) Sebastian Siegel, created: 2005/06/08, last modified: 2005/07/06\n\n[m,n] = size(a);\na = sortrows(a);\t% sort rows according to 1., 2., 3., ... column (ascending)\n\t\t\t% purpose: \"normalize\" according to first column later\n\n% before actually reducing similar rows, let's also check if there are similarities that differ by a factor (therefore \"normalize\")\n\nnneg = sum(a(:,1)<0);\t% count negative entries in first column\nnzer = sum(a(:,1)==0);\t% count zero entries in first column\nnpos = sum(a(:,1)>0);\t% count positive entries in first column\n\na = [a a]; % purpose: will work on \"normalized\" a and original a\n% divide according to entries in first column (if not zero):\na(1:nneg,1:n) = a(1:nneg,1:n)./-(a(1:nneg,1)*ones(1,n)); % the negative part\na(nneg+nzer+1:m,1:n) = a(nneg+nzer+1:m,1:n)./(a(nneg+nzer+1:m,1)*ones(1,n)); % the positive part\n% now a(:,1:n) is \"normalized\" and a(:,n+1:2*n) is still the original a\n\n% sort according to \"normalized\" a\na = sortrows(a,1:n);\n\n% delete similar rows (according to a(:,1:n-1)) => (save the min value of b):\nnsimilar = sum(sum((a(1:m-1,1:n-1) == a(2:m,1:n-1)),2)==n-1); % ...\n% (a(1:m-1,1:n-1) == a(2:m,1:n-1)) ... similar neighbored rows (disregard \n%    column n which represents b) will produce [1 1 1 ...], other have entries with '0'\n% sum( expression above ,2) ... add entries in a row\n% expression above == n-1 ... test if all entries in a row were 1 \n% sum( expression above ) ... get the number of similar rows\nif nsimilar > 0, % true if redundant rows exist\n\ta(:,n+1:2*n)=a(:,n+1:2*n).*([1;(1-(sum((a(1:m-1,1:n-1) == ...\n\t    a(2:m,1:n-1)),2)==n-1))]*ones(1,n)); % ...\n\t% [1;(1-(sum((a(1:m-1,1:n-1) == a(2:m,1:n-1)),2)==n-1))] ... column vector\n\t%      where each '0' represents a row which is similar to the one above\n\t% ( expression above *ones(1,n)) ... expand column vector to matrix where\n\t%      each row consists of the same entries\n\t% a(:,n+1:2*n).* expression above ... now each redundant row has entries with %      zeros only in the right half of a\n\ta = sortrows(a(:,n+1:2*n)); % sort rows according to n+1., n+2., n+3., ... \n\t%      column (ascending) of a and save result to a \n\t%      (now a has only n columns again)\n\t[temp,position]= max(sum(a==zeros(m,n),2)==n); % ...\n\t% find position of the first redundant row\n\ta = [a(1:position-1,:); a(position+nsimilar:m,:)]; % assemble a without\n\t%      redundant rows\nelse\n\ta = a(:,n+1:2*n); % reduce a to original part (right half)\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/7957-fourier-motzkin-elimination/fourmotz/reduce_rows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5599355180423091}}
{"text": "function fact_test ( )\n\n%*****************************************************************************80\n%\n%% FACT_TEST tests the use of the MEX file FACT.F\n%\n%  Discussion:\n%\n%    The file fact.F is a FORTRAN77 function which computes the factorial.\n%\n%    This M file \"compiles\" fact.F, and then shows how it can be called.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 September 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'FACT_TEST\\n' );\n  fprintf ( 1, '  MATLAB version\\n' );\n  fprintf ( 1, '  Demonstrate a simple use of the MEX compiler,\\n' );\n  fprintf ( 1, '  which allows MATLAB to call FORTRAN77 functions.\\n' );\n  \n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Get a directory listing.  The file \"fact.F\" should,\\n' );\n  fprintf ( 1, '  show up here.\\n' );\n\n  ls\n  \n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Compile the file \"fact.F\".\\n' );\n\n  mex fact.F\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Get a directory listing.  A new file should show up,\\n' );\n  fprintf ( 1, '  containing the compiled information.\\n' );\n\n  ls\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Now use FACT as though it were a MATLAB M-file function.\\n' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '   N  (N Factorial)' );\n  fprintf ( 1, '\\n' );\n\n  for i = 1 : 10\n\n    j = fact ( i );\n\n    fprintf ( 1, '  %2d  %10d\\n', i, j );\n\n  end\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'FACT_TEST:\\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/matlab_calls_f77/fact_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.5599355085446538}}
{"text": "function [hp] = kW2hp(kW)\n% Convert power from kilowatts to mechanical horsepower.\n% Chad A. Greene 2012\nhp = kW*1.34102209;\n", "meta": {"author": "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/kW2hp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5599355060398944}}
{"text": "function [Model, Info] = linear_map_sparse_cov(X,Y,Model,parm)\n%  Estimate linear weight matrix for input-output mapping\n%     Automatic Relevance Prior for each input dimension\n%     is imposed to get sparse weight matrix\n%\n%   [Model, Info] = linear_map_sparse_cov(X,Y,Model,parm)\n%\n% --- Input\n%  X  : Input data  ( M x T )\n%  Y  : Output data ( N x T )\n%  N  =  # of output\n%  M  =  # of input\n%  T  =  # of data\n%\n%  Model : Structure for estimated model\n%  Model.SY0 :  Output data variance                 ( 1 x 1 )\n%  Model.A0  :  (Output data var)/(Input data var)   ( 1 x 1 )\n%\n%  parm  : Structure for learning parameter\n%  parm.Ntrain :  # of training\n%  parm.Nskip  :  skip # for print\n%  parm.a_min  :  Min value for pruning small variance component\n%  parm.Prune  :  = 1 : Prune small variance & irrelevant input dimension\n%\n% --- Output\n%  Model : Structure for estimated model\n%  Model.SY  :  Noise variance         ( 1 x 1 )\n%  Model.SW  :  Weight variance        ( M x M )\n%  Model.W   :  Weight matrix          ( N x M )\n%  Model.A   :  Prior weight variance  ( N x M ) ARD hyper parameter\n%\n%  Info  : Structure for learning process history\n%  Info.FE  = LP + H : Free energy\n%  Info.LP  = - (Log error)\n%  Info.H   = - (# of effective weight parameters)\n%\n% 2007/1/26 Made by M. Sato\n\n% Constants\nMINVAL  = 1.0e-15;\nMinCond = 1.0e-10;\n\n% # of total training iteration\nNtrain = parm.Ntrain;\n\nNskip  = 100;   % skip steps for display info\na_min  = 1e-10; % Minimum value for weight pruning\nFdiff  = 1e-10; % Threshold for convergence\nNcheck = 100;   % Minimum number of training iteration\nFstep  = 5;     % Free energy convergence check step\nPrune  = 1;     % Prune mode\n\nif isfield(parm,'Nskip'), Nskip  = parm.Nskip; end;\nif isfield(parm,'Fdiff'), Fdiff   = parm.Fdiff; end;\nif isfield(parm,'a_min'), a_min   = parm.a_min ; end;\nif isfield(parm,'Prune'), Prune = parm.Prune; end;\nif isfield(parm,'Ncheck'), Ncheck = parm.Ncheck; end\nif isfield(parm,'Fstep'),Fstep  = parm.Fstep ; end\n\n% # of embedding dimension\nif isfield(parm,'Dtau')\n\tD    = parm.Dtau; \n\ttau  = parm.Tau;\nelse\n\tD    = 1;\n\ttau  = 1;\nend\n\n% Dimension\n[M ,Tx ,Nx ]= size(X); % input dim\n[N ,Ty ,Ny ]= size(Y); % output dim\n\nif Nx~=Ny, error('Trial number is different for input & output'); end\nif Tx~=Ty, error('Time sample is different for input & output'); end\n\n% Reshape into 2D matrix\nT = Tx*Nx; % # of data\nX = reshape(X, [M T]);\nY = reshape(Y, [N T]);\n\n% # of stable VB-update in initial training\nif isfield(parm,'Npre_train')\n\tNpre_train = parm.Npre_train;\nelse\n\tNpre_train = Ntrain;\nend\nif Npre_train > Ntrain, Npre_train = Ntrain; end;\n\nfprintf('linear map sparse covariance start\\n')\nif 0 % hacked TH111005\n    fprintf('--- Output Dimension  = %d\\n',N)\n    fprintf('--- Input  Dimension  = %d\\n',M)\n    fprintf('--- Embedding  Dimension  = %d\\n',D)\n    fprintf('--- Number of trials  = %d\\n',Nx)\n    fprintf('--- Number of training sample = %d\\n',Tx)\n    fprintf('--- Total update iteration    = %d (%d)\\n',Ntrain,Npre_train)\nelse\n    fprintf('---O:%d/I:%d/E:%d/Nt:%d/Ns:%d/Ti:%d(%d)/\\n',N,M,D,Nx,Tx,Ntrain,Npre_train)\nend\n%  \n% --- Initialization\n%  A  : Initial variable to use 1st update\n%     : 1 x M\n\n% Input/Output variance\nsx = mean(repadd(X, - mean(X,2)).^2, 2);\nsy = mean(repadd(Y, - mean(Y,2)).^2, 2);\n\nA0  = 1./mean(sx);\nSY0 = mean(sy);\n\nif isempty(Model)\n\tA   = repmat(A0, [1,M]);\n\tW   = zeros(N,M);\n\tSY  = SY0;\nelse\n\tA   = Model.A ;\t % 1 x M\n\tW   = Model.W ;  % N x M\n\tSY  = mean(Model.SY);  % 1 x 1\nend\n\nif isfield(parm,'Ta0') && parm.Ta0 > 0,\n\tTa0 = parm.Ta0;\n\ta0  = parm.a0 * A0;\nelse\n\tTa0 = 0;\n\ta0  = 1;\nend\n\n%  --- Initialization by other method ---\n% Model.mode = 'scalar': ARD term = alpha * W^2 \n% Model.mode = 'cov'   : ARD term = alpha * W^2 * SY(^-1) \n%\nif isfield(Model, 'mode') &&  strcmp(Model.mode,'scalar')==1,\n\tfprintf('Old result is used as initial value\\n')\n\tfprintf('Old method = %s\\n', Model.method)\n\tA  = sum(A,1)./(sum(SY));\nend\n\nA = max(A,MINVAL);\n\n% Original input dimension\nM_ALL = M;\n\nif isfield(Model,'ix_act')\n\t% Active index\n\tIX_act = Model.ix_act;\n\n\tX = X(IX_act,:); \t% M x T\n\tM = length(IX_act);\nelse\n\tIX_act = 1:M;\nend\n\n% Initial active index\nM_all  = M;\nA_all  = A/max(A) ;\nix_act_old = 1:M;\n\nix_act = find( A_all > a_min );   % effective indices\nMnew   = length(ix_act);  \t\t% # of effective input\n\nif Mnew < M,\n    % convert to relative index\n    jx_act = trans_index(ix_act,ix_act_old,M_all);\n    \n    M   = Mnew;\n    A   = A(jx_act) ;  \t\t\t% 1 x M\n    W   = W(:,jx_act) ;  \t\t% N x M\n\tX \t= X(jx_act,:);\t\t\t% M x T\nend\n\n% Input covariance\n%XX  = (X * X')/T;   \t% M x M\n%YX  = (Y * X')/T;       % N x M\n%YY  = sum(Y.^2,2)/T;    % N x 1\n\n% Covariance matrix (not normalised)\nYX  = (Y * X');       % N x M\nYY  = sum(Y.^2,2);    % N x 1\n\nif 0 % hacked TH111005\nfprintf('a_min = %g\\n', a_min)\nfprintf('SY0   = %g\\n', SY0)\nfprintf('SY    = %g\\n', SY)\nend\n% Working variable\nif T <= M\n\tXX = []; \n\tCC = zeros(T,T);\n\tSW = zeros(T,T);\nelse\n\tXX = (X * X');   \t  % M x M\n\tCC = zeros(M,M);\n\tSW = zeros(M,M);\nend\n\nG_A = zeros(1,M);       % 1 x M\nlog_a = 0;\nA_old = A;\n\n% Free energy histry\nFE  = zeros(Ntrain,1);\nLP  = zeros(Ntrain,1);\nH   = zeros(Ntrain,1);\nMM  = zeros(Ntrain,1);\nErr = zeros(Ntrain,1);\n\n% ARD hyper param. history\nif isfield(parm,'Debug') & ~isempty(parm.Debug) & parm.Debug > 0\n\tDebug = 1;\n\tA_tmp = zeros(M_all, ceil(Ntrain/Nskip));\nelse\n\tDebug = 0;\nend\n\nk_save  = 0;\n\n%%%%%% Learning Loop %%%%%%\nfor k=1:Ntrain\n\t% ARD hyper variance parameter\n\t% A = 1/alpha\n\n\tif T < M\n\t    % Weight variance\n\t    % inv(X*X' + 1./A) = A - A * X * inv(X'*A*X + 1) * X' * A\n\t\t%  C = ( X' *A* X + eye(T) );  \n\t\tXA = repmultiply(X' , A); % T x M\n\t    CC = XA * X + eye(T);  % T x T\n\t\t\n\t\t% Weight update\n\t    % inv(X*X' + 1./A) = A - A * X * Cinv * X' * A\n\t\t% W0 = YX .* A;\n\t\t% W  = W0 - (((W0 * X) * Cinv) * X') .* A;\n\t\t% W  = W0 - ((W0 * X) / C ) * XA;\n\t\tW  = repmultiply(YX , A);\n\t\tXC = X / CC;\n\t\tW  = W - (W * XC) * XA;\n\t\t\n\t\t%  G_A = diag( X * inv(C) * X' *A )\n\t\t%      = diag( (X / C) * X') .*A \n\t\tG_A  = A .* sum(X .* XC, 2)';\n\t\t\n\t\t% Log variance\n\t\tlog_sw  = - log_det(CC) ;\n\t\tif mod(k, Nskip)==0, fprintf('- '); end\n\telse\n\t\tif isempty(XX)\n\t\t\t% covariance matrix in reduced space\n\t\t\tXX = X * X';\n\t\t\t% save original index\n\t\t\tIX_act = IX_act(ix_act);\n\t\t\t% new active index in reduced space\n\t\t\tix_act = 1:M;\n\t\t\tM_all  = M;\n\t\t\tA_all  = A;\n\t\tend\n\t\t\n\t\t% Weight covariance\n    \tSW  = XX + diag(1./A);\n\t\t\n\t\t% Weight update\n\t\tW  = YX / SW;\n\t\t\n\t\t% SW  = XX + diag(1./A)\n\t\t% G_A = diag( XX * inv(SW))\n\t\t%     = 1 - diag(inv(SW)) ./A\n\t\tG_A = diag( XX /SW )';\n\t\t\n\t\tlog_sw  = - log_det(SW) - sum(log(A));\n\t\tif mod(k, Nskip)==0, fprintf('+ '); end\n\tend\n\t\n\tWW = sum(W.^2, 1);\n    % Noise variance update\n    SY = (sum(YY) - sum(sum(W.*YX)))/(N*T);\n    \n    if (SY/SY0) <= MINVAL,\n\t    % Error\n\t    dY  = Y - W * X;        % N x T\n\t    dYY = sum(dY.^2, 2);  \t% N x 1\n\t\n\t    SY  = (sum(dYY) + sum( WW./A ))/(N*T);\n\t    % Prevent zero variance\n\t    SY  = max( SY, MINVAL);\n\t    fprintf('*')\n\tend\n\t\n\t% Log variance\n    log_sy  = N * log(SY) ;\n    \n    if Ta0 > 0,\n\t    log_a   = Ta0 * sum( - log(A./a0) - a0./A + 1);\n\tend\n\t\n    % Free energy\n    H(k)   =   0.5*N * (log_sw - M);\n    LP(k)  = - 0.5*(T * log_sy) ;\n    FE(k)  = LP(k) + H(k);\n    Err(k) = (SY)./(SY0);\n    MM(k)  = M;\n\n    % Estimation Gain\n    %jx_act = find(G_A > a_min);\n    G_A = max((G_A), MINVAL);\n\n    % Hyper parameter for weight variance (ARD)\n\tif k <= Npre_train,\n\t\t% VB update rule\n\t\t% N * A  = (1./SY)' * (W.^2) + N * (A - A.*G_A)  ; \n\t\t% A  = (WW./SY + N * (A - A.*G_A) + 2*Ta0*a0)./( N + 2*Ta0 );\n\t\t% A^2 = A .* (WW./SY) ./ (G_A * N);\t\n        try % modified by TH130111\n            A2=A;\n            A  = sqrt(A.*(WW./SY)./(G_A * N));\n        catch\n            A=A2;\n        end\n\telse\n\t    % Accelerated update rule\n\t\t%\tA  = (1./SY)' * (W.^2) ./ (G_A * N);\t\n\t    A  = ((WW./SY) + 2*Ta0*a0)./(G_A * N + 2*Ta0);\n\tend\n\t\n    % Prune small variance\n    if Prune == 1\n\t    % Find active input dimension\n\t    ix_act_old = ix_act;\n\t    \n\t    % Recover all component\n\t    switch\tPrune\n\t    case\t1\n\t\t    A_all(ix_act) = WW/max(WW);    % Prune by Weight\n\t    case\t2\n\t\t    A_all(ix_act) = A /max(A);\t   % Prune by Alpha\n\t    case\t3\n\t\t    A_all(ix_act) = A * (1/SX);    % Prune by Alpha\n\t    end\n\t    \n\t    % Find active input dimension (absolute index)\n\t    ix_act = find( A_all > a_min ); % effective indices\n\t    Mnew   = length(ix_act);  \t\t% # of effective input\n\t    \n\t    if Mnew < M,\n\t\t    % convert to relative index\n\t\t    jx_act = trans_index(ix_act,ix_act_old,M_all);\n\t\t    \n\t\t    M   = Mnew;\n\t\t    A   = A(jx_act) ;  \t\t\t% 1 x M\n\t\t    W   = W(:,jx_act) ;  \t\t% N x M\n\t\t\tX \t= X(jx_act,:);\t\t\t% M x T\n\t\t\tYX  = YX(:,jx_act);  \t \t% N x M\n\t\t\tif ~isempty(XX)\n\t\t\t\tXX\t= XX(jx_act,jx_act);\t% M x M\n\t\t\tend\n\t\tend\n\telse\n\t\tA = max(A,MINVAL);\n    end\n\n    if mod(k, Nskip)==0\n        % Save history\n\t\tif Debug == 1\n        \tk_save = k_save + 1;\n        \tA_tmp(:,k_save) = A_all(:);\n\t\tend\n\t\t\n        fprintf('Iter = %4d, M = %4d, err = %g, F = %g, H = %g\\n', ...\n               k, M, Err(k), FE(k), - H(k));\n    end\n\n\tif k > Ncheck && M == MM(k-1)\n\t\tAdif = max(abs(A - A_old));\n\telse\n\t\tAdif = 1;\n\tend\n\tif Adif < Fdiff, \n\t\tfprintf('Converged : Alpha change = %g\\n',Adif)\n\t\tbreak; \n\tend;\n\t\n\tA_old = A;\n\t\n%\t\tFdif = (FE(k) - FE(k-Fstep))/abs(FE(k));\n%\telse\n%\t\tFdif = Fdiff + 1;\n%\tend\nend\n\n% convert to relative index\nix_act = IX_act(ix_act);\n\n% Active index\nModel.ix_act = ix_act;\nModel.M_all  = M_ALL ;\n\n% Save trained variable\n%  W & A is sufficient for cov-method initialization\nModel.A  = A ;\nModel.W  = W ;\nModel.SY = SY;\n\nModel.method = 'linear_map_sparse_cov';\nModel.mode   = 'cov';\nModel.sparse = 'sparse';\n\n% Save history\nInfo.FE  = FE(1:k);\nInfo.LP  = LP(1:k);\nInfo.H   = H(1:k) ;\nInfo.Err = Err(1:k);\nInfo.M   = MM(1:k);\n\nif exist('A_tmp','var')\n\tInfo.A   = A_tmp(:,1:k_save) ;\nend\n\n\n%%% ---- Index transformation from old active_index to current active_index\nfunction\tjx = trans_index(ix,ix_old,M)\n% ix = ix_old(jx)\n\nN = length(ix_old);\nItrans = zeros(M,1);\nItrans(ix_old) = 1:N;\n\njx = Itrans(ix);\n", "meta": {"author": "KamitaniLab", "repo": "GenericObjectDecoding", "sha": "c98f24370668109fd9978bc8b43a33bd43926f47", "save_path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding", "path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding/GenericObjectDecoding-c98f24370668109fd9978bc8b43a33bd43926f47/code/matlab/lib/SPR_2009_12_17/linear_map_sparse_cov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5598874223719847}}
{"text": "function [COU, FA_STD, ADC_STD] = wild_bootstrapping_DTI( I, bval, Mask, Nreps, DT, VectorField )\n% WILD_BOOTSTRAPPING_DTI Returns uncertainty measures from diffusion tensor\n% images via wild bootstrapping. See Whitcher 2008 - Using the Wild \n% Bootstrap to Quantify Uncertainty in Diffusion Tensor Imaging\n%\n%\n% Inputs:\n%\n%   I is the input image, of any dimensionality, with the diffusion \n%   scans in the last dimension\n%     \n%   BVAL is the b-matrix, of size [3 3 N] (same as in fit_DT)\n%\n%   MASK is the mask of voxels for analysis, same size as the first N-1\n%   dimensions of I. \n%\n%   NREPS is the number of Monte Carlo repetitions (default 1000)\n%\n%   DT and VectorField are optional - if you have a ground truth that you\n%   want to compare against, instead of the input signal.\n%\n% Outputs:\n%\n%   COU is the cone of uncertainty (in degrees) (See Jones 2003 - \n%   Determining and Visualizing Uncertainty in Estimates of Fiber \n%   Orientation From Diffusion Tensor MRI). Here, the 95th percentile is\n%   returned. The COU of the second and third eigenvectors is concatenated\n%   in the last dimension.\n%\n%   FA_STD is the standard deviation of the fractional anisotropy over \n%   the repetitions\n%\n%   ADC_STD is the standard deviation of the ADC over the repetitions\n    \n% Author: Darryl McClymont <darryl.mcclymont@gmail.com>\n% Copyright \ufffd 2014 University of Oxford\n% Version: 0.1.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 <http://www.gnu.org/licenses/>.\n\n% check arguments\nnarginchk(2,6);\nnargoutchk(0, 3);\n\nsz = size(I);\n\nif nargin < 3\n    Mask = ones(sz(1:end-1));\nend\n\nif nargin < 4\n    Nreps = 1000;\nend\n\n\n% save memory and time by fitting in vector form\nI = reshape(I, [prod(sz(1:end-1)), sz(end)]);\n\nif isscalar(Mask)\n    Mask = I(:,1) >= Mask;\nend\n\n    \nIvector = I(Mask(:), :);\n\n% if we haven't been given a ground truth, fit the tensor\nif nargin < 5\n    [DT, ~, ~, VectorField, ~] = fit_DT(Ivector, bval);\nend\n\n% Model fitted image\nIfit = dt2image(DT, bval);\n% Residuals\nResids = Ivector - Ifit;\n\n% DT_reps = zeros([size(DT), Nreps]);\n% FA_reps = zeros([size(FA), Nreps]);\n% ADC_reps = zeros([size(ADC), Nreps]);\n% VectorField_reps = zeros([size(VectorField), Nreps]);\n% EigVals_reps = zeros([size(EigVals), Nreps]);\n\n\n\n% for N iterations, randomly multiply the residuals by 1 or -1 and compute\n% parameters\nfor n = Nreps:-1:1\n    if rem(n, 10) == 0 \n        fprintf('%d, ', n);\n    end\n    \n    % either 1 or -1, with 50% probability each (Rademacher)\n    F = rand(size(Resids)) > 0.5;\n    F = F * 2 - 1;\n\n    Resids_to_add = Resids .* F;\n\n    Inew = Ifit + Resids_to_add;\n\n    [~, FA2, ADC2, VectorField2, ~] = fit_DT(Inew, bval);\n    \n    VectorField2 = real(VectorField2);\n    \n    %DT_reps(:,:,n) = DT2;\n    FA_reps(:,1,n) = FA2;\n    ADC_reps(:,1,n) = ADC2;\n    VectorField_reps(:,:,:,n) = VectorField2;\n    %EigVals_reps(:,:,n) = EigVals2;\n    \nend\n\nfprintf('done.\\n')\n\nFA_STD = zeros(size(Mask));\nFA_STD(Mask) = std(FA_reps, [], 3);\n\nADC_STD = zeros(size(Mask));\nADC_STD(Mask) = std(ADC_reps, [], 3);\n\n\n% angle between original data and bootstrapped data\nAngle_deviation_primary = zeros(size(FA_reps));\nAngle_deviation_secondary = zeros(size(FA_reps));\nAngle_deviation_tertiary = zeros(size(FA_reps));\n\nfor n = 1:Nreps\n    % primary eigenvectors\n    v1 = real(squeeze(VectorField(:,:,1)));\n    v2 = real(squeeze(VectorField_reps(:,:,1,n)));\n    \n    % ensure unit magnitude\n    v1 = bsxfun(@rdivide, v1, sqrt(sum(v1.^2, 2))+eps);\n    v2 = bsxfun(@rdivide, v2, sqrt(sum(v2.^2, 2))+eps);\n    \n    theta = dot(v1, v2, 2);\n    Angle_deviation_primary(:,1,n) = acos(theta) / pi * 180;\n    \n    % secondary eigenvectors\n    v1 = real(squeeze(VectorField(:,:,2)));\n    v2 = real(squeeze(VectorField_reps(:,:,2,n)));\n    \n    % ensure unit magnitude\n    v1 = bsxfun(@rdivide, v1, sqrt(sum(v1.^2, 2))+eps);\n    v2 = bsxfun(@rdivide, v2, sqrt(sum(v2.^2, 2))+eps);\n    \n    theta = dot(v1, v2, 2);\n    Angle_deviation_secondary(:,1,n) = acos(theta) / pi * 180;\n    \n    % tertiary eigenvectors\n    v1 = real(squeeze(VectorField(:,:,3)));\n    v2 = real(squeeze(VectorField_reps(:,:,3,n)));\n    \n    % ensure unit magnitude\n    v1 = bsxfun(@rdivide, v1, sqrt(sum(v1.^2, 2))+eps);\n    v2 = bsxfun(@rdivide, v2, sqrt(sum(v2.^2, 2))+eps);\n    \n    theta = dot(v1, v2, 2);\n    Angle_deviation_tertiary(:,1,n) = acos(theta) / pi * 180;\n    \n    \nend\n\n% bigger than 90 degrees? flip it over\nAngle_deviation_primary(Angle_deviation_primary > 90) = 180 - Angle_deviation_primary(Angle_deviation_primary > 90);\nAngle_deviation_secondary(Angle_deviation_secondary > 90) = 180 - Angle_deviation_secondary(Angle_deviation_secondary > 90);\nAngle_deviation_tertiary(Angle_deviation_tertiary > 90) = 180 - Angle_deviation_tertiary(Angle_deviation_tertiary > 90);\n\n% 95th percentile\nCOU_primary = zeros(size(Mask));\nCOU_primary(Mask) = prctile(Angle_deviation_primary, 95, 3);\nCOU_secondary = zeros(size(Mask));\nCOU_secondary(Mask) = prctile(Angle_deviation_secondary, 95, 3);\nCOU_tertiary = zeros(size(Mask));\nCOU_tertiary(Mask) = prctile(Angle_deviation_tertiary, 95, 3);\n\nn = ndims(COU_primary);\nif (n == 2) && (size(COU_primary,2) == 1), n = 1; end % ndims gives a vector 2\n\nCOU = cat(n+1, COU_primary, COU_secondary, COU_tertiary);\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/DiffusionMRIToolbox/wild_bootstrapping_DTI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5598874207389242}}
{"text": "function [MPa] = hPa2MPa(hPa)\n% Convert pressure from hectopascals to megapascals.\n% Chad Greene 2012\nMPa = hPa*0.000100000;", "meta": {"author": "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/hPa2MPa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006919830720203, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5598874040511905}}
{"text": "function b = cc_mv ( m, n, ncc, icc, ccc, acc, x )\n\n%*****************************************************************************80\n%\n%% CC_MV multiplies a CC matrix by a vector\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    14 July 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Iain Duff, Roger Grimes, John Lewis,\n%    User's Guide for the Harwell-Boeing Sparse Matrix Collection,\n%    October 1992\n%\n%  Parameters:\n%\n%    Input, integer M, the number of rows.\n%\n%    Input, integer N, the number of columns.\n%\n%    Input, integer NCC, the number of CC values.\n%\n%    Input, integer ICC(NCC), the CC rows.\n%\n%    Input, integer CCC(N+1), the compressed CC columns\n%\n%    Input, real ACC(NCC), the CC values.\n%\n%    Input, real X(N), the vector to be multiplied.\n%\n%    Output, real B(M), the product A*X.\n%\n  b = zeros(m,1);\n\n  for j = 1 : n\n    for k = ccc(j) : ccc(j+1) - 1\n      i = icc(k);\n      b(i) = b(i) + acc(k) * 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/cc_io/cc_mv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.559871526287421}}
{"text": "% Examples employing logarithms, exponentials, and entropy functions\n%\n%  max_entropy.m                    - Entropy maximization\n%  sparse_covariance_est.m          - Sparse covariance estimation for Gaussian variables\n%  sparse_covariance_est_tradeoff.m - Sparse covariance estimation for Gaussian variables\n%  weighted_analytic_center.m       - Weighted analytic center of a set of linear inequalities\nhelp Contents\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/log_exp/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5597800552684075}}
{"text": "function out = TreatData(data,treat,vnames,dates,DatesOpt)\n% =======================================================================\n% Treat data.\n% =======================================================================\n% [nobs, dates] = CountDate(fo_year,lo_year,frequency,fo_period,lo_period)\n% -----------------------------------------------------------------------\n% INPUT\n%\t- data: structure where the the data is stored\n%\t- treat: vector (of length N) with type of treatment\n%\t- vnames: vector (of length N) with variable names\n% -----------------------------------------------------------------------\n% OUTPUT\n%\t- out: matrix of treated data\n% =======================================================================\n% Ambrogio Cesa Bianchi, March 2015\n% ambrogio.cesabianchi@gmail.com\n\n% Retrieve some parameters\nnobs = DatesOpt.nobs;\nfo_year = DatesOpt.fo_year;\nlo_year = DatesOpt.lo_year;\nfrequency = DatesOpt.frequency;\nfo_period = DatesOpt.fo_period;\nlo_period = DatesOpt.lo_period;\n\n% Get first\nif strcmp(frequency,'y')\n    aux = num2str(fo_year);\nelse\n    aux = [num2str(fo_year) frequency num2str(fo_period)];\nend\nfo = find(strcmp(aux,dates));\n\n% Get last\nif strcmp(frequency,'y')\n    aux = num2str(lo_year);\nelse\n    aux = [num2str(lo_year) frequency num2str(lo_period)];\nend\nlo = find(strcmp(aux,dates));\n\n% Initialize matrix \nnvar = length(vnames);\nout = nan(nobs,nvar);\n\nfor ii=1:nvar\n    % No treatment\n    if treat(ii)==0\n        out(:,ii) = data.(vnames{ii})(fo:lo);\n    % Log\n    elseif treat(ii)==1\n        out(:,ii) = log(data.(vnames{ii})(fo:lo));\n    % Log-diff\n    elseif treat(ii)==2\n        out(:,ii) = XoX(data.(vnames{ii})(fo:lo),1,'logdiff');\n    % Diff\n    elseif treat(ii)==3\n        out(:,ii) = XoX(data.(vnames{ii})(fo:lo),1,'diff');\n    end\nend", "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/Utils/TreatData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5597623156504935}}
{"text": "function [lat, lon, azi, rk] = cassini_inv(lat0, lon0, x, y, ellipsoid)\n%CASSINI_INV  Inverse Cassini-Soldner projection\n%\n%   [LAT, LON] = CASSINI_INV(LAT0, LON0, X, Y)\n%   [LAT, LON, AZI, RK] = CASSINI_INV(LAT0, LON0, X, Y, ELLIPSOID)\n%\n%   performs the inverse Cassini-Soldner projection of points (X,Y) to\n%   (LAT,LON) using (LAT0,LON0) as the center of projection.  These input\n%   arguments can be scalars or arrays of equal size.  The ELLIPSOID vector\n%   is of the form [a, e], where a is the equatorial radius in meters, e is\n%   the eccentricity.  If ellipsoid is omitted, the WGS84 ellipsoid (more\n%   precisely, the value returned by DEFAULTELLIPSOID) is used.  GEODPROJ\n%   defines the projection and gives the restrictions on the allowed ranges\n%   of the arguments.  The forward projection is given by CASSINI_FWD.\n%\n%   AZI and RK give metric properties of the projection at (LAT,LON); AZI\n%   is the azimuth of the easting (X) direction and RK is the reciprocal of\n%   the northing (Y) scale.  The scale in the easting direction is 1.\n%\n%   LAT0, LON0, LAT, LON, AZI are in degrees.  The projected coordinates X,\n%   Y are in meters (more precisely the units used for the equatorial\n%   radius).  RK is dimensionless.\n%\n%   This routine depends on the MATLAB File Exchange package \"Geodesics on\n%   an ellipsoid of revolution\":\n%\n%     http://www.mathworks.com/matlabcentral/fileexchange/39108\n%\n%   See also GEODPROJ, CASSINI_FWD, GEODRECKON, DEFAULTELLIPSOID.\n\n% Copyright (c) Charles Karney (2012) <charles@karney.com>.\n%\n% This file was distributed with GeographicLib 1.29.\n\n  if nargin < 4, error('Too few input arguments'), end\n  if nargin < 5, ellipsoid = defaultellipsoid; end\n  try\n    [~] = lat0 + lon0 + x + y;\n  catch err\n    error('lat0, lon0, x, y have incompatible sizes')\n  end\n\n  [lat1, lon1, azi0] = geodreckon(lat0, lon0, y, 0, ellipsoid);\n  [lat, lon, azi, ~, ~, rk] = ...\n      geodreckon(lat1, lon1, x, azi0 + 90, ellipsoid);\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/39366-geodesic-projections-for-an-ellipsoid/geographiclib-matlab/cassini_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5597200430619638}}
{"text": "function [B, Y] = compressSELVE(X, SELVEparam)\n%function Y = compressSELVE(X, Anchor, lambda, s, sigma, tempResults)\n\nAnchor = SELVEparam.anchor;\ns = SELVEparam.s;\nlambda = SELVEparam.lambda;\nsigma = SELVEparam.sigma;\ntempResults = SELVEparam.tempResults;\n\n[n,dim] = size(X);\nm = size(Anchor,1);\n\n%% get Z\nZ = zeros(n,m);\nDis = sqdist(X',Anchor');\nclear X;\nclear Anchor;\n\nval = zeros(n,s);\npos = val;\nfor i = 1:s\n    [val(:,i),pos(:,i)] = min(Dis,[],2);\n    tep = (pos(:,i)-1)*n+[1:n]';\n    Dis(tep) = 1e60;\nend\nclear Dis;\nclear tep;\nval = exp(-val/(1/1*sigma^2));\nval = repmat(sum(val,2).^-1,1,s).*val; %% normalize\ntep = (pos-1)*n+repmat([1:n]',1,s);\nZ([tep]) = [val];\nZ = sparse(Z);\nclear tep;\nclear val;\nclear pos;\nlamda1 = sum(Z);\nZ = diag(lamda1.^-0.5)*Z'; %Z : fea * ins\nZ = Z';\n\ntempS = tempResults.T*Z' + repmat(tempResults.beta,1,size(Z,1));\nY = double(tempS > repmat(tempResults.Ui,1,n));\nY = Y';\nB = compactbit(Y);\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/Method-SELVE/compressSELVE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.5597200311926325}}
{"text": "%% Trend-Cycle tutorial: dating turning  points and computing cyclical statistics\n% Authors:   Filippo Ferroni and  Fabio Canova\n% Date:     27/05/2020, revised  15/12/2020\n\nclose all; clc; clear all;\n\naddpath ../../cmintools/\naddpath ../../bvartools/\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% this program illustrates the use of BB program to  date  turning  points\n% and  compute business cycle statistics\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%% exercises  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%  exercise 1: Vary the censoring  rules.\n%  exercise 2: Use  a  shorter  sample. Do  the  turning  points  coincide?\n%  exercise 3: Change  the  thresh  parameter.\n%  exercise 4: Change  the  data  set.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%=======================================================================\n% LOAD DATA\n%=======================================================================\nlload=0; % =0 euro data, =1 US data\n\nif lload==0\n    % Euro area AWM DATABASE: Quarterly\n    [a,b,~] = xlsread('awm19up18');\n    % names of variables\n    varnames = b(1,2:end);\n    \n    % time convention: Q1 = .00 and Q4 =0.75\n    time = 1970 : .25 : 2017.75;\n    time_start   = find(time==1970.50);\n    time_start1  = find(time==1999.50);\n    time_end     = find(time==2017.75);\n    time_break   = find(time==2007.75);\n    \n    % The  CREDIT DATA: Quartely\n    [e,f,~]=xlsread('ECB_Credit_gaps.xlsx');\n    varnames2= f(1,2:end);\n    \n    % real GDP, real consumption, real  investment, GDP defl, HICP,\n    % short and long term interest rate, commodity  prices,\n    % labor  productivity, total  employment, credit to NFC to  GDP\n    yy = [a(:,1) a(:,2) a(:,4) a(:,7) a(:,19) a(:,33) a(:,34) ...\n        a(:,35) a(:,42) a(:,29) e(time_start-2:time_end,25)];\n    % names: YER PCR ITR YED HICP STN LTN COMPR LPROD LNN\n    \n    % data transformations:\n    % 1. the log of output, consumption,investment\n    ddata(:,1:3) = log(yy(time_start+1 : time_end,1:3));\n    % 2. the log/log difference of GDP deflator index and CPI\n    %ddata(:,4:5) = log(yy(time_start+1  : time_end,4:5));\n    ddata(:,4:5) = diff(log(yy(time_start : time_end,4:5)))*400;\n    % 3. the level of short and long term interest rate\n    ddata(:,6:7) = yy(time_start +1 : time_end,6:7);\n    % 4. the log/log difference of commodity prices\n    ddata(:,8) = log(yy(time_start+1  : time_end,8));\n    %ddata(:,8) = diff(log(yy(time_start : time_end,8)))*400;\n    % 5. the taking the log of labor  productivity and  employment\n    ddata(:,9:10) = log(yy(time_start+1 : time_end,9:10));\n    %ddata(:,9) = diff(log(yy(time_start+1 : time_end,9)));\n    %ddata(:,10) = log(yy(time_start+1 : time_end,10));\n    \n    %  data for  credit  to  GDP starts  only  at  time_start1 (1999:25)\n    ddata(:,11) = yy(time_start+1:time_end,11);\n    endd=length(ddata);\n    \n    % pick log output, log consumption, log  investment, log labor\n    % productivity, log employment, interest rate, inflation rate\n    ddd=ddata(:,[1 2 3 9 10 6 5]);\n    T=length(ddd);\n    time_data = time(time_start+1:time_end);\n    \nelse\n    \n    % US DATABASE: Quarterly\n    \n    % real GDP, urate, real consumption, gdp defl, real  investment,\n    % capacity utilization, call rate, 10y goverment  bond  rate\n    % names: RGDP, URATE, C, GDPdef, inv, capU, callrate, 10ygbond\n    [c,d,~] = xlsread('USdata.xlsx');\n    % names of variables\n    varnames = d(1,2:end);\n    \n    % time convention: Q1 = .00 and Q4 =0.75\n    time = 1969.75 : .25 : 2019.50;\n    time_start   = find(time==1970.25);\n    time_end     = find(time==2019.50);\n    time_break   = find(time==2007.75);\n    \n    tt=length(c);\n    \n    % data transformations:\n    \n    % 1. difference log of output, consumption,investment\n    yy1(1: tt,[1 2 3]) = log(c(1 : tt,[1 3 5]));\n    % 2. difference the log GDP deflator index\n    yy1(2: tt,6) = diff(log(c(1: tt,4)))*400;\n    % 3. leave  the Urate capU unchanged\n    yy1(2: tt,[4 5])= c(2:tt,[2 6]);\n    % 4. leave call rate, 10 year unchanged\n    yy1(2: tt,7:8)= c(2:tt,7:8);\n    % 5. compute detrended C/Y, I/Y ratio\n    yy1(1: tt,9) = c(1 : tt,3)./c(1: tt,1);\n    yy1(1: tt,10) = c(1 : tt,5)./c(1: tt,1);\n    % 6. Compute term  spread\n    yy1(1: tt,11) = c(1 : tt,8)-c(1: tt,7);\n    \n    ddd=yy1;\n    T=length(ddd);\n    time_data = time(2:tt);\nend\n\n%% Parameters\n\n%frequency\nfreq   = 'q';        % 'q' for quarterly, 'm' for monthly %\nif lload==0\n    tstart = [1970 3];\n    tend   = [2017 3];\nelseif lload==1\n    tstart = [1970 3];\n    tend   = [2019 3];\nend\n\n% cycle parameters\noptions.turnphase   = 2;\noptions.phase       = 2;          % censoring rules %\noptions.cycle       = 5;          % lenght of cycle\noptions.thresh      = 10.4;       % bypasses phase and cycle restriction if peak to trough is > than thresh\n\noptions.nrep     = 1;        % 1 if analyze real data\noptions.complete = 1;        % if= 1- use complete cycles,if =0 -use incomplete cycles (excess still on complete cycle)\n\n\ndura=zeros(size(ddd,2),2);  ampl=zeros(size(ddd,2),2);\ncumm=zeros(size(ddd,2),2);  excc=zeros(size(ddd,2),2);\ndurcv=zeros(size(ddd,2),2); ampcv=zeros(size(ddd,2),2);\nexccv=zeros(size(ddd,2),2); nott=zeros(size(ddd,2),1);\nturn    = time(time_start+1:time_end)';\nzz      = time(time_start+1:time_end)';\n% tid     = linspace(1970.75,2017.75,T)';\n\nfor qq = 1 : size(ddd,2)\n    if  lload==0\n        % EA\n        x = ddd(:,qq);\n    else\n        % US\n        x = ddd(time_start+1:time_end,qq);\n        time_data = time(time_start+1:time_end);\n    end\n    % dating_mbbq\n    disp('series')\n    disp(qq)\n\n    % Computes turning points and imposes restrictions in one step\n    [dt_(qq)] = date_(x, time_data, freq, tstart, tend, options); \n        \n    zz      = [zz dt_(qq).st];\n    turn    = [turn dt_(qq).trinary];\n    \n    dura(qq,:)  = dt_(qq).dura;\n    ampl(qq,:)  = dt_(qq).ampl;\n    cumm(qq,:)  = dt_(qq).cumm;\n    excc(qq,:)  = dt_(qq).excc;\n    durcv(qq,:) = dt_(qq).durcv;\n    ampcv(qq,:) = dt_(qq).amplcv;\n    exccv(qq,:) = dt_(qq).exccv;\n    nott(qq,:)  = dt_(qq).notentp;\n    %plot(tid,trinary,'linewidth',1)\n    %title('Turning  points')\n    \nend\n\npause;\n\ndisp(' ')\ndisp('statistics on average cycle')\n\ndisp('duration contractions/duration expansions')\ndisp(dura)\n\ndisp('amplitudes contractions/amplitude expansions')\ndisp(ampl)\n\ndisp('cumulative contractions/cumulative expansions')\ndisp(cumm)\n\ndisp('excess movements percent of triangle area')\ndisp('contractions/expansions')\ndisp(excc)\n\ndisp('cv of durations contractions/expansions')\ndisp(durcv)\n\ndisp('cv of amplitudes contractions/expansions')\ndisp(ampcv)\n\ndisp('cv of excess movements contractions/expansions')\ndisp(exccv)\n\n%disp('no of its skipped since no peaks+troughs<=2')\n%disp(nott)\n\n%disp('states indicators:contraction=0, expansion=1')\n%format  short  g\n%round(zz, 2)\n\ndisp('concordance index BC phases')\nma=corr(zz,'type','Spearman');\ndisp(ma(2,3:size(ma,2)))\n\ndisp('concordance index turning  points')\nqa=corr(turn,'type','Spearman');\ndisp(qa(2,3:size(qa,2)))\n\n\n[aa,bb]=size(turn);\ntsum=zeros(aa,1);\nfor kk=1:aa\n    ssum=0;\n    for  qq=2:bb\n        ssum=ssum+turn(kk,qq);\n    end\n    tsum(kk)=ssum;\nend\n\nif lload==0\ntid     = linspace(1970.75,2017.75,T)';\nelse\ntid     = linspace(1970.75,2019.50,T-3)';\nend \nplot(tid,tsum,'linewidth',2)\ntitle('Distribution of Turning  points')\n\ndisp('Distribution of  peaks')\ndp=[zz(find(tsum>=1),1) tsum(find(tsum>=1),1)];\ndisp(fix(dp))\ndisp('Distribution of  throughs')\ndt=[zz(find(tsum<=-1),1) tsum(find(tsum<=-1),1)];\n\ndisp(fix(dt))\n\n% dates\n% peaks    mean 1974.00; 1980.00; 1992.00; 2001.00;  2008:00;  2011.25;\n%          mode 1974.50; 1980.00; 1992.00; 2001.25;  2008.00;  2011.50;\n% throughs mean 1975.25; 1984.25; 1993.75; 2002.75;  2009:50;  2013.00;\n%          mode 1975.00; 1984.25; 1993.75; NaN;      2010.00;  2013.00;\n\n\n% costructing a  recession indicator\nrecind=zeros(time_end-time_start,1);\n\n% recession dates\nrec1b = find(time==1974.00);\nrec1e = find(time==1975.25);\n\nrec2b = find(time==1980.00);\nrec2e = find(time==1984.25);\n\nrec3b = find(time==1992.00);\nrec3e = find(time==1993.75);\n\nrec4b = find(time==2001.00);\nrec4e = find(time==2002.75);\n\nrec5b = find(time==2008.00);\nrec5e = find(time==2009.50);\n\nrec6b = find(time==2011.25);\nrec6e = find(time==2013.00);\n\n\nfor i=rec1b:rec1e\n    recind(i,1)=1;\nend\n\nfor i=rec2b:rec2e\n    recind(i,1)=1;\nend\nfor i=rec3b:rec3e\n    recind(i,1)=1;\nend\n\nfor i=rec4b:rec4e\n    recind(i,1)=1;\nend\n\nfor i=rec5b:rec5e\n    recind(i,1)=1;\nend\n\nfor i=rec6b:rec6e\n    recind(i,1)=1;\nend\n\nif  lload==0\n    save Eurorec recind\nelse\n    save Usarec recind\nend\nreturn\n\n", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/examples/Trend-Cycle-Dating tutorial/example_2_dating.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5597012785775225}}
{"text": "%% housekeeping\nclear\nclc\nclose all\n%% \"rise\" the model\nm=rise('fs2000_rise');\n%% pushing the particular vector (different from the initial estimation point)\n% Note we have to declare the regime of the parameter\n\ncalibration=struct();\n\tcalibration.alp=0.330;\n\tcalibration.bet=0.990;\n\tcalibration.gam=0.003;\n\tcalibration.mst=1.011;\n\tcalibration.rho=0.700;\n\tcalibration.psi=0.787;\n\tcalibration.del=0.020;\n\tcalibration.sig_a=0.014;\n\tcalibration.sig_m=0.005;\nm=set(m,'parameters',calibration); \n\n%% solve the model and \nm=solve(m);\n\n%% print the solution \n\nm.print_solution\n\ndisp('This should be identical to the dynare solution (see folder dynare_version)')\n\n%% lets do some estimation: we need the data\n% get the data from the dynare_version folder\n\nrun dynare_version\\fsdat_simul\n\n% rise needs data to be passed as a ts object with dates and\n% names of the variables. So we proceed to constructing the database\n\n% we use the same start date as in the Schorfheide paper even though the\n% data are not the same\nstartdate='1950q1';\ndatabase=ts(startdate,[gp_obs,gy_obs],{'gp_obs','gy_obs'});\n\n%% pass the data to the rise object\n\n% 192 observations are used in dynare\nend_date= obs2date(startdate,192);\n% the loglinear option of dynare implies:\n% 1- we have to take the log of our data. \n% 2- we have to exponentiate the corresponding variables in the rise model\n% file. Dynare does this by taking the log of the steady state during\n% estimation and this does not ring too transparent to me.\n\n% In rise, we can just take the log of the whole database. This is  \n% what we do in passing the data. But we also need to tell ts\n% that the logged variables should have the same names as the original\n% ones. In order to do that, we add set the flag to true when taking the\n% log.\nvnames=database.varnames;\ndatabase=log(database);\ndatabase.varnames=vnames;\nm=set(m,'data',database,'estim_end_date',end_date);\n\n%% estimate the model\nprofile off\nprofile on\nm=estimate(m);%,'optimizer',@csminwellwrap,'debug',true\nprofile off\nprofile viewer\n\n%% do posterior simulation\n[objective,lb,ub,x0,SIG]=pull_objective(m);\n\nSIG=utils.cov.nearest(SIG);\n\ndraws_mcmc = 1000; % number of parameter draws through MCMC.\nndraws_burnin = floor(0.1*draws_mcmc);\nmcmc_options=struct('burnin',ndraws_burnin,'N',draws_mcmc,'thin',1,...\n    'nchain',2);\nResults=mh_sampler(objective,lb,ub,mcmc_options,x0,SIG);\n\n%% update the description of the parameters\nm=set(m,'tex_name',...\n    {\n    'alp','$\\alpha$'\n    'bet','$\\beta$' \n    'gam','$\\gamma$' \n    'rho','$\\rho$' \n    'psi','$\\psi$'\n\t'del','$\\delta$' \n    'sig_a','$\\sigma_a$' \n    'sig_m','$\\sigma_m$'\n    });\n%% plot priors, posteriors, priors and posteriors\nplot_priors(m)\nplot_posteriors(m,Results)\nplot_priors_and_posteriors(m,Results)\n%% plot priors, posteriors, priors and posteriors for a subset of parameters\nclose all\nmyparams={'alp','gam','psi'};\nplot_priors(m,myparams)\nplot_posteriors(m,Results,myparams)\nplot_priors_and_posteriors(m,Results,myparams)\n%% check curvature at the mode\nmode_curvature(m)\n\n%% check curvature at the mode for a subset of parameters\nmode_curvature(m,myparams)\n\n%% check curvature at the mode for a subset of parameters\nprofile off\nprofile on\nmode_curvature(m,myparams)\nprofile off\nprofile viewer\n", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/FrankSchorfheide/LossFunction_JAE2000/howto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067208930584, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5597012740998308}}
{"text": "function f = exp(f) \n%EXP  Exponential of a CHEBFUN3T object.\n%   EXP(F) returns the exponential of a CHEBFUN3T object F. \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    return \nend \n\nop = @(x,y,z) exp(feval(f, x, y, z));    % Resample.\nf = chebfun3t(op, f.domain);             % Call constructor.\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3t/exp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5597012708983156}}
{"text": "function Population = EnvironmentalSelection(Population,Offspring,N)\n% The environmental selection of GDE3\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    %% Select by constraint-domination\n    PopObj    = Population.objs;\n    PopCon    = Population.cons;\n    feasibleP = all(PopCon<=0,2);\n    OffObj    = Offspring.objs;\n    OffCon    = Offspring.cons;\n    feasibleO = all(OffCon<=0,2);\n    % The offsprings which can replace its parent\n    updated = ~feasibleP&feasibleO  | ...\n              ~feasibleP&~feasibleO & all(PopCon>=OffCon,2) | ...\n              feasibleP&feasibleO   & all(PopObj>=OffObj,2);\n    % The offsprings which can add to the population\n    selected = feasibleP&feasibleO & any(PopObj<OffObj,2) & any(PopObj>OffObj,2);\n    % Update the population\n    Population(updated) = Offspring(updated);\n    Population          = [Population,Offspring(selected)];\n    \n    %% Select by non-dominated sorting and crowding distance\n    PopObj   = Population.objs;\n    PopCon   = Population.cons;\n    feasible = all(PopCon<=0,2);\n    % Non-dominated sorting based on constraint-domination\n    FrontNo = inf(1,length(Population));\n    [FrontNo(feasible),MaxFNo] = NDSort(PopObj(feasible,:),inf);\n    FrontNo(~feasible) = NDSort(PopCon(~feasible,:),inf) + MaxFNo;\n    % Determine the last front\n    MaxFNo    = find(cumsum(hist(FrontNo,1:max(FrontNo)))>=N,1);\n    lastFront = find(FrontNo==MaxFNo);\n    % Eliminate solutions in the last front one by one\n    while length(lastFront) > N - sum(FrontNo<MaxFNo)\n        [~,worst] = min(CrowdingDistance(PopObj(lastFront,:)));\n        lastFront(worst) = [];\n    end\n    Population = Population([find(FrontNo<MaxFNo),lastFront]);\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/GDE3/EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5596376787183065}}
{"text": "function out_ztimes = genas(cumu,xt,totbin,bin0,bin1)\n    % Uses the GenAS algorithm to determine times of maximum Z values (as given by function AS) for a cumulative time curve\n    %\n    %  Syntax:     ztimes = genas(cumu,xt,totbin,bin0,bin1)\n    %\n    %  This Matlab function uses the GenAS algorithm of Habermann\n    %  to determine times of maximum Z values (as given by function AS)\n    %  for a cumulative time curve.\n    %\n    %  cumu is a histogram of events using a predefined bin length\n    %  xt is the total time vector (in decimal years)\n    %  bin0 is the cutoff at the beginning and bin1 at end of the analyses\n    %  totbin is the total number of bins (including those with 0 z-values)\n    %  ztimes is a vector with max-zvalues, its indexes give the bin number\n    %  ------------------                                  R. Zuniga, 4/94\n    \n    global ztimes\n    global sumx\n    \n    report_this_filefun();\n    as=zeros(1,totbin);\n    % if ~exist('sumx', 'var'); sumx = sum(cumu); end\n    sumx = [sumx; sum(cumu)];\n    sumx = max(sumx);\n    par2 = sumx*0.1;\n    %\n    %\n    for i = bin0+3:1:bin1-3          % calculate mean and z value for AS\n        mean1 = mean(cumu(bin0:i));\n        mean2 = mean(cumu(i+1:bin1));\n        var1 = cov(cumu(bin0:i));\n        var2 = cov(cumu(i+1:bin1));\n        if mean1 && mean2 ~= 0\n            as(i) = (mean1 - mean2)/(sqrt(var1/(i-bin0+1)+var2/(bin1-i)));\n        else\n            as(i) = 0;\n            \n        end     %if mean1\n        \n    end     % for i\n    \n    %   S = sprintf('bin0 %3d bin1 %3d i  %d',bin0, bin1, i);\n    %   disp(S)\n    %\n    % check for threshold  (z = 1.96 -> 95%,  2.57  -> 99%)\n    %as\n    [xmax,ixs] = max(abs(as));\n    if abs(as(ixs)) >= 2.57\n        zmax = as(ixs);\n        as = as*0 ;\n        as(ixs) = zmax;\n        \n        ztimes(ixs) = as(ixs);      % form (vector) ztimes\n        %  find(ztimes)\n        \n        xsum = cumsum(cumu);\n        \n        t1(1) = xt(ixs);\n        t1(2) = xsum(ixs);\n        t1p = [  t1(1)  t1(2); t1(1)   t1(2)+par2 ];\n        plot(t1p(:,1),t1p(:,2),'k');\n        set(gca,'NextPlot','add');\n        \n        S = sprintf('bin0 %d sig-Z at %d bin1 %d ',bin0, ixs, bin1);\n        disp(S)\n        \n        ztimes = genas(cumu,xt,totbin,bin0,ixs);  %call genas again for both extremes\n        ztimes = genas(cumu,xt,totbin,ixs,bin1);\n        \n    end     %if abs\n    \n    ztimes(1,totbin) = 0;    %   pad the end of ztimes\n    as = as*0;\n    out_ztimes = ztimes; %return a version that isn't the global\n    \n    %\n    %  Plot the as(t)\n    %\n    %figure_w_normalized_uicontrolunits(2)\n    %clf\n    % orient tall\n    % rect = [0.2,  0.20, 0.55, 0.75];\n    % axes('position',rect)\n    %set(gca,'NextPlot','add')\n    %%plotyy(xt,cumu2,xt,as*10,'m')\n    %% y2label('z-value')\n    %% plot(xt,as*10,'+m')\n    %% plot(xt,as*10,'m')\n    % %text(0.70,0.5,'+: AS * 10','sc')\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/genas.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5596376674162935}}
{"text": "function [net, opts] = get_model(opts, addFC)\nif nargin < 2, addFC = true; end\n\nt0 = tic;\nmodelFunc = str2func(sprintf('models.%s', opts.arch));\n[net, opts, in_name, in_dim] = modelFunc(opts);\nlogInfo('%s in %.2fs', opts.arch, toc(t0));\n\n% + FC layer\nif addFC\n    convobj = dagnn.Conv('size', [1 1 in_dim opts.dim], ...\n        'pad', 0, 'stride', 1, 'hasBias', true);\n    params = convobj.initParams();\n    net.addLayer('fc', convobj, {in_name}, {'logits'}, {'fc_w', 'fc_b'});\n    p1 = net.getParamIndex('fc_w');\n    p2 = net.getParamIndex('fc_b');\n    net.params(p1).value = params{1};\n    net.params(p2).value = params{2};\n    net.params(p1).learningRate = opts.lrmult;\n    net.params(p2).learningRate = opts.lrmult;\n\n    in_name = 'logits';\n    in_dim  = opts.dim;\nend\n\n% + l2 normalization layer\nnet.addLayer('L2norm', dagnn.LRN('param', [2*in_dim, 0, 1, 0.5]), ...\n    {in_name}, {'feats_l2'});\n\n% + loss layer\nlossobj = str2func(opts.obj);\nnet.addLayer('loss', lossobj('opt', opts), {'feats_l2', 'labels'}, {'objective'});\n\n% print\nif 0\n    net.print({'data', [opts.imageSize opts.imageSize 3 opts.batchSize]}, ...\n        'MaxNumColumns', 4, 'Layers', [], 'Parameters', []);\nend\n\nend\n", "meta": {"author": "kunhe", "repo": "FastAP-metric-learning", "sha": "ca85b2ab3f22460795d4306c8fa01c655d17027e", "save_path": "github-repos/MATLAB/kunhe-FastAP-metric-learning", "path": "github-repos/MATLAB/kunhe-FastAP-metric-learning/FastAP-metric-learning-ca85b2ab3f22460795d4306c8fa01c655d17027e/matlab/get_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5596376561142804}}
{"text": "function [out] = evap_2(p1,S,Smax,Ep,dt)\n%evap_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 <https://www.gnu.org/licenses/> for details.\n\n% Flux function\n% ------------------\n% Description:  Evaporation at a scaled, plant-controlled rate\n% Constraints:  f <= Ep\n%               f <= S/dt\n% @(Inputs):    p1   - plant-controlled base evaporation rate [mm/d]\n%               S    - current storage [mm]\n%               Smax - maximum storage [mm]\n%               Ep   - potential evapotranspiration rate [mm/d]\n%               dt   - time step size [d]\n\nout = min([p1*S/Smax,Ep,S/dt]);\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/evap_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5596376455258912}}
{"text": "function [ind,d] = find(v,w,epsilon,varargin)\n% return index of all points in a epsilon neighborhood of a vector\n%\n% Syntax\n%   ind = find(v,w,epsilon) % find all points out of v in a epsilon neighborhood of w\n%   ind = find(v,w)         % find closest point out of v to w\n%\n% Input\n%  v, w    - @vector3d\n%  epsilon - double\n%\n% Options\n%  antipodal - include <VectorsAxes.html antipodal symmetry>\n%\n% Output\n%  ind     - int32\n\n% compute distances\nd = angle_outer(v,w,varargin{:});\n\n% find neigbours\nif nargin >= 3\n  if epsilon == 1\n    [d,ind] = min(d,[],1);\n  else\n    ind = d < epsilon;\n  end\nelse\n  [d,ind] = min(d,[],1);\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@vector3d/find.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5596376440986427}}
{"text": "classdef MyODEMR < ALGORITHM\n% <multi/many> <real/integer>\n% Many-objective differential evolution with mutation restriction\n% nP --- 500 --- Number of reference points for IGD calculation\n\n%------------------------------- Reference --------------------------------\n% R. Denysiuk, L. Costa, and I. E. Santo, Many-objective optimization using\n% differential evolution with variable-wise mutation restriction,\n% Proceedings of the Annual Conference on Genetic and Evolutionary\n% Computation, 2013, 591-598.\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    methods\n        function main(Algorithm,Problem)\n            %% Parameter setting\n            nP = Algorithm.ParameterSet(500);\n\n            %% Generate hyperplane \n            P = UniformPoint(nP,Problem.M);\n\n            %% Generate random population\n            Population = Problem.Initialization();\n\n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                Offspring  = Operator(Problem,Population(1:Problem.N),Population(randi(Problem.N,1,Problem.N)),Population(randi(Problem.N,1,Problem.N)));\n                Population = EnvironmentalSelection([Population,Offspring],Problem.N,P);\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/Algorithms/Multi-objective optimization/MyO-DEMR/MyODEMR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5596359027230021}}
{"text": "function [y]=tt_exp(x, eps, varargin)\n%Computation of the pointwise exponential in TT format\n%   [Y]=TT_EXP(X,EPS,VARARGIN) This function computes pointwise exponential\n%   using scaling and squaring method of the TT-vector X. EPS is the\n%   accuracy parameter, varargins: \n%       N is the number of summand for the local Taylor\n%           series (N=10 by default, usually enough). \n%       RMAX is the TT-rank bound.\n\n\n% nrm = norm(x);\nif (isa(x, 'tt_tensor'))\n    nrm = tt_max_abs(x);\nelse\n    nrm = tt_max_abs(qtttucker_to_linqtt(x, eps));\nend;\nn0 = floor(max(log2(nrm), 0))+1;\nx = x./(2^n0);\nif (isa(x, 'tt_tensor'))\n    ons = tt_ones(x.n);\nelse\n    ons = [];\n    for i=1:(x.core.d)\n        curons = tt_ones(x.tuck{i}.n);\n        curons = qtt_tucker(curons, x.tuck{i}.d, eps);\n        ons = kron(ons, curons);\n    end;\nend;\ny = ons;\n\nN = 10;\nhdm = 'svd';\nrmax = Inf;\nepst = eps;\nwhile (length(varargin)==1)\n    varargin = varargin{1};\nend;\nfor i=1:2:length(varargin)-1\n    switch lower(varargin{i})\n        case 'n'\n            N=varargin{i+1};\n        case 'rmax'\n            rmax=varargin{i+1};\n        case 'epst'\n            epst=varargin{i+1};\n        case 'hdm'\n            hdm=varargin{i+1};\n            \n        otherwise\n            error('Unrecognized option: %s\\n',varargin{i});\n    end\nend\n\nfor k=(N-1):-1:1\n% for k=1:N-1\n    y=ons+(y.*x)/k;\n    y=round(y,epst,rmax);\nend\n\nfor k=1:n0\n    if (strcmp(hdm, 'svd'))\n        y=round(y.*y,eps*(0.5^(n0-k)),rmax);\n        fprintf('squaring %d\\n', k);\n    else\n        if (isa(x, 'tt_tensor'))\n%             y = mvk3(diag(y), y, eps, 'nswp', 20, 'kickrank', 2);\n            y = tt_mvk4(diag(y), y, eps, 'nswp', 20);\n        else\n%             y = mvrk(diag(y), y, eps, 'nswp', 20, 'kickrank', 2);\n            y = mvrk2(diag(y), y, eps, 'nswp', 20);\n        end;\n    end;\nend\n\nend", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/exp/tt_exp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5596358984110752}}
{"text": "function [yNext,didConverge]=implicitWeakRungeKStep(y,t,a,B,deltaT,algorithm,aCur,BCur,useNewton,useGaussian,maxIter,RelTol,AbsTol)\n%%IMPLICITWEAKRUNGEKSTEP Perform a single step of an implicit weak\n%           stochastic Runge-Kutta method under It\ufffd calculus. This\n%           integrates d-dimensional stochastic differential equation of\n%           the form:\n%           dy=a(y,t)*dt+B(y,t)*dW\n%           where dW is the differential of an m-dimensional Wiener\n%           process. As the stepsize used decreases, weak methods converge\n%           such that integrals with the random process are a measure are\n%           correct (for example, to determine moments). However, they do\n%           not converge to the optimal path, unlike strong methods.\n%\n%INPUTS: y The dX1 initial value of the random process.\n%        t The scalar initial time of the random process. If an empty\n%          matrix is passed, t=0 is used.\n%        a A function handle to the drift function. This is called as\n%          a(y,t) and returns a dX1 vector. If one wishes to use Newton's\n%          method for the implicit iteration, then the calling format is\n%          [aVal,papy]=a(y,t), where papy is the dXd matrix of partial\n%          derivatives of a with respect to the elements of y papy(:,i) is\n%          the derivative with respect to the ith component of y.\n%        B A function handle to the diffusion matrix function. This is\n%          called as B(y,t) and returns a dXm matrix.\n%   deltaT The time increment over which the step is taken.\n% algorithm A parameter specifying the algorithm to use. Possible values\n%          are:\n%          0 Use the implicit order 2.0 weak scheme for scalar noise from\n%            Equation 5.12 of Chapter 15.5 of [1], which is the same as\n%            Equation 4.12 of Chapter 15.4 and is the implicit form of \n%            Equation 1.1 in Chapter 15.1 of [1]. This requires that m=1.\n%          1 Use the autonomous implicit order 2.0 weak scheme from\n%            Equation 5.14 of Chapter 15.5 of [1], which is the same as\n%            Equation 4.13 of Chapter 15.4 and is the implicit form of \n%            Equation 1.3 in Chapter 15.1 of [1]. This requires that a and\n%            B not depend on t.\n%          2 Use the autonomous explicit order 2.0 weak scheme for additive\n%            noise that comes as a special case of Equation 5.14 of Chapter\n%            15.5 of [1]. This requires that a and B not depend on t and\n%            that B does not depend on x.\n% aCur, BCur Often one might already have the values a(x,t) and B(x,t). If\n%          so, then they should be provided as the dX1 and dXm aCur and\n%          BCur to avoid recalculation. If unavailable, these values can be\n%          omitted or empty matrices passed.\n% useNewton Indicates whether the implicit iteration should be performed\n%          using Newton's method or fixed-point iteration. The default if\n%          omitted or an empty matrix is passed is false (fixed-point\n%          iteration). If Newton's method is used, then papy must be\n%          returned by the function a.\n% useGaussian Algorithms 0 and 1 have a choice of how the random component\n%          is generated. If useGaussian=true, then Gaussian random\n%          variables will be used. Otherwise, simpler random variables\n%          having the same desired moment properties will be used. the\n%          default if omitted or an empty matrix is passed is true.\n%  maxIter The maximum number of iterations to perform. The default if\n%          omitted or an empty matrix is passed is 2.\n% RelTol, AbsTol The relative and absolute tolerances on the iterations\n%          before declaring convergence. If these are set to 0 (the default\n%          if omitted or empty matrices are passed), then the algorithm\n%          will just iterate for the maximum number of iterations. the\n%          tolerances apply to each element of x. Convergence is declared\n%          if all(diff<=AbsTol)||all(diff<=RelTol*abs(yNext)).\n%\n%OUTPUTS: yNext The estimated value of the process after taking a step of\n%               deltaT. This is a random value.\n%   didConverge If RelTol and/or AbsTol are not zero and maxIter>0, then\n%               this indicates whether the iterations converged to the\n%               desired accuracy. Otherwise, this is just an empty matrix.\n%\n%EXAMPLE 1:\n%This is an example of a nonlinear scalar problem with non-additive noise\n%where an explicit solution is available as a basis of comparison. In\n%Chapter 4.4 of [1], the stochastic differential equation and its solution\n%are from Equation 4.40. We compare the performance of the explicit\n%solution (taking the expected value using cubature integration) and the\n%implicit solution.\n% rng(1)%Make exact run repeatable.\n% numMC=1e3;\n% numSteps=1;\n% algorithm=1;\n% useNewton=true;\n% deltaT=1.1;\n% y0=0.5;\n% aDrift=@(y,t)((1/3)*y^(1/3));\n% BDiff=@(y,t)(y^(2/3));\n% papy=@(y)1/(9*y^(2/3));\n% aFun=@(y,t)dealRobust(aDrift(y,t),papy(y));\n% explSim=@(W)(y0^(1/3)+(1/3)*W)^3;\n% \n% %Take the expected value of the explicit solution using quadrature\n% %integration.\n% [xi,w]=quadraturePoints1D(6);%2*6-1=11th order.\n% numPts=length(w);\n% xi=sqrt(deltaT)*xi;\n% muCub=0;\n% for k=1:numPts\n%     muCub=muCub+w(k)*explSim(xi(:,k));\n% end\n% \n% valsRKImp=zeros(1,numMC);\n% valsRK=zeros(1,numMC);\n% for curMC=1:numMC\n%     y=y0;\n%     yExp=y0;\n%     t=0;\n%     for curStep=1:numSteps\n%         s=rng();%Record the state prior to generating the random variables.\n%         y=implicitWeakRungeKStep(y,t,aFun,BDiff,deltaT/numSteps,algorithm,[],[],useNewton);\n% \n%         rng(s)%Drive the explicit step with the same random process as the\n%               %implicit one.\n%         yExp=weakRungeKStep(yExp,t,aDrift,BDiff,deltaT/numSteps,algorithm);\n%         t=t+deltaT/numSteps;\n%     end\n%     valsRKImp(curMC)=y;\n%     valsRK(curMC)=yExp;\n% end\n% muRKImp=mean(valsRKImp);\n% muRK=mean(valsRK);\n% abs((muRKImp-muCub)./muCub)%Relative mean error, implicit.\n% abs((muRK-muCub)./muCub)%Relative mean error, explicit.\n%The implicit error will be about 0.0086 and the explicit error will be\n%about 0.0153. Thus, the algorithm improves the explicit method in this\n%instance.\n%\n%EXAMPLE 2:\n%Here, we compare the implicit strong Taylor method to the explicit method\n%on a linear model. This is done with the same noise driving both\n%processes.\n% algorithm=2;\n% useNewton=false;\n% numMC=1e3;\n% deltaT=1/3;\n% numSteps=5;\n% y0=[1/4;-12];\n% A=[1.1,0.1;\n%    -0.2,2.2];\n% D=[1.5,-0.4;\n%    0.1,1];\n% d=size(D,1);\n% [F,Q]=linDynMod2Disc(deltaT,A,D);\n% mu=F*y0;\n% P=Q;\n% aDrift=@(x,t)(A*x);\n% BDiff=@(x,t)(D);\n% \n% aFun=@(y,t)dealRobust(aDrift(y,t),A);\n% \n% valsRKImp=zeros(d,numMC);\n% valsRK=zeros(d,numMC);\n% for curMC=1:numMC\n%     yExpl=y0;\n%     y=y0;\n%     t=0;\n%     for curStep=1:numSteps\n%         s=rng();%Record the state prior to generating the random variables.\n%         y=implicitWeakRungeKStep(y,t,aFun,BDiff,deltaT/numSteps,algorithm,[],[],useNewton);\n% \n%         rng(s)%Drive the explicit step with the same random process as the\n%               %implicit one.\n%         yExpl=weakRungeKStep(yExpl,t,aDrift,BDiff,deltaT/numSteps,algorithm);\n%         t=t+deltaT/numSteps;\n%     end\n%     valsRKImp(:,curMC)=y;\n%     valsRK(:,curMC)=yExpl;\n% end\n% [muRKImp,PRKImp]=calcMixtureMoments(valsRKImp);\n% [muRK,PRK]=calcMixtureMoments(valsRK);\n% norm(muRKImp-mu)./norm(mu)%Relative mean error, implicit.\n% norm(PRKImp-P,'fro')./norm(P,'fro')%Relative variance error,implicit.\n% norm(muRK-mu)./norm(mu)%Relative mean error, explicit.\n% norm(PRK-P,'fro')./norm(P,'fro')%Relative variance error,explicit.\n%One will typically see that the relative errors of the implicit method are\n%notably better than the explicit method.\n%\n%EXAMPLE 3:\n%This is an example of what is considered a \"stiff\" problem in Section 12.2\n%of [1] with non-additive noise. The problem has an explicit solution in\n%terms of the Wiener process W. We use quadrature integration to obtain the\n%mean of that solution, which is used as the true moments for comparison.\n%We compare this implicit method with an explicit step. This is a 2X1\n%process with scalar noise.\n% rng(1)%Make the exact run repeatable.\n% algorithm=0;\n% useNewton=false;\n% useGaussian=false;\n% numMC=1e3;\n% a=25;\n% b=2;\n% deltaT=1/10;\n% numSteps=10;\n% A=[-a,a;\n%     a,-a];\n% B=[b,0;\n%    0,b];\n% aDrift=@(y,t)A*y;\n% BDiff=@(y,t)B*y;\n% d=2;\n% papy=A;\n% aFun=@(y,t)dealRobust(aDrift(y,t),papy);\n% %The explicit solution; equation 2.5 in Chapter 12.2 of [1].\n% expSol=@(W,deltaT,y0)(expm((A-(1/2)*B^2)*deltaT+B*W)*y0);\n% y0=[1;0.1];\n% \n% %Take the expected value of the explicit solution using quadrature\n% %integration.\n% [xi,w]=quadraturePoints1D(6);%2*6-1=11th order.\n% numPts=length(w);\n% xi=sqrt(deltaT)*xi;\n% muCub=zeros(d,1);\n% for k=1:numPts\n%     muCub=muCub+w(k)*expSol(xi(:,k),deltaT,y0);\n% end\n% \n% valsRK=zeros(d,numMC);\n% valsRKExplicit=zeros(d,numMC);\n% for curMC=1:numMC\n%     y=y0;\n%     yExp=y0;\n%     t=0;\n%     for curStep=1:numSteps\n%         s=rng();%Record the state prior to generating the random variables.\n%         y=implicitWeakRungeKStep(y,t,aFun,BDiff,deltaT/numSteps,algorithm,[],[],useNewton,useGaussian);\n% \n%         rng(s)%Drive the explicit step with the same random process as the\n%               %implicit one.\n%         yExp=weakRungeKStep(yExp,t,aDrift,BDiff,deltaT/numSteps,algorithm,[],[],useGaussian);\n%         t=t+deltaT/numSteps;\n%     end\n%     valsRK(:,curMC)=y;\n%     valsRKExplicit(:,curMC)=yExp;\n% end\n% muRK=mean(valsRK,2);\n% muRKExp=mean(valsRKExplicit,2);\n% norm((muRK-muCub)./norm(muCub))%Relative mean error, implicit.\n% norm((muRKExp-muCub)./norm(muCub))%Relative mean error, explicit.\n%One will get a relative implicit error of about 0.0119 and a relative\n%explicit error of about 0.0121. Getting rid of the random seed, the\n%implicit solution is typically more accurate than the explicit. Using the\n%Gaussian noise option also improves performance.\n%\n%REFERENCES:\n%[1] P. E. Kloeden and E. Platen, Numerical Solution of Stochastic\n%    Differential Equations. Berlin: Springer, 1999.\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<13||isempty(AbsTol))\n    AbsTol=0;\nend\n\nif(nargin<12||isempty(RelTol))\n    RelTol=0; \nend\n\nif(nargin<11||isempty(maxIter))\n    maxIter=2;\nend\n\nif(nargin<10||isempty(useGaussian))\n    useGaussian=true;\nend\n\nif(nargin<9||isempty(useNewton))\n    useNewton=false;\nend\n\nif(nargin<8||isempty(BCur))\n    BCur=B(y,t); \nend\n\nif(nargin<7||isempty(aCur))\n    aCur=a(y,t); \nend\n\nif(isempty(t))\n    t=0; \nend\n\nif(algorithm>=0&&algorithm<=2)\n    [yNext,fixedTerm]=weakRungeKStep(y,t,a,B,deltaT,algorithm,aCur,BCur,useGaussian);\n    \n    tNext=t+deltaT;\n    if(useNewton)\n        [yNext,didConverge]=implicitNewtonIter(y,a,deltaT/2,yNext,tNext,fixedTerm,maxIter,RelTol,AbsTol);\n    else\n        [yNext,didConverge]=implicitFixedPointIter(y,a,deltaT/2,yNext,tNext,fixedTerm,maxIter,RelTol,AbsTol);\n    end\nelse\n    error('Unknown algorithm specified.')\nend\nend\n\nfunction [yNext,didConverge]=implicitFixedPointIter(yOld,a,coeff,yNext,tNext,fixedTerm,maxIter,RelTol,AbsTol)\n%IMPLICITFIXEDITER This iterates the function\n%                  yNext=a(yNext,tNext)*coeff+fixedTerm\n%                  Iterations continue until the RelTol and or AbsTol\n%                  conditions are met or maxIter iterations have elapsed.\n%\n%December 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n    if(RelTol==0&&AbsTol==0)\n        %Fixed point iteration for the maximum number of steps.\n        for curIter=1:maxIter\n            yNext=a(yNext,tNext)*coeff+fixedTerm;\n        end\n        didConverge=[];\n    else%Iterate until meeting the convergence bound.\n        didConverge=false;\n        for curIter=1:maxIter\n            yNext=a(yNext,tNext)*coeff+fixedTerm;\n\n            diff=abs(yOld-yNext);\n            if(all(diff<=AbsTol)||all(diff<=RelTol*abs(yNext)))\n                didConverge=true;\n                break; \n            end\n\n            yOld=yNext;\n        end\n    end\nend\n\nfunction [yNext,didConverge]=implicitNewtonIter(yOld,a,coeff,yNext,tNext,fixedTerm,maxIter,RelTol,AbsTol)\n%%IMPLICITNEWTONITER This function uses Newton's method to try to solve\n%                    a(yNext,tNext)*coeff+fixedTerm-yNext=0\n%                    for yNext.Iterations continue until the RelTol and or\n%                    AbsTol conditions are met or maxIter iterations have\n%                    elapsed.\n%\n%December 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n    d=size(yNext,1);\n    \n    I=eye(d,d);\n    if(RelTol==0&&AbsTol==0)\n        %Newton's iteration for the maximum number of steps.\n        for curIter=1:maxIter\n            [aVal,papy]=a(yNext,tNext);\n            F=yNext-fixedTerm-coeff*aVal;\n            dF=I-coeff*papy;\n            yNext=yNext-dF\\F;\n        end\n        didConverge=[];\n    else%Iterate until meeting the convergence bound.\n        didConverge=false;\n        for curIter=1:maxIter\n            [aVal,papy]=a(yNext,tNext);\n            F=aVal-fixedTerm-coeff*aVal;\n            dF=I-coeff*papy;\n            yNext=yNext-dF\\F;\n\n            diff=abs(yOld-yNext);\n            if(all(diff<=AbsTol)||all(diff<=RelTol*abs(yNext)))\n                didConverge=true;\n                break; \n            end\n\n            yOld=yNext;\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/Stochastic_Processes/implicitWeakRungeKStep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5596358963333653}}
{"text": "function [theta_median theta_std theta_lbound theta_ubound sigma_median]=panel6estimates(d,N,n,T,theta_gibbs,sigma_gibbs,cband)\n\n\n% obtain point estimates for the structural factors\n% loop over sample periods\nfor ii=1:T\n   % loop over structural factors\n   for jj=1:d\n   theta_median(jj,1,ii)=[quantile(theta_gibbs(jj,:,ii),0.5)];\n   theta_std(jj,1,ii)=std(theta_gibbs(jj,:,ii));\n   theta_lbound(jj,1,ii)=[quantile(theta_gibbs(jj,:,ii),(1-cband)/2)];\n   theta_ubound(jj,1,ii)=[quantile(theta_gibbs(jj,:,ii),1-(1-cband)/2)];\n   end\nend\n\n\n% obtain point estimates for sigma\n% loop over sample periods\nfor ii=1:T\n   % loop over sigma entries\n   for jj=1:(N*n)^2\n   sigma_median(jj,1,ii)=[quantile(sigma_gibbs(jj,:,ii),0.5)];\n   end\nend\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/panel6estimates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5596358913288692}}
{"text": "function [Ybus, Yf, Yt] = makeYbus(baseMVA, bus, branch)\n%MAKEYBUS   Builds the bus admittance matrix and branch admittance matrices.\n%   [YBUS, YF, YT] = MAKEYBUS(MPC)\n%   [YBUS, YF, YT] = MAKEYBUS(BASEMVA, BUS, BRANCH)\n%   \n%   Returns the full bus admittance matrix (i.e. for all buses) and the\n%   matrices YF and YT which, when multiplied by a complex voltage vector,\n%   yield the vector currents injected into each line from the \"from\" and\n%   \"to\" buses respectively of each line. Does appropriate conversions to p.u.\n%   Inputs can be a MATPOWER case struct or individual BASEMVA, BUS and\n%   BRANCH values. Bus numbers must be consecutive beginning at 1\n%   (i.e. internal ordering).\n%\n%   See also MAKEJAC, MAKESBUS, EXT2INT.\n\n%   MATPOWER\n%   Copyright (c) 1996-2016, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n%% extract from MPC if necessary\nif nargin < 3\n    mpc     = baseMVA;\n    baseMVA = mpc.baseMVA;\n    bus     = mpc.bus;\n    branch  = mpc.branch;\nend\n\n%% constants\nnb = size(bus, 1);          %% number of buses\nnl = size(branch, 1);       %% number of lines\n\n%% define named indices into bus, branch matrices\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...\n    TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...\n    ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;\n\n%% check that bus numbers are equal to indices to bus (one set of bus numbers)\nif any(bus(:, BUS_I) ~= (1:nb)')\n    error('makeYbus: buses must be numbered consecutively in bus matrix; use ext2int() to convert to internal ordering')\nend\n\n%% for each branch, compute the elements of the branch admittance matrix where\n%%\n%%      | If |   | Yff  Yft |   | Vf |\n%%      |    | = |          | * |    |\n%%      | It |   | Ytf  Ytt |   | Vt |\n%%\nstat = branch(:, BR_STATUS);                    %% ones at in-service branches\nYs = stat ./ (branch(:, BR_R) + 1j * branch(:, BR_X));  %% series admittance\nBc = stat .* branch(:, BR_B);                           %% line charging susceptance\ntap = ones(nl, 1);                              %% default tap ratio = 1\ni = find(branch(:, TAP));                       %% indices of non-zero tap ratios\ntap(i) = branch(i, TAP);                        %% assign non-zero tap ratios\ntap = tap .* exp(1j*pi/180 * branch(:, SHIFT)); %% add phase shifters\nYtt = Ys + 1j*Bc/2;\nYff = Ytt ./ (tap .* conj(tap));\nYft = - Ys ./ conj(tap);\nYtf = - Ys ./ tap;\n\n%% compute shunt admittance\n%% if Psh is the real power consumed by the shunt at V = 1.0 p.u.\n%% and Qsh is the reactive power injected by the shunt at V = 1.0 p.u.\n%% then Psh - j Qsh = V * conj(Ysh * V) = conj(Ysh) = Gs - j Bs,\n%% i.e. Ysh = Psh + j Qsh, so ...\nYsh = (bus(:, GS) + 1j * bus(:, BS)) / baseMVA; %% vector of shunt admittances\n\n%% bus indices\nf = branch(:, F_BUS);                           %% list of \"from\" buses\nt = branch(:, T_BUS);                           %% list of \"to\" buses\n\n%% for best performance, choose method based on MATLAB vs Octave and size\nif nb < 300 || have_feature('octave')   %% small case OR running on Octave\n    %% build Yf and Yt such that Yf * V is the vector of complex branch currents injected\n    %% at each branch's \"from\" bus, and Yt is the same for the \"to\" bus end\n    i = [1:nl 1:nl]';                           %% double set of row indices\n    Yf = sparse(i, [f; t], [Yff; Yft], nl, nb);\n    Yt = sparse(i, [f; t], [Ytf; Ytt], nl, nb);\n\n    %% build Ybus\n    Ybus = sparse([f;f;t;t], [f;t;f;t], [Yff;Yft;Ytf;Ytt], nb, nb) + ... %% branch admittances\n            sparse(1:nb, 1:nb, Ysh, nb, nb);        %% shunt admittance\nelse                                %% large case running on MATLAB\n    %% build connection matrices\n    Cf = sparse(1:nl, f, ones(nl, 1), nl, nb);      %% connection matrix for line & from buses\n    Ct = sparse(1:nl, t, ones(nl, 1), nl, nb);      %% connection matrix for line & to buses\n\n    %% build Yf and Yt such that Yf * V is the vector of complex branch currents injected\n    %% at each branch's \"from\" bus, and Yt is the same for the \"to\" bus end\n    Yf = sparse(1:nl, 1:nl, Yff, nl, nl) * Cf + sparse(1:nl, 1:nl, Yft, nl, nl) * Ct;\n    Yt = sparse(1:nl, 1:nl, Ytf, nl, nl) * Cf + sparse(1:nl, 1:nl, Ytt, nl, nl) * Ct;\n\n    %% build Ybus\n    Ybus = Cf' * Yf + Ct' * Yt + ...            %% branch admittances\n            sparse(1:nb, 1:nb, Ysh, nb, nb);    %% shunt admittance\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/makeYbus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5596358863243729}}
{"text": "% DEMSPGP1DGP5 Do a simple 1-D regression after Snelson & Ghahramani's example.\n\n% GP\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'spgp1d';\nexperimentNo = 5;\n\n% load data\n[X, y] = mapLoadData(dataSetName);\n\n% Set up model\noptions = gpOptions('dtcvar');\noptions.numActive = 9;\noptions.optimiser = 'scg';\n\n% use the deterministic training conditional.\nq = size(X, 2);\nd = size(y, 2);\n\nmodel = gpCreate(q, d, X, y, options);\nmodel.X_u = randn(9, 1)*0.25 - 0.75;\nparams = gpExtractParam(model);\nmodel = gpExpandParam(model, params);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = gpOptimise(model, display, iters);\n\n% Save the results.\nmodelWriteResult(model, dataSetName, experimentNo);\n\n\ndemSpgp1dPlot\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gp/demSpgp1dGp5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5596358813198763}}
{"text": "function [Z]=rplus(X,Y)\n% \n% Replicating addition\n%\n% Does element by element operations on X and Y where non-same sized\n% dimensions are implicity wrapped round to match the size of the larger\n% to give a result matrix Z with size max(size(X),size(Y));\n%\n% In this case returns double array with X+Y\n%\n% See also repops, plus, minus\n%\n% Copyright 2006- by Jason D.R. Farquhar (jdrf@zepler.org)\n% Inspired by code by Douglas M. Schwarz & Aki Vehtari.\nZ=repop(X,'+',Y);\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/svm/repop/rplus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5594864186189193}}
{"text": "function calpak_test26 ( )\n\n%*****************************************************************************80\n%\n%% CALPAK_TEST26 tests JED_TO_YMDF_SAKA and YMDF_TO_JED_SAKA.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    16 March 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CALPAK_TEST26\\n' );\n  fprintf ( 1, '  For the Saka calendar:\\n' );\n  fprintf ( 1, '  JED_TO_YMDF_SAKA: JED -> YMDF.\\n' );\n  fprintf ( 1, '  YMDF_TO_JED_SAKA: YMDF -> JED.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  JED (in)    YMDF                JED (out)\\n' );\n  fprintf ( 1, '\\n' );\n\n  jed_epoch = epoch_to_jed_saka ( );\n\n  i = 0;\n\n  while ( 1 )\n\n    i = i + 1;\n    jed1 = jed_test ( i );\n\n    if ( jed1 < 0.0 )\n      break\n    end\n\n    if ( jed_epoch <= jed1 )\n\n      [ y2, m2, d2, f2 ] = jed_to_ymdf_saka ( jed1 );\n\n      s2 = ymdf_to_s_numeric ( y2, m2, d2, f2 );\n\n      jed3 = ymdf_to_jed_saka ( y2, m2, d2, f2 );\n\n      fprintf ( 1, '  %11.2f  %20s  %11.2f\\n', jed1, s2, jed3 );\n\n    end\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/calpak/calpak_test26.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355186, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5594864124649451}}
{"text": "function pass = test_laplacian(pref)\n% Test LAPLACIAN \n\nif ( nargin == 0 )\n    pref = chebfunpref; \nend\ntol = 50*pref.cheb3Prefs.chebfun3eps;\n\n% Check definition: \nF = chebfun3(@(x,y,z) cos(x.*z)+sin(y.*z));\nlapF = laplacian(F);\nlapF1 = diff(F, 2, 1) + diff(F, 2, 2) + diff(F, 2, 3);\npass(1) = norm(lapF1 - lapF) < tol;\n\n% Check definition: \nF = chebfun3(@(x,y,z) cos(x) + y.*z + z.^2);\nlapF = laplacian(F);\nlapF1 = diff(F, 2, 1) + diff(F, 2, 2) + diff(F, 2, 3);\npass(2) = norm(lapF1 - lapF) < tol;\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun3/test_laplacian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.5594864078774336}}
{"text": "close all; clear all;\n\n%% Setting of the problem\nglobal s\npde = fracLapdata8; \npde.L = 1;\noption.theta = 0.3;\noption.estType = 'star';\noption.maxIt = 17;\noption.maxN = 5e4;\noption.solver = 'mg';\noption.tol = 1e-6;\n[node,elem] = squaremesh([-1,1,-1,1],0.5);\nbdFlag = setboundary(node,elem,'Dirichlet');\n\n% %% s = 0.2\n% s = 0.2;\n% afemfracLap(node,elem,pde,bdFlag,option);\n% \n% %% s = 0.4\n% s = 0.4;\n% afemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.6\ns = 0.6;\nafemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.8\ns = 0.8;\nafemfracLap(node,elem,pde,bdFlag,option);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fracLaplacian/afemratefracLapdistribution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5593539483951011}}
{"text": "function [targetMissDist, dVNorm, hOrbit, dVVect, dVVectNTW, eRVect, xferOrbit, departUT, timeSOI] = departureTargetMissDistance(x, dVVectNTW, eOrbit, departBodyInfo, arriveBodyInfo, parentBodyInfo, departUT, arrivalUT)\n%UNTITLED Summary of this function goes here\n%   Detailed explanation goes here\n    eTru = x(1);\n    progradeDV = x(2);\n    dVVectNTW(1) = progradeDV;\n    \n    eSMA = eOrbit(1);\n    eEcc = eOrbit(2);\n    eInc = eOrbit(3);\n    eRAAN = eOrbit(4);\n    eArg = eOrbit(5);\n%     eTru = eOrbit(6);\n    \n    eTruAtDepartUT = eOrbit(6);\n    eMeanMotion = computeMeanMotion(eSMA, departBodyInfo.gm);\n    \n    eMean = computeMeanFromTrueAnom(eTru, eEcc);\n    eMeanAtDepartUT = computeMeanFromTrueAnom(eTruAtDepartUT, eEcc);\n    departDeltaTBurnPosAdjust = (eMean-eMeanAtDepartUT)/eMeanMotion;\n    departUT = departUT + departDeltaTBurnPosAdjust;\n\n    [eRVect,eVvect] = getStatefromKepler(eSMA, eEcc, eInc, eRAAN, eArg, eTru, departBodyInfo.gm);\n    tHat = eVvect/norm(eVvect);\n    wHat = cross(eRVect,eVvect)/norm(cross(eRVect,eVvect));\n    nHat = cross(tHat,wHat)/norm(cross(tHat,wHat));\n    ECI2TWNRotMat = [tHat,wHat,nHat];\n    dVVect = ECI2TWNRotMat * dVVectNTW;\n    dVNorm = norm(dVVect);\n    \n    hRVect = eRVect;\n    hVVect = eVvect + dVVect;\n    [hSMA, hECC, hINC, hRAAN, hARG, hTRU] = getKeplerFromState(hRVect,hVVect,departBodyInfo.gm);\n    hOrbit = [hSMA, hECC, hINC, hRAAN, hARG, hTRU];\n    \n    rSOI = getSOIRadius(departBodyInfo, parentBodyInfo);\n\n    hTruSOI = computeTrueAFromRadiusEcc(rSOI, hOrbit(1), hOrbit(2));\n    [rVectSOI,vVectSOI]=getStatefromKepler(hOrbit(1), hOrbit(2), hOrbit(3), hOrbit(4), hOrbit(5), hTruSOI, departBodyInfo.gm);\n    hOrbit(7) = hTruSOI;\n    \n    meanDepartTime = computeMeanFromTrueAnom(hOrbit(6), hOrbit(2));\n    meanSOITime = computeMeanFromTrueAnom(hTruSOI, hOrbit(2));\n    hMeanMotion = computeMeanMotion(hOrbit(1), departBodyInfo.gm);\n    deltaT2SOI = (meanSOITime-meanDepartTime)/hMeanMotion; \n    \n    timeSOI = departUT - deltaT2SOI; %may be a + sign here\n    [departBodyRVect, departBodyVVect] = getStateAtTime(departBodyInfo, timeSOI, parentBodyInfo.gm);\n    scInParentOrbitRVect = departBodyRVect + rVectSOI;\n    scInParentOrbitVVect = departBodyVVect + vVectSOI;\n    [smaXAct, eccXAct, incXAct, raanXAct, argXAct, truDXAct] = getKeplerFromState(scInParentOrbitRVect,scInParentOrbitVVect,parentBodyInfo.gm);\n    xferOrbit = [smaXAct, eccXAct, incXAct, raanXAct, argXAct, truDXAct];    \n    \n    bodyInfoXAct.sma = smaXAct;\n    bodyInfoXAct.ecc = eccXAct;\n    bodyInfoXAct.inc = rad2deg(incXAct);\n    bodyInfoXAct.raan = rad2deg(raanXAct);\n    bodyInfoXAct.arg = rad2deg(argXAct);\n    bodyInfoXAct.mean = computeMeanFromTrueAnom(truDXAct, eccXAct);\n    bodyInfoXAct.epoch = timeSOI;\n    \n    [rVectXAct, vVectXAct] = getStateAtTime(bodyInfoXAct, arrivalUT, parentBodyInfo.gm);\n    [~, ~, ~, ~, ~, truAXAct] = getKeplerFromState(rVectXAct,vVectXAct,parentBodyInfo.gm);\n    xferOrbit(7) = truAXAct;\n    [rVectArriveBody, ~] = getStateAtTime(arriveBodyInfo, arrivalUT, parentBodyInfo.gm);\n    targetMissDist = norm(rVectArriveBody-rVectXAct);\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/astrodynamics/departureTargetMissDistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.55932260708703}}
{"text": "function f1 = p06_f1 ( x )\n\n%*****************************************************************************80\n%\n%% P06_F1 evaluates the first derivative for problem 6.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 February 2002\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X, the value of the variable.\n%\n%    Output, real F1, the first derivative of the\n%    objective function.\n%\n  f1 = -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/p06_f1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.5593220458672755}}
{"text": "function intrec(Z)\n%INTREC Performs morphological character recognition\n%INTREC(X) recognizes the characters (in integer form) present in the\n%image X and displays it as output. INTREC uses morphological operations(like\n%Dilation and Hit-or-Miss transform) to recognize characters.The charecter\n%size of the integers present in the image should be exactly 26, otherwise \n%it may not recognize it.\n%\n%Example:\n%X=imread('testimage1.bmp');\n%imshow(X)\n%intrec(X)\n%The digits found in the image are:\n%0\n%3\n%5  \n%--------------------------------------------------------------------------\n%Authors: Jahanzeb Rajput and Mohammad Fahad\n%Department of Electrical Engineering\n%University of Engineering and Technology, Lahore, Pakistan.\n%--------------------------------------------------------------------------\n\nA= imread ('zero.bmp');\nB= imread ('one.bmp');\nC= imread ('two.bmp');\nD= imread ('three.bmp');\nE= imread ('four.bmp');\nF= imread ('five.bmp');\nG= imread ('six.bmp');\nH= imread ('seven.bmp');\nI= imread ('eight.bmp');\nJ= imread ('nine.bmp');\n%SE 2\nSE = strel('square',3);\n\nK=imdilate(A,SE);A2=K-A;\n\nL=imdilate(B,SE);B2=L-B;\n\nM=imdilate(C,SE);C2=M-C;\n\nN=imdilate(D,SE);D2=N-D;\n\nO=imdilate(E,SE);E2=O-E;\n\nP=imdilate(F,SE);F2=P-F;\n\nQ=imdilate(G,SE);G2=Q-G;\n\nR=imdilate(H,SE);H2=R-H;\n\nS=imdilate(I,SE);I2=S-I;\n\nT=imdilate(J,SE);J2=T-J;\n%-------------------------\n%Hit or Miss\n%-------------------------\ndisp('The digits found in the image are:');\nif ~isempty(nonzeros(bwhitmiss(Z,A,A2)))\n  disp('0');\nend\n%imshow('num1.bmp') \n%U=bwhitmiss(Z,F,F2);\n%figure\n%imshow(U)\nif ~isempty(nonzeros(bwhitmiss(Z,B,B2)))\n    disp('1');\nend\n\nif ~isempty(nonzeros(bwhitmiss(Z,C,C2)))\n   disp('2');\nend\n\nif ~isempty(nonzeros(bwhitmiss(Z,D,D2)))\n    disp('3');\nend\n\nif ~isempty(nonzeros(bwhitmiss(Z,E,E2)))\n   disp('4');\nend\n\nif ~isempty(nonzeros(bwhitmiss(Z,F,F2)))\n   disp('5');\nend\n\nif ~isempty(nonzeros(bwhitmiss(Z,G,G2)))\n   disp('6');\nend\n\nif ~isempty(nonzeros(bwhitmiss(Z,H,H2)))\n   disp('7');\nend\n\nif ~isempty(nonzeros(bwhitmiss(Z,I,I2)))\n   disp('8');\nend\n\nif ~isempty(nonzeros(bwhitmiss(Z,J,J2)))\n   disp('9');\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/9477-morphological-character-recognition/Intrecog/intrec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5593035626313269}}
{"text": "%function []=mcmc()\n\nclear all; clc;\n\n%% MCMC options\nnloop=110; % number of iterations for mcmcm\nburnin=10;  % number of initial iterations to discard\nthin=10;    % save every nth iteration \nM=4;        %number of group components desired\n\n\n%% set starting values for Z, S_BAR, SIGMA_S B_BAR SIGMA_B MU\nload real_data;\n[Z_st S_BAR_st SIGMA_S_st B_BAR_st SIGMA_B_st N_k_st N_k1k2_st]=get_initial_values_new(N,M_i,S,B,Q,M);\nZ=Z_st; % Mi x M matrices of group indicators\nS_BAR=S_BAR_st; % cluster centroid locations\nSIGMA_S=SIGMA_S_st; % cluster centroid variances\nB_BAR=B_BAR_st; % group level connectivities\nSIGMA_B=SIGMA_B_st; % variances of connectivities\nN_k=N_k_st; % number of components that belong to each cluster\nN_k1k2=N_k1k2_st; % pairwise counts of group level clusters\nMU=ones(M,1)/M; %probabilities of membership in group-level clusters.\n\n\n%% initialize arrays of posterior draws\nkeep=round((nloop-burnin)/thin);\nZ_array=cell(keep,1);\nS_BAR_array=cell(keep,1);\nSIGMA_S_array=cell(keep,1);\nB_BAR_array=cell(keep,1);\nSIGMA_B_array=cell(keep,1);\nMU_array=cell(keep,1);\niter_array=0;\n\n%%Hyperparameters\nc=10000;                    %'c' in the paper\neta=median(N_k_st);         % 'eta' in paper\nSS=eta*mean(SIGMA_S,3);     % 'S' in the paper\np1=1;                       % 'a' in the paper\np2=1;                       % 'b' in the paper\n\n\n%% run MCMC \n\nfor iter=1:nloop\n\n    % Draw S_BAR (group centroid locations)\n    for k=1:M\n        mu_s_bar_k=zeros(3,1);\n        Sigma_s_bar_k=inv(N_k(k)*inv(SIGMA_S(:,:,k))+inv(SS));\n        for i=1:N\n            if max(Z{i}(:,k))==1\n                j_k=find(Z{i}(:,k)==1);\n                for j=1:length(j_k)\n                    mu_s_bar_k=mu_s_bar_k+S{i}(j_k(j),:)';\n                end\n            end\n        end\n        mu_s_bar_k=Sigma_s_bar_k*inv(SIGMA_S(:,:,k))*mu_s_bar_k;\n        S_BAR(k,:)=mvnrnd(mu_s_bar_k,Sigma_s_bar_k);\n    end\n\n    \n    % Draw SIGMA_S (group centoid covariance matrices)\n    for k=1:M\n        eta_k=eta+.5*N_k(k);\n        SS_k=SS;\n        for i=1:N\n            if max(Z{i}(:,k))==1\n                j_k=find(Z{i}(:,k)==1);\n                for j=1:length(j_k)\n                    SS_k=SS_k+.5*(S{i}(j_k(j),:)-S_BAR(k,:))'*(S{i}(j_k(j),:)-S_BAR(k,:));\n                end\n            end\n        end\n        SS_k=.5*(SS_k+SS_k');\n        inv_SS_k=inv(SS_k);\n        inv_SS_k=.5*(inv_SS_k+inv_SS_k');\n        SIGMA_S(:,:,k)=inv(wishrnd(inv_SS_k,eta_k));\n    end  \n    \n    \n    % Draw B_BAR (group mean connectivites)\n    for k1=1:M\n        for k2=1:M\n            mu_b_bar_k1k2=zeros(Q,1);\n            Sigma_sq_b_k1k2=1/(1/c+N_k1k2(k1,k2)/SIGMA_B(k1,k2))*eye(Q);\n            for i=1:N\n                n_k1=sum(Z{i}(:,k1));\n                n_k2=sum(Z{i}(:,k2));\n                if(and(n_k1>=1,n_k2>=1))\n                    j_k1=find(Z{i}(:,k1)==1);\n                    j_k2=find(Z{i}(:,k2)==1);\n                    for j1=1:n_k1\n                        for j2=1:n_k2\n                            mu_b_bar_k1k2=mu_b_bar_k1k2+B{i}{j_k1(j1),j_k2(j2)}';\n                        end\n                    end\n                end\n            end\n            mu_b_bar_k1k2=Sigma_sq_b_k1k2*mu_b_bar_k1k2/SIGMA_B(k1,k2);\n            B_BAR{k1,k2}=mvnrnd(mu_b_bar_k1k2,Sigma_sq_b_k1k2);\n        end\n    end\n    \n    % Draw SIGMA_B (group connectivity variances)\n    for k1=1:M\n        for k2=1:M\n            p1_k1k2=p1+.5*Q*N_k1k2(k1,k2);\n            p2_k1k2=p2;\n            for i=1:N\n                n_k1=sum(Z{i}(:,k1));\n                n_k2=sum(Z{i}(:,k2));\n                if(and(n_k1>=1,n_k2>=1))\n                    j_k1=find(Z{i}(:,k1)==1);\n                    j_k2=find(Z{i}(:,k2)==1);\n                    for j1=1:n_k1\n                        for j2=1:n_k2\n                            p2_k1k2=p2_k1k2+.5*sum((B{i}{j_k1(j1),j_k2(j2)}-B_BAR{k1,k2}).^2);\n                        end\n                    end\n                end\n            end\n            SIGMA_B(k1,k2)=1/gamrnd(p1_k1k2,1/p2_k1k2);\n        end\n    end\n\n\n    % Draw Z (indicators of group membership)   \n    ind=randperm(N);\n    for i=ind\n        ind_i=randperm(M_i(i));\n        for j=ind_i\n            Log_p_ij=zeros(M,1);\n            for k=1:M\n                Sigma_s_ijk=SIGMA_S(:,:,k);\n                s_ijk=S{i}(j,:)-S_BAR(k,:);\n                log_p_s_ijk=-.5*log(det(Sigma_s_ijk))-.5*s_ijk*inv(Sigma_s_ijk)*s_ijk';\n                log_p_b_ijk=0;\n                for j1=1:M_i(i)\n                    if j==j1\n                        log_p_b_ijk=log_p_b_ijk-.5*Q*log(det(SIGMA_B(k,k)))...\n                        -.5*sum((B{i}{j,j}-B_BAR{k,k}).^2)/SIGMA_B(k,k);\n                    end\n                    if and(not(j==j1),find(Z{i}(j1,:)==1)==k)\n                        log_p_b_ijk=log_p_b_ijk-.5*Q*log(det(SIGMA_B(k,k)))...\n                        -.5*sum((B{i}{j1,j1}-B_BAR{find(Z{i}(j1,:)==1),find(Z{i}(j1,:)==1)}).^2)/...\n                            SIGMA_B(find(Z{i}(j,:)==1),find(Z{i}(j,:)==1));                    \n                    end\n                    if not(find(Z{i}(j,:)==1)==find(Z{i}(j1,:)==1))\n                        log_p_b_ijk=log_p_b_ijk-.5*Q*log(det(SIGMA_B(k,find(Z{i}(j1,:)==1))))...\n                        -.5*sum((B{i}{j,j1}-B_BAR{k,find(Z{i}(j1,:)==1)}).^2)/...\n                              SIGMA_B(k,find(Z{i}(j1,:)==1));\n                    end\n                end\n                for j2=1:M_i(i)\n                    if not(find(Z{i}(j2,:)==1)==find(Z{i}(j,:)==1))\n                        log_p_b_ijk=log_p_b_ijk-.5*Q*log(det(SIGMA_B(find(Z{i}(j2,:)==1),k)))...\n                        -.5*sum((B{i}{j2,j}-B_BAR{find(Z{i}(j2,:)==1),k}).^2)/...\n                                SIGMA_B(find(Z{i}(j2,:)==1),k);\n                    end\n                end\n                Log_p_ij(k)=MU(k)+log_p_s_ijk+log_p_b_ijk;\n            end\n            Log_p_ij=Log_p_ij-max(Log_p_ij);\n            P_ij=exp(Log_p_ij)/sum(exp(Log_p_ij));\n            v=rand;\n            Z{i}(j,:)=0*Z{i}(j,:);\n            if v<=P_ij(1)\n                   Z{i}(j,1)=1;\n                   log_p_ij=Log_p_ij(1);\n            end\n            for k=1:(M-1)\n               if(and(v>sum(P_ij(1:k)),v<=sum(P_ij(1:(k+1)))))\n                   Z{i}(j,k+1)=1;\n                   log_p_ij=Log_p_ij(k);\n               end\n            end\n        end\n    end\n\n    % Draw MU (probabilities of clusters)   \n    N_k1k2=zeros(M);\n    for k1=1:M\n        for k2=1:M\n            for i=1:N\n                n_k1=sum(Z{i}(:,k1));\n                n_k2=sum(Z{i}(:,k2));\n                if(and(n_k1>=1,n_k2>=1))\n                    if not(k1==k2)\n                        N_k1k2(k1,k2)=N_k1k2(k1,k2)+n_k1*n_k2;\n                    end                \n                    if k1==k2\n                        N_k1k2(k1,k2)=N_k1k2(k1,k2)+n_k1;\n                    end\n                end\n            end\n        end\n    end\n    N_k=diag(N_k1k2);\n    MU=drchrnd(1/M*ones(1,M)+N_k',1);\n\n    \n    % Posterior Draw arrays    \n    if and(iter>=burnin,thin*round(iter/thin)==iter)\n        iter_array=iter_array+1;\n        Z_array{iter_array}=Z;\n        S_BAR_array{iter_array}=S_BAR;\n        SIGMA_S_array{iter_array}=SIGMA_S;\n        B_BAR_array{iter_array}=B_BAR;\n        SIGMA_B_array{iter_array}=SIGMA_B;\n        MU_array{iter_array}=MU;\n\n        %compute and print out intermediate estimates of source locations\n        S_BAR_mean=S_BAR_array{1};\n        for j=2:iter_array\n            S_BAR_mean=S_BAR_mean+S_BAR_array{j};\n        end\n        S_BAR_mean=S_BAR_mean/iter_array;\n        iter\n        [S_BAR_st zeros(M,1) S_BAR_mean]\n        \n        %[sqrt(sum(min(pdist2(S_BAR_true,S_BAR_st)').^2))/M sqrt(sum(min(pdist2(S_BAR_true,S_BAR_mean)').^2))/M]\n      \n        %compute and print intermediate indicator probs for random subject\n        i=discretesample(repmat(1,N,1)/N,1);\n        Z_i_mean=Z_array{1}{i};\n        for j=2:iter_array\n           Z_i_mean=Z_i_mean+Z_array{j}{i};\n        end\n        Z_st{i}\n        Z_i_mean=Z_i_mean/iter_array\n    end\n        \n            \nend\n\nsave mcmc_outputs nloop M Z_array S_BAR_array SIGMA_S_array B_BAR_array SIGMA_B_array MU_array iter_array\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/grp/bayes/mcmc_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5593035603542638}}
{"text": "%rf_combineRF.m\n%Peter Truong, Sunnybrook Research Institute 2021.\n%\n% USAGE:\n% [rf,AMPINT]=rf_combineRF(rf_struct1,rf_struct2);\n% \n% DESCRIPTION:\n% Combines two similar rf waveforms (e.g. same pulse, but one frequency\n% shifted), in FID-A rf pulse structure format.\n% \n% INPUTS:\n% rf_struct1 = RF pulse definition structure.\n% rf_struct2 = RF pulse definition structure, similar to rf_struct1\n\n%\n% OUTPUTS:\n% rf         = Output rf waveform of the combined rf pulse, in FID-A rf \n%              pulse structure format.\n% AMPINT     = Calculated amplitude integral (for use in Siemens .pta files).\nfunction [rf,AMPINT]=rf_combineRF(rf_struct1,rf_struct2)\n\n%Convert waveforms to complex form\nrf1_waveform=rf_struct1.waveform(:,2).*exp(1i.*rf_struct1.waveform(:,1)*pi/180);\nrf2_waveform=rf_struct2.waveform(:,2).*exp(1i.*rf_struct2.waveform(:,1)*pi/180);\n\n%Here we compute the Amplitude integral(AMPINT), which is used by magnetom\n%to calculate the transmitter power that is required in order to achieve\n%the desired flip angle\nrf1_waveform_scaled=rf1_waveform./max(abs(rf1_waveform));\nAI=sum(rf1_waveform_scaled);\n\ncombined_waveform=rf1_waveform + rf2_waveform;\ncombined_waveform_scaled=combined_waveform./max(abs(combined_waveform));\nAMPINT=AI./max(abs(combined_waveform_scaled));\n\nrf=rf_struct1;\nrf.waveform(:,1)=phase(combined_waveform_scaled).*180/pi;\nrf.waveform(:,2)=abs(combined_waveform_scaled);\n\n% updating time-bandwidth product & time-w1max product\nrf.tbw=rf_struct1.tbw+rf_struct2.tbw;\nrf.tw1=rf_struct1.tw1+rf_struct2.tw1;\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/rfPulseTools/rf_combineRF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5593035535230744}}
{"text": "function [R,theta] = round_sra(X,opt)\n%% Given the moment matrix X, round R and theta from X\nif nargin < 2\n    opt = 1;\nend\nX     = X{1};\nn     = size(X,1);\nN     = round((n-10)/10);\n[V,D] = eig(X);\n[~,I] = sort(diag(D),'descend');\nV     = V(:,I);\n%% take the opt-th eigenvector\nnropt = length(opt);\nx     = V(:,opt);\nR     = zeros(3,3,nropt);\ntheta = zeros(N,nropt);\nfor k = 1:nropt\n    xk    = x(:,k);\n    xk    = xk/xk(1);\n    %% round that eigenvector\n    Rk    = reshape( xk(1+blkIndices(1,9)),3,3 );\n    Rk    = project2SO3(Rk);\n    \n    thetak= sign( xk(10+1:10+N) );\n    thetak(thetak==0) = 1;\n    \n    R(:,:,k)     = Rk;\n    theta(:,k)   = thetak;\nend\nend", "meta": {"author": "MIT-SPARK", "repo": "CertifiablyRobustPerception", "sha": "dd149d0c54093cfb72a8f912f4ae807635db6f3b", "save_path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception", "path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception/CertifiablyRobustPerception-dd149d0c54093cfb72a8f912f4ae807635db6f3b/SingleRotationAveraging/solvers/round_sra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5593035430982569}}
{"text": "%% FUNCTION Least_Weight2FGLasso\n%   Weighted Fused Group Lasso and Weighted Lasso with Least Squares Loss .\n%\n%% OBJECTIVE\n%   argmin_W { \\sum_i^t (0.5 * norm (Y{i} - X{i}' * W(:, i))^2)\n%              + \\sum_{i=1}^d rho1{i} * \\|W(i, :)\\|_1\n%              + \\sum_{i=1}^d rho2{i} \\sum_{j=1}^{t-1}* \\|W(i, j) - W(i, j+1)\\|_1\n%          }\n%   rho1: weighted Lasso sparse.\n%   rho2: weighted Fused Lasso.\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% rho1: d * 1    - weighted Lasso.\n% rho2: d * 1    - weighted fused Lasso.\n%\n%% OUTPUT\n% W: model: d * t\n% funcVal: function value vector.\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 <http://www.gnu.org/licenses/>.\n%\n%   Copyright (C) 2011 - 2012 Jiayu Zhou, Jun Liu 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 June 3, 2012.\n%\n%% RELATED PAPERS\n%\n%   [1] Zhou, J., Jun, L., Narayan, A. V. and Ye, J.  Modeling Disease\n%   Progression via Fused Sparse Group Lasso. KDD 2012\n%\n%% RELATED FUNCTIONS\n%   Least_NCFGLasso, init_opts\n\nfunction [W, funcVal] = Least_Weight2FGLasso(X, Y, rho1, rho2, opts)\n\n\nif nargin <5\n    opts = [];\nend\n\n% initialize options.\nopts=init_opts(opts);\n\n\ntask_num  = length (X);\ndimension = size(X{1}, 1);\n\nif length(rho1) ~= dimension\n    error('Size of rho1 is not correct! Should be equivalent to dimension')\nend\n\nif length(rho2) ~= dimension\n    error('Size of rho2 is not correct! Should be equivalent to dimension')\nend\n\nfuncVal = [];\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% initialize a starting point\nif opts.init==2\n    W0 = zeros(dimension, task_num);\nelseif opts.init == 0\n    W0 = W0_prep;\nelse\n    if isfield(opts,'W0')\n        W0=opts.W0;\n        if (nnz(size(W0)-[dimension, task_num]))\n            error('\\n Check the input .W0');\n        end\n    else\n        W0=W0_prep;\n    end\nend\n\nbFlag=0; % this flag tests whether the gradient step only changes a little\n\n\nWz= W0;\nWz_old = W0;\n\nt = 1;\nt_old = 0;\n\niter = 0;\ngamma = 1;\ngamma_inc = 2;\n\nwhile iter < opts.maxIter\n    alpha = (t_old - 1) /t;\n    \n    Ws = (1 + alpha) * Wz - alpha * Wz_old;\n    \n    % compute function value and gradients of the search point\n    gWs  = gradVal_eval(Ws);\n    Fs   = funVal_eval (Ws);\n    \n    while true\n        Wzp = ReweightFGLasso_projection(Ws - gWs/gamma, rho1 ./ gamma, rho2 ./ gamma);\n        Fzp = funVal_eval  (Wzp);\n        \n        delta_Wzp = Wzp - Ws;\n        r_sum = norm(delta_Wzp, 'fro')^2;\n        %         Fzp_gamma = Fs + trace(delta_Wzp' * gWs)...\n        %             + gamma/2 * norm(delta_Wzp, 'fro')^2;\n        Fzp_gamma = Fs + sum(sum(delta_Wzp.* gWs))...\n            + gamma/2 * r_sum;\n        \n        if (Fzp <= Fzp_gamma)\n            break;\n        else\n            gamma = gamma * gamma_inc;\n        end\n    end\n    \n    Wz_old = Wz;\n    Wz = Wzp;\n    \n    funcVal = cat(1, funcVal, Fzp + nonsmooth_eval(Wz, rho1, rho2));\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    % test stop condition.\n    switch(opts.tFlag)\n        case 0\n            if iter>=2\n                if (abs( funcVal(end) - funcVal(end-1) ) <= opts.tol)\n                    break;\n                end\n            end\n        case 1\n            if iter>=2\n                if (abs( funcVal(end) - funcVal(end-1) ) <=...\n                        opts.tol* funcVal(end-1))\n                    break;\n                end\n            end\n        case 2\n            if ( funcVal(end)<= opts.tol)\n                break;\n            end\n        case 3\n            if iter>=opts.maxIter\n                break;\n            end\n    end\n    \n    iter = iter + 1;\n    t_old = t;\n    t = 0.5 * (1 + (1+ 4 * t^2)^0.5);\n    \nend\n\nW = Wzp;\n\n% private functions\n\n    function [Wp] = ReweightFGLasso_projection (W, lambda_1, lambda_2)\n        % solve it in row wise, since that\n        % \\sum_i^d rho1{i} * \\|W(i, :)\\|_1 is row coupled.\n        % for each row we need to solve the proximal opterator\n        % W(i, :) = argmin_w { 0.5 \\|w - v\\|_2^2\n        %            + lambda_1{i} * \\|w\\|_1\n        %            + lambda_2{i} * \\|R * w\\|_1 }\n        % NOTE: Here the R is t-1 * t, the outside R is t * t-1, and\n        Wp = zeros(size(W));\n        \n        for i = 1 : size(W, 1)\n            v = W(i, :);\n            \n            w0 = zeros(length(v)-1, 1);\n            w = flsa(v, w0,  lambda_1(i), lambda_2(i), length(v), 1000, 1e-9, 1, 6);\n            \n            Wp(i, :) = w';\n        end\n    end\n\n% smooth part gradient.\n    function [grad_W] = gradVal_eval(W)\n        if opts.pFlag\n            grad_W = zeros(size(W));\n            parfor i = 1:task_num\n                grad_W(:, i) = X{i}*(X{i}' * W(:,i)-Y{i});\n            end\n        else\n            grad_W = [];\n            for i = 1:task_num\n                grad_W = cat(2, grad_W, X{i}*(X{i}' * W(:,i)-Y{i}) );\n            end\n        end\n    end\n\n% smooth part gradient.\n    function [funcVal] = funVal_eval (W)\n        funcVal = 0;\n        if opts.pFlag\n            parfor i = 1: task_num\n                funcVal = funcVal + 0.5 * norm (Y{i} - X{i}' * W(:, i))^2;\n            end\n        else\n            for i = 1: task_num\n                funcVal = funcVal + 0.5 * norm (Y{i} - X{i}' * W(:, i))^2;\n            end\n        end\n    end\n\n    function [non_smooth_value] = nonsmooth_eval(W, rho_1, rho_2)\n        non_smooth_value = 0;\n        for i = 1 : size(W, 1)\n            w = W(i, :);\n            non_smooth_value = non_smooth_value ...\n                + rho_1(i) * norm(w, 1) + rho_2(i) * norm(R * 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_Weight2FGLasso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.559303537227566}}
{"text": "function Derive_EoM()\n% Derive_EoM()\n%\n% This function generates the equations of motion for what I will call the \n% \"Retractable Double Pendulum\" model of walking. It uses the Matlab\n% symbolic toolbox to generate the equations of motion, and then\n% automatically writes them to a file. \n%\n% The model consists of a point mass at each foot and at the hip. The feet\n% are connected to this hip by an extensible, actuated, leg. Each foot has\n% an 'ankle actuator' to provide a control torque, and there is another\n% torque actuator at the hip, connecting the two legs.\n%\n% Written by Matthew Kelly\n% November 29, 2013\n% Cornell University\n%\n% See also WRITE_CONTINUOUSDYNAMICS\nclc; clear; commandwindow;\naddpath ../Shared\nDirectory = '../computerGeneratedCode';  %Write all code in this directory\ndisp('Running Derive_EoM...')\ndisp(' -> Defining Model');\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                             Model                                       %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% This model of walking is comprised of three point masses: one at each\n% foot and one at the hip. The equations are derived for three phases of\n% motion: Flight, Single Stance, and Double Stance. The lets in this\n% walking model are massless and have variable length. There are five\n% controls available to the system: force actuator in each leg, foot torque\n% when foot is in contact with the ground, and hip torque. There are six\n% degrees of freedom in this model: position of foot one (x1,y1), position\n% of the hip (x0,y0), and position of foot two (x2, y2).\n\n% The position of the hip\nx0 = sym('x0','real'); % Horizontal position of the hip\ny0 = sym('y0','real'); % Vertical position of the hip\n\n% The position of foot one\nx1 = sym('x1','real'); % Horizontal position of foot one\ny1 = sym('y1','real'); % Vertical position of foot one\n\n% The position of foot two\nx2 = sym('x2','real'); % Horizontal position of foot two\ny2 = sym('y2','real'); % Vertical position of foot two\n\n% Each leg has a small mass at the foot and a large mass at the hip. Since\n% the two hip masses are coincident, they are treated as a single mass. \nm1 = sym('m1','real');  % Mass of foot one\nm2 = sym('m2','real');  % Mass of foot two\nM = sym('M','real');  % Mass of the hip of the robot \n\n% The system experiences a constant gravitational acceleration:\ng = sym('g','real');\n\n% Axial Force along each leg. This force is considered to be an actuator \n% input to the system. Compression is positive.\nF1 = sym('F1','real'); % Force in the stance leg\nF2 = sym('F2','real'); % Force in the swing leg\n\n% Constraint force normal to each leg. Connects ankle torques to system\nN1 = sym('N1','real'); % Constraint force at foot one\nN2 = sym('N2','real'); % constraint force between legs\n\n% There is a torque motor connecting the two legs, and an ankle motor on\n% the stance leg.\nT1 = sym('T1','real'); % Ankle Torque, acting on leg one\nT2 = sym('T2','real'); % Ankle Torque, acting on leg two\nThip = sym('Thip','real'); % Hip torque. From leg one acting on leg two\n\n% Ground contact forces at each foot\nH1 = sym('H1','real'); % Horizontal contact force at foot one\nV1 = sym('V1','real'); % Vertical contact force at foot one\nH2 = sym('H2','real'); % Horizontal contact force at foot two\nV2 = sym('V2','real'); % Vertical contact force at foot wto\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                        State Derivatives                                %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% The first time derivative of each state. These are considered known.\n% The position of the hip\ndx0 = sym('dx0','real'); % Horizontal velocity of the hip\ndy0 = sym('dy0','real'); % Vertical velocity of the hip\ndx1 = sym('dx1','real'); % Horizontal velocity of foot one\ndy1 = sym('dy1','real'); % Vertical velocity of foot one\ndx2 = sym('dx2','real'); % Horizontal velocity of foot two\ndy2 = sym('dy2','real'); % Vertical velocity of foot two\n\n% The second time derivative of each state. Goal is to find these.\nddx0 = sym('ddx0','real'); % Horizontal acceleration of the hip\nddy0 = sym('ddy0','real'); % Vertical acceleration of the hip\nddx1 = sym('ddx1','real'); % Horizontal acceleration of foot one\nddy1 = sym('ddy1','real'); % Vertical acceleration of foot one\nddx2 = sym('ddx2','real'); % Horizontal acceleration of foot two\nddy2 = sym('ddy2','real'); % Vertical acceleration of foot two\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                 Coordinate System & Kinematics                          %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% Inertial reference frame:\ni = [1;0;0];  %Positive horizontal axis\nj = [0;1;0];  %Positive vertical axis\nk = [0;0;1];  %Positive lateral axis\n\n%Relative change in each ordinate along the legs\nX1 = (x1-x0); dX1 = (dx1-dx0);\nY1 = (y1-y0); dY1 = (dy1-dy0);\nX2 = (x2-x0); dX2 = (dx2-dx0);\nY2 = (y2-y0); dY2 = (dy2-dy0);\n\n%length of both legs:\n% This is a commonly used expression that is costly to calculate, so I\n% numerically calculate it as an intermediate step.\nL1 = sym('L1','real');\nL2 = sym('L2','real');\ndL1 = sym('dL1','real');\ndL2 = sym('dL2','real');\n\n%Angles of both legs, as measured in the k direction from the -j axis:\n% th1 = sym('th1','real');\n% th2 = sym('th2','real');\ndth1 = sym('dth1','real');\ndth2 = sym('dth2','real');\n\n% Matlab symbolic toolbox was not being friendly, so I did a small amount\n% of the math out by hand. I believe the following to be true:\n% \n%  L^2 = x^2 + y^2\n% (d/dt)(L) = (x*dx + y*dy)/L\n% (d/dt)(atan2(x,y)) = (dx*y - x*dy)/L^2\n%\n\n\nKinematics.L1 = sqrt(X1^2 + Y1^2);\nKinematics.L2 = sqrt(X2^2 + Y2^2);\n\nKinematics.dL1 = (X1*dX1 + Y1*dY1)/L1;\nKinematics.dL2 = (X2*dX2 + Y2*dY2)/L2;\n\nKinematics.th1 = atan2(X1,Y1);\nKinematics.th2 = atan2(X2,Y2);\nKinematics.dth1 = (dX1*Y1 - X1*dY1)/L1^2;\nKinematics.dth2 = (dX2*Y2 - X2*dY2)/L2^2;\n\n\n% Unit vectors pointing from the hip to foot one (a1) and it's normal (b1)\na1 = (X1*i + Y1*j)/L1;\nb1 = (-Y1*i + X1*j)/L1;\n\n% Unit vectors pointing from the hip to foot two (a2) and it's normal (b2)\na2 = (X2*i + Y2*j)/L2;\nb2 = (-Y2*i + X2*j)/L2;\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                        Position Vectors                                 %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% Point 0 = Hip\n% Point 1 = Foot One\n% Point 2 = Foot Two\n\nr0 = x0*i + y0*j;         % Position of Hip(Absolute)\nr1 = x1*i + y1*j;         % Position of Foot One (Absolute)\nr2 = x2*i + y2*j;         % Position of Foot Two (Absolute)\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                      Position Derivatives                               %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\ndr0 = dx0*i + dy0*j;         % Velocity of Hip(Absolute)\ndr1 = dx1*i + dy1*j;         % Velocity of Foot One (Absolute)\ndr2 = dx2*i + dy2*j;         % Velocity of Foot Two (Absolute)\n\nddr0 = ddx0*i + ddy0*j;         % Acceleration of Hip(Absolute)\nddr1 = ddx1*i + ddy1*j;         % Acceleration of Foot One (Absolute)\nddr2 = ddx2*i + ddy2*j;         % Acceleration of Foot Two (Absolute)\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                Linear Momentum Balance on Foot One                      %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nsum_of_forces = simplify(V1*j + H1*i + N1*b1 - m1*g*j + F1*a1);\nlinear_momentum_rate = m1*ddr1;\n\nLMB_F1 = simplify(sum_of_forces - linear_momentum_rate);\nLMB_F1_i = dot(LMB_F1,i);\nLMB_F1_j = dot(LMB_F1,j);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                Linear Momentum Balance on Foot Two                      %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nsum_of_forces = simplify(V2*j + H2*i + N2*b2 - m2*g*j + F2*a2);\nlinear_momentum_rate = m2*ddr2;\n\nLMB_F2 = simplify(sum_of_forces - linear_momentum_rate);\nLMB_F2_i = dot(LMB_F2,i);\nLMB_F2_j = dot(LMB_F2,j);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                Linear Momentum Balance on Hip                           %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nsum_of_forces = simplify(-F1*a1 - N1*b1 - F2*a2 - N2*b2 - M*g*j);\nlinear_momentum_rate = M*ddr0;\n\nLMB_H = simplify(sum_of_forces - linear_momentum_rate);\nLMB_H_i = dot(LMB_H,i);\nLMB_H_j = dot(LMB_H,j);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%               Angular Momentum Balance on Leg One                       %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nsum_of_torques = (T1 + Thip - N1*L1)*k;\nangular_momentum_rate = 0*k;   %Leg One has no mass\n\nAMB_L1_k = dot(simplify(sum_of_torques - angular_momentum_rate),k);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%               Angular Momentum Balance on Leg One                       %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nsum_of_torques = (T2 - Thip - N2*L2)*k;\nangular_momentum_rate = 0*k;   %Leg Two has no mass\n\nAMB_L2_k = dot(simplify(sum_of_torques - angular_momentum_rate),k);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%      Collect Implicit Equations of Motion and Phase constraints         %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% All phases of motion share these equations. An additional four equations\n% are required to solve the system, which come from the 'definition' of\n% each phase of motion.\n\nPhysics = [         LMB_F1_i;\n                    LMB_F1_j;\n                    LMB_F2_i;\n                    LMB_F2_j;\n                    LMB_H_i;\n                    LMB_H_j;\n                    AMB_L1_k;\n                    AMB_L2_k    ]; \n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                        Solve Flight Dynamics                            %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% During flight, the contact forces are all equal to zero. Treat as knowns.              \n% %             H1==0;\n% %             V1==0;\n% %             H2==0;\n% %             V2==0;   \n\nUnknowns = [    ddx0;    ddy0;    \n                ddx1;    ddy1;  \n                ddx2;    ddy2;    \n                N1;     N2];    \n\ndisp(' -> Solving Flight Dynamics')\nSoln = jacobSolve(Physics,Unknowns);\n\nDyn.Flight = Soln;\nDyn.Flight.H1 = sym('0');\nDyn.Flight.V1 = sym('0');\nDyn.Flight.H2 = sym('0');\nDyn.Flight.V2 = sym('0');\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                 Solve Single Stance One Dynamics                        %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% During single stance one, contact forces at Foot Two are equal to zero. \n% Additionally, we know that the velocity and acceleration of Foot One are\n% both also equal to zero.\n% %             ddx1==0;\n% %             ddy1==0;\n% %             H2==0;\n% %             V2==0;  \n\nUnknowns = [    ddx0;   ddy0;    \n                H1;     V1  \n                ddx2;   ddy2;    \n                N1;     N2];      \n\ndisp(' -> Solving Single Stance One Dynamics')\nSoln = jacobSolve(Physics,Unknowns);\n\nDyn.SingleOne = Soln;\nDyn.SingleOne.ddx1 = sym('0');\nDyn.SingleOne.ddy1 = sym('0');\nDyn.SingleOne.H2 = sym('0');\nDyn.SingleOne.V2 = sym('0');\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                 Solve Single Stance Two Dynamics                        %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% During single stance two, contact forces at Foot One are equal to zero. \n% Additionally, we know that the velocity and acceleration of Foot Two are\n% both also equal to zero.\n%\n%             ddx2 == 0;   \n%             ddy2 == 0;\n%             H1==0;\n%             V1==0;  \n\nUnknowns = [    ddx0;   ddy0;    \n                ddx1;   ddy1;  \n                H2;     V2;    \n                N1;     N2];     \n                  \n        \ndisp(' -> Solving Single Stance Two Dynamics')\nSoln = jacobSolve(Physics,Unknowns);\n\nDyn.SingleTwo = Soln;\nDyn.SingleTwo.ddx2 = sym('0');\nDyn.SingleTwo.ddy2 = sym('0');\nDyn.SingleTwo.H1 = sym('0');\nDyn.SingleTwo.V1 = sym('0');\n\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                   Solve Double Stance Dynamics                          %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% During double stance, both feet remain stationary. \n% Additionally, we know that the velocity and acceleration of Foot One are\n% both also equal to zero.\n%               ddx1 == 0;\n%               ddy1 == 0;\n%               ddx2 == 0;\n%               ddy2 == 0;\n\n% In Double Stance, Both feet remain stationary. Add constraint equation.\n% Note that the constraint is on acceleration, NOT velocity. This means\n% that these equations will only yield the desired solutions if the initial\n% velocity of Foot Two == 0;\n\n\nUnknowns = [    ddx0;   ddy0  \n                N1;     N2;     \n                H1;     V1;     \n                H2;     V2];    \n\ndisp(' -> Solving Double Stance Dynamics')\nSoln = jacobSolve(Physics,Unknowns);\n\nDyn.Double = Soln;\nDyn.Double.ddx1 = sym('0');\nDyn.Double.ddy1 = sym('0');\nDyn.Double.ddx2 = sym('0');\nDyn.Double.ddy2 = sym('0');\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%              Write Continuous Dynamics Function Files                   %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\ndisp(' -> Writing Continuous Dynamics Functions')\n\nStates = cell(12,2);\nStates(1,:) = {'x0','(m) Hip horizontal position'};\nStates(2,:) = {'y0','(m) Hip vertical position'};\nStates(3,:) = {'x1','(m) Foot One horizontal position'};\nStates(4,:) = {'y1','(m) Foot One vertical position'};\nStates(5,:) = {'x2','(m) Foot Two horizontal position'};\nStates(6,:) = {'y2','(m) Foot Two vertical position'};\n\nStates(7,:) = {'dx0','(m/s) Hip horizontal velocity'};\nStates(8,:) = {'dy0','(m/s) Hip vertical velocity'};\nStates(9,:) = {'dx1','(m/s) Foot One horizontal velocity'};\nStates(10,:) = {'dy1','(m/s) Foot One vertical velocity'};\nStates(11,:) = {'dx2','(m/s) Foot Two horizontal velocity'};\nStates(12,:) = {'dy2','(m/s) Foot Two vertical velocity'};\n\nContacts = cell(4,2);\nContacts(1,:) = {'H1','(N) Foot One, horizontal contact force'};\nContacts(2,:) = {'V1','(N) Foot One, vertical contact force'};\nContacts(3,:) = {'H2','(N) Foot Two, horizontal contact force'};\nContacts(4,:) = {'V2','(N) Foot Two, vertical contact force'};\n\nActuators = cell(5,2);\nActuators(1,:) = {'F1','(N) Compresive axial force in Leg One'};\nActuators(2,:) = {'F2','(N) Compresive axial force in Leg Two'};\nActuators(3,:) = {'T1','(Nm) External torque applied to Leg One'};\nActuators(4,:) = {'T2','(Nm) External torque applied to Leg Two'};\nActuators(5,:) = {'Thip','(Nm) Torque acting on Leg Two from Leg One'};\n\nParameters = cell(4,2);\nParameters(1,:) = {'m1','(kg) Foot One mass'};\nParameters(2,:) = {'m2','(kg) Foot Two mass'};\nParameters(3,:) = {'M','(kg) Hip mass'};\nParameters(4,:) = {'g','(m/s^2) Gravity'};\n\nCommonExpressions = cell(2,2);\nCommonExpressions(1,:) = {'L1s','L1.^2'};\nCommonExpressions(2,:) = {'L2s','L2.^2'};\n\nFileData = cell(3,4);\nFileData(1,:) = {'Flight','dynamics_flight',...\n    'Dymanics Model: retractable double pendulum biped',...\n    'Motion Phase: Flight'};\nFileData(2,:) = {'SingleOne','dynamics_singleStanceOne',...\n    'Dymanics Model: retractable double pendulum biped',...\n    'Motion Phase: Single Stance One'};\nFileData(3,:) = {'SingleTwo','dynamics_singleStanceTwo',...\n    'Dymanics Model: retractable double pendulum biped',...\n    'Motion Phase: Single Stance Two'};\nFileData(4,:) = {'Double','dynamics_doubleStance',...\n    'Dymanics Model: retractable double pendulum biped',...\n    'Motion Phase: Double Stance'};\n\nFileWritingSetup = Make_Struct(Dyn,States,Contacts,Actuators,...\n    Kinematics,CommonExpressions,Parameters,FileData,Directory);\n\nWrite_ContinuousDynamics(FileWritingSetup);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                          Find System Energy                             %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nEnergy.Potential.m1 = simplify(m1*g*dot(r1,j));\nEnergy.Potential.m2 = simplify(m2*g*dot(r2,j));\nEnergy.Potential.M = simplify(M*g*dot(r0,j));\n\nEnergy.Kinetic.m1 = simplify(0.5*m1*norm(dr1).^2);\nEnergy.Kinetic.m2 = simplify(0.5*m2*norm(dr2).^2);\nEnergy.Kinetic.M = simplify(0.5*M*norm(dr0)^2);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                         Write Energy Function                           %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\ndisp(' -> Writing Kinematics Function')\n\nFileWritingSetup = Make_Struct(Energy,States,Parameters,Directory);\n\nWrite_Energy(FileWritingSetup);\n\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                          Write Power Function                           %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\ndisp(' -> Writing Actuator Power Function')\n\nPower.legOne = F1*dL1;\nPower.legTwo = F2*dL2;\nPower.ankleOne = T1*dth1;\nPower.ankleTwo = T2*dth2;\nPower.hip = Thip*(dth2-dth1);\n\nFileWritingSetup = Make_Struct(Power,Kinematics,...\n    States,Actuators,Directory);\n\nWrite_ActuatorPower(FileWritingSetup);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                          Write Kinematics Function                           %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\ndisp(' -> Writing Kinematics Function')\n\nFileWritingSetup = Make_Struct(Kinematics, States, Directory);\n\nWrite_Kinematics(FileWritingSetup);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                             Impact Equations                            %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% Assume that any transitions between phases can be modeled by external\n% impluses being applied to either Foot One or Foot Two. \n%\n% Each of the point masses in the model is connected to the others through\n% force and torque actuators. Assume that at any instant in time there is a\n% finite force or torque being provided by each of those actuators. In the\n% limit as the duration of the impact goes to zero, the impulse transfered\n% across those actuators also goes to zero.\n%\n% Thus, I conclude that the collision maps can be applied by solving the\n% kinematic constraints before and after the collision.\n%\n% Since the masses in this system are essientally decoupled from eachother\n% as far as impacts are concerned, the impact map can be simplified to the\n% following statement: \"The state is unchanged, except for the velocity of\n% the mass that strikes the ground, which should go to zero\".\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                    Write Impact Map Function Files                      %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\ndisp(' -> Writing Phase Map Function')\n\nFileWritingSetup = ...\n    Make_Struct(States, Directory);\n\nWrite_PhaseMap(FileWritingSetup);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n%                    Write Conversion Function                            %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\ndisp(' -> Writing Conversion Function')\n\nFileWritingSetup = Make_Struct(States,Actuators,Contacts,Directory);\n\nWrite_Convert(FileWritingSetup);\n\ndisp('DONE!');\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%                    SUB-FUNCTIONS                                  %%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nfunction Soln = jacobSolve(Equations,Unknowns)\n%\n% FUNCTION: \n%   Solve a nonlinear system of equations by assuming that it is linear in\n%   the unknown variables (which is true for these mechanics problems)\n%\n% ARGUMENTS:\n%   Equations = [Nx1] vector of symbolic expressions that are equal to zero\n%   Unknowns = [Nx1] vector of symbolic variables to solve Equations for\n%\n% RETURNS:\n%   Soln = a struct with a field for each unknown\n%\n% The matlab solve command seems to have a problem with solving large\n% systems of non-linear equations. In the case of classical mechanics\n% problems, it turns out that these systems are not too hard to solve\n% because they are actually linear in the accelerations and constraint\n% forces. Assuming that this is true, then you can transform the equations\n% into a linear system by taking partial derivatives. Once this step is\n% done, then matlab does a great job of solving the linear system.\n%\n% MATH:\n%   Equations = 0;                  % By Definition\n%   Equations = A*x + b;            % Assume: form, A independant* of x\n%   A = jacobian(Equations wrt x);  % \n%   b = Equations - A*x;            %\n%   0 = A*x + b;                    %\n%   x = -A\\b;                       % Solved!\n%\n\nA = simplify(jacobian(Equations,Unknowns));\nb = simplify(Equations - A*Unknowns);\nx = simplify(-A\\b);\n\nfor i=1:length(Unknowns)\n   Soln.(char(Unknowns(i))) = x(i); \nend\n\nend\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/FancyDoublePendulum/Cartesian/Derive_Equations_of_Motion/Derive_EoM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5592229764603408}}
{"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%==============================================================================\n%\n% Tutorial for FAIR:  rotating an US image\n%\n%   - load US data\n%   - set image viewer and interpolator and trafo=rigid2D\n%   - run a loop over different angles\n%==============================================================================\n\nclear, close all, help(mfilename)\n\n%% load data\nTdata = double(imread('US.jpg'));\nomega = [0,size(Tdata,1),0,size(Tdata,2)];\nm     = [192,128] ;\nxc    = getCellCenteredGrid(omega,m);\n\n% setup interpolation scheme and image viewer\nimgModel('reset','imgModel','linearInter');\nviewImage('reset','viewImage','viewImage2D','colormap',gray(256),'axis','off');\nfprintf('%20s : %s\\n','viewImage',viewImage);\nfprintf('%20s : %s\\n','image model',imgModel);\n\n% shortcuts for plotting stuff\nGrid   = @(X)   plotGrid(X,omega,m,'spacing',8,'color','w');\ndimstr = @(m)   sprintf('%s=[%s]',inputname(1),sprintf(' %d',m));\nTitle  = @(s,t) title([s,sprintf(', t=%s',num2str(t))],'fontsize',30);\n\n\n%% display initial image\nFAIRfigure(1,'figname',mfilename); clf; subplot(1,2,1); \nviewImage(imgModel(Tdata,omega,xc),omega,m); hold on; gh = Grid(xc);\ntitle(sprintf('%s, %s','data',dimstr(m)),'fontsize',30);\n\n%% initialize transformation\ntrafo('set','trafo','rigid2D');\nS = @(t) t/6;\n\n% y(t) = R(t)*x+(I-R(t))*c, \n%\n% R(t) = [cos(t) -sin(t) ], c = [omega(1)]/2\n%        [sin(w)  cos(t) ]      [omega(2)]\n%\n% or y(t) = rigid2D(w,x), where w = [t;(I-R(t))omega'/2].\nc  = (omega(2:2:end)+omega(1:2:end))'/2\nwc = @(t) [t;(eye(2)-[ cos(t),-sin(t);sin(t),cos(t)])*c];\n  \n%=======================================================================================\n% the loop over time t\n%=======================================================================================\nt = 0.35*pi*sin(linspace(0,2.5*pi,101));\n\nfor j=1:length(t),\n  yc = trafo(wc(t(j)),xc);      % compute the transformed points\n  Tc = imgModel(Tdata,omega,yc);   % compute the transformed image\n\n  if j == 1,              % initialize visualization\n    figure(1); subplot(1,2,1); %colordef(gcf,'black');\n    set(gh,'visible','off'); gh = Grid(yc);\n    title(sprintf('%s, %s','data',dimstr(m)),'fontsize',30);\n    subplot(1,2,2); vh = viewImage(Tc,omega,m); Title(trafo,t(j));\n    FAIRpause;\n  else,                   % continue plots\n    subplot(1,2,1); set(gh,'visible','off');        gh = Grid(yc);\n    axis(omega)\n    subplot(1,2,2); set(vh,'cdata',reshape(Tc,m)'); Title(trafo,t(j));\n    FAIRpause(1/2000)\n  end;\n  drawnow; fprintf('.'); if rem(j,50) == 0, fprintf('\\n'); end;\nend;\nfprintf('\\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/E4_US_rotation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5592229676036489}}
{"text": "function [ correlations, rms, mean_correlation, mean_RMSE, long_correlation, long_RMSE, predictions, gts ] = evaluate_CCNF_model( alphas, betas, thetas, x, y, similarityFNs, sparsityFNs, offset, scaling, verbose, PrecalcQ2sFlat)\n%evaluate_CCNF_model Evaluate the trained model on test (or training data)\n\n% For visualising time series predictions\nnum_x_plots = 8;\nnum_y_plots = 10;\n\ntotal_plots = num_x_plots * num_y_plots;\n\nif(iscell(x))        \n    num_seqs = numel(x);\n    x = cell2mat(x)';\n    % add a bias term\n    x =  cat(1, ones(1,size(x,2)), x);\nelse\n    % if not a cell it has already been flattened, and is constant\n    % (most likely)\n    num_seqs = size(y,2);\n    \nend\n\n% if not sure about const assume it is not\nconst = false;\n\nif(nargin < 11)\n    [ ~, ~, PrecalcQ2sFlat, ~ ] = CalculateSimilarities( num_seqs, x, similarityFNs, sparsityFNs, y, const);\nend\n    \ncorrelations = zeros(num_seqs, 1);\nrms = zeros(num_seqs, 1);\n\n% concatenated data for an alternative correlation\ny_predConcat = [];\ny_trueConcat = [];\n\n% Predict each sequence\nfor q=1:num_seqs\n     \n    if(iscell(y))        \n        seq_length = size(y{q},1);\n        yq = y{q};\n    else\n        seq_length = size(y,1);            \n        yq = y(:,q);\n    end\n    \n    X = x(:,(q-1)*seq_length+1:q*seq_length);\n\n    h1 = 1./(1 + exp(-thetas * X));\n    b = (2 * alphas' * h1)';\n          \n    PrecalcQ2flat = PrecalcQ2sFlat{q};\n\n    precalc_eye = eye(seq_length);\n    precalc_zeros = zeros(seq_length);\n\n    SigmaInv = CalcSigmaCCNFflat(alphas, betas, seq_length, PrecalcQ2flat, precalc_eye, precalc_zeros);\n    \n    y_est = SigmaInv \\ b;\n\n    % Can optionally supply the scaling and offset used on the training\n    % labels to be applied inversely\n    y_est = y_est/scaling + offset;\n\n    if(numel(y_est) > 1)        \n        R = corrcoef(y_est, yq);\n        correlations(q) = R(1,2);\n    end\n    \n    rms(q) = sqrt( mean((y_est - yq).^2) );\n    \n    y_predConcat = cat(1, y_predConcat, y_est);\n    y_trueConcat = cat(1, y_trueConcat, yq);\n\n    if(verbose)\n\n        if(mod(q,total_plots) == 1)\n            figure;\n            remainingPlots = nExamples - q;\n            if(remainingPlots < total_plots)\n                num_y_plots = ceil(remainingPlots / num_x_plots);            \n            end            \n        end        \n        \n        subplot(num_y_plots,num_x_plots,mod(q-1,total_plots)+1);\n        t = 1:nFrames;\n        plot(t,y{q},'g',t,y_est,'b');\n        title(sprintf('C %.2f, R %.2f', correlations(q), rms(q)));\n        set(gca, 'XTick', [], 'YTick', []);\n    \n    end   \n    \nend\n\n% Compute the error metrics\nmean_correlation = mean(correlations); \nmean_RMSE = mean(rms);\nlong_correlation = corr(y_predConcat, y_trueConcat).^2;\n\nlong_RMSE = sqrt(mean((y_predConcat - y_trueConcat).^2));\npredictions = y_predConcat;\ngts = y_trueConcat;\n\nif(verbose)\n    figure\n    plot([1:numel(y_trueConcat)],y_trueConcat,'g',[1:numel(y_trueConcat)],y_predConcat,'b');\n    title(sprintf('C %.2f, R %.2f', long_correlation, long_RMSE));\n    set(gca, 'XTick', [], 'YTick', []);\nend\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/model_training/CCNF/CCNF/lib/evaluate_CCNF_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5592229543361975}}
{"text": "function TorF = hasPQcap(gen, hilo)\n%HASPQCAP  Checks for P-Q capability curve constraints.\n%   TORF = HASPQCAP(GEN, HILO) returns a column vector of 1's and 0's. The 1's\n%   correspond to rows of the GEN matrix which correspond to generators which\n%   have defined a capability curve (with sloped upper and/or lower bound on\n%   Q) and require that additional linear constraints be added to the OPF.\n%\n%   The GEN matrix in version 2 of the MATPOWER case format includes columns\n%   for specifying a P-Q capability curve for a generator defined as the\n%   intersection of two half-planes and the box constraints on P and Q. The\n%   two half planes are defined respectively as the area below the line\n%   connecting (Pc1, Qc1max) and (Pc2, Qc2max) and the area above the line\n%   connecting (Pc1, Qc1min) and (Pc2, Qc2min).\n%\n%   If the optional 2nd argument is 'U' this function returns true only for\n%   rows corresponding to generators that require the upper constraint on Q.\n%   If it is 'L', only for those requiring the lower constraint. If the 2nd\n%   argument is not specified or has any other value it returns true for rows\n%   corresponding to gens that require either or both of the constraints.\n%\n%   It is smart enough to return true only if the corresponding linear\n%   constraint is not redundant w.r.t the box constraints.\n\n%   MATPOWER\n%   Copyright (c) 2005-2016, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n\n%% default value\nif nargin < 2\n    hilo = 'B';     %% look at both top and bottom by default\nend\n\n%% for which gens is it specified\nk = find( gen(:, PC1) | gen(:, PC2) );\nng = size(gen, 1);\n\nif isempty(k)\n    TorF = zeros(ng, 1);\nelse\n    %% eliminate cases where QMIN = QMAX = QC\n    kk = find( gen(k, QMIN) == gen(k, QMAX) & ...\n                gen(k, QMIN) == gen(k, QC1MAX) & ...\n                gen(k, QMIN) == gen(k, QC1MIN) & ...\n                gen(k, QMIN) == gen(k, QC2MAX) & ...\n                gen(k, QMIN) == gen(k, QC2MIN) );\n    k(kk) = [];\n\n    %% check for errors in capability curve data\n    if any( gen(k, PC1) >= gen(k, PC2) )\n        error('hasPQcap: must have Pc1 < Pc2');\n    end\n    if any( gen(k, QC2MAX) <= gen(k, QC2MIN) & gen(k, QC1MAX) <= gen(k, QC1MIN) )\n        error('hasPQcap: capability curve defines an empty set');\n    end\n\n    %% for which gens is it specified\n    k = find( gen(:, PC1) ~= gen(:, PC2) );\n    L = zeros(ng, 1);\n    U = zeros(ng, 1);\n    dPc = gen(k, PC2) - gen(k, PC1);\n\n    if ~strcmp(hilo, 'U')       %% include lower constraint\n        dQc = gen(k, QC2MIN) - gen(k, QC1MIN);\n        Qmin_at_Pmin = gen(k, QC1MIN) + (gen(k, PMIN) - gen(k, PC1)) .* ...\n            dQc ./ dPc;\n        Qmin_at_Pmax = gen(k, QC1MIN) + (gen(k, PMAX) - gen(k, PC1)) .* ...\n            dQc ./ dPc;\n        L(k) = Qmin_at_Pmin > gen(k, QMIN) | Qmin_at_Pmax > gen(k, QMIN);\n    end\n\n    if ~strcmp(hilo, 'L')       %% include upper constraint\n        dQc = gen(k, QC2MAX) - gen(k, QC1MAX);\n        Qmax_at_Pmin = gen(k, QC1MAX) + (gen(k, PMIN) - gen(k, PC1)) .* ...\n            dQc ./ dPc;\n        Qmax_at_Pmax = gen(k, QC1MAX) + (gen(k, PMAX) - gen(k, PC1)) .* ...\n            dQc ./ dPc;\n        U(k) = Qmax_at_Pmin < gen(k, QMAX) | Qmax_at_Pmax < gen(k, QMAX);\n    end\n\n    TorF = L | U;\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/hasPQcap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5592082870098504}}
{"text": "%KERNELM Trainable kernel mapping, dissimilarity representation\n% \n%   [W,J] = KERNELM(A,KERNEL,SELECT,P1,P2 , ...)\n%    W    = A*KERNELM([],KERNEL,SELECT,P1,P2 , ...)\n%    W    = A*KERNELM(KERNEL,SELECT,P1,P2 , ...)\n%    K    = B*W\n%\n% INPUT\n%   A,B         Datasets\n%   KERNEL      Untrained kernel / dissimilarity representation,\n%               a mapping computing proximities between objects.\n%               default: Euclidean dissimilarities: PROXM('d',1)\n%   SELECT      Name of object selection procedure, see below\n%   P1,P2, ...  Additional parameters for SELECT\n%\n% OUTPUT\n%   W          Mapping\n%   J          Vector with indices of selected objects for representation\n%   K          Kernel matrix, dissimilarity representation, \n%              size [SIZE(B,1) LENGTH(J)]\n%\n% DESCRIPTION\n% Computes the kernel mapping W for the representation objects in A. The \n% computation of the kernel matrix, which is a proximity matrix (similarities\n% or dissimilarities) should be defined in KERNEL by an untrained mapping \n% like PROXM for predefined proximities or USERKERNEL for user specified\n% proximities.\n% A*KERNEL should 'train' the kernel, i.e. specify A as representation set.\n% B*(A*KERNEL) should compute the kernel matrix: a dataset.\n%\n% The only advantage of this routine over kernel mappings defined by PROXM\n% or USERKERNEL is that it includes some options for object selection\n% (prototype selection) of the initial representation set.\n%\n% Initially, the kernel mapping has a size [SIZE(A,2) SIZE(A,1)]. For\n% increased efficiency or accuracy the representation set may be reduced\n% by a routine given by the string SELECT to select to objects J, using \n% possibly additional parameters P1, P2, etcetera. \n%\n% The following choices for SELECT are supported:\n% \n% 'random'    random selection of P1 objects, maximum P2\n% 'gendat'    [X,Y,J] = GENDAT(A,P1)\n% 'kcentres'  [LAB,J] = KCENTRES(DISTM(A),P1,P2)\n% 'modeseek'  [LAB,J] = MODESEEK(DISTM(A),P1)\n% 'edicon'    J = EDICON(DISTM(A),P1,P2,P3)\n% 'featsel'   J = +FEATSELM(A*KERNELM(A,TYPE,P),P1,P2,P3)\n%\n% REFERENCES\n% 1. E.Pekalska, R.P.W.Duin, P.Paclik, Prototype selection for dissimilarity-\n% based classification, Pattern Recognition, vol. 39, no. 2, 2006, 189-208.\n% 2. E.Pekalska and R.P.W.Duin, The Dissimilarity Representation for Pattern\n% Recognition, Foundations and Applications, World Scientific, 2005, 1-607.\n% \n% EXAMPLE\n% a = gendatb;\n% w = (scalem*kernelm([],'random',5)*fisherc); \n% scatterd(a)\n% plotc(a*w)\n% plotc(a*w,'r')\n% plotc(a*w,'b')\n%\n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% DATASETS, MAPPINGS, PROXM, USERKERNEL, KERNELC\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: kernelm.m,v 1.7 2007/07/10 08:25:29 duin Exp $\n\nfunction w = kernelm(varargin)\n\n\targin = shiftargin(varargin,'prmapping');\n\targin = shiftargin(varargin,'char',2);\n  argin = setdefaults(argin,[],proxm([],'d',1),[],[],[],[]);\n  if mapping_task(argin,'definition')\n    w = define_mapping(argin,'untrained');\n    w = setname(w,'Kernel mapping');\n  else % training\n    varargin = cell(1,numel(argin)-3);\n    [a,kernel,select,varargin{:}] = deal(argin{:}); \n    if isstr(kernel) % old format of call: kernelm(a,type,p,n), training\n      type = kernel;\n      p = select;\n      if ~isempty(varargin)\n        if length(varargin) > 1\n          error('Wrong parameters supplied')\n        end\n        n = varargin{1};\n      else\n        n = [];\n      end\n      [m,k] = size(a);\n      kernel = proxm([],type,p);\n      w = prmapping(mfilename,'trained',{a*kernel},getlab(a),k,m);\n      if ~isempty(n)\n        w = w*pcam(a*w,n);\n      end\n      w = setname(w,'Kernel Mapping');\n\n    elseif isa(kernel,'prmapping') && ...\n           ~strcmp(getmapping_file(kernel),mfilename) % training\n\n      a = testdatasize(a);\n      a = testdatasize(a,'objects');\n      isuntrained(kernel);\n      [m,k] = size(a);\n      %w = prmapping('kernelm','trained',{a*kernel},getlab(a),k,m);\n      if isempty(select)\n        w = prmapping('kernelm','trained',{a*kernel},getlab(a),k,m);\n      elseif ismapping(select)\n        r = a*select;\n        w = prmapping('kernelm','trained',{r*kernel},getlab(a),k,size(r,1));\n      else\n        switch select\n          case 'random'\n            J = randperm(m);\n            n = varargin{1};\n            if isempty(n) | n > m\n              error('Number of objects to be selected not given or too large')\n            end\n            if n < 1, n = ceil(n*m); end % fraction given\n            if ~isempty(varargin{2})\n              n = min(n,varargin{2});\n            end\n            J = J(1:n);\n          case 'gendat'    \n            [x,y,J] = gendat(a,varargin{1});\n          case 'kcentres'  \n            [lab,J] = kcentres(distm(a),varargin{1:2});\n          case 'modeseek'  \n            [lab,J] = modeseek(distm(a),varargin{1});\n          case 'edicon'    \n            J = edicon(distm(a),varargin{1:3});\n          case 'featsel'\n            w = prmapping('kernelm','trained',{a*kernel},getlab(a),k,m);\n            J = +featselm(a*w,varargin{1:3});\n          otherwise\n            error('Unknown choice for object selection')\n        end\n        % redefine mapping with reduced representation set\n        labels_out = getlab(a);\n        w = prmapping('kernelm','trained',{a(J,:)*kernel},labels_out(J,:),k,length(J));\n      end\n      w = setname(w,'Kernel Mapping');\n\n    else % Execution of the mapping, w will be a dataset.\n\n      kern = getdata(kernel,1); % trained kernel is stored in datafield\n      K = a*kern;\n      w = setdat(a,K,kern);\n\n    end\n    \n  end\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/kernelm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5592082836253516}}
{"text": "%this shows an example of using the \"get axes\" information from graph_picker\n\nim=imread('example_graph.jpg');%load image\n%display('identify reference points in graph picker and ''get axes''');\n%[tmp]=graph_picker(im);\n\n\nfigure\nimage(im);%this is the same image that was used for graph_picker\naxis off\nh_imax=axes;%get handle to current axes\nX=[2.722513e-01 8.272251e-01 1.204188e+00 1.612565e+00 2.146597e+00 2.774869e+00 3.591623e+00 4.219895e+00 ];%sample data\nY=[4.821429e+00 8.928571e+00 1.696429e+01 2.767857e+01 3.142857e+01 2.946429e+01 3.232143e+01 3.732143e+01 ];\nplot(X,Y,'ob');\naxis([-2.129e+00 6.055e+00 -1.191e+01 5.744e+01]);%this comes from graph_picker\nset(h_imax,'color','none');%turn off background color\ngrid on", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41313-graph-picker/graph_picker/overplot_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5592082817759765}}
{"text": "function [pvec, pstruct] = tapas_hgf_ar1_mab_transp(r, ptrans)\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 <http://www.gnu.org/licenses/>.\n\n\npvec    = NaN(1,length(ptrans));\npstruct = struct;\n\nl = r.c_prc.n_levels;\n\npvec(1:l)         = ptrans(1:l);                           % mu_0\npstruct.mu_0      = pvec(1:l);\npvec(l+1:2*l)     = exp(ptrans(l+1:2*l));                  % sa_0\npstruct.sa_0      = pvec(l+1:2*l);\npvec(2*l+1:3*l)   = tapas_sgm(ptrans(2*l+1:3*l),1);        % phi\npstruct.phi       = pvec(2*l+1:3*l);\npvec(3*l+1:4*l)   = ptrans(3*l+1:4*l);                     % m\npstruct.m         = pvec(3*l+1:4*l);\npvec(4*l+1:5*l-1) = exp(ptrans(4*l+1:5*l-1));              % ka\npstruct.ka        = pvec(4*l+1:5*l-1);\npvec(5*l:6*l-1)   = ptrans(5*l:6*l-1);                     % om\npstruct.om        = pvec(5*l:6*l-1);\npvec(6*l)         = exp(ptrans(6*l));                      % al\npstruct.al        = pvec(6*l);\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_ar1_mab_transp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5592082774667901}}
{"text": "function [nodes2, edges2] = grMergeNodeClusters(nodes, edges)\n%GRMERGENODECLUSTERS Merge cluster of connected nodes in a graph\n%\n%   grMergeNodeClusters(nodes, edges)\n%   Detects groups of nodes that belongs to the same global node, and\n%   replace them by a unique node. Coordinates of reference node is given\n%   by the median coordinates of cluster nodes.\n%\n%   This function is intended to be used as filter after a binary image\n%   skeletonization and vectorization.\n%\n%\n%   See Also\n%   grMergeNodesMedian\n%\n\n%   -----\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 13/08/2003.\n%\n\n%   HISTORY\n\n\n%% Initialization\n\n% intialize result \nnodes2 = nodes;\nedges2 = edges;\n\n% compute degree of each node\ndegrees = grNodeDegree(1:size(nodes, 1), edges)';\n\n% find index of multiple nodes\nindMul = find(degrees > 2);\n\n% indices of edges that link several multiple nodes\nindEdges = sum(ismember(edges, indMul), 2) == 2;\n\n% associate a label to each cluster\nlabels = grLabel(nodes, edges(indEdges, :));\nclusterLabels = unique(labels(indMul));\n\n\n%% Replace each cluster by median point\n\n% iterate on clusters\nfor i = 1:length(clusterLabels)\n    % indices of nodes of the current cluster\n    inds = find(labels == clusterLabels(i));\n    \n    % coordinates of new reference node\n    clusterNodes = nodes(inds, :);\n    medianNode = median(clusterNodes, 1);\n    \n    % replace coordinates of reference node\n    refNode = min(inds);\n    nodes2(refNode, :) = medianNode;\n    \n    % replace node indices in edge array\n    edges2(ismember(edges2, inds)) = refNode;\nend\n\n\n%% Clean up\n\n% keep only relevant nodes\ninds = unique(edges2(:));\nnodes2 = nodes2(inds, :);\n\n% relabeling of edges\nfor i = 1:length(inds)\n    edges2(edges2 == inds(i)) = i;\nend\n\n% remove double edges\nedges2 = unique(sort(edges2, 2), 'rows');\n\n% remove 'loops'\nedges2(edges2(:,1) == edges2(:,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/graphs/grMergeNodeClusters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5590503073794025}}
{"text": "function [pvec] = real_mutate(pvec, pmut_real, eta_m, ...\n                                min_realvar, max_realvar)\n%   This code applies polynomical mutation over pvec.\n\nnreal = length(pvec);\n\nif(nreal < 10)\n    pvec = polymut_looped(pvec, pmut_real, eta_m, ...\n                            min_realvar, max_realvar);\nelse\n    pvec = polymut_vectorized(pvec, pmut_real, eta_m, ...\n                            min_realvar, max_realvar);\nend\nend\n\nfunction [pvec] = polymut_looped(pvec, pmut_real, eta_m, ...\n                                    min_realvar, max_realvar)\n% This is the original translation from the nsga-2 c-code.\nnreal = length(pvec);\nfor j = 1:nreal\n    if (rand(1) <= pmut_real)\n    % if (randomperc() <= pmut_real) % SLOW !!!\n        y = pvec(j);\n        yl = min_realvar(j);\n        yu = max_realvar(j);\n        delta1 = (y-yl)/(yu-yl);\n        delta2 = (yu-y)/(yu-yl);\n        mut_pow = 1.0/(eta_m + 1.0);\n        r = rand(1) ;\n        % r = randomperc() ; % SLOW !!!\n        if (r <= 0.5)\n            xy = 1.0 - delta1;\n            val = 2.0 * r + (1.0 - 2.0 * r) * (xy ^ (eta_m + 1.0));\n            deltaq = (val ^ mut_pow) - 1.0;\n        else\n            xy = 1.0 - delta2;\n            val = 2.0 * (1.0 - r) + 2.0 * (r - 0.5) * (xy ^ (eta_m + 1.0));\n            deltaq = 1.0 - (val ^ mut_pow);\n        end\n        y = y + deltaq * (yu - yl);\n        if (y < yl)\n            y = yl;\n        end\n        if (y > yu)\n            y = yu;\n        end\n        pvec(j) = y ;\n    end\nend\nend\n\nfunction [pvec] = polymut_vectorized(pvec, pmut_real, eta_m, ...\n                                        min_realvar, max_realvar)\n% This is the vectorized version of the above code. This code is generally \n% 3 times faster than the above, more gain could be observed if the number \n% of variable is bigger and the mutation rate is higher.\n\nnreal = length(pvec);\nmut_index = rand(1,nreal) < pmut_real ;\n% mut_index = randompercv(1,nreal) < pmut_real ; % SLOW !!!\nabs_mut_index = 1:nreal ;\nabs_mut_index = abs_mut_index(mut_index);\nmlen = length(abs_mut_index);\n\nif(mlen > 0)\n    eta_mv = ones(1,mlen) * eta_m ;\n    yv = pvec(mut_index) ;    \n    ylv = min_realvar(mut_index).';\n    yuv = max_realvar(mut_index).';\n    delta1v = (yv - ylv) ./ (yuv - ylv);\n    delta2v = (yuv - yv) ./ (yuv - ylv);\n    mut_powv = 1.0 ./ (eta_mv + 1.0);\n    rv = rand(1, mlen); % r2s ;\n    % rv = randompercv(1, mlen); % r2s ; % SLOW !!!\n    rvlthalf = rv < 0.5 ;\n    valv1 = 2.0 .* rv + (1.0 - 2.0 .* rv) .* ...\n                        ((1.0 - delta1v) .^ (eta_mv + 1.0));    \n    valv2 = 2.0 .* (1.0 - rv) + 2.0 .* (rv - 0.5) .* ... \n                        ((1.0 - delta2v) .^ (eta_mv + 1.0));\n    deltaqv = rvlthalf .* ((valv1 .^ mut_powv) - 1.0) + ...\n             (~rvlthalf) .* (1.0 - (valv2 .^ mut_powv)); \n    yv = yv + deltaqv .* (yuv - ylv);\n    yltyl = yv < ylv ;\n    ygtyu = yv > yuv ;\n    yv = (yltyl .* ylv) + (yv .* (~yltyl));\n    yv = (ygtyu .* yuv) + (yv .* (~ygtyu));            \n    pvec = pvec' ;\n    pvec(abs_mut_index.',:) = yv' ;\n    pvec = pvec' ;\nend\nend\n\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/real_mutate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7217431943271998, "lm_q1q2_score": 0.5590502859599642}}
{"text": "function [pos, tlight] = littim (tjd, idbody, pose, tlite)\n\n% this function computes the position of a solar system body,\n% as antedated for light-time.\n\n%      tjd    = tdb julian date of observation (in)\n\n%      idbody = id number of body, used in calls to solsys (in)\n\n%      pose   = position vector of observer (or the geocenter),\n%               with respect to origin at solar system barycenter,\n%               referred to icrs axes, components in au (in)\n\n%      tlite  = first approximation to light-time, in days (in)\n%               (can be set to 0.0d0 if unknown)\n\n%      pos    = position vector of body, with respect to origin at\n%               observer (or the geocenter), referred to icrs axes,\n%               components in au (out)\n\n%      tlight = final light-time, in days (out)\n\n% ported from NOVAS 3.1\n\n%%%%%%%%%%%%%%%%%%%%%%%\n\n% set light-time convergence tolerance\n\ntol = 1.0d-9;\n\nt0 = 0.0d0;\n\nt1 = tjd - t0;\n\nt2 = t1 - tlite;\n\n% iterate to obtain correct light-time (usually converges rapidly)\n\nfor iter = 1:10\n\n    [pos1, vel1, ierr] = solsys (t2, str2num(idbody), 0);\n\n    [pos, tlight] = geocen (pos1, pose);\n\n    if (ierr ~= 0)\n\n        fprintf ('\\nplace: cannot obtain coordinates of object at jd %16.8f', t0 + t2);\n\n        return\n\n    end\n\n    t3 = t1 - tlight;\n\n    if (abs(t3 - t2) > tol)\n\n        t2 = t3;\n\n    else\n\n        break\n\n    end\n\nend\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/sun_moon/novas/littim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5589797512431851}}
{"text": "function sim_2prob(value2trans) % autogenerated function wrapper\n    % turned into function by Celso G Reyes 2017\n    \n    ZG=ZmapGlobal.Data; % used by get_zmap_globals\n    \n    \n    report_this_filefun(mfilename('fullpath'));\n    \n    \n    % needed variables\n    % BigCatalog        big catalog from which to take the eqs randomly, produced by translating\n    %                   consists of 100000 eqs\n    % ni                number of earthquakes in a bin, i.e. sample size\n    % NuBins            number of bins\n    % BinLength         1/length(xt), length of shortest possible interval\n    % winlen_days               length of interval in times shortest\n    % NuRep             number of repetitions\n    \n    delta=winlen_days/NuBins;\n    \n    for nto=1:NuRep\n        disp(nto);\n        \n        which=ceil(100000*(rand(ni)));\n        for i=1:ni\n            rancata(i)=BigCatalog(which(i));\n        end\n        clear i which;\n        rancata=ceil(rancata*NuBins);\n        \n        for i=1:NuBins\n            l=sum(rancata==i); Bins(i,1)=sum(l); clear l;\n        end\n        clear rancata i;\n        \n        FirstBin=ceil(rand(1)*(NuBins-winlen_days+1));\n        \n        \n        zin=Bins(FirstBin:FirstBin+winlen_days-1); zout=[Bins(1:FirstBin-1,1); Bins(FirstBin+winlen_days:NuBins,1)];\n        ToBeFitted(nto,1)=nto;\n        % calculating beta\n        ToBeFitted(nto,2)=(sum(zin)-ni*delta)/(sqrt(ni*delta*(1-delta)));\n        % calculating z\n        ToBeFitted(nto,3)=(mean(zout)-mean(zin))/(sqrt(var(zin)/sum(zin)+var(zout)/sum(zout)));\n        clear Bins FirstBin zin zout;\n    end\n    clear BigCatalog nto delta;\n    \n    [meanval, std] =normfit(ToBeFitted(:,2)); IsFitted(1,1)=meanval; IsFitted(1,2)=std;\n    [meanval, std] =normfit(ToBeFitted(:,3)); IsFitted(2,1)=meanval; IsFitted(2,2)=std;\n    clear meanval std;\n    clear ToBeFitted;\n    \n    switch value2trans\n        case 'beta'\n            Pbeta = normcdf(BetaValues,IsFitted(1,1),IsFitted(1,2));\n            l = Pbeta == 0; Pbeta(l) = nan;\n        case 'z'\n            Pbeta = normcdf(BetaValues,IsFitted(2,1),IsFitted(2,2));\n            l = Pbeta == 0; Pbeta(l) = nan;\n    end\n    \n    % plot the resuts\n    figure\n    pq = -log10(1-Pbeta); l = isinf(pq);pq(l) = 18 ;\n    pl1 = plot(xt,pq,'color',[0.0 0.5 0.9]);\n    hold on\n    l = pq < 1.3; pq(l) = nan;\n    pl3 = plot(xt,pq,'b','Linewidth',2);\n    \n    pq = -log10(Pbeta);l = isinf(pq);pq(l) = 18 ;\n    pl2 = plot(xt,pq,'color',[0.8 0.6 0.8]);\n    l = pq < 1.3; pq(l) = nan;\n    pl4 = plot(xt,pq,'r','Linewidth',2);\n    \n    maxd = [get(pl1,'Ydata') get(pl2,'ydata') ]; maxd(isinf(maxd)) = []; maxd = max(maxd);\n    if maxd < 5 ; maxd = 5; end\n    if isnan(maxd) == 1 ; maxd = 10; end\n    \n    legend([pl3 pl4],'Rate increases','Rate decreases');\n    set(gca,'Ylim',[0 maxd+1])\n    set(gca,'YTick',[1.3 2 3 4 5])\n    set(gca,'YTickLabel',[ '    5%' ; '    1%' ;  '  0.1%' ;  ' 0.01%' ; '0.001%'])\n    set(gca,'TickDir','out','Ticklength',[0.02 0.02],'pos',[0.2 0.2 0.7 0.7]);\n    xlabel('Time [years]')\n    ylabel('Significance level');\n    set(gcf,'color','w')\n    grid\n    \n    uicontrol('Units','normal',...\n        'Position',[.8 .0 .1 .05],'String','Explain ... ',...\n        'callback',@(~,~)showweb('explproba'));\n    \n    delete(probut)\n    \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/sim_2prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5589797391498538}}
{"text": "function [img_pca,img_pca_null]=connectopic_laplacian(s,ind_ins,N,Vn,Null)\n\n% Input:\n% s: similarity matrx\n% ind_ins: index of subcortical voxels\n% N: size of image (MNI152:91x109x91)\n% K: degree, used when Disparity=1\n% Vn: index of gradient to compute: Vn=2 -> Gradint I; Vn=3 -> Gradient II; Vn=4 -> Gradient III\n% Null: property of null data,structural variable including the following:\n\n% Null.NumNull: Number of randomizations if compute the null data\n% Null.T: number of time points in the empirical data\n% Null.FWHM: Gaussian smooth kernel used in the empirical data\n% Null.voxelsize: voxel size in mm in the empirical data\n\n% Output:\n% img_pca: eigenmap (main output)\n% img_pca_null: eigenmap computed from null data\n\n%Global thresholding. Haak et al 2017\nimg_pca=zeros(N);\nw=squareform(pdist(s));  %similarity to distance mapping\n\nfprintf('Thresholding to minimum density needed for graph to remain connected\\n');\nind_upper=find(triu(ones(length(w),length(w)),1));\n[~,ind_srt]=sort(w(ind_upper));\nw_thresh=zeros(length(w),length(w));\ndns=linspace(0.001,1,1000);\nfor i=1:length(dns)\n    ttl=ceil(length(ind_upper)*dns(i));\n    w_thresh(ind_upper(ind_srt(1:ttl)))=s(ind_upper(ind_srt(1:ttl)));\n    [~,comp_sizes]=get_components(~~w_thresh+~~w_thresh');\n    if length(comp_sizes)==1\n        break\n    end\nend\n\nfprintf('Density=%0.2f%%\\n',100*(length(find(~~w_thresh))/length(ind_upper)));\ndns=dns(i);\nw_thresh=w_thresh+w_thresh';\n\nfprintf('Computing Laplacian\\n');\nL=diag(sum(w_thresh))-w_thresh;\n\nfprintf('Finding eigenvectors\\n');\n[v,d]=eig(L);d=diag(d);\n\n% Variance explained\nper=1./d(2:end);\nper=per/sum(per)*100;\n \n%figure; plot(per(1:20));\n\nif v(1,Vn)>v(end,Vn)\n    y=v(:,Vn);\nelse\n    y=-v(:,Vn);\nend\nmin_val=min(y);\ny=y-min_val;\nimg_pca(ind_ins)=y;\n\nif nargin==5\n    fprintf('Null Model: Synthetic data + MST + Geometry\\n');\n    NumNull=Null.NumNull;\n    T=Null.T;\n    FWHM=Null.FWHM;\n    voxelsize=Null.voxelsize;\n    \n    % Reference matrix\n    fprintf('Generating reference matrix\\n')\n    M=zeros(length(ind_ins),length(ind_ins));\n    for i=1:length(ind_ins)\n        for j=1:length(ind_ins)\n            [xx1,yy1,zz1]=ind2sub(N,ind_ins(i));\n            [xx2,yy2,zz2]=ind2sub(N,ind_ins(j));\n            dd=sqrt((xx1-xx2)^2 + (yy1-yy2)^2 + (zz1-zz2)^2);\n            if dd<=sqrt(2)\n                M(i,j)=1;\n            end\n        end\n    end\n    ind_m_upper=find(triu(M,1)); % All the available locations (neighboring only)\n    \n    % Randomizations\n    \n    img_pca_null=zeros([N,NumNull]);\n    for nn=1:NumNull\n        fprintf('Simulating random data %d\\n',nn)\n        x=randn([N,T]);\n        x_ins=zeros(T,length(ind_ins));\n        frst=0;\n        for i=1:T\n            x(:,:,:,i)=imgaussfilt3(x(:,:,:,i),FWHM/voxelsize/2.355);\n            tmp=x(:,:,:,i);\n            x_ins(i,:)=tmp(ind_ins);\n            show_progress(i,T,frst);frst=1;\n        end\n        clear x\n        % Normalization\n        x_ins=detrend(x_ins,'constant'); x_ins=x_ins./repmat(std(x_ins),T,1);\n        \n        % Correlation\n        c=x_ins'*x_ins; c=c/T;z=atanh(c);\n        \n        [~,ind_srt_z]=sort(z(ind_upper),'descend');\n        ind_z_upper=ind_upper(ind_srt_z(1:ttl)); % Available locations;ttl is computed from acutual data\n        \n        % MST ensures that the graph is fully connected\n        % Only allow MST found in the neighboring locations\n        ss=zeros(size(s));\n        ss(ind_m_upper)=rand(length(ind_m_upper),1);\n        ss=ss+ss';\n        \n        mst=adjacency(minspantree(graph(ss)));\n        ind_mst_upper=find(triu(mst,1));\n        \n        % Randomise top weighted edges.\n        ind_srt_ttl=ind_upper(ind_srt(1:ttl));\n        ind_rand=randperm(length(ind_srt_ttl));\n        ind_srt_ttl=ind_srt_ttl(ind_rand);\n        \n        % Add edges to mst locations first\n        Nm=length(ind_mst_upper);\n        w_thresh_null=zeros(size(s));\n        w_thresh_null(ind_mst_upper)=s(ind_srt_ttl(1:Nm));\n        \n        % Then, add remaining edges to remaining desired locations\n        ind_remain=setdiff(ind_z_upper,ind_mst_upper);\n        ind_rand=randperm(length(ind_remain));\n        ind_remain=ind_remain(ind_rand);\n        w_thresh_null(ind_remain(1:ttl-Nm))=s(ind_srt_ttl(Nm+1:ttl));\n        \n        [~,comp_sizes]=get_components(~~w_thresh_null+~~w_thresh_null');\n        if length(comp_sizes)~=1\n            fprintf('Warning: Null model is not fully connected\\n')\n        end\n        dns_null=length(find(~~w_thresh_null))/length(ind_upper);\n        fprintf('Density null=%0.2f%%\\n',dns_null*100);\n        \n        w_thresh_null=w_thresh_null + w_thresh_null';\n        \n        fprintf('Computing Laplacian\\n');\n        L=diag(sum(w_thresh_null))-w_thresh_null;\n        \n        fprintf('Finding eigenvectors\\n');\n        [v,d]=eig(L);d=diag(d);\n        \n        if v(1,Vn)>v(end,Vn)\n            y=v(:,Vn);\n        else\n            y=-v(:,Vn);\n        end\n        min_val_null=min(y);\n        y=y-min_val_null;\n        tmp=zeros(N);\n        tmp(ind_ins)=y;\n        img_pca_null(:,:,:,nn)=tmp;\n        \n    end\nelse\n    img_pca_null=[];\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/connectopic_laplacian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5589797371853903}}
{"text": "function outpoints = icbm_spm2tal(inpoints)\n%\n% This function converts coordinates from MNI space (normalized \n% using the SPM software package) to Talairach space using the \n% icbm2tal transform developed and validated by Jack Lancaster \n% at the Research Imaging Center in San Antonio, Texas.\n%\n% http://www3.interscience.wiley.com/cgi-bin/abstract/114104479/ABSTRACT\n% \n% FORMAT outpoints = icbm_spm2tal(inpoints)\n% Where inpoints is N by 3 or 3 by N matrix of coordinates\n% (N being the number of points)\n%\n% ric.uthscsa.edu 3/14/07\n\n% find which dimensions are of size 3\ndimdim = find(size(inpoints) == 3);\nif isempty(dimdim)\n  error('input must be a N by 3 or 3 by N matrix')\nend\n\n% 3x3 matrices are ambiguous\n% default to coordinates within a row\nif dimdim == [1 2]\n  disp('input is an ambiguous 3 by 3 matrix')\n  disp('assuming coordinates are row vectors')\n  dimdim = 2;\nend\n\n% transpose if necessary\nif dimdim == 2\n  inpoints = inpoints';\nend\n\n% Transformation matrices, different for each software package\nicbm_spm = [0.9254 0.0024 -0.0118 -1.0207\n\t   \t   -0.0048 0.9316 -0.0871 -1.7667\n            0.0152 0.0883  0.8924  4.0926\n            0.0000 0.0000  0.0000  1.0000];\n\n% apply the transformation matrix\ninpoints = [inpoints; ones(1, size(inpoints, 2))];\ninpoints = icbm_spm * inpoints;\n\n% format the outpoints, transpose if necessary\noutpoints = inpoints(1:3, :);\nif dimdim == 2\n  outpoints = outpoints';\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/Talairach-2009-11-02/icbm_spm2tal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.558979726903246}}
{"text": "function [projmat_art,D] = tomoproj_art_2(im,angles)\n%TOMOPROJ_ART   [projmat_art,D] = tomoproj_art(im,angles)\n%   unit of angles: Degree;\n%   projection direction: When angle == 0, X-ray passes through up-down\n%    direction;\n%\n%   Phymhan\n%   02-Aug-2013 14:07:06\n\n%Pad image\n[im_pad,D] = impad(im);\n%Calculate projection\nnum_proj = length(angles);\nprojmat_art = zeros(num_proj,2*D);\nfor k = 1:num_proj\n    im_rot = imrotate(im_pad,-angles(k),'bilinear','crop');\n    projmat_art(k,  1:  D) = sum(im_rot,1) ;\n    projmat_art(k,D+1:2*D) = sum(im_rot,2)';\nend\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43008-tomotools/tomotool/tomoproj_art_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5589754915161127}}
{"text": "function collocation_test ( )\n\n%*****************************************************************************80\n%\n%% COLLOCATION_TEST tests the COLLOCATION library.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    29 March 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  timestamp ( );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'COLLOCATION_TEST\\n' );\n  fprintf ( 1, '  MATLAB version.\\n' );\n  fprintf ( 1, '  Test the COLLOCATION library.\\n' );\n \n  collocation_test01 ( );\n  collocation_test02 ( );\n  collocation_test03 ( );\n%\n%  Terminate.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'COLLOCATION_TEST\\n' );\n  fprintf ( 1, '  Normal end of execution.\\n' );\n  fprintf ( 1, '\\n' );\n  timestamp ( );\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/collocation/collocation_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334527, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.5589754900233086}}
{"text": "function X = ttm(X,V,varargin)\n%TTM Tensor times matrix for ktensor.\n%\n%   Y = TTM(X,A,N) computes the n-mode product of the ktensor X with a\n%   matrix A; i.e., X x_N A.  The integer N specifies the dimension\n%   (or mode) of X along which A should be multiplied.  If size(A) =\n%   [J,I], then X must have size(X,N) = I.  The result will be a\n%   ktensor of the same order and size as X except that size(Y,N) = J.\n%\n%   Y = TTM(X,{A,B,C,...}) computes the n-mode product of the ktensor\n%   X with a sequence of matrices in the cell array.  The n-mode\n%   products are computed sequentially along all dimensions (or modes)\n%   of X. The cell array contains ndims(X) matrices.\n%\n%   Y = TTM(X,{A,B,C,...},DIMS) computes the sequence tensor-matrix\n%   products along the dimensions specified by DIMS.\n%\n%   Y = TTM(...,'t') performs the same computations as above except\n%   the matrices are transposed.\n%\n%   Examples\n%   X = ktensor({rand(5,2),rand(3,2),rand(4,2),rand(2,2)});\n%   A = rand(4,5); B = rand(4,3); C = rand(3,4); D = rand(3,2);\n%   Y = ttm(X, A, 1)         %<-- computes X times A in mode-1\n%   Y = ttm(X, {A,B,C,D}, 1) %<-- same as above\n%   Y = ttm(X, A', 1, 't')   %<-- same as above\n%   Y = ttm(X, {A,B,C,D}, [1 2 3 4]) %<-- 4-way multiply\n%   Y = ttm(X, {D,C,B,A}, [4 3 2 1]) %<-- same as above\n%   Y = ttm(X, {A,B,C,D})            %<-- same as above\n%   Y = ttm(X, {A',B',C',D'}, 't')   %<-- same as above\n%   Y = ttm(X, {C,D}, [3 4])     %<-- X times C in mode-3 & D in mode-4\n%   Y = ttm(X, {A,B,C,D}, [3 4]) %<-- same as above\n%   Y = ttm(X, {A,B,D}, [1 2 4])   %<-- 3-way multiply\n%   Y = ttm(X, {A,B,C,D}, [1 2 4]) %<-- same as above\n%   Y = ttm(X, {A,B,D}, -3)        %<-- same as above\n%   Y = ttm(X, {A,B,C,D}, -3)      %<-- same as above\n%\n%   See also KTENSOR, KTENSOR/TTV, TENSOR/TTM.\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\n\n\n%%%%%%%%%%%%%%%%%%%%%%\n%%% ERROR CHECKING %%%\n%%%%%%%%%%%%%%%%%%%%%%\n\n% Check the number of arguments\nif (nargin < 2)\n    error('TTM requires at least two arguments.');\nend\n\n% Check for transpose option\nisTranspose = false;\nif numel(varargin) > 0\n  if isnumeric(varargin{1});\n    dims = varargin{1};\n  end\n  isTranspose =  (ischar(varargin{end}) && (varargin{end} == 't'));\nend\n\n% Check for dims argument\nif ~exist('dims','var')\n    dims = [];\nend\n\n% Check that 2nd argument is cell array. If not, recall with V as a\n% cell array with one element.\nif ~iscell(V)\n    X = ttm(X,{V},dims,varargin{end});\n    return;\nend\n\n% Get sorted dims and index for multiplicands\n[dims,vidx] = tt_dimscheck(dims,ndims(X),numel(V));\n\n% Determine correct size index\nif isTranspose\n  j = 1; \nelse\n  j = 2;\nend\n\n% Check that each multiplicand is the right size.\nfor i = 1:numel(dims)\n    if (ndims(V) ~= 2) || (size(V{vidx(i)},j) ~= size(X,dims(i)))\ndisp(size(V{vidx(i)}))\ndisp(size(X))\n\n        error('Multiplicand is wrong size');\n    end\nend\n\n% Do the multiplications in the specified modes. \nfor i = 1:numel(dims) \n  if isTranspose\n    X.u{dims(i)} = V{vidx(i)}'* X.u{dims(i)};\n  else\n    X.u{dims(i)} = V{vidx(i)} * X.u{dims(i)};\n  end\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u7c7b\u7b97\u6cd5/DEEP-TENSOR-FACTORIZATION-FOR-HYPERSPECTRAL-IMAGE-CLASSIFICATION-master/code/tensor_toolbox_2.6/@ktensor/ttm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5589754885305038}}
{"text": "function [xu,yu,xl,yl,xc,yc]=GenerateNACASeries5Airfoil(afid,dotcount,xmod)\n\n%--------------------------------------------------------------------------\n%GenerateNACASeries5Airfoil\n%Version 1.20\n%Created by Stepen (zerocross_raptor@yahoo.com)\n%Created 20 November 2010\n%Last modified 30 November 2011\n%--------------------------------------------------------------------------\n%GenerateNACASeries5Airfoil generates the airfoil vertexes' coordinate of\n%the given NACA Series 5 Airfoil. The math equation used to generates the\n%airfoil coordinates is based on Theory of Wing Section Chapter 6 by Abbott\n%and Doenhoff.\n%--------------------------------------------------------------------------\n%Syntax:\n%[xu,yu,xl,yl,xc,yc]=GenerateNACASeries5Airfoil(afid,dotcount,xmod)\n%Input argument:\n%- afid (1 x 5 str) specifies NACA Series 5 Airfoil identifier.\n%- dotcount (1 x 1 int) specifies the number of vertexes to be generated on\n%  the airfoil's camber/mean line.\n%- xmod (str) specifies the mode of airfoil vertex distribution. Enter\n%  'Uniform' to create uniform vertex distribution or 'Cosine' to create\n%  vertex distribution based on cosine function (More vertex on the leading\n%  edge region).\n%Output argument:\n%- xu (i x 1 num) specifies the x axis location of airfoil's upper surface\n%  vertexes in fraction of chord. The airfoil's upper surface vertex are\n%  arranged from leading edge (the first element of xu) to the trailing\n%  edge (the last element of xu).\n%- yu (i x 1 num) specifies the y axis location of airfoil's upper surface\n%  vertexes in fraction of chord. The airfoil's upper surface vertex are\n%  arranged from leading edge (the first element of yu) to the trailing\n%  edge (the last element of yu).\n%- xl (i x 1 num) specifies the x axis location of airfoil's lower surface\n%  vertexes in fraction of chord. The airfoil's lower surface vertex are\n%  arranged from leading edge (the first element of xl) to the trailing\n%  edge (the last element of xl).\n%- yl (i x 1 num) specifies the y axis location of airfoil's lower surface\n%  vertexes in fraction of chord. The airfoil's lower surface vertex are\n%  arranged from leading edge (the first element of yl) to the trailing\n%  edge (the last element of yl).\n%- xc (i x 1 num) specifies the x axis location of airfoil's camber line\n%  vertexes in fraction of chord. The airfoil's camber line vertex are\n%  arranged from leading edge (the first element of xc) to the trailing\n%  edge (the last element of xc).\n%- yc (i x 1 num) specifies the y axis location of airfoil's camber line\n%  vertexes in fraction of chord. The airfoil's camber line vertex are\n%  arranged from leading edge (the first element of yc) to the trailing\n%  edge (the last element of yc).\n%--------------------------------------------------------------------------\n\n%CodeStart-----------------------------------------------------------------\n%Checking input afid\n    if ~ischar(afid)\n        error('Airfoil identifier must be a string!')\n    end\n    if numel(afid)~=5\n        error('Airfoil identifier must be a 5 digit number!')\n    end\n    if isempty(str2double(afid))\n        error('Airfoil identifier must be a 5 digit number!')\n    end\n    id=str2double(afid([2,3]));\n    if (id~=10)&&(id~=20)&&(id~=30)&&(id~=40)&&(id~=50)\n        error(['Airfoil identifier must start with X10,',...\n               ' X20, X30, X40, or X50!'])\n    end\n%Checking input dotcount\n    if numel(dotcount)~=1\n        error('Number of vertex must be scalar!')\n    end\n    if (mod(dotcount,1~=0))||(dotcount<0)\n        error('Number of vertex must be positive integer!')\n    end\n%Checking input xmod\n    if nargin<3\n        xmod='Cosine';\n    end\n    if (~strcmpi(xmod,'Uniform'))&&(~strcmpi(xmod,'Cosine'))\n        error('Vertex distribution input must be Uniform or Cosine!')\n    end\n%Declaring look-up table\n    mtable=[0.0580,0.1260,0.2025,0.2900,0.3910];\n    ktable=[361.4000,51.6400,15.9570,6.6430,3.2300];\n%Assigning identifier to equation coefficient\n    id1=str2double(afid(1));\n    id2=str2double(afid([2,3]));\n    id3=str2double(afid([4,5]));\n    cl=id1*(3/2)*(10/100);      %Design lift coefficient\n    p=id2*(1/2)*(1/100);        %Maximum camber location\n    t=id3*(1/100);              %Maximum thickness\n    if t==0\n        warning(['Zero thickness airfoil!',...\n                 ' Airfoil will be just a camber line!'])\n    end\n    m=mtable(str2double(afid(2)));\n    k=ktable(str2double(afid(2)));\n%Calculating x-axis location of camber line vertexes\n    panelcount=dotcount-1;\n    if strcmpi(xmod,'Uniform')\n        panellength=1/panelcount;\n        xc=(0:panellength:1)';\n    elseif strcmpi(xmod,'Cosine')\n        deltadeg=90/panelcount;\n        xc=1-cosd(0:deltadeg:90)';\n    end\n%Preallocating array for speed\n    yc=zeros(dotcount,1);\n    gc=zeros(dotcount,1);\n    yt=zeros(dotcount,1);\n    xu=zeros(dotcount,1);\n    xl=zeros(dotcount,1);\n    yu=zeros(dotcount,1);\n    yl=zeros(dotcount,1);\n%Calculating y-axis location of camber line vertexes and camber gradient\n    if m~=0\n        for i=1:1:dotcount\n            if xc(i)<=p\n                yc(i)=(k/6)*((xc(i)^3)-...\n                             (3*m*(xc(i)^2))+...\n                             ((m^2)*(3-m)*xc(i)));\n                gc(i)=(k/6)*((2*(xc(i)^2))-...\n                             (6*m*xc(i))+...\n                             (((3*(m^2))-(m^3))));\n            elseif xc(i)>p\n                yc(i)=(k/6)*(m^3)*(1-xc(i));\n                gc(i)=-1*(k/6)*(m^3);\n            end\n        end\n    end\n%Correcting camber line vertexes and camber gradient for extended series\n    yc=yc*(id1/2);\n    gc=gc*(id1/2);\n%Converting camber gradient to camber slope and normal\n    sc=atand(gc);\n%Calculating thickness distribution\n    for i=1:1:dotcount\n        yt(i)=5*t*((0.29690*(xc(i)^0.5))-...\n                   (0.12600*xc(i))-...\n                   (0.35160*(xc(i)^2))+...\n                   (0.28430*(xc(i)^3))-...\n                   (0.10150*(xc(i)^4)));\n    end\n%Generating airfoil vertexes\n    for i=1:1:dotcount\n        xu(i)=xc(i)-yt(i)*sind(sc(i));\n        yu(i)=yc(i)+yt(i)*cosd(sc(i));\n        xl(i)=xc(i)+yt(i)*sind(sc(i));\n        yl(i)=yc(i)-yt(i)*cosd(sc(i));\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/34035-drawdatcomaircraft/GenerateNACASeries5Airfoil.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.558975473335625}}
{"text": "function [PSNR, SSIM, IFC] = evaluate_SR(img_GT, img_HR, scale, compute_ifc)\n% -------------------------------------------------------------------------\n%   Description:\n%       Compute PSNR, SSIM and IFC for SR\n%       We convert RGB image to grayscale and crop boundaries for 'scale'\n%       pixels\n%\n%   Input:\n%       - img_GT        : Ground truth image\n%       - img_HR        : predicted HR image\n%       - scale         : upsampling scale\n%       - compute_ifc   : evaluate IFC [default = 0 since it's slow]\n%\n%   Citation: \n%       Fast and Accurate Image Super-Resolution with Deep Laplacian Pyramid Networks\n%       Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang\n%       arXiv, 2017\n%\n%   Contact:\n%       Wei-Sheng Lai\n%       wlai24@ucmerced.edu\n%       University of California, Merced\n% -------------------------------------------------------------------------\n\n    if ~exist('compute_ifc', 'var')\n        compute_ifc = 0;\n    end\n    \n    %% quantize pixel values\n    img_GT = im2double(im2uint8(img_GT)); \n    img_HR = im2double(im2uint8(img_HR)); \n        \n    %% convert to gray scale\n    if( size(img_GT, 3) > 1 )\n        img_GT = rgb2ycbcr(img_GT); img_GT = img_GT(:, :, 1);\n        img_HR = rgb2ycbcr(img_HR); img_HR = img_HR(:, :, 1);\n    end\n    \n    %% crop boundary\n    img_GT = shave_bd(img_GT, scale);\n    img_HR = shave_bd(img_HR, scale);\n    \n    % evaluate\n    PSNR = psnr(img_GT, img_HR);\n    SSIM = ssim(img_GT, img_HR);\n    \n    % comment IFC to speed up testing\n    IFC = 0;\n    if compute_ifc\n        IFC = ifcvec(img_GT, img_HR);\n        if( ~isreal(IFC) )\n            IFC = 0;\n        end\n    end\n\nend", "meta": {"author": "phoenix104104", "repo": "LapSRN", "sha": "95154bba82a3aab9bdaec8e0eedd4187babc5ed2", "save_path": "github-repos/MATLAB/phoenix104104-LapSRN", "path": "github-repos/MATLAB/phoenix104104-LapSRN/LapSRN-95154bba82a3aab9bdaec8e0eedd4187babc5ed2/utils/evaluate_SR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5589737406152616}}
{"text": "function K = white_noise_correlation ( s, t )\n\n%*****************************************************************************80\n%\n%% WHITE_NOISE_CORRELATION evaluates the white_noise correlation function.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 February 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Petter Abrahamsen,\n%    A Review of Gaussian Random Fields and Correlation Functions,\n%    Norwegian Computing Center, 1997.\n%\n%  Parameters:\n%\n%    Input, real S(*), T(*), pairs of argument values.\n%\n%    Output, real K(*), the correlation function values\n%\n  K = zeros ( size ( s ) );\n\n  i = find ( s == t );\n\n  K(i) = 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/correlation_chebfun/white_noise_correlation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.5589737358104381}}
{"text": "function shadedTimeSeries(X, Ydata, indicator, Xlabel, Ylabels, colour, Yspacing)\n% SHADEDTIMESERIES(X, Ydata, indicator, Xlabel, Ylabels, colour, Yspacing)\n%\n% Plot time series one above the other with coloured strips highlighting\n% interesting features.\n%\n% All data is in columns.\n%\n% X is the time vector.\n% Each column of Ydata will be plotted in a separate subplot, one beneath\n% the other.\n% Indicator is a logical array where the ones indicate the areas of\n% interest that will be shaded.\n% Xlabel is a string for labeling the bottom horizontal axis.\n% Ylabels is a cell array of strings used for labeling the Y axes.\n% Colour is an RGB colour array that will be used for shading.\n% Yspacing is the percentage of vertical padding to leave above and below\n% each plot so that they don't touch the top and bottom of their respective\n% plots.\n%\n% If Ydata has only one column then the function will draw in the current\n% plot or subplot; this is useful if you want to organise your own plots\n% and subplots but still use the shading feature. If Ydata has more than\n% one column then the function will create a new figure with a subplot for\n% each column of Ydata.\n%\n% Example 1 - same indicator for all subplots: \n%           time = [1:50]';\n%           acceleration = rand(50,1);\n%           velocity = cumtrapz(acceleration, time);\n%           position = cumtrapz(velocity, time);\n%           indicator = [zeros(1,10) ones(1,10) zeros(1,25) ones(1,5)]';\n%           shadedTimeSeries(time, [acceleration velocity position], indicator, 'Time', {'Acceleration' 'Velocity' 'Position'}, [0 0.8 0.3], 10);\n%\n%\n% Example 2 - different indicators for each subplot: \n%           time = [1:50]';\n%           acceleration = rand(50,1);\n%           velocity = cumtrapz(acceleration, time);\n%           position = cumtrapz(velocity, time);\n%           indicator = [zeros(1,10) ones(1,10) zeros(1,25) ones(1,5); ones(1,3) zeros(1,10) ones(1,30) zeros(1,7); zeros(1,20) ones(1,20) zeros(1,10)]';\n%           shadedTimeSeries(time, [acceleration velocity position], indicator, 'Time', {'Acceleration' 'Velocity' 'Position'}, [0 0.8 0.3], 10);\n%\n%    \n%\n% Example 3 - single plot at a time for full control: \n%           time = [1:50]';\n%           acceleration = rand(50,1);\n%           velocity = cumtrapz(acceleration, time);\n%           position = cumtrapz(velocity, time);\n%           indicator = [zeros(1,10) ones(1,10) zeros(1,25) ones(1,5)]';\n%           figure;\n%           subplot(3,1,1);\n%           shadedTimeSeries(time, acceleration, indicator, 'Time', {'Acceleration'}, [1 .7 1], 10);\n%           hold on\n%           text(10,1,'Custom text.');\n%           subplot(3,1,2);\n%           shadedTimeSeries(time, velocity, indicator, 'Time', {'Velocity'}, [1 .7 1], 10);\n%           xlabel('');\n%           subplot(3,1,3);\n%           shadedTimeSeries(time, position, indicator, 'Time', {'Position'}, [1 .7 1], 10);\n%           grid on;\n%\n% Carl Fischer. March 2011.\n% http://eis.comp.lancs.ac.uk/~carl/blog/\n\nif nargin < 3\n    error('Please provide at least X, Ydata and indicator parameters.');\nend\n% Check consistency of compulsory parameters first.\nif length(X) ~= size(Ydata,1)\n    if length(X) == size(Ydata,2)\n        Ydata = Ydata';\n    else\n        error('X and Ydata must have the same length.');\n    end\nend\nif length(X) ~= size(indicator,1)\n    if length(X) == size(indicator,2)\n        indicator = indicator';\n    else\n        error('X and indicator must have the same length.');\n    end\nend\nif nargin < 4\n    Xlabel = '';\nend\nif nargin < 5\n    Ylabels = cell(1,size(Ydata,2));\nend\nif nargin < 6 || isempty(colour)\n    colour = [0 .7 .7];\nend\nif nargin < 7 || isempty(Yspacing)\n    Yspacing = 5;\nend\n\n\nif length(Ylabels) ~= size(Ydata,2)\n    error('The number of Ylabels should match the number of data traces in Ydata.');\nend\nif size(indicator,2) > 1 && size(indicator,2) ~= size(Ydata,2)\n    error('If there is more than one column in indicator, their number must match the number of columns in Ydata.');\nend\n\nfor column_idx = 1:size(indicator,2)\n    start_marks{column_idx} = find(diff(indicator(:,column_idx)) > 0);\n    end_marks{column_idx} = find(diff(indicator(:,column_idx)) < 0);\n    if start_marks{column_idx}(1) > end_marks{column_idx}(1) % plot is shaded from start\n        start_marks{column_idx} = [1; start_marks{column_idx}];\n    end\n    if start_marks{column_idx}(end) > end_marks{column_idx}(end) % plot is shaded until end\n        end_marks{column_idx} = [end_marks{column_idx}; length(X)];\n    end\nend\nif size(Ydata,2) > 1\n    figure;\nend\nfor i = 1:size(Ydata,2)\n    if size(indicator,2) == 1\n        plot_partial(X, Ydata(:,i), start_marks{1}, end_marks{1}, i, Ylabels{i}, size(Ydata,2));\n    else\n        plot_partial(X, Ydata(:,i), start_marks{i}, end_marks{i}, i, Ylabels{i}, size(Ydata,2));\n    end\n    if i ~= size(Ydata,2)\n        set(gca,'xticklabel',[]) % remove x label for all except bottom plot\n    end\nend\nxlabel(Xlabel);\n\n\n\n    function plot_partial(x, ydata, start_marks, end_marks, number, name, total)\n        if size(Ydata,2) > 1\n            subplot(total,1,number);\n        end\n        hold on;\n        ylabel(name);\n        xlim([x(1) x(end)]);% force plot to go from edge to edge\n        padding = Yspacing/100*(max(ydata)-min(ydata));% spacing at top and bottom of plotted line\n        ylim([min(ydata)-padding max(ydata)+padding]); % default leaves too much space around graph\n        \n        for j = 1:min(length(start_marks), length(end_marks)) % create all the shaded areas\n            % This patch line was ripped from ShadePlotForEmphasis.m by\n            % Michael Robbins on Matlab Central.\n            patch([repmat( x(start_marks(j)),1,2) repmat( x(end_marks(j)),1,2)], ...\n                [get(gca,'YLim') fliplr(get(gca,'YLim'))], ...\n                [0 0 0 0],colour,'EdgeColor', 'none');\n        end\n        plot(x, ydata, 'LineWidth', 3); % plot data line on top of colour patch\n        set(gca, 'layer', 'top'); % put ticks back on top of colour patch\n        hold off;\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/20625-shaded-time-series/shadedTimeSeries.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.5589737324063645}}
{"text": "function [Vout,HT_index, HT_values]=make_halfway_vertices(EV_table,ET_table,ETV_index,V,Ne)\n% ETV_index_sparse=sparse(size(V,1),size(V,1));\n%\n% for i=1:size(ETV_index,1)\n% \tif(ETV_index(i,1)>0)\n% \t\tETV_index_sparse(ETV_index(i,1),ETV_index(i,2))=i;\n% \telse\n% \t\tET_table=ET_table(1:(i-1),:);\n% \t\tEV_table=EV_table(1:(i-1));\n% \t\tbreak\n% \tend\n% end\n\n\n% Table to cell array\nETV_index_vall=cell(length(V),1);\nfor i=1:size(ETV_index,1)\n    if(ETV_index(i,1)>0)\n        ETV_index_vall{ETV_index(i,1)}=[ETV_index_vall{ETV_index(i,1)} i];\n    else\n        ET_table=ET_table(1:(i-1),:);\n        EV_table=EV_table(1:(i-1));\n        break;\n    end\nend\n\nHT_index=cell(length(V),1);\nHT_values=cell(length(V),1);\n\n% Make output V\nVout=zeros(size(V,1)*4,3);\nVout(1:size(V,1),:)=V;\nVindex=size(V,1);\n\nfor i=1:length(V)\n    Pneig=Ne{i};\n    for j=1:length(Pneig);\n        % Get the tangent and velocity of the edge P -> Pneig\n        index=Ne{i}; vals=ETV_index_vall{i}; select1=vals(index==Pneig(j));\n        Va=EV_table( select1); Ea=ET_table( select1,:);\n        % Get the tangent and velocity of the edge Pneig -> P\n        index=Ne{Pneig(j)}; vals=ETV_index_vall{Pneig(j)}; select2=vals(index==i);\n        Vb=EV_table(select2); Eb=ET_table(select2,:);\n            \n        % The four points describing the spline\n        P0=V(i,:);\n        P3=V(Pneig(j),:);\n        P1=P0+Ea*Va/3;\n        P2=P3+Eb*Vb/3;\n               \n        % Spline used to calculated the xyz coordinate of the middle of each edge;\n        c = 3*(P1 - P0);\n        b = 3*(P2 - P1) - c;\n        a = P3 - P0 - c - b;\n       \n        halfwayp = a*0.125 + b*0.250 + c*0.500 + P0;\n        \n        % Save the edge middle point\n        if(sum(HT_index{i}==Pneig(j))==0)\n            Vindex=Vindex+1;\n            Vout(Vindex,:)=halfwayp;\n            HT_index {i}= [HT_index{i} Pneig(j)];\n            HT_values{i}=[HT_values{i} Vindex];\n            HT_index {Pneig(j)}=[HT_index{ Pneig(j)} i];\n            HT_values{Pneig(j)}=[HT_values{Pneig(j)} Vindex];\n        end\n    end\nend\nVout=Vout(1:Vindex,:);\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/meshTools/refinepatch_version2b/make_halfway_vertices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5589737307043278}}
{"text": "function f2=f2(x)\nBound=[-10 10];\n\nif nargin==0\n    f2 = Bound;\nelse\n    f2=sum(abs(x))+prod(abs(x));\nend", "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/\u6570\u5b66\u5efa\u6a21\u6bd4\u8d5b\u5e38\u7528\u7684\u4ee3\u7801/\u7c92\u5b50\u7fa4\u7b97\u6cd5/PSO Code/f2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5589737238961805}}
{"text": "function  idsNms = selectBoundingBoxesNonMaxSup( boundingBoxes, scores, varargin )\n%selectBoundingBoxesNonMaxSup performs the NMS on the candidate bounding boxes\n% boxes should be in [X1,Y1,W,H] format\n%\n% idsNms = selectBoundingBoxesNonMaxSup( boundingBoxes, scores )\n%\n% Input: \n%   boundingBoxes - double[ numBoxes x 4], each line correponds to the bounding box in [X1,Y1,W,H] format\n%   scores - double[numBoxes x 1], scores of the bounding boxes, will be sorted in the decreasing order\n% \n% Extra parameters: \n%   nmsIntersectionOverAreaThreshold - IoA threshold used to select boxes\n%   numBoundingBoxMax - maximum number of boxes selected by NMS\n%\n% Output:\n%   idsNms - indices of the bounding boxes selected by NMS\n\nif ~exist('varargin', 'var')\n    varargin = {};\nend\n%% parameters\nopts = struct;\nopts.numBoundingBoxMax = inf;\nopts.nmsIntersectionOverAreaThreshold = 0.3;\nopts = vl_argparse(opts, varargin);\n\n% if opts.nmsIntersectionOverAreaThreshold == inf the code will get into the infinite loop\nopts.nmsIntersectionOverAreaThreshold = min( opts.nmsIntersectionOverAreaThreshold, 100 );\n\n%% do the job\nnumBbs = length(scores);\n[~, ids] = sort(scores, 'descend');\n\nidsNms = nan( min(opts.numBoundingBoxMax, numel(ids)), 1 );\nidsNms(1) = ids(1);\n\nnumBbNms = 1;\niBb = 1;\nwhile numBbNms < opts.numBoundingBoxMax && iBb < numBbs\n    curIou = inf;\n    while max( curIou(:) ) > opts.nmsIntersectionOverAreaThreshold && iBb < numBbs\n        iBb = iBb + 1;\n        curIou = bbIntersectionOverArea( boundingBoxes( idsNms(1 : numBbNms), : ), boundingBoxes( ids(iBb), : ) );\n    end\n    \n    if max( curIou(:) ) <= opts.nmsIntersectionOverAreaThreshold\n        numBbNms = numBbNms + 1;\n        idsNms( numBbNms ) = ids( iBb );\n    end\nend\n\nidsNms = idsNms(1 : numBbNms);\n\nend\n\n", "meta": {"author": "aosokin", "repo": "cnn_head_detection", "sha": "80624e7a25c62f7b504fa6f4d830136beb66eec8", "save_path": "github-repos/MATLAB/aosokin-cnn_head_detection", "path": "github-repos/MATLAB/aosokin-cnn_head_detection/cnn_head_detection-80624e7a25c62f7b504fa6f4d830136beb66eec8/utils/selectBoundingBoxesNonMaxSup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5589737238961805}}
{"text": "function newFaces = minConvexHull(points, varargin)\n%MINCONVEXHULL Return the unique minimal convex hull of a set of 3D points\n%\n%   FACES = minConvexHull(PTS)\n%   NODES is a set of 3D points  (as a Nx3 array). The function computes\n%   the convex hull, and merge contiguous coplanar faces. The result is a\n%   set of polygonal faces, such that there are no coplanar faces.\n%   FACES is a cell array, each cell containing the vector of indices of\n%   nodes given in NODES for the corresponding face.\n%\n%   FACES = minConvexHull(PTS, PRECISION)\n%   Adjust the threshold for deciding if two faces are coplanar or\n%   parallel. Default value is 1e-14.\n%\n%   Example\n%     % extract square faces from a cube\n%     [n, e, f] = createCube;\n%     f2 = minConvexHull(n);\n%     drawMesh(n, f2);\n%\n%     % Subdivides and smooths a mesh rpresenting a cube\n%     [n, e, f] = createCube;\n%     [n2, f2] = subdivideMesh(n, triangulateFaces(f), 4);\n%     [n3, f3] = smoothMesh(n2, f2);\n%     figure; drawMesh(n3, f3);\n%     axis equal; view(3);\n%     % merge coplanar faces, making apparent the faces of the original cube\n%     f4 = minConvexHull(n3);\n%     figure; drawMesh(n3, f4);\n%     axis equal; view(3);\n%\n%\n%   See also\n%   meshes3d, mergeCoplanarFaces, drawMesh, convhull, convhulln\n%\n\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2006-07-05\n% Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n% HISTORY\n%   20/07/2006 add tolerance for coplanarity test\n%   21/08/2006 fix small bug due to difference of methods to test\n%       coplanarity, sometimes resulting in 3 points of a face being not\n%       coplanar! Also add control on precision\n%   18/09/2007 ensure faces are given as horizontal vectors\n\n% set up precision\nacc = 1e-14;\nif ~isempty(varargin)\n    acc = varargin{1};\nend\n\n% triangulated convex hull. It is not uniquely defined.\nfaces = convhulln(points);\n\n% compute centroid of the nodes\npointsCentroid = centroid(points);\n\n% number of base triangular faces\nN = size(faces, 1);\n\n% compute normals of given faces\nnormals = planeNormal(createPlane(...\n    points(faces(:,1),:), points(faces(:,2),:), points(faces(:,3),:)));\n\n% initialize empty faces\nnewFaces = {};\n\n\n% Processing flag for each triangle\n% 1 : triangle to process, 0 : already processed\n% in the beginning, every triangle face need to be processed\nflag = ones(N, 1);\n\n% iterate on each triangular face of the convex hull\nfor iFace = 1:N\n    \n    % check if face was already performed\n    if ~flag(iFace)\n        continue;\n    end\n\n    % indices of faces with same normal\n    ind = find(abs(vectorNorm3d(cross(repmat(normals(iFace, :), [N 1]), normals)))<acc);\n    ind = ind(ind~=iFace);\n    \n    % keep only coplanar faces (test coplanarity of points in both face)\n    ind2 = iFace;\n    for j = 1:length(ind)\n        if isCoplanar(points([faces(iFace,:) faces(ind(j),:)], :), acc)\n            ind2 = [ind2 ind(j)]; %#ok<AGROW>\n        end\n    end\n    \n    \n    % compute order of the vertices in current face\n    faceVertices = unique(faces(ind2, :));\n    [tmp, I]  = angleSort3d(points(faceVertices, :)); %#ok<ASGLU>\n    \n    % create the new face, ensuring it is a row vector\n    face = faceVertices(I);\n    face = face(:)';\n    \n    % ensure face has normal pointing outwards\n    outerNormal = meshFaceCentroids(points, face) - pointsCentroid;\n    if dot(meshFaceNormals(points, face), outerNormal, 2) < 0\n        face = face([1 end:-1:2]);\n    end\n    \n    % add a new face to the list\n    newFaces = [newFaces {face}]; %#ok<AGROW>\n    \n    % mark processed faces\n    flag(ind2) = 0;\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/meshes3d/minConvexHull.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5589737207933934}}
{"text": "function [FRF,FBB] = Receiver(Fopt,NRF)\n\n% randomly generate FRF\n[Nt,Ns] = size(Fopt);\nFRF = [];\nfor i = 1:NRF\n    FRF = blkdiag(FRF, exp(sqrt(-1) * unifrnd (0,2*pi,[Nt/NRF,1])));\nend\nFRF = 1/sqrt(Nt)*FRF;\n\ny = [];\nwhile(isempty(y) || abs(y(1)-y(2))>1e-3)\n    % fix FRF, optimize FBB\n    FBB = pinv(FRF) * Fopt;\n    \n    y(1) = norm(Fopt-FRF*FBB,'fro')^2;\n    \n    % fix FBB, optimize FRF\n    for i = 1:Nt\n        m = ceil(i*NRF/Nt);\n        FRF(i,m) = 1/sqrt(Nt) * exp( sqrt(-1) * angle( Fopt(i,:)*FBB(m,:)' ) );\n    end\n    \n    y(2) = norm(Fopt-FRF*FBB,'fro')^2;\nend\n\nend", "meta": {"author": "yuxianghao", "repo": "Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems", "sha": "18f610e24498f2305a498459150492e17626754b", "save_path": "github-repos/MATLAB/yuxianghao-Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems", "path": "github-repos/MATLAB/yuxianghao-Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems/Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems-18f610e24498f2305a498459150492e17626754b/Narrowband/SDR-AltMin/Receiver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5589388592715037}}
{"text": "function y2=K_q_escorTsallis(P1,P2,q)\n  [M,N]=size(P1);\n    y=ones(1,N);\n    A1=ones(1,N);\n    for n=1:N\n    A1=sum(P1(:,n).^(1/q));\n    A2=sum(P2(:,n).^(1/q));\n       y(1,n)=sum( (P1(:,n)./((A1)^q)).*( ((P2(:,n).^(1/q))/A2).^(1-q) -((P1(:,n).^(1/q))/A1).^(1-q)) );\n    end\n    y2=y/(q-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/18133-shannon-and-non-extensive-entropy/entropy/K_q_escorTsallis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5589388514375897}}
{"text": "%EXnmr_cgls_mrnsd Example script, 2D NMR relaxometry\n\n% Silvia Gazzola, University of Bath\n% Per Christian Hansen, Technical University of Denmark\n% James G. Nagy, Emory University\n% April, 2018.\n\n% Clear workspace and command window.\nclear, clc\n\n% Choose if you would like to see the results displayed in a single figure \n% window ('subplots') or in multiple figure windows ('manyplots').\ndispres = 'subplots';\n% dispres = 'manyplots';\n\nLW = 2;  % Plot line width.\nMS = 10; % Size of markers on plots.\n\nrng(0);  % Make sure this test is repeatable.\n\n% Define the test problem.\nn = 64;\nNoiseLevel = 0.05;\n[A, b, x, ProbInfo] = PRnmr(n);\nbn = PRnoise(b, NoiseLevel);\n\n% Compute a CGLS solution, specifying the noise level for the discrepancy\n% principle, and use true solution to compute error norms.\neta = 1.02;\noptions = IRset('x_true', x, 'NoiseLevel', NoiseLevel, 'eta', eta, 'NoStop', 'on');\n[x_cgls, IterInfo_cgls] = IRcgls(A, bn, 1:500, options);\n\n% Compute MRNSD reconstruction.\nK = [1, 100:100:20000];\n[x_mrnsd, IterInfo_mrnsd] = IRmrnsd(A, bn, K, options);\n\n% Display the reconstructions;\n% uncomment as appropriate to avoid displaying titles and legends.\nif strcmp(dispres, 'subplots')\n    figure(1), clf\n    subplot(3,3,1), PRshowx(x, ProbInfo), colormap hsv\n    title('True solution','interpreter','latex','fontsize',24)\n    set(gca,'fontsize',10)\n    %\n    subplot(3,3,4), PRshowx(IterInfo_cgls.BestReg.X, ProbInfo), colormap hsv\n    title('Best CGLS solution','interpreter','latex','fontsize',24)\n    set(gca,'fontsize',10)\n    %\n    subplot(3,3,2), semilogy(IterInfo_mrnsd.Enrm,'linewidth',1.5)\n    hold on\n    hl = legend('{\\tt info.Enrm}');\n    % hl = legend('IRmrnsd error');\n    set(hl,'interpreter','latex','fontsize',12)\n    semilogy(IterInfo_mrnsd.BestReg.It, IterInfo_mrnsd.BestReg.Enrm, 'ro', 'LineWidth', 1.5, 'MarkerSize', 6)\n    axis([0 max(K) 0.08 1.2])\n    semilogy(IterInfo_mrnsd.StopReg.It, IterInfo_mrnsd.StopReg.Enrm, 'ms', 'LineWidth', 1.5, 'MarkerSize', 6)\n    set(gca,'fontsize',12)\n    title('Error history','interpreter','latex','fontsize',24)\n    set(gca,'fontsize',10)\n    %\n    subplot(3,3,5), PRshowx(IterInfo_mrnsd.BestReg.X, ProbInfo)\n    title(['Best MRNSD sol., $k$ = ',num2str(IterInfo_mrnsd.BestReg.It)],...\n    'interpreter','latex','fontsize',24)\n    set(gca,'fontsize',10)\n    %\n    subplot(3,3,3)\n    semilogy(K,IterInfo_mrnsd.Rnrm(K),'-',K,eta*NoiseLevel*ones(size(K)),'--','linewidth',1.5)\n    hl = legend('{\\tt info.Rnrm}','{\\tt eta*NoiseLevel}','location','northwest');\n    % hl = legend('IRmrnsd residual','{\\tt eta*NoiseLevel}','location','northwest');\n    set(hl,'interpreter','latex')\n    axis([0 max(K) 0.045 0.08])\n    title('Residula history','interpreter','latex','fontsize',24)\n    set(gca,'fontsize',10)\n    %\n    subplot(3,3,6), PRshowx(IterInfo_mrnsd.StopReg.X, ProbInfo)\n    title(['DP MRNSD sol., $k$ = ',num2str(IterInfo_mrnsd.StopReg.It)],...\n    'interpreter','latex','fontsize',24)\n    set(gca,'fontsize',10)\nelseif strcmp(dispres, 'manyplots')\n    figure(1), clf\n    PRshowx(x,ProbInfo), colormap hsv\n    title('True solution','interpreter','latex','fontsize',24)\n    set(gca,'fontsize',24)\n    %\n    figure(2), clf\n    PRshowx(IterInfo_cgls.BestReg.X, ProbInfo), colormap hsv\n    title('Best CGLS solution','interpreter','latex','fontsize',24)\n    set(gca,'fontsize',24)\n    %\n    figure(3), clf\n    semilogy(IterInfo_mrnsd.Enrm,'linewidth',LW)\n    hold on\n    semilogy(IterInfo_mrnsd.BestReg.It, IterInfo_mrnsd.BestReg.Enrm, 'ro', 'LineWidth', LW, 'MarkerSize', MS)\n    semilogy(IterInfo_mrnsd.StopReg.It, IterInfo_mrnsd.StopReg.Enrm, 'ms', 'LineWidth', LW, 'MarkerSize', MS)\n    axis([0 max(K) 0.08 1.2])\n    % hl = legend('{\\tt info.Enrm}','location','North');\n    % set(hl,'interpreter','latex','fontsize',24)\n    hl = legend('IRmrnsd error','optimal stopping iteration', ...\n      'DP stopping iteration','location','North');\n    set(hl,'interpreter','latex','fontsize',16)\n    title('Error history','interpreter','latex','fontsize',24)\n    set(gca,'fontsize',30)\n    %\n    figure(4), clf\n    PRshowx(IterInfo_mrnsd.BestReg.X, ProbInfo), colormap hsv\n    title(['Best MRNSD sol., $k$ = ',num2str(IterInfo_mrnsd.BestReg.It)],...\n    'interpreter','latex','fontsize',24)\n    set(gca,'fontsize',24)\n    %\n    figure(5), clf\n    semilogy(K,IterInfo_mrnsd.Rnrm(K),'-',K,eta*NoiseLevel*ones(size(K)),'--','linewidth',LW)\n    % hl = legend('{\\tt info.Rnrm}','{\\tt eta*NoiseLevel}','location','north');\n    hl = legend('IRmrnsd residual','{\\tt eta*NoiseLevel}','location','north');\n    set(hl,'interpreter','latex','fontsize',24)\n    title('Residual history','interpreter','latex','fontsize',24)\n    axis([0 max(K) 0.045 0.08])\n    set(gca,'fontsize',30)\n    %\n    figure(6), clf\n    PRshowx(IterInfo_mrnsd.StopReg.X,ProbInfo), colormap hsv\n    title(['DP MRNSD sol., $k$ = ',num2str(IterInfo_mrnsd.StopReg.It)],...\n    'interpreter','latex','fontsize',24)\n    set(gca,'fontsize',24)\nend\n\nreturn\n\n% A number of instructions useful to save the displayed figures follow;\n% the defualt is not to execute them. If you wish to save the displayed\n% figures in the dedicated 'Results' folder, please comment the above\n% return statement\noldcd = cd;\nif strcmp(dispres, 'subplots')\n    try\n        cd('Results')\n    catch\n        mkdir('Results')\n        cd('Results')\n    end\n    figure(1), print -dpng -r300 EXnmr\nelseif strcmp(dispres, 'manyplots')\n    try\n        cd('Results')\n    catch\n        mkdir('Results')\n        cd('Results')\n    end\n    % save as eps\n    figure(1), print -depsc -r300 EXnmr_a.eps\n    figure(2), print -depsc -r300 EXnmr_d.eps\n    figure(3), print -depsc -r300 EXnmr_b.eps\n    figure(4), print -depsc -r300 EXnmr_e.eps\n    figure(5), print -depsc -r300 EXnmr_c.eps\n    figure(6), print -depsc -r300 EXnmr_f.eps\n    % save as png\n    figure(1), print -dpng -r300 EXnmr_a\n    figure(2), print -dpng -r300 EXnmr_d\n    figure(3), print -dpng -r300 EXnmr_b\n    figure(4), print -dpng -r300 EXnmr_e\n    figure(5), print -dpng -r300 EXnmr_c\n    figure(6), print -dpng -r300 EXnmr_f\nend\ncd(oldcd)\n\n% Uncomment the following return statement if you wish to save the\n% displayed figures as MATLAB figures\n\n% return\n\noldcd = cd;\nif strcmp(dispres, 'subplots')\n    try\n        cd('Results')\n    catch\n        mkdir('Results')\n        cd('Results')\n    end\n    figure(1), saveas('EXnmr.fig')\nelseif strcmp(dispres, 'manyplots')\n    try\n        cd('Results')\n    catch\n        mkdir('Results')\n        cd('Results')\n    end\n    saveas(figure(1), 'EXnmr_a.fig')\n    saveas(figure(2), 'EXnmr_b.fig')\n    saveas(figure(3), 'EXnmr_c.fig')\n    saveas(figure(4), 'EXnmr_d.fig')\n    saveas(figure(5), 'EXnmr_e.fig')\n    saveas(figure(6), 'EXnmr_f.fig')\nend\ncd(oldcd)", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/EXcodes/EXnmr_cgls_mrnsd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.74316801430083, "lm_q1q2_score": 0.5588716994311205}}
{"text": "function subset_check ( n, t )\n\n%*****************************************************************************80\n%\n%% SUBSET_CHECK checks a subset.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 August 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Donald Kreher, Douglas Simpson,\n%    Combinatorial Algorithms,\n%    CRC Press, 1998,\n%    ISBN: 0-8493-3988-X,\n%    LC: QA164.K73.\n%\n%  Parameters:\n%\n%    Input, integer N, the number of elements in the master set.\n%    N must be positive.\n%\n%    Input, integer T(N), the subset.  If T(I) = 0, item I is\n%    not in the subset; if T(I) = 1, item I is in the subset.\n%\n  if ( n < 1 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'SUBSET_COLEX_RANK - Fatal error!\\n' );\n    fprintf ( 1, '  N = %d < 1.\\n', n );\n    error ( 'SUBSET_COLEX_RANK - Fatal error!' );\n  end\n\n  for i = 1 : n\n\n    if ( t(i) ~= 0 && t(i) ~= 1 )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'SUBSET_COLEX_RANK - Fatal error!\\n' );\n      fprintf ( 1, '  T(%d) = %d, but must be 0 or 1.\\n', i, t(i) );\n      error ( 'SUBSET_COLEX_RANK - 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/combo/subset_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.5588716871872391}}
{"text": "classdef RMMEDA_F5 < PROBLEM\n% <multi> <real> <large/none>\n% Benchmark MOP for testing RM-MEDA\n\n%------------------------------- Reference --------------------------------\n% Q. Zhang, A. Zhou, and Y. Jin, RM-MEDA: A regularity model-based\n% multiobjective estimation of distribution algorithm, IEEE Transactions on\n% Evolutionary Computation, 2008, 12(1): 41-63.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            g = 1 + 9*mean((X(:,2:end).^2-repmat(X(:,1),1,size(X,2)-1)).^2,2);\n            PopObj(:,1) = X(:,1);\n            PopObj(:,2) = g.*(1-sqrt(PopObj(:,1)./g));\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - sqrt(R(:,1));\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R = obj.GetOptimum(100);\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/MOPs with variable linkages/RMMEDA_F5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.5588716868926151}}
{"text": "% ACOT   Inverse cotangent, result in radian.\n%    ACOT(X) is the inverse cotangent of the elements of X.\n% \n%    Class support for input X: \n%       float: double, single\n% \n%    See also COT, ACOTD.\n%\n%    Reference page in Doc Center\n%       doc acot\n%\n%    Other functions named acot\n%\n%       codistributed/acot    gpuArray/acot    sym/acot    ts/acot\n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/classes/time_series/@ts/acot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.558871682614905}}
{"text": "function suborder = triangle_nco_suborder ( rule, suborder_num )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_NCO_SUBORDER returns the suborders for an NCO rule.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 January 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Peter Silvester,\n%    Symmetric Quadrature Formulae for Simplexes,\n%    Mathematics of Computation,\n%    Volume 24, Number 109, January 1970, pages 95-100.\n%\n%  Parameters:\n%\n%    Input, integer RULE, the index of the rule.\n%\n%    Input, integer SUBORDER_NUM, the number of suborders of the rule.\n%\n%    Output, integer SUBORDER(SUBORDER_NUM), the suborders of the rule.\n%\n  if ( rule == 1 )\n    suborder(1:suborder_num) = [ ...\n      1 ];\n  elseif ( rule == 2 )\n    suborder(1:suborder_num) = [ ...\n      3 ];\n  elseif ( rule == 3 )\n    suborder(1:suborder_num) = [ ...\n      3, 3 ];\n  elseif ( rule == 4 )\n    suborder(1:suborder_num) = [ ...\n      3, 6, 1 ];\n  elseif ( rule == 5 )\n    suborder(1:suborder_num) = [ ...\n      3, 6, 3, 3 ];\n  elseif ( rule == 6 )\n    suborder(1:suborder_num) = [ ...\n      3, 6, 6, 3, 3 ];\n  elseif ( rule == 7 )\n    suborder(1:suborder_num) = [ ...\n      3, 6, 6, 3, 3, 6, 1 ];\n  elseif ( rule == 8 )\n    suborder(1:suborder_num) = [ ...\n      3, 6, 6, 3, 6, 6, 3, 3 ];\n  elseif ( rule == 9 )\n    suborder(1:suborder_num) = [ ...\n      3, 6, 6, 3, 6, 6, 3, 6, 3, 3  ];\n\n  else\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'TRIANGLE_NCO_SUBORDER - Fatal error!\\n' );\n    fprintf ( 1, '  Illegal RULE = %d\\n', rule );\n    error ( 'TRIANGLE_NCO_SUBORDER - 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/triangle_nco_rule/triangle_nco_suborder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.5588716786318194}}
{"text": "function [K,H] = calc_Laplacians(I,seg_map,M,eta,beta1,beta2)\n[rows,cols,B] = size(I);\nN = rows*cols;\n\nif isempty(seg_map)\n    [W,Neighbors] = image2graph(I,eta,1e-9);\nelse\n    [W,Neighbors] = image2graph(double(seg_map),1e-3,1e-9);\nend\n\nD = diag(sum(W,2));\nL = D - W;\nL = sparse(L);\nK = L - beta2/beta1*speye(N);\n\nW = ones(M,M);\nD = diag(sum(W,2));\nH = D - W;\n\nW = diag(ones(1,B-1),-1) + diag(ones(1,B-1),1);\nD = diag(sum(W,2));\nG = D - W;\nG = sparse(G);\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/SCM/calc_Laplacians.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.5588570078274409}}
{"text": "function smallpot = marginalize_pot(bigpot, keep, maximize, useC)\n% MARGINALIZE_POT Marginalize a cpot onto a smaller domain.\n% smallpot = marginalize_pot(bigpot, keep, maximize, useC)\n%\n% The maximize argument is ignored - maxing out a Gaussian is the same as summing it out,\n% since the mode and mean are equal.\n% The useC argument is ignored.\n\nnode_sizes = sparse(1, max(bigpot.domain));\nnode_sizes(bigpot.domain) = bigpot.sizes;\nsum_over = mysetdiff(bigpot.domain, keep);\n\nif sum(node_sizes(sum_over))==0 % isempty(sum_over)\n  %smallpot = bigpot;\n  smallpot = cpot(keep, node_sizes(keep), bigpot.g, bigpot.h, bigpot.K);\nelse\n  [h1, h2, K11, K12, K21, K22] = partition_matrix_vec(bigpot.h, bigpot.K, sum_over, keep, node_sizes);\n  n = length(h1);\n  K11inv = inv(K11);\n  g = bigpot.g + 0.5*(n*log(2*pi) - log(det(K11)) + h1'*K11inv*h1);\n  if length(h2) > 0 % ~isempty(keep) % we are are actually keeping something\n    A = K21*K11inv;\n    h = h2 - A*h1;\n    K = K22 - A*K12;\n  else\n    h = [];\n    K = [];\n  end\n  smallpot = cpot(keep, node_sizes(keep), g, h, K);\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/potentials/@cpot/marginalize_pot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5588570035752711}}
{"text": "function [y] = spm_gx_fmri_linear(x,u,P,M)\n% Simulated BOLD response to input (linear version)\n% FORMAT [y] = spm_gx_fmri_linear(x,u,P,M)\n% y          - BOLD response (%)\n% x          - state vector     (see spm_fx_fmri)\n% P          - Parameter vector (see spm_fx_fmri)\n% M          - model specification structure (see spm_nlsi)\n%__________________________________________________________________________\n%\n% This function implements the BOLD signal model described in: \n%\n% Stephan KE, Weiskopf N, Drysdale PM, Robinson PA, Friston KJ (2007)\n% Comparing hemodynamic models with DCM. NeuroImage 38: 387-401.\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston & Klaas Enno Stephan\n% $Id: spm_gx_fmri_linear.m 6262 2014-11-17 13:47:56Z karl $\n \n \n% Biophysical constants for 1.5T\n%==========================================================================\n \n% time to echo (TE) (default 0.04 sec)\n%--------------------------------------------------------------------------\ntry, TE = M.TE; catch, TE = 0.04; end\n \n% resting venous volume (%)\n%--------------------------------------------------------------------------\nV0  = 4;\n\n% estimated region-specific ratios of intra- to extra-vascular signal \n%--------------------------------------------------------------------------\nep  = 1*exp(P.epsilon);\n \n% slope r0 of intravascular relaxation rate R_iv as a function of oxygen \n% saturation S:  R_iv = r0*[(1 - S)-(1 - S0)] (Hz)\n%--------------------------------------------------------------------------\nr0  = 25;\n \n% frequency offset at the outer surface of magnetized vessels (Hz)\n%--------------------------------------------------------------------------\nnu0 = 40.3; \n \n% resting oxygen extraction fraction\n%--------------------------------------------------------------------------\nE0  = 0.4;\n \n%-Coefficients in BOLD signal model\n%==========================================================================\nk1  = 4.3*nu0*E0*TE;\nk2  = ep*r0*E0*TE;\nk3  = 1 - ep;\n \n%-Output equation of BOLD signal model\n%==========================================================================\nv   = x(:,4) + 1;\nq   = x(:,5) + 1;\ny   = V0*((k1 + k2).*(1 - q) + (k3 - k2).*(1 - v));\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_gx_fmri_linear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.558857001842146}}
{"text": "function cache = create_loc_cc_fftn_cache(metric, metric_param_pix, volmov, volfix, internal_dtype, maskfix, deps, loc_cc_approximate)\n%     deps = 1e-5;\n    Nd = 3;\n    if size(volmov, 3) == 1\n        Nd = 2;\n    end\n    szvolfix = [size(volfix, 1), size(volfix, 2), size(volfix, 3)];\n    \n    cache = [];\n    if numel(metric_param_pix) == 1\n        metric_param_pix = metric_param_pix * ones(1,Nd);\n    end\n    metric_param_pix = metric_param_pix(1:Nd);\n    \n    metr_threshold = 0.4;\n    metr_threshold = 0.8;\n    metric_param_pix(metric_param_pix < metr_threshold) = metr_threshold;\n    sgm = metric_param_pix;\n    hsz = max(2*ceil(2*sgm) + 1, 5);\n    filterRadius = (hsz-1)/2;\n    \n    pad_size = ceil(filterRadius);\n    start = pad_size+1;\n\n    stop = start + size(volfix) - 1;\n    vol_fix_p = padarray(volfix, pad_size, 'symmetric');\n    \n    if Nd == 2\n        [n1, n2] = ndgrid(1:size(vol_fix_p,1), 1:size(vol_fix_p,2));\n    elseif Nd == 3\n        [n1, n2, n3] = ndgrid(1:size(vol_fix_p,1), 1:size(vol_fix_p,2), 1:size(vol_fix_p,3));\n    end\n    c = ceil(size(n1)/2)+1;\n    if Nd == 2\n        g = exp(- (n1-c(1)).^2/(2*sgm(1)^2) - (n2-c(2)).^2/(2*sgm(2)^2));\n    elseif Nd == 3\n        g = exp(- (n1-c(1)).^2/(2*sgm(1)^2) - (n2-c(2)).^2/(2*sgm(2)^2) - (n3-c(3)).^2/(2*sgm(3)^2));\n    end\n    \n    g = g/sum(g(:));\n    g = fftshift(g);\n    fg = fftn(g, size(vol_fix_p));\n    convop = @(fx) (ifftn(fftn(fx) .* fg, 'symmetric'));\n\n    mean_fix = convop(vol_fix_p);\n    sgm_fix = convop(vol_fix_p.^2) - mean_fix.^2 + deps;\n    sgm_fix = sqrt(sgm_fix);\n    \n%     maskfix_pad = [];\n    if ~isempty(maskfix)\n        maskfix_pad = padarray(maskfix, pad_size, 'symmetric');\n        sgm_fix = sgm_fix ./ maskfix_pad;\n        sgm_fix_inv = maskfix_pad ./ sgm_fix;\n    else\n        sgm_fix_inv = 1 ./ sgm_fix;\n    end\n    \n    cache.fg = fg;\n    cache.vol_fix_p = vol_fix_p;\n    cache.mean_fix = mean_fix;\n    cache.sgm_fix = sgm_fix;\n    cache.sgm_fix_inv = sgm_fix_inv;\n    cache.start = start;\n    cache.stop = stop;\n    \n    cache.pad_size = pad_size;\n    cache.metric_name = metric;\n    cache.sigma = metric_param_pix;\n    cache.internal_dtype = internal_dtype;\n    cache.deps = deps;\n%     cache.maskfix = maskfix;\n%     cache.maskfix_pad = maskfix_pad;\n    cache.maskfix_pad = [];\n    cache.loc_cc_approximate = loc_cc_approximate;\n    \n    if strcmp(metric, 'loc_cc_fftn_gpu')\n        cache.fg = gpuArray((cache.fg));\n        cache.vol_fix_p = gpuArray((cache.vol_fix_p));\n        cache.mean_fix = gpuArray((cache.mean_fix));\n        cache.sgm_fix = gpuArray((cache.sgm_fix));\n        cache.deps = gpuArray(cache.deps);\n        cache.sgm_fix_inv = gpuArray(sgm_fix_inv);\n%         cache.maskfix = gpuArray(cache.maskfix);\n%         cache.maskfix_pad = gpuArray(cache.maskfix_pad);\n    elseif strcmp(metric, 'loc_cc_fftn_gpu_single')\n        cache.fg = gpuArray(single(cache.fg));\n        cache.vol_fix_p = gpuArray(single(cache.vol_fix_p));\n        cache.mean_fix = gpuArray(single(cache.mean_fix));\n        cache.sgm_fix = gpuArray(single(cache.sgm_fix));\n        cache.deps = gpuArray(single(cache.deps));\n        cache.sgm_fix_inv = gpuArray(single(sgm_fix_inv));\n%         cache.maskfix = gpuArray(single(cache.maskfix));\n%         cache.maskfix_pad = gpuArray(single(cache.maskfix_pad));\n    elseif strcmp(metric, 'loc_cc_fftn_single')\n        cache.fg = (single(cache.fg));\n        cache.vol_fix_p = (single(cache.vol_fix_p));\n        cache.mean_fix = (single(cache.mean_fix));\n        cache.sgm_fix = (single(cache.sgm_fix));\n        cache.deps = (single(cache.deps));\n        cache.sgm_fix_inv = (single(sgm_fix_inv));\n    end\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_metrics/create_loc_cc_fftn_cache.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5588569983758948}}
{"text": "function [f]=comp_idwilt(coef,g)\n%COMP_IDWILT  Compute Inverse discrete Wilson transform.\n% \n%   This is a computational routine. Do not call it\n%   directly.\n\n%   AUTHOR : Peter L. S\u00f8ndergaard.\n%   TESTING: OK\n%   REFERENCE: OK\n\nM=size(coef,1)/2;\nN=2*size(coef,2);\nW=size(coef,3);\n\na=M;\n\nL=N*a;\n\ncoef2=zeros(2*M,N,W,assert_classname(coef,g));\n\n% First and middle modulation are transferred unchanged.\ncoef2(1,1:2:N,:) = coef(1,:,:);\nif mod(M,2)==0\n  coef2(M+1,1:2:N,:) = coef(M+1,:,:);\nelse\n  coef2(M+1,2:2:N,:) = coef(M+1,:,:);\nend;\n\nif M>2\n  % cosine, first column.\n  coef2(3:2:M,1:2:N,:)        = 1/sqrt(2)*coef(3:2:M,:,:);\n  coef2(2*M-1:-2:M+2,1:2:N,:) = 1/sqrt(2)*coef(3:2:M,:,:);\n\n  % sine, second column\n  coef2(3:2:M,2:2:N,:)        = -1/sqrt(2)*i*coef(M+3:2:2*M,:,:);\n  coef2(2*M-1:-2:M+2,2:2:N,:) =  1/sqrt(2)*i*coef(M+3:2:2*M,:,:);\nend;\n\n\n% sine, first column.\ncoef2(2:2:M,1:2:N,:)        = -1/sqrt(2)*i*coef(2:2:M,:,:);\ncoef2(2*M:-2:M+2,1:2:N,:)   =  1/sqrt(2)*i*coef(2:2:M,:,:);\n\n% cosine, second column\ncoef2(2:2:M,2:2:N,:)        = 1/sqrt(2)*coef(M+2:2:2*M,:,:);\ncoef2(2*M:-2:M+2,2:2:N,:)   = 1/sqrt(2)*coef(M+2:2:2*M,:,:);\n\nf = comp_isepdgt(coef2,g,L,a,2*M,0);\n\n\n% Apply the final DGT\n%f=comp_idgt(coef2,g,a,[0 1],0,0);\n\n% Clean signal if it is known to be real\nif (isreal(coef) && isreal(g))\n  f=real(f);\nend;\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_idwilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070838, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5588384375787738}}
{"text": "% SP_EXTERIOR_DERIVAITVE: computes the exterior derivative as a matrix with size \n%  given by the dimension of two consecutive spaces in the De Rham sequence.\n%\n%   diff_op = sp_exterior_derivative (space1, space2);\n%\n% INPUT:\n%\n%   space1:  domain space of the exterior derivative (number of columns)\n%   space2:  image space of the exterior derivative (number of rows)\n%\n% OUTPUT:\n%\n%   diff_op: sparse matrix representation of the differential operator.\n% \n% Copyright (C) 2020-2023 Bernard Kapidani, 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%    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 <http://www.gnu.org/licenses/>.\n\nfunction diff_op = sp_exterior_derivative (space1, space2)\n\n  assert (strcmpi(space1.transform, 'grad-preserving'), ...\n    'The first space cannot be the one for integral-preserving splines (or n-forms)')\n\n  ndim = numel (space1.knots);\n  if (ndim == 1)\n    grad_curl = 'grad';\n    assert (space1.degree == space2.degree+1, 'The degrees are not compatible')\n    assert (numel(space1.knots{1}) == numel(space2.knots{1})+2, 'The knot vectors are not compatible')\n  elseif (ndim == 2)\n    if (strcmpi (space2.transform, 'curl-preserving'))\n      grad_curl = 'grad';\n      deg_shift = {[1 0], [0 1]};\n      knt_shift = {[2 0], [0 2]};\n    elseif (strcmpi (space2.transform, 'div-preserving'))\n      grad_curl = 'curl';\n      deg_shift = {[0 1], [1 0]};\n      knt_shift = {[0 2], [2 0]};\n    else\n      error ('The second space should be either curl-preserving or div-preserving')\n    end\n    for idim = 1:ndim\n      assert (all(space1.degree == space2.scalar_spaces{idim}.degree+deg_shift{idim}), 'The degrees are not compatible')\n      assert (all(cellfun(@numel,space1.knots) == (cellfun(@numel, space2.scalar_spaces{idim}.knots)+knt_shift{idim})), ...\n        'The knot vectors are not compatible')\n    end\n  elseif (ndim == 3)\n    grad_curl = 'grad';\n    deg_shift = {[1 0 0], [0 1 0], [0 0 1]};\n    knt_shift = {[2 0 0], [0 2 0], [0 0 2]};\n    assert (strcmpi(space2.transform, 'curl-preserving'), ...\n      'The second space should be the one for curl-conforming splines')\n    for idim = 1:ndim\n      assert (all(space1.degree == space2.scalar_spaces{idim}.degree+deg_shift{idim}), 'The degrees are not compatible')\n      assert (all(cellfun(@numel,space1.knots) == (cellfun(@numel, space2.scalar_spaces{idim}.knots)+knt_shift{idim})), ...\n        'The knot vectors are not compatible')\n    end\n  end\n  \n  diff_ops = op_geom_exterior (space1.knots, space1.degree, grad_curl);\n  diff_op = diff_ops{1};\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_scalar/sp_exterior_derivative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5588038343328455}}
{"text": "function t_modcost(quiet)\n%T_MODCOST  Tests for code in MODCOST.\n\n%   MATPOWER\n%   Copyright (c) 2010-2016, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\nif nargin < 1\n    quiet = 0;\nend\n\nn_tests = 162;\n\nt_begin(n_tests, quiet);\n\n%% define named indices into data matrices\n[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;\n\n%% generator cost data\n%\t1\tstartup\tshutdown\tn\tx1\ty1\t...\txn\tyn\n%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\ngencost0 = [\n\t2\t0\t0\t3\t0.01\t0.1\t1\t0\t0\t0\t0\t0;\n\t2\t0\t0\t5\t0.0006\t0.005\t0.04\t0.3\t2\t0\t0\t0;\n\t1\t0\t0\t4\t0\t0\t10\t200\t20\t600\t30\t1200;\n\t1\t0\t0\t4\t-30\t-2400\t-20\t-1800\t-10\t-1000\t0\t0;\n];\n\n%%-----  scalar values for alpha  -----\ngencost = modcost(gencost0, 5, 'SCALE_F');\n\nt = 'modcost SCALE_F - quadratic';\nt_is(totcost(gencost, [0;0;0;0])/5, [1;2;0;0], 8, t);\nt_is(totcost(gencost, [1;0;0;0])/5, [1.11;2;0;0], 8, t);\nt_is(totcost(gencost, [2;0;0;0])/5, [1.24;2;0;0], 8, t);\n\nt = 'modcost SCALE_F - 4th order polynomial';\nt_is(totcost(gencost, [0;0;0;0])/5, [1;2;     0;0], 8, t);\nt_is(totcost(gencost, [0;1;0;0])/5, [1;2.3456;0;0], 8, t);\nt_is(totcost(gencost, [0;2;0;0])/5, [1;2.8096;0;0], 8, t);\n\nt = 'modcost SCALE_F - pwl (gen)';\nt_is(totcost(gencost, [0;0;5;0 ])/5, [1;2;100;0], 8, t);\nt_is(totcost(gencost, [0;0;10;0])/5, [1;2;200;0], 8, t);\nt_is(totcost(gencost, [0;0;15;0])/5, [1;2;400;0], 8, t);\nt_is(totcost(gencost, [0;0;20;0])/5, [1;2;600;0], 8, t);\nt_is(totcost(gencost, [0;0;25;0])/5, [1;2;900;0], 8, t);\nt_is(totcost(gencost, [0;0;30;0])/5, [1;2;1200;0], 8, t);\nt_is(totcost(gencost, [0;0;35;0])/5, [1;2;1500;0], 8, t);\n\nt = 'modcost SCALE_F - pwl (load)';\nt_is(totcost(gencost, [0;0;0;-5 ])/5, [1;2;0;-500], 8, t);\nt_is(totcost(gencost, [0;0;0;-10])/5, [1;2;0;-1000], 8, t);\nt_is(totcost(gencost, [0;0;0;-15])/5, [1;2;0;-1400], 8, t);\nt_is(totcost(gencost, [0;0;0;-20])/5, [1;2;0;-1800], 8, t);\nt_is(totcost(gencost, [0;0;0;-25])/5, [1;2;0;-2100], 8, t);\nt_is(totcost(gencost, [0;0;0;-30])/5, [1;2;0;-2400], 8, t);\nt_is(totcost(gencost, [0;0;0;-35])/5, [1;2;0;-2700], 8, t);\n\n\ngencost = modcost(gencost0, 2, 'SCALE_X');\n\nt = 'modcost SCALE_X - quadratic';\nt_is(totcost(gencost, [0;0;0;0]*2), [1;2;0;0], 8, t);\nt_is(totcost(gencost, [1;0;0;0]*2), [1.11;2;0;0], 8, t);\nt_is(totcost(gencost, [2;0;0;0]*2), [1.24;2;0;0], 8, t);\n\nt = 'modcost SCALE_X - 4th order polynomial';\nt_is(totcost(gencost, [0;0;0;0]*2), [1;2;     0;0], 8, t);\nt_is(totcost(gencost, [0;1;0;0]*2), [1;2.3456;0;0], 8, t);\nt_is(totcost(gencost, [0;2;0;0]*2), [1;2.8096;0;0], 8, t);\n\nt = 'modcost SCALE_X - pwl (gen)';\nt_is(totcost(gencost, [0;0;5;0 ]*2), [1;2;100;0], 8, t);\nt_is(totcost(gencost, [0;0;10;0]*2), [1;2;200;0], 8, t);\nt_is(totcost(gencost, [0;0;15;0]*2), [1;2;400;0], 8, t);\nt_is(totcost(gencost, [0;0;20;0]*2), [1;2;600;0], 8, t);\nt_is(totcost(gencost, [0;0;25;0]*2), [1;2;900;0], 8, t);\nt_is(totcost(gencost, [0;0;30;0]*2), [1;2;1200;0], 8, t);\nt_is(totcost(gencost, [0;0;35;0]*2), [1;2;1500;0], 8, t);\n\nt = 'modcost SCALE_X - pwl (load)';\nt_is(totcost(gencost, [0;0;0;-5 ]*2), [1;2;0;-500], 8, t);\nt_is(totcost(gencost, [0;0;0;-10]*2), [1;2;0;-1000], 8, t);\nt_is(totcost(gencost, [0;0;0;-15]*2), [1;2;0;-1400], 8, t);\nt_is(totcost(gencost, [0;0;0;-20]*2), [1;2;0;-1800], 8, t);\nt_is(totcost(gencost, [0;0;0;-25]*2), [1;2;0;-2100], 8, t);\nt_is(totcost(gencost, [0;0;0;-30]*2), [1;2;0;-2400], 8, t);\nt_is(totcost(gencost, [0;0;0;-35]*2), [1;2;0;-2700], 8, t);\n\n\ngencost = modcost(gencost0, 3, 'SHIFT_F');\n\nt = 'modcost SHIFT_F - quadratic';\nt_is(totcost(gencost, [0;0;0;0])-3, [1;2;0;0], 8, t);\nt_is(totcost(gencost, [1;0;0;0])-3, [1.11;2;0;0], 8, t);\nt_is(totcost(gencost, [2;0;0;0])-3, [1.24;2;0;0], 8, t);\n\nt = 'modcost SHIFT_F - 4th order polynomial';\nt_is(totcost(gencost, [0;0;0;0])-3, [1;2;     0;0], 8, t);\nt_is(totcost(gencost, [0;1;0;0])-3, [1;2.3456;0;0], 8, t);\nt_is(totcost(gencost, [0;2;0;0])-3, [1;2.8096;0;0], 8, t);\n\nt = 'modcost SHIFT_F - pwl (gen)';\nt_is(totcost(gencost, [0;0;5;0 ])-3, [1;2;100;0], 8, t);\nt_is(totcost(gencost, [0;0;10;0])-3, [1;2;200;0], 8, t);\nt_is(totcost(gencost, [0;0;15;0])-3, [1;2;400;0], 8, t);\nt_is(totcost(gencost, [0;0;20;0])-3, [1;2;600;0], 8, t);\nt_is(totcost(gencost, [0;0;25;0])-3, [1;2;900;0], 8, t);\nt_is(totcost(gencost, [0;0;30;0])-3, [1;2;1200;0], 8, t);\nt_is(totcost(gencost, [0;0;35;0])-3, [1;2;1500;0], 8, t);\n\nt = 'modcost SHIFT_F - pwl (load)';\nt_is(totcost(gencost, [0;0;0;-5 ])-3, [1;2;0;-500], 8, t);\nt_is(totcost(gencost, [0;0;0;-10])-3, [1;2;0;-1000], 8, t);\nt_is(totcost(gencost, [0;0;0;-15])-3, [1;2;0;-1400], 8, t);\nt_is(totcost(gencost, [0;0;0;-20])-3, [1;2;0;-1800], 8, t);\nt_is(totcost(gencost, [0;0;0;-25])-3, [1;2;0;-2100], 8, t);\nt_is(totcost(gencost, [0;0;0;-30])-3, [1;2;0;-2400], 8, t);\nt_is(totcost(gencost, [0;0;0;-35])-3, [1;2;0;-2700], 8, t);\n\n\ngencost = modcost(gencost0, -4, 'SHIFT_X');\n\nt = 'modcost SHIFT_X - quadratic';\nt_is(totcost(gencost, [0;0;0;0]-4), [1;2;0;0], 8, t);\nt_is(totcost(gencost, [1;0;0;0]-4), [1.11;2;0;0], 8, t);\nt_is(totcost(gencost, [2;0;0;0]-4), [1.24;2;0;0], 8, t);\n\nt = 'modcost SHIFT_X - 4th order polynomial';\nt_is(totcost(gencost, [0;0;0;0]-4), [1;2;     0;0], 8, t);\nt_is(totcost(gencost, [0;1;0;0]-4), [1;2.3456;0;0], 8, t);\nt_is(totcost(gencost, [0;2;0;0]-4), [1;2.8096;0;0], 8, t);\n\nt = 'modcost SHIFT_X - pwl (gen)';\nt_is(totcost(gencost, [0;0;5;0 ]-4), [1;2;100;0], 8, t);\nt_is(totcost(gencost, [0;0;10;0]-4), [1;2;200;0], 8, t);\nt_is(totcost(gencost, [0;0;15;0]-4), [1;2;400;0], 8, t);\nt_is(totcost(gencost, [0;0;20;0]-4), [1;2;600;0], 8, t);\nt_is(totcost(gencost, [0;0;25;0]-4), [1;2;900;0], 8, t);\nt_is(totcost(gencost, [0;0;30;0]-4), [1;2;1200;0], 8, t);\nt_is(totcost(gencost, [0;0;35;0]-4), [1;2;1500;0], 8, t);\n\nt = 'modcost SHIFT_X - pwl (load)';\nt_is(totcost(gencost, [0;0;0;-5 ]-4), [1;2;0;-500], 8, t);\nt_is(totcost(gencost, [0;0;0;-10]-4), [1;2;0;-1000], 8, t);\nt_is(totcost(gencost, [0;0;0;-15]-4), [1;2;0;-1400], 8, t);\nt_is(totcost(gencost, [0;0;0;-20]-4), [1;2;0;-1800], 8, t);\nt_is(totcost(gencost, [0;0;0;-25]-4), [1;2;0;-2100], 8, t);\nt_is(totcost(gencost, [0;0;0;-30]-4), [1;2;0;-2400], 8, t);\nt_is(totcost(gencost, [0;0;0;-35]-4), [1;2;0;-2700], 8, t);\n\nt = 'modcost empty gencost';\ngencost = modcost([], 7);\nt_ok(isempty(gencost), t);\n\n%%-----  vector values for alpha  -----\nalpha = [10; 9; 8; 7];\ngencost = modcost(gencost0, alpha, 'SCALE_F');\n\nt = 'modcost vector SCALE_F - quadratic';\nt_is(totcost(gencost, [0;0;0;0])./alpha, [1;2;0;0], 8, t);\nt_is(totcost(gencost, [1;0;0;0])./alpha, [1.11;2;0;0], 8, t);\nt_is(totcost(gencost, [2;0;0;0])./alpha, [1.24;2;0;0], 8, t);\n\nt = 'modcost vector SCALE_F - 4th order polynomial';\nt_is(totcost(gencost, [0;0;0;0])./alpha, [1;2;     0;0], 8, t);\nt_is(totcost(gencost, [0;1;0;0])./alpha, [1;2.3456;0;0], 8, t);\nt_is(totcost(gencost, [0;2;0;0])./alpha, [1;2.8096;0;0], 8, t);\n\nt = 'modcost vector SCALE_F - pwl (gen)';\nt_is(totcost(gencost, [0;0;5;0 ])./alpha, [1;2;100;0], 8, t);\nt_is(totcost(gencost, [0;0;10;0])./alpha, [1;2;200;0], 8, t);\nt_is(totcost(gencost, [0;0;15;0])./alpha, [1;2;400;0], 8, t);\nt_is(totcost(gencost, [0;0;20;0])./alpha, [1;2;600;0], 8, t);\nt_is(totcost(gencost, [0;0;25;0])./alpha, [1;2;900;0], 8, t);\nt_is(totcost(gencost, [0;0;30;0])./alpha, [1;2;1200;0], 8, t);\nt_is(totcost(gencost, [0;0;35;0])./alpha, [1;2;1500;0], 8, t);\n\nt = 'modcost vector SCALE_F - pwl (load)';\nt_is(totcost(gencost, [0;0;0;-5 ])./alpha, [1;2;0;-500], 8, t);\nt_is(totcost(gencost, [0;0;0;-10])./alpha, [1;2;0;-1000], 8, t);\nt_is(totcost(gencost, [0;0;0;-15])./alpha, [1;2;0;-1400], 8, t);\nt_is(totcost(gencost, [0;0;0;-20])./alpha, [1;2;0;-1800], 8, t);\nt_is(totcost(gencost, [0;0;0;-25])./alpha, [1;2;0;-2100], 8, t);\nt_is(totcost(gencost, [0;0;0;-30])./alpha, [1;2;0;-2400], 8, t);\nt_is(totcost(gencost, [0;0;0;-35])./alpha, [1;2;0;-2700], 8, t);\n\n\ngencost = modcost(gencost0, alpha, 'SCALE_X');\n\nt = 'modcost vector SCALE_X - quadratic';\nt_is(totcost(gencost, [0;0;0;0].*alpha), [1;2;0;0], 8, t);\nt_is(totcost(gencost, [1;0;0;0].*alpha), [1.11;2;0;0], 8, t);\nt_is(totcost(gencost, [2;0;0;0].*alpha), [1.24;2;0;0], 8, t);\n\nt = 'modcost vector SCALE_X - 4th order polynomial';\nt_is(totcost(gencost, [0;0;0;0].*alpha), [1;2;     0;0], 8, t);\nt_is(totcost(gencost, [0;1;0;0].*alpha), [1;2.3456;0;0], 8, t);\nt_is(totcost(gencost, [0;2;0;0].*alpha), [1;2.8096;0;0], 8, t);\n\nt = 'modcost vector SCALE_X - pwl (gen)';\nt_is(totcost(gencost, [0;0;5;0 ].*alpha), [1;2;100;0], 8, t);\nt_is(totcost(gencost, [0;0;10;0].*alpha), [1;2;200;0], 8, t);\nt_is(totcost(gencost, [0;0;15;0].*alpha), [1;2;400;0], 8, t);\nt_is(totcost(gencost, [0;0;20;0].*alpha), [1;2;600;0], 8, t);\nt_is(totcost(gencost, [0;0;25;0].*alpha), [1;2;900;0], 8, t);\nt_is(totcost(gencost, [0;0;30;0].*alpha), [1;2;1200;0], 8, t);\nt_is(totcost(gencost, [0;0;35;0].*alpha), [1;2;1500;0], 8, t);\n\nt = 'modcost vector SCALE_X - pwl (load)';\nt_is(totcost(gencost, [0;0;0;-5 ].*alpha), [1;2;0;-500], 8, t);\nt_is(totcost(gencost, [0;0;0;-10].*alpha), [1;2;0;-1000], 8, t);\nt_is(totcost(gencost, [0;0;0;-15].*alpha), [1;2;0;-1400], 8, t);\nt_is(totcost(gencost, [0;0;0;-20].*alpha), [1;2;0;-1800], 8, t);\nt_is(totcost(gencost, [0;0;0;-25].*alpha), [1;2;0;-2100], 8, t);\nt_is(totcost(gencost, [0;0;0;-30].*alpha), [1;2;0;-2400], 8, t);\nt_is(totcost(gencost, [0;0;0;-35].*alpha), [1;2;0;-2700], 8, t);\n\n\ngencost = modcost(gencost0, alpha, 'SHIFT_F');\n\nt = 'modcost vector SHIFT_F - quadratic';\nt_is(totcost(gencost, [0;0;0;0])-alpha, [1;2;0;0], 8, t);\nt_is(totcost(gencost, [1;0;0;0])-alpha, [1.11;2;0;0], 8, t);\nt_is(totcost(gencost, [2;0;0;0])-alpha, [1.24;2;0;0], 8, t);\n\nt = 'modcost vector SHIFT_F - 4th order polynomial';\nt_is(totcost(gencost, [0;0;0;0])-alpha, [1;2;     0;0], 8, t);\nt_is(totcost(gencost, [0;1;0;0])-alpha, [1;2.3456;0;0], 8, t);\nt_is(totcost(gencost, [0;2;0;0])-alpha, [1;2.8096;0;0], 8, t);\n\nt = 'modcost vector SHIFT_F - pwl (gen)';\nt_is(totcost(gencost, [0;0;5;0 ])-alpha, [1;2;100;0], 8, t);\nt_is(totcost(gencost, [0;0;10;0])-alpha, [1;2;200;0], 8, t);\nt_is(totcost(gencost, [0;0;15;0])-alpha, [1;2;400;0], 8, t);\nt_is(totcost(gencost, [0;0;20;0])-alpha, [1;2;600;0], 8, t);\nt_is(totcost(gencost, [0;0;25;0])-alpha, [1;2;900;0], 8, t);\nt_is(totcost(gencost, [0;0;30;0])-alpha, [1;2;1200;0], 8, t);\nt_is(totcost(gencost, [0;0;35;0])-alpha, [1;2;1500;0], 8, t);\n\nt = 'modcost vector SHIFT_F - pwl (load)';\nt_is(totcost(gencost, [0;0;0;-5 ])-alpha, [1;2;0;-500], 8, t);\nt_is(totcost(gencost, [0;0;0;-10])-alpha, [1;2;0;-1000], 8, t);\nt_is(totcost(gencost, [0;0;0;-15])-alpha, [1;2;0;-1400], 8, t);\nt_is(totcost(gencost, [0;0;0;-20])-alpha, [1;2;0;-1800], 8, t);\nt_is(totcost(gencost, [0;0;0;-25])-alpha, [1;2;0;-2100], 8, t);\nt_is(totcost(gencost, [0;0;0;-30])-alpha, [1;2;0;-2400], 8, t);\nt_is(totcost(gencost, [0;0;0;-35])-alpha, [1;2;0;-2700], 8, t);\n\n\ngencost = modcost(gencost0, -alpha, 'SHIFT_X');\n\nt = 'modcost vector SHIFT_X - quadratic';\nt_is(totcost(gencost, [0;0;0;0]-alpha), [1;2;0;0], 8, t);\nt_is(totcost(gencost, [1;0;0;0]-alpha), [1.11;2;0;0], 8, t);\nt_is(totcost(gencost, [2;0;0;0]-alpha), [1.24;2;0;0], 8, t);\n\nt = 'modcost vector SHIFT_X - 4th order polynomial';\nt_is(totcost(gencost, [0;0;0;0]-alpha), [1;2;     0;0], 8, t);\nt_is(totcost(gencost, [0;1;0;0]-alpha), [1;2.3456;0;0], 8, t);\nt_is(totcost(gencost, [0;2;0;0]-alpha), [1;2.8096;0;0], 8, t);\n\nt = 'modcost vector SHIFT_X - pwl (gen)';\nt_is(totcost(gencost, [0;0;5;0 ]-alpha), [1;2;100;0], 8, t);\nt_is(totcost(gencost, [0;0;10;0]-alpha), [1;2;200;0], 8, t);\nt_is(totcost(gencost, [0;0;15;0]-alpha), [1;2;400;0], 8, t);\nt_is(totcost(gencost, [0;0;20;0]-alpha), [1;2;600;0], 8, t);\nt_is(totcost(gencost, [0;0;25;0]-alpha), [1;2;900;0], 8, t);\nt_is(totcost(gencost, [0;0;30;0]-alpha), [1;2;1200;0], 8, t);\nt_is(totcost(gencost, [0;0;35;0]-alpha), [1;2;1500;0], 8, t);\n\nt = 'modcost vector SHIFT_X - pwl (load)';\nt_is(totcost(gencost, [0;0;0;-5 ]-alpha), [1;2;0;-500], 8, t);\nt_is(totcost(gencost, [0;0;0;-10]-alpha), [1;2;0;-1000], 8, t);\nt_is(totcost(gencost, [0;0;0;-15]-alpha), [1;2;0;-1400], 8, t);\nt_is(totcost(gencost, [0;0;0;-20]-alpha), [1;2;0;-1800], 8, t);\nt_is(totcost(gencost, [0;0;0;-25]-alpha), [1;2;0;-2100], 8, t);\nt_is(totcost(gencost, [0;0;0;-30]-alpha), [1;2;0;-2400], 8, t);\nt_is(totcost(gencost, [0;0;0;-35]-alpha), [1;2;0;-2700], 8, t);\n\nt = 'modcost vector empty gencost';\ngencost = modcost([], alpha);\nt_ok(isempty(gencost), t);\n\nt_end;\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/t/t_modcost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5588038288759718}}
{"text": "% Undistort points using camera parameters\n%\n% This function is much faster than Matlab's undistortPoints and works on large\n% point sets. The code is based on cvUndistortPoints function from OpenCV library.\n% Also this function works with NaN values.\n%\n%  USAGE\n%   undistortedPoints = undistortPoints(points, cameraParams)\n%   points              Nx2 ([x y]) matrix of points.\n%   cameraParams        Camera calibration information.\n%   undistortedPoints   Nx2 ([x y]) matrix with undistorted points.\n%\nfunction undistortedPoints = undistortPoints(points, cameraParams)\n    origin = [cameraParams.IntrinsicMatrix(3, 1:2)];\n    cx = origin(1);\n    cy = origin(2);\n    fx = cameraParams.IntrinsicMatrix(1, 1);\n    fy = cameraParams.IntrinsicMatrix(2, 2);\n    ifx = 1 / fx;\n    ify = 1 / fy;\n    iters = 50;\n    k = cameraParams.RadialDistortion;\n    p_coef = cameraParams.TangentialDistortion;\n    \n    if length(k) == 2\n        k(3) = 0;\n    end\n\n    x = points(:, 1);\n    y = points(:, 2);\n    x = (x - cx) .* ifx;\n    y = (y - cy) .* ify;\n    x0 = x;\n    y0 = y;\n\n    for j = 1:iters\n        r2 = x.*x + y.*y;\n        icdist = 1 ./ (1 + ((k(3).*r2 + k(2)).*r2 + k(1)) .* r2);\n        deltaX = 2.*p_coef(1).*x.*y + p_coef(2).*(r2 + 2.*x.*x);\n        deltaY = p_coef(1) .* (r2 + 2.*y.*y) + 2.*p_coef(2).*x.*y;\n        x = (x0 - deltaX) .* icdist;\n        y = (y0 - deltaY) .* icdist;\n    end\n\n    undistortedPoints(:, 1) = round(x .* fx + cx);\n    undistortedPoints(:, 2) = round(y .* fy + cy);\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/+helpers/undistortPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.558803823419098}}
{"text": "function [d,S] = solve_for_d_S(Y,A,R,options)\n[N,B] = size(Y);\nM = size(A,2);\n\nsigma0 = 0.1; % initial sigma\nsigma_max = 1;\nsigma_min = 1e-9;\ndelta_t0 = 1e-9;\n\ndisp('Start estimating D and S');\nC = kron((A'*A),eye(B));\nYAR = (Y-A*R)';\nZ = YAR*A;\nE = diag(sum(YAR.^2,2));\nF1 = YAR*A;\nF = zeros(M*B,B);\nfor i = 1:M\n    F((i-1)*B+1:i*B,:) = diag(F1(:,i));\nend\n\nd = (1/N)*sum(YAR.^2,2);\nd = 1./sqrt(d);\n\nS = eye(M*B,M*B);\nif 0\n    u = 1/sqrt(B) * ones(B,1);\n    S1 = sigma0^2*u*u' + 1e-4*eye(B);\n    S1 = inv(S1);\nelse\n    S1 = sigma0^(-2)*eye(B);\nend\n\nfor j = 1:M\n    inds = (j-1)*B+1:j*B;\n    S(inds,inds) = diag(1./d) * S1 * diag(1./d);\nend\n\nerrors2 = eval_obj_fun_D_S(S,d,C,YAR,Z,M,B,N);\nfor iter = 1:300\n    % solve for S\n    z = diag(d)*Z;\n    z = z(:);\n    if 0\n        obj_fun_S = @(S) eval_obj_fun_S(S,C,z,M,B);\n        fun_der_S = @(S) calc_der_S(S,C,z,M,B);\n        proj_fun_S = @(S) project_to_spd(S,d,sigma_min,sigma_max,M,B);\n\n        S = projected_gradient_descent(S, obj_fun_S, fun_der_S, ...\n            proj_fun_S, delta_t0);\n    else\n        if 1\n            proj_fun_S = @(S) project_to_spd(S,d,sigma_min,sigma_max,1,B);\n            for j = 1:M\n                obj_fun_Sj = @(Sj) eval_obj_fun_Sj(Sj,S,C,z,M,B,j);\n                fun_der_Sj = @(Sj) calc_der_Sj(Sj,S,C,z,B,j);\n                inds = (j-1)*B+1:j*B;\n                Sj = S(inds,inds);\n                Sj = projected_gradient_descent(Sj, obj_fun_Sj, fun_der_Sj, ...\n                    proj_fun_S, 1e-5);\n                S(inds,inds) = Sj;\n            end\n        else\n            der_S = calc_der_S(S,C,z,M,B);\n            proj_fun_S = @(S) project_to_spd(S,d,sigma_min,sigma_max,1,B);\n            for j = 1:M\n                obj_fun_Sj = @(Sj) eval_obj_fun_Sj(Sj,S,C,z,M,B,j);\n                fun_der_Sj = @(Sj) calc_der_Sj_approx(Sj,der_S,B,j);\n                inds = (j-1)*B+1:j*B;\n                Sj = S(inds,inds);\n                Sj = projected_gradient_descent(Sj, obj_fun_Sj, fun_der_Sj, ...\n                    proj_fun_S, 1e-3);\n                S(inds,inds) = Sj;\n            end\n        end\n    end\n    \n    % solve for D\n    Q = S + C;\n    G = (1/N)*(E-F'*(Q\\F));\n    fcn_d = @(d) G*d - 1./d;\n    fsolve_opts = optimset('Display','off');\n    d = fsolve(fcn_d, 1./sqrt((1/N)*diag(E)), fsolve_opts);\n        \n    % calc error\n    err = eval_obj_fun_D_S(S,d,C,YAR,Z,M,B,N);\n    errors2 = [errors2;err];\n    if test_convergence(errors2, 1e-8), break; end\n    \n    if mod(iter,10) == 0\n        disp(['Process iteration ',num2str(iter),'. The objective ',...\n            'function has value ',num2str(err)]);\n    end\nend\n\n\nfunction S = project_to_spd(S,d,sigma_min,sigma_max,M,B)\ntouch_bd = 0;\nS = (S + S')/2;\nfor j = 1:M\n    inds = (j-1)*B+1:j*B;\n    S3 = S(inds,inds);\n    SigmaInv = diag(d) * S3 * diag(d);\n    [V,D] = eig(SigmaInv);\n    d1 = diag(D);\n    low_bd = 1/(sigma_max^2);\n    up_bd = 1/(sigma_min^2);\n    \n    if ~isempty(find(d1<low_bd, 1))\n        touch_bd = touch_bd + 1;\n%         break;\n    end\n    \n    d1(d1<low_bd) = low_bd;\n    d1(d1>up_bd) = up_bd;\n    S(inds,inds) = diag(1./d)*V*diag(d1)*V'*diag(1./d);\nend\n\nif touch_bd >= 1\n%     disp(['Uncertainty amount upper bound touched ',num2str(touch_bd),' times']);\n    \n    % Once uncertainty amount upper bound touched. It means the change of\n    % the covariance is too large. Setting S to 0 will make the objective\n    % function be Inf, thus revoke the delta_t.\n    \n%     if touch_bd >= 1\n%         S = 0 * eye(M*B);\n%     end\nend\n\n\nfunction val = eval_obj_fun_Sj(Sj,S,C,z,M,B,j)\ninds = (j-1)*B+1:j*B;\nS(inds,inds) = Sj;\nval = eval_obj_fun_S(S,C,z,M,B);\n\n\nfunction val = eval_obj_fun_S(S,C,z,M,B)\nQ = S + C;\n% R = chol(Q);\nval1 = 0;\nfor j = 1:M     \n    inds = (j-1)*B+1:j*B;\n    val1 = val1 + logdet(S(inds,inds));\nend\n\n% val = -z'*(Q\\z) + logdet(Q) - val1;\nR = chol(Q);\ny = R'\\z;\nval = -sum(y.^2) + 2*sum(log(diag(R))) - val1;\n\nfunction val = eval_obj_fun_D_S(S,d,C,YAR,Z,M,B,N)\nz = diag(d)*Z;\nz = z(:);\n\nval = eval_obj_fun_S(S,C,z,M,B);\nval = val + sum(sum((diag(d)*YAR).^2)) - 2*N*sum(log(d));\n\n\nfunction der = calc_der_S(S,C,z,M,B)\nQ = S + C;\ninvQ = inv(Q);\ny = invQ*z;\nT = y*y';\nder = zeros(M*B,M*B);\nfor j = 1:M\n    inds = (j-1)*B+1:j*B;\n    Sj = S(inds,inds);\n    der(inds,inds) = T(inds,inds) + invQ(inds,inds) - inv(Sj);\nend\n\n% der_norm = norm(der,'fro');\n% der = der/der_norm;\n\n\nfunction der = calc_der_Sj(Sj,S,C,z,B,j)\ninds = (j-1)*B+1:j*B;\nS(inds,inds) = Sj;\n\nQ = S + C;\ninvQ = inv(Q);\ny = invQ*z;\nT = y*y';\nder = zeros(B,B);\n\nder = T(inds,inds) + invQ(inds,inds) - inv(Sj);\n\nder_norm = norm(der,'fro');\nder = der/der_norm;\n\nfunction der = calc_der_Sj_approx(Sj,der_S,B,j)\ninds = (j-1)*B+1:j*B;\nder = der_S(inds,inds);\n\nder_norm = norm(der,'fro');\nder = der/der_norm;\n\nfunction d = solve_for_d1(Y,A,R,S)\n[N,B] = size(Y);\nM = size(A,2);\n\nYAR = Y - A*R;\nE = diag(sum(YAR.^2,1));\n\nQ = S + kron((A'*A),eye(B));\n\nF1 = A'*YAR;\nF = zeros(M*B,B);\nfor i = 1:M\n    F((i-1)*B+1:i*B,:) = diag(F1(i,:));\nend\nG = (1/N)*(E-F'*(Q\\F));\n\nfcn_d = @(d) G*d - 1./d;\nd = fsolve(fcn_d, 1./sqrt((1/N)*diag(E)));", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/SCM/solve_for_d_S.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5588038177949286}}
{"text": "function ef = cpf_qlim_event(cb_data, cx)\n%CPF_QLIM_EVENT  Event function to detect gen reactive power limit violations\n%   EF = CPF_QLIM_EVENT(CB_DATA, CX)\n%\n%   CPF event function to detect generator reactive power limit violations,\n%   i.e. Qg <= Qmin or Qg >= Qmax.\n%\n%   Inputs:\n%       CB_DATA : struct of data for callback functions\n%       CX : struct containing info about current point (continuation soln)\n%\n%   Outputs:\n%       EF : event function value\n\n%   MATPOWER\n%   Copyright (c) 2016, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%   and Shrirang Abhyankar, Argonne National Laboratory\n%\n%   This file is part of MATPOWER.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://matpower.org for more info.\n\n%% event function value is 2 ng x 1 vector equal to:\n%%      [ Qg - Qmax ]\n%%      [ Qmin - Qg ]\n\n%% define named indices into bus, gen, branch matrices\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n\n%% get updated MPC\nd = cb_data;\nmpc = cpf_current_mpc(d.mpc_base, d.mpc_target, ...\n    d.Ybus, d.Yf, d.Yt, d.ref, d.pv, d.pq, cx.V, cx.lam, d.mpopt);\n\n%% compute Qg violations for on-line gens, not at PQ buses\nnb = size(mpc.bus, 1);\nng = size(mpc.gen, 1);\non = find(mpc.gen(:, GEN_STATUS) > 0 & ...  %% which generators are on?\n          mpc.bus(mpc.gen(:, GEN_BUS), BUS_TYPE) ~= PQ);  %% ... and are not PQ buses\ngbus = mpc.gen(on, GEN_BUS);                %% what buses are they at?\nngon = size(on, 1);\n\n%% build connection matrix, element i, j is 1 if gen on(i) at bus j is ON\nCg = sparse((1:ngon)', gbus, ones(ngon, 1), ngon, nb);\nC = Cg * Cg';\n\n%% violations are based on total violation at bus, not individual violations\n%% (see https://github.com/MATPOWER/matpower/issues/26)\nv_Qmax = NaN(ng, 1);\nv_Qmin = v_Qmax;\nv_Qmax(on) = C * (mpc.gen(on, QG) - mpc.gen(on, QMAX));\nv_Qmin(on) = C * (mpc.gen(on, QMIN) - mpc.gen(on, QG));\n\n%% assemble event function value\nef = [v_Qmax; v_Qmin];\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/cpf_qlim_event.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.558803817627633}}
{"text": "% [INPUT]\n% data = A float t-by-n matrix containing the time series to be sanitized.\n% x = A vector of length t containing the numeric observation dates of the time series (if empty, observations are assumed to be linearly spaced between 1 and t).\n% w = An integer [5,21] representing the length of the moving window used to detect outliers (if empty, no outliers replacement is performed).\n% m = A vector of 2 floats (-Inf,Inf) containing minimum and maximum clamping values (if empty, no clamping is performed).\n%\n% [OUTPUT]\n% data = A float t-by-n matrix containing the sanitized time series.\n\nfunction data = sanitize_data(varargin)\n\n    persistent ip;\n\n    if (isempty(ip))\n        ip = inputParser();\n        ip.addRequired('data',@(x)validateattributes(x,{'double'},{'real' '2d' 'nonempty'}));\n        ip.addRequired('x',@(x)validateattributes(x,{'double'},{'real'}));\n        ip.addRequired('w',@(x)validateattributes(x,{'double'},{'real'}));\n        ip.addRequired('m',@(x)validateattributes(x,{'double'},{'real'}));\n    end\n\n    ip.parse(varargin{:});\n\n    ipr = ip.Results;\n    data = ipr.data;\n    [x,w,m] = validate_input(data,ipr.x,ipr.w,ipr.m);\n\n    nargoutchk(1,1);\n\n    data = sanitize_data_internal(data,x,w,m);\n\nend\n\nfunction data = sanitize_data_internal(data,x,w,m)\n\n    for i = 1:size(data,2)\n        y = data(:,i);\n\n        nan_indices = isnan(y);\n\n        if (all(nan_indices))\n            continue;\n        end\n\n        if (any(nan_indices))\n            y = fill_missing_values(y,x,nan_indices);\n        end\n\n        if (~isempty(w))\n            y = replace_outliers(y,x,w);\n        end\n\n        if (~isempty(m))\n            y = min(max(y,m(1)),m(2));\n        end\n\n        data(:,i) = y;\n    end\n\nend\n\nfunction y = fill_missing_values(y,x,nan_indices)\n\n    d = diff(nan_indices);\n\n    if (nan_indices(1))\n        z = find(d == -1,1,'first');\n        y(1:z) = y(z+1);\n        nan_indices(1:z) = 0;\n    end\n\n    if (nan_indices(end))\n        z = find(d == 1,1,'last');\n        y(z+1:end) = y(z);\n        nan_indices(z+1:end) = 0;\n    end\n\n    y(nan_indices) = spline(x(~nan_indices),y(~nan_indices),x(nan_indices));\n\nend\n\nfunction y = replace_outliers(y,x,w)\n\n    f = 3 * (-1 / (sqrt(2) * erfcinv(1.5)));\n    k = floor(w * 0.5);\n    n = numel(y);\n    p = nan(k,1);\n\n    xp = [p; y; p];\n\n    m_med = zeros(n,1);\n    m_mad = zeros(n,1);\n\n    for i = 1:k\n        x_i = y(1:k+i);\n        m = median(x_i);\n\n        m_med(i) = m;\n        m_mad(i) = median(abs(x_i - m));\n    end\n\n    for i = k+1:n-k-1\n        x_i = xp(i:i+w,:);\n        m = median(x_i);\n\n        m_med(i) = m;\n        m_mad(i) = median(abs(x_i - m));\n    end\n\n    for i = n-k:n\n        x_i = y(i-k:end);\n        m = median(x_i);\n\n        m_med(i) = m;\n        m_mad(i) = median(abs(x_i - m));\n    end\n\n    b = m_mad .* f;\n    lb = m_med - b;\n    ub = m_med + b;\n\n    is_outlier = (y > ub) | (y < lb);\n    d = diff(is_outlier);\n\n    if (is_outlier(1) == 1)\n        z = find(d == -1,1,'first');\n        y(1:z) = y(z+1);\n        is_outlier(1:z) = 0;\n    end\n\n    if (is_outlier(end))\n        z = find(d == 1,1,'last');\n        y(z+1:end) = y(z);\n        is_outlier(z+1:end) = 0;\n    end\n\n    y(is_outlier) = spline(x(~is_outlier),y(~is_outlier),x(is_outlier));\n\nend\n\nfunction [x,w,m] = validate_input(data,x,w,m)\n\n    t = size(data,1);\n\n    if (isempty(x))\n        x = 1:t;\n    else\n        if (~isvector(x))\n            error('The value of ''x'' is invalid. Expected input to be a vector.');\n        end\n\n        if (numel(x) ~= t)\n            error(['The value of ''x'' is invalid. Expected input to contain ' num2str(t) ' elements.']);\n        end\n\n        if (~all(isfinite(x)))\n            error('The value of ''x'' is invalid. Expected input to contain finite elements.');\n        end\n\n        if (~all(diff(x) > 0))\n            error('The value of ''x'' is invalid. Expected input to contain increasing elements.');\n        end\n    end\n\n    if (~isempty(w))\n        if (~isscalar(w))\n            error('The value of ''w'' is invalid. Expected input to be a scalar.');\n        end\n\n        if (~isfinite(w))\n            error('The value of ''w'' is invalid. Expected input to be finite.');\n        end\n\n        if (floor(w) ~= w)\n            error('The value of ''w'' is invalid. Expected input to be an integer.');\n        end\n\n        if ((w < 5) || (w > 21))\n            error('The value of ''w'' is invalid. Expected input to have a value >= 5 and <= 21.');\n        end\n\n        w = w - 1;\n    end\n\n    if (~isempty(m))\n        if (~isvector(m))\n            error('The value of ''m'' is invalid. Expected input to be a vector.');\n        end\n\n        if (numel(m) ~= 2)\n            error('The value of ''m'' is invalid. Expected input to contain 2 elements.');\n        end\n\n        if (~all(isfinite(m)))\n            error('The value of ''m'' is invalid. Expected input to contain finite elements.');\n        end\n\n        if (any(floor(m) ~= m))\n            error('The value of ''m'' is invalid. Expected input to contain integer elements.');\n        end\n\n        if (m(1) >= m(2))\n            error('The value of ''m'' is invalid. Expected input first element to be less than the input second element.');\n        end\n    end\n\nend\n", "meta": {"author": "TommasoBelluzzo", "repo": "SystemicRisk", "sha": "f5e9b4823eabab2130974e535d13762c0cb3e4bf", "save_path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk", "path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk/SystemicRisk-f5e9b4823eabab2130974e535d13762c0cb3e4bf/ScriptsData/sanitize_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5588038176276329}}
{"text": "function [model, B, elapse] = AGH2_learn(A, maxbits, Anchor,s)\n%   This is a function of Two Layer AGH (Anchor Graph Hashing) learning.\n%\n%\tUsage:\n%\t[model, B,elapse] = AGH2_learn(A, maxbits, Anchor,s)\n%\n%\t      A: Rows of vectors of data points. Each row is sample point\n%   maxbits: Code length\n%    Anchor: Anchors (landmarks), Each row is sample point\n%         s: Number of nearest anchor to learn a representation\n%            of the sample vector \n%\n%     model: Used for encoding a test sample point.\n%\t      B: The binary code of the input data A. Each row is sample point\n%    elapse: The coding time (training time).\n%\n%\n%\n%   version 2.0 --Nov/2016 \n%   version 1.0 --Jan/2014 \n%\n%   Written by  Yue Lin (linyue29@gmail.com)\n%               Deng Cai (dengcai AT gmail DOT com) \n%                                             \n\ntmp_T = tic;\n\noptions.CodingMethod = 'Gaussian';\n\nnAnchor = 1500;\nif ~exist('Anchor','var')\n    [~,Anchor]=litekmeans(A,nAnchor,'MaxIter',5,'Replicates',1);\nend\nif ~exist('s','var')\n    s = 50;\nend\n\n[B, W, Thres, sigma] = TwoLayerAGH_Train(A, Anchor, maxbits, s, 0, options);\n\nmodel.W = W;\nmodel.Thres = Thres;\nmodel.sigma = sigma;\nmodel.Anchor = Anchor;\nmodel.s = s;\nmodel.options = options;\n\nelapse = toc(tmp_T);\nend\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/ANNS/Hashing/Unsupervised/AGH2_learn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5588038120034631}}
{"text": "function edge = lineToEdge(line)\n%LINETOEDGE Convert a straight line to a finite edge.\n%\n%   EDGE = lineToEdge(LINE)\n%   Returns the edge with same origin as the line LINE, and with second\n%   extremity corresponding to the addition of line origin and direction.\n%   LINE is represented as [X0 Y0  DX DY]\n%   EDGE is represented as [X1 Y1  X2 Y2]\n%\n%   Example\n%     line = [3 4  1 2];\n%     edge = lineToEdge(line)\n%     edge =\n%          3   4   4   6\n%\n%   See also \n%     lines2d, edges2d, edgeToLine\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2019-05-07, using Matlab 9.6.0.1072779 (R2019a)\n% Copyright 2019-2022 INRA - Cepia Software Platform\n\nedge = [line(:, 1:2) line(:,1:2)+line(:,3:4)];\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom2d/lineToEdge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.5587687269610471}}
{"text": "function [varargout] = ndgrid(varargin)\n\n%   NDGRID Generation of arrays for N-D functions and interpolation.\n%   [X1,X2,X3,...] = NDGRID(x1,x2,x3,...) transforms the domain\n%   specified by vectors x1,x2,x3, etc. into arrays X1,X2,X3, etc. that\n%   can be used for the evaluation of functions of N variables and N-D\n%   interpolation.  The i-th dimension of the output array Xi are copies\n%   of elements of the vector xi.\n%\n%   [X1,X2,...] = NDGRID(x) is the same as [X1,X2,...] = NDGRID(x,x,...).\n%\n%   For example, to evaluate the function  x2*exp(-x1^2-x2^2-x^3) over the\n%   range  -2 < x1 < 2,  -2 < x2 < 2, -2 < x3 < 2,\n%\n%       [x1,x2,x3] = ndgrid(-2:.2:2, -2:.25:2, -2:.16:2);\n%       z = x2 .* exp(-x1.^2 - x2.^2 - x3.^2);\n%       slice(x2,x1,x3,z,[-1.2 .8 2],2,[-2 -.2])\n%\n%   NDGRID is like MESHGRID except that the order of the first two input\n%   arguments are switched (i.e., [X1,X2,X3] = NDGRID(x1,x2,x3) produces\n%   the same result as [X2,X1,X3] = MESHGRID(x2,x1,x3)).  Because of\n%   this, NDGRID is better suited to N-D problems that aren't spatially\n%   based, while MESHGRID is better suited to problems in cartesian\n%   space (2-D or 3-D).\n%\n%   This is a drop-in replacement for the matlab version in elmat, which is\n%   relatively slow for big grids. FIXME this function still only works up\n%   to 5 dimensions\n%\n%   See also MESHGRID, INTERPN.\n\n%   Copyright(C) 2010, Jan-Mathijs Schoffelen, DCCN\n%\n% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip\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 <http://www.gnu.org/licenses/>.\n%\n% $Id: ndgrid.m 2956 2011-02-25 19:57:31Z jansch $\n\nif nargin==0\n  error('MATLAB:ndgrid:NotEnoughInputs', 'Not enough input arguments.');\nend\nif nargin==1, varargin = repmat(varargin,[1 max(nargout,2)]); end\n\nndims = numel(varargin);\nswitch ndims\ncase 2\n  ones1 = ones(1,numel(varargin{1}));\n  ones2 = ones(1,numel(varargin{2}));\n  \n  x   = varargin{1}(:);\n  y   = varargin{2}(:)';\n  \n  varargout{1} = x(:, ones2);\n  varargout{2} = y(ones1, :);\ncase 3\n  ones1 = ones(1,numel(varargin{1}));\n  ones2 = ones(1,numel(varargin{2}));\n  ones3 = ones(1,numel(varargin{3}));\n  \n  x   = varargin{1}(:);\n  y   = varargin{2}(:)';\n  z   = zeros(1,1,numel(varargin{3}));\n  z(:) = varargin{3};\n  \n  varargout{1} = x(:, ones2, ones3);\n  varargout{2} = y(ones1, :, ones3);\n  varargout{3} = z(ones1, ones2, :);\ncase 4\n  ones1 = ones(1,numel(varargin{1}));\n  ones2 = ones(1,numel(varargin{2}));\n  ones3 = ones(1,numel(varargin{3}));\n  ones4 = ones(1,numel(varargin{4}));\n  \n  x   = varargin{1}(:);\n  y   = varargin{2}(:)';\n  z   = zeros(1,1,numel(varargin{3}));\n  z(:) = varargin{3};\n  xx   = zeros(1,1,1,numel(varargin{4}));\n  xx(:) = varargin{4};\n  \n  varargout{1} = x(:, ones2, ones3, ones4);\n  varargout{2} = y(ones1, :, ones3, ones4);\n  varargout{3} = z(ones1, ones2, :, ones4);\n  varargout{4} = xx(ones1, ones2, ones3, :);\ncase 5\n  ones1 = ones(1,numel(varargin{1}));\n  ones2 = ones(1,numel(varargin{2}));\n  ones3 = ones(1,numel(varargin{3}));\n  ones4 = ones(1,numel(varargin{4}));\n  ones5 = ones(1,numel(varargin{5}));\n  \n  x   = varargin{1}(:);\n  y   = varargin{2}(:)';\n  z   = zeros(1,1,numel(varargin{3}));\n  z(:) = varargin{3};\n  xx   = zeros(1,1,1,numel(varargin{4}));\n  xx(:) = varargin{4};\n  yy   = zeros(1,1,1,1,numel(varargin{5}));\n  yy(:) = varargin{5};\n  \n  varargout{1} = x(:, ones2, ones3, ones4, ones5);\n  varargout{2} = y(ones1, :, ones3, ones4, ones5);\n  varargout{3} = z(ones1, ones2, :, ones4, ones5);\n  varargout{4} = xx(ones1, ones2, ones3, :,ones5);\n  varargout{5} = yy(ones1, ones2, ones3, :,ones5);\notherwise\n  error('this version of ndgrid supports inputs up to 5 dimensions');\n  %call the ndgrid from elmat\n  %FIXME this has to be done\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/external/fileio/private/ndgrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.5587687187984391}}
{"text": "function blas1_z_test02 ( )\n\n%*****************************************************************************80\n%\n%% TEST02 tests DZNRM2.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 January 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 5;\n\n  x = [ ...\n     2.0 - 1.0 * i, ...\n    -4.0 - 2.0 * i, ...\n     3.0 + 1.0 * i, ...\n     2.0 + 2.0 * i, ...\n    -1.0 - 1.0 * i ];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST02\\n' );\n  fprintf ( 1, '  DZNRM2 returns the Euclidean norm of a complex vector.\\n' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The vector X:\\n' );\n  fprintf ( 1, '\\n' );\n  for j = 1 : n\n    fprintf ( 1, '  %6d  %10f  %10f\\n', j, real ( x(j) ), imag ( x(j) ) );\n  end\n\n  incx = 1;\n  norm = dznrm2 ( n, x, incx );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The L2 norm of X is %f\\n', 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/blas1_z/blas1_z_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.558768710635831}}
{"text": "function test_suite=test_pca\n% tests for cosmo_pca\n%\n% #   For CoSMoMVPA's copyright information and license terms,   #\n% #   see the COPYING file distributed with CoSMoMVPA.           #\n    try % assignment of 'localfunctions' is necessary in Matlab >= 2016\n        test_functions=localfunctions();\n    catch % no problem; early Matlab versions can use initTestSuite fine\n    end\n    initTestSuite;\n\n\nfunction [pca_samples,coef,mu,expl]=helper_cosmo_pca_wrapper(samples,...\n                                                            keep_count)\n    if isnan(keep_count)\n        args={};\n    else\n        args={keep_count};\n    end\n\n    [pca_samples,params]=cosmo_pca(samples,args{:});\n    coef=params.coef;\n    mu=params.mu;\n    expl=params.explained;\n\nfunction [pca_samples,coef,mu,expl]=helper_matlab_pca_wrapper(samples,...\n                                                            keep_count)\n    % PCA implementation using Matlab statistics toolbox\n    cosmo_check_external('!pca',true);\n\n    if isnan(keep_count)\n        args={};\n    else\n        args={'NumComponents',keep_count};\n    end\n\n    [coef,pca_samples,unused,unused,expl,mu]=pca(samples,args{:});\n    expl=expl';\n\n\n\nfunction test_pca_more_samples_than_features\n    nsamples=ceil(rand()*10)+10;\n    nfeatures=nsamples+10;\n\n    nfeatures=5;\n    nsamples=2;\n\n    helper_test_pca_correspondence(nsamples,nfeatures)\n\nfunction test_pca_more_features_than_samples\n    nfeatures=ceil(rand()*10)+10;\n    nsamples=nfeatures+10;\n\n    helper_test_pca_correspondence(nsamples,nfeatures)\n\nfunction test_pca_col_vector\n    nfeatures=1;\n    nsamples=ceil(rand()*10)+10;\n\n    helper_test_pca_correspondence(nsamples,nfeatures)\n\nfunction test_pca_row_vector\n    nfeatures=ceil(rand()*10)+10;\n    nsamples=1;\n\n    helper_test_pca_correspondence(nsamples,nfeatures)\n\n\nfunction test_pca_near_square_samples\n    nfeatures=ceil(rand()*10)+10;\n    for nsamples=nfeatures+(-1:1);\n        helper_test_pca_correspondence(nsamples,nfeatures)\n    end\n\n\n\nfunction test_pca_too_many_components\n    nsamples=ceil(rand()*10)+10;\n    nfeatures=nsamples;\n    for nkeep=nfeatures+(-1:1)\n        handle=@()cosmo_pca(rand(nsamples,nfeatures),nkeep);\n        if nkeep>nfeatures\n            assertExceptionThrown(handle,'');\n        else\n            handle(); % should be ok\n        end\n    end\n\nfunction test_pca_regression\n    xs=[   2.032   -0.8918  -0.8258    1.163    1.157   -1.291   ;...\n           0.5838   1.844    1.166    -0.8484   3.493   -0.1991  ;...\n          -1.444   -0.2617  -1.921     3.085   -1.372    1.727   ;...\n          -0.5177   2.339    0.4412    1.856    0.4794   0.08323 ;...\n           1.191   -0.204   -0.2088    1.755   -0.9548   0.5012  ;...\n          -1.326    2.724    0.1476    0.5024   3.407   -0.4803  ];\n\n    s=[  -0.5008    2.8648   -0.7589   -0.5301    0.0144  ;...\n          3.5030    0.5915    0.2537    0.8888    0.0226  ;...\n         -3.8914   -1.6525   -0.7549    0.4558    0.0157  ;...\n          0.1140   -1.3350    1.0615   -0.7253    0.0293  ;...\n         -2.1851    1.0744    0.9553    0.2445   -0.0444  ;...\n          2.9603   -1.5432   -0.7566   -0.3338   -0.0376];\n\n    coef=[  0.0014    0.7569    0.3369   -0.0540    0.3234  ;...\n            0.4052   -0.5164    0.4105   -0.3355   -0.0290  ;...\n            0.3133    0.0275    0.6618    0.0901    0.1745  ;...\n           -0.4294   -0.2190   -0.0420   -0.5306    0.6797  ;...\n            0.7090    0.0436   -0.5070    0.0744    0.4815  ;...\n           -0.2251   -0.3313    0.1456    0.7677    0.4127];\n\n    mu=[0.0864    0.9248   -0.2001    1.2522    1.0349    0.0568];\n\n    explained=[64.7794   26.0994    6.0071    3.1059    0.0082];\n\n    for nkeep=[NaN,1:7]\n        if isnan(nkeep)\n            args={};\n            ncomp=5;\n        else\n            args={nkeep};\n            ncomp=min(nkeep,5);\n        end\n\n\n        if nkeep>6\n            assertExceptionThrown(@()cosmo_pca(xs,args{:}),'');\n        else\n            [xs_pca,param]=cosmo_pca(xs,args{:});\n\n            tolerance_arg={'absolute',5e-3};\n            assertElementsAlmostEqual(xs_pca,s(:,1:ncomp),...\n                                        tolerance_arg{:});\n\n            expected_fieldnames={'coef','explained','mu'};\n            assertEqual(sort(fieldnames(param)),...\n                            sort(expected_fieldnames(:)));\n            assertElementsAlmostEqual(param.coef,coef(:,1:ncomp),...\n                                                tolerance_arg{:});\n            assertElementsAlmostEqual(param.mu,mu,...\n                                                tolerance_arg{:});\n            assertElementsAlmostEqual(param.explained,explained,...\n                                                tolerance_arg{:});\n\n        end\n    end\n\n\nfunction test_pca_basic_properties\n    nfeatures=ceil(rand()*10+10);\n    nsamples=ceil(rand()*10+10)+nfeatures;\n\n    x=randn(nsamples,nfeatures);\n    [y,param]=cosmo_pca(x);\n\n    % explained variance is on diagonal\n    d=y'*y;\n    assertElementsAlmostEqual(100*diag(d)/trace(d),param.explained');\n\n    % components are orthogonal\n    d_zero_diag=d-diag(diag(d));\n    assertElementsAlmostEqual(d_zero_diag,zeros(nfeatures));\n\n    % average is computed correctly\n    assertElementsAlmostEqual(mean(x,1),param.mu);\n\n    % x can be reconstructed\n    assertElementsAlmostEqual(x,bsxfun(@plus,param.mu,y*param.coef'));\n\nfunction test_pca_exceptions()\n    aet=@(varargin)assertExceptionThrown(@()...\n                    cosmo_pca(varargin{:}),'');\n    aet(struct);\n    aet({1});\n    aet(randn([2 2 2 ]));\n\nfunction helper_test_pca_correspondence(nsamples,nfeatures)\n    if cosmo_skip_test_if_no_external('!pca')\n        return;\n    end\n\n    for nkeep=[NaN,-1,0,1,...\n                ceil(nsamples/2),ceil(nfeatures/2),...\n                nsamples-1,nfeatures-1,...\n                nsamples,nfeatures,nsamples+1,nfeatures+1]\n        helper_test_pca_correspondence_nkeep(nsamples,nfeatures,nkeep);\n    end\n\nfunction helper_test_pca_correspondence_nkeep(nsamples,nfeatures,nkeep)\n    x=rand(nsamples,nfeatures);\n    try\n        % if the following statement throws an exception, then\n        % matlab's pca must also throw an exception\n        [p1,c1,m1,e1]=helper_matlab_pca_wrapper(x,nkeep);\n    catch\n        % cosmo pca should also throw error\n        assertExceptionThrown(@()helper_cosmo_pca_wrapper(x,nkeep),'');\n        return\n    end\n\n    % no error, verify that output match\n    [p2,c2,m2,e2]=helper_cosmo_pca_wrapper(x,nkeep);\n\n    tolerance_arg={'relative',1e-5};\n    assertElementsAlmostEqual(p1,p2,tolerance_arg{:});\n    assertElementsAlmostEqual(c1,c2,tolerance_arg{:});\n    assertElementsAlmostEqual(m1,m2,tolerance_arg{:});\n    assertElementsAlmostEqual(e1,e2,tolerance_arg{:});\n\n\nfunction test_pca_retain_is_row_vector()\n    nsamples=ceil(10+rand()*10);\n    x=randn(nsamples);\n    [y,params]=cosmo_pca(x);\n    assertEqual(size(params.explained),[1 nsamples-1]);", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/tests/test_pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760727, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5587687060635872}}
{"text": "function [W,varW,X,varX] = gprotate2pca(W,varW,X,varX,weights)\n\n[M,D] = size(W);\nN = cols(X);\n\n%WW = W'*W + diag(rowsum(varW));\n\n% $$$ % Use ML zero mean (mu should be updated after this function!!) ..\n% $$$ dmu = mean(X,2);\n\n% $$$ % Move bias\n% $$$ X = X - repmat(dmu,1,n);\n% $$$ mu = mu + W*dmu;\n\nQx = 1;\n\n%warning('DISCARDING VARIANCES!!')\n\n% Whiten w.r.t. X\nmuX = mean(X,2);\nX0 = bsxfun(@minus,X,muX);\nXX = X0*X0' + diag(colsum(varX));\n% $$$ if fixw\n% $$$   [Vx,Dx,tmp] = svd(XX/(n-m)); % USE THIS IF FIXED w ??\n% $$$ else\n[Vx,Dx,tmp] = svd(XX/N);\n% $$$ end\nQx = diag(1./sqrt(diag(Dx))) * Vx';\nQw = Vx*sqrt(Dx);\nW = W * Qw;\nfor i=1:M\n  varW(i,:) = diag(Qw'*diag(varW(i,:))*Qw);\nend\nX = Qx * X;\nfor j = 1:N\n  varX(:,j) = diag(Qx*diag(varX(:,j))*Qx');\nend\n\nrotationX = Qx;\n\n% $$$ % Check that XX is really whitened! (because of numerical issues!!)\n% $$$ XX = X*X' + sum(CovX,3);\n% $$$ if fixw\n% $$$   [Vx,Dx,tmp] = svd(XX/(n-m)); % USE THIS IF FIXED w ??\n% $$$ else\n% $$$   [Vx,Dx,tmp] = svd(XX/n);\n% $$$ end\n% $$$ if Dx(1) > 1.1\n% $$$   % Whiten w.r.t. X AGAIN\n% $$$   Qx = diag(1./sqrt(diag(Dx))) * Vx';\n% $$$   Qw = Vx*sqrt(Dx);\n% $$$   W = W * Qw;\n% $$$   for i=1:size(CovW,3)\n% $$$     CovW(:,:,i) = Qw'*CovW(:,:,i)*Qw;\n% $$$   end\n% $$$   X = Qx * X;\n% $$$   for j = 1:size(CovX,3)\n% $$$     Sv{j} = Qx*Sv{j}*Qx';\n% $$$     CovX(:,:,j) = Qx*CovX(:,:,j)*Qx';\n% $$$   end\n% $$$ end\n\nQx = 1;\n% Diagonalize w.r.t. W\nWW = W'*W + diag(rowsum(varW));\n% Use weights!!\nif nargin >= 5\n  WW = W'*diag(weights(:))*W + diag(weights(:)' * varW);\n%  WW = W'*diag(weights(:))*W + diag(rowsum(varW));\n% $$$   w = sqrt(weights);\n% $$$   WW = bsxfun(@times, WW, w(:));\n% $$$   WW = bsxfun(@times, WW, w(:)');\nend\n%WW = W'*W + sum(CovW,3);\n[Vw,Dw,tmp] = svd(WW);\n%norms_of_W = sqrt(diag(Dw))\n%[Dw,I] = sort(diag(Dw), 'descend');\n%Vw = Vw(:,I);\nQx = Vw' * Qx;\nQw = Vw;\nW = W * Qw;\nfor i=1:M\n  varW(i,:) = diag(Qw'*diag(varW(i,:))*Qw);\nend\nX = Qx * X;\nfor j = 1:N\n  varX(:,j) = diag(Qx*diag(varX(:,j))*Qx');\nend\n\nrotationX = Qx * rotationX;\n\n% Rotate such that, the largest loadings are positive\nfor d=1:cols(W)\n  if max(W(:,d)) < max(-W(:,d))\n    W(:,d) = -W(:,d);\n    X(d,:) = -X(d,:);\n  end\nend\n\n% $$$ figure\n% $$$ imagesc(abs(rotationX));\n% $$$ \n% $$$ figure\n% $$$ plot( sum(W.^2,1) )\n% $$$ \n% $$$ figure\n% $$$ plot( diag(Dw) )\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gppca/gprotate2pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5587678541992411}}
{"text": "close all; clearvars; clc;\nN = 256;\nPhi = spx.dict.simple.dirac_hadamard_mtx(N);\nfigure;\nimagesc(Phi);\ncolorbar;\nexport_fig images/demo_dirac_hadamard_1.png -r120 -nocrop;\n\nmu1 = spx.dict.babel(Phi);\nfigure;\nplot(mu1);\ngrid on;\nexport_fig images/demo_dirac_hadamard_babel.png -r120 -nocrop;\n\n\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/docs/book/sparse_signal_models/demo_dirac_hadamard_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5587678435238691}}
{"text": "function y = BasisQuadPhiX(x1,x2)\ny = [x1*x1;\n    x1*x2;\n    x2*x2;\n    x1*x1*x1;\n    x1*x1*x2;\n    x1*x2*x2;\n    x2*x2*x2;\n    x1*x1*x1*x1;\n    x1*x1*x1*x2;\n    x1*x1*x2*x2;\n    x1*x2*x2*x2;\n    x2*x2*x2*x2;];\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/Chapter4_Example3/BasisQuadPhiX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.5587678321462233}}
{"text": "%IMM_UPDATE  UKF based Interacting Multiple Model (IMM) Filter update step\n%\n% Syntax:\n%   [X_i,P_i,MU,X,P] = IMM_UPDATE(X_p,P_p,c_j,ind,dims,Y,H,R)\n%\n% In:\n%   X_p  - Cell array containing N^j x 1 mean state estimate vector for\n%          each model j after prediction step\n%   P_p  - Cell array containing N^j x N^j state covariance matrix for \n%          each model j after prediction step\n%   c_j  - Normalizing factors for mixing probabilities\n%   ind  - Indices of state components for each model as a cell array\n%   dims - Total number of different state components in the combined system\n%   Y    - Dx1 measurement vector.\n%   H    - Measurement matrices for each model as a cell array.\n%   h    - Measurement mean\n%   param - parameters\n%   R    - Measurement noise covariances for each model as a cell array.\n%\n% Out:\n%   X_i  - Updated state mean estimate for each model as a cell array\n%   P_i  - Updated state covariance estimate for each model as a cell array\n%   MU   - Probabilities of each model\n%   X    - Combined state mean estimate\n%   P    - Combined state covariance estimate\n%   \n% Description:\n%   IMM-UKF filter measurement update step. If some of the models have linear\n%   measurements standard Kalman filter update step is used for those.\n%\n% See also:\n%   IMM_PREDICT, IMM_SMOOTH, IMM_FILTER\n\n% History:\n%   01.11.2007 JH The first official version.\n%\n% Copyright (C) 2007 Jouni Hartikainen\n%\n% $Id: imm_update.m 111 2007-11-01 12:09:23Z jmjharti $\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\nfunction [X_i,P_i,MU,X,P] = uimm_update(X_p,P_p,c_j,ind,dims,Y,H,h,R,param)\n    % Number of models \n    m = length(X_p);\n\n    % Space for update state mean, covariance and likelihood of measurements\n    X_i = cell(1,m);\n    P_i = cell(1,m);\n    lambda = zeros(1,m);\n\n    % Update for each model\n    for i = 1:m\n        % Update the state estimates\n        if isempty(h) | isempty(h{i})\n            [X_i{i}, P_i{i}, K, IM, IS, lambda(i)] = kf_update(X_p{i},P_p{i},Y,H{i},R{i});\n        else            \n            [X_i{i}, P_i{i}, K, IM, IS, lambda(i)] = ukf_update1(X_p{i},P_p{i},Y,h{i},R{i},param{i});\n        end\n    end\n    \n    % Calculate the model probabilities\n    MU = zeros(1,m); \n    c = sum(lambda.*c_j);\n    MU = c_j.*lambda/c;\n    \n    % In case lambda's happen to be zero    \n    if c == 0\n        MU = c_j;\n    end\n    \n    % Output the combined updated state mean and covariance, if wanted.\n    if nargout > 3\n        % Space for estimates\n        X = zeros(dims,1);\n        P = zeros(dims,dims);\n        % Updated state mean\n        for i = 1:m\n            X(ind{i}) = X(ind{i}) + MU(i)*X_i{i};\n        end\n        % Updated state covariance\n        for i = 1:m\n            P(ind{i},ind{i}) = P(ind{i},ind{i}) + MU(i)*(P_i{i} + (X_i{i}-X(ind{i}))*(X_i{i}-X(ind{i}))');\n        end\n    end\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/uimm_update.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.558738942660072}}
{"text": "% BETALPR - Beta Distribution - Log Probability Ratio\n% Copyright (c) 1998, Harvard University. Full copyright in the file Copyright\n% \n%   [ lpr ] = betalpr(p1,p2,alpha,beta)\n%\n% returns the log of the p(p1) / p(p2) when both\n% are distributed Beta(alpha,beta).\n%\n% See also: METROP, *LPR\n\nfunction [ lpr ] = betalpr(p1,p2,alpha,beta)\nlpr = (alpha-1) * log(p1/p2) + (beta-1) * log((1-p1)/(1-p2)) ;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/198-mcmc/mcmc/betalpr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5587114337459413}}
{"text": "addpath data/\n\npatch_dim = 64;\nnum_patches = 10000;\nlisting = dir('data/denoise/mit_saliency/*.jpg');\n\nnum_file = 20;\nfor m = 1 : num_file\n    fprintf('Extracting patch batch: %d / %d\\n', m, num_file);\n    % extract random patches\n    samples = zeros(patch_dim, patch_dim, 3, num_patches);\n    labels = zeros(size(samples));\n    for i = 1 : num_patches\n        if (mod(i,100) == 0)\n            fprintf('Extracting patch: %d / %d\\n', i, num_patches);\n        end\n        \n        r_idx = random('unid', size(listing, 1));\n        orig_img = imread(strcat('data/denoise/mit_saliency/', listing(r_idx).name));\n\n        orig_img_size = size(orig_img);\n        offset = 30;\n        r = random('unid', orig_img_size(1) - patch_dim - 2*offset + 1) + offset;\n        c = random('unid', orig_img_size(2) - patch_dim - 2*offset + 1) + offset;\n        \n        input_patch = im2double(orig_img(r:r+patch_dim-1, c:c+patch_dim-1, :));\n\n        samples(:,:,:,i) = imnoise(input_patch, 'gaussian', 0, 0.01);\n        labels(:,:,:,i) = input_patch;\n    end\n    samples = single(samples);\n    labels = single(labels);\n    % save it\n    filename = strcat('data\\denoise\\train\\patches_', num2str(m));\n    save(filename, '-v7.3', 'samples', 'labels');\nend\n\n\n", "meta": {"author": "jimmy-ren", "repo": "vcnn_double-bladed", "sha": "a4de90e845875f6e30632f2e879d3afb81c0ebc1", "save_path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed", "path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed/vcnn_double-bladed-a4de90e845875f6e30632f2e879d3afb81c0ebc1/applications/image_denoise/gen_data/gen_training_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.558711423204109}}
{"text": "function temp = lpass(E_map)\nn = size(E_map,1);\nt = E_map;\nsn = 33;\n\n\n\n\nvec = linspace(-pi,pi,sn)'*ones(1,sn);\ngaus = exp((-vec.^2- (vec').^2)/2)/sqrt(2*pi);\n\nspan = [fliplr(fliplr(t).') flipud(t) t.';fliplr(t) t fliplr(t);t.' flipud(t) fliplr(fliplr(t).')];\nconvdata = conv2(span,gaus);\nl = (size(convdata,2)-n)/2;\ntemp = convdata((l+1):(end-l) , (l+1):(end-l));\ntemp = temp./sum(sum(temp)).*sum(sum(E_map));", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/fat-water-separate/lpass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5587114184675314}}
{"text": "function G = repmat(f, M, N)\n%REPMAT   Replicate and tile a CHEBFUN.\n%   REPMAT(F, M, N) or REPMAT(F, [M, N]) creates an array-valued CHEBFUN by\n%   tiling copies of F. If F is a column CHEBFUN, then REPMAT(F, 1, N) returns\n%   an array-valued CHEBFUN with N*SIZE(F, 2) CHEBFUN columns. If F is a row\n%   CHEBFUN, REPMAT(F, M, 1) returns an array-valued CHEBFUN with M*size(F, 1).\n%\n% See also HORZCAT, VERTCAT, CAT.\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:\nif ( nargin == 2 )\n    if ( length(M) ~= 2 )\n        error('CHEBFUN:CHEBFUN:repmat:notEnoughInputs', ...\n            'Requires REPMAT(F, M, N) or REPMAT(F, [M, N]).')\n    end\n    N = M(2);  \n    M = M(1);\nend\n\nif ( f(1).isTransposed )\n    % REPMAT a row CHEBFUN:\n    if ( N ~= 1 )\n        error('CHEBFUN:CHEBFUN:repmat:row',...\n            'Use REPMAT(F, M, 1) to replicate and tile row CHEBFUN objects.')\n    else\n        G = repmat({f}, M, 1);\n        G = vertcat(G{:});\n    end\nelse\n    % REPMAT a column CHEBFUN:\n    if ( M ~= 1 )\n        error('CHEBFUN:CHEBFUN:repmat:col',...\n            'Use REPMAT(F, 1, N) to replicate and tile column CHEBFUN objects.')\n    else\n        G = repmat({f}, 1, N);\n        G = horzcat(G{:});\n    end\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/repmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5586676692055271}}
{"text": "function f = comp_ifwt(c,g,a,J,Ls,ext)\n%COMP_IFWT Compute Inverse DWT\n%   Usage:  f = comp_ifwt(c,g,J,a,Ls,ext);\n%\n%   Input parameters:\n%         c     : Cell array of length M = J*(filtNo-1)+1. Each element is Lc(m)*W array\n%         g     : Synthesis wavelet filters - cell-array of length *filtNo*.\n%         J     : Number of filterbank iterations.\n%         a     : Upsampling factors - array of length *filtNo*.\n%         Ls    : Length of the reconstructed signal.\n%         ext   : 'per','zero','odd','even', Type of the forward transform boundary handling.\n%\n%   Output parameters:\n%         f     : Reconstructed data - Ls*W array.\n%\n\n% see comp_fwt for explanantion\nassert(a(1)==a(2),'First two elements of a are not equal. Such wavelet filterbank is not suported.');\n\n\n% Impulse responses to a correct format.\nfiltNo = numel(g);\n%gCell = cellfun(@(gEl) conj(flipud(gEl.h(:))),g,'UniformOutput',0);\ngCell = cellfun(@(gEl) gEl.h(:),g,'UniformOutput',0);\n\nif strcmp(ext,'per')\n   % Initial shift of the filter to compensate for it's delay.\n   % \"Zero\" delay reconstruction is produced.\n   % offset = cellfun(@(gEl) gEl.offset,g); \n   %offset = cellfun(@(gEl) 1-numel(gEl.h)-gEl.offset,g); \n   offset = cellfun(@(gEl) gEl.offset,g);\nelseif strcmp(ext,'valid')\n   offset = -cellfun(@(gEl) numel(gEl.h)-1,g);\nelse\n   % -1 + 1 = 0 is used for better readability and to be consistent\n   % with the shift in comp_fwt.\n   % Here we are cheating, because we are making the filters\n   % anti-causal to compensate for the delay introduced by causal\n   % analysis filters. \n   % Instead, we could have used causal filters here and do the\n   % delay compensation at the end (cropping f).\n   % offset = -cellfun(@(gEl) numel(gEl),gCell) + (a -1) +1;\n   offset = -(a-1);\nend\n\n\nLc = cellfun(@(cEl) size(cEl,1),c);\nLc(end+1) = Ls;\ntempca = c(1);\ncRunPtr = 2;\nfor jj=1:J\n   tempca=comp_ifilterbank_td([tempca;c(cRunPtr:cRunPtr+filtNo-2)],gCell,a,Lc(cRunPtr+filtNo-1),offset,ext); \n   cRunPtr = cRunPtr + filtNo -1;\nend\n% Save reconstructed data.\nf = tempca;\n\n\n\n% for ch=1:chans\n%   tempca = c(LcStart(1):LcEnd(1),ch);\n%   LcRunPtr = filtNo+1;\n%   cRunPtr = 2;\n%   for jj=1:J\n%      tempca = comp_upconv({tempca}, Lc(LcRunPtr),{tmpg{1}},a(1),skip(1),ext,0);\n%      for ff=2:filtNo\n%         % tempca = tempca + comp_upconv({c{cRunPtr}(:,ch)}, Lc(LcRunPtr),{tmpg},a(ff),skip,doNoExt,0);\n%         tempca = tempca + comp_upconv({c(LcStart(cRunPtr):LcEnd(cRunPtr),ch)}, Lc(LcRunPtr),{tmpg{ff}},a(ff),skip(ff),ext,0);\n%         cRunPtr = cRunPtr + 1;\n%      end\n%      LcRunPtr = LcRunPtr + filtNo -1;\n%   end\n%   f(:,ch) = tempca;\n% end\n\n\n    \n    \n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_ifwt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5586676651705548}}
{"text": "function [ icc, ccc ] = st_to_cc_index ( nst, ist, jst, ncc, n )\n\n%*****************************************************************************80\n%\n%% ST_TO_CC_INDEX creates CC indices from ST data.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    14 July 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer NST, the number of ST elements.\n%\n%    Input, integer IST(NST), JST(NST), the ST rows and columns.\n%\n%    Input, integer NCC, the number of CC elements.\n%\n%    Input, integer N, the number of columns.\n%\n%    Output, integer ICC(NCC), the CC rows.\n%\n%    Output, integer CCC(N+1), the compressed CC columns.\n%\n\n%\n%  Sort the elements.\n%\n  [ jst2, ist2 ] = i4vec2_sort_a ( nst, jst, ist );\n%\n%  Get the unique elements.\n%\n  [ jcc, icc ] = i4vec2_sorted_uniquely ( nst, jst2, ist2, ncc );\n%\n%  Compress the column index.\n%\n  ccc = zeros(n+1,1);\n\n  ccc(1) = 1;\n  jlo = 1;\n  for i = 1 : ncc\n    jhi = jcc(i);\n    if ( jhi ~= jlo )\n      ccc(jlo+1:jhi) = i;\n      jlo = jhi;\n    end\n  end\n  jhi = n + 1;\n  ccc(jlo+1:jhi) = ncc + 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/st_to_cc/st_to_cc_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.5586676536867211}}
{"text": "function dz = dynamics(z,u,param)\n% dz = dynamics(z,u,param)\n%\n% Computes the first-order form of the dynamics for the combined chain\n% integrator and pendulum system\n%\n% INPUTS:\n%   z = [x;v1;v2];\n%   u = [u1;u2];\n%\n% OUTPUTS:\n%   dz = dz/dt\n%\n\nx = z(1,:);\nv1 = z(2,:);\n% v2 = z(3,:);   %Unused\nu1 = u(1,:);\nu2 = u(2,:);\n\n% Pendulum physics\ndv1 = pendulum(x,v1,u1,param);\n\n% Integrator chain physics:\ndx = v1;\ndv2 = u2;\n\n% Combine:\ndz = [dx;dv1;dv2];\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/minimumSnap/minAccel/dynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788903594355, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5586676462378595}}
{"text": "function [M0, T1] = mtv_compute_m0_t1(data, flipAngles, TR, b1Map, roi, fixT1, verbose)\n\n% function function [M0 T1] = mtv_compute_m0_t1 (data, flipAngles, TR [, b1Map, roi, fixT1, verbose])\n% -----------------------------------------------------------\n% This function performs a weighted-least squares data fit\n% on SPGR T1-weighted data set\n% INPUTS:\n% data: width x length x slices x flipAngles matrix\n% flipAngles: a vector of flip angles (in degrees) that corresponds to\n% data(:,:,:,4)\n% TR: in s\n% b1Map: a width x length x slices matrix that contains the relative flip\n% angle (i.e. if nominal alpha is 60, and measured alpha is 61, then b1Map\n% = 61/60\n% roi: binary mask (Matrix)\n% fixT1: scalar or Matrix. If 0 --> do not fix T1.\n% verbose: logical\n%\n\nif ndims(data)<3, data = permute(data(:),[2 3 4 1]); end\ndataSize = size(data);\nif (nargin < 4) || isempty(b1Map)\n    b1Map = ones([dataSize(1:end-1) 1]);\nend\n\nif nargin<5 || isempty(roi)\n    roi = ones(dataSize(1:end-1));\nend\n\nif nargin<6\n    fixT1 = 0;\nend\n\nif nargin<7\n    verbose = 0;\nend\n\nif max(size(b1Map) ~= dataSize(1:length(size(b1Map)))), error('B1 size is different from data size'); end\n\ndims = size(data);\nT1 = zeros(dims(1:end-1));\nM0 = zeros(dims(1:end-1));\n\nwarning('off');\n%sprintf('%s\\n\\n\\n','loop over voxels...')\nfor vox=1:dims(1)*dims(2)*dims(3)\n    %disp([sprintf('\\b\\b\\b\\b\\b%3i',floor(vox/(dims(1)*dims(2)*dims(3))*100)) '%'])\n    if roi(vox) && b1Map(vox)~=0\n\n    kk=floor((vox-1)/(dims(1)*dims(2))); jj=floor((vox-kk*dims(1)*dims(2)-1)/(dims(1))); ii=vox-kk*dims(1)*dims(2)-jj*dims(1);\n    kk=kk+1; jj=jj+1;\n    %ii\n        if ~fixT1\n            %% T1 Mapping Using Variable Flip Angle SPGR Data With\n            % Flip Angle Correction - Liberman, et al.\n            y = squeeze(squeeze(data(ii,jj,kk, :)))./sin(flipAngles/180*pi*b1Map(vox))';\n            x = squeeze(squeeze(data(ii,jj,kk, :)))./tan(flipAngles/180*pi*b1Map(vox))';\n            \n            % fit data\n            param = polyfit(x,y,1);\n%             fitresult = LinearFit(x, y, verbose);\n%             param = coeffvalues(fitresult); % slope and intercept of the fitting\n            param(isnan(param))=0;\n            \n%             ci = confint(fitresult,0.682); % confidence interval of the fitting (returns the slope and intercept of the lines framing the fit) -- corresponding to 2*sigma\n%             ci(isnan(ci)) = 0;\n%            \n            % compute PD and T1\n            [~,T1(vox)]=getT1(param,TR);\n        else\n            %% if T1 is known\n            T1(vox)=fixT1(min(vox,end));\n        end\n        %% Get M0\n        [FA,iFA]=min(flipAngles);\n        \n        M0(vox)=getM0fromT1(T1(vox),TR(1),data(ii,jj,kk,iFA),FA*b1Map(vox));\n        % add length of the confidence interval at 68.2% in the fourth\n        % dimension\n        \n        if ~fixT1\n%             [~,t1_min]=getT1(ci(1,:),TR);\n%             [~,t1_max]=getT1(ci(2,:),TR);\n%             M02(vox)=abs(getM0fromT1(t1_max,TR,data(ii,jj,kk,ialpha),alpha)-getM0fromT1(t1_min,TR,data(ii,jj,kk,ialpha),alpha));\n%             T12(vox)=abs(t1_max-t1_min);\n        end\n        \n    end\nend\nif ~fixT1\n%    T1(:,:,:,2)=T12;\n%     M0(:,:,:,2)=M02;\nend\n%display('...done')\n\n\nfunction [fitresult, gof] = LinearFit(x, y, verbose)\n%CREATEFIT(X,Y)\n%  Create a fit.\n%\n%  Data for 'untitled fit 1' fit:\n%      X Input : x\n%      Y Output: y\n%  Output:\n%      fitresult : a fit object representing the fit.\n%      gof : structure with goodness-of fit info.\n%\n%  See also FIT, CFIT, SFIT.\n\n%  Auto-generated by MATLAB on 22-Jan-2015 15:51:35\n\n\n% Fit: 'untitled fit 1'.\n[xData, yData] = prepareCurveData( x, y );\n\n% Set up fittype and options.\nft = fittype( 'poly1' );\n\n% Fit model to data.\n[fitresult, gof] = fit( xData, yData, ft );\n\n% Plot fit with data.\nif verbose && max(xData~=0) && max(yData~=0)\n    \n    figure(100)\n    h = plot( fitresult, xData, yData,'+');\n    set(h,'MarkerSize',30)\n    legend( h, 'y vs. x', 'untitled fit 1', 'Location', 'NorthEast' );\n    p11 = predint(fitresult,x,0.95,'observation','off');\n    hold on\n    plot(x,p11,'m--'); drawnow;\n    hold off\n    % Label axes\n    xlabel( 'x' );\n    ylabel( 'y' );\n    grid on\n    saveas(gcf,['temp.jpg']);\nend\n\n\nfunction [M0,T1]=getT1(param,TR)\na=param(1); % slope\nb=param(2); % intercept\nif a>0\n    T1 = -TR/log(a);\nelse  % due to noise or bad fitting\n    T1 = 0.000000000000001;\nend\nM0 = b/(1-exp(-TR/T1));\n\n\nfunction M0=getM0fromT1(T1,TR,S,FA)\n% Volz, S., N\ufffdth, U., Deichmann, R., 2012. Correction of systematic errors in quantitative proton density mapping. Magn. Reson. Med. 68, 74?85.\n% Steady state\nST=(1-exp(-TR./T1))./(1-cos(FA*pi/180).*exp(-TR./T1)).*sin(FA*pi/180);\n% M0=RP*PD (RP=Receiver Profile)\nM0=S/ST;\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/MTVfun/mtv_compute_m0_t1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5586625718201782}}
{"text": "function cnnnumgradcheck(net, x, y)\n    epsilon = 1e-4;\n    er      = 1e-8;\n    n = numel(net.layers);\n    for j = 1 : numel(net.ffb)\n        net_m = net; net_p = net;\n        net_p.ffb(j) = net_m.ffb(j) + epsilon;\n        net_m.ffb(j) = net_m.ffb(j) - epsilon;\n        net_m = cnnff(net_m, x); net_m = cnnbp(net_m, y);\n        net_p = cnnff(net_p, x); net_p = cnnbp(net_p, y);\n        d = (net_p.L - net_m.L) / (2 * epsilon);\n        e = abs(d - net.dffb(j));\n        if e > er\n            error('numerical gradient checking failed');\n        end\n    end\n\n    for i = 1 : size(net.ffW, 1)\n        for u = 1 : size(net.ffW, 2)\n            net_m = net; net_p = net;\n            net_p.ffW(i, u) = net_m.ffW(i, u) + epsilon;\n            net_m.ffW(i, u) = net_m.ffW(i, u) - epsilon;\n            net_m = cnnff(net_m, x); net_m = cnnbp(net_m, y);\n            net_p = cnnff(net_p, x); net_p = cnnbp(net_p, y);\n            d = (net_p.L - net_m.L) / (2 * epsilon);\n            e = abs(d - net.dffW(i, u));\n            if e > er\n                error('numerical gradient checking failed');\n            end\n        end\n    end\n\n    for l = n : -1 : 2\n        if strcmp(net.layers{l}.type, 'c')\n            for j = 1 : numel(net.layers{l}.a)\n                net_m = net; net_p = net;\n                net_p.layers{l}.b{j} = net_m.layers{l}.b{j} + epsilon;\n                net_m.layers{l}.b{j} = net_m.layers{l}.b{j} - epsilon;\n                net_m = cnnff(net_m, x); net_m = cnnbp(net_m, y);\n                net_p = cnnff(net_p, x); net_p = cnnbp(net_p, y);\n                d = (net_p.L - net_m.L) / (2 * epsilon);\n                e = abs(d - net.layers{l}.db{j});\n                if e > er\n                    error('numerical gradient checking failed');\n                end\n                for i = 1 : numel(net.layers{l - 1}.a)\n                    for u = 1 : size(net.layers{l}.k{i}{j}, 1)\n                        for v = 1 : size(net.layers{l}.k{i}{j}, 2)\n                            net_m = net; net_p = net;\n                            net_p.layers{l}.k{i}{j}(u, v) = net_p.layers{l}.k{i}{j}(u, v) + epsilon;\n                            net_m.layers{l}.k{i}{j}(u, v) = net_m.layers{l}.k{i}{j}(u, v) - epsilon;\n                            net_m = cnnff(net_m, x); net_m = cnnbp(net_m, y);\n                            net_p = cnnff(net_p, x); net_p = cnnbp(net_p, y);\n                            d = (net_p.L - net_m.L) / (2 * epsilon);\n                            e = abs(d - net.layers{l}.dk{i}{j}(u, v));\n                            if e > er\n                                error('numerical gradient checking failed');\n                            end\n                        end\n                    end\n                end\n            end\n        elseif strcmp(net.layers{l}.type, 's')\n%            for j = 1 : numel(net.layers{l}.a)\n%                net_m = net; net_p = net;\n%                net_p.layers{l}.b{j} = net_m.layers{l}.b{j} + epsilon;\n%                net_m.layers{l}.b{j} = net_m.layers{l}.b{j} - epsilon;\n%                net_m = cnnff(net_m, x); net_m = cnnbp(net_m, y);\n%                net_p = cnnff(net_p, x); net_p = cnnbp(net_p, y);\n%                d = (net_p.L - net_m.L) / (2 * epsilon);\n%                e = abs(d - net.layers{l}.db{j});\n%                if e > er\n%                    error('numerical gradient checking failed');\n%                end\n%            end\n        end\n    end\n%    keyboard\nend\n", "meta": {"author": "rasmusbergpalm", "repo": "DeepLearnToolbox", "sha": "5df2801f2196a2afddb7a87f800e63e153c34995", "save_path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox", "path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox/DeepLearnToolbox-5df2801f2196a2afddb7a87f800e63e153c34995/CNN/cnnnumgradcheck.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5586625660498749}}
{"text": "function model = lleCreate(inputDim, outputDim, Y, options)\n\n% LLECREATE Locally linear embedding model.\n% FORMAT\n% DESC creates a structure for a locally linear embedding.\n% ARG latentDimension : dimension of latent space.\n% ARG outputDim : dimension of data.\n% ARG Y : the data to be modelled in design matrix format (as many\n% rows as there are data points).\n% ARG options : options structure as returned by lleOptions.\n% RETURN model : model structure containing LLE model.\n% \n% COPYRIGHT : Neil D. Lawrence, 2008, 2009\n%\n% SEEALSO : lleOptions, modelCreate\n\n\n% MLTOOLS\n\nmodel.type = 'lle';\n\nif size(Y, 2) ~= outputDim\n  error(['Input matrix Y does not have dimension ' num2str(d)]);\nend\nmodel.isNormalised = options.isNormalised;\nmodel.regulariser = options.regulariser;\nmodel.acyclic = options.acyclic;\nmodel.k = options.numNeighbours;\nmodel.Y = Y;\nmodel.d = outputDim;\nmodel.q = inputDim;\nmodel.N = size(Y, 1);\n\nif isfield(model, 'acyclic') && model.acyclic\n  model.indices = findAcyclicNeighbours(model.Y, model.k);\nelse\n  model.indices = findNeighbours(model.Y, model.k);\nend\nmodel.W = spalloc(model.N, model.N, model.N*model.k);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/lleCreate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.558662565305944}}
{"text": "% phd_test.m\n% ====================================================>\n% This is a test script which demonstrates the usage of the \"SMC_PHD\" class.\n% \n% SETUP:\n%  * Before running the simulation, open \"2_crossing_targets.mat\" or \"3_roaming_targets.mat\" datasets, from the \"datasets\" folder\n%  * The datasets have been extracted by simulating the motion of differential robots in a 2D-plane (x,y)\n%  * The \"gen_obs_cluttered_multi3\" function takes as an input the ground truth data, including information about the measurement noise and clutter rate\n%     and then produces 1xNk cell array of corrupted and cluttered measurements, Nk being the total number of timesteps\n\n% Load the ground truth data\nload('multiple-robot-tracking.mat');\n\n% Plot settings\nShowPlots = 1;              % Set to 0 to hide plots\nShowPrediction = 0;         % Set to 0 to skip showing prediction\nShowUpdate = 1;             % Set to 0 to skip showing update\n\nlambdaV = 0; % Expected number of clutter measurements over entire surveillance region\nV = 10^2;     % Volume of surveillance region (10x10 2D-grid)\nV_bounds = [0 10 0 10]; % [x_min x_max y_min y_max]\nP_D = 1; \n\n% Instantiate a Transitionamic model\ntransition_model = ConstantVelocityX('NumDims',2,'VelocityErrVariance',0.0001);\n\n% Instantiate a Measurement model\nmeasurement_model = LinearGaussianX('NumMeasDims',2,'NumStateDims',4,'MeasurementErrVariance',0.02,'Mapping',[1 3]);\n%measurement_model = RangeBearing2CartesianX('NumStateDims',4,'MeasurementErrVariance',[0.001,0.02],'Mapping',[1 3]);\n\n% Instantiate a clutter model\nclutter_model = PoissonRateUniformPositionX('ClutterRate',lambdaV,'Limits',[V_bounds(1:2);V_bounds(3:4)]);\n\n% Instantiate birth model\nbirth_model = DistributionBasedBirthModelX('Distribution', UniformDistributionX([V_bounds(1:2); ...\n                                                                                [-0.1 0.1 ];...\n                                                                                V_bounds(3:4);...\n                                                                                [-0.1 0.1 ]]),...\n                                           'BirthIntensity', 0.0001);\n\n% Instantiate detection model                                       \ndetection_model = ConstantDetectionProbabilityX('DetectionProbability',P_D);\n                                       \n% Compile the State-Space model\nmodel = StateSpaceModelX(transition_model,...\n                       measurement_model,...\n                       'Clutter',clutter_model,...\n                       'Birth', birth_model,...\n                       'Detection', detection_model);\n\n% Extract the ground truth data from the example workspace\nNumIter = size(GroundTruth,2);\n\n% Set BirthIntensity\nNumTracks = 3;\n\n% Generate DataList\nmeas_simulator = MultiTargetMeasurementSimulatorX('Model',model);\nDataList = meas_simulator.simulate(GroundTruthStateSequence);\n\n% Assign PHD parameter values\nconfig.Model = model;\n[priorParticles, priorWeights] = model.Birth.random(50000);\nconfig.StatePrior = ParticleStateX(priorParticles,10*priorWeights);\nconfig.BirthScheme = {'Expansion', 5000};\nconfig.SurvivalProbability = 0.99;\n\n% Instantiate PHD filter\nmyphd = SMC_PHDFilterX(config);\n\n% Create figure windows\nif(ShowPlots)\n    img = imread('maze.png');\n    \n    % set the range of the axes\n    % The image will be stretched to this.\n    min_x = 0;\n    max_x = 10;\n    min_y = 0;\n    max_y = 10;\n\n    % make data to plot - just a line.\n    x = min_x:max_x;\n    y = (6/8)*x;\n\n    figure('units','normalized','outerposition',[0 0 .5 1])\n    ax(1) = gca;\n    figure('units','normalized','outerposition',[.5 0 .5 1])\n    ax(2) = gca;\nend\n\n% START OF SIMULATION\n% ===================>\nfor k=1:NumIter\n    fprintf('Iteration = %d/%d\\n================>\\n',k,NumIter);\n    \n    % Extract DataList at time k\n    tempDataList = DataList(k);     \n    \n    % Change PHD filter parameters\n    myphd.MeasurementList = tempDataList; % New observations\n    \n    % Predict PHD filter\n    myphd.predict();\n        \n    % Update PHD filter\n    myphd.update();\n    \n    fprintf(\"Estimated number of targets: %f\\n\", sum(myphd.StatePosterior.Weights));\n    % Plot update step results\n    if(ShowPlots && ShowUpdate)\n        % Plot data\n        cla(ax(1));\n         % Flip the image upside down before showing it\n        imagesc(ax(1),[min_x max_x], [min_y max_y], flipud(img));\n\n        % NOTE: if your image is RGB, you should use flipdim(img, 1) instead of flipud.\n        hold on;\n        h2 = plot(ax(1), DataList(k).Vectors(1,:),DataList(k).Vectors(2,:),'k*','MarkerSize', 10);\n        for j=1:NumTracks\n            states = [GroundTruthTracks(j).Trajectory.Vector];\n            h2 = plot(ax(1), states(1,1:k), states(3,1:k),'b.-','LineWidth',1);\n            h2 = plot(ax(1), states(1,k), states(3,k),'bo','MarkerSize', 10);\n        end\n        p_i = myphd.IntensityPerHypothesis(2:end);\n\n        ValidHypothesisInds = find(p_i>0.8)+1;\n        for j = 1:length(ValidHypothesisInds)\n            hypInd = ValidHypothesisInds(j);\n            dist = ParticleDistributionX(myphd.StatePrediction.Particles,myphd.weightsPerHypothesis_(hypInd,:));\n            dist.resample(1000);\n            plot(ax(1), dist.Particles(1,:), dist.Particles(3,:), '.');\n            text(ax(1), dist.Mean(1,:), dist.Mean(3,:), num2str(p_i(hypInd-1)),'FontSize',20,'Color','k');\n        end\n        \n        % set the y-axis back to normal.\n        set(ax(1),'ydir','normal');\n        str = sprintf('Robot positions (Update)');\n        title(ax(1),str)\n        xlabel('X position (m)')\n        ylabel('Y position (m)')\n        axis(ax(1),V_bounds)\n            \n        % Plot PHD\n        cla(ax(2), 'reset');\n        [bandwidth,density,X,Y]=kde2d(myphd.StatePosterior.Particles([1,3],:)');\n        %contour3(X,Y,density,50);\n        h = surf(ax(2),X,Y,density);        \n        shading interp\n        colormap(ax(2), jet(3000))\n        %set(h, 'edgecolor','none')\n        hold on;\n%         plot(ax(2), myphd.Particles(1,:), myphd.Particles(3,:), '.')\n%         hold on;\n        plot(ax(2), myphd.MeasurementList.Vectors(1,:), myphd.MeasurementList.Vectors(2,:), 'y*');\n        axis(ax(2), [V_bounds]);\n        str = sprintf('PHD intensity (Update)');\n        xlabel(ax(2),'X position (m)')\n        ylabel(ax(2),'Y position (m)')\n        zlabel(ax(2),'Intensity')\n        title(ax(2),str)\n        pause(0.01)\n    end\nend", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Filters/PHD/SMC_PHDFilterX/Example/example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5586625602795713}}
{"text": "% MPC applied to HIV system using a SINDYc model.\n% Function for TESTING\n\nclear all, close all, clc\nfigpath = '../FIGURES/HIV/'; mkdir(figpath)\ndatapath = '../DATA/HIV/'; mkdir(datapath)\naddpath('../utils');\n\nSystemModel = 'HIV';\nModelName = 'SINDYc';\n\n%% Load Model\nNvar = 5;\nInputSignalTypeModel = 'prbs'; % prbs; chirp; noise; sine2; sphs; mixed\nload(fullfile(datapath,['EX_',SystemModel,'_SI_SINDYc','_',InputSignalTypeModel,'.mat'])) \n\n%% TRUE SYSTEM PARAMETERS\nrun_HIV_params\nyout = poolDataLIST({'x1','x2','x3','x4','x5','u'},Models.SINDYc.Xi,6,3,0);\n\n% ZURAKOWSKI\nxi_truth.term{1} = {'1', 'x1', 'x1x2', 'x1x2u'};\nxi_truth.coeff{1} = [lambda1, -d, -alpha1, eta*alpha1];\nxi_truth.term{2} = {'x2', 'x1x2', 'x2x4', 'x2x5', 'x1x2u'};\nxi_truth.coeff{2} = [-a, alpha1, -p1, -p2, -eta*alpha1];\nxi_truth.term{3} = {'x3', 'x2x3', 'x1x2x3'};\nxi_truth.coeff{3} = [-b2, -c2*q, c2];\nxi_truth.term{4} = {'x4', 'x2x4'};\nxi_truth.coeff{4} = [-b1, c1];\nxi_truth.term{5} = {'x5', 'x2x3'};\nxi_truth.coeff{5} = [-h, c2*q];\n\n\n% Construct true Xi\nXi0 = zeros(size(Models.SINDYc.Xi));\nfor i = 1:Nvar\n    for j = 1:length(xi_truth.term{i})\n        idx = find(strcmp(yout,xi_truth.term{i}(j)));\n        Xi0(idx,i) = xi_truth.coeff{i}(j);\n    end\nend\n\n\n%% Apply Model predictive control to system using SINDYc model\nselect_model = 'SINDYc';\npest.ahat = Model.Xi(:,1:Nvar); % Use Xi0(:,1:Nvar) to execute true model parameters\npest.polyorder = Model.polyorder;\npest.usesine = Model.usesine;\npest.dt = 1/12; %Model.dt; % Don't need to use the same time step model was trained on\n\n\n% Parameters MPC\noptions = optimoptions('fmincon','Algorithm','sqp','Display','none', ...\n    'MaxIterations',100);\nNweeks = 50;\nDuration = Nweeks*7;             % Run for 'Duration' time units\nTon = 0;                         % Time units when control is turned on   \nx0n = [10, 0.1, 0.1, 0.1, 0.1]'; % Initial condition\nTs  = pest.dt;                   % Sampling time [1/hr]\nTcontrol = 0;\ngetMPCparams    \n\n% Reference state, which shall be achieved\nxref = zeros(1,5);\nxref(2) = ((c2*(lambda1-d*q)-b2*alpha1) - sqrt((c2*(lambda1-d*q)-b2*alpha1)^2 - 4*alpha1*c2*q*d*b2))/(2*alpha1*c2*q);\nxref(1) = lambda1/(d+alpha1*xref(2));\nxref(4) = 0;\nxref(5) = (xref(2)*c2*(alpha1*q-a) + b2*alpha1)/(c2*p2*xref(2));\nxref(3) = h*xref(5)/(c2*q*xref(2));\n\n\n% Initialize variables\nNt = (Duration/Ts)+1;\nuopt0    = 0;\nxhat     = x0n;\nuopt     = uopt0.*ones(Nu,1);\nxHistory = zeros(Nvar,Nt); xHistory(:,1) = xhat;\nuHistory = zeros(1,Nt); uHistory(1)   = uopt(1);\ntHistory = zeros(1,Nt); tHistory(1)   = Tcontrol;\nrHistory = zeros(Nvar,Nt);\n\n%%\n% Start simulation\nfprintf('Simulation started.  It might take a while...\\n')\ntic\nfor ct = 1:(Duration/Ts)   % For each iteration: take measurements & optimize control input & apply control input\n    \n    if mod(ct*Ts,7) == 0 % Update once a week\n        % NMPC with full-state feedback\n        COSTFUN = @(u) ObjectiveFCN_models(u,xhat,N,Nu,xref,uHistory(:,ct),pest,diag(Q),R,Ru,select_model);\n        CONSFUN = @(u) ConstraintFCN_models(u,uHistory(:,ct),xhat,N,LBo,UBo,LBdu,UBdu,pest,select_model);\n        uopt = fmincon(COSTFUN,uopt,[],[],[],[],LB,UB,CONSFUN,options);\n    end\n    \n    % Integrate system\n    xhat = rk4u(@HIVsys_ZURAKOWSKI,xhat,uopt(1),Ts/2,2,[],0); \n    xHistory(:,ct+1) = xhat;\n    uHistory(:,ct+1) = uopt(1);\n    tHistory(:,ct+1) = ct*Ts+Tcontrol; \n    rHistory(:,ct+1) = xref;\n    \n    if mod(ct,1000) == 0\n        disp(['PROGRESS: ',num2str(100*ct/(Duration/Ts)),'%'])\n    end\n    \n    \nend\nfprintf('Simulation finished!\\n')\ntoc\n\n%%\nclear ph\nfigure;box on,hold on\nccolors = get(gca,'colororder');\nplot(tHistory(1:ct)/7,xref(1)*ones(length(tHistory(1:ct)),1)./max(xHistory(1,1:ct)),'--','Color',ccolors(1,:),'LineWidth',1), hold on\nplot(tHistory(1:ct)/7,xref(2)*ones(length(tHistory(1:ct)),1)./max(xHistory(2,1:ct)),'--','Color',ccolors(2,:),'LineWidth',1)\nplot(tHistory(1:ct)/7,xref(3)*ones(length(tHistory(1:ct)),1)./max(xHistory(3,1:ct)),'--','Color',ccolors(3,:),'LineWidth',1)\nph(1) = plot(tHistory(1:ct)/7,xHistory(1,1:ct)./max(xHistory(1,1:ct)),'-','Color',ccolors(1,:),'LineWidth',1.5);\nph(2) = plot(tHistory(1:ct)/7,xHistory(2,1:ct)./max(xHistory(2,1:ct)),'-','Color',ccolors(2,:),'LineWidth',1.5);\nph(3) = plot(tHistory(1:ct)/7,xHistory(3,1:ct)./max(xHistory(3,1:ct)),'-','Color',ccolors(3,:),'LineWidth',1.5);\nph(4) = plot(tHistory(1:ct)/7,uHistory(1:ct),'-k','LineWidth',1.5);\nylim([0 1])\nlegend(ph,'x1','x2','x3','u')\n%% Show results\nclear ph\n\nfigure;hold on, box on,\nccolors = get(gca,'colororder');\nplot(tHistory,xref1(1)*ones(length(tHistory),1),'--','Color',ccolors(1,:),'LineWidth',1)\nplot(tHistory,xref1(2)*ones(length(tHistory),1),'--','Color',ccolors(2,:),'LineWidth',1)\nplot(tHistory,xref1(3)*ones(length(tHistory),1),'--','Color',ccolors(3,:),'LineWidth',1)\nph(1) = plot(tHistory,xHistory(1,:),'-','Color',ccolors(1,:),'LineWidth',1.5);\nph(2) = plot(tHistory,xHistory(2,:),'-','Color',ccolors(2,:),'LineWidth',1.5);\nph(3) = plot(tHistory,xHistory(3,:),'-','Color',ccolors(3,:),'LineWidth',1.5);\nph(4) = plot(tHistory,uHistory,'-k','LineWidth',1.5);\nxlabel('Time')\nylabel('xi')\nlegend(ph,'x1','x2','x3','Control')\naxis tight\nset(gca,'xtick',[50,100,150,200])\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto')\n\n%% Save Results\nResults.t = tHistory;\nResults.x = xHistory;\nResults.u = uHistory;\nResults.J = evalObjectiveFCN(uHistory,xHistory,rHistory,diag(Q),R,Ru);\n\n", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/EX_HIV_THERAPY/MPC_HIV_SINDYc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5586625573944193}}
{"text": "function [cm] = in2cm(in)\n% Convert length from inches to centimeters. \n% Chad A. Greene\ncm = in*2.54;", "meta": {"author": "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/in2cm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5586583105678423}}
{"text": "\n%ReLU function\n\nx = -10:0.01:10;\ny = x;\ny(x<0) = 0;\nplot(x,y);\nxlabel('x');\nylabel('y');\ngrid on\n\n", "meta": {"author": "TheAlgorithms", "repo": "MATLAB-Octave", "sha": "e150b77ad256de46c1ce3815c3d7945ac4fc28dc", "save_path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave", "path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave/MATLAB-Octave-e150b77ad256de46c1ce3815c3d7945ac4fc28dc/algorithms/machine_learning/Activation Functions/ReLU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.55865829866161}}
{"text": "function transmat = ex_transmat(nt)\n%EX_TRANSMAT  Example transition probability matrix definition.\n\n%   MOST\n%   Copyright (c) 2015-2016, Power Systems Engineering Research Center (PSERC)\n%   by Ray Zimmerman, PSERC Cornell\n%\n%   This file is part of MOST.\n%   Covered by the 3-clause BSD License (see LICENSE file for details).\n%   See https://github.com/MATPOWER/most for more info.\n\ntransmat = cell(1, nt);\nT = [ 0.158655253931457; 0.682689492137086; 0.158655253931457 ];\n[transmat{:}] = deal(T * ones(1,3));\ntransmat{1} = T;\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/most/lib/t/ex_transmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.55865829866161}}
{"text": "function [ n_data, j1, j2, j3, j4, j5, j6, j7, j8, j9, fx ] = nine_j_values ...\n  ( n_data )\n\n%*****************************************************************************80\n%\n%% NINE_J_VALUES returns some values of the Wigner 9J function.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    09 February 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%  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 J1, J2, J3, J4, J5, J6, J7, J8, J9,\n%    the arguments of the function.\n%\n%    Output, real FX, the value of the function.\n%\n  n_max = 9;\n\n  fx_vec = [ ...\n     0.0004270039294528318, ...\n    -0.001228915451058514, ...\n    -0.0001944260688400887, ...\n     0.003338419923885592, ...\n    -0.0007958936865080434, ...\n    -0.004338208690251972, ...\n     0.05379143536399187, ...\n     0.006211299937499411, ...\n     0.03042903097250921 ];\n  j1_vec = [ ...\n    1.0, ...\n    1.5, ...\n    2.0, ...\n    1.0, ...\n    1.5, ...\n    2.0, ...\n    0.5, ...\n    1.0, ...\n    1.5  ];\n  j2_vec = [ ...\n    8.0, ...\n    8.0, ...\n    8.0, ...\n    3.0, ...\n    3.0, ...\n    3.0, ...\n    0.5, ...\n    0.5, ...\n    0.5  ];\n  j3_vec = [ ...\n    7.0, ...\n    7.0, ...\n    7.0, ...\n    2.0, ...\n    2.0, ...\n    2.0, ...\n    1.0, ...\n    1.0, ...\n    1.0 ];\n  j4_vec = [ ...\n    6.5, ...\n    6.5, ...\n    6.5, ...\n    4.0, ...\n    4.0, ...\n    4.0, ...\n    2.0, ...\n    2.0, ...\n    2.0 ];\n  j5_vec = [ ...\n    7.5, ...\n    7.5, ...\n    7.5, ...\n    1.5, ...\n    1.5, ...\n    1.5, ...\n    1.0, ...\n    1.0, ...\n    1.0 ];\n  j6_vec = [ ...\n    7.5, ...\n    7.5, ...\n    7.5, ...\n    3.0, ...\n    3.0, ...\n    3.0, ...\n    1.5, ...\n    1.5, ...\n    1.5 ];\n  j7_vec = [ ...\n    6.0, ...\n    6.0, ...\n    6.0, ...\n    3.5, ...\n    3.5, ...\n    3.5, ...\n    1.5, ...\n    1.5, ...\n    1.5 ];\n  j8_vec = [ ...\n    10.0, ...\n    10.0, ...\n    10.0, ...\n     2.0, ...\n     2.0, ...\n     2.0, ...\n     0.5, ...\n     0.5, ...\n     0.5 ];\n  j9_vec = [ ...\n    6.0, ...\n    6.0, ...\n    6.0, ...\n    2.0, ...\n    2.0, ...\n    2.0, ...\n    1.5, ...\n    1.5, ...\n    1.5 ];\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    j1 = 0.0;\n    j2 = 0.0;\n    j3 = 0.0;\n    j4 = 0.0;\n    j5 = 0.0;\n    j6 = 0.0;\n    j7 = 0.0;\n    j8 = 0.0;\n    j9 = 0.0;\n    fx = 0.0;\n  else\n    j1 = j1_vec(n_data);\n    j2 = j2_vec(n_data);\n    j3 = j3_vec(n_data);\n    j4 = j4_vec(n_data);\n    j5 = j5_vec(n_data);\n    j6 = j6_vec(n_data);\n    j7 = j7_vec(n_data);\n    j8 = j8_vec(n_data);\n    j9 = j9_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/nine_j_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5586582986616099}}
{"text": "function b = cppsl ( ap, n, b )\n\n%*****************************************************************************80\n%\n%% CPPSL solves a complex hermitian positive definite linear system.\n%\n%  Discussion:\n%\n%    The matrix is assumed to have been factored by CPPCO or CPPFA.\n%\n%    A division by zero will occur if the input factor contains\n%    a zero on the diagonal.  Technically this indicates\n%    singularity but it is usually caused by improper subroutine\n%    arguments.  It will not occur if the subroutines are called\n%    correctly and INFO == 0.\n%\n%    To compute inverse(A) * C where C is a matrix with P columns:\n%\n%      call cppco(ap,n,rcond,z,info)\n%\n%      if (rcond is too small .or. info /= 0) then\n%        error\n%      end if\n%\n%      do j = 1, p\n%        call cppsl(ap,n,c(1,j))\n%      end do\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 May 2007\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, complex AP(N*(N+1)/2), the output from CPPCO or CPPFA.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Input, complex B(N), the right hand side.\n%\n%    Output, complex B(N), the solution.\n%\n  kk = 0;\n  for k = 1 : n\n    t = conj ( ap(kk+1:kk+k-1) ) * transpose ( b(1:k-1) );\n    kk = kk + k;\n    b(k) = ( b(k) - t ) / ap(kk);\n  end\n\n  for k = n : -1 : 1\n    b(k) = b(k) / ap(kk);\n    kk = kk - k;\n    t = -b(k);\n    b(1:k-1) = b(1:k-1) + t * ap(kk+1:kk+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/linpack_c/cppsl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5586582889723459}}
{"text": "function [nodes, edges] = createTestGraph02(varargin)\n%CREATETESTGRAPH02  Test graph for geodesic functions\n%\n%   [nodes edges] = createTestGraph02;\n%\n%   Example\n%     [nodes edges] = createTestGraph02;\n%     figure;\n%     axis([0 100 10 90]);\n%     axis equal;\n%     drawGraph(nodes, edges);\n%\n%   See also\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-05-19,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\nnodes = [ ...\n   10 40; ...\n   10 60; ...\n   20 50; ...\n   40 50; ...\n   50 20; ...\n   50 40; ...\n   50 60; ...\n   50 80; ...\n   60 50; ...\n   80 50; ...\n   90 40; ...\n   90 60];\n\nedges = [...\n    1  3; ...\n    2  3; ...\n    3  4; ...\n    4  6; ...\n    4  7; ...\n    5  6; ...\n    6  9; ...\n    7  8; ...\n    7  9; ...\n    9 10; ...\n   10 11; ...\n   10 12];", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/tests/graphs/createTestGraph02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.5586143191629961}}
{"text": "for i = 60:63\n\tn = 2^i;\n\tp = [0.4; 0.6];\n\tx = sample_hist(p, n);\n\tassert(sum(x) == n);\n\tassert(max(abs(x/n - p)) < 1e-4);\nend\n", "meta": {"author": "tminka", "repo": "lightspeed", "sha": "e65560c5aa3aae947a62dd662a6444cdfa96fc4f", "save_path": "github-repos/MATLAB/tminka-lightspeed", "path": "github-repos/MATLAB/tminka-lightspeed/lightspeed-e65560c5aa3aae947a62dd662a6444cdfa96fc4f/tests/test_sample_hist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.558614315130756}}
{"text": "function toms179_test02 ( )\n\n%*****************************************************************************80\n%\n%% TOMS179_TEST02 demonstrates the use of MDBETA.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    30 January 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TOMS179_TEST02:\\n' );\n  fprintf ( 1, '  MDBETA estimates the value of the modified Beta function.\\n' );\n  fprintf ( 1, '  Compare with tabulated values.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '      X         P         Q         ' );\n  fprintf ( 1, 'Beta                      Beta                    Diff\\n' );\n  fprintf ( 1, '                                    ' );\n  fprintf ( 1, '(Tabulated)               (MDBETA)\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, p, q, x, fx ] = beta_cdf_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    [ fx2, ifault ] = mdbeta ( x, p, q );\n\n    fprintf ( 1, '  %8.4f  %8.4f  %8.4f  %24.16e  %24.16e  %10.4e\\n', ...\n    p, q, x, fx, fx2, abs ( fx - fx2 ) );\n\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms179/toms179_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.5586143144436526}}
{"text": "function [ hScatterObj ] = ScatterSparse( mS, varargin )\n% ----------------------------------------------------------------------------------------------- %\n% [ hScatterObj ] = ScatterSparse( mS, varargin )\n% Visualize sparsity pattern of matrix. Comparable to `spy()` with all the\n% controls given by `scatter()`.\n% Input:\n%   - mS                -   Input Sparse Matrix.\n%                           Structure: Matrix (numRows x numCols).\n%                           Type: 'Single' / 'Double' (Sprase).\n%                           Range: (-inf, inf).\n%   - varargin          -   Scatter Plot Parameters.\n%                           Set of parameters accepeted by `scatter()`.\n%                           Structure: NA.\n%                           Type: NA.\n%                           Range: NA.\n% Output:\n%   - hScatterObj       -   Scatter Plot Object.\n%                           Structure: Scalar.\n%                           Type: Handler / Object.\n%                           Range: NA.\n% References:\n%   1.  A\n% Remarks:\n%   1.  Supports any functionality by `scatter()` plot.\n% TODO:\n%   1.  \n%   Release Notes:\n%   -   1.0.000     19/07/2021  Royi Avital\n%       *   First release version.\n% ----------------------------------------------------------------------------------------------- %\n\narguments\n    mS (:, :) {mustBeNumeric, mustBeReal, mustBeSparse}\nend\narguments (Repeating)\n    varargin\nend\n\n[vI, vJ, ~] = find(mS);\nhScatterObj = scatter(vJ, vI, varargin{:});\n\n\nend\n\n\nfunction [ ] = mustBeSparse( mS )\n    \nif(~issparse(mS))\n    eid = 'mustBeSparse:mSMustBeSparse';\n    msg = 'The input matrix must be sparse.';\n    throwAsCaller(MException(eid, msg));\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/Q76344/ScatterSparse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.5586143070662752}}
{"text": "%  Script file: timings.m\n%\n%  Purpose: \n%    This program calculates the time required to \n%    calculate the squares of all integers from 1 to\n%    10,000 in four different ways:\n%    1.  Using a for loop with an uninitialized output\n%        array.\n%    2.  Using a for loop with a pre-allocated output\n%        array and NO JIT compiler.\n%    3.  Using a for loop with a pre-allocated output\n%        array and the JIT compiler.\n%    4.  Using vectors.\n%\n%  Record of revisions:\n%      Date       Programmer          Description of change\n%      ====       ==========          =====================\n%    01/29/07    S. J. Chapman        Original code \n%\n% Define variables:\n%   ii, jj       -- Loop index\n%   average1     -- Average time for calculation 1\n%   average2     -- Average time for calculation 2\n%   average3     -- Average time for calculation 3\n%   average4     -- Average time for calculation 4\n%   maxcount     -- Number of times to loop calculation\n%   square       -- Array of squares\n\n% Perform calculation with an uninitialized array \n% \"square\".  This calculation is done only once \n% because it is so slow.\nmaxcount = 1;               % Number of repetitions\ntic;                        % Start timer\nfor jj = 1:maxcount        \n   clear square             % Clear output array\n   for ii = 1:10000       \n     square(ii) = ii^2;     % Calculate square\n   end\nend\naverage1 = (toc)/maxcount;  % Calculate average time \n\n% Perform calculation with a pre-allocated array \n% \"square\", calling an external function to square\n% the number.  This calculation is averaged over 10   \n% loops.\nmaxcount = 10;              % Number of repetitions\ntic;                        % Start timer\nfor jj = 1:maxcount        \n   clear square             % Clear output array\n   square = zeros(1,10000); % Pre-initialize array\n   for ii = 1:10000       \n     square(ii) = sqr(ii);  % Calculate square\n   end\nend\naverage2 = (toc)/maxcount;  % Calculate average time \n\n% Perform calculation with a pre-allocated array \n% \"square\".  This calculation is averaged over 100  \n% loops.\nmaxcount = 100;             % Number of repetitions\ntic;                        % Start timer\nfor jj = 1:maxcount        \n   clear square             % Clear output array\n   square = zeros(1,10000); % Pre-initialize array\n   for ii = 1:10000       \n     square(ii) = ii^2;     % Calculate square\n   end\nend\naverage3 = (toc)/maxcount;  % Calculate average time \n\n% Perform calculation with vectors.  This calculation \n% averaged over 1000 executions. \nmaxcount = 1000;            % Number of repetitions\ntic;                        % Start timer\nfor jj = 1:maxcount        \n   clear square             % Clear output array\n   ii = 1:10000;            % Set up vector\n   square = ii.^2;          % Calculate square\nend\naverage4 = (toc)/maxcount;  % Calculate average time \n\n% Display results\nfprintf('Loop / uninitialized array        = %8.4f\\n', average1);\nfprintf('Loop / initialized array / no JIT = %8.4f\\n', average2);\nfprintf('Loop / initialized array / JIT    = %8.4f\\n', average3);\nfprintf('Vectorized                        = %8.4f\\n', average4);\n", "meta": {"author": "101Hub", "repo": "Matlab101", "sha": "07273f68f1147a110443aeb121fa10962234f298", "save_path": "github-repos/MATLAB/101Hub-Matlab101", "path": "github-repos/MATLAB/101Hub-Matlab101/Matlab101-07273f68f1147a110443aeb121fa10962234f298/assets/\u300aMatlab\u7f16\u7a0b\u300b\u6e90\u7801/chap4/timings.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.5586143023469322}}
{"text": "function W = randInitializeWeights(L_in, L_out)\n    %RANDINITIALIZEWEIGHTS Randomly initialize the weights of a layer with L_in\n    %incoming connections and L_out outgoing connections\n    %   W = RANDINITIALIZEWEIGHTS(L_in, L_out) randomly initializes the weights \n    %   of a layer with L_in incoming connections and L_out outgoing \n    %   connections. \n    %\n    %   Note that W should be set to a matrix of size(L_out, 1 + L_in) as\n    %   the column row of W handles the \"bias\" terms\n    %\n    EPSILON_INIT = 0.12;\n    W = rand(L_out, 1 + L_in) * 2 * EPSILON_INIT - EPSILON_INIT;\nend\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/nn/2-representation/randInitializeWeights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.558614289563108}}
{"text": "function [P,S] = computeSMFromWProjective( W, method, isCalibrated )\n% Compute SfM from measurements for projective camera\n%\n% This function should not be called directly: it does not contain\n% pre-processing steps (removal of calibration matrix if known) or\n% post-procssing steps (affine/metric upgrades) and bundle adjustment\n% computeSMFromW should always be used instead.\n%\n% Essential matrix decomposition\n% Reference: HZ2, p259, Result 9.19, and p. 294\n% nFrame==2 && isCalibrated\n% fast\n%\n% Normalized 8-point algorithm\n% Reference: HZ2, p279 and alg 11.1 p. 282\n% nFrame==2 && ~isCalibrated\n% fast\n%\n% Projective Factorization\n% Reference: HZ2, p445, Algorithm 18.2\n% Sturm and Triggs ECCV 96\n% A Factorization Based Algorithm for Multi-Image Projective Structure and\n% Motion\n% nFrame>2 && method==0\n%\n% Projective Factorization\n% Reference: Iterative Extensions of the Sturm/Triggs Algorithm:\n% Convergence and Nonconvergence, from Oliensis, Hartley, PAMI 07\n% nFrame>2 && method==Inf\n% slower\n%\n% If there are any missing entries:\n% Low-Rank Matrix Fitting Based on Subspace Perturbation Analysis\n% with Applications to Structure from Motion\n% Hongjun Jia, Aleix M. Martinez, PAMI 08\n%\n% Returns the structure and camera parameters in an Animation object\n%\n% USAGE\n%   anim = computeSMFromWProjective( W, method )\n%\n% INPUTS\n%  W            - [ 2 x nPoint x nFrame ] 2D projected features\n%  method       - [inf] method for performing SFM (see above for details)\n%  isCalibrated - flag indicating if the camera is calibrated (only used\n%                 for 2 frames)\n%\n% OUTPUTS\n%  P          - [ 3 x 4 x nFrame ] projection matrices\n%  S          - [ 3 x nPoint ] structure matrix\n%\n% EXAMPLE\n%\n% See also\n%\n% Vincent's Structure From Motion Toolbox      Version 3.1.1\n% Copyright (C) 2008-2011 Vincent Rabaud.  [vrabaud-at-cs.ucsd.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the GPL [see external/gpl.txt]\n\nnFrame = size(W,3); nPoint = size(W,2);\n\nP=zeros(3,4,nFrame); P(:,:,1)=eye(3,4);\n\nWIsnan=isnan(W);\nhasAnyNan=any(WIsnan(:));\n\n% Normalized 8-point algorithm\n% Reference: HZ2, p279 and alg 11.1 p. 282\nif nFrame==2\n  % Normalize input data\n  [x T]=normalizePoint(W(:,:,1),Inf);\n  [xp Tp]=normalizePoint(W(:,:,2),Inf);\n  \n  A=[xp([1 1],:).*x; xp(1,:); xp([2 2],:).*x;xp(2,:);x;ones(1,nPoint)]';\n  \n  [U,S,V]=svd(A,0); F=reshape(V(:,end),[3,3])';\n  [U,S,V]=svd(F,0);\n  F=U*diag([S(1,1) S(2,2) 0])*V';\n  \n  F=[ Tp; 0 0 1 ]'*F*[ T; 0 0 1 ];\n  \n  if ~isCalibrated\n    P(:,:,2) = convertPF([],F,true);\n    S = computeSFromWM( true, W, P, 'method', 0 );\n  else\n    % Essential matrix decomposition\n    % Reference: HZ2, p259, Result 9.19, and p. 294\n    [ U disc V ] = svd(F);\n    if det(U)<0; U=-U; end; if det(V)<0; V=-V; end\n    \n    % Check which of the 4 possibilities gives a point in front of both\n    % cameras\n    WW = [ 0 -1 0; 1 0 0; 0 0 1 ];\n    maxCount=0;\n    for i = 1 : 4\n      switch i\n        case 1,\n          P(:,:,2) = [ U*WW*V' U(:,3) ];\n        case 2,\n          P(:,:,2) = [ U*WW*V' -U(:,3) ];\n        case 3,\n          P(:,:,2) = [ U*WW'*V' U(:,3) ];\n        case 4,\n          P(:,:,2) = [ U*WW'*V' -U(:,3) ];\n      end\n      \n      C = zeros(3,2); v = C;\n      for j = 1 : 2\n        % camera center (Reference: HZ2, p158-161)\n        M = P(:,1:3,j);\n        C(:,j)=-M\\P(:,4,j);\n        % principal axis\n        v(:,j) = det(M)*M(3,:)';\n      end\n      % compute the image of a point\n      STmp = computeSFromWM( true, W, P, 'method', 0);\n      maxCountTmp = sum((v(:,1)'*bsxfun(@minus,STmp,C(:,1)))>0) + ...\n        sum((v(:,2)'*bsxfun(@minus,STmp,C(:,2)))>0);\n      if maxCountTmp>maxCount\n        P2 = P(:,:,2); maxCount = maxCountTmp; S=STmp;\n      end\n    end\n    P(:,:,2) = P2;\n  end\nend\n\n% Projective Factorization\n% Reference: Iterative Extensions of the Sturm/Triggs Algorithm:\n% Convergence and Nonconvergence, from Oliensis, Hartley, PAMI 07\nif nFrame>2 && ismember(method,[ 0 Inf ]) && ~hasAnyNan\n  % Normalize coordinates\n  [ W T ] = normalizePoint(W,-Inf);\n  \n  % Initialize\n  lam = ones( 1, nPoint, nFrame );\n  WSquaredSum = sum(W.^2,1);\n  C0Const = sum(WSquaredSum(:));\n  for n=1:50\n    % Stage 1\n    if method==0\n      for k = 1 : 10\n        % normalize each column and then each row\n        lam=bsxfun(@rdivide, lam, sqrt(sum(lam.^2,2)));\n        lam=bsxfun(@rdivide, lam, sqrt(sum(lam.^2,3)));\n      end\n    end\n    \n    % get the best rank 4 approximation\n    % Wkm1 is for Wk minus 1\n    [Wkm1,Wkm1Hat]=projSturmTriggsWkm1Wkm1Hat(lam,W);\n    WWkm1Hat = sum(W.*Wkm1Hat,1);\n    \n    if method==Inf\n      if n==1\n        mu = norm(Wkm1(:)-Wkm1Hat(:))^2/norm(Wkm1(:))^4*1.1;\n      else\n        C0 = mu*C0Const;\n        C1 = mu*sum(WWkm1Hat(:));\n        C2 = WWkm1Hat.^2./WSquaredSum; C2 = mu*sum(C2(:));\n        C3 = mu*sum(Wkm1Hat(:).^2);\n      end\n    end\n    \n    % Stage 2\n    % get the optimal lambdas\n    lam=WWkm1Hat./WSquaredSum;\n    \n    % Stage 3\n    if method==Inf && n>1\n      a = roots( [ C0, -(C0^2-2*C1), -(2*C0*C3-C2), ...\n        -(4*C1*C3-2*C2*C0), C0*C3^2-2*C2*C3, ...\n        2*C1*C3^2-C2^2, C2*C3^2 ] );\n      a = real(a(abs(imag(a))<1e-10)); a = a(a>=0);\n      \n      if length(a)>1\n        zkm1=C3*C0/C2;\n        if abs(zkm1-1)>eps\n          a = a( sign(zkm1-1)==sign(a/sqrt(C3)-1) );\n        else a = sqrt(C2/C0)+1;\n        end\n      end\n      lam = ( a + lam )*sqrt(a/(a^2*C0+2*a*C1+C2));\n      %        [a,sqrt(a/(a^2*C0+2*a*C1+C2)), mean(lam(:)), std(lam(:))]\n    end\n  end\n  \n  % De-normalize coordinates\n  Wk = bsxfun(@times,lam,W);\n  [ U S V ] = svd( reshape(permute(Wk,[1,3,2]),3*nFrame,nPoint),...\n    'econ' );\n  P = U(:,1:4)*S(1:4,1:4); S = V(:,1:4)';\n  \n  PTmp = P;\n  S = normalizePoint(S,4);\n  P = zeros(3,4,nFrame);\n  for i=1:nFrame; P(:,:,i) = T(:,:,i)\\PTmp(3*i-2:3*i,:); end\nend\n\n% Low-Rank Matrix Fitting Based on Subspace Perturbation Analysis\n% with Applications to Structure from Motion\n% Hongjun Jia, Aleix M. Martinez, PAMI 08\nif nFrame>2 && ismember(method,[ 0 Inf ]) && hasAnyNan\n  % Normalize coordinates\n  [ q TW ] = normalizePoint(W, -Inf);\n  HHat=reshape(permute(q,[1,3,2]),3*nFrame,nPoint);\n  TInv=1./permute(sum(q.*q,1),[3,2,1]);\n  Sk=HHat;\n  for k = 1 : 30\n    % Sk is HHat (homogeneous W) but scaled by lambda, initialized to 1\n    [PStack,S]=lowRankDecomposition(Sk,4);\n    \n    % make sure the columns of PStack are orthonormal\n    [PStack,disc,disc]=svd(PStack,'econ');\n    \n    P = permute(reshape(PStack,3,nFrame,4),[1,3,2]);\n    %sumTot=0;\n    for j=1:nPoint\n      mask=~isnan(TInv(:,j));\n      if all(~mask); continue; end\n      Cj=permute(sum(bsxfun(@times,q(:,j,mask),P(:,:,mask)),1),[3,2,1]);\n      % Solve the maximum of the Rayleigh quotient\n      % it is the highest eigenvector of A*v=lam*(1./TjInv)*v\n      % or heighest eigen value of TjInv*A*v=lam*v\n      A=Cj*Cj';\n      [lamjTmp,val]=eigs(bsxfun(@times,TInv(mask,j),A),1,'lm');\n      lamj=zeros(1,1,nFrame); lamj(mask)=lamjTmp;\n      %sumTot=sumTot+lamjTmp'*Cj*Cj'*lamjTmp/(lamjTmp'*diag(1./ ...\n      % TInv(mask,j))*lamjTmp);\n      Sk(:,j)=reshape(bsxfun(@times,q(:,j,:),lamj),3*nFrame,1);\n    end\n    %sumTot;\n  end\n  [PStack,S]=lowRankDecomposition(Sk,4);\n  \n  PTmp = PStack;\n  S = normalizePoint(S,4);\n  P = zeros(3,4,nFrame);\n  for i=1:nFrame; P(:,:,i) = TW(:,:,i)\\PTmp(3*i-2:3*i,:); end\nend\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [ Wkm1, Wkm1Hat ]=projSturmTriggsWkm1Wkm1Hat(lam,W)\n% perform the computation of Wk and its rank 4 approximation\n% in Storm Triggs\nnFrame=size(W,3); nPoint=size(W,2);\nWkm1 = bsxfun(@times,lam,W);\n[ U S V ] = svd( reshape(permute(Wkm1,[1,3,2]),3*nFrame,nPoint), 'econ' );\nWkm1Hat = permute(reshape(U(:,1:4)*S(1:4,1:4)*V(:,1:4)',3,nFrame,...\n  nPoint),[1,3,2]);\nend\n", "meta": {"author": "vrabaud", "repo": "sfm_toolbox", "sha": "7ce933b31b71292eddabb40bacfd619720fa221d", "save_path": "github-repos/MATLAB/vrabaud-sfm_toolbox", "path": "github-repos/MATLAB/vrabaud-sfm_toolbox/sfm_toolbox-7ce933b31b71292eddabb40bacfd619720fa221d/sfm/private/computeSMFromWProjective.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5585934736292518}}
{"text": "function [fMc, fBvalue, fBStd, fAvalue, fSigmaLow, fSigmaHi] = calc_McduebBst(magnitudes, varargin)\n    % calc_McduebBst  Calculate Mc using the function b-value vs. cut-off-magnitude: Bootstrap approach\n    % [fMc, fBvalue, fBStd, fAvalue, fSigmaLow, fSigmaHi] = calc_McduebBst(mCatalog, fBinning, nWindowSize, nMinNumberEvents, nSample)\n    %-------------------------------------------------------------------------------------------------------\n    % Calculate Mc using the function b-value vs. cut-off-magnitude: Bootstrap approach\n    % Decision criterion for b and Mc: b_i-std_Bst(b_i) <= b_ave <= b_i+std_Bst(b_i)\n    \n    % Relevant reference: Cao A., Gao, S.S., Temporal variation of seismic b-values\n    % beneath northeastern Japan island arc, GRL, 29, 9, 2002\n    %\n    % Incoming variables:\n    % magnitudes         : EQ catalog magnitudes\n    % fBinning         : Bin size\n    % nWindowSize      : Window size\n    % nMinNumberEvents : Minimum number of events\n    % nSample          : Number of bootstrap samples\n    %\n    % Outgoing variables:\n    % fMc              : Magnitude of completeness\n    % fBvalue          : b-value\n    % fBStd            : 2nd moment of b-value-distribution (comparable to standard deviation)\n    % fAvalue          :a-value\n    % fSigmaLow        : 16-percentile of b-value distribution\n    % fSigmaHi         : 84-percentile of b-value distribution\n    % Author: J. Woessner\n    % updated: 04.06.03\n    \n    % Check input\n    p=inputParser;\n    p.addOptional('fBinning',0.1);\n    p.addOptional('nWindowSize',5);\n    p.addOptional('nMinNumberEvents',50);\n    p.addOptional('nSample',100);\n    p.parse(varargin{:});\n    \n    PCTL_RANGE = [16, 84];\n    \n    fBinning            = p.Results.fBinning;\n    nWindowSize         = p.Results.nWindowSize;\n    nMinNumberEvents    = p.Results.nMinNumberEvents;\n    nSample             = p.Results.nSample;\n    \n    \n    % Set fix values\n    fMinMag = min(magnitudes);\n    fMaxMag = max(magnitudes);\n    \n    % Create bootstrap samples using bootstrap matlab toolbox\n    deepdim = 1; % for deepdim = 1:size(magnitudes,2)\n    mMag_bstsamp = bootrsp(magnitudes,nSample);\n    % Calculate b-with magnitude\n    magBins = fMinMag:fBinning:fMaxMag;\n    nBins = numel(magBins);\n    \n    % mBvalue = nan(nBins, 7); % contains [meanb_value, meanb_value_std, meana_value vSigma(1) vSigma(2), fStdBst]\n    mean_b_value     = nan(nBins,1);\n    mean_b_value_std = nan(nBins,1);\n    mean_a_value     = nan(nBins,1);\n    mean_mag         = nan(nBins,1);\n    sigmas           = nan(nSample,2);\n    std_bst          = nan(nBins,1);\n    \n    for i = 1 : nBins\n        fMag = magBins(i);\n        mBvalue_bst = nan(nSample, 4); % resets each pass, contains [b_value, b_value_std, a_value, magvalue]\n        \n        magMask = mMag_bstsamp >= fMag - 0.05;\n        \n        idxs        = (i-1).* nSample + (1:nSample);\n        b_value     = nan(nSample,1);\n        b_value_std = nan(nSample,1);\n        a_value     = nan(nSample,1);\n        \n        mBvalue_bst(idxs,4) = fMag; \n        for nSamp=1:nSample\n            bvalIsNan = magMask(:, nSamp);\n            mCat = mMag_bstsamp(bvalIsNan, nSamp);\n            \n            % Check for minimum number of events\n            \n            if numel(mCat) >= nMinNumberEvents\n                [ b_value(nSamp), b_value_std(nSamp), a_value(nSamp)] =  calc_bmemag(mCat, fBinning);\n            end\n        end\n        mBvalue_bst(idxs, 1:3) = [b_value, b_value_std, a_value];\n        \n        % Check for Nan and create output for [16 84]-percentile\n        bvalIsNan   = isnan(b_value);\n        bval_nonans = b_value(~bvalIsNan);\n        \n        if ~isempty(bval_nonans)\n            vSigma = prctile(bval_nonans, PCTL_RANGE);\n            if length(bval_nonans)==1\n                vSigma = vSigma';\n            end\n            fStdBst = std(bval_nonans, 1, 'omitnan'); % Calculate 2nd moment\n            \n            sigmas(i,:)         = vSigma;\n            std_bst(i)          = fStdBst;\n        end\n        \n        mean_b_std_a_mag    = mean(mBvalue_bst,'omitnan');\n        mean_b_value(i)     = mean_b_std_a_mag(1);\n        mean_b_value_std(i) = mean_b_std_a_mag(2);\n        mean_a_value(i)     = mean_b_std_a_mag(3);\n        mean_mag(i)         = mean_b_std_a_mag(4);\n        \n        % mBvalue(i,:) = [mean(mBvalue_bst,'omitnan'), vSigma(1), vSigma(2), fStdBst]; % contains [meanb_value, meanb_value_std, meana_value, meanmag, vSigma(1), vSigma(2), fStdBst]\n        \n    end % END of FOR fMag\n    \n    % Use bootstrap percentiles to decide for Mc\n    totalSteps = nBins - nWindowSize + 1;\n    \n    b_avg       = movmean(mean_b_value, nWindowSize, 'Endpoints','discard');\n    keeprows    = sigmas(1:totalSteps, 1) <= b_avg & b_avg <= sigmas(1:totalSteps, 2);\n    \n    % b_avg       = b_avg(keeprows); % apply to b_avg before changing it's size\n    \n    keeprows(nBins) = false; % OK, because len(keeprows) (aka. totalsteps) is always less than nBins\n    fMc         = mean_mag(keeprows);\n    fBvalue     = mean_b_value(keeprows);\n    fAvalue     = mean_a_value(keeprows);\n    fBStd       = mean_b_value_std(keeprows);\n    fSigmaLow   = sigmas(keeprows, 1);\n    fSigmaHi    = sigmas(keeprows, 2);\n        \n\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/jochen/seisvar/calc/calc_McduebBst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5585934727680051}}
{"text": "function lo=v_lpcrf2lo(rf)\n%V_LPCRF2LO Convert reflection coefficients to log area ratios LO=(RF)\n%the output values are limited to about +-14.5\n\n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: v_lpcrf2lo.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\nr=max(min(rf,1-1E-6),1E-6-1);\nlo=log((1-r)./(1+r));\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_lpcrf2lo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5585934628036763}}
{"text": "%%\n% Test for power diagrams\n\n%%\n% Test for power diagrams\n\naddpath('power_bounded/');\n\nrep = 'results/power-diagrams/';\n[~,~] = mkdir(rep);\n\n% number of sites\nN = 50;\n% x and y coordinate of the sites\nsigma = .1;\nxy = sigma*randn(N, 2)+1/2;\nxy(1,:) = 1/2; % center points\n\n% the bounding box in clockwise order\nbb = [0,0; 0,1; 1,1; 1,0];\n\nlambda = [1 5 10 100];\nlambda = linspace(1,1.1,5);\n\nfor i=1:length(lambda)% weights\n    w = ones(N,1);w(1) = lambda(i);    \n    % get the power diagram\n    [V,C] = power_bounded(xy(:,1),xy(:,2), w, bb);\n    % draw the resulted power diagram\n    plot_power(xy,V,C,bb);\n    saveas(gcf, [rep 'power-' num2str(i), '.eps'], 'epsc');\n    drawnow;\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/_site/code/semi-discrete/test_power.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5585662046860439}}
{"text": "function dl=lpcaa2dl(aa)\n%LPCAA2DL LPC: Convert area coefficients to dct of log area DL=(AA)\n\n% note: we do not correct for sinc distortion; perhaps we should multiply by\n% k=1:p-1;s=[sqrt(0.5)/p 2*sin(pi*k/(2*p))./(pi*k)];\n\n\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: lpcaa2dl.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[nf,p2]=size(aa);\ndl=rdct(log(aa(:,2:p2-1)./aa(:,p2*ones(1,p2-2))).').';\n\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/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/lpcaa2dl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5585661958324493}}
{"text": "function [ SimilarityMatrix ] = similarityNeighbor( x, n, range)\n%SIMILARITYNEIGHBOR Summary of this function goes here\n%   Detailed explanation goes here\n\n    sz = size(x,1);\n    SimilarityMatrix = eye(sz);\n\n    i = 1:sz-n;\n    SimilarityMatrix(sub2ind([sz, sz], i+n,i)) = 1;\n    SimilarityMatrix(sub2ind([sz, sz], i,i+n)) = 1;\n\n    % invalidate the illegal values from the mask (if at least one element is\n    % not present in the mask set similarity to 0)\n%     if(numel(mask)~=0)\n%         invalidInds = sum(mask(:,range),2) < numel(range);\n% \n%         SimilarityMatrix(invalidInds,:) = 0;\n%         SimilarityMatrix(:,invalidInds) = 0;\n%     end\n    \n    DiagMask = ones(size(x, 1)) - eye(size(x,1));\n    SimilarityMatrix = SimilarityMatrix .* DiagMask;\n    SimilarityMatrix = SimilarityMatrix + eye(size(x, 1));\n    \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/CCRF/lib/similarityNeighbor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.558563326270652}}
{"text": "function x = bernoulli_cdf_inv ( cdf, a )\n\n%*****************************************************************************80\n%\n%% BERNOULLI_CDF_INV inverts the Bernoulli CDF.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 September 2004\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real CDF, the value of the CDF.\n%    0.0D+00 <= CDF <= 1.0.\n%\n%    Input, real A, the parameter of the PDF.\n%    0.0D+00 <= A <= 1.0.\n%\n%    Output, integer X, the corresponding argument.\n%\n  if ( cdf < 0.0 | 1.0 < cdf )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'BERNOULLI_CDF_INV - Fatal error!\\n' );\n    fprintf ( 1, '  CDF < 0 or 1 < CDF.\\n' );\n    error ( 'BERNOULLI_CDF_INV - Fatal error!' );\n  end\n\n  if ( cdf <= 1.0 - a )\n    x = 0;\n  else\n    x = 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/prob/bernoulli_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.5585633178790637}}
{"text": "function bool = iseven(number)\n%ISEVEN true for even integer\n%\n%   Usage: bool = iseven(number)\n%\n%   Input parameters:\n%       number  - number (or vector/matrix with numbers) to be tested\n%\n%   Output parameters:\n%       bool    - true if the number is even, false else\n%\n%   See also: isodd\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%% ===== Computation =====================================================\n% Create answer\nbool = false( size(number) );\n% Look for even numbers, use bitget to overcome a mod() bug, see\n% https://bit.ly/1wcNYBI\nbool(bitget(number,1)==0) = true;\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_general/iseven.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5585633169018239}}
{"text": "function [hd_record]=tvhdecomp(beta_gibbs,D_record,strshocks_record,It,Bu,Y,n,m,p,k,T)\n\n\n\n\n\n\n\n\n\n\n\n% preliminary tasks\n% first create the hd_record and temp cells\nhd_record=cell(n,n+1);\ntemp=cell(n,2);\n\n\n\n% then initiate the Gibbs algorithm\nfor ii=1:It-Bu\n\n% recover beta for the current iteration (one column for each period)\nbeta_iter=[];\nfor jj=1:T\nbeta_iter=[beta_iter beta_gibbs{jj,1}(:,ii)];\nend\n    \n\n% recover D for the current iteration (one page for each period)\nD_iter=repmat(reshape(D_record(:,ii),n,n),[1,1,T]);\n\n% recover the series of period-specific orthogonal IRFs\n[IRFcell]=bear.tvhdsim(beta_iter,D_iter,n,m,p,T,k);\n\n\n% recover the structural disturbances\nETA=[];\nfor jj=1:n\nETA=[ETA;strshocks_record{jj,1}(ii,:)];\nend\nETA=ETA';\n\n\n% then compute the historical decomposition\n   % loop over variables\n   for jj=1:n\n      % loop over shocks\n      for kk=1:n\n      % loop over shocks\n      vshocks=ETA(:,kk);\n         % loop over time periods\n         for ll=1:T\n         % initiate the vectors of IRFs and shocks\n         virf=[];\n            % then loop over IRF periods\n            for mm=1:ll\n            % create the vector of IRF coefficients\n            virf=[virf IRFcell{mm,ll}(jj,kk)];\n            end\n         % compute then the contribution of shock kk for variable jj at period ll\n         hd_record{jj,kk}(ii,ll)=virf*flipud(vshocks(1:ll,1));\n         end\n      end\n   end\n\n\n% then go for next Gibbs iteration\nend\n\n\n\n\n\n% step 6: compute the contributions of deterministic variables\n% loop over rows of temp/hd_record\nfor ii=1:n\n% fill the Ytot matrix in temp\n% initial condition\ntemp{ii,1}=hd_record{ii,1};\n   % sum over the remaining columns of hd_record\n   for jj=2:n\n   temp{ii,1}=temp{ii,1}+hd_record{ii,jj};\n   end\n% fill the Y matrix in temp\ntemp{ii,2}=repmat(Y(:,ii)',It-Bu,1);\n% fill the Yd matrix in hd_record\nhd_record{ii,n+1}=temp{ii,2}-temp{ii,1};\n% go for next variable\nend\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/tvhdecomp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5584133554014205}}
{"text": "clear all\n\ndt = 0.05;\nt  = 0:dt:20;\n\nNsamples = length(t);\n\nXsaved = zeros(Nsamples, 3);\nZsaved = zeros(Nsamples, 1);\n               \nfor k=1:Nsamples\n  r = GetRadar(dt); \n\n  [pos vel alt] = RadarUKF(r, dt);\n  \n  Xsaved(k, :) = [pos vel alt];\n  Zsaved(k)    = r;\nend \n\n\nPosSaved = Xsaved(:, 1);\nVelSaved = Xsaved(:, 2);\nAltSaved = Xsaved(:, 3);\n\nt = 0:dt:Nsamples*dt-dt;\n\nfigure\nplot(t, PosSaved)\n\nfigure\nplot(t, VelSaved)\n\nfigure\nplot(t, AltSaved)", "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/TestRadarUKF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5584133506414567}}
{"text": "function fh = sumcolumns_fh(m,w)\n% This is almost an MV2DF, but it does not return derivatives on numeric\n% input, w.\n%\n%  w -> W = reshape(w,m,[]) -> sum(W,1)'\n\n\nif nargin==0\n    test_this();\n    return;\nend\n\n\nmap = @(w) map_this(w,m);\ntransmap = @(y) transmap_this(y,m);\n\n\nfh = linTrans([],map,transmap);\n\nif exist('w','var') && ~isempty(w)\n    fh = fh(w);\nend\n\n\nend\n\n\nfunction w = transmap_this(y,m) \n  w = repmat(y(:).',m,1);\nend\n\nfunction s = map_this(w,m) \nW = reshape(w,m,[]);\ns = sum(W,1);\nend\n\n\nfunction test_this()\nm = 3; \nn = 4;\nf = sumcolumns_fh(m);\nW = randn(m,n);\ntest_MV2DF(f,W(:));\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/linear/sumcolumns_fh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5584133441440456}}
{"text": "function [z,mz,onrim,Hd_record] = cg_steihaug(grad,hess,Delta,epsilon,maxCG,y,Hd_back,quiet)\n% Helper function for trustregion_newton_cg\n\nsavemem = true;\n\ngrad = grad(:);\nonrim = false;\nif exist('Hd_back','var') && ~isempty(Hd_back)\n    Hd_record = Hd_back;\n    backtrack = true;\nelse\n    backtrack = false;\n    if savemem\n        Hd_record = zeros(length(grad),maxCG,'single');\n    else\n        Hd_record = zeros(length(grad),maxCG);\n    end\nend\n\nz = zeros(size(grad));  % z is step, we start at origin\nmz = 0;                 % 2nd order prediction for objective change at step z \nr = grad;               % 2nd order residual at z:  r = H*z-grad\nd = -r;                 % we're going down\n\nresidual = sqrt(r'*r)/epsilon;\nif residual <= 1\n    Hd_record = [];\n    fprintf('CG 0: as far as I can see, this should never happen\\n');\n    fprintf('CG 0: converged with zero step, residual = %g\\n',residual);\n    return\nend\n\nj=0;\nwhile true\n    if backtrack && j+1 <= size(Hd_back,2)\n        Hd = double(Hd_back(:,j+1));\n    else\n        Hd = hess(d);\n        if j+1 <= size(Hd_record)\n            Hd_record(:,j+1) = Hd;\n        end\n    end\n    dHd = d'*Hd;\n    if dHd <=0 %region is non-convex in direction d\n        a = d'*d;\n        b = 2*z'*d;\n        c = z'*z-Delta^2;\n        discr = sqrt(b^2-4*a*c);\n        tau1 = (-b - discr)/(2*a);\n        tau2 = (-b + discr)/(2*a);\n        model = @(tau) tau*grad'*d + 0.5*tau^2*dHd;\n        if model(tau1) < model(tau2)\n            tau = tau1;\n        else\n            tau = tau2;\n        end\n        z = z + tau*d;\n        mz = mz + tau*d'*grad + 0.5*tau^2*dHd;\n        onrim = true;\n        if ~quiet, fprintf('CG %i: curv=%g, jump to trust region boundary\\n',j,dHd); end\n        break;\n    end\n    \n    alpha = r'*r/dHd;\n    old_z = z;\n    old_mz = mz;\n    z = z + alpha*d;\n    mz = mz + alpha*d'*grad + 0.5*alpha^2*dHd;\n\n    \n    radius = sqrt(z'*z)/Delta;\n    if radius > 1\n        a = d'*d;\n        b = 2*z'*d;\n        c = old_z'*old_z-Delta^2;\n        discr = sqrt(b^2-4*a*c);\n        tau = (-b + discr)/(2*a);\n        z = old_z + tau*d;\n        mz = old_mz + tau*d'*grad + 0.5*tau^2*dHd;\n        onrim = true;\n        if ~quiet, fprintf('CG %i: curv=%g, terminate on trust region boundary, model=%g\\n',j,dHd,-mz); end\n        break;\n    end\n\n    old_r = r;\n    r = r + alpha*Hd;\n    residual = sqrt(r'*r)/epsilon;\n    if residual <= 1 \n        if ~quiet, \n            fprintf('CG %i: curv=%G, converged inside trust region; radius = %g, residual=%g, model=%g\\n',j,dHd,radius,residual,-mz); \n        end\n        break;\n    end\n    \n    overshot = ~isempty(y) && y+mz <0;\n    if overshot \n        if ~quiet, \n            fprintf('CG %i: curv=%G, overshot inside trust region; radius = %g, residual=%g, model=%g\\n',j,dHd,radius,residual,-mz);\n        end\n        break;\n    end\n    \n    %stopped = backtrack && j+1 >= maxCG;\n    stopped = j+1 >= maxCG;\n    if stopped \n        if ~quiet, \n            fprintf('CG %i: curv=%G, stopped inside trust region; radius = %g, residual=%g, model=%g\\n',j,dHd,radius,residual,-mz);\n        end\n        break;\n    end\n    \n    \n    \n    \n    beta = (r'*r)/(old_r'*old_r);\n    d = -r + beta*d;\n    if ~quiet, fprintf('CG %i: curv=%g, radius = %g, residual=%g, model=%g\\n',j,dHd,radius,residual,-mz); end\n    j = j+1;\nend\n\n\nif j+1<size(Hd_record,2)\n    Hd_record = Hd_record(:,1:j+1);\nend\nreturn\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/TRNCG/cg_steihaug.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5584133435648961}}
{"text": "function [ar, name] = aspectratio(D)\n%\n% ar = height / width\n\nk = 0;\nfor i = 1:length(D);\n    if isfield(D(i).annotation, 'object')\n        Nobjects = length(D(i).annotation.object);\n        \n        for n = 1:Nobjects\n            [X,Y] = getLMpolygon(D(i).annotation.object(n).polygon);\n\n            k = k+1;\n            ar(k) = abs((max(Y)-min(Y))/(0.00001+max(X)-min(X)));\n            name{k} = D(i).annotation.object(n).name;\n        end\n    end\nend\n", "meta": {"author": "CSAILVision", "repo": "LabelMeToolbox", "sha": "b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2", "save_path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox", "path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox/LabelMeToolbox-b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2/main/aspectratio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5584133393840819}}
{"text": "function [y, gene, times, scale, rawExp] = gpsimLoadEcoliData\n\n% GPSIMLOADECOLIDATA Load in E. coli data for the represion case.\n% FORMAT\n\n% RETURN y : the normalised expression levels.\n% RETURN yvar : the variance of the normalised expression levels.\n% RETURN gene : the gene names and Affymetrix array tags.\n% RETURN times : the times of the expression measurements.\n% RETURN scale : the scaling factor applied to normalise.\n% RETURN rawExp : the raw gene expresion level.\n% \n% SEEALSO : demEcoliMap1\n%\n% COPYRIGHT : Pei Gao, Neil D. Lawrence and Magnus Rattary, 2008\n\n% SHEFFIELDML\n\nif exist('./data/ecoliData.mat') == 2 \n  load('./data/ecoliData.mat');\nelse\n  expData = importdata('./data/ecoliNormalisedData.txt');\n  rawExp.data = expData';\n  rawExp.genes = {'dinF', 'dinI', 'lexA', 'recA', 'recN', 'ruvA', 'ruvB', ...\n                  'sbmC', 'sulA', 'umuC', 'umuD', 'uvrB', 'yebG', 'yjiW' };\n  \n  targetInd = [2 3 6 7 9 11 12 14];\n  \n% Perform log-normal transformation.\n  yFull = exp(rawExp.data(:, targetInd));  % Logs are normally distributed\n                                   % ... recover mean in exp space.\n  \n  % Rescale so that average standard deviation of curves is 1.\n  scale = sqrt(var(yFull));\n  scaleMat = ones(size(yFull, 1), 1)*scale;\n  y{1} = yFull./scaleMat;\n  times = [0 5 10 20 40 60]';\n  gene = rawExp.genes(targetInd);\n%  save('./data/ecoliData.mat', 'y', 'gene', 'times', 'scale', 'rawExp');\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gpsim/gpsimLoadEcoliData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6791786991753929, "lm_q1q2_score": 0.5584133382257833}}
{"text": "function varargout=ndstest(TOL)\n%Performs numerous tests of ndSparse math operations, \n%\n%  ndstest(TOL)\n%\n%TOL is a tolerance value on the percent error. Execution will pause in debug\n%mode for inspection if any one of the tests exhibits an error greater than\n%TOL.\n\nif nargin<1\n TOL=inf; %default tolerance value on discrepancies\nend\n\nCHECKTYPES=false;\n\n%%function for measuring error\n\n err=@(x,y) DiscrepancyMeasure(x,y,TOL,CHECKTYPES);\n \n  \nPf=srand(3,3,2,4);\nQf=srand(size(Pf));\nAf=srand(3,2)*1i;  \nBf=srand(3,2);\nCf=srand(3,2);\nSf=srand(3);\nVrf=1:(numel(Pf)-3);\nVcf=Vrf.';\nthree=single(3);\n\n%%Representations of the above as ndSparse objects \nP=ndSparse(Pf(:),size(Pf));   % =Pf\nQ=ndSparse(Qf(:),size(Qf));   % =Qf\nA=ndSparse(Af);   % =Af\nB=ndSparse(Bf);   % =Bf\nC=ndSparse(Cf);   % =Cf\nS=ndSparse(Sf);   % =Sf\nVc=ndSparse(Vcf);   % =Vcf\nVr=ndSparse(Vrf);   % =Vrf\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%TESTS%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%Test of full()\nError(1)=     err( full(P), Pf  );  \nError(end+1)= err( full(Q), Qf  );  \nError(end+1)= err( full(S), Sf );  \n\n%%Test of sparse2d, sparse\n\n  %Error(end+1)= ~isequal( sparse(A), A ); %obsolete test of sparse(ndSparse)\n\nError(end+1)= ~isequal( sparse2d(A), reshape(sparse(Af),[],size(Af,ndims(Af)) ) );\nError(end+1)= ~isequal( sparse(A), sparse(Af) );\n\n   %%No sense in proceding if the tests so far didn't pass - the error\n   %%calculations rely on the functionality of full@ndSparse()\n    if max(Error)>TOL,\n        Error,\n        error 'Something wrong with sparse() and full() methods'; \n    end\n\n%Test of logical, double\n\nError(end+1)=err( class(logical(P)), class(logical(Pf)));\nError(end+1)=err( class(double(P)), class(double(Pf)));\n\n\n%%Test isnumeric, islogical, isempty, issparse, isfloat, isreal,isinf, \n%      isnan, isfinite, isequal, isequalwithequalnans            \nError(end+1)= err( isnumeric(P),1);\nError(end+1)= err( ~isnumeric(P>0),1);\nError(end+1)= err( isfloat(P),1);\nError(end+1)= err( ~isfloat(P>0),1);\nError(end+1)= err( ~islogical(P),1);\nError(end+1)= err( islogical(P>0),1);           \nError(end+1)= err( ~isempty(P),1);   \nError(end+1)= err( isempty(ndSparse([])),1);\nError(end+1)= err( issparse(P),1);\nError(end+1)= err( issparse(A), 1 );\nError(end+1)= err( ~isreal(A), 1 );\nError(end+1)= err( isreal(B), 1 );\n\n     Z=P; Z(1)=nan; Z(2)=inf;\n     Zf=full(Z);\n     \nError(end+1)= err( isnan(Z), isnan(Zf) );\nError(end+1)= err( isinf(Z), isinf(Zf) );     \nError(end+1)= err( isfinite(Z), isfinite(Zf) );      \nError(end+1)= err( ~isequal(Z,Zf), 1 ); \nError(end+1)= err( ~isequal(Zf,Z), 1 ); \nError(end+1)= err( ~isequal(Z,Zf,Z), 1 ); \nError(end+1)= err( ~isequal(Zf,Z,Z), 1 ); \nError(end+1)= err( isequalwithequalnans(Z,Zf), 1 ); \nError(end+1)= err( isequalwithequalnans(Zf,Z), 1 );\nError(end+1)= err( isequalwithequalnans(Z,Zf,Z), 1 ); \nError(end+1)= err( isequalwithequalnans(Zf,Z,Zf), 1 ); \n\n\n%Test of real, imag, conj, abs,sqrt\n\n     Z=ndSparse(Bf+Af); %complex result\n     Zf=full(Z);\n     \nError(end+1)= err( real(Z), real(Zf) );\nError(end+1)= err( imag(Z), imag(Zf) );     \nError(end+1)= err( conj(Z), conj(Zf) );   \nError(end+1)= err( abs(Z), abs(Zf) );\nError(end+1)= err( sqrt(Z), sqrt(Zf) );\n            \n\n\n%%Test of size\n\nError(end+1)=err( size(P), size(Pf) );\nError(end+1)=err( size(P,2), size(Pf,2) );\n\n       [mm,nn]  =size(Q);\n       [mmm,nnn]=size(Qf);\n       \nError(end+1)=err( [mm,nn] , [mmm,nnn] );\n\n%%Test of reshape\n\nError(end+1)= err( reshape(P,size(P,1),[]) , reshape(Pf,size(Pf,1),[]));\n\n%%Test of permute, ipermute\n\n       ord=randperm(ndims(Pf));\n       Z=permute(P,ord);\n       Zf=permute(Pf,ord);\n       \nError(end+1)= err( Z , Zf );\nError(end+1)= err( ipermute(Z,ord) ,  Pf );\n\n\n%%Test of transpose, ctranspose\nError(end+1)= err( A.' ,  Af.'   );\nError(end+1)= err( A'  ,  Af'   );\n\n\n%%Test of uplus, uminus\n\nError(end+1)= err( +P  , +Pf );\nError(end+1)= err( -Q  , -Qf );\n\n%%Test of plus, minus\n\nError(end+1)= err( P+Q  , Pf+Qf );\nError(end+1)= err( P-Q ,  Pf-Qf );\n\n\n%%Test of inv\n\nError(end+1)= err( inv(S)  , inv(Sf) );\n\n%%Test of find\n\n            [II,JJ,KK]=find(P);\n            [IIf,JJf,KKf]=find(Pf);      \n            \nError(end+1)= err( II  , IIf );\nError(end+1)= err( JJ  , JJf );\nError(end+1)= err( KK  , KKf );\n\n%%Test of mtimes\n\nError(end+1)= err( A*three , Af*three  );  %scalar with ndSparse\nError(end+1)= err( three*P , three*Pf  );\n\nError(end+1)= err( S*A , Sf*Af  ); % 2 ndSparses\n\n   x=Af(end,:).';\n   y=Af(:,end).';\n\nError(end+1)= err( A*[x,x] , Af*[x,x]  ); %pre-mult with columnized data\nError(end+1)= err( [y;y]*A , [y;y]*Af  ); %post-mult with columnized data\n\nError(end+1)= err( S*Af , Sf*Af  ); %mixed op\n\n\n\n%%Test of mldivide\nError(end+1)= err( three\\P , three\\Pf  );  %scalar with ndSparse\nError(end+1)= err( three\\A , three\\Af  );\nError(end+1)= err( B\\A , Bf\\Af  ); % 2 ndSparses\nError(end+1)= err( B\\Af , Bf\\Af  );\n\n\n%%Test of mrdivide\n  \n    Bt=B.'; Btsp=Bf.';\n\nError(end+1)= err( Bt/three , Btsp/three  );%scalar with ndSparse\n\nError(end+1)= err( P/three , Pf/three  );%scalar with ndSparse\nError(end+1)= err( A.'/Bt , Af.'/Btsp ); % 2 ndSparses\nError(end+1)= err( Af.'/Bt , Af.'/Btsp );\n\n\n%%Test of times\n\nError(end+1)= err( P.*three , Pf.*three  );  %scalar with ndSparse\nError(end+1)= err( three.*P , three.*Pf  );\n\nError(end+1)= err( P.*Q , Pf.*Qf  ); % 2 ndSparses\nError(end+1)= err( Pf.*Q , Pf.*Qf  ); \n\n%%Test of rdivide\n\nError(end+1)= err( Q./three , Qf./three  );  %scalar with ndSparse\nError(end+1)= err( three./Q , three./Qf  );\n\nError(end+1)= err( P./Q , Pf./Qf  ); %2 ndSparses\nError(end+1)= err( Q./P , Qf./Pf  ); %2 ndSparses\nError(end+1)= err( Qf./P , Qf./Pf  ); %mixed\n\n%%Test of ldivide\n\nError(end+1)= err( Q.\\three , Qf.\\three  );  %scalar with ndSparse\nError(end+1)= err( three.\\Q , three.\\Qf  );\n\nError(end+1)= err( Q.\\P , Qf.\\Pf  ); %2 ndSparses\nError(end+1)= err( P.\\Q , Pf.\\Qf  ); %2 ndSparses\nError(end+1)= err( Pf.\\Q , Pf.\\Qf  );\n\n%%Test of power, mpower\nError(end+1)= err( P.^three ,  Pf.^three   );\nError(end+1)= err( three.^P ,  three.^Pf   );\nError(end+1)= err( Q.^P ,  Qf.^Pf   );\nError(end+1)= err( Qf.^P ,  Qf.^Pf   );\n\n%%Test of mpower\nError(end+1)= err( S^three  ,  Sf^three   );\n\n\n%%Test of relops\n\nError(end+1)= err( P>P ,  Pf>Pf   );\nError(end+1)= err( P>Pf ,  Pf>Pf   );\nError(end+1)= err( P>three/6  , Pf>three/6   );\n\nError(end+1)= err( P>=P ,  Pf>=Pf   );\nError(end+1)= err( P>=Pf ,  Pf>=Pf   );\nError(end+1)= err( P>=three/6  , Pf>=three/6   );\n\nError(end+1)= err( P<P ,  Pf<Pf   );\nError(end+1)= err( P<Pf ,  Pf<Pf   );\nError(end+1)= err( P<three/6  , Pf<three/6   );\n\nError(end+1)= err( P<=P ,  Pf<=Pf   );\nError(end+1)= err( P<=Pf ,  Pf<=Pf   );\nError(end+1)= err( P<=three/6  , Pf<=three/6   );\n\n\nError(end+1)= err( P==P ,  Pf==Pf   );\nError(end+1)= err( P==Pf ,  Pf==Pf   );\nError(end+1)= err( P==three/6  , Pf==three/6   );\n\nError(end+1)= err( P~=P ,  Pf~=Pf   );\nError(end+1)= err( P~=Pf ,  Pf~=Pf   );\nError(end+1)= err( P~=three/6  , Pf~=three/6   );\n\n%%Test of logical ops\n\nError(end+1)= err( P&P ,  Pf&Pf   );\nError(end+1)= err( P&Pf ,  Pf&Pf   );\nError(end+1)= err( P|three/6  , Pf|three/6   );\n\nError(end+1)= err( ~P ,   ~Pf   );\nError(end+1)= err( ~Q  ,  ~Qf  );\n\n\n%%Test of sum\n\nError(end+1)= err( sum(P,1)  , sum(Pf,1) );\nError(end+1)= err( sum(Q,2)  , sum(Qf,2) );\nError(end+1)= err( sum(P)    , sum(Pf) );\nError(end+1)= err( sum(P,'native')    , sum(Pf,'native') );\nError(end+1)= err( sum(P,3,'double')    , sum(Pf,3,'double') );\nError(end+1)= err( sum(P,4)    , sum(Pf,4) );\nError(end+1)= err( sum(P,5)    , sum(Pf,5) );\n\n%%Test of cat, horzcat, vertcat\n\nError(end+1)= err([P,P] ,[Pf,Pf]);\nError(end+1)= err([Pf,P] ,[Pf,Pf]);\nError(end+1)= err([P,Pf] ,[Pf,Pf]);\n\nError(end+1)= err([P;P] ,[Pf;Pf]);\nError(end+1)= err([Pf;P] ,[Pf;Pf]);\nError(end+1)= err([P;Pf] ,[Pf;Pf]);\n\nError(end+1)= err([P,P] ,[Pf,Pf]);\nError(end+1)= err([Pf,P] ,[Pf,Pf]);\nError(end+1)= err([P,Pf] ,[Pf,Pf]);\n\nError(end+1)= err(cat(3,P,P,P) ,cat(3,Pf,Pf,Pf));\nError(end+1)= err(cat(3,Pf,P) ,cat(3,Pf,Pf));\nError(end+1)= err(cat(3,P,Pf) ,cat(3,Pf,Pf));\n\nError(end+1)= err(cat(4,P,Pf) ,cat(4,Pf,Pf));\nError(end+1)= err(cat(5,P,Pf) ,cat(5,Pf,Pf));\n\n\n%%Test of spfun\n\n f=@(x) cos(x).^2;\n \nError(end+1)= err( spfun(f,P) ,    reshape(full(spfun(f,Pf(:))) ,size(Pf)) );\n\n\n\n\n%%Test of subsindex\n\n   idx=1:3;\n   Zf=rand(3);\n\nError(end+1)= err( Zf(ndSparse(idx)) , Zf(idx) );   \n   \n\n%%Test of subsref\n\n\nError(end+1)= err( P(P<.5) ,  Pf(Pf<.5)   ); %logical indexing\nError(end+1)= err( Pf(P<.5) ,  Pf(Pf<.5)   ); \nError(end+1)= err( P(Pf<.5) ,  Pf(Pf<.5)   );\n\nError(end+1)= err( P(:) ,  Pf(:)   );  %linear indexing\nError(end+1)= err( P(1) ,  Pf(1)   );  \nError(end+1)= err( P(1:4) ,  Pf(1:4)   );\nError(end+1)= err( P((1:4).') ,  Pf((1:4).')   );\nError(end+1)= err( Vc(1:3) ,  Vcf(1:3)   );\nError(end+1)= err( Vr(1:3) ,  Vrf(1:3)   );\n\nError(end+1)= err( P(Vc(1:3)) ,  Pf(Vcf(1:3))   ); %indexing vectors test different shaping rules\nError(end+1)= err( Pf(Vc(1:3)) ,  Pf(Vcf(1:3))   );\nError(end+1)= err( P(Vcf(1:3)) ,  Pf(Vcf(1:3))   );\nError(end+1)= err( Pf(Vcf(1:3)) ,  Pf(Vcf(1:3))   );\n\n\nError(end+1)= err( P(2,1,2,2) ,  Pf(2,1,2,2)   ); %subscript indexing\nError(end+1)= err( P(2,:,2,2) ,  Pf(2,:,2,2)   );\nError(end+1)= err( P(:,1,:,2) ,  Pf(:,1,:,2)   ); \nError(end+1)= err( P(:,2,2,2) ,  Pf(:,2,2,2)   );\nError(end+1)= err( P(1,2,2,:) ,  Pf(1,2,2,:)   );\nError(end+1)= err( P(:,:,:,2) ,  Pf(:,:,:,2)   );\n\nError(end+1)= err( P(2,1,2) ,  Pf(2,1,2)   ); %truncated subscript indexing\nError(end+1)= err( P(2,:,2) ,  Pf(2,:,2)   );\nError(end+1)= err( P(:,1,:) ,  Pf(:,1,:)   ); \nError(end+1)= err( P(:,2,2) ,  Pf(:,2,2)   );\n\n            lidx=logical([1 0]);\n            \nError(end+1)= err( P(lidx,lidx,1:2) ,  Pf(lidx,lidx,1:2)   ); %combine all types of indexing\nError(end+1)= err( P(lidx,lidx,:) ,  Pf(lidx,lidx,:)   ); \nError(end+1)= err( P(lidx,:,lidx) ,  Pf(lidx,:,lidx)   ); \n\n\n%%Test of subsasgn\n\n        Z=P; \n        Zf=Pf;\n\n        Z(Z<.5)=6;   Zf(Zf<.5)=6;\n       \n        \nError(end+1)= err(  Z, Zf); %logical indexing\n\n        Z(1)=7;   Zf(1)=7;\n       \n        \nError(end+1)= err(  Z, Zf); %scalar indexing\n\n\n\n        Z(Zf<.5)=13; Zf(Zf<.5)=13;\n       \n        \nError(end+1)= err( Z ,  Zf   );\n\n           Z(:)=999; Zf(:)=999;\n           \nError(end+1)= err(  Z, Zf    ); \n\n           Z(1:4)=88;  Zf(1:4)=88;  \n\nError(end+1)= err( Z ,  Zf   );\n\n          Z((1:4).')=77;  Zf((1:4).')=77; \n\nError(end+1)= err(Z,Zf);\n         \n          d=rand;\n          Z(2,1,2,2)=d;   Zf(2,1,2,2)=d;\n          \nError(end+1)= err(Z,Zf); %subscript indexing\n\n           d=rand;         \n          Z(2,:,2,2)=d;  Zf(2,:,2,2)=d;\n\nError(end+1)= err(Z,Zf);\n\n          d=rand;\n          Z(:,2,2,2)=d;  Zf(:,2,2,2)=d; \n\nError(end+1)= err(Z,Zf);\n\n          d=rand;         \n          Z(:,:,:,2)=d;  Zf(:,:,:,2)=d;  \n          \n\n\nError(end+1)= err(Z,Zf);\n\n           mm=size(Z,1)+3;\n           nn=size(Z,2)+3;\n\n          Z(mm,nn,:,:)=5;  Zf(mm,nn,:,:)=5; %matrix expansion test\n\n          \nError(end+1)= err(Z,Zf);\n\n          Z(:,1:2:end,:,:)=[];  Zf(:,1:2:end,:,:)=[]; %null assignment test          \n          \nError(end+1)= err(Z,Zf);\n\n           Z=P; Zf=Pf;\n           Z(:,mod(1:2:end,2)==1,:,:)=[];  %null assignment test logical indexing\n           Zf(:,mod(1:2:end,2)==1,:,:)=[];\n           \n           \nError(end+1)= err(Z,Zf);          \n          \n      Z=P; Zf=Pf;\n      Z(:,:,:,:,1)=0;  Zf(:,:,:,:,1)=0; %matrix expansion with n-1 colons          \n      Z(:,:,:,:,1)=[];  Zf(:,:,:,:,1)=[]; %null assignment with n-1 colons \n      \n      \nError(end+1)= err(Z,Zf); \n\n           Z=P; Zf=Pf;\n\n           d=rand(size(Zf(:,:,1)));\n           \n           Z(:,:,1)=d;  Zf(:,:,1)=d; %nonscalar assignment\n           \nError(end+1)= err( Z , Zf   ); \n\n            idx={':'};\n            \n            Z=P; Zf=Pf;\n            d=rand(size(Zf(idx{:})));\n            \n            Z(idx{:})=d;  Zf(idx{:})=d;%nonscalar assignment\n            \n                     \nError(end+1)= err(Z,Zf);            \n\n            lidx=logical([1 0]);\n            \n            idx={lidx,lidx,1:2};\n            \n            Z=P; Zf=Pf;\n            d=rand(size(Zf(idx{:})));\n            \n            Z(idx{:})=d;  Zf(idx{:})=d;%combine all types of indexing\n            \n            \nError(end+1)= err( Z , Zf   ); \n\n\n\n\n\n\n%%Test of all(), any(), mean(), max/min\n\n      Z=P>.5; Zf=Pf>.5;\n      \n      Z(:,1,1,1)=0; Zf(:,1,1,1)=0;\n     \n      Args={ {},{1},{2},{3},{4},{5} };\n      for jj=1:length(Args)\n          \n          args=Args{jj};\n          \nError(end+1)= err( all(Z,args{:})  , all(Zf,args{:}) );\n\nError(end+1)= err( any(Z,args{:})  , any(Zf,args{:}) );\n\nError(end+1)= err( mean(Z,args{:})  , mean(Zf,args{:}) );\n\nError(end+1)= err( all(P,args{:})  , all(Pf,args{:}) );\n\nError(end+1)= err( any(P,args{:})  , any(Pf,args{:}) );\n\nError(end+1)= err( mean(P,args{:})  , mean(Pf,args{:}) );\n      end\n \n\n        Args={ {1},{2},{3},{4},{5} };\n \n      for jj=1:length(Args)\n          \n          args=Args{jj};        \n        \n          [Z,idx]=max(P,[],args{:});\n          [Zf,idxf]=max(Pf,[],args{:});\n          \nError(end+1)= err( Z ,Zf );       \nError(end+1)= err( idx ,idxf );    \n\n      end\n      \nError(end+1)= err( max(P,Q) , max(Pf,Qf) );      \nError(end+1)= err( max(P,Qf) , max(Pf,Qf) );      \nError(end+1)= err( max(Pf,Q) , max(Pf,Qf) );   \n\n \n      for jj=1:length(Args)\n          \n          args=Args{jj};        \n        \n          [Z,idx]=min(P,[],args{:});\n          [Zf,idxf]=min(Pf,[],args{:});\n          \nError(end+1)= err( Z ,Zf );       \nError(end+1)= err( idx ,idxf );    \n\n      end\n      \nError(end+1)= err( min(P,Q) , min(Pf,Qf) );      \nError(end+1)= err( min(P,Qf) , min(Pf,Qf) );      \nError(end+1)= err( min(Pf,Q) , min(Pf,Qf) );   \n\n\n       %%%%%%2D cases%%%%%\n\n      Z=B>.5; Zf=Bf>.5;\n      \n      Z(:,1,1,1)=0; Zf(:,1,1,1)=0;\n     \n      Args={ {},{1},{2},{3},{4},{5} };\n      for jj=1:length(Args)\n          \n          args=Args{jj};\n          \nError(end+1)= err( all(Z,args{:})  , all(Zf,args{:}) );\n\nError(end+1)= err( any(Z,args{:})  , any(Zf,args{:}) );\n\nError(end+1)= err( mean(Z,args{:})  , mean(Zf,args{:}) );\n\n\n      end\n \n\n        Args={ {1},{2},{3},{4},{5} };\n \n      for jj=1:length(Args)\n          \n          args=Args{jj};        \n        \n          [Z,idx]=max(B,[],args{:});\n          [Zf,idxf]=max(Bf,[],args{:});\n          \nError(end+1)= err( Z ,Zf );       \nError(end+1)= err( idx ,idxf );    \n\n      end\n      \nError(end+1)= err( max(B,C) , max(Bf,Cf) );      \nError(end+1)= err( max(B,Cf) , max(Bf,Cf) );      \nError(end+1)= err( max(Bf,C) , max(Bf,Cf) );   \n\n \n      for jj=1:length(Args)\n          \n          args=Args{jj};        \n        \n          [Z,idx]=min(B,[],args{:});\n          [Zf,idxf]=min(Bf,[],args{:});\n          \nError(end+1)= err( Z ,Zf );       \nError(end+1)= err( idx ,idxf );    \n\n      end\n      \nError(end+1)= err( min(B,C) , min(Bf,Cf) );      \nError(end+1)= err( min(B,Cf) , min(Bf,Cf) );      \nError(end+1)= err( min(Bf,C) , min(Bf,Cf) );   \n       \n       \n%Test of numel\nError(end+1)= err( numel(P) , numel(Pf) );\n\n%Test of repmat, circshift\n\n       N=ndims(Pf)+1;\n       z=ones(1,N);\n\n       \n       for kk=0:N\n\n           idx=nchoosek(1:N,kk);\n           \n           for jj=1:size(idx,1)\n               \n             arg2=z;\n             arg2(idx(jj,:))=2;\n  \nError(end+1)= err( repmat(P,arg2) , repmat(Pf,arg2) );\nError(end+1)= err( repmat(P,arg2-1) , repmat(Pf,arg2-1) );\nError(end+1)= err( circshift(P,arg2) , circshift(Pf,arg2) );\nError(end+1)= err( circshift(P,arg2-1) , circshift(Pf,arg2-1) );             \nError(end+1)= err( circshift(A,arg2) , circshift(Af,arg2) );\nError(end+1)= err( circshift(A,arg2-1) , circshift(Af,arg2-1) );             \n\n           end\n       end\n\n              Z=P*0; Zf=full(Z);\n       \nError(end+1)= err( repmat(Z,arg2) , repmat(Zf,arg2) );\nError(end+1)= err( circshift(Z,arg2) , circshift(Zf,arg2) );\nError(end+1)= err( repmat(Z,arg2-1) , repmat(Zf,arg2-1) );\nError(end+1)= err( circshift(Z,arg2-1) , circshift(Zf,arg2-1) );\n       \n       \n%Test of squeeze, shiftdim      \n\n     N=ndims(Pf);\n     z=ones(1,2*N); z(2:2:end)=size(P);\n     Z=reshape(P,[1 1 z]); %add some singleton dimensions\n     Zf=full(Z);\n     \nError(end+1)= err( squeeze(Z) , squeeze(Zf) );     \n\n    [Z,n]=shiftdim(Z); [Zf,nf]=shiftdim(Zf);\n\nError(end+1)= err( Z , Zf);  \nError(end+1)= err( n , nf);  \n\nError(end+1)= err( shiftdim(Z,3) , shiftdim(Zf,3));\nError(end+1)= err( shiftdim(Z,-3) , shiftdim(Zf,-3));\n\n%Test of bsxfun\n\n\n     funcs={@plus,@minus,@times,@rdivide,@ldivide,@power,...\n            @max,@min,@rem,@mod,@atan2,@hypot,@(a,b) a.^2-b};\n\n     lfuncs={@eq,@ne,@lt,@le,@gt,@ge,@and,@or,@xor};\n      \n     HH=P;\n     for qq=1:2 \n         \n     \n     \n     %test non-logical funcs\n     H=HH; Hf=full(H);\n     Z=mean(H,1); Z=mean(Z,3);   Zf=full(Z);\n     \n     \n     for kk=1:2\n        for ii=1:length(funcs)\n         \n          fun=funcs{ii};\n          \nError(end+1)= err( bsxfun(fun,Z,H) ,     bsxfun(fun,Zf,Hf)  );    \nError(end+1)= err( bsxfun(fun,Z,Hf) ,     bsxfun(fun,Zf,Hf)  );           \nError(end+1)= err( bsxfun(fun,Zf,H) ,     bsxfun(fun,Zf,Hf)  );    \nError(end+1)= err( bsxfun(fun,three,H) ,     bsxfun(fun,three,Hf)  );  \nError(end+1)= err( bsxfun(fun,Zf,three) ,     bsxfun(fun,Zf,three)  ); \n\n       end\n      \n      Z=mean(H,2); Zf=full(Z);\n      \n      end\n      \n      %test logical lfuncs      \n      H=(HH<0.5); Hf=full(H);\n      Z=mean(H,1); Z=mean(Z,3); \n      Z=(Z>0.5);  Zf=full(Z);\n     \n     \n      onebit=(rand>=0.5);\n      \n      for kk=1:2\n       for ii=1:length(lfuncs)\n         \n          fun=lfuncs{ii};\n          \nError(end+1)= err( bsxfun(fun,Z,H) ,     bsxfun(fun,Zf,Hf)  );    \nError(end+1)= err( bsxfun(fun,Z,Hf) ,     bsxfun(fun,Zf,Hf)  );           \nError(end+1)= err( bsxfun(fun,Zf,H) ,     bsxfun(fun,Zf,Hf)  );    \nError(end+1)= err( bsxfun(fun,onebit,H) ,     bsxfun(fun,onebit,Hf)  );  \nError(end+1)= err( bsxfun(fun,Zf,onebit) ,     bsxfun(fun,Zf,onebit)  ); \n\n       end\n      \n      Z=mean(H,2); \n      Z=(Z>0.5); Zf=full(Z);\n      \n      \n      end\n     \n      HH=repmat(P,[1,1,1,0]);\n     \n     end\n      \n%Test of ndSparse.build, nzmax, nonzeros   \n      \n      nzm=10;\n      Z=ndSparse.build([1 1 1; 2 2 2; 3 3 3; 4 4 4], 1:4,[4 4 6],nzm);\n      Zf=zeros(4,4,6); for ii=1:4, Zf(ii,ii,ii)= ii; end\n\nError(end+1)= err( Z , Zf  );    \nError(end+1)= err( nzmax(Z) , nzm );\nError(end+1)= err( nonzeros(Z) , nonzeros(Zf) );\n\n      nzm=10;\n      Z=ndSparse.build([1 1 1; 2 2 2; 3 3 3; 4 4 4], 5,[4 4 6],nzm);\n      Zf=zeros(4,4,6); for ii=1:4, Zf(ii,ii,ii)= 5; end\n\nError(end+1)= err( Z , Zf  );    \nError(end+1)= err( nzmax(Z) , nzm );\nError(end+1)= err( nonzeros(Z) , nonzeros(Zf) );\n\n\n       Z=ndSparse.build([4 4 6]);\n       Zf=zeros(4,4,6); \n\nError(end+1)= err( Z , Zf  );   \nError(end+1)= err( ndSparse.build([],[],[4 4 6]) , Zf  );    \nError(end+1)= err( nzmax(Z) , 1 );\nError(end+1)= err( nonzeros(Z) , nonzeros(Zf) );       \n       \n\n%Test of ndSparse.spalloc\n\n      nzm=10;\n      Z=ndSparse.spalloc([3,5,3],nzm);\n      Zf=full(Z);\n      \nError(end+1)= err( nzmax(Z) , nzm );  \nError(end+1)= err( Z , Zf );  \n\n%Test of ndSparse.accumarray\n\n         args={[1 1 1; 2 2 2; 3 3 3;2 2 2], [5,4,3,2]};\n         Z=ndSparse.accumarray(args{:});\n         Zf=accumarray(args{:});\n         \nError(end+1)= err( Z , Zf );  \n\n         args={[1 1 1; 2 2 2; 3 3 3;2 2 2], [5,4,3,2],[4 4 4]};\n         Z=ndSparse.accumarray(args{:});\n         Zf=accumarray(args{:});\n\nError(end+1)= err( Z , Zf );          \n\n         args={[1;2;3;2], [5,4,3,2]};\n         Z=ndSparse.accumarray(args{:});\n         Zf=accumarray(args{:});\n\nError(end+1)= err( Z , Zf );   \n\n         args={[1;2;3;2], [5,4,3,2],[4,1]};\n         Z=ndSparse.accumarray(args{:});\n         Zf=accumarray(args{:});\n\nError(end+1)= err( Z , Zf ); \n\n    \n         args={[1;2;3;2], [5,4,3,2],[4,1],@prod};\n         Z=ndSparse.accumarray(args{:});\n         Zf=accumarray(args{:});\n\nError(end+1)= err( Z , Zf ); \n\n%Test of spones\n\n          Z=ndSparse.build([1,1,1], 5,[3,5,3]);\n          Zf=full(Z); Zf(~~Zf)=1;\n       \nError(end+1)= err( spones(Z) , Zf );  \n      \n%Test of length\n\nError(end+1)= err( length(P) , length(Pf) );  \n\n%Test of triu,triul\n\nError(end+1)= err( triu(A) , triu(Af) );\nError(end+1)= err( triu(A,1) , triu(Af,1) );\nError(end+1)= err( triu(A,-1) , triu(Af,-1) );\n\nError(end+1)= err( tril(A) , tril(Af) );\nError(end+1)= err( tril(A,1) , tril(Af,1) );\nError(end+1)= err( tril(A,-1) , tril(Af,-1) );\n\nError(end+1)= err( triu(S) , triu(Sf) );\nError(end+1)= err( triu(S,1) , triu(Sf,1) );\nError(end+1)= err( triu(S,-1) , triu(Sf,-1) );\n\nError(end+1)= err( tril(S) , tril(Sf) );\nError(end+1)= err( tril(S,1) , tril(Sf,1) );\nError(end+1)= err( tril(S,-1) , tril(Sf,-1) );\n\n%Test of flipdim\n\nError(end+1)= err( flipdim(P,1) , flipdim(Pf,1) );\nError(end+1)= err( flipdim(P,2) , flipdim(Pf,2) );\nError(end+1)= err( flipdim(P,3) , flipdim(Pf,3) );\n\n\n%Test of  fliplr\n\n   Z=P(:,:,:,1); Zf=full(Z);   for ii=1:size(Zf,3), Zf(:,:,ii)=fliplr( Zf(:,:,ii) ); end\n\nError(end+1)= err( fliplr(Z) ,  Zf );\n\n%Test of flipud \n\n   Z=P(:,:,:,1);  Zf=full(Z);    for ii=1:size(Zf,3), Zf(:,:,ii)=flipud( Zf(:,:,ii) ); end\n   \nError(end+1)= err( flipud(Z) ,  Zf );\n\n%Test of rot90\n\n  Z=P(:,:,:,1);  Zf=full(Z);    for ii=1:size(Zf,3), Zf(:,:,ii)=rot90( Zf(:,:,ii) ); end\n   \nError(end+1)= err( rot90(Z) ,  Zf );\n\n             for kk=-5:5\n\n   Z=P(:,:,:,1);  Zf=full(Z);    for ii=1:size(Zf,3), Zf(:,:,ii)=rot90( Zf(:,:,ii) ,kk); end\n   \nError(end+1)= err( rot90(Z,kk) , Zf);\n\n             end\n\n%Test of convn\n\n            args={{},{'full'},{'same'},{'valid'}};\n            Zs=sparse([0;0;1;2]); Zf=full(Zs);\n            \n            for ii=1:length(args)\n                \nError(end+1)= err( convn(P,P,args{ii}{:}) , convn(Pf,Pf,args{ii}{:}) );\nError(end+1)= err( convn(P,A,args{ii}{:}) , convn(Pf,Af,args{ii}{:}) );\n\nError(end+1)= err( convn(Pf,P,args{ii}{:}) , convn(Pf,Pf,args{ii}{:}) );\nError(end+1)= err( convn(Pf,A,args{ii}{:}) , convn(Pf,Af,args{ii}{:}) );\n\nError(end+1)= err( convn(P,Pf,args{ii}{:}) , convn(Pf,Pf,args{ii}{:}) );\nError(end+1)= err( convn(P,Af,args{ii}{:}) , convn(Pf,Af,args{ii}{:}) );\n             \n\nError(end+1)= err( convn(P,Zs,args{ii}{:}) , convn(Pf,Zf,args{ii}{:}) );\nError(end+1)= err( convn(Zs,P,args{ii}{:}) , convn(Zf,Pf,args{ii}{:}) );\n\nError(end+1)= err( convn(P,Zf,args{ii}{:}) , convn(Pf,Zf,args{ii}{:}) );\nError(end+1)= err( convn(Zf,P,args{ii}{:}) , convn(Zf,Pf,args{ii}{:}) );\n\n            end\n\n            Hf={rand(2,1),rand(1,3)};\n            H=Hf;\n            H{1}=ndSparse(H{1}); \n            \n            Zf=diag([0 0 0 0 0 1 1]);\n            Zs=sparse(Zf); \n            \n           for ii=1:length(args)\n                \nError(end+1)= err( convn(H{:},A,args{ii}{:}) , conv2(Hf{:},Af,args{ii}{:}) );\n\nError(end+1)= err( convn(H{:},Zs,args{ii}{:}) , conv2(Hf{:},Zf,args{ii}{:}) );\n\n\nError(end+1)= err( convn(H{:},Zf,args{ii}{:}) , conv2(Hf{:},Zf,args{ii}{:}) );\n\n           end\n\n\n           \n           \n%%Test of allml(), anyml(), meanml(), maxml/minml, summl, catml\n\n      Z=P>.5; Zf=Pf>.5;\n      \n      Z(:,1,1,1)=0; Zf(:,1,1,1)=0;\n     \n      Args={ {},{1},{2},{3},{4},{5} };\n      for jj=1:length(Args)\n          \n          args=Args{jj};\n          \nError(end+1)= err( allml(Z,args{:})  , all(Zf,args{:}) );\n\nError(end+1)= err( anyml(Z,args{:})  , any(Zf,args{:}) );\n\nError(end+1)= err( meanml(Z,args{:})  , mean(Zf,args{:}) );\n\nError(end+1)= err( allml(P,args{:})  , all(Pf,args{:}) );\n\nError(end+1)= err( anyml(P,args{:})  , any(Pf,args{:}) );\n\nError(end+1)= err( meanml(P,args{:})  , mean(Pf,args{:}) );\n      end\n \n\n        Args={ {1},{2},{3},{4},{5} };\n \n      for jj=1:length(Args)\n          \n          args=Args{jj};        \n        \n          [Z,idx]=maxml(P,[],args{:});\n          [Zf,idxf]=max(Pf,[],args{:});\n          \nError(end+1)= err( Z ,Zf );       \nError(end+1)= err( idx ,idxf );    \n\n      end\n      \nError(end+1)= err( maxml(P,Q) , max(Pf,Qf) );      \nError(end+1)= err( maxml(P,Qf) , max(Pf,Qf) );      \nError(end+1)= err( maxml(Pf,Q) , max(Pf,Qf) );   \n\n \n      for jj=1:length(Args)\n          \n          args=Args{jj};        \n        \n          [Z,idx]=minml(P,[],args{:});\n          [Zf,idxf]=min(Pf,[],args{:});\n          \nError(end+1)= err( Z ,Zf );       \nError(end+1)= err( idx ,idxf );    \n\n      end\n      \nError(end+1)= err( minml(P,Q) , min(Pf,Qf) );      \nError(end+1)= err( minml(P,Qf) , min(Pf,Qf) );      \nError(end+1)= err( minml(Pf,Q) , min(Pf,Qf) );   \n\n\n       %%%%%%2D cases%%%%%\n\n      Z=B>.5; Zf=Bf>.5;\n      \n      Z(:,1,1,1)=0; Zf(:,1,1,1)=0;\n     \n      Args={ {},{1},{2},{3},{4},{5} };\n      for jj=1:length(Args)\n          \n          args=Args{jj};\n          \nError(end+1)= err( allml(Z,args{:})  , all(Zf,args{:}) );\n\nError(end+1)= err( anyml(Z,args{:})  , any(Zf,args{:}) );\n\nError(end+1)= err( meanml(Z,args{:})  , mean(Zf,args{:}) );\n\n\n      end\n \n\n        Args={ {1},{2},{3},{4},{5} };\n \n      for jj=1:length(Args)\n          \n          args=Args{jj};        \n        \n          [Z,idx]=maxml(B,[],args{:});\n          [Zf,idxf]=max(Bf,[],args{:});\n          \nError(end+1)= err( Z ,Zf );       \nError(end+1)= err( idx ,idxf );    \n\n      end\n      \nError(end+1)= err( maxml(B,C) , max(Bf,Cf) );      \nError(end+1)= err( maxml(B,Cf) , max(Bf,Cf) );      \nError(end+1)= err( maxml(Bf,C) , max(Bf,Cf) );   \n\n \n      for jj=1:length(Args)\n          \n          args=Args{jj};        \n        \n          [Z,idx]=minml(B,[],args{:});\n          [Zf,idxf]=min(Bf,[],args{:});\n          \nError(end+1)= err( Z ,Zf );       \nError(end+1)= err( idx ,idxf );    \n\n      end\n      \nError(end+1)= err( minml(B,C) , min(Bf,Cf) );      \nError(end+1)= err( minml(B,Cf) , min(Bf,Cf) );      \nError(end+1)= err( minml(Bf,C) , min(Bf,Cf) );  \n\nError(end+1)= err( summl(P,1)  , sum(Pf,1) );\nError(end+1)= err( summl(Q,2)  , sum(Qf,2) );\nError(end+1)= err( summl(P)    , sum(Pf) );\nError(end+1)= err( summl(P,'native')    , sum(Pf,'native') );\nError(end+1)= err( summl(P,3,'double')    , sum(Pf,3,'double') );\nError(end+1)= err( summl(P,4)    , sum(Pf,4) );\nError(end+1)= err( summl(P,5)    , sum(Pf,5) );\n\nError(end+1)= err(catml(3,P,P,P) ,cat(3,Pf,Pf,Pf));\nError(end+1)= err(catml(3,Pf,P) ,cat(3,Pf,Pf));\nError(end+1)= err(catml(3,P,Pf) ,cat(3,Pf,Pf));\n\nError(end+1)= err(catml(4,P,Pf) ,cat(4,Pf,Pf));\nError(end+1)= err(catml(5,P,Pf) ,cat(5,Pf,Pf));\n\n\n\n       N=ndims(Pf)+1;\n       z=ones(1,N);\n\n       \n       for kk=0:N\n\n           idx=nchoosek(1:N,kk);\n           \n           for jj=1:size(idx,1)\n               \n             arg2=z;\n             arg2(idx(jj,:))=2;\n \nError(end+1)= err( circshiftml(P,arg2) , circshift(Pf,arg2) );\nError(end+1)= err( circshiftml(P,arg2-1) , circshift(Pf,arg2-1) );             \nError(end+1)= err( circshiftml(A,arg2) , circshift(Af,arg2) );\nError(end+1)= err( circshiftml(A,arg2-1) , circshift(Af,arg2-1) );             \n\n           end\n       end\n\n              Z=P*0; Zf=full(Z);\n       \nError(end+1)= err( circshiftml(Z,arg2) , circshift(Zf,arg2) );\nError(end+1)= err( circshiftml(Z,arg2-1) , circshift(Zf,arg2-1) );\n\n\n%%%%%%%%%%%%%%%%%%%%%%%END OF TESTS%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nMAX_ERROR=max(Error);\n\nif any(~isfinite(Error)), warning 'There were improper Error values'; keyboard; end\n\ndisp(['Maximum observed error was   ' num2str(MAX_ERROR) ' percent.'])\n\nif nargout, varargout{1}=Error; end\n\nfunction errval=DiscrepancyMeasure(X,Y,TOL,CHECKTYPES)\n\n\n  if Discrepancy(0,Y)\n    errval=Discrepancy(X,Y)/Discrepancy(0,Y)*100; %normalize\n  else\n    errval=Discrepancy(X,Y); \n  end\n  \n \n  \n  isndSparse=@(c) ~isempty(strfind(class(c),'ndSparse'));\n  \n  if CHECKTYPES\n    if ~isndSparse(X),\n       warning(['X is not ndSparse class, but rather class ' class(X)]) \n    end\n  end\n\n  if errval>TOL || ~isfinite(errval), \n      disp ' '; disp 'Discrepancy detected'\n      errval, \n      x=full(X); y=full(Y);\n      keyboard;\n  end \n  \n  \nfunction errval=Discrepancy(X,Y) \n%Primary error measurement function\n\n  fin=@(a) reshape( a(isfinite(a)),[],1);\n  nonfin=@(a) reshape(  a(~isfinite(a))  ,[],1); \n\n  x=full(X); y=full(Y);\n\n  if ( isequal(x,y));\n     errval=0; return\n  elseif xor(isempty(x),isempty(y))\n      errval=1; return\n  end\n  \n  errval= norm( fin(x-y) , inf)+...   \n       ~isequalwithequalnans(nonfin(x),nonfin(y))*...\n       ~isempty([nonfin(x);nonfin(y)])+ ~isequal(size(X),size(Y)); \n\n\n\nfunction out=srand(varargin)\n\n   out=rand(varargin{:})-.5;\n\n\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/ndSparse_G3_2013_03_13/ndstest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5584085008214593}}
{"text": "function [indpeak twfPer indtrough] = peakfinder(twf,fmin,fmax)\n% [indpeak twfPer indtrough] = peakfinder(twf,<fmin>,<fmax>)\n%\n% Finds local peaks in a near-periodic waveform. This fails if the\n% peaks are closer than 1/2 period. twfPer is the period of twf in\n% samples. If the 1st or last peak are less than 90% of the mean of\n% the rest of the peaks, they are exluded. \n%\n% fmin,fmax are constraints on the fundamental frequency and are\n% given in units of items per time point (NOT IN Hz!).\n%\n% $Id: peakfinder.m,v 1.9 2010/05/18 19:31:44 greve Exp $\n\nindpeak = [];\n\nif(nargin < 1 | nargin > 3)\n  fprintf('[indpeak twfPer indtrough] = peakfinder(twf,<fmin>,<fmax>)\\n');\n  return;\nend\n\nNtp = length(twf);\nnn = 1:Ntp;\n\n% detrend - necessary?\nX = fast_polytrendmtx(1,Ntp,1,3);\n%twf = twf - X*(inv(X'*X)*(X'*twf));\n\n% Get major period of waveform\n[fftaxis, deltafreq] = fast_fftaxis(Ntp,1);\nnfft = length(fftaxis);\nnnfft = 1:nfft;\ntwffft = abs(fft(twf-mean(twf)));\nif(exist('fmin','var'))\n  indok = find(fftaxis >= fmin & fftaxis <= fmax);\nelse\n  indok = [1:length(fftaxis)];\nend\n[tmp k] = max(twffft(indok));\ntwfFreq = fftaxis(indok(k));\ntwfPer = 1/twfFreq;\ntwfPerSamp      = round(twfPer);\ntwfHalfPerSamp  = round(twfPerSamp/2);\ntwfQuartPerSamp = round(twfPerSamp/4);\n\n%plot(fftaxis,twffft(nnfft))\n%keyboard\n\n% Assume global peak is a local peak\n[tmp k0] = max(twf);\n%fprintf('global peak at %d %f\\n',k0,k0/25);\n\n% Look ahead, starting at global peak\nindpeak = k0;\nkprev = k0;\nwhile(1)\n  % Find next max by searhing over time starting at 1/2\n  % period beyond the previous max and ending one period\n  % later. This fails if the peaks are closer than 1/2\n  % period.\n  kstart = kprev + twfHalfPerSamp;\n  k = kstart + [0:twfPerSamp-1];\n  indok = find(k < Ntp);\n  if(length(indok) < twfQuartPerSamp) break; end\n  k = k(indok);\n  [tmp mmax] = max(twf(k));\n  kmax = kstart + mmax - 1;\n  indpeak = [indpeak kmax];\n  kprev = kmax;\nend\n\n% Look behind (reverse and look ahead)\ntwfrev = flipud(twf(:));\nk0rev = Ntp - k0 + 1; % DONT = max(twfrev);\nindpeakrev = []; % dont include k0rev here\nkprev = k0rev;\nwhile(1)\n  kstart = kprev + twfHalfPerSamp;\n  k = kstart + [0:twfPerSamp-1];\n  indok = find(k < Ntp);\n  if(length(indok) < twfQuartPerSamp) break; end\n  k = k(indok);\n  [tmp mmax] = max(twfrev(k));\n  kmax = kstart + mmax - 1;\n  indpeakrev = [indpeakrev kmax];\n  kprev = kmax;\nend\n\n% Convert reversed indices to forard indices\nindpeakrevfor = Ntp - indpeakrev + 1;\nindpeak = sort([indpeak indpeakrevfor]);\nnpeaks = length(indpeak);\n\n% Decide whether to eliminate the first peak\n% Compute mean of closest 3 peaks\npeakfirst = twf(indpeak(1));\nindpm = [2:min(4,npeaks)];\npeakmean = mean(twf(indpeak(indpm)));\n% Must be greater than 0.7 times this mean\nif(peakfirst < .7*peakmean)  indpeak = indpeak(2:end); end\n\n% Decide whether to eliminate the last peak\n% Compute mean of closest 3 peaks\npeaklast  = twf(indpeak(end));\nindpm = [max(npeaks-3,1),max(npeaks-1,1)];\npeakmean = mean(twf(indpeak(indpm)));\n% Must be greater than 0.7 times this mean\nif(peaklast  < .7*peakmean)  indpeak = indpeak(1:end-1); end\n\n% Make sure they are unique (why not always?)\nindpeak = unique(indpeak);\n\nnpeaks = length(indpeak);\nindtrough = zeros(size(indpeak));\nfor nthpeak = 1:npeaks\n  i1 = indpeak(nthpeak);\n  if(nthpeak < npeaks)\n    i2 = indpeak(nthpeak+1);\n  else\n    i2 = Ntp;\n  end\n  if(i2 > i1 + 1) i1 = i1 + 1; end\n  [mmin imin] = min(twf(i1:i2));\n  indtrough(nthpeak) = imin+i1-1;\nend\n\nif(0)\nnn = 1:Ntp;\nplot(nn,twf,nn(indpeak),twf(indpeak),'*',nn(indtrough),twf(indtrough),'o');\nfprintf('Period %f\\n',twfPerSamp);\nkeyboard\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/external/freesurfer/peakfinder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5584084972797665}}
{"text": "% VISUALIZEMCMCMARGINALS\n%\n% This function accepts a list of sample lists, each from a different MCMC run.  It then visualizes\n% the estimated marginals for each variable in V over the lifetime of the MCMC run.\n%\n% samples_list - a list of sample lists; each sample list is a m-by-n matrix where m is the\n% number of samples and n is the number of variables in the state of the Markov chain\n%\n% V - an array of variables\n% D - the dimensions of the variables in V\n% F - a list of factors (used in computing likelihoods of each sample)\n% window_size - size of the window over which to aggregate samples to compute the estimated\n%               marginal at a given time\n% ExactMarginals - the exact marginals of V (optional)\n%\n% Copyright (C) Daphne Koller, Stanford University, 2012\n\nfunction VisualizeMCMCMarginals(samples_list, V, D, F, window_size, ExactMarginals, tname)\n\nfor i = 1:length(V)\n    figure;\n    v = V(i);\n    d = D(i);\n    title(['Marginal for Variable ', num2str(v)]);\n    if exist('ExactMarginals') == 1, M = ExactMarginals(i); end;\n    for j = 1:length(samples_list)\n        samples_v = samples_list{j}(:, v);\n        indicators_over_time = zeros(length(samples_v), d);\n        for k = 1:length(samples_v)\n            indicators_over_time(k, samples_v(k)) = 1;\n        end\n\n        % estimated_marginal = cumsum(indicators_over_time, 1);\n        estimated_marginal = [];\n        for k = 1:size(indicators_over_time, 2)\n            estimated_marginal = [estimated_marginal, smooth(indicators_over_time(:, k), window_size)];\n        end\n        % Prune ends\n        estimated_marginal = estimated_marginal(window_size/2:end - window_size/2, :);\n\n\n        estimated_marginal = estimated_marginal ./ ...\n            repmat(sum(estimated_marginal, 2), 1, size(estimated_marginal, 2));\n        hold on;\n        plot(estimated_marginal, '-', 'LineWidth', 2);\n        title(['Est marginals for entry ' num2str(i) ' of samples for ' tname])\n        if exist('M') == 1\n            plot([1; size(estimated_marginal, 1)], [M.val; M.val], '--', 'LineWidth', 3);\n        end\n        set(gcf,'DefaultAxesColorOrder', rand(d, 3));\n    end\nend\n\n% Visualize likelihood of sample at each time step\nall_likelihoods = [];\nfor i = 1:length(samples_list)\n    samples = samples_list{i};\n    likelihoods = [];\n    for j = 1:size(samples, 1)\n        likelihoods = [likelihoods; LogProbOfJointAssignment(F, samples(j, :))];\n    end\n    all_likelihoods = [all_likelihoods, likelihoods];\nend\nfigure;\ntitle('Likelihoods')\nplot(all_likelihoods, '-', 'LineWidth', 2);\n", "meta": {"author": "anhncs", "repo": "Probabilistic-Graphical-Models", "sha": "7fd4ef255db59ecbfe1a134cadbc4be5ca839894", "save_path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models", "path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models/Probabilistic-Graphical-Models-7fd4ef255db59ecbfe1a134cadbc4be5ca839894/5.Approximate Inference/VisualizeMCMCMarginals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.5584084884302696}}
{"text": "function sr=comp_gabreassign(s,tgrad,fgrad,a);\n%COMP_GABREASSIGN  Reassign time-frequency distribution.\n%   Usage:  sr = comp_gabreassign(s,tgrad,fgrad,a);\n%\n%   `comp_gabreassign(s,tgrad,fgrad,a)` will reassign the values of the positive\n%   time-frequency distribution *s* using the instantaneous time and frequency\n%   *fgrad* and *ifdummy*. The lattice is determined by the time shift *a* and\n%   the number of channels deduced from the size of *s*.\n%\n%   See also: gabreassign\n%\n%   References: aufl95\n\n%   AUTHOR : Peter L. S\u00f8ndergaard.\n%   TESTING: OK\n%   REFERENCE: OK\n\n[M,N,W]=size(s);\nL=N*a;\nb=L/M;\n\nfreqpos=fftindex(M);  \ntgrad=bsxfun(@plus,tgrad/b,freqpos);\n\ntimepos=fftindex(N);\nfgrad=bsxfun(@plus,fgrad/a,timepos.');\n\ntgrad=round(tgrad);\nfgrad=round(fgrad);\n\ntgrad=mod(tgrad,M);\nfgrad=mod(fgrad,N);  \n  \nsr=zeros(M,N,W,assert_classname(s,tgrad,fgrad));\n\nfgrad=fgrad+1;\ntgrad=tgrad+1;\n\nfor w=1:W\n    for ii=1:M\n        for jj=1:N      \n            sr(tgrad(ii,jj),fgrad(ii,jj),w) = sr(tgrad(ii,jj),fgrad(ii,jj),w)+s(ii,jj,w);\n        end;\n    end;  \nend;\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_gabreassign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5583168233952975}}
{"text": "function y = perform_curvelet_transform(x,options)\n\n% perform_curvelet_transform - a wrapper to curvlab\n%\n%     M = perform_curvelet_transform(MW,options);\n%\n%   Forward and backward curvelet transform\n%   You must provide options.n (width of the image).\n%\n%   Visit www.curvelab.org for the full code.\n\noptions.null = 0;\nfinest = getoptions(options, 'finest',1)  ; % =1(curv)  =2(wav)\nnbscales = getoptions(options, 'nbscales', 5); % log2(size(M,1))-2;\nnbangles_coarse = getoptions(options, 'nbangles_coarse', 16);\nis_real = getoptions(options, 'is_real', 0);\nn = getoptions(options, 'n', 1,1);\n\nif not(iscell(x))\n    % fwd transform\n    y = fdct_wrapping(x, is_real, finest, nbscales, nbangles_coarse);\nelse\n    y = real( ifdct_wrapping(x, is_real, n,n ) ); \nend\n\n%%\n\nfunction C = fdct_wrapping(x, is_real, finest, nbscales, nbangles_coarse)\n\n% fdct_wrapping.m - Fast Discrete Curvelet Transform via wedge wrapping - Version 1.0\n%\n% Inputs\n%   x           M-by-N matrix\n%\n% Optional Inputs\n%   is_real     Type of the transform\n%                   0: complex-valued curvelets\n%                   1: real-valued curvelets\n%               [default set to 0]\n%   finest      Chooses one of two possibilities for the coefficients at the\n%               finest level:\n%                   1: curvelets\n%                   2: wavelets\n%               [default set to 2]\n%   nbscales    number of scales including the coarsest wavelet level\n%               [default set to ceil(log2(min(M,N)) - 3)]\n%   nbangles_coarse\n%               number of angles at the 2nd coarsest level, minimum 8,\n%               must be a multiple of 4. [default set to 16]\n%\n% Outputs\n%   C           Cell array of curvelet coefficients.\n%               C{j}{l}(k1,k2) is the coefficient at\n%                   - scale j: integer, from finest to coarsest scale,\n%                   - angle l: integer, starts at the top-left corner and\n%                   increases clockwise,\n%                   - position k1,k2: both integers, size varies with j\n%                   and l.\n%               If is_real is 1, there are two types of curvelets,\n%               'cosine' and 'sine'. For a given scale j, the 'cosine'\n%               coefficients are stored in the first two quadrants (low\n%               values of l), the 'sine' coefficients in the last two\n%               quadrants (high values of l).  \n%\n% See also ifdct_wrapping.m, fdct_wrapping_param.m\n%\n% By Laurent Demanet, 2004\n\nX = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)));\n[N1,N2] = size(X);\nif nargin < 2, is_real = 0; end;\nif nargin < 3, finest = 2; end;\nif nargin < 4, nbscales = ceil(log2(min(N1,N2)) - 3); end;\nif nargin < 5, nbangles_coarse = 16; end;\n\n% Initialization: data structure\nnbangles = [1, nbangles_coarse .* 2.^(ceil((nbscales-(nbscales:-1:2))/2))];\nif finest == 2, nbangles(nbscales) = 1; end;\nC = cell(1,nbscales);\nfor j = 1:nbscales\n    C{j} = cell(1,nbangles(j));\nend;\n\n% Loop: pyramidal scale decomposition\nM1 = N1/3;\nM2 = N2/3;\nif finest == 1,\n\n    % Initialization: smooth periodic extension of high frequencies\n    bigN1 = 2*floor(2*M1)+1;\n    bigN2 = 2*floor(2*M2)+1;\n    equiv_index_1 = 1+mod(floor(N1/2)-floor(2*M1)+(1:bigN1)-1,N1);\n    equiv_index_2 = 1+mod(floor(N2/2)-floor(2*M2)+(1:bigN2)-1,N2);\n    X = X(equiv_index_1,equiv_index_2);\n        % Invariant: equiv_index_1(floor(2*M1)+1) == (N1 + 2 - mod(N1,2))/2\n        % is the center in frequency. Same for M2, N2.\n    window_length_1 = floor(2*M1) - floor(M1) - 1 - (mod(N1,3)==0);\n    window_length_2 = floor(2*M2) - floor(M2) - 1 - (mod(N2,3)==0);\n        % Invariant: floor(M1) + floor(2*M1) == N1 - (mod(M1,3)~=0)\n        % Same for M2, N2.\n    coord_1 = 0:(1/window_length_1):1;\n    coord_2 = 0:(1/window_length_2):1;\n    [wl_1,wr_1] = fdct_wrapping_window(coord_1);\n    [wl_2,wr_2] = fdct_wrapping_window(coord_2);\n    lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];\n    if mod(N1,3)==0, lowpass_1 = [0, lowpass_1, 0]; end;\n    lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];\n    if mod(N2,3)==0, lowpass_2 = [0, lowpass_2, 0]; end;\n    lowpass = lowpass_1'*lowpass_2;\n    Xlow = X .* lowpass;\n\n    scales = nbscales:-1:2;\n\nelse\n    \n    M1 = M1/2;\n    M2 = M2/2;\n    window_length_1 = floor(2*M1) - floor(M1) - 1;\n    window_length_2 = floor(2*M2) - floor(M2) - 1;\n    coord_1 = 0:(1/window_length_1):1;\n    coord_2 = 0:(1/window_length_2):1;\n    [wl_1,wr_1] = fdct_wrapping_window(coord_1);\n    [wl_2,wr_2] = fdct_wrapping_window(coord_2);\n    lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];\n    lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];\n    lowpass = lowpass_1'*lowpass_2;\n    hipass = sqrt(1 - lowpass.^2);\n    Xlow_index_1 = ((-floor(2*M1)):floor(2*M1)) + ceil((N1+1)/2);\n    Xlow_index_2 = ((-floor(2*M2)):floor(2*M2)) + ceil((N2+1)/2);\n    Xlow = X(Xlow_index_1, Xlow_index_2) .* lowpass;\n    Xhi = X;\n    Xhi(Xlow_index_1, Xlow_index_2) = Xhi(Xlow_index_1, Xlow_index_2) .* hipass;\n    C{nbscales}{1} = fftshift(ifft2(ifftshift(Xhi)))*sqrt(prod(size(Xhi)));\n    if is_real, C{nbscales}{1} = real(C{nbscales}{1}); end;\n    \n    scales = (nbscales-1):-1:2;\n\nend;\nfor j = scales,\n\n    M1 = M1/2;\n    M2 = M2/2;\n    window_length_1 = floor(2*M1) - floor(M1) - 1;\n    window_length_2 = floor(2*M2) - floor(M2) - 1;\n    coord_1 = 0:(1/window_length_1):1;\n    coord_2 = 0:(1/window_length_2):1;\n    [wl_1,wr_1] = fdct_wrapping_window(coord_1);\n    [wl_2,wr_2] = fdct_wrapping_window(coord_2);\n    lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];\n    lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];\n    lowpass = lowpass_1'*lowpass_2;\n    hipass = sqrt(1 - lowpass.^2);\n    Xhi = Xlow;                 % size is 2*floor(4*M1)+1 - by - 2*floor(4*M2)+1\n    Xlow_index_1 = ((-floor(2*M1)):floor(2*M1)) + floor(4*M1) + 1;\n    Xlow_index_2 = ((-floor(2*M2)):floor(2*M2)) + floor(4*M2) + 1;\n    Xlow = Xlow(Xlow_index_1, Xlow_index_2);\n    Xhi(Xlow_index_1, Xlow_index_2) = Xlow .* hipass;\n    Xlow = Xlow .* lowpass;     % size is 2*floor(2*M1)+1 - by - 2*floor(2*M2)+1\n    \n    % Loop: angular decomposition\n    l = 0;\n    nbquadrants = 2 + 2*(~is_real);\n    nbangles_perquad = nbangles(j)/4;\n    for quadrant = 1:nbquadrants\n        M_horiz = M2 * (mod(quadrant,2)==1) + M1 * (mod(quadrant,2)==0);\n        M_vert = M1 * (mod(quadrant,2)==1) + M2 * (mod(quadrant,2)==0);\n        if mod(nbangles_perquad,2),\n            wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);\n            wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;\n            wedge_ticks = [wedge_ticks_left, wedge_ticks_right(end:-1:1)];\n        else\n            wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);\n            wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;\n            wedge_ticks = [wedge_ticks_left, wedge_ticks_right((end-1):-1:1)];\n        end;\n        wedge_endpoints = wedge_ticks(2:2:(end-1));         % integers\n        wedge_midpoints = (wedge_endpoints(1:(end-1)) + wedge_endpoints(2:end))/2;\n                % integers or half-integers\n        \n        % Left corner wedge\n        l = l+1;\n        first_wedge_endpoint_vert = round(2*floor(4*M_vert)/(2*nbangles_perquad) + 1);\n        length_corner_wedge = floor(4*M_vert) - floor(M_vert) + ceil(first_wedge_endpoint_vert/4);\n        Y_corner = 1:length_corner_wedge;\n        [XX,YY] = meshgrid(1:(2*floor(4*M_horiz)+1),Y_corner);\n        width_wedge = wedge_endpoints(2) + wedge_endpoints(1) - 1;\n        slope_wedge = (floor(4*M_horiz) + 1 - wedge_endpoints(1))/floor(4*M_vert);\n        left_line = round(2 - wedge_endpoints(1) + slope_wedge*(Y_corner - 1));\n                                                            % integers\n        [wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));\n        first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...\n            mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));\n        first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...\n            mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));\n                % Coordinates of the top-left corner of the wedge wrapped\n                % around the origin. Some subtleties when the wedge is\n                % even-sized because of the forthcoming 90 degrees rotation\n        for row = Y_corner\n            cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n            admissible_cols = round(1/2*(cols+1+abs(cols-1)));\n            new_row = 1 + mod(row - first_row, length_corner_wedge);\n            wrapped_data(new_row,:) = Xhi(row,admissible_cols) .* (cols > 0);\n            wrapped_XX(new_row,:) = XX(row,admissible_cols);\n            wrapped_YY(new_row,:) = YY(row,admissible_cols);\n        end;\n        slope_wedge_right = (floor(4*M_horiz)+1 - wedge_midpoints(1))/floor(4*M_vert);\n        mid_line_right = wedge_midpoints(1) + slope_wedge_right*(wrapped_YY - 1);\n                % not integers in general\n        coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(2) - wedge_endpoints(1)) * ...\n            (wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);\n        C2 = 1/(1/(2*(floor(4*M_horiz))/(wedge_endpoints(1) - 1) - 1) + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));\n        C1 = C2 / (2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1);\n        wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) = ...\n            wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) + 1;\n        coord_corner = C1 + C2 * ((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert))) ./ ...\n            (2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert))));\n        wl_left = fdct_wrapping_window(coord_corner);\n        [wl_right,wr_right] = fdct_wrapping_window(coord_right);\n        wrapped_data = wrapped_data .* (wl_left .* wr_right);\n\n        switch is_real\n            case 0\n                wrapped_data = rot90(wrapped_data,-(quadrant-1));\n                C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n            case 1\n                wrapped_data = rot90(wrapped_data,-(quadrant-1));\n                x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n                C{j}{l} = sqrt(2)*real(x);\n                C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);\n        end;\n                \n        % Regular wedges\n        length_wedge = floor(4*M_vert) - floor(M_vert);\n        Y = 1:length_wedge;\n        first_row = floor(4*M_vert)+2-ceil((length_wedge+1)/2)+...\n            mod(length_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));\n        for subl = 2:(nbangles_perquad-1);\n            l = l+1;\n            width_wedge = wedge_endpoints(subl+1) - wedge_endpoints(subl-1) + 1;\n            slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(subl))/floor(4*M_vert);\n            left_line = round(wedge_endpoints(subl-1) + slope_wedge*(Y - 1));\n            [wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_wedge,width_wedge));\n            first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...\n                mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));\n            for row = Y\n                cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n                new_row = 1 + mod(row - first_row, length_wedge);\n                wrapped_data(new_row,:) = Xhi(row,cols);\n                wrapped_XX(new_row,:) = XX(row,cols);\n                wrapped_YY(new_row,:) = YY(row,cols);             \n            end;\n            slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(subl-1))/floor(4*M_vert);\n            mid_line_left = wedge_midpoints(subl-1) + slope_wedge_left*(wrapped_YY - 1);\n            coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl) - wedge_endpoints(subl-1)) * ...\n                (wrapped_XX - mid_line_left)./(floor(4*M_vert)+1 - wrapped_YY);\n            slope_wedge_right = ((floor(4*M_horiz)+1) - wedge_midpoints(subl))/floor(4*M_vert);\n            mid_line_right = wedge_midpoints(subl) + slope_wedge_right*(wrapped_YY - 1);\n            coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl+1) - wedge_endpoints(subl)) * ...\n                (wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);\n            wl_left = fdct_wrapping_window(coord_left);\n            [wl_right,wr_right] = fdct_wrapping_window(coord_right);\n            wrapped_data = wrapped_data .* (wl_left .* wr_right);\n            switch is_real\n                case 0\n                    wrapped_data = rot90(wrapped_data,-(quadrant-1));\n                    C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n                case 1\n                    wrapped_data = rot90(wrapped_data,-(quadrant-1));\n                    x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n                    C{j}{l} = sqrt(2)*real(x);\n                    C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);\n            end;\n        end;\n\n        % Right corner wedge\n        l = l+1;\n        width_wedge = 4*floor(4*M_horiz) + 3 - wedge_endpoints(end) - wedge_endpoints(end-1);\n        slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(end))/floor(4*M_vert);\n        left_line = round(wedge_endpoints(end-1) + slope_wedge*(Y_corner - 1));\n        [wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));\n        first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...\n            mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));\n        first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...\n            mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));\n        for row = Y_corner\n            cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n            admissible_cols = round(1/2*(cols+2*floor(4*M_horiz)+1-abs(cols-(2*floor(4*M_horiz)+1))));\n            new_row = 1 + mod(row - first_row, length_corner_wedge);\n            wrapped_data(new_row,:) = Xhi(row,admissible_cols) .* (cols <= (2*floor(4*M_horiz)+1));\n            wrapped_XX(new_row,:) = XX(row,admissible_cols);\n            wrapped_YY(new_row,:) = YY(row,admissible_cols);\n        end;\n        slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(end))/floor(4*M_vert);\n        mid_line_left = wedge_midpoints(end) + slope_wedge_left*(wrapped_YY - 1);\n        coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(end) - wedge_endpoints(end-1)) * ...\n            (wrapped_XX - mid_line_left)./(floor(4*M_vert) + 1 - wrapped_YY);\n        C2 = -1/(2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1 + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));\n        C1 = -C2 * (2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1);\n        wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY - 1)/floor(4*M_vert)) = ...\n            wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY - 1)/floor(4*M_vert)) - 1;\n        coord_corner = C1 + C2 * (2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert)))) ./ ...\n            ((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert)));\n        wl_left = fdct_wrapping_window(coord_left);\n        [wl_right,wr_right] = fdct_wrapping_window(coord_corner);\n\n        wrapped_data = wrapped_data .* (wl_left .* wr_right);\n        switch is_real\n            case 0\n                wrapped_data = rot90(wrapped_data,-(quadrant-1));\n                C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n            case 1\n                wrapped_data = rot90(wrapped_data,-(quadrant-1));\n                x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n                C{j}{l} = sqrt(2)*real(x);\n                C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);\n        end;\n\n        if quadrant < nbquadrants, Xhi = rot90(Xhi); end;\n    end;\nend;\n\n% Coarsest wavelet level\nC{1}{1} = fftshift(ifft2(ifftshift(Xlow)))*sqrt(prod(size(Xlow)));\nif is_real == 1,\n    C{1}{1} = real(C{1}{1});\nend;\n\n\nfunction x = ifdct_wrapping(C, is_real, M, N)\n\n% ifdct_wrapping.m - Inverse Fast Discrete Curvelet Transform via wedge wrapping - Version 1.0\n% This is in fact the adjoint, also the pseudo-inverse\n%\n% Inputs\n%   C           Cell array containing curvelet coefficients (see\n%               description in fdct_wrapping.m)\n%   is_real     As used in fdct_wrapping.m\n%   M, N        Size of the image to be recovered (not necessary if finest\n%               = 2)\n%\n% Outputs\n%   x           M-by-N matrix\n%\n% See also fdct_wrapping.m\n%\n% By Laurent Demanet, 2004\n\n% Initialization\nnbscales = length(C);\nnbangles_coarse = length(C{2});\nnbangles = [1, nbangles_coarse .* 2.^(ceil((nbscales-(nbscales:-1:2))/2))];\nif length(C{end}) == 1, finest = 2; else finest = 1; end;\nif finest == 2, nbangles(nbscales) = 1; end;\nif nargin < 2, is_real = 0; end;\nif nargin < 4,\n    if finest == 1, error('Syntax: IFCT_wrapping(C,M,N) where the matrix to be recovered is M-by-N'); end;\n    [N1,N2] = size(C{end}{1});\nelse\n    N1 = M;\n    N2 = N;\nend;\n\nM1 = N1/3;\nM2 = N2/3;\n\nif finest == 1;\n    \n    bigN1 = 2*floor(2*M1)+1;\n    bigN2 = 2*floor(2*M2)+1;\n    X = zeros(bigN1,bigN2);\n\n    % Initialization: preparing the lowpass filter at finest scale\n    window_length_1 = floor(2*M1) - floor(M1) - 1 - (mod(N1,3)==0);\n    window_length_2 = floor(2*M2) - floor(M2) - 1 - (mod(N2,3)==0);\n    coord_1 = 0:(1/window_length_1):1;\n    coord_2 = 0:(1/window_length_2):1;\n    [wl_1,wr_1] = fdct_wrapping_window(coord_1);\n    [wl_2,wr_2] = fdct_wrapping_window(coord_2);\n    lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];\n    if mod(N1,3)==0, lowpass_1 = [0, lowpass_1, 0]; end;\n    lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];\n    if mod(N2,3)==0, lowpass_2 = [0, lowpass_2, 0]; end;\n    lowpass = lowpass_1'*lowpass_2;\n\n    scales = nbscales:-1:2;\n   \nelse\n\n    M1 = M1/2;\n    M2 = M2/2;\n    \n    bigN1 = 2*floor(2*M1)+1;\n    bigN2 = 2*floor(2*M2)+1;\n    X = zeros(bigN1,bigN2);\n    \n    window_length_1 = floor(2*M1) - floor(M1) - 1;\n    window_length_2 = floor(2*M2) - floor(M2) - 1;\n    coord_1 = 0:(1/window_length_1):1;\n    coord_2 = 0:(1/window_length_2):1;\n    [wl_1,wr_1] = fdct_wrapping_window(coord_1);\n    [wl_2,wr_2] = fdct_wrapping_window(coord_2);\n    lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];\n    lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];\n    lowpass = lowpass_1'*lowpass_2;\n    hipass_finest = sqrt(1 - lowpass.^2);\n    \n    scales = (nbscales-1):-1:2;\n    \nend;\n\n% Loop: pyramidal reconstruction\n\nXj_topleft_1 = 1;\nXj_topleft_2 = 1;\nfor j = scales,\n\n    M1 = M1/2;\n    M2 = M2/2;\n    window_length_1 = floor(2*M1) - floor(M1) - 1;\n    window_length_2 = floor(2*M2) - floor(M2) - 1;\n    coord_1 = 0:(1/window_length_1):1;\n    coord_2 = 0:(1/window_length_2):1;\n    [wl_1,wr_1] = fdct_wrapping_window(coord_1);\n    [wl_2,wr_2] = fdct_wrapping_window(coord_2);\n    lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];\n    lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];\n    lowpass_next = lowpass_1'*lowpass_2;\n    hipass = sqrt(1 - lowpass_next.^2);\n    Xj = zeros(2*floor(4*M1)+1,2*floor(4*M2)+1);\n    \n    % Loop: angles\n    l = 0;\n    nbquadrants = 2 + 2*(~is_real);\n    nbangles_perquad = nbangles(j)/4;\n    for quadrant = 1:nbquadrants\n        \n        M_horiz = M2 * (mod(quadrant,2)==1) + M1 * (mod(quadrant,2)==0);\n        M_vert = M1 * (mod(quadrant,2)==1) + M2 * (mod(quadrant,2)==0);\n        if mod(nbangles_perquad,2),\n            wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);\n            wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;\n            wedge_ticks = [wedge_ticks_left, wedge_ticks_right(end:-1:1)];\n        else\n            wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);\n            wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;\n            wedge_ticks = [wedge_ticks_left, wedge_ticks_right((end-1):-1:1)];\n        end;\n        wedge_endpoints = wedge_ticks(2:2:(end-1));         % integers\n        wedge_midpoints = (wedge_endpoints(1:(end-1)) + wedge_endpoints(2:end))/2;\n        \n        % Left corner wedge\n        \n        l = l+1;\n        first_wedge_endpoint_vert = round(2*floor(4*M_vert)/(2*nbangles_perquad) + 1);\n        length_corner_wedge = floor(4*M_vert) - floor(M_vert) + ceil(first_wedge_endpoint_vert/4);\n        Y_corner = 1:length_corner_wedge;\n        [XX,YY] = meshgrid(1:(2*floor(4*M_horiz)+1),Y_corner);\n        width_wedge = wedge_endpoints(2) + wedge_endpoints(1) - 1;\n        slope_wedge = (floor(4*M_horiz) + 1 - wedge_endpoints(1))/floor(4*M_vert);\n        left_line = round(2 - wedge_endpoints(1) + slope_wedge*(Y_corner - 1));\n        [wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));\n        first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...\n            mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));\n        first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...\n            mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));\n        \n        for row = Y_corner\n            cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n            new_row = 1 + mod(row - first_row, length_corner_wedge);\n            admissible_cols = round(1/2*(cols+1+abs(cols-1)));\n            wrapped_XX(new_row,:) = XX(row,admissible_cols);\n            wrapped_YY(new_row,:) = YY(row,admissible_cols);\n        end;\n\n        slope_wedge_right = (floor(4*M_horiz)+1 - wedge_midpoints(1))/floor(4*M_vert);\n        mid_line_right = wedge_midpoints(1) + slope_wedge_right*(wrapped_YY - 1);\n                                                            % not integers\n                                                            % in general\n        coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(2) - wedge_endpoints(1)) * ...\n            (wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);\n        C2 = 1/(1/(2*(floor(4*M_horiz))/(wedge_endpoints(1) - 1) - 1) + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));\n        C1 = C2 / (2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1);\n        wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) = ...\n            wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) + 1;\n        coord_corner = C1 + C2 * ((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert))) ./ ...\n            (2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert))));\n        wl_left = fdct_wrapping_window(coord_corner);\n        [wl_right,wr_right] = fdct_wrapping_window(coord_right);\n        switch is_real\n         case 0\n          wrapped_data = fftshift(fft2(ifftshift(C{j}{l})))/sqrt(prod(size(C{j}{l})));\n          wrapped_data = rot90(wrapped_data,(quadrant-1));\n         case 1\n          x = C{j}{l} + sqrt(-1)*C{j}{l+nbangles(j)/2};\n          wrapped_data = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)))/sqrt(2);\n          wrapped_data = rot90(wrapped_data,(quadrant-1));\n        end;\n        wrapped_data = wrapped_data .* (wl_left .* wr_right);\n \n        % Unwrapping data\n        for row = Y_corner\n            cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n            admissible_cols = round(1/2*(cols+1+abs(cols-1)));\n            new_row = 1 + mod(row - first_row, length_corner_wedge);\n            Xj(row,admissible_cols) = Xj(row,admissible_cols) + wrapped_data(new_row,:);\n                                % We use the following property: in an assignment\n                                % A(B) = C where B and C are vectors, if\n                                % some value x repeats in B, then the\n                                % last occurrence of x is the one\n                                % corresponding to the eventual assignment.\n        end;\n\n        % Regular wedges\n        length_wedge = floor(4*M_vert) - floor(M_vert);\n        Y = 1:length_wedge;\n        first_row = floor(4*M_vert)+2-ceil((length_wedge+1)/2)+...\n            mod(length_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));\n        for subl = 2:(nbangles_perquad-1);\n            l = l+1;\n            width_wedge = wedge_endpoints(subl+1) - wedge_endpoints(subl-1) + 1;\n            slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(subl))/floor(4*M_vert);\n            left_line = round(wedge_endpoints(subl-1) + slope_wedge*(Y - 1));\n            [wrapped_XX, wrapped_YY] = deal(zeros(length_wedge,width_wedge));\n            first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...\n                mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));\n            for row = Y\n                cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n                new_row = 1 + mod(row - first_row, length_wedge);\n                wrapped_XX(new_row,:) = XX(row,cols);\n                wrapped_YY(new_row,:) = YY(row,cols);\n            end;\n            slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(subl-1))/floor(4*M_vert);\n            mid_line_left = wedge_midpoints(subl-1) + slope_wedge_left*(wrapped_YY - 1);\n            coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl) - wedge_endpoints(subl-1)) * ...\n                (wrapped_XX - mid_line_left)./(floor(4*M_vert)+1 - wrapped_YY);\n            slope_wedge_right = ((floor(4*M_horiz)+1) - wedge_midpoints(subl))/floor(4*M_vert);\n            mid_line_right = wedge_midpoints(subl) + slope_wedge_right*(wrapped_YY - 1);\n            coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl+1) - wedge_endpoints(subl)) * ...\n                (wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);\n            wl_left = fdct_wrapping_window(coord_left);\n            [wl_right,wr_right] = fdct_wrapping_window(coord_right);\n            switch is_real\n             case 0\n              wrapped_data = fftshift(fft2(ifftshift(C{j}{l})))/sqrt(prod(size(C{j}{l})));\n              wrapped_data = rot90(wrapped_data,(quadrant-1));\n             case 1\n              x = C{j}{l} + sqrt(-1)*C{j}{l+nbangles(j)/2};\n              wrapped_data = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)))/sqrt(2);\n              wrapped_data = rot90(wrapped_data,(quadrant-1));\n            end;\n            wrapped_data = wrapped_data .* (wl_left .* wr_right);\n            \n            % Unwrapping data\n            for row = Y\n                cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n                new_row = 1 + mod(row - first_row, length_wedge);\n                Xj(row,cols) = Xj(row,cols) + wrapped_data(new_row,:);\n            end;\n\n        end;    % for subl\n        \n        % Right corner wedge\n        l = l+1;\n        width_wedge = 4*floor(4*M_horiz) + 3 - wedge_endpoints(end) - wedge_endpoints(end-1);\n        slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(end))/floor(4*M_vert);\n        left_line = round(wedge_endpoints(end-1) + slope_wedge*(Y_corner - 1));\n        [wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));\n        first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...\n            mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));\n        first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...\n            mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));\n        \n        for row = Y_corner\n            cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n            admissible_cols = round(1/2*(cols+2*floor(4*M_horiz)+1-abs(cols-(2*floor(4*M_horiz)+1))));\n            new_row = 1 + mod(row - first_row, length_corner_wedge);\n            wrapped_XX(new_row,:) = XX(row,admissible_cols);\n            wrapped_YY(new_row,:) = YY(row,admissible_cols);        \n        end;\n        YY = Y_corner'*ones(1,width_wedge);\n        slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(end))/floor(4*M_vert);\n        mid_line_left = wedge_midpoints(end) + slope_wedge_left*(wrapped_YY - 1);\n        coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(end) - wedge_endpoints(end-1)) * ...\n            (wrapped_XX - mid_line_left)./(floor(4*M_vert)+1 - wrapped_YY);\n        C2 = -1/(2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1 + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));\n        C1 = -C2 * (2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1);\n        wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY-1)/floor(4*M_vert)) = ...\n            wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY-1)/floor(4*M_vert)) - 1;\n        coord_corner = C1 + C2 * (2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert)))) ./ ...\n            ((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert)));\n        wl_left = fdct_wrapping_window(coord_left);\n        [wl_right,wr_right] = fdct_wrapping_window(coord_corner);\n        switch is_real\n         case 0\n          wrapped_data = fftshift(fft2(ifftshift(C{j}{l})))/sqrt(prod(size(C{j}{l})));\n          wrapped_data = rot90(wrapped_data,(quadrant-1));\n         case 1\n          x = C{j}{l} + sqrt(-1)*C{j}{l+nbangles(j)/2};\n          wrapped_data = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)))/sqrt(2);\n          wrapped_data = rot90(wrapped_data,(quadrant-1));\n        end;\n        wrapped_data = wrapped_data .* (wl_left .* wr_right);\n        \n         % Unwrapping data\n        for row = Y_corner\n            cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n            admissible_cols = round(1/2*(cols+2*floor(4*M_horiz)+1-abs(cols-(2*floor(4*M_horiz)+1))));\n            new_row = 1 + mod(row - first_row, length_corner_wedge);\n            Xj(row,fliplr(admissible_cols)) = Xj(row,fliplr(admissible_cols)) + wrapped_data(new_row,end:-1:1);\n                                % We use the following property: in an assignment\n                                % A(B) = C where B and C are vectors, if\n                                % some value x repeats in B, then the\n                                % last occurrence of x is the one\n                                % corresponding to the eventual assignment.\n        end;\n\n        Xj = rot90(Xj);\n        \n    end;    % for quadrant\n    \n    Xj = Xj .* lowpass;\n    Xj_index1 = ((-floor(2*M1)):floor(2*M1)) + floor(4*M1) + 1;\n    Xj_index2 = ((-floor(2*M2)):floor(2*M2)) + floor(4*M2) + 1;\n    Xj(Xj_index1, Xj_index2) = Xj(Xj_index1, Xj_index2) .* hipass;\n    \n    loc_1 = Xj_topleft_1 + (0:(2*floor(4*M1)));\n    loc_2 = Xj_topleft_2 + (0:(2*floor(4*M2)));\n    X(loc_1,loc_2) = X(loc_1,loc_2) + Xj;\n\n    % Preparing for loop reentry or exit\n    \n    Xj_topleft_1 = Xj_topleft_1 + floor(4*M1) - floor(2*M1);\n    Xj_topleft_2 = Xj_topleft_2 + floor(4*M2) - floor(2*M2);\n    \n    lowpass = lowpass_next;\n    \nend;    % for j\n\nif is_real\n    Y = X;\n    X = rot90(X,2);\n    X = X + conj(Y);\nend\n    \n% Coarsest wavelet level\nM1 = M1/2;\nM2 = M2/2;\nXj = fftshift(fft2(ifftshift(C{1}{1})))/sqrt(prod(size(C{1}{1})));\nloc_1 = Xj_topleft_1 + (0:(2*floor(4*M1)));\nloc_2 = Xj_topleft_2 + (0:(2*floor(4*M2)));\nX(loc_1,loc_2) = X(loc_1,loc_2) + Xj .* lowpass;\n\n% Finest level\nM1 = N1/3;\nM2 = N2/3;\nif finest == 1,\n\n    % Folding back onto N1-by-N2 matrix\n    shift_1 = floor(2*M1)-floor(N1/2);\n    shift_2 = floor(2*M2)-floor(N2/2);\n    Y = X(:,(1:N2)+shift_2);\n    Y(:,N2-shift_2+(1:shift_2)) = Y(:,N2-shift_2+(1:shift_2)) + X(:,1:shift_2);\n    Y(:,1:shift_2) = Y(:,1:shift_2) + X(:,N2+shift_2+(1:shift_2));\n    X = Y((1:N1)+shift_1,:);\n    X(N1-shift_1+(1:shift_1),:) = X(N1-shift_1+(1:shift_1),:) + Y(1:shift_1,:);\n    X(1:shift_1,:) = X(1:shift_1,:) + Y(N1+shift_1+(1:shift_1),:);\n    \nelse\n    \n    % Extension to a N1-by-N2 matrix\n    Y = fftshift(fft2(ifftshift(C{nbscales}{1})))/sqrt(prod(size(C{nbscales}{1})));\n    X_topleft_1 = ceil((N1+1)/2) - floor(M1);\n    X_topleft_2 = ceil((N2+1)/2) - floor(M2);\n    loc_1 = X_topleft_1 + (0:(2*floor(M1)));\n    loc_2 = X_topleft_2 + (0:(2*floor(M2)));\n    Y(loc_1,loc_2) = Y(loc_1,loc_2) .* hipass_finest + X;\n    X = Y;\n    \nend;\n\nx = fftshift(ifft2(ifftshift(X)))*sqrt(prod(size(X)));\nif is_real, x = real(x); end;\n\n\nfunction [wl,wr] = fdct_wrapping_window(x)\n\n% fdct_wrapping_window.m - Creates the two halves of a C^inf compactly supported window\n%\n% Inputs\n%   x       vector or matrix of abscissae, the relevant ones from 0 to 1\n%\n% Outputs\n%   wl,wr   vector or matrix containing samples of the left, resp. right\n%           half of the window\n%\n% Used at least in fdct_wrapping.m and ifdct_wrapping.m\n%\n% By Laurent Demanet, 2004\n\nwr = zeros(size(x));\nwl = zeros(size(x));\nx(abs(x) < 2^-52) = 0;\nwr((x > 0) & (x < 1)) = exp(1-1./(1-exp(1-1./x((x > 0) & (x < 1)))));\nwr(x <= 0) = 1;\nwl((x > 0) & (x < 1)) = exp(1-1./(1-exp(1-1./(1-x((x > 0) & (x < 1))))));\nwl(x >= 1) = 1;\nnormalization = sqrt(wl.^2 + wr.^2);\nwr = wr ./ normalization;\nwl = wl ./ normalization;\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/perform_curvelet_transform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5583168075929172}}
{"text": " function x = nufft2_adj(X, st)\n%function x = nufft2_adj(X, st)\n%\tSUPERCEDED BY nufft_adj.m\n%\tApply adjoint of 2D NUFFT to vector(s) X\n%\tin:\tX\t[M,L]\n%\t\tst\t\tstructure precomputed by nufft2_init()\n%\tout:\tx\t[N1,N2,L]\n%\n%\tCopyright 2001-9-17\tJeff Fessler\tThe University of Michigan\n\n%\n%\tif no arguments, then run a simple test\n%\nif nargin < 1\n\thelp(mfilename)\n\n\tN1 = 4;\n\tN2 = 8;\n\tn_shift = [2.7 3.1];\t% random shifts to stress it\n\to1 = 2 * pi * [0.0 0.1 0.3 0.4 0.7 0.9]';\n\to2 = flipud(o1);\n\tst = nufft2_init([o1 o2], N1, N2, 4, 6, 2*N1, 2*N2, n_shift, 0, 'best');\n\n\tM = length(o1);\n\tA = zeros(M, N1*N2);\n\tfor n1=1:N1\n\t\tfor n2=1:N2\n\t\t\tx = zeros(N1,N2); x(n1,n2) = 1;\n\t\t\tjj = n1 + (n2-1) * N1;\n\t\t\tA(:,jj) = nufft2(x, st);\n\t\tend\n\tend\n\n\tAa = zeros(N1*N2, M);\n\tfor ii=1:M\n\t\ty = zeros(M,1); y(ii,1) = 1;\n\t\tAa(:,ii) = col(nufft2_adj(y, st));\n\tend\n\n\tprintf('max %% = %g', max_percent_diff(A,Aa'))\n\tclear x\nreturn\nend\n\n%\textract attributes from structure\nK1 = st.K1;\nK2 = st.K2;\nif size(X,1) ~= st.M, error size, end\n\n%\n%\tadjoint of interpolator using precomputed sparse matrix\n%\nXk = full(st.p' * X);\t\t\t% [K1*K2,L]\nXk = reshape(Xk, [K1 K2 size(X,2)]);\t% [K1,K2,L]\n\nx = K1 * K2 * ifft2(Xk);\t\t% [K1,K2,L]\n\n% eliminate zero padding from ends\nx = x(1:st.N1,1:st.N2,:);\t\t% [N1,N2,L]\n\nif ndims(x) == 2\n\tx = x .* st.sn;\nelse\n\terror '3d not done'\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/archive/nufft2_adj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5583168038146975}}
{"text": "function [ r, z, c, s ] = zchex ( r, ldr, p, k, l, z, ldz, nz, job )\n\n%*****************************************************************************80\n%\n%% ZCHEX updates a Cholesky factorization.\n%\n%  Discussion:\n%\n%    ZCHEX updates a Cholesky factorization\n%\n%      A = hermitian(R) * R\n%\n%    of a positive definite matrix A of order P under diagonal\n%    permutations of the form\n%\n%      E' * A * E\n%\n%    where E is a permutation matrix.  Specifically, given\n%    an upper triangular matrix R and a permutation matrix\n%    E (which is specified by K, L, and JOB), ZCHEX determines\n%    a unitary matrix U such that\n%\n%      U * R * E = RR,\n%\n%    where RR is upper triangular.  At the user's option, the\n%    transformation U will be multiplied into the array Z.\n%\n%    If A = hermitian(X)*X, so that R is the triangular part of the\n%    QR factorization of X, then RR is the triangular part of the\n%    QR factorization of X * E, that is, X with its columns permuted.\n%\n%    For a less terse description of what ZCHEX does and how\n%    it may be applied, see the LINPACK guide.\n%\n%    The matrix Q is determined as the product U(L-K)*...*U(1)\n%    of plane rotations of the form\n%\n%      (    C(I)       S(I) )\n%      (                    ) ,\n%      ( -conj(S(i))  C(I) )\n%\n%    where C(I) is real, the rows these rotations operate on\n%    are described below.\n%\n%    There are two types of permutations, which are determined\n%    by the value of job.\n%\n%    JOB = 1, right circular shift:\n%    The columns are rearranged in the following order.\n%\n%      1, ..., K-1, L, K, K+1, ..., L-1, L+1, ..., P.\n%\n%    U is the product of L-K rotations U(I), where U(I)\n%    acts in the (L-I,L-I+1)-plane.\n%\n%    JOB = 2, left circular shift:\n%    The columns are rearranged in the following order\n%\n%      1, ..., K-1, K+1, K+2, ..., L, L, L+1, ..., P.\n%\n%    U is the product of L-K rotations U(I), where U(I)\n%    acts in the (K+I-1,K+I)-plane.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 May 2007\n%\n%  Author:\n%\n%    MATLAB version by John Burkardt\n%\n%  Reference:\n%\n%    Jack Dongarra, Cleve Moler, Jim Bunch and 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%\n%  Parameters:\n%\n%    Input, complex R(LDR,P); the upper triangular factor that is to be updated.\n%    Elements below the diagonal are not referenced.\n%\n%    Input, integer LDR, the leading dimension of R, which is at least P.\n%\n%    Input, integer P, the order of the matrix.\n%\n%    Input, integer K, the first column to be permuted.\n%\n%    Input, integer L, the last column to be permuted.\n%    L must be strictly greater than K.\n%\n%    Input, complex Z(LDZ,NZ), an array of NZ P-vectors into\n%    which the transformation U is multiplied.\n%\n%    Input, integer LDZ, the leading dimension of Z, which must\n%    be at least P.\n%\n%    Input, integer NZ, the number of columns of the matrix Z.\n%\n%    Input, integer JOB, determines the type of permutation.\n%    1, right circular shift.\n%    2, left circular shift.\n%\n%    Output, complex R(LDR,P), the updated factor.\n%\n%    Output, complex Z(LDZ,NZ), the updated matrix.  Z is not referenced\n%    if NZ = 0.\n%\n%    Output, real C(P), the cosines of the transforming rotations.\n%\n%    Output, complex S(P), the sines of the transforming rotations.\n%\n  if ( job == 1 )\n%\n%  Right circular shift.\n%\n%  Reorder the columns.\n%\n    for i = 1 : l\n      ii = l - i + 1;\n      s(i) = r(ii,l);\n    end\n\n    for jj = k : l - 1\n      j = l - 1 - jj + k;\n      r(1:j,j+1) = r(1:j,j);\n      r(j+1,j+1) = 0.0;\n    end\n\n    for i = 1 : k - 1\n      ii = l - i + 1;\n      r(i,k) = s(ii);\n    end\n%\n%  Calculate the rotations.\n%\n    t = s(1);\n    for i = 1 : l - k\n      [ c(i), s(i), s(i+1) ] = zrotg ( s(i+1), t );\n      t = s(i+1);\n    end\n\n    r(k,k) = t;\n    for j = k+1 : p\n      il = max ( 1, l - j + 1 );\n      for ii = il : l - k\n        i = l - ii;\n        t = c(ii) * r(i,j) + s(ii) * r(i+1,j);\n        r(i+1,j) = c(ii) * r(i+1,j) - conj ( s(ii) ) * r(i,j);\n        r(i,j) = t;\n      end\n    end\n%\n%  If required, apply the transformations to Z.\n%\n    for j = 1 : nz\n      for ii = 1 : l - k\n        i = l - ii;\n        t = c(ii) * z(i,j) + s(ii) * z(i+1,j);\n        z(i+1,j) = c(ii) * z(i+1,j) - conj ( s(ii) ) * z(i,j);\n        z(i,j) = t;\n      end\n    end\n\n  else\n%\n%  Left circular shift.\n%\n%  Reorder the columns.\n%\n    for i = 1 : k\n      ii = l - k + i;\n      s(ii) = r(i,k);\n    end\n\n    for j = k : l - 1\n      r(1:j,j) = r(1:j,j+1);\n      jj = j - k + 1;\n      s(jj) = r(j+1,j+1);\n    end\n\n    for i = 1 : k\n      ii = l - k + i;\n      r(i,l) = s(ii);\n    end\n\n    r(k+1:l,l) = 0.0;\n%\n%  Reduction loop.\n%\n    for j = k : p\n%\n%  Apply the rotations.\n%\n      if ( j ~= k )\n        iu = min ( j - 1, l - 1 );\n        for i = k : iu\n          ii = i - k + 1;\n          t = c(ii) * r(i,j) + s(ii) * r(i+1,j);\n          r(i+1,j) = c(ii) * r(i+1,j) - conj ( s(ii) ) * r(i,j);\n          r(i,j) = t;\n        end\n      end\n\n      if ( j < l )\n        jj = j - k + 1;\n        t = s(jj);\n        [ c(jj), s(jj), r(j,j) ] = zrotg ( r(j,j), t );\n      end\n\n    end\n%\n%  Apply the rotations to Z.\n%\n    for j = 1 : nz\n      for i = k : l - 1\n        ii = i - k + 1;\n        t = c(ii) * z(i,j) + s(ii) * z(i+1,j);\n        z(i+1,j) = c(ii) * z(i+1,j) - conj ( s(ii) ) * z(i,j);\n        z(i,j) = t;\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/linpack_z/zchex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5583168019092792}}
{"text": "function pass = test_linearize_init_fails(~)\n%TEST_LINEARIZE_INIT_FAILS   Test that we get sensible error messages when we\n%are dealing with an initial guess that makes the chebop fail to evaluate.\n\n%% First order problem which is OK, as it's solved as an IVP\nN = chebop(0, 1);\nN.op = @(u) diff(u) - sqrt(u);\nN.lbc = 1;\nu = N\\1;\npass(1) = norm(N(u)-1) < 1e-10;\n\n%% First order problem which is OK, not OK when try to solve as a BVP\nN = chebop(0, 1);\nN.op = @(u) diff(u) - sqrt(u);\nN.bc = @(u) u(0) - 1;\ntry\n    u = N\\1;\ncatch ME\n    pass(2) = strcmp(ME.identifier, ...\n        'CHEBFUN:CHEBOP:linearize:invalidInitialGuess');\nend\n\n%% Nor when solvebvp is called directly\nN = chebop(0, 1);\nN.op = @(u) diff(u) - sqrt(u);\nN.lbc = 1;\ntry\n    u = solvebvp(N, 1);\ncatch ME\n    pass(3) = strcmp(ME.identifier, ...\n        'CHEBFUN:CHEBOP:linearize:invalidInitialGuess');\nend\n\n%% Second order problem\nN = chebop(0, 1);\nN.op = @(u) diff(u,2) - sqrt(u);\nN.bc = 1;\ntry\n    u = N\\1;\ncatch ME\n    pass(4) = strcmp(ME.identifier, ...\n        'CHEBFUN:CHEBOP:linearize:invalidInitialGuess');\nend\n\n%% Second order problem, different function causing issues\nN = chebop(0, 1);\nN.op = @(u) diff(u,2) - 1./u;\nN.bc = 1;\ntry\n    u = N\\1;\ncatch ME\n    pass(5) = strcmp(ME.identifier, ...\n        'CHEBFUN:CHEBOP:linearize:invalidInitialGuess');\nend\n\n%% Coupled system, OK when solved as an IVP\nN = chebop(0, 1);\nN.op = @(x, u, v) [diff(u,2) - sqrt(v); diff(v,2) + 1./u];\nN.lbc = @(u,v) [u-1; diff(u)-.1; v-2; diff(v) + .2];\nuv = N\\[1; 2];\npass(6) = norm(N(uv) - [1;2]) < 1e-8;\n\n%% Coupled system, OK when solved as an IVP\nN = chebop(0, 1);\nN.op = @(x, u, v) [diff(u,2) - sqrt(v); diff(v,2) + 1./u];\nN.bc = @(x,u,v) [u(0) - 1; u(1) + 1; v(0) - 2; v(0) - 3];\ntry\n    uv = N\\1;\ncatch ME\n    pass(7) = strcmp(ME.identifier, ...\n        'CHEBFUN:CHEBOP:linearize:invalidInitialGuess');\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebop/test_linearize_init_fails.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5581513549910878}}
{"text": "function [vMc, mStd_McBoot, fStd_Mc, blo, bhi] = calc_BstMcPercInt(mCatalog,fBinning, alpha)\n% [vProbMin, vMcBest, mMag_bstsamp, fStd_Mc, fConfLow, fConfUp] = calc_BstMcPerInt(mCatalog, fBinning)\n%---------------------------------------------------------------------------\n% Bootstrap EQ catalog and determine Mc confidence due to modelling with\n% MLS fitting entire FMD distribution\n%\n% Incoming variables:\n% mCatalog   : EQ catalog\n% fBinning   : Magnitude binning interval\n%\n% Outgoing variables:\n% vProbMin     : Vector of maximum likelihood scores\n% vMcBest      : Best Mc estimate according to MLS\n% mMag_bstsamp : Matrix of bootstrap samples of magnitudes\n% fStd_Mc      : Standard deviation (assuming normal distribution\n%\n% J. Woessner: woessner@seismo.ifg.ethz.ch\n% last update: 31.01.03\n\n% Initialize\nvMls = [];\nvMc = [];\nvStd_Mcboot = [];\nvMls_boot = [];\nvMc_boot = [];\nmStd_McBoot = [];\n\nnB = 100; % Bootstrap replicates to calculate confidence intervals\n\n% Get magnitudes\nvMags = mCatalog(:,6);\n\n% Create bootstrap samples using bootstrap matlab toolbox\nnSample = 50;\nmMag_bstsamp = bootrsp(vMags,nSample);\n!date\n% First step: Estimate standard error of Mc original distribution\n% Determine Mc uncertainty\nfor nSamp=1:nSample\n    mCatalog(:,6) = mMag_bstsamp(:,nSamp);\n    [mResult, fMls, fMc, fMu, fSigma, mDatPredBest, vPredBest] = calc_McCdfnormal(mCatalog, fBinning);\n    vMls = [vMls; fMls];\n    vMc =  [vMc; fMc];\nend\nfStd_Mc = std(vMc);\n!date\n% Second step: Estimate standard error for each Mc of a bootstrap sample\nfor i = 1:nB\n    i\n    mCatalog(:,6) = mMag_bstsamp(:,i);\n    mMag_bst = bootrsp(mCatalog(:,6),nSample);\n    % Bootstrap using the sample for estimating Mc\n    for n= 1:nSample\n        mCatalog(:,6) = mMag_bstsamp(:,nSample);\n        [mResult, fMls, fMc, fMu, fSigma, mDatPredBest, vPredBest] = calc_McCdfnormal(mCatalog, fBinning);\n        vMls_boot = [vMls_boot; fMls];\n        vMc_boot =  [vMc_boot; fMc];\n    end\n    fStd_Mcboot = std(vMc_boot);\n    vStd_Mcboot = [vStd_Mcboot; fStd_Mcboot];\n    mStd_McBoot = [mStd_McBoot; vStd_Mcboot];\nend\n\n% Percentile interval\nfExp = nB*alpha/2;\nsbval = sort(mStd_Mcboot);\nblo = sbval(k);\nbhi = sbval(nB-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/seisvar/calc/calc_BstMcPercint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5581356398788913}}
{"text": "function [out] = percolation_1(p1,S,dt)\n%percolation_1 \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 <https://www.gnu.org/licenses/> for details.\n\n% Flux function\n% ------------------\n% Description:  Percolation at a constant rate\n% Constraints:  f <= S/dt\n% @(Inputs):    p1   - base percolation rate [mm/d]\n%               S    - current storage [mm]\n%               dt   - time step size [d]\n\nout = min(p1,S/dt);\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_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5581356381675978}}
{"text": "function y = log_sum_exp( varargin )\n\n%LOG_SUM_EXP    log(sum(exp(x))).\n%   LOG_SUM_EXP(X) = LOG(SUM(EXP(X)).\n%\n%   When used in a CVX model, LOG_SUM_EXP(X) causes CVX's successive\n%   approximation method to be invoked, producing results exact to within\n%   the tolerance of the solver. This is in contrast to LOGSUMEXP_SDP,\n%   which uses a single SDP-representable global approximation.\n%\n%   If X is a matrix, LOGSUMEXP_SDP(X) will perform its computations\n%   along each column of X. If X is an N-D array, LOGSUMEXP_SDP(X)\n%   will perform its computations along the first dimension of size\n%   other than 1. LOGSUMEXP_SDP(X,DIM) will perform its computations\n%   along dimension DIM.\n%\n%   Disciplined convex programming information:\n%       LOG_SUM_EXP(X) is convex and nondecreasing in X; therefore, X\n%       must be convex (or affine).\n\npersistent P\nif isempty( P ),\n    P.map = cvx_remap( { 'real' ; 'convex' } );\n    P.funcs = { @lse_1, @lse_2 };\n    P.zero = -Inf;\n    P.reduce = true;\n    P.constant = 1;\n    P.reverse = false;\n    P.name = 'log_sum_exp';\n    P.dimarg = 2;\nend\ncvx_expert_check( 'log_sum_exp', varargin{1} );\ny = cvx_reduce_op( P, varargin{:} );\n\nfunction x = lse_1( x )\nxmid = 0.5 * ( max( x, [], 1 ) + min( x, [], 1 ) );\nx = log( sum( exp( bsxfun( @minus, x, xmid ) ), 1 ) ) + xmid;\n\nfunction y = lse_2( x ) %#ok\n[nx,nv] = size(x); %#ok\ncvx_begin\n    variable w( nx, nv )\n    epigraph variable y( 1, nv )\n    exp( x - repmat( y, [ nx, 1 ] ) ) <= w; %#ok\n    sum( w, 1 ) == 1; %#ok\ncvx_end\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\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/log_sum_exp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5581356331650748}}
{"text": "%LMNC Levenberg-Marquardt trained feed-forward neural net classifier\n% \n%  [W,HIST] = LMNC (A,UNITS,ITER,W_INI,T)\n%\n% INPUT\n%  A        Dataset\n%  UNITS    Vector with numbers of units in each hidden layer (default: [5])\n%  ITER     Number of iterations to train (default: inf)\n%  W_INI    Weight initialization network mapping (default: [], meaning \n%           initialization by Matlab's neural network toolbox)\n%  T        Tuning set (default: [], meaning use A)\n%\n% OUTPUT\n%  W        Trained feed-forward neural network mapping\n%  HIST     Progress report (see below)\n%\n% DESCRIPTION \n% A feed-forward neural network classifier with length(N) hidden layers with \n% N(I) units in layer I is computed for the dataset A. Training is stopped \n% after ITER epochs (at least 50) or if the iteration number exceeds twice \n% that of the best classification result. This is measured by the labeled \n% tuning set T. If no tuning set is supplied A is used. W_INI is used, if \n% given, as network initialization. Use [] if the standard Matlab \n% initialization is desired. Progress is reported in file FID (default 0). \n%\n% The entire training sequence is returned in HIST (number of epochs, \n% classification error on A, classification error on T, MSE on A, MSE on T,\n% mean of squared weights).\n% \n% Uses the Mathworks' Neural Network toolbox.\n%\n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% MAPPINGS, DATASETS, BPXNC, NEURC, RNNC, RBNC, PRPROGRESS\n\n% Copyright: R.P.W. Duin, duin@ph.tn.tudelft.nl\n% Faculty of Applied Physics, Delft University of Technology\n% P.O. Box 5046, 2600 GA Delft, The Netherlands\n\n% $Id: lmnc.m,v 1.3 2007/06/15 09:58:30 duin Exp $\n\nfunction [w,hist] = lmnc(varargin)\n\n\t\t[w,hist] = ffnc(mfilename,varargin{:});\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/lmnc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5581356314537812}}
{"text": "classdef TTeMPS_op_laplace\n% TTeMPS_op_laplace\n%\n%   A MATLAB class for representing and manipulating \n%   Laplace-like operators in the TT/MPS operator format,\n%\n%   Laplace-like operators are of the form\n%         L \\otimes I \\otimes I \\otimes I \n%       + I \\otimes L \\otimes I \\otimes I \n%       + ... \n%       + I \\otimes I \\otimes I \\otimes L\n% \n%   with e.g. L being the discrete 1D-Laplacian matrix. \n\n%   TTeMPS Toolbox. \n%   Michael Steinlechner, 2013-2016\n%   Questions and contact: michael.steinlechner@epfl.ch\n%   BSD 2-clause license, see LICENSE.txt\n\nproperties( SetAccess = public, GetAccess = public )\n\n    L0\n    U           % core tensors as 4D doubles\n    rank\n    order\n    size_row\n    size_col\n    V_L\n    E_L\n\nend\n\n% Set methods for Cores\nmethods\n    \n    function A = set.U( A, U_);\n        \n        A.U = U_;\n        A = update_properties( A );\n\n    end\n\n\n    function A = update_properties( A );\n\n        A.rank = [1,  2*ones(1, length(A.U)-1), 1];  % the TT rank is always two for such Laplace-like tensors\n        size_col_ = cellfun( @(y) size(y,1), A.U);\n        A.size_col = size_col_ ./ (A.rank(1:end-1).*A.rank(2:end));\n        A.size_row = cellfun( @(y) size(y,2), A.U);\n        A.order = length( A.size_row );\n\n    end\n\nend\n\nmethods( Access = public )\n\n    function A = TTeMPS_op_laplace(varargin)\n    %LAPLACE Construct a tensor in TT/MPS format and return TTeMPS_op_laplace object.\n    %\n    %   A = TTEMPS_OP_LAPLACE( L, D ) creates the D-dimensional Laplace-like\n    %       TT/MPS operator using the supplied matrix L.\n    %\n    %\n        if nargin == 1\n            % debug constructor\n            A.U = varargin{1};\n            A = update_properties( A );\n            A.L0 = [];\n            A.V_L = [];\n            A.E_L = [];\n        % Default constructor\n        elseif (nargin == 2)\n\n            % only one matrix passed\n            L = varargin{1};\n            A.L0 = L;\n            d = varargin{2};\n\n            A.V_L = [];\n            A.E_L = [];\n            \n            [m,n] = size( L );\n            E = speye( m, n );\n            a_1 = sparse( 1, 1, 1, 2, 1 );\n            a_mid = sparse( 2, 1, 1, 4, 1 );\n            a_end = sparse( 2, 1, 1, 2, 1 );\n            b_1 = sparse( 2, 1, 1, 2, 1 );\n            b_mid = sparse( [1;4], [1;1], [1;1], 4, 1 );\n            b_end = sparse( 1, 1, 1, 2, 1 );\n\n            A.U = cell( 1, d );\n            A.U{1} = kron( L, a_1 ) + kron( E, b_1 );\n            A_mid = kron( L, a_mid ) + kron( E, b_mid );\n            for i=2:d-1\n                A.U{i} = A_mid;\n            end\n            A.U{d} = kron( L, a_end ) + kron( E, b_end );\n\n            A = update_properties( A );\n\n        else\n            error('Invalid number of arguments.')\n        end\n    end\n    \n    \n    % Other public functions\n    y = apply( A, x, idx );\n    A = mtimes( B, A );\n    res = contract( A, x, y, idx );\n    \n    disp( A, name );\n    display( A );\n\n    B = TTeMPS_op_laplace_to_TTeMPS_op( A );\n    B = TTeMPS_op_laplace_to_TT_matrix( A );\n    expB = constr_precond_inner( A, X, mu );\n    \n\n    function A = initialize_precond( A )\n        [A.V_L, A.E_L] = eig(full(A.L0));\n        A.E_L = diag( A.E_L );\n    end\nend\n\n\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/@TTeMPS_op_laplace/TTeMPS_op_laplace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5581029192712452}}
{"text": "function [ scaled_regions ] = map_regions_to_mult_scales(region_params, regions, image_size, scales )\n% map_regions_to_mult_scales: given a set of regions that comes from an\n% image of size image_size, it maps each of them to the appropriate image \n% scale from set of scales given from the parameter scales.\n% \n% INPUTS:\n% 1) region_params: (type struct) the region pooling parameters. Some of \n% its fields are:\n%   a) sz_conv_standard: (scalar value) the last convolution size\n%   b) step_standard: (scalar value) is the stride in pixels of the output \n%   of the last convolutional layer of the network where the regions are \n%   going to be projected (for VGG16 is equal to 16).\n% 2) regions: is a N x 8 array with the N input regions. Each region is \n% represented by 8 values [xo0, yo0, xo1, yo1, xi0, yi0, xi1, yi1] that \n% correspond to its outer rectangle [xo0, yo0, xo1, yo1] and its inner \n% rectangle [xi0, yi0, xi1, yi1]. \n% 3) image_size: 2 x 1 or 1 x 2 array with the size of the original image\n% 4) scales: NS x 1 or 1 x NS array with the image scales that are used. NS\n% is the number of images. The i-th value is the size in pixels of the\n% smallest dimension of the image in the i-th scale.\n% \n% OUTPUT:\n% 1) scaled_regions: is a N x 9 array with the N output regions. Each region is \n% represented by 9 values [scale_id, xo0, yo0, xo1, yo1, xi0, yi0, xi1, yi1]  \n% that correspond to its outer rectangle [xo0, yo0, xo1, yo1] and its inner \n% rectangle [xi0, yi0, xi1, yi1]. scale_id corresponds to the scale id to\n% which each region is mapped.\n%\n% This file is part of the code that implements the following paper:\n% Title      : \"LocNet: Improving Localization Accuracy for Object Detection\"\n% Authors    : Spyros Gidaris, Nikos Komodakis\n% Institution: Universite Paris Est, Ecole des Ponts ParisTech\n% ArXiv link : http://arxiv.org/abs/1511.07763\n% code       : https://github.com/gidariss/LocNet\n%\n% AUTORIGHTS\n% --------------------------------------------------------\n% Copyright (c) 2016 Spyros Gidaris\n% \n% Title     : \"LocNet: Improving Localization Accuracy for Object Detection\"\n% ArXiv link: http://arxiv.org/abs/1511.07763\n% Licensed under The MIT License [see LICENSE for details]\n% ---------------------------------------------------------\n\nboxes_out = regions(:,1:4);\nboxes_in  = regions(:,5:8);\n\nmin_img_sz = min(image_size(1:2));\n\nif length(scales) > 1\n    box_areas      = (boxes_out(:,3) - boxes_out(:, 1) + 1) .* (boxes_out(:,4) - boxes_out(:,2) + 1);\n    expected_scale = region_params.sz_conv_standard * region_params.step_standard * min_img_sz ./ sqrt(box_areas);\n    expected_scale = round(expected_scale(:));\n    [~, best_scale_ids] = min(abs(bsxfun(@minus, scales, expected_scale(:))), [], 2);   \nelse\n    best_scale_ids = ones(size(boxes_out, 1), 1);\nend\n    \nboxes_scales     = scales(best_scale_ids(:));\nscaled_boxes_out = bsxfun(@times, (boxes_out - 1), (boxes_scales(:) - 1)) / (min_img_sz - 1) + 1;\nscaled_boxes_in  = bsxfun(@times, (boxes_in  - 1), (boxes_scales(:) - 1)) / (min_img_sz - 1) + 1;\nscaled_regions   = [best_scale_ids(:), scaled_boxes_out, scaled_boxes_in];\nend", "meta": {"author": "gidariss", "repo": "LocNet", "sha": "a4678b87d9e63dcea07d9afd978d1223174d8be3", "save_path": "github-repos/MATLAB/gidariss-LocNet", "path": "github-repos/MATLAB/gidariss-LocNet/LocNet-a4678b87d9e63dcea07d9afd978d1223174d8be3/code/region-funs/map_regions_to_mult_scales.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5581029167670768}}
{"text": "% SATGLOBE4 - Draw an idealized satellite view of earth\n%\n% This file renders a fully manipulatable satellite view\n% of earth at a resolution of four pixels per degree, with added\n% international political boundaries and gridlines.\n% The imagery was obtained from NASA, then postprocessed.\n% The globe was rendered using the Matlab Mapping Toolbox.\n%\n% The Mapping Toolbox is not needed to use this file; however,\n% if you have the toolbox, you will be able to use the plot3m\n% command to add your own graphics. If not, you can simply use plot3.\n%\n% In order to save storage space, this m-file loads image\n% data from the file satglobe.mat, and then creates the\n% graticule mesh itself. This process allows users who\n% do not have the Matlab Mapping Toolbox to render the\n% figure, but it does take a few moments to compute the\n% mesh. Using this trick, the data storage is reduced\n% considerably; however, once the figure is rendered, you\n% may wish to save it as a regular Matlab figure file\n% to increase speed.\n%\n% Michael Kleder, 2004\n\nfunction satglobe4\nload satglobe4\nth=repmat((0:.25:180)'*pi/180,[1 1441]);\nph=repmat((-180:.25:180)*pi/180,[721 1]);\ns.children(1).properties.XData = sin(th).*cos(ph);\ns.children(1).properties.YData = sin(th).*sin(ph);\ns.children(1).properties.ZData = cos(th);\ns.children(1).properties.CData = double(c)/255;\nfigure;\nstruct2handle(s,gcf);\nset(gcf,'color','k','renderer','zbuffer','inverthardcopy','off','name',...\n   'Earth at 4 Pixels per Degree, by Michael Kleder');\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/5791-satglobe4-visualizing-earth-from-space-3-d-rendering-of-nasa-satellite-imagery/satglobe4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5580548807908331}}
{"text": "function [V, policy, iter, cpu_time] = mdp_policy_iteration(P, R, discount, policy0, max_iter, eval_type)\n\n% max_iter=2000;\n% eval_type=1;\n\n% mdp_policy_iteration  Resolution of discounted MDP \n%                       with policy iteration algorithm\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%   policy0(S) = starting policy, optional \n%   max_iter = maximum number of iteration to be done, upper than 0, \n%              optional (default 1000)\n%   eval_type = type of function used to evaluate policy: \n%              0 for mdp_eval_policy_matrix, else mdp_eval_policy_iterative\n%              optional (default 0)\n% Evaluation --------------------------------------------------------------\n%   V(S)   = value function \n%   policy(S) = optimal policy\n%   iter     = number of done iterations\n%   cpu_time = used CPU time\n%--------------------------------------------------------------------------\n% In verbose mode, at each iteration, displays the number \n% of differents actions between policy n-1 and n\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 <ORGANIZATION> 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\ncpu_time = cputime;\n\nglobal mdp_VERBOSE;\n\n% check of arguments\nif iscell(P); S = size(P{1},1); else S = size(P,1); end;\nif iscell(P); A = length(P); else A = size(P,3); end\n\nif discount <= 0 || discount >= 1\n    disp('--------------------------------------------------------')\n    disp('MDP Toolbox ERROR: Discount rate must be in ]0; 1[')\n    disp('--------------------------------------------------------')\nelseif nargin > 3 && (size(policy0,1)~=S || any(mod(policy0,1)) || any(policy0<1)|| any(policy0>A) )\n    disp('--------------------------------------------------------')\n    disp('MDP Toolbox ERROR: policy0 must a (Sx1) vector with integer from 1 to A')\n    disp('--------------------------------------------------------')\nelseif nargin > 4 && max_iter <= 0\n    disp('--------------------------------------------------------')\n    disp('MDP Toolbox ERROR: The maximum number of iteration must be upper than 0')\n    disp('--------------------------------------------------------')\nelse\n    \n    PR = mdp_computePR(P,R);\n\n    % initialization of optional arguments\n    if nargin < 6; eval_type = 0; end;\n    if nargin < 5; max_iter = 1000; end;\n    if nargin < 4;\n        % initialization of policy: \n        % the one wich maximizes the expected immediate reward\n        [nil, policy0] = mdp_bellman_operator(P,PR,discount,zeros(S,1));\n    end;\n    \n%     if mdp_VERBOSE; disp('  Iteration  Number_of_different_actions'); end;\n        disp('  Iteration  Number_of_different_actions');\n\n    iter = 0;\n    policy = policy0;\n    is_done = false;\n    while ~is_done\n        iter = iter + 1;\n        if  (eval_type==0)   \n            V = mdp_eval_policy_matrix(P,PR,discount,policy);         \n        else\n            V = mdp_eval_policy_iterative(P,PR,discount,policy);\n        end;\n        [nil, policy_next] = mdp_bellman_operator(P,PR,discount,V);\n        \n\tn_different = sum(policy_next ~= policy);\n%         if mdp_VERBOSE; disp(['       ' num2str(iter) '                 '  num2str(n_different)]); end;\n        disp(['       ' num2str(iter) '                 '  num2str(n_different)]);\n\n        if all(policy_next==policy) || iter == max_iter || (iter > 20 && n_different <=5)\n            is_done = true; \n        else\n            policy = policy_next;\n        end;\n    end;\n    \nend; \n\ncpu_time = cputime - cpu_time;\n", "meta": {"author": "matthieukomorowski", "repo": "AI_Clinician", "sha": "0669f8907e65503641857ca76aa46938641e513f", "save_path": "github-repos/MATLAB/matthieukomorowski-AI_Clinician", "path": "github-repos/MATLAB/matthieukomorowski-AI_Clinician/AI_Clinician-0669f8907e65503641857ca76aa46938641e513f/MDPtoolbox/mdp_policy_iteration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5580548807908331}}
{"text": "function c = rdivide(a,b)\n% function C=rdivide(A,B)\n%\n% DESCRIPTION\n%   Element-by-element right division\n%\n% INPUTS\n%   A: polynomial\n%   B: matrix of constants\n%\n% OUTPUTS\n%   C: polynomial, the result of division.\n%\n% SYNTAX\n%   C= A./B\n%     A and B must have the same dimensions unless one\n%     is a scalar.  Scalars can be divided with anything.\n%   C = rdivide(A,B)\n%     Function-call form\n\n% 10/22/2002: PJS  Initial Coding\n\n% Promote a to polynomial\na = polynomial(a);\nsza = size(a);\n\n% Promote b to polynomial\nb = polynomial(b);\nszb = size(b);\n\nif isempty(a) || isempty(b)\n    \n    if isempty(a) && all(szb==[1 1])\n        % empty./scalar = empty(sza)\n        c=polynomial(zeros(sza));\n        return;\n    elseif isempty(b) && all(sza==[1 1])\n        % scalar./empty = empty(szb)\n        c=polynomial(zeros(szb));\n        return;\n    elseif all(sza==szb)\n        c=polynomial(zeros(sza));\n        return;\n    else\n        error('Matrix dimensions must agree.');\n    end\n    \nelseif all(sza==szb) || all(sza==[1 1]) || ...\n        all(szb==[1 1])\n    \n    % Matrix./Matrix\n    degidx = find(b.degmat);\n    if ~isempty(degidx)\n        error('B must be a constant.');\n    end\n    b = combine(b);\n    bcoef = reshape(b.coefficient,b.matdim);\n    c = times(a,1./bcoef);\nelse\n    \n    error('Matrix dimensions must agree');\nend\n\n\n\n\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/multipoly/@polynomial/rdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.558054880790833}}
{"text": "function [yd] = cm2yd(cm)\n% Convert length from centimeters to yards.\n% Chad A. Greene 2012\nyd = cm*0.01093613298338;", "meta": {"author": "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/cm2yd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5580548702323904}}
{"text": "function [A uTrue uEst] = buildAlignmentMatrix( zTrue, zEst )\n% Given true and estimated label sequence, construct align matrix A\n%   where A( ke, kt ) = fraction of labels ke aligned \n%                          from ESTIMATED label ke to TRUE label kt\n% Note that each ROW of A will sum to 1\n\nuTrue = unique( zTrue );\nuEst  = unique( zEst  );\n\nfor ue = 1:length( uEst )\n    ts = zEst == uEst(ue);\n    A(ue,:) = histc( zTrue(ts),  uTrue );\nend\nA = bsxfun( @rdivide, A, sum(A,2)  );", "meta": {"author": "michaelchughes", "repo": "NPBayesHMM", "sha": "22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd", "save_path": "github-repos/MATLAB/michaelchughes-NPBayesHMM", "path": "github-repos/MATLAB/michaelchughes-NPBayesHMM/NPBayesHMM-22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd/code/BPHMM/BPutil/relabel/buildAlignmentMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5580548625869577}}
{"text": "function erf_test ( )\n\n%*****************************************************************************80\n%\n%% ERF_TEST tests R4_ERF and R8_ERF.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 September 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n  addpath ( '../test_values' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'ERF_TEST:\\n' );\n  fprintf ( 1, '  Test ERF_VALUES, R4_ERF R8_ERF\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '             X          ERF(X)\\n' );\n  fprintf ( 1, '                     R4_ERF(X)        Diff\\n' );\n  fprintf ( 1, '                     R8_ERF(X)        Diff\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x, fx1 ] = erf_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fx2 = r4_erf ( single ( x ) );\n    fx3 = r8_erf ( x );\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  %14.4f  %14.6g\\n', x, fx1 );\n    fprintf ( 1, '                  %14.6g  %14.6g\\n', fx2, abs ( fx1 - fx2 ) );\n    fprintf ( 1, '                  %14.6g  %14.6g\\n', fx3, abs ( fx1 - fx3 ) );\n\n  end\n\n  rmpath ( '../test_values' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/erf_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.5580548588852108}}
{"text": "function [x]=gdist(a,x)\n%[Y] = GDIST(A, X) Guitar Distortion\n%\n%   GDIST creates a distortion effect like that of\n%   an overdriven guitar amplifier. This is a Matlab \n%   implementation of an algorithm that was found on \n%   www.musicdsp.org.\n%\n%   A = The amount of distortion.  A\n%       should be chosen so that -1<A<1.\n%   X = Input.  Should be a column vector \n%       between -1 and 1.\n%\n%coded by: Steve McGovern, date: 09.29.04\n%URL: http://www.steve-m.us\n\nk = 2*a/(1-a);\nx = (1+k)*(x)./(1+k*abs(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/6639-guitar-distortion-effect/gdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5580548580964738}}
{"text": "function obj=stat_fit(obj,varargin)\n% stat_fit() Display a custom fit of the data\n%\n% Example syntax gramm_object.stat_fit('fun',@(alpha,beta,x)alpha*cos(x-beta),'disp_fit',true)\n%\n% This fuction uses the curve fitting toolbox function fit() to\n% fit a provided anonymous function with arguments\n% (param1,param2,...paramN,x) to the data.\n% Parameters:\n% - 'fun': anonymous function used for the fit\n% - 'StartPoint': Array containing starting values for the\n% parameter to be fitted [start_param1,start_param2,...start_paramN]\n% - 'intopt': Option passed to predint() for the type of bounds\n% to compute, 'observation' for bounds of a new observation\n% (default), or 'functional' for bounds of the fitted curve.\n% - 'geom', 'fullrange', 'disp_fit' options: see stat_glm()\n% - 'fullrange': set to true if you want the fits to be\n%   displayed over the whole width of each subplot instead of\n%   being displayed over the range of x values used for the fit\n% - 'disp_fit': set to true to display the fitted parameters\n\np=inputParser;\nmy_addParameter(p,'fun',@(a,b,x)a*x+b);\nmy_addParameter(p,'StartPoint',[]);\nmy_addParameter(p,'intopt','observation');\nmy_addParameter(p,'geom','area');\nmy_addParameter(p,'fullrange',false);\nmy_addParameter(p,'disp_fit',false);\nparse(p,varargin{:});\nobj.geom=vertcat(obj.geom,{@(dobj,dd)my_fit(dobj,dd,p.Results)});\nobj.results.stat_fit={};\nend\n\n\n\nfunction hndl=my_fit(obj,draw_data,params)\n\ncombx=comb(draw_data.x);\ncomby=comb(draw_data.y);\n\n%Remove NaNs\nsel=~isnan(combx) & ~isnan(comby);\ncombx=combx(sel);\ncomby=comby(sel);\n\n%Do the fit depending on options\nif isempty(params.StartPoint)\n    mdl=fit(shiftdim(combx),shiftdim(comby),params.fun);\nelse\n    mdl=fit(shiftdim(combx),shiftdim(comby),params.fun,'StartPoint',params.StartPoint);\nend\n\n%Create x values for the fit plot\nif params.fullrange\n    newx=linspace(obj.var_lim.minx,obj.var_lim.maxx,100)';\nelse\n    newx=linspace(min(combx),max(combx),100)';\nend\n%Get fit value and CI\nnewy=feval(mdl,newx);\nyci=predint(mdl,newx,1-obj.stat_options.alpha,params.intopt);\n\n\nobj.results.stat_fit{obj.result_ind,1}.x=newx;\nobj.results.stat_fit{obj.result_ind,1}.y=newy;\nobj.results.stat_fit{obj.result_ind,1}.yci=yci;\nobj.results.stat_fit{obj.result_ind,1}.model=mdl;\n\n%Plot fit\nhndl=plotci(obj,newx,newy,yci,draw_data,params.geom);\n\n%Store plotted handles\nhnames=fieldnames(hndl);\nfor k=1:length(hnames)\n    obj.results.stat_fit{obj.result_ind,1}.(hnames{k})=hndl.(hnames{k});\nend\n\n%Do we display the results ?\nif params.disp_fit\n    %Set Y position of display\n    if obj.firstrun(obj.current_row,obj.current_column)\n        obj.extra.mdltext(obj.current_row,obj.current_column)=0.05;\n    else\n        obj.extra.mdltext(obj.current_row,obj.current_column)=obj.extra.mdltext(obj.current_row,obj.current_column)+0.03;\n    end\n    %Get formula and parameters\n    form=formula(mdl);\n    cvals=coeffvalues(mdl);\n    cnames=coeffnames(mdl);\n    %Replace parameter names by their value in the formula\n    for c=1:length(cnames)\n        form=strrep(form,cnames{c},num2str(cvals(c),2));\n    end\n    obj.results.stat_fit{obj.result_ind,1}.text_handle=text('Units','normalized','Position',[0.1 obj.extra.mdltext(obj.current_row,obj.current_column)],'color',draw_data.color,...\n        'String',form);\nend\n\n\n\nend\n", "meta": {"author": "piermorel", "repo": "gramm", "sha": "b0fc59245c17d6fbcd86a105d893aeb745fb51e2", "save_path": "github-repos/MATLAB/piermorel-gramm", "path": "github-repos/MATLAB/piermorel-gramm/gramm-b0fc59245c17d6fbcd86a105d893aeb745fb51e2/@gramm/stat_fit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5580256494328015}}
{"text": "function corrplot(c)\n\n% Called internally by correlation/plot to plot correlation matrix.\n\n% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks\n% $Date$\n% $Revision$\n\n\n% PREP PLOT\nfigure('Color','w','Position',[50 50 600 500]);\nset(gcf,'DefaultAxesFontSize',14);\nimagesc(c.C);\ntitle('Maximum correlation coefficient');\n\n\n% ADD DATES TO AXES\nn = length(c.trig);\nset(gca,'XTick',[1:round(n/25):n]);\nset(gca,'YTick',[1:round(n/25):n]);\nyt = get(gca,'YTick');\nset(gca,'YTickLabel',datestr(c.trig(yt),'yyyy-mm-dd HH:MM'),'FontSize',6);\n\n%xt = get(gca,'XTick');\n%set(gca,'XTickLabel',datestr(c.trig(xt),'yyyy-mm-dd HH:MM'),'FontSize',6,'Rotation',90);\n\n\n% DRESS UP THE FIGURE\ncaxis([0 1]);\ncmap = load('colormap_corr.txt');\ncolormap(cmap);\ncolorbar;\nxlabel('Event number');\nylabel('Event date');\n\n\n%PRINT OUT FIGURE\nset(gcf, 'paperorientation', 'portrait');\nset(gcf, 'paperposition', [1.25 2.5 6 6] );\n%print(gcf, '-depsc2', 'FIG_tartan.ps');\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/core/@correlation/private/corrplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5580256373825332}}
{"text": "classdef cluster\n\nmethods(Static)\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Following functions are meant for assisting in \n% setting up experiments.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n    function labels = labels_from_cluster_sizes(cluster_sizes)\n        % total number of points\n        S = sum(cluster_sizes);\n        % Number of points in array\n        K = numel(cluster_sizes);\n        labels = zeros(1, S);\n        i = 0;\n        for k=1:K\n            Sk  = cluster_sizes(k);\n            for s=1:Sk\n                i = i+1;\n                labels(i) = k;\n            end\n        end\n        return;\n    end\n\n    function [cluster_sizes, labels] = cluster_sizes_from_labels(labels)\n        tbl = tabulate(labels);\n        labels = tbl(:, 1)';\n        cluster_sizes =  tbl(:, 2)';\n    end\n\n    function [start_indices, end_indices] = start_end_indices(cluster_sizes)\n        % Returns start and end indices from cluster sizes\n        start_indices = cumsum(cluster_sizes) + 1;\n        start_indices = [1 start_indices(1:end-1)];\n        end_indices = start_indices + cluster_sizes -1;\n    end\n\n    function result = clustering_error(estimated_labels, true_labels, num_clusters)\n        % finds out an appropriate mapping between\n        % true labels and estimated labels and \n        % calculates the corresponding clustering error\n\n        % make sure that both are row vectors\n        if ~isrow(estimated_labels)\n            estimated_labels = estimated_labels';\n        end\n        if ~isrow(true_labels)\n            true_labels = true_labels';\n        end\n        if size(estimated_labels) ~= size(true_labels)\n            error('Both estimated and true label arrays should have same size.');\n        end\n        % Let us consider all possible mappings\n        possible_mappings = perms(1:num_clusters);\n        % number of possible mappings\n        num_mappings = size(possible_mappings,1 );\n        % number of labels\n        num_labels = size(estimated_labels, 2);\n        % number of misclustered points for each mapping\n        missed_points = zeros(num_mappings, 1);\n        for j=1:num_mappings\n            %cur_mapping = possible_mappings(j, :)\n            mapped_labels = possible_mappings(j, true_labels);\n            missed_points(j) = sum(estimated_labels ~= mapped_labels);\n        end\n        % missed_points\n        % we choose the mapping with minimum mismatch\n        [miss, index] = min(missed_points, [], 1);\n        % final clustering error value\n        result.num_labels = num_labels;\n        result.num_missed_points = miss;\n        result.error  = miss / num_labels;\n        result.error_perc = result.error * 100;\n        % corresponding mapping\n        result.mapping = possible_mappings(index, :);\n        result.mapped_labels = result.mapping(true_labels);\n        result.misses = estimated_labels ~= result.mapped_labels;\n    end\n\n    function result = clustering_error_hungarian_mapping(estimated_labels, true_labels, num_clusters)\n        % make sure that both are row vectors\n        if ~isrow(estimated_labels)\n            estimated_labels = estimated_labels';\n        end\n        if ~isrow(true_labels)\n            true_labels = true_labels';\n        end\n        if size(estimated_labels) ~= size(true_labels)\n            error('Both estimated and true label arrays should have same size.');\n        end\n        % number of labels\n        num_labels = size(estimated_labels, 2);\n        mapped_labels = bestMap(estimated_labels, true_labels)';\n        miss = sum(estimated_labels ~= mapped_labels);\n        % final clustering error value\n        result.num_labels = num_labels;\n        result.num_missed_points = miss;\n        result.error  = miss / num_labels;\n        result.error_perc = result.error * 100;\n        result.mapped_labels = mapped_labels;\n        result.misses = estimated_labels ~= result.mapped_labels;\n    end\n\n\nend\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/cluster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5580256326499032}}
{"text": "\n% main file \n\nclose all\nclear all\n\n\n% read Template image\nim1=imread('K.bmp');\n%im1=imread('S.bmp');\n%im1=imread('image1.jpg');\n\n\n% read Traget Image\nim2=imread('letters.bmp');\n%im2=imread('image2.jpg');\n\n% apply templete matching using power of the image\nresult1=tmp(im1,im2);\n\nfigure,\nsubplot(2,2,1),imshow(im1);title('Template');\nsubplot(2,2,2),imshow(im2);title('Target');\nsubplot(2,2,3),imshow(result1);title('Matching Result using tmp');\n\n\n% apply templete matching using DC components of the image\nresult2=tmc(im1,im2);\n\nfigure,\nsubplot(2,2,1),imshow(im1);title('Template');\nsubplot(2,2,2),imshow(im2);title('Target');\nsubplot(2,2,3),imshow(result2);title('Matching Result using tmc');", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/20061-template-matching/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5580256300648946}}
{"text": "function E = edges4connected(height,width)\n\n% EDGE4CONNECTED Creates edges where each node\n%   is connected to its four adjacent neighbors on a \n%   height x width grid.\n%   E - a vector in which each row i represents an edge\n%   E(i,1) --> E(i,2). The edges are listed is in the following \n%   neighbor order: down,up,right,left, where nodes \n%   indices are taken column-major.\n%\n%   (c) 2008 Michael Rubinstein, WDI R&D and IDC\n%   $Revision$\n%   $Date$\n%\n\nN = height*width;\nI = []; J = [];\n% connect vertically (down, then up)\nis = [1:N]'; is([height:height:N])=[];\njs = is+1;\nI = [I;is;js];\nJ = [J;js;is];\n% connect horizontally (right, then left)\nis = [1:N-height]';\njs = is+height;\nI = [I;is;js];\nJ = [J;js;is];\n\nE = [I,J];\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/21310-maxflow/edges4connected.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.5580256242584543}}
{"text": "function [Cext,val] = extendLSAPEinstance(C,val)\n% Extend a cost matrix for error-correcting matching to its square version\n%\n%  [Cext,val] = extendCostMtx(C,val)\n%\n%  inputs:\n%  C (n+1)x(m+1) cost matrix of an error-correcting bipartite graph\n%  val the value used to fill 2nd and 3rd block of Cext (optional)\n%  val = max(max(C)) + 1 if not given\n%\n%  outputs:\n%  Cext (n+m)x(m+n) extended cost matrix\n%  valcpt (optional) is the value val used to fill 2nd and 3rd block of\n%  Cext\n%  \n%         | c(1,1)   ...  c(1,m-1)  | c(1,m) val   ...      val   |\n%         |   .              .      |  val  c(2,m) val ...   .    | \n%         |   .              .      |   .                   val   |\n%         | c(n-1,1) ... c(n-1,m-1) |  val     ...   val c(n-1,m) |\n%  Cext =  -------------------------------------------------------\n%         | c(n,1) val  ...    val  |                             |\n%         |  val c(n,2) val ..  .   |           0_{m,n}           |\n%         |   .                val  |                             |\n%         |  val  ...  val c(n,m-1) |                             |\n%\n%\n%   author: Sebastien Bougleux\n%   institution: Normandie Univ, UNICAEN, ENSICAEN, CNRS, GREYC\n% -----------------------------------------------------------\n% This file is part of LSAPE.\n% LSAPE is free software: you can redistribute it and/or modify\n% it under the terms of the CeCILL-C License. See README file \n% for more details.\n% -----------------------------------------------------------\n    \n    if ~exist('val','var') || nargin == 1\n        val = max(max(C)) + 1;\n    end\n    \n    D = val .* cast(ones(size(C,1)-1),class(C));\n    E = val .* cast(ones(size(C,2)-1),class(C));\n    D(logical(eye(size(D)))) = C(1:end-1,end);\n    E(logical(eye(size(E)))) = C(end,1:end-1);\n    Cext = [[C(1:end-1,1:end-1),D];[E,zeros(size(C,2)-1,size(C,1)-1)]];\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/_site/code/toolbox/toolbox-lsap/extendLSAPEinstance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5580147002054149}}
{"text": "classdef trigdouble < chebdouble\n%FOURDOUBLE   Fourier double class. \n%\n%   See the CHEBDOUBLE class for details.\n%\n%   This class in intended solely as a worker-class for PDESOLVE.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n    methods\n        \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% CLASS CONSTRUCTOR:\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        function obj = trigdouble(varargin)\n            \n            % Call the CHEBDOUBLE constructor:\n            obj = obj@chebdouble(varargin{:});\n            \n        end\n        \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    %% CLASS METHODS:\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%        \n\n        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  DIFF  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        function u = diff(u, k)\n            %DIFF   Compute the k-th derivative of u using Fourier\n            % differentiation matrices defined by diffmat.\n            \n            % Store the diffmat D as a persistent variable to allow speeding up\n            % if we work with the same discretization at multiple time steps.\n            % Note that the matrix D is independent of the domain, since it is\n            % scaled separately below.\n            persistent D\n            \n            % Assume first-order derivative:\n            if ( nargin == 1 )\n                k = 1;\n            end\n            \n            N = length(u.values);\n            \n            % Construct D if we don't match a previous discretization:\n            if ( isempty(D) || numel(D) < k || size(D{k}, 1) ~= N )\n                D{k} = trigcolloc.diffmat(N, k); % Diffmat\n            end\n            \n            % Interval scaling. (Note: trigtech.diffmat is defined on [0, 2*pi))\n            c = 2/diff(u.domain);\n            \n            % Muliplying by the kth-order differentiation matrix:\n            u.values = c^k*(D{k}*u.values);\n            \n            % Update the difforder:\n            u.diffOrder = u.diffOrder + k;\n            \n        end\n        \n        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  SUM  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        % The differential operators\n        function I = sum(u, a, b)\n            %SUM  Compute the integral of u.\n            \n            persistent W\n            \n            if ( nargin > 1 )\n                % TODO: Add support.\n                error('CHEBFUN:FOURDOUBLE:sum:notImplemented', ...\n                    'Partial integrals not implemented yet.')\n            end\n            \n            N = length(u.values);\n            \n            % Retrieve or compute weights:\n            if ( N > 5 && numel(W) >= N && ~isempty(W{N}) )\n                % Weights are already in storage!\n            else\n                c = diff(u.domain)/2; % Interval scaling.\n                W{N} = c*trigtech.quadwts(N);\n            end\n            \n            % Find the sum by muliplying by the weights vector:\n            I = W{N}*u.values;\n            \n        end\n        \n        function I = integral(varargin)\n            I = sum(varargin{:});\n        end\n        \n        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  CUMSUM  %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        % The differential operators\n        function u = cumsum(u)\n            %CUMSUM   Compute the indefinite integral of the Chebyshev\n            %         interpolant to u.\n            \n            % TODO: Add support.\n            error('CHEBFUN:FOURDOUBLE:cumsum:notImplemented', ...\n                'CUMSUM not implemented yet.')\n            \n        end\n        \n        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  FRED  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        function u = fred(K, u)\n            %FRED  Fredholm operator with kernel K.\n            %   FRED(K, U) computes the action of the Fredholm operator with\n            %   kernel K on the Chebyshev interpolant to the points in the\n            %   vector U.\n            \n            % TODO: Add support.\n            error('CHEBFUN:FOURDOUBLE:fred:notImplemented', ...\n                'FRED not implemented yet.')\n            \n        end\n        \n        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  VOLT  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        function u = volt(K, u)\n            %VOLT  Volterra operator with kernel K.\n            %   VOLT(K, U) computes the action of the Volterra operator with\n            %   kernel K on the Chebyshev interpolant to the points in the\n            %   vector U.\n            \n            % TODO: Add support.\n            error('CHEBFUN:FOURDOUBLE:volt:notImplemented', ...\n                'VOLT not implemented yet.')\n            \n        end\n\n        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  FEVAL  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        function out = feval(u, y)\n            %FEVAL  Evaluate polynomial interpolant of data {X_four, U} at a\n            % point y using barycentric interpolation.\n            \n            persistent dom x\n            \n            n = length(u.values);\n            udom = u.domain;\n            \n            if ( length(x) ~= n || isempty(dom) || ~all(dom == udom) )\n                x = trigpts(n, dom);\n                dom = udom;\n            end\n            \n            out = trigBary(y, u.values, x, udom);\n\n        end\n                \n    end\n    \nend\n\n\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/trigdouble.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.5580146835178804}}
{"text": "[K u] = sphere_wp;\nh=trisurf(K,u(:,1),u(:,2),u(:,3));\nset(h,'FaceColor',[0.7 0.7 0.7],'EdgeColor','none','FaceLighting','gouraud');\naxis equal;\nlight('Position',[1 -1 0],'Style','infinite');\n% light('Position',[10 10 10],'Style','infinite');\nxlim([-2,10]);\nylim([-2,2]);\nzlim([-2,2]);\n\n% animation loop:\nu0=u;\nfor t=0:0.02:5\n    R=1+0.2*sin(10*t); % change radius\n    x=0+4+3*sin(8.1234*t); % change x position\n    u=R*u0;\n    u(:,1)=u(:,1)+x;\n    set(h,'Vertices',u);\n    drawnow;\n    pause(1/50);\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/25711-sphere-without-poles/animation_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5579394149869401}}
{"text": "function [h, compUpJV] =  lfmComputeH3JV(gamma1_p, gamma1_m, sigma2, t1, ...\n    t2, preFactor, mode)\n\n% LFMCOMPUTEH3JV Helper function for computing part of the LFMJV kernel.\n% FORMAT\n% DESC computes a portion of the LFMJV kernel.\n% ARG gamma1 : Gamma value for first system.\n% ARG gamma2 : Gamma value for second system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG preFactor : precomputed constants.\n% ARG mode: indicates the correct derivative.\n% RETURN h : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio Alvarez, 2010\n\n% KERN\n\n% Evaluation of h\n\nif nargout>1\n    compUpJV{1} = lfmjvComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode);\n    compUpJV{2} = lfmjvComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\n    h = preFactor(1)*compUpJV{1} + preFactor(2)*compUpJV{2};\nelse\n    h = preFactor(1)*lfmjvComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode) ...\n        + preFactor(2)*lfmjvComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\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/lfmComputeH3JV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.557939404325143}}
{"text": "function output = calc_traversal_dist(ai)\n\n% This function will generate position coordinates of chain code (ai). Number of \n% harmonic elements (n), and number of points for reconstruction (m) must be \n% specified.  \n\n    x_ = 0;\n    y_ = 0;\n    \n    for i = 1 : size(ai, 2)        \n        x_ = x_ + sign(6 - ai(i)) * sign(2 - ai(i));\n        y_ = y_ + sign(4 - ai(i)) * sign(ai(i));\n        p(i, 1) = x_;\n        p(i, 2) = y_;\n    end\n    \n    output = p;\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/32800-elliptic-fourier-for-shape-analysis/calc_traversal_dist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5579393994017181}}
{"text": "function xDup=dupEls(x,numTimes)\n%%DUPELS Return a vector with the elements of the vector x duplicated \n%        numTimes.\n%\n%INPUTS: x A vectors whose elements are to be duplicated.\n% numTimes The number of times the elements in x are to be duplicated.\n%\n%OUTPUTS: xDup A vector the same orientation (row or column vector) as x\n%              where the elements of x have been duplicated numTimes. For\n%              example, if x=[1;2;3], then dupEls(x,3) returns\n%              [1;1;1;2;2;2;3;3;3].\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nxDim=length(x);\nxDup=zeros(xDim*numTimes,1);\n\n%If the input was a row vector.\nif(size(x,1)==1)\n    xDup=xDup';\nend\n\nsel=(0:(xDim-1))*numTimes;\nfor curDup=1:numTimes\n    xDup(sel+curDup)=x;\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/Misc/dupEls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.5579393969400056}}
{"text": "function [r, s] = randInt(rangeNums, dimensions)\n    start = rangeNums(1);\n    last = rangeNums(2);\n    r = start + (last - start) * rand(dimensions);\n    r = round(r);\n    s = sum(sum(r));\nend", "meta": {"author": "anishLearnsToCode", "repo": "introduction-to-programming-with-matlab", "sha": "4eb0dfab3f41b8a20d890e8d01a9e9b7463de410", "save_path": "github-repos/MATLAB/anishLearnsToCode-introduction-to-programming-with-matlab", "path": "github-repos/MATLAB/anishLearnsToCode-introduction-to-programming-with-matlab/introduction-to-programming-with-matlab-4eb0dfab3f41b8a20d890e8d01a9e9b7463de410/week-5/randInt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5579059155038895}}
{"text": "function A = HALS_spatial_thresh(Y, A, C, active_pixel, maxIter, sn)\n%% run HALS by fixating all spatial components \n% input: \n%   Y:  d*T, fluorescence data\n%   A:  d*K, spatial components \n%   C:  K*T, temporal components \n%   active_pixel, mask for pixels to be updated \n\n% output: \n%   A: d*K, updated spatial components \n\n% Author: Pengcheng Zhou, Carnegie Mellon University, adapted from Johannes\n% Friedrich's NIPS paper \"Fast Constrained Non-negative Matrix\n% Factorization for Whole-Brain Calcium Imaging Data\n\n%% options for HALS\nif nargin<5;    maxIter = 1;    end   %maximum iteration number \nif nargin<4;    active_pixel=true(size(A));\nelseif isempty(active_pixel)\n    active_pixel = true(size(A)); \nelse\n    active_pixel = logical(active_pixel); \nend     %determine nonzero pixels \nif ~exist('sn', 'var')||isempty(sn)\n    sn = GetSn(Y); \nend\nsn = reshape(sn, [], 1); \n%% initialization \nA(~active_pixel) = 0; \nK = size(A, 2);     % number of components \nCmean = mean(C,2); \nYmean = mean(Y,2); \nT = size(C,2); \nU = double(Y*C'-T*(Ymean*Cmean')); \nV = double(C*C'-T*(Cmean*Cmean')); \ncc = diag(V);   % squares of l2 norm all all components \ncc_thr = 3.0./sqrt(cc); \n\n%% updating \nfor miter=1:maxIter\n    for k=1:K\n        if cc(k)==0\n            continue; \n        end\n        tmp_ind = active_pixel(:, k); \n        if sum(tmp_ind)==0\n            A(:, k) = 0; \n            continue; \n        end\n        ak = A(tmp_ind, k)+(U(tmp_ind, k)-A(tmp_ind,:)*V(:, k))/cc(k);\n        ak(ak<sn(tmp_ind)*cc_thr(k)) = 0; \n        A(tmp_ind, k) = ak; \n    end\nend", "meta": {"author": "zhoupc", "repo": "CNMF_E", "sha": "ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f", "save_path": "github-repos/MATLAB/zhoupc-CNMF_E", "path": "github-repos/MATLAB/zhoupc-CNMF_E/CNMF_E-ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f/ca_source_extraction/utilities/HALS_spatial_thresh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.5579059011820937}}
{"text": "function ComparingSymmetry\n\nincPhi = pi/180;\n\n\nfileName = 'StressSymmetryTraction';\nsPnormT = computeExperiment(incPhi,fileName);\n\n\nfileName = 'StressSymmetryCompression';\nsPnormC = computeExperiment(-incPhi,fileName);\n\nend\n\nfunction sPnorm = computeExperiment(incPhi,fileName)\n\ntxi = pi/2 - 0.2;%1083;\nrho = 0.9;\nq = 4;\n\nphi = 0+incPhi;\npNorm = 'max';\nprint = false;\nhMesh = 0.01;\nhasToCaptureImage = true;\n\nmx = SuperEllipseParamsRelator.mx(txi,rho,q); \nmy = SuperEllipseParamsRelator.my(txi,rho,q);\n\ns.mx       = mx;\ns.my       = my;\ns.q        = q;\ns.phi      = phi;\ns.pNorm    = pNorm;\ns.print    = print;\ns.hMesh    = hMesh;\ns.fileName = fileName;\ns.hasToCaptureImage = false;\nsN = StressNormSuperEllipseComputer(s);\nsPnorm = sN.compute();\nsN.printStress();\n\n\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/Homogenization/Sources/VadamecumCalculator/ComparingSymmetry.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5579032891200975}}
{"text": "%returns the first component of the frequency representation of the signal\nclassdef SpectralEntropy < Algorithm\n    \n    methods (Access = public)\n        \n        function obj = SpectralEntropy()\n            obj.name = 'SpectralEntropy';\n            obj.inputPort = DataType.kSignal;\n            obj.outputPort = DataType.kFeature;\n        end\n        \n        %receives a power spectrum\n        function result = compute(~,powerSpectrum)\n            \n            %Normalization\n            sumPower = sum(powerSpectrum + 1e-12);\n            powerSpectrum = powerSpectrum / sumPower;\n            \n            %entropy calculation\n            result = -sum(powerSpectrum .* log2(powerSpectrum+eps));\n        end\n        \n        function metrics = computeMetrics(~,input)\n            n = size(input,1);\n            flops = 21 * n;\n            memory = n * 4;\n            outputSize = Constants.kFeatureBytes;\n            metrics = Metric(flops,memory,outputSize);\n        end\n    end\nend\n", "meta": {"author": "avenix", "repo": "WDK", "sha": "c525222b02bd390b4758d30f1cd8b19af043108e", "save_path": "github-repos/MATLAB/avenix-WDK", "path": "github-repos/MATLAB/avenix-WDK/WDK-c525222b02bd390b4758d30f1cd8b19af043108e/ARC/algorithm/6-featureExtraction/frequency domain/SpectralEntropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5579032872156092}}
{"text": "%%********************************************************************\n%% blkbarrier: calculate \n%% [-v(p)*logdet(X{p}),   v(p)*logdet(Z{p}) + n*v(p)*(1-log(v(p)))]\n%% [-v(p)*log(gam(X{p})), v(p)*log(gam(Z{p})) + v(p)]\n%% [-v(p)*log(X{p}),      v(p)*log(Z{p}) + n*v(p)*(1-log(v(p)))]\n%%********************************************************************\n\n  function objadd = blkbarrier(blk,X,Z,Xchol,Zchol,v); \n\n   objadd = zeros(1,2); tmp = zeros(1,2); \n   for p = 1:size(blk,1)\n      pblk = blk(p,:);\n      vp = v{p};\n      idx = find(vp > 0);   \n      if ~isempty(idx) \n         vpsub = vp(idx); \n         if size(vpsub,1) < size(vpsub,2); vpsub = vpsub'; end\n         if strcmp(pblk{1},'s')\n            ss = [0, cumsum(pblk{2})]; \n            logdetX = 2*log(diag(Xchol{p})); \n            logdetZ = 2*log(diag(Zchol{p})); \n            logdetXsub = zeros(length(idx),1); \n            logdetZsub = zeros(length(idx),1); \n            for k = 1:length(idx)\n               idxtmp = [ss(idx(k))+1:ss(idx(k)+1)]; \n               logdetXsub(k) = sum(logdetX(idxtmp)); \n               logdetZsub(k) = sum(logdetZ(idxtmp)); \n            end\n            tmp(1) = -sum(vpsub.*logdetXsub); \n            tmp(2) = sum(vpsub.*logdetZsub + (pblk{2}(idx)').*vpsub.*(1-log(vpsub))); \n         elseif strcmp(pblk{1},'q')\n            gamX = sqrt(qops(pblk,X{p},X{p},2)); \n            gamZ = sqrt(qops(pblk,Z{p},Z{p},2)); \n            tmp(1) = -sum(vpsub.*log(gamX(idx))); \n            tmp(2) = sum(vpsub.*log(gamZ(idx)) + vpsub); \n         elseif strcmp(pblk{1},'l')\n            logX = log(X{p}); logZ = log(Z{p});\n            tmp(1) = -sum(vpsub.*logX(idx)); \n            tmp(2) = sum(vpsub.*logZ(idx) + vpsub.*(1-log(vpsub))); \n         end \n         objadd = objadd + tmp; \n      end\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/Solver/blkbarrier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.557880030309497}}
{"text": "function [ class, clsize, critvl, ntrans, ifault ] = swap ( varval, class, ...\n  clsize, in, ik, iv, critvl, ntrans, ifault )\n\n%*****************************************************************************80\n%\n%% SWAP interchanges objects between different classes to improve a criterion.\n%\n%  Discussion:\n%\n%    This routine is given a classification of objects, including the\n%    number of objects in each class, and the current value of some criterion\n%    which is desired to be minimized.\n%\n%    The routine calculates the change in criterion for all possible swaps,\n%    that is, operations in which two objects in different classes exchange\n%    places. Each swap that would result in a lowering of the criterion is\n%    executed, and the related quantities are updated.\n%\n%    When no more advantageous swaps can be found, the routine returns.\n%\n%    The routine relies on a user-supplied routine, CRSWAP, to report the\n%    expected change in the criterion for a given swap, and to carry\n%    out that transfer if requested.\n%\n%    The variables CLASS and CRITVL have been added to the argument list\n%    of CRSWAP.\n%\n%    Also, the order of the two classes \"L\" and \"M\" was interchanged in\n%    the call to CRSWAP.  The original order was counterintuitive.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    18 February 2008\n%\n%  Author:\n%\n%    Original FORTRAN77 version by Banfield, Bassill.\n%    MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Colin Banfield, LC Bassill,\n%    Algorithm AS 113:\n%    A transfer for non-hierarchichal classification,\n%    Applied Statistics,\n%    Volume 26, Number 2, 1977, pages 206-210.\n%\n%  Parameters:\n%\n%    Input, real VARVAL(IN,IV), the data values.  There are\n%    IN objects, each having spatial dimension IV.\n%\n%    Input, integer CLASS(IN), the initial classification of\n%    each object.\n%\n%    Input, integer CLSIZE(IK), the initial number of objects\n%    in each class.\n%\n%    Input, integer IN, the number of objects.\n%\n%    Input, integer IK, the number of classes.\n%\n%    Input, integer IV, the number of spatial dimensions,\n%    or variates, of the objects.\n%\n%    Input, real CRITVL, the initial value of the criterion.\n%\n%    Output, integer CLASS(IN), the classification of\n%    each object.\n%\n%    Output, integer CLSIZE(IK), the number of objects\n%    in each class.\n%\n%    Output, real CRITVL, the current value of the criterion.\n%\n%    Output, integer NTRANS, the number of transfers executed.\n%\n%    Output, integer IFAULT, error indicator.\n%    0, no error detected.\n%    1, the number of classes was less than 2.\n%    2, the number of objects was less than the number of classes.\n%\n  eps = 1.0E-38;\n  ntrans = 0;\n\n  if ( ik <= 1 )\n    ifault = 1\n    return\n  end\n\n  if ( in <= ik )\n    ifault = 2;\n    return\n  end\n\n  ifault = 0;\n  icount = 0;\n  itop = ( in * ( in - 1 ) ) / 2;\n\n  i = 1;\n\n  while ( 1 )\n\n    i = i + 1;\n\n    if ( itop <= icount )\n      break\n    end\n\n    if ( in < i )\n      i = 1;\n      continue\n    end\n\n    l = class(i);\n    k = l;\n    it = i - 1;\n%\n%  Test the swap of object I from class M to L,\n%  and object J from class L to M.\n%\n    for j = 1 : it\n\n      icount = icount + 1;\n      m = class(j);\n\n      if ( l ~= j )\n\n        if ( clsize(l) ~= 1 | clsize(m) ~= 1 )\n\n          iswitch = 1;\n          inc = crswap ( varval, class, clsize, in, ik, iv, critvl, ...\n            i, j, l, m, iswitch );\n\n          if ( inc < - eps )\n\n            critvl = critvl + inc;\n            icount = 0;\n\n            iswitch = 2;\n            crswap ( varval, class, clsize, in, ik, iv, critvl, ...\n              i, j, l, m, iswitch );\n\n            ntrans = ntrans + 1;\n            class(i) = m;\n            class(j) = l;\n            l = m;\n\n          end\n\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/asa113/swap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.5578429588192985}}
{"text": "function jrt=jacprojRT(j, i, rt, xyz, r0, a)\n% symbolic projection function Jacobian\n% code automatically generated with maple\n\n  qr0=r0(j*4+1:(j+1)*4);\n\n  t1 = (rt(1) ^ 2);\n  t2 = (rt(2) ^ 2);\n  t3 = (rt(3) ^ 2);\n  t5 = sqrt((1 - t1 - t2 - t3));\n  t6 = 0.1e1 / t5;\n  t7 = t6 * qr0(2);\n  t9 = -t7 * rt(1) + qr0(1);\n  t11 = t6 * qr0(3);\n  t13 = -t11 * rt(1) - qr0(4);\n  t15 = t6 * qr0(4);\n  t17 = -t15 * rt(1) + qr0(3);\n  t19 = -t9 * xyz(1) - t13 * xyz(2) - t17 * xyz(3);\n  t24 = -t5 * qr0(2) - qr0(1) * rt(1) - rt(2) * qr0(4) + rt(3) * qr0(3);\n  t31 = t5 * qr0(3) + qr0(1) * rt(2) + rt(3) * qr0(2) - rt(1) * qr0(4);\n  t37 = t5 * qr0(4) + qr0(1) * rt(3) + rt(1) * qr0(3) - rt(2) * qr0(2);\n  t39 = t24 * xyz(1) - t31 * xyz(2) - t37 * xyz(3);\n  t41 = t6 * qr0(1);\n  t43 = -t41 * rt(1) - qr0(2);\n  t48 = t5 * qr0(1) - rt(1) * qr0(2) - rt(2) * qr0(3) - rt(3) * qr0(4);\n  t52 = t48 * xyz(1) + t31 * xyz(3) - t37 * xyz(2);\n  t57 = t43 * xyz(1) + t13 * xyz(3) - t17 * xyz(2);\n  t62 = t43 * xyz(2) + t17 * xyz(1) - t9 * xyz(3);\n  t67 = t48 * xyz(2) + t37 * xyz(1) + t24 * xyz(3);\n  t72 = t43 * xyz(3) + t9 * xyz(2) - t13 * xyz(1);\n  t77 = t48 * xyz(3) - t24 * xyz(2) - t31 * xyz(1);\n  t89 = -t19 * t31 - t39 * t13 + t43 * t67 + t48 * t62 + t72 * t24 - t77 * t9 + t57 * t37 + t52 * t17;\n  t99 = -t19 * t37 - t39 * t17 + t43 * t77 + t48 * t72 - t57 * t31 - t52 * t13 - t62 * t24 + t67 * t9;\n  t106 = -t39 * t37 + t48 * t77 - t52 * t31 - t67 * t24 + rt(6);\n  t107 = 0.1e1 / t106;\n  t119 = -t39 * t31 + t48 * t67 + t77 * t24 + t52 * t37 + rt(5);\n  t123 = t106 ^ 2;\n  t124 = 0.1e1 / t123;\n  t125 = (a(1) * (t39 * t24 + t48 * t52 - t67 * t37 + t77 * t31 + rt(4)) + a(2) * t119 + a(3) * t106) * t124;\n  t129 = -t7 * rt(2) + qr0(4);\n  t132 = -t11 * rt(2) + qr0(1);\n  t135 = -t15 * rt(2) - qr0(2);\n  t137 = -t129 * xyz(1) - t132 * xyz(2) - t135 * xyz(3);\n  t141 = -t41 * rt(2) - qr0(3);\n  t146 = t141 * xyz(1) + t132 * xyz(3) - t135 * xyz(2);\n  t151 = t141 * xyz(2) + t135 * xyz(1) - t129 * xyz(3);\n  t157 = t141 * xyz(3) + t129 * xyz(2) - t132 * xyz(1);\n  t170 = -t137 * t31 - t39 * t132 + t141 * t67 + t48 * t151 + t157 * t24 - t77 * t129 + t146 * t37 + t52 * t135;\n  t180 = -t137 * t37 - t39 * t135 + t141 * t77 + t48 * t157 - t146 * t31 - t52 * t132 - t151 * t24 + t67 * t129;\n  t187 = -t7 * rt(3) - qr0(3);\n  t190 = -t11 * rt(3) + qr0(2);\n  t193 = -t15 * rt(3) + qr0(1);\n  t195 = -t187 * xyz(1) - t190 * xyz(2) - t193 * xyz(3);\n  t199 = -t41 * rt(3) - qr0(4);\n  t204 = t199 * xyz(1) + t190 * xyz(3) - t193 * xyz(2);\n  t209 = t199 * xyz(2) + t193 * xyz(1) - t187 * xyz(3);\n  t215 = t199 * xyz(3) + t187 * xyz(2) - t190 * xyz(1);\n  t228 = -t195 * t31 - t39 * t190 + t199 * t67 + t48 * t209 + t215 * t24 - t77 * t187 + t204 * t37 + t52 * t193;\n  t238 = -t195 * t37 - t39 * t193 + t199 * t77 + t48 * t215 - t204 * t31 - t52 * t190 - t209 * t24 + t67 * t187;\n  t255 = (a(4) * t119 + a(5) * t106) * t124;\n  jrt(1) = (a(1) * (t19 * t24 - t39 * t9 + t43 * t52 + t48 * t57 - t62 * t37 - t67 * t17 + t72 * t31 + t77 * t13) + a(2) * t89 + a(3) * t99) * t107 - t125 * t99;\n  jrt(2) = (a(1) * (t137 * t24 - t39 * t129 + t141 * t52 + t48 * t146 - t151 * t37 - t67 * t135 + t157 * t31 + t77 * t132) + a(2) * t170 + a(3) * t180) * t107 - t125 * t180;\n  jrt(3) = (a(1) * (t195 * t24 - t39 * t187 + t199 * t52 + t48 * t204 - t209 * t37 - t67 * t193 + t215 * t31 + t77 * t190) + a(2) * t228 + a(3) * t238) * t107 - t125 * t238;\n  jrt(4) = a(1) * t107;\n  jrt(5) = a(2) * t107;\n  jrt(6) = a(3) * t107 - t125;\n  jrt(7) = (a(4) * t89 + a(5) * t99) * t107 - t255 * t99;\n  jrt(8) = (a(4) * t170 + a(5) * t180) * t107 - t255 * t180;\n  jrt(9) = (a(4) * t228 + a(5) * t238) * t107 - t255 * t238;\n  jrt(10) = 0.0e0;\n  jrt(11) = a(4) * t107;\n  jrt(12) = a(5) * t107 - t255;\n", "meta": {"author": "vrabaud", "repo": "sfm_toolbox", "sha": "7ce933b31b71292eddabb40bacfd619720fa221d", "save_path": "github-repos/MATLAB/vrabaud-sfm_toolbox", "path": "github-repos/MATLAB/vrabaud-sfm_toolbox/sfm_toolbox-7ce933b31b71292eddabb40bacfd619720fa221d/external/sba/matlab/jacprojRT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5578393133405843}}
{"text": "%% ARDRONE TEST\n\n% Author: James A. Douthwaite\n\nclassdef ARdrone_LQR < ARdrone_prev\n%% INITIALISE THE AGENT SPECIFIC PARAMETERS\n    % LQR SPECIFIC PARAMETERS\n    properties\n\n    end\n    %% ///////////////////////// MAIN METHODS /////////////////////////////\n    methods \n        % Constructor\n        function this = ARdrone_LQR(varargin)\n            \n            % Call the super class\n            this@ARdrone_prev(varargin);                                         % Create the super class 'agent'                  \n             \n            % DYNAMIC CONSTRAINTS\n            this.v_nominal = 2.0; \n            this.v_max = 3;\n            \n            % Append control parameter\n            %obj.DYNAMICS.Q = diag([1 1 1 1 1 1 2 1 1 1 1 1])*1.5E1;\n            this.DYNAMICS.Q = diag([1 1 1 1 1 1 1 1 1 1 1 1])*1.5E1;\n            this.DYNAMICS.R = diag(ones(4,1))*1E-4;     \n            this.DYNAMICS.N = zeros(size(this.DYNAMICS.SS.B));        % Terminal input penalisation     \n                        \n            % Calculate the linear feedback from the LQR\n            this.DYNAMICS.K_lqr = this.CreateController_LQR(...\n                this.DYNAMICS.SS,...\n                this.DYNAMICS.Q,...\n                this.DYNAMICS.R,...\n                this.DYNAMICS.N);\n      \n            % //////////////// Check for user overrides ///////////////////            \n            % - It is assumed that overrides to the properties are provided\n            %   via the varargin structure.\n            [this] = this.ApplyUserOverrides(varargin); % Recursive overrides \n            % /////////////////////////////////////////////////////////////\n        end\n        % Setup\n        % - The same as any 2D/3D object\n        % Main \n        function this = main(this,ENV,varargin)\n            % INPUTS:\n            % varargin - Cell array of inputs\n            % >dt      - The timestep\n            % >objects - The detectable objects cell array of structures\n            % OUTPUTS:\n            % obj      - The updated project\n\n            % //////////// CHECK FOR NEW INFORMATION UPDATE ///////////////\n            % UPDATE THE AGENT WITH THE NEW ENVIRONMENTAL INFORMATION\n            this = this.GetAgentUpdate(ENV,varargin{1});\n            \n            % /////////////////// WAYPOINT TRACKING ///////////////////////\n            % Get desired heading\n            desiredHeadingVector = this.GetTargetHeading();\n            desiredVelocity = desiredHeadingVector*this.v_nominal;\n            \n            % Express velocity vector in NED coordinates\n            if ENV.currentTime <= 1\n                desiredVelocity = zeros(3,1);\n            end\n            \n            p_wp = this.targetWaypoint.position(:,this.targetWaypoint.sampleNum);\n            \n            % Convert from 'xyz' to 'ned'\n%             desiredVelocity = enu2ned(desiredVelocity);\n%             desiredNEDstate = [p_wp;zeros(3,1);zeros(6,1)];\n            \n            % LQR controller update\n            this = this.Controller_position(ENV,enu2ned(p_wp));\n            \n%             this = this.Controller_velocity(ENV,enu2ned(desiredVelocity));\n            \n            % \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ RECORD THE AGENT-SIDE DATA \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n            this.DATA.inputNames = {'$\\dot{x}$ (m/s)','$\\dot{y}$ (m/s)','$\\dot{z}$ (m/s)',...\n                                   '$\\dot{\\phi}$ (rad/s)','$\\dot{\\theta}$ (rad/s)','$\\dot{\\psi}$ (rad/s)'};\n            this.DATA.inputs(1:numel(this.DATA.inputNames),ENV.currentStep) = this.localState(7:end);          % Record the control inputs \n        end\n    end\n    \n    %% /////////////////////// AUXILLARY METHODS //////////////////////////\n    % CONTROLLER METHODS\n    methods\n        % ARdrone controller (local position)\n        function [this] = Controller_position(this,ENV,NEDposition)\n            \n            % CALCULATE THE NEW STATE REFERENCE\n            if ~this.IsIdle()\n                X_desired = [NEDposition;zeros(2,1);-this.localState(6);zeros(6,1)];  \n            else\n                % Idle reference\n                X_desired = [zeros(5,1);this.localState(6);zeros(6,1)];\n            end\n            \n            % /////////////////// AIRCRAFT DYNAMICS ///////////////////////\n            useLinearModel = false;\n            if ~useLinearModel\n                [this.localState] = this.UpdateNonLinearPlant(ENV,this.localState,X_desired);\n            else\n                [this.localState] = this.UpdateLinearPlant(ENV,this.localState,X_desired);         \n            end\n            \n            % \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ GLOBAL UPDATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n            this = this.GlobalUpdate_ARdrone(ENV.dt,this.localState);\n        end\n        % ARdrone controller (local velocity)\n        function [this] = Controller_velocity(this,ENV,NEDVelocity)\n            \n            % CALCULATE THE NEW STATE REFERENCE\n            if ~this.IsIdle()\n                X_desired = [zeros(5,1);this.localState(6);NEDVelocity;zeros(3,1)];  \n            else\n                % Idle reference\n                X_desired = [zeros(5,1);this.localState(6);zeros(6,1)];\n            end\n            \n            % /////////////////// AIRCRAFT DYNAMICS ///////////////////////\n            useLinearModel = false;\n            if ~useLinearModel\n                [this.localState] = this.UpdateNonLinearPlant(ENV,this.localState,X_desired);\n            else\n                [this.localState] = this.UpdateLinearPlant(ENV,this.localState,X_desired);         \n            end\n            \n            % \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ GLOBAL UPDATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n            this = this.GlobalUpdate_ARdrone(ENV.dt,this.localState);\n        end\n    end\n    methods (Static)\n        % Create an LQR controller (feedback gain)\n        function [K_lqr] = CreateController_LQR(SS,Q,R,N)\n            % This function designs the LQR controller used to provide\n            % error feedback.\n            \n            if nargin < 6\n                N = zeros(size(SS.B));\n            end\n            \n            % Get the LQR feedback             \n            [K_lqr,~,~] = lqr(SS,Q,R,N);   \n            \n            % IGNORE POSITION FEEDBACK\n            K_lqr(:,1:3) = 0;   % Omit position feedback\n            % IGNORE XY POSITION FEEDBACK\n%             K_lqr(:,1:2) = 0; % Omit XY position feedback\n            % IGNORE HEADING FEEDBACK\n%             K_lqr(:,6) = 0;  \n        end \n    end\n    % //////////////////////// MODELLING/DYNAMICS /////////////////////////\n    methods\n        % ODE45 - UPDATE NONLINEAR CLOSED LOOP DYNAMICS\n        function [X] = UpdateNonLinearPlant(this,TIME,X0,X_desired)\n            % This function computes the state update for the current agent\n            % using the ode45 function.\n            \n            % Input sanity check\n            assert(isstruct(TIME),'Expecting a time structure.');\n            \n            X = X0; % Default to no change\n            \n            % DETERMINE THE INTEGRATION PERIOD\n            if TIME.currentTime ~= TIME.timeVector(end)\n                % INTEGRATE THE DYNAMICS OVER THE TIME STEP \n                [~,Xset] = ode45(@(t,X) this.ARdrone_nonLinear_closedLoop(X,X_desired),...\n                    [0 TIME.dt],X0,odeset('RelTol',1e-2,'AbsTol',TIME.dt*1E-2));\n                X = Xset(end,:)';\n            end\n        end\n        % ODE45 - UPDATE LINEAR CLOSED LOOP DYNAMICS\n        function [X] = updateLinearPlant(this,TIME,X0,X_desired)\n            % This function computes the state update for the current agent\n            % using the ode45 function.\n            \n            % Input sanity check\n            assert(isstruct(TIME),'Expecting a time structure.');\n            \n            X = X0; % Default to no change\n            \n            % Check for the last time-step\n            if TIME.currentTime ~= TIME.timeVector(end) \n                % INTEGRATE THE DYNAMICS OVER THE TIME STEP\n                [~,Xset] = ode45(@(t,X) this.ARdrone_linear_closedLoop(X,X_desired),...\n                    [0 TIME.dt],X0,odeset('RelTol',1e-2,'AbsTol',TIME.dt*1E-2));\n                X = Xset(end,:)';\n            end\n        end\n    end\n    methods\n        % CLOSED-LOOP NONLINEAR DYNAMICS\n        function [dX] = ARdrone_nonLinear_closedLoop(this,X,X_desired)\n            % THE STATE ERROR\n            Xerror = X - X_desired;\n            % THE NOMINAL INPUT\n            [Uss] = this.ARdrone_nominalInput(X);\n            % GET THE NOMINAL INPUT + LQR FEEDBACK\n            U = Uss - this.DYNAMICS.K_lqr*Xerror;\n            % CALL THE OPENLOOP DYNAMICS\n            [dX] = this.ARdrone_nonLinear_openLoop(X,U);\n        end\n        % CLOSED-LOOP LINEAR DYNAMICS\n        function [dX] = ARdrone_linear_closedLoop(this,X,X_desired)\n            % THE STATE ERROR\n            Xerror = X - X_desired;\n            % GET THE NOMINAL INPUT + LQR FEEDBACK\n            dU = - this.DYNAMICS.K_lqr*Xerror;\n            % CALL THE OPENLOOP DYNAMICS\n            [dX] = this.ARdrone_linear_openLoop(X,dU);\n        end\n    end\nend\n% AGENT STATE VECTOR [x;y;z;psi;the;phi;v;u;w;p;q;r]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/objects/ARdrone_LQR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5577358307619165}}
{"text": "function results  = RS_DF_rstest(z);\n\nrvec = (0:0.001:1);\nP = size(z,1);\n\ncumcumz = [];    \nfor r = rvec\n    cumcumz = [cumcumz (z<r)-r];\nend\n\nv = sum(cumcumz,1)/sqrt(P);\n\nQv = []; Qvabs = [];\nfor rs = 1:size(rvec,2);\n    Qv = [Qv; v(1,rs)'*v(1,rs)]; \n    Qvabs = [Qvabs; abs(v(1,rs)')];\nend \n\nKv = max(Qvabs);\nCVMv = mean(Qv);\n\nresults(1,1) = Kv;\nresults(1,2) = CVMv;", "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/RS_DF_rstest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.557735829569889}}
{"text": "function mpe = find_mpe(engine, evidence)\n% FIND_MPE Find the most probable explanation (Viterbi)\n% mpe = enter_evidence(engine, evidence, ...)\n%\n% evidence{i,t} = [] if if X(i,t) is hidden, and otherwise contains its observed value (scalar or column vector)\n%\n\nobslik = mk_hmm_obs_lik_matrix(engine, evidence);\npath = viterbi_path(engine.startprob, engine.transprob, obslik);\nbnet = bnet_from_engine(engine);\nns = bnet.node_sizes_slice;\nns(bnet.observed) = 1;\nass = ind2subv(ns, path);\nmpe = num2cell(ass');\nmpe(bnet.observed,:) = evidence(bnet.observed,:);\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/inference/dynamic/@hmm_inf_engine/find_mpe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5577358252680704}}
{"text": "function [stats,Y,X] = spm_mci_mvnpost (post,method,verbose,max_lag)\n% Are MCMC samples consistent with Gaussian posterior ?\n% FORMAT [stats,Y,X] = spm_mci_mvnpost (post,method,verbose,max_lag)\n%\n% post      posterior data structure from spm_mci_post\n% method    'ESS' or 'thinning'\n% verbose   create plots\n% max_lag   maximum potential lag for MAR model\n% \n% stats     (multivariate) normal test statistics\n%           See spm_mci_mvntest.m\n% Y         uncorrelated posterior samples\n% X         original posterior samples\n% \n% Run Gaussianity test on Markov chain samples\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: spm_mci_mvnpost.m 6697 2016-01-27 14:57:28Z spm $\n\ntry, pmax=max_lag; catch, pmax=10; end\ntry, meth=method; catch, meth='ESS'; end\ntry, ver=verbose; catch, ver=1; end\n\n\nj=post.ind;\nX=post.P(:,j)';\nNj=length(j);\nNp=size(post.P,1);\n        \nif any(std(X)==0)\n    disp('Warning from spm_mci_mvnpost: some parameters have zero variance');\n    stats=[];\n    return\nend\n\nswitch meth\n    case 'ESS',\n        %C=cov(post.P(:,post.ind)');\n        for p=1:Np,\n            ess(p)=spm_mci_ess(post.P(p,j));\n            %v(p)=C(p,p)*ess(p)/Nj;\n        end\n        %post.Cp=diag(v);\n        %mess=mean(ess);\n        mess=ceil(min(ess));\n        stats = spm_mci_mvntest(X,mess);\n        \n        if ver\n            disp('ESS method');\n            disp('Effective Sample Sizes:');\n            disp(ess);\n        end\n        \n    case 'thinning',\n        for p=1:Np,\n            [tmp,m(p)]=spm_mci_ess(post.P(p,j));\n        end\n        lag=max(m)+1;\n        Y=X(1:lag:end,:);\n        stats = spm_mci_mvntest(Y);\n        if ver\n            disp('Thinning method');\n            disp(sprintf('Using only every %d-th sample',lag));\n        end\n        \n        \n    otherwise\n        disp('Unknown method in spm_mci_mvnpost.m');\n        return\nend", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/inference/spm_mci_mvnpost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5575859041020331}}
{"text": "function r8poly_print ( m, a, title )\n\n%*****************************************************************************80\n%\n%% R8POLY_PRINT prints out a polynomial.\n%\n%  Discussion:\n%\n%    The power sum form is:\n%\n%      p(x) = a(1) + a(2) * x + ... + a(m-1) * x^(m-1) + a(m) * x^(m-1)\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 February 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer M, the nominal degree of the polynomial.\n%\n%    Input, real A(1:M+1), the polynomial coefficients.\n%    A(1) is the constant term and\n%    A(M+1) is the coefficient of X^(M).\n%\n%    Input, string TITLE, a title.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '%s\\n', title );\n  fprintf ( 1, '\\n' );\n\n  if ( a(m+1) < 0.0 )\n    plus_minus = '-';\n  else\n    plus_minus = ' ';\n  end\n\n  mag = abs ( a(m+1) );\n\n  if ( 3 <= m + 1 )\n    fprintf ( 1, '  p(x) = %c%14g * x^%d\\n', plus_minus, mag, m );\n  elseif ( m + 1 == 2 )\n    fprintf ( 1, '  p(x) = %c%14g * x\\n', plus_minus, mag );\n  elseif ( m + 1 == 1 )\n    fprintf ( 1, '  p(x) = %c%14g\\n', plus_minus, mag );\n  end\n\n  for i = m : -1 : 1\n\n    if ( a(i) < 0.0 )\n      plus_minus = '-';\n    else\n      plus_minus = '+';\n    end\n\n    mag = abs ( a(i) );\n\n    if ( mag ~= 0.0 )\n\n      if ( 3 <= i )\n        fprintf ( 1, '         %c%14g * x^%d\\n', plus_minus, mag, i-1 );\n      elseif ( i == 2 )\n        fprintf ( 1, '         %c%14g * x\\n', plus_minus, mag );\n      elseif ( i == 1 )\n        fprintf ( 1, '         %c%14g\\n', plus_minus, mag );\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/r8lib/r8poly_print.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.5575858936646548}}
{"text": "function group = GroupDV(Problem,DV,PV,nPerGroup)\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 Huangke Chen\n\n   ub  = Problem.upper(DV);\n   lb  = Problem.lower(DV); \n   dim = length(DV);\t% the dim of the distance variables\n   \n   fixPV  = (Problem.lower(PV)+Problem.upper(PV))/2;\t% the value vector for position variables\n   meanDV = (ub+lb)/2;\n   \n   f_archiveF = repmat(zeros(dim,dim),1,Problem.M);\t% cell(dim, dim);\n   \n   fhatDVDecs     = repmat(lb,dim,1) + eye(dim).*repmat(meanDV,dim,1);\n   fhatDecs       = [repmat(fixPV,dim,1) fhatDVDecs];\n   fhatPopulation = Problem.Evaluation(fhatDecs);\n   fhat_archiveF  = fhatPopulation.objs;\n   \n   lambdaF = repmat(zeros(dim,dim),1,Problem.M);\t% cell(dim, dim);\n   \n   p1Dec   = [fixPV lb]; \n   tempFp1 = Problem.Evaluation(p1Dec);\n   fp1F    = tempFp1.objs;\n   \n   for i = 1 : dim-1      \n       fp2 = fhat_archiveF(i,:);\n       for j = i+1 : dim\n           \n           fp3 = fhat_archiveF(j,:);\n\n           p4      = lb;\n           p4(i)   = meanDV(i);\t% temp;\n           p4(j)   = meanDV(j);\t% temp;\n           p4Dec   = [fixPV p4];\n           tempFp4 = Problem.Evaluation(p4Dec);\n           fp4     = tempFp4.objs;\n           \n           f_archiveF(i,j:dim:size(f_archiveF,2)) = fp4;\n\n           d1 = fp2 - fp1F;\n           d2 = fp4 - fp3;\n           \n           lambdaF(i,j:dim:size(lambdaF,2)) = abs(d1-d2);\n       end\n   end\n   \n   % Check for each objective\n   bigTheta = false(length(DV));\n   \n   for i = 1 : Problem.M\n       \n       lambda = lambdaF(:,(i-1)*dim+1:i*dim);\n       fp1    = fp1F(i);\n       \n       fhat_archive = fhat_archiveF(:,i);\n       \n       tempF_archive = f_archiveF(:,(i-1)*dim+1:i*dim);\n       f_archive     = tempF_archive + tempF_archive';\n       \n       F1 = ones(dim,dim)*fp1;\n       F2 = repmat(fhat_archive',dim,1);\n       F3 = repmat(fhat_archive,1,dim);\n       F4 = f_archive;\n       \n       FS   = cat(3,F1,F2,F3,F4);\n       Fmax = max(FS,[],3);\n       \n       FS       = cat(3,F1+F4,F2+F3);\n       Fmax_inf = max(FS,[],3);\n\n       theta = false(dim);\n\n       muM       = eps/2;\n       gamma     = @(n)((n.*muM)./(1-n.*muM));\n       errlb     = gamma(2)*Fmax_inf;\n       errub     = gamma(dim^0.5)*Fmax;\n       I2        = lambda >= errub;\n       theta(I2) = 1;\n       \n       % add, then find not less than 1\n       bigTheta = bigTheta + theta;\n   end\n   \n   bigTheta(bigTheta>0) = true;\n\n   L = size(bigTheta,1);\t% number of vertex\n   \n   % Breadth-first search\n   labels = zeros(1,L);     % all vertex unexplored at the begining\n   rts    = [];\n   ccc    = 0;              % connected components counter\n   while 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(bigTheta(p,:));\t% 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\n   end\n   \n   group_num = max(labels);\n   allgroups = cell(1,group_num);\n   for i = 1 : group_num\n       allgroups{i} = find(labels==i);\n   end\n   \n   h = @(x)(length(x)==1);\n   sizeone = cellfun(h,allgroups);\n   \n   seps = allgroups(sizeone);\n   seps = cell2mat(seps);\n   \n   allgroups(sizeone) = [];\n   nonseps            = allgroups;\n\n   group = {};\n   for ns = 1 : length(nonseps)     % the non-seperate variables\n       group = {group{1:end} DV(nonseps{ns})};\n   end\n\n   for g = 1 : nPerGroup : length(seps)\n       index = seps(g:min(g+nPerGroup-1,length(seps)));\n       group = {group{1: end} DV(index)};\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/S3-CMA-ES/GroupDV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5575858936646547}}
{"text": "function hermite_poly_phys_values_test ( )\n\n%*****************************************************************************80\n%\n%% HERMITE_POLY_PHYS_VALUES_TEST demonstrates the use of HERMITE_POLY_PHYS_VALUES.\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  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'HERMITE_POLY_PHYS_VALUES_TEST:\\n' );\n  fprintf ( 1, '  HERMITE_POLY_PHYS_VALUES stores values of\\n' );\n  fprintf ( 1, '  the physicist''s Hermite polynomials.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '     N      X            H(N,X)\\n' );\n  fprintf ( 1, '\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, n, x, fx ] = hermite_poly_phys_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fprintf ( 1, '  %4d  %12f  %24.16e\\n', n, x, fx );\n\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/hermite_poly_phys_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.5575858905550046}}
{"text": "function [m, maxnum] = mymode(x)\n% computes the mode of x (the most commonly occuring value)\n% x must be discrete and numeric\n% if several values tie for frequency of occurance, each will be returned\n% m - the most common value\n% maxnum - the number of times that x==m\n\n[g, gn] = grp2idx(x);\nmaxnum = 0;\nm = [];\nfor i = 1:length(gn)\n    count = sum(g==i);\n    if count > maxnum\n        maxnum = count;\n        m = str2num(gn{i});\n        c = 1;\n    elseif count == maxnum\n        m(c+1) = str2num(gn{i});\n        c = c + 1;\n    end\nend\n\nm = sort(m);", "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/mymode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.5574834129897721}}
{"text": "function s = logsumexp(a, dim)\n% Returns log(sum(exp(a),dim)) while avoiding numerical underflow.\n% Default is dim = 1 (columns).\n% logsumexp(a, 2) will sum across rows instead of columns.\n% Unlike matlab's \"sum\", it will not switch the summing direction\n% if you provide a row vector.\n\n% Written by Tom Minka\n% (c) Microsoft Corporation. All rights reserved.\n\nif nargin < 2\n  dim = 1;\nend\n\n% subtract the largest in each column\n[y, i] = max(a,[],dim);\ndims = ones(1,ndims(a));\ndims(dim) = size(a,dim);\na = a - repmat(y, dims);\ns = y + log(sum(exp(a),dim));\ni = find(~finite(y));\nif ~isempty(i)\n  s(i) = y(i);\nend\n", "meta": {"author": "FuzhenZhuang", "repo": "Transfer-Learning-Toolkit", "sha": "24b5323b354aee844b8b7df9fcad17fdfb191dc4", "save_path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit", "path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit/Transfer-Learning-Toolkit-24b5323b354aee844b8b7df9fcad17fdfb191dc4/utilities/TLLibrary64/LR/lightspeed/logsumexp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5574833992765087}}
{"text": "function vrot=givapp(c,s,vin,k)\n%givapp   apply a sequence of Givens rotations\n%   input\n%          c, s      vectors of length k-1 defining rotations\n%          vin       vector of length k to which rotations are applied\n%          k         k-1 = number of rotations\n%   output\n%          tranformed vector after rotations are applied\n% called by gmres_r\n%   IFISS function: HCE; 15 March 2005.\n\n% \n%  C. T. Kelley, July 10, 1994\n%Copyright 1994 C. T. Kelley.  \n%Reproduced and distributed with permission of the copyright holder.\n%\n% This code comes with no guarantee or warranty of any kind.\n%\n%  function vrot=givapp(c, s, vin, k)\n%\nvrot=vin;\nfor i=1:k\n    w1=c(i)*vrot(i)-s(i)*vrot(i+1);        % Change on next line, 6/3/97\n    w2=s(i)*vrot(i)+conj(c(i))*vrot(i+1);  % w2=s(i)*vrot(i)+c(i)*vrot(i+1);\n    vrot(i:i+1)=[w1,w2];\nend\n", "meta": {"author": "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/givapp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5574833916033682}}
{"text": "function test_triangulation_test02 ( )\n\n%*****************************************************************************80\n%\n%% TEST02 tests P00_TEST_NUM and P00_SAMPLE.\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  m = 2;\n  seed_start = 123456789;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST02\\n' );\n  fprintf ( 1, '  P00_TEST_NUM reports the number of problems.\\n' );\n  fprintf ( 1, '  P00_SAMPLE returns sample points from the region.\\n' );\n\n  test_num = p00_test_num ( );\n\n  for test = 1 : test_num\n\n    seed = seed_start;\n\n    title = p00_title ( test );\n\n    n = 20;\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Test number         =  %d\\n', test );\n    fprintf ( 1, '  Title:              = \"%s\"\\n', title );\n    fprintf ( 1, '  Spatial dimension M =  %d\\n', m );\n    fprintf ( 1, '  Number of samples N =  %d\\n', n );\n    fprintf ( 1, '  Initial SEED:       =  %d\\n', seed );\n    fprintf ( 1, '\\n' );\n\n    [ point, seed ] = p00_sample ( test, m, n, seed );\n\n    r8mat_transpose_print ( m, n, point, '  The sample points:' );\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/test_triangulation_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.5574833870322804}}
{"text": "clear all;\nclose all;\nclc;\nexport = true;\nconfigs = cell(1, 5);\nconfigs{1} = create_config([1 1 1 1 1 1], 4, '1-4');\nconfigs{2} = create_config([2 1 1 1 1 1], 4, '2.1-4');\nconfigs{3} = create_config([4 2 1 1 1 1], 4, '42.1-4');\nconfigs{4} = create_config([2 2 2 2 2 2], 4, '2-4');\nconfigs{5} = create_config([2 2 2 2 2 2], 8, '2-8');\n\nnc = numel(configs);\n\npoints = [150  275  490  885 1600 2885 5205 9400 16980];\nnns = numel(points);\nclustering_acc_perc_mat = zeros(nc, nns);\nspr_perc_mat = zeros(nc, nns);\nspr_error_perc_mat = zeros(nc, nns);\n\nfor c=1:nc\n    config = configs{c};\n    if isempty(config)\n        continue;\n    end\n    solver_name = sprintf('ssc_mc_omp_%s', config.name);\n    filepath = sprintf('bin/solver_%s.mat', solver_name);\n    load(filepath);\n\n    clustering_acc_perc_mat(c, :)  = result.clustering_acc_perc_arr;\n    spr_perc_mat(c, :) = result.spr_perc_arr;\n    spr_error_perc_mat(c, :) = 100 * result.spr_error_arr;\n    fprintf('%s Points: \\n', solver_name);\n    fprintf('%4d ', result.num_points_arr);\n    fprintf('\\n');\n\n    fprintf('Accuracy: \\n');\n    fprintf('%.2f ', result.clustering_acc_perc_arr);\n    fprintf('\\n');\n\n    % plot_bench_results(result, solver_name);\nend\n\nlegends = {'OMP', 'MC-OMP 2.1-4', 'MC-OMP 42.1-4', 'MC-OMP 2-4', 'MC-OMP 2-8'};\n\nfprintf('\\n\\nAccuracy: \\n');\ndisp(clustering_acc_perc_mat);\n\nfprintf('\\nSubspace preserving representations: \\n');\ndisp(spr_perc_mat);\n\nfprintf('\\nSubspace representation error: \\n');\ndisp(spr_error_perc_mat);\n\n\nstyles = spx.graphics.plot_styles();\nmf = spx.graphics.Figures;\nmf.new_figure('Clustering Accuracy');\nfor c=1:nc\n    style = styles{c};\n    plot(points, clustering_acc_perc_mat(c, :), style);\n    hold on;\nend\nxlabel('Points');\nylabel('Clustering accuracy (%)');\nylim([40 100]);\ngrid on;\nlegend(legends, 'Location', 'SouthEast');\nif export\nset(gcf, 'units', 'inches', 'position', [.8 .8 4 3]);\nset(gca,'FontSize',8);\nset(findall(gcf,'type','text'),'FontSize',8);\nexport_fig plots/clustering_accuracy.png -r120 -nocrop;\nexport_fig plots/clustering_accuracy.pdf;\nend\n\nmf.new_figure('Subspace preserving representations');\nfor c=1:nc\n    style = styles{c};\n    plot(points, spr_perc_mat(c, :), style);\n    hold on;\nend\nxlabel('Points');\nylabel('Subspace preserving representation percentage (%)');\nylim([0 100]);\ngrid on;\nlegend(legends, 'Location', 'SouthEast');\nif export\nset(gcf, 'units', 'inches', 'position', [.8 .8 4 3]);\nset(gca,'FontSize',8);\nset(findall(gcf,'type','text'),'FontSize',8);\nexport_fig plots/subspace_preserving_representation_perc.png -r120 -nocrop;\nexport_fig plots/subspace_preserving_representation_perc.pdf;\nend\n\n\nmf.new_figure('Subspace representation error');\nfor c=1:nc\n    style = styles{c};\n    plot(points, spr_error_perc_mat(c, :), style);\n    hold on;\nend\nxlabel('Points');\nylabel('Subspace representation error  (%)');\nylim([0 50]);\ngrid on;\nlegend(legends);\nif export\nset(gcf, 'units', 'inches', 'position', [.8 .8 4 3]);\nset(gca,'FontSize',8);\nset(findall(gcf,'type','text'),'FontSize',8);\nexport_fig plots/subspace_representation_error_perc.png -r120 -nocrop;\nexport_fig plots/subspace_representation_error_perc.pdf;\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/experiments/ssc_mc_omp/print_bench_ssc_mc_omp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5574628243813959}}
{"text": "classdef CEC2017_F20 < PROBLEM\n% <single> <real> <constrained>\n% CEC'2017 constrained optimization benchmark problem\n\n%------------------------------- Reference --------------------------------\n% G. Wu, R. Mallipeddi, and P. N. Suganthan, Problem definitions and\n% evaluation criteria for the CEC 2017 competition on constrained real-\n% parameter optimization, National University of Defense Technology, China,\n% 2016.\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        O;  % Optimal decision vector\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2017.mat'),'Data');\n            obj.O = Data{12}.o;\n            obj.M = 1;\n            if isempty(obj.D); obj.D = 10; end\n            obj.D = min(obj.D,length(obj.O));\n            obj.lower    = zeros(1,obj.D) - 100;\n            obj.upper    = zeros(1,obj.D) + 100;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            Y = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            Y = Y.^2;\n            PopObj = sum(0.5+(sin(sqrt(Y(:,1:end-1)+Y(:,2:end))).^2-0.5)./(1+0.001*sqrt(Y(:,1:end-1)+Y(:,2:end))).^2,2) + ...\n                     0.5+(sin(sqrt(Y(:,end)+Y(:,1))).^2-0.5)./(1+0.001*sqrt(Y(:,end)+Y(:,1))).^2;\n        end\n        %% Calculate constraint violations\n        function PopCon = CalCon(obj,PopDec)\n            Y = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            Y = sum(Y,2);\n            PopCon(:,1) = cos(Y).^2 - 0.25*cos(Y) - 0.125;\n            PopCon(:,2) = exp(cos(Y)) - exp(0.25);\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/Single-objective optimization/CEC 2017/CEC2017_F20.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5574628175865214}}
{"text": "function Tfin=final(yy,T,robot)\ntam=length(T);\nTf=yy*T{tam};\nglobal radio;\nglobal Tinicial;\nglobal intervalos;\n%Tinicial=directkinematic(robot,[0 0 0 0 0 0]);\n\n x=Tf(1:3,1);\n y=Tf(1:3,2);\n z=Tf(1:3,3);\n Tfin{1}=Tf;\n pmedio=[Tf(1,4),Tf(2,4),(Tf(3,4)- radio)/2];\n \n for j=2:1:(intervalos*2);\n    if j<=intervalos \n       final(1,j)=(j-1)*(pmedio(1)-Tf(1,4))/intervalos + Tf(1,4);\n       final(2,j)=(j-1)*(pmedio(2)-Tf(2,4))/intervalos + Tf(2,4);\n       final(3,j)=(j-1)*(pmedio(3)-Tf(3,4))/intervalos + Tf(3,4);\n       %Ejes tramo final\n       xz=final(1,j);\n       yz=final(2,j);\n       zz=final(3,j);\n       p(:,j)=[xz yz zz]';\n       z(:,j)=p(:,j)/norm(p(:,j)');\n       x(2:3,j)=x(2:3,j-1);\n       x(1,j)=(-z(2,j)*x(2,j)-z(3,j)*x(3,j))/z(1,j);\n       x(:,j) = x(:,j)/norm(x(:,j));\n       y(:,j)=cross(z(:,j),x(:,j));\n       f=[x(:,j) y(:,j) z(:,j) p(:,j)];\n       Tfin{j}=[f; 0 0 0 1];\n    else\n        \n       final(1,j)=(j-(intervalos))*(Tinicial(1,4)-pmedio(1))/intervalos + pmedio(1);\n       final(2,j)=(j-(intervalos))*(Tinicial(2,4)-pmedio(2))/intervalos + pmedio(2);\n       final(3,j)=(j-(intervalos))*(Tinicial(3,4)-pmedio(3))/intervalos + pmedio(3);\n\n\n       %Ejes tramo final\n       xz=final(1,j);\n       yz=final(2,j);\n       zz=final(3,j);\n       p(:,j)=[xz yz zz]';\n       z(:,j)=p(:,j)/norm(p(:,j)');\n       x(2:3,j)=x(2:3,j-1);\n       x(1,j)=(-z(2,j)*x(2,j)-z(3,j)*x(3,j))/z(1,j);\n       x(:,j) = x(:,j)/norm(x(:,j));\n       y(:,j)=cross(z(:,j),x(:,j));\n       f=[x(:,j) y(:,j) z(:,j) p(:,j)];\n       Tfin{j}=[f; 0 0 0 1];\n    end\n end\n \n Tfin{j+1}=Tinicial;\n%     figure\n%     hold on\n%     z=Tf(1:3,4);\n%     v=Tinicial(1:3,4);\n%     h(:,1)=Tf(1:3,4);\n%     for i=2:length(Tfin);\n%         h(:,i)=Tfin{i-1}(1:3,4);\n%     end\n%    % h(:,7)=T1(1:3,4)\n%      plot3(z(1),z(2),z(3),'*')\n%      plot3(pmedio(1),pmedio(2),pmedio(3),'*')\n%      hold on\n%      plot3(h(1,:),h(2,:),h(3,:)) \n%      d=length(h);\n%      plot3(v(1),v(2),v(3),'*') \nend", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/projects/draw_on_a_sphere/final.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5574628070045531}}
{"text": "function [p T hFig res] = rmCompareModelsGUI_paramTTest(M, plotFlag);\n% Compare the distributions of pRF parameters between models in a compare\n% models GUI.\n%\n%   [p T hFig df res] = rmCompareModelsGUI_paramTTest([M, plotFlag=1]);\n%\n% INPUTS:\n%\tM: rmCompareModelsGUI structure. See rmCompareModelsGUI_getData.\n%\t[Default: get from current figure]\n%\n%\tplotFlag: flag to indicate whether to plot the results or just return\n%\tthem. [default: 1, plot 'em]\n%\n% OUTPUTS:\n%\tp: [nModels x nModels x 7] matrix of p-values, for one-tailed T tests\n%\tbetween the parameters for each model. The 7 slices reflect the 7\n%\tparameters analyzed:\n%\t\t1) x0\n%\t\t2) y0\n%\t\t3) sigma (major)\n%\t\t4) polar angle\n%\t\t5) eccentricity\n%\t\t6) variance explained\n%\t\t7) beta coefficient for main pRF term.\n%\tSo, for instance, p(2,1,3) reflects a comparison of the third parameter\n%\t(pRF size or sigma) for the test where model 2 is greater than model 1.\n%\t\n%\tT: [nModels x nModels x 7] matrix of T-values, corresponding to the p-\n%\tvalues given in p. \n%\n%\thFig: if plotFlag==1, returns a handle to the plotted data. Otherwise,\n%\treturns empty.\n%\n%\tres: further results struct, with the following fields:\n%\t\tdf: degrees of freedom for the T tests\n%\n%\t\talpha: alpha threshold for the T tests, based on p=0.01 with\n%\t\tBonferroni correction for multiple comparisons within these tests\n%\n%\t\tH: matrix of 'results' indicating whether to accept (=0) or reject (=1) \n%\t\tthe null hypothesis that the parameters come from the same\n%\t\tdistribution. Same format as p and T.\n%\n%\t\tCI_lo, CI_hi: 100 * (1-alpha)% confidence intervals for the true mean for\n%\t\teach comparison (same format as H). CI_lo is the lower bound, CI_hi\n%\t\tis the upper bound.\n%\n%\t\tsd: pooled estimate of the population standard deviation for each\n%\t\tcomparison (same format as H). \n%\t\n%\n% ras, 05/2009.\nif notDefined('M'),\t\tM = get(gcf, 'UserData');\t\t\tend\nif notDefined('plotFlag'),\tplotFlag = 1;\t\t\t\t\tend\nif ishandle(M),\t\t\tM = get(M, 'UserData');\t\t\t\tend\n\np = [];\nT = [];\nhFig = [];\n\nfields = {'x0' 'y0' 'sigma' 'pol' 'ecc' 'varexp' 'beta'};\n\n% let's pick an alpha value that takes into account multiple comparisons\n% (not that it really matters -- in the initial iteration, we don't return\n% these, and let the user decide their own thresholds based on the\n% p-values):\nalpha = 0.01 / (7 * M.nModels);\nres.alpha = alpha;\n\n%% loop across parameters\nfor n = 1:7\n\tf = fields{n};\n\t\n\t% get the param values for all models\n\tif n < 7\n\t\tdata = reshape( [M.(f){:}], [M.nVoxels M.nModels] );\n\telse\n\t\t% n==7: beta values: need the specific beta for the main\n\t\t% effect\n\t\tfor m = 1:M.nModels\n\t\t\ttmp{m} = [ M.beta{m}(:,1) ]';\n\t\tend\n\t\tdata = reshape( [tmp{:}], [M.nVoxels M.nModels] );\n\tend\n\n\t%% loop across model pairs\n\tfor ii = 1:M.nModels\t\n\t\tfor jj = 1:M.nModels\n\t\t\t% run the one-sided T test\n\t\t\t[H P CI STATS] = ttest2(data(:,ii), data(:,jj), alpha, 'right');\n\t\t\t\n\t\t\t% record the main stat values\n\t\t\tp(ii,jj,n) = P;\n\t\t\tT(ii,jj,n) = STATS.tstat;\n\t\t\t\n\t\t\t% record other results\n\t\t\tres.df(ii,jj,n) = STATS.df;\n\t\t\tres.H(ii,jj,n) = H;\n\t\t\tres.CI_lo(ii,jj,n) = CI(1);\n\t\t\tres.CI_hi(ii,jj,n) = CI(2);\n\t\t\tres.sd(ii,jj,n) = STATS.sd;\n\t\tend\n\tend\nend\n\n\n%% plot if requested\nif plotFlag==1\n\tnm = sprintf('Cross-Model T Tests %s', M.roi.name);\n\th = figure('Color', 'w', 'Name', nm);\n\t\n\tfor z = 1:7\n\t\tsubplot(3, 3, z);\n\t\t\n\t\t% get the param values for all models\n\t\tf = fields{z};\n\t\tif z < 7\n\t\t\tdata = reshape( [M.(f){:}], [M.nVoxels M.nModels] );\n\t\telse\n\t\t\t% ii==7: beta values: need the specific beta for the main\n\t\t\t% effect\n\t\t\tfor m = 1:M.nModels\n\t\t\t\ttmp{m} = [ M.beta{m}(:,1) ]';\n\t\t\tend\n\t\t\tdata = reshape( [tmp{:}], [M.nVoxels M.nModels] );\n\t\tend\n\t\t\n\t\t% compute the mean, SEM of the data\n\t\tY = nanmean(data);\n\t\tE = nanstd(data); %  ./ sqrt(M.nVoxels - 1);\n\t\t\n\t\tstarbar(Y, E, any(res.H(:,:,z)));\n\t\tset(gca, 'Box', 'off');  tuftify;\n\t\txlabel('Model #', 'FontSize', 12);\n\t\tylabel(f, 'FontSize', 12);\n\t\t\n\t\ttitle(f, 'FontSize', 14);\n\tend\n\t\n\tnm = sprintf('Cross-Model T Values %s', M.roi.name);\n\th = figure('Color', 'w', 'Name', nm, 'Units', 'norm', ...\n\t\t\t  'Position', [.4 .3 .4 .4]);\n\t\n\tfor z = 1:7\n\t\tsubplot(3, 3, z);\n\t\t\n\t\tf = fields{z};\n\t\t\n\t\tdrawXCorrMatrix( T(:,:,z), mrvMinmax(T) + [-.2 .2], 1 );\n\t\t\n\t\t% label each entry in the lower-left-hand plot\n% \t\tif z==7\n\t\t\taxis on\n\t\t\tset(gca, 'Box', 'off', 'XTick', 1:M.nModels, ...\n\t\t\t\t'YTick', 1:1:M.nModels, 'FontSize', 9)\n\t\t\txlabel('Model #', 'FontSize', 12);\n\t\t\tylabel('Model #', 'FontSize', 12);\n% \t\tend\n\t\t\n\t\ttitle( ['T Values: ' f], 'FontSize', 14 );\n\tend\n\t\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/CompareModels/rmCompareModelsGUI_paramTTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5574374189084115}}
{"text": "%% parLimNat\n% Below is a demonstration of the features of the |parLimNat| function\n\n%% Syntax\n% |[xx,S]=parLimNat(xx_c,[xx_min xx_max],x);|\n\n%% Description\n% The |parLimNat| function can be used to constrain parameters from\n% [-inf,inf] to the range [xx_min xx_max] with the values xx_c at its\n% centre. The constraining can be used in combination with optimization\n% routinges that do not naturally handle parameter constraints. \n\n%% Examples\n\nclear; close all; clc;\n\n%%\n% PLOT SETTINGS\nfontSize=25;\nfontSize2=15;\nmarkerSize=45;\nlineWidth1=2;\nlineWidth2=1;\n\n%% Example: Constraining parameters (normal centre)\nxx_c=5;\nxx_min=0;\nxx_max=10;\nx=linspace(xx_c-10,xx_c+10,1000);\n[xx,S]=parLimNat(xx_c,[xx_min xx_max],x);\n\ncFigure; hold on; grid on;\ntitle('Constraining using parLimNat','FontSize',fontSize);\nxlabel('\"free\" x','FontSize',fontSize); ylabel('constrained x','FontSize',fontSize); \n\nplot(x,xx,'r-','LineWidth',lineWidth1);\nplot(xx_min,xx_min,'k.','markerSize',markerSize);\nplot(xx_max,xx_max,'k.','markerSize',markerSize);\nplot(xx_c,xx_c,'k.','markerSize',markerSize);\n\ntext(xx_c+0.5,xx_c,'xx_c = centre','Interpreter','none','FontSize',fontSize2);\ntext(xx_max,xx_max-0.5,'xx_max = upper bound','Interpreter','none','FontSize',fontSize2);\ntext(xx_min-2.5,xx_min+0.5,'xx_min = lower bound','Interpreter','none','FontSize',fontSize2);\n\naxis tight; axis equal;\nset(gca,'FontSize',fontSize);\ndrawnow;\n\n%% Example: Constraining parameters (out of centre centre)\nxx_c=2;\nxx_min=0;\nxx_max=10;\nx=linspace(xx_c-10,xx_c+15,100);\n[xx,S]=parLimNat(xx_c,[xx_min xx_max],x);\n\ncFigure; hold on; grid on;\ntitle('Constraining using parLimNat','FontSize',fontSize);\nxlabel('\"free\" x','FontSize',fontSize); ylabel('constrained x','FontSize',fontSize); \n\nplot(x,xx,'r-','LineWidth',lineWidth1);\nplot(xx_min,xx_min,'k.','markerSize',markerSize);\nplot(xx_max,xx_max,'k.','markerSize',markerSize);\nplot(xx_c,xx_c,'k.','markerSize',markerSize);\n\ntext(xx_c+0.5,xx_c,'xx_c = centre','Interpreter','none','FontSize',fontSize2);\ntext(xx_max,xx_max-0.5,'xx_max = upper bound','Interpreter','none','FontSize',fontSize2);\ntext(xx_min-2.5,xx_min+0.5,'xx_min = lower bound','Interpreter','none','FontSize',fontSize2);\n\naxis tight; axis equal;\nset(gca,'FontSize',fontSize);\ndrawnow;\n\n%% \n%\n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_parLimNat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5574374105171324}}
{"text": "function [modelstring, typeflag, order] = modeltype(ar,ma)\n\n%MODELTYPE provides a description for an ARMA-model\n%   [modelstring, typeflag, order] = modeltype(AR,MA)\n%\n%   modelstring: AR, MA, ARMA\n%   typeflag:    1   2   3\n%   order: AR(p): p, MA(q): q, ARMA(r,r-1): r, NaN otherwise.\n%   (ARMA setting for 'order' only for use with ARMAsel)   \n%\n%   Example:\n%   modeltype([1 .2 .5],[1 .3])\n%   modeltype: ARMA(2,1)\n%\n%   See also: ARMAsel.\n\n%S. de Waele, MARCH 2001\n\nk = length(ar)-1; l = length(ma)-1;\nif ~l,\n   modelstring = ['AR(' int2str(k) ')']; typeflag = 1; order = k;\nelseif ~k\n   modelstring = ['  MA(' int2str(l) ')']; typeflag = 2; order = l;\nelse\n   modelstring = ['ARMA(' int2str(k) ',' int2str(l) ')']; typeflag = 3;\n   if l == k-1,\n       order = k;\n   else\n       order = NaN;\n   end\nend\n\nif ~nargout,\n   disp(['modeltype: ' modelstring])\n   clear modelstring typeflag\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/3680-automatic-spectral-analysis/AutomaticSpectra/TimserTools/modeltype.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5574374092466261}}
{"text": "% Chapter 8 - Planar Systems.\n% Program_8c - Phase Portrait of a Nonlinear System (Fig. 8.12).\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% Phase portrait of a nonlinear system of ODE's.\n% IMPORTANT - Program_8a is vectorfield.m.\nclear\n% sys=inline('[x(2);x(1)*(1-(x(1))^2)+x(2)]','t', 'x');\nsys = @(t,x) [x(2);x(1)*(1-(x(1))^2)+x(2)]; \nvectorfield(sys,-3:.5:3,-3:.5:3);\n     hold on\n     sep=1;\n     for x0=-3:sep:3\n         for y0=-3:sep:3\n            [ts,xs] = ode45(sys,[0 6],[x0 y0]);\n            plot(xs(:,1),xs(:,2))\n         end\n     end\n     for x0=-3:sep:3\n         for y0=-3:sep:3\n            [ts,xs] = ode45(sys,[0 -6],[x0 y0]);\n            plot(xs(:,1),xs(:,2))\n         end\n     end\n     hold off\naxis([-3 3 -3 3])\nfsize=15;\nset(gca,'XTick',-3:1:3,'FontSize',fsize)\nset(gca,'YTick',-3:1:3,'FontSize',fsize)\nxlabel('x(t)','FontSize',fsize)\nylabel('y(t)','FontSize',fsize)\nhold off\n\n% End of Program_8c.", "meta": {"author": "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_8c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5574373949046273}}
{"text": "function SF = SF_evaluation(MF)\nRF = diff(MF,1,1);\nRF1 = sqrt(mean(mean(RF.^2)));\nCF = diff(MF,1,2);\nCF1 = sqrt(mean(mean(CF.^2)));\nSF = sqrt(RF1^2+CF1^2);\nend\n", "meta": {"author": "Linfeng-Tang", "repo": "Image-Fusion", "sha": "9e6159f4a09ece3d3a1da6f9ca444436b7012c64", "save_path": "github-repos/MATLAB/Linfeng-Tang-Image-Fusion", "path": "github-repos/MATLAB/Linfeng-Tang-Image-Fusion/Image-Fusion-9e6159f4a09ece3d3a1da6f9ca444436b7012c64/General Evaluation Metric/Evaluation/SF_evaluation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240964782012, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5573990856882421}}
{"text": "classdef OmoriModel < int32\n    enumeration\n        pck   (1) % 3 free parameters: p, c , k      % Modified Omori law (pck)\n        pckk  (2) % 4 free parameters: p, c , k1, k2 % MOL with secondary aftershock (pckk)\n        ppckk (3) % 5 free parameters: p1,p2,c,k1,k2 % MOL with secondary aftershock\n        ppcckk(4) % 6 free parameters: p1,p2,c1, c2,k1,k2 % MOL with secondary aftershock\n    end\n    \n    methods(Static)\n        function cm = doForecast(nMod, t, p_1, c_1, k_1, t_break, k_2, p_2, c_2) % notice funky order!\n            % log likelyhood\n            %   where p = pvalues as n x 1\n            %   where c = cvalues as n x 1\n            %   where k = kvalues as n x 1\n            %   where t = amount of time after the main shock, as m x 1 duration\n            %\n            %   returns an n x m matrix of values\n            %\n            % each row represents ONE time.\n            % each column represents one itteration of p,c, and k\n            %\n            %  for scalar p,c,k, this would return a single row of values. one for each time.\n            %  for scalar t, this would returna  single column of values.\n            %\n            %  p1t1   p2t1  p3t1     params ->\n            %  p1t2   p2t2  p3t2\n            %  p1t3   p2t3  p3t3\n            %  p1t4   p2t4  p3t4\n            %\n            %  time\n            %    |\n            %    v\n            \n            \n            assert(isrow(p_1) && isrow(c_1) && isrow(k_1) , 'All p,c,k input values should be rows');\n            assert(all(numel(p_1) == [ numel(k_1), numel(c_1)]),'p, c, and k values should have same length');\n            assert(isvector(t), 'time should be a vector');\n            if isduration(t)\n                t=days(t);\n            end\n            if ~iscolumn(t)\n                t=t';\n            end\n            \n            cm = nan(numel(t),numel(p_1));\n            sz=size(cm);\n            switch nMod\n                case OmoriModel.pck\n                    % deal with non infinite solutions first\n                    idx = p_1 ~= 1;\n                    c=c_1(idx); \n                    k=k_1(idx);\n                    p=p_1(idx);\n                    cm(:,idx) = k ./ (p-1) .* (c .^ (1-p)-(t +c).^ (1-p));\n                    \n                    c=c_1(~idx);\n                    k=k_1(~idx);\n                    p=[];\n                    cm(:,~idx) = k .* log(t ./ c + 1);\n                    \n                    \n                case {OmoriModel.pckk, OmoriModel.ppckk, OmoriModel.ppcckk}\n                    \n                    assert(isrow(p_2) && isrow(c_2) && isrow(k_2) , 'All p2,c2,k2 input values should be rows');\n                    assert(all(numel(p_1) == [ numel(p_2) numel(k_2), numel(c_2)]),'pn, cn, and kn values should have same length');\n                    assert(isscalar(t_break));\n                    if isduration(t_break)\n                        t_break=days(t_break);\n                    end\n                    \n                    isafter = t >= t_break;\n                    cm(~isafter,:) =  OmoriModel.doForecast(OmoriModel.pck, t(~isafter), p_1, c_1, k_1);\n                    \n                    idx = p_1 ~= 1 & p_2 ~= 1;\n                    if any(idx)\n                        c1 = c_1(idx);\n                        c2 = c_2(idx);\n                        p1 = p_1(idx);\n                        p2 = p_2(idx);\n                        k1 = k_1(idx);\n                        k2 = k_2(idx);\n                        cm(isafter,idx) = k1./(p1-1) .* (c1.^(1-p1)-(t(isafter)+c1).^(1-p1)) + k2./(p2-1).*(c2.^(1-p2)-(t(isafter)-t_break + c2).^(1-p2));\n                    end\n                    \n                    idx = p_1 ~= 1 & p_2 == 1;\n                    if any(idx)\n                        c1 = c_1(idx);\n                        c2 = c_2(idx);\n                        p1 = p_1(idx);\n                        p2 = [];\n                        k1 = k_1(idx);\n                        k2 = k_2(idx);\n                        cm(isafter,idx) = k1./(p1-1) .* (c1.^(1-p1)-(t(isafter)+c1).^(1-p1)) + k2 .* log((t(isafter)-t_break)./c2+1);\n                    end\n                    \n                    idx = p_1 == 1 & p_2 ~= 1;\n                    if any(idx)\n                        c1 = c_1(idx);\n                        c2 = c_2(idx);\n                        p1 = [];\n                        p2 = p_2(idx);\n                        k1 = k_1(idx);\n                        k2 = k_2(idx);\n                        cm(isafter,idx) =k1.*log(t(isafter)./c1+1) + k2./(p2-1).*(c2.^(1-p2)-(t(isafter)-t_break+c2).^(1-p2));\n                    end\n                    \n                    idx = p_1 == 1 & p_2 == 1;\n                    if any(idx)\n                        c1 = c_1(idx);\n                        c2 = c_2(idx);\n                        p1 = [];\n                        p2 = [];\n                        k1 = k_1(idx);\n                        k2 = k_2(idx);\n                        cm(isafter,idx) = k1.*log(t(isafter)./c1+1) + k2.*log((t(isafter)-t_break)./c2+1);\n                    end\n                    \n            end\n            assert(isequal(size(cm),sz)); % make sure sizes are as expected\n        end\n    end\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/OmoriModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5573990700161605}}
{"text": "function pred = knntest(Xtest,class_t,X,class,K,dist_type,pret_type)\n\n% prediction of new samples with calculated model\n%\n% pred = knnpred(Xtest,X,class,K,dist_type,pret_type)\n%\n% ------------ INPUT ---------------------------------------------------\n% Xtest:        dataset to be predicted [n_test x p] n objects, p variables\n% X:            training data matrix (n x p)\n% class:        training class vector (n x 1)\n% K:            number of neighbors\n% dist_type:    'euclidean' Euclidean distance\n%               'mahalanobis' Mahalanobis distance\n%               'cityblock' City Block metric\n%               'minkowski' Minkowski metric\n%               'sm' Sokal-Michener \n%               'jt' Jaccard Tanimoto\n%               'gle' Gleason-Dice\n%               'ct4' Consonni-Todeschini\n%               'ac' Austin-Colwell\n% pret_type:    'cent' cenering\n%               'scal' variance scaling\n%               'auto' for autoscaling (centering + variance scaling)\n%               'rang' range scaling (0-1)\n%               'fp'   fingerprints\n%\n% ------------ OUTPUT --------------------------------------------------\n% pred is a structure conyaining\n% class_pred    predicted class vector [n_test x 1]\n% neighbors     list of k neighbors for each predicted sample [n_test x k]\n% \n% version 1.0 - september 2009\n% Davide Ballabio\n% Milano Chemometrics and QSAR Research Group\n% www.disat.unimib.it/chm\n\n% version 2.0 - February 2012\n% Kamel Mansouri\n% Milano Chemometrics and QSAR Research Group\n% www.disat.unimib.it/chm\n\n% data check\nif length(class)~=size(X,1)\n    disp('the class input should be for the training set')\n    %class_tr=input('class tr');\n    %class=evalin(WS,);\n    %keyboard\nend\n\n[n,p] = size(Xtest);\n[X_scal_train,param] = data_pretreatment(X,pret_type);\nX_scal = test_pretreatment(Xtest,param);\nXd = [X_scal;X_scal_train];\n% D = pdist(Xd,model.set.dist_type);\n% D = squareform(D);\nD = knn_calc_dist(X_scal_train,X_scal,dist_type,pret_type);\nneighbors = zeros(n,K);\nfor i=1:n\n    D_in = D(i,:);\n    [d_tmp,n_tmp] = sort(D_in);\n    neighbors(i,:) = n_tmp(1:K);\n    d_neighbors = d_tmp(1:K);\n    class_calc(i) = knnclass(class(neighbors(i,:)),d_neighbors,max(class),K);\n    dc(i,:)=d_neighbors;\nend\n\npred.neighbors  = neighbors;\npred.class_pred = class_calc';\npred.class_param = calc_class_param(pred.class_pred ,class_t);\npred.D=D;\npred.dc=dc;", "meta": {"author": "kmansouri", "repo": "OPERA", "sha": "fcbe8024c01f49cd9498187c0ff8c5c45d6dc833", "save_path": "github-repos/MATLAB/kmansouri-OPERA", "path": "github-repos/MATLAB/kmansouri-OPERA/OPERA-fcbe8024c01f49cd9498187c0ff8c5c45d6dc833/OPERA_Source_code/knntest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5573990663449727}}
{"text": "% m-file which generates data from a simple system with a localized\n% nonlinearity and processes it using RLM's zeroing algorithm.\n%\n% Matt Allen, June 27, 2005\n% MSA: Major Update - Nov, 2005 - changed to two arbitrary subsystems.\n% \nclear all; close all;\n\n% Set up system parameters\n% m1 = 1; m2 = 1; m3 = 1; m4 = 1; m5 = 1;\n    M1 = eye(5);\n    M2 = 0.1*eye(2); % Subsystem is about 10% the weight of normal system.\n    \n    kall = 1e6;\n    k1 = kall; k2 = kall; k3 = kall; k4 = kall; k5 = kall; k6 = kall; kat = kall;\n    K1 = [k1, -k1, 0, 0, 0; % System 1\n        -k1, k1+k2, -k2, 0, 0\n        0, -k2, k2+k3, -k3, 0;\n        0, 0, -k3, k3+k4, -k4;\n        0, 0, 0, -k4, k4];\n    Ns1 = 5; Ns2 = 2; Ntot = 7;\n    K2 = [k5, -k5; % System 2 - attached subsystem - dof's\n        -k5, k5];\n    Mtot = [M1, zeros(size(M1,1),size(M2,2));\n        zeros(size(M2,1),size(M1,2)), M2];\n    Ktot = [K1, zeros(size(K1,1),size(K2,2));\n        zeros(size(K2,1),size(K1,2)), K2];\n    % Specify how systems are connected\n    at_ns = [2,6]; % attachment happens between this pair of nodes.\n    fext_ns = 5; % Node at which external force is applied\n    fnl_vec = zeros(Ntot,1); fnl_vec(at_ns(1)) = -1; fnl_vec(at_ns(2)) = 1;\n    fext_vec = zeros(Ntot,1); fext_vec(fext_ns(1)) = 1;\n    dnodes = [1:Ntot];\n    vnodes = [(Ntot+1):(Ntot*2)];\n    \n    % Damping Matrix    \n    cfactk = 0.00003; % multiplied by K to get damping.\n    cfactm = 8; % Multiplied by M to get damping\n    % for k = 1:5; eval(['c',num2str(k),' = cfact*k',num2str(k),';']); end\n    C1 = cfactk*K1 + cfactm*M1;\n    C2 = cfactk*K2 + cfactm*M2; % proportional damping\n    Ctot = [C1, zeros(size(C1,1),size(C2,2));\n        zeros(size(C2,1),size(C1,2)), C2];\n    \n    % Linearized System Analysis %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        % add a linear spring between attachment nodes\n        Mlin = Mtot;\n        Klin = Ktot;\n        Klin(at_ns,at_ns) = Klin(at_ns,at_ns) + kat*[1, -1; -1, 1];\n        % Linear Damping matrix:\n        Clin = Ctot;\n        Clin(at_ns,at_ns) = Clin(at_ns,at_ns) + cfactk*kat*[1, -1; -1, 1];\n\n    % State Space Eigenanalysis\n    Slin = [Clin, Mlin; Mlin, zeros(size(Mlin))];\n    Rlin = [-Klin, zeros(size(Mlin));\n        zeros(size(Mlin)), Mlin];\n    Alin = (Slin\\Rlin);\n    [Philin,lamlin] = eig(Alin);\n    lamlin = diag(lamlin);\n    [junk,sind] = sort(abs(lamlin) - 0.001*min(abs(lamlin))*(imag(lamlin) > 0));\n    lamlin = lamlin(sind);\n    Philin = Philin(:,sind);\n\n%         % Plot Mode Shapes\n%         figure(1)\n%         hls = plot([1:Ntot], imag(Philin(1:Ntot,1:2:end ))); grid on;\n%         legend(hls, num2str([1:Ntot].'));\n%         xlabel('X-coordinate');\n%         ylabel('Im\\{Mode Shape\\}');\n\n    wns = abs(lamlin);\n    fns = wns/2/pi;\n    zts = -real(lamlin)./abs(lamlin);\n    disp('Natural Frequencies:, Damping Ratios:');\n    [fns, zts]\n%     DispFnZt(lamlin) - replace 2 lines abouve with this if you have the EMA Functions toolbox\n    \n    % Nonlinear Parameters\n    NLType = 'bang'\n    if strcmp(NLType,'bang');\n        % Bang (Contact) Nonlinearity\n        delcont = 1e-3;\n        k4mult = 20; % Factor by which k4 increases: k4_contact = k4*k4mult\n        c4mult = 1; % Factor by which c4 increases: c4_contact = c4*c4mult\n    elseif strcmp(NLType,'cubic');\n        % Cubic Spring\n        katnl = 1e8;\n    else\n        error('NLType not recognized');\n    end\n    % Force paramters\n        % length of half-sine force pulse\n        % This is normalized in the EOM to unit area and multiplied by Afnl\n        tfp = 1e-4;\n        Afnl = 4e9;\n        \n    % Which Response to Use in evaluating Nonlinearity (i.e. x1, x2, x3..?)\n    respind = 6;\n    \n    % Number of numerical derivatives to evaluate.  This M-file simulates\n    % the displacement response of the 5-DOF system.  To simulate the\n    % measurement of the velocity or acceleration response, the\n    % displacement response is differentiated using finite differences\n    % (i.e. Matlab's 'diff' command.)  This parameter sets the number of\n    % derivatives to perform:\n    nders = 2;\n        % nders = 0; => use displacement\n        % nders = 1; => use velocity\n        % nders = 2; => use acceleration\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Put all of this in a structure for the EOM\nglobal eom\nS = whos;\nfor k = 1:length(S)\n    eval(['eom.',S(k).name,' = ',S(k).name,';']);\nend\n    \n    % Compute TF of Linearized System\n    F = zeros(Ntot,1); F(fext_ns) = 1;\n    wlin = [1:1:500]*2*pi;\n    Halin = zeros(Ntot,length(wlin));\n    for k = 1:length(wlin)\n        Halin(:,k) = wlin(k).^2*([Mlin*-wlin(k).^2 + Clin*i*wlin(k) + Klin]\\F);\n    end\n    Halin = Halin.';\n\n%     figure(2)\n%     semilogy(wlin/2/pi,abs(Halin)); grid on;\n%     xlabel('Frequency (Hz)')\n%     ylabel('H_{ACCEL}(\\omega)');\n%     for k = 1:Ntot; leg_txt{k} = ['H_{',num2str(k),',5}']; end\n%     legend(leg_txt);\n\n  \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Nonlinear Simulation\n% Compute sample rate and time\n    elas_modes = find(imag(lamlin) > 0);\n    dt = (5*2*max(fns(elas_modes)))^-1;\n    Tmin = log(0.001)/(-min(abs(real(lamlin(elas_modes)))));\n    N = 2^ceil(log2(Tmin/dt));\n    \n    ts = [0:dt:(N-1)*dt].';\n    \n% Specify initial time step so the solver doesn't miss the pulse:\n    odeopts = odeset('InitialStep',tfp/10,'AbsTol',1e-9);\n    \n    % [ts_ode,hnl] = ode45(@nldetect_anex2_v1_eom,ts,zeros(10,1),odeopts,eom);\n    \n% Alternate Calling form:\nsol = ode45(@nldt_bng_cub_v2_eom,[ts(1),ts(end)],zeros(Ntot*2,1),odeopts);\n    [hnl, hnldot] = deval(sol,ts);\n    hnl = hnl.';  hnldot = hnldot.';\n    \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Linear Simulation\nltisys = ss(Alin,Slin\\[F; zeros(Ntot,1)],[eye(Ntot), zeros(Ntot)], zeros(Ntot,1));\n    \n    % Use fine sample increment over duration of pulse\n    if tfp < dt\n        tlini = [0:100].'*tfp/100;\n        ulini = (Afnl*2*tfp/pi)*sin((pi/tfp)*tlini);\n        % Over Pulse duation to first sample\n        [ylini,junki,xlini] = lsim(ltisys, [ulini], [tlini], zeros(Ntot*2,1));\n        [ylin, junk2, xlin2] = lsim(ltisys, zeros(2,1), [junki(end); ts(2)], xlini(end,:).');\n        % Free Response\n        [ylin, junk3, xlin3] = lsim(ltisys, zeros(size(ts(2:end))), ts(2:end), xlin2(end,:).');\n        hlin = [xlini(1,:); xlin2(end,:); xlin3(2:end,:)];\n    else\n        error('tfp > dt not yet supported!');\n    end\n    \n% Plot Results\nfigure(10); set(gcf,'Position',[532   189   560   567]);\nsubplot(2,1,1)\nplot(ts, hlin(:,respind), ts, hnl(:,respind), 'o-',sol.x, sol.y(respind,:), '.:'); grid on;\nlegend('h_{(r,5)} LIN','h_{(r,5)} NL','h_{(r,5)} ODE45');\nxlabel('time (s)');\ntitle('Comparison of Linear and Nonlinear Time Responses')\n\n% Approximate derivatives of the response:\ndisp(['Number of Derivatives Requested: ',num2str(nders)]);\nndhlin = [zeros(nders,1); dt^-nders*diff(hlin(:,respind ),nders,1);];\nndhnl = [zeros(nders,1); dt^-nders*diff(hnl(:,respind ),nders,1); ];\n%   Derivatives computed by \"diff\" don't appear to be ideal.  I don't know\n%   that they are equivalent to a forward difference scheme.\n% Select ODE45 derivatives - USE ODE45 Derivatives in the analysis!\nif nders == 0;\n    dhnlode = hnl(:,respind);\nelseif nders == 1;\n    dhnlode = hnl(:,respind + Ntot);\nelseif nders == 2;\n    dhnlode = hnldot(:,respind + Ntot);\nend    \ntsdh = ts;%ts((1+nders):end);\nsubplot(2,1,2)\nplot(tsdh, ndhlin, tsdh, ndhnl, ts, dhnlode, '.'); grid on;\nlegend(['h_D_{(',num2str(respind),',5)} LIN'],['h_D_{(',num2str(respind),',5)} NL'],...\n    ['h_D_{(',num2str(respind),',5)} NL-ODE45']);\nxlabel('time (s)');\ntitle('Comparison of Derivatives of Linear and Nonlinear Responses')\n\n% Find Actual force curve:\n% This must be modified manually\n% Fnl2 = Mtot(at_ns(2),at_ns(2))*hnldot(:,Ntot+at_ns(2)) - k5*(hnl(:,at_ns(2)) - hnl(:,at_ns(2)+1));\nFnl2 = Mtot(at_ns(2),:)*(hnldot(:,vnodes).') + Ktot(at_ns(2),:)*(hnl(:,dnodes).');\n    if abs(fext_vec(at_ns(1))) > 0; warning('Equation for Force may not be correct'); end\nFnl3 = - Mtot(at_ns(1),:)*(hnldot(:,vnodes).') - Ktot(at_ns(1),:)*(hnl(:,dnodes).');\n    if abs(fext_vec(at_ns(1))) > 0; warning('Equation for Force may not be correct'); end\ndelt_nl = hnl(:,at_ns(1)) - hnl(:,at_ns(2));\n\n% Track the magnitude of the displacement of spring 4 - for NL\nfigure(11); set(gcf, 'Units','Normalized'); set(gcf,'Position',[0.069444,  0.48444, 0.43819, 0.39111]);\n    set(gcf,'Name','Force vs. Delta Curve','Toolbar','figure');\nsubplot(1,3,1)\ndeltas = [-100:100]*(max(delt_nl)/100);\nif strcmp(NLType,'bang');\n    for k = 1:length(deltas)\n        if deltas(k) < eom.delcont % No Contact Occurs\n            Fnl(k) = eom.kat*deltas(k);\n        else                % Contact Occurs\n            Fnl(k) = eom.kat*eom.k4mult*deltas(k);\n        end\n    end\nelseif strcmp(NLType,'cubic');\n    Fnl = kat*deltas.*(1+katnl.*deltas.^2);\nend\nplot(Fnl, deltas*1e3, ...\n    k4*deltas, deltas*1e3, '--',...\n    Fnl2,delt_nl*1e3,'.',...\n    Fnl3,delt_nl*1e3,'k.'); grid on;\nax1h = gca;\nylabel('\\bf\\Delta - NL Spring (mm)'); xlabel('\\bfSpring Force')\ntitle('\\bfSpring Curve');\nhx = subplot(1,3,2:3)\nplot(ts*1e3, delt_nl*1e3); grid on;\n% Set Axes to Equal\n    ylim2 = get(gca,'Ylim');\n    set(ax1h,'Ylim',ylim2);\nxlabel('\\bftime (ms)'); ylabel('\\bf\\Delta - NL Spring (mm)');\ntitle('\\bfDisplacement of NL Spring');\n\n% Add button to make y-axes equal\nset(hx,'tag','Main');\n    PointsPerPixel = 72/get(0,'ScreenPixelsPerInch');\n    hf = gcf;\n    h1 = uicontrol('Parent',hf, ...\n        'Units','points', ...\n        'Position',[168, 51, 45, 25]*PointsPerPixel, ...\n        'Callback','set_equal_ylims(hf);', ...\n        'String','EqYlim', ...\n        'Tag','YAxEqual');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Analysis\n\nif strcmp(NLType,'bang');\n    % ZNLDetect(hlin(:,respind),ts,[0,0.2],400)\n    [Hmat,fs,ts_zc] = ZNLDetect(dhnlode,tsdh,[0,0.1],500);\n    % ZNLDetectC(hnldot(:,6:10),tsdh,[0,0.3],30,400)\nelseif strcmp(NLType,'cubic');\n    [Hmat,fs,ts_zc] = ZNLDetect(dhnlode,tsdh,[0,0.15],500,4);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Alternate analysis - use all sensors with ZNLDetectC\n% This gives 20 ZEFFTs equally distributed between 0 and 0.1 s, 0 to 500 Hz\n%\n% [Hmat,fs,ts_zc] = ZNLDetectC(hnldot(:,8:end),tsdh,[0,0.1],500,20);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24292-nonlinearity-detection-using-zeroed-early-time-ffts/Example_Script.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5573943805180066}}
{"text": "function [km] = in2km(in)\n% Convert length from inches to kilometers.\n% Chad Greene 2012\nkm = in*0.0000254;", "meta": {"author": "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/in2km.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5573943723599942}}
{"text": " function [sn,psdx,ff] = get_noise_fft(Y,options)\n        \n        defoptions = CNMFSetParms;\n        if nargin < 2 || isempty(options); options = defoptions; end\n\n        if ~isfield(options,'noise_range'); options.noise_range = defoptions.noise_range; end\n        range_ff = options.noise_range;\n        if ~isfield(options,'noise_method'); options.noise_method = defoptions.noise_method; end\n        method = options.noise_method;\n        if ~isfield(options,'block_size'); options.block_size = defoptions.block_size; end                \n        block_size = options.block_size;\n        if ~isfield(options,'split_data'); options.split_data = defoptions.split_data; end\n        split_data = options.split_data;\n        if ~isfield(options,'max_timesteps') || isempty(options.max_timesteps); \n            options.max_timesteps = defoptions.max_timesteps;\n        end\n        \n        dims = ndims(Y);\n        sizY = size(Y);\n        N = min(sizY(end),options.max_timesteps);\n        if N < sizY(end)\n           %Y = reshape(Y,prod(sizY(1:end-1)),[]);\n           switch ndims(Y), \n               case 2,\n                    Y(:,N+1:end) = [];\n               case 3, \n                    Y(:,:,N+1:end) = [];\n               case 4, \n                    Y(:,:,:,N+1:end) = [];\n           end\n        end\n        \n        Fs = 1;        \n        ff = 0:Fs/N:Fs/2;\n        indf=ff>range_ff(1);\n        indf(ff>range_ff(2))=0;\n        if dims > 1\n            d = prod(sizY(1:dims-1));\n            Y = reshape(Y,d,N);\n            Nb = prod(block_size);\n            SN = cell(ceil(d/Nb),1);\n            PSDX = cell(ceil(d/Nb),1);\n            if ~split_data\n                for ind = 1:ceil(d/Nb); \n                    xdft = fft(Y((ind-1)*Nb+1:min(ind*Nb,d),:),[],2); \n                    xdft = xdft(:,1: floor(N/2)+1); % FN: floor added.\n                    psdx = (1/(Fs*N)) * abs(xdft).^2;\n                    psdx(:,2:end-1) = 2*psdx(:,2:end-1) + eps;\n                    %SN{ind} = mean_psd(psdx(:,indf),method);\n                    switch lower(method)\n                        case 'mean'\n                            SN{ind}=sqrt(mean(psdx(:,indf)/2,2));\n                        case 'median'\n                            SN{ind}=sqrt(median(psdx(:,indf)/2,2));\n                        case 'logmexp'\n                            SN{ind} = sqrt(exp(mean(log(psdx(:,indf)/2),2)));\n                        otherwise\n                            error('unknown method for averaging noise..')\n                    end\n                    PSDX{ind} = psdx;\n                end\n            else\n                nc = ceil(d/Nb);\n                Yc = mat2cell(Y,[Nb*ones(nc-1,1);d-(nc-1)*Nb],N);\n                parfor ind = 1:ceil(d/Nb); \n                    xdft = fft(Yc{ind},[],2); \n                    xdft = xdft(:,1:floor(N/2)+1);\n                    psdx = (1/(Fs*N)) * abs(xdft).^2;\n                    psdx(:,2:end-1) = 2*psdx(:,2:end-1) + eps;\n                    Yc{ind} = [];\n                    switch lower(method)\n                        case 'mean'\n                            SN{ind}=sqrt(mean(psdx(:,indf)/2,2));\n                        case 'median'\n                            SN{ind}=sqrt(median(psdx(:,indf)/2,2));\n                        case 'logmexp'\n                            SN{ind} = sqrt(exp(mean(log(psdx(:,indf)/2),2)));\n                        otherwise\n                            error('unknown method for averaging noise..')\n                    end\n                    \n                end\n            end\n            sn = cell2mat(SN);\n        else\n            xdft = fft(Y);\n            xdft = xdft(:,1:floor(N/2)+1);\n            psdx = (1/(Fs*N)) * abs(xdft).^2;\n            psdx(:,2:end-1) = 2*psdx(:,2:end-1) + eps;\n            switch lower(method)\n                case 'mean'\n                    sn = sqrt(mean(psdx(:,indf)/2,2));\n                case 'median'\n                    sn = sqrt(median(psdx(:,indf)/2,2));\n                case 'logmexp'\n                    sn = sqrt(exp(mean(log(psdx(:,indf)/2),2)));\n                otherwise\n                    error('unknown method for averaging noise..')\n            end\n        end\n        psdx = cell2mat(PSDX);\n        if dims > 2\n            sn = reshape(sn,sizY(1:dims-1));\n        end\n end\n", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/utilities/get_noise_fft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5573943612479213}}
{"text": "function adjust_bvecs(ecclog,bvecsfile,newbvecsfile)\n% This code is written by Liang Zhan (zhan.liang@ucla.edu)\n% This is to rotate gradient table using eddy_correct output\n% Input variables are:\n%  1) ecclog --- this is one output from eddy_correct\n%  2) bvecsfile --- this is bvec generated from dicom\n%  3) newbvecsfile --- this is output name for adjusted bvecs \n\nfid=fopen(ecclog);\nmat=[];\nwhile ~feof(fid)\n    % skip first three lines\n    for i=1:3\n      fgetl(fid);\n    end\n    % read four lines\n    for i=1:4\n     x=str2num(fgetl(fid))\n    mat=[mat\n         x];\n    end\n    % skip one line\n    fgetl(fid);    \nend\nfclose(fid);\n\n% read bvecs file\nbvecs = load(bvecsfile);\nif(size(bvecs,2)==3 && size(bvecs,1)>3)\n    bvecs = bvecs';\nend\n\n% rotate bvecs\nrotbvecs = zeros(size(bvecs));\nfor i = 1:size(bvecs,2)\n    %M = mat((i-1)*4+1:i*4,:);\n    %M = mat(((i-1)*3+1):i*4,:);\n    %M = M(1:3,1:3);\n    M = mat(1:3,1:3);\n    % extract rotation matrix\n    [u,s,v] = svd(M*M');\n    R = inv(u*sqrt(s)*v')*M;\n    \n    rotbvecs(:,i) = R*bvecs(:,i);\nend\n\nsave(newbvecsfile,'rotbvecs','-ascii');\nend\n", "meta": {"author": "HennyJie", "repo": "BrainGB", "sha": "a95544c37a661649ad93bce3d3e6e5640428220d", "save_path": "github-repos/MATLAB/HennyJie-BrainGB", "path": "github-repos/MATLAB/HennyJie-BrainGB/BrainGB-a95544c37a661649ad93bce3d3e6e5640428220d/brainnet_construction/adjust_bvecs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5573611843290689}}
{"text": "function imin = i4vec_imin ( n, a )\n\n%*****************************************************************************80\n%\n%% I4VEC_IMIN computes the index of the minimum element of an I4VEC.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    17 April 2005\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, integer A(N), the array.\n%\n%    Output, integer IMIN, the index of the smallest entry.\n%\n  if ( n <= 0 )\n\n    imin = 0;\n\n  else\n\n    amin = a(1);\n    imin = 1;\n\n    for i = 2 : n\n\n      if ( a(i) < amin )\n        amin = a(i);\n        imin = i;\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/i4lib/i4vec_imin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.557361177585971}}
{"text": "classdef nnsoftmax < nntest\n  properties (TestParameter)\n    h = {1 2 3}\n    w = {1 2}\n  end\n  methods (Test)\n    function basic(test,h,w)\n      d = 10 ;\n      n = 3 ;\n      x = test.randn(h,w,d,n,'single')/test.range ;\n      y = vl_nnsoftmax(x) ;\n      dzdy = test.randn(size(y),'single') ;\n      dzdx = vl_nnsoftmax(x, dzdy) ;\n      test.der(@(x) vl_nnsoftmax(x), x, dzdy, dzdx, 1e-2) ;\n    end\n  end\nend\n", "meta": {"author": "willard-yuan", "repo": "cnn-for-image-retrieval", "sha": "2e3e8ab76e2c971314be55b5ae44e02884003261", "save_path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval/cnn-for-image-retrieval-2e3e8ab76e2c971314be55b5ae44e02884003261/matconvnet-1.0-beta17/matlab/xtest/suite/nnsoftmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5573611732135679}}
{"text": "function [CD0] = DetermineProfileDrag(airfoildata,geo,panel)\n%Determine the wing profile drag from the airfoils' drag polars\n\nairfoil_r = geo.rootindex;\nairfoil_t = geo.tipindex;\n\n%Root dimensions\nchord_r = geo.c_r;\n\n%Determine Reynolds number at root; using log10 because regression was\n%done this way\nRe_r = log10(geo.Re_r);\n\n%Convert back to degrees because the polynomial regression of the XFOIL\n%drag data is in terms of degrees\nalpha_r = (geo.i_r + geo.alpha)*180/pi;\nb = cell2mat(airfoildata{2}(airfoil_r)); %Load the coefficients\nc = cell2mat(airfoildata{3}(airfoil_r));\nd = cell2mat(airfoildata{4}(airfoil_r));\nk = cell2mat(airfoildata{5}(airfoil_r));\ncd0_r = b(1) + b(2)*Re_r + b(3)*Re_r^2;\ncd1_r = c(1) + c(2)*Re_r + c(3)*Re_r^2;\ncd2_r = d(1) + d(2)*Re_r + d(3)*Re_r^2;\nalpha_stall_r = k(1) + k(2)*Re_r + k(3)*Re_r^2;\n\n%Test to see if airfoil is past stall angle of attack\nif alpha_r > alpha_stall_r\n    cd2_r = 2*cd2_r;\n    %Double the last coefficient to account for the large increase in drag\n    %past stall\nend\n\n%Tip dimensions\nchord_t = geo.c_r*geo.taper;\n\n%Determine Reynolds number at tip, use log10 because performed regression\n%using log10\nRe_t = log10(geo.Re_t);\n\n%Convert back to degrees because the polynomial regression of the XFOIL\n%drag data is in terms of degrees\nalpha_t = (geo.i_r + geo.twist + geo.alpha)*180/pi; \nb = cell2mat(airfoildata{2}(airfoil_t)); %Load the coefficients\nc = cell2mat(airfoildata{3}(airfoil_t));\nd = cell2mat(airfoildata{4}(airfoil_t));\nk = cell2mat(airfoildata{5}(airfoil_t));\ncd0_t = b(1) + b(2)*Re_t + b(3)*Re_t^2;\ncd1_t = c(1) + c(2)*Re_t + c(3)*Re_t^2;\ncd2_t = d(1) + d(2)*Re_t + d(3)*Re_t^2;\nalpha_stall_t = k(1) + k(2)*Re_t + k(3)*Re_t^2;\n\n%Test to see if airfoil is past stall angle of attack\nif alpha_t > alpha_stall_t\n    cd2_t = 2*cd2_t;\n    %Double the last coefficient to account for the large increase in drag\n    %past stall\nend\n\n%eta represents the fraction from 0 to 1 at the center of the panel where 0\n%corresponds to y = 0 and 1 corresponds to y = b\neta = (2*(1:geo.ns)-1)/(2*geo.ns);\nchord = chord_r + eta*(chord_t-chord_r);\nalpha = alpha_r + eta*(alpha_t-alpha_r);\ncd0 = cd0_r + eta*(cd0_t-cd0_r);\ncd1 = cd1_r + eta*(cd1_t-cd1_r);\ncd2 = cd2_r + eta*(cd2_t-cd2_r);\n\nDeltay = zeros(1,geo.ns);\nfor i = 1:geo.ns\n    Deltay(i) = panel(i,1).BV2(2) - panel(i,1).BV1(2);\nend\n\nD_q = (cd0 + cd1.*alpha + cd2.*alpha.^2).*chord.*Deltay;\n\nCD0 = 2*sum(D_q,2)/geo.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/15442-wing-designer/DetermineProfileDrag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5573611679823618}}
{"text": "function x=pcmu2lin(p,s)\n%PCMU2LIN Convert Mu-law PCM to linear X=(P,S)\n%\tlin = pcmu2lin(pcmu) where pcmu contains a vector\n%\tof mu-law values in the range 0 to 255.\n%\tNo checking is performed to see that numbers are in this range.\n%\n%\tOutput values are divided by the scale factor s:\n%\n%\t\t   s\t\tOutput Range\n%\n%\t\t   1\t\t+-8031\t(integer values)\n%\t\t4004.2\t+-2.005649 (default)\n%\t\t8031\t\t+-1\n%\t\t8159\t\t+-0.9843118 (+-1 nominal full scale)\n%\n%\tThe default scaling factor 4004.189931 is equal to\n%\tsqrt((2207^2 + 5215^2)/2) this follows ITU standard G.711.\n%\tThe sine wave with PCM-Mu values [158 139 139 158 30 11 11 30]\n%\thas a mean square value of unity corresponding to 0 dBm0.\n\n\n\n%      Copyright (C) Mike Brookes 1998\n%      Version: $Id: pcmu2lin.m 713 2011-10-16 14:45:43Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin<2\n  t=9.98953613E-4;\nelse\n  t=4/s;\nend\n\nm=15-rem(p,16);\nq=floor(p/128);\ne=(127-p-m+128*q)/16;\nx=(q-0.5).*(pow2(m+16.5,e)-16.5)*t;\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/pcmu2lin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5573611570301328}}
{"text": "function [cleanZ] = PatchDCTGG(Z,patchSize,noiseSD,imsize,W,invW,excludeList)\n% a simple thresholding denoiser - approx. corresponds to a sprase prior\n% over the marginals\nif ~exist('excludeList','var')\n    excludeList = [];\nend\n\nmeanZ = mean(Z);\nZ = bsxfun(@minus,Z,meanZ);\nif (~isempty(excludeList))\n    WZ = W*Z(:,excludeList);\nelse\n    WZ = W*Z;\nend\n\nt = noiseSD*3;\nWZ(abs(WZ)<t)=0;\ncleanZ = Z;\nif ~isempty(excludeList)\n    cleanZ(:,excludeList) = invW*WZ;\nelse\n    cleanZ = invW*WZ;\nend\ncleanZ = bsxfun(@plus,cleanZ,meanZ);\n", "meta": {"author": "lbasek", "repo": "image-denoising-benchmark", "sha": "9d753198d715b7628c8e7d9259dfa5c219d033ea", "save_path": "github-repos/MATLAB/lbasek-image-denoising-benchmark", "path": "github-repos/MATLAB/lbasek-image-denoising-benchmark/image-denoising-benchmark-9d753198d715b7628c8e7d9259dfa5c219d033ea/algoritms/matlab/EPLL/extra/PatchDCTGG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5573218486392681}}
{"text": "close all\nclear all\npath(path,'..\\..\\..\\FUZZCLUST')\n%the data\nload motorcycle.txt\ndata.X = motorcycle(:,[1 2]);\n\n[N,n]=size(data.X);\n\n%data normalization\ndata = clust_normalize(data,'range');\nplot(data.X(:,1),data.X(:,2),'.')\nhold on\n%parameters\nparam.c=4;\nparam.vis=1;\nparam.val=1;\n%clustering\nresult=kmeans(data,param);\n%validation\nresult = validity(result,data,param);\nresult.validity", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/7486-clustering-toolbox/Demos/clusteringexamples/motorcycle/Kmeanscall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5573218483991933}}
{"text": "function A = makehatch(hatch)\n%MAKEHATCH Predefined hatch patterns\n%  MAKEHATCH(HATCH) returns a matrix with the hatch pattern for HATCH\n%   according to the following table:\n%      HATCH        pattern\n%     -------      ---------\n%        /          right-slanted lines\n%        \\          left-slanted lines\n%        |          vertical lines\n%        -          horizontal lines\n%        +          crossing vertical and horizontal lines\n%        x          criss-crossing lines\n%        .          single dots\n%\n%  See also: APPLYHATCH\n\n%  Copyright 2009 The MathWorks, Inc.\n\nn = 6;\nA=zeros(n);\nswitch (hatch)\n case '/'\n  A = fliplr(eye(n));\n case '\\'\n  A = eye(n);\n case '|'\n  A(:,1) = 1;\n case '-'\n  A(1,:) = 1;\n case '+'\n  A(:,1) = 1;\n  A(1,:) = 1;\n case 'x'\n  A = eye(n) | fliplr(diag(ones(n-1,1),-1));\n case '.'\n  A(1:2,1:2)=1;\n otherwise\n  error(['Undefined hatch pattern \"' hatch '\".']);\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/1736-hatched-fill-patterns/makehatch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5573218372743148}}
{"text": "%    The following is an implementation of the guided filter (GF) based\n%    context enhancement (GFCE) through fusion of infrared and visible\n%    images.\n%    Ref: Zhiqiang Zhou et al. \"Fusion of infrared and visible images for night-vision context \n%    enhancement\", Applied Optics, 55(23), 2016\n%    \n%    Some of the test images were obtained at\n%      http://www.imagefusion.org\n%      http://www.ece.lehigh.edu/SPCRL/IF/image_fusion.htm\n%\n%    Zhiqiang Zhou, Beijing Institute of Technology\n%    Apr. 2016\nfor iname =1:50\n\n% close all;\nnLevel = 4;\nname = num2str(iname);\n%  path_Vis = '.\\image\\b01_1.tif';      path_IR = '.\\image\\b01_2.tif';\npath_Vis = ['..\\..\\road\\ir\\',name,'.jpg']; path_IR = ['..\\..\\road\\vi\\',name,'.jpg'];\n% path_Vis = '.\\image\\Trees4906_Vis.jpg'; path_IR = '.\\image\\Trees4906_IR.jpg';\n% path_Vis = '.\\image\\Octec_Vis.jpg';     path_IR = '.\\image\\Octec_IR.jpg';\n% path_Vis = '.\\image\\Road_Vis.jpg';      path_IR = '.\\image\\Road_IR.jpg';\n% path_Vis = '.\\image\\Kayak_Vis.jpg';     path_IR = '.\\image\\Kayak_IR.jpg';\n% path_Vis = '.\\image\\Steamboat_Vis.jpg'; path_IR = '.\\image\\Steamboat_IR.jpg';\n% path_Vis = '.\\image\\Trees4917_Vis.jpg'; path_IR = '.\\image\\Trees4917_IR.jpg';\n% path_Vis = '.\\image\\Dune_Vis.jpg';      path_IR = '.\\image\\Dune_IR.jpg';\n\n[img1, img2, para.name] = PickName(path_Vis, path_IR);\nparaShow1.fig = 'Visible image';\nparaShow2.fig = 'Infrared image';\n\n\n%% ---------- Visibility enhancement for visible image--------------\nimg1E = Ehn_GF(img1);\nimg1 = img1E;\n%% ---------- Infrared image normalization--------------\nmi = min(img2(:));\nma = max(img2(:));\nimg2 = (img2-mi)/(ma-mi)*255;\n%% ---------- Automatic parameter selection --------------\nRs = Relative_PS(img2, img1);\nif Rs<0.8\n    lambda = 100\nelse\n    if Rs>1.6\n        lambda = 2000\n    else\n        lambda = 2500*Rs - 1900\n    end\nend    \n\n%% ---------- Hybrid multiscale decomposition based on guided filter--------------\nsigma = 2;  k = 2;\nr0 = 2;     eps0 = 0.1;  \nl = 2;\n\nM1 = cell(1, nLevel+1);\nM1L = cell(1, nLevel+1);\nM1{1} = img1/255;\nM1L{1} = M1{1};\nM1D = cell(1, nLevel+1);\nM1E = cell(1, nLevel+1);\nsigma0 = sigma;\nr = r0;\neps = eps0;\nfor ii = 2:nLevel+1,\n    \n%     % ***using fast guided filter, which has the potential to achieve real-time performance when codes are fully optimized\n%     % ***NOTE: large subsampling ratio may cause problem for fusion of some source images.\n%     s = max(1, r/2); % subsampling ratio\n%     M1{ii} = fastguidedfilter_md(M1{ii-1}, M1{ii-1}, r, 100^2, s);  \n%     M1L{ii} = fastguidedfilter_md(M1L{ii-1}, M1L{ii-1}, r, eps^2, s);\n    \n    M1{ii} = guidedfilter(M1{ii-1}, M1{ii-1}, r, 100^2);  \n    M1L{ii} = guidedfilter(M1L{ii-1}, M1L{ii-1}, r, eps^2);    \n    \n    M1D{ii} = M1{ii-1} - M1L{ii};\n    M1E{ii} = M1L{ii} - M1{ii};\n    \n    sigma0 = k*sigma0;\n    r = k*r;\n    eps = eps/l;\nend\n\nM2 = cell(1, nLevel+1);\nM2L = cell(1, nLevel+1);\nM2{1} = img2/255;\nM2L{1} = M2{1};\nM2D = cell(1, nLevel+1);\nM2E = cell(1, nLevel+1);\nsigma0 = sigma;\nr = r0;\neps = eps0;\nfor ii = 2:nLevel+1,\n%     s = max(1, r/2);\n%     M2{ii} = fastguidedfilter_md(M2{ii-1}, M2{ii-1}, r, 100^2, s);\n%     M2L{ii} = fastguidedfilter_md(M2L{ii-1}, M2L{ii-1}, r, eps^2, s);\n    M2{ii} = guidedfilter(M2{ii-1}, M2{ii-1}, r, 100^2);\n    M2L{ii} = guidedfilter(M2L{ii-1}, M2L{ii-1}, r, eps^2);    \n \n    M2D{ii} = M2{ii-1} - M2L{ii};\n    M2E{ii} = M2L{ii} - M2{ii};\n\n    sigma0 = k*sigma0;\n    r = k*r;\n    eps = eps/l;\nend\n\n%% ---------- Fusion --------------\n\nfor j = nLevel+1:-1:3\nD2 = abs(M2E{j});\nD1 = abs(M1E{j});\nR = max(D2-D1, 0);\nRmax = max(R(:));\nP = R/Rmax;\n\nCj = atan(lambda*P)/atan(lambda);\n\nsigma_b = 2*sigma0;\nif j == nLevel+1\n    w = floor(3*sigma_b);\n    h = fspecial('gaussian', [2*w+1, 2*w+1], sigma_b);\n    lambda0 = lambda;\n    Cb = atan(lambda0*P)/atan(lambda0);\n    Cb = imfilter(Cb, h, 'symmetric');\n    MB = Cb.*M2{nLevel+1} + (1-Cb).*M1{nLevel+1};\nend\n\nsigma_c = 1;\nw = floor(3*sigma_c);\nh = fspecial('gaussian', [2*w+1, 2*w+1], sigma_c);   \nCj = imfilter(Cj, h, 'symmetric');\n\nmd = Cj.*M2E{j}+ (1-Cj).*M1E{j};\nMB = MB + md;\nmd = Cj.*M2D{j}+ (1-Cj).*M1D{j};\nMB = MB + md;\nend \n\nsigma_t = 1;\nw = floor(3*sigma_t);\nh = fspecial('gaussian', [2*w+1, 2*w+1], sigma_t);   \nC11 = double(abs(M1E{2}) < abs(M2E{2}));\nC11 = imfilter(C11, h, 'symmetric');\nmd = C11.*M2E{2}+ (1-C11).*M1E{2};\nMB = MB + md;  \nC10 = double(abs(M1D{2}) < abs(M2D{2}));\nmd = C10.*M2D{2}+ (1-C10).*M1D{2};\nMB = MB + md;\nFI = min(round(MB*275), 255);\nFI = max(FI, 0);\n\nparaShow.fig = 'Result';\nShowImageGrad(FI, paraShow,iname);\n\nend\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/Context-Enhance-via-Fusion-master/Context_Enhance_via_Fusion/GFCE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5573218315918378}}
{"text": "p560\n\n% at zero pose\nt = fkine(p560, qz)\nt\nq = ikine560(p560, t)\nq\nfkine(p560, q)\nikine560(p560, t, 'r')\nikine560(p560, t, 'rn')\n\nikine(p560, t)\n\n% at nominal pose\nqn\nt = fkine(p560, qn)\nt\n%q = ikine560(p560, t)\nq\nfkine(p560, q)\nikine(p560, t, [0, 0.7, 3, 0, 0.7, 0])\n\n% along trajectory\n[q,qd,qdd] = jtraj(qz, qr, 20)\nfkine(p560, q)\n\nt1 = fkine(p560, qz)\nt2 = fkine(p560, qr)\ntraj = ctraj(t1, t2, 5)\nikine(p560, traj)\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/test/kinematics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938799869521, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5573218263895116}}
{"text": "function value = r4_gamma ( x )\n\n%*****************************************************************************80\n%\n%% R4_GAMMA evaluates the 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%    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 gamma function of X.\n%\n  persistent dxrel\n  persistent gcs\n  persistent ngcs\n  persistent sq2pil\n  persistent xmax\n  persistent xmin\n  persistent xsml\n\n  sq2pil = 0.91893853320467274;\n\n  if ( isempty ( ngcs ) )\n\n    gcs = [ ...\n      0.008571195590989331, ...\n      0.004415381324841007, ...\n      0.05685043681599363, ...\n     -0.004219835396418561, ...\n      0.001326808181212460, ...\n     -0.0001893024529798880, ...\n      0.0000360692532744124, ...\n     -0.0000060567619044608, ...\n      0.0000010558295463022, ...\n     -0.0000001811967365542, ...\n      0.0000000311772496471, ...\n     -0.0000000053542196390, ...\n      0.0000000009193275519, ...\n     -0.0000000001577941280, ...\n      0.0000000000270798062, ...\n     -0.0000000000046468186, ...\n      0.0000000000007973350, ...\n     -0.0000000000001368078, ...\n      0.0000000000000234731, ...\n     -0.0000000000000040274, ...\n      0.0000000000000006910, ...\n     -0.0000000000000001185, ...\n      0.0000000000000000203 ]';\n\n    ngcs = r4_inits ( gcs, 23, 0.1 * r4_mach ( 3 ) );\n    [ xmin, xmax ] = r4_gaml ( );\n    xsml = exp ( max ( log ( r4_mach ( 1 ) ), ...\n      - log ( r4_mach ( 2 ) ) ) + 0.01 );\n    dxrel = sqrt ( r4_mach ( 4 ) );\n\n  end\n\n  y = abs ( x );\n\n  if ( y <= 10.0 )\n\n    n = r4_aint ( x );\n    if ( x < 0.0 )\n      n = n - 1;\n    end\n    y = x - n;\n    n = n - 1;\n    value = 0.9375 + r4_csevl ( 2.0 * y - 1.0, gcs, ngcs );\n\n    if ( n == 0 )\n\n      return\n\n    elseif ( n < 0 )\n\n      n = - n;\n\n      if ( x == 0.0 )\n        fprintf ( 1, '\\n' );\n        fprintf ( 1, 'R4_GAMMA - Fatal error!\\n' );\n        fprintf ( 1, '  X is 0.\\n' );\n        error ( 'R4_GAMMA - Fatal error!' )\n      end\n\n      if ( x < 0.0 && x + n - 2 == 0.0 )\n        fprintf ( 1, '\\n' );\n        fprintf ( 1, 'R4_GAMMA - Fatal error!\\n' );\n        fprintf ( 1, '  X is a negative integer.\\n' );\n        error ( 'R4_GAMMA - Fatal error!' )\n      end\n\n      if ( x < - 0.5 && ...\n        abs ( ( x - r4_aint ( x - 0.5 ) ) / x ) < dxrel )\n        fprintf ( 1, '\\n' );\n        fprintf ( 1, 'R4_GAMMA - Warning!\\n' );\n        fprintf ( 1, '  X too near a negative integer,\\n' );\n        fprintf ( 1, '  answer is half precision.\\n' );\n      end\n\n      if ( y < xsml )\n        fprintf ( 1, '\\n' );\n        fprintf ( 1, 'R4_GAMMA - Fatal error!\\n' );\n        fprintf ( 1, '  X is so close to zero that Gamma overflows.\\n' );\n        error ( 'R4_GAMMA - Fatal error!' )\n      end\n\n      for i = 1 : n\n        value = value / ( x + i - 1 );\n      end\n\n    elseif ( n == 0 )\n\n    else\n\n      for i = 1 : n\n        value = ( y + i ) * value;\n      end\n\n    end\n\n  else\n\n    if ( xmax < x )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'R4_GAMMA - Fatal error!\\n' );\n      fprintf ( 1, '  X so big that Gamma overflows.\\n' );\n      error ( 'R4_GAMMA - Fatal error!' )\n    end\n%\n%  Underflow.\n%\n    if ( x < xmin )\n      value = 0.0;\n      return\n    end\n\n    value = exp ( ( y - 0.5 ) * log ( y ) - y + sq2pil + r4_lgmc ( y ) );\n\n    if ( 0.0 < x )\n      return\n    end\n\n    if ( abs ( ( x - r4_aint ( x - 0.5 ) ) / x ) < dxrel )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'R4_GAMMA - Warning!\\n' );\n      fprintf ( 1, '  X too near a negative integer,\\n' );\n      fprintf ( 1, '  answer is half precision.\\n' );\n    end\n\n    sinpiy = sin ( pi * y );\n\n    if ( sinpiy == 0.0 )\n      fprintf ( 1, '\\n' );\n      fprintf ( 1, 'R4_GAMMA - Fatal error!\\n' );\n      fprintf ( 1, '  X is a negative integer.\\n' );\n      error ( 'R4_GAMMA - Fatal error!' )\n    end\n\n    value = - pi / ( y * sinpiy * value );\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_gamma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5572482712663144}}
{"text": "%% Example Scene\n%\n% This script demonstrates using a combination of functions to create\n% terrain, add a sky, set some lighting options, and provide the ability to\n% rotate around the figure. It uses several of MATLAB's 3D graphics \n% commands, including patches, lighting, camera positioning, and\n% projection. If any of these are unfamiliar, the documentation covers them\n% well. MATLAB can produce much more than simple plots.\n%\n% This script is likely to take between 3 and 30 seconds to complete on\n% most computers.\n%\n% Tucker McClure\n% Copyright 2012, The MathWorks, Inc.\n\n%%\n% Create or clear a figure for the rendering.\nfigure(1);\nclf();\n\n%% Land and Sea\n\n% Create the terrain height map.\n[~, ~, ~, hm, xm, ym] = generate_terrain(7, 513, 0, 0.1);\n\n% Generate appropriate colors.\ncm = generate_terrain_colors(hm);\n\n% Flatten the oceans.\nhmp = max(hm, 0);\n\n% Draw the land and calculate its normal vectors.\nh_land = patch(surf2patch(xm, ym, hmp, cm));\n[nx, ny, nz] = surfnorm(hmp);\nland_normals = [nx(:), ny(:), nz(:)];\n\n% Set it's material properties for interpolated colors and appropriate\n% lighting.\nset(h_land, 'VertexNormals',    land_normals, ...\n            'DiffuseStrength',  0.8, ...      % Reacts to light direction\n            'SpecularStrength', 0, ...        % Not shiny\n            'AmbientStrength',  0.3, ...      % Reacts to ambient light\n            'BackFaceLighting', 'unlit');     % Don't illuminate reverse\n\n% Add a black backdrop beneath the land. Sometimes a vertex seems to miss\n% its position slightly, and sky colors creep through, and that's weird.\npatch('Faces',           [1 2 3 4], ...\n      'Vertices',        [-1 -1 -0.01; ...\n                           1 -1 -0.01; ...\n                           1  1 -0.01; ...\n                          -1  1 -0.01], ...\n      'FaceVertexCData', 0.25*ones(4, 3));\n        \n%% Sky\n        \n% Draw a random time of day between sunrise and sunset. Get the\n% corresponding light color. The sky is always the color of the sun at noon\n% (and is then affected by the sun color at the current time).\ncurrent_time = 0.24 + 0.52 * rand();\nsun_color    = sun_tones(current_time);\nsky_color    = sun_tones(0.5);\n\n% Create the sky patch by scaling a sphere. Note that the nothing in the\n% scene can be rendered outside of [-100, 100] on any axis due to a\n% documented rendering bug. Therefore, the sphere will be scaleld up to\n% 99, which is plenty far away since the terrain is limited to [-1, 1].\n[xs, ys, zs] = sphere(16);\nsky_scale = 99;\nsky_patch = surf2patch(sky_scale*xs, sky_scale*ys, sky_scale*zs, ...\n                       repmat(reshape(sky_color, [1 1 3]), [17 17 1]));\nh_sky = patch(sky_patch);\n\n% Set appropriate lighting options for the sky.\nset(h_sky, 'DiffuseStrength',  0.3, ...\n           'SpecularStrength', 0, ...\n           'AmbientStrength',  1, ...\n           'BackFaceLighting', 'unlit');\n\n% Vertex normals are the opposite of what I expect. Reverse them.\nset(h_sky,  'VertexNormals', -get(h_sky, 'VertexNormals'));\n\n%% Sun\n\n% Create a light for the sun.\nh_light = lightangle(90, 360*(current_time - 0.25));\n\n% Set the light's color.\nset(h_light, 'Color', sun_color);\n\n% Set the ambient color used in the scene.\nset(gca(), 'AmbientLightColor', sun_color);\n\n% Use decent lighting.\nlighting gouraud;\n\n%% Axes and Global Settings\n\n% Set axes options.\ncamera_target   = [0 0 mean(hmp(:)) + 0.5*std(hmp(:))];\ncamera_position = camera_target + [1.15 0 0.5];\nset(gca, 'DataAspectRatio', [1 1 1], ...\n         'Visible',         'off', ...\n         'Projection',      'Perspective', ...\n         'Position',        [0 0 1 1], ...\n         'CameraTarget',    camera_target, ...\n         'CameraViewAngle', 45, ...\n         'CameraUpVector',  [0 0 1], ...\n         'CameraPosition',  camera_position, ...\n         'XLim',            [-100 100], ...\n         'YLim',            [-100 100], ...\n         'ZLim',            [-100 100]);\ncamorbit(360*rand(), 0);\n\n% Patches should have no edges and interpolated face colors.\nshading interp;\n\n% Force the drawing.\ndrawnow();\n\n% Add FigureRotator to allow the user to rotate around the middle of the\n% scene and zoom in and out using a mouse. This is available in the extras\n% zip file or from File Exchange. Use |unzip terrain_generation_extras.zip|\n% in this directory to extract FigureRotator along with an example file.\nif exist('FigureRotator', 'class');\n    f = FigureRotator(gca());\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/39559-automatic-terrain-generation/example_scene.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5572482595970731}}
{"text": "function [G, pixels, patches] = gsp_patch_graph(img, param)\n%GSP_PATCH_GRAPH Create a graph by NN patches of an image\n%   Usage :  G = compute_patch_graph( img );\n%            [G, f] = gsp_patch_graph( img, param );\n%            [G, f, patches] = gsp_patch_graph( img, param );\n%\n%   Input parameters:\n%       img         : Input image (unknown pixels marked as NaN)\n%       param       : Structure of optional parameters\n%\n%   Output parameters:\n%       G           : Resulting graph\n%       f           : Image signal\n%       patches     : Patches\n%\n%   'compute_patch_graph( path , param )' creates a graph between pixels in\n%   an image by connecting them using the euclidean distance between\n%   patches around the pixels\n%\n%   Additional parameters\n%   ---------------------\n%\n%   * *param.patch_size*      : int     the patch size in pixels (odd)\n%   * *param.scale*           : float   to rescale the input image\n%   * *param.rho*             : float   spatial constraint\n%   * *use_incomplete_patch*  : boolean use incomplete patch for the graph construction\n%   * *param.nnparam*         : struct  parameters for graph construction\n%\n\n% Author: Johan Paratte, Michael Defferrard, Nathanael Perraudin\n% Date: November 2014\n% \n\n    if nargin < 2\n    % Define parameters\n        param = {};\n    end\n    \n    if ~isfield(param, 'patch_size'), param.patch_size = 5; end\n    if ~isfield(param, 'rho'), param.rho = 0.001; end\n    if ~isfield(param, 'use_incomplete_patch'), param.use_incomplete_patch = 0; end\n    if ~isfield(param, 'nnparam')\n       param.nnparam = {};\n       param.nnparam.center = 0;\n       param.nnparam.resize = 0;\n       param.nnparam.k = 10;\n       param.nnparam.use_l1 = 0;\n       param.nnparam.use_flann = 1;\n    end\n    \n    if (mod(param.patch_size, 2) == 0) \n        disp('Patch size must be odd, converting to closest odd number');\n        param.patch_size = param.patch_size + 1;\n    end\n    \n%     if length(size(img)) > 2\n%        img = rgb2gray(img); \n%     end\n\n    %Extract patches\n    [oheight, owidth,Nc] = size(img);\n    \n    \n    \n    psize = param.patch_size;\n    \n    %Parameters\n    if isfield(param, 'scale')\n        img = imresize(img, param.scale);\n    end\n    \n    margin = floor(psize / 2);\n    \n\n    \n    dim = psize*psize;\n    %height = (oheight - 2*margin);\n    %width = (owidth - 2*margin);\n    \n    %Expand the image to compensate the margin\n    h = oheight;\n    w = owidth;\n    new_img = zeros(h + 2*margin, w + 2*margin,Nc);\n    %Copy image\n    new_img(1+margin:end-margin, 1+margin:end-margin,:) = img;\n    %Four lines\n    new_img(1:margin, 1+margin:end-margin,:) = img(margin:-1:1, :,:);\n    new_img(1+margin:end-margin, 1:margin,:) = img(:, margin:-1:1,:);\n    new_img(end-margin:end, 1+margin:end-margin,:) = img(end:-1:end-margin, :,:);\n    new_img(1+margin:end-margin, end-margin:end,:) = img(:,end:-1:end-margin,:);\n    %Four corners\n    new_img(1:margin, 1:margin,:) = img(margin:-1:1, margin:-1:1,:);\n    new_img(1:margin, end-margin:end,:) = img(margin:-1:1, end:-1:end-margin,:);\n    new_img(end-margin:end, 1:margin,:) = img(end:-1:end-margin, margin:-1:1,:);\n    new_img(end-margin:end, end:-1:end-margin,:) = img(end:-1:end-margin, end:-1:end-margin,:);\n    \n    % Signals on the graph.\n    patches = zeros(h*w, dim*Nc+2);\n    pixels  = double(reshape(img, h*w, Nc)); % zeros(h*w, 1);\n    coords  = zeros(h*w, 2);  % gsp_plot_signal takes [x,y]\n    coords(:,2) = repmat((h:-1:1).', w, 1);\n    coords(:,1) = reshape(repmat((1:+1:w), h, 1), [], 1);\n    \n    % Pre-allocation.\n    nUnknown = sum(sum(img(:,:,1)<0)) * 2;\n    unknowns = zeros(nUnknown, 1);\n    iUnknown = 0;\n    \n    count = 1;\n    \n    % For speed improvement, one of the for loop can probably be removed\n    % here\n    for w = 1:owidth\n       for h = 1:oheight\n            patches(count, 1:Nc*dim) = reshape(new_img(h:h+psize-1, w:w+psize-1,:), 1, Nc*dim);\n            patches(count, Nc*dim+1:end) = [param.rho*w; param.rho*h];\n            count = count + 1;\n        end\n    end\n    \n    fprintf('Compute graph with %d vertices\\n', size(patches,1));\n    \n    if param.use_incomplete_patch\n\n        G = gsp_rmse_mv_graph(patches, param.nnparam);\n    else\n        % Ignore patches which contain unknown pixel values.\n        % We do not want them to be connected with known patches.\n        clearedPatches = patches;\n\n        for count = 1:size(clearedPatches,1)\n            if sum(isnan(clearedPatches(count,:)))\n                clearedPatches(count,:) = -1e3;\n                % List of unknown patches.\n                iUnknown = iUnknown + 1;\n                unknowns(iUnknown) = count;\n            end\n        end\n\n\n        G = gsp_nn_graph(clearedPatches, param.nnparam);\n\n        % Disconnect unknown patches.\n        unknowns = unknowns(1:iUnknown);\n        G.W(unknowns,:) = 0;\n        G.W(:,unknowns) = 0;\n        \n        % Update G.A, G.d and G.Ne.\n        G = gsp_graph_default_parameters(G);\n    end\n    \n\n    \n    % These are coordinates in the high dimensional patch space. We prefer\n    % to visualize the graph in the 2D image space.\n%     patches = G.coords;\n    G.coords = coords;\n    G.plotting.limits = [1,w,1,h];\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/imageprocessing/gsp_patch_graph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5572482545477639}}
{"text": "function M=ImpliedExpRets(S,w)\n\nM_=S*w;\n\ns=sqrt(mean(diag(S)));\nM=M_/mean(M_)*.5*s;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21307-fully-flexible-views-and-stress-testing/EntropyPooling/RankingInformation/ImpliedExpRets.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5572302116532863}}
{"text": "function [f] = elec_ellipse_fit_optim(r, X, Y, Z, xo, yo, zo)\n\n% elec_ellipse_fit_optim - Optimization for elec_ellipse_fit.m\n%\n% Called from elec_ellipse_fit.m\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:54 $\n\n% Licence:  GNU GPL, no implied or express warranties\n% History:  02/2002, Darren.Weber_at_radiology.ucsf.edu\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% r is a 3x1 vector of radius values for each x,y,z axis component of\n% ellipse\n%\n% equation of ellipsoid with center (xo,yo,zo) and radius for each axis (x,y,z) = (a,b,c):\n% (( x - xo )^2 / a^2) + (( y - yo )^2 / b^2) + (( z - zo )^2 / c^2) = 1\n%\n% This function below creates a scalar value to\n% return to the fminsearch function in elec_ellipse_fit.\n\nE = ( (X-xo).^2 )/r(1).^2 + ((Y-yo).^2)/r(2).^2 + ((Z-zo).^2)/r(3).^2  - 1;\n\nf = sum( E .* E );  % sum of squares returned\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_ellipse_fit_optim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5572236590073386}}
{"text": "function fx1 = p09_fx1 ( x )\n\n%*****************************************************************************80\n%\n%% P09_FX1 evaluates the derivative of the function for problem 9.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    07 May 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, real X, the abscissa.\n%\n%    Output, real FX1, the first derivative of the function at X.\n%\n  x2 = x - 6.25;\n\n  if ( x2 < - 0.25 )\n    fx1 = 0.75;\n  elseif ( x2 < 0.25 )\n    fx1 = 2.0;\n  else\n    fx1 = 0.75;\n  end\n\n  return\nend\n", "meta": {"author": "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/p09_fx1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.5572236573331384}}
{"text": "function [regions, thresholds, maxSig] = imMultiOtsuThreshold(img, nClasses, varargin)\n% Multilevel Thresholding using Otsu Method.\n%\n%   CLASSES = imMultiOtsuThreshold(IMG, NC)\n%   Computes a segmentation of the input grayscale image IMG into NC \n%   classes. The number of classes must be comprised between 2 and 5.\n%\n%   [CLASSES, THRESHOLDS] = imMultiOtsuThreshold(IMG, NC)\n%   Also returns the list of threshold. The number of threshold values is\n%   the number of classes minus one.\n%\n%   Example\n%     % segment cameraman image into three classes\n%     img = imread('cameraman.tif');\n%     [classes, threshs] = imMultiOtsuThreshold(img, 3);\n%     rgb = label2rgb(classes, 'jet', [1 0 0], 'shuffle');\n%     figure; imshow(rgb);\n%     % also displays histogram with threshold levels\n%     figure; imHistogram(img);\n%     hold on;\n%     for i = 1:2\n%        plot(threshs([i i]), [0 1800], 'color', 'r', 'linewidth', 2);\n%     end\n%\n%   References\n%   * Ping-Sung Liao, Tse-Sheng Chen, Pau-Choo Chung (2001). \"A Fast\n%   Algorithm for Multilevel Thresholding\". Journal of Information Science\n%   and Engineering, Vol. 17 No. 5, pp. 713-727.  \n%   https://jise.iis.sinica.edu.tw/JISESearch/pages/View/PaperView.jsf?keyId=86_1302#\n%   * https://imagej.net/Multi_Otsu_Threshold\n%\n%   See also\n%     imOtsuThreshold, imHistogram, imMaxEntropyThreshold\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% INRAE - BIA Research Unit - BIBS Platform (Nantes)\n% Created: 2021-01-29,    using Matlab 9.8.0.1323502 (R2020a)\n% Copyright 2021 INRAE.\n\n%% Input arguments\n\nif ~isa(img, 'uint8')\n    error('Requires a grayscale uint8 image as first input');\nend\n\nif nClasses < 2 || nClasses > 5\n    error('The number of classes must be comprised between 2 and 5.');\nend\n\n\n%% Initialisations\n\n% compute histogram, and convert into probability density\n[h, levels] = imHistogram(img, varargin{:});\nh = h / sum(h);\n\n% number of gray levels\nnLevels = length(levels);\n\nPuv = zeros(nLevels, nLevels);\nSuv = zeros(nLevels, nLevels);\nHuv = zeros(nLevels, nLevels);\n\n% initialize diagonal terms\nfor i = 1:nLevels\n    Puv(i, i) = h(i);\n    Suv(i, i) = h(i) * i;\nend\n\n% initialize first rows\nfor i = 2:nLevels\n    Puv(1, i) = Puv(1, i-1) + h(i);\n    Suv(1, i) = Suv(1, i-1) + i*h(i);  \nend\n% initialize the rest of the matrices\nfor u = 2:nLevels\n    for v = u+1:nLevels\n        Puv(u, v) = Puv(1, v) - Puv(1, u-1);\n        Suv(u, v) = Suv(1, v) - Suv(1, u-1);\n    end\nend\n\n% now calculate Huv\nfor u = 1:nLevels\n    for v = u+1:nLevels\n        if Puv(u,v) > 0\n            Huv(u,v) = Suv(u,v) * Suv(u,v) / Puv(u,v);\n        end\n    end\nend\n\n\n%% Main processing\n\n% create array for threshold values (first one is zeros, last one is inf)\nthresholds = zeros(nClasses+1, 1);\nthresholds(end) = inf;\n\n% iterate over all possible combinations\nmaxSig = 0.0;\nswitch nClasses\n    case 2\n        % two classes -> only need to find second threshold value\n        for i = 1:nLevels-1\n            Sq = Huv(1,i) + Huv(i+1, end);\n            if Sq >= maxSig\n                thresholds(2) = i;\n                maxSig = Sq;\n            end\n        end\n        \n    case 3\n        % three classes\n        for i = 1:nLevels-2\n            for j = i+1:nLevels-1\n                Sq = Huv(1,i) + Huv(i+1, j) + Huv(j+1, end);\n                if Sq >= maxSig\n                    thresholds(2) = i;\n                    thresholds(3) = j;\n                    maxSig = Sq;\n                end\n            end\n        end\n        \n    case 4\n        % four classes\n        for i = 1:nLevels-3\n            for j = i+1:nLevels-2\n                for k = j+1:nLevels-1\n                    Sq = Huv(1,i) + Huv(i+1, j) + Huv(j+1, k) + Huv(k+1, end);\n                    if Sq >= maxSig\n                        thresholds(2) = i;\n                        thresholds(3) = j;\n                        thresholds(4) = k;\n                        maxSig = Sq;\n                    end\n                end\n            end\n        end\n        \n    case 5\n        % five classes\n        for i = 1:nLevels-3\n            for j = i+1:nLevels-2\n                for k = j+1:nLevels-1\n                    for m = k+1:nLevels-1\n                        Sq = Huv(1,i) + Huv(i+1, j) + Huv(j+1, k) + Huv(k+1, m) + Huv(m+1, end);\n                        if Sq >= maxSig\n                            thresholds(2) = i;\n                            thresholds(3) = j;\n                            thresholds(4) = k;\n                            thresholds(5) = m;\n                            maxSig = Sq;\n                        end\n                    end\n                end\n            end\n        end\n        \n    otherwise\n        error('Can not manage %d number of classes', nClasses);\nend\n\n\n%% Create region image\n\nregions = zeros(size(img), 'uint8');\nfor i = 1:nClasses\n    inds = img >= thresholds(i) & img < thresholds(i+1);\n    regions(inds) = i;\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/imMultiOtsuThreshold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5572236428861136}}
{"text": "function linplus_test0196 ( )\n\n%*****************************************************************************80\n%\n%%  TEST0196 tests R8VEC_TO_R8GE, R8GE_TO_R8VEC.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 March 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 4;\n  n = 6;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST0196\\n' );\n  fprintf ( 1, '  For a general matrix,\\n' );\n  fprintf ( 1, '  R8VEC_TO_R8GE converts a real vector to a R8GE matrix.\\n' );\n  fprintf ( 1, '  R8GE_TO_R8VEC converts a R8GE matrix to a real vector.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Matrix rows M =    %d\\n', m );\n  fprintf ( 1, '  Matrix columns N = %d\\n', n );\n\n  a = r8ge_indicator ( m, n );\n\n  r8ge_print ( m, n, a, '  The R8GE indicator matrix:' );\n\n  x = r8ge_to_r8vec ( m, n, a );\n\n  k = 0;\n  for j = 1 : n\n    for i = 1 : m\n      k = k + 1;\n      fprintf ( 1, '%4d  %4d  %4d  %14f\\n', i, j, k, x(k) );\n    end\n  end\n\n  a = r8vec_to_r8ge ( m, n, x );\n\n  r8ge_print ( m, n, a, '  The recovered R8GE indicator matrix:' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/linplus_test0196.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.5571807861560645}}
{"text": "% clear; close all; clc;\n\nfunction ani_slider\nfs = 200;\nt = 0:1/fs:5-1/fs;\nf = 1;\nx = sin(2*pi*1*t);\n\nfigure;\nset(gcf,'position',[500 500 640 480]);\nfigsize = get(gcf,'position');\nh = plot(t,x);\n\nSliderH = uicontrol('style','slider','position',[70 6 512 20],'min',1,'max',5,'value',1,'callback',@cbfcn);\n\n    function cbfcn(src, event)\n       f = SliderH.Value ;\n       x = sin(2*pi*f*t);\n       h = plot(t,x);\n    end\nend\n", "meta": {"author": "angeloyeo", "repo": "gongdols", "sha": "7be9fbd988dec6edab1dc881cb22d63e6f69398d", "save_path": "github-repos/MATLAB/angeloyeo-gongdols", "path": "github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/MATLAB\uac15\uc758/animation\ub9cc\ub4e4\uae30/uicontrol\uc744_\ud65c\uc6a9\ud55c_animation/ani_slider_using_callback.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5571807792849969}}
{"text": "function gsp()\n% GSP General Piecewise Spline Interpolation\n%\n% GSP is a graphical user interface which takes x and y points as inputs, along with\n% the order m, then outputs mth order splines between each of the x points. In most \n% cases additional constraints are to be entered as well.\n% \n% Example:\n% \n% Input:\n% \n% x points : [1 2 3 4]\n% y points : [2 7 -1 5]\n% Order    : 2\n% *One Additional Constraint is Required*\n% f''(1) = 0\n% \n% Output:\n% Polynomials:\n%   0             5            -3\n% -13            57           -55\n%  27          -183           305\n% \n% In the Range:\n% 1  2\n% 2  3\n% 3  4\n% \n% This means the following:\n% \n% for 1 < x < 2   y = 0*x^2 + 5*x - 3\n% for 2 < x < 3   y = -13*x^2 + 57*x - 55\n% for 3 < x < 4   y = 27*x^2 - 183*x + 305\n% \n% You can obtain the mentioned forms using poly2sym (requires Symbolic Math Toolbox).\n% \n% If you want to delete constraints, put its values as '*'. For more help and examples,\n% see the pictures accompanied in the zip file. An optional feature can be\n% accesessed if the function MQUAKE is present. mquake.m can be found here:\n% <http://www.mathworks.com/matlabcentral/fileexchange/22816>\n% \n% To launch the GUI, type gsp in the command window with this file in the current directory.\n% Alternatively, you can choose Debug -> Run from this editor window, or press F5.\n% \n% \n% Husam Aldahiyat, 2009\n% numandina@gmail.com\n%\nglobal aA\n\n%% figure and uicontrols\nfigure('units','normalized','position',[.2 .2 .65 .65],'menubar','none','numbertitle','off','color','w','name','General Splines')\naxes('position',[.35 .1 .5 .5])\ned1=uicontrol('style','edit','units','normalized','position',[.025 .875 .1 .05],'backgroundcolor','w');\nuicontrol('style','text','units','normalized','position',[.025 .94 .1 .025],'backgroundcolor','w','string','x Points');\ned2=uicontrol('style','edit','units','normalized','position',[.025 .75 .1 .05],'backgroundcolor','w');\nuicontrol('style','text','units','normalized','position',[.025 .81 .1 .025],'backgroundcolor','w','string','Y Points');\npx=uicontrol('style','listbox','units','normalized','position',[.2 .75 .1 .2],'max',2,'backgroundcolor','w',...\n\t'string',{'Example 1';'Example 2';'Example 3';'Example 4';'Example 5';'Example 6'},'callback',@pn);\ned3=uicontrol('style','edit','units','normalized','position',[.045 .63 .05 .05],'backgroundcolor','w','callback',@cond);\nuicontrol('style','text','units','normalized','position',[.025 .69 .1 .025],'backgroundcolor','w','string','Spline Order');\nerr=uicontrol('style','text','foregroundcolor','r','units','normalized','position',[.025 .55 .22 .05],'backgroundcolor','w',...\n\t'horizontalalignment','left');\nuicontrol('style','pushbutton','units','normalized','position',[.15 .63 .05 .05],'backgroundcolor','w','callback',@go,'string','Solve');\npv=uicontrol('style','pushbutton','units','normalized','position',[.22 .63 .075 .05],'backgroundcolor','w','callback',@dv,...\n\t'string','Continuity','visible','off');\nthih=uicontrol('style','edit','units','normalized','position',[.025 .025 .125 .525],'backgroundcolor','w','max',2,'string','',...\n\t'horizontalalignment','right','fontsize',13,'fontname','calibri');\nedc=uicontrol('style','edit','units','normalized','position',[.15 .025 .075 .525],'backgroundcolor','w','max',2,...\n\t'horizontalalignment','left','fontsize',13,'fontname','calibri','string','');\nAp=uicontrol('style','listbox','units','normalized','position',[.35 .675 .5 .25],'backgroundcolor','w','max',2,'fontname','courier',...\n\t'callback',@chv);\nAc=uicontrol('style','listbox','units','normalized','position',[.85 .675 .125 .25],'backgroundcolor','w','max',2,'fontname','courier');\nuicontrol('style','text','units','normalized','position',[.35 .935 .5 .025],'backgroundcolor','w','max',2,'string','Spline Polynomials');\nuicontrol('style','text','units','normalized','position',[.85 .935 .12 .025],'backgroundcolor','w','max',2,'string','For x in the range');\n\n\tfunction cond(varargin)\t\t\n\t\tm=str2double(get(ed3,'string'));\n\t\tif m>1\n\t\t\tx=str2num(get(ed1,'string')); %#ok\n\t\t\tif isempty(x)\n\t\t\t\tset(err,'string','Please give values for x')\n\t\t\t\treturn\n\t\t\tend\n\t\t\tset(err,'string',sprintf('%d Additional Condition(s) Needed',m-1))\n\t\t\ttrip=cell(m*2,1);\n\t\t\tfor k1=1:m\n\t\t\t\tkoi=repmat('''',1,k1);\n\t\t\t\ttrip{k1}=['f ',koi,'(',num2str(x(1)),') = '];\n\t\t\t\ttrip{k1+m}=['f ',koi,'(',num2str(x(end)),') = '];\n\t\t\tend\n\t\t\tset(thih,'string',trip);\n\t\telse\n\t\t\tset(err,'string','No Additional Constraints Required');\n\t\t\tset(edc,'string','')\n\t\t\tset(thih,'string','')\n\t\tend\n\t\tif m>1\n\t\t\tset(edc,'string',repmat('*',m*2,1))\n\t\tend\n\tend\n\n\tfunction pn(varargin)\n\t\tswitch get(px,'value')\n\t\t\tcase 1\n\t\t\t\t set(ed1,'string','0 10')\n\t\t\t\t set(ed2,'string','0 0')\n\t\t\t\t set(ed3,'string','2')\n\t\t\t\t cond\n\t\t\t\t set(err,'string','')\n\t\t\t\t set(edc,'string',['5';'*';'*';'*'])\n\t\t\tcase 2\n\t\t\t\t set(ed1,'string','0 1 2')\n\t\t\t\t set(ed2,'string','0 1 0')\n\t\t\t\t set(ed3,'string','3')\n\t\t\t\t cond\n\t\t\t\t set(err,'string','')\n\t\t\t\t set(edc,'string',['0';'*';'*';'0';'*';'*'])\t\n\t\t\tcase 3\n\t\t\t\t set(ed1,'string','0 1 2')\n\t\t\t\t set(ed2,'string','0 1 0')\n\t\t\t\t set(ed3,'string','5')\n\t\t\t\t cond\n\t\t\t\t set(err,'string','')\n\t\t\t\t set(edc,'string',['0';'0';'*';'*';'*';'0';'0';'*';'*';'*'])\t\t\t\t\n\t\t\tcase 4\n\t\t\t\t set(ed1,'string','1 2 3 4 7')\n\t\t\t\t set(ed2,'string','2 -4 0 3 0')\n\t\t\t\t set(ed3,'string','3')\n\t\t\t\t cond\n\t\t\t\t set(err,'string','')\n\t\t\t\t set(edc,'string',['*';'0';'*';'*';'0';'*'])\t\t\t\t\n\t\t\tcase 5\n\t\t\t\t set(ed1,'string','1 2 4 6 8 10')\n\t\t\t\t set(ed2,'string','2 4 -2 3 1 0')\n\t\t\t\t set(ed3,'string','5')\n\t\t\t\t cond\n\t\t\t\t set(err,'string','')\n\t\t\t\t set(edc,'string',strvcat('5','0','*','*','*','-4','3','*','*','*')) %#ok\t\t\t\n\t\t\tcase 6\t\t\t\n\t\t\t\t set(ed1,'string','1 2 4 6 8 10')\n\t\t\t\t set(ed2,'string','2 4 -2 3 1 0')\n\t\t\t\t set(ed3,'string','5')\n\t\t\t\t cond\n\t\t\t\t set(err,'string','')\n\t\t\t\t set(edc,'string',strvcat('-5','0','*','*','*','4','3','*','*','*')) %#ok\n\t\tend\t\t\n\tend\n\n%% Solution\n\n\tfunction go(varargin)\n\t\tset(pv,'visible','off')\n\t\tx=str2num(get(ed1,'string')); %#ok\n\t\ty=str2num(get(ed2,'string')); %#ok\n\t\tif length(y)~=length(x)\n\t\t\tset(err,'string','Points are not of equal lengths')\n\t\t\treturn\n\t\tend\n\t\tif any(find(abs(sort(x)-x)>1e-10))\n\t\t\tset(err,'string','x Points need to be ascending')\n\t\t\treturn\n\t\tend\n\t\tif length(unique(x))<length(x)\n\t\t\tset(err,'string','Repeated x points found')\n\t\t\treturn\n\t\tend\n\t\tm=str2double(get(ed3,'string'));\n\t\tn=length(x)-1; % number of splines\n\t\tg=fliplr(0:m);\n\t\tDAT=zeros((m+1)*n);\n\t\tB=zeros(n*(1+m),1);\n\t\tB(1:n+1)=y;\n\t\tS=zeros(n,m+1);\n\t\tfor k=1:n\n\t\t\tDAT(k,k+m*k-m:k+m*k)=x(k).^g;\n\t\tend\n\t\tDAT(k+1,k+m*k-m:k+m*k)=x(k+1).^g;\n\t\tk=k+2;\n\t\tpoln=ones(1,m+1);\n\t\tfor k2=1:m\n\t\t\tpol=[poln,zeros(1,(k2-1))];\n\t\t\tfor p=1:n-1\n\t\t\t\tDAT(k+p+k2*n-k2-n,p*m+p-m:p*m+p+m+1)=...\n\t\t\t\t\trepmat(pol,1,2).*repmat(x(p+1),1,(m+1)*2).^repmat(g-(k2-1),1,2).*[ones(1,m+1),-ones(1,m+1)];\n\t\t\tend\t\t\t\n\t\t\tpoln=polyder(poln);\n\t\tend\n\t\taa=(get(edc,'string'));\t\n\t\tif m>1\n\t\t\tcon=find(~ismember(1:m*2,findstr(aa(:,1)','*'))==1);\n\t\t\tif length(con)>m-1\n\t\t\t\tset(err,'string','Too many constraints entered')\n\t\t\t\treturn\n\t\t\tend\n\t\t\tif isempty(con)\n\t\t\t\tset(err,'string','Too few constraints entered')\n\t\t\t\treturn\n\t\t\tend\n\t\t\tfor lp=1:m-1\n\t\t\t\tpoln=ones(1,m+1);\n\t\t\t\two=con(1);\n\t\t\t\tif wo>m\n\t\t\t\t\tcon(1)=con(1)-m;\n\t\t\t\tend\n\t\t\t\tfor h1=1:con(1)\n\t\t\t\t\tpoln=polyder(poln);\n\t\t\t\tend\n\t\t\t\tif wo>m\t\t\t\t\t\n\t\t\t\t\tDAT(end-(m-1-lp),end-m:end)=repmat(x(end),1,m+1).^(g-con(1)).*[poln,zeros(1,m+1-length(poln))];\n\t\t\t\t\tB(end-(m-1-lp))=str2double(aa(wo,:));\n\t\t\t\tend\n\t\t\t\tif wo<=m\n\t\t\t\t\tDAT(end-(m-1-lp),1:m+1)=[poln,zeros(1,m+1-length(poln))].*repmat(x(1),1,m+1).^(g-con(1));\n\t\t\t\t\tB(end-(m-1-lp))=str2double(aa(con(1),:));\n\t\t\t\tend\n\t\t\t\tcon(1)=[];\n\t\t\tend\n\t\tend\n\t\tDAT(isnan(DAT))=0;\t\t\n\t\ts=DAT\\B;\n\t\tC=zeros(n,2);\n\t\tfor k=1:n\n\t\t\tS(k,:)=s(k*(m+1)-m:k*(m+1));\n\t\t\tC(k,:)=x(k:k+1);\n\t\tend\n\t\tset(err,'string','')\n\n%% Displaying Results\n\n\t\tset(Ap,'string',num2str(S))\n\t\tset(Ac,'string',num2str(C))\n\t\tcla reset\n\t\thold on\n\t\tst=[1 0 0;0 1 0];\n\t\tfor k=1:n\n\t\t\tt=linspace(C(k,1),C(k,2),100);\n\t\t\tf=polyval(S(k,:),t);\n\t\t\taA(k)=plot(t,f);\n\t\t\tset(findobj('color','b'),'color',st(mod(k,2)+1,:),'linewidth',2)\t\t\t\n\t\tend\n\t\tplot(x,y,'.')\n\t\tset(findobj('marker','.'),'markersize',10,'color','k')\n\t\txlabel('x')\n\t\tylabel('y')\n\t\txlim([x(1)-1 x(end)+1])\n\t\th=axis;\n\t\tif h(3)>min(y)-1\n\t\t\th(3)=min(y)-1;\n\t\tend\n\t\tif h(4)<max(y)+1\n\t\t\th(4)=max(y)+1;\n\t\tend\n\t\taxis(h)\n\t\tset(pv,'visible','on')\n\tend\n\n\tfunction dv(varargin)\n\t\tS=str2num(get(Ap,'string')); %#ok\n\t\tC=str2num(get(Ac,'string')); %#ok\n\t\tst=[1 0 0;0 1 0];\n\t\tm=str2double(get(ed3,'string'));\n\t\tn=length(str2num(get(ed1,'string')))-1; %#ok\n\t\tfigure('color','w','menubar','none','numbertitle','off','name','Continuity')\n\t\tfor k2=1:m\n\t\t\tfor g=1:n\n\t\t\t\tS(g,:)=[zeros(m+1-length([polyder(S(g,1:end-k2+1)),zeros(1,k2)])),polyder(S(g,1:end-k2+1)),zeros(1,k2)];\n\t\t\tend\n\t\t\tsubplot(ceil(m/2),ceil(m/ceil(m/2)),k2)\n\t\t\thold on\n\t\t\tfor k=1:n\n\t\t\t\tt=linspace(C(k,1),C(k,2),100);\n\t\t\t\tf=polyval(S(k,1:end-k2),t);\n\t\t\t\tplot(t,f);\n\t\t\t\tset(findobj('color','b'),'color',st(mod(k,2)+1,:),'linewidth',2)\n\t\t\tend\n\t\t\ttitle(sprintf('Derivate Order %d',k2))\n\t\tend\n\tend\n\n\tfunction chv(varargin)\t\t\n\t\th=axis;\n\t\ttry\n\t\t\tmquake(aA(get(Ap,'value')),(h(2)+h(4))/4,.5,1)\n\t\tcatch\n\t\tend\n\tend\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/22912-mth-order-piecewise-spline-interpolation/gsp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5571807762769204}}
{"text": "% CHARACTER RECOGNITION SYSTEM\n\nfunction CR()\nclear workspace\nclear\n% Input Data Preparation\nx=65;\nfor i=1:4\nal=char(x);\nfl=strcat(al,'.bmp');\ninp(i,:)=roworder(fl);\nx=x+1;\nend\ninp=inp';\ninp=double(inp);\n%Output Data Preparation\nfor i=0:3\n    x=dec2bin(i,2);\n    for j=1:2\n        y(j)=str2num(x(j));\n    end\n    out(i+1,:)=y;\nend\nout=out';\n% Network Creation\n     network=newff([zeros(size(inp,1),1) ones(size(inp,1),1)],[7 2],{'logsig','logsig'});\n  %   network=init(network);\n     \nnetwork.iw{1}=dlmread('layer1.txt');\nnetwork.b{1}=dlmread('layer1b.txt');\nnetwork.lw{2}=dlmread('layer2.txt');\nnetwork.b{2}=dlmread('layer2b.txt');\n\n% Network Training  \nnetwork.performFcn = 'sse';\nnetwork.trainParam.epochs = 500;\nnetwork=train(network,inp,out);\n% Network Testing \n  display('Network Testing - With Boldness (Arial)');\n  D=sim(network,inp);\n  D=round(D);\n  D\n % Testing with new data\nx=65;\nfor i=1:4\nal=char(x);\nfl=strcat(al,'1.bmp');\nin(i,:)=roworder(fl);\nx=x+1;\nend \nin=in';\nin=double(in);\ndisplay('Testing with New Data - Without Boldness (Arial)');\nE=sim(network,in);\nE=round(E);\nE\n%Testing with new data\n x=65;\nfor i=1:4\nal=char(x);\nfl=strcat(al,'2.bmp');\nin1(i,:)=roworder(fl);\nx=x+1;\nend \nin1=in1';\nin1=double(in1);\ndisplay('Testing with New Data - With Boldness (Tahoma)');\nF=sim(network,in1);\nF=round(F);\nF\nend\n\nfunction inprs=roworder(fl)\ninpdt=imread(fl);\ninprs=reshape(inpdt',1,size(inpdt,1)*size(inpdt,2));\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/14489-neural-network-programs/programs/CR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5571807644662812}}
{"text": "% POP_NEWTIMEF - Returns estimates and plots of event-related (log) spectral\n%           perturbation (ERSP) and inter-trial coherence (ITC) phenomena \n%           timelocked to a set of single-channel input epochs \n%\n% Usage:\n%   >> pop_newtimef(EEG, typeplot);          % pop_up window\n%   >> pop_newtimef(EEG, typeplot, lastcom); % pop_up window\n%   >> pop_newtimef(EEG, typeplot, channel); % do not pop-up window\n%   >> pop_newtimef(EEG, typeproc, num, tlimits,cycles,\n%                        'key1',value1,'key2',value2, ... );   \n%     \n% Graphical interface:\n%   \"Channel/component number\" - [edit box] this is the index of the data \n%              channel or the index of the component for which to plot the\n%              time-frequency decomposition.\n%   \"Sub-epoch time limits\" - [edit box] sub epochs may be extracted (note that\n%              this function aims at plotting data epochs not continuous data).\n%              You may select the new epoch limits in this edit box.\n%   \"Use n time points\" - [multiple choice list] this is the number of time\n%              points to use for the time-frequency decomposition. The more\n%              time points, the longer the time-frequency decomposition\n%              takes to compute.\n%   \"Frequency limits\" - [edit box] these are the lower and upper\n%              frequency limit of the time-frequency decomposition. Instead\n%              of limits, you may also enter a sequence of frequencies. For\n%              example to compute the time-frequency decomposition at all\n%              frequency between 5 and 50 hertz with 1 Hz increment, enter \"1:50\"\n%   \"Use limits, padding n\" - [multiple choice list] \"using limits\" means\n%              to use the upper and lower limits in \"Frequency limits\" with\n%              a specific padding ratio (padratio argument of newtimef).\n%              The last option \"use actual frequencies\" forces newtimef to\n%              ignore the padratio argument and use the vector of frequencies  \n%              given as input in the \"Frequency limits\" edit box.\n%   \"Log spaced\" - [checkbox] you may check this box to compute log-spaced\n%              frequencies. Note that this is only relevant if you specify\n%              frequency limits (in case you specify actual frequencies,\n%              this parameter is ignored).\n%   \"Use divisive baseline\" - [multiple choice list] there are two types of\n%              baseline correction, additive (the baseline is subtracted)\n%              or divisive (the data is divided by the baseline values).\n%              The choice is yours. There is also the option to perform \n%              baseline correction in single trials. See the 'trialbase' \"full\"\n%              option in the newtimef.m documentation for more information.\n%   \"No baseline\" - [checkbox] check this box to compute the raw time-frequency\n%              decomposition with no baseline removal.\n%   \"Wavelet cycles\" - [edit box] specify the number of cycle at the lowest \n%              and highest frequency. Instead of specifying the number of cycle \n%              at the highest frequency, you may also specify a wavelet\n%              \"factor\" (see newtimef help message). In addition, it is\n%              possible to specify actual wavelet cycles for each frequency\n%              by entering a sequence of numbers.\n%   \"Use FFT\" - [checkbox] check this checkbox to use FFT instead of\n%              wavelet decomposition.\n%   \"ERSP color limits\" - [edit box] set the upper and lower limit for the\n%              ERSP image. \n%   \"see log power\" - [checkbox] the log power values (in dB) are plotted. \n%              Uncheck this box to plot the absolute power values.\n%   \"ITC color limits\" - [edit box] set the upper and lower limit for the\n%              ITC image. \n%   \"plot ITC phase\" - [checkbox] check this box plot plot (overlaid on\n%              the ITC amplitude) the polarity of the ITC complex value.\n%   \"Bootstrap significance level\" - [edit box] use this edit box to enter\n%              the p-value threshold for masking both the ERSP and the ITC\n%              image for significance (masked values appear as light green)\n%   \"FDR correct\" - [checkbox] this correct the p-value for multiple comparisons\n%              (across all time and frequencies) using the False Discovery\n%              Rate method. See the fdr.m function for more details.\n%   \"Optional newtimef arguments\" - [edit box] addition argument for the\n%              newtimef function may be entered here in the 'key', value\n%              format.\n%   \"Plot Event Related Spectral Power\" - [checkbox] plot the ERSP image\n%              showing event related spectral stimulus induced changes\n%   \"Plot Inter Trial Coherence\" - [checkbox] plot the ITC image.\n%   \"Plot Curve at each frequency\" - [checkbox] instead of plotting images,\n%              it is also possible to display curves at each frequency.\n%              This functionality is beta and might not work in all cases.\n% \n% Inputs:            \n%   INEEG    - input EEG dataset\n%   typeproc - type of processing: 1 process the raw channel data \n%                                  0 process the ICA component data\n%   num      - component or channel number\n%   tlimits  - [mintime maxtime] (ms) sub-epoch time limits to plot\n%   cycles   -  > 0 --> Number of cycles in each analysis wavelet \n%               = 0 --> Use FFTs (with constant window length \n%                       at all frequencies)\n%\n% Optional inputs:\n%    See the NEWTIMEF function.\n%    \n% Outputs: Same as NEWTIMEF; no outputs are returned when a\n%          window pops-up to ask for additional arguments\n%\n% Saving the ERSP and ITC output values:\n%    Simply look up the history using the eegh function (type eegh).\n%    Then copy and paste the POP_NEWTIMEF command and add output args.\n%    See the NEWTIMEF function for a list of outputs. For instance,\n% >> [ersp itc powbase times frequencies] = pop_newtimef( EEG, ....);\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 2001 \n%\n% See also: NEWTIMEF, EEGLAB \n\n% Copyright (C) 2002 University of California San Diego\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% 03-08-02 add eeglab option & optimize variable sizes -ad\n% 03-10-02 change newtimef call -ad\n% 03-18-02 added title -ad & sm\n% 04-04-02 added outputs -ad & sm\n\nfunction varargout = pop_newtimef(EEG, typeproc, num, tlimits, cycles, varargin );\n\nvarargout{1} = '';\n% display help if not enough arguments\n% ------------------------------------\nif nargin < 2\n\thelp pop_newtimef;\n\treturn;\nend;\t\nlastcom = [];\nif nargin < 3\n\tpopup = 1;\nelse\n\tpopup = ischar(num) | isempty(num);\n\tif ischar(num)\n\t\tlastcom = num;\n\tend\nend\n\n% pop up window\n% -------------\nif popup\n\t[txt, vars] = gethelpvar('newtimef.m');\n    commandchan = 'tmpEEG = get(gcbf, ''userdata''); tmpchanlocs = tmpEEG(1).chanlocs; [tmp tmpval] = pop_chansel({tmpchanlocs.labels}, ''withindex'', ''on'', ''selectionmode'', ''single''); set(findobj(gcbf, ''tag'', ''chan''), ''string'',tmpval); clear tmpEEG tmp tmpchanlocs tmpval'; \n\t\n    g = [1 0.3 0.6 0.4];\n    g2 = [1 0.3 0.25 0.75];\n\tgeometry = { g2 g g g g g g g [0.975 1.27] [1] [1.2 1 1.2]};\n    uilist = { ...\n               { 'Style', 'text', 'string', fastif(typeproc, 'Channel number', 'Component number'), 'fontweight', 'bold'  } ...\n\t\t\t   { 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') 'tag' 'chan'} ...\n               { 'style' 'pushbutton' 'string'  '...', 'enable' fastif(~isempty(EEG(1).chanlocs) && typeproc, 'on', 'off') 'callback' commandchan } ...               \n               {} ...\n               ...\n\t\t\t   { 'Style', 'text', 'string', 'Sub epoch time limits [min max] (msec)', 'fontweight', 'bold' } ...\n\t\t\t   { 'Style', 'edit', 'string', getkeyval(lastcom,4,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) 'tag' 'tlimits' } ...\n               { 'Style', 'popupmenu', 'string', 'Use 50 time points|Use 100 time points|Use 150 time points|Use 200 time points|Use 300 time points|Use 400 time points' 'tag' 'ntimesout' 'value' 4} { } ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'Frequency limits [min max] (Hz) or sequence', 'fontweight', 'bold' } ...\n\t\t\t   { 'Style', 'edit', 'string', '' 'tag' 'freqs'  } ...\n               { 'Style', 'popupmenu', 'string', 'Use limits, padding 1|Use limits, padding 2|Use limits, padding 4|Use actual freqs.' 'tag' 'nfreqs' }  ...\n               { 'Style', 'checkbox', 'string' 'Log spaced' 'value' 0 'tag' 'freqscale' } ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'Baseline limits [min max] (msec) (0->pre-stim.)', 'fontweight', 'bold' } ...\n\t\t\t   { 'Style', 'edit', 'string', '0' 'tag' 'baseline' } ...\n\t\t\t   { 'Style', 'popupmenu',  'string', 'Use divisive baseline (DIV)|Use standard deviation (STD)|Use single trial DIV baseline|Use single trial STD baseline' 'tag' 'basenorm' } ...\n               { 'Style', 'checkbox', 'string' 'No baseline' 'tag' 'nobase' } ...\n               ...\n               { 'Style', 'text', 'string', 'Wavelet cycles [min max/fact] or sequence', 'fontweight', 'bold' } ...\n               { 'Style', 'edit', 'string', getkeyval(lastcom,5,[],'3 0.8') 'tag' 'cycle' } ...\n               { 'Style', 'checkbox', 'string' 'Use FFT' 'value' 0 'tag' 'fft' } ...\n               { } ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'ERSP color limits [max] (min=-max)', 'fontweight', 'bold' } ...\n               { 'Style', 'edit', 'string', '' 'tag' 'erspmax'} ...\n               { 'Style', 'checkbox', 'string' 'see log power (set)' 'tag' 'scale' 'value' 1} {} ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'ITC color limits [max]', 'fontweight', 'bold' } ...\n               { 'Style', 'edit', 'string', '' 'tag' 'itcmax'} ...\n               { 'Style', 'checkbox', 'string' 'plot ITC phase (set)' 'tag' 'plotphase' } {} ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold' } ...\n               { 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') 'tag' 'alpha'} ...\n               { 'Style', 'checkbox', 'string' 'FDR correct (set)' 'tag' 'fdr' } {} ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'Optional newtimef() arguments (see Help)', 'fontweight', 'bold', ...\n\t\t\t\t 'tooltipstring', 'See newtimef() help via the Help button on the right...' } ...\n\t\t\t   { 'Style', 'edit', 'string', '' 'tag' 'options' } ...\n\t\t\t   {} ...\n\t\t\t   { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ...\n\t\t\t\t 'Plot Event Related Spectral Power', 'tooltipstring', ...\n\t\t\t\t 'Plot log spectral perturbation image in the upper panel' 'tag' 'plotersp' } ...\n\t\t\t   { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotitc','present',0), 'string', ...\n\t\t\t\t 'Plot Inter Trial Coherence', 'tooltipstring', ...\n\t\t\t\t 'Plot the inter-trial coherence image in the lower panel' 'tag' 'plotitc' } ...\n\t\t\t   { 'Style', 'checkbox', 'value', 0, 'string', ...\n\t\t\t\t 'Plot curve at each frequency' 'tag' 'plotcurve' } ...\n\t\t\t };\n      % { 'Style', 'edit', 'string', '''padratio'', 4, ''plotphase'', ''off''' } ...\n\t\t\t   %{ 'Style', 'text', 'string',  '[set] -> Plot ITC phase sign', 'fontweight', 'bold', ...\n\t\t\t%\t 'tooltipstring', ['Plot the sign (+/-) of inter-trial coherence phase' 10 ...\n\t\t\t%\t\t'as red (+) or blue (-)'] } ...\n\t\t\t%   { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',1) } { } ...\n\n\t[ tmp1, tmp2, strhalt, result ] = inputgui( 'geometry', geometry, 'uilist', uilist, 'helpcom', 'pophelp(''pop_newtimef'');', ...\n\t\t\t\t\t   'title', fastif(typeproc, 'Plot channel time frequency -- pop_newtimef()', ...\n\t\t\t\t\t\t\t  'Plot component time frequency -- pop_newtimef()'), 'userdata', EEG);\n\tif length( tmp1 ) == 0 return; end\n\n\tif result.fft,      result.cycle = '0'; end\n\tif result.nobase,   result.baseline = 'NaN'; end\n    \n    num   = eeg_decodechan(EEG.chanlocs, result.chan );\n\ttlimits\t = eval( [ '[' result.tlimits ']' ] ); \n\tcycles\t = eval( [ '[' result.cycle   ']' ] );\n    freqs    = eval( [ '[' result.freqs   ']' ] );\n    %result.ncycles == 2 is ignored\n    \n    % add topoplot\n    % ------------\n    options = [];\n    if isfield(EEG.chanlocs, 'theta') && ~isempty(EEG.chanlocs(num).theta)\n        if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end\n        if typeproc == 1\n            if isempty(EEG.chanlocs), caption = [ 'Channel ' int2str(num) ]; else caption = EEG.chanlocs(num).labels; end\n            options = [options ', ''topovec'', ' int2str(num) ...\n                        ', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''caption'', ''' caption '''' ];\n        else\n            options = [options ', ''topovec'', EEG.icawinv(:,' int2str(num) ...\n                       '), ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''caption'', [''IC ' num2str(num) ''']' ];\n      end\n    end\n    \n\tif ~isempty( result.baseline ),  options = [ options ', ''baseline'',[' result.baseline ']' ]; end\n    if ~isempty( result.alpha ),     options = [ options ', ''alpha'',' result.alpha ];   end\n\tif ~isempty( result.options ),   options = [ options ',' result.options ];            end\n\tif ~isempty( result.freqs ),     options = [ options ', ''freqs'', [' result.freqs ']'   ]; end\n\tif ~isempty( result.erspmax ),   options = [ options ', ''erspmax'', [' result.erspmax ']' ]; end\n\tif ~isempty( result.itcmax ),    options = [ options ', ''itcmax'','  result.itcmax ];      end\n\tif ~result.plotersp,             options = [ options ', ''plotersp'', ''off''' ];     end\n\tif ~result.plotitc,              options = [ options ', ''plotitc'' , ''off''' ];     end\n\tif result.plotcurve,             options = [ options ', ''plottype'', ''curve''' ];   end\n\tif result.fdr,                   options = [ options ', ''mcorrect'', ''fdr''' ];     end\n\tif result.freqscale,             options = [ options ', ''freqscale'', ''log''' ];    end\n\tif ~result.plotphase,            options = [ options ', ''plotphase'', ''off''' ];    end\n\tif ~result.scale,                options = [ options ', ''scale'', ''abs''' ];        end\n    if result.ntimesout == 1,        options = [ options ', ''ntimesout'', 50' ];         end\n    if result.ntimesout == 2,        options = [ options ', ''ntimesout'', 100' ];        end\n    if result.ntimesout == 3,        options = [ options ', ''ntimesout'', 150' ];        end\n    if result.ntimesout == 5,        options = [ options ', ''ntimesout'', 300' ];        end\n    if result.ntimesout == 6,        options = [ options ', ''ntimesout'', 400' ];        end\n    if result.nfreqs == 1,           options = [ options ', ''padratio'', 1' ];           end  \n    if result.nfreqs == 2,           options = [ options ', ''padratio'', 2' ];           end   \n    if result.nfreqs == 3,           options = [ options ', ''padratio'', 4' ];           end\n    if result.nfreqs == 4,           options = [ options ', ''nfreqs'', ' int2str(length(freqs)) ]; end\n    if result.basenorm == 2,         options = [ options ', ''basenorm'', ''on''' ];      end\n    if result.basenorm == 4,         options = [ options ', ''basenorm'', ''on''' ];      end\n    if result.basenorm >= 3,         options = [ options ', ''trialbase'', ''full''' ];      end\n\n    % add title\n    % ---------\n\tif isempty( findstr(  '''title''', result.options))\n        if ~isempty(EEG.chanlocs) && typeproc\n            chanlabel = EEG.chanlocs(num).labels;\n        else\n            chanlabel = int2str(num);\n        end\n\tend\n    \n    % compute default winsize\n    % -----------------------\n    if EEG.xmin < 0 && isempty(findstr( '''winsize''', result.options)) && isempty( result.freqs )\n        fprintf('Computing window size in pop_newtimef based on half of the length of the baseline period');\n        options = [ options ', ''winsize'', ' int2str(-EEG.xmin*EEG.srate) ];\n    end\n    \n\tfigure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end\nelse\n    options = [ ',' vararg2str(varargin) ];\nend\n\n% compute epoch limits\n% --------------------\nif isempty(tlimits)\n\ttlimits = [EEG.xmin, EEG.xmax]*1000;\nend\npointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1));\npointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate+1, EEG.pnts));\npointrange = [pointrange1:pointrange2];\n\n% call function sample either on raw data or ICA data\n% ---------------------------------------------------\nif typeproc == 1\n\ttmpsig = EEG.data(num,pointrange,:);\nelse\n\tif ~isempty( EEG.icasphere )\n        if ~isempty(EEG.icaact)\n    \t\ttmpsig = EEG.icaact(num,pointrange,:);\n \t    else\n            tmpsig = (EEG.icaweights(num,:)*EEG.icasphere)*reshape(EEG.data(:,pointrange,:), EEG.nbchan, EEG.trials*length(pointrange));\n        end\n\telse\n\t\terror('You must run ICA first');\n\tend;\t\nend;\t \ntmpsig = reshape( tmpsig, length(num), size(tmpsig,2)*size(tmpsig,3));\n\n% outputs\n% -------\noutstr = '';\nif ~popup\n    for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end\n    if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end\nend\n\n% plot the datas and generate output command\n% --------------------------------------------\nif length( options ) < 2\n    options = '';\nend\nif nargin < 4\n    varargout{1} = sprintf('figure; pop_newtimef( EEG, %d, %d, [%s], [%s] %s);', typeproc, num, ...\n\t\t\tint2str(tlimits), num2str(cycles), options);\nend\ncom = sprintf('%s newtimef( tmpsig(:, :), length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options);\neval(com)\t    \n\nreturn;\n\n% get contextual help\n% -------------------\nfunction txt = context(var, allvars, alltext);\n\tloc = strmatch( var, allvars);\n\tif ~isempty(loc)\n\t\ttxt= alltext{loc(1)};\n\telse\n\t\tdisp([ 'warning: variable ''' var ''' not found']);\n\t\ttxt = '';\n\tend\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/popfunc/pop_newtimef.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.557180764466281}}
{"text": "function center = imGeodesicExtremities(img, varargin)\n%IMGEODESICEXTREMITIES Compute geodesic extremities of a binary particle\n%\n%   RES = imGeodesicExtremities(IMG);\n%   IMG is a binary image representing a connected particle. The result RES\n%   is a binary image with foreground pixels corresponding to the geodesic\n%   extremities of the particle. The geodesic extremities are the pixels\n%   belonging to the particle whose geodesic propagation equal the geodesic\n%   length of the particle.\n%\n%   RES = imGeodesicExtremities(IMG, WEIGHTS);\n%   use different weights for the computation of distances. See\n%   imChamferDistance for further details.\n%\n%   Example\n%   imGeodesicExtremities\n%\n%   Note:\n%   As the algorithm propagates geodesic distances from each foreground\n%   pixel, the computation time may be expensive.\n%\n%   See also\n%   imGeodesics, imChamferDistance, imGeodesicPropagation\n%   imGeodesicRadius, imGeodesicCenter, imGeodesicDiameter\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2009-05-22,    using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009 INRA - Cepia Software Platform.\n\npropag = imGeodesicPropagation(img, varargin{:});\nmaxVal = max(propag(img));\ncenter = propag==maxVal;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/36724-image-chamfer-distances-and-geodesic-diameter/imGeodesics/imGeodesicExtremities.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.557180759526709}}
{"text": "function A = VBA_spm_mesh_adjacency(F)\n% Compute the adjacency matrix of a triangle mesh\n% FORMAT A = spm_mesh_adjacency(F)\n% F        - a [fx3] faces array or a patch structure\n% \n% A        - adjacency matrix as a sparse [vxv] array\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin\n% $Id: spm_mesh_adjacency.m 4035 2010-08-05 18:54:32Z guillaume $\n\nif ~isnumeric(F) && isfield(F,'vertices')\n    N = size(F.vertices,1);\n    F = double(F.faces);\n    A = sparse([F(:,1); F(:,1); F(:,2); F(:,2); F(:,3); F(:,3)], ...\n           [F(:,2); F(:,3); F(:,1); F(:,3); F(:,1); F(:,2)], 1, N, N);\nelse\n    if isstruct(F), F = F.faces; end\n    F = double(F);\n    A = sparse([F(:,1); F(:,1); F(:,2); F(:,2); F(:,3); F(:,3)], ...\n           [F(:,2); F(:,3); F(:,1); F(:,3); F(:,1); F(:,2)], 1);\nend\n       \nA = double(A > 0);\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/thrid-party/spm/VBA_spm_mesh_adjacency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5571421963918869}}
{"text": "function A = spm_mesh_adjacency(F)\n% Compute the adjacency matrix of a triangle mesh\n% FORMAT A = spm_mesh_adjacency(F)\n% F        - a [fx3] faces array or a patch structure\n% \n% A        - adjacency matrix as a sparse [vxv] array\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin\n% $Id: spm_mesh_adjacency.m 4035 2010-08-05 18:54:32Z guillaume $\n\nif ~isnumeric(F) && isfield(F,'vertices')\n    N = size(F.vertices,1);\n    F = double(F.faces);\n    A = sparse([F(:,1); F(:,1); F(:,2); F(:,2); F(:,3); F(:,3)], ...\n           [F(:,2); F(:,3); F(:,1); F(:,3); F(:,1); F(:,2)], 1, N, N);\nelse\n    if isstruct(F), F = F.faces; end\n    F = double(F);\n    A = sparse([F(:,1); F(:,1); F(:,2); F(:,2); F(:,3); F(:,3)], ...\n           [F(:,2); F(:,3); F(:,1); F(:,3); F(:,1); F(:,2)], 1);\nend\n       \nA = double(A > 0);\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_adjacency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5571421847332586}}
{"text": "function varargout = sl2dmatcov(type, data, matsiz, n, meanmat, PL, PR, w)\n%SL2DMATCOV Computes the 2D matrix-covariances\n%\n% $ Syntax $\n%   - CL = sl2dmatcov('CL', data, matsiz, n, meanmat, PL, PR, w)\n%   - CR = sl2dmatcov('CR', data, matsiz, n, meanmat, PL, PR, w)\n%   - [CL, CR] = sl2dmatcov('Both', data, matsiz, n, meanmat, PL, PR, w)\n%\n% $ Arguments $\n%   - data:     the stack of matrices or the cell array of filenames of the\n%               array files storing the matrices.\n%   - matsiz:   the size of each matrix\n%   - n:        the number of samples\n%   - PL:       the left-projection matrix, default = []\n%   - PR:       the right-projection matrix, default = []\n%   - w:        the weights of the matrix samples, default = []\n%\n% $ Remarks $\n%   - The function computes the 2D matrix-covariances according to \n%     the following formulas:\n%       Y_i = PL^T * (X - meanX)* PR \n%       CL = ( sum_{i=1}^n w(i) * Y_i * Y_i^T ) / ( sum_{i=1}^n w(i) )\n%       CR = ( sum_{i=1}^n w(i) * Y_i^T * Y_i ) / ( sum_{i=1}^n w(i) )\n%     Following special cases are considered:\n%       If w is empty, then we take w(i) = 1 for all i\n%       If PL is empty, then we take PL as an identity matrix\n%       If PR is empty, then we take PR as an identity matrix\n%       If meanmat is 0, then we take meanmat as a zero matrix\n%\n% $ History $\n%   - Created by Dahua Lin, on Jul 31st, 2006\n%\n\n%% parse and verify input arguments\n\nif nargin < 5\n    raise_lackinput('sl2dmatcov', 5);\nend\nif nargin < 6\n    PL = [];\nend\nif nargin < 7\n    PR = [];\nend\nif nargin < 8\n    w = [];\nend\n\nmatsiz = matsiz(:)';\nif length(matsiz) ~= 2\n    error('sltoolbox:invalidarg', ...\n        'matsiz shoudl be a 2-elem vector');\nend\nif ~isequal(size(meanmat), matsiz)\n    error('sltoolbox:invalidarg', ...\n        'The size of mean matrix is not as specified');\nend\n\nd1 = matsiz(1);\nd2 = matsiz(2);\nif ~isempty(PL) && size(PL, 1) ~= d1\n    error('sltoolbox:invalidarg', ...\n        'The size of PL is inconsistent with the matrix dimension');\nend\nif ~isempty(PR) && size(PR, 1) ~= d2\n    error('sltoolbox:invalidarg', ...\n        'The size of PR is inconsistent with the matrix dimension');\nend\n\nif ~isempty(w)\n    if length(w) ~= n\n        error('The weights length is inconsistent with the number of samples');\n    end\n    tw = sum(w);\nelse\n    tw = n;\nend\n\n\n%% Main body\n\nif isnumeric(data)\n\n    if ~isequal(size(data), [matsiz, n])\n        error('sltoolbox:invalidarg', ...\n            'The size of data is inconsistent with specified');\n    end\n    \n    Y = compute_Y(data, meanmat, PL, PR);\n    \n    switch type\n        case 'CL'\n            CL = compute_SL(Y, w);\n            CL = CL / tw;\n            varargout = {CL};\n        case 'CR'\n            CR = compute_SR(Y, w);\n            CR = CR / tw;\n            varargout = {CR};\n        case 'Both'\n            [CL, CR] = compute_SLSR(Y, w);\n            CL = CL / tw;\n            CR = CR / tw;\n            varargout = {CL, CR};\n        otherwise\n            error('sltoolbox:invalidarg', ...\n                'invalid type: %s', type);\n    end            \n    \n    \nelseif iscell(data)\n    \n    nfiles = length(data);\n    cf = 0;\n    \n    switch type\n        case 'CL'\n            for i = 1 : nfiles\n                curarr = slreadarray(data{i});\n                curn = size(curarr, 3);\n                Y = compute_Y(curarr, meanmat, PL, PR);\n                curCL = compute_SL(Y, w); \n                if i == 1\n                    CL = curCL;\n                else\n                    CL = CL + curCL;\n                end\n                clear Y curCL;\n                cf = cf + curn;\n            end\n            CL = CL / tw;\n            varargout = {CL};\n            \n        case 'CR'\n            for i = 1 : nfiles\n                curarr = slreadarray(data{i});\n                curn = size(curarr, 3);\n                Y = compute_Y(curarr, meanmat, PL, PR);\n                curCR = compute_SR(Y, w); \n                if i == 1\n                    CR = curCR;\n                else\n                    CR = CR + curCR;\n                end\n                clear Y curCR;\n                cf = cf + curn;\n            end\n            CR = CR / tw;\n            varargout = {CR};\n            \n        case 'Both'\n            for i = 1 : nfiles\n                curarr = slreadarray(data{i});\n                curn = size(curarr, 3);\n                Y = compute_Y(curarr, meanmat, PL, PR);\n                [curCL, curCR] = compute_SLSR(Y, w); \n                if i == 1\n                    CL = curCL;\n                    CR = curCR;\n                else\n                    CL = CL + curCL;\n                    CR = CR + curCR;\n                end\n                clear Y curCL curCR;\n                cf = cf + curn;\n            end\n            CL = CL / tw;\n            CR = CR / tw;\n            varargout = {CL, CR};\n            \n        otherwise\n            error('sltoolbox:invalidarg', ...\n                'invalid type: %s', type);        \n    end\n    \n    if cf ~= n\n        error('sltoolbox:sizmismatch', ...\n            'The total number of samples is not n');\n    end\n            \nelse\n    error('sltoolbox:invalidarg', ...\n        'data should be a numeric array or a cell array of filenames');    \nend\n\n\n\n%% Core routine\n\nfunction Y = compute_Y(X, M, PL, PR)\n\nn = size(X, 3);\nif isempty(PL)\n    if isempty(PR)\n        if isequal(M, 0)\n            Y = X;\n        else\n            Y = zeros(size(X, 1), size(X, 2), n);\n            for i = 1 : n\n                Y(:,:,i) = X(:,:,i) - M;\n            end\n        end\n    else\n        Y = zeros(size(X, 1), size(PR, 2), n);\n        if isequal(M, 0)           \n            for i = 1 : n\n                Y(:,:,i) = X(:,:,i) * PR;\n            end\n        else\n            for i = 1 : n\n                Y(:,:,i) = (X(:,:,i) - M) * PR;\n            end\n        end\n    end\nelse\n    PLT = PL';\n    if isempty(PR)\n        Y = zeros(size(PL, 2), size(X, 2), n);\n        if isequal(M, 0)\n            for i = 1 : n\n                Y(:,:,i) = PLT * X(:,:,i);\n            end\n        else\n            for i = 1 : n\n                Y(:,:,i) = PLT * (X(:,:,i) - M);\n            end\n        end\n    else\n        Y = zeros(size(PL, 2), size(PR, 2), n);\n        if isequal(M, 0)\n            for i = 1 : n\n                Y(:,:,i) = PLT * X(:,:,i) * PR;\n            end\n        else\n            for i = 1 : n\n                Y(:,:,i) = PLT * (X(:,:,i) - M) * PR;\n            end\n        end\n    end\nend\n\n\nfunction SL = compute_SL(Y, w)\n\nSL = zeros(size(Y, 1));\nn = size(Y, 3);\nif isempty(w)\n    for i = 1 : n\n        curY = Y(:, :, i);\n        SL = SL + curY * curY';\n    end\nelse\n    for i = 1 : n\n        curY = Y(:, :, i);\n        SL = SL + w(i) * curY * curY';\n    end\nend\n\nfunction SR = compute_SR(Y, w)\n\nSR = zeros(size(Y, 2));\nn = size(Y, 3);\nif isempty(w)\n    for i = 1 : n\n        curY = Y(:, :, i);\n        SR = SR + curY' * curY;\n    end\nelse\n    for i = 1 : n\n        curY = Y(:, :, i);\n        SR = SR + w(i) * curY' * curY;\n    end\nend    \n\nfunction [SL, SR] = compute_SLSR(Y, w)\n\nSL = zeros(size(Y, 1));\nSR = zeros(size(Y, 2));\nn = size(Y, 3);\nif isempty(w)\n    for i = 1 : n\n        curY = Y(:, :, i);\n        SL = SL + curY * curY';\n        SR = SR + curY' * curY;\n    end\nelse\n    for i = 1 : n\n        curY = Y(:, :, i);\n        SL = SL + w(i) * curY * curY';\n        SR = SR + w(i) * curY' * curY;\n    end\nend\n    \n        \n", "meta": {"author": "lmthang", "repo": "nmt.hybrid", "sha": "50d5c025f18ed280ff0fd2e2adce327f4170a2c3", "save_path": "github-repos/MATLAB/lmthang-nmt.hybrid", "path": "github-repos/MATLAB/lmthang-nmt.hybrid/nmt.hybrid-50d5c025f18ed280ff0fd2e2adce327f4170a2c3/code/wordsim/code/sltoolbox_r101/sltoolbox_r101/sltoolbox/subspace_ex/sl2dmatcov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5571421793496116}}
{"text": "function [solution, nIterations, bestApprox] = sparseLP(model, approximation, params)\n% DC programming for solving the sparse LP\n% :math:`min ||x||_0` subject to linear constraints\n% See `Le Thi et al., DC approximation approaches for sparse optimization,\n% European Journal of Operational Research, 2014`;\n% http://dx.doi.org/10.1016/j.ejor.2014.11.031\n%\n% USAGE:\n%\n%    [solution, nIterations, bestApprox] = sparseLP(model, approximation, params);\n%\n% INPUTS:\n%    model:       Structure containing the following fields describing the linear constraints:\n%\n%                        * .A - `m x n` LHS matrix\n%                        * .b - `m x 1` RHS vector\n%                        * .lb - `n x 1` Lower bound vector\n%                        * .ub - `n x 1` Upper bound vector\n%                        * .csense - `m x 1` Constraint senses, a string containting the model sense for\n%                          each row in `A` ('E', equality, 'G' greater than, 'L' less than).\n%\n% OPTIONAL INPUTS\n%    approximation:    appoximation type of zero-norm. Available approximations:\n%\n%                        * 'cappedL1' : Capped-L1 norm\n%                        * 'exp'      : Exponential function\n%                        * 'log'      : Logarithmic function\n%                        * 'SCAD'     : SCAD function\n%                        * 'lp-'      : `L_p` norm with `p < 0`\n%                        * 'lp+'      : `L_p` norm with `0 < p < 1`\n%                        * 'l1'       : L1 norm\n%                        * 'all'      : try all approximations and return the best result\n%\n% OPTIONAL INPUTS:\n%    params:           Parameters structure:\n%\n%                        * .nbMaxIteration - stopping criteria - number maximal of iteration (Defaut value = 1000)\n%                        * .epsilon - stopping criteria - (Defaut value = 10e-6)\n%                        * .theta - parameter of the approximation (Defaut value = 0.5)\n%\n% OUTPUT:\n%    solution:         Structure containing the following fields:\n%\n%                        * .x - `n x 1` solution vector\n%                        * .stat - status:\n%\n%                          * 1 =  Solution found\n%                          * 2 =  Unbounded\n%                          * 0 =  Infeasible\n%                          * -1=  Invalid input\n% \n%   nIterations:       Number of iterations\n%   bestApprox:        Best approximation\n%\n% .. Author: - Hoai Minh Le,\t20/10/2015\n%              Ronan Fleming,    2017\n\navailableApprox = {'exp','log','SCAD','lp-','lp+','l1','cappedL1','all'};\n\nif ~exist('approximation','var')\n    approximation='cappedL1';\nend\n\n% Check inputs\nif nargin < 3\n    params.nbMaxIteration = 1000;\n    params.epsilon = 1e-6;\n    params.theta   = 0.5;\n    params.pNeg = -1;\n    params.pPos = 0.5;\nelse\n    if ~isfield(params,'nbMaxIteration')\n        params.nbMaxIteration = 1000;\n    end\n    \n    if ~isfield(params,'epsilon')\n        params.epsilon = 1e-6;\n    end\n    \n    if ~isfield(params,'theta')\n        params.theta   = 0.5;\n    end\n    \n    if ~isfield(params,'pNeg')\n        params.pNeg = -1;\n    end\n    \n    if ~isfield(params,'pPos')\n        params.pPos = 0.5;\n    end\n    \nend\n\nif ~isfield(model,'A')\n    error('Error:LHS matrix is not defined');\n    solution.stat = -1;\n    return;\nend\nif ~isfield(model,'b')\n    error('RHS vector is not defined');\n    solution.stat = -1;\n    return;\nend\nif ~isfield(model,'lb')\n    error('Lower bound vector is not defined');\n    solution.stat = -1;\n    return;\nend\nif ~isfield(model,'ub')\n    error('Upper bound vector is not defined');\n    solution.stat = -1;\n    return;\nend\nif ~isfield(model,'csense')\n    error('Constraint sense vector is not defined');\n    solution.stat = -1;\n    return;\nend\n\nif ~ismember(approximation,availableApprox)\n    error('Approximation is not valid');\n    solution.stat = -1;\n    return;\nend\n\nbestApprox = '';\n\nswitch approximation\n    case 'all'\n        approximations = setdiff(availableApprox,'all','stable');\n        bestResult = size(model.A,2);\n        bestSolution.x = [];\n        bestSolution.stat = 0;\n        bestIterations = 0;\n        feasTol = getCobraSolverParams('LP','feasTol');\n        for i=1:length(approximations)\n            %disp(approximations(i))\n            %try\n            [candSolution,candIterations] = sparseLP(model,approximations{i},params);\n            %catch\n            %fail gracefully\n            %solutionL0.stat = 0;\n            %end\n            if candSolution.stat == 1\n                candResult = nnz(abs(candSolution.x) > feasTol);\n                if bestResult >= candResult\n                    bestResult = candResult;\n                    bestApprox = approximations{i};\n                    bestSolution = candSolution;\n                    bestIterations = candIterations;\n                end\n            end\n        end\n        solution = bestSolution;\n        nIterations = bestIterations;\n        \n    otherwise\n        [nbMaxIteration,epsilon,theta,pNeg,pPos] = deal(params.nbMaxIteration,params.epsilon,params.theta,params.pNeg,params.pPos);\n        [A,b,lb,ub,csense] = deal(model.A,model.b,model.lb,model.ub,model.csense);\n        \n        %Parameters\n        nbIteration = 0;\n        epsilonP = 10e-2;\n        alpha = 3;\n        [m,n] = size(A);\n        \n        %Create the linear sub-programme that one needs to solve at each iteration, only its\n        %objective function changes, the constraints set remains.\n        \n        % Constraints\n        % Ax <=b\n        % t >= x\n        % t >= -x\n        A2 = [A         sparse(m,n);\n            speye(n) -speye(n);\n            -speye(n) -speye(n)];\n        b2 = [b; zeros(2*n,1)];\n        csense2 = [csense;repmat('L',2*n, 1)];\n        \n        % Bound;\n        % lb <= x <= ub\n        % 0  <= t <= max(|lb|,|ub|)\n        lb2 = [lb;zeros(n,1)];\n        ub2 = [ub;max(abs(lb),abs(ub))];\n        \n        %Define the linear sub-problem\n        subLPproblem = struct('osense',1,'A',A2,'csense',csense2,'b',b2,'lb',lb2,'ub',ub2);\n        \n        %Initialisation\n        x = zeros(n,1);\n        obj_old = evalObj(x,theta,pNeg,pPos,epsilonP,alpha,approximation);\n        \n        %DCA\n        tic\n        while nbIteration < nbMaxIteration\n            \n            x_old = x;\n            \n            %Solve the linear problem\n            subLPproblem.c = updateObj(x,theta,pNeg,pPos,epsilonP,alpha,approximation);\n            solution = solveCobraLP(subLPproblem);\n            \n            if solution.stat == 1\n                x = solution.full(1:n);\n                \n                %Check stopping criterion\n                error_x = norm(x - x_old);\n                obj_new = evalObj(x,theta,pNeg,pPos,epsilonP,alpha,approximation);\n                error_obj = abs(obj_new - obj_old);\n                if (error_x < epsilon) || (error_obj < epsilon)\n                    break;\n                else\n                    obj_old = obj_new;\n                end\n                % Automatically update the approximation parameter theta\n                if theta < 1000\n                    theta = theta * 1.5;\n                end\n                nbIteration = nbIteration + 1;\n                %             disp(strcat('DCA - Iteration: ',num2str(nbIteration)));\n                %             disp(strcat('Obj:',num2str(obj_new)));\n                %             disp(strcat('Stopping criteria error: ',num2str(min(error_x,error_obj))));\n                %             disp('=================================');\n            else\n                x = [];\n                break;\n            end\n        end\n        \n        time = toc;\n        solution.x = x;\n        solution.time = time;\n        nIterations = nbIteration;\n        \nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/base/solvers/cardOpt/sparseLP/sparseLP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5571421739659645}}
{"text": "function HTriggeredRaster(H,V,L); \nnPks = 5; % number of examples to plot\npkHt = .1; % min peak height compared to maximum\nH(sum(H,2)==0,:)=[];\n[N T] = size(V);\n[K,~] = size(H);\n\nclf\nfor fi = 1:K\n    axStart = .1 + (fi-1)*.8/K; \n    axW = .8/K*.85; \n    axL(fi) = subplot('Position', [axStart .1 axW .8]);\n\n    [pks, locs] = findpeaks(H(fi,:),'MinPeakHeight',max(H(fi,:))*pkHt);\n    \n    [~, ind] = sort(pks, 'descend'); \n    ind = ind(1:min(nPks,length(ind))); \n    pks = pks(ind); locs = locs(ind);\n\n\n    R = []; \n    twin = [1:L];\n    c = 1;\n    for pi = 1:length(pks)\n        R(c,:,:) = V(:,min(locs(pi)+twin,size(V,2)));\n        c = c+1;\n    end\n    \n    hold on\n    for ni = 1:N\n        plot([0 L+1], ni*length(pks)*[1 1], 'color', [1 .8 .8], 'linewidth', .1)\n    end\n    \n    Rmat = reshape(R,N*length(pks), length(twin));\n    [Xmat,Ymat] = meshgrid(1:size(Rmat,2),1:size(Rmat,1));\n    indBurst = find(Rmat>0);\n    s = scatter(Xmat(indBurst)+.9*(-.5+rand(size(indBurst))),Ymat(indBurst), ...\n       15, 0*[1 1 1], '.', 'markerfacecolor', 'flat', 'MarkerfaceAlpha',5/nPks, 'MarkerfaceAlpha',5/nPks);\n\n    set(gca, 'ydir', 'reverse')\n    axis tight; axis off\nend\n\n", "meta": {"author": "FeeLab", "repo": "seqNMF", "sha": "229b9b19ac3a34b8378945ec7f9e331e004bb777", "save_path": "github-repos/MATLAB/FeeLab-seqNMF", "path": "github-repos/MATLAB/FeeLab-seqNMF/seqNMF-229b9b19ac3a34b8378945ec7f9e331e004bb777/misc_elm/HTriggeredRaster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.557142173520297}}
{"text": "function c = model_center_of_mass(model)\n\nc = [mean(model.x),mean(model.y),mean(model.z)];", "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/model_center_of_mass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5570788447087713}}
{"text": "%% === compare timings for MULT\n\n% number of repeats (to increase measurement accuracy)\nR  = 10;        \n\n% what sizes of (square) matrices do we want measure? (log spacing)\nnn = unique(round(exp(linspace(log(4),log(100),10))));  \n\n% number of different sizes to try\nN  = length(nn);\n\n% size of the output C, in Megabytes\nMbytes = 10;\n\ntime   = zeros(N,3,R);\nops    = zeros(N,1);\n\ncandidates = {'A*B',  'mmx_naive',  @(a,b)mmx_naive('m',a,b);\n              'A''*B',  'mmx_naive',  @(a,b)mmx_naive('m',a,b,'tn');\n              'A*B''',  'mmx_naive',  @(a,b)mmx_naive('m',a,b,'nt');\n              'A''*B''',  'mmx_naive',  @(a,b)mmx_naive('m',a,b,'tt');\n              'A*Bs',  'mmx_naive',  @(a,b)mmx_naive('m',a,b,'ns');\n              'As*B',  'mmx_naive',  @(a,b)mmx_naive('m',a,b,'sn');\n};\n\nfuncs = cell(0,0);\nfor i=1:size(candidates,1)\n   found_it = ~isempty(which(candidates{i,2}));\n   if found_it\n      funcs(end+1,:) = candidates(i,[1 3]); %#ok<SAGROW>\n   else\n      fprintf('Could not find %s in your path, ignoring.\\n',candidates{i,2});\n   end\nend\nnf    = length(funcs);\n\nfor i = 1:N\n    \n   n = nn(i);\n\n   r1 = n;\n   c1 = n;\n   r2 = c1;\n   c2 = n;\n\n   pages = round(1e6*Mbytes / (8*r1*c2));\n   \n   A     = rand(r1,c1,pages);\n   B     = rand(r2,c2,pages);   \n   \n   B(B>0.5) = 0;\n   A(A>0.5) = 0;\n   \n   ops(i)   = r1*c2*(2*c1-1)*pages;   \n   fprintf('multiplying %d*%d matrix pairs of dimension [%dx%d]\\n',R*nf,pages,n,n)\n\n   for r = 1:R\n      for f = 1:nf %nf:-1:1\n         tstart = tic;\n         C = funcs{length(funcs)+1-f,2}(A,B);\n         time(i,length(funcs)+1-f,r)  = toc(tstart);\n         pause(1/10000);\n      end\n   end\nend\n\n%% graphics\n\ngflops   = 1e-9*bsxfun(@times, ops, 1./time);\ngFLP     = mean(gflops,3);\n\nclf\nhold on \ncols = get(gca,'ColorOrder');\ncols = [cols; cols];\nfor i = 1:size(gflops,2)\n   plot(nn,gFLP(:,i),'color',cols(i,:),'linewidth',3);\nend\nfor i = 1:size(gflops,2)\n   plot(nn,squeeze(gflops(:,i,:)),'.','color',cols(i,:))\nend\n\ngrid on\nset(gca,'xlim',[1 max(nn)])\nylabel('\\bf Gigaflops')\nxlabel('\\bf dimension')\n\nlegend(funcs{:,1},'location','northwest')\n\ntitle('\\bf Comparison between mmx, ndfun, and mtimesx. (in Gflops, bigger is better)')\n\n%% make PDF\n% set(gcf,'color','w')\n% export_fig 'comparison' -png", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/tests/test_multi/mmx-master/test/compare_mult_T.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5570728038464271}}
{"text": "function [ a, info ] = cpofa ( a, lda, n )\n\n%*****************************************************************************80\n%\n%% CPOFA factors a complex hermitian positive definite matrix.\n%\n%  Discussion:\n%\n%    CPOFA is usually called by CPOCO, but it can be called\n%    directly with a saving in time if RCOND is not needed.\n%    (time for CPOCO) = (1 + 18/N) * (time for CPOFA).\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 May 2007\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, complex A(LDA,N), the hermitian matrix to be factored.\n%\n%    Input, integer LDA, the leading dimension of A.\n%\n%    Input, integer N, the order of the matrix.\n%\n%    Output, complex A(LDA,N); an upper triangular matrix R so that  \n%      A = hermitian(R)*R\n%    where hermitian(R) is the conjugate transpose.  The strict lower \n%    triangle is unaltered.  If INFO /= 0, the factorization is not \n%    complete.  Only the diagonal and upper triangle are used.\n%\n%    Output, integer INFO.\n%    0, for normal return.\n%    K, signals an error condition.  The leading minor of order K is \n%    not positive definite.\n%\n  info = 0;\n\n  for j = 1 : n\n\n    s = 0.0;\n\n    for k = 1 : j-1\n      t = a(k,j) - a(1:k-1,k)' * a(1:k-1,j);\n      t = t / a(k,k);\n      a(k,j) = t;\n      s = s + real ( t * conj ( t ) );\n    end\n\n    s = real ( a(j,j) ) - s;\n\n    if ( s <= 0.0 | imag ( a(j,j) ) ~= 0.0 )\n      info = j;\n      break\n    end\n\n    a(j,j) = 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/linpack_c/cpofa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5570052690420841}}
{"text": "function [gal] = m32gal(m3)\n% Convert volume from cubic meters to US liquid gallons. \n% Chad Greene 2012\ngal = m3*264.17205236;", "meta": {"author": "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/m32gal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5570052678274384}}
{"text": "function out = sum(f)\n%SUM   Definite integral of a SINGFUN on the interval [-1,1].\n%   SUM(F) is the integral of F from -1 to 1.\n%\n% See also CUMSUM, DIFF.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Note for developers:\n%\n% The main algorithm:\n%\n% When the smoothPart of F is a CHEBTECH, that is, it can be written as\n% Chebyshev sum, the integral\n%\n% I = \\int_{-1}^{1} F dx = \\sum_{0}^{n-1} c_r M_r,\n%\n% where M_r = \\int_{-1}^{1} (1+x)^a(1-x)^b T_r(x) dx is the rth Jacobi moment.\n%\n% The computation of M_r is treated differently for different a and b:\n%\n% (I) when a == b, M_r are the Gegenbauer moments, which bear a closed-form\n% solution as indicated in [2] and [4].\n%\n% (II) when a ~= b, M_r are the general Jacobi moments, which can be obtained\n% using a three-term recursive relation discussed in [3].\n%\n% This way, all quadratures in SINGFUN, along with those in CHEBTECH are now\n% entirely of Clenshaw-Curtis style.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Useful References:\n%\n% [1]. K. Xu and M. Javed, Singfun Working Note, August 2013\n%\n% [2]. Hunter, D., and Nikolov, G., Gaussian Quadrature of Chebyshev\n% Polynomials, J. Comput. Appl. Math. 94 (1998), 123-131.\n%\n% [3]. Piessens, R., and Branders, M., The Evaluation and Application of Some\n% Modified Moments, BIT 13 (1973), 443-450.\n%\n% [4]. Sommariva, A., Fast construction of Fejer and Clenshaw\u2013Curtis rules for\n% general weight functions, Computers & Mathematics with Applications 65\n% (2012), 682-693.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%\n% Trivial cases:\nif ( all(f.exponents == 0) )\n    % If both the exponents are trivial, then compute the integral by calling\n    % the sum in smoothfun.\n    out = sum(f.smoothPart);\n    return\n    \nelseif ( all(f.exponents <= -1) )\n    % The integral is divergent or not a number when both the exponents are\n    % non-zero.\n    \n    if ( isreal(f) )\n        \n        % The sign of the smoothPart of F at the end points:\n        sl = sign(get(f.smoothPart, 'lval'));\n        sr = sign(get(f.smoothPart, 'rval'));\n        \n        if  ( sl == sr )\n            out = sl.*inf;\n        else\n            out = NaN;\n        end\n        \n    else\n        % The sign of the real part of the smoothPart of F at the end\n        % points:\n        rsl = sign(real(get(f.smoothPart, 'lval')));\n        rsr = sign(real(get(f.smoothPart, 'rval')));\n        \n        % The sign of the real part of the smoothPart of F at the end\n        % points:\n        isl = sign(imag(get(f.smoothPart, 'lval')));\n        isr = sign(imag(get(f.smoothPart, 'rval')));\n        \n        if ( (rsl == rsr) && (isl == isr) )\n            out = Inf + 1i*Inf;\n        else\n            out = NaN;\n        end\n    end\n    \n    return\n    \nelseif ( any(f.exponents <= -1) )\n    \n    % The integral is divergent or not a number when one of the exponents \n    % are non-zero.\n    \n    if ( isreal(f) )\n        \n        % The sign of the smoothPart of F at the end points:\n        sl = sign(get(f.smoothPart, 'lval'));\n        sr = sign(get(f.smoothPart, 'rval'));\n        \n        s = [sl sr];\n        ind = ( f.exponents <= -1 );\n        out = Inf*s(ind);\n        \n    else\n        % The sign of the real part of the smoothPart of F at the end\n        % points:\n        rsl = sign(real(get(f.smoothPart, 'lval')));\n        rsr = sign(real(get(f.smoothPart, 'rval')));\n        \n        % The sign of the real part of the smoothPart of F at the end\n        % points:\n        isl = sign(imag(get(f.smoothPart, 'lval')));\n        isr = sign(imag(get(f.smoothPart, 'rval')));\n        \n        rs = [rsl rsr];\n        is = [isl isr];\n        ind = ( f.exponents <= -1 );\n        \n        % The real part:\n        realPart = 0;\n        if ( any(rs) )\n            realPart = Inf*rs(ind);\n        end\n        \n        % The imaginary part:\n        imagPart = 0;\n        if ( any(is) )\n            imagPart = Inf*is(ind);\n        end\n        \n        % The sum:\n        out = realPart + imagPart;\n    end\n    \n    return\nend\n           \n%%\n% The non-trivial case:\n\nif ( isa(f.smoothPart, 'chebtech') )\n    \n    % If the smooth part of F is a CHEBTECH, then evaluate the integral by using\n    % Clenshaw-Curtis-Jacobi moments and the Chebyshev coefficients:\n    \n    % Grab the number of points for the smooth part of f:\n    n = length(f);\n\n    % Grab the exponents:\n    a = f.exponents(1);\n    \n    if ( diff(f.exponents) == 0 )\n        % If the exponents at the endpoints are same, then compute the\n        % appropriate modified moments for Gegenbauer weights.\n    \n        r = a + .5;\n        m0 = gamma(r + .5)*sqrt(pi)/gamma(r + 1);\n        k = 1:floor((n-1)/2);\n        % Even modified moments for M_2k = \\int_{-1}^1 (1-x)^a(1+x)^a T_2k(x) dx\n        % and notice that the odd moments vanish due to parity.\n        m = m0*[1, cumprod((k - r - 1)./(k + r))];\n        % Form the modified moments vector:\n        M(1:2:n) = m;\n        M(2:2:n) = 0;\n        \n    else\n        \n        % The general case:\n        b = f.exponents(2);\n        \n        % Common coefficient for the modified moments:\n        c1 = a + 1;\n        c2 = b + 1;\n        c3 = a + b + 1;\n        c4 = c1 + c2;\n        c5 = a - b;\n        c0 = (2^c3)*beta(c1, c2);\n        \n        % Compute the hypergeometric function related to the modified moments:\n        M = zeros(1,n);\n        M(1) = 1;\n        if ( n > 1 )\n            M(2) = c5/c4;           \n            % Sister Celine's three-term recurrence:\n            for j = 3:n\n                M(j) = (2*c5*M(j-1) + (j - 2 - c4)*M(j-2)) / (c3 + j - 1);\n            end\n        end\n        % Compute the modified moments:\n        M = c0*M;\n        \n    end\n        \n    % Chebyshev coefficients of the smooth part of F:\n    coeffs = get(f, 'coeffs');\n    \n    % multiplication of weights and values\n    out = M*coeffs;\n\n    \nelse\n    %%\n    % If f.smoothPart is not a CHEBTECH, we evaluate the integral by using\n    % Gauss-Jacobi points and weights.\n    \n    % Give a sufficiently large number: \n    % [TODO]: This number needs to be determined in future when other 'tech's join. \n    % [TODO]: Or perhaps compute iteratively until result doesn't change?\n    n = 1000;\n    \n    [x, w] = jacpts(ceil(n/2) + 1, f.exponents(2), f.exponents(1));\n    out = w*feval(f.smoothPart, x);\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/@singfun/sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5569833210908431}}
{"text": "function lam_msg = CPD_to_lambda_msg(CPD, msg_type, n, ps, msg, p)\n% CPD_TO_LAMBDA_MSG Compute lambda message (gaussian)\n% lam_msg = compute_lambda_msg(CPD, msg_type, n, ps, msg, p)\n% Pearl p183 eq 4.52\n\nswitch msg_type\n case 'd',\n  error('gaussian_CPD can''t create discrete msgs')\n case 'g',\n  self_size = CPD.sizes(end);\n  if all(msg{n}.lambda.precision == 0) % no info to send on\n    lam_msg.precision = zeros(self_size);\n    lam_msg.info_state = zeros(self_size, 1);\n    return;\n  end\n  cpsizes = CPD.sizes(CPD.cps);\n  dpval = 1;\n  Q = CPD.cov(:,:,dpval);\n  Sigmai = Q;\n  wmu = zeros(self_size, 1);\n  for k=1:length(ps)\n    pk = ps(k);\n    if pk ~= p\n      bk = block(k, cpsizes);\n      Bk = CPD.weights(:, bk, dpval);\n      m = msg{n}.pi_from_parent{k};\n      Sigmai = Sigmai + Bk * m.Sigma * Bk';\n      wmu = wmu + Bk * m.mu; % m.mu = u(k)\n    end\n  end\n  % Sigmai = Q + sum_{k \\neq i} B_k Sigma_k B_k'\n  i = find_equiv_posns(p, ps);\n  bi = block(i, cpsizes);\n  Bi = CPD.weights(:,bi, dpval);\n  \n  if 0\n  P = msg{n}.lambda.precision;\n  if isinf(P) % inv(P)=Sigma_lambda=0\n    precision_temp = inv(Sigmai);\n    lam_msg.precision = Bi' * precision_temp * Bi;\n    lam_msg.info_state = precision_temp * (msg{n}.lambda.mu - wmu);\n  else\n    A = inv(P + inv(Sigmai));\n    precision_temp = P + P*A*P;\n    lam_msg.precision = Bi' * precision_temp * Bi;\n    self_size = length(P);\n    C = eye(self_size) + P*A;\n    z = msg{n}.lambda.info_state;\n    lam_msg.info_state = C*z - C*P*wmu;\n  end\n  end\n  \n  if isinf(msg{n}.lambda.precision)\n    Sigma_lambda = zeros(self_size, self_size); % infinite precision => 0 variance\n    mu_lambda = msg{n}.lambda.mu; % observed_value;\n  else\n    Sigma_lambda = inv(msg{n}.lambda.precision);\n    mu_lambda = Sigma_lambda * msg{n}.lambda.info_state;\n  end\n  precision_temp = inv(Sigma_lambda + Sigmai);\n  lam_msg.precision = Bi' * precision_temp * Bi;\n  lam_msg.info_state = Bi' * precision_temp * (mu_lambda - wmu);\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/CPDs/@gaussian_CPD/Old/CPD_to_lambda_msg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5569833103062553}}
{"text": "function [Decoded,Decoder_Chip,Temp_Decoded,intgrl] =  ...\n  CDMA_decode(OutSignal,Chipbit,User_to_Decode, ...\n  SamplesPerBit,SamplePerChip,TotalDataBit)\n\n% ........................ CDMA Decoding Starts Here .....................\nclipto = TotalDataBit*SamplesPerBit;\n\n\nTotalChips = length(Chipbit(:,User_to_Decode));\nDecoder_Chip1 =[];\nfor l1 = 1:TotalDataBit\n    Decoder_Chip1 = vertcat(Decoder_Chip1,Chipbit(:,User_to_Decode));\nend\nDecoder_Chip = MakeSampled(Decoder_Chip1,length(OutSignal),SamplePerChip);\nTemp_Decoded = OutSignal.*Decoder_Chip;\nTemp_Decoded = Temp_Decoded(1:TotalDataBit*SamplesPerBit);\n\nintgrl = zeros(length(Temp_Decoded),1);\nAvg_Ingl = 0;\nDecoded = zeros(TotalDataBit,1);\n    bitno = 0;\n    for l1 = 1:TotalChips*SamplePerChip:length(Temp_Decoded)\n        bitno = bitno+1;\n        for l2 = l1:(l1+TotalChips*SamplePerChip-1)\n            if (l2==1),intgrl(1)=Temp_Decoded(1);continue;end\n            intgrl(l2) = intgrl(l2-1) + Temp_Decoded(l2);\n        end\n        if (intgrl(l2)>0),\n            Decoded(bitno)=1;\n        else\n            Decoded(bitno)=-1;\n        end\n        intgrl(l2) = 0;\n    end\nintgrl=vertcat(intgrl,zeros(length(OutSignal)-length(intgrl),1));\nTemp_Decoded = vertcat(Temp_Decoded,zeros(length(OutSignal)-length(Temp_Decoded),1));\n% ........................ CDMA Decoding Ends Here .....................", "meta": {"author": "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/CDMA_decode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5569833097507166}}
{"text": "function ap_multi = compute_AP_multiCam(good_image, junk_image, index, queryCam, testCam)\ngood_cam = testCam(good_image);\ngood_cam_uni = unique(good_cam); \nap_multi = zeros(1, 6);\n\n% on the same camera\ngood_cam_now = queryCam;\nngood = length(junk_image)-1;\njunk_image_now = [good_image; index(1)];\ngood_image_now = setdiff(junk_image, index(1));\nold_recall = 0; \nold_precision = 1.0; \nap = 0; \nintersect_size = 0; \nj = 0; \ngood_now = 0; \nfor n = 1:length(index) \n    flag = 0;\n    if ~isempty(find(good_image_now == index(n), 1)) \n        flag = 1; % good image \n        good_now = good_now+1; \n    end\n    if ~isempty(find(junk_image_now == index(n), 1))\n        continue; % junk image \n    end\n\n    if flag == 1%good\n        intersect_size = intersect_size + 1; \n    end \n    if ngood == 0\n        ap_multi(good_cam_now) = 0;\n        break;\n    end\n    recall = intersect_size/ngood; \n    precision = intersect_size/(j + 1); \n    ap = ap + (recall - old_recall)*((old_precision+precision)/2); \n    old_recall = recall; \n    old_precision = precision; \n    j = j+1; \n\n    if good_now == ngood \n        ap_multi(good_cam_now) = ap;\n        break; \n    end \nend \n\nfor k = 1:length(good_cam_uni)\n    good_cam_now = good_cam_uni(k);\n    ngood = length(find(good_cam == good_cam_now));\n    pos_junk = find(good_cam ~= good_cam_now);\n    junk_image_now = [junk_image; good_image(pos_junk)];\n    pos_good = find(good_cam == good_cam_now);\n    good_image_now = good_image(pos_good);\n    old_recall = 0; \n    old_precision = 1.0; \n    ap = 0; \n    intersect_size = 0; \n    j = 0; \n    good_now = 0; \n    for n = 1:length(index) \n        flag = 0;\n        if ~isempty(find(good_image_now == index(n), 1)) \n            flag = 1; % good image \n            good_now = good_now+1; \n        end\n        if ~isempty(find(junk_image_now == index(n), 1))\n            continue; % junk image \n        end\n\n        if flag == 1%good\n            intersect_size = intersect_size + 1; \n        end \n        recall = intersect_size/ngood; \n        precision = intersect_size/(j + 1); \n        ap = ap + (recall - old_recall)*((old_precision+precision)/2); \n        old_recall = recall; \n        old_precision = precision; \n        j = j+1; \n\n        if good_now == ngood \n            ap_multi(good_cam_now) = ap;\n            break; \n        end \n    end \nend\n\nend\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/utils/compute_AP_multiCam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5569833051917304}}
{"text": " function ob = Gdelaysum1(varargin)\n%function ob = Gdelaysum1([options])\n%|\n%| Construct Gdelaysum1 object that performs weighted sums of a delayed signal.\n%| This is useful for model-based reconstruction of THz images.\n%| See Gdelaysum1_test() at end for example usage.\n%|\n%| y[n;m] = sum_{k=0}^{Nx-1} h[n - d[k;m]] x[k], n=0,...,Ny-1, m=0,...,Nm-1\n%| for 0 <= n - d[k] <= Nh - 1\n%|\n%| required\n%|\t'Ny'\t[1]\t\toutput signal length\n%|\t'delay'\t[Nx Nm]\t\tdelays\n%|\n%| options\n%|\t'h'\t[Nh 1]\t\timpulse response, default [1]\n%|\t'nthread' [1]\t\t# threads, default 1\n%|\n%| out\n%|\tob\t[Ny*Nm Nx]\tFatrix object\n%|\n%| Copyright 2006-8-25, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(varargin{1}, 'test'), Gdelaysum1_test, return, end\nif nargin < 4, ir_usage, end\n\n% defaults\narg.Ny = [];\narg.delay = [];\narg.h = 1;\narg.nthread = 1;\narg.class = 'fatrix2';\narg.chat = false;\n\n% options\narg = vararg_pair(arg, varargin);\n\nif isempty(arg.delay), fail 'delay required', end\nif isempty(arg.Ny), fail 'Ny required', end\n\narg.h = single(arg.h);\narg.delay = single(arg.delay);\narg.nthread = int32(arg.nthread);\narg.chat = int32(arg.chat);\n\n[arg.Nx arg.Nm] = size(arg.delay);\narg.Nh = length(arg.h);\n\narg.str_forw_mex = 'delaysum1,forw';\narg.str_back_mex = 'delaysum1,back';\nif arg.nthread > 1\n\targ.str_forw_mex = 'delaysum1,forw,thr';\n\targ.str_back_mex = 'delaysum1,back,thr';\nend\n\nswitch arg.class\ncase 'Fatrix'\n\targ.dim = [arg.Ny * arg.Nm, arg.Nx];\n\tob = Fatrix(arg.dim, arg, ...\n\t\t'abs', @Gdelaysum1_abs, 'power', @Gdelaysum1_power, ...\n\t\t'forw', @Gdelaysum1_forw_Fatrix, ...\n\t\t'back', @Gdelaysum1_back_Fatrix);\ncase 'fatrix2'\n\n\todim = arg.Ny*arg.Nm;\n\tforw = @(arg, x) delaysum1_mex(arg.str_forw_mex, arg.h, arg.delay, ...\n\t\targ.nthread, single(x), int32(arg.Ny), arg.chat);\n\tback = @(arg, y) delaysum1_mex(arg.str_back_mex, arg.h, arg.delay, ...\n\t\targ.nthread, single(y), arg.chat);\n\tob = fatrix2('idim', arg.Nx, 'odim', odim, 'arg', arg, ...\n\t\t'abs', @Gdelaysum1_abs, 'power', @Gdelaysum1_power, ...\n\t\t'forw', forw, 'back', back);\notherwise\n\tfail 'bug'\nend\n\n\n% Gdelaysum1_abs(): |A|\nfunction ob = Gdelaysum1_abs(ob)\nob.arg.h = abs(ob.arg.h);\n\n\n% Gdelaysum1_power(): A .^ p\nfunction ob = Gdelaysum1_power(ob, p)\nob.arg.h = ob.arg.h .^ p;\n\n\n% Gdelaysum1_forw_Fatrix(): y = A * x\n% in\n%\tx\t[Nx L]\n% out\n%\ty\t[Ny*Nm L]\n%\nfunction y = Gdelaysum1_forw_Fatrix(arg, x)\n\nLL = size(x, 2);\ny = zeros(arg.Ny*arg.Nm, LL, 'single');\nfor ll=1:LL\n\ttmp = single(x(:,ll));\n\ttmp = delaysum1_mex(arg.str_forw_mex, arg.h, arg.delay, ...\n\t\targ.nthread, tmp, int32(arg.Ny), arg.chat);\n\ty(:,ll) = tmp(:);\nend\n\n\n% Gdelaysum1_back_Fatrix(): x = A' * y\n% in\n%\ty\t[Ny*Nm L]\n% out\n%\tx\t[Nx L]\n%\nfunction x = Gdelaysum1_back_Fatrix(arg, y)\n\nLL = size(y, 2);\nx = zeros(arg.Nx, LL, 'single');\nfor ll=1:LL\n\ttmp = single(y(:,ll));\n\ttmp = delaysum1_mex(art.str_back_mex, arg.h, arg.delay, ...\n\t\targ.nthread, tmp, arg.chat);\n\tx(:,ll) = tmp;\nend\n\n\n% Gdelaysum1_test\nfunction Gdelaysum1_test\n\ndelay = [10 20 40; 50 51 52];\nh = [4 3 -2 1]';\nNy = 80;\nats = {'nthread', jf('ncore')};\nA = Gdelaysum1('Ny', Ny, 'h', h, 'delay', delay, ats{:});\n\nx = [1 0]';\ny1 = A * x;\ny1 = reshapee(y1, Ny, []);\nif im\n\tclf, plot(y1, '-o')\nend\n\n%mask = true(A.arg.Nx,1);\n%Fatrix_test_basic(A, mask)\nfatrix2_tests(A)\ntest_adjoint(A);\n\nif 1 % compare Fatrix and fatrix2\n\tNy = 2^11;\n\tNx = 2^10;\n\tNm = 2^9;\n\tNh = 2^8;\n\trng(0)\n\tdelay = rand(Nx, Nm);\n\tx = rand(Nx, 1);\n\targs = {'Ny', Ny, 'h', (1:Nh)', 'delay', delay, ats{:}};\n\tA1 = Gdelaysum1(args{:}, 'class', 'Fatrix');\n\tA2 = Gdelaysum1(args{:}, 'class', 'fatrix2');\n\tcpu etic\n\ty1 = A1 * x;\n\tcpu etoc 'Fatrix'\n\tcpu etic\n\ty2 = A2 * x;\n\tcpu etoc 'fatrix2'\n\tjf_equal(y1, y2)\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/systems/Gdelaysum1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5569832995216673}}
{"text": "function y=sum_rate_direct(x,A,B,omega,K)\n    tmp=zeros(K,K);\n    for i0=1:K\n        for k0=1:K\n            tmp(i0,k0)=abs(x'*A(:,:,i0,k0)+B(i0,k0))^2;\n        end\n    end\n    yt=zeros(K,1);\n    for k0=1:K\n        tmp1=sum(tmp(:,k0));\n        tmp2=tmp1-tmp(k0,k0);\n        yt(k0)=log(1+tmp(k0,k0)/(tmp2+1));\n    end\n    y=-omega*yt;\nend\n\n", "meta": {"author": "guohuayan", "repo": "WSR_maximization_for_RIS_system", "sha": "180ffe88b68ba792f5f1ddcce405bb6576067c92", "save_path": "github-repos/MATLAB/guohuayan-WSR_maximization_for_RIS_system", "path": "github-repos/MATLAB/guohuayan-WSR_maximization_for_RIS_system/WSR_maximization_for_RIS_system-180ffe88b68ba792f5f1ddcce405bb6576067c92/fig4/sum_rate_direct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5569832887370789}}
{"text": "function ff=ref_fac(f,W,c,d,p,q,permutation)\n%REF_FAC  Reference factorization.\n%\n%  This function cannot handle multidimensional arrays.\n%  Reshape to matrix BEFORE you call this.\n%\n\n% Output\nff=zeros(p*q*W,c*d);\n\n% If d==1, it is not possible to further reduce the size of\n% wk. Actually, some of the following code produces an\n% error, because Matlab interprets an fft of a 1x q*W*p as a\n% a row operation !\nif d>1\n  \n  % Shape to match first fft pass.\n  work=zeros(d,q*W*p);\n  \n  % This loop iterates over the number of truly different wk's.\n  for ko=0:c-1\n    \n    % Permute and copy into work array.\n    % Format is suited for fft.\n    work(:)=f(permutation+ko,:);\n      \n    % Execute the fft and place transposed in ff.\n    ff(:,1+ko*d:(ko+1)*d)=fft(work.',[],2);\n      \n  end;\n    \nelse\n    \n  % Work arrays.\n  work=zeros(p*q*W,1);\n  \n  for ko=0:c-1\n    \n    % Permute input.\n    work(:)=f(permutation+ko,:);\n    \n    % Write the block.\n    ff(:,ko+1)=work;\n  end\n  \nend;    \n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_fac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5568886526508358}}
{"text": "function [Ka, pKa] = acidDissociationConstant(metAbbr, Alberty2006, metAbbrAlbertyAbbr, temp, is, chi)\n% Acid dissociation constant for the different metabolite species that make up a reactant\n%\n% USAGE:\n%\n%    [Ka, pKa] = acidDissociationConstant(metAbbr, Alberty2006, metAbbrAlbertyAbbr, temp, is, chi)\n%\n% INPUTS:\n%    metAbbr:               reconstruction reactant abbreviation\n%    Alberty2006:           Basic data on the metabolite species that make\n%                           up a reactant, compiled by Robert A. Alberty,\n%                           Massachusetts Institute of Technology.\n%                           In Print: `Robert A. Alberty, Biochemical Thermodynamics:\n%                           Applications of Mathematica. John Wiley & Sons, 2006. p391-395`\n%                           Online: BasicBioChemData3.nb\n%                           http://library.wolfram.com/infocenter/MathSource/5704/\n%    metAbbrAlbertyAbbr:    mapping from model metabolite primary key to\n%                           primary key of reactants in `Alberty2006`\n%\n% OPTIONAL INPUT\n%    temp:                  temperature (default 298.15 K)\n%    is:                    ionic strength (default 0 M)\n%    chi:                   electrical potential (default 0)\n%\n% OUTPUTS:\n%    Ka:                    apparent equilibrium constants\n%    pKa:                   :math:`-log_{10}(Ka)`\n\nif ~exist('temp','var')\n    temp=298.15;\nend\nif ~exist('is','var')\n    is=0;\nend\nif ~exist('chi','var')\n    chi=0;\nend\n\n%find the alberty abbreviation for this metabolite Abbreviation\nalbertyAbbr=metAbbrAlbertyAbbr(strcmp(metAbbr,metAbbrAlbertyAbbr(:,2)),3);\n\n%make a list of alberty abbreviations\nklt=size(Alberty2006,2);\nallAlbertyAbbr=cell(klt,1);\nfor k=1:klt\n    allAlbertyAbbr{k}=Alberty2006(k).abbreviation;\nend\n%index for matching data for the alberty abbreviation\nn=find(strcmp(albertyAbbr,allAlbertyAbbr));\n\n\n%find the number of species within pseudoisomer group\np=max(find(~isnan(Alberty2006(n).basicData(:,1))));\n\n%no Legendre transformation for pH or electrical potential\nLegendre     = 0;\nLegendreCHI  = 0;\npHr = 7; %dummy, has no effect\n\n[dGf0,dHf0,mf,aveHbound,aveZi,lambda,gpfnsp]=calcdGHT(Alberty2006(n).basicData(1:p,1),Alberty2006(n).basicData(1:p,2),Alberty2006(n).basicData(1:p,3),Alberty2006(n).basicData(1:p,4),pHr,is,temp,chi,Legendre,LegendreCHI);\n\nKa=zeros(p-1);\npKa=zeros(p-1);\n\ngasConstant = 8.314472/1000; % kJ K-1 mol-1\n\n%RTalpha p 49 Alberty 2003\n%where alpha is the Debye-Huckel Constant\ngibbscoeff = (9.20483*temp)/10^3 - (1.284668*temp^2)/10^5 + (4.95199*temp^3)/10^8;\n\n% A <--> A- + H+\n% Take into account the ionic strength effect on the Gibbs energy of a\n% hydrogen ion\nzi=1;\nhydrogenIonistermG = -(gibbscoeff*(zi.^2)*is^0.5)/(1 + 1.6*is^0.5);\n\nfor x=1:p-1\n\n    Ka(x)  =  exp((gpfnsp(x+1,1)-gpfnsp(x,1)-hydrogenIonistermG)/(gasConstant*temp));\n    if 1\n        pKa(x) =  -(gpfnsp(x+1,1)-gpfnsp(x,1)-hydrogenIonistermG)/(gasConstant*temp*log(10));\n    else\n        %p244 Alberty 2003 uses a slightly less accurate gas constant so slight\n        %difference\n        gpfnsp=Alberty2006(n).basicData(1:p,1);\n        pKa(x) =  -(gpfnsp(x+1,1)-gpfnsp(x,1))/(log(10)* 8.31451 * .29815);\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/src/analysis/thermo/reactantContribution/acidDissociationConstant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5568886467603114}}
{"text": "function y = sample_node(CPD, pev)\n% SAMPLE_NODE Draw a random sample from P(Xi | x(pi_i), theta_i)  (gaussian)\n% y = sample_node(CPD, parent_evidence)\n%\n% pev{i} is the value of the i'th parent (if there are any parents)\n% y is the sampled value (a scalar or vector)\n\nif length(CPD.dps)==0\n  i = 1;\nelse\n  dpvals = cat(1, pev{CPD.dps});\n  i = subv2ind(CPD.sizes(CPD.dps), dpvals(:)');\nend\n\nif length(CPD.cps) == 0 \n  y = gsamp(CPD.mean(:,i), CPD.cov(:,:,i), 1);\nelse\n  pev = pev(:);\n  x = cat(1, pev{CPD.cps});\n  y = gsamp(CPD.mean(:,i) + CPD.weights(:,:,i)*x(:), CPD.cov(:,:,i), 1);\nend\ny = y(:);\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/CPDs/@gaussian_CPD/sample_node.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5568886421472902}}
{"text": "function T = compute_tensor_field_random(n,options)\n\n% compute_tensor_field_random - create 2D TF\n%\n%   T = compute_tensor_field_random(n,options);\n%\n%   Copyright (c) 2008 Gabriel Peyre\n\noptions.null = 0;\nsigma_flow = getoptions(options, 'sigma_tensor', 50*n/256);\nniter_tensor = getoptions(options, 'niter_tensor', 8);\nverb = getoptions(options, 'verb', 1);\n\nT = randn(n,n,3);\nen = linspace(.5,1,n^2);\nan = linspace(.1,1,n^2);\nor = linspace(-pi/2,pi/2,n^2);\nfor i=1:niter_tensor\n    if verb\n        progressbar(i,niter_tensor);\n    end\n    T = perform_blurring(T,sigma_flow);\n    U = perform_tensor_mapping(T,+1);\n%    clf;\n%   for k=1:3\n%        subplot(1,3,k); a = U(:,:,k);\n%        hist(a(:),100); axis tight;\n%    end\n%    drawnow;\n    U(:,:,1) = perform_histogram_equalization(U(:,:,1), en);\n    U(:,:,2) = perform_histogram_equalization(U(:,:,2), an);\n    U(:,:,3) = perform_histogram_equalization(U(:,:,3), or);\n    T = perform_tensor_mapping(U,-1);\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_diffc/compute_tensor_field_random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.556888636301947}}
{"text": "function theta = get_theta_bounds(e1,e2,F,dim)\n\n[theta1,~] = get_theta(e1,dim);\n[theta2,l2] = get_theta(e2,dim);\n\n%% trasfer l2 to i1\nl2(:,1) = F_transfer_l(F,l2(:,1),e2);\nl2(:,2) = F_transfer_l(F,l2(:,2),e2);\n\ntheta2(1) = l_get_angle(l2(:,1));\ntheta2(2) = l_get_angle(l2(:,2));\n\nif theta2(1)>theta2(2)\n    theta2 = flipud(theta2);\nend\n\ntheta(1) = max(theta1(1),theta2(1));\ntheta(2) = min(theta1(2),theta2(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/42209-image-rectification/get_theta_bounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5568605938423261}}
{"text": "function x_stdft = stdft(x, N, K, N_fft)\n\nframes      = 1:K:(length(x)-N);\nx_stdft     = zeros(length(frames), N_fft);\n\nw           = hanning(N);\nx           = x(:);\n\nfor i = 1:length(frames)\n    ii              = frames(i):(frames(i)+N-1);\n\tx_stdft(i, :) \t= fft(x(ii).*w, N_fft);\nend\n", "meta": {"author": "mpariente", "repo": "pystoi", "sha": "9ff1cfa743d59b50f1bd35c21c2e8686de6ac026", "save_path": "github-repos/MATLAB/mpariente-pystoi", "path": "github-repos/MATLAB/mpariente-pystoi/pystoi-9ff1cfa743d59b50f1bd35c21c2e8686de6ac026/tests/matlab/stdft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5568540906557924}}
{"text": "function pot = combine_pots(pot1, pot2)\n% COMBINE_POTS combine two potentials \n% pot = combine_pots(pot1, pot2)\n\n% Reduce both potentials before trying to combine them. \n% Cf. \"Stable Local computation with Conditional Gaussian Distributions\", page 9\n% Consider again two potentials with minimal tail\n\n% Guarantee minimal tails. If pot1 or pot2 are minimal, they are not changed\npot1 = reduce_pot(pot1);\npot2 = reduce_pot(pot2);\n\n%if the intersect set of these two potentials' head conts. combination is undifined\nif ~isempty( myintersect(pot1.cheaddom, pot2.cheaddom) )\n    return;\nend\n\nif  isempty( myintersect(pot1.domain, pot2.cheaddom) ) | isempty( myintersect(pot2.domain, pot1.cheaddom))\n    % if satisfy the condition of directed combine\n    pot = direct_combine_pots(pot1, pot2);\nelse\n    % perform recursive combine\n    pot = recursive_combine_pots(pot1, pot2);\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/@scgpot/combine_pots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5568540846778564}}
{"text": "function compare_implementations()\n\nn_trials = 50;\nn_obstacles = 5;\nmatlab_times = nan(1, n_trials);\ncpp_times = nan(1, n_trials);\n\niter = 1;\nwhile iter <= n_trials\n  dim = 1 + ceil(iter / 20);\n  A_bounds = [eye(dim); -eye(dim)];\n  b_bounds = [ones(dim, 1); zeros(dim, 1)];\n\n  obstacle_pts = iris.test.random_obstacles(dim, n_obstacles, zeros(dim,1), ones(dim,1), 0.05);\n  obstacles = mat2cell(obstacle_pts, size(obstacle_pts, 1), size(obstacle_pts, 2), ones(1, size(obstacle_pts, 3)));\n  start = 0.5 * ones(dim,1);\n  options = struct('require_containment', false,...\n                   'error_on_infeasible_start', false,...\n                   'termination_threshold', 2e-2,...\n                   'iter_limit', 100);\n\n  try\n    t0 = tic();\n    [A_c, b_c, C_c, d_c] = iris.inflate_regionmex(obstacles, A_bounds, b_bounds, start, options);\n    cpp_times(iter) = toc(t0);\n\n    t0 = tic();\n    [A_m, b_m, C_m, d_m] = iris.inflate_region_fallback(obstacle_pts, A_bounds, b_bounds, start, options);\n    matlab_times(iter) = toc(t0);\n\n    iter = iter + 1\n  catch\n    continue\n  end\n\n  % assert(iris.util.equal_up_to_permutations(A_c, A_m, 1e-2));\n  % assert(iris.util.equal_up_to_permutations(b_c, b_m, 1e-2));\n  assert(all(all(abs(C_c - C_m) < 1e-2)));\n  assert(all(all(abs(d_c - d_m) < 1e-2)));\n\nend\n\nfprintf(1, 'c++ mean: %f std: %f\\n', mean(cpp_times), std(cpp_times));\nfprintf(1, 'matlab mean: %f std: %f\\n', mean(matlab_times), std(matlab_times));\n", "meta": {"author": "rdeits", "repo": "iris-distro", "sha": "ff624610a82a858862d55732136dbc2cc9ab16fc", "save_path": "github-repos/MATLAB/rdeits-iris-distro", "path": "github-repos/MATLAB/rdeits-iris-distro/iris-distro-ff624610a82a858862d55732136dbc2cc9ab16fc/src/matlab/+iris/+test/compare_implementations.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.556854078046188}}
{"text": "function [ o, x, w ] = en_r2_11_1 ( n, option )\n\n%*****************************************************************************80\n%\n%% EN_R2_11_1 implements the Stroud rule 11.1 for region EN_R2.\n%\n%  Discussion:\n%\n%    The rule has order \n%\n%      O = ( 4 * N^5 - 20 * N^4 + 140 * N^3 - 130 * N^2 + 96 * N + 15 ) / 15.\n%\n%    The rule has precision P = 11.\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%    There are two versions of each rule, chosen by setting the\n%    OPTION variable to 1 or 2.\n%\n%    The rule as tabulated by Stenger is available for N = 2 through 20.\n%    This function accepts N = 3 through 5.\n%\n%     N    O\n%    __  ___\n%     3  151\n%     4  417\n%     5  983\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    21 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%    3 <= N <= 5.\n%\n%    Input, integer OPTION, chooses rule option 1 or 2.\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 ( n < 3 | 5 < n )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'EN_R2_11_1 - Fatal error!\\n' );\n    fprintf ( 1, '  3 <= N <= 5 required.\\n' );\n    error ( 'EN_R2_11_1 - Fatal error!' )\n  end\n\n  if ( nargin < 2 )\n    option = 1;\n  end\n\n  if ( option < 1 | 2 < option )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'EN_R2_11_1 - Fatal error!\\n' );\n    fprintf ( 1, '  1 <= OPTION <= 2 required.\\n' );\n    error ( 'EN_R2_11_1 - Fatal error!' )\n  end\n\n  o = ( 4 * n^5 - 20 * n^4 + 140 * n^3 - 130 * n^2 + 96 * n + 15 ) / 15;\n  volume = sqrt ( pi^n );\n\n  if ( n == 3 & option == 1 )\n    u =     0.235060497367449E+01;\n    v =     0.436077411927617E+00;\n    w2 =    0.133584907401370E+01;\n    b0 =  - 0.881591029957858E+01;\n    b1 =  - 0.751996143360650E-01;\n    b2 =    0.621743189471515E+01;\n    b3 =    0.241426451456494E+00;\n    b4 =  - 0.120709739276065E-02;\n    b5 =  - 0.427751221210138E+01;\n    b6 =    0.550169924840163E-01;\n    b7 =    0.237084999634707E-01;\n    b8 =  - 0.169791992887741E-02;\n    b9 =  - 0.252266276123350E-04;\n    b10 =   0.326777873717691E+01;\n    b11 =   0.968469949206802E-02;\n    b12 =   0.789754514877422E-03;\n    b13 =   0.000000000000000E+00;\n    b14 =   0.000000000000000E+00;\n    b15 =   0.000000000000000E+00;\n  elseif ( n == 3 & option == 2 )\n    u =     0.235060497367449E+01;\n    v =     0.133584907401370E+01;\n    w2 =    0.436077411927617E+00;\n    b0 =  - 0.141214037032900E+02;\n    b1 =  - 0.803730274707282E-01;\n    b2 =    0.235546545595906E+00;\n    b3 =    0.888123191556611E+01;\n    b4 =    0.142467131155533E-03;\n    b5 =    0.582993124006494E-01;\n    b6 =  - 0.561099173155661E+01;\n    b7 =  - 0.204028691521686E-02;\n    b8 =    0.252880089932256E-01;\n    b9 =  - 0.814378678627283E-04;\n    b10 =   0.804353953375146E-02;\n    b11 =   0.393451849690453E+01;\n    b12 =   0.171183493169724E-03;\n    b13 =   0.000000000000000E+00;\n    b14 =   0.000000000000000E+00;\n    b15 =   0.000000000000000E+00;\n  elseif ( n == 4 & option == 1 )\n    u =     0.235060497367449E+01;\n    v =     0.436077411927617E+00;\n    w2 =    0.133584907401370E+01;\n    b0 =    0.241502736147339E+03;\n    b1 =  - 0.196095938531478E+00;\n    b2 =  - 0.128675737999280E+03;\n    b3 =    0.307568784278696E+00;\n    b4 =  - 0.480908422319460E-02;\n    b5 =    0.698087019367085E+02;\n    b6 =    0.631837143743771E-01;\n    b7 =    0.392226151971179E-01;\n    b8 =  - 0.300948471646799E-02;\n    b9 =  - 0.650235306755170E-04;\n    b10 = - 0.386951974646715E+02;\n    b11 =   0.171656829095787E-01;\n    b12 =   0.139980343116450E-02;\n    b13 =   0.101552487093372E-04;\n    b14 =   0.222435922356439E+02;\n    b15 =   0.000000000000000E+00;\n  elseif ( n == 4 & option == 2 )\n    u =     0.235060497367449E+01;\n    v =     0.133584907401370E+01;\n    w2 =    0.436077411927617E+00;\n    b0 =  - 0.151944464736584E+03;\n    b1 =  - 0.223498438689039E+00;\n    b2 =    0.243574919068010E+00;\n    b3 =    0.634373877008693E+02;\n    b4 =  - 0.782065187814018E-04;\n    b5 =    0.911833754536616E-01;\n    b6 =  - 0.238927288245914E+02;\n    b7 =  - 0.422314408318853E-02;\n    b8 =    0.448218289217760E-01;\n    b9 =  - 0.138053374667391E-03;\n    b10 =   0.607473265800655E-02;\n    b11 =   0.697375246129742E+01;\n    b12 =   0.303414841680135E-03;\n    b13 = - 0.314574391771792E-05;\n    b14 =   0.409103498175100E-02;\n    b15 =   0.000000000000000E+00;\n  elseif ( n == 5 & option == 1 )\n    u =     0.235060497367449E+01;\n    v =     0.436077411927617E+00;\n    w2 =    0.133584907401370E+01;\n    b0 =    0.255885269311763E+04;\n    b1 =  - 0.439598677491526E+00;\n    b2 =  - 0.106541406144610E+04;\n    b3 =    0.453540909054264E+00;\n    b4 =  - 0.132100905623778E-01;\n    b5 =    0.418606568954203E+03;\n    b6 =    0.511394563043680E-01;\n    b7 =    0.645581013845604E-01;\n    b8 =  - 0.533417277494500E-02;\n    b9 =  - 0.137981626254496E-03;\n    b10 = - 0.147436933189884E+03;\n    b11 =   0.304253807765057E-01;\n    b12 =   0.248108698207828E-02;\n    b13 =   0.113652094546015E-04;\n    b14 =   0.394257407160391E+02;\n    b15 =   0.331725011358320E-05;\n  elseif ( n == 5 & option == 2 )\n    u =     0.235060497367449E+01;\n    v =     0.133584907401370E+01;\n    w2 =    0.436077411927617E+00;\n    b0 =  - 0.761305347548192E+03;\n    b1 =  - 0.536360805019297E+00;\n    b2 =    0.110669832078736E+00;\n    b3 =    0.246421088923968E+03;\n    b4 =  - 0.773649327968607E-03;\n    b5 =    0.169088641205970E+00;\n    b6 =  - 0.670700680243651E+02;\n    b7 =  - 0.856090560229205E-02;\n    b8 =    0.794446232770302E-01;\n    b9 =  - 0.220272863263544E-03;\n    b10 = - 0.373515812228225E-02;\n    b11 =   0.123606544052884E+02;\n    b12 =   0.537788804557843E-03;\n    b13 = - 0.122101861480881E-04;\n    b14 =   0.725117070759373E-02;\n    b15 =   0.331725011358320E-05;\n  end\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) = 0.0;\n  w(k) = b0;\n%\n%  2 * N points.\n%\n  for i = 1 : n\n    k = k + 1;\n    x(i,k) = - u;\n    w(k) = b1;\n    k = k + 1;\n    x(i,k) = + u;\n    w(k) = b1;\n  end\n%\n%  2 * N points.\n%\n  for i = 1 : n\n    k = k + 1;\n    x(i,k) = - v;\n    w(k) = b2;\n    k = k + 1;\n    x(i,k) = + v;\n    w(k) = b2;\n  end\n%\n%  2 * N points.\n%\n  for i = 1 : n\n    k = k + 1;\n    x(i,k) = - w2;\n    w(k) = b3;\n    k = k + 1;\n    x(i,k) = + w2;\n    w(k) = b3;\n  end\n%\n%  4 * ( N * ( N - 1 ) / 2 ) points.\n%\n  for i = 1 : n - 1\n    for j = i + 1 : n\n      k = k + 1;\n      x(i,k) = - u;\n      x(j,k) = - u;\n      w(k) = b4;\n      k = k + 1;\n      x(i,k) = - u;\n      x(j,k) = + u;\n      w(k) = b4;\n      k = k + 1;\n      x(i,k) = + u;\n      x(j,k) = - u;\n      w(k) = b4;\n      k = k + 1;\n      x(i,k) = + u;\n      x(j,k) = + u;\n      w(k) = b4;\n    end\n  end\n%\n%  4 * ( N * ( N - 1 ) / 2 ) points.\n%\n  for i = 1 : n - 1\n    for j = i + 1 : n\n      k = k + 1;\n      x(i,k) = - v;\n      x(j,k) = - v;\n      w(k) = b5;\n      k = k + 1;\n      x(i,k) = - v;\n      x(j,k) = + v;\n      w(k) = b5;\n      k = k + 1;\n      x(i,k) = + v;\n      x(j,k) = - v;\n      w(k) = b5;\n      k = k + 1;\n      x(i,k) = + v;\n      x(j,k) = + v;\n      w(k) = b5;\n    end\n  end\n%\n%  4 * ( N * ( N - 1 ) / 2 ) points.\n%\n  for i = 1 : n - 1\n    for j = i + 1 : n\n      k = k + 1;\n      x(i,k) = - w2;\n      x(j,k) = - w2;\n      w(k) = b6;\n      k = k + 1;\n      x(i,k) = - w2;\n      x(j,k) = + w2;\n      w(k) = b6;\n      k = k + 1;\n      x(i,k) = + w2;\n      x(j,k) = - w2;\n      w(k) = b6;\n      k = k + 1;\n      x(i,k) = + w2;\n      x(j,k) = + w2;\n      w(k) = b6;\n    end\n  end\n%\n%  4 * ( N * ( N - 1 ) ) points.\n%\n  for i = 1 : n - 1\n    for j = i + 1 : n\n      k = k + 1;\n      x(i,k) = - u;\n      x(j,k) = - v;\n      w(k) = b7;\n      k = k + 1;\n      x(i,k) = - u;\n      x(j,k) = + v;\n      w(k) = b7;\n      k = k + 1;\n      x(i,k) = + u;\n      x(j,k) = - v;\n      w(k) = b7;\n      k = k + 1;\n      x(i,k) = + u;\n      x(j,k) = + v;\n      w(k) = b7;\n      k = k + 1;\n      x(i,k) = - v;\n      x(j,k) = - u;\n      w(k) = b7;\n      k = k + 1;\n      x(i,k) = - v;\n      x(j,k) = + u;\n      w(k) = b7;\n      k = k + 1;\n      x(i,k) = + v;\n      x(j,k) = - u;\n      w(k) = b7;\n      k = k + 1;\n      x(i,k) = + v;\n      x(j,k) = + u;\n      w(k) = b7;\n    end\n  end\n%\n%  4 * ( N * ( N - 1 ) ) points.\n%\n  for i = 1 : n - 1\n    for j = i + 1 : n\n      k = k + 1;\n      x(i,k) = - u;\n      x(j,k) = - w2;\n      w(k) = b8;\n      k = k + 1;\n      x(i,k) = - u;\n      x(j,k) = + w2;\n      w(k) = b8;\n      k = k + 1;\n      x(i,k) = + u;\n      x(j,k) = - w2;\n      w(k) = b8;\n      k = k + 1;\n      x(i,k) = + u;\n      x(j,k) = + w2;\n      w(k) = b8;\n      k = k + 1;\n      x(i,k) = - w2;\n      x(j,k) = - u;\n      w(k) = b8;\n      k = k + 1;\n      x(i,k) = - w2;\n      x(j,k) = + u;\n      w(k) = b8;\n      k = k + 1;\n      x(i,k) = + w2;\n      x(j,k) = - u;\n      w(k) = b8;\n      k = k + 1;\n      x(i,k) = + w2;\n      x(j,k) = + u;\n      w(k) = b8;\n    end\n  end\n%\n%  8 * ( N * ( N - 1 ) * ( N - 2 ) / 6 ) points.\n%\n  for i = 1 : n - 2\n    for j = i + 1 : n - 1\n      for l = j + 1 : n\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = - u;\n        x(l,k) = - u;\n        w(k) = b9;\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = - u;\n        x(l,k) = + u;\n        w(k) = b9;\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = + u;\n        x(l,k) = - u;\n        w(k) = b9;\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = + u;\n        x(l,k) = + u;\n        w(k) = b9;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = - u;\n        x(l,k) = - u;\n        w(k) = b9;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = - u;\n        x(l,k) = + u;\n        w(k) = b9;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = + u;\n        x(l,k) = - u;\n        w(k) = b9;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = + u;\n        x(l,k) = + u;\n        w(k) = b9;\n      end\n    end\n  end\n%\n%  8 * ( N * ( N - 1 ) * ( N - 2 ) / 6 ) points.\n%\n  for i = 1 : n - 2\n    for j = i + 1 : n - 1\n      for l = j + 1 : n\n        k = k + 1;\n        x(i,k) = - v;\n        x(j,k) = - v;\n        x(l,k) = - v;\n        w(k) = b10;\n        k = k + 1;\n        x(i,k) = - v;\n        x(j,k) = - v;\n        x(l,k) = + v;\n        w(k) = b10;\n        k = k + 1;\n        x(i,k) = - v;\n        x(j,k) = + v;\n        x(l,k) = - v;\n        w(k) = b10;\n        k = k + 1;\n        x(i,k) = - v;\n        x(j,k) = + v;\n        x(l,k) = + v;\n        w(k) = b10;\n        k = k + 1;\n        x(i,k) = + v;\n        x(j,k) = - v;\n        x(l,k) = - v;\n        w(k) = b10;\n        k = k + 1;\n        x(i,k) = + v;\n        x(j,k) = - v;\n        x(l,k) = + v;\n        w(k) = b10;\n        k = k + 1;\n        x(i,k) = + v;\n        x(j,k) = + v;\n        x(l,k) = - v;\n        w(k) = b10;\n        k = k + 1;\n        x(i,k) = + v;\n        x(j,k) = + v;\n        x(l,k) = + v;\n        w(k) = b10;\n      end\n    end\n  end\n%\n%  8 * ( N * ( N - 1 ) * ( N - 2 ) / 6 ) points.\n%\n  for i = 1 : n - 2\n    for j = i + 1 : n - 1\n      for l = j + 1 : n\n        k = k + 1;\n        x(i,k) = - w2;\n        x(j,k) = - w2;\n        x(l,k) = - w2;\n        w(k) = b11;\n        k = k + 1;\n        x(i,k) = - w2;\n        x(j,k) = - w2;\n        x(l,k) = + w2;\n        w(k) = b11;\n        k = k + 1;\n        x(i,k) = - w2;\n        x(j,k) = + w2;\n        x(l,k) = - w2;\n        w(k) = b11;\n        k = k + 1;\n        x(i,k) = - w2;\n        x(j,k) = + w2;\n        x(l,k) = + w2;\n        w(k) = b11;\n        k = k + 1;\n        x(i,k) = + w2;\n        x(j,k) = - w2;\n        x(l,k) = - w2;\n        w(k) = b11;\n        k = k + 1;\n        x(i,k) = + w2;\n        x(j,k) = - w2;\n        x(l,k) = + w2;\n        w(k) = b11;\n        k = k + 1;\n        x(i,k) = + w2;\n        x(j,k) = + w2;\n        x(l,k) = - w2;\n        w(k) = b11;\n        k = k + 1;\n        x(i,k) = + w2;\n        x(j,k) = + w2;\n        x(l,k) = + w2;\n        w(k) = b11;\n      end\n    end\n  end\n%\n%  8 * ( N * ( N - 1 ) * ( N - 2 ) / 2 ) points.\n%\n  for i = 1 : n - 2\n    for j = i + 1 : n - 1\n      for l = j + 1 : n\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = - u;\n        x(l,k) = - v;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = - u;\n        x(l,k) = + v;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = + u;\n        x(l,k) = - v;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = + u;\n        x(l,k) = + v;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = - u;\n        x(l,k) = - v;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = - u;\n        x(l,k) = + v;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = + u;\n        x(l,k) = - v;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = + u;\n        x(l,k) = + v;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = - v;\n        x(l,k) = - u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = - v;\n        x(l,k) = + u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = + v;\n        x(l,k) = - u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = - u;\n        x(j,k) = + v;\n        x(l,k) = + u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = - v;\n        x(l,k) = - u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = - v;\n        x(l,k) = + u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = + v;\n        x(l,k) = - u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + u;\n        x(j,k) = + v;\n        x(l,k) = + u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = - v;\n        x(j,k) = - u;\n        x(l,k) = - u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = - v;\n        x(j,k) = - u;\n        x(l,k) = + u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = - v;\n        x(j,k) = + u;\n        x(l,k) = - u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = - v;\n        x(j,k) = + u;\n        x(l,k) = + u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + v;\n        x(j,k) = - u;\n        x(l,k) = - u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + v;\n        x(j,k) = - u;\n        x(l,k) = + u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + v;\n        x(j,k) = + u;\n        x(l,k) = - u;\n        w(k) = b12;\n        k = k + 1;\n        x(i,k) = + v;\n        x(j,k) = + u;\n        x(l,k) = + u;\n        w(k) = b12;\n      end\n    end\n  end\n%\n%  16 * ( N * ( N - 1 ) * ( N - 2 ) * ( N - 3 ) / 24 ) points.\n%\n  for i = 1 : n - 3\n    for j = i + 1 : n - 2\n      for l = j + 1 : n - 1\n        for m = l + 1 : n\n          k = k + 1;\n          x(i,k) = - u;\n          x(j,k) = - u;\n          x(l,k) = - u;\n          x(m,k) = - u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = - u;\n          x(j,k) = - u;\n          x(l,k) = - u;\n          x(m,k) = + u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = - u;\n          x(j,k) = - u;\n          x(l,k) = + u;\n          x(m,k) = - u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = - u;\n          x(j,k) = - u;\n          x(l,k) = + u;\n          x(m,k) = + u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = - u;\n          x(j,k) = + u;\n          x(l,k) = - u;\n          x(m,k) = - u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = - u;\n          x(j,k) = + u;\n          x(l,k) = - u;\n          x(m,k) = + u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = - u;\n          x(j,k) = + u;\n          x(l,k) = + u;\n          x(m,k) = - u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = - u;\n          x(j,k) = + u;\n          x(l,k) = + u;\n          x(m,k) = + u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = + u;\n          x(j,k) = - u;\n          x(l,k) = - u;\n          x(m,k) = - u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = + u;\n          x(j,k) = - u;\n          x(l,k) = - u;\n          x(m,k) = + u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = + u;\n          x(j,k) = - u;\n          x(l,k) = + u;\n          x(m,k) = - u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = + u;\n          x(j,k) = - u;\n          x(l,k) = + u;\n          x(m,k) = + u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = + u;\n          x(j,k) = + u;\n          x(l,k) = - u;\n          x(m,k) = - u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = + u;\n          x(j,k) = + u;\n          x(l,k) = - u;\n          x(m,k) = + u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = + u;\n          x(j,k) = + u;\n          x(l,k) = + u;\n          x(m,k) = - u;\n          w(k) = b13;\n          k = k + 1;\n          x(i,k) = + u;\n          x(j,k) = + u;\n          x(l,k) = + u;\n          x(m,k) = + u;\n          w(k) = b13;\n        end\n      end\n    end\n  end\n%\n%  16 * ( N * ( N - 1 ) * ( N - 2 ) * ( N - 3 ) / 24 ) points.\n%\n  for i = 1 : n - 3\n    for j = i + 1 : n - 2\n      for l = j + 1 : n - 1\n        for m = l + 1 : n\n          k = k + 1;\n          x(i,k) = - v;\n          x(j,k) = - v;\n          x(l,k) = - v;\n          x(m,k) = - v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = - v;\n          x(j,k) = - v;\n          x(l,k) = - v;\n          x(m,k) = + v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = - v;\n          x(j,k) = - v;\n          x(l,k) = + v;\n          x(m,k) = - v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = - v;\n          x(j,k) = - v;\n          x(l,k) = + v;\n          x(m,k) = + v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = - v;\n          x(j,k) = + v;\n          x(l,k) = - v;\n          x(m,k) = - v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = - v;\n          x(j,k) = + v;\n          x(l,k) = - v;\n          x(m,k) = + v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = - v;\n          x(j,k) = + v;\n          x(l,k) = + v;\n          x(m,k) = - v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = - v;\n          x(j,k) = + v;\n          x(l,k) = + v;\n          x(m,k) = + v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = + v;\n          x(j,k) = - v;\n          x(l,k) = - v;\n          x(m,k) = - v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = + v;\n          x(j,k) = - v;\n          x(l,k) = - v;\n          x(m,k) = + v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = + v;\n          x(j,k) = - v;\n          x(l,k) = + v;\n          x(m,k) = - v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = + v;\n          x(j,k) = - v;\n          x(l,k) = + v;\n          x(m,k) = + v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = + v;\n          x(j,k) = + v;\n          x(l,k) = - v;\n          x(m,k) = - v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = + v;\n          x(j,k) = + v;\n          x(l,k) = - v;\n          x(m,k) = + v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = + v;\n          x(j,k) = + v;\n          x(l,k) = + v;\n          x(m,k) = - v;\n          w(k) = b14;\n          k = k + 1;\n          x(i,k) = + v;\n          x(j,k) = + v;\n          x(l,k) = + v;\n          x(m,k) = + v;\n          w(k) = b14;\n        end\n      end\n    end\n  end\n%\n%  All quintuples UUUUU with 32 sign combinations.\n%\n  for i1 = 1 : n - 4\n    for i2 = i1 + 1 : n - 3\n      for i3 = i2 + 1 : n - 2\n        for i4 = i3 + 1 : n - 1\n          for i5 = i4 + 1 : n\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = - u;\n            x(i3,k) = - u;\n            x(i4,k) = - u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = - u;\n            x(i3,k) = - u;\n            x(i4,k) = - u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = - u;\n            x(i3,k) = - u;\n            x(i4,k) = + u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = - u;\n            x(i3,k) = - u;\n            x(i4,k) = + u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = - u;\n            x(i3,k) = + u;\n            x(i4,k) = - u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = - u;\n            x(i3,k) = + u;\n            x(i4,k) = - u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = - u;\n            x(i3,k) = + u;\n            x(i4,k) = + u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = - u;\n            x(i3,k) = + u;\n            x(i4,k) = + u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = + u;\n            x(i3,k) = - u;\n            x(i4,k) = - u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = + u;\n            x(i3,k) = - u;\n            x(i4,k) = - u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = + u;\n            x(i3,k) = - u;\n            x(i4,k) = + u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = + u;\n            x(i3,k) = - u;\n            x(i4,k) = + u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = + u;\n            x(i3,k) = + u;\n            x(i4,k) = - u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = + u;\n            x(i3,k) = + u;\n            x(i4,k) = - u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = + u;\n            x(i3,k) = + u;\n            x(i4,k) = + u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = - u;\n            x(i2,k) = + u;\n            x(i3,k) = + u;\n            x(i4,k) = + u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = - u;\n            x(i3,k) = - u;\n            x(i4,k) = - u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = - u;\n            x(i3,k) = - u;\n            x(i4,k) = - u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = - u;\n            x(i3,k) = - u;\n            x(i4,k) = + u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = - u;\n            x(i3,k) = - u;\n            x(i4,k) = + u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = - u;\n            x(i3,k) = + u;\n            x(i4,k) = - u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = - u;\n            x(i3,k) = + u;\n            x(i4,k) = - u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = - u;\n            x(i3,k) = + u;\n            x(i4,k) = + u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = - u;\n            x(i3,k) = + u;\n            x(i4,k) = + u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = + u;\n            x(i3,k) = - u;\n            x(i4,k) = - u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = + u;\n            x(i3,k) = - u;\n            x(i4,k) = - u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = + u;\n            x(i3,k) = - u;\n            x(i4,k) = + u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = + u;\n            x(i3,k) = - u;\n            x(i4,k) = + u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = + u;\n            x(i3,k) = + u;\n            x(i4,k) = - u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = + u;\n            x(i3,k) = + u;\n            x(i4,k) = - u;\n            x(i5,k) = + u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = + u;\n            x(i3,k) = + u;\n            x(i4,k) = + u;\n            x(i5,k) = - u;\n            w(k) = b15;\n            k = k + 1;\n            x(i1,k) = + u;\n            x(i2,k) = + u;\n            x(i3,k) = + u;\n            x(i4,k) = + u;\n            x(i5,k) = + u;\n            w(k) = b15;\n          end\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/stroud/en_r2_11_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857831, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.556814129935959}}
{"text": "function sF = cos(sF, varargin)\n% cost of a function\n% Syntax\n%   sF = cos(sF)\n%   sF = cos(sF, 'bandwidth', bandwidth)\n%\n% Input\n%  sF - @S2FunHarmonic\n%\n% Output\n%  sF - @S2FunHarmonic\n%\n% Options\n%  bandwidth - minimal degree of the spherical harmonic\n%\n\nsF = sF.quadrature(@(v) cos(sF.eval(v)),varargin{:});\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/S2Fun/@S2FunHarmonic/cos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5568141197335061}}
{"text": " function out = equivs(var1, var2, varargin)\n%function out = equivs(var1, var2, command)\n%|\n%| verify that var1 and var2 are equivalent to within single precision accuracy\n%| if not, print error message.  an alternative to isequal().\n%| See also: jf_equal\n%|\n%| option\n%|\t'thresh'\tthreshold (default: 1e-6)\n%|\t'format'\tformat for displaying the two variables (default: '')\n%|\t'fail'\t0|1\tif 1 (default) then fail if not equivalent, else warn\n%|\n%| out\n%|\tout\t\t0|1\n%|\n%| Copyright 2007, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(var1, 'test'), equivs_test, return, end\nif nargin < 2, ir_usage, end\n\narg.thresh = 1e-6;\narg.format = '';\narg.fail = true;\narg = vararg_pair(arg, varargin);\n\nif isempty(var1) && isempty(var2)\n\tok = true;\n\nelseif ~isequal(size(var1), size(var2))\n\tprintm([': size(%s) = %s'], inputname(1), mat2str(size(var1)))\n        printm([': size(%s) = %s'], inputname(2), mat2str(size(var2)))\n\tequivs_show(var1, var2, inputname(1), inputname(2), arg.format)\n\tif arg.fail\n\t\tfail('incompatible dimensions')\n\telse\n\t\twarn('incompatible dimensions')\n\t\treturn\n\tend\n\nelse\n\tvar1 = var1(:);\n\tvar2 = var2(:);\n\tif any(isnan(var1)) || any(isnan(var2))\n\t\tif arg.fail\n\t\t\tfail('nan')\n\t\telse\n\t\t\twarn('nan')\n\t\t\tok = false;\n\t\t\treturn\n\t\tend\n\tend\n\n\tnorm = (max(abs(var1)) + max(abs(var2))) / 2;\n\tif ~norm\n\t\tok = true; % both zero!\n\telse\n\t\terr = max(abs(var1-var2)) / norm;\n\t\tok = err < arg.thresh;\n\tend\nend\n\nif nargout\n\tout = ok;\nend\n\nif ok\n\treturn\nend\n\n[name line] = caller_name;\nif isempty(name)\n\tstr = '';\nelse\n\tstr = sprintf('%s %d:', name, line);\nend\n\nname1 = inputname(1);\nname2 = inputname(2);\nminmax(var1, ['equivs ' name1 ':'])\nminmax(var2, ['equivs ' name2 ':'])\ndiff = var1 - var2;\nif ~isreal(diff)\n\tdiff = abs(diff);\nend\nminmax(diff)\nprintm([str ' normalized difference of %g between \"%s\" \"%s\"'], ...\n\terr, name1, name2);\nif arg.fail\n\tfail('not equal to within single precision, thresh=%g', arg.thresh)\nelse\n\twarn('not equal to within single precision, thresh=%g', arg.thresh)\nend\n\n\nfunction equivs_show(var1, var2, name1, name2, format)\nif isempty(format), return, end\ndisp(name1)\ndisp(num2str(var1, format))\ndisp(name2)\ndisp(num2str(var2, format))\n\n\nfunction equivs_test\nrng(0)\nx = randn(1000,200);\ny = dsingle(x);\nequivs(x,y)\n\npassed = 0;\ntry\n\ty = x + 2e-6 * max(x(:));\n\tequivs(x,y)\n\tpassed = 1;\ncatch\nend\nif passed, error 'this should have failed!', end\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/equivs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.5567988194320523}}
{"text": "\nload 'sdae_rbm_mnist_vis.mat';\n\ncolors = colormap;\n\nfigure;\nhold on;\nfor c = 1:10\n    x = H(X_labels == (c-1), 1);\n    y = H(X_labels == (c-1), 2);\n    rndidx = randperm(length(x));\n    x = x(rndidx(1:500));\n    y = y(rndidx(1:500));\n\n    plot(x, y, 'x', 'Color', colors(ceil(c/10 * 64), :));\nend\nhold off;\n\n\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/example/vis_mnist_rbm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.5567988146035456}}
{"text": "%This function sorts the input array in ascending order using the Comb Sort algorithm\n%For details, refer https://en.wikipedia.org/wiki/Comb_sort\n\nfunction y = comb_sort(array)\n            \nlen = length(array);\nk = len;\nisSwapped = true;\n% value of shrink should be greater than 1\nshrink = 1.4; \nwhile ((k > 1) || (isSwapped == true))    \n    k = max(floor(k / shrink),1);   \n    % Bubble sort with given value of k\n    i = 1;\n    isSwapped = false;\n    while ((i + k) <= len)\n        if (array(i) > array(i + k))\n            array = swap(array,i,i + k);\n            isSwapped = true;\n        end\n        i = i + 1;\n    end\nend\ny = array;\nend\n\nfunction array = swap(array,i,j)\nvalue = array(i);\narray(i) = array(j);\narray(j) = value;\n% Note: In practice, array should be passed by reference\nend\n", "meta": {"author": "TheAlgorithms", "repo": "MATLAB-Octave", "sha": "e150b77ad256de46c1ce3815c3d7945ac4fc28dc", "save_path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave", "path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave/MATLAB-Octave-e150b77ad256de46c1ce3815c3d7945ac4fc28dc/algorithms/sorting/comb_sort.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.785308578375437, "lm_q1q2_score": 0.5567988079937553}}
{"text": "%IM_THRESHOLD Fixed mapping thresholding images (DIP_Image)\n%\n%\tB = IM_THRESHOLD(A,TYPE,PAR,INV)\n%\tB = A*IM_THRESHOLD([],TYPE,PAR,INV)\n%\tB = A*IM_THRESHOLD(TYPE,PAR,INV)\n%\n% INPUT\n%   A        Dataset with object images (possibly multi-band)\n%   TYPE     Type of procedure, see below\n%   PAR      Related parameter\n%   INV      If INV = 1, result inverted, default INV = 0.\n%\n% OUTPUT\n%   B        Dataset with thresholded images\n%\n% DESCRIPTION\n% The following procedures are supported (TYPE)\n% 'isodata':      Thresholding using the Isodata algorithm\n% 'otsu':         See IM2BW\n% 'triangle':    *Thresholding using chord method\n%                 (a.k.a. skewed bi-modality, maximum distance to triangle)\n%                 by Zack, Rogers and Latt (1973).\n% 'background':  *Thresholding using unimodal background-symmetry method.\n% 'fixed':        Thresholding at a fixed value.\n% 'double':      *Thresholding between two fixed values.\n% 'volume':      *Thresholding to obtain a given volume fraction.\n% 'hysteresis':  *From the binary image (in>low) only those regions are\n%                 selected for which at least one pixel is (in>high)\n%\n% The following parameters are related to these procedures (PAR):\n% ('background'): Distance to the peak where we cut-off, in\n%                 terms of the half-width at half the maximum.\n%                 Inf selects the default value, which is 2.\n% ('fixed'):      Threshold value. Inf means halfway between\n%                 minimum and maximum value.\n% ('double'):     Two threshold values. Inf means min+[1/3,2/3]*(max-min).\n% ('volume'):     Parameter = the volume fraction (Inf means 0.5)\n% ('hysteresis'): Two values: low, high (see above)\n%\n% * routine needs DIP_IMAGE\n%\n% This routine is for smart thresholding. Simple thresholding can also be\n% performed by B = A > PAR, which is the same as using the type 'fixed'.\n%\n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% DATASETS, DATAFILES, DIP_IMAGE, THRESHOLD\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 b = im_threshold(varargin)\n\n\targin = shiftargin(varargin,'char');\n  argin = setdefaults(argin,[],'isodata',inf,0);\n  if mapping_task(argin,'definition')\n    b = define_mapping(argin,'fixed');\n    b = setname(b,'Image threshold');\n  else\n    [a,type,par,inv] = deal(argin{:});\n    if isa(a,'prdataset') % allows datafiles too\n      isobjim(a);\n      b = filtim(a,mfilename,{type,par,inv});\n      b = setfeatsize(b,getfeatsize(a));\n    elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image\n      switch lower(type)\n        case('isodata')\n          mina = min(a(:));  maxa = max(a(:));\n          b = 255*(a-mina)/(maxa-mina);\n          t0 = 128;\n          for j=1:25\n            U = b >  t0;\n            L = b <= t0;\n            n2 = mean(b(U)); n1 = mean(b(L));\n            t1 = (n1+n2)/2;\n            if t1 == t0;\n              break;\n            else\n              t0 = t1;\n            end\n          end\n          b = b > t0;\n        case('fixed')\n          b = a > par;\n        case('otsu')\n          b = im2bw(a);\n        case {'triangle','background','double','volume','hysteresis'}\n          checktoolbox('dipimage');       \n          a = 1.0*dip_image(a);\n          b = threshold(a,type,par);\n        otherwise\n          error 'Illegal thresholding type'\n      end\n      if inv\n        b = 1-b;\n      end\n    end\n  end\n\nreturn", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/im_threshold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.556798802649904}}
{"text": "function [ a_lu, pivot, info ] = r8gb_trf ( m, n, ml, mu, a )\n\n%*****************************************************************************80\n%\n%% R8GB_TRF performs a LAPACK-style PLU factorization of a R8GB matrix.\n%\n%  Discussion:\n%\n%    The R8GB storage format is for an M by N banded matrix, with lower \n%    bandwidth ML and upper bandwidth MU.  Storage includes room for ML \n%    extra superdiagonals, which may be required to store nonzero entries \n%    generated during Gaussian elimination.\n%\n%    The original M by N matrix is \"collapsed\" downward, so that diagonals\n%    become rows of the storage array, while columns are preserved.  The\n%    collapsed array is logically 2*ML+MU+1 by N.  \n%\n%    This is a simplified, standalone version of the LAPACK\n%    routine R8GBTRF.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    20 March 2004\n%\n%  Author:\n%\n%    MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Anderson, Bai, Bischof, Demmel, Dongarra, Du Croz, Greenbaum,\n%    Hammarling, McKenney, Ostrouchov, Sorensen,\n%    LAPACK User's Guide,\n%    Second Edition,\n%    SIAM, 1995.\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, integer ML, the number of subdiagonals within the band of A.\n%    0 <= ML.\n%\n%    Input, integer MU, the number of superdiagonals within the band of A.\n%    0 <= MU.\n%\n%    Input, real A(2*ML+MU+1,N), the matrix A in band storage.\n%\n%    Output, real A_LU(2*ML+MU+1,N), information about the PLU factorization.\n%\n%    Output, integer PIVOT(min(M,N)), the pivot indices;\n%    for 1 <= i <= min(M,N), row i of the matrix was interchanged with\n%    row IPIV(i).\n%\n%    Output, integer INFO, error flag.\n%    = 0: successful exit;\n%    < 0: an input argument was illegal;\n%    > 0: if INFO = +i, U(i,i) 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  info = 0;\n  a_lu(1:2*ml+mu+1,1:n) = a(1:2*ml+mu+1,1:n);\n%\n%  KV is the number of superdiagonals in the factor U, allowing for fill-in.\n%\n  kv = mu + ml;\n%\n%  Set fill-in elements in columns MU+2 to KV to zero.\n%\n  for j = mu + 2 : min ( kv, n )\n    for i = kv - j + 2 : ml\n      a_lu(i,j) = 0.0E+00;\n    end\n  end\n%\n%  JU is the index of the last column affected by the current stage\n%  of the factorization.\n%\n  ju = 1;\n\n  for j = 1 : min ( m, n )\n%\n%  Set the fill-in elements in column J+KV to zero.\n%\n    if ( j + kv <= n )\n      a_lu(1:ml,j+kv) = 0.0;\n    end\n%\n%  Find the pivot and test for singularity.\n%  KM is the number of subdiagonal elements in the current column.\n%\n    km = min ( ml, m-j );\n\n    piv = abs ( a_lu(kv+1,j) );\n    jp = kv + 1;\n\n    for i = kv + 2 : kv + km + 1\n      if ( piv < abs ( a_lu(i,j) ) )\n        piv = abs ( a_lu(i,j) );\n        jp = i;\n      end\n    end\n\n    jp = jp - kv;\n\n    pivot(j) = jp + j - 1;\n\n    if ( a_lu(kv+jp,j) ~= 0.0E+00 )\n\n      ju = max ( ju, min ( j+mu+jp-1, n ) );\n%\n%  Apply interchange to columns J to JU.\n%\n      if ( jp ~= 1 )\n        for i = 0 : ju - j\n          t = a_lu(kv+jp-i,j+i);\n          a_lu(kv+jp-i,j+i) = a_lu(kv+1-i,j+i);\n          a_lu(kv+1-i,j+i) = t;\n        end\n      end\n%\n%  Compute the multipliers.\n%\n      if ( 0 < km )\n\n        a_lu(kv+2:kv+km+1,j) = a_lu(kv+2:kv+km+1,j) / a_lu(kv+1,j);\n%\n%  Update the trailing submatrix within the band.\n%\n        if ( j < ju )\n\n          for k = 1 : ju-j\n\n            if ( a_lu(kv+1-k,j+k) ~= 0.0E+00 )\n\n              for i = 1 : km\n                a_lu(kv+i+1-k,j+k) = a_lu(kv+i+1-k,j+k) ...\n                  - a_lu(kv+i+1,j) * a_lu(kv+1-k,j+k);\n              end\n            end\n          end\n        end\n      end\n\n    else\n%\n%  If pivot is zero, set INFO to the index of the pivot\n%  unless a zero pivot has already been found.\n%\n      if ( info == 0 )\n        info = j\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/r8gb_trf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5567988001180255}}
{"text": "function S = globMatrixIFE3DPreCond(fun,coef,mesh,femI,fem1,fem2,dindx,dindy)\n\n%% USAGE: generate stiffness global matrix on a 3D mesh \n%\n% INPUTS:\n% fun --- coefficient function\n% mesh --- a struct data contains very rich mesh information.\n% fem1 --- global DoF for test function space\n% fem2 --- global DoF for trial function space\n%\n% OUTPUTS:\n% [IN JN XN] --- triplets of the sparse matrix from regular elements. \n% [II JI XI] --- triplets of the sparse matrix from interface elements. \n\n% Last Modified: 08/07/2020 by Xu Zhang \n\n%% 0. Initializaiton\nif strcmp(fem1.type,'P1')||strcmp(fem1.type,'DGP1')||strcmp(fem1.type,'CR')\n    feEvalBas1 = @evalP1Bas3D;\nelseif strcmp(fem1.type,'P2')||strcmp(fem1.type,'DGP2')\n    feEvalBas1 = @evalP2Bas3D;\nend\n\nif strcmp(fem2.type,'P1')||strcmp(fem2.type,'DGP1')||strcmp(fem2.type,'CR')\n    feEvalBas2 = @evalP1Bas3D;\nelseif strcmp(fem2.type,'P2')||strcmp(fem2.type,'DGP2')\n    feEvalBas2 = @evalP2Bas3D;\nend\n\n%% 1. Matrix on noninterface elements\ndof1 = fem1.ldof; dof2 = fem2.ldof; nloc = dof1*dof2; \nntID = find(mesh.tLoc > 0); ntN = length(ntID);\nAN = fem1.area(ntID); \ngxN = fem1.gx(ntID,:); gyN = fem1.gy(ntID,:); gzN = fem1.gz(ntID,:); gw = fem1.gw;\nXN = zeros(nloc*ntN, 1);\n\ncoefN = feval(fun,gxN,gyN,gzN);\nIbas = cell(dof1,1); \nJbas = cell(dof2,1); \nfor i = 1:dof1\n    Ibas{i} = feEvalBas1(fem1.bas(ntID,:,i), gxN, gyN, gzN, dindx);\nend\nfor j = 1:dof2\n    Jbas{j} = feEvalBas2(fem2.bas(ntID,:,j), gxN, gyN, gzN, dindy); \nend\n\nIN = reshape(repmat(fem1.t(ntID,:),4,1),nloc*ntN,1);\nJN = repmat(reshape(fem2.t(ntID,:),dof2*ntN,1),4,1);\nind = 0;\nfor i = 1:dof1\n    for j = 1:dof2\n        XN(ind+1:ind+ntN) = AN.*(sum(((Ibas{i}.*(coefN.*Jbas{j})).*gw'),2));\n        ind = ind + ntN;\n    end\nend\nID = find(XN~=0); \nSN = sparse(IN(ID),JN(ID),XN(ID),size(fem1.p,1),size(fem2.p,1));\n\n%% 2. Matrix on interface elements\nAI = femI.area; gw = femI.gw; gxI = femI.gx; gyI = femI.gy; gzI = femI.gz; \nntI = size(femI.t,1); % not number of interface element, but quadrature element\nXI = zeros(nloc*ntI, 1);\n\ncoefI = (coef(1)+coef(2))/2;\nIbas = cell(dof1,1); \nJbas = cell(dof2,1); \nfor i = 1:dof1\n    Ibas{i} = feEvalBas1(femI.bas(:,:,i), gxI, gyI, gzI, dindx);\nend\nfor j = 1:dof2\n    Jbas{j} = feEvalBas2(femI.bas(:,:,j), gxI, gyI, gzI, dindy);\nend\n\nII = reshape(repmat(femI.t,4,1),nloc*ntI,1);\nJI = repmat(reshape(femI.t,dof2*ntI,1),4,1);\nind = 0; \nfor i = 1:dof1\n    for j = 1:dof2\n        XI(ind+1:ind+ntI) = AI.*(sum(((Ibas{i}.*(coefI.*Jbas{j})).*gw'),2));\n        ind = ind + ntI;\n    end\nend\nSI = sparse(II,JI,XI,size(fem1.p,1),size(fem2.p,1));\nS = SN + SI;", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/globMatrixIFE3DPreCond.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5567455096496435}}
{"text": "function [gx,dG_dX,dG_dPhi,d2G_dXdPhi] = g_ERP(x,Phi,u,inG)\n% neural mass observation function (DCM for ERPs)\n\nn = size(x,1);          % should be 9\nnPhi = length(Phi);     % should be 1\n\n\ng = exp(Phi(1)).*[0  0   0   0   0   0   0   0   1\n                  0  0   0   0   0   0   0   0   0.3\n                  0  0   0   0   0   0   0   0   -0.2\n                  0  0   0   0   0   0   0   0   -0.7];\n\n\n% state observation\ngx = g*x;\n\n\n\n%------ gradients evaluations ------%\n\n% wrt the hidden states\ndG_dX = g';\n\n\n% wrt the observation parameters\ndG_dPhi = (g*x)';\n\n\n% mixed partial derivatives\nd2G_dXdPhi(:,:,1) = zeros(n,nPhi);\nd2G_dXdPhi(9,1,1) = exp(Phi(1));\nd2G_dXdPhi(:,:,2) = 0.3*d2G_dXdPhi(:,:,1);\nd2G_dXdPhi(:,:,3) = -0.2*d2G_dXdPhi(:,:,1);\nd2G_dXdPhi(:,:,4) = -0.7*d2G_dXdPhi(:,:,1);\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/g_ERP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5567454992879114}}
{"text": "function [fAphi] = calc_FaultStyle(rStress)\n    % Determine the faulting style based on Quantifying Anderson's fault type\n% [fAphi] = calc_FaultStyle(rStress)\n% ------------------------------------------\n% Determining the faulting style based on Quantifying Anderson's fault type\n% by B. Simpson, 1997, JGR\n%\n% Incoming:\n% rStress : Structure from script gui_NodeCalcStressInv giving stress\n%           tensor inversion by Michael\n% Output:\n% fAphi   : 0 <= fAphi < 1 Normal faulting\n%           1 <= fAphi < 2 Strike slip\n%           2 <= fAphi < 3 Thrust faulting\n%\n% jowoe@gps.caltech.edu\n% 19.05.2006\n\n% Stress tensor from Michael inversion\nmS=[rStress.fS11 rStress.fS12 rStress.fS13; rStress.fS12 rStress.fS22 rStress.fS23; rStress.fS13 rStress.fS23 rStress.fS33];\n\n% Eigenvector; sorted from max. compressive to minimum (S1, S2, S3)\n% Maximum compressive is the most negative value\nvEig = eig(mS);\n\n% Check for \"most\" vertical axis\nvPlunge = [rStress.fS1Plunge; rStress.fS2Plunge; rStress.fS3Plunge];\n\nvSel = (vPlunge == max(vPlunge));\nfSigvert = vEig(vSel);\n\n% This is because maximum compressive is negative\nfSighmax = min(vEig(~vSel,:));\nfSighmin = max(vEig(~vSel,:));\n\nif fSighmax > fSigvert\n    n = 0;\nelseif fSigvert > fSighmin\n    n = 2;\nelse\n    n = 1;\nend\n% Formula 2, Simpson, JGR, 1997\nfAphi = (n+0.5)+(-1)^n*(rStress.fPhi-0.5);\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/jochen/stressinv/calc_FaultStyle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5567454992879114}}
{"text": "function y = glm_fit_model(x,k,v);\n%\n% y = glm_fit_model(x,k,v);\n%\n% A model used to generate a 'synthetic' \n% autocorrelation function which may estimate\n% temporally-correlated noise for within-\n% skull voxels: see Burock and Dale, HBM 2000\n% for more info.\n%\n% This is just broken off as a separate function\n% for use in calling matlab's fminsearch routine.\n%\n% original code by gb, 11/04\n% updated by ras, 05/05\ny = norm((1 - x(1))*(x(2).^(1:k)') - v)^2;\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/GLM/glm_fit_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5567454716096754}}
{"text": "function CPerm=permuteMatrix(C,order)\n%%PERMUTEMATRIX Given an n1Xn2X...nS matrix, rearrange the dimensions of C\n%      to be in the order specified by order. All elements of order must be\n%      unique, real, positive, integer values from 1 to S. This functions\n%      in the same manner as Matlab's permute function. The permutation\n%      performed by this function is not done in-place. This type of\n%      permutation is a type of tensor matrix transpose.\n%\n%INPUTS: C An n1Xn2X...XnS matrix.\n%    order The length S order vector. This should hold integer values from\n%          1 to S with no repeats.\n%\n%OUTPUTS: CPerm C with its dimensions permuted according to order.\n%\n%The algorithm is essentially brute force. It goes through each element in\n%C and find the tuple of the associated element in CPerm to which the\n%assignment must be performed.\n%\n%EXAMPLE:\n% C=100*rand(3,4,5);\n% order=[3,2,1];\n% CPerm=permuteMatrix(C,order);\n%One will ntoe that size(CPerm) is note [5,4,3].\n%\n%March 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nS=ndims(C);\nnumOrderEls=length(order);\n\nif(isempty(order)&&~isempty(C))\n   error('order cannot be empty with a non-empty C.') \nend\n\nif(numOrderEls<S)\n    error('The ordering vector must be >=ndims(C).')\nend\n\nif(any(order>numOrderEls)||any(order<1))\n    error('')\nend\n\nif(isempty(C))\n    CPerm=[];\n    return;\nend\n\nnVals=size(C);\n\nif(numOrderEls>S)\n   nVals=[nVals,ones(1,numOrderEls-S)];\n   S=numOrderEls;\nend\n\ntotalEls=numel(C);\n\ncumProdNew=zeros(S,1);\nnValsNew=zeros(S,1);\ninvPerm=zeros(S,1);\nnewIdx=zeros(S,1);%Initialization\nidx=zeros(S,1);%Initialization\n\niNew=order(1);\nnValsNew(1)=nVals(iNew);\n\ninvPerm(iNew)=1;\ncumProdNew(1)=1;\n\nfor i=2:S\n    iNew=order(i);\n    \n    nValsNew(i)=nVals(iNew);\n    invPerm(iNew)=i;\n\n    cumProdNew(i)=cumProdNew(i-1)*nValsNew(i-1);\nend\n\nCPerm=zeros(nValsNew(:)');\n\nnewLinIdx=0;\nlinIdx=0;\nwhile(1)\n    %Assign the current tuple.\n    CPerm(newLinIdx+1)=C(linIdx+1);\n    \n    %Move on to the next tuple.\n    linIdx=linIdx+1;\n    \n    if(linIdx>=totalEls)\n        break;\n    end\n    \n    %The code below is similar to that in getNextTuple, because we are\n    %updating the tuples for newIdx.\n    curLevel=1;\n    while(1)\n        %Try incrementing the order at this level.\n        idx(curLevel)=idx(curLevel)+1;\n        if(idx(curLevel)<nVals(curLevel))\n            iNew=invPerm(curLevel);\n            newIdx(iNew)=newIdx(iNew)+1;\n            newLinIdx=newLinIdx+cumProdNew(iNew);\n\n            idx(1:(curLevel-1))=0;\n            break;\n        else\n            %If the value is invalid, then just keep ascending and\n            %adjust newLinIdx.\n            iNew=invPerm(curLevel);\n\n            newLinIdx=newLinIdx-newIdx(iNew)*cumProdNew(iNew);\n            newIdx(iNew)=0;\n\n            curLevel=curLevel+1;\n            continue;\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.", "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/permuteMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5567234011329162}}
{"text": "function tests = test_stackSlice(varargin)\n%TEST_STACKSLICE  One-line description here, please.\n%\n%   output = test_stackSlice(input)\n%\n%   Example\n%   test_stackSlice\n%\n%   See also\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-12-02,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\ntests = functiontests(localfunctions);\n\n\nfunction test_sliceX_gray(testCase) %#ok<*DEFNU>\n\nimg = createTestImage;\ndim = stackSize(img);\n\nsliceYZ = stackSlice(img, 1, 5);\nassertEqual(testCase, [dim(3) dim(2)], size(sliceYZ));\n\nsliceYZ = stackSlice(img, 'x', 5);\nassertEqual(testCase, [dim(3) dim(2)], size(sliceYZ));\n\n\nfunction test_sliceY_gray(testCase) %#ok<*DEFNU>\n\nimg = createTestImage;\ndim = stackSize(img);\n\nsliceZX = stackSlice(img, 2, 5);\nassertEqual(testCase, [dim(1) dim(3)], size(sliceZX));\n\nsliceZX = stackSlice(img, 'y', 5);\nassertEqual(testCase, [dim(1) dim(3)], size(sliceZX));\n\n\nfunction test_sliceZ_gray(testCase) %#ok<*DEFNU>\n\nimg = createTestImage;\ndim = stackSize(img);\n\nsliceXY = stackSlice(img, 3, 5);\nassertEqual(testCase, [dim(2) dim(1)], size(sliceXY));\n\nsliceXY = stackSlice(img, 'z', 5);\nassertEqual(testCase, [dim(2) dim(1)], size(sliceXY));\n\n\nfunction img = createTestImage\n\n[x, y, z] = meshgrid(1:10, 1:15, 1:20);\nimg = 5*x + 4*y + 3*z;\n\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/tests/imStacks/test_stackSlice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5566976482846806}}
{"text": "function [output] = F_sigmoid(input_layer)\ninput = input_layer.a;\noutput = sigmoid(input);\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/graph/F_sigmoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5566416427758861}}
{"text": "function [ a, seed ] = r8vec_uniform ( n, b, c, seed )\n\n%*****************************************************************************80\n%\n%% R8VEC_UNIFORM returns a scaled pseudorandom R8VEC.\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 N, the number of entries in the vector.\n%\n%    Input, real B, C, the range of the pseudorandom values.\n%\n%    Input, integer SEED, a seed for the random number generator.\n%\n%    Output, real A(N), the vector of pseudorandom values.\n%\n%    Output, integer SEED, an updated seed for the random number generator.\n%\n  if ( seed == 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8VEC_UNIFORM - Fatal error!\\n' );\n    fprintf ( 1, '  Input SEED = 0!\\n' );\n    error ( 'R8VEC_UNIFORM - Fatal error!' );\n  end\n\n  for i = 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 + 2147483647;\n    end\n\n    a(i) = b + ( c - b ) * seed * 4.656612875E-10;\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/r8vec_uniform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5566204397620136}}
{"text": "function test_failed=test_firwin\n%TEST_FIRWIN  Test the firwin windows\n%\n%  This test script verifies the properties listed in the help of firwin\n  \n  \nallwins = getfield(arg_firwin,'flags','wintype');\n\ntest_failed=0;\n\ndisp(' ===============  TEST_FIRWIN ================');\n\nfor L=[18,19,20,21]\n\n  for cent=0:1\n    if cent==0\n      centtype='wp';\n    else\n      centtype='hp';\n    end;\n    for ii=1:length(allwins);\n      winname=allwins{ii};\n      \n      [g,info]=firwin(winname,L,centtype);\n      \n      res = 1-isevenfunction(fir2long(g,2*L),centtype);\n      [test_failed,fail]=ltfatdiditfail(res,test_failed);\n      \n      s=sprintf(['SYMM %10s %s L: %i %0.5g %s'],winname,centtype,L,res,fail);\n      disp(s);\n      \n      if cent==0\n        res=1-g(1);\n        \n        [test_failed,fail]=ltfatdiditfail(res,test_failed);\n        \n        s=sprintf(['PEAK %10s %s L: %i %0.5g %s'],winname,centtype,L,res,fail);\n        disp(s);\n        \n        \n      end;\n      \n      if mod(L,2)==0 \n        if info.ispu\n          gpu=g+fftshift(g);\n          res=norm(gpu-gpu(1)*ones(L,1));\n          \n          [test_failed,fail]=ltfatdiditfail(res,test_failed);\n          \n          s=sprintf(['PU   %10s %s L: %i %0.5g %s'],winname,centtype,L,res,fail);\n          disp(s);\n          \n        end;\n        \n        if info.issqpu\n          gpu=g.^2+fftshift(g.^2);\n          res=norm(gpu-gpu(1)*ones(L,1));\n          \n          [test_failed,fail]=ltfatdiditfail(res,test_failed);\n          \n          s=sprintf(['SQPU %10s %s L: %i %0.5g %s'],winname,centtype,L,res,fail);\n          disp(s);\n          \n        end;\n      end;      \n    end;\n      \n  end;\n  \nend;\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/testing/test_firwin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721303, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5566112885860749}}
{"text": "function peakmask = getpeaks(w)\n   %GETPEAKS return mask for peak values for a waveform\n   %     PEAKMASK = GETPEAKS(WAVEFORM)\n   %     returns a mask of all maximums in the waveform.\n   %\n   %   Input Arguments\n   %       WAVEFORM: waveform object  (SINGLE WAVEFORM)\n   %\n   %   Output\n   %       PEAKMASK: a mask of all local maximums within the waveform.\n   %       This mask can then be used to reference the peak points in a\n   %       waveform\n   %\n   %   a MASK is a logical array the same size as the waveform's data,\n   %   where the value is TRUE when that data point is a peak, and is zero\n   %   otherwise.\n   %\n   %   in some cases, it may be preferable to get the peakmask for the\n   %   absolute value of the data, that way both highs and lows are marked.\n   %\n   % See also WAVEFORM/HILBERT\n   \n   % AUTHOR: Celso Reyes, Geophysical Institute, Univ. of Alaska Fairbanks\n   % $Date$\n   % $Revision$\n   \n   if ~isscalar(w)\n      error('Waveform:getpeaks:tooManyWaveforms',...\n         'getpeaks can only be used with individual waveforms');\n   end\n   BiggerLeft = [(w.data(1:end-1) >= w.data(2:end)); true];\n   BiggerRight = [true ; (w.data(1:end-1) < w.data(2:end))];\n   peakmask = (BiggerLeft & BiggerRight);\nend", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@waveform/getpeaks.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5566112857755573}}
{"text": "% Example for the algorithms described in \n%\n%       D. Kressner, M. Steinlechner, A. Uschmajew:\n%\t\tLow-rank tensor methods with subspace correction for symmetric eigenvalue problems\n%\t\tSIAM J. Sci. Comput., 36(5):A2346-A2368, 2014.\n%\n% Code to produce Figure 4.4: Three Eigenvalues for Henon-Heiles with \n% with n=28, d=10\n\n%   TTeMPS Toolbox. \n%   Michael Steinlechner, 2013-2016\n%   Questions and contact: michael.steinlechner@epfl.ch\n%   BSD 2-clause license, see LICENSE.txt\n% =========================================================================\nclear all\nclose all\n\nn = 28;\nd = 10;\nA = TTeMPS_op_NN_hermite(n, d);\np = 3;\nr = 1;\n\n% Run block eigenvalue procedure:\n% =========================================================================\n\nif ~exist('hh_3_blk_hermite.mat','file')\n    opts = struct( 'maxiter', 3, ...\n                   'maxrank', 40, ...\n                   'tol', 1e-8, ... \n                   'tolOP', 1e-3, ... \n                   'tolLOBPCG', 1e-6, ... \n                   'maxiterLOBPCG', 500, ... \n                   'verbose', true , ...\n                   'precInner', true);\n\n    rng(11)\n    rr = [1, 1 * ones(1, d-1), 1];\n    [X_blk_hermite, C_blk_hermite, evalue_blk_hermite, residuums_blk_hermite, micro_res_blk_hermite, objective_blk_hermite, t_blk_hermite] = block_eigenvalue( A, p, rr, opts);\n    save('hh_3_blk_hermite', 'X_blk_hermite', 'C_blk_hermite', 'evalue_blk_hermite', 'residuums_blk_hermite', 'micro_res_blk_hermite', 'objective_blk_hermite','t_blk_hermite');\nelse\n    load('hh_3_blk_hermite.mat')\nend\n\n% Run EVAMEn:\n% =========================================================================\n\nif ~exist('hh_3_evamen_hermite.mat','file')\n    opts = struct( 'maxiter', 3, ...\n                   'maxrank', 40, ...\n                   'maxrankRes', 2, ...\n                   'tol', 1e-8, ... \n                   'tolOP', 1e-3, ... \n                   'tolLOBPCG', 1e-6, ... \n                   'maxiterLOBPCG', 500, ... \n                   'verbose', true , ...\n                   'precInner', true);\n    rng(11)\n    rr = [1, 1 * ones(1, d-1), 1];\n    [X_evamen_hermite, C_evamen_hermite, evalue_evamen_hermite, residuums_evamen_hermite, micro_res_evamen_hermite, objective_evamen_hermite, t_evamen_hermite] = amen_eigenvalue( A, 1, p, rr, opts);\n    save('hh_3_evamen_hermite', 'X_evamen_hermite', 'C_evamen_hermite', 'evalue_evamen_hermite', 'residuums_evamen_hermite', 'micro_res_evamen_hermite', 'objective_evamen_hermite','t_evamen_hermite');\nelse\n    load('hh_3_evamen_hermite.mat')\nend\n\n\n% Prepare data for plotting:\n% =========================================================================\n\nevalue_end = repmat(evalue_blk_hermite(:,end), [1,size(evalue_blk_hermite,2)-1]);\nev_blk_hermite = abs(evalue_blk_hermite(:,1:end-1) - evalue_end);\nev_evamen_hermite = abs(evalue_evamen_hermite(:,1:end-1) - evalue_end);\n\n\n% Plot vs. Iterations\n% =========================================================================\nf = figure\nset(0,'defaultlinelinewidth',2)\nsubplot(1,2,1)\n\nsemilogy( sqrt(sum(micro_res_blk_hermite.^2, 1)), '-b' )\nhold on\nsemilogy( sqrt(sum(micro_res_evamen_hermite.^2, 1)), '-k' )\n\nsemilogy( sum(ev_blk_hermite,1), '--b' )\nsemilogy( sum(ev_evamen_hermite,1), '--k' )\n\nres_blk_hermite         = sqrt(sum(micro_res_blk_hermite.^2, 1))\nres_evamen_hermite  = sqrt(sum(micro_res_evamen_hermite.^2, 1))\n\nsemilogy((d-1):(d-1):length(micro_res_blk_hermite),res_blk_hermite(:,(d-1):(d-1):end),'ob')\nsemilogy((d-1):(d-1):length(micro_res_evamen_hermite),res_evamen_hermite(:,(d-1):(d-1):end),'ok')\n\nsemilogy((d-1):(d-1):length(ev_blk_hermite),sum(ev_blk_hermite(:,(d-1):(d-1):end),1),'ob')\nsemilogy((d-1):(d-1):length(ev_evamen_hermite),sum(ev_evamen_hermite(:,(d-1):(d-1):end),1),'ok')\n\nset(gca,'fontsize',20)\nxlabel('Microiterations')\nylabel('Residual and eigenvalue error')  \n\n% Plot vs. Time\n% =========================================================================\n\nsubplot(1,2,2)\nsemilogy( t_blk_hermite, sqrt(sum(micro_res_blk_hermite.^2, 1)), '-b' )\nhold on\nsemilogy( t_evamen_hermite, sqrt(sum(micro_res_evamen_hermite.^2, 1)), '-k' )\n\nsemilogy( t_blk_hermite, sum(ev_blk_hermite,1), '--b' )\nsemilogy( t_evamen_hermite, sum(ev_evamen_hermite,1), '--k' )\n\nsemilogy(t_blk_hermite((d-1):(d-1):end),res_blk_hermite(:,(d-1):(d-1):end),'ob')\nsemilogy(t_evamen_hermite((d-1):(d-1):end),res_evamen_hermite(:,(d-1):(d-1):end),'ok')\n\nsemilogy(t_blk_hermite((d-1):(d-1):end),sum(ev_blk_hermite(:,(d-1):(d-1):end),1),'ob')\nsemilogy(t_evamen_hermite((d-1):(d-1):end),sum(ev_evamen_hermite(:,(d-1):(d-1):end),1),'ok')\n\nsemilogy(t_blk_hermite((d-1):(d-1):end),        res_blk_hermite(:,(d-1):(d-1):end),'ob')\nsemilogy(t_evamen_hermite((d-1):(d-1):end), res_evamen_hermite(:,(d-1):(d-1):end),'ok')\n\nsemilogy(t_blk_hermite((d-1):(d-1):end),        sum(ev_blk_hermite(:,(d-1):(d-1):end),1),'ob')\nsemilogy(t_evamen_hermite((d-1):(d-1):end), sum(ev_evamen_hermite(:,(d-1):(d-1):end),1),'ok')\n\n\nh_leg = legend('Res. err., Block-ALS',... \n       'Res. err. EVAMEn, prec.',...\n       'EV. err., Block-ALS',... \n       'EV. err. EVAMEn, prec.')\nset(gca,'fontsize',20)\nset(h_leg, 'fontsize',16)\nxlabel('Time [s]')\nylabel('Residual and eigenvalue error')  \n\nset(f, 'Position', [0 0 1200 700])\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/examples/ex_henon_3_hermite.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5566112857755573}}
{"text": "function [ n_data, nu, x, fx ] = bessel_in_values ( n_data )\n\n%*****************************************************************************80\n%\n%% BESSEL_IN_VALUES returns some values of the In Bessel function.\n%\n%  Discussion:\n%\n%    The modified Bessel functions In(Z) and Kn(Z) are solutions of\n%    the differential equation\n%\n%      Z^2 W'' + Z * W' - ( Z^2 + N^2 ) * W = 0.\n%\n%    In Mathematica, the function can be evaluated by:\n%\n%      BesselI[n,x]\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    29 September 2004\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Milton Abramowitz and Irene Stegun,\n%    Handbook of Mathematical Functions,\n%    US Department of Commerce, 1964.\n%\n%    Stephen Wolfram,\n%    The Mathematica Book,\n%    Fourth Edition,\n%    Wolfram Media / Cambridge University Press, 1999.\n%\n%  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 NU, the order of the function.\n%\n%    Output, real X, the argument of the function.\n%\n%    Output, real FX, the value of the function.\n%\n  n_max = 28;\n\n  fx_vec = [ ...\n     0.5016687513894678E-02, ...\n     0.1357476697670383E+00, ...\n     0.6889484476987382E+00, ...\n     0.1276466147819164E+01, ...\n     0.2245212440929951E+01, ...\n     0.1750561496662424E+02, ...\n     0.2281518967726004E+04, ...\n     0.3931278522104076E+08, ...\n     0.2216842492433190E-01, ...\n     0.2127399592398527E+00, ...\n     0.1033115016915114E+02, ...\n     0.1758380716610853E+04, ...\n     0.2677764138883941E+21, ...\n     0.2714631559569719E-03, ...\n     0.9825679323131702E-02, ...\n     0.2157974547322546E+01, ...\n     0.7771882864032600E+03, ...\n     0.2278548307911282E+21, ...\n     0.2752948039836874E-09, ...\n     0.3016963879350684E-06, ...\n     0.4580044419176051E-02, ...\n     0.2189170616372337E+02, ...\n     0.1071597159477637E+21, ...\n     0.3966835985819020E-24, ...\n     0.4310560576109548E-18, ...\n     0.5024239357971806E-10, ...\n     0.1250799735644948E-03, ...\n     0.5442008402752998E+19 ];\n\n  nu_vec = [ ...\n     2,  2,  2,  2, ...\n     2,  2,  2,  2, ...\n     3,  3,  3,  3, ...\n     3,  5,  5,  5, ...\n     5,  5, 10, 10, ...\n    10, 10, 10, 20, ...\n    20, 20, 20, 20 ];\n\n  x_vec = [ ...\n      0.2E+00, ...\n      1.0E+00, ...\n      2.0E+00, ...\n      2.5E+00, ...\n      3.0E+00, ...\n      5.0E+00, ...\n     10.0E+00, ...\n     20.0E+00, ...\n      1.0E+00, ...\n      2.0E+00, ...\n      5.0E+00, ...\n     10.0E+00, ...\n     50.0E+00, ...\n      1.0E+00, ...\n      2.0E+00, ...\n      5.0E+00, ...\n     10.0E+00, ...\n     50.0E+00, ...\n      1.0E+00, ...\n      2.0E+00, ...\n      5.0E+00, ...\n     10.0E+00, ...\n     50.0E+00, ...\n      1.0E+00, ...\n      2.0E+00, ...\n      5.0E+00, ...\n     10.0E+00, ...\n     50.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    nu = 0;\n    x = 0.0;\n    fx = 0.0;\n  else\n    nu = nu_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/bessel_in_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5566112811075142}}
{"text": "function value = r4_besi1e ( x )\n\n%*****************************************************************************80\n%\n%% R4_BESI1E: exponentially scaled Bessel function I of order 1 of an R4 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 exponentially scaled Bessel function I\n%    of order 1 of X.\n%\n  persistent ai1cs\n  persistent ai12cs\n  persistent bi1cs\n  persistent ntai1\n  persistent ntai12\n  persistent nti1\n  persistent xmin\n  persistent xsml\n\n  if ( isempty ( nti1 ) )\n\n    ai1cs = [ ...\n     -0.02846744181881479E+00, ...\n     -0.01922953231443221E+00, ...\n     -0.00061151858579437E+00, ...\n     -0.00002069971253350E+00, ...\n      0.00000858561914581E+00, ...\n      0.00000104949824671E+00, ...\n     -0.00000029183389184E+00, ...\n     -0.00000001559378146E+00, ...\n      0.00000001318012367E+00, ...\n     -0.00000000144842341E+00, ...\n     -0.00000000029085122E+00, ...\n      0.00000000012663889E+00, ...\n     -0.00000000001664947E+00, ...\n     -0.00000000000166665E+00, ...\n      0.00000000000124260E+00, ...\n     -0.00000000000027315E+00, ...\n      0.00000000000002023E+00, ...\n      0.00000000000000730E+00, ...\n     -0.00000000000000333E+00, ...\n      0.00000000000000071E+00, ...\n     -0.00000000000000006E+00 ]';\n    ai12cs = [ ...\n      0.02857623501828014E+00, ...\n     -0.00976109749136147E+00, ...\n     -0.00011058893876263E+00, ...\n     -0.00000388256480887E+00, ...\n     -0.00000025122362377E+00, ...\n     -0.00000002631468847E+00, ...\n     -0.00000000383538039E+00, ...\n     -0.00000000055897433E+00, ...\n     -0.00000000001897495E+00, ...\n      0.00000000003252602E+00, ...\n      0.00000000001412580E+00, ...\n      0.00000000000203564E+00, ...\n     -0.00000000000071985E+00, ...\n     -0.00000000000040836E+00, ...\n     -0.00000000000002101E+00, ...\n      0.00000000000004273E+00, ...\n      0.00000000000001041E+00, ...\n     -0.00000000000000382E+00, ...\n     -0.00000000000000186E+00, ...\n      0.00000000000000033E+00, ...\n      0.00000000000000028E+00, ...\n     -0.00000000000000003E+00 ]';\n    bi1cs = [ ...\n     -0.001971713261099859E+00, ...\n      0.40734887667546481E+00, ...\n      0.034838994299959456E+00, ...\n      0.001545394556300123E+00, ...\n      0.000041888521098377E+00, ...\n      0.000000764902676483E+00, ...\n      0.000000010042493924E+00, ...\n      0.000000000099322077E+00, ...\n      0.000000000000766380E+00, ...\n      0.000000000000004741E+00, ...\n      0.000000000000000024E+00 ]';\n\n    nti1 = r4_inits ( bi1cs, 11, 0.1 * r4_mach ( 3 ) );\n    ntai1 = r4_inits ( ai1cs, 21, 0.1 * r4_mach ( 3 ) );\n    ntai12 = r4_inits ( ai12cs, 22, 0.1 * r4_mach ( 3 ) );\n    xmin = 2.0 * r4_mach ( 1 );\n    xsml = sqrt ( 8.0 * r4_mach ( 3 ) );\n\n  end\n\n  y = abs ( x );\n\n  if ( x == 0.0 )\n    value = 0.0;\n  elseif ( y <= xmin )\n    value = 0.0;\n  elseif ( y <= xsml )\n    value = 0.5 * x;\n    value = exp ( - y ) * value;\n  elseif ( y <= 3.0 )\n    value = x * ( 0.875 ...\n      + r4_csevl ( y * y / 4.5 - 1.0, bi1cs, nti1 ) );\n    value = exp ( - y ) * value;\n  elseif ( y <= 8.0 )\n    value = ( 0.375 + r4_csevl ( ( 48.0 / y - 11.0 ) / 5.0, ...\n      ai1cs, ntai1) ) / sqrt ( y );\n    if ( x < 0.0 )\n      value = - value;\n    end\n  else\n    value = ( 0.375 + r4_csevl ( 16.0 / y - 1.0, ai12cs, ntai12 ) ) ...\n      / sqrt ( y );\n    if ( x < 0.0 )\n      value = - value;\n    end\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r4_besi1e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5566015991678974}}
{"text": "function rotError = get_rot_error(R_est,R_gt,d)\n\nnrNodes = size(R_est,1) / d;\nrotError = zeros(nrNodes, 1);\nfor i=1:nrNodes\n    Rdiff = R_gt(blkIndices(i,d),:)' * R_est(blkIndices(i,d),:); \n    rotError(i, 1) = abs( atan2(Rdiff(2, 1), Rdiff(1, 1)) );\nend", "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/lib/get_rot_error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5566015898977087}}
{"text": "% NaN    Not-a-Number.\n%    NaN is the IEEE arithmetic representation for Not-a-Number.\n%    A NaN is obtained as a result of mathematically undefined\n%    operations like 0.0/0.0  and inf-inf.\n% \n%    NaN('double') is the same as NaN with no inputs.\n% \n%    NaN('single') is the single precision representation of NaN.\n% \n%    NaN(N) is an N-by-N matrix of NaNs.\n% \n%    NaN(M,N) or NaN([M,N]) is an M-by-N matrix of NaNs.\n% \n%    NaN(M,N,P,...) or NaN([M,N,P,...]) is an M-by-N-by-P-by-... array of NaNs.\n% \n%    NaN(..., CLASSNAME) is an array of NaNs of class specified by the \n%    string CLASSNAME. CLASSNAME can be either 'single' or 'double'.\n% \n%    NaN(..., 'like', Y) is an array of NaNs with the same data type, sparsity,\n%    and complexity (real or complex) as the single or double precision numeric \n%    variable Y.\n% \n%    Note: The size inputs M, N, and P... should be nonnegative integers. \n%    Negative integers are treated as 0.\n% \n%    See also INF, ISNAN, ISFINITE, ISFLOAT.\n%\n%    Reference page in Doc Center\n%       doc nan\n%\n%    Other functions named nan\n%\n%       codistributed/nan      codistributor2dbc/nan    gpuArray/nan\n%       codistributor1d/nan    distributed/nan          ts/nan\n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/classes/time_series/@ts/nan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.737158174177441, "lm_q1q2_score": 0.5564917533785277}}
{"text": "function [tm,im] = maprect(tr,pr)\n%MAPRECT find the tree-to-rectangle mappings.\n%   [TM,IM] = MAPRECT(TR,PR) returns the tree-to-rectangle \n%   and rectangle-to-tree mappings for a given aabb-tree TR \n%   and a collection of query vertices PI.\n%\n%   The tree-to-item mapping TM is a structure representing\n%   the intersection of the items PI with the tree TR. TM.II \n%   is an M-by-1 array of tree indices and TM.LL is an \n%   M-by-1 cell array of item lists. Specifically, items in \n%   the list TM.LL{JJ} intersect with the node TM.II(JJ).\n%\n%   The item-to-tree mapping IM is a structure representing\n%   the inverse mapping. IM.II is an N-by-1 array of item\n%   indices and IM.LL is an N-by-1 cell array of node lists.\n%   Specifically, nodes in the list IM.LL{JJ} intersect with\n%   the item IM.II(JJ).\n%\n%   See also QUERYSET, MAPVERT, MAKETREE\n\n%   Darren Engwirda : 2017 --\n%   Email           : de2363@columbia.edu\n%   Last updated    : 09/04/2017\n\n%----------------------- call SCANTREE to do the actual work\n    if (nargout == +1)\n       [tm   ] = scantree(tr,pr,@partrect);     \n    else\n       [tm,im] = scantree(tr,pr,@partrect);\n    end\n    \nend\n\nfunction [j1,j2] = partrect(pr,b1,b2)\n%PARTRECT partition points between boxes B1,B2 for SCANTREE.\n\n    j1 = true(size(pr,1),1) ;\n    j2 = true(size(pr,1),1) ;\n\n    nd = size(b1,2) / +2;\n    \n    for ax = +1 : nd\n%--------------- remains TRUE if inside bounds along axis AX\n    j1 = j1 & pr(:,ax+nd*1) ...\n           >= b1(  ax+nd*0) ...\n            & pr(:,ax+nd*0) ...\n           <= b1(  ax+nd*1) ;\n        \n%--------------- remains TRUE if inside bounds along axis AX\n    j2 = j2 & pr(:,ax+nd*1) ...\n           >= b2(  ax+nd*0) ...\n            & pr(:,ax+nd*0) ...\n           <= b2(  ax+nd*1) ;    \n    end\n\nend\n\n\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/GEOM_UTIL/aabb-tree/maprect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5564917403010322}}
{"text": "function [mm2] = cm22mm2(cm2)\n% Convert area from square centimeters to square millimeters.\n% Chad A. Greene 2012\nmm2 = cm2*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/35258-unit-converters/unit_converters/cm22mm2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5564562899353485}}
{"text": "function X = normalize(X,N,normtype,mode)\n%NORMALIZE Normalizes the columns of the factor matrices.\n%\n%   NORMALIZE(X) normalizes the columns of each factor matrix using the\n%   vector 2-norm, absorbing the excess weight into lambda. Also ensures\n%   that lambda is positive.   \n%\n%   NORMALIZE(X,N) absorbs the weights into the Nth factor matrix instead\n%   of lambda. (All the lambda values are 1.)\n%\n%   NORMALIZE(X,0) equally divides the weights across the factor matrices.\n%   (All the lambda values are 1.)\n%\n%   NORMALIZE(X,[]) is equivalent to NORMALIZE(X). \n%\n%   NORMALIZE(X,'sort') is the same as the above except it sorts the\n%   components by lambda value, from greatest to least. \n%\n%   NORMALIZE(X,V,1) normalizes using the vector one norm (sum(abs(x))\n%   rather than the two norm (sqrt(sum(x.^2))), where V can be any of the\n%   second arguments decribed above.\n%\n%   NORMALIZE(X,[],1,I) just normalizes the I-th factor using whatever norm\n%   is specified by the 3rd argument (1 or 2).\n%\n%   See also KTENSOR, ARRANGE, REDISTRIBUTE, TOCELL.\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\n\n%%\nif ~exist('N','var')\n    N = -1;\nend\n\nif isempty(N)\n    N = -1;\nend\n\nif isequal(N,'sort')\n    N = -2;\nend\n\nif ~exist('normtype','var')\n    normtype = 2;\nend\n\nif exist('mode', 'var')\n    for r = 1:length(X.lambda)\n        tmp = norm(X.u{mode}(:,r),normtype);\n        if (tmp > 0)\n            X.u{mode}(:,r) = X.u{mode}(:,r) / tmp;\n        end\n        X.lambda(r) = X.lambda(r) * tmp;\n    end\n    return;\nend\n\n%% Ensure that matrices are normalized\nfor r = 1:length(X.lambda)\n    for n = 1:ndims(X)\n        tmp = norm(X.u{n}(:,r),normtype);\n        if (tmp > 0)            \n            X.u{n}(:,r) = X.u{n}(:,r) / tmp;\n        end\n        X.lambda(r) = X.lambda(r) * tmp;        \n    end\nend\n\n%% Check that all the lambda values are positive\nidx = find(X.lambda < 0);\nX.u{1}(:,idx) = -1 * X.u{1}(:,idx);\nX.lambda(idx) = -1 * X.lambda(idx);\n\n%% Absorb the weight into one factor, if requested\nif (N == 0)\n    D = diag(nthroot(X.lambda,ndims(X)));\n    X.u = cellfun(@(x) x*D, X.u, 'UniformOutput', false);\n    X.lambda = ones(size(X.lambda));\nelseif (N > 0)\n    X.u{N} = X.u{N} * diag(X.lambda);\n    X.lambda = ones(size(X.lambda));\nelseif (N == -2)\n    if ncomponents(X) > 1\n        [~,p] = sort(X.lambda,'descend');\n        X = arrange(X,p);\n    end\nend\n\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/\u5206\u7c7b\u7b97\u6cd5/DEEP-TENSOR-FACTORIZATION-FOR-HYPERSPECTRAL-IMAGE-CLASSIFICATION-master/code/tensor_toolbox_2.6/@ktensor/normalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5564562855354052}}
{"text": "function combo_test36 ( )\n\n%*****************************************************************************80\n%\n%% COMBO_TEST36 tests SETPART_ENUM.\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  fprintf ( 1, ' \\n' );\n  fprintf ( 1, 'COMBO_TEST36\\n' );\n  fprintf ( 1, '  Set partitions:\\n' );\n  fprintf ( 1, ' \\n' );\n  fprintf ( 1, '  SETPART_ENUM enumerates,\\n' );\n  fprintf ( 1, ' \\n' );\n%\n%  Enumerate.\n%\n  for n = 1 : 6\n    npart = setpart_enum ( n );\n    fprintf ( 1, '  %4d  %4d\\n', n, npart );\n  end\n\n  return\nend\n", "meta": {"author": "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_test36.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.5564562831391864}}
{"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,U,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{11} = '    u = [2xn] matrix of inputs';\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\ninput{1} = {'u1','torque acting on link 1 wrt ground'};\ninput{2} = {'u2','torque acting on link 2 wrt ground'};\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,u,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:length(input)\n    fprintf(fid,[input{i}{1} ' = u(' num2str(i) ',:); %%' input{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/doublePendulumForced/writeDoublePendulumDynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5564562776788398}}
{"text": "%compute orientation of tailcentralvector\n\nfunction [data,units]=compute_tailcentralang(trx,n)\n\nlarvae=trx.exp2flies{n};\nnumlarvae=numel(larvae);\ntailcentralang=cell(1,numlarvae);\n\nfor i=1:numlarvae\n    larva=larvae(i);\n    tailcentralang{1,i}=bsxfun(@atan2,trx(larva).ycentral_mm-trx(larva).ytail_mm,trx(larva).xcentral_mm-trx(larva).xtail_mm);\nend\nunits=parseunits('rad');\ndata=tailcentralang;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/larva_compute_perframe_features/compute_tailcentralang.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.6825737214979746, "lm_q1q2_score": 0.5564562618865441}}
{"text": "% Jiao Xianjun (putaoshu@msn.com; putaoshu@gmail.com)\n% generate frequency domain PSS and time domain PSS signal\n% A script of project: https://github.com/JiaoXianjun/rtl-sdr-LTE\n\nfunction [fd_pss, td_pss] = pss_gen\nfd_pss = zeros(128,3);\ntd_pss = zeros(128+9,3);\nfor i=1:3\n    temp=pss(i-1);\n    fd_pss(:,i)=[0 temp(32:end) zeros(1,65) temp(1:31)].';\n    temp_td=idft(fd_pss(:,i))*sqrt(128/62);\n    td_pss(:,i)=[temp_td(end-8:end); temp_td];\nend\n", "meta": {"author": "JiaoXianjun", "repo": "rtl-sdr-LTE", "sha": "037a25f164f17b1a1d82e2eb02285550f50af9b9", "save_path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE", "path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE/rtl-sdr-LTE-037a25f164f17b1a1d82e2eb02285550f50af9b9/matlab/pss_gen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5563674558834507}}
{"text": "function s = addnaka(s)\n%ADDNAKA Add the Nakagami distribution.\n\n%   Copyright 1993-2004 The MathWorks, Inc.\n%   $Revision: 1.1.6.7 $  $Date: 2003/12/11 03:50:49 $\n\nj = length(s) + 1;\ns(j).name = 'Nakagami';\ns(j).code = 'nakagami';\ns(j).pnames = {'mu' 'omega'};\ns(j).pdescription = {'shape' 'scale'};\ns(j).prequired = [false false];\ns(j).fitfunc = @nakafit;\ns(j).likefunc = @nakalike;\ns(j).cdffunc = @nakacdf;\ns(j).pdffunc = @nakapdf;\ns(j).invfunc = @nakainv;\ns(j).statfunc = @nakastat;\ns(j).loginvfunc = [];\ns(j).logcdffunc = [];\ns(j).hasconfbounds = false;\ns(j).censoring = true;\ns(j).paramvec = true;\ns(j).support = [0 Inf];\ns(j).closedbound = [false false];\ns(j).iscontinuous = true;\ns(j).islocscale = false;\ns(j).uselogpp = false;\n\n\n% ==== Nakagami distribution functions ====\n\n% these distribution functions do not yet handle arrays of parameters\n\nfunction y = nakapdf(x, mu, omega)\n%NAKAPDF Nakagami probability density function (pdf).\nmu(mu <= 0) = NaN;\nomega(omega <= 0) = NaN;\n\nx(x<0) = 0;\n% equivalent to y = 2.*x .* gampdf(x.^2, mu, omega./mu), but the version here\n% puts all the x terms into gampdf, so Inf*0, etc. is handled there.\ny = 2.*sqrt(omega./mu).*exp(gammaln(mu+.5) - gammaln(mu)) .* gampdf(x.^2, mu+.5, omega./mu);\n\n\nfunction p = nakacdf(x, mu, omega)\n%NAKACDF Nakagami cumulative distribution function (cdf).\nmu(mu <= 0) = NaN;\nomega(omega <= 0) = NaN;\n\nx(x<0) = 0;\np = gamcdf(x.^2, mu, omega./mu);\n\n\nfunction x = nakainv(p, mu, omega)\n%NAKAINV Inverse of the Nakagami cumulative distribution function (cdf).\nmu(mu <= 0) = NaN;\nomega(omega <= 0) = NaN;\n\nx = sqrt(gaminv(p,mu,omega./mu));\n\n\nfunction r = nakarnd(mu, omega, varargin)\n%NAKARND Random arrays from the Nakagami distribution.\nmu(mu <= 0) = NaN;\nomega(omega <= 0) = NaN;\n\n[err, sizeOut] = statsizechk(2,mu,omega,varargin{:});\nif err > 0\n    error('stats:nakarnd:InconsistentSizes','Size information is inconsistent.');\nend\n\nr = sqrt(gamrnd(mu,omega./mu,sizeOut));\n\n\nfunction [m,v] = nakastat(mu, omega)\n%NAKASTAT Mean and variance for the Nakagami distribution.\nmu(mu <= 0) = NaN;\nomega(omega <= 0) = NaN;\n\ngamratio = exp(gammaln(mu+.5) - gammaln(mu));\nm = gamratio .* sqrt(omega./mu);\nv = omega .* (1 - gamratio.^2 ./ mu);\n\n\nfunction [nlogL,acov] = nakalike(params,data,cens,freq)\n%NAKALIKE Negative log-likelihood for the Nakagami distribution.\nif nargin < 4 || isempty(freq), freq = ones(size(data)); end\nif nargin < 3 || isempty(cens), cens = zeros(size(data)); end\n\nnlogL = naka_nloglf(params, data, cens, freq);\nif nargout > 1\n    acov = mlecov(params, data, 'nloglf',@naka_nloglf, 'cens',cens, 'freq',freq);\nend\n\n\n% ==== Nakagami fitting functions ====\n\nfunction [phat,pci] = nakafit(x,alpha,cens,freq,opts)\n%NAKAFIT Parameter estimates and confidence intervals for Nakagami data.\n\nif nargin < 2 || isempty(alpha), alpha = .05; end\nif nargin < 3 || isempty(cens), cens = zeros(size(x)); end\nif nargin < 4 || isempty(freq), freq = ones(size(x)); end\nif nargin < 5, opts = []; end\n\nif any(x <= 0)\n    error('stats:nakafit:BadData','The data in X must be positive');\nend\n\nphat = gamfit(x.^2,alpha,cens,freq,opts);\nphat(2) = phat(1).*phat(2); % (a,b) -> (mu,omega)\nif nargout > 1\n    acov = mlecov(phat, x, 'nloglf',@naka_nloglf, 'cens',cens, 'freq',freq);\n    probs = [alpha/2; 1-alpha/2];\n    se = sqrt(diag(acov))';\n    pci = norminv(repmat(probs,1,numel(phat)), [phat; phat], [se; se]);\n    % CI on the log scale for omega?\nend\n\n\nfunction [nll,ngrad] = naka_nloglf(parms, x, cens, freq)\n%NAKA_NLOGLF Objective function for Nakagami maximum likelihood.\n\n% do all the calculations in terms of the gamma dist'n\na = parms(1);\nb = parms(2)./parms(1); % (mu,omega) -> (a,b)\nloggama = gammaln(a);\nlogb = log(b);\n\nxsq = x.^2;\nz = xsq ./ b;\nlogz = log(z);\nL = (a-1).*logz - z - loggama - logb + log(2.*x);\nncen = sum(freq.*cens);\nif ncen > 0\n    cen = (cens == 1);\n    zcen = z(cen);\n    if nargout == 1\n        Scen = gammainc(zcen,a,'upper');\n    else\n        [dScen,Scen] = dgammainc(zcen,a,'upper');\n    end\n    L(cen) = log(Scen);\nend\nnll = -sum(freq .* L);\n\nif nargout > 1\n    dL1 = logz - psi(a);\n    dL2 = (z - a)./b;\n    if ncen > 0\n        dL1(cen) = dScen ./ Scen;\n        dL2(cen) = exp(a.*logz(cen) - logb - zcen - loggama) ./ Scen;\n    end\n    ngrad = -[sum(freq .* dL1) sum(freq .* dL2)];\n\n    % transform back to Nakagami parameters\n    ngrad = ngrad * [1 0; -b./a 1./a]; % (a,b) -> (mu,omega)\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/SpatialLayout_shrink/spatiallayoutcode/GeometricContext/geomContext_src_07_02_08/src/tools/weightedstats/private/addnaka.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5563674491070475}}
{"text": "function g = grad(SO3F,varargin)\n% right-sided gradient of an SO3Fun\n%\n% Syntax\n%   G = SO3F.grad % compute the gradient\n%   g = SO3F.grad(rot) % evaluate the gradient in rot\n%\n%   % go 5 degree in direction of the gradient\n%   ori_new = exp(rot,5*degree*normalize(g)) \n%\n% Input\n%  SO3F - @SO3FunCBF\n%  rot  - @rotation / @orientation\n%\n% Output\n%  G - @SO3VectorField\n%  g - @vector3d\n%\n% Description\n% general formula:\n%\n% $$s(g1_i) = sum_j c_j DRK(<g h_j,r_j>) g h_j x r_j $$\n%\n\n\n% fallback to generic method\nif check_option(varargin,'check') || nargin == 1 || ~isa(varargin{1},'rotation')\n  g = grad@SO3Fun(SO3F,varargin{:});\n  return\nend\n\nori = varargin{1};\n\n% symmetrise - only crystal symmetry\n[h,l] = symmetrise(SO3F.h.normalize,'unique');\nr = repelem(SO3F.r.normalize,l);\nw = repelem(SO3F.weights./l,l);\n\ng = vector3d.zeros(size(ori));\nfor i = 1:length(h)\n  g = g + w(i) * SO3F.psi.grad(dot(ori*h(i),r(i),'noSymmetry'),'polynomial') .* ...\n      cross(h(i),inv(ori) * r(i));\nend\nend\n\nfunction test\n\ncs = crystalSymmetry('1');\nodf = fibreODF(Miller(0,0,1,cs),vector3d.Z);\nomega = linspace(-20,20)*degree;\nomega = 15 *degree;\nref = orientation.byAxisAngle(vector3d(1,0,10),omega,cs)\n\n\ng1 = odf.grad(ref)\ng2 = odf.grad(ref,'check','delta',0.05*degree)\n  \nplot(omega./degree,[g1.x,g2.x])\n\nomega2 = linspace(-5,5)*degree;\nori1 = ref * rotation.byAxisAngle(g1,omega2);\nori2 = ref * rotation.byAxisAngle(g2,omega2);\nori3 = ref * rotation.byAxisAngle(normalize(g1+g2),omega2);\n%ori4 = ref * rotation.byAxisAngle(normalize(g1-g2),'angle',omega2);\nori4 = ref * rotation.byAxisAngle(vector3d(-1,2,0),omega2);\n\nplot(omega2./degree,[odf.eval(ori1(:)),odf.eval(ori2(:)),odf.eval(ori3(:)),odf.eval(ori4(:))])\n\n\n\nend\n\nfunction test2\n\n  cs = crystalSymmetry('321');\n  odf = fibreODF(Miller(1,2,3,cs),vector3d(-1,3,2));\n  \n  ref = orientation.rand(1000,cs)\n  \n  g1 = odf.grad(ref)\n  g2 = odf.grad(ref,'check','delta',0.05*degree)\n  \n  hist(norm(g1-g2)./degree)\n  \n  ref = orientation.id(cs) * cs(5);\n  \n  f = S2FunHarmonic.quadrature(@(r) ...\n    odf.eval(rotation.byAxisAngle(r,5*degree)*ref));\n  \n  plot(f,'lower')\n  \n  annotate(odf.grad(ref))\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3FunCBF/grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5563674473173191}}
{"text": "function [EEG, globalTrendOut] = removeGlobalTrend(EEG, globalTrendIn) \n% Perform detrending or high pass filtering to remove low frequency\n%\n% Usage:\n%   EEG = removeTrend(EEG)\n%   [EEG, detrendOut] = removeTrend(EEG, detrendIn)\n%\n% Input:\n%   EEG               Structure that requires .data and .srate fields \n%   detrendIn         Input structure with fields described below\n% \n% Structure parameters (detrendIn):\n%   detrendChannels   Vector of channels to detrend or filter \n%                     (default is all channels)\n%   detrendType       One of the strings 'high pass', 'linear', or 'none' \n%                     indicating type of detrending (default is'linear')\n%   detrendCutoff     Detrend or high pass cutoff (default is 1 Hz)\n%   detrendStepSize   Seconds for detrend window slide (default is 0.02 s)\n%\n% Output:\n%   EEG               Revised EEG structure channels detrended or filtered\n%   detrendOut        Structure with the following items described below:\n% \n% Structure parameters (detrendOut):\n%   detrendChannels   Vector of detrended or filtered channels \n%   detrendType       Type of detrending or filtering\n%   detrendCutoff     High pass cutoff or detrend window (default is 1 Hz)\n%   detrendStepSize   Seconds for detrend window slide (default is 0.02 s)\n%   detrendCommand    String version of detrending command\n%\n% Implementation notes:\n%   1) High pass filtering is done with EEGLAB pop_eegfiltnew FIR filter\n%   2) Detrending is done with the chronux_2 runline command\n%   3) The EEG.data array will be converted to double regardless of type\n%\n%% Check the parameters\nif nargin < 1 || ~isstruct(EEG)\n    error('removeGlobalTrend:NotEnoughArguments', 'first argument must be a structure');\nelseif nargin < 2 || ~exist('globalTrendIn', 'var') || isempty(globalTrendIn)\n    globalTrendIn = struct();\nend\nif ~isstruct(globalTrendIn)\n    error('removeGlobalTrend:NoData', 'second argument must be a structure')\nend\n\ndefaults = getPrepDefaults(EEG, 'globaltrend');\nglobalTrendOut = struct('globalTrendChannels', [], 'doLocal', [], ...\n    'localCutoff', [], 'localStepSize', [], 'linearFit', [], ...\n     'channelCorrelations', []);\n[globalTrendOut, errors] = checkPrepDefaults(globalTrendIn, globalTrendOut, defaults);\nif ~isempty(errors)\n    error('removeGlobalTrend:BadParameters', ['|' sprintf('%s|', errors{:})]);\nend\n%% Detrend the data either using high pass or linear detrending\nif globalTrendOut.doLocal\n    params = struct('detrendChannels', globalTrendOut.globalTrendChannels, ...\n                    'detrendType', 'linear', ...\n                    'detrendCutoff', globalTrendOut.localCutoff, ...\n                    'detrendStepSize', globalTrendOut.localStepSize);\n                \n    [EEG, trend] = removeTrend(EEG, params);\n    globalTrendOut.localTrend = trend;\nend\n\nchannels = 1:size(EEG.data, 1);\nglobalTrendOut.globalTrendChannels = channels;\nt = 0:(size(EEG.data, 2) - 1);\nt = t/EEG.srate;\ndata = EEG.data(channels, :);\nmyPval = zeros(size(data, 1), 2);\nmyCorr = zeros(size(data, 1), 1);\nparfor k = 1:size(data, 1)\n  myPval(k, :) = polyfit(t, data(k, :), 1);\n  myCorr(k) = corr(t', (data(k, :))');\n  data(k, :) = data(k, :) - polyval(myPval(k, :), t);\nend\nglobalTrendOut.linearFit = myPval;\nglobalTrendOut.channelCorrelations = myCorr;\nEEG.data(channels, :) = data;", "meta": {"author": "VisLab", "repo": "EEG-Clean-Tools", "sha": "9ac9ea0c21d44b57f9e9f93b62ca727c7b75c73e", "save_path": "github-repos/MATLAB/VisLab-EEG-Clean-Tools", "path": "github-repos/MATLAB/VisLab-EEG-Clean-Tools/EEG-Clean-Tools-9ac9ea0c21d44b57f9e9f93b62ca727c7b75c73e/PrepPipeline/utilities/removeGlobalTrend.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5563674441203725}}
{"text": "function P = putcolor11(A11, sizeP)\n%------------------------------------------------------------------------------\n%\n% Gridfunction A11 is upsampled.\n%\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw <Paul.de.Zeeuw@cwi.nl>  http://homepages.cwi.nl/~pauldz/\n% Last Revision: June 6, 1999.\n% (c) 1999-2002 Stichting CWI, Amsterdam\n%------------------------------------------------------------------------------\n[n, m] = size(A11);\nif nargin == 2\n  nP = sizeP(1);\n  mP = sizeP(2);\n  if nP < 2*n\n    error(' putcolor11 - 1st dimension of P too small ')\n  end\n  if mP < 2*m\n    error(' putcolor11 - 2nd dimension of P too small ')\n  end\nelseif nargin == 1\n  nP = 2*n+1;\n  mP = 2*m+1;\nelse\n  error(' putcolor11 - wrong number of arguments ')\nend\nP=reshape(linspace(0,0,nP*mP),nP,mP);\nP(2:2:nP, 2:2:mP)=A11;\n%------------------------------------------------------------------------------\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/putcolor11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.69925440852404, "lm_q1q2_score": 0.5563674273706191}}
{"text": "function [annotation, img] = LMimpad(annotation, img, PADSIZE, PADVAL)\n% [annotation, img] = LMimpad(annotation, img, PADSIZE, PADVAL)\n%\n% [annotation, img] = LMimpad(annotation, img, [256 256], 0)\n% PADSIZE = nrows x ncols (final image size)\n% PADVAL = value for the border\n\n[nrows, ncols, cols]=size(img);\n\nif PADSIZE(1)<nrows || PADSIZE(2)<ncols\n    error('ERROR: image is larger than target size. Use LMimcrop instead.')\nend\n\nDy = fix((PADSIZE(1)-nrows)/2);\nDx = fix((PADSIZE(2)-ncols)/2);\n\n\nimg = [repmat(PADVAL, [PADSIZE(1) Dx cols]) ...\n    [repmat(PADVAL, [Dy ncols cols]); img; repmat(PADVAL, [PADSIZE(1)-nrows-Dy ncols cols])] ...\n    repmat(PADVAL, [PADSIZE(1) PADSIZE(2)-ncols-Dx cols])];\n\n% Change the polygon coordinates\nif isfield(annotation, 'object')\n    Nobjects = length(annotation.object); n=0;\n    for i = 1:Nobjects\n        [x,y] = getLMpolygon(annotation.object(i).polygon);\n        x = round(x + Dx);\n        y = round(y + Dy);\n        annotation.object(i).polygon = setLMpolygon(x,y);\n        \n%         Npoints = length(annotation.object(i).polygon.pt);\n%         for j = 1:Npoints\n%             x=str2num(annotation.object(i).polygon.pt(j).x);\n%             y=str2num(annotation.object(i).polygon.pt(j).y);\n% \n%             x = round(x + Dx);\n%             y = round(y + Dy);\n% \n%             annotation.object(i).polygon.pt(j).x = num2str(x);\n%             annotation.object(i).polygon.pt(j).y = num2str(y);\n%         end\n    end\nend \n", "meta": {"author": "CSAILVision", "repo": "LabelMeToolbox", "sha": "b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2", "save_path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox", "path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox/LabelMeToolbox-b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2/imagemanipulation/LMimpad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5563119013021134}}
{"text": "function x = nonzeros(a)\n%NONZEROS     Implements  nonzeros(a)  for sparse interval matrix\n%\n%   x = nonzeros(a)\n%\n%Functionality as in Matlab.\n%\n\n% written  08/09/02     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 08/25/07     S.M. Rump  huge indices for sparse matrices\n% modified 02/18/08     S.M. Rump  no column vector output for ND arrays\n% modified 10/18/08     S.M. Rump  huge arrays\n% modified 05/31/09     S.M. Rump  multiple arrays\n% modified 10/03/12     S.M. Rump  spones for ND-arrays\n% modified 11/13/12     S.M. Rump  cure Matlab 7.0 bug\n%\n\n  if a.complex\n    if isequal(a.rad,0)\n      x = cintval(nonzeros(a.mid));\n    else\n      [m,n] = size(a.mid);          % n is product of remaining indices for multiple arrays\n      if length(n)>1                % cure bug in Matlab 7.0 (R14)\n        a.mid = reshape(a.mid,m,n);   % make sure dimension fits with sparse(...)\n        a.rad = reshape(a.rad,m,n);   % a.rad cannot be 0\n      end\n      [I,J] = find(spones(a.mid)+spones(a.rad));    % correct index set\n      xmid = complex( real(nonzeros(real(a.mid)+sparse(I,J,sqrt(-1),m,n))) , ...\n                      real(nonzeros(imag(a.mid)+sparse(I,J,sqrt(-1),m,n))) );\n      xrad = real( real(nonzeros(a.rad+sparse(I,J,sqrt(-1),m,n))) );\n      x = intval(xmid,xrad,'midrad');\n      if size(x.mid,1)==1\n        x.mid = x.mid.';\n        x.rad = x.rad';\n      end\n    end\n  else\n    [m,n] = size(a.inf);\n    if prod(size(a.inf))<2^31       % not huge\n      if issparse(a.inf)\n        x = nonzeros(a.inf(:)+sqrt(-1)*a.sup(:));\n      else\n        x = nonzeros(complex(a.inf(:),a.sup(:)));\n      end\n      x = intval(real(x),imag(x),'infsup');\n      return\n      I = find(spones(a.inf)+spones(a.sup));\n      x = intval(squeeze(a.inf(I)),squeeze(a.sup(I)),'infsup');\n      sizexinf = size(x.inf);\n      if ( length(sizexinf)<3) & ( size(x.inf,1)==1 )\n        x.inf = x.inf';\n        x.sup = x.sup';\n      end\n    else                            % huge array\n      [I,J,asup] = find(a.sup);\n      x = nonzeros(a.inf + sparse(I,J,complex(0,asup),m,n));\n      x = intval(real(x),imag(x),'infsup');\n    end\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/nonzeros.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5563118962063063}}
{"text": "function ci =  cusum(cat)\n    % This function calculates the CUMSUm function (Page 1954).\n    %\n\n    report_this_filefun(mfilename('fullpath'));\n\n    [existFlag,figNumber]=figure_exists('CUSUM',1); %find figure with name 'CUSUM', and do not pop to foreground\n\n    if existFlag\n        cfig = figNumber;\n    else\n        cfig=figure_w_normalized_uicontrolunits(...                  %build figure for plot\n            'Units','normalized','NumberTitle','off',...\n            'Name','CUSUM',...\n            'MenuBar','none',...\n            'visible','off',...\n            'pos',[ 0.300  0.3 0.4 0.6]);\n        ho=false;\n        \n        matdraw\n    end   % if fig exist\n\n\n    m  = cat(:,6);\n    me = mean(m);\n    i = (1:1:length(m));\n    ci = cumsum(m)' - i.*me;\n\n    figure_w_normalized_uicontrolunits(cfig)\n    delete(gca);delete(gca);\n    plot(cat(:,3),ci,'o')\n    %plot(i,ci,'o')\n    set(gca,'visible','on','FontSize',10,'FontWeight','normal',...\n        'FontWeight','normal','LineWidth',1.0,...\n        'Box','on')\n    xlabel('Time [yrs]')\n    ylabel('CUSUM [yrs]')\n    grid\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/cusum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.556311891110499}}
{"text": "function boolVal=isImag(x)\n%%ISIMAG Returns true if x is a purely imaginary vector or matrix. That\n%        is, it is complex and all real elements are exactly zero.\n%\n%INPUT: x A scalar or matrix. This must be of a numeric type; that is, not\n%         a cell array, a string, etc.\n%\n%OUTPUTS: boolVal This is true is x is a complex matrix (isreal is false)\n%                 and all real components are zero.\n%\n%December 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(isreal(x))\n   boolVal=false;\n   return;\nend\n\nif(all(real(x(:))==0))\n    boolVal=true;\nelse\n    boolVal=false;\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Misc/isImag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.5563118792872555}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% function mBlock= PolarToRec(mRadialSlice,cubeSide,cPyramid)\n%% Generates the XYZ coordiante of Polar Grid in Cartesian Grid\n%%Input:   mRadialSlice: 3-d Radial slcie matrix\n%%        cubeSide: order of block matrix in 3-d to be assembled\n%%        cPyramid: cell containing one of 3 pyramid information\n%%Output: \n%%        mBlock: block matrix in 3-d to be assembled\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction mBlock= PolarToRec(mRadialIdx,mRadial,cubeSide,pyramid,F)\nmBlock=zeros(cubeSide,cubeSide,cubeSide); \nfor j=mRadialIdx(3,1):mRadialIdx(3,2)\n  for i=mRadialIdx(1,1):mRadialIdx(1,2)\n    for k=mRadialIdx(2,1):mRadialIdx(2,2)\n      mBlock(pyramid.X(i,k,j),pyramid.Y(i,k,j),pyramid.Z(i,k,j))=...\n       +mRadial(i-mRadialIdx(1,1)+1, k-mRadialIdx(2,1)+1, j-mRadialIdx(3,1)+1);\n    end\n  end\nend    \n\n% FToggle=F==0;\n% F=F+FToggle;\n%   mBlock=mBlock./F;\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/Shearlet/3DBP/PolarToRec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5563118729616606}}
{"text": "function A_sparse = build_sparse ( )\n\n%*****************************************************************************80\n%\n%% BUILD_SPARSE demonstrates how a sparse matrix can be assembled in parallel.\n%\n%  Discussion:\n%\n%    Actually, what this script demonstrates is how components of the sparse\n%    matrix can be evaluated in parallel.  To create the final sparse matrix\n%    data structure requires that the \"sparse()\" command itself be called on\n%    a single processor.\n%\n%    Thus, this script tries to take advantage of parallel processing, assuming\n%    that the evaluation of matrix entries is expensive, compared to the minor\n%    cost of collecting the entries from each processor to form the final matrix.\n%\n%    We want to construct a rectangular sparse matrix.  This matrix can be \n%    thought of as a diagonal block matrix, with each diagonal block\n%    being of arbitrary size and shape.\n%\n%    This problem was posed by Vitor Nunes, 18 August 2011.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    29 August 2011\n%\n%  Author:\n%\n%    Gene Cliff\n%\n%  Parameters:\n%\n%    Output, real sparse A_sparse(*,*), the sparse matrix.\n%\n%  Local parameters:\n%\n%    Local, real A_kb(*,*), used to store one block of the matrix.\n%\n%    Local, integer i_blk(N_blk), the global row index just before each \n%    block begins.\n%\n%    Local, cell array II, the global row indices for the entries\n%    in each block.\n%\n%    Local, integer j_blk(N_blk), the global column index just before \n%    each block begins.\n%\n%    Local, cell array JJ(N_blk,1), the global column indices for the entries\n%    in each block.\n%\n%    Local, integer N_blk, the number of block matrices.\n%\n%    Local, integer row_blks(N_blk), the row dimension of each block.\n%\n%    Local, integer col_blks(N_blk), the column dimension of each block.\n%\n%    Local, cell array VV, the values of the entries in each block.\n%\n\n%\n%% Set data that defines the arrangement of blocks.\n%\n%  The row dimension of the global matrix is the sum of row_blks,\n%  and the column dimension is the sum of col_blks.  In this\n%  case, our matrix has dimensions 44 by 41, and 359 nonzero entries.\n%\n  N_blk = 5;\n  row_blks = [ 4;  7;  9; 10; 14];\n  col_blks = [ 8; 10;  5; 10;  8];\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Global matrix dimension is M = %d, N = %d\\n', ...\n    sum ( row_blks ), sum ( col_blks ) );\n% \n%% Initialization.\n%\n  i_blk = cumsum ( row_blks(1:N_blk-1) );\n  j_blk = cumsum ( col_blks(1:N_blk-1) );\n  i_blk = [ 0; i_blk ];\n  j_blk = [ 0; j_blk ];\n% \n%  The cell arrays II, JJ, and VV will contain the I, J and value\n%  information for the entries in each block.\n%\n  II = cell ( N_blk, 1);\n  JJ = cell ( N_blk, 1);\n  VV = cell ( N_blk, 1);\n%\n%% Loop over the sub-blocks.\n%\n  parfor k_blk = 1 : N_blk\n% \n%  Here, the user would fill in the numeric values of the blocks\n%  in a way that depended on the problem that was being set up.\n%\n%  For this demonstration, CREATE_BLOCK simply assigns arbitrary\n%  values to the entries in the block.  In an actual problem, we\n%  assume that the evaluation of these entries would be an expensive\n%  process, so that parallel execution will result in a substantial\n%  speedup.\n%\n    A_kb = create_block ( k_blk, row_blks(k_blk), col_blks(k_blk) ); \n        \n    i_row = 1 : row_blks(k_blk);\n%\n%  I_BLK and J_BLK tell us how far to shift the local indices to get \n%  the global row and column indices II and JJ.\n%\n    n_els = row_blks(k_blk) * col_blks(k_blk);\n\n    II{k_blk}(:,1) = i_blk(k_blk) ...\n      + reshape ( repmat ( i_row(:), 1, col_blks(k_blk) ), n_els, 1 );\n\n    JJ{k_blk}(:, 1) = j_blk(k_blk) ...\n      + reshape ( repmat ( 1:col_blks(k_blk), row_blks(k_blk), 1 ), n_els, 1 );\n\n    VV{k_blk}(:, 1) = reshape ( A_kb, n_els, 1 );             \n\n  end\n%\n%% Now have the SPARSE command assemble the sparse matrix from the\n%  data in the cell arrays.  This command does NOT execute in parallel.\n%\n  A_sparse = sparse ( cell2mat ( II ), cell2mat ( JJ ), cell2mat ( VV ), ...\n    sum ( row_blks ), sum ( col_blks ) );  \n\n  return\nend\n", "meta": {"author": "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_parfor/sparse_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5563116493433797}}
{"text": "%Sensor Refs=[use (0,1), val, obs noise std, ini std]\n%u is assumed to be a random constant (with infinite initial variance)\nfunction [u, ximu, Pimu, Pu, Pux]=selfcalib1(imu_data, Aimu, Qimu, Cimu, Rimu, PimuInv, M, sensor_ref)\n\nDBG=0;  %Debug\n\nnu=size(M,2); %# of kinematic variables\nns=size(M,1); %# of sensors\nnimu=size(Aimu,1);    %total # of imu states\n\nif (isempty(sensor_ref)) %not a compulsory argument\n    sensor_ref=zeros(size(M,2),4);\nend\n\n%System model (augment with kv)\nA=diagmat_v000(Aimu, eye(nu),[]);\nQ=diagmat_v000(Qimu, zeros(nu), []);\nC=[M Cimu];\nR=Rimu;\nPinv=diagmat_v000(PimuInv, zeros(nu), []);\n\n%External body acc/rot rate observations\nnext=0;\nCext=[];\nRext=[];\nyext=[];\nfor in=1:nu\n    if (sensor_ref(in,1)==1)     %there is an external obs\n        next=next+1;\n        Cext=[Cext;zeros(1,size(A,1))];\n        Cext(end,in)=1;\n        Rext=diagmat_v000(sensor_ref(in,3)^2,Rext,[]);\n        yext=[yext;sensor_ref(in,2)];\n        if (sensor_ref(in,4)~=0)    %external obs have random bias\n            A=diagmat_v000(1, A, []);\n            Q=diagmat_v000(0, Q, []);\n            Pinv=diagmat_v000(1/sensor_ref(in,4)^2, Pinv, []);\n            C=[C zeros(ns,1)];\n            Cext=[Cext zeros(next,1)];\n            Cext(end,end)=1;\n        end\n    end\nend\nnst=size(A,1);\n\n%%%%% Start the estimation routine\n%%Sensor outputs\n%%For the first sensor data use the innovation form (Pinv is probably singular)\ny=imu_data(:,1);\nRinv=inv(R);\nP=inv(Pinv+C'*Rinv*C);\nxest=P*(C'*Rinv*y);\n%%External obs\nif (next>0)\n    K=P*Cext'*inv(Cext*P*Cext'+Rext);\n    xest=xest+K*(yext-Cext*xest);\n    P=(eye(nst)-K*Cext)*P*(eye(nst)-K*Cext)'+K*Rext*K';\nend\n\n\nif (DBG)\n    ndat=size(imu_data,2);\n    debmn=zeros(nu,ndat);\n    debop=zeros(size(A,1),ndat);\n    \n    WLS=lsmat_v001(M,R,0);\n    mean_dat=WLS*y;\n    debmn(:,1)=mean_dat;\n    debop(:,1)=xest;\nend\n\n%For the rest use standard KF\nfor in=2:size(imu_data,2) \n    %%%prediction\n    xest=A*xest;\n    P=A*P*A'+Q;\n    \n    %%%filter\n    %%Sensor data\n    y=imu_data(:,in);\n    K=P*C'*inv(C*P*C'+R);\n    %K(1:nimu,:)=0;\n    xest=xest+K*(y-C*xest);\n    P=(eye(nst)-K*C)*P*(eye(nst)-K*C)'+K*R*K';\n    %%External obs\n    if (next>0)\n        K=P*Cext'*inv(Cext*P*Cext'+Rext);\n        xest=xest+K*(yext-Cext*xest);\n        P=(eye(nst)-K*Cext)*P*(eye(nst)-K*Cext)'+K*Rext*K';\n    end\n    \n    if (DBG)\n        mean_dat=((in-1)*mean_dat+(WLS*y))/in;\n        debmn(:,in)=mean_dat;\n        debop(:,in)=xest;\n    end\nend\n\n%Outputs (combine deterministic and stochastic results)\nximu=xest(nu+1:nu+nimu,1);\nPimu=P(nu+1:nu+nimu,nu+1:nu+nimu);\nu=xest(1:nu,:);\nPu=P(1:nu,1:nu);\nPux=P(1:nu,nu+1:nu+nimu);\n\n\nif (DBG)\n    in=1;\n    figure;\n    plot(imu_data(in,:))\n    hold on;\n    plot(debmn(in,:),'r')\n    plot(debop(in,:),'g')\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/initialization/selfcalib1_v001.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5562185527707667}}
{"text": "function [csd,Hz] = spm_ccf2csd(ccf,Hz)\n% Converts cross covariance function to cross spectral density\n% FORMAT [csd,Hz] = spm_ccf2csd(ccf,Hz)\n%\n% ccf  (N,:,:)          - cross covariance functions\n% Hz   (n x 1)          - vector of frequencies (Hz)\n%\n% csd  (n,:,:)          - cross spectral density (cf, mar.P)\n%\n% See also: \n%  spm_ccf2csd.m, spm_ccf2mar, spm_csd2ccf.m, spm_csd2mar.m, spm_mar2csd.m,\n%  spm_csd2coh.m and spm_Q\n%\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_ccf2csd.m 5895 2014-02-26 14:28:23Z karl $\n \n% unpack cells\n%--------------------------------------------------------------------------\nif iscell(ccf)\n    for i = 1:length(ccf)\n       csd{i}    = spm_ccf2csd(ccf{i},Hz);\n    end\n    return\nend\n \n% unpack time bins (for time-frequency responses)\n%--------------------------------------------------------------------------\nif ndims(ccf) == 4\n    for i = 1:size(ccf,1)\n       csd(i,:,:,:) = spm_ccf2csd(squeeze(ccf(i,:,:,:)),Hz);\n    end\n    return\nend\n\n% Frequencies\n%--------------------------------------------------------------------------\nds    = Hz(2) - Hz(1);\ngi    = ceil(Hz/ds) + 1;\nN     = Hz(end);\n\n% Fourier transform cross-spectral density\n%==========================================================================\nfor i = 1:size(ccf,2)\n    if ismatrix(ccf)\n        g          = fft(ccf(:,i));\n        csd(:,i)   = g(gi)/N/ds;\n    else\n        for j = 1:size(ccf,3)\n            g          = fft(ccf(:,i));\n            csd(:,i,j) = g(gi)/N/ds;\n        end\n    end\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/toolbox/spectral/spm_ccf2csd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.5562185437127538}}
{"text": "function CNet(Net)\n\nformat compact\nformat long e\ntheta = linspace(0,2*pi,length(Net)+1);\nxy = zeros(length(Net)+1,2);\nx = cos(theta);\ny = sin(theta);\nxy(1:length(Net)+1,1) = x(1:length(Net)+1);\nxy(1:length(Net)+1,2) = y(1:length(Net)+1);\nfigure, gplot(Net,xy,'.-');\nset(gcf, 'Color', [1 1 1]);\naxis('equal');\nxlim([-1.1 1.1]);\nylim([-1.1 1.1]);\naxis 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/11947-b-a-scale-free-network-generation-and-visualization/CNet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5562002353216778}}
{"text": "%+========================================================================+\n%|                                                                        |\n%|            This script uses 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    \u00a0\u00a0\u00a0\u00a0         |\n%|                                                                        |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it.                                                      |\n%|________________________________________________________________________|\n%|   '&`   |                                                              |\n%|    #    |   FILE       : nrtHmxLowrank.m                               |\n%|    #    |   VERSION    : 0.50                                          |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |\n%|  ( # )  |   CREATION   : 25.11.2018                                    |\n%|  / 0 \\  |   LAST MODIF :                                               |\n%| ( === ) |   SYNOPSIS   : Compare compressor with total pivoting        |\n%|  `---'  |                                                              |\n%+========================================================================+\n\nclear all\nclose all\nclc\n\n% Gypsilab path\nrun('../../addpathGypsilab.m')\n\n% Dimensions\nNx  = 100;\nNy  = 101;\nrk  = 10;\ntol = 1e-3;\n\n% Compress zeros\nM     = zeros(Nx,Ny);\n[A,B] = hmxACA(M,tol);\nnorm(A*B,'inf')\n\n% Compress ones\nM     = ones(Nx,Ny);\n[A,B] = hmxACA(M,tol);\nnorm(A*B-M,'inf')/norm(M,'inf')\n\n% Compress eye \nM          = eye(Nx,Ny);\n[~,~,flag] = hmxACA(M,tol);\nflag\n\n% Compress circular permutation for eye\nM = circshift(eye(Nx,Ny),3,2);\n[~,~,flag] = hmxACA(M,tol);\nflag\n\n% Compress 1-eye \nM          = 1-eye(Nx,Ny);\n[~,~,flag] = hmxACA(M,tol);\nflag\n\n% Compress random\nM     = rand(Nx,rk) * rand(rk,Ny);\n[A,B] = hmxACA(M,tol);\nnorm(A*B-M,'inf')/norm(M,'inf')\n\n% Compress random complex\nM     = (-1+2*rand(Nx,rk)+1i*(-1+2*rand(Nx,rk))) * (rand(rk,Ny) + 1i*rand(rk,Ny));\n[A,B] = hmxACA(M,tol);\nnorm(A*B-M,'inf')/norm(M,'inf')\n\n% Compress 1x2 block with zeros\nM     = rand(Nx,rk) * rand(rk,Ny);\nZ     = zeros(Nx,10);\nM     = [M Z];\n[A,B] = hmxACA(M,tol);\nnorm(A*B-M,'inf')/norm(M,'inf')\n\n% Compress 2x1 block with zeros\nM     = rand(Nx,rk) * rand(rk,Ny);\nZ     = zeros(10,Ny);\nM     = [M ; Z];\n[A,B] = hmxACA(M,tol);\nnorm(A*B-M,'inf')/norm(M,'inf')\n\n% Compress 2x2 block random\nM     = rand(Nx,rk) * rand(rk,Ny);\nZ     = zeros(Nx,Ny);\nM     = [M Z ; Z M];\n[A,B] = hmxACA(M,tol);\nnorm(A*B-M,'inf')/norm(M,'inf')\n\n% Compress 4x4 block random\nM     = rand(Nx,rk) * rand(rk,Ny);\nZ     = zeros(Nx,Ny);\nM     = [M Z ; Z M];\nZ     = zeros(size(M));\nM     = [M Z ; Z M];\n[A,B] = hmxACA(M,tol);\nnorm(A*B-M,'inf')/norm(M,'inf')\n\n% Compress 2x2 inegal block random (to be hardly improved...)\nM     = rand(Nx,rk) * rand(rk,Ny);\nZ     = zeros(Nx,1);\nM     = [M zeros(Nx,1) ; zeros(1,Ny) 1];\n[A,B] = hmxACA(M,tol);\nnorm(A*B-M,'inf')/norm(M,'inf')\n\n% Compress 4x4 inegal block random (to be hardly improved...)\nM     = rand(Nx,rk) * rand(rk,Ny);\nZ     = zeros(Nx,1);\nM     = [M zeros(Nx,3) ; zeros(3,Ny) eye(3)];\n[A,B] = hmxACA(M,tol);\nnorm(A*B-M,'inf')/norm(M,'inf')\n\n% Build orthogonal mesh\nvtx   = [0 0 0 ; eye(3)];\nelt   = [1 3 2 ; 1 2 4];\ncol   = [1 ; 2];\nmesh  = msh(vtx,elt,col);\nmesh  = refine(mesh,0.2);\n[~,I] = sort(mesh.col);\nmesh  = mesh.sub(I);\n\n% Translate\nmesh2          = mesh;\nmesh2.vtx(:,1) = mesh2.vtx(:,1) + 2;\n\n% Graphical representation\nfigure\nplot(mesh)\nhold on\nplotNrm(mesh)\nplot(mesh2)\naxis equal\nview(-180,30)\n\n% Build double layer matrix\nGxy{1} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]1',1);\nGxy{2} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]2',1);\nGxy{3} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]3',1);\nD      = integral(dom(mesh,3),dom(mesh2,3),fem(mesh,'P0'),Gxy,ntimes(fem(mesh2,'P0')));\n\n% Graphical represenation\nfigure\nimagesc(abs(D))\ncolorbar\n\n% Compression\n[A,B] = hmxACA(D,tol);\nnorm(A*B-D,'inf')/norm(D,'inf')\n\n\n\n\ndisp('~~> Michto gypsilab !')\n\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/gypsilabModified/nonRegressionTest/hierarchicalMatrix/nrtHmxLowrank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5562002256354752}}
{"text": "clear all; close all; clc;\naddpath('tools');\n\ndb_name = '256_ObjectCategories'; % '256_ObjectCategories' as a option\nnumRetrieval = 10;\n\n% load dataset\nif strcmp(db_name, 'faceDataset')\n    load feat4096Norml.mat;\n    path_imgDB = './faceDataset/';\n    addpath(path_imgDB);\n    queryID = 1900;\nelseif strcmp(db_name, '256_ObjectCategories')\n    %load 256feat2048Norml.mat; % 0.495471\n    % load 256feat4096Norml.mat; % 0.484413\n    load feat4096Norml.mat;\n    path_imgDB = './database/';\n    addpath(path_imgDB);\n    %example\n    queryID = 1; %\nend\n\n%if not normalize, then do\n% featNorm = normalize1(feat);\n% save('feat4096Norml.mat','featNorm', 'rgbImgList');\n\n% [pc, ~] = eigs(double(cov(feat)), 128);\n% feat = feat*pc;\n\n%virsulazation\nretrieval_virsulazation( queryID, numRetrieval, feat_norm, imgNamList);\n", "meta": {"author": "willard-yuan", "repo": "cnn-for-image-retrieval", "sha": "2e3e8ab76e2c971314be55b5ae44e02884003261", "save_path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval/cnn-for-image-retrieval-2e3e8ab76e2c971314be55b5ae44e02884003261/queryInDatabaseDemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5562002237633532}}
{"text": "function llh = GFM_llh( theta, tree )\n\n% Evaluate the likelihood of data under the estimated GFM model\n% This is *exactly* the same procedure for likelihood computation as in\n% GFM_EM\n%\n% Syntax:\n%   llh = GFM_llh( theta, tree )\n%\n%\n% Input:\n%   theta : Parameter cell for GFM model.\n%\n%   tree  : Wavelet tree from DWT2_TO_CELL\n%\n%\n% Output:\n%   llh   : Vector with log-likelihood for each direction and all trees\n\nif size(theta, 1) ~= numel(tree)-1\n    error('Wavelet transform must have the same size as theta');\nend\n\nL = length(tree) - 1;\nM = numel( theta{1} );\n\n% Naming convention:\n% beta1 is beta_u\n% beta2 is beta_{rho(u),u}\n\n[no_rows, no_cols] = cellfun( @(x) size(x{1}), tree(2:end) );\n[beta1, lh, cond_joint_probs] = deal( cell(L,1) );\n\nfor l = 1:L\n    beta1{l} = ones(no_rows(l), no_cols(l), M);\n    lh{l} = zeros(no_rows(l), no_cols(l));\n    cond_joint_probs{l} = ones(no_rows(l), no_cols(l), M, M);\nend\n\n[beta2, prod_beta2, state_probs] = deal( beta1 );\n[beta1_rep] = deal( cond_joint_probs );\nllh = zeros(3, 1);\n\nfor d = 1:3\n    for l = L:-1:1\n        w{l} = repmat(tree{l+1}{d}, [1 1 M]);\n        likelihood = normpdf( w{l}, 0, ...\n            repmat(reshape(theta{l,3,d}, [1 1 M]), [no_rows(l) no_cols(l) 1]) );\n        \n        % Make sure numerically large coefficients doesn't evaluate to all\n        % zeros\n        idx = find( sum(likelihood, 3) == 0 );\n        if ~isempty( idx )\n            likelihood(idx) = 1/M;\n        end\n        \n        state_probs{l} = repmat( reshape( theta{l,1,d}, [1 1 M] ), [no_rows(l) no_cols(l) 1] );\n        \n        % For the non-leaf nodes beta1 needs an additional factor\n        if l < L\n            % Compute beta2\n            trans_probs{l+1} = repmat(reshape( theta{l+1,2,d}, [1 1 M M] ), [no_rows(l+1) no_cols(l+1) 1]);\n            beta1_rep{l+1} = repmat( beta1{l+1}, [1 1 1 M] );\n            state_probs_rep{l+1} = repmat( state_probs{l+1}, [1 1 1 M] );\n            \n            beta2_full = trans_probs{l+1} .* beta1_rep{l+1} ./ state_probs_rep{l+1};\n            beta2{l+1} = squeeze( sum(beta2_full, 3) );\n            \n            % Product of beta2's with common parent\n            prod_beta2{l} = ...\n                beta2{l+1}(1:2:end, 1:2:end, :) .* ...\n                beta2{l+1}(2:2:end, 1:2:end, :) .* ...\n                beta2{l+1}(1:2:end, 2:2:end, :) .* ...\n                beta2{l+1}(2:2:end, 2:2:end, :);\n            \n            % Unnormalized beta1\n            tmp = prod_beta2{l} .* likelihood .* state_probs{l};\n        else\n            % Unnormalized beta1\n            tmp = likelihood .* state_probs{l};\n        end\n        \n        % Likelihood and beta1\n        lh{l} = sum( tmp, 3 );\n        beta1{l} = tmp ./ repmat( lh{l}, [1 1 M] );\n    end\n    \n    % The total likelihood for this direction\n    llh(d) = sum( cellfun(@(x) sum(log( max(x(:), eps) )), lh) );\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/GFM/GFM_llh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5562002207923735}}
{"text": "function [rDisambig,sourceInfo]=disambiguateClust1D(rMeas,ampMeas,deltaR,rMax,clustDist,twoWayDisambig,threshold)\n%%DISAMBIGUATECLUST1D This function uses a clustering algorithm to\n%                   disambiguate measurements in one dimension. It can\n%                   handle measurements from multiple simultaneous targets.\n%                   Information on which detections went into the\n%                   disambiguated measurements is also returned. The\n%                   snapshots all have a different number of bins; the\n%                   lengths in deltaR should be relatively prime (coprime)\n%                   integers (possibly all times a scaling constant). When\n%                   the \"true\" value of a detection is outside of the range\n%                   0<=rMeas<deltaR(i) for the ith interval, it is aliased\n%                   back in. This function tries to dealias the\n%                   measurements and determine how many detections are\n%                   present. This function only considers aliasing in a\n%                   positive (+deltaR) direction and is thus best suited\n%                   for dealiasing ranges.\n%\n%INPUTS: rMeas A numIntX1 or 1XnumInt cell matrix with the detections in\n%              each interval. Each cell contains a numMeasX1 or 1XnumMeas\n%              vector of the detections in that interval. Detections should\n%      ampMeas A numIntX1 or 1XnumInt cell matrix with the positive real\n%              amplitudes associated with the detections in each interval.\n%              These are used to perform a weighted average to determine\n%              the true target location.\n%       deltaR The numIntX1 or 1XnumInt vector of the unambiguous range in\n%              each interval. These values must be relatively prime\n%              integers (times a common possibly non-integer scale factor)\n%              for the algorithm to work.\n%         rMax The maximum unambiguous range to consider for the\n%              completely unaliased measurements (all dealiased values\n%              are less than this. If this value is omitted or an empty\n%              matrix is passed, then the default of prod(deltaR) is used,\n%              which is the maximum from the Chinese remainder theorem.\n%              However, as demonstrated below, the presence of multiple\n%              targets can cause extra distant \"ghost\" detections to appear\n%              due to the interference of the targets. Thus, it is often\n%              good to design the maximum unambiguous value to be very big\n%              and to limit the maximum number of bins actually considered.\n%              Put another way, use more coprime intervals.\n%    clustDist This is the distance to determine that two aliased-out\n%              values are in the same cluster. This depends on the scaling\n%              of the intervals. The default if this parameter is omitted\n%              or an empty matrix is passed is 0.5, which is good if deltaR\n%              are all integers.\n% twoWayDisambig If this is false, then the integers over which aliasing\n%              are performed are only positive. Otherwise, they can be\n%              positive and negative, which can be more convenient for\n%              Doppler disambiguation.\n%    threshold An optional threshold for declaring a detection. At least\n%              this many common intervals must cluster together. The\n%              default if this parameter is omitted or an empty matrix is\n%              passed is numInt.\n%\n%OUTPUTS: rDisambig The values of the detections, a numDetectX1 vector.\n%              These are weighted averages of the values in rMeas that went\n%              into the detections. If there are no detections, then this\n%              will be an empty matrix.\n%        sourceInfo Information allowing one to reconstruct which values in\n%              rMeas went into forming each detection. This is a\n%              numDetectX1 cell array. Each cell ion the array has a \n%              numMeasX2 matrix providing information on the measurements\n%              in that cluster. The first column gives the number of the\n%              interval that produced the measurement (index of rMeas) and\n%              the second column provides information on which measurement\n%              in that interval led to the detection.\n%\n%The general idea of such clustering is described in [1] and [2]. However,\n%it is done differently here. The authors in [2] described a\n%disambiguiation algorithm that is unusable if one of the intervals does\n%not produce detections and the basic algorithm in [1] is only focussed on\n%a single target. Here, we alias out the measurement across all ambiguity\n%intervals and then determine which aliased out measurements gate. Two\n%values gate if they are from different intervals and are within clustDist\n%of each other. A DisjointSet data structure is used to take the gating\n%ifnromation and cluster the aliased out measurements. Clusters of a\n%sufficient size are counted as detections. Note that this clustering is\n%not globally optimal as it is still possible for two detections from a\n%single PRI to end up in one cluster, which is only particularly likely\n%with closely spaced targets. An optimal clustering algorithm would be a\n%multiframe assignment problem.\n%\n%Note that because linear averaging is performed, points very near the\n%edges will not average to the correct values. However, since measurement\n%noises are typically small and unambiguous intervals large, this is seldom\n%a problem.\n%\n%EXAMPLE 1:\n%This is similar to the toy example given in [2], except we add some noise\n%to the measurements In this instance, the algorithm will produce results\n%that are close to the true unaliased bins.\n% deltaR=[7;8;11];\n% maxR=24;\n% \n% trueBins=[6;13];\n% \n% rMeas=cell(3,1);\n% for curInt=1:3\n%     rMeas{curInt}=unique(wrapRange(trueBins,0,deltaR(curInt)));\n%     %Add noise.\n%     rMeas{curInt}=rMeas{curInt}+0.1*randn(size(rMeas{curInt}));\n% end\n%\n%[rDisambig,sourceInfo]=disambiguateClust1D(rMeas,[],deltaR,maxR)\n%\n%EXAMPLE 2:\n%This example is better suited for Doppler disambiguation Here, positive\n%and negaitve values are present, which could correspond to positive and\n%negative range rates. The disambiguation is thus two-sided and the maximum\n%number of bins used is limited so that irrelevant extra-fast targets are\n%not detected.\n% deltaR=[7;8;11;13];\n% maxR=100;\n% %-50 to 49\n% trueBins=[6;-13];\n% \n% rMeas=cell(3,1);\n% for curInt=1:4\n%     rMeas{curInt}=unique(wrapRange(trueBins,0,deltaR(curInt)));\n%     %Add noise.\n%     rMeas{curInt}=rMeas{curInt}+0.1*randn(size(rMeas{curInt}));\n% end\n% disambiguateClust1D(rMeas,[],deltaR,maxR,[],true)\n%\n%REFERENCES:\n%[1] G. Trunk and S. Brockett, \"Range and velocity ambiguity resolution,\"\n%    in Record of the IEEE National Radar Conference, Lynnfield, MA, 20-22\n%    Apr. 1993, pp. 146-149.\n%[2] P. Stinco, M. Greco, F. Gini, A. Farina, and L. Timmoneri, \"Analysis\n%    and comparison of two disambiguity algorithms: The modified CA and\n%    CRT,\" in Proceedings of the International Radar Conference -\n%    Surveillance for a Safer World, Bordeaux, France, 12-16 Oct. 2009.\n%\n%December 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<4||isempty(rMax))\n   rMax=prod(deltaR);\nend\n\nnumPRI=length(rMeas);\nif(nargin<5||isempty(clustDist))\n   clustDist=0.5;\nend\n\nif(nargin<6||isempty(twoWayDisambig))\n   twoWayDisambig=false; \nend\n\nif(nargin<7||isempty(threshold))\n   threshold=numPRI;\nend\n\n%Determine the maximum number of aliased out measurements in both\n%directions.\nnumAliased=0;\nfor curPRI=1:numPRI\n    aliasedMax=ceil(rMax/deltaR(curPRI));\n    numAliased=numAliased+length(rMeas{curPRI})*aliasedMax;\nend\n\n%We will now alias out all of the measurements\nmeasList=zeros(numAliased,1);\n%souceData(i,1) holds the PRI that produced the aliased-out measurement.\n%sourceData(i,2) holds the index of the measurement in the PRI.\nsourceData=zeros(numAliased,2);\nnumAdded=0;\nfor curPRI=1:numPRI\n    curMeas=rMeas{curPRI};\n    numMeas=length(curMeas);\n\n    aliasedMax=ceil(rMax/deltaR(curPRI));\n    if(twoWayDisambig)\n        valRange=(-ceil((aliasedMax)/2)):fix((aliasedMax)/2);\n    else\n        valRange=(0:(aliasedMax-1));\n    end\n      \n    aliasedVals=bsxfun(@plus,curMeas(:),deltaR(curPRI)*valRange);\n    origIdx=repmat(1:numMeas,1,aliasedMax+1);\n    aliasedVals=aliasedVals(:);\n    origIdx=origIdx(:);\n    if(twoWayDisambig)\n        %Get rid of values that aliased to values that are too low.\n        %Get rid of values that aliased too low or too high\n        sel=(aliasedVals>=-rMax/2)&(aliasedVals<=rMax/2);\n        aliasedVals=aliasedVals(sel);\n    else\n        %Get rid of values that aliased to values that are too high.\n        sel=aliasedVals<=rMax;\n        aliasedVals=aliasedVals(sel);\n    end\n    \n    origIdx=origIdx(sel);\n\n    num2Add=length(aliasedVals);\n    idx2Add=(numAdded+1):(numAdded+num2Add);\n    \n    measList(idx2Add)=aliasedVals;\n    \n    sourceData(idx2Add,1)=curPRI;\n    sourceData(idx2Add,2)=origIdx;\n    \n    numAdded=numAdded+num2Add;\nend\n\n%Shrink to fit.\nmeasList=measList(1:numAdded);\nsourceData=sourceData(1:numAdded,:);\n\n%Sort the values.\n[measList,idx]=sort(measList,'ascend');\nsourceData=sourceData(idx,:);\n\n%Create a DisjointSet and determine which measurements gate with each other.\n%The DisjointSet will cluster them. To gate, they must be sufficiently\n%close and also not within the same interval. The loops go through all\n%pairs of aliased-out measurements. We take advantage of having sorted the\n%measurements so that once a distance comparison fails, no measurements are\n%farther ranges are considered.\ngateSet=DisjointSet(numAdded);\nfor idx1=1:(numAdded-1)\n    for idx2=(idx1+1):numAdded\n        %If they originate in different PRIs.\n        if(sourceData(idx1,1)~=sourceData(idx2,1))\n            if(abs(measList(idx1)-measList(idx2))<clustDist)\n                %The two values gate together.\n                gateSet.unionFromList([idx1;idx2]);\n            else\n                break;\n            end\n        end\n    end\nend\n\n%Form clusters.\ntheClust=gateSet.createClusterSet();\n\n%Count how many clusteres are large enough to keep.\nnumClusters=theClust.numClusters();\n\nnumPastThresh=sum(theClust.clustSize>=threshold);\nrDisambig=zeros(numPastThresh,1);\nsourceInfo=cell(numPastThresh,1);\n\ncurDetectClust=0;\nfor curClust=1:numClusters\n    numMeasCur=theClust.clustSize(curClust);\n    if(numMeasCur>=threshold)\n        sourceDataCur=sourceData(theClust(curClust,:),:);\n        \n        rAmpCur=zeros(numMeasCur,1);\n        if(~isempty(ampMeas))\n            for curMeas=1:numMeasCur\n                PRI=sourceDataCur(curMeas,1);\n                idx=sourceDataCur(curMeas,2);\n                idxR=theClust(curClust,curMeas);\n                \n                rAmpCur(curMeas,1)=measList(idxR);\n                rAmpCur(curMeas,2)=ampMeas{PRI}(idx);\n            end\n        else\n             for curMeas=1:numMeasCur\n                idxR=theClust(curClust,curMeas);\n                \n                rAmpCur(curMeas,1)=measList(idxR);\n                rAmpCur(curMeas,2)=1;\n            end\n        end\n\n        curDetectClust=curDetectClust+1;\n        \n        %A simple weighted average.\n        rDisambig(curDetectClust)=sum(rAmpCur(:,1).*rAmpCur(:,2))/sum(rAmpCur(:,2));\n        sourceInfo{curDetectClust}=sourceDataCur;\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/disambiguateClust1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5562002159492717}}
{"text": "function box_behnken_test02 ( )\n\n%*****************************************************************************80\n%\n%% BOX_BEHNKEN_TEST02 tests R8MAT_WRITE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    05 February 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n  dim_num = 4;\n\n  range = [ ...\n    0.0, 0.0, 0.0, 0.0; ...\n    1.0, 1.0, 1.0, 1.0 ]';\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'BOX_BEHNKEN_TEST02\\n' );\n  fprintf ( 1, '  R8MAT_WRITE writes a Box-Behnken dataset\\n' );\n  fprintf ( 1, '  to a file.\\n' );\n\n  r8mat_transpose_print ( dim_num, 2, range, '  The ranges:' );\n\n  x_num = box_behnken_size ( dim_num );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  For dimension DIM_NUM = %d\\n', dim_num );\n  fprintf ( 1, '  the Box-Behnken design is of size %d\\n', x_num );\n\n  x = box_behnken ( dim_num, x_num, range );\n\n  file_out_name = 'box_behnken_04_33.txt';\n\n  r8mat_write ( file_out_name, dim_num, x_num, x );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  The data was written to the file \"%s\".\\n', file_out_name );\n\n  return\nend\n", "meta": {"author": "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_behnken/box_behnken_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.5560989762943551}}
{"text": "%% FUNCTION nchoose\n%   How many unique combinations of 1 to N elements are there. This \n%   function is not intended to directly called by users. \n%   See the Logistic_iMSF function.\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 <http://www.gnu.org/licenses/>.\n%\n%   Copyright (C) 2011 - 2012 Lei Yuan, 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 June 12, 2012.\n%\n%% RELATED FUNCTIONS\n%   init_opts, Construct_iMSF, Logistic_iMSF, MultiSource_LogisticR\n\nfunction W = nchoose(S)\n\nN = numel(S) ; \n\n% How many unique combinations of 1 to N elements are there\nM = (2^N)-1 ;\nif N > 18,\n    warning('Nchoose:LargeOutput', ...\n        'There are %d unique combinations. Please be patient ...',M) ;\nend\n\nS = S(:).' ;   % make the set a row vector, for uniform output\n\nW = cell(M,1) ;    % Pre-allocation of output\np2=2.^(N-1:-1:0) ; % This part of the formula can be taken out of the loop\n\nfor i=1:M,\n    % calculate the (reversed) binary representation of i\n    % select the elements of the set based on this representation\n    W{i} = S(bitget(i*p2,N) > 0) ; \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/iMSF/nchoose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5560989705525937}}
{"text": "function [ won bet happy tt ] = auction( w, iter, e, verbose )\n% Subroutine AUCTION is a implemetation of the auction Algorithm \n% presented in Turing's Invisible Hand. Although well discribed the \n% pseudo-algorithm presented there contained an error which was corrected \n% by line 62-65 replacing \n%           if ((w(ii,j) - p(j)) >= 0)\n%\n% [ won bet happiness ] = auction( w, iter, e, verbose )\n% Inputs:\n%   w (g x b) \n%     the rows is the bidders\n%     the cols is the goods\n%     the values are every bidder i's percieved value of good j \n%   iter \n%     iterations iterations to do\n%   e\n%     e is the epsilon - the minumum bet increase (default e = 1/(ngoods+1)\n%     ) \n%\n% Copyright (C) 2012 - Pieter V. Reyneke, South Africa\n%\n% Open Source licence, use whereever you like but at own risk, keep this\n% complete copyright notice in the code and please send me updates and \n% report errors to pieter.reyneke@gmail.com. Will give recognition, if\n% requested, after any valid comment leading to an update was recieved. \n%\n% Author: PV Reyneke\n\nif (nargin<1)\n    w = rand(3)*10;\nend\n\nif (nargin<2)\n    iter = Inf;\nend\n\nif (nargin<4)\n    verbose = 1;\nend\n\np   = zeros(1,size(w,2));     % reset all goods' current bets (top - tracks)\nwon = zeros(1,size(w,2));     % reset cuurent winners for each good\nq   = 1:size(w,1);            % create queue for bidders (left - obs)\n\nif (nargin<3)\n    e = 1/(length(p)+1);\nend\n\nif (verbose)\n    display('The percieved value of goods (top) by each bidder (left):');\n    display([num2str(w, '%3.0f') ]);\nend\n\ni = find(q>0,1);              % take first non-committed bidder\nii = q(i);\ntdead = 0;\ntic\nwhile (~isempty(ii) && (iter > 0))\n    q(q==ii) = 0;             % out of queue\n    [v, j] = max(w(ii,:) - p); % search for good w greatest value \n                              % above current bid for bidder i\n    if ( ((w(ii,j) - (p(j) + e)) >= 0) && ...   \n         ...                  % if our current bidder i values good j \n         ...                  % more than previous bidder plus epsilon \n         (won(j) ~= ii) )     % and the bot is not on himself already\n        if (won(j)>0)\n            k = find(q==0,1); % find first open bidder space\n            q(k:(end-1)) = q((k+1):end); \n                              % shift left and put \n            q(end) = won(j);  % previous highest bidder back in the queue\n        end\n        won(j) = ii;          % assign current bidder i to good j\n        p(j) = p(j) + e;      % and save the new bet\n    end\n    \n    if (verbose)\n        tsss = toc;\n        display(['Bets(in epsilons)  : ' num2str(p/e, '%3.0f') ]);\n        display(['Bidder             : ' num2str(won, '%3.0f') ]);\n        display(['Left todo          : ' num2str(q, '%3.0f') ]);\n        display(['-----------------------------------------' ]);\n        tdead = toc - tsss;\n    end\n    i = find(q>0,1);          % take next non-committed bidder\n    ii = q(i);\n    iter = iter-1;\nend\nbet = p;\ntt = toc;\n\n% measuring each bidder's happiness (the invariant of above loop)\nhappy = won;\niown = find(won > 0);\nfor (ii = won(iown))\n    iii = won(ii);\n    if (~isempty(iii))\n        jjj = find(iii==won,1);\n        if (~isempty(jjj))\n            happy(iii) = (sum(e + w(iii,jjj) - p < w(iii,:) - p) == 0);\n        end\n    end\nend\niown = find(won > 0);\nfor (ii = won(iown))\n    iii = won(ii);\n    happy(iii) = happy(iii) | (sum(w(iii,:) - p > 0));\nend\n\nj = 1;\ncost = 0;\nfor (i=won)\n    cost = cost + w(i,j);\n    j = j+1;\nend\n\n\nif (verbose)\n    display(['Assignment Cost    : ' num2str(cost, '%5.3f') ]);\n    display(['Happiness          : ' num2str(happy, '%3.0f') ]);\n    display(['Calc took          : ' num2str((tt - tdead) * 1000, '%5.3f') ' ms' ]);\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/34673-a-jacobi-auction-algorithm-implementation-simple/auction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5560989678872468}}
{"text": "function V = hogDraw( H, w )\n% Create visualization of hog descriptor.\n%\n% USAGE\n%  V = hogDraw( H, [w] )\n%\n% INPUTS\n%  H          - [m n oBin*4] computed hog features\n%  w          - [15] width for each glyph\n%\n% OUTPUTS\n%  V          - [m*w n*w] visualization of hog features\n%\n% EXAMPLE\n%\n% See also hog\n%\n% Piotr's Image&Video Toolbox      Version 2.41\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\n% fold 4 normalizations\nnFold=4; s=size(H); s(3)=s(3)/nFold; w0=H; H=zeros(s);\nfor o=0:nFold-1, H=H+w0(:,:,(1:s(3))+o*s(3)); end;\n\n% construct a \"glyph\" for each orientaion\nif(nargin<2 || isempty(w)), w=15; end\nbar=zeros(w,w); bar(:,round(.45*w):round(.55*w))=1;\nbars=zeros([size(bar) s(3)]);\nfor o=1:s(3), bars(:,:,o)=imrotate(bar,-(o-1)*180/s(3),'crop'); end\n\n% make pictures of positive weights by adding up weighted glyphs\nH(H<0)=0; V=zeros(w*s(1:2));\nfor r=1:s(1), rs=(1:w)+(r-1)*w;\n  for c=1:s(2), cs=(1:w)+(c-1)*w;\n    for o=1:s(3), V(rs,cs)=V(rs,cs)+bars(:,:,o)*H(r,c,o); end\n  end\nend\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SketchTokens-master/toolbox/channels/hogDraw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.556098963170957}}
{"text": "function tests = LocnTest\n  tests = functiontests(localfunctions);\n  clc\nend\n\nfunction setupOnce(testCase)\n    testCase.TestData.Duration = 50;\nend\n\nfunction Vehicle_test(tc)\n    %%\n    randinit\n    V = diag([0.005, 0.5*pi/180].^2);\n\n    v = Bicycle('covar', V);\n    v.add_driver( RandomPath(10) );\n\n    v.run(tc.TestData.Duration);\n    v.plot_xy();\n    s = v.char();\n\n    J = v.Fx(v.x, [.1 .2]);\n    J = v.Fv(v.x, [.1 .2]);\nend\n\nfunction DeadReckoning_test(tc)\n    %%\n    randinit\n    V = diag([0.005, 0.5*pi/180].^2);\n    P0 = diag([0.005, 0.005, 0.001].^2);\n\n    v = Bicycle('covar', V);\n    v.add_driver( RandomPath(10) );\n    s = char(v);\n\n    ekf = EKF(v, V, P0);\n    ekf.run(tc.TestData.Duration);\n\n    clf\n    ekf.plot_xy\n    hold on \n    v.plot_xy('r')\n    grid on\n    xyzlabel\n\n    ekf.plot_ellipse('g')\n    ekf.plot_P()\nend\n\nfunction MapLocalization_test(tc)\n    %%\n    randinit\n    W = diag([0.1, 1*pi/180].^2);\n    P0 = diag([0.005, 0.005, 0.001].^2);\n    V = diag([0.005, 0.5*pi/180].^2);\n\n    map = LandmarkMap(20);\n    map = LandmarkMap(20, 'verbose');\n    map = LandmarkMap(20, 10, 'verbose');\n    map = LandmarkMap(20, 10);\n    s = char(map);\n\n    veh = Bicycle('covar', V);\n    veh.add_driver( RandomPath(10) );\n    sensor = RangeBearingSensor(veh, map, 'covar', W);\n    sensor.interval = 5;\n    ekf = EKF(veh, W, P0, sensor, W, map);\n\n    ekf.run(tc.TestData.Duration);\n\n    clf\n    map.plot()\n    veh.plot_xy('b');\n    ekf.plot_xy('r');\n    ekf.plot_ellipse('k')\n    grid on\n    xyzlabel\n\n    clf\n    ekf.plot_P()\nend\n\nfunction Mapping_test(tc)\n    %%\n    randinit\n    W = diag([0.1, 1*pi/180].^2);\n    V = diag([0.005, 0.5*pi/180].^2);\n\n    map = LandmarkMap(20, 10);\n\n    veh = Bicycle('covar', V);\n    veh.add_driver( RandomPath(10) );\n\n    sensor = RangeBearingSensor(veh, map, 'covar', W);\n    sensor.interval = 5;\n\n    ekf = EKF(veh, [], [], sensor, W, []);\n    ekf.run(tc.TestData.Duration);\n    \n\n    clf\n    map.plot()\n    veh.plot_xy('b');\n    ekf.plot_map('g');\n    grid on\n    xyzlabel\n    \n    %%\n    verifyEqual(tc, numcols(ekf.landmarks), 20);\n\nend\n\nfunction SLAM_test(tc)\n    %%\n    randinit\n    W = diag([0.1, 1*pi/180].^2);\n    P0 = diag([0.005, 0.005, 0.001].^2);\n    V = diag([0.005, 0.5*pi/180].^2);\n\n    map = LandmarkMap(20, 10);\n\n    veh = Bicycle(V);\n    veh.add_driver( RandomPath(10) );\n\n    sensor = RangeBearingSensor(veh, map, 'covar', W);\n    sensor.interval = 1;\n\n    ekf = EKF(veh, V, P0, sensor, W, []);\n    ekf\n    ekf.verbose = false;\n    ekf.run(tc.TestData.Duration);\n\n\n    clf\n    map.plot()\n    veh.plot_xy('b');\n    ekf.plot_xy('r');\n    ekf.plot_ellipse('k')\n    grid on\n    xyzlabel\n\n    clf\n    ekf.plot_P()\n\n    clf\n    map.plot();\n    ekf.plot_map('g');\n    \n    %%\n    verifyEqual(tc, numcols(ekf.landmarks), 20);\n\nend\n\nfunction ParticleFilter_test(tc)\n    %%\n    randinit\n    map = LandmarkMap(20);\n\n    W = diag([0.1, 1*pi/180].^2);\n    v = Bicycle('covar', W);\n    v.add_driver( RandomPath(10) );\n    V = diag([0.005, 0.5*pi/180].^2);\n    sensor = RangeBearingSensor(v, map, 'covar', V);\n\n    Q = diag([0.1, 0.1, 1*pi/180]).^2;\n    L = diag([0.1 0.1]);\n    pf = ParticleFilter(v, sensor, Q, L, 1000);\n    pf\n    pf.run(tc.TestData.Duration);\n\n    plot(pf.std)\n    xlabel('time step')\n    ylabel('standard deviation')\n    legend('x', 'y', '\\theta')\n    grid       \n\n    clf\n    pf.plot_pdf();\n    clf\n    pf.plot_xy();\nend\n\nfunction posegraph_test(tc)\n    pg = PoseGraph('pg1.g2o')\n    tc.verifyClass(pg, 'PoseGraph');\n    tc.verifyEqual(pg.graph.n, 4);\n    \n    clf\n    pg.plot()\n    pg.optimize('animate')\n    close all\n    \n    pg = PoseGraph('killian-small.toro')\n    tc.verifyClass(pg, 'PoseGraph');\n    tc.verifyEqual(pg.graph.n, 1941);\n    \n    pg = PoseGraph('killian.g2o', 'laser')\n    tc.verifyClass(pg, 'PoseGraph');\n    tc.verifyEqual(pg.graph.n, 3873);\n    \n    [r,theta] = pg.scan(1);\n    tc.verifyClass(r, 'double');\n    tc.verifyLength(r, 180);\n    tc.verifyClass(theta, 'double');\n    tc.verifyLength(theta, 180);\n    \n    [x,y] = pg.scan(1);\n    tc.verifyClass(x, 'double');\n    tc.verifyLength(x, 180);\n    tc.verifyClass(y, 'double');\n    tc.verifyLength(y, 180);\n    \n    pose = pg.pose(1);\n    tc.verifyClass(pose, 'double');\n    tc.verifySize(pose, [3 1]);\n    \n    t = pg.time(1);\n    tc.verifyClass(t, 'double');\n    tc.verifySize(t, [1 1]);\n    \n    w = pg.scanmap('ngrid', 3000);\n    tc.verifyClass(w, 'int32');\n    tc.verifySize(w, [3000 3000]);\n    \n    tc.assumeTrue(exist('idisp', 'file'));  %REMINDER\n    clf\n    pg.plot_occgrid(w);\n    close all\n    \nend\n\nfunction makemap_test(tc)\n        tc.assumeTrue(false);  %REMINDER\n\nend\n\nfunction chi2inv_test(tc)\n    tc.verifyEqual( chi2inv_rtb(0,2), 0);\n    tc.verifyEqual( chi2inv_rtb(1,2), Inf);\n    tc.verifyEqual( chi2inv_rtb(3,2), NaN);\n    \n    tc.verifyError( @() chi2inv_rtb(1,1), 'RTB:chi2inv_rtb:badarg');\n    \nend", "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/unit_test/LocnTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.556098963170957}}
{"text": "function A = my_spdiags(v,diagonals,m,n)\n%MY_SPDIAGS Construct a banded matrix from diagonal input\n%\n% A = my_spdiags(v,diagonals,m,n);\n%\n% Inputs:\n%  v  the diagonals to be inserted in the matrix - each column of v is one\n%     diagonal in diagonals\n%  diagonals  the index of diagonals requested\n%  m,n  the dimension of the requested matrix\n% Outputs:\n%  A  the requested banded sparse matrix\n%\n\nA = ...\n\nend\n\n", "meta": {"author": "odedstein", "repo": "sgi-introduction-course", "sha": "52278fc3b3dab52febb110a1a09d770f46b5e417", "save_path": "github-repos/MATLAB/odedstein-sgi-introduction-course", "path": "github-repos/MATLAB/odedstein-sgi-introduction-course/sgi-introduction-course-52278fc3b3dab52febb110a1a09d770f46b5e417/010_sparse_matrices/exercise/my_spdiags.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.5560801760661905}}
{"text": "%PEAK2  Find peaks in a matrix\n%\n% ZP = PEAK2(Z, OPTIONS) are the peak values in the 2-dimensional signal Z.\n%\n% [ZP,IJ] = PEAK2(Z, OPTIONS) as above but also returns the indices of the \n% maxima in the matrix Z.  Use SUB2IND to convert these to row and column \n% coordinates\n%\n% Options::\n% 'npeaks',N    Number of peaks to return (default all)\n% 'scale',S     Only consider as peaks the largest value in the horizontal \n%               and vertical range +/- S points.\n% 'interp'      Interpolate peak (default no interpolation)\n% 'plot'        Display the interpolation polynomial overlaid on the point data\n%\n% Notes::\n% - A maxima is defined as an element that larger than its eight neighbours.\n%   Edges elements will never be returned as maxima.\n% - To find minima, use PEAK2(-V).\n% - The interp options fits points in the neighbourhood about the peak with\n%   a paraboloid and its peak position is returned.  In this case IJ will \n%   be non-integer.\n%\n% See also PEAK, SUB2IND.\n\n\n\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\n% Copyright (c) Peter Corke 1/96\n\nfunction [zp,xypout, aout] = peak2(z, varargin)\n\n    % process input options\n    opt.npeaks = 2;\n    opt.scale = 1;\n    opt.interp = false;\n    \n    [opt,args] = tb_optparse(opt, varargin);\n    \n    \n    % create a neighbourhood mask for non-local maxima\n    % suppression\n    h = opt.scale;\n    w = 2*h+1;\n    M = ones(w,w);\n    M(h+1,h+1) = 0;\n    \n    % compute the neighbourhood maximum\n    znh = iwindow(double(z), M, 'max', 'wrap');\n    \n    % find all pixels greater than their neighbourhood\n    k = find(z > znh);\n    \n    \n    % sort these local maxima into descending order\n    [zpk,ks] = sort(z(k), 'descend');\n\n    k = k(ks);\n    \n    npks = min(length(k), opt.npeaks);\n    k = k(1:npks);\n    \n    [y,x] = ind2sub(size(z), k);\n    xy = [x y]';\n    \n\n    % interpolate the peaks if required\n    if opt.interp\n        \n        \n        xyp = [];\n        zp = [];\n        ap = [];\n               \n        % for each previously identified peak x(i), y(i)\n        for xyt=xy\n            % fit a polynomial to the local neighbourhood\n            try\n                \n                x = xyt(1); y = xyt(2);\n\n                \n                % now try to interpolate the peak over a 3x3 window\n                \n                zc = z(x,   y);\n                zn = z(x,   y-1);\n                zs = z(x,   y+1);\n                ze = z(x+1, y);\n                zw = z(x-1, y);\n                \n                dx = (ze - zw)/(2*(2*zc - ze - zw));\n                dy = (zn - zs)/(2*(zn - 2*zc + zs));\n\n                zest = zc - (ze - zw)^2/(8*(ze - 2*zc + zw)) - (zn - zs)^2/(8*(zn - 2*zc + zs));\n                \n                aest = min(abs([ze/2 - zc + zw/2, zn/2 - zc + zs/2]));\n\n                \n            catch\n                % handle situation where neighbourhood falls off the data\n                % vector\n                warning('Peak at %f too close to edge of image, skipping', x(i));\n                continue;\n            end\n            %\n            \n            % store x, y for the refined peak\n            xyp = [xyp [x+dx; y+dy]];\n            zp = [zp zest];\n            ap = [ap aest];\n\n        end\n    else\n        % no interpolation case\n        xyp = xy;\n        zp = z(k)';\n        ap = [];\n\n    end\n    \n    \n    % return values\n    if nargout > 1\n        xypout = xyp;\n    end\n    if nargout > 2\n        aout = ap;\n    end\n        \n\n\n\n    \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/common/peak2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5560801725899923}}
{"text": "%computes the maximum of the Harmonic Product Spectrum\n%> called by ::ComputePitch\n%>\n%> @param X: spectrogram (dimension FFTLength X Observations)\n%> @param f_s: sample rate of audio data \n%>\n%> @retval f_0 HPS maximum (in Hz)\n% ======================================================================\nfunction [f_0] = PitchSpectralHps (X, f_s)\n\n    % initialize\n    iOrder = 4;\n    f_min = 300;\n    k_min = round(f_min/f_s * 2 * (size(X, 1)-1)) + 1;\n\n    afHps = X;\n    \n    % compute the HPS\n    for j = 2:iOrder\n        afHps = afHps .* [X(1:j:end, :); zeros(size(X, 1)-size(X(1:j:end,:), 1), size(X, 2))];\n    end\n    \n    % find max index and convert to Hz\n    [fDummy, f_0] = max(afHps(k_min:end, :), [], 1);\n    f_0 = (f_0 + k_min - 2) / (size(X, 1)-1) * f_s / 2;\n    f_0(sum(afHps, 1) == 0) = 0;\nend\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/PitchSpectralHps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5560487789849716}}
{"text": "function Sfi = GetSf(angles, offsets, T2f, SfTable)\n%GetSf interpolate Sf values from precomputed table\n\nSfi = zeros(length(angles),1);\nprinted = false;\n\n% This is a little workspace trick to limit the number of \n% Sf table interpolation warnings to the command window/console. \n% If the counterSfMiss variable exists in the base workspace, \n% its value will nbe subjected to evaluation. If not, will be assigned\n% with 0 and broadcasted to the base workspace. \n% This is not a go-to *.m practice, especially if done without enough \n% comments.\n\n\nfor ii = 1:length(angles)\n   \n[xi, yi, zi] = meshgrid(offsets(ii), angles(ii), T2f);\nSfi(ii) = interp3(SfTable.offsets, SfTable.angles, SfTable.T2f, SfTable.values, xi, yi, zi);\n\n    if (isnan(Sfi(ii)))\n        \n        if ~evalin('base','exist(''counterSfMiss'')')\n          counterSfMiss = 0;\n          assignin('base','counterSfMiss',counterSfMiss);\n         else\n         counterSfMiss  = evalin('base','counterSfMiss');\n      \n        % Print this once for all the angles. Allow 10 global prints in total.\n        % Fetch the variable from workspace. Doing this here instead of L14\n        % means one less condition, which matters when there are thousands.\n\n        if ~printed && counterSfMiss < 11\n         % Get value from base kspace.   \n          cprintf('magenta','Cannot interpolate value from current Sf table : angle: %f; offset: %f; T2f: %f\\n',angles(ii), offsets(ii), T2f);\n          cprintf('blue','%s','Calculating the missing Sf value...');\n          if counterSfMiss==10\n            cprintf('blue','%s','Remaining warnings for missing Sf value interpolations have been silenced for this processs');\n          end\n          counterSfMiss = counterSfMiss + 1;\n          assignin('base','counterSfMiss',counterSfMiss);\n          printed = true;\n        end\n        \n        end \n        \n        MTpulse = GetPulse(angles(ii),offsets(ii),SfTable.PulseTrf,SfTable.PulseShape,SfTable.PulseOpt);\n        Sfi(ii) = computeSf(T2f, MTpulse);\n    end\nend", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/SPGRfun/functions/GetSf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478913248044, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5559475740414834}}
{"text": "function edges = crackPattern2(box, points, alpha, varargin)\n%CRACKPATTERN2 Create a (bounded) crack pattern tessellation\n%\n%   E = crackPattern2(BOX, POINTS, ALPHA)\n%   create a crack propagation pattern wit following parameters :\n%   - pattern is bounded by area BOX which is a polygon.\n%   - each crack originates from points given in POINTS\n%   - directions of each crack is given by a [NxM] array ALPHA, where M is\n%   the number of rays emanating from each seed/\n%   - a crack stop when it reaches another already created crack. \n%   - all cracks stop when they reach the border of the frame, given by box\n%   (a serie of 4 points).\n%   The result is a collection of edges, in the form [x1 y1 x2 y2].\n%\n%   E = crackPattern2(BOX, POINTS, ALPHA, SPEED)\n%   Also specify speed of propagation of each crack.\n%\n%\n%   See the result with :\n%     figure;\n%     drawEdge(E);\n%\n%   See also drawEdge\n%\n%   ---------\n%\n%   author : David Legland \n%   INRA - TPV URPOI - BIA IMASTE\n%   created the 25/05/2004.\n%\n\n%   HISTORY :\n\nif ~isempty(varargin)\n    speed = varargin{1};\nelse\n    speed = ones(size(points, 1), 1);\nend\n\n% Compute line equations for each initial crack.\n% The 'Inf' at the end correspond to the position of the limit.\n% If an intersection point is found with another line, but whose position\n% is after this value, this means that another crack stopped it before it\n% reach the intersection point.\nNP = size(points, 1);\nlines = zeros(0, 5);\nfor i=1:size(alpha, 2)    \n    lines = [lines; points speed.*cos(alpha(:,i)) speed.*sin(alpha(:,i)) Inf*ones(NP, 1)];\nend\nNL = size(lines, 1);\n\n% initialize lines for borders, but assign a very high speed, to be sure\n% borders will stop all cracks.\ndx = (box([2 3 4 1],1)-box([1 2 3 4],1))*max(speed)*5;\ndy = (box([2 3 4 1],2)-box([1 2 3 4],2))*max(speed)*5;\n\n% add borders to the lines set\nlines = [lines ; createLine(box, dx, dy) Inf*ones(4,1)];\n\nedges = zeros(0, 4);\n\n\nwhile true    \n    modif = 0;\n    \n    % try to update each line\n\tfor i=1:NL\n        \n        % initialize first point of edge\n        edges(i, 1:2) = lines(i, 1:2);\n        \n        % compute intersections with all other lines\n        pi = intersectLines(lines(i,:), lines);\n        \n        % compute position of all intersection points on the current line \n        pos = linePosition(pi, lines(i,:));\n        \n                \n        % consider points to the right (positive position), and sort them\n        indr = find(pos>1e-12 & pos~=Inf);\n        [posr, indr2] = sort(pos(indr));\n        \n        \n        % look for the closest intersection to the right\n        for i2=1:length(indr2)\n            \n            % index of intersected line\n            il = indr(indr2(i2));\n\n            % position of point relative to intersected line\n            pos2 = linePosition(pi(il, :), lines(il, :));\n            \n            % depending on the sign of position, tests if the line2 can\n            % stop the current line, or if it was stopped before\n            if pos2>0\n                if pos2<abs(posr(i2)) && pos2<lines(il, 5)\n                    if lines(i, 5) ~= posr(i2)\n                        edges(i, 3:4) = pi(il,:);\n                        lines(i, 5) = posr(i2); \n                        modif = 1;\n                    end                                                           \n                    break;\n                end\n            end\n        end   % end processing of right points of the line\n              \n        \n\tend % end processing of all lines\n    \n    % break the infinite loop if no more modification was made\n    if ~modif\n        break;\n    end\nend\n\n% add edges of the surronding box.\nedges = [edges ; box(1,:) box(2,:) ; box(2,:) box(3,:); ...\n                 box(3,:) box(4,:) ; box(4,:) box(1,:)  ];\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/geom2d/crackPattern2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5559475730550288}}
{"text": "function X = arrange(X,foo)\n%ARRANGE Arranges the rank-1 components of a ktensor.\n%\n%   ARRANGE(X) normalizes the columns of the factor matrices and then sorts\n%   the ktensor components by magnitude, greatest to least.\n%\n%   ARRANGE(X,N) absorbs the weights into the Nth factor matrix instead of\n%   lambda. \n%\n%   ARRANGE(X,P) rearranges the components of X according to the\n%   permutation P. P should be a permutation of 1 to NCOMPOMENTS(X). \n%\n%   See also KTENSOR, NCOMPONENTS, NORMALIZE.\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\n\n%% Just rearrange and return if second argument is a permutation\nif exist('foo','var') && (length(foo) > 1)\n    X.lambda = X.lambda(foo);\n    for i = 1 : ndims(X)\n        X.u{i} = X.u{i}(:,foo);\n    end   \n    return;\nend\n\n%% Ensure that matrices are normalized\nX = normalize(X);\n\n%% Sort\n[X.lambda, idx] = sort(X.lambda, 1, 'descend');\nfor i = 1 : ndims(X)\n    X.u{i} = X.u{i}(:,idx);\nend\n\n%% Absorb the weight into one factor, if requested\nif exist('foo','var')\n    r = length(X.lambda);\n    X.u{end} = full(X.u{end} * spdiags(X.lambda,0,r,r));\n    X.lambda = ones(size(X.lambda));\nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u7c7b\u7b97\u6cd5/DEEP-TENSOR-FACTORIZATION-FOR-HYPERSPECTRAL-IMAGE-CLASSIFICATION-master/code/tensor_toolbox_2.6/@ktensor/arrange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5559475667748578}}
{"text": "function r8_epsilon_test ( )\n\n%*****************************************************************************80\n%\n%% R8_EPSILON_TEST tests R8_EPSILON.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    01 September 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8_EPSILON_TEST\\n' );\n  fprintf ( 1, '  R8_EPSILON produces the R8 roundoff unit.\\n' );\n  fprintf ( 1, '\\n' );\n\n  r = r8_epsilon ( );\n  fprintf ( 1, '  R = R8_EPSILON()         = %e\\n', r );\n\n  s = ( 1.0 + r ) - 1.0;\n  fprintf ( 1, '  ( 1 + R ) - 1            = %e\\n', s );\n\n  s = ( 1.0 + ( r / 2.0 ) ) - 1.0;\n  fprintf ( 1, '  ( 1 + (R/2) ) - 1        = %e\\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/r8lib/r8_epsilon_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.5559475505812029}}
{"text": "function table = distableAll(board)\n\nn = numel(board);\ntable = NaN * zeros(n);\n\nfor i = 1:n\n    table(i,i) = 0;\n    table(i, board(i).Neighbors) = 1;\n    d = 1;\n    N = -1;\n    while nnz(~isnan(table(i,:))) ~= N;\n        N = nnz(~isnan(table(i,:)));\n        for j = find(table(i,:) == d)\n            for k = board(j).Neighbors\n                if i ~= k && isnan(table(i, k))\n                    table(i, k) = d + 1;\n                end\n            end\n        end        \n        d = d + 1;\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/34438-risk/Final/distableAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.555939583694363}}
{"text": "function preprocess_shape_collection(path_shapes,path_save,global_params, shot_params)\n    d = dir([path_shapes,'*.mat']);\n    \n    if ~exist(path_save, 'dir')\n       mkdir(path_save)\n    end\n\n    for i=1:numel(d)\n        %Load shapes\n        model = load([path_shapes,d(i).name]); \n        model.X = model.VERT(:,1); model.Y = model.VERT(:,2); model.Z = model.VERT(:,3);\n        \n        %Calculate LBO eigenfunctions and SHOT descriptors\n        [model_evecs,~,model_evals,model_S] = extract_eigen_functions_new(model,global_params.num_evecs);\n        model_shot = calc_shot(model.VERT', model.TRIV', 1:model.n, shot_params.num_bins, shot_params.radius, 3)';\n\n        %save as single\n        model_evecs_trans = single(model_evecs'*model_S);\n        model_evecs = single(model_evecs);\n        model_S = single(full(diag(model_S)));\n        save([path_save,d(i).name],'model_shot', 'model_evecs', 'model_evecs_trans', 'model_S', 'shot_params');\n\n        display(i)\n    end\n    \n    delete(gcp('nocreate'))\nend\n\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/preprocess_shape_collection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5559395727913373}}
{"text": "function [c, ceq] = ma_inclinationConstraint(stateLog, eventID, lbInc, ubInc, bodyIDApply, celBodyData, maData)\n%ma_semiEccentricityConstraint Summary of this function goes here\n%   Detailed explanation goes here\n    normFact = pi;\n\n    if(ischar(eventID) && strcmpi(eventID,'final'))\n        eventNum = max(stateLog(:,13));\n    else\n%         hMAMainGUI = findall(0,'tag','ma_MainGUI');\n%         maData = getappdata(hMAMainGUI,'ma_data');\n        [~, eventNum] = getEventByID(eventID, maData.script);\n    end\n\n    eventLog = stateLog(stateLog(:,13)==eventNum,:);\n\n    bodyEventLog = eventLog(eventLog(:,8)==bodyIDApply,:);\n    if(isempty(bodyEventLog))\n        finalEntry = eventLog(end,:);\n    else\n        finalEntry = bodyEventLog(end,:);\n    end\n    \n    bodyID = finalEntry(8);\n\n    if(bodyID == bodyIDApply || bodyIDApply==-1)\n        bodyInfo = getBodyInfoByNumber(bodyID, celBodyData);\n        gmu = bodyInfo.gm;\n        rVect = finalEntry(2:4)';\n        vVect = finalEntry(5:7)';\n\n        [~, ~, inc, ~, ~, ~] = getKeplerFromState(rVect,vVect,gmu);\n\n        if(lbInc == ubInc)\n            c = [0 0];\n            ceq(1) = inc - ubInc;\n        else\n            c(1) = inc - ubInc;\n            c(2) = lbInc - inc;\n            ceq = [0];\n        end\n        c = c/normFact;\n        ceq = ceq/normFact;\n    else\n        c = [0 0];\n        ceq = [0];\n    end\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/ksptot_ma/optimization/constraints/zArchive/ma_inclinationConstraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888478, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5559395726072128}}
{"text": "function F = intkernel(X,vp,gp,avg_flag)\n%INTKERNEL Expected GP kernel in scalar correlation\n\nif nargin < 4 || isempty(avg_flag); avg_flag = false; end\n\nK = vp.K;           % Number of components\n[N,D] = size(X);\nmu(:,:) = vp.mu;\nsigma(1,:) = vp.sigma;\nlambda(:,1) = vp.lambda(:);\nw(1,:) = vp.w;\n\nNs = numel(gp.post);            % Hyperparameter samples\n\nF = zeros(N,Ns);\n\nif isfield(vp,'delta') && ~isempty(vp.delta)\n    delta = vp.delta;\nelse\n    delta = 0;\nend\n\n% Integrated mean function being used?\nintegrated_meanfun = isfield(gp,'intmeanfun') && gp.intmeanfun > 0;\n\nif integrated_meanfun\n    % Evaluate basis functions\n    Hs = gplite_intmeanfun(X,gp.intmeanfun);\nend\n    \n% Loop over hyperparameter samples\nfor s = 1:Ns\n    hyp = gp.post(s).hyp;\n    \n    % Extract GP hyperparameters from HYP\n    ell = exp(hyp(1:D));\n    ln_sf2 = 2*hyp(D+1);\n    sum_lnell = sum(hyp(1:D));\n    \n    if integrated_meanfun\n        %betabar = gp.post(s).intmean.betabar';\n        %KinvHtbetabar = gp.post(s).intmean.HKinv'*betabar;\n        plus_idx = gp.intmeanfun_var > 0;\n        HKinv = gp.post(s).intmean.HKinv(plus_idx,:);\n        Tplusinv = gp.post(s).intmean.Tplusinv;\n    end\n            \n    L = gp.post(s).L;\n    Lchol = gp.post(s).Lchol;\n    \n    sn2_eff = 1/gp.post(s).sW(1)^2;\n    \n    ddl = sq_dist(bsxfun(@rdivide,X',ell),bsxfun(@rdivide,gp.X',ell));\n    ll = exp(ln_sf2 -0.5*ddl);\n    \n    if Lchol\n        zz = (L\\(L'\\ll'))/sn2_eff;\n    else\n        zz = -L*ll';\n    end\n\n    for k = 1:K\n        tau_k = sqrt(sigma(k)^2*lambda.^2 + ell.^2 + delta.^2);\n        lnnf_k = ln_sf2 + sum_lnell - sum(log(tau_k));  % Covariance normalization factor\n        delta_k = bsxfun(@rdivide,bsxfun(@minus, mu(:,k), gp.X'), tau_k);\n        z_k = exp(lnnf_k -0.5 * sum(delta_k.^2,1));\n\n        dd_k = bsxfun(@rdivide,bsxfun(@minus, mu(:,k), X'), tau_k);\n        zz_k = exp(lnnf_k -0.5 * sum(dd_k.^2,1));\n        \n        F(:,s) = F(:,s) + w(k)*(zz_k - z_k*zz)';\n        \n        % Contribution of integrated mean function\n        if integrated_meanfun\n            switch gp.intmeanfun\n                case 1; u_k = 1;\n                case 2; u_k = [1,mu(:,k)'];\n                case 3; u_k = [1,mu(:,k)',(mu(:,k).^2 + sigma(k)^2*lambda.^2)'];\n                case 4; u_k = [1,mu(:,k)',(mu(:,k).^2 + sigma(k)^2*lambda.^2)',mumu_mat(k,:)];\n            end\n            \n            F(:,s) = F(:,s) + w(k)*((u_k(plus_idx)*(Tplusinv*Hs)) ...\n                + ((z_k*HKinv')*(Tplusinv*(HKinv*ll'))) ...\n                - (u_k(plus_idx)*(Tplusinv*(HKinv*ll'))) ...\n                - ((z_k*HKinv')*(Tplusinv*Hs)))';\n        end\n        \n        \n    end\nend\n\n% Average multiple hyperparameter samples\nif Ns > 1 && avg_flag\n    F = mean(F,2);\nend\n\nend\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/misc/intkernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5559395563447359}}
{"text": "function plot_strike_dip(catalog,ax)\n    % plot strike and dip for a catalog using DipDirection and Dip\n    % specify the axes\n    \n    dipdir=catalog.DipDirection;\n    dip=catalog.Dip;\n    x0=catalog.Longitude;\n    y0=catalog.Latitude;\n    \n    strikescale=0.5;\n    dipscale=0.3;\n    linecolor = [1 0 0];\n    limit_to_axes = true;\n    \n    % figure out some scaling stuff\n    axun = get(ax,'Units');\n    set(ax,'Units','pixels')\n    p=fix(get(ax,'Position'));\n    set(ax,'Units',axun);\n    \n    % TODO: do something with p and the xlim to come up with an appropriately sized symbol\n    \n    \n    delete(findobj(gcf,'Tag','diptest'))\n    \n    \n    strike = wrapTo360(dipdir-90);\n    scaling = ax.DataAspectRatio;\n    labels = cellstr( num2str(dip) );\n    labels=\"  \"+labels;\n    \n    is_horiz = dip==0;\n    is_vert = dip==90;\n    \n    dx = cosd(strike) .* strikescale ./scaling(2);\n    dy = sind(strike) .* strikescale ./ scaling(1);\n    xx = ([x0,x0,x0] + [-dx, dx, nan(size(x0))])';\n    yy = ([y0,y0,y0] + [-dy, dy, nan(size(y0))])';\n    xx=xx(:);\n    yy=yy(:);\n    \n    hold on;\n    plot(ax,xx,yy,'r','linewidth',1,'Tag','diptest','DisplayName','Strikes')\n    \n    dipx=cosd(dipdir(:))* dipscale./scaling(2);\n    dipy=sind(dipdir(:))* dipscale./scaling(1);\n    xdx = ([x0,x0,x0] + [zeros(size(x0)) - is_vert .* dipx, dipx, nan(size(x0))])';\n    ydy = ([y0,y0,y0] + [zeros(size(y0)) - is_vert .* dipy, dipy, nan(size(y0))])';\n    \n    xdx=xdx(:);\n    ydy=ydy(:);\n    plot(ax,xdx,ydy,'Color',linecolor,'linewidth',1.5,'Tag','diptest','DisplayName','Dips')\n    if any(is_horiz)\n        plot(ax,x0(is_horiz),y0(is_horiz),'o','Color',linecolor,'linewidth',1.5,'Tag','diptest','DisplayName','HorizDips')\n    end\n    if limit_to_axes\n        rangeidx=in_range(x0,xlim) & in_range(y0,ylim);\n        text(ax,x0(rangeidx), y0(rangeidx), labels(rangeidx), 'VerticalAlignment','top',...\n            'HorizontalAlignment','left',...\n            'Tag','diptest',...\n            'Color',linecolor .* 0.66);\n        \n    else\n        text(ax,x0, y0, labels, 'VerticalAlignment','top',...\n            'HorizontalAlignment','left',...\n            'Tag','diptest',...\n            'Color',linecolor .* 0.66);\n    end\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/cgr_utils/plot_strike_dip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5559351839615749}}
{"text": "function [ x_wave ] = wavethresh_2D( x, waveletStages, waveletFilterName, wavecoeffS, lambdaWave, L )\n%\n% (c) Marc Fischer, Thomas Kuestner\n% ---------------------------------------------------------------------\n\n    x_wave_helper = wavedec2(x,waveletStages,waveletFilterName);\n    x_wave_helper = softthresh_real(x_wave_helper,lambdaWave/L);\n    x_wave = waverec2(x_wave_helper,wavecoeffS,waveletFilterName);\n\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_Proximal/wavethresh_2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5559351838523222}}
{"text": "function [xe,Pe,lm_seq] = update_std(xe,Pe,lm_seq,z,R)\n\n\nlenz = length(find(z(3,:)>0));\nlenx = size(xe,1);\n\nglobal gDISTBEAR\n\nnf = 0;\n\n% % update\nfor i= 1:lenz\n    % data association (based on landmark id)\n    % TODO: use nearest neighbor to do the job\n    is_exist = ~(lm_seq - z(3,i));\n    idx = find(is_exist);\n    \n    ii = 2*i+(-1:0);\n    \n    % update: already in the state vecor\n    if ~isempty(idx)\n        nf = nf+1;\n        jj = 2*nf+(-1:0);\n        if gDISTBEAR\n            [zhat,Hii] = measurement_model_std(xe,idx);   %Hekf=Hii\n            H(jj,:) = Hii;\n            r(jj,1) = [ z(1,i)-zhat(1,1);  pi_to_pi(z(2,i)-zhat(2,1)) ];\n            Rf(jj,jj) = R(ii,ii);\n        else\n            [zhat,Hii] = measurement_model_std(xe,idx);   %Hekf=Hii\n            H(jj,:) = Hii;\n            r(jj,1) = [ z(1,i)-zhat(1,1);  (z(2,i)-zhat(2,1)) ];\n            Rf(jj,jj) = R(ii,ii);\n        end\n    end\nend\n\nif nf~=0\n    S = H*Pe*H'+ Rf;\n    S = (S+S')*0.5;\n    \n    if isspd(S)\n        \n        K = Pe*H'/S;\n        xe = xe + K*r;\n        Pe = (eye(length(Pe)) - K*H) * Pe *(eye(length(Pe)) - K*H)' + K*Rf*K';\n        \n    end\nend\n\n\n\n% % augment\nfor i= 1:lenz\n    % data association (known)\n    is_exist = ~(lm_seq - z(3,i));\n    idx = find(is_exist);\n    \n    lenx= size(xe,1);\n    ii = 2*i + (-1:0);\n    \n    % add the new landmark into the state vector\n    if isempty(idx)\n        lm_seq = [lm_seq; z(3,i)];\n        \n        \n        if gDISTBEAR\n            % augment state\n            d = z(1,i);\n            th = z(2,i);\n            k_xL = [d*cos(th); d*sin(th)];\n            \n            x_L = xe(1:2,1) + [ d*cos(th+xe(3)); d*sin(th+xe(3)) ];\n            xe = [xe; x_L];\n            \n            % jacobians\n            J = [0 -1; 1 0];\n            C = [cos(xe(3))  -sin(xe(3));   sin(xe(3))   cos(xe(3)) ];\n            \n            H_Lk = [ 1/norm(k_xL)*k_xL'; 1/norm(k_xL)^2*k_xL'*J' ];\n            \n            HR = - H_Lk* C'*[eye(2)  J*(x_L-xe(1:2,1))];\n            HL = H_Lk* C';\n            \n        else\n            % augment state\n            k_xL = z(1:2,i);\n            \n            C = [cos(xe(3)) -sin(xe(3));  sin(xe(3)) cos(xe(3)) ];\n            x_L = xe(1:2,1) + C*k_xL;\n            xe = [xe; x_L];\n            \n            % jacobians\n            J = [0 -1; 1 0];\n            C = [cos(xe(3))  -sin(xe(3));   sin(xe(3))   cos(xe(3)) ];\n            \n            HR = - C'*[eye(2)  J*(x_L-xe(1:2,1))];\n            HL = C';\n        end\n        \n        \n        V_std = null([HR,HL]);\n        \n        \n        % augment covariance\n        rng= lenx+1:lenx+2;\n        Pe(rng,rng)= inv(HL)*HR*Pe(1:3,1:3)*HR'*inv(HL)' + inv(HL)*R(ii,ii)*inv(HL)'; % landmark cov\n        Pe(rng,1:3)= -inv(HL)*HR*Pe(1:3,1:3); % landmark-robot xcorr\n        Pe(1:3,rng)= Pe(rng,1:3)';\n        if lenx>3\n            rnm= 4:lenx;\n            Pe(rng,rnm)= -inv(HL)*HR*Pe(1:3,rnm);\n            Pe(rnm,rng)= Pe(rng,rnm)';\n        end\n        Pe = 0.5*(Pe+Pe');\n    end\nend\n\n", "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/update_std.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.5558391393409391}}
{"text": "function x = ProxLP(y,p,tau)\n\nif p==Inf\n    p = 1e3;\nend\n\nif length(y(:))>1\n    for i=1:length(y(:))\n        x(i)=ProxLP(y(i),p,tau);\n    end\n    x = reshape(x,size(y));\n    return\nend\n\nx = linspace(0,abs(y)*10,1000);\n[~,k] = min( 1/2*(x-abs(y)).^2 + tau*abs(x).^p );\nx = x(k)*sign(y);\n\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/code/gradflow-metric/ProxLP (Copie en conflit de Gabriel Peyr\u00e9 2017-11-26).m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5558391340312304}}
{"text": "% the basic RIM quantifier: Q(r)=r^alpha\nfunction re=weight1(n,m) % n-length of weighting vector, m - is alpha\nre=[];\nfor h=1:n\n    re=[re ((h/n).^m-((h-1)/n).^m)];\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/38871-similarity-classifier-with-owa-operators/SimClassOWA/owaw1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5558391337405912}}
{"text": "function [Model, Info] = linear_sparse_space_sw(X,Y,Model,parm)\n%  Estimate linear weight matrix for input-output mapping\n%     Automatic Relevance Prior for each input dimension \n%     in original input space (not for delay embedding space)\n%     is imposed to get sparse weight matrix\n%  Trial data with variable sample number is supported \n%     by setting sample number of each trial\n%  Notice !!\n%     Delay embedding is done in this module,\n%     then input vector should be original input data without embedding\n%\n%     Covariance is calculated in original input space,\n%     then increse of embedding dimension make no problem in computation\n% \n%   [Model, Info] = linear_sparse_space_sw(X,Y,Model,parm)\n% --- Input\n%  Y  : Output data ( N x T x Ntrial )\n%  X  : Input data  ( M x (T + (Dtau-1)*Tau)  x Ntrial)\n%  N  =  # of output\n%  M  =  # of input (original input space dimension)\n%  T  =  # of time sample\n%\n%  Estimate the following model\n%    Y(t) = W * [X(:, t + (Dtau-1)*Tau ); ...; X(:, t)]\n%\n%  Model : Structure for estimated model\n%  if Model is empty, initialization is done before training\n%  if Model is previous training result, re-training us done\n%\n%  parm  : Structure for learning parameter\n%  parm.Npre_train :  # of VB-update in initial training\n%  parm.Ntrain :  # of training\n%  parm.Nskip  :  skip # for print\n%  parm.a_min  :  Min value for pruning small variance component\n%  parm.Prune  :  = 1 : Prune small variance & irrelevant input dimension\n%\n%  parm.Tau       = Lag time\n%  parm.Dtau      = Number of embedding dimension\n%    Total input dimension in embedding space is (M * parm.Dtau)\n%  parm.Trial : Valid_sample number for each trial [Ntrial x 1]\n%    if parm.Trial = [15 10] and T = 15, \n%       last 5 samples in 2nd trial is not used for estimation\n% --- Output\n%  Model : Structure for estimated model\n%  Model.SY  :  Noise variance         ( 1 x 1 )\n%  Model.W   :  Weight matrix          ( N x M*D ) , D = parm.Dtau\n%  Model.A   :  Prior weight variance  ( 1 x M*D ) \n%  Model.ix_act : Active index for W after pruning\n%\n%  Info  : Structure for learning process history\n%  Info.FE  = LP + H : Free energy\n%  Info.LP  = Log likelihood\n%  Info.H   = - Model entropy\n%\n% 2009-10-18 Made by M. Sato\n\nMINVAL = 1.0e-15;\nMinCond = 1e-8;\n\nfprintf('Linear sparse space (variable trial length) start\\n')\n\n% Dimension\n[N ,T  ,Ntrial]  = size(Y); % N = # of output\n[M ,Tx ,Ntrialx] = size(X); % M = # of input without embedding\n\n% Number of samples for each trial\nif isfield(parm,'Trial'), \n\tTrial = parm.Trial;\n\tif length(Trial) ~= Ntrial, error('Trial sample seting is wrong');end\n\tif max(Trial) > T, error('Trial sample seting is wrong');end\nelse\n\tTrial = repmat(T, [Ntrial 1]);\nend\n% Set valid sample flag for each trial\ntrial_sw = zeros(N,T,Ntrial);\nfor n = 1:Ntrial\n\ttrial_sw(:,1:Trial(n),n) = 1;\nend\n\t\nTall = sum(Trial);\n\nif Ntrial~=Ntrialx, error('# of trial is different in X and Y'); end;\n\n% # of total training iteration\nNtrain = parm.Ntrain;\n\nNskip  = 100;   % skip steps for display info\na_min  = 1e-10; % Minimum value for weight pruning\nFdiff  = 1e-10; % Threshold for convergence\nNcheck = 100;   % Minimum number of training iteration\nFstep  = 5;     % Free energy convergence check step\nPrune  = 1;     % Prune mode\n\nif isfield(parm,'Nskip'), Nskip  = parm.Nskip; end;\nif isfield(parm,'Fdiff'), Fdiff   = parm.Fdiff; end;\nif isfield(parm,'a_min'), a_min   = parm.a_min ; end;\nif isfield(parm,'Prune'), Prune = parm.Prune; end;\nif isfield(parm,'Ncheck'), Ncheck = parm.Ncheck; end\nif isfield(parm,'Fstep'),Fstep  = parm.Fstep ; end\n\n% # of embedding dimension\nif isfield(parm,'Dtau')\n\tD    = parm.Dtau; \n\ttau  = parm.Tau;\nelse\n\tD    = 1;\n\ttau  = 1;\nend\n\nif Ntrain < 1, Info = []; return; end;\n\nif isfield(parm,'Npre_train')\n\tNpre_train = parm.Npre_train;\nelse\n%\tNpre_train = Ntrain;\n\tif Tall >= 2*M*D\n\t\tNpre_train = 0;\n\telseif Tall >= M*D\n\t\tNpre_train = fix(Ntrain/2);\n\telse\n\t\tNpre_train = Ntrain;\n\tend\nend\n\nif Npre_train > Ntrain, Npre_train = Ntrain; end;\n\nfprintf('--- Output Dimension  = %d\\n',N)\nfprintf('--- Input  Dimension  = %d\\n',M)\nfprintf('--- Embedding  Dimension  = %d\\n',D)\nfprintf('--- Number of trials  = %d\\n',Ntrial)\nfprintf('--- Number of training sample = %d\\n',Tall)\nfprintf('--- Total update iteration    = %d (%d)\\n',Ntrain,Npre_train)\n\n% Original input dimension\nXdim  = M;\nM_ALL = Xdim*D;\n\n%  \n% --- Initialization\n%  W , A : Initial variable to use 1st update\n%  \n\n% Input/Output variance\nsx = mean((X(:) - mean(X(:))).^2);\nsy = mean((Y(:) - mean(Y(:))).^2);\n\nSY0 = mean(sy);\nA0  = 1./mean(sx);\n\nif isfield(parm,'Ta0') && parm.Ta0 > 0,\n\tTa0 = parm.Ta0;\n\ta0  = parm.a0 * A0;\nelse\n\tTa0 = 0;\n\ta0  = 1;\nend\n\n% 'linear_sparse_space'\n%    ARD term = alpha * W^2  : A = W^2\nif isfield(Model,'ix_act')\n\tSY  = mean(Model.SY);  % 1 x 1\n\n\t% Recover old estimate of A in full embedding space\n\tix_act = Model.ix_act;\n\tAold = zeros(1,M_ALL); % 1 x M_ALL\n\tWold = zeros(N,M_ALL);\n\t\n\tAold(ix_act) = sum(Model.A,1);\n\tWold(:,ix_act) = Model.W;\n\n\tif M_ALL ~= Xdim*D,\n\t\tfprintf('M_ALL=%d,Xdim=%d,D=%d\\n',M_ALL ,Xdim ,D)\n\t\terror('M_ALL ~= Xdim*D')\n\tend\n\t% Summation over time delay component\n\tA  = mean(reshape(Aold,[Xdim,D]),2);\t% Xdim x 1\n\t\n\t% Active index in input space without embedding\n\tIX_act = find(A > 0);\n\tA  = A(IX_act);\n\tM  = length(IX_act);\n\t\n\tid  = repmat( (0:(D-1))* Xdim ,[M 1]) + repmat(IX_act, [1 D]);\n\tW   = Wold(:,id(:)) ;  % N x (M*D)\n\n\tX  = X(IX_act,:,:); % M x T\nelse\n\tA = repmat(A0, [Xdim, 1]);\n\tW = zeros(N,M_ALL);\n\tSY  = SY0;\n\t% Save original input index for pruning\n\tIX_act = (1:Xdim)';\nend\n\nrx  = 1/(D + 1);\nSX  = SY*rx;\n\nfprintf('a_min = %g\\n', a_min)\nfprintf('SY0 = %g\\n', SY0)\nfprintf('SY  = %g\\n', SY)\n\n% Active index in input space without embedding\nix_act  = (1:M)';\n\n% Delay embedding index for W\nWid = [(0:(D-1))'* M + 1 , (1:D)'* M];\n\n% Input covariance (Spatial dimension)\nTrial = Trial+(D-1)*tau;\n\nXX = zeros(M,M);\nfor n=1:Ntrial\n\tXX = XX + X(:,1:Trial(n), n) * X(:,1:Trial(n), n)';\nend\nXX  = XX / sum(Trial);\n\nSW = inv( Tall.* XX + diag(1./A) );\n\n% Working variable\ndY  = zeros(N,T,Ntrial);% N x T x Ntrial\ndYX = zeros(N,M*D);     % N x M*D\nG_A = zeros(M,1);       % M x 1\nWW  = sum(reshape(sum(W.^2,1),[M,D]),2);\t% M x 1\n\n% Free energy histry\nFE  = zeros(Ntrain,1);\nLP  = zeros(Ntrain,1);\nH   = zeros(Ntrain,1);\nErr = zeros(Ntrain,1);\nMhist = zeros(Ntrain,1);\n\n% ARD hyper param. history\nif isfield(parm,'Debug') && ~isempty(parm.Debug) && parm.Debug > 0\n\tDebug = 1;\n\tA_tmp = zeros(M_ALL, ceil(Ntrain/Nskip));\nelse\n\tDebug = 0;\nend\n% recover all component\nA_all  = zeros(M,1);\n\nk_save  = 0;\n\n%%%%%% Learning Loop %%%%%%\nfor k=1:Ntrain\n\t% Ainv = alpha , A = 1/alpha\n\tAinv    = 1./A;\t\n\n\t%    dY  = Y - W * X\n\t%    dYX = (dY * X')/T;\n\tdY  = error_delay_time_sw(X, Y, W, tau, Trial); % N x T x Ntrial\n\tdY  = dY .* trial_sw;                           % mask invalid samples\n    dYX = error_corr_delay_sw(X, dY, D, tau, Trial);% N x M*D\n    \n    dYY = sum(dY(:).^2)/(N*Tall); \n    dYX = dYX/(Tall);   \n\n    % Noise variance update\n    WWA = sum(WW .*Ainv);\n    SX  = (rx) .* dYY + WWA/(N*Tall) ;\n\t%  SX  = rx .* dYY + sum(SW(:) .* XX(:)) ./rx ;\n\n    % Prevent zero variance\n    SX  = max( SX, MINVAL);\n\tSY  = SX/rx;\n\t\n    % Log variance\n    SWA     = diag(SW) .* Ainv;\n    log_sw  = (N*D)*(log_det(SW) + sum(log(Ainv)) - sum(SWA) + M);\n    log_sy  = N * sum( log(SY) );\n    log_a   = Ta0*sum(log(Ainv) - a0.*Ainv + 1);\n    \n    % Free energy\n    LP(k)  = - (0.5*Tall) * log_sy ;\n    H(k)   = 0.5*( log_sw + log_a );\n%    H(k)   = 0.5*( log_sw + log_a - WWA );\n    FE(k)  = LP(k) + H(k);\n    Err(k) = sum(dYY)/(SY0);\n\n    % Weight variance\n    % SW = inv( (T./SX) .* XX + diag(Ainv) );   ( M x M )\n    SW  = XX + diag( Ainv./Tall );\n    \n   \tif rcond(SW) > MinCond,\n\t\tSW  = inv( SW );\n\telse\n\t\tSW  = pinv( SW );\n\tend\n\n    % Weight update\n    % W   = (T/SX)*( W * XX + rx .* dYX ) * SW; ( N x MD )\n\tfor j=1:D\n    \tW(:,Wid(j,1):Wid(j,2)) = ( W(:,Wid(j,1):Wid(j,2)) * XX ...\n    \t                       + rx * dYX(:,Wid(j,1):Wid(j,2)) ) * SW;\n    end\n    \n\t%  ARD for each input (average over output & delay)\n\tWW  = sum(reshape(sum(W.^2,1),[M,D]),2);\t\t% M x 1\n\n    % Hyper parameter for weight variance (ARD)\n    SW  = SW /Tall; % = inv(Tall*XX + diag(Ainv))\n%  \tG_A = 1 - diag(SW).*Ainv ;\n%  \t    = diag( ((Tall*XX + Ainv) - Ainv) * SW )\n%  \t    = diag( (Tall*XX) * SW ) \n  \tG_A = Tall*sum(XX.*SW,2);\n\tG_A = max((G_A), MINVAL);\n\t\n\tif k <= Npre_train,\n\t\t% VB update rule (Stable)\n\t\t% (N*D)*A  = WW./SX + (N*D) * diag(SW) \n\t\t% (N*D)*A*(1 - diag(SW)./A)  = WW./SX \n\t\t% Modefied VB update rule (Stable)\n\t\tA  = (WW./SX + (N*D) * diag(SW) + 2*Ta0*a0)/( N*D + 2*Ta0 );\n%\t    A  = sqrt(A.*(WW./SX)./(G_A*N*D));\n\telse\n\t    % Accelerated update rule\n\t    A  = sqrt(A.*(WW./SX)./(G_A*N*D));\n%\t    A  = ((WW./SX) + 2*Ta0*a0)./(G_A*N*D + 2*Ta0);\n\tend\n\t\n    % Prune small variance\n    if Prune > 0\n\t    % Find active input dimension\n\t    ix_act_old = ix_act;\n\t    \n\t    % Recover all component\n\t    switch\tPrune\n\t    case\t1\n\t\t    A_all(ix_act) = WW/max(WW);    % Prune by Weight\n\t    case\t2\n\t\t    A_all(ix_act) = A /max(A);\t   % Prune by Alpha\n\t    case\t3\n\t\t    A_all(ix_act) = A * (1/SX);    % Prune by Alpha\n\t    end\n\t    \n\t    % Find active input dimension (absolute index)\n\t    ix_act = find( A_all > a_min ); % effective indices\n\t    Mnew   = length(ix_act);  \t\t% # of effective input\n\t    \n\t    if Mnew < M,\n\t\t    % convert to relative index\n\t\t    jx_act = trans_index(ix_act,ix_act_old,Xdim);\n\t\t    \n\t\t    A   = A(jx_act) ;  % 1 x M\n\t\t    SW  = SW(jx_act,jx_act);  % M x M\n\n\t\t\t% Effective delay embedding index for W\n\t\t\tid  = repmat( (0:(D-1))* M ,[Mnew 1]) + repmat(jx_act, [1 D]);\n\t\t    W   = W(:,id(:)) ;  % N x MD\n\n\t\t\t% New delay embedding index for W\n\t\t    M   = Mnew;\n\t\t\tWid = [(0:(D-1))'* M + 1 , (1:D)'* M];\n\t\t\t\n\t\t\tWW  = WW(jx_act);\n\t\t    X   = X(jx_act,:,:);  \t % M x T x Ntrial\n\t\t    XX  = XX(jx_act,jx_act); % M x M\n\t\tend\n    else\n\t\tA = max(A,MINVAL);\n    end\n    % END of if Prune == 1\n\tMhist(k) = M;\n\t\n    if mod(k, Nskip)==0\n        % Save history\n\t\tif Debug == 1\n        \tk_save = k_save + 1;\n        \tA_tmp(:,k_save) = A_all(:);\n\t\tend\n\t\t\n        fprintf('Iter=%4d, M =%4d, err=%g, F=%g, H=%g, SY=%g, Wmin=%g\\n',...\n        \t\t        k, M, Err(k), FE(k), -2*H(k)/log(Tall), ...\n        \t\t        SY, min(WW)/max(WW));\n    end\n    \n    % Convergence check\n\tif k > Ncheck,\n\t\tFdif = (FE(k) - FE(k-Fstep))/(abs(FE(k))+eps);\n\telse\n\t\tFdif = Fdiff + 1;\n\tend\n\t\n\tif (Fdiff > abs(Fdif)), \n\t\tfprintf('Converged : Free energy change = %g\\n',Fdif)\n\t\tbreak; \n\tend;\n\t\t\nend\n\n% convert to relative index\nix_act = IX_act(ix_act);\n\n% Delay embedding index for W in full input space\nid  = repmat( (0:(D-1))* Xdim ,[M 1]) + repmat(ix_act, [1 D]);\n% Recover A in full embedding input space\nA   = repmat(A(:), [1 D]);\n\n% Active index\nModel.ix_act = id(:);\nModel.M_all  = M_ALL ;\n\n% Save output variable\nModel.A    = A(:)' ; % 1 x M*D\nModel.W    = W ;\nModel.SY   = SY;\nModel.SW   = SW; % = inv(Tall*XX + diag(Ainv))\n\nModel.method = 'linear_sparse_space';\nModel.mode   = 'cov';\nModel.sparse = 'sparse';\n\n% Save history\nInfo.FE  = FE(1:k);\nInfo.LP  = LP(1:k);\nInfo.H   = H(1:k) ;\nInfo.Err = Err(1:k);\nInfo.M   = Mhist(1:k);\n\nif exist('A_tmp','var')\n\tInfo.A   = A_tmp(:,1:k_save) ;\nend\n\n%%% ---- Index transformation from old active_index to current active_index\nfunction\tjx = trans_index(ix,ix_old,M)\n\nN = length(ix_old);\nItrans = zeros(M,1);\nItrans(ix_old) = 1:N;\n\njx = Itrans(ix);\n", "meta": {"author": "KamitaniLab", "repo": "GenericObjectDecoding", "sha": "c98f24370668109fd9978bc8b43a33bd43926f47", "save_path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding", "path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding/GenericObjectDecoding-c98f24370668109fd9978bc8b43a33bd43926f47/code/matlab/lib/SPR_2009_12_17/linear_sparse_space_sw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505966, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5558391287215214}}
{"text": "function tx = updateFastBoundaryClassifierFeatures(X, s1, s2, eid)\n% tx = updateFastBoundaryClassifierFeatures(X, s1, s2, eid)\n%\n% Computes a simple set of features based on two regions s1 and s2, each\n% containing one or more segments from X and separated by edglets given by\n% eid.\n\n\nng = 5; % five geometric classes\n\ntx = zeros([1 33], 'single');\n\nf = 0;\n\n\n%% Edge features\ntx(f+1) = sum(X.edge.pb(eid).*X.edge.length(eid)) / sum(X.edge.length(eid));\n    \narea1 = X.region.area(s1);\narea2 = X.region.area(s2);\n\nf = f+1;\n\n%% Region features\n\n% area\nsumarea1 = sum(area1);\nsumarea2 = sum(area2);\ntx(f+(1:2)) = [min([sumarea1 sumarea2], [], 2) max([sumarea1 sumarea2], [], 2)];\n\n% color\nmeanColor1 = sum(X.region.colorMean(s1, :).*[area1 area1 area1], 1) / sumarea1;\nmeanColor2 = sum(X.region.colorMean(s2, :).*[area2 area2 area2], 1) / sumarea2;\ntx(f+3) = sqrt(sum((meanColor1-meanColor2).^2, 2));\n\n% position\nleft1 = min(X.region.x(s1, 1));  right1 = max(X.region.x(s1, 3));\nleft2 = min(X.region.x(s2, 1));  right2 = max(X.region.x(s2, 3));\nbot1 = min(X.region.y(s1, 1));  top1 = max(X.region.y(s1, 3));\nbot2 = min(X.region.y(s2, 1));  top2 = max(X.region.y(s2, 3));\n\ntx(f+4) = top1-top2;\ntx(f+5) = bot1-bot2;\ntx(f+6) = top1-bot2; \ntx(f+7) = bot1-top2;\ntx(f+8) = top1-bot1;\ntx(f+9) = top2-bot2;\ntx(f+10) = left1-left2;\ntx(f+11) = right1-right2;\ntx(f+12) = right1-left1;\ntx(f+13) = right2-left2; \n\n% x alignment\nx1 = [left1 right1]; \nx2 = [left2 right2]; \ntx(f+14) = (min([x1(:, 2) x2(:, 2)], [], 2)-max([x1(:, 1) x2(:, 1)], [], 2)) ./ ...\n    (max([x1(:, 2) x2(:, 2)], [], 2)-min([x1(:, 1) x2(:, 1)], [], 2));\n\n% y overlap\ny1 = [bot1 top1]; \ny2 = [bot2 top2]; \ntx(f+15) = (min([y1(:, 2) y2(:, 2)], [], 2)-max([y1(:, 1) y2(:, 1)], [], 2)) ./ ...\n    (max([y1(:, 2) y2(:, 2)], [], 2)-min([y1(:, 1) y2(:, 1)], [], 2));\n\nf = f + 15;\n\n\n%% 3D Geometry features\n\n% geometric context features\ngc = X.region.geomContext;\ngc1 = sum(gc(s1, :).*repmat(area1, [1 size(gc, 2)]), 1) / sumarea1;\ngc2 = sum(gc(s2, :).*repmat(area2, [1 size(gc, 2)]), 1) / sumarea2;\n\ntx(f+(1:ng)) = gc1;\ntx(f+ng+(1:ng)) = gc2;\ntx(f+2*ng+(1:ng)) = gc1-gc2; \ntx(f+3*ng+1) = sum(abs(gc1-gc2), 2)/2;\n\n[maxval1, maxlab1] = max([gc1(:, 1) sum(gc1(:, 2:4), 2) gc1(:, 5)], [], 2);\n[maxval2, maxlab2] = max([gc2(:, 1) sum(gc2(:, 2:4), 2) gc2(:, 5)], [], 2);\ntx(f+3*ng+2) = (maxlab1-1)*3+ maxlab2;\n\nf= f + 17;\n\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/iccv07Final/src/updateFastBoundaryClassifierFeatures.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.5558391169395474}}
{"text": "function F = constraint(X,quantifier,Y)\n% Internal class for constraint list\n\nsuperiorto('sdpvar');\nsuperiorto('double');\nsuperiorto('logical');\n\n% Evaluate\nswitch quantifier\n    case '>'\n        Z = X - Y;      \n    case '>='\n        Z = X - Y;     \n    case '<'\n        Z = Y - X;      \n    case '<='\n        Z = Y - X;\n    case '=='\n        Z = Y - X;      \n    otherwise\n        error('Quantifier not supported')\nend\n\nif isa(Z,'double')\n    \n    if  size(Z,1)==size(Z,2) &&  norm(Z-Z',inf)<1e-12 && ~isequal(quantifier,'==')\n        checkSDP = 1;\n    else\n        checkSDP = 0;\n    end\n    \n    if checkSDP\n        if min(eig(Z))>=0\n            warning('Inequality constraint evaluated to trivial true.')\n            F = [];\n            return\n        else\n            error('Inequality constraint evaluated to trivial false (no decision variable in constraint)')            \n        end\n    else\n        Z = Z(:);\n        switch quantifier\n            case '=='\n                if all(Z)==0\n                    warning('Equality constraint evaluated to trivial true.')\n                    F = [];\n                    return\n                else\n                    error('Equality constraint evaluated to trivial false (no decision variable in constraint)')\n                end\n            case {'<=','>='}\n                if all(Z>=0)\n                    warning('Inequality constraint evaluated to trivial true.')\n                    F = [];\n                    return\n                else\n                    error('Inequality constraint evaluated to trivial false (no decision variable in constraint)')\n                end\n            case {'<','>'}\n                if all(Z>0)\n                    warning('Inequality constraint evaluated to trivial true.')\n                    F = [];\n                    return\n                else\n                    error('Inequality constraint evaluated to trivial false (no decision variable in constraint)')\n                end\n        end\n    end\nend\n\nswitch quantifier\n    case {'>','<'}\n        F.strict(1) = 1;\n    case {'>=','<=','=='}\n        F.strict(1) = 0;\n    otherwise\n        error('Quantifier not supported')\nend\nif isa(Z,'sdpvar') && ~isequal(quantifier,'==')\n    if issquare(Z)\n        if ~ishermitian(Z)\n            warning('YALMIP:SuspectNonSymmetry','Suspect non-symmetry in square constaint <a href=\"yalmip.github.io/inside/debuggingnonsymmetricsquare\">(Learn more)</a> ')            \n        end\n    end\nend\nF.List={X,quantifier,Y};\nF.Evaluated{1} = Z;\nF.ConstraintID = yalmip('ConstraintID');\nF.tag{1} = '';\nF = class(F,'constraint');\n\t", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/@constraint/constraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.555839106610769}}
{"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%==============================================================================\n%\n% function [yc,y1,y2,y3] = grid2grid(yc,m,in,out)\n%\n% transfers input grid (c,s,n) to output grid (c,s,n) using inter- and extrapolation\n% central operation are reduce/expand, acting on each dimension individually\n%\n% Input:\n%   yc        input grid\n%   m         number of discretization points\n%   in        type of input grid\n%   out       type of output grid\n% Output:\n%   yc        output grid\n%   y1,y2,y3  components of yc\n%\n%==============================================================================\n\nfunction [yc,y1,y2,y3] = grid2grid(yc,m,in,out)\n\nif nargin == 0, % help and minimal example\n  runMinmalExample;\n  return;\nend;\n\ndim = length(m);  y{1} = []; y{3} = []; y{3} = [];\nif ~exist('out','var'), out = in;  end;\n\nswitch in,\n  case {'centered','cell-centered'}, n = prod(m);\n    % decompose Yin\n    for j=1:dim, y{j} = reshape(yc((j-1)*n+(1:n)),m); end;\n    switch out,\n      case {'centered','cell-centered'},\n      case 'staggered', for j=1:dim, y{j} = extend(y{j},j); end;\n      case 'nodal',\n        for j=1:dim,\n          for k=1:dim, y{j} = extend(y{j},k); end;\n        end;\n    end;\n    \n  case 'staggered',\n    % decompose Yin, get dimensions right\n    E = eye(dim) + m'*ones(1,dim); n = cumsum([0,prod(E)]);\n    for j=1:dim, y{j} = reshape(yc(n(j)+1:n(j+1)),E(:,j)'); end;\n    switch out,\n      case {'centered','cell-centered'}, for j=1:dim, y{j} = reduce(y{j},j); end;\n      case 'staggered',\n      case 'nodal',\n        for j=1:dim,\n          for k=setdiff(1:dim,j), y{j} = extend(y{j},k); end;\n        end;\n    end;\n    \n  case 'nodal', n = prod(m+1);\n    % decompose Yin\n    for j=1:dim, y{j} = reshape(yc((j-1)*n+(1:n)),m+1); end;\n    switch out,\n      case {'centered','cell-centered'},\n        for j=1:dim, for k=1:dim, y{j} = reduce(y{j},k); end; end;\n      case 'staggered',\n        for j=1:dim, for k=setdiff(1:dim,j) y{j} = reduce(y{j},k); end; end;\n      case 'nodal',\n    end;\n    \n  otherwise,\n    error('can not interpret flags')\nend;\ny1 = y{1}; y2 = y{2}; y3 = y{3}; yc = [y1(:);y2(:);y3(:)];\n\n%------------------------------------------------------------------------------\n\n% the following operators act on x=y{k} in the j-th direction,\n% permuting x makes j the first direction, averaging (extend creates two\n% additional outside points based on linear BC) and permute back\n\nfunction x = reduce(x,j)\nm = size(x); J = [j,setdiff(1:length(size(x)),j)];\nx = permute(x,J); x = (x(1:end-1,:,:)+x(2:end,:,:))/2; x = ipermute(x,J);\n\nfunction x = extend(x,j)\nm = size(x); J = [j,setdiff(1:length(size(x)),j)]; x = permute(x,J);\nx = [1.5*x(1,:,:)-0.5*x(2,:,:);(x(1:end-1,:,:)+x(2:end,:,:))/2;...\n  1.5*x(end,:,:)-0.5*x(end-1,:,:)];\nx = ipermute(x,J);\n\n%------------------------------------------------------------------------------\n\nfunction runMinmalExample\nhelp(mfilename);\nomega = [0,6,0,4]; m = [4 3];\n\nh   = (omega(2:2:end)-omega(1:2:end))./m;\neps = 0.2*min(h);\n\nyC  = getCellCenteredGrid(omega,m); %yC = yC + eps*randn(size(yC));\nyN  = reshape(getNodalGrid(omega,m),[],2);\nyS  = getStaggeredGrid(omega,m);\n\nyCN = grid2grid(yC,m,'centered','nodal');\nyCS = grid2grid(yC,m,'centered','staggered');\nySN = grid2grid(yS,m,'staggered','nodal');\nySC = grid2grid(yS,m,'staggered','centered');\nyNC = grid2grid(yN,m,'nodal','centered');\nyNS = grid2grid(yN,m,'nodal','staggered');\n\nyC  = reshape(yC, [],2);\nyN  = reshape(yN, [],2);\nyCN = reshape(yCN,[],2);\nySN = reshape(ySN,[],2);\nySC = reshape(ySC,[],2);\nyNC = reshape(yNC,[],2);\n\n\nFAIRfigure(1); clf;\n\nsubplot(3,2,1);\nplotGrid(yN,omega,m,'color','g'); hold on;\nplot(yC(:,1),yC(:,2),'bs');\nplot(yCN(:,1),yCN(:,2),'m*');\ntitle(sprintf('%s: example cell-centered to nodel',mfilename)); \n\nsubplot(3,2,2);\nplotGrid(yN,omega,m,'color','g'); hold on;\nplot(yC(:,1),yC(:,2),'bs');\n[y11,y12,y21,y22] = splittStaggeredGrid(yCS,omega,m);\nplot(y11,y12,'m>',y21,y22,'m^');\ntitle(sprintf('%s: example cell-centered to staggered',mfilename)); \n\n[y11,y12,y21,y22] = splittStaggeredGrid(yS,omega,m);\nsubplot(3,2,3);\nplotGrid(yN,omega,m,'color','g'); hold on;\nplot(y11,y12,'b>',y21,y22,'b^');\nplot(ySC(:,1),ySC(:,2),'ms');\ntitle(sprintf('%s: example staggered to cell-centered',mfilename)); \n\nsubplot(3,2,4);\nplotGrid(yN,omega,m,'color','g'); hold on;\nplot(y11,y12,'b>',y21,y22,'b^');\nplot(ySN(:,1),ySN(:,2),'m*');\ntitle(sprintf('%s: example staggered to nodal',mfilename)); \n\nsubplot(3,2,5);\nplotGrid(yN,omega,m,'color','g'); hold on;\nplot(yN(:,1),yN(:,2),'b*');\nplot(yNC(:,1),yNC(:,2),'ms');\ntitle(sprintf('%s: example nodal to cell-centered',mfilename)); \n\nsubplot(3,2,6);\nplotGrid(yN,omega,m,'color','g'); hold on;\nplot(yN(:,1),yN(:,2),'b*');\n[y11,y12,y21,y22] = splittStaggeredGrid(yNS,omega,m);\nplot(y11,y12,'m>',y21,y22,'m^');\n\ntitle(sprintf('%s: example nodal to staggered',mfilename)); \n\n%------------------------------------------------------------------------------\n\nfunction [y11,y12,y21,y22] = splittStaggeredGrid(yS,omega,m);\ndim = length(omega)/2;\ne  = @(i) (1:dim == i); % i-th unit vector\nns = cumsum([0;prod(ones(dim,1)*m+eye(dim),2)]);\nyN = reshape(grid2grid(yS,m,'staggered','nodal'),[m+1,2]);\ny11 = reshape(yS(ns(1)+1:ns(2)),m+e(1));\ny12 = (yN(:,1:end-1,2)+yN(:,2:end,2))/2;\ny21 = (yN(1:end-1,:,1)+yN(2:end,:,1))/2;\ny22 = reshape(yS(ns(2)+1:ns(3)),m+e(2));\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/numerics/grid2grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5558245564078628}}
{"text": "% Originally Coded By: Niall Mangan\n% Copyright 2017, All Rights Reserved\n% Code by Niall Mangan for paper \"Inferring biological networks by sparse\n% identification of nonlinear dynamics\"\n% by N. M. Mangan S. L. Brunton, J. L. Proctor, and J. N. Kutz\n% Original Code: https://github.com/niallmm/iSINDy\n%%\n% This file is modified to compare the performance of i-SINDy on\n% insufficient data.\n% Modified by:K, 2019/07/16\n% Find equations for yeast glycolysis state variable 6\n%%\nclc;clear all;close all;\n\naddpath('./utils');\naddpath('./bioutils');\nFolderName='Results2';\n\n% define libarary parameters\nlaurentorder = 0;\npolyorder = 6;\nusesine = 0;\ndyorder = 1;\n\n% clear variables from other solutions.\nclear Theta Thetastring Xi indTheta lambdavec numterms errorv indopt\nclear indTheta1 Xi1 numterms1 nT\n\n% Here we load the previously simulated data\nload('TrainingData.mat')\n\n%% Define some parameters for the implicit SINDy\n% Initial lambda value, which is the value used for soft thresholding in ADM\n% To make implicit SINDy work, you need to carefully tune these two\n% parameters. The below values are the best one that I found.\ntol = 1e-4;\nlambda = 3e-4;\n\n% counter\njj = 1;\n\n% initialize the number of nonzero terms found for the lambda\nnum= 1;\nerrorvec= 0;\n\n% Define maximum iteration you need\nMaxIter = 1000;\n\n% Plot option, we set it to zero\nplottag=0;\n\n% Define the for loop\npercent_start=0.3;\npercent_end=1;\nd_percent=0.1;\n\n% Define how many results you want to get for each percentage\nN_Iter=20;\n\nfor iter=1:N_Iter\n    for percent=percent_start:d_percent:percent_end\n        fprintf('\\n\\n\\t Using %i percent of the data...\\n',percent*100)\n        \n        fprintf('\\n\\t\\t Calculating for the %i time...\\n',iter)\n        % Get the data length\n        new_length=round(percent*length(xt));\n        \n        % Shuffel the original data\n        Sequence=randperm(size(xt,1));\n        xt_dum=xt(Sequence,:);\n        dxt_dum=dxt(Sequence,:);\n        \n        % Assign the value to the new variables\n        Data=xt_dum(1:new_length,:);dData=dxt_dum(1:new_length,:);\n        \n        % Define the number of states\n        n=size(Data,2);\n        \n        % pool Data  (i.e., build library of nonlinear time series)\n        [Theta, Thetastring] = poolDatady(Data,n,polyorder,usesine, laurentorder, dData(:,6), dyorder);\n        \n        % for now calculate null space using null function\n        nT = null(Theta);\n        \n        % Get the sparse vector\n        tic\n        [indTheta1, Xi1, numterms1] = ADMinitvary(nT,lambda,MaxIter,tol, plottag);\n        fprintf('\\t\\t\\t Calculation finished! Used %d seconds.\\n',toc)\n        \n        % Save the calculation result of current iteration\n        fprintf('\\n\\t\\t\\t\\t Saving the result...\\n')\n        tic\n        cc=clock;\n        ResultName=strcat(FolderName,'/implicit_SINDY_Data_Length_',num2str(percent*100),'_','Iter',num2str(iter),'_',num2str(cc(3)),'_',num2str(cc(4)),'_',num2str(cc(5)),'_',num2str(round(cc(6))),'.mat');\n        save(ResultName,'Xi1','indTheta1','percent')\n        fprintf('\\n\\t\\t\\t\\t Saving finished! Using %i seconds...\\n',toc)\n        \n    end\nend\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Comparison/DataLength/YeastGlycolysis/iSINDy/S6_yeast_glycolysis_SwipeLength.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5558245449258814}}
{"text": "function [ fx ] = f_BSLinGame(x,theta,u,in)\n% evolution function for BSL learner engaging in dyadic games\n% [ fx ] = f_BSLinGame(x,theta,u,in)\n% BSL is simply tracking the log-odds of P(o_t=1|o_{t-1}), where o is the\n% opponent's binary action. This variable is updated according to a\n% Laplace-Kalman filter, yielding 2 sufficient statistics (m and V) per\n% combination of past outcome. BSL can learn sequences of arbitrary depth\n% (K). For example, if K=1, then BSL tracks 2 probabilities, namely: \n% P(o_t=1|o_{t-1}=1) and P(o_t=1|o_{t-1}=0). More generally, BSL tracks 2^K\n% probabilities. In this scheme, the only evolution param (theta) is BSL's\n% prior volatity about the log-odds.\n% Note: unsampled sequences will eventually be \"forgotten\", since the\n% prediction step in the Laplace-Kalman update will dilute any previously\n% sampled evidence.\n% IN:\n%   - x: sufficient statistics of log-odds of P(o=1):\n%       x(1:2^K)= E[log-odds]\n%       x((2^K)+1:2^(K+1))= log V[log-odds]\n%   - theta: BSL's prior volatity\n%   - u: sequence of past outcomes:\n%       u(1)= opponent's last move\n%       u(2)= learner's last move\n%       u(3:K+2) = sequence of K past opponent's moves\n%   - in: depth of sequence learning\n% OUT:\n%   - fx: updated sufficient statistics of log-odds of P(o=1)\n\nif VBA_isWeird (u) % e.g., 1st trial\n    fx = x;\n    return\nend\n\nu(2) = []; % remove agent's previous move\n[fx] = f_BSL(x,theta,u,in);", "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_BSLinGame.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5558028033300568}}
{"text": "function [elem2dof,dofSign,edge] = dofBDM1(elem)\n%% DOFBDM1 dof structure for BDM1 element\n%\n% [elem2dof,dofSign,edge] = dofBDM1(elem) constructs data structure for\n% the BDM face element in 3-D. elem is the connectivity matrix for a 3-D\n% triangulation. elem2dof is the elementwise pointer from elem to dof\n% indices. dofSign records the consistency of the local and global edge\n% orientation. edge is the edge matrix.\n%\n% Added by Ming Wang.\n%\n%  See also dof3BDM1, dofRT0, dof3RT0\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n[elem2edge,dofSign,edge] = dofRT0(elem);\nNT = size(elem,1);  NE = size(edge,1);\ntotaledge = uint32([elem(:,[2 3]); elem(:,[3 1]); elem(:,[1 2])]);\n[tempvar,i] = sort(totaledge,2); %#ok<*ASGLU>\n[tempvar,j]= sort(i,2);\nelem2dof = repmat(elem2edge(:),1,2) + uint32((j-1)*NE);\nelem2dof = reshape(elem2dof(:),NT,6);\ndofSign = repmat(dofSign,1,2);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/dof/dofBDM1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5557974478470262}}
{"text": "% Test file for @chebfun/join.m.\n\nfunction pass = test_join(pref)\n\nif ( nargin == 0  )\n    pref = chebfunpref();\nend\n\n% Generate a few random points in [-1 1] to use as test values.\nseedRNG(7681);\nxr = 2 * rand(1000, 1) - 1;\n\n% Check scalar CHEBFUNs.\nf_op = @sin;\nf1 = chebfun(f_op, [-1 -0.5 0]);\nf2 = chebfun(f_op, [0 0.5 1]);\nf = join(f1, f2);\npass(1) = norm(feval(f, xr) - f_op(xr), inf) < 10*vscale(f)*eps;\n\n% Check array-valued CHEBFUNs.\nf_op = @(x) [sin(x) cos(x)];\nf1 = chebfun(f_op, [-1 -0.5 0]);\nf2 = chebfun(f_op, [0 0.5 1]);\nf = join(f1, f2);\nerr = feval(f, xr) - f_op(xr);\npass(2) = norm(err(:), inf) < 10*vscale(f)*eps;\n\n% Check for quasimatrices.\nf1q = quasimatrix(f1);\nf2q = quasimatrix(f2);\nfq = join(f1q, f2q);\nerr = feval(fq, xr) - f_op(xr);\npass(3) = norm(err(:), inf) < 10*vscale(fq)*eps;\n\n% Check row CHEBFUNs.\nft = join(f1.', f2.');\nerr = feval(ft, xr) - f_op(xr).';\npass(4) = ft.isTransposed && (norm(err(:), inf) < 10*vscale(ft)*eps);\n\n% Check row quasimatrices.\nftq = join(f1q.', f2q.');\nerr = feval(ftq, xr) - f_op(xr).';\npass(5) = ftq(1,:).isTransposed && (norm(err(:), inf) < 10*vscale(ftq)*eps);\n\n% Check operation when the domains don't match.\nf = chebfun(@sin, [-1 -0.5 0]);\ng = chebfun(@cos, [1 1.5 2]);\nh = join(f, g);\npass(6) = isequal(h.domain, [-1 -0.5 0 0.5 1]) && ...\n    norm(feval(h, xr) - h_exact_fun(xr), inf) < 10*vscale(h)*eps;\n\n% Check error conditions.\ntry\n    f = join(f1, f2.');\n    pass(7) = false;\ncatch ME\n    pass(7) = strcmp(ME.identifier, 'CHEBFUN:CHEBFUN:join:columnJoin:trans') ...\n        || strcmp(ME.identifier, 'CHEBFUN:CHEBFUN:join:dim');\nend\n\n% Test for singular function:\nop1 = @(x) sin(x)./(x+1);\nop2 = @(x) sin(x);\nf = chebfun(op1, [-1 -0.5 0], 'exps', [-1 0 0]);\ng = chebfun(op2, [1 2]);\nh = join(f, g);\nx = sort(xr);\nh_vals = feval(h, x);\nind = ( x < 0 );\nindComp = ~ind;\nh_exact1 = feval(op1, x(ind));\nh_exact2 = feval(op2, x(indComp)+1);\nh_exact = [h_exact1; h_exact2];\nerr = h_exact - h_vals;\npass(8) = isequal(h.domain, [-1 -0.5 0 1]) && ...\n    norm(err, inf) < 1e5*vscale(h)*eps;\n\n% Test for function defined on unbounded domain:\n\n% Set the domain:\ndomf = [-Inf -3];\ndomg = [1 Inf];\ndomCheck = [-1e2 1e2];\n\n% Generate a few random points to use as test values:\nx = diff(domCheck) * rand(100, 1) + domCheck(1);\n\nopf = @(x) x.*exp(x);\nf = chebfun(opf, domf);\nopg = @(x) (1-exp(-x))./x;\ng = chebfun(opg, domg);\nh = join(f, g);\nx = sort(x);\nh_vals = feval(h, x);\nind = ( x < -3 );\nindComp = ~ind;\nh_exactf = feval(opf, x(ind));\nh_exactg = feval(opg, x(indComp) + (domg(1) - domf(2)));\nh_exact = [h_exactf; h_exactg];\nerr = h_exact - h_vals;\npass(9) = isequal(h.domain, [-Inf -3 Inf]) && ...\n    norm(err, inf) < 1e1*vscale(h)*eps;\n\n\nend\n\nfunction y = h_exact_fun(x)\n    y = zeros(size(x));\n\n    xl_ind = x <= 0;\n    xl = x(xl_ind);\n    y(xl_ind) = sin(xl);\n\n    xr_ind = x > 0;\n    xr = x(xr_ind);\n    y(xr_ind) = cos(xr + 1);\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun/test_join.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.5557974433411967}}
{"text": "function c = band(a,p,q)\n%BAND         Extract band from matrix a, lower bandwidth p, upper bandwidth q\n%   if parameter q is omitted, q:=p\n%\n%   c = band(a,p,q)\n%\n\n% written  10/16/98     S.M. Rump\n% modified 11/30/98     S.M. Rump  improved speed\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%\n\n  if nargin<3\n    q = p;\n  end\n\n  c = a;\n\n  if a.complex\n    c.mid = tril(triu(a.mid,-p),q);\n    c.rad = tril(triu(a.rad,-p),q);\n  else\n    c.inf = tril(triu(a.inf,-p),q);\n    c.sup = tril(triu(a.sup,-p),q);\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/band.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5557974433411966}}
{"text": "function [pd, labels] = imPerimeterDensity(img, varargin)\n% Perimeter density of a 2D binary structure, using Crofton formula.\n%\n%   Pv = imPerimeterDensity(IMG)\n%\n%   Example\n%   imPerimeterDensity\n%\n%   See also\n%     imPerimeter\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% Created: 2010-01-21,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n\n%% Pre-processing\n\n% check image dimension\nif ndims(img) ~= 2 %#ok<ISMAT>\n    error('first argument should be a 2D image');\nend\n\n% in case of a label image, return a vector with a set of results\nif ~islogical(img)\n    % extract labels (considers 0 as background)\n    labels = unique(img);\n    labels(labels==0) = [];\n    \n    % allocate result array\n    nLabels = length(labels);\n    pd = zeros(nLabels, 1);\n\n    props = regionprops(img, 'BoundingBox');\n    \n    % compute perimeter of each label considered as binary image\n    for i = 1:nLabels\n        label = labels(i);\n        bin = imcrop(img, props(label).BoundingBox) == label;\n        pd(i) = imPerimeterDensity(bin, varargin{:});\n    end\n    \n    return;\nend\n\n\n%% Extract input arguments\n\n% in case of binary image, compute only one label\nlabels = 1;\n\n% default number of directions\nnDirs = 4;\n\n% default image resolution\ndelta = [1 1];\n\n% parse parameter name-value pairs\nwhile ~isempty(varargin)\n    var = varargin{1};\n    \n    if isnumeric(var)        \n        % option is either number of directions or resolution\n        if isscalar(var)\n            nDirs = var;\n        else\n            delta = var;\n        end\n        varargin(1) = [];\n        \n    elseif ischar(var)\n        if length(varargin) < 2\n            error('Parameter name must be followed by parameter value');\n        end\n    \n        if strcmpi(var, 'ndirs')\n            nDirs = varargin{2};\n        elseif strcmpi(var, 'resolution')\n            delta = varargin{2};\n        else\n            error(['Unknown parameter name: ' var]);\n        end\n        \n        varargin(1:2) = [];\n    end\nend\n\n\n%% Compute perimeter within image, and normalize by area\n\n% component area in image\np = imPerimeterEstimate(img, nDirs, delta);\n\n% total area of image, without borders\ntotalArea = prod(size(img)-1) * prod(delta);\n\n% compute perimeter density\npd = p / totalArea;\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMinkowski/imPerimeterDensity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.555797438835367}}
{"text": "function ind = rhoInside(rho,minRho,maxRho)\n\nminr = mod(minRho+1e-6,2*pi)-3e-6; % in [-2e-6,2*pi-3e-6]\nmaxr = mod(maxRho-1e-6,2*pi)+3e-6; % in [2e-6,2*pi+3e-6]\n\nif minr < 0\n  rho = mod(rho+1e-6,2*pi);\nelse\n  rho = mod(rho-1e-6,2*pi);\nend\n\nif minr < maxr\n  ind = rho > minr & rho < maxr;\nelse\n  ind = rho > minr | rho < maxr;\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/tools/math_tools/rhoInside.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5557974310000316}}
{"text": "function out=cot(x)\n\nout=cos(x)./sin(x);\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/cot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5557306754224848}}
{"text": "function [EB] = bit2EB(bit)\n% Convert computery things from bits to exabytes.\n% Chad A. Greene 2012\nEB = bit*2^-63;", "meta": {"author": "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/bit2EB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156295, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.555712133359739}}
{"text": "function IntegrateEuler(j)\n% following Featherstone \"Robot Dynamics Algorithm\" p.103\n% '04 May 8 s.k AIST  \nglobal uLINK Dtime\n\nif j == 0 return; end\nif j == 1\n    [uLINK(j).p, uLINK(j).R] = SE3exp(j, Dtime);    \n    uLINK(j).vo = uLINK(j).vo + Dtime * uLINK(j).dvo;\n    uLINK(j).w  = uLINK(j).w  + Dtime * uLINK(j).dw;    \n    %IntegrateSE3(j, Dtime);\nelse\n    uLINK(j).q  = uLINK(j).q  + Dtime * uLINK(j).dq;\n    uLINK(j).dq = uLINK(j).dq + Dtime * uLINK(j).ddq;\nend\n\nIntegrateEuler(uLINK(j).sister);\nIntegrateEuler(uLINK(j).child);\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/IntegrateEuler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5556606592501756}}
{"text": "function [distancemap]=surfacemap(Vertices,faces,Index)\n\n%this function defines how many vertices each vertex is away from the\n%specifc vertex with index \"Index3\". \n\n%the first collumn gives the vertex indices, the second the number of\n%vertices each vertex is distant from the Index vertix\n%the third collumn gives the \"weigth\" for each, meaning the number of\n%vertices of the same generation devided by the total number of vertices\n\nfaces(:,4)=1:length(faces);\ndistancemap(:,1)=1:length(Vertices(:,1));\ndistancemap(Index,2)=1;\ndistancemap(Index,3)=1-length(double(find(distancemap(:,2))))/length(Vertices(:,1));\n\n\na=2;\nfacestemp1(1,1)=Index;\n\nwhile isempty(faces)==0 \n\n    indicesconnectedfaces=vertcat(find(double(ismember(faces(:,1),facestemp1))),find(double(ismember(faces(:,2),facestemp1))),find(double(ismember(faces(:,3),facestemp1))));\n    connectedfaces=faces(indicesconnectedfaces,:);\n    indicesvertices=unique(reshape(connectedfaces(:,1:3),3*length(connectedfaces(:,1)),1));\n    distancemap(indicesvertices,2)=a;\n    faces(indicesconnectedfaces,:)=[];\n    \n    indicesoldvertces=find(double(ismember(indicesvertices,facestemp1)));\n    distancemap(indicesvertices(indicesoldvertces,:),2)=a-1;\n    indicesvertices(indicesoldvertces,:)=[];\n    facestemp1=indicesvertices;\n    distancemap(indicesvertices,3)=1-length(double(find(distancemap(:,2))))/length(Vertices(:,1));\n    a=a+1;\nend\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41396-nonrigidicp/nonrigidICP/surfacemap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5556606567829409}}
{"text": "% Calculate border coverage for detected fields in a circular arena\n%\n% This function calculates firing map border coverage that is further used\n% in calculation of a border score. This function must be used with recordings\n% done in a circular environment. See USAGE for details.\n%\n%  USAGE\n%   coverage = analyses.borderCoverageCircular(fieldsMap, <options>)\n%   fieldsMap   2D binary matrix that repressents firing properties of the field.\n%               fieldsMap must be a polar version of a regular firing rate map. This\n%               means that x-axis should contain values in range 1-360, y-axis range\n%               is 1 to radius of the circular arena.\n%               fieldsMap should contain NaN for unvisited bins. Other possible values:\n%               0 for zero firing rate, i.e. area that doesn't belong to a fields.\n%               Any positive number marks an area of a field. For example, if there is\n%               just a single field, then fieldsMap could consist of 3 values: NaNs, zeros,\n%               and ones.\n%   <options>   Optional list of property-value pairs (see table below)\n%\n%   ==============================================================================================\n%    Properties    Values\n%   ----------------------------------------------------------------------------------------------\n%    'searchWidth'  If map is not perfect, but contains NaN values along borders, then\n%                   search for border pixels can have NaNs. To mitigate this, we check\n%                   searchWidth rows/columns near border and if the closest to the border pixel\n%                   equals to NaN, we search for first non-NaN value in searchWidth rows/columns.\n%                   This argument is optional and default value is 8 bins.\n%    'walls'        Definition of walls along which the coverage is calculated. Provided by\n%                   a 2D matrix Nx2. Each row defines 1 wall. Each row should have two values in degrees:\n%                   1. angle at which wall starts.\n%                   2. angle at which wall ends.\n%                   Default value is [1 360], which represents a single wall around the whole circular\n%                   environment. Note that you can not use 0 as an angle.\n%   ==============================================================================================\n%   coverage    Border coverage, ranges from 0 to 1.\n%\nfunction coverage = borderCoverageCircular(fieldsMap, varargin)\n    coverage = 0;\n\n    inp = inputParser;\n    defaultSearchWidth = 8;\n    defaultWalls = [1 360];\n\n    checkSearchWidth = @(x) isnumeric(x) && isscalar(x) && (x > 0);\n    checkWalls = @(x) size(x, 2) == 2 && all(x(:) > 0) && all(x(:) <= 360);\n\n    addRequired(inp, 'fieldsMap', @(x) isnumeric(x) && size(x, 2) == 360);\n    addParameter(inp, 'searchWidth', defaultSearchWidth, checkSearchWidth);\n    addParameter(inp, 'walls', defaultWalls, checkWalls);\n\n    parse(inp, fieldsMap, varargin{:});\n\n    walls = inp.Results.walls;\n    searchWidth = inp.Results.searchWidth;\n    fieldsMap(fieldsMap > 1) = 1; % make it binary\n\n    for i = 1:size(walls, 1)\n        wall = walls(i, :);\n\n        aux_map = fieldsMap(end-searchWidth+1:end, wall(1):wall(2));\n        [covered, norm] = wall_field(aux_map);\n        coverage = max([covered/norm, coverage]);\n    end\nend\n\n% 'covered' pixels will have distance to border 0.\n% Essentially we need to calculate number of elements,\n% that equal to zero and take NaNs into account.\nfunction [covered, norm] = wall_field(map)\n    lx = size(map, 2);\n    map = flipud(map);\n\n    D = bwdist(map);\n    nanIndices = find(isnan(map(1, :)));\n    numNans = length(nanIndices);\n    for i = 1:numNans\n        testColumn = nanIndices(i);\n        nonNan = find(~isnan(map(:, testColumn)), 1, 'first');\n        if ~isempty(nonNan)\n            numNans = numNans - 1;\n            D(1, testColumn) = D(nonNan, testColumn);\n        end\n    end\n\n    norm = lx - numNans;\n    covered = nansum(D(1, :) == 0) - numNans;\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/borderCoverageCircular.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5556606498287479}}
{"text": "function localangle = point_angle(bw, seed, R, start, NeighborNum) \n\n% This function computes the angle of seed from the start point\nif (nargin == 4)\n    NeighborNum =3;\nend\n\n[M, N]= size(bw);\n\n% image(y,x) <==>(x-1)*M + y\nseedy = mod(seed, M);\nif (seedy==0) seedy = M; end\nseedx = 1 + (seed - seedy)/M;\nstarty = mod(start, M);\nif (starty==0) starty = M; end\nstartx = 1 + (start - starty)/M;\n\ndy = 1 + R + starty - seedy;\ndx = 1 + R + startx - seedx;\n\n% set the region border from 1:8*R\nregion = zeros(2*R+1);\nregion(R+1:-1:1,end) = (1:R+1)';\nregion(1,end-1:-1:2)= R+2:3*R;\nregion(1:end,1)= (3*R+1:5*R+1)';\nregion(end,2:end-1) = 5*R+2:7*R;\nregion(end:-1:R+2,end) = (7*R+1:8*R)';\n\nstartidx = region(dy, dx);\nanglevec = point_anglevec(bw, seed, R); \n\nif (startidx==0)\n    localangle = [];\n    return;\nend\n\nif (anglevec(startidx)==0)\n    localangle = [];\n    return;\nend\n\nlocalangle = findangle(anglevec, startidx);\nlocalnum = prod(size(localangle));\n\nif (localnum > NeighborNum)\n    localangle = localangle(1:NeighborNum);\nend\nif (localnum < NeighborNum)\n    localangle = [localangle, zeros(1, NeighborNum - localnum )];\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/23015-feature-based-retinal-image-registration/Registration/code/point_angle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5556353258127908}}
{"text": "% eeg_lat2point() - convert latencies in time units relative to the\n%                   time locking event of an eeglab() data epoch to \n%                   latencies in data points (assuming concatenated epochs).\n% Usage:\n%       >> [newlat] = eeg_lat2point( lat_array, epoch_array,...\n%                                 srate, timelimits, timeunit);\n% Inputs:\n%   lat_array   - latency array in 'timeunit' units (see below)\n%   epoch_array - epoch number for each latency\n%   srate       - data sampling rate in Hz\n%   timelimits  - [min max] epoch timelimits in 'timeunit' units (see below)\n%   timeunit    - time unit relative to seconds. Default is 1 = seconds.\n%\n% Outputs:\n%   newlat      - converted latency values in points assuming concatenated\n%                 data epochs (see eeglab() event structure)\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 2 Mai 2002\n%\n% See also: eeg_point2lat(), eeglab()\n\n% Copyright (C) 2 Mai 2002 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\nfunction newlat = eeg_lat2point( lat_array, epoch_array, srate, timewin, timeunit);\n\nif nargin <4\n    help eeg_lat2point;\n    return;\nend;    \nif nargin <5\n\ttimeunit = 1;\nend;\n\nif length(lat_array) ~= length(epoch_array)\n\tif length(epoch_array)~= 1\n\t\tdisp('eeg_lat2point: latency and epochs must have the same length'); return;\n\telse\n\t\tepoch_array = ones(1,length(lat_array))*epoch_array;\n\tend;\nend;\nif length(timewin) ~= 2\n    disp('eeg_lat2point: timelimits must have length 2'); return;\nend;\nif iscell(epoch_array)\n\tepoch_array = [ epoch_array{:} ];\nend;\nif iscell(lat_array)\n\tlat_array = [ lat_array{:} ];\nend\n\ntimewin = timewin*timeunit;\npnts = (timewin(2)-timewin(1))*srate+1;\nnewlat  = (lat_array*timeunit-timewin(1))*srate+1 + (epoch_array-1)*pnts;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/popfunc/eeg_lat2point.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5556353041602071}}
{"text": "classdef RWMOP8 < PROBLEM\n% <multi> <real> <constrained>\n% Car side impact design problem\n\n%------------------------------- Reference --------------------------------\n% A. Kumar, G. Wu, M. Ali, Q. Luo, R. Mallipeddi, P. Suganthan, and S. Das,\n% A benchmark-suite of real-world constrained multi-objective optimization\n% problems and some baseline results, Swarm and Evolutionary Computation,\n% 2021, 67: 100961.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Initialization\n        function Setting(obj)\n            obj.M        = 3;\n            obj.D        = 7;\n            obj.lower    = [0.5,0.45,0.5,0.5,0.875,0.4,0.4];\n            obj.upper    = [1.5,1.35,1.5,1.5,2.625,1.2,1.2];\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Evaluate multiple solutions\n        function Population = Evaluation(obj,varargin)\n            x  = varargin{1};\n            x1 = x(:,1);\n            x2 = x(:,2);\n            x3 = x(:,3);\n            x4 = x(:,4);\n            x5 = x(:,5);\n            x6 = x(:,6);\n            x7 = x(:,7);\n            VMBP = 10.58-0.674.*x1.*x2-0.67275.*x2;\n            VFD  = 16.45-0.489.*x3.*x7-0.843.*x5.*x6;\n            % Objective function\n            f(:,1) = 1.98+4.9.*x1.*6.67.*x2+6.98.*x3+4.01.*x4+1.78.*x5+1e-5.*x6+2.73.*x7;\n            f(:,2) = 4.72-0.5.*x4-0.19.*x2.*x3;\n            f(:,3) = 0.5.*(VMBP+VFD);\n            % Constraints\n            g(:,1) = -1+1.16-0.3717.*x2.*x4-0.0092928.*x3;\n            g(:,2) = -0.32+0.261-0.0159.*x1.*x2-0.06486.*x1-0.019.*x2.*x7+0.0144.*x2.*x5+0.0154464.*x6;\n            g(:,3) = -0.32+0.74-0.61.*x2-0.031296.*x3-0.031872.*x7+0.227.*x2.^2;\n            g(:,4) = -0.32+0.214+0.00817.*x5-0.045195.*x1-0.0135168.*x1+0.03099.*x2.*x6-0.018.*x2.*x7+0.007176.*x3+0.023232.*x3-0.00364.*x5.*x6-0.018.*x2.^2;\n            g(:,5) = -32+33.86+2.95.*x3-5.057.*x1.*x2-3.795.*x2-3.4431.*x7+1.45728;\n            g(:,6) = -32+28.98+3.818.*x3-4.2.*x1.*x2+1.27296.*x6-2.68065.*x7;\n            g(:,7) = -32+46.36-9.9.*x2-4.4505.*x1;\n            g(:,8) = f(:,2)-4;\n            g(:,9) = VMBP - 9.9;\n            Population = SOLUTION(varargin{1},f,g,varargin{2:end});\n            obj.FE     = obj.FE + length(Population);\n        end\n         %% Generate a point for hypervolume calculation\n        function R = GetOptimum(obj,~)\n            R = [9.2596587e+01   4.0000000e+00   1.2699733e+01];\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/RWMOPs/RWMOP8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5556063204869752}}
{"text": "function ConvHDRtoStack(fmtIn, fmtOut, bSampling, ldr_gamma)\n%\n%        ConvHDRtoStack(fmtIn, fmtOut, bSampling, ldr_gamma)\n%\n%        \n%        For example:\n%           ConvLDRtoLDR('hdr', 'jpg', 2.2);\n%\n%        This lines tonemaps all the .hdr files in the folder using the \n%        Reinhard et al.'s operator and it saves them as .jpg files using\n%        gamma 2.2\n%\n%        Input:\n%           -fmtIn: an input string represeting the LDR format of the images\n%           to be converted. This can be: 'hdr', 'pfm'\n%           -fmtOut: an input string represeting the LDR format of\n%           converted images. This can be: 'jpeg', 'jpg', 'png', etc.\n%           -bSampling: using or not histogram sampling\n%           -ldr_gamma: the encoding gamma for the LDR images. The default\n%           value is 2.2\n%\n%        Output:\n%           -ret: a boolean value, true or 1 if the method succeeds\n%\n%     Copyright (C) 2012-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 <http://www.gnu.org/licenses/>.\n%\n\nif(~exist('bSampling', 'var'))\n    bSampling = 0;\nend\n\nif(~exist('ldr_gamma', 'var'))\n    ldr_gamma = 2.2;\nend\n\nlst = dir(['*.', fmtIn]);\n\nfor i=1:length(lst)\n    disp(lst(i).name);\n    \n    tmp_name = lst(i).name;    \n    img = hdrimread(tmp_name);\n    L = lum(img);    \n    L = imresize(L, 0.5, 'bilinear');\n    \n    if(bSampling)\n        fstops = ExposureHistogramSampling(L, 8, 2);\n    else\n        minL = round(log2(min(L(:))));\n        maxL = round(log2(max(L(:))));\n        fstops = -maxL:-minL; \n    end\n    \n    for j=1:length(fstops)   \n        disp(fstops(j));\n        img_exp_j = GammaTMO(img, ldr_gamma, fstops(j));\n        \n        bSkip = 0;\n        if(~bSampling)\n            tImg1 = ClampImg(round(255 * img_exp_j) / 255, 0, 1);\n            val = mean(tImg1(:)); %mean value\n\n            if((val < 0.1) || (val > 0.9))\n                bSkip = 1;\n            end\n   \n        end\n            \n        if(~bSkip)\n            tmp_name_we = RemoveExt(tmp_name);\n            tmp_name_out = [tmp_name_we, '_fstop_', num2str(j), '.', fmtOut];\n            imwrite(img_exp_j, tmp_name_out);\n        end\n    end       \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/BatchFunctions/ConvHDRtoStack.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5556063043805575}}
{"text": "function [traj, infStates] = tapas_hgf_whichworld(r, p, varargin)\n% Calculates the trajectories of the agent's representations under the HGF\n%\n% This function can be called in two ways:\n% \n% (1) tapas_hgf_whichworld(r, p)\n%   \n%     where r is the structure generated by tapas_fitModel and p is the parameter vector in native space;\n%\n% (2) tapas_hgf_whichworld(r, ptrans, 'trans')\n% \n%     where r is the structure generated by tapas_fitModel, ptrans is the parameter vector in\n%     transformed space, and 'trans' is a flag indicating this.\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 <http://www.gnu.org/licenses/>.\n\n% Check whether we have a configuration structure\nif ~isfield(r,'c_prc')\n    error('tapas:hgf:ConfigRequired', 'Configuration required: before calling tapas_hgf_whichworld, tapas_hgf_whichworld_config has to be called.');\nend\n\n% Transform paramaters back to their native space if needed\nif ~isempty(varargin) && strcmp(varargin{1},'trans');\n    p = tapas_hgf_whichworld_transp(r, p);\nend\n\n% Number of worlds\nnw = r.c_prc.nw;\n\n% Bernoulli parameters that characterize\n% worlds (column vector)\nbp = [0.85; 0.15];\n\n% Unpack parameters\nmu2_0 = p(1:nw);\nsa2_0 = p(nw+1:2*nw);\nmu3_0 = p(2*nw+1);\nsa3_0 = p(2*nw+2);\nka    = p(2*nw+3);\nom    = p(2*nw+4);\nth    = p(2*nw+5);\nm     = p(2*nw+6);\nphi   = p(2*nw+7);\n\n% Add dummy \"zeroth\" trial\nu = [0; r.u(:,1)];\n\n% Number of trials (including prior)\nn = length(u);\n\n% Initialize updated quantities\n\n% Representations\nmu1 = NaN(n,nw);\npi1 = NaN(n,nw);\nmu2 = NaN(n,nw);\npi2 = NaN(n,nw);\nmu3 = NaN(n,1);\npi3 = NaN(n,1);\n\n% Other quantities\nmu1hat = NaN(n,nw);\npi1hat = NaN(n,nw);\nmu2hat = NaN(n,nw);\npi2hat = NaN(n,nw);\nmu3hat = NaN(n,1);\npi3hat = NaN(n,1);\nv2     = NaN(n,1);\nw2     = NaN(n,nw);\nda1    = NaN(n,nw);\nda2    = NaN(n,nw);\n\n% Representation priors\n% Note: first entries of the other quantities remain\n% NaN because they are undefined and are thrown away\n% at the end; their presence simply leads to consistent\n% trial indices.\nmu1(1,:) = tapas_sgm(mu2_0, 1);\npi1(1,:) = 1./(mu1(1,:).*(1-mu1(1,:)));\nmu2(1,:) = mu2_0;\npi2(1,:) = 1./sa2_0;\nmu3(1)   = mu3_0;\npi3(1)   = 1/sa3_0;\n\n% Pass through representation update loop\nfor k = 2:1:n\n    if not(ismember(k-1, r.ign))\n        \n        %%%%%%%%%%%%%%%%%%%%%%\n        % Effect of input u(k)\n        %%%%%%%%%%%%%%%%%%%%%%\n\n        % 1st level\n        % ~~~~~~~~~\n        % Predictions\n        mu1hat(k,:) = tapas_sgm(mu2(k-1,:), 1);\n        \n        % Precisions of predictions\n        pi1hat(k,:) = 1./(mu1hat(k,:).*(1 -mu1hat(k,:)));\n\n        % Updates (simply applying Bayes' theorem)\n        \n        % Likelihood of outcome u(k)\n        llh = bp.^u(k).*(1-bp).^(1-u(k));\n        \n        % Marginal likelihood of outcome\n        mllh = mu1hat(k,:)*llh;\n        \n        % Posterior for each world\n        mu1(k,:) = mu1hat(k,:).*llh'./mllh;\n\n        % Precision of posterior\n        pi1(k,:) = 1./(mu1(k,:).*(1-mu1(k,:)));\n        \n        % Prediction errors\n        da1(k,:) = mu1(k,:) -mu1hat(k,:);\n\n        % 2nd level\n        % ~~~~~~~~~\n        % Predictions\n        mu2hat(k,:) = mu2(k-1,:);\n        \n        % Precisions of predictions\n        pi2hat(k,:) = 1./(1./pi2(k-1,:) +exp(ka *mu3(k-1) +om));\n\n        % Updates\n        pi2(k,:) = pi2hat(k,:) +1./pi1hat(k,:);\n\n        mu2(k,:) = mu2hat(k,:) +1./pi2(k,:) .*da1(k,:);\n\n        % Volatility prediction errors\n        da2(k,:) = (1./pi2(k,:) +(mu2(k,:) -mu2hat(k,:)).^2) .*pi2hat(k,:) -1;\n\n\n        % 3rd level\n        % ~~~~~~~~~\n        % Predictions\n        mu3hat(k) = mu3(k-1) +phi *(m -mu3(k-1));\n        \n        % Precision of prediction\n        pi3hat(k) = 1/(1/pi3(k-1) +th);\n\n        % Weighting factors\n        v2(k)   = exp(ka *mu3(k-1) +om);\n        w2(k,:) = v2(k) *pi2hat(k,:);\n\n        % Updates\n        pi3(k) = pi3hat(k) +1/nw*sum(1/2 *ka^2 *w2(k,:) .*(w2(k,:) +(2 *w2(k,:) -1) .*da2(k,:)));\n\n        if pi3(k) <= 0\n            error('tapas:hgf:NegPostPrec', 'Negative posterior precision. Parameters are in a region where model assumptions are violated.');\n        end\n\n        mu3(k) = mu3hat(k) +sum(1/2 *1/pi3(k) *ka *w2(k,:) .*da2(k,:));\n    \n    else\n        mu1(k,:) = mu1(k-1,:);\n        pi1(k,:) = pi1(k-1,:);\n        mu2(k,:) = mu2(k-1,:);\n        pi2(k,:) = pi2(k-1,:);\n        mu3(k)   = mu3(k-1);\n        pi3(k)   = pi3(k-1);\n\n        mu1hat(k,:) = mu1hat(k-1,:);\n        pi1hat(k,:) = pi1hat(k-1,:);\n        mu2hat(k,:) = mu2hat(k-1,:);\n        pi2hat(k,:) = pi2hat(k-1,:);\n        mu3hat(k)   = mu3hat(k-1);\n        pi3hat(k)   = pi3hat(k-1);\n        v2(k)       = v2(k-1);\n        w2(k,:)     = w2(k-1,:);\n        da1(k,:)    = da1(k-1,:);\n        da2(k,:)    = da2(k-1,:);\n    end\nend\n\n% Implied learning rates at the first level\nsgmmu2 = tapas_sgm(mu2, 1);\nlr1    = diff(sgmmu2)./da1(2:n,:);\nlr1(da(2:n,1)==0) = 0;\n\n% Remove representation priors\nmu1(1,:)  = [];\npi1(1,:)  = [];\nmu2(1,:)  = [];\npi2(1,:)  = [];\nmu3(1)    = [];\npi3(1)    = [];\n\n% Remove other dummy initial values\nmu1hat(1,:) = [];\npi1hat(1,:) = [];\nmu2hat(1,:) = [];\npi2hat(1,:) = [];\nmu3hat(1,:) = [];\npi3hat(1)   = [];\nv2(1)       = [];\nw2(1,:)     = [];\nda1(1,:)    = [];\nda2(1,:)    = [];\n\n% Create result data structure\ntraj = struct;\n\ntraj.mu = NaN(n-1,3,nw);\ntraj.mu(:,1,:) = mu1;\ntraj.mu(:,2,:) = mu2;\ntraj.mu(:,3,1) = mu3;\n\ntraj.sa = NaN(n-1,3,nw);\ntraj.sa(:,1,:) = 1./pi1;\ntraj.sa(:,2,:) = 1./pi2;\ntraj.sa(:,3,1) = 1./pi3;\n\ntraj.muhat = NaN(n-1,3,nw);\ntraj.muhat(:,1,:) = mu1hat;\ntraj.muhat(:,2,:) = mu2hat;\ntraj.muhat(:,3,1) = mu3hat;\n\ntraj.sahat = NaN(n-1,3,nw);\ntraj.sahat(:,1,:) = 1./pi1hat;\ntraj.sahat(:,2,:) = 1./pi2hat;\ntraj.sahat(:,3,1) = 1./pi3hat;\n\ntraj.v       = v2;\ntraj.w       = w2;\n\ntraj.da = NaN(n-1,2,nw);\ntraj.da(:,1,:) = da1;\ntraj.da(:,2,:) = da2;\n\n% Updates with respect to prediction\ntraj.ud = traj.mu -traj.muhat;\n\n% Psi (precision weights on prediction errors)\npsi        = NaN(n-1,3,nw);\npsi(:,2,:) = 1./pi2;\npsi(:,3,:) = diag(1./pi3) *pi2hat;\ntraj.psi   = psi;\n\n% Epsilons (precision-weighted prediction errors)\nepsi        = NaN(n-1,3,nw);\nepsi(:,2,:) = squeeze(psi(:,2,:)) .*da1;\nepsi(:,3,:) = squeeze(psi(:,3,:)) .*da2;\ntraj.epsi   = epsi;\n\n% Full learning rate (full weights on prediction errors)\nwt        = NaN(n-1,3,nw);\nwt(:,1,:) = lr1;\nwt(:,2,:) = psi(:,2,:);\nwt(:,3,:) = 1/2 *ka *diag(1/pi3) *w2;\ntraj.wt   = wt;\n\n% Create matrices for use by the observation model\ninfStates = NaN(n-1,3,nw,4);\ninfStates(:,:,:,1) = traj.muhat;\ninfStates(:,:,:,2) = traj.sahat;\ninfStates(:,:,:,3) = traj.mu;\ninfStates(:,:,:,4) = traj.sa;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_whichworld.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5556062984920453}}
{"text": "% absolute value of smoothed change in orientation\nfunction [data,units] = compute_abssmoothdtheta(trx,n)\n\nflies = trx.exp2flies{n};\nnflies = numel(flies);\ndata = cell(1,nflies);\nfor i = 1:nflies,\n  fly = flies(i);\n  data{i} = abs(trx(fly).smoothdtheta);\nend\nunits = parseunits('rad/s');\n\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/compute_abssmoothdtheta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5556062979723386}}
{"text": "function pde = constant_fun(bm,bp,r,x0,y0,z0,coef)\n%% USAGE: polynomial solution for Poisson equation\n%  Last Modified: 02/21/2020 by Xu Zhang\n\n%% PDE Structure\npde = struct('intf',@intf,...\n    'exactu1',@exactu1,'exactu2',@exactu2,'exactu3',@exactu3,...\n    'um1',@um1,'um2',@um2,'um3',@um3,'up1',@up1,'up2',@up2,'up3',@up3,...\n    'Dxu',@Dxu,'Dxum',@Dxum,'Dxup',@Dxup,'Dyu',@Dyu,...\n    'Dyum',@Dyum,'Dyup',@Dyup,'Dzu',@Dzu,'Dzum',@Dzum,'Dzup',@Dzup,...\n    'f1',@f1,'f2',@f2,'f3',@f3,...\n    'fm1',@fm1,'fm2',@fm2,'fm3',@fm3,...\n    'fp1',@fp1,'fp2',@fp2,'fp3',@fp3,...\n    'A',@A,'Am',@Am,'Ap',@Ap,'one',@one);\n\npde.bm = bm;\npde.bp = bp;\n%% interface function\n    function u = intf(x,y,z)\n        u = ((x-x0).^2 + (y-y0).^2 + (z-z0).^2).^(1/2)/r-1;\n    end\n\n%% exact solution\n    function u = exactu1(x,y,z)\n        u = um1(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = up1(x(id),y(id),z(id));\n    end\n    function u = exactu2(x,y,z)\n        u = um2(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = up2(x(id),y(id),z(id));\n    end\n    function u = exactu3(x,y,z)\n        u = um3(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = up3(x(id),y(id),z(id));\n    end\n    function u = um1(x,y,z)\n        u = coef*ones(size(x));\n    end\n    function u = um2(x,y,z)\n        u = coef*ones(size(x));\n    end\n    function u = um3(x,y,z)\n        u = coef*ones(size(x));\n    end\n    function u = up1(x,y,z)\n        u = coef*ones(size(x));\n    end\n    function u = up2(x,y,z)\n        u = coef*ones(size(x));\n    end\n    function u = up3(x,y,z)\n        u = coef*ones(size(x));\n    end\n\n%% Boundary Function\n    function u = gD1(x,y,z)\n        u = exactu1(x,y,z);\n    end\n    function u = gD2(x,y,z)\n        u = exactu2(x,y,z);\n    end\n    function u = gD3(x,y,z)\n        u = exactu3(x,y,z);\n    end\n%% Derivative of the exact solution\n    function u = Dxu(x,y,z)\n        u = Dxum(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Dxup(x(id),y(id),z(id));\n    end\n    function u = Dyu(x,y,z)\n        u = Dyum(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Dyup(x(id),y(id),z(id));\n    end\n    function u = Dzu(x,y,z)\n        u = Dzum(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Dzup(x(id),y(id),z(id));\n    end\n    function u = Dxum(x,y,z)\n        u = zeros(size(x));\n    end\n    function u = Dyum(x,y,z)\n        u = zeros(size(x));\n    end\n    function u = Dzum(x,y,z)\n        u = zeros(size(x));\n    end\n    function u = Dxup(x,y,z)\n        u = zeros(size(x));\n    end\n    function u = Dyup(x,y,z)\n        u = zeros(size(x));\n    end\n    function u = Dzup(x,y,z)\n        u = zeros(size(x));\n    end\n\n    function u = Duker(x,y,z)\n        u = zeros(size(x));\n    end\n\n%% right hand side function\n    function u = f1(x,y,z)\n        u = fm1(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = fp1(x(id),y(id),z(id));\n    end\n    function u = f2(x,y,z)\n        u = fm2(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = fp2(x(id),y(id),z(id));\n    end\n    function u = f3(x,y,z)\n        u = fm3(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = fp3(x(id),y(id),z(id));\n    end\n\n    function u = fm1(x,y,z)\n        u = coef*ones(size(x));\n    end\n    function u = fm2(x,y,z)\n        u = coef*ones(size(x));\n    end\n    function u = fm3(x,y,z)\n        u = coef*ones(size(x));\n    end\n    function u = fp1(x,y,z)\n        u = coef*ones(size(x));\n    end\n    function u = fp2(x,y,z)\n        u = coef*ones(size(x));\n    end\n    function u = fp3(x,y,z)\n        u = coef*ones(size(x));\n    end\n\n%% Diffusion coefficient function\n    function u = A(x,y,z)\n        u = Am(x,y,z);\n        id = intf(x,y,z) > 0;\n        u(id) = Ap(x(id),y(id),z(id));\n    end\n    function u = Am(x,y,z)\n        u = bm*ones(size(x));\n    end\n    function u = Ap(x,y,z)\n        u = bp*ones(size(x));\n    end\n\n%% Other function\n    function u = one(x,y,z)\n        u = ones(size(x));\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/research/IVEM/ExampleFun/constant_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5555360518032135}}
{"text": "function colorTest()\n\n%   colorTest() creates a test image showing the color encoding scheme\n\n%   According to the c++ source code of Daniel Scharstein \n%   Contact: schar@middlebury.edu\n\n%   Author: Deqing Sun, Department of Computer Science, Brown University\n%   Contact: dqsun@cs.brown.edu\n%   $Date: 2007-10-31 20:22:10 (Wed, 31 Oct 2006) $\n\n% Copyright 2007-2010, Brown University, Providence, RI. USA\n%\n% \n%                         All Rights Reserved\n% \n% Permission to use, copy, modify, and distribute this software and its\n% documentation for any purpose other than its incorporation into a\n% commercial product is hereby granted without fee, provided that the\n% above copyright notice appear in all copies and that both that\n% copyright notice and this permission notice appear in supporting\n% documentation, and that the name of the author and Brown University not be used in\n% advertising or publicity pertaining to distribution of the software\n% without specific, written prior permission.\n% \n% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,\n% INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY\n% PARTICULAR PURPOSE.  IN NO EVENT SHALL THE AUTHOR OR BROWN UNIVERSITY BE LIABLE FOR\n% ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.   \n\n%% test color pattern of Daniel's c++ code\n\ntruerange = 1;\nheight = 151;\nwidth  = 151;\nrange = truerange * 1.04;\n\ns2 = round(height/2);\n\n[x y] = meshgrid(1:width, 1:height);\n\nu = x*range/s2 - range;\nv = y*range/s2 - range;\n\nimg = computeColor(u/truerange, v/truerange);\n\nimg(s2,:,:) = 0;\nimg(:,s2,:) = 0;\n\nfigure;\nimshow(img);\ntitle('test color pattern');\npause; close;\n\n% test read and write flow\nF(:,:,1) = u;\nF(:,:,2) = v;\nwriteFlowFile(F, 'colorTest.flo');\nF2 = readFlowFile('colorTest.flo');\n\nu2 = F2(:,:,1);\nv2 = F2(:,:,2);\n\nimg2 = computeColor(u2/truerange, v2/truerange);\n\nimg2(s2,:,:) = 0;\nimg2(:,s2,:) = 0;\n\nfigure; imshow(img2);\ntitle('saved and reloaded test color pattern');\npause; close;\n\n% color encoding scheme for optical flow\nimg = computeColor(u/range/sqrt(2), v/range/sqrt(2));\n\nimg(s2,:,:) = 0;\nimg(:,s2,:) = 0;\n\nfigure;\nimshow(img);\ntitle('optical flow color encoding scheme');\npause; close;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/spaceTime/optflow_deqing/utils/flowColorCode/colorTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5555360422744936}}
{"text": "function A10 = synA10min(A11, A00, cmax)\n%-----------------------------------------------------------------------------\n%\n% For each point of colour 10 this function assigns the minimum value at the\n% neighbouring gridpoints of colours 11 and 00.\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw <Paul.de.Zeeuw@cwi.nl>  http://homepages.cwi.nl/~pauldz/\n% Last Revision: December 7, 2001.\n% (c) 1998-2002 Stichting CWI, Amsterdam\n%-----------------------------------------------------------------------------\n[n00, m00]=size(A00);\n[n11, m11]=size(A11);\nn10=n11;\nm10=m00;\n%[n10, m10]=size(A10);\nif     m10 == m11\n  S=min(A11, stripR(extL(A11, cmax)));\nelseif m10 == m11+1 \n  S=min(extL(A11, cmax), extR(A11, cmax));\nelse\n  disp([' size A11 = ' int2str(size(A11)) ' size A00 = ' int2str(size(A00))]);\n  error(' synA10min - A11 and A00 do not match ');\nend\nif     n10 == n00\n  T=min(A00, stripU(extD(A00, cmax)));\nelseif n10 == n00-1 \n  T=min(stripD(A00), stripU(A00));\nelse\n  disp([' size A11 = ' int2str(size(A11)) ' size A00 = ' int2str(size(A00))]);\n  error(' synA10min - A11 and A00 do not match ');\nend\n%Note: all(size(S) == size(T)) & all(size(S) == [n10 m10]) always holds.\nA10=min(S, T);\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/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/synA10min.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5555360422744935}}
{"text": "%% FACE_POOL runs the example interactively with MATLABPOOL.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 June 2010\n%\n%  Author:\n%\n%    Gene Cliff, John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'FACE_POOL\\n' );\n  fprintf ( 1, '  Evaluate FACE_FUN directly with MATLABPOOL.\\n' );\n%\n%  Load the MAT file containing the grid coordinates as the variable\n%  \"Grid\" and the element connectivity as the variable \"e_conn\".\n%\n  load GRID\n%\n%  We will be looking for tetrahedrons which have one face lying\n%  on a plane defining one side of the box.  To define this box\n%  we must specify:\n%\n%  II, the index of the \"I\" variable which is constant on the plane.\n%  If the constant variable is X, then II is 1, and so on.\n%\n%  VAL_II, the value of the constant \"I\" variable.\n%\n%  XJ_LB, XJ_UB, the upper and lower bounds for the \"J\" nonconstant variable.\n%\n%  XK_LB, XK_UB, the upper and lower bounds for the \"K\" nonconstant variable.\n%\n%  The \"J\" and \"K\" variables are the first and second variables to follow\n%  the \"I\" variable, assuming that we are counting with wrap around.\n%  There are thus three possibilities for I, J and K:\n%\n%    I  J  K\n%   -- -- --\n%    1  2  3\n%    2  3  1\n%    3  1  2\n%\n%  Our choices below specify that we are looking at the plane Z = 3.0,\n%  and more specifically, the box in that plane for which\n%  -1.0 <= X <= +1.0, and -1.0 <= Y <= +1.0.\n%\n  ii = 3;\n  val_ii = 3.0;\n  xj_lb = -1.0;\n  xj_ub = +1.0;\n  xk_lb = -1.0;\n  xk_ub = +1.0;\n%\n%  Call FACE_FUN to compute a list of the triangular faces of the\n%  tetrahedral elements which lie on the boundary plane.\n%\n%  Get 4 \"labs\" to work on the job.\n%\n  matlabpool open local 4\n  F_conn = face_fun ( Grid, e_conn, ii, val_ii, xj_lb, xj_ub, xk_lb, xk_ub );\n  matlabpool close\n\n  face_num = size ( F_conn, 2 );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Number of triangles on boundary is %d\\n', face_num );\n%\n%  Display the surface triangulation.\n%\n  i_pl = setdiff ( 1:3, ii );\n\n  triplot ( F_conn', Grid(:, i_pl(1)), Grid(:, i_pl(2)) );\n\n  if ( ii == 1 )\n    title ( 'Triangular faces on X boundary plane' );\n    xlabel ( '- Y axis -' );\n    ylabel ( '- Z axis -' );\n  elseif ( ii == 2 )\n    xlabel ( '- X axis -' );\n    title ( 'Triangular faces on Y boundary plane' );\n    ylabel ( '- Z axis -' );\n  elseif ( ii == 3 )\n    xlabel ( '- X axis -' );\n    ylabel ( '- Y axis -' );\n    title ( 'Triangular faces on Z boundary plane' );\n  end\n\n  axis equal\n  axis tight\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/face_spmd/face_pool.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.555536034989502}}
{"text": "function [Estimation_X] = REKF_propagate(Estimation_X, OdometryFromThis2Next, Sigma_ODO )\n\n\n\n% retrieve v and w\nv = OdometryFromThis2Next(1:3);\nw = OdometryFromThis2Next(4:6);\n\n\n\nNumberOfLandmarks = size(Estimation_X.landmarks, 2);\n%Jrw = jaco_r(-w);\nJrw=eye(3);\nExpMinusM = so3_exp(-w);\n\n\n\n\ntemp = repmat({Estimation_X.orientation}, NumberOfLandmarks+2,1 );\nA = blkdiag(temp{:});\n A(4:6,1:3)=skew(Estimation_X.position)*Estimation_X.orientation;\n \nif NumberOfLandmarks>0\n   for i=1:NumberOfLandmarks\n    A(6+3*i-2:6+3*i,1:3)=skew(Estimation_X.landmarks(1:3,i))*Estimation_X.orientation;\n   end\nend\n\n\n%B1=[-Jrw  zeros(3,3); -skew(v)*Jrw -eye(3)];\n\nB1=[eye(3)  zeros(3,3); zeros(3,3) eye(3)];\n\nB=[B1; sparse(3*NumberOfLandmarks,6)];\nB=sparse(B);\n\nadA=A*B;\n\nodoCov=diag([w.^2;v.^2])*Sigma_ODO^2;\n\n% final update the covariance\nEstimation_X.cov = Estimation_X.cov+ adA*odoCov*adA';\n\n% update position and orientation\nEstimation_X.position = Estimation_X.position+Estimation_X.orientation*v;\nEstimation_X.orientation = Estimation_X.orientation*so3_exp(w);\n\n\nend\n\n\n\n\n", "meta": {"author": "RomaTeng", "repo": "EKF-SLAM-on-Manifold", "sha": "12d7d8d88c84161baed173e38d49dedb4adb2b96", "save_path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold", "path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold/EKF-SLAM-on-Manifold-12d7d8d88c84161baed173e38d49dedb4adb2b96/right_ekf_3d_mod/REKF_propagate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5555126088487038}}
{"text": "function [Ta,Ka,Ba,Tg,Kg,Bg,Tm2a,Bm,Vm,mag_strength]=ImuCalibration_Gesture(data)\n% input data raw IMU data from mpu9250 \n% data :time accelerometer  gyroscope   magnetometer \n%  cal_acc=Ta*Ka*(raw_acc+Ba)\n%  cal_gyro=Tg*Kg*(raw_gyro+Bg)\n%  cal_mag=Tm2a*(raw_mag+Bm)\n%\n% author  Zhang Xin\n\n\n[~,fix_point,rotation]=FindFixData(data,30);\n\n[Ta,Ka,Ba]=ICRA2014_acc(fix_point);\n\nBg=-mean(fix_point(:,4:6),1)';\n\nn=size(rotation,1);\n\nrotation{n+1}=Ta;\nrotation{n+2}=Ka;\nrotation{n+3}=Ba;\nrotation{n+4}=Bg;\n\n[Tg,Kg]=ICRA_2014_gyro(rotation);\n\n%[Tm2a,Bm,Vm]=mag2acc_matrix(fix_point,Ta,Ka,Ba);\n\n[Tm2a,Bm,Vm,mag_strength]=Cal_mag4acc_frame(rotation,fix_point,Tg,Kg);\n\nSet_Bias_Gyro=[0.1,-0.4,1.5];\n\nSee_Gesture( data,Ta,Ka,Ba,Tg,Kg,Bg,Tm2a,Bm,Vm,Set_Bias_Gyro);\n\nend\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/ImuCalibration_Gesture.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5555126027971744}}
{"text": "function varargout = rank(varargin)\n%RANK      Rank of a SPHEREFUN.\n%   RANK(F) produces an estimate of the rank of the approximant F.\n%\n%   RANK(F, TOL) is the number of singular values of F greater than TOL/N, where\n%   N is the first singular value of F.\n%\n% See also SPHEREFUN/LENGTH.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n[varargout{1:nargout}] = rank@separableApprox(varargin{:});\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/@spherefun/rank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867969424067, "lm_q2_score": 0.6959583250334527, "lm_q1q2_score": 0.5555047462638539}}
{"text": "function f = makeimagestack(m,wantnorm,addborder,csize,bordersize)\n\n% function f = makeimagestack(m,wantnorm,addborder,csize,bordersize)\n%\n% <m> is a 3D matrix.  if more than 3D, we reshape to be 3D.\n%   we automatically convert to double format for the purposes of this function.\n% <wantnorm> (optional) is\n%   0 means no normalization\n%   [A B] means normalize and threshold values such that A and B map to 0 and 1.\n%   X means normalize and threshold values such that X percentile\n%     from lower and upper end map to 0 and 1.  if the X percentile\n%     from the two ends are the same, then map everything to 0.\n%   -1 means normalize to 0 and 1 using -max(abs(m(:))) and max(abs(m(:)))\n%   -2 means normalize to 0 and 1 using 0 and max(m(:))\n%   -3 means normalize to 0 and 1 using min(m(:)) and max(m(:))\n%   default: 0.\n% <addborder> (optional) is\n%    0 means do not add border\n%    1 means add border at the right and bottom of each image.\n%      the border is assigned the maximum value.\n%    2 means like 1 but remove the final borders at the right and bottom.\n%   -1 means like 1 but assign the border the middle value instead of the max.\n%   -2 means like 2 but assign the border the middle value instead of the max.\n%    j means like 1 but assign the border a value of 0.\n%  2*j means like 2 but assign the border a value of 0.\n%  NaN means plot images into figure windows instead of returning a matrix.\n%      each image is separated by one matrix element from surrounding images.\n%      in this case, <wantnorm> should not be 0.\n%    default: 1.\n% <csize> (optional) is [X Y], a 2D matrix size according\n%   to which we concatenate the images (row then column).\n%   default is [], which means try to make as square as possible\n%   (e.g. for 16 images, we would use [4 4]).\n%   special case is -1 which means use [1 size(m,3)].\n%   another special case is [A 0] or [0 A] in which case we\n%   set 0 to be the minimum possible to fit all the images in.\n% <bordersize> (optional) is number of pixels in the border in the case that\n%   <addborder> is not NaN.  default: 1.\n%\n% if <addborder> is not NaN, then return a 3D matrix.  the first two dimensions \n% contain images concatenated together, with any extra slots getting filled \n% with the minimum value.  the third dimension contains additional sets of images\n% (if necessary).\n%\n% if <addborder> is NaN, then make a separate figure window for each set of images.\n% (actually, we create new figure windows only for sets after the first set.  so the\n% we attempt to draw the first set in the current figure window.)  in each figure window,\n% we plot individual images using imagesc scaled to the range [0,1].\n% we return <f> as [].\n%\n% example:\n% a = randn(10,10,12);\n% imagesc(makeimagestack(a,-1));\n% imagesc(makeimagestack(a,-1,NaN));\n\n% input\nif ~exist('wantnorm','var') || isempty(wantnorm)\n  wantnorm = 0;\nend\nif ~exist('addborder','var') || isempty(addborder)\n  addborder = 1;\nend\nif ~exist('csize','var') || isempty(csize)\n  csize = [];\nend\nif ~exist('bordersize','var') || isempty(bordersize)\n  bordersize = 1;\nend\n\n% calc\nnrows = size(m,1);\nncols = size(m,2);\n\n% make double if necessary\nm = double(m);\nwantnorm = double(wantnorm);\n\n% make <m> 3D if necessary\nm = reshape(m,size(m,1),size(m,2),[]);\n\n% find range, normalize\nif length(wantnorm)==2\n  m = normalizerange(m,0,1,wantnorm(1),wantnorm(2));\n  mn = 0;\n  mx = 1;\nelseif wantnorm==0\n  mn = nanmin(m(:));\n  mx = nanmax(m(:));\nelseif wantnorm==-1\n  m = normalizerange(m,0,1,-max(abs(m(:))),max(abs(m(:))));\n  mn = 0;\n  mx = 1;\nelseif wantnorm==-2\n  m = normalizerange(m,0,1,0,max(m(:)));\n  mn = 0;\n  mx = 1;\nelseif wantnorm==-3\n  m = normalizerange(m,0,1,min(m(:)),max(m(:)));\n  mn = 0;\n  mx = 1;\nelse\n  rng = range_outlier(m(:),wantnorm);\n  if rng(2)==rng(1)\n    m = zeros(size(m));  % avoid error from normalizerange.m\n  else\n    m = normalizerange(m,0,1,rng(1),rng(2));\n  end\n  mn = 0;\n  mx = 1;\nend\nmd = (mn+mx)/2;\n\n% number of images\nnumim = size(m,3);\n\n% calculate csize if necessary\nif isempty(csize)\n  rows = floor(sqrt(numim));  % MAKE INTO FUNCTION?\n  cols = ceil(numim/rows);\n  csize = [rows cols];\nelseif isequal(csize,-1)\n  csize = [1 numim];\nelseif csize(1)==0\n  csize(1) = ceil(numim/csize(2));\nelseif csize(2)==0\n  csize(2) = ceil(numim/csize(1));\nend\n\n% calc\nchunksize = prod(csize);\nnumchunks = ceil(numim/chunksize);\n\n% convert to cell vector, add some extra matrices if necessary\nm = splitmatrix(m,3);\nm = [m repmat({repmat(mn,size(m{1}))},1,numchunks*chunksize-numim)];\n\n% figure case\nif isnan(addborder)\n\n  for p=1:numchunks\n    if p ~= 1\n      drawnow; figure;\n    end\n    hold on;\n    for q=1:chunksize\n      xx = linspace(1+(ceil(q/csize(1))-1)*(ncols+1),ncols+(ceil(q/csize(1))-1)*(ncols+1),ncols);\n      yy = linspace(1+(mod2(q,csize(1))-1)*(nrows+1),nrows+(mod2(q,csize(1))-1)*(nrows+1),nrows);\n      imagesc(xx,yy,m{(p-1)*chunksize+q},[0 1]);\n    end\n    axis equal;\n    set(gca,'YDir','reverse');\n  end\n  f = [];\n\n% matrix case\nelse\n\n  % add border?\n  if imag(addborder) || addborder\n    for p=1:length(m)\n      m{p}(end+(1:bordersize),:) = choose(imag(addborder),0,choose(addborder > 0,mx,md));\n      m{p}(:,end+(1:bordersize)) = choose(imag(addborder),0,choose(addborder > 0,mx,md));\n    end\n  end\n  \n  % combine images\n  f = [];\n  for p=1:numchunks\n    temp = m((p-1)*chunksize + (1:chunksize));\n    f = cat(3,f,cell2mat(reshape(temp,csize)));\n  end\n  \n  % remove final?\n  if abs(addborder)==2\n    f(end-bordersize+1:end,:,:) = [];\n    f(:,end-bordersize+1:end,:) = [];\n  end\n\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/makeimagestack.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5555047446151954}}
{"text": "function c = camGraphics(csize,euler)\n\n%CAMGRAPHICS Create a camera graphics 3D object.\n%   CAMGRAPHICS creates a solid representing a camera. The objective is\n%   heading towards the camera optical axis and is located at camera\n%   position. Initial configuration is: position at origin and optical\n%   axis aligned with world's Z axis.\n%\n%   The result is a structure with fields:\n%       .vert0  the vertices in camera frame.\n%       .vert   the vertices in world frame.\n%       .faces  the definition of faces.\n%\n%   Fields .vert and .faces are used to draw the object via the PATCH\n%   command. Further object repositionning is accomplished with DRAWOBJECT.\n%\n%   CAMGRAPHICS(SIZE) allows for choosing the camera size. Default is 0.1.\n%\n%   CAMGRAPHICS(SIZE,EULER) admits a different orientation to the default\n%   one. To make the camera look in the X-axis direction, use EULER =\n%   [-pi/2 0 -pi/2].\n%\n%   See also PATCH, SET, DRAWOBJECT.\n\n%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nif nargin < 2\n    euler = zeros(3,1);\n    if nargin < 1\n        csize = 0.1;\n    end\nend\n\n\nd = .6; % objective diameter\nf = .5; % objective length\nh = .8; % body height\nw = 1;  % body width\nt = .3; % body thickness\n\n% objective vertices\na         = (0:pi/4:2*pi-pi/4)';\nna        = length(a);\ncircle    = d/2*[cos(a),sin(a)];\nobjective = [circle,zeros(na,1);circle,f*ones(na,1)];\n\n% body vertices\nrect      = [1 1;-1 1;-1 -1;1 -1]*diag([w h])/2;\nbody      = [rect,zeros(4,1);rect,-t*ones(4,1)];\n\n% rotation matrix\nR = e2R(euler);\n\n% vertices in camera frame\nvert0     = [body;objective]*R';\n\n% graphics structure - vertices and faces\nc.vert0   = csize*vert0;\nc.vert    = c.vert0;\nc.faces   = [ ...\n    01 02 03 04\n    05 06 07 08\n    01 02 06 05\n    02 03 07 06\n    03 04 08 07\n    04 01 05 08\n    09 10 18 17\n    10 11 19 18\n    11 12 20 19\n    12 13 21 20\n    13 14 22 21\n    14 15 23 22\n    15 16 24 23\n    16 09 17 24];\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 <http://www.gnu.org/licenses/>.\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/Simulation/camGraphics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.555504737933026}}
{"text": "function m = computem (L, w, W, K, Phi)\n\n  % Get the number of documents.\n  D = length(L);  \n\n  % Initialize the counts \"m\".\n  m = zeros(W,K);\n  \n  % Repeat for every document, then for every word in the document.\n  is = 0;\n  for d = 1:D\n    is = is(end) + (1:L(d));\n    for i = is\n      j      = w(i);\n      m(j,:) = m(j,:) + Phi(:,i)';\n    end\n  end\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/OptiToolbox/Solvers/lbfgsb/distribution/computem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5555047328995154}}
{"text": "function [hr] = yr2hr(yr)\n% Convert time from Julian years (365.25 days) to hours. \n% Chad Greene 2012\nhr = yr*8766;", "meta": {"author": "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/yr2hr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5555047262173459}}
{"text": "function vw = replaceROIQuadrilateralCoords(vw,corners)\n%\n% vw = replaceROIQuadrilateralCoords(vw,corners)\n%\n% Author:  BW,AAB\n% Purpose:\n%   Replace the coordinates in the currently selected roi with a\n%   quadrilateral region defined by the corners.\n\ncurSlice =viewGet(vw, 'Current Slice');\n\n% is this a flat view with potential rotations/flips?\n% if so, we need to rotate the corners to reflect how they would be\n% displayed given the current settings\nif strcmp(vw.viewType, 'Flat')\n\t% we need to do some reorienting to get the corners into the standard\n\t% view coordinate system, then rotate them:\n\tcornerCoords = [fliplr(corners) repmat(curSlice, [size(corners, 1) 1])]';\n\tcornerCoords = (rotateCoords(vw, cornerCoords, 0));\n\tcorners = cornerCoords([2 1],:)';\nend\n\t\n% Create a binary image with 1s within this quadrilateral\npolyIm = roipoly(vw.ui.image,corners(:,1),corners(:,2));\n\n% % markPoly returns an image with 1's marking the polygon\n% dims=size(vw.ui.image);\n% polyIm = markPoly(dims);\n\n% Compute image coordinates\npolyImIndices = find(polyIm);\npolyImCoords = indices2Coords(polyImIndices,size(polyIm));\n\n% Add curSlice as 3rd row to get volume coordinates\npolyCoords = [polyImCoords; curSlice*ones(1,size(polyImCoords,2))];\n\n% Do an (inverse) rotation if necessary\nif (strcmp(vw.viewType,'Flat'))\n    polyCoords = (rotateCoords(vw,polyCoords,1));\nend\n\n\n% Convert coords to canonical frame of reference\npolyCoords = curOri2CanOri(vw,polyCoords);\n\nvw.ROIs(vw.selectedROI).coords = polyCoords;\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/replaceROIQuadrilateralCoords.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5555047228324941}}
{"text": "function s=shuffle(x,c)\n%Syntax: s=shuffle(x,c)\n%______________________\n%\n% Makes c shuffled surrogates of a time series x.\n%\n% s is the shuffled 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 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(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\nfor i=1:c\n    \n    % Make a random vector with indices up to n\n    s1=randperm(N);\n    \n    % Shuffle the original x with respect to s1\n    s(:,i)=x(s1);\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/shuffle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.5554634885650636}}
{"text": "%% brute_force_tune\n% Code to test the performance of various tuning parameters\n% Works sorta like RANSAC I guess?\n% Adam Werries 2016, see Apache 2.0 license.\n\nk_max = 50;\n% Specify ranges\naccel_bias_PSD = logspace(-10,-4,100);\ngyro_bias_PSD = logspace(-10,-4,100);\n% Repeat arrays\naccel_bias_PSD = repmat(accel_bias_PSD, [1 k_max]);\ngyro_bias_PSD = repmat(gyro_bias_PSD, [1 k_max]);\n% Generate random selections of each vector\nnum_items = length(accel_bias_PSD);\naccel_bias_i = randperm(num_items);\ngyro_bias_i = randperm(num_items);\n\nrms_error_filter = Inf*ones(1,num_items);\nmax_error_filter = Inf*ones(1,num_items);\nparfor i = 1:num_items\n    fprintf('Iteration: %d, ABias: %08.5e, GBias: %08.5e\\n', i, accel_bias_PSD(accel_bias_i(i)), gyro_bias_PSD(gyro_bias_i(i)));\n    temp_conf = LC_KF_config;\n    temp_conf.accel_bias_PSD = accel_bias_PSD(accel_bias_i(i));\n    temp_conf.gyro_bias_PSD = gyro_bias_PSD(gyro_bias_i(i));\n    [out_profile,out_IMU_bias_est,out_KF_SD] = Loosely_coupled_INS_GNSS(init_cond, filter_time, epoch, lla, gps, imu, temp_conf, est_IMU_bias);\n    xyz = out_profile(:,2:4);\n    if ~any(any(isnan(xyz))) && ~any(any(isinf(xyz)))\n        llh = ecef2lla(xyz);\n        [x,y] = deg2utm(llh(:,1),llh(:,2));\n        x = x-min_x;\n        y = y-min_y;\n%         h = -llh(:,3);\n%         distance = ((ground_truth_full(:,1)-x).^2 + (ground_truth_full(:,2)-y).^2 + (ground_truth_full(:,3)-h).^2).^0.5;\n        distance = ((ground_truth_full(:,1)-x).^2 + (ground_truth_full(:,2)-y).^2).^0.5;\n        rms_error_filter(i) = rms(distance);\n        max_error_filter(i) = max(distance);\n    end\nend\n\n[minmax, i] = min(max_error_filter);\nfprintf('\\nBest max: %08.4f, rms is %08.4f\\n', minmax, rms_error_filter(i));\nfprintf('Best iteration for max: %d, ABias: %08.5e, GBias: %08.5e\\n', i, accel_bias_PSD(accel_bias_i(i)), gyro_bias_PSD(gyro_bias_i(i)));\n[minrms, i] = min(rms_error_filter);\nfprintf('Best rms: %08.4f, max is %08.4f\\n', minrms, max_error_filter(i));\nfprintf('Best iteration for rms: %d, ABias: %08.5e, GBias: %08.5e\\n', i, accel_bias_PSD(accel_bias_i(i)), gyro_bias_PSD(gyro_bias_i(i)));\n[minrms, i] = min((rms_error_filter+max_error_filter)/2);\nfprintf('Best average of RMS and max: %08.4f, rms is  %08.4f, max is %08.4f\\n', minrms, rms_error_filter(i), max_error_filter(i));\nfprintf('Best iteration for rms: %d, ABias: %08.5e, GBias: %08.5e\\n', i, accel_bias_PSD(accel_bias_i(i)), gyro_bias_PSD(gyro_bias_i(i)));\n", "meta": {"author": "awerries", "repo": "kalman-localization", "sha": "558ca7fae1779aa71da61ec4829299bbbdbf62ff", "save_path": "github-repos/MATLAB/awerries-kalman-localization", "path": "github-repos/MATLAB/awerries-kalman-localization/kalman-localization-558ca7fae1779aa71da61ec4829299bbbdbf62ff/MATLAB/Tuning/tune_bias_psd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5554542158595932}}
{"text": "% efficiencyOFexpDesigns2 : OVERLAPPING EVENTS\n% ER-fMRI data analysis\n% script:\n% throughout we assume TR=2.\n\n\nloadDataYes=1; % =1 -> loads existing data file\n\npluginCorrYes=0;\ndaleYes=1; % 1-usual Dale efficiency. 0-Fisher\n\n% event matrices are defined based on vectors with the average\n% energy removed\n\ncutEndPad=0; %cutting reduces efficiency!\nnReps=10000; %n-2;\nn2=24; % assumed # TRs to cover HDR fn\nnVals=1;\npwRange=6:10; %7\n\nif ~loadDataYes,\n\nrndEffAll=[];\nmEffAll=[];\n\ntic\nfor pwr=pwRange,\n% creating event vectors\nms=m2bin([mseq(2,pwr,0,1)])'; % fixing to the length of 2^n\nn=length(ms)  % scan duration in TRs\nif pluginCorrYes\n  b=[0.406;0.8825]; % parameters from SPG fMRI data\n  fittedACorr=autocorrFnct(b,1:n+(n2-1)*rem(cutEndPad+1,2));\n  Cninv=inv(toeplitz(fittedACorr));\nelse\n  Cninv=eye(n+(n2-1)*rem(cutEndPad+1,2));\nend;\n\nmEff=zeros(1,n-1);\n\nshift=2^(pwr-1);\n%shift1=2^(pwr-2)*3;\n%XXXXXXXXXXXXXXXXXXXXX\nfor cycle=1:(2^pwRange(1))-2,\n  mEvent=ms; %row 1\n  mEvent=[mEvent; [ms(shift+1:end) ms(1:shift)]];%row 3\n  mEvent=[mEvent; [ms(cycle+1:end) ms(1:cycle)]];%row 2\n\n  % defining event matrix as convolution matrix\n  %eventMatrix=makeEventMtrx(mEvent-(ones(length(mEvent),1)*...\n  %sum(mEvent'))'/length(mEvent),n2); \n\t\n  eventMatrix=makeEventMtrx(mEvent,n2); \n\t\n  if cutEndPad, eventMatrix=eventMatrix(1:n,:); end;\n  eventMatrix=eventMatrix-ones(size(eventMatrix,1),1)* ...\n    sum(eventMatrix)/size(eventMatrix,1);\n\n  if daleYes,\n    designEff=1/trace(inv(eventMatrix'*Cninv*eventMatrix));\n  else\n    designEff=trace(eventMatrix'*Cninv*eventMatrix);\n  end;\n\t\n  mEff(cycle)=designEff;\nend;\n\n%mProbab=sum(mEvent'); mProbab=mean(mProbab)/n;\nplot(mEff,'k','LineWidth',2); \nset(gca,'FontSize',12);\nxlabel('Cyclical shift of event vector #3','FontSize',16)\nylabel('Efficiency','FontSize',16)\n%axis([0 n 0 1])\nset(gca,'Position',[.2,.15,.7,.7]);\nset(gcf,'PaperPosition',[1,1,5,4]);\n%print -dpsc2 cyclingOverlapping3ev\ndrawnow;\npause\n\nfoo=max(mEff);\nmEffAll=[mEffAll, foo(1)];\n\n% for simply randomized designs:\nnVals=size(mEvent,1);\nnOnes=0.5;\noverlapYes=1;\n\nrndEff=[];\nfor k=1:nReps;\n   %nOnes=k/(n-1);\n      \n\trndEvent=balancedRnd(n,nVals,nOnes,overlapYes);\n\t%if k==1, sum(rndEvent'), end;\n        eventMatrix=makeEventMtrx(rndEvent-(ones(length(rndEvent),1)*sum(rndEvent'))'/length(rndEvent),n2);\n   if cutEndPad, eventMatrix=eventMatrix(1:n,:); end;\n        if daleYes,\n\t  designEff=1/trace(inv(eventMatrix'*Cninv*eventMatrix));\n\telse\n\t  designEff=trace(eventMatrix'*Cninv*eventMatrix);\n\tend;\n\t\n\trndEff=[rndEff, designEff];\nend;\nrndEffAll=[rndEffAll;rndEff];\nend;\ntoc;\n\nelse \n  eval(['load dataEff',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nh']);\nend %fi loadDataYes\n\nnn=2.^[pwRange]-1;\n\n\nfigure(1); clf;\n%[b,a]=hist(rndEff,20); \n%bar(a,b/nReps); hold on;\n%plot(max(mEff),0,'k*'); \n\nloglog(nn,mEffAll,'r*');hold on;\n\n% theoretical max:\n%theoMax=(nn+1)/n2/4;\n%loglog(nn,theoMax,'g+');hold on;\np99=max(rndEffAll'); %prctile(rndEffAll',99.9);\np00=min(rndEffAll'); %prctile(rndEffAll',0.1);\nmed=median(rndEffAll');\nloglog(nn,med,'k.-','LineWidth',2);\nloglog([nn;nn],[p00;p99],'k')\nloglog([nn*.93;nn*1.1],[p00;p00],'k')\nloglog([nn*.93;nn*1.1],[p99;p99],'k')\n\naxis([50 10^3*1.2 10^-.5 10^1*3]);\n%set(gca,'YTick',[0.003 .01 .1 .3 1 3 10 30]);\nset(gca,'XTick',[2^6 2^7 2^8 2^9 2^10]);\nset(gca,'LineWidth',2,'FontSize',12);\n\nxlabel('Sequence length','FontSize',12);\nylabel('Efficiency','FontSize',12);\ntitle(['With Overlap: n_e=',num2str(nVals),' p=',num2str(nOnes),' n_h=',num2str(n2)]);\n\nset(gca,'Position',[.2,.15,.7,.7]);\nset(gcf,'PaperPosition',[1,1,4,3]);\neval(['print -dpsc2 eff',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nh_over']);\ndisp(['print -dpsc2 eff',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nh_over']);\n\n\n\nfigure(2); clf;\nsemilogx(nn,mEffAll./max(rndEffAll'),'-ok','LineWidth',2); hold on;\nsemilogx(nn,mEffAll./med,':+k','LineWidth',2)\nset(gca,'Position',[.2,.15,.7,.7]);\nxlabel('Sequence length','FontSize',12);\nylabel('m-seq/random efficiency ratio','FontSize',12);\ntitle(['With overlap: n_e=',num2str(nVals),' p=',num2str(nOnes),' n_h=',num2str(n2)]);\nset(gca,'Position',[.2,.15,.7,.7]);\nset(gcf,'PaperPosition',[1,1,4,3]);\nset(gca,'XTick',[2^6 2^7 2^8 2^9 2^10]);\nset(gca,'LineWidth',2,'FontSize',12);\naxis([50 10^3*1.2 .9 2.5]);\neval(['print -dpsc2 eff',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nhRATIO']);\ndisp(['print -dpsc2 eff',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nhRATIO']);\n\neval(['save dataEff',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nh rndEffAll p99 p00 med mEffAll']);\ndisp(['save dataEff',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nh rndEffAll p99 p00 med mEffAll']);\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/M-sequence/mseq/efficiencyOFexpDesigns2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5554541876620551}}
{"text": "function [Gal] = G2Gal(G)\n% Convert acceleration from average acceration due to Earth's gravity to \n% galileos \n% Chad A. Greene 2012\nGal = G*9.80665e+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/35258-unit-converters/unit_converters/G2Gal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303384097947, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5553713338627454}}
{"text": "function [x,e,obj,err,iter] = tracelassoR(A,b,lambda,opts)\n\n% Solve the trace Lasso regularized minimization problem by M-ADMM\n%\n% min_{x,e} loss(e)+lambda*||A*Diag(x)||_*, s.t. Ax+e=b\n% loss(e) = ||e||_1 or 0.5*||e||_2^2\n% ---------------------------------------------\n% Input:\n%       A       -    d*n matrix\n%       b       -    d*1 vector\n%       opts    -    Structure value in Matlab. The fields are\n%           opts.loss       -   'l1' (default): loss(e) = ||e||_1 \n%                               'l2': loss(e) = 0.5*||e||_2^2\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%       e       -    d*1 vector\n%       obj     -    objective function value\n%       err     -    residual \n%       iter    -    number of iterations\n%\n% version 1.0 - 18/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;\nloss = 'l1';\n\nif ~exist('opts', 'var')\n    opts = [];\nend\nif isfield(opts, 'loss');        loss = opts.loss;            end\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[d,n] = size(A);\nx = zeros(n,1);\nZ = zeros(d,n);\ne = zeros(d,1);\nY1 = e;\nY2 = Z;\n\nAtb = A'*b;\nAtA = A'*A;\ninvAtA = (AtA+diag(diag(AtA)))\\eye(n);\n\niter = 0;\nfor iter = 1 : max_iter\n    xk = x;\n    ek = e;\n    Zk = Z;    \n    % first super block {Z,e}\n    [Z,nuclearnorm] = prox_nuclear(A*diag(x)-Y2/mu,lambda/mu);\n    if strcmp(loss,'l1')\n        e = prox_l1(b-A*x-Y1/mu,1/mu);\n    elseif strcmp(loss,'l2')\n        e = mu*(b-A*x-Y1/mu)/(1+mu);\n    else\n        error('not supported loss function');\n    end    \n    % second super block {x}\n    x = invAtA*(-A'*(Y1/mu+e)+Atb+diagAtB(A,Y2/mu+Z));\n    dY1 = A*x+e-b;\n    dY2 = Z-A*diag(x);\n    chgx = max(abs(xk-x));\n    chge = max(abs(ek-e));\n    chgZ = max(max(abs(Zk-Z)));\n    chg = max([chgx chge chgZ max(abs(dY1(:))) max(abs(dY2(:)))]);\n    if DEBUG        \n        if iter == 1 || mod(iter, 10) == 0\n            obj = comp_loss(e,loss)+lambda*nuclearnorm;    \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_loss(e,loss)+lambda*nuclearnorm;\nerr = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2);\n\nfunction v = diagAtB(A,B)\n% A, B - d*n matrices\n% v = diag(A'*B), n*1 vector\n\nn = size(A,2);\nv = zeros(n,1);\nfor i = 1 : n\n   v(i) = A(:,i)'*B(:,i); \nend\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/tracelassoR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5553713199947176}}
{"text": "function [ know, x ] = p37_sol ( n )\n\n%*****************************************************************************80\n%\n%% P37_SOL returns the solution for problem 37.\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 order of the problem.  This value\n%    is only needed for those problems with variable N.\n%\n%    Output, integer KNOW.\n%    If KNOW is 0, then the solution is not known.\n%    If KNOW is positive, then the solution is known, and is returned in X.\n%\n%    Output, real X(N), the solution, if known.\n%\n  know = 1;\n\n  x = pi * ones ( 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_opt/p37_sol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.5553713165277105}}
{"text": "\nclear all\nclose all\n\ndisp('Synthetic data from nonlinear ODE model');\ndisp('defined in Ramsay et al. (2007)');\ndisp('based on Van der Pol oscillator and which');\ndisp('reduces to Fitzhugh-Nagumo for certain parameters');\n\nsigma_e=0.01;\n[M,U] = mci_ramsay_struct(sigma_e);\n\n% Use higher integration tolerances than by default\nM.reltol=1e-3;\nM.abstol=1e-5;\n\nrand_init=0;\nif rand_init\n    P=spm_normrnd(M.vpE,M.pC,1);\nelse\n    P=[log(0.2) log(0.2)]';\nend\n\ntic;\nY = mci_ramsay_gen(P,M,U);\ntoc\n\nmci_plot_outputs(M,Y);\n\n%mcmc.inference='vl';\n%mcmc.inference='langevin';\n%mcmc.maxits=16;\n%mcmc.verbose=1;\n\nmcmc.inference='ais';\nmcmc.anneal='geometric';\nmcmc.prop='lmc';\nmcmc.nprop=1;\nmcmc.J=16;\nmcmc.maxits=8;\nmcmc.rec_traj=1;\n\npost = spm_mci_post (mcmc,M,U,Y,P);\n\nif ~strcmp(mcmc.inference,'vl')\n    spm_mci_diag(post);\n    \n    stats = spm_mci_mvnpost (post,'ESS')\n    stats = spm_mci_mvnpost (post,'thinning')\n    \n    for j=1:length(P),\n        spm_mci_quantiles (post,j,0);\n    end\nend\n    \nload ramsay-surface\nfigure\nsurf(S.x,S.y,L);\nxlabel(S.name{1});\nylabel(S.name{2});\n\nfigure;\nimagesc(S.pxy(1,:),S.pxy(2,:),L);\naxis xy\nhold on\nxlabel(S.name{1});\nylabel(S.name{2});\nhold on\nms=10;\nplot(M.pE(1),M.pE(2),'wo','MarkerSize',ms);\nplot(P(1),P(2),'w+','MarkerSize',ms);\nif ~strcmp(mcmc.inference,'vl')\n    j=post.ind;\n    plot(post.P(1,j),post.P(2,j),'w.');\nend\nplot(post.Ep(1),post.Ep(2),'kx','MarkerSize',ms);\n\nif strcmp(mcmc.inference,'ais')\n    % plot individual trajectories\n    figure\n    xlim([-2 0]);\n    ylim([-2 0]);\n    hold on\n    for i=1:mcmc.maxits,\n        xx=squeeze(post.traj(i,1,:));\n        yy=squeeze(post.traj(i,2,:));\n        plot(xx,yy,'k-');\n        plot(xx(end),yy(end),'kx','MarkerSize',ms);\n        xlabel(S.name{1});\n        ylabel(S.name{2});\n        disp('Press space to see more trajectories');\n        pause\n        \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/mci/demo-thermodynamic/mci_demo_ramsay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5553713150711872}}
{"text": "function varargout = chol( f, varargin )\n%CHOL    Cholesky factorization of a SEPARABLEAPPROX. \n%\n% R = CHOL( F ), if F is a nonnegative definite SEPARABLEAPPROX then this \n% returns an upper triangular quasimatrix so that R'*R is a\n% decomposition of F. If F is not nonnegative definite then an error is thrown.\n%\n% L = CHOL(F, 'lower'), if F is a nonnegative definite SEPARABLEAPPROX then this\n% produces a lower triangular quasimatrix so that L*L' is a decomposition of F.\n% If F is not nonnegative definite then an error is thrown. \n% \n% [R, p] = CHOL( F ), with two outputs never throwns an error message. If F is\n% nonnegative definite then p is 0 and R is the same as above. If F is \n% symmetric but negative definite or semidefinite then p is a positive \n% integer such that R has p columns and R'*R is a rank p nonnegative definite \n% SEPARABLEAPPROX that approximates F. \n% This is particular useful when F is nonnegative definite, but rounding errors\n% have perturbed it to be semidefinite. \n%\n% [L, p] = CHOL(F, 'lower') same as above but the first argument is lower \n% triangular. \n%\n% For more information about the factorization: \n% A. Townsend and L. N. Trefethen, Continuous analogues of matrix\n% factorizations, Proc. Royal Soc. A., 2015. \n%\n% See also LU, and QR. \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    varargout = cell(1, nargout);\n    return\nend\n\n% Is the separableApprox on a square domain?: \nif ( ~domainCheck(f.cols, f.rows) )\n    error('CHEBFUN:SEPARABLEAPPROX:chol:domain', ...\n        'SEPARABLEAPPROX is not on a square domain.');\nend\n\n% Get rank of f: \nk = length( f ); \n\n% All the pivots should be on the y = x line. \nPivLoc = f.pivotLocations; \n\nif ( isempty( PivLoc ) ) \n    % For some reason (probably because f was made with sampling data, rather\n    % than a handle) f didn't have any pivot information. Make it now: \n    f = compose(f, @plus, 0 ); \n    varargout = {chol( f )}; \n    return\nend\n\n% Find the first pivot location is off-diagonal: \nDiagk = find( PivLoc(:,1) ~= PivLoc(:,2), 1, 'first'); \nk = min( k, Diagk ); \n\n% Check that the pivots are positive:  \nPosk = find( pivots( f ) < 0, 1, 'first');\nk = min(k, Posk); \n\n% Were all the pivots nonnegative and the locations on the diagonal?\nposdef = ( k == length( f ) );\n\n\n% Return an error if the function is not nonnegative definite: \nif ( nargout < 2 && ~isempty( posdef ) && ~posdef )\n    error('CHEBFUN:SEPARABLEAPPROX:chol:definite', ...\n        'SEPARABLEAPPROX is not nonnegative definite.');\nend\n\n% Get the CDR decomposition (already computed by constructor):\n[C, D, R] = cdr( f );\n\n% Return an error if the function is not symmetric: \ndom = f.domain; \nr = 0.0192475;   % arbitrary point in [-1,1] \ns = -.34756987;  % arbitrary point in [-1,1]\nr = diff(dom(1:2))/2*r + mean(dom(1:2)); \ns = diff(dom(3:4))/2*s + mean(dom(3:4)); \nsymTest = abs(feval(f,r,s) - feval(f,s,r)) < 1e2*eps;\nif ( ~symTest )\n    error('CHEBFUN:SEPARABLEAPPROX:chol:symmetric', ...\n        'The SEPARABLEAPPROX must be a symmetric function.');\nend\n\n% How many terms are posdef: \np = k; \nif ( isempty( p ) )\n    p = length( f ); \nend\n% Extract out posdef part: \nC = C( :, 1:p ); \nD = D( 1:p, 1:p ); \nR = R( :, 1:p ); \n\n% Balance scaling:\nC = C * sqrt( D ); \nR = R * sqrt( D );\n\n% Output to user: \nif ( ( nargout < 2 ) && ( nargin == 1 ) )\n    varargout = { R.' };\nelseif ( ( nargout < 2 ) && strcmpi( varargin{ 1 }, 'lower') )\n    varargout = { C }; \nelseif ( ( nargout == 2 ) && ( nargin == 1 ) )\n    varargout = { R.', p }; \nelseif ( ( nargout == 2 ) && strcmpi( varargin{ 1 }, 'lower') )\n    varargout = { C, p };\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/@separableApprox/chol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.7025300449389327, "lm_q1q2_score": 0.5553713072346091}}
{"text": "% NMF-ALS: NMF solved by Alternating Least Squares\n% process_video('NMF', 'NMF-ALS', 'dataset/demo.avi', 'output/demo_NMF-ALS.avi');\nalg_path_aux = fullfile(lrs_conf.nmf_path,'NMF-DTU-Toolbox');\naddpath(genpath(alg_path_aux));\n\nM = sparse(M);\n\n% als: Alternating least squares.\n[W, H] = nmf(M,1,'als');\n\nL = W * H;\nS = M - L;\n\nrmpath(genpath(alg_path_aux));\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/NMF-ALS/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5553296089685456}}
{"text": "function showSpaceImages(img, x, y, scaling, limits)\n%\n% Displays images organized in a 2D space\n%\n% input:\n%   img: array [nrows ncols 3 nimages]\n%   x,y  = coordinate for each image\n\nif nargin<5\n    x1 = min(x(:));\n    y1 = min(y(:));\n    x2 = max(x(:));\n    y2 = max(y(:));\nelse\n    x1 = limits(1);\n    x2 = limits(2);\n    y1 = limits(3);\n    y2 = limits(4);\nend\n\n%xa = x - min(x(:));\n%ya = y - min(y(:));\n\nif nargin<4\n    scaling = 2;\nend\n\n%S = max(xa);\n%xa = (0.975-0.05*scaling)*xa/S+0.025;\n%S = max(ya);\n%ya = (0.975-0.05*scaling)*ya/S+0.025;\n\n\nxa = (0.975-0.05*scaling)*(x - x1)/(x2-x1) + 0.05*scaling;\nya = (0.975-0.05*scaling)*(y - y1)/(y2-y1) + 0.05*scaling;\n\nfigure\nfor n = length(xa):-1:1\n    n\n    h=axes('position', [xa(n) ya(n) .05*scaling .05*scaling]);\n    image(uint8(img(:,:,:,n)), 'parent', h)\n    axis('off'); axis('equal')\nend\n\n", "meta": {"author": "CSAILVision", "repo": "LabelMeToolbox", "sha": "b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2", "save_path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox", "path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox/LabelMeToolbox-b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2/main/showSpaceImages.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5553268045035192}}
{"text": "%\n% Extract variable names from any number of polynomial strings\n%\n% Syntax:  (pvar is the shortened alias for GetVariables)\n%          >> z = GetVariables(f)\n%          >> z = GetVariables(f,g,h)\n% \n%  to extract variables from a cell array f of polynomial strings:\n%          >> z = GetVariables(f{:})\n%\n%  Input:   f --- (string) polynomial\n% Output:   z --- (cell)   variable names of f\n% \n% Example:  >> f = '-2*x + 9*x*y^2 - 9*x^2*y^2 + 8*x^3*y^2';\n%           >> g = '5 - x^3*z';\n%           >> z = GetVariables(f,g)\n%           z = \n%               'x'    'y'    'z'\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/GetVariables.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6893056040203134, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.5553267842523278}}
{"text": "classdef prtBrvDiscreteStickBreaking < prtBrv & prtBrvVbOnline\n\n\n\n\n\n\n\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Properties required by prtAction\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    properties (SetAccess = private)\n        name = 'Discrete Stick Breaking Bayesian Random Variable';\n        nameAbbreviation = 'BRVSB';\n    end\n    \n    properties (SetAccess = protected)\n        isSupervised = false;\n        isCrossValidateValid = true;\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Methods for prtBrv\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n    methods\n          \n        function self = estimateParameters(self, x)\n            self = conjugateUpdate(self, self, x);\n        end\n        \n        function y = predictivePdf(self, x)\n            y = exp(predictiveLogPdf(self, x));\n        end\n        \n        function y = predictiveLogPdf(self, x)\n            %%%% FIXME\n            % The true predictive here is a product of beta-binomials\n            % Since that isn't implemented yet we use the average\n            % variational loglikelihood\n            \n            y = conjugateVariationalAverageLogLikelihood(self, x);\n        end\n        \n        function val = getNumDimensions(self)\n            val = size(self.model.beta,1);\n        end\n    \n        function self = initialize(self, x)\n            x = self.parseInputData(x);\n            if ~self.model.isValid\n                self.model = self.model.defaultParameters(size(x,2));\n            end\n        end\n        \n        % Optional methods\n        %------------------------------------------------------------------\n        function kld = conjugateKld(obj, priorObj)\n            kld = obj.model.kld(priorObj.model);\n        end\n        \n        function s = posteriorMeanStruct(obj)\n            s.probabilities = exp(obj.model.expectedValueLogProbabilities);\n        end\n        \n        function val = plotLimits(self)\n            val = [0 length(self(1).model.lambda)+1 0 length(self(1).model.lambda)+1];\n        end\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Methods for prtBrvVb\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n    methods\n        function [self, training] = vbBatch(self,x)\n            % Since we are purely conjugate we actually don't need vbBatch\n            % However we must implement it.\n            self = conjugateUpdate(self,x);\n            training = struct([]);\n        end\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Methods for prtBrvVbOnline\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n    methods\n        function self = vbOnlineInitialize(self, x) %#ok<INUSD>\n            randDraw = rand(1,self.nDimensions);\n            randDraw = randDraw./sum(randDraw);\n            \n            self = self.conjugateUpdate(self, randDraw);\n        end\n        \n        function [self, training] = vbOnlineUpdate(self, priorSelf, x, training, prevSelf, learningRate, D) %#ok<INUSL>\n            x = self.parseInputData(x);\n            \n            [self.model, training] = self.model.vbOnlineWeightedUpdate(priorObj.model, sum(x,1), [], lambda, D, prevObj.model);\n        end\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Methods for prtBrvMembershipModel\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n    methods\n        % Don't actually inherit from prtBrvMembershipModel but these two\n        % methods are abstracted there\n        function self = conjugateUpdate(self, prior, x)\n            x = parseInputData(self,x); \n            self.model = self.model.conjugateUpdate(prior.model,x);\n        end\n        \n        function obj = weightedConjugateUpdate(obj, priorObj, x, weights)\n            x = parseInputData(self,x); \n            obj.model = obj.model.conjugateUpdate(priorObj.model,bsxfun(@times,x,weights));\n        end\n    end\n    \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Methods for prtBrvVbOnlineMembershipModel\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n    methods\n        function [obj, training] = vbOnlineWeightedUpdate(obj, priorObj, x, weights, lambda, D, prevObj)\n            x = obj.parseInputData(x);\n            if ~isempty(weights)\n                x = bsxfun(@times,x,weights);\n            end\n            \n            [obj.model, training] = obj.model.vbOnlineWeightedUpdate(priorObj.model, sum(x,1), [], lambda, D, prevObj.model);\n        end\n    end\n        \n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Properties for prtBrvDiscreteStickBreaking use\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    properties\n        model = prtBrvDiscreteStickBreakingHierarchy;\n    end\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    % Methods for prtBrvDiscreteStickBreaking use\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    methods\n        function obj = prtBrvDiscreteStickBreaking(varargin)\n            if nargin < 1\n                return\n            end\n            obj = obj.constructorInputParse(varargin{:});\n        end\n        \n        function val = expectedLogMean(obj)\n            val = obj.model.expectedValueLogProbabilities(:)';\n        end\n        \n        function model = modelDraw(obj)\n            model.probabilities = draw(obj.model);\n        end\n    end\n    \n    methods (Hidden)\n        function x = parseInputData(self,x) %#ok<MANU>\n            if isnumeric(x)\n                return\n            elseif prtUtilIsSubClass(class(x),'prtDataSetBase')\n                x = x.getObservations();\n            else \n                error('prt:prtBrvDiscreteStickBreaking:parseInputData','prtBrvDiscreteStickBreaking requires a prtDataSet or a numeric 2-D matrix');\n            end\n        end\n    end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/]beta/brv/prtBrvDiscreteStickBreaking.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478256, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5553267762103462}}
{"text": "% This is material illustrating the methods from the book\n% Financial Modelling  - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors:  Joerg Kienitz\n%           Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\nfunction [y,m] = getPathsAsian(S0, r, sigma, dt, NSim, Nr)\n% path retrieval for Asian options\n\nif length(S0) > 1\n    lenS = length(S0);             % for using this with different starting values\n    R = exp((r - sigma^2/2) * dt ...\n    + sigma * sqrt(dt) * randn(NSim,Nr,lenS));   % random noise + drift\n    tmp = zeros(NSim,1,lenS);\n    tmp(:,1,:) = repmat(log(S0)',NSim,1);\n    y = exp(cumsum([tmp, R], 2));    % path set simple example\nelse\n    R = exp((r - sigma^2/2) * dt ...\n    + sigma * sqrt(dt) * randn(NSim,Nr));\n    y = cumprod([S0*ones(NSim,1), R], 2); %S0 in Spalte 1 -> Indexverschiebung\n\nend\n\ntmp = repmat(1:Nr, NSim, 1); %Hilfsmatrix\nm = [y(:,1) cumsum(y(:,2:end), 2) ./ tmp];\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/37620-american-monte-carlo/AmericanMC/getPathsAsian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5553267762103461}}
{"text": "classdef CEC2017_F3 < PROBLEM\n% <single> <real> <constrained>\n% CEC'2017 constrained optimization benchmark problem\n\n%------------------------------- Reference --------------------------------\n% G. Wu, R. Mallipeddi, and P. N. Suganthan, Problem definitions and\n% evaluation criteria for the CEC 2017 competition on constrained real-\n% parameter optimization, National University of Defense Technology, China,\n% 2016.\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        O;  % Optimal decision vector\n    end\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            CallStack = dbstack('-completenames');\n            load(fullfile(fileparts(CallStack(1).file),'CEC2017.mat'),'Data');\n            obj.O = Data{3};\n            obj.M = 1;\n            if isempty(obj.D); obj.D = 10; end\n            obj.D = min(obj.D,length(obj.O));\n            obj.lower    = zeros(1,obj.D) - 100;\n            obj.upper    = zeros(1,obj.D) + 100;\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopObj = sum(cumsum(Z,2).^2,2);\n        end\n        %% Calculate constraint violations\n        function PopCon = CalCon(obj,PopDec)\n            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n            PopCon(:,1) = sum(Z.^2-5000*cos(0.1*pi*Z)-4000,2);\n            PopCon(:,2) = abs(sum(Z.*sin(0.1*pi*Z),2)) - 1e-4;\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/Single-objective optimization/CEC 2017/CEC2017_F3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.817574471748733, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5552791768196058}}
{"text": "%% housekeeping\nclear\nclose all\nclc\n%% bring in the data\n[num,txt] = xlsread('Smets_Wouters_data.xlsx');\nvnames=strrep(txt,' ','');\ndate_start='1947q3';\ndata=ts(date_start,num(:,2:end),vnames);\ndata=pages2struct(data);\nfigure('name','observed data')\nfor ii=1:numel(vnames)\n    subplot(3,3,ii)\n    v=vnames{ii};\n    plot(data.(v),'linewidth',2)\n    title(v)\nend\nxrotate(45)\n\n%% Set the RFVAR\nendo_aliases=struct('robs','interest rates',...\n    'dy','GDP growth',...\n    'labobs','hours worked',...\n    'pinfobs','inflation',...\n    'dw','wages growth',...\n    'dc','Consumption growth',...\n    'dinve','Investment growth');\n\nendog=fieldnames(endo_aliases);\n\nnlags=3;\n\nconst=true;\n\nexog={};\n\nrv=rfvar(endog,exog,nlags,const); % formerly redfvar\n\n%% Estimate the reduced-form VAR\n\nrv1=estimate(rv,data);%,{db.LGDP.start,db.LGDP.finish}\n\n%% identification setup\n\nshock_aliases=struct('mp','monetary policy',...\n    'ad','aggreg. demand',...\n    'as','aggreg. supply',...\n    'ls','labor supply');\n\nstructural_shocks=fieldnames(shock_aliases);\n\nident_restr={\n    %     'dy{inf}@mp',0\n    %     'dy{inf}@ad',0\n    %     'dy{inf}@as',0\n    %     'dy{inf}@ls',0\n    'robs{0}@mp','+'\n    'dy@mp','-'\n    'pinfobs@mp','-'\n    'robs{0}@ad','+'\n    'pinfobs@ad','+'\n    'dy@ad','+'\n    %     'robs@as','-'\n    'dy@as','+'\n    'pinfobs@as','-'\n    'robs@ls','-'\n    'dy@ls','+'\n    'labobs@ls','+'\n    %     'pinfobs@ls','-'\n    'dw@ls','-'\n    };\n\nagnostic=true;\n\nmax_trials=6000;\n\n[Rfunc,ident]=identification(rv1,ident_restr,structural_shocks,...\n        agnostic,max_trials);\n\n%% Impulse responses\n\nmyirfs=irf(rv1,structural_shocks,40,[],Rfunc);\n\n%% Plot the IRFs for one particular rotation\n\nfor ishock=1:numel(structural_shocks)\n    \n    shock=structural_shocks{ishock};\n    \n    figure('name',['Orthogonalized responses to a ',...\n        shock_aliases.(shock),' shock']);\n    \n    for ivar=1:numel(endog)\n        \n        vname=endog{ivar};\n        \n        subplot(3,3,ivar)\n        \n        plot(myirfs.(shock).(vname),'linewidth',2)\n        \n        title(endo_aliases.(vname))\n        \n    end\n    \nend\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/RFVAR_identification/howto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5552791752579793}}
{"text": "function estimation_results = notREKF_SLAM(data, NumberOfSteps)\n% R-EKF SLAM \n\n% load pre-given data: odometry and observations\nif nargin < 1\n    load('./data.mat');\nend\n\ndata_matrix = data.state;\n\nodom_sigma = data.odom_sigma;\nobsv_sigma = data.obsv_sigma;\n\n% odoCov = data.odom_cov;   % constant variable\n% obsCov = data.obse_cov;   % constant variable\n\n%%%%%%%%%%%%%%%%%%%% Estimation_X is used to save the state in each step %%%%%%%%%%%%%%%%%%%%  \n%%%%%%%%%%%%%%%%%%%% In every step, all elements of Estimation_X will be changed %%%%%%%%%%%%\nEstimation_X.orientation = data.poses.orientation(1:3,1:3);\nEstimation_X.position    = data.poses.position(:,1);\nEstimation_X.cov         = sparse(6,6);\nEstimation_X.landmarks   = [];       % the landmarks observed until this step (included), 4*N format, the 4-th row is the index\nEstimation_X0.IndexObservedNew=[];\nEstimation_X0.IndexObservedAlreadyThis=[];\n%%%%%%%%%%%%%%%%%%%% Estimation_X is used to save the state in each step %%%%%%%%%%%%%%%%%%%%  \n\n\n% Initialize\nif nargin < 2\n    NumberOfSteps = max(data_matrix(:,4));  % step instead of pose,  hence, it does not include pose 0\nelseif NumberOfSteps > max(data_matrix(:,4))\n    NumberOfSteps = max(data_matrix(:,4));\nend\nestimation_results = cell(1, NumberOfSteps+1);\nestimation_results{1} = Estimation_X;\nrow_idx = (data_matrix(:, end) <= NumberOfSteps+1);\ndata_matrix = data_matrix(row_idx, :);\n\n\nfor i = 0:NumberOfSteps\n    IndexOfCurrentStepInDataMatrix = find(data_matrix(:,4) == i); \n    m = size(IndexOfCurrentStepInDataMatrix, 1);\n    if ( mod(i, 50) == 0 )\n        disp(['Processing pose ', int2str(i)]);\n    end\n    % det(Estimation_X.cov)\n    if i==NumberOfSteps-1\n    a=1;\n    end\n    \n    if i ~= NumberOfSteps\n        OdometryFromThis2Next = data_matrix(IndexOfCurrentStepInDataMatrix(m-5):IndexOfCurrentStepInDataMatrix(m),1);\n        if m > 6\n            CameraMeasurementThis = [ data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(m-6) , 1 ),...\n                                      data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(m-6) , 3 )];    \n           [Estimation_X] = notREKF_update(Estimation_X, CameraMeasurementThis, obsv_sigma );\n        end\n        \n        estimation_results{i+1} = Estimation_X;\n        \n%        propagation using odometry info\n        [Estimation_X] = notREKF_propagate(Estimation_X, OdometryFromThis2Next, odom_sigma );\n\n    else\n        a=2;\n        if m > 6\n            CameraMeasurementThis = [ data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(end) , 1 ) , ...\n                                      data_matrix( IndexOfCurrentStepInDataMatrix(1): IndexOfCurrentStepInDataMatrix(end) , 3 )];\n            [Estimation_X] = notREKF_update(Estimation_X, CameraMeasurementThis, obsv_sigma );\n        end\n        estimation_results{i+1} = Estimation_X;\n    end\nend\nclearvars -except estimation_results", "meta": {"author": "RomaTeng", "repo": "EKF-SLAM-on-Manifold", "sha": "12d7d8d88c84161baed173e38d49dedb4adb2b96", "save_path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold", "path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold/EKF-SLAM-on-Manifold-12d7d8d88c84161baed173e38d49dedb4adb2b96/not_right_ekf_3d/notREKF_SLAM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5552791692202022}}
{"text": "function foff=comp_warpedfoff(fc,bw,fs,L,freqtoscale,scaletofreq,do_symmetric)\n%COMP_WARPEDFOFF  foff for warped filters\n\nfcwasnegative = fc < 0;\n\nif fcwasnegative && do_symmetric\n   fc = -fc;\n   fcscale = freqtoscale(fc);\n   foff = -floor(scaletofreq(fcscale+.5*bw)/fs*L)+1;\nelse\n   fcscale = freqtoscale(fc);\n   foff = floor(scaletofreq(fcscale-.5*bw)/fs*L)+1;\nend\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_warpedfoff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5552791646396867}}
{"text": "function gT = simwhiteKernDiagGradX(kern, t)\n\n% SIMWHITEKERNDIAGGRADX Gradient of SIM-WHITE kernel's diagonal w.r.t. t.\n% FORMAT\n% DESC computes the gradient of the diagonal of the SIM-White (Single Input\n% Motif - White) kernel matrix with respect to the elements of the input\n% column vector given in t.\n% ARG kern : the kernel structure for which gradients are being computed.\n% ARG t : the input data in the form of a design matrix.\n% RETURN gT : the gradients of the diagonal with respect to each element\n% of t. The returned matrix has the same dimensions as t.\n%\n% SEEALSO : simwhiteKernParamInit, kernDiagGradX, simwhitekernGradX\n%\n% COPYRIGHT : David Luengo, 2009\n\n% KERN\n\n\nif (kern.isStationary == true)\n    gT = zeros(size(t));\nelse\n    gT = kern.variance * (kern.sensitivity^2) * exp(-2*kern.decay*t);\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/simwhiteKernDiagGradX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5552791639110559}}
{"text": "function [OffDec,OffVel] = Operator_LMOCSO(Problem,Loser,Winner,Rate)\n% The competitive swarm optimizer of LMOCSO\n\n%  Copyright (C) 2021 Xu Yang\n%  Xu Yang <xuyang.busyxu@qq.com> or <xuyang369369@gmail.com>\n\n    %% Parameter setting\n    LoserDec  = Loser.decs;\n    WinnerDec = Winner.decs;\n    [N,D]     = size(LoserDec);\n\tLoserVel  = Loser.adds(zeros(N,D));\n    WinnerVel = Winner.adds(zeros(N,D));\n    \n    %% Competitive swarm optimizer\n    r1     = repmat(rand(N,1),1,D);\n    r2     = repmat(rand(N,1),1,D);\n    \n    OffVel = r1.*LoserVel + r2.*(WinnerDec-LoserDec);\n    OffDec = LoserDec + OffVel;\n    \n    if Problem.FE/Problem.maxFE < Rate\n        LoserVel1 = rand(N,D);\n        OffVel1 = r1.*LoserVel1 + r2.*(WinnerDec-LoserDec);\n        OffDec1 = LoserDec + OffVel1 + r1.*(OffVel1-LoserVel1);\n        \n        OffDec = [OffDec;OffDec1];\n        OffVel = [OffVel;OffVel1];\n    end\n    \n    %% Add the winners\n    OffDec = [OffDec;WinnerDec];\n    OffVel = [OffVel;WinnerVel];\n \n    %% Polynomial mutation\n    [N,D] = size(OffDec);\n    Lower = repmat(Problem.lower,N,1);\n    Upper = repmat(Problem.upper,N,1);\n    disM  = 20;\n    Site  = rand(N,D) < 1/D;\n    mu    = rand(N,D);\n    temp  = Site & mu<=0.5;\n    OffDec       = max(min(OffDec,Upper),Lower);\n    OffDec(temp) = OffDec(temp)+(Upper(temp)-Lower(temp)).*((2.*mu(temp)+(1-2.*mu(temp)).*...\n                   (1-(OffDec(temp)-Lower(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1))-1);\n    temp  = Site & mu>0.5; \n    OffDec(temp) = OffDec(temp)+(Upper(temp)-Lower(temp)).*(1-(2.*(1-mu(temp))+2.*(mu(temp)-0.5).*...\n                   (1-(Upper(temp)-OffDec(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1)));          \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/FDV/Operator_LMOCSO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5552791631824249}}
{"text": "function bd = mne_block_diag(A,n);\n%\n%   function bd = mne_block_diag(A,n)\n%\n%   Make or extract a sparse block diagonal matrix\n%\n%   If A is not sparse, then returns a sparse block diagonal \"bd\", diagonalized from the\n%   elements in \"A\".\n%   \"A\" is ma x na, comprising bdn=(na/\"n\") blocks of submatrices.\n%   Each submatrix is ma x \"n\", and these submatrices are\n%   placed down the diagonal of the matrix.\n%\n%   If A is already sparse, then the operation is reversed, yielding a block\n%   row matrix, where each set of n columns corresponds to a block element\n%   from the block diagonal.\n%\n%   Routine uses NO for-loops for speed considerations.\n\n\n\n%\n% Principal Investigators and Developers:\n% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,\n%    University of Southern California, Los Angeles, CA\n% ** John C. Mosher, PhD, Biophysics Group,\n%    Los Alamos National Laboratory, Los Alamos, NM\n% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,\n%    CNRS, Hopital de la Salpetriere, Paris, France\n%\n% Copyright (c) 2005 BrainStorm by the University of Southern California\n% This software distributed  under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPL\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% Author: John C. Mosher 1993 - 2004\n%\n%\n% Modifications for mne Matlab toolbox\n%\n%   Matti Hamalainen\n%   2006\n%   Revision 1.2  2006/04/23 15:29:40  msh\n%   Added MGH to the copyright\n%\n%   Revision 1.1  2006/04/18 20:44:46  msh\n%   Added reading of forward solution.\n%   Use length instead of size when appropriate\n%\n%\n\n\nif(~issparse(A)),        % then make block sparse\n    [ma,na] = size(A);\n    bdn = na/n;             % number of submatrices\n\n    if(bdn - fix(bdn)),\n        error('Width of matrix must be even multiple of n');\n    end\n\n    tmp = reshape([1:(ma*bdn)]',ma,bdn);\n    i = zeros(ma*n,bdn);\n    for iblock = 1:n,\n        i((iblock-1)*ma+[1:ma],:) = tmp;\n    end\n\n    i = i(:);             % row indices foreach sparse bd\n\n\n    j = [1:na];\n    j = j(ones(ma,1),:);\n    j = j(:);             % column indices foreach sparse bd\n\n    bd = sparse(i,j,A(:));\n\nelse                 % already is sparse, unblock it\n\n    [mA,na] = size(A);        % matrix always has na columns\n    % how many entries in the first column?\n    bdn = na/n;            % number of blocks\n    ma = mA/bdn;            % rows in first block\n\n    % blocks may themselves contain zero entries.  Build indexing as above\n    tmp = reshape([1:(ma*bdn)]',ma,bdn);\n    i = zeros(ma*n,bdn);\n    for iblock = 1:n,\n        i((iblock-1)*ma+[1:ma],:) = tmp;\n    end\n\n    i = i(:);             % row indices foreach sparse bd\n\n\n    j = [0:mA:(mA*(na-1))];\n    j = j(ones(ma,1),:);\n    j = j(:);\n\n    i = i + j;\n\n    bd = full(A(i));     % column vector\n    bd = reshape(bd,ma,na);    % full matrix\nend\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/external/mne/mne_block_diag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5552791518355011}}
{"text": "function [P] = prolongation(CV,CF,V,varargin)\n  % PROLONGATION Build a linear prolongation operator taking solutions on a\n  % coarse mesh (CV,CF) and prolongating (upsampling) them onto vertices of a\n  % fine mesh (V). Useful for multigrid and embedded mesh deformations.\n  %\n  % P = prolongation(CV,CF,V)\n  %\n  % Inputs:\n  %   CV  #CV by dim list of coarse mesh vertex positions\n  %   CF  #CF by dim+1 list of coarse mesh element indices into CV\n  %   V  #V by dim list of fine mesh vertex positions\n  %   Optional:\n  %     'Extrapolation'  followed by name of method to use for points in V\n  %       lying outside (CV,CF). One of the following:\n  %         {'linear'}   finds closest element and uses barycentric coordinates\n  %           (with some negative weights). This is linearly precise.\n  %         'contstant'  finds closest point and uses its barycentric\n  %           coordinates (all non-negtive since it lies on a facet). This is\n  %           only constantly precise.\n  % Outputs:\n  %   P  #V by #CV prolongation matrix so that X = P * CX prolongates a\n  %     solution CX on the coarse mesh to a solution X on the fine mesh.\n  % \n\n  [I] = in_element_aabb(CV,CF,V);\n  I0 = find(I==0);\n  extrapolation = 'linear';\n  % Map of parameter names to variable names\n  params_to_variables = containers.Map( ...\n    {'Extrapolation'}, ...\n    {'extrapolation'});\n  v = 1;\n  while v <= numel(varargin)\n    param_name = varargin{v};\n    if isKey(params_to_variables,param_name)\n      assert(v+1<=numel(varargin));\n      v = v+1;\n      % Trick: use feval on anonymous function to use assignin to this workspace\n      feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n    else\n      error('Unsupported parameter: %s',varargin{v});\n    end\n    v=v+1;\n  end\n\n  switch size(CF,2)\n  case 4\n    [BF,BJ,BK] = boundary_faces(CF);\n    BV = V;\n    % Extrapolate\n    % Snap to boudnary and use snapped points interpolation\n    [~,BI,BVI0] = point_mesh_squared_distance(V(I0,:),CV,BF);\n    I(I0) = BJ(BI);\n    switch extrapolation\n    case 'linear'\n      % Leave BV\n    case 'constant'\n      BV(I0,:) = BVI0;\n    otherwise\n      error('Unknown extrapolation (%s)',extrapolation);\n    end\n    [IV] = max(I,[],2);\n    % recover barycentric coordinates (interpolation & extrapolation)\n    B = barycentric_coordinates( ...\n      BV,CV(CF(IV,1),:),CV(CF(IV,2),:),CV(CF(IV,3),:),CV(CF(IV,4),:));\n    %% Snap to closest vertex\n    %B(any(B<0,2),:) = bsxfun(@eq,max(B(any(B<0,2),:),[],2),B(any(B<0,2),:));\n  case 3\n    % Dirty trick to make V,CV 3D\n    BV = V;\n    if ~isempty(I0)\n      pV = V;\n      pCV = CV;\n      pBV = BV;\n      pV(:,end+1:3) = 0;\n      pCV(:,end+1:3) = 0;\n      [~,I(I0),pBVI0] = point_mesh_squared_distance(pV(I0,:),pCV,CF);\n      switch extrapolation\n      case 'linear'\n        % Leave BV\n      case 'constant'\n        BV(I0,:) = pBVI0(:,1:2);\n      otherwise\n        error('Unknown extrapolation (%s)',extrapolation);\n      end\n    end\n    [IV] = max(I,[],2);\n    B = barycentric_coordinates( ...\n      BV,CV(CF(IV,1),:),CV(CF(IV,2),:),CV(CF(IV,3),:));\n  end\n\n  P = sparse( ...\n    repmat(1:size(V,1),size(CF,2),1)', ...\n    CF(IV,:), ...\n    B, ...\n    size(V,1),size(CV,1));\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/prolongation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.555279146526355}}
{"text": "function [str] = printDVManeuversMFMSToTextbox(hDvManInfoText,waypoints,dVDepartVectNTW,deltaVVectNTW,eOrbit,orbitsIn,paddLen,form)\n%UNTITLED4 Summary of this function goes here\n%   Detailed explanation goes here\n\n    hRule = getHRule();\n    str = {};\n    \n    sumDv = 0;\n    for(i=1:length(waypoints)-1) %#ok<*NO4LP>\n        if(i==1)\n            dvVect = dVDepartVectNTW;\n            ta = eOrbit(8);\n        else\n            dvVect = deltaVVectNTW(:,i-1);\n            ta = orbitsIn(i-1,6);\n        end\n        \n        str{end+1} = ['Burn Information to Depart ', cap1stLetter(waypoints{i}.name)];\n        str{end+1} = hRule;\n        str{end+1} = [paddStr('Total Delta-V = ',paddLen), num2str(norm(dvVect), form), ' km/s'];\n        str{end+1} = [paddStr('Prograde Delta-V = ',paddLen), num2str(1000*dvVect(1), form), ' m/s'];\n        str{end+1} = [paddStr('Orbit Normal Delta-V = ',paddLen), num2str(1000*dvVect(2), form), ' m/s'];\n        str{end+1} = [paddStr('Radial Delta-V = ',paddLen), num2str(1000*dvVect(3), form), ' m/s'];\n        str{end+1} = '---------------------';\n        str{end+1} = [paddStr('Burn True Anomaly = ',paddLen), num2str(rad2deg(ta), form), ' deg'];\n        str{end+1} = hRule;\n        \n        sumDv = sumDv + norm(dvVect);\n    end\n    \n    str{end+1} = [paddStr('Total Mission Delta-V = ',paddLen), num2str(sumDv, form), ' km/s'];\n    \n    set(hDvManInfoText,'String',str);\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/text/analysisOutputs/printDVManeuversMFMSToTextbox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7217432182679957, "lm_q1q2_score": 0.5550784377697014}}
{"text": "function visualizeData( X, k, IDX, types, C )\n% Project high dim. data unto principal components (PCA) for visualization.\n%\n% Optionally IDX can be specified to indicate different classes for the\n% points; in this case points in different classes are displayed using\n% different colors. Up to 12 types are handled (for technical reasons\n% involving plot), any cluster with a label>12 is assigned the label 12.\n%\n% USAGE\n%  visualizeData( X, k, [IDX], [types], [C] )\n%\n% INPUTS\n%  X       - column vector of data - N vectors of dimension p (X is Nxp)\n%  k       - dimension to which to reduce data (2 or 3)\n%  IDX     - [] cluster membership [see kmeans2.m]\n%  types   - [] cell array of length ntypes of text labels for each type\n%  C       - [] cluster centers (Kxp)\n%\n% OUTPUTS\n%\n% EXAMPLE\n%  X = [randn(100,5); randn(100,5)+4];\n%  C = [mean(X(1:100,:)); mean(X(101:200,:))];\n%  IDX = [ones(100,1); 2*ones(100,1)];\n%  visualizeData( X, 2, IDX, {'type1','type2' }, C);\n%\n% See also KMEANS2, DEMOCLUSTER\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 || isempty(IDX) ); IDX=[]; end\nif( nargin<4 || isempty(types) ); types=[]; end\nif( nargin<5 || isempty(C) ); C=[]; end\n\n% apply PCA if necessary\nif( size(X,2)~= k )\n  [ U, mu ] = pca( X' );\n  X = pcaApply( X', U, mu, k )';\n  if(~isempty(C)); C = pcaApply( C', U, mu, k )'; end\nend\n\n%%% get k\nk = size(X,2);\nif( k==1 ); X = [X zeros(size(X))]; k = 2; end\nif( k>3 ); error( 'k must be <= 3'); end\n\n%%% show points\nif( isempty(IDX) )\n  if( k==2 )\n    plot( X(:,1), X(:,2), '.' );\n  elseif( k==3 )\n    plot3( X(:,1), X(:,2), X(:,3), '.' );\n  end;\n\nelse\n  IDX(IDX>12)=12;  m=max(IDX);\n\n  if( k==2)\n    % plot points\n    R = cell(1,3*m+3);\n    for i=1:m;\n      R((3*i-2):(3*i)) = {X(IDX==i,1), X(IDX==i,2), '.'};\n    end;\n    R((3*m+1):(3*m+3)) = {X(IDX==-1,1), X(IDX==-1,2), 'k.'};\n    plot( R{:} );\n\n    % plot centers\n    if( ~isempty(C) )\n      R=cell(1,3*m);\n      for i=1:m;  R((3*i-2):(3*i)) = {C(i,1), C(i,2), 'x'}; end\n      hold('on');  plot( R{:}, 'MarkerSize', 30 );  hold('off');\n    end;\n\n  elseif( k==3 )\n    % plot points\n    R = cell(1,4*m+4);\n    for i=1:m;\n      R((4*i-3):(4*i)) = {X(IDX==i,1), X(IDX==i,2), X(IDX==i,3), '.'};\n    end;\n    R((4*m+1):(4*m+4)) = {X(IDX==-1,1), X(IDX==-1,2), X(IDX==-1,3), 'k.'};\n    plot3( R{:} );\n\n    % plot centers\n    if( ~isempty(C) )\n      R=cell(1,4*m);\n      for i=1:m;  R((4*i-3):(4*i)) = {C(i,1), C(i,2), C(i,3), 'x'}; end\n      hold('on'); plot3( R{:}, 'MarkerSize', 30 );  hold('off');\n    end\n  end\nend\naxis('equal');\n\n%%% show legend if types is provided\nif(~isempty(types));  legend(types); end\n", "meta": {"author": "pdollar", "repo": "toolbox", "sha": "e87332637bbe8e8b92dd487c87567d9628404523", "save_path": "github-repos/MATLAB/pdollar-toolbox", "path": "github-repos/MATLAB/pdollar-toolbox/toolbox-e87332637bbe8e8b92dd487c87567d9628404523/classify/visualizeData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5550784362035441}}
{"text": "%BUCKYTUMBLE shows tumbling Bucky Ball\n%   BUCKYTUMBLE -- display the Bucky Ball, slowly tumbling in space\n%   Needs perms.m\n\n%   Bill McKeeman\n\nfunction buckytumble\n  gr = (1+sqrt(5))/2;                  % golden ration\n  d = @(a,b) a + b*gr;                 % vertex function\n\n  bb = perms(...                       % Bucky Ball vertices\n    [d(0,0), d(0,3), d(1,0)            % truncated icosahedron\n     d(1,0), d(0,2), d(2,1)\n     d(2,0), d(0,1), d(1,2)]/2, 'cycles', 'signs', 'unique');\n  [s,f] = edges(bb);                   % start,finish\n  \n  mx = max(abs(bb(:)))*1.2;            % frame the picture\n  mz = max(abs(bb(3,:)));              % z scale\n  clip = @(vec) min(max(vec,0),1);     % black and white\n  axis([-mx mx -mx mx]);               % fix the axes\n  axis equal\n  axis off\n  bg = .8*[1 1 1];                     % background grey\n  set(gcf, 'color', bg);\n\n  hold on\n  tumble;                              % plot it\n  hold off\n\n  return;\n  \n  % compute the edges of a polyhedron\n  function [s,f] = edges(p)\n    m = size(p,1);\n    d = inf(m);                        % distance matrix\n    for i=1:m\n      for j=i+1:m\n        seg = p(i,:)-p(j,:);           % vertex pairs\n        d(i,j) = sqrt(seg*seg');       % distance between\n      end\n    end  \n    es = min(d(:));                    % nearest neighbors\n    TOL = es/10000;\n    [s,f] = find(abs(d-es)<TOL);       % compensate for roundoff\n  end\n\n  % tumble until stopped with ^C\n  function tumble\n    nd = size(bb,2);\n    a = rand(nd)/25;                   % about 1 degree\n    p = bb;                            % rotatable vertex set\n    for reps = 1:intmax\n      dr = ndrotate(a);\n      for i=1:100                      % 100, then change direction\n        cla;                           % clear previous\n        fromInfinity(p);               % new edges\n        drawnow;\n        p = p*dr;                      % new position\n        pause(0.03);                   % leave some cycles \n      end\n      a = a + (rand-0.5)/100;          % change direction\n    end\n  end\n\n  % plot 2-D shadow of edges\n  function fromInfinity(p) \n    for k = 1:numel(s)                 % all edges\n      e1 = [p(s(k),1)  p(f(k),1)];     % x end\n      e2 = [p(s(k),2)  p(f(k),2)];     % y end\n      z = p(s(k),3) + p(f(k),3);       % 2*mx : -2*mx\n      h = ((z+2*mz)/mz)/4;             %    1 : 0 \n      h = 1-h;                         %    0 : 1\n      c = clip([h h h]);               % black is nearest\n      w = 2-h;\n      plot(e1, e2, 'color', c, 'linewidth', w);\n    end\n  end\n\n  % turn angles into orthogonal matrix\n  function res = ndrotate(angles)\n    [m,n] = size(angles);\n    res = eye(n);\n    for i=1:m\n      for j=1:n\n        if i ~= j && angles(i,j) ~= 0\n          tmp = eye(n);\n          tmp(i,i) = cos(angles(i,j));\n          tmp(j,j) = tmp(i,i);\n          tmp(i,j) = -sin(angles(i,j));\n          tmp(j,i) = -tmp(i,j);\n          res = res*tmp;\n        end\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/10329-tumbling-bucky-ball/buckytumble.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.555024523781828}}
{"text": "function [u,p,edge,A,eqn,info] = StokesP2P1(node,elem,pde,bdFlag,option)\n%% STOKESP2P1 Stokes equation: P2-P1 Taylor-Hood elements.\n%\n%   [u,p] = STOKESP2P1(node,elem,pde,bdFlag) use quadratic and piceswise\n%   linear elements to approximate velocity u and pressure p, repectively.\n% \n%       -div(mu*grad u) + grad p = f in \\Omega,\n%                        - div u = 0  in \\Omega,\n%   with \n%       Dirichlet boundary condition        u = g_D  on \\Gamma_D, \n%       Neumann boundary condition du/dn - np = g_N  on \\Gamma_N.\n%\n%   It is a choice of option.fem in Stokes. Please read Stokes for more\n%   information on the input and output.\n%\n% See also Stokes, Poisson, StokesP2P1\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('option','var'), option = []; end\n\ntic;\n%% Construct Data Structure\n[elem2dof,edge,bdDof] = dofP2(elem);\nN = size(node,1);  NT = size(elem,1);  Nu = N+size(edge,1);   Np = N;\n\n%% Compute geometric quantities and gradient of local basis\n[Dlambda,area] = gradbasis(node,elem);\n\n%% Assemble stiffness matrix for Laplace operator\n% generate sparse pattern\nii = zeros(21*NT,1); jj = 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,'nu'), pde.nu = []; end\nif ~isfield(option,'quadorder')\n    % constant viscosity\n    option.quadorder = 2;        % default order\n    if ~isempty(pde.nu) && isnumeric(pde.nu) % numerical viscosity\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(:,:,5) = 4*(lambda(p,3)*Dlambda(:,:,1)+lambda(p,1)*Dlambda(:,:,3));\n    Dphip(:,:,4) = 4*(lambda(p,2)*Dlambda(:,:,3)+lambda(p,3)*Dlambda(:,:,2));\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    index = 0;\n    for i = 1:6\n        for j = i:6\n            Aij = 0;\n            if isempty(pde.nu) || isnumeric(pde.nu)\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.nu) && (pde.nu~=1)\n                Aij = pde.nu*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);   upperIdx = ~diagIdx;\nA = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Nu,Nu);\nAU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Nu,Nu);\nA = A + AU + AU';\nA = blkdiag(A,A);\nclear Aij ii jj sA\n\n%% Assemble the matrix for divergence operator\nDx = sparse(Np,Nu);\nDy = sparse(Np,Nu);\n[lambda, w] = quadpts(2); % (div(P2), P1) is P2\nnQuad = size(lambda,1);\nfor p = 1:nQuad\n    % Dphi at quadrature points\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    Dphip(:,:,6) = 4*(lambda(p,1)*Dlambda(:,:,2)+lambda(p,2)*Dlambda(:,:,1));    \n    for i = 1:6 \n        for j = 1:3\n            Dxij = 0;\n            Dyij = 0;\n            Dxij = Dxij + w(p)*Dphip(:,1,i).*lambda(p,j);\n            Dyij = Dyij + w(p)*Dphip(:,2,i).*lambda(p,j);\n            Dx = Dx + sparse(elem(:,j),double(elem2dof(:,i)),Dxij.*area,Np,Nu);\n            Dy = Dy + sparse(elem(:,j),double(elem2dof(:,i)),Dyij.*area,Np,Nu);\n        end\n    end\nend\nB = -[Dx Dy];\nclear Dxij Dyij Dx Dy Dphip\n\n%% Assemble right hand side\nf1 = zeros(Nu,1);\nf2 = zeros(Nu,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,weight] = quadpts(option.fquadorder);\n    % basis values at quadrature points\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    phi(:,6) = 4*lambda(:,1).*lambda(:,2);\n    nQuad = size(lambda,1);\n    ft1 = zeros(NT,6);\n    ft2 = 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        % function values at quadrature points\n        fp = pde.f(pxy);\n        % evaluate fp outside.\n        for j = 1:6\n            ft1(:,j) = ft1(:,j) + fp(:,1).*phi(p,j)*weight(p);\n            ft2(:,j) = ft2(:,j) + fp(:,2).*phi(p,j)*weight(p);\n        end\n    end\n    ft1 = ft1.*repmat(area,1,6);\n    ft2 = ft2.*repmat(area,1,6);\n    f1 = accumarray(elem2dof(:),ft1(:),[Nu 1]);\n    f2 = accumarray(elem2dof(:),ft2(:),[Nu 1]);\nend\nclear phi ft1 ft2\n\n%% Boundary Conditions\n[AD,BD,f,g,u,p,ufreeDof,pDof] = getbdStokesP2P1;\n\n%% Record assembeling 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(ufreeDof), return; end\nif isempty(option) || ~isfield(option,'solver')    % no option.solver\n    if length(f)+length(g) <= 1e3  % Direct solver for small size systems\n        option.solver = 'direct';\n    else          % Multigrid-type  solver for large size systems\n        option.solver = 'asmg';\n    end\nend\nsolver = option.solver;\n\n% solve\nswitch solver\n    case 'direct'\n        tic\n        bigA = [AD, B'; ...\n                B, sparse(Np,Np)];\n        bigF = [f; g];\n        bigu = [u; p];\n        bigFreeDof = [ufreeDof; 2*Nu+pDof];\n        bigu(bigFreeDof) = bigA(bigFreeDof,bigFreeDof)\\bigF(bigFreeDof);\n        u = bigu(1:2*Nu);\n        p = bigu(2*Nu+1:end);\n        residual = norm(bigF - bigA*bigu);\n        info = struct('solverTime',toc,'itStep',0,'err',residual,'flag',2,'stopErr',residual);        \n    case 'mg'\n%         option.tol = Np^(-2);        \n        option.solver  = 'WCYCLE';\n        [u(ufreeDof),p,info] = mgstokes(A(ufreeDof,ufreeDof),B(:,ufreeDof),f(ufreeDof),g,...\n                                        u(ufreeDof),p,elem,ufreeDof,option);         \n    case 'asmg'\n        [u(ufreeDof),p,info] = asmgstokes(A(ufreeDof,ufreeDof),B(:,ufreeDof),f(ufreeDof),g,...\n                                          u,p,node,elem,bdFlag,ufreeDof,option); \nend\n\n%% Post-process\nif length(pDof) ~= Np % p is unique up to a constant\n    % impose the condition int(p)=0\n    c = sum(mean(p(elem),2).*area)/sum(area);\n    p = p - c;\nend\n\n%% Output information\neqn = struct('A',AD,'B',BD,'f',f,'g',g,'ufreeDof',ufreeDof,'pDof',pDof);\ninfo.assembleTime = assembleTime;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbdStokesP2P1\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    function [AD,BD,f,g,u,p,ufreeDof,pDof] = getbdStokesP2P1\n    %% Boundary condition of Stokes equation: P2-P0 elements\n\n    %% Initial set up\n%     f = [f1; f2];    % set in Neumann boundary condition\n    g = zeros(Np,1);\n    u = zeros(2*Nu,1);    \n    p = zeros(Np,1);\n    ufreeDof = (1:Nu)';\n    pDof = (1:Np)';\n    \n    if ~exist('bdFlag','var'), bdFlag = []; end\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: Find Dirichlet dof and modify the matrix\n    % Find Dirichlet boundary dof: fixedDof and pDof\n    isFixedDof = false(Nu,1);     \n    if ~isempty(bdFlag)       % case: bdFlag is not empty \n        elem2edge = elem2dof(:,4:6)-N;\n        isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n        isFixedDof(edge(isDirichlet,:)) = true;   % nodes of all D-edges\n        isFixedDof(N + find(isDirichlet')) = true;% dof on D-edges\n        fixedDof = find(isFixedDof);\n        ufreeDof = 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        ufreeDof = find(~isFixedDof);    \n    end\n    if isempty(fixedDof) % pure Neumann boundary condition\n        % pde.g_N could be empty which is homogenous Neumann boundary condition\n        fixedDof = 1;\n        ufreeDof = (2:Nu)';    % eliminate the kernel by enforcing u(1) = 0;\n    end\n\n    % Modify the matrix\n    % Build Dirichlet boundary condition into the matrix AD by enforcing\n    % AD(fixedDof,fixedDof)=I, AD(fixedDof,ufreeDof)=0, AD(ufreeDof,fixedDof)=0.\n    % BD(:,fixedDof) = 0 and thus BD'(fixedDof,:) = 0.\n    bdidx = zeros(2*Nu,1); \n    bdidx([fixedDof; Nu+fixedDof]) = 1;\n    Tbd = spdiags(bdidx,0,2*Nu,2*Nu);\n    T = spdiags(1-bdidx,0,2*Nu,2*Nu);\n    AD = T*A*T + Tbd;\n    BD = B*T;\n\n    %% Part 2: Find boundary edges and modify the right hand side f and g\n    % Find boundary edges: Neumann and Robin\n    Neumann = []; Robin = []; %#ok<*NASGU>\n    if ~isempty(bdFlag)\n        isNeumann(elem2edge((bdFlag(:)==2)|(bdFlag(:) == 3))) = true;\n        isRobin(elem2edge(bdFlag(:)==3)) = true;\n        Neumannidx = find(isNeumann);        \n        Neumann   = edge(isNeumann,:);\n        Robin     = edge(isRobin,:);\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        Neumann = edge(bdDof>N,:);\n        if ~isempty(pde.g_R)\n            Robin = Neumann;\n        end\n    end\n\n    % Neumann boundary condition\n    if ~isempty(pde.g_N) && ~isempty(Neumann) && ~(isnumeric(pde.g_N) && (pde.g_N == 0))\n        [lambda,w] = quadpts1(3);\n        nQuad = size(lambda,1);\n        % quadratic bases (1---3---2)\n        bdphi(:,1) = (2*lambda(:,1)-1).*lambda(:,1);\n        bdphi(:,2) = (2*lambda(:,2)-1).*lambda(:,2);\n        bdphi(:,3) = 4*lambda(:,1).*lambda(:,2);\n        % length of edge\n        ve = node(Neumann(:,1),:) - node(Neumann(:,2),:);\n        edgeLength = sqrt(sum(ve.^2,2));\n        % update RHS\n        gex = zeros(size(Neumann,1),2);   % x-component\n        gey = zeros(size(Neumann,1),2);   % y-component\n        for pp = 1:nQuad\n            pxy = lambda(pp,1)*node(Neumann(:,1),:)+lambda(pp,2)*node(Neumann(:,2),:);\n            gp = pde.g_N(pxy);\n            gex(:,1) = gex(:,1) + w(pp)*edgeLength.*gp(:,1)*bdphi(pp,1);\n            gex(:,2) = gex(:,2) + w(pp)*edgeLength.*gp(:,1)*bdphi(pp,2);\n            gey(:,1) = gey(:,1) + w(pp)*edgeLength.*gp(:,2)*bdphi(pp,1);\n            gey(:,2) = gey(:,2) + w(pp)*edgeLength.*gp(:,2)*bdphi(pp,2);\n            f1(N+Neumannidx) = f1(N+Neumannidx) + w(pp)*edgeLength.*gp(:,1)*bdphi(pp,3); % interior bubble\n            f2(N+Neumannidx) = f2(N+Neumannidx) + w(pp)*edgeLength.*gp(:,2)*bdphi(pp,3); % interior bubble\n        end\n        f1(1:N) = f1(1:N) + accumarray(Neumann(:), gex(:),[N,1]);\n        f2(1:N) = f2(1:N) + accumarray(Neumann(:), gey(:),[N,1]);\n    end\n    f = [f1; f2];\n    % The case non-empty Neumann but g_N=[] corresponds to the zero flux\n    % boundary condition on Neumann edges and no modification is needed.\n\n    % Dirichlet boundary conditions\n    if ~isempty(fixedDof) && ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && (pde.g_D == 0))\n        u1 = zeros(Nu,1);\n        u2 = zeros(Nu,1);\n        idx = (fixedDof > N);              % index of edge dof\n        uD = pde.g_D(node(fixedDof(~idx),:));  % bd value at vertex dofs    \n        u1(fixedDof(~idx)) = uD(:,1);\n        u2(fixedDof(~idx)) = uD(:,2);\n        bdEdgeIdx = fixedDof(idx)-N;\n        bdEdgeMid = (node(edge(bdEdgeIdx,1),:)+node(edge(bdEdgeIdx,2),:))/2;\n        uD = pde.g_D(bdEdgeMid);         % bd values at middle points of edges\n        u1(fixedDof(idx)) = uD(:,1);\n        u2(fixedDof(idx)) = uD(:,2);\n        u = [u1; u2]; % Dirichlet bd condition is built into u\n        f = f - A*u;  % bring affect of nonhomgenous Dirichlet bd condition to\n        g = g - B*u;  % the right hand side\n        g = g - mean(g);         \n        f(fixedDof) = u1(fixedDof);\n        f(fixedDof+Nu) = u2(fixedDof);\n    end\n    % The case non-empty Dirichlet but g_D=[] corresponds to the zero Dirichlet\n    % boundary condition and no modification is needed.\n    \n    % modfiy pressure dof for pure Dirichlet\n    if isempty(Neumann)\n        pDof = (1:Np-1)';\n    end\n    \n    ufreeDof = [ufreeDof; Nu+ufreeDof];    \n    end % end of function getbdStokesP2P1\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nend\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/equation/StokesP2P1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5549236184565421}}
{"text": "function pred = ml_predicthdca(trials, model)\n% Prediction function for Hierarchical Discriminant Component Analysis\n% Prediction = ml_predicthdca(Trials, Model)\n%\n% In:\n%   Trials  : the data a matrix, as in ml_predict\n%\n%   Model   : predictive model as produced by ml_trainhdca\n%\n% Out:\n%   Prediction  : discrete probability distribution, formatted as\n%                 {'disc' [NxC] [Cx1]}, with element #2 being the per-class probability and \n%                 element #3 the original target values per class\n%                 thus, the expected target values are Prediction{2}*Prediction{3}\n%\n% Examples:\n%   targets might look like this: [-1 -1 1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1 ...]' \n%\n%   model = ml_trainhdca(data,targets)\n%   p = ml_predicthdca(data, model); expectation = p{2}*p{3};\n%   now expectation might look like this: [-0.6 -0.9 +0.4 -0.7 +0.8 -0.1 +0.5 +1.0 -0.9 +1.0 -1.0 -1.0 +1.0 ...]'\n%\n% See also:\n%   ml_trainhdca\n%\n%                           Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n%                           2010-04-03\n\n\nif isfield(model,'voted')\n    % dispatch to the voter for multi-class classification\n    pred = ml_predictvote(trials,model);\nelse\n    % for each modality range...\n    for m=1:length(model.modality_ranges)\n        range = model.modality_ranges{m};\n        \n        % for each sub-block...\n        for b=size(trials,2):-1:1\n            % extract per-block features\n            blocktrials = reshape(trials(range,b,:),[],size(trials,3))';\n            blockpredictions{b} = blocktrials*model.blockmodels{m}{b}.w' - model.blockmodels{m}{b}.b';\n        end\n        % extract per-modality features\n        layertrials = cat(2,blockpredictions{:});\n        rangepredictions{m} = layertrials*model.rangemodels{m}.w' - model.rangemodels{m}.b'; %#ok<AGROW>\n    end\n    % perform top-level prediction\n    toptrials = cat(2,rangepredictions{:});\n    pred = ml_predictlda(toptrials,model.topmodel);\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_predicthdca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5549236044763409}}
{"text": "% load textbook.mat\nS=[-1  0  1 1 0;\n    1 -1  0 0 0;\n    0  1 -1 0 -1];\n\nmodel.S=S;\nmodel.lb=[0 0 -10 5 5]';\nmodel.ub=[5 5 0 0 0]';\nmodel.c=zeros(5,1);\nmodel.c(5,1)=1;\n\nv = checkThermodynamicConsistency(model);\n\ndisp(norm(v))\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/thermo/thermoFBA/testCheckThermodynamicConsistency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5549236037661034}}
{"text": "function X = mrdivide(A, B)\n%/   Right matrix divide for a BNDFUN.\n%   A/B divides the BNDFUN A by a scalar B. More generally, it gives the\n%   least-squares solution (with respect to the continuous L^2 norm) to X*B = A\n%   when either A or B is a BNDFUN.  Note that in the latter case, formally it\n%   is X.' that is returned, as BNDFUN objects are always columns.\n%\n% See also QR, RDIVIDE, 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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Case B is a matrix: X*B = A  ==> X = A/B = (Q*R)/B = Q*(R/B)\n%\n% Case A is a matrix: X*B = X*(Q*R) = A ==> X = (A/R)*Q' ==> X' = Q*(A/R)'\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ( (size(B, 2) ~= size(A, 2)) && ~(isa(B, 'double') && isscalar(B)) )\n    error('CHEBFUN:BNDFUN:mrdivide:size', 'Matrix dimensions must agree.');\n    \nelseif ( isa(B, 'double') )  % BNDFUN / double\n    \n    if ( isscalar(B) )\n        % Scalar case is easy:\n        X = A;                              % Copy A to X\n        X.onefun = X.onefun/B;              % mrdivide of the onefun\n    else\n        % Call MRDIVIDE at the ONEFUN level:\n        X = A;\n        X.onefun = (A.onefun/B);\n        \n%         % Alternatively, we could call QR() at the BNDFUN level\n%         % For matrix case, we do least squares via QR:\n%         [Q, R] = qr(A, 0);\n%         X = Q*(R/B);\n    end\n    \nelseif ( isa(A, 'double') )  % double / BNDFUN\n    \n    % Call MRDIVIDE at the ONEFUN level:\n    X = B;\n    X.onefun = (A/B.onefun);\n    X = X/(.5*diff(B.domain));\n    \n%     % Alternatively we could call QR() at the BNDFUN level:\n%     % Do least squares via QR:\n%     [Q, R] = qr(B, 0);\n%     % Return the transpose for the output.\n%     X = Q*(A/R).';\n    \nelseif ( isa(B, 'bndfun') && isa(A, 'bndfun') )\n    error('CHEBFUN:BNDFUN:mrdivide:bndfunDivBndfun', ...\n        'Use ./ to divide BNDFUN by a BNDFUN.');\n    \nelse\n    error('CHEBFUN:BNDFUN:mrdivide:badArg', '%s/%s is not well-defined.', ...\n        class(A), class(B));\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/@bndfun/mrdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5549236020279347}}
{"text": "%%\n% Perform softmax prediction.\n%\n% Thang Luong @ 2015, <lmthang@stanford.edu>\n%\n%%\nfunction [cost, probs, scores, scoreIndices] = softmaxLayerForward(W, inVec, predLabels, curMask)\n  mask = curMask.mask;\n  unmaskedIds = curMask.unmaskedIds;\n  \n  % softmax_h -> predictions\n  [probs, scores, norms] = softmax(W*inVec, mask);\n  \n  % cost\n  predLabels = predLabels(unmaskedIds);\n  scoreIndices = sub2ind(size(scores), predLabels, unmaskedIds); % 1 * length(tgtPredictedWords)\n  cost = - sum(scores(scoreIndices)) + sum(log(norms).*mask);\nend", "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/layers/softmaxLayerForward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5549235971311217}}
{"text": "function out = Rstar(d, n, e, fun)\n%finds rate that achieves a given excess distortion at a given blocklength for\n%Gaussian source with unit variance\n%d - excess distortion\n%n - block length (scalar)\n%e - excess probability\n%fun - which function to use for calculation\n\n%\n%   Created in 2012 by Victoria Kostina (vkostina@caltech.edu)\n%\n\n%starting points - 'persistent' to make optimization faster\npersistent x0;\n%rate distortion\nRd = -1/2*log2(d);\n%precision options\ntol = 1e-10;\noptions = optimset('TolX',tol, 'MaxFunEvals', 500, 'Algorithm', 'active-set', 'Display', 'off');\n\nswitch lower(fun)\n    case {'shannon', 'spherecoveringa', 'generalc', 'generalcopt'}\n        if isempty(x0)\n            x0 = [Rd 3*Rd]; %rate\n        end\n        out = Generic();\n    case 'normal'\n        %normal approximation:\n        out = Normal();\n    case 'spherecoveringc'\n        %converse via sphere covering\n        out = SphereCoveringC();\n    case 'rogersa'\n        out = RogersA();\n    otherwise\n        disp('Unknown type.')\nend\n\n\n%--------------------------------------------------------------------------\n    function out = Generic()\n        out = fzero(@(x)goal(x) - e, x0, options);\n        function out = goal(x)\n            out = Pexcess(x, d, n, fun);\n        end\n    end\n\n%--------------------------------------------------------------------------\n    function out = Normal()\n        %Normal approximation\n        out = - .5*log2(d) + 1/sqrt(2*n)*Qinv(e)*log2(exp(1));\n    end\n\n%--------------------------------------------------------------------------\n    function out = SphereCoveringC()\n        %converse via sphere covering\n        \n        %find rstar:\n        factor = 3;\n        rstar = fzero(@(x)chi2cdf(x^2*n, n) - chi2cdf(factor*n, n) + e, 1);\n        out = rate(d);\n        \n        function out = rate(x)\n            out = 1/2*log2(rstar^2/x);\n        end\n    end\n\n%--------------------------------------------------------------------------\n    function out = RogersA()\n        rstar = fzero(@(x)1 - chi2cdf(x^2*n, n) - e, 1);\n        out = rogers(rstar/sqrt(d));\n        function out = rogers(r)\n            if r >= n\n                out = log2(exp(1))+ log2((n*log(n)+n*log(log(n)) + 5*n)) + n*log2(r);\n            elseif r >= n/log(n)\n                out = log2(n*(n*log(n)+n*log(log(n)) + 5*n)) + n*log2(r);\n            elseif r >2\n                out = log2(7^(4*log(7)/7)/4*sqrt(2*pi)) + log2(n^(3/2)*((n-1)*log(r*n)+(n-1)*log(log(n)+log(n)/2+log((pi*sqrt(2*n))/(sqrt(pi*n)-2))))) - log2(r*(1-2/log(n))*(1 - 2/sqrt(pi*n))*(log(n))^2) + n*log2(r);\n            else\n                out = log2(sqrt(2*pi)) + log2(sqrt(n)*((n-1)*log(r*n)+(n-1)*log(log(n)+log(n)/2+log((pi*sqrt(2*n))/(sqrt(pi*n)-2))))) - log2(r*(1-2/log(n))*(1 - 2/sqrt(pi*n))) + n*log2(r);\n            end\n            out = out/n;\n        end\n    end\n\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/sc/GMS/Rstar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5549235953929521}}
{"text": "% Test file for @classicfun/max.m\n\nfunction pass = test_max(pref)\n\n% Get preferences.\nif ( nargin < 1 )\n    pref = chebfunpref();\nend\n\n% Set a domain for BNDFUN.\ndata.domain = [-2 7];\n    \n%% \n% Spot-check the extrema for a few BNDFUN.\npass(1) = test_spotcheck_max(@(x) sin(10*x), data, 1, pref);\npass(2) = test_spotcheck_max(@airy, data, 0.535656656015700, pref);\npass(3) = test_spotcheck_max(@(x) -1./(1 + x.^2), data, -.02, pref);\npass(4) = test_spotcheck_max(@(x) (x/10).^3.*cosh(x/10), ...\n    data, 0.7^3*cosh(0.7), pref);\n\n%%\n% Check operation for array-valued BNDFUN inputs.\nfun_op = @(x) [sin(10*x) airy(x) (x/10).^3.*cosh(x/10)];\nf = bndfun(fun_op, data, pref);\n[y, x] = max(f);\nexact_max = [1 0.535656656015700 0.7^3*cosh(0.7)];\nfx = [sin(10*x(1)) airy(x(2)) (x(3)/10).^3.*cosh(x(3)/10)];\ntol = 10*get(f, 'vscale')*eps;\npass(5) = (all(abs(y - exact_max) < 10*tol) && ...\n    all(abs(fx - exact_max) < tol));\n    \n\n%%\n% Test for complex-valued BNDFUN.\npass(6) = test_spotcheck_max(@(x) (x/2).*(exp(1i*(x/2))+1i*sin(x/2)), ...\n    data, -3.277598405517787 - 2.455482593827339i, pref);\n\nfun_op = @(x) [((x-2).^2/4+1).*exp(1i*(x/2)) ... \n    -((x+1).^2/4+1).*exp(1i*(x/2))];\nf = bndfun(fun_op, data, pref);\n[y, x] = max(f);\nexact_max = [-6.789310982858273-2.543178400749744i 15.919763683943538+5.963314870723537i];\nfx = [((x(1)-2).^2/4+1).*exp(1i*(x(1)/2)) ... \n    -((x(2)+1).^2/4+1).*exp(1i*(x(2)/2))];\ntol = get(f, 'vscale')*eps;\npass(7) = (all(abs(y - exact_max) < 10*tol) && ...\n    all(abs(fx - exact_max) < tol));\n    \n      \n%% Test for UNBNDFUN:\n\n% Functions on [a inf]:\n\n% Set the domain:\ndata.domain = [1 Inf];\n\nop = @(x) x.*exp(-x);\nf = unbndfun(op, data);\n[y, x] = max(f);\nyExact = exp(-1);\nxExact = 1;\nerrY = y - yExact;\nerrX = x - xExact;\npass(8) = norm([errY errX], inf) < 1e3*eps*get(f,'vscale');\n    \n\nend\n\n%%\n% Spot-check the results for a given BNDFUN.\nfunction result = test_spotcheck_max(fun_op, data, exact_max, pref)\n\nf = bndfun(fun_op, data, pref);\n[y, x] = max(f);\nfx = fun_op(x);\ntol = 100*get(f, 'vscale')*eps;\n    \nresult = (all(abs(y - exact_max) < tol) && ...\n          all(abs(fx - exact_max) < tol));\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/classicfun/test_max.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5549226656846564}}
{"text": "function gX = rbfperiodic2KernDiagGradX(kern, X)\n\n% RBFPERIODIC2KERNDIAGGRADX Gradient of RBFPERIODIC2 kernel's diagonal with respect to X.\n% FORMAT\n% DESC computes the gradient of the diagonal of the RBF periodic covariance with variying period kernel matrix with\n% respect to the elements of the design matrix given in X.\n% ARG kern : the kernel structure for which gradients are being computed.\n% ARG X : the input data in the form of a design matrix.\n% RETURN gX : the gradients of the diagonal with respect to each element\n% of X. The returned matrix has the same dimensions as X.\n%\n% SEEALSO : rbfperiodic2KernParamInit, kernDiagGradX, rbfperiodic2kernGradX\n%\n% COPYRIGHT : Neil D. Lawrence, 2007, 2009\n%\n% MODIFICATIONS : Andreas C. Damianou, 2011\n%\n% MODIFICATIONS : Michalis K. Titsias, 2011\n\n% KERN\n\n\ngX = zeros(size(X));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/rbfperiodic2KernDiagGradX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5548418921556421}}
{"text": "%% GEOMETRIC COLLISION AVOIDANCE AGENT (agent_2D_vectorSharing.m) %%%%%%%%%\n% This programs contains a generic agent object with the 2017 3D geometric\n% avoidance alogorithm applied to conduct course corrections.\n\n% Author: James A. Douthwaite\n\nclassdef agent_2D_vectorSharing < agent_2D & agent_vectorSharing\n    %% ////////////////////// MAIN CLASS METHODS //////////////////////////\n    methods \n        % Constructor\n        function [this] = agent_2D_vectorSharing(varargin)\n\n            % Call the super class\n            this@agent_2D(varargin);    \n\n            % //////////////////// SENSOR PARAMETERS //////////////////////\n            [this.SENSORS] = this.GetDefaultSensorParameters();     % Default sensing\n%             [this.SENSORS] = this.GetCustomSensorParameters();       % Experimental sensing\n            % /////////////////////////////////////////////////////////////\n\n            % //////////////// Check for user overrides ///////////////////\n            this = this.ApplyUserOverrides(varargin); % Recursive overrides\n            % /////////////////////////////////////////////////////////////\n        end\n        % Setup - X = [x y psi dx dy dpsi]\n        function [this] = setup(this,localXYZVelocity,localXYZrotations)\n            % This function calculates the intial state for a generic\n            % object.\n            % The default state vector:\n            % [x y psi dx dy dpsi]\n            % INITIALISE THE 2D STATE VECTOR WITH CONCANTINATED VELOCITIES\n            [this] = this.setup_2DVelocities(localXYZVelocity,localXYZrotations);\n        end\n        % Main\n        function [this] = main(this,ENV,varargin)\n            % This function is designed to house a generic agent process\n            % cycle that results in an acceleration vector in the global axis.\n            % INPUTS:\n            % varargin - Cell array of inputs\n            % >dt      - The timestep\n            % >objects - The detectable objects cell array of structures\n            % OUTPUTS:\n            % obj      - The updated project\n            \n            % INPUT HANDLING\n            dt = ENV.dt;\n\n            % PLOT AGENT FIGURE\n            visualiseProblem = 0;\n            visualiseAgent = 1;\n            if this.objectID == visualiseAgent && visualiseProblem == 1\n                overHandle = figure(100+this.objectID);\n                hold on; grid on;\n                axis equal;\n                xlabel('x_{m}'); ylabel('y_{m}'); zlabel('z_{m}');\n            end \n                        \n            % //////////// CHECK FOR NEW INFORMATION UPDATE ///////////////\n            [this,obstacleSet,agentSet] = this.GetAgentUpdate(ENV,varargin{1});       % IDEAL INFORMATION UPDATE\n            % /////////////////////////////////////////////////////////////\n            \n            % /////////////////// WAYPOINT TRACKING ///////////////////////\n            % Design the current desired trajectory from the waypoint.\n            desiredHeadingVector = this.GetTargetHeading();\n            desiredVelocity = desiredHeadingVector*this.v_nominal;\n\n            % ////////////////// OBSTACLE AVOIDANCE ///////////////////////\n            % Modify the desired velocity with the augmented avoidance velocity.\n            avoidanceSet = [obstacleSet,agentSet];\n            algorithm_start = tic; algorithm_indicator = 0;  \n            if ~isempty(avoidanceSet) \n                algorithm_indicator = 1;\n                % GET THE UPDATED DESIRED VELOCITY\n                 [desiredHeadingVector,desiredSpeed] = this.GetAvoidanceCorrection(desiredVelocity,visualiseProblem);\n                 desiredVelocity = desiredHeadingVector*desiredSpeed;\n            end\n            algorithm_dt = toc(algorithm_start);                           % Stop timing the algorithm\n            \n            desiredVelocity\n            \n            % ///////////////////// CONTROLLER ////////////////////////////\n            this = this.Controller(dt,desiredVelocity);\n            \n            % ////////////// RECORD THE AGENT-SIDE DATA ///////////////////\n            this = this.writeAgentData(ENV,algorithm_indicator,algorithm_dt);      % Record when the algorithm is ran\n            this.DATA.inputNames = {'$v_x$ (m/s)','$v_y$ (m/s)','$\\dot{\\psi}$ (rad/s)'};\n            this.DATA.inputs(1:length(this.DATA.inputNames),ENV.currentStep) = this.localState(4:6);         % Record the control inputs\n            \n            % // DISPLAY CONFLICT RESOLUTION\n            if this.objectID == visualiseAgent && visualiseProblem == 1\n                this = this.GetAnimationFrame(overHandle,ENV,'resolutionZone.gif');\n                close(overHandle);\n            end\n        end\n    end\n    %% /////////////////////// AUXILLARY METHODS //////////////////////////\n    methods (Access = public)\n        % GET THE AVOIDANCE CORRECTION\n        function [heading,speed] = GetAvoidanceCorrection(this,desiredVelocity,visualiseProblem)\n            % This function calculates the collision avoidance velocity in\n            % light of the current obstacles\n            \n            % Check we aren't stopping\n            [heading,speed] = this.nullVelocityCheck(desiredVelocity);\n            if speed == 0\n                return \n            end\n            \n            % AGENT KNOWLEDGE\n            [p_i,v_i,r_i] = this.GetAgentMeasurements(); % Its own position, velocity and radius\n            \n            % Define the obstacle list\n            obstacleIDs = [this.MEMORY([this.MEMORY.type] ~= OMAS_objectType.waypoint).objectID];\n                        \n            % MOVE THROUGH THE PRIORITISED OBSTACLE SET\n            optimalSet = [];\n            for j = 1:numel(obstacleIDs)\n                % Fetch the obstacle trajectories\n                p_j = this.GetLastMeasurementByID(obstacleIDs(j),'position');\n                % Neighbour conditions\n                neighbourConditionA = j < this.maxNeighbours;            % Maximum number of neighbours\n                neighbourConditionB = norm(p_j) < this.neighbourDist;       % [CONFIRMED]\n                if ~neighbourConditionA || ~neighbourConditionB\n                    continue\n                end\n                \n                % Get further obstacle information\n                v_j = this.GetLastMeasurementByID(obstacleIDs(j),'velocity');\n                r_j = this.GetLastMeasurementByID(obstacleIDs(j),'radius');\n                \n                % OBSTACLE KNOWLEDGE\n                p_j = p_j + p_i;\n                v_j = v_j + v_i;                                           % Convert relative parameters to absolute\n\n                % COMPUTE THE VECTOR SHARING PROBLEM\n                [Voptimal] = this.Define2DVectorSharingVelocity(...\n                    desiredVelocity,...\n                    p_i,v_i,r_i,...\n                    p_j,v_j,r_j,...\n                    visualiseProblem);\n                optimalSet = horzcat(optimalSet,[Voptimal;abs(norm(desiredVelocity - Voptimal))]);\n            end\n            \n            % INTERPRETING THE AVOIDANCE VELOCITY SET\n            if ~isempty(optimalSet)\n                inputDim = 2;\n                % THE CLOSEST OBSTACLE\n                %                 avoidanceVelocity = optimalSet(1:inputDim,1);\n                % FIND THE MINIMUM MAGNITUDE DEVIATION FROM THE DESIRED\n                [~,minIndex] = min(optimalSet((inputDim+1),:),[],2);       % Return the index of the smallest vector\n                avoidanceVelocity = optimalSet(1:inputDim,minIndex);\n            else\n                % NOTHING TO AVOID, CHOOSE OPTIMAL VELOCITY\n                avoidanceVelocity = desiredVelocity;\n            end\n            \n            % CHECK VELOCITY IS PERMISSIBLE\n            if any(isnan(avoidanceVelocity))\n%                 heading = [1;0];   \n%                 speed = 0;\n                speed   = norm(desiredVelocity);\n                heading = desiredVelocity/speed;    % Retain forward direction\n            else\n                [heading,speed] = this.nullVelocityCheck(avoidanceVelocity);\n            end\n        end\n        % DEFINE THE VECTOR SHARING AVOIDANCE PROBLEM\n        function [U_a] = Define2DVectorSharingVelocity(obj,desiredVelocity,p_a,v_a,r_a,p_b,v_b,r_b,visualiseProblem)\n            % This function calculates the avoidance vectors based on the\n            % principle of vector sharing.\n            % INPUTS:\n            % desiredVelocity - The true optimal vector\n            % p_a - The agent's absolute position\n            % v_a - The agent's absolute velocity\n            % r_a - The agent's radius\n            % p_b - The obstacle's absolute position\n            % v_b - The obstacle's absolute velocity\n            % r_b - The obstacle's radius\n            % visualiseProblem - Plot flag\n            % OUTPUTS:\n            % U_a - The optimal vector heading, scaled by the desired\n            %       velocity.\n                        \n            % Generate the 3D inputs \n            p_a = [p_a;0]; v_a = [v_a;0];\n            p_b = [p_b;0]; v_b = [v_b;0];\n            % Pass to the 3D function\n            [U_a] = obj.Define3DVectorSharingVelocity(...\n                desiredVelocity,...\n                p_a,v_a,r_a,...\n                p_b,v_b,r_b,...\n                visualiseProblem);\n            % Reform the inputs for 2D application\n            U_a = U_a(1:2,1);\n        end\n    end\n    % The function uses the same sensor characteristics from the parent\n    % class \"agent_vectorSharing.m\".\nend\n% AGENT STATE VECTOR [x;y;phi;xdot;ydot;phidot]", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/objects/agent_2D_vectorSharing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042765, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5548418869068156}}
{"text": "function [yCouch, lines] =  getCouchLocationHough(scan3M,minLengthOpt,retryOpt)\n\n% Function: getCouchLocationHough\n% Description: Returns anterior coordinate of patient couch surface\n%\n% Usage\n% inputStack is a 3-dim array of CT scan image with array axes [Y,X,Z]. [Note: \"Image\" notation permutes Y <-> X]\n% yCouch, the Y-coordinate of the scanning table/couch\n%\n% EML 2020-04-13\n%\n\nif ~exist('minLengthOpt','var')\n    minLengthOpt = [];\nend\n\nif ~exist('retryOpt','var')\n    retryOpt = 0;\nend\n\nmidptS = floor(size(scan3M,1)/2);\n\nmaxM = max(scan3M, [], 3);\nhisteqM = histeq(maxM);\nedgeM1 = edge(histeqM,'sobel',[],'horizontal');\nedgeM2 = bwmorph(edgeM1,'thicken');\n    \n[H,T,R] = hough(edgeM2);\nP = houghpeaks(H,20);\n\nif isempty(minLengthOpt)\n    minLength = floor(size(edgeM2,2)/8); % couch covers 1/8th of image\nelse\n    minLength = minLengthOpt;\nend\n\n% lines = houghlines(edgeM2,T,R,P,'FillGap',5,'MinLength',minLength);\nlines = houghlines(edgeM2,T,R,P);\noverlapFraction = zeros(1,numel(lines));\nmidV = [floor(0.5*midptS):floor(0.5*midptS) + midptS];\n% Require couch lines to have same starting & ending point2\nyi = zeros(1,numel(lines)); \n% figure; imagesc(maxM); axis equal; hold on\nfor i = 1:numel(lines)\n    len = norm(lines(i).point1 - lines(i).point2);\n    if lines(i).point1(2) == lines(i).point2(2) && len > minLength\n%         xy = [lines(i).point1; lines(i).point2];\n%         plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');\n%         % Plot beginnings and ends of lines\n%         plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');\n%         plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');\n        lineV = [lines(i).point1(1):lines(i).point2(1)];\n        if lines(i).point1(2) > midptS && ~isempty(intersect(lineV,midV))\n            yi(i) = lines(i).point2(2); \n            overlapFraction(i) = numel(intersect(lineV,midV));\n        end\n    end\nend\n\nif any(overlapFraction)\n    [~,I] = max(overlapFraction);\n    yCouch = yi(I);\nelse\n    yCouch = min(yi(find(yi > 0)));\nend\n\nif retryOpt && isempty(yCouch)\n    [yCouch, lines] =  getCouchLocationHough(scan3M,minLength/2);\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Contouring/getCouchLocationHough.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5548418859669484}}
{"text": "function dz = dynamics(z,u,param)\n% dz = dynamics(z,u,param)\n%\n% Computes the first-order form of the dynamics for the combined chain\n% integrator and pendulum system\n%\n% INPUTS:\n%   z = [x;v1;v2;a2;j2];\n%   u = [u1;u2];\n%\n% OUTPUTS:\n%   dz = dz/dt\n%\n\nx = z(1,:);\nv1 = z(2,:);\n% v2 = z(3,:);   %Unused\na2 = z(4,:);   \nj2 = z(5,:);   \nu1 = u(1,:);\nu2 = u(2,:);\n\n% Pendulum physics\ndv1 = pendulum(x,v1,u1,param);\n\n% Integrator chain physics:\ndx = v1;\ndv2 = a2;\nda2 = j2;\ndj2 = u2;\n\n% Combine:\ndz = [dx;dv1;dv2;da2;dj2];\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/minimumSnap/minSnap/dynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5548418850270809}}
{"text": "%QUATERNION\tconstructor for quaternion objects\n%\t\n% \tQUATERNION([s v1 v2 v3])\tfrom 4 elements\n% \tQUATERNION(v, theta)\t\tfrom vector plus angle\n% \tQUATERNION(R)\t\t\tfrom a 3x3 or 4x4 matrix\n% \tQUATERNION(q)\t\t\tfrom another quaternion\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\nfunction q = Quaternion(a1, a2)\n\n\n\tif nargin == 0,\n\t\tq.s = 1;\n\t\tq.v = [0 0 0];\n\t\tq = class (q, 'Quaternion');\n\t\n\telseif nargin == 1\n\t\tif isa(a1, 'Quaternion')\n\t\t\tq = a1;\n\t\t\tq = class(q, 'Quaternion');\n\t\telseif isreal (a1) && size(a1) == 1      \n\t\t\tq.s = a1(1);\n\t\t\tq.v = [0,0,0];\n\t\t\tq = class(q, 'Quaternion');\n\t\telseif isreal (a1) && all (size (a1) == [1 3]) # Quaternion (vector part)\n\t\t\tq.s = 0;\n\t\t\tq.v = a1(1:3);\n\t\t\tq = class(q, 'Quaternion');\n\t\telseif all(size(a1) == [3 3])\n\t\t\tq = Quaternion( tr2q(a1) );\n\t\telseif all(size(a1) == [4 4])\n\t\t\tq = Quaternion( tr2q(a1(1:3,1:3)) );\n\t\telseif all(size(a1) == [1 4])\n\t\t\tq.s = a1(1);\n\t\t\tq.v = a1(2:4);\n\t\t\tq = class(q, 'Quaternion');\n\t\telse\n\t\t\terror('unknown dimension of input');\n\t\tend\n\telseif nargin == 2\n\t\tif  isscalar(a1) && isvector(a2) \n\t\t\tq.s = cos(a1/2);\n\t\t\tq.v = (sin(a1/2)*unit(a2(:)'));\n\t\t\tq = class(q, 'Quaternion');\n\t\tend\n\tend\nendfunction\n%TR2Q\tConvert homogeneous transform to a unit-quaternion\n%\n%\tQ = tr2q(T)\n%\n%\tReturn a unit quaternion corresponding to the rotational part of the\n%\thomogeneous transform T.\n%\n%\tSee also Q2TR\n\n\n% Ryan Steidnl based on Robotics Toolbox for MATLAB (v6 and v9)\n%\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\nfunction q = tr2q(t)\n\tqs = sqrt(trace(t)+1)/2.0;\n\tkx = t(3,2) - t(2,3);\t% Oz - Ay\n\tky = t(1,3) - t(3,1);\t% Ax - Nz\n\tkz = t(2,1) - t(1,2);\t% Ny - Ox\n\n\tif (t(1,1) >= t(2,2)) & (t(1,1) >= t(3,3)) \n\t\tkx1 = t(1,1) - t(2,2) - t(3,3) + 1;\t% Nx - Oy - Az + 1\n\t\tky1 = t(2,1) + t(1,2);\t\t\t% Ny + Ox\n\t\tkz1 = t(3,1) + t(1,3);\t\t\t% Nz + Ax\n\t\tadd = (kx >= 0);\n\telseif (t(2,2) >= t(3,3))\n\t\tkx1 = t(2,1) + t(1,2);\t\t\t% Ny + Ox\n\t\tky1 = t(2,2) - t(1,1) - t(3,3) + 1;\t% Oy - Nx - Az + 1\n\t\tkz1 = t(3,2) + t(2,3);\t\t\t% Oz + Ay\n\t\tadd = (ky >= 0);\n\telse\n\t\tkx1 = t(3,1) + t(1,3);\t\t\t% Nz + Ax\n\t\tky1 = t(3,2) + t(2,3);\t\t\t% Oz + Ay\n\t\tkz1 = t(3,3) - t(1,1) - t(2,2) + 1;\t% Az - Nx - Oy + 1\n\t\tadd = (kz >= 0);\n\tend\n\n\tif add\n\t\tkx = kx + kx1;\n\t\tky = ky + ky1;\n\t\tkz = kz + kz1;\n\telse\n\t\tkx = kx - kx1;\n\t\tky = ky - ky1;\n\t\tkz = kz - kz1;\n\tend\n\tnm = norm([kx ky kz]);\n\tif nm == 0,\n\t\tq = Quaternion([1 0 0 0]);\n\telse\n\t\ts = sqrt(1 - qs^2) / nm;\n\t\tqv = s*[kx ky kz];\n\n\t\tq = Quaternion([qs qv]);\n\n\tend\nendfunction \n\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/@Quaternion/Quaternion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5548418807181221}}
{"text": "function [ahm,AHM_f,AHM_ahmf] = fromFrameAhm(F,ahmf)\n\n% FROMFRAMEAHM  Transforms AHM from local frame to global frame.\n%   AHM = FROMFRAMEAHM(F,AHMF) transforms the Inverse Depth point IF from the\n%   local frame F to the global frame. The frame F can be specified either\n%   with a 7-vector F=[T;Q], where T is the translation vector and Q the\n%   orientation quaternion, of via a structure containing at least the\n%   fields F.t, F.q, F.R and F.Rt (translation, quaternion, rotation matrix\n%   and its transpose).\n%\n%   [AHM,AHM_f,AHM_if] = FROMFRAMEAHM(...) returns the Jacobians wrt F and AHMF.\n\n%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n\nxf  = ahmf(1:3,:);\nmf  = ahmf(4:6,:);\nsf  = ahmf(7,:);\n\n[t,q,R] = splitFrame(F);\n\nif nargout == 1\n\n    x  = fromFrame(F,xf);\n    m  = R*mf;\n\n    ahm  = [x;m;sf];\n\nelse\n\n    if size(ahmf,2) > 1\n        error('Jacobians not available for multiple ahms')\n    else\n\n        [x, X_f, X_xf] = fromFrame(F,xf);\n        [m,M_q,M_mf]   = Rp(q,mf);\n\n        ahm    = [x;m;sf];\n\n        AHM_f = [...\n            X_f\n            zeros(3,3) M_q\n            zeros(1,7)];\n\n        AHM_ahmf = [...\n            X_xf          zeros(3,4)\n            zeros(3,3) M_mf zeros(3,1)\n            zeros(1,6)           1];\n\n    end\nend\n\nreturn\n\n%% jac\n\nsyms x y z a b c d X Y Z U V W R real\nF   = [x;y;z;a;b;c;d];\nahmf = [X;Y;Z;U;V;W;R];\n\n[ahm,AHM_f,AHM_ahmf] = fromFrameAhm(F,ahmf);\n\nsimplify(AHM_f  - jacobian(ahm,F))\nsimplify(AHM_ahmf - jacobian(ahm,ahmf))\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 <http://www.gnu.org/licenses/>.\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/fromFrameAhm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5548418754692958}}
{"text": "function [cout,hout] = tricontour(p,t,Hn,N)\n% Contouring for functions defined on triangular meshes\n%\n%   TRICONTOUR(p,t,F,N)\n%\n% Draws contours of the surface F, where F is defined on the triangulation\n% [p,t]. These inputs define the xy co-ordinates of the points and their\n% connectivity:\n%\n%   P = [x1,y1; x2,y2; etc],            - xy co-ordinates of nodes in the \n%                                         triangulation\n%   T = [n11,n12,n13; n21,n23,n23; etc] - node numbers in each triangle\n%\n% The last input N defines the contouring levels. There are several\n% options:\n%\n%   N scalar - N number of equally spaced contours will be drawn\n%   N vector - Draws contours at the levels specified in N\n%\n% A special call with a two element N where both elements are equal draws a\n% single contour at that level.\n%\n%   [C,H] = TRICONTOUR(...)\n%\n% This syntax can be used to pass the contour matrix C and the contour\n% handels H to clabel by adding clabel(c,h) or clabel(c) after the call to\n% TRICONTOUR.\n%\n% TRICONTOUR can also return 3D contours similar to CONTOUR3 by adding\n% view(3) after the call to TRICONTOUR.\n%\n% Type \"contourdemo\" for some examples.\n%\n% See also, CONTOUR, CLABEL\n% This function does NOT interpolate back onto a Cartesian grid, but\n% instead uses the triangulation directly.\n%\n% If your going to use this inside a loop with the same [p,t] a good\n% modification is to make the connectivity \"mkcon\" once outside the loop\n% because usually about 50% of the time is spent in \"mkcon\".\n%\n% Darren Engwirda - 2005 (d_engwirda@hotmail.com)\n% Updated 15/05/2006\n% I/O checking\nif nargin~=4\n    error('Incorrect number of inputs')\nend\nif nargout>2\n    error('Incorrect number of outputs')\nend\n% Error checking\nif (size(p,2)~=2) || (size(t,2)~=3) || (size(Hn,2)~=1)\n    error('Incorrect input dimensions')\nend\nif size(p,1)~=size(Hn,1)\n    error('F and p must be the same length')\nend\nif (max(t(:))>size(p,1)) || (min(t(:))<=0)\n    error('t is not a valid triangulation of p')\nend\nif (size(N,1)>1) && (size(N,2)>1)\n    error('N cannot be a matrix')\nend\n% Make mesh connectivity data structures (edge based pointers)\n[e,eINt,e2t] = mkcon(p,t);\nnumt = size(t,1);       % Num triangles\nnume = size(e,1);       % Num edges\n%==========================================================================\n%                Quadratic interpolation to centroids\n%==========================================================================\n% Nodes\nt1 = t(:,1); t2 = t(:,2); t3 = t(:,3);\n% FORM FEM GRADIENTS\n% Evaluate centroidal gradients (piecewise-linear interpolants)\nx23 = p(t2,1)-p(t3,1);  y23 = p(t2,2)-p(t3,2);\nx21 = p(t2,1)-p(t1,1);  y21 = p(t2,2)-p(t1,2);\n% Centroidal values\nHtx = (y23.*Hn(t1) + (y21-y23).*Hn(t2) - y21.*Hn(t3)) ./ (x23.*y21-x21.*y23);\nHty = (x23.*Hn(t1) + (x21-x23).*Hn(t2) - x21.*Hn(t3)) ./ (y23.*x21-y21.*x23);\n% Form nodal gradients.\n% Take the average of the neighbouring centroidal values\nHnx = 0*Hn; Hny = Hnx; count = Hnx;\nfor k = 1:numt\n    % Nodes\n    n1 = t1(k); n2 = t2(k); n3 = t3(k);\n    % Current values\n    Hx = Htx(k); Hy = Hty(k);\n    % Average to n1\n    Hnx(n1)   = Hnx(n1)+Hx;\n    Hny(n1)   = Hny(n1)+Hy;\n    count(n1) = count(n1)+1;\n    % Average to n2\n    Hnx(n2)   = Hnx(n2)+Hx;\n    Hny(n2)   = Hny(n2)+Hy;\n    count(n2) = count(n2)+1;\n    % Average to n3\n    Hnx(n3)   = Hnx(n3)+Hx;\n    Hny(n3)   = Hny(n3)+Hy;\n    count(n3) = count(n3)+1;\nend\nHnx = Hnx./count;\nHny = Hny./count;\n% Centroids [x,y]\npt = (p(t1,:)+p(t2,:)+p(t3,:))/3;\n% Take unweighted average of the linear extrapolation from nodes to centroids\nHt = ( Hn(t1) + (pt(:,1)-p(t1,1)).*Hnx(t1) + (pt(:,2)-p(t1,2)).*Hny(t1) + ...\n       Hn(t2) + (pt(:,1)-p(t2,1)).*Hnx(t2) + (pt(:,2)-p(t2,2)).*Hny(t2) + ...\n       Hn(t3) + (pt(:,1)-p(t3,1)).*Hnx(t3) + (pt(:,2)-p(t3,2)).*Hny(t3) )/3;\n% DEAL WITH CONTOURING LEVELS\nif length(N)==1\n    lev = linspace(max(Ht),min(Ht),N+1);\n    num = N;\nelse\n    if (length(N)==2) && (N(1)==N(2))\n        lev = N(1);\n        num = 1;\n    else\n        lev = sort(N);\n        num = length(N);\n        lev = lev(num:-1:1);\n    end\nend\n% MAIN LOOP\nc   = [];\nh   = [];\nin  = false(numt,1);\nvec = 1:numt;\nold = in;\nfor v = 1:num       % Loop over contouring levels\n    \n    % Find centroid values >= current level\n    i     = vec(Ht>=lev(v));\n    i     = i(~old(i));         % Don't need to check triangles from higher levels\n    in(i) = true;\n    \n    % Locate boundary edges in group\n    bnd  = [i; i; i];       % Just to alloc\n    next = 1;\n    for k = 1:length(i)\n        ct    = i(k);\n        count = 0;\n        for q = 1:3     % Loop through edges in ct\n            ce = eINt(ct,q);\n            if ~in(e2t(ce,1)) || ((e2t(ce,2)>0)&&~in(e2t(ce,2)))    \n                bnd(next) = ce;     % Found bnd edge\n                next      = next+1;\n            else\n                count = count+1;    % Count number of non-bnd edges in ct\n            end\n        end\n        if count==3                 % If 3 non-bnd edges ct must be in middle of group\n            old(ct) = true;         % & doesn't need to be checked for the next level\n        end\n    end\n    numb = next-1; bnd(next:end) = [];\n    \n    % Skip to next lev if empty\n    if numb==0\n        continue\n    end\n    \n    % Place nodes approximately on contours by interpolating across bnd\n    % edges    \n    t1  = e2t(bnd,1);\n    t2  = e2t(bnd,2);\n    ok  = t2>0;\n    \n    % Get two points for interpolation. Always use t1 centroid and \n    % use t2 centroid for internal edges and bnd midpoint for boundary \n    % edges\n    \n    % 1st point is always t1 centroid\n    H1 = Ht(t1);                                                % Centroid value\n    p1 = ( p(t(t1,1),:)+p(t(t1,2),:)+p(t(t1,3),:) )/3;          % Centroid [x,y]\n    \n    % 2nd point is either t2 centroid or bnd edge midpoint\n    i1        = t2(ok);                                         % Temp indexing\n    i2        = bnd(~ok);\n    H2        = H1;\n    H2(ok)    = Ht(i1);                                         % Centroid values internally\n    H2(~ok)   = ( Hn(e(i2,1))+Hn(e(i2,2)) )/2;                  % Edge values at boundary\n    p2        = p1;\n    p2(ok,:)  = ( p(t(i1,1),:)+p(t(i1,2),:)+p(t(i1,3),:) )/3;   % Centroid [x,y] internally\n    p2(~ok,:) = ( p(e(i2,1),:)+p(e(i2,2),:) )/2;                % Edge [x,y] at boundary\n    \n    % Linear interpolation\n    r     = (lev(v)-H1)./(H2-H1);\n    penew = p1 + [r,r].*(p2-p1);\n    \n    % Do a temp connection between adjusted node & endpoint nodes in\n    % ce so that the connectivity between neighbouring adjusted nodes\n    % can be determined\n    vecb    = (1:numb)';\n    m       = 2*vecb-1;\n    c1      = 0*m;\n    c2      = 0*m;\n    c1(m)   = e(bnd,1);\n    c1(m+1) = e(bnd,2);\n    c2(m)   = vecb;\n    c2(m+1) = vecb;\n    \n    % Sort connectivity to place connected edges in sucessive rows\n    [c1,i] = sort(c1); c2 = c2(i);\n    \n    % Connect adjacent adjusted nodes\n    k    = 1;\n    next = 1;\n    while k<(2*numb)\n        if c1(k)==c1(k+1)\n            c1(next) = c2(k);\n            c2(next) = c2(k+1);\n            next     = next+1;\n            k        = k+2;         % Skip over connected edge\n        else\n            k = k+1;                % Node has only 1 connection - will be picked up above\n        end\n    end\n    ncc          = next-1; \n    c1(next:end) = []; \n    c2(next:end) = [];\n    \n    \n    % Plot the contours\n    % If an output is required, extra sorting of the\n    % contours is necessary for CLABEL to work.   \n    if nargout>0\n        \n        % Form connectivity for the contour, connecting \n        % its edges (rows in cc) with its vertices.\n        ndx = repmat(1,nume,1);\n        n2e = 0*penew;\n        for k = 1:ncc\n            % Vertices\n            n1 = c1(k); n2 = c2(k);\n            % Connectivity\n            n2e(n1,ndx(n1)) = k; ndx(n1) = ndx(n1)+1;\n            n2e(n2,ndx(n2)) = k; ndx(n2) = ndx(n2)+1;\n        end\n        bndn = n2e(:,2)==0;         % Boundary nodes\n        bnde = bndn(c1)|bndn(c2);   % Boundary edges\n        \n        % Alloc some space\n        tmpv = repmat(0,1,ncc);\n        \n        % Loop through the points at the current contour level (lev(v))\n        % Try to assemble the CS data structure introduced in \"contours.m\"\n        % so that clabel will work. Assemble CS by \"walking\" around each \n        % subcontour segment contiguously.\n        ce    = 1;\n        start = ce;\n        next  = 2;\n        cn    = c2(1);\n        flag  = false(ncc,1);        \n        x     = tmpv; x(1) = penew(c1(ce),1);\n        y     = tmpv; y(1) = penew(c1(ce),2);\n        for k = 1:ncc\n            \n            % Checked this edge\n            flag(ce) = true;\n            \n            % Add vertices to patch data\n            x(next) = penew(cn,1);\n            y(next) = penew(cn,2);\n            next    = next+1;\n            \n            % Find edge (that is not ce) joined to cn\n            if ce==n2e(cn,1)\n                ce = n2e(cn,2);\n            else\n                ce = n2e(cn,1);\n            end\n            \n            % Check the new edge\n            if (ce==0)||(ce==start)||(flag(ce))     \n               \n                % Plot current subcontour as a patch and save handles\n                x   = x(1:next-1);\n                y   = y(1:next-1);\n                z   = repmat(lev(v),1,next);\n                h   = [h; patch('Xdata',[x,NaN],'Ydata',[y,NaN],'Zdata',z, ...\n                                'Cdata',z,'facecolor','none','edgecolor','flat')]; hold on      \n                \n                % Update the CS data structure as per \"contours.m\"\n                % so that clabel works\n                c = horzcat(c,[lev(v), x; next-1, y]);\n                \n                if all(flag)    % No more points at lev(v)\n                    break\n                else            % More points, but need to start a new subcontour\n                    \n                    % Find the unflagged edges\n                    edges = find(~flag);\n                    ce    = edges(1);\n                    % Try to select a boundary edge so that we are \n                    % not repeatedly running into the boundary\n                    for i = 1:length(edges)\n                        if bnde(edges(i))\n                            ce = edges(i); break\n                        end\n                    end\n                    % Reset counters\n                    start = ce;\n                    next  = 2;\n                    % Get the non bnd node in ce\n                    if bndn(c2(ce))\n                        cn = c1(ce);\n                        % New patch vectors\n                        x = tmpv; x(1) = penew(c2(ce),1);\n                        y = tmpv; y(1) = penew(c2(ce),2);\n                    else\n                        cn = c2(ce);\n                        % New patch vectors\n                        x = tmpv; x(1) = penew(c1(ce),1);\n                        y = tmpv; y(1) = penew(c1(ce),2);\n                    end                    \n                    \n                end\n            \n            else                            \n                % Find node (that is not cn) in ce\n                if cn==c1(ce)\n                    cn = c2(ce);\n                else\n                    cn = c1(ce);\n                end\n            end\n            \n        end\n        \n    else        % Just plot the contours as is, this is faster...\n        \n        z = repmat(lev(v),2,ncc);\n        \n        patch('Xdata',[penew(c1,1),penew(c2,1)]', ...\n              'Ydata',[penew(c1,2),penew(c2,2)]', ...\n              'Zdata',z,'Cdata',z,'facecolor','none','edgecolor','flat'); \n          \n        hold on\n        \n    end\n    \nend\n% Assign outputs if needed\nif nargout>0\n    cout = c;\n    hout = h;\nend\nreturn\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [e,eINt,e2t] = mkcon(p,t)\nnumt = size(t,1);\nvect = 1:numt;\n% DETERMINE UNIQUE EDGES IN MESH\n \ne       = [t(:,[1,2]); t(:,[2,3]); t(:,[3,1])];             % Edges - not unique\nvec     = (1:size(e,1))';                                   % List of edge numbers\n[e,j,j] = unique(sort(e,2),'rows');                         % Unique edges\nvec     = vec(j);                                           % Unique edge numbers\neINt    = [vec(vect), vec(vect+numt), vec(vect+2*numt)];    % Unique edges in each triangle\n% DETERMINE EDGE TO TRIANGLE CONNECTIVITY\n% Each row has two entries corresponding to the triangle numbers\n% associated with each edge. Boundary edges have one entry = 0.\nnume = size(e,1);\ne2t  = repmat(0,nume,2);\nndx  = repmat(1,nume,1);\nfor k = 1:numt\n    % Edge in kth triangle\n    e1 = eINt(k,1); e2 = eINt(k,2); e3 = eINt(k,3);\n    % Edge 1\n    e2t(e1,ndx(e1)) = k; ndx(e1) = ndx(e1)+1;\n    % Edge 2\n    e2t(e2,ndx(e2)) = k; ndx(e2) = ndx(e2)+1;\n    % Edge 3\n    e2t(e3,ndx(e3)) = k; ndx(e3) = ndx(e3)+1;\nend\nreturn\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/tricontour.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5548418745294285}}
{"text": "function err = RotateMatrixCriterion(R,U)\n\ndx = R*U(:,1)-[1;0;0;0];\ndy = R*U(:,2)-[0;1;0;0];\nerr = dx'*dx + dy'*dy;", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/spaceTime/adamMice/analysis/RotateMatrixCriterion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5547036261040833}}
{"text": "function RDr=scd_model_GPD_RDr(d,Delta,delta,Dr)\n% RDr=scd_model_GPD_RDr(d,Delta,delta,Dr)\n\nalpha=4*delta*Dr/d^2; beta=4*Delta*Dr/d^2;\na=[1.84118378134065\t5.33144277352503\t8.53631636634628\t11.7060049025920\t14.8635886339090].^2;% roots of bessel J1'\ntd=Delta-delta/3;\n\nk=zeros(length(delta),5);\nfor m=1:5;\n    numerator=2*alpha*a(m) - 2 + 2*exp(-alpha*a(m)) + (2-exp(alpha*a(m))-exp(-alpha*a(m))).*exp(-beta*a(m));\n    denominator=alpha.^2*a(m).^3.*(a(m)-1);\n    k(:,m)=numerator(:)./denominator(:);\nend\nk(isnan(k))=0;\nRDr=sum(k,2).*d.^2./(2*td);", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/CHARMEDfun/scd_model_GPD_RDr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5546994526247327}}
{"text": "function H = hurst_estimate(sequence,method,isplot,opt)\n%\n% 'hurst_estimate' estimate the hurst parameter of a given sequence with\n%     an appointed method. The algorithms of the methods can be found in\n%     Murad's Taqqu, Vadim Teverovsky and Walter Willinger's paper\n%     \"Estimators for long-range dependence: an empirical study\" or other\n%     related papers.\n% Inputs:\n%     sequence: the input sequence for estimate\n%     method: the name of a function which used to estimate the hurst\n%             parameter of the sequence,e.g.\n%               'aggvar': use aggvar function to estimate.\n%               'RS': use RS function to estimate.\n%               'per': use per function to estimate.\n%     isplot: whether display the plot. without a plot if isplot equal to 0\n%     opt: a optional parameter for some methods\n% Outputs:\n%     H: the estimated hurst coeffeient of the input sequence\n% Examples:\n%     H = hurst_estimate('peng',sequence,1);\n%\n\n%  Author: Chu Chen \n%  Version 1.0,  03/10/2008\n%  chen-chu@163.com\n%\n\nif nargin == 2\n    isplot = 0;\n    H = feval(method,sequence,isplot);\nelseif nargin == 3\n    H = feval(method,sequence,isplot);\nelseif nargin == 4\n    H = feval(method,sequence,isplot,opt);\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/hurst_estimate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5546424187924968}}
{"text": "function writePolygonSet(polys, filename)\n%WRITEPOLYGONSET Write a set of simple polygons into a file.\n%   \n%   writePolygonSet(POLYS, FILENAME);\n%   Writes the set of polygons in the file FILENAME.\n%   Following format is used:\n%     X11 X12 X13 ... X1N\n%     Y11 Y12 Y13 ... Y1N\n%     X21 X22 X23 ... X2N\n%     Y21 Y22 Y23 ... Y2N\n%   Each polygon may have a different number of vertices. \n%\n%   See also \n%   polygons2d, readPolygonSet\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2013-01-14\n% Copyright 2013-2022 INRA - TPV URPOI - BIA IMASTE\n\n% open file for reading\nfid = fopen(filename, 'wt');\n\nfor i = 1:length(polys)\n    poly = polys{i};\n    n = size(poly, 1);\n    \n    % precompute format\n    format = [repmat('%g ', 1, n) '\\n'];\n    \n    % write one line for x, then one line for y\n    fprintf(fid, format, poly(:,1)');\n    fprintf(fid, format, poly(:,2)');    \nend\n\n% close file\nfclose(fid);\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/writePolygonSet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.5546424150211537}}
{"text": "function dice = dice_labels(lname1, lname2)\n% d = dice_labels(lname1, lname2)\n%\n% computes Dice coefficient of the two given label files.\n% \n\n%\n% dice_labels.m\n%\n% Original Author: Nick Schmansky\n% CVS Revision Info:\n%    $Author: nicks $\n%    $Date: 2011/03/02 00:04:12 $\n%    $Revision: 1.2 $\n%\n% Copyright \u00a9 2011 The General Hospital Corporation (Boston, MA) \"MGH\"\n%\n% Terms and conditions for use, reproduction, distribution and contribution\n% are found in the 'FreeSurfer Software License Agreement' contained\n% in the file 'LICENSE' found in the FreeSurfer distribution, and here:\n%\n% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense\n%\n% Reporting: freesurfer@nmr.mgh.harvard.edu\n%\n\nlabel1 = read_label('',lname1);\nlabel2 = read_label('',lname2);\n\nlabel1Size = size(label1,1);\nlabel2Size = size(label2,1);\n\nhits = 0;\nfor i=1:label1Size\n   x1 = label1(i,2);\n   y1 = label1(i,3);\n   z1 = label1(i,4);\n   for j=1:label2Size\n     x2 = label2(j,2);\n     y2 = label2(j,3);\n     z2 = label2(j,4);\n     if ((x1==x2) && (y1==y2) && (z1==z2))\n       hits = hits+1;\n       break;\n     end\n   end\nend\n\ndice = (2 * hits) / (label1Size + label2Size);\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/external/freesurfer/dice_labels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.5546424141409658}}
{"text": "function a = r8cc_inc ( m, n, nz_num, colptr, rowind, a, i, j, aij )\n\n%*****************************************************************************80\n%\n%% R8CC_INC increments a value of a R8CC matrix.\n%\n%  Discussion:\n%\n%    The R8CC format is the double precision sparse compressed column\n%    format.  Associated with this format, we have an M by N matrix\n%    with NZ_NUM nonzero entries.  We construct the column pointer\n%    vector COL of length N+1, such that entries of column J will be\n%    stored in positions COL(J) through COL(J+1)-1.  This indexing\n%    refers to both the ROW and A vectors, which store the row indices\n%    and the values of the nonzero entries.  The entries of the\n%    ROW vector corresponding to each column are assumed to be\n%    ascending sorted.\n%\n%    The R8CC format is equivalent to the MATLAB \"sparse\" format,\n%    and the Harwell Boeing \"real unsymmetric assembled\" (RUA) format.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    01 September 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Iain Duff, Roger Grimes, John Lewis,\n%    User's Guide for the Harwell-Boeing Sparse Matrix Collection,\n%    October 1992\n%\n%  Parameters:\n%\n%    Input, integer M, the number of rows of the matrix.\n%\n%    Input, integer N, the number of columns of the matrix.\n%\n%    Input, integer NZ_NUM, the number of nonzero entries.\n%\n%    Input, integer COLPTR(N+1), indicate where each column's data begins.\n%\n%    Input, integer ROWIND(NZ_NUM), the row indices.\n%\n%    Input, real A(NZ_NUM), the nonzero entries.\n%\n%    Input, integer I, J, the indices of the value to retrieve.\n%\n%    Input, real AIJ, the value to be added to A(I,J).\n%\n%    Output, real A(NZ_NUM), entry (I,J) has been incremented.\n%\n\n%\n%  Seek sparse index K corresponding to full index (I,J).\n%\n  k = r8cc_ijk ( m, n, nz_num, colptr, rowind, i, j );\n%\n%  If no K was found, we fail.\n%\n  if ( k == -1 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'R8CC_INC - Fatal error!\\n' );\n    fprintf ( 1, '  R8CC_IJK could not find the entry.\\n' );\n    fprintf ( 1, '  Row I = %d\\n', i );\n    fprintf ( 1, '  Col J = %d\\n', j );\n    error ( 'R8CC_INC - Fatal error!' );\n  end\n\n  a(k) = a(k) + aij;\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r8cc_inc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.5546424112498106}}
{"text": "function epoch= getBestEpoch(recalls, recallNs, N)\n    if nargin<3, N= 5; end\n    \n    % This command is generally OK\n    % [~, epoch]= max(recalls(recallNs==N,:));\n    % but the following does tie-breaking\n    \n    nRecalls= length(recallNs);\n    nEpochs= size(recalls, 2);\n    assert( nRecalls==size(recalls, 1) );\n    \n    posN= find( recallNs==N, 1);\n    assert(~isempty(posN));\n    posNs= posN:-1:1;\n    if posN<nRecalls\n        posNs= [posNs, (posN+1):nRecalls];\n    end\n    \n    potential= true(1, nEpochs);\n    for posN= posNs\n        maxVal= max(recalls(posN, potential));\n        isMax= abs(recalls(posN,:)-maxVal)<1e-6;\n        potential= potential & isMax;\n        if sum(potential)<=1\n            break;\n        end\n    end\n    \n    epoch= find( potential, 1 );\n    assert(~isempty(epoch));\nend\n", "meta": {"author": "Relja", "repo": "netvlad", "sha": "652dbe71aa45c691961ddd9f6cf902574e6bdc2f", "save_path": "github-repos/MATLAB/Relja-netvlad", "path": "github-repos/MATLAB/Relja-netvlad/netvlad-652dbe71aa45c691961ddd9f6cf902574e6bdc2f/getBestEpoch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5546424065982797}}
{"text": "function est = refine_grid_estimates(f_obj, grid, est_idx)\n%REFINE_GRID_ESTIMATES Refines DOA estimates obtained from a grid.\n%Inputs:\n%   f_obj - Objective function. Its local minimums identify the DOAs.\n%   grid - Grid used for the original estimation.\n%   est_idx - Indices (corresponding to the grid) of the original\n%             estimates.\n%Output:\n%   est - Refined estimates.\nest = zeros(size(est_idx));\nif size(grid, 1) == 1\n    % 1d\n    n_iter = 10;\n    subgrid_size = 10;\n    for kk = 1:length(est_idx)\n        % k-th DOA\n        % init bounds\n        if est_idx(kk) > 1\n            lb = grid(est_idx(kk) - 1);\n        else\n            lb = grid(1);\n        end\n        if est_idx(kk) < length(grid)\n            ub = grid(est_idx(kk) + 1);\n        else\n            ub = grid(end);\n        end\n        % refine\n        for ii = 1:n_iter\n            % find minimum over the subgrid\n            subgrid = linspace(lb, ub, subgrid_size);\n            obj_vals = f_obj(subgrid);\n            [~, min_idx] = min(obj_vals);\n            % update bounds\n            if min_idx > 1\n                lb = subgrid(min_idx - 1);\n            else\n                lb = subgrid(1);\n            end\n            if min_idx < subgrid_size\n                ub = subgrid(min_idx + 1);\n            else\n                ub = subgrid(end);\n            end\n        end\n        est(kk) = subgrid(min_idx);\n    end\nelse\n    % 2d\n    error('Not implemented.');\nend\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/estimator/refine_grid_estimates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5546424048379037}}
{"text": "function [h,ax] = plot3d(v,data,varargin)\n% plot spherical data\n%\n% Syntax\n%   plot3d(v,data)\n%\n% Input\n%\n% See also\n% savefigure\n\n% -------------------- GET OPTIONS ----------------------------------------\n\n% where to plot\nif check_option(varargin,'parent')\n  ax = get_option(varargin,'parent');\nelse\n  ax = gca;\nend\n\n% scale and shift if required\nv = v .* get_option(varargin,'scale',1);\nv = v + get_option(varargin,'shift',0);\n\n\n% plot\n%v = v .* reshape(data,size(v));\nh = surf(v.x,v.y,v.z,reshape(double(data),size(v,1),size(v,2),[]),'parent',ax,...\n  'edgeColor','none');\n\n% colormap\nif numel(v) == numel(data), mtexColorMap(ax,getMTEXpref('defaultColorMap')); end\n\n\nif ~ishold\n \n  axis(ax,'equal','vis3d','off');\n\n  set(ax,'XDir','rev','YDir','rev',...\n    'XLim',[-1,1],'YLim',[-1,1],'ZLim',[-1,1]);\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@vector3d/plot3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5546424048379037}}
{"text": "% The COBRAToolbox: testFBA.m\n%\n% Purpose:\n%     - tests the basic functionality of FBA\n%       Tests four basic solution: Optimal minimum 1-norm solution, Optimal\n%       solution on fructose, Optimal anaerobic solution, Optimal ethanol\n%       secretion rate solution returns 1 if all tests were completed succesfully, 0 if not\n%\n% Authors:\n%     - Original file: Joseph Kang 04/27/09\n%     - CI integration: Laurent Heirendt January 2017\n%\n\n% save the current path\ncurrentDir = pwd;\n\n% initialize the test\nfileDir = fileparts(which('testFBA'));\ncd(fileDir);\n\n% set the tolerance\ntol = 1e-8;\n\n% define the solver packages to be used to run this test\nsolverPkgs = {'ibm_cplex', 'mosek', 'gurobi', 'tomlab_cplex', 'glpk'};\n\n% load the model\nload('testFBAData.mat');\nmodel = readCbModel('testFBAData.mat','modelName','model');\nfor k = 1:length(solverPkgs)\n\n    % change the COBRA solver (LP)\n    solverOK = changeCobraSolver(solverPkgs{k}, 'LP', 0);\n\n    if solverOK == 1\n        fprintf('   Testing flux balance analysis using %s ... ', solverPkgs{k});\n\n        % check the optimal solution - BiomassEcoli\n        fprintf('\\n>> Optimal minimum 1-norm solution\\n');\n        model = changeObjective(model, {'BiomassEcoli'}, 1);\n        solution = optimizeCbModel(model);\n\n        % testing if f values are within range\n        assert(abs(solution.f - solutionStd.f) < tol);\n\n        % testing if c*x == f\n        assert(abs(model.c' * solution.x - solution.f) < tol);\n\n        % print the flux vector\n        printFluxVector(model, solution.x, true, true);\n\n        % check the optimal solution - fructose\n        fprintf('\\n>> Optimal solution on fructose\\n');\n        model2 = changeRxnBounds(model, {'EX_glc(e)', 'EX_fru(e)'}, [0 -9], 'l');\n        solution2 = optimizeCbModel(model2);\n\n        % testing if f values are within range\n        assert(abs(solution2.f - solution2Std.f) < tol);\n\n        % testing if c*x == f\n        assert(abs(model2.c' * solution2.x - solution2.f) < tol);\n\n        % print the flux vector\n        printFluxVector(model2, solution.x, true, true);\n\n        % check the optimal anaerobic solution\n        fprintf('\\n>> Optimal anaerobic solution\\n');\n        model3 = changeRxnBounds(model, 'EX_o2(e)', 0, 'l');\n        solution3 = optimizeCbModel(model3);\n\n        % testing if f values are within range\n        assert(abs(solution3.f - solution3Std.f) < tol);\n\n        % testing if c*x == f\n        assert(abs(model3.c' * solution3.x - solution3.f) < tol);\n\n        % check the optimal ethanol secretion rate solution\n        fprintf('\\n>> Optimal ethanol secretion rate solution \\n');\n        model4 = changeObjective(model, 'EX_etoh(e)', 1);\n        solution4 = optimizeCbModel(model4);\n\n        % testing if f values are within range\n        assert(abs(solution4.f - solution4Std.f) < tol);\n\n        % testing if c*x == f\n        assert(abs(model4.c' * solution4.x - solution4.f) < tol);\n\n        % output a success message\n        fprintf('Done.\\n');\n    end\nend\n\n% change the directory\ncd(currentDir)\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/verifiedTests/analysis/testFBA/testFBA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920211198871, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5545929093886387}}
{"text": "% Check that online inference gives same results as filtering for various algorithms\n\nN = 3;\nQ = 2;\nss = N*2;\n\nrand('state', 0);\nrandn('state', 0);\n\n\nobs_size = 1;\ndiscrete_obs = 0;\nbnet = mk_chmm(N, Q, obs_size, discrete_obs);\nns = bnet.node_sizes_slice;\n\nengine = {};\nengine{end+1} = hmm_inf_engine(bnet);\nE = length(engine);\n\nonodes = (1:N)+N;\n\nT = 4;\nev = cell(ss,T);\nev(onodes,:) = num2cell(randn(N, T));\n\n\nfilter = 1;\nloglik2 = zeros(1,E);\nfor e=1:E\n  [engine2{e}, loglik2(e)] = enter_evidence(engine{e}, ev, 'filter', filter);\nend\n\nloglik = zeros(1,E);\nmarg1 = cell(E,N,T);\nfor e=1:E\n  ll = zeros(1,T);\n  engine{e} = dbn_init_bel(engine{e});\n  for t=1:T\n    [engine{e}, ll(t)] = dbn_update_bel(engine{e}, ev(:,t), t);\n    for i=1:N\n      marg1{e,i,t} = dbn_marginal_from_bel(engine{e}, i);\n    end\n  end\n  loglik1(e) = sum(ll);\nend\n\nassert(approxeq(loglik1, loglik2))\n\na = zeros(E,N,T);\nfor e=1:E\n  for t=1:T\n    for i=1:N\n      marg2{e,i,t} = marginal_nodes(engine2{e}, i, t);\n      a(e,i,t) = (approxeq(marg2{e,i,t}.T(:), marg1{e,i,t}.T(:)));\n    end\n  end\nend\n\nassert(all(a(:)==1))\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/dynamic/Old/online1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5545929028002515}}
{"text": "function [correct_class_decision_values normalized_rank_results rank_confusion_matrix] = get_rank_and_decision_value_results(cv, YTe, classifier_labels, decision_values, create_rank_confusion_matrix)\n% This helper method calculates the normalized rank results, the decision values for the correct class, and the rank confusion matrix information.\n%  This method should be run every time the classifier is tested.\n%\n%  Input parameters:\n%    YTe:  the labels for the current test points\n%    decision_values:  The decision values for the current test point\n%    create_rank_confusion_matrix:  whether a confusion matrix should be created\n%\n%  The returned values are in the structure NORMALIZED_RANK_AND_DECISION_VALUE_RESULTS and have the fields\n%\n%   correct_class_decision_values: a [num_test_points x 1] vector containing the decision value for the ith test point (for the correct class of the ith point)\n%\n%   normalized_rank_results:  a [num_test_points x 1] vector containing the normalized rank value for the ith test point \n%\n%   rank_confusion_matrix: [num_predicted_classes x num_actual classes] current rank confusion matrix.  \n%      the i, j entry of this matrix tells how high up on the rank of predictions for the jth class\n%      was entry i.  \n%\n\n%==========================================================================\n\n%     This code is part of the Neural Decoding Toolbox.\n%     Copyright (C) 2011 by Ethan Meyers (emeyers@mit.edu)\n% \n%     This program is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 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 <http://www.gnu.org/licenses/>.\n    \n%==========================================================================   \n\n\nrank_confusion_matrix = [];\n\n\nYTe_unique_values = unique(YTe);\n\n    \n% % %[vals sorted_inds] = sort(decision_values', 'descend');   % NEED TO BE CAREFUL THERE IS NOT TIE IN THE MAX DECISION VALUE (could create a bias in results)                        \n[vals sorted_inds] = sort((decision_values + eps .* rand(size(decision_values)))', 'descend');   % adding a small amount of noise so that there is not a tie in the decision values                       \nthe_ranks_all_test_points = sorted_inds';   % each row has all the ranked order results for a given test point (i.e., all ranks for YTe(i))\n\n\n% go through all test points and find the ranking and the decision value of the real label \nfor iTestPoint = 1:length(YTe)                                            \n    curr_rank_results(iTestPoint) = find(YTe_unique_values(the_ranks_all_test_points(iTestPoint, :)) == YTe(iTestPoint));  % find rank of the real label YTe \n    correct_class_decision_values(iTestPoint) = decision_values(iTestPoint, (classifier_labels == YTe(iTestPoint)));   % find the decision value for real label\nend    \n\n\n\nnormalized_rank_results = 1 - (((curr_rank_results) - 1)./(length(YTe_unique_values) - 1));\n\n\n\n% get information to create the rank confusion matrix\nif create_rank_confusion_matrix == 1\n    for iUniqueYTe = 1:length(YTe_unique_values)   % assuming that each time unique(YTe) has all possible label values (if it doesn't then this code will not work)\n\n            curr_rank_inds = find(YTe == YTe_unique_values(iUniqueYTe));\n            [rank_cm_vals rank_cm_inds] = sort(the_ranks_all_test_points(curr_rank_inds, :)');   % rank_cm_inds contains predicted classes from the most likely (first index value), to least likely (last index value) \n\n            rank_confusion_matrix(:, iUniqueYTe) = sum(1 -((rank_cm_inds -1)./(length(YTe_unique_values) - 1)), 2);  % add all test points together for a total rank confusion matrix\n\n    end  \nend\n\n\n    \n    \n\n\n\n\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/ndt_1_0_4/cross_validators/@standard_resample_CV/get_rank_and_decision_value_results.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5545929012919254}}
{"text": "function newimg = move3dimage(img,Vy,Vx,Vz,method,offsets,jacobian_modulation)\n%\n% Calculate the moved image: \n%    newimg = move3dimage3(img,Vy,Vx,Vz,method,offsets)\n%\n% Input: \n%\tVy, Vx, Vz\t- the motion field\n%\tmethod\t\t- interpolation method, default value is 'linear'\n%   zoffset\t\t- Offset of Z for the motion field dimension respective to\n%\t\t\t\t  the img dimension\n%\n% In version 3, the input method is allowed to be larger than the dimension\n% of motion fields. This actually allows better recostruction of the moved\n% images because the motion fields could extend larger than the original\n% dimension. An additional parameter has been added, the 'offsets'\n% parameter.\n% \n%\nif ~exist('method','var') || isempty(method)\n\tmethod = 'linear';\nend\n\nif ~exist('offsets','var') || isempty(offsets)\n\toffsets = [0 0 0];\nelseif length(offsets) == 1\n\toffsets = [0 0 offsets];\nend\n\nif ~exist('jacobian_modulation','var') || isempty(jacobian_modulation)\n\tjacobian_modulation = 0;\nend\n\n% Computer Jacobian\nif jacobian_modulation ~= 0\n\tjac = compute_jacobian(Vy,Vx,Vz);\nend\n\ndimimg = mysize(img);\ndimmotion = mysize(Vy);\nx0 = single([1:dimmotion(2)])+offsets(2);\ny0 = single([1:dimmotion(1)])+offsets(1);\nz0 = single([1:dimmotion(3)])+offsets(3);\n[xx,yy,zz] = meshgrid(x0,y0,z0);\t% xx, yy and zz are the original coordinates of image pixels\n\nVy = max((yy-Vy),1); clear yy; Vy = min(Vy,dimimg(1)); \nVx = max((xx-Vx),1); clear xx; Vx = min(Vx,dimimg(2));\nVz = max((zz-Vz),1); clear zz; Vz = min(Vz,dimimg(3));\n\nif dimimg(3) > 1\n\tnewimg = zeros(dimmotion,'single');\n\tif offsets(3) == 0 && size(img,3) == size(Vy,3)\n\t\tspacing = 20;\n\t\tif mod(dimimg(3),spacing) == 1\n\t\t\tspacing = 19;\n\t\tend\n\t\t\n\t\tN = ceil(dimimg(3)/spacing);\n\t\tfprintf('Moving image');\n\t\tfor k = 1:N\n\t\t\tfprintf('.');\n\t\t\tzmin = (k-1)*spacing+1;\n\t\t\tzmax = min(dimimg(3),k*spacing);\n\t\t\tzmin2 = floor(min(min(min(Vz(:,:,zmin:zmax)))));\n\t\t\tzmax2 = ceil(max(max(max(Vz(:,:,zmin:zmax)))));\n\t\t\t%newimg(:,:,zmin:zmax) = interp3(xx(:,:,zmin2:zmax2),yy(:,:,zmin2:zmax2),zz(:,:,zmin2:zmax2),img(:,:,zmin2:zmax2),Vx(:,:,zmin:zmax),Vy(:,:,zmin:zmax),Vz(:,:,zmin:zmax),method);\n\t\t\tnewimg(:,:,zmin:zmax) = interp3(x0,y0,z0(zmin2:zmax2),img(:,:,zmin2:zmax2),Vx(:,:,zmin:zmax),Vy(:,:,zmin:zmax),Vz(:,:,zmin:zmax),method);\n\t\tend\n\t\tfprintf('\\n');\n\telse\n\t\tnewimg = interp3(img,Vx,Vy,Vz,method,0);\n\tend\n\t%newimg = interp3(img,Vx,Vy,Vz,method,0);\nelse\n\tnewimg = interp2(img,Vx,Vy,method,0);\nend\n\n%newimg = interpn(img,yy-Vy,xx-Vx,zz-Vz,method,0);\n\n\nif jacobian_modulation ~= 0\n\t% Apply Jacobin intensity modulation\n\tjac(isinf(jac)) = 1;\n\tjac(jac<0) = 1;\n\tnewimg = newimg .* jac;\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/ImageRegistration/OpticalFlow/move3dimage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5545928947035378}}
{"text": "function jed = ymdf_to_jed_zoroastrian ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_JED_ZOROASTRIAN converts a Zoroastrian YMDF date to a JED.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    17 March 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer Y, M, D, real F, the YMDF date.\n%\n%    Output, real JED, the corresponding Julian Ephemeris Date.\n%\n  jed_epoch = epoch_to_jed_zoroastrian ( );\n\n  jed = jed_epoch + ( d - 1 ) + 30 * ( m - 1 ) + 365 * ( y - 1 ) + 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_zoroastrian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.5545928912705735}}
{"text": "function [y_splined, x_spline, s_weights, y_splined_ext] = splinerMat(x, y, dxs, reg_factor, x_ext)\n% SYNTAX:\n%   [y_splined, x_spline, s_weights, y_splined_ext] = splinerMat(x, y, dxs, reg_factor, <x_ext>)\n%\n% EXAMPLE:\n%   [y_splined, x_spline, s_weights, y_splined_ext] = splinerMat(x, y, 4, 0, x_ext);\n%   [y_splined, x_spline, s_weights, y_splined_ext] = splinerMat(x, [y y_var], 4, 0, x_ext);\n%\n% INPUT:\n%   x            [n x 1] observation time\n%   y            [n x 1] observation value\n%                [n x 2] observation value and variances (in this case the variances of the data are taken into account)\n%   dxs          [1 x 1] spline base size\n%   reg_factor   [1 x 1] regularization factor on the first derivative\n%   x_ext        [m x 1] points in which to compute the interpolation\n%\n% OUTPUT:\n%   y_splined     [n x 1] interpolated observation (on the observation epochs)\n%   x_spline      [o x 1] center of the (o) splines\n%   s_weights     [o x 1] weights of the splines\n%   y_splined_ext [m x 1] spline interpolated in x_ext positions\n%\n% DESCRIPTION:\n%   Interpolate with cubic splines a given dataset\n%\n\n%--- * --. --- --. .--. ... * ---------------------------------------------\n%               ___ ___ ___\n%     __ _ ___ / __| _ | __|\n%    / _` / _ \\ (_ |  _|__ \\\n%    \\__, \\___/\\___|_| |___/\n%    |___/                    v 1.0RC1\n%\n%--------------------------------------------------------------------------\n%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n%  Written by:        Andrea Gatti\n%  Contributors:      Andrea Gatti, Giulio Tagliaferro\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 <http://www.gnu.org/licenses/>.\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n    if (nargin < 4)\n        reg_factor = 0;\n    end\n    if isempty(x)\n        x = 1:size(y, 1);\n    end\n    \n    inan = isnan(y);\n    if (size(y,2) == 2)\n        inan = inan(:,1) | inan(:,2);\n    end\n    \n    x(inan) = [];\n    y(inan) = [];\n    \n    [x, id] = sort(x);\n    y = y(id,:);\n    if ~isempty(y)\n        if ((nargin == 3) || (reg_factor == 0))\n            if (size(y,2) == 2)\n                [y_splined, x_spline, s_weights] = spliner_v51(x,y(:,1),y(:,2),dxs);\n            else\n                [y_splined, x_spline, s_weights] = spliner_v5(x,y,dxs);\n            end\n        else\n            if (size(y,2) == 2)\n                [y_splined, x_spline, s_weights] = spliner_v51R(x,y(:,1),y(:,2),dxs, reg_factor);\n            else\n                [y_splined, x_spline, s_weights] = spliner_v5R(x,y,dxs, reg_factor);\n            end\n        end\n    else\n        y_splined = y;\n        x_spline = [];\n        s_weights = [];\n    end\n\n    % Interpolation => using spline to predict in different coordinates\n    % (not present in the C version)\n    if (nargin == 5)\n        if ~isempty(x_spline)\n            mask = (isnan(s_weights));\n            if (length(mask) > 2)\n                mask = mask | [mask(2:end); 0] | [0; mask(1:end-1)];\n            end\n            s_weights = interp1(x_spline(~mask),s_weights(~mask),x_spline);\n            if (size(x_ext,1)==1)\n                x_ext = x_ext';\n            end\n            y_splined_ext = zeros(size(x_ext,1),1);\n            for s = 1:length(x_spline)\n                tau = round((x_ext-repmat(x_spline(s),length(x_ext),1))/dxs *1e13)/1e13; % 1e13 rounding necessary to avoid numerical problems\n                y_splined_ext = y_splined_ext + s_weights(s)*cubicSpline(tau);\n            end\n        else\n            y_splined_ext = nan(numel(x_ext),1);\n        end\n    else\n        y_splined_ext = y_splined;\n    end\n    tmp = nan(numel(inan),1);\n    tmp(~inan) = y_splined;\n    y_splined = tmp;\nend\n\n% No Regularization + variances\nfunction [y_splined, x_spline, s_weights] = spliner_v51(x, y, y_var, dxs)\n    nObs = length(x);\n\n    % size of the intervall to interpolate\n    x_span = x(nObs) - x(1);\n    x0 = x(1);\n    x = x - x0;\n    \n    % compute the number of splines needed for the interpolation\n    n_splines = ceil(x_span/dxs) + 3;\n\n    % compute spline centers\n    x_spline = zeros(n_splines,1);\n    s_weights = [];\n    s_center = x(1) - (((n_splines-3)*dxs-x_span)/2) - dxs;\n    for i = 1:n_splines\n        x_spline(i) = s_center+(i-1)*dxs;\n    end\n\n    % init A matrix\n    A = zeros(nObs, 4);\n    skips = zeros(n_splines,1);\n    N = sparse(n_splines,n_splines);\n    TN = zeros(n_splines, 1);\n\n    cur_spline = 1;          % first spline whose domain intersect the observation\n    %tau = 0;                % normalized distance between the observation and the center of the cur_spline\n    i = 1;                  % index of the first observation\n    first_obs = i;          % first observation used in the current A matrix\n    first_spline = 1;       % first spline used in the current A matrix\n    n_skip = 0;              % number of spline to \"skip\" because ain't intersecting an observation\n    used_obs = 0;            % number of observation used in building the N matrix\n    y_splined = zeros(length(y),1);           % output\n    skips(1) = 0;\n    while (i <= nObs)\n        % Compute the distance between the current observation and the current spline\n        tau = round((x(i)-x_spline(cur_spline))/dxs *1e13)/1e13; % 1e13 rounding necessary to avoid numerical problems\n        if (tau <= 2)\n            % fill the design matrix\n            A(i-first_obs+1,:) = cubicSpline([tau (tau-1) (tau-2) (tau-3)]);\n            used_obs = used_obs+1;\n            n_skip = 0;\n            i = i+1;\n        else\n            cur_local_spline = cur_spline-first_spline+1;\n            skips(cur_spline+1) = i-first_obs;\n            % This block of the A matrix is completed\n            % Computing N\n            n_skip = n_skip +1;\n            if (n_skip < 4)\n                if (n_skip == 1)\n                    A2 = A((skips(cur_spline)+1):i-first_obs,:);\n                    iQ = sparse(diag(1./y_var(first_obs+skips(cur_spline):i-1)));\n                    N(cur_local_spline:cur_local_spline+3,cur_local_spline:cur_local_spline+3) = sparse(N(cur_local_spline:cur_local_spline+3,cur_local_spline:cur_local_spline+3) + A2'*iQ*A2);\n\n                    % Computing TN\n                    TN(cur_local_spline:cur_local_spline+3) = TN(cur_local_spline:cur_local_spline+3) + A2' * iQ * y(first_obs+skips(cur_spline):i-1);\n                end\n                cur_spline = cur_spline +1;\n            else\n                % If I skip more than 3 times the spline solutions are independent,\n                % I can start solving my filtering for the first i points\n\n                s_par = [];\n                if (used_obs < size(N,2))\n                    fprintf('WARNING: Regularization is needed observations are less than splines.\\n         Adding 1e-9 on the normal matrix diagonal\\n');\n                    R = sparse(eye(cur_local_spline)*1e-9);\n                    s_par = (N(1:cur_local_spline,1:cur_local_spline)+R)\\TN(1:cur_local_spline);\n                else\n                    s_par = (N(1:cur_local_spline,1:cur_local_spline))\\TN(1:cur_local_spline);\n                end\n                s_weights = [s_weights; s_par];\n\n                for s = first_spline:cur_spline-3\n                    y_splined(skips(s)+first_obs:skips(s+1)+first_obs-1) = y_splined(skips(s)+first_obs:skips(s+1)+first_obs-1) + A((skips(s):skips(s+1)-1)+1,:) * s_par(s-first_spline+1:s+3-first_spline+1);\n                end\n\n                % find the next spline whose domain intersect the next observation\n                tau = (x(i)-x_spline(cur_spline))/dxs;\n                while (tau > 2)\n                    cur_spline = cur_spline+1;\n                    tau = (x(i)-x_spline(cur_spline))/dxs;\n                    if (tau > 2),\n                        s_weights(cur_spline) = nan;\n                    end\n                end\n                first_spline = cur_spline;\n                first_obs = i;\n                skips(cur_spline) = 0;\n\n                A = zeros(nObs-i, 4);\n                N = sparse(n_splines-cur_spline+1, n_splines-cur_spline+1);\n                TN = zeros(n_splines-cur_spline+1,1);\n                used_obs = 0;\n            end\n        end\n    end\n\n    skips(cur_spline+1) = i-first_obs;\n    if (n_skip == 0)\n        A2 = A(skips(cur_spline)+1:i-first_obs,:);\n        iQ = sparse(diag(1./y_var(first_obs+skips(cur_spline):i-1)));\n        N(cur_spline-first_spline+1:cur_spline+3-first_spline+1,cur_spline-first_spline+1:cur_spline+3-first_spline+1) = sparse(N(cur_spline-first_spline+1:cur_spline+3-first_spline+1,cur_spline-first_spline+1:cur_spline+3-first_spline+1) + A2'*iQ*A2);\n\n        % Computing TN\n        TN(cur_spline-first_spline+1:cur_spline+3-first_spline+1) = TN(cur_spline-first_spline+1:cur_spline+3-first_spline+1) + A2' * iQ * y(first_obs+skips(cur_spline):i-1);\n    end\n\n    % find the interpolation for the last subset of observations\n    s_par = [];\n    if (used_obs < size(N,2))\n        fprintf('WARNING: Regularization is needed observations are less than splines.\\n         Adding 1e-9 on the normal matrix diagonal\\n');\n        R = speye(size(N,2), size(N,2))*1e-9;\n        s_par = (N+R)\\TN;\n    else\n        s_par = N\\TN;\n    end\n    s_weights = [s_weights; s_par];\n\n    for s = first_spline:cur_spline\n        if ((skips(s)<skips(s+1)))\n            y_splined(skips(s)+first_obs:skips(s+1)+first_obs-1) = y_splined(skips(s)+first_obs:skips(s+1)+first_obs-1) + A((skips(s):skips(s+1)-1)+1,:) * s_par(s-first_spline+1:s+3-first_spline+1);\n        end\n    end\n    \n    x_spline = x_spline + x0;\nend\n\n% Regularization + variances\nfunction [y_splined, x_spline, s_weights] = spliner_v51R(x, y, y_var, dxs, reg_factor)\n    nObs = length(x);\n\n    y_var(y_var < reg_factor/2) = reg_factor/2;\n    % size of the intervall to interpolate\n    x_span = x(nObs) - x(1);\n    x0 = x(1);\n    x = x - x0;\n    \n    % compute the number of splines needed for the interpolation\n    n_splines = ceil(x_span/dxs) + 3;\n\n    % compute spline centers\n    x_spline = zeros(n_splines,1);\n    s_weights = [];\n    s_center = x(1) - (((n_splines-3)*dxs-x_span)/2) - dxs;\n    for i = 1:n_splines\n        x_spline(i) = s_center+(i-1)*dxs;\n    end\n\n    % init A matrix\n    A = zeros(nObs, 4);\n    skips = zeros(n_splines,1);\n    N = sparse(n_splines,n_splines);\n    TN = zeros(n_splines, 1);\n\n    cur_spline = 1;          % first spline whose domain intersect the observation\n    tau = 0;                % normalized distance between the observation and the center of the cur_spline\n    i = 1;                  % index of the first observation\n    first_obs = i;          % first observation used in the current A matrix\n    first_spline = 1;       % first spline used in the current A matrix\n    n_skip = 0;              % number of spline to \"skip\" because ain't intersecting an observation\n    used_obs = 0;            % number of observation used in building the N matrix\n    y_splined = zeros(length(y),1);           % output\n    skips(1) = 0;\n    while (i <= nObs)\n        % Compute the distance between the current observation and the current spline\n        tau = round((x(i)-x_spline(cur_spline))/dxs *1e13)/1e13; % 1e13 rounding necessary to avoid numerical problems\n        if (tau <= 2)\n            % fill the design matrix\n            A(i-first_obs+1,:) = cubicSpline([tau (tau-1) (tau-2) (tau-3)]);\n            used_obs = used_obs+1;\n            n_skip = 0;\n            i = i+1;\n        else\n            cur_local_spline = cur_spline-first_spline+1;\n            skips(cur_spline+1) = i-first_obs;\n            % This block of the A matrix is completed\n            % Computing N\n            n_skip = n_skip +1;\n            if (n_skip < 4)\n                if (n_skip == 1)\n                    A2 = A((skips(cur_spline)+1):i-first_obs,:);\n                    iQ = sparse(diag(1./y_var(first_obs + skips(cur_spline):i-1)));\n                    N(cur_local_spline:cur_local_spline+3,cur_local_spline:cur_local_spline+3) =   sparse(N(cur_local_spline:cur_local_spline+3,cur_local_spline:cur_local_spline+3) + A2'*iQ*A2);\n\n                    % Computing TN\n                    TN(cur_local_spline:cur_local_spline+3) = TN(cur_local_spline:cur_local_spline+3) + A2' * iQ * y(first_obs+skips(cur_spline):i-1);\n                end\n                cur_spline = cur_spline +1;\n            else\n                % find the next spline whose domain intersect the next observation\n                tau = (x(i)-x_spline(cur_spline))/dxs;\n                while (tau > 2)\n                    cur_spline = cur_spline+1;\n                    tau = (x(i)-x_spline(cur_spline))/dxs;\n                end\n                skips(cur_spline) = skips(cur_spline-1);\n                used_obs = -1e10;\n            end\n        end\n    end\n\n    skips(cur_spline+1) = i-first_obs;\n    if (n_skip == 0)\n        A2 = A(skips(cur_spline)+1:i-first_obs,:);\n        iQ = sparse(diag(1./y_var(first_obs+skips(cur_spline):i-1)));\n        N(cur_spline-first_spline+1:cur_spline+3-first_spline+1,cur_spline-first_spline+1:cur_spline+3-first_spline+1) = sparse(N(cur_spline-first_spline+1:cur_spline+3-first_spline+1,cur_spline-first_spline+1:cur_spline+3-first_spline+1) + A2'*iQ*A2);\n\n        % Computing TN\n        TN(cur_spline-first_spline+1:cur_spline+3-first_spline+1) = TN(cur_spline-first_spline+1:cur_spline+3-first_spline+1) + A2' * iQ * y(first_obs+skips(cur_spline):i-1);\n    end\n\n    % find the interpolation for the last subset of observations\n    s_par = [];\n    if (size(N,2)>2)\n        if reg_factor == 0\n            fprintf('WARNING: Regularization is needed observations are less than splines.\\n         Adding 1e-9 on the normal matrix diagonal\\n');\n            reg_factor = 1e-9;\n        end\n        R = sparse(eye(size(N,2))-diag(ones(size(N,2)-1,1),1)-diag(ones(size(N,2)-1,1),-1) + diag([0; ones(size(N,2)-2,1); 0]));\n        R = R*reg_factor;\n        s_par = (N+R)\\TN;\n    else\n        if (used_obs < size(N,2))\n            if reg_factor == 0\n                fprintf('WARNING: Regularization is needed observations are less than splines.\\n         Adding 1e-9 on the normal matrix diagonal\\n');\n                reg_factor = 1e-9;\n            end\n            R = sparse(eye(size(N,2))*reg_factor);\n            s_par = (N+R)\\TN;\n        else\n            s_par = N\\TN;\n        end\n    end\n    s_weights = [s_weights; s_par];\n\n    for s = first_spline:cur_spline\n        if ((skips(s)<skips(s+1)))\n            y_splined(skips(s)+first_obs:skips(s+1)+first_obs-1) = y_splined(skips(s)+first_obs:skips(s+1)+first_obs-1) + A((skips(s):skips(s+1)-1)+1,:) * s_par(s-first_spline+1:s+3-first_spline+1);\n        end\n    end\n    \n    x_spline = x_spline + x0;\nend\n\n% No Regularization - no variances\nfunction [y_splined, x_spline, s_weights] = spliner_v5(x, y, dxs)\n    nObs = length(x);\n\n    % size of the intervall to interpolate\n    x_span = x(nObs) - x(1);\n    x0 = x(1);\n    x = x - x0;\n    \n    % compute the number of splines needed for the interpolation\n    n_splines = ceil(x_span/dxs) + 3;\n\n    % compute spline centers\n    x_spline = zeros(n_splines,1);\n    s_center = x(1) - (((n_splines-3)*dxs-x_span)/2) - dxs;\n    for i = 1:n_splines\n        x_spline(i) = s_center+(i-1)*dxs;\n    end\n    \n    % init A matrix\n    A = zeros(nObs, 4);\n    A_idx = zeros(nObs, 4);\n    \n    tau   = round(rem(x',dxs)/dxs*1e13)/1e13;  % 1e13 rounding necessary to avoid numerical problems\n    idx   = floor((x')/dxs)+1; \n    A     = cubicSpline4Col(tau);\n    A_idx = [idx(:) idx(:)+1 idx(:)+2 idx(:)+3];\n    n_par = max(A_idx(:,4));\n    n_obs = numel(x);\n    rows  = repmat((1:n_obs)',1,4);\n    \n    A = sparse(rows, A_idx, A, n_obs, n_par);\n    \n    idx_null = sum(A~=0) == 0;\n    A(:,idx_null) = [];\n    \n    N = A'*A;\n    B = A'*y;\n    \n    x = N\\B;\n    \n    s_weights = nan(numel(idx_null),1);\n    s_weights(~idx_null) = x;\n    y_splined = A*x;\n\n    x_spline = x_spline + x0;\nend\n\n% Regularization - no variances\nfunction [y_splined, x_spline, s_weights] = spliner_v5R(x, y, dxs, reg_factor)\n    nObs = length(x);\n\n    % size of the intervall to interpolate\n    x_span = x(nObs) - x(1);\n    x0 = x(1);\n    x = x - x0;\n    \n    % compute the number of splines needed for the interpolation\n    n_splines = ceil((x_span+eps(x_span))/dxs) + 3;\n\n    % compute spline centers\n    x_spline = zeros(n_splines,1);\n    s_weights = [];\n    s_center = x(1) - (((n_splines-3)*dxs-x_span)/2) - dxs;\n    for i = 1:n_splines\n        x_spline(i) = s_center+(i-1)*dxs;\n    end\n\n    % init A matrix\n    A = zeros(nObs, 4);\n    skips = zeros(n_splines,1);\n    N = sparse(n_splines,n_splines);\n    TN = zeros(n_splines, 1);\n\n    cur_spline = 1;          % first spline whose domain intersect the observation\n    tau = 0;                % normalized distance between the observation and the center of the cur_spline\n    i = 1;                  % index of the first observation\n    first_obs = i;          % first observation used in the current A matrix\n    first_spline = 1;       % first spline used in the current A matrix\n    n_skip = 0;              % number of spline to \"skip\" because ain't intersecting an observation\n    used_obs = 0;            % number of observation used in building the N matrix\n    y_splined = zeros(length(y),1);           % output\n    skips(1) = 0;\n    while (i <= nObs)\n        % Compute the distance between the current observation and the current spline\n        tau = round((x(i) - x_spline(cur_spline))/dxs * 1e13) / 1e13; % 1e13 rounding necessary to avoid numerical problems\n        if (tau <= 2)\n            % fill the design matrix\n            A(i-first_obs+1,:) = cubicSpline([tau (tau-1) (tau-2) (tau-3)]);\n            used_obs = used_obs+1;\n            n_skip = 0;\n            i = i+1;\n        else\n            cur_local_spline = cur_spline-first_spline+1;\n            skips(cur_spline+1) = i-first_obs;\n            % This block of the A matrix is completed\n            % Computing N\n            n_skip = n_skip +1;\n            if (n_skip < 4)\n                if (n_skip == 1)\n                    A2 = A((skips(cur_spline)+1):i-first_obs,:);\n                    N(cur_local_spline:cur_local_spline+3,cur_local_spline:cur_local_spline+3) =   sparse(N(cur_local_spline:cur_local_spline+3,cur_local_spline:cur_local_spline+3) + A2'*A2);\n\n                    % Computing TN\n                    TN(cur_local_spline:cur_local_spline+3) = TN(cur_local_spline:cur_local_spline+3) + A2' * y(first_obs+skips(cur_spline):i-1);\n                end\n                cur_spline = cur_spline +1;\n            else\n                % find the next spline whose domain intersect the next observation\n                tau = (x(i)-x_spline(cur_spline))/dxs;\n                while (tau > 2)\n                    cur_spline = cur_spline+1;\n                    tau = (x(i)-x_spline(cur_spline))/dxs;\n                end\n                skips(cur_spline) = skips(cur_spline-1);\n                used_obs = -1e10;\n            end\n        end\n    end\n\n    skips(cur_spline+1) = i-first_obs;\n    if (n_skip == 0)\n        A2 = A(skips(cur_spline)+1:i-first_obs,:);\n        N(cur_spline-first_spline+1:cur_spline+3-first_spline+1,cur_spline-first_spline+1:cur_spline+3-first_spline+1) = N(cur_spline-first_spline+1:cur_spline+3-first_spline+1,cur_spline-first_spline+1:cur_spline+3-first_spline+1) + A2'*A2;\n\n        % Computing TN\n        TN(cur_spline-first_spline+1:cur_spline+3-first_spline+1) = TN(cur_spline-first_spline+1:cur_spline+3-first_spline+1) + A2' * y(first_obs+skips(cur_spline):i-1);\n    end\n\n    % find the interpolation for the last subset of observations\n    s_par = [];\n    if (size(N,2)>2)\n        %fprintf('WARNING: Regularization is needed observations are less than splines.\\n         Adding 1e-9 on the normal matrix diagonal\\n');\n        R = (speye(size(N,2), size(N,2)) - spdiags(ones(size(N,2), 1), 1, size(N,2), size(N,2)) - spdiags(ones(size(N,2), 1), -1, size(N,2), size(N,2)) + spdiags([0; ones(size(N,2) - 2, 1); 0], 0, size(N,2), size(N,2))) * reg_factor;\n        s_par = (N+R)\\TN;\n    else\n        if (used_obs < size(N,2))\n            %fprintf('WARNING: Regularization is needed observations are less than splines.\\n         Adding 1e-9 on the normal matrix diagonal\\n');\n            R = speye(size(N,2)) * reg_factor;\n            s_par = (N+R)\\TN;\n        else\n            s_par = N\\TN;\n        end\n    end\n    s_weights = [s_weights; s_par];\n\n    for s = first_spline:cur_spline\n        if (skips(s) == 0 && s > 1)\n            skips(s) = skips(s-1);\n        end\n        if ((skips(s)<skips(s+1)))\n            y_splined(skips(s)+first_obs:skips(s+1)+first_obs-1) = y_splined(skips(s)+first_obs:skips(s+1)+first_obs-1) + A((skips(s):skips(s+1)-1)+1,:) * s_par(s-first_spline+1:s+3-first_spline+1);\n        end\n    end\n    \n    x_spline = x_spline + x0;\nend\n\n% SYNTAX:\n%   [y] = cubicSpline(t)\n%\n% EXAMPLE:\n%   [y] = cubicSpline(1)\n%\n% INPUT:\n%   t = normalized value from [-2 to 2] of the distance between the\n%       observation and the center of the cubic spline\n%\n% OUTPUT:\n%   y = value of the spline in the given point\n%\n% DESCRIPTION:\n%   Get the value of the cubic spline with a base of 4 at the given t normalized\n%   value\n%\n% USEFUL VALUES:\n%   2/3 = cubicSpline(0);\n%   1/6 = cubicSpline(-1);\n%   1/6 = cubicSpline(1);\n%\n% by Andrea Gatti\n%\nfunction [y] = cubicSpline(t)\n\n% FAST VECTORIAL IMPLEMENTATION\ny = zeros(size(t));\npos = (t > -2) + (t > -1) - (t > 1) - (t > 2);\n\n% pos = 0    => spline = 0;\n% pos = 1    => spline = (-abs(t)+2)^3/6;\n% pos = 2    => spline = ((-abs(t)+2)^3 - 4*(-abs(t)+1)^3)/6;\n\np1 = pos==1;\np2 = pos==2;\nt = abs(t);\ny(p1) = (2-t(p1)).^3/6;\ny(p2) = ((2-t(p2)).^3 - 4*(1-t(p2)).^3)/6;\n\n%  PLAIN IMPLEMENTATION\n%\n% \tif ((t < -2) || (t > 2))\n% \t\ty = 0;\n%     else\n%         if (t < 0)\n%             if (t <= -1)\n%                 tmp2=(t+2);\n%                 y = (tmp2*tmp2*tmp2 / 6);\n%             else\n%                 tmp1=(t+1);\n%                 tmp2=(t+2);\n%                 y = ((tmp2*tmp2*tmp2 - 4*tmp1*tmp1*tmp1) / 6);\n%             end\n%         else\n%             if (t < 1)\n%                 tmp1=(1-t);\n%                 tmp2=(2-t);\n%                 y = ((tmp2*tmp2*tmp2 - 4*tmp1*tmp1*tmp1) / 6);\n%             else\n%                 tmp2=(2-t);\n%                 y = (tmp2*tmp2*tmp2 / 6);\n%             end\n%         end\n%     end\nend\n\nfunction [val] = cubicSpline4Col(t)\n    % Compute matrix entry for cubic spline\n    %\n    % INPUT\n    %   t -> 0 : 1\n    %   order -> 1,3\n    %\n    % SYNTAX:\n    %  Core_Utils.cubicSplic(t)\n    val = zeros(numel(t),4);\n    val(:,1) = (1 - t).^3/6;\n    val(:,2) = ((2-t).^3 - 4*(1-t).^3)/6;\n    val(:,3) = ((1+t).^3 - 4*(t).^3)/6;\n    val(:,4) = (t).^3/6;\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/flagAndFilters/splinerMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5545928845434153}}
{"text": "%% batman\n% Below is a demonstration of the features of the |batman| function\n\n%% Syntax\n% |[x,y]=batman(n);|\n% |[V]=batman(n);|\n\n%% Description\n% The |batman| function implements a particular version of the so called\n% batmat-equation, a curve defining the batman logo. The input for this\n% function is the number of desired points n. The user may request a sigle\n% nx2 output array or two nx1 arrays (x and y coordinates). \n%\n% This is a MATLAB implementation of the parameterised Batman equation\n% presented by Jerome White (http://www.talljerome.com/ @talljerome,\n% https://youtu.be/oaIsCJw0QG8), in particular the form presented here: \n% https://www.desmos.com/calculator/ajnzwedvql\n% Modification: The batman is scaled to be 2 in width.\n\n%% Examples\n\nclear; close all; clc;\n\n%% Example 1: \n\nn=250; %Number of points on curve\n[x,y]=batman(n); \n\n%%\n\ncFigure; hold on;\nxlabel('x'); ylabel('y'); \nplot([x;x(1)],[y;y(1)],'k.-','LineWidth',3,'MarkerSize',25);\naxis tight; axis equal; \nset(gca,'FontSize',25);\ngrid on; box on; \ngdrawnow; \n\n%% \n%\n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_batman.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5545828545432123}}
{"text": "function [err,time,solver,eqn] = femStokes(node,elem,pde,bdFlag,option,varargin)\n%% FEMSTOKES solve the Stokes equation by various finite element methods\n%\n%   FEMSTOKES computes approximations to the Stokes equation on a\n%   sequence of meshes obtained by uniform refinement of a input mesh.\n% \n% Created by Ming Wang at Nov., 2012.\n%\n% See also femPoisson femrateStokes\n%\n% Copyright (C)  Long Chen. See COPYRIGHT.txt for details.\n\n%% Default setting of mesh and pde data\nif ~exist('node','var') || ~exist('elem','var')\n    [node,elem] = squaremesh([0,1,0,1],0.125);  % default mesh is a square\nend\nif ~exist('option','var'), option = []; end\nif ~exist('pde','var')\n    pde = Stokesdata1;                          % default data\nend\nif ~exist('bdFlag','var')\n    bdFlag = setboundary(node,elem,'Dirichlet'); \nend\n\n%% Parameters\noption = femoption(option);\nmaxIt = option.maxIt;   maxN = option.maxN; L0 = option.L0;\noption = femStokesoption(option);\nelemType = option.elemType; refType = option.refType;\n\n%% Generate an initial mesh \nfor k = 1:L0\n    if strcmp(option.refType,'red')\n        [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n    elseif strcmp(option.refType,'bisect')\n        [node,elem,bdFlag] = uniformbisect(node,elem,bdFlag);\n    end\nend\n\n%% Initialize err\nerruH1 = zeros(maxIt,1); errpL2 = zeros(maxIt,1); \nerrTime = zeros(maxIt,1); solverTime = zeros(maxIt,1); \nassembleTime = zeros(maxIt,1); meshTime = zeros(maxIt,1); \nitStep = zeros(maxIt,1);  stopErr = zeros(maxIt,1); flag = zeros(maxIt,1);\nN = zeros(maxIt,1);\n\n%% Finite Element Method        \nfor k = 1:maxIt\n    % solve the equation\n    switch upper(elemType)\n        case 'P2P1'\n            [u,p,edge,A,eqn,info] = StokesP2P1(node,elem,pde,bdFlag,option);\n        case 'P2P0'\n            [u,p,edge,A,eqn,info] = StokesP2P0(node,elem,pde,bdFlag,option);\n        case 'ISOP2P1'\n            [u,p,edge,A,eqn,info] = StokesisoP2P1(node,elem,pde,bdFlag,option);\n        case 'ISOP2P0'\n            [u,p,edge,A,eqn,info] = StokesisoP2P0(node,elem,pde,bdFlag,option);\n        case 'CRP0'\n            [u,p,edge,A,eqn,info] = StokesCRP0(node,elem,pde,bdFlag,option);\n        case 'CRP1'\n            [u,p,edge,A,eqn,info] = StokesCRP1(node,elem,pde,bdFlag,option);\n        case 'MINI'\n            [u,p,edge,A,eqn,info] = StokesMini(node,elem,pde,bdFlag,option);\n        case 'P1BP1'\n            [u,p,edge,A,eqn,info] = StokesP1bP1(node,elem,pde,bdFlag,option);\n    end    \n    % compute error\n    tic;\n%     if strcmp(elemType,'P1BP1')\n%         uI = Lagrangeinterpolate(pde.exactu,node,elem);\n%     elseif strcmp(elemType(1:2),'CR')\n%         uI = Lagrangeinterpolate(pde.exactu,node,elem,'CR',edge);        \n%     end\n    if strcmp(elemType,'P2P0') || strcmp(elemType,'P2P1') || ...\n       strcmp(elemType,'isoP2P0') || strcmp(elemType,'isoP2P1')\n        uI = pde.exactu([node; (node(edge(:,1),:)+node(edge(:,2),:))/2]);\n    elseif strcmp(elemType,'CRP0') || strcmp(elemType,'CRP1')\n        uI = pde.exactu((node(edge(:,1),:)+node(edge(:,2),:))/2);\n    elseif strcmp(elemType,'Mini')\n        uI = pde.exactu(node);\n    elseif strcmp(elemType,'P1bP1')\n        % bubble part won't be taken in the error computation\n        Nv = size(node,1); NT = size(elem,1);\n        u0 = pde.exactu(node);\n        uI = u;\n        uI([(1:Nv)'; NT+Nv+(1:Nv)']) = u0(:);\n    end\n    erruH1(k) = sqrt((u-uI(:))'*A*(u-uI(:)));\n    errpL2(k) = getL2error(node,elem,pde.exactp,p);\n    errTime(k) = toc;\n    % record time\n    solverTime(k) = info.solverTime;\n    assembleTime(k) = info.assembleTime;\n    if option.printlevel>1\n        fprintf('Time to compute the error %4.2g s \\n H1 err %4.2g    L2err %4.2g \\n',...\n            errTime(k),erruH1(k), errpL2(k));\n    end\n    % record solver information\n    itStep(k) = info.itStep;\n%    stopErr(k) = info.stopErr;\n%    flag(k) = info.flag;\n    % plot\n    N(k) = size(node,1);\n    if option.plotflag && N(k) < 2e3 % show mesh and solution for small size\n        if length(p) == size(elem,1) % piecewise constant function\n            p = recoverP02P1(node,elem,p);\n        end\n        figure(1);  showresult(node,elem,p);\n    end\n    if N(k) > maxN\n        break;\n    end\n    % refine mesh\n    tic;\n    if strcmp(refType,'red')\n        [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n    elseif strcmp(refType,'bisect')\n        [node,elem,bdFlag] = uniformbisect(node,elem,bdFlag);\n    end\n    meshTime(k) = toc;\nend\nh = 1./sqrt(N(1:k));\n\n%% Plot convergence rates\nif option.rateflag\n    figure;\n    set(gcf,'Units','normal'); \n    set(gcf,'Position',[0.25,0.25,0.55,0.4]);\n    subplot(1,2,1)\n    showrateh(h,erruH1(1:k),1,'k-+','|u_I-u_h|_1');\n    subplot(1,2,2)\n    showrateh(h,errpL2(1:k),1,'m-+','||p-p_h||');\nend\n\n%% Output\nerr = struct('N',N,'uH1',erruH1(1:k),'pL2',errpL2(1:k));          \ntime = struct('N',N,'err',errTime(1:k),'solver',solverTime(1:k), ...\n              'assmble',assembleTime(1:k),'mesh',meshTime(1:k));\nsolver = struct('N',N(1:k),'itStep',itStep(1:k),'time',solverTime(1:k),...\n                'stopErr',stopErr(1:k),'flag',flag(1:k));\n            \n%% Display error\nts = zeros(k,6); ts = char(ts);\ndisplay('#nodes     |u_I-u_h|_1      ||p-p_h||  ');\n% format shorte\ndisplay([num2str(err.N) ts num2str(err.uH1,'%0.5e') ts num2str(err.pL2,'%0.5e')]);", "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/femStokes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059560743422, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5545828511236971}}
{"text": "function [inH2O] = kPa2inH2O(kPa)\n% Convert pressure from kilopascals to inches of water.\n% Chad Greene 2012\ninH2O = kPa*4.01463;", "meta": {"author": "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/kPa2inH2O.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5545828495725323}}
{"text": " function R = Robject(kappa, varargin)\n%function R = Robject(kappa, [options])\n%|\n%| Build roughness penalty regularization \"object\" based on C = Cdiff() object,\n%| for regularized solutions to inverse problems.\n%|\n%| General form of nonquadratic penalty function:\n%|\tR(x) = \\sumk w_k \\pot([Cx]_k), where [Cx]_k = \\sum_j c_{kj} x_j.\n%|\t\n%| For quadratic case, \\potk(t) = t^2/2 in which case\n%|\tR(x) = x' C' W C x / 2, where W depends on beta and edge_type.\n%|\n%| Penalty gradient is C' D C x, where D = diag{\\wpot_k([Cx]_k)}.\n%|\n%| in\n%|\tkappa\t[nx,ny[,nz]]\tkappa array, or logical support mask\n%|\n%| options\n%|\tedge_type '?'\t\thow to handle mask edge conditions (see Cdiff)\n%|\t\t'none'\t\tno roughness penalty (NOT DONE)\n%|\t\t'tight'\t\tonly penalize within-mask differences (default)\n%|\t\t'leak'\t\tpenalize between mask and neighbors\n%|\t\t\t\t(its primary use for consistency with ASPIRE)\n%|\t'order', ?\t\t1st-order or 2nd-order differences (see Cdiff)\n%|\t'offsets', [?]\t\toffsets to neighboring pixels\n%|\t\t\t\t\t(see Cdiff for the defaults)\n%|\t\t\t\tuse '3d:26' to penalize all 13 pairs of nbrs\n%|\t\t\t\tuse '0' for C = I (identity matrix)\n%|\t'beta', ?\t\tglobal regularization parameter\n%|\t\t\t\t\tdefault: 2^0\n%|\t'delta', ?\t\tpotential parameter, see potential_func()\n%|\t\t\t\t\tor {delta, param}.  default: inf\n%|\t'potential', '?'\te.g., 'huber', see potential_func()\n%|\t\t\t\tdefault: 'quad' for quadratic regularization.\n%|\t'type_denom', '?'\ttype of \"denominator\"\n%|\t\t\t\t\t(for quadratic surrogates like SPS)\n%|\t\t'matlab'\tdenominator for SPS\n%|\t\t'aspire'\tdenominator for SPS that matches aspire\n%|\t\t'none'\t\tno denominator (default)\n%|\t\t\t\t(because R.E and R.denom needed only for SPS)\n%|\t'distance_power', ?\t1 classical (default), 2 possibly improved\n%|\t\t\t\t\tsee penalty_mex()\n%|\t'user_wt', [?]\t\tUser-provided array of penalty weight values\n%|\t\t\t\t\tsize: [nx,ny[,nz],#offsets]\n%|\t\t\t\tof dimension [size(mask) length(offsets)].\n%|\t\t\t\tThese are .* the usual wt values for edge_type.\n%|\t'mask'\t\t\tOverride default: mask = (kappa ~= 0)\n%|\n%| out\n%|\tR structure has the following \"methods\" \n%|\tR.penal(R, x)\tevaluates R(x)\n%|\tR.cgrad(R, x)\tevaluates \\cgrad R(x) (column gradient)\n%|\tR.denom(R, x)\tevaluates denominator for separable surrogate\n%|\t[pderiv pcurv] = feval(R.dercurv, R, C1*x) derivatives and curvatures\n%|\t\t\tfor non-separable parabola surrogates\n%|\tR.diag(R)\tdiagonal of Hessian of R (at x=0), for preconditioners.\n%|\tR.C1\t\tdifferencing matrix, with entries 1 and -1,\n%|\t\t\talmost always should be used in conjunction with R.wt\n%|\n%| Typical use:\tmask = true([128 128]); % or something more conformal\n%|\t\tR = Robject(mask, 'beta', 2^7);\n%|\n%| Copyright 2004-11-14, Jeff Fessler, University of Michigan\n\nif nargin < 1, ir_usage, end\nif streq(kappa, 'test'), run_mfile_local 'Robject_test', return, end\n\n% option defaults\nR.potential = 'quad';\nR.beta = 2^0;\nR.delta = inf;\nR.edge_type = 'tight';\nR.type_denom = 'none';\nR.distance_power = 1;\nR.order = 1; % 1st-order differences, used in call to Cdiff\nR.user_wt = []; % user-provided wt values\nR.mask = [];\nR.offsets = [];\n\n% parse name/value option pairs\nR = vararg_pair(R, varargin);\n\n% dimensions, and default offsets\nif isempty(R.offsets)\n\tif ndims(kappa) == 2\n\t\t[nx ny] = size(kappa);\n\t\tR.offsets = [1 nx nx+1 nx-1];\n\telseif ndims(kappa) == 3\n\t\t[nx ny nz] = size(kappa);\n\t\tR.offsets = [1 nx nx*ny];\n\telse\n\t\terror 'only 2D and 3D done'\n\tend\nelseif streq(R.offsets, '3d:26') % all 26 neighbors (13 pairs)\n\t[nx ny nz] = size(kappa);\n\tR.offsets = [1 nx+[0 1 -1] nx*ny+col(outer_sum([-1:1],[-1:1]*nx))'];\nend\n\nif ~iscell(R.delta)\n\tR.delta = {R.delta};\nend\n\nR.offsets = int32(R.offsets);\n\nif streq(R.edge_type, 'none')\n\terror 'todo: unpenalized'\nend\n\nif R.beta < 0, warn('Negative beta? This is probably wrong!'), end\n\nR.isquad = streq(R.potential, 'quad');\n\nif isempty(R.mask)\n\tR.mask = kappa ~= 0; % default is to infer from kappas\nend\nif ~islogical(R.mask), error 'mask must be logical', end\n\n%\n% build plain sparse differencing object \"C1\", containing 1 and -1 values\n% (or identity matrix)\n%\nR.C_is_I = any(R.offsets == 0);\nif R.C_is_I\n\tif any(R.offsets), error 'identity is offsets=0', end\n\tR.C1 = diag_sp(ones(sum(R.mask(:)),1)); % identity matrix\n\tR.wt = R.beta;\n\nelse\n\tR.C1 = Cdiff(R.mask, 'offsets', R.offsets, ...\n\t\t\t'edge_type', 'none', 'order', R.order);\n\n\t% wk factors\n\tR.wt_string = sprintf('wk,%s,%d', R.edge_type, R.order);\n\tR.wt = penalty_mex(R.wt_string, single(kappa), R.offsets, R.distance_power);\n\tR.wt = R.beta * single(R.wt(:)); % absorb beta into wk factors\nend\n\n% incorporate user provided wk values\nif ~isempty(R.user_wt)\n\tR.wt = single(R.wt .* R.user_wt(:));\n\tR.user_wt = []; % save memory\nend\n\n% trick: for quadratic case, provide a R.C object where C = sqrt(W) * C1\nif R.isquad\n\tR.C = R.C1;\n\tR.C.cascade_after = diag_sp(sqrt(R.wt));\nend\n\n%\n% desired potential function\n%\nR.pot = potential_func(R.potential, R.delta{:});\n\n%\n% functions\n%\nR.dercurv = @Robject_dercurv;\nR.handle_denom = @Robject_denom;\nR.handle_diag = @Robject_diag;\n% trick: the following form of R.penal allows multiple realizations of x\nR.penal = @(R, x) ... % 2014-04-27 added 'double' to better match new version\n\tsum(repmat(R.wt, ncol(x)) .* R.pot.potk(R.pot, R.C1 * x), 'double');\nR.cgrad = @(R, x) R.C1' * (diag_sp(R.wt) * R.pot.dpot(R.pot, R.C1 * x));\nR.diag = @(R, x) R.handle_diag(R);\nR.denom = @(R, x) R.handle_denom(R, x);\n\n%\n% precompute denominator for separable quadratic case if needed\n%\nif ~streq(R.type_denom, 'none') && R.isquad\n\tif streq(R.type_denom, 'matlab') || streq(R.type_denom, 'aspire')\n\t\tt = R.wt .* R.pot.wpot(R.pot, 0);\n\t\tif R.C_is_I\n\t\t\tR.denom_max0 = t;\n\t\telse\n\t\t\tt = reshape(t, [size(R.mask) length(R.offsets)]);\n\t\t\tif R.order == 1 % fix: order=2 denom?\n\t\t\t\tt = 2 * t; % \"2\" because (1,-1) differences\n\t\t\t\tR.denom_max0 = penalty_mex('diff1,back2', ...\n\t\t\t\t\t\tsingle(t), R.offsets);\n\t\t\telseif R.order == 2 % (-1,2,1) so ?\n\t\t\t\tt = 4 * t; % 4 = |-1| + |2| + |-1|\n\t\t\t\tR.denom_max0 = penalty_mex('diff2,backA', ...\n\t\t\t\t\t\tsingle(t), R.offsets);\n\t\t\telse\n\t\t\t\terror 'order not done for denom'\n\t\t\tend\n\t\t\tR.denom_max0 = single(R.denom_max0(R.mask));\n\t\tend\n\telse\n\t\terror(['Unknown type_denom: ' R.type_denom])\n\tend\nend\n\n\n%\n% Robject_denom()\n% jth penalty separable surrogate curvature is d_j = \\sumk |\\ckj| \\ck \\wpotk\n% where \\ck = \\sumj |\\ckj|.\n% Here, ck = 2 since there is a +1 and a -1 per row of C1 (for 1st-order) \n% Also, |\\ckj| = |\\ckj|^2 since \\ckj = +/- 1, so we can use 'diff1,back2'\n%\nfunction denom = Robject_denom(R, x)\nif streq(R.type_denom, 'none')\n\terror 'denom not initialized'\nend\n\nif R.isquad\n\tdenom = R.denom_max0;\nelse\n\tt = single(R.wt .* R.pot.wpot(R.pot, R.C1 * x));\n\tif R.C_is_I\n\t\tdenom = single(t);\n\telse\n\t\tt = reshape(t, [size(R.mask) length(R.offsets)]);\n\t\tif R.order == 1\n\t\t\tt = 2 * t; % because (1,-1)\n\t\t\tdenom = penalty_mex('diff1,back2', t, R.offsets);\n\t\telseif R.order == 2 % (-1,2,1) so ck = 4\n\t\t\tt = 4 * t; % 4 = |-1| + |2| + |-1|\n\t\t\tdenom = penalty_mex('diff2,backA', ...\n\t\t\t\t\tsingle(t), R.offsets);\n\t\telse\n\t\t\terror 'order not done'\n\t\tend\n\t\tdenom = single(denom(R.mask));\n\tend\nend\n\n\n%\n% evaluate diagonal of Hessian of (quadratic surrogate for) R at x=0\n% \\sum_k w_k |c_kj|^2 \\wpot(0)\n%\nfunction rjj = Robject_diag(R)\nt = single(R.wt .* R.pot.wpot(R.pot, 0));\nt = reshape(t, [size(R.mask) length(R.offsets)]);\nif R.C_is_I\n\terror 'not done, ask jeff'\nelse\n\trjj = penalty_mex('diff1,back2', t, R.offsets);\n\trjj = double(rjj(R.mask));\nend\n\n\n%\n% evaluate \\dpoti and \\wpoti\n%\nfunction [deriv, curv] = Robject_dercurv(R, C1x)\nderiv = R.wt .* R.pot.wpot(R.pot, C1x) .* C1x; \ncurv = R.wt .* R.pot.wpot(R.pot, C1x);\n\n\n%\n% Compute both cgrad and denom (of separable surrogate) efficiently.\n% Unused for now, but could be used if anonymous functions are too inefficient\n% since both R.cgrad and R.denom use C*x so there is redundancy.\n% What we really need is an anonymous function that has two output arguments.\n% No, the feval with a function_handle will suffice!\n%\n%function [cgrad, denom] = Robject_cgrad_denom(R, x)\n%if R.isquad\n%\tcgrad = R.C' * (R.C * x);\n%\tdenom = R.denom;\n%else\n%\tCx = R.C * x;\n%\twx = R.wt .* R.pot.wpot(R.pot, Cx);\n%\tcgrad = R.C' * (wx .* Cx);\n%\tdenom = R.E * wx;\n%end\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/Robject.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5545828477041819}}
{"text": "function [oz] = cm32oz(cm3)\n% Convert volume from cubic centimeters to US liquid ounces. \n% Chad Greene 2012\noz = cm3*0.033814022701;", "meta": {"author": "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/cm32oz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059707450325, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5545828464702024}}
{"text": "%  INTERNAL FUNCTION: computes chebyshev distances\n% \n%  ::\n% \n%    c=chebyshev_distance(y)\n% \n%  Args:\n% \n%     - **y** [numeric] : N x T x G array, with\n% \n%       - **N** [numeric] : number of simulations/replications\n%       - **T** [numeric] : sample length (time series dimension)\n%       - **G** [numeric] : number of variables\n% \n%  Returns:\n%     :\n% \n%     - **c** [N x 1 vector] : chebyshev distances\n% \n%  See also:\n%      - standardized_distance\n%      - multivariate_chebyshev_box\n% \n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/m/+utils/+forecast/+kolsrud/chebyshev_distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5545828427335022}}
{"text": "function [t,x_new,f_new,g_new,funEvals,H] = ArmijoBacktrack(...\n    x,t,d,f,fr,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,funObj,options,varargin)\n% [t,x_new,f_new,g_new,funEvals,H] = ArmijoBacktrack(...\n%    x,t,d,f,fr,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,funObj,varargin)\n%\n% Backtracking linesearch to satisfy Armijo condition\n%\n% Inputs:\n%   x: starting location\n%   t: initial step size\n%   d: descent direction\n%   f: function value at starting location\n%   fr: reference function value (usually funObj(x))\n%   gtd: directional derivative at starting location\n%   c1: sufficient decrease parameter\n%   debug: display debugging information\n%   LS_interp: type of interpolation\n%   progTol: minimum allowable step length\n%   doPlot: do a graphical display of interpolation\n%   funObj: objective function\n%   varargin: parameters of objective function\n%\n% Outputs:\n%   t: step length\n%   f_new: function value at x+t*d\n%   g_new: gradient value at x+t*d\n%   funEvals: number function evaluations performed by line search\n%   H: Hessian at initial guess (only computed if requested)\n%\n% recet change: LS changed to LS_interp and LS_multi\n\n% Evaluate the Objective and Gradient at the Initial Step\nif nargout == 6\n    [f_new,g_new,H] = funObj(x + t*d,varargin{:});\nelse\n  \n  x_struct = vector2struct(x+t*d, options.TEMPLATE);\n  [f_new,g_new_struct] = feval(funObj, x_struct,varargin{:});\n  g_new = struct2vector(g_new_struct);\n  \nend\nfunEvals = 1;\n\nwhile f_new > fr + c1*t*gtd || ~isLegal(f_new)\n    temp = t;\n    \n    if LS_interp == 0 || ~isLegal(f_new)\n        % Ignore value of new point\n        if debug\n            fprintf('Fixed BT\\n');\n        end\n        t = 0.5*t;\n    elseif LS_interp == 1 || ~isLegal(g_new)\n        % Use function value at new point, but not its derivative\n        if funEvals < 2 || LS_multi == 0 || ~isLegal(f_prev)\n            % Backtracking w/ quadratic interpolation based on two points\n            if debug\n                fprintf('Quad BT\\n');\n            end\n            t = polyinterp([0 f gtd; t f_new sqrt(-1)],doPlot,0,t);\n        else\n            % Backtracking w/ cubic interpolation based on three points\n            if debug\n                fprintf('Cubic BT\\n');\n            end\n            t = polyinterp([0 f gtd; t f_new sqrt(-1); t_prev f_prev sqrt(-1)],doPlot,0,t);\n        end\n    else\n        % Use function value and derivative at new point\n        \n        if funEvals < 2 || LS_multi == 0 || ~isLegal(f_prev)\n            % Backtracking w/ cubic interpolation w/ derivative\n            if debug\n                fprintf('Grad-Cubic BT\\n');\n            end\n            t = polyinterp([0 f gtd; t f_new g_new'*d],doPlot,0,t);\n        elseif ~isLegal(g_prev)\n            % Backtracking w/ quartic interpolation 3 points and derivative\n            % of two\n            if debug\n                fprintf('Grad-Quartic BT\\n');\n            end\n            t = polyinterp([0 f gtd; t f_new g_new'*d; t_prev f_prev sqrt(-1)],doPlot,0,t);\n        else\n            % Backtracking w/ quintic interpolation of 3 points and derivative\n            % of two\n            if debug\n                fprintf('Grad-Quintic BT\\n');\n            end\n            t = polyinterp([0 f gtd; t f_new g_new'*d; t_prev f_prev g_prev'*d],doPlot,0,t);\n         end\n    end\n    \n    % Adjust if change in t is too small/large\n    if t < temp*1e-3\n        if debug\n            fprintf('Interpolated Value Too Small, Adjusting\\n');\n        end\n        t = temp*1e-3;\n    elseif t > temp*0.6\n        if debug\n            fprintf('Interpolated Value Too Large, Adjusting\\n');\n        end\n        t = temp*0.6;\n    end\n\n    % Store old point if doing three-point interpolation\n    if LS_multi\n        f_prev = f_new;\n        t_prev = temp;\n        if LS_interp == 2\n            g_prev = g_new;\n        end\n    end\n    \n    if ~saveHessianComp && nargout == 6\n        [f_new,g_new,H] = funObj(x + t*d,varargin{:});\n    else\n      \n      x_struct = vector2struct(x+t*d, options.TEMPLATE);\n      [f_new,g_new_struct] = feval(funObj, x_struct,varargin{:});\n      g_new = struct2vector(g_new_struct);\n  \n%         [f_new,g_new] = funObj(x + t*d,varargin{:});\n    end\n    funEvals = funEvals+1;\n\n    % Check whether step size has become too small\n    if max(abs(t*d)) <= progTol\n        if debug\n            fprintf('Backtracking Line Search Failed\\n');\n        end\n        t = 0;\n        f_new = f;\n        g_new = g;\n        break;\n    end\nend\n\n% Evaluate Hessian at new point\nif nargout == 6 && funEvals > 1 && saveHessianComp\n    \n  [f_new,g_new,H] = funObj(x + t*d,varargin{:});\n  funEvals = funEvals+1;\n    \nend\n\nx_new = x + t*d;\n\nend\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/ArmijoBacktrack.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5545828377628222}}
{"text": "function [Btuph] = hp2Btuph(hp)\n% Convert power from mechanical horsepower to British \n% thermal units per hour. \n% Chad A. Greene 2012\nBtuph = hp*2544.433577644;", "meta": {"author": "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/hp2Btuph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5545828309237919}}
{"text": "% system process model in local s0 frame with dcm formulation, Cs0e is the\n% transformation between the sensor local s0 frame and e-frame\n% written by Huai\n% rqs02e, r s0 in e, q s0 2e, rvqs0, rs in s0, vs in s0, qs0 2s\n% acc, m/s^2, acc by imu in s frame, gyro, rad/s, angular rate by imu\n% w.r.t i frame coordinated in s frame, dt, time interval for covariance update\nfunction [STM Qd]=sys_local_dcm_v000(rqs02e, rvqs0, acc, gyro, dt, imutype, modelNo)\n% the covariance corresponds to states, rs0 in e, q s02e,\n% rs in s0, v s in s0, q s02s, ba, bg, sa, sg, qs2c, Ts in c,\n% for each group frame, qs02si and Tsi in s0, for each\n% point, its inverse depth, here we are only interested up to sa and sg\n% for modelNo=3 and imutype=5, MEMS\n% acc bias drift, random walk\n% gyro bias drift, random walk\n% acc scale factor, random walk\n% gyro scale factor, random walk\n\n% for modelNo=1 and imutype=5 the acc and gyro turn on bias are removed\nR=6317000; % earth average radius\n%system disturbance coefs\nN=zeros(15,6);\nN(13:15,4:6)=eye(3); %attitude\nCs02s=quat2dcm_v000(rvqs0(7:10));\nN(10:12,1:3)=Cs02s'; %velocity\n\n%system matrix\nA=zeros(15);\n% 0s for r s0 in e and q s0 to e\nA(7:9, 10:12)=eye(3); % rs in s0\n%Velocity\nxyz_imu=rqs02e(1:3)+quatrot_v000(rqs02e(4:7),rvqs0(1:3),0);\nunit=xyz_imu/norm(xyz_imu,2);\nLlh=ecef2geo_v000(xyz_imu,0);\n[Rn, Re, g, sL, cL, WIE_E]=geoparam_v000(Llh);\ngeCoeff=-g*R^2/norm(xyz_imu,2)^3*(eye(3)-3*(unit*unit'))-skew([0;0;WIE_E])*skew([0;0;WIE_E]);\nCs02e=quat2dcm_v000(rqs02e(4:7));\nA(10:12,1:3)=Cs02e'*geCoeff;\nA(10:12,7:9)=Cs02e'*geCoeff*Cs02e;\n\nCne=pos2Cne_v000(Llh(1), Llh(2));\nge=Cne(:,3)*g-[xyz_imu(1:2);0]*WIE_E^2; % gravitation in e frame\nA(10:12,4:6)=Cs02e'*(-skew(ge)+geCoeff*skew(quatrot_v000(rqs02e(4:7),rvqs0(1:3),0))+...\n    skew(skew([0;0;WIE_E])*skew([0;0;WIE_E])*xyz_imu)-2*skew(quatrot_v000(rqs02e(4:7),rvqs0(4:6),0))*skew([0;0;WIE_E]));\n\nA(10:12, 10:12)=-2*skew(quatrot_v000(rqs02e(4:7),[0;0;WIE_E], 1));\nA(10:12, 13:15)=-Cs02s'*skew(acc);\n%Attitude\nA(13:15,4:6)=Cs02s*Cs02e'*skew([0;0;WIE_E]);\nA(13:15,13:15)=skew(-gyro);\nAnav=A;\nNnav=N;\n% X(k+1) = ffun[X(k),U(k),V(k)]\n% X(k+1) = Ak*X(k)+Gk*Vk\n\n%%%%Imu error model parameters\n[Aimu_d, Qimu_d, Cimu, Rimu]=imu_err_model_v001(acc, gyro, dt, imutype, modelNo);\n\n%%%%Combine and discretize nav and imu models\n% this discretization can also be accomplished by Loan's matrix exponential\n% method, see sys_metric_phipsi_v000.m\nnavStates=15;\nAnav_d=eye(navStates)+dt*Anav;  %Use 1st order taylor series to discretize Anav\nQnav=Nnav*Rimu*Nnav';\nQnav_d=dt/2*(Anav_d*Qnav+Qnav*Anav_d');      %Use trapezoidal rule to discretize Rimu\n\nSTM=zeros(navStates+size(Aimu_d,1));\nSTM(1:navStates,1:navStates)=Anav_d;\nSTM(1:navStates,1+navStates:end)=Nnav*Cimu*dt;\nSTM(1+navStates:end,1+navStates:end)=Aimu_d;\n\nQd=zeros(navStates+size(Aimu_d,1));\nQd(1:navStates,1:navStates)=Qnav_d;\nQd(1+navStates:end,1+navStates:end)=Qimu_d;\nQd(1:navStates,1+navStates:end)=Nnav*Cimu*Qimu_d*dt/2;\nQd(1+navStates:end,1:navStates)=Qd(1:navStates,1+navStates:end)';\nend", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/propagation/sys_local_dcm_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5545828202701119}}
{"text": "%Simple function to test the cross method\nd=10;\n%elem_fun=@(x) sum(x); %Just sum of everything \np=0:d-1; p = 2.^p; \na=-5;b=5;\nn=2^d;\nh=(b-a)/(n-1);\n%mv=@(x) x.^3;\nmv=@(x) sqrt(x)+abs(x);\n%elem_fun=@(x) 1.0./(dot((x-1),p)+1e-3); %Just sum of everything \n%elem_fun=@(x) mv(1e-12+dot(x-1,p)*h);\n\n%Compare functions of TT-tensors\nx=tt_x(d,2); x=tt_tensor(x); \ne=tt_ones(d,2);e=tt_tensor(e);\nx=a*e+h*x; x=round(x,1e-13);\nx1=kron(e,x); x2=kron(x,e);\nrs=x1.^2+x2.^2; rs=round(rs,1e-13);\n%fun=@(x) 1.0./sqrt(x);\n%fun=@(x) 1.0./x;\nfun=@(x) exp(-x.^4);\n%fun = @(x) x.^2;\nrs=x;\n%elem_fun = @(ind) fun(rs(ind));\n%elem_fun=@(ind) rs(ind);\n%elem_fun=@(x) sqrt(x(1))+x(2);\nelem_fun = @(ind) fun(rs(ind));\neps=1e-6;\nD=ndims(rs);\n%y=tt_rc2(2*d,2,elem_fun,1e-12);\ny=tt_rc(D,2,elem_fun,1e-6,'nswp',40);\n%v=tt_rand(size(y),ndims(y),2);\n%y=y+v; y=round(y,1e-12);\n%y1=tt_rc(D,2,elem_fun,1e-8,'nswp',40,'x0',y);\n\nz=funcrs2(rs,fun,1e-6,rs,20);\nz=round(z,1e-12);\nz1=tt_rc(D,2,elem_fun,1e-8,'nswp',40,'x0',z);\n\n\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/tests/ancient/test_cross.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.5545152773633979}}
{"text": "function []=TVESLMdisp(beta_median,beta_std,beta_lbound,beta_ubound,sigma_median,sigma_t_median,sigma_t_lbound,sigma_t_ubound,X,Y,n,m,p,k,T,bex,ar,lambda1,lambda2,lambda3,lambda4,lambda5,gamma,IRFt,const,endo,exo,startdate,enddate,stringdates1,decimaldates1,pref, Ylevel, Psi_median, Psi_lbound, Psi_ubound, sizetraining,PriorExcel)\n\n\n\n\n\n\n\n\n\n\n% before displaying and saving the results, start estimating the evaluation measures for the model\n\n\n% obtain first a point estimate betatilde of the VAR coefficients\n% this is simply the median\nbetatilde=beta_median;\nBtilde=reshape(betatilde,k,n);\n% use this estimate to produce predicted values for the model, following (a.8.2)\nYtilde=X*Btilde;\n% then produce the corresponding residuals, using (a.8.3)\nEPStilde=Y-Ytilde;\n\n\n% check first whether the model is stationary, using (a.7.2)\n[stationary eigmodulus]=bear.checkstable(betatilde,n,p,k);\n\n\n% Compute then the sum of squared residuals\n% compute first the RSS matrix, defined in (a.8.4)\nRSS=EPStilde'*EPStilde;\n% retain only the diagonal elements to get the vector of RSSi values\nrss=diag(RSS);\n\n\n% Go on calculating R2\n% generate Mbar\nMbar=eye(T)-ones(T,T)/T;\n% then compute the TSS matrix, defined in (a.8.7)\nTSS=Y'*Mbar*Y;\n% generate the R2 matrix in (a.8.8)\nR2=eye(n)-RSS./TSS;\n% retain only the diagonal elements to get the vector of R2 values\nr2=diag(R2);\n\n\n% then calculate the adjusted R2, using (a.8.9)\nR2bar=eye(n)-((T-1)/(T-k))*(eye(n)-R2);\n% retain only the diagonal elements to get the vector of R2bar values\nr2bar=diag(R2bar);\n\n\n\n\n\n\n\n% now start displaying and saving the results\n\n\n% preliminary task: create and open the txt file used to save the results\n\nfilelocation=fullfile(pref.results_path, [pref.results_sub '.txt']);\nfid=fopen(filelocation,'wt');\n\n% print toolbox header\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\nfprintf('%s\\n','%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%');\nfprintf(fid,'%s\\n','%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%');\nfprintf('%s\\n','%                                                                                                       %%');\nfprintf(fid,'%s\\n','%                                                                                                    %');\nfprintf('%s\\n','%    BAYESIAN ESTIMATION, ANALYSIS AND REGRESSION (BEAR) TOOLBOX                                         %');\nfprintf(fid,'%s\\n','%    BAYESIAN ESTIMATION, ANALYSIS AND REGRESSION (BEAR) TOOLBOX                                     %');\nfprintf('%s\\n','%                                                                                                        %');\nfprintf(fid,'%s\\n','%                                                                                                    %');\nfprintf('%s\\n','%    This statistical package has been developed by the external developments division of the ECB.       %');\nfprintf(fid,'%s\\n','%    This statistical package has been developed by the external developments division of the ECB.   %');\nfprintf('%s\\n','%                                                                                                        %');\nfprintf(fid,'%s\\n','%                                                                                                    %');\nfprintf('%s\\n','%    Authors:                                                                                            %');\nfprintf(fid,'%s\\n','%    Authors:                                                                                        %');\nfprintf('%s\\n','%    Romain Legrand  (Romain Legrand <b00148883@essec.edu>)                                              %');\nfprintf(fid,'%s\\n','%    Romain Legrand  (Romain Legrand <b00148883@essec.edu>)                                          %');\nfprintf('%s\\n','%    Alistair Dieppe (adieppe@worldbank.org)                                                             %');\nfprintf(fid,'%s\\n','%    Alistair Dieppe (adieppe@worldbank.org)                                                         %');\nfprintf('%s\\n','%    Bj\u00f6rn van Roye  (Bjorn.van_Roye@ecb.europa.eu)                                                      %');\nfprintf(fid,'%s\\n','%    Bj\u00f6rn van Roye  (Bjorn.van_Roye@ecb.europa.eu)                                                  %');\nfprintf('%s\\n','%                                                                                                        %');\nfprintf(fid,'%s\\n','%                                                                                                    %');\nfprintf('%s\\n','%    Version 5,0                                                                                        %');\nfprintf(fid,'%s\\n','%    Version 5.0                                                                                   %');\nfprintf('%s\\n','%                                                                                                        %');\nfprintf(fid,'%s\\n','%                                                                                                    %');\nfprintf('%s\\n','%    The authors are grateful to Paolo Bonomolo, Marta Banbura, Martin Bruns, Fabio Canova,              %');\nfprintf(fid,'%s\\n','%    The authors are grateful to Paolo Bonomolo, Marta Banbura, Martin Bruns, Fabio Canova,          %');\nfprintf('%s\\n','%    Matteo Ciccarelli, Marek Jarocinski, Niccolo Battistini, Gabriel Bobeica                            %');\nfprintf(fid,'%s\\n','%    Matteo Ciccarelli, Marek Jarocinski, Niccolo Battistini, Gabriel Bobeica                        %');\nfprintf('%s\\n','%    Michele Lenza, Chiara Osbat, Mirela Miescu, Gary Koop, Giorgio Primiceri                            %');\nfprintf(fid,'%s\\n','%    Michele Lenza, Chiara Osbat, Mirela Miescu, Gary Koop, Giorgio Primiceri,                       %');\nfprintf('%s\\n','%    Michal Rubaszek, Barbara Rossi, Ben Schumann, Peter Welz, Hugo Vega de la Cruz and Francesca Loria. %');\nfprintf(fid,'%s\\n','%  Michal Rubaszek, Barbara Rossi, Ben Schumann, Peter Welz, Hugo Vega de la Cruz and Francesca Loria%');\nfprintf('%s\\n','%    valuable input and advice which contributed to improve the quality of this work.                    %');\nfprintf(fid,'%s\\n','%  valuable input and advice which contributed to improve the quality of this work.                  %');\nfprintf('%s\\n','%                                                                                                        %');\nfprintf(fid,'%s\\n','%                                                                                                    %');\nfprintf('%s\\n','%   These programmes are the responsibilities of the authors and not of the ECB and the Worldbank.       %'); \nfprintf(fid,'%s\\n','%   These programmes are the responsibilities of the authors and not of the ECB and the Worldbank.   %'); \nfprintf('%s\\n','%   Errors and ommissions remain those of the authors.                                                   %'); \nfprintf(fid,'%s\\n','%   Errors and ommissions remain those of the authors.                                               %');\nfprintf('%s\\n','%                                                                                                        %');\nfprintf(fid,'%s\\n','%                                                                                                    %');\nfprintf('%s\\n','%    Please do not use or quote this work without permission.                                            %');\nfprintf(fid,'%s\\n','%    Please do not use or quote this work without permission.                                        %');\nfprintf('%s\\n','%                                                                                                        %');\nfprintf(fid,'%s\\n','%                                                                                                    %');    \nfprintf('%s\\n','%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%');\nfprintf(fid,'%s\\n','%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%');\n% print then estimation results\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\ntoolboxinfo='BEAR toolbox estimates';\nfprintf('%s\\n',toolboxinfo);\nfprintf(fid,'%s\\n',toolboxinfo);\n\ntime=clock;\ndatestring=datestr(time);\ndateinfo=['Date: ' datestring(1,1:11) '   Time: ' datestring(1,13:17)];\nfprintf('%s\\n',dateinfo);\nfprintf(fid,'%s\\n',dateinfo);\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\nVARtypeinfo='Stochastic volatility BVAR';\nfprintf('%s\\n',VARtypeinfo);\nfprintf(fid,'%s\\n',VARtypeinfo);\n\n\n\nmodelinfo='Survey Local Mean Stochastic Volatility VAR';\nfprintf('%s\\n',modelinfo);\nfprintf(fid,'%s\\n',modelinfo);\n\n\nif IRFt==1\nSVARinfo='structural decomposition: none'; \nelseif IRFt==2\nSVARinfo='structural decomposition: choleski factorisation'; \nelseif IRFt==3\nSVARinfo='structural decomposition: triangular factorisation'; \nelseif IRFt==4\nSVARinfo='structural decomposition: sign restrictions'; \nend\nfprintf('%s\\n',SVARinfo);\nfprintf(fid,'%s\\n',SVARinfo);\n\ntemp='endogenous variables: ';\nfor ii=1:n\ntemp=[temp ' ' endo{ii,1} ' '];\nend\nendoinfo=temp;\nfprintf('%s\\n',endoinfo);\nfprintf(fid,'%s\\n',endoinfo);\n\ntemp='exogenous variables: ';\nif const==0 && m==0\ntemp=[temp ' none'];\nelseif const==1 && m==1\ntemp=[temp ' constant '];\nelseif const==0 && m>0\n   for ii=1:m-1\n   temp=[temp ' ' exo{ii,1} ' '];\n   end\nelseif const==1 && m>1\ntemp=[temp ' constant '];\n   for ii=1:m-1\n   temp=[temp ' ' exo{ii,1} ' '];\n   end\nend\nexoinfo=temp;\nfprintf('%s\\n',exoinfo);\nfprintf(fid,'%s\\n',exoinfo);\n\nsampledateinfo=['estimation sample: ' startdate '-' enddate];\nfprintf('%s\\n',sampledateinfo);\nfprintf(fid,'%s\\n',sampledateinfo);\n\nsamplelengthinfo=['Size of the Trainingsample: ' num2str(sizetraining)];\nfprintf('%s\\n',samplelengthinfo);\nfprintf(fid,'%s\\n',samplelengthinfo);\n\nsamplelengthinfo=['sample size (omitting initial conditions and Trainingsample): ' num2str(T)];\nfprintf('%s\\n',samplelengthinfo);\nfprintf(fid,'%s\\n',samplelengthinfo);\n\nlaginfo=['number of lags included in regression: ' num2str(p)];\nfprintf('%s\\n',laginfo);\nfprintf(fid,'%s\\n',laginfo);\n\nif PriorExcel==1\n    arprint=[];\n    for ii=1:n\n        arprint=[arprint num2str(ar(ii,1)) '  '];\n    end\n hyperparam2=['autoregressive coefficients (ar):                ' arprint];\nelse\n hyperparam2=['autoregressive coefficients (ar):                ' num2str(ar(1,1))];\nend\nfprintf('%s\\n',hyperparam2);\nfprintf(fid,'%s\\n',hyperparam2);\n\nhyperparam3=['overall tightness (lambda1):                    ' num2str(lambda1)];\nfprintf('%s\\n',hyperparam3);\nfprintf(fid,'%s\\n',hyperparam3);\n\n\nhyperparam4=['cross-variable weighting (lambda2):             ' num2str(lambda2)];\nfprintf('%s\\n',hyperparam4);\nfprintf(fid,'%s\\n',hyperparam4);\n\nhyperparam5=['lag decay (lambda3):                            ' num2str(lambda3)];\nfprintf('%s\\n',hyperparam5);\nfprintf(fid,'%s\\n',hyperparam5);\n\n%hyperparam6=['exogenous variable tightness (lambda4):         ' num2str(lambda4)];\n%fprintf('%s\\n',hyperparam6);\n%fprintf(fid,'%s\\n',hyperparam6);\n\nif bex==1\nhyperparam7=['block exogeneity shrinkage (lambda5):           ' num2str(lambda5)];\nfprintf('%s\\n',hyperparam7);\nfprintf(fid,'%s\\n',hyperparam7);\nend\n\nhyperparam8=['AR coefficient of stochastic volatiltiy of VAR residuals(gamma):    ' num2str(gamma)];\nfprintf('%s\\n',hyperparam8);\nfprintf(fid,'%s\\n',hyperparam8);\n\n\n% display coefficient estimates\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\ncoeffinfo=['VAR coefficients (beta): posterior estimates'];\nfprintf('%s\\n',coeffinfo);\nfprintf(fid,'%s\\n',coeffinfo);\n\n\nfor ii=1:n\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nif ii~=1\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nend\n\n\nendoinfo=['Endogenous: ' endo{ii,1}];\nfprintf('%s\\n',endoinfo);\nfprintf(fid,'%s\\n',endoinfo);\n\n\ncoeffheader=fprintf('%25s %15s %15s %15s %15s\\n','','Median','St.dev','Low.bound','Upp.bound');\ncoeffheader=fprintf(fid,'%25s %15s %15s %15s %15s\\n','','Median','St.dev','Low.bound','Upp.bound');\n\n\n% handle the endogenous\n   for jj=1:n\n      for kk=1:p\n      values=[beta_median((ii-1)*k+n*(kk-1)+jj,1) beta_std((ii-1)*k+n*(kk-1)+jj,1) beta_lbound((ii-1)*k+n*(kk-1)+jj,1) beta_ubound((ii-1)*k+n*(kk-1)+jj,1)];\n      fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n',strcat(endo{jj,1},'(-',int2str(kk),')'),values);\n      fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n',strcat(endo{jj,1},'(-',int2str(kk),')'),values);\n      end\n   end\n\n\n% handle the exogenous\n   % if there is no constant:\n   if const==0\n      % if there is no exogenous at all, obvioulsy, don't display anything\n      if m==0\n      % if there is no constant but some other exogenous, display them\n      else\n         for jj=1:m\n         values=[beta_median(ii*k-m+jj,1) beta_std(ii*k-m+jj,1) beta_lbound(ii*k-m+jj,1) beta_ubound(ii*k-m+jj,1)];\n         fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n         fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n         end\n      end\n   % if there is a constant\n   else\n   % display the results related to the constant\n         values=[beta_median(ii*k-m+1,1) beta_std(ii*k-m+1,1) beta_lbound(ii*k-m+1,1) beta_ubound(ii*k-m+1,1)];\n         fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n','Constant',values);\n         fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n','Constant',values);\n      % if there is no other exogenous, stop here\n      if m==1\n      % if there are other exogenous, display their results\n      else\n         for jj=1:m-1\n         values=[beta_median(ii*k-m+jj+1,1) beta_std(ii*k-m+jj+1,1) beta_lbound(ii*k-m+jj+1,1) beta_ubound(ii*k-m+jj+1,1)];\n         fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n         fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n         end\n      end\n   end\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\n% display evaluation measures\nrssinfo=['Sum of squared residuals: ' num2str(rss(ii,1),'%.2f')];\nfprintf('%s\\n',rssinfo);\nfprintf(fid,'%s\\n',rssinfo);\n\n\nr2info=['R-squared: ' num2str(r2(ii,1),'%.3f')];\nfprintf('%s\\n',r2info);\nfprintf(fid,'%s\\n',r2info);\n\n\nadjr2info=['adj. R-squared: ' num2str(r2bar(ii,1),'%.3f')];\nfprintf('%s\\n',adjr2info);\nfprintf(fid,'%s\\n',adjr2info);\n\n\nend\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\n\n% display VAR stability results\neigmodulus=reshape(eigmodulus,p,n);\nstabilityinfo1=['Roots of the characteristic polynomial (modulus):'];\nfprintf('%s\\n',stabilityinfo1);\nfprintf(fid,'%s\\n',stabilityinfo1);\nfor ii=1:p\ntemp=num2str(eigmodulus(ii,1),'%.3f');\n   for jj=2:n\n   temp=[temp,'  ',num2str(eigmodulus(ii,jj),'%.3f')];\n   end\nfprintf('%s\\n',temp);\nfprintf(fid,'%s\\n',temp);\nend\nif stationary==1;\nstabilityinfo2=['No root lies outside the unit circle.'];\nstabilityinfo3=['The estimated VAR model satisfies the stability condition'];\nfprintf('%s\\n',stabilityinfo2);\nfprintf(fid,'%s\\n',stabilityinfo2);\nfprintf('%s\\n',stabilityinfo3);\nfprintf(fid,'%s\\n',stabilityinfo3);\nelse\nstabilityinfo2=['Warning: at leat one root lies on or outside the unit circle.'];\nstabilityinfo3=['The estimated VAR model will not be stable'];\nfprintf('%s\\n',stabilityinfo2);\nfprintf(fid,'%s\\n',stabilityinfo2);\nfprintf('%s\\n',stabilityinfo3);\nfprintf(fid,'%s\\n',stabilityinfo3);\nend\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\n% display posterior for sigma\nsigmainfo1=['sigma (residual covariance matrix): posterior estimates'];\nfprintf('%s\\n',sigmainfo1);\nfprintf(fid,'%s\\n',sigmainfo1);\n% calculate the (integer) length of the largest number in sigma, for formatting purpose\nwidth=length(sprintf('%d',floor(max(abs(bear.vec(sigma_median))))));\n% add a separator, a potential minus sign, and three digits (total=5) to obtain the total space for each entry in the matrix\nwidth=width+5;\nfor ii=1:n\ntemp=[];\n   for jj=1:n\n   % convert matrix entry into string\n   number=num2str(sigma_median(ii,jj),'% .3f');\n      % pad potential missing blanks\n      while numel(number)<width\n      number=[' ' number];\n      end\n   number=[number '  '];\n   temp=[temp number];\n   end\nfprintf('%s\\n',temp);\nfprintf(fid,'%s\\n',temp);\nend\n% notice about use of long-run values\nsigmainfo2=['Note: Last period observation variance covariance matrix'];\nsigmainfo3=['Note: The last period observation variance covariance matrix will also be used for identification.'];\n%sigmainfo4=['Note: The historical decomposition and structural shocks are dependend on this choice.'];\n\nfprintf('%s\\n',sigmainfo2);\nfprintf(fid,'%s\\n',sigmainfo2);\nfprintf('%s\\n',sigmainfo3);\nfprintf(fid,'%s\\n',sigmainfo3);\n%fprintf('%s\\n',sigmainfo4);\n%fprintf(fid,'%s\\n',sigmainfo4);\nfclose(fid);\n\n\n\n\n% Finally, display the results in terms of graph\nif pref.plot\n% plot actual vs. fitted\nactualfitted=figure('Tag','BEARresults');\nset(actualfitted,'Color',[0.9 0.9 0.9]);\nset(actualfitted,'name','model estimation: actual vs fitted')\nncolumns=ceil(n^0.5);\nnrows=ceil(n/ncolumns);\nfor ii=1:n\nsubplot(nrows,ncolumns,ii)\nhold on\nplot(decimaldates1,Y(:,ii),'Color',[0 0 0],'LineWidth',2);\nplot(decimaldates1,Ytilde(:,ii),'Color',[1 0 0],'LineWidth',2);\nhold off\nset(gca,'XLim',[decimaldates1(1,1) decimaldates1(end,1)],'FontName','Times New Roman');\ntitle(endo{ii,1},'FontName','Times New Roman','FontSize',10,'FontWeight','normal');\n   if ii==1\n   plotlegend=legend('actual','fitted');\n   set(plotlegend,'FontName','Times New Roman');\n   end\nend\n\n\n% plot the residuals\nresiduals=figure('Tag','BEARresults');\nset(residuals,'Color',[0.9 0.9 0.9]);\nset(residuals,'name','model estimation: residuals')\nfor ii=1:n\nsubplot(nrows,ncolumns,ii)\nplot(decimaldates1,EPStilde(:,ii),'Color',[0 0 0],'LineWidth',2)\nset(gca,'XLim',[decimaldates1(1,1) decimaldates1(end,1)],'FontName','Times New Roman');\ntitle(endo{ii,1},'FontName','Times New Roman','FontSize',10,'FontWeight','normal');\nend\n\n\n% plot first the time-varying variance and covariance estimates\nvarcov=figure('Tag','BEARresults');\nset(varcov,'Color',[0.9 0.9 0.9]);\nset(varcov,'name','model estimation: residual variance and covariance')\nfor ii=1:n\n   for jj=1:ii\n   subplot(n,n,n*(ii-1)+jj)\n   hold on\n   Xpatch=[decimaldates1' fliplr(decimaldates1')];\n   Ypatch=[sigma_t_lbound{ii,jj}(p+1:end,1)' fliplr(sigma_t_ubound{ii,jj}(p+1:end,1)')];\n   HDpatch=patch(Xpatch,Ypatch,[0.7 0.78 1]);\n   set(HDpatch,'facealpha',0.6);\n   set(HDpatch,'edgecolor','none');\n   plot(decimaldates1,sigma_t_median{ii,jj}(p+1:end,1),'Color',[0.4 0.4 1],'LineWidth',2);\n   plot([decimaldates1(1,1),decimaldates1(end,1)],[0 0],'k--');\n   hold off\n   set(gca,'XLim',[decimaldates1(1,1) decimaldates1(end,1)],'FontName','Times New Roman');\n      % top labels\n      if jj==ii\n      title(['var(' endo{ii,1} ')'],'FontWeight','normal');\n      else\n      title(['cov(' endo{jj,1} ',' endo{ii,1} ')'],'FontWeight','normal');\n      end\n   end   \nend\n\n\n\nend % pref.plot\n\n% finally, save the results on excel\n\n% compute the cell for actual and fitted\n% create the cell that will be saved on excel\nafcell={};\n% build preliminary elements: space between the tables\nvertspace=repmat({''},T+3,1);\n% loop over variables (horizontal dimension)\nfor ii=1:n\n% create cell of actual/fitted for variable ii\ntemp=['actual and fitted: ' endo{ii,1}];\naf_i=[temp {''} {''};{''} {''} {''};{''} {'sample'} {'fitted'};stringdates1 num2cell(Y(:,ii)) num2cell(Ytilde(:,ii))];\nafcell=[afcell af_i vertspace];\nend\n% trim\nafcell=afcell(:,1:end-1);\n% write in excel\nif pref.results==1\n    bear.xlswritegeneral(fullfile(pref.results_path, [pref.results_sub '.xlsx']),afcell,'actual fitted','B2');\nend\n\n% then compute the cell for the residuals\n% create the cell that will be saved on excel\nhorzspace=repmat({''},1,n);\nrescell=[{'residuals'} horzspace;{''} horzspace;{''} endo';stringdates1 num2cell(EPStilde)];\n% write in excel\nif pref.results==1\n    bear.xlswritegeneral(fullfile(pref.results_path, [pref.results_sub '.xlsx']),rescell,'resids','B2');\nend\n\n% finally compute the cell for the time varying variance and covariance\n% create the cell that will be saved on excel\nvarcovcell={};\n% build preliminary elements: space between the tables\nhorzspace=repmat({''},2,5*n);\nvertspace=repmat({''},T+3,1);\n% loop over variables (vertical dimension)\nfor ii=1:n\ntempcell={};\n   % loop over shocks (horizontal dimension)\n   for jj=1:ii\n   % create cell of hd record for the contribution of shock jj in variable ii fluctuation\n      % if a sign restriction identification scheme has been used, use the structural shock labels\n      if jj==ii\n      temp=['variance of ' endo{ii,1} ' residuals'];\n      % otherwise, the shocks are just orthogonalised shocks from the variables: use variable names\n      else\n      temp=['covariance between ' endo{jj,1} ' and ' endo{ii,1} 'residuals'];\n      end\n   vc_ij=[temp {''} {''} {''};{''} {''} {''} {''};{''} {'lw. bound'} {'median'} {'up. bound'};stringdates1 num2cell(sigma_t_lbound{ii,jj}(p+1:end,:)) num2cell(sigma_t_median{ii,jj}(p+1:end,:)) num2cell(sigma_t_ubound{ii,jj}(p+1:end,:))];\n   tempcell=[tempcell vc_ij vertspace];\n   end\n   % complete with blanks (for repeated covariance values)\n   for jj=1:n-ii\n   tempcell=[tempcell cell(T+3,5)]; \n   end\nvarcovcell=[varcovcell;horzspace;tempcell];\nend\n% trim\nvarcovcell=varcovcell(3:end,1:end-1);\n% write in excel\nif pref.results==1\n    bear.xlswritegeneral(fullfile(pref.results_path, [pref.results_sub '.xlsx']),varcovcell,'time variation','B2');\nend\n%trend and cycle decomposition\n%plot\n% Finally, display the results in terms of graph\nif pref.plot\n% plot actual vs. fitted\ntrendcycle=figure('Tag','BEARresults');\nset(trendcycle,'Color',[0.9 0.9 0.9]);\nset(trendcycle,'name','Local mean (trend) and actual data')\nncolumns=ceil(n^0.5);\nnrows=ceil(n/ncolumns);\nfor ii=1:n\nsubplot(nrows,ncolumns,ii)\nhold on\nXpatch=[decimaldates1' fliplr(decimaldates1')];\nYpatch=[Psi_lbound(p+1:end,ii)' fliplr(Psi_ubound(p+1:end,ii)')];\nHDpatch=patch(Xpatch,Ypatch,[0.7 0.78 1]);\nset(HDpatch,'facealpha',0.6);\nset(HDpatch,'edgecolor','none');\nplot(decimaldates1,Psi_median(p+1:end,ii),'Color',[1 0 0],'LineWidth',2);\nplot(decimaldates1,Ylevel(p+1:end,ii),'Color',[0 0 0],'LineWidth',2);\nhold off\nset(gca,'XLim',[decimaldates1(1,1) decimaldates1(end,1)],'FontName','Times New Roman');\ntitle(endo{ii,1},'FontName','Times New Roman','FontSize',10,'FontWeight','normal');\n   if ii==1\n   plotlegend=legend('Credible Bands Local Mean', 'Median Estimate Local Mean (Trend component)','Actual Data');\n   set(plotlegend,'FontName','Times New Roman');\n   % user defined position (ex : right bottom)\n   set(plotlegend,'Position',[0.7443    0.1782    0.1518    0.1286])\n   % automatic\n   %set(plotlegend,'Location','best')\n   end\nend\n\n%finally record the local mean estimates in excel\n\n% compute the cell for actual and fitted\n% create the cell that will be saved on excel\ntrendcell={};\n% build preliminary elements: space between the tables\nvertspace=repmat({''},T+3,1);\n% loop over variables (horizontal dimension)\nfor ii=1:n\n% create cell of actual/fitted for variable ii\ntemp=['Local mean estimates: ' endo{ii,1}];\ntrendcell_i=[temp {''} {''} {''};{''} {''} {''} {''};{'dates'} {'upper bound'} {'median'} {'lower bound'};stringdates1 num2cell(Psi_ubound(p+1:end,ii)) num2cell(Psi_median(p+1:end,ii)) num2cell(Psi_lbound(p+1:end,ii))];\ntrendcell=[trendcell trendcell_i vertspace];\nend\n% trim\ntrendcell=trendcell(:,1:end-1);\n% write in excel\nif pref.results==1\n    bear.xlswritegeneral(fullfile(pref.results_path, [pref.results_sub '.xlsx']),trendcell,'Local Mean Estimates','B2');\nend\n\nend \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/TVESLMdisp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314707995588, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.554515275981866}}
{"text": "%% manage paths\n\npath_dict = manage_paths();\n\npath2module = path_dict(1);\npath2matlabcode_folder = path_dict(2);\npath2input = path_dict(3);\npath2output = path_dict(4);\n\n%%\n%Handover \"mode\", \"another_map\", \"raceline_percentage_mode\" & \"raceline_percent_value\" from Workspace\nmode=evalin('base', 'mode');\nanother_map=evalin('base', 'another_map');\ncenterline_mode=evalin('base', 'centerline_mode');\nraceline_percentage_mode=evalin('base', 'raceline_percentage_mode');\nif raceline_percentage_mode==1\n    raceline_percent_value=evalin('base', 'raceline_percent_value');\nend\n%Import Track file\nif centerline_mode==1\n    name=evalin('base','name');\n    res_centerline_mode=evalin('base','resolution');\n    track=importdata(strcat(path2output,'\\tracks\\Track_',name,'_',strrep((num2str(res_centerline_mode)),'.','-'),'.mat'));\n    map_name=[name,'_',strrep((num2str(res_centerline_mode)),'.','-')];\nelse\n    path_track=evalin('base','path_track');\n    filename=evalin('base', 'filename');\n    track=importdata(path_track);\n    map_name=filename(7:end-4);\nend\n \n%Convert track to double\ntrack=double(track);\n\n%Get size of track_limits_filled file\npixelwidth_x=size(track,2);\npixelwidth_y=size(track,1);\nif pixelwidth_x>=pixelwidth_y\n    pixelwidth=pixelwidth_x;\nelse \n    pixelwidth=pixelwidth_y;\nend\n\n%Extract origin of coordinates from track_limits_filled file\nx_min_lim=track(1,1);\nx_max_lim=track(1,2);\ny_min_lim=track(2,1);\ny_max_lim=track(2,2);\n\n%Generate x-y-range array\nx_lim=[x_min_lim x_max_lim];\ny_lim=[y_min_lim y_max_lim];\n\n%Generate parameter for random mode depending on size of track_limits_filled.pgm file\nrand_n=round(pixelwidth/113)+1;\n\n%Extract resolution of Map\nresolution=track(1,3)/100;\n\n%Generate origin of coordinates Array\nlimits=[x_min_lim x_max_lim ; y_min_lim y_max_lim ];\n\n%Delete origin information\ntrack(1:2,1:3)=0;\n%Calculate raceline mode \"normal\" and \"percentage\"\nif strcmp(mode,'raceline') || raceline_percentage_mode ==1\n        %Handover Raceline Path from base workspace\n        path_raceline=evalin('base','path_raceline');\n        %Read in Raceline\n        fid=fopen(path_raceline,'r');\n        exportraceline=textscan(fid, '%f %f %f %f %f %f %f', 'Headerlines', 3, 'delimiter', ';');\n        %exportraceline=textscan(fid, '%f %f', 'Headerlines', 2, 'delimiter', ';');\n        fclose(fid);\n        %Separate Columns of Raceline file, short file and get size\n        x_0_race=exportraceline{:,2};\n        y_0_race=exportraceline{:,3};\n        intervall=round(size(x_0_race,1)/300);\n        x_0_race=x_0_race(1:intervall:end,:);\n        y_0_race=y_0_race(1:intervall:end,:);\n        height=size(x_0_race,1);\n        %Calculate gradients and normals of all points\n        m_tang_race=gradient(y_0_race,x_0_race);\n        m_normal_race= (-1./m_tang_race);\n        %Calculate X and Y-component of displacement of 2 meters\n        x_komp_2m=sqrt((2^2)./((1+m_normal_race.^2)));\n        y_komp_2m=m_normal_race.*x_komp_2m;\n        %Get variables from base workspace\n        if strcmp(mode,'raceline')\n            raceline_value_1=evalin('base', 'raceline_value_1');\n            raceline_value_2=evalin('base', 'raceline_value_2');\n        elseif raceline_percentage_mode==1\n            raceline_value_1=1+raceline_percent_value/100;\n            if raceline_value_1<1\n                raceline_value_2=-0.03;\n            else\n                raceline_value_2=0.03;\n            end    \n        end    \n        %Calculate new coordinates with distance of 0m, 4m and 10 meters\n        xyz_0m=[x_0_race y_0_race raceline_value_1*ones(height,1)];\n        xyz_4m_plus= [x_0_race+2*(x_komp_2m) y_0_race+2*(y_komp_2m) raceline_value_1*exp(-raceline_value_2*0.1*4^2)*ones(height,1)];\n        xyz_4m_minus= [x_0_race-2*(x_komp_2m) y_0_race-2*(y_komp_2m) raceline_value_1*exp(-raceline_value_2*0.1*4^2)*ones(height,1)];\n        xyz_10m_plus= [x_0_race+5*(x_komp_2m) y_0_race+5*(y_komp_2m) raceline_value_1*exp(-raceline_value_2*0.1*10^2)*ones(height,1)];\n        xyz_10m_minus= [x_0_race-5*(x_komp_2m) y_0_race-5*(y_komp_2m) raceline_value_1*exp(-raceline_value_2*0.1*10^2)*ones(height,1)];\n        xyz=[xyz_0m;xyz_4m_plus;xyz_4m_minus;xyz_10m_plus;xyz_10m_minus];\n        \n        %Calculate conversion factors coordinates <-> pixels\n        x_change=(pixelwidth_x/(abs(x_lim(1))+abs(x_lim(2))));\n        y_change=(pixelwidth_y/(abs(y_lim(1))+abs(y_lim(2))));\n        \n        %Generate intervall in coordination space\n        x_intervall=linspace(x_change*x_lim(1),x_change*x_lim(2),pixelwidth_x);\n        y_intervall=linspace(y_change*y_lim(1),y_change*y_lim(2),pixelwidth_y);\n        y_intervall=y_intervall(:);\n        \n        %Interpolate points in mesh\n        [X,Y,Z]= griddata(x_change*xyz(:,1), y_change*xyz(:,2), xyz(:,3),x_intervall, y_intervall, 'cubic');\n        Z=flipud(Z);\n        %if raceline mode\n        if strcmp(mode,'raceline')\n            Z(isnan(Z))=0;\n            Z(Z<0)=0;\n        %if raceline percentage mode\n        elseif raceline_percentage_mode==1\n            Z(isnan(Z))=1;\n            if raceline_value_1>1\n                Z(Z<1)=1;\n            else\n                Z(Z>1)=1;\n            end    \n        end           \nend\n\n%Handover of other variables from Workspace depending on mode\n%Insert origin of coordinates information and save file\ncurrentFolder=cd;\nswitch mode\n    case 'global'\n         global_value=evalin('base', 'global_value');\n         result=track.*global_value*100;\n         if raceline_percentage_mode==1\n             result=result.*Z;\n         end\n         result=int16(round(result));\n         surf(result,'EdgeColor','none');\n         set(gca,'YDir', 'reverse');\n         set(gca,'XLim',[0, pixelwidth_x],'XTick',[0 pixelwidth_x]);\n         set(gca,'YLim',[0, pixelwidth_y],'YTick',[0 pixelwidth_y]);\n         view([0 90]);\n         caxis([0 global_value*100+20]);\n         colorbar\n         result(1:2,1:2)=limits;\n         result(1,3)=resolution*100;\n         if raceline_percentage_mode==1\n%             save([currentFolder,'\\frictionmap_tools\\matlab_code\\outputs\\maps\\Map_',map_name,'Meter_Global_',strrep((num2str(global_value)),'.','-'),'_Raceline_', strrep((num2str(raceline_percent_value)),'.','-'),'_Percent.mat'], 'result');\n            save([currentFolder,'\\variable_friction\\generate_map\\outputs\\maps\\Map_',map_name,'Meter_Global_',strrep((num2str(global_value)),'.','-'),'_Raceline_', strrep((num2str(raceline_percent_value)),'.','-'),'_Percent.mat'], 'result');\n         else\n%             save([currentFolder,'\\frictionmap_tools\\matlab_code\\outputs\\maps\\Map_',map_name,'Meter_Global_',strrep((num2str(global_value)),'.','-'),'.mat'], 'result');\n            save([currentFolder,'\\variable_friction\\generate_map\\outputs\\maps\\Map_',map_name,'Meter_Global_',strrep((num2str(global_value)),'.','-'),'.mat'], 'result');\n         end\n    case 'random'\n         random_value_1=evalin('base', 'random_value_1');\n         random_value_2=evalin('base', 'random_value_2');\n         A=rand(rand_n);\n         B=A.*(random_value_2-random_value_1)+random_value_1;\n         C=interp2(B,7,'cubic',0);\n         D=C(1:pixelwidth_y,1:pixelwidth_x);\n         result=D.*track*100;\n         if raceline_percentage_mode==1\n             result=result.*Z;\n         end\n         result=int16(round(result));\n         surf(result,'EdgeColor','none');\n         set(gca,'YDir', 'reverse');\n         set(gca,'XLim',[0, pixelwidth_x],'XTick',[0 pixelwidth_x]);\n         set(gca,'YLim',[0, pixelwidth_y],'YTick',[0 pixelwidth_y]);\n         caxis([random_value_1*100-20 random_value_2*100+20]);\n         colorbar\n         view([0 90]);\n         result(1:2,1:2)=limits;\n         result(1,3)=resolution*100;\n         if raceline_percentage_mode==1\n             save(strcat(path2output,'\\maps\\Map_',map_name,'Meter_Random_',strrep((num2str(random_value_1)),'.','-'),'_',strrep((num2str(random_value_2)),'.','-'),'_Raceline_', strrep((num2str(raceline_percent_value)),'.','-'),'_Percent.mat'), 'result');\n         else\n             save(strcat(path2output,'\\maps\\Map_',map_name,'Meter_Random_',strrep((num2str(random_value_1)),'.','-'),'_',strrep((num2str(random_value_2)),'.','-'),'.mat'), 'result');\n         end    \n    case 'raceline'\n        result=Z.*track*100;\n        result=int16(round(result));\n        surf(result,'EdgeColor','none');\n        set(gca,'YDir', 'reverse');\n        set(gca,'XLim',[0, pixelwidth_x],'XTick',[0 pixelwidth_x]);\n        set(gca,'YLim',[0, pixelwidth_y],'YTick',[0 pixelwidth_y]);\n        view([0 90]);\n        caxis([0 raceline_value_1*100]);\n        colorbar\n        result(1:2,1:2)=limits;\n        result(1,3)=resolution*100;\n        save([path2output, '\\maps\\Map_',map_name,'Meter_Raceline_',strrep((num2str(raceline_value_1)),'.','-'),'_',strrep((num2str(raceline_value_2)),'.','-'),'.mat'], 'result');\nend\n%If another_map==1, run Read_FrictionmodeGUI again\nif another_map==1\n    Read_FrictionmodeGUI();\n    clc\n    \"Friction Coefficient Map(s) generated successfully!\" %#ok<NOPTS>\nelseif another_map==0  \n    clc\n    \"Friction Coefficient Map(s) generated successfully!\" %#ok<NOPTS>\n    evalin('base','clear');\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_environment/variable_friction/archive/generate_map/scripts/Friction_Map_Creation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5545152730748206}}
{"text": "function f=maxdiag(x,varargin)\n% Maximizaton of the diagonality of hte matrix. \ncovmat = varargin{1};   % #pix X #pix X #taus \nsizevec = varargin{2};\nW = reshape(x, sizevec(1)*sizevec(2), sizevec(3)); % #pix X #comp\n% W = max(W,eps);\nntau = size(covmat,3); % #taus (different time delays)\nftmp = zeros(1,ntau);\nfcol = zeros(1,sizevec(3));\nfor tau=1:ntau\n    covmattmp = covmat(:,:,tau);\n    for col=1:sizevec(3)\n        wcol = W(:,col);\n        fcol(col) = log(wcol'*covmattmp*wcol);\n    end\n    ftmp(tau) = 0.5*sum(fcol);\nend\n\nf = sum(ftmp);", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/conjgradfunctions/maxdiag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5545152655146759}}
{"text": "function [ x, know ] = p02_sol ( m, know )\n\n%*****************************************************************************80\n%\n%% P02_SOL returns known solutions for problem 2.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 February 2012\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, integer M, the spatial dimension.\n%\n%    Input/output, integer KNOW.\n%    On input, KNOW is 0, or the index of the previously returned solution.\n%    On output, KNOW is 0 if there are no more solutions, or it is the\n%    index of the next solution.\n%\n%    Output, real X(M), the solution.\n%\n  if ( know == 0 )\n    know = 1;\n    x = [ ...\n      0.390500591228663, ...\n      0.392051909813608, ...\n      0.393601661544812, ...\n      0.395149843840982 ]';\n  else\n    know = 0;\n    x = zeros ( m, 1 );\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_opt_con/p02_sol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.5545066295987854}}
{"text": "function [x,state] = struct_transpose(z,task)\n%STRUCT_TRANSPOSE Transpose.\n%   [x,state] = struct_transpose(z) computes x as the transpose of z. The\n%   structure state stores information which is reused in computing the\n%   right and left Jacobian-vector products.\n%\n%   struct_transpose(z,task) computes the right or left Jacobian-vector\n%   product of this transformation, depending on the structure task. Use\n%   the structure state and add the field 'r' of the same shape as z or the\n%   field 'l' of the same shape as x to obtain the structure task for\n%   computing the right and left Jacobian-vector products\n%   \n%      (dF(:)/dz(:).')*task.r(:) and\n%      (dF(:)/dz(:).')'*task.l(:) + conj((dF(:)/dconj(z(:)).')'*task.l(:)),\n%   \n%   respectively. Here, F(z) represents this transormation, (:) signifies\n%   vectorization and the derivative w.r.t. z (conj(z)) is a partial\n%   derivative which treats conj(z) (z) as constant. The output has the\n%   same shape as x or z for the right and left Jacobian-vector products,\n%   respectively.\n%   \n%   See also struct_conj, struct_ctranspose.\n\n%   Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n%            Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)\n%            Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)\n%\n%   References:\n%   [1] L. Sorber, M. Van Barel, L. De Lathauwer, \"Structured data fusion,\"\n%       ESAT-SISTA Internal Report 13-177, KU Leuven, 2013.\n\nif nargin < 2, task = []; end\nstate = [];\n\nif isempty(task) || (isempty(task.l) && isempty(task.r))\n    x = z.';\nelseif ~isempty(task.r)\n    x = task.r.';\nelseif ~isempty(task.l)\n    x = task.l.';\nend\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+tensorlab/struct_transpose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5545066295987852}}
{"text": "function new_x = monolist(x,dmax,dmin)\n% MONOLIST Generate monomials\n%\n% y = MONOLIST(x,dmax,dmin)\n%\n% Returns the monomials [1 x(1) x(1)^2 ... x(1)^dmax(1) x(2) x(1)x(2)  etc...]\n%\n% >>sdpvar x y z\n% >>sdisplay(monolist([x y z],4))\n%\n%  Input\n%     x      : Vector with SDPVAR variables\n%     dmax   : Integers > 0\n%\n%  See also POLYNOMIAL, DEGREE\n\n% Flatten\nx = reshape(x,1,length(x));\nx_orig = x;\n\nif nargin == 3\n    if length(dmin)>1 || any(dmin > dmax) || ~isequal(dmin,fix(dmin))\n        error('dmin has to be an integer scalar larger than dmax');\n    end\nelseif nargin == 2\n    dmin = 0;\nend\n\nif (length(dmax)==1 | all(dmax(1)==dmax)) & islinear(x) & ~isa(x,'ncvar')\n    dmax = dmax(1);\n    % Powers in monomials\n    powers = monpowers(length(x),dmax);\n   \n    powers = powers(find(sum(powers,2)>=dmin),:);\n    \n    % Use fast method for x^alpha\n    if isequal(getbase(x),[zeros(length(x),1) eye(length(x))])\n        new_x = recovermonoms(powers,x);\n        return\n    end\n\n    % Monolist on dense vectors is currently extremely slow, but also\n    % needed in some applications (stability analysis using SOS) For\n    % performance issue, the code below is hard-coded for special cases\n    % FIX : Urgent, find underlying indexing...\n    \n    % Vectorize quadratic and quadrtic case\n    if dmax==2 & length(x)>1\n        V=x.'*[1 x];\n        ind=funkyindicies(length(x));\n        new_x = [1 V(ind(:)).'].';\n        return\n    elseif (length(x)==4 & dmax==6)\n        \n         ind =[    1           2           3           4           5           6           7           8,\n\n           9          10          11          12          13          14          15          16,\n\n          17          18          19          20          21          22          23          24,\n\n          25          26          27          28          29          30          31          32,\n\n          33          34          49          50          51          52          86          53,\n\n          54          55          89          56          57          91          58          92,\n\n         126          59          60          61          95          62          63          97,\n\n          64          98         132          65          66         100          67         101,\n\n\n         135          68         102         136         170         185         186         187,\n\n         188         222         256         189         190         191         225         259,\n\n\n         192         193         227         261         194         228         262         296,\n\n         330         364         195         196         197         231         265         198,\n\n         199         233         267         200         234         268         302         336,\n\n         370         201         202         236         270         203         237         271,\n\n         305         339         373         204         238         272         306         340,\n\n         374         408         442         476         510         525         526         527,\n\n         528         562         596         630         529         530         531         565,\n\n\n         599         633         532         533         567         601         635         534,\n\n\n         568         602         636         670         704         738         772         806,\n\n\n         840         535         536         537         571         605         639         538,\n\n         539         573         607         641         540         574         608         642,\n\n         676         710         744         778         812         846         541         542,\n\n         576         610         644         543         577         611         645         679,\n\n         713         747         781         815         849         544         578         612,\n\n\n         646         680         714         748         782         816         850         884,\n\n\n         918         952         986        1020        1054        1088        1122        1156,\n\n        1190          0            0          0          0             0           0            0];\n        ind = ind';\n        ind = ind(find(ind));\n        v=monolist(x,3);\n        V=v(2:end)*v.';\n        new_x = [1;V(ind(:))];\n        return\n    elseif dmax==4 & (1<=length(x)) & length(x)<=4 %& length(x)>1\n        v=monolist(x,2);\n        V=v(2:end)*v.';\n\n        % Cone to generate indicies\n        %p = sdpvar(n,1);\n        %v = monolist(p,2);\n        %V = v(2:end)*v';V=V(:);\n        %m = monolist(p,4)\n        %ind = [];\n        %for i = 2:length(m)\n        % ind = [ind min(find(~any(V-m(i))))];\n        %end\n\n        switch length(x)\n            case 1\n                new_x = [1; V([1 2 4 6]')];\n                return\n            case 2\n                new_x = [1;V([1 2 3 4 5 8 9 10 15 18 19 20 25 30]')];\n                return;\n            case 3\n                new_x=[1;V([1 2 3 4 5 6 7 8 9 13 14 15 24 16 17 26 18 27 36 40 41 42 51 60 43 44 53 62 45 54 63 72 81 90]')];\n                return\n            case 4\n                new_x=[1;V([    1     2     3     4     5     6     7     8     9    10    11    12    13    14    19    20    21    35    22    23    37    24    38    52    25    26    40    27    41    55    28    42 56    70    75    76    77    91   105    78    79    93   107    80    94   108   122   136  150    81    82    96   110    83    97   111   125   139   153    84    98   112   126   140  154   168   182   196   210]')];\n                return\n            otherwise\n        end\n    end\n\n\n    % Na, we have things like (c'x)^alpha\n    % precalc x^p\n    for i = 1:length(x)\n        temp = x(i);\n        precalc{i,1} = temp;\n        for j = 2:1:dmax\n            temp = temp*x(i);\n            precalc{i,j} = temp;\n        end\n    end\n\n    new_x = [];\n\n    for i = 1:size(powers,1) % All monomials\n        temp = 1;\n\n        for j = 1:size(powers,2) % All variables\n            if powers(i,j)>0\n                temp = temp*precalc{j,powers(i,j)};\n            end\n        end\n        new_x = [new_x temp];\n\n    end\n\nelse\n\n    dmax = dmax(:)*ones(1,length(x_orig));\n\n    x = [1 x];\n\n    % Lame loop to generate all combinations\n    new_x = 1;\n    for j = 1:1:max(dmax)\n        temp = [];\n        for i = 1:length(x)\n            temp = [temp x(i)*new_x];\n        end\n        new_x = temp;\n        new_x = fliplr(unique(new_x));\n        new_degrees = degree(new_x,x(2:end));\n        remv = [];\n        for i = 1:length(dmax);\n            if new_degrees(i)>=dmax(i)\n                x = recover(setdiff(getvariables(x),getvariables(x_orig(i))));\n                x = [1;x(:)];\n                remv = [remv i];\n            end\n        end\n        dmax = dmax(setdiff(1:length(dmax),remv));\n    end\nend\nnew_x = reshape(new_x(:),length(new_x),1);\nif dmin > 0\n    for i = 1:length(new_x)\n        if sum(powers(i,:)) < dmin\n            keep(i) = 0;\n        else\n            keep(i) = 1;\n        end\n    end\n    if any(keep==0)\n        new_x = new_x(find(keep));\n    end\nend\n\nfunction ind = funkyindicies(n)\n\nM=reshape(1:n*(n+1),n,n+1);\nind = M(:,1)';\nfor i = 1:n\n    ind = [ind M(i,2:i+1)];\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/extras/monolist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5545030011513171}}
{"text": "function double_c_plot ( x, y, c )\n\n%*****************************************************************************80\n%\n%% DOUBLE_C_PLOT displays the \"double C\" data.\n%\n%  Discussion:\n%\n%    The data comprises a \"C\" shape and its reverse, which do not intersect,\n%    but which nestle together fairly closely.  \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%    John Burkardt\n%\n%  Parameters:\n%\n%   Input, real X(N), Y(N), the coordinates of the data points.  The points\n%   have been shuffled so that data belonging to the two components is\n%   interleaved.\n%\n%   Input, integer C(N), is 1 or 2, depending on which set the corresponding\n%   data point belongs to.\n%\n  i1 = ( c == 1 );\n  i2 = ( c == 2 );\n\n  n1 = sum ( i1 );\n  n2 = sum ( i2 );\n\n  plot ( x(i1), y(i1), 'r.', ...\n         x(i2), y(i2), 'b.' )\n\n  xlabel ( '<-- X -->' );\n  ylabel ( '<-- Y -->' );\n  title ( sprintf ( 'Double C Data, N1 (red) = %d, N2 (blue) = %d', n1, n2 ) );\n  grid on\n  axis equal\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/double_c_data/double_c_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.5545029997741219}}
{"text": "% calc_frap - makes the actual analysis of the FRAP data\n%   [k,D1k,D1,D2,gamma2,gamma0,v_conv,a_conv]=...\n%   calc_frap(file_in,dx,Ipre,Idark,istart,t,trc,Rp_max,nr) where:\n%\n%   k =  spatial frequencies [um^-1]\n%   D1k = D1(k2), the diffusion coefficient determined for each k\n%       separately [um^2s^-1]\n%   D1 and D2 = effective values of the diffusion coefficients D1 and\n%       D2 [um^2s^-1]\n%   gamma2 = the intensity fraction of component 2\n%   gamma0 = the intensity fraction of immobile molecules\n%   v_conv = the absolute velocity of the tracked center of mass [um/s]\n%   a_conv = the angle the tracked center of mass moves in, with 0 degrees\n%       corresponding to moving horizontally from the left to the right\n%       [degrees]\n%\n%   file_in = the filename + directory of the image stack\n%   dx = the pixel size (square pixels assumed)\n%   Ipre = the pre-bleach intensity\n%   Idark = the dark count intensity\n%   istart = the first post-bleach frame\n%   t = the times for each frame\n%   trc = parameter that if equal to 'y' leads to tracking of the center of\n%       mass for each frame (otherwise the center of mass is determined from\n%       the first post-bleach frame)\n%   Rp_max = the maximum radial value used in the analysis [pixels]\n%   nr = a vector for all frames in the image stack. If nr==1 then this\n%       image will be part of the analysis.\n\nfunction [k,D1k,D1,D2,gamma2,gamma0,v_conv,a_conv]=...\n    calc_frap(file_in,dx,Ipre,Idark,istart,t,trc,Rp_max,nr)\n\n% closes the figures\nclose(figure(1))\nclose(figure(2))\n\n% Meshpoints\nx=(1:1:size(Ipre,2));\ny=(size(Ipre,1):-1:1);\n[Xx,Yy]=meshgrid(x,y);\n\n% Calculates the centre of mass from the first frame after bleaching\nI=double(imread(file_in,istart))-Idark;\nI2=I./Ipre;\n\nfig=figure(1);\nset(fig,'Color','w');\nI2_min=max(0.5,min(I2(:)));\nimshow(I2,[I2_min,min([1+(1-I2_min)*0.1,max(I2(:))])]);\nax1 = gca;\nset(ax1,'FontSize',8)\naxis square\nh=title({'Define a polygon around the bleached spot (close with the right mouse button).';...\n    'Exit by double clicking the inner part of the polygon.'},...\n    'Color','k','BackgroundColor','w');\nhp=get(h);\npos=hp.Position;\npos(2)=pos(2)+50;\nset(h,'Position',pos);\nBW=roipoly; % the region in which the bleached spot is situated\n\n% Calculates the centre of mass (x_cm,y_cm)\nx_cm=sum(sum(Xx.*(1-I2).*BW))/sum(sum((1-I2).*BW));\ny_cm=sum(sum(Yy.*(1-I2).*BW))/sum(sum((1-I2).*BW));\nRr=sqrt((Xx-x_cm).^2+(Yy-y_cm).^2);\nwid=max(Rr(BW==1)); % max r-value to use to calculate the center of mass\n\nfigure(1)\nhold on\nplot3([x_cm-10,x_cm+10],[max(Yy(:))-y_cm+1,max(Yy(:))-y_cm+1],max(I2(:))*ones(1,2),...\n    [x_cm,x_cm],[max(Yy(:))-y_cm+1-10,max(Yy(:))-y_cm+1+10],max(I2(:))*ones(1,2),'LineWidth',2,'Color',[1 1 1])\nhold off\npause(0.2)\n\n% Defines the options for nonlinear fitting\noptions=optimset('Display','off');\n\nNrp=512;    % the length of r\n\n% Determines the radial distance r and the radius of the field of view R\n[test,r,R,Rp_max]=I_radial(Nrp,x_cm,y_cm,Xx,Yy,Xx,Rp_max);\nr=r*dx;\nR=R*dx;\n\n% Initiates variables\nwf=zeros(sum(nr==1),1);\nx_cm2=zeros(sum(nr==1),1);\ny_cm2=zeros(sum(nr==1),1);\nIxx=zeros(size(x_cm2));\nIyy=zeros(size(x_cm2));\nIxy=zeros(size(x_cm2));\nAf=zeros(sum(nr==1),1);\nIsum=zeros(sum(nr==1),1);\nIr=zeros(sum(nr==1),Nrp);\ng=zeros(sum(nr==1),Nrp);\ni=0;\n\nt=t(nr==1)';    % updates the time vector\n\nfor n_t=1:length(nr)\n    % n_t==0 if a frame is omitted from the analysis\n    if nr(n_t)==1\n        i=i+1;\n\n        I=double(imread(file_in,istart+n_t-1))-Idark;   % Reads the image\n        I2=I./Ipre; % The relative intensity\n\n        if i==1\n            x_cm2(i)=x_cm;\n            y_cm2(i)=y_cm;\n            \n            I20=I2;           \n        else\n            x_cm2(i)=x_cm2(i-1);\n            y_cm2(i)=y_cm2(i-1);\n        end\n      \n        if i>2\n            x_cm2(i)=(x_cm2(i-1)-x_cm2(i-2))/(t(i-1)-t(i-2))*(t(i)-t(i-1))+x_cm2(i-1);\n            y_cm2(i)=(y_cm2(i-1)-y_cm2(i-2))/(t(i-1)-t(i-2))*(t(i)-t(i-1))+y_cm2(i-1);\n        end\n        \n%         % Take away the immobile fraction\n%         if trc=='y'\n%             gamma_g=0.020;   % immobile fraction\n%             I2=I2+(I2_inf-I20)*gamma_g;\n%         end\n        \n        % Determines I2(inf) using values at the edge of the image\n        nx=round(length(x)*0.1);\n        ny=round(length(y)*0.1);\n        I2s=sum(sum(I2(1:ny,:)))+sum(sum(I2(end:end-ny,:)))+...\n            sum(sum(I2(:,1:nx)))+sum(sum(I2(:,end:end-nx)));\n        I2n=sum(sum(~isnan(I2(1:ny,:))))+sum(sum(~isnan(I2(end:end-ny,:))))+...\n            sum(sum(~isnan(I2(:,1:nx))))+sum(sum(~isnan(I2(:,end:end-nx))));\n        I2_inf=I2s/I2n;\n        beta=I2_inf;\n\n        % If trc=='y' then the program tracks (and moves) the center of mass\n        % for each frame\n        Iin=(I2_inf-I2);\n        if trc=='y'\n            for j=1:3\n                Rr2=(Xx-x_cm2(i)).^2+(Yy-y_cm2(i)).^2;\n                BW=Rr2<(wid^2);\n                cm_w=Iin(BW==1);\n                Xx_w=Xx(BW==1);\n                Yy_w=Yy(BW==1);\n\n                % Calculates the centre of mass (x_cm,y_cm)\n                x_cm2(i)=sum(Xx_w.*cm_w)/sum(cm_w);\n                y_cm2(i)=sum(Yy_w.*cm_w)/sum(cm_w);\n            end   \n        else      \n            Rr2=(Xx-x_cm2(i)).^2+(Yy-y_cm2(i)).^2;\n            BW=Rr2<(wid^2);\n            cm_w=Iin(BW==1);\n            Xx_w=Xx(BW==1);\n            Yy_w=Yy(BW==1);\n            x_cm2(i)=x_cm;\n            y_cm2(i)=y_cm;           \n        end\n        \n        % Calculates the moments (Ixx and Iyy) and product (Ixy) of inertia for the bleached spot\n        Ixx(i)=sum((Yy_w-y_cm2(i)).^2.*cm_w);\n        Iyy(i)=sum((Xx_w-x_cm2(i)).^2.*cm_w);\n        Ixy(i)=sum((Xx_w-x_cm2(i)).*(Yy_w-y_cm2(i)).*cm_w);\n\n        % Performs the radial averaging of I2 around the centre of mass\n        Ir(i,:)=I_radial(Nrp,x_cm2(i),y_cm2(i),Xx,Yy,I2,Rp_max);\n\n        % Determines Ir(R,0) using values where r>0.9R\n        if i==1\n            Ir0=mean(Ir(1,r>(max(r)*0.9)));\n        end\n\n        % Determines the integral of Ir at r<R\n        Isum(i)=2*pi*Ir(i,1)*r(1)*r(1);\n        for j=2:length(r)\n            Isum(i)=Isum(i)+2*pi*(Ir(i,j)*r(j)+Ir(i,j-1)*r(j-1))/2*(r(j)-r(j-1));\n        end\n\n        % Determines starting parameters used to fit the tail of Ir\n        y=Ir(i,:)/Ir0;\n        x=r;\n        pos=1;\n        y0=y(pos);\n        while (1-y0)>(1-y(1))*exp(-1) && pos<length(y)\n            pos=pos+1;\n            y0=y(pos);\n        end\n        w_g0=sqrt(x(pos)^2-x(1)^2);\n\n        y=Ir(i,r>max(r)*1/2)/Ir0;\n        x=r(r>max(r)*1/2);\n        pos=1;\n        y0=y(pos);\n        while (1-y0)>(1-y(1))*exp(-1) && pos<length(y)\n            pos=pos+1;\n            y0=y(pos);\n        end\n        w_g=max(sqrt(x(pos)^2-x(1)^2),w_g0);\n\n        % Makes a curve fit to the tail of Ir (for r>R/2) for each frame\n        p0=[min(1-Ir(i,1)/Ir0,abs(1-y(1))*exp(x(1)^2/w_g^2)),w_g];\n        p0_2=p0;\n        if i>1\n            p0_2=p;\n        end\n        \n        [p1,sse1]=lsqcurvefit(@(p,r) fkn_gauss(p,r,Isum(i),Isum(1),Ir0),p0,x,y*Ir0,...\n            [0,0],[Inf,Inf],options);\n\n        [p2,sse2]=lsqcurvefit(@(p,r) fkn_gauss(p,r,Isum(i),Isum(1),Ir0),p0_2,x,y*Ir0,...\n            [0,0],[Inf,Inf],options);\n\n        if sse1<sse2\n            p=p1;\n        else\n            p=p2;\n        end\n        \n        wf(i)=p(2); % w(t)\n        Af(i)=p(1); % A(t)\n        [y,beta]=fkn_gauss(p,r,Isum(i),Isum(1),Ir0);    % y = Ir|r>R\n\n        % Compensates for temporal variations using beta and for\n        % a net influx of molecules with y\n        g(i,:)=(y-Ir(i,:))/beta;\n    \n        if mod(i,10)==0 || i==1 || i==sum(nr==1)\n            figure(2)\n            ax1 = gca;\n            set(ax1,'FontSize',12)\n            plot(r,Ir(i,:)/beta,'b.',r(r>(max(r)*1/2)),y(r>(max(r)*1/2))/beta,'r-','LineWidth',2)\n            xlabel('r [\\mum]','FontSize',12)\n            ylabel('Intensity [a.u.]','FontSize',12)\n            title(['Frame ',num2str(i),' out of ',num2str(sum(nr==1))],'FontSize',12)\n            xlim([min(r),max(r)])\n            pause(0.1)\n        end\n        \n    end\nend\n\n% Calculates the Hankel transform and performs the curve fits yielding D1,\n% D2, gamma2 and gamma0\n[k,D1k,D1,D2,gamma2,gamma0,v_conv,a_conv]=...\n    hankel_diff(r,t,R,g,wf,Af,Nrp,trc,x_cm2,y_cm2,dx,Ixx,Iyy,Ixy);\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/29388-frapanalysis/frap_analysis 2p5/calc_frap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5545029901132861}}
{"text": "function test_failed=test_spread\n%TEST_SPREAD  Test spreading function.\n%\n%  This script runs a throrough test of the SPREADOP routine,\n%  testing it on a range of input parameters.\nglobal LTFAT_TEST_TYPE;\ndisp(' ===============  TEST_SPREAD ================');\n\ndisp('--- Used subroutines ---');\n\nwhich comp_col2diag\n\nLr=[12, 13 ];\n\ntest_failed=0;\n\ncondNoLim.('single') = 100;\ncondNoLim.('double') = 100;\n\nfor ii=1:length(Lr);\n\nL=Lr(ii); \n\nspfraction=.5;\n\nfor rtype=1:2\n  \n  if rtype==1\n    rname='REAL ';\t\n  else\n    rname='CMPLX';\t\n  end;\n  \n  for sptype=1:2\n    \n    if sptype==1\n      spname='FULL  ';\t\n    else\n      spname='SPARSE';\t\n      if ~strcmpi(LTFAT_TEST_TYPE,'double')\n          disp(sprintf('Skipping. Cannot work with sparse matrices of type %s.',LTFAT_TEST_TYPE));\n          break;\n      end\n    end;\n\n    \n    condNo = 1e10;\n    while condNo>condNoLim.(LTFAT_TEST_TYPE)\n    if rtype==1\n      if sptype==1\n        coef=tester_rand(L,L);\n        T=tester_rand(L,L);\n        coef2=tester_rand(L,L);\n      else\n        coef=tester_sprand(L,L,spfraction);\n        T=tester_sprand(L,L,spfraction);\n        coef2=tester_sprand(L,L,spfraction);          \n      end;\n    else\n      if sptype==1\n        coef=tester_crand(L,L);\n        T=tester_crand(L,L);\n        coef2=tester_crand(L,L);\n      else\n        coef=tester_sprand(L,L,spfraction);\n        T=tester_sprand(L,L,spfraction);\n        coef2=tester_sprand(L,L,spfraction);          \n      end;\n    end;\n    \n      coeftmp=ifft(full(coef))*L;\n      % The following matrix is inverted in spreadinv. We want a nicer cond\n      % number in order not to fail\n      Ttmp=comp_col2diag(coeftmp);\n      condNo = cond(Ttmp); \n    end\n\n    \n    for W=1:3\n      \n      if rtype==1\n        f=tester_rand(L,W);\n      else\n        f=tester_crand(L,W);\n      end;\n      \n      \n      % ---------- Reference testing ------------ \n      \n      fs=spreadop(f,coef);  \n      fs2=ref_spreadop(f,coef,1);\n      \n      fsdiff=fs-fs2;\n      res=norm(fsdiff(:));      \n      [test_failed,fail]=ltfatdiditfail(res,test_failed);\n      s=sprintf('REF %s %s L:%3i W:%2i %0.5g %s',rname,spname,L,W,res,fail);\n      disp(s)\n\n      % -------- Inversion testing -------------\n     \n      r=spreadinv(fs,coef);\n\n      rdiff=f-r;\n      res=norm(rdiff(:));      \n      [test_failed,fail]=ltfatdiditfail(res,test_failed);\n      s=sprintf('INV %s %s L:%3i W:%2i %0.5g %s',rname,spname,L,W,res,fail);\n      disp(s)\n      \n\n      % -------- Twisted convolution -------------------\n\n      f1=spreadop(spreadop(f,coef2),coef);\n      f2=spreadop(f,tconv(coef,coef2));\n      \n      rdiff=f1-f2;\n      res=norm(rdiff(:));      \n      [test_failed,fail]=ltfatdiditfail(res,test_failed);\n      s=sprintf('TWI %s %s L:%3i W:%2i %0.5g %s',rname,spname,L,W,res,fail);\n      disp(s)\n      \n      % -------- Spreading function ---------------------\n      \n      coef=spreadfun(T);\n      \n      rdiff=T*f-spreadop(f,coef);\n      \n      res=norm(rdiff(:));      \n      [test_failed,fail]=ltfatdiditfail(res,test_failed);\n      s=sprintf('FUN %s %s L:%3i W:%2i %0.5g %s',rname,spname,L,W,res,fail);\n      disp(s)\n\n      % -------- Adjoint operator -----------------------\n      \n      cadj=spreadadj(coef);\n\n      rdiff=T'*f-spreadop(f,cadj);\n      \n      res=norm(rdiff(:));      \n      [test_failed,fail]=ltfatdiditfail(res,test_failed);\n      s=sprintf('ADJ %s %s L:%3i W:%2i %0.5g %s',rname,spname,L,W,res,fail);\n      disp(s)\n\n      \n    end;\n\n  end;  \n  \nend;\nend;\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/testing/test_spread.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.554502990092817}}
{"text": "% Dynamical model function for the random sine signal demo\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\nfunction x_n = ekf_sine_f(x,param)\n    dt = param(1);\n    A = [1 dt 0;0 1 0;0 0 1];\n    x_n = A*x(1:3,:);\n    if size(x,1) == 7 || size(x,1) == 6\n        x_n(1:3,:) = x_n(1:3,:) + x(4:6,:);\n    end\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_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5545029845840361}}
{"text": "function ac = lpcweight(ar,c)\n%  lpcweight --> LPC based perceptual weighting filter.\n%\n%    ac = lpcweight(ar,c)\n%\n%    The function takes the LP coefficients, ar = [1 -a(1) ... -a(M)],\n%    and the parameter, c, as inputs, and returns the coefficients of\n%    the filter function A(z/c) in the vector ac.\n\n% Linear predictor order.\nM = length(ar);\n\n% The i'th coefficient of A(z/c) is given by ar(i)*c^(i-1).\nac = ar;\nci = c;\nfor (i=2:M)\n  ac(i) = ar(i)*ci;\n  ci = ci*c;\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/39038-celp-codec/CELP_done/lpcweight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5545029845430974}}
{"text": "function fem=springs(fem,iter);\n% SPRING is legacy code that moves internal points of a finite \n%  element mesh such that the mesh quality is improved.  The movement\n%  of nodes is accomplished with a Laplacian smoothing action, so \n%  that each point not located along the boundary is moved toward\n%  the center of mass of the polygon formed by the adjacent\n%  triangles. The process is repeated according to the setting \n%  of the ITER variable.\n%\n%       Calls laplace_smooth.m with specified input.\n% FileName:  springs.m\n% Written By:  unknown\n% Date Last Modified:\n%    May 9, 2007 -- Chris Massey, NRL Code 7322, Stennis Spc Cnt., MS\n%                   Deleted code and replaced with a call to \n%                   laplace_smooth.m.\n%    May 15, 2007 -- Chris Massey, -- Fixed bug, should send over the\n%                   node list not the element list.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  \nif nargin==1,\n    iter=5;\nend\n\nfem = laplace_smooth(fem,1:length(fem.x),iter);\n\nreturn\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/Nodal_Reduce_Matlab_Codes/springs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5545029790957235}}
{"text": "function gT = simKernDiagGradX(kern, t);\n\n% SIMKERNDIAGGRADX Gradient of SIM kernel's diagonal with respect to the\n% input times t.\n% FORMAT\n% DESC computes the gradient of the diagonal of the single input motif\n% kernel matrix with respect to the elements of the design matrix given\n% in t.\n% ARG kern : the kernel structure for which gradients are being computed.\n% ARG t : the input data in the form of a design matrix.\n% RETURN gT : the gradients of the diagonal with respect to each element\n% of t. The returned matrix has the same dimensions as t.\n%\n% SEEALSO : simKernParamInit, kernDiagGradX, simkernGradX\n%\n% COPYRIGHT : Neil D. Lawrence, 2006\n%\n% COPYRIGHT : David Luengo, 2009\n\n% KERN\n\nif size(t, 2) > 1\n  error('Input can only have one column');\nend\n\nsigma = sqrt(2/kern.inverseWidth);\nt = t - kern.delay;\nhalfSigmaD = 0.5*sigma*kern.decay;\n\ngT = zeros(size(t));\n\nif (kern.isStationary == false)\n    lnPart1 = lnDiffErfs(halfSigmaD, halfSigmaD-t/sigma);\n    gT = kern.variance * exp(halfSigmaD*halfSigmaD - 2*kern.decay*t + lnPart1);\nelse\n    gT = zeros(size(t));\nend\n\nif ~isfield(kern, 'isNormalised') || (kern.isNormalised == false)\n    gT = gT * sigma * sqrt(pi);\nend\n\nif isfield(kern, 'gaussianInitial') && kern.gaussianInitial,\n  error('simKerDiagGradX not implemented for gaussianInitial')\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/simKernDiagGradX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5545029790752549}}
{"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%==============================================================================\n%\n% Tutorial for FAIR: compact version of matrix-based regularization\n%\n%  S(y) = alpha/2 * norm(B*(y-yRef))^2,\n%\n% where\n%  alpha regularization parameter, weights regularization versus \n%        distance in the joint objective function, alpha = 1 here\n%  yRef  is a reference configuration, e.g. yRef = x or a \n%        pre-registration result\n%  B     a discrete partial differential operator either in explicit\n%        matrix form or as a structure containing the necessary\n%        parameters to compute B*y\n% see also regularizer E8_regularization_MF\n%==============================================================================\n\nclear, close all, help(mfilename);\n\n% (c) Jan Modersitzki 2009/03/25, see FAIR.2 and FAIRcopyright.m.\n% note: '%' is used so hide comments in the book                              \n% Example for usage of regularization\n% (c) Jan Modersitzki 2009/04/02, see FAIR.2 and FAIRcopyright.m.\n% illustrates the usage of L2-norm based regularization\n%\n%\n\n% initialize the regularization and create a starting  point\nregularizer('reset','regularizer','mbElastic','alpha',1,'mu',1,'lambda',0);\ny0 = @(omega,m) randn(size(getStaggeredGrid(omega,m)));\n\n% 2D example, initialize physical domain and number of discretization points\nomega = [0,1,0,1]; m = [16,12];   % \n\n% test derivative of 2D implementation\nfctn = @(yc) regularizer(yc,omega,m);  checkDerivative(fctn,y0(omega,m));\n\n% 3D example, initialize physical domain and number of discretization points\nomega = [0,1,0,1,0,1]; m  = [16,12,8];\n\n% test derivative of 3D implementation\nfctn = @(yc) regularizer(yc,omega,m); \ncheckDerivative(fctn,y0(omega,m));\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_regularizationElasticMB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5544608281912632}}
{"text": "%-------------------------------------------------------------------------\n% Coupling Kinetic and Fluid System of Euler Equations\n% To solve Shock Tube Problem\n%\n% Kinetic equation use SBBGK and Hydrodynamic equation use Roe Euler\n%\n% Based on: \n%  [1] Pierre Degond, Giacomo Dimarco and Luc Mieussens\n%      A moving interface method for dynamic kinetic-fluid coupling\n%      Journal of Computation Physics 227(2007)1176-1208\n%\n% By Manuel Diaz and Yun-Da Tsai   \n% 007@IAM 25.01.2013\n%-------------------------------------------------------------------------\n\nclear all; clc; close all;\n\n%% Global Variables\nglobal CFL r_time theta dt dtdx nx\nglobal w k nv\nglobal gamma etpfix\n\n%% Controling Parameters\nname        ='SBBGK1d'; % Simulation Name\nCFL         = 0.05;     % CFL condition\nr_time      = 1/10000;  % Relaxation time\ntEnd        = 0.1;      % End time\ntheta       = 0;        % {-1} BE, {0} MB, {1} FD.\nquad        = 2;        % for NC = 1 , GH = 2\nmethod      = 1;        % for TVD = 1, WENO3 = 2, WENO5 = 3\nIC_case     = 1;        % IC: {1}Sod's, {2}LE, {3}RE, {4}DS, {5}SS, {6}Cavitation\nplot_figs   = 1;        % 0: no, 1: yes please!\nwrite_ans   = 0;        % 0: no, 1: yes please!\ngamma       = 2.4;      % Ratio of specific heats\nflxtype     = 2;        % {1} Roe, {2} LF, {3} LLF, {4} Upwind <-non-conservative!\netpfix      = 0.90;     % {#} Harten's sonic entropy fix value, {0} no entropy fix\n\n%% Space Discretization\nnx  = 60;                      % number of cells\nx   = linspace(0,1,nx);         % Physical domain -x\ndx  = max(x(2:end)-x(1:end-1)); % delta x\n\n%% Load Initial Condition\n[z0,ux0,t0,p0,rho0,E0] = SSBGK_IC1d(x,IC_case);\n\n%% Load Initial Cut Function\nxa = 0;   % buffer left boundary\nxb = 1;   % buffer right boundary\n%h0  = cutfunc(x,xa,xb);  % Physical Cut Function\n%h0 = ones(size(x));\nh0 = zeros(size(x));\n\n%% Discretization of the Velocity Space\n% Microscopic Velocity Discretization (using Discrete Ordinate Method)\n% that is to make coincide discrete values of microscopic velocities with\n% values as the value points for using a quadrature method, so that we can\n% integrate the velocity probability distribution to recover our\n% macroscopics properties.\nswitch quad\n\n    case{1} % Newton Cotes Quadrature:\n    V  = [-20,20];  % range: a to b\n    nv = 200;       % nodes desired (may not the actual value)\n    [c,w,k] = cotes_xw(V(1),V(2),nv,5); % Using Netwon Cotes Degree 5\n        \n    case{2} % Gauss Hermite Quadrature:\n    nv = 60;          % nodes desired (the actual value)\n    [c,w] = GaussHermite(nv); % for integrating range: -inf to inf\n    k = 1;            % quadrature constant.\n    w = w.*exp(c.^2); % weighting function of the Gauss-Hermite quadrature\n    \n    otherwise\n        error('Order must be between 1 and 2');\nend\n\n%% Applying DOM\n% The actual nv value will be computed using 'lenght' vector function:\nnv = length(c); \n% Remap velocity points\n    c = repmat(c,1,nx);     w = repmat(w,1,nx);\n% Remap classical IC\n    [rho0,ux0,p0] = apply_DOM(rho0,ux0,p0,nv);\n% Remap Semiclassical IC\n    [z0,t0,E0] = apply_DOM(z0,t0,E0,nv);\n% Remap h coeficient\n  h0 = repmat(h0,nv,1);\n\n%% Semi0-classical Equilibrium Distribution Function\nM0 = f_equilibrium_1d(z0,ux0,c,t0,theta); \n\n%% Load initial Conditions and Spliting of information\nM = M0; rho = rho0; ux = ux0; t = t0; p = p0; z = z0; h = h0; E = E0;\n\n%% Split ICs in R and L\nrhor = h.*rho0;     rhol = (1-h).*rho0;\nuxr = h.*ux0;       uxl = (1-h).*ux0;\npr = h.*p0;         pl = (1-h).*p0;\n\n[zr,~,tr,~] = macroproperties1d(rhor,rhor.*uxr,pr+0.5*rhor.*uxr.^2,nx,nv,theta);\n[zl,~,tl,~] = macroproperties1d(rhol,rhol.*uxl,pl+0.5*rhol.*uxl.^2,nx,nv,theta);\n\nfr = f_equilibrium_1d(zr,uxr,c,tr,theta);\n\n%% Main Loop \n% Compute next time step\ndt = dx*CFL/max(c(:,1));\ntime  = 0:dt:tEnd;\ndtdx = dt/dx;\n\nMl = f_equilibrium_1d(zl,uxl,c,tl,theta) ;\nMl(isnan(Ml)) = 0;     fr(isnan(fr)) = 0;\nf = fr + Ml; % computed here for ploting purposes\n\ncount = 1; % iteration counter\ntic;\nfor tsteps = time\n      \n    % Compute M_eq for the entire domain\n    M_eq = f_equilibrium_1d(z,ux,c,t,theta);     % total % theta = 0;\n    \n    % Break total information into r and l\n    if (tsteps>1)\n        rhol = (1-h).*rho;\n        uxl = (1-h).*ux;\n        pl = (1-h).*p;\n    end\n    \n    % Plot IC\n    %if plot_figs == 1; surf(f); end;\n    \n    % Compute vector 'q'\n    q = [rhol(1,:) ; rhol(1,:).*uxl(1,:) ; pl(1,:)+0.5*rhol(1,:).*uxl(1,:).^2];\n    \n    % Update Physical cut function 'h'\n    h_next = h; % this means: fixed buffer assumption\n\n% uncomment for BGK ******************************************************\n%     % Evaluate Modified Boltzmann BGK\n%     [fr_next] = ModSBBGK(h,h_next,M_eq,fr,Ml,c,flxtype);\n%     \n%     % Compute macroscopic moments\n%     [rhor,rhour,Er] = macromoments1d(k,w,fr_next,c);\n%     \n%     % macroscopic properties\n%     [zr,uxr,tr,pr] = macroproperties1d(rhor,rhour,Er,nx,nv,theta);\n% \n%         rhol = zeros(size(x));\n%         rhoul = zeros(size(x));\n%         El = zeros(size(x));\n%         Ml_next = zeros(size(fr));\n% uncomment for BGK ******************************************************\n    \n% uncomment for EULER*****************************************************   \n    rhor = zeros(size(x));\n    rhour = zeros(size(x));\n    Er = zeros(size(x));\n    fr_next = zeros(size(Ml));\n\n    % Evaluate Modificed Roe Euler Solver\n    [rhol,rhoul,El] = ModEuler(h,h_next,q,fr_next,c);\n    \n    %plot partial result\n    if plot_figs == 1; \n        subplot(1,3,1); plot(x,rhol,'o'); title('Density');\n        subplot(1,3,2); plot(x,rhoul./rhol,'o'); title('Velocity');\n        subplot(1,3,3); plot(x,El,'o'); title('Energy');\n    end\n    \n    % macroscopic properties\n    [zl,uxl,tl,pl] = macroproperties1d(rhol,rhoul,El,nx,nv,theta);\n    \n    % Apply DOM\n    [tl,zl,uxl] = apply_DOM(tl,zl,uxl,nv);\n    \n    % Compute Ml_next\n    Ml_next = f_equilibrium_1d(zl,uxl,c,tl,theta) ;\n    \n% uncomment for EULER***************************************************** \n    \n    % New time step info: sum left and righ values with 'NaN' filter sum\n    % function. \n    Ml_next(isnan(Ml)) = 0;     fr_next(isnan(fr_next)) = 0;\n    f   = fr_next + Ml_next;    % total f\n    rho = nansum([rhol;rhor]);  % total density\n    rhou= nansum([rhoul;rhour]);% total velocity in x\n    E   = nansum([El;Er]);      % total persure\n    \n    %Apply Neumann BC's in total variables\n    f(:,1)  = f(:,2);           f(:,end)  = f(:,end-1);\n    rho(:,1)= rho(:,2);         rho(:,end)= rho(:,end-1);\n    rhou(:,1) = rhou(:,2);      rhou(:,end) = rhou(:,end-1);\n    E(:,1)  = E(:,2);           E(:,end)  = E(:,end-1);\n    \n    % Recover Semiclassical Conditions for next time step\n    [z,ux,t,p] = macroproperties1d(rho,rhou,E,nx,nv,theta);\n    \n    %Apply DOM\n    [rho,ux,p] = apply_DOM(rho,ux,p,nv);\n    [t,z,E] = apply_DOM(t,z,E,nv);\n    \n    % Update information\n    fr = fr_next;\n    \n    % update counter\n    count = count+1;\n    \n    % update plot\n    drawnow\nend\ntoc;\n% write/plot final output\n%plot(x,r_total,'o');\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/BufferProblem/test/2013.1.21/Main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5544608117767771}}
{"text": "% TEST_MAXWELL_RING_H_DRCHLT: data function for Dirichlet boundary condition.\n\nfunction h = test_maxwell_ring_h_drchlt (x, y, ind)\n\n  [theta, r] = cart2pol (x, y);\n  h = zeros (size(x));\n  switch (ind)\n    case 1\n      h = -sin(theta) .* sin(y) + cos(theta) .* sin(x);\n    case 2\n      h = sin(theta) .* sin(y) - cos(theta) .* sin(x);\n    case 3\n      h = -sin(y);\n    case 4\n      h = sin(x);\n    otherwise\n      error ('h_drchlt: unknown reference number')\n  end\n\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/maxwell/data_files/test_maxwell_ring_h_drchlt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5544188547129644}}
{"text": "% lapplot() -  Compute the discrete laplacian of EEG scalp distribution(s)\n%                \n% Usage:\n%   >> laplace = lapplot(map,eloc_file,draw)\n% \n% Inputs:\n%    map        - Activity levels, size (nelectrodes,nmaps)\n%    eloc_file\t- Electrode location filename (.loc file) \n%                 For format, see  >> topoplot example \n%    draw       - If defined, draw the map(s) {default: no}\n%\n% Output:\n%    laplace    - Laplacian map, size (nelectrodes,nmaps)\n%\n% Note: uses del2()\n%\n% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 1998 \n%\n% See also: topoplot(), gradplot()\n\n% Copyright (C) Scott Makeig, SCCN/INC/UCSD, La Jolla, 1998 \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% 01-25-02 reformated help & license, added links -ad \n\nfunction [laplac] = lapplot(map,filename,draw)\n\nif nargin < 2\n\thelp lapplot;\n\treturn;\nend;\n\nMAXCHANS = size(map,1);\nGRID_SCALE = 2*MAXCHANS+5;\nMAX_RADIUS = 0.5;\n\n% ---------------------\n% Read the channel file\n% ---------------------\nif isstr( filename )\n\tfid = fopen(filename); \n\tlocations = fscanf(fid,'%d %f %f %s',[7 MAXCHANS]);\n\tfclose(fid);\n\tlocations = locations';\n\tTh = pi/180*locations(:,2);   % convert degrees to rads\n\tRd = locations(:,3);\n\tii = find(Rd <= MAX_RADIUS); % interpolate on-scalp channels only\n\tTh = Th(ii);\n\tRd = Rd(ii);\n\t[x,y] = pol2cart(Th,Rd);\nelse\n\tx = real(filename);\n\ty = imag(filename);\nend;\t\n\n% ---------------------------------------------------\n% Locate nearest position of an electrode in the grid \n% ---------------------------------------------------\nxi = linspace(-0.5,0.5,GRID_SCALE);   % x-axis description (row vector)\nyi = linspace(-0.5,0.5,GRID_SCALE);   % y-axis description (row vector)\nfor i=1:MAXCHANS\n   [useless_var horizidx(i)] = min(abs(y(i) - xi));    % find pointers to electrode\n   [useless_var vertidx(i)] = min(abs(x(i) - yi));     % positions in Zi\nend;\n   \n% -----------------\n% Compute laplacian\n% -----------------\nfor i=1:size(map,2) \n   \t[Xi,Yi,Zi] = griddata(y,x,map(:,i),yi',xi, 'v4');   % interpolate data\n\n   \tlaplac2D = del2(Zi);\n\tpositions = horizidx + (vertidx-1)*GRID_SCALE;\n\tlaplac(:,i) = laplac2D(positions(:));\n\n\t% ------------------\n\t% Draw laplacian map\n\t% ------------------\n\tif exist('draw');\n        mask = (sqrt(Xi.^2+Yi.^2) <= MAX_RADIUS);\n        laplac2D(find(mask==0)) = NaN;\n\n\t\tsubplot(ceil(sqrt(size(map,2))), ceil(sqrt(size(map,2))), i);\n\t\tcontour(laplac2D); \n\t\ttitle( int2str(i) );\n\n% %%% Draw Head %%%%\nax = axis; \nwidth = ax(2)-ax(1);\naxis([ax(1)-width/3 ax(2)+width/3 ax(3)-width/3 ax(4)+width/3])\nsteps = 0:2*pi/100:2*pi;\nbasex = .18*MAX_RADIUS;  \ntip = MAX_RADIUS*1.15; \nbase = MAX_RADIUS-.004;\nEarX = [.497 .510 .518 .5299 .5419 .54 .547 .532 .510 .489];\nEarY = [.0555 .0775 .0783 .0746 .0555 -.0055 -.0932 -.1313 -.1384 -.1199];\n\nHCOLOR = 'k';\nHLINEWIDTH = 1.8;\n\n% Plot Head, Ears, Nose\nhold on\nplot(1+width/2+cos(steps).*MAX_RADIUS*width,...\n     1+width/2+sin(steps).*MAX_RADIUS*width,...\n    'color',HCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % head\n\nplot(1+width/2+[.18*MAX_RADIUS*width;0;-.18*MAX_RADIUS*width],...\n     1+width/2+[base;tip;base]*width,...\n    'Color',HCOLOR,'LineWidth',HLINEWIDTH);                 % nose\n   \nplot(1+width/2+EarX*width,...\n     1+width/2+EarY*width,...\n           'color',HCOLOR,'LineWidth',HLINEWIDTH)           % l ear\nplot(1+width/2-EarX*width,...\n     1+width/2+EarY*width,...\n           'color',HCOLOR,'LineWidth',HLINEWIDTH)           % r ear\n\nhold off\naxis off\n\n\tend;\nend;                   \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/functions/miscfunc/lapplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5544188409623558}}
{"text": "function [label, centroid, dis] = fkmeans(X, k, options)\n% FKMEANS Fast K-means with optional weighting and careful initialization.\n% [L, C, D] = FKMEANS(X, k) partitions the vectors in the n-by-p matrix X\n% into k (or, rarely, fewer) clusters by applying the well known batch\n% K-means algorithm. Rows of X correspond to points, columns correspond to\n% variables. The output k-by-p matrix C contains the cluster centroids. The\n% n-element output column vector L contains the cluster label of each\n% point. The k-element output column vector D contains the residual cluster\n% distortions as measured by total squared distance of cluster members from\n% the centroid.\n%\n% FKMEANS(X, C0) where C0 is a k-by-p matrix uses the rows of C0 as the\n% initial centroids instead of choosing them randomly from X.\n%\n% FKMEANS(X, k, options) allows optional parameter name/value pairs to \n% be specified. Parameters are:\n%\n%   'weight' - n-by-1 weight vector used to adjust centroid and distortion\n%              calculations. Weights should be positive.\n%   'careful' - binary option that determines whether \"careful seeding\"\n%               as recommended by Arthur and Vassilvitskii is used when\n%               choosing initial centroids. This option should be used\n%               with care because numerical experiments suggest it may\n%               be counter-productive when the data is noisy.\n%\n% Notes\n% (1) The careful seeding procedure chooses the first centroid at random\n% from X, and each successive centroid from the remaining points according\n% to the categorical distribution with selection probabilities proportional\n% to the point's minimum squared Euclidean distance from the already chosen\n% centroids. This tends to spread the points out more evenly, and, if the\n% data is made of k well separated clusters, is likely to choose an initial\n% centroid from each cluster. This can speed convergence and reduce the\n% likelihood of getting a bad solution [1]. However, in experiments where\n% 5% uniformly distributed noise data was added to such naturally clustered\n% data the results were frequently worse then when centroids were chosen at\n% random.\n% (2) If, as is possible, a cluster is empty at the end of an iteration,\n% then there may be fewer than k clusters returned. In practice this seems\n% to happen very rarely.\n% (3) Unlike the Mathworks KMEANS this implementation does not perform a\n% final, slow, phase of incremental K-means ('onlinephase') that guarantees\n% convergence to a local minimum. \n%\n% References\n% [1] \"k-means++: The Advantages of Careful Seeding\", by David Arthur and\n% Sergei Vassilvitskii, SODA 2007.\n\nn = size(X,1);\n\n% option defaults\nweight = 0; % uniform unit weighting\ncareful = 0;% random initialization\n\nif nargin == 3\n    if isfield(options, 'weight')\n        weight = options.weight;\n    end\n    if isfield(options,'careful')\n        careful = options.careful;\n    end\nend\n\n% If initial centroids not supplied, choose them\nif isscalar(k)\n    % centroids not specified\n    if careful\n        k = spreadseeds(X, k);\n    else\n        k = X(randsample(size(X,1),k),:);\n    end\nend\n\n% generate initial labeling of points\n[~,label] = max(bsxfun(@minus,k*X',0.5*sum(k.^2,2)));\nk = size(k,1);\n\nlast = 0;\n\nif ~weight\n    % code defactoring for speed\n    while any(label ~= last)\n        % remove empty clusters\n        [~,~,label] = unique(label);\n        % transform label into indicator matrix\n        ind = sparse(label,1:n,1,k,n,n);\n        % compute centroid of each cluster\n        centroid = (spdiags(1./sum(ind,2),0,k,k)*ind)*X;\n        % compute distance of every point to each centroid\n        distances = bsxfun(@minus,centroid*X',0.5*sum(centroid.^2,2));\n        % assign points to their nearest centroid\n        last = label;\n        [~,label] = max(distances);\n    end\n    dis = ind*(sum(X.^2,2) - 2*max(distances)');\nelse\n    while any(label ~= last)\n        % remove empty clusters\n        [~,~,label] = unique(label);\n        % transform label into indicator matrix\n        ind = sparse(label,1:n,weight,k,n,n);\n        % compute centroid of each cluster\n        centroid = (spdiags(1./sum(ind,2),0,k,k)*ind)*X;\n        % compute distance of every point to each centroid\n        distances = bsxfun(@minus,centroid*X',0.5*sum(centroid.^2,2));\n        % assign points to their nearest centroid\n        last = label;\n        [~,label] = max(distances);\n    end\n    dis = ind*(sum(X.^2,2) - 2*max(distances)');\nend\nlabel = label';\n\n% Code below this line reused from the file exchange submission K-means++\n% (http://www.mathworks.com/matlabcentral/fileexchange/28901-k-means) in\n% accordance with the license:\n% vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\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 the\n%       documentation and/or other materials provided with the distribution\n%       \n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n% IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n% THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n% PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n% 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\n% PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n% LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n% \nfunction D = sqrdistance(A, B)\n% Square Euclidean distances between all sample pairs\n% A:  n1 x d data matrix\n% B:  n2 x d data matrix\n% WB: n2 x 1 weights for matrix B\n% D: n2 x n1 pairwise square distance matrix\n%    D(i,j) is the squared distance between A(i,:) and B(j,:)\n% Written by Michael Chen (sth4nth@gmail.com). July 2009.\nn1 = size(A,1); n2 = size(B,2);\nm = (sum(A,1)+sum(B,1))/(n1+n2);\nA = bsxfun(@minus,A,m);\nB = bsxfun(@minus,B,m);\nD = full((-2)*(A*B'));\nD = bsxfun(@plus,D,full(sum(B.^2,2))');\nD = bsxfun(@plus,D,full(sum(A.^2,2)))';\nend\n\nfunction [S, idx] = spreadseeds(X, k)\n% X: n x d data matrix\n% k: number of seeds\n% reference: k-means++: the advantages of careful seeding.\n% by David Arthur and Sergei Vassilvitskii\n% Adapted from softseeds written by Mo Chen (mochen@ie.cuhk.edu.hk), \n% March 2009.\n[n,d] = size(X);\nidx = zeros(k,1);\nS = zeros(k,d);\nD = inf(n,1);\nidx(1) = ceil(n.*rand);\nS(1,:) = X(idx(1),:);\nfor i = 2:k\n    D = min(D,sqrdistance(S(i-1,:),X));\n    idx(i) = find(cumsum(D)/sum(D)>rand,1);\n    S(i,:) = X(idx(i),:);\nend\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/31274-fast-k-means/fkmeans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5544188314352876}}
{"text": "function result = spsym (A, quick)\t\t\t\t\t    %#ok\n%SPSYM determine if a sparse matrix is symmetric, Hermitian, or skew-symmetric.\n%   If so, also determine if its diagonal has all positive real entries.\n%   A must be sparse.\n%\n%   Example:\n%   result = spsym (A) ;\n%   result = spsym (A,quick) ;\n%\n%   If quick = 0, or is not present, then this routine returns:\n%\n%       1: if A is rectangular\n%       2: if A is unsymmetric\n%       3: if A is symmetric, but with one or more A(j,j) <= 0\n%       4: if A is Hermitian, but with one or more A(j,j) <= 0 or with\n%           nonzero imaginary part\n%       5: if A is skew symmetric (and thus the diagonal is all zero as well)\n%       6: if A is symmetric with real positive diagonal\n%       7: if A is Hermitian with real positive diagonal\n%\n%   If quick is nonzero, then the function can return more quickly, as soon as\n%   it finds a diagonal entry that is <= 0 or with a nonzero imaginary part.\n%   In this case, it returns 2 for a square matrix, even if the matrix might\n%   otherwise be symmetric or Hermitian.\n%\n%   Regardless of the value of \"quick\", this function returns 6 or 7 if A is\n%   a candidate for sparse Cholesky.\n%\n%   For an MATLAB M-file function that computes the same thing as this\n%   mexFunction (but much slower), see the get_symmetry function by typing\n%   \"type spsym\".\n%\n%   This spsym function does not compute the transpose of A, nor does it need\n%   to examine the entire matrix if it is unsymmetric.  It uses very little\n%   memory as well (just size-n workspace, where n = size (A,1)).\n%\n%   Examples:\n%       load west0479\n%       A = west0479 ;\n%       spsym (A)\n%       spsym (A+A')\n%       spsym (A-A')\n%       spsym (A+A'+3*speye(size(A,1)))\n%\n%   See also mldivide.\n\n%       function result = get_symmetry (A,quick)\n%       %GET_SYMMETRY: does the same thing as the spsym mexFunction.\n%       % It's just a lot slower and uses much more memory.  This function\n%       % is meant for testing and documentation only.\n%       [m n] = size (A) ;\n%       if (m ~= n)\n%           result = 1 ;            % rectangular\n%           return\n%       end\n%       if (nargin < 2)\n%           quick = 0 ;\n%       end\n%       d = diag (A) ;\n%       posdiag = all (real (d) > 0) & all (imag (d) == 0) ;\n%       if (quick & ~posdiag)\n%           result = 2 ;            % Not a candidate for sparse Cholesky.\n%       elseif (~isreal (A) & nnz (A-A') == 0)\n%           if (posdiag)\n%               result = 7 ;        % complex Hermitian, with positive diagonal\n%           else\n%               result = 4 ;        % complex Hermitian, nonpositive diagonal\n%           end\n%       elseif (nnz (A-A.') == 0)\n%           if (posdiag)\n%               result = 6 ;        % symmetric with positive diagonal\n%           else\n%               result = 3 ;        % symmetric, nonpositive diagonal\n%           end\n%       elseif (nnz (A+A.') == 0)\n%           result = 5 ;            % skew symmetric\n%       else\n%           result = 2 ;            % unsymmetric\n%       end\n\n% With additional outputs, spsym computes the following for square matrices:\n% (in this case \"quick\" is ignored, and set to zero):\n%\n% [result xmatched pmatched nzoffdiag nnzdiag] = spsym(A)\n%\n%   xmatched is the number of nonzero entries for which A(i,j) = conj(A(j,i)).\n%   pmatched is the number of entries (i,j) for which A(i,j) and A(j,i) are\n%   both in the pattern of A (the value doesn't matter).  nzoffdiag is the\n%   total number of off-diagonal entries in the pattern.  nzdiag is the number\n%   of diagonal entries in the pattern.  If the matrix is rectangular,\n%   xmatched, pmatched, nzoffdiag, and nzdiag are not computed (all of them are\n%   returned as zero).  Note that a matched pair, A(i,j) and A(j,i) for i != j,\n%   is counted twice (once per entry).\n\n%   Copyright 2006-2007, Timothy A. Davis\n%   http://www.cise.ufl.edu/research/sparse\n\nerror ('spsym mexFunction not found') ;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/SuiteSparse/CHOLMOD/MATLAB/spsym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.554352219682837}}
{"text": "% Automatic flight control of F8 aircraft using model predictive control\n% and various models\n\n% MPC execution time for sine3 models\n% 83.5243, 188.2009, 2.1348e+03\n% 79.5731, 179.1829, 2.1387e+03\n\nclear all, close all, clc\n\nSystemModel = 'F8';\n\nfigpath = ['../FIGURES/',SystemModel,'/'];mkdir(figpath)\ndatapath = ['../DATA/',SystemModel,'/'];mkdir(datapath)\naddpath('../utils');\n\n%% Load Models\nNvar = 3;\nInputSignalTypeModel = 'sine3';             % Use actuation to collect training data\nInputSignalTypeModel_Validation = 'sine2';  % Use actuation to collect validation data to test for generalization\n\n% DelayDMDc\nModelTypeDMDc = 'DMDc'; % Model: DelayDMDc , DMDc\nload(fullfile(datapath,['EX_',SystemModel,'_SI_',ModelTypeDMDc,'_',InputSignalTypeModel,'.mat'])) \nModels.DelayDMDc = Model;\n\n% SINDYc\nload(fullfile(datapath,['EX_',SystemModel,'_SI_SINDYc','_',InputSignalTypeModel,'.mat'])) \nModels.SINDYc = Model;\n\n% NARX\nNARX_SUBSTRACT_MEAN = 0;\nload(fullfile(datapath,['EX_',SystemModel,'_SI_NARX','_',InputSignalTypeModel,'.mat'])) \nModels.NARX = Model;\n\n\n%% Get training data\nENSEMBLE_DATA = 0;\nONLY_TRAINING_LENGTH = 1;\nInputSignalType = InputSignalTypeModel;\nNdelay = Models.DelayDMDc.Ndelay;\ngetTrainingData\n\n%% Get validation data: Model comparison\nInputSignalType = InputSignalTypeModel_Validation;\nNdelay = Models.DelayDMDc.Ndelay;\ntspanV =[tspan(end):dt:150];\n\n% Forcing\nif strcmp(InputSignalTypeModel_Validation,'sine2')\n    forcing = @(x,t) [(.05* (sin(0.7*t).*sin(.1*t).*sin(.2*t).*sin(.05*t)) )];\nelseif strcmp(InputSignalTypeModel_Validation,'sine3')\n    forcing = @(x,t) (.5*sin(5*t).*sin(.5*t)+0.1).^3;\nend\n\n% Reference\n[tA,xA] = ode45(@(t,x)F8Sys(t,x,forcing(x,t)),tspanV,x(end,1:3),options);   % true model\nu_valid = forcing(0,tA)';\n\n% DelayDMDc / DMDc\nif Ndelay == 1\n    x0      = [x(end,1:Nvar)];\n    Hunew   = [u(end),u_valid(1:end-1)];\n    [xB,tB] = lsim(Models.DelayDMDc.sys,Hunew,tspanV,[x0-[Models.DelayDMDc.xmean]]');\nelseif Ndelay > 1\n    x0      = [x(end-Ndelay+1,1:Nvar),x(end,1:Nvar)];\n    Hunew   = [ u(end-Ndelay+1:end),u_valid(1:end-Ndelay);\n        u(end),u_valid(1:end-1)];\n    [xB,tB] = lsim(Models.DelayDMDc.sys,Hunew,tspanV,[x0-[Models.DelayDMDc.xmean]]');\n    xB = xB(:,Nvar+1:2*Nvar); xB = xB + repmat(xmean,[size(xB,1) 1]);\nend\nxB = xB + repmat(Models.DelayDMDc.xmean,[length(tB) 1]);\n\n% SINDYc\n[tC,xC]=ode45(@(t,x)sparseGalerkinControl(t,x,forcing(x,t),Models.SINDYc.Xi(:,1:Nvar),Models.SINDYc.polyorder,Models.SINDYc.usesine),tspanV,x(end,1:Nvar),options);  % approximate\n\n% NARX\nUdummy = [u(end),u_valid(1:end)];\nHdummy = zeros(Nvar,size(Udummy,2));\nif NARX_SUBSTRACT_MEAN == 1\n    NARX_xmean = Models.NARX.xmean;\nelse\n    NARX_xmean = zeros(size(Models.NARX.xmean'));\nend\n\nHdummy(:,1) = x(end,1:Nvar)'-NARX_xmean';\n[Us,Ui,Si] = preparets(Models.NARX.net,con2seq(Udummy),{},con2seq(Hdummy));\nxD = Models.NARX.net(Us,Ui,Si); % Predict on validation data\nxD = cell2mat(xD)'; xD = [x0;xD(1:end-1,:)]; \nxD(2:end,:) = xD(2:end,:) + repmat(NARX_xmean,[size(xD,1)-1 1]);\n\n%% Show results\nclear ph\nh = figure;\nsubplot(3,1,1), box on, hold on\nplot([tB(1) tB(1)],[-100 100],'--k')\nplot(t,x(:,1),'Color',[.4 .4 .4],'LineWidth',1.5);\nplot(tA,xA(:,1),'k','LineWidth',1.5);\nplot(tB,xB(:,1),'r-','LineWidth',1.5);\nplot(tC,xC(:,1),'g--','LineWidth',1.5);\nplot(tA(1:end),xD(:,1),'-.','Color',[0.7,0.7,1],'LineWidth',1.5);\ngrid on\nylim([-0.4 0.3])\nylabel('x_1','FontSize',13)\nset(gca,'FontSize',13)\n\nsubplot(3,1,2), box on, hold on\nplot([tB(1) tB(1)],[-100 100],'--k')\nplot(t,x(:,2),'Color',[.4 .4 .4],'LineWidth',1.5);\nplot(tA,xA(:,2),'k','LineWidth',1.5);\nplot(tB,xB(:,2),'r-','LineWidth',1.5);\nplot(tC,xC(:,2),'g--','LineWidth',1.5);\nplot(tA(1:end),xD(:,2),'-.','Color',[0.7,0.7,1],'LineWidth',1.5);\nylim([-4 0.1])\nset(gca,'FontSize',13)\nylabel('x_2','FontSize',13)\n\nsubplot(3,1,3), box on, hold on\nplot([tB(1) tB(1)],[-100 100],'--k')\nph(1) = plot(t,x(:,3),'Color',[.4 .4 .4],'LineWidth',1.5);\nph(2) = plot(tA,xA(:,3),'k','LineWidth',1.5);\nph(3) = plot(tB,xB(:,3),'r-','LineWidth',1.5);\nph(4) = plot(tC,xC(:,3),'g--','LineWidth',1.5);\nph(5) = plot(tA(1:end),xD(:,3),'-.','Color',[0.7,0.7,1],'LineWidth',1.5);\nl1=legend(ph,'Training','Validation',ModelTypeDMDc,'SINDYc','NARX');\nset(l1,'Location','NorthWest')\ngrid on\nylim([-0.9 0.5])\nylabel('x_3','FontSize',13)\nset(gca,'FontSize',13)\nxlabel('Time','FontSize',13)\n\n\nset(h,'Units','Inches');\nset(gcf,'Position',[1 1 6. 5.5])\npos = get(h,'Position');\nset(h,'PaperPositionMode','Auto','PaperSize',[pos(3), pos(4)])\nprint(h,'-painters','-depsc2',  '-loose','-cmyk', [figpath,'EX_',SystemModel,'_SI_Comparison_Validation_',InputSignalTypeModel,'_',InputSignalType,'.eps'],'-r0');\n\n\n%% Actuation signal\nt_valid = tspanV;\nclear ph\nfigure,box on, hold on,\nccolors = get(gca,'colororder');\nplot([tA(1),tA(1)],[-15 260],':','Color',[0.4,0.4,0.4],'LineWidth',1.5)\nplot(t,u,'-k','LineWidth',1);\nplot(t_valid,u_valid,'-k','LineWidth',1);\ngrid off\nylim([min([u u_valid])+0.05*min([u u_valid]) max([u u_valid])+0.05*max([u u_valid])])\nxlim([0 t_valid(end)])\nxlabel('Time')\nylabel('Input')\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto')\nprint('-depsc2', '-loose','-cmyk', [figpath,'EX_',SystemModel,'_SI_Comparison_Validation_',InputSignalTypeModel,'_',InputSignalType,'_Actuation.eps']);\n\n%% True SINDYc model parameters\nXi0 = zeros(size(Models.SINDYc.Xi));\nXi0([2,4,5,6,8,10,16,18,19,25,35],1) = [-0.877,1,-0.215,0.47,-0.088,-0.019,3.846,-1,0.28,0.47,0.63];\nXi0([4],2) = 1;\nXi0([2,4,5,6,16,19,25,35],3) = [-4.208,-0.396,-20.967,-0.47,-3.564,6.265,46,61.4];\n\n%% MPC\n% Parameters MPC\noptions = optimoptions('fmincon','Algorithm','sqp','Display','none', ...\n    'MaxIterations',100);\nDuration = 6;                   % Run for 'Duration' time units\nTon = 0;                        % Time units when control is turned on\ngetMPCparams\n          \nx0n=[0.1 0 0]'; %xA(end,:)';    % Initial condition\nTcontrol = tA(end);             % Time offset to combine training, prediction and control phase\n\n% Parameters Models\nModelCollection = {ModelTypeDMDc, 'SINDYc', 'NARX'}; % 51.8924, 46.0083, 1.4662e+03 execution times\nNmodels = length(ModelCollection);\n\nclear Results\nResults(1:Nmodels) = struct('x',[], 'u', [], 't', [], 'xref', [], 'J', [], 'elapsed_time', []);\n\nTs = Models.SINDYc.dt;\n\n%%\nfor iM = 1:Nmodels\n    select_model = ModelCollection{iM}; % DelayDMDc; DMDc; NARX ; SINDYc\n    \n    % Prepare variables\n    Nt = (Duration/Ts)+1;\n    uopt0    = 0;\n    xhat     = x0n;\n    uopt     = uopt0.*ones(Nu,1);\n    xHistory = zeros(Nvar,Nt); xHistory(:,1) = xhat;\n    uHistory = zeros(1,Nt); uHistory(1)   = uopt(1);\n    tHistory = zeros(1,Nt); tHistory(1)   = Tcontrol;\n    rHistory = zeros(1,Nt);\n    \n    % Parameters Model\n    switch select_model\n        case 'DelayDMDc'\n            pest.dt     = Models.DelayDMDc.dt;\n            pest.sys    = Models.DelayDMDc.sys;\n            pest.xmean  = xmean';\n            pest.udelay = zeros(1,N);\n            pest.xdelay = [x(end-Ndelay+1,1:2)]';\n            pest.Nxlim  = size(x,1);\n        case 'DMDc'\n            pest.dt = Models.DelayDMDc.dt;\n            pest.sys = Models.DelayDMDc.sys;\n            pest.xmean = Models.DelayDMDc.xmean';\n            pest.Nxlim = size(x,1);  \n        case 'SINDYc'\n            pest.ahat = Models.SINDYc.Xi(:,1:Nvar); % Replace with Xi0 to test true model\n            pest.polyorder = Models.SINDYc.polyorder;\n            pest.usesine = Models.SINDYc.usesine;\n            pest.dt = Models.SINDYc.dt;\n        case 'NARX'\n            pest.net = Models.NARX.net;\n            pest.Ndelay = 1;\n            pest.udelay = zeros(1,Ndelay);\n            pest.xdelay = zeros(2,length(pest.udelay));\n            pest.xdelay(:,1:Ndelay) = [x(end-Ndelay+1:end,1:2)]';\n            pest.Nxlim = size(x,1);\n    end\n    \n    \n    % Start simulation\n    fprintf('Simulation started.  It might take a while...\\n')\n    tic\n    for ct = 1:(Duration/Ts)\n        \n        % Set references over prediction horizon\n        tref = (ct:ct+N-1).*Ts;\n        xref = [xrefFUN(tref); zeros(1,N); zeros(1,N)];\n        \n        % NMPC with full-state feedback\n        COSTFUN = @(u) ObjectiveFCN_models(u,xhat,N,Nu,xref,uHistory(:,ct),pest,diag(Q),R,Ru,select_model);\n        CONSFUN = @(u) ConstraintFCN_models(u,uHistory(:,ct),xhat,N,LBo,UBo,LBdu,UBdu,pest,select_model);\n        uopt = fmincon(COSTFUN,uopt,[],[],[],[],LB,UB,CONSFUN,options);\n        \n        % Run without constraints\n%         uopt = fmincon(COSTFUN,uopt,[],[],[],[],[],[],[],options);        \n        \n        % Integrate system\n        xhat = rk4u(@F8Sys,xhat,uopt(1),Ts/10,10,[],0); \n        xHistory(:,ct+1) = xhat;\n        uHistory(:,ct+1) = uopt(1);\n        tHistory(:,ct+1) = ct*Ts+Tcontrol;\n        rHistory(:,ct+1) = xref(1,2);\n       \n    end\n    tElapsed = toc    \n    fprintf('Simulation finished!\\n')\n    \n    % Collect results\n    Results(iM).eval_time = tElapsed;\n    Results(iM).xref = rHistory;\n    Results(iM).x = xHistory;\n    Results(iM).u = uHistory;\n    Results(iM).t = tHistory;\n    Results(iM).J = evalObjectiveFCN(Results(iM).u,Results(iM).x,Results(iM).xref,diag(Q),R,Ru);\n    Results(iM).elapsed_time = tElapsed;\n\n    VIZ_SI_Validation_MPC\n    \n    if iM==Nmodels % Plot ensemble training for NN / NARX\n       VIZ_SI_Validation_MPC_ensemble(ct,t_valid,u_valid,xHistory,tHistory,uHistory,Results,t,tA,xA,xB,xC,xD,select_model,SystemModel,figpath,N,InputSignalTypeModel,Nmodels,ModelCollection)\n    end\n    \nend\n\n% MPC Execution times using N=10: 120.9128, 96.8967, 2.1755e+03\n\n%% Unforced\n[tU,xU] = ode45(@(t,x)F8Sys(t,x,0,[]),tHistory,xA(end,1:3),options);   % true model\n\n%% Show cost\nclear ph\nfigure, hold on, box on\nph(1) = plot(Results(1).t,cumsum(Results(1).J),'-r','LineWidth',2);\nph(3) = plot(Results(1).t,cumsum(Results(3).J),'-.','Color',[0.7,0.7,1],'LineWidth',2);\nph(2) = plot(Results(1).t,cumsum(Results(2).J),'--g','LineWidth',2);\n\nxlim([Results(1).t(1) Results(1).t(end)])\nylabel('Cost','FontSize',14)\nxlabel('Time','FontSize',14)\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto')\n\nprint('-depsc2', '-loose','-cmyk', [figpath,'EX_',SystemModel,'_SI_Comparison_Validation_',InputSignalTypeModel,'_',InputSignalType,'_Cost','_N_',num2str(N),'.eps']);\n    \n\n%% Show control stage separate\nclear ph\nfigure, hold on, box on\nph(4) = plot(Results(1).t(2:end),(Results(1).xref(2:end)),'-k','LineWidth',2);\nph(1) = plot(Results(1).t,(Results(1).x(1,:)),'-r','LineWidth',2);\nph(3) = plot(Results(1).t,(Results(3).x(1,:)),'-.','Color',[0.7,0.7,1],'LineWidth',2);\nph(2) = plot(Results(1).t,(Results(2).x(1,:)),'--g','LineWidth',2);\n\nl1=legend(ph,ModelCollection,'Ref');\nset(l1,'Location','NorthEast')\nxlim([Results(1).t(1) Results(1).t(end)])\nylim([-0.25 .25])\nylabel('AoA','FontSize',14)\nxlabel('Time','FontSize',14)\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto')\n\nprint('-depsc2', '-loose','-cmyk', [figpath,'EX_',SystemModel,'_SI_Comparison_',InputSignalTypeModel,'_',InputSignalType,'_AoA','_N_',num2str(N),'.eps']);\n\nclear ph\nfigure, hold on, box on\nph(1) = plot(Results(1).t,(Results(1).u(:)),'-r','LineWidth',2);\nph(3) = plot(Results(1).t,(Results(3).u(:)),'-.','Color',[0.7,0.7,1],'LineWidth',2);\nph(2) = plot(Results(1).t,(Results(2).u(:)),'--g','LineWidth',2);\n\nxlim([Results(1).t(1) Results(1).t(end)])\nylabel('Input','FontSize',14)\nxlabel('Time','FontSize',14)\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto')\n\nprint('-depsc2', '-loose','-cmyk', [figpath,'EX_',SystemModel,'_SI_Comparison_',InputSignalTypeModel,'_',InputSignalType,'_Input','_N_',num2str(N),'.eps']);\n\n\n%% Save results\nsave(fullfile(datapath,['MPC_',SystemModel,'_Results_AllModels_',InputSignalTypeModel,'_',InputSignalType,'_N_',num2str(N),'.mat']),'Results')\nsave(fullfile(datapath,['MPC_',SystemModel,'_Results_AllModels_',InputSignalTypeModel,'_',InputSignalType,'_All','_N_',num2str(N),'.mat']))", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/EX_FLIGHT_CONTROL_F8/MPC_F8_ModelComparison.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.5543522071464393}}
{"text": "function Ne = som_neighborhood(Ne1,n)\n\n%SOM_NEIGHBORHOOD Calculate neighborhood matrix.\n%\n% Ne = som_neighborhood(Ne1,n)\n% \n%  Ne = som_neighborhood(Ne1);\n%  Ne = som_neighborhood(som_unit_neighs(topol),2);\n%\n%  Input and output arguments ([]'s are optional): \n%   Ne1       (matrix, size [munits m]) a sparse matrix indicating\n%                      the units in 1-neighborhood for each map unit\n%   [n]       (scalar) maximum neighborhood which is calculated, default=Inf\n% \n%   Ne        (matrix, size [munits munits]) neighborhood matrix,\n%                      each row (and column) contains neighborhood\n%                      values from the specific map unit to all other\n%                      map units, or Inf if the value is unknown.\n%\n% For more help, try 'type som_neighborhood' or check out online documentation.\n% See also SOM_UNIT_NEIGHS, SOM_UNIT_DISTS, SOM_UNIT_COORDS, SOM_CONNECTION.\n\n%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% som_neighborhood\n%\n% PURPOSE\n%\n% Calculate to which neighborhood each map unit belongs to relative to\n% each other map unit, given the units in 1-neighborhood of each unit.\n%\n% SYNTAX\n%\n%  Ne = som_neighborhood(Ne1);\n%  Ne = som_neighborhood(Ne1,n);\n%\n% DESCRIPTION\n%\n% For each map unit, finds the minimum neighborhood to which it belongs\n% to relative to each other map unit. Or, equivalently, for each map \n% unit, finds which units form its k-neighborhood, where k goes from \n% 0 to n. \n%\n% The neighborhood is calculated iteratively using the reflexivity of\n% neighborhood.\n%     let  N1i  be the 1-neighborhood set a unit i\n% and let  N11i be the set of units in the 1-neighborhood of any unit j in N1i\n%     then N2i  (the 2-neighborhood set of unit i) is N11i \\ N1i\n%\n% Consider, for example, the case of a 5x5 map. The neighborhood in case of\n% 'rect' and 'hexa' lattices (and 'sheet' shape) for the unit at the\n% center of the map are depicted below: \n% \n%   'rect' lattice           'hexa' lattice\n%   --------------           --------------\n%   4  3  2  3  4            3  2  2  2  3\n%   3  2  1  2  3             2  1  1  2  3\n%   2  1  0  1  2            2  1  0  1  2\n%   3  2  1  2  3             2  1  1  2  3\n%   4  3  2  3  4            3  2  2  2  3\n% \n% Because the iterative procedure is rather slow, the neighborhoods \n% are calculated upto given maximal value. The uncalculated values\n% in the returned matrix are Inf:s.\n% \n% REQUIRED INPUT ARGUMENTS\n% \n%  Ne1   (matrix) Each row contains 1, if the corresponding unit is adjacent \n%                 for that map unit, 0 otherwise. This can be calculated \n%                 using SOM_UNIT_NEIGHS. The matrix can be sparse.\n%                 Size munits x munits.\n%\n% OPTIONAL INPUT ARGUMENTS\n%\n%  n     (scalar) Maximal neighborhood value which is calculated, \n%                 Inf by default (all neighborhoods).\n%\n% OUTPUT ARGUMENTS\n%\n%  Ne    (matrix) neighborhood values for each map unit, size is\n%                 [munits, munits]. The matrix contains the minimum\n%                 neighborhood of unit i, to which unit j belongs, \n%                 or Inf, if the neighborhood was bigger than n.\n%\n% EXAMPLES\n%\n%  Ne = som_neighborhood(Ne1,1);    % upto 1-neighborhood\n%  Ne = som_neighborhood(Ne1,Inf);  % all neighborhoods\n%  Ne = som_neighborhood(som_unit_neighs(topol),4);\n%\n% SEE ALSO\n% \n%  som_unit_neighs   Calculate units in 1-neighborhood for each map unit.\n%  som_unit_coords   Calculate grid coordinates.\n%  som_unit_dists    Calculate interunit distances.\n%  som_connection    Connection matrix.\n\n% Copyright (c) 1999-2000 by the SOM toolbox programming team.\n% http://www.cis.hut.fi/projects/somtoolbox/\n\n% Version 1.0beta juuso 141097\n% Version 2.0beta juuso 101199\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Check arguments \n\nerror(nargchk(1, 2, nargin));\n\nif nargin<2, n=Inf; end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Action\n\n% initialize\nif issparse(Ne1), Ne = full(Ne1); else Ne = Ne1; end\nclear Ne1\n[munits dummy] = size(Ne);\nNe(find(Ne==0)) = NaN;\nfor i=1:munits, Ne(i,i)=0; end\n\n% Calculate neighborhood distance for each unit using reflexsivity\n% of neighborhood: \n%   let  N1i be the 1-neighborhood set a unit i\n%   then N2i is the union of all map units, belonging to the \n%        1-neighborhood of any unit j in N1i, not already in N1i\nk=1; \nif n>1, \n  fprintf(1,'Calculating neighborhood: 1 '); \n  N1 = Ne; \n  N1(find(N1~=1)) = 0;   \nend\nwhile k<n && any(isnan(Ne(:))),\n  k=k+1;\n  fprintf(1,'%d ',k);\n  for i=1:munits,\n    candidates = isnan(Ne(i,:));              % units not in any neighborhood yet\n    if any(candidates), \n      prevneigh = find(Ne(i,:)==k-1);         % neighborhood (k-1)\n      N1_of_prevneigh = any(N1(prevneigh,:)); % union of their N1:s\n      Nn = find(N1_of_prevneigh & candidates); \n      if length(Nn), Ne(i,Nn) = k; Ne(Nn,i) = k; end\n    end\n  end\nend\nif n>1, fprintf(1,'\\n'); end\n\n% finally replace all uncalculated distance values with Inf\nNe(find(isnan(Ne))) = Inf;\n\nreturn;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% faster version? \n\nl = size(Ne1,1); Ne1([0:l-1]*(l+1)+1) = 1; Ne = full(Ne1); M0 = Ne1; k = 2; \nwhile any(Ne(:)==0), M1=(M0*Ne1>0); Ne(find(M1-M0))=k; M0=M1; k=k+1; end\nNe([0:l-1]*(l+1)+1) = 0;\n", "meta": {"author": "ilarinieminen", "repo": "SOM-Toolbox", "sha": "f2597abc1ae33c2060e0443d49e854011ff21831", "save_path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox", "path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox/SOM-Toolbox-f2597abc1ae33c2060e0443d49e854011ff21831/som/som_neighborhood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5543522028040337}}
{"text": "%% Copyright (C) 2016-2017 Lagu\n%% Copyright (C) 2017, 2019, 2022 Colin B. Macdonald\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see <http://www.gnu.org/licenses/>.\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defmethod @@sym ellipticK (@var{m})\n%% Complete elliptic integral of the first kind.\n%%\n%% The complete elliptic integral of the first kind\n%% with parameter @var{m} is defined by:\n%% @example\n%% @group\n%% syms m\n%% ellipticK (m)\n%%   @result{} ans = (sym) K(m)\n%% @end group\n%%\n%% @group\n%% rewrite (ans, 'Integral')         % doctest: +SKIP\n%%   @result{} ans = (sym)\n%%       \u03c0\n%%       \u2500\n%%       2\n%%       \u2320\n%%       \u23ae         1\n%%       \u23ae \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 d\u03b1\n%%       \u23ae    _______________\n%%       \u23ae   \u2571          2\n%%       \u23ae \u2572\u2571  1 - m\u22c5sin (\u03b1)\n%%       \u2321\n%%       0\n%% @end group\n%% @end example\n%%\n%% Examples:\n%% @example\n%% @group\n%% diff (ellipticK (m), m)\n%%   @result{} (sym)\n%%       -(1 - m)\u22c5K(m) + E(m)\n%%       \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n%%           2\u22c5m\u22c5(1 - m)\n%% @end group\n%%\n%% @group\n%% vpa (ellipticK (sym (pi)/4))\n%%   @result{} (sym) 2.2252536839853959577044373301346\n%% @end group\n%% @end example\n%%\n%% There are other conventions for the inputs of elliptic integrals,\n%% @pxref{@@sym/ellipticF}.\n%%\n%% @seealso{@@sym/ellipke, @@sym/ellipticF, @@sym/ellipticE, @@sym/ellipticPi}\n%% @end defmethod\n\n\nfunction y = ellipticK (m)\n  if (nargin > 1)\n    print_usage ();\n  end\n\n  % y = ellipticF (sym (pi)/2, m);\n  y = elementwise_op ('elliptic_k', m);\n\nend\n\n\n%!error ellipticK (sym(1), 2)\n\n%!assert (isequal (ellipticK (sym (0)), sym (pi)/2))\n%!assert (isequal (ellipticK (sym (-inf)), sym (0)))\n\n%!assert (double (ellipticK (sym (1)/2)), 1.854074677, 10e-10)\n%!assert (double (ellipticK (sym (pi)/4)), 2.225253684, 10e-10)\n%!assert (double (ellipticK (sym (-55)/10)), 0.9324665884, 10e-11)\n\n%!test\n%! % compare to double ellipke\n%! m = 1/5;\n%! ms = sym(1)/5;\n%! [K, E] = ellipke (m);\n%! assert (double (ellipticK (ms)), K, -1e-15)\n%! assert (double (ellipticE (ms)), E, -1e-15)\n\n%!test\n%! % compare to double ellipke\n%! if (exist ('OCTAVE_VERSION', 'builtin'))\n%! m = -10.3;\n%! ms = -sym(103)/10;\n%! [K, E] = ellipke (m);\n%! assert (double (ellipticK (ms)), K, -1e-15)\n%! assert (double (ellipticE (ms)), E, -1e-15)\n%! end\n\n%!test\n%! % compare to Maple\n%! us = vpa (ellipticK (sym (7)), 40);\n%! % > evalf(EllipticK(sqrt(7)), 40);\n%! maple = vpa ('0.6168027921799632674669917683443602673441', 40) - ...\n%!         vpa ('0.9114898734184488922164103102629560336918j', 40);\n%! assert (abs (double (maple - us)), 0, 1e-39)\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/ellipticK.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.554352202558624}}
{"text": "function out=errorplot(x,y,dy,plottypes,dx);\n% \n%  2 dimensional plot with error bars\n%\n%\tBy: P.S.Basran\t\t6/17/03\n%\n%       Toronto-Sunnybrook Cancer Centre\n%       Dept. Medical Physics\n%       Parminder.Basran@sw.ca\n%\n%\n%\t\n%\tFunction:\n%\t\tThis function produces a two dimensional plot with error bars.\n%\t\t\n%\tSyntax:\n% \t\tout=errorplot(x,y,dy,plottypes,dx)\n%\n%\tInputs:\n%\t\t    x - is a [1 x n] dimensional vector\n%           y - is a [m x n] dimensional matrix for multidimensional plots\n%          dy - is a [m x n] dimensional matrix whose dimensions must match those of y\n%   plottypes - is a [1 x 4] dimensional vector whose entries specify the plottype in the\n%               same fashion as the variable 's' in the function plot(x,y,s).\n%               NOTE: current version of this requires the plottype to be specified in \n%               all instances, and to be 4 characters in length.\n%          dx - is a real number that specifices the dimensions of the horizontal tics\n%               for each error bar. The default value is 0.25 the dimension of x.\n%\n%\tOutputs:\n%\t\t   - plot with legend, labeled '1', '2', etc.\n%\n%   Example:\n%\n%           %For a single plot:\n%\n%           x=[-10:1:10];\n%           y1=x.^2;\n%           dy1=0.3*y1.*rand(size(x)); % \n%           plottype1=[':   '];\n%           errorplot(x,y1,dy1,plottype1);\n%\n%           % For multiple plots:\n%\n%           y2=0.5*x.^2;\n%           dy2=0.2*y2.*rand(size(x)); % \n%           plottype2=['o-- '];\n%           y=[y1; y2];\n%           dy=[dy1; dy2];\n%           errorplot(x,y,dy,[plottype1 plottype2],1);\n%\n\n%   Modification Log:\n%       June 17 - 2003: alpha version\n%       March 11 - 2004: fix for the plottypes ....thanks to Sean Verret\n%\n\n\nerror(nargchk(2,5,nargin));\n\nif nargin <5, dx=(x(2)-x(1))/4;\n    if nargin < 4, plottypes='';\n        if nargin < 3, dy='';\n            [a,b]=size(y);\n            for i=1:a, plot(x,y(i,:)); end % default to a regular plot for 2 inputs \n        end, end, end\n\n%Provide plot and legend\n[a,b]=size(y);\nif a>b,\n    y=y';\n    [a,b]=size(y);\nend\n\ntx=[];\nfor i=1:a,\n    plot(x,y(i,:),plottypes(4*(i-1)+1:4*i));;\n    tx=[tx; 'plot ' num2str(i)];\n    hold on;\nend\nlegend(tx);\n\n%Now the error bars\nfor i=1:a,\n    for j=1:b,\n        %horizontal lines\n        line([x(j) x(j)], [y(i,j)-dy(i,j) y(i,j)+dy(i,j)]);\n        %top vertical line\n        line([x(j)-dx x(j)+dx], [y(i,j)+dy(i,j) y(i,j)+dy(i,j)]);\n        %bottom vertical line\n        line([x(j)-dx x(j)+dx], [y(i,j)-dy(i,j) y(i,j)-dy(i,j)]);\n     end\nend\n\nhold off", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3612-errorplot-m/errorplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.5543521984616281}}
{"text": "%compute sumspinerelangle\n\nfunction [data,units]=compute_sumspinerelangle(trx,n)\n\nlarvae=trx.exp2flies{n};\nnumlarvae=numel(larvae);\nspineangles=cell(1,numlarvae);\nspinerelangle=cell(1,numlarvae);\nsumspinerelangle=cell(1,numlarvae);\nfor i=1:numlarvae\n    larva=larvae(i);\n    spineangles{1,i}=bsxfun(@atan2,trx(larva).yspine_mm(1:end-1,:)-trx(larva).yspine_mm(2:end,:),trx(larva).xspine_mm(1:end-1,:)-trx(larva).xspine_mm(2:end,:));\n    % spinerelangle{1,i}=bsxfun(@atan2,sin(spineangles{1,i}(2:end,:))-sin(spineangles{1,i}(1:end-1,:)),cos(spineangles{1,i}(2:end,:))-cos(spineangles{1,i}(1:end-1,:)));\n    % KB: this method of measuring the difference between angles didn't\n    % make sense to me. \n    spinerelangle{1,i} = modrange(-diff(spineangles{i},1,1),-pi,pi);\n    sumspinerelangle{1,i}=sum(spinerelangle{1,i},1);\nend\n\nunits=parseunits('rad');\ndata=sumspinerelangle;", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/larva_compute_perframe_features/compute_sumspinerelangle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5543118994687893}}
{"text": "function [x, infos] = div_mu_partial_nmf(V, rank, in_options)\n%\n% This file is part of NMFLibrary\n%\n% Created by H.Kasai on Feb. 16, 2017\n%\n% Change log: \n%\n%       June 16, 2022 (Hiroyuki Kasai): Initial version.\n%\n%       Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n    % set dimensions and samples\n    [m, n] = size(V);\n \n    % set local options\n    local_options = [];\n    local_options.alg           = 'mu';\n    local_options.norm_h        = 0;\n    local_options.norm_w        = 1;    \n    local_options.alpha         = 2;\n    local_options.delta         = 0.1;\n    local_options.metric_type   = 'kl-div'; % 'kl-div' (default)\n    local_options.d_alpha       = -1; % for alpha divergence\n    local_options.d_beta        = 0; % for beta divergence \n    local_options.myeps         = 1e-16;\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 ~strcmp(options.alg, 'mu')\n        fprintf('Invalid algorithm: %s. Therfore, we use mu (i.e., multiplicative update).\\n', options.alg);\n        options.alg = 'mu';\n    end\n\n    % initialize factors\n    init_options = options;\n    [init_factors, ~] = generate_init_factors(V, rank, init_options);    \n    W = init_factors.W;\n    H = init_factors.H;      \n    \n    % initialize\n    method_name = sprintf('MU-Partial (%s:%s)', options.alg, options.metric);\n    epoch = 0;    \n    grad_calc_count = 0; \n\n    if options.verbose > 0\n        fprintf('# %s: started ...\\n', method_name);           \n    end       \n  \n    % store initial info\n    clear infos;\n%     if strcmp(options.metric, 'alpha-div')\n%         metric_param = options.d_alpha;\n%     elseif strcmp(options.metric, 'beta-div')\n%         metric_param = options.d_beta;        \n%     end\n    [infos, f_val, optgap] = store_nmf_info(V, W, H, [], options, [], epoch, grad_calc_count, 0);\n    \n    if options.verbose > 1\n        fprintf('MU-Partial (%s:%s): Epoch = 0000, cost = %.16e, optgap = %.4e\\n', options.alg, options.metric, f_val, optgap); \n    end  \n\n    % set start time\n    start_time = tic();\n\n    % main loop\n    while true\n        \n        % check stop condition\n        [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n        if stop_flag\n            display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n            break;\n        end        \n\n        if strcmp(options.alg, 'mu')\n            if strcmp(options.metric, 'euc')\n                \n                % update H\n                H = H .* (W' * V) ./ (W' * W * H);\n                H = H + (H<options.myeps) .* options.myeps;\n\n                % update W\n                W(:, options.updateW) = W(:, options.updateW) .* (V * H(options.updateW, :)') ...                \n                    ./ (W * (H * H(options.updateW, :)'));                \n                W = W + (W<options.myeps) .* options.myeps;\n                \n            elseif strcmp(options.metric, 'kl-div')\n                \n                % update W\n                W(:, options.updateW) = W(:, options.updateW) .* ...\n                    ((V./(W*H + options.myeps))*H(options.updateW, :)')./(ones(m,1)*sum(H(options.updateW, :)'));\n                if options.norm_w ~= 0\n                    W = normalize_W(W, options.norm_w);\n                end                \n                \n                % update H\n                H = H .* (W'*(V./(W*H + options.myeps)))./(sum(W)'*ones(1,n));\n                if options.norm_h ~= 0\n                    H = normalize_H(H, options.norm_h);\n                end                    \n\n            elseif strcmp(options.metric, 'alpha-div')\n                \n                % update W\n                W(:, options.updateW) = W(:, options.updateW) .* ...\n                    ( ((V+options.myeps) ./ (W*H+options.myeps)).^options.d_alpha * H(options.updateW, :)').^(1/options.d_alpha);\n                if options.norm_w ~= 0\n                    W = normalize_W(W, options.norm_w);\n                end\n                W = max(W, options.myeps);\n\n                % update H\n                H = H .* ( (W'*((V+options.myeps)./(W*H+options.myeps)).^options.d_alpha) ).^(1/options.d_alpha);\n                if options.norm_h ~= 0\n                    H = normalize_H(H, options.norm_h);\n                end\n                H = max(H, options.myeps);\n                \n            elseif strcmp(options.metric, 'beta-div')\n\n                WH = W * H;\n                \n                % update W\n                W(:, options.updateW) = W(:, options.updateW) .* ...\n                    ( ((WH.^(options.d_beta-2) .* V)*H(options.updateW, :)') ./ ...\n                    max(WH.^(options.d_beta-1)*H(options.updateW, :)', options.myeps) );\n\n                             \n                if options.norm_w ~= 0\n                    W = normalize_W(W, options.norm_w);\n                end\n                \n                WH = W * H;\n\n                % update H\n                H = H .* ( (W'*(WH.^(options.d_beta-2) .* V)) ./ max(W'*WH.^(options.d_beta-1), options.myeps) );\n                if options.norm_h ~= 0\n                    H = normalize_H(H, options.norm_h);\n                end \n            else\n                error('Invalid metric.')\n            end            \n    \n        end\n        \n        % measure elapsed time\n        elapsed_time = toc(start_time);        \n        \n        % measure gradient calc count\n        grad_calc_count = grad_calc_count + m*n;\n\n        % update epoch\n        epoch = epoch + 1;         \n        \n        % store info\n        infos = store_nmf_info(V, W, H, [], options, infos, epoch, grad_calc_count, elapsed_time);  \n        \n        % display info\n        display_info(method_name, epoch, infos, options);     \n        \n    end\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/divergence/div_mu_partial_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5543118874826946}}
{"text": "function x=v_usasi(n,fs)\n%V_USASI generates N samples of USASI noise at sample frequency FS X=(N,FS)\n\n% This routine is based on the USASI noise defined in [1] which was later\n% reissued as [2]. USASI noise is intended to simulate the long-term average\n% of typical audio program material. The routine does not currently implement\n% the pulsation at 2.5Hz 12.5% duty cycle that is recommended by the standard.\n% Also it should probably be scaled to a well-defined power.\n%\n%  [1] NRSC AM Reemphasis, Deemphasize, and Broadcast Audio Transmission Bandwidth Specifications,\n%      EIA-549 Standard, Electronics Industries Association , July 1988.\n%  [2] NRSC AM Reemphasis, Deemphasize, and Broadcast Audio Transmission Bandwidth Specifications,\n%      NRSC-1-A Standard, Sept 2007, Online: http://www.nrscstandards.org/SG/NRSC-1-A.pdf \n\n%      Copyright (C) Mike Brookes 1997\n%      Version: $Id: v_usasi.m 10865 2018-09-21 17:22:45Z dmb $\n%\n%   VOICEBOX is a MATLAB toolbox for speech processing.\n%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   This program is free software; you can redistribute it and/or modify\n%   it under the terms of the GNU General Public License as published by\n%   the Free Software Foundation; either version 2 of the License, or\n%   (at your option) any later version.\n%\n%   This program is distributed in the hope that it will be useful,\n%   but WITHOUT ANY WARRANTY; without even the implied warranty of\n%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%   GNU General Public License for more details.\n%\n%   You can obtain a copy of the GNU General Public License from\n%   http://www.gnu.org/copyleft/gpl.html or by writing to\n%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin<2 fs=8000; end\nb=[1 0 -1];\na=poly(exp(-[100 320]*2*pi/fs));\n\nx=v_randfilt(b,a,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_usasi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5543118828430705}}
{"text": "function r = mpower(a,b)\n%MPOWER       Implements  a ^ b  for intervals\n%\n% either a and b are (interval) scalar or, b is scalar integer\n%\n\n% written  10/16/98     S.M. Rump\n% modified 12/30/98     S.M. Rump  improved performance and even exponent\n% modified 05/20/02     S.M. Rump  interval integer exponent checked\n% modified 04/04/04     S.M. Rump  set round to nearest for safety\n%                                    NaN corrected\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  % for both a and b scalars, use .^ with improved diameter for even exponent\n  if ( prod(size(a))==1 ) & ( prod(size(b))==1 )\n    r = a .^ b ;\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  % Check integer exponent\n  if isa(b,'intval') & all(inf(b)==sup(b)) \n    b = b.inf; \n    if ~isreal(b)\n      error('invalid call of intval mpower ^')\n    end\n    a = intval(a);\n  end\n  \n  if isa(b,'double') & isreal(b) & prod(size(b))==1 & b==round(b)\n    [m n] = size(a);\n    if m~=n\n      error('intval mpower of non-square matrix')\n    end\n    if b==0\n      if issparse(a)\n        r = intval(speye(size(a)));\n      else\n        r = intval(eye(size(a)));\n      end\n      index = isnan(a) & ( b==0 );\n      if any(index(:))\n        %VVVV  r(index) = NaN;\n        s.type = '()'; s.subs = {index}; r = subsasgn(r,s,NaN);\n        %AAAA  Matlab bug fix\n      end\n    else                        % b is integer\n      b_is_negative = b<0;\n      b = abs(b) - 1;           % abs(b) is at least 1\n      r = a;\n      while b>0\n        if mod(b,2)==1\n          r = r*a;\n        end\n        b = floor(b/2);\n        if b~=0\n          a = a*a;\n        end\n      end\n      if b_is_negative\n        r = inv(r);\n      end\n    end\n  else\n    error('invalid call of intval mpower ^')\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/mpower.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82446190912407, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5543118762699841}}
{"text": "function areasmooth = LowPassFilterArea(area,filterorder,maxfreq)\n\nf = fdesign.lowpass('N,F3db',filterorder,maxfreq);\nh = design(f,'butter');\nh.PersistentMemory = true;\n\nh.filter(fliplr(area));\nareasmooth = h.filter(area);\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/LowPassFilterArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5542935816426526}}
{"text": "function w = clean(w)\n% CLEAN Clean up waveform object(s)\n%   w = clean(w) will detrend waveforms (in a smart way, aware of NaN\n%   values marking missing values), then use fillgaps to mark bounded NaNs\n%   with linear-interpolated values, and also mark bounded NaNs with zeroes\n%   (now okay, since trend has been removed, so no weird startup effects).\n%   It then removes non-linear trends using a 20-s (0.05 Hz) highpass\n%   filter.\n\n% Glenn Thompson March 28, 2017\n\n    for c=1:numel(w)\n        \n        if ~isempty(w(c))\n            \n            % remove spikes of length 1\n            w(c) = medfilt1(w(c), 3); \n\n            % smart detrend\n            w(c) = detrend(w(c));\n\n            % % fill gaps to get rid of NaNs marking missing values, so we can filter\n            w(c) = fillgaps(w(c), 'interp');\n\n            % highpass data at 20s - to remove non-linear trends\n            f = filterobject('h',0.05,2);\n            w(c) = filtfilt(f,w(c));\n        \n        end\n    end\n\nend", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@waveform/clean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5542935697698107}}
{"text": "classdef StressNormSuperEllipseComputer < handle\n    \n    properties (Access = private)\n        microProblem\n        fName\n        outputFolder\n    end\n    \n    properties (Access = private)\n        mx\n        my\n        q\n        phi\n        pNorm\n        print\n        fileName\n        hasToCaptureImage\n        testName\n        iter\n        meshBackground\n        mesh\n        hMesh\n    end\n    \n    methods (Access = public)\n        \n        function obj = StressNormSuperEllipseComputer(cParams)\n            obj.init(cParams);\n        end\n        \n        function sPnorm = compute(obj)\n            obj.createMicroProblem()\n            sPnorm = obj.computePstressNorm();\n        end\n        \n        function var = computeCellVariables(obj)\n            obj.compute();\n            mProblem = obj.microProblem;\n            var.Ctensor = mProblem.variables.varFromCh.Chomog;\n            var.tstress = mProblem.variables.varFromCh.tstress;\n            var.tstrain = mProblem.variables.varFromCh.tstrain;\n            var.displ   = mProblem.variables.varFromCh.tdisp;\n            var.volume  = mProblem.mesh.computeVolume();\n            var.mesh    = mProblem.mesh;\n            \n            quad = Quadrature.set(var.mesh.geometryType);\n            quad.computeQuadrature('CONSTANT');\n            volume = var.mesh.computeDvolume(quad);\n            var.integrationVar.dV    = volume;\n            var.integrationVar.nstre = size(var.tstress,1);\n            var.integrationVar.ngaus = size(var.tstress,2);\n            var.integrationVar.geoVol = obj.meshBackground.computeVolume();\n        end\n        \n        function printImage(obj)\n            outputName = [obj.fileName,'Print'];\n            if obj.print\n                    s.mesh       = obj.mesh;\n                    s.outPutName = outputName;\n                    printer = SuperEllipsePrinter(s);\n                    printer.print();\n                if obj.hasToCaptureImage\n                    printer.captureImage()\n                end\n            end\n        end\n        \n        function printStress(obj)\n            if obj.print\n                microP = obj.microProblem;\n                outputName = [obj.fileName,'Print'];\n                dI.mesh    =  microP.mesh;\n                dI.outName = outputName;\n                dI.pdim    = '2D';\n                dI.ptype   = 'MICRO';\n                ps = PostProcessDataBaseCreator(dI);\n                dB = ps.getValue();\n                postCase = 'ElasticityMicro';\n                postProcess = Postprocess(postCase,dB);\n                d.fields = microP.variables;\n                d.quad   = microP.element.quadrature;\n                postProcess.print(obj.iter,d);\n            end\n        end\n        \n    end\n    \n    methods (Access = private)\n        \n        function init(obj,cParams)\n            obj.mx       = cParams.mx;\n            obj.my       = cParams.my;\n            obj.q        = cParams.q;\n            obj.phi      = cParams.phi;\n            obj.pNorm    = cParams.pNorm;\n            obj.print    = cParams.print;\n            obj.fileName = cParams.fileName;\n            obj.iter     = cParams.iter;\n            obj.hMesh    = cParams.hMesh;\n            obj.hasToCaptureImage = cParams.hasToCaptureImage;\n            obj.computeFileNameAndOutputFolder();\n        end\n        \n        function computeFileNameAndOutputFolder(obj)\n            obj.fName = [obj.fileName];\n            obj.outputFolder = fullfile(pwd,'Output',obj.fName);\n        end\n        \n        function sPnorm2 = computePstressNorm(obj)\n            stress = [sin(obj.phi) cos(obj.phi) 0];\n            p = obj.pNorm;\n            sPnorm2 = obj.microProblem.computeStressPnorm(stress,p);\n        end\n        \n        function ls = createLevelSet(obj)\n            sM.coord  = obj.meshBackground.coord;\n            sM.connec = obj.meshBackground.connec;\n            s.mesh = Mesh_Total(sM);\n            \n            s.widthH = obj.mx;\n            s.widthV = obj.my;\n            s.pnorm  = obj.q;\n            s.type = 'smoothRectangle';\n            \n            s.levelSetCreatorSettings = s;\n            s.type = 'LevelSet';\n            \n            s.scalarProductSettings.epsilon = 1;\n            levelSet = LevelSet(s);\n            ls = levelSet.value;\n        end\n        \n        function createBackgroundMesh(obj)\n            obj.testName = 'RVE_Square_Triangle_FineFine';\n            %obj.testName = 'RVE_Square_Triangle_Fine';\n            s.testName = obj.testName;\n            obj.meshBackground = Mesh().createFromFile(s); \n        end\n        \n        function createMesh(obj)\n            s.fileName = obj.fileName;\n            s.levelSet = obj.createLevelSet();\n            s.meshBackground = obj.meshBackground;\n            s.hMesh = obj.hMesh;\n            mCreator = MeshCreatorFromLevelSetWithMMG(s);\n            obj.mesh = mCreator.create();\n        end\n        \n        function createMicroProblem(obj)\n            obj.createBackgroundMesh();\n            obj.createMesh();\n            femSolver = Elastic_Problem_Micro.create(obj.testName);\n            femSolver.setMesh(obj.mesh);\n            props.kappa = .75;\n            props.mu    = .375;\n            femSolver.setMatProps(props);\n            obj.microProblem = femSolver;\n        end\n        \n    end\n    \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/Homogenization/Sources/VadamecumCalculator/StressNormSuperEllipseComputer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5542935668006506}}
{"text": "% AS-RPCA: Active Subspace: Towards Scalable Low-Rank Learning (Liu and Yan, 2012)\n% process_video('RPCA', 'AS-RPCA', 'dataset/demo.avi', 'output/demo_AS-RPCA.avi');\nlambda = 1/sqrt(min(size(M)));\n[L,S] = as_rpca(M,lambda);\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/AS-RPCA/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5542935593805993}}
{"text": "function [ n_data, a, b, x, fx ] = von_mises_cdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% VON_MISES_CDF_VALUES returns some values of the von Mises CDF.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    08 December 2004\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Kanti Mardia and Peter Jupp,\n%    Directional Statistics,\n%    Wiley, 2000, QA276.M335\n%\n%  Parameters:\n%\n%    Input/output, integer N_DATA.  The user sets N_DATA to 0 before the\n%    first call.  On each call, the routine increments N_DATA by 1, and\n%    returns the corresponding data; when there is no more data, the\n%    output value of N_DATA will be 0 again.\n%\n%    Output, real A, B, the parameters of the function.\n%\n%    Output, real X, the argument of the function.\n%\n%    Output, real FX, the value of the function.\n%\n  n_max = 23;\n\n  a_vec = [ ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.1E+01, ...\n     0.1E+01, ...\n     0.1E+01, ...\n     0.1E+01, ...\n     0.1E+01, ...\n     0.1E+01, ...\n    -0.2E+01, ...\n    -0.1E+01, ...\n     0.0E+01, ...\n     0.1E+01, ...\n     0.2E+01, ...\n     0.3E+01, ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.0E+00 ];\n\n  b_vec = [ ...\n     0.1E+01, ...\n     0.1E+01, ...\n     0.1E+01, ...\n     0.1E+01, ...\n     0.1E+01, ...\n     0.2E+01, ...\n     0.2E+01, ...\n     0.2E+01, ...\n     0.2E+01, ...\n     0.2E+01, ...\n     0.2E+01, ...\n     0.3E+01, ...\n     0.3E+01, ...\n     0.3E+01, ...\n     0.3E+01, ...\n     0.3E+01, ...\n     0.3E+01, ...\n     0.0E+00, ...\n     0.1E+01, ...\n     0.2E+01, ...\n     0.3E+01, ...\n     0.4E+01, ...\n     0.5E+01 ];\n\n  fx_vec = [ ......\n    0.2535089956281180E-01, ...\n    0.1097539041177346E+00, ...\n    0.5000000000000000E+00, ...\n    0.8043381312498558E+00, ...\n    0.9417460124555197E+00, ...\n    0.5000000000000000E+00, ...\n    0.6018204118446155E+00, ...\n    0.6959356933122230E+00, ...\n    0.7765935901304593E+00, ...\n    0.8410725934916615E+00, ...\n    0.8895777369550366E+00, ...\n    0.9960322705517925E+00, ...\n    0.9404336090170247E+00, ...\n    0.5000000000000000E+00, ...\n    0.5956639098297530E-01, ...\n    0.3967729448207649E-02, ...\n    0.2321953958111930E-03, ...\n    0.6250000000000000E+00, ...\n    0.7438406999109122E+00, ...\n    0.8369224904294019E+00, ...\n    0.8941711407897124E+00, ...\n    0.9291058600568743E+00, ...\n    0.9514289900655436E+00 ];\n\n  x_vec = [ ......\n    -0.2617993977991494E+01, ...\n    -0.1570796326794897E+01, ...\n     0.0000000000000000E+00, ...\n     0.1047197551196598E+01, ...\n     0.2094395102393195E+01, ...\n     0.1000000000000000E+01, ...\n     0.1200000000000000E+01, ...\n     0.1400000000000000E+01, ...\n     0.1600000000000000E+01, ...\n     0.1800000000000000E+01, ...\n     0.2000000000000000E+01, ...\n     0.0000000000000000E+00, ...\n     0.0000000000000000E+00, ...\n     0.0000000000000000E+00, ...\n     0.0000000000000000E+00, ...\n     0.0000000000000000E+00, ...\n     0.0000000000000000E+00, ...\n     0.7853981633974483E+00, ...\n     0.7853981633974483E+00, ...\n     0.7853981633974483E+00, ...\n     0.7853981633974483E+00, ...\n     0.7853981633974483E+00, ...\n     0.7853981633974483E+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    a = 0.0;\n    b = 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    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/von_mises_cdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5542932647465068}}
{"text": "function besi0_test ( )\n\n%*****************************************************************************80\n%\n%% BESI0_TEST tests R4_BESI0 and R8_BESI0.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 September 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n  addpath ( '../test_values' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'BESI0_TEST:\\n' );\n  fprintf ( 1, '  Test BESI0_VALUES, R4_BESI0, R8_BESI0\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '             X       BESI0(X)\\n' );\n  fprintf ( 1, '                  R4_BESI0(X)         Diff\\n' );\n  fprintf ( 1, '                  R8_BESI0(X)         Diff\\n' );\n\n  n_data = 0;\n\n  while ( 1 )\n\n    [ n_data, x, fx1 ] = bessel_i0_values ( n_data );\n\n    if ( n_data == 0 )\n      break\n    end\n\n    fx2 = r4_besi0 ( single ( x ) );\n    fx3 = r8_besi0 ( x );\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  %14.4f  %14.6g\\n', x, fx1 );\n    fprintf ( 1, '                  %14.6g  %14.6g\\n', fx2, abs ( fx1 - fx2 ) );\n    fprintf ( 1, '                  %14.6g  %14.6g\\n', fx3, abs ( fx1 - fx3 ) );\n\n  end\n\n  rmpath ( '../test_values' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/besi0_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.5542932647465066}}
{"text": "function r8vec_split_test ( )\n\n%*****************************************************************************80\n%\n%% R8VEC_SPLIT_TEST tests R8VEC_SPLIT.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 February 2003\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 25;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8VEC_SPLIT_TEST\\n' );\n  fprintf ( 1, '  R8VEC_SPLIT splits a vector into\\n' );\n  fprintf ( 1, '  entries less than and greater than a\\n' );\n  fprintf ( 1, '  splitting value.\\n' );\n\n  b = 0.0;\n  c = 10.0;\n  seed = 123456789;\n\n  [ a, seed ] = r8vec_uniform_ab ( n, b, c, seed );\n\n  a(1:n) = round ( a(1:n) ) / 2.0;\n\n  split = 0.5 * ( a(1) + a(n) );\n\n  r8vec_print ( n, a, '  The array:' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Splitting value is %f\\n', split );\n\n  [ a, isplit ] = r8vec_split ( n, a, split );\n \n  r8vec_print ( n, a, '  The split array:' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Array entries <= SPLIT up to index %d\\n', isplit );\n\n  return\nend\n", "meta": {"author": "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_split_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.5542932527854718}}
{"text": "function [startingvals,nu,lambda,LLs,outputParameters]=igarch_starting_values(startingvals,epsilon,fepsilon,p,q,T,errorType,igarchType,constant)\n% Perform a grid search to find decent starting values for IGARCH(P,Q)\n% esimtation.  If starting values are user supplied (and thus nonempty), reformats\n% starting values depending on ERRORTYPE.\n%\n% USAGE:\n%   [STARTINGVALS,NU,LAMBDA,LLS,OUTPUTPARAMETERS] = ...\n%        igarch_starting_values(STARTINGVALS,EPSILON,EPSILON2,P,Q,T,ERRORTYPE,IGARCHTYPE,CONSTANT)\n%\n% INPUTS:\n%   STARTINGVALS     - A vector of starting values or empty to perform a grid search\n%   EPSILON          - A column of mean zero data\n%   FEPSILON         - Either abs(EPSILON) or EPSILON.^2, depending on IGARCHTYPE\n%   P                - Positive, scalar integer representing the number of\n%                      symmetric innovations\n%   Q                - Non-negative, scalar integer representing the number\n%                      of lags of conditional variance (0 for ARCH)\n%   T                - Length of EPSILON\n%   ERRORTYPE        - [OPTIONAL] The error distribution used, valid types are:\n%                       'NORMAL'    - Gaussian Innovations [DEFAULT]\n%                       'STUDENTST' - T distributed errors\n%                       'GED'       - Generalized Error Distribution\n%                       'SKEWT'     - Skewed T distribution\n%   IGARCHTYPE       - [OPTIONAL] The type of variance process, either\n%                        1 - Model evolves in absolute values\n%                        2 - Model evolves in squares [DEFAULT]\n%   CONSTANT         - [OPTIONAL] Logical value indicating whether model\n%                       should include a constant.  Default is true (include).\n%\n% OUTPUTS:\n%   STARTINGVALS     - A vector of starting values (CONSTANT+p+q) by 1\n%   NU               - Distribution kurtosis parameter, empty if not applicable\n%   LAMBDA           - Distribution asymmetry parameter, empty if not applicable\n%   LLS              - A vector of log likelihoods corresponding to OUTPUTPARAMETERS\n%   OUTPUTPARAMETERS - A matrix of alternative starting values, sorted by log likelihood\n%\n% COMMENTS:\n%   See also IGARCH\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1    Date: 7/12/2009\n\n\n%Initialize variables\nLLs=[];\noutputParameters=[];\n\n%No starting values provided\nif isempty(startingvals)\n    nu=[];\n    lambda=[];\n    \n    %Procedure is to find best starting values, using a grid search find values for normal, then\n    \n    %Possible starting values based on commonly estimated values\n    a=[.05 .1 .2];\n    la=length(a);\n    ab=1;\n    lb=length(ab);\n    \n    %Many outputParameters and LLs\n    outputParameters=zeros(la*lb,1+p+q-1);\n    LLs=zeros(la,1);\n    \n    %Adjustment is needed to the intercept.  Assumes normality\n    if igarchType==1\n        adjFactor=sqrt(2/pi);\n        backCast=mean(abs(epsilon));\n    else\n        adjFactor=1;\n        backCast=cov(epsilon);\n    end\n    \n    %Use an index to count\n    index=1;\n    \n    for i=1:la\n        %Loop over a\n        alpha=a(i);\n        tempAlpha=alpha*ones(p,1)/p;\n        %Beta must satisfy the unit root\n        beta=1-sum(tempAlpha);\n        %Pick omega to match the unconditional\n        if constant\n            omega=backCast*.01*adjFactor;\n        else\n            omega = [];\n        end\n        %Build the parameter vector\n        \n        if q==0\n            parameters=[omega; tempAlpha];\n        else\n            parameters=[omega; tempAlpha; beta*ones(q-1,1)/q];\n        end\n        %Set the output parameters\n        outputParameters(index,:)=parameters';\n        %Set the log likelihoods\n        LLs(index)=igarch_likelihood(parameters, epsilon, fepsilon, p, q, 1, igarchType, constant, backCast, T, false);\n        %Increment\n        index=index+1;\n    end\n    %Sort the LLs so the best (lowest, since we minimize the -1*LL)\n    [LLs,index]=sort(LLs);\n    %Order the starting values\n    startingvals=outputParameters(index(1),:)';\n    %Order the ouputParameters\n    outputParameters=outputParameters(index,:);\n    %Use generic values for nu and lambda if needed\n    if errorType==2\n        nu=8;\n    elseif errorType==3\n        nu=1.9;\n    elseif errorType==4\n        nu=8;\n        lambda=-.1;\n    end\nelse\n    %Values provided, only parse them\n    nu=[];\n    lambda=[];\n    if errorType==2 || errorType==3 || errorType==4\n        nu=startingvals(constant+p+q);\n    end\n    if errorType==4\n        lambda=startingvals(constant+p+q+1);\n    end\n    startingvals=startingvals(1:constant+p+q-1);\nend\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/univariate/igarch_starting_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.554272749023383}}
{"text": "function [ relpos, psize3, delta_midy ] = gen2dOffset_v2( box1, box2, issplitting )\n%GEN2DOFFSET_V2 compute the rotation and offsets between two sibling boxes\n% INPUT: box1, box2 - 3d box of base box with absolute position\n%\n% OUTPUT: relpos - 13d vector (rp of box2 relative to box1), including:\n%                    (1) relative orientation - 1 bit degree\n%                    (3) offsets - 2 bits\n%                    (4) 16 classes (4 classes along each axis) - 8 bits\n%                    (5) attachments (4 possible cases) - 4 bits\n%                    (6) alignments (aligned along each axis) - 2 bit\n\n% box1 info\npcent = box1(1:3);\npfront = box1(4:6);\npup = box1(7:9);\npsize = box1(10:12);\npaxes = cross(pfront,pup);\npaxes = paxes/norm(paxes,2);\n\n% box2 info\nccent = box2(1:3);\ncfront = box2(4:6);\ncup = box2(7:9);\ncsize = box2(10:12);\ncaxes = cross(cfront,cup);\ncaxes = caxes/norm(caxes,2);\n\ntransform = genTransMat(pfront,pup);\nncent = ccent-pcent;\nncent = transform*ncent; % child's center position in parent's local frame\nnfront = cfront;\nnfront = transform*nfront; % child's front direction in parent's local frame\nnfront = nfront/norm(nfront,2);\nnup = cup;\nnup = transform*nup; % child's up direction in parent's local frame\nnup = nup/norm(nup,2);\nnaxes = cross(nfront,nup);\nnaxes = naxes/norm(naxes,2);\n\n% 4 corner points of parent box under its own local frame\nplfront = [1;0;0];\nplaxes = [0;0;1];\nppoints(:,1) = psize(1)*plfront/2 + psize(3)*plaxes/2;\nppoints(:,2) = psize(1)*plfront/2 - psize(3)*plaxes/2;\nppoints(:,3) = -psize(1)*plfront/2 - psize(3)*plaxes/2;\nppoints(:,4) = -psize(1)*plfront/2 + psize(3)*plaxes/2;\n\n% 4 corner points of child box under its parent's local frame\ncpoints(:,1) = ncent + csize(1)*nfront/2 + csize(3)*naxes/2;\ncpoints(:,2) = ncent + csize(1)*nfront/2 - csize(3)*naxes/2;\ncpoints(:,3) = ncent - csize(1)*nfront/2 - csize(3)*naxes/2;\ncpoints(:,4) = ncent - csize(1)*nfront/2 + csize(3)*naxes/2;\n\n% the relative positions\npmaxx = max(ppoints(1,:));\npmaxy = max(ppoints(3,:));\npminx = min(ppoints(1,:));\npminy = min(ppoints(3,:));\ncmaxx = max(cpoints(1,:));\ncmaxy = max(cpoints(3,:));\ncminx = min(cpoints(1,:));\ncminy = min(cpoints(3,:));\n\ndelta_midy = 0;\nif(issplitting==1)\n    pmidy = (pmaxy+pminy)/2;\n    cmidy = (cmaxy+cminy)/2;\n    delta_midy = pmidy-cmidy;\n    pmaxy = cmaxy;\n    pminy = cminy;\nend\npsize3 = pmaxy-pminy;\n\n% relative position class along x axis\ndelta_x = [pminx-cmaxx;pminx-cminx;pmaxx-cmaxx;pmaxx-cminx];\n[~,classxindex] = min(abs(delta_x));\noffsets(1) = delta_x(classxindex);\n\n% relative position class along y axis\ndelta_y = [pminy-cmaxy;pminy-cminy;pmaxy-cmaxy;pmaxy-cminy];\n[~,classyindex] = min(abs(delta_y));\noffsets(2) = delta_y(classyindex);\n\n% alignment info\nattachindex = 1;\nattacheps = 0.011; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif(abs(offsets(1))<attacheps)\n    attachindex = attachindex + 1;\nend\nif(abs(offsets(2))<attacheps)\n    attachindex = attachindex + 2;\nend\nattachvec = zeros(4,1);\nattachvec(attachindex) = 1;\n\n% form the relpos vector\nrot_eps = 0.01;\nalignment = [1;0;0;0;0];\nif(abs(nfront(1)-1)<rot_eps)\n    alignment = [0;1;0;0;0]; % nfront = [1,0,0];\nend \nif(abs(nfront(1)+1)<rot_eps)\n    alignment = [0;0;1;0;0]; % nfront = [-1,0,0];\nend \nif(abs(nfront(3)-1)<rot_eps)\n    alignment = [0;0;0;1;0]; % nfront = [0,0,1];\nend \nif(abs(nfront(3)+1)<rot_eps)\n    alignment = [0;0;0;0;1]; % nfront = [0,0,-1];\nend \n\nif(nfront(1)==0)\n    if(nfront(3)>0)\n        degree = -0.5;\n    else\n        degree = 0.5;\n    end\nelse\n    degree = atand(nfront(3)/nfront(1));\n    if(nfront(1)<0)\n        if(degree<0)\n            degree = degree-180;\n        else\n            degree = degree+180;\n        end\n    end\n    degree = mod(degree,360)/180-1;\nend\nif(abs(degree)>1)\n        o=0;\n    end\n\nclassindex = classxindex + (classyindex-1)*4;\nclassvec = zeros(16,1);\nclassvec(classindex) = 1;\nrelpos = [degree;offsets(1);offsets(2);classvec;attachvec;alignment];\n\n% tmpcent = pcent;\n% tmpfsize = (max(cmaxx,pmaxx)-min(cminx,pminx));\n% tmpasize = (max(cmaxy,pmaxy)-min(cminy,pminy));\n% tmpobb = [tmpcent;plfront;0;1;0;tmpfsize;1;tmpasize];\n% draw3dOBB_v2(box1,'r');\n% draw3dOBB_v2(box2,'g');\n% draw3dOBB_v2(tmpobb,'y');\n\nend\n\n", "meta": {"author": "ManyiLi12345", "repo": "GRAINS", "sha": "7806359dada1283a110886d4b634fdedf6963e63", "save_path": "github-repos/MATLAB/ManyiLi12345-GRAINS", "path": "github-repos/MATLAB/ManyiLi12345-GRAINS/GRAINS-7806359dada1283a110886d4b634fdedf6963e63/3-datapreparation/gen2dOffset_v2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5542727437977409}}
{"text": "function kSpaceLow = updownsample( kSpaceHigh, lInputImage, out_size, lAAfilter)\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%\n% input:    in_m                - input matrix for up/down sampling, in fourier domain\n%                                 \n%           out_size            - desired number of pixels in the output image\n\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% \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\nif(nargin < 4)\n    lAAfilter = true;\nend\n\n% ==============================================\n% get input image size, and calculate the gain\n% ==============================================\nout_x_sz = out_size(1); out_y_sz = out_size(2); out_z_sz = out_size(3);\n[in_x_sz,in_y_sz, in_z_sz, nCha, nTime] = size( kSpaceHigh );\ngain_x = out_x_sz/in_x_sz;\ngain_y = out_y_sz/in_y_sz;\ngain_z = out_z_sz/in_z_sz;\n\n% upsample or downsample as needed\n% ==================================\nif(lInputImage)\n    % image -> kSpace\n    kSpaceHigh = fftnshift(kSpaceHigh,1:3);\nend\n\n% check if up/down sampling is needed at all\nif(gain_x == 1 && gain_y == 1 && gain_z == 1)\n    kSpaceLow = kSpaceHigh;\n    dImgLow = ifftnshift(kSpaceLow,1:3);\n    return;\nend\n\n% if downsampling -> apply anti-aliasing filter\nif(gain_x < 1 && gain_y < 1 && gain_z < 1 && lAAfilter)\n    kSpaceHigh = kSpaceHigh .* repmat(windowND(@hamming, [size(kSpaceHigh,1), size(kSpaceHigh,2), size(kSpaceHigh,3)]),[1 1 1 size(kSpaceHigh,4) size(kSpaceHigh,5)]);\nend\n\n% build grid vectors for the up/down sampling\n% ============================================\n% if the input is even & output is odd-> use floor for all\n% if the output is even & input is odd -> use ceil for all\n% other cases - don't care\n% for downsampling -> the opposite\nif (~mod( in_x_sz,2 ) && (out_x_sz>in_x_sz)) || (mod( in_x_sz,2 ) && (out_x_sz<in_x_sz))\n    x_output_space  = max(floor((out_x_sz-in_x_sz)/2),0) + [1:min(in_x_sz,out_x_sz)];\n    x_input_space   = max(floor((in_x_sz-out_x_sz)/2),0) + [1:min(in_x_sz,out_x_sz)];\nelse\n    x_output_space  = max(ceil((out_x_sz-in_x_sz)/2),0) + [1:min(in_x_sz,out_x_sz)];\n    x_input_space   = max(ceil((in_x_sz-out_x_sz)/2),0) + [1:min(in_x_sz,out_x_sz)];\nend\nif (~mod( in_y_sz,2 ) && (out_y_sz>in_y_sz)) || (mod( in_y_sz,2 ) && (out_y_sz<in_y_sz))\n   y_output_space  = max(floor((out_y_sz-in_y_sz)/2),0) + [1:min(in_y_sz,out_y_sz)];\n   y_input_space   = max(floor((in_y_sz-out_y_sz)/2),0) + [1:min(in_y_sz,out_y_sz)];\nelse\n   y_output_space  = max(ceil((out_y_sz-in_y_sz)/2),0) + [1:min(in_y_sz,out_y_sz)];\n   y_input_space   = max(ceil((in_y_sz-out_y_sz)/2),0) + [1:min(in_y_sz,out_y_sz)];\nend\nif (~mod( in_z_sz,2 ) && (out_z_sz>in_z_sz)) || (mod( in_z_sz,2 ) && (out_z_sz<in_z_sz))\n   z_output_space  = max(floor((out_z_sz-in_z_sz)/2),0) + [1:min(in_z_sz,out_z_sz)];\n   z_input_space   = max(floor((in_z_sz-out_z_sz)/2),0) + [1:min(in_z_sz,out_z_sz)];\nelse\n   z_output_space  = max(ceil((out_z_sz-in_z_sz)/2),0) + [1:min(in_z_sz,out_z_sz)];\n   z_input_space   = max(ceil((in_z_sz-out_z_sz)/2),0) + [1:min(in_z_sz,out_z_sz)];\nend\n\n\n% perform the up/down sampling\nkSpaceLow  = zeros( out_x_sz, out_y_sz, out_z_sz, size(kSpaceHigh,4), size(kSpaceHigh,5) );\n% kSpaceHigh = fftshift(fftshift(fftshift(kSpaceHigh,1),2),3); % already zero-centered\nkSpaceLow(x_output_space,y_output_space, z_output_space, :, :) = kSpaceHigh(x_input_space,y_input_space, z_input_space, :, :);\n    \n        \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/updownsample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5542727433809131}}
{"text": "function w = padua_weights ( l )\n\n%*****************************************************************************80\n%\n%% PADUA_WEIGHTS returns quadrature weights for Padua points.\n%\n%  Discussion:\n%\n%    The order of the weights corresponds to the ordering used\n%    by the companion function padua_points().\n%\n%    Caliari, de Marchi and Vianello supplied a MATLAB code pdwtsMM\n%    which carries out this same computation in a way that makes\n%    more efficient use of MATLAB's vector and matrix capabilities.  \n%    This version of the computation was painfully rewritten to display \n%    the individual scalar computations, so that it could be translated\n%    into other languages.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    11 June 2014\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Marco Caliari, Stefano de Marchi, Marco Vianello,\n%    Bivariate interpolation on the square at new nodal sets,\n%    Applied Mathematics and Computation,\n%    Volume 165, Number 2, 2005, pages 261-274.\n%\n%  Parameters:\n%\n%    Input, integer L, the level of the set.\n%    0 <= L\n%\n%    Output, real W((L+1)*(L+2)/2), the quadrature weights.\n%\n  if ( l == 0 )\n    w = 4.0;\n    return\n  end\n%\n%  Relatives of L/2:\n%\n  lp1h = floor ( ( l + 1 ) / 2 );\n  lp2h = floor ( ( l + 2 ) / 2 );\n  lp3h = floor ( ( l + 3 ) / 2 );\n%\n%  TE1, TE2, TO1, TO2: \n%  Even and odd Chebyshev polynomials on subgrids 1 and 2.\n%\n  te1 = zeros(lp2h,lp2h);\n  for j = 1 : lp2h\n    for i = 1 : lp2h\n      te1(i,j) = cos ( 2 * ( i - 1 ) * ( 2 * j - 2 ) * pi / l );\n    end\n  end\n  te1(2:lp2h,1:lp2h) = te1(2:lp2h,1:lp2h) * sqrt ( 2.0 );\n\n  to1 = zeros(lp2h,lp1h);\n  for j = 1 : lp1h\n    for i = 1 : lp2h\n      to1(i,j) = cos ( 2 * ( i - 1 ) * ( 2 * j - 1 ) * pi / l );\n    end\n  end\n  to1(2:lp2h,1:lp1h) = to1(2:lp2h,1:lp1h) * sqrt ( 2.0 );\n\n  te2 = zeros(lp2h,lp3h);\n  for j = 1 : lp3h\n    for i = 1 : lp2h\n      te2(i,j) = ...\n        cos ( 2 * ( i - 1 ) * ( 2 * j - 2 ) * pi / ( l + 1 ) );\n    end\n  end\n  te2(2:lp2h,1:lp3h) = te2(2:lp2h,1:lp3h) * sqrt ( 2.0 );\n\n  to2 = zeros(lp2h,lp2h);\n  for j = 1 : lp2h\n    for i = 1 : lp2h\n      to2(i,j) = ...\n        cos ( 2 * ( i - 1 ) * ( 2 * j - 1 ) * pi / ( l + 1 ) );\n    end\n  end\n  to2(2:lp2h,1:lp2h) = to2(2:lp2h,1:lp2h) * sqrt ( 2.0 );\n%\n%  MOM: Moments matrix for even * even pairs.\n%\n  mom = zeros(lp2h,lp2h);\n\n  for j = 1 : lp2h\n    mj = 2.0 * sqrt ( 2.0 ) / ( 1.0 - ( 2 * j - 2 ) ^2 );\n    for i = 1 : lp2h + 1 - j\n      mi = 2.0 * sqrt ( 2.0 ) / ( 1.0 - ( 2 * i - 2 ) ^2 );\n      mom(i,j) = mi * mj;\n    end\n  end\n\n  mom(1,1:lp2h) = mom(1,1:lp2h) / sqrt ( 2.0 );\n  mom(1:lp2h,1) = mom(1:lp2h,1) / sqrt ( 2.0 );\n\n  if ( mod ( l, 2 ) == 0 )\n    mom(lp2h,1) = mom(lp2h,1) / 2.0;\n  end\n%\n%  TMTOE and TMTEO: matrix products.\n%\n  tmtoe = zeros(lp2h,lp2h);\n\n  for j2 = 1 : lp2h\n    for i2 = 1 : lp2h+1-j2\n      for j = 1 : lp2h\n        for i = 1 : lp2h\n          tmtoe(i,j) = tmtoe(i,j) + to2(i2,i) * mom(j2,i2) * te1(j2,j);\n        end\n      end\n    end\n  end\n\n  tmteo = zeros(lp3h,lp1h);\n\n  for j2 = 1 : lp2h\n    for i2 = 1 : lp2h+1-j2\n      for j = 1 : lp1h\n        for i = 1 : lp3h\n          tmteo(i,j) = tmteo(i,j) + te2(i2,i) * mom(j2,i2) * to1(j2,j);\n        end\n      end\n    end\n  end\n%\n%  W1 and W2: Interpolation weight matrices.\n%\n  w1 = 2.0 * ones(lp2h,lp2h) / ( l * ( l + 1 ) );\n\n  w1(1:lp2h,1) = w1(1:lp2h,1) / 2.0;\n\n  if ( mod ( l, 2 ) == 0 )\n    w1(1:lp2h,lp2h) = w1(1:lp2h,lp2h) / 2.0;\n    w1(lp2h,1:lp2h) = w1(lp2h,1:lp2h) / 2.0;\n  end\n\n  w2 = 2.0 * ones(lp3h,lp1h) / ( l * ( l + 1 ) );\n  w2(1,1:lp1h) = w2(1,1:lp1h) / 2.0;\n\n  if ( mod ( l, 2 ) == 1 )\n    w2(lp3h,1:lp1h) = w2(lp3h,1:lp1h) / 2.0;\n    w2(1:lp3h,lp1h) = w2(1:lp3h,lp1h) / 2.0;\n  end\n%\n%  Cubature weights as matrices on the subgrids.\n%\n  for j = 1 : lp2h\n    for i = 1 : lp2h\n      w1(i,j) = w1(i,j) * tmtoe(i,j);\n    end\n  end\n\n  for j = 1 : lp1h\n    for i = 1 : lp3h\n      w2(i,j) = w2(i,j) * tmteo(i,j);\n    end\n  end\n%\n%  Pack weight matrices W1 and W2 into the vector W.\n%\n  n = ( ( l + 1 ) * ( l + 2 ) ) / 2;\n  w = zeros(n,1);\n\n  if ( mod ( l, 2 ) == 0 )\n\n    for i = 1 : lp2h\n      for j = 1 : lp2h\n        w(i+(2*j-2)*lp2h) = w1(i,j);\n      end\n    end\n\n    for i = 1 : lp3h\n      for j = 1 : lp1h\n        w(i+(2*j-1)*lp2h) = w2(i,j);\n      end\n    end\n\n  else\n\n    for j = 1 : lp1h\n      for i = 1 : lp2h\n        w(i+(j-1)*(l+2)) = w1(i,j);\n      end\n    end\n\n    for j = 1 : lp1h\n      for i = 1 : lp3h\n        w(i+lp2h+(j-1)*(l+2)) = w2(i,j);\n      end\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/padua/padua_weights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.554272732929629}}
{"text": "function [R, movement, verbose] = tapas_physio_create_movement_regressors(...\n    movement, verbose)\n% Reads realignment parameters, creates derivative/squared & outlier regressor\n%\n% [R, movement, verbose] = ...\n%       tapas_physio_create_movement_regressors(movement, verbose)\n%\n% The 6 realignment parameters can be augmented by their derivatives (in\n% total 12 parameters) + the squares of parameters and derivatives (in\n% total 24 parameters), leading to a Volterra expansion as in\n%\n%               Friston KJ, Williams S, Howard R, Frackowiak\n%               RS, Turner R. Movement-related effects in fMRI\n%               time-series. Magn Reson Med. 1996;35:346?355.)\n%\n% IN\n%   movement    physio.model.movement\n%   verbose     physio.verbose\n% OUT\n%   R                   [nScans, (6|12|24)+nOutliers] regressor matrix \n%                       from movement modeling\n%   movement            structure (as defined in tapas_physio_new) with the\n%                       following fields\n%   rp                  [nScans, 6] realignment parameters\n%   dRp                 [nScans, 6] temporal difference of realignment\n%                       parameters, prepending one line of zeros (for 1st\n%                       scan)\n%   quality_measures.   structure holding the suggested quality control\n%                       measures for subject motion of Power et al., 2014,\n%                       Fig. 2; all rotational parameters are transformed\n%                       into translations by multiplying with rHead (arc\n%                       length)\n%       FD              framewise displacement (FD)\n%       absTransDisplacement\n%                       sum of absolute values of translational (x,y,z)\n%                       realignment estimates, reflecting absolute\n%                       displacement of the head\n%       absRotDisplacement\n%                       sum of absolute values of rotational (rotation \n%                       around x,y,z-axis = pitch/roll/yaw)\n%                       realignment estimates, reflecting absolute\n%                       displacement of the head on its surface (arc\n%                       length)\n%       rmsdTrans       root mean squared framewise translational displacement (over x,y,z)\n%                       equals to euclidean distance of center of\n%                       mass of head between consecutive volumes\n%       rmsdRot         root mean squared framewise rotational displacement \n%                       (rotation around x,y,z axis)\n%                       equals to euclidean distance of between angles\n%                       between consecutive volumes\n%       meanFD          mean (over volumes) of framewise displacement \n%                       summary measure for subject (or session)\n%       rmsMovement     root mean square (over scans) of detrended\n%                       realignment estimates\n%                       summary measure for subject (or session)\n%\n%   censoring.          structure with censoring information (detected outliers,\n%                       computed quality values for censoring method maxval/fd:  \n%       nOutliers       number of detected outliers\n%       R_outlier       stick/spike regressors indicating location of\n%                       detected outliers\n%       iOutlierTrans   volume indices of translation-related outliers\n%       iOutlierRot     volume indices of rotation-related outliers\n%       iOutlierArray   volume indices of all detected outliers\n%\n%\n% EXAMPLE\n%   tapas_physio_create_movement_regressors\n%\n%   See also tapas_physio_new tapas_physio_main_create_regressors\n\n% Author: Lars Kasper\n% Created: 2015-07-10\n% Copyright (C) 2015 TNU, Institute for Biomedical Engineering,\n%                    University of Zurich and ETH Zurich.\n%\n% This file is part of the TAPAS PhysIO Toolbox, which is released under the terms of the GNU General Public\n% License (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 <http://www.gnu.org/licenses/>.\n\nrHead = 50; % head radius in mm for FD computation (Power et al., 2012)\n\n[fp, fn, ext] = fileparts(movement.file_realignment_parameters);\n\nif ~exist(movement.file_realignment_parameters, 'file')\n    verbose = tapas_physio_log('No input multiple regressors found', verbose, 1);\n    R = [];\nelse\n    tmp = load(movement.file_realignment_parameters);\n    if strcmp('.txt', ext) % text-file\n        rp = tmp;\n    else % mat file\n        rp = tmp.R;\n    end\n    \n    \n    %% Motion Quality control\n    \n     [quality_measures, dRp] = ...\n         tapas_physio_get_movement_quality_measures(rp, rHead);\n     \n    \n    %% Motion 6/12/24 model\n    R = rp;\n    \n    % Include derivatives\n    if movement.order > 6\n        R = [rp, dRp];\n    end\n    \n    % Include squared regressors/derivatives\n    if movement.order > 12\n        R = [R, R.^2];\n    end\n    \n    % Sanity check if order misspecified\n    movement.order = size(R, 2);\n    \n    %% Motion Censoring\n    % Include outlier movements exceeding thresholds as stick regressors\n    % Euclidean distance used!\n    iOutlierArray = [];\n    iOutlierTrans = [];\n    iOutlierRot = [];\n    \n    \n \n    switch lower(movement.censoring_method)\n        case 'none' % done\n        case 'fd' % framewise displacement\n            iOutlierArray = find(quality_measures.FD > ...\n                movement.censoring_threshold);\n        case 'maxval'   % tresholds for max abrupt translation/rotation,\n                        % even per axis\n            switch numel(movement.censoring_threshold)\n                case {1,2}\n                    outlier_translation_mm = movement.censoring_threshold(1);\n                    outlier_rotation_deg = movement.censoring_threshold(end);\n                    iOutlierTrans = find(quality_measures.rmsdTrans > outlier_translation_mm);\n                    iOutlierRot = find(quality_measures.rmsdRot > outlier_rotation_deg/180*pi);\n                case 6\n                    ct = movement.censoring_threshold;\n                    ct(4:6) = ct/180*pi;\n                    iOutlierTrans = dRp(:,1) > ct(1) || dRp(:,2) > ct(2) || dRp(:,3) > ct(3);\n                    iOutlierRot = dRp(:,4) > ct(4) || dRp(:,5) > ct(5) || dRp(:,6) > ct(6);\n                otherwise\n                    error('censoring threshold has to be 1,2 or 6 element vector. See tapas_physio_new');\n            end\n             \n            iOutlierArray = unique([iOutlierTrans; iOutlierRot]);\n        case 'dvars' %DVARS, as in Power et al, 2012\n            % TODO\n    end\n    \n    \n    %% Construct censoring regressor matrix\n    nOutliers = numel(iOutlierArray);\n    \n    nScans = size(rp,1);\n    R_outlier = zeros(nScans, nOutliers);\n    for iOutlier = 1:nOutliers\n        R_outlier(iOutlierArray(iOutlier), iOutlier) = 1;\n    end\n    \n   \n    censoring = struct('nOutliers', nOutliers, 'R_outlier', R_outlier, ...\n        'iOutlierTrans', iOutlierTrans, 'iOutlierRot', iOutlierRot, ...\n        'iOutlierArray', iOutlierArray);\n    \n    if verbose.level >= 2\n        switch lower(movement.censoring_method)\n            case 'fd'\n                verbose.fig_handles(end+1) = tapas_physio_plot_movement_outliers_fd(rp, ...\n                    quality_measures, censoring, movement.censoring_threshold);\n            case 'maxval'\n                verbose.fig_handles(end+1) = tapas_physio_plot_movement_outliers_maxval(rp, ...\n                    quality_measures, censoring, movement.censoring_threshold);\n        end\n    end\n    \n    \n    %% Gather return values\n    movement.censoring = censoring;\n    movement.rp = rp;\n    movement.dRp = dRp;\n    movement.quality_measures = quality_measures;\n    \n    R = [R, R_outlier];\n    \nend\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/PhysIO/code/model/tapas_physio_create_movement_regressors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5542727329296289}}
{"text": "function [res, inds] = polylineSubcurve(poly, t0, t1)\n%POLYLINESUBCURVE Extract a portion of a polyline.\n%\n%   POLY2 = polylineSubcurve(POLYLINE, POS0, POS1)\n%   Create a new polyline, by keeping vertices located between positions\n%   POS0 and POS1, and adding points corresponding to positions POS0 and\n%   POS1 if they are not already vertices.\n%\n%   [POLY2, INDS] = polylineSubcurve(POLYLINE, POS0, POS1)\n%   Also returns the indices of the original polyline that were selected.\n%   The size of the array INDS may be smaller than the array POLY, due to\n%   the addition of new vertices at the extremities.\n%\n%   Example\n%     Nv = 100;\n%     poly = circleAsPolygon([10 20 30], Nv);\n%     poly2 = polylineSubcurve(poly, 15, 65);\n%     drawCurve(poly2);\n%\n%   See also \n%     polygons2d, polygonSubCurve\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inrae.fr\n% Created: 2009-04-30, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009-2022 INRAE - Cepia Software Platform\n\n% number of vertices\nNv = size(poly, 1);\n\nif t0 < t1\n    % format positions\n    t0 = max(t0, 0);\n    t1 = min(t1, Nv-1);\nend\n\n% indices of extreme vertices inside subcurve\nind0 = ceil(t0)+1;\nind1 = floor(t1)+1;\n\n% get the portion of polyline between 2 extremities\nif t0 < t1\n    inds = ind0:ind1;\nelse\n    inds = [ind0:Nv 1:ind1];\nend\n\nres = poly(inds, :);\n\n% add first point if it is not already a vertex\nif t0 ~= ind0-1\n    res = [polylinePoint(poly, t0); res];\nend\n\n% add last point if it is not already a vertex\nif t1 ~= ind1-1\n    res = [res; polylinePoint(poly, t1)];\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/polylineSubcurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.5542590518886347}}
{"text": "%GRIDROTATE Rotate grid.\n%\n%   [ GRID ] = GRIDROTATE( GRID, TH, AX ) Applies rotation angle TH\n%   (radians) to grid points around the origin (in 3D around axis AX:\n%   1 = x-axis (default), 2 = y-axis, 3 = z-axis). The input argument\n%   GRID can either be a grid struct or simply an array of\n%   coordinates. Normals will also be recalculated in the case of a\n%   grid struct with boundary information.\n%\n%   See also GRIDEXTRUDE, GRIDMERGE, GRIDREVOLVE, GRIDSCALE\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/grid/gridrotate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5541978374005048}}
{"text": "%% OPTI Toolbox Global Nonlinear Programming Examples\n%\n% This file contains a number of Global NLP problems and demonstrates how \n% to solve them using the OPTI Toolbox. You should read and complete\n% BasicUsage.m & NonlinearProgramming.m BEFORE running the below examples.\n%\n%   Copyright (C) 2014 Jonathan Currie (IPL)\n\n% There is also a page on the Wiki which supplements this example:\nweb('https://www.inverseproblem.co.nz/OPTI/index.php/Probs/GNLP');\n\n%% Determing which Solver to Use\n% OPTI Toolbox comes with a number of NLP solvers, thus to determine which\n% ones are available on your system you can type:\nclc\noptiSolver('NLP')\n\n% Note the columns DR and GL. A cross in DR indicates the solver requires\n% 1st (and perhaps 2nd) derivatives, while a cross in GL indicates the\n% solver can solve Global Optimization problems. For noisy problems unless\n% you have exact derivatives, avoid solvers with a cross in DR.\n\n%% Typical Global Optimization Problems\n% Global optimization problems result from any of the following circumstances:\n%\n%       - Objectives containing noise / a stochastic element\n%       - Non-convex functions (functions which are not a bowl / hill in 2D)\n%       - Objectives that include periodic functions (sin, cos)\n%       - Parameter estimation of ODEs solved with adaptive step integrators\n%       - Any problem that contains multiple local minima.\n%\n% An extreme example from Wolfram is shown below:\nclc\n%Objective\nfun = @(x) norm([x(1) - sin(2*x(1) + 3*x(2)) - cos(3*x(1) - 5*x(2));\n          x(2) - sin(x(1) - 2*x(2)) + cos(x(1) + 3*x(2))]);\nlb = [-4;-4]; ub = [4;4];\nx0 = [-4;-4];\n\n%Plot      \nn = 1e2;\nx = linspace(-4,4,n); y = linspace(-4,4,n); Z = zeros(n,n);\nfor i = 1:n\n    for j = 1:n\n        Z(j,i) = fun([x(i),y(j)]);\n    end\nend\nsurfc(x,y,Z)\ncolormap summer; shading interp; lighting phong; view(-38,58);\nxlabel('x1'); ylabel('x2'); zlabel('obj'); title('Wolfram Global Optimization Problem'); \n\n%% Example 1 - Basic Setup\n% The main difference when solving a Global NLP is that OPTI treats Global\n% and Local NLP problems identically, and therefore you will have to specify\n% a Global solver. For this example we will build 4 OPTI objects with 4\n% different solvers:\nclc\n%Build OPTI Problem\nprob = optiprob('fun',fun,'bounds',lb,ub);\n%Choose Global Solver\nopts1 = optiset('solver','nomad');\nopts2 = optiset('solver','pswarm');\nopts3 = optiset('solver','nlopt','solverOpts',nloptset('algorithm','GN_DIRECT'));\nopts4 = optiset('solver','ipopt','warnings','off');\n\n%Pass to OPTI Constructor for Error Checking + Setup\nOpt1 = opti(prob,opts1); \nOpt2 = opti(prob,opts2); \nOpt3 = opti(prob,opts3); \nOpt4 = opti(prob,opts4); \n\n% Call solve to solve the problem. Check the plot for a comparison of the\n% solution points. Note NOMAD and NLOPT are deterministic with the current\n% settings, PSWARM includes random elements, and IPOPT is for comparison of\n% a local solution.\n\n[x1,fval1] = solve(Opt1,x0);\n[x2,fval2] = solve(Opt2,x0);\n[x3,fval3] = solve(Opt3,x0);\n[x4,fval4] = solve(Opt4,x0);\n\nview(0,90); hold on;\nplot3(x0(1),x0(2),10,'kx','markersize',10);\nplot3(x1(1),x1(2),10,'ro'); text(x1(1)+0.1,x1(2)+0.1,10,sprintf('NOMAD: %f',fval1));\nplot3(x2(1),x2(2),10,'ro'); text(x2(1)+0.1,x2(2)-0.1,10,sprintf('PSWARM: %f',fval2));\nplot3(x3(1),x3(2),10,'ro'); text(x3(1)+0.1,x3(2)+0.2,10,sprintf('NLOPT: %f',fval3));\nplot3(x4(1),x4(2),10,'ro'); text(x4(1)+0.1,x4(2)+0.1,10,sprintf('IPOPT: %f',fval4));\nhold off;\n\n%% Problem 2 - Quartic\n% Includes Linear and Nonlinear Constraints\nclc\n%Problem\nfun = @(x) x(1)^4 - 14*x(1)^2 + 24*x(1) - x(2)^2;\n\n%Linear Constraints\nA = [-1 1]; b = 8;\n%Nonlinear Constraints\nnlcon = @(x) (-x(1)^2) - 2*x(1) + x(2);\nnlrhs = -2;\nnle = -1;\n%Bounds + Starting Guess\nlb = [-8;0];\nub = [10;10];\nx0 = [0;0];\n\n% Solving a constrained global optimization problem. Note linear\n% constraints will be converted to nonlinear ones for this solver\nopts = optiset('solver','nomad','solverOpts',nomadset('direction_type','lt 2n')); \nOpt = opti('fun',fun,'ineq',A,b,'nlmix',nlcon,nlrhs,nle,'bounds',lb,ub,'options',opts)\n\n% This may take a few seconds...\n[x,fval,exitflag,info] = solve(Opt,x0)  \n\n%% Example 3 - Solving with PSwarm\n% Note x0 is on the local minima side of the saddle\nclc\n%Problem\nfun = @(x) -2*x(1)*x(2);\n\n%Constraints\nlb = [-0.5;-0.5];\nub = [1;1];\nx0 = [-0.3;-0.3]; \n\n%Plot      \nn = 1e2;\nx = linspace(-0.5,1,n); y = linspace(-0.5,1,n); Z = zeros(n,n);\nfor i = 1:n\n    for j = 1:n\n        Z(j,i) = fun([x(i),y(j)]);\n    end\nend\nsurfc(x,y,Z); hold on; plot3(x0(1),x0(2),fun(x0),'r.','markersize',20); hold off;\ncolormap winter; shading flat; lighting gouraud; view(18,28);\nxlabel('x1'); ylabel('x2'); zlabel('obj'); title('Saddle Point Optimization Problem'); \n\n% PSwarm solves bounded and linearly constrained global problems\nOpt = opti('fun',fun,'bounds',lb,ub,'options',optiset('solver','pswarm'))\n\n\n[x,fval,exitflag,info] = solve(Opt,x0)  \nplot(Opt,3)\n\n%% Example 4 - White Box Quartic\n% The following problem is the same as problem 2, however this time we are\n% going to solve it using a white box solver (SCIP). The SCIP interface\n% will parse the following functions into an algebraic description,\n% allowing SCIP to find a global solution to this problem.\nclc\n%Problem\nfun = @(x) x(1)^4 - 14*x(1)^2 + 24*x(1) - x(2)^2;\n\n%Linear Constraints\nA = [-1 1]; b = 8;\n%Nonlinear Constraints\nnlcon = @(x) (-x(1)^2) - 2*x(1) + x(2);\nnlrhs = -2;\nnle = -1;\n%Bounds + Starting Guess\nlb = [-8;0];\nub = [10;10];\nx0 = [0;0];\n\n% SCIP solves a subset of nonlinear and mixed integer problems, provided\n% the problem is deterministics and constains a subset of allowable functions.\nOpt = opti('fun',fun,'ineq',A,b,'nlmix',nlcon,nlrhs,nle,'bounds',lb,ub,...\n           'options',optiset('solver','scip'))\n\n[x,fval,exitflag,info] = solve(Opt,x0)  \nplot(Opt)\n\n%% Example 5 - OPTI's Multi-Start Solver\n% For simple, low dimensional problems, OPTI's mulit-start is a naive\n% algorithm for searching the problem space for a global solution. See the\n% following page for more examples:\n\nweb('https://www.inverseproblem.co.nz/OPTI/index.php/Advanced/MultiSolve');\n\nclc\nOpt = opti(Opt,'solver','ipopt');\n[x,fval,exitflag,info] = multisolve(Opt,x0)  \nmultiplot(Opt)\n\n%% Summary\n% While Global Optimization solvers may take longer, many real engineering\n% problems result in noisy or non-convex objectives and local solvers will\n% often struggle to return a result, or fall into the closest local\n% optima. OPTI provides a range of competitive blackbox global optimization\n% solvers which can return much better results, as well as a white box\n% solver for academic users which guarantees a global solution.\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/math/opti/Examples/Global_NonlinearProgramming.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833789613197, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5541555360439716}}
{"text": "classdef SimpAllInterpolationImplicit2D < SimpAllInterpolationImplicit\n    \n   methods  (Access = public)\n        \n        function obj = SimpAllInterpolationImplicit2D(cParams)\n            obj.init(cParams);\n            obj.computeNstre();\n            obj.computeSymbolicInterpolationFunctions();\n            obj.dmu0 = obj.computeDmu0();\n            obj.dmu1 = obj.computeDmu1();\n            obj.dk0  = obj.computeDKappa0();\n            obj.dk1  = obj.computeDKappa1();\n        end\n\n   end\n        \n    methods  (Access = protected)\n        \n        function [pMu,pKappa] = computePolarizationTensorAsMuKappa(eMatrix,eInclusion,nuMatrix,nuInclusion)\n            coef = obj.compute2Dcoefficients(eMatrix,eInclusion,nuMatrix,nuInclusion);\n            [p1,p2] = obj.computeP1P2(coef);\n            [pMu,pKappa] = obj.computePkappaPmu(p1, p2);\n        end\n        \n        function dmu0 = computeDmu0(obj)\n            E1  = obj.matProp.E1;\n            E0  = obj.matProp.E0;\n            nu1 = obj.matProp.nu1;\n            nu0 = obj.matProp.nu0;\n            mu0 = obj.matProp.mu0;\n            [pMu0,~] = obj.computePolarizationTensorAsMuKappa(E0,E1,nu0,nu1);\n            dmu0     = -mu0*pMu0;\n        end\n        \n        function dmu1 = computeDmu1(obj)\n            E1  = obj.matProp.E1;\n            E0  = obj.matProp.E0;\n            nu1 = obj.matProp.nu1;\n            nu0 = obj.matProp.nu0;\n            mu1 = obj.matProp.mu1;\n            [pMu1,~] = obj.computePolarizationTensorAsMuKappa(E1,E0,nu1,nu0);\n            dmu1     = mu1*pMu1;\n        end\n        \n        function dkappa0 = computeDKappa0(obj)\n            E1     = obj.matProp.E1;\n            E0     = obj.matProp.E0;\n            nu1    = obj.matProp.nu1;\n            nu0    = obj.matProp.nu0;\n            kappa0 = obj.matProp.kappa0;\n            [~,pKappa0] = obj.computePolarizationTensorAsMuKappa(E0,E1,nu0,nu1);\n            dkappa0     = -kappa0*pKappa0;\n        end\n        \n        function dkappa1 = computeDKappa1(obj)\n            E1     = obj.matProp.E1;\n            E0     = obj.matProp.E0;\n            nu1    = obj.matProp.nu1;\n            nu0    = obj.matProp.nu0;\n            kappa1 = obj.matProp.kappa1;\n            [~,pKappa1] = obj.computePolarizationTensorAsMuKappa(E1,E0,nu1,nu0);\n            dkappa1     = kappa1*pKappa1;\n        end\n\n    end\n    \n    methods  (Access = protected, Static)\n    \n        function coef = compute2Dcoefficients(eMatrix,eInclusion,nuMatrix,nuInclusion)\n            coef.a    = (1 + nuMatrix)/(1 - nuMatrix);\n            coef.b    = (3 - nuMatrix)/(1 + nuMatrix);\n            coef.gam  = eInclusion/eMatrix;\n            coef.tau1 = (1 + nuInclusion)/(1 + nuMatrix);\n            coef.tau2 = (1 - nuInclusion)/(1 - nuMatrix);\n            coef.tau3 = (nuInclusion*(3*nuMatrix - 4) + 1)/(nuMatrix*(3*nuMatrix - 4) + 1);\n        end\n        \n        function [p1,p2] = computeP(s)\n            a    = s.a;\n            b    = s.b;\n            gam  = s.gam;\n            tau1 = s.tau1;\n            tau2 = s.tau2;\n            tau3 = s.tau3;\n            p1   = 1/(b*gam+tau1)*(1+b)*(tau1-gam);\n            p2   = 0.5*(a-b)/(b*gam+tau1)*(gam*(gam-2*tau3)+tau1*tau2)/(a*gam+tau2);\n        end\n        \n        function [pMu,pKappa] = computePKappaMu(p1, p2)\n            pMu    = p1;\n            pKappa = 2*p2 + p1;\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/MaterialInterpolation/SimpAllInterpolationImplicit2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5540549102713742}}
{"text": "clear, clc;\n\n% This is an example for running the function altra\n%\n%  Problem:\n%\n%  min  1/2 || x - v||^2 + z * sum_j w_j ||x_{G_j}||\n%\n%  G_j's are nodes with tree structure\n%\n%  The tree structured 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%\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%  Note: \n%  1) If each element of x is a leaf node of the tree and the weight for\n%  this leaf node are the same, we provide an alternative \"efficient\" input\n%  for this kind of node, by creating a \"super node\" with \n%  opts.ind(1,1)=-1; opts.ind(2,1)=-1; and opts.ind(3,1)=the common weight.\n%\n%  2) If the features are well ordered in that, the features of the left\n%  tree is always less than those of the right tree, opts.ind(1,:) and\n%  opts.ind(2,:) contain the \"real\" starting and ending indices. That is to\n%  say, x( opts.ind(1,j):opts.ind(2,j) ) denotes x_{G_j}. In this case,\n%  the entries in opts.ind(1:2,:) are within 1 and n.\n%\n%\n%  If the features are not well ordered, please use the input opts.G for\n%  specifying the index so that  \n%   x( opts.G ( opts.ind(1,j):opts.ind(2,j) ) ) denotes x_{G_j}.\n%  In this case, the entries of opts.G are within 1 and n, and the entries of\n%  opts.ind(1:2,:) are within 1 and length(opts.G).\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%%\n\ncd ..\ncd ..\n\nroot=cd;\naddpath(genpath([root '/SLEP']));\n                     % add the functions in the folder SLEP to the path\n                   \n% change to the original folder\ncd Examples/tree;\n\nn=10000;\nv=randn(n,1);\nind=[ [-1, -1, 0.5]'; [1, 3000, 0.2]'; [3001, 6000, 0.2]'; [6001, 10000, 0.2]';...\n    [1, 10000, 2]'];\n\nnodes=size(ind,2);\n\ntic;\nx=altra(v, n, ind, nodes);\ntoc;\n\n", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Toolbox/SLEP_package_4.1/Examples/tree/example_altra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5540548989696731}}
{"text": "function [x,fval,exitflag,info,Opt] = opti_bintprog(f,A,b,Aeq,beq,x0,opts)\n%OPTI_BINTPROG Solve a BIP using an OPTI BIP Solver (Matlab Overload)\n%\n%   [x,fval,exitflag,info] = opti_bintprog(f,A,b,Aeq,beq,x0) solves the \n%   linear program min f'x where A,b are the inequality constraints, \n%   Aeq,beq are the equality constraints and x0 is the initial guess. All\n%   decision variables are binary only.\n%\n%   [x,fval,exitflag,info] = opti_bintprog(f,...,x0,opts) allows the user \n%   to specify optiset options. This includes specifying a solver via the\n%   'solver' field of optiset.\n%\n%   [x,...,info,Opt] = opti_bintprog(f,...) returns the internally built\n%   OPTI object.\n\n%   Copyright (C) 2011 Jonathan Currie (I2C2)\n\n\n% Handle missing arguments\nif nargin < 7, opts = optiset; end \nif nargin < 6, x0 = []; end\nif nargin < 5, beq = []; end\nif nargin < 4, Aeq = []; end\nif nargin < 3, error('You must supply at least 3 arguments to opti_bintprog'); end\n\n%Build OPTI Object\nOpt = opti('f',f,'ineq',A,b,'eq',Aeq,beq,'x0',x0,'int',repmat('B',size(f)),'options',opts);\n\n%Solve\n[x,fval,exitflag,info] = solve(Opt);\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/Utilities/Matlab Overloads/opti_bintprog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5540548882620436}}
{"text": "function [maxCI minCI] = calculateConfidenceInterval(tau, sPeriod, rCount,alpha,stabDev)\n%This function calculates max and min confidence intervals for the XDEV\n%calculation. The method used is found in the NIST Handbook of Frequency\n%Stability Analysis page 37 section 5.3.1. tau is the array of tau values\n%used in the stability calculation. Sample Period is used to calculate the\n%number of values used in a particular tau calculation. rCount is the\n%number of total readings at the sample period. alpha is an array of values\n%for determine power law noise type. stabDev is the array of XDEV\n%calculations.\n\ntCount = length(tau); %get total number of calculations\nmaxCI = zeros(1,tCount); %initiate arrays\nminCI = zeros(1,tCount);\n\nfor i = 1:tCount %for number of calculations\n    avgCount = tau(i) / sPeriod; %gets count for averaging\n    vCount = rCount / avgCount; %get number of loop iterations needed\n    vCount = floor(vCount); %convert loopCount to integer in case it is a non int\n\n    %perform confidence interval calculation based on noise type\n    if alpha(i) >= 1.5 %dominant noise type is white PM\n        temp = .99*(stabDev(i)/sqrt(vCount));\n    elseif alpha(i) < 1.5 && alpha(i) >= .5 %dominant noise type is flicker PM\n        temp = .99*(stabDev(i)/sqrt(vCount));\n    elseif alpha(i) < .5 && alpha(i) >= -.5 %dominant noise type is white FM\n        temp = .87*(stabDev(i)/sqrt(vCount));\n    elseif alpha(i) < -.5 && alpha(i) >= -1.5 %dominant nosie type is flicker FM\n        temp = .77*(stabDev(i)/sqrt(vCount));\n    else %dominant noise type is random walk FM\n        temp = .75*(stabDev(i)/sqrt(vCount));\n    end\n\n    %set min and max confidence limits\n    maxCI(i) = stabDev(i) + temp;\n    minCI(i) = stabDev(i) - temp;\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/31319-stability-analyzer-53230a/Stability Analyzer 2.0/calculateConfidenceInterval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5540032546621751}}
{"text": "function [obs, hidden] = pomdp_sample(initial_prob, transmat, obsmat, act)\n% SAMPLE_POMDP Generate a random sequence from a Partially Observed Markov Decision Process.\n% [obs, hidden] = sample_pomdp(prior, transmat, obsmat, act)\n%\n% Inputs:\n% prior(i) = Pr(Q(1)=i)\n% transmat{a}(i,j) = Pr(Q(t)=j | Q(t-1)=i, A(t)=a)\n% obsmat(i,k) = Pr(Y(t)=k | Q(t)=i)\n% act(a) = A(t), so act(1) is ignored\n%\n% Output:\n% obs and hidden are vectors of length T=length(act)\n\n\nlen = length(act);\nhidden = mdp_sample(initial_prob, transmat, act);\nobs = zeros(1, len);\nfor t=1:len\n  obs(t) = sample_discrete(obsmat(hidden(t),:));\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/murphy/hmm/pomdp_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5540032381792361}}
{"text": "function wishart_test06 ( )\n\n%*****************************************************************************80\n%\n%% WISHART_TEST06 compares the Wishart and Bartlett sample matrices.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 July 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n\n%\n%  Access the PDFLIB and RNGLIB libraries.\n%\n  addpath ( '../pdflib' );\n  addpath ( '../rnglib' );\n%\n%  Initialize the RNGLIB library.\n%  Normally, we would do this just once, here at the beginning.\n%  In this example, however, we really want to do it just before\n%  we call each of the sampling routines, so that they both access\n%  the same set of random numbers...\n%\n  initialize ( );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'WISHART_TEST06:\\n' );\n  fprintf ( 1, '  Verify that, if using the same set of random numbers,\\n' );\n  fprintf ( 1, '    W = T'' * T,\\n' );\n  fprintf ( 1, '  where\\n' );\n  fprintf ( 1, '    W = wishart_sample ( n, df, sigma );\\n' );\n  fprintf ( 1, '    T = bartlett_sample ( n, df, sigma );\\n' );\n%\n%  Set the parameters.\n%\n  n = 3;\n  df = 5;\n  r = [ 5.0, 1.0, 3.0; ...\n        0.0, 4.0, 2.0; ...\n        0.0, 0.0, 6.0 ];\n  sigma = r' * r;\n  r8mat_print ( n, n, sigma, '  Covariance SIGMA:' );\n%\n%  Initialize the random number package and compute W.\n%\n  initialize ( );\n  w = wishart_sample ( n, df, sigma );\n%\n%  Initialize the random number package again, and compute T.\n%\n  initialize ( );\n  t = bartlett_sample ( n, df, sigma );\n%\n%  Compute T' * T and compare it to W.\n%\n  tt = t' * t;\n\n  diff = r8mat_norm_fro_affine ( n, n, w, tt );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Frobenius norm of error is %g\\n', diff );\n%\n%  Release the PDFLIB and RNGLIB libraries.\n%\n  rmpath ( '../pdflib' );\n  rmpath ( '../rnglib' );\n\n  return\nend\n", "meta": {"author": "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/wishart_test06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.5539920750750272}}
{"text": "function D = hmm_kl (hmm_p,hmm_q)\n% Computes Kullback-Leibler divergence between two Hidden Markov Model\n% distributions, through an approximation (an upper bound) as proposed in\n% M. Do (2003). IEEE Signal Processing Letters 10\n%\n% Author: Diego Vidaurre, OHBA, University of Oxford (2018)\n\nK = length(hmm_p.Pi);\nif K~=length(hmm_q.Pi)\n    error(['The two HMMs must have the same number of states, ' ...\n        'and their order must correspond'])\nend\nif (hmm_p.train.order ~= hmm_q.train.order) || ...\n        (~strcmpi(hmm_p.train.covtype,hmm_q.train.covtype)) || ...\n        (length(hmm_p.train.embeddedlags) ~= length(hmm_q.train.embeddedlags)) || ...\n        (any(hmm_p.train.embeddedlags ~= hmm_q.train.embeddedlags)) || ...\n        (hmm_p.train.zeromean ~= hmm_q.train.zeromean)  \n   error('The state configuration of the two HMMs must be identical') \nend\nhmm = hmm_p; setstateoptions;\nif isfield(hmm_p.state(1),'W')\n    ndim = size(hmm_p.state(1).W.Mu_W,2);\nelse\n    ndim = size(hmm_p.state(1).Omega.Gam_rate,2);\nend\nS = hmm.train.S==1;\nregressed = sum(S,1)>0;\n\nD = 0;\nif hmm_p.train.id_mixture\n   hmm_p.P = 1/K*ones(K); hmm_q.P = 1/K*ones(K); \nend\nnu = compute_nu (hmm_p.Pi,hmm_p.P); % weight vector\n\n% Non-state specific stuff\nswitch train.covtype\n    case {'uniquediag','shareddiag'}\n        for n = 1:ndim\n            if ~regressed(n), continue; end\n            D = D + gamma_kl(hmm_p.Omega.Gam_shape,hmm_q.Omega.Gam_shape, ...\n                hmm_p.Omega.Gam_rate(n),hmm_q.Omega.Gam_rate(n));\n        end\n    case {'uniquefull','sharedfull'}\n        D = D + wishart_kl(hmm_p.Omega.Gam_rate(regressed,regressed),...\n            hmm_q.Omega.Gam_rate(regressed,regressed), ...\n            hmm_p.Omega.Gam_shape,hmm_q.Omega.Gam_shape);\n    case 'pca'\n        D = D + gamma_kl(hmm_p.Omega.Gam_shape,hmm_q.Omega.Gam_shape, ...\n                hmm_p.Omega.Gam_rate,hmm_q.Omega.Gam_rate);\nend\n\n% State specific stuff\nfor k = 1:K\n    \n    % Trans probabilities\n    kk = hmm.train.Pstructure(k,:);\n    D = D + nu(k) * dirichlet_kl(hmm_p.Dir2d_alpha(k,kk),hmm_q.prior.Dir2d_alpha(k,kk));\n    \n    % State distribution\n    hs = hmm_p.state(k);\n    hs0 = hmm_q.state(k);\n    \n    if ~isempty(hs.W.Mu_W)\n        if train.uniqueAR || ndim==1\n            if train.uniqueAR || ndim==1\n                D = D + nu(k) * gauss_kl(hs.W.Mu_W, hs0.W.Mu_W, hs.W.S_W, hs0.W.S_W);\n            else\n                D = D + nu(k) * gauss_kl(hs.W.Mu_W, hs0.W.Mu_W, ...\n                    permute(hs.W.S_W,[2 3 1]), permute(hs0.W.S_W,[2 3 1]));\n            end\n        elseif strcmp(train.covtype,'diag') || ...\n                strcmp(train.covtype,'uniquediag') || strcmp(train.covtype,'shareddiag') || ...\n                strcmp(train.covtype,'pca')\n            for n = 1:ndim\n                D = D + nu(k) * gauss_kl(hs.W.Mu_W(Sind(:,n),n),hs0.W.Mu_W(Sind(:,n),n), ...\n                    permute(hs.W.S_W(n,Sind(:,n),Sind(:,n)),[2 3 1]),...\n                    permute(hs0.W.S_W(n,Sind(:,n),Sind(:,n)),[2 3 1]));\n            end\n        else % full or sharedfull\n            mu_w = hs.W.Mu_W';\n            mu_w = mu_w(:);\n            mu_w0 = hs0.W.Mu_W';\n            mu_w0 = mu_w0(:);\n            D = D + nu(k) * gauss_kl(mu_w,mu_w0, hs.W.S_W, hs0.W.S_W);\n        end\n    end\n    \n    switch train.covtype\n        case 'diag'\n            for n=1:ndim\n                if ~regressed(n), continue; end\n                D = D + nu(k) * gamma_kl(hs.Omega.Gam_shape,hs0.Omega.Gam_shape, ...\n                    hs.Omega.Gam_rate(n),hs0.Omega.Gam_rate(n));\n            end\n        case 'full'\n            try\n                D = D + nu(k) * wishart_kl(hs.Omega.Gam_rate(regressed,regressed),...\n                    hs0.Omega.Gam_rate(regressed,regressed), ...\n                    hs.Omega.Gam_shape,hs0.Omega.Gam_shape);\n            catch\n                error(['Error computing kullback-leibler divergence of the cov matrix - ' ...\n                    'Something strange with the data?'])\n            end            \n    end\n    \n    if ~isempty(orders) && ~train.uniqueAR && ndim>1\n        for n1=1:ndim\n            for n2=1:ndim\n                if (train.symmetricprior && n2<n1) || S(n1,n2)==0, continue; end\n                D = D + nu(k) * gamma_kl(hs.sigma.Gam_shape(n1,n2),hs0.sigma.Gam_shape(n1,n2), ...\n                    hs.sigma.Gam_rate(n1,n2),hs0.sigma.Gam_rate(n1,n2));\n            end\n        end\n    end\n    if ~isempty(orders)\n        for i=1:length(orders)\n            D = D + nu(k) * gamma_kl(hs.alpha.Gam_shape,hs0.alpha.Gam_shape, ...\n                hs.alpha.Gam_rate(i),hs0.alpha.Gam_rate(i));\n        end\n    end\nend\n\nend\n\nfunction nu = compute_nu (Pi,P)\neps = 1e-6;\nnu = Pi * P;\nwhile true\n    nu0 = nu; \n    nu = nu * P;\n    if mean(nu(:)-nu0(:))<eps, break; end\nend  \nend\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/hmm_kl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5539049382556364}}
{"text": "function [u] = spm_erp_u(t,P,M)\n% returns the [scalar] input for EEG models (Gaussian function)\n% FORMAT [u] = spm_erp_u(t,P,M)\n% t      - PST (seconds)\n% P      - parameter structure\n%   P.R  - scaling of [Gaussian] parameters\n%\n% u   - stimulus-related (subcortical) input\n%\n% See spm_fx_erp.m and spm_erp_priors.m\n%__________________________________________________________________________\n%\n% David O, Friston KJ (2003) A neural mass model for MEG/EEG: coupling and\n% neuronal dynamics. NeuroImage 20: 1743-1755\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_erp_u.m 7679 2019-10-24 15:54:07Z spm $\n\n\n% preliminaries - check durations (ms)\n%--------------------------------------------------------------------------\ntry\n    if length(M.dur) ~= length(M.ons)\n        M.dur = M.dur(1) + M.ons - M.ons;\n    end\ncatch\n    M.dur = 32 + M.ons - M.ons;\nend\n\n% check sustained input (0,1)\n%--------------------------------------------------------------------------\ntry\n    if length(M.sus) ~= length(M.ons)\n        M.sus = M.sus(1) + M.ons - M.ons;\n    end\ncatch\n    M.sus = 0 + M.ons - M.ons;\nend\n\n% stimulus - Gaussian (subcortical) impulse\n%--------------------------------------------------------------------------\nnu    = length(M.ons);\nu     = sparse(length(t),nu);\nt     = t*1000;\nfor i = 1:nu\n    \n    % Gaussian bump function\n    %----------------------------------------------------------------------\n    delay  = M.ons(i) + 128*P.R(i,1);\n    scale  = M.dur(i) * exp(P.R(i,2));\n    U      = exp(-(t - delay).^2/(2*scale^2));\n    \n    % sustained inputs\n    %----------------------------------------------------------------------\n    try\n        prop = M.sus(i)*exp(P.R(i,3));\n    catch\n        prop = M.sus(i);\n    end\n    U      = prop*cumsum(U)/sum(U) + U*(1 - prop);\n    u(:,i) = 32*U;\nend\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/dcm_meeg/spm_erp_u.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6442250928250374, "lm_q1q2_score": 0.553816959470571}}
{"text": "\n% Information-Flow Matte Refinement\n% This function implements the matte refinement approach described in\n% Yagiz Aksoy, Tunc Ozan Aydin, Marc Pollefeys, \"Designing Effective \n% Inter-Pixel Information Flow for Natural Image Matting\", CVPR, 2017.\n% 'alphaHat' and 'confidences' parameters are typically obtained by a\n% sampling-based natural matting algorithm. 'confidences' is filled by\n% ones if not provided. Optional input parameter 'params' can be \n% customized by editing the default values in the struct returned \n% by 'getMattingParams('IFM').\n% - **_K parameters represent the number of nonlocal neighbors found\n%   for color mixture,  and intra-U flows, while **_xyw define the effect of\n%   spatial proximity.\n% - **_mult define the weight of each information flow. \n% - loc_*** define the parameters for the matting Laplacian.\n% - refinement_mult determines how much trust is given to the initial\n%   alpha estimation\n\nfunction alpha = informationFlowMatteRefinement(image, trimap, alphaHat, confidences, params, suppressMessages)\n    abmtSetup\n    tic;\n    if ~exist('confidences', 'var') || isempty(confidences)\n        confidences = ones(size(alphaHat(:,:,1)));\n    end\n    if ~exist('params', 'var') || isempty(params)\n        params = getMattingParams('IFM');\n    end\n    if ~exist('suppressMessages', 'var') || isempty(suppressMessages)\n        suppressMessages = false;\n    end\n    if(~suppressMessages) display('Matte refinement via Information-Flow Matting...'); end\n\n    image = im2double(image);\n    trimap = im2double(trimap(:,:,1));\n    alphaHat = im2double(alphaHat(:,:,1));\n\n    % Compute L_IFM\n    unk = trimap < 0.8 & trimap > 0.2;\n    dilUnk = imdilate(unk, ones(3, 3));\n    if(~suppressMessages) display('     Computing color mixture flow...'); end\n    Lap = affinityMatrixToLaplacian(colorMixtureAffinities(image, params.cm_K, dilUnk, [], params.cm_xyw));\n    Lap = params.cm_mult * (Lap' * Lap);\n    if(~suppressMessages) display('     Computing matting Laplacian...'); end\n    Lap = Lap + params.loc_mult * affinityMatrixToLaplacian(mattingAffinity(image, dilUnk, params.loc_win, params.loc_eps));\n    if(~suppressMessages) display('     Computing intra-U flow...'); end\n    Lap = Lap + params.iu_mult * affinityMatrixToLaplacian(colorSimilarityAffinities(image, params.iu_K, unk, unk, params.iu_xyw));\n\n    if(~suppressMessages) display('     Solving for alphas...'); end\n    alpha = solveForAlphas(Lap, trimap, params.lambda, params.usePCGtoSolve, alphaHat, confidences, params.refinement_mult);\n\n    alpha = reshape(alpha, [size(image, 1), size(image, 2)]);\n\n    dur = toc;\n    if(~suppressMessages) display(['Done. It took ' num2str(dur) ' seconds.']); end\nend\n", "meta": {"author": "yaksoy", "repo": "AffinityBasedMattingToolbox", "sha": "ab3951065321b67d3ad67333779cbb2078474939", "save_path": "github-repos/MATLAB/yaksoy-AffinityBasedMattingToolbox", "path": "github-repos/MATLAB/yaksoy-AffinityBasedMattingToolbox/AffinityBasedMattingToolbox-ab3951065321b67d3ad67333779cbb2078474939/informationFlowMatteRefinement.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5537448836368163}}
{"text": "classdef UF5 < PROBLEM\n% <multi> <real> <large/none>\n% Unconstrained benchmark MOP\n\n%------------------------------- Reference --------------------------------\n% Q. Zhang, A. Zhou, S. Zhao, P. N. Suganthan, W. Liu, and S. Tiwari,\n% Multiobjective optimization test instances for the CEC 2009 special\n% session and competition, School of CS & EE, University of Essex, Working\n% Report CES-487, 2009.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = [0,zeros(1,obj.D-1)-1];\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            J1 = 3 : 2 : obj.D;\n            J2 = 2 : 2 : obj.D;\n            Y  = X - sin(6*pi*repmat(X(:,1),1,obj.D)+repmat(1:obj.D,size(X,1),1)*pi/obj.D);\n            hY = 2*Y.^2 - cos(4*pi*Y) + 1;\n            PopObj(:,1) = X(:,1)   + (1/20+0.1)*abs(sin(20*pi*X(:,1)))+2*mean(hY(:,J1),2);\n            PopObj(:,2) = 1-X(:,1) + (1/20+0.1)*abs(sin(20*pi*X(:,1)))+2*mean(hY(:,J2),2);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = (0:1:20)'/20;\n            R(:,2) = 1 - R(:,1);\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/UF/UF5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5537448803461487}}
{"text": "function days = month_length_republican ( y, m )\n\n%*****************************************************************************80\n%\n%% MONTH_LENGTH_REPUBLICAN returns the number of days in a Republican month.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 July 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer Y, the year in which the month occurred.\n%\n%    Input, integer M, the number of the month.\n%\n%    Output, integer DAYS, the number of days\n%    in the month.\n%\n\n%\n%  Copy the input.\n%\n  m2 = m;\n  y2 = y;\n%\n%  Check the input.\n%\n  [ y2, m2, ierror ] = ym_check_republican ( y2, m2 );\n\n  if ( ierror ~= 0 )\n    days = 0;\n    return\n  end\n%\n%  Get the number of days in the month.\n%\n  if ( 1 <= m2 && m2 <= 12 )\n    days = 30;\n  else if ( m2 == 13 )\n    if ( year_is_leap_republican ( y2 ) )\n      days = 6;\n    else\n      days = 5;\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/calpak/month_length_republican.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210895, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.5537448736424688}}
{"text": "function r = sqr(a)\n%SQR          Taylor (elementwise) square  sqr(a)\n%\n\n% written  05/21/09     S.M. Rump\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  e = 1e-30;\n  if 1+e==1-e                           % fast check for rounding to nearest\n    rndold = 0;\n  else\n    rndold = getround;\n    setround(0)\n  end\n\n  K1 = getappdata(0,'INTLAB_TAYLOR_ORDER') + 1;\n\n  r = a;\n  r.t(1,:) = sqr(a.t(1,:));\n  for j=2:K1\n    r.t(j,:) = sum(a.t(1:j,:).*a.t(j:-1:1,:),1);\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/taylor/@taylor/sqr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5537448685841232}}
{"text": "function [C,CompositeObjectiveValue, SingleObjectiveValues]=ITERevaluate_X0...\n    (Problem,Constraints,Spec,Objectives,askflag,printflag)\n\nif nargin < 5; askflag = true; end\nif nargin < 6; printflag = true; end\nif askflag\nchoice = txtmenu('What do you want to evaluate?',...\n    'Current design point','Lower bound','Upper bound');\n% choice = 0;\nswitch choice\n    case 0\n        x0 = Problem.x0(Problem.activeX);\n    case 1\n        x0 = Problem.lb(Problem.activeX);\n    case 2\n        x0 = Problem.ub(Problem.activeX);\nend\nelse\n    x0 = Problem.x0(Problem.activeX);\nend\n        \n[C] = EVALnonlcons(x0,Problem,Constraints,Spec);\n\nif printflag\njnk=Constraints.conLabels(Constraints.active_cons);\nfprintf('%30s\\t\\t%s\\n','CONSTRAINT','MARGIN (%)');\nfor ii = 1:nnz(Constraints.active_cons)\n    fprintf('%30s\\t\\t%-3.1f\\n',jnk{ii},-100*C(ii));\nend\ndisp(' ')\nend\n\n[CompositeObjectiveValue, SingleObjectiveValues] = EVALobjective...\n    (x0,Problem,Objectives,Spec,0,'single');\n\nif printflag\njnk=Objectives.ObjLabels;\n\n\nfprintf('%15s\\t\\t%10s\\t\\t%s\\n','OBJECTIVE','WEIGHTING','VALUE');\nfor ii = 1:Objectives.nObj\n    if Objectives.weightings(ii)\n     fprintf('%15s\\t\\t%9.2f\\t\\t%-3.2d\\n',jnk{ii},...\n         Objectives.weightings(ii),SingleObjectiveValues(ii));\n    end\nend\n\ndisp(' ')\nfprintf('Composite Objective Value:   %d\\n',CompositeObjectiveValue')\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/41725-core-conceptual-optimization-of-rotorcraft-environment/CORE_v0p7 - for upload may 2013/CORE/ITERevaluate_X0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5537448668572265}}
{"text": "function F = acscd(F, varargin)\n%ACSCD   Inverse cosecant of a CHEBFUN, result in degrees.\n%   ACSCD(F) computes the inverse cosecant (in degrees) of the CHEBFUN F.\n%\n%   ACSCD(F, PREF) does the same but uses the CHEBFUNPREF object PREF when\n%   computing the composition.\n%\n% See also CSCD, ACSC.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. See\n% http://www.chebfun.org/ for Chebfun information.\n\n% Call the compose method:\nF = compose(F, @acscd, varargin{:});\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/acscd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956580806813577, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5537448651303294}}
{"text": "% SCRIPT TEST THE DIRECT DYNAMICS OF A 2 DOF PLANAR ROBOT ROBOT\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 <http://www.gnu.org/licenses/>.\n\nclose all\n\nfprintf('\\nTHE SIMULATION PRESENTS THE ROBOT AT AN INITIAL POSITION WHEN NO TORQUES ARE APPLIED\\n')\n\n%load robot parameters\nrobot=load_robot('example', '2dofplanar');\n\n%simulate for 10 seconds, change this depending on your computer speed and\n%the total time that you want to simulate\ntotal_simulation_time = 10; \n\n%initial position and joint speed\nq0 = [0 0]';\nqd0 = [0 0]';\n\ndrawrobot3d(robot, q0);\nadjust_view(robot);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The student should try different combinations of the following parameters:\n%   g: the direction of the gravity vector. In this case, if we select g=[0  0 9.81]'; \n%       the movement of the arm is not affected by the gravity, since it\n%       moves in a plane perpendicular to the gravity vector.\n%   tau: the torques applied to each joint. The student should observe the effects of selecting\n%       tau = [0 0 0]' or different values in combination with the\n%       direction of the vector g.\n%   robot.dynamics.friction = 0 selects no friction at the joints, whereas\n%       robot.dynamics.friction = 1 considers that there exists friction. This\n%       friction is modelled by robot.motors.Viscous (viscous friction) and\n%       robot.motors.Coulomb (Coulomb friction). The student should observe\n%       that selecting g=[0  9.81 0]' and tau = [0 0 0]' and\n%       robot.dynamics.friction = 0 turns into an infinite triple pendulum\n%       movement. In addition, selecting selecting g=[0  9.81 0]' and tau = [0 0 0]' and\n%       robot.dynamics.friction = 1 simulates the case in which the triple\n%       pendulum converges to a steady solution with the three links\n%       hanging along the Y direction.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%you may redefine the gravity vector\n%in this case you may one of the next two lines, that define\n%the gravity acting along the Y axis or the Z axis, respectively.\ng=[0  -9.81 0]'; %y0 axis\n\ntau = [20 20]';%no torques applied\n%select friction or not\nrobot.dynamics.friction = 1;\n\nfprintf('\\nCOMPUTING FORWARD DYNAMICS (this may take a while)')\n\n%this may take a while, since it requires integration\n%of the acceleration at each time step\n[t, q, qd] = forwarddynamic(robot, total_simulation_time, q0, qd0, tau, g, []);\n\nfigure, plot(t, q), grid, title('Position vs. time')\nxlabel('time (s)'), ylabel('Position (rad)')\nlegend('q_1', 'q_2', 'q_3', 'q_4', 'q_5', 'q_6');\n\nfigure, plot(t, qd), grid, title('Speed vs. time')\nxlabel('time (s)'), ylabel('Speed (rad/s)')\nlegend('qd_1', 'qd_2', 'qd_3', 'qd_4', 'qd_5', 'qd_6');\n\n%plot results faster in animate!\nqq = q(:,1:2:end);\n\n%animate it!!\nanimate(robot, qq)\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/forwarddynamics_2DOF_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6959583124210895, "lm_q1q2_score": 0.553744861839662}}
{"text": "classdef RMMEDA_F9 < PROBLEM\n% <multi> <real> <large/none>\n% Benchmark MOP for testing RM-MEDA\n\n%------------------------------- Reference --------------------------------\n% Q. Zhang, A. Zhou, and Y. Jin, RM-MEDA: A regularity model-based\n% multiobjective estimation of distribution algorithm, IEEE Transactions on\n% Evolutionary Computation, 2008, 12(1): 41-63.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 2;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = [1,zeros(1,obj.D-1)+10];\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            t = X(:,2:end).^2 - repmat(X(:,1),1,size(X,2)-1);\n            g = sum(t.^2/4000,2) - prod(cos(t./repmat(sqrt(1:size(X,2)-1),size(X,1),1)),2) + 2;\n            PopObj(:,1) = X(:,1);\n            PopObj(:,2) = g.*(1-sqrt(PopObj(:,1)./g));\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R(:,1) = linspace(0,1,N)';\n            R(:,2) = 1 - sqrt(R(:,1));\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            R = obj.GetOptimum(100);\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/MOPs with variable linkages/RMMEDA_F9.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5537350127322508}}
{"text": "function varargout = contour3( f, varargin )\n%CONTOUR3   3-D contour plot of a SPHEREFUN.\n%   CONTOUR3(F) is a contour plot of F treating the values of F as heights\n%   above the sphere, analagous to SURF(F, 'projection', 'bumpy'). A\n%   contour plot shows the level curves of F for some values V. The values\n%   V are chosen automatically.\n%\n%   CONTOUR3(F, N) draws N contour lines, overriding the automatic number.\n%   The values V are still chosen automatically.\n%   \n%   CONTOUR3(F, V) draws LENGTH(V) contour lines at the values specified in\n%   the vector V. Use CONTOUR3(F, [V V]) to compute a single contour at the\n%   level V.\n%\n%   CONTOUR3(F, 'NUMPTS', N) plots the contour lines on an N by N uniform\n%   grid. If NUMPTS is not given then we plot on a 200 by 200 grid.\n%\n% See also CONTOUR, CONTOURF.\n\n% Copyright 2020 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( isempty(f) )  % Empty check.\n    contour3([]);\n    return\nend\n\nholdState = ishold;\n\n% Minimum number of plotting points:\nminplotnum = 200;\n\n% Extract from the inputs the user defined options: \nj = 1; \nargin = {};\nwhile ( ~isempty(varargin) )\n    if ( strcmpi(varargin{1}, 'numpts') ) % If given numpts then use them.\n        minplotnum = varargin{2};\n        varargin(1:2) = [];\n    else\n        argin{j} = varargin{1};\n        varargin(1) = [];\n        j = j+1;\n    end\nend\n\nif ( isa(f, 'spherefun') )\n    dom = f.domain;\n    % Evaluate at equally spaced grid: \n    x = linspace(dom(1), dom(2), minplotnum);\n    y = linspace(dom(3), dom(4), minplotnum);\n    vals = sample(f, minplotnum-1, minplotnum);\n    vals = [vals vals(:,1)];\nelse\n    error('CHEBFUN:SPHEREFUN:contour3:inputs', ...\n        'Input must be a spherefun.');\nend\n\nif ( iscolat(f) )\n    xc = @(ll,tt,rr) rr.*cos(ll).*sin(tt);\n    yc = @(ll,tt,rr) rr.*sin(ll).*sin(tt);\n    zc = @(tt,rr) rr.*cos(tt);\nelse\n    xc = @(ll,tt,rr) rr.*cos(ll).*cos(tt);\n    yc = @(ll,tt,rr) rr.*sin(ll).*cos(tt);\n    zc = @(tt,rr) rr.*sin(tt);\nend\n\n% Use contour rather than contourc so that it can handle parsing the inputs\n% correctly.\n[c, h] = contour( x', y', vals, argin{:} );\n\n% Extract out the options we need to plot the contours with plot3.\nLW = 'LineWidth'; \nlw = h.LineWidth;\nLS = 'LineStyle'; \nls = h.LineStyle;\nLC = 'Color'; \nlc = h.LineColor;\nlevelList = h.LevelList;\nclrmap = parula(numel(levelList));\n\n% Remove the contour plot that was generated.\ndelete(h);\n\nscl = 0.15;           % Match the bumpy parameter in SPHEREFUN/SURF().\nlim = [-1-scl 1+scl]; % Pad the axis limits.\nm = minandmax2(f);\n\n% If the plot is not being added to another, then set the axis properties.\nif ( ~holdState )\n    xlim(lim), ylim(lim), zlim(lim)\n    daspect([1 1 1])\n    grid on, box off\n    hold on\nend\nview(3)\n\ncl = size(c,2);\nk = 1;\nwhile ( k < cl )\n    kl = c(2,k);\n    v = k+1:k+kl;\n\n    % Bump out the radial components according to the function values.\n    rr = rescale(c(1,k), 1-scl, 1+scl, 'InputMin', m(1), 'InputMax', m(2));\n    xv = xc(c(1,v), c(2,v), rr);\n    yv = yc(c(1,v), c(2,v), rr);\n    zv = zc(c(2,v), rr);\n\n    % If the line color is a float then we are plotting all contours in a\n    % single color.\n    if ( isfloat(lc) )\n        plot3(xv, yv, zv, LW, lw, LC, lc, LS, ls);\n    else\n        % We need to plot each contour in a color using the default \n        % colormap.\n        % Determine the color for the level being plotted.\n        clr = clrmap(abs(c(1, k) - levelList) < 10*eps, :);\n        plot3(xv, yv, zv, LW, lw, LC, clr, LS, ls);\n    end\n\n    k = k+kl+1;\nend\n\nif ( ~holdState )\n    hold off\nend\n\n% Return plot handle if appropriate.\nif ( nargout >= 1 )\n    warning('CHEBFUN:SPHEREFUN:contour3:outputs', ...\n        'Outputs from contour3 are not supported');\n    varargout = { [], [] };\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/@spherefun/contour3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.5537350053717084}}
{"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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\n%%begin\n\n% A serial link manipulator comprises a series of links.  Each link is described\n% by four Denavit-Hartenberg parameters.\n%\n% Let's define a simple 2 link manipulator.  The first link is\n\nL1 = Link('d', 0, 'a', 1, 'alpha', pi/2)\n\n% The Link object we created has a number of properties\nL1.a\nL1.d\n\n% and we determine that it is a revolute joint\nL1.isrevolute\n\n% For a given joint angle, say q=0.2 rad, we can determine the link transform\n% matrix\nL1.A(0.2)\n\n% The second link is\nL2 = Link('d', 0, 'a', 1, 'alpha', 0)\n\n% Now we need to join these into a serial-link robot manipulator\n\nbot = SerialLink([L1 L2], 'name', 'my robot')\n% The displayed robot object shows a lot of details.  It also has a number of\n% properties such as the number of joints\nbot.n\n\n% Given the joint angles q1 = 0.1 and q2 = 0.2 we can determine the pose of the\n% robot's end-effector\n\nbot.fkine([0.1 0.2])\n% which is referred to as the forward kinematics of the robot.  This, and the\n% inverse kinematics are covered in separate demos.\n\n% Finally we can draw a stick figure of our robot\n\nbot.plot([0.1 0.2])\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/robot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5537349913651548}}
{"text": "% Script demonstrating usage of the ccmod function.\n%\n% Author: Brendt Wohlberg <brendt@lanl.gov>  Modified: 2015-04-09\n%\n% This file is part of the SPORCO library. Details of the copyright\n% and user license can be found in the 'Copyright' and 'License' files\n% distributed with the library.\n\n\n% Training images\nS0 = zeros(512, 512, 5);\nS0(:,:,1) = single(stdimage('lena.grey')) / 255;\nS0(:,:,2) = single(stdimage('barbara.grey')) / 255;\nS0(:,:,3) = single(stdimage('kiel.grey')) / 255;\nS0(:,:,4) = single(rgb2gray(stdimage('mandrill'))) / 255;\ntmp = single(stdimage('man.grey')) / 255;\nS0(:,:,5) = tmp(101:612, 101:612);\n\n\n%Reduce images size to speed up demo script\ntmp = zeros(256, 256, 5);\nfor k = 1:size(S0,3),\n  tmp(:,:,k) = imresize(S0(:,:,k), 0.5);\nend\nS0 = tmp;\n\n\n% Filter input images and compute highpass images\nnpd = 16;\nfltlmbd = 5;\n[Sl, Sh] = lowpass(S0, fltlmbd, npd);\n\n% Load dictionary\nload([sporco_path '/Data/ConvDict.mat']);\ndmap = containers.Map(ConvDict.Label, ConvDict.Dict);\nD0 = dmap('12x12x36');\n\n\n% Set up cbpdn parameters\nlambda = 0.1;\nopt = [];\nopt.Verbose = 1;\nopt.MaxMainIter = 200;\nopt.AutoRho = 1;\nopt.AutoRhoPeriod = 1;\nopt.RelaxParam = 1.8;\n\n% Compute sparse representation on current dictionary\n[X, optinf] = cbpdn(D0, Sh, lambda, opt);\n\n\n% Set up ccmod parameters\nopt = [];\nopt.Verbose = 1;\nopt.MaxMainIter = 500;\nopt.sigma = size(Sh,3);\nopt.AutoSigma = 1;\nopt.AutoSigmaPeriod = 1;\nopt.RelaxParam = 1.8;\nopt.AuxVarObj = 1;\n\n% Update dictionary for training set S\n[D1, optinf1] = ccmod(X, Sh, size(D0), opt);\n\n\n% Plot functional value and residuals\nfigure;\nsubplot(1,3,1);\nplot(optinf1.itstat(:,2));\nxlabel('Iterations');\nylabel('Functional value');\nsubplot(1,3,2);\nsemilogy(optinf1.itstat(:,4));\nxlabel('Iterations');\nylabel('Primal residual');\nsubplot(1,3,3);\nsemilogy(optinf1.itstat(:,5));\nxlabel('Iterations');\nylabel('Dual residual');\n\n\n% Update dictionary with new filter sizes for training set S\ndsz = [repmat([12 12]', [1 24]) repmat([8 8]', [1 12])];\n[D2, optinf2] = ccmod(X, Sh, dsz, opt);\n\n\n% Display dictionaries\nfigure;\nsubplot(1,3,1);\nimdisp(tiledict(D0));\ntitle('D0');\nsubplot(1,3,2);\nimdisp(tiledict(D1));\ntitle('D1');\nsubplot(1,3,3);\nimdisp(tiledict(D2, dsz));\ntitle('D2');\n\n\n% Plot functional value evolution\nfigure;\nplot(optinf1.itstat(:,2), 'r');\nhold on;\nplot(optinf2.itstat(:,2), 'b');\nhold off;\nxlabel('Iterations');\nylabel('Functional value');\nlegend('D2', 'D3');\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/ConvSR_Image_Fusion_Codes/sporco/Demo/demo_ccmod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5536885416436088}}
{"text": "function mimgR = red_channel_mean2(ops)\n\n% numPlanes = length(ops.planesToProcess);\n\n%% build file list with red channel\n\nif (isfield(ops, 'SubDirsRed') && ~isempty(ops.SubDirsRed))\n   subDirsRed = ops.SubDirsRed;\nelse\n    if (isfield(ops, 'expred') && ~isempty(ops.expred))\n        for i = 1:length(ops.expred)\n            subDirsRed{i} = sprintf('%d', ops.expred(i));\n        end\n    else\n        warning('could not find red channel info, returning...')\n        return;\n    end \nend\n%%\n% build file list\nfsrootRED = [];\n\nfor j = 1:length(subDirsRed)\n    fsrootRED{j} = dir(fullfile(ops.RootDir, subDirsRed{j}, '*.tif'));\n    \n    for k = 1:length(fsrootRED{j})\n        fsrootRED{j}(k).name = fullfile(ops.RootDir, subDirsRed{j}, fsrootRED{j}(k).name);         \n    end\nend\n\n%%\nfsRED = [];\nfor j = 1:length(fsrootRED)\n    fsRED = [fsRED {fsrootRED{j}.name}];\nend\n\n\n%%\nD = [];\nfor k = 1:length(fsRED)    \n    data = loadFramesBuff(fsRED{k});\n    \n    data = cat(3, D, data);    \nend\n\n\n%%\nclear mimgR\nfor j = 1:ops.nplanes\n    i0 = ops.nchannels_red + (j-1)*ops.nchannels_red; \n    %mimgR(:,:,j) = mean(data(:,:,i0:ops.nplanes*ops.nchannels:end), 3);\n    datj = data(:,:,i0:ops.nplanes*ops.nchannels_red:end);\n    ops1  = AlignIterativeKriging(datj, ops);\n    mimgR(:,:,j) = ops1.mimg;    \nend\n\n%%", "meta": {"author": "cortex-lab", "repo": "Suite2P", "sha": "c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5", "save_path": "github-repos/MATLAB/cortex-lab-Suite2P", "path": "github-repos/MATLAB/cortex-lab-Suite2P/Suite2P-c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5/redChannel/red_channel_mean2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5536885400359379}}
{"text": "% DEMOIL5 Oil data with partially independent training conditional.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'oil';\nexperimentNo = 5;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('pitc');\noptions.optimiser = 'scg';\nlatentDim = 2;\nd = size(Y, 2);\n\nmodel = fgplvmCreate(latentDim, d, Y, options);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\ncapName = dataSetName;;\ncapName(1) = upper(capName(1));\nsave(['dem' capName num2str(experimentNo) '.mat'], 'model');\n\nif exist('printDiagram') & printDiagram\n  fgplvmPrintPlot(model, lbls, capName, experimentNo);\nend\n\n\n% Load the results and display dynamically.\nfgplvmResultsDynamic(dataSetName, experimentNo, 'vector')\n\n% compute the nearest neighbours errors in latent space.\nerrors = fgplvmNearestNeighbour(model, lbls);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demOil5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629215, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5536885333007845}}
{"text": "function [H2,Z2,sLen2,iter]=FGD_H(V,W,H,Z,Lpos,Lneg,tol)\n\n% Fast gradient descent (FGD) with Newton method for NPAF\n% Copyright@Naiyang Guan and Dacheng Tao\n% Arguments:\n%     sLen: step length\n\n% Calculate scaled negative gradient at H\nn=size(H,2);\nG=H.*(W'*(V./Z)+H*Lneg)./(sum(W)'*ones(1,n)+H*Lpos)-H;\nL=Lpos-Lneg;\nZ1=W*G;\na=sum(sum(L.*(G'*G)));\nd=sum(sum(L.*(G'*H)))+sum(sum(Z1));\nC=Z./Z1;\n\n% Newton method\nsLen=1;\nfor iter=1:20,\n    [sum1,sum2]=SumC1(V,C,sLen);\n    sLen1=sLen-(a*sLen-sum1+d)/(a+sum2);\n    if abs(sLen1-sLen)<tol,\n        break;\n    else\n        sLen=sLen1;\n    end\nend\n\n% Step length to boundary of positive orthant\nif min(G(:))>=0\n    sLen3=Inf;\nelse\n    C=H./G;\n    sLen3=min(-C(C<0));\nend\n\n% Best step length\nsLen2=max(min(sLen1,0.99*sLen3),1);\nH2=H+sLen2*G;\nZ2=Z+sLen2*Z1;\n\nreturn;", "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/FGD_H.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5536643225769678}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% shanChen.m: Multi-component fluid, using a LB method,\n%   based on the Shan-Chen model\n% [X.Shan and H.Chen, http://dx.doi.org/10.1103/PhysRevE.47.1815].\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Lattice Boltzmann sample, written in Matlab\n% Copyright (C) 2008 Orestis Malaspinas, Andrea Parmigiani, Jonas Latt\n% Address: EPFL-STI-LIN Station 9\n% E-mail: orestis.malaspinas@epfl.ch\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 (at your option) any later version.\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% You should have received a copy of the GNU General Public\n% License along with this program; if not, write to the Free\n% Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n% Boston, MA  02110-1301, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclear\nclf\n\n% GENERAL FLOW CONSTANTS\n\nly           = 201;\nlx           = 201;\n\nG = -1.2;  % Amplitude of the molecular interaction force\n\nomega1 = 1.;  % Relaxation parameter for fluid 1\nomega2 = 1.;  % Relaxation parameter for fluid 2\n\nmaxT   = 80000;    % total number of iterations\ntPlot  = 40;       % iterations between successive graphical outputs\n\n% D2Q9 LATTICE CONSTANTS\ntNS   = [4/9, 1/9,1/9,1/9,1/9, 1/36,1/36,1/36,1/36];\ncxNS  = [  0,   1,  0, -1,  0,    1,  -1,  -1,   1];\ncyNS  = [  0,   0,  1,  0, -1,    1,   1,  -1,  -1];\noppNS = [  1,   4,  5,  2,  3,    8,   9,   6,   7];\n\n[y,x] = meshgrid(1:ly,1:lx);\n\ndrho = 0.001;\ndelta_rho = -drho*(1-2.0*rand(lx));\n\n% INITIAL CONDITION FOR BOTH DISTRIBUTION FUNCTIONS: (T=0) ==> TIn(i) = t(i)\nfor i=1:9\n    fIn(i,1:lx,1:ly) = tNS(i).*(1.0 + delta_rho);\n    gIn(i,1:lx,1:ly) = tNS(i).*(1.0 - delta_rho);\nend\n\nrho1  = reshape(sum(fIn),lx,ly);\nimagesc(rho1');\ncolorbar\ntitle('Fluid 1 density');\naxis equal off; drawnow\n\n% MAIN LOOP (TIME CYCLES)\nGomega1 = G/omega1;\nGomega2 = G/omega2;\nfor cycle = 1:maxT\n    % MACROSCOPIC VARIABLES\n    rho1 = sum(fIn);\n    rho2 = sum(gIn);\n    jx1  = reshape ( (cxNS * reshape(fIn,9,lx*ly)), 1,lx,ly);\n    jy1  = reshape ( (cyNS * reshape(fIn,9,lx*ly)), 1,lx,ly);\n    jx2  = reshape ( (cxNS * reshape(gIn,9,lx*ly)), 1,lx,ly);\n    jy2  = reshape ( (cyNS * reshape(gIn,9,lx*ly)), 1,lx,ly);\n   \n    rhoTot_OMEGA = rho1*omega1 + rho2*omega2;\n    uTotX = (jx1*omega1+jx2*omega2) ./ rhoTot_OMEGA;\n    uTotY = (jy1*omega1+jy2*omega2) ./ rhoTot_OMEGA;\n\t\n    rhoContrib1x = 0.0;\n    rhoContrib2x = 0.0;\n    \n    rhoContrib1y = 0.0;\n    rhoContrib2y = 0.0;\n    for i=2:9\n        rhoContrib1x = rhoContrib1x + circshift(rho1*tNS(i), [0,cxNS(i),cyNS(i)])*cxNS(i);\n        rhoContrib1y = rhoContrib1y + circshift(rho1*tNS(i), [0,cxNS(i),cyNS(i)])*cyNS(i);\n        \n        rhoContrib2x = rhoContrib2x + circshift(rho2*tNS(i), [0,cxNS(i),cyNS(i)])*cxNS(i);\n        rhoContrib2y = rhoContrib2y + circshift(rho2*tNS(i), [0,cxNS(i),cyNS(i)])*cyNS(i);\n    end\n    \n    uTotX1 = uTotX - Gomega1.*rhoContrib2x; %POTENTIAL CONTRIBUTION OF FLUID 2 ON 1\n    uTotY1 = uTotY - Gomega1.*rhoContrib2y;\n    \n    uTotX2 = uTotX - Gomega2.*rhoContrib1x; %POTENTIAL CONTRIBUTION OF FLUID 2 ON 1\n    uTotY2 = uTotY - Gomega2.*rhoContrib1y;\n\n   % COLLISION STEP FLUID 1 AND 2\n   for i=1:9\n      cuNS1        = 3*(cxNS(i)*uTotX1+cyNS(i)*uTotY1);\n      cuNS2        = 3*(cxNS(i)*uTotX2+cyNS(i)*uTotY2);\n      \n      fEq(i,:,:)   = rho1 .* tNS(i) .* ...\n                       ( 1 + cuNS1 + 0.5*(cuNS1.*cuNS1) - 1.5*(uTotX1.^2+uTotY1.^2) );\n                       \n      gEq(i,:,:)   = rho2 .* tNS(i) .* ...\n                       ( 1 + cuNS2 + 0.5*(cuNS2.*cuNS2) - 1.5*(uTotX2.^2+uTotY2.^2) );\n                       \n      fOut(i,:,:)  = fIn(i,:,:) - omega1 .* (fIn(i,:,:)-fEq(i,:,:));\n      gOut(i,:,:)  = gIn(i,:,:) - omega2 .* (gIn(i,:,:)-gEq(i,:,:));\n   end\n\n   % STREAMING STEP FLUID 1 AND 2\n   for i=1:9\n      fIn(i,:,:) = circshift(fOut(i,:,:), [0,cxNS(i),cyNS(i)]);\n      gIn(i,:,:) = circshift(gOut(i,:,:), [0,cxNS(i),cyNS(i)]);\n   end\n\n   % VISUALIZATION\n   if(mod(cycle,tPlot)==0)\n       rho1     = reshape(rho1,lx,ly);\n       imagesc(rho1'); colorbar\n       title('Fluid 1 density');\n       axis equal off; drawnow\n   end\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/LBM/shanchen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.6297746143530798, "lm_q1q2_score": 0.5536643204563437}}
{"text": "function maskM = fastPolyFill(pointsM,optS)\n%function maskM = fastPolyFill(pointsM,optS)\n%fastPolyFill:  fills in images given polygons defining edges.\n%Intention is to only fill a voxel if it's center is in the polygon.\n%Faster than previous version by a significant factor (about x10).\n%JOD; 17 June 05.\n%Fixed bug, 5 July 05.\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n%     This version of CERR is free software: you can redistribute it and/or modify\n%     it under the terms of the GNU General Public License as published by\n%     the Free Software Foundation, either version 3 of the License, or\n%     (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR.  If not, see <http://www.gnu.org/licenses/>.\n\nimageSizeV = optS.ROIImageSize;\n\nxOffset = optS.xCTOffset;\nyOffset = optS.yCTOffset;\n\nnumRows = double(imageSizeV(1));\nnumCols = double(imageSizeV(2));\n\nxInV = pointsM(:,1);\nyInV = pointsM(:,2);\n\nmaskM = zeros(numRows,numCols);\n%could also be a double.\n\n%preallocate a table of voxel indices\n%'next to' refers to voxel centers just to the right of where polygon\n%edges cross a line connecting voxel centers.\nnextToPtsM = sparse(numRows * 4, numCols * 4); %hard to imagine bigger (sparse is faster than full)\nnumNextToPtsV = zeros(numRows,1);\n\n%convert to \"row and col space\", that is, a continuous space where\n%s is a coord that runs from 1 to numCols (along x axis)\n%t is a coord that runs from 1 to numRows (along -y axis)\nsInV = (xInV - xOffset)/optS.ROIxVoxelWidth + (numCols + 1)/2;\ntInV = (yInV - yOffset)/optS.ROIyVoxelWidth + (numRows + 1)/2;\n\n% % APA: snap points to integer-grid using nearest neighbor interpolation and\n% % delete duplicates\n% [S,T] = meshgrid(1:numCols+1,1:numRows+1);\n% indSnap = interp2(S,T,reshape(1:(numCols+1)*(numRows+1),numRows+1,numCols+1),sInV,tInV,'*nearest');\n% STpts = [S(ind2sub([numCols+1 numRows+1],indSnap)) T(ind2sub([numCols+1 numRows+1],indSnap))];\n% goodPtsV = [1;any(diff(STpts),2)];\n% sInV = STpts(find(goodPtsV),1);\n% tInV = STpts(find(goodPtsV),2);\n\n%For each polygonal element, compute and add one to 'row starters,' centers of\n%voxels (assumed at image coords) whose rows cross the polygonal elements\n%and are the first element to the right of that polygonal element's row crossing.\n%\n%Use the parameterization col = n * deltaRow + c + rowURPt    (URPt = upper\n%right point).\n%\n%Algorithm:\n%1.  Determine n\n%2.  Determine c\n%3.  Determine vector of row crossings\n%4.  Determine vector of column crossings\n%5.  Add one to row starters.\n\n%Loop over polygonal elements\n%For polygonal elements:\n\nshift_sV = [sInV(end); sInV(1:end-1)];\nshift_tV = [tInV(end); tInV(1:end-1)];\n\nsM = [sInV(:), shift_sV];\ntM = [tInV(:), shift_tV];\n\n%Loop over polygonal edges, put ones where voxel centers are inside\n%polygon.\nfor i = 1 : length(sInV)\n    \n    if tM(i,1) ~= tM(i,2)   %skip horizontal lines\n        \n        tMax = max([tM(i,1),tM(i,2)]);\n        tMin = min([tM(i,1),tM(i,2)]);\n        \n        %determine n (line parameterization: s = n * t + c )\n        n = (sM(i,1) - sM(i,2))/(tM(i,1) - tM(i,2));\n        %determine c, could vectorize these two\n        c = sM(i,1) - n * tM(i,1);\n        \n        %get delta_tV\n        tPtsV = ceil(tMin) : floor(tMax);\n%         tPtsV = tMin+1 : tMax; % APA\n        delta_tV = tPtsV - tMax;\n        sPtsV = n * delta_tV + c + n * tMax; %these are s values at edge 'crossings'\n        \n        %derive s values 'next to the right' of the crossings\n        sVoxelsV = ceil(sPtsV);\n        \n        %catalogue\n        for j = 1: length(sVoxelsV)            \n            num = numNextToPtsV(tPtsV(j));\n            numNextToPtsV(tPtsV(j)) = num + 1;\n            nextToPtsM(tPtsV(j),num+1) = sVoxelsV(j);         \n        end\n        \n    end\n    \nend\n\n%This should be faster than the oft-used cumsum trick:\nfor i = 1 : numRows\n    num = numNextToPtsV(i);\n    if num ~=0\n        %get 'em\n        nextToPtsV = nextToPtsM(i,1:num);\n        %sort 'em\n        sortPtsV = sort(full(nextToPtsV));\n        %fill image\n        for j = 1 : length(sortPtsV)/2\n            indV = sortPtsV(2*j-1) : sortPtsV(2*j) - 1;\n            maskM(i * ones(1,length(indV)),indV) = 1;\n        end\n    end\nend\n\n%lastly, correct an oversight in writing the code: rows need to be flipped:\nmaskM = flipud(maskM);  %fast operation.\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/ScanConversion/fastPolyFill.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5536643023826261}}
{"text": "% [INPUT]\n% va = A vector of floats [0,Inf) of length n representing the market values of assets.\n% vap = Input argument representing the distributional parameters of assets whose type depends on the chosen option pricing model:\n%   - for Black-Scholes-Merton, a float [0,Inf) representing the annualized volatility of assets;\n%   - for Gram-Charlier, a row vector of floats (-Inf,Inf) of length 3 whose values represent respectively the annualized volatility, skewness and excess kurtosis of assets.\n% cds = A vector of floats [0,Inf) of length n representing the credit default swap spreads.\n% db = A float or a vector of floats [0,Inf) of length n representing the default barrier.\n% r = A float or a vector of floats (-Inf,Inf) of length n representing the annualized risk-free interest rate.\n% t = A float or a vector of floats (0,Inf) of length n representing the time to maturity of default barrier.\n%\n% [OUTPUT]\n% el = A column vector of floats [0,Inf) of length n representing the expected losses.\n% cl = A column vector of floats [0,Inf) of length n representing the contingent liabilities.\n% a = A column vector of floats [0,1] of length n representing the contingent alphas.\n\nfunction [el,cl,a] = contingent_claims_analysis(varargin)\n\n    persistent ip;\n\n    if (isempty(ip))\n        ip = inputParser();\n        ip.addRequired('va',@(x)validateattributes(x,{'double'},{'real' 'finite' 'nonnegative' '2d' 'nonempty'}));\n        ip.addRequired('vap',@(x)validateattributes(x,{'double'},{'real' 'finite' 'vector' 'nonempty'}));\n        ip.addRequired('cds',@(x)validateattributes(x,{'double'},{'real' 'nonnegative' 'vector' 'nonempty'}));\n        ip.addRequired('db',@(x)validateattributes(x,{'double'},{'real' 'finite' 'nonnegative' 'vector' 'nonempty'}));\n        ip.addRequired('r',@(x)validateattributes(x,{'double'},{'real' 'finite' 'vector' 'nonempty'}));\n        ip.addRequired('t',@(x)validateattributes(x,{'double'},{'real' 'finite' '>' 0 'vector' 'nonempty'}));\n    end\n\n    ip.parse(varargin{:});\n\n    ipr = ip.Results;\n    [va,vap,cds,db,r,t] = validate_input(ipr.va,ipr.vap,ipr.cds,ipr.db,ipr.r,ipr.t);\n\n    nargoutchk(3,3);\n\n    [el,cl,a] = contingent_claims_analysis_internal(va,vap,cds,db,r,t);\n\nend\n\nfunction [el,cl,a] = contingent_claims_analysis_internal(va,vap,cds,db,r,t)\n\n    s = vap(1);\n    st = s * sqrt(t);\n\n    dbd = db .* exp(-r .* t);\n\n    d1 = (log(va ./ db) + ((r + (0.5 * s^2)) .* t)) ./ st;\n    d2 = d1 - st;\n\n    put_price = (dbd .* normcdf(-d2)) - (va .* normcdf(-d1));\n\n    if (numel(vap) == 3)\n        g = vap(2);\n        k = vap(3);\n\n        t1 = (g / 6) .* ((2 * s) - d1);\n        t2 = (k / 24) .* (1 - d1.^2 + (3 .* d1 .* s) - (3 * s^2));\n\n        put_price = put_price - (va .* normcdf(d1) .* s .* (t1 - t2));\n    end\n\n    put_price = max(0,put_price);\n\n    rd = dbd - put_price;\n\n    cds_put_price = dbd .* (1 - exp(-cds .* max(0.5,((db ./ rd) - 1)) .* t));\n    cds_put_price = min(cds_put_price,put_price);  \n\n    a = max(0,min(1 - (cds_put_price ./ put_price),1));\n    a(~isreal(a)) = 0;\n\n    el = put_price;\n    cl = el .* a;\n\nend\n\nfunction [va,vap,cds,db,r,t] = validate_input(va,vap,cds,db,r,t)\n\n    va = va(:);\n    va_len = numel(va);\n\n    if (va_len < 5)\n        error('The value of ''va'' is invalid. Expected input to be a vector containing at least 5 elements.');\n    end\n\n    vap_len = numel(vap);\n\n    if ((vap_len ~= 1) && (vap_len ~= 3))\n        error('The value of ''vap'' is invalid. Expected input to be a vector containing either 1 or 3 elements.');\n    end\n\n    if (vap(1) < 0)\n        error('The value of ''vap'' is invalid. Expected input first element to be greater than or equal to 0.');\n    end\n\n    cds = cds(:);\n\n    if (numel(va) ~= va_len)\n        error(['The value of ''cds'' is invalid. Expected input to be a vector of length ' num2str(va_len) ' elements.']);\n    end\n\n    if (all(cds >= 1))\n        cds = cds ./ 10000;\n    end\n\n    data = {db(:) r(:) t(:)};\n\n    l = unique(cellfun(@numel,data));\n    l_scalar = (l == 1);\n\n    if (any(l_scalar))\n        if (any(l(~l_scalar) ~= va_len))\n            error(['The number of elements of ''db'', ''r'' and ''t'' must be either 1 or equal to ' num2str(va_len) '.']);\n        end\n    else\n        if (any(l ~= va_len))\n            error(['The number of elements of ''db'', ''r'' and ''t'' must be either 1 or equal to ' num2str(va_len) '.']);\n        end\n    end\n\n    for i = 1:numel(data)\n        data_i = data{i};\n\n        if (numel(data_i) == 1)\n            data{i} = repmat(data_i,va_len,1);\n        end\n    end\n\n    [db,r,t] = deal(data{:});\n\nend\n", "meta": {"author": "TommasoBelluzzo", "repo": "SystemicRisk", "sha": "f5e9b4823eabab2130974e535d13762c0cb3e4bf", "save_path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk", "path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk/SystemicRisk-f5e9b4823eabab2130974e535d13762c0cb3e4bf/ScriptsModels/contingent_claims_analysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.5536642981413779}}
{"text": "function Ximg = preimage_rbf(Xtr,sig2,U,B,type,npcs,maxIts)\n%\n% function Ximg = preimage_rbf(Xtr,sig2,U,B,type,npcs,maxIts)\n%   Reconstruction or denoising after kernel PCA with RBF kernels, i.e. to find the\n%   approximate preimage (in the input space) of the corresponding feature space expansions\n% \n% Inputs \n%   Xtr     : N by d matrix of the training data used to find the prinicipal components.\n%   sig2    : parameter for the RBF kernel used, k(x,z)=exp(-norm(x-z)^2/sig2).\n%   U       : the eigenvectors computed from the kernel PCA using RBF kernel with parameter sig2.\n%   B       : for reconstruction, B is the compressed data,\n%               i.e. the projections of the data on to the first n PCs;\n%             for denoising, B is the Nt by d matrix of original noisy data;\n%             if not specified, Xtr is denoised instead.\n%   type    : 'reconstruct' or 'denoise'\n%   npcs    : number of PCs used for approximation\n%   maxIts  : maximum iterations allowed to update the preimage, 1000 by default.\n%\n% Outputs\n%   Ximg    : the reconstructed or denoised data in the input space\n% \n% Usage e.g. \n%   >> [lam,U] = kpca(Xtr,'RBF_kernel',sig2);\n%   >> [lam, perm] = sort(-lam); lam = -lam; U = U(:,perm); \n%   >> projections = kernel_matrix(Xtr,'RBF_kernel',sig2,Xtest)'*U;\n%   >> Xr = preimage_rbf(Xtr,sig2,U,projections(:,1:npcs),'r'); % Reconstruction\n%   >> Xd = preimage_rbf(Xtr,sig2,U(:,1:npcs),Xnoisy,'d');      % Denoising\n%   >> Xdtr = preimage_rbf(Xtr,sig2,U(:,1:npcs));  % Denoising on the training data\n%\n% see also:\n%    kpca, denoise_kpca, RBF_kernel\n%\n% Reference\n%   Mika S., Schoelkopf B., Smola A., Muller K.-R., Scholz M., Ratsch G. (1999), ``Kernel\n%   PCA and de-noising in feature spaces'', Advances in Neural Information Processing\n%   Systems 11, 536-542, MIT Press. \n%\n\n% Copyright (c) 2011,  KULeuven-ESAT-SCD, License & help @ http://www.esat.kuleuven.be/sista/lssvmlab\n\nMAXDX=1e-6; % Convergence criterion\n[~, dim]=size(Xtr);\nmX=mean(Xtr); sX=std(Xtr);\n\nif nargin<4, B = Xtr; end\n[Nt, dimB] = size(B);\n\nif nargin<5\n    if dimB==dim, type='denoise'; else type='reconstruct'; end\nelse\n    if type(1)~='d'&type(1)~='r'| (type(1)=='d'&dimB~=dim),\n        warning('Invalid type specified, default value is used!')\n        if dimB==dim, type='denoise'; else type='reconstruct'; end \n    end\nend\n\nif nargin<6\n    if type(1)=='r'; npcs=dimB; else npcs=size(U,2); end\nelse\n    if npcs>size(U,2) | (type(1)=='r' & npcs~=dimB),\n        warning('Invalid number of PCs, default value is used!'),\n        if type(1)=='r'; npcs=dimB; else npcs=size(U,2); end\n    end\nend\n\nif nargin<7, maxIts=1000; end\n\nU=U(:,1:npcs); \n\nfor n=1:Nt\n    cont=1; t=0; ts=0; \n    if type(1)=='r'\n        % reconstuction\n        rs = U*B(n,:)'; \n        x = zeros(1, dim); % set the initial value of approximate preimage for reconstruction\n        k = RBF_kernel(x,Xtr,sig2);         \n    else\n        % denoise\n        x = B(n,:); % initial value of the approximate preimage for denoising is the noisy data\n        k = RBF_kernel(x,Xtr,sig2); \n        rs = U*(k'*U)';\n    end                             \n\n    % iteratively update the approximate preimage x\n    %\n    while cont, \n\n        d=rs'*k; % the reconstruction error is (const-2d)\n\n        if d==0; \n            % choose a different starting value  \n%            [k,id]=min(k); x_new = Xtr(id,:);\n            randn('state',cputime+ts); x_new=(randn(1,dim)+mX).*sX;  \n            fprintf('%5d> Starting value changed!(d=0) \\n', ts);  \n        else \n            % update approximate preimage with a linear combination of kpca training data\n            x_new = sum(rs.*k*ones(1,dim).*Xtr)/d;\n        end\n\n        dx = norm(x_new - x); \n        x = x_new;\n\n        t=t+1; ts=ts+1;\n    \n        if dx<MAXDX; \n            cont = 0; \n         % fprintf('%5d> Converged! \\n', ts); \n        else\n            if ts>=maxIts;\n                cont=0;\n                fprintf('%5d> Maximum iteration reached!\\n', ts); \n            elseif t>=500;\n                % choose a different starting value                 \n%                [k,id]=min(k); x = Xtr(id,:); \n                randn('state',cputime+ts); x=(randn(1,dim)+mX).*sX;  \n                t=0;\n            end\n        end\n        k = RBF_kernel(x,Xtr,sig2); \n        \n    end % while\n    Ximg(n,:)=x_new;\nend % for\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/preimage_rbf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5536322090837021}}
{"text": "function A2 = project_to_simplex(A)\n%PROJECT_TO_SIMPLEX Summary of this function goes here\n%   Detailed explanation goes here\n[N,M] = size(A);\n[A1,IX] = sort(A',1,'descend');\nJ = ones(N,1)*(1:M); J = J';\nA1cum = cumsum(A1,1)-1*ones(M,N);\nA1minus = (A1 - (A1cum ./ J)) > 0;\n\nrho = max(double(A1minus).*J,[],1);\ntheta = A1cum(sub2ind([M N],rho,(1:N)))./rho;\n\nA1 = A1 - ones(M,1)*theta;\nA1(A1<0) = 0;\n\n% reorder\nA2 = zeros(N,M);\nfor i = 1:M\n    A2(:,i) = A1(IX==i);\nend\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/common/project_to_simplex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.553632207714934}}
{"text": "function [mGal] = nmps22mGal(nmps2)\n% Convert acceleration from nanometers per square-second to milligalileos\n% Chad A. Greene 2012\nmGal = nmps2*1e-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/35258-unit-converters/unit_converters/nmps22mGal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5536322063461653}}
{"text": "function G =  getGroupOverlapColor27(row, col)\n\n\n    N = row*col;\n\n    g = sparse(zeros(N,1));\n    g = diag(g);\n \n \n    \n    %% build overlapping group\n    \n    % top let corner group\n     \n    g(1, 1 ) = 1;\n    g(1, 2 ) = 1;\n    g(1, 1+row ) = 1;\n    g(1, 2+row ) = 1;\n    \n     % bottom let corner group \n  \n    g(row, row-1 ) = 1;\n    g(row, row ) = 1;\n    g(row, row-1+row ) = 1;\n    g(row, row+row ) = 1;\n    \n    % top right corner group\n   \n    g((col-1)*row+1, (col-1)*row+1 ) = 1;\n    g((col-1)*row+1, (col-2)*row+1 ) = 1;\n    g((col-1)*row+1, (col-1)*row+2 ) = 1;\n    g((col-1)*row+1, (col-2)*row+2 ) = 1;\n    \n    % bottom right corner group\n    \n    g((col-1)*row+row , (col-1)*row+row-1 ) = 1;\n    g((col-1)*row+row , (col-2)*row+row-1 ) = 1;\n    g((col-1)*row+row , (col-1)*row+row ) = 1;\n    g((col-1)*row+row , (col-2)*row+row ) = 1;\n            \n            \n    \n    \n    % boundary group\n    \n    for i=2:col-1\n        % top row rgoup\n \n        j = 1;    \n  \n        g( (i-1)*row+j  , (i-2)*row+j   ) = 1;\n        g( (i-1)*row+j  , (i-2)*row+j+1 ) = 1;\n         \n        g( (i-1)*row+j  , (i-1)*row+j   ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j+1 ) = 1;             \n        \n        g( (i-1)*row+j  , i*row+j   ) = 1;\n        g( (i-1)*row+j  , i*row+j+1 ) = 1;\n\n        % bottom row group\n    \n        j = row;\n        \n        g( (i-1)*row+j  , (i-2)*row+j-1 ) = 1;\n        g( (i-1)*row+j  , (i-2)*row+j   ) = 1;\n      \n        g( (i-1)*row+j  , (i-1)*row+j-1 ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j   ) = 1;\n                \n        g( (i-1)*row+j  , i*row+j-1 ) = 1;\n        g( (i-1)*row+j  , i*row+j   ) = 1;\n         \n        \n        \n    end\n    \n    for j=2:row-1\n          % left column rgoup\n    \n            \n        i=1;\n        \n        g( (i-1)*row+j  , (i-1)*row+j-1 ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j   ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j+1 ) = 1;             \n        g( (i-1)*row+j  , i*row+j-1 ) = 1;\n        g( (i-1)*row+j  , i*row+j   ) = 1;\n        g( (i-1)*row+j  , i*row+j+1 ) = 1;\n\n        % right  column group\n \n\n        i=col;\n        \n        \n        g( (i-1)*row+j  , (i-2)*row+j-1 ) = 1;\n        g( (i-1)*row+j  , (i-2)*row+j   ) = 1;\n        g( (i-1)*row+j  , (i-2)*row+j+1 ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j-1 ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j   ) = 1;\n        g( (i-1)*row+j  , (i-1)*row+j+1 ) = 1;             \n        \n    end\n    \n    for i=2:col-1    \n        for j=2:row-1  \n            \n            \n            g( (i-1)*row+j  , (i-2)*row+j-1 ) = 1;\n            g( (i-1)*row+j  , (i-2)*row+j   ) = 1;\n            g( (i-1)*row+j  , (i-2)*row+j+1 ) = 1;\n            g( (i-1)*row+j  , (i-1)*row+j-1 ) = 1;\n            g( (i-1)*row+j  , (i-1)*row+j   ) = 1;\n            g( (i-1)*row+j  , (i-1)*row+j+1 ) = 1;             \n            g( (i-1)*row+j  , i*row+j-1 ) = 1;\n            g( (i-1)*row+j  , i*row+j   ) = 1;\n            g( (i-1)*row+j  , i*row+j+1 ) = 1;      \n\n        end\n    end\n   \n   \n     G =[g; g; g];\n    \n\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/GOSUS/getGroupOverlapColor27.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5536322039573923}}
{"text": "function [fp, fm] = partition(f)\n% PARTITION   Partition a DISKFUN into its even/periodic odd/anti-periodic\n% parts.\n%\n% [FP, FM] = partition(F) partitions F into two diskfuns FP & FM with the\n% following properties:\n% \n%   FP has a CDR decomposition such that C is even and R is pi periodic.\n%   FM has a CDR decomposition such that C is odd and R is pi\n%   anti-periodic.\n%\n% See also DISKFUN/COMBINE.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n\nif ( ~isa(f,'diskfun') )\n    error('DISKFUN:partition:unknown',['Undefined function ''partition'' for ' ...\n        'input argument of type %s.'], class(f));\nend\n\nif ( isempty(f) )\n    fp = diskfun();\n    fm = diskfun();\n    return\nend\n\n% Do the even-pi-periodic case first.\nid = f.idxPlus;\n\nif isempty(id)\n    fp = diskfun();\nelse\n    fp = f;\n    fp.cols = fp.cols(:, id);\n    fp.rows = fp.rows(:, id);\n    fp.pivotValues = fp.pivotValues(id, :);\n    fp.pivotLocations = fp.pivotLocations(id, :); \n    fp.idxPlus = 1:length(id);\n    fp.idxMinus = [];\nend\n\n% Now the odd case.\nid = f.idxMinus;\n\nif ( isempty(id) )\n    fm = diskfun();\nelse\n    fm = f;\n    fm.cols = fm.cols(:, id);\n    fm.rows = fm.rows(:, id);\n    fm.pivotValues = fm.pivotValues(id);\n    fm.pivotLocations = fm.pivotLocations(id, :);\n    fm.idxMinus = 1:length(id);\n    fm.idxPlus = [];\n    fm.nonZeroPoles = 0;\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/@diskfun/partition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.55361797318517}}
{"text": "function p = square_uniform ( n )\n\n%*****************************************************************************80\n%\n%% SQUARE_UNIFORM returns sample points from the unit square.\n%\n%  Discussion:\n%\n%    This routine returns N points sampled uniformly at random\n%    from within the unit square.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 May 2006\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the number of points to generate.\n%\n%    Output, real P(N,2), the sample points.\n%\n  p = rand ( 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/cvt_metric/square_uniform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.5535453579131612}}
{"text": "% SP_HCURL_ERROR: Evaluate the error in H(curl) norm.\n%\n%   [errhcurl, errl2, errcurl] = sp_hcurl_error (space, msh, u, uex, curluex);\n%\n% INPUT:\n%\n%    space:   object defining the space of discrete functions (see sp_vector)\n%    msh:     object defining the domain partition and the quadrature rule (see msh_cartesian)\n%    u:       vector of dof weights\n%    uex:     function handle to evaluate the exact solution\n%    curluex: function handle to evaluate the curl of the exact solution\n%\n% OUTPUT:\n%\n%     errhcurl: error in H(curl) norm\n%     errl2:    error in L^2 norm\n%     errcurl:  error of the curl in L^2 norm\n%\n% Copyright (C) 2010 Carlo de Falco, Rafael Vazquez\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 Octave; see the file COPYING.  If not, see\n% <http://www.gnu.org/licenses/>.\n\nfunction [errhcurl, errl2, errcurl] = sp_hcurl_error (space, msh, u, uex, curluex)\n\n  if (numel(u) ~= space.ndof)\n    error ('Wrong size of the vector of degrees of freedom')\n  end\n\n  errl2 = 0;\n  errcurl = 0;\n\n  for iel = 1:msh.nel_dir(1)\n    msh_col = msh_evaluate_col (msh, iel);\n    sp_col  = sp_evaluate_col (space, msh_col, 'value', true, 'curl', true);\n\n    [~, err_l2, err_curl] = sp_hcurl_error (sp_col, msh_col, u, uex, curluex);\n\n    errcurl = errcurl + err_curl.^2;\n    errl2 = errl2 + err_l2.^2;\n  end\n\n  errhcurl = sqrt (errl2 + errcurl);\n  errl2 = sqrt (errl2);\n  errcurl = sqrt (errcurl);\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_vector/sp_hcurl_error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5535453530058183}}
{"text": "function b = r8vec_bracket6 ( nd, xd, ni, xi )\n\n%*****************************************************************************80\n%\n%% R8VEC_BRACKET6 brackets data between successive entries of a sorted R8VEC.\n%\n%  Discussion:\n%\n%    We assume XD is sorted.\n%\n%    If XI(I) is contained in the interval [XD(1),XD(N)], then the value of\n%    B(I) indicates that XI(I) is contained in [ XD(B(I)), XD(B(I)+1) ].\n%\n%    If XI(I) is not contained in the interval [XD(1),XD(N)], then B(I) = -1.\n%\n%    This code implements a version of binary search which is perhaps more\n%    understandable than the usual ones.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 October 2012\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer ND, the number of data values.\n%\n%    Input, real XD(N,1), the sorted data.\n%\n%    Input, integer NI, the number of inquiry values.\n%\n%    Input, real XI(NI,1), the query values.\n%\n%    Output, integer B(NI,1), the bracket information.\n%\n  xd = xd(:);\n  xi = xi(:);\n  b = zeros ( ni, 1 );\n\n  for i = 1 : ni\n\n    if ( xi(i) < xd(1) || xd(nd) < xi(i) )\n\n      b(i) = -1;\n\n    else\n\n      l = 1;\n      r = nd;\n\n      while ( l + 1 < r )\n        m = floor ( ( l + r ) / 2 );\n        if ( xi(i) < xd(m) )\n          r = m;\n        else\n          l = m;\n        end\n      end\n\n      b(i) = l;\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_bracket6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.5535453509161896}}
{"text": "% This is the main FastSLAM loop. This script calls all the required\n% functions in the correct order.\n%\n% You can disable the plotting or change the number of steps the filter\n% runs for to ease the debugging. You should however not change the order\n% or calls of any of the other lines, as it might break the framework.\n%\n% If you are unsure about the input and return values of functions you\n% should read their documentation which tells you the expected dimensions.\n\n% Turn off pagination:\nmore off;\n\nclear all;\nclose all;\n\n% Make tools available\naddpath('tools');\n\n% Read world data, i.e. landmarks. The true landmark positions are not given to the robot\nlandmarks = read_world('../data/world.dat');\n% Read sensor readings, i.e. odometry and range-bearing sensor\ndata = read_data('../data/sensor_data.dat');\n\n% Get the number of landmarks in the map\nN = size(landmarks,2);\n\nnoise = [0.005, 0.01, 0.005]';\n\n% how many particles\nnumParticles = 100;\n\n% initialize the particles array\nparticles = struct;\nfor i = 1:numParticles\n  particles(i).weight = 1. / numParticles;\n  particles(i).pose = zeros(3,1);\n  particles(i).history = cell();\n  for l = 1:N % initialize the landmarks aka the map\n    particles(i).landmarks(l).observed = false;\n    particles(i).landmarks(l).mu = zeros(2,1);    % 2D position of the landmark\n    particles(i).landmarks(l).sigma = zeros(2,2); % covariance of the landmark\n  end\nend\n\n% toogle the visualization type\n%showGui = true;  % show a window while the algorithm runs\nshowGui = false; % plot to files instead\n\n% Perform filter update for each odometry-observation pair read from the\n% data file.\nfor t = 1:size(data.timestep, 2)\n%for t = 1:50\n    printf('timestep = %d\\n', t);\n\n    % Perform the prediction step of the particle filter\n    particles = prediction_step(particles, data.timestep(t).odometry, noise);\n\n    % Perform the correction step of the particle filter\n    particles = correction_step(particles, data.timestep(t).sensor);\n\n    % Generate visualization plots of the current state of the filter\n    plot_state(particles, landmarks, t, data.timestep(t).sensor, showGui);\n\n    % Resample the particle set\n    particles = resample(particles);\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/fastslam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5535453431911327}}
{"text": "function value = grad(psi,co2)\n\n\nN = psi.bandwidth;\nA = psi.A(:);\n\nk = 1:0.5:(N+1)/2;\nk(2:2:end) = 0;\nl = (N+1)/2:0.5:N;\nl(end-1:-2:1)=0;\nM = triu(hankel(k,l)-toeplitz([0,k(1:end-1)]));\n\nAhat = (-4) * (M*A(2:end));\n\nDpsi = SO3Kernel(Ahat);\n\n% TODO: Interpolation error: Try\n% psi = SO3DeLaValleePoussinKernel(90);\n% psi2=SO3Kernel(psi.A);\n% omega = 35*degree:0.01:pi;\n% plot(omega/degree,psi.grad(cos(omega/2)) )\n% hold on\n% plot(omega/degree, psi2.grad(cos(omega/2)) )\n% hold off\n\n\nif nargin == 2\n  value = Dpsi.eval(co2).*co2.*sqrt(1-co2.^2);\nelse\n  value = SO3KernelHandle(@(co2) Dpsi.eval(co2).*co2.*sqrt(1-co2.^2));\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/SO3KernelFunctions/@SO3Kernel/grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.5535183817398539}}
{"text": "% Driver script for solving the 3D advection equations\nGlobals3D;\n\n% Order of polymomials used for approximation \nN = 8;\n\n% Generate simple mesh\nfilename = 'cubeK6.neu'\n[Nv, VX, VY, VZ, K, EToV] = MeshReaderGambit3D(filename);\n\n% Initialize solver and construct grid and metric\nStartUp3D;\n\n% set initial conditions\nu = exp(-1*(x.^2 + y.^2 + z.^2));\n\n% Solve Problem\nFinalTime = 0.8;\n[u] = Advec3D(u,FinalTime);\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/AdvecDriver3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5535183640949284}}
{"text": "function [dLdp,iCpY,L] = mci_approach_deriv (P,M,U,Y)\n% Gradient of log-likelihood for approach model\n% FORMAT [dLdp,iCpY,L] = mci_approach_deriv (P,M,U,Y)\n%\n% dLdp      gradient of log joint\n% iCpY      curvature (Fisher Information)\n% L         log joint\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: mci_approach_deriv.m 6548 2015-09-11 12:39:47Z will $\n\nG = mci_approach_gen (P,M,U);\nif isstruct(Y)\n    e = Y.y-G;\nelse\n    e = Y-G;\nend\n\nV=exp(P(1));\ntau=exp(P(2));\nt=U.X;\n\ny=-60+V*(1-exp(-t/tau));\n\ndydp = [V*(1-exp(-t/tau)),-V*exp(-t/tau).*(t/tau)];\ndLdp = dydp'*M.iCe*e;\niCpY = dydp'*M.iCe*dydp;\n\nif nargout > 2\n    L = mci_approach_like (P,M,U,Y);\nend\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/mci/models/approach/mci_approach_deriv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5535183632373378}}
{"text": "function [parent, post] = cs_etree (A, mode)                                %#ok\n%CS_ETREE elimination tree of A or A'*A.\n%   parent = cs_etree (A) returns the elimination tree of A.\n%   parent = cs_etree (A,'col') returns the elimination tree of A'*A.\n%   parent = cs_etree (A,'sym') is the same as cs_etree(A).\n%   For the symmetric case (cs_etree(A)), only triu(A) is used.\n%\n%   [parent,post] = cs_etree(...) also returns a postorder of the tree.\n%\n%   Example:\n%       Prob = UFget ('HB/bcsstk01') ; A = Prob.A ;\n%       parent = cs_etree (A) ; treeplot (parent) ;\n%\n%   See also ETREE, TREEPLOT.\n\n%   Copyright 2006-2007, Timothy A. Davis.\n%   http://www.cise.ufl.edu/research/sparse\n\nerror ('cs_etree mexFunction not found') ;\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/CSparse/cs_etree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5534267034216849}}
{"text": "classdef RodAlign < dagnn.Layer\n\n    properties\n        subdivisions = [6 6]\n        transformation = 1/8\n    end\n  \n    methods\n        function outputs = forward(obj, inputs, params) \n          % calculation on cpu is faster for matlab\n          inputs{1} = gather(inputs{1});\n          inputs{2} = gather(inputs{2});\n          \n          feat_h = size(inputs{1},1);\n          feat_w = size(inputs{1},2);\n          num_roi = size(inputs{2},2);\n          roi_h_start = max(round(inputs{2}(2,:) * obj.transformation),1);\n          roi_w_start = max(round(inputs{2}(3,:) * obj.transformation),1);\n          roi_h_end = min(round(inputs{2}(4,:) * obj.transformation),feat_h);\n          roi_w_end = min(round(inputs{2}(5,:) * obj.transformation),feat_w);\n          \n          scale_h = feat_h / obj.subdivisions(1);\n          scale_w = feat_w / obj.subdivisions(2);\n          bin_h = ((1:obj.subdivisions(1))-0.5) * scale_h;\n          bin_W = ((1:obj.subdivisions(2))-0.5) * scale_w;\n          \n          floor_bin_h = max(floor(bin_h),1);\n          ceil_bin_h = floor_bin_h+1;\n          floor_bin_w = max(floor(bin_W),1);\n          ceil_bin_w = floor_bin_w+1;\n          c11 = min(ceil_bin_h-bin_h,1)'*min(ceil_bin_w-bin_W,1);\n          c12 = min(ceil_bin_h-bin_h,1)'*max(bin_W-floor_bin_w,0);\n          c21 = max((bin_h-floor_bin_h),0)'*min(ceil_bin_w-bin_W,1);\n          c22 = max(bin_h-floor_bin_h,0)'*max(bin_W-floor_bin_w,0);\n          feats = repmat(inputs{1},1,1,1,num_roi);\n          for i = 1:num_roi\n              feats(roi_h_start(i):roi_h_end(i),roi_w_start(i):roi_w_end(i),:,i) = 0;\n          end\n          outputs = c11.*feats(floor_bin_h,floor_bin_w,:,:) ...\n                  + c12.*feats(floor_bin_h,ceil_bin_w,:,:) ... \n                  + c21.*feats(ceil_bin_h,floor_bin_w,:,:) ...\n                  + c22.*feats(ceil_bin_h,ceil_bin_w,:,:);\n          outputs = {gpuArray(outputs)};\n\n        end\n\n        function [derInputs, derParams] = backward(obj, inputs, param, derOutputs)\n          %When assigning into a GPUArray, the subscripts must contain unique values.\n          inputs{1} = gather(inputs{1});\n          inputs{2} = gather(inputs{2});\n          derOutputs{1} = gather(derOutputs{1});\n          \n          feat_h = size(inputs{1},1);\n          feat_w = size(inputs{1},2);\n          ch = size(inputs{1},3);\n          num_roi = size(inputs{2},2);\n          roi_h_start = max(round(inputs{2}(2,:) * obj.transformation),1);\n          roi_w_start = max(round(inputs{2}(3,:) * obj.transformation),1);\n          roi_h_end = min(round(inputs{2}(4,:) * obj.transformation),feat_h);\n          roi_w_end = min(round(inputs{2}(5,:) * obj.transformation),feat_w);\n          \n          scale_h = feat_h / obj.subdivisions(1);\n          scale_w = feat_w / obj.subdivisions(2);\n          bin_h = ((1:obj.subdivisions(1))-0.5) * scale_h;\n          bin_W = ((1:obj.subdivisions(2))-0.5) * scale_w;\n          \n          floor_bin_h = max(floor(bin_h),1);\n          ceil_bin_h = floor_bin_h+1;\n          floor_bin_w = max(floor(bin_W),1);\n          ceil_bin_w = floor_bin_w+1;\n          c11 = min(ceil_bin_h-bin_h,1)'*min(ceil_bin_w-bin_W,1);\n          c12 = min(ceil_bin_h-bin_h,1)'*max(bin_W-floor_bin_w,0);\n          c21 = max((bin_h-floor_bin_h),0)'*min(ceil_bin_w-bin_W,1);\n          c22 = max(bin_h-floor_bin_h,0)'*max(bin_W-floor_bin_w,0);\n          \n          derbilinear = zeros([feat_h,feat_w,ch,num_roi],'single');\n          for i = 1:num_roi\n              derbilinear(floor_bin_h,floor_bin_w,:,i) = derbilinear(floor_bin_h,floor_bin_w,:,i) + c11 .* derOutputs{1}(:,:,:,i);\n              derbilinear(floor_bin_h,ceil_bin_w,:,i) = derbilinear(floor_bin_h,ceil_bin_w,:,i) + c12 .* derOutputs{1}(:,:,:,i);\n              derbilinear(ceil_bin_h,floor_bin_w,:,i) = derbilinear(ceil_bin_h,floor_bin_w,:,i) + c21 .* derOutputs{1}(:,:,:,i);\n              derbilinear(ceil_bin_h,ceil_bin_w,:,i) = derbilinear(ceil_bin_h,ceil_bin_w,:,i) + c22 .* derOutputs{1}(:,:,:,i);\n              derbilinear(roi_h_start(i):roi_h_end(i),roi_w_start(i):roi_w_end(i),:,i) = 0;\n          end\n          derInputs{1} = gpuArray(sum(derbilinear,4));\n              \n          derInputs{2} = [];\n          derParams = {} ;\n        end\n\n        function obj = RodAlign(varargin)\n          obj.load(varargin);\n        end\n    end\nend\n", "meta": {"author": "HuiZeng", "repo": "Grid-Anchor-based-Image-Cropping", "sha": "d3262a1bc840cd998cdff4bee0c712b4ad0787b7", "save_path": "github-repos/MATLAB/HuiZeng-Grid-Anchor-based-Image-Cropping", "path": "github-repos/MATLAB/HuiZeng-Grid-Anchor-based-Image-Cropping/Grid-Anchor-based-Image-Cropping-d3262a1bc840cd998cdff4bee0c712b4ad0787b7/tools/+dagnn/RodAlign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5533267572904351}}
{"text": "function [thrs, fars, frrs] = slroc(scores, signs, thres, op)\n%SLROC Computes the ROC\n%\n% $ Syntax $\n%   - [thrs, fars, frrs] = slroc(scores, signs, thres, op) \n%\n% $ Arguments $\n%   - scores:           the scores representing the signal intensities\n%   - signs:            the signs representing the groundtruth (0 or 1)\n%   - thres:            the descriptor indicating how to sample the \n%                       thresholds at which the rate is computed\n%   - op:               the option stating the attributes of the scores.\n%   - thrs:             the sampled threshold values\n%   - fars:             the false accept rates at the sampled thresholds\n%   - frrs:             the false reject rates at the sampled thresholds\n% \n% $ Description $\n%   - [thrs, fars, frrs] = slroc(scores, signs, thres, op) Computes the \n%     ROC of a receiver from the scores and groudtruth signs. The argument \n%     thres specifies the sampled thresholds at which the false accept \n%     rate and false reject rate is evaluated. If thres is an integer, \n%     say n, then n equal-interval integers from lowest to highest scores \n%     are taken as samples. The thres can also be a vector containing the \n%     sampled thresholds, which should be arranged in ascending order.\n%     op states the attributes of the scores, which\n%     takes either of the two values: 'high' or 'low'. If op is 'high', a \n%     higher score indicates a better match; if op is 'low', a lower score\n%     indicates a better match. The cumulative score will be computed\n%     up to the number of all classes.\n%     For output, if n thresholds are sampled, then thrs, fars, and frrs\n%     for all n x 1 vectors, containing the sampled threshold values,\n%     and the corresponding false accept rates, and false reject rates.\n%\n% $ History $\n%   - Created by Dahua Lin on Jun 9th, 2005\n%   - Modified by Dahua Lin on May 1st, 2006\n%     - Base on the sltoolbox v4\n%   - Modified by Dahua Lin on Aug 8th, 2006\n%     - Base on slhistroc\n%   \n\n%% parse and verify the input arguments\nif nargin < 4\n    raise_lackinput('slroc', 4);\nend\nif ~isequal(size(scores), size(signs))\n    error('sltoolbox:sizmismatch', ...\n        'The sizes of scores and signs are not match');\nend\n\n% the following two statements are disabled in the 2006-08-08 modification\n% since scores(signs) will automatic serialize the values\n% there is no need to write this statement, just a waste of time and mem\n% scores = scores(:); \n% signs = logical(signs(:));\n\nif numel(thres) == 1\n    n = thres;\n    highscore = max(max(scores));\n    lowscore = min(min(scores));\n    thrs = linspace(lowscore, highscore, n)';\nelse\n    thrs = thres(:);\nend\n\n    \n\n%% compute\nscores_a = scores(signs);\nscores_r = scores(~signs);\n\nhist_a = histc(scores_a, thrs);\nhist_r = histc(scores_r, thrs);\n\n[thrs, fars, frrs] = slhistroc(hist_a, hist_r, thrs, op);\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/perfeval/slroc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5532116268361958}}
{"text": "function d = month_to_ides_roman ( m )\n\n%*****************************************************************************80\n%\n%% MONTH_TO_IDES_ROMAN returns the day of the ides of a Roman month.\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%  Parameters:\n%\n%    Input, integer M, the month index.\n%\n%    Output, integer D, the day of the ides of the month.\n%\n  ides = [ 13, 13, 15, 13, 15, 13, 15, 13, 13, 15, 13, 13 ];\n\n  if ( m < 1 || 12 < m )\n    d = -1;\n  else\n    d = ides(m);\n  end\n\n  return\nend\n", "meta": {"author": "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/month_to_ides_roman.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.5532116258203347}}
{"text": "function [L,S] = gosus(M,opts)\n  regularizer = 0.1;\n  param.superpixel.slicParam = [10, regularizer; 20, regularizer; 40,regularizer; 80, regularizer;];\n  %  param.superpixel.slicParam = [5,regularizer;  10, regularizer; 20, regularizer;  40,regularizer ; ];\n  param.maxIter = 200;\n  param.tol = 1e-4;\n  param.lambda = 0.33;    %   bestAccu = 0.9762, lambda = 0.33; threshold = 8e-6;\n  param.rank = 2; % subspace dimension\n  param.eta = 1e-3;   % stepsize for subspace updating\n  %param.sampleSize = 20; % number of sample frames to learn the background\n  %param.trainSize = 24; % sample from the fist 240 frames to learn the background\n  %param.startIndex = 1;   %  which frame to start\n  %param.randomStart = true;  \n  param.admm.I = speye(size(M,1)*3);\n\n  %U = orth(randn(size(M,1)*3, param.rank));\n  [U, ~] = svds([M(:,1:25);M(:,1:25);M(:,1:25)], param.rank);\n\n  for i = 1:size(M,2)\n    disp(i);\n    I = M(:,i);\n    im = im2uint8(reshape(I,[opts.rows opts.cols]));\n    im = repmat(im,[1 1 3]);\n\n    param.admm.G = getGroupSuperColor27(im, param);\n    param.admm.Z = sparse(size(M,1)*3, size(param.admm.G, 2), 0);\n    param.admm.Y = param.admm.Z;\n\n    v = double(im(:))/255.0;\n\n    [x, w] = solveWXADMM(U, v, param);\n\n    pL = U*w; % low-rank\n    pS = pL-v; % sparse\n    %E = v;\n\n    imgL = reshape(pL, size(im));\n    imgS = reshape(pS, size(im));\n\n    vL = imgL(:,:,1);\n    vS = imgS(:,:,1);\n\n    vL = vL(:);\n    vS = vS(:);\n\n    L(:,i) = vL;\n    S(:,i) = vS;\n\n    %L = U*w; % low-rank\n    %E = v;\n\n    %fg = L-v;\n    %fg(abs(x)<=8e-10) = 0;\n    %fg(abs(x)>8e-10) = 1;\n\n    %subplot(1,3,1), imshow(im,[]);\n    %subplot(1,3,2), imshow(reshape(L, size(im)),[]);\n    %subplot(1,3,3), imshow(reshape(fg, size(im)),[]);\n\n    residual = param.lambda*(U*w + x - v);\n    U = updateSubspace(U, residual, w, param);\n\n    %pause(.01);\n  end\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/st/GOSUS/gosus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6825737214979746, "lm_q1q2_score": 0.5532116173852484}}
{"text": "function i4vec_order_type_test ( )\n\n%*****************************************************************************80\n%\n%% I4VEC_ORDER_TYPE_TEST tests I4VEC_ORDER_TYPE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 4;\n  test_num = 6;\n%\n%  Each ROW of the definition is a COLUMN of the matrix.\n%\n  x_test = [ ...\n    1, 3, 2, 4; ...\n    2, 2, 2, 2; ...\n    1, 2, 2, 4; ...\n    1, 2, 3, 4; ...\n    4, 4, 3, 1; ...\n    9, 7, 3, 0 ]';\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'I4VEC_ORDER_TYPE_TEST\\n' );\n  fprintf ( 1, '  I4VEC_ORDER_TYPE classifies an integer vector as\\n' );\n  fprintf ( 1, '  -1: no order\\n' );\n  fprintf ( 1, '   0: all equal;\\n' );\n  fprintf ( 1, '   1: ascending;\\n' );\n  fprintf ( 1, '   2: strictly ascending;\\n' );\n  fprintf ( 1, '   3: descending;\\n' );\n  fprintf ( 1, '   4: strictly descending.\\n' );\n\n  for test = 1 : test_num\n\n    x(1:n) = x_test(1:n,test);\n\n    order = i4vec_order_type ( n, x );\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  The following vector has order type %d\\n', order );\n    fprintf ( 1, '\\n' );\n    for j = 1 : n\n      fprintf ( 1, '  %6d  %6d\\n', j, x(j) );\n    end\n\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/i4lib/i4vec_order_type_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.553211615353527}}
{"text": "function [ n_data, a, x, fx ] = jacobi_dn_values ( n_data )\n\n%*****************************************************************************80\n%\n%% JACOBI_DN_VALUES returns some values of the Jacobi elliptic function DN(A,X).\n%\n%  Discussion:\n%\n%    In Mathematica, the function can be evaluated by:\n%\n%      JacobiDN[ x, a ]\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 A, the parameter of the function.\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  a_vec = [ ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.0E+00, ...\n     0.5E+00, ...\n     0.5E+00, ...\n     0.5E+00, ...\n     0.5E+00, ...\n     0.5E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00, ...\n     1.0E+00 ];\n\n  fx_vec = [ ...\n     0.1000000000000000E+01, ...\n     0.1000000000000000E+01, ...\n     0.1000000000000000E+01, ...\n     0.1000000000000000E+01, ...\n     0.1000000000000000E+01, ...\n     0.9975093485144243E+00, ...\n     0.9901483195224800E+00, ...\n     0.9429724257773857E+00, ...\n     0.8231610016315963E+00, ...\n     0.7108610477840873E+00, ...\n     0.9950207489532265E+00, ...\n     0.9803279976447253E+00, ...\n     0.8868188839700739E+00, ...\n     0.6480542736638854E+00, ...\n     0.2658022288340797E+00, ...\n     0.3661899347368653E-01, ...\n     0.9803279976447253E+00, ...\n     0.8868188839700739E+00, ...\n     0.6480542736638854E+00, ...\n     0.2658022288340797E+00  ];\n\n  x_vec = [ ...\n      0.1E+00, ...\n      0.2E+00, ... \n      0.5E+00, ...\n      1.0E+00, ...\n      2.0E+00, ...\n      0.1E+00, ...\n      0.2E+00, ...\n      0.5E+00, ...\n      1.0E+00, ...\n      2.0E+00, ...\n      0.1E+00, ...\n      0.2E+00, ...\n      0.5E+00, ...\n      1.0E+00, ...\n      2.0E+00, ...\n      4.0E+00, ...\n     -0.2E+00, ...\n     -0.5E+00, ...\n     -1.0E+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    a = 0.0;\n    x = 0.0;\n    fx = 0.0;\n  else\n    a = a_vec(n_data);\n    x = x_vec(n_data);\n    fx = fx_vec(n_data);\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/jacobi_dn_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.5532116101201229}}
{"text": "function [] = plotWavefield(f, c, fs, T, thetaArrivalAngles, phiArrivalAngles, amplitudes)\n\nif isscalar(f)\n    f = f*ones(1,numel(thetaArrivalAngles));\nend\n\nif ~exist('amplitudes','var')\n    amplitudes = ones(1,numel(thetaArrivalAngles));\nend\n\n% Grid-points for calculating the field\n[x, y] = meshgrid(-0.5:0.02:0.5,-0.5:0.02:0.5);\nnPoints = size(x,1);\nxPoints = x(:)';\nyPoints = y(:)';\nnSamples = T*fs;\nt = 0:1/fs:nSamples/fs-1/fs;\n\nsignal_field = 0;\nfor k = 1:numel(thetaArrivalAngles)\n    doa = squeeze(steeringVector(xPoints, yPoints, f(k), c, thetaArrivalAngles(k), phiArrivalAngles(k)));\n    signal = 10^(amplitudes(k)/20)*doa*exp(1j*2*pi*f(k)*t);\n    signal_field = signal_field + signal;  \nend\n\n\nfigure(11);clf\nset(gcf,'color','w')\ncolormap('spring')\ncmap = [1 1 1]*0.5;\n%plot(0.5*cos(0:pi/50:2*pi),0.5*sin(0:pi/50:2*pi),'Color',[1 1 1],'linewidth',1.5)\nhold on\nset(gca,'color',[0 0 0],'xcolor',cmap,'ycolor',cmap,'zcolor',cmap)\nset(gca,'XTickLabel',[],'YTickLabel',[],'ZTickLabel',[])\nset(gca,'XMinorGrid','on','YMinorGrid','on','ZMinorGrid','on','MinorGridColor',[1 1 1],'MinorGridLineStyle','-')\naxis([-0.5 0.5 -0.5 0.5 -0.5 0.5])\nview(110,25)\ntext(0.46,-0.5,-0.45,'x','color',[1 1 1])\ntext(-0.5,0.46,-0.45,'y','color',[1 1 1])\ntext(-0.5,-0.5,0.46,'z','color',[1 1 1])\n\nz = reshape(real(signal_field(:,1))'/25,nPoints,nPoints);\nh = surf(x,y,z,'edgecolor','none','FaceAlpha',0.7');\nh.ZDataSource = 'z';\n\ntitle(['t = ' num2str(sprintf('%0.1f',t(1)*1e3)) ' ms'],'fontweight','normal')\n    \nfor sample = 2:nSamples\n    pause(0.01)\n    \n    z = reshape(real(signal_field(:,sample))'/25,nPoints,nPoints);\n    refreshdata(h, 'caller')\n    \n    title(['t = ' num2str(sprintf('%0.1f',t(sample)*1e3)) ' ms'],'fontweight','normal')\n    \nend", "meta": {"author": "jorgengrythe", "repo": "beamforming", "sha": "0e0406044a102869f63c6006f952094827b81669", "save_path": "github-repos/MATLAB/jorgengrythe-beamforming", "path": "github-repos/MATLAB/jorgengrythe-beamforming/beamforming-0e0406044a102869f63c6006f952094827b81669/plot/plotWavefield.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594355, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5532116080884003}}
{"text": "function [g,a,fc,L,info]=audfilters(fs,Ls,varargin)\n%AUDFILTERS Generates filters equidistantly spaced on auditory frequency scales\n%   Usage:  [g,a,fc,L]=audfilters(fs,Ls);\n%           [g,a,fc,L]=audfilters(fs,Ls,...);\n%\n%   Input parameters:\n%      fs    : Sampling rate (in Hz).\n%      Ls    : Signal length.\n%   Output parameters:\n%      g     : Cell array of filters.\n%      a     : Downsampling rate for each channel.\n%      fc    : Center frequency of each channel.\n%      L     : Next admissible length suitable for the generated filters.\n%\n%   `[g,a,fc,L]=audfilters(fs,Ls)` constructs a set of filters *g* that are\n%   equidistantly spaced on a perceptual frequency scale (see |freqtoaud|) between\n%   0 and the Nyquist frequency. The filter bandwidths are proportional to the \n%   critical bandwidth of the auditory filters |audfiltbw|. The filters are intended \n%   to work with signals with a sampling rate of *fs*. The signal length *Ls* is \n%   mandatory, since we need to avoid too narrow frequency windows.\n%\n%   By default the ERB scale is chosen but other frequency scales are\n%   possible. Currently supported scales are 'erb', 'erb83', 'bark', 'mel'\n%   and 'mel1000', and can be changed by passing the associated string as \n%   an optional parameter. See |freqtoaud| for more information on the\n%   supported frequency scales.\n%\n%   By default, a Hann window shape is chosen as prototype frequency \n%   response for all filters. The prototype frequency response can be \n%   changed by passing any of the window types from |firwin| or |freqwin| \n%   as an optional parameter.\n%\n%   `[g,a,fc,L]=audfilters(fs,Ls,fmin,fmax)` constructs a set of filters \n%   between *fmin* and *fmax*. The filters are equidistantly spaced on the \n%   selected frequency scale. One additional filter will be positioned at \n%   the 0 and Nyquist frequencies each, so as to cover the full range of \n%   positive frequencies. \n%   The values of *fmin* and *fmax* can be instead specified using a \n%   key/value pair as::\n%\n%       [g,a,fc,L]=audfilters(fs,Ls,...,'fmin',fmin,'fmax',fmax)\n%\n%   Default values are *fmin=0* and *fmax=fs/2*. \n%\n%   For more details on the construction of the filters, please see the\n%   given references.\n%\n%   Downsampling factors\n%   --------------------\n%\n%   The integer downsampling rates of the channels must all divide the\n%   signal length, |filterbank| will only work for input signal lengths\n%   being multiples of the least common multiple of the downsampling rates.\n%   See the help of |filterbanklength|. \n%   The fractional downsampling rates restrict the filterbank to a single\n%   length *L=Ls*.\n%\n%   `[g,a]=audfilters(...,'regsampling')` constructs a non-uniform\n%   filterbank with integer subsampling factors.\n%\n%   `[g,a]=audfilters(...,'uniform')` constructs a uniform filterbank\n%   where the integer downsampling rate is the same for all the channels. This\n%   results in most redundant representation which produces nice plots.\n%\n%   `[g,a]=audfilters(...,'fractional')` constructs a filterbank with\n%   fractional downsampling rates *a*. \n%   This results in the least redundant system.\n%\n%   `[g,a]=audfilters(...,'fractionaluniform')` constructs a filterbank with\n%   fractional downsampling rates *a*, which are uniform for all filters\n%   except the \"filling\" low-pass and high-pass filters which can have different\n%   fractional downsampling rates. This is useful when uniform subsampling\n%   and low redundancy at the same time are desirable.\n%\n%   Additional parameters\n%   ---------------------\n%\n%   `audfilters` accepts the following optional parameters:\n%\n%     'spacing',b        Specify the spacing between the filters, measured in\n%                        scale units. Default value is *b=1* for the scales\n%                        'erb', 'erb83' and 'bark'; the default is *b=100* for\n%                        'mel' and 'mel1000'.\n%\n%     'bwmul',bwmul      Bandwidth of the filters relative to the bandwidth\n%                        returned by |audfiltbw|. Default value is *bwmul=1* for \n%                        the scales 'erb', 'erb83' and 'bark'; the default is \n%                        *b=100* for 'mel' and 'mel1000'.\n%\n%     'redmul',redmul    Redundancy multiplier. Increasing the value of this\n%                        will make the system more redundant by lowering the\n%                        channel downsampling rates. It is only used if the\n%                        filterbank is a non-uniform filterbank. Default\n%                        value is *1*. If the value is less than one, the\n%                        system may no longer be painless.\n% \n%     'redtar',redtar    Target redundancy. The downsampling factors will be\n%                        adjusted to achieve a redundancy as close as possible\n%                        to 'redtar'.\n%\n%     'M',M              Specify the total number of filters between *fmin* and \n%                        *fmax*. If this parameter is specified, it overwrites the\n%                        `'spacing'` parameter.\n%\n%     'symmetric'        Create filters that are symmetric around their centre\n%                        frequency. This is the default.\n%\n%     'warped'           Create asymmetric filters that are symmetric on the\n%                        auditory scale. \n%\n%     'complex'          Construct a filterbank that covers the entire\n%                        frequency range instead of just the positive \n%                        frequencies this allows the analysis of complex\n%                        valued signals.\n%\n%     'nosubprec'        Disable subsample window positions.\n%\n%     'trunc_at'         When using a prototype defined in |freqwin|, a hard \n%                        thresholding of the filters at the specified threshold \n%                        value is performed to reduce their support size. \n%                        The default value is *trunc_at=10e-5*. When no \n%                        truncation is desired, *trunc_at=0* should be chosen.\n%                        This value is ignored when a prototype shape from\n%                        |firwin| was chosen.\n%\n%     'min_win',min_win  Minimum admissible window length (in samples).\n%                        Default is *4*. This restrict the windows not\n%                        to become too narrow when *L* is low.\n%\n%   Examples:\n%   ---------\n%\n%   In the first example, we construct a highly redudant uniform\n%   filterbank on the ERB scale and visualize the result:::\n%\n%     [f,fs]=greasy;  % Get the test signal\n%     [g,a,fc,L]=audfilters(fs,length(f),'uniform','M',100);\n%     c=filterbank(f,g,a);\n%     plotfilterbank(c,a,fc,fs,90,'audtick');\n%\n%   In the second example, we construct a non-uniform filterbank with\n%   fractional sampling that works for this particular signal length, and\n%   test the reconstruction. The plot displays the response of the\n%   filterbank to verify that the filters are well-behaved both on a\n%   normal and an ERB-scale. The second plot shows frequency responses of\n%   filters used for analysis (top) and synthesis (bottom). :::\n%\n%     [f,fs]=greasy;  % Get the test signal\n%     L=length(f);\n%     [g,a,fc]=audfilters(fs,L,'fractional');\n%     c=filterbank(f,{'realdual',g},a);\n%     r=2*real(ifilterbank(c,g,a));\n%     norm(f-r)\n%\n%     % Plot the response\n%     figure(1);\n%     subplot(2,1,1);\n%     R=filterbankresponse(g,a,L,fs,'real','plot');\n%\n%     subplot(2,1,2);\n%     semiaudplot(linspace(0,fs/2,L/2+1),R(1:L/2+1));\n%     ylabel('Magnitude');\n%\n%     % Plot frequency responses of individual filters\n%     gd=filterbankrealdual(g,a,L);\n%     figure(2);\n%     subplot(2,1,1);\n%     filterbankfreqz(gd,a,L,fs,'plot','linabs','posfreq');\n%\n%     subplot(2,1,2);\n%     filterbankfreqz(g,a,L,fs,'plot','linabs','posfreq');\n%\n%\n%   See also: filterbank, ufilterbank, ifilterbank, ceil23\n%\n%   References: ltfatnote027 nehobaprpide18\n\n% Authors: Peter L. S\u00f8ndergaard (original 'erbfilters' function)\n% Modified by: Thibaud Necciari, Nicki Holighaus\n% Comments updated by: Nicki Holighaus (09.05.22)\n\n% Date: 16.12.16\n\ncomplainif_notenoughargs(nargin,2,upper(mfilename));\ncomplainif_notposscalar(fs,'fs',upper(mfilename));\ncomplainif_notposint(Ls,'Ls',upper(mfilename));\n\nfirwinflags=getfield(arg_firwin,'flags','wintype');\nfreqwinflags=getfield(arg_freqwin,'flags','wintype');\n\ndefinput.flags.wintype = [ firwinflags, freqwinflags];\ndefinput.keyvals.M=[];\ndefinput.keyvals.redmul=1;\ndefinput.keyvals.min_win = 4;\ndefinput.keyvals.bwmul=[];\ndefinput.keyvals.spacing=[];\ndefinput.keyvals.trunc_at=10^(-5);\ndefinput.keyvals.fmin=0;\ndefinput.keyvals.fmax=fs/2;\ndefinput.keyvals.redtar=[];\ndefinput.flags.subprec={'subprec','nosubprec'};\ndefinput.flags.audscale={'erb','erb83','bark','mel','mel1000'};\ndefinput.flags.warp     = {'symmetric','warped'};\ndefinput.flags.real     = {'real','complex'};\ndefinput.flags.sampling = {'regsampling','uniform','fractional',...\n                           'fractionaluniform'};\n\n[varargin,winCell] = arghelper_filterswinparser(definput.flags.wintype,varargin);\n\n[flags,kv]=ltfatarghelper({'fmin','fmax'},definput,varargin);\nif isempty(winCell), winCell = {flags.wintype}; end\n\nswitch flags.audscale\n    case {'mel','mel1000'} % The mel scales are very fine, therefore default spacing is adjusted\n        definput.keyvals.bwmul=100;\n        definput.keyvals.spacing=100;\n    otherwise\n        definput.keyvals.bwmul=1;\n        definput.keyvals.spacing=1;\nend\n[flags,kv]=ltfatarghelper({'fmin','fmax','redtar'},definput,varargin);\n\nif flags.do_bark && (fs > 44100)\n    error(['%s: Bark scale is not suitable for sampling rates higher than 44.1 kHz. ',...\n    'Please choose another scale.'],upper(mfilename));\nend \n\nif ~isscalar(kv.bwmul) || kv.bwmul <= 0\n    error('%s: bwmul must be a positive scalar.',upper(mfilename));\nend\n\nif ~isscalar(kv.redmul) || kv.redmul <= 0\n    error('%s: redmul must be a positive scalar.',upper(mfilename));\nend\n\nif ~isempty(kv.redtar)\n    if ~isscalar(kv.redtar) || kv.redtar <= 0\n        error('%s: redtar must be a positive scalar.',upper(mfilename));\n    end\nend\n\nif kv.redtar <= 1\n    warning('%s: redtar is very low; the resulting system might be unstable.',upper(mfilename));\nend\n\nif kv.fmax <= kv.fmin || kv.fmin < 0 || kv.fmax > fs/2\n    error('%s: fmax must be bigger than fmin and in the range [0,fs/2].',upper(mfilename));\nend\n\nif kv.trunc_at > 1 || kv.trunc_at < 0\n    error('%s: trunc_at must be in range [0,1].',upper(mfilename));\nend\n\nif ~isscalar(kv.min_win) || rem(kv.min_win,1) ~= 0 || kv.min_win < 1\n    error('%s: min_win must be an integer bigger or equal to 1.',upper(mfilename));\nend\n\nif ~isempty(kv.M)\n    complainif_notposint(kv.M,'M',upper(mfilename));\n    kv.spacing = (freqtoaud(kv.fmax,flags.audscale) - freqtoaud(kv.fmin,flags.audscale))/(kv.M-1);\nend\n\n% Construct function handle for filter prototype and determine its ERB-type\n% bandwidth\n[filterfunc,winbw] = helper_filtergeneratorfunc(...\n                          flags.wintype,winCell,fs,kv.bwmul,kv.min_win,kv.trunc_at,...\n                          flags.audscale,flags.do_subprec,flags.do_symmetric,flags.do_warped);\n\n% Construct the AUD filterbank\nfmin = max(kv.fmin,audtofreq(kv.spacing,flags.audscale));\nfmax = min(kv.fmax,fs/2);\n\ninnerChanNum = floor((freqtoaud(fmax,flags.audscale)-freqtoaud(fmin,flags.audscale))/kv.spacing)+1;\n\nfmax = audtofreq(freqtoaud(fmin,flags.audscale)+(innerChanNum-1)*kv.spacing,flags.audscale);\n\n% Make sure that fmax < fs/2, and F_ERB(fmax) = F_ERB(fmin)+k/spacing, for\n% some k.\ncount = 0;\nwhile fmax >= fs/2\n    count = count+1;\n    fmax = audtofreq(freqtoaud(fmin,flags.audscale)+(innerChanNum-count-1)*kv.spacing,flags.audscale);    \nend\ninnerChanNum = innerChanNum-count;\n\nif fmax <= fmin || fmin > fs/4 || fmax < fs/4\n    error(['%s: Bad combination of fs, fmax and fmin.'],upper(mfilename));\nend\n\n% Center frequencies are given as equidistantly spaced points on auditory \n% scale \nfc=audspace(fmin,fmax,innerChanNum,flags.audscale).';\nfc = [0;fc;fs/2];\nM2 = innerChanNum+2;\n\nind = (2:M2-1)';\n%% Compute the frequency support\n% fsupp is measured in Hz \n\nfsupp=zeros(M2,1);\naprecise=zeros(M2,1);\n\nif flags.do_symmetric\n    fsupp(ind)=audfiltbw(fc(ind),flags.audscale)/winbw*kv.bwmul;\n    \n    % Generate lowpass filter parameters     \n    fsupp(1) = 0; % Placeholder value \n    % Determine border of passband\n    fps0 = audtofreq(freqtoaud(fc(2),flags.audscale)+3*kv.spacing,flags.audscale);% f_{p,s}^{-}\n    % Determine lowpass width\n    fsupp_temp1 = audfiltbw(fps0,flags.audscale)/winbw*kv.bwmul;\n    % Determine bandwidth-adapted decimation factor\n    aprecise(1) = max(fs./(2*max(fps0,0)+fsupp_temp1*kv.redmul),1);  \n    \n    % Generate highpass filter parameters     \n    fsupp(end) = 0; % Placeholder value\n    % Determine border of passband\n    fps0 = audtofreq(freqtoaud(fc(end-1),flags.audscale)-3*kv.spacing,flags.audscale);% f_{p,s}^{+}\n    % Determine highpass width\n    fsupp_temp1 = audfiltbw(fps0,flags.audscale)/winbw*kv.bwmul;\n    % Determine bandwidth-adapted decimation factor\n    aprecise(end) = max(fs./(2*(fc(end)-min(fps0,fs/2))+fsupp_temp1*kv.redmul),1);\nelse    \n    % fsupp_scale is measured on the selected auditory scale\n    % The scaling is incorrect, it does not account for the warping (NH:\n    % I do think it is correct.)\n    fsupp_scale=1/winbw*kv.bwmul;\n\n    % Convert fsupp into the correct widths in Hz, necessary to compute\n    % \"a\" in the next if-statement\n    fsupp(ind)=audtofreq(freqtoaud(fc(ind),flags.audscale)+fsupp_scale/2,flags.audscale)-...\n               audtofreq(freqtoaud(fc(ind),flags.audscale)-fsupp_scale/2,flags.audscale);\n    \n    % Generate lowpass filter parameters     \n    fsupp(1) = 0; % Placeholder value\n    % Determine border of passband\n    fps0 = audtofreq(freqtoaud(fc(2),flags.audscale)+3*kv.spacing,flags.audscale);% f_{p,s}^{-}\n    % Determine lowpass width\n    fsupp_temp1 = audfiltbw(fps0,flags.audscale)/winbw*kv.bwmul;\n    % Determine bandwidth-adapted decimation factor\n    aprecise(1) = max(fs./(2*max(fps0,0)+fsupp_temp1*kv.redmul),1);\n    \n    % Generate highpass filter parameters     \n    fsupp(end) = 0; % Placeholder value\n    % Determine border of passband\n    fps0 = audtofreq(freqtoaud(fc(end-1),flags.audscale)-3*kv.spacing,flags.audscale);% f_{p,s}^{+}\n    % Determine highpass width\n    fsupp_temp1 = audfiltbw(fps0,flags.audscale)/winbw*kv.bwmul;\n    % Determine bandwidth-adapted decimation factor\n    aprecise(end) = max(fs./(2*(fc(end)-min(fps0,fs/2))+fsupp_temp1*kv.redmul),1);\nend;\n\n% Do not allow lower bandwidth than keyvals.min_win\nfsuppmin = kv.min_win/Ls*fs;\nfor ii = 1:numel(fsupp)\n    if fsupp(ii) < fsuppmin;\n        fsupp(ii) = fsuppmin;\n    end\nend\n\n% Find suitable channel subsampling rates\naprecise(ind)=fs./fsupp(ind)/kv.redmul;\naprecise=aprecise(:);\n\nif any(aprecise<1)\n    error('%s: Invalid subsampling rates. Decrease redmul.',upper(mfilename))\nend\n\n%% Compute the downsampling rate\nif flags.do_regsampling\n    % Shrink \"a\" to the next composite number\n    a=floor23(aprecise);\n\n    % Determine the minimal transform length\n    L=filterbanklength(Ls,a);\n\n    % Heuristic trying to reduce lcm(a)\n    while L>2*Ls && ~(all(a)==a(1))\n        maxa = max(a);\n        a(a==maxa) = 0;\n        a(a==0) = max(a);\n        L = filterbanklength(Ls,a);\n    end\n\n% Determine true decimation factors from \"aprecise\" according to chosen\n% subsampling scheme (see help above)\nelseif flags.do_fractional\n    L = Ls;\n    N=ceil(Ls./aprecise);\n    a=[repmat(Ls,M2,1),N];\nelseif flags.do_fractionaluniform\n    L = Ls;\n    N=ceil(Ls./min(aprecise));\n    a= repmat([Ls,N],M2,1);\nelseif flags.do_uniform\n    a=floor(min(aprecise));\n    L=filterbanklength(Ls,a);\n    a = repmat(a,M2,1);\nend;\n\n% Get an expanded \"a\" / Convert \"a\" to LTFAT 2-column fractional format\nafull=comp_filterbank_a(a,M2,struct());\n\n%% Compute the scaling of the filters\n% Filters are scaled such that the energy of the subband coefficients\n% remains approximately constant independent of the decimation factor\nscal=sqrt(afull(:,1)./afull(:,2));\n\n%% Construct the real or complex filterbank\n\nif flags.do_real\n    % Scale the first and last channels\n    scal(1)=scal(1)/sqrt(2);\n    scal(M2)=scal(M2)/sqrt(2);\nelse\n    % Replicate the centre frequencies and sampling rates, except the first and\n    % last\n    a=[a;flipud(a(2:M2-1,:))];\n    scal=[scal;flipud(scal(2:M2-1))];\n    fc  =[fc; -flipud(fc(2:M2-1))];\n    fsupp=[fsupp;flipud(fsupp(2:M2-1))];\n    ind = [ind;numel(fc)+2-(M2-1:-1:2)'];\nend;\n\n\n%% Compute the filters\n% This is actually much faster than the vectorized call.\ng = cell(1,numel(fc));\nfor m=ind.'\n    g{m}=filterfunc(fsupp(m),fc(m),scal(m));\nend\n\n% Generate lowpass filter\ng{1} = audlowpassfilter(g(1:M2),a(1:M2,:),fc(1:M2),fs,scal(1),kv,flags);\n\n% Generate highpass filter\ng{M2} = audhighpassfilter(g(1:M2),a(1:M2,:),fc(1:M2),fs,scal(M2),kv,flags);\n\n% Adjust the downsampling rates in order to achieve 'redtar' (see help\n% above)\nif ~isempty(kv.redtar)\n    if flags.do_uniform\n        % Compute and display redundancy for verification\n        org_red = (M2-2)/a(1);\n        a_new = floor(a*org_red/kv.redtar);\n        scal_new = org_red/kv.redtar*ones(numel(g),1);\n        % new_red = (M2-2)/a_new(1);\n    else\n        % The decimation factors of all filters except for lowpass and \n        % highpass are adjusted proportional to their bandwidth. For \n        % lowpass and highpass, only the tapered part is considered for \n        % adjustment to better preserve stability. Please consult the\n        % references for details. \n        dk_old = a(:,1)./a(:,2);\n        org_red = sum(2./dk_old(2:end-1));\n        a_new = [a(1,:);[a(2:end-1,1),ceil(a(2:end-1,2)*kv.redtar/org_red)];a(end,:)];\n        % Adjust d0 and dK to the new redundancy\n        cbw = 2*sum(audfiltbw(fc(2:M2-1),flags.audscale)/winbw*kv.bwmul)/(kv.redtar*fs);\n        % Low-pass\n        fps0 = audtofreq(freqtoaud(fc(2),flags.audscale)+3*kv.spacing,flags.audscale);% f_{p,s}^{-}\n        fsupp_temp0 = audfiltbw(fps0,flags.audscale)/winbw*kv.bwmul;\n        a_new(1,2) = ceil(Ls/max(fs./(2*fps0+fsupp_temp0/cbw),1));  \n        % High-pass\n        fps1 = audtofreq(freqtoaud(fc(end-1),flags.audscale)-3*kv.spacing,flags.audscale);% f_{p,s}^{+}\n        fsupp_temp1 = audfiltbw(fps1,flags.audscale)/winbw*kv.bwmul;\n        a_new(end,2) = ceil(Ls/max(fs./(2*(fc(end)-fps1)+fsupp_temp1/cbw),1));\n        % Finally re-scale all filters\n        dk_new = a_new(:,1)./a_new(:,2);\n        scal_new = dk_new./dk_old; \n        % new_red = sum(2./dk_new)-sum(1./dk_new([1,end]));\n    end\n    g_new = filterbankscale(g,sqrt(scal_new)'); % Perform rescaling\n    a = a_new;\n    g = g_new;\n    if 0\n        % Compute and display redundancy for verification\n        fprintf('Original redundancy: %g \\n', org_red);\n        fprintf('Target redundancy: %g \\n', kv.redtar);\n        fprintf('Actual redundancy: %g \\n', new_red);\n    end\nend\n\nwinbwrat = winbw/0.754;\nbasebw = 1.875657;\n\ninfo.fc  = 2*fc/fs;\ninfo.tfr = @(L)(1/L)*1./((2*fsupp*winbwrat/fs)./basebw).^2;\n\n\n\nfunction glow = audlowpassfilter(g,a,fc,fs,scal,kv,flags)    \n\n% Make a probe, compute the restricted filter bank response to check if low-pass filter is needed\nLprobe = 10000;\nFBresp0 = filterbankresponse(g(2:end-1),a(2:end-1,:),Lprobe,'real');\neps_thr = 1e-3;\nind_f1 = floor(fc(2)*Lprobe/fs);\nind_fK = floor(fc(end-1)*Lprobe/fs);\nif ind_f1 == 0 || ...\n    min(FBresp0(1:ind_f1)) >= (1-eps_thr)*min(FBresp0(ind_f1:ind_fK))\n%       Not required\n    glow.H = @(L) 0;\n    glow.foff = @(L) 0;\n    glow.realonly = 0;\n    glow.delay = 0;\n    glow.fs = g{2}.fs;\nelse\n\n%       Required\n    % Compute the transition frequencies f_{p,s}^{-} and f_{p,e}^{-}\n    % Determines the width of the plateau\n    fps = audtofreq(freqtoaud(fc(2),flags.audscale)+3*kv.spacing,flags.audscale);\n    % Determines the cosine transition frequency\n    fpe = audtofreq(freqtoaud(fc(2),flags.audscale)+4*kv.spacing,flags.audscale);\n    fsupp_LP = 2*fpe;\n    ratio = 2*(fpe-fps)/fsupp_LP;\n    Lw = @(L) min(ceil(fsupp_LP*L/fs),L);\n\n    P0 = blfilter({'hann','taper',ratio},fsupp_LP,'fs',fs,'inf','min_win',kv.min_win);\n    temp_fbresp = @(L) filterbankresponse(g(2:end-1),a(2:end-1,:),L,'real');\n    Hinv = @(L) sqrt(max(temp_fbresp(L))-temp_fbresp(L));\n\n%     Compute the final low-pass filter\n    glow.H = @(L) fftshift(long2fir(...\n        filterbankfreqz(P0,a(1,:),L).*Hinv(L),Lw(L)))*scal;\n    glow.foff = @(L) -floor(Lw(L)/2);\n    glow.realonly = 0;\n    glow.delay = 0;\n    glow.fs = g{2}.fs;\nend\n    \nfunction ghigh = audhighpassfilter(g,a,fc,fs,scal,kv,flags)\n\n% Make a probe, compute the restricted filter bank response to check if hi-pass filter is needed\nLprobe = 10000;\nFBresp0 = filterbankresponse(g(2:end-1),a(2:end-1,:),Lprobe,'real');\neps_thr = 1e-3;\nind_f1 = floor(fc(2)*Lprobe/fs);\nind_fK = floor(fc(end-1)*Lprobe/fs);\nif ind_f1 == 0 ||...\n    min(FBresp0(ind_fK:floor(Lprobe/2))) >= (1-eps_thr)*min(FBresp0(ind_f1:ind_fK))\n%       Not required\n    ghigh.H = @(L) 0;\n    ghigh.foff = @(L) 0;\n    ghigh.realonly = 0;\n    ghigh.delay = 0;\n    ghigh.fs = g{2}.fs;\nelse\n\n    %     Compute the transition frequencies f_{p,s}^{+} and f_{p,e}^{+}\n    % Determines the width of the plateau\n    fps = audtofreq(freqtoaud(fc(end-1),flags.audscale)-3*kv.spacing,flags.audscale);\n    % Determines the cosine transition frequency\n    fpe = audtofreq(freqtoaud(fc(end-1),flags.audscale)-4*kv.spacing,flags.audscale);\n\n    %     plateauWidth = 2*(fs/2-fps);\n    fsupp_HP = 2*(fs/2-fpe);\n    ratio = 2*(fps-fpe)/fsupp_HP;\n    Lw = @(L) min(ceil(fsupp_HP*L/fs),L);\n\n    PK = blfilter({'hann','taper',ratio},fsupp_HP,'fc',fs/2,'fs',fs,'inf','min_win',kv.min_win);\n    temp_fbresp = @(L) filterbankresponse(g(2:end-1),a(2:end-1,:),L,'real');\n    Hinv = @(L) sqrt(max(temp_fbresp(L))-temp_fbresp(L));\n\n    %     Compute the final high-pass filter\n    ghigh.H = @(L) fftshift(long2fir(fftshift(...\n        filterbankfreqz(PK,a(1,:),L).*Hinv(L)),Lw(L)))*scal;\n\n    ghigh.foff = @(L) ceil(L/2)-floor(Lw(L)/2)-1;\n    ghigh.realonly = 0;\n    ghigh.delay = 0;\n    ghigh.fs = g{2}.fs;\nend\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/filterbank/audfilters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789040926008, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5532116069954905}}
{"text": "% Test file for trigtech/diff.m\n\nfunction pass = test_diff(pref)\n\n% Get preferences.\nif ( nargin < 1 )\n    pref = trigtech.techPref();\nend\n\n% Generate a few random points to use as test values.\nseedRNG(6178);\nx = 2 * rand(100, 1) - 1;\n\ntestclass = trigtech();\n\n%%\n% Spot-check derivatives for a couple of functions.\n\nf = testclass.make({[],[-.25;.75]});\ndf = diff(f);\ndf_coeffs_exact = [.25*pi*1i;0];\npass(1) = (norm(df.coeffs-df_coeffs_exact, inf) < eps*norm(df_coeffs_exact,inf));\n\nf = testclass.make(@(x) exp(cos(pi*x)), [], pref);\ndf = diff(f);\ndf_exact = @(x) -pi*sin(pi*x).*exp(cos(pi*x));\nerr = df_exact(x) - feval(df, x);\npass(2) = (norm(err, inf) < 1e3*vscale(df)*eps);\n    \n\na = 10; b = 20;\nf = testclass.make(@(x) cos(a*pi*sin(b*pi*x)), [], pref);\ndf = diff(f);\ndf_exact = @(x) -pi^2*a*b*cos(b*pi*x).*sin(a*pi*sin(b*pi*x));\nerr = df_exact(x) - feval(df, x);\npass(3) = (norm(err, inf) < 1e4*vscale(df)*eps);\n    \n\nf = testclass.make(@(x) exp(-50*x.^2), [], pref);\ndf = diff(f);\ndf_exact = @(x) -100*x.*exp(-50*x.^2);\nerr = df_exact(x) - feval(df, x);\npass(4) = (norm(err, inf) < 100*vscale(df)*eps);\n    \n\na1 = 4; b1 = 3; a2 = 6; b2 = 4;\nf = testclass.make(@(x) cos(a1*pi*sin(b1*pi*x)) + 1i*cos(a2*pi*sin(b2*pi*x)), [], pref);\ndf = diff(f);\ndf_exact = @(x) -pi^2*a1*b1*cos(b1*pi*x).*sin(a1*pi*sin(b1*pi*x)) - 1i*pi^2*a2*b2*cos(b2*pi*x).*sin(a2*pi*sin(b2*pi*x));\nerr = df_exact(x) - feval(df, x);\npass(5) = (norm(err, inf) < 1e3*vscale(df)*eps);\n    \n\n%%\n% Verify that calling diff() gives the same answer as direct construction.\n\nf = testclass.make(@(x) 1/21/pi*cos(21*pi*x), [], pref);\ndf = testclass.make(@(x) -sin(21*pi*x), [], pref);\nerr = diff(f) - df;\npass(6) = (norm(err.coeffs, inf) < 100*vscale(df)*eps);\n\n%%\n% Verify basic differentiation rules.\n\nf = testclass.make(@(x) exp(1)-exp(cos(3*pi*x)), [], pref);\ndf = diff(f);\ng = testclass.make(@(x) exp(-sin(2*pi*x)), [], pref);\ndg = diff(g);\ntol_f = 10*vscale(df)*eps;\ntol_g = 10*vscale(dg)*eps;\n\nerrfn = diff(f + g) - (df + dg);\nerr = feval(errfn, x);\npass(7) = (norm(err, inf) < 10*max(tol_f, tol_g));\n    \n    \nerrfn = diff(f.*g) - (f.*dg + g.*df);\nerr = feval(errfn, x);\npass(8) = (norm(err, inf) < length(f)*max(tol_f, tol_g));\n\nconst = testclass.make(@(x) ones(size(x)), [], pref);\ndconst = diff(const);\nerr = feval(dconst, x);\npass(9) = (norm(err, inf) == 0);\n\n%%\n% Check higher-order derivatives.  (NB:  We relax the tolerance by n + 1\n% factors of 10, where n is the number of derivatives taken.)\n\nf = testclass.make(@(x) exp(cos(4*pi*x))-1, [], pref);\ndf2 = diff(f, 2);\ndf2_exact = @(x) -16*pi^2*exp(cos(4*pi*x)).*(cos(4*pi*x) + cos(4*pi*x).^2 - 1);\nerr = df2_exact(x) - feval(df2, x);\npass(10) = (norm(err, inf) < 1e3*vscale(df2)*eps);\n    \n\nf = testclass.make(@(x) sin(pi*x), [], pref);\ndf6 = diff(f, 6);\ndf6_exact = -pi^6*f;\nerr = feval(df6_exact,x) - feval(df6, x);\npass(11) = (norm(err, inf) < 100*vscale(df6)*eps);\n\nf = testclass.make(@(x) (1/10/pi)*cos(10*pi*sin(pi*x)), [], pref);\ndf5 = diff(f, 5);\nerr = feval(df5,[-1;1]);  % Odd derivatives of this function vanish at +-1\npass(12) = (norm(err, inf) < 1e3*vscale(df5)*eps);\n    \n\n%%\n% Check operation for array-valued chebtech objects.\nf = testclass.make(@(x) [exp(-50*x.^2) sin(4*pi*(x-0.2)) 1i*exp(cos(pi*x))], [], pref);\ndf = diff(f);\ndf_exact = @(x) [-100*x.*exp(-50*x.^2) 4*pi*cos(4*pi*(x-0.2)) -pi*1i*sin(pi*x).*exp(cos(pi*x))];\nerr = feval(df, x) - df_exact(x);\npass(13) = (norm(err(:), inf) < 100*max(vscale(df)*eps));\n    \n\n% DIM option.\ndim2df = diff(f, 1, 2);\ng = @(x) [(sin(4*pi*(x-0.2))-exp(-50*x.^2))  (1i*exp(cos(pi*x))-sin(4*pi*(x-0.2)))];\nerr = feval(dim2df, x) - g(x);\npass(14) = isequal(size(vscale(dim2df)), [1 2]) && ...\n    (norm(err(:), inf) < 100*max(vscale(dim2df)*eps));\n    \n\n\ndim2df2 = diff(f, 2, 2);\ng = @(x) exp(-50*x.^2) - 2*sin(4*pi*(x-0.2)) + 1i*exp(cos(pi*x));\nerr = feval(dim2df2, x) - g(x);\npass(15) = isequal(size(vscale(dim2df2)), [1 1]) && ...\n    (norm(err(:), inf) < 1e3*max(vscale(dim2df2)*eps));\n    \n\n% DIM option should return an empty trigtech for non-array-valued input.\nf = testclass.make(@(x) sin(pi*x));\ndim2df = diff(f, 1, 2);\npass(16) = (isempty(dim2df.coeffs));\n\n% even example with complex coefficients\nf = testclass.make({[],[1+1i;1-1i]});\ndf = diff(f);\ndf_coeffs_exact = [-pi*1i*(1+1i);0;];\npass(17) = (norm(df.coeffs-df_coeffs_exact, inf) < eps*norm(df_coeffs_exact,inf));\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/trigtech/test_diff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789040926009, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5532116017620865}}
{"text": "function EIN = PQIntNoise (f)\n% Generate the internal noise energy vector\n\n% P. Kabal $Revision: 1.1 $  $Date: 2003/12/07 13:34:10 $\n\nN = length (f);\nfor (m = 0:N-1)\n    INdB = 1.456 * (f(m+1) / 1000)^(-0.8);\n    EIN(m+1) = 10^(INdB / 10);\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/PQIntNoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5531631702715898}}
{"text": "function perr = p_err(t, pc, pk, qp, tt, ts)\n    %p_err calculate p error\n    sumln=sum(log(t+pc));\n    qsumln=pk/qp^2;\n    qsumln=qsumln*(((tt+pc)^qp)*(1-qp*log(tt+pc))-((ts+pc)^qp)*(1-qp*log(ts+pc)));\n    esumln=qsumln+sumln;\n    perr=esumln;\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/p_err.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5531631664445161}}
{"text": "% explore balloon model stability\n\nclear all\nclose all\nclc\n\nxg1 = [-5:0.2:5];\nxg2 = xg1;\nn = length(xg1);\nlm = zeros(n,n);\nkas = [-4:0.2:4];\nkaf = [-3:0.2:3];\n\ntry\n\n    load demo_stability_hrf.mat\n    % get max eigenvalue\n    P = [0;0;0;0;0;0];\n    for i=1:n\n        for j=1:n\n            J = VBA_numericDiff(@f_HRF,1,[xg1(i);xg2(j);0;0],P,0,[]);\n            lm(i,j) = max(real(eig(J)));\n        end\n    end\n\n    % get separatrix\n    stab = zeros(n,n);\n    stab(lm>=0) = -1;\n    L = del2(stab);\n    sep = zeros(n,n);\n    sep(L<0)=1;\n    p = length(find(L==1));\n    y = [];\n    for i=1:n\n        for j=1:n\n            if sep(i,j)==1\n                y = [y,[xg1(i);xg2(j)]];\n            end\n        end\n    end\n    g_fname = @g_exp;\n    options.inG.x = y(2,:)';\n    options.priors.muPhi = [1;1;0];\n    options.priors.SigmaPhi = eye(3);\n    options.priors.SigmaPhi(1,1) = 0;\n    options.priors.SigmaPhi(3,3) = 0;\n    options.verbose = 0;\n    options.DisplayWin = 0;\n    dim.n_theta         = 0;\n    dim.n_phi           = 3;\n    dim.n               = 0;\n    [posterior,out] = VBA_NLStateSpaceModel(y(1,:)',[],[],g_fname,dim,options);\n\ncatch\n\n    % loop over different kas/kaf\n    phi = zeros(length(kaf),length(kas));\n    for k=1:length(kas)\n        for l=1:length(kaf)\n            k,l\n            % get max eigenvalue\n            P = [0;0;kaf(l);kas(k);0;0];\n            for i=1:n\n                for j=1:n\n                    J = VBA_numericDiff(@f_HRF,1,[xg1(i);xg2(j);0;0],P,0,[]);\n                    lm(i,j) = max(real(eig(J)));\n                end\n            end\n\n            % get separatrix\n            stab = zeros(n,n);\n            stab(lm>=0) = -1;\n            L = del2(stab);\n            sep = zeros(n,n);\n            sep(L<0)=1;\n            p = length(find(L==1));\n            y = [];\n            for i=1:n\n                for j=1:n\n                    if sep(i,j)==1\n                        y = [y,[xg1(i);xg2(j)]];\n                    end\n                end\n            end\n            g_fname = @g_exp;\n            options.inG.x = y(2,:)';\n            options.priors.muPhi = [1;1;0];\n            options.priors.SigmaPhi = eye(3);\n            options.priors.SigmaPhi(1,1) = 0;\n            options.priors.SigmaPhi(3,3) = 0;\n            options.verbose = 0;\n            options.DisplayWin = 0;\n            dim.n_theta         = 0;\n            dim.n_phi           = 3;\n            dim.n               = 0;\n            [posterior,out] = VBA_NLStateSpaceModel(y(1,:)',[],[],g_fname,dim,options);\n            phi(l,k) = posterior.muPhi(2);\n\n        end\n    end\n\nend\n\n% store for display purposes\nx = options.inG.x;\ngx = out.suffStat.gx;\nPHI = posterior.muPhi;\n\ngkaf = kron(ones(1,length(kas)),kaf)';\ngkaf = gkaf - mean(gkaf);\ngkas = kron(kas,ones(1,length(kaf)))';\ngkas = gkas - mean(gkas);\noptions = [];\ng_fname = @g_exp2d;\noptions.inG.gkaf = gkaf;\noptions.inG.gkas = gkas;\noptions.priors.muPhi = ones(1,1);\noptions.priors.SigmaPhi = 1e4*eye(1);\noptions.verbose = 1;\noptions.DisplayWin = 1;\ndim.n_theta         = 0;\ndim.n_phi           = 1;\ndim.n               = 0;\n[posterior,out] = VBA_NLStateSpaceModel(...\n    phi(:),[],[],g_fname,dim,options);\nI = reshape(out.suffStat.gx,length(kaf),length(kas));\n\n\n% display results\n\nhf = figure('color',[1 1 1],'position',[649,40,767,1105],'menubar','none');\nha = subplot(3,2,1,'parent',hf);\nhi = imagesc(flipud(lm),'parent',ha);\nxlabel(ha,'x2: blood inflow')\nylabel(ha,'x1: vasodilatory signal')\ntitle(ha,'max eigenvalue')\ncolorbar('peer',ha);\n\nha = subplot(3,2,2,'parent',hf);\nhi = plot(y(2,:),y(1,:),'.','parent',ha);\nxlabel(ha,'x2: blood inflow')\nylabel(ha,'x1: vasodilatory signal')\nset(ha,...\n    'xlim',[min(xg1),max(xg1)],...\n    'ylim',[min(xg1),max(xg1)],...\n    'nextplot','add')\naxis(ha,'square')\ngrid(ha,'on')\ntitle(ha,...\n    ['separatrix: kas=',...\n    num2str(P(4)),...\n    ' ; kaf=',...\n    num2str(P(3))])\nset(ha,'nextplot','add')\n[xs,is] = sort(x);\nys = gx(is);\nplot(ha,xs,ys,'k','parent',ha)\nplot(0,0,'r+','parent',ha);\nstr = ['x(1) = ',...\n    'theta',...\n    '*exp(',...\n    'x(2)) : theta = ',...\n    num2str(PHI(2))];\nlegend(ha,{'numerical',str,'equilibrium'})\n\nha = subplot(3,2,3,'parent',hf);\nhi = imagesc(phi,'parent',ha);\ncolorbar('peer',ha);\nxlabel(ha,'kas')\nylabel(ha,'kaf')\ntitle('separatrix parameter (theta)')\n\nha = subplot(3,2,4,'parent',hf);\nhi = plot(kas,phi','parent',ha);\nxlabel(ha,'kas')\nylabel(ha,'separatrix parameter (theta)')\ngrid(ha,'on');\naxis(ha,'tight')\nfor i=1:length(kaf)\n    leg{i} = ['kaf=',num2str(kaf(i))];\nend\nlegend(ha,leg)\ntitle(ha,'separatrix parameter (theta)')\n\nha = subplot(3,2,5,'parent',hf);\nhi = imagesc(I,'parent',ha);\ncolorbar('peer',ha);\nxlabel(ha,'kas')\nylabel(ha,'kaf')\ntitle('fitted separatrix parameter (theta)')\n\nha = subplot(3,2,6,'parent',hf);\nhi = plot(phi(:),I(:),'k.','parent',ha);\nmi = min([phi(:);I(:)]);\nma = max([phi(:);I(:)]);\nset(ha,'nextplot','add')\nplot(ha,[mi ma],[mi ma],'r')\nxlabel(ha,'sep param')\nylabel(ha,'fitted sep param (theta)')\ntitle('sep param model fit')\n\nstr = ['theta = ',...\n    num2str(posterior.muPhi(1)),...\n    '*exp(kaf/2 - |kas-kaf/2|)'];\nlegend(ha,{'numerical',str})\ngrid(ha,'on');\nset(ha,'xlim',[mi ma],'ylim',[mi ma])\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/4_neural/demo_stability_HRF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5531631548320384}}
{"text": "function [X_hat]=SD_detector(y,H,nT)\n    % Input parameters\n    %     y : received signal, nRx1\n    %     H : Channel matrix, nRxnT\n    %    nT : number of Tx antennas\n    % Output parameter\n    %    X_hat : estimated signal, nTx1\n\n    global x_list;         % candidate symbols in real constellations\n    global x_now;          % temporary x_vector elements\n    global x_hat;          % inv(H)*y\n    global x_sliced;       % sliced x_hat\n    global x_pre;          % x vectors obtained in the previous stage\n    global real_constellation; % real constellation\n    global R;               % R in the QR decomposition\n    global radius_squared; % radius^2\n    global x_metric;       % ML metrics of previous stage candidates\n    global len;             % nT*2\n    QAM_table2 = [-3-3j, -3-j, -3+3j, -3+j, -1-3j, -1-j, -1+3j, -1+j,3-3j, ...\n               3-j, 3+3j, 3+j, 1-3j, 1-j, 1+3j, 1+j]/sqrt(10); % 16-QAM\n    real_constellation = [-3 -1 1 3]/sqrt(10);\n    y =[real(y); imag(y)];     % y : complex vector  -> real vector\n    H =[real(H)  -(imag(H)) ; imag(H)   real(H)];    \n    % H : complex vector  -> real vector\n    len = nT*2; % complex -> real\n    x_list = zeros(len,4); % 4 : real constellation length, 16-QAM\n    x_now = zeros(len,1); x_hat = zeros(len,1); x_pre = zeros(len,1); x_metric = 0;\n    [Q,R] = qr(H);     % nR x nT QR decomposition\n    x_hat = inv(H)*y;                % zero forcing equalization\n    x_sliced = QAM16_real_slicer(x_hat,len)';  % slicing\n    radius_squared  = norm(R*(x_sliced-x_hat))^2;  % Radious^2\n    transition = 1;\n    % meaning of transition \n    % 0 : radius*2, 1~len : stage number\n    % len+1 : compare two vectors in terms of norm values\n    % len+2 : finish\n    flag = 1; \n    % transition tracing 0 : stage index increases by +1 \n    %1 : stage index decreases by -1 \n    %2 : 1->len+2 or len+1->1\n    while (transition<len+2)\n       if transition==0    % radius_squared*2\n         [flag,transition,radius_squared,x_list]= radius_control(radius_squared,transition);\n        elseif transition <= len\n         [flag,transition] = stage_processing(flag,transition);\n        elseif transition == len+1 % \n         [flag,transition] = compare_vector_norm(transition);\n       end\n    end\n    ML = x_pre;\n    for i=1:len/2\n        X_hat(i) = ML(i)+j*ML(i+len/2);\n    end\nend\n\nfunction [flag,transition] = stage_processing(flag,transition)\n    % Input parameters\n    %    flag : previous stage index\n    %       flag = 0 : stage index decreased -> x_now empty -> new x_now\n    %       flag = 1 : stage index decreased -> new x_now\n    %       flag = 2 : previous stage index =len+1 ->  If R>R'? start from the first stage\n    %     transition : stage number\n    % Output parameters\n    %     flag : stage number is calculated from flag\n    %     transition : next stage number, 0 : R*2, 1: next stage, len+2: finish\n    global x_list x_metric x_now x_hat real_constellation R radius_squared x_sliced;\n\n    global x_list;\n    global x_metric;\n    global x_now;\n    global x_hat;\n    global real_constellation;\n    global R;\n    global radius_squared;\n    global x_sliced;\n    stage_index = length(R(1,:))-(transition-1); \n    if flag == 2  % previous stage=len+1 : recalculate radius R'\n      radius_squared  = norm(R*(x_sliced-x_hat))^2;\n    end\n    if flag ~= 0 % previous stage=len+1 or 0 \n    -> upper and lower bound calculation, x_list(stage_index,:)\n        [bound_lower bound_upper] = bound(transition);\n        for i =1:4    % search for a candidate in x_now(stage_index),\n           % 4=size(real_constellation), 16-QAM assumed\n           if bound_lower <= real_constellation(i) && real_constellation(i) <= bound_upper\n             list_len = list_length(x_list(stage_index,:));\n             x_list(stage_index,list_len+1) = real_constellation(i);\n           end\n        end\n    end\n    list_len = list_length(x_list(stage_index,:));\n    if list_len == 0     % no candidate in x_now\n      if x_metric == 0 || transition ~= 1 \n        % transition >=2 ? if no candidate ? decrease stage index\n        flag = 0;\n        transition = transition-1;\n       elseif x_metric ~= 0 && transition == 1 \n        % above two conditions are met? ML solution found\n        transition = length(R(1,:))+2;  % finish stage\n      end\n    else              % candidate exist in x_now ? increase stage index\n      flag = 1;\n      transition = transition+1;\n      x_now(stage_index) = x_list(stage_index,1);\n      x_list(stage_index,:) = [x_list(stage_index,[2:4]) 0]; \nend\n\nfunction [bound_lower bound_upper]=bound(transition)\n    % Input parameters\n    %     R : [Q R] = qr(H)\n    %     radius_squared : R^2\n    %     transition : stage number\n    %     x_hat : inv(H)*y\n    %     x_now : slicing x_hat\n    % Output parameters\n    %     bound_lower : bound lower\n    %     bound_upper : bound upper\n\n    global R  radius_squared  x_now  x_hat;\n    len = length(x_hat);\n    temp_sqrt = radius_squared;\n    temp_k=0;\n    for i=1:1:transition-1\n       temp_abs=0;\n       for k=1:1:i\n          index_1 = len-(i-1);\n          index_2 = index_1+ (k-1);\n          temp_k = R(index_1,index_2)*(x_now(index_2)-x_hat(index_2));\n          temp_abs=temp_abs+temp_k;\n       end\n       temp_sqrt = temp_sqrt - abs(temp_abs)^2;\n    end\n    temp_sqrt = sqrt(temp_sqrt);\n    temp_no_sqrt = 0;\n    index_1 = len-(transition-1);\n    index_2 = index_1;\n    for i=1:1:transition-1\n       index_2 = index_2+1;\n       temp_i = R(index_1,index_2)*(x_now(index_2)-x_hat(index_2));\n       temp_no_sqrt = temp_no_sqrt - temp_i;\n    end\n    temp_lower = -temp_sqrt + temp_no_sqrt;\n    temp_upper = temp_sqrt + temp_no_sqrt;\n    index = len-(transition-1);\n    bound_lower = temp_lower/R(index,index) + x_hat(index);\n    bound_upper = temp_upper/R(index,index) + x_hat(index);\n    bound_upper = fix(bound_upper*sqrt(10))/sqrt(10);  \n    bound_lower = ceil(bound_lower*sqrt(10))/sqrt(10); \nend\n\nfunction [len]=list_length(list)\n    % Input parameter\n    %     list : vector type\n    % Output parameter\n    %     len : index number\n\n    len = 0;\n    for i=1:4\n       if list(i)==0,  break;  else len = len+1;  end\n    end\nend\n\nfunction [flag,transition,radius_squared,x_list] =radius_control(radius_squared,transition)\n    % Input parameters\n    %     radius_squared : current radius\n    %     transition : current stage number\n    % Output parameters\n    %     radius_squared : doubled radius\n    %     transition : next stage number\n    %     flag : next stage number is calculated from flag\n    global len;\n    radius_squared = radius_squared*2;\n    transition = transition+1;\n    flag = 1;\n    x_list(len,:)=zeros(1,4);\nend\n\nfunction [check]=vector_comparison(vector_1,vector_2)\n    % check if the two vectors are the same\n    % Input parameters\n    %   pre_x : vector 1\n    %   now_x : vector 2\n    % Output parameters\n    %   check : 1-> same vectors, 0-> different vectors\n    check = 0;\n    len1 = length(vector_1);  len2 = length(vector_2);\n    if len1 ~= len2\n      error('vector size is different');\n    end\n    for column_num = 1:len1\n       if vector_1(column_num,1) == vector_2(column_num,1)\n         check = check + 1;\n       end\n    end\n    if check == len1,  check = 1;\n     else    check = 0;\n    end\nend\n\nfunction [flag,transition]=compare_vector_norm(transition)\n    % stage index increased(flag = 1) : recalculate x_list(index,:)\n    % stage index decreased(flag = 0) : in the previous stage, no candidate x_now in x_list\n    % Input parameters\n    %     flag : previous stage\n    %     transition : stage number\n    % Output parameters\n    %    flag : next stage number is calculated from flag\n    %    transition : next stage number\n    global x_list x_pre x_metric x_now x_hat R radius_squared x_sliced len;\n    vector_identity = vector_comparison(x_pre,x_now); \n    % check if the new candidate is among the ones we found before\n    if vector_identity == 1  \n      % if 1 ? ML solution found\n      len_total = 0;\n      for i=1:len  % if the vector is unique ? len_total = 0\n         len_total = len_total + list_length(x_list(i,:));\n      end\n      if len_total == 0      % ML solution vector found\n        transition = len+2; % finish\n        flag = 1;\n       else                      % more than one candidates \n        transition = transition-1;  % go back to the previous stage\n        flag =0;\n      end\n     else  % if 0 ? new candidate vector is different from the previous candidate vector and norm is smaller ? restart\n      x_sliced_temp = x_now;\n      metric_temp  = norm(R*(x_sliced_temp-x_hat))^2;\n      if metric_temp <=  radius_squared \n        % new candidate vector has smaller metric ? restart\n        x_pre = x_now;  x_metric = metric_temp;\n        x_sliced = x_now;  transition = 1;       % restart\n        flag = 2;  x_list=zeros(len,4); % initialization\n        x_now=zeros(len,1);  % initialization\n       else % new candidate vector has a larger ML metric\n        transition = transition-1;  % go back to the previous stage\n        flag =0;\n      end\n    end\nend\n", "meta": {"author": "LyricYang", "repo": "MIMO_OFDM", "sha": "df25e1837bc4019f2bbcd946bc49b0942827a847", "save_path": "github-repos/MATLAB/LyricYang-MIMO_OFDM", "path": "github-repos/MATLAB/LyricYang-MIMO_OFDM/MIMO_OFDM-df25e1837bc4019f2bbcd946bc49b0942827a847/\u7b2c11\u7ae0 \u7a7a\u95f4\u590d\u7528\u7684MIMO\u7cfb\u7edf\u7684\u4fe1\u53f7\u68c0\u6d4b/\u7403\u5f62\u8bd1\u7801/SD_detector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5531631480362167}}
{"text": "%DEMO_SPATIAL2  Demonstration for a disease mapping problem with Gaussian\n%               process prior and negative binomial observation\n%               model\n%\n%  Description\n%    The disease mapping problem consist of a data with number of\n%    death cases, Y, and background population, N, appointed to\n%    co-ordinates, X. The goal is to find a relative risk surface,\n%    which describes if the number of death cases in certain areas\n%    is lower or higher than expected. The data is simulated.\n%\n%    The model is constructed as follows:\n%\n%    The number of death cases Y_i in area i is assumed to satisfy\n%\n%         Y_i ~ Neg-Bin(Y_i| d, E_i * r_i)\n%\n%    where E_i is the expected number of deaths (see Vanhatalo and\n%    Vehtari (2007), how E_i is evaluated) at area i, r_i is the\n%    relative risk and d is the dispersion parameter coverning the\n%    variance.\n%\n%    We place a zero mean Gaussian process prior for log(R), R =\n%    [r_1, r_2,...,r_n], which implies that at the observed input\n%    locations latent values, f, have prior\n%\n%         f = log(R) ~ 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. We place a prior\n%    for parameters, p(th).\n%\n%    The inference is conducted first with Laplace approximation\n%    and then with EP. We use compactly supported covariance\n%    function which leads to sparse covariance matrix.\n%\n%  See also  \n%    DEMO_REGRESSION1, DEMO_CLASSIFIC1, DEMO_SPATIAL1\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% Laplace approximation\n% =====================================\n\n% load the data\nS = which('demo_spatial2');\ndata = load(strrep(S,'demo_spatial2.m','demodata/spatial2.txt'));\n\nx = data(:,1:2);\nye = data(:,3);\ny = data(:,4);\n\n% Now we have loaded the following parameters\n% x = co-ordinates \n% y = number of deaths\n% ye = the expexted number of deaths\n\nfprintf(['GP with negative-binomial observation model, Laplace\\n' ...\n         'integration over the latent values and MAP estimate\\n' ...\n         'for the parameters\\n']);\n\n% Create the covariance functions\npl = prior_t();\npm = prior_sqrtt('s2', 0.3);\nif ~exist('ldlchol')\n  warning('GPstuff:SuiteSparseMissing',...\n    ['SuiteSparse is not properly installed. \\n' ...\n    'Using gpcf_sexp (non-compact support) instead of gpcf_ppcs2 (compact support)']);\n  gpcf1 = gpcf_sexp('lengthScale', 5, 'magnSigma2', 0.05);\n  gpcf1 = gpcf_sexp(gpcf1, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\nelse\n  gpcf1 = gpcf_ppcs2('nin', 2, 'lengthScale', 5, 'magnSigma2', 0.05);\n  gpcf1 = gpcf_ppcs2(gpcf1, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\nend\n\n% Create the likelihood structure\nlik = lik_negbin();\n\n% Create the GP structure\ngp = gp_set('lik', lik, 'cf', gpcf1, 'jitterSigma2', 1e-4); \n\n% Set the approximate inference method to Laplace\ngp = gp_set(gp, 'latent_method', 'Laplace');\n\n% Set the options for the scaled conjugate optimization\nopt=optimset('TolFun',1e-2,'TolX',1e-2,'Display','iter');\n% Optimize with the scaled conjugate gradient method\ngp=gp_optim(gp,x,y,'z',ye,'opt',opt);\n\n% Visualize sparsity pattern\nfigure\nC = gp_trcov(gp,x);\nfprintf('Proportion of non-zeros is %.4f\\n',nnz(C) / prod(size(C)))\np = amd(C);\nspy(C(p,p))\n\n% Make prediction to the data points\n[Ef, Varf] = gp_pred(gp, x, y, x, 'z', ye);\n\n% Define help parameters for plotting\nxii=sub2ind([120 70],x(:,2),x(:,1));\n[X1,X2]=meshgrid(1:70,1:120);\n\n% Plot the figures\nfigure\nG=repmat(NaN,size(X1));\nG(xii)=exp(Ef);\npcolor(X1,X2,G),shading flat\ncolormap(mapcolor(G)),colorbar\nset(gca, 'Clim', [0.2    1.5])\naxis equal\naxis([0 70 0 120])\ntitle('Posterior median of the relative risk (Laplace)')\n\nfigure\nG=repmat(NaN,size(X1));\nG(xii)=(exp(Varf) - 1).*exp(2*Ef+Varf);\npcolor(X1,X2,G),shading flat\ncolormap(mapcolor(G)),colorbar\n%set(gca, 'Clim', [0.005    0.03])\naxis equal\naxis([0 70 0 120])\ntitle('Posterior variance of the relative risk (Laplace)')\n\n\n% =====================================\n% EP approximation\n% =====================================\nfprintf(['GP with negative-binomial observation model, EP\\n' ...\n         'integration over the latent values and MAP estimate\\n' ...\n         'for the parameters\\n']);\n\n% Set the approximate inference method to EP\ngp = gp_set(gp, 'latent_method', 'EP');\n\n% Set the options for the scaled conjugate optimization\nopt=optimset('TolFun',1e-2,'TolX',1e-2,'Display','iter');\n% Optimize with the scaled conjugate gradient method\ngp=gp_optim(gp,x,y,'z',ye,'opt',opt);\n\n% Visualize sparsity pattern\nfigure\nC = gp_trcov(gp,x);\nfprintf('Proportion of non-zeros is %.4f\\n',nnz(C) / prod(size(C)))\np = amd(C);\nspy(C(p,p))\n\n% make prediction to the data points\n[Ef, Varf] = gp_pred(gp, x, y, x, 'z', ye);\n\n% Define help parameters for plotting\nxii=sub2ind([120 70],x(:,2),x(:,1));\n[X1,X2]=meshgrid(1:70,1:120);\n\n% Plot the figures\nfigure\nG=repmat(NaN,size(X1));\nG(xii)=exp(Ef);\npcolor(X1,X2,G),shading flat\ncolormap(mapcolor(G)),colorbar\nset(gca, 'Clim', [0.2    1.5])\naxis equal\naxis([0 70 0 120])\ntitle('Posterior median of the relative risk (EP)')\n\nfigure\nG=repmat(NaN,size(X1));\nG(xii)=(exp(Varf) - 1).*exp(2*Ef+Varf);\npcolor(X1,X2,G),shading flat\ncolormap(mapcolor(G)),colorbar\n%set(gca, 'Clim', [0.005    0.03])\naxis equal\naxis([0 70 0 120])\ntitle('Posterior variance of the relative risk (EP)')\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_spatial2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5531196249572974}}
{"text": "function [alphas,l,rho,d12,ix] = matRad_siddonRayTracer(isocenter, ...\n                                    resolution, ...\n                                    sourcePoint, ...\n                                    targetPoint, ...\n                                    cubes)\n% siddon ray tracing through 3D cube to calculate the radiological depth \n% according to Siddon 1985 Medical Physics\n% \n% call\n%   [alphas,l,rho,d12,vis] = matRad_siddonRayTracer(isocenter, ...\n%                               resolution, ...\n%                               sourcePoint, ...\n%                               targetPoint, ...\n%                               cubes)\n%\n% input\n%   isocenter:      isocenter within cube [voxels]\n%   resolution:     resolution of the cubes [mm/voxel]\n%   sourcePoint:    source point of ray tracing\n%   targetPoint:    target point of ray tracing\n%   cubes:          cell array of cubes for ray tracing (it is possible to pass\n%                   multiple cubes for ray tracing to save computation time)\n%\n% output (see Siddon 1985 Medical Physics for a detailed description of the\n% variales)\n%   alphas          relative distance between start and endpoint for the \n%                    intersections with the cube\n%   l               lengths of intersestions with cubes\n%   rho             densities extracted from cubes\n%   d12             distance between start and endpoint of ray tracing\n%   ix              indices of hit voxels\n%\n% References\n%   [1] http://www.ncbi.nlm.nih.gov/pubmed/4000088\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% Add isocenter to source and target point. Because the algorithm does not\n% works with negatives values. This put (resolution.x,resolution.y,resolution.z)\n% in the center of first voxel\n\nsourcePoint = sourcePoint + isocenter;\ntargetPoint = targetPoint + isocenter;\n\n% Save the numbers of planes.\n[yNumPlanes, xNumPlanes, zNumPlanes] = size(cubes{1});\nxNumPlanes = xNumPlanes + 1;\nyNumPlanes = yNumPlanes + 1;\nzNumPlanes = zNumPlanes + 1;\n\n% eq 11\n% Calculate the distance from source to target point.\nd12 = norm(sourcePoint-targetPoint);\n\n% eq 3\n% Position of first planes in millimeter. 0.5 because the central position\n% of the first voxel is at [resolution.x resolution.y resolution.z]\nxPlane_1 = .5*resolution.x;\nyPlane_1 = .5*resolution.y;\nzPlane_1 = .5*resolution.z;\n\n% Position of last planes in milimiter\nxPlane_end = (xNumPlanes - .5)*resolution.x;\nyPlane_end = (yNumPlanes - .5)*resolution.y;\nzPlane_end = (zNumPlanes - .5)*resolution.z;\n\n% eq 4\n% Calculate parametrics values of \\alpha_{min} and \\alpha_{max} for every\n% axis, intersecting the ray with the sides of the CT. \nif targetPoint(1) ~= sourcePoint(1)\n    aX_1   = (xPlane_1 - sourcePoint(1)) / (targetPoint(1) - sourcePoint(1));\n    aX_end = (xPlane_end - sourcePoint(1)) / (targetPoint(1) - sourcePoint(1));\nelse\n    aX_1   = [];\n    aX_end = [];\nend\nif targetPoint(2) ~= sourcePoint(2)\n    aY_1   = (yPlane_1 - sourcePoint(2)) / (targetPoint(2) - sourcePoint(2));\n    aY_end = (yPlane_end - sourcePoint(2)) / (targetPoint(2) - sourcePoint(2));\nelse\n    aY_1   = [];\n    aY_end = [];\nend\nif targetPoint(3) ~= sourcePoint(3)\n    aZ_1   = (zPlane_1 - sourcePoint(3)) / (targetPoint(3) - sourcePoint(3));\n    aZ_end = (zPlane_end - sourcePoint(3)) / (targetPoint(3) - sourcePoint(3));\nelse\n    aZ_1   = [];\n    aZ_end = [];\nend\n\n% eq 5\n% Compute the \\alpha_{min} and \\alpha_{max} in terms of parametric values\n% given by equation 4.\nalpha_min = max([0 min(aX_1,aX_end) min(aY_1,aY_end) min(aZ_1,aZ_end)]);\nalpha_max = min([1 max(aX_1,aX_end) max(aY_1,aY_end) max(aZ_1,aZ_end)]);\n\n% eq 6\n% Calculate the range of indeces who gives parametric values for\n% intersected planes.\nif targetPoint(1) == sourcePoint(1)\n    i_min = []; i_max = [];\nelseif targetPoint(1) > sourcePoint(1)\n    i_min = xNumPlanes - (xPlane_end - alpha_min * (targetPoint(1) - sourcePoint(1)) - sourcePoint(1))/resolution.x;\n    i_max = 1          + (sourcePoint(1) + alpha_max * (targetPoint(1) - sourcePoint(1)) - xPlane_1)/resolution.x;\n    % rounding\n    i_min = ceil(1/1000*(round(1000*i_min)));\n    i_max = floor(1/1000*(round(1000*i_max)));\nelse\n    i_min = xNumPlanes - (xPlane_end - alpha_max * (targetPoint(1) - sourcePoint(1)) - sourcePoint(1))/resolution.x;\n    i_max = 1          + (sourcePoint(1) + alpha_min * (targetPoint(1) - sourcePoint(1)) - xPlane_1)/resolution.x;\n    i_min = ceil(1/1000*(round(1000*i_min)));\n    i_max = floor(1/1000*(round(1000*i_max)));\nend\nif targetPoint(2) == sourcePoint(2)\n    j_min = []; j_max = [];\nelseif targetPoint(2) > sourcePoint(2)\n    j_min = yNumPlanes - (yPlane_end - alpha_min * (targetPoint(2) - sourcePoint(2)) - sourcePoint(2))/resolution.y;\n    j_max = 1          + (sourcePoint(2) + alpha_max * (targetPoint(2) - sourcePoint(2)) - yPlane_1)/resolution.y;\n    j_min = ceil(1/1000*(round(1000*j_min)));\n    j_max = floor(1/1000*(round(1000*j_max)));\nelse\n    j_min = yNumPlanes - (yPlane_end - alpha_max * (targetPoint(2) - sourcePoint(2)) - sourcePoint(2))/resolution.y;\n    j_max = 1          + (sourcePoint(2) + alpha_min * (targetPoint(2) - sourcePoint(2)) - yPlane_1)/resolution.y;\n    j_min = ceil(1/1000*(round(1000*j_min)));\n    j_max = floor(1/1000*(round(1000*j_max)));\nend\nif targetPoint(3) == sourcePoint(3)\n    k_min = []; k_max = [];\nelseif targetPoint(3) >= sourcePoint(3)\n    k_min = zNumPlanes - (zPlane_end - alpha_min * (targetPoint(3) - sourcePoint(3)) - sourcePoint(3))/resolution.z;\n    k_max = 1          + (sourcePoint(3) + alpha_max * (targetPoint(3) - sourcePoint(3)) - zPlane_1)/resolution.z;\n    k_min = ceil(1/1000*(round(1000*k_min)));\n    k_max = floor(1/1000*(round(1000*k_max)));\nelse\n    k_min = zNumPlanes - (zPlane_end - alpha_max * (targetPoint(3) - sourcePoint(3)) - sourcePoint(3))/resolution.z;\n    k_max = 1          + (sourcePoint(3) + alpha_min * (targetPoint(3) - sourcePoint(3)) - zPlane_1)/resolution.z;\n    k_min = ceil(1/1000*(round(1000*k_min)));\n    k_max = floor(1/1000*(round(1000*k_max)));\nend\n\n% eq 7\n% For the given range of indices, calculate the paremetrics values who\n% represents intersections of the ray with the plane.\nif i_min ~= i_max\n    if targetPoint(1) > sourcePoint(1)\n        alpha_x = (resolution.x*(i_min:1:i_max)-sourcePoint(1)-.5*resolution.x)/(targetPoint(1)-sourcePoint(1));\n    else\n        alpha_x = (resolution.x*(i_max:-1:i_min)-sourcePoint(1)-.5*resolution.x)/(targetPoint(1)-sourcePoint(1));\n    end\nelse\n    alpha_x = [];\nend\nif j_min ~= j_max\n    if targetPoint(2) > sourcePoint(2)\n        alpha_y = (resolution.y*(j_min:1:j_max)-sourcePoint(2)-.5*resolution.y)/(targetPoint(2)-sourcePoint(2));\n    else\n        alpha_y = (resolution.y*(j_max:-1:j_min)-sourcePoint(2)-.5*resolution.y)/(targetPoint(2)-sourcePoint(2));\n    end\nelse\n    alpha_y = [];\nend\nif k_min ~= k_max\n    if targetPoint(3) > sourcePoint(3)\n        alpha_z = (resolution.z*(k_min:1:k_max)-sourcePoint(3)-.5*resolution.z)/(targetPoint(3)-sourcePoint(3));\n    else\n        alpha_z = (resolution.z*(k_max:-1:k_min)-sourcePoint(3)-.5*resolution.z)/(targetPoint(3)-sourcePoint(3));\n    end\nelse\n    alpha_z = [];\nend\n\n% eq 8\n% Merge parametrics sets.\nalphas = unique([alpha_min alpha_x alpha_y alpha_z alpha_max]);\n\n% eq 10\n% Calculate the voxel intersection length.\nl = d12*diff(alphas);\n\n% eq 13\n% Calculate \\alpha_{middle}\nalphas_mid = .5*(alphas(1:end-1)+alphas(2:end));\n\n% eq 12\n% Calculate the voxel indices: first convert to physical coords\ni_mm = sourcePoint(1) + alphas_mid*(targetPoint(1) - sourcePoint(1));\nj_mm = sourcePoint(2) + alphas_mid*(targetPoint(2) - sourcePoint(2));\nk_mm = sourcePoint(3) + alphas_mid*(targetPoint(3) - sourcePoint(3));\n% then convert to voxel index\ni = round(i_mm/resolution.x);\nj = round(j_mm/resolution.y);\nk = round(k_mm/resolution.z);\n\n% Handle numerical instabilities at the borders.\ni(i<=0) = 1; j(j<=0) = 1; k(k<=0) = 1;\ni(i>xNumPlanes-1) = xNumPlanes-1;\nj(j>yNumPlanes-1) = yNumPlanes-1;\nk(k>zNumPlanes-1) = zNumPlanes-1;\n\n% Convert to linear indices\nix = j + (i-1)*size(cubes{1},1) + (k-1)*size(cubes{1},1)*size(cubes{1},2); \n\n% obtains the values from cubes\nrho = cell(numel(cubes),1);\nfor i = 1:numel(cubes)\n    rho{i} = cubes{i}(ix);\nend\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/matRad_siddonRayTracer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5531196243690356}}
{"text": "% Author: Housam Binous\n\n% Dynamic and control of a tank using the genetic algorithm toolbox\n\n% National Institute of Applied Sciences and Technology, Tunis, TUNISIA\n\n% Email: binoushousam@yahoo.com\n\nfunction f=obj2(par)\n\nglobal sys\n\n% real PID controller's transfer function\n\nnum=[par(2) 1];\nden=[par(2) 0];\n\npid1=tf(num,den);\n\nnum=[par(3) 1];\nden=[0.1*par(3) 1];\n\npid2=tf(num,den);\n\npid=par(1)*pid1*pid2;\n\n% response to change in set point\n% set point for tank's height is equal to 2\n\nsys_series=series(pid,sys);\n\nsys_controlled=feedback(sys_series,1);\n\nu=2*ones(501,1);\n\n[y1 t3]=lsim(sys_controlled,u,0:0.01:5);\n\n% objective function to be minimized by\n% genetic algorithm in order to obtain\n% real PID controller's parameters\n\nf=0;\n\nfor i=1:201\n    f=f+abs(2-y1(i))*t3(i);\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/16523-dynamic-and-control-of-tanks-height-using-genetic-algorithm-toolbox-and-fminsearch/tank/obj2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5531196221171488}}
{"text": "% This is a simple example of how to fit \n% a cubic spline contour\n% to data using active geometric shape model. \n\n% Copyright (C) 2012 Quan Wang <wangq10@rpi.edu>, \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% Quan Wang, Kim L. Boyer, \n% The active geometric shape model: A new robust deformable shape model and its applications, \n% Computer Vision and Image Understanding, Volume 116, Issue 12, December 2012, Pages 1178-1194, \n% ISSN 1077-3142, 10.1016/j.cviu.2012.08.004. \n% \n% For commercial use, please contact the authors. \n\nclear;clc;close all;\naddpath('../force field');\naddpath('../math');\n\n%% 1. experiment set up\n\n% image size = 400*500\nrows=400;\ncols=500;\n\n% number of trials\nNum_Of_Trials=10;\n\n% number of data points and outliers\nnum_data=100;\nnum_outlier=5;\nnoise=5;\n\n% number of landmarks for data/model\nNlm=6; % data\nNN=6; % model\n\n% ground truth parameters\nx0=250+(rand(1)-0.5)*100;\ny0=200+(rand(1)-0.5)*100;\nD0=60+rand(1,Nlm)*100;\n\n% image blur parameters\nsigma1=20;\nsigma2=5;\n\n%% 2. generate data\n\n% generate data points and outliers\ntheta=rand(num_data,1)*2*pi;\nlm_theta=linspace(0,2*pi,Nlm+1);\nDD=myspline(lm_theta,D0,theta);\nx=x0+DD.*cos(theta)+noise*randn(size(theta));\ny=y0+DD.*sin(theta)+noise*randn(size(theta));\nx=[x;rand(num_outlier,1)*cols];\ny=[y;rand(num_outlier,1)*rows];\nx=round(x);\ny=round(y);\nx(x<1)=1;\nx(x>cols)=cols;\ny(y<1)=1;\ny(y>rows)=rows;\nxp=x;\nyp=y;\n\n% display data points and outliers\nplot(x,y,'.');\naxis equal;\naxis([1 cols 1 rows]);\ntitle('data points and outliers');\nxlabel('x');\nylabel('y');\ndrawnow;\n\n% generate image\nI=zeros(rows,cols);\nfor i=1:max(size(y))\n    I(y(i),x(i))=100;\nend\n[m n]=size(I);\n\n%% 3. GVF field\nI2=gaussianBlur(I,sigma1);\n[u,v] = GVF(I2, 1 , 0.1, 50);\ndx2=u;dy2=v;\n\nI3=gaussianBlur(I,sigma2);\n[dx3 dy3]=gradient(I3);\n\nbest_fit=Inf;\n\n%% 4. many trials\ndisp('Fitting the cubic spline contour...');\nfor trial=1:Num_Of_Trials\n    close all;\n    fprintf('Trial: %d\\n',trial);\n    init=[250+(rand(1)-0.5)*100,200+(rand(1)-0.5)*100,60+rand(1,NN)*40];\n    increment=[0.2,0.2,0.2];\n    threshold=[0.000001,0.000001,0.000001];\n    bound=[40,150];\n    %% fit a spline contour\n    % stage 1: big sigma\n    [xc yc D fit_save]=fit_spline_contour_force(...\n        init,increment,threshold,bound,dx2,dy2,500,0);\n    \n    % stage 2: small sigma\n    [xc yc D]=fit_spline_contour_force(...\n        [xc yc D],increment,threshold,bound,dx3,dy3,100,0);\n    \n    %% correction\n    clear D2;\n    for k=1:NN\n        dt=2*pi/100000;\n        angle=2*pi/NN*(k-1);\n        \n        lm_theta=linspace(0,2*pi,NN+1);\n        distances=myspline(lm_theta,D,[angle-dt angle angle+dt]);\n        r=D(k);\n        r1=(distances(3)-distances(1)) / (2*dt);\n        r2=(distances(3)+distances(1)-2*distances(2)) / (dt^2);\n        D2(k)=correctCurve_polar(r,r1,r2,sigma2,100);\n    end\n    D=D2;\n    \n    %% fitness function\n    beta=0.9;\n    fit0=0;\n    fit1=0;\n    fit2=0;\n    [x,y,theta]=spline_contour_in_image(m,n,xc,yc,D);\n    [x1,y1,theta1]=spline_contour_in_image(m,n,xc,yc,D*beta);\n    [x2,y2,theta2]=spline_contour_in_image(m,n,xc,yc,D/beta);\n    for i=1:max(size(theta))\n        fit0=fit0+norm([dx2(y(i),x(i)),dy2(y(i),x(i))]);\n    end\n    for i=1:max(size(theta1))\n        fit1=fit1+norm([dx2(y1(i),x1(i)),dy2(y1(i),x1(i))]);\n    end\n    for i=1:max(size(theta2))\n        fit2=fit2+norm([dx2(y2(i),x2(i)),dy2(y2(i),x2(i))]);\n    end\n    fit0=fit0/max(size(theta));\n    fit1=fit1/max(size(theta1));\n    fit2=fit2/max(size(theta2));\n    current_fit=fit0-fit1/2-fit2/2;\n    \n    if current_fit<best_fit\n        best_fit=current_fit;\n        best_xc=xc;\n        best_yc=yc;\n        best_D=D;\n        best_fit_save=fit_save;\n    end\nend\n\n% display fitting results\nclose all;\n\nfigure;\nplot(xp,yp,'.');\naxis equal;\naxis([1 cols 1 rows]);\nhold on;\ntheta=0:0.01:2*pi;\n[x2,y2,temp]=spline_contour_in_image(rows,cols,best_xc,best_yc,best_D);\nplot(x2,y2,'-.r','LineWidth',2);\nplot(xp,yp,'.');\nlegend('noisy data points and outliers','active geometric shape model fit');\ntitle('fitting a cubic spline contour using active geometric shape model');\nxlabel('x');\nylabel('y');\n\n%% 5. show numerical results\nfprintf('num_data=%-4d    num_outlier=%-4d    \\n',num_data,num_outlier);\nfprintf('Nlm(data)=%-4d   Nlm(model)=%-4d    \\n',Nlm,NN);\nfprintf('------------------------------------------------------------\\n');\nfprintf('         xc        yc        D   \\n');\nfprintf('True:  ');\ndisp([x0 y0 D0]);\nfprintf('Fit:   ');\ndisp([best_xc best_yc best_D]);\n\n%% 6. show fitness function\nfigure;hold on;\nplot(1:500,best_fit_save,'b','LineWidth',2);\nlegend('fitness function');\ngrid on;\nxlabel('iteration');\nylabel('fitness function');\ntitle('fitness function in each iteration');", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/38358-active-geometric-shape-models/AGSM_toolkit_v1.0/code/spline closed contour fitting/demo_spline_contour_fitting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5531196116895271}}
{"text": "function [sys,x0,str,ts]=Nonlinear_PD_fhan(t,x,u,flag,r,h,h1)\n\nif flag==0\n\n    sys = [0;1;1;2;0;1;1];\n     x0 = [0];                       \n    str = [ ];\n     ts = [h 0];           \n   \nelseif flag==2\n    \n    \n    sys=-fhan(u(1),u(2),r,h1);    \n    \nelseif flag==3\n    sys=x;\n    \nelseif flag==4\n    sys=sys+h;\n    \nelse \n    sys=[];\nend\nfunction y=fhan(x1,x2,r,h)\nd=r*h;\nd0=h*d;\ny=x1+h*x2;\na0=sqrt(d^2+8*r*abs(y));\nif abs(y)>d0\n    a=x2+(a0-d)*sign(y)/2;\nelse\n    a=x2+y/h;\nend\n\nif abs(a)>d\n    y=-r*sign(a);\nelse \n    y=-r*a/d;\nend", "meta": {"author": "TianfaYao", "repo": "ADRC", "sha": "6f1f96ebda1684c44af4dec4214b4880f4aa8cec", "save_path": "github-repos/MATLAB/TianfaYao-ADRC", "path": "github-repos/MATLAB/TianfaYao-ADRC/ADRC-6f1f96ebda1684c44af4dec4214b4880f4aa8cec/\u8d3a\u5e86\u6bd5\u4e1a\u8bba\u6587ADRC\u5168\u96c6\u5305\u4ec5\u7528\u4e8e\u5185\u90e8\u5171\u4eab\u4e0d\u8981\u5916\u4f20/MyLibrary/Nonlinear_PD_fhan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5530870230049049}}
{"text": "function bvec_sub_test ( )\n\n%*****************************************************************************80\n%\n%% BVEC_SUB_TEST tests BVEC_SUB;\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    03 January 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 10;\n  seed = 123456789;\n  test_num = 10;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'BVEC_SUB_TEST\\n' );\n  fprintf ( 1, '  BVEC_SUB subtracts binary vectors representing integers;\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '        I        J        I - J   BVEC_SUB\\n' );\n  fprintf ( 1, '\\n' );\n\n  for test = 1 : test_num\n    \n    [ i, seed ] = i4_uniform_ab ( -100, 100, seed );\n    [ j, seed ] = i4_uniform_ab ( -100, 100, seed );\n\n    k = i - j;\n\n    bvec1 = i4_to_bvec ( i, n );\n    bvec2 = i4_to_bvec ( j, n );\n    bvec4 = bvec_sub ( n, bvec1, bvec2 );\n    l = bvec_to_i4 ( n, bvec4 );\n\n    fprintf ( 1, '  %8d  %8d  %8d  %8d\\n', i, j, k, l );\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/bvec/bvec_sub_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.5530672270742187}}
{"text": "function out = correl_compare_dep_permtest(y1,y2,varargin)\n% Compare dependent correlations between pairs of vectors in y1 and y2\n%\n% :Usage:\n% ::\n%\n%     out = correl_compare_dep_permtest(y1,y2,['alpha',myalpha],['rank'],['table'])\n%\n% :PERMUTATION TEST: for correl_compare_dep\n%\n% Repeats dep. correl. analysis for each pair of columns\n% Returns results in correlation matrix form, where number of rows and\n% cols. are the number of pairs [y1(:,i) y2(:,i)]\n%\n% myalpha is 2-tailed alpha value; p-values are 2-tailed\n% FDR correction is at .01, 2-tailed\n%\n% Based on Steiger, 1980, tests for comparing dependent correlations.\n%\n% :Examples:\n% ::\n%\n%    for i = 1:length(cl), y1(:,i) = cl.CONTRAST.data(:,2); y2(:,i) = cl.CONTRAST.data(:,1); end\n%    for i = 1:length(cl), y1(:,i) = cl(i).CONTRAST.data(:,2); y2(:,i) = cl(i).CONTRAST.data(:,1); end\n%    y1 is matrix of obs x data vectors for condition 1\n%    y2 is matrix of obs x data vectors for condition 2\n%    out = correl_compare_dep(y1,y2)\n%\n%    figure('Color','w');nmdsfig(c.GroupSpace,c.ClusterSolution.classes, ...\n%    c.names,out.sig,1,{'Pos' 'Neg'});\n%    nmdsfig_legend(c.ClusterSolution.X,c.r)\n%\n%    % compare correlations on cluster averages\n%    c_compare = correl_compare_dep(y1avg,y2avg,'alpha',.05,'rank','table','names',c.APPLY_CLUSTER.names);\n\n\n    myalpha = .05;\n    dorankdata = 0;\n    dotable = 0;\n    names = [];\n\n    for i = 1:length(varargin)\n        if isstr(varargin{i})\n            switch varargin{i}\n                % functional commands\n                case 'alpha', myalpha = varargin{i+1};\n                case 'rank', dorankdata = 1;\n                case 'table', dotable = 1;\n                case 'names', names = varargin{i+1};\n                otherwise, warning(['Unknown input string option:' varargin{i}]);\n            end\n        end\n    end\n\n\n    [N,npairs] = size(y1);\n\n\n    [rows,cols,ncorr] = corrcoef_indices(npairs);\n\n    if nargin < 4, dorankdata = 0; end\n    if dorankdata\n        str = sprintf('Ranking data: Nonparametric correlations'); fprintf(1,str);\n\n        for i = 1:npairs\n            y1(:,i) = rankdata(y1(:,i));\n            y2(:,i) = rankdata(y2(:,i));\n        end\n    else\n        str = sprintf('Assuming continuous data (no ranks).'); fprintf(1,str);\n    end\n\n    erase_string(str);\n\n    i = 1; j = 2; k = 3; h = 4;\n\n    % ----------------------------------------\n    %%% Correct Permutation %%%\n    % ----------------------------------------\n    str = sprintf('Computing differences among correlations %04d',0); fprintf(1,str);\n    \n    [diffr,Zstar2,rr,pvec] = compare_dep_subfcn(ncorr,y1,y2,rows,cols,i,j,k,h,N);\n\n    erase_string(str);\n    \n    % ----------------------------------------\n    %%% All output stuff %%%\n    % ----------------------------------------\n    r1 = reconstruct(rr(:,1),npairs,ncorr,rows,cols);\n    r2 = reconstruct(rr(:,2),npairs,ncorr,rows,cols);\n\n    Z = reconstruct(Zstar2,npairs,ncorr,rows,cols);\n    p = reconstruct(pvec,npairs,ncorr,rows,cols);\n\n    dat = [rr diffr Zstar2 pvec];\n    dat = [rows cols dat];\n    dat = dat(pvec <= myalpha,:);\n\n    diffr = reconstruct(diffr,npairs,ncorr,rows,cols);\n\n    sig = (p <= myalpha - eye(size(p))) .* sign(diffr);\n\n    % FDR corrected\n    pthr = FDR(pvec,.05);\n    if isempty(pthr), pthr = 0; end\n\n    sigfdr = (p <= pthr) .* sign(diffr);\n\n    out = struct('alpha',myalpha,'r1',r1,'r2',r2,'diffr',diffr, ...\n        'Z',Z,'p',p,'sig',sig,'pthr',pthr,'sigfdr',sigfdr,'sigstats',dat);\n\n    % output table...\n    if dotable\n        if isempty(names)\n            disp(['No names entered; try ''names'' keyword to add them.']);\n            for ii = 1:npairs, names{ii} = ['R' num2str(ii)]; end\n        end\n\n        disp(['Uncorrected, p < ' num2str(myalpha)])\n        maketable(out,'sig',names);\n        disp('')\n\n        disp(['FDR corrected, p < ' num2str(myalpha)])\n        maketable(out,'sigfdr',names);\n        disp('')\n    end\n\n    % ----------------------------------------\n    %%% Permutations %%%\n    % ----------------------------------------\n    niter = 5000;\n\n    [out.nalpha,out.n01,out.nalpha_posvsneg,out.n01_posvsneg] = do_perms;\n    out.crit_n_at_alpha = prctile(out.nalpha,95);\n    out.crit_n_at_01 = prctile(out.n01,95);\n    out.crit_sumsigned_at_alpha = prctile(out.nalpha_posvsneg,97.5);\n    out.crit_sumsigned_at_01 = prctile(out.n01_posvsneg,97.5);\n    \n    out.numsig_at_alpha = sum(squareform(out.p) <= out.alpha);\n    out.numsig_at_01 = sum(squareform(out.p) <= .01);\n\n    out.sumsigned_at_alpha = sum(  (squareform(out.p) <= out.alpha) .* sign(squareform(out.diffr))  );\n    out.sumsigned_at_01 = sum(  (squareform(out.p) <= .01) .* sign(squareform(out.diffr))  );\n    \n    \n    if dotable\n        fprintf(1,'Alpha: %3.4f, Num. sig: %3.0f, Critical num sig: %3.0f\\n',out.alpha,out.numsig_at_alpha,out.crit_n_at_alpha);\n        fprintf(1,'Alpha: %3.4f, Num. sig: %3.0f, Critical num sig: %3.0f\\n',.01,out.numsig_at_01,out.crit_n_at_01);\n            \n        fprintf(1,'Alpha: %3.4f, Sum of signed sig.: %3.0f, Critical num 2-tailed: %3.0f\\n',out.alpha,out.sumsigned_at_alpha, out.crit_sumsigned_at_alpha);\n        fprintf(1,'Alpha: %3.4f, Sum of signed sig.: %3.0f, Critical num 2-tailed: %3.0f\\n',.01,out.sumsigned_at_01, out.crit_sumsigned_at_01);\n    \n    end\n    \n    \n    % nested function\n    % get number of significant effects under null hypothesis at alpha and at\n    % .01\n    function [nalpha,n01,nalpha_posvsneg,n01_posvsneg] = do_perms\n        \n        nalpha = zeros(1,niter);\n        n01 = nalpha;\n        nalpha_posvsneg = nalpha;\n        n01_posvsneg = nalpha;\n        \n        fprintf(1,'Getting distribution for number of significant correlations.\\n  Running %3.0f permutations: %04d',niter,0);\n        \n        for ii = 1:niter\n            fprintf(1,'\\b\\b\\b\\b%04d',ii);\n     \n            % permute data\n            for jj = 2:npairs\n                wh = randperm(N);\n                y1(:,jj) = y1(wh,jj);\n                y2(:,jj) = y2(wh,jj);                \n            end\n            \n            % test correlations\n            [diffr,Zstar2,rr,pvec] = compare_dep_subfcn(ncorr,y1,y2,rows,cols,i,j,k,h,N,0);\n           \n            nalpha(ii) = sum(pvec <= myalpha);\n            n01(ii) = sum(pvec <= .01);\n            \n            nalpha_posvsneg(ii) = sum(  (pvec <= myalpha) .* sign(diffr)  );\n            n01_posvsneg(ii) = sum(  (pvec <= .01) .* sign(diffr)  );\n            \n        end\n        fprintf(1,'\\n');\n        \n    end\n        \n    end   %%% end main function\n\n    \n    \n    \n    \n    \n    \n    function [diffr,Zstar2,rr,pvec] = compare_dep_subfcn(ncorr,y1,y2,rows,cols,i,j,k,h,N,dotext)\n    \n    diffr = zeros(ncorr,1);     % correlation difference\n    Zstar2 = zeros(ncorr,1);    % from Steiger, the Z-score\n    rr = zeros(ncorr,2);        % the correl values for y1 and y2\n\n    if ~exist('dotext','var'), dotext = 1; end\n    \n    for cc = 1:ncorr\n\n        if dotext, fprintf(1,'\\b\\b\\b\\b%04d',cc); end\n\n        % get full correlation matrix for the 4 variables involved\n        dat = [y1(:,[rows(cc) cols(cc)]) y2(:,[rows(cc) cols(cc)])];\n\n        % get differences between correlation z-values (estimate)\n        [diffr(cc),r,rr(cc,:),diffrz,z] = correlation_diffs(dat,i,j,k,h);\n\n        s = covcorr(r,i,j,k,h);         % covariance of corr coeffs\n\n        Zstar2(cc) = diffrz * sqrt( (N-3) ./ (2-(2*s)) );\n\n        % bootstrap\n        %vals = bootstrp(5000,@correlation_diffs,dat,i,j,k,h);\n        %Zboot(cc) = mean(vals) ./ std(vals);\n\n        %if Zstar2(cc) > 2, keyboard, end\n    end\n\n    pvec = 2 * (1 - normcdf(abs(Zstar2)));\n\n    end\n    \n    \n    \n\nfunction [diffr,r,rr,diffrz,z] = correlation_diffs(dat,i,j,k,h)\n    % get differences between correlation z-values\n    r = corrcoef(dat);\n\n    rr = [r(i,j) r(k,h)];                % correls to be compared\n    diffr = -diff(rr);              % negative sign means we get (1) - (2)\n\n    if nargout > 3\n        z = .5 .* log( (1+rr) ./ (1-rr) );\n        diffrz = -diff(z);               % diff btwn correl z values\n    end\n\n    end\n\n\n\nfunction [rows,cols,ncorr] = corrcoef_indices(npairs)\n    % upper triangle only\n    tmp = triu(ones(npairs));\n    tmp = tmp - eye(npairs);\n    [rows,cols] = find(tmp);\n    ncorr = length(rows);\n    end\n\n\n\n\nfunction s = covcorr(R,i,j,k,h)\n\n    % pool correl. coeff for more stable var est.\n    % as they are equal under Ho.  Steiger, 1980, eq. 14 for Z*\n    pooledr = mean([R(i,j) R(k,h)]);\n    s = pearsonf(R,i,j,k,h) ./  ( corvar(pooledr) );\n\n    end\n\n\nfunction cv = corvar(r)\n    % variance of a correlation coefficient\n    % simplified form (special case) of pearsonf\n    cv = (1 - r^2) ^ 2;\n    end\n\n\n    % % function cv = co(R,x,y)\n    % % % x and y are 2-vector indices of matrix R to compute covariance for\n    % % % cv is covariance\n    % % cv = pearsonf(R,x(1),x(2),y(1),y(2));\n    % % end\n\n\nfunction pf = pearsonf(R,i,j,k,h)\n\n    % Pearson-Filon: covariance (or var) of element i,j with element k,h\n    % depending on correlation values\n\n    % for variance of 1 correl, works as well, and reduces to:\n    % (1 - rr(1)^2)^2\n\n    pf = (1/2) .* R(i,j) .* R(k,h) .* ...\n        ( R(i,k).^2 + R(i,h).^2 + R(j,k).^2 + R(j,h).^2 ) + ...\n        R(i,k) .* R(j,h) + R(i,h) .* R(j,k) - ...\n        R(i,j) .* ( R(j,k) .* R(j,h) + R(i,k) .* R(i,h) ) - ...\n        R(k,h) .* ( R(j,k) .* R(i,k) + R(j,h) .* R(i,h) );\n\n\n    end\n\n\n\n\n    % function pf = pearsonf2(r,j,k,h,m)\n    %\n    % pf = .5 * ( (r(j,h) - r(j,k)*r(k,h)) * (r(k,m) - r(k,h)*r(h,m))  + ...\n    %     (r(j,m) - r(j,h)*r(h,m)) * (r(k,h) - r(k,j)*r(j,h)) + ...\n    %     (r(j,h) - r(j,m)*r(m,h)) * (r(k,m) - r(k,j)*r(j,m)) + ...\n    %     (r(j,m) - r(j,k)*r(k,m)) * (r(k,h) - r(k,m)*r(m,h))    );\n    %\n    % end\n\nfunction valmat = reconstruct(vals,npairs,ncorr,rows,cols)\n\n    valmat = zeros(npairs);\n    for i = 1:ncorr\n        valmat(rows(i),cols(i)) = vals(i);\n    end\n    valmat = valmat + valmat';\n\n    end\n\n\n\nfunction erase_string(str1)\n    fprintf(1,repmat('\\b',1,length(str1))); % erase string\n    end\n\n\n% function maketable(c_compare,whfield,names)\n%     [rows,cols] = find(triu(c_compare.(whfield)));\n%     if isempty(rows)\n%         disp('No significant results.')\n%     else\n%         fprintf(1,'Name1\\tName2\\trow\\tcol.\\t+ or -\\tZ\\tp\\n');\n%         for i = 1:length(rows)\n%             fprintf(1,'%s\\t%s\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.2f\\t%3.4f\\n',names{rows(i)}, ...\n%                 names{cols(i)},rows(i),cols(i),c_compare.(whfield)(rows(i),cols(i)),c_compare.Z(rows(i),cols(i)),c_compare.p(rows(i),cols(i)));\n%         end\n%     end\n%     fprintf(1,'\\n');\n%     end\n\n\nfunction maketable(c_compare,whfield,names)\n    \n    str = {'-' '+'};\n    [rows,cols] = find(triu(c_compare.(whfield)));\n    if isempty(rows)\n        disp('No significant results.')\n    else\n        fprintf(1,'Name1\\tName2\\trow\\tcol.\\t+ or -\\tr1\\tr2\\tZ\\tp\\n');\n        for i = 1:length(rows)\n            fprintf(1,'%s\\t%s\\t%3.0f\\t%3.0f\\t%s\\t%3.3f\\t%3.3f\\t%3.2f\\t%3.4f\\n', ...\n                names{rows(i)}, names{cols(i)},rows(i),cols(i), ...                 \n                str{1.5 + (.5.*c_compare.(whfield)(rows(i),cols(i)))}, ...          % + or - sign\n                c_compare.r1(rows(i),cols(i)),c_compare.r2(rows(i),cols(i)), ...   % correlations\n                c_compare.Z(rows(i),cols(i)),c_compare.p(rows(i),cols(i)));        % Z and p\n        end\n    end\n    fprintf(1,'\\n');\nend\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/Statistics_tools/correl_compare_dep_permtest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5530672232221098}}
{"text": "//Make some assumptions\n// let's assume seq_len = 64 for now\n// N d_mod d_ff h dk dv \n// 6 512   2048 8 64 64\nConstant Seq_Len 128;\n\nNetwork Transformer {\n\t//Start encoder\n\tLayer MH_FC_DimReduce_VKQ_0 { //Batched FC layer, where seq_len is batch, input is d_model x 1\n\t\tType: CONV\n\t\tStride { X: 1, Y: 1 }\t// k = 3 * 512, one for each VKQ\n\t\tDimensions { N: Seq_Len, K: 1536, C: 1, R: 1, S: 512, Y:1, X:512 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(1,1) C;\n\t\t\tTemporalMap(Sz(R),Sz(R)) R;\n\t\t\tTemporalMap(Sz(S),Sz(S)) S;\n\t\t\tTemporalMap(Sz(R),1) Y;\n\t\t\tTemporalMap(Sz(S),1) X;\t\n\t\t\tCluster(1, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t\tTemporalMap(Sz(R),1) Y;\n\t\t\tTemporalMap(Sz(S),1) X;\n\t\t\tTemporalMap(Sz(R),Sz(R)) R;\n\t\t\tTemporalMap(Sz(S),Sz(S)) S;\n\t\t}\n\t} //good\n\n\tLayer SD_MatMul_QK_00 { //Mat mul, batch is 1\n\t\tType: CONV //MatMul -> M(seql)xK(dv)xN(seql)-> filter = Kx1(m chans), input = KxN \n\t\tStride { X: 1, Y: 1 }\n\t\t//N=1, K(conv)=M(matr), C=1, R(conv)=K(matr),S=1,Y(conv)=K(matr), X(conv)=N(matr)\n\t\tDimensions { N: 1, K: Seq_Len, C: 1, R: 64, S: 1, Y:64, X:Seq_Len }\n\t\tDataflow {\n\t\t\tSpatialMap(2,1) K;\n\t\t\tTemporalMap(1,1) C;\n\t\t\tTemporalMap(Sz(R),Sz(R)) R;\n\t\t\tTemporalMap(Sz(S),Sz(S)) S;\n\t\t\tTemporalMap(Sz(R),1) Y;\n\t\t\tTemporalMap(Sz(S),1) X;\t\n\t\t\t\n\t\t}\n\t}\n\n\tLayer SD_MatMul_V_00 { //Mat mul, batch is 1\n\t\tType: CONV //MatMul -> M(seql)xK(seql)xN(dv)-> filter = Kx1(m chans), input = KxN \n\t\tStride { X: 1, Y: 1 }\n\t\t//N=1, K(conv)=M(matr), C=1, R(conv)=K(matr),S=1,Y(conv)=K(matr), X(conv)=N(matr)\n\t\tDimensions { N: 1, K: Seq_Len, C: 1, R: Seq_Len, S: 1, Y:Seq_Len, X:64 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(1,1) C;\n\t\t\tTemporalMap(Sz(R),Sz(R)) R;\n\t\t\tTemporalMap(Sz(S),Sz(S)) S;\n\t\t\tTemporalMap(Sz(R),1) Y;\n\t\t\tTemporalMap(Sz(S),1) X;\t\n\t\t\tCluster(1, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t\tTemporalMap(Sz(R),1) Y;\n\t\t\tTemporalMap(Sz(S),1) X;\n\t\t\tTemporalMap(Sz(R),Sz(R)) R;\n\t\t\tTemporalMap(Sz(S),Sz(S)) S;\n\t\t}\n\t}\n\t\n\t// done with h parallel sd layers now\n\tLayer MH_FC_DimRecast_0 { //Batched FC layer, where seq_len is batch, input is d_model x 1\n\t\tType: CONV\n\t\tStride { X: 1, Y: 1 }\t// v,k,q have been combined\n\t\tDimensions { N: Seq_Len, K: 512, C: 1, R: 1, S: 512, Y:1, X:512 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(1,1) C;\n\t\t\tTemporalMap(Sz(R),Sz(R)) R;\n\t\t\tTemporalMap(Sz(S),Sz(S)) S;\n\t\t\tTemporalMap(Sz(R),1) Y;\n\t\t\tTemporalMap(Sz(S),1) X;\t\n\t\t\tCluster(1, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t\tTemporalMap(Sz(R),1) Y;\n\t\t\tTemporalMap(Sz(S),1) X;\n\t\t\tTemporalMap(Sz(R),Sz(R)) R;\n\t\t\tTemporalMap(Sz(S),Sz(S)) S;\n\t\t}\n\t} //good\n\n\t/// done with h parallel sd layers now\n\tLayer FF_A_0 { //Batched FC layer, where seq_len is batch, input is d_model x 1\n\t\tType: CONV //2048 output neurons, 512->2048\n\t\tStride { X: 1, Y: 1 }\t\n\t\tDimensions { N: Seq_Len, K: 2048, C: 1, R: 1, S: 512, Y:1, X:512 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(1,1) C;\n\t\t\tTemporalMap(Sz(R),Sz(R)) R;\n\t\t\tTemporalMap(Sz(S),Sz(S)) S;\n\t\t\tTemporalMap(Sz(R),1) Y;\n\t\t\tTemporalMap(Sz(S),1) X;\t\n\t\t\tCluster(1, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t\tTemporalMap(Sz(R),1) Y;\n\t\t\tTemporalMap(Sz(S),1) X;\n\t\t\tTemporalMap(Sz(R),Sz(R)) R;\n\t\t\tTemporalMap(Sz(S),Sz(S)) S;\n\t\t}\n\t} //good\n\n\t/// done with h parallel sd layers now\n\tLayer FF_B_0 { //Batched FC layer, where seq_len is batch, input is d_model x 1\n\t\tType: CONV //2048 -> 512\n\t\tStride { X: 1, Y: 1 }\t\n\t\tDimensions { N: Seq_Len, K: 512, C: 1, R: 1, S: 2048, Y:1, X:2048 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(1,1) C;\n\t\t\tTemporalMap(Sz(R),Sz(R)) R;\n\t\t\tTemporalMap(Sz(S),Sz(S)) S;\n\t\t\tTemporalMap(Sz(R),1) Y;\n\t\t\tTemporalMap(Sz(S),1) X;\t\n\t\t\tCluster(1, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t\tTemporalMap(Sz(R),1) Y;\n\t\t\tTemporalMap(Sz(S),1) X;\n\t\t\tTemporalMap(Sz(R),Sz(R)) R;\n\t\t\tTemporalMap(Sz(S),Sz(S)) S;\n\t\t}\n\t} //good\n\n\n}\n\n", "meta": {"author": "maestro-project", "repo": "maestro", "sha": "4eb08d17c87caf1ee3f3a351b10eb9b8ef70dd87", "save_path": "github-repos/MATLAB/maestro-project-maestro", "path": "github-repos/MATLAB/maestro-project-maestro/maestro-4eb08d17c87caf1ee3f3a351b10eb9b8ef70dd87/data/mapping/Transformer_Layers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5530513599254304}}
{"text": "function handWritingTest\n%%\nclc\nclear\nclose all\n%% \u83b7\u53d6\u76ee\u5f55\u4e0b\u7684\u6240\u6709txt\u6587\u4ef6\u540d\u79f0\nd = dir(['digits/trainingDigits/' '*.txt']); % struct \u7c7b\u578b\ndircell = struct2cell(d); %cell \u7c7b\u578b\ntrainSetLen = size(dircell,2);\nK = 4;\ndataSize = 1024;\ntrainLabels = zeros(trainSetLen,1);\ntrainSet = [];\nsimpleTrainSet = zeros(1,dataSize);\nsimpleTestSet = zeros(1,dataSize);\n\n%% \u52a0\u8f7d\u6570\u636e\nfprintf('loading data...')\nfor i = 1:trainSetLen\n    trainName =  dircell(1,i);\n    trainFilename = cell2mat(trainName);\n    trainLabels(i) = str2num(trainFilename(1));\n\n    fid = fopen(['digits/trainingDigits/' trainFilename],'r');\n    traindata = fscanf(fid,'%s');\n    for j = 1:dataSize\n        simpleTrainSet(j) =  str2num(traindata(j));\n    end\n    trainSet = [trainSet ; simpleTrainSet];\n    fclose(fid);\nend\n\nd = dir(['digits/testDigits/' '*.txt']); % struct \u7c7b\u578b\ndircell = struct2cell(d); %cell \u7c7b\u578b\ntestSetLen = size(dircell,2);\nerror = 0;\n%% \u6d4b\u8bd5\u6570\u636e\nfor k = 1:testSetLen\n    testName =  dircell(1,k);\n    testFilename = cell2mat(testName);\n    testLabels = str2num(testFilename(1));\n\n    fid = fopen(['digits/testDigits/' testFilename],'r');\n    testdata = fscanf(fid,'%s');\n    for j = 1:dataSize\n        simpleTestSet(j) =  str2num(testdata(j));\n    end\n    classifyResult = KNN(simpleTestSet,trainSet,trainLabels,K);\n    fprintf('\u8bc6\u522b\u6570\u5b57\u4e3a\uff1a%d  \u771f\u5b9e\u6570\u5b57\u4e3a\uff1a%d\\n' , [classifyResult , testLabels])\n    if(classifyResult~=testLabels)\n        error = error+1;\n    end\n    fclose(fid);\nend\n\nfprintf('\u8bc6\u522b\u51c6\u786e\u7387\u4e3a\uff1a%f\\n',1-error/testSetLen)\n\nend\n", "meta": {"author": "llp1992", "repo": "MachineLearning", "sha": "315c00285b758a7aee0c8a80db2d2f6dfbbe9aef", "save_path": "github-repos/MATLAB/llp1992-MachineLearning", "path": "github-repos/MATLAB/llp1992-MachineLearning/MachineLearning-315c00285b758a7aee0c8a80db2d2f6dfbbe9aef/KNN/handWritingTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5530298952925125}}
{"text": "%% Compose two vector fields\n%  Changed: Dec 31st, 2011\n%\nfunction [vx,vy,vz] = compose(ax,ay,az, bx,by,bz)\n\n    % Piggyback\n    piggybackscale = 1.2; % just to get too many outside values\n    [ax,lim] = piggyback(ax,piggybackscale);\n    [ay,lim] = piggyback(ay,piggybackscale);\n    [az,lim] = piggyback(az,piggybackscale);\n    [bx,lim] = piggyback(bx,piggybackscale);\n    [by,lim] = piggyback(by,piggybackscale);\n    [bz,lim] = piggyback(bz,piggybackscale);\n\n    % Coordinates\n    nx = size(ax,1);\n    ny = size(ax,2);\n    nz = size(ax,3);\n    \n    [y,x,z] = ndgrid(1:nx, 1:ny, 1:nz); % coordinate image\n\n    % Where points are going\n    xp  = iminterpolate(x+ax, bx,by,bz);\n    yp  = iminterpolate(y+ay, bx,by,bz);\n    zp  = iminterpolate(z+az, bx,by,bz);\n    \n    % Update field\n    vx = xp - x;\n    vy = yp - y;\n    vz = zp - z;\n    \n    % Zero vectors going outside the image\n    zr  = (xp==0 & yp==0 & zp==0);\n    vx(zr) = 0;\n    vy(zr) = 0;\n    vz(zr) = 0;\n\n    % Unpiggyback\n    vx = vx(lim(1):lim(2),lim(3):lim(4),lim(5):lim(6));\n    vy = vy(lim(1):lim(2),lim(3):lim(4),lim(5):lim(6));\n    vz = vz(lim(1):lim(2),lim(3):lim(4),lim(5):lim(6));\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/39194-diffeomorphic-log-demons-image-registration/demons/demons3d/compose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5530298904966895}}
{"text": "function fcnn = fcnnupdateweights(fcnn)\n%FCNNUPDATEWEIGHTS Update the weights of fully-connected neural net.\n%   FCNN = FCNUPDATEWEIGHTS(FCNN]) updates the weights of the\n%   fully-connected net, FCNN. The following code implements Step 4 in\n%   Table 14.9.\n%\n%   Type  \n%\n%    >> help fcninfo\n%\n%   at the prompt for detailed explanations of the components of the\n%   fully-connected neural net.\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% Number of layers.\nL = numel([fcnn.NumNodes]);\n\n% Learning rate constant.\nalpha = fcnn(L).Alpha;\n\n% Update the weights.\nfor k = 2:L\n   fcnn(k).Weights = fcnn(k).Weights - alpha*(fcnn(k).D)*(fcnn(k - 1).A');\n   fcnn(k).Biases = fcnn(k).Biases - alpha*sum(fcnn(k).D,2);  \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/fcnnFunctions/fcnnupdateweights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5530298904966894}}
{"text": "function k = exor ( i, j )\n\n%% EXOR calculates the exclusive OR of two integers.\n%\n%  Modified:\n%\n%    31 March 2003\n%\n%  Author:\n%\n%   John Burkardt\n%\n%  Reference:\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%  Parameters:\n%\n%    Input, integer I, J, two values whose exclusive OR is needed.\n%\n%    Output, integer K, the exclusive OR of I and J.\n%\n  k = 0;\n  l = 1;\n%\n  i = floor ( i );\n  j = floor ( j );\n\n  while ( i ~= 0 | j ~= 0 )\n%\n%  Check the current right-hand bits of I and J.\n%  If they differ, set the appropriate bit of K.\n%\n    i2 = floor ( i / 2 );\n    j2 = floor ( j / 2 );\n\n    if ( ...\n      ( ( i == 2 * i2 ) & ( j ~= 2 * j2 ) ) | ...\n      ( ( i ~= 2 * i2 ) & ( j == 2 * j2 ) ) )\n      k = k + l;\n    end\n\n    i = i2;\n    j = j2;\n    l = 2 * l;\n\n  end\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/Sobol/exor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5530298880403851}}
{"text": "% pop_newtimef() - Returns estimates and plots of event-related (log) spectral\n%           perturbation (ERSP) and inter-trial coherence (ITC) phenomena \n%           timelocked to a set of single-channel input epochs \n%\n% Usage:\n%   >> pop_newtimef(EEG, typeplot);          % pop_up window\n%   >> pop_newtimef(EEG, typeplot, lastcom); % pop_up window\n%   >> pop_newtimef(EEG, typeplot, channel); % do not pop-up window\n%   >> pop_newtimef(EEG, typeproc, num, tlimits,cycles,\n%                        'key1',value1,'key2',value2, ... );   \n%     \n% Graphical interface:\n%   \"Channel/component number\" - [edit box] this is the index of the data \n%              channel or the index of the component for which to plot the\n%              time-frequency decomposition.\n%   \"Sub-epoch time limits\" - [edit box] sub epochs may be extracted (note that\n%              this function aims at plotting data epochs not continuous data).\n%              You may select the new epoch limits in this edit box.\n%   \"Use n time points\" - [muliple choice list] this is the number of time\n%              points to use for the time-frequency decomposition. The more\n%              time points, the longer the time-frequency decomposition\n%              takes to compute.\n%   \"Frequency limits\" - [edit box] these are the lower and upper\n%              frequency limit of the time-frequency decomposition. Instead\n%              of limits, you may also enter a sequence of frequencies. For\n%              example to compute the time-frequency decomposition at all\n%              frequency between 5 and 50 hertz with 1 Hz increment, enter \"1:50\"\n%   \"Use limits, padding n\" - [muliple choice list] \"using limits\" means\n%              to use the upper and lower limits in \"Frequency limits\" with\n%              a specific padding ratio (padratio argument of newtimef).\n%              The last option \"use actual frequencies\" forces newtimef to\n%              ignore the padratio argument and use the vector of frequencies  \n%              given as input in the \"Frequency limits\" edit box.\n%   \"Log spaced\" - [checkbox] you may check this box to compute log-spaced\n%              frequencies. Note that this is only relevant if you specify\n%              frequency limits (in case you specify actual frequencies,\n%              this parameter is ignored).\n%   \"Use divisive baseline\" - [muliple choice list] there are two types of\n%              baseline correction, additive (the baseline is subtracted)\n%              or divisive (the data is divided by the baseline values).\n%              The choice is yours. There is also the option to perform \n%              baseline correction in single trials. See the 'trialbase' \"full\"\n%              option in the newtimef.m documentation for more information.\n%   \"No baseline\" - [checkbox] check this box to compute the raw time-frequency\n%              decomposition with no baseline removal.\n%   \"Wavelet cycles\" - [edit box] specify the number of cycle at the lowest \n%              and highest frequency. Instead of specifying the number of cycle \n%              at the highest frequency, you may also specify a wavelet\n%              \"factor\" (see newtimef help message). In addition, it is\n%              possible to specify actual wavelet cycles for each frequency\n%              by entering a sequence of numbers.\n%   \"Use FFT\" - [checkbox] check this checkbox to use FFT instead of\n%              wavelet decomposition.\n%   \"ERSP color limits\" - [edit box] set the upper and lower limit for the\n%              ERSP image. \n%   \"see log power\" - [checkbox] the log power values (in dB) are plotted. \n%              Uncheck this box to plot the absolute power values.\n%   \"ITC color limits\" - [edit box] set the upper and lower limit for the\n%              ITC image. \n%   \"plot ITC phase\" - [checkbox] check this box plot plot (overlayed on\n%              the ITC amplitude) the polarity of the ITC complex value.\n%   \"Bootstrap significance level\" - [edit box] use this edit box to enter\n%              the p-value threshold for masking both the ERSP and the ITC\n%              image for significance (masked values appear as light green)\n%   \"FDR correct\" - [checkbox] this correct the p-value for multiple comparisons\n%              (accross all time and frequencies) using the False Discovery\n%              Rate method. See the fdr.m function for more details.\n%   \"Optional newtimef arguments\" - [edit box] addition argument for the\n%              newtimef function may be entered here in the 'key', value\n%              format.\n%   \"Plot Event Related Spectral Power\" - [checkbox] plot the ERSP image\n%              showing event related spectral stimulus induced changes\n%   \"Plot Inter Trial Coherence\" - [checkbox] plot the ITC image.\n%   \"Plot Curve at each frequency\" - [checkbox] instead of plotting images,\n%              it is also possible to display curves at each frequency.\n%              This functionality is beta and might not work in all cases.\n% \n% Inputs:            \n%   INEEG    - input EEG dataset\n%   typeproc - type of processing: 1 process the raw channel data \n%                                  0 process the ICA component data\n%   num      - component or channel number\n%   tlimits  - [mintime maxtime] (ms) sub-epoch time limits to plot\n%   cycles   -  > 0 --> Number of cycles in each analysis wavelet \n%               = 0 --> Use FFTs (with constant window length \n%                       at all frequencies)\n%\n% Optional inputs:\n%    See the newtimef() function.\n%    \n% Outputs: Same as newtimef(); no outputs are returned when a\n%          window pops-up to ask for additional arguments\n%\n% Saving the ERSP and ITC output values:\n%    Simply look up the history using the eegh function (type eegh).\n%    Then copy and paste the pop_newtimef() command and add output args.\n%    See the newtimef() function for a list of outputs. For instance,\n% >> [ersp itc powbase times frequencies] = pop_newtimef( EEG, ....);\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 2001 \n%\n% See also: newtimef(), eeglab() \n\n% Copyright (C) 2002 University of California San Diego\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% 01-25-02 reformated help & license -ad \n% 03-08-02 add eeglab option & optimize variable sizes -ad\n% 03-10-02 change newtimef call -ad\n% 03-18-02 added title -ad & sm\n% 04-04-02 added outputs -ad & sm\n\nfunction varargout = pop_newtimef(EEG, typeproc, num, tlimits, cycles, varargin );\n\nvarargout{1} = '';\n% display help if not enough arguments\n% ------------------------------------\nif nargin < 2\n\thelp pop_newtimef;\n\treturn;\nend;\t\nlastcom = [];\nif nargin < 3\n\tpopup = 1;\nelse\n\tpopup = isstr(num) | isempty(num);\n\tif isstr(num)\n\t\tlastcom = num;\n\tend;\nend;\n\n% pop up window\n% -------------\nif popup\n\t[txt vars] = gethelpvar('newtimef.m');\n\t\n    g = [1 0.3 0.6 0.4];\n\tgeometry = { g g g g g g g g [0.975 1.27] [1] [1.2 1 1.2]};\n    uilist = { ...\n               { 'Style', 'text', 'string', fastif(typeproc, 'Channel number', 'Component number'), 'fontweight', 'bold'  } ...\n\t\t\t   { 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') 'tag' 'chan'} {} {} ...\n               ...\n\t\t\t   { 'Style', 'text', 'string', 'Sub epoch time limits [min max] (msec)', 'fontweight', 'bold' } ...\n\t\t\t   { 'Style', 'edit', 'string', getkeyval(lastcom,4,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) 'tag' 'tlimits' } ...\n               { 'Style', 'popupmenu', 'string', 'Use 50 time points|Use 100 time points|Use 150 time points|Use 200 time points|Use 300 time points|Use 400 time points' 'tag' 'ntimesout' 'value' 4} { } ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'Frequency limits [min max] (Hz) or sequence', 'fontweight', 'bold' } ...\n\t\t\t   { 'Style', 'edit', 'string', '' 'tag' 'freqs'  } ...\n               { 'Style', 'popupmenu', 'string', 'Use limits, padding 1|Use limits, padding 2|Use limits, padding 4|Use actual freqs.' 'tag' 'nfreqs' }  ...\n               { 'Style', 'checkbox', 'string' 'Log spaced' 'value' 0 'tag' 'freqscale' } ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'Baseline limits [min max] (msec) (0->pre-stim.)', 'fontweight', 'bold' } ...\n\t\t\t   { 'Style', 'edit', 'string', '0' 'tag' 'baseline' } ...\n\t\t\t   { 'Style', 'popupmenu',  'string', 'Use divisive baseline (DIV)|Use standard deviation (STD)|Use single trial DIV baseline|Use single trial STD baseline' 'tag' 'basenorm' } ...\n               { 'Style', 'checkbox', 'string' 'No baseline' 'tag' 'nobase' } ...\n               ...\n               { 'Style', 'text', 'string', 'Wavelet cycles [min max/fact] or sequence', 'fontweight', 'bold' } ...\n               { 'Style', 'edit', 'string', getkeyval(lastcom,5,[],'3 0.5') 'tag' 'cycle' } ...\n               { 'Style', 'checkbox', 'string' 'Use FFT' 'value' 0 'tag' 'fft' } ...\n               { } ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'ERSP color limits [max] (min=-max)', 'fontweight', 'bold' } ...\n               { 'Style', 'edit', 'string', '' 'tag' 'erspmax'} ...\n               { 'Style', 'checkbox', 'string' 'see log power (set)' 'tag' 'scale' 'value' 1} {} ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'ITC color limits [max]', 'fontweight', 'bold' } ...\n               { 'Style', 'edit', 'string', '' 'tag' 'itcmax'} ...\n               { 'Style', 'checkbox', 'string' 'plot ITC phase (set)' 'tag' 'plotphase' } {} ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold' } ...\n               { 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') 'tag' 'alpha'} ...\n               { 'Style', 'checkbox', 'string' 'FDR correct (set)' 'tag' 'fdr' } {} ...\n\t\t\t   ...\n\t\t\t   { 'Style', 'text', 'string', 'Optional newtimef() arguments (see Help)', 'fontweight', 'bold', ...\n\t\t\t\t 'tooltipstring', 'See newtimef() help via the Help button on the right...' } ...\n\t\t\t   { 'Style', 'edit', 'string', '' 'tag' 'options' } ...\n\t\t\t   {} ...\n\t\t\t   { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ...\n\t\t\t\t 'Plot Event Related Spectral Power', 'tooltipstring', ...\n\t\t\t\t 'Plot log spectral perturbation image in the upper panel' 'tag' 'plotersp' } ...\n\t\t\t   { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotitc','present',0), 'string', ...\n\t\t\t\t 'Plot Inter Trial Coherence', 'tooltipstring', ...\n\t\t\t\t 'Plot the inter-trial coherence image in the lower panel' 'tag' 'plotitc' } ...\n\t\t\t   { 'Style', 'checkbox', 'value', 0, 'string', ...\n\t\t\t\t 'Plot curve at each frequency' 'tag' 'plotcurve' } ...\n\t\t\t };\n      % { 'Style', 'edit', 'string', '''padratio'', 4, ''plotphase'', ''off''' } ...\n\t\t\t   %{ 'Style', 'text', 'string',  '[set] -> Plot ITC phase sign', 'fontweight', 'bold', ...\n\t\t\t%\t 'tooltipstring', ['Plot the sign (+/-) of inter-trial coherence phase' 10 ...\n\t\t\t%\t\t'as red (+) or blue (-)'] } ...\n\t\t\t%   { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',1) } { } ...\n\n\t[ tmp1 tmp2 strhalt result ] = inputgui( geometry, uilist, 'pophelp(''pop_newtimef'');', ...\n\t\t\t\t\t   fastif(typeproc, 'Plot channel time frequency -- pop_newtimef()', ...\n\t\t\t\t\t\t\t  'Plot component time frequency -- pop_newtimef()'));\n\tif length( tmp1 ) == 0 return; end;\n\n\tif result.fft,      result.cycle = '0'; end;\n\tif result.nobase,   result.baseline = 'NaN'; end;\n    \n\tnum\t     = eval( [ '[' result.chan    ']' ] ); \n\ttlimits\t = eval( [ '[' result.tlimits ']' ] ); \n\tcycles\t = eval( [ '[' result.cycle   ']' ] );\n    freqs    = eval( [ '[' result.freqs   ']' ] );\n    %result.ncycles == 2 is ignored\n    \n    % add topoplot\n    % ------------\n    options = [];\n    if isfield(EEG.chanlocs, 'theta') && ~isempty(EEG.chanlocs(num).theta)\n        if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end;\n        if typeproc == 1\n            if isempty(EEG.chanlocs), caption = [ 'Channel ' int2str(num) ]; else caption = EEG.chanlocs(num).labels; end;\n            options = [options ', ''topovec'', ' int2str(num) ...\n                        ', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''caption'', ''' caption '''' ];\n        else\n            options = [options ', ''topovec'', EEG.icawinv(:,' int2str(num) ...\n                       '), ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''caption'', [''IC ' num2str(num) ''']' ];\n      end;\n    end;\n    \n\tif ~isempty( result.baseline ),  options = [ options ', ''baseline'',[' result.baseline ']' ]; end;\n    if ~isempty( result.alpha ),     options = [ options ', ''alpha'',' result.alpha ];   end;\n\tif ~isempty( result.options ),   options = [ options ',' result.options ];            end;\n\tif ~isempty( result.freqs ),     options = [ options ', ''freqs'', [' result.freqs ']'   ]; end;\n\tif ~isempty( result.erspmax ),   options = [ options ', ''erspmax'', [' result.erspmax ']' ]; end;\n\tif ~isempty( result.itcmax ),    options = [ options ', ''itcmax'','  result.itcmax ];      end;\n\tif ~result.plotersp,             options = [ options ', ''plotersp'', ''off''' ];     end;\n\tif ~result.plotitc,              options = [ options ', ''plotitc'' , ''off''' ];     end;\n\tif result.plotcurve,             options = [ options ', ''plottype'', ''curve''' ];   end;\n\tif result.fdr,                   options = [ options ', ''mcorrect'', ''fdr''' ];     end;\n\tif result.freqscale,             options = [ options ', ''freqscale'', ''log''' ];    end;\n\tif ~result.plotphase,            options = [ options ', ''plotphase'', ''off''' ];    end;\n\tif ~result.scale,                options = [ options ', ''scale'', ''abs''' ];        end;\n    if result.ntimesout == 1,        options = [ options ', ''ntimesout'', 50' ];         end;\n    if result.ntimesout == 2,        options = [ options ', ''ntimesout'', 100' ];        end;\n    if result.ntimesout == 3,        options = [ options ', ''ntimesout'', 150' ];        end;\n    if result.ntimesout == 5,        options = [ options ', ''ntimesout'', 300' ];        end;\n    if result.ntimesout == 6,        options = [ options ', ''ntimesout'', 400' ];        end;\n    if result.nfreqs == 1,           options = [ options ', ''padratio'', 1' ];           end;    \n    if result.nfreqs == 2,           options = [ options ', ''padratio'', 2' ];           end;    \n    if result.nfreqs == 3,           options = [ options ', ''padratio'', 4' ];           end;\n    if result.nfreqs == 4,           options = [ options ', ''nfreqs'', ' int2str(length(freqs)) ]; end;\n    if result.basenorm == 2,         options = [ options ', ''basenorm'', ''on''' ];      end;\n    if result.basenorm == 4,         options = [ options ', ''basenorm'', ''on''' ];      end;\n    if result.basenorm >= 3,         options = [ options ', ''trialbase'', ''full''' ];      end;\n\n    % add title\n    % ---------\n\tif isempty( findstr(  '''title''', result.options))\n        if ~isempty(EEG.chanlocs) & typeproc\n            chanlabel = EEG.chanlocs(num).labels;\n        else\n            chanlabel = int2str(num);\n        end;\n\tend;\n    \n    % compute default winsize\n    % -----------------------\n    if EEG.xmin < 0 && isempty(findstr( '''winsize''', result.options)) && isempty( result.freqs )\n        fprintf('Computing window size in pop_newtimef based on half of the length of the baseline period');\n        options = [ options ', ''winsize'', ' int2str(-EEG.xmin*EEG.srate) ];\n    end;\n    \n\tfigure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;\nelse\n    options = [ ',' vararg2str(varargin) ];\nend;\n\n% compute epoch limits\n% --------------------\nif isempty(tlimits)\n\ttlimits = [EEG.xmin, EEG.xmax]*1000;\nend;\t\npointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1));\npointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts));\npointrange = [pointrange1:pointrange2];\n\n% call function sample either on raw data or ICA data\n% ---------------------------------------------------\nif typeproc == 1\n\ttmpsig = EEG.data(num,pointrange,:);\nelse\n\tif ~isempty( EEG.icasphere )\n        if ~isempty(EEG.icaact)\n    \t\ttmpsig = EEG.icaact(num,pointrange,:);\n \t    else\n            tmpsig = (EEG.icaweights(num,:)*EEG.icasphere)*reshape(EEG.data(:,pointrange,:), EEG.nbchan, EEG.trials*length(pointrange));\n        end;\n\telse\n\t\terror('You must run ICA first');\n\tend;\t\nend;\t \ntmpsig = reshape( tmpsig, length(num), size(tmpsig,2)*size(tmpsig,3));\n\n% outputs\n% -------\noutstr = '';\nif ~popup\n    for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;\n    if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;\nend;\n\n% plot the datas and generate output command\n% --------------------------------------------\nif length( options ) < 2\n    options = '';\nend;\nif nargin < 4\n    varargout{1} = sprintf('figure; pop_newtimef( %s, %d, %d, [%s], [%s] %s);', inputname(1), typeproc, num, ...\n\t\t\tint2str(tlimits), num2str(cycles), options);\nend;\ncom = sprintf('%s newtimef( tmpsig(:, :), length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options);\neval(com)\t    \n\nreturn;\n\n% get contextual help\n% -------------------\nfunction txt = context(var, allvars, alltext);\n\tloc = strmatch( var, allvars);\n\tif ~isempty(loc)\n\t\ttxt= alltext{loc(1)};\n\telse\n\t\tdisp([ 'warning: variable ''' var ''' not found']);\n\t\ttxt = '';\n\tend;\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/eeglab14_0_0b/functions/popfunc/pop_newtimef.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5530298832445621}}
{"text": "function varargout = log(varargin)\n\nswitch class(varargin{1})\n\n    case 'sdpvar'\n         % Try to detect logsumexp construction etc\n        varargout{1} = check_for_special_cases(varargin{:});\n        % Nope, then just define this logarithm\n        if isempty(varargout{1})\n            varargout{1} = InstantiateElementWise(mfilename,varargin{:});\n        end\n        \n    case 'char'\n                    \n        operator = CreateBasicOperator('concave','increasing','callback');                             \n        operator.derivative = @(x)(1./(abs(x)+eps));\n        operator.inverse = @(x)(exp(x));\n        operator.domain = [0 inf];\n        operator.singularity = [0 -inf -inf] ;\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 f = check_for_special_cases(x)\nf = [];\n% Check for log(1+x)\nbase = getbase(x);\nif all(base(:,1)==1)\n    f = slog(x-1);\n    return;\nend\n% Check if user is constructing log(sum(exp(x)))\nif base(1)~=0\n    return\nend\nif ~all(base(2:end)==1)\n    return\nend\nmodelst = yalmip('extstruct',getvariables(x));\nif isempty(modelst)\n    return;\nend\nif length(modelst)==1\n    models{1} = modelst;\nelse\n    models = modelst;\nend\n% LOG(DET(X))\nif length(models)==1\n    if strcmp(models{1}.fcn,'det_internal')\n        n = length(models{1}.arg{1});\n        try\n            f = logdet(reshape(models{1}.arg{1},sqrt(n),sqrt(n)));\n        catch\n        end\n        return\n    end\nend\n% LOG(EXP(x1)+...+EXP(xn))\nfor i = 1:length(models)\n    if ~strcmp(models{i}.fcn,'exp')        \n        return\n    end      \nend\np = [];\nfor i = 1:length(models)\n    p = [p;models{i}.arg{1}];\nend\nf = logsumexp(p);\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/log.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5530256875947127}}
{"text": "% LINESEG - Form straight line segements from an edge list.\n%\n% Usage: [seglist, nedgelist] = lineseg(edgelist, tol, angtol, linkrad)\n%\n% Arguments:  edgelist - Cell array of edgelists (row col) coords.\n%             tol      - Maximum deviation from straight line before a\n%                        segment is broken in two (measured in pixels).\n%             angtol   - Angle tolerance used when attempting to merge line\n%                        segements (radians).\n%             linkrad  - Maximum distance between end points of line\n%                        segments for segments to be elegible for\n%                        linking (pixels).\n%  angtol and linkrad are optional.  If these parameters are omitted the\n%  merging phase is omitted.\n%\n% Returns:  seglist - an Nx4 array storing line segments in the form\n%                      [x1 y1 x2 y2\n%                       x1 y1 x2 y2\n%                          . . .    ] etc \n%\n%         nedgelist - a new cell array of edge lists where each edge list\n%                     corresponds to each segment in seglist above.  The\n%                     edgelist is in row,column coords in the form\n%                     { [r1 c1   [r1 c1   etc }\n%                        r2 c2    ...\n%                        ...\n%                        rN cN]   ....]\n%\n% * Note that a non-empty nedgelist is only returned if there is no segment\n%   merging. \n%\n% This function takes each array of edgepoints in edgelist, finds the\n% size and position of the maximum deviation from the line that joins the\n% endpoints, if the maximum deviation exceeds the allowable tolerance the\n% edge is shortened to the point of maximum deviation and the test is\n% repeated.  In this manner each edge is broken down to line segments,\n% each of which adhere to the original data with the specified tolerance.\n%\n% The optional final edge merging phase is provided because the initial\n% edge linking phase may have separated edges at `Y' junctions in the\n% image.  The merging phase can reconnect broken branches.\n% Note however that the merging process can be slow.\n%\n% See also:  EDGELINK, MAXLINEDEV, MERGESEG, DRAWSEG\n%\n\n% Copyright (c) 2000-2005 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% December 2000 - Original version\n% February 2003 - Added the returning of nedgelist data.\n\n% ** need to preallocate memory to improve speed ***\n\nfunction [linelist, nedgelist] = lineseg(edgelist, tol, angtol, linkrad)\n    \n    linelist = [];\n    Nline = 0;\n    Nedge = length(edgelist);\n    \n    if nargin == 2\n\tmerge = 0;\n    else\n\tmerge = 1;\n    end\n    \n    for e = 1:Nedge\n        y = edgelist{e}(:,1);\n\tx = edgelist{e}(:,2);\n\n\tfst = 1;                % Indecies of first and last points in edge\n\tlst = length(x);        % segment being considered.\n\t\n\twhile  fst<lst\n\t    [m,i,d] = maxlinedev(x(fst:lst),y(fst:lst));  % Find size & posn of\n                                                          % maximum deviation.\n\t    \n\t    while m > tol       % While deviation is > tol  (m/d) ?\n\t\tlst = i+fst-1;  % Shorten line to point of max deviation by adjusting lst\n\t\t[m,i,d] = maxlinedev(x(fst:lst),y(fst:lst));\n\t    end\n\t    \n\t    Nline = Nline+1;\n            % Record line segment. Note that (c,r) corresponds to (x,y)\n\t    linelist(Nline,:) = [x(fst) y(fst) x(lst) y(lst)]; \n\t    % Record edgelist that corresponds to the segment.\n\t    nedgelist{Nline} = [y(fst:lst) x(fst:lst)];\n\t               \n%\t    fst = lst+1;        % Reset fst and lst.\n\t    fst = lst;        % make new fst match last lst so that segments\n                              % share endpoints.\n\t    lst = length(x);\n\tend\n\t\n    end\n    % fprintf('No of segments = %d\\n',length(linelist)); \n    % drawseg(linelist,1), title('Raw segments');\n    \n    if merge\n%\tfprintf('\\nMerging Segments\\n');\n\tlinelist = mergeseg(linelist, angtol, linkrad, tol);\n\tnedgelist = {};\n%\tfprintf('No of merged segments = %d\\n',length(linelist));\n        % drawseg(linelist,2), title('Merged segments');\n    end\n    \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/lineseg/pkline/lineseg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5530256875947127}}
{"text": "function varargout = tanh(varargin)\n%TANH   Hyperbolic tangent of a CHEBFUN2.\n%\n%   TANH(F) returns the hyperbolic tangent of a CHEBFUN2.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n[varargout{1:nargout}] = tanh@separableApprox(varargin{:});\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/tanh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5530256656048322}}
{"text": "function [u,p] = StokesLSCDGS(u,p,f,g,A,B,auxMat,elem,smootherOpt,Ai,Si,SSi,Res,Pro)\n%% STOKESLSCDGSTRI Matrix-vecotr form DGS relaxation for Stokes eqns\n%\n%************************** Algorithm Description *************************\n% \n%  In matrix form, we need to solve the equations\n%\n%         Lx =  |A B' | |u| = |f|\n%               |B -D | |p| = |0|\n%  Distributive matrix will be given by\n%\n%         M = |I            B'|\n%             |0 -inv(BB')BAB'|,\n%\n%  Therefore, the transformed matrix T will be\n%\n%         T = L*M = |A  PAB'               |    with P = I-B'inv(BB')B\n%                   |B  BB'+D*inv(BB')BAB' |\n%\n%         tildeT = |Su   0|    with Su and Sp smoother for A and BB'.\n%                  |B   Sp|\n%\n%  The matrix form DGS update can be written as\n%\n%    |uk+1|   |uk|                 |ru|     with ru = f-Auk -B'pk,\n%    |    | = |  | + M*inv(tildeT)*|  |\n%    |pk+1|   |pk|                 |rp|     and  rp = 0-Buk\n%\n%********************** End-of- Algorithm Description *********************\n%\n%  Created by Ming Wang (with discussion with Long Chen) at Jan, 2012.\n\n%% Set up of smoothers\nsmoothingstep = smootherOpt.smoothingstep;\nsmootherSp = upper(smootherOpt.smootherSp);\nsmootherbarSp = upper(smootherOpt.smootherbarSp);\nif isfield(smootherOpt,'smootherbarSpPara')\n    smootherbarSpPara = smootherOpt.smootherbarSpPara;\nelse\n    smootherbarSpPara = 1;\nend\nif strcmp(smootherbarSp,'VCYCLE') || strcmp(smootherSp,'VCYCLE')\n    % mg Parameters for barSp\n    optionmg.solvermaxit = 1;\n%     optionmg.tol = 0.1;\n    optionmg.solver = 'VCYCLE'; \n    optionmg.smoothingstep = 2;\n    optionmg.printlevel=0; \n    optionmg.setupflag = 0;\nend\n\n%% initialize smoother \nBt = auxMat.Bt;\nBBt = auxMat.BBt;\nBABt = auxMat.BABt;\nSu = auxMat.Su;\nSp = auxMat.Sp;\nSpt = auxMat.Spt;\nDSp = auxMat.DSp; \n\n%% DGS relaxation step\nfor k = 1: smoothingstep\n    % Step 1: relax Momentum eqns\n    u = u + Su\\(f-Bt*p-A*u);\n    % Step 2: relax transformed Continuity eqns\n    rp = g - B*u;\n    switch(smootherSp)\n        case 'SGS'\n            dq = Spt\\(DSp.*(Sp\\rp)); % symmetric Gauss-Seidel iteration\n        case 'GS'\n            dq = Sp\\rp; % Gauss-Seidel iteration\n        case 'VCYCLE'\n            if exist('elem','var')\n                dq = mg(BBt,rp,elem,optionmg,Ai,Si,SSi,Res,Pro); % mg vcycle\n            else\n                dq = amg(BBt,rp,optionmg); % mg vcycle\n            end\n    end\n    % Step 3: transform the correction back to the original variables\n    %   Step 3.1: velocity\n    u = u + Bt*dq;\n    %   Step 3.2: pressure\n    dq = BABt*dq;\n%     dq = dq - mean(dq);\n    switch(smootherbarSp)\n        case 'GS'\n            dp = Spt\\dq;\n        case 'SGS'\n            dp = Sp\\(DSp.*(Spt\\dq));\n%             dp = dp + Sp\\(DSp.*(Spt\\(dq - BBt*dp)));\n        case 'VCYCLE'\n%            dp = BBt\\dq;\n            if exist('elem','var')\n%                 dq =dq-mean(dq);\n                dp = mg(BBt,dq,elem,optionmg,Ai,Si,SSi,Res,Pro); % mg vcycle;\n            else\n                dp = amg(BBt,dq,optionmg);\n            end\n    end\n    p = p - smootherbarSpPara*dp; \n    \nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/solver/StokesLSCDGS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5530256656048322}}
{"text": "% Function to compute the gradient of the given optical flow\n%\n%    Copyright (C) 2013  Anestis Papazoglou\n%\n%    You can redistribute and/or modify this software for non-commercial use\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%    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 <http://www.gnu.org/licenses/>.\n%\n%    For commercial use, contact the author for licensing options.\n%\n%    Contact: a.papazoglou@sms.ed.ac.uk\n\nfunction result = getFlowGradient( flow )\n\n    if( iscell( flow ) )\n        framesNumber = length( flow );\n    \n        gradients = cell( 1, framesNumber );\n        for( i = 1: framesNumber )\n            grad( :, :, 1 ) = gradient( single( flow{ i }( :, :, 1 ) ) );\n            [ ~, grad( :, :, 2 ) ] = ...\n                gradient( single( flow{ i }( :, :, 2 ) ) );\n        \n            gradients{ i } = grad;\n        end\n        result = gradients;\n    else\n        [ height, width, ~ ] = size( flow );\n        grad = zeros( height, width, 2, 'single' );\n        if( ~isfloat( flow ) )\n            flow = single( flow );\n        end\n        \n        grad( :, :, 1 ) = gradient( flow( :, :, 1 ) );\n        [ ~, grad( :, :, 2 ) ] = gradient( flow( :, :, 2 ) );\n        \n        result = grad;\n    end\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u5272\u7b97\u6cd5/Saliency-Aware-Video-Object-Segmentation-old--master/code/subCode/getFlowGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5530256546098917}}
{"text": "function view = plotResidualError(view,scan,baseFrame)\n%\n% view = plotResidualError(view,scan,[baseFrame])\n%\n% Plots the rmse between each frame and a baseFrame\n%\n% If you change this function make parallel changes in:\n%   plotMaxTSErr\n%\n% djh, 2/2001. rmse instead of var, conver to 3.0\n\nif ~exist('scan','var')\n   scan = getCurScan(view);\nend\nif ~exist('baseFrame','var')\n   baseFrame=1;\n   %baseFrame=nFrames;\nend\n\nslices = sliceList(view,scan);\nnSlices = length(slices);\nnFrames = numFrames(view,scan);\n\n% Load tSerises and compute RMSE slice by slice\nwaitHandle = mrvWaitbar(0,'Loading tSeries and computing RMSE.  Please wait...');\nvres = zeros(nSlices,nFrames);\nfor slice=slices\n   mrvWaitbar(slice/nSlices);\n   tSeries = loadtSeries(view,scan,slice);\n   for frame=1:nFrames\n      vres(slice,frame) = sqrt(mse(tSeries(frame,:),tSeries(baseFrame,:)));\n   end\nend\nclose(waitHandle)\n\n% mean across slices\nvres = mean(vres);\n\n% dont plot anything for the base frame (otherwise it would be 0)\nvres(baseFrame)=NaN;\n\n% plot it\nselectGraphWin;\nfontSize = 14;\nset(gcf,'Name',['RMSE, scan: ',num2str(scan),', baseframe:',int2str(baseFrame)]);\nx = 1:nFrames;\nplot(x,vres,'-b','LineWidth',2)\nset(gca,'FontSize',fontSize)\nset(gca,'XLim',[0,nFrames]);\nxlabel('Frame number','FontSize',fontSize) \nylabel('RMSE (raw intensity units)','FontSize',fontSize) \n\n% Save the data in gca('UserData')\ndata.frameNumbers = x;\ndata.tSeries  =  vres;\nset(gca,'UserData',data);\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/Plots/plotResidualError.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5529712224064046}}
{"text": "%implementation of the TVE SLM model by Martha Banbura and Andries van Vlodrop (2017) \n%by Ben Schumann (2020)\n\nfunction [Ys, Yt, Y, data_endo, const, priorValues, dataValues, sizetraining]=...\n    TVESLM_prior(data_endo, data_exo, names, endo, lags, lambda1, lambda2, lambda3, lambda5, ar, bex, dataSLM, namesSLM, datesSLM, const, priorexo, gamma)\n%input n, data_endo, data_exo lags, q, lambda1, lambda2, lambda3, lambda5,ar bex,dataSLM, namesSLM, datesSLM, endo, names,n\n%output ys, data_endo, Yt, const, priorValues,dataValues. data.values\n\n%% Preliminaries\np=lags;\nT = size(data_endo,1);\nn = size(data_endo,2);\n% compute m, the number of exogenous variables in the model\n% if data_exo is empty, set m=0\nif isempty(data_exo)==1\nm=0;\n% if data_exo is not empty, count the number of exogenous variables that will be included in the model\nelse\nm=size(data_exo,2);\n% Also, trim a number initial rows equal to the number of lags, as they will be suppressed from the endogenous as well to create initial conditions\ndata_exo=data_exo(p+1:end,:);\nend\n\nif const ==1\n    m=m-1;\n    const=0; %no constant as the VAR is estimated on the local mean adjusted variables\nend \n\n% determine k, the number of parameters to estimate in each equation; it is equal to np+m\nk=n*p+m;\n% determine q, the total number of VAR parameters to estimate; it is equal to n*k\nq=n*k;\n%Divide the sample into a training sample and an estimation sample\nsizetraining = floor(size(data_endo,1)/5) + lags;\nYt = data_endo(1:sizetraining,:);           %training sample\ndataValues.Yt = Yt;                         %training sample\n\nY = data_endo((sizetraining-lags)+1:end,:); %estimation sample\ndataValues.Y = Y;                           %estimation sample\n\ndataValues.data_endo_full = data_endo;\ndata_endo = data_endo((sizetraining-lags)+1:end,:);\n\n%Determine for which variables there is a survey local mean and build selection matrix\n\nHaveSLM = ismember(endo,namesSLM)'; %first establish for which variables we have survey local mean data\nns = sum(HaveSLM);                  %check how many endogenous variables have a survey local mean\nYs = nan(size(Y,1),ns);\nni = 0;\nPpsi = zeros(ns,n);                 %create selection matrix for measurement equation\n% for kk = 1:n\n%     if HaveSLM(1,kk) ==1\n%         ni = ni+1;\n%         Ys(:,kk) = dataSLM(sizetraining-lags+1:end,kk);\n%         Ppsi(ni,kk) = 1;            %selection matrix for local mean measurement equation\n%     end\n% end\nfor kk = 1:n\n    if ismember(endo{kk,1},namesSLM)\n        %find entry in ismember\n        IndexC= find(strcmp(namesSLM, endo{kk,1}));\n        ni = ni+1;\n        Ys(:,IndexC) = dataSLM(sizetraining-lags+1:end,IndexC);\n        Ppsi(IndexC,kk) = 1;            %selection matrix for local mean measurement equation\n    end\nend\n\ndataValues.Ppsi = Ppsi;\n\ndataValues.Ys = Ys;                 %Survey local mean after training sample\n\n%%%%%%%%%%%%%%%%%% set the prior values%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% prior for stochastic volatility in VAR residuals priors (H = A^-1'*Lambda_t*A^-1')\n%estimate an ar(p) process for setting the prior variances\n[arvar]=bear.arloop(Yt,1,lags,n);\narvar = arvar*((size(Yt,1)-lags-lags-1)/(size(Yt,1)-lags-1)); %translate bear into Banbura et al (2017) estimate of ar(4) VCV\n\npriorValues.priorVarAscaling_H =10;  %prior variance for the below diagonal elements of A (constant part of VCV\npriorValues.priorMeanAscaling_H=0;   %prior mean for the below diagonal elements of A\n\npriorValues.mean_ln_h0=log(arvar);    %prior mean of the initial condition for stochastic volatilty VAR residuals\npriorValues.var_ln_h0 = 10*ones(n,1); %prior variance for the inital condition  for stochastic volatilty VAR residuals\n\npriorValues.phi_h=0.01;               %centering parameter for the variance of the stochastic volatility process in the VAR residuals\npriorValues.d_h=10;                   %scaling parameter for the variance of the stochastic volatility process in the VAR residuals\n\npriorValues.offset_c = 0.001;         %constant for log transformation in order to avoid numerical problems of log close to 0\n\n\n%% Priors for Reduced form VAR coefficients (independent normal wishart)\npriorValues.vars  =arvar; \n%for bear sampling\npriorValues.lambda1=lambda1;        % overall tightness\npriorValues.lambda2=lambda2;        % cross variable shrinkage\npriorValues.lambda3=lambda3;        % lag shrinkage\npriorValues.lambda5=lambda5;        % block exogeneity shrinkage\npriorValues.ar = ar;                % prior values for ar(1) coefficients of the variable\n\n%for banbura et al sampling\npriorValues.lambda=lambda1^2;       % only used for banbura large model sampling\npriorValues.theta=lambda3;          % only used for banbura large model sampling\n\nif size(ar,1) < n              % if no variable specific priors were given \n    artemp=zeros(n,1);\n    for kk=1:n\n        artemp(kk,1)=ar;\n    end \n    ar = artemp;\nend \n\n% start with beta0, defined in (1.3.4)\n% it is a q*1 vector of zeros, save for the n coefficients of each variable on their own first lag \nbeta0=zeros(q,1);\n\nfor ii=1:n\nbeta0((ii-1)*k+ii,1)=ar(ii,1);\nend\n\n\n% if a prior for the exogenous variables is selected put it in here:\nfor ii=1:n\n    beta0(k*ii)=priorexo(ii,1);\nend\n\n% next compute omega0, the variance-covariance matrix of beta, defined in (1.3.8)\n% set it first as a q*q matrix of zeros\nomega0=zeros(q,q);\n\n% set the variance on coefficients related to own lags, using (1.3.5)\nfor ii=1:n\n   for jj=1:p\n   omega0((ii-1)*k+(jj-1)*n+ii,(ii-1)*k+(jj-1)*n+ii)=(lambda1/jj^lambda3)^2;\n   end\nend\n\n\n%  set variance for coefficients on cross lags, using (1.3.6)\nfor ii=1:n\n   for jj=1:p\n      for kk=1:n\n      if kk==ii\n      else\n      omega0((ii-1)*k+(jj-1)*n+kk,(ii-1)*k+(jj-1)*n+kk)=(arvar(ii,1)/arvar(kk,1))*(((lambda1*lambda2)/(jj^lambda3))^2);\n      end\n      end\n   end\nend\n\n\n% finally set the variance for exogenous variables, using (1.3.7)\nfor ii=1:n \n   for jj=1:m\n   omega0(ii*k-m+jj,ii*k-m+jj)=arvar(ii,1)*((lambda1*lambda4)^2);\n   end\nend\n\n\n% if block exogeneity has been selected, implement it, according to (1.7.4)\nif bex==1\n   for ii=1:n\n      for jj=1:n\n         if blockexo(ii,jj)==1\n            for kk=1:p\n            omega0((jj-1)*k+(kk-1)*n+ii,(jj-1)*k+(kk-1)*n+ii)=omega0((jj-1)*k+(kk-1)*n+ii,(jj-1)*k+(kk-1)*n+ii)*lambda5^2;\n            end\n         else\n         end\n      end\n   end\n% if block exogeneity has not been selected, don't do anything \nelse\nend\n\npriorValues.beta0=beta0;        %prior for the reduced form VAR coefficients in vectorized form\npriorValues.omega0=omega0;       %prior variance for reduced form VAR coefficients \n\n%% Priors for the measurement equation (G)\n\npriorValues.mean_ln_g0=zeros(ns,1); %mean of the initial condition in the variance of measurement equation residuals\npriorValues.var_ln_g0 = 10*ones(ns,1); %variance of the initial condition in the variance of measurement equation residuals\n\npriorValues.phi_g=0.01;    %centering parameter for the variance of measurement equation residuals\npriorValues.d_g=10;        %scaling parameter for the variance of the stochastic volatility process in the VAR residuals\n\n%% Priors for the local mean equation\npriorValues.meanTS=mean(Yt)';          %start values for mean corrected Kalman smoother simulation in order to draw from the local mean process\npriorValues.kappa = 1000;              %variance of the initial state for the local mean\n\npriorValues.gamma = gamma;             %value for ar coefficient in \n\npriorValues.mean_ln_v0=log(arvar);     %prior mean of the initial condition for stochastic volatilty in the state transition equation\npriorValues.var_ln_v0 = 10*ones(n,1);  %prior variance of the initial condition for stochastic volatilty in the state transition equation\n\npriorValues.d_v=10;                    %scaling parameter for the variance of the stochastic volatility process in the VAR residuals\npriorValues.phi_v=0.01;                %centering parameter for the variance of transition equation residuals\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/TVESLM_prior.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5529712112380902}}
{"text": "function [Y X Z n m p T k1 k3 q1 q2 q3]=maprelim(data_endo,data_exo,const,lags,regimeperiods,names)\n\n\n\n% function [Y X Z n m p T k1 k3 q1 q2 q3]=maprelim(data_endo,data_exo,const,lags)\n% creates the preliminary values necessary for all the subsequent computations\n% inputs:  - matrix 'data_endo': the matrix storing the endogenous time series data used to estimate the model\n%          - matrix 'data_exo': the matrix storing the exogenous time series data used to estimate the model\n%          - integer 'const': 0-1 value determining whether a constant term should be included in the model\n%          - integer 'lags': the number of lags to include in the model\n% outputs: - matrix 'Y': the matrix of endogenous variables, defined in (3.5.10)\n%          - matrix 'X': the matrix of endogenous regressors, defined in (3.5.10)\n%          - matrix 'Z': the matrix of exogenous regressors, defined in (3.5.10)\n%          - integer 'n': the number of endogenous variables in the model\n%          - integer 'm': the number of exogenous variables in the model\n%          - integer 'p': the number of lags in the model\n%          - integer 'T': the sample size, i.e. the number of time periods used to estimate the model\n%          - integer 'k1': the number of coefficients related to the endogenous variables for each equation in the model\n%          - integer 'k3': the number of coefficients related to the exogenous variables for each equation, in the reformulated model (3.5.5)\n%          - integer 'q1': the total number of VAR coefficients related to the endogenous variables\n%          - integer 'q2': the total number of VAR coefficients related to the exogenous variables\n%          - integer 'q3': the total number of VAR coefficients related to the exogenous variables, in the reformulated model (3.5.5)\n\n\n\n% first compute p, the number of lags in the model, defined p77\np=lags;\n\n% then compute n, the number of endogenous variables in the model; it is simply the number of columns in the matrix 'data_endo'\nn=size(data_endo,2);\n\n\n% augment the matrix of exogenous with a column of ones to account for the constant\n%data_exo=[ones(size(data_endo,1),1) data_exo];\n%alternative data exo\n\nif isempty(regimeperiods);\n    data_exo=[ones(size(data_endo,1),1)];\nelse\ndata_exo=[ones(size(data_endo,1),1) zeros(size(data_endo,1),1)];\ndata_exo(find(strcmp(names(2:end,1),regimeperiods(1))):find(strcmp(names(2:end,1),regimeperiods(2))),2)=1;\ndata_exo(find(strcmp(names(2:end,1),regimeperiods(1))):find(strcmp(names(2:end,1),regimeperiods(2))),1)=0;\nend\n\nif isempty(regimeperiods);\n    data_exo=[ones(size(data_endo,1),1)];\nelse\ndata_exo=[ones(size(data_endo,1),1) zeros(size(data_endo,1),1)];\ndata_exo(find(strcmp(names(2:end,1),regimeperiods(1))):find(strcmp(names(2:end,1),regimeperiods(2))),2)=1;\nend\n% then compute m, the number of exogenous variables in the model, defined p77\n% if data_exo is empty, set m=0\nm=size(data_exo,2);\n\n% estimate k1, the number of parameters related to endogenous variables in each equation, defined p77\nk1=n*p;\n\n% estimate q1, the total number of parameters related to endogenous variables, defined p77\nq1=n*k1;\n\n% estimate q2, the total number of parameters related to exogenous variables, defined p77\nq2=n*m;\n\n% estimate k3, the number of parameters related to exogenous variables in each equation of the modified system, defined p78\nk3=m*(p+1);\n\n% estimate q3, the total number of parameters related to endogenous variables in the modified system, defined p78\nq3=n*k3;\n\n% obtain the matrices Y and X, defined in (3.6.10)\n% to do so, use the lagx function on the data matrix\ntemp=bear.lagx(data_endo,lags);\n\n% to build X, take off the n initial columns of current data\nX=temp(:,n+1:end);\n\n% save the n first columns of temp as Y\nY=temp(:,1:n);\n\n% obtain the matrix Z, defined in (3.6.10)\ntemp=bear.lagx(data_exo,lags);\ntemp(:,m+1:end)=-temp(:,m+1:end);\nZ=temp;\n\n\n% Define T, the number of periods of the model, as the number of rows of Y\nT=size(Y,1);\n\n% obtain eventually y, Xbar and Zbar, as defined in (XXX)\ny=Y(:);\nXbar=kron(eye(n),X);\nZbar=kron(eye(n),Z);\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/unreachableCode_ToRemove/maprelim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5529711946129799}}
{"text": "function S = HALMSinit(w0,mu,fb,ff,delay)\n\n% HALMSinit     Initialize Parameter Structure of the LMS Algorithm\n%               for Hearing Aids. Refer to Fig. 1.9 \n%\n% Arguments:\n% w0            Coefficients of FIR filter at start (@n=1)\n% mu            Step size for LMS algorithm \n% ff            Feedforward path\n% fb            Feedback path\n% delay         Delay to adaptive filter\n%\n% by Lee, Gan, and Kuo, 2008\n% Subband Adaptive Filtering: Theory and Implementation\n% Publisher: John Wiley and Sons, Ltd\n\n\n% Assign structure fields\n\nS.coeffs     = w0(:);       % Weight (column) vector of FIR filter \nS.step       = mu;          % Step size of the LMS algorithm\nS.iter       = 0;           % Iteration count\nS.ff         = ff;          % Feedforward path\nS.fb         = fb;          % Feedback path\nS.delay      = delay;       % Delay \nS.AdaptStart = length(w0);  % Running effect of adaptive filter\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/Common Code/HALMSinit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5529711943582566}}
{"text": "function gX = mlpKernGradX(kern, X, X2)\n\n% MLPKERNGRADX Gradient of MLP kernel with respect to input locations.\n% FORMAT\n% DESC computes the gradident of the multi-layer perceptron\n% kernel with respect to the input positions where both the row\n% positions and column positions are provided separately.\n% ARG kern : kernel structure for which gradients are being\n% computed.\n% ARG x1 : row locations against which gradients are being computed.\n% ARG x2 : column locations against which gradients are being computed.\n% RETURN g : the returned gradients. The gradients are returned in\n% a matrix which is numData2 x numInputs x numData1. Where numData1 is\n% the number of data points in X1, numData2 is the number of data\n% points in X2 and numInputs is the number of input\n% dimensions in X.\n%\n% SEEALSO mlpKernParamInit, kernGradX, mlpKernDiagGradX\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006, 2009\n\n% KERN\n\n\ngX = zeros(size(X2, 1), size(X2, 2), size(X, 1));\nfor i = 1:size(X, 1);\n  gX(:, :, i) = mlpKernGradXpoint(kern, X(i, :), X2);\nend\n  \n\nfunction gX = mlpKernGradXpoint(kern, x, X2)\n\n% MLPKERNGRADXPOINT Gradient with respect to one point of x.\n\ninnerProd = X2*x';  \nnumer = innerProd*kern.weightVariance + kern.biasVariance;\nvec1 = sum(x.*x, 2)*kern.weightVariance + kern.biasVariance + 1;\nvec2 = sum(X2.*X2, 2)*kern.weightVariance + kern.biasVariance + 1;\ndenom = sqrt(vec2*vec1');\narg = numer./denom;\ngX = zeros(size(X2));\ntwooverpi = 2/pi;\nfor j = 1:size(X2, 2)\n  gX(:, j)=X2(:, j)./denom - vec2.*x(:, j).*numer./denom.^3;\n  gX(:, j) = twooverpi*kern.weightVariance*kern.variance*gX(:, j)./sqrt(1-arg.*arg);\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/mlpKernGradX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5529711886467373}}
{"text": "classdef VariationalRefinement < handle\n    %VARIATIONALREFINEMENT  Variational optical flow refinement\n    %\n    % This class implements variational refinement of the input flow field,\n    % i.e. it uses input flow to initialize the minimization of the following\n    % functional:\n    %\n    %     E(U) = integral_{Omega}(delta * Psi(E_I) + gamma * Psi(E_G) + alpha * Psi(E_S))\n    %\n    % where `E_I`, `E_G`, `E_S` are color constancy, gradient constancy and\n    % smoothness terms respectively. `Psi(s^2) = sqrt(s^2 + epsilon^2)` is a\n    % robust penalizer to limit the influence of outliers. A complete\n    % formulation and a description of the minimization procedure can be found\n    % in [Brox2004].\n    %\n    % ## References\n    % [Brox2004]:\n    % > Thomas Brox, Andres Bruhn, Nils Papenberg, and Joachim Weickert.\n    % > \"High accuracy optical flow estimation based on a theory for warping\".\n    % > In Computer Vision-ECCV 2004, pages 25-36. Springer, 2004.\n    %\n    % See also: cv.VariationalRefinement.calc\n    %\n\n    properties (SetAccess = private)\n        % Object ID\n        id\n    end\n\n    properties (Dependent)\n        % Number of outer (fixed-point) iterations in the minimization\n        % procedure. default 5\n        FixedPointIterations\n        % Number of inner successive over-relaxation (SOR) iterations in the\n        % minimization procedure to solve the respective linear system.\n        % default 5\n        SorIterations\n        % Relaxation factor in SOR. default 1.6\n        Omega\n        % Weight of the smoothness term. default 20.0\n        Alpha\n        % Weight of the color constancy term. default 5.0\n        Delta\n        % Weight of the gradient constancy term. default 10.0\n        Gamma\n    end\n\n    %% Constructor/destructor\n    methods\n        function this = VariationalRefinement()\n            %VARIATIONALREFINEMENT  Creates an instance of VariationalRefinement\n            %\n            %     obj = cv.VariationalRefinement()\n            %\n            % See also: cv.VariationalRefinement.calc\n            %\n            this.id = VariationalRefinement_(0, 'new');\n        end\n\n        function delete(this)\n            %DELETE  Destructor\n            %\n            %     obj.delete()\n            %\n            % See also: cv.VariationalRefinement\n            %\n            if isempty(this.id), return; end\n            VariationalRefinement_(this.id, 'delete');\n        end\n    end\n\n    %% DenseOpticalFlow\n    methods\n        function flow = calc(this, I0, I1, varargin)\n            %CALC  Calculates an optical flow\n            %\n            %     flow = obj.calc(I0, I1)\n            %     flow = obj.calc(I0, I1, 'OptionName',optionValue, ...)\n            %\n            % ## Input\n            % * __I0__ first 8-bit single-channel input image.\n            % * __I1__ second input image of the same size and the same type\n            %   as `I0`.\n            %\n            % ## Output\n            % * __flow__ computed flow image that has the same size as `I0`\n            %   and type `single` (2-channels).\n            %\n            % ## Options\n            % * __InitialFlow__ specify the initial flow. Not set by default.\n            %\n            % See also: cv.VariationalRefinement\n            %\n            flow = VariationalRefinement_(this.id, 'calc', I0, I1, varargin{:});\n        end\n\n        function collectGarbage(this)\n            %COLLECTGARBAGE  Releases all inner buffers\n            %\n            %     obj.collectGarbage()\n            %\n            VariationalRefinement_(this.id, 'collectGarbage');\n        end\n    end\n\n    %% VariationalRefinement\n    methods\n        function [flow_u, flow_v] = calcUV(this, I0, I1, varargin)\n            %CALCUV  calc function overload to handle separate horizontal (u) and vertical (v) flow components (to avoid extra splits/merges)\n            %\n            %     [flow_u, flow_v] = obj.calcUV(I0, I1)\n            %     [flow_u, flow_v] = obj.calcUV(I0, I1, 'OptionName',optionValue, ...)\n            %\n            % ## Input\n            % * __I0__ first 8-bit single-channel input image.\n            % * __I1__ second input image of the same size and the same type\n            %   as `I0`.\n            %\n            % ## Output\n            % * **flow_u** computed horizontal flow image that has the same\n            %   size as `I0` and type `single` (1-channel1).\n            % * **flow_v** computed vertical flow image that has the same size\n            %   as `I0` and type `single` (1-channel1).\n            %\n            % ## Options\n            % * __InitialFlowU__ specify initial U-flow. Not set by default.\n            % * __InitialFlowV__ specify initial V-flow. Not set by default.\n            %\n            % Note that `flow(:,:,1)==flow_u`, and `flow(:,:,2)==flow_v`.\n            %\n            % See also: cv.VariationalRefinement.calc\n            %\n            [flow_u, flow_v] = VariationalRefinement_(this.id, 'calcUV', I0, I1, varargin{:});\n        end\n    end\n\n    %% Algorithm\n    methods (Hidden)\n        function clear(this)\n            %CLEAR  Clears the algorithm state\n            %\n            %     obj.clear()\n            %\n            % See also: cv.VariationalRefinement.empty\n            %\n            VariationalRefinement_(this.id, 'clear');\n        end\n\n        function b = empty(this)\n            %EMPTY  Returns true if the algorithm is empty\n            %\n            %     b = obj.empty()\n            %\n            % ## Output\n            % * __b__ Returns true if the algorithm is empty (e.g. in the very\n            %   beginning or after unsuccessful read).\n            %\n            % See also: cv.VariationalRefinement.clear\n            %\n            b = VariationalRefinement_(this.id, 'empty');\n        end\n\n        function name = getDefaultName(this)\n            %GETDEFAULTNAME  Returns the algorithm string identifier\n            %\n            %     name = obj.getDefaultName()\n            %\n            % ## Output\n            % * __name__ This string is used as top level XML/YML node tag\n            %   when the object is saved to a file or string.\n            %\n            % See also: cv.VariationalRefinement.save, cv.VariationalRefinement.load\n            %\n            name = VariationalRefinement_(this.id, 'getDefaultName');\n        end\n\n        function save(this, filename)\n            %SAVE  Saves the algorithm to a file\n            %\n            %     obj.save(filename)\n            %\n            % ## Input\n            % * __filename__ Name of the file to save to.\n            %\n            % This method stores the algorithm parameters in a file storage.\n            %\n            % See also: cv.VariationalRefinement.load\n            %\n            VariationalRefinement_(this.id, 'save', filename);\n        end\n\n        function load(this, fname_or_str, varargin)\n            %LOAD  Loads algorithm from a file or a string\n            %\n            %     obj.load(fname)\n            %     obj.load(str, 'FromString',true)\n            %     obj.load(..., 'OptionName',optionValue, ...)\n            %\n            % ## Input\n            % * __fname__ Name of the file to read.\n            % * __str__ String containing the serialized model you want to\n            %   load.\n            %\n            % ## Options\n            % * __ObjName__ The optional name of the node to read (if empty,\n            %   the first top-level node will be used). default empty\n            % * __FromString__ Logical flag to indicate whether the input is a\n            %   filename or a string containing the serialized model.\n            %   default false\n            %\n            % This method reads algorithm parameters from a file storage.\n            % The previous model state is discarded.\n            %\n            % See also: cv.VariationalRefinement.save\n            %\n            VariationalRefinement_(this.id, 'load', fname_or_str, varargin{:});\n        end\n    end\n\n    %% Getters/Setters\n    methods\n        function value = get.FixedPointIterations(this)\n            value = VariationalRefinement_(this.id, 'get', 'FixedPointIterations');\n        end\n        function set.FixedPointIterations(this, value)\n            VariationalRefinement_(this.id, 'set', 'FixedPointIterations', value);\n        end\n\n        function value = get.SorIterations(this)\n            value = VariationalRefinement_(this.id, 'get', 'SorIterations');\n        end\n        function set.SorIterations(this, value)\n            VariationalRefinement_(this.id, 'set', 'SorIterations', value);\n        end\n\n        function value = get.Omega(this)\n            value = VariationalRefinement_(this.id, 'get', 'Omega');\n        end\n        function set.Omega(this, value)\n            VariationalRefinement_(this.id, 'set', 'Omega', value);\n        end\n\n        function value = get.Alpha(this)\n            value = VariationalRefinement_(this.id, 'get', 'Alpha');\n        end\n        function set.Alpha(this, value)\n            VariationalRefinement_(this.id, 'set', 'Alpha', value);\n        end\n\n        function value = get.Delta(this)\n            value = VariationalRefinement_(this.id, 'get', 'Delta');\n        end\n        function set.Delta(this, value)\n            VariationalRefinement_(this.id, 'set', 'Delta', value);\n        end\n\n        function value = get.Gamma(this)\n            value = VariationalRefinement_(this.id, 'get', 'Gamma');\n        end\n        function set.Gamma(this, value)\n            VariationalRefinement_(this.id, 'set', 'Gamma', value);\n        end\n    end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/+cv/VariationalRefinement.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5529711886467373}}
{"text": "%% Parameters\n\nF_update = [1 0 1 0; 0 1 0 1; 0 0 1 0; 0 0 0 1];\n\nNpop_particles = 4000;\n\nXstd_rgb = 50;\nXstd_pos = 25;\nXstd_vec = 5;\n\nXrgb_trgt = [255; 0; 0];\n\n%% Loading Movie\n\nvr = VideoReader('Person.wmv');\n\nNpix_resolution = [vr.Width vr.Height];\nNfrm_movie = floor(vr.Duration * vr.FrameRate);\n\n%% Object Tracking by Particle Filter\n\nX = create_particles(Npix_resolution, Npop_particles);\n\nfor k = 1:Nfrm_movie\n    \n    % Getting Image\n    Y_k = read(vr, k);\n    \n    % Forecasting\n    X = update_particles(F_update, Xstd_pos, Xstd_vec, X);\n    \n    % Calculating Log Likelihood\n    L = calc_log_likelihood(Xstd_rgb, Xrgb_trgt, X(1:2, :), Y_k);\n    \n    % Resampling\n    X = resample_particles(X, L);\n\n    % Showing Image\n    show_particles(X, Y_k); \n%    show_state_estimated(X, Y_k);\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/33666-simple-particle-filter-demo/PF_Video_EN/particle_filter_by_saved_movie.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5529169740576652}}
{"text": "%data comes from the EUROC MAV dataset V1_01_medium\nclear;\nclose all;\naddpath myToolbox\naddpath filters\naddpath data\n\ntMin = 1081; % starting IMU time\ntImagesMin = 109; % starting camera time\n\n%% Initialization\nfreqIMU = 200; %Hz\nfreqCam = 20; %Hz\n\nParamGlobal.dirImage = 'V1_02_medium/mav0/cam0/data/';\ndirImage = 'V1_02_medium/mav0/cam0/data/';\nfileData = 'DATA_MEDIUM.mat';\nfileImages = 'fileImages_MEDIUM.mat';\noffset = 881;\n\n% IMU and frame date\nload(fileData);\nt = tIMU;\nt = t/10^9; % ns -> s\ng = 9.81*[0;0;-1]; %gravity field\nomega = omega(:,tMin:end);\nacc = acc(:,tMin:end);\nt = t(tMin:end);\ntIMU = tIMU(tMin:end);\nParamGlobal.tIMU = tIMU;\nNbSteps = length(tIMU);\nNbStepsMax = 8000;\n\nload(fileImages); \ntImages = tImages(tImagesMin:end);\nfileImages = fileImages(tImagesMin:end);\nParamGlobal.fileImages = fileImages;\n%corect offset\ntReal(1:offset) = [];\ntrajReal.x(:,1:offset) = []; \ntrajReal.v(:,1:offset) = [];\ntrajReal.quat(1:offset) = [];\ntrajReal.psi(1:offset) = [];\ntrajReal.theta(1:offset) = [];\ntrajReal.phi(1:offset) = [];\ntrajReal.omega_b(:,1:offset) = [];\ntrajReal.a_b(:,1:offset) = [];\nobsTimes = zeros(length(t),1);\nobsTimes(1:10:end) = 1; % IMU is 10 times faster than camera\n\n%% Init Filter\nP0amers = diag([1;1;1]*1.e-3); %initial landmark covariance\nR = 1.0^2*eye(2); %measurement noise for one landmark\nParamFilter.NbAmers = 30; %nominal number of landmarks in the state\nParamFilter.NbAmersMin = ParamFilter.NbAmers;\nParamFilter.EcartPixelMax = 20;\n\n% init covariance\np0Rot = (0.01*pi/180)^2;\np0v =  1.e-4;\np0x =  1.e-8;\np0omegab = 1.e-6;\np0ab = 1.e-6;\nP0 = diag([p0Rot*ones(3,1);p0v*ones(3,1);p0x*ones(3,1);...\n    p0omegab*ones(3,1);p0ab*ones(3,1)]);\n\n% process noises\nq_omega = (1.6968e-4)^2*200;\nq_a = (2e-3)^2*200;\nq_omegab = (1.9393e-5)^2*200;\nq_ab = (3e-3)^2*200;\nQ = diag([q_omega*ones(3,1);q_a*ones(3,1);q_omegab* ...\n    ones(3,1);q_ab*ones(3,1)]);\nQc = chol(Q);\nP0 = blkdiag(P0,kron(eye(ParamFilter.NbAmers),P0amers));\n\n%depending on the chosen camera %cam0\nParamFilter.chiC = [0.0148655429818, -0.999880929698, 0.00414029679422, -0.0216401454975;\n    0.999557249008, 0.0149672133247, 0.025715529948, -0.064676986768;\n    -0.0257744366974, 0.00375618835797, 0.999660727178, 0.00981073058949;\n    0.0, 0.0, 0.0, 1.0]; % camera pose\nParamFilter.Pi = [458.654 0 0; 0 457.296 0; 367.215, 248.375 1]';%camera calibration matrix\nParamFilter.cameraParams = cameraParameters('IntrinsicMatrix', ParamFilter.Pi',...\n    'RadialDistortion',[-0.28340811, 0.07395907],...\n    'TangentialDistortion',[0.00019359, 1.76187114e-05]);\n\n% Initialisation of the state is obtained following [Mur-Artal,2017],\nload('data/ORB_SLAM_init.mat');\nRot0 = eul2rotm([trajReal.psi(1),trajReal.theta(1),trajReal.phi(1)]);\nx0 = trajReal.x(:,1);\nv0 = trajReal.v(:,1);\nomega_b0 = orb_slam.omega_b;\na_b0 = orb_slam.a_b;\nPosAmers0 = orb_slam.PosAmers;\ntrackerMain = orb_slam.trackerMain;\ntrackerBis = orb_slam.trackerBis;\nmyTracks = orb_slam.myTracks;\n\nIdxImage = 2; % image index\n\ntrajL = initTraj(NbSteps);\nRotL = Rot0;\nvL = v0;\nxL = x0;\nomega_bL = omega_b0;\na_bL = a_b0;\nPosAmersL = PosAmers0;\nP_L = P0;\nS_L = chol(P_L);\nchiL = state2chi(RotL,vL,xL,PosAmersL);\n\ntrajR = initTraj(NbSteps);\nRotR = Rot0;\nvR = v0;\nxR = x0;\nomega_bR = omega_b0;\na_bR = a_b0;\nPosAmersR = PosAmers0;\nP_R = P0;\nS_R = chol(P_R);\nchiR = state2chi(RotR,vR,xR,PosAmersR);\n\ntrajRef = initTraj(NbSteps);\nRotRef = Rot0;\nvRef = v0;\nxRef = x0;\nomega_bRef = omega_b0;\na_bRef = a_b0;\nPosAmersRef = PosAmers0;\nP_Ref = blkdiag(P0);\nS_Ref = chol(P_Ref);\nchiRef = [RotRef xRef;0 0 0 1];\nxidotRef = zeros(6,1);\n\ntrajU = initTraj(NbSteps);\nRotU = Rot0;\nvU = v0;\nxU = x0;\nomega_bU = omega_b0;\na_bU = a_b0;\nPosAmersU = PosAmers0;\nP_U = blkdiag(P0);\nS_U = chol(P_U);\n\ntrajI = initTraj(NbSteps);\nRotI = Rot0;\nvI = v0;\nxI = x0;\nomega_bI = omega_b0;\na_bI = a_b0;\nPosAmersI = PosAmers0;\nP_I = blkdiag(P0);\n\n%% Filtering\nfor i = 2:NbStepsMax\n    % propagation\n    dt = t(i)-t(i-1);\n    omega_i = omega(:,i);\n    acc_i = acc(:,i);\n    \n    chiAntR = chiR;\n    RotR = RotR*expSO3((omega_i-omega_bR)*dt);\n    vR = vR+(RotR*(acc_i-a_bR)+g)*dt;\n    xR = xR+vR*dt;\n    chiR = state2chi(RotR,vR,xR,PosAmersR);\n    S_R = rukfPropagation(dt,chiR,chiAntR,omega_bR,a_bR,S_R,omega_i,...\n        acc_i,Qc,g);\n    \n    % propagation for others filters\n    chiAntL = chiL;\n    RotL = RotL*expSO3((omega_i-omega_bL)*dt);\n    vL = vL+(RotL*(acc_i-a_bL)+g)*dt;\n    xL = xL+vL*dt;\n    chiL = state2chi(RotL,vL,xL,PosAmersL);\n    S_L = lukfPropagation(dt,chiL,chiAntL,omega_bL,a_bL,S_L,omega_i,...\n        acc_i,Qc,g);\n    \n    chiAntRef = [RotRef,xRef;zeros(1,3) 1];\n    vAnt = vRef;\n    RotRef = RotRef*expSO3((omega_i-omega_bRef)*dt);\n    vRef = vRef+(RotRef*(acc_i-a_bRef)+g)*dt;\n    xRef = xRef+vRef*dt;\n    xidotRef = xidotRef + [omega_i-omega_bRef;vRef]*dt;\n    chiRef = [RotRef,xRef;zeros(1,3) 1];\n    S_Ref = ukfRefPropagation(dt,chiRef,chiAntRef,vAnt,omega_bRef,...\n        a_bRef,S_Ref,omega_i,acc_i,Qc,g);\n    \n    RotAntU = RotU;\n    RotU = RotU*expSO3((omega_i-omega_bU)*dt);\n    vU = vU+(RotU*(acc_i-a_bU)+g)*dt;\n    xU = xU+vU*dt;\n    chiU = [RotU,xU;zeros(1,3) 1];\n    S_U = ukfPropagation(dt,RotU,RotAntU,vAnt,omega_bU,a_bU,S_U,omega_i,...\n        acc_i,Qc,g);\n    \n    [RotI,vI,xI,PosAmersI,P_I] = iekfPropagation(dt,RotI,vI,xI,...\n        omega_bI,a_bI,PosAmersI,P_I,omega_i,acc_i,Q,g);\n    chiI = state2chi(RotI,vI,xI,PosAmersI);\n    \n    % if measurement\n    if obsTimes(i) == 1\n        % track points in image\n        [y,yAmers,trackerMain,trackerBis,pointsMain,validityMain,...\n            myTracks,pointsBis] = ...\n            ObserveLandmarks(trackerMain,trackerBis,dirImage,IdxImage,...\n            fileImages,ParamFilter,RotR,xR,PosAmersR,i,S_R,myTracks);\n        \n        % update state\n        param.yAmers = yAmers;\n        [chiR,omega_bR,a_bR,S_R] = rukfUpdate(chiR,omega_bR,...\n            a_bR,S_R,y,param,R,ParamFilter);\n        [RotR,vR,xR,PosAmersR] = chi2state(chiR);\n        \n        % update other filters\n        chiL = state2chi(RotL,vL,xL,PosAmersL);\n        [chiL,omega_bL,a_bL,S_L] = lukfUpdate(chiL,omega_bL,...\n            a_bL,S_L,y,param,R,ParamFilter);\n        [RotL,vL,xL,PosAmersL] = chi2state(chiL);\n        \n        param.PosAmers = PosAmersRef;\n        chiRef = state2chi(RotRef,vRef,xRef,PosAmersRef);\n        [chiRef,vRef,PosAmersRef,omega_bRef,a_bRef,S_Ref,xidotRef] = ukfRefUpdate(chiRef,vRef,omega_bRef,...\n            a_bRef,S_Ref,y,param,R,ParamFilter,PosAmersRef,xidotRef);\n        RotRef = chiRef(1:3,1:3);\n        xRef = chiRef(1:3,4);\n        \n        param.PosAmers = PosAmersU;\n        chiU = state2chi(RotU,vU,xU,PosAmersU);\n        [RotU,vU,xU,PosAmersU,omega_bU,a_bU,S_U] = ukfUpdate(RotU,vU,xU,omega_bU,...\n            a_bU,S_U,y,param,R,ParamFilter,PosAmersU);\n        \n        [chiI,omega_bI,a_bI,P_I] = iekfUpdate(chiI,omega_bI,a_bI,...\n            P_I,y,R,ParamFilter,yAmers);\n        [RotI,vI,xI,PosAmersI] = chi2state(chiI);\n        \n        % save trajectory\n        trajR = updateTraj(trajR,RotR,vR,xR,omega_bR,a_bR,i);\n        trajL = updateTraj(trajL,RotL,vL,xL,omega_bL,a_bL,i);\n        trajRef = updateTraj(trajRef,RotRef,vRef,xRef,omega_bRef,a_bRef,i);\n        trajU = updateTraj(trajU,RotU,vU,xU,omega_bU,a_bU,i);\n        trajI = updateTraj(trajI,RotI,vI,xI,omega_bI,a_bI,i);\n        \n        % remplace non visible landmarks\n        [S_R,PosAmersR,ParamFilter,trackerBis,myTracks,PosAmersNew,...\n            IdxAmersNew,trackCov,pointsMain,validityMain] = manageAmers(S_R,...\n            PosAmersR,ParamFilter,ParamGlobal,trackerBis,...\n            trajR,i,pointsMain,validityMain,IdxImage,myTracks,pointsBis);\n        chiR = state2chi(RotR,vR,xR,PosAmersR);\n        \n        setPoints(trackerMain,pointsMain,validityMain);\n        \n        % remplace non visible landmarks for others filters with same\n        % landmarks\n        if isempty(IdxAmersNew) == 0\n            P_L = S_L'*S_L;\n            P_Ref = S_Ref'*S_Ref;\n            P_U = S_U'*S_U;\n            for jj = 1:length(IdxAmersNew)\n                idx = IdxAmersNew(jj);\n                idxP = 15+(3*idx-2:3*idx);\n                P_L(:,idxP) = 0;\n                P_L(idxP,:) = 0;\n                P_L(idxP,idxP) = trackCov{jj};\n                PosAmersL(:,idx) = PosAmersNew(jj,:)';\n                P_Ref(:,idxP) = 0;\n                P_Ref(idxP,:) = 0;\n                P_Ref(idxP,idxP) = trackCov{jj};\n                PosAmersRef(:,idx) = PosAmersNew(jj,:)';\n                P_U(:,idxP) = 0;\n                P_U(idxP,:) = 0;\n                P_U(idxP,idxP) = trackCov{jj};\n                PosAmersU(:,idx) = PosAmersNew(jj,:)';\n                P_I(:,idxP) = 0;\n                P_I(idxP,:) = 0;\n                P_I(idxP,idxP) = trackCov{jj};\n                PosAmersI(:,idx) = PosAmersNew(jj,:)';\n            end\n            S_L = chol(P_L);\n            chiL = state2chi(RotL,vL,xL,PosAmersL);\n            S_Ref = chol(P_Ref);\n            chiRef = [RotRef,xRef;zeros(1,3) 1];\n            S_U = chol(P_U);\n            chiI = state2chi(RotI,vI,xI,PosAmersI);\n        end\n        disp(i/200);\n        IdxImage = IdxImage+1;\n    else\n        trajR = updateTraj(trajR,RotR,vR,xR,omega_bR,a_bR,i);\n        trajL = updateTraj(trajL,RotL,vL,xL,omega_bL,a_bL,i);\n        trajRef = updateTraj(trajRef,RotRef,vRef,xRef,omega_bRef,a_bRef,i);\n        trajU = updateTraj(trajU,RotU,vU,xU,omega_bU,a_bU,i);\n        trajI = updateTraj(trajI,RotI,vI,xI,omega_bI,a_bI,i);\n    end\nend\n\n%% Plots\nerrorR = computeError(trajR,trajReal,i);\nerrorL = computeError(trajL,trajReal,i);\nerrorU = computeError(trajU,trajReal,i);\nerrorRef = computeError(trajRef,trajReal,i);\nerrorI = computeError(trajI,trajReal,i);\n\nfigure;hold on;\nplot(t(2:i-1)-t(2),errorR.errorR);\nplot(t(2:i-1)-t(2),errorL.errorR);\nplot(t(2:i-1)-t(2),errorRef.errorR);\nplot(t(2:i-1)-t(2),errorU.errorR);\nplot(t(2:i-1)-t(2),errorI.errorR);\ndisp(sqrt(mean([errorR.errorR errorL.errorR  errorRef.errorR errorU.errorR errorI.errorR].^2)));\nlegend('R-UKF-LG','L-UKF-LG','SE(3)-UKF','UKF','IEKF')\nxlabel('t (s)')\nylabel('RMSE attitdude (\u00b0)')\ntitle('RMSE on attitude as function of time')\nfigure\nhold on;\nplot(t(2:i-1)-t(2),errorR.errorX);\nplot(t(2:i-1)-t(2),errorL.errorX);\nplot(t(2:i-1)-t(2),errorRef.errorX);\nplot(t(2:i-1)-t(2),errorU.errorX);\nplot(t(2:i-1)-t(2),errorI.errorX);\ndisp(sqrt(mean([errorR.errorX  errorL.errorX errorRef.errorX errorU.errorX errorI.errorX].^2)));\nlegend('R-UKF-LG','L-UKF-LG','SE(3)-UKF','UKF','IEKF')\nxlabel('t (s)')\nylabel('RMSE position (m)')\ntitle('RMSE on position as function of time')", "meta": {"author": "mbrossar", "repo": "FUSION2018", "sha": "ff97d009d80151b2ce2b2c62ffe792a90e1ed7de", "save_path": "github-repos/MATLAB/mbrossar-FUSION2018", "path": "github-repos/MATLAB/mbrossar-FUSION2018/FUSION2018-ff97d009d80151b2ce2b2c62ffe792a90e1ed7de/mainExperiment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5528955506946803}}
{"text": "% Build and initialize the computational graph for extracting log Mel\n% filterbank features\n%\nfunction [layer, para] = BuildFbankExtractionNet()\npara.output = 'tmp';\npara.IO.nStream = 1;\npara.NET.sequential = 1;\npara.cost_func.layer_idx = [];\n\npara = ConfigBasicSTFT(para);\nlayer = genNetworkFbankExtraction(para.topology);     % generate the network graph\n\n% generating the scaling factor for the input, as we will need to use a\n% small constant in the logarithm. We need to make sure that the power of\n% speech are larger than this constant most of the time. \nscale = 1e4;        % we hard code the scale to be a constant so that all network will use the same number\nscale = scale/2^16; % note that we are using int16 to store waveform samples, so need to scale down\nlayer = InitWavScaleLayer(layer, scale);\n\n% set Mel filterbank linear transform\nlayer = InitMelLayer(layer, para);\n\npara.out_layer_idx = length(layer);\n\npara = ParseOptions2(para);\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/examples/beamforming/lib/BuildFbankExtractionNet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5528955450662302}}
{"text": "function [y,nz] = ompdenoise1(params,msgdelta)\n%OMPDENOISE1 OMP denoising of 1-D signals.\n%  OMPDENOISE1 denoises a 1-dimensional signal using OMP denoising. The\n%  function syntax is identical to OMPDENOISE, but it runs significantly\n%  faster on 1-D signals. OMPDENOISE1 requires somewhat more memory than\n%  OMPDENOISE (approximately the size of the input signal), so if memory is\n%  limited, OMPDENOISE can be used instead.\n%\n%  See also OMPDENOISE.\n\n\n%  Ron Rubinstein\n%  Computer Science Department\n%  Technion, Haifa 32000 Israel\n%  ronrubin@cs\n%\n%  August 2009\n\n\n% parse input arguments %\n\nx = params.x(:);\nD = params.dict;\nblocksize = params.blocksize;\n\n\n% maxval %\nif (isfield(params,'maxval'))\n  maxval = params.maxval;\nelse\n  maxval = 1;\nend\n\n\n% gain %\nif (isfield(params,'gain'))\n  gain = params.gain;\nelse\n  gain = 1.15;\nend\n\n\n% maxatoms %\nif (isfield(params,'maxatoms'))\n  maxatoms = params.maxatoms;\nelse\n  maxatoms = floor(prod(blocksize)/2);\nend\n\n\n% stepsize %\nif (isfield(params,'stepsize'))\n  stepsize = params.stepsize;\nelse\n  stepsize = 1;\nend\nif (any(stepsize<1))\n  error('Invalid step size.');\nend\n\n\n% noise mode %\nif (isfield(params,'noisemode'))\n  switch lower(params.noisemode)\n    case 'psnr'\n      sigma = maxval / 10^(params.psnr/20);\n    case 'sigma'\n      sigma = params.sigma;\n    otherwise\n      error('Invalid noise mode specified');\n  end\nelseif (isfield(params,'sigma'))\n  sigma = params.sigma;\nelseif (isfield(params,'psnr'))\n  sigma = maxval / 10^(params.psnr/20);\nelse\n  error('Noise strength not specified');\nend\n\n\n% lambda %\nif (isfield(params,'lambda'))\n  lambda = params.lambda;\nelse\n  lambda = maxval/(10*sigma);\nend\n\n\n% msgdelta %\nif (nargin <2)\n  msgdelta = 5;\nend\nif (msgdelta<=0)\n  msgdelta = -1;\nend\n\n\nepsilon = sqrt(prod(blocksize)) * sigma * gain;   % target error for omp\n\n\nMEM_LOW = 1;\nMEM_NORMAL = 2;\nMEM_HIGH = 3;\n\nif (isfield(params,'memusage'))\n  switch lower(params.memusage)\n    case 'low'\n      memusage = MEM_LOW;\n    case 'normal'\n      memusage = MEM_NORMAL;\n    case 'high'\n      memusage = MEM_HIGH;\n    otherwise\n      error('Invalid memory usage mode');\n  end\nelse\n  memusage = MEM_NORMAL;\nend\n\n\n% denoise the signal %\n\nif (memusage >= MEM_NORMAL)\n  G = D'*D;\nend\n\n\n% process the signal in batches to conserve memory\n% choose batchsize so im2col returns a matrix of approximately the same\n% size as the signal\nbatchsize = ceil(length(x)*stepsize/blocksize + blocksize);\n\ny = zeros(size(x));\nids = 1:min(batchsize,length(x));\nnz = 0;\n\ntid = timerinit('ompdenoise', length(x));\nwhile (length(ids)>=blocksize)\n\n  % extract the signal blocks\n  blocks = im2col(x(ids),[blocksize 1],'sliding');\n  blocks = blocks(:,1:stepsize:end);\n\n  % remove DC\n  [blocks, dc] = remove_dc(blocks,'columns');\n\n  % denoise the blocks\n  if (memusage == MEM_LOW)\n    gamma = omp2(D,blocks,[],epsilon,'maxatoms',maxatoms);\n  else\n    gamma = omp2(D,blocks,G,epsilon,'maxatoms',maxatoms);\n  end\n  nz = nz + nnz(gamma);\n  cleanblocks = add_dc(D*gamma, dc, 'columns');\n\n  y(ids) = y(ids) + col2imsum(cleanblocks, [blocksize 1], [length(ids) 1], [stepsize 1]);\n  ids = ids + floor((batchsize-blocksize)/stepsize)*stepsize + stepsize;\n  if (ids(end)>length(x))\n    ids = ids(ids<=length(x));\n  end\n  \n  % display status\n  if (msgdelta>0 && ~isempty(ids)>0)\n    timereta(tid, ids(1), msgdelta);\n  end\n\nend\n\nif (msgdelta>0)\n  timereta(tid, length(x));\nend\n\n\ncnt = countcover(size(x),[blocksize 1],[stepsize 1]);\ny = (y+lambda*x)./(cnt + lambda);\ny = reshape(y,size(params.x));\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/Aplus/ksvdbox/ompdenoise1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5528576761235012}}
{"text": "function X = ttm(X,V,varargin)\n%TTM Tensor times matrix for ktensor.\n%\n%   Y = TTM(X,A,N) computes the n-mode product of the ktensor X with a\n%   matrix A; i.e., X x_N A.  The integer N specifies the dimension\n%   (or mode) of X along which A should be multiplied.  If size(A) =\n%   [J,I], then X must have size(X,N) = I.  The result will be a\n%   ktensor of the same order and size as X except that size(Y,N) = J.\n%\n%   Y = TTM(X,{A,B,C,...}) computes the n-mode product of the ktensor\n%   X with a sequence of matrices in the cell array.  The n-mode\n%   products are computed sequentially along all dimensions (or modes)\n%   of X. The cell array contains ndims(X) matrices.\n%\n%   Y = TTM(X,{A,B,C,...},DIMS) computes the sequence tensor-matrix\n%   products along the dimensions specified by DIMS.\n%\n%   Y = TTM(...,'t') performs the same computations as above except\n%   the matrices are transposed.\n%\n%   Examples\n%   X = ktensor({rand(5,2),rand(3,2),rand(4,2),rand(2,2)});\n%   A = rand(4,5); B = rand(4,3); C = rand(3,4); D = rand(3,2);\n%   Y = ttm(X, A, 1)         %<-- computes X times A in mode-1\n%   Y = ttm(X, {A,B,C,D}, 1) %<-- same as above\n%   Y = ttm(X, A', 1, 't')   %<-- same as above\n%   Y = ttm(X, {A,B,C,D}, [1 2 3 4]) %<-- 4-way multiply\n%   Y = ttm(X, {D,C,B,A}, [4 3 2 1]) %<-- same as above\n%   Y = ttm(X, {A,B,C,D})            %<-- same as above\n%   Y = ttm(X, {A',B',C',D'}, 't')   %<-- same as above\n%   Y = ttm(X, {C,D}, [3 4])     %<-- X times C in mode-3 & D in mode-4\n%   Y = ttm(X, {A,B,C,D}, [3 4]) %<-- same as above\n%   Y = ttm(X, {A,B,D}, [1 2 4])   %<-- 3-way multiply\n%   Y = ttm(X, {A,B,C,D}, [1 2 4]) %<-- same as above\n%   Y = ttm(X, {A,B,D}, -3)        %<-- same as above\n%   Y = ttm(X, {A,B,C,D}, -3)      %<-- same as above\n%\n%   See also KTENSOR, KTENSOR/ARRANGE, TENSOR/TTM\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\n\n\n%%%%%%%%%%%%%%%%%%%%%%\n%%% ERROR CHECKING %%%\n%%%%%%%%%%%%%%%%%%%%%%\n\n% Check the number of arguments\nif (nargin < 2)\n    error('TTM requires at least two arguments.');\nend\n\n% Check for transpose option\nisTranspose = false;\nif numel(varargin) > 0\n  if isnumeric(varargin{1});\n    dims = varargin{1};\n  end\n  isTranspose =  (ischar(varargin{end}) && (varargin{end} == 't'));\nend\n\n% Check for dims argument\nif ~exist('dims','var')\n    dims = [];\nend\n\n% Check that 2nd argument is cell array. If not, recall with V as a\n% cell array with one element.\nif ~iscell(V)\n    X = ttm(X,{V},dims,varargin{end});\n    return;\nend\n\n% Get sorted dims and index for multiplicands\n[dims,vidx] = tt_dimscheck(dims,ndims(X),numel(V));\n\n% Determine correct size index\nif isTranspose\n  j = 1; \nelse\n  j = 2;\nend\n\n% Check that each multiplicand is the right size.\nfor i = 1:numel(dims)\n    if (ndims(V) ~= 2) || (size(V{vidx(i)},j) ~= size(X,dims(i)))\ndisp(size(V{vidx(i)}))\ndisp(size(X))\n\n        error('Multiplicand is wrong size');\n    end\nend\n\n% Do the multiplications in the specified modes. \nfor i = 1:numel(dims) \n  if isTranspose\n    X.u{dims(i)} = V{vidx(i)}'* X.u{dims(i)};\n  else\n    X.u{dims(i)} = V{vidx(i)} * X.u{dims(i)};\n  end\nend\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/@ktensor/ttm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5528576675813294}}
{"text": "function poly2 = clipConvexPolygon3dHP(poly, plane)\n%CLIPCONVEXPOLYGON3DHP Clip a convex 3D polygon with Half-space\n%\n%   POLY2 = clipConvexPolygon3dHP(POLY, PLANE)\n%   POLY is a N-by-3 array of points, and PLANE is given as:\n%   [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2].\n%   The result POLY2 is also an array of 3d points, sometimes smaller than\n%   poly, and that can be 0-by-3 (empty polygon).\n%\n%   POLY2 = clipConvexPolygon3dHP(POLY, PT0, NORMAL)\n%   uses plane with normal NORMAL and containing point PT0.\n%\n%\n%   See also:\n%   polygons3d, polyhedra\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2007-01-05\n% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\n\n%   HISTORY\n%   2007/14/09 fix postprocessing of last point\n\n% ensure last point is the same as the first one\nif sum(poly(end, :) == poly(1,:)) ~= 3\n    poly = [poly; poly(1,:)];\nend\n\n% initialize empty polygon\npoly2 = zeros(0, 2);\n\n% compute visible points\nbelow = isBelowPlane(poly, plane);\n\n% case of empty polygon\nif sum(below) == 0\n    return;\nend\n\n% case of totally clipped polygon\nif sum(below) == length(below)\n    poly2 = poly;\n    return;\nend\n\n% indices of edges intersecting the plane\nind = find(below ~= below([2:end 1]));\n\n% compute intersection points: they are 2 for a convex polygon\nlines = createLine3d(poly(ind, :), poly(ind+1, :));\npInt = intersectLinePlane(lines, plane);\n\n% insert intersection points and remove invisible points\nif below(1)\n    poly2 = [poly(1:ind(1), :); pInt; poly(ind(2)+1:end, :)];\nelse\n    poly2 = [pInt(1, :); poly(ind(1)+1:ind(2), :); pInt(2, :)];\nend\n\n% remove last point if it is the same as the first one\nif sum(poly2(end, :) == poly2(1,:)) == 3\n    poly2(end, :) = [];\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/geom3d/clipConvexPolygon3dHP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5528576675813294}}
{"text": "function [ num_int, pint ] = plane_imp_triangle_int_add_3d ( p1, p2, dist1, ...\n  dist2, num_int, pint )\n\n%*****************************************************************************80\n%\n%% PLANE_IMP_TRIANGLE_INT_ADD_3D is a utility for plane/triangle intersections.\n%\n%  Discussion:\n%\n%    This routine is called to consider the value of the signed distance\n%    from a plane of two nodes of a triangle.  If the two values\n%    have opposite signs, then there is a point of intersection between\n%    them.  The routine computes this point and adds it to the list.\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 P1(3), P2(3), the coordinates of two vertices \n%    of a triangle.\n%\n%    Input, real DIST1, DIST2, the signed distances of the \n%    two vertices from a plane.\n%\n%    Input, integer NUM_INT, the number of intersection points.\n%\n%    Input, real PINT(3,NUM_INT), the intersection points.\n%\n%    Output, integer NUM_INT, the updated number of intersection points.\n%\n%    Output, real PINT(3,NUM_INT), the updated intersection points.\n%\n  dim_num = 3;\n\n  if ( dist1 == 0.0 )\n    num_int = num_int + 1;\n    pint(1:dim_num,num_int) = p1(1:dim_num);\n  elseif ( dist2 == 0.0 )\n    num_int = num_int + 1;\n    pint(1:dim_num,num_int) = p2(1:dim_num);\n  elseif ( dist1 * dist2 < 0.0 )\n    alpha = dist2 / ( dist2 - dist1 );\n    num_int = num_int + 1;\n    pint(1:dim_num,num_int) = alpha * p1(1:dim_num) + ( 1.0 - alpha ) * p2(1:dim_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/geometry/plane_imp_triangle_int_add_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5528576675813293}}
{"text": "%% FUNCTION Least_Trace\n%   Trace-Norm Regularized Learning with Least Squares Loss.\n%\n%% OBJECTIVE\n%   argmin_W { sum_i^t (0.5 * norm (Y{i} - X{i}' * W(:, i))^2)\n%            + rho1 \\|W\\|_*}\n%   where \\|W\\|_* = sum(svd(W, 0)) is the trace norm\n%\n%% INPUT\n%   X: {n * d} * t - input matrix\n%   Y: {n * 1} * t - output matrix\n%   rho1: trace norm regularization parameter\n%\n%% OUTPUT\n%   W: model: d * t\n%   funcVal: function value vector.\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 <http://www.gnu.org/licenses/>.\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 June 3, 2012.\n%\n%% RELATED PAPERS\n%\n%   [1] Ji, S. and Ye, J. An Accelerated Gradient Method for Trace Norm Minimization, ICML 2009\n%\n%% RELATED FUNCTIONS\n%   Logistic_Trace, init_opts\n\n%% Code starts here\nfunction [W, funcVal] = Least_Trace(X, Y, rho1, opts)\n\nif nargin <3\n    error('\\n Inputs: X, Y, and rho1 should be specified!\\n');\nend\nX = multi_transpose(X);\n\nif nargin <4\n    opts = [];\nend\n\n% initialize options.\nopts=init_opts(opts);\n\nif isfield(opts, 'rho_L2')\n    rho_L2 = opts.rho_L2;\nelse\n    rho_L2 = 0;\nend\n\n\ntask_num  = length (X);\ndimension = size(X{1}, 1);\nfuncVal = [];\n\n% precomputation.\nXY = cell(task_num, 1);\nW0_prep = [];\nfor t_idx = 1: task_num\n    XY{t_idx} = X{t_idx}*Y{t_idx};\n    W0_prep = cat(2, W0_prep, XY{t_idx});\nend\n\n% initialize a starting point\nif opts.init==2\n    W0 = zeros(dimension, task_num);\nelseif opts.init == 0\n    W0 = W0_prep;\nelse\n    if isfield(opts,'W0')\n        W0=opts.W0;\n        if (nnz(size(W0)-[dimension, task_num]))\n            error('\\n Check the input .W0');\n        end\n    else\n        W0=W0_prep;\n    end\nend\n\n\nbFlag=0; % this flag tests whether the gradient step only changes a little\n\nWz= W0;\nWz_old = W0;\n\nt = 1;\nt_old = 0;\n\n\niter = 0;\ngamma = 1;\ngamma_inc = 2;\n\nwhile iter < opts.maxIter\n    alpha = (t_old - 1) /t;\n    \n    Ws = (1 + alpha) * Wz - alpha * Wz_old;\n    \n    % compute function value and gradients of the search point\n    gWs  = gradVal_eval(Ws);\n    Fs   = funVal_eval  (Ws);\n    \n    while true\n        [Wzp Wzp_tn] = trace_projection(Ws - gWs/gamma, 2 * rho1 / gamma);\n        Fzp = funVal_eval  (Wzp);\n        \n        delta_Wzp = Wzp - Ws;\n        r_sum = norm(delta_Wzp, 'fro')^2;\n        %Fzp_gamma = Fs + trace(delta_Wzp' * gWs) + gamma/2 * norm(delta_Wzp, 'fro')^2;\n        Fzp_gamma = Fs + sum(sum(delta_Wzp .* gWs)) + gamma/2 * norm(delta_Wzp, 'fro')^2;\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        if (Fzp <= Fzp_gamma)\n            break;\n        else\n            gamma = gamma * gamma_inc;\n        end\n    end\n    \n    Wz_old = Wz;\n    Wz = Wzp;\n    \n    %funcVal = cat(1, funcVal, Fzp + rho1 * sum( svd(Wzp, 0) ));\n    funcVal = cat(1, funcVal, Fzp + rho1 * Wzp_tn);\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    % test stop condition.\n    switch(opts.tFlag)\n        case 0\n            if iter>=2\n                if (abs( funcVal(end) - funcVal(end-1) ) <= opts.tol)\n                    break;\n                end\n            end\n        case 1\n            if iter>=2\n                if (abs( funcVal(end) - funcVal(end-1) ) <=...\n                        opts.tol* funcVal(end-1))\n                    break;\n                end\n            end\n        case 2\n            if ( funcVal(end)<= opts.tol)\n                break;\n            end\n        case 3\n            if iter>=opts.maxIter\n                break;\n            end\n    end\n    \n    iter = iter + 1;\n    t_old = t;\n    t = 0.5 * (1 + (1+ 4 * t^2)^0.5);\n    \nend\n\nW = Wzp;\n\n\n% private functions\n    function [grad_W] = gradVal_eval(W)\n        if opts.pFlag\n            grad_W = zeros(size(W));\n            parfor t_ii = 1:task_num\n                XWi = X{t_ii}' * W(:,t_ii);\n                XTXWi = X{t_ii}* XWi;\n                grad_W(:, t_ii) = XTXWi - XY{t_ii};\n                %grad_W = cat(2, grad_W, X{t_ii}*(X{t_ii}' * W(:,t_ii)-Y{t_ii}) );\n            end\n        else\n            grad_W = [];\n            for t_ii = 1:task_num\n                XWi = X{t_ii}' * W(:,t_ii);\n                XTXWi = X{t_ii}* XWi;\n                grad_W = cat(2, grad_W, XTXWi - XY{t_ii});\n                %grad_W = cat(2, grad_W, X{t_ii}*(X{t_ii}' * W(:,t_ii)-Y{t_ii}) );\n            end\n        end\n        grad_W = grad_W + rho_L2 * 2 * W;\n    end\n\n    function [funcVal] = funVal_eval (W)\n        funcVal = 0;\n        if opts.pFlag\n            parfor i = 1: task_num\n                funcVal = funcVal + 0.5 * norm (Y{i} - X{i}' * W(:, i))^2;\n            end\n        else\n            for i = 1: task_num\n                funcVal = funcVal + 0.5 * norm (Y{i} - X{i}' * W(:, i))^2;\n            end\n        end\n        funcVal = funcVal + rho_L2 * norm(W, 'fro')^2;\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/low_rank/Least_Trace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5527838268877591}}
{"text": "% function x = synsq_cwt_iw(Tx, fs, opt)\n%\n% Inverse Synchrosqueezing transform of Tx with associated\n% frequencies in fs.  This implements Eq. 5 of [1].\n%\n% 1. E. Brevdo, N.S. Fu\u010dkar, G. Thakur, and H-T. Wu, \"The\n% Synchrosqueezing algorithm: a robust analysis tool for signals\n% with time-varying spectrum,\" 2011.\n%\n% Input:\n%   Tx, fs: See help synsq_cwt_fw\n%   opt: options structure (see help synsq_cwt_fw)\n%      opt.type: type of wavelet used in synsq_cwt_fw\n%\n%      other wavelet options (opt.mu, opt.s) should also match\n%      those used in synsq_cwt_fw\n%\n% Output:\n%   x: reconstructed signal\n%\n% Example:\n%   [Tx,fs] = synsq_cwt_fw(t, x, 32); % Synchrosqueezing\n%   Txf = synsq_filter_pass(Tx, fs, -Inf, 1); % Pass band filter\n%   xf = synsq_cwt_iw(Txf, fs);  % Filtered signal reconstruction\n%\n%---------------------------------------------------------------------------------\n%    Synchrosqueezing Toolbox\n%    Authors: Eugene Brevdo (http://www.math.princeton.edu/~ebrevdo/)\n%---------------------------------------------------------------------------------\nfunction x = synsq_cwt_iw(Tx, fs, opt)\n    if nargin<3, opt = struct(); end\n    if ~isfield(opt, 'type'), opt.type = 'morlet'; end\n\n    % Find the admissibility coefficient Cpsi\n    Css = synsq_adm(opt.type, opt);\n    \n    [na, N] = size(Tx);\n\n    % Integration\n    % Due to linear discretization of integral in log(fs), this becomes\n    % a simple normalized sum.\n    x = real(1/Css * ones(1,na) * Tx);\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/synchrosqueezing/synchrosqueezing/synsq_cwt_iw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5527838264272478}}
{"text": "function [result]=sv_timeperdiff(mCatalog, fTimePeriod)\n% function [result]=sv_timeperdiff(mCatalog, fTimePeriod)\n% --------------------------------------------------------------------------------------\n% Function to calculate absolute difference of number of events between\n% two time periods of an earthquake catalog\n% Author: J. Woessner\n% woessner@seismo.ifg.ethz.ch\n% last update: 08.07.02\n%\n% Incoming variables:\n% mCatalog           : current earthquake catalog\n% params.fTimePeriod : Time period in days\n%\n% Outgoing variable:\n% result.dNdiffsumVal      : total difference of number of events in the two time periods\n% result.dNdiffsumYearVal  : total difference of number of events in the two time periods normalized to a year\n% result.dNdiffsumMonthVal : total difference of number of events in the two time periods normalized to a month\n% result.dNdiff            : Difference of seismicity in 0.1 magnitude bins\n\n% Init variable\nresult=[];\n\n% Create the catalogs for two time periods\nfStartTime = min(mCatalog(:,3));\nfEndTime = max(mCatalog(:,3));\n\n[result.mFirstCatalog, result.mSecondCatalog, result.fFirstPeriodExact, result.fSecondPeriodExact, result.fFirstPeriod,...\n        result.fSecondPeriod] = ex_SplitCatalog(mCatalog, fSplitTime, 0, 100, 0, 100);\n\n[dEv_val dMags dEv_valsum dEv_valsum_rev,  dMags_rev] =fcumulsum(result.mFirstCatalog);\n[dEv_val2 dMags2 dEv_valsum2 dEv_valsum_rev2,  dMags_rev2] =fcumulsum(result.mSecondCatalog);\n\n\nresult.dNdiff = dEv_val2-dEv_val;\nresult.dNdiffYear=result.dNdiff/365;\nresult.dNdiffMonth = result.dNdiffYear/12;\n\nresult.dNdiffsum = cumsum(result.dNdiff');\nresult.dNdiffsumVal = result.dNdiffsum(length(result.dNdiffsum));\nresult.dNdiffsumYearVal = result.dNdiffsumVal/365;\nresult.dNdiffsumMonthVal = result.dNdiffsumYearVal/12;\n\nresult.dMags = dMags;\nresult.dMags = dMags2;\nreturn\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/Functionlab/calc_timeperdiff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5527838264272477}}
{"text": "% SB2_PREPROCESSBASIS  Do basis matrix pre-processing for SPARSEBAYES\n%\n% [BASIS, SCALES] = SB2_PREPROCESSBASIS(BASIS)\n%\n% OUTPUT ARGUMENTS:\n%\n%\tBASIS\tNxM matrix of basis vectors appropriately pre-processed\n%\t\t\t(scaled to unit length per column) \n% \n%\tSCALES\tVector of scaling factors applied\n%\n% \n% INPUT ARGUMENTS:\n% \n%\tBASIS\tNxM matrix of basis vectors (one column per basis function)\n%\n% NOTES: \n% \n% Simply normalises the basis vectors to unit length, returning the\n% original lengths so that the weights can be rescaled appropriately\n% before returning to the user.\n%\n\n%\n% Copyright 2009, Vector Anomaly Ltd\n%\n% This file is part of the SPARSEBAYES library for Matlab (V2.0).\n%\n% SPARSEBAYES 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 Free\n% Software Foundation; either version 2 of the License, or (at your option)\n% any later version.\n%\n% SPARSEBAYES 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\n% more details.\n%\n% You should have received a copy of the GNU General Public License along\n% with SPARSEBAYES in the accompanying file \"licence.txt\"; if not, write to\n% the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n% MA 02110-1301 USA\n%\n% Contact the author: m a i l [at] m i k e t i p p i n g . c o m\n%\nfunction [BASIS, Scales] = SB2_PreProcessBasis(BASIS)\n\n%\n[N,M]\t= size(BASIS);\n%\n% Compute \"lengths\" of basis vectors (columns of BASIS)\n% \nScales\t= sqrt(sum(BASIS.^2));\n%\n% Work-around divide-by-zero inconvenience\n% \nScales(Scales==0)\t= 1;\n%\n% Normalise each basis vector to \"unit length\"\n% \nfor m=1:M\n  BASIS(:,m)\t= BASIS(:,m) / Scales(m);\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/SparseBayes-2.0/SB2_PreProcessBasis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5527838205686495}}
{"text": "% ir_mri_al_p2_example.m\n% Example of MRI SENSE reconstruction from under-sampled k-space data\n% using the AL-P2 algorithm from Mar. 2011 T-MI paper.\n% Sathish Ramani, circa 2011\n% 2013-07-14, modified by Jeff Fessler\n\n%% Test image - Shepp-Logan Phantom\nif ~isvar('img')\n\tN = 256;\n\tif exist('phantom') % matlab with image processing toolbox\n\t\timg = phantom('Modified Shepp-Logan', N)';\n\t\timg = 256 * (img + 0.05);\n\telse\n\t\timg = ellipse_im(256);\n\t\timg = 256 * (img/max(img(:)) + 0.05);\n\tend\n\t[rs, cs] = size(img); Npix = rs*cs; mn = min(img(:)); mx = max(img(:));\n\tparams.rs = rs;\n\tparams.cs = cs;\n\tparams.mn = mn;\n\tparams.mx = mx;\n\tparams.Npix = Npix;\n\tim plc 2 3\n\tim(1, img, 'true image')\nend\n\n\n%% sensitivity maps\nif ~isvar('smap')\n\tsmap = mri_sensemap_sim('nx', N, 'rcoil', 175, 'dx', 1);\n\tncoils = size(smap, 3);\n\tparams.ncoils = ncoils;\n\tim(2, abs(smap), '|sense maps|'), cbar\nend\n\n\n%% load sampling pattern\nif ~isvar('SP')\n\tload('PDiskR256x256L1R2.252.25B0.8R1D1pctg20.2972.mat', 'SP', 'sampname');\n\tNcentx = 8; % sample a window of 2*N around DC along x\n\tNcenty = 8; % sample a window of 2*N around DC along y\n\n\tparams.samp = sampname;\n\tSP = coverDC_SamplingMask(SP, Ncentx, Ncenty);\n\tlSP = length(find(SP>0)); % # of sampling points\n\tprintm('Sampling %0.2f%% of k-space', lSP / Npix * 100)\n\n\t% Sampling pattern for the output of each coil\n\tSP3 = repmat(SP, [1 1 ncoils]); \n\tim(3, [-N/2:N/2-1], [-N/2:N/2-1], fftshift(SP), 'sampling pattern')\nend\n\n\n%% Data samples\nif ~isvar('Data')\n\tSNR = 30; % SNR of noisy data\n\tsmap_img = smap .* repmat(img, [1 1 ncoils]); % sensitivity-weighted images\n\tsmap_Img = fft2(smap_img); % FFT of Sensitivity-weighted images\n\n\t% Add white Gaussian noise of desired SNR\n\tseedr = 0;\n\tstdnois = zeros(1, ncoils);\n\tnoise_vr = zeros(rs, cs, ncoils);\n\tfor ismap = 1:ncoils\n\t\tDtemp = smap_Img(:,:,ismap);\n\t\tsigpow = sum(abs(Dtemp(:)).^2)/(rs*cs);\n\t\tstdnois(ismap) = sqrt(sigpow*10^(-SNR/10)); % Std. deviation of noise at ith coil\n\t\trandn('state', seedr + ismap);\n\t\tnoise_realz = (randn(rs,cs) + j*randn(rs,cs))/sqrt(2);\n\t\tnoise_vr(:, :, ismap) = noise_realz;\n\tend\n\tSQCStd = diag(stdnois);\n\tnoisecorr = zeros(rs, cs, ncoils);\n\tfor irK = 1 : ncoils % Apply the above correlation to the generated i.i.d noise to create correlated noise\n\t\tdump(1, 1, :) = SQCStd(irK, :);\n\t\tnoisecorr(:, :, irK) = sum(repmat(dump, [rs cs 1]) .* noise_vr, 3);\n\tend\n\tfullData = smap_Img + noisecorr; % Noisy fully-sampled Data\n\tData = fullData .* SP3; % Generate undersampled k-space data by applying a mask\n\tfftshift2 = @(x) fftshift(fftshift(Data, 1), 2);\n\tim(5, max(log(abs(fftshift2(Data))), 0), 'Data')\nprompt\nend\n\n\n%% Simple iFFT / sum-of-squares recon of raw k-space data\nif ~isvar('recon_sos')\n\trecon_sos = ifft2(Data);\n\trecon_sos = sqrt(sum(abs(recon_sos).^2, 3));\n\tparams.recon_sos = recon_sos;\n\tim(4, recon_sos, 'SoS recon')\nend\n\n\n%% Initial Estimate = SoS + slight perturbation\nif ~isvar('xini')\n\trandn('state', seedr);\n\txini = recon_sos + (randn(rs,cs) + sqrt(-1) * randn(rs,cs))*0.001;\n\terrini = xini - img;\n\terrini = sqrt(sum(abs(errini(:)).^2)/Npix)/mx;\n\txlabelf('nrmse %g dB', 20*log10(nrms(xini, img)))\n\tim(6, abs(xini-img), '|SoS error|')\nprompt\nend\n\n\n%% Noise decorrelation in data and redefined\n% (square root of inverse of noise correlation matrix weighted) sensitivity maps\nif ~isvar('smap2')\n\trecon_F = Npix * ifft2(SP3 .* Data);\n\trecon_SF = sum(conj(smap) .* recon_F, 3);\n\n\tparams.smap = smap;\n\tsmap2 = sum(abs(smap).^2, 3); % S'S\n%\tim(smap2)\nend\n\n\n%% Penalty / regularizer / prior\nif ~isvar('lod')\n\tparams.Prior.PriorType{1} = 'TV'; % Type of penalty for wavelet coef.\n\tparams.Prior.PriorType{2} = 'TV'; % Type of penalty for wavelet coef.\n\n\t% Type of sparsifying transform\n\tparams.Operator = 'FD'; % finite differences\n\t% params.Operator = 'W'; % Redundant wavelet transform\n\t% params.Operator = 'WFD'; % Redundant wavelet transform & finite diff.\n\n\t% Wavelet Options\n\tparams.Wavelet.redundancy = 'undecimated'; % Undecimated wavelet transform using wavelet filters corresponding to standard orthonormal wavelets\n\tparams.Wavelet.wname = 'haar'; % undecimated Haar wavelets\n\tparams.Wavelet.nlev = 2; % wavelet transform with 2 levels \n\tparams.Wavelet.includeApprox = false; % exclude approximation level in the regularizer\n\n%\ttodo: make it ok in octave\n%\tUw = Gwave2('mask', true(rs,cs), 'nlevel', params.Wavelet.nlev)'; % trick\n\n\tdwtmode('per', 'nodisp'); % Period boundaries for wavelet implementation\n\t% params.Wavelet.redundancy = 'none'; % decimatSENSERecon_MRI029_Spiral6_23_2.1_SNR20_OpFD_PriorTV_Lam13.5_variablesed Orthonomal wavelet transform\n\n\t% Wavelet filters\n\t[lod, hid, lor, hir] = wfilters(params.Wavelet.wname);\n\n\t% Normalize filters so as to avoid a product with 0.5 during inverse undecimated wavelet transform \n\tparams.Wavelet.lod = lod/sqrt(2); \n\tparams.Wavelet.hid = hid/sqrt(2); \n\tparams.Wavelet.lor = lor/sqrt(2); \n\tparams.Wavelet.hir = hir/sqrt(2); \nend\n\n\n%% Parameters of the algorithms\nif ~isvar('RR')\n\t% Regularization parameters for the wavelet and TV prior\n\tparams.lambda = mean(stdnois .^ 2) * [1 0.1];\n\tparams.precon = 0;\n\tparams.betaD = 1e-10;\n\tparams.xinf = zeros(rs,cs);\n\tparams.xinfnorm = 1;\n\tparams.dcosttol = 1e18;\n\tparams.dxtol = 0;\n\n\t% Parameters for size of vectors\n\t[lzALP2 sALP2 eALP2 sr er] = get_Size_AuxVar(params);\n\n\tparams.AL.lzALP2 = lzALP2;\n\tparams.AL.sALP2 = sALP2;\n\tparams.AL.eALP2 = eALP2;\n\n\tparams.AL.sr = sr;\n\tparams.AL.er = er;\n\n\tRR = compute_RR(params); % FFT of R^T * R\n\tmxRR = max(RR(:));\n\tmnRR = min(RR(:));\n\tparams.AL.RR = RR;\n\n\t% Other setting\n\tparams.figno = 1;\n\tparams.subplot_img = 5;\n\tparams.subplot_err = 6;\n\tparams.maxitr = 400;\n\tparams.maxitr_in = 1;\n\tparams.dispfig = 1;\n\tparams.dispitr = 1;\n\tparams.dispitrnum = 10;\nend\n\n\n%% prepare to run AL-P2\nif ~isvar('zALP2')\n\tmxsmap2 = max(smap2(:));\n\tmnsmap2 = min(smap2(:));\n\tcondSS =  mxsmap2 / mnsmap2; % Condition number of S'S\n\n\tkapx = 0.9 * condSS;\n\tkapu0 = 24; % condition number of (FF + mu*I)\n\tkapu2 = 12; % condition number of (RR + nu2/n1*I)\n\n\tnu2 = (mxsmap2 - mnsmap2 * kapx) / (kapx - 1);\n\tmu = Npix / (kapu0 - 1); % min eig val of F'F = 0, while max eig val of F'F = N where the DFT matrix F is assumed to be un-normalized \n\tnu1 = (kapu2 - 1) * nu2 / (mxRR - mnRR * kapu2);\n\tnuratio = nu2 / nu1;\n\n\t% warn if any of the mu's is negative or less than eps\n\tif ((mu <= 0) || (nu1 <= 0) || (nu2 <= 0))\n\t\terror('At least one of the mu, nu''s is not positive');\n\tend\n\n\t% Inverse of some matrices required for solving sub-problems\n\tiPpmu = 1 ./ (Npix * SP3 + mu); % Freq. Response of (F'F + mu * I)^-1\n\tiSpnu2 = 1./(smap2 + nu2); % Inverse of (S'S + nu2 * I)\n\tiRpnu2nu1 = 1./(RR + nuratio); % Freq. Response of (R'R + nu2/nu1 * I)^-1\n\n\tparams.AL.mu = mu;\n\tparams.AL.nu1 = nu1;\n\tparams.AL.nu2 = nu2;\n\tparams.AL.iPpmu = iPpmu;\n\tparams.AL.iSpnu2= iSpnu2;\n\tparams.AL.iRpnu2nu1 = iRpnu2nu1;\n\n\tdALP2 = zeros(rs, cs, params.AL.lzALP2);\n\tzALP2 = dALP2;\nend\n\n\n%% Run AL-P2!\nif ~isvar('x_est'), printm 'running al-p2'\n\t[x_est CALP2 TALP2 EALP2 ERRALP2] = SENSERecon_ALP2(img, ...\n\t\tSP3, Data, recon_F, dALP2, zALP2, xini, params);\n\tprintm('Recon time = %g secs', sum(TALP2(:)))\n\tprintm('Recon NRMSE = %g ', ERRALP2(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/ramani/al-p2/ir_mri_al_p2_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.552783809772476}}
{"text": "% test for line integral convolution\n\nn = 180;\npath(path, 'toolbox/');\n\nrep = 'results/lic/';\nif not(exist(rep))\n    mkdir(rep);\nend\n\noptions.bound = 'per';\n%% generate a random irrotational vector field\nsigma = 30;\nv = perform_blurring(randn(n,n,2), sigma, options);\nv = perform_vf_normalization(v);\n\noptions.histogram = 'gaussian';\noptions.histogram = 'linear';\noptions.verb = 1;\n% size of the features\noptions.spot_size = 1.3;\n\n\n%% original image\nname = 'mandrill-color';\nname = 'flowers';\nname = 'rand';\noptions.dt = 0.5;\nw_list = [4 6 8 10 12 14];\nif strcmp(name, 'rand')\n    sigma = 1.2;\n    M0 = perform_blurring(randn(n), sigma, options);\n    M0 = perform_histogram_equalization(M0, options.histogram);\nelse\n    options.dt = 1.5;\n    w_list = w_list * 2;\n    options.histogram = [];\n    M0 = load_image(name,n);\n    M0 = rescale( crop(M0,n) );\nend\n\n%% iterated lic\nM = M0;\nw = 12;\nfor i=1:4\n    options.M0 = M;\n    M = perform_lic(v, w, options);\nend\n\n\n%% lic for increasing times\nclose all;\nclf;\noptions.M0 = M0;\nfor i=1:min(length(w_list),6)\n    M = perform_lic(v, w_list(i), options);\n    imageplot(M, '', 2,3, i);\nend\n\nsaveas(gcf, [rep name '-lic-results.png'], 'png');\n\n\nreturn;\n\n%% display with overlapping vector field\nif size(M,3)==1\n    figure; clf;\n    sub = 4;\n    plot_vf(v(1:sub:end, 1:sub:end,:), M);\n    colormap gray(256);\n    saveas(gcf, [rep, 'lic-vector-field.png'], 'png');\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_image/tests/test_lic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5527837985157908}}
{"text": "%% Copyright (C) 2014-2016, 2022 Colin B. Macdonald\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see <http://www.gnu.org/licenses/>.\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defmethod  @@sym limit (@var{expr}, @var{x}, @var{a}, @var{dir})\n%% @defmethodx @@sym limit (@var{expr}, @var{x}, @var{a})\n%% @defmethodx @@sym limit (@var{expr}, @var{a})\n%% @defmethodx @@sym limit (@var{expr})\n%% Evaluate symbolic limits.\n%%\n%% The limit of @var{expr} as @var{x} tends to @var{a} from\n%% @var{dir}.  @var{dir} can be @code{left} or @code{right}.\n%%\n%% Examples:\n%% @example\n%% @group\n%% syms x\n%% L = limit(sin(x)/x, x, 0)\n%%   @result{} L = (sym) 1\n%% L = limit(1/x, x, sym(inf))\n%%   @result{} L = (sym) 0\n%% L = limit(1/x, x, 0, 'left')\n%%   @result{} L = (sym) -\u221e\n%% L = limit(1/x, x, 0, 'right')\n%%   @result{} L = (sym) \u221e\n%% @end group\n%% @end example\n%%\n%% If @var{x} is omitted, @code{symvar} is used to determine the\n%% variable.  If @var{a} is omitted, it defaults to 0.\n%%\n%% @var{dir} defaults to @code{right}.  Note this is different from\n%% Matlab's Symbolic Math Toolbox which returns @code{NaN} for\n%% @code{limit(1/x, x, 0)}\n%% (and @code{+/-inf} if you specify @code{left/right}).  I'm not\n%% sure how to get this nicer behaviour from SymPy.\n%% FIXME: this is https://github.com/cbm755/octsympy/issues/74\n%%\n%% @seealso{@@sym/diff}\n%% @end defmethod\n\n\nfunction L = limit(f, x, a, dir)\n\n  if (nargin > 4 || nargin < 1)\n    print_usage ();\n  end\n\n  f = sym(f);\n  if (nargin < 4)\n    dir= 'right';\n  end\n  if (nargin == 2)\n    a = x;\n    x = symvar(f, 1);\n  end\n  if (nargin == 1)\n    x = symvar(f, 1);\n    a = 0;\n  end\n\n  switch (lower (dir))\n    case {'left' '-'}\n      pdir = '-';\n    case {'right' '+'}\n      pdir = '+';\n    otherwise\n      print_usage ();\n  end\n\n  if (isempty (x))\n    L = f;\n    return\n  end\n\n  L = elementwise_op ('lambda f, x, a, dir: f.limit(x, a, dir=dir)', ...\n                      sym(f), sym(x), sym(a), pdir);\nend\n\n\n%!error limit (sym(1), 2, 3, 4, 5)\n\n%!shared x, oo\n%! syms x\n%! oo = sym(inf);\n\n%!assert (isa (limit(x, x, pi), 'sym'))\n\n%!assert (isequal (limit(x, x, pi), sym(pi)))\n\n%!assert (isequal (limit(sin(x)/x, x, 0), 1))\n\n%!test\n%! % left/right-hand limit\n%! assert (isequal (limit(1/x, x, 0, 'right'), oo))\n%! assert (isequal (limit(1/x, x, 0), oo))\n%! assert (isequal (limit(1/x, x, 0, 'left'), -oo))\n%! assert (isequal (limit(1/x, x, oo), 0))\n%! assert (isequal (limit(sign(x), x, 0, 'left'), -1))\n%! assert (isequal (limit(sign(x), x, 0, 'right'), 1))\n%! assert (isequal (limit(sign(x), x, 0, '-'), -1))\n%! assert (isequal (limit(sign(x), x, 0, '+'), 1))\n\n%!test\n%! % matrix\n%! syms y\n%! A = [x 1/x x*y];\n%! B = sym([3 sym(1)/3 3*y]);\n%! assert (isequal (limit(A, x, 3), B))\n\n%!test\n%! % omitting arguments\n%! syms a\n%! assert (isequal (limit(a), 0))\n%! assert (isequal (limit(a*x+a+2), a+2))\n%! assert (isequal (limit(a*x+a+2, 6), 7*a+2))\n\n%!test\n%! % constants\n%! assert (isequal (limit(sym(6)), 6))\n%! assert (isequal (limit(sym(6), 7), 6))\n%! assert (isequal (limit([sym(6) sym(2)], 7), [6 2]))\n\n%!test\n%! % double constant, with sym limit\n%! a = limit (6, sym(0));\n%! assert (isa (a, 'sym'))\n%! assert (isequal (a, sym(6)))\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/limit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.5527818254870217}}
{"text": "function [P,x] = polytope(X,options)\n% polytope  Converts constraints to polytope object        \n%\n% P     = polytope(F)\n% [P,x] = polytope(F)\n%\n% P : polytope object (Requires the Multi-parametric Toolbox)\n% x : sdpvar object defining the variables in the polytope P.H*x<=P.K\n% F : Constraint object with linear inequalities\n%\n% See also sdpvar/polytope\n\nif nargin < 2\n    options = sdpsettings;\nelseif isempty(options)\n    options = sdpsettings;\nend\n    \n[p,recoverdata,solver,diagnostic,F] = compileinterfacedata(X,[],[],[],options,0);\n\nif any(p.K.q) || any(p.K.s) || any(p.variabletype)\n  error('Polytope can only be applied to MILP-representable constraints.')\nend\n\nif any(p.K.f)\n    try\n        [P,x] = polyhedron(X,options);\n        return\n    catch\n        disp('MPT does not support polytopes with empty interior')\n        disp('Note that these equality constraints might have been generated internally by YALMIP')\n        error('Functionality not yet supported')\n    end\nend\n\nif isempty(p.binary_variables) && isempty(p.integer_variables)\n    P = polytope(-p.F_struc(:,2:end),p.F_struc(:,1));\n    x = recover(p.used_variables);\nelse    \n    nBin = length(p.binary_variables);\n    [pBinary,removeEQ,removeLP] = extractOnly(p,p.binary_variables);\n    p.F_struc = [p.F_struc(removeEQ,:);p.F_struc(p.K.f+removeLP,:)];\n    p.K.f = length(removeEQ);\n    p.K.l = length(removeLP);\n    p.used_variables(p.binary_variables)=[];\n    x = recover(p.used_variables);\n    \n    P = [];\n    for i = 0:2^nBin-1\n        comb = dec2decbin(i,nBin);\n        if checkfeasiblefast(pBinary,comb(:),1e-6)\n            pi = p;\n            H = -p.F_struc(:,2:end);% Hx < K\n            K = p.F_struc(:,1);\n            K = K-H(:,p.binary_variables)*comb(:);\n            H(:,p.binary_variables)=[];\n            P = [P polytope(H,K)];\n        end\n    end\nend\n\nfunction pLP = extractLP(p)\npLP = p;\npLP.F_struc = pLP.F_struc(1:p.K.f+p.K.l,:);\npLP.K.q = 0;\npLP.K.s = 0;\n\nfunction [pRed,removeEQ,removeLP] = extractOnly(p,these)\npRed = p;\np.F_struc(:,1+these) = 0;\n\nremoveEQ = find(any(p.F_struc(1:pRed.K.f,2:end),2));\nremoveLP = find(any(p.F_struc(1+pRed.K.f:end,2:end),2));\npRed.F_struc(pRed.K.f+removeLP,:)=[];\npRed.F_struc(removeEQ,:)=[];\npRed.K.f = pRed.K.f - length(removeEQ);\npRed.K.l = pRed.K.l - length(removeLP);\npRed.F_struc = pRed.F_struc(:,[1 1+these]);\npRed.lb = pRed.lb(these);\npRed.ub = pRed.ub(these);", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/@lmi/polytope.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5527818252652966}}
{"text": "function msm_to_mm_test10 ( )\n\n%*****************************************************************************80\n%\n%% MSM_TO_MM_TEST10 tests MSM_TO_MM_ARRAY_REAL_SYMMETRIC.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    02 November 2008\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'MSM_TO_MM_TEST10\\n' );\n  fprintf ( 1, '  Convert an MSM to MM array real symmetric format.\\n' );\n\n  output_filename = 'msm_to_mm_test10.mm';\n\n  a = r8mat_indicator ( 4, 4 );\n  a = a + a';\n%\n%  Have MSM_TO_MM write the matrix to a file.\n%\n  msm_to_mm ( output_filename, a, 'array', 'real', 'symmetric' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/msm_to_mm/msm_to_mm_test10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.5527818168599176}}
{"text": "% angle to the closest roi\nfunction [data,units] = compute_angle2closestroi2(trx,n)\n\nflies = trx.exp2flies{n};\nnflies = numel(flies);\ndata = cell(1,nflies);\n\nfor i = 1:nflies,\n  fly = flies(i);\n  \n  % roi closest to fly\n  closestroi = trx(fly).closestroi2;\n  \n  % position of fly\n  xnose_mm1 = trx(fly).xnose_mm;\n  ynose_mm1 = trx(fly).ynose_mm;\n  theta_mm1 = trx(fly).theta_mm;\n\n  ROIdata=trx.roi2{n}.data{fly};\n  \n  % loop over all rois\n  for j = 1:size(ROIdata,1),\n    \n    % frames where this roi is closest\n    idx = find(closestroi == j);\n    if isempty(idx), continue; end\n    \n    % angle to roi\n    dx2 = ROIdata(j,1)-xnose_mm1(idx);\n    dy2 = ROIdata(j,2)-ynose_mm1(idx);\n    theta2 = atan2(dy2,dx2);\n    \n    % angle relative to fly's orientation\n    data{i}(idx) = modrange(theta2 - theta_mm1(idx),-pi,pi);\n\n  end\nend\n\nunits = parseunits('rad');", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/compute_angle2closestroi2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5527623887760845}}
{"text": "function [sys,x0,str,ts]=ADRC_3(t,x,u,flag,h,TD,ESO,NLSEF,b0)\n\nswitch flag\n    case 0\n        [sys,x0,str,ts]=mdlInitializeSizes(h);\n    case 2\n        sys=mdlUpdate(x,u,h,TD,ESO,b0);\n    case 3\n        sys=mdlOutputs(x,NLSEF,b0);\n    case 4,\n        sys=mdlGetTimeOfNextVarHit(t,h);\n    case {1,9}\n        sys=[];\n    otherwise \n        error(['Unhandled flag=',num2str(flag)]);\nend\nfunction [sys,x0,str,ts]=mdlInitializeSizes(h)\n    sizes=simsizes;\n    sizes.NumContStates=0;\n    sizes.NumDiscStates=7;\n    sizes.NumOutputs=2;\n    sizes.NumInputs=3;\n    sizes.DirFeedthrough=1;\n    sizes.NumSampleTimes=1;\n    sys=simsizes(sizes);\n    x0=[0;0;0;0;0;0;0];\n    str=[];\n    ts=[h 0];\nfunction sys=mdlUpdate(x,u,h,TD,ESO,b0)\n    e1=x(1)-u(1);\n    fh=fhan(e1,x(2),TD(1),TD(2));\n    sys(1)=x(1)+h*x(2);\n    sys(2)=x(2)+h*x(3);\n    sys(3)=x(3)+h*fh;\n    e2=x(4)-u(2);\n    sys(4)=x(4)+h*(x(5)-ESO(1)*e2);\n    sys(5)=x(5)+h*(x(6)-ESO(2)*fal(e2,0.5,ESO(5)));\n    sys(6)=x(6)+h*(x(7)-ESO(3)*fal(e2,0.25,ESO(5))+b0*u(3));\n    sys(7)=x(7)+h*(-ESO(4)*fal(e2,0.125,ESO(5)));\n    \n%     fe=fal(e,0.5,Delta);\n%     fe1=fal(e,0.25,Delta);\n%     sys(1,1)=x(1)+h2*(x(2)-BB(1)*e);\n%     sys(2,1)=x(2)+h2*(x(3)-BB(2)*fe+u(1));\n%     sys(3,1)=x(3)+h2*(-BB(3)*fe1);\nfunction sys=mdlOutputs(x,NLSEF,b0)\n    e3=x(1)-x(4);\n    e4=x(2)-x(5);\n    e5=x(3)-x(6);\n    %sys(1)=NLSEF(1)*e3+NLSEF(2)*e4+NLSEF(3)*e5-x(7)/b0;\n    sys(1)=NLSEF(1)*fal(e3,0.5,NLSEF(4))+NLSEF(2)*fal(e4,0.75,NLSEF(4))+NLSEF(3)*fal(e5,1.5,NLSEF(4))-x(7)/b0;\n    sys(2)=x(1);\nfunction sys=mdlGetTimeOfNextVarHit(t,h)\n    sys=t+h;\n    \n        \nfunction y=fhan(x1,x2,r,h)\nd=r*h;\nd0=h*d;\ny=x1+h*x2;\na0=sqrt(d^2+8*r*abs(y));\nif abs(y)>d0\n    a=x2+(a0-d)*sign(y)/2;\nelse\n    a=x2+y/h;\nend\n\nif abs(a)>d\n    y=-r*sign(a);\nelse \n    y=-r*a/d;\nend\n\nfunction f=fal(e,a,d)\n    if abs(e)<d\n        f=e*d^(a-1);\n    else f=(abs(e))^a*sign(e);\n    end", "meta": {"author": "TianfaYao", "repo": "ADRC", "sha": "6f1f96ebda1684c44af4dec4214b4880f4aa8cec", "save_path": "github-repos/MATLAB/TianfaYao-ADRC", "path": "github-repos/MATLAB/TianfaYao-ADRC/ADRC-6f1f96ebda1684c44af4dec4214b4880f4aa8cec/\u8d3a\u5e86\u6bd5\u4e1a\u8bba\u6587ADRC\u5168\u96c6\u5305\u4ec5\u7528\u4e8e\u5185\u90e8\u5171\u4eab\u4e0d\u8981\u5916\u4f20/MyLibrary/ADRC_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5526624596697258}}
{"text": "function Q = ForwardStepIC2D(x2d, y2d, time)\n \n% function Q = ForwardStepIC2D(x2d, y2d, time)\n% Purpose: compute plane flow configuration \n\nGlobals2D;\n\ngamma = 1.4;\n\nrho = gamma*ones(Np,K);  p = ones(Np,K); \n\n% M = |u|/c,  c = sqrt(gamma*p/rho)\nrhou = rho.*(3*ones(Np, K)); rhov = zeros(Np, K); \nEner = p/(gamma-1.0) + (rhou.^2+rhov.^2)./(2*rho);\n\nQ(:,:,1) = rho; Q(:,:,2) = rhou; Q(:,:,3) = rhov; Q(:,:,4) = Ener; \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/ForwardStepIC2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5526624591279165}}
{"text": "function [E,ER] = arap_energy(V,F,U,varargin)\n  % ARAP_ENERGY This function is meant as a very human readable groundtruth for\n  % evaluating ARAP energies.\n  % For faster energy computation see `arap_gradient.m`\n  %\n  % Inputs:\n  %    V  #V by dim list of mesh vertex rest positions\n  %    F  #F by simplex list of element indices into V\n  %    U  #V by dim list of deformed vertex positions\n  %   Optional:\n  %     'Energy' followed by 'spokes','spokes-and-rims', or 'elements'\n  %       {'elements' or 'spokes-and-rims'} for tets or triangles respectively.\n  % Outputs:\n  %    E  scalar energy\n  %    ER  #R list of \"per-rotation\" energy contributions\n  %\n  %\n  % Known issues:\n  % If E_G is the energy returned by arap_gradient, then\n  % 'spokes-and-rims' energy E = 3 E_G \n  % 'spokes' energy E = 2 E_G \n  % 'elements' energy E = E_G\n  %\n\n\n  switch size(F,2)\n  case 4\n    energy = 'elements';\n  case 3\n    energy = 'spokes-and-rims';\n  end\n  % default values\n  % Map of parameter names to variable names\n  params_to_variables = containers.Map( {'Energy'}, ...\n    {'energy'});\n  v = 1;\n  while v <= numel(varargin)\n    param_name = varargin{v};\n    if isKey(params_to_variables,param_name)\n      assert(v+1<=numel(varargin));\n      v = v+1;\n      % Trick: use feval on anonymous function to use assignin to this workspace\n      feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n    else\n      error('Unsupported parameter: %s',varargin{v});\n    end\n    v=v+1;\n  end\n\n  dim = size(V,2);\n  C = cotangent(V,F);\n\n  n = size(V,1);\n  m = size(F,1);\n  switch energy\n  case 'spokes'\n    nr = size(V,1);\n    edge_set = cell(nr,1);\n    switch size(F,2)\n    case 4\n      AC = sparse( ...\n        F(:,[2 3 1 4 4 4 3 1 2 1 2 3]),F(:,[3 1 2 1 2 3 2 3 1 4 4 4]), ...\n        [C C],n,n);\n    case 3\n      AC = sparse(F(:,[2 3 1 3 1 2]),F(:,[3 1 2 2 3 1]),[C C],n,n);\n    end\n    % loop over vertices\n    for r = 1:nr\n      [Jr,~,Cr] = find(AC(:,r));\n      Ir = repmat(r,numel(Jr),1);\n      edge_set{r}.E = [Ir Jr];\n      edge_set{r}.C = Cr;\n    end\n  case {'elements','spokes-and-rims'}\n    nr = size(F,1);\n    switch size(F,2)\n    case 3\n      I = F(:,[2 3 1]);\n      J = F(:,[3 1 2]);\n    case 4\n      I = F(:,[2 3 1 4 4 4]);\n      J = F(:,[3 1 2 1 2 3]);\n    end\n    edge_set = cell(nr,1);\n    % loop over elements\n    for r = 1:nr\n      edge_set{r}.E = [I(r,:)' J(r,:)'];\n      edge_set{r}.C = C(r,:);\n    end\n    if strcmp(energy,'spokes-and-rims')\n      Fedge_set = edge_set;\n      nr = size(V,1);\n      edge_set = cell(nr,1);\n      V2F = sparse( ...\n        F,repmat(1:size(F,1),size(F,2),1)',repmat(1:size(F,2),size(F,1),1),n,m);\n      % loop over vertices\n      for r = 1:nr\n        [~,Fr] = find(V2F(r,:));\n        edge_set{r}.E = [];\n        edge_set{r}.C = [];\n        for f = Fr\n          edge_set{r}.E = [edge_set{r}.E;Fedge_set{f}.E];\n          edge_set{r}.C = [edge_set{r}.C Fedge_set{f}.C];\n        end\n      end\n\n    end\n\n  end\n\n  ER = zeros(nr,1);\n  % loop over rotations\n  for r = 1:nr\n    % get edges for this rotation\n    Er = edge_set{r}.E;\n    Cr = edge_set{r}.C;\n    S = zeros(dim,dim);\n    % loop over edges to build covariance matrix for rotation fitting\n    for e = 1:size(Er,1)\n      i = Er(e,1);\n      j = Er(e,2);\n      ev = V(j,:)-V(i,:);\n      eu = U(j,:)-U(i,:);\n      S = S + Cr(e) * eu'*ev;\n    end\n    R = fit_rotation(S);\n    % Loop over edges to compute energy contribution\n    for e = 1:size(Er,1)\n      i = Er(e,1);\n      j = Er(e,2);\n      ev = V(j,:)-V(i,:);\n      eu = U(j,:)-U(i,:);\n      %ER(r) = ER(r) + 0.5 * Cr(e) * (eu - ev*R)*(eu - ev*R)';\n      %ER(r) = ER(r) + 0.5 * Cr(e) * (eu*eu' - 2*ev*R*eu' + ev*R*R'*ev');\n      ER(r) = ER(r) + 0.5 * Cr(e) * (eu*eu' - 2*ev*R*eu' + ev*ev');\n    end\n  end\n  E = sum(ER);\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/arap_energy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5526624570985808}}
{"text": "function [x, infos] = incremental_mu_nmf(V, rank, in_options)\n% Incremental non-negative matrix factorization (NMF) with outliers (INCNMF) algorithm.\n%\n% Inputs:\n%       matrix      V\n%       rank        rank\n%       in_options  options\n% Output:\n%       w           solution of w\n%       infos       information\n%\n% References:\n%       S. S. Bucak, B. Gunsel,\n%       \"Incremental Subspace Learning via Non-negative Matrix Factorization,\"\n%       Pattern Recognition, 2009.\n%    \n%\n% This file is part of NMFLibrary.\n%\n% Created by H.Kasai on Feb. 12, 2017\n%\n% Change log: \n%\n%       Oct. 27, 2017 (Hiroyuki Kasai): Fixed algorithm. \n%\n%       May. 20, 2019 (Hiroyuki Kasai): Added initialization module.\n%\n%       Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n    % set dimensions and samples\n    [m, n] = size(V);\n\n    % set local options\n    local_options = [];\n    local_options.max_inneriter     = 1;\n    local_options.online            = 0;\n    local_options.tolcostdegrease   = 1e-8;\n    local_options.alpha             = 0.5;  \n    local_options.beta              = 0.5;     \n    \n    % check input options\n    if ~exist('in_options', 'var') || isempty(in_options)\n        in_options = struct();\n    end      \n    % merge options\n    options = mergeOptions(get_nmf_default_options(), local_options);   \n    options = mergeOptions(options, in_options); \n    \n    % initialize factors\n    init_options = options;\n    [init_factors, ~] = generate_init_factors(V, rank, init_options);    \n    W = init_factors.W;\n    H = init_factors.H; \n\n    % initialize\n    method_name = 'Incremental-MU';     \n    epoch = 0;\n    grad_calc_count = 0;\n\n    if options.verbose > 0\n        fprintf('# %s: started ...\\n', method_name);           \n    end      \n    \n    if options.online\n        ht = H(:, end); %why\n    else\n        % Do nothing\n    end\n    A = V * H';\n    B = H * H';\n    \n    % store initial info\n    clear infos;\n    [infos, f_val, optgap] = store_nmf_info(V, W, H, [], options, [], epoch, grad_calc_count, 0);\n    \n    if options.verbose > 1\n        fprintf('%s: Epoch = 0000, cost = %.16e, optgap = %.4e\\n', method_name, f_val, optgap); \n    end\n    \n    % set start time\n    start_time = tic();\n     \n    % main outer loop\n    while true\n        \n        % check stop condition\n        [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n        if stop_flag\n            display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n            break;\n        end  \n        \n        % main inner loop\n        for t = 1 : options.batch_size : n - 1\n              \n            vt = V(:, t:t+options.batch_size -1);\n            \n            % Need to be considered more carefully\n            if options.online\n                % Do nothing (??)\n            else\n                ht = H(:, t:t+options.batch_size-1);\n            end\n            \n            for j = 1 : options.max_inneriter\n                \n                % Compute new ht (column vector at t)\n                ht = ht .* (W' * vt) ./ (W' * (W * ht) + 1e-9); \n                ht = ht + (ht<eps) .* eps; \n\n                % Compute new W\n                vht = vt * ht';\n                hht = ht * ht';\n                A_tmp = options.beta * A + options.alpha * vht;\n                B_tmp = options.beta * B + options.alpha * hht;\n                W = W .* ( A_tmp ./ (W * B_tmp + 1e-9) ); % Add 1e-9 to avoid 0 in the denom.\n                W = W + (W<eps) .* eps;\n                \n               if j > 1\n                    oldobj = newobj;\n                end\n                newobj = ((sum(sum((vt-W*ht).^2)))/m);\n                \n                if options.verbose > 2\n                    fprintf('\\t[%d-%d-%d] %e\\n', epoch, t, j, newobj);\n                end\n\n                if j > 1 && (oldobj-newobj)/newobj < options.tolcostdegrease\n                    break;\n                end                \n\n            end\n            \n            grad_calc_count = grad_calc_count + m * options.batch_size;            \n            \n            % update A and B\n            A = options.beta * A + options.alpha * vht;\n            B = options.beta * B + options.alpha * hht;     \n            \n            % update ht (columb of H at t)\n            H(:,t:t+options.batch_size-1) = ht;             \n            \n            if options.verbose > 2\n                % measure cost \n                f_val = nmf_cost(V, W, H, []);\n                fprintf('%s: inner [%03d-%03d] %e\\n', method_name, epoch, t, f_val);\n            end            \n        end\n        \n        % measure elapsed time\n        elapsed_time = toc(start_time);        \n        \n        % update epoch\n        epoch = epoch + 1;    \n\n        % store info\n        infos = store_nmf_info(V, W, H, [], options, infos, epoch, grad_calc_count, elapsed_time);  \n        \n        % display info\n        display_info(method_name, epoch, infos, options);\n\n    end \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/online/incremental_mu_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5526624545274356}}
{"text": "function  [fx,dfdx,dfdp] = f_Qlearning(x,P,u,in)\n% // VBA toolbox //////////////////////////////////////////////////////////\n%\n% [fx,dfdx,dfdP] = f_Qlearning(x,P,u,in)\n% Reinforcement-learning evolution function for a n-armed bandit task\n%\n% An RL agent learns by trial and error. A bandit task is such that, after\n% each action, the agent receives a feedback (reward if positive,\n% punishment if negative). The RL agent updates its action values as\n% follows:\n% V(chosen action) = V(chosen action) + alpha*(feedback-V(chosen action))\n% V(unchosen action) = V(unchosen action)\n% IN: \n%\t- x: action values (n x 1)\n%\t- P: learning rate (will be sigmoid transformed)\n%\t- u: (1) previous action \n%        (2) feedback received for previous action\n%\t- in: [useless]\n% OUT:\n%   - fx: updated action values\n%   - dfdx/dfdP: gradients for VBA inversion\n\n% /////////////////////////////////////////////////////////////////////////\n\n\n% Get parameter values\n% =========================================================================\n% Some of the model parameters can only take values within a certain range.\n% However, the VBA toolbox can only perform estimation of unbounded values.\n% To solve this, we transform the values passed by VBA to map them on the\n% acceptable range for each parameter.\n\n% learning rate \nalpha = VBA_sigmoid(P); % [-Inf,Inf] -> [0 1]\n\n\n% Apply delta-rule to update action values\n% =========================================================================\n\n% get experimental conditions\nprevActionIdx = u(1)+1; % action 0 is first index\nfeedback = u(2);\n\n% start with previous values\nfx = x; \n\n% udpdate previous action value\ndelta = feedback - x(prevActionIdx);\nfx(prevActionIdx) = x(prevActionIdx) + alpha*delta; % update chosen value\n\n\n% Compute evolution function's gradient\n% =========================================================================\n% This is not necessary, as the toolbox will approximate those gradients if\n% needed. However, providing the analytical gradient can higly speed-up the\n% inversion.\n\nn = numel(x);\n\n% derivative w.r.t hidden state\n% -------------------------------------------------------------------------\ndfdx = eye(n);\ndfdx(prevActionIdx,prevActionIdx) = 1 - alpha;\n\n% derivative w.r.t parameters\n% -------------------------------------------------------------------------\ndfdp = zeros(1,n);\ndfdp(prevActionIdx) = alpha*(1-alpha)*delta;\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_Qlearning.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5526624514144813}}
{"text": "% Digital Video Stabilization and Rolling Shutter Correction using Gyroscopes\n% Copyright (C) 2011 Alexandre Karpenko\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% 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 <http://www.gnu.org/licenses/>.\n\nfunction W = imalign(T, I, p)\n% align the template image T to the input image I\n\nif size(T,3) == 3\n    T = rgb2gray(T);\nend\nif size(I,3) == 3\n    I = rgb2gray(I);\nend\nif max(T(:)) > 1\n    T = double(T) / 255;\nend\nif max(I(:)) > 1\n    I = double(I) / 255;\nend\n\ngradTx = filter2(fspecial('sobel')', T);\ngradTy = filter2(fspecial('sobel') , T);\n%{\nfigure(1); showim(reshape(gradTx, size(T)));\nfigure(2); showim(reshape(gradTy, size(T)));\npause;\n%}\n\nx = repmat((1:size(T,2)) , size(T,1), 1);\ny = repmat((1:size(T,1))', 1, size(T,2));\n\ngradT_dWdp = [gradTx(:) .* x(:) ...\n              gradTy(:) .* x(:) ...\n              gradTx(:) .* y(:) ...\n              gradTy(:) .* y(:) ...\n              gradTx(:)         ...\n              gradTy(:)         ];\n\nH = gradT_dWdp' * gradT_dWdp;\n\np = p(:);\n\nfor i=1:100\n    W = [1+p(1)  p(3)  p(5); ...\n          p(2)  1+p(4) p(6)];\n      \n    figure(1); clf;\n    imshow(imtransform(T,  maketform('affine', W'), 'XData', [1 size(I,2)], 'YData', [1 size(I,1)]));\n    hold on;\n    h = imshow(I);\n    set(h, 'AlphaData', 0.6);\n    pause(0.01);\n    \n    WI = imtransform(I,  maketform('affine', W'), 'XData', [1 size(I,2)], 'YData', [1 size(I,1)], 'FillValues', NaN);\n    errorIm = WI - T;\n    errorIm(isnan(errorIm)) = 0;\n    delp = H \\ (gradT_dWdp' * errorIm(:));\n    p = p + delp;\n    display(p);\nend", "meta": {"author": "alex-golts", "repo": "Video-Stabilization", "sha": "03455a8bb589cb8fcb1e6900cf59bc3d8cc24078", "save_path": "github-repos/MATLAB/alex-golts-Video-Stabilization", "path": "github-repos/MATLAB/alex-golts-Video-Stabilization/Video-Stabilization-03455a8bb589cb8fcb1e6900cf59bc3d8cc24078/imalign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5526624483015268}}
{"text": "function [beta_gibbs,F_gibbs,L_gibbs,phi_gibbs,sigma_gibbs,lambda_t_gibbs,sigma_t_gibbs,sbar,favar,It,Bu]=...\n    favar_stvol3gibbs(Xbart,Xt,yt,B0,phi0,alpha0,delta0,f0,upsilon0,betahat,sigmahat,gamma,G,I_o,omega,T,n,k,It,Bu,pick,pickf,favar,data_endo,lags)\n\n%% preliminaries\n% initialise variables\nnfactorvar=favar.nfactorvar;\nnumpc=favar.numpc;\nfavarX=favar.X(:,favar.plotX_index);\nonestep=favar.onestep;\nSigma=bear.nspd(favar.Sigma);\nLl=favar.L;\nfavar_X=favar.X;\n% load priors\nL0=favar.L0*eye(n);\na0=favar.a0;\nb0=favar.b0;\n% sigmahat=(1/T)*(EPS'*EPS);\n\n% preallocation\nLl_gibbs=zeros(size(Ll(:),1),It-Bu);\nR2_gibbs=zeros(size(favarX,2),It-Bu);\n\nif onestep==0 %static factors in this case\n    FY=data_endo;\n    pbstring='two-step'; %string for the progress bar\n    % elseif onestep==1\n    %     pbstring='one-step'; %string for the progress bar\nend\n\n\n% preliminary elements for the algorithm\n% compute the product G'*I_gamma*G (to speed up computations of deltabar)\nGIG=G'*I_o*G;\n% compute alphabar\nalphabar=T+alpha0;\n\n\n\n% initiate the Gibbs sampler\n% initiate the counting of iterations\ncount=1;\npickcount=1;\n% initiate the record matrices and cells\nbeta_gibbs=[];\nF_gibbs=[];\nL_gibbs=[];\nphi_gibbs=[];\nsigma_gibbs=[];\nlambda_t_gibbs={};\nsigma_t_gibbs={};\n\n\n\n% step 1: determine initial values for the algorithm\n\n% initial value for beta\nbeta=betahat;\nB=reshape(beta,k,n);\n% initial value for f_2,...,f_n\n% obtain the triangular factorisation of sigmahat\n[Fhat Lambdahat]=bear.triangf(sigmahat);\n% obtain the initial value for F\nF=Fhat;\n% obtain the inverse of Fhat\n[invFhat]=bear.invltod(Fhat,n);\n% create the cell storing the different vectors of invF\nFinv=cell(n,1);\n% store the vectors\nfor ii=2:n\n    Finv{ii,1}=invFhat(ii,1:ii-1);\nend\n% initial values for L\nL=zeros(T,1);\n% initial values for phi\nphi=1;\n\n\n\n% step 2: determine the sbar values and Lambda\nsbar=diag(Lambdahat);\nLambda=sparse(diag(sbar));\n% then determine sigma^(0)\nsigma=F*Lambda*F';\n\n\n% step 3: recover the series of initial values for lambda_1,...,lambda_T and sigma_1,...,sigma_T\nlambda_t=repmat(diag(sbar),1,1,T);\nsigma_t=repmat(sigmahat,1,1,T);\n\n% create a progress bar\nhbar = bear.parfor_progressbar(It,['Progress of the Gibbs sampler (',pbstring,').']);\n\n%% run the Gibbs sampler\nwhile count<=It\n    \n    % step 4: draw beta from its conditional posterior\n    % first compute the summations required for omegabar and betabar\n    summ1=zeros(k,k);\n    summ2=zeros(k,n);\n    % run the summation\n    for jj=1:T\n        prodt=Xt{jj,1}'*exp(-L(jj,1));\n        summ1=summ1+prodt*Xt{jj,1};\n        summ2=summ2+prodt*yt(:,:,jj)';\n    end\n    % then obtain the inverse of phi0\n    invphi0=diag(1./diag(phi0));\n    % obtain the inverse of phibar\n    invphibar=summ1+invphi0;\n    % recover phibar\n    C=chol(bear.nspd(invphibar),'Lower')';\n    invC=C\\speye(k);\n    phibar=invC*invC';\n    % recover Bbar\n    Bbar=phibar*(summ2+invphi0*B0);\n    % draw B from its posterior\n    B=bear.matrixndraw(Bbar,sigma,phibar,k,n);\n    % finally recover beta by vectorising\n    beta=B(:);\n    \n    \n    % step 5: draw the series f_2,...,f_n from their conditional posteriors\n    % recover first the residuals\n    for jj=1:T\n        epst(:,:,jj)=yt(:,:,jj)-Xbart{jj,1}*beta;\n    end\n    % then draw the vectors in turn\n    for jj=2:n\n        % first compute the summations required for upsilonbar and fbar\n        summ1=zeros(jj-1,jj-1);\n        summ2=zeros(jj-1,1);\n        % run the summation\n        for kk=1:T\n            prodt=epst(1:jj-1,1,kk)*exp(-L(kk,1));\n            summ1=summ1+prodt*epst(1:jj-1,1,kk)';\n            summ2=summ2+prodt*epst(jj,1,kk)';\n        end\n        summ1=(1/sbar(jj,1))*summ1;\n        summ2=(-1/sbar(jj,1))*summ2;\n        % then obtain the inverse of upsilon0\n        invupsilon0=diag(1./diag(upsilon0{jj,1}));\n        % obtain upsilonbar\n        invupsilonbar=summ1+invupsilon0;\n        C=chol(bear.nspd(invupsilonbar));\n        invC=C\\speye(jj-1);\n        upsilonbar=full(invC*invC');\n        % recover fbar\n        fbar=upsilonbar*(summ2+invupsilon0*f0{jj,1});\n        % finally draw f_i^(-1)\n        Finv{jj,1}=fbar+chol(bear.nspd(upsilonbar),'lower')*randn(jj-1,1);\n    end\n    % recover the inverse of F\n    invF=eye(n);\n    for jj=2:n\n        invF(jj,1:jj-1)=Finv{jj,1};\n    end\n    % eventually recover F\n    F=bear.invltod(invF,n);\n    % update sigma\n    sigma=F*Lambda*F';\n    \n    % step 6: draw phi from its conditional posterior\n    % estimate deltabar\n    deltabar=L'*GIG*L+delta0;\n    % draw the value phi_i\n    phi=bear.igrandn(alphabar/2,deltabar/2);\n    \n    % step 7: draw the series lambda_t from their conditional posteriors, t=1,...,T\n    % consider periods in turn\n    for kk=1:T\n        % a candidate value will be drawn from N(lambdabar,phibar)\n        % the definitions of lambdabar and phibar varies with the period, thus define them first\n        % if the period is the first period\n        if kk==1\n            lambdabar=(gamma*L(2,1))/(1/omega+gamma^2);\n            phibar=phi/(1/omega+gamma^2);\n            % if the period is the final period\n        elseif kk==T\n            lambdabar=gamma*L(T-1,1);\n            phibar=phi;\n            % if the period is any period in-between\n        else\n            lambdabar=(gamma/(1+gamma^2))*(L(kk-1,1)+L(kk+1,1));\n            phibar=phi/(1+gamma^2);\n        end\n        % now draw the candidate\n        cand=lambdabar+phibar^0.5*randn;\n        % compute the acceptance probability\n        prob=bear.mhprob3(cand,L(kk,1),sbar,epst(:,1,kk),Finv,n);\n        % draw a uniform random number\n        draw=rand;\n        % keep the candidate if the draw value is lower than the prob\n        if draw<=prob\n            L(kk,1)=cand;\n            % if not, just keep the former value\n        end\n    end\n    % then recover the series of matrices lambda_t and sigma_t\n    for kk=1:T\n        lambda_t(:,:,kk)=exp(L(kk,1))*diag(sbar);\n        sigma_t(:,:,kk)=F*lambda_t(:,:,kk)*F';\n    end\n    \n    %% Sample Sigma and Ll (static)\n    [Sigma,Ll]=bear.favar_SigmaL(Sigma,Ll,nfactorvar,numpc,onestep,n,favar_X,FY,a0,b0,T,lags,L0);\n    \n    %% record phase\n    % if the burn-in sample phase is not yet over\n    if count<=Bu\n        % simply add 1 to the iteration count\n        count=count+1;\n        % on the other hand, if the burn-in sample phase is over\n    elseif count>Bu\n        % adding one iteration to the count will depend on wether post-burn selection applies\n        % if there is no post burn selection\n        if pick==0\n            % record the results\n            beta_gibbs(:,count-Bu)=beta;\n            F_gibbs(:,:,count-Bu)=F;\n            L_gibbs(:,:,count-Bu)=L;\n            phi_gibbs(count-Bu,1)=phi;\n            sigma_gibbs(:,count-Bu)=sigma(:);\n            % save the factors and loadings (keep the notation in the code consistent, although - except L - they don't change)\n            Ll_gibbs(:,count-Bu)=Ll(:);\n            \n            % compute R2 (Coefficient of Determination) for plotX variables (keep the notation in the code consistent, although they don't change)\n            R2=bear.favar_R2(favarX,FY);\n            R2_gibbs(:,count-Bu)=R2(:);\n            for jj=1:T\n                lambda_t_gibbs{jj,1}(:,:,count-Bu)=lambda_t(:,:,jj);\n                sigma_t_gibbs{jj,1}(:,:,count-Bu)=sigma_t(:,:,jj);\n            end\n            % then add one to the count\n            count=count+1;\n            % if there is post burn selection, only one draw over 'fpick' draws will be retained\n        elseif pick==1\n            % if the iteration does not correspond to fpick, don't record the results, don't increase the regular count, but do increase pickcount by 1, and do record the acceptance rate of the Metropolis-Hastings step\n            if pickcount~=pickf\n                pickcount=pickcount+1;\n                % on the other hand, if the iteration does correspond to fpick\n            elseif pickcount==pickf\n                % do record the results\n                beta_gibbs(:,count-Bu)=beta;\n                F_gibbs(:,:,count-Bu)=F;\n                L_gibbs(:,:,count-Bu)=L;\n                phi_gibbs(count-Bu,1)=phi;\n                sigma_gibbs(:,count-Bu)=sigma(:);\n                % save the factors and loadings (keep the notation in the code consistent, although - except L - they don't change)\n                Ll_gibbs(:,count-Bu)=Ll(:);\n                \n                % compute R2 (Coefficient of Determination) for plotX variables (keep the notation in the code consistent, although they don't change)\n                R2=bear.favar_R2(favarX,FY);\n                R2_gibbs(:,count-Bu)=R2(:);\n                for jj=1:T\n                    lambda_t_gibbs{jj,1}(:,:,count-Bu)=lambda_t(:,:,jj);\n                    sigma_t_gibbs{jj,1}(:,:,count-Bu)=sigma_t(:,:,jj);\n                end\n                % then increase the regular count by 1 and re-initialise pickcount\n                count=count+1;\n                pickcount=1;\n            end\n        end\n    end\n    \n    % update progress by one iteration\n    hbar.iterate(1);\n    \nend\n\n% in case we have thinning of the draws,\nthin=abs(round(favar.thin)); % should be a positive integer\nif thin~=1\n    beta_gibbs=beta_gibbs(:,thin:thin:end);\n    F_gibbs=F_gibbs(:,thin:thin:end);\n    L_gibbs=L_gibbs(:,thin:thin:end);\n    phi_gibbs=phi_gibbs(:,thin:thin:end);\n    sigma_gibbs=sigma_gibbs(:,thin:thin:end);\n    Ll_gibbs=Ll_gibbs(:,thin:thin:end);\n    R2_gibbs=R2_gibbs(:,thin:thin:end);\n    for jj=1:T\n        lambda_t_gibbs=lambda_t_gibbs(:,:,thin:thin:end);\n        sigma_t_gibbs=sigma_t_gibbs(:,:,thin:thin:end);\n    end\n    It=(1/thin)*It;\n    Bu=(1/thin)*Bu;\nend\n\n% save in favar structure\nfavar.L_gibbs=Ll_gibbs;\nfavar.R2_gibbs=R2_gibbs;\n\nclose(hbar);   %close progress bar\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/favar_stvol3gibbs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5526624457303818}}
{"text": "function [stat,pval,statAll,pvalAll]=grangercause(y,constant,lags,het,uncorr,inference)\n% Granger causality testing with a variance-covariance matrix estimated under a variety of\n% assumptions on the covariance of the errors:\n%   * Conditionally Homoskedastic and Uncorrelated\n%   * Conditionally Homoskedastic but Correlated\n%   * Heteroskedastic but Conditionally Uncorrelated\n%   * Heteroskedastic and Correlated\n%\n% USAGE:\n%   [STAT] = grangercause(Y,CONSTANT,LAGS)\n%   [STAT,PVAL,STATALL,PVALALL] = grangercause(Y,CONSTANT,LAGS,HET,UNCORR,INFERENCE)\n%\n% INPUTS:\n%   Y             - A T by K matrix of data\n%   CONSTANT      - Scalar variable: 1 to include a constant, 0 to exclude\n%   LAGS          - Non-negative integer vector representing the VAR orders to include in the model.\n%   HET           - [OPTIONAL] A scalar integer indicating the type of covariance estimator\n%                      0 - Homoskedastic\n%                      1 - Heteroskedastic [DEFAULT]\n%   UNCORR        - [OPTIONAL] A scalar integer indicating the assumed structure of the error\n%                     covariance matrix\n%                      0 - Correlated errors  [DEFAULT]\n%                      1 - Uncorrelated errors\n%   INFERENCE     - [OPTIONAL] Inference method\n%                      1 - Likelihood ratio [DEFAULT]\n%                      2 - LM test\n%                      3 - Wald test\n%\n% OUTPUTS:\n%   STAT          - K by K matrix of Granger causality statistics computed using the specified\n%                     covariance estimator and inference method. STAT(i,j) corresponds to a test that\n%                     y(i) is not caused by y(j)\n%   PVAL          - K by K matrix of p-values corresponding to STAT\n%   STATALL       - K by 1 vector of Granger causality statistics computed using the specified\n%                     covariance estimator and inference method. STATALL(i) corresponds to a test that\n%                     y(i) is not caused by any y(j), j neq i\n%   PVALALL       - K by 1 vector of p-values corresponding to STATALL\n%\n% COMMENTS:\n%   Granger causality tests based on a VAR including any lags.\n%\n%   y(:,t)' = CONST + P(1) * y(:,y-1) + P(2)*y(:,y-2) + ... + P(1)*y(:,t-K)'\n%\n%   where P(j) are K by K parameter matrices and CONST is a K by 1 parameter matrix (if CONSTANT==1)\n%\n% EXAMPLE:\n%   Conduct GC testing in a VAR(1) with a constant\n%        parameters = grangercause(y,1,1)\n%   Conduct GC testing in a VAR(3) with no constant\n%        parameters = grangercause(y,0,[1:3])\n%   Conduct GC testing in a VAR that includes lags 1 and 3 with a constant\n%        parameters = grangercause(y,1,[1 3])\n%\n% See also VECTORAR, VECTORARVCV\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3.0    Date: 1/1/2007\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin<3 || nargin>6\n    error('3 to 6 inputs required')\nend\nif nargin==3\n    het=1;\n    uncorr=0;\n    inference=1;\nelseif nargin==4\n    uncorr=0;\n    inference=1;\nelseif nargin==5\n    inference=1;\nend\n% Check Y\nif ndims(y)~=2\n    error('Y must be T by K')\nend\n% Check constant\nif ~isscalar(constant)\n    error('CONSTANT must be either 0 or 1')\nend\nif ~ismember(constant,[0 1])\n    error('CONSTANT must be either 0 or 1')\nend\n% Check lags\nif ndims(lags)~=2\n    error('LAGS must be a vector of positive integers containing lags to include')\nend\nif size(lags,1)>size(lags,2)\n    lags = lags';\nend\nif ~all(lags>0)\n    error('LAGS must be a vector of positive integers containing lags to include')\nend\nif ~all(floor(lags)==lags)\n    error('LAGS must be a vector of positive integers containing lags to include')\nend\nif length(lags)~=length(unique(lags))\n    error('LAGS must be a vector of unique elements')\nend\nlags=sort(lags);\n% Check het\nif ~isscalar(het)\n    error('HET must be either 0 or 1')\nend\nif ~ismember(het,[0 1])\n    error('HET must be either 0 or 1')\nend\n% Check uncorr\nif ~isscalar(uncorr)\n    error('UNCORR must be either 0 or 1')\nend\nif ~ismember(uncorr,[0 1])\n    error('UNCORR must be either 0 or 1')\nend\n% Inference mathod\nif ~isscalar(inference)\n    error('INFERENCE must be either 0 or 1')\nend\nif ~ismember(inference,[1 2 3])\n    error('INFERENCE must be either 0 or 1')\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% Inference Methods\n% 1. LR MLE : Relatively easy, need to iteratively depete the correct\n% columns and reestimate.  Use a LR test\n% 2. Wald: Just compute the VCV, then figure out how to select the correct\n%       rows, and you are done\n% 3. LM: Have to re-estimate under the null and use those errors to compute\n%       the scores.  Test is based on scores.\n% 4. LR Robust: Just like LM above but using errors estimated under the\n%       alternative\n\n\n% LR MLE\n% First generate the unrestricted errors, then iterate across series and\n% drop regressors\n\nT=size(y,1);\nK=size(y,2);\nP=length(lags);\nm=max(lags);\nylags=cell(K,1);\nfor k=1:K\n    ytemp = [ones(m,1)*mean(y(:,k));\n        y(:,k)];\n    [nothing,ylags{k}]=newlagmatrix(ytemp,m,0);\nend\n\nX=zeros(T,K+constant);\nindex=1;\nif constant\n    X(:,1)=ones(T,1);\n    index=index+1;\nend\np=length(lags);\nfor i=1:p\n    for k=1:K\n        X(:,index)=ylags{k}(:,lags(i));\n        index=index+1;\n    end\nend\n\n% Each column contains the parameters for a single y\nparamvec = X\\y;\nerrors = y-X*paramvec;\ns2=errors'*errors/T;\ne=cell(K,K);\nfor i=1:K\n    for j=1:K\n        % i will be the LHS variable, j will be the lags\n        tempX=X;\n        allcols = 1:size(X,2);\n        % Drop columns j, K+j, 2K+j,...P(K-1)*j (+constant if present)\n        if constant\n            drop = (j:K:size(X,2)-1)+constant;\n        else\n            drop = (j:K:size(X,2));\n        end\n        remain = setdiff(allcols,drop);\n        beta = tempX(:,remain)\\y(:,i);\n        % These errors are estiamted under the null and can be used for LR and LM testing\n        e{i,j} = y(:,i)-tempX(:,remain)*beta;\n    end\nend\n% Construct the regressions needed to test the \"all\" hypothesis\neall = cell(K,1);\nfor i=1:K\n    tempX = X;\n    % Keep columns i, K+i, 2K+i, P(K-1)*i (+constant if present)\n    if constant\n        remain = [constant (i:K:(size(X,2)-1))+constant];\n    else\n        remain = i:K:size(X,2);\n    end\n    beta = tempX(:,remain)\\y(:,i);\n    eall{i} = y(:,i)-tempX(:,remain)*beta;\nend\n\nNp = p*K+constant;\nstat = zeros(K);\nstatAll = zeros(K,1);\n% Homoskedastic Likelihood Ratio\nif inference==1 && het==0\n    for i=1:K\n        for j=1:K\n            e2=errors;\n            e2(:,i)=e{i,j};\n            sR=e2'*e2/T;\n            stat(i,j)=(T-P*K^2+P)*(log(det(sR))-log(det(s2)));\n        end\n    end\n    for i=1:K\n        e2=errors;\n        e2(:,i) = eall{i};\n        sR=e2'*e2/T;\n        statAll(i)=(T-P*K^2+(K-1)*P)*(log(det(sR))-log(det(s2)));\n    end\n    % Heteroskedasticity robust LR;  key here is score covariance is computed\n    % using errors estimated under the alternative\nelseif inference==1 && het==1\n    for i=1:K\n        for j=1:K\n            e2=errors;\n            e2(:,i)=e{i,j};\n            X2=repmat(X,1,K);\n            e2=reshape(repmat(e2,Np,1),T,K*Np);\n            s=X2.*e2;\n            sbar=mean(s);\n            % Estimate S using the errors, not e2\n            S=vectorarscorecov(errors,X,het,uncorr,K,T,Np);\n            stat(i,j)=(T-P*K^2+P)*sbar*S^(-1)*sbar';\n        end\n    end\n    for i=1:K\n        e2=errors;\n        e2(:,i)=eall{i};\n        X2=repmat(X,1,K);\n        e2=reshape(repmat(e2,Np,1),T,K*Np);\n        s=X2.*e2;\n        sbar=mean(s);\n        % Estimate S using the errors, not e2\n        S=vectorarscorecov(errors,X,het,uncorr,K,T,Np);\n        statAll(i)=(T-P*K^2+(K-1)*P)*sbar*S^(-1)*sbar';\n    end\n    % All LM tests since function will handle;  the key here is that the errors\n    % are computed under the null\nelseif inference==2\n    for i=1:K\n        for j=1:K\n            e2=errors;\n            e2(:,i)=e{i,j};\n            X2=repmat(X,1,K);\n            e2=reshape(repmat(e2,Np,1),T,K*Np);\n            s=X2.*e2;\n            sbar=mean(s);\n            e2=errors;\n            e2(:,i)=e{i,j};\n            S=vectorarscorecov(e2,X,het,uncorr,K,T,Np);\n            stat(i,j)=(T-P*K^2+P)*sbar*S^(-1)*sbar';\n        end\n    end\n    for i=1:K\n        e2=errors;\n        e2(:,i)=eall{i};\n        X2=repmat(X,1,K);\n        e2=reshape(repmat(e2,Np,1),T,K*Np);\n        s=X2.*e2;\n        sbar=mean(s);\n        e2=errors;\n        e2(:,i)=eall{i};\n        S=vectorarscorecov(e2,X,het,uncorr,K,T,Np);\n        statAll(i)=(T-P*K^2+(K-1)*P)*sbar*S^(-1)*sbar';\n    end\n    % Wald tests\nelseif inference==3\n    XpXi = ((X'*X)/T)^(-1);\n    Ainv = kron(eye(K),XpXi);\n    B = vectorarscorecov(errors,X,het,uncorr,K,T,Np);\n    V = Ainv*B*Ainv;\n    %Vinv=V^(-1);\n    % Now I have to cleverly select the parameters to set to 0 and then\n    % compute the wald tests\n    % Easier to iterate over the j's in the inside loop\n    for i=1:K\n        for j=1:K\n            temp=zeros(size(paramvec))';\n            % Select the columns of the parameters to test\n            if constant\n                pl = (j:K:size(X,2)-1)+constant;\n            else\n                pl = (j:K:size(X,2));\n            end\n            \n            temp(i,pl)=1;\n            temp=temp';\n            temp=temp(:);\n            pl = find(temp);\n            p = paramvec;\n            p = p(:);\n            stat(i,j)=(T-P*K^2+P)*(p(pl)'*V(pl,pl)^(-1)*p(pl));\n        end\n    end\n    for i=1:K\n        temp=zeros(size(paramvec))';\n        % Select the columns of the parameters to test\n        if constant\n            remain = [constant (i:K:size(X,2)-1)+constant];\n        else\n            remain = (i:K:size(X,2)-1);\n        end\n        pl = setdiff(1:size(X,2),remain);\n        temp(i,pl)=1;\n        temp=temp';\n        temp=temp(:);\n        pl = find(temp);\n        p = paramvec;\n        p = p(:);\n        statAll(i)=(T-P*K^2+(K-1)*P)*(p(pl)'*V(pl,pl)^(-1)*p(pl));\n    end\nend\n% All stats have the same dist\npval=1-chi2cdf(stat,length(lags));\npvalAll = 1-chi2cdf(statAll,(K-1)*length(lags));\n\n\n\nfunction S=vectorarscorecov(errors,X,het,uncorr,K,T,Np)\ns2=errors'*errors/T;\nXpX=X'*X/T;\nif ~het && uncorr\n    S=kron(diag(diag(s2)),XpX);\nelseif ~het && ~uncorr\n    S=kron(s2,XpX);\nelseif het && uncorr\n    X2=repmat(X,1,K);\n    e2=reshape(repmat(errors,Np,1),T,K*Np);\n    s=X2.*e2;\n    s=s-repmat(mean(s),T,1);\n    S=zeros(Np*K);\n    for i=1:K\n        sel=(i-1)*Np+1:i*Np;\n        temp = s(:,sel);\n        S(sel,sel)=temp'*temp/T;\n    end\nelseif het && ~uncorr\n    X2=repmat(X,1,K);\n    e2=reshape(repmat(errors,Np,1),T,K*Np);\n    s=X2.*e2;\n    s=s-repmat(mean(s),T,1);\n    S=s'*s/T;\nend\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/timeseries/grangercause.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5526567534027967}}
{"text": "%SerialLink.jacob_dot Derivative of Jacobian\n%\n% JDQ = R.jacob_dot(Q, QD) is the product (6x1) of the derivative of the\n% Jacobian (in the world frame) and the joint rates.\n%\n% Notes::\n% - This term appears in the formulation for operational space control XDD = J(Q)QDD + JDOT(Q)QD\n% - Written as per the reference and not very efficient.\n%\n% References::\n% - Fundamentals of Robotics Mechanical Systems (2nd ed)\n%   J. Angleles, Springer 2003.\n% - A unified approach for motion and force control of robot manipulators: The operational space formulation\n%  O Khatib, IEEE Journal on Robotics and Automation, 1987.\n%\n% See also SerialLink.jacob0, diff2tr, tr2diff.\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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\nfunction Jdot = jacob_dot(robot, q, qd)\n\n\tn = robot.n;\n    links = robot.links;\n\n    % Using the notation of Angeles:\n    %   [Q,a] ~ [R,t] the per link transformation\n    %   P ~ R   the cumulative rotation t2r(Tj) in world frame\n    %   e       the last column of P, the local frame z axis in world coordinates\n    %   w       angular velocity in base frame\n    %   ed      deriv of e\n    %   r       is distance from final frame\n    %   rd      deriv of r\n    %   ud      ??\n\n    for i=1:n\n        T = links(i).A(q(i));\n        Q{i} = t2r(T);\n        a{i} = transl(T)';\n    end\n\n    P{1} = Q{1};\n    e{1} = [0 0 1]';\n    for i=2:n\n        P{i} = P{i-1}*Q{i};\n        e{i} = P{i}(:,3);\n    end\n\n    % step 1\n    w{1} = qd(1)*e{1};\n    for i=1:(n-1)\n        w{i+1} = qd(i+1)*[0 0 1]' + Q{i}'*w{i};\n    end\n\n    % step 2\n    ed{1} = [0 0 0]';\n    for i=2:n\n        ed{i} = cross(w{i}, e{i});\n    end\n\n    % step 3\n    rd{n} = cross( w{n}, a{n});\n    for i=(n-1):-1:1\n        rd{i} = cross(w{i}, a{i}) + Q{i}*rd{i+1};\n    end\n\n    r{n} = a{n};\n    for i=(n-1):-1:1\n        r{i} = a{i} + Q{i}*r{i+1};\n    end\n\n    ud{1} = cross(e{1}, rd{1});\n    for i=2:n\n        ud{i} = cross(ed{i}, r{i}) + cross(e{i}, rd{i});\n    end\n\n    % step 4\n    %  swap ud and ed\n    v{n} = qd(n)*[ud{n}; ed{n}];\n    for i=(n-1):-1:1\n        Ui = blkdiag(Q{i}, Q{i});\n        v{i} = qd(i)*[ud{i}; ed{i}] + Ui*v{i+1};\n    end\n\n    Jdot = v{1};\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/@SerialLink/jacob_dot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7185943865443352, "lm_q1q2_score": 0.5526567335545048}}
{"text": "function [ a, b ] = p04_ab ( m )\n\n%*****************************************************************************80\n%\n%% P04_AB returns bounds for problem 4.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    15 February 2012\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, integer M, the spatial dimension.\n%\n%    Output, real A(M,1), B(M,1), lower and upper bounds.\n%\n  a(1:m,1) = 0.0;\n  b(1:m,1) = 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_opt_con/p04_ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.55265673272298}}
{"text": "function [rpm] = THz2rpm(THz)\n% Convert frequency from terahertz to revolutions per minute.\n% Chad A. Greene 2012\nrpm = THz*60*1e+12;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/THz2rpm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5526229661409883}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D \n% shape modeling and analysis toolkit. \n% It is a software package developed at Shenlab in Center for Neuroimaging, \n% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)\n% It is available to the scientific community as copyright freeware \n% under the terms of the GNU General Public Licence.\n% \n% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University\n% \n% This file is part of SPHARM-MAT.\n% \n% SPHARM-MAT is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% SPHARM-MAT is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with SPHARM-MAT. If not, see <http://www.gnu.org/licenses/>.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction performPCA(confs, objs)\n\nnumSbj = length(objs);\ngroupID = confs.GroupID;\n\n% set parameters\nfvecs = [];\t% fvecs is accumulator of coefficients from each species.\nkeep = numSbj-1;\t% number of eigenvectors to keep\n\n% do processing of each file\nfor i = 1:numSbj\n\t% read in file.\n\tfile = objs{i};\n\tload(file);\n\t[path, name, ext] = fileparts(file);\n\tclear('faces', 'vertices', 'sph_verts');\n\n\t[nrows ncols] = size(fvec);\n\ttemp = fvec.';\n\ttemp = reshape(temp, (nrows*3), 1);\n\tfvecs = [fvecs temp];\nend\nclear('fvec', 'temp', 'name');\n\nfvecs = fvecs.';\n[eigenvecs, scores, eigenvals] = princomp(fvecs);\n% trace_eig = trace(eigenvals);\nperc_variance_explained = eigenvals/sum(eigenvals);\n\n% drop cells that are to not be kept\neigenvecs = eigenvecs(:,1:keep);\n%scores = scores(:,1:keep);\neigenvals = eigenvals(1:keep,1);\nperc_variance_explained = perc_variance_explained(1:keep,:);\ncum_percent_explained = cumsum(perc_variance_explained);\n\nnew_name = [confs.OutDirectory '/' confs.OutputName];\nif exist(new_name,'file')\n    prompt = {'Enter new filename:'};\n    dlg_title = 'New File Name';\n    num_lines = 1;\n    def = {new_name};\n    answer = inputdlg(prompt,dlg_title,num_lines,def);    \n    new_name = answer{1};\nend\n\nsave(new_name, 'fvecs', 'eigenvecs', 'eigenvals', 'perc_variance_explained', ... \n    'cum_percent_explained', 'scores','groupID');\n\nreturn;", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SpharmToolbox/code/performPCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5526229661409883}}
{"text": "function [image1,image2,img3]=mosaic_map(img1,img2,d)\n\n[m1,n1,p1] = size(img1);\nm11 = ceil(m1/d);\nn11 = ceil(n1/d);\nfor i=1:2:m11\n    for j=2:2:n11\n        img1((i-1)*d+1:i*d,(j-1)*d+1:j*d,:)=0;\n    end\nend\nfor i=2:2:m11\n    for j=1:2:n11\n        img1((i-1)*d+1:i*d,(j-1)*d+1:j*d,:)=0;\n    end\nend\nimage1=img1(1:m1,1:n1,:);\n\n%%\n[m2,n2,p2] = size(img2);\nm22 = ceil(m2/d);\nn22 = ceil(n2/d);\nfor i=1:2:m22\n    for j=1:2:n22\n       img2((i-1)*d+1:i*d,(j-1)*d+1:j*d,:)=0;\n    end\nend\nfor i=2:2:m22\n    for j=2:2:n22\n       img2((i-1)*d+1:i*d,(j-1)*d+1:j*d,:)=0;\n    end\nend\nimage2=img2(1:m2,1:n2,:);\n%%\nimg3=image1+image2;\n\nend\n", "meta": {"author": "LJY-RS", "repo": "RIFT-multimodal-image-matching", "sha": "7ea830e2f13cc3c226f975fe9e98b7666a8f26fb", "save_path": "github-repos/MATLAB/LJY-RS-RIFT-multimodal-image-matching", "path": "github-repos/MATLAB/LJY-RS-RIFT-multimodal-image-matching/RIFT-multimodal-image-matching-7ea830e2f13cc3c226f975fe9e98b7666a8f26fb/mosaic_map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.552622962198771}}
{"text": "function test_ft_mvaranalysis\n\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_mvaranalysis\n\nfs = 500;\nnchan = 32;\nstart_time = -1; %s\nend_time = 2.5; %s\nnsamples = (end_time - start_time) * fs + 1;\n\ndata = [];\ndata.time{1} = linspace(start_time, end_time, nsamples);\ndata.trial{1} = randn(nchan,nsamples);\ndata.label = cellstr(num2str((1:nchan).'));\n\ncfg = [];\ndataout = ft_mvaranalysis(cfg,data);\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_ft_mvaranalysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.552622962198771}}
{"text": "classdef madgwick < handle\n    methods (Static = true)\n        \n        function q = imu(q, Gyroscope, Accelerometer, SamplePeriod, Beta)\n            \n            % Normalise accelerometer measurement\n            acc = Accelerometer;\n            if(norm(acc) == 0), return; end   % handle NaN\n            acc = acc / norm(acc);  % normalise magnitude\n            \n            % Gradient decent algorithm corrective step\n            F = (quatrotate(q, [0 0 1]) - acc)';\n%             F = [2*(q(2)*q(4) - q(1)*q(3)) - Accelerometer(1)\n%                 2*(q(1)*q(2) + q(3)*q(4)) - Accelerometer(2)\n%                 2*(0.5 - q(2)^2 - q(3)^2) - Accelerometer(3)];\n\n            J = [-2*q(3),\t2*q(4),    -2*q(1),\t2*q(2)\n                2*q(2),     2*q(1),     2*q(4),\t2*q(3)\n                0,         -4*q(2),    -4*q(3),\t0    ];\n            step = (J'*F);\n            step = step / norm(step);\t% normalise step magnitude\n            \n            % Compute rate of change of quaternion\n            qd = 0.5 * quatmultiply(q, [0 Gyroscope]) - Beta * step';\n            \n            % Integrate to yield quaternion\n            q = q + qd * SamplePeriod;\n            q = q / norm(q); % normalise quaternion\n        end\n        \n        function q = ahrs(q, Gyroscope, Accelerometer, Magnetometer, SamplePeriod, Beta)\n            \n            % Normalise accelerometer measurement\n            if(norm(Accelerometer) == 0), return; end\t% handle NaN\n            acc = Accelerometer / norm(Accelerometer);\t% normalise magnitude\n            \n            % Normalise magnetometer measurement\n            if(norm(Magnetometer) == 0), return; end\t% handle NaN\n            mag = Magnetometer / norm(Magnetometer);\t% normalise magnitude\n            \n            % Reference direction of Earth's magnetic feild\n            h = quatrotate(quatconj(q), mag);\n            h = [0 h];\n            b = [0 norm([h(2) h(3)]) 0 h(4)];\n            \n            % Gradient decent algorithm corrective step\n             F= (quatrotate(q, [0 0 1]) - acc)';\n             F = [F;  (quatrotate(q, [b(2) 0 b(4)]) - mag)'];\n            \n%             F = [2*(q(2)*q(4) - q(1)*q(3)) - Accelerometer(1)\n%                 2*(q(1)*q(2) + q(3)*q(4)) - Accelerometer(2)\n%                 2*(0.5 - q(2)^2 - q(3)^2) - Accelerometer(3)\n%                 2*b(2)*(0.5 - q(3)^2 - q(4)^2) + 2*b(4)*(q(2)*q(4) - q(1)*q(3)) - Magnetometer(1)\n%                 2*b(2)*(q(2)*q(3) - q(1)*q(4)) + 2*b(4)*(q(1)*q(2) + q(3)*q(4)) - Magnetometer(2)\n%                 2*b(2)*(q(1)*q(3) + q(2)*q(4)) + 2*b(4)*(0.5 - q(2)^2 - q(3)^2) - Magnetometer(3)];\n            J = [-2*q(3),                 \t2*q(4),                    -2*q(1),                         2*q(2)\n                2*q(2),                 \t2*q(1),                    \t2*q(4),                         2*q(3)\n                0,                         -4*q(2),                    -4*q(3),                         0\n                -2*b(4)*q(3),               2*b(4)*q(4),               -4*b(2)*q(3)-2*b(4)*q(1),       -4*b(2)*q(4)+2*b(4)*q(2)\n                -2*b(2)*q(4)+2*b(4)*q(2),\t2*b(2)*q(3)+2*b(4)*q(1),\t2*b(2)*q(2)+2*b(4)*q(4),       -2*b(2)*q(1)+2*b(4)*q(3)\n                2*b(2)*q(3),                2*b(2)*q(4)-4*b(4)*q(2),\t2*b(2)*q(1)-4*b(4)*q(3),        2*b(2)*q(2)];\n            step = (J'*F);\n            step = step / norm(step);\t% normalise step magnitude\n            \n            % Compute rate of change of quaternion\n            qd = 0.5 * quatmultiply(q, [0 Gyroscope]) - Beta * step';\n\n            % Integrate to yield quaternion\n            q = q + qd * SamplePeriod;\n            q = q / norm(q); % normalise quaternion\n        end\n    end\nend", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/lib/ch_madgwick.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.5526126034660411}}
{"text": "function Mh = hmxFusion(Mh)\n%+========================================================================+\n%|                                                                        |\n%|         OPENHMX - LIBRARY FOR H-MATRIX COMPRESSION AND ALGEBRA         |\n%|           openHmx 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    \u00a0\u00a0\u00a0\u00a0         |\n%|                                                                        |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it.                                                      |\n%|________________________________________________________________________|\n%|   '&`   |                                                              |\n%|    #    |   FILE       : hmxFusion.m                                   |\n%|    #    |   VERSION    : 0.40                                          |\n%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |\n%|  ( # )  |   CREATION   : 14.03.2017                                    |\n%|  / 0 \\  |   LAST MODIF : 14.03.2018                                    |\n%| ( === ) |   SYNOPSIS   : Fusion and recompress for full, sparse and    |\n%|  `---'  |                low-rank leaves                               |\n%+========================================================================+\n\n%%% H-Matrix\nif (Mh.typ == 0)\n    % Check and convert leaf data\n    typ = zeros(1,4);\n    for i = 1:4\n        % Children data        \n        typ(i) = Mh.chd{i}.typ;\n        dat    = Mh.chd{i}.dat;        \n        tol    = Mh.chd{i}.tol;\n        dim    = size(Mh.chd{i});\n\n        % Full or sparse matrix\n        if (typ(i) == 2)\n            % Non zeros terms\n            n = nnz(dat);\n            \n            % Sparse\n            if issparse(dat)\n                % Compress\n                if (n == 0)\n                    A    = zeros(dim(1),0);\n                    B    = zeros(0,dim(2));\n                    flag = 1;\n                    \n                % Full\n                elseif (n > 1/4*prod(dim))\n                    dat  = full(dat);\n                    flag = 2;\n                    \n                % Sparse\n                else\n                    flag = 0;\n                end\n                \n            % Full\n            else\n                % Compress\n                if (n == 0)\n                    A    = zeros(dim(1),0);\n                    B    = zeros(0,dim(2));\n                    flag = 1;\n                    \n                % Sparse\n                elseif (n <= 1/4*prod(dim))\n                    dat  = sparse(double(dat));\n                    flag = 2;\n                 \n                % Compress\n                else\n                    [A,B,flag] = hmxSVD(dat,tol);\n                end\n            end\n            \n            % Update\n            if (flag == 1)\n                Mh.chd{i}.dat = {A,B};\n                Mh.chd{i}.typ = 1;\n                typ(i)        = 1;\n            \n            elseif (flag == 2)\n                Mh.chd{i}.dat = dat;\n            end\n        end\n    end\n    \n    % Low-rank fusion (QRSVD)\n    if (sum(typ==1) == 4)\n        % Rank for each leaf\n        rk = zeros(1,4);\n        nk = 0;\n        for i = 1:4\n            rk(i) = size(Mh.chd{i}.dat{1},2);\n            nk    = nk + sum(size(Mh.chd{i}))*rk(i); \n        end\n        \n        % Low rank matrix\n        A = zeros(size(Mh,1),sum(rk),class(Mh.pos{1}));\n        B = zeros(sum(rk),size(Mh,2),class(Mh.pos{2}));\n        j = 0;\n        for i = 1:4\n            A(Mh.row{i},j+(1:rk(i))) = Mh.chd{i}.dat{1};\n            B(j+(1:rk(i)),Mh.col{i}) = Mh.chd{i}.dat{2};            \n            j = j + rk(i);\n        end\n        \n        % Recompression\n        [A,B] = hmxQRSVD(A,B,Mh.tol);\n        \n        % Update\n        if (sum(size(Mh))*size(A,2) <= nk)  \n            Mh.typ = 1;\n            Mh.row = cell(1,4);\n            Mh.col = cell(1,4); \n            Mh.chd = cell(1,4);\n            Mh.dat = {A,B};\n        end\n    end\n    \n%%% Unavalaible case \nelse\n    error('hmxFusion.m : unavailable case')\nend\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/openHmx/hmxFusion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5526125831125717}}
{"text": "function varargout = acosh(varargin)\n\nswitch class(varargin{1})\n\n    case 'sdpvar'\n        varargout{1} = InstantiateElementWise(mfilename,varargin{:});\n\n    case 'char'\n\n        operator = CreateBasicOperator('positive','callback');   \n        operator.convexity = @convexity;\n        operator.bounds = @bounds;\n        operator.domain = [1 inf];                 \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)\nif xU<=-1\n    L = acosh(xU);\n    U = acosh(xL);\nelseif xL>=1\n    L = acosh(xL);\n    U = acosh(xU);\nelseif xU <= 1\n    L = 0;\n    U = acosh(xL);\nelse\n    L = 0;\n    U = acosh(xU);\nend\n\nfunction vexity = convexity(xL,xU)\nif xL >= 1\n    vexity = 'concave';\nelseif xU <= -1\n    vexity = 'concave';\nelse\n    vexity = 'none';\nend\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/acosh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5525957569793539}}
{"text": "function val = objective(guess,IC)\n\n%Runs a large number of simulations of the controlled simulation and then\n%returns a combination of state and actuation error\n\nduration = 3;  \ndt = 0.05;\nn = round(duration/dt);\n\nz = IC;\n\n%Weighting between relative cost. \nx_cost = 0.7^-2;\nv_cost = 1.5^-2;\nu_cost = 1.0^-2;\n\n%Run simulation using RK4 integration in parallel\nval = 0; %cost accumulator\nfor i=1:n\n    [k1, u] = rhs(z,guess);\n    k2 = rhs(z + 0.5*dt*k1,guess);\n    k3 = rhs(z + 0.5*dt*k2,guess);\n    k4 = rhs(z + k3,guess);\n    \n    z = z + (dt/6)*(k1 + 2*k2 + 2*k3 + k4);\n    \n    val = val + x_cost*sum(z(1,:).^2);\n    val = val + v_cost*sum(z(2,:).^2);\n    val = val + u_cost*sum(u.^2);\nend\n\nend\n\nfunction [xdot, u] = rhs(z,k)\n\nu = control(z,k);\nxdot = dynamics(z,u);\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/cmaes_controlDesign/objective.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5525957440931301}}
{"text": "function encmodel = standard_encoding(X,Y,T,options,binsize)\n% Compute maps representing the \"encoding\" model for each\n% time point (or window, see below) in the trial (i.e. a GML). \n% The reported statistic is the explained variance from\n% regressing Y on the data at this sensor/voxel.\n%\n% INPUT\n% X: Brain data, (time by regions) or (time by trials by regions)\n% Y: Stimulus, (time by q); q is no. of stimulus features OR\n%              (no.trials by q), meaning that each trial has a single\n%              stimulus value\n% T: Length of series\n% options: structure with the preprocessing options - see documentation in \n%                       https://github.com/OHBA-analysis/HMM-MAR/wiki\n% binsize: how many consecutive time points will be used for each estiamtion. \n%           By default, this is 1, such that one encoding model\n%               is estimated using 1 time point\n%\n% OUTPUT\n% encmodel:  (time points by regions) maps of activation (explained variances)\n% \n% Author: Diego Vidaurre, OHBA, University of Oxford (2018)\n\noptions.Nfeatures = 0; \noptions.pca = 0;\noptions.embeddedlags = 0;\noptions.K = 1; \n[X,Y,T] = preproc4hmm(X,Y,T,options); \n\nif (binsize/2)==0\n    warning(['binsize must be an odd number, setting to ' num2str(binsize+1)])\n    binsize = binsize + 1; \nend\n\nN = length(T); ttrial = T(1); \np = size(X,2); q = size(Y,2);\nX = reshape(X,[ttrial N p]);\nY = reshape(Y,[ttrial N q]);\n\nif any(T~=ttrial), error('All trials must have the same length'); end\nif nargin<5, binsize = 1; end\n\nencmodel = NaN(ttrial,p);\n\nfor t = halfbin+1 : ttrial-halfbin\n    r = t-halfbin:t+halfbin;\n    for j = 1:p\n        Xj = X(t,:,j);\n        Xj = zscore(Xj(:));\n        Yj = reshape(Y(r,:,:),binsize*N,q);\n        beta = (Yj' * Yj) \\ (Yj' * Xj);\n        res = (Xj - Yj * beta).^2;\n        res0 = Xj.^2;\n        encmodel(t,j) = 1 - sum(res(:))/sum(res0(:));\n    end\nend\nend", "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/task/standard_encoding.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5525957429187336}}
{"text": "% Get vertex coordinates for the patch type 'T'\n% [C, NW, NE, SW, SE] = HealpixGetPatchVertexCoordsT(n, i, j, INFO)\n%\n% Parameters\n% n : grid resolution\n% i : ring index\n% j : intra-ring index\n% INFO : intermediate information (output of HealpixSelectPatchClass())\n% C : intra-patch coordinates\n% NW : coordinates for north-east vertex\n% NE : coordinates for north-west vertex\n% SW, SE : coordinates for south vertex (always SW = SE since the patch is triangular shape)\n\nfunction [C, NW, NE, SW, SE] = HealpixGetPatchVertexCoordsT(n, i, j, INFO)\n\nint_j = fix(j);\nif int_j == 0\n    int_j = 4 * n;\nend\neast_int_j = mod(int_j + 1 - 1, 4 * INFO.int_i_n) + 1;\n\nif INFO.is_south_pole == 0\n    NW = [n, int_j];\n    NE = [n, east_int_j];\n    SW = [n + 1, int_j];\n    SE = SW;\n\n    decimal_i = INFO.decimal_i_n;\nelse\n    SW = [3 * n, int_j];\n    SE = [3 * n, east_int_j];\n    NW = [3 * n - 1, int_j];\n    NE = NW;\n\n    decimal_i = 1 - INFO.decimal_i_n;\nend\n\ndecimal_j = INFO.decimal_polar_intra_part;\n\nif 1 > INFO.decimal_i_n\n    C = [decimal_i, decimal_j / (1 - INFO.decimal_i_n)] - 0.5;\nelse\n    C = [decimal_i, decimal_j] - 0.5;\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/extern/HealpixLib/HealpixGetPatchVertexCoordsT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5525537968913554}}
{"text": "close all; clear all;\n\n%% Setting of the problem\nglobal s\npde = fonedata; % f = 1;\npde.L = 1;\noption.theta = 0.3;\noption.estType = 'star';\noption.maxIt = 20;\noption.maxN = 2e5;\noption.solver = 'mg';\noption.yrefinement = 10; % ratio of h_y/h_x\noption.gNquadorder = 5;\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;\nafemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.4\ns = 0.4;\nafemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.6\ns = 0.6;\nafemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.8\ns = 0.8;\nafemfracLap(node,elem,pde,bdFlag,option);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fracLaplacian/afemratefracLapLshapencfwithyrefinement.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5525537884829351}}
{"text": "function [out,Xt,str,ts] = rfnn_miso_grid(t,Xt,u,flag,itaVector,alphaVector, NumInVars,NumInTerms,x0,T)\n\n% This program is an implementation of the on line RFNN (MISO) system.\n% The structure of the network is determined by the user.\n% The input space is partitioned using the grid-type method.\n% All parameters of the network are estimated by Gradient Descent (GD)\n% through error backpropagation. \n\n    ninp = NumInVars;\n    nout = 1;\n   ninps = ninp+nout+1;  % number of inputs to sfunction [ x y LE ]\n   NumRules = NumInTerms^NumInVars;  % Grid-Type Input Space Partitioning.\n       ns = 4*NumInVars*NumInTerms + NumRules;\n     nds = 3*NumInVars*NumInTerms + NumRules;\n     % Learning Rates\n     ita1 = itaVector(1); ita2 = itaVector(2);\n     ita3 = itaVector(3); ita4 = itaVector(4);\n     % Momentum Constants.\n     alpha1 = alphaVector(1); alpha2 = alphaVector(2); \n     alpha3 = alphaVector(3); alpha4 = alphaVector(4);\n%  ----------------------- % initial informations --------------\nif abs(flag)==0\n\n    out = [0,ns+nds,1+ns+nds,ninps,0,1,1];    % states, outputs, inputs, ?, df, #ts\n    str = [];                                 % API block consistency\n     ts = T;                                  % sample time\n    Xt = x0;\n%  ----------------------- % state derivatives -----------------\nelseif abs(flag) == 2\n   \n          x = u(1:ninp);\n          e = u(ninp+1:ninp+nout);\n   learning = u(ninp+nout+1);\n\nif learning == 1 \n  \n   % Unroll the states:  \n   off=1;\n   off_end=NumInVars*NumInTerms;\n   mean2=reshape(Xt(off:off_end),NumInVars,NumInTerms);  \n   \n   off=off_end+1;\n   off_end=off + NumInVars*NumInTerms-1;\n   sigma2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off+NumInVars*NumInTerms-1;\n   Theta2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off + NumRules-1;\n   W = reshape(Xt(off:off_end),NumRules,1);\n      \n   off=off_end+1;\n   off_end=off+NumInVars*NumInTerms-1;\n   Out2 = reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   % Unroll the differential states:\n   off=off_end+1;\n   off_end=off + NumInVars*NumInTerms-1;\n   dmean2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off + NumInVars*NumInTerms-1;\n   dsigma2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off + NumInVars*NumInTerms-1;\n   dTheta2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off + NumRules-1;\n   dW = reshape(Xt(off:off_end),NumRules,1); \n      \n      \n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  %                                                    FEEDFORWARD OPERATION                                                      %\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % LAYER 2 - INPUT TERM NODES\n  Out2_pr = Out2;\n\n In2 = x*ones(1,NumInTerms) + Out2_pr.*Theta2;\n Out2 = exp(-((In2-mean2)./sigma2).^2);\n \n% LAYER 3 - RULE (PRODUCT) NODES\nprecond = comb(Out2);\n Out3 = prod(precond,2);\n \n%%%%%%%%%%%% END OF NETWORK FUNCTIONALITY SECTION %%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\t\t\t \t\t\t\t\t                 PARAMETER LEARNING SECTION\t                       \t\t\t                %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% BACKWARD PASS. Error Backpropagation\n% LAYERS 4-3\ndelta3 = e*W;\n\n% LAYER 2\nQ = zeros(NumInVars,NumInTerms,NumRules);  \nfor i=1:NumInVars\n     for j=1:NumInTerms\n          for k=1:NumRules  \n       \t       if Out2(i,j)== precond(k,i) && Out2(i,j)~=0\n      \t\t\t  Q(i,j,k) = (Out3(k)/Out2(i,j))*delta3(k);\n               end\n          end \n   \t  end \n end\n\n ThetaE = sum(Q,3);\n              \n% LAYER 1 PARAMETER ADJUSTMENT BY GRADIENT DESCENT.  \ndeltamean2  =  2*ThetaE.*Out2.*(In2-mean2)./((sigma2).^2);\ndeltasigma2 =  2*ThetaE.*Out2.*((In2-mean2).^2)./(sigma2.^3);\ndeltaTheta2 = -2*ThetaE.*Out2.*(In2-mean2).*Out2_pr./sigma2.^2; \n\ndmean2 = ita2*deltamean2 + alpha2*dmean2;\n mean2  = mean2 + dmean2;\n\ndsigma2 = ita3*deltasigma2 + alpha3*dsigma2;\n  sigma2 = sigma2 + dsigma2;\n\ndTheta2 = ita4*deltaTheta2 + alpha4*dTheta2;\n Theta2  = Theta2 + dTheta2;\n\n% LAYER 4 PARAMETER ADJUSTMENT\n  deltaW = e*Out3;\n  dW = ita1*deltaW + alpha1*dW;\n   W = W + dW;\n\n%%%%%%%%%%%   END OF PARAMETER LEARNING PROCESS %%%%%%%%%\n% State Vector Storage.\n% Xt = [mean2 sigma2 Theta2 W Out2 dmean2 dsigma2 dTheta2 dW];\n\nXt = [ reshape(mean2,NumInVars*NumInTerms,1);\n          reshape(sigma2,NumInVars*NumInTerms,1);\n          reshape(Theta2,NumInVars*NumInTerms,1);\n          W;\n          reshape(Out2,NumInVars*NumInTerms,1);\n          reshape(dmean2,NumInVars*NumInTerms,1);\n          reshape(dsigma2,NumInVars*NumInTerms,1);\n          reshape(dTheta2,NumInVars*NumInTerms,1);\n          dW;];\nend\n\nout=Xt;\n\n%  ----------------------- % outputs -------------------------\nelseif flag == 3\n   \n  % Unpack the network's parameters first...\n   off=1;\n   off_end=NumInVars*NumInTerms;\n   mean2=reshape(Xt(off:off_end),NumInVars,NumInTerms);  \n   \n   off=off_end+1;\n   off_end=off + NumInVars*NumInTerms-1;\n   sigma2=reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off+NumInVars*NumInTerms-1;\n   Theta2 =reshape(Xt(off:off_end),NumInVars,NumInTerms);\n   \n   off=off_end+1;\n   off_end=off + NumRules - 1;\n   W = Xt(off:off_end);\n   \n   off=off_end+1;\n   off_end=off+NumInVars*NumInTerms-1;\n   Out2 = reshape(Xt(off:off_end),NumInVars,NumInTerms);\n         \n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  %                                                       FEEDFORWARD OPERATION                                                       %\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  % LAYER 1 - INPUT TERM NODES\n  Out2_pr = Out2;\n\n  x = u(1:ninp);\n In2 = x*ones(1,NumInTerms) + Out2_pr.*Theta2;\n Out2 = exp(-((In2-mean2)./sigma2).^2);\n \n% LAYER 3 - RULE (PRODUCT) NODES\nprecond = comb(Out2);\n Out3 = prod(precond,2);\n \n % LAYER 4 \n  outact = W.'*Out3;\n\n  % Block Outputs Vector Formation.\n   out=[outact;Xt];            \n     \nelse\n   out=[];\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/43021-recurrent-fuzzy-neural-network-rfnn-library-for-simulink/S-functions/rfnn_miso_grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5525094218471455}}
{"text": "function tP = calcTriplePoints(gB)\n%\n% Input\n%  gB - @grainBoundary\n\n\n% list of phaseIds ordered as grainIds\ngrainId = gB.grainId;\ngrainPhaseId = zeros(max(grainId(:)),1);\ngrainPhaseId(grainId(grainId>0)) = gB.phaseId((grainId>0));\n\n% compute triple points\n[i,~,f] = find(gB.F);\nI_VF = sparse(f,i,1,size(gB.V,1),size(gB.F,1));\nI_VG = (I_VF * gB.I_FG)==2;\n% triple points are those with exactly 3 neigbouring grains and 3\n% boundary segments\nitP = full(sum(I_VG,2)==3 & sum(I_VF,2)==3);\n[tpGrainId,~] = find(I_VG(itP,:).');\ntpGrainId = reshape(tpGrainId,3,[]).';\ntpPhaseId = full(grainPhaseId(tpGrainId));\n\n% compute ebsdId\n% first step: compute faces at the triple point\n% clean up incidence matrix\n%I_FD(~any(I_FD,2),:) = [];\n% incidence matrix between triple points and voronoi cells\n%I_TD = I_VF(itP,:) * I_FD;\n[tPBoundaryId,~] = find(I_VF(itP,:).');\ntPBoundaryId = reshape(tPBoundaryId,3,[]).';\n\n% get the three end vertices\niV = reshape(gB.F(tPBoundaryId,:),[],6).';\n% TODO: the repmat can be removed in new versions of Matlab\niV = reshape(iV(iV ~= repmat(find(itP).',size(iV,1),1)).',3,[]).';\n\ntP = triplePointList(find(itP),gB.V,...\n  tpGrainId,tPBoundaryId,tpPhaseId,iV,gB.phaseMap,gB.CSList);\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/EBSDAnalysis/@grainBoundary/calcTriplePoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5525094153424694}}
{"text": "% This function produce short-time Fourier transform on the input signal\n% according to the settings \n% Author: Xiao Xiong\n% Created: 2006\n% Last modified: 24 Jun, 2006\n\n\nfunction fft_x = sfft_multi(x,frame_size,frame_shift,FFT_length,window_type,do_DC_remove, useGPU, doDithering)\n\n% x should be a TxN matrix, where T is the number of samples, and N is the\n% number of channels. \n\nif exist('do_DC_remove')==0 || length(do_DC_remove)==0\n    do_DC_remove = 1;\nend\nif exist('useGPU')==0 || length(useGPU)==0\n    useGPU = 0;\nend\n\nif exist('doDithering')==0 || length(doDithering)==0\n   x = x + randn(size(x))/2^32;\nend\n\n% produce the hamming windowm\nif exist('window_type')==0 || length(window_type)==0\n    window = my_hamming(frame_size);\nelse\n    switch window_type\n        case 'hamming'\n            window = my_hamming(frame_size);\n        case 'hanning'\n            window = hanning(frame_size);\n        case 'rectangular'\n            window = ones(frame_size,1);\n    end\nend\n\nif do_DC_remove\n    % DC offset removing\n    x = DC_remove(gather(x),0.999);\n    % pre-emphasis, boost the high frequency spectrum\n\n    if 0\n        % Method 2: Direct operation. In multichannel case, method 2 is\n        % slower\n        y = x(2:end,:) - 0.97*x(1:end-1,:);\n        x = [x(1,:); y];\n    else\n        % Method 1: Call filter function. Too slow\n        A    = [1 -0.97];\n        x = filter(A,1,gather(x));\n    end\nend\n\nif useGPU && ~IsInGPU(x)\n    x = gpuArray(x);\nend\n\n\nif license('test', 'Signal_Toolbox')\n    x_store = my_enframe(x, frame_size, frame_shift);\nelse\n    for i=1:size(x,2)\n        tmp = enframe(x(:,i), frame_size, frame_shift)';\n        if i==1\n            if useGPU\n                x_store = gpuArray.zeros(size(tmp,1), size(tmp,2), size(x,2), class(gather(x)));\n            else\n                x_store = zeros(size(tmp,1), size(tmp,2), size(x,2), class(x));\n            end\n        end\n        x_store(:,:,i) = tmp;\n    end\n    x_store = permute(x_store, [1 3 2]);\nend\n\nx_store = bsxfun(@times, x_store, window);\n\nfft_x = fft(x_store,FFT_length);\n\nN = FFT_length;\nn = 0:N-1;\nk = 0:N-1;\nDFT_Trans = exp(-sqrt(-1)*2*pi*n(:)*k(:)'/N);\nspec = DFT_Trans(1:N/2+1,1:frame_size) * squeeze(x_store(:,1,:));\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/feature/sfft_multi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5524878950470271}}
{"text": "classdef prtClassBinomial < prtClass\n %prtClassBinomial  Maximum a Posteriori classifier for binary data using\n %  IID binomial distributions for each feature (column) under each\n %  hypothesis (class)\n %\n %  Properties:\n %      \n %       priorSuccesses = 1e-3;  %I think I did this right.\n %       priorTrials = 10000e-3;\n %\n \n    properties (SetAccess=private)\n        name = 'Binomial'  \n        nameAbbreviation = 'Binom'      \n        isNativeMary = true;       \n    end\n    \n    properties\n        priorSuccesses = 1e-3;\n        priorTrials = 10000e-3;\n        pSuccessByClass = [];\n    end\n    \n    methods\n        % Constructor\n        function self = prtClassBinomial(varargin)\n            \n            self.classTrain = 'prtDataInterfaceCategoricalTargets';\n            self.classRun = 'prtDataSetBase';\n            self.classRunRetained = false;\n            \n            self = prtUtilAssignStringValuePairs(self,varargin{:});\n        end\n    end\n    \n    methods (Access = protected, Hidden = true)\n        \n        function self = trainAction(self,ds)\n            \n            self.pSuccessByClass = [];\n            for iClass = 1:ds.nClasses;\n                classDs = ds.retainClassesByInd(iClass);\n                pVec = (sum(classDs.X,1)+self.priorSuccesses)./(classDs.nObservations + self.priorTrials);\n                pVec = full(pVec);\n                self.pSuccessByClass(iClass,:) = pVec;\n            end\n        end\n        \n        function ds = runAction(self,ds)\n            \n            nClasses = size(self.pSuccessByClass,1);\n            logLikelihoods = zeros(ds.nObservations, nClasses);\n            for iY = 1:nClasses\n                pVec = self.pSuccessByClass(iY,:);\n                xOut = bsxfun(@times,ds.X,pVec) + bsxfun(@times,~ds.X,1-pVec);\n                logLikelihoods(:,iY) = sum(log(xOut),2);\n            end\n            logLikelihoods = exp(bsxfun(@minus, logLikelihoods, prtUtilSumExp(logLikelihoods.').'));\n            ds.X = logLikelihoods;\n        end\n    end\n    methods\n        function [sorted,pDist] = getSortedFeatures(self)\n            % [sorted,pDist] = getSortedFeatures(self)\n            %   Return the list of the features in sorted order.  pDist is\n            %   the corresponding distance between the MLEs of the mean\n            %   p(true)\n            \n            nClasses = size(self.pSuccessByClass,1);\n            if nClasses ~= 2\n                error('Only for binary problems');\n            end\n            pDist = self.pSuccessByClass(2,:)-self.pSuccessByClass(1,:);\n            absDist = abs(pDist);\n            [~,sorted] = sort(absDist,'descend');\n            pDist = pDist(sorted);\n            \n        end\n    end\n    \nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/class/prtClassBinomial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.552487894378273}}
{"text": "function i4row_sort_a_test ( )\n\n%*****************************************************************************80\n%\n%% I4ROW_SORT_A_TEST tests I4ROW_SORT_A;\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 April 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 10;\n  n = 4;\n  b = 0;\n  c = 10;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'I4ROW_SORT_A_TEST\\n' );\n  fprintf ( 1, '  For a rectangular integer matrix:\\n' );\n  fprintf ( 1, '  I4ROW_SORT_A sorts the rows;\\n' );\n\n  seed = 123456789;\n\n  [ a, seed ] = i4mat_uniform_ab ( m, n, b, c, seed );\n\n  i4mat_print ( m, n, a, '  The original matrix:' );\n\n  a = i4row_sort_a ( m, n, a );\n\n  i4mat_print ( m, n, a, '  The row-sorted matrix:' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/i4lib/i4row_sort_a_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.5524878927120676}}
{"text": "function [energy] = getSpecOrbitEnergyFromSma(sma, gmu)\n%getSpecOrbitEnergyFromSma Summary of this function goes here\n%   Detailed explanation goes here\n\n    energy = -gmu/(2*sma);\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/astrodynamics/getSpecOrbitEnergyFromSma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5524878897083544}}
{"text": "function [x,fval,exitflag,info,Opt] = opti_mintprog(f,A,b,Aeq,beq,lb,ub,int,sos,opts)\n%OPTI_MINTPROG Solve a MILP using an OPTI MILP Solver (Matlab-Like Overload)\n%\n%   [x,fval,exitflag,info] = opti_mintprog(f,A,b,Aeq,beq,lb,ub,int) solves \n%   the linear program min f'x where A,b are the inequality constraints, \n%   Aeq,beq are the equality constraints, lb,ub are the decision variable \n%   bounds and int is a string of integer variables ('C', 'I', 'B').\n%\n%   [x,fval,exitflag,info] = opti_minprog(f,...,int,sos) allows Special\n%   Ordered Sets (SOS) to be specified via the sos structure. Fields must\n%   include 'type' ('1' or '2'), 'index' (vector) and 'weight' (vector).\n%   Multiple SOS can be supplied as cell arrays.\n%\n%   [x,fval,exitflag,info] = opti_mintprog(f,...,sos,opts) allows the user \n%   to specify optiset options. This includes specifying a solver via the\n%   'solver' field of optiset.\n%\n%   [x,...,info,Opt] = opti_mintprog(f,...) returns the internally built\n%   OPTI object.\n\n%   Copyright (C) 2011 Jonathan Currie (I2C2)\n\n\n% Handle missing arguments\nif nargin < 10, opts = optiset; end \nif nargin < 9, sos = []; end\nif nargin < 8, int = []; end\nif nargin < 7, ub = []; end\nif nargin < 6, lb = []; end\nif nargin < 5, beq = []; end\nif nargin < 4, Aeq = []; end\nif nargin < 3, error('You must supply at least 3 arguments to opti_mintprog'); end\n\n%Check SOS\nif(~isempty(sos))\n    if(~isfield(sos,'type')), error('The SOS structure must have the field type!'); end\n    if(~isfield(sos,'index')), error('The SOS structure must have the field index!'); end\n    if(~isfield(sos,'weight')), error('The SOS structure must have the field weight!'); end\nend\n\n%Build OPTI Object\nOpt = opti('f',f,'ineq',A,b,'eq',Aeq,beq,'bounds',lb,ub,'int',int,'sos',sos,'options',opts);\n\n%Solve\n[x,fval,exitflag,info] = solve(Opt);\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/Utilities/Matlab Overloads/opti_mintprog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5524878830321736}}
{"text": "function L = spm_mesh_get_lm(M,T)\n% Identification of local maxima on a textured surface mesh\n% FORMAT L = spm_mesh_get_lm(M,T)\n% M        - a [nx3] faces array or a patch structure or a [nxn] adjacency\n%            matrix\n% T        - a [nx1] texture vector\n%\n% L        - indices of vertices that are local maxima\n%__________________________________________________________________________\n% Copyright (C) 2010-2016 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin\n% $Id: spm_mesh_get_lm.m 6867 2016-09-12 15:04:44Z guillaume $\n\n\n%-Get adjacency matrix\n%--------------------------------------------------------------------------\nif ~isnumeric(M) || size(M,1) ~= size(M,2)\n    A = spm_mesh_adjacency(M);\nelse\n    A = M;\nend\n\n%-Get neighbours, restricted to vertices that actually have data (~= NaN)\n%--------------------------------------------------------------------------\nout      = isnan(T(:)');\nif all(out), L = []; return; end             % empty domain\nA(:,out) = 0;\nA(out,:) = 0;\nN        = spm_mesh_neighbours(A);\nif isempty(N), L = find(~out); return; end   % only singletons\n%S       = ~any(N(~out,:),2);                % some singletons\n\n%-Identify local maxima\n%--------------------------------------------------------------------------\nT        = [T; -Inf];\nN(N<1)   = numel(T);\nL        = all(bsxfun(@gt,T(1:end-1),T(N)),2);\nL        = find(L');\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_get_lm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.552487878362255}}
{"text": "function [data,units] = compute_max_wing_angle(trx,n)\n\nflies = trx.exp2flies{n};\nnflies = numel(flies);\ndata = cell(1,nflies);\nfor i = 1:nflies,\n  fly = flies(i);\n\n  % signed maximum: left wing will be negative, right wing positive\n  data{i} = max(-trx(fly).wing_anglel,trx(fly).wing_angler);\n  \nend\nunits = parseunits('rad');\n\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/compute_perframe_features/compute_max_wing_angle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5524878783622549}}
{"text": "function p=polelague(n)\n\n% p=polegend(n)\n% Almacena en las filas de la matriz p los coefs de los polinomios de Legendre\n\np(1,1)=1;\np(2,1:2)=[-1 1]; \nfor k=2:n\n   p(k+1,1:k+1)=((2*(k-2)*[0 p(k,1:k)]+3*[0 p(k,1:k)]-[p(k,1:k) 0]-(k-1).^2*[0 0 p(k-1,1:k-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/8067-gauss-laguerre/polelague.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5523914763376985}}
{"text": "function [l,L_k,L_hm,L_beta] = invPinHoleAPlucker(Sk,hm,beta)\n\n% INVPINHOLEAPLUCKER Retro-projects anchored plucker line\n%   INVPINHOLEAPLUCKER(K,L,BETA) retro-projects the anchored Plucker line\n%   from the homogeneous 2D line HM and a pin hole camera K=[u0;v0;au;av]\n%   at the origin. BETA specifies the unobservable direction of the line.\n%   BETA is a 2-vector expressed in the plane base given by\n%   PLANEVEC2PLANEBASE.\n%\n%   [l,L_k,L_hm,L_beta] = ... returns Jacobians wrt K, HM and BETA.\n%\n%   See also INVPINHOLEPLUCKER.\n\n%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nif nargout == 1\n    % Plucker line \n    pl = invPinHolePlucker(Sk,hm,beta) ;\n\n    % anchored Plucker line L\n    l = anchorPlucker(pl,[0;0;0]);\n\nelse\n    % Plk lin in Sensor Frame\n    [pl, PL_k, PL_hm, PL_beta] = invPinHolePlucker(Sk,hm,beta) ;\n    \n    % L in sensor frame\n    [l, L_pl] = anchorPlucker(pl,[0;0;0]);\n    \n    % chain rule\n    L_k    = L_pl * PL_k;\n    L_hm   = L_pl * PL_hm;\n    L_beta = L_pl * PL_beta;\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 <http://www.gnu.org/licenses/>.\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/invPinHoleAPlucker.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5523914643383114}}
{"text": "function slide30\n\t\n\ta = [0 0 0;\n\t\t1 0 0;\n\t\t1 1 0;\n\t\t0 1 0;\n\t\t0 0 1;\n\t\t1 0 1;\n\t\t1 1 1;\n\t\t0 1 1];\n\t\n\tb = [1 2 6 5;\n\t\t2 3 7 6;\n\t\t3 4 8 7;\n\t\t4 1 5 8;\n\t\t1 2 3 4;\n\t\t5 6 7 8];\n\t\n\tp1 = patch('faces',b,...\n\t\t'vertices',a,...\n\t\t'facecolor',[.5 .5 .5],...\n\t\t'edgecolor',[1,1,1],...\n\t\t'facealpha',0.5);\n\t\n\tview(3)\n\taxis square\n\t\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/25856-using-patch-and-rotate-basics/slide30.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5523914618071137}}
{"text": "function [y,deriv] = compose_mv(outer,inner,x)\n% COMPOSE_MV is an MV2DF (see MV2DF_API_DEFINITION.readme) which represents\n% the combination of two functions. If 'outer' is an MV2DF for a function\n% g() and 'inner' for a function f(), then this MV2DF represents g(f(x)).\n\n%feature scopedaccelenablement off\n\nif nargin==0\n    test_this();\n    return;\nend\n\n\nif isempty(x)\n    y = @(w)compose_mv(outer,inner,w);\n    return;\nend\n\nif isa(x,'function_handle')\n    fh = compose_mv(outer,inner,[]);  % fh =@(x) outer(inner(x))\n    y = compose_mv(fh,x,[]);          %  y =@(w) outer(inner(x(w)))\n    return;\nend\n\n% if ~isa(outer,'function_handle')\n%     outer = const_mv2df([],outer);\n% end\n% if ~isa(inner,'function_handle')\n%     inner = const_mv2df([],inner);\n% end\n\n\n\nif nargout==1\n    y = outer(inner(x));\n    return;\nend\n\n[y1,deriv1] = inner(x);\n[y,deriv2] = outer(y1);\nderiv = @(g3) deriv_this(deriv1,deriv2,g3);\n\n\n\nfunction [g,hess,linear] = deriv_this(deriv1,deriv2,g3)\n\nif nargout==1\n    g = deriv1(deriv2(g3));\n    return;\nend\n\n[g2,hess2,lin2] = deriv2(g3);\n[g,hess1,lin1] = deriv1(g2);\n\nhess =@(d) hess_this(deriv1,hess1,hess2,lin1,lin2,d);\n\nlinear = lin1 && lin2;\n\n\nfunction [h,Jv] = hess_this(deriv1,hess1,hess2,lin1,lin2,d)\n\n\nif nargout==1\n    if ~lin2\n        [h1,Jv1] = hess1(d);\n        h2 = hess2(Jv1);\n        h2 = deriv1(h2);\n    elseif ~lin1\n        h1 = hess1(d);\n    end\nelse\n    [h1,Jv1] = hess1(d);\n    [h2,Jv] = hess2(Jv1);\n    if ~lin2\n        h2 = deriv1(h2);\n    end\nend\n\nif lin1 && lin2\n    h=[];\nelseif (~lin1) && (~lin2)\n    h = h1+h2;\nelseif lin1\n    h = h2;\nelse % if lin2\n    h = h1;\nend\n\nfunction test_this()\n\nfprintf('-------------- Test 1 ------------------------\\n');\nfprintf('Composition g(f(w)): f() is non-linear and g() is non-linear:\\n');\nA = randn(4,5);\nB = randn(5,4);\n\nw = [A(:);B(:)];\n\nf = @(w) gemm(w,4,5,4);\ng1 = gemm(f,2,4,2);\n\ntest_MV2DF(g1,w);\nfprintf('--------------------------------------\\n\\n');\n\n\nfprintf('-------------- Test 2 ------------------------\\n');\nfprintf('Composition g(f(w)): f() is linear and g() is non-linear:\\n');\nA = randn(4,5);\nB = randn(5,4);\n\nw = [A(:);B(:)];\n\n\nT = randn(40);\nf = @(w) linTrans(w,@(x)T*x,@(y)T.'*y);\ng2 = gemm(f,4,5,4);\n\ntest_MV2DF(g2,w);\nfprintf('--------------------------------------\\n\\n');\n\n\nfprintf('-------------- Test 3 ------------------------\\n');\nfprintf('Composition g(f(w)): f() is non-linear and g() is linear:\\n');\nA = randn(4,5);\nB = randn(5,4);\n\nw = [A(:);B(:)];\nf = @(w) gemm(w,4,5,4);\n\nT = randn(16);\ng3 = linTrans(f,@(x)T*x,@(y)T.'*y);\n\ntest_MV2DF(g3,w);\nfprintf('--------------------------------------\\n\\n');\n\n\n\n\nfprintf('-------------- Test 4 ------------------------\\n');\nfprintf('Composition g(f(w)): f() is linear and g() is linear:\\n');\nw = randn(10,1);\nT1 = randn(11,10);\nf = @(w) linTrans(w,@(x)T1*x,@(y)T1.'*y);\n\nT2 = randn(5,11);\ng4 = linTrans(f,@(x)T2*x,@(y)T2.'*y);\n\n\ntest_MV2DF(g4,w);\nfprintf('--------------------------------------\\n\\n');\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_combination/compose_mv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5523914546512549}}
{"text": "classdef IMMOEA_F8 < PROBLEM\n% <multi> <real> <large/none>\n% Benchmark MOP for testing IM-MOEA\n\n%------------------------------- Reference --------------------------------\n% R. Cheng, Y. Jin, K. Narukawa, and B. Sendhoff, A multiobjective\n% evolutionary algorithm using Gaussian process-based inverse modeling,\n% IEEE Transactions on Evolutionary Computation, 2015, 19(6): 838-856.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        %% Default settings of the problem\n        function Setting(obj)\n            obj.M = 3;\n            if isempty(obj.D); obj.D = 30; end\n            obj.lower    = zeros(1,obj.D);\n            obj.upper    = ones(1,obj.D);\n            obj.encoding = ones(1,obj.D);\n        end\n        %% Calculate objective values\n        function PopObj = CalObj(obj,X)\n            t = X(:,3:obj.D).^(1./(1+3*repmat(3:obj.D,size(X,1),1)/obj.D)) - repmat(X(:,1),1,obj.D-2);\n            g = sum(t.^2,2);\n            PopObj(:,1) = cos(pi/2*X(:,1)).*cos(pi/2*X(:,2)).*(1+g);\n            PopObj(:,2) = cos(pi/2*X(:,1)).*sin(pi/2*X(:,2)).*(1+g);\n            PopObj(:,3) = sin(pi/2*X(:,1)).*(1+g);\n        end\n        %% Generate points on the Pareto front\n        function R = GetOptimum(obj,N)\n            R = UniformPoint(N,3);\n            R = R./repmat(sqrt(sum(R.^2,2)),1,3);\n        end\n        %% Generate the image of Pareto front\n        function R = GetPF(obj)\n            a = linspace(0,pi/2,10)';\n            R = {sin(a)*cos(a'),sin(a)*sin(a'),cos(a)*ones(size(a'))};\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/MOPs with variable linkages/IMMOEA_F8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5523914546512549}}
{"text": "function affineTransformationMatrix = get_affine_matrix(this)\n% Transforms geometry parameters into affine 4x4 matrix (T*R*Z*S)\n% with T = Translation, R = Rotation, Z = Zooming (Scaling with Resolution)\n%      S = Shearing\n% i.e. performing operations in the order from right to left, in particular\n% rotation before translation\n%\n%   Y = MrImageGeometry()\n%   Y.get_affine_matrix(inputs)\n%\n% This is a method of class MrImageGeometry.\n%\n% IN\n%\n% OUT\n%\n% EXAMPLE\n%   get_affine_matrix\n%\n%   See also MrImageGeometry tapas_uniqc_spm_matrix\n\n% Author:   Saskia Klein & Lars Kasper\n% Created:  2014-07-15\n% Copyright (C) 2014 Institute for Biomedical Engineering\n%                    University of Zurich and ETH Zurich\n%\n% This file is part of the TAPAS UniQC Toolbox, which is released\n% under the terms of the GNU General Public Licence (GPL), version 3.\n% 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).\n% For further details, see the file COPYING or\n%  <http://www.gnu.org/licenses/>.\n\n\nP(1:3) = this.offcenter_mm;\nP(4:6) = this.rotation_deg*pi/180;\nP(7:9) = this.resolution_mm;\nP(10:12) = this.shear;\n\naffineTransformationMatrix = tapas_uniqc_spm_matrix(P);", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrImageGeometry/get_affine_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5523284832870408}}
{"text": "function [n_best P_best V C]=fast_oopsi(F,V,P)\n% this function solves the following optimization problem:\n% (*) n_best = argmax_{n >= 0} P(n | F)\n% which is a MAP estimate for the most likely spike train given the\n% fluorescence signal.  given the model:\n%\n% <latex>\n% \\begin{align}\n% C_t &= \\gamma*C_{t-1} + n_t, \\qquad & n_t & \\sim \\text{Poisson}(n_t; \\lamda_t \\Delta)\n% F_t &= \\alpha(C_t + \\beta) + \\sigma \\varepsilon_t, &\\varepsilon_t &\\sim \\mathcal{N}(0,1)\n% \\end{align}\n% </latex>\n%\n% if F_t is a vector, then 'a' is a vector as well\n% we approx the Poisson with an Exponential (which means we don't require integer numbers of spikes).\n% we take an \"interior-point\" approach to impose the nonnegative contraint on (*).\n% each step is solved in O(T)\n% time by utilizing gaussian elimination on the tridiagonal hessian, as\n% opposed to the O(T^3) time typically required for non-negative\n% deconvolution.\n%\n% Input---- only F is REQUIRED.  the others are optional\n% F:        fluorescence time series (can be a vector (1 x T) or a matrix (Np x T)\n%\n% V.        structure of algorithm Variables\n%   Ncells: # of cells within ROI\n%   T:      # of time steps\n%   Npixels:# of pixels in ROI\n%   dt:     time step size, ie, frame duration, ie, 1/(imaging rate)\n%   n:      if true spike train is known, and we are plotting, plot it (only required is est_a==1)\n%   h:      height of ROI (assumes square ROI) (# of pixels) (only required if est_a==1 and we are plotting)\n%   w:      width of ROI (assumes square ROI) (# of pixels) (only required if est_a==1 and we are plotting)\n%\n%   THE FOLLOWING FIELDS CORRESPOND TO CHOICES THAT THE USER MAKE\n%\n%   fast_poiss:     1 if F_t ~ Poisson, 0 if F_t ~ Gaussian\n%   fast_nonlin:    1 if F_t is a nonlinear f(C_t), and 0 if F_t is a linear f(C_t)\n%   fast_plot:      1 to plot results after each pseudo-EM iteration, 0 otherwise\n%   fast_thr:       1 if thresholding inferred spike train before estiamting {a,b}\n%   fast_iter_max:  max # of iterations of pseudo-EM  (1 to use default initial parameters)\n%   fast_ignore_post: 1 to keep iterating pseudo-EM even if posterior is not increasing, 0 otherwise\n%\n%   THE BELOW FIELDS INDICATE WHETHER ONE WANTS TO ESTIMATE EACH OF THE\n%   PARAMETERS. IF ANY IS SET TO ZERO, THEN WE DO NOT TRY TO UPDATE THE\n%   ORIGINAL ESTIMATE, GIVEN EITHER BY THE USER, OR THE INITIAL ESTIMATE\n%   FROM THE CODE\n%\n%   est_sig:    1 to estimate sig\n%   est_lam:    1 to estimate lam\n%   est_gam:    1 to estimate gam\n%   est_b:      1 to estimate b\n%   est_a:      1 to estimate a\n%\n% P.        structure of neuron model Parameters\n%\n%   a:      spatial filter\n%   b:      background fluorescence\n%   sig:    standard deviation of observation noise\n%   gam:    decayish, ie, tau=dt/(1-gam)\n%   lam:    firing rate-ish, ie, expected # of spikes per frame\n%\n% Output---\n% n_best:   inferred spike train\n% P_best:   inferred parameter structure\n% V:        structure of Variables for algorithm to run\n\n%% initialize algorithm Variables\nstarttime   = cputime;\nsiz         = size(F);      if siz(2)==1, F=F'; siz=size(F); end\nj=0;\n% variables determined by the data\nif nargin < 2,              V   = struct;       end\nif ~isfield(V,'Ncells'),    V.Ncells = 1;       end     % # of cells in image\nif ~isfield(V,'T'),         V.T = siz(2);       end     % # of time steps\nif ~isfield(V,'Npixels'),   V.Npixels = siz(1); end     % # of pixels in ROI\nif ~isfield(V,'dt'),                                    % frame duration\n    fr = input('\\nwhat was the frame rate for this movie (in Hz)?: ');\n    V.dt = 1/fr;\nend\n\n% variables determined by the user\nif ~isfield(V,'fast_poiss'),V.fast_poiss = 0;   end     % whether observations are Poisson\nif ~isfield(V,'fast_nonlin'),   V.fast_nonlin   = 0; end\nif V.fast_poiss && V.fast_nonlin,\n    reply = input('\\ncan be nonlinear observations and poisson, \\ntype 1 for nonlin, 2 for poisson, anything else for neither: ');\n    if reply==1,        V.fast_poiss = 0;   V.fast_nonlin = 1;\n    elseif reply==2,    V.fast_poiss = 1;   V.fast_nonlin = 0;\n    else                V.fast_poiss = 0;   V.fast_nonlin = 0;\n    end\nend\nif ~isfield(V,'fast_iter_max'), V.fast_iter_max=1; end % max # of iterations before convergence\n\n% things that matter if we are iterating to estimate parameters\nif V.fast_iter_max>1;\n    if V.fast_poiss || V.fast_nonlin,\n        disp('\\ncode does not currrently support estimating parameters for \\npoisson or nonlinear observations');\n        V.fast_iter_max=1;\n    end\n    \n    if ~isfield(V,'fast_plot'), V.fast_plot = 0; end\n    if V.fast_plot==1\n        FigNum = 400;\n        if V.Npixels>1, figure(FigNum), clf, end        % figure showing estimated spatial filter\n        figure(FigNum+1), clf                           % figure showing estimated spike trains\n        if isfield(V,'n'), siz=size(V.n); V.n(V.n==0)=NaN; if siz(1)<siz(2), V.n=V.n'; end; end\n    end\n    \n    if ~isfield(V,'est_sig'),   V.est_sig   = 0; end    % whether to estimate sig\n    if ~isfield(V,'est_lam'),   V.est_lam   = 0; end    % whether to estimate lam\n    if ~isfield(V,'est_gam'),   V.est_gam   = 0; end    % whether to estimate gam\n    if ~isfield(V,'est_a'),     V.est_a     = 0; end    % whether to estimate a\n    if ~isfield(V,'est_b'),     V.est_b     = 1; end    % whether to estimate b\n    if ~isfield(V,'fast_plot'), V.fast_plot = 1; end    % whether to plot results from each iteration\n    if ~isfield(V,'fast_thr'),  V.fast_thr  = 0; end    % whether to threshold spike train before estimating 'a' and 'b'\n    if ~isfield(V,'fast_ignore_post'), V.fast_ignore_post=0; end % whether to ignore the posterior, and just keep the last iteration\nend\n\n% normalize F if it is only a trace\nif V.Npixels==1\n    F=detrend(F);\n    F=F-min(F)+eps;\nend\n\n%% set default model Parameters\n\n\n\nif nargin < 3,          P       = struct;                       end\nif ~isfield(P,'sig'),   P.sig   = mean(mad(F',1)*1.4826);       end\nif ~isfield(P,'gam'),   P.gam   = (1-V.dt/1)*ones(V.Ncells,1);  end\nif ~isfield(P,'lam'),   P.lam   = 10*ones(V.Ncells,1);          end\nif ~isfield(P,'a'),     P.a     = median(F,2);                  end\n\nif ~isfield(P,'b'),\n    if V.Npixels==1, P.b = quantile(F,0.05);\n    else P.b=median(F,2);\n    end\nend    \n    \n%% define some stuff needed for est_MAP function\n\n% for brevity and expediency\nZ   = zeros(V.Ncells*V.T,1);                    % zero vector\nM   = spdiags([repmat(-P.gam,V.T,1) repmat(Z,1,V.Ncells-1) (1+Z)], -V.Ncells:0,V.Ncells*V.T,V.Ncells*V.T);  % matrix transforming calcium into spikes, ie n=M*C\nI   = speye(V.Ncells*V.T);                      % create out here cuz it must be reused\nH1  = I;                                        % initialize memory for Hessian matrix\nH2  = I;                                        % initialize memory for other part of Hessian matrix\nd0  = 1:V.Ncells*V.T+1:(V.Ncells*V.T)^2;        % index of diagonal elements of TxT matrices\nd1  = 1+V.Ncells:V.Ncells*V.T+1:(V.Ncells*V.T)*(V.Ncells*(V.T-1)); % index of off-diagonal elements of TxT matrices\nposts = Z(1:V.fast_iter_max);                   % initialize likelihood\nif numel(P.lam)==V.Ncells\n    lam = V.dt*repmat(P.lam,V.T,1);             % for lik\nelseif numel(P.lam)==V.Ncells*V.T\n    lam = V.dt*P.lam;\nelse\n    error('lam must either be length V.T or 1');\nend\n\nif V.fast_poiss==1\n    H       = I;                                % initialize memory for Hessian matrix\n    gamlnF  = gammaln(F+1);                     % for lik\n    sumF    = sum(F,1)';                        % for grad & Hess\nend\n\n%% if not iterating to estimate parameters, only this is necessary\n[n C posts(1)] = est_MAP(F,P);\nn_best = n;\nP_best = P;\nV.fast_iter_tot = 1;\nV.post = posts(1);\npost_max = posts(1);\n\nif V.fast_iter_max>1\n    options = optimset('Display','off');        % don't show warnings for parameter estimation\n    i       = 1;                                % iteration #\n    i_best  = i;                                % iteration with highest likelihood\n    conv    = 0;                                % whether algorithm has converged yet\nelse\n    conv    = 1;\nend\n\n%%  if parameters are unknown, do pseudo-EM iterations\nwhile conv == 0\n    if V.fast_plot == 1, MakePlot(n,F,P,V); end % plot results from previous iteration\n    i               = i+1;                      % update iteratation number\n    V.fast_iter_tot = i;                        % record of total # of iterations\n    P               = est_params(n,C,F,P,b);    % update parameters based on previous iteration\n    [n C posts(i)]  = est_MAP(F,P);             % update inferred spike train based on new parameters\n    \n    if posts(i)>post_max || V.fast_ignore_post==1% if this is the best one, keep n and P\n        n_best  = n;                            % keep n\n        P_best  = P;                            % keep P\n        i_best  = i;                            % keep track of which was best\n        post_max= posts(i);                     % keep max posterior\n    end\n    \n    % if lik doesn't change much (relatively), or returns to some previous state, stop iterating\n    if  i>=V.fast_iter_max || (abs((posts(i)-posts(i-1))/posts(i))<1e-3 || any(posts(1:i-1)-posts(i))<1e-5)% abs((posts(i)-posts(i-1))/posts(i))<1e-5 || posts(i-1)-posts(i)>1e5;\n        MakePlot(n,F,P,V);\n        disp('convergence criteria met')\n        V.post  = posts(1:i);\n        conv    = 1;\n    end\n    sound(3*sin(linspace(0,90*pi,2000)))        % play sound to indicate iteration is over\nend\n\nV.fast_time = cputime-starttime;                % time to run code\nV           = orderfields(V);                   % order fields alphabetically to they are easier to read\nP_best      = orderfields(P_best);\n% n_best      = n_best./repmat(max(n_best),V.T,1);\n\nP_best.j=j;\n\n%% fast filter function\n    function [n C post] = est_MAP(F,P)\n        \n        % initialize n and C\n        z = 1;                                  % weight on barrier function\n        llam = reshape(1./lam',1,V.Ncells*V.T)';\n        if V.fast_nonlin==1\n            n = V.gauss_n;\n        else\n            n = 0.01+0*llam;                    % initialize spike train\n        end\n        C = 0*n;                                % initialize calcium\n        for j=1:V.Ncells\n            C(j:V.Ncells:end) = filter(1,[1, -P.gam(j)],n(j:V.Ncells:end)); %(1-P.gam(j))*P.b(j);\n        end\n        \n        % precompute parameters required for evaluating and maximizing likelihood\n        b           = repmat(P.b,1,V.T);       % for lik\n        if V.fast_poiss==1\n            suma    = sum(P.a);                 % for grad\n        else\n            M(d1)   = -repmat(P.gam,V.T-1,1);   % matrix transforming calcium into spikes, ie n=M*C\n            ba      = P.a'*b; ba=ba(:);         % for grad\n            aa      = repmat(diag(P.a'*P.a),V.T,1);% for grad\n            aF      = P.a'*F; aF=aF(:);         % for grad\n            e       = 1/(2*P.sig^2);            % scale of variance\n            H1(d0)  = -2*e*aa;                   % for Hess\n        end\n        grad_lnprior  = M'*llam;                  % for grad\n        \n        \n        % find C = argmin_{C_z} lik + prior + barrier_z\n        while z>1e-13                           % this is an arbitrary threshold\n            \n            if V.fast_poiss==1\n                Fexpect = P.a*(C+b')';          % expected poisson observation rate\n                lik = -sum(sum(-Fexpect+ F.*log(Fexpect) - gamlnF)); % lik\n            else\n                if V.fast_nonlin==1\n                    S = C./(C+P.k_d);\n                else\n                    S = C;\n                end\n                D = F-P.a*(reshape(S,V.Ncells,V.T))-b; % difference vector to be used in likelihood computation\n                lik = e*D(:)'*D(:);             % lik\n            end\n            post = lik + llam'*n - z*sum(log(n));\n            s    = 1;                           % step size\n            d    = 1;                           % direction\n            while norm(d)>5e-2 && s > 1e-3      % converge for this z (again, these thresholds are arbitrary)\n                if V.fast_poiss==1\n                    glik    = suma - sumF./(C+b');\n                    H1(d0)  = sumF.*(C+b').^(-2); % lik contribution to Hessian\n                elseif V.fast_nonlin==1\n                    glik    = -2*P.a*P.k_d*D'.*(C+P.k_d).^-2;\n                    H1diag  = (-P.a*P.k_d-2*(C+P.k_d).*D').*((C+P.k_d).^-4);\n                    H1(d0)  = H1diag;\n                else\n                    glik    = -2*e*(aF-aa.*C-ba);  % gradient\n                end\n                g       = glik + grad_lnprior - z*M'*(n.^-1);\n                H2(d0)  = n.^-2;                % log barrier part of the Hessian\n                H       = H1 - z*(M'*H2*M);     % Hessian\n                d   = H\\g;                     % direction to step using newton-raphson\n                hit = -n./(M*d);                % step within constraint boundaries\n                hit=hit(hit>0);\n                if any(hit<1)\n                    s = min(1,0.99*min(hit));\n                else\n                    s = 1;\n                end\n                post1 = post+1;\n                while post1>=post+1e-7          % make sure newton step doesn't increase objective\n                    C1  = C+s*d;\n                    n   = M*C1;\n                    if V.fast_poiss==1\n                        Fexpect = P.a*(C1+b')';\n                        lik1    = -sum(sum(-Fexpect+ F.*log(Fexpect) - gamlnF));\n                    else\n                        if V.fast_nonlin==1\n                            S1 = C1./(C1+P.k_d);\n                        else\n                            S1 = C1;\n                        end\n                        D = F-P.a*(reshape(S1,V.Ncells,V.T))-b; % difference vector to be used in likelihood computation\n                        lik1 = e*D(:)'*D(:);             % lik\n                    end\n                    post1 = lik1 + llam'*n - z*sum(log(n));\n                    s   = s/5;                  % if step increases objective function, decrease step size\n\n                    if s<1e-20; disp('reducing s further did not increase likelihood'), break; end      % if decreasing step size just doesn't do it\n                end\n                C    = C1;                      % update C\n                post = post1;                   % update post\n            end\n            z=z/10;                             % reduce z (sequence of z reductions is arbitrary)\n        end\n        \n        % reshape things in the case of multiple neurons within the ROI\n        n=reshape(n,V.Ncells,V.T)';\n        C=reshape(C,V.Ncells,V.T)';\n    end\n\n%% Parameter Update\n    function P = est_params(n,C,F,P,b)\n        \n        % generate regressor for spatial filter\n        if V.est_a==1 || V.est_b==1\n            if V.fast_thr==1\n                CC=0*C;\n                for j=1:V.Ncells\n                    nsort   = sort(n(:,j));\n                    nthr    = nsort(round(0.98*V.T));\n                    nn      = Z(1:V.T);\n                    nn(n(:,j)<=nthr)=0;\n                    nn(n(:,j)>nthr)=1;\n                    CC(:,j) = filter(1,[1 -P.gam(j)],nn) + (1-P.gam(j))*P.b(j);\n                end\n            else\n                CC      = C;\n            end\n            \n            if V.est_b==1\n                A = [CC -1+Z(1:V.T)];\n            else\n                A=CC;\n            end\n            X = A\\F';\n            \n            P.a = X(1:V.Ncells,:)';\n            if V.est_b==1\n                P.b = X(end,:)';\n                b   = repmat(P.b,1,V.T);\n            end\n            \n            D   = F-P.a*(reshape(C,V.Ncells,V.T)) - b;\n            \n            mse = D(:)'*D(:);\n        end\n        \n        if V.est_a==0 && V.est_b==0 && (V.est_sig==1 || V.est_lam==1),\n            D   = F-P.a*(reshape(C,V.Ncells,V.T)+b);\n            mse = D(:)'*D(:);\n        end\n        \n        % estimate other parameters\n        if V.est_sig==1,\n            P.sig = sqrt(mse)/V.T;\n        end\n        if V.est_lam==1,\n            nnorm   = n./repmat(max(n),V.T,1);\n            if numel(P.lam)==V.Ncells\n                P.lam   = sum(nnorm)'/(V.T*V.dt);\n                lam     = repmat(P.lam,V.T,1)*V.dt;\n            else\n                P.lam   = nnorm/(V.T*V.dt);\n                lam     = P.lam*V.dt;\n            end\n            \n        end\n    end\n\n%% MakePlot\n    function MakePlot(n,F,P,V)\n        if V.fast_plot == 1\n            if V.Npixels>1                                     % plot spatial filter\n                figure(FigNum), nrows=V.Ncells;\n                for j=1:V.Ncells, subplot(1,nrows,j),\n                    imagesc(reshape(P.a(:,j),V.w,V.h)),\n                    title('a')\n                end\n            end\n            \n            figure(FigNum+1),  ncols=V.Ncells; nrows=3; END=V.T; h=zeros(V.Ncells,2);\n            for j=1:V.Ncells                                  % plot inferred spike train\n                h(j,1)=subplot(nrows,ncols,(j-1)*ncols+1); cla\n                if V.Npixels>1, Ftemp=mean(F); else Ftemp=F; end\n                plot(z1(Ftemp(2:END))+1), hold on,\n                bar(z1(n_best(2:END,j)))\n                title(['best iteration ' num2str(i_best)]),\n                axis('tight')\n                set(gca,'XTickLabel',[],'YTickLabel',[])\n                \n                h(j,2)=subplot(nrows,ncols,(j-1)*ncols+2); cla\n                bar(z1(n(2:END,j)))\n                if isfield(V,'n'), hold on,\n                    for k=1:V.Ncells\n                        stem(V.n(2:END,k)+k/10,'LineStyle','none','Marker','v','MarkerEdgeColor','k','MarkerFaceColor','k','MarkerSize',2)\n                    end\n                end\n                set(gca,'XTickLabel',[],'YTickLabel',[])\n                title(['current iteration ' num2str(i)]),\n                axis('tight')\n            end\n            \n            subplot(nrows,ncols,j*nrows),\n            plot(1:i,posts(1:i))    % plot record of likelihoods\n            title(['max lik ' num2str(post_max,4), ',   lik ' num2str(posts(i),4)])\n            set(gca,'XTick',2:i,'XTickLabel',2:i)\n            drawnow\n        end\n    end\nend", "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/oopsi-master/fast_oopsi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5523284713376069}}
{"text": "classdef PartialDCT < spx.dict.Operator \n\nproperties(SetAccess=private)\n    % Dimensions\n    row_pics\n    col_perm\n    num_rows\n    num_cols\nend\n\nmethods\n\nfunction self = PartialDCT(row_pics, col_perm)\n    if nargin < 2\n        error('Row selection and column permutation must be specified');\n    end\n    self.row_pics = row_pics;\n    self.col_perm = col_perm;\n    self.num_rows = numel(row_pics);\n    self.num_cols = numel(col_perm);\n    if self.num_rows > self.num_cols\n        error('Number of rows cannot be greater than number of columns.');\n    end\nend\n\nfunction [mm, nn]  = get_size(self)\n    mm = self.num_rows;\n    nn = self.num_cols;\nend\n\nfunction result = apply(self, vectors)\n    if size(vectors, 1) ~= self.num_cols\n        error('Dimensions mismatch');\n    end\n    result = dct(vectors(self.col_perm, :));\n    result = result(self.row_pics, :);\nend\n\nfunction result = apply_ctranspose(self, vectors)\n    if size(vectors, 1) ~= self.num_rows\n        error('Dimensions mismatch');\n    end\n    num_vectors = size(vectors, 2);\n    full_vectors = zeros(self.num_cols, num_vectors);\n    full_vectors(self.row_pics, :) = vectors;\n    result = zeros(self.num_cols, num_vectors);\n    result(self.col_perm, :) = idct(full_vectors);\nend\n\nfunction result = double(self)\n    % Converts the operator into a MATRIX\n    result = self.apply(eye(self.num_cols));\nend\n\n\nfunction result = norm(self)\n    error('Not implemented');\nend\n\nend\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/+dict/PartialDCT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5523279309721197}}
{"text": "% DEMBRENDAN1 Use the GP-LVM to model the Frey face data with back constraints.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'brendan';\nexperimentNo = 1;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('fitc');\noptions.optimiser = 'conjgrad';\noptions.back = 'kbr';\noptions.backOptions = kbrOptions(Y);\noptions.backOptions.kern = kernCreate(Y, 'rbf');\noptions.backOptions.kern.inverseWidth = 0.00001;\n\nlatentDim = 2;\nd = size(Y, 2);\n\nmodel = fgplvmCreate(latentDim, d, Y, options);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\ncapName = dataSetName;;\ncapName(1) = upper(capName(1));\nsave(['dem' capName num2str(experimentNo) '.mat'], 'model');\n\nif exist('printDiagram') & printDiagram\n  fgplvmPrintPlot(model, lbls, capName, experimentNo);\nend\n\n\n% Load the results and display dynamically.\nfgplvmResultsDynamic(dataSetName, experimentNo, 'image', [20 28], 1, 0, 1)\n\n% compute the nearest neighbours errors in latent space.\nerrors = fgplvmNearestNeighbour(model, lbls);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demBrendan1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5523279309721197}}
{"text": "function ind = mohsst5_points_to_grid_index(C)\n\n%data = mohsst5_loaddata();\n\nlon = C(1,:);\nlat = C(2,:);\n\nN_lon = 72;\nN_lat = 36;\n\n% Random locations to 5x5-grid\nind_lon = floor(lon/5)+(N_lon/2+1);\nind_lat = N_lat - (floor(lat/5)+(N_lat/2+1)) + 1;\n\nind = (ind_lon-1)*N_lat + ind_lat;", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/datasets/mohsst5/mohsst5_points_to_grid_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5523279287706393}}
{"text": "function [u] = spm_uc_RF(a,df,STAT,R,n)\n% Corrected critical height threshold at a specified significance level\n% FORMAT [u] = spm_uc_RF(a,df,STAT,R,n)\n% a     - critical probability - {alpha}\n% df    - [df{interest} df{residuals}]\n% STAT  - Statistical field\n%         'Z' - Gaussian field\n%         'T' - T field\n%         'X' - Chi-squared field\n%         'F' - F field\n% R     - RESEL Count {defining search volume}\n% n     - number of conjoint SPMs\n%\n% u     - critical height {corrected}\n%\n%__________________________________________________________________________\n%\n% spm_uc returns the corrected critical threshold at a specified significance\n% level (a). If n > 1 a conjunction probability over the n values of the\n% statistic is returned.\n%__________________________________________________________________________\n% Copyright (C) 1999-2012 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_uc_RF.m 4634 2012-02-01 19:01:09Z guillaume $\n\n\n%-Find approximate value\n%--------------------------------------------------------------------------\nu  = spm_u((a/max(R))^(1/n),df,STAT);\ndu = 1e-6;\n\n%-Approximate estimate using E{m}\n%--------------------------------------------------------------------------\nd  = 1;\nwhile abs(d) > 1e-6\n    [P, P, p] = spm_P_RF(1,0,u,df,STAT,R,n);\n    [P, P, q] = spm_P_RF(1,0,u + du,df,STAT,R,n);\n    d         = (a - p)/((q - p)/du);\n    u         = u + d;\n    if isinf(u), u=+Inf; return; end\nend\n\n%-Refined estimate using 1 - exp(-E{m})\n%--------------------------------------------------------------------------\nd  = 1;\nwhile abs(d) > 1e-6\n    p         = spm_P_RF(1,0,u,df,STAT,R,n);\n    q         = spm_P_RF(1,0,u + du,df,STAT,R,n);\n    d         = (a - p)/((q - p)/du);\n    u         = u + d;\n    if isinf(u), u=+Inf; return; 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/spm_uc_RF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5523279287706393}}
{"text": "function [ FRF, FBB ] = OMP( Fopt, NRF, At )\n\nFRF = [];\nFres = Fopt;\nfor k = 1:NRF\n    PU = At' * Fres;\n%     [aa,bb] = max(diag(PU * PU'));\n    [aa,bb] = max(sum( abs(PU).^2, 2 ));\n    FRF = [FRF , At(:,bb)];\n    FBB = pinv(FRF) * Fopt; %use pseudoinverse to avoid the inverse of a possible singular matrix\n    Fres = (Fopt - FRF * FBB) / norm(Fopt - FRF * FBB,'fro');\nend\n\nend\n\n", "meta": {"author": "yuxianghao", "repo": "Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems", "sha": "18f610e24498f2305a498459150492e17626754b", "save_path": "github-repos/MATLAB/yuxianghao-Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems", "path": "github-repos/MATLAB/yuxianghao-Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems/Alternating-minimization-algorithms-for-hybrid-precoding-in-millimeter-wave-MIMO-systems-18f610e24498f2305a498459150492e17626754b/Narrowband/OMP Algorithm/OMP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5523279237655392}}
{"text": "function anim = computeSMFromW( isProj, W, varargin )\n% Recover rigid structure and motion from 2D calibrated measurements W\n%\n% Essential matrix decomposition\n% Reference: HZ2, p259, Result 9.19, and p. 294\n% isProj && nFrame==2 && isCalibrated\n% fast\n%\n% Normalized 8-point algorithm\n% Reference: HZ2, p279 and alg 11.1 p. 282\n% isProj && nFrame==2 && ~isCalibrated\n% fast\n%\n% Projective Factorization\n% Reference: HZ2, p445, Algorithm 18.2\n% Sturm and Triggs ECCV 96\n% A Factorization Based Algorithm for Multi-Image Projective Structure and\n% Motion\n% isProj && nFrame>2 && method==0\n%\n% Projective Factorization\n% Reference: Iterative Extensions of the Sturm/Triggs Algorithm:\n% Convergence and Nonconvergence, from Oliensis, Hartley, PAMI 07\n% isProj && nFrame>2 && method==Inf\n% slower\n%\n% Gold Standard for Affine camera matrix\n% Reference: HZ2, p351, Algorithm 14.1\n% ~isProj && nFrame==2 && onlyErrorFlag\n% fast\n%\n% Tomasi Kanade without the metric constraint\n% Affine camera matrix, MLE estimation (Tomasi Kanade)\n% Reference: HZ2, p437, Algorithm 18.1\n% ~isProj && nFrame>2\n% fast\n%\n% Tomasi Kanade with the metric constraint\n% ~isProj && nFrame>2 && isCalibrated && method=0\n% fast\n%\n% Tomasi Kanade with the metric constraint (more accurate computation)\n% ~isProj && nFrame>2 && isCalibrated && method=inf\n% slow\n%\n% Tomasi Kanade and autocalibration\n% ~isProj && nFrame>2 && ~isCalibrated\n% slow\n%\n% if doAffineUpgrade and/or doMetricUpgrade are true, affine and metric\n% upgrades from Chandraker IJCV 2009 is applied\n% slow\n%\n% If there are any missing entries:\n% Low-Rank Matrix Fitting Based on Subspace Perturbation Analysis\n% with Applications to Structure from Motion\n% Hongjun Jia, Aleix M. Martinez, PAMI 08\n%\n% Returns the structure and camera parameters in an Animation object\n%\n% USAGE\n%   anim = computeSMFromW( isProj, W, 'method',method )\n%   anim = computeSMFromW( isProj, W,'method',Inf,'onlyErrorFlag',true )\n%\n% INPUTS\n%  isProj     - flag indicating if the camera is projective\n%  W          - [] [ 2 x nPoint x nFrame ] 2D projected features (NaN if\n%               missing entry\n%  varargin   - list of paramaters in quotes alternating with their values\n%       - 'isCalibrated' [false] flag indicating if the cameras are\n%                        calibrated (intrinsic parameters are identity)\n%       - 'doAffineUpgrade' [false] flag indicating if the affine upgrade\n%                        is computed\n%       - 'doMetricUpgrade' [false] flag indicating if the metric upgrade\n%                        is computed\n%       - 'K',[] [3 x 1 ], [ 3 x nFrame ] calibration parameters\n%                       (or [5 x 1 ], [ 5 x nFrame ] when projective)\n%                       If given, they won't be optimized upon, you will\n%                       need to run bundle adjustment after that\n%       - 'KFull',[] [3 x 3 ] or [ 3 x 3 x nFrame ] calibration matrices\n%       - 'method', [inf] method for performing SFM (see above for details)\n%       - 'onlyErrorFlag', [false] flag indicating if only the error is\n%         needed when nFrame==2 && method==Inf && ~isProj\n%       - 'nItrSba', [100] number of bundle adjustment iterations\n%       - 'tolAffine', [1e-5] tolerance for affine upgrade as explained in\n%                          affineUpgrade\n%       - 'tolMetric', [1e-5] tolerance for affine upgrade as explained in\n%                          metricUprgade\n%\n% OUTPUTS 1\n%  anim      - Animation object\n%\n% OUTPUTS 2\n%  err       - error, acoording to Gold Standard for Affine camera matrix\n%\n% EXAMPLE\n%\n% See also\n%\n% Vincent's Structure From Motion Toolbox      Version 3.1.1\n% Copyright (C) 2008-2011 Vincent Rabaud.  [vrabaud-at-cs.ucsd.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the GPL [see external/gpl.txt]\n\n[ isCalibrated doAffineUpgrade doMetricUpgrade K KFull method ...\n  onlyErrorFlag nItrSBA tolAffine tolMetric ] = getPrmDflt( varargin, ...\n  { 'isCalibrated' false 'doAffineUpgrade' false 'doMetricUpgrade' false ...\n  'K' [] 'KFull' [] 'method' inf 'onlyErrorFlag' false 'nItrSBA' 100 ...\n  'tolAffine' 1e-5 'tolMetric' 1e-5}, 1);\n\n% Remove points that do not have two views with no NaN's\ngood_point_mask = sum(~any(isnan(W),1),3) >=2;\nW = W(:,good_point_mask,:);\n\nnFrame = size(W,3); nPoint = size(W,2);\n\nif doMetricUpgrade; doAffineUpgrade=true; end\nif nFrame==2\n  doAffineUpgrade=false;\n  if ~isCalibrated; doMetricUpgrade=false; end\nend\n\nif size(W,1)==3; W = normalizePoint(W,3); end\n\n% create an animation object that wil contain the output\nanim=Animation(); anim.isProj=isProj; WOri=W;\n\n% If calibrated, apply inv(K)\nif ~isempty(K); anim.K=K; end\nif ~isempty(KFull); anim.KFull=KFull; end\nKFull=anim.KFull;\nif ~isempty(KFull)\n  isCalibrated=true;\n  doMetricUpgrade=true;\n  anim.KFull=[];\n  % unapply the internal parameter matrix to the measurements\n  if size(KFull,3)==1\n    W = normalizePoint(multiTimes(inv(KFull),normalizePoint(W,-3),1.2),3);\n  else\n    invKFull = zeros(3,3,nFrame);\n    for i=1:nFrame; invKFull(:,:,i) = inv(KFull(:,:,i)); end\n    W = normalizePoint(multiTimes(inv(KFull),normalizePoint(W,-3),2),3);\n  end\nend\n\nif isProj\n  [P,S] = computeSMFromWProjective( W, method, isCalibrated );\nelse\n  [P,S] = computeSMFromWAffine( W, method, onlyErrorFlag );\nend\nif onlyErrorFlag; anim=P; return; end\n\n% fill the Animation object with the results\nanim.S=S; anim.P=P; anim.W=W;\n\n% perform an affine upgrade if requested\nH=[];\nif anim.isProj && ~isCalibrated\n  % do bundle adjustment\n  if nItrSBA > 0\n    anim = bundleAdjustment( anim, 'nItr', nItrSBA );\n  else\n    anim = bundleAdjustment( anim, 'nItr', 20 );\n  end\n  \n  % modify P so that P(:,:,1)==eye(3,4)\n  anim=anim.setFirstPRtToId();\n  \n  % if we want to do an affine upgrade\n  if doAffineUpgrade\n    % only apply the quasi affine upgrade if we are under octave\n    % (as Yalmip does not work there)\n    if exist('OCTAVE_VERSION','builtin')==5\n      warning('Only performing a quasi-affine upgrade under Octave');\n      [ HEye, Hqa ] = affineUpgrade(anim);\n      H=HEye*Hqa;\n    else\n      [ HEye, Hqa, pInf ] = affineUpgrade(anim, 'tol', tolAffine);\n      % if the camera is calibrated or if we do not do a metric upgrade\n      % stop here\n      if ~doMetricUpgrade\n        % apply H\n        H=eye(4); H(4,1:3)=-pInf;\n        H=HEye*H;\n      end\n    end\n    if doMetricUpgrade\n      % perform a metric upgrade if requested\n      if exist('OCTAVE_VERSION','builtin')==5\n        H=metricUpgrade(anim, 'isCalibrated', isCalibrated);\n      else\n        [ H, anim.KFull ]=metricUpgrade(anim, 'pInf', pInf, ...\n          'isCalibrated', isCalibrated, 'tol', tolMetric);\n      end\n    end\n  end\nend\nif anim.isProj && ~isCalibrated\n  if doMetricUpgrade\n    H=metricUpgrade(anim, 'isCalibrated', isCalibrated, 'method', method);\n  end\nend\n\n% apply the homography H\nif ~isempty(H)\n  anim.P=multiTimes(anim.P,H,1);\n  anim.S=normalizePoint(H\\normalizePoint(anim.S,-4),4);\nend\n\n% recover rotations and translations\nif doMetricUpgrade && (exist('OCTAVE_VERSION','builtin')~=5 || isCalibrated)\n  P=anim.P;\n  if ~isCalibrated && ~isempty(anim.KFull)\n    if size(anim.KFull,3)==1; P=multiTimes(inv(anim.KFull),P,1.2);\n    else P=multiDiv(anim.KFull,P,2);\n    end\n  end\n  R=zeros(3,3,nFrame);\n  if anim.isProj\n    for i=1:nFrame\n      P(:,:,i)=P(:,:,i)/nthroot(det(P(:,1:3,i)),3);\n      R(:,:,i)=rotationMatrix(P(:,1:3,i));\n    end\n    anim.t=reshape(P(:,4,:),3,nFrame);\n  else\n    for i=1:nFrame\n      R(:,:,i)=rotationMatrix(rotationMatrix(P(1:2,1:3,i)));\n    end\n    anim.t=reshape(P(1:2,4,:),2,nFrame); anim.t(3,:)=0;\n  end\n  anim.R=R;\n  \n  anim=anim.setFirstPRtToId();\nend\n\n% update the mask if any\nmask=reshape(any(~isnan(W),1),nPoint,nFrame);\nif any(mask==0); anim.mask=mask; end\n\n% do a final bundle adjustment\nif nItrSBA > 0; anim = bundleAdjustment( anim, 'nItr', nItrSBA ); end\n\nW = anim.W; S = anim.S;\nanim.W = zeros(2, length(good_point_mask), nFrame);\nanim.S = zeros(3, length(good_point_mask), nFrame);\nanim.W = W; anim.S = S;\n\n% Re-assign the KFull from the input arguments if any\nif ~isempty(KFull); anim.KFull=KFull; anim.W=WOri; end\nend\n", "meta": {"author": "vrabaud", "repo": "sfm_toolbox", "sha": "7ce933b31b71292eddabb40bacfd619720fa221d", "save_path": "github-repos/MATLAB/vrabaud-sfm_toolbox", "path": "github-repos/MATLAB/vrabaud-sfm_toolbox/sfm_toolbox-7ce933b31b71292eddabb40bacfd619720fa221d/sfm/computeSMFromW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.552327923031712}}
{"text": "% test for data interpolation using geodesic distances\n\nrep  = 'data/';\nrep  = '';\n\nname = 'mm';\nname = 'cavern';\nname = 'disk';\nname = 'toto';\nname = 'boat';\nname = 'cartoon';\n\nclear options;\noptions.null = 0;\n\n%% compute a binary shape\nn = 300;\nif strcmp(name, 'toto')\n    M0 = load_image([rep name],n);\n    M = sum(M0,3);\n    M = 1-(M==M(1));\n    % compute the constraint map\n    CM = zeros(n) + Inf; CM(M==0) = -Inf;\n    options.constraint_map = CM; % constraint the propagation inside the shape\n    W = ones(n);\n    mode = 'interpolation';\nelse\n    n0 = [];\n    if strcmp(name, 'disk')\n        n0 = n;\n    end\n    if strcmp(name, 'cartoon')\n        n0 = 400;\n    end\n    M = load_image([rep name],n0);\n    M = rescale(crop(M,n)); M0 = M;\n    M = rescale(sum(M,3));\n    W = compute_edge_energy(M, 1.2);\n    W = 1./rescale(W,0.001,1);\n    mode = 'colorization';\nend\n\n% RGB2COL matrix\nCM = rand(3); CM(:,1) = 1;\n[CM,R] = qr(CM); CM(:,1) = 1/3; CM = CM'; \n\n%% pick some points\nb = 1;\npoints = [];\nwhile b==1\n    clf;\n    hold on;\n    imagesc(rescale(M)); axis image; axis off;\n    if not(isempty(points))\n        plot_scattered(points(end:-1:1,:));\n    end\n    colormap gray(256); axis ij;\n    hold off;\n    [y,x,b] = ginput(1);\n    if b==1\n        points(:,end+1) = [x;y];\n    end\nend\nnpoints = size(points,2);\n% random colors (sqrt to make it more colorfull\nf = rand(3,npoints);\nf = ( f ./ repmat(sum(f,1),[3, 1]) ).^(1);\n% use fixed palette\nfc = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 1 0 1; 0 1 1; 0.2 0.7 1; 1 0.2 0.7; 0.7 1 0.2; 0.2 1 0.7]';\nsel =  floor(rand(npoints,1)*6)+1;\nf = fc(:,sel);\n\nif strcmp(mode, 'colorization')\n    % random CbCr\n    f = CM*f; f = f(2:end,:);\nend\n\n%% perform interpolation\nif strcmp(mode, 'colorization')\n    sigma_list = 0.001/n;\n    alpha_list = 3;\nelse\n    % the smaller, the more interpolation is performed\n    % the higher, the more diffusion it is\n    sigma_list = [25 25 25 0.01 0.01 0.01]/n;\n    % the higher, the more \"voronoi\"-like it is\n    alpha_list = [1 3 50 1 3 50];\nend\n\nnsigma = length(sigma_list);\nnrows = 1;\nif nsigma>3\n    nrows = 2;\nend\n\nclf;\nfor i=1:nsigma\n    options.sigma = sigma_list(i);\n    options.alpha = alpha_list(i);\n    [A,G] = perform_geodesic_interpolation(W,points,f,options);\n    \n    if strcmp(mode, 'colorization')\n        % cat the luminosity component\n        A = cat(3, M,A);\n        A = reshape(A, [n^2 3])';\n        A = ( (CM^(-1)) * A )';\n        A = reshape( A, [n n 3] );\n    end\n    A = clamp(A);\n    subplot(nrows,ceil(nsigma/nrows), i);\n    hold on;\n    imagesc(rescale(A)); axis image; axis off; axis ij;\n    plot_scattered(points(end:-1:1,:));\n    hold off;\n    title(['\\alpha=' num2str(options.alpha) ', \\sigma=' num2str(options.sigma)]);\nend", "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_interpolation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5523279130215115}}
{"text": "function test_subplot_2D\n%TEST_SUBPLOT_2D Test subplot 2D with DRAGZOOM\n\nfigure('Units', 'pixels');\nx = -pi*2:0.1:pi*2;\ny1 = sin(x);\ny2 = cos(x);\ny3 = sin(x).^3 - cos(x).^2;\n\nhax1 = subplot(3, 1, 1); \nplot(hax1, x, y1, '.-r')\n\nhax2 = subplot(3, 1, 2); \nplot(hax2, x, y2, 'o-b')\n\nhax3 = subplot(3, 1, 3); \nplot(hax3, x, y3, '*-g')\nlegend('test')\n\n% dragzoom([hax1; hax3]); % manage only axes 1 and axes 3\ndragzoom()\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29276-dragzoom-drag-and-zoom-tool/test_subplot_2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5522986847976417}}
{"text": "function determ = conex2_determinant ( alpha )\n\n%*****************************************************************************80\n%\n%% CONEX2_DETERMINANT returns the determinant of the CONEX2 matrix.\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%  Parameters:\n%\n%    Input, real ALPHA, the scalar defining A.  \n%\n%    Output, real DETERM, the determinant.\n%\n  determ = 1.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_mat/conex2_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.5522729615155751}}
{"text": "function test_suite = test_daubcqf\ninitTestSuite;\n\nfunction test_daubcqf_min\n  [a, b] = daubcqf(4);\n  ax = [0.482962913144534   0.836516303737808   0.224143868042013  -0.129409522551260];\n  bx = [0.129409522551260   0.224143868042013  -0.836516303737808   0.482962913144534];\nassertVectorsAlmostEqual(a, ax, 'relative', 0.001);\nassertVectorsAlmostEqual(b, bx, 'relative', 0.001);\n\nfunction test_daubcqf_max\n  [a, b] = daubcqf(4, 'max');\n  ax = [-0.129409522551260   0.224143868042013   0.836516303737808   0.482962913144534];\n  bx = [-0.482962913144534   0.836516303737808  -0.224143868042013  -0.129409522551260];\nassertVectorsAlmostEqual(a, ax, 'relative', 0.001);\nassertVectorsAlmostEqual(b, bx, 'relative', 0.001);\n\nfunction test_daubcqf_mid_even_k\n  [a, b] = daubcqf(4, 'mid');\n  ax = [0.482962913144534   0.836516303737808   0.224143868042013  -0.129409522551260];\n  bx = [0.129409522551260   0.224143868042013  -0.836516303737808   0.482962913144534];\nassertVectorsAlmostEqual(a, ax, 'relative', 0.001);\nassertVectorsAlmostEqual(b, bx, 'relative', 0.001);\n\nfunction test_daubcqf_mid_odd_k\n  [a, b] = daubcqf(6, 'mid');\n  ax = [0.332670552950083   0.806891509311093   0.459877502118491  -0.135011020010255  -0.085441273882027   0.035226291885710];\n  bx = [-0.035226291885710  -0.085441273882027   0.135011020010255   0.459877502118491 -0.806891509311093   0.332670552950083];\nassertVectorsAlmostEqual(a, ax, 'relative', 0.001);\nassertVectorsAlmostEqual(b, bx, 'relative', 0.001);\n\nfunction test_daubcqf_odd\n  handle = @() daubcqf(9);\nassertExceptionThrown(handle, '');\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/tests/test_daubcqf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5522729615155751}}
{"text": "function s = ymdf_to_s_roman ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_S_ROMAN writes a Roman YMDF date into a string.\n%\n%  Example:\n%\n%     Y  M   D  F    S\n%    --  -  --  ---  -----------------------------------\n%    56  4   1  0.1  Kalends Aprilis DVI AUC\n%    56  4   2  0.2  Ante diem iv Nones Aprilis DVI AUC\n%    56  4   3  0.3  Ante diem iii Nones Aprilis DVI AUC\n%    56  4   4  0.4  Pridie Nones Aprilis DVI AUC\n%    56  4   5  0.5  Nones Aprilis DVI AUC\n%    56  4   6  0.6  Ante diem viii Ides Aprilis DVI AUC\n%    56  4   7  0.7  Ante diem vii Ides Aprilis DVI AUC\n%    56  4   8  0.8  Ante diem vi Ides Aprilis DVI AUC\n%    56  4   9  0.9  Ante diem v Ides Aprilis DVI AUC\n%    56  4  10  0.0  Ante diem iv Ides Aprilis DVI AUC\n%    56  4  11  0.0  Ante diem iii Ides Aprilis DVI AUC\n%    56  4  12  0.0  Pridie Ides Aprilis DVI AUC\n%    56  4  13  0.0  Ides Aprilis DVI AUC\n%    56  4  14  0.0  Ante diem xvii Kalends Maius DVI AUC\n%    56  4  15  0.0  Ante diem xvi Kalends Maius DVI AUC\n%    ...\n%    56  4  28  0.0  Ante diem iv Kalends Maius DVI AUC\n%    56  4  29  0.0  Ante diem iii Kalends Maius DVI AUC\n%    56  4  30  0.0  Pridie Kalends Maius DVI AUC\n%\n%  Discussion:\n%\n%    \"AUC\" means \"ab urbe condita\", or \"from the founding of the city\".\n%\n%    At the moment, we ignore F.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    16 March 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer Y, M, D, real F, the YMDF date.\n%\n%    Output, string S, a string representing the date.\n%\n\n%\n%  Check the input.\n%\n  [ y2, m2, d2, ierror ] = ymd_check_roman ( y, m, d );\n\n  if ( ierror ~= 0 )\n    s = '?';\n    return\n  end\n\n  s_month = month_to_month_name_roman ( m2 );\n%\n%  Get the next month's name.\n%\n  m3 = i4_wrap ( m2 + 1, 1, 12 );\n  s_month_next = month_to_month_name_roman ( m3 );\n\n  nones = month_to_nones_roman ( m2 );\n  ides = month_to_ides_roman ( m2 );\n  last = month_length_roman ( y2, m2 );\n\n  if ( d2 == 1 )\n    s = [ 'Kalends ', s_month ];\n  elseif ( d2 < nones - 1 )\n    jday = nones + 1 - d2;\n    s_day = i4_to_roman ( jday );\n    s = [ 'Ante diem ', s_day, ' Nones ', s_month ];\n  elseif ( d2 == nones - 1 )\n    s = [ 'Pridie Nones ', s_month ];\n  elseif ( d2 == nones )\n    s = [ 'Nones ', s_month ];\n  elseif ( d2 < ides - 1 )\n    jday = ides + 1 - d2;\n    s_day = i4_to_roman ( jday );\n    s = [ 'Ante diem ', s_day, ' Ides ', s_month ];\n  elseif ( d2 == ides - 1 )\n    s = [ 'Pridie Ides ', s_month ];\n  elseif ( d2 == ides )\n    s = [ 'Ides ', s_month ];\n  elseif ( m2 == 2 && year_is_leap_roman ( y2 ) )\n\n    if ( d2 < 25 )\n      jday = last + 1 - d2;\n      s_day = i4_to_roman ( jday );\n      s = [ 'Ante diem ', s_day, ' Kalends ', s_month_next ];\n    elseif ( d2 == 25 )\n      jday = last + 2 - d2;\n      s_day = i4_to_roman ( jday );\n      s = [ 'Ante diem Bis ', s_day, ' Kalends ', s_month_next ];\n    elseif ( d2 < last )\n      jday = last + 2 - d2;\n      s_day = i4_to_roman ( jday );\n      s = [ 'Ante diem ', s_day, ' Kalends ', s_month_next ];\n    else\n      s = [ 'Pridie Kalends ', s_month_next ];\n    end\n\n  elseif ( d2 < last )\n    jday = last + 2 - d2;\n    s_day = i4_to_roman ( jday );\n    s = [ 'Ante diem ', s_day, ' Kalends ', s_month_next ];\n  else\n    s = [ 'Pridie Kalends ', s_month_next ];\n  end\n\n  s_year = i4_to_roman ( y2 );\n  s = [ s, ' ', s_year, ' AUC' ];\n\n  s = s_blanks_delete ( 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/ymdf_to_s_roman.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.5522729531589701}}
{"text": "function varargout = norm(varargin)\n%NORM (overloaded)\n%\n% t = NORM(x,P)\n%\n% The variable t can only be used in convexity preserving\n% operations such as t<0, max(t,y)<1, minimize t etc.\n%\n%    For matrices...\n%      NORM(X) models the largest singular value of X, max(svd(X)).\n%      NORM(X,2) is the same as NORM(X).\n%      NORM(X,1) models the 1-norm of X, the largest column sum, max(sum(abs(X))).\n%      NORM(X,inf) models the infinity norm of X, the largest row sum, max(sum(abs(X'))).\n%      NORM(X,'fro') models the Frobenius norm, sqrt(sum(diag(X'*X))).\n%    For vectors...\n%      NORM(V) = norm(V,2) = standard Euclidean norm.\n%      NORM(V,inf) = max(abs(V)).\n%      NORM(V,1) = sum(abs(V))\n%\n% SEE ALSO SUMK, SUMABSK\n\n%% ***************************************************\n% This file defines a nonlinear operator for YALMIP\n%\n% It can take three different inputs\n% For DOUBLE inputs, it returns standard double values\n% For SDPVAR inputs, it generates an internal variable\n%\n% When first input is 'model' it returns the graph\n% in the first output and structure describing some\n% properties of the operator.\n\n%% ***************************************************\nswitch class(varargin{1})\n\n    case 'double' % What is the numerical value of this argument (needed for displays etc)\n        % SHOULD NEVER HAPPEN, THIS SHOULD BE CAUGHT BY BUILT-IN\n        error('Overloaded SDPVAR/NORM CALLED WITH DOUBLE. Report error')\n\n    case 'sdpvar' % Overloaded operator for SDPVAR objects. Pass on args and save them.\n        if nargin == 1\n            varargout{1} = yalmip('addextendedvariable',mfilename,varargin{1},2);\n        else\n            switch varargin{2}\n                case {1,2,inf,'inf','fro'}\n                    varargout{1} = yalmip('addextendedvariable',mfilename,varargin{:});\n                otherwise\n                    error('norm(x,P) only supported for P = 1, 2, inf and ''fro''');\n            end\n        end\n\n    case 'char' % YALMIP sends 'model' when it wants the epigraph or hypograph\n        switch varargin{1}\n            case 'graph'\n                t = varargin{2};\n                X = varargin{3};\n                p = varargin{4};\n\n                % Code below complicated by two things\n                % 1: Absolute value for complex data -> cone constraints on\n                %    elements\n                % 2: SUBSREF does not call SDPVAR subsref -> use extsubsref.m\n\n                % FIX : Exploit symmetry to create smaller problem\n                switch p\n                    case 1\n                        z = sdpvar(size(X,1),size(X,2),'full');\n                        if min(size(X))>1\n                            if isreal(X)\n                                F = (-z <= X <= z);\n                            else\n                                F = ([]);\n                                for i = 1:size(X,1)\n                                    for j = 1:size(X,2)\n                                        xi = extsubsref(X,i,j);\n                                        zi = extsubsref(z,i,j);\n                                        F = F + (cone([real(xi);imag(xi)],zi));\n                                    end\n                                end\n                            end\n                            F = F + (sum(z,1) <= t);\n                        else\n                            if isreal(X)\n                                F = (-z <= X <= z) + (sum(z) <= t);\n                                [M,m] = derivebounds(X);\n                                bounds(z,0,max(abs([M -m]),[],2));\n                                bounds(t,0,sum(max(abs([M -m]),[],2)));\n                            else\n                                F = ([]);\n                                for i = 1:length(X)\n                                    xi = extsubsref(X,i);\n                                    zi = extsubsref(z,i);\n                                    F = F + (cone([real(xi);imag(xi)],zi));\n                                end\n                                F = F + (sum(z) <= t);\n                            end\n                        end\n                    case 2\n                        z = sdpvar(size(X,1),size(X,2));\n                        if min(size(X))>1\n                            F = ([t*eye(size(X,1)) X;X' t*eye(size(X,2))])>=0;\n                        else\n                            F = (cone(X(:),t));\n                        end\n                    case {inf,'inf'}\n                        if min(size(X))>1\n                            z = sdpvar(size(X,1),size(X,2),'full');\n                            if isreal(X)\n                                F = (-z <= X <= z);\n                            else\n                                F = ([]);\n                                for i = 1:size(X,1)\n                                    for j = 1:size(X,2)\n                                        xi = extsubsref(X,i,j);\n                                        zi = extsubsref(z,i,j);\n                                        F = F + (cone([real(xi);imag(xi)],zi));\n                                    end\n                                end\n                            end\n                            F = F + (sum(z,2) <= t);\n                        else\n                            if isreal(X)\n                                F = (-t <= X <= t);\n                                [M,m,infbound] = derivebounds(X);\n                                if ~infbound\n                                    F = F + (0<=t<=max(M));\n                                end\n                            else\n                                F = ([]);\n                                for i = 1:length(X)\n                                    xi = extsubsref(X,i);\n                                    F = F + (cone([real(xi);imag(xi)],t));\n                                end\n                            end\n                        end\n                    case 'fro'\n                        X.dim(1)=X.dim(1)*X.dim(2);\n                        X.dim(2)=1;\n                        F = (cone(X,t));\n                    otherwise\n                end\n                varargout{1} = F;\n                varargout{2} = struct('convexity','convex','monotonicity','none','definiteness','positive');\n                varargout{3} = X;\n            case 'milp'\n\n                t = varargin{2};\n                X = varargin{3};\n                p = varargin{4};\n                if ~isreal(X) | isequal(p,2) | isequal(p,'fro') | min(size(X))>1 % Complex valued data, matrices and 2-norm not supported\n                    varargout{1} = [];\n                    varargout{2} = [];\n                    varargout{3} = [];\n                else\n                    if p==1\n                        X     = reshape(X,length(X),1);\n                        absX  = sdpvar(length(X),1);\n                        d     = binvar(length(X),1);\n                        [M,m] = derivebounds(X);\n                         F = ([]);\n                         positive = find(m >= 0);\n                         negative = find(M <= 0);\n                         \n                         % d(find(positive)) = 1;\n                         % d(find(negative)) = 0;                         \n                         if ~isempty(positive)                             \n                             d = subsasgn(d,struct('type','()','subs',{{positive}}),1);\n                         end\n                         if ~isempty(negative)                             \n                             d = subsasgn(d,struct('type','()','subs',{{negative}}),0);\n                         end\n                         \n                         F = F + (X <= M.*d)     + (2*m.*d     <= absX+X <= 2*M.*d);\n                         F = F + (X >= m.*(1-d)) + (2*m.*(1-d) <= absX-X <= 2*M.*(1-d));\n                         F = F + (t - sum(absX) == 0);\n                         \n                    else\n\n                        if 0\n\n                            %2^n cases\n                            %e.g in 2d,\n                            %norm([x;y],inf) = y, y>0, y>x.y>-x\n                            %                = x, x>0, x>y.x>-y\n\n                            n = length(X);\n                            X     = reshape(X,n,1);\n                            absX  = sdpvar(n,1);\n                            d     = binvar(n,1);\n                            [M,m] = derivebounds(X);\n\n                            F = (sum(d)==0);\n\n                            top = 1;\n                            for i = 1:n\n                                xi = extsubsref(X,i);\n                                y = extsubsref(X,setdiff(1:n,i));\n                                for sign_abs_largest_variable = -1:2:1\n                                    di = extsubsref(d,top);\n                                    for j = setdiff(1:n,i)\n                                        y = extsubsref(X,j);\n                                        for sign_other = -1:2:1\n                                            F = F + (xi*sign_abs_largest_variable >= sign_other*y);\n                                            F = F + (-M*100*(1-di) <= xi*sign_abs_largest_variable-t <= t+M*100*(1-di));\n                                        end\n                                    end\n                                    top = top + 1;\n                                end\n                            end\n\n\n\n\n                        else\n                            % OLD\n                            n = length(X);\n                            X     = reshape(X,n,1);\n                            absX  = sdpvar(n,1);\n                            d     = binvar(n,1);\n                            [M,m] = derivebounds(X);\n                            F = ([]);\n                            F = F + (X <= M.*d)     + (2*m.*d     <= absX+X <= 2*M.*d);\n                            F = F + (X >= m.*(1-d)) + (2*m.*(1-d) <= absX-X <= 2*M.*(1-d));\n                            M = max(M,-m);\n                            d = binvar(n,1);\n                            F = F + (sum(d)==1);\n                            F = F + (absX <= t <= absX + M.*(1-d));\n\n                            kk = [];\n                            ii = [];\n                            for i = 1:n\n                                k = [1:1:i-1 i+1:1:n]';\n                                ii = [ii;repmat(i,n-1,1)];\n                                kk = [kk;k];\n                                Mm = M(k);\n                            end\n                            xii = extsubsref(absX,ii);\n                            dii = extsubsref(d,ii);\n                            xkk = extsubsref(absX,kk);\n                            F = F + (xkk <= xii+(M(kk)-m(ii)).*(1-dii));\n                        end\n\n                        %   for i = 1:n\n                        %       xi = extsubsref(absX,i);\n                        %       di = extsubsref(d,i);\n                        %       for k = [1:1:i-1 i+1:1:n]\n                        %           xk = extsubsref(absX,k);\n                        %           F = F + (xk <= xi+M(k)*(1-di));\n                        %       end\n                        %   end\n\n                    end\n                    varargout{1} = F;\n                    varargout{2} = struct('convexity','milp','monotonicity','milp','definiteness','positive');\n                    varargout{3} = X;\n                end\n            otherwise\n                error('SDPVAR/NORM called with CHAR argument?');\n        end\n    otherwise\n        error('Strange type on first argument in SDPVAR/NORM');\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/extras/@ncvar/norm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5522487644050063}}
{"text": "%GETSIZE Dataset size and number of classes\n%\n%  [M,K,C] = GETSIZE(A,DIM)\n%\n% INPUT\n%   A    Dataset\n%   DIM  1,2 or 3 : the number of the output argument to be returned\n%\n% OUTPUT\n%   M    Number of objects\n%   K    Number of features\n%   C    Number of classes\n%\n% DESCRIPTION\n% Returns size of the dataset A and the number of classes. C is determined\n% from the number of labels stored in A.LABLIST. If DIM = 1,2 or 3, just \n% one of these numbers is returned, e.g. C = GETSIZE(A,3).\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/@prdataset/getsize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5521957662522077}}
{"text": "function calpak_test013 ( )\n\n%*****************************************************************************80\n%\n%% CALPAK_TEST013 tests JED_TO_YMDF_ARMENIAN and YMDF_TO_JED_ARMENIAN.\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  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'CALPAK_TEST013\\n' );\n  fprintf ( 1, '  For the Armenian calendar:\\n' );\n  fprintf ( 1, '  JED_TO_YMDF_ARMENIAN: JED -> YMDF.\\n' );\n  fprintf ( 1, '  YMDF_TO_JED_ARMENIAN: YMDF -> JED.\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  JED (in)    YMDF               JED (out)\\n' );\n  fprintf ( 1, '\\n' );\n\n  jed_epoch = epoch_to_jed_armenian ( );\n\n  i = 0;\n\n  while ( 1 )\n\n    i = i + 1;\n    jed1 = jed_test ( i );\n \n    if ( jed1 < 0.0 )\n      break\n    end\n\n    if ( jed_epoch <= jed1 )\n\n      [ y2, m2, d2, f2 ] = jed_to_ymdf_armenian ( jed1 );\n\n      s2 = ymdf_to_s_numeric ( y2, m2, d2, f2 );\n\n      jed3 = ymdf_to_jed_armenian ( y2, m2, d2, f2 );\n\n      fprintf ( 1, '  %11.2f  %20s  %11.2f\\n', jed1, s2, jed3 );\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/calpak/calpak_test013.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5521957454098926}}
{"text": "function code = tree_rooted_code ( nnode, parent )\n\n%*****************************************************************************80\n%\n%% TREE_ROOTED_CODE returns the code of a rooted tree.\n%\n%  Discussion:\n%\n%    This code for a rooted tree depends on the node ordering, so it's actually\n%    the code for a labeled rooted tree.  To eliminate the effects of node\n%    labeling, one could choose as the code for a tree the maximum of all\n%    the codes associated with the different possible labelings of the tree.\n%    There are more effective ways of arriving at this code than simply\n%    generating all possible codes and comparing them.  \n%\n%    For a tree with NNODES, the code is a list of 2*NNODE 0's and 1's,\n%    describing a traversal of the tree starting at an imaginary node 0,\n%    moving \"down\" to the root (a code entry of 1), and then moving\n%    \"down\" (1) or \"up\" (0) as the tree is traversed in a depth first\n%    manner.  The final move must be from the root up to the imaginary\n%    node 0.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license. \n%\n%  Modified:\n%\n%    28 June 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer NNODE, the number of nodes.\n%\n%    Input, integer PARENT(NNODE), is the parent node of each node.\n%    The node with parent 0 is the root.\n%\n%    Output, integer CODE(2*NNODE), the code for the tree.\n%\n\n%\n%  Find the root.\n%\n  father = 0;\n  for i = 1 : nnode\n    if ( parent(i) == 0 )\n      k = 1;\n      code(1) = 1;\n      father = i;\n      break\n    end\n  end\n\n  if ( father == 0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'TREE_ROOTED_CODE - Fatal error!\\n' );\n    fprintf ( 1, '  Could not find the root.\\n' );\n    error ( 'TREE_ROOTED_CODE - Fatal error!' );\n  end\n\n  while ( father ~= 0 ) \n\n    k = k + 1;\n    code(k) = 0;\n\n    for son = 1 : nnode\n      if ( parent(son) == father )\n        code(k) = 1;\n        father = son;\n        break\n      end\n    end\n\n    if ( code(k) == 0 )\n      parent(father) = - parent(father);\n      father = - parent(father);\n    end\n\n  end\n\n  parent(1:nnode) = - parent(1:nnode);\n\n  return\nend\n", "meta": {"author": "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_code.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.5521953687098895}}
{"text": "function [ less, equal, more ] = r8r8vec_index_search ( n, x, y, indx, ...\n  xval, yval )\n\n%*****************************************************************************80\n%\n%% R8R8VEC_INDEX_SEARCH searches for an R8R8 value in an indexed sorted list.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 May 2005\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer N, the size of the current list.\n%\n%    Input, real X(N), Y(N), the list.\n%\n%    Input, integer INDX(N), the sort index of the list.\n%\n%    Input, real XVAL, YVAL, the value to be sought.\n%\n%    Output, integer LESS, EQUAL, MORE, the indexes in INDX of the\n%    entries of X that are just less than, equal to, and just greater\n%    than XVAL.  If XVAL does not occur in X, then EQUAL is zero.\n%    If XVAL is the minimum entry of X, then LESS is 0.  If XVAL\n%    is the greatest entry of X, then MORE is N+1.\n%\n  if ( n <= 0 )\n    less = 0;\n    equal = 0;\n    more = 0;\n    return\n  end\n\n  lo = 1;\n  hi = n;\n\n  xlo = x(indx(lo));\n  ylo = y(indx(lo));\n\n  xhi = x(indx(hi));\n  yhi = y(indx(hi));\n\n  compare = r8r8_compare ( xval, yval, xlo, ylo );\n\n  if ( compare == -1 )\n    less = 0;\n    equal = 0;\n    more = 1;\n    return\n  elseif ( compare == 0 )\n    less = 0;\n    equal = 1;\n    more = 2;\n    return\n  end\n\n  compare = r8r8_compare ( xval, yval, xhi, yhi );\n\n  if ( compare == 1 )\n    less = n;\n    equal = 0;\n    more = n + 1;\n    return\n  elseif ( compare == 0 )\n    less = n - 1;\n    equal = n;\n    more = n + 1;\n    return\n  end\n\n  while ( 1 )\n\n    if ( lo + 1 == hi )\n      less = lo;\n      equal = 0;\n      more = hi;\n      return\n    end\n\n    mid = round ( ( lo + hi ) / 2 );\n    xmid = x(indx(mid));\n    ymid = y(indx(mid));\n\n    compare = r8r8_compare ( xval, yval, xmid, ymid );\n\n    if ( compare == 0 )\n      equal = mid;\n      less = equal - 1;\n      more = equal + 1;\n      return\n    elseif ( compare == -1 )\n      hi = mid;\n    elseif ( compare == +1 )\n      lo = mid;\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/r8r8vec_index_search.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.5521953687098895}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%\tSurfBox-MATLAB (c)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%\n%%\tYue M. Lu and Minh N. Do\n%%\n%%\tDepartment of Electrical and Computer Engineering\n%%\tCoordinated Science Laboratory\n%%\tUniversity of Illinois at Urbana-Champaign\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%\n%%\tsurf_vec2coeff.m\n%%\t\n%%\tFirst created: 04-06-07\n%%\tLast modified: 04-06-07\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Y = surf_coeff2vec(c, size_info)\n\n%% Convert the surfacelet coefficient stored in a linear vector to a nested\n%% cell array.\n%%\n%% Input:\n%%\n%% c: a linear vector storing all the coefficients.\n%%\n%% size_info: a book keeping cell array storing the dimension information\n%% of Y. This is useful when we want to convert c back to Y. See \n%% surf_vec2coeff.m for details.\n%%\n%% Output:\n%%\n%% Y: an L+1 by 1 cell array containing the surfacelet coefficients. See\n%% Surfdec.m for details\n%%\n\n\n%% we can inherit the nested structure\nY = size_info;\n\n%% number of multiscale levels\nL = length(Y) - 1;\n\nNcoeff = 1;\n\nfor n = 1 : L\n    for m = 1 : length(Y{n})\n        for k = 1 : length(Y{n}{m})\n            sz = size_info{n}{m}{k};\n            d = prod(sz);\n            Y{n}{m}{k} = reshape(c(Ncoeff : Ncoeff + d - 1), sz);\n            Ncoeff = Ncoeff + d;\n        end\n    end\nend\n\n%% the lowpass subband\nsz = size_info{end};\nY{end} = reshape(c(Ncoeff : end), sz);\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_TRAFO/Surfacelet/surf_vec2coeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5521953668529314}}
{"text": "function plotProjectedAmps(view, scanList,projectionPhase)\n%\n% plotProjectedAmplitudes(view, [scanList])\n% \n% Bar plot of the amplitudes for each scan, averaging across\n% all pixels (in all slices) in the current ROI.  The bar heights\n% and a coarse SEM can be obtained from get(gca,'UserData').\n% \n% gmb  5/25/98\n% bw   2/19/99  Added seY field to the UserData field.\n%\t    seY is an estimate of the variability in the\n%      amplitudes.  It is the SEM of the in the complex \n%      (amp*exp(-i*ph)) representation.  The values are\n%      computed in vectorMean.m\n% rfd  7/18/02 Added optional scanList.\n\nif(~exist('scanList','var'))\n    scanList = [1:numScans(view)];\nend\nif (~exist('projectionPhase','var'))\n    computeProjPhase=1;\nelse\n    computeProjPhase=0;\nend\n% Compute means across scans, for all pixels in the\n% currently selected ROI.  The seZ value is the mean\n% distance from the mean.\n[meanAmps,meanPhs,seZ] = vectorMeans(view);\n\n%Reference scan is the current scan\nrefScan = getCurScan(view);\n\n% Compute the amplitude projected onto the reference phase\nif (computeProjPhase)\n    projectionPhase=meanPhs(refScan);\nend\nmeanProjectedAmps = meanAmps.*cos(meanPhs-projectionPhase);\n\nselectGraphWin;\n\n% Header\nROIname = view.ROIs(view.selectedROI).name;\nheaderStr = ['Mean of projected amplitudes, ROI ',ROIname];\nset(gcf,'Name',headerStr);\n\n%plot the bar graph\nclf\nfontSize = 14;\nh = mybar(meanProjectedAmps(scanList), zeros(size(scanList)), num2str(scanList'));\nxlabel('Scan','FontSize',fontSize);\nylabel('Mean Projected Amplitude','FontSize',fontSize);\nylim =get(gca,'YLim');\nset(gca,'YLim',ylim*1.1);\nset(gca,'FontSize',fontSize);\n\nfoo = cell2struct(h,'bar');\nhbar = foo(find(scanList==refScan)).bar;\nset(hbar,'FaceColor','r')\n\n%Save the data in gca('UserData')\ndata.y = meanProjectedAmps;\ndata.refScan = refScan;\ndata.seY = seZ;\nset(gca,'UserData',data);\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/Plots/plotProjectedAmps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5521953612004812}}
{"text": "function [ r, s1, s2, s3 ] = r8_random ( s1, s2, s3 )\n\n%*****************************************************************************80\n%\n%% R8_RANDOM returns a pseudorandom number between 0 and 1.\n%\n%  Discussion:\n%\n%    This function returns a pseudo-random number rectangularly distributed\n%    between 0 and 1.   The cycle length is 6.95E+12.  (See page 123\n%    of Applied Statistics (1984) volume 33), not as claimed in the\n%    original article.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    08 July 2008\n%\n%  Author:\n%\n%    Original FORTRAN77 version by Brian Wichman, David Hill.\n%    MATLAB version by John Burkardt.\n%\n%  Reference:\n%\n%    Brian Wichman, David Hill,\n%    Algorithm AS 183: An Efficient and Portable Pseudo-Random\n%    Number Generator,\n%    Applied Statistics,\n%    Volume 31, Number 2, 1982, pages 188-190.\n%\n%  Parameters:\n%\n%    Input, integer S1, S2, S3, three values used as the\n%    seed for the sequence.  These values should be positive\n%    integers between 1 and 30,000.\n%\n%    Output, real R, the next value in the sequence.\n%\n%    Output, integer S1, S2, S3, updated seed values.\n%\n  s1 = mod ( 171 * s1, 30269 );\n  s2 = mod ( 172 * s2, 30307 );\n  s3 = mod ( 170 * s3, 30323 );\n\n  r = mod ( s1 / 30269.0 ...\n          + s2 / 30307.0 ...\n          + s3 / 30323.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/asa183/r8_random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5521953565172982}}
{"text": "function points = mergeClosePoints(points, varargin)\n%MERGECLOSEPOINTS Merge points that are closer than a given distance.\n%\n%   PTS2 = mergeClosePoints(PTS, DIST)\n%   Remove points in the array PTS such that no points closer than the\n%   distance DIST remain in the array.\n%\n%   PTS2 = mergeClosePoints(PTS)\n%   If the distance is not specified, the default value 1e-14 is used.\n%\n%\n%   Example\n%     pts = rand(200, 2);\n%     pts2 = mergeClosePoints(pts, .1);\n%     figure; drawPoint(pts, '.');\n%     hold on; drawPoint(pts2, 'mo');\n%\n%   See also \n%     points2d, removeMultipleVertices\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2013-10-04, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2013-2022 INRA - Cepia Software Platform\n\n% default values\nminDist = 1e-14;\nif ~isempty(varargin)\n    minDist = varargin{1};\nend\n\ni = 1;\nwhile i < size(points, 1)\n    dist = distancePoints(points(i,:), points);\n    inds = dist < minDist;\n    inds(i) = 0;\n    \n    points(inds, :) = [];\n    \n    % switch to next point\n    i = i + 1;\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom2d/mergeClosePoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5521953546603403}}
{"text": "function [V, S, varexp, w, Yhat] = plssquash(X, Y, varargin)\n% Decomposes data X into K components that are ordered in their \n% covariance with Y, designed to predict orthogonal parts of Y\n%\n% :Usage:\n% ::\n%\n%     [V, S, varexp, w, Yhat] = plssquash(X, Y, varargin)\n%\n% :Optional Inputs:\n%   - case {'noplot'}, turn off plotting\n%   - case 'ndims', save only first ndims (K) vectors\n%\n% :Outputs:\n%\n%   **V:**\n%        'eigenvetors', or weights, on data (columns)\n%\n%   **S:**\n%        score matrix, N x K\n%\n%   **varexp:**\n%        sqrt(r-square) with first k components predicting Y\n%\n%   **w:**\n%        V*b, integrated weights.  for predicting new data, pred = X*w\n%\n%   **Yhat:**\n%        X*V*b, or S*b\n%\n% ..\n%    Tor Wager, 9/12/09\n% ..\n\ndoplot = 1;\nndims = length(Y) - 1; \n\nfor i = 1:length(varargin)\n    if ischar(varargin{i})\n        switch varargin{i}\n            case {'noplot'}, doplot = 0;\n            case 'ndims', ndims = varargin{i + 1};\n                \n            otherwise, warning(['Unknown input string option:' varargin{i}]);\n        end\n    end\nend\n    \n% univariate covariance-based weights\n% imperfect prediction\nX = X - repmat(mean(X), size(X, 1), 1); %scale(X);\nY = scale(Y);\n\n%\n% neither V nor S appears to have orthogonal columns, though many are\n% later columns, as df in Y is approached, appear to be highly colinear\n% this may be because all variance in Y is basically explained...\n\nclear V  % V is voxel weights for each component 1:K\nclear S\nrY = Y; % Y values to successively predict; intialize to Y\n\nfor i = 1:ndims  %ceil(length(Y)./2)\n\n    % V = voxel weights, based on univariate relationship with rY\n    V(:,i) = (X' * rY); %.^ .5;\n    V(:,i) = V(:,i) ./ norm(V(:,i));\n\n    % score matrix, N x K\n    % these will ultimately be predictors for Y\n    % chosen to maximize predictive power with few orthogonal components\n    S = X*V;\n\n    rY = Y - S * pinv(S) * Y;\n\n    b = pinv(S) * Y;\n    Yhat = S * b;\n\n    rsq(i) = 1 - var(rY) ./ var(Y);\n    \n    if doplot\n        create_figure('Fit'); plot(Yhat, Y, 'kx'); refline; \n\n        rsq_adj(i) = 1 - (1-rsq(i)) * ((size(Y,1)-1) ./ (size(Y,1)-i-1));\n\n        title(sprintf('cum. r-squared = %3.1f, adj = %3.1f', 100*rsq(i), 100*rsq_adj(i)));\n        drawnow; pause(.3)\n    end\n    \nend\n\nvarexp = sqrt(rsq);\n\nb = pinv(S) * Y;\nYhat = S * b;\nw = V * b;  % final weight vector\n\n%prediction = mean(training) + data*S*b\n%Yhat = X * V * b;\n%figure; plot(Yhat, Y, 'kx')\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/plssquash.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5520821736890256}}
{"text": "function [Pgood,Pbad] = NDS(Population,K)\n% Sort the population based on non-dominated sorting and crowding distance\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    FrontNo  = NDSort(Population.objs,inf);\n    CrowdDis = CrowdingDistance(Population.objs,FrontNo);\n    [~,rank] = sortrows([FrontNo;-CrowdDis]');\n    Pgood    = Population(rank(1:K));\n    Pbad     = Population(rank(end-K+1: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/CPS-MOEA/NDS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5520821728096926}}
{"text": "function [ t, rank ] = subset_colex_successor ( n, t, rank )\n\n%*****************************************************************************80\n%\n%% SUBSET_COLEX_SUCCESSOR computes the subset colexicographic successor.\n%\n%  Discussion:\n%\n%    In the original code, there is a last element with no successor.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    22 August 2011\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Donald Kreher, Douglas Simpson,\n%    Combinatorial Algorithms,\n%    CRC Press, 1998,\n%    ISBN: 0-8493-3988-X,\n%    LC: QA164.K73.\n%\n%  Parameters:\n%\n%    Input, integer N, the number of elements in the master set.\n%    N must be positive.\n%\n%    Input/output, integer T(N), describes a subset.  T(I) is 0 if\n%    the I-th element of the master set is not in the subset, and is\n%    1 if the I-th element is part of the subset.\n%    On input, T describes a subset.\n%    On output, T describes the next subset in the ordering.\n%    If the input T was the last in the ordering, then the output T\n%    will be the first.\n%\n%    Input/output, integer RANK, the rank.\n%    If RANK = -1 on input, then the routine understands that this is\n%    the first call, and that the user wishes the routine to supply\n%    the first element in the ordering, which has RANK = 0.\n%    In general, the input value of RANK is increased by 1 for output,\n%    unless the very last element of the ordering was input, in which\n%    case the output value of RANK is 0.\n%\n\n%\n%  Return the first element.\n%\n  if ( rank == -1 )\n    t(1:n) = 0;\n    rank = 0;\n    return\n  end\n%\n%  Check.\n%\n  subset_check ( n, t );\n\n  for i = 1 : n\n\n    if ( t(i) == 0 )\n      t(i) = 1;\n      rank = rank + 1;\n      return\n    else\n      t(i) = 0;\n    end\n\n  end\n\n  rank = 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/combo/subset_colex_successor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.5520821706100697}}
{"text": "function c = tapas_hgf_ar1_binary_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the Hierarchical Gaussian Filter (HGF) for AR(1) processes\n% for binary inputs in the absence of perceptual uncertainty.\n%\n% The HGF is the model introduced in \n%\n% Mathys C, Daunizeau J, Friston, KJ, and Stephan KE. (2011). A Bayesian foundation\n% for individual learning under uncertainty. Frontiers in Human Neuroscience, 5:39.\n%\n% The binary HGF model has since been augmented with a positive factor kappa1 which\n% scales the second level with respect to the first, i.e., the relation between the\n% first and second level is\n%\n% p(x1=1|x2) = s(kappa1*x2), where s(.) is the logistic sigmoid.\n%\n% By default, kappa1 is fixed to 1, leading (apart from the AR(1) process) to the\n% model introduced in Mathys et al. (2011).\n%\n% This file refers to BINARY inputs (Eqs 1-3 in Mathys et al., (2011));\n% for continuous inputs, refer to tapas_hgf_config.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% The HGF configuration consists of the priors of parameters and initial values. All priors are\n% Gaussian in the space where the quantity they refer to is estimated. They are specified by their\n% sufficient statistics: mean and variance (NOT standard deviation).\n% \n% Quantities are estimated in their native space if they are unbounded (e.g., the omegas). They are\n% estimated in log-space if they have a natural lower bound at zero (e.g., the sigmas).\n% \n% The phis are estimated in 'logit space' because they are confined to the interval from 0 to 1.\n% 'Logit-space' is a logistic sigmoid transformation of native space with a variable upper bound\n% a>0:\n% \n% tapas_logit(x) = ln(x/(a-x)); x = a/(1+exp(-tapas_logit(x)))\n%\n% Parameters can be fixed (i.e., set to a fixed value) by setting the variance of their prior to\n% zero. Aside from being useful for model comparison, the need for this arises whenever the scale\n% and origin at the j-th level are arbitrary. This is the case if the observation model does not\n% contain the representations mu_j and sigma_j. A choice of scale and origin is then implied by\n% fixing the initial value mu_j_0 of mu_j and either kappa_j-1 or omega_j-1.\n%\n% Fitted trajectories can be plotted by using the command\n%\n% >> tapas_hgf_binary_plotTraj(est)\n% \n% where est is the stucture returned by tapas_fitModel. This structure contains the estimated\n% perceptual parameters in est.p_prc and the estimated trajectories of the agent's\n% representations (cf. Mathys et al., 2011). Their meanings are:\n%              \n%         est.p_prc.mu_0       row vector of initial values of mu (in ascending order of levels)\n%         est.p_prc.sa_0       row vector of initial values of sigma (in ascending order of levels)\n%         est.p_prc.phi        row vector of phis (representing reversion slope to attractor; in ascending order of levels)\n%         est.p_prc.m        row vector of ms (representing attractors; in ascending order of levels)\n%         est.p_prc.ka         row vector of kappas (in ascending order of levels)\n%         est.p_prc.om         row vector of omegas (in ascending order of levels)\n%\n% Note that the first entry in all of the row vectors will be NaN because, at the first level,\n% these parameters are either determined by the second level (mu_0 and sa_0) or undefined (rho,\n% kappa, and omega).\n%\n%         est.traj.mu          mu (rows: trials, columns: levels)\n%         est.traj.sa          sigma (rows: trials, columns: levels)\n%         est.traj.muhat       prediction of mu (rows: trials, columns: levels)\n%         est.traj.sahat       precisions of predictions (rows: trials, columns: levels)\n%         est.traj.v           inferred variance of random walk (rows: trials, columns: levels)\n%         est.traj.w           weighting factors (rows: trials, columns: levels)\n%         est.traj.da          volatility prediction errors  (rows: trials, columns: levels)\n%         est.traj.ud          updates with respect to prediction  (rows: trials, columns: levels)\n%         est.traj.psi         precision weights on prediction errors  (rows: trials, columns: levels)\n%         est.traj.epsi        precision-weighted prediction errors  (rows: trials, columns: levels)\n%         est.traj.wt          full weights on prediction errors (at the first level,\n%                                  this is the learning rate) (rows: trials, columns: levels)\n%\n% Note that in the absence of sensory uncertainty (which is the assumption here), the first\n% column of mu, corresponding to the first level, will be equal to the inputs. Likewise, the\n% first column of sa will be 0 always.\n%\n% Tips:\n% - When analyzing a new dataset, take your inputs u and responses y and use\n%\n%   >> est = tapas_fitModel(y, u, 'tapas_hgf_binary_config', 'tapas_bayes_optimal_binary_config');\n%\n%   to determine the Bayes optimal perceptual parameters (given your current priors as defined in\n%   this file here, so choose them wide and loose to let the inputs influence the result). You can\n%   then use the optimal parameters as your new prior means for the perceptual parameters.\n%\n% - If you get an error saying that the prior means are in a region where model assumptions are\n%   violated, lower the prior means of the omegas, starting with the highest level and proceeding\n%   downwards.\n%\n% - Alternatives are lowering the prior means of the kappas, if they are not fixed, or adjusting\n%   the values of the kappas or omegas, if any of them are fixed.\n%\n% - If the log-model evidence cannot be calculated because the Hessian poses problems, look at\n%   est.optim.H and fix the parameters that lead to NaNs.\n%\n% - Your guide to all these adjustments is the log-model evidence (LME). Whenever the LME increases\n%   by at least 3 across datasets, the adjustment was a good idea and can be justified by just this:\n%   the LME increased, so you had a better model.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2017 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 <http://www.gnu.org/licenses/>.\n\n\n% Config structure\nc = struct;\n\n% Model name\nc.model = 'tapas_hgf_ar1_binary';\n\n% Number of levels (minimum: 3)\nc.n_levels = 3;\n\n% Input intervals\n% If input intervals are irregular, the last column of the input\n% matrix u has to contain the interval between inputs k-1 and k\n% in the k-th row, and this flag has to be set to true\nc.irregular_intervals = false;\n\n% Sufficient statistics of Gaussian parameter priors\n\n% Initial mus and sigmas\n% Format: row vectors of length n_levels\n% For all but the first two levels, this is usually best\n% kept fixed to 1 (determines origin on x_i-scale). The \n% first level is NaN because it is determined by the second,\n% and the second implies neutrality between outcomes when it\n% is centered at 0.\nc.mu_0mu = [NaN, 0, 1];\nc.mu_0sa = [NaN, 0, 0];\n\nc.logsa_0mu = [NaN, log(0.006), log(4)];\nc.logsa_0sa = [NaN,          0,      0];\n\n% Phis\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\n% Fix this to zero (-Inf in logit space) to set to zero.\nc.logitphimu = [NaN, -Inf, tapas_logit(0.1,1)];\nc.logitphisa = [NaN,    0,                  2];\n\n% ms\n% Format: row vector of length n_levels.\n% This should be fixed for all levels where the omega of\n% the next lowest level is not fixed because that offers\n% an alternative parametrization of the same model.\nc.mmu = [NaN, c.mu_0mu(2), c.mu_0mu(3)];\nc.msa = [NaN,           0,           1];\n\n% Kappas\n% Format: row vector of length n_levels-1.\n% Fixing log(kappa1) to log(1) leads to the original HGF model.\n% Higher log(kappas) should be fixed (preferably to log(1)) if the\n% observation model does not use mu_i+1 (kappa then determines the\n% scaling of x_i+1).\nc.logkamu = [log(1), log(1)];\nc.logkasa = [     0,      0];\n\n% Omegas\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\nc.ommu = [NaN,  -2,  -6];\nc.omsa = [NaN, 4^2, 4^2];\n\n% Gather prior settings in vectors\nc.priormus = [\n    c.mu_0mu,...\n    c.logsa_0mu,...\n    c.logitphimu,...\n    c.mmu,...\n    c.logkamu,...\n    c.ommu,...\n         ];\n\nc.priorsas = [\n    c.mu_0sa,...\n    c.logsa_0sa,...\n    c.logitphisa,...\n    c.msa,...\n    c.logkasa,...\n    c.omsa,...\n         ];\n\n% Check whether we have the right number of priors\nexpectedLength = 5*c.n_levels+(c.n_levels-1);\nif length([c.priormus, c.priorsas]) ~= 2*expectedLength;\n    error('tapas:hgf:PriorDefNotMatchingLevels', 'Prior definition does not match number of levels.')\nend\n\n% Model function handle\nc.prc_fun = @tapas_hgf_ar1_binary;\n\n% Handle to function that transforms perceptual parameters to their native space\n% from the space they are estimated in\nc.transp_prc_fun = @tapas_hgf_ar1_binary_transp;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_ar1_binary_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5520821697307369}}
{"text": "function [prob,sol,fmin] = nls_prob(varargin)\n%NLS_PROB  Return an OPTI NLS \n%\n%   prob = nls_prob(no) return a pre-built optiprob of a saved NLS.\n%\n%   [prob,sol,fmin] = NLS_prob(no) returns the optimum solution and function\n%   eval at the optimum\n%\n%   no = nls_prob() returns the number of problems available for testing.\n\n%   (C) 2012 Jonathan Currie (IPL)\n\n% Functions are taken from:\n% More, J. J., B. S. Garbow, and K. E. Hillstrom. \"Testing Unconstrained \n% Optimization Software.\" ACM Transactions on Mathematical Software 7, \n% no. 1 (1981): 17-41. \n\n%Check if just returning no problems\nif(nargin < 1)\n    prob = 20; sol = []; fmin = [];\n    return;\nelse\n    no = varargin{1};\nend          \n\n%Big switch yard\nswitch(no)\n    case 1 \n        fun = @(x) [10*(x(2)-x(1)^2); 1 - x(1)];\n        ydata = zeros(2,1);\n        x0 = [-1.2;1];\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [1,1];\n        fmin = 0;\n        \n    case 2 \n        fun = @(x) [-13 + x(1) + ((5 - x(2))*x(2) - 2)*x(2);\n                    -29 + x(1) + ((x(2) + 1)*x(2) - 14)*x(2)];\n        ydata = zeros(2,1);\n        x0 = [0.5;-2];\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [5,4];\n        fmin = 0;\n        \n    case 3 \n        fun = @(x) [1e4*x(1)*x(2) - 1;\n                    exp(-x(1)) + exp(-x(2)) - 1.0001];\n        ydata = zeros(2,1);\n        x0 = [0;1];\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [1.098e-5;9.106];\n        fmin = 0;\n        \n    case 4 \n        fun = @(x) [x(1) - 1e6; x(2) - 2e-6; x(1)*x(2) - 2];\n        ydata = zeros(3,1);\n        x0 = [1;1];\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [1e6,2e-6];\n        fmin = 0;\n        \n    case 5 \n        fun = @(x) [1.5 - x(1)*(1 - x(2)); 2.25 - x(1)*(1 - x(2)^2); 2.625 - x(1)*(1 - x(2)^3) ];\n        ydata = zeros(3,1);\n        x0 = [1;1];\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [3;0.5];\n        fmin = 0;\n        \n    case 6 \n        i = (1:10)';\n        fun = @(x) 2 + 2*i - (exp(x(1)*i) + exp(x(2)*i));\n        ydata = zeros(10,1);\n        x0 = [0.3;0.4];\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [0.2578;0.2578];\n        fmin = 124.36226865;\n        \n    case 7 \n        fun = @more7;\n        ydata = zeros(3,1);\n        x0 = [-1;0;0];\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [1;0;0];\n        fmin = 0;\n        \n    case 8 \n        u = (1:15)';\n        v = 16 - u;\n        w = zeros(15,1);\n        for i = 1:15\n            w(i) = min(u(i),v(i));\n        end\n        y = [0.14;0.18;0.22;0.25;0.29;0.32;0.35;0.39;0.37;0.58;0.73;0.96;1.34;2.10;4.39];        \n        fun = @(x) (x(1) + u ./ (v*x(2) + w*x(3)));\n        x0 = [1;1;1];\n        prob = optiprob('fun',fun,'ydata',y,'x0',x0);            \n        sol = [];\n        fmin = 8.21487e-3;\n        \n    case 9 \n        i = (1:15)';\n        y = [0.0009;0.0044;0.0175;0.0540;0.1295;0.2420;0.3521;0.3989;0.3521;0.2420;0.1295;0.0540;0.0175;0.0044;0.0009];\n        t = (8 - i)./2;\n        fun = @(x) x(1)*exp((-x(2)*(t - x(3)).^2)./2);\n        x0 = [0.4;1;0];\n        prob = optiprob('fun',fun,'ydata',y,'x0',x0);            \n        sol = [];\n        fmin = 1.12793e-8;\n        \n    case {10,11}\n        i = (1:16)';\n        y = [34780;28610;23650;19630;16370;13720;11540;9744;8261;7030;6005;5147;4427;3820;3307;2872];\n        t = 45 + 5*i;\n        fun = @(x) x(1)*exp(x(2)./(t + x(3)));   \n        x0 = [0.02;4000;250];\n        prob = optiprob('fun',fun,'ydata',y,'x0',x0);            \n        sol = [];\n        fmin = 87.9458;      \n    \n%     case 11 %not working??\n%         m = 100;\n%         i = [1:m]';        \n%         t = i./100;\n%         y = 25 + (-50 * log(t)).^(2/3);\n%         fun = @(x) exp(-(abs(y*100.*i*x(2)).^x(3))./x(1)) - t; \n%         x0 = [5;2.5;0.15];\n%         ydata = zeros(m,1);\n%         prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n%         sol = [50;25;1.5];\n%         fmin = 0; \n        \n    case 12\n        m = 3;\n        i = (1:m)';        \n        t = 0.1*i;\n        fun = @(x) exp(-t*x(1)) - exp(-t*x(2)) - x(3)*exp(-t) - exp(-10*t); \n        x0 = [0;10;20];\n        ydata = zeros(m,1);\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [1;10;1];\n        fmin = 0;\n        \n    case 13\n        fun = @(x) [x(1) + 10*x(2);\n                    sqrt(5)*(x(3) - x(4));\n                    (x(3) - 2*x(3))^2;\n                    sqrt(10)*(x(1)-x(4))^2]; \n        x0 = [3;-1;0;1];\n        ydata = zeros(4,1);\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [0;0;0;0];\n        fmin = 0;\n        \n    case 14\n        fun = @(x) [10*(x(2)-x(1)^2);\n                    1 - x(1);\n                    sqrt(90)*(x(4)-x(3)^2);\n                    1 - x(3);\n                    sqrt(10)*(x(2) + x(4) - 2);\n                    10^(-0.5)*(x(2)-x(4))]; \n        x0 = [3;-1;-3;-1];\n        ydata = zeros(6,1);\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [1;1;1;1];\n        fmin = 0;\n        \n    case 15\n        y = [0.1957;0.1947;0.1735;0.16;0.0844;0.0627;0.0456;0.0342;0.0323;0.0235;0.0246];\n        u = [4;2;1;0.5;0.25;0.167;0.125;0.1;0.0833;0.0714;0.0625];\n        fun = @(x) (x(1)*(u.^2 + u*x(2))) ./ (u.^2 + u*x(3) + x(4)); \n        x0 = [0.25;0.39;0.415;0.39];\n        prob = optiprob('fun',fun,'ydata',-y,'x0',x0);            \n        sol = [];\n        fmin = 3.07505e-4;\n        \n    case 16\n        m = 20;\n        i = (1:m)';\n        t = i/5;\n        fun = @(x) (x(1) + t*x(2) - exp(t)).^2 + (x(3) + x(4)*sin(t) - cos(t)).^2; \n        x0 = [25;5;-5;-1];\n        ydata = zeros(m,1);\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [];\n        fmin = 85822.2016;\n        \n    case 17\n        m = 33;\n        i = (1:m)';\n        t = 10*(i - 1);\n        y = [0.844;0.908;0.932;0.936;0.925;0.908;0.881;0.850;0.818;0.784;0.751;0.718;0.685;0.658;0.628;0.603;...\n             0.58;0.558;0.538;0.522;0.506;0.490;0.478;0.467;0.457;0.448;0.438;0.431;0.424;0.42;0.414;0.411;0.406];\n        fun = @(x) (x(1) + x(2)*exp(-t*x(4)) + x(3)*exp(-t*x(5))); \n        x0 = [0.5;1.5;-1;0.01;0.02];\n        prob = optiprob('fun',fun,'ydata',-y,'x0',x0);            \n        sol = [];\n        fmin = 5.46489e-5;\n        \n    case 18\n        m = 13;\n        i = (1:m)';\n        t = 0.1*i;\n        y = exp(-t) - 5*exp(-10*t) + 3*exp(-4*t);\n        fun = @(x) x(3)*exp(-t*x(1)) - x(4)*exp(-t*x(2)) + x(6)*exp(-t*x(5)); \n        x0 = [1;2;1;1;1;1];\n        prob = optiprob('fun',fun,'ydata',y,'x0',x0);            \n        sol = [];\n        fmin = 0; %5.65565e-3; seems wrong?\n        \n    case 19\n        m = 65;\n        i = (1:m)';\n        t = (i-1)/10;\n        y = [1.366;1.191;1.112;1.013;0.991;0.885;0.831;0.847;0.786;0.725;0.746;0.679;0.608;0.655;0.616;0.606;0.602;0.626;0.651;0.724;0.649;0.649;...\n            0.694;0.644;0.624;0.661;0.612;0.558;0.533;0.495;0.5;0.423;0.395;0.375;0.372;0.391;0.396;0.405;0.428;0.429;0.523;0.562;0.607;0.653;...\n            0.672;0.708;0.633;0.668;0.645;0.632;0.591;0.559;0.597;0.625;0.739;0.710;0.729;0.720;0.636;0.581;0.428;0.292;0.162;0.098;0.054];\n        fun = @(x) (x(1)*exp(-t*x(5)) + x(2)*exp(-(t-x(9)).^2*x(6)) + x(3)*exp(-(t-x(10)).^2*x(7)) + x(4)*exp(-(t-x(11)).^2*x(8))); \n        x0 = [1.3;0.65;0.65;0.7;0.6;3;5;7;2;4.5;5.5];\n        prob = optiprob('fun',fun,'ydata',y,'x0',x0);            \n        sol = [];\n        fmin = 4.01377e-2;\n        \n    case 20\n        m = 31; n = 12;\n        fun = @more20; \n        x0 = zeros(n,1);\n        ydata = zeros(m,1);\n        prob = optiprob('fun',fun,'ydata',ydata,'x0',x0);            \n        sol = [];\n        fmin = 4.72238e-10;\n        \n    otherwise\n        error('Problem not available or not implemented yet');\nend\n\n\nfunction j = more7(x)\n\nif(x(1) > 0)\n    theta = 1/(2*pi)*atan(x(2)/x(1));\nelse\n    theta = 1/(2*pi)*atan(x(2)/x(1)) + 0.5;\nend\n\nj(1,1) = 10*(x(3) - 10*theta);\nj(2,1) = 10*(x(1)^2 + x(2)^2)^0.5 - 1;\nj(3,1) = x(3);\n\n\nfunction f = more20(x)\nn = length(x);\nj = (2:n)';\nj2 = (1:n)';\nt = 0.1*(1:29)';\nf = zeros(31,1);\nfor k = 1:29\n    f(k) = sum( (j-1).*x(2:end).*t(k).^(j-2) ) - sum( x.*t(k).^(j2-1) ) - 1;\nend\nf(30) = x(1);\nf(31) = x(2) - x(1)^2 - 1;\n\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/math/opti/Test Problems/nls_prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5520821684104465}}
{"text": "function [blockVectorX,lambda,varargout] = ...\n    lobpcg(blockVectorX,operatorA,varargin)\n%LOBPCG solves Hermitian partial eigenproblems using preconditioning\n%\n% [blockVectorX,lambda]=lobpcg(blockVectorX,operatorA)\n%\n% outputs the array of algebraic smallest eigenvalues lambda and\n% corresponding matrix of orthonormalized eigenvectors blockVectorX of the\n% Hermitian (full or sparse) operator operatorA using input matrix\n% blockVectorX as an initial guess, without preconditioning, somewhat\n% similar to\n%\n% opts.issym=1;opts.isreal=1;K=size(blockVectorX,2);\n% [blockVectorX,lambda]=eigs(operatorA,K,'SR',opts);\n%\n% for real symmetric operator operatorA, or\n%\n% K=size(blockVectorX,2);[blockVectorX,lambda]=eigs(operatorA,K,'SR');\n% for Hermitian operator operatorA.\n%\n% [blockVectorX,lambda,failureFlag]=lobpcg(blockVectorX,operatorA)\n% also returns a convergence flag.\n% If failureFlag is 0 then all the eigenvalues converged; otherwise not all\n% converged.\n%\n% [blockVectorX,lambda,failureFlag,lambdaHistory,residualNormsHistory]=...\n% lobpcg(blockVectorX,'operatorA','operatorB','operatorT',blockVectorY,...\n% residualTolerance,maxIterations,verbosityLevel);\n%\n% computes smallest eigenvalues lambda and corresponding eigenvectors\n% blockVectorX of the generalized eigenproblem Ax=lambda Bx, where\n% Hermitian operators operatorA and operatorB are given as functions, as\n% well as a preconditioner, operatorT. The operators operatorB and\n% operatorT must be in addition POSITIVE DEFINITE. To compute the largest\n% eigenpairs of operatorA, simply apply the code to operatorA multiplied by\n% -1. The code does not involve ANY matrix factorizations of operratorA and\n% operatorB, thus, e.g., it preserves the sparsity and the structure of\n% operatorA and operatorB.\n%\n% residualTolerance and maxIterations control tolerance and max number of\n% steps, and verbosityLevel = 0, 1, or 2 controls the amount of printed\n% info. lambdaHistory is a matrix with all iterative lambdas, and\n% residualNormsHistory are matrices of the history of 2-norms of residuals\n%\n% Required input:\n%  * blockVectorX (class numeric) - initial approximation to eigenvectors,\n%    full or sparse matrix n-by-blockSize. blockVectorX must be full rank.\n%  * operatorA (class numeric, char, or function_handle) - the main operator\n%    of the eigenproblem, can be a matrix, a function name, or handle\n%\n% Optional function input:\n%   * operatorB (class numeric, char, or function_handle) - the second\n%     operator, if solving a generalized eigenproblem, can be a matrix,\n%      a function name, or handle; by default if empty, operatorB=I.\n%   * operatorT  (class char or function_handle) - the preconditioner,\n%     by default operatorT(blockVectorX)=blockVectorX.\n%\n% Optional constraints input:\n%   blockVectorY (class numeric) - a full or sparse n-by-sizeY matrix of\n%   constraints, where sizeY < n. blockVectorY must be full rank.\n%   The iterations will be performed in the (operatorB-)\n%   orthogonal complement of the column-space of blockVectorY.\n%\n% Optional scalar input parameters:\n%   residualTolerance (class numeric) - tolerance, by default,\n%   residualTolerance=n*sqrt(eps) maxIterations - max number of iterations,\n%   by default, maxIterations = min(n,20) verbosityLevel - either 0 (no\n%   info), 1, or 2 (with pictures); by default, verbosityLevel = 0.\n%\n% Required output: blockVectorX and lambda (both class numeric) are\n% computed blockSize eigenpairs, where blockSize=size(blockVectorX,2)\n% for the initial guess blockVectorX if it is full rank.\n%\n% Optional output: failureFlag (class integer), lambdaHistory (class numeric)\n% and residualNormsHistory (class numeric) are described above.\n%\n% Functions operatorA(blockVectorX), operatorB(blockVectorX) and\n% operatorT(blockVectorX) must support blockVectorX being a matrix, not\n% just a column vector.\n%\n% Every iteration involves one application of operatorA and operatorB, and\n% one of operatorT.\n%\n% Main memory requirements: 6 (9 if isempty(operatorB)=0) matrices of the\n% same size as blockVectorX, 2 matrices of the same size as blockVectorY\n% (if present), and two square matrices of the size 3*blockSize.\n%\n% In all examples below, we use the Laplacian operator in a 20x20 square\n% with the mesh size 1 which can be generated in MATLAB by running\n% A = delsq(numgrid('S',21)); n=size(A,1);\n% or in MATLAB and Octave by\n% [~,~,A] = laplacian([19,19]); n=size(A,1);\n% see http://www.mathworks.com/matlabcentral/fileexchange/27279\n%\n% The following Example:\n%\n% [blockVectorX,lambda,failureFlag]=lobpcg(randn(n,8),A,1e-5,50,2);\n%\n% attempts to compute 8 first eigenpairs without preconditioning,\n% but not all eigenpairs converge after 50 steps, so failureFlag=1.\n%\n% The next Example:\n%\n% blockVectorY=[];lambda_all=[];\n% for j=1:4\n%   [blockVectorX,lambda]=...\n%                    lobpcg(randn(n,2),A,blockVectorY,1e-5,200,2);\n%   blockVectorY=[blockVectorY,blockVectorX];\n%   lambda_all=[lambda_all' lambda']'; pause;\n% end\n%\n% attemps to compute the same 8 eigenpairs by calling the code 4 times\n% with blockSize=2 using orthogonalization to the previously founded\n% eigenvectors.\n%\n% The following Example:\n%\n% R=ichol(A,struct('michol','on')); precfun = @(x)R\\(R'\\x);\n% [blockVectorX,lambda,failureFlag]=lobpcg(randn(n,8),A,[],@(x)precfun(x),1e-5,60,2);\n%\n% computes the same eigenpairs in less then 25 steps, so that failureFlag=0\n% using the preconditioner function \"precfun\", defined inline. If \"precfun\"\n% is defined as a MATLAB function in a file, the function handle\n% @(x)precfun(x) can be equivalently replaced by the function name 'precfun'\n% Running\n%\n% [blockVectorX,lambda,failureFlag]=...\n%          lobpcg(randn(n,8),A,speye(n),@(x)precfun(x),1e-5,50,2);\n%\n% produces similar answers, but is somewhat slower and needs more memory as\n% technically a generalized eigenproblem with B=I is solved here.\n%\n% The following Example for a mostly diagonally dominant sparse matrix A\n% demonstrates different types of preconditioning, compared to the standard\n% use of the main diagonal of A:\n%\n% clear all; close all;\n% n = 1000; M = spdiags([1:n]',0,n,n); precfun=@(x)M\\x;\n% A=M+sprandsym(n,.1); Xini=randn(n,5); maxiter=15; tol=1e-5;\n% [~,~,~,~,rnp]=lobpcg(Xini,A,tol,maxiter,1);\n% [~,~,~,~,r]=lobpcg(Xini,A,[],@(x)precfun(x),tol,maxiter,1);\n% subplot(2,2,1), semilogy(r'); hold on; semilogy(rnp',':>');\n% title('No preconditioning (top)'); axis tight;\n% M(1,2) = 2; precfun=@(x)M\\x; % M is no longer symmetric\n% [~,~,~,~,rns]=lobpcg(Xini,A,[],@(x)precfun(x),tol,maxiter,1);\n% subplot(2,2,2),  semilogy(r'); hold on; semilogy(rns','--s');\n% title('Nonsymmetric preconditioning (square)'); axis tight;\n% M(1,2) = 0; precfun=@(x)M\\(x+10*sin(x)); % nonlinear preconditioning\n% [~,~,~,~,rnl]=lobpcg(Xini,A,[],@(x)precfun(x),tol,maxiter,1);\n% subplot(2,2,3),  semilogy(r'); hold on; semilogy(rnl','-.*');\n% title('Nonlinear preconditioning (star)'); axis tight;\n% M=abs(M-3.5*speye(n,n)); precfun=@(x)M\\x;\n% [~,~,~,~,rs]=lobpcg(Xini,A,[],@(x)precfun(x),tol,maxiter,1);\n% subplot(2,2,4),  semilogy(r'); hold on; semilogy(rs','-d');\n% title('Selective preconditioning (diamond)'); axis tight;\n%\n% Revision 4.16 adds support for distributed or codistributed arrays\n% available in MATLAB BigData toolbox, e.g.,\n%\n% A = codistributed(diag(1:100)); B = codistributed(diag(101:200));\n% [blockVectorX,lambda]=lobpcg(randn(100,2),A,1e-5,5,2)\n%\n% Revision 4.17 adds support for single precision, e.g.,\n% A = diag(1:100); B = single(diag(101:200));\n% [blockVectorX,lambda]=lobpcg(randn(100,2),A,1e-5,15,2);\n% A = diag(1:100); B = diag(101:200);\n% [blockVectorX,lambda]=lobpcg(randn(100,2,'single'),A,1e-5,15,2);\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% This main function LOBPCG is a version of\n% the preconditioned conjugate gradient method (Algorithm 5.1) described in\n% A. V. Knyazev, Toward the Optimal Preconditioned Eigensolver:\n% Locally Optimal Block Preconditioned Conjugate Gradient Method,\n% SIAM Journal on Scientific Computing 23 (2001), no. 2, pp. 517-541.\n% http://dx.doi.org/10.1137/S1064827500366124\n%\n% Known bugs/features:\n%\n% - an excessively small requested tolerance may result in often restarts\n% and instability. The code is not written to produce an eps-level\n% accuracy! Use common sense.\n%\n% - the code may be very sensitive to the number of eigenpairs computed,\n% if there is a cluster of eigenvalues not completely included, cf.\n%\n% operatorA=diag([1 1.99 2:99]);\n% [blockVectorX,lambda]=lobpcg(randn(100,1),operatorA,1e-10,80,2);\n% [blockVectorX,lambda]=lobpcg(randn(100,2),operatorA,1e-10,80,2);\n% [blockVectorX,lambda]=lobpcg(randn(100,3),operatorA,1e-10,80,2);\n%\n% - using a nonsymmetric preconditioner is possible, but may be unstable\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The main distribution site:\n% https://github.com/lobpcg/blopex\n%\n% A C-version of this code is a part of the\n% https://github.com/lobpcg/blopex\n% package and is directly available, e.g., in SLEPc and HYPRE.\n%\n% A python version of this code is in\n% https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.lobpcg.html\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   License:  MIT / Apache-2.0\n%   Copyright (c) 2000-2019 A.V. Knyazev, Andrew.Knyazev@ucdenver.edu\n%   $Revision: 1.2 $  $Date: 13-June-2019\n%   This revision is tested in 9.6.0.1114505 (R2019a) Update 2, but is\n%   expected to work on any >R2007b MATLAB.\n%   Revision 4.13 tested in MATLAB 6.5-7.13.\n%   Revision 4.13 tested and available in Octave 3.2.3-3.4.2, see\n%   https://octave.sourceforge.io/linear-algebra/function/lobpcg.html\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Begin\n% Function gather defined to be identity if nonexistent, before 2016a\nif exist(\"gather\", \"file\") == 2\n    mygather=@(x)gather(x);\nelse\n    mygather=@(x)x;\nend\n% constants\nCONVENTIONAL_CONSTRAINTS = 1;\nSYMMETRIC_CONSTRAINTS = 2;\n%Initial settings\nfailureFlag = 1;\nif nargin < 2\n    error('BLOPEX:lobpcg:NotEnoughInputs',...\n        strcat('There must be at least 2 input agruments: ',...\n        'blockVectorX and operatorA'));\nend\nif nargin > 8\n    warning('BLOPEX:lobpcg:TooManyInputs',...\n        strcat('There must be at most 8 input agruments ',...\n        'unless arguments are passed to a function'));\nend\nif ~isnumeric(blockVectorX)\n    error('BLOPEX:lobpcg:FirstInputNotNumeric',...\n        'The first input argument blockVectorX must be numeric');\nend\n[n,blockSize]=size(blockVectorX);\nif blockSize > n\n    error('BLOPEX:lobpcg:FirstInputFat',...\n        'The first input argument blockVectorX must be tall, not fat');\nend\nif n < 6\n    error('BLOPEX:lobpcg:MatrixTooSmall',...\n        'The code does not work for matrices of small sizes');\nend\nif isa(operatorA,'numeric')\n    nA = size(operatorA,1);\n    if any(size(operatorA) ~= nA)\n        error('BLOPEX:lobpcg:MatrixNotSquare',...\n            'operatorA must be a square matrix or a string');\n    end\n    if size(operatorA) ~= n\n        error('BLOPEX:lobpcg:MatrixWrongSize',...\n            ['The size ' int2str(size(operatorA))...\n            ' of operatorA is not the same as ' int2str(n)...\n            ' - the number of rows of blockVectorX']);\n    end\nend\ncount_string = 0;\noperatorT = [];\noperatorB = [];\nresidualTolerance = [];\nmaxIterations = [];\nverbosityLevel = [];\nblockVectorY = []; sizeY = 0;\nfor j = 1:nargin-2\n    if isequal(size(varargin{j}),[n,n])\n        if isempty(operatorB)\n            operatorB = varargin{j};\n        else\n            error('BLOPEX:lobpcg:TooManyMatrixInputs',...\n                strcat('Too many matrix input arguments. ',...\n                'Preconditioner operatorT must be an M-function'));\n        end\n    elseif isequal(size(varargin{j},1),n) && size(varargin{j},2) < n\n        if isempty(blockVectorY)\n            blockVectorY = varargin{j};\n            sizeY=size(blockVectorY,2);\n        else\n            error('BLOPEX:lobpcg:WrongConstraintsFormat',...\n                'Something wrong with blockVectorY input argument');\n        end\n    elseif ischar(varargin{j}) || isa(varargin{j},'function_handle')\n        if count_string == 0\n            if isempty(operatorB)\n                operatorB = varargin{j};\n                count_string = count_string + 1;\n            else\n                operatorT = varargin{j};\n            end\n        elseif count_string == 1\n            operatorT = varargin{j};\n        else\n            warning('BLOPEX:lobpcg:TooManyStringFunctionHandleInputs',...\n                'Too many string or FunctionHandle input arguments');\n        end\n    elseif isequal(size(varargin{j}),[n,n])\n        error('BLOPEX:lobpcg:WrongPreconditionerFormat',...\n            'Preconditioner operatorT must be an M-function');\n    elseif max(size(varargin{j})) == 1\n        if isempty(residualTolerance)\n            residualTolerance = varargin{j};\n        elseif isempty(maxIterations)\n            maxIterations = varargin{j};\n        elseif isempty(verbosityLevel)\n            verbosityLevel = varargin{j};\n        else\n            warning('BLOPEX:lobpcg:TooManyScalarInputs',...\n                'Too many scalar parameters, need only three');\n        end\n    elseif isempty(varargin{j})\n        if isempty(operatorB)\n            count_string = count_string + 1;\n        elseif ~isempty(operatorT)\n            count_string = count_string + 1;\n        elseif ~isempty(blockVectorY)\n            error('BLOPEX:lobpcg:UnrecognizedEmptyInput',...\n                ['Unrecognized empty input argument number ' int2str(j+2)]);\n        end\n    else\n        error('BLOPEX:lobpcg:UnrecognizedInput',...\n            ['Input argument number ' int2str(j+2) ' not recognized.']);\n    end\nend\nif verbosityLevel\n    if issparse(blockVectorX)\n        fprintf(['The sparse initial guess with %i colunms '...\n            'and %i raws is detected  \\n'],n,blockSize);\n    else\n        fprintf(['The full initial guess with %i colunms '...\n            'and %i raws is detected  \\n'],n,blockSize);\n    end\n    if ischar(operatorA)\n        fprintf('The main operator is detected as an M-function %s \\n',...\n            operatorA);\n    elseif isa(operatorA,'function_handle')\n        fprintf('The main operator is detected as an M-function %s \\n',...\n            func2str(operatorA));\n    elseif issparse(operatorA)\n        fprintf('The main operator is detected as a sparse matrix \\n');\n    else\n        fprintf('The main operator is detected as a full matrix \\n');\n    end\n    if isempty(operatorB)\n        fprintf('Solving standard eigenvalue problem, not generalized \\n');\n    elseif ischar(operatorB)\n        fprintf(['The second operator of the generalized eigenproblem \\n'...\n            'is detected as an M-function %s \\n'],operatorB);\n    elseif isa(operatorB,'function_handle')\n        fprintf(['The second operator of the generalized eigenproblem \\n'...\n            'is detected as an M-function %s \\n'],func2str(operatorB));\n    elseif issparse(operatorB)\n        fprintf(strcat('The second operator of the generalized',...\n            'eigenproblem \\n is detected as a sparse matrix \\n'));\n    else\n        fprintf(strcat('The second operator of the generalized',...\n            'eigenproblem \\n is detected as a full matrix \\n'));\n    end\n    if isempty(operatorT)\n        fprintf('No preconditioner is detected \\n');\n    elseif ischar(operatorT)\n        fprintf('The preconditioner is detected as an M-function %s \\n',...\n            operatorT);\n    elseif isa(operatorT,'function_handle')\n        fprintf('The preconditioner is detected as an M-function %s \\n',...\n            func2str(operatorT));\n    end\n    if isempty(blockVectorY)\n        fprintf('No matrix of constraints is detected \\n')\n    elseif issparse(blockVectorY)\n        fprintf('The sparse matrix of %i constraints is detected \\n',sizeY);\n    else\n        fprintf('The full matrix of %i constraints is detected \\n',sizeY);\n    end\n    if issparse(blockVectorY) ~= issparse(blockVectorX)\n        warning('BLOPEX:lobpcg:SparsityInconsistent',...\n            strcat('The sparsity formats of the initial guess and ',...\n            'the constraints are inconsistent'));\n    end\nend\n% Set defaults\nif isempty(residualTolerance)\n    residualTolerance = sqrt(eps)*n;\nend\nif isempty(maxIterations)\n    maxIterations = min(n,20);\nend\nif isempty(verbosityLevel)\n    verbosityLevel = 0;\nend\nif verbosityLevel\n    fprintf('Tolerance %e and maximum number of iterations %i \\n',...\n        residualTolerance,maxIterations)\nend\n%constraints preprocessing\nif isempty(blockVectorY)\n    constraintStyle = 0;\nelse\n    %    constraintStyle = SYMMETRIC_CONSTRAINTS; % more accurate?\n    constraintStyle = CONVENTIONAL_CONSTRAINTS;\nend\nif constraintStyle == CONVENTIONAL_CONSTRAINTS\n    \n    if isempty(operatorB)\n        gramY = blockVectorY'*blockVectorY;\n    else\n        if isnumeric(operatorB)\n            blockVectorBY = operatorB*blockVectorY;\n        else\n            blockVectorBY = feval(operatorB,blockVectorY);\n        end\n        gramY=blockVectorY'*blockVectorBY;\n    end\n    gramY=(gramY'+gramY)*0.5;\n    if isempty(operatorB)\n        blockVectorX = blockVectorX - ...\n            blockVectorY*(gramY\\(blockVectorY'*blockVectorX));\n    else\n        blockVectorX =blockVectorX - ...\n            blockVectorY*(gramY\\(blockVectorBY'*blockVectorX));\n    end\n    \nelseif constraintStyle == SYMMETRIC_CONSTRAINTS\n    \n    if ~isempty(operatorB)\n        if isnumeric(operatorB)\n            blockVectorY = operatorB*blockVectorY;\n        else\n            blockVectorY = feval(operatorB,blockVectorY);\n        end\n    end\n    if isempty(operatorT)\n        gramY = blockVectorY'*blockVectorY;\n    else\n        blockVectorTY = feval(operatorT,blockVectorY);\n        gramY = blockVectorY'*blockVectorTY;\n    end\n    gramY=(gramY'+gramY)*0.5;\n    if isempty(operatorT)\n        blockVectorX = blockVectorX - ...\n            blockVectorY*(gramY\\(blockVectorY'*blockVectorX));\n    else\n        blockVectorX = blockVectorX - ...\n            blockVectorTY*(gramY\\(blockVectorY'*blockVectorX));\n    end\n    \nend\n%Making the initial vectors (operatorB-) orthonormal\nif isempty(operatorB)\n    %[blockVectorX,gramXBX] = qr(blockVectorX,0);\n    gramXBX=mygather(blockVectorX'*blockVectorX);\n    if ~isreal(gramXBX)\n        gramXBX=(gramXBX+gramXBX')*0.5;\n    end\n    [gramXBX,cholFlag]=chol(gramXBX);\n    if  cholFlag ~= 0\n        error('BLOPEX:lobpcg:ConstraintsTooTight',...\n            'The initial approximation after constraints is not full rank');\n    end\n    blockVectorX = blockVectorX/gramXBX;\nelse\n    %[blockVectorX,blockVectorBX] = orth(operatorB,blockVectorX);\n    if isnumeric(operatorB)\n        blockVectorBX = operatorB*blockVectorX;\n    else\n        blockVectorBX = feval(operatorB,blockVectorX);\n    end\n    gramXBX=blockVectorX'*blockVectorBX;\n    if ~isreal(gramXBX)\n        gramXBX=(gramXBX+gramXBX')*0.5;\n    end\n    [gramXBX,cholFlag]=chol(gramXBX);\n    if  cholFlag ~= 0\n        error('BLOPEX:lobpcg:InitialNotFullRank',...\n            '%s\\n%s', ...\n            'The initial approximation after constraints is not ',...\n            'full rank or/and operatorB is not positive definite');\n    end\n    blockVectorX = blockVectorX/gramXBX;\n    blockVectorBX = blockVectorBX/gramXBX;\nend\n% Checking if the problem is big enough for the algorithm,\n% i.e. n-sizeY > 5*blockSize\n% Theoretically, the algorithm should be able to run if\n% n-sizeY > 3*blockSize,\n% but the extreme cases might be unstable, so we use 5 instead of 3 here.\nif n-sizeY < 5*blockSize\n    error('BLOPEX:lobpcg:MatrixTooSmall','%s\\n%s', ...\n        'The problem size is too small, relative to the block size.',...\n        'Try using eig() or eigs() instead.');\nend\n% Preallocation\nresidualNormsHistory=zeros(blockSize,maxIterations);\nlambdaHistory=zeros(blockSize,maxIterations+1);\ncondestGhistory=zeros(1,maxIterations+1);\nblockVectorAR=zeros(n,blockSize, 'like', blockVectorX);\nblockVectorP=zeros(n,blockSize, 'like', blockVectorX);\nblockVectorAP=zeros(n,blockSize, 'like', blockVectorX);\nif ~isempty(operatorB)\n    blockVectorBR=zeros(n,blockSize, 'like', blockVectorX);\n    blockVectorBP=zeros(n,blockSize, 'like', blockVectorX);\nend\n%Initial settings for the loop\nif isnumeric(operatorA)\n    blockVectorAX = operatorA*blockVectorX;\nelse\n    blockVectorAX = feval(operatorA,blockVectorX);\nend\ngramXAX = full(blockVectorX'*blockVectorAX);\ngramXAX = (gramXAX + gramXAX')*0.5;\n% eig(...,'chol') uses only the diagonal and upper triangle -\n% not true in MATLAB\n% Octave v3.2.3-4, eig() does not support inputting 'chol'\n[coordX,gramXAX]=eig(gramXAX,eye(blockSize));\nlambda=diag(gramXAX); %eig returns non-ordered eigenvalues on the diagonal\nif issparse(blockVectorX)\n    coordX=sparse(coordX);\nend\nblockVectorX  =  blockVectorX*coordX;\nblockVectorAX = blockVectorAX*coordX;\nif ~isempty(operatorB)\n    blockVectorBX = blockVectorBX*coordX;\nend\nclear coordX\ncondestGhistory(1)=-log10(eps)/2;  %if too small cause unnecessary restarts\nlambdaHistory(1:blockSize,1) = mygather(lambda);\nactiveMask = true(blockSize,1);\n% currentBlockSize = blockSize; %iterate all\n%\n% restart=1;%steepest descent\n%The main part of the method is the loop of the CG method: begin\nfor iterationNumber=1:maxIterations\n    \n    %     %Computing the active residuals\n    %     if isempty(operatorB)\n    %%         if currentBlockSize > 1\n    %%             blockVectorR(:,activeMask)=blockVectorAX(:,activeMask) - ...\n    %%                 blockVectorX(:,activeMask)*spdiags(lambda(activeMask),0,currentBlockSize,currentBlockSize);\n    %%         else\n    %%             blockVectorR(:,activeMask)=blockVectorAX(:,activeMask) - ...\n    %%                 blockVectorX(:,activeMask)*lambda(activeMask);\n    %%         end\n    %         blockVectorR(:,activeMask)=blockVectorAX(:,activeMask) - ...\n    %         bsxfun(@times,blockVectorX(:,activeMask),lambda(activeMask)');\n    %     else\n    %%         if currentBlockSize > 1\n    %%             blockVectorR(:,activeMask)=blockVectorAX(:,activeMask) - ...\n    %%                 blockVectorBX(:,activeMask)*spdiags(lambda(activeMask),0,currentBlockSize,currentBlockSize);\n    %%         else\n    %%             blockVectorR(:,activeMask)=blockVectorAX(:,activeMask) - ...\n    %%                 blockVectorBX(:,activeMask)*lambda(activeMask);\n    %%         end\n    %         blockVectorR(:,activeMask)=blockVectorAX(:,activeMask) - ...\n    %         bsxfun(@times,blockVectorBX(:,activeMask),lambda(activeMask)');\n    %     end\n    \n    %Computing all residuals\n    if isempty(operatorB)\n        %         if blockSize > 1\n        %             blockVectorR = blockVectorAX - ...\n        %                 blockVectorX*spdiags(lambda,0,blockSize,blockSize);\n        %         else\n        %             blockVectorR = blockVectorAX - blockVectorX*lambda;\n        %             %to make blockVectorR full when lambda is just a scalar\n        %         end\n        blockVectorR = blockVectorAX - ...\n            bsxfun(@times,blockVectorX,lambda');\n    else\n        %        if blockSize > 1\n        %             blockVectorR = blockVectorAX - ...\n        %                 blockVectorBX*spdiags(lambda,0,blockSize,blockSize);\n        %        else\n        %             blockVectorR = blockVectorAX - blockVectorBX*lambda;\n        %        end\n        blockVectorR = blockVectorAX - ...\n            bsxfun(@times,blockVectorBX,lambda');\n    end\n    \n    %Satisfying the constraints for the active residulas\n    if constraintStyle == SYMMETRIC_CONSTRAINTS\n        if isempty(operatorT)\n            blockVectorR(:,activeMask) = blockVectorR(:,activeMask) - ...\n                blockVectorY*(gramY\\(blockVectorY'*...\n                blockVectorR(:,activeMask)));\n        else\n            blockVectorR(:,activeMask) = blockVectorR(:,activeMask) - ...\n                blockVectorY*(gramY\\(blockVectorTY'*...\n                blockVectorR(:,activeMask)));\n        end\n    end\n    \n    residualNorms = full(sqrt(sum(conj(blockVectorR).*blockVectorR)'));\n    residualNormsHistory(1:blockSize,iterationNumber) = ...\n        mygather(residualNorms);\n    \n    %index antifreeze\n    activeMask = full(residualNorms > residualTolerance) & activeMask;\n    %activeMask = full(residualNorms > residualTolerance);\n    %above allows vectors back into active, which causes problems with frosen Ps\n    %activeMask = full(residualNorms > 0);      %iterate all, ignore freeze\n    \n    currentBlockSize = mygather(sum(activeMask));\n    if  currentBlockSize == 0\n        failureFlag=0; %all eigenpairs converged\n        break\n    end\n    \n    %Applying the preconditioner operatorT to the active residulas\n    if ~isempty(operatorT)\n        blockVectorR(:,activeMask) = ...\n            feval(operatorT,blockVectorR(:,activeMask));\n    end\n    \n    if constraintStyle == CONVENTIONAL_CONSTRAINTS\n        if isempty(operatorB)\n            blockVectorR(:,activeMask) = blockVectorR(:,activeMask) - ...\n                blockVectorY*(gramY\\(blockVectorY'*...\n                blockVectorR(:,activeMask)));\n        else\n            blockVectorR(:,activeMask) = blockVectorR(:,activeMask) - ...\n                blockVectorY*(gramY\\(blockVectorBY'*...\n                blockVectorR(:,activeMask)));\n        end\n    end\n    \n    %Making active (preconditioned) residuals orthogonal to blockVectorX\n    if isempty(operatorB)\n        blockVectorR(:,activeMask) = blockVectorR(:,activeMask) - ...\n            blockVectorX*(blockVectorX'*blockVectorR(:,activeMask));\n    else\n        blockVectorR(:,activeMask) = blockVectorR(:,activeMask) - ...\n            blockVectorX*(blockVectorBX'*blockVectorR(:,activeMask));\n    end\n    \n    %Making active residuals orthonormal\n    if isempty(operatorB)\n        %[blockVectorR(:,activeMask),gramRBR]=...\n        %qr(blockVectorR(:,activeMask),0); %to increase stability\n        gramRBR=blockVectorR(:,activeMask)'*blockVectorR(:,activeMask);\n        if ~isreal(gramRBR)\n            gramRBR=(gramRBR+gramRBR')*0.5;\n        end\n        [gramRBR,cholFlag]=chol(gramRBR);\n        if  cholFlag == 0\n            blockVectorR(:,activeMask) = blockVectorR(:,activeMask)/gramRBR;\n        else\n            warning('BLOPEX:lobpcg:ResidualNotFullRank',...\n                'The residual is not full rank.');\n            break\n        end\n    else\n        if isnumeric(operatorB)\n            blockVectorBR(:,activeMask) = ...\n                operatorB*blockVectorR(:,activeMask);\n        else\n            blockVectorBR(:,activeMask) = ...\n                feval(operatorB,blockVectorR(:,activeMask));\n        end\n        gramRBR=blockVectorR(:,activeMask)'*blockVectorBR(:,activeMask);\n        if ~isreal(gramRBR)\n            gramRBR=(gramRBR+gramRBR')*0.5;\n        end\n        [gramRBR,cholFlag]=chol(gramRBR);\n        if  cholFlag == 0\n            blockVectorR(:,activeMask) = ...\n                blockVectorR(:,activeMask)/gramRBR;\n            blockVectorBR(:,activeMask) = ...\n                blockVectorBR(:,activeMask)/gramRBR;\n        else\n            warning('BLOPEX:lobpcg:ResidualNotFullRankOrElse',...\n                strcat('The residual is not full rank or/and operatorB ',...\n                'is not positive definite.'));\n            break\n        end\n    end\n    clear gramRBR;\n    \n    if isnumeric(operatorA)\n        blockVectorAR(:,activeMask) = ...\n            mygather(operatorA*blockVectorR(:,activeMask));\n    else\n        blockVectorAR(:,activeMask) = ...\n            feval(operatorA,blockVectorR(:,activeMask));\n    end\n    \n    condestGmean = mean(condestGhistory(max(1,iterationNumber-10-...\n        round(log(currentBlockSize))):iterationNumber));\n    \n    %  restart=1;\n    \n    % The Raileight-Ritz method for [blockVectorX blockVectorR blockVectorP]\n    if isa(blockVectorAR, 'single')    % single initial\n        myeps = 1; % play safe\n    elseif isa(blockVectorR, 'single') %single somethings else\n        myeps = eps(single(1));\n    else                               % double everything\n        myeps = eps;\n    end\n    if  mygather(residualNorms) > myeps^0.6\n        explicitGramFlag = 0;\n    else\n        explicitGramFlag = 1;  %suggested by Garrett Moran, private\n    end\n    \n    activeRSize=size(blockVectorR(:,activeMask),2);\n    if iterationNumber == 1\n        activePSize=0;\n        restart=1;\n    else\n        activePSize=size(blockVectorP(:,activeMask),2);\n        restart=0;\n    end\n    \n    gramXAR=full(blockVectorAX'*blockVectorR(:,activeMask));\n    gramRAR=full(blockVectorAR(:,activeMask)'*blockVectorR(:,activeMask));\n    gramRAR=(gramRAR'+gramRAR)*0.5;\n    \n    if explicitGramFlag\n        gramXAX=full(blockVectorAX'*blockVectorX);\n        gramXAX=(gramXAX'+gramXAX)*0.5;\n        if isempty(operatorB)\n            gramXBX=full(blockVectorX'*blockVectorX);\n            gramRBR=full(blockVectorR(:,activeMask)'*...\n                blockVectorR(:,activeMask));\n            gramXBR=full(blockVectorX'*blockVectorR(:,activeMask));\n        else\n            gramXBX=full(blockVectorBX'*blockVectorX);\n            gramRBR=full(blockVectorBR(:,activeMask)'*...\n                blockVectorR(:,activeMask));\n            gramXBR=full(blockVectorBX'*blockVectorR(:,activeMask));\n        end\n        gramXBX=(gramXBX'+gramXBX)*0.5;\n        gramRBR=(gramRBR'+gramRBR)*0.5;\n        \n    end\n    \n    if iterationNumber > 1\n        %Making active conjugate directions orthonormal\n        if isempty(operatorB)\n            %[blockVectorP(:,activeMask),gramPBP] = qr(blockVectorP(:,activeMask),0);\n            gramPBP=blockVectorP(:,activeMask)'*blockVectorP(:,activeMask);\n            if ~isreal(gramPBP)\n                gramPBP=(gramPBP+gramPBP')*0.5;\n            end\n            [gramPBP,cholFlag]=chol(gramPBP);\n            if  cholFlag == 0\n                blockVectorP(:,activeMask) = ...\n                    blockVectorP(:,activeMask)/gramPBP;\n                blockVectorAP(:,activeMask) = ...\n                    blockVectorAP(:,activeMask)/gramPBP;\n                restart = 0;\n            else\n                warning('BLOPEX:lobpcg:DirectionNotFullRank',...\n                    'The direction matrix is not full rank.');\n                restart = 1;\n            end\n        else\n            gramPBP=blockVectorP(:,activeMask)'*blockVectorBP(:,activeMask);\n            if ~isreal(gramPBP)\n                gramPBP=(gramPBP+gramPBP')*0.5;\n            end\n            [gramPBP,cholFlag]=chol(gramPBP);\n            if  cholFlag == 0\n                blockVectorP(:,activeMask) = ...\n                    blockVectorP(:,activeMask)/gramPBP;\n                blockVectorAP(:,activeMask) = ...\n                    blockVectorAP(:,activeMask)/gramPBP;\n                blockVectorBP(:,activeMask) = ...\n                    blockVectorBP(:,activeMask)/gramPBP;\n                restart = 0;\n            else\n                warning('BLOPEX:lobpcg:DirectionNotFullRank',...\n                    strcat('The direction matrix is not full rank ',...\n                    'or/and operatorB is not positive definite.'));\n                restart = 1;\n            end\n        end\n        clear gramPBP\n    end\n    \n    for cond_try=1:2           %cond_try == 2 when restart\n        \n        if ~restart\n            gramXAP=full(blockVectorAX'*blockVectorP(:,activeMask));\n            gramRAP=full(blockVectorAR(:,activeMask)'*...\n                blockVectorP(:,activeMask));\n            gramPAP=full(blockVectorAP(:,activeMask)'*...\n                blockVectorP(:,activeMask));\n            gramPAP=(gramPAP'+gramPAP)*0.5;\n            \n            if explicitGramFlag\n                gramA = [ gramXAX     gramXAR     gramXAP\n                    gramXAR'    gramRAR     gramRAP\n                    gramXAP'     gramRAP'    gramPAP ];\n            else\n                gramA = [ diag(lambda)  gramXAR  gramXAP\n                    gramXAR'      gramRAR  gramRAP\n                    gramXAP'      gramRAP'  gramPAP ];\n            end\n            \n            clear gramXAP  gramRAP gramPAP\n            \n            if isempty(operatorB)\n                gramXBP=full(blockVectorX'*blockVectorP(:,activeMask));\n                gramRBP=full(blockVectorR(:,activeMask)'*...\n                    blockVectorP(:,activeMask));\n            else\n                gramXBP=full(blockVectorBX'*blockVectorP(:,activeMask));\n                gramRBP=full(blockVectorBR(:,activeMask)'*...\n                    blockVectorP(:,activeMask));\n                %or blockVectorR(:,activeMask)'*blockVectorBP(:,activeMask);\n            end\n            \n            if explicitGramFlag\n                if isempty(operatorB)\n                    gramPBP=full(blockVectorP(:,activeMask)'*...\n                        blockVectorP(:,activeMask));\n                else\n                    gramPBP=full(blockVectorBP(:,activeMask)'*...\n                        blockVectorP(:,activeMask));\n                end\n                gramPBP=(gramPBP'+gramPBP)*0.5;\n                gramB = [ gramXBX  gramXBR  gramXBP\n                    gramXBR' gramRBR  gramRBP\n                    gramXBP' gramRBP' gramPBP ];\n                clear   gramPBP\n            else\n                gramB=[eye(blockSize) zeros(blockSize,activeRSize) gramXBP\n                    zeros(blockSize,activeRSize)' eye(activeRSize) gramRBP\n                    gramXBP' gramRBP' eye(activePSize) ];\n            end\n            \n            clear gramXBP  gramRBP;\n            \n        else\n            \n            if explicitGramFlag\n                gramA = [ gramXAX   gramXAR\n                    gramXAR'    gramRAR  ];\n                gramB = [ gramXBX  gramXBR\n                    gramXBR' eye(activeRSize)  ];\n                clear gramXAX gramXBX gramXBR\n            else\n                gramA = [ diag(lambda)  gramXAR\n                    gramXAR'        gramRAR  ];\n                gramB = eye(blockSize+activeRSize);\n            end\n            \n            clear gramXAR gramRAR;\n            \n        end\n        \n        condestG = log10(cond(gramB))+1;\n        if (condestG/condestGmean > 2 && condestG > 2 )|| condestG > 8\n            %black magic - need to guess the restart\n            if verbosityLevel\n                fprintf('Restart on step %i as condestG %5.4e \\n',...\n                    iterationNumber,condestG);\n            end\n            if cond_try == 1 && ~restart\n                restart=1; %steepest descent restart for stability\n            else\n                warning('BLOPEX:lobpcg:IllConditioning',...\n                    'Gramm matrix ill-conditioned: results unpredictable');\n            end\n        else\n            break\n        end\n        \n    end\n    \n    [gramA,gramB]=eig(gramA,gramB);\n    lambda=diag(gramB(1:blockSize,1:blockSize));\n    coordX=gramA(:,1:blockSize);\n    \n    clear gramA gramB\n    \n    if issparse(blockVectorX)\n        coordX=sparse(coordX);\n    end\n    \n    if ~restart\n        blockVectorP =  blockVectorR(:,activeMask)*...\n            coordX(blockSize+1:blockSize+activeRSize,:) + ...\n            blockVectorP(:,activeMask)*...\n            coordX(blockSize+activeRSize+1:blockSize + ...\n            activeRSize+activePSize,:);\n        blockVectorAP = blockVectorAR(:,activeMask)*...\n            coordX(blockSize+1:blockSize+activeRSize,:) + ...\n            blockVectorAP(:,activeMask)*...\n            coordX(blockSize+activeRSize+1:blockSize + ...\n            activeRSize+activePSize,:);\n        if ~isempty(operatorB)\n            blockVectorBP = blockVectorBR(:,activeMask)*...\n                coordX(blockSize+1:blockSize+activeRSize,:) + ...\n                blockVectorBP(:,activeMask)*...\n                coordX(blockSize+activeRSize+1:blockSize+activeRSize+activePSize,:);\n        end\n    else %use block steepest descent\n        blockVectorP =   blockVectorR(:,activeMask)*...\n            coordX(blockSize+1:blockSize+activeRSize,:);\n        blockVectorAP = blockVectorAR(:,activeMask)*...\n            coordX(blockSize+1:blockSize+activeRSize,:);\n        if ~isempty(operatorB)\n            blockVectorBP = blockVectorBR(:,activeMask)*...\n                coordX(blockSize+1:blockSize+activeRSize,:);\n        end\n    end\n    \n    blockVectorX = blockVectorX*coordX(1:blockSize,:) + blockVectorP;\n    blockVectorAX = blockVectorAX*coordX(1:blockSize,:) + blockVectorAP;\n    if ~isempty(operatorB)\n        blockVectorBX = blockVectorBX*coordX(1:blockSize,:) + blockVectorBP;\n    end\n    clear coordX\n    %%end RR\n    \n    lambdaHistory(1:blockSize,iterationNumber+1) = mygather(lambda);\n    condestGhistory(iterationNumber+1) = mygather(condestG);\n    \n    if verbosityLevel\n        fprintf('Iteration %i current block size %i \\n',...\n            iterationNumber,currentBlockSize);\n        fprintf('Eigenvalues lambda %17.16e \\n',mygather(lambda));\n        fprintf('Residual Norms %e \\n',mygather(residualNorms'));\n    end\nend\n%The main step of the method was the CG cycle: end\n%Postprocessing\n%Making sure blockVectorX's \"exactly\" satisfy the blockVectorY constrains??\n%Making sure blockVectorX's are \"exactly\" othonormalized by final \"exact\" RR\nif isempty(operatorB)\n    gramXBX=full(blockVectorX'*blockVectorX);\nelse\n    if isnumeric(operatorB)\n        blockVectorBX = operatorB*blockVectorX;\n    else\n        blockVectorBX = feval(operatorB,blockVectorX);\n    end\n    gramXBX = full(blockVectorX'*blockVectorBX);\nend\ngramXBX=(gramXBX'+gramXBX)*0.5;\nif isnumeric(operatorA)\n    blockVectorAX = operatorA*blockVectorX;\nelse\n    blockVectorAX = feval(operatorA,blockVectorX);\nend\ngramXAX = full(blockVectorX'*blockVectorAX);\ngramXAX = (gramXAX + gramXAX')*0.5;\n%Raileigh-Ritz for blockVectorX, which is already operatorB-orthonormal\n[coordX,gramXBX] = eig(gramXAX,gramXBX);\nlambda=diag(gramXBX);\nif issparse(blockVectorX)\n    coordX=sparse(coordX);\nend\nblockVectorX  =   blockVectorX*coordX;\nblockVectorAX  =  blockVectorAX*coordX;\nif ~isempty(operatorB)\n    blockVectorBX  =  blockVectorBX*coordX;\nend\n%Computing all residuals\nif isempty(operatorB)\n    %     if blockSize > 1\n    %         blockVectorR = blockVectorAX - ...\n    %             blockVectorX*spdiags(lambda,0,blockSize,blockSize);\n    %     else\n    %         blockVectorR = blockVectorAX - blockVectorX*lambda;\n    %     end\n    blockVectorR = blockVectorAX - ...\n        bsxfun(@times,blockVectorX,lambda');\nelse\n    %     if blockSize > 1\n    %         blockVectorR=blockVectorAX - ...\n    %             blockVectorBX*spdiags(lambda,0,blockSize,blockSize);\n    %     else\n    %         blockVectorR = blockVectorAX - blockVectorBX*lambda;\n    %     end\n    blockVectorR = blockVectorAX - ...\n        bsxfun(@times,blockVectorBX,lambda');\nend\nresidualNorms=full(sqrt(sum(conj(blockVectorR).*blockVectorR)'));\nresidualNormsHistory(1:blockSize,iterationNumber) = ...\n    mygather(residualNorms);\nif verbosityLevel\n    fprintf('Final Eigenvalues lambda %17.16e \\n',mygather(lambda));\n    fprintf('Final Residual Norms %e \\n',mygather(residualNorms'));\nend\nif verbosityLevel == 2\n    whos\n    figure(491)\n    semilogy((abs(residualNormsHistory(1:blockSize,1:iterationNumber-1)))');\n    title('Residuals for Different Eigenpairs','fontsize',16);\n    ylabel('Eucledian norm of residuals','fontsize',16);\n    xlabel('Iteration number','fontsize',16);\n    %axis tight;\n    %axis([0 maxIterations+1 1e-15 1e3])\n    set(gca,'FontSize',14);\n    figure(492);\n    semilogy(abs((lambdaHistory(1:blockSize,1:iterationNumber)-...\n        repmat(mygather(lambda),1,iterationNumber)))');\n    title('Eigenvalue errors for Different Eigenpairs','fontsize',16);\n    ylabel('Estimated eigenvalue errors','fontsize',16);\n    xlabel('Iteration number','fontsize',16);\n    %axis tight;\n    %axis([0 maxIterations+1 1e-15 1e3])\n    set(gca,'FontSize',14);\n    drawnow;\nend\nvarargout(1)={failureFlag};\nvarargout(2)={lambdaHistory(1:blockSize,1:iterationNumber)};\nvarargout(3)={residualNormsHistory(1:blockSize,1:iterationNumber-1)};\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/umap/umap/lobpcg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5520821653314906}}
{"text": "function [dyn] = N2dyn(N)\n% Convert force from newtons to dyne. \n% Chad A. Greene 2012\ndyn = N*100000;", "meta": {"author": "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/N2dyne.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.552067123031747}}
{"text": "function [locs pks]=peakseek(x,minpeakdist,minpeakh)\n% Alternative to the findpeaks function.  This thing runs much much faster.\n% It really leaves findpeaks in the dust.  It also can handle ties between\n% peaks.  Findpeaks just erases both in a tie.  Shame on findpeaks.\n%\n% x is a vector input (generally a timecourse)\n% minpeakdist is the minimum desired distance between peaks (optional, defaults to 1)\n% minpeakh is the minimum height of a peak (optional)\n%\n% (c) 2010\n% Peter O'Connor\n% peter<dot>ed<dot>oconnor .AT. gmail<dot>com\n\nif size(x,2)==1, x=x'; end\n\n% Find all maxima and ties\nlocs=find(x(2:end-1)>=x(1:end-2) & x(2:end-1)>=x(3:end))+1;\n\nif nargin<2, minpeakdist=1; end % If no minpeakdist specified, default to 1.\n\nif nargin>2 % If there's a minpeakheight\n    locs(x(locs)<=minpeakh)=[];\nend\n\nif minpeakdist>1\n    while 1\n\n        del=diff(locs)<minpeakdist;\n\n        if ~any(del), break; end\n\n        pks=x(locs);\n\n        [garb mins]=min([pks(del) ; pks([false del])]); %#ok<ASGLU>\n\n        deln=find(del);\n\n        deln=[deln(mins==1) deln(mins==2)+1];\n\n        locs(deln)=[];\n\n    end\nend\n\nif nargout>1,\n    pks=x(locs);\nend\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/26581-peakseek/peakseek.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5520671148715314}}
{"text": "function [ y2, j2, f2 ] = ymdf_to_yjf_islamic ( y1, m1, d1, f1 )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_YJF_ISLAMIC converts from YMDF to YJF form in the Islamic calendar.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    19 April 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Parameters:\n%\n%    Input, integer Y1, M1, D1, real F1,\n%    the YMDF date.\n%\n%    Output, integer Y2, J2, real F2, the YJF date.\n%\n\n%\n%  Check the date.\n%\n  [ y1, m1, d1, ierror ] = ymd_check_islamic ( y1, m1, d1 );\n\n  if ( ierror ~= 0 )\n    y2 = 0;\n    j2 = 0;\n    f2 = 0.0;\n    return\n  end\n\n  y2 = y1;\n  j2 = d1;\n  f2 = f1;\n%\n%  Add in the days of the elapsed months.\n%\n  for m = 1 : m1 - 1\n    j2 = j2 + month_length_islamic ( y2, m );\n  end\n\n  return\nend\n", "meta": {"author": "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_yjf_islamic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5520671148715314}}
{"text": "function tQuantUnif\n\nFPDF = PDFFn('Laplace');\n\nSym = true;\n%Sym = false;\nNlevA = [4 8 16 32 64 128 256];\nfor (Nlev = NlevA)\n  [Yq, Xq, MSE, Entropy, SNRdB, sdV] = QuantUnif(Nlev, FPDF, Sym);\n%  Xq\n%  Yq\n  fprintf('Nlev:%4d, SNR =%5.1f dB, s/V =%6.3f, Entropy =%5.2f bits\\n', ...\n      Nlev, SNRdB, sdV, Entropy); \nend\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/24333-quantizers/Quantizer/test/tQuantUnif.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5519687061698906}}
{"text": "function ierror = part_rsf_check ( n, npart, a )\n\n%*****************************************************************************80\n%\n%% PART_RSF_CHECK checks a reverse standard form partition of an integer.\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%    N must be positive.\n%\n%    Input, integer NPART, the number of parts of the partition.\n%    1 <= NPART <= N.\n%\n%    Input, integer A(NPART), contains the partition.\n%    A(1) through A(NPART) contain the nonzero integers which\n%    sum to N.  The entries must be in ASCENDING order.\n%\n%    Output, integer IERROR, error flag.\n%    0, no error.\n%    -1, N is illegal.\n%    -2, NPART is illegal.\n%    -3, the entries do not add up to N.\n%    I, the I-th entry of A is illegal.\n%\n  ierror = 0;\n\n  if ( n < 1 )\n    ierror = -1;\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'PART_RSF_CHECK - Fatal error!\\n' );\n    fprintf ( 1, '  N < 1.\\n' );\n    error ( 'PART_RSF_CHECK - Fatal error!\\n' );\n  end\n\n  if ( npart < 1 || n < npart )\n    ierror = -2;\n    return\n  end\n%\n%  Every entry must lie between 1 and N.\n%\n  for i = 1 : npart\n    if ( a(i) < 1 || n < a(i) )\n      ierror = i;\n      return\n    end\n  end\n%\n%  The entries must be in ascending order.\n%\n  for i = 2 : npart\n    if ( a(i) < a(i-1) )\n      ierror = i;\n      return\n    end\n  end\n%\n%  The entries must add up to N.\n%\n  if ( sum ( a(1:npart) ) ~= n )\n    ierror = -3;\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/combo/part_rsf_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.7931059585194574, "lm_q1q2_score": 0.5519686844623123}}
{"text": "function pass = test_fevalm( pref ) \n% Test spherefun/fevalm \n\nif ( nargin == 0) \n    pref = chebfunpref; \nend\n\ntol = 100*pref.cheb2Prefs.chebfun2eps;\nrng(2016);\n\n% Check empty spherefun: \nf = spherefun;\ns = pi*(2*rand(5,1) - 1); \nt = pi/2*rand(5,1); \nB = fevalm(f, s, t); \npass(1) = isempty( B );\n\n% Check rank 1 spherefun: \nf = chebfun2(@(lam,th) cos(lam).*sin(th)); \ns = pi*(2*rand(5,1) - 1); \nt = pi/2*rand(5,1); \n[ss, tt] = meshgrid( s, t); \nA = feval(f, ss, tt); \nB = fevalm(f, s, t); \npass(2) = norm( A - B ) < tol; \n\n% Check essentially one dimensional function:\nf = spherefun(@(lam,th) exp(-(cos(th)-1).^2)); \ns = pi*(2*rand(5,1) - 1); \nt = pi/2*rand(5,1); \n[ss, tt] = meshgrid( s, t); \nA = feval(f, ss, tt); \nB = fevalm(f, s, t); \npass(3) = norm( A - B ) < tol; \n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/spherefun/test_fevalm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5519686825533645}}
{"text": "function segment_length = p05_boundary_segment_length ( segment_index, h )\n\n%*****************************************************************************80\n%\n%% P05_BOUNDARY_SEGMENT_LENGTH returns boundary segment lengths in problem 05.\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 SEGMENT_INDEX, the index of one of the boundary segments.\n%\n%    Input, real H, the suggested spacing between points.\n%\n%    Output, integer SEGMENT_LENGTH, the number of points in the segment.\n%\n  center1 = [  0.0, 0.0 ];\n  center2 = [ -0.4, 0.0 ];\n  r1 = 1.00;\n  r2 = 0.55;\n\n  if ( h <= 0.0 )\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'P05_BOUNDARY_SEGMENT_LENGTH - Fatal error!\\n' );\n    fprintf ( 1, '  Nonpositive H = %f\\n', h );\n    error ( 'P05_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n  end\n  \n  if ( segment_index == 1 )\n\n    n = round ( ( pi * ( r1  + r2 ) ...\n      + ( ( center2(1) - r2 ) - ( center1(1) - r1 ) ) ...\n      + ( ( center1(1) + r1 ) - ( center2(1) + r2 ) ) ) / h );\n    n = max ( n, 21 );\n    segment_length = n;\n\n  else\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'P05_BOUNDARY_SEGMENT_LENGTH - Fatal error!\\n' );\n    fprintf ( 1, '  Illegal SEGMENT_INDEX = %d\\n', segment_index );\n    error ( 'P05_BOUNDARY_SEGMENT_LENGTH - 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/test_triangulation/p05_boundary_segment_length.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5519686793572176}}
{"text": "function cost = rcrossvalidatelssvm(model,Y, L, omega, estfct,combinefct)\n%%%%%%%%%%%%%%%%%%%%%\n% INTERNAL FUNCTION %\n%%%%%%%%%%%%%%%%%%%%%\n% Estimate the model performance of a model with l-fold robust crossvalidation\n\n% Copyright (c) 2011,  KULeuven-ESAT-SCD, License & help @\n% http://www.esat.kuleuven.be/sista/lssvmlab\n\n%\n% initialisation and defaults\n%\n%if size(X,1)~=size(Y,1), error('X and Y have different number of datapoints'); end\n[nb_data,y_dim] = size(Y);\nd = size(model.xtrain,2);\n% LS-SVMlab\neval('model = initlssvm(model{:});',' ');\nmodel.status = 'changed';\n\neval('L;','L=min(round(sqrt(size(model.xfull,1))),10);');\neval('estfct;','estfct=''mse'';');\neval('combinefct;','combinefct=''mean'';');\n\npy = Y;\n[~,Y] = postlssvm(model,[],Y);\n\ngams = model.gamcsa; \neval('sig2s = model.kernel_parscsa;','sig2s=[];')\neval('deltas = model.deltacsa;','deltas=[];')\n%\n%initialize: no incremental  memory allocation\n%\ncosts = zeros(L,length(gams));\nblock_size = floor(nb_data/L);\n\n% check whether there are more than one gamma or sigma\nfor j =1:numel(gams)\n    if strcmp(model.kernel_type,'RBF_kernel') || strcmp(model.kernel_type,'RBF4_kernel')\n        model = changelssvm(changelssvm(model,'gam',gams(j)),'kernel_pars',sig2s(j));\n        eval('model.delta=deltas(j);','model.delta=[];')\n    elseif strcmp(model.kernel_type,'lin_kernel')\n        model = changelssvm(model,'gam',gams(j));\n        eval('model.delta=deltas(j);','model.delta=[];')\n    elseif strcmp(model.kernel_type,'poly_kernel')\n        model = changelssvm(changelssvm(model,'gam',gams(j)),'kernel_pars',[sig2s(1,j);sig2s(2,j)]);\n        eval('model.delta=deltas(j);','model.delta=[];')\n    else\n        model = changelssvm(changelssvm(model,'gam',gams(j)),'kernel_pars',[sig2s(1,j);sig2s(2,j);sig2s(3,j)]);\n        eval('model.delta=deltas(j);','model.delta=[];')\n    end\n    \n    S = ones(nb_data,1); \n    Atot = kernel_matrix2(omega,model.kernel_type,model.kernel_pars,d)+eye(nb_data)./model.gam;\n    %\n    %\n    % start loop over l validations\n    %\n    for l = 1:L,\n\n        % divide in data and validation set, trainings data set is a copy\n        % of permutated_data, validation set is just a logical index\n        if l==L,\n            train = 1:block_size*(l-1);\n            validation = block_size*(l-1)+1:nb_data;\n        else\n            train = [1:block_size*(l-1) block_size*l+1:nb_data];\n            validation = block_size*(l-1)+1:block_size*l;\n        end\n\n        A = [0 S(train)';S(train) Atot(train,train)];\n        b = [0;py(train)]; \n\n        % Solve linear system\n        sol = linsolve(A,b,struct('SYM',true));\n\n        % Determine residuals ek\n        ek = sol(2:end)./model.gam;\n        g = model.gam;\n        %for i=2:size(A,1), A(i,i) = A(i,i) - 1/g; end\n        A = A-eye(size(train,2)+1)./g; A(1,1)=0;\n        Ah = A;\n        %\n        % robust estimation of the variance\n        %\n        for k = 1:30\n            vare = 1.483*median(abs((ek)-median(ek)));\n            alphaold = sol(2:end);\n            %\n            % robust re-estimation of the alpha's and the b\n            %\n            cases = reshape((ek./vare),1,size(ek,1));\n            W = g*weightingscheme(cases,model.weights,model.delta);\n            \n            for t=1:size(train,2), A(t+1,t+1) = A(t+1,t+1)+1./W(t); end   \n                        \n            sol = linsolve(A,b,struct('SYM',true));\n                        \n            ek = sol(2:end)./W';\n            A = Ah;\n            if norm(abs(alphaold-sol(2:end)),'fro')<=1e-3,\n                %fprintf('\\n Converged after %.0f iteration(s)', k);\n                k = inf;                \n            end\n            model.status = 'changed';\n        end\n        \n        % regression\n        % Simulate system on validation data\n        yh = Atot(train,validation)'*sol(2:end) + ones(numel(validation),1)*sol(1);\n        [~,yh] = postlssvm(model,[],yh);\n        z = yh - Y(validation,:);\n        eval('costs(l,j) = feval(estfct,z);')\n    end\nend\n\ncost = feval(combinefct, costs);\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/rcrossvalidatelssvm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5519322813758891}}
{"text": "function [rglm,yclean] = spm_rglm (y,X,m,priors,verbose)\n% Fit a Robust GLM \n% FORMAT [rglm,yclean] = spm_rglm (y,X,m,priors,verbose)\n%\n% The noise is modelled with a Mixture of Zero-Mean Gaussians \n%\n% y          [N x 1] data vector\n% X          [N x p] design matrix\n% m          Number of mixture components\n% priors     .alpha      [1 x 1] weight precision (default=0.001)\n%            .mean_err   [m x 1] vector of mean error SD\n%            .std_err    [m x 1] vector of dev of error SD\n% verbose    0/1 to printout inner workings (default=0)\n%\n% rglm       Returned model \n% yclean     'Clean' data\n%\n% -------------------------------------------------------\n% The fields in rglm are:\n%\n% m                The number of error components\n% fm               The negative free energy\n% loops            Number of iterations used\n%\n%                  In the field priors:\n%\n% lambda_0         Dirichlet parameters for mixing coeffs\n% b_0,c_0          Gamma parameters for precisions\n%\n%                  In the field posts:\n%\n% lambda           Dirichlet parameters  for mixing coeffs\n% b,c              Gamma parameters for precisions\n% w_mean           Mean estimated regression coefficients\n% w_cov            Covariance of regression coefficients\n% pi               mixing coefficients (lambda/sum(lambda))\n% variances        variances (1./(b.*c))\n% gamma            the responsilities of each noise component\n%___________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: spm_rglm.m 1276 2008-03-28 18:29:19Z guillaume $\n\nif nargin < 4 | isempty(priors)\n    mean_alpha=0.001;\n    % Set variance priors\n    b_0=1000*ones(m,1);\n    c_0=0.001*ones(m,1);\nelse\n    mean_alpha=priors.alpha;\n    for mm=1:m,\n        b_0(mm)=(priors.std_err(mm)^2)/priors.mean_err(mm);\n        c_0(mm)=priors.mean_err(mm)/b_0(mm);\n    end\nend\n\nif (m==1)\n    rglm=spm_glm(y,X,mean_alpha);\n    return\nend\n\nif nargin < 5 | isempty(verbose)\n    verbose=0;\nend\n\ny=y(:);\nN=length(y);\np=size(X,2);\nspX=issparse(X);\n\n% Initialise regression coefficients to maximum likelihood solution\nif spX\n    iX=inv(X'*X);\n    w_mean=iX*X'*y;\nelse\n    iX=inv(X'*X);\n    w_mean = pinv(X)*y;\nend\ny_pred = full(X*w_mean);\nerr=y-y_pred;\nv=mean((y-y_pred).^2);\nw_cov = v*iX;\n\n% Set mixing priors\nlambda_0=5;\n\n% Cluster on absolute difference from mean\nzmix=spm_kmeans1(abs(err-mean(err)),m);\n% Posterior for mixers\nlambda=100*zmix.pi+lambda_0;\nzmean=[zmix.m].^2;\n% Posterior for precisions\nvar_precision=1/std(zmean)^2;\nfor s=1:m,\n      % Set so that b*c=precision and  b^2*c=var_precision\n      precision=1/zmean(s);\n      b(s)=var_precision/precision;\n      c(s)=(precision^2)/var_precision;\nend\n\nif verbose\n    disp('Init');\n    for s=1:m, \n        disp(sprintf('State %d mix=%1.2f var=%1.2f',s,lambda(s)/sum(lambda),1/(b(s)*c(s))));\n    end\nend\n\nlik=[];\ntol=0.0001;\nmax_loops=100;\nWLOOPS=5;\nfor loops=1:max_loops,\n    \n    % E-step\n    lambda_tot=sum(lambda);\n    ypred=full(X*w_mean);\n    ypred2=ypred.^2;\n    y2=y.^2;\n    xt=X';\n    y_err=full(sum(xt.*(w_cov*xt)));\n    \n    tv=y2-2*ypred.*y+y_err'+ypred2;\n    tv=tv';\n    for s=1:m,\n        log_tilde_pi(s)=psi(lambda(s))-psi(lambda_tot);\n        log_tilde_beta(s)=psi(c(s))+log(b(s));\n        tilde_pi(s)=exp(log_tilde_pi(s));\n        tilde_beta(s)=exp(log_tilde_beta(s));\n        mean_beta(s)=c(s)*b(s);\n        tilde_var(s,:)=tv;\n        gamma(s,:)=tilde_pi(s)*(tilde_beta(s)^0.5)*exp(-0.5*mean_beta(s)*tv);\n    end\n    gamma_n=sum(gamma);\n    for s=1:m,\n        if mean(gamma_n) > eps\n            % If component still exists\n            gamma(s,:)=gamma(s,:)./gamma_n;\n        end\n    end\n    \n    \n    % M-step\n    % Part I\n    for s=1:m,\n        pi_bar(s)=mean(gamma(s,:));\n        N_bar(s)=N*pi_bar(s);\n        mean_bar(s)=mean(gamma(s,:)'.*y);\n        dg=sparse(1:N,1:N,gamma(s,:));\n        x_bar(s,:)=mean(dg*X);\n        var_bar_mu(s)=mean(gamma(s,:).*tilde_var(s,:));\n    end\n    \n    % CALCULATE THE FREE ENERGY\n    avg_likelihood=sum(N_bar.*(log_tilde_pi+0.5*log_tilde_beta));\n    fit=-0.5*N*sum(mean_beta.*var_bar_mu);\n    % Ensure that 0 log 0 = 0\n    ent_s=sum(sum(-gamma.*log(gamma+eps)));\n    avg_likelihood=avg_likelihood+fit+ent_s;\n    lambda_p=lambda_0*ones(1,m);\n    kl_dir=spm_kl_dirichlet(lambda,lambda_p,log_tilde_pi);\n    kl_gamm=0;\n    for s=1:m,\n        kl_gamm=kl_gamm+spm_kl_gamma(b(s),c(s),b_0(s),c_0(s));\n    end\n    kl_weights=spm_kl_normald(w_mean,w_cov,zeros(1,p),(1/mean_alpha)*eye(p));\n    fm= avg_likelihood - kl_dir - kl_gamm - kl_weights;\n    \n    % Convergence criterion\n    oldlik=lik;\n    lik=fm;\n    if (mod(loops-1,WLOOPS)==0)\n        if (loops>1)\n            if abs((lik-oldlik)/lik) < tol\n                break;\n            end\n        end\n    end\n    \n    % M-Step: Part II\n    for s=1:m,\n        % Mixers\n        lambda(s)=N_bar(s)+lambda_0;\n        % Precisions\n        b(s)=1/(0.5*N*var_bar_mu(s)+1/b_0(s));\n        c(s)=0.5*N_bar(s)+c_0(s);\n        mean_beta(s)=c(s)*b(s);\n    end\n    \n    if mod(loops,WLOOPS)==0\n        % Regression coefficients\n        cc=sparse(p,p);\n        cw=zeros(p,1);\n        for s=1:m,\n            dg=sparse(1:N,1:N,gamma(s,:));\n            cc=cc+mean_beta(s)*X'*dg*X;\n            cw=cw+mean_beta(s)*X'*dg*y;\n        end\n        cc=cc+mean_alpha*speye(p);\n        w_cov=inv(cc);\n        w_mean=w_cov*cw;\n    end\n    \n    if verbose\n        disp(sprintf('It=%d, L_AV =%1.2f, KL Mix=%1.2f, KL Prec=%1.2f, KL-W=%1.2f, Fm=%1.2f',loops,avg_likelihood,kl_dir,kl_gamm,kl_weights,fm));\n        disp(' ');\n        disp(sprintf('Iteration number=%d',loops));\n        for s=1:m,\n            var=1/(b(s)*c(s));\n            disp(sprintf('State %d pi_bar=%1.2f var=%1.2f',s,pi_bar(s),var));\n        end\n    end\n    \n    \nend\n\n% Put variables into data structure\nrglm.m=m;\nrglm.fm=fm;\nrglm.kl_dir=kl_dir;\nrglm.kl_gamm=kl_gamm;\nrglm.kl_w=kl_weights;\nrglm.mean_alpha=mean_alpha;\nrglm.priors.lambda_0=lambda_0;\nrglm.priors.c_0=c_0;\nrglm.priors.b_0=b_0;\nfor k=1:m,\n  rglm.posts.lambda(k)=lambda(k);\nend\nfor k=1:m,\n  rglm.posts.c(k)=c(k);\n  rglm.posts.b(k)=b(k);\nend\nrglm.posts.w_mean=w_mean;\nrglm.posts.w_cov=w_cov;\n\nfor k=1:m,\n  rglm.posts.pi(k)=lambda(k)/sum(lambda);\nend\nrglm.posts.variances=1./(b.*c);\nrglm.posts.gamma=gamma;\nrglm.loops=loops;\n\n% Get 'clean' data\nif m > 1\n    [tmp,outlier_class]=min(rglm.posts.pi);\n    e=y-ypred;\n    outlier_error=rglm.posts.gamma(outlier_class,:)'.*e;\n    yclean=ypred+e-outlier_error;\nelse\n    yclean=y;\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/mixture/spm_rglm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5519322731872183}}
{"text": "function [y,ysup] = erf_rnd(x,rnd)\n% input x real non-negative column vector\n% rnd  -1  y = lower bound for erf(x)\n%       1  y = upper bound for erf(x)\n%      []  [y,ysup] inclusion of erf(x)\n% rounding may be altered after leaving erf_rnd\n%\n\n% written  05/30/13     S.M. Rump\n%\n\n  x2 = hex2num('4017744f8f74e94b');     % ~5.86: erf(x)>pred(1) for x>=x2\n  \n  y = x;\n  if isempty(rnd)\n    ysup = x;\n  end\n  \n  index = ( x<=0.5 );                   % first method\n  if any(index)                         % x in [0,0.5]\n    if isempty(rnd)\n      [y(index),ysup(index)] = erf_rnd1(x(index),rnd,6);\n    else\n      y(index) = erf_rnd1(x(index),rnd,6);\n    end\n  end\n  Index = index;                        % store finished indices\n  \n  index = ( ~Index ) & ( x<x2 );        % second method\n  if any(index)                         % x in (0.5,x2)\n    y_index = 1 - erfc_rnd2(x(index));\n    if rnd==-1\n      y(index) = y_index.inf;\n    elseif rnd==1\n      y(index) = y_index.sup;\n    else\n      y(index) = y_index.inf;\n      ysup(index) = y_index.sup;\n    end\n  end\n  \n  index = ( x>=x2 );\n  if any(index)                         % x in [x2,inf]\n    if isempty(rnd)                     % inclusion [y,ysup] of erf(x)\n      y(index) = hex2num('3fefffffffffffff');   % pred(1)\n      ysup(index) = 1;\n    elseif rnd==1                       % y upper bound for erf(x)\n      y(index) = 1;\n    else                                % y lower bound for erf(x)\n      y(index) = hex2num('3fefffffffffffff');   % pred(1)\n    end\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/private/erf_rnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.6406358548398979, "lm_q1q2_score": 0.5519322718311646}}
{"text": "function [nV, eV, aV, alt, lat, long, type, id] = DecodeBits_ADI(bits, currentLat, currentLong)\n% Copyright 2015, The MathWorks, Inc.\n\n% Read message bits and decode valid messages for position, velocity and\n% altitude data\n\n% Initialize data\nnV = 0;\neV = 0;\naV = 0;\nalt = 0;\nlat = 0;\nlong = 0;\ntype = 'X';\nid = [bits(9:12)'*[8;4;2;1] bits(13:16)'*[8;4;2;1] bits(17:20)'*[8;4;2;1] bits(21:24)'*[8;4;2;1] bits(25:28)'*[8;4;2;1] bits(29:32)'*[8;4;2;1]]\n\n% Check 9th and 10th hex characters for mesasge type\ntf1 = bits(33:36)'*[8;4;2;1];\ntf2 = bits(37:40)'*[8;4;2;1];\nif tf1 == 9 && tf2 == 9\n    [nV, eV, aV] = AltVelCalc_ADI(bits);\n    type = 'A';\nelseif tf1 == 5 || tf1 == 6\n    [lat, long, alt] = LatLongCalcSingle_ADI(bits, currentLat, currentLong);\n    type = 'L';\nelseif tf1 == 9 && tf2 == 0\n    [lat, long, alt] = LatLongCalcSingle_ADI(bits, currentLat, currentLong);\n    type = 'L';\nend\n\n", "meta": {"author": "analogdevicesinc", "repo": "MathWorks_tools", "sha": "5f8df06d4fc2f4832ed9ec8b722fb750b2261f20", "save_path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools", "path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools/MathWorks_tools-5f8df06d4fc2f4832ed9ec8b722fb750b2261f20/targeting_models/ADSB/DecodeBits_ADI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5519322568098767}}
{"text": "% MatrixUser, a multi-dimensional matrix analysis software package\n% https://sourceforge.net/projects/matrixuser/\n% \n% The MatrixUser is a matrix analysis software package developed under Matlab\n% Graphical User Interface Developing Environment (GUIDE). It features \n% functions that are designed and optimized for working with multi-dimensional\n% matrix under Matlab. These functions typically includes functions for \n% multi-dimensional matrix display, matrix (image stack) analysis and matrix \n% processing.\n%\n% Author:\n%   Fang Liu <leoliuf@gmail.com>\n%   University of Wisconsin-Madison\n%   Aug-30-2014\n\n\n\nfunction MU_funcWaterfall(Temp,Event,handles)\nhandles = guidata(handles.MU_matrix_display);\n\nfigure;\nwaterfall(double(handles.BMatrix));\ncolormap(handles.V.Color_map);\n\n\nend", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/External/MatrixUser2.2/Src/FuncLib/MU_funcWaterfall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5519215009165775}}
{"text": "function T = RpToTrans(R, p)\n% *** CHAPTER 3: RIGID-BODY MOTIONS ***\n% Takes rotation matrix R and position p.\n% Returns the corresponding homogeneous transformation matrix T in SE(3).\n% Example Input:\n% \n% clear; clc;\n% R = [[1, 0, 0]; [0, 0, -1]; [0, 1, 0]];\n% p = [1; 2; 5];\n% T = RpToTrans(R, p)\n% \n% Output:\n% T =\n%     1     0     0     1\n%     0     0    -1     2\n%     0     1     0     5\n%     0     0     0     1\n\nT = [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/RpToTrans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5519215009165773}}
{"text": "function [imgOut, exposure_value] = SelectOverexposedTMO(img, percent)\n%\n%        [imgOut, exposure_value] = SelectOverexposedTMO(img, percent)\n%\n%       \n%        A simple TMO that generates an SDR image with a given percentage\n%        of overexposed pixels.\n%\n%        Input:\n%           -img: input HDR image\n%           -percent: percentage of overexposed pixels.\n%\n%        Output:\n%           -imgOut: a single exposure with the selected percentage of\n%           overexposed pixels. \n%\n%\n% \n%     Copyright (C) 2022 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 <http://www.gnu.org/licenses/>.\n%\n\nif ~exist('percent', 'var')\n    percent = 0.1;\nend\n\ngamma_inv = 1.0 / 2.2;\n\n    function err = residual(c)    \n        \n        if c > 0.0\n            tmp = ClampImg((img * c).^gamma_inv, 0.0, 1.0); \n            L = lum(tmp);\n            tmp_percent = length(find(L >= 0.95)) / numel(L);\n        \n            err = abs(tmp_percent - percent);\n        else\n            err = 1e9;\n        end\n    end\n\nexposure_start = 1.0;\nexposure_value = fminsearch(@residual, exposure_start, getOpts);\n\nimgOut = ClampImg(img * exposure_value, 0.0, 1.0);\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/SelectOverexposedTMO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800692021119887, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5519214972522893}}
{"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 <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\n%%begin\n\n% Forward dynamics is the computation of joint accelerations given position and\n% velocity state, and actuator torques.  It is useful in simulation of a robot\n% control system.\n%\n% Consider a Puma 560 at rest in the zero angle pose, with zero applied joint \n% torques. The joint acceleration would be given by\n\nmdl_puma560\np560.accel(qz, zeros(1,6), zeros(1,6))\n\n% To be useful for simulation this function must be integrated.  fdyn() uses the\n% MATLAB function ode45() to integrate the joint acceleration.  It also allows \n% for a user written function to compute the joint torque as a function of \n% manipulator state.\n%\n% To simulate the motion of the Puma 560 from rest in the zero angle pose \n% with zero applied joint torques\n\ntic\n[t q qd] = p560.nofriction().fdyn(10, [], qz);\ntoc\n\n% and the resulting motion can be plotted versus time\n\nsubplot(3,1,1)\nplot(t,q(:,1))\nxlabel('Time (s)');\nylabel('Joint 1 (rad)')\nsubplot(3,1,2)\nplot(t,q(:,2))\nxlabel('Time (s)');\nylabel('Joint 2 (rad)')\nsubplot(3,1,3)\nplot(t,q(:,3))\nxlabel('Time (s)');\nylabel('Joint 3 (rad)')\n\n% Clearly the robot is collapsing under gravity, but it is interesting to \n% note that rotational velocity of the upper and lower arm are exerting \n% centripetal and Coriolis torques on the waist joint, causing it to rotate.\n\n% This can be shown in animation also\nclf\np560.plot(q)\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/fdyn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5519214929137428}}
{"text": "function linplus_test535 ( )\n\n%*****************************************************************************80\n%\n%% TEST535 tests R8S3_READ, R8S3_READ_SIZE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 March 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  input_file = 'r8s3_matrix.txt';\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST535\\n' );\n  fprintf ( 1, '  For a R8S3 system,\\n' );\n  fprintf ( 1, '  R8S3_READ_SIZE reads the size of the matrix.\\n' );\n  fprintf ( 1, '  R8S3_READ reads the matrix.\\n' );\n\n  [ n, nz_num ] = r8s3_read_size ( input_file );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  R8S3_READ_SIZE reports matrix size data:\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Matrix order N =         %d\\n', n );\n  fprintf ( 1, '  Matrix nonzeros NZ_NUM = %d\\n', nz_num );\n\n  [ row, col, a ] = r8s3_read ( input_file, n, nz_num );\n\n  isym = 0;\n\n  r8s3_print_some ( n, n, nz_num, isym, row, col, a, 1, 1, ...\n    10, 10, '  Initial 10x10 block of recovered R8S3 matrix:' );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Deleting the matrix data file \"%s\"\\n', input_file );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/linplus_test535.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.5519214910815994}}
{"text": "function [img1_rot, rot, err] = AlignLLPanoramas(img1, img2, bVisualization)\n%\n%\n%     [img1_rot, rot, err] = AlignLLPanoramas(img1, img2, bVisualization)\n%\n%     This function finds the rotation around Y-axis in pixel for aligning\n%     the panorma img1 (in longitude-latitude format) to the panorma\n%     img2 (in longitude-latitude format).\n%       \n%     Note that img1 and img2 have to share the same Y-axis in order to\n%     produce a meaningful result!\n%\n%\n%     Input:\n%       -img1: unaligned image\n%       -img2: reference panorama for alignment\n%       -bVisualization: if it set to 1 this will show the result of \n%                        minimization\n%\n%     Output:\n%       -img1_rot: img1 rotated to be aligned to img2\n%       -rot: rotation in pixel. Img1 needs to be shifted of rot pixels in\n%             order to be aligned to img2. For the rotation use imShiftWrap.m\n%       -err: matching error\n%\n%     Copyright (C) 2012-16  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 <http://www.gnu.org/licenses/>.\n%\n\nif(~exist('bVisualization', 'var'))\n    bVisualization = 0;\nend\n\nc = size(img1, 2);\n\n%Calculate the descriptor\nLwa_ext = (logMean(lum(img1)) + logMean(lum(img2))) / 2.0;\n\nimg1_tmo = ReinhardTMO(img1, 0.15, 1e9, 'global', [], Lwa_ext);\nimg2_tmo = ReinhardTMO(img2, 0.15, 1e9, 'global', [], Lwa_ext);\n\nline1 = LLDescriptor(img1_tmo, 1)';\nline2 = LLDescriptor(img2_tmo, 1)';\n\n%minimization of the rotation\nrot = 0;\nerr = sum((line1 - line2).^2);\n\nfor i=1:(c - 1)\n    line1 = circshift(line1, 1);\n    tmpErr = sum((line1 - line2).^2);\n\n    if(tmpErr < err)\n        rot = i;\n        err = tmpErr;\n    end\nend\n\n%plotting the result\nif(bVisualization)\n    line1 = circshift(line1, rot);\n    plot(1:c, line1, 1:c, line2);\nend\n\nimg1_rot = imShiftWrap(img1, rot);\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/EnvironmentMaps/AlignLLPanoramas.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5519214892494557}}
{"text": "%% Copyright (C) 2008 Eric Chassande-Mottin\n%% Copyright (C) 2011 Carn\u00eb Draug\n%% Copyright (C) 2016, 2018, 2022 Colin B. Macdonald\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 <http://www.gnu.org/licenses/>.\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defun laguerreL (@var{n}, @var{x})\n%% Evaluate Laguerre polynomials.\n%%\n%% Compute the value of the Laguerre polynomial of order @var{n}\n%% for each element of @var{x}.\n%% For example, the Laguerre polynomial of order 14 evaluated at\n%% the point 6 is\n%% @example\n%% @group\n%% @c doctest: +SKIP_IF(compare_versions (OCTAVE_VERSION(), '6.0.0', '<'))\n%% laguerreL (14, 6)\n%%   @result{} 0.9765\n%% @end group\n%% @end example\n%%\n%% This implementation uses a three-term recurrence directly on the values\n%% of @var{x}.  The result is numerically stable, as opposed to evaluating\n%% the polynomial using the monomial coefficients.  For example, we can\n%% compare the above result to a symbolic construction:\n%% @example\n%% @group\n%% syms x\n%% L = laguerreL (14, x);\n%% exact = subs (L, x, 6)\n%%   @result{} exact = (sym)\n%%       34213\n%%       \u2500\u2500\u2500\u2500\u2500\n%%       35035\n%% @end group\n%% @end example\n%% If we extract the monomial coefficients and numerically evaluate the\n%% polynomial at a point, the result is rather poor:\n%% @example\n%% @group\n%% coeffs = sym2poly (L);\n%% @c doctest: +XFAIL_IF(compare_versions (OCTAVE_VERSION(), '6.0.0', '<'))\n%% polyval (coeffs, 6)\n%%   @result{} 0.9765\n%% err = ans - double (exact);\n%% num2str (err, '%.3g')\n%%   @result{} -1.68e-11\n%% @end group\n%% @end example\n%% So please don't do that!  The numerical @code{laguerreL} function\n%% does much better:\n%% @example\n%% @group\n%% err = laguerreL (14, 6) - double (exact)\n%%   @result{} err = 9.9920e-16\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/laguerreL}\n%% @end defun\n\nfunction L = laguerreL(n, x)\n\n  if (nargin ~= 2)\n    print_usage ();\n  end\n\n  if (any (n < 0) || any (mod (n, 1) ~= 0))\n    error('second argument \"n\" must consist of positive integers');\n  end\n\n  if (~isscalar (n) && isscalar (x))\n    x = x*ones (size (n));\n  elseif (~isscalar (n) && ~isscalar (x) && ~isequal (size (n), size (x)))\n    error ('inputs must be same size or scalar')\n  end\n\n  L0 = ones (size (x), class(x));\n  L1 = 1 - x;\n\n  if (isscalar (n))\n    if (n == 0)\n      L = L0;\n    elseif (n == 1)\n      L = L1;\n    else\n      for k = 2:n\n        L = (2*k-1-x)/k .* L1 - (k-1)/k * L0;\n        L0 = L1;\n        L1 = L;\n      end\n    end\n  else\n    L = L0;\n    L(n >= 1) = L1(n >= 1);\n    maxn = max (n(:));\n    for k = 2:maxn\n      I = (n >= k);  % mask for entries still to be updated\n      L(I) = (2*k - 1 - x(I))/k .* L1(I) - (k - 1)/k * L0(I);\n      L0 = L1;\n      L1 = L;\n    end\n  end\n\nend\n\n\n%!error laguerreL (1)\n%!error laguerreL (1, 2, 3)\n\n%!assert (isequal (laguerreL (0, rand), 1))\n\n%!test\n%! x = rand;\n%! assert (isequal (laguerreL (1, x), 1 - x))\n\n%!test\n%! x=rand;\n%! y1=laguerreL(2, x);\n%! p2=[.5 -2 1];\n%! y2=polyval(p2,x);\n%! assert(y1 - y2, 0, 10*eps);\n\n%!test\n%! x=rand;\n%! y1=laguerreL(3, x);\n%! p3=[-1/6 9/6 -18/6 1];\n%! y2=polyval(p3,x);\n%! assert(y1 - y2, 0, 20*eps);\n\n%!test\n%! x=rand;\n%! y1=laguerreL(4, x);\n%! p4=[1/24 -16/24 72/24 -96/24 1];\n%! y2=polyval(p4,x);\n%! assert(y1 - y2, 0, 30*eps)\n\n%!error <positive integer> laguerreL(1.5, 10)\n%!error <same size or scalar> laguerreL([0 1], [1 2 3])\n%!error <same size or scalar> laguerreL([0 1], [1; 2])\n\n%!test\n%! % numerically stable implementation (in n)\n%! L = laguerreL (10, 10);\n%! Lex = 1763/63;\n%! assert (L, Lex, -eps)\n%! L = laguerreL (20, 10);\n%! Lex = -177616901779/14849255421;  % e.g., laguerreL(sym(20),10)\n%! assert (L, Lex, -eps)\n\n%!test\n%! % vectorized x\n%! L = laguerreL (2, [5 6 7]);\n%! Lex = [3.5 7 11.5];\n%! assert (L, Lex, eps)\n\n%!test\n%! L = laguerreL (0, [4 5]);\n%! assert (L, [1 1], eps)\n\n%!test\n%! % vector n\n%! L = laguerreL ([0 1 2 3], [4 5 6 9]);\n%! assert (L, [1 -4 7 -26], eps)\n\n%!test\n%! % vector n, scalar x\n%! L = laguerreL ([0 1 2 3], 6);\n%! assert (L, [1 -5 7 1], eps)\n\n%!assert (isa (laguerreL (0, single (1)), 'single'))\n%!assert (isa (laguerreL (1, single ([1 2])), 'single'))\n%!assert (isa (laguerreL ([1 2], single ([1 2])), 'single'))\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/laguerreL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.5519214878032733}}
{"text": "%DEMO_IMPROVEMARGINALS  Demonstration of marginal posterior improvements \n%                       in Laplace and EP algorithms.\n%\n%  Description\n%    Demonstration of marginal posterior corrections of latent\n%    variables in classification task. Demonstrated corrections are\n%    'fact' (EP & Laplace) and 'cm2' (Laplace). The corrected\n%    posterior distributions are compared to histograms of MCMC\n%    samples to assess the quality of corrections.\n%\n%   Reference\n%     Cseke & Heskes (2011). Approximate Marginals in Latent Gaussian\n%     Models. Journal of Machine Learning Research 12 (2011), 417-454\n%\n%  See also\n%    GP_PREDCM, DEMO_IMPROVEMARGINALS2\n%\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% Probit likelihood with EP\n% ---------------------------\nS = which('demo_improvemarginals');\nL = strrep(S,'demo_improvemarginals.m','demodata/synth.tr');\nx=load(L);\ny=x(:,end);\ny = 2.*y-1;\nx(:,end)=[];\n[n, nin] = size(x);\n\n% Load sampled results so the demo won't take hours or days to finish...\nL = strrep(S,'demo_improvemarginals.m','demodata/samples_marginal.mat');\nload(L);\n\n% Test data\nxt1=repmat(linspace(min(x(:,1)),max(x(:,1)),20)',1,20);\nxt2=repmat(linspace(min(x(:,2)),max(x(:,2)),20)',1,20)';\nxt=[xt1(:) xt2(:)];\n\n% Create a likelihood function\nlik = lik_probit();\n%lik = lik_logit();\n\n% Create a covariance function\ngpcf = gpcf_sexp('lengthScale', [0.9 0.9], 'magnSigma2', 10);\n\n% Set the prior for the parameters of the covariance function\npl = prior_t();\npm = prior_sqrtunif();\ngpcf = gpcf_sexp(gpcf, 'lengthScale_prior', pl,'magnSigma2_prior', pm); %\n\n% Create the GP structure (type is by default FULL)\ngp = gp_set('lik', lik, 'cf', gpcf, 'jitterSigma2', 1e-9);\n\n% Set the approximate inference method \ngp = gp_set(gp, 'latent_method', 'EP');\n\nind = 22;\nng=50;\nngt=30;\npc_ep=zeros(ng, 1); p_ep=zeros(ng,1); c_ep=zeros(ng,1); fvec_ep=zeros(ng,1);\npc_ep_pred=zeros(ngt, 1); p_ep_pred=zeros(ngt,1); c_ep_pred=zeros(ngt,1); fvec_ep_pred=zeros(ngt,1);\n\n% If we didnt load previously computed samples we would run the following\n% to get the MCMC samples for latents\n\n% gp2 = gp_set(gp, 'latent_method', 'MCMC');\n% \n% % set MC options\n% latent_opt.repeat=10;\n% \n% % obtain MC samples\n% rgp=gp_mc(gp2, x, y, 'latent_opt', latent_opt, 'nsamples', 4000, 'repeat', 2, 'display', 100);\n% rgp=thin(rgp,100);\n% \n% f_mc = rgp.latentValues(:,ind);\nf_mc = f_mc_probit;\nfor i=1:length(ind)\n  figure;\n  subplot(2,1,1);\n  \n  [testi, testi2] = hist(f_mc(:,i),50);\n  width = testi2(2)-testi2(1);\n  area = sum(testi.*width);\n  testi = testi./area;\n  b = bar(testi2,testi);\n  h = findobj(gca,'Type','patch');\n  set(h,'FaceColor','w')\n  hold on;\n  [Eft_ep, Varft_ep] = gp_pred(gp,x,y,x);\n  start=tic;\n  [pc_ep(:,i), fvec_ep(:,i), p_ep(:,i)] = gp_predcm(gp,x,y,'ind', ind(i), 'fcorr', 'fact'); tt_epfact=toc(start);\n  s = plot(fvec_ep(:,i), p_ep(:,i), '-k', fvec_ep(:,i), norm_pdf(fvec_ep(:,i), Eft_ep(ind(i)), sqrt(Varft_ep(ind(i)))),'-m', fvec_ep(:,i), pc_ep(:,i), '-r');\n  set(s,'LineWidth',2)\n  set(get(get(b,'Annotation'),'LegendInformation'),...\n    'IconDisplayStyle','off');\n  legend('EP-L', 'EP-G', 'EP-FACT');\n  title('Marginal corrections for probit likelihood (EP)');\n\n  subplot(2,1,2)\n\n  % Predictive corrections\n  [Eft_ep_pred, Varft_ep_pred] = gp_pred(gp,x,y,xt);\n  start=tic;\n  [pc_ep_pred(:,i), fvec_ep_pred(:,i), p_ep_pred(:,i)] = gp_predcm(gp,x,y,xt, 'ind', ind(i), 'fcorr', 'fact', 'ng', ngt);tt_epfact2=toc(start);\n  \n%   if ~exist(p_mc, 'var')\n%     % If sampled before\n%     [Ef_mc, Varf_mc]=gpmc_preds(rgp, x, y, xt(ind,:));\n%     p_mc=[];\n%     for i2=1:size(rgp.etr,1)\n%       p_mc=[p_mc norm_pdf(fvec_ep_pred(:,i), Ef_mc(:,i2), sqrt(Varf_mc(:,i2)))]; \n%     end\n%     p_mc=mean(p_mc,2);\n%   end\n  \n  plot(fvec_ep_pred(:,i), p_ep_pred(:,i), '-k', fvec_ep_pred(:,i), pc_ep_pred(:,i), '-r', fvec_ep_pred(:,i), ptx_prob, '-c');\n  set(s,'LineWidth',2)\n  legend('EP-G', 'EP-FACT', 'MCMC');\n  title('Predictive marginal corrections for probit likelihood (EP)');\nend\n\n% ---------------------------\n% Probit likelihood with Laplace\n% ---------------------------\n\n% Create the GP structure (type is by default FULL)\ngp = gp_set(gp, 'latent_method', 'Laplace');\n\n% Index for comparison values\nind = 22;\npc_la=zeros(ng, 1); p_la=zeros(ng,1); c_la=zeros(ng,1); fvec_la=zeros(ng,1);\npc_la_pred=zeros(ngt, 1); p_la_pred=zeros(ngt,1); c_la_pred=zeros(ngt,1); fvec_la_pred=zeros(ngt,1);\npc_la2=zeros(ng, 1); p_la2=zeros(ng,1); c_la2=zeros(ng,1); fvec_la2=zeros(ng,1);\npc_la_pred2=zeros(ngt, 1); p_la_pred2=zeros(ngt,1); c_la_pred2=zeros(ngt,1); fvec_la_pred2=zeros(ngt,1);\n\nfor i=1:length(ind)\n  figure; subplot(2,1,1);\n  [testi, testi2] = hist(f_mc(:,i),50);\n  width = testi2(2)-testi2(1);\n  area = sum(testi.*width);\n  testi = testi./area;\n  b = bar(testi2,testi);\n  h = findobj(gca,'Type','patch');\n  set(h,'FaceColor','w')\n  hold on;\n  [Eft_la, Varft_la] = gp_pred(gp,x,y,x);\n  start=tic;[pc_la(:,i), fvec_la(:,i), p_la(:,i), c_la(:,i)] = gp_predcm(gp,x,y,'ind', ind(i), 'fcorr', 'cm2'); tt_lacm2=toc(start); \n  start=tic;[pc_la2(:,i), fvec_la(:,i), p_la2(:,i), c_la2(:,i)] = gp_predcm(gp,x,y,'ind', ind(i), 'fcorr', 'fact'); tt_lafact=toc(start);\n  s = plot(fvec_la(:,i), p_la(:,i), '-k', fvec_la(:,i), norm_pdf(fvec_la(:,i), Eft_la(ind(i)), sqrt(Varft_la(ind(i)))), '-m', ...\n          fvec_la(:,i), pc_la2(:,i), '-r', fvec_la(:,i), pc_la(:,i), '-b');\n  set(s,'LineWidth',2)\n  set(get(get(b,'Annotation'),'LegendInformation'),...\n    'IconDisplayStyle','off');\n  legend('LA-L', 'LA-G', 'LA-FACT', 'LA-CM2');\n  title('Marginal corrections for probit likelihood (Laplace)');\n\n  % Predictive corrections\n  subplot(2,1,2);\n  [Eft_la_pred, Varft_la_pred] = gp_pred(gp,x,y,xt);\n  start=tic;[pc_la_pred(:,i), fvec_la_pred(:,i), p_la_pred(:,i), c_la_pred(:,i)] = gp_predcm(gp,x,y,xt, 'ind', ind(i), 'fcorr', 'cm2', 'ng', 30); tt_lacm22=toc(start);\n  start=tic;[pc_la_pred2(:,i), fvec_la_pred(:,i), p_la_pred2(:,i), c_la_pred2(:,i)] = gp_predcm(gp,x,y,xt, 'ind', ind(i), 'fcorr', 'fact','ng', 30); tt_lafact2=toc(start);\n  s = plot(fvec_la_pred(:,i), p_la_pred2(:,i), '-k', fvec_la_pred(:,i), pc_la_pred(:,i), '-r', fvec_la_pred(:,i), pc_la_pred2(:,i), '-b', fvec_la_pred(:,i), ptx_lap, '-c');\n  legend('LA-G', 'LA-CM2', 'LA-FACT', 'MCMC');\n  title('Predictive marginal corrections for probit likelihood (Laplace)');\nend\n\nfprintf('Time elapsed for marginal corrections with EP-FACT: %.1f s and for predictions %.1f s\\n', tt_epfact, tt_epfact2);\nfprintf('Time elapsed for marginal corrections with LA-CM2: %.1f s and for predictions %.1f s\\n', tt_lacm2, tt_lacm22);\nfprintf('Time elapsed for marginal corrections with LA-FACT: %.1f s and for predictions %.1f s\\n', tt_lafact, tt_lafact2);\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_improvemarginals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5519214826928036}}
{"text": "function x = sample_fs(xf, grid_sz)\n\n% Samples the Fourier series\n\nsz = [size(xf,1) size(xf,2)];\n\nif nargin < 2 || all(sz == grid_sz)\n    x = prod(sz) * cifft2(xf);\nelse\n    if any(grid_sz < sz)\n        error('The grid size must be larger than or equal to the signal size')\n    end\n    tot_pad = grid_sz - sz;\n    pad_sz = ceil(tot_pad/2);\n    xf_pad = padarray(xf, pad_sz);\n    if any(mod(tot_pad,2) == 1)\n        % Handle odd padding\n        xf_pad = xf_pad(1:end-mod(tot_pad(1),2), 1:end-mod(tot_pad(2),2), :, :);\n    end\n    x = prod(grid_sz) * cifft2(xf_pad);\nend\n\n\n", "meta": {"author": "martin-danelljan", "repo": "ECO", "sha": "27e8ae565cd63ec14bafcaad8b5b993bec8f3e69", "save_path": "github-repos/MATLAB/martin-danelljan-ECO", "path": "github-repos/MATLAB/martin-danelljan-ECO/ECO-27e8ae565cd63ec14bafcaad8b5b993bec8f3e69/implementation/fourier_tools/sample_fs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006919830720203, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5519214710256816}}
{"text": "function h = a2h(A);\n\n% H = a2h(ABCD)\n%\n% ABCD to Hybrid-H transformation\n% only for 2x2 matrices\n\nd = A(1,1)*A(2,2) - A(1,2)*A(2,1);\n\nwhile abs(A(2,2)) < 1e-8\n    A(2,2) = A(2,2)*(1+rand*1e-8);\nend;\n\nh(1,1) = A(1,2)/A(2,2);\nh(1,2) = d/A(2,2);\nh(2,1) = -1/A(2,2);\nh(2,2) = A(2,1)/A(2,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/6080-s-parameter-toolbox-+-z-y-h-g-abcd-t/sbox/a2h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.551893518480203}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Inverse dynamics for the 2dof planar robot\n%\n%   tau = inversedynamics_2dofplanar_fast(robot, q, qd, qdd, fe)\n%   \n%   Where robot stores the kinematic and dynamic parameters for this robot.\n%   q: joint positions.\n%   qd: joint velocities.\n%   qdd: joint accelerations.\n%   fe: vector of external forces. (unused)\n%\n%   This function just executes the inverse dynamic model for this robot.\n%   The equations to compute this dynamic model can be found in:\n%   \"ROBOT ANALYSIS. The mechanics of Serial and Parallel\n%        manipulators\". Lung Weng Tsai. John Wiley and Sons, inc. ISBN:\n%        0-471-32593-7. page 405.\n%\n%   Author: Arturo Gil Aparicio arturo.gil@umh.es\n%   Date: 08/03/2014\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 <http://www.gnu.org/licenses/>.\nfunction tau = inversedynamics_2dofplanar_fast(robot, q, qd, qdd, fe)\n\nfprintf('\\nComputing inverse dynamics for the %s robot', robot.name);\n\na = eval(robot.DH.a);\na1=a(1);\na2=a(2);\n\ngc=9.81;\n\nm1=robot.dynamics.masses(1);\nm2=robot.dynamics.masses(2);\n\n%express it as a general dynamic function\n%M*qdd + V + G = Q, where Q is a vector of generalized forces or moments\n% in this case, it is done just to represent the equations more clearly.\n% have a look at the directdynamics_2dofplanar_fast function to observe\n% this expression used to compute the direct dynamic model\n\n%M is a 2x2 manipulator inertia matrix\nM = [(m1*(1/3) + m2)*a1^2 + m2*a1*a2*cos(q(2)) + (1/3)*m2*a2^2 ... \n      (1/2)*m2*a1*a2*cos(q(2))+(1/3)*m2*a2^2 ;\n      (1/2)*m2*a1*a2*cos(q(2))+(1/3)*m2*a2^2  (1/3)*m2*a2^2];\n\nV=[-m2*a1*a2*sin(q(2))*(qd(1)*qd(2)+(1/2)*qd(2)^2);\n    (1/2)*m2*a1*a2*sin(q(2))*qd(1)^2];\n\nG=[gc*(((1/2)*m1+m2)*a1*cos(q(1)) + (1/2)*m2*a2*cos(q(1)+q(2)));\n    (1/2)*m2*gc*a2*cos(q(1)+q(2))];\n  \n\ntau = M*qdd + V + G;\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/demos/simulink/simulate_2DOFplanar_arm/inversedynamics_2dofplanar_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5518935166345268}}
{"text": "function [kg] = ug2kg(ug)\n% Convert mass from micrograms to kilograms. \n% Chad Greene 2012\nkg = ug*1E-9 ;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/ug2kg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504228, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5518935136101286}}
{"text": "function [ y, symm ] = cvx_s_symmetric_ut( m, n, symm )\n%CVX_S_SYMMETRIC_UT Symmetric matrices (upper triangle storage).\nif m ~= n,\n    cvx_throw( 'Symmetric structure requires square matrices.' );\nend\nsymm = false;\nnsq = n * n;\nntr = 0.5 * ( nsq + n );\nc   = 0 : n - 1;\nc   = c( ones( 1, n ), : );\nr   = c';\nmn  = min( r, c );\nmx  = max( r, c );\ny   = mn + 0.5 * mx .* ( mx + 1 ) + 1;\ny   = sparse( y( : ), 1 : nsq, 1, ntr, nsq );\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/structures/cvx_s_symmetric_ut.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.5518870853480166}}
{"text": "function value = i4_btest ( i4, pos )\n\n%*****************************************************************************80\n%\n%% I4_BTEST returns TRUE if the POS-th bit of an I4 is 1.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    23 January 2007\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    Military Standard 1753,\n%    FORTRAN, DoD Supplement To American National Standard X3.9-1978,\n%    9 November 1978.\n%\n%  Parameters:\n%\n%    Input, integer I4, the integer to be tested.\n%\n%    Input, integer POS, the bit position, between 0 and 31.\n%\n%    Output, logical VALUE, is TRUE if the POS-th bit of I4 is 1.\n%\n  i4_huge = 2147483647;\n\n  if ( pos < 0 )\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'I4_BTEST - Fatal error!\\n' );\n    fprintf ( 1, '  POS < 0.\\n' );\n    error ( 'I4_BTEST - Fatal error!' );\n\n  elseif ( pos < 31 )\n\n    if ( 0 <= i4 )\n      j = floor ( i4 );\n    else\n      j = floor ( ( i4_huge + i4 ) + 1 );\n    end\n\n    for k = 1 : pos\n      j = floor ( j / 2 );\n    end\n\n    if ( mod ( j, 2 ) == 0 )\n      value = 0;\n    else\n      value = 1;\n    end\n\n  elseif ( pos == 31 )\n\n    if ( i4 < 0 )\n      value = 1;\n    else\n      value = 0;\n    end\n\n  elseif ( 31 < pos )\n\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, 'I4_BTEST - Fatal error!\\n' );\n    fprintf ( 1, '  31 < POS.\\n' );\n    error ( 'I4_BTEST - 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/bvec/i4_btest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5518870684391001}}
{"text": "function [W] = winding_number(V,F,O,varargin)\n  % WINDING_NUMBER Compute the sum of solid angles of a triangle (tetrahedron)\n  % described by points (vectors) V\n  % \n  % [W] = winding_number(V,F,O)\n  % [W] = winding_number(V,F,O,'ParameterName',ParameterValue, ...)\n  %\n  % Inputs:\n  %  V  #V by 3 list of vertex positions\n  %  F  #F by 3 list of triangle indices\n  %  O  #O by 3 list of origin positions\n  %  Optional inputs:\n  %    'Hierarchical'  followed by true or false. Use hierarchical evaluation.\n  %      for mex: {true}, for matlab this is not supported \n  %    'Fast' followed by whether to use fast-winding-number {false}\n  %    'RayCast' followed by true or flase. Use ray cast version of approximate\n  %      evaluation: {false}\n  %    'TwoDRays' followed by true or false. Use 2d rays only.\n  %    'NumRays' followed by the number of rays to cast for each origin\n  % Outputs:\n  %  W  no by 1 list of winding numbers\n  %\n\n  warning('not mex...');\n  S = solid_angle(V,F,O);\n  W = sum(S,2);\n  switch size(F,2)\n  case 3\n    W = W/(2*pi);\n  case 4\n    W = W/(4*pi);\n  end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mex/winding_number.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.551835232630728}}
{"text": "function yhat=lfsmooth(varargin)\n%\n% a simple interface to locfit.\n% output is a vector of smoothed values, at each data point.\n% all locfit options, except evaluation structures, are valid.\n%\n% Example, to smooth a time series of observations,\n%\n% t = (1:100)';\n% y = 2*sin(t/10) + normrnd(0,1,100,1);\n% plot(t,y,'.');\n% hold on;\n% plot(t,lfsmooth(t,y,'nn',0.5));\n% hold off;\n%\n\n% Minimal input validation    \nif nargin < 1\n   error( 'At least one input argument required' );\nend\n\nfit = locfit(x,varargin{:},'module','simple');\nyhat = fit.fit_points.fitted_values;\n\nreturn;\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/locfit/m/lfsmooth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.551702894354957}}
{"text": "function pass = test_isPeriodicTech(pref)\n% Test isPeriodicTech().\n\nif ( nargin == 0 )\n    pref = chebfunpref; \nend\ntol = 1000*pref.cheb3Prefs.chebfun3eps;\n\nf = chebfun3v(@(x,y,z) x, @(x,y,z) y);\npass(1) = ~isPeriodicTech(f);\n\nf1 = chebfun3(@(x,y,z) cos(pi*x), 'trig');\nf2 = chebfun3(@(x,y,z) sin(pi*y), 'trig');\npass(2) = isPeriodicTech([f1; f2]);\npass(3) = isPeriodicTech([f1; f2; f2]);\nF = [f1; f2];\npass(4) = isPeriodicTech([F; f2]);\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/chebfun3v/test_isPeriodicTech.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5517028921860415}}
{"text": "function test_issue1400\n\n% WALLTIME 00:10:00\n% MEM 2gb\n% DEPENDENCY ft_selectdata\n\nntrial = 2;\n\ndata = [];\ndata.label = {'1'};\nfor i=1:ntrial\n  t = (1:1000)/1000 + i; % time vectors are unaligned to show the error\n  s = sin(i*2*pi*t); % make a sine with 1, 2, 3, ... Hz\n  data.time{i} = t;\n  data.trial{i}(1,:) = s;  % insert it in the first channel\nend\n\ndisp('Demonstrate averaging over time:')\ndisp('Averaging trials 1, 2')\ncfg = [];\ncfg.trials = [1,2];\ncfg.avgoverrpt = 'yes';\ncfg.keeprpt = 'no';\ncfg.verbosity = 'off';\ntmpdata = ft_selectdata(cfg, data);\n\n% disp(['trialinfo(1, 1) = ', num2str(tmpdata.trialinfo(1,1))])\ndisp(['trial 1 time = ', regexprep(num2str(data.time{1}(1:5)),'\\s+',', ')])\ndisp(['trial 2 time = ', regexprep(num2str(data.time{2}(1:5)),'\\s+',', ')])\ndisp(['average time = ', regexprep(num2str(tmpdata.time{1}(1:5)),'\\s+',', ')])\n\n% add some trialinfo which is a mix of numbers and letters\ndisp('Demonstrate averaging over trialinfo:')\ndata.trialinfo = table([1;2],{'a'; 'b'});\ndisp(['trialinfo class is: ', class(data.trialinfo)])\n\n% This would return an error in ft_selectdata, because it \n% averaging the table prior to discarding the averaged trialinfo\ndisp('Averaging trials 1, 2')\ncfg = [];\ncfg.trials = [1,2];\ncfg.avgoverrpt = 'yes';\ncfg.keeprpt = 'no';\ncfg.verbosity = 'off';\ntmpdata = ft_selectdata(cfg, data);\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_issue1400.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370421, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.551702889463948}}
{"text": "function a = tanh(a)\n%TANH         Gradient hyperbolic tangent tanh(a)\n%\n\n% written  10/16/98     S.M. Rump\n% modified 10/14/00     S.M. Rump  use Tony's trick\n% modified 04/04/04     S.M. Rump  set round to nearest for safety\n%                                    iaccelaration for sparse input\n% modified 04/06/05     S.M. Rump  rounding unchanged\n% modified 09/28/08     S.M. Rump  check for rounding to nearest improved\n% modified 10/08/08     S.M. Rump  improved sparse multiplication: not using intval data type\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  e = 1e-30;\n  if 1+e==1-e                           % fast check for rounding to nearest\n    rndold = 0;\n  else\n    rndold = getround;\n    setround(0)\n  end\n\n  N = getappdata(0,'INTLAB_GRADIENT_NUMVAR');\n\n  % use full(a.x(:)): cures Matlab V6.0 bug\n  % a=7; i=[1 1]; x=a(i), b=sparse(a); y=b(i)  yields row vector x but column vector y\n  % ax is full anyway\n  ax = 1 ./ sqr(cosh(full(a.x(:))));\n  a.x = tanh(a.x);\n  if issparse(a.dx)\n    sizeax = size(a.dx,1);\n    [ia,ja,sa] = find(a.dx);\n    if isa(a.x,'intval')\n      adx = times(ax(ia),sa,0);\n      if adx.complex\n        a.dx = intval( sparse(ia,ja,adx.mid,sizeax,N) , sparse(ia,ja,adx.rad,sizeax,N) , 'midrad' );\n      else\n        a.dx = intval( sparse(ia,ja,adx.inf,sizeax,N) , sparse(ia,ja,adx.sup,sizeax,N) , 'infsup' );\n      end\n    else\n      a.dx = sparse(ia,ja,ax(ia).*sa,sizeax,N);\n    end\n  else\n    a.dx = a.dx .* ax(:,ones(1,N));\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/gradient/@gradient/tanh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5517028872950327}}
{"text": "    % design_matrix: data class for creating a design matrix to be used with a linear model including fmri data.\n    %\n    %\n    % Inputs:\n    % ---------------------------------------------------------------------\n    % dat                       : M x N numeric matrix containing Observations and Variables\n    %                           If dat is a file name then will try to\n    %                           import data into design_matrix object.\n    %                           Make sure there is only text in header and\n    %                           not anywhere else.\n    %\n    % varname                   : Cell array containing variable names.  Must\n    %                             match number of column in data matrix\n    %\n    % Examples:\n    % ---------------------------------------------------------------------\n    % DM = design_matrix([ones(10,1), (1:10)', (1:10).^2'],{'Intercept','X','X2'})\n    %\n    % Original version: Copyright Luke Chang 2/2014\n    \n    % Notes:\n    % Need to add these Methods:\n    % -create regressor from stim times\n    % -pca\n\nclassdef design_matrix < handle\n    properties\n        dat = [];\n        varname = {};\n        fname = '';\n    end\n    \n    methods\n        function obj = design_matrix(dat, varname)\n            class constructor % Initialize instance of design_matrix\n            \n            if(nargin > 1)\n                try\n                    if(~ismatrix(dat) || ~isnumeric(dat) || iscell(dat))\n                        error('Make sure input data is a matrix')\n                    end\n                    if(length(varname) ~= size(dat,2) || ~iscell(varname));\n                        error('Make sure the number of variable names corresponds to number of data columns.')\n                    end\n                    obj.dat = dat;\n                    obj.varname = varname;\n                catch err\n                    error('Make sure input variable names are in a cell array with length equal to number of data columns and data is a matrix.')\n                end\n                obj.varname = varname;\n                \n            elseif(nargin > 0)\n                \n                %import data into design_matrix if dat is a filename\n                if ischar(dat)\n                    ftest = exist(dat,'file'); %check if valid file\n                    if ftest == 2\n                        data = importdata(dat);\n                        obj.dat = data.data;\n                        obj.varname = data.colheaders;\n                    end\n                    \n                elseif(~ismatrix(dat) || ~isnumeric(dat) || iscell(dat))\n                    error('Make sure input data is a matrix')\n                else\n                    \n                    obj.dat = dat;\n                end\n                \n            else % if nothing initialize empty object\n                return\n            end\n        end\n        \n        function names(obj)\n            % names(obj)\n            %\n            % List variable names for each regressor\n            display(obj.varname)\n        end\n        \n        function dim = size(obj, varargin)\n            % dim = size(obj, varargin)\n            %\n            % Return dimensions of design matrix\n            % Optional Input: Indicate Dimension(row = 1 or column = 2)\n            \n            if nargin > 1\n                dim = size(obj.dat, varargin{1});\n            else\n                dim = size(obj.dat);\n            end\n        end\n        \n        function plot(obj)\n            % plot(obj)\n            %\n            % Plot design matrix\n            imagesc(obj.dat)\n        end\n        \n        function save(obj, fname)\n            % save(obj, fname)\n            %\n            % Save Design Matrix to file\n            \n            save(fname, obj)\n        end\n        \n        function obj = addvariable(obj, x, varargin)\n            % obj = addvariable(obj, x, varargin)\n            %\n            % Add regressor to design matrix\n            %\n            % optional inputs\n            % -------------------------------------------------------------------\n            % 'Name'        : 'Name' followed by Variable name\n            %                  Default is 'newVx'\n            %\n            % 'Order'       : 'Order' followed by where to insert new data columns location\n            %                  Default is end\n            \n            % Check Inputs\n            if size(x,1) ~= size(obj,1)\n                error('Make sure new variable column is the same length as design matrix')\n            end\n            \n            % Defaults\n            for i = 1:size(x,2)\n                newname{i} = ['newV' num2str(i)];\n            end\n            isnewname = 0;\n            varorder = size(obj,2); %add to end\n            \n            % Parse inputs\n            % -------------------------------------------------------------------\n            for varg = 1:length(varargin)\n                if ischar(varargin{varg})\n                    % reserved keywords\n                    if strcmpi('name',varargin{varg})\n                        if length(varargin{varg + 1}) == size(x,2)\n                            newname = varargin{varg + 1};\n                            isnewname = 1;\n                        else\n                            error('Make sure ''Name'' is follwed by a valid variable name')\n                        end\n                        varargin{varg} = {}; varargin{varg + 1} = {};\n                    end\n                    \n                    if strcmpi('order',varargin{varg})\n                        if isnumeric(varargin{varg + 1}) && varargin{varg + 1} <= size(obj,2)\n                            varorder = varargin{varg + 1};\n                        else\n                            error('Make sure ''Order'' is follwed by a valid column number')\n                        end\n                        varargin{varg} = {}; varargin{varg + 1} = {};\n                    end\n                end\n            end\n            % -------------------------------------------------------------------\n            \n            % Update Name vector if not empty\n            if ~isempty(obj.varname)\n                if varorder == 1 %begin\n                    obj.varname = [newname, obj.varname];\n                elseif varorder == size(obj,2) %end\n                    obj.varname = [obj.varname, newname];\n                else %Somewhere inbetween\n                    obj.varname = [obj.varname(1:varorder), newname, obj.varname(varorder + 1 : end)];\n                end\n            end\n            \n            % Add new variables to design Matrix\n            if varorder == 1 %begin\n                obj.dat = [x, obj.dat];\n            elseif varorder == size(obj,2) %end\n                obj.dat = [obj.dat, x];\n            else %Somewhere inbetween\n                obj.dat = [obj.dat(:,1:varorder), x, obj.dat(:,varorder + 1 : end)];\n            end\n        end\n        \n        function obj = zscore(obj, varargin)\n            % obj = zscore(obj, varargin)\n            %\n            % Standardize columns of design matrix\n            %\n            % optional inputs\n            % -------------------------------------------------------------------\n            % 'center'        : Only remove mean, don't standardize\n            \n            % Defaults\n            center = 0; %Only remove mean\n            \n            % optional inputs\n            % -------------------------------------------------------------------\n            for varg = 1:length(varargin)\n                if ischar(varargin{varg})\n                    % reserved keywords\n                    if strcmpi('center',varargin{varg})\n                        center=1;\n                        varargin{varg} = {};\n                    end\n                end\n            end\n            % -------------------------------------------------------------------\n            \n            if center\n                obj.dat = obj.dat - repmat(mean(obj.dat),size(obj,1),1);\n            else\n                obj.dat = zscore(obj.dat);\n            end\n        end\n        \n        function obj = removevariable(obj, x)\n            % obj = removevariable(obj, x)\n            %\n            % Remove columns from design_matrix\n            %\n            % Inputs\n            % -------------------------------------------------------------------\n            % x             : Input vector of columns to remove\n            \n            obj.dat(:,x) = [];\n            obj.varname(x) = [];\n        end\n        \n        function obj = addintercept(obj)\n            % obj = addintercept(obj)\n            %\n            % Add intercept to design matrix\n            \n            %Check if Intercept exists\n            if sum(strcmpi(obj.varname,'intercept')) > 0\n                error('Intercept Name already included in obj.varname')\n            end\n            \n            %Check if any variable only includes ones\n            for i = 1:size(obj,2)\n                if sum(obj.dat(:,i)==1) == size(obj,1)\n                    error('There is already a column of ones that resembles an intercept')\n                end\n            end\n            \n            obj.dat = [obj.dat, ones(size(obj,1),1)];\n            obj.varname = [obj.varname, 'Intercept'];\n        end\n        \n        function obj = removeintercept(obj)\n            %  obj = removeintercept(obj)\n            %\n            % Remove intercept from design matrix\n            \n            %Check if any variable only includes ones or if intercept is in varname\n            for i = 1:size(obj,2)\n                whereint(i) = sum(obj.dat(:,i)==1) == size(obj,1);\n            end\n            if sum(whereint) == 0\n                error('There does not appear to be any column of ones that resembles an intercept')\n            elseif sum(strcmpi('intercept',obj.varname)) == 0\n                error('Intercept Name is not included in obj.varname')\n            end\n            \n            % now remove intercept\n            obj.dat(:,whereint) = [];\n            obj.varname(whereint) = [];\n        end\n        \n        function vif = vif(obj, varargin)\n            % vif = vif(obj, varargin)\n            %\n            % Check for multicollinearity by getting variance inflation factors\n            %\n            % See original getvif.m in canlab repository - OptimizeDesign11/core_functions/getvif.m\n            %\n            % optional inputs\n            % -------------------------------------------------------------------\n            % 'nointercept'       : Remove intercept (turned off by default)\n            \n            % Defaults\n            noint = 0;\n            if strcmpi('nointercept',varargin)\n                noint = 1;\n            end\n            \n            %Remove intercept if asked\n            if noint\n                obj = removeintercept(obj);\n            end\n            \n            %Calculate VIF\n            for i = 1:size(obj.dat,2)\n                X = obj.dat;\n                y = X(:,i);\n                X(:,i) = [];\n                b = X\\y;\n                fits = X * b;\n                rsquare = var(fits) / var(y);\n                \n                if rsquare == 1,rsquare = .9999999;end\n                \n                vif(i) = 1 / (1 - rsquare);\n            end\n        end\n        \n        function r = corr(obj)\n            % Calculate pairwise correlation of regressors in design_matrix\n            \n            r = corr(obj.dat);\n        end\n        \n        function obj = normalizedrank(obj, varargin)\n            % obj = normalizedrank(obj, varargin)\n            %\n            % Rank each regressor and normalize between [0,1]\n            %\n            % See normalizedrank.m for optional inputs\n            \n            obj.dat = normalizedrank(obj.dat, varargin);\n        end\n        \n        function obj = conv_hrf(obj, varargin)\n            % obj = conv_hrf(obj, varargin)\n            %\n            % Convolve each regressors with hemodynamic response function\n            % Uses spm_hrf.m\n            %\n            % optional inputs\n            % -------------------------------------------------------------------\n            % 'tr'           : Input TR to use for creating HRF\n            %                  (e.g., 'tr', 3)\n            %\n            % 'select'       : Select Input vector of regressors to convolve\n            %                  (e.g., 'select', [2,4])\n            %\n            % 'custom_hrf'   : Use custom HRF (e.g., 'custom_hrf', [1.00, 0.59, 0.39, 0.27]\n            \n            % Defaults\n            include = (1:size(obj,2)); %Convolve entire Design Matrix by default\n            tr = 2;\n            \n            % Check if spm_hrf is on path\n            checkspm =  which('spm_hrf.m');\n            if isempty(checkspm), error('Make sure spm is in matlab path'); end\n            \n            % Parse inputs\n            % -------------------------------------------------------------------\n            for varg = 1:length(varargin)\n                if ischar(varargin{varg})\n                    % reserved keywords\n                    if strcmpi('tr',varargin{varg})\n                        if isnumeric(varargin{varg + 1})\n                            tr = varargin{varg + 1};\n                            crf = spm_hrf(tr);\n                        else\n                            error('Make sure ''tr'' is followed by valid number')\n                        end\n                        varargin{varg} = {}; varargin{varg + 1} = {};\n                    end\n                    \n                    if strcmpi('select',varargin{varg})\n                        if isnumeric(varargin{varg + 1}) && all(varargin{varg + 1} <= size(obj,2))\n                            include = varargin{varg + 1};\n                        else\n                            error('Make sure ''select'' is followed by a valid column number')\n                        end\n                        varargin{varg} = {}; varargin{varg + 1} = {};\n                    end\n                    \n                    if strcmpi('custom_hrf',varargin{varg})\n                        if isnumeric(varargin{varg + 1}) && all(varargin{varg + 1} <= size(obj,2))\n                            crf = varargin{varg + 1};\n                        else\n                            error('Make sure ''custom_hrf'' is followed by a vector of a canonical response function')\n                        end\n                        varargin{varg} = {}; varargin{varg + 1} = {};\n                    end\n                end\n            end\n            % -------------------------------------------------------------------\n            \n            %Convolution of task\n            for i = 1:length(include)\n                convdat = conv(obj.dat(:,include(i)),crf);\n                \n                %Cut off extra data from convolution\n                obj.dat(:,include(i)) = convdat(1:size(obj,1));\n            end\n        end\n        \n        function obj = hpfilter(obj, varargin)\n            % obj = hpfilter(obj, varargin)\n            %\n            % Add High pass filter design matrix using spm's discrete\n            % cosine Transform (spm_filter.m)\n            %\n            % optional inputs\n            % -------------------------------------------------------------------\n            % 'tr'           : Input TR to use for creating HRF\n            %                  (e.g., 'tr', 3) Default = 2;\n            %\n            % 'duration'     : Duration of high pass filter in seconds\n            %                  (e.g., 'duration', 100) Default = 180;\n            \n            % Defaults\n            tr = 2;\n            filterlength = 180;\n            \n            % Check if spm_hrf is on path\n            checkspm =  which('spm_filter.m');\n            if isempty(checkspm), error('Make sure spm is in matlab path'); end\n            \n            % Parse inputs\n            % -------------------------------------------------------------------\n            for varg = 1:length(varargin)\n                if ischar(varargin{varg})\n                    % reserved keywords\n                    if strcmpi('tr',varargin{varg})\n                        if isnumeric(varargin{varg + 1})\n                            tr = varargin{varg + 1};\n                        else\n                            error('Make sure ''tr'' is followed by valid number')\n                        end\n                        varargin{varg} = {}; varargin{varg + 1} = {};\n                    end\n                    if strcmpi('duration',varargin{varg})\n                        if isnumeric(varargin{varg + 1})\n                            filterlength = varargin{varg + 1};\n                        else\n                            error('Make sure ''duration'' is followed by valid number')\n                        end\n                        varargin{varg} = {}; varargin{varg + 1} = {};\n                    end\n                end\n            end\n            % -------------------------------------------------------------------\n            \n            %create high pass filter\n            K.RT = tr;\n            K.row = 1:size(obj,1);\n            K.HParam = filterlength;\n            nK = spm_filter(K);\n            if isempty(nK.X0), error('Check if filter duration is too long'); end\n            \n            %Add filter to design_matrix\n            obj.dat = [obj.dat, nK.X0];\n            \n            %Add variable names\n            for i = 1:size(nK.X0,2)\n                filtname{i} = ['hpfilter' num2str(i)];\n            end\n            obj.varname = [obj.varname, filtname];\n        end\n        \n        function stats = regress(obj, Y, varargin)\n            % [B,BINT,R,RINT,STATS] = regress(obj, Y)\n            %\n            % Regress design matrix on vector Y\n            % Uses matlab's regress function\n            %\n            % optional inputs\n            % -------------------------------------------------------------------\n            % 'robust'           : use robust regression\n            \n            % Defaults\n            doRobust = 0;\n            for i = 1:length(varargin)\n                if strcmpi(varargin(i),'robust')\n                    doRobust = 1;\n                    find_robust = exist('robustfit');\n                    if find_robust ~= 2\n                        error('Make sure robustfit is on your path, requires the stats toolbox')\n                    end\n                    varargin(i) = [];\n                end\n            end\n            \n            if ~doRobust\n                [stats.B, stats.BINT, stats.R, stats.RINT, stats.STATS] = regress(Y, obj.dat);\n            else\n                [stats.B, stats.STATS] = robustfit(obj.dat, Y,[],[],'off');\n            end\n        end\n        \n        function obj = onsettimes(obj, onset, names, tr, timing )\n            % obj = onsettimes(obj, onset, names, tr, timing )\n            %\n            %Create stimulus regressor from onset times\n            %\n            % Inputs\n            % -------------------------------------------------------------------\n            % onset        : Input cell array of onset times for each\n            %                   regressor in FSL's 3 column format (e.g., onset in sec, duration in sec, weight).\n            %\n            % names        : Cell array of variable names corresponding\n            %                to each onset cell (e.g., {'BlueOn','RedOn'})\n            %\n            % tr           : Repetition time (e.g., 2)\n            %\n            % timing       : Timing converstion from onset array to design matrix\n            %                  (e.g., 'sec2tr','tr2sec','sec2sec',or\n            %                  'tr2tr'). Need to know which format each\n            %                  array is in.\n            \n            %Convert Onset Times Into Boxcar Regressors\n            r = zeros(size(obj,1),length(onset));\n            for i = 1:length(onset)\n                for j = 1:size(onset{i},1)\n                    switch timing\n                        case 'sec2tr'\n                            if floor(onset{i}(j,1)/tr) == 0\n                                r(1 : 1 + ceil(onset{i}(j,2)), i) = onset{i}(j,3);\n                            else\n                                r(floor(onset{i}(j,1) / tr) : floor(onset{i}(j,1) / tr) + ceil(onset{i}(j,2) / tr) - 1, i) = onset{i}(j,3);\n                            end\n                        case 'tr2sec'\n                            r(floor(onset{i}(j,1) * tr) : floor(onset{i}(j,1) * tr) + ceil(onset{i}(j,2) * tr) - 1, i) = onset{i}(j,3);\n                        case {'sec2sec', 'tr2tr'}\n                            r(floor(onset{i}(j,1)) : floor(onset{i}(j,1)) + ceil(onset{i}(j,2)) - 1, i) = onset{i}(j,3);\n                    end\n                end\n            end\n            obj.dat = [obj.dat, r];\n            \n            %Add Variable names\n            obj.varname = [obj.varname, names];\n        end\n        \n        function obj = write(obj, varargin)\n            % obj = write(obj, varargin)\n            %\n            % -------------------------------------------------------------------\n            % write design_matrix object into csv file.  Will use obj.fname\n            % or can specify optional name\n            %\n            % -------------------------------------------------------------------\n            % Optional Inputs\n            % -------------------------------------------------------------------\n            % fname        : path and file name of csv file.\n            % -------------------------------------------------------------------\n            \n            \n            if nargin > 1 %use supplied file name\n                if ischar(varargin{1})\n                    hdr = sprintf('%s,',obj.varname{:});\n                    hdr(end) = '';\n                    dlmwrite(varargin{1}, hdr,'') %Write Header 1st\n                    dlmwrite(varargin{1}, obj.dat, 'delimiter',',','-append','precision',10) %Append data\n                end\n                \n            elseif ~isempty(obj.fname) %use obj.fname\n                hdr = sprintf('%s,',obj.varname{:});\n                hdr(end) = '';\n                dlmwrite(obj.fname, hdr, ''); %Write Header 1st\n                dlmwrite(obj.fname, obj.dat, 'delimiter',',','-append','precision',10) %Append data\n            else\n                error('Please supply valid file name with path to save.')\n            end\n            \n        end\n        \n        function c = horzcat(varargin)\n            % function c = horzcat(varargin)\n            % -------------------------------------------------------------------\n            % Implements the horzcat ([a b]) operator on design_matrix objects across variables.\n            % Requires that each object has an equal number of rows\n            % -------------------------------------------------------------------\n            % Examples:\n            % c = [dm1 dm2];\n            % -------------------------------------------------------------------\n            \n            %check if number of rows is the same\n                        %check if varnames are the same\n            nrow = [];\n            for i = 1:nargin\n                nrow(i) = size(varargin{i},1);\n            end\n            for i = 1:nargin\n                for j = 1:nargin\n                    if nrow(i)~=nrow(j)\n                        error('objects have a different number of rows')\n                    end\n                end\n            end\n            \n            dat = [];\n            varname = [];\n            for i = 1:nargin\n                    %Check if design_matrix object\n                if ~isa(varargin{i}, 'design_matrix')\n                    error('Input Data is not an design_matrix object')\n                end\n                \n                dat = [dat, varargin{i}.dat];\n                varname = [varname, varargin{i}.varname];\n            end\n            \n            c = varargin{1};\n            c.dat = dat;\n            c.varname = varname;\n        end\n        \n        function c = vertcat(varargin)\n            % function c = vertcat(varargin)\n            % -------------------------------------------------------------------\n            % Implements the vertcat ([a b]) operator on design_matrix objects across rows.\n            % Requires that each object has an equal number of columns and\n            % that each varname is identical\n            % -------------------------------------------------------------------\n            % Examples:\n            % c = [dm1; dm2];\n            % -------------------------------------------------------------------\n            \n            %check if varnames are the same\n            varname = {};\n            for i = 1:nargin\n                varname{i} = varargin{i}.varname;\n            end\n            for i = 1:nargin\n                for j = 1:nargin\n                    if ~strcmpi(varname{i},varname{j})\n                        error('variable names do not match')\n                    end\n                end\n            end\n            dat = [];\n            for i = 1:nargin\n                %Check if design_matrix object\n                if ~isa(varargin{i}, 'design_matrix')\n                    error('Input Data is not an design_matrix object')\n                end\n                dat = [dat; varargin{i}.dat];\n            end\n            \n            c = varargin{1};\n            c.dat = dat;\n        end\n        \n    end %methods\nend %class\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Model_building_tools/design_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5516832250416137}}
{"text": "function w = quadwts(n)\n%QUADWTS   Quadrature weights for Chebyshev points of 2nd kind.\n%   QUADWTS(N) returns the N weights for Clenshaw-Curtis quadrature on 2nd-kind\n%   Chebyshev points.\n%\n% See also CHEBPTS, BARYWTS.\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% We use a variant of Waldvogel's algorithm [1], due to Nick Hale. (See below)\n% We note this is similar to Greg Von Winkel's approach, which can be found on\n% the MathWorks File Exchange.\n%\n% Let $f(x) = \\sum_{k=0}^nc_kT_k(x)$, then\\vspace*{-3pt} }\n%   I(f) = v.'*c\n% where\n%   v = \\int_{-1}^1T_k(x)dx = { 2/(1-k^2) : k even\n%                             { 0         : k odd\n%     = v'*inv(TT)*f(x) where TT_{j,k} = T_k(x_j)\n%     = (inv(TT)'*v)'*f(x)\n% Therefore\n%   I(f) = w.'f(x) => w = inv(TT).'*v;\n% Here inv(TT).' = inv(TT) is an inverse discrete cosine transform of Type I.\n%\n% Furthermore, since odd entries in v are zero, can compute via FFT without\n% doubling up from N to 2N (though we still need to double up from N/2 to N to \n% facilitate the use of ifft).\n%\n% References:\n%   [1] Joerg Waldvogel, \"Fast construction of the Fejer and Clenshaw-Curtis\n%       quadrature rules\", BIT Numerical Mathematics 46 (2006), pp 195-202.\n%   [2] Greg von Winckel, \"Fast Clenshaw-Curtis Quadrature\", \n%       http://www.mathworks.com/matlabcentral/fileexchange/6911, (2005)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ( n == 0 )                      % Special case (no points!)\n    w = [];\nelseif ( n == 1 )                  % Special case (single point)\n    w = 2;\nelse                               % General case\n    c = 2./[1, 1-(2:2:(n-1)).^2];  % Exact integrals of T_k (even)\n    c = [c, c(floor(n/2):-1:2)];   % Mirror for DCT via FFT\n    w = ifft(c);                   % Interior weights\n    w([1,n]) = w(1)/2;             % Boundary weights\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/quadwts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.5516832203102963}}
{"text": "function pass = test_mean(pref)\n\nif ( nargin == 0 )\n    pref = chebfunpref();\nend\n\n%% Two arguments:\nf = chebfun(@sin, pref);\ng = chebfun(@cos, pref);\nh = chebfun(@(x) .5*(sin(x) + cos(x)), pref);\npass(1) = normest(mean(f, g) - h) < 10*eps;\n\nf = chebfun(@(x) [sin(x), cos(x)], pref);\ng = chebfun(@(x) [cos(x), 1i*exp(x)], pref);\nh = .5*(f+g);\npass(2) = normest(mean(f, g) - h) < 10*eps;\n\n%% One argument:\nf = chebfun(@sin, pref);\npass(3) = abs(mean(f)) < eps;\npass(4) = abs(mean(f.')) < eps;\n\nf = chebfun(@(x) [sin(x), x], pref);\npass(5) = norm(mean(f), inf) < eps;\npass(6) = norm(mean(f.'), inf) < eps;\n\nf = chebfun(@(x) [sin(x), x], [0, 6], pref);\npass(7) = norm(mean(f) - sum(f)/6, inf) < vscale(f)*eps;\npass(8) = norm(mean(f.') - sum(f).'/6, inf) < vscale(f)*eps;\n\n%% singular function: a finite case\n\n% define the domain:\ndom = [-2 7];\n\nop = @(x) sin(100*x)./((x-dom(1)).^0.5.*(x-dom(2)).^0.5);\nf = chebfun(op, dom, 'exps', [-0.5 -0.5], 'splitting', 'on');\nm = mean(f);\nm_exact = -0.01273522016443600i;\npass(9) = abs(m - m_exact) < 1e5*eps*abs(m_exact);\n\n\n%% singular function: an infinite case\n\n% define the domain:\ndom = [-2 7];\n\nop = @(x) sin(100*x)./((x-dom(1)).^1.5.*(dom(2)-x).^0.5);\nf = chebfun(op, dom, 'exps', [-1.5 -0.5], 'splitting', 'on');\nm = mean(f);\npass(10) = ( isinf(m) );\n\n%% singular function: a NaN case\n\n% define the domain:\ndom = [-2 7];\n\nop = @(x) sin(98*x)./((x-dom(1)).^1.5.*(dom(2)-x).^1.5);\nf = chebfun(op, dom, 'exps', [-1.5 -1.5], 'splitting', 'on');\nm = mean(f);\npass(11) = ( isnan(m) );\n\n%% Test for functions defined on unbounded domain:\n\n% Functions on [-inf inf]:\n\n% Set the domain:\ndom = [-Inf 2 Inf];\n\nop1 = @(x) x.^2.*exp(-x.^2);\nop2 = @(x) (1-exp(-x.^2))./x.^2 + 2;\nf = chebfun({op1 op2}, dom);\nM = mean(f);\npass(12) = isnan(M);\n\n% Function defined on [0 Inf]:\n\n% Specify the domain: \ndom = [0 Inf];\n\nop = @(x) 0.75+sin(10*x)./exp(x);\nf = chebfun(op, dom, 'splitting', 'on');\nM = mean(f);\npass(13) = abs(M - 0.75) < 1e2*eps*vscale(f);\n\nx = chebfun('x');\nf = mean([x 3*x], 2);\npass(14) = norm(f-2*x) < 1e2*eps;\n\nf = mean([x 3*x], 1);\npass(15) = norm( f - mean([x 3*x]) ) == 0;\n\npass(16) = (norm(mean(x,1) - mean(x.',2)) == 0);\n\npass(17) = (norm(mean(x') - 0) < 1e2*eps);\n\npass(18) = (norm(mean(x',1) - x') == 0);\n\nend\n\nfunction out = normest(f, dom)\n\n% Generate a few random points to use as test values.\nseedRNG(6178);\nif ( nargin == 1 )\n    x = 2 * rand(100, 1) - 1;\nelse\n    x = sum(dom) * rand(10, 1) - dom(1);\nend\n\nout = norm(feval(f, x), inf);\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun/test_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.551683210847661}}
{"text": "function s=minmod(a,b)\n% The minmod limiter\ns=0.5*(sign(a)+sign(b)).*min(abs(a),abs(b));", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/OperatorSplitting/AppendixA/minmod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5516832081666305}}
{"text": "%DEMO_NEURALNETCOV  Demonstration of Gaussian process with a neural\n%                   network covariance function\n%                    \n%  Description\n%    Infinite neural network solutions in 2D and 1D regression\n%    problems with a comparison to Gaussian process solution given\n%    by squared exponential covariance function. The noisy\n%    observations y are assumed to satisfy\n%\n%         y = f + e,    where e ~ N(0, s^2)\n%\n%    where f is an unknown underlying function. A zero mean\n%    Gaussian process prior is assumed for f\n%\n%         f ~ N(0, K),\n%\n%    where K is the covariance matrix whose elements are given by\n%    neural network (or squared exponential) covariance function. A\n%    prior is assumed for parameters of the covariance functions,\n%    and the inference is done with a MAP estimate for parameter\n%    values.\n%\n%    For more detailed discussion of infinite neural networks, see\n%    e.g.\n%\n%      Neal, R. M. (1996). Bayesian Learning for Neural Networks. \n%      Springer-Verlag.\n%\n%      Williams, C. K. I. (1996). Computing with infinite networks. \n%      In Advances in Neural Information Processing Systems 9. MIT\n%      Press, Cambridge, MA.\n%\n%\n%  See also DEMO_REGRESSION1\n\n% Copyright (c) 2010 Jaakko Riihim\ufffdki, 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% 2D REGRESSION DATA\n\n% create 2D example data\nx=rand(300,2)*2-1;\ny=zeros(size(x,1),1); y(x(:,1)>0&x(:,2)>0)=1;\ny=y+0.1*randn(size(y));\n\n[n, nin] = size(x);\n\n% --- Construct the model ---\n\n% squared exponential covariance function\ngpcf1 = gpcf_sexp('lengthScale', ones(1,nin), 'magnSigma2', 1);\n% neural network covariance function\ngpcf2 = gpcf_neuralnetwork('weightSigma2', ones(1,nin), 'biasSigma2', 1);\n% Gaussian noise structures\nlik = lik_gaussian('sigma2', 0.2^2);\n\n% a prior structure for GP parameters\npt = prior_t('s2', 4);\ngpcf1 = gpcf_sexp(gpcf1, 'lengthScale_prior', pt, 'magnSigma2_prior', pt);\ngpcf2 = gpcf_neuralnetwork(gpcf2, 'weightSigma2_prior', pt, 'biasSigma2_prior', pt);\n\ngp = gp_set('lik', lik, 'cf', gpcf1);\ngp2 = gp_set('lik', lik, 'cf', gpcf2);\n\n% --- MAP estimate using scaled conjugate gradient algorithm ---\n%     (see scg for more details)\n\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);\ngp2=gp_optim(gp2,x,y,'opt',opt);\n\n% create points where predictions are made\n[xt1,xt2]=meshgrid(-1.5:0.05:1.5,-1.5:0.05:1.5);\nxt=[xt1(:) xt2(:)];\n% compute the predictions\n[Eft_map, Varft_map] = gp_pred(gp, x, y, xt);\n[Eft_map2, Varft_map2] = gp_pred(gp2, x, y, xt);\n\n% Plot the predictions and data\nfigure, set(gcf, 'color', 'w')\nmesh(xt1, xt2, reshape(Eft_map,size(xt1,1),size(xt1,2)));\nhold on\nplot3(x(:,1), x(:,2), y, '*')\naxis on;\ntitle('GP (squared exponential) predictions and the data points');\n\nfigure, set(gcf, 'color', 'w')\nmesh(xt1, xt2, reshape(Eft_map2,size(xt1,1),size(xt1,2)));\nhold on\nplot3(x(:,1), x(:,2), y, '*')\naxis on;\ntitle('GP (neural network) predictions and the data points');\n\n% 1D REGRESSION DATA\n\n% create a 1D toy data\nx=rand(100,1)*4-2;\ny=norm_pdf(4*x)+0.05*randn(size(x));\n[n, nin] = size(x);\n\ngpcf1 = gpcf_sexp('lengthScale', ones(1,nin), 'magnSigma2', 1);\ngpcf2 = gpcf_neuralnetwork('weightSigma2', ones(1,nin), 'biasSigma2', 1);\n\ngpcf1 = gpcf_sexp(gpcf1, 'lengthScale_prior', pt, 'magnSigma2_prior', pt);\ngpcf2 = gpcf_neuralnetwork(gpcf2, 'weightSigma2_prior', pt, 'biasSigma2_prior', pt);\nlik = lik_gaussian();\n\ngp = gp_set('lik', lik, 'cf', gpcf1);\ngp2 = gp_set('lik', lik, 'cf', gpcf2);\n\n% --- MAP estimate using scaled conjugate gradient algorithm ---\n%     (see fminscg for more details)\n\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);\ngp2=gp_optim(gp2,x,y,'opt',opt);\n\n% create points where predictions are made\nxgrid=linspace(min(x)-1.5,max(x)+1.5,200)';\n[Eft_map, Varft_map, lpyt_map, Eyt_map, Varyt_map] = gp_pred(gp, x, y, xgrid, 'yt', ones(200,1));\n[Eft_map2, Varft_map2, lpyt_map2, Eyt_map2, Varyt_map2] = gp_pred(gp2, x, y, xgrid, 'yt', ones(200,1));\n\n% Plot the predictions and data\ncolor1=ones(1,3)*0.8; color2=ones(1,3)*0.5;\nfigure, set(gcf, 'color', 'w'), hold on\nh1=fill([xgrid' fliplr(xgrid')], [(Eyt_map+1.96*sqrt(Varyt_map))' fliplr((Eyt_map-1.96*sqrt(Varyt_map))')], color1, 'edgecolor', color1);\n% GP mean\nh2=plot(xgrid, Eyt_map, 'color', color2, 'linewidth', 3);\n% observations\nh3=plot(x, y, 'xk', 'markersize', 10, 'linewidth', 2);\n% true function\nh4=plot(xgrid, norm_pdf(4*xgrid), 'color', 'r', 'linewidth', 2);\nlegend([h1 h2 h3 h4], 'GP 95% CI', 'GP mean', 'observations', 'true latent function')\ntitle('GP (squared exponential) predictions and the data points');\n\nfigure, set(gcf, 'color', 'w'), hold on\nh1=fill([xgrid' fliplr(xgrid')], [(Eyt_map2+1.96*sqrt(Varyt_map2))' fliplr((Eyt_map2-1.96*sqrt(Varyt_map2))')], color1, 'edgecolor', color1);\n% GP mean\nh2=plot(xgrid, Eyt_map2, 'color', color2, 'linewidth', 3);\n% observations\nh3=plot(x, y, 'xk', 'markersize', 10, 'linewidth', 2);\n% true function\nh4=plot(xgrid, norm_pdf(4*xgrid), 'color', 'r', 'linewidth', 2);\nlegend([h1 h2 h3 h4], 'GP 95% CI', 'GP mean', 'observations', 'true latent function')\ntitle('GP (neural network) predictions and the data points');\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_neuralnetcov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5516556931348269}}
{"text": "function\t[W ,Ydim, Xdim, Dtau] = get_estimated_weight(Model,parm,wmode);\n% return Weight matrix from 'Model'\n%  [W ,Ydim, Xdim, Dtau] = get_estimated_weight(Model,parm,wmode);\n% W : Weight matrix : 2D-matrix [Ydim x (Xdim * Dtau)]\n% Dtau : time embedding dim\n% Ydim : Output space dim\n% Xdim : Input space dim\n%   To get temporal filter shape of Weight matrix\n% Wd = reshape( W, [Ydim, Xdim, Dtau]);\n% Wd(n,m,:) : Weight for n-th output & m-th input data\n%\n% 2008-5-20 Masa-aki Sato\n\nif isfield(parm,'Dtau')\n\tDtau  = parm.Dtau;\nelse\n\tDtau  = 1;\nend\n\nM_all = Model.M_all;\nYdim  = size(Model.W,1);\nXdim  = M_all/Dtau;\n\nif isfield(Model,'ix_act')\n\t% Active index\n\tix_act = Model.ix_act;\n\n\tW = zeros(Ydim ,M_all);\n\tW(:,ix_act) = Model.W;\nelse\n\tW =  Model.W;\nend\n\nif exist('wmode','var') && wmode==0, return; end;\n\nif length(parm.xmean) == Xdim,\n\tparm.xmean = repmat(parm.xmean ,[Dtau 1]);\n\tparm.xnorm = repmat(parm.xnorm ,[Dtau 1]);\nend\n\n% Scale back by normalization factor\nif isfield(parm,'xnorm') & isfield(parm,'ynorm')\n\tW = (parm.ynorm(:)*(1./parm.xnorm(:)')) .* W;\nend\n", "meta": {"author": "KamitaniLab", "repo": "GenericObjectDecoding", "sha": "c98f24370668109fd9978bc8b43a33bd43926f47", "save_path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding", "path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding/GenericObjectDecoding-c98f24370668109fd9978bc8b43a33bd43926f47/code/matlab/lib/SPR_2009_12_17/get_estimated_weight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5515966291628839}}
{"text": "close;\nclear;\n\nload models.mat;\nscale_rat = 10;\nNN_Number = 5;\n\n%[ img1_desc_types, detectedPts1, locations1,pts1 ] = create_mesh_sift_features(vertex1, faces1, scale_rat);\n[ img1_desc_types, ~, ~,pts1 ] = create_mesh_spin_features(vertex1, faces1,5,scale_rat);\n\n%[ img2_desc_types, detectedPts2, locations2,pts2] = create_mesh_sift_features(vertex2, faces2, scale_rat);\n[ img2_desc_types, ~, ~,pts2] = create_mesh_spin_features(vertex2, faces2,5,scale_rat);\n\nDescrData = pdist2(img1_desc_types,img2_desc_types);\n\n[~,NN_Data]=sort(DescrData,2,'ascend');\nNN_Data=NN_Data(:,1:NN_Number);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/36316-local-depth-sift-and-scale-invariant-spin-image-local-features-for-3d-meshes/descriptor_toolbox/find_candidates_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5515966236829767}}
{"text": "function [lambda, r2] = duration_amplitude(self, law, min_amplitude, mag_zone)\n    %DURATION_AMPLITUDE Use the duration-amplitde\n    %Compute the fraction of a data series above each\n    %amplitude level, plot the duration vs amplitude data, and then\n    %allow user input to fit a regression line.\n    %   rsamObject.duration_amplitude(law, min_amplitude)\n    %   \n    %   Inputs: \n    %       law = 'exponential' or 'power'\n    %       min_amplitude = (Optional) the smallest amplitude to use on\n    %       the x-axis. Otherwise will be 10^10 times smallest than the\n    %       largest amplitude.\n    %\n    %   Outputs:\n    %       (None) A graph is plotted, the user clicks two points, and\n    %       from that slope, the characteristic amplitude is computed\n    %       and shown on the screen.\n\n    y = self.data;\n    n = length(y);\n    a = abs(y);\n    max_amplitude = max(a);\n    if ~exist('min_amplitude', 'var')\n        min_amplitude = max([min(a) max(a)*1e-10]);\n    end\n\n    % Method 1\n    index=0;\n    x = min_amplitude;\n    while x < max_amplitude,\n        i = find(a>x);\n        f = length(i);\n        index = index+1;\n        frequency(index) = f;\n        threshold(index) = x;\n        x = x * 1.2;\n    end\n    clear x y a  f  n  min_amplitude max_amplitude index ;\n\n    %             % Method 2\n    %             threshold = [0.0 logspace(min_amplitude, max_amplitude, 50)];\n    %             nsamples=[];\n    %             for d = 1:length(threshold)\n    %                 i = find(a > threshold(d));\n    %                 frequency(d) = length(i)/length(y);\n    %             end \n    %             clear d, nsamples, i, y\n\n    %% PLOT_DURATION_AMPLITUDE \n    % plot graph, user select two points, compute\n    % characteristic from slope.\n    % Use different method depending on whether it is a\n    % power law or exponential.\n\n    % define x and y\n    switch law\n        case {'exponential'}\n            x = threshold;\n            xlabelstr = 'RMS Displacement(nm)';\n        case {'power'}\n            x = log10(threshold);\n            xlabelstr = 'log10(RMS Displacement(nm))';\n        otherwise\n            error('law unknown')\n    end\n    y=log10(frequency);\n\n    % plot duration-amplitude data as circles\n    figure\n    plot(x,y,'o');\n    xlabel(xlabelstr);\n    ylabel('log10(Cumulative Minutes)');\n    hold on;\n    %set(gca,'XLim',[xmin xmax]);\n\n    lambda=0;\n    r2=0;\n\n    % check if we have pre-set the magnitude range, effectively\n    % our x1 and x2 click points with ginput\n    if exist('mag_zone','var') % no user select\n        switch law\n            case {'power'}\n                x1=min(mag_zone);\n                x2=max(mag_zone);\n            case {'exponential'}\n                x1=10^min(mag_zone);\n                x2=10^max(mag_zone);\n\n            otherwise\n                error('law unknown')\n        end      \n        if x1<min(x)\n            x2=min(x);\n        end\n        y1=interp1(x,y,x1);\n        if x2>max(x)\n            x2=max(x);\n        end\n        y2=interp1(x,y,x2); \n\n        % draw a dotted line to show where user selected\t\n        %plot([x1 x2], [y1 y2], '-.');\n\n        % select requested data range and do a least squares fit\n        ii = find(x >= x1 & x <= x2);\n        wx = x(ii);\n        wy = y(ii);\n        [p,S]=polyfit(wx,wy,1);\n        yfit = polyval(p,wx);\n        thiscorr = corrcoef(wy, yfit)\n        %try\n        if numel(thiscorr)>1\n            r2 = thiscorr(1,2);\n\n            % compute lambda\n            switch law\n                case {'exponential'}\n                    lambda = -p(1)/log10(exp(1));\n                case {'power'}\n                    lambda = -p(1); \n                otherwise\n                    error('law unknown')\n            end\n\n            disp(sprintf('characteristic D_R_S=%.2f cm^2, R^2=%.2f',lambda,r2));\n\n            % draw the fitted line\n            xf = [min(wx) max(wx)];\n            yf = xf * p(1) + p(2);\n            plot(xf, yf,'-');\n\n            %ylabel('log10(t/t0)');\n            %xlabel(sprintf('D_R_S (%s) (cm^2)',measure));\n\n\n            % Add legend\n            yrange=get(gca,'YLim');\n            xlim = get(gca,'XLim');\n            xmax=max(xlim);\n\n            xpos = xmax*0.65;\n            ypos = (yrange(2)-yrange(1))*0.8;\n            r2str=sprintf('%.2f',r2);\n            lambdastr=sprintf('%.2f',lambda);\n            if strcmp(law,'exponential')\n                tstr = [' \\lambda=',lambdastr,' R^2=',r2str];\n            else\n                tstr = [' \\gamma=',lambdastr,' R^2=',r2str];\n            end\n\n            text(xpos, ypos, tstr, ...\n                'FontName','Helvetica','FontSize',[14],'FontWeight','bold');   \n        else\n            lambda=NaN;\n            r2=NaN;\n        end\n\n    else\n\n        % user select a range of data\n        disp('Left-click Select lowest X, any other mouse button to ignore this station')\n        [x1, y1, button1]=ginput(1);\n        if button1==1\n            disp('Left-click Select highest X, any other mouse button to ignore this station')\n            [x2, y2, button2]=ginput(1);    \n            if button2==1\n                if x2>x1\n                   % draw a dotted line to show where user selected\t\n                    plot([x1 x2], [y1 y2], '-.');\n\n                    % select requested data range and do a least squares fit\n                    ii = find(x >= x1 & x <= x2);\n                    wx = x(ii);\n                    wy = y(ii);\n                    [p,S]=polyfit(wx,wy,1);\n                    yfit = polyval(p,wx);\n                    thiscorr = corrcoef(wy, yfit)\n\n                    r2 = thiscorr(1,2);\n\n                    % compute lambda\n                    switch law\n                        case {'exponential'}\n                            lambda = -p(1)/log10(exp(1));\n                        case {'power'}\n                            lambda = -p(1); \n                        otherwise\n                            error('law unknown')\n                    end\n\n                    disp(sprintf('characteristic D_R_S=%.2f cm^2, R^2=%.2f',lambda,r2));\n\n                    % draw the fitted line\n                    xf = [min(wx) max(wx)];\n                    yf = xf * p(1) + p(2);\n                    plot(xf, yf,'-');\n\n                    %ylabel('log10(t/t0)');\n                    %xlabel(sprintf('D_R_S (%s) (cm^2)',measure));\n\n\n                    % Add legend\n                    yrange=get(gca,'YLim');\n                    xlim = get(gca,'XLim');\n                    xmax=max(xlim);\n\n                    xpos = xmax*0.65;\n                    ypos = (yrange(2)-yrange(1))*0.8;\n                    r2str=sprintf('%.2f',r2);\n                    lambdastr=sprintf('%.2f',lambda);\n                    if strcmp(law,'exponential')\n                        tstr = [self.sta,' \\lambda=',lambdastr,' R^2=',r2str];\n                    else\n                        tstr = [self.sta,' \\gamma=',lambdastr,' R^2=',r2str];\n                    end\n\n                    text(xpos, ypos, tstr, ...\n                        'FontName','Helvetica','FontSize',[14],'FontWeight','bold');\n\n\n                end\n            end\n        end\n    end\nend\t", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@rsam/extensions/duration_amplitude.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5515966126454671}}
{"text": "function out = echo_enc_bf(signal, text, d0, d1, alpha, L)\n%ECHO_ENC Echo Hiding with Backward and Forward Echo Kernels\n%\n%   INPUT VARIABLES\n%       signal : Cover signal\n%       text   : Message to hide\n%       d0     : Delay rate for bit0\n%       d1     : Delay rate for bit1\n%       alpha  : Echo amplitude\n%       L      : Length of frames\n%\n%   OUTPUT VARIABLES\n%       out    : Stego signal\n%\n%   Kadir Tekeli (kadir.tekeli@outlook.com)\n\nif nargin < 4\n\td0 = 150;     %Delay rate for bit0\n\td1 = 200;     %Delay rate for bit1\nend\n\nif nargin < 5\n\talpha = 0.5;  %Echo amplitude\nend\n\nif nargin < 6\n\tL = 8*1024;   %Length of frames\nend\n\n[s.len, s.ch] = size(signal);\nbit = getBits(text);\nnframe = floor(s.len/L);\nN = nframe - mod(nframe,8);      %Number of frames (for 8 bit)\n\nif (length(bit) > N)\n\twarning('Message is too long, being cropped!');\n\tbits = bit(1:N);\nelse\n\twarning('Message is being zero padded...');\n\tbits = [bit, num2str(zeros(N-length(bit), 1))'];\nend\n\n[echo_zro, echo_one] = bf_echo(signal, d0, d1, alpha);  %Echo signals\nmix = mixer(L, bits, 0, 1, 256) * ones(1, s.ch);        %Mixer signal\n\n%%%%%%%%%%%%%%%%%%%%%%% EMBEDDING MESSAGE... %%%%%%%%%%%%%%%%%%%%%%%\nout = signal(1:N*L, :) + echo_zro(1:N*L, :) .* abs(mix-1) ...\n                       + echo_one(1:N*L, :) .* mix;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nout = [out; signal(N*L+1:s.len, :)];   %Rest of the signal\nend\n", "meta": {"author": "ktekeli", "repo": "audio-steganography-algorithms", "sha": "695ae978cdec2537d64db771ed4a12887bda92f8", "save_path": "github-repos/MATLAB/ktekeli-audio-steganography-algorithms", "path": "github-repos/MATLAB/ktekeli-audio-steganography-algorithms/audio-steganography-algorithms-695ae978cdec2537d64db771ed4a12887bda92f8/02-Echo-Hiding/03-Echo-Hiding-BF-Kernel/echo_enc_bf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5515846356120713}}
{"text": "classdef ContrastiveLoss < dagnn.GenericLoss\n  properties\n    margin = 1;\n  end\n\n  methods\n    function outputs = forward(obj, inputs, params)\n      switch numel(inputs)\n        case 3\n          outputs{1} = vl_nncontrloss(inputs{:}, 'margin', obj.margin);\n        case 4\n          outputs{1} = vl_nncontrloss(inputs{1:3}, 'margin', inputs{4});\n        otherwise\n          error('Invalid number of inputs.');\n      end\n      if true\n        isPos = inputs{3} == 1;\n        % posDist = mean(norm(reshape(inputs{1}(:, :, :, isPos) - inputs{2}(:, :, :, isPos), [], sum(isPos))));\n        % negDist = mean(norm(reshape(inputs{1}(:, :, :, ~isPos) - inputs{2}(:, :, :, ~isPos), [], sum(~isPos))));\n        posDist = sqrt(sum((reshape(inputs{1}(:, :, :, isPos) - inputs{2}(:, :, :, isPos), [], sum(isPos))).^2,1));\n        negDist = sqrt(sum((reshape(inputs{1}(:, :, :, ~isPos) - inputs{2}(:, :, :, ~isPos), [], sum(~isPos))).^2,1));\n        eer = vl_eer([-1*ones(1,numel(posDist)) 1*ones(1,numel(negDist))],[posDist negDist]);\n        fprintf('PD: %.2f ND: %.2f EER: %.3f ', mean(posDist), mean(negDist) ,eer);\n      end\n      \n      logoutputs = outputs;\n      logoutputs{1} = numel(inputs{3})*eer;\n      obj.account(inputs, logoutputs);\n    end\n\n    function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)\n      switch numel(inputs)\n        case 3\n          [dzdx1, dzdx2] = vl_nncontrloss(inputs{:}, derOutputs{1}, 'margin', obj.margin);\n        case 4\n          [dzdx1, dzdx2] = vl_nncontrloss(inputs{1:3}, derOutputs{1}, 'margin', inputs{4});\n        otherwise\n          error('Invalid number of inputs.');\n      end\n      derInputs = {dzdx1, dzdx2, []};\n      derParams = {} ;\n    end\n\n    function obj = ContrastiveLoss(varargin)\n      obj.load(varargin{:}) ;\n    end\n  end\nend", "meta": {"author": "a-nagrani", "repo": "VGGVox", "sha": "53481f018be60541909bcb2ae1c65cdd8ea3c147", "save_path": "github-repos/MATLAB/a-nagrani-VGGVox", "path": "github-repos/MATLAB/a-nagrani-VGGVox/VGGVox-53481f018be60541909bcb2ae1c65cdd8ea3c147/matlab/+dagnn/ContrastiveLoss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5515846356120713}}
{"text": "function sws = sw_normalized(sw, swc, sor)\n%SW_NORMALIZED maps the saturation from [0, 1] to [swc, 1-sor]\nsws=((sw>swc).*(sw<1-sor).*(sw-swc)./(1-sor-swc)+(sw>=1-sor));\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/FieldGeology/sw_normalized.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5515846299880913}}
{"text": "classdef ChTargetFactory < handle\n    \n    methods (Access = public, Static)\n        \n        function Ch_star = create(cParams)\n            \n            switch cParams.type\n                case 'negative_poisson'\n                    \n                    E1  = cParams.E_plus;\n                    E0  = cParams.E_minus;\n                    nu1 = cParams.nu_plus;\n                    nu0 = cParams.nu_minus;\n                    kappa_f = @(E,nu) E/2*(1-nu);\n                    mu_f = @(E,nu) E/2*(1-nu);\n                    \n                    k_plus = kappa_f(E1,nu1);\n                    mu_plus = mu_f(E1,nu1);\n                    \n                    k_minus = kappa_f(E0,nu0);\n                    mu_minus = mu_f(E0,nu0);\n                    \n                    \n                    nu = @(k,mu) (k-mu)/(k+mu);\n                    E = @(k,mu) (4*k*mu)/(k+mu);\n                    C = @(E,nu) (E/(1-nu*nu)*[1 nu 0; nu 1 0; 0 0 (1-nu)/2]);\n                    \n                    kappa_nu_min = k_minus;\n                    mu_nu_min = mu_plus;\n                    \n                    nu_min = nu(kappa_nu_min,mu_nu_min);\n                    E_nu_min = E(kappa_nu_min,mu_nu_min);\n                    C_nu_min = C(E_nu_min,nu_min);\n                    Ch_star = C_nu_min;\n                    \n                case 'nu_0_6' %From Sigmund Thesis% rho = 0.38\n                    C = @(E,nu) (E/(1-nu*nu)*[1 nu 0; nu 1 0; 0 0 (1-nu)/2]);\n                    nu = -0.6;\n                    E = (1-nu*nu)*0.04;\n                    Ch_star = C(E,nu);\n                    \n                case 'Seba' % Es=0.08; nus=-0.25\n                    Ch_star = [0.0853    -0.0213       0;\n                               -0.0213    0.0853       0;\n                                   0         0    0.0533];\n                \n                case 'Nu0_2'\n                    %Ch_star = [0.0287   -0.0069    0.0068;\n                    %           -0.0069    0.0287    0.0068;\n                    %           0.0068    0.0068    0.0137];\n                           \n                    %Ch_star = [0.0129   -0.0158    0.0000;\n                    %           -0.0158    0.0812   -0.0000;\n                    %           0.0000   -0.0000    0.0021];\n                    \n                    Ch_star = [  0.0157   -0.0174   -0.0000;\n                                -0.0174    0.0815   -0.0000;\n                                -0.0000   -0.0000    0.0025];\n                               \n                    \n                case 'nu_0_8' %From Sigmund Thesis% rho = 0.25\n                    C = @(E,nu) (E/(1-nu*nu)*[1 nu 0; nu 1 0; 0 0 (1-nu)/2]);\n                    nu = -0.8;\n                    E = (1-nu*nu)*0.02;\n                    Ch_star = C(E,nu);\n                    \n                case 'Vfrac07'\n                    Ch_star =[\n                        0.4256    0.2837         0\n                        0.2837    0.4256         0\n                        0         0    0.1419];\n                    \n                case 'Vfrac06'\n                    Ch_star =[\n                        0.2909    0.1940         0\n                        0.1940    0.2909         0\n                        0         0    0.0970];\n                    \n                case 'Vfrac05'\n                    Ch_star =[\n                        0.1892    0.1261         0\n                        0.1261    0.1892         0\n                        0         0    0.0631];\n                    \n                case 'Vfrac04'\n                    Ch_star =[\n                        0.1141    0.0761         0\n                        0.0761    0.1141         0\n                        0         0    0.0380];\n                    \n                case 'Vfrac04b' %Circle of 0.4 radius\n                         Ch_star = [ 0.7519    0.2237   -0.0000;\n                                  0.2237    0.7519   -0.0000;\n                                 -0.0000   -0.0000    0.2245];\n                    \n                case 'Vfrac03'\n                    Ch_star =[\n                        0.0611    0.0407         0\n                        0.0407    0.0611         0\n                        0         0    0.0204];\n                    \n                case 'HorizontalRectangleInclusion'\n                    Ch_star = [0.4637    0.0010    0.0000\n                               0.0010    0.0031    0.0000\n                               -0.0000    0.0000    0.0011];\n\n                case 'Composite'\n                    Ch_star =[1 0.15 0;\n                        0.15 0.5 0;\n                        0 0 0.2];\n                case 'HoneyComb'\n                    Ch_star =0.094*[1 0.75 0\n                        0.75 1 0\n                        0 0 0.125];\n                case 'InvertedHoneyComb'\n                    Ch_star =0.08*[1 -0.5 0\n                        -0.5 1 0\n                        0 0 0.06];\n                case 'AcousticZeroShearA'\n                    Ch_star =[1 1 0;\n                        1 1 0;\n                        0 0 0];\n                case 'NegativePoiss06'\n                    Ch_star =0.04*[1 -0.6 0;\n                        -0.6 1 0;\n                        0 0 0.8];\n                case 'IsotropyHexagon'\n                    Ch_star = [0.5931 0.1882 0.0000;\n                               0.1882 0.5931 0.0000;\n                               0.0000 0.0000 0.2025]; \n            end\n        end\n    end\n    \nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Shape Functions/ChTargetFactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5515846244879419}}
{"text": "function [tg,theta] = tgmo(tmap,ntex,radius,norient,varargin)\n% function [tg,theta] = tgmo(tmap,ntex,radius,norient,...)\n%\n% Compute the texture gradient at a single scale and multiple\n% orientations.\n%\n% INPUT\n%\ttmap\t\tTexton map, values in [1,ntex].\n%\tntex\t\tNumber of textons.\n%\tradius\t\tRadius of disc for texture gradient.\n%\tnorient\t\tNumber of orientation at which to compute \n%\t\t\tthe texture gradient.\n%\t'smooth'\tSmoothing method, one of \n%\t\t\t{'gaussian','savgol','none'}, default 'none'.\n%\t'sigma'\t\tSigma for smoothing, default to radius.\n%\t'tsim'\t\tTexton similarity matrix.  If not \n%\t\t\tprovided, then use chi-squared.\n%\n% OUTPUT\n%\ttg\t\tSize [h w norient] array of tg images.\n%\ttheta\t\tVector of disc orientations (which are \n%\t\t\torthogonal to the texture gradient).\n%\n% David R. Martin <dmartin@eecs.berkeley.edu>\n% March 2003\n\n% process options\nsmooth = 'none';\nsigma = radius;\nusechi2 = true;\nfor i = 1:2:numel(varargin),\n  opt = varargin{i};\n  if ~ischar(opt), error('option names not a string'); end\n  if i==numel(varargin), error(sprintf('option ''%s'' has no value',opt)); end\n  val = varargin{i+1};\n  switch opt,\n   case 'smooth',\n    switch val,\n     case {'none','gaussian','savgol'}, smooth=val;\n     otherwise, error(sprintf('invalid option smooth=''%s''',val));\n    end\n   case 'sigma', sigma=val;\n   case 'tsim', tsim=val; usechi2=false;\n   otherwise, error(sprintf('invalid option ''%s''',opt));\n  end\nend\n\nradius = max(1,radius);\nnorient = max(1,norient);\ntheta = (0:norient-1)/norient*pi;\n\n[h,w] = size(tmap);\ntg = zeros(h,w,norient);\nfwrite(2,'[');\nfor i = 1:norient,\n  fwrite(2,'.');\n  if usechi2,\n    tg(:,:,i) = tgso(tmap,ntex,radius,theta(i),...\n                     'smooth',smooth,'sigma',sigma);\n  else\n    tg(:,:,i) = tgso(tmap,ntex,radius,theta(i),...\n                     'smooth',smooth,'sigma',sigma,'tsim',tsim);\n  end\nend\nfwrite(2,sprintf(']\\n'));\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/segbench/lib/matlab/tgmo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5515654671386578}}
{"text": "classdef matRad_SquaredUnderdosing < DoseObjectives.matRad_DoseObjective\n% matRad_SquaredUnderdosing Implements a penalized squared underdosing objective\n%   See matRad_DoseObjective for interface description\n%\n% References\n%   -\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2020 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    properties (Constant)\n        name = 'Squared Underdosing';\n        parameterNames = {'d^{min}'};\n        parameterTypes = {'dose'};\n    end\n    \n    properties\n        parameters = {60};\n        penalty = 1;\n    end\n    \n    methods\n        function obj = matRad_SquaredUnderdosing(penalty,dMin)\n            %If we have a struct in first argument\n            if nargin == 1 && isstruct(penalty)\n                inputStruct = penalty;\n                initFromStruct = true;\n            else\n                initFromStruct = false;\n                inputStruct = [];\n            end\n            \n            %Call Superclass Constructor (for struct initialization)\n            obj@DoseObjectives.matRad_DoseObjective(inputStruct);\n            \n            %now handle initialization from other parameters\n            if ~initFromStruct\n                if nargin == 2 && isscalar(dMin)\n                    obj.parameters{1} = dMin;\n                end\n                \n                if nargin >= 1 && isscalar(penalty)\n                    obj.penalty = penalty;\n                end\n            end\n        end\n        \n        %% Calculates the Objective Function value\n        function fDose = computeDoseObjectiveFunction(obj,dose)\n            % overdose : dose minus prefered dose\n            underdose = dose - obj.parameters{1};\n            \n            % apply positive operator\n            underdose(underdose>0) = 0;\n            \n            % claculate objective function\n            fDose = obj.penalty/numel(dose) * (underdose'*underdose);\n        end\n        \n        %% Calculates the Objective Function gradient\n        function fDoseGrad   = computeDoseObjectiveGradient(obj,dose)\n            % overdose : dose minus prefered dose\n            underdose = dose - obj.parameters{1};\n            \n            % apply positive operator\n            underdose(underdose>0) = 0;\n            \n            % calculate delta\n            fDoseGrad = 2 * obj.penalty/numel(dose) * underdose;\n        end\n    end\n    \nend\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/optimization/+DoseObjectives/matRad_SquaredUnderdosing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5515654608287018}}
{"text": "function rs = scalogram(s, scalemin, scalemax, scalestep, mlen)\n\n%tstoolbox/@signal/scalogram\n%   Syntax:\n%     * rs = scalogram(s) => scalemin=0.1\n%     * rs = scalogram(s, scalemin) => scalemax=1\n%     * rs = scalogram(s, scalemin, scalemax) => scalestep=0.1\n%     * rs = scalogram(s, scalemin, scalemax, scalestep) => mlen=10\n%     * rs = scalogram(s, scalemin, scalemax, scalestep, mlen)\n%\n%   Scalogram of signal s using morlet wavelet. See also: spec2.\n%\n% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt\n\nnarginchk(1,5);\n\nif nargin<2\n\tscalemin = 0.1;\nend\nif nargin<3\n\tscalemax = 1;\nend\nif nargin<4\n\tscalestep = 0.1;\nend\nif nargin<6\n\tmlen = 10;\nend\n\nc = scalogram(s.core, scalemin, scalemax, scalestep, mlen);\nrs = signal(c, s);\t% special constructor calling syntax for working routines\na = achse(unit, scalemin, scalestep);\nrs = setaxis(rs, 2, a);\nrs = setplothint(rs, 'spectrogram');\nrs = addhistory(rs, ['Calculated scalogram']);\nrs = addcommandlines(rs, 's = scalogram(s', scalemin, scalemax, scalestep);\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/scalogram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5515654556108707}}
{"text": "function test_bug2342\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY\n\n\n% first create some data\n%--------------------------------------------------------\n% make 3 channels with no direct link between 1 and 2\ncfg             = [];\ncfg.ntrials     = 100;\ncfg.triallength = 0.5;\ncfg.fsample     = 200;\ncfg.nsignal     = 3;\ncfg.method      = 'ar';\ncfg.params(:,:,1) = [ 0.8 0   0; \n                      0   0.9 0.5;\n                      0.4 0   0.5];\ncfg.params(:,:,2) = [-0.5    0  0; \n                        0 -0.8  0; \n                        0    0 -0.2];\ncfg.noisecov      = [0.3 0 0;\n                       0 1 0;\n                       0 0 0.2];\n\ndata            = ft_connectivitysimulation(cfg);\ndata2           = data;\ndata2.label     = {'signal001b';'signal002b';'signal003b'};\ndata            = ft_appenddata([], data, data2);\n\n% according to Martin, padding should get rid of most the zigzags.\n\n% freqanalysis\ncfgf           = [];\ncfgf.method    = 'mtmfft';\ncfgf.output    = 'fourier';\ncfgf.tapsmofrq = 4;\nfreq           = ft_freqanalysis(cfgf, data);\ncfgf.padding   = 10;\nfreqpad        = ft_freqanalysis(cfgf, data);\n\n% connectivityanalysis\ncfg = [];\ncfg.method           = 'granger';\ncfg.granger.sfmethod = 'bivariate';\ng    = ft_connectivityanalysis(cfg, freq);\ngpad = ft_connectivityanalysis(cfg, freqpad);\n\n%...but it doesn't\n\n% now make it more realistic and add a bit of noise to signals 4-6 (to make\n% it not perfectly collinear).\ndata2 = data;\nfor k = 1:numel(data.trial)\n  data2.trial{k}(4:6,:) = data.trial{k}(4:6,:)+randn(3,100)*0.000001;\nend\n\ncfgf           = [];\ncfgf.method    = 'mtmfft';\ncfgf.output    = 'fourier';\ncfgf.tapsmofrq = 2;\nfreq2           = ft_freqanalysis(cfgf, data2);\ncfgf.padding   = 10;\nfreq2pad        = ft_freqanalysis(cfgf, data2);\n\n% connectivityanalysis\ncfg = [];\ncfg.method           = 'granger';\ncfg.granger.sfmethod = 'bivariate';\ng2    = ft_connectivityanalysis(cfg, freq2);\ng2pad = ft_connectivityanalysis(cfg, freq2pad);\n\n% conclusion: adding a tiny bit of noise removes the zigzags.\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_bug2342.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5515654514851638}}
{"text": "% DEMROBOTWIRELESS2 Wireless Robot data from University of Washington, without dynamics and without back constraints.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'robotWireless';\nexperimentNo = 2;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('ftc');\noptions.back = 'mlp';\noptions.backOptions = mlpOptions;\n\nlatentDim = 2;\nd = size(Y, 2);\n\nmodel = fgplvmCreate(latentDim, d, Y, options);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\ncapName = dataSetName;\ncapName(1) = upper(capName(1));\nsave(['dem' capName num2str(experimentNo) '.mat'], 'model');\n\n% Load the results and display dynamically.\nfgplvmResultsDynamic(dataSetName, experimentNo, 'vector')\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demRobotWireless2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5515036589683241}}
{"text": "function x = prox_cvx(v, lambda, f, l, u)\n% PROX_CVX    The proximal operator of a generic function.\n%\n%   prox_cvx(v,lambda,f) is the proximal operator of f with parameter lambda\n%   evaluated at v. Here, f is a closure, possibly described by an anonymous\n%   function. It is also possible to provide lower and upper bounds, so\n%   prox_cvx(v,f,l,u) is the prox operator of f + I_[l,u].\n%\n%   For example,\n%\n%     prox_cvx(v, lambda, (@(x) norm(x,1))\n%\n%   is equivalent to the soft thresholding operator.\n%\n%   WARNING: This is a *very* inefficient way of evaluating a proximal\n%   operator. This function is mainly for rapid prototyping and\n%   testing custom implementations of particular proximal operators.\n%   It may also be useful when suffering from extreme laziness.\n\n\n    if ~exist('l', 'var') || isnan(l)\n        l = -Inf;\n    end\n\n    if ~exist('u', 'var') || isnan(u)\n        u = Inf;\n    end\n\n    L = 1/(2*lambda);\n    [m n] = size(v);\n\n    if min(m,n) == 1\n        cvx_begin quiet\n            variable x(max(m,n))\n            minimize(f(x) + L*sum_square(x - v))\n            subject to\n                v >= l;\n                v <= u;\n        cvx_end\n    elseif m == n && m > 1\n        cvx_begin quiet\n            variable x(n,n) symmetric\n            minimize(f(x) + L*pow_pos(norm(x - v, 'fro'), 2))\n            subject to\n                x == semidefinite(n)\n        cvx_end\n    else\n        x = nan(size(v));\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/prox_cvx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5515036485692478}}
{"text": "function [xnew,ynew]=splineValue(x,y)\n%+++ spline for interpolation.\n%+++ \n%+++ Aug., 2010.\n\nminx=min(x);\nmaxx=max(x);\nd=(maxx-minx)/128;\nxnew=linspace(minx-d,maxx+d,128)';\nynew=spline(x,y,xnew);\n\n\n", "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/plslda/splineValue.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5515036480162583}}
{"text": "function f1 = perform_curve_subdivision(f, nsub, options)\n\n% perform_curve_subdivision - perform subdivision\n%\n%   f1 = perform_curve_subdivision(f, nsub, options);\n%\n%   Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\nif nsub<=0\n    f1 = f; return;\nend\nif size(f,1)>size(f,2)\n    f = f';\nend\nif size(f,1)>1\n    for k=1:size(f,1)\n        f1(k,:) = perform_curve_subdivision(f(k,:), nsub, options);\n    end\n    return;\nend\n\nh = getoptions(options, 'h', [1 4 6 4 1]);\nh = 2*h/sum(h(:));\n\nif not(isfield(options, 'bound'))\n    options.bound = 'per';\nend\n\nf = perform_curve_subdivision(f, nsub-1, options);\n\nf = f(:)';\nn = length(f);\nf1 = zeros(1,n*2);\nf1(1:2:end) = f;\nf1 = perform_convolution(f1, h, options);\nf1 = f1(:)';", "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_wavelet_meshes/perform_curve_subdivision.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5515036429549676}}
{"text": "function [ Vehicle ] = gen_trajectory( t )\n\n     radius = 10;   \n    Vehicle.position = radius* [ 5*cos(0.3*t/4); 4*sin(0.2*t/4); 2*sin(0.2*t/4+1) ];\n    %Vehicle.position = radius* [ 5*cos(0.03*t); 4*sin(0.02*t); 2*sin(0.02*t+1) ];\n    Vehicle.euler = [0.5*t+2; -0.3*t; 0.4*t];\n    \n\n    \n    \n    \n    \n    % generate rotation matrix\n    for i = 1:size(Vehicle.euler, 2)\n        Vehicle.orientation((i-1)*3+1:i*3, 1:3) = euler2rotation_matrix(Vehicle.euler(:, i));\n    end\nend\n\n", "meta": {"author": "RomaTeng", "repo": "EKF-SLAM-on-Manifold", "sha": "12d7d8d88c84161baed173e38d49dedb4adb2b96", "save_path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold", "path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold/EKF-SLAM-on-Manifold-12d7d8d88c84161baed173e38d49dedb4adb2b96/datagen_3d/gen_trajectory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5515036376171816}}
{"text": "function [dS,t,f]=mtdspecgramc(data,movingwin,phi,params)\n% Multi-taper derivative of the time-frequency spectrum - continuous process\n%\n% Usage:\n%\n% [dS,t,f]=mtdspecgramc(data,movingwin,phi,params)\n% Input: \n%   Note that all times can be in arbitrary units. But the units have to be\n%   consistent. So, if E is in secs, win, t have to be in secs, and Fs has to\n%   be Hz. If E is in samples, so are win and t, and Fs=1. In case of spike\n%   times, the units have to be consistent with the units of data as well.\n%\n%       data        (in form samples x channels/trials or a single vector) -- required\n%       movingwin         (in the form [window winstep] i.e length of moving\n%                                                 window and step size.\n%                                                 Note that units here have\n%                                                 to be consistent with\n%                                                 units of Fs - required\n%       phi         (angle for evaluation of derivative) -- required\n%                       e.g. phi=[0,pi/2] giving the time and frequency\n%                       derivatives\n%       params: structure with fields tapers, pad, Fs, fpass, trialave\n%       -optional\n%           tapers : precalculated tapers from dpss or in the one of the following\n%                    forms: \n%                    (1) A numeric vector [TW K] where TW is the\n%                        time-bandwidth product and K is the number of\n%                        tapers to be used (less than or equal to\n%                        2TW-1). \n%                    (2) A numeric vector [W T p] where W is the\n%                        bandwidth, T is the duration of the data and p \n%                        is an integer such that 2TW-p tapers are used. In\n%                        this form there is no default i.e. to specify\n%                        the bandwidth, you have to specify T and p as\n%                        well. Note that the units of W and T have to be\n%                        consistent: if W is in Hz, T must be in seconds\n%                        and vice versa. Note that these units must also\n%                        be consistent with the units of params.Fs: W can\n%                        be in Hz if and only if params.Fs is in Hz.\n%                        The default is to use form 1 with TW=3 and K=5\n%                     Note that T has to be equal to movingwin(1).\n%\n%\t        pad\t\t    (padding factor for the FFT) - optional (can take values -1,0,1,2...). \n%                    -1 corresponds to no padding, 0 corresponds to padding\n%                    to the next highest power of 2 etc.\n%\t\t\t      \t e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT\n%\t\t\t      \t to 512 points, if pad=1, we pad to 1024 points etc.\n%\t\t\t      \t Defaults to 0.\n%           Fs   (sampling frequency) - optional. Default 1.\n%           fpass    (frequency band to be used in the calculation in the form\n%                                   [fmin fmax])- optional. \n%                                   Default all frequencies between 0 and Fs/2\n%           trialave - (average over trials/channels when 1, don't average when 0) - optional. Default 0\n% Output:\n%       dS      (spectral derivative in form phi x time x frequency x channels/trials if trialave=0; \n%               in form phi x time x frequency if trialave=1)\n%       t       (times)\n%       f       (frequencies)\n\nif nargin < 3; error('Need data, window parameters and angle'); end;\nif nargin < 4; params=[]; end;\n\nif length(params.tapers)==3 & movingwin(1)~=params.tapers(2);\n    error('Duration of data in params.tapers is inconsistent with movingwin(1), modify params.tapers(2) to proceed')\nend\n\n[tapers,pad,Fs,fpass,err,trialave,params]=getparams(params);\nclear err\ndata=change_row_to_column(data);\n[N,C]=size(data);\nNwin=round(Fs*movingwin(1)); % number of samples in window\nNstep=round(movingwin(2)*Fs); % number of samples to step through\nnfft=max(2^(nextpow2(Nwin)+pad),Nwin);\nf=getfgrid(Fs,nfft,fpass); Nf=length(f);\nparams.tapers=dpsschk(tapers,Nwin,Fs); % check tapers\nparams.tapers=tapers;\nwinstart=1:Nstep:N-Nwin+1;\nnw=length(winstart);\nif trialave==0; dS=zeros(length(phi),nw,Nf,C); else dS=zeros(length(phi),nw,Nf); end; \nfor n=1:nw;\n   indx=winstart(n):winstart(n)+Nwin-1;\n   datawin=data(indx,:);\n   [ds,f]=mtdspectrumc(datawin,phi,params);\n   dS(:,n,:,:)=ds;\nend;\ndS=squeeze(dS);\nsz=size(dS);\n% if length(sz)==3;\n%    dS=permute(dS,[2 1 3 4]);\n% elseif length(phi)>1\n%    dS=permute(dS,[2 1 3]);\n% end;\nwinmid=winstart+round(Nwin/2);\nt=winmid/Fs;\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/spectral_analysis/continuous/mtdspecgramc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5515036370641923}}
{"text": "function out=acos(x)\n\nprecision=x(1).precision;\nmpPi=mppi(precision);\nout=mpPi/2+i.*log(i*x+sqrt(1-x.^2));\n\n%%%precision=x(1).precision;\n%%%out=mp(zeros(size(x)));\n%%%\n%%%mpPi=mppi(precision);\n%%%for ii=1:numel(x)\n%%% out(ii)=mpPi/2+i*log(i*x(ii)+sqrt(1-x(ii)^2));\n%%%end % for ii=1:max(ex,\n\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/acos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5515036314499118}}
{"text": "function [ gradientParams, SigmaInvs, CholDecomps, Sigmas ] = gradientCCRFFull( params, lambda_a, lambda_b, PrecalcBs, x, y, Precalc_yBys, PrecalcBsFlat)\n%GRADIENTPRF Summary of this function goes here\n%   Detailed explanation goes here\n\n    nExamples = numel(x);\n\n    numBetas = size(PrecalcBsFlat{1},2);\n    numAlphas = numel(params) - numBetas;\n    \n    alphasInit = params(1:numAlphas);\n    betasInit = params(numAlphas+1:end);\n    gradientParams = zeros(size(params));\n    \n    % These might be use to calculate the LogLikelihood, don't want to\n    % recompute them\n    SigmaInvs = cell(nExamples, 1);\n    CholDecomps = cell(nExamples, 1);\n    Sigmas = cell(nExamples, 1);\n    gradients = zeros(nExamples, numel(params));\n    for q = 1 : nExamples\n\n        yq = y{q};\n        xq = x{q};\n\n        PrecalcB = PrecalcBs{q};\n        PrecalcB_flat = PrecalcBsFlat{q};\n        \n        [ logGradientsAlphas, logGradientsBetas, SigmaInv, CholDecomp, Sigma ] = gradientCCRF_withoutReg(alphasInit, betasInit, PrecalcB, xq, yq, Precalc_yBys(q, :), PrecalcB_flat);\n        SigmaInvs{q} = SigmaInv;\n        CholDecomps{q} = CholDecomp;\n        Sigmas{q} = Sigma;\n        \n        gradients(q,:) = [logGradientsAlphas; logGradientsBetas];\n    end\n    gradientParams = sum(gradients,1)';\n    regAlpha = alphasInit * lambda_a;\n    regBeta = betasInit * lambda_b;\n    gradientParams = gradientParams - [regAlpha; regBeta];\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/CCRF/lib/gradientCCRFFull.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5515036314499117}}
{"text": "function r = plus(p,q)\n% MEAS/PLUS  Implement p + q for meas.\n\n% make a meas called r\nr = meas();\n\n% give it the right entries\nr.value = p.value + q.value;\nr.error = sqrt(p.error^2 + q.error^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/16606-error-propagation-class/@meas/plus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5515036263886207}}
{"text": "function [Torr] = ftH2O2Torr(ftH2O)\n% Convert pressure from feet of water column at 4 degrees to torr\n% Chad Greene 2012\nTorr = ftH2O*22.4198;", "meta": {"author": "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/ftH2O2Torr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5514663079807439}}
{"text": "function ap=aperiodiccomp(apv,dpv,ashift,f0,nshift,imgi)\n%\tap=aperiodiccomp(apv,dpv,ashift,f0,nshift,fftl,imgi);\n%\tCalculate aperiodicity index \n%\tInput parameters\n%\t\tapv, dpv : Upper and lower envelope\n%\t\tashift\t\t: shift step for aperiodicity index calculation (ms)\n%\t\tf0\t\t\t: fundamental frequency (Hz)\n%\t\tnshift\t\t: shift step for f0 information (ms)\n%\t\tfftl\t\t: FFT size\n%\t\timgi\t\t: display indicator, 1: display on (default) 0: off\n\n%   modified to add the waitbar on 08/Dec./2002\n%\tmodified by Takahashi 10/Aug./2005\n%\tmodified by Kawahara 10/Sept./2005\n\nif nargin==5; imgi=1; end;\n%[nn,mm]=size(nsgram);\nmm=length(f0);\n%%nn=fftl/2+1;\n[~,m2]=size(apv);\n\nx=(0:m2-1)'*ashift;\nxi=(0:mm-1)'*nshift;\nxi=min(max(x),xi);\n\nif imgi==1; hpg=waitbar(0.1,'Interpolating periodicity information'); end;\nif imgi==1; drawnow; end;\n%ap=interp1q(x,(dpv-apv)',xi)';%,'*linear')';\nap = interp1(x, (dpv-apv)',xi, 'linear', 'extrap')';\nif imgi==1; close(hpg); end;\n\n", "meta": {"author": "HidekiKawahara", "repo": "legacy_STRAIGHT", "sha": "964684981fe12cd232c5e882259dff126b3af0f2", "save_path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT", "path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT/legacy_STRAIGHT-964684981fe12cd232c5e882259dff126b3af0f2/src/aperiodiccomp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5514663025387986}}
{"text": "function [lf] = halfspace_medium_leadfield(rd, elc, vol)\n\n% HALFSPACE_MEDIUM_LEADFIELD calculate the halfspace medium leadfield\n% on positions pnt for a dipole at position rd and conductivity cond\n% The halfspace solution requires a plane dividing a conductive zone of\n% conductivity cond, from a non coductive zone (cond = 0)\n%       \n% [lf] = halfspace_medium_leadfield(rd, elc, cond)\n\n% Copyright (C) 2011, Cristiano Micheli and 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 <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nsiz = size(rd);\nif any(siz==1)\n  % positions are specified as a single vector\n  Ndipoles = prod(siz)/3;\n  rd = rd(:)'; % ensure that it is a row vector\nelseif siz(2)==3\n  % positions are specified as a Nx3 matrix -> reformat to a single vector\n  Ndipoles = siz(1);\n  rd = rd';\n  rd = rd(:)'; % ensure that it is a row vector\nelse\n  ft_error('incorrect specification of dipole locations');\nend\n\nNelc     = size(elc,1);\nlf       = zeros(Nelc,3*Ndipoles);\n\nfor i=1:Ndipoles\n  % this is the position of dipole \"i\"\n  dip1 = rd((1:3) + 3*(i-1));\n  \n  % distances electrodes - dipole\n  r1 = elc - ones(Nelc,1) * dip1;\n  \n  % Method of mirror dipoles:\n  % Defines the position of mirror dipoles being symmetric to the plane\n  dip2 = get_mirror_pos(dip,vol);\n  \n  % distances electrodes - mirror dipole\n  r2 = elc - ones(Nelc,1) * dip2;\n  \n  % denominator\n  R1 =  (4*pi*vol.cond) * (sum(r1' .^2 ) .^ 1.5)';\n  % denominator, mirror term\n  R2 = -(4*pi*vol.cond) * (sum(r2' .^2 ) .^ 1.5)';\n  \n  % condition of dipoles falling in the non conductive halfspace  \n  condition = get_dip_halfspace(dip1,vol);\n  \n  invacuum = acos(dot(ori,(P-pnt)./norm(P-pnt))) < pi/2;\n  \n  if invacuum\n    ft_warning('dipole lies on the vacuum side of the plane');\n    lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3);\n  elseif any(R1)==0\n    ft_warning('dipole coincides with one of the electrodes');\n    lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3);\n  else\n    lf(:,(1:3) + 3*(i-1)) = (r ./ [R1 R1 R1]) + (rp ./ [R2 R2 R2]);\n  end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/forward/private/halfspace_medium_leadfield.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5514452598710092}}
{"text": "% op_phaseAlignAverages_fd.m\n% Jamie Near, McGill University 2014.\n% \n% USAGE:\n% [out,phs]=op_phaseAlignAverages_fd(in,minppm,maxppm,Npts,avg,weighting)\n% \n% DESCRIPTION:\n% Perform time-domain spectral registration using a limited range of\n% frequencies and using only phase adjustment (no frequency adjustment).\n% This is rarely used.  \n% \n% INPUTS:\n% in         = Input data structure.\n% minppm     = Minimum of frequency range (ppm).\n% maxppm     = Maximum of frequnecy range (ppm).\n% Npts       = Number of points in time domain to use for alignment.\n% avg        = Align averages to the average of the averages ('y'), or the \n%              first average in the series ('n'); \n% weighting\t = (Optional) Apply less weight to the later points of the fid?\n%\n% OUTPUTS:\n% out        = Output following alignment of averages.  \n% phs        = Vector of phases (in degrees) used for alignment.\n\nfunction [out,phs]=op_phaseAlignAverages_fd(in,minppm,maxppm,Npts,avg,weighting)\n\nif ~in.flags.addedrcvrs\n    error('ERROR:  I think it only makes sense to do this after you have combined the channels using op_addrcvrs.  ABORTING!!');\nend\n\nif nargin<6\n    weighting='n';\nend\n\nif in.dims.subSpecs==0\n    B=1;\nelse\n    B=in.sz(in.dims.subSpecs);\nend\n\nphs=zeros(in.sz(in.dims.averages),B);\nin_avg=op_averaging(in);\nfids=zeros(size(in.fids));\nif weighting=='y' || weighting=='Y'\n    temp=op_freqrange(in_avg,minppm,maxppm);\n    wgt_func=abs(temp.fids).^2;\nelse\n    temp=op_freqrange(in_avg,minppm,maxppm);\n    wgt_func=ones(size(temp.fids));\nend\n\nfor m=1:B\n    if avg=='y'||avg=='Y'\n        base=in_avg;\n        base=op_freqrange(base,minppm,maxppm);\n        base=base.fids(1:Npts,m);\n        begin=1;\n    else\n        base=op_freqrange(in,minppm,maxppm);\n        base=base.fids(1:Npts,1,m);\n        begin=2;\n        fids(:,1,m)=in.fids(:,1,m);\n    end\n    for n=begin:in.sz(in.dims.averages)\n        datarange=op_freqrange(in,minppm,maxppm);\n        phsdiffs=(phase(base)-phase(datarange.fids(1:Npts,n,m)))*180/pi;\n        phs(n,m)=mean(phsdiffs.*wgt_func(1:Npts,m))/mean(wgt_func(1:Npts,m));\n        fids(:,n,m)=addphase(in.fids(:,n,m),phs(n,m));\n    end\nend\n\n\n%re-calculate Specs using fft\nspecs=fftshift(ifft(fids,[],in.dims.t),in.dims.t);\n\n\n%FILLING IN DATA STRUCTURE\nout=in;\nout.fids=fids;\nout.specs=specs;\n\n%FILLING IN THE FLAGS\nout.flags=in.flags;\nout.flags.writtentostruct=1;\nout.flags.freqcorrected=1;\n\nend\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/processingTools/op_phaseAlignAverages_fd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.63341026367784, "lm_q1q2_score": 0.5514452495930464}}
{"text": "function Vf = fillMissingGrid(xGridV, yGridV, zGridV, Vf)\n% function matrixOut = fillMissingGrid(xGridV, yGridV, zGridV, Vf)\n%\n% This function takes in a matrix that contains NaN values and replaces\n% them with values that are linearly interpolated from the surrounding.\n%\n% APA, 10/03/2012\n\n% Find NaN locations\nindNaN = isnan(Vf(:,:,:,1));\n\n% Find Not NaN locations\nindNotNaN = ~isnan(Vf(:,:,:,1));\n\n% Create x,y,z 3D grid\n[xM,yM,zM] = meshgrid(xGridV, yGridV, zGridV);\n\n% Get x,y,z of NaN points\nxNaNv = xM(indNaN);\nyNaNv = yM(indNaN);\nzNaNv = zM(indNaN);\n\n% Get x,y,z of Not-NaN points\nxNotNaNv = xM(indNotNaN);\nyNotNaNv = yM(indNotNaN);\nzNotNaNv = zM(indNotNaN);\n\n% Get values at Not-NaN points\nxVf = Vf(:,:,:,1);\nxVfv = xVf(indNotNaN);\nyVf = Vf(:,:,:,2);\nyVfv = yVf(indNotNaN);\nzVf = Vf(:,:,:,3);\nzVfv = zVf(indNotNaN);\n\n\nFx = TriScatteredInterp([xNotNaNv yNotNaNv zNotNaNv],double(xVfv));\nFy = TriScatteredInterp([xNotNaNv yNotNaNv zNotNaNv],double(yVfv));\nFz = TriScatteredInterp([xNotNaNv yNotNaNv zNotNaNv],double(zVfv));\n\n\nxVfNaN = Fx([xNaNv yNaNv zNaNv]);\nyVfNaN = Fy([xNaNv yNaNv zNaNv]);\nzVfNaN = Fz([xNaNv yNaNv zNaNv]);\n\n\n% xVfNaN = zeros(1,length(xNaNv));\n% yVfNaN = xVfNaN;\n% zVfNaN = xVfNaN;\n% numVoxels = length(xNaNv);\n% \n% for i=1:numVoxels\n%     disp([num2str(i),' / ', num2str(numVoxels)])\n%     %     % Find distance of NaN from all the Not-NaN points\n%     %     distV = (xNaNv(i) - xNotNaNv).^2 + (yNaNv(i) - yNotNaNv).^2 + (zNaNv(i) - zNotNaNv).^2;\n%     %     % Sort by distance\n%     %     [~,indV] = sort(distV);\n%     \n%     %     indKrig = indV(1:20);\n%     indKrig = [];\n%     % Search in neighborhood    \n%     searchRadius = 0.2;\n%     while sum(indKrig>0) < 5\n%         indKrig = (xNaNv(i) - xNotNaNv).^2 + (yNaNv(i) - yNotNaNv).^2 + (zNaNv(i) - zNotNaNv).^2 <= searchRadius^2;\n%         searchRadius = searchRadius + 0.1;\n%     end\n%     % Kriging\n%     dmodelX = dacefit([xNotNaNv(indKrig) yNotNaNv(indKrig) zNotNaNv(indKrig)], double(xVfv(indKrig)), @regpoly0, @correxp, 10, 1e-1, 20);\n%     xVfKrig = predictor([xNaNv(i) yNaNv(i) zNaNv(i)], dmodelX);\n%     dmodelY = dacefit([xNotNaNv(indKrig) yNotNaNv(indKrig) zNotNaNv(indKrig)], double(yVfv(indKrig)), @regpoly0, @correxp, 10, 1e-1, 20);\n%     yVfKrig = predictor([xNaNv(i) yNaNv(i) zNaNv(i)], dmodelY);\n%     dmodelZ = dacefit([xNotNaNv(indKrig) yNotNaNv(indKrig) zNotNaNv(indKrig)], double(zVfv(indKrig)), @regpoly0, @correxp, 10, 1e-1, 20);\n%     zVfKrig = predictor([xNaNv(i) yNaNv(i) zNaNv(i)], dmodelZ);\n%     \n%     xNotNaNv = [xNotNaNv; xNaNv(i)];\n%     yNotNaNv = [yNotNaNv; yNaNv(i)];\n%     zNotNaNv = [zNotNaNv; zNaNv(i)];\n%     xVfv = [xVfv; xVfKrig];\n%     yVfv = [yVfv; yVfKrig];\n%     zVfv = [zVfv; zVfKrig];\n%     \n%     xVfNaN(i) = xVfKrig;\n%     yVfNaN(i) = yVfKrig;\n%     zVfNaN(i) = zVfKrig;\n%     \n% end\n\nxVf(indNaN) = xVfNaN;\nyVf(indNaN) = yVfNaN;\nzVf(indNaN) = zVfNaN;\nVf(:,:,:,1) = xVf;\nVf(:,:,:,2) = yVf;\nVf(:,:,:,3) = zVf;\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/fillMissingGrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5514452410864479}}
{"text": "function [varargout] = likGaussWarpExact(warp, hyp, y, mu, varargin)\n\n% likGaussWarp - Warped Gaussian likelihood for regression. \n% The expression for the likelihood is \n%   likGaussWarp( y | t ) = likGauss( g(y) | t ) * g'(y),\n% where likGauss is the Gaussian likelihood and g is the warping function.\n%\n% The hyperparameters are:\n%\n% hyp = [ theta_1\n%         theta_2\n%           ..\n%         theta_ng\n%         log(sn) ]\n%\n% Here, sn is the standard deviation of the underlying Gaussian and theta_i for\n% i=1..ng are the ng hyperparameters of the warping function g.\n%\n% At the moment, likGaussWarp offers 3 different warping functions:\n% id                   yields g(y) = y  =>  likGaussWarp = likGauss\n% poly<m> e.g. 'poly1' yields g(y) = y  =>  likGaussWarp = likGauss\n%              'poly3' yields g(y) = y + c1*sy*ay^2 + c2*sy*ay^3\n%                             where sy = sign(y), ay = abs(y), cj = exp(theta_j)\n% tanh<m> e.g. 'tanh0' yields g(y) = y  =>  likGaussWarp = likGauss\n%              'tanh2' yields g(y) = y + a1*tanh(b1*(y+c1)) + a2*tanh(b2*(y+c2))\n%                 where aj = exp(theta_j), bj = exp(theta_j+m), bj = theta_j+2*m\n%\n% The code is based on the exposition in the paper Warped Gaussian Processes,\n% NIPS, 2003 by Edward Snelson, Carl Rasmussen and Zoubin Ghahramani.\n%\n% Several modes are provided, for computing likelihoods, derivatives and moments\n% respectively, see likFunctions.m for the details. In general, care is taken\n% to avoid numerical issues when the arguments are extreme.\n%\n% Copyright (c) by Hannes Nickisch, 2013-10-24.\n%\n% See also LIKFUNCTIONS.M.\n\nlik = {@likGauss}; % in principle any likelihood function can be warped but only\n% for homoscedastic likelihoods, in particular Gaussian has feasible integrals\nif numel(warp)==0, warp = 'id'; end               % set default warping function\nif ischar(warp) || isa(warp,'function_handle'); warp = {warp}; end\n\nng = feval(warp{:});        % number of hyperparameters for the warping function\nnhyp = ['(',num2str(ng),'+',feval(lik{:}),')'];      % number of hyperparameters\nif nargin<4, varargout = {nhyp}; return, end       % report number of parameters\nnhyp = eval(nhyp);\nif nhyp>length(hyp), error('not enough hyperparameters'), end\n\n[gy,lgpy] = feval(warp{:},y,hyp(1:ng));                     % evaluate warping function\n\n% [gy,ig(warp,gy,hyp(1:ng))]'\ni = 0; if nargin>6, i = varargin{3}; varargin{3} = varargin{3}-ng; end\nvarargout = cell(nargout,1);              % allocate memory for output arguments\nif i==0 || ng<i                               % only evaluate the required parts\n  [varargout{:}] = feval(lik{:},hyp(ng+1:end),gy,mu,varargin{:});     % eval lik\nend\nif nargin<6                              % prediction mode if inf is not present\n  if numel(y)==0,  y = zeros(size(mu)); end\n  s2zero = 1; if nargin>4, s2 = varargin{1}; end                       % s2==0 ?\n  if nargin>4&&numel(s2)>0&&norm(s2)>eps>0, s2zero = 0; end\n  if s2zero                                                    % log probability\n    lp = likGaussWarpExact(warp, hyp, y, mu, [], 'infLaplace'); s2 = 0*mu;\n  else\n    lp = likGaussWarpExact(warp, hyp, y, mu, s2, 'infEP');               % prediction\n  end\n  if nargout>0, varargout{1} = lp; end                       % works for any lik\n  % the predictive moments are very hard to compute for lik not being likGauss\n  if nargout>1\n    ymu = mu;                                                % first g(y) moment\n    sn2 = exp(2*hyp(ng+1));                            % Gaussian noise variance\n    ys2 = s2 + sn2;                                         % second g(y) moment\n%     ymuM = ig(warp,ymu,hyp(1:ng));                                    % median\n%     yupp = ig(warp,ymu+2*sqrt(ys2),hyp(1:ng));       % 95% confidence interval\n%     ylow = ig(warp,ymu-2*sqrt(ys2),hyp(1:ng));\n%     ys2C = (yupp-ylow).^2/16;\n\n%    N = 20; [t,w] = gauher(N); oN = ones(1,N);     % Gaussian-Hermite quadrature\n%    Z = sqrt(ys2(:))*t'+ymu(:)*oN;\n%    Y = ig(warp,Z,hyp(1:ng));\n%    ymu = Y*w; ys2 = (Y-ymu*oN).^2*w;                % first and second y moment\n    \n    ymu = feval(warp{:},mu,hyp(1:ng),'inv');\n    % muin = feval(warp{:},mu,hyp(1:ng));\n    %ylow = feval(warp{:},muin-10*sqrt(ys2),hyp(1:ng),'inv');\n    ylow = feval(warp{:},mu-sqrt(ys2),hyp(1:ng),'inv');\n    ys2 = (ymu-ylow).^2;\n    \n    varargout{2} = reshape(ymu,size(mu));\n    if nargout>2\n      varargout{3} = ys2;\n    end\n  end\n\nelse\n  inf = varargin{2};                                    % obtain input variables\n  switch inf\n  case {'infLaplace','infEP'}                     % they have the same structure\n    if nargin<7                                             % no derivative mode\n      if nargout>0, varargout{1} = varargout{1} + lgpy; end\n    else                                                       % derivative mode\n      if i<=ng                  % derivatives w.r.t. warping function parameters\n        n = max([numel(y),numel(mu)]);\n        for j=2:nargout, varargout{j} = zeros(n,1); end\n        [dgy,dlgpy] = feval(warp{:},y,hyp(1:ng),i);    % warping function derivative\n        out = cell(nargout+1,1);                               % allocate memory\n        [out{:}] = likGaussWarpExact(warp, hyp, y, mu, varargin{1:2});    % query lik\n        % works only for homoscedastic likelihoods where y and mu can be swapped\n        if nargout>0, varargout{1} = dlgpy - out{2}.*dgy; end % apply chain rule\n        if nargout>1, varargout{2} =       - out{3}.*dgy; end\n        if nargout>2, varargout{3} =       - out{4}.*dgy; end\n      end\n    end\n\n  case 'infVB'           % output does not depend on mu and following parameters\n  end\nend", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/warp/likGaussWarpExact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5514452332904198}}
{"text": "function [ mK ] = CreateConvMtx( vK, numElements, operationMode, convShape )\n%UNTITLED6 Summary of this function goes here\n%   Detailed explanation goes here\n\nOPERATION_MODE_CONVOLUTION = 1;\nOPERATION_MODE_CORRELATION = 2;\n\nCONVOLUTION_SHAPE_FULL         = 1;\nCONVOLUTION_SHAPE_SAME         = 2;\nCONVOLUTION_SHAPE_VALID        = 3;\n\nswitch(operationMode)\n    case(OPERATION_MODE_CONVOLUTION)\n        vK = vK(end:-1:1);\n    case(OPERATION_MODE_CORRELATION)\n        % vK = vK; %<! Default Code is correlation\nend\n\nkernelLength    = length(vK);\nmK = zeros([numElements + kernelLength - 1, numElements]);\n\nfor ii = 1:numElements + kernelLength - 1\n    kernelLastIdx     = min(kernelLength, kernelLength + numElements - ii);\n    kernelFirstIdx    = max(kernelLastIdx - ii + 1, 1);\n    \n    kernelEffLength = kernelLastIdx - kernelFirstIdx + 1;\n    \n    colLastIdx   = min(ii, numElements);\n    colFirstIdx  = colLastIdx - kernelEffLength + 1;\n    \n    mK(ii, colFirstIdx:colLastIdx)   = vK(kernelFirstIdx:kernelLastIdx);\nend\n\nswitch(convShape)\n    case(CONVOLUTION_SHAPE_FULL)\n        % mK = mK;\n    case(CONVOLUTION_SHAPE_SAME)\n        rowIdxFirst = 1 + floor(kernelLength / 2);\n        rowIdxLast  = rowIdxFirst + numElements - 1;\n        mK = mK(rowIdxFirst:rowIdxLast, :);\n    case(CONVOLUTION_SHAPE_VALID)\n        mK = mK(kernelLength:end - kernelLength + 1, :);\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/Q2969/CreateConvMtx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.5513730565463393}}
{"text": "function []=plot_reprojectVSreal_points_stereo(I1,I2,imagePoints,stereoParams,IndpairsUsed)\n%% function for plot each image with reprojected points vs. real points and straight lines, and reprojection error statistics in STEP0\n%\n% INPUTS:\n% * CBimagesInfo\n% * cameraCBparameters:  a structure containing all the calibration parameters created in STEP0\n%\n%%\n\n% plot each image with reprojected points vs. real points and straight lines\nNimages=length(IndpairsUsed);\nreprojectedPoints1=stereoParams.CameraParameters1.ReprojectedPoints;\nreprojectedPoints2=stereoParams.CameraParameters2.ReprojectedPoints;\nreprojectionErrors1=stereoParams.CameraParameters1.ReprojectionErrors;\nreprojectionErrors2=stereoParams.CameraParameters2.ReprojectionErrors;\n\nif (stereoParams.CameraParameters1.ImageSize(1)>=stereoParams.CameraParameters1.ImageSize(2))\n    n=1; m=8; p1=1:3; p2=4; p3=5:7; p4=8;\nelse\n   n=2; m=6; p1=1:5; p2=6; p3=7:11; p4=12;\nend\n    \n\n% PLOT\n% define tabs\nf = figure('name','Reprojected points on all images. Scroll between tabs to view the different images','units','normalized','outerposition',[.1 .1 .8 .8]);\ntabgp = uitabgroup(f);\n\nicount=0;\nfor iplot=IndpairsUsed'\n    icount=icount+1;\n    %plot\n    tab(icount) = uitab(tabgp,'Title',['IM' num2str(iplot)]);\n    \n    axes('Parent',tab(icount)); % somewhere to plot\n    \n    subplot(n,m,p1)\n    imshow(I1(:,:,:,iplot)); hold all;\n    plot(imagePoints(:,1,icount,1), imagePoints(:,2,icount,1),'go','linewidth',1.5);\n    plot(reprojectedPoints1(:,1,icount),reprojectedPoints1(:,2,icount),'r+','linewidth',1.5);\n    title(['Camera left, Image ' num2str(iplot)]);\n    drawnow\n    legend('Detected Points','Reprojected Points');\n    hold off;\n    \n    reprojectionErrorsNow1=reprojectionErrors1(:,:,icount);\n    reprojectionErrorsMgnNow1=sqrt(sum(reprojectionErrorsNow1.^2,2));\n    reprojectionErrorsNow1=[reprojectionErrorsNow1 reprojectionErrorsMgnNow1];\n    \n    subplot(n,m,p2)\n    boxplot(reprojectionErrorsNow1,'Labels',{'X','Y','Mgn'});\n    ylim([-max(abs(reprojectionErrorsNow1(:))) max(abs(reprojectionErrorsNow1(:)))]);\n    title({'Reprojection error'; 'statistics [pix]'});\n    \n    subplot(n,m,p3)\n    imshow(I2(:,:,:,iplot)); hold all;\n    plot(imagePoints(:,1,icount,2), imagePoints(:,2,icount,2),'go','linewidth',1.5);\n    plot(reprojectedPoints2(:,1,icount),reprojectedPoints2(:,2,icount),'r+','linewidth',1.5);\n    title(['Camera right, Image ' num2str(iplot)]);\n    drawnow\n    legend('Detected Points','Reprojected Points');\n    hold off;\n    \n    reprojectionErrorsNow2=reprojectionErrors2(:,:,icount);\n    reprojectionErrorsMgnNow2=sqrt(sum(reprojectionErrorsNow2.^2,2));\n    reprojectionErrorsNow2=[reprojectionErrorsNow2 reprojectionErrorsMgnNow2];\n    \n    subplot(n,m,p4)\n    boxplot(reprojectionErrorsNow2,'Labels',{'X','Y','Mgn'});\n    ylim([-max(abs(reprojectionErrorsNow2(:))) max(abs(reprojectionErrorsNow2(:)))]);\n    title({'Reprojection error'; 'statistics [pix]'});\n    \nend\n\n\nend\n\n \n%% \n% MultiDIC: a MATLAB Toolbox for Multi-View 3D Digital Image Correlation\n% \n% License: <https://github.com/MultiDIC/MultiDIC/blob/master/LICENSE.txt>\n% \n% Copyright (C) 2018  Dana Solav\n% \n% If you use the toolbox/function for your research, please cite our paper:\n% <https://engrxiv.org/fv47e>", "meta": {"author": "MultiDIC", "repo": "MultiDIC", "sha": "d363c3ea74673e58df275d4a4c8e528ef5472acb", "save_path": "github-repos/MATLAB/MultiDIC-MultiDIC", "path": "github-repos/MATLAB/MultiDIC-MultiDIC/MultiDIC-d363c3ea74673e58df275d4a4c8e528ef5472acb/lib_MultiDIC/plot_reprojectVSreal_points_stereo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.551373048680268}}
{"text": "function nwspgr_size_test ( )\n\n%*****************************************************************************80\n%\n%% NWSPGR_SIZE_TEST tests NWSPGR_SIZE.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    08 January 2013\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'NWSPGR_SIZE_TEST:\\n' );\n  fprintf ( 1, '  NWSPGR_SIZE returns the size of a sparse grid, based on:\\n' );\n  fprintf ( 1, '  one of the built-in 1D rules, or a family of 1D rules\\n' );\n  fprintf ( 1, '  supplied by the user.\\n' );\n\n  d = 2;\n  k = 3;\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Kronrod-Patterson, [0,1], Dim %d, Level %d Symmetric\\n', d, k );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Full          %4d\\n', nwspgr_size ( 'kpu', d, k, 1, 0 ) );\n  fprintf ( 1, '  Compressed    %4d\\n', nwspgr_size ( 'kpu', d, k, 1, 1 ) );\n\n  d = 2;\n  k = 3;\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Kronrod-Patterson, (-oo,+oo), Dim %d, Level %d Symmetric\\n', d, k );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Full          %4d\\n', nwspgr_size ( 'kpn', d, k, 1, 0 ) );\n  fprintf ( 1, '  Compressed    %4d\\n', nwspgr_size ( 'kpn', d, k, 1, 1 ) );\n\n  d = 2;\n  k = 3;\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Gauss-Legendre, [0,1], Dim %d, Level %d Symmetric\\n', d, k );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Full          %4d\\n', nwspgr_size ( 'gqu', d, k, 1, 0 ) );\n  fprintf ( 1, '  Compressed    %4d\\n', nwspgr_size ( 'gqu', d, k, 1, 1 ) );\n\n  d = 2;\n  k = 3;\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Gauss Hermite, (-oo,+oo), [0,1], Dim %d, Level %d Symmetric\\n', d, k );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Full          %4d\\n', nwspgr_size ( 'gqn', d, k, 1, 0 ) );\n  fprintf ( 1, '  Compressed    %4d\\n', nwspgr_size ( 'gqn', d, k, 1, 1 ) );\n\n  d = 2;\n  k = 3;\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Clenshaw Curtis, [-1,+1], [0,1], Dim %d, Level %d Unsymmetric\\n', d, k );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Full        %4d\\n', nwspgr_size ( 'cce', d, k, 0, 0 ) );\n  fprintf ( 1, '  Compressed  %4d\\n', nwspgr_size ( 'cce', d, k, 0, 1 ) );\n%\n%  Do a table.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Dimension / Level table for Clenshaw Curtis Exponential (CCE) Compressed\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ' Dim:  ' )\n  for d = 1 : 10\n    fprintf ( 1, '  %6d', d );\n  end\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'Level:\\n' );\n  for k = 1 : 6\n    fprintf ( 1, '  %2d:  ', k );\n    for d = 1 : 10\n      fprintf ( 1, '  %6d', nwspgr_size ( 'cce', d, k, 0, 1 ) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n%\n%  Do a table.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Dimension / Level table for Clenshaw Curtis Exponential (CCE) Uncompressed\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ' Dim:  ' )\n  for d = 1 : 10\n    fprintf ( 1, '  %6d', d );\n  end\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'Level:\\n' );\n  for k = 1 : 6\n    fprintf ( 1, '  %2d:  ', k );\n    for d = 1 : 10\n      fprintf ( 1, '  %6d', nwspgr_size ( 'cce', d, k, 0, 0 ) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n%\n%  Do a GLL table.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Dimension / Level table for Gauss-Legendre Linear (GLL) Compressed\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ' Dim:  ' )\n  for d = 1 : 6\n    fprintf ( 1, '  %6d', d );\n  end\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'Level:\\n' );\n  for k = 1 : 11\n    fprintf ( 1, '  %2d:  ', k );\n    for d = 1 : 6\n      fprintf ( 1, '  %6d', nwspgr_size ( 'gqu2', d, k, 0, 1 ) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n%\n%  Do a GLO table.\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  Dimension / Level table for Gauss-Legendre-Odd (GLO) Compressed\\n' );\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, ' Dim:  ' )\n  for d = 1 : 6\n    fprintf ( 1, '  %6d', d );\n  end\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'Level:\\n' );\n  for k = 1 : 11\n    fprintf ( 1, '  %2d:  ', k );\n    for d = 1 : 6\n      fprintf ( 1, '  %6d', nwspgr_size ( 'glo', d, k, 0, 1 ) );\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_hw/nwspgr_size_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5513730453351824}}
{"text": "function test007 ( )\n\n%*****************************************************************************80\n%\n%% TEST007 tests TET_MESH_SEARCH_NAIVE and TET_MESH_SEARCH_DELAUNAY.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    19 August 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  test_num = 5;\n  tet_order = 4;\n  seed = 123456789;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'TEST007\\n' );\n  fprintf ( 1, '  TET_MESH_SEARCH_NAIVE uses a naive algorithm\\n' );\n  fprintf ( 1, '  to search a tetrahedral mesh for the tetrahedron\\n' );\n  fprintf ( 1, '  containing a point.\\n' );\n  fprintf ( 1, '  TET_MESH_SEARCH_DELAUNAY uses a faster algorithm\\n' );\n  fprintf ( 1, '  which is appropriate if the tet mesh is Delaunay.\\n' );\n%\n%  Set up the example tetrahedron mesh.\n%\n  [ node_num, tet_num ] = tet_mesh_order4_example_size ( );\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, '  This mesh has tetrahedron order %d\\n', tet_order );\n  fprintf ( 1, '  The number of tetrahedrons is   %d\\n', tet_num );\n\n  [ node_xyz, tet_node ] = tet_mesh_order4_example_set ( node_num, tet_num );\n%\n%  TET_NEIGHBOR is needed for the Delaunay search.\n%\n  tet_neighbor = tet_mesh_neighbor_tets ( tet_order, tet_num, tet_node );\n\n  for test = 1 : test_num\n%\n%  Choose a tetrahedral index at random.\n%\n    [ tet1, seed ] = i4_uniform ( 1, tet_num, seed );\n    fprintf ( 1, '\\n' );\n    fprintf ( 1, '  Point was chosen from tetrahedron    %8d\\n', tet1 );\n%\n%  Choose a point at random from the tetrahedron.\n%\n    [ p, seed ] = tetrahedron_sample ( node_xyz(1:3,tet_node(1:4,tet1)), 1, seed );\n%\n%  Naive search.\n%\n    [ tet2, step_num ] = tet_mesh_search_naive ( node_num, node_xyz, ...\n      tet_order, tet_num, tet_node, p );\n\n    fprintf ( 1, '  Naive search ended in tetrahedron    %8d after %d steps\\n', ...\n      tet2, step_num );\n%\n%  Delaunay search.\n% \n    [ tet3, face, step_num ] = tet_mesh_search_delaunay ( node_num, ...\n      node_xyz, tet_order, tet_num, tet_node, tet_neighbor, p );\n\n    fprintf ( 1, ...\n      '  Delaunay search ended in tetrahedron %8d after %d steps.\\n', ...\n      tet3, step_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/tet_mesh/tet_mesh_test007.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5513730408141965}}
{"text": "function c8mat_identity_test ( )\n\n%*****************************************************************************80\n%\n%% C8MAT_IDENTITY_TEST tests C8MAT_IDENTITY.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    14 February 2015\n%\n%  Author:\n%\n%    John Burkardt\n%\n  m = 4;\n  n = 4;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'C8MAT_IDENTITY_TEST\\n' );\n  fprintf ( 1, '  C8MAT_IDENTITY returns the complex identity matrix.\\n' );\n\n  a = c8mat_identity ( n );\n\n  c8mat_print ( m, n, a, '  The identity matrix:' );\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/c8lib/c8mat_identity_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.551360806799216}}
{"text": "function bounds = computeBounds(config)\n% bounds = computeBounds(config)\n%\n% This function returns the bounds on the decision variables, to be passed\n% to the trajectory optimization solver.\n%\n% INPUTS:\n%   config.dyn = physical parameters of the model\n%       .m1 = cart mass\n%       .m2 = pole mass\n%       .g = gravity\n%       .l = pendulum length\n%\n% OUTPUTS:\n%   bounds = struct of bounds for decision variables:\n%       .initialTime.lower = scalar\n%       .initialTime.upper = scalar\n%       .finalTime.lower = scalar\n%       .finalTime.upper = scalar\n%       .initialState.lower = [ns, 1]\n%       .initialState.upper = [ns, 1]\n%       .finalState.lower = [ns, 1]\n%       .finalState.upper = [ns, 1]\n%       .state.lower = [ns, 1]\n%       .state.upper = [ns, 1]\n%       .control.lower = [nc, 1]\n%       .control.upper = [nc, 1]\n%\n\n\n% Unpack physical parameters\nm1 = config.dyn.m1;\n% m2 = config.dyn.m2;\ng = config.dyn.g;\nl = config.dyn.l;\n\n% Boundry values\nbounds.initialState.lower = [0;0;0;0];\nbounds.initialState.upper = bounds.initialState.lower;\nbounds.finalState.lower = [config.guess.state(1:2,end);0;0];\nbounds.finalState.upper = bounds.finalState.lower;\n\n% Bounds on duration (total trajectory time)\nwn = sqrt(l/g);\nbounds.initialTime.lower = 0;\nbounds.initialTime.upper = 0;\nbounds.finalTime.lower = 0.5*(2*pi*wn);\nbounds.finalTime.upper = 4*(2*pi*wn);\n\n% Bounds on state:\nbounds.state.lower = [-1.0*l; -2*pi; -10*l/wn; -10*pi/wn];\nbounds.state.upper = [1.0*l; 2*pi; 10*l/wn; 10*pi/wn];\n\n% Bounds on control:\nbounds.control.lower = -5*m1*g;\nbounds.control.upper = 5*m1*g;\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/TrajectoryOptimization/Example_2_CartPole/computeBounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5513607915542047}}
{"text": "function [output] = F_tanh(input_layer)\ninput = input_layer.a;\noutput = tanh(input);\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/graph/F_tanh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.551360779862138}}
{"text": "function [mu,sig,alpha,beta] = fit_eeg_distribution(X,min_clean_fraction,max_dropout_fraction,quants,step_sizes,beta)\n% Estimate the mean and standard deviation of clean EEG from contaminated data.\n% [Mu,Sigma,Alpha,Beta] = fit_eeg_distribution(X,MinCleanFraction,MaxDropoutFraction,FitQuantiles,StepSizes,ShapeRange)\n%\n% This function estimates the mean and standard deviation of clean EEG from a sample of amplitude\n% values (that have preferably been computed over short windows) that may include a large fraction\n% of contaminated samples. The clean EEG is assumed to represent a generalized Gaussian component in\n% a mixture with near-arbitrary artifact components. By default, at least 25% (MinCleanFraction) of\n% the data must be clean EEG, and the rest can be contaminated. No more than 10%\n% (MaxDropoutFraction) of the data is allowed to come from contaminations that cause lower-than-EEG\n% amplitudes (e.g., sensor unplugged). There are no restrictions on artifacts causing\n% larger-than-EEG amplitudes, i.e., virtually anything is handled (with the exception of a very\n% unlikely type of distribution that combines with the clean EEG samples into a larger symmetric\n% generalized Gaussian peak and thereby \"fools\" the estimator). The default parameters should be\n% fine for a wide range of settings but may be adapted to accomodate special circumstances.\n%\n% The method works by fitting a truncated generalized Gaussian whose parameters are constrained by\n% MinCleanFraction, MaxDropoutFraction, FitQuantiles, and ShapeRange. The alpha and beta parameters\n% of the gen. Gaussian are also returned. The fit is performed by a grid search that always finds a\n% close-to-optimal solution if the above assumptions are fulfilled.\n%\n% In:\n%   X : vector of amplitude values of EEG, possible containing artifacts\n%       (coming from single samples or windowed averages)\n%\n%   MinCleanFraction : Minimum fraction of values in X that needs to be clean\n%                      (default: 0.25)\n%\n%   MaxDropoutFraction : Maximum fraction of values in X that can be subject to\n%                        signal dropouts (e.g., sensor unplugged) (default: 0.1)\n%\n%   FitQuantiles : Quantile range [lower,upper] of the truncated generalized Gaussian distribution\n%                  that shall be fit to the EEG contents (default: [0.022 0.6])\n%\n%   StepSizes : Step size of the grid search; the first value is the stepping of the lower bound\n%               (which essentially steps over any dropout samples), and the second value\n%               is the stepping over possible scales (i.e., clean-data quantiles)\n%               (default: [0.01 0.01])\n%\n%   ShapeRange : Range that the clean EEG distribution's shape parameter beta may take (default:\n%                1.7:0.15:3.5)\n%\n% Out:\n%   Mu : estimated mean of the clean EEG distribution\n%\n%   Sigma : estimated standard deviation of the clean EEG distribution\n%\n%   Alpha : estimated scale parameter of the generalized Gaussian clean EEG distribution (optional)\n%\n%   Beta : estimated shape parameter of the generalized Gaussian clean EEG distribution (optional)\n%\n%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n%                                2013-08-15\n\n% Copyright (C) Christian Kothe, SCCN, 2013, christiankothe@gmail.com\n%\n% This program is free software; you can redistribute it and/or modify it under the terms of the GNU\n% General Public License as published by the Free Software Foundation; either version 2 of the\n% License, or (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\n% even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n% General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License along with this program; if not,\n% write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307\n% USA\n\n% assign defaults\nif ~exist('min_clean_fraction','var') || isempty(min_clean_fraction)\n    min_clean_fraction = 0.25; end\nif ~exist('max_dropout_fraction','var') || isempty(max_dropout_fraction)\n    max_dropout_fraction = 0.1; end\nif ~exist('quants','var') || isempty(quants)\n    quants = [0.022 0.6]; end\nif ~exist('step_sizes','var') || isempty(step_sizes)\n    step_sizes = [0.01 0.01]; end\nif ~exist('beta','var') || isempty(beta)\n    beta = 1.7:0.15:3.5; end\n\n% sanity checks\nif ~isvector(quants) || numel(quants) > 2\n    error('Fit quantiles needs to be a 2-element vector (support for matrices deprecated).'); end\nif any(quants(:)<0) || any(quants(:)>1)\n    error('Unreasonable fit quantiles.'); end\nif any(step_sizes<0.0001) || any(step_sizes>0.1)\n    error('Unreasonable step sizes.'); end\nif any(beta>=7) || any(beta<=1)\n    error('Unreasonable shape range.'); end\n\n% sort data so we can access quantiles directly\nX = double(sort(X(:)));\nn = length(X);\n\n% calc z bounds for the truncated standard generalized Gaussian pdf and pdf rescaler\nfor b=1:length(beta)    \n    zbounds{b} = sign(quants-1/2).*gammaincinv(sign(quants-1/2).*(2*quants-1),1/beta(b)).^(1/beta(b)); %#ok<*AGROW>\n    rescale(b) = beta(b)/(2*gamma(1/beta(b)));\nend\n\n% determine the quantile-dependent limits for the grid search\nlower_min = min(quants);                    % we can generally skip the tail below the lower quantile\nmax_width = diff(quants);                   % maximum width is the fit interval if all data is clean\nmin_width = min_clean_fraction*max_width;   % minimum width of the fit interval, as fraction of data\n\n% get matrix of shifted data ranges\nX = X(bsxfun(@plus,(1:round(n*max_width))',round(n*(lower_min:step_sizes(1):lower_min+max_dropout_fraction))));\nX1 = X(1,:); X = bsxfun(@minus,X,X1);\n\nopt_val = Inf;\n% for each interval width...\nfor m = round(n*(max_width:-step_sizes(2):min_width))\n    % scale and bin the data in the intervals\n    nbins = round(3*log2(1+m/2));\n    H = bsxfun(@times,X(1:m,:),nbins./X(m,:));\n    logq = log(histc(H,[0:nbins-1,Inf]) + 0.01);\n    \n    % for each shape value...\n    for b=1:length(beta)\n        bounds = zbounds{b};\n        % evaluate truncated generalized Gaussian pdf at bin centers\n        x = bounds(1)+(0.5:(nbins-0.5))/nbins*diff(bounds);\n        p = exp(-abs(x).^beta(b))*rescale(b); p=p'/sum(p);\n        \n        % calc KL divergences\n        kl = sum(bsxfun(@times,p,bsxfun(@minus,log(p),logq(1:end-1,:)))) + log(m);\n        \n        % update optimal parameters\n        [min_val,idx] = min(kl);\n        if min_val < opt_val\n            opt_val = min_val;\n            opt_beta = beta(b);\n            opt_bounds = bounds;\n            opt_lu = [X1(idx) X1(idx)+X(m,idx)];\n        end\n    end\nend\n\n% recover distribution parameters at optimum\nalpha = (opt_lu(2)-opt_lu(1))/diff(opt_bounds);\nmu = opt_lu(1)-opt_bounds(1)*alpha;\nbeta = opt_beta;\n\n% calculate the distribution's standard deviation from alpha and beta\nsig = sqrt((alpha^2)*gamma(3/beta)/gamma(1/beta));\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/misc/fit_eeg_distribution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5513071791575295}}
{"text": "function test_bug1082\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_prepare_vol_sens ft_prepare_headmodel ft_compute_leadfield ft_plot_topo3d ft_headmodel_openmeeg\n\nfprintf('***  DIAGNOSTICAL INFORMATION ***\\n');\nfprintf('test script is running on host: %s\\n', gethostname());\n\n%%\n\n% generate a unit sphere\n[pnt, tri] = mesh_sphere(162);\n\n% create the BEM geometries (in mm)\nbnd = [];\nbnd.pnt = pnt * 100;\nbnd.tri = tri; % normals outwards\n% bnd.tri = fliplr(tri); % normals inwards\n\n% create a set of electrodes\nsel = find(pnt(:,3)>0);\nsens = [];\nsens.chanpos = pnt(sel,:) * 100;\nsens.elecpos = sens.chanpos;\nfor i=1:length(sel)\n  sens.label{i} = sprintf('chan%03d', i);\nend\n\n% this is the position of the dipole\npos = [0 0 50];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% calculate volume conductors\n\ntmpcfg = [];\ntmpcfg.conductivity = [1];\ntmpcfg.method = 'singlesphere';\nvol1 = ft_prepare_headmodel(tmpcfg,bnd);\n[vol1, sens1] = ft_prepare_vol_sens(vol1, sens);\nlf1 = ft_compute_leadfield(pos, sens1, vol1);\n\ntmpcfg = [];\ntmpcfg.conductivity = [1];\ntmpcfg.method = 'openmeeg';\nvol2 = ft_prepare_headmodel(tmpcfg,bnd);\n[vol2, sens2] = ft_prepare_vol_sens(vol2, sens);\nlf2 = ft_compute_leadfield(pos, sens2, vol2);\n\ntmpcfg = [];\ntmpcfg.conductivity = [1];\ntmpcfg.method = 'dipoli';\nvol3 = ft_prepare_headmodel(tmpcfg,bnd);\n[vol3, sens3] = ft_prepare_vol_sens(vol3, sens);\nlf3 = ft_compute_leadfield(pos, sens3, vol3);\n\n%%\n\nfigure;\nsubplot(2,2,1); ft_plot_topo3d(sens1.chanpos, lf1(:,1))\nsubplot(2,2,2); ft_plot_topo3d(sens1.chanpos, lf1(:,2))\nsubplot(2,2,3); ft_plot_topo3d(sens1.chanpos, lf1(:,3))\ncolorbar\n\nfigure;\nsubplot(2,2,1); ft_plot_topo3d(sens2.chanpos, lf2(:,1))\nsubplot(2,2,2); ft_plot_topo3d(sens2.chanpos, lf2(:,2))\nsubplot(2,2,3); ft_plot_topo3d(sens2.chanpos, lf2(:,3))\ncolorbar\n\nfigure;\nsubplot(2,2,1); ft_plot_topo3d(sens3.chanpos, lf3(:,1))\nsubplot(2,2,2); ft_plot_topo3d(sens3.chanpos, lf3(:,2))\nsubplot(2,2,3); ft_plot_topo3d(sens3.chanpos, lf3(:,3))\ncolorbar\n\n% figure;\n% subplot(2,2,1); ft_plot_topo3d(senst.chanpos, lft(:,1))\n% subplot(2,2,2); ft_plot_topo3d(senst.chanpos, lft(:,2))\n% subplot(2,2,3); ft_plot_topo3d(senst.chanpos, lft(:,3))\n% colorbar\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/failed_bug1082.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5513071791575295}}
{"text": "function kern = svargplvmInitDynKernel(kern, globalOpt, optionsDyn, indexInComp)\n\n% SVARGPLVMINITDYNKERNEL\n% VARGPLVM\n\nX = optionsDyn.t;\n\nfprintf('# Initialising kernel %s', kern.type);\nif nargin > 3\n    fprintf(' in place %d of the comp structure.\\n', indexInComp);\nelse\n    fprintf('\\n');\nend\n\n% This is a recursive function. The recursion ending condition is for a\n% kernel to not be a compound.\nif isfield(kern, 'comp')\n    for i=1:length(kern.comp)\n        if ~isfield(kern.comp{i}, 'index') || isempty(kern.comp{i}.index)\n            curInds = 1:kern.comp{i}.inputDimension;\n        else\n            curInds = kern.comp{i}.index;\n        end\n        curOptionsDyn = optionsDyn;\n        curOptionsDyn.t = X(:, curInds);\n        kern.comp{i} = svargplvmInitDynKernel(kern.comp{i}, globalOpt, curOptionsDyn, i);\n    end\nelse\n    % This is not a compound kernel, so we can initialise this signel\n    % element.\n    kernelType = kern.type;\n   % if strcmp(kernelType, 'white')\n   %     kern.variance = 1e-2; % Usual values: 1e-1, 1e-3\n   % end\n    \n    if strcmp(kernelType, 'whitefixed')\n        kern.variance = globalOpt.fixedwhiteVar;\n        fprintf(1,'# fixedwhite variance: %d\\n',globalOpt.fixedwhiteVar);\n    end\n    \n\n    if strcmp(kernelType, 'bias')\n        kern.variance = 0.1;\n        fprintf(1,'# Bias variance: %d\\n',kern.variance);\n    end\n    \n     \n    if strcmp(kernelType, 'rbfperiodic') || strcmp(kernelType, 'rbfperiodic2')\n        kern.period = globalOpt.periodicPeriod;\n        fprintf(1,'# periodic period %d\\n',globalOpt.periodicPeriod);\n         dst = dist2(optionsDyn.t, optionsDyn.t);\n         lb = min(dst(:));\n         ub = max(dst(:));\n         inv_width = 2 / (ub+lb);\n         inv_width = globalOpt.inverseWidthMult / (ub+lb); %% NEW\n         kern.inverseWidth = inv_width;   \n         if strcmp(kernelType, 'rbfperiodic2')\n             kern.factor = 2*pi/kern.period;\n         end\n    end\n        \n    \n    \n    % The following is related to the expected number of\n    % zero-crossings.(larger inv.width numerator, rougher func)\n    if strcmp(kernelType,'rbf') || strcmp(kernelType,'matern32') || strcmp(kernelType,'matern52')\n        % NEW\n         dst = dist2(optionsDyn.t, optionsDyn.t);\n         lb = min(dst(:));\n         ub = max(dst(:));\n         %inv_width = 2 / (ub+lb);\n         inv_width = globalOpt.inverseWidthMult / (ub+lb); %% NEW\n        if strcmp(kernelType,'rbf')\n            kern.inverseWidth = inv_width;\n        elseif strcmp(kernelType, 'matern32') || strcmp(kernelType, 'matern52')\n            kern.lengthScale = 1/inv_width;\n        end\n         \n         %kern.comp{1}.inverseWidth = inv_width;\n        %kern.inverseWidth = optionsDyn.inverseWidth./(((max(max(optionsDyn.t))-min(min(optionsDyn.t)))).^2);\n\n        if ~globalOpt.mappingInitialisation && (exist('indexInComp') && indexInComp == 1)\n            kern.variance = 1;\n        end\n    end\nend\n\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/svargplvmInitDynKernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5513071782125745}}
{"text": "function residual ( )\n\n%*****************************************************************************80\n%\n%% RESIDUAL assembles the residual vector.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 April 2006\n%\n  global area\n  global beta\n  global difeta\n  global fzero\n  global indx\n  global kappa\n  global lambda1\n  global lambda2\n  global m\n  global nel\n  global neqn\n  global nnodes\n  global node\n  global nq\n  global nu1\n  global nu2\n  global nunk\n  global xc\n  global xl\n  global xr\n\n  resid = zeros(nunk*neqn,1 ); \n  xq = zeros(3);\n  wq = zeros(3);\n%\n%  Set up quadrature information on [-1,1]\n%\n  [ xq, wq ] = gauss3pt;\n\n  for it = 1 : nel\n\n    for iq = 1 : nq\n\n      x = xc(node(it,1)) + area(it) / 2.0 * ( xq(iq) + 1.0 );\n      ar = area(it) * wq(iq);\n%\n%  Evaluate solutions at quadrature points.\n%\n      [ vh, vhx ] = eval_pt ( x, it, vcur ); \n      [ ch, chx ] = eval_pt ( x, it, ccur ); \n      [ fh, fhx ] = eval_pt ( x, it, fcur ); \n      [ etah, etahx ] = eval_pt ( x, it, etacur );\n      [ vhold, vhxold ] = eval_pt ( x, it, vold ); \n      [ chold, chxold ] = eval_pt ( x, it, cold ); \n      [ fhold, fhxold ] = eval_pt ( x, it, fold ); \n      [ etahold, etahxold ] = eval_pt ( x, it, etaold );\n\n      tauxovertau = tau_prob ( fh, fhx, ch, chx );\n\n      for nuk = 1 : 4 \n\n        for in = 1 : nnodes\n\n          ip = node(it,in);\n          i = indx(ip);\n\n          if ( 0 < i )\n\n            [ bb, bx ] = quadbf ( x, it, in, xc, node ); \n\n            term_linear = 0;\n            term_nonlin = 0;\n\n            if ( nuk == 1 )\n              term_time = ( vh - vhold ) / dt; \n              term_nonlin = ( lambda1 * vh * etah ) / ( 1.0 + nu1 * vh );\n            elseif ( nuk == 2 )\n              term_time = ( ch - chold ) / dt;\n              term_nonlin = -lambda1 * vh * etah / ( 1.0 + nu1 * vh );\n            elseif ( nuk == 3 )\n              term_time = ( fh - fhold ) / dt;\n              term_nonlin = -beta * fh * ( fzero - fh ) * etah + ...\n                lambda2 * ch * fh / ( 1.0 + nu2 * ch);\n            elseif ( nuk == 4 )\n              term_time = ( etah - etahold ) / dt;\n              term_linear = difeta * bx * etah * ( etahx / etah - tauxovertau );\n            end\n\n            k = i + ( nuk - 1 ) * nunk;\n            [rhs_source] = rhsfun_source ( x, time, bb, nuk );\n\n            resid(k) = resid(k) + ( rhs_source  ...\n              - ( term_time + term_nonlin ) * bb - term_linear ) * ar;\n            \n          end\n\n        end\n\n      end\n\n    end       \n\n  end \n%\n%  Calculate norm of residual vector.\n%\n  resid_norm = sqrt ( resid' * resid ) / ( neqn * nunk )\n\n  return\nend\n", "meta": {"author": "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/residual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5513071730148915}}
{"text": "%% simple example of use of renorm_sibling_3d\nclear; close all;\nx = mandrill;\n%% compute roto-translation scattering of an image\noptions.Q = 2;\nWop = wavelet_factory_3d_pyramid(options, options, options);\nSx = scat(x, Wop);\n\n%% L1 renormalization\nop = @(x)(sum(x, 3));\nSx_renorm = renorm_sibling_3d(Sx, op);\n\n%% L1 + smoothing renormalization\nop = renorm_factory_L1_smoothing(1);\n[Sx_renorm, siblings] = renorm_sibling_3d(Sx, op);\n\n%%\nimage_scat(Sx, 0, 0);\n%%\nimage_scat(Sx_renorm, 0, 0);\n%%\nclose all;\nimagesc(log(image_scat_layer(Sx{3},0,1)+0.001));\n\n%%\nimage_scat(Sx_renorm, 1, 1);\n%%\nimage_scat(Sx, 1, 1);\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/test/scatutils/test_renorm_sibling_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5513071574218414}}
{"text": "function [Hdraw,HvarsDraw,phi_Hdraw,Adraw,h0]=sampleH_Ben(yData,Psi,A,B,phi_H,HvarsOld,priorValues,dataValues,n,h0,HH)\n\n%yData=YData\n%Psi=PsiDraw_prop\n%A=Adraw\n%B=Bdraw\n%phi_H=phi_Hdraw'\n%HvarsOld=HvarsDraw\n%% Initialize\noffset_c=priorValues.offset_c; %constant for log transformation \n\n[T,M]=size(yData);\np = size(B,1)/M; %lags of the B vector that has dimensions MxM*p (no constant), each column is one regression\n\n% obtain prior data\nb0=priorValues.mean_ln_h0;  %log mean of the initial state (variance scaling parameters) as residuals from an AR(4) in the training sample\na0=eye(n)/priorValues.var_ln_h0(1,1);    %variance of the initial state for the elements of lambda\n\npriorPhi_H=priorValues.phi_h;            %centering parameter for the inverse gamma of the variance of the innovations governing the random walk for lambda\npriorD_H  =priorValues.d_h;              %scaling parameter for the inverse gamma distribution for the variance of the innovations governing the random walk for lambda\n\nS_h = priorPhi_H*ones(n,1);\nnu_h = 3*ones(n,1);\n%% Prepare Data\n\nY_Psi=yData-Psi;  %subtract the local mean\nY_Psi(1:p,:)=yData(1:p,:)-ones(p,1)*mean(yData(1:p,:)); %also generate initial conditions for the construction of the lagmatrix\nX_Psi = lagmatrix(Y_Psi,1:p); %create RHS of the VAR part                          \nX_Psi = X_Psi(p+1:end,:);     %remove the first p rows of RHS\nY_Psi=Y_Psi(p+1:end,:);       %and do so for LHS\n\nE=Y_Psi-X_Psi*B;              %VAR residuals\nEscaled=E*A';                 %transform such that VAR residuals have variance Lambda\n\nHvars=zeros(T,M);             %sampled states (diagonal elements of lambda)\n\n\n%% Sample (States,Vars,phi)\n\nfor i=1:M\n    % prepare for each i\n    residsTemp=Escaled(:,i);\n    yStar=log(residsTemp.^2+offset_c); %transform scaled residuals\n    phi=phi_H(i); %previous draw for the variance of this particular variable\n    lnSigma2=log(HvarsOld(p+1:T,i)); % note log => h = ln sigma2\n    \n    % sample offset mixture\n    [yStarAdj, Ht] = bear.statesMix(yStar,lnSigma2);\n\n   % sample h conditional on the state \n    iSig_s = sparse(1:T-p,1:T-p,1./Ht); %state dependent variance\n    Kh = HH/phi + iSig_s;\n    h_hat = Kh\\(h0(i,1)/phi*HH*ones(T-p,1) + iSig_s*(yStarAdj));\n    logVarsDraw_Hi = h_hat + chol(Kh,'lower')'\\randn(T-p,1);\n    Hvars(:,i)=exp([zeros(1,p) logVarsDraw_Hi']');\n    \n \n    % sample phi\n%     [phiDraw_Hi]=samplePhi(logVarsDraw_Hi,priorD_H,priorPhi_H);\n%     phi_Hdraw(i)=phiDraw_Hi; \n    \n    \nend\n    \n   % sample phi \n    diff = (log(Hvars(p+1:end,:)) - [h0'; log(Hvars(p+1:end-1,:))]).^2;             \n    phi_Hdraw = 1./gamrnd(nu_h + size(diff,1)/2, 1./(S_h + sum(diff)'/2))';    \n\n% sample the initial value\n    Kh0 = a0 + sparse(1:n,1:n,1./phi_Hdraw');\n    h0_hat = Kh0\\(a0*b0 + log(Hvars(p+1,:)')./phi_Hdraw');\n    h0 = h0_hat + chol(Kh0,'lower')'\\randn(n,1);    \n\n%% Sample A\n[Adraw]=bear.sampleA_H(yData,Psi,B,Hvars,T,priorValues,dataValues);\nAdrawInv=Adraw\\eye(M);\n\n%% Construct H\nHdraw=zeros(M,M,T);\n\n\nfor t=1:T\n    Hdraw(:,:,t)=AdrawInv*diag(Hvars(t,:))*AdrawInv';\nend\n \nHvarsDraw=Hvars;\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/unreachableCode_ToRemove/sampleH_Ben.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.551273336808598}}
{"text": "function [fPerMc, res2] = calc_GoodnessFit(mCatalog, fMc, fBinning)\n% function [fPerMc, res2] = calc_FitComp(mCatalog, fMc, fBinning);\n% -----------------------------------------------------------------------------\n%\n% Function to calculate  Goodness of fit percentage of a fitted to observed\n% magnitude frequency distribution\n%\n% Incoming variables:\n% mCatalog\n% fMc\n% fBinning\n%\n% Outgoing variables:\n% fPerMc : Percentage of fit\n% res2   : Result\n%\n% Author: J. Woessner\n% woessner@seismo.ifg.ethz.ch\n% last update: 23.01.03\n\n\nvSel = mCatalog(:,6) > (fMc - (fBinning/2));\nnNumberEvents = length(mCatalog(vSel,6));\nif nNumberEvents >= 25\n    [fDummy fBValue fDummy,  fDummy] =  bmemag(mCatalog(vSel,:));\n\n    fStartMag = fMc; % Starting magnitude (hypothetical Mc)\n\n    % log10(N)=A-B*M\n    vMag = [fStartMag:fBinning:10]; % Ending magnitude must be sufficiently high\n    vNumber = 10.^(log10(nNumberEvents)-fBValue*(vMag - fStartMag));\n    vNumber = round(vNumber);\n\n    % Find the last bin with an event\n    nLastEventBin = min(find(vNumber == 0)) - 1;\n    if isempty(nLastEventBin)\n        nLastEventBin = length(vNumber);\n    end\n    % Determine set of all magnitude bins with number of events > 0\n    ct = round((vMag(nLastEventBin)-fStartMag)*(1/fBinning) + 1);\n\n    PM=vMag(1:ct);\n    vNumber = vNumber(1:ct);\n    [bval, vDummy] = hist(mCatalog(vSel,6),PM);\n    b3 = fliplr(cumsum(fliplr(bval)));    % N for M >= (counted backwards)\n    res2 = sum(abs(b3 - vNumber))/sum(b3)*100;\n    fPerMc = 100-res2;\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/jochen/seisvar/calc/calc_GoodnessFit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5512733351040884}}
{"text": "clear all;\n\n% This script is used to test time and frequency estimation / correction of\n% a simulated DroneID burst.  No equalization is done in this script.\n% There is a simulated fractional time offset applied, but the script will\n% fail if that time offset is anything other than 0 or 0.5.  This is\n% something that will likely have to be fixed by the equalizer or by\n% upsampling to find the most correct fractional starting time offset\n\n%% Parameters\nsample_rate = 15.36e6;\nfft_size = get_fft_size(sample_rate);\ncarrier_spacing = round(sample_rate / fft_size);\n\n% Pick a worst case Parts Per Million (PPM) to support.  20 PPM is the\n% value for the HackRF SDR's oscialltor.  Then choose the worst case\n% frequency that the SDR will operate at.  In this case 5.9 GHz is the\n% highest frequency the radio will need to tune to for DroneID.  Use that\n% to then figure out what the worst case frequency offset (in Hz) can be.\n% That will be used as the search space for the Integer Frequency Offset\n% (IFO) which is done later.\nworst_case_ppm = 20;\nworst_case_freq = 5.9e9;\nmax_allowed_freq_offset = worst_case_freq * worst_case_ppm / 1e6;\nmax_allowed_int_freq_offset = ceil(max_allowed_freq_offset / carrier_spacing);\n\n% Pick a frequency offset to test with\nfrequency_offset = max_allowed_freq_offset - 3.3e3;\n\n% Calculate the long and short cyclic prefix lengths\n[long_cp_len, short_cp_len] = get_cyclic_prefix_lengths(sample_rate);\n\n% Below are the cyclic prefix lengths for each OFDM symbol\ncyclic_prefixes = [\n    long_cp_len, ...\n    short_cp_len, ...\n    short_cp_len, ...\n    short_cp_len, ...\n    short_cp_len, ...\n    short_cp_len, ...\n    short_cp_len, ...\n    short_cp_len, ...\n    long_cp_len\n];\n\n% Calculate how many samples there are in one DroneID burst\ntotal_burst_sample_count = (fft_size * length(cyclic_prefixes)) + sum(cyclic_prefixes);\n\n% Calculate how many guard carriers there are in one OFDM symbol\n[left_guards, right_guards] = get_num_guard_carriers(sample_rate);\n\n% Number of constellation points in the underlying PSK\nmodulation_order = 4;\n\n% Number of occupied OFDM carriers per symbol\nnum_data_carriers = 600;\n\n%% OFDM Time Domain Creation\nmodulator = comm.OFDMModulator( ...\n    \"FFTLength\", fft_size, ...\n    \"NumGuardBandCarriers\", [left_guards; right_guards], ...\n    \"CyclicPrefixLength\", cyclic_prefixes, ...\n    \"NumSymbols\", length(cyclic_prefixes), ...\n    \"InsertDCNull\", true);\n\n% Modulate 9 random OFDM symbols worth of PSK samples\nsymbols = pskmod( ...\n    randi([0, modulation_order - 1], num_data_carriers, length(cyclic_prefixes)), ...\n    modulation_order);\n\n% Create the OFDM time domain\nmodulated_samples = modulator(symbols);\n\n%% Insert ZC Sequence at symbol 4\n\n% Figure out where in the modulated samples that the ZC sequence should\n% start (this includes the cyclic prefix)\nsymbol_4_offset = (fft_size * 3) + sum(cyclic_prefixes(1:3));\n\n% Create the time domain ZC sequence for symbol 4\nzc_seq = create_zc(fft_size, 4);\n\n% Tack on the cyclic prefix to build the full symbol\nfull_zc_seq = [zc_seq(end-cyclic_prefixes(4)+1:end); zc_seq];\n\n% Insert the full ZC sequence symbol in place of the modulated symbol 4\nmodulated_samples(symbol_4_offset:symbol_4_offset + length(full_zc_seq) - 1) = full_zc_seq;\n\n% Convert to row vector\nmodulated_samples = reshape(modulated_samples, 1, []);\n\n%% Prepend/Append Zeros\n\n% These zeros are needed to simulate an actual received sample and the\n% ambiguity of where the burst actually starts.  The number of samples\n% isn't critical, but should be something > about 30 samples\nnum_zeros = 50;\n\nzero_vec = zeros(1, num_zeros);\nmodulated_samples = [zero_vec, modulated_samples, zero_vec];\n\n%% Add in a 0.5 sample time offset\n\n% This simulates the clocks of the transmitter and receiver not being\n% perfectly synced up.  Upsample by 4, then skip the first two samples, and\n% downsample by 4\nmodulated_samples = resample(modulated_samples, 4, 1);\nmodulated_samples = [modulated_samples(2:end), 0, 0];\nmodulated_samples = resample(modulated_samples, 1, 4);\n\n%% Add Noise\n\n% This is not an exact SNR.  Just add gaussian noise to the signal to\n% simulate real world reception\nmodulated_samples = awgn(modulated_samples, 10, 'measured');\n\nfigure(1);\nplot(10 * log10(abs(modulated_samples).^2));\ntitle('Time Domain with Noise');\n%% Apply Frequency Offset\n\nfreq_offset_vector = exp(1j * 2 * pi * frequency_offset / sample_rate * [1:length(modulated_samples)]);\nfreq_offset_samples = modulated_samples .* freq_offset_vector;\n\nfigure(2);\nsubplot(3, 1, 1); plot(10 * log10(abs(fftshift(fft(modulated_samples))).^2));\ntitle('Original Modulated Samples (FFT)')\nsubplot(3, 1, 2); plot(10 * log10(abs(fftshift(fft(freq_offset_vector))).^2));\ntitle('Frequency Offset Vector (FFT)')\nsubplot(3, 1, 3); plot(10 * log10(abs(fftshift(fft(freq_offset_samples))).^2));\ntitle('Frequency Offset Samples (FFT)')\n\n%% Find the ZC sequence\n\n% Find the start of the burst by looking at the cyclic prefixes.  Make sure\n% to look PAST `num_zeros` since in the real world it will not be known\n% where the burst actually starts, so the search space will be rather large\nsto_estimate = est_sto(freq_offset_samples, sample_rate, num_zeros * 1.5);\n\n% Calculate how many samples after the start of the burst that the ZC\n% sequence should be located (this offset includes the ZC sequence cyclic\n% prefix)\nzc_seq_offset = (fft_size * 3) + long_cp_len + (short_cp_len * 3);\n\n% Calculate where in the sample vector the ZC sequence starts\nauto_corr_index = sto_estimate + zc_seq_offset;\n\nfprintf(\"Sample offset error: %d\\n\", sto_estimate - num_zeros - 1);\n%% Estimate coarse freq offset and adjust\n\n% Use the cyclic prefix of the ZC sequence to do coarse frequency offset\n% estimation (the ZC sequence is the 4th OFDM symbol).  \ncoarse_cp_len = cyclic_prefixes(4);\ncp_len_window_size = coarse_cp_len;\n\n% The auto_corr_index points to the start of the ZC sequence, so back off\n% by the length of the 4th cyclic prefix\ncoarse_offset_start = auto_corr_index - coarse_cp_len;\n\n% Extract out `fft_size + coarse_cp_len` samples\nwindow = freq_offset_samples(coarse_offset_start:coarse_offset_start + fft_size + coarse_cp_len - 1);\n\n% Extract the first and last `coarse_cp_len` samples from the window\nwindow_left = window(1:coarse_cp_len);\nwindow_right = window(end - coarse_cp_len + 1:end);\n\n% Calculate the coarse frequency offset in radians and Hz by taking the dot\n% product of the two windows\ncfo_est_radians = angle(sum(window_left .* conj(window_right))) / fft_size;\ncfo_est_hz = cfo_est_radians * sample_rate / (2 * pi);\n\n% Adjust for the frequency offset\ncfo_est_adj_vector = exp(1j * cfo_est_radians * [1:length(freq_offset_samples)]);\nfreq_offset_samples = freq_offset_samples .* cfo_est_adj_vector;\n\n%% Integer frequency offset estimation\n% The ZC sequence will be used to find the integer frequency offset.  So,\n% extract out just the samples for the ZC sequence (not including the\n% cyclic prefix)\nreceived_zc_sym = freq_offset_samples(auto_corr_index:auto_corr_index + fft_size - 1);\n\nfigure(3); \nplot(abs(received_zc_sym));\ntitle('ZC Sequence (Time Domain Magnitude)');\n\n% Estimate the integer frequency offset\nest_int_offset_hz = est_integer_freq_offset(received_zc_sym, sample_rate, max_allowed_int_freq_offset);\n\n% Adjust for the integer frequency offset\nifo_est_adj_vector = exp(1j * 2 * pi * est_int_offset_hz / sample_rate * [1:length(freq_offset_samples)]);\nfreq_offset_samples = freq_offset_samples .* ifo_est_adj_vector;\n\n% Print out how far off the combination of coarse and integer freq offset\n% was from the true value\nresidual_freq_error_hz = est_int_offset_hz + cfo_est_hz + frequency_offset;\nfprintf(\"Remaining Frequency Offset (Hz): %f\\n\", residual_freq_error_hz);\n\n%% Extract OFDM Data Carriers\ndemod = comm.OFDMDemodulator( ...\n    \"FFTLength\", fft_size, ...\n    \"NumGuardBandCarriers\", [left_guards; right_guards], ...\n    \"CyclicPrefixLength\", cyclic_prefixes, ...\n    \"NumSymbols\", length(cyclic_prefixes), ...\n    \"RemoveDCCarrier\", true);\n\n% Extract out just the samples in the burst and run those through the OFDM\n% demodulator\nburst_samples = freq_offset_samples(sto_estimate:sto_estimate + total_burst_sample_count - 1);\ndemod_symbols = demod(reshape(burst_samples, [], 1));\n\n% Plot just the data carrying OFDM symbol constellations (the 4th symbol is\n% the ZC sequence)\nfigure(4);\nplot(demod_symbols(:,[1,2,3,5,6,7,8,9]), 'o');\ntitle('Demodulated Constellations')\n", "meta": {"author": "proto17", "repo": "dji_droneid", "sha": "6ecbd20bdb1babbe2481a3870221553a10cdfe21", "save_path": "github-repos/MATLAB/proto17-dji_droneid", "path": "github-repos/MATLAB/proto17-dji_droneid/dji_droneid-6ecbd20bdb1babbe2481a3870221553a10cdfe21/matlab/updated_scripts/unused_scripts/test_integer_freq_offset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5512733282860497}}
{"text": "function [dlnZ_dmu, dlnZ_dvs] = heavisideNoiseGradVals(noise, mu, varsigma, y)\n\n% HEAVISIDENOISEGRADVALS Gradient wrt mu and varsigma of log-likelihood for heaviside noise model.\n\n% IVM\n\nD = size(mu, 2);\nc = y./sqrt(varsigma);\nu = zeros(size(c));\ndlnZ_dmu = zeros(size(c));\nfor i = 1:D\n  u(:, i) = c(:, i).*(mu(:, i) + noise.bias(i));\n  dlnZ_dmu(:, i) = c(:, i).*ngaussian(u(:, i))...\n            ./(cumGaussian(u(:, i))+ ...\n               noise.eta/(1-2*noise.eta));\nend\ndlnZ_dvs = -.5*c.*u.*dlnZ_dmu;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/noise/heavisideNoise/heavisideNoiseGradVals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5512695761974168}}
{"text": "function [best_overlap,best_boxes] = closest_candidates(gt_boxes, candidates)\n% do a matching between gt_boxes and candidates\n\n  num_gt_boxes = size(gt_boxes, 1);\n  num_candidates = size(candidates, 1);\n  \n  iou_matrix = zeros(num_gt_boxes, num_candidates);\n  for i = 1:num_gt_boxes\n    iou = overlap(gt_boxes(i,:), candidates);\n    iou_matrix(i,:) = iou';\n  end\n  \n  best_overlap = zeros(num_gt_boxes, 1);\n  best_boxes = -ones(num_gt_boxes, 4);\n\n  [best_overlap,best_boxes] = greedy_matching(iou_matrix, gt_boxes, candidates);\nend\n\nfunction [best_overlap,best_boxes] = greedy_matching(iou_matrix, gt_boxes, candidates)\n  [n, m] = size(iou_matrix);\n  assert(n == size(gt_boxes, 1));\n  assert(m == size(candidates, 1));\n  if n > m\n    gt_matching = greedy_matching_rowwise(iou_matrix');\n    candidate_matching = (1:m)';\n  else\n    gt_matching = (1:n)';\n    candidate_matching = greedy_matching_rowwise(iou_matrix);\n  end\n  \n  best_overlap = zeros(n, 1);\n  best_boxes = zeros(n, 4);\n  for pair_idx = 1:numel(gt_matching)\n    gt_idx = gt_matching(pair_idx);\n    candidate_idx = candidate_matching(pair_idx);\n    \n    best_overlap(gt_idx) = iou_matrix(gt_idx, candidate_idx);\n    best_boxes(gt_idx,:) = candidates(candidate_idx, :);\n  end\nend\n\nfunction [matching, objective] = greedy_matching_rowwise(iou_matrix)\n  assert(size(iou_matrix, 1) <= size(iou_matrix, 2));\n  n = size(iou_matrix, 1);\n  matching = zeros(n, 1);\n  objective = 0;\n  for i = 1:n\n    % find max element int matrix\n    [max_per_row, max_col_per_row] = max(iou_matrix, [], 2);\n    [max_iou,row] = max(max_per_row);\n    if max_iou == -inf\n      break\n    end\n    \n    objective = objective + max_iou;\n    col = max_col_per_row(row);\n    matching(row) = col;\n    iou_matrix(row,:) = -inf;\n    iou_matrix(:,col) = -inf;\n  end\nend\n\n", "meta": {"author": "hosang", "repo": "detection-proposals", "sha": "858368afffde5ff4028020fcb1dd4381705ccbfb", "save_path": "github-repos/MATLAB/hosang-detection-proposals", "path": "github-repos/MATLAB/hosang-detection-proposals/detection-proposals-858368afffde5ff4028020fcb1dd4381705ccbfb/shared/closest_candidates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5512402791458632}}
{"text": "function Cbar = computeCbar(A, B, ny, nu)\n    Cbar_tmp = cell(ny,nu);\n    tmp = B;\n    \n    \n    for i=1:nu\n       for k=1:(i-1)\n           Cbar_tmp{k,i} = zeros(size(B));\n       end\n       \n       for j=i:ny\n           Cbar_tmp{j,i} = tmp;\n           tmp = A*tmp;\n       end\n       \n       tmp = B;\n    end\n    \n    Cbar = cell2mat(Cbar_tmp);\nend", "meta": {"author": "ccalas", "repo": "mpc", "sha": "2b30095dc94efb7799e861eb5acc6fe02110a328", "save_path": "github-repos/MATLAB/ccalas-mpc", "path": "github-repos/MATLAB/ccalas-mpc/mpc-2b30095dc94efb7799e861eb5acc6fe02110a328/computeCbar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5512402678451781}}
{"text": "function rgb = gray2rgb(im,map,n)\n  % GRAY2RGB\n  %\n  % rgb = gray2rgb(im,map,n)\n  %\n  % Use a colormap, map, to convert a grayscale/intensity image with n colors\n  % to pseudocolor rgb image. The n colors in the original image are mapped\n  % evenly to colors in the given colormap, not according to value.\n  %\n  % rgb = gray2rgb(im,map)\n  %\n  % Same as above but compute number of colors in im\n  %\n  % rgb = gray2rgb(im)\n  %\n  % Use default colormap and compute number of colors in im\n  %\n  % Inputs:\n  %  im  grayscale image, 2d array (h,w)\n  %  map  colormap\n  %  n  (optional) number of colors in im, default is to compute unique colors,\n  %    this is usually preferred but it's time consuming so if the value is\n  %    already known then it can be given.\n  % Outputs:\n  %  rgb  color Red, Green, Blue image, 3d array (h,w,3)\n  %\n  % See also: rgb2gray, hsv2rgb, rgb2hsv, imshow\n  %\n\n  % number of unique colors\n  if(~exist('n','var'))\n    n = size(unique(im),1);\n  end\n\n  if(~exist('map','var'))\n    if(~exist('gray2ind'))\n      error( ...\n        'Image processing toolbox seems not installed, try again without map')\n    end\n    if(isempty(get(0,'CurrentFigure')))\n      map = jet(n);\n    else\n      map = colormap;\n    end\n    %map = jet(n);\n    m = size(map,1);\n  else\n    m = size(map,1);\n  end\n\n  if(exist('gray2ind')&&n<=65536)\n    \n    in = gray2ind(im,n);\n\n    if(strcmp(class(in),'uint8') && (n/(n/m)) > 256)\n      in = uint16(in);\n    end\n\n    if( m <= 256 )\n      rgb = label2rgb(idivide(in,n/m,'fix')+1,map);\n    else\n      rgb = ind2rgb(idivide(in,n/m,'fix'),map);\n    end\n\n    % if it's not going to change the result it's faster to convert to and\n    % from uint8 and use label2rgb\n    if(strcmp(class(im),'double'))\n      rgb = im2double(rgb);\n    elseif(strcmp(class(im),'uint16'))\n      rgb = im2uint16(rgb);\n    end\n  else \n    % slope\n    m = 1/(1/4);\n    % precomputation\n    mim = m*im;\n    nmim = -mim;\n    x1 = im<1/8;\n    x2 = im>=1/8 & im<3/8;\n    x3 = im>=3/8 & im<5/8;\n    x4 = im>=5/8 & im<7/8;\n    x5 = im>=7/8;\n    rgb = cat( 3, ...\n      x3.*(mim - (3/8)*m)   + x4.*1 + x5.*(nmim + (9/8)*m), ...\n      x2.*(mim - (1/8)*m)   + x3.*1 + x4.*(nmim + (7/8)*m), ...\n      x1.*(mim + 0.5)       + x2.*1 + x3.*(nmim + (5/8)*m));\n  end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/imageprocessing/gray2rgb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5512402570791508}}
{"text": "function [childId, packetId] = calcVariantId(parentOri,childOri,p2c,varargin)\n% compute variantIds and packetId from parent / child orientation pairs\n%\n% Syntax\n%\n%   variantId = calcVariantId(parentOri,childOri,p2c)\n%\n%   % compute packetIds\n%   [variantId,packetId] = calcVariantId(parentOri,childOri,p2c,...\n%     {hklParent,hklChild})\n%\n%   % packet determination\n%   hklParent = Miller({1,1,1},{1,-1,1},{-1,1,1},{1,1,-1},p2c.CS);\n%   hklChild  = Miller(1,0,1,p2c.SS);\n%\n%   [variantId,packetId] = calcVariantId(parentOri,childOri,p2c,...\n%     {hklParent,hklChild})\n%\n% Input\n%  parentOri - parent @orientation\n%  childOri  - child @orientation\n%  p2c       - parent to child mis@orientation\n%  hklParent, hklChild - correspondent planes between parent and child\n%\n% Output\n%  variantId - variant id\n%  packetId  - packet id\n%\n\n% all child variants\nchildVariants  = variants(p2c, parentOri);\n\nif size(childVariants,1) == 1\n  childVariants = repmat(childVariants,length(childOri),1);\nend\n  \n% compute distance to all possible variants\nd = dot(childVariants,repmat(childOri(:),1,size(childVariants,2)));\n\n% take the best fit\n[~,childId] = max(d,[],2);\n\n% compute packetId if required\nif nargout == 2\n  % Get packet definition\n  tmp = getClass(varargin,'cell');\n  isMiller = [];\n  for ii = 1:length(tmp); isMiller(ii) = ~isempty(getClass(tmp(ii),'Miller')); end\n  \n  if sum(isMiller) == 2 % definition given\n    ind = find(isMiller);\n    h1 = tmp{ind(1)};  \n    h2 = tmp{ind(2)};\n  else % definition assumed\n    warning('Packet ID calculation assuming {111}_p||{110}_c');\n    h1 = Miller({1,1,1},{1,-1,1},{-1,1,1},{1,1,-1},p2c.CS);\n    h2 = Miller(1,0,1,p2c.SS);\n  end\n  \n  omega = dot(variants(p2c,h1),h2);\n\n  [~,packetId] = max(omega,[],1);\n  \n  packetId = packetId(childId);\n  \nend\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/misorientation/calcVariantId.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5511743891553474}}
{"text": "function [P_O] = getColourMap(patch, bg_hist, fg_hist, n_bins, grayscale_sequence)\n%% GETCOLOURMAP computes pixel-wise probabilities (PwP) given PATCH and models BG_HIST and FG_HIST\n    % check whether the patch has 3 channels\n    [h, w, d] = size(patch);\n    % figure out which bin each pixel falls into\n    bin_width = 256/n_bins;\n    % convert image to d channels array\n    patch_array = reshape(double(patch), w*h, d);\n    % to which bin each pixel (for all d channels) belongs to\n    bin_indices = floor(patch_array/bin_width) + 1;\n    % Get pixel-wise posteriors (PwP)\n    P_bg = getP(bg_hist, h, w, bin_indices, grayscale_sequence);\n    P_fg = getP(fg_hist, h, w, bin_indices, grayscale_sequence);\n\n    % Object-likelihood map\n    P_O = P_fg ./ (P_fg + P_bg);\nend\n", "meta": {"author": "bertinetto", "repo": "staple", "sha": "7b6b5b579a7cd25acae6bcabe93f8dfb78040215", "save_path": "github-repos/MATLAB/bertinetto-staple", "path": "github-repos/MATLAB/bertinetto-staple/staple-7b6b5b579a7cd25acae6bcabe93f8dfb78040215/getColourMap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5511743891553473}}
{"text": "function [Y,W,A] = FDICA(X,W,A,F_i)\n\n%First step: Initialization\n% step_size=1e-5;                   %the step distance\nstep_size = 0.1;\n% C_r=0.0002;                             % correlation\nmax_iteration=1000;                   % the max number of iteration\n\n% if(F_i==33) \n%     step_size = step_size/10;\n% end\n%%%%%%%%%%\nframe_N = size(X,2);\n% if(F_i==16)\n%     a =1;\n% end\nsign_size = 0;\ny_f = W*X;\nnorm = max(abs(y_f),[],2);\n% if(norm>10)\n%     norm = repmat(norm,1,size(W,2));\n%     W = W./norm;\n%     y_f = W*X;\n% end\n\nfor n_i=1:max_iteration\n%         y_fun = power(1+exp(-y_r),-1)+j*power(1+exp(-y_i),-1);\n%         W_o1 = step_size*(diag(diag(y_fun*y_f'/frame_N))-(y_fun*y_f'/frame_N))*W_o{K_i}+W_o{K_i};\n    y_f = W*X;\n    y_r = real(y_f);\n    y_i = imag(y_f);\n    y_fun = tanh(y_r)+1i*tanh(y_i);\n    sign = abs(det(eye(size(X,1))-(y_fun*y_f'/frame_N)));\n    A(n_i,F_i-1) = sign;\n    %%%%%This part trys to adjust the step_size which is unnecessary\n    if(sign>100 && sign_size ==0)\n        step_size = step_size/10;\n        sign_size =1;\n    end\n    if(sign>1000 && sign_size ==1)\n        step_size = step_size/10;\n        sign_size =2;\n    end\n    if(sign>10000 && sign_size ==2)\n        step_size = step_size/10;\n        sign_size =3;\n    end\n    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    W1 = step_size*(eye(size(X,1))-(y_fun*y_f'/frame_N))*W+W;\n    W = W1;\n\n    if(sign<1e-4)\n        break;\n    end\n%     A(n_i,F_i-1) = abs(det(eye(size(X,1))-(y_fun*y_f'/frame_N)));\n%     A(n_i,K_i) = abs(det(eye(size(s,2))-(y_fun*y_f'/frame_N)));\n%     if(abs(A(n_i,K_i))<0.001) break; end;\nend\nA(end,F_i-1) = n_i;\nY = y_f;\n% Y = Project_back(W,y_f);\nreturn;", "meta": {"author": "KyleZhang1118", "repo": "Voice-Separation-and-Enhancement", "sha": "77d16c120356dbbca3ee768d293df5d743d343ad", "save_path": "github-repos/MATLAB/KyleZhang1118-Voice-Separation-and-Enhancement", "path": "github-repos/MATLAB/KyleZhang1118-Voice-Separation-and-Enhancement/Voice-Separation-and-Enhancement-77d16c120356dbbca3ee768d293df5d743d343ad/FDICA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.551174387796613}}
{"text": "function Fitness = CalFitness(PopObj,PopCon)\n% Calculate the fitness of each solution\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 Kangjia Qiao\n\n    N = size(PopObj,1);\n    if nargin == 1\n        CV = zeros(N,1);\n    else\n        CV = sum(max(0,PopCon),2);\n    end\n\n    %% Detect the dominance relation between each two solutions\n    Dominate = false(N);\n    for i = 1 : N-1\n        for j = i+1 : N\n            if CV(i) < CV(j)\n                Dominate(i,j) = true;\n            elseif CV(i) > CV(j)\n                Dominate(j,i) = true;\n            else\n                k = any(PopObj(i,:)<PopObj(j,:)) - any(PopObj(i,:)>PopObj(j,:));\n                if k == 1\n                    Dominate(i,j) = true;\n                elseif k == -1\n                    Dominate(j,i) = true;\n                end\n            end\n        end\n    end\n    \n    %% Calculate S(i)\n    S = sum(Dominate,2);\n    \n    %% Calculate R(i)\n    R = zeros(1,N);\n    for i = 1 : N\n        R(i) = sum(S(Dominate(:,i)));\n    end\n    \n    %% Calculate D(i)\n    Distance = pdist2(PopObj,PopObj);\n    Distance(logical(eye(length(Distance)))) = inf;\n    Distance = sort(Distance,2);\n    D = 1./(Distance(:,floor(sqrt(N)))+2);\n    \n    %% Calculate the fitnesses\n    Fitness = R + D';\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/URCMO/CalFitness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5511743847276146}}
{"text": "%-------------------------------------------------------------------------------------------------------------\n% This is an implementation of the MCWNNM algorithm for real color image denoising.\n% Author:  Jun Xu, csjunxu@comp.polyu.edu.hk\n%              The Hong Kong Polytechnic University\n%\n% Please refer to the following paper if you use this code:\n%\n% @article{MCWNNM,\n% \tauthor = {Jun Xu and Lei Zhang and David Zhang and Xiangchu Feng},\n% \ttitle = {Multi-channel Weighted Nuclear Norm Minimization for Real Color Image Denoising},\n% \tjournal = {ICCV},\n% \tyear = {2017}\n% }\n%\n% Please see the file License.txt for the license governing this code.\n%-------------------------------------------------------------------------------------------------------------\n\nclear;\nOriginal_image_dir  =    'kodak_color/';\nfpath = fullfile(Original_image_dir, '*.png');\nim_dir  = dir(fpath);\nim_num = length(im_dir);\n\nnSig = [5 30 15];\n\nPar.nSig      =   nSig;                                 % Variance of the noise image\nPar.win =   20;                                   % Non-local patch searching window\nPar.Constant         =  2 * sqrt(2);                              % Constant num for the weight vector\nPar.Innerloop =   2;                                    % InnerLoop Num of between re-blockmatching\nPar.ps       =   6;                            % Patch size\nPar.step        =   5;\nPar.Iter          =   6;                            % total iter numbers\nPar.display = true;\n\n\n% Par.method = 'WNNM_ADMM'\nPar.method = 'MCWNNM_ADMM'\nPar.maxIter = 10;\n\nPar.model = '2';\n\nPar.delta     =   0.1;                                  % Parameter between each iter\nPar.lambda = 0.75;\nPar.mu = 1.001;\nPar.rho = 0.05;\n% record all the results in each iteration\nPar.PSNR = zeros(Par.Iter, im_num, 'single');\nPar.SSIM = zeros(Par.Iter, im_num, 'single');\nfor i = 1:im_num\n    Par.image = i;\n    Par.nSig0 = nSig;\n    Par.nlsp        =   70;   % Initial Non-local Patch number\n    Par.I =  double( imread(fullfile(Original_image_dir, im_dir(i).name)) );\n    S = regexp(im_dir(i).name, '\\.', 'split');\n    [h, w, ch] = size(Par.I);\n    Par.nim = zeros(size(Par.I));\n    for c = 1:ch\n        randn('seed',0);\n        Par.nim(:, :, c) = Par.I(:, :, c) + Par.nSig0(c) * randn(size(Par.I(:, :, c)));\n    end\n    fprintf('%s :\\n',im_dir(i).name);\n    PSNR =   csnr( Par.nim, Par.I, 0, 0 );\n    SSIM      =  cal_ssim( Par.nim, Par.I, 0, 0 );\n    fprintf('The initial value of PSNR = %2.4f, SSIM = %2.4f \\n', PSNR,SSIM);\n    %\n    time0 = clock;\n    if Par.model == '1'\n        [im_out, Par] = MCWNNM_ADMM1_Denoising( Par.nim, Par.I, Par );\n    elseif Par.model == '2'\n        [im_out, Par] = MCWNNM_ADMM2_Denoising( Par.nim, Par.I, Par );\n    else\n        [im_out, Par] = MCWNNM_ADMM_Denoising( Par.nim, Par.I, Par );\n    end\n    fprintf('Total elapsed time = %f s\\n', (etime(clock,time0)) );\n    im_out(im_out>255)=255;\n    im_out(im_out<0)=0;\n    % calculate the PSNR\n    Par.PSNR(Par.Iter, Par.image)  =   csnr( im_out, Par.I, 0, 0 );\n    Par.SSIM(Par.Iter, Par.image)      =  cal_ssim( im_out, Par.I, 0, 0 );\n    imname = sprintf([Par.method '_nSig' num2str(nSig(1)) num2str(nSig(2)) num2str(nSig(3)) '_' Par.model '_Oite' num2str(Par.Iter) '_Iite' num2str(Par.maxIter) '_rho' num2str(Par.rho) '_mu' num2str(Par.mu) '_lambda' num2str(Par.lambda) '_' im_dir(i).name]);\n    imwrite(im_out/255, imname);\n    fprintf('%s : PSNR = %2.4f, SSIM = %2.4f \\n',im_dir(i).name, Par.PSNR(Par.Iter, Par.image),Par.SSIM(Par.Iter, Par.image)     );\nend\nmPSNR=mean(Par.PSNR,2);\n[~, idx] = max(mPSNR);\nPSNR =Par.PSNR(idx,:);\nSSIM = Par.SSIM(idx,:);\nmSSIM=mean(SSIM,2);\nfprintf('The best PSNR result is at %d iteration. \\n',idx);\nfprintf('The average PSNR = %2.4f, SSIM = %2.4f. \\n', mPSNR(idx),mSSIM);\nname = sprintf([Par.method '_' Par.model '_nSig' num2str(nSig(1)) num2str(nSig(2)) num2str(nSig(3)) '_' Par.model '_Oite' num2str(Par.Iter) '_Iite' num2str(Par.maxIter) '_rho' num2str(Par.rho) '_mu' num2str(Par.mu) '_lambda' num2str(Par.lambda) '.mat']);\nsave(name,'nSig','PSNR','SSIM','mPSNR','mSSIM');\n", "meta": {"author": "csjunxu", "repo": "MCWNNM-ICCV2017", "sha": "e6db69b01ff21e89461cc49893c89afb1a9a941c", "save_path": "github-repos/MATLAB/csjunxu-MCWNNM-ICCV2017", "path": "github-repos/MATLAB/csjunxu-MCWNNM-ICCV2017/MCWNNM-ICCV2017-e6db69b01ff21e89461cc49893c89afb1a9a941c/Demo_MCWNNM_ADMM2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5511743816586147}}
{"text": "function test_vbgppcamv(vbpca, ppca)\n\nrand('state', 6);\nrandn('state', 6);\n\nif nargin < 1\n  vbpca = false;\nend\nif nargin < 2\n  ppca = false;\nend\n\ninW = [120*rand(1,30); 80*rand(1,30)];\ninX = 1:300;\n\nM = length(inW);\nN = length(inX);\nD = 2;\nX = zeros(D,N);\nW = zeros(M,D);\n\n% Covariance matrices\nlogthetaW = log(3e3);\nlogthetaX = log(10);\n\n% Covariance functions\ngpcovW = {@gpcovScale, @(logtheta,x1,x2) gpcov(logtheta,x1,x2,@sqdistEarth)};\nlogthetaW = [3; logthetaW(:)];\npseudoW = cell(D,1);%zeros([dimW,Mp,D]);\nMp = ceil(0.2*M);\nfor d=1:D\n  permM = randperm(M);\n  pseudoW{d} = inW(:,permM(1:Mp));% + randn(2,Mp);\nend\n\ngpcovX = @gpcov;\n\n\n% Generate latent variables\nfor d=1:D\n% $$$   W(:,d) = mvnrnd(zeros(1,M),CovW)';\n% $$$   X(d,:) = mvnrnd(zeros(1,N),CovX);\n  \n  W(:,d) = gprnd(inW, logthetaW, gpcovW);\n\n  lsX = 10*ceil(exp(logthetaX(end)));\n  X(d,:) = filter(hamming(lsX), 1, randn(N,1));\n% $$$   W(:,d) = filter(ones(lsW,1)/lsW, 1, randn(M,1));\n% $$$   X(d,:) = filter(ones(lsX,1)/lsX, 1, randn(N,1));\n  covfunW{d} = gpcovW;\n  covfunX{d} = gpcovX;\n  initthetaW{d} = logthetaW-1;\n  initthetaX{d} = logthetaX-1;\nend\n\nW = W * diag( sqrt(M./rowsum(W.^2)) );\nX = diag( sqrt(N./colsum(X.^2)) ) * X;\n\nfigure\nplot(X');\nreturn\n\n% $$$ tsplot(X)\n% $$$ tsplot(W')\n% $$$ return\n\n% Generate data\nY = W*X;\n\n% Noise level\ns2 = 0.1;\n\n% Make noisy observations\nYn = Y + sqrt(s2)*randn(M,N);  % noise\nYnm = Yn; Ynm(rand(M,N)<0.5) = nan; % missing values\nYtest = Yn; Ytest(~isnan(Ynm)) = nan;\n\ninitthetaW\n\n% Learn GP PCA\nmaxiter = 3e1;\nQ = vbgppcamv(Ynm,D,inW,inX,covfunW,initthetaW,covfunX,initthetaX, ...\n              'maxiter',maxiter, 'pseudodensityx', 0.4, 'pseudodensityw', ...\n              0.4, 'loglikelihood', true, 'updatehyper', 5, 'maxsearchx', ...\n              3, 'maxsearchw', 200, 'initpseudow', {pseudoW});\n\nest_noise = 1/Q.tau\nreal_noise = s2\n\n% Learn other models\nif ppca\n  Qppca = pca_full(Ynm,D,'maxiters',maxiter,'rotate2pca',true, ...\n                   'algorithm','ppca');\n  Yh_ppca = Qppca.A * Qppca.S + repmat(Qppca.Mu,1,N);\n  testrmse_ppca = rmse(Ytest, Yh_ppca)\n  noiselessrmse_ppca = rmse(Y, Yh_ppca)\nend\nif vbpca\n  Qvbpca = vbpcamv(Ynm,M-1,'maxiters',maxiter);\n  Yh_vbpca = Qvbpca.W * Qvbpca.X + repmat(Qvbpca.mu,1,N);\n  testrmse_vbpca = rmse(Ytest, Yh_vbpca)\n  noiselessrmse_vbpca = rmse(Y, Yh_vbpca)\nend\n\n\n\nYh_gppca = Q.W * Q.X;\ntestrmse_gppca = rmse(Ytest, Yh_gppca)\nnoiselessrmse_gppca = rmse(Y, Yh_gppca)\nfigure\nsubplot(5,1,1);\nplot(Y');\ntitle('Original noiseless data')\nsubplot(5,1,2);\nplot(Ynm');\ntitle('Observed data')\nsubplot(5,1,3);\nplot(Yh_gppca');\ntitle('Reconstruction of GP VB PCA')\nif vbpca\n  subplot(5,1,4);\n  plot(Yh_vbpca');\n  title('Reconstruction of VB PCA')\nend\nif ppca\n  subplot(5,1,5);\n  plot(Yh_ppca');\n  title('Reconstruction of PPCA')\nend\n\nvX = Q.varX;%diag(Q.CovX);\neX = 2*sqrt(vX);%sqrt( vX(reshape(1:(N*D), D, N)) );\nvW = Q.varW;%diag(Q.CovW);\neW = 2*sqrt(vW);%sqrt( vW(reshape(1:(M*D), M, D)) );\ntsgpplot(inX, Q.X', eX', 'pseudoinputs', {Q.pseudoX});\n\n%tsgpplot(inW, Q.W, eW, 'pseudoinputs', {Q.pseudoW});\nfigure\nfor d=1:D\n  subplot(D,1,d);\n  mapproj('global-ellipse');\n  mapplot(inW(1,:),inW(2,:),'ro');\n  hold on\n  mapplot(Q.pseudoW{d}(1,:),Q.pseudoW{d}(2,:),'k+');\n  mapcoast\nend\n\nfigure\nmapproj('global-ellipse');\ngpmapcolor(Q.pseudoW, Q.Wp, Q.CovWp, -180:5:180, -90:5:90, Q.logthetaW, covfunW);\n% $$$ gpmapcolor({Q.pseudoW}, {Q.Wp}, {Q.CovWp}, 0:10:360, 0:10:180, {Q.logthetaW}, ...\n% $$$            covfunW);\n\n% $$$ exp(Q.logthetaW{1})\n% $$$ exp(Q.logthetaW{2})\n% $$$ \n% $$$ exp(Q.logthetaX{1})\n% $$$ exp(Q.logthetaX{2})\n\n% $$$ % DEBUG: (test the effect of CovXp)\n% $$$ X = zeros(D,N);\n% $$$ varX = zeros(D,N);\n% $$$ for d=1:D\n% $$$   [X(d,:), varX(d,:)] = gppred(Q.pseudoX{d}, Q.Xp{d}, 0, inX, covfunX{d}, ...\n% $$$                                Q.logthetaX{d});\n% $$$ end    \n% $$$ varX;\n% $$$ tsgpplot(inX, X', 2*sqrt(varX'), 'pseudoinputs', {Q.pseudoX});\n% $$$ exp(Q.logthetaX{1})\n\n% $$$ figure\n% $$$ pcolor(Q.CovXp{1});\n% $$$ figure\n% $$$ pcolor(Q.CovWp{1});\n\n\nreturn\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n%inv(funcK_noiseless(D,[10;10;1;10;10]));return\n[p, loglike] = gplearn(ymv, @(p) funcK_noisy(D,p), [10;10;1;300;300;0.1])\n%[p, loglike] = gplearn(ymv, @(p) funcK_noisy(D,p), [300;300;10;1;1])\n%[p, loglike] = gplearn(ymv, @(p) funcK_noisy(D,p), [300;300;10;5;5;10;0.1])\n%[p, loglike] = gplearn(ymv, @(p) funcK_noisy(D,p), [1000;100;0.1;3;100;0.059;1;0.1])\n%[p, loglike] = gplearn(ymv, @(p) funcK_noisy(D,p), [100;100;3;100;0.059;1;0.1])\n\n%p(1:4) = [2000;30;0.1;10]\n%p(3) = 0.1;\n[mu,Cov] = gppred(th,tmv,ymv, @(x1,x2) funcK_noiseless(gpdist(x1,x2),p(1:(end-1))), p(end));\nyh = mnorm_rnd(mu, Cov, 10);\n\nfigure\nclf\nplot(th, yh, 'r')\nfigure\nclf\ngpplot(th,mu,Cov);\nhold on\nplot(tmv,ymv,'k+')\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction gpmapplot(coord, y)\nx = coord';\n% Use haversine distance measure\nmydist = @(x1,x2) gpdist(x1,x2,@dist_coord);\nD = mydist(x,x);\nfuncK = @(p) gpK(@() gpK_ratquad(D,p(1),p(2),p(3)), ...\n                 @() gpK_noise(length(D),p(4)));\n[p, loglike] = gplearn(y, funcK, [10;5;1;1e-5])\nfuncK_noiseless = @(D) gpK(@() gpK_ratquad(D, p(1),p(2),p(3)));\n[LONI, LATI] = get_grid(40, 40);\nxh = [LONI(:)';LATI(:)'];\n[mu,Cov] = gppred(xh,x,y, @(x1,x2) funcK_noiseless(mydist(x1,x2)), p(4));\nyh = mu;\nZI = reshape(yh, size(LONI));\nplot_map\nhold on\nm_pcolor(LONI, LATI, ZI);\n\n% Set nice colormap\ncolormap(climcolmap);\nshading flat;\nlim = max( -min(yh), max(yh) );\nset(gca, 'clim', [-lim lim]);\n\nreturn\n\n% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ function D = gpdist(x1, x2, funcDist)\n% $$$ if isvector(x1)\n% $$$   x1 = x1(:)';\n% $$$   x2 = x2(:)';\n% $$$ end\n% $$$ if nargin < 3\n% $$$   funcDist = @(z1,z2) abs(z1-z2);\n% $$$ end\n% $$$ %[X2,X1] = meshgrid(x2,x1);\n% $$$ n1 = size(x1,2);\n% $$$ n2 = size(x2,2);\n% $$$ D = zeros(n1,n2);\n% $$$ for i=1:n1\n% $$$   for j=1:n2\n% $$$     D(i,j) = funcDist(x1(:,i),x2(:,j));\n% $$$   end\n% $$$ end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction d = dist_coord(coord1, coord2, varargin)\n% d = dist(X1, X2)\n% returns geographical distance in kilometers\n% input vectors must be the same size and shape!!\n% Approximates earth as a sphere.\n% Distance is calculated for \n\nif nargin > 2\n  nargin\nend\n\n% Quadratic mean radius from Wikipedia\nR_avg = 6372.795477598;\n\n% Convert to radians\nq = pi / 180;\nlon1 = coord1(1,:) * q;\nlat1 = coord1(2,:) * q;\nlon2 = coord2(1,:) * q;\nlat2 = coord2(2,:) * q;\n\n% Distance calculation (haversine law)\ndlat = lat2 - lat1;\ndlon = lon2 - lon1;\na = sin(dlat/2).^2 + cos(lat1).*cos(lat2).*(sin(dlon/2).^2);\nc = 2 * atan2(sqrt(a), sqrt(1-a));\nd = R_avg * c;\n\nreturn\n\n% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ function [p,loglike] = gplearn(y, funcK, init_p)\n% $$$ opts = optimset('GradObj', 'on');\n% $$$ [p, negloglike] = fminunc(@(p) cost(y, funcK, p), init_p, opts);\n% $$$ loglike = -negloglike;\n% $$$ \n% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ function [mu,Cov] = gppred(xh, x, y, funcK, noise)\n% $$$ if nargin == 1\n% $$$   x = [];\n% $$$   y = [];\n% $$$ end\n% $$$ \n% $$$ Kxhx = funcK(xh,x);\n% $$$ invKxx = inv(funcK(x,x)+noise^2*eye(length(x)));\n% $$$ Kxhxh = funcK(xh,xh);\n% $$$ if isempty(Kxhx)\n% $$$   Kxhx = 0;\n% $$$ end\n% $$$ if isempty(invKxx)\n% $$$   invKxx = 0;\n% $$$ end\n% $$$ mu = Kxhx*invKxx*y;\n% $$$ if isempty(mu)\n% $$$   mu = zeros(size(xh));\n% $$$ end\n% $$$ Cov = Kxhxh - Kxhx*invKxx*Kxhx';\n\n% $$$ % $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ % $$$ function gpplot(x, mu, Cov)\n% $$$ % $$$ e = sqrt(diag(Cov));\n% $$$ % $$$ X = [x(1:end); x(end:-1:1)];\n% $$$ % $$$ Y = [mu(1:end)+e; mu(end:-1:1)-e(end:-1:1)];\n% $$$ % $$$ C = [.65,.65,.65];\n% $$$ % $$$ fill(X,Y,C,'EdgeColor',C);\n% $$$ % $$$ hold on\n% $$$ % $$$ plot(x,mu,'k');\n% $$$ \n% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ function [K, dK] = gpK(varargin)\n% $$$ K = 0;\n% $$$ dK = [];\n% $$$ for i=1:nargin\n% $$$   if nargout == 1\n% $$$     Knew = varargin{i}();\n% $$$   else\n% $$$     [Knew,dKnew] = varargin{i}();\n% $$$     n = size(dKnew,3);\n% $$$     if isempty(dK)\n% $$$       dK = dKnew;\n% $$$     else\n% $$$       dK(:,:,end+(1:n)) = dKnew;\n% $$$     end\n% $$$   end\n% $$$   K = K + Knew;\n% $$$ end\n% $$$ \n% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ function [K, dK] = gpK_noise(n, p1);\n% $$$ K = p1^2 * eye(n);\n% $$$ if nargout >= 2\n% $$$   dK = K * 2/p1;\n% $$$ end\n% $$$ \n% $$$ % $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ % $$$ function [K, dK] = gpK_sqexp(D, p1, p2)\n% $$$ % $$$ K = p1^2*exp(-0.5*D.^2/(p2^2));\n% $$$ % $$$ \n% $$$ % $$$ if nargout >= 2\n% $$$ % $$$   dK = zeros([size(D), 2]);\n% $$$ % $$$   dK(:,:,1) = K .* 2 / p1;\n% $$$ % $$$   dK(:,:,2) = K .* (-0.5*D.^2) .* (-2*p2^(-3));\n% $$$ % $$$ end\n% $$$ \n% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ function [K, dK] = gpK_decper(D, p1, p2, p3, p4)\n% $$$ K = p1^2*exp(-0.5*(D.^2)/(p2^2)-2*sin(pi*D*p3).^2/(p4^2));\n% $$$ \n% $$$ if nargout >= 2\n% $$$   dK = zeros([size(D),4]);\n% $$$   dK(:,:,1) = K .* 2 / p1;\n% $$$   dK(:,:,2) = K .* (-0.5*D.^2) .* (-2*p2^(-3));\n% $$$   dK(:,:,3) = K .* (-2*sin(pi*D*p3)*2) .* cos(pi*D*p3) .* (pi*D);\n% $$$   dK(:,:,4) = K .* (-2*sin(pi*D*p3).^2) * (-2)*p4^(-3);\n% $$$ end\n% $$$ \n% $$$ % $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ % $$$ function [K,dK] = gpK_ratquad(D, p1, p2, p3)\n% $$$ % $$$ %%% p3 = p3^2;\n% $$$ % $$$ f = 1 + D.^2/(2*p3^2*p2^2);\n% $$$ % $$$ K = p1^2*f.^(-p3^2);\n% $$$ % $$$ \n% $$$ % $$$ if nargout >= 2\n% $$$ % $$$   dK = zeros([size(D),3]);\n% $$$ % $$$   dK(:,:,1) = K .* 2 / p1;\n% $$$ % $$$   dK(:,:,2) = K .* (-p3^2).*f.^(-1) .* (-2).*D.^2/(2*p3^2)*p2^(-3);\n% $$$ % $$$   dK(:,:,3) = K .* (-2*p3*log(f) + (-p3^2)./f.*D.^2/(2*p2^2) * (-2) * p3^(-3));\n% $$$ % $$$ end\n% $$$ \n% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ function [f, df] = cost(y,funcK,p)\n% $$$ [K,dK] = funcK(p);\n% $$$ [f,df] = loglikelihood(y,K,dK);\n% $$$ f = -f;\n% $$$ df = -df;\n% $$$ \n% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ function [loglike, dloglike] = loglikelihood(y,K,dK)\n% $$$ invK = inv(K);\n% $$$ logdetK = log(det(K));\n% $$$ if logdetK < -1e100;\n% $$$   logdetK = -1e100;\n% $$$ end\n% $$$ n = length(y);\n% $$$ \n% $$$ loglike = -0.5*y'*invK*y - 0.5*logdetK - 0.5*n*log(2*pi);\n% $$$ \n% $$$ if nargout >= 2\n% $$$   m = size(dK,3);\n% $$$   dloglike = zeros(m,1);\n% $$$   a = invK * y;\n% $$$   W = a*a' - invK;\n% $$$   for i = 1:m\n% $$$     dloglike(i) = 0.5*sum(sum(W.*dK(:,:,i)));\n% $$$   end\n% $$$ end\n% $$$ \n% $$$ \n% $$$ % $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ % $$$ function y = mnorm_rnd(mu, Cov, n)\n% $$$ % $$$ m = max(length(mu), length(Cov));\n% $$$ % $$$ \n% $$$ % $$$ opts.issym = true;\n% $$$ % $$$ opts.isreal = true;\n% $$$ % $$$ [V,D] = svd(Cov);\n% $$$ % $$$ D(D<0) = 0;\n% $$$ % $$$ D = sqrt(D);\n% $$$ % $$$ A = V * D;\n% $$$ % $$$ \n% $$$ % $$$ y = repmat(mu,1,n) + A*randn(m,n);\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gppca/test_vbgppcamv_earth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5511204790406173}}
{"text": "%MDL_IR140 Create model of the ABB IRB 140 manipulator\n%\n% MDL_IRB140_MOD is a script that creates the workspace variable irb140 which\n% describes the kinematic characteristics of an ABB IRB 140 manipulator\n% using modified DH conventions.\n%\n% Also define the workspace vectors:\n%   qz         zero joint angle configuration\n%\n% Reference::\n% - ABB IRB 140 data sheet\n% - \"The modeling of a six degree-of-freedom industrial robot for \n%   the purpose of efficient path planning\",\n%   Master of Science Thesis, Penn State U, May 2009,\n%   Tyler Carter\n%\n% See also mdl_irb140, mdl_puma560, mdl_stanford, mdl_twolink, SerialLink.\n%\n% Notes::\n% - SI units of metres are used.\n% - The tool frame is in the centre of the tool flange.\n% - Zero angle configuration has the upper arm vertical and lower arm\n%   horizontal.\n\n% MODEL: ABB, IRB140, 6DOF, modified_DH\n\n\n% Copyright (C) 1993-2017, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB.  If not, see <http://www.gnu.org/licenses/>.\n%\n% http://www.petercorke.com\n\nclear L\n\n% joint angle limits from \n% A combined optimization method for solving the inverse kinematics problem...\n% Wang & Chen\n% IEEE Trans. RA 7(4) 1991 pp 489-\nL(1) = Revolute('d', 0.352, 'a', 0, 'alpha', 0, 'offset', 0, 'modified');\nL(2) = Revolute('d', 0, 'a', 0.070, 'alpha', pi/2, 'offset', 0, 'modified');\nL(3) = Revolute('d', 0, 'a', 0.360, 'alpha', 0, 'offset', 0, 'modified');\nL(4) = Revolute('d', 0.380, 'a', 0, 'alpha', pi/2, 'offset', 0, 'modified');\nL(5) = Revolute('d', 0, 'a', 0, 'alpha', -pi/2, 'offset', 0, 'modified');\nL(6) = Revolute('d', 0, 'a', 0, 'alpha', pi/2, 'offset', 0, 'modified');\n\nL(1).m = 34655.36e-3;\nL(1).r = [27.87 43.12 -89.03]*1e-3;\nL(1).I = [\n    512052539.74 1361335.88 51305020.72\n    1361335.88 464074688.59 70335556.04\n    51305020.72 70335556.04 462745526.12]*1e-9;\n\nL(2).m = 15994.59e-3;\nL(2).r = [ 198.29 9.73 92.43]*1e03;\nL(2).I = [\n    94817914.40 -3859712.77 37932017.01\n    -3859712.77 328604163.24 -1088970.86\n    37932017.01 -1088970.86 277463004.88]*1e-9;\n\nL(3).m = 20862.05e-3;\nL(3).r = [ -4.56 -79.96 -5.86];\nL(3).I = [\n    500060915.95 -1863252.17 934875.78\n    -1863252.17 75152670.69 -15204130.09\n    934875.78 -15204130.09 515424754.34]*1e-9;\n\nirb140 = SerialLink(L, 'name', 'IRB 140', ...\n    'manufacturer', 'ABB', 'comment', 'modified DH');\n\n%\n% some useful poses\n%\nqz = [0 0 0 0 0 0]; % zero angles, L shaped pose\n\nclear L\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/models/mdl_irb140_mdh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5511204717250646}}
{"text": "function [Va_idx, gamma_idx, R_idx] = Td2idx(Td)\n% Td2idx\n\nVa_trim = Td(1);\ngamma_trim = Td(2);\nR_trim = Td(3);\n\nif ~exist('P_Td', 'var')\n    param_table_T\nend\nVa_idx = floor((Va_trim - P_Td.Va_min) / P_Td.Va_step)+1;\ngamma_idx = floor((gamma_trim - P_Td.gamma_min) / P_Td.gamma_step)+1;\nif ~isfinite(R_trim)\n    R_idx = 1;\nelse\n    R_idx = floor((R_trim - P_Td.R_min) / P_Td.R_step)+2;\nend\n\nif Va_idx > P_Td.Va_n_steps\n    Va_idx = P_Td.Va_n_steps;\n    str = ['Va_trim ' num2str(Va_trim) 'm/s too big.'];\n    disp(str)\nelseif Va_idx < 1\n    Va_idx = 1;\n    str = ['Va_trim ' num2str(Va_trim) 'm/s too small.'];\n    disp(str)\nend\n\nif gamma_idx > P_Td.gamma_n_steps\n    gamma_idx = P_Td.gamma_n_steps;\n    str = ['gamma_trim ' num2str(rad2deg(gamma_trim)) ' too big.'];\n    disp(str)\nelseif gamma_idx < 1\n    gamma_idx = 1;\n    str = ['gamma_trim ' num2str(rad2deg(gamma_trim)) ' too small.'];\n    disp(str)\nend\n\nif R_idx > P_Td.R_n_steps\n    R_idx = P_Td.R_n_steps;\n    str = ['R_trim ' num2str(R_trim) 'm too big.'];\n    disp(str)\nelseif R_idx < 1\n    R_idx = 1;\n    str = ['R_trim ' num2str(R_trim) 'm too small.'];\n    disp(str)\nend\n\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/control/control_drone/Td2idx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5511204621665353}}
{"text": "function [ferns,hsPr] = fernsClfChangeFernDepth( data, hs, ferns, Snew, varargin )\n% Train random fern classifier.\n%\n% See \"Fast Keypoint Recognition in Ten Lines of Code\" by Mustafa Ozuysal,\n% Pascal Fua and Vincent Lepetit, CVPR07.\n%\n% Dimensions:\n%  M - number ferns\n%  S - fern depth\n%  F - number features\n%  N - number input vectors\n%  H - number classes\n%\n% USAGE\n%  [ferns,hsPr] = fernsClfTrain( data, hs, [varargin] )\n%\n% INPUTS\n%  data     - [NxF] N length F feature vectors\n%  hs       - [Nx1] target output labels in [1,H]\n%  varargin - additional params (struct or name/value pairs)\n%   .S        - [10] fern depth (ferns are exponential in S)\n%   .M        - [50] number of ferns to train\n%   .thrr     - [0 1] range for randomly generated thresholds\n%   .bayes    - [1] if true combine probs using bayes assumption\n%   .ferns    - [] if given reuse previous ferns (recompute pFern)\n%\n% OUTPUTS\n%  ferns    - learned fern model w the following fields\n%   .fids     - [MxS] feature ids for each fern for each depth\n%   .thrs     - [MxS] threshold corresponding to each fid\n%   .pFern    - [2^SxHxM] learned log probs at fern leaves\n%   .bayes    - if true combine probs using bayes assumption\n%   .inds     - [NxM] cached indices for original training data\n%   .H        - number classes\n%  hsPr     - [Nx1] predicted output labels\n%\n% EXAMPLE\n%  N=5000; H=5; d=2; [xs0,hs0,xs1,hs1]=demoGenData(N,N,H,d,1,1);\n%  fernPrm=struct('S',4,'M',50,'thrr',[-1 1],'bayes',1);\n%  tic, [ferns,hsPr0]=fernsClfTrain(xs0,hs0,fernPrm); toc\n%  tic, hsPr1 = fernsClfApply( xs1, ferns ); toc\n%  e0=mean(hsPr0~=hs0); e1=mean(hsPr1~=hs1);\n%  fprintf('errors trn=%f tst=%f\\n',e0,e1); figure(1);\n%  subplot(2,2,1); visualizeData(xs0,2,hs0);\n%  subplot(2,2,2); visualizeData(xs0,2,hsPr0);\n%  subplot(2,2,3); visualizeData(xs1,2,hs1);\n%  subplot(2,2,4); visualizeData(xs1,2,hsPr1);\n%\n% See also fernsClfApply, fernsInds\n%\n% Piotr's Image&Video Toolbox      Version 2.50\n% Copyright 2010 Piotr Dollar.  [pdollar-at-caltech.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the Lesser GPL [see external/lgpl.txt]\n\n% get additional parameters and check dimensions\ndfs={'thrr',[0 1],'tmp',''};\n[thrr,~]=getPrmDflt(varargin,dfs,1);\n\n[M,Sold] = size(ferns.fids);\n[N,F]=size(data); assert(length(hs)==N);\nH=max(hs); assert(all(hs>0)); assert(Snew<=20);\n\nif Snew == Sold,\nelseif Snew < Sold,\n  Sremove = Sold - Snew;\n  \n  % remove classifiers from ferns\n  ferns.thrs(:,Snew+1:Sold) = [];\n  ferns.fids(:,Snew+1:Sold) = [];\n  \n  % remove corresponding bits from inds\n  ferns.inds = bitshift(ferns.inds,-Sremove);\n  \n  % accumulate counts into parent nodes\n  ferns.counts = reshape(sum(reshape(ferns.counts,[2^Snew,2^Sremove,H,M]),2),[2^Snew,H,M]);\n  \n  % convert fern leaf class counts into probabilities\n  if( ferns.bayes<=0 )\n    norm = 1./sum(ferns.counts,2);\n    ferns.pFern = bsxfun(@times,ferns.counts,norm);\n  else\n    norm = 1./sum(ferns.counts,1);\n    ferns.pFern = bsxfun(@times,ferns.counts,norm);\n    ferns.pFern=log(ferns.pFern);\n  end\nelse\n  \n  Sadd = Snew - Sold;\n  \n  % generate some new classifiers for each fern\n  ferns.thrs(:,Sold+1:Snew) = rand(M,Sadd)*(thrr(2)-thrr(1))+thrr(1);\n  ferns.fids(:,Sold+1:Snew) = uint32(floor(rand(M,Sadd)*F+1)); \n  \n  % new lower bits to inds\n  indsadd=fernsInds(data,ferns.fids(:,Sold+1:Snew),ferns.thrs(:,Sold+1:Snew));\n  ferns.inds = bitshift(ferns.inds,Sadd) + indsadd;\n  \n  % re-histogram\n  ferns.counts = zeros(2^Snew,H,M); \n  edges = 1:2^Snew;\n  for h=1:H, \n    inds1=ferns.inds(hs==h,:);\n    for m=1:M, \n      ferns.counts(:,h,m)=histc(inds1(:,m),edges); \n    end\n  end\n  ferns.counts = ferns.counts + ferns.bayes;\n\n  % convert fern leaf class counts into probabilities\n  if( ferns.bayes<=0 )\n    norm = 1./sum(ferns.counts,2);\n    ferns.pFern = bsxfun(@times,ferns.counts,norm);\n  else\n    norm = 1./sum(ferns.counts,1);\n    ferns.pFern = bsxfun(@times,ferns.counts,norm);\n    ferns.pFern=log(ferns.pFern);\n  end\nend\n\nif(nargout==2), hsPr=fernsClfApply([],ferns,inds); end\n\nend\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/fernsClfChangeFernDepth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5511062093730826}}
{"text": "function [Y, G] = rbfOut(model, X);\n\n% RBFOUT Output of an RBF model.\n% FORMAT \n% DESC gives the output of a radial basis function model, the function is\n% a wrapper for rbffwd.\n% ARG model : the model for which the output is required.\n% ARG X : the input data for which the output is required.\n% RETURN Y : the output.\n%\n% FORMAT \n% DESC gives the output of a radial basis function model.\n% ARG model : the model for which the output is required.\n% ARG X : the input data for which the output is required.\n% RETURN Y : the output.\n% RETURN G : the hidden layer activations.\n%\n% SEEALSO : rbffwd, rbf, modelOut\n%\n% COPYRIGHT : Neil D. Lawrence, 2006, 2007, 2008\n\n% MLTOOLS\n\n  if nargout > 1\n    [Y, G] = rbffwd(model, X);\n  else\n    Y = rbffwd(model, X);\n  end\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/rbfOut.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5511061942287128}}
{"text": "function obj=stat_summary(obj,varargin)\n% stat_summary Display summarized data for each value of X\n%\n% Example syntax (default arguments): gramm_object.stat_summary('type','ci','geom','lines','setylim',false)\n% For each unique value of x, this can display various estimates of\n% the location and variability of the corresponding y distribution.\n% The optional 'name',value pairs can ne the following:\n% - 'type':\n%       - 'ci' : display the mean and the 95% confidence\n%       interval of the mean (based on the assumption of a normal\n%       distribution)\n%       - 'bootci' : display the mean and the 95% confidence\n%       interval of the mean computed by bootstrap\n%       - 'sem' : display the mean and the standard error of\n%       the mean\n%       - 'std' : display the mean and the standard deviation\n%       and the mean\n%       - 'quartile': display the 25% 50% (median) and 75%\n%       percentiles\n%       - '95percentile': display the median and 2.5 and 97.5\n%       percentiles\n%       - 'fitnormalci'\n%       - 'fitpoissonci'\n%       - 'fitbinomialci'\n%       - 'fit95percentile'\n%       - @function : provide a the handle to a custom function that takes \n%       y values (as an n_repetitions x n_data_points matrix) and returns \n%       both the central value and the CI with a matrix [y_central ; yc_CI_low ; y_CI_high]\n%       (with y_central, and y_CIs being 1 x n_data_points arrays).\n%       Example that uses the trimmed mean instead of regular mean:\n%\n%       custom_statfun = @(y)([trimmean(y,2.5);bootci(500,{@(ty)trimmean(ty,2.5),y},'alpha',0.05)]); \n%       gramm_object.stat_summary('type', custom_statfun)\n%\n% - 'geom' (possibility to combine them using a cellstr, e.g. 'geom',{'bar','black_errorbar'} ):\n%       - 'line': displays a line that connects the central locations\n%       (mean,median)\n%       - 'lines': displays a line that connects the central locations\n%       and lighter lines for the variabilities\n%       - 'area': displays a line that connects the central locations\n%       and a transparent area for the variabilities. WARNING:\n%       this changes the renderer to opengl and disables proper\n%       vector output on older matlab versions\n%       - 'area_only': displays the variabilities only, using a transparent area\n%       - 'solid_area': displays a line that connects the locations\n%       and a solid area for the variabilities. Use this for\n%       export to vector output.\n%       - 'errorbar': displays error bars for variabilities.\n%       - 'black_errorbar': displays black error bars for variabilities.\n%       - 'bar': displays the locations as bars\n%       - 'edge_bar': displays the locations as bars with black edge\n%       - 'point': displays the locations as points\n% - 'setylim': set to true if you want the y axis limits to be\n% set by the summarized data instead of the underlying data\n% points.\n% - 'interp': Use to interpolate the output, takes the same parameters as\n% interp1 in order to specify the interpolation type. When the\n% polar mode is specified as closed, or when 'interp','polar' is used\n% the interpolation uses interpft, which supposes regular sampling around the circle.\n% - 'interp_in': Use to (linearly) interpolate the input. This is intended\n% for input given as cells when the x value is different for\n% each cell and not aligned. The argument corresponds to the\n% number of points used to generate the interpolation. Ideally\n% for this the number of number of points should be higher than\n% the x resolution of the data, otherwise some data will be\n% unused.\n% - 'bin_in': Use to bin the input. This is intended for input\n% given as a 1-D array, creates bins over x and computes the summary\n% over the binned data. Argument corresponds to the number of\n% bins\n% - 'dodge': use to dodge the plotted elements depending on\n% color (recommended for 'bar', 'errorbar', 'black_errorbar').\n% A value of 0 deactivates dodging. Other values set the space\n% between the dodged elements as ratio of the x intervals.\n% - 'width': use to set the width of bars and error bars (error\n% bars are 1/4 th the width of bars).\n%\n% A setting of 'dodge',1,'width',1 will create bars that are\n% fully dodged (ie don't overlap, but are not separated) and where\n% all bars occupy the full interval between the x values, e.g.:\n% * __    *\n% *|  |__ *\n% *|  |  |*\n% *|__|__|*\n%\n% A setting of 'dodge',0.8,'width',0.8 will have fully dodged bars that are\n% not separated, but only occupy 50% of the space between x\n% values, e.g.:\n% *  _    *\n% * | |_  *\n% * | | | *\n% * |_|_| *\n%\n%A setting of 'dodge',0.8,'width',0.6 will add some\n% spacing between the bars, e.g.:\n% *  _      *\n% * | |  _  *\n% * | | | | *\n% * |_| |_| *\n%\n% A setting of 'dodge',0.8,'width',1 will create dodged but overlapping\n% bars, e.g.:\n% *  ___    *\n% * |  _|_  *\n% * | |   | *\n% * |_|___| *\n\n\n\np=inputParser;\nmy_addParameter(p,'type','ci'); %'95percentile'\nmy_addParameter(p,'geom','area');\nmy_addParameter(p,'dodge',[]);\nmy_addParameter(p,'width',[]);\nmy_addParameter(p,'setylim',false);\nmy_addParameter(p,'interp','none');\nmy_addParameter(p,'interp_in',-1);\nmy_addParameter(p,'bin_in',-1);\nparse(p,varargin{:});\n\nobj.geom=vertcat(obj.geom,{@(dobj,dd)my_summary(dobj,dd,p.Results)});\nobj.results.stat_summary={};\nend\n\n\n\n\nfunction hndl=my_summary(obj,draw_data,params)\n\n%Advanced defaults\nif isempty(params.dodge)\n    if sum(strcmp(params.geom,'bar'))>0 && draw_data.n_colors>1 %If we have a bar as geom, we dodge\n        params.dodge=0.6;\n    else\n        params.dodge=0;\n    end\nend\n\nif isempty(params.width) %If no width given\n    if params.dodge>0 %Equal to dodge if dodge given\n        params.width=params.dodge*0.8;\n    else\n        params.width=0.5;\n    end\nend\n\n\n\nif iscell(draw_data.x) || iscell(draw_data.y) %If input was provided as cell/matrix\n    \n    if params.interp_in>0\n        %If requested we interpolate the input\n        uni_x=linspace(obj.var_lim.minx,obj.var_lim.maxx,params.interp_in);\n        [x,y]=cellfun(@(x,y)deal(uni_x,interp1(x,y,uni_x,'linear')),draw_data.x,draw_data.y,'UniformOutput',false,'ErrorHandler',@(st,a,b)deal([],[]));\n        y=padded_cell2mat(y);\n        if isempty(y) %likely because we had only single points\n            y = nan(size(uni_x));\n            disp('Error in summary input interpolation... nothing plotted')\n        end\n    else\n        %If not we just make a padded matrix for fast\n        %computations (we'll assume that X are roughly at the\n        %same location for the same indices)\n        x=padded_cell2mat(draw_data.x);\n        y=padded_cell2mat(draw_data.y);\n        uni_x=nanmean(x);\n        %Add a check for X alignment\n        x_diff=max(x)-min(x);\n        if  size(x,1)>1 && any(x_diff(1:end-1)>diff(uni_x)/10) %More than a tenth of delta x variation\n            warning(['some repeated X values are misaligned (max ' num2str(max(x_diff)) '), use ''interp_in'' in stat_summary() or live with the consequences'])\n        end\n    end\n    \n    if params.bin_in>0\n        warning('bin_in in stat_summary() not supported for Matrix/Cell X/Y inputs');\n    end\n    \n    if ischar(params.type) && ~isempty(strfind(params.type,'fit'))\n        %If we have a params.type using distributions fits we\n        %can't vectorize the call to computeci so we do it in a for\n        %loop\n        ymean=zeros(length(uni_x),1);\n        yci=zeros(length(uni_x),2);\n        for ind_x=1:length(uni_x)\n            [ymean(ind_x),yci(ind_x,:)]=computeci(y(:,ind_x),params.type,obj.stat_options.alpha,obj.stat_options.nboot);\n        end\n    else\n        if size(y,1)==1\n            ymean=y;\n            yci=nan(length(uni_x),2);\n        else\n            [ymean,yci]=computeci(y,params.type,obj.stat_options.alpha,obj.stat_options.nboot);\n        end\n    end\n    \nelse %If input was provided as 1D array\n    \n    x=comb(draw_data.x);\n    y=comb(draw_data.y);\n    \n    if params.bin_in>0\n        %If X binning was requested we do it\n        binranges=linspace(obj.var_lim.minx,obj.var_lim.maxx,params.bin_in+1);\n        bincenters=(binranges(1:(end-1))+binranges(2:end))/2;\n        [~,binind]=my_histcounts(x,binranges,'count');\n        uni_x=bincenters;\n        sel=binind~=0; %histcounts can return zero as bin index if NaN data we remove them here\n        x=bincenters(binind(sel));\n        y=y(sel);\n    else\n        %         if sum(strcmp(params.geom,'area'))>0 || sum(strcmp(params.geom,'line'))>0 ||...\n        %                 sum(strcmp(params.geom,'lines'))>0  || sum(strcmp(params.geom,'solid_area'))>0\n        %             %To avoid interruptions in line and area plots we\n        %             %compute uniques over current data only\n        %             uni_x=unique(x); %Sorted is the default\n        %         else\n        %             if obj.x_factor\n        %                 %If x is a factor we space everything as one\n        %                 uni_x=obj.var_lim.minx:1:obj.var_lim.maxx;\n        %             else\n        %                 %compute unique Xs at the facet level to avoid\n        %                 %weird bar sizing issues when dodging and when\n        %                 %colors are missing\n        %                 facet_x=comb(draw_data.facet_x);\n        %                 uni_x=unique(facet_x);\n        %             end\n        %         end\n        \n        uni_x=unique(x);\n        \n        %Here we need to implement a loose 'unique' because of\n        %potential numerical errors\n        uni_x(diff(uni_x)<1e-10)=[];\n    end\n    \n    if params.interp_in>0\n        warning('interp_in in stat_summary() not supported for non Matrix/Cell X/Y inputs');\n    end\n    \n    ymean=nan(length(uni_x),1);\n    yci=nan(length(uni_x),2);\n    \n    %Loop over unique X values\n    for ind_x=1:length(uni_x)\n        %And here we have a loose selection also because of\n        %potential numerical errors\n        ysel=y(abs(x-uni_x(ind_x))<1e-10);\n        \n        if ~isempty(ysel)\n            [ymean(ind_x),yci(ind_x,:)]=computeci(ysel,params.type,obj.stat_options.alpha,obj.stat_options.nboot);\n        end\n    end\nend\n\n\n%Do we set the y limits according to the smoothed curves or to\n%the original data ?\nif params.setylim\n    if sum(sum(isnan(yci)))~=numel(yci) %We only do this if yci is not weird\n        if obj.firstrun(obj.current_row,obj.current_column) %Initialize for the first run in the subplot\n            obj.plot_lim.maxy(obj.current_row,obj.current_column)=max(max(yci));\n            obj.plot_lim.miny(obj.current_row,obj.current_column)=min(min(yci));\n        else %Update for subsequent runs in the subplot\n            if max(max(yci))>obj.plot_lim.maxy(obj.current_row,obj.current_column)\n                obj.plot_lim.maxy(obj.current_row,obj.current_column)=max(max(yci));\n            end\n            if min(min(yci))<obj.plot_lim.miny(obj.current_row,obj.current_column)\n                obj.plot_lim.miny(obj.current_row,obj.current_column)=min(min(yci));\n            end\n        end\n    end\nend\n\n%When we do bar plots we want to have zero in the y axis anyway\nif sum(strcmp(params.geom,'bar'))>0\n    if obj.plot_lim.miny(obj.current_row,obj.current_column)>0 %Values above zero -> change miny\n        obj.plot_lim.miny(obj.current_row,obj.current_column)=0;\n    end\n    if obj.plot_lim.maxy(obj.current_row,obj.current_column)<0 %Values below zero -> change maxy\n        obj.plot_lim.maxy(obj.current_row,obj.current_column)=0;\n    end\nend\n\n%Do we interpolate the summary results for display ?\nif ~strcmp(params.interp,'none')\n    if size(yci,1)>2\n        yci=yci';\n    end\n    \n    if obj.polar.is_polar && obj.polar.is_polar_closed && ~strcmp(params.interp,'polar')\n        disp([params.interp ' interpolation overriden, ''polar'' used']);\n        params.interp='polar'; %%If the plot is polar we override the interpolation type do an optimal fft interpolation\n    end\n    \n    if strcmp(params.interp,'polar')\n        %Perform checks on uni_x\n        dx=unique_no_nan(diff([uni_x ; uni_x(1)+2*pi])); %compute step\n        if any(abs(diff(dx))>1e-12) %handle numerical precision problems (exact version would be length(dx)>1 )\n            disp('ERROR: ''polar'' interpolation requires periodic sampling, displayed results are incorrect');\n        end\n        uni_x=uni_x(1):pi/50:uni_x(1)+99*pi/50;\n        ymean=interpft(ymean,100);\n        tmp_yci1=interpft(yci(1,:),100);\n        tmp_yci2=interpft(yci(2,:),100);\n        yci=[tmp_yci1 ; tmp_yci2];\n    else\n        %For non polar plots we do a regular interpolation\n        new_x=linspace(min(uni_x),max(uni_x),100);\n        ymean=interp1(uni_x,ymean,new_x,params.interp);\n        tmp_yci1=interp1(uni_x,yci(1,:),new_x,params.interp);\n        tmp_yci2=interp1(uni_x,yci(2,:),new_x,params.interp);\n        yci=[tmp_yci1 ; tmp_yci2];\n        uni_x=new_x;\n    end\nend\n\n%If X were modified\nif params.bin_in>0 || params.interp_in>0 || ~strcmp(params.interp,'none')\n    %We reinitialize dodging parameters for plotci to work correctly\n    draw_data.dodge_avl_w=uni_x(2)-uni_x(1);\n    draw_data.dodge_fallback=true;\n    draw_data.dodge_x=1;\n    draw_data.dodge_n=draw_data.n_colors;\n    draw_data.dodge_ind=draw_data.color_index;\n    \n    %draw_data.dodge_x=shiftdim(uni_x);\n    %draw_data.dodge_n=repmat(draw_data.n_colors,length(uni_x),1);\n    %draw_data.dodge_ind=repmat(draw_data.color_index,length(uni_x),1);\nend\n\n%Store results\nobj.results.stat_summary{obj.result_ind,1}.x=uni_x;\nobj.results.stat_summary{obj.result_ind,1}.y=ymean;\nobj.results.stat_summary{obj.result_ind,1}.yci=yci;\n\n%Do the actual plotting\nhndl=plotci(obj,uni_x,ymean,yci,draw_data,params.geom,params.dodge,params.width);\n\n%Copy handles\nif isstruct(hndl)\n    hnames=fieldnames(hndl);\n    for k=1:length(hnames)\n        obj.results.stat_summary{obj.result_ind,1}.(hnames{k})=hndl.(hnames{k});\n    end\nelse\n    disp('Nothing plotted... Error in summary computation?')\nend\nend\n\n\n\nfunction [ymean,yci]=computeci(y,type,alpha,nboot)\n\nymean=nanmean(y);\n\n%Check number of samples\nnsamp=size(y,1);\nif nsamp<3 && strcmp(type,'bootci')\n    disp('Less than 3 samples for bootstrap CI computation...Skipping')\n    yci=repmat([NaN NaN],size(y,2));\n    return;\nend\nif nsamp<2\n    disp('Less than 2 samples for CI computation...Skipping')\n    yci=repmat([NaN NaN],size(y,2));\n    return;\nend\n\nif isa(type,'function_handle')\n    try\n        temp=type(y);\n        ymean=temp(1,:);\n        yci=temp(2:3,:);\n    catch ME\n        disp(['Error in custom summary computation: ' ME.message ' ...skipping']);\n        yci=repmat([NaN NaN],size(y,2));\n        ymean=nan(size(y,2),1);\n    end\n    return;\nend\n\ntry\n    switch type\n        case 'bootci'\n            yci=bootci(nboot,{@(ty)nanmean(ty),y},'alpha',alpha);\n        case 'ci'\n            %ci=1.96*nanstd(y)./sqrt(sum(~isnan(y)));\n            %Correction for small samples (equivalent to fitnormalci)\n            ci=tinv(1-alpha/2,sum(~isnan(y))-1).*nanstd(y)./sqrt(sum(~isnan(y)));\n            yci=bsxfun(@plus,ymean,[-ci;ci]);\n        case 'std'\n            ci=nanstd(y);\n            yci=bsxfun(@plus,ymean,[-ci;ci]);\n        case 'sem'\n            ci=nanstd(y)./sqrt(sum(~isnan(y)));\n            yci=bsxfun(@plus,ymean,[-ci;ci]);\n        case 'quartile'\n            ymean=nanmedian(y);\n            yci=prctile(y,[25 75]);\n        case '95percentile'\n            ymean=nanmedian(y);\n            yci=prctile(y,[2.5 97.5]);\n        case 'fitnormalci'\n            pd=fitdist(y,'Normal');\n            ymean=pd.mean();\n            ci=paramci(pd,alpha);\n            yci=ci(:,1)';\n        case 'fitpoissonci'\n            pd=fitdist(y,'Poisson');\n            ymean=pd.mean();\n            ci=paramci(pd,alpha);\n            yci=ci(:,1)';\n        case 'fitnegbinomialci'\n            pd=fitdist(y,'NegativeBinomial');\n            ymean=pd.mean();\n            ci=paramci(pd,alpha);\n            yci=ci(:,1)';\n        case 'fitbinomialci'\n            pd=fitdist(y,'Binomial');\n            ymean=pd.mean;\n            ci=paramci(pd,alpha);\n            yci=ci(:,2)';\n        case 'fit95percentile'\n            pd=fitdist(y,'Normal');\n            ymean=pd.icdf(0.5);\n            yci=pd.icdf([0.025 0.975]);\n        otherwise\n            warning(['Unknown CI type ' type]);\n    end\ncatch ME\n    disp(['Error in CI computation: ' ME.message ' ...skipping']);\n    yci=repmat([NaN NaN],size(y,2));\nend\nend\n", "meta": {"author": "piermorel", "repo": "gramm", "sha": "b0fc59245c17d6fbcd86a105d893aeb745fb51e2", "save_path": "github-repos/MATLAB/piermorel-gramm", "path": "github-repos/MATLAB/piermorel-gramm/gramm-b0fc59245c17d6fbcd86a105d893aeb745fb51e2/@gramm/stat_summary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5511061942287127}}
{"text": "function rimgs = slresizeimg(imgs, newsiz, interpker)\n%SLRESIZEIMG Resizes the images by interpolation\n%\n% $ Syntax $\n%   - rimgs = slresizeimg(imgs, newsiz, interpker)\n%\n% $ Arguments $\n%   - imgs:         The set of images\n%   - newsiz:       The new image size to be resized to\n%                   It can be in two forms:\n%                   - [new_height, new_width]\n%                   - ratio to the original size\n%   - interpker:    The interpolation kernel (default = 'linear')\n%   - rimgs:        The resized images\n%\n% $ Description $\n%   - rimgs = slresizeimg(imgs, newsiz, interpker) resizes the image\n%     to new size by interpolation. \n%\n% $ Remarks $\n%   - The implementation is based on slimginterp.\n%\n% $ History $\n%   - Created by Dahua Lin, on Sep 3, 2006\n%\n\n%% parse and verify input\n\nif nargin < 2\n    raise_lackinput('slresizeimg', 2);\nend\nh0 = size(imgs, 1);\nw0 = size(imgs, 2);\n\nif isnumeric(newsiz)\n    if length(newsiz) == 1\n        h = newsiz * h0;\n        w = newsiz * w0;\n    elseif length(newsiz) == 2\n        [h, w] = sltakeval(newsiz);\n    else\n        error('sltoolbox:invalidarg', 'The newsiz is invalid');\n    end\nelse\n    error('sltoolbox:invalidarg', 'The newsiz is invalid');\nend\n\nif nargin < 3 || isempty(interpker)\n    interpker = 'linear';\nend\n\n%% generate coordinate map\n\nI = linspace(1, h0, h)';\nJ = linspace(1, w0, w);\nI = I(:, ones(1, w));\nJ = J(ones(h, 1), :);\n\n%% Do interpolation\n\nrimgs = slimginterp(imgs, I, J, interpker);\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/imgproc/slresizeimg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956580806813576, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5511061858521902}}
{"text": "function f2 = p06_f2 ( x )\n\n%*****************************************************************************80\n%\n%% P06_F2 evaluates the second derivative for problem 6.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    26 February 2002\n%\n%  Author:\n%\n%    John Burkardt\n%\n%  Reference:\n%\n%    LE Scales,\n%    Introduction to Non-Linear Optimization,\n%    Springer, 1985.\n%\n%  Parameters:\n%\n%    Input, real X, the values of the variables.\n%\n%    Output, real F2, the second derivative.\n%\n  f2 = 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_min/p06_f2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.5510392233479604}}
{"text": "function out = WL_dwtcoeff(y,wname,level)\n% WL_dwtcoeff   Discrete wavelet transform coefficients.\n%\n% Decomposes the time series using a given wavelet and outputs statistics on the\n% coefficients obtained up to a maximum level, level.\n%\n%---INPUTS:\n%\n% y, the input time series\n%\n% wname, the mother wavelet, e.g., 'db3', 'sym2' (see Wavelet Toolbox\n%           Documentation)\n%\n% level, the level of wavelet decomposition (can be set to 'max' for the maximum\n%               level determined by wmaxlev)\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,\n% <http://www.benfulcher.com>\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 <http://www.gnu.org/licenses/>.\n% ------------------------------------------------------------------------------\n\n% ------------------------------------------------------------------------------\n%% Check that a Wavelet Toolbox license is available:\n% ------------------------------------------------------------------------------\nBF_CheckToolbox('wavelet_toolbox')\n\n% ------------------------------------------------------------------------------\n%% Check Inputs\n% ------------------------------------------------------------------------------\ndoPlot = false; % Plot results to figures\nN = length(y); % Length of the time series\n\nif nargin < 2 || isempty(wname)\n    wname = 'db3'; % Daubechies wavelet filter\nend\nif nargin < 3 || isempty(level)\n    level = 3; % level of wavelet decomposition\nend\nif strcmp(level,'max')\n    level = wmaxlev(N,wname);\nend\n\nmaxLevelAllowed = wmaxlev(N,wname);\nif maxLevelAllowed < level\n    fprintf(1,'Chosen level is too large for this wavelet on this signal...\\n');\nend\n\n% ------------------------------------------------------------------------------\n%% Perform Wavelet Decomposition\n% ------------------------------------------------------------------------------\n% Computes the following:\n%   (*) Wavelet decomposition vector, c\n%   (*) Bookkeeping vector, l\n\nif maxLevelAllowed < level\n    [c, l] = wavedec(y, maxLevelAllowed, wname);\nelse\n    [c, l] = wavedec(y, level, wname);\nend\n\n%% Expand DWT coefficients for visualization\n% nbcol = 64; % color discretization steps\n%\n% cfd = zeros(level,N); % detail coefficients\n% for k = 1:level\n%     d = detcoef(c,l,k);\n%     d = d(:)';\n%     d = d(ones(1,2^k),:);\n%     cfd(k,:) = wkeep1(d(:)',N);\n% end\n%\n% cfd =  cfd(:);\n% I = find(abs(cfd)<sqrt(eps));\n% cfd(I) = zeros(size(I));\n% cfd = reshape(cfd,level,N);\n% cfd = wcodemat(cfd,nbcol,'row');\n\n%-------------------------------------------------------------------------------\n%% Plotting\n%-------------------------------------------------------------------------------\nif doPlot\n    figure('color','w'); box('on');\n    colormap(pink(nbcol));\n    image(cfd);\n    tics = 1:level;\n    labs = int2str((1:level)');\n    set(gca,'YTicklabelMode','manual','Ydir','normal', 'Box','On','Ytick',tics,'YTickLabel',labs);\n    title('Discrete Wavelet Transform, Absolute Coefficients.');\n    xlabel('Time (or Space)')\n    ylabel('Level');\nend\n\n% ------------------------------------------------------------------------------\n%% Get statistics on coefficients\n% ------------------------------------------------------------------------------\nfor k = 1:level\n    if k <= maxLevelAllowed\n        d = detcoef(c,l,k); % detail coefficients at level k\n        % maximum coefficient at this level:\n        out.(sprintf('maxd_l%u',k)) = max(d);\n        % minimum coefficient at this level:\n        out.(sprintf('mind_l%u',k)) = min(d);\n        % std coefficients at this level:\n        out.(sprintf('stdd_l%u',k)) = std(d);\n        % 1-D noise coefficient estimate (estimate of the noise std):\n        out.(sprintf('noisestd_l%u',k)) = wnoisest(c,l,k);\n    else\n        out.(sprintf('maxd_l%u',k)) = NaN;\n        out.(sprintf('mind_l%u',k)) = NaN;\n        out.(sprintf('stdd_l%u',k)) = NaN;\n        out.(sprintf('noisestd_l%u',k)) = NaN;\n    end\nend\n\n\n% %% Compress Signal\n% % Set approximation coefficients to zero\n% % nc = wthcoef('a',c,l);\n% NC = wthcoef('t',c,l,N,T,SORH);\n%\n%\n% %% Single Level Reconstruction\n% X = waverec(c,l,wname);\n% plot(X);\n% keyboard\n\n\n%% Extract Approximation Coefficients from wavelet decomposition structure\n\n% CA = appcoef(C,L,wname,level);\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/WL_dwtcoeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5510392226624866}}
{"text": "function G = greens_function_mono(x,y,z,xs,src,f,conf)\n%GREENS_FUNCTION_MONO Green's function in the frequency domain\n%\n%   Usage: G = greens_function_mono(x,y,z,xs,src,f,conf)\n%\n%   Input options:\n%       x,y,z   - x,y,z points for which the Green's function should be\n%                 calculated / m\n%       xs      - position of the source\n%       src     - source model of the Green's function. Valid models are:\n%                   'ps'  - point source\n%                   'ls'  - line source\n%                   'pw'  - plane wave\n%                   'dps' - dipole point source\n%       f       - frequency of the source / Hz\n%       conf    - configuration struct (see SFS_config)\n%\n%   Output parameters:\n%       G       - Green's function evaluated at the points x,y,z\n%\n%   GREENS_FUNCTION_MONO(x,y,z,xs,src,f,conf) calculates the Green's function\n%   for the given source model located at xs for the given points x,y and the\n%   frequency f.\n%\n%   See also: sound_field_mono\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 ==================================\n% Disabled checking for performance reasons\n\n\n%% ===== Configuration ==================================================\nc = conf.c;\nphase = conf.phase;\n\n\n%% ===== Computation =====================================================\n% Frequency\nomega = 2*pi*f;\n% Calculate Green's function for the given source model\nif strcmp('ps',src)\n    % Source model for a point source: 3D Green's function.\n    %\n    %              1  e^(-i w/c |x-xs|)\n    % G(x-xs,w) = --- -----------------\n    %             4pi      |x-xs|\n    %\n    % https://sfs.rtfd.io/en/3.2/sources/#equation-fd-point\n    %\n    G = 1/(4*pi) * exp(-1i*omega/c .* sqrt((x-xs(1)).^2+(y-xs(2)).^2+(z-xs(3)).^2)) ./ ...\n            sqrt((x-xs(1)).^2+(y-xs(2)).^2+(z-xs(3)).^2);\n\nelseif strcmp('dps',src)\n    % Source model for a dipole point source: derivative of 3D Green's function.\n    %\n    %  d                1   / iw       1    \\   (x-xs) ns\n    % ---- G(x-xs,w) = --- | ----- + ------- | ----------- e^(-i w/c |x-xs|)\n    % d ns             4pi  \\  c     |x-xs| /   |x-xs|^2\n    %\n    % r = |x-xs|\n    r = sqrt((x-xs(1)).^2+(y-xs(2)).^2+(z-xs(3)).^2);\n    % scalar = (x-xs) nxs\n    scalar = xs(4).*(x-xs(1)) + xs(5).*(y-xs(2))  + xs(6).*(z-xs(3));\n    %\n    G = 1/(4*pi) .* (1i*omega/c + 1./r) .* scalar./r.^2 .* exp(-1i*omega/c.*r);\n\nelseif strcmp('ls',src)\n    % Source model for a line source: 2D Green's function.\n    %\n    %                i   (2) / w        \\\n    % G(x-xs,w) =  - -  H0  |  - |x-xs|  |\n    %                4       \\ c        /\n    %\n    % https://sfs.rtfd.io/en/3.2/sources/#equation-fd-line\n    %\n    G = -1i/4 * besselh(0,2,omega/c* ...\n        sqrt( (x-xs(1)).^2 + (y-xs(2)).^2 + (z-xs(3)).^2 ));\n\nelseif strcmp('pw',src)\n    % Source model for a plane wave:\n    %\n    % G(x,w) = e^(-i w/c n x)\n    %\n    % https://sfs.rtfd.io/en/3.2/sources/#equation-fd-plane\n    %\n    % Direction of plane wave\n    nxs = xs(:,1:3) / norm(xs(:,1:3));\n    % Calculate sound field\n    G = exp(-1i*omega/c.*(nxs(1).*x+nxs(2).*y+nxs(3).*z));\nelse\n    error('%s: %s is not a valid source model for the Green''s function', ...\n        upper(mfilename),src);\nend\n\n% Add phase to be able to simulate different time steps\nG = G .* exp(-1i*phase);\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_monochromatic/greens_function_mono.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6513548782017746, "lm_q1q2_score": 0.551008738278463}}
{"text": "classdef MimImageCoordinateUtilities\n    % MimImageCoordinateUtilities. Utility functions related to processing 3D\n    % image coordinates\n    %\n    %\n    %     Licence\n    %     -------\n    %     Part of the TD MIM Toolkit. https://github.com/tomdoel\n    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com\n    %     Distributed under the MIT licence. Please see website for details.\n    %    \n    \n    methods (Static)\n        \n        % In Matlab, matrices can be represented as a linear vector. So every\n        % point in a 3D matrix has a linear index as well as an i-j-k\n        % coordinate. This function returns the 'offset' values which can be\n        % added to the linear index of any point to return the linear indices of\n        % its nearest neighbours.\n        function [linear_offsets, linear_offsets27] = GetLinearOffsets(image_size)\n            % Compute linear index offsets for diretion vectors\n            dirs = [5, 23, 11, 17, 13, 15];\n            linear_offsets = MimImageCoordinateUtilities.GetLinearOffsetsForDirections(dirs, image_size);\n            \n            dirs = 1:27;\n            linear_offsets27 = MimImageCoordinateUtilities.GetLinearOffsetsForDirections(dirs, image_size);\n        end\n        \n        function linear_offsets = GetLinearOffsetsForDirections(dirs, image_size)\n            direction_vectors = MimImageCoordinateUtilities.CalculateDirectionVectors;            \n            linear_offsets = zeros(1, numel(dirs));\n            for n = 1 : length(dirs)\n                direction = dirs(n);\n                direction_vector = direction_vectors(direction, :);\n                start_point = [2 2 2];\n                i_end_point = start_point + direction_vector;\n                i = [start_point(1); i_end_point(1)];\n                j = [start_point(2); i_end_point(2)];\n                k = [start_point(3); i_end_point(3)];\n                linear_indices = sub2ind(image_size, i, j, k);\n                linear_offsets(n) = linear_indices(2) - linear_indices(1);\n            end\n        end\n        \n        % Returns the coordinates of each point in a 3x3x3 matrix relative to\n        % its centre\n        function direction_vectors = CalculateDirectionVectors\n            [i, j, k] = ind2sub([3 3 3], 1:27);\n            direction_vectors = [i' - 2, j' - 2, k' - 2];\n        end\n\n        % This function alters matrix indices to transform from a smaller matrix to\n        % a bigger one\n        function new_indices = OffsetIndices(indices, offset, size_small, size_big)\n            indices_i = (indices - 1);\n            div1 = (size_small(1));\n            div2 = (size_small(1)*size_small(2));\n            \n            k_mod = rem(indices_i, div2);\n            \n            k = (indices_i - k_mod)/div2; % Equivalent to idivide but quicker\n            \n            i = mod(k_mod, div1);\n            \n            j = (k_mod - i)/div1; % Equivalent to idivide but quicker\n            \n            i = i + offset(1);\n            j = j + offset(2);\n            k = k + offset(3);\n\n            % Note that i,j,k can be negative, in the case where a border has\n            % been added to the image so its coordinates extend beyond the\n            % boundaries of the original image\n            \n            new_indices = 1 + (i) + (j)*size_big(1) + (k)*size_big(1)*size_big(2);\n        end\n        \n        % Creates an image cropped to the smallest box size that encloses all\n        % the points specified by their linear indices.\n        function [offset reduced_image reduced_image_size] = GetMinimalImageForIndices(indices, image_size)\n            if size(indices, 1) > 1\n                error('GetMinimalImageForIndices requires indices to be in a row vector');\n            end\n            indices = int32(indices);\n            [i, j, k] = MimImageCoordinateUtilities.FastInd2sub(image_size, indices);\n            \n            voxel_coordinates = [i' j' k'];\n            mins = min(voxel_coordinates, [], 1);\n            maxs = max(voxel_coordinates, [], 1);\n            reduced_image_size = maxs - mins + int32([1 1 1]);\n            reduced_image = false(reduced_image_size);\n            offset = mins - 1;\n            i = MimImageCoordinateUtilities.FastSub2ind(reduced_image_size, voxel_coordinates(:,1)-offset(1), voxel_coordinates(:,2)-offset(2), voxel_coordinates(:,3)-offset(3));\n            \n            reduced_image(i) = true;\n        end\n        \n        % A faster alternative to Ind2sub\n        function [i, j, k] = FastInd2sub(im_size, indices)\n            indices = indices - 1;\n            div1 = (im_size(1));\n            div2 = ((im_size(1)*im_size(2)));\n            \n            k_mod = rem(indices, div2);\n            \n            k = 1 + (indices - k_mod)/div2; % Equivalent to idivide but quicker\n            i = 1 + mod(k_mod, im_size(1));\n            j = 1 + (k_mod - i + 1)/div1; % Equivalent to idivide but quicker\n        end\n        \n        function indices = FastSub2ind(im_size, i, j, k)\n            indices = i + (j-1)*im_size(1) + (k-1)*im_size(1)*im_size(2);\n        end\n\n        function rot_matrix = GetEulerRotationMatrix(phi, theta, psi)\n            rot_matrix = zeros(3,3);\n            \n            rot_matrix(1, 1) = cos(psi)*cos(phi) - cos(theta)*sin(phi)*sin(psi);\n            rot_matrix(1, 2) = cos(psi)*sin(phi) + cos(theta)*cos(phi)*sin(psi);\n            rot_matrix(1, 3) = sin(psi)*sin(theta);\n            \n            rot_matrix(2, 1) = -sin(psi)*cos(phi) - cos(theta)*sin(phi)*cos(psi);\n            rot_matrix(2, 2) = -sin(psi)*sin(phi) + cos(theta)*cos(phi)*cos(psi);\n            rot_matrix(2, 3) = cos(psi)*sin(theta);\n            \n            rot_matrix(3, 1) =  sin(theta)*sin(phi);\n            rot_matrix(3, 2) = -sin(theta)*cos(psi);\n            rot_matrix(3, 3) = cos(theta);\n        end\n        \n        function affine_matrix = CreateAffineMatrix(x)\n            affine_matrix = zeros(3, 4, 'single');\n            affine_matrix(:) = x(:);\n            affine_matrix = [affine_matrix; [0 0 0 1]];\n        end\n        \n        function affine_matrix = CreateAffineTranslationMatrix(x)\n            affine_matrix = zeros(3, 4, 'single');\n            affine_matrix(1, 1) = 1;\n            affine_matrix(2, 2) = 1;\n            affine_matrix(3, 3) = 1;\n            affine_matrix(4, 4) = 1;\n            affine_matrix(1:3, 4) = x;\n        end\n        \n        function affine_matrix = CreateRigidAffineMatrix(x)\n            affine_matrix = zeros(3, 4, 'single');\n            \n            euler_rot_matrix = MimImageCoordinateUtilities.GetEulerRotationMatrix(x(1), x(2), x(3));\n            affine_matrix(1:3, 1:3) = euler_rot_matrix;\n            affine_matrix(1:3, 4) = x(4:6);\n            \n            affine_matrix = [affine_matrix; [0 0 0 1]];\n        end\n        \n        function [i, j, k] = TransformCoordsAffine(i, j, k, augmented_matrix)\n            [j, i, k] = MimImageCoordinateUtilities.TranslateAndRotateMeshGrid(j, i, k, augmented_matrix(1:3,1:3), augmented_matrix(1:3,4));\n        end\n        \n        function [i, j, k] = TransformCoordsFluid(i, j, k, deformation_field)\n            i = i - deformation_field.RawImage(:,:,:,1);\n            j = j - deformation_field.RawImage(:,:,:,2);\n            k = k - deformation_field.RawImage(:,:,:,3);\n        end\n        \n        function [X, Y, Z] = TranslateAndRotateMeshGrid(X, Y, Z, rot_matrix, trans_matrix)\n            % Rotates and translates meshgrid generated coordinates in 3D\n            % Note coordinates are [XYZ] NOT [IJK]\n            [X, Y, Z] = MimImageCoordinateUtilities.RotateMeshGrid(X + trans_matrix(1), Y + trans_matrix(2), Z + trans_matrix(3), rot_matrix);\n        end\n\n        function [X, Y, Z] = RotateMeshGrid(X, Y, Z, rot_matrix)\n            % Rotates coordinates that are given in 3D meshgrid matrices\n            coords = rot_matrix * [ ...\n                reshape(X, 1, numel(X)); ...\n                reshape(Y, 1, numel(Y)); ...\n                reshape(Z, 1, numel(Z)) ...\n                ];\n            \n            X = reshape(coords(1, :), size(X));\n            Y = reshape(coords(2, :), size(Y));\n            Z = reshape(coords(3, :), size(Z));\n        end\n        \n        function affine_matrix = GetAffineTranslationFromPatientPosition(image_1, image_2)\n            \n            % Get the coordinates of the centre of the first voxel in image1,\n            % relative to the centre of image1\n            [i1, j1, k1] = image_1.GlobalCoordinatesToCoordinatesMm([1, 1, image_1.OriginalImageSize(3)]);\n            [i1, j1, k1] = image_1.GlobalCoordinatesMmToCentredGlobalCoordinatesMm(i1, j1, k1);\n            image_1_origin_coordinates = [i1, j1, k1];\n            image_1_centre_coordinates = image_1.GlobalOrigin - image_1_origin_coordinates;\n            \n            % Get the coordinates of the centre of the first voxel in image2,\n            % relative to centre of image2\n            [i2, j2, k2] = image_2.GlobalCoordinatesToCoordinatesMm([1, 1, image_2.OriginalImageSize(3)]);\n            [i2, j2, k2] = image_2.GlobalCoordinatesMmToCentredGlobalCoordinatesMm(i2, j2, k2);\n            image_2_origin_coordinates = [i2, j2, k2];\n            image_2_centre_coordinates = image_2.GlobalOrigin - image_2_origin_coordinates;\n            \n            translation = image_1_centre_coordinates - image_2_centre_coordinates;\n\n            translation = translation([2 1 3]);\n            translation(3) = - translation(3);\n            affine_matrix = MimImageCoordinateUtilities.CreateAffineTranslationMatrix(translation);\n        end\n    \n        function deformation_field = AdjustDeformationFieldForInitialAffineTransformation(deformation_field, affine_initial_matrix)\n            % To combine a rigid transformation with a nonrigid deformation field, \n            % compute the change in image coordinates after applying the\n            % deformation field and then the rigid affine transformation.\n            \n            [df_i, df_j, df_k] = deformation_field.GetCentredGlobalCoordinatesMm;\n            [df_i, df_j, df_k] = ndgrid(df_i, df_j, df_k);\n            [df_i_t, df_j_t, df_k_t] = MimImageCoordinateUtilities.TransformCoordsFluid(df_i, df_j, df_k, deformation_field);\n            [df_i_t, df_j_t, df_k_t] = MimImageCoordinateUtilities.TransformCoordsAffine(df_i_t, df_j_t, df_k_t, affine_initial_matrix);\n            \n            deformation_field_raw = zeros(deformation_field.ImageSize);\n            deformation_field_raw(:,:,:,1) = df_i - df_i_t;\n            deformation_field_raw(:,:,:,2) = df_j - df_j_t;\n            deformation_field_raw(:,:,:,3) = df_k - df_k_t;\n            deformation_field2 = deformation_field.BlankCopy;\n            deformation_field2.ChangeRawImage(deformation_field_raw);\n            deformation_field = deformation_field2;\n        end\n        \n        function [permutation_vector, flip] = GetDimensionPermutationVectorFromDicomOrientation(orientation, reporting)\n            % Returns a vector which defines the order in which the dimensions of an\n            % DICOM image volume should be permuted in order to align it with the\n            % PTK coordinate system\n\n            % DICOM coordinates are XYZ but Matlab's coordinates are YXZ. We\n            % convert the orientation to Matlab coordinates, which we refer to as IJK.\n            orientation_1 = orientation([5, 4, 6])'; % Direction of first image axis in ijk (=yxz) coordinates\n            orientation_2 = orientation([2, 1, 3])'; % Direction of second image axis in ijk (=yxz) coordinates\n            \n            % By switching the i and j axes we have inverted the coordinate\n            % system, so we need to flip the k dimension\n            orientation_1(3) = - orientation_1(3);\n            orientation_2(3) = - orientation_2(3);\n            \n            % Determine the PTK dimensions to which each of these vectors correspond\n            [permutation_vector, dimension_1, dimension_2, dimension_3] = MimImageCoordinateUtilities.GetPermutationFromOrientations(orientation_1, orientation_2, reporting);\n\n            % Calculate flip for each dimension, based on whether the\n            % dimension axis lies in the same or opposite direction to the\n            % image axis\n            orientation_3 = cross(orientation_2, orientation_1);\n            flip = MimImageCoordinateUtilities.GetFlipFromOrientations(orientation_1, orientation_2, orientation_3, dimension_1, dimension_2, dimension_3);\n            \n            % Check the resulting vector is valid\n            if (sum(permutation_vector == 1) ~= 1) || (sum(permutation_vector == 2) ~= 1) || (sum(permutation_vector == 3) ~= 1) || ...\n                    ~isempty(setdiff(permutation_vector, [1,2,3]))\n                reporting.Error('MimImageCoordinateUtilities:InvalidPermutationVector', 'GetDimensionPermutationVectorFromDicomOrientation() resulted in an invalid permutation vector');\n            end\n        end\n        \n        function [permutation_vector, flip] = GetDimensionPermutationVectorFromNiiOrientation(header, reporting)\n            % Returns a vector which defines the order in which the dimensions of a\n            % nii image volume should be permuted in order to align it with the\n            % PTK coordinate system\n\n            if header.SformCode > 0\n                d1 = [-1; -1; 1].*header.SrowX(1:3);\n                d2 = [-1; -1; 1].*header.SrowY(1:3);\n                [permutation_vector, flip] = MimImageCoordinateUtilities.GetDimensionPermutationVectorFromDicomOrientation([d1; d2], reporting);\n            elseif header.QformCode > 0\n                B = header.QuaternB;\n                C = header.QuaternC;\n                D = header.QuaternD;\n                A = sqrt(1 - B^2 - C^2 - D^2);\n                d1 = [-1; -1; 1].*[A^2+B^2-C^2-D^2; 2*(B*C - A*D); 2*(B*D+A*C)];\n                d2 = [-1; -1; 1].*[2*(B*C + A*D); A^2 + C^2 - B^2 - D^2; 2*(C*D - A*B)];\n                d3 = [-1; -1; 1].*[2*(B*D - A*C); 2*(C*D + A*B); A^2 + D^2 - B^2 - C^2];\n                [permutation_vector, flip] = MimImageCoordinateUtilities.GetDimensionPermutationVectorFromDicomOrientation([d1; d2], reporting);\n            else\n                d1 = [-1; -1; 1].*[1; 0; 0];\n                d2 = [-1; -1; 1].*[0; 1; 0];\n                [permutation_vector, flip] = MimImageCoordinateUtilities.GetDimensionPermutationVectorFromDicomOrientation([d1; d2], reporting);\n            end\n        end\n                \n        function [permutation_vector, flip] = GetDimensionPermutationVectorForAnalyze(orientation, reporting)\n            permutation_vector = [2, 1, 3];\n            flip = [false, false, true];\n        end\n        \n        function [permutation_vector, dimension_1, dimension_2, dimension_3] = GetPermutationFromOrientations(orientation_1, orientation_2, reporting)\n            [dimension_1, dimension_2, dimension_3] = MimImageCoordinateUtilities.GetDimensionIndicesFromOrientations(orientation_1, orientation_2, reporting);\n            \n            permutation_vector = [3, 3, 3];\n            permutation_vector(dimension_1) = 1;\n            permutation_vector(dimension_2) = 2;\n        end\n        \n        function flip = GetFlipFromOrientations(orientation_1, orientation_2, orientation_3, dimension_1, dimension_2, dimension_3)\n            flip = [false, false, false];\n            flip(dimension_1) = orientation_1(dimension_1) < 0; \n            flip(dimension_2) = orientation_2(dimension_2) < 0;\n            flip(dimension_3) = orientation_3(dimension_3) < 0;\n        end\n        \n        function dicom_cosine = AnatomicalOrientationToDicomCosine(anatomical_orientation_char, reporting)\n            switch anatomical_orientation_char\n                case 'R'\n                    dicom_cosine = [1, 0, 0];\n                case 'L'\n                    dicom_cosine = [-1, 0, 0];\n                case 'A'\n                    dicom_cosine = [0, 1, 0];\n                case 'P'\n                    dicom_cosine = [0, -1, 0];\n                case 'I'\n                    dicom_cosine = [0, 0, 1];\n                case 'S'\n                    dicom_cosine = [0, 0, -1];\n                otherwise\n                    reporting.Error('MimImageCoordinateUtilities:UnknownAnatomicalOrientation', ['MimImageCoordinateUtilities: WARNING: no implementation yet for anatomical orientation ' anatomical_orientation_char '.']);\n            end\n        end\n        \n        function [permutation_vector, flip_orientation] = GetDimensionPermutationVectorFromAnatomicalOrientation(anatomical_orientation_string, reporting)\n            direction_cosine_1 = MimImageCoordinateUtilities.AnatomicalOrientationToDicomCosine(anatomical_orientation_string(1), reporting);\n            direction_cosine_2 = MimImageCoordinateUtilities.AnatomicalOrientationToDicomCosine(anatomical_orientation_string(2), reporting);\n            direction_cosine_3 = MimImageCoordinateUtilities.AnatomicalOrientationToDicomCosine(anatomical_orientation_string(3), reporting);\n            \n            [permutation_vector, flip_orientation] = MimImageCoordinateUtilities.GetDimensionPermutationVectorFromMhdCosines(direction_cosine_1, direction_cosine_2, direction_cosine_3, reporting);\n        end\n            \n        function [permutation_vector, flip_orientation] = GetDimensionPermutationVectorFromMhdCosines(direction_cosine_1, direction_cosine_2, direction_cosine_3, reporting)\n            % Determines the permutation and flip transformations required\n            % to convert MetaIO data to PTK data\n            \n            % DICOM coordinates are XYZ but Matlab's coordinates are YXZ. We\n            % convert the orientation to Matlab coordinates, which we refer to as IJK.\n            orientation_1 = direction_cosine_2([2, 1, 3])'; % Direction of first image axis in ijk (=yxz) coordinates\n            orientation_2 = direction_cosine_1([2, 1, 3])'; % Direction of second image axis in ijk (=yxz) coordinates\n            orientation_3 = direction_cosine_3([2, 1, 3])'; % Direction of third image axis in ijk (=yxz) coordinates\n            \n            % By switching the i and j axes we have inverted the coordinate\n            % system, so we need to flip the k dimension\n            orientation_1(3) = - orientation_1(3);\n            orientation_2(3) = - orientation_2(3);\n            orientation_3(3) = - orientation_3(3);\n            \n            % Determine the PTK dimensions to which each of these vectors correspond\n            [permutation_vector, dimension_1, dimension_2, dimension_3] = MimImageCoordinateUtilities.GetPermutationFromOrientations(orientation_1, orientation_2, reporting);\n\n            % Calculate flip for each dimension, based on whether the\n            % dimension axis lies in the same or opposite direction to the\n            % image axis\n            flip_orientation = MimImageCoordinateUtilities.GetFlipFromOrientations(orientation_1, orientation_2, orientation_3, dimension_1, dimension_2, dimension_3);\n            \n            % Check the resulting vector is valid\n            if (sum(permutation_vector == 1) ~= 1) || (sum(permutation_vector == 2) ~= 1) || (sum(permutation_vector == 3) ~= 1) || ...\n                    ~isempty(setdiff(permutation_vector, [1,2,3]))\n                reporting.Error('MimImageCoordinateUtilities:InvalidPermutationVector', 'GetDimensionPermutationVectorFromAnatomicalOrientation() resulted in an invalid permutation vector');\n            end            \n        end\n        \n        function [dimension_number_1, dimension_number_2, dimension_number_3] = GetDimensionIndicesFromOrientations(orientation_vector_1, orientation_vector_2, reporting)\n            % The orientation vector is formed of cosines. Typically these will\n            % be 1s and 0s but we allow for small variations in the angles.\n\n            [~, dimension_number_1] = max(abs(orientation_vector_1(:)));\n            remaining_dimensions = setdiff([1,2,3], dimension_number_1);\n            reduced_orientation_vector_2 = orientation_vector_2(remaining_dimensions);\n            [~, dimension_number_2_from_reduced_set] = max(abs(reduced_orientation_vector_2(:)));\n            dimension_number_2 = remaining_dimensions(dimension_number_2_from_reduced_set);\n            dimension_number_3 = setdiff([1, 2, 3], [dimension_number_1, dimension_number_2]);\n        end\n        \n        function spline_points = CreateSplineCurve(points, num_points)\n            number_of_points = size(points, 1);\n            number_of_coordinates = size(points, 2);\n            extended_points = zeros(number_of_points + 2, number_of_coordinates);\n            extended_points(2 : number_of_points + 1, :) = points;\n            extended_points(1, :) = extended_points(2, :) - (extended_points(3, :) - extended_points(2, :));\n            extended_points(end, :) = extended_points(end - 1, :) - (extended_points(end - 2, : ) - extended_points(end - 1, :));\n            \n            extended_number_of_points = size(extended_points, 1);\n            interval_values = linspace(0, 1, num_points + 1);\n            interval_values2 = interval_values.^2;\n            interval_values3 = interval_values.^3;\n            \n            for index = 2 : extended_number_of_points - 2\n                coeffs = (1/6).*[...\n                        extended_points(index - 1,:)  + 4*extended_points(index, :) + extended_points(index + 1, :); ...\n                    - 3*extended_points(index - 1, :) + 3*extended_points(index + 1, :); ...\n                      3*extended_points(index - 1, :) - 6*extended_points(index, :) + 3*extended_points(index + 1, :); ...\n                    -   extended_points(index - 1, :) + 3*extended_points(index, :) - 3*extended_points(index + 1, :) + extended_points(index+2, :) ...\n                ]';\n                \n                interval = [ones(size(interval_values)); interval_values; interval_values2; interval_values3];\n                spline_points(:, (index - 2)*num_points + 1 : (index - 1)*num_points + 1) = coeffs*interval;\n            end\n        end\n        \n        \n        \n        function dicom_coordinates = PTKToDicomCoordinates(ptk_coordinates, template_image)\n            offset = template_image.GetDicomOffset;\n            dicom_coordinates = ptk_coordinates + repmat(offset, size(ptk_coordinates, 1), 1);\n        end\n        \n        function [d_x, d_y, d_z] = PTKToDicomCoordinatesCoordwise(p_x, p_y, p_z, template_image)\n            offset = template_image.GetDicomOffset;\n            d_x = p_x + offset(1);\n            d_y = p_y + offset(2);\n            d_z = p_z + offset(3);\n        end\n        \n        function ptk_coordinates = DicomToPTKCoordinates(dicom_coordinates, template_image)\n            offset = template_image.GetDicomOffset;\n            ptk_coordinates = dicom_coordinates - repmat(offset, size(dicom_coordinates, 1), 1);\n        end\n        \n        function dicom_coordinates = PTKToCornerCoordinates(ptk_coordinates, template_image)\n            offset = template_image.GetCornerOffset;\n            dicom_coordinates = ptk_coordinates + repmat(offset, size(ptk_coordinates, 1), 1);\n        end\n        \n        function [d_x, d_y, d_z] = PTKToCornerCoordinatesCoordwise(p_x, p_y, p_z, template_image)\n            offset = template_image.GetCornerOffset;\n            d_x = p_x + offset(1);\n            d_y = p_y + offset(2);\n            d_z = p_z + offset(3);\n        end\n        \n        function ptk_coordinates = CornerToPTKCoordinates(corner_coordinates, template_image)\n            offset = template_image.GetCornerOffset;\n            ptk_coordinates = corner_coordinates - repmat(offset, size(corner_coordinates, 1), 1);\n        end\n        \n        function [ptk_x, ptk_y, ptk_z] = CoordinatesMmToPTKCoordinates(ic, jc, kc)\n            ptk_x = jc;\n            ptk_y = ic;\n            ptk_z = -kc;\n        end\n        \n        function coordinates_mm = PTKCoordinatesToCoordinatesMm(ptk_coordinates)\n            coordinates_mm = [ptk_coordinates(:, 2), ptk_coordinates(:, 1), - ptk_coordinates(:, 3)];\n        end\n\n        function dicom_coordinates = PTKCoordinatesToCornerCoordinates(ptk_coordinates, template_image)\n            offset = template_image.GetCornerOffset;\n            dicom_coordinates = ptk_coordinates + repmat(offset, size(ptk_coordinates, 1), 1);\n        end\n        \n        function dicom_coordinates = CoordinatesMmToCornerCoordinates(ptk_coordinates, template_image)\n            voxel_size = template_image.VoxelSize;\n            \n            % Adjust to coordinates at centre of first voxel\n            offset = -voxel_size/2;\n            offset = [offset(2), offset(1), -offset(3)];\n            \n            % Shift the global origin to the first slice of the image\n            global_origin = [0, 0, 0];\n            \n            % Adjust to Dicom origin\n            offset = offset + global_origin;\n            \n            dicom_coordinates = [ptk_coordinates(:, 2), ptk_coordinates(:, 1), - ptk_coordinates(:, 3)];\n            dicom_coordinates = dicom_coordinates + repmat(offset, size(ptk_coordinates, 1), 1);\n        end\n        \n        function ptk_coordinates = CornerToCoordinatesMm(dicom_coordinates, template_image)\n            voxel_size = template_image.VoxelSize;\n            \n            offset = -voxel_size/2;\n            offset = [offset(2), offset(1), -offset(3)];\n            \n            dicom_coordinates = dicom_coordinates - repmat(offset, size(dicom_coordinates, 1), 1);\n            \n            ptk_coordinates = [dicom_coordinates(:, 2), dicom_coordinates(:, 1), - dicom_coordinates(:, 3)];\n        end\n        \n        function ptk_coordinates = ConvertToPTKCoordinates(coordinates, coordinate_system, template_image)\n            switch coordinate_system\n                case MimCoordinateSystem.PTK\n                    ptk_coordinates = coordinates;\n                case MimCoordinateSystem.Dicom\n                    ptk_coordinates = MimImageCoordinateUtilities.DicomToPTKCoordinates(coordinates, template_image);\n                case MimCoordinateSystem.DicomUntranslated\n                    ptk_coordinates = MimImageCoordinateUtilities.CornerToPTKCoordinates(coordinates, template_image);\n                otherwise\n                    reporting.Error('MimImageCoordinateUtilities:UnsupportedCoordinateSystem', 'The coordinate system specified by parameter coordinate_system is not supported');\n            end\n        end\n\n        function coordinates = ConvertFromPTKCoordinates(ptk_coordinates, coordinate_system, template_image)\n            switch coordinate_system\n                case MimCoordinateSystem.PTK\n                    coordinates = ptk_coordinates;\n                case MimCoordinateSystem.Dicom\n                    coordinates = MimImageCoordinateUtilities.PTKToDicomCoordinates(ptk_coordinates, template_image);\n                case MimCoordinateSystem.DicomUntranslated\n                    coordinates = MimImageCoordinateUtilities.PTKToCornerCoordinates(ptk_coordinates, template_image);\n                otherwise\n                    reporting.Error('MimImageCoordinateUtilities:UnsupportedCoordinateSystem', 'The coordinate system specified by parameter coordinate_system is not supported');\n            end\n        end\n        \n        function [c_x, c_y, c_z] = ConvertFromPTKCoordinatesCoordwise(p_x, p_y, p_z, coordinate_system, template_image)\n            switch coordinate_system\n                case MimCoordinateSystem.PTK\n                    c_x = p_x;\n                    c_y = p_y;\n                    c_z = p_z;\n                case MimCoordinateSystem.Dicom\n                    [c_x, c_y, c_z] = MimImageCoordinateUtilities.PTKToDicomCoordinatesCoordwise(p_x, p_y, p_z, template_image);\n                case MimCoordinateSystem.DicomUntranslated\n                    [c_x, c_y, c_z] = MimImageCoordinateUtilities.PTKToCornerCoordinatesCoordwise(p_x, p_y, p_z, template_image);\n                otherwise\n                    reporting.Error('MimImageCoordinateUtilities:UnsupportedCoordinateSystem', 'The coordinate system specified by parameter coordinate_system is not supported');\n            end\n        end\n        \n        \n        function voxel_indices = AddNearestNeighbours(voxel_indices, template_image)\n            if isempty(voxel_indices)\n                return;\n            end\n            [~, linear_offsets27] = MimImageCoordinateUtilities.GetLinearOffsets(template_image.ImageSize);\n            voxel_indices = repmat(int32(voxel_indices), 27, 1) + repmat(int32(linear_offsets27'), 1, length(voxel_indices));\n            voxel_indices = unique(voxel_indices(:));\n        end\n        \n        function global_coordinates = GetGlobalCoordinatesForPoints(point_list, template_image)\n            xc = [point_list.CoordX];\n            yc = [point_list.CoordY];\n            zc = [point_list.CoordZ];\n            ptk_coords = [xc', yc', zc'];\n            coordinates_mm = MimImageCoordinateUtilities.PTKCoordinatesToCoordinatesMm(ptk_coords);\n            global_coordinates = round(template_image.CoordinatesMmToGlobalCoordinates(coordinates_mm));\n        end\n        \n        function global_indices = GetGlobalIndicesForPoints(point_list, template_image)\n            global_coordinates = MimImageCoordinateUtilities.GetGlobalCoordinatesForPoints(point_list, template_image);\n            global_indices = template_image.GlobalCoordinatesToGlobalIndices(global_coordinates);\n        end\n        \n        function dist = DistanceBetweenPoints(point_1, point_2)\n            dist = norm([point_1.CoordX - point_2.CoordX, point_1.CoordY - point_2.CoordY, point_1.CoordZ - point_2.CoordZ]);\n        end\n        \n        % Select an appropriate image orientation for exporting an image\n        function orientation = ChooseOrientation(voxel_size)\n            orientation = GemImageOrientation.XY;\n            [sorted_voxel_size, sorted_voxel_size_index] = sort(voxel_size, 'descend');\n            if abs(sorted_voxel_size(1) - sorted_voxel_size(2)) > abs(sorted_voxel_size(2) - sorted_voxel_size(3))\n                if sorted_voxel_size_index(1) == 1\n                    orientation = GemImageOrientation.XZ;\n                end\n            end\n        end\n        \n        function offset_voxels = GetOriginOffsetVoxels(from_image, to_image)\n            if ~isempty(to_image.GlobalOrigin) && ~isempty(from_image.GlobalOrigin)\n                offset_mm = to_image.GlobalOrigin - from_image.GlobalOrigin;\n                offset_voxels = offset_mm./from_image.VoxelSize;\n            else\n                offset_voxels = [0, 0, 0];\n            end\n        end\n        \n        function [Y, X] = GetSliceCoordinates(coordinates_3d, dimension)\n            % Returns the 2D [Y, X] coordinates for a 2D slice in the \n            % specified orientation given a set of 3D [i,j,k] coordinates\n           switch dimension\n               case GemImageOrientation.XZ\n                   Y = coordinates_3d(:, 3);\n                   X = coordinates_3d(:, 2);\n               case GemImageOrientation.YZ\n                   Y = coordinates_3d(:, 3);\n                   X = coordinates_3d(:, 1);\n               case GemImageOrientation.XY\n                   Y = coordinates_3d(:, 1);\n                   X = coordinates_3d(:, 2);\n               otherwise\n                   error('Unsupported dimension');\n           end\n        end\n    end\nend\n\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/mim/Library/Utilities/MimImageCoordinateUtilities.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5510087382784629}}
{"text": "function gr=bvalue(catalogObject, mcType, manual_on)\n    %BVALUE evaluate b-value, a-value and magnitude of completeness\n    % of an earthquake catalog stored in a Catalog object.\n    %\n    % gr = BVALUE(catalogObject, MCTYPE) produces a Gutenberg-Richter type plot \n    %    with the best fit line and display of b-,a-values and Mc \n    %    for catalogObject. These values are also returned in a structure.\n    %    MCTYPE is a number from 1-5 \n    %    to select the algorithm used for calculation of the \n    %    magnitude of completeness. Options are:\n    %\n    %    1: Maximum curvature\n    %    2: Fixed Mc = minimum magnitude (Mmin)\n    %    3: Mc90 (90% probability)\n    %    4: Mc95 (95% probability)\n    %    5: Best combination (Mc95 - Mc90 - maximum curvature)\n    %\n    % * Note: it seems only 1 only really works, and 5 is same as 1 *'\n    %\n    % gr = BVALUE(catalogObject, MCTYPE, manual_on) where the value of manual_on\n    %    computes as true will give the user the ability to manually pick a\n    %    linear segment on the graph too (which is then plotted with a\n    %    green line). The manual Mc and bvalue are returned in the gr\n    %    structure as gr.Mc_manual and gr.bvalue_manual\n\n    % Liberally adapted from original code in ZMAP.\n    % Author: Silvio De Angelis, 27/07/2012 00:00:00\n    % Modified and included in Catalog by Glenn Thompson,\n    % 14/06/2014\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\n    % Free Software Foundation, Inc.,\n    % 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n    if nargin < 2\n        disp('* Note: it seems only 1 only really works, and 5 is same as 1 *')\n        mcType = menu('mcType can be:','Maximum curvature','Fixed Mc = minimum magnitude (Mmin)', ...\n            'Mc90 (90% probability)', 'Mc95 (95% probability)', ...\n            'Best combination (Mc95 - Mc90 - maximum curvature)')\n    end\n    if ~exist('manual_on','var')\n        manual_on = false;\n    end\n\n    % form magnitude vector - removing any NaN values with find\n    good_magnitude_indices = find(catalogObject.mag > -3.0);\n    mag = catalogObject.mag(good_magnitude_indices);\n    %MIN AND MAX MAGNITUDE IN catalogObject\n    minimum_mag = min(mag);\n    maximum_mag = max(mag);\n\n    %COUNT EVENTS IN EACH MAGNITUDE BIN\n    [bval, xt2] = hist(mag, (minimum_mag:0.1:maximum_mag));\n\n    %CUMULATIVE NUMBER OF EVENTS IN EACH MAGNITUDE BIN\n    bvalsum = cumsum(bval);\n\n    %NUMBER OF EVENTS IN EACH BIN IN REVERSE ORDER\n    bval2 = bval(length(bval):-1:1);\n\n    %NUMBER OF EVENTS IN EACH MAGNITUDE BIN IN REVERSE ORDER\n    bvalsum3 = cumsum(bval(length(bval):-1:1));\n\n    %BINS IN REVERSE ORDER\n    xt3 = (maximum_mag:-0.1:minimum_mag);\n    backg_ab = log10(bvalsum3);\n\n    %CREATE FIGURE WINDOW AND MAKE FREQUENCY-MAGNITUDE PLOT\n    figure('Color','w','Position',[0 0 600 600])\n\n    pl = semilogy(xt3,bvalsum3,'sb'); % semilogy is same as plot, except a log (base10) scale is used for Y-axis\n    set(pl, 'LineWidth', [1.0],'MarkerSize', [10],'MarkerFaceColor','r','MarkerEdgeColor','k');\n    axis square\n    hold on\n\n    pl1 = semilogy(xt3,bval2,'^b');\n    set(pl1, 'LineWidth',[1.0],'MarkerSize',[10],'MarkerFaceColor','w','MarkerEdgeColor','k');\n    xlabel('Magnitude','Fontsize', 12)\n    ylabel('Cumulative Number','Fontsize',12)\n    set(gca,'visible','on','FontSize',12,'FontWeight','normal',...\n        'FontWeight','bold','LineWidth',[1.0],'TickDir','in','Ticklength',[0.01 0.01],...\n        'Box','on','Tag','cufi','color','w')\n\n    %ESTIMATE B-VALUE (MAX LIKELIHOOD ESTIMATE)\n    Nmin = 10;\n    fMccorr = 0;\n    fBinning = 0.1;\n\n    if length(mag) >= Nmin\n\n        %GOODNESS-OF-FIT TO POWER LAW\n        %%%%%%%%%%%%%%%%%% mcperc_ca3.m start %%%%%%%%%%%%%%%%%%%%\n        % This is a completeness determination test\n\n        [bval,xt2] = hist(mag,-2:0.1:6);\n        l = max(find(bval == max(bval)));\n        magco0 =  xt2(l);\n\n        dat = [];\n\n        %for i = magco0-0.6:0.1:magco0+0.2\n        for i = magco0-0.5:0.1:magco0+0.7\n            l = mag >= i - 0.0499;\n            nu = length(mag(l));\n            if length(mag(l)) >= 25;\n                %[bv magco stan av] =  bvalca3(catZmap(l,:),2,2);\n                [mw bv2 stan2 av] =  Catalog.bvalue_lib.bmemag(mag(l));\n                Catalog.bvalue_lib.synthb_aut;\n                dat = [ dat ; i res2];\n            else\n                dat = [ dat ; i nan];\n            end\n\n        end\n\n        j =  min(find(dat(:,2) < 10 ));\n        if isempty(j) == 1; Mc90 = nan ;\n        else;\n            Mc90 = dat(j,1);\n        end\n\n        j =  min(find(dat(:,2) < 5 ));\n        if isempty(j) == 1; Mc95 = nan ;\n        else;\n            Mc95 = dat(j,1);\n        end\n\n        j =  min(find(dat(:,2) < 10 ));\n        if isempty(j) == 1; j =  min(find(dat(:,2) < 15 )); end\n        if isempty(j) == 1; j =  min(find(dat(:,2) < 20 )); end\n        if isempty(j) == 1; j =  min(find(dat(:,2) < 25 )); end\n        j2 =  min(find(dat(:,2) == min(dat(:,2)) ));\n        %j = min([j j2]);\n\n        Mc = dat(j,1);\n        magco = Mc;\n        prf = 100 - dat(j2,2);\n        if isempty(magco) == 1; magco = nan; prf = 100 -min(dat(:,2)); end\n        %display(['Completeness Mc: ' num2str(Mc) ]);\n        %%%%%%%%%%%%%%%%%% mcperc_ca3.m end %%%%%%%%%%%%%%%%%%%%%%\n\n        %CALCULATE MC\n        [fMc] = Catalog.bvalue_lib.calc_Mc(mag, mcType, fBinning, fMccorr);\n        l = mag >= fMc-(fBinning/2);\n        if length(mag(l)) >= Nmin\n            [fMeanMag, fBValue, fStd_B, fAValue] =  Catalog.bvalue_lib.calc_bmemag(mag(l), fBinning);\n        else\n            [fMc, fBValue, fStd_B, fAValue] = deal(NaN);\n        end\n\n        %STANDARD DEV OF a-value SET TO NAN;\n        [fStd_A, fStd_Mc] = deal(NaN);\n\n    else\n        [fMc, fStd_Mc, fBValue, fStd_B, fAValue, fStd_A, ...\n            fStdDevB, fStdDevMc] = deal(NaN);\n    end\n\n    magco = fMc;\n    index_low=find(xt3 < magco+.05 & xt3 > magco-.05);\ntry\n    mag_hi = xt3(1);\n    index_hi = 1;\n    mz = xt3 <= mag_hi & xt3 >= magco-.0001;\n    mag_zone=xt3(mz);\n    y = backg_ab(mz);\n\n    %PLOT MC IN FIGURE\n    Mc = semilogy(xt3(index_low),bvalsum3(index_low)*1.5,'vk');\n    set(Mc,'LineWidth',[1.0],'MarkerSize',7)\n    Mc = text(xt3(index_low)+0.2,bvalsum3(index_low)*1.5,'Mc');\n    set(Mc,'FontWeight','normal','FontSize',12,'Color','k')\n\n    %CREATE AND PLOT FIT LINE\n    sol_type = 'Maximum Likelihood Solution';\n    bw=fBValue;\n    aw=fAValue;\n    ew=fStd_B;\n    p = [ -1*bw aw];\n    f = polyval(p,mag_zone);\n    f = 10.^f;\n    hold on\n    ttm= semilogy(mag_zone,f,'k');\n    set(ttm,'LineWidth',[2.0])\n    std_backg = ew;\n\n    %ERROR CALCULATIONS\n    %b = mag;\n    bv = [];\n    si = [];\n\n    set(gca,'XLim',[min(mag)-0.5  max(mag+0.5)])\n    %set(gca,'YLim',[0.9 length(mag+30)*2.5]);\n\n    p=-p(1,1);\n    p=fix(100*p)/100;\n    tt1=num2str(bw,3);\n    tt2=num2str(std_backg,1);\n    tt4=num2str(bv,3);\n    tt5=num2str(si,2);\n    tmc=num2str(magco,2);\n    rect=[0 0 1 1];\n    h2=axes('position',rect);\n    set(h2,'visible','off');\n    t=catalogObject.gettimerange();\n    a0 = aw-log10((t(2)-t(1))/365);\n\n    text(.53,.88, ['b-value = ',tt1,' +/- ',tt2,',  a value = ',num2str(aw,3)],'FontSize',12);\n    text(.53,.85,sol_type,'FontSize',12 );\n    text(.53,.82,['Magnitude of Completeness = ',tmc],'FontSize',12);\n    \n    %% Added by Glenn 2018-05-01 to return a structure\n    gr.bvalue = str2num(tt1);\n    gr.bvalue_error = str2num(tt2);\n    gr.avalue = aw;\n    gr.Mc = str2num(tmc);\n    \n    %% Manually fit a line (added by Glenn 2018-05-01)\n    if manual_on\n        [xmag, yN] = ginput(2);\n        slope = (log10(yN(1)) - log10(yN(2) )) / (xmag(2) - xmag(1) )\n        plot(xmag, yN, 'g');\n        gr.Mc_manual = xmag(1);\n        gr.bvalue_manual = slope;\n        text(xmag(1) + (xmag(2)-xmag(1))*0.5, yN(1) + (yN(2)-yN(1))*0.5, sprintf('manual b=%.2f',slope),'Color','g');\n    end\ncatch\n    gr.bvalue = NaN;\n    gr.Mc = NaN;\n    gr.avalue = NaN;\n    gr.bvalue_error = NaN;\nend\n    \nend ", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@Catalog/bvalue.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.6513548782017746, "lm_q1q2_score": 0.5510087281591365}}
{"text": "function [f, grad] = DL1c_regularization(Knots, kspc, D, csqrt)\n    gvol = prod(kspc);\n    k = 1;\n    ksz = size(Knots(:,:,:, 1));\n    Nd = size(Knots, 4);\n    f = 0;\n    grad = zeros(size(Knots));\n    p = 1;\n%     p = 0.85;\n    \n    for nn = 1 : size(Knots, 5)\n        for i = 1 : Nd\n            tmp = D * fl(Knots(:,:,:, i, nn));\n        \n            t2 = sqrt(tmp(:).^2 + csqrt);\n            f = f + sum(t2.^p);\n            \n%             grad = D' * ((abs(tmp)+deps).^(p-1) .* sign(tmp)) * p;\n            \n%             gr = D' * fl(tmp ./ t2);\n            gr = D' * (tmp .* (t2.^(p-2)) * p);\n            \n            grad(:,:,:, i, nn) = grad(:,:,:, i, nn) + reshape(gr, ksz);\n        end\n    end\n    f = f * gvol;\n    grad = grad * gvol;\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/regularizers/DL1c_regularization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5510087268280226}}
{"text": "%RANDOMFORESTC Breiman's random forest\n%\n%   W = RANDOMFORESTC(A,L,N)\n%   W = A*RANDOMFORESTC([],L,N)\n%\n% INPUT\n%   A       Dateset used for training\n%   L       Number of decision trees to be generated (default 50)\n%   N       Size of feature subsets to be used (default 1)\n%\n% OUTPUT\n%   W       Resulting, trained feature space classifier\n%\n% DESCRIPTION\n% Train a decision forest on A, using L decision trees, each trained on\n% a bootstrapped version of dataset A. Each decison tree is using random\n% feature subsets of size N in each node.  When N=0, no feature subsets\n% are used.\n%\n% REFERENCES\n% [1] L. Breiman, Random Forests, Machine learning, vol. 45 (1), 5-32, 2001\n%\n% SEE ALSO (<a href=\"http://37steps.com/prtools\">PRTools Guide</a>)\n% DATASETS, MAPPINGS, DTC\n\n% Copyright: D.M.J. Tax, D.M.J.Tax@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\nfunction out = randomforestc(varargin)\n\nargin = setdefaults(varargin,[],50,1);\nif mapping_task(argin,'definition')\n  \n  out = define_mapping(argin,'untrained',['RandForest' int2str(argin{2})]);\n  \nelseif mapping_task(argin,'training')\n  \n  [a,L,featsubset] = deal(argin{:});\n\tisvaldfile(a,2,2); % at least 2 obj/class, 2 classes\n\topt = [];\n\t[n,dim,opt.K] = getsize(a);\n\topt.featsubset = featsubset;\n\tv = cell(L,1);\n\tfor i=1:L\n\t\t[x,z] = gendat(a);\n    if exist('decisiontree','file')==3\n      v{i} = decisiontree(+x,getnlab(x),opt.K,opt.featsubset);\n    else\n\t\t prwarning(2,'No compiled decisiontree found, using the slower Matlab implementation.');\n    \tv{i} = tree_train(+x,getnlab(x),opt);\n    end\n  end\n  out = trained_classifier(a,v);\n  \nelseif mapping_task(argin,'execution')\n  \n  [a,w] = deal(argin{1:2}); \n\tv = getdata(w);\n\tn = size(a,1);  % nr objects\n\tK = size(w,2);  % nr of classes\n\tnrv = length(v); % nr of trees\n    out = zeros(n,K);\n    if exist('decisiontree')==3\n      for j=1:nrv\n        I = decisiontree(v{j},+a);\n        out = out + accumarray([(1:n)' I],ones(n,1),[n K]);\n      end\n    else\n      % the old fashioned slow Matlab code\n      for i=1:n\n        x = +a(i,:);\n        for j=1:nrv\n          I = tree_eval(v{j},x);\n          out(i,I) = out(i,I)+1;\n        end\n      end\n      out = out./repmat(sum(out,2),1,K);\n    end\n    out = setdat(a,out,w);\n    \nelse\n  error('Illegal call')\nend\n\nreturn\n\n%    out = tree_eval(w,x)\n%\nfunction out = tree_eval(w,x)\n\nn = size(x,1);\nout = zeros(n,1);\n\nfor i=1:n\n\n\tv=w;\n\t% if the first split is already solving everything (1 obj. per class)\n\tif isa(v,'double')\n\t\tout(i,1) = v;\n\tend\n\twhile (out(i,1)==0)\n\t\tif (x(i,v.bestf)<v.bestt)\n\t\t\tv = v.l;\n\t\telse\n\t\t\tv = v.r;\n\t\tend\n\t\tif isa(v,'double')\n\t\t\tout(i,1) = v;\n\t\tend\n\tend\nend\n\n%\n%    w = tree_train(x,y,opt)\n%\nfunction w = tree_train(x,y,opt)\n\n% how good are we in this node?\nerr = tree_gini(y,opt.K);\nif (err==0)\n\n\tw = y(1); % just predict this label\n\nelse\n\t% we split further\n\tn = size(x,1);\n\n\t% optionally, choose only from a subset\n\tif (opt.featsubset>0)\n\t\tfss = randperm(size(x,2));\n\t\tfss = fss(1:opt.featsubset);\n\telse\n\t\tfss = 1:size(x,2);\n\tend\n\n\t% check each feature separately:\n\tbesterr = inf; bestf = []; bestt = []; bestj = []; bestI = [];\n\tfor i=fss\n\t\t% sort the data along feature i:\n\t\t[xi,I] = sort(x(:,i)); yi = y(I);\n\t\t% run over all possible splits:\n\t\tfor j=1:n-1\n\t\t\t% compute the gini\n\t\t\terr = j*tree_gini(yi(1:j),opt.K) + (n-j)*tree_gini(yi(j+1:n),opt.K);\n\t\t\t% and see if it is better than before.\n\t\t\tif (err<besterr)\n\t\t\t\tbesterr = err;\n\t\t\t\tbestf = i;\n\t\t\t\tbestj = j;\n\t\t\t\tbestt = mean(xi(j:j+1));\n\t\t\t\tbestI = I;\n\t\t\tend\n\t\tend\n\tend\n\n\t% store\n\tw.bestf = bestf;\n\tw.bestt = bestt;\n\t%  now find the children:\n\tw.l = tree_train(x(bestI(1:bestj),:),y(bestI(1:bestj)),opt);\n\tw.r = tree_train(x(bestI(bestj+1:end),:),y(bestI(bestj+1:end)),opt);\nend\n\t\nfunction g = tree_gini(y,K)\n\nout = zeros(1,K);\nfor k=1:K\n\tout(k) = mean(y==k);\nend\n\ng = out*(1-out)';\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/randomforestc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5510087217683596}}
{"text": "function [meshStruct]=hexMeshCylinder(varargin)\n\n% function [meshStruct]=hexMeshCylinder(cylRadius,cylLength,pointSpacing)\n% ------------------------------------------------------------------------\n%\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n%\n% 2021/02/26 Created\n% 2021/05/08 @Fireedman (Luis Antonio Aguilar) added \"end\" to function\n%------------------------------------------------------------------------\n\n%% Parse input\n\nswitch nargin\n    case 0\n        cylRadius=[];\n        cylLength=[];\n        pointSpacing=[];\n    case 1\n        cylRadius=varargin{1};\n        cylLength=[];\n        pointSpacing=[];\n    case 2\n        cylRadius=varargin{1};\n        cylLength=varargin{2};\n        pointSpacing=[];\n    case 3\n        cylRadius=varargin{1};\n        cylLength=varargin{2};\n        pointSpacing=varargin{3};\nend\n\n%Check for empty variables\nif isempty(cylRadius)\n    cylRadius=1; %Unit radius\nend\n\nif isempty(cylLength)\n    cylLength=cylRadius; %Height the same as radius\nend\n\nif isempty(pointSpacing)\n    pointSpacing=(cylRadius*2*pi)/10; %One tenth of circumference\nend\n\nif numel(pointSpacing)==1\n    pointSpacing=pointSpacing.*ones(1,2);\nend\n\n%%\n%Set number of elements for core\nnumElementsCore=ceil(((cylRadius*2*pi)./pointSpacing(1))/4);\n\nif numElementsCore<1\n    numElementsCore=1;\nend\n\n%Set number of nodes allong circumference\nnumElementsHeight=ceil(cylLength./pointSpacing(2));\nif numElementsHeight<1\n    numElementsHeight=1;\nend\n\n%% Create quad mesh for disc\n\n%Raw quad mesh\n[Fs,Vs]=discQuadMesh(numElementsCore,cylRadius,0.6);\n\n%Smoothen\nEb=patchBoundary(Fs);\ncontrolParSmooth.n=25;\ncontrolParSmooth.Method='LAP';\ncontrolParSmooth.RigidConstraints=unique(Eb(:));\n[Vs]=patchSmooth(Fs,Vs,[],controlParSmooth);\n\n%% Thicken to elements\n\n%Thicken\n[E,V,Fp1,Fp2]=patchThick(Fs,Vs,1,cylLength,numElementsHeight);\nV(:,3)=V(:,3)-cylLength/2;\n\n%Get element faces\n[F,~]=element2patch(E,[],'hex8');\n\n%Find boundary faces\n[indFree]=freeBoundaryPatch(F);\nFb=F(indFree,:);\n\n%Assign boundary labels (or colors)\nfaceBoundaryMarker=zeros(size(Fb,1),1); %Side of cylinder\nfaceBoundaryMarker(all(ismember(Fb,Fp1),2))=1; %Original (e.g. top)\nfaceBoundaryMarker(all(ismember(Fb,Fp2),2))=2; %Thickened (e.g. bottom)\n\n%% Collect output\n\nmeshStruct.nodes=V;\nmeshStruct.facesBoundary=Fb;\nmeshStruct.boundaryMarker=faceBoundaryMarker;\nmeshStruct.faces=F;\nmeshStruct.elements=E;\nmeshStruct.elementMaterialID=ones(size(E,1),1);\nmeshStruct.faceMaterialID=ones(size(F,1),1);\n\nend\n\n%%\n% _*GIBBON footer text*_\n%\n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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-2021 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 <http://www.gnu.org/licenses/>.\n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/hexMeshCylinder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245617, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.551008719238528}}
{"text": "clc;\nclear;\nclose all;\nwarning off;\naddpath(genpath(cd));\n\nI=double(imread('E:\\lichang\\1.Image fusion total variation\\img\\tank\\tank_IR.png'))/255;\n%V=double(imread('E:\\lichang\\1.Image fusion total variation\\img\\tank\\tank_VIS.png'))/255;\n% I=histeq(I);\n% V=histeq(V);\n% figure; imshow(I);\n% figure; imshow(V);\n% imwrite(I,'new_4917_IR.png','png');\n% imwrite(V,'new_4917_VIS.png','png');\n% I=rgb2gray(I);\n% V=rgb2gray(V);\n%proposed\nnmpdef;\npars_irn = irntvInputPars('l2tv');\n\npars_irn.adapt_epsR   = 1;\npars_irn.epsR_cutoff  = 0.01;   % This is the percentage cutoff\npars_irn.adapt_epsF   = 1;\npars_irn.epsF_cutoff  = 0.05;   % This is the percentage cutoff\n\npars_irn.pcgtol_ini = 1e-4;\n\npars_irn.loops      = 5;\npars_irn.U0         = I;\n\npars_irn.variant       = NMP_TV_SUBSTITUTION;\npars_irn.weight_scheme = NMP_WEIGHTS_THRESHOLD;\npars_irn.pcgtol_ini    = 1e-2;\npars_irn.adaptPCGtol   = 1;\nFinal_Metric=zeros(6,1); \ntic;\nfor i=[0.1:0.1:0.9]%[0.01:0.01:0.09 0.1:0.1:0.9 1:10 20:10:100]\n   \n    X = irntv(I, {}, i, pars_irn);\n    X=im2gray(X);\n    imwrite(X,strcat('Proposed_tank_',strcat(num2str(i),'.png')),'png');\n    %figure; \n    %imshow(X);\n%     Result = Metric(uint8(abs(I)*255),uint8(abs(V)*255),uint8(abs(X*255)));\n%     temp=Result.Total;\n%     Final_Metric=max(Final_Metric,temp);\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/GTF/source/Demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.551008711649033}}
{"text": "  function atten = xray_filters(mtype, thickness, energy, varargin)\n%|function atten = xray_filters(mtype, thickness, energy, [options])\n%|\n%| Compute X-ray photon survival probability as a function of energy\n%| for various materials.\n%| in\n%|\tmtype\t\t\t'aluminum', 'copper', ...\n%|\t\t\t\tcan be a cell array {L} for multiple filters\n%|\tthickness\t\tin cm (can be an array [L] if mtype is cell)\n%|\tenergy\t[N,1]\t\tin keV (vector)\n%| option\n%|\t'units'\tcm | mm\t\tdefault: cm\n%| out\n%|\tatten\t[N,L]\t\tunitless survival probabilities\n%|\n%| Copyright 2001-04-27, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(mtype, 'test'), xray_filters_test, return, end\nif nargin < 3, ir_usage, end\n\narg.units = 'cm';\narg = vararg_pair(arg, varargin);\n\nif iscell(mtype)\n\tLL = length(mtype);\n\tif length(thickness) ~= LL, error 'thickness / material mismatch', end\n\tatten = zeros(length(energy), LL);\n\tfor ll=1:LL\n\t\tatten(:,ll) = xray_filters(mtype{ll}, thickness(ll), ...\n\t\t\tenergy(:), 'units', arg.units);\n\tend\nreturn\nend\n\nmass_atten = xray_read_atten(mtype, energy, 'units', arg.units); % [N,L]\ndensity = xray_read_dens(mtype, 'units', arg.units); % [L,1]\natten = exp(-mass_atten .* thickness .* density);\n\n\nfunction xray_filters_test\nkev = [20:200]';\nmtype = {'lead', 'copper', 'aluminum'};\nt = xray_filters(mtype, [0.01 0.2 0.1], kev);\nif im\n\tclf, semilogy(kev, t, '-o'), axis([20 200 10^-2 1]),\n\tir_legend(mtype)\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/ct/xray_filters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5509643740695068}}
{"text": "% VOCLABELCOLORMAP Creates a label color map such that adjacent indices have different\n% colors.  Useful for reading and writing index images which contain large indices,\n% by encoding them as RGB images.\n%\n% CMAP = VOCLABELCOLORMAP(N) creates a label color map with N entries.\nfunction cmap = VOClabelcolormap(N)\n\nif nargin==0\n    N=256;\nend\ncmap = zeros(N,3);\nfor i=1:N\n    id = i-1; r=0;g=0;b=0;\n    for j=0:7\n        r = bitor(r, bitshift(bitget(id,1),7 - j));\n        g = bitor(g, bitshift(bitget(id,2),7 - j));\n        b = bitor(b, bitshift(bitget(id,3),7 - j));\n        id = bitshift(id,-3);\n    end\n    cmap(i,1)=r; cmap(i,2)=g; cmap(i,3)=b;\nend\ncmap = cmap / 255;\n", "meta": {"author": "quantombone", "repo": "exemplarsvm", "sha": "54c07ec4faa96fb949991ebc512eaf7446e034f7", "save_path": "github-repos/MATLAB/quantombone-exemplarsvm", "path": "github-repos/MATLAB/quantombone-exemplarsvm/exemplarsvm-54c07ec4faa96fb949991ebc512eaf7446e034f7/VOCcode/VOClabelcolormap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5509643720434076}}
{"text": "function [ lo, hi ] = p06_box ( m )\n\n%*****************************************************************************80\n%\n%% P06_BOX returns a bounding box for problem 06.\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%    Output, real LO(M), HI(M), the low and high corners of the box.\n%\n  r1 = 1.0;\n  r2 = 0.5;\n\n  lo(1:m) = [ -r1, -r1 ];\n  hi(1:m) = [ +r1, +r1 ];\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_triangulation/p06_box.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.5509643720434076}}
{"text": "% This function recursively cuts a sentence into shorter segments no longer \n% than a predefined maximum length, based purely on the information about\n% short pause durations and locations. \n% Inputs:\n%   sent_len: length of the sentence in terms of frames\n%   sp_len: length of the short pauses in the sentence\n%   middle_frame: middle of the short pauses\n%   max_seg_len: maximum length of every resulting segments. \n%   weight_location: the weight of short pause location. This is relative to the\n%       short pause duration\n% Outputs:\n%   cutting_point: an array of suggested cutting points\n% \n% Authors: Xiong Xiao \n% Date Created: 2009\n% Last Modified: 16 April 2014\n%\nfunction cutting_point = choose_cutting_points_by_sp(sent_len, sp_len, middle_frame, max_seg_len, loc_weight)\nif nargin<5\n    loc_weight = 1;\nend\nif sent_len < max_seg_len\n    cutting_point = [];\nelseif length(sp_len)<2\n    cutting_point = [];\nelse\n    % Choose the sp for splitting\n    % Two rules to select a sp: 1) longer sp segments should be\n    % given higher priority; 2) sp near to center of the sentence\n    % should be given higher priority. The weight of these two\n    % criteria will be adjsuted by a weighting loc_weight\n    sent_center = round(sent_len/2);\n    score = [];\n    for k = 1:length(sp_len)\n        if middle_frame(k) < max_seg_len/5 || sent_len-middle_frame(k)<max_seg_len/5    % we don't cut by short pause that is too close to the both ends\n            score(k) = 0;\n        else\n            dist_to_center = abs(middle_frame(k)-sent_center)/sent_center;      % how far is current short pause to the sentence center relatively, which is in [0 0.5] interval. \n            % we change the distance to log scale, multiple it by -3 to convert it to positive number. As log(0) is infinity, we need to set a upper limit to the log distance. \n            location_score = min(20, -3*log(dist_to_center) );              \n            score(k) = sp_len(k) + loc_weight * location_score;     % we still have loc_weight to tune the relative weight of the two factors\n        end\n    end\n    [best_sp, idx] = max(score);    % everytime we only cut the current sentence once. \n    cutting_point = middle_frame(idx);\n    \n    sub_points = choose_cutting_points_by_sp(cutting_point, sp_len(1:idx-1), middle_frame(1:idx-1), max_seg_len, loc_weight);     % See whether left segment needs to be cut further\n    cutting_point = ([sub_points cutting_point]);\n    sub_points = choose_cutting_points_by_sp(sent_len - cutting_point(end), sp_len(idx+1:end), middle_frame(idx+1:end)-cutting_point(end), max_seg_len, loc_weight);     % See whether left segment needs to be cut further\n    cutting_point = ([cutting_point sub_points+cutting_point(end)]);\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/utils/choose_cutting_points_by_sp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5509643691312589}}
{"text": "%function f = s6990029.m\n%This function was completed on Tuesday, 16 November 2002\n%as a part of a course, in order to form a good-interfaced program \n%for producing random variables from the negative binomial distribution.\n%\n%Made by P.B.(6990029)\nfunction s6990029\n\nfprintf('In a few seconds a pop-up screen will prompt you to choose from one\\nof 4 methods, in order to generate random variables from the Negative Binomial Distribution.');\nfprintf('\\n\\nLOADING('),\nfor j=1:30\nfprintf('---')\npause(0.06990029)\nend\nfprintf(')')\nfprintf('\\n')\n\n\nK=menu('Choose a method for generating n random variables from the Neg.Binomial :','1) Inverse transform Method','2) Convolution Method (using Bernoulli D.)','3) Convolution Method (using Geometrical D.)','4) Acceptance Rejection Method','**************************Which is faster=better***********************','Exit');\n\n\n%Method 1\n\n\nif (K==1)\n    \ndisp('You have selected the Inverse Transform method. Please wait...');\npause(2);\nclc;clear;\nN = input('Please give me the size of the sample : ');\nR = input('Type the value of the parameter of successes R : ');\nP = input('Now give the probability of success P : ');\ndisp('Please standby...');\n\n%set up the storage space and the clock\ntic\nX = zeros(1,N);\nx =1:N;\n\nfor x =1:N\npr(x)  = NBINCDF(x,R,P);\nend\n\npr(N)=1;    %epeidh en vgainei panta 1 to teleutaio stoixeio tou pinaka ths a8roistikhs ...kammia fora... dhmiourgei provlhmata!!!\n\nfor i=1:N\n s=1;\nu= rand;\nwhile u > pr(s)\n    s=s+1;\nend\nX(i) = s;\nend\n\n%stop the clock \nt=toc;  \nfp=fopen('c:\\data1.txt','w');\nfprintf(fp,' %3.0f \\n',X);\nfclose(fp);\ndisp('Your sample has been saved in data1.txt');\nfprintf('The time needed, depending on your machine'' speed \\n and the complexity of the algorithm, was: ');disp(t)\npause(2);\n\nload handel;\nsound(y,Fs);\n\n\n%the empirical histogram\n\n[n,h]= hist(X,10);\nn=n/(h(2)-h(1))/N;\nbar(h,n,1,'w')\nhold on\n\n%theoritical curve\n\nfor x =1:N\npr(x)  = NBINPDF(x,R,P);\nend\nx =1:N;\nplot(x,pr,'k');\nhold off\ntitle('Empirical & Theoritical pdf of the Neg. Binomial Distribution');\nxlabel('X');\nylabel('P(X)');\n\n%Method 2\n\n\nelseif (K==2)\n    \nfprintf('You have selected the Convolution method \\n(using as a prime several Bernoulli variables). \\n\\nPlease wait...');\npause(4);\nclc;clear;\nN = input('Please give me the size of the sample : ');\nR = input('Type the value of the parameter of successes R : ');\nP = input('Now give the probability of the bernoulli trials P : ');\ndisp('Please standby...');\n\n%set up the storage space and the clock\ntic\n\nX = zeros(1,N);\nfor j=1:N\nh=0;\ni=0;\nwhile h < R\nu=rand;\ni=i+1;\nif  u <= P\nh = h+1;\nend\nend\nX(j)=i-R;               % duskolo shmeio...orismos:...o arithmos twn dokimwn mexri R epituxies!             \nend\n\nt=toc;  \nfp=fopen('c:\\data2.txt','w');\nfprintf(fp,' %3.0f \\n',X);\nfclose(fp);\ndisp('Your sample has been saved in data2.txt');\nfprintf('The time needed, depending on your machine'' speed \\n and the complexity of the algorithm, was: ');disp(t)\npause(2);\n\nload handel;\nsound(y,Fs);\n\n\n%the empirical histogram\n\n[n,h]= hist(X,10);\nn=n/(h(2)-h(1))/N;\nbar(h,n,1,'w')\nhold on\n\n%theoritical curve\n\nfor x =1:N\npr(x)  = NBINPDF(x,R,P);\nend\nx =1:N;\nplot(x,pr,'k');\nhold off\ntitle('Empirical & Theoritical pdf of the Neg. Binomial Distribution');\nxlabel('X');\nylabel('P(X)');\n\n\n\n%METHOD 3\n\n\nelseif (K==3)\n    \nfprintf('You have selected the Convolution method \\n(using as a prime several Geometrical variables). \\n\\nPlease wait...');\npause(4);\nclc;clear;\nN = input('Please give me the size of the sample : ');\nR = input('Type the value of the parameter of successes R : ');\nP = input('Now give the probability of the bernoulli trials P : ');\ndisp('Please standby...');\n\n%set up the storage space and the clock\ntic\n\nX = zeros(1,N);\n\nG=geornd(P,N,R);\n\nX=G*ones(R,1);\n\n%stop the clock \nt=toc;  \nfp=fopen('c:\\data3.txt','w');\nfprintf(fp,' %3.0f \\n',X);\nfclose(fp);\ndisp('Your sample has been saved in data3.txt');\nfprintf('The time needed, depending on your machine'' speed \\n and the complexity of the algorithm, was: ');disp(t)\npause(2);\n\nload handel;\nsound(y,Fs);\n\n\n%the empirical histogram\n\n[n,h]= hist(X,10);\nn=n/(h(2)-h(1))/N;\nbar(h,n,1,'w')\nhold on\n\n%theoritical curve\n\nfor x =1:N\npr(x)  = NBINPDF(x,R,P);\nend\nx =1:N;\nplot(x,pr,'k');\nhold off\ntitle('Empirical & Theoritical pdf of the Neg. Binomial Distribution');\nxlabel('X');\nylabel('P(X)');\n  \n    \n \n%METHOD 4\n\nelseif (K==4)\n    \nfprintf('You have selected the Acceptance-Rejection method). \\n\\nPlease wait...');\npause(4);\nclc;clear;\nN = input('Please give me the size of the sample : ');\nR = input('Type the value of the parameter of successes R : ');\nP = input('Now give the probability of the bernoulli trials P : ');\ndisp('Please standby...');\n\n%set up the storage space and the clock\ntic\n \nfor x =1:N\npr(x)  = NBINPDF(x,R,P);\nend\n\nc=max(pr)*N;\n\nirv=1;\nwhile irv<=N\n    y = unidrnd(N);\n    u = rand(1);\n    if u <= (pr(y))/c ;\n        X(irv) =  y;\n        irv = irv +1;\n    end\nend\n\n\n\n%stop the clock \nt=toc;  \n%save to disk\nfp=fopen('c:\\data4.txt','w');\nfprintf(fp,' %3.0f \\n',X);\nfclose(fp);\ndisp('Your sample has been saved in data4.txt');\nfprintf('The time needed, depending on your machine'' speed \\n and the complexity of the algorithm, was: ');disp(t)\npause(2);\n\nload handel;\nsound(y,Fs);\n\n\n%the empirical histogram\n\n[n,h]= hist(X,10);\nn=n/(h(2)-h(1))/N;\nbar(h,n,1,'w')\nhold on\n\n%theoritical curve\n\nfor x =1:N\npr(x)  = NBINPDF(x,R,P);\nend\nx =1:N;\nplot(x,pr,'k');\nhold off\ntitle('Empirical & Theoritical pdf of the Neg. Binomial Distribution');\nxlabel('X');\nylabel('P(X)');\n      \n\n%Test for overall performance within the range of the two parameters (R,P)\n\n%#########################################################################################\n\nelseif (K==5)\n    \n    clc;\n    fprintf('You have selected to test between the three first  methods.\\nFor the 4th one the envelope function selected was rather unsuitable since it was\\nthe discrete uniform.\\nWith an other function as an envelope it would be very hard to test\\nthrough a wide range of (R,P)\\nsince the Neg. Binomial''s shape would change.\\n\\nPlease wait. It will take some time ...\\n');\npause(5);\n\nclear;\nN = input('Please give me the size of the sample. It would be most preferable to choose sample bigger than 10000! : ');\n\nfprintf('Please go drink a coffee...\\n')\n\n    q=1;\n    \n    for R=10:N    \n    for P=0.3:0.2:0.7\n        %1st\ntic\nX = zeros(1,N);\nx =1:N;\n\nfor x =1:N\npr(x)  = NBINCDF(x,R,P);\nend\n\npr(N)=1;    %epeidh en vgainei panta 1 to teleutaio stoixeio tou pinaka ths a8roistikhs ...kammia fora... dhmiourgei provlhmata!!!\n\nfor i=1:N\n s=1;\nu= rand;\nwhile u> pr(s)\n    s=s+1;\nend\n    X(i) = s;\nend\n%stop the clock \nt1=toc;  \n\n%2nd\n\ntic\n\nX = zeros(1,N);\nfor j=1:N\nh=0;\ni=0;\nwhile h < R\nu=rand;\ni=i+1;\nif  u <= P\nh = h+1;\nend\nend\nX(j)=i-R;               % duskolo shmeio...orismos:...o arithmos twn dokimwn mexri R epituxies!             \nend\n\nt2=toc;  \n\n\n%3rd\n\n\ntic\n\nX = zeros(1,N);\n\nG=geornd(P,N,R);\n\nX=G*ones(R,1);\n\n%stop the clock \nt3=toc;  \n\nq=q+1;\n\nT(q,:)=[t1 t2 t3];\n\nend\nend\n\nboxplot(T);\nanova1(T);\n\nfprintf('\\n\\n\\n\\n\\nOne would choose the method which uses the sum of the geometrical variables\\nsince the Anova table also recommends this method!\\nHave a nice day.')\n\nelse\n disp('Have a nice Day!!!');\n\n%break\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/2759-random-numbers-from-negative-binomial-distribution/s6990029.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5509366343513316}}
{"text": "function [node,elem,bdFlag,HB] = uniformrefine3(node,elem,bdFlag,HB)\n%% UNIFORMREFINE3 uniformly refine a 3-D triangulation.\n% \n% [node,elem] = uniformrefine3(node,elem) divides each tetrahedra into\n% eight small similar sub-tetrahedrons.\n%\n% [node,elem,bdFlag] = uniformrefine3(node,elem,bdFlag) also update boundary\n% conditions represented by bdFlag.\n%\n% [node,elem,~,HB] = uniformrefine3(node,elem) outpus HB array which is\n% useful for nodal interpolation. Unlike bisect3, HB is not useful for the\n% coarsening. See uniformcoarsen3red.\n%\n% Warning: uniform refine in 3D is not orientation presereved. Some volumes\n% of the sub-tetrahedron are negative. The ordering is special such that\n% the refinement can be easy. See uniformrefine3doc for details.\n%\n% Example\n%\n%     [node,elem] = cubemesh([-1,1,-1,1,-1,1]);\n%     figure(1); subplot(1,3,1); \n%     set(gcf,'Units','normal'); set(gcf,'Position',[0.25,0.25,0.5,0.3]);\n%     showmesh3(node,elem,[],'FaceAlpha',0.35); view([210 8]);\n%     [node,elem] = uniformrefine3(node,elem);\n%     figure(1); subplot(1,3,2);\n%     showmesh3(node,elem,[],'FaceAlpha',0.35); view([210 8]);\n%     bdFlag = setboundary3(node,elem,'Dirichlet');\n%     [node,elem,~,bdFlag] = uniformrefine3(node,elem,[],bdFlag);\n%     figure(1); subplot(1,3,3);\n%     showmesh3(node,elem,[],'FaceAlpha',0.35); view([210 8]);\n%\n% See also uniformbisect, uniformrefine, bisect, bisect3, uniformcoarsen3red\n%\n% Reference page in Help browser\n%  <a href=\"matlab:ifem uniformrefine3doc\">ifem uniformrefine3doc</a>\n%\n% Reference: J. Bey. Simplicial grid refinement: on Freudenthal's algorithm\n% and the optimal number of congruence classes. Numer. Math.. 85(1):1--29,\n% 2000. p11 Algorithm: RedRefinement3D.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('bdFlag','var'), bdFlag =[]; end\nif ~exist('HB','var'),    HB = [];     end\n\n%% Construct data structure\n[elem2dof,edge] = dof3P2(elem);\nN = size(node,1); NT = size(elem,1); NE = size(edge,1);\n\n%% Add new nodes\nnode(N+1:N+NE,:) = (node(edge(:,1),:)+node(edge(:,2),:))/2;\nif ~isempty(HB)    \n    maxgeneration = max(HB(:,4));\n    HB(N+1:N+NE,[1 2 3]) = [(N+1:N+NE)', edge(:,1:2)]; \n    HB(N+1:N+NE,4) = maxgeneration + 1; \nend\n\n%% Refine each tetrahedron into 8 tetrahedrons\nt = 1:NT;\np(t,1:10) = elem2dof;\nelem(8*NT,:) = [0 0 0 0]; % enlarge the elem array\nelem(t,:) = [p(t,1), p(t,5), p(t,6), p(t,7)];\nelem(NT+1:2*NT,:) = [p(t,5), p(t,2), p(t,8), p(t,9)];\nelem(2*NT+1:3*NT,:) = [p(t,6), p(t,8), p(t,3), p(t,10)];\nelem(3*NT+1:4*NT,:) = [p(t,7), p(t,9), p(t,10), p(t,4)];\n% always use diagonal 6-9. The ordering is important. See the reference.\nelem(4*NT+1:5*NT,:) = [p(t,5), p(t,6), p(t,7), p(t,9)];\nelem(5*NT+1:6*NT,:) = [p(t,5), p(t,6), p(t,8), p(t,9)];\nelem(6*NT+1:7*NT,:) = [p(t,6), p(t,7), p(t,9), p(t,10)];\nelem(7*NT+1:8*NT,:) = [p(t,6), p(t,8), p(t,9), p(t,10)];\n\n%% Update boundary edges\nif ~isempty(bdFlag)\n    bdFlag(8*NT,:) = [0 0 0 0]; % enlarge the bdFlag array\n    bdFlag(NT+1:2*NT,[1 3 4]) = bdFlag(t,[1 3 4]); \n    bdFlag(2*NT+1:3*NT,[1 2 4]) = bdFlag(t,[1 2 4]); \n    bdFlag(3*NT+1:4*NT,[1 2 3]) = bdFlag(t,[1 2 3]);\n    % always use diagonal 6-9\n    bdFlag(4*NT+1:5*NT,2) = bdFlag(t,3);\n    bdFlag(5*NT+1:6*NT,4) = bdFlag(t,4);\n    bdFlag(6*NT+1:7*NT,3) = bdFlag(t,2);\n    bdFlag(7*NT+1:8*NT,1) = bdFlag(t,1);\n    % change t in the last\n    bdFlag(t,1) = 0;\nelse\n    bdFlag = [];\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/uniformrefine3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5509366343513316}}
{"text": "function [CP2,CNTmat,TOTmat,LENmat] = zero_crossing(M,T,XX,ZIU,ZIL,Z,mu)\n% Estimate out of control points and change-point using zero-crossing\n% method.\n%\n% :Usage:\n% ::\n%\n%     [CP2,CNTmat,TOTmat,LENmat] = zero_crossing(M,T,XX,ZIU,ZIL,Z,mu)\n%\n% Used in ewma5.m  See ewma5 for description of variables.\n\n\nCP2 = NaN .* zeros(M,1); % Estimation via Zero-crossings\nCNTmat  = zeros(M,1);\nTOTmat = zeros(M,1);\nLENmat = zeros(M,T);\n\nwh = all(XX' - repmat(mean(XX'),size(XX,2),1) <= eps) | any(isnan(XX),2)';\nwh = find(~wh);\n    \nooc = ZIU - ZIL;    % pos if occ +, neg if ooc -, zero otherwise\nfor d=wh,\n\n    % Calculate last 'zero-crossing'\n\n    amiout = find(ooc(d,:)); \n    if isempty(amiout)\n        amiout = 0;\n    else\n        amiout = amiout(1);\n        amiout = ooc(d,amiout);  % first ooc tp, -1 or 1\n    end\n    \n    switch amiout\n        \n        case 1\n            dat = Z(d,:)-mu(d);\n            tmp = ZIU(d,:);\n            [a,b] = max((conv([1 1 1],tmp) == 3));  % must be OOC 3 consecutive points\n            [a,zc] = max((dat(1:b) < 0).*(1:b));\n            CP2(d) = zc;\n\n        case -1\n            dat = Z(d,:)-mu(d);\n            tmp = ZIL(d,:);\n            [a,b] = max((conv([1 1 1],tmp) == 3));  % must be OOC 3 consecutive points\n            [a,zc] = max((dat(1:b) > 0).*(1:b));\n            CP2(d) = zc;\n            \n        case 0\n            CP2(d) = NaN;\n            tmp = 0 .* ZIL(d,:);\n        otherwise\n            error('This should never happen'),keyboard\n    end\n\n    % Calculate number of out-of-control runs and their widths\n\n    [cnt tot len] = cnt_runs(tmp);\n    CNTmat(d) = cnt;\n    TOTmat(d) = tot;\n    LENmat(d,:) = len';\n\nend;\n\nCP2(find(CP2 == 1)) = NaN;\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/hewma_utility/zero_crossing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5509366343513316}}
{"text": "%%\ncol = {[0 114 178],[0 158 115], [213 94 0],[230 159 0],...\n    [86 180 233], [204 121 167], [64 224 208], [240 228 66]};\n\n%% AR(1)\ng = .95;\n[Y, trueC, trueSpikes] = gen_data();\nN = size(Y, 1); \n\n% run deconvolution\nlam = 2.4;\n[c_oasis, s_oasis] = oasisAR1(Y(1,:), g, lam);\n[c_foopsi, s_foopsi] = foopsi(Y(1,:), g, lam);\n\n% plot results\nfigure('papersize', [15, 4]);\ninit_fig;\n\n% c\naxes('position', [.05, .57, .95, .37]);\nhold on;\nplot(Y(1,:), 'color', col{8}/255);\nalpha(.7);\nplot(trueC(1,:), 'color', col{3}/255, 'linewidth', 1.5);\nplot(c_oasis, 'color', col{1}/255);\nplot(c_foopsi, '--', 'color', col{7}/255);\naxis tight;\nxlim([0, 2000]);\nset(gca, 'xtick', [0, 25, 50, 75]*30);\nset(gca, 'xticklabel', []);\nset(gca, 'ytick', 0:2);\nylabel('Fluor.');\nbox off;\nlegend('Data', 'Truth', 'OASIS', 'CVX', 'location', 'northeast', 'orientation', 'horizontal');\n% s\naxes('position', [.05, .18, .95, .37]);\nhold on;\nplot(trueSpikes(1,:), 'color', col{3}/255, 'linewidth', 1.5);\nplot(s_oasis, 'color', col{1}/255);\nplot(s_foopsi, '--', 'color', col{7}/255);\naxis tight;\nxlim([0, 2000]);\nset(gca, 'xtick', [0, 25, 50, 75]*30);\nset(gca, 'xticklabel', get(gca, 'xtick')/30);\nset(gca, 'ytick', [0,1]);\nxlabel('Time [s]');\nylabel('Activity.');\n\nsaveas(gcf, 'fig/traceAR1.pdf');\n\n%% time it\nfprintf('\\n**************AR 1**************\\n'); \ntic;\nfor m=1:N\n    [c_oasis, s_oasis] = oasisAR1(Y(m,:), g, lam);\nend\nfprintf('OASIS: %.3f seconds\\n', toc);\n\ntic;\nfor m=1:N\n    [c_foopsi, s_foopsi] = foopsi(Y(1,:), g, lam); %#ok<ASGLU>\nend\nfprintf('FOOPSI: %.3f seconds\\n', toc);\nfprintf('\\n**************AR 1**************\\n'); \n\n%% AR(2)\n% simulation\ng = [1.7, -0.712];\nsn = 1;\nseed = 3;\n[Y, trueC, trueSpikes] = gen_data(g, sn, [], [], [], [], [], seed);\n[N, T] = size(Y);\n\n% deconvolution\nlam = 25;\n[c_onnls, s_onnls] = onnls(Y(1,:), g, lam);\n[c_foopsi, s_foopsi] = foopsi(Y(1,:), g, lam);\nfigure('papersize', [15, 4]);\ninit_fig;\n\n% plot results\nfigure('papersize', [15, 4]);\ninit_fig;\n\n% c\naxes('position', [.05, .57, .46, .37]);\nhold on;\nplot(Y(1,:), 'color', col{8}/255, 'linewidth', 0.5);\nalpha(.7);\nplot(trueC(1,:), 'color', col{3}/255, 'linewidth', 1.5);\nplot(c_onnls, 'color', col{1}/255);\nplot(c_foopsi, '--', 'color', col{7}/255);\naxis tight;\nxlim([0, 1200]);\nset(gca, 'xtick', 0:300:1500);\nset(gca, 'xticklabel', []);\nylim(round([1+min(Y(1,:)), max(Y(1,:))-0.5]));\nylabel('Fluor.');\nbox off;\n% s\naxes('position', [.05, .18, .46, .37]);\nhold on;\nplot(trueSpikes(1,:), 'color', col{3}/255, 'linewidth', 1.5);\nplot(s_onnls, 'color', col{1}/255);\nplot(s_foopsi, '--', 'color', col{7}/255);\naxis tight;\nxlim([0, 1200]);\nset(gca, 'xtick', 0:300:1500);\nset(gca, 'xticklabel', get(gca, 'xtick')/30);\nset(gca, 'ytick', [0,1]);\nxlabel('Time [s]');\nylabel('Activity.');\n\n%% timeit\nfprintf('\\n**************AR 2**************\\n'); \ntic;\nfor m=1:N\n    [c_onnls, s_onnls] = onnls(Y(m,:), g, lam);\nend\nfprintf('online NNLS: %.3f seconds\\n', toc);\n\ntic;\nfor m=1:N\n    [c_foopsi, s_foopsi] = foopsi(Y(m,:), g, lam);\nend\nfprintf('FOOPSI: %.3f seconds\\n', toc);\nfprintf('\\n**************AR 2**************\\n'); \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "zhoupc", "repo": "CNMF_E", "sha": "ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f", "save_path": "github-repos/MATLAB/zhoupc-CNMF_E", "path": "github-repos/MATLAB/zhoupc-CNMF_E/CNMF_E-ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f/OASIS_matlab/examples/Paper/fig3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5509366240384196}}
{"text": "function [diagnostics,out] = VBA_getDiagnostics(posterior,out)\n% derives post-hoc diagnostics of VBA's model inversion\n% function [diagnostics,out] = VBA_getDiagnostics(posterior,out)\n% Post-hoc diagnostics include: goodness-of-fit metrics, Volterra kernels,\n% null model evidence, posterior entropies, etc...\n% IN:\n%   - posterior,out: VBA's output structures\n% OUT:\n%   - diagnostics: a structure containing the following fields:\n%       .pgx: mean of the prior predictive density\n%       .pvy: variance of the prior predictive density\n%       .kernels: Volterra kernels (if options.kernelSize>0)\n%       .efficiency: posterior entropies\n%       .DKL: prior/posterior Kullback-Leibler divergences\n%       .LLH0: log-evidence of the null model\n%       .MT_x: microtime hidden states time series\n%       .MT_gx: microtime predicted data time series\n%       .microTime: microtime sampling grid\n%       .sampleInd: sub-indexing of the microtime sampling grid\n%       .dy: data residuals structure (e.g., autocorrelation...)\n%       .dx: states innovations structure\n%       .C: posterior correlation matrix\n\nu = out.u;\ny = out.y;\n\n% get goodness-tof-fit metrics\ntry; out.fit; catch; out.fit = VBA_getFit(posterior,out); end\n\n% derive Volterra kernels\nif out.dim.n_t>1 && out.options.kernelSize>0\n    try\n        kernels = VBA_getVolterraKernels(posterior,out);\n    catch\n        VBA_disp('  *** could not derive kernels!\\n',out.options);\n        kernels = [];\n    end\nelse\n    kernels = [];\nend\n\n% get null model (H0) evidence\n[LLH0] = VBA_LMEH0(y,out.options);\n\n% Entropies and KL divergences\ngsi = find([out.options.sources.type]==0) ;\nif isempty(gsi)\n    efficiency.sigma = NaN;\n    DKL.sigma = NaN;\nelse\n    for iG=1:numel(gsi)\n        efficiency.sigma(iG) = -out.suffStat.Ssigma(iG);\n        m0 = out.options.priors.a_sigma(iG)/out.options.priors.b_sigma(iG);\n        v0 = out.options.priors.a_sigma(iG)/out.options.priors.b_sigma(iG)^2;\n        m = posterior.a_sigma(iG)/posterior.b_sigma(iG);\n        v = posterior.a_sigma(iG)/posterior.b_sigma(iG)^2;\n        DKL.sigma(iG) = VBA_KL(m0,v0,m,v,'Gamma');\n    end\nend\nif out.dim.n > 0 % hidden states and initial conditions\n    efficiency.X = -out.suffStat.SX;\n    efficiency.X0 = -out.suffStat.SX0;\n    if isinf(out.options.priors.a_alpha) && isequal(out.options.priors.b_alpha,0)\n        efficiency.alpha = NaN;\n        DKL.alpha = NaN;\n    else\n        efficiency.alpha = -out.suffStat.Salpha;\n        m0 = out.options.priors.a_alpha./out.options.priors.b_alpha;\n        v0 = out.options.priors.a_alpha./out.options.priors.b_alpha^2;\n        m = posterior.a_alpha(end)./posterior.b_alpha(end);\n        v = posterior.a_alpha(end)./posterior.b_alpha(end)^2;\n        DKL.alpha = VBA_KL(m0,v0,m,v,'Gamma');\n    end\n    try\n        DKL.X = 0;\n        for t=1:out.dim.n_t\n            IN = out.options.params2update.x{t};\n            m0 = out.options.priors.muX(IN,t);\n            v0 = out.options.priors.SigmaX.current{t}(IN,IN);\n            m = posterior.muX(IN,t);\n            v = posterior.SigmaX.current{t}(IN,IN);\n            DKL.X = DKL.X + VBA_KL(m0,v0,m,v,'Normal');\n        end\n    catch\n        DKL.X = NaN;\n    end\n    IN = out.options.params2update.x0;\n    m0 = out.options.priors.muX0(IN);\n    v0 = out.options.priors.SigmaX0(IN,IN);\n    m = posterior.muX0(IN);\n    v = posterior.SigmaX0(IN,IN);\n    DKL.X0 = VBA_KL(m0,v0,m,v,'Normal');\nelse\n    efficiency.X = NaN;\n    efficiency.X0 = NaN;\n    efficiency.alpha = NaN;\n    DKL.X = NaN;\n    DKL.X0 = NaN;\n    DKL.alpha = NaN;\nend\nif out.dim.n_phi > 0 % observation parameters\n    efficiency.Phi = -out.suffStat.Sphi;\n    IN = out.options.params2update.phi;\n    m0 = out.options.priors.muPhi(IN);\n    v0 = out.options.priors.SigmaPhi(IN,IN);\n    if ~out.options.OnLine\n        m = posterior.muPhi(IN);\n        v = posterior.SigmaPhi(IN,IN);\n    else\n        m = posterior.muPhi(IN,end);\n        v = posterior.SigmaPhi{end}(IN,IN);\n    end\n    DKL.Phi = VBA_KL(m0,v0,m,v,'Normal');\nelse\n    efficiency.Phi = NaN;\n    DKL.Phi = NaN;\nend\nif out.dim.n_theta > 0 % evolution parameters\n    efficiency.Theta = -out.suffStat.Stheta;\n    IN = out.options.params2update.theta;\n    m0 = out.options.priors.muTheta(IN);\n    v0 = out.options.priors.SigmaTheta(IN,IN);\n    if ~out.options.OnLine\n        m = posterior.muTheta(IN);\n        v = posterior.SigmaTheta(IN,IN);\n    else\n        m = posterior.muTheta(IN,end);\n        v = posterior.SigmaTheta{end}(IN,IN);\n    end\n    DKL.Theta = VBA_KL(m0,v0,m,v,'Normal');\nelse\n    efficiency.Theta = NaN;\n    DKL.Theta = NaN;\nend\n\n% get prior predictive density\ntry\n    [muy,Vy] = VBA_getLaplace(u,out.options.f_fname,out.options.g_fname,out.dim,out.options,0,'diag');\ncatch\n    muy =[];\n    Vy = [];\nend\n\n% get micro-time posterior hidden-states estimates\ntry\n    [MT_x,MT_gx,microTime,sampleInd] = VBA_microTime(posterior,u,out);\ncatch\n    MT_x = [];\n    MT_gx = [];\n    microTime = 1:out.dim.n_t;\n    sampleInd = 1:out.dim.n_t;\nend\n\n% get residuals structure: data noise\nfor iS = 1:numel(out.options.sources)\n    % source wise\n    ySource = out.options.sources(iS).out ;\n    res = out.suffStat.dy(ySource,:);\n    if out.options.sources(iS).type==0\n        gi = find(iS==find([out.options.sources(:).type]==0));\n        iQyt = out.options.priors.iQy(:,gi);\n        res = getWeightedResiduals(res,iQyt);\n    end\n    % remove skipped\n    res(out.options.isYout(ySource,:)==1) = NaN ;\n    dy(iS).dy = res(:);\n    dy(iS).R = VBA_spm_autocorr(res);\n    dy(iS).m = VBA_nanmean(dy(iS).dy);\n    dy(iS).v = VBA_nanvar(dy(iS).dy);\n    [dy(iS).ny,dy(iS).nx] = hist(dy(iS).dy,10);\n    dy(iS).ny = dy(iS).ny./sum(dy(iS).ny);\n    d = diff(dy(iS).nx);\n    d = abs(d(1));\n    dy(iS).d = d;\n    spgy = sum(exp(-0.5.*(dy(iS).m-dy(iS).nx).^2./dy(iS).v));\n    dy(iS).grid = dy(iS).nx(1):d*1e-2:dy(iS).nx(end);\n    dy(iS).pg = exp(-0.5.*(dy(iS).m-dy(iS).grid).^2./dy(iS).v);\n    dy(iS).pg = dy(iS).pg./spgy;\n    if  out.options.sources(iS).type==0\n        igs = sum([out.options.sources(1:iS).type]==0);\n        shat = posterior.a_sigma(igs)./posterior.b_sigma(igs);\n        spgy = sum(exp(-0.5.*shat.*dy(iS).nx.^2));\n        dy(iS).pg2 = exp(-0.5.*shat.*dy(iS).grid.^2);\n        dy(iS).pg2 = dy(iS).pg2./spgy;\n    end\nend\n\n% get residuals structure: state noise\nif ~isempty(out.suffStat.dx)\n    wdx = getWeightedResiduals(out.suffStat.dx,out.options.priors.iQx);\n    dx.dx = wdx(:);\n    dx.m = mean(dx.dx);\n    dx.v = var(dx.dx);\n    [dx.ny,dx.nx] = hist(dx.dx,10);\n    dx.ny = dx.ny./sum(dx.ny);\n    d = diff(dx.nx);\n    d = abs(d(1));\n    dx.d = d;\n    spgy = sum(exp(-0.5.*(dx.m-dx.nx).^2./dx.v));\n    dx.grid = dx.nx(1):d*1e-2:dx.nx(end);\n    dx.pg = exp(-0.5.*(dx.m-dx.grid).^2./dx.v);\n    dx.pg = dx.pg./spgy;\n    ahat = posterior.a_alpha(end)./posterior.b_alpha(end);\n    spgy = sum(exp(-0.5.*ahat.*dx.nx.^2));\n    dx.pg2 = exp(-0.5.*ahat.*dx.grid.^2);\n    dx.pg2 = dx.pg2./spgy;\nelse\n    dx.dx = [];\nend\n\n% get parameters posterior correlation matrix\nif out.dim.n > 0 && isinf(out.options.priors.a_alpha) && isequal(out.options.priors.b_alpha,0)\n    S = out.suffStat.ODE_posterior.SigmaPhi;\nelse\n    S = NaN*zeros(out.dim.n+out.dim.n_theta+out.dim.n_phi);\n    ind = 0;\n    if out.dim.n_phi > 0\n        if iscell(posterior.SigmaPhi) % online version\n            SP = posterior.SigmaPhi{end};\n        else\n            SP = posterior.SigmaPhi;\n        end\n        S(1:out.dim.n_phi,1:out.dim.n_phi) = SP;\n        ind = out.dim.n_phi;\n    end\n    if out.dim.n_theta > 0\n        if iscell(posterior.SigmaTheta) % online version\n            SP = posterior.SigmaTheta{end};\n        else\n            SP = posterior.SigmaTheta;\n        end\n        S(ind+1:ind+out.dim.n_theta,ind+1:ind+out.dim.n_theta) = SP;\n        ind = ind + out.dim.n_theta;\n    end\n    if out.dim.n > 0 && out.options.updateX0\n        if iscell(posterior.SigmaX0) % online version\n            SP = posterior.SigmaX0{end};\n        else\n            SP = posterior.SigmaX0;\n        end\n        S(ind+1:ind+out.dim.n,ind+1:ind+out.dim.n) = SP;\n    end\nend\nC = VBA_cov2corr(S);\nC = C + diag(NaN.*diag(C));\ntick = [0];\nltick = [];\nticklabel = cell(0,0);\nif out.dim.n_phi > 0\n    ltick = [ltick,tick(end)+out.dim.n_phi/2];\n    tick = [tick,out.dim.n_phi];\n    ticklabel{end+1} = 'phi';\nend\nif out.dim.n_theta > 0\n    ltick = [ltick,tick(end)+out.dim.n_theta/2];\n    tick = [tick,tick(end)+out.dim.n_theta];\n    ticklabel{end+1} = 'theta';\nend\nif out.dim.n > 0 && out.options.updateX0\n    ltick = [ltick,tick(end)+out.dim.n/2];\n    tick = [tick,tick(end)+out.dim.n];\n    ticklabel{end+1} = 'x0';\nend\ntick = tick +0.5;\ntick = tick(2:end-1);\nltick = ltick + 0.5;\n\n\n% wrap up\ndiagnostics.pgx = reshape(muy,out.dim.p,[]);\ndiagnostics.pvy = reshape(Vy,out.dim.p,[]);\ndiagnostics.kernels = kernels;\ndiagnostics.efficiency = efficiency;\ndiagnostics.DKL = DKL;\ndiagnostics.LLH0 = LLH0;\ndiagnostics.MT_x = MT_x;\ndiagnostics.MT_gx = MT_gx;\ndiagnostics.microTime = microTime;\ndiagnostics.sampleInd = sampleInd;\ndiagnostics.dy = dy;\ndiagnostics.dx = dx;\ndiagnostics.ltick = ltick;\ndiagnostics.tick = tick;\ndiagnostics.ticklabel = ticklabel;\ndiagnostics.C = C;\nout.diagnostics = diagnostics;\n\n\nfunction wdx = getWeightedResiduals(dx,iQx)\n% weigths residuals according to (state/data) precision matrix\nwdx = zeros(size(dx));\nfor t = 1:size(dx,2)\n    sqrtiQ = VBA_sqrtm (iQx{t});\n    wdx(:,t) = sqrtiQ*dx(:,t);\nend\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/core/diagnostics/VBA_getDiagnostics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5509366214244235}}
{"text": "close all;\nclear all;\nclc;\n\naddpath([cd '/utilies']);\nload(['AR_EigenFace']);\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n%FDDL parameter\n%%%%%%%%%%%%%%%%%%%%%%%%\nopts.nClass        =   100;\nopts.wayInit       =   'PCA';\nopts.lambda1       =   0.005;\nopts.lambda2       =   0.05;\nopts.nIter         =   15;\nopts.show          =   true;\n[Dict,Drls,CoefM,CMlabel] = FDDL(tr_dat,trls,opts);\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n% Sparse Classification\n%%%%%%%%%%%%%%%%%%%%%%%%\nlambda   =   0.005;\nnClass   =   opts.nClass;\nweight   =   0.5;\n\ntd1_ipts.D    =   Dict;\ntd1_ipts.tau1 =   lambda;\nif size(td1_ipts.D,1)>=size(td1_ipts.D,2)\n   td1_par.eigenv = eigs(td1_ipts.D'*td1_ipts.D,1);\nelse\n   td1_par.eigenv = eigs(td1_ipts.D*td1_ipts.D',1);  \nend\n\nID   =   [];\nfor indTest = 1:size(tt_dat,2)\n    fprintf(['Totalnum:' num2str(size(tt_dat,2)) 'Nowprocess:' num2str(indTest) '\\n']);\n    td1_ipts.y          =      tt_dat(:,indTest);   \n    [opts]              =      IPM_SC(td1_ipts,td1_par);\n    s                   =      opts.x;\n    \n    for indClass  =  1:nClass\n        temp_s            =  zeros(size(s));\n        temp_s(indClass==Drls) = s(indClass==Drls);\n        zz                =  tt_dat(:,indTest)-td1_ipts.D*temp_s;\n        gap(indClass)     =  zz(:)'*zz(:);\n        \n        mean_coef_c         =   CoefM(:,indClass);\n        gCoef3(indClass)    =  norm(s-mean_coef_c,2)^2;    \n    end\n    \n    wgap3  = gap + weight*gCoef3;\n    index3 = find(wgap3==min(wgap3));\n    id3    = index3(1);\n    ID     = [ID id3];\nend  \n\nfprintf('%s%8f\\n','reco_rate  =  ',sum(ID==ttls)/(length(ttls)));", "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/FDDL/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5509052586484599}}
{"text": "function test15\n%TEST15 test cs_amd\n%\n% Example:\n%   test15\n% See also: testall\n\n%   Copyright 2006-2007, Timothy A. Davis.\n%   http://www.cise.ufl.edu/research/sparse\n\n\nrand ('state', 0) ;\nrandn ('state', 0) ;\nclf\n\nfor trials = 1:100\n    n = fix (200 * rand (1)) ;\n    d = 0.05 * rand (1) ;\n    A = sprandn (n, n, d) ;\n\n    % add a randomly placed dense column\n    k = fix (n * rand (1)) ;\n    k = max (1, k) ;\n    k = min (n, k) ;\n    A (:,k) = 1 ;\n\n    try\n        p0 = amd (A) ;\n    catch\n        p0 = symamd (A) ;\n    end\n    p1 = cs_amd (A) ;\n\n    if (any (sort (p1) ~= 1:n))\n        error ('not perm!') ;\n    end\n\n    C = A+A' + speye (n) ;\n    lnz0 = sum (symbfact (C (p0,p0))) ;\n    lnz1 = sum (symbfact (C (p1,p1))) ;\n    subplot (1,3,1) ; spy (C)\n    subplot (1,3,2) ; spy (C (p0,p0))\n    subplot (1,3,3) ; spy (C (p1,p1))\n    fprintf ('n %4d nz %6d lnz %6d %6d\\n', n, nnz(A), lnz0, lnz1) ;\n    drawnow\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/CSparse/MATLAB/Test/test15.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5509052465142186}}
{"text": "function [price] = PROJ_Double_Barrier(N,alph,call,L,U, S_0,W,M,T,r,rnCHF)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% About: Pricing Function for Discrete Double Barrier Options using PROJ method\n% Models Supported: Levy Processes, including jump diffusions and Black-Scholes model\n% Returns: price of contract\n% Author: Justin Lars Kirkby\n%\n% ----------------------\n% Contract/Model Params \n% ----------------------\n% S_0 = initial stock price (e.g. 100)\n% W   = strike  (e.g. 100)\n% r   = interest rate (e.g. 0.05)\n% q   = dividend yield (e.g. 0.05)\n% T   = time remaining until maturity (in years, e.g. T=1)\n% M   = number of subintervals of [0,T] (total of M+1 monitoring points in time grid, including S_0)\n% call = 1 for call (else put)\n% [L,U] = barriers\n% rnCHF = risk netural characteristic function (function handle with single argument)\n%\n% ----------------------\n% Numerical (PROJ) Params \n% ----------------------\n% N     = number of grid/basis points (power of 2, e.g. 2^12), resolution = 2*alph/(N-1)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nl = log(L/S_0);  u = log(U/S_0);  dt = T/M;\n\nK = N/2;\ndx = (u-l)/(K-1);\na  = 1/dx;\n\nE  = ceil(2*alph/(u-l));\nif M<= 12\n    E = min(E,4);\nelse\n    E = min(E,3);\nend\n\n\na2    = a^2;\nN_Ee  = E*N;\nCons2 = 24*a2*exp(-r*dt)/N_Ee ;\n\n\ngrand = @(w)rnCHF(w).*(sin(w/(2*a))./w).^2./(2+cos(w/a));\ndw    = 2*pi*a/N_Ee ;\nomega = (dw: dw: (N_Ee -1)*dw);      %We calcuate coefficient of w=0 explicitly\nzmin  = (1 - E*K)*dx;           %K corresponds to zero\nbeta  = Cons2*real(fft([1/(24*a^2) exp(-1i*zmin*omega).*feval(grand,omega)]));\n\ntoepM = [beta(E*K:-1:(E-1)*K+1)';0; beta((E+1)*K-1:-1:E*K+1)'];\ntoepM = fft(toepM);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%STEP 1: Payoff Coefficients\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nxmin = l;\nnnot = floor(1-xmin*a);   %index to left of x_0=0\nlws = log(W/S_0);\nnbar = floor(a*(lws - xmin)+1);\nrho   = lws - (xmin+(nbar - 1)*dx);\nzeta  = a*rho;\nxnbar = xmin + (nbar - 1)*dx;\n\nThet  = zeros(K,1);\nCons3 = 1/48;\nCons4 = 1/12;\n\n%%%%%%  Gaussian Quad Constants\nq_plus = (1 + sqrt(3/5))/2;  q_minus = (1 - sqrt(3/5))/2;\nb3  = sqrt(15); b4 = b3/10;\n\n\n%%%% PAYOFF CONSTANTS-----------------------------------\nvarthet_01 = exp(.5*dx)*(5*cosh(b4*dx) - b3*sinh(b4*dx) + 4)/18;\nvarthet_m10 = exp(-.5*dx)*(5*cosh(b4*dx) + b3*sinh(b4*dx) + 4)/18;\nvarthet_star = varthet_01 + varthet_m10;\n\nif call==1  %DBC\n    sigma = 1 - zeta; sigma_plus = (q_plus-.5)*sigma; sigma_minus = (q_minus-.5)*sigma;\n    es1 = exp(dx*sigma_plus); es2 = exp(dx*sigma_minus);\n    dbar_0 = .5 + zeta*(.5*zeta-1);\n    dbar_1 = sigma*(1 - .5*sigma);\n\n    d_0 = exp((rho+dx)*.5)*sigma^2/18*(5*((1-q_minus)*es2 +(1-q_plus)*es1) + 4);\n    d_1 = exp((rho-dx)*.5)*sigma/18*(5*( (.5*(zeta+1) +sigma_minus)*es2 + (.5*(zeta+1) +sigma_plus)*es1 ) + 4*(zeta+1) );\n    \n   \n    Thet(nbar)         = W*(exp(-rho)*d_0 - dbar_0);\n    Thet(nbar + 1)     = W*(exp(dx-rho)*(varthet_01 +d_1) -(.5 + dbar_1) );\n    Thet(nbar + 2:K-1) = exp(xmin +dx*(nbar+1:K-2))*S_0*varthet_star - W;\n    Thet(K)            = U*varthet_m10 - W/2;\n    %%%%%%%\n    p = ifft(toepM.*fft([Thet(1:K);zeros(K,1)]));\n    Val = p(1:K);\n    %%%%%%%\n    for m=M-2:-1:0\n        Thet(1)      = Cons3*(13*Val(1)+15*Val(2)-5*Val(3)+Val(4));\n        Thet(K)      = Cons3*(13*Val(K)+15*Val(K-1)-5*Val(K-2)+Val(K-3));\n        Thet(2:K -1) = Cons4*(Val(1:K-2)+10*Val(2:K-1)+Val(3:K));\n        %%%%%%%\n        p        = ifft(toepM.*fft([Thet(1:K);zeros(K,1)]));\n        Val = p(1:K);\n    end\n    \n    \nelse  %DBP\n    zeta_plus = zeta*q_plus; zeta_minus = zeta*q_minus;\n    rho_plus = rho*q_plus; rho_minus = rho*q_minus;\n\n    ed1 = exp(rho_minus); ed2 = exp(rho/2); ed3 = exp(rho_plus);\n\n    dbar_1 = zeta^2/2;\n    dbar_0 = zeta - dbar_1;         %  dbar_1 = zeta + .5*((zeta - 1)^2 - 1);\n    d_0    = zeta*(5*( (1-zeta_minus)*ed1 + (1-zeta_plus)*ed3 ) + 4*(2-zeta)*ed2)/18;\n    d_1    = zeta*( 5*(zeta_minus*ed1 + zeta_plus*ed3) + 4*zeta*ed2 )/18;            \n\n    Thet(1)        =  W/2 - L*varthet_01;\n    Thet(2:nbar-1) =  W - exp(xmin +dx*(1:nbar-2))*S_0*varthet_star;\n    Thet(nbar)     =  W*(.5 + dbar_0 - exp(-rho)*(varthet_m10 + d_0));\n    Thet(nbar + 1) =  W*(dbar_1 - exp(- rho)*d_1);\n    %%%%%%%\n    p   = ifft(toepM.*fft([Thet(1:K);zeros(K,1)]));\n    Val = p(1:K);\n    %%%%%%%\n    for m=M-2:-1:0\n        Thet(1)      = Cons3*(13*Val(1)+15*Val(2)-5*Val(3)+Val(4));\n        Thet(K)      = Cons3*(13*Val(K)+15*Val(K-1)-5*Val(K-2)+Val(K-3));\n        Thet(2:K -1) = Cons4*(Val(1:K-2)+10*Val(2:K-1)+Val(3:K));\n        %%%%%%%\n        p    = ifft(toepM.*fft([Thet(1:K);zeros(K,1)]));\n        Val  = p(1:K);\n    end   \nend\n\nxnot = l+(nnot-1)*dx;\nxs = [xnot-2*dx,xnot-dx,xnot,xnot+dx,xnot+2*dx];\nys = [Val(nnot-2),Val(nnot-1),Val(nnot),Val(nnot+1),Val(nnot+2)];\nprice = spline(xs,ys,0);\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/LEVY/Barrier_Options/PROJ_Double_Barrier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5508966401948369}}
{"text": "%% FM Comparison (with SHOT descriptors) - First run preprocess_artist_model.m\nclear all; close all; clc\n\naddpath(genpath('./'))\naddpath(genpath('./../Tools/'))\n\nmodel_0 = load('./tf_artist/model_0.mat');\nmodel_1 = load('./tf_artist/model_1.mat');\nA = model_0.model_evecs_trans*model_0.model_shot;\nB = model_1.model_evecs_trans*model_1.model_shot;\nC = mldivide(A',B')'; %B = C*A\nP = model_1.model_evecs*C*model_0.model_evecs_trans;\nP = normc(P);\n[~, matches_0_1] = max(P,[],1);\n\nmesh_0 = load('./artist_models/model_0_remesh'); mesh_0 = mesh_0.part;\nmesh_1 = load('./artist_models/model_1_remesh'); mesh_1 = mesh_1.model;\nD_0 = load('./tf_artist/model_0_dist.mat'); D_0 = D_0.D;\nD_1 = load('./tf_artist/model_1_dist.mat'); D_1 = D_1.D;\n\ncolors = create_colormap(mesh_1,mesh_1);\nfigure;\nsubplot(1,2,1); colormap(colors);\nplot_scalar_map(mesh_1,[1: size(mesh_1.VERT,1)]');freeze_colors;title('Target');\n\nsubplot(1,2,2); colormap(colors(matches_0_1,:));\nplot_scalar_map(mesh_0,[1: size(mesh_0.VERT,1)]');freeze_colors;title('Source');\n\nsave('matches_axiomatic_SHOT_FM.mat','matches_0_1');\n\n%% PMF Refinement\n[~, matches_filter] = ...\n    my_mfilter(mesh_0.n, mesh_1.n, matches_0_1 , [], 150000/400, D_0, D_1, 0); %corr is not used and set to [];\n   \nfigure;\nsubplot(1,2,1); colormap(colors);\nplot_scalar_map(mesh_1,[1: size(mesh_1.VERT,1)]');freeze_colors;title('Target');\n\nsubplot(1,2,2); colormap(colors(matches_filter,:));\nplot_scalar_map(mesh_0,[1: size(mesh_0.VERT,1)]');freeze_colors;title('Source');\n\nsave('matches_axiomatic_SHOT_FM_PMF.mat','matches_filter');\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/Single Pair Experiment/SHOT_FM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5507314311759854}}
{"text": "% SYNTAX:\n% dc = hmrR_OD2Conc_new_Nirs( dod, SD, ppf )\n%\n% UI NAME:\n% OD_to_Conc\n%\n% DESCRIPTION:\n% Convert OD to concentrations\n%\n% INPUTS:\n% dod: the change in OD (#time points x #channels)\n% SD:  the SD structure\n% ppf: Partial path length factors for each wavelength. If there are 2 wavelengths \n%      of data, then this is a vector of 2 elements.  Typical value is ~6 for each \n%      wavelength if the absorption change is uniform over the volume of tissue measured. \n%      To approximate the partial volume effect of a small localized absorption change \n%      within an adult human head, this value could be as small as 0.1. Convention is \n%      becoming to set ppf=1 and to not divide by the source-detector separation such that \n%      the resultant \"concentration\" is in units of Molar mm (or Molar cm if those are the \n%      spatial units). This is becoming wide spread in the literature but there is no \n%      fixed citation. Use a value of 1 to choose this option.\n%\n% OUTPUTS:\n% dc: the concentration data (#time points x 3 x #SD pairs\n%     3 concentrations are returned (HbO, HbR, HbT)\n%\n% USAGE OPTIONS:\n% Delta_OD_to_Conc: dc = hmrR_OD2Conc_new_Nirs( dod, SD, ppf )\n%\n% PARAMETERS:\n% ppf: [1.0, 1.0, 1.0]\n%\nfunction dc = hmrR_OD2Conc_new_Nirs( dod, SD, ppf )\n\ndc = [];\nnWav = length(SD.Lambda);\nml = SD.MeasList;\n\nif length(ppf) < nWav\n    errordlg('WARNING: Data contains more than 3 wavelengths. Using PPF value of 1 for all wavelengths.');\n    ppf = ones(1, nWav);\nelseif length(ppf) > nWav\n    d = length(ppf)-nWav;\n    ppf(end-d+1:end) = [];\nend\n\nif ~isempty(find(ppf==1))\n    ppf = ones(size(ppf));\nend\n\nnTpts = size(dod,1);\n\ne = GetExtinctions( SD.Lambda );\nif ~isfield(SD,'SpatialUnit')\n    e = e(:,1:2) / 10; % convert from /cm to /mm\nelseif strcmpi(SD.SpatialUnit,'mm')\n    e = e(:,1:2) / 10; % convert from /cm to /mm\nelseif strcmpi(SD.SpatialUnit,'cm')\n    e = e(:,1:2) ;\nend\neinv = inv( e'*e )*e';\n\nlst = find( ml(:,4)==1 );\nfor idx=1:length(lst)\n    idx1 = lst(idx);\n    idx2 = find( ml(:,4)>1 & ml(:,1)==ml(idx1,1) & ml(:,2)==ml(idx1,2) );\n    rho = norm(SD.SrcPos(ml(idx1,1),:)-SD.DetPos(ml(idx1,2),:));\n    if ppf(1)~=1\n        dc(:,:,idx) = ( einv * (dod(:,[idx1 idx2'])./(ones(nTpts,1)*rho*ppf))' )';\n    else\n        dc(:,:,idx) = ( einv * (dod(:,[idx1 idx2'])./(ones(nTpts,1)))' )';\n    end\nend\ndc(:,3,:) = dc(:,1,:) + dc(:,2,:);\n", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/FuncRegistry/UserFunctions/Archive/hmrR_OD2Conc_Nirs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.5507314275810643}}
{"text": "function S = MSAFinit(w0,mu,N,L,H,F)\n\n% MSAFinit      Initialize Parameter Structure for the MSAF Algorithm\n%                 Psuedo-QMF CMFB is Used by Default, H and F are Used Otherwise\n%\n% Arguments: \n% w0            Coefficients of FIR filter at start\n% mu            Step size\n% N             Number of subbands\n% H             Analysis filter bank (optional), each column represents a filter\n% F             Synthesis filter bank (optional), each column represents a filter\n\nif nargin > 4\n    if (size(H,2)~=N)|(size(F,2)~=N)\n        error('Columns of H (%d) or F (%d) not match with N = %d',size(H,2),size(F,2),N);\n    end\nelse\n\n% Defualt filter bank: Pseudo-QMF CMFB\n\n    [hopt,passedge] = opt_filter(L-1,N); % Generate a prototype lowpass filter\n    [H,F] = make_bank(hopt,N);           % Generate filter banks using cosine modulation\n    H = sqrt(N)*H';                      % Analysis section\n    F = sqrt(N)*F';                      % Synthesis section\nend\n\n% Assign structure fields\n\nS.coeffs        = w0(:);                 % Convert to column vector of length M\nS.step          = mu;\nS.analysis      = H;\nS.synthesis     = F;\nS.iter          = 0;                     % Iteration count\nS.alpha         = ones(1,N)*1e-4;        % Small positive constant\nS.AdaptStart    = L + length(w0);        % Running effect of analysis and adaptive filter, \n                                         %   minimum L + M\n\n\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 6 -- Multiband-structured subband adaptive filters/MSAFinit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5507314216827934}}
{"text": "function [inside] = bounding_mesh(pos, pnt, tri);\n\n% BOUNDING_MESH determines if a point is inside/outside a triangle mesh \n% whereby the bounding triangle mesh should be closed.\n%\n% [inside] = bounding_mesh(pos, pnt, tri)\n%\n% where\n%   pos     position of point of interest (can be 1x3 or Nx3)\n%   pnt     bounding mesh vertices\n%   tri     bounding mesh triangles\n%\n% See also SOLID_ANGLE\n\n% Copyright (C) 2003, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip\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 <http://www.gnu.org/licenses/>.\n%\n% $Id: bounding_mesh.m 2885 2011-02-16 09:41:58Z roboos $\n\nglobal fb;\nif isempty(fb)\n  fb = 0;\nend\n\nnpos = size(pos, 1);\nnpnt = size(pnt, 1);\nntri = size(tri, 1);\n\n% determine a cube that encompases the boundary triangulation\nbound_min = min(pnt);\nbound_max = max(pnt);\n\n% determine a sphere that is completely inside the boundary triangulation\nbound_org = mean(pnt);\nbound_rad = sqrt(min(sum((pnt - repmat(bound_org, size(pnt,1), 1)).^2, 2)));\n\ninside = zeros(npos, 1);\nfor i=1:npos\n  if fb\n    fprintf('%6.2f%%', 100*i/npos);\n  end\n  if any(pos(i,:)<bound_min) || any(pos(i,:)>bound_max)\n    % the point is outside the bounding cube\n    inside(i) = 0;\n    if fb, fprintf(' outside the bounding cube\\n'); end\n  elseif sqrt(sum((pos(i,:)-bound_org).^2, 2))<bound_rad \n    % the point is inside the interior sphere\n    inside(i) = 1;\n    if fb, fprintf(' inside the interior sphere\\n'); end\n  else\n    % the point is inside the bounding cube but outside the interior sphere\n    % compute the total solid angle of the surface, which is zero for a point outside\n    % the triangulation and 4*pi or -4*pi for a point inside (depending on the triangle\n    % orientation)\n    tmp = pnt - repmat(pos(i,:), npnt, 1);\n    solang = solid_angle(tmp, tri);\n    if any(isnan(solang))\n      inside(i) = nan;\n    elseif (abs(sum(solang))-2*pi)<0\n      % total solid angle is (approximately) zero\n      inside(i) = 0;\n    elseif (abs(sum(solang))-2*pi)>0\n      % total solid angle is (approximately) plus or minus 4*pi\n      inside(i) = 1;\n    end\n    if fb, fprintf(' solid angle\\n'); end\n  end\nend\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/external/fieldtrip_partial/inverse/private/bounding_mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5507314216827933}}
{"text": "function linpack_c_test33 ( )\n\n%*****************************************************************************80\n%\n%% TEST33 tests CSPFA and CSPDI.\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    25 June 2009\n%\n%  Author:\n%\n%    John Burkardt\n%\n  n = 3;\n\n  fprintf ( 1, '\\n' )\n  fprintf ( 1, 'TEST33\\n' );\n  fprintf ( 1, '  For a single precision complex (C)\\n' );\n  fprintf ( 1, '  symmetric matrix in packed storage (SP)\\n' );\n  fprintf ( 1, '  CSPFA factors the matrix.\\n' );\n  fprintf ( 1, '  CSPDI computes the determinant or inverse.\\n' );\n  fprintf ( 1, '\\n' )\n  fprintf ( 1, '  The matrix order is N = %d\\n', n );\n%\n%  Set the values of the packed matrix A.\n%\n  k = 0;\n  seed = 123456789;\n\n  for j = 1 : n\n\n    for i = 1 : j-1\n      k = k + 1;\n      [ a(k), seed ] = c4_uniform_01 ( seed );\n    end\n\n    k = k + 1;\n    [ a(k), seed ] = c4_uniform_01 ( seed );\n\n  end\n%\n%  Copy the packed matrix into a \"normal\" matrix.\n%\n  k = 0;\n  for j = 1 : n\n    for i = 1 : j\n      k = k + 1;\n      a_save(i,j) = a(k);\n    end\n  end\n\n  for j = 1 : n\n    a_save(j+1:n,j) = transpose ( a_save(j,j+1:n) );\n  end\n\n  fprintf ( 1, '\\n' )\n  fprintf ( 1, '  The matrix A is\\n' );\n  fprintf ( 1, '\\n' )\n \n  for i = 1 : n\n    for j = 1 : n\n      fprintf ( 1, '  (%8f  %8f)', real ( a_save(i,j) ), imag ( a_save(i,j) ) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n%\n%  Factor the matrix A.\n%\n  [ a, ipvt, info ] = cspfa ( a, n );\n \n  if ( info ~= 0 )\n    fprintf ( 1, '\\n' )\n    fprintf ( 1, '  CSPFA returned an error flag INFO = %d\\n', info );\n    return\n  end\n%\n%  Get the determinant.\n%\n  job = 10;\n  [ a, det ] = cspdi ( a, n, ipvt, job );\n \n  fprintf ( 1, '\\n' )\n  fprintf ( 1, '  Determinant = (%8f  %8f)*10^(%8f)\\n', ...\n    real ( det(1) ), imag ( det(1) ), real ( det(2) ) );\n%\n%  Get the inverse.\n%\n  job = 01;\n  [ a, det ] = cspdi ( a, n, ipvt, job );\n%\n%  Copy the packed matrix into a \"normal\" matrix.\n%\n  k = 0;\n  for j = 1 : n\n    for i = 1 : j\n      k = k + 1;\n      b_save(i,j) = a(k);\n    end\n  end\n\n  for j = 1 : n\n    b_save(j+1:n,j) = transpose ( b_save(j,j+1:n) );\n  end\n \n  c(1:n,1:n) = b_save(1:n,1:n) * a_save(1:n,1:n);\n\n  fprintf ( 1, '\\n' )\n  fprintf ( 1, '  The product inv(A) * A is\\n' );\n  fprintf ( 1, '\\n' )\n \n  for i = 1 : n\n    for j = 1 : n\n      fprintf ( 1, '  (%8f  %8f)', real ( c(i,j) ), imag ( c(i,j) ) );\n    end\n    fprintf ( 1, '\\n' );\n  end\n\n  return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_c/linpack_c_test33.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5506543318910392}}
{"text": "%% FEM2D_SCRIPT carries out the finite element assembly and solution procedures.\n%\n%  Discussion:\n%\n%    The BATCH command runs scripts, not functions.  So we have to write\n%    this short script if we want to work with BATCH!\n%\n%  Licensing:\n%\n%    This code is distributed under the GNU LGPL license.\n%\n%  Modified:\n%\n%    29 March 2010\n%\n%  Author:\n%\n%    John Burkardt\n%\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'FEM2D_SCRIPT\\n' );\n  fprintf ( 1, '  Call FEM2D_FUN to set up and solve the system.\\n' );\n%\n%  Get the problem parameters.\n%\n  param = p_data ( );\n%\n%  Set up the mesh, the linear system, and solve.\n%\n  [ x, z_ss ] = fem2d_fun ( param );\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_heat_rectangle_steady_spmd/fem2d_script.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5506543272729544}}
{"text": "%% Armstrong no\n\nfunction n= is_armstrong(num)\nif(num<0)\n    n=0; %as negative no can't be armstrong\nend\nsum=0;\ntemp=num;\nwhile(temp>0)\n    sum=sum*10 + rem(temp,10);\n    temp=fix(temp/10);\nend\nif(sum==num)\n    n=1;    % the no is armstrong\nelse\n    n=0;    % the no is not armstrong\nend\nend\n", "meta": {"author": "TheAlgorithms", "repo": "MATLAB-Octave", "sha": "e150b77ad256de46c1ce3815c3d7945ac4fc28dc", "save_path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave", "path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave/MATLAB-Octave-e150b77ad256de46c1ce3815c3d7945ac4fc28dc/algorithms/maths/is_armstrong.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5506543196023485}}
{"text": "function varargout = pnopt_backtrack( x, d, t, f_x, h_x, dg_x, smoothF, ...\n  nonsmoothF, desc_param, xtol, maxIter )\n% pnopt_backtrack : Backtracking line search for step that satisfies a sufficient \n%   descent condition.\n% \n%   $Revision: 0.8.0 $  $Date: 2012/12/01 $\n% \n% --------------------Initialize--------------------\n\n  % Set line search parameters\n  beta = 0.5;\n\n  % Set termination flags\n  FLAG_SUFFDESC = 1;\n  FLAG_TOLX     = 2;\n  FLAG_MAXFUNEV = 3;\n\n  iter = 0;\n  \n  desc = dg_x + nonsmoothF( x + d ) - h_x;\n  \n  % --------------------Main Loop--------------------\n  while 1\n    iter = iter + 1;\n    \n    % Evaluate trial point and function value.\n    y = x + d * t;\n    if nargout > 6\n      [ g_y, Dg_y, D2g_y ] = smoothF( y );\n    else\n      [ g_y, Dg_y ] = smoothF( y );\n    end\n    h_y = nonsmoothF( y );\n    f_y = g_y + h_y;\n    \n    % Check termination criteria\n    if f_y < f_x + desc_param * t * desc         % Sufficient descent condition satisfied\n      flag = FLAG_SUFFDESC;  \n      break\n    elseif t <= xtol            % Step length too small\n      flag = FLAG_TOLX;\n      break\n    elseif iter >= maxIter      % Too many line search iterations\n      flag = FLAG_MAXFUNEV;\n      break\n    end\n\n    % Backtrack if objective value not well-defined\n    if isnan( f_y ) || isinf( f_y ) || abs( f_y - f_x - t * dg_x ) <= 1e-9\n      t = beta * t;\n    % Safeguard quadratic interpolation\n    else\n      t_interp = - ( dg_x * t^2) / ( 2 * ( f_y - f_x - t * dg_x ) );\n      if 0.01 <= t_interp && t_interp <= 0.99*t \n        t = t_interp;\n      else\n        t = beta * t;\n      end\n    end\n\n  end \n  \n  if nargout > 6\n    varargout = { y, f_y, Dg_y, D2g_y, t, flag ,iter };\n  else\n    varargout = { y, f_y, Dg_y, t, flag ,iter };\n  end\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/pacifier/private/pnopt_backtrack.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5506543196023485}}
{"text": "function b = isPointInPolygon(point, poly)\n%ISPOINTINPOLYGON Test if a point is located inside a polygon\n%\n%   B = isPointInPolygon(POINT, POLYGON)\n%   Returns true if the point is located within the given polygon.\n%\n%   This function is simply a wrapper for the function inpolygon, to avoid\n%   decomposition of point and polygon coordinates.\n%\n%   Example\n%     pt1 = [30 20];\n%     pt2 = [30 5];\n%     poly = [10 10;50 10;50 50;10 50];\n%     isPointInPolygon([pt1;pt2], poly)\n%     ans =\n%          1\n%          0\n%\n%     poly = [0 0; 10 0;10 10;0 10;NaN NaN;3 3;3 7;7 7;7 3];\n%     pts = [5 1;5 4];\n%     isPointInPolygon(pts, poly);\n%     ans =\n%          1\n%          0\n%\n%\n%   See also\n%   points2d, polygons2d, inpolygon, isPointInTriangle\n\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@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%   2013-04-24 add support for multiply connected polygons\n\n% In case of a multiple polygon, decompose into a set of contours, and\n% performs test for each contour\nif iscell(poly) || any(isnan(poly(:)))\n    % transform as a cell array of simple polygons\n    polygons = splitPolygons(poly);\n    N = length(polygons);\n    Np = size(point, 1);\n    \n    % compute orientation of polygon, and format to have Np*N matrix\n    areas = zeros(N, 1);\n    for i = 1:N\n        areas(i) = polygonArea(polygons{i});\n    end\n    ccw = areas > 0;\n    ccw = repmat(ccw', Np, 1);\n    \n    % test if point inside each polygon\n    in = false(size(point, 1), N);\n    for i = 1:N\n        poly = polygons{i};\n        in(:, i) = inpolygon(point(:,1), point(:,2), poly(:,1), poly(:,2));\n    end\n    \n    % count polygons containing point, weighted by polygon orientation\n    b = sum(in.*(ccw==1) - in.*(ccw==0), 2) > 0;\n\nelse\n    % standard test for simple polygons\n    b = inpolygon(point(:,1), point(:,2), poly(:,1), poly(:,2));\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/isPointInPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.5506543111489606}}
{"text": "function tv = Fval(u, img, alpha, huber)\n% total variation part of the criterion\n\n[H W] = size(img);\nN = W * H;\n\nnabla = make_derivatives_mine(H, W);\n\nif huber\n    tv = nabla * u(:);\n    tv_size = sqrt(tv(1:N).^2 + tv(N+1:end).^2);\n    idx1 = tv_size <= alpha;\n    idx2 = tv_size > alpha;\n    tv = sum(tv_size(idx1).^2/(2*alpha)) + sum(tv_size(idx2) - alpha/2);\nelse\n    tv = nabla * u(:);\n    tv = sum(sqrt(tv(1:N).^2 + tv(N+1:end).^2));\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u53bb\u566a\u7b97\u6cd5/TVdenoising-master/Fval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5506098343080754}}
{"text": "function r8col_to_r8vec_test ( )\n\n%*****************************************************************************80\n%\n%% R8COL_TO_R8VEC_TEST tests R8COL_TO_R8VEC.\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  m = 3;\n  n = 4;\n\n  fprintf ( 1, '\\n' );\n  fprintf ( 1, 'R8COL_TO_R8VEC_TEST\\n' );\n  fprintf ( 1, '  R8COL_TO_R8VEC converts an array of columns to a vector.\\n' );\n  fprintf ( 1, '\\n' );\n \n  for i = 1 : m\n    for j = 1 : n\n      a(i,j) = 10 * i + j;\n    end\n  end\n\n  r8mat_print ( m, n, a, '  The array of columns:' );\n \n  x = r8col_to_r8vec ( m, n, a );\n \n  r8vec_print ( m*n, x, '  The resulting vector of columns:' );\n \n  return\nend\n", "meta": {"author": "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/r8col_to_r8vec_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.5506098293842943}}
{"text": "function Offspring = Operator(Problem,Particle,Pbest,Gbest)\n% Particle swarm optimization in MMOPSO\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    %% Parameter setting\n    ParticleDec = Particle.decs;\n    PbestDec    = Pbest.decs;\n    GbestDec    = Gbest.decs;\n    [N,D]       = size(ParticleDec);\n    ParticleVel = Particle.adds(zeros(N,D));\n\n    %% Particle swarm optimization\n    W  = repmat(unifrnd(0.1,0.5,N,1),1,D);\n    r1 = repmat(rand(N,1),1,D);\n    r2 = repmat(rand(N,1),1,D);\n    C1 = repmat(unifrnd(1.5,2,N,1),1,D);\n    C2 = repmat(unifrnd(1.5,2,N,1),1,D);\n    OffVel        = W.*ParticleVel;\n    temp          = repmat(rand(N,1)<0.7,1,D);\n    OffVel(temp)  = OffVel(temp) + C1(temp).*r1(temp).*(PbestDec(temp)-ParticleDec(temp));\n    OffVel(~temp) = OffVel(~temp) + C2(~temp).*r2(~temp).*(GbestDec(~temp)-ParticleDec(~temp));\n    OffDec        = ParticleDec + OffVel;\n    Offspring     = Problem.Evaluation(OffDec,OffVel);\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/MMOPSO/Operator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5506098211429659}}
{"text": "function [Gc,Kp,Ti,Td,H]=optPID(key,typ,vars)\nk=vars(1); L=vars(2); T=vars(3); N=vars(4); \nTd=[];H=1;\nif length(vars)==5, iC=vars(5); tt=0;  \nelse, \n   Kc=vars(5); Tc=vars(6); kappa=vars(7); tt=1; \nend\nif tt==0\n   if key==2\nPIDtab=[0.980, 0.712, 0.569, 1.072, 0.786, 0.628;\n       -0.892,-0.921,-0.951,-0.560,-0.559,-0.583;\n        0.690, 0.968, 1.023, 0.648, 0.883, 1.007;\n       -0.155,-0.247,-0.179,-0.114,-0.158,-0.167];\n   elseif key==3\nPIDtab=[1.048, 1.042, 0.968, 1.154, 1.142, 1.061; \n       -0.897,-0.897,-0.904,-0.567,-0.579,-0.583;\n        1.195, 0.987, 0.977, 1.047, 0.919, 0.892;\n       -0.368,-0.238,-0.253,-0.220,-0.172,-0.165;\n        0.489, 0.385, 0.316, 0.490, 0.384, 0.315;\n        0.888, 0.906, 0.892, 0.708, 0.839, 0.832];\n   elseif key==4\nPIDtab=[1.260, 1.053, 0.942, 1.295, 1.120, 1.001;\n       -0.887,-0.930,-0.933,-0.619,-0.625,-0.624;\n        0.701, 0.736, 0.770, 0.661, 0.720, 0.754;\n       -0.147,-0.126,-0.130,-0.110,-0.114,-0.116;\n        0.375, 0.349, 0.308, 0.378, 0.350, 0.308;\n        0.886, 0.907, 0.897, 0.756, 0.811, 0.813];\n   end\n   ii=0; if (L/T>1) ii=3; end; tt=L/T; \n   a1=PIDtab(1,ii+iC); b1=PIDtab(2,ii+iC); \n   a2=PIDtab(3,ii+iC); b2=PIDtab(4,ii+iC); \n   Kp=a1/k*tt^b1; Ti=T/(a2+b2*tt); \n   if key==3| key==4\n      a3=PIDtab(5,ii+iC); b3=PIDtab(6,ii+iC); \n      Td=a3*T*tt^b3;\n   end\nelse\n   if key==2,\n      Kp=0.361*Kc; Ti=0.083*(1.935*kappa+1)*Tc; \n   elseif key==3,\n      Kp=0.509*Kc; Td=0.125*Tc;\n      Ti=0.051*(3.302*kappa+1)*Tc;\n   elseif key==4,\n      Kp=(4.437*kappa-1.587)...\n         /(8.024*kappa-1.435)*Kc; \n      Ti=0.037*(5.89*kappa+1)*Tc;  \n      Td=0.112*Tc;\n   end\nend\nif key==2, Gc=tf(Kp*[Ti,1],[Ti,0]);\nelseif key==3\n   nn=[Kp*Ti*Td*(N+1)/N, Kp*(Ti+Td/N), Kp];\n   dd=Ti*[Td/N,1,0]; Gc=tf(nn,dd);\nelseif key==4\n   Gc=tf(Kp*[Ti,1],[Ti,0]);\n   nH=[(1+Kp/N)*Ti*Td, Kp*(Ti+Td/N), Kp];\n   dH=Kp*conv([Ti,1],[Td/N,1]); H=tf(nH,dH);\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/2302-feedback-control-systems/xue/optpid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5506098178254184}}
{"text": "function [R,eff] = randmio_und_connected(R, ITER)\n%RANDMIO_UND_CONNECTED     Random graph with preserved degree distribution\n%\n%   R = randmio_und_connected(W,ITER);\n%   [R eff] = randmio_und_connected(W, ITER);\n%\n%   This function randomizes an undirected network, while preserving the\n%   degree distribution. The function does not preserve the strength\n%   distribution in weighted networks. The function also ensures that the\n%   randomized network maintains connectedness, the ability for every node\n%   to reach every other node in the network. The input network for this\n%   function must be connected.\n%\n%   Input:      W,      undirected (binary/weighted) connection matrix\n%               ITER,   rewiring parameter\n%                       (each edge is rewired approximately ITER times)\n%\n%   Output:     R,      randomized network\n%               eff,    number of actual rewirings carried out\n%\n%   References: Maslov and Sneppen (2002) Science 296:910\n%\n%\n%   2007-2012\n%   Mika Rubinov, UNSW\n%   Jonathan Power, WUSTL\n%   Olaf Sporns, IU\n\n%   Modification History:\n%   Jun 2007: Original (Mika Rubinov)\n%   Apr 2008: Edge c-d is flipped with 50% probability, allowing to explore\n%             all potential rewirings (Jonathan Power)\n%   Mar 2012: Limit number of rewiring attempts, count number of successful\n%             rewirings (Olaf Sporns)\n\n\nn=size(R,1);\n[i,j]=find(tril(R));\nK=length(i);\nITER=K*ITER;\n\n% maximal number of rewiring attempts per 'iter'\nmaxAttempts= round(n*K/(n*(n-1)));\n% actual number of successful rewirings\neff = 0;\n\nfor iter=1:ITER\n    att=0;\n    while (att<=maxAttempts)                                     %while not rewired\n        rewire=1;\n        while 1\n            e1=ceil(K*rand);\n            e2=ceil(K*rand);\n            while (e2==e1)\n                e2=ceil(K*rand);\n            end\n            a=i(e1); b=j(e1);\n            c=i(e2); d=j(e2);\n            \n            if all(a~=[c d]) && all(b~=[c d])\n                break           %all four vertices must be different\n            end\n        end\n        \n        if rand>0.5\n            i(e2)=d; j(e2)=c; \t%flip edge c-d with 50% probability\n            c=i(e2); d=j(e2); \t%to explore all potential rewirings\n        end\n        \n        %rewiring condition\n        if ~(R(a,d) || R(c,b))\n            %connectedness condition\n            if ~(R(a,c) || R(b,d))\n                P=R([a d],:);\n                P(1,b)=0; P(2,c)=0;\n                PN=P;\n                PN(:,d)=1; PN(:,a)=1;\n                \n                while 1\n                    P(1,:)=any(R(P(1,:)~=0,:),1);\n                    P(2,:)=any(R(P(2,:)~=0,:),1);\n                    P=P.*(~PN);\n                    if ~all(any(P,2))\n                        rewire=0;\n                        break\n                    elseif any(any(P(:,[b c])))\n                        break\n                    end\n                    PN=PN+P;\n                end\n            end %connectedness testing\n            \n            if rewire               %reassign edges\n                R(a,d)=R(a,b); R(a,b)=0;\n                R(d,a)=R(b,a); R(b,a)=0;\n                R(c,b)=R(c,d); R(c,d)=0;\n                R(b,c)=R(d,c); R(d,c)=0;\n                \n                j(e1) = d;          %reassign edge indices\n                j(e2) = b;\n                eff = eff+1;\n                break;\n            end %edge reassignment\n        end %rewiring condition\n        att=att+1;\n    end %while not rewired\nend %iterations", "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/randmio_und_connected.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5506098129016372}}
{"text": "function Q = planarize(V,F,varargin)\n  % PLANARIZE Planarize the quads of quad mesh using the local-local technique\n  % of \"Interactive Planarization and Optimization of 3D Meshes\" [Poranne et\n  % al. 2012]\n  % \n  % Q = planarize(V,F,varargin)\n  %\n  % Inputs:\n  %   V  #V by dim list of mesh vertex positions\n  %   F  #F by 4 list of quad indices into V\n  %     Optional:\n  %       'MaxIter' followed by maximum number of iterations {100}\n  %       'mu' followed by \"mu\" penalty value {0.9}\n  %       'r' followed by \"r\" penalty shrink factor {0.9}\n  % Outputs:\n  %   Q  #V by dim list of new mesh vertex positions\n  %\n\n  % default values\n  max_iter = 100;\n  mu = 0.9;\n  r = 0.9;\n  % Map of parameter names to variable names\n  params_to_variables = containers.Map( ...\n    {'MaxIter','mu','r'}, ...\n    {'max_iter','mu','r'});\n  v = 1;\n  while v <= numel(varargin)\n    param_name = varargin{v};\n    if isKey(params_to_variables,param_name)\n      assert(v+1<=numel(varargin));\n      v = v+1;\n      % Trick: use feval on anonymous function to use assignin to this workspace\n      feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n    else\n      error('Unsupported parameter: %s',varargin{v});\n    end\n    v=v+1;\n  end\n\n  % number of quads\n  m = size(F,1);\n  % number of vertices\n  n = size(V,1);\n  dim = 3;\n  T = [F(:,[1 2 3]);F(:,[1 3 4])];\n  N = normalizerow(normals(V,T));\n  % Initial guess for N\n  N = 0.5*(N(1:m,:)+N(m+1:end,:));\n  A = doublearea(V,T);\n  % A sort of barycentric massmatrix for quad meshes\n  M = repdiag(sparse(T(:),T(:),0.25*repmat(A,3,1),n,n),dim);\n  E = [];\n\n  % nsp = 3;\n  % subplot(1,nsp,1);\n  % BC = barycenter(V,F);\n  % trisurf(F,V(:,1),V(:,2),V(:,3));\n  % hold on;\n  % quiver3(BC(:,1),BC(:,2),BC(:,3),N(:,1),N(:,2),N(:,3));\n  % hold off;\n\n  % \"corner\" incidence\n  C = sparse(F(:),repmat(1:m,1,4)',1,n,m);\n\n  D = zeros(m,1);\n\n  Q = V;\n  iter = 1;\n  while true\n\n    % LOCAL\n    for ni = 1:m\n      Qn = Q(F(ni,:),:);\n      Mn = mean(Qn,1);\n      Qnc = bsxfun(@minus,Qn,Mn);\n      [EV,ED] = eig(Qnc'*Qnc);\n      [~,mi] = min(diag(ED));\n      N(ni,:) = EV(:,mi);\n      D(ni) = -Mn*N(ni,:)';\n    end\n\n    % LOCAL\n    for v = 1:n\n      % faces incident on v\n      J = find(C(v,:));\n      NJ = N(J,:);\n      DJ = D(J);\n      AJ = mu*eye(3) + (1-mu)*(NJ'*NJ);\n      bJ = mu*V(v,:)' - (1-mu)*NJ'*DJ;\n      Q(v,:) = AJ\\bJ;\n    end\n\n    % GLOBAL\n    %% \"corner\" incidence for each dimension with Nj\n    %This is wrong becase D should be scalar...\n    %CN = sparse( ...\n    %  reshape(bsxfun(@plus,F(:),(0:dim-1)*n),dim*m*4,1), ...\n    %  reshape(bsxfun(@plus,repmat((1:m)',4,1),(0:dim-1)*m),dim*m*4,1), ...\n    %  reshape(repmat(N,4,1),4*m*dim,1), ...\n    %  n*dim,m);\n    %% \u03bc \u2016P-Q\u2016\u00b2 + (1-\u03bc)\u2211_ij(n_j*q_i-d_j)\u00b2\n    %% Identity\n    %I = repdiag(speye(m,m),dim);\n    %H = [          mu*M        (1-mu)*CN; ...\n    %          (1-mu)*CN'       (1-mu)*I];\n    %l = [-mu*2*M*V(:);zeros(m*dim,1)];\n    %QD = min_quad_with_fixed(H,l,[],[]);\n    %Q = reshape(QD(1:n*dim),n,dim);\n    %D = reshape(QD(n*dim+1:end),m,dim);\n    %% (1-\u03bc)\u2211_ij(n_j*q_i-d_j)\u00b2\n    %% \u2016n_i\u2016\u00b2 = 1\n    %% \n    %CQ = sparse( ...\n    %  reshape(bsxfun(@plus,F(:),(0:dim-1)*n),dim*m*4,1), ...\n    %  reshape(bsxfun(@plus,repmat((1:m)',4,1),(0:dim-1)*m),dim*m*4,1), ...\n    %  reshape(Q(F(:),:),m*dim*4,1), ...\n    %  n*dim,m*dim);\n    %%H = (1-mu)*diag(sum(CQ'.^2,2));\n    %%l = (1-mu)*-2*diag(sum(CQ',2))*D(:);\n    %%% min N'HN - 2N'l\n    %%% \u2016N\u2016\u00b2 = m\n\n    %subplot(1,nsp,2);\n    %BC = barycenter(Q,F);\n    %trisurf(F,Q(:,1),Q(:,2),Q(:,3));\n    %hold on;\n    %quiver3(BC(:,1),BC(:,2),BC(:,3),N(:,1),N(:,2),N(:,3));\n    %hold off;\n\n    %NT = normalizerow(normals(Q,T));\n    %e = sum(sum((NT(1:m,:)-NT(m+(1:m),:)).^2,2));\n    %E = [E(:);e];\n    %subplot(1,nsp,3);\n    %loglog(E);\n    iter = iter+1;\n    if iter>max_iter\n      break;\n    end\n\n    mu = r*mu;\n  end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/planarize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.550609808833512}}
{"text": "function  [im_out, par] = SC_Sigma_1AG(par)\nim_out    =   par.nim;\n% parameters for noisy image\n[h,  w, ch]      =  size(im_out);\npar.h = h;\npar.w = w;\npar.ch = ch;\npar = SearchNeighborIndex( par );\nfor ite  =  1 : par.outerIter\n    %     % iterative regularization\n    im_out = im_out+par.delta*(par.nim - im_out);\n    % image to patches and estimate local noise variance\n    Y = Image2PatchNew( im_out, par );\n    % estimation of noise variance\n    dif = mean( mean( mean( (par.nim-im_out).^2 ) ) );\n    par.sigma = sqrt( abs( par.nSig^2 - dif ) );\n    % estimation of noise variance\n    if mod(ite-1, par.innerIter)==0\n        par.nlsp = par.nlsp - par.nlspgap;\n        % searching  non-local patches\n        blk_arr = Block_Matching( Y, par );\n    end\n    % Weighted Sparse Coding\n    Y_hat = zeros(par.ps2ch, par.maxrc, 'single');\n    W_hat = zeros(par.ps2ch, par.maxrc, 'single');\n    for i = 1:par.lenrc\n        index = blk_arr(:, i);\n        nlY = Y( : , index );\n        DC = mean(nlY, 2);\n        nDCnlY = bsxfun(@minus, nlY, DC);\n        % update D and S\n        [D, ~, ~] = svd( full(nDCnlY), 'econ' );\n        % update C by soft thresholding\n        B = D' * nDCnlY;\n        C = sign(B) .* max( abs(B) -  par.lambda*par.sigma^2, 0 );\n        % update Y\n        nDCnlYhat = D * C;\n        % add back DC components\n        nlYhat = bsxfun(@plus, nDCnlYhat, DC);\n        % aggregation\n        Y_hat(:, index) = Y_hat(:, index) + nlYhat;\n        W_hat(:, index) = W_hat(:, index) + ones(par.ps2ch, par.nlsp);\n    end\n    % Reconstruction\n    im_out = PGs2Image(Y_hat, W_hat, par);\n    % calculate the PSNR and SSIM\n    PSNR =   csnr( im_out*255, par.I*255, 0, 0 );\n    SSIM      =  cal_ssim( im_out*255, par.I*255, 0, 0 );\n    fprintf('Iter %d : PSNR = %2.4f, SSIM = %2.4f\\n', ite, PSNR, SSIM);\n    par.PSNR(ite, par.image) = PSNR;\n    par.SSIM(ite, par.image) = SSIM;\nend\nreturn;\n\n", "meta": {"author": "csjunxu", "repo": "TWSC-ECCV2018", "sha": "5e23808ba916885de66541119784c5b3e68a607a", "save_path": "github-repos/MATLAB/csjunxu-TWSC-ECCV2018", "path": "github-repos/MATLAB/csjunxu-TWSC-ECCV2018/TWSC-ECCV2018-5e23808ba916885de66541119784c5b3e68a607a/WSCandSC_notoptimized/SC_Sigma_1AG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5506098071221992}}
{"text": "function [Y_pred, loglikelihoodX] = LDApredict(model,Gamma,X,classification,intercept)\n% For an inferred LDA model and state timecourses, computes the\n% likelihood manifold in X space and computes the likelihood function for\n% each class of labels.\nif nargin<4\n    classification=true;\nend\nif nargin<5\n    intercept=true;\nend\n[T2,K] = size(Gamma);\n[T,nDimX] = size(X);\nnDimY = size(model.state(1).W.Mu_W,2)-nDimX;\nbetas_mu = cell(K,1);\nbetas_sigma = cell(K,1);\nfor k = 1:K\n    betas_mu{k} = model.state(k).W.Mu_W((nDimX+1):end,1:nDimX);\n    if strcmp(model.train.covtype,'full') || strcmp(model.train.covtype,'uniquefull') ...\n            || strcmp(model.train.covtype,'sharedfull')\n        S = model.train.S==1;\n        betas_sigma{k} = model.state(k).W.S_W(logical(S(:)),logical(S(:)));\n    else\n        betas_sigma{k} = model.state(k).W.S_W(1:nDimX,(nDimX+1):end,(nDimX+1):end); \n    end\nend\n\n% Iterate through labels, noting that the distribution in x space can be\n% computed as a sum for each condition:\nif intercept\n    numconds = size(betas_mu{1},1)-1;\nelse\n    numconds = size(betas_mu{1},1);\nend\nbetamu_givenY = zeros(numconds,K,nDimX);\nbetasig_givenY = zeros(numconds,K,nDimX,nDimX);\nfor testcond = 1:numconds\n    % compute each state's distribution in x space - assuming intercept has\n    % been used\n    for k=1:K\n        if intercept %account for mean term in generative model:\n            %betamu_givenY(testcond,k,:) = betas_mu{k}(1,:) + betas_mu{k}(1 + testcond,:);\n            betamu_givenY(testcond,k,:) = betas_mu{k}(1 + testcond,:);\n        else\n            betamu_givenY(testcond,k,:) = betas_mu{k}(testcond,:);\n        end\n        if strcmp(model.train.covtype,'full') || strcmp(model.train.covtype,'uniquefull') || ...\n            strcmp(model.train.covtype,'sharedfull')\n            betasig_givenY(testcond,k,:,:) = betas_sigma{k}([1:nDimY:nDimY*nDimX],[1:nDimY:nDimY*nDimX])+...\n                betas_sigma{k}([testcond:nDimY:nDimY*nDimX],[testcond:nDimY:nDimY*nDimX]);\n        else % Naive bayes classifier - just take uncertainty on each channel\n            betasig_givenY(testcond,k,:,:) = diag(betas_sigma{k}(:,testcond + 1,testcond + 1)) + ...\n                diag(betas_sigma{k}(:,1,1)) + 2*diag(betas_sigma{k}(:,1,testcond + 1));\n        end\n    end\nend\n\n% iterate through time, computing likelihood of X given Gamma:\nif isfield(model,'Omega')\n    if isfield(model.Omega,'pseudomean')\n        CovMat = model.Omega.pseudomean(1:nDimX,1:nDimX);\n    elseif strcmp(model.train.covtype,'uniquediag') || ...\n           strcmp(model.train.covtype,'shareddiag')  % Naive Bayes case\n        prec = diag(model.Omega.Gam_shape ./ model.Omega.Gam_rate(1:nDimX));\n        CovMat = inv(prec);\n    else % shared full covariance matrix\n        prec = model.Omega.Gam_shape * model.Omega.Gam_irate(1:nDimX,1:nDimX);\n        CovMat = inv(prec);\n    end\nelse\n    if strcmp(model.train.covtype,'diag')\n        for k=1:K\n            prec = diag(model.state(k).Omega.Gam_shape ./ model.state(k).Omega.Gam_rate(1:nDimX));\n            CovMat(:,:,k) = inv(prec);\n        end\n    else % statewise full covariance\n        for k=1:K\n            prec = model.state(k).Omega.Gam_shape * model.state(k).Omega.Gam_irate(1:nDimX,1:nDimX);\n            CovMat(:,:,k) = inv(prec);\n        end\n    end\nend\n\n% remove intercept from data if necessary:\nif intercept\n    for k=1:K\n        X = X - Gamma(:,k) * betas_mu{k}(1,:);\n    end\n    Y_pred = zeros(T,nDimY-1);\nelse\n    Y_pred = zeros(T,nDimY);\nend\nloglikelihoodX = zeros(size(Y_pred));\nif T==T2\n    for t=1:T\n        CovMat_t = sum(CovMat .* repmat(permute(Gamma(t,:),[3,1,2]),nDimX,nDimX,1),3);\n        if classification\n            for testcond = 1:numconds\n                mu = sum(squeeze(betamu_givenY(testcond,:,:)) .*repmat(Gamma(t,:)',1,nDimX));\n                mu_rec(testcond,t,:) = mu;\n                S = CovMat_t + squeeze(sum(betasig_givenY(testcond,:,:,:).*repmat(permute(Gamma(t,:)',[3,1,2]),1,1,nDimX,nDimX),2));\n                loglikelihoodX(t,testcond) = -0.5*log(det(S)) -0.5 * (X(t,:) - mu) * inv(S) * (X(t,:) - mu)';\n            end\n            m = max(loglikelihoodX(t,:),[],2);\n            Y_pred(t,:) = loglikelihoodX(t,:)==m;\n            if sum(Y_pred(t,:))>1\n                warning(['Equal scores achieved for multiple classes, t=',int2str(t),'\\n\\n']);\n                a = find(Y_pred(t,:));\n                Y_pred(t,a) = 0;\n                Y_pred(t,a(randi(length(a)))) = 1; %randomly silence all but one of these entries \n            end\n        else\n            betas_t = permute(sum(repmat(Gamma(t,:),[numconds,1,nDimX]).* betamu_givenY,2),[1,3,2]);\n            \n            %alternative implementation:\n            if ~intercept\n                sigma_Y = inv(inv(eye(nDimY)) + betas_t * inv(CovMat_t) * betas_t');\n            else\n                sigma_Y = inv(inv(eye(nDimY-1)) + betas_t * inv(CovMat_t) * betas_t');\n            end\n            betas_backwardmodel = inv(CovMat_t) * betas_t' * sigma_Y;\n            Y_pred(t,:) = X(t,:)*betas_backwardmodel;\n        end\n    end\nelse\n%implies Gamma invariant, so collapse over time:\n    for testcond = 1:numconds\n        mu = squeeze(betamu_givenY(testcond,:,:))';\n        mu_rec(testcond,:) = mu;\n        sig = CovMat + squeeze(betasig_givenY(testcond,:,:,:));\n        loglikelihoodX(:,testcond) = -0.5 * log(det(sig)) -0.5 * sum(((X-repmat(mu,T,1))*inv(sig)).*(X-repmat(mu,T,1)),2);\n    end\n    m = max(loglikelihoodX(:,:),[],2);\n    Y_pred = loglikelihoodX(:,:)==repmat(m,1,numconds);\nend\nif numconds==2 && all(Y_pred(:,1) == 1-Y_pred(:,2))\n    % binary output:\n    Y_pred = Y_pred(:,1);\nend\nend", "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/task/utils/LDApredict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5505676776469173}}
{"text": "function [W] = MW2W(MW)\n% Convert power from megawatts to watts. \n% Chad A. Greene 2012\nW = MW*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/MW2W.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5505073156455234}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2017 Lime Microsystems Ltd.\n%\n% Licensed under the Apache License, Version 2.0 (the 'License');\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n%\n%    http://www.apache.org/licenses/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an 'AS IS' BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nfunction NumptyGraphs(fpltname,iqDataTx,iqDataRxRaw,iqDataRx,binData,din,dout,FSR,osr,msgLen,saveGraphs)\n  %\n  %   D I S P L A Y   G R A P H I C A L   S U M M A R Y\n  %\n  subplot(2,3,1);\n  plot(iqDataTx(1:((msgLen+1)*osr)),'b');\n  xlabel('Time');\n  ylabel('Level');\n  title('Filtered BPSK Message');\n  grid on;\n  subplot(2,3,2);\n  plot(binData,'go',dout,'rx-');\n  legend('transmitted','received');\n  xlabel('Time');\n  ylabel('Level');\n  title('Binary Message');\n  grid on;\n  subplot(2,3,3);\n  fsc=FSR*((-(length(iqDataRx)-1)/2):((length(iqDataRx)-1)/2))/length(iqDataRx);\n  fftr=fftshift(mag2db(abs(fft(iqDataTx)/length(iqDataTx))+1e-5));\n  plot(fsc,fftr);\n  grid on;\n\ttitle('Spectrum of RRC Filtered Tx Signal');\n\txlabel('Frequency MHz');\n\tylabel('Level (dB)');\n\taxis('tight');\n  subplot(2,3,4);\n  fftr=fftshift(mag2db(abs(fft(iqDataRxRaw)/length(iqDataRxRaw))+1e-5));\n  plot(fsc,fftr);\n  grid on;\n\ttitle('Spectrum of Raw Rx Signal');\n\txlabel('Frequency MHz');\n\tylabel('Level (dB)');\n\taxis('tight');\n  subplot(2,3,5);\n  fftr=fftshift(mag2db(abs(fft(iqDataRx)/length(iqDataRx))+1e-5));\n  plot(fsc,fftr);\n  grid on;\n\ttitle('Spectrum of RRC Filtered Rx Signal');\n\txlabel('Frequency MHz');\n\tylabel('Level (dB)');\n\taxis('tight');\n  subplot(2,3,6);\n \tplot(iqDataRx,'b-',din,'rx');\n\tgrid on;\n\ttitle('Trajectory of RRC Filtered RX signal');\n\txlabel('I level');\n\tylabel('Q level');\n  legend('Traj','Locked');\n  if saveGraphs\n    print( fpltname, '-dpng' );\n  end\nend\n", "meta": {"author": "myriadrf", "repo": "LimeSDR_Workshop", "sha": "c3bfe944a89836d6eadc67a0352f2b5b7e1727a4", "save_path": "github-repos/MATLAB/myriadrf-LimeSDR_Workshop", "path": "github-repos/MATLAB/myriadrf-LimeSDR_Workshop/LimeSDR_Workshop-c3bfe944a89836d6eadc67a0352f2b5b7e1727a4/octave/NumptyDemo/NumptyGraphs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5505073132105557}}
{"text": "function [vol, labels] = imVolume(img, varargin)\n% Volume of regions within a 3D binary or label image.\n%\n%   V = imVolume(IMG);\n%   Compute volume of the image. IMG is either a binary image, or a label\n%   image. In the case of a label image, the area of each labeled area is\n%   returned in a column vector with as many elements as the number of\n%   labels.\n%\n%   V = imVolume(IMG, SCALE);\n%   Also specify scale of image tile. SCALE si a 1-by-3 array, containing\n%   voxel size in each direction.\n%   \n%   See Also\n%   imVolumeDensity, imSurfaceArea, imMeanBreadth\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% Created: 2010-01-15,    using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRAE - Cepia Software Platform.\n\n\n%% Parse input arguments\n\n% check image dimension\nif ndims(img) ~= 3\n    error('first argument should be a 3D binary or label image');\nend\n\n% the labels to compute\nlabels = [];\n\n% default spatial calibration\ndelta = [1 1 1];\n\n% parse parameter name-value pairs\nwhile ~isempty(varargin)\n    var1 = varargin{1};\n    varargin(1) = [];\n    \n    if isnumeric(var1)\n        % option can be number of directions, spatial calibration, or list\n        % of labels\n        if all(size(var1) == [1 3])\n            % spatial calibration\n            delta = var1;\n        elseif ~isscalar(var1) && size(var1, 2) == 1\n            % list of labels to compute\n            labels = var1;\n        else\n            error('Unable to parse input argument');\n        end\n    else\n        error('Expect numeric input only');\n    end\nend\n\n\n%% Process label images\n\n% in case of a label image, return a vector with a set of results\nif ~islogical(img)\n    % extract labels if necessary (considers 0 as background)\n    if isempty(labels)\n        labels = imFindLabels(img);\n    end\n    \n    % allocate memory\n    vol = zeros(length(labels), 1);\n    \n    % iterate over labels\n    for i = 1:length(labels)\n        vol(i) = imVolume(img==labels(i), delta);\n    end\n    return;\nend\n\n\n%% Process binary images\n\n% in case of binary image, compute only one label...\nlabels = 1;\n\n% compute area, multiplied by image resolution\nvol = sum(img(:)) * prod(delta);\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMinkowski/imVolume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5505073108185159}}
{"text": "function b = isint(x)\n%ISINT  True for integers.\n%\n%   ISINT(X) returns 1's where the elements of X are integers and 0's where\n%   they are not.  For example, ISINT([ 2e9 pi 3+5i NaN ]) is [ 1 0 1 0 ].\n%\n%   See also ISEVEN, ISODD.\n\n%   Author:      Peter J. Acklam\n%   Time-stamp:  2003-04-12 14:30:59 +0200\n%   E-mail:      pjacklam@online.no\n%   URL:         http://home.online.no/~pjacklam\n\n   error(nargchk(1, 1, nargin));\n   if ~isnumeric(x)\n      error('Argument must be a numeric array.');\n   end\n\n   cls = class(x);                      % class of input argument\n   if isempty(x)\n      b = feval(cls, x);                % return empty array of same class\n   else\n      switch cls\n         case 'double'\n            b = x == round(x);\n         case 'single'\n            % \"mod\" is not defined for class \"single\"; so convert input to\n            % double, compare, and convert back\n            d = double(x);\n            b = single(d == round(d));\n         case {'int8', 'int16', 'int32', 'int64', ...\n               'uint8', 'uint16', 'uint32', 'uint64'}\n            % return an array of ones of the same class as input argument\n            b = logical(repmat(feval(cls, 1), size(x)));\n         otherwise\n            error('Argument is of unrecognized class.');\n      end\n   end\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/lib/util/matutil/isint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5505073059915084}}
{"text": "function a = cosh(a)\n%COSH         Gradient hyperbolic cosine cosh(a)\n%\n\n% written  10/16/98     S.M. Rump\n% modified 10/14/00     S.M. Rump  use Tony's trick\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/28/08     S.M. Rump  check for rounding to nearest improved\n% modified 10/08/08     S.M. Rump  improved sparse multiplication: not using intval data type\n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  e = 1e-30;\n  if 1+e==1-e                           % fast check for rounding to nearest\n    rndold = 0;\n  else\n    rndold = getround;\n    setround(0)\n  end\n\n  N = getappdata(0,'INTLAB_GRADIENT_NUMVAR');\n\n  ax = sinh(a.x(:));\n  a.x = cosh(a.x);\n  if issparse(a.dx)\n    sizeax = size(a.dx,1);\n    [ia,ja,sa] = find(a.dx);\n    % take care of scalar a.x: cures Matlab V6.0 bug\n    % a=7; i=[1 1]; x=a(i), b=sparse(a); y=b(i)  yields row vector x but column vector y\n    ax = ax(ia);    \n    if isa(a.x,'intval')\n      adx = times(ax(:),sa(:),0);\n      if adx.complex\n        a.dx = intval( sparse(ia,ja,adx.mid,sizeax,N) , sparse(ia,ja,adx.rad,sizeax,N) , 'midrad' );\n      else\n        a.dx = intval( sparse(ia,ja,adx.inf,sizeax,N) , sparse(ia,ja,adx.sup,sizeax,N) , 'infsup' );\n      end\n    else\n      a.dx = sparse(ia,ja,ax(:).*sa(:),sizeax,N);\n    end\n  else\n    a.dx = a.dx .* ax(:,ones(1,N));\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/gradient/@gradient/cosh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5504600108998018}}
{"text": "% Fit a piece-wise linear regression model.\n% Here is the model\n%\n%  X \\\n%  | |\n%  Q |\n%  | /\n%  Y\n%\n% where all arcs point down.\n% We condition everything on X, so X is a root node. Q is a softmax, and Y is a linear Gaussian.\n% Q is hidden, X and Y are observed.\n\nX = 1;\nQ = 2;\nY = 3;\ndag = zeros(3,3);\ndag(X,[Q Y]) = 1;\ndag(Q,Y) = 1;\nns = [1 2 1]; % make X and Y scalars, and have 2 experts\ndnodes = [2];\nonodes = [1 3];\nbnet = mk_bnet(dag, ns, 'discrete', dnodes, 'observed', onodes);\n\nIRLS_iter = 10;\nclamped = 0;\n\nbnet.CPD{1} = root_CPD(bnet, 1);\n\nif 0\n  % start with good initial params\n  w = [-5 5];  % w(:,i) is the normal vector to the i'th decisions boundary\n  b = [0 0];  % b(i) is the offset (bias) to the i'th decisions boundary\n  \n  mu = [0 0];\n  sigma = 1;\n  Sigma = repmat(sigma*eye(ns(Y)), [ns(Y) ns(Y) ns(Q)]);\n  W = [-1 1];\n  W2 = reshape(W, [ns(Y) ns(X) ns(Q)]);\n\n  bnet.CPD{2} = softmax_CPD(bnet, 2, w, b,  clamped, IRLS_iter);\n  bnet.CPD{3} = gaussian_CPD(bnet, 3, mu, Sigma, W2);\nelse\n  % start with rnd initial params\n  rand('state', 0);\n  randn('state', 0);\n  bnet.CPD{2} = softmax_CPD(bnet, 2, 'clamped', clamped, 'max_iter', IRLS_iter);\n  bnet.CPD{3} = gaussian_CPD(bnet, 3);\nend\n\n\n\nload('/examples/static/Misc/mixexp_data.txt', '-ascii');        \n% Just use 1/10th of the data, to speed things up\ndata = mixexp_data(1:10:end, :);\n%data = mixexp_data;\n \n%plot(data(:,1), data(:,2), '.')\n\n\ns = struct(bnet.CPD{2}); % violate object privacy\n%eta0 = [s.glim.b1; s.glim.w1]';\neta0 = [s.glim{1}.b1; s.glim{1}.w1]';\ns = struct(bnet.CPD{3}); % violate object privacy\nW = reshape(s.weights, [1 2]);\ntheta0 = [s.mean; W]';\n\n%figure(1)\n%mixexp_plot(theta0, eta0, data);\n%suptitle('before learning')\n\nncases = size(data, 1);\ncases = cell(3, ncases);\ncases([1 3], :) = num2cell(data');\n\nengine = jtree_inf_engine(bnet);\n\n% log lik before learning\nll = 0;\nfor l=1:ncases\n  ev = cases(:,l);\n  [engine, loglik] = enter_evidence(engine, ev);\n  ll = ll + loglik;\nend\n\n% do learning\nmax_iter = 5;\n[bnet2, LL2] = learn_params_em(engine, cases, max_iter);\n\ns = struct(bnet2.CPD{2});\n%eta2 = [s.glim.b1; s.glim.w1]';\neta2 = [s.glim{1}.b1; s.glim{1}.w1]';\ns = struct(bnet2.CPD{3});\nW = reshape(s.weights, [1 2]);\ntheta2 = [s.mean; W]';\n\n%figure(2)\n%mixexp_plot(theta2, eta2, data);\n%suptitle('after learning')\n\nfprintf('mixexp2: loglik before learning %f, after %d iters %f\\n', ll, length(LL2),  LL2(end));\n\n\n\n", "meta": {"author": "beckel", "repo": "nilm-eval", "sha": "83a2cd5fb911299cc267bd9998636934af781915", "save_path": "github-repos/MATLAB/beckel-nilm-eval", "path": "github-repos/MATLAB/beckel-nilm-eval/nilm-eval-83a2cd5fb911299cc267bd9998636934af781915/Matlab/lib/bnt/BNT/examples/static/mixexp2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5504600099446888}}
{"text": "function conv2pool()\n    global config mem;\n    curr_layer_idx = config.misc.current_layer;\n    mem.layer_inputs{curr_layer_idx} = reshape(accumarray(mem.pooling_matrix{curr_layer_idx}, mem.activations{curr_layer_idx-1}(:), ...\n                        [size(mem.activations{curr_layer_idx-1},1)*size(mem.activations{curr_layer_idx-1},2)/4, 1]), size(mem.activations{curr_layer_idx-1}, 2)/4, size(mem.activations{curr_layer_idx-1}, 1));\nend\n\n", "meta": {"author": "jimmy-ren", "repo": "vcnn_double-bladed", "sha": "a4de90e845875f6e30632f2e879d3afb81c0ebc1", "save_path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed", "path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed/vcnn_double-bladed-a4de90e845875f6e30632f2e879d3afb81c0ebc1/layers_adapters/conv2pool.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5504600099446887}}
{"text": "function C = addlongerror(C,err,exponent)\n%ADDLONGERROR Add error to long number\n%\n%  C = addlongerror(A,err,exponent)\n%\n%Error term of C is updated by err. Third argument optional, default 0.\n%If exponent is specified, error term is updated by err*10^exponent\n%\n%Input C, err and exponent may be column vectors\n%\n\n% written  12/30/98     S.M. Rump\n% modfied  02/09/00     S.M. Rump  rounding unchanged after use\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% modified 01/29/10     S.M. Rump  only warning if no interval arithmetic \n% modified 08/26/12     S.M. Rump  global variables removed\n%\n\n  INTLAB_LONG_BETA = getappdata(0,'INTLAB_LONG_BETA');\n  INTLAB_LONG_ERROR = getappdata(0,'INTLAB_LONG_ERROR');\n  \n  if ~INTLAB_LONG_ERROR\n    warning('long arithmetic changed to interval arithmetic, see longinit')\n    INTLAB_LONG_ERROR = 1;\n  end\n\n  if any( err<0 )\n    error('negative error specified in addlongerror')\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 nargin==3\n    setround(1)\n    % 10^exponent = beta^(Ernd+Efrac)\n    E = exponent / log10(INTLAB_LONG_BETA);\n    Ernd = round(E);\n    Efrac = E - Ernd;\n    err = err .* INTLAB_LONG_BETA.^Efrac;\n    setround(0)                         % set rounding to nearest\n  else\n    Ernd = 0;\n  end\n  C.error = errorupdate( 1 , C.error , 0  , 1 , err , Ernd );\n  C.error = errornormalize(C.error);\n\n  C = normalize(C);\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/long/@long/addlongerror.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5504600056367326}}
{"text": "function [y n] = var_nan(x)\n\nfor ii=1:size(x,2)\n    tmp = x(:,ii);\n    tmp(isnan(tmp))=[];\n    y(ii)=var(tmp);\n    n(ii)=size(tmp,1);\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/var_nan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5504600056367325}}
{"text": "addpath('mex');\n\n% we provide two sequences \"car\" and \"table\"\n% example = 'table';\nexample = 'car';\n\n% load the two frames\nim1 = im2double(imread([example '1.jpg']));\nim2 = im2double(imread([example '2.jpg']));\n\n% im1 = imresize(im1,0.5,'bicubic');\n% im2 = imresize(im2,0.5,'bicubic');\n\n% set optical flow parameters (see Coarse2FineTwoFrames.m for the definition of the parameters)\nalpha = 0.012;\nratio = 0.75;\nminWidth = 20;\nnOuterFPIterations = 7;\nnInnerFPIterations = 1;\nnSORIterations = 30;\n\npara = [alpha,ratio,minWidth,nOuterFPIterations,nInnerFPIterations,nSORIterations];\n\n% this is the core part of calling the mexed dll file for computing optical flow\n% it also returns the time that is needed for two-frame estimation\ntic;\n[vx,vy,warpI2] = Coarse2FineTwoFrames(im1,im2,para);\ntoc\n\nfigure;imshow(im1);figure;imshow(warpI2);\n\n\n\n% output gif\nclear volume;\nvolume(:,:,:,1) = im1;\nvolume(:,:,:,2) = im2;\nif exist('output','dir')~=7\n    mkdir('output');\nend\nframe2gif(volume,fullfile('output',[example '_input.gif']));\nvolume(:,:,:,2) = warpI2;\nframe2gif(volume,fullfile('output',[example '_warp.gif']));\n\n\n% visualize flow field\nclear flow;\nflow(:,:,1) = vx;\nflow(:,:,2) = vy;\nimflow = flowToColor(flow);\n\nfigure;imshow(imflow);\nimwrite(imflow,fullfile('output',[example '_flow.jpg']),'quality',100);\n", "meta": {"author": "qingsenyangit", "repo": "AHDRNet", "sha": "03d1329ff0e7dce8151dfbe685ff558110e262da", "save_path": "github-repos/MATLAB/qingsenyangit-AHDRNet", "path": "github-repos/MATLAB/qingsenyangit-AHDRNet/AHDRNet-03d1329ff0e7dce8151dfbe685ff558110e262da/GenerH5Data/Libraries/OpticalFlow/demoflow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5504599994185505}}
{"text": "function x = sb_solve(sysmat,vecb)\n\n% SB_SOLVE\n%\n% $Id$\n\n%scalen\ndisp('Scaling stiffness matrix...')\ndkond = 1./(sqrt(diag(sysmat)));\nvecb = vecb.*dkond;\n[indexi, indexj, s] = find(sysmat);\nsys_size = size(sysmat,1);\nclear sysmat;\ns = (s.*dkond(indexi)).*dkond(indexj);\ns(1) = 1;\ndisp('Preconditioning...')\nL = sparse(indexi,indexj,s,sys_size,sys_size,length(s));\n%partch\ntry\n    L = ichol(L);\ncatch\n    disp('Could not compute incomplete Cholesky-decompositon. Rescaling stiffness matrix...')\n    alpha = 0.5d-6;\n    alpha = alpha*8.d0;\n    alpha = 1 / (alpha + 1);\n    s = alpha*s;\n    dia = find(indexi == indexj);\n    s(dia) = (1./alpha)*s(dia);\n    s(dia) = sqrt(s(dia));\n    s(1) = 1;\n    L = sparse(indexi,indexj,s,sys_size,sys_size,length(s));\n    clear dia;\n    L = ichol(L);\nend\n%startvektor\ndisp('Finding startvector...')\nvecb_ = L \\ (-vecb);\nvecx = L' \\ vecb_;\nclear vecb_;\n%sonstiges\nsysmat = sparse(indexi,indexj,s,sys_size,sys_size,length(s));\nsysmat = sysmat + sysmat' - sparse(1:sys_size,1:sys_size,diag(sysmat),sys_size,sys_size,sys_size);\nclear indexi indexj s;\n%dprod = sysmat * vecx;\n%l\u00f6sen\ndisp('Solving equation system...')\n[x,fl,rr,it,rv]= pcg(sysmat,vecb,10e-9,5000,L,L',vecx);\n%fl\nrr\n%it\n%rescal\nx = x.*dkond;\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/simbio/sb_solve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5504550464698266}}
{"text": "function z = s2z4(S);\n\n% Z = s2z4(S)\n%\n% Scattering to Impedance transformation\n% only for N-by-4 matrix\n\n%d = (1 - S(:, 1)).*(1 - S(:, 4)) - S(:,2).* S(:, 3);\n\nfor i = 1:size(S,1)\n  d(i) = (1 - S(i, 1)).*(1 - S(i, 4)) - S(i,2).* S(i, 3);\n  while abs(d(i)) < 1e-8\n    fckindex = 1+round(rand*3);\n    S(i, fckindex) = S(i, fckindex)*(1+rand*1e-8);\n    d(i) = (1 - S(i, 1)).*(1 - S(i, 4)) - S(i,2).* S(i, 3);\n  end;\nend;\n\nd = rot90(d, 3);\n\n% at this point the I-S matrix should be non-singular\n\nz(:, 1) = ((1 + S(:, 1)).*(1 - S(:, 4)) + S(:,2).* S(:, 3))./d;\nz(:, 2) = 2* S(:,2)./d;\nz(:, 3) = 2* S(:,3)./d; \nz(:, 4) = ((1 - S(:, 1)).*(1 + S(:, 4)) + S(:,2).* S(:, 3))./d;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6080-s-parameter-toolbox-+-z-y-h-g-abcd-t/sbox/s2z4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5503237974273961}}
{"text": "c = 340;                    % Sound velocity (m/s)\nfs = 16000;                 % Sample frequency (samples/s)\nr = [2 1.5 3 ; 1 1.5 2];    % Receiver positions [x_1 y_1 z_1 ; x_2 y_2 z_2] (m)\ns = [2 3.5 2];              % Source position [x y z] (m)\nL = [5 4 6];                % Room dimensions [x y z] (m)\nbeta = 0.4;                 % Reverberation time (s)\nn = 4096;                   % Number of samples\nmtype = 'omnidirectional';  % Type of microphone\norder = -1;                 % -1 equals maximum reflection order!\ndim = 3;                    % Room dimension\norientation = 0;            % Microphone orientation (rad)\nhp_filter = 1;              % Enable high-pass filter\n\nh = rir_generator(c, fs, r, s, L, beta, n, mtype, order, dim, orientation, hp_filter);", "meta": {"author": "ZitengWang", "repo": "MASP", "sha": "c3dae1444b60213a1ae31b0a81906a03e729c7c6", "save_path": "github-repos/MATLAB/ZitengWang-MASP", "path": "github-repos/MATLAB/ZitengWang-MASP/MASP-c3dae1444b60213a1ae31b0a81906a03e729c7c6/Simulation/RIR-Generator/example_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118215, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5502904331213263}}
{"text": "function [doog_filters, texton_data] = cluster_learning_create_image_filters;\n\n% create pair data\nangle_step = 15;\nfilter_size = 5;\nsigma = 1.5;\nr = 0.25;\n\n% create DOOG filters\nnum_angles=180/angle_step;\ndoog_filters = zeros(filter_size, filter_size, num_angles);\nfor (theta=0:angle_step:180-angle_step)\n    doog_filters(:, :, theta/angle_step+1)=createDOOGFilter(sigma, r, theta, filter_size); \nend\n\n% load textons\nif 0\ntexton_data = load('D:\\Projects\\Tools\\textons\\unitex_6_1_2_1.4_2_32.mat');\nordered_textons = select_diverse_textons(texton_data.tsim, 12);\nnew_tims = cell(length(ordered_textons), 1);\nfor i = 1:length(new_tims)\n    new_tims{i} = texton_data.tim{ordered_textons(i)};\nend\ntexton_data.tim = new_tims;\nend\n\ntexton_data.tim = [];\n%num_textons = length(texton_data.tim);", "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/cluster_learning_create_image_filters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5502904316646794}}
{"text": "function [ output_data ] = deweightmem( input_data, weight_fun, oversample_rate, dim )\n%DEWEIGHTMEM Make complex SAR uniformly weighted in one dimension\n%\n%    output_data = deweightmem(input_data, weight_fun, oversample_rate, dim)\n%\n%       Parameter name    Description\n% \n%       input_data        Array of complex values to deweight\n%       weight_fun        Description of weighting applied.  Either a\n%                            function handle to a function that takes a\n%                            single argument (number of elements) and\n%                            produces the weighting to apply, or a vector\n%                            that is the weighting function sampled.\n%       oversample_rate   Amount of sampling beyond the ImpRespBW in the\n%                            processing dimension. (Default is Nyquist\n%                            sampling = 1).\n%       dim               Dimension over which to perform deweighting.\n%                            Default is 1.\n%       output_data       INPUT_DATA with normalization applied\n%\n% This implementation assumes that the data has already been \"deskewed\" and\n% that the frequency support is centered.\n%\n% Author: Wade Schwartzkopf, NGA/R\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////\n\nif ~exist('oversample_rate','var')\n    oversample_rate = 1;\nend\nif ~exist('dim','var')\n    dim = 1;\nend\n\ndata_size = size(input_data,dim);\nweight_size = round(data_size/oversample_rate); % Weighting only valid across ImpRespBW\nif ~exist('weight_fun','var')||isempty(weight_fun) % No weighting passed in.  Do nothing.\n    output_data = input_data;\n    return;\nelseif isa(weight_fun, 'function_handle')\n    weighting = weight_fun(weight_size);\nelseif isvector(weight_fun)\n    weighting = interpft(weight_fun,weight_size);\nend\n% weighting = weighting * sqrt(mean(1./weighting.^2)); % We want total power maintained\nweight_zp = ones(data_size,1); % Don't scale outside of ImpRespBW\nweight_zp(floor((data_size-weight_size)/2)+(1:weight_size)) = weighting;\nif dim==2\n    weight_zp = weight_zp.';\nend\n\n% Divide out weighting in spatial frequency domain\noutput_data = fftshift(fft(input_data,[],dim),dim);\noutput_data = bsxfun(@rdivide,output_data,weight_zp);\noutput_data = ifft(ifftshift(output_data,dim),[],dim);\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/Processing/normalize_sicd/deweight/deweightmem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.5502785119684312}}
{"text": "%% brute_force_tune\n% Code to test the performance of various tuning parameters\n% Works sorta like RANSAC I guess?\n% Adam Werries 2016, see Apache 2.0 license.\n\nk_max = 40;\n% Specify ranges\ninit_b_a_unc = linspace(10,3000,100);\ninit_b_g_unc = linspace(0,500,100);\n% Repeat arrays\ninit_b_a_unc = repmat(init_b_a_unc, [1 k_max]);\ninit_b_g_unc = repmat(init_b_g_unc, [1 k_max]);\n% Generate random selections of each vector\nnum_items = length(init_b_a_unc);\nba_i = randperm(num_items);\nbg_i = randperm(num_items);\nrms_error_filter = zeros(1,num_items);\nmax_error_filter = zeros(1,num_items);\nparfor i = 1:num_items\n    fprintf('Iteration: %d, aBiasUnc: %08.3f, gBiasUnc: %08.3f\\n', i, init_b_a_unc(ba_i(i)), init_b_g_unc(bg_i(i)));\n    temp_conf = LC_KF_config;\n    temp_conf.init_b_a_unc = init_b_a_unc(ba_i(i)) * mug_to_mps2;\n    temp_conf.init_b_g_unc = init_b_g_unc(bg_i(i)) * deg_to_rad / 3600;\n    [out_profile,out_IMU_bias_est,out_KF_SD] = Loosely_coupled_INS_GNSS(init_cond, filter_time, epoch, lla, gps, imu, temp_conf, est_IMU_bias);\n    xyz = out_profile(:,2:4);\n    llh = ecef2lla(xyz);\n    [x,y] = deg2utm(llh(:,1),llh(:,2));\n    x = x-min_x;\n    y = y-min_y;\n    \n    distance = ((ground_truth_full(:,1)-x).^2 + (ground_truth_full(:,2)-y).^2).^0.5;\n    rms_error_filter(i) = rms(distance);\n    max_error_filter(i) = max(distance);\nend\n\n[minmax, i] = min(max_error_filter);\nfprintf('\\nBest max: %08.3f, rms is %08.3f\\n', minmax, rms_error_filter(i));\nfprintf('Best iteration for max: %d, aBiasUnc: %08.3f, gBiasUnc: %08.3f\\n', i, init_b_a_unc(ba_i(i)), init_b_g_unc(bg_i(i)));\n[minrms, i] = min(rms_error_filter);\nfprintf('Best rms: %08.3f, max is %08.3f\\n', minrms, max_error_filter(i));\nfprintf('Best iteration for rms: %d, aBiasUnc: %08.3f, gBiasUnc: %08.3f\\n', i, init_b_a_unc(ba_i(i)), init_b_g_unc(bg_i(i)));\n", "meta": {"author": "awerries", "repo": "kalman-localization", "sha": "558ca7fae1779aa71da61ec4829299bbbdbf62ff", "save_path": "github-repos/MATLAB/awerries-kalman-localization", "path": "github-repos/MATLAB/awerries-kalman-localization/kalman-localization-558ca7fae1779aa71da61ec4829299bbbdbf62ff/MATLAB/Tuning/tune_bias_unc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5502785076786305}}
{"text": "function pass = test_iszero( pref ) \n\n% Grab some preferences\nif ( nargin == 0 )\n    pref = chebfunpref();\nend\n\n% Test with function 1-1\nf = ballfun(ones(21,20,22));\ng = f-f;\npass(1) = iszero(g);\n\n% Test with function 10^-20\nf = ballfun(10^(-20));\npass(2) = (iszero(f) == 0);\n\n% Test with function 0\nf = ballfun(0);\npass(3) = iszero(f);\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/ballfun/test_iszero.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5502184609496582}}
{"text": "%% This file will be used to generate the simulation data of\n% the Belousov Zhabotinsky reaction.\n% Code By: K\n% Last Updated: 2019/06/24\n%% Clear all\nclose all;clear all;clc;\n%% Add path\n[fld_status, fld_msg, fld_msgID]=mkdir('Datas');\n[fld_status, fld_msg, fld_msgID]=mkdir('Figures');\naddpath('Datas')\naddpath('Figures')\naddpath('Functions')\n%% Define parameters for the simulation\n% Define diffusion rate\nDx=0.01;Dz=0.01;Ds=1;Du=1;\n\n% Others\nq=0.1;f=1.5;ksi=0.3;alpha=0.3;beta=0.26;gama=0.4;ksi2=1.5;ksi3=0.003;phi=0;\n\n% Define the time horizon\ndt=0.001;T=1;\ntspan=0:dt:T;\n\n% Define the spatial domain\nL=20; % Total length of each dimension\nn=128; % Discretization point of each dimension\nN=n*n; % Total points used, n^2\n\nx2=linspace(-L/2,L/2,n+1); x=x2(1:n);\ny=x;dx=x(2)-x(1);\n\nkx=(2*pi/L)*[0:(n/2-1) -n/2:-1];\nky=kx;\n\n% Get n-dimensional grid\n[X,Y]=meshgrid(x,y);\n[KX,KY]=meshgrid(kx,ky);\nK2=KX.^2+KY.^2; K22=reshape(K2,N,1);\nKx=reshape(KX,N,1);Ky=reshape(KY,N,1);Kxx=reshape(KX,N,1);Kyy=reshape(KY,N,1);\n\n% Create a time matrix\nr_t=zeros(n,n,length(tspan));r=zeros(n,n,length(tspan));r_x=zeros(n,n,length(tspan));r_xx=zeros(n,n,length(tspan));r_y=zeros(n,n,length(tspan));r_yy=zeros(n,n,length(tspan));\nz_t=zeros(n,n,length(tspan));z=zeros(n,n,length(tspan));z_x=zeros(n,n,length(tspan));z_xx=zeros(n,n,length(tspan));z_y=zeros(n,n,length(tspan));z_yy=zeros(n,n,length(tspan));\ns_t=zeros(n,n,length(tspan));s=zeros(n,n,length(tspan));s_x=zeros(n,n,length(tspan));s_xx=zeros(n,n,length(tspan));s_y=zeros(n,n,length(tspan));s_yy=zeros(n,n,length(tspan));\nu_t=zeros(n,n,length(tspan));u=zeros(n,n,length(tspan));u_x=zeros(n,n,length(tspan));u_xx=zeros(n,n,length(tspan));u_y=zeros(n,n,length(tspan));u_yy=zeros(n,n,length(tspan));\nr_lap=zeros(n,n,length(tspan));z_lap=zeros(n,n,length(tspan));s_lap=zeros(n,n,length(tspan));u_lap=zeros(n,n,length(tspan));\n%% Set a Guassian for the initial condition\nr0=cos(sqrt(X.^2+Y.^2)).^2+GaussianFilter(X,Y,0.05,0.05,0,0)+GaussianFilter(X,Y,1,0.01,0,0)+GaussianFilter(X,Y,0.01,1,0,0)+GaussianFilter(X,Y,0.25,0.25,5,5)+GaussianFilter(X,Y,0.25,0.25,5,-5)+GaussianFilter(X,Y,0.25,0.25,-5,5)+GaussianFilter(X,Y,0.25,0.25,-5,-5)+0.1;\nz0=sin(0.1*sqrt(X.^2+Y.^2)).^2+GaussianFilter(X,Y,0.05,0.01,0,0)+GaussianFilter(X,Y,0.25,0.25,5,5)+GaussianFilter(X,Y,0.25,0.25,5,-5)+GaussianFilter(X,Y,0.25,0.25,-5,5)+GaussianFilter(X,Y,0.25,0.25,-5,-5)+0.1;\ns0=sin(sqrt(X.^2+Y.^2)).^2+GaussianFilter(X,Y,0.5,0.5,0,5)+GaussianFilter(X,Y,0.5,0.5,5,0)+GaussianFilter(X,Y,0.5,0.5,0,-5)+GaussianFilter(X,Y,0.5,0.5,-5,0)+0.1;\nu0=cos(sqrt(X.^2+Y.^2)).^2+GaussianFilter(X,Y,0.5,0.01,0,0)+GaussianFilter(X,Y,0.01,0.5,0,0)+GaussianFilter(X,Y,0.25,0.25,5,5)+GaussianFilter(X,Y,0.25,0.25,5,-5)+GaussianFilter(X,Y,0.25,0.25,-5,5)+GaussianFilter(X,Y,0.25,0.25,-5,-5)+0.01;\n\n%% Plot the initial conditions\nfigure(1)\nsurf(x,y,r0)\nset(gca,'FontSize',18);\nset(gcf,'Position',[100 100 600 600]);\nset(gcf,'PaperPositionMode','auto');\nview(-18,35)\nbox('off')\naxis('off')\n\nfigure(2)\nsurf(x,y,z0)\nset(gca,'FontSize',18);\nset(gcf,'Position',[100 100 600 600]);\nset(gcf,'PaperPositionMode','auto');\nview(-18,35)\nbox('off')\naxis('off')\n\nfigure(3)\nsurf(x,y,s0)\nset(gca,'FontSize',18);\nset(gcf,'Position',[100 100 600 600]);\nset(gcf,'PaperPositionMode','auto');\nview(-18,35)\nbox('off')\naxis('off')\n\nfigure(4)\nsurf(x,y,u0)\nset(gca,'FontSize',18);\nset(gcf,'Position',[100 100 600 600]);\nset(gcf,'PaperPositionMode','auto');\nview(-18,35)\nbox('off')\naxis('off')\n%%\nclose all\n% Transfer the initial guess to fourier domain\nxzsu0t=[reshape(fft2(r0),1,N) reshape(fft2(z0),1,N) reshape(fft2(s0),1,N) reshape(fft2(u0),1,N)].';\n\ntic\nopts = odeset('RelTol',1e-12,'AbsTol',1e-13);\nNeedDev=0;\n[time,xzsusol]=ode45(@(time,xzsut)BZ_Reaction_PDE(time,xzsut,Kx,Kxx,Ky,Kyy,K22,n,N,Dx,Dz,Ds,Du,q,f,ksi,alpha,beta,gama,ksi2,ksi3,phi,NeedDev),tspan,xzsu0t,opts);\ntoc\n\n%% Extract values\n% After simulation, we extract the derivative\nNeedDev=1;\n\nfor pin=1:length(tspan)\n    % Get the derivative data\n    [~,r_t(:,:,pin),z_t(:,:,pin),s_t(:,:,pin),u_t(:,:,pin),r(:,:,pin),z(:,:,pin),s(:,:,pin),u(:,:,pin),r_x(:,:,pin),z_x(:,:,pin),s_x(:,:,pin),u_x(:,:,pin),r_y(:,:,pin),z_y(:,:,pin),s_y(:,:,pin),u_y(:,:,pin),r_xx(:,:,pin),z_xx(:,:,pin),s_xx(:,:,pin),u_xx(:,:,pin),r_yy(:,:,pin),z_yy(:,:,pin),s_yy(:,:,pin),u_yy(:,:,pin),r_lap(:,:,pin),z_lap(:,:,pin),s_lap(:,:,pin),u_lap(:,:,pin)]=...\n        BZ_Reaction_PDE(0,xzsusol(pin,:).',Kx,Kxx,Ky,Kyy,K22,n,N,Dx,Dz,Ds,Du,q,f,ksi,alpha,beta,gama,ksi2,ksi3,phi,NeedDev);\nend\n%% Test out whehter the derivative is correct here\nfor pin=2:length(tspan)\n    % Test out the zt (All time derivative tested, the Fourier derivative result matches the finite differences result)\n    %     u_t_dum(:,:,pin)=(u(:,:,pin)-u(:,:,pin-1))/dt;\n    %     figure(1)\n    %     clf\n    %     surf(x,y,u_t_dum(:,:,pin))\n    %     \n    %     figure(2)\n    %     clf\n    %     surf(x,y,u_t(:,:,pin))\n    %     \n    %     Dum=u_t_dum(:,:,pin)-u_t(:,:,pin);\n    %     norm(Dum(:))\n    \n    % Test out the r_x, r_y (All tested, the answer matches)\n    %     figure(1)\n    %     clf\n    %     surf(x,y,u_x(:,:,pin))\n    %     \n    %     for kk=1:n\n    %        Dum(kk,:)=CalDerivative(u(kk,:,pin),dx,1); \n    %     end\n    %     \n    %     figure(2)\n    %     clf\n    %     surf(x,y,Dum)\n    %     \n    %     figure(3)\n    %     clf\n    %     surf(x,y,u_y(:,:,pin))\n    %     \n    %     for kk=1:n\n    %        Dum(:,kk)=CalDerivative(u(:,kk,pin),dx,1); \n    %     end\n    %     \n    %     figure(4)\n    %     clf\n    %     surf(x,y,Dum)\n    \n    % Test r_xx (All tested, the results matches)\n    %     figure(1)\n    %     clf\n    %     surf(x,y,u_xx(:,:,pin))\n    %\n    %     for kk=1:n\n    %         Dum_x(kk,:)=CalDerivative(u(kk,:,pin),dx,1);\n    %     end\n    %\n    %     for kk=1:n\n    %         Dum_xx(kk,:)=CalDerivative(Dum_x(kk,:),dx,1);\n    %     end\n    %\n    %     figure(2)\n    %     clf\n    %     surf(x,y,Dum_xx)\n    %\n    %     figure(3)\n    %     clf\n    %     surf(x,y,u_yy(:,:,pin))\n    %\n    %     for kk=1:n\n    %         Dum_y(:,kk)=CalDerivative(u(:,kk,pin),dx,1);\n    %     end\n    %\n    %     for kk=1:n\n    %         Dum_yy(:,kk)=CalDerivative(Dum_y(:,kk),dx,1);\n    %     end\n    %\n    %     figure(4)\n    %     clf\n    %     surf(x,y,Dum_yy)\n    %\n    %     figure(5)\n    %     clf\n    %     surf(x,y,u_lap(:,:,pin))\n    %\n    %     figure(6)\n    %     clf\n    %     surf(x,y,Dum_xx+Dum_yy)\n    %\n    %     figure(7)\n    %     clf\n    %     surf(x,y,u_xx(:,:,pin)+u_yy(:,:,pin))\nend\n\n%% Plot the result and save it to file\n%Creat Movie\nSave_Animation=1;\n\nStates=['r','z','s','u'];\nfor pin=1:4\n    if pin==1\n        Animate=r;\n        limits=[0 1];\n    elseif pin==2\n        Animate=z;\n        limits=[0 1];\n    elseif pin==3\n        Animate=s;\n        limits=[0 1];\n    elseif pin==4\n        Animate=u;\n        limits=[0 1];\n    end\n    if Save_Animation==1\n        name=strcat('BZ_Diffusion_',States(pin),'_',num2str(T),'_Seconds');\n        writerObj = VideoWriter(name,'MPEG-4'); % Name it.\n        writerObj.FrameRate = 20; % How many frames per second.\n        writerObj.Quality = 100;\n        open(writerObj);\n        for j=1:15:length(tspan)\n            clf\n            pcolor(x,y,Animate(:,:,j))\n            shading interp\n            colormap(parula)\n            caxis(limits)\n            colorbar\n            %Make plot propotional\n            set(gca,'FontSize',18);\n            set(gcf,'Position',[50 50 1000 1000]);\n            set(gcf,'PaperPositionMode','auto');\n            set(gca,'DataAspectRatio',[1 1 1])\n            drawnow limitrate\n            Mov=getframe(gcf);\n            writeVideo(writerObj,Mov);\n        end\n        % Close the object or you can't read the final file correctly\n        close(writerObj)\n    end\nend\n\n%% Save files\nSave_File=1;\nif Save_File==1\n    save(strcat('Datas\\Simulation_BZ_',num2str(T),'_Seconds_',num2str(n),'_Grid.mat'),'r_t','z_t','s_t','u_t','r','z','s','u',...\n        'r_x','z_x','s_x','u_x','r_y','z_y','s_y','u_y','r_xx','z_xx','s_xx','u_xx',...\n        'r_yy','z_yy','s_yy','u_yy','dt','T','tspan','dx','x')\nend\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Implicit-PDE/BZ_Reaction/Data_Generation_BZ_Main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5502184562832413}}
{"text": "% SP_H1_ERROR: Evaluate the error in H^1 norm.\n%\n%   [errh1, errl2, errh1s] = sp_h1_error (space, msh, u, uex, graduex)\n%\n% INPUT:\n%\n%    space:   object defining the space of discrete functions (see sp_vector)\n%    msh:     object defining the domain partition and the quadrature rule (see msh_cartesian)\n%    u:       vector of dof weights\n%    uex:     function handle to evaluate the exact solution\n%    graduex: function handle to evaluate the gradient of the exact solution\n%\n% OUTPUT:\n%\n%     errh1:  error in H^1 norm\n%     errl2:  error in L^2 norm\n%     errh1s: error in H^1 seminorm\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 Octave; see the file COPYING.  If not, see\n% <http://www.gnu.org/licenses/>.\n\nfunction [errh1, errl2, errh1s] = sp_h1_error (space, msh, u, uex, graduex)\n\n  if (numel(u) ~= space.ndof)\n    error ('Wrong size of the vector of degrees of freedom')\n  end\n\n  errl2 = 0; errh1s = 0;\n  for iel = 1:msh.nel_dir(1)\n    msh_col = msh_evaluate_col (msh, iel);\n    sp_col  = sp_evaluate_col (space, msh_col, 'value', true, 'gradient', true);\n    \n    [~, err_l2, err_h1s] = sp_h1_error (sp_col, msh_col, u, uex, graduex);\n    \n    errh1s = errh1s + err_h1s.^2;\n    errl2 = errl2 + err_l2.^2;\n  end\n  \n  errh1 = sqrt (errl2 + errh1s);\n  errl2 = sqrt (errl2);\n  errh1s = sqrt (errh1s);\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_vector/sp_h1_error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5502184516168243}}
{"text": "function test_example_conditional_granger\n\n% MEM 4gb\n% WALLTIME 00:10:00\n\n%\n%% Conditional Granger causality in the frequency domain\n%\n% Conditional Granger causality is a derivative of spectral Granger causality that is computed over a triplet of channels (or blocks of channels). It provides the advantage that for this triplet, it allows to differentiate between a delayed parallel drive from sources <i>A</i> to be <i>B</i> and <i>C</i> and a sequential drive from <i>A</i> to <i>B</i> to <i>C</i>.\n%\n% This example illustrates the simulation and base analysis of the paper\n%\n% See also: [the connectivity tutorial]/tutorial/connectivity/).\n%\n%% # Setup and simulating the data sets\n%\n% First, define parameters under which samples should be simulated.\n%\nsimcfg             = [];\nsimcfg.ntrials     = 500;\nsimcfg.triallength = 1;\nsimcfg.fsample     = 200;\nsimcfg.nsignal     = 3;\nsimcfg.method      = 'ar';\n\n% We want to simulate a system with three signals. Their noise is modeled as white noise processes with zero mean and standard deviations\n%\n%\n% They will have the covariances &zeta;, &eta; and &epsilon;. We also require a paramters &mu;=0.5.\n%\n% parameters of the model itself\nmu                 = 0.5;\nabsnoise           = [ 1.0   0.2   0.3 ];\n\n% First, we generate the sample for the case of sequential driving.\n% We want to incorporate the system\n%\n%\n% which we can do like this:\n%\n% params(i,j,k): j -> i at t=k\nsimcfg.params(:,:,1) = [   0      0      0;\n                         1.0      0      0;\n                           0    1.0     mu];\n\n% Note that the matrix representation for the covariance reads from columns to row, other than the MVAR-model is read intuitively. But we still need to hand the parameters of the noise to the model:\n%\n% paper defines stds, not cov:\nsimcfg.noisecov      = diag(absnoise.^2);\n\ndata2           = ft_connectivitysimulation(simcfg);\n\n% Now create sample data for the case of differentially delayed driving,\n%\n%\n% which we can write as\n%\nsimcfg.params(:,:,1) = [   0      0      0;\n                         1.0      0      0;\n                           0      0     mu];\nsimcfg.params(:,:,2) = [   0      0      0;\n                           0      0      0;\n                         1.0      0      0];\n\n% We build the actual MVAR-representation...\n%\ndata1           = ft_connectivitysimulation(simcfg);\n\n% #\n%\nfigure\nplot(data1.time{1}, data1.trial{1})\nlegend(data1.label)\nxlabel('time (s)')\n\n% Don't be confused that we started with data2 and conclude with data1. This is just to maintain the order the systems have in the paper.\n%\n%% # MVAR model frequency analysis\n% We generate spectral representations from the MVAR representations we defined with data1 and data2. After all, we want to compute spectral Granger causality. Fast Fourier is a good starting point.\n%\nfreq                   = [];\nfreq.freqcfg           = [];\nfreq.freqcfg.method    = 'mtmfft';\nfreq.freqcfg.output    = 'fourier';\nfreq.freqcfg.tapsmofrq = 2;\nfreqdata1           = ft_freqanalysis(freq.freqcfg, data1);\nfreqdata2           = ft_freqanalysis(freq.freqcfg, data2);\n\n%% # \"Regular\" Granger causality\n% Let first compute regular bivariate Granger causality, as this makes the difference clear to what we want.\n%\ngrangercfg = [];\ngrangercfg.method  = 'granger';\ngrangercfg.granger.conditional = 'no';\ngrangercfg.granger.sfmethod = 'bivariate';\n\ngdata = [];\ngdata.g1_bivar_reg      = ft_connectivityanalysis(grangercfg, freqdata1);\ngdata.g2_bivar_reg      = ft_connectivityanalysis(grangercfg, freqdata2);\n\n%% # Multivariate conditional Granger causality\n% However, we clearly want a multivariate approach. Also, we need to define channel combinations, as we now require triplets of inputs.\n%\ngrangercfg.granger.conditional = 'yes';\ngrangercfg.channelcmb  = {'signal001', 'signal002', 'signal003'};\ngrangercfg.granger.sfmethod = 'multivariate';\ngrangercfg.granger.conditional = 'yes';\n\n% block-wise causality\ngrangercfg.granger.block(1).name   = freqdata1.label{1};\ngrangercfg.granger.block(1).label  = freqdata1.label(1);\ngrangercfg.granger.block(2).name   = freqdata1.label{2};\ngrangercfg.granger.block(2).label  = freqdata1.label(2);\ngrangercfg.granger.block(3).name   = freqdata1.label{3};\ngrangercfg.granger.block(3).label  = freqdata1.label(3);\n\ngdata.g1_multi_reg_conditional = ft_connectivityanalysis(grangercfg, freqdata1);\ngdata.g2_multi_reg_conditional = ft_connectivityanalysis(grangercfg, freqdata2);\n\n%% # Evaluation\n% The label combinations are 6x2 cell arrays, containing all 2-permutations\n% tuplets from the channels. How to interpret this?\n% Is the combination a, b representing F<sub>a&rarr;b|c</sub>?\n% Let's check this. In scenario 2, we should clearly see a higher causality\n% from 1&rarr;3 | 2 than in scenario 1 of the differentially delayed\n% drive. This corresponds to row 4 in the\n% gdata.g1_multi_reg_conditional.labelcmb.\n% So, let's compare the labelcmb 1, 3 in both scenarios:\n%\nscenario1_mean = mean(gdata.g1_multi_reg_conditional.grangerspctrm(4, :));\nscenario2_mean = mean(gdata.g2_multi_reg_conditional.grangerspctrm(4, :));\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_example_connectivity_conditional_granger20220113.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6893056295505784, "lm_q1q2_score": 0.5501946459470513}}
{"text": "function knee_angle(nlp, bounds)\n    % constraints for step length and step width\n    \n    domain = nlp.Plant;\n    x = domain.States.x;\n    \n    % knee angle\n    knee = [x('qBRight') - x('qARight')\n        x('qBLeft') - x('qALeft')];\n    knee_fun = SymFunction(['kneeAngles_',domain.Name], knee, {x});\n    addNodeConstraint(nlp, knee_fun, {'x'}, 'all', ...\n        bounds.constrBounds.knee.lb, ...\n        bounds.constrBounds.knee.ub,'Linear');\n    \nend\n\n", "meta": {"author": "ayonga", "repo": "frost-dev", "sha": "e5dc0624d834520872bfa588dd3eda5643da71de", "save_path": "github-repos/MATLAB/ayonga-frost-dev", "path": "github-repos/MATLAB/ayonga-frost-dev/frost-dev-e5dc0624d834520872bfa588dd3eda5643da71de/example/marlo/+opt/+constraint/knee_angle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5501946408525714}}
{"text": "\nfunction [ csd ] = bz_CSD (lfp, varargin)\n\n% [ CSD ] = bz_CSD (lfp, varargin)\n% Calculates the 1D approximation of current source density (CSD) from a\n% linear array of LFPs\n\n% INPUT\n%    lfp            a buzcode structure with fields lfp.data,\n%                                                   lfp.timestamps\n%                                                   lfp.samplingRate\n%                   -lfp can also be a [t x 1] timeseries signal. in which\n%                   case you need to input 'samplingRate'\n%    <options>      optional list of property-value pairs (see table below)\n%\n%    =========================================================================\n%     Properties    Values\n%    -------------------------------------------------------------------------\n%       channels    vector with channels to inlcude. If empty take all (default)\n%       win         time interval to compute CSD. If empty take all (default)\n%       spat_sm     degree of spatial smoothing. Default = 0.\n%       temp_sm     degree of temporal smoothing. Default = 0.\n%       plotCSD     true/false. Default true.\n%       plotLFP     true/false. Default true.\n%    =========================================================================\n\n% OUTPUT:\n%    CSD           a buzcode structure with fields csd.data,\n%                                                   csd.timestamps\n%                                                   csd.samplingRate\n%                                                   csd.channels \n%                                                   csd.params\n\n% Antonio FR, 7/18\n\n%% Parse inputs\n\np = inputParser;\naddParameter(p,'channels',1:size(lfp.data,2),@isvector);\naddParameter(p,'samplingRate',1250,@isnumeric);\naddParameter(p,'win',[1 size(lfp.data,1)],@isnumeric);\naddParameter(p,'spat_sm',11,@isnumeric);\naddParameter(p,'temp_sm',11,@isnumeric);\naddParameter(p,'doDetrend',false,@islogical);\naddParameter(p,'plotCSD',true,@islogical);\naddParameter(p,'plotLFP',true,@islogical);\n\nparse(p,varargin{:});\nchannels = p.Results.channels;\nsamplingRate = p.Results.samplingRate;\nspat_sm = p.Results.spat_sm;\ntemp_sm = p.Results.temp_sm;\ndoDetrend = p.Results.doDetrend;\nplotCSD = p.Results.plotCSD;\nplotLFP = p.Results.plotLFP;\n\n%lfp input\nif isstruct(lfp)\n    data = lfp.data;\n    timestamps = lfp.timestamps;\n    samplingRate = lfp.samplingRate;\nelseif iscell(lfp) %for multiple trials\n    celllengths = cellfun(@length,lfp);\n    data = vertcat(lfp{:});\nelseif isnumeric(lfp)\n    data = lfp;\n    timestamps = [1:length(lfp)]'./samplingRate;\nend\n\nwin = p.Results.win*samplingRate;\n\n\n%% Compute CSD\n\nlfp_frag = data(win(1):win(2),channels)*-1;\n\n% detrend\nif doDetrend\n   lfp_frag = detrend(lfp_frag')';\nend\n    \n% temporal smoothing\nif temp_sm > 0\n   for ch = 1:size(lfp_frag,2) \n       lfp_frag(:,ch) = smooth(lfp_frag(:,ch),temp_sm,'sgolay');\n   end\nend\n\n% spatial smoothing\nif spat_sm > 0\n   for t = 1:size(lfp_frag,1) \n       lfp_frag(t,:) = smooth(lfp_frag(t,:),spat_sm,'lowess');\n   end\nend\n\n% calculate CSD \nCSD = diff(lfp_frag,2,2);\n\n% generate output structure\ncsd.data = CSD;\ncsd.timestamps = timestamps(win(1):win(2));\ncsd.samplingRate = samplingRate;\ncsd.channels = channels; \ncsd.params.spat_sm = spat_sm;\ncsd.params.temp_sm = temp_sm;\ncsd.params.detrend = doDetrend;\n\n%% Plot\n\nif plotLFP\n    \n    cmax = max(max(CSD)); \n\n    figure;\n    subplot(1,2,1);\n    contourf(timestamps(win(1):win(2)),1:size(CSD,2),CSD',40,'LineColor','none');hold on;\n    colormap jet; caxis([-cmax cmax]);\n    set(gca,'YDir','reverse');xlabel('time (s)');ylabel('channel');title('CSD'); \n   \n    subplot(1,2,2);\n    for ch=1:size(lfp_frag,2)\n        offset = 500*(ch-1);\n        sh_tmp = 10e5*(lfp_frag(:,ch)) + offset;\n        plot(timestamps(win(1):win(2)),sh_tmp,'k','LineWidth',1.5); hold on;\n        clear sh_tmp\n    end\n    set(gca,'YDir','reverse','YTickLabel',[]);ylim([-500 offset+500]);xlim([timestamps(win(1)) timestamps(win(2))]);\n    xlabel('time (s)');ylabel('channel');title('LFP');   \n    \nelseif plotCSD  \n    \n     cmax = max(max(CSD)); \n   \n     figure;\n     contourf(timestamps(win(1):win(2)),1:size(CSD,2),CSD',40,'LineColor','none');hold on;\n     colormap jet; caxis([-cmax cmax]);\n     set(gca,'YDir','reverse');xlabel('time (s)');ylabel('channel');title(CSD); \n   \nend\n\nend\n\n\n    \n\n\n\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/analysis/lfp/CurrentSourceDensity/bz_CSD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5501946306636114}}
{"text": "function P = sammon(D, P, varargin)\n\n%SAMMON Computes Sammon's mapping of a data set.\n%\n% P = sammon(D, P, [value], [mode], [alpha], [Mdist])\n%\n%  P = sammon(D,2);            % projection to 2-dim space\n%  P = sammon(sMap,3);         % projects the codebook vectors\n%  P = sammon(sMap,3,[],[],[],Md) % uses distance matrix Md\n%  som_grid(sMap,'Coord',P)    % visualization of map projection\n%\n%  Input and output arguments ([]'s are optional):\n%   D        (matrix) size dlen x dim, data to be projected\n%            (struct) data or map struct            \n%   P        (scalar) output dimension\n%            (matrix) size dlen x odim, initial projection matrix\n%   [value]  (scalar) all different modes (the next argument) require \n%                     a value, default = 100\n%   [mode]   (string) 'steps' or 'errlimit' or 'errchange' or 'seconds',\n%                     see below, default is 'steps'\n%   [alpha]  (scalar) iteration step size, default = 0.2\n%   [Dist]   (matrix) pairwise distance matrix, size dlen x dlen.\n%                     If the distances in the input space should\n%                     be calculated otherwise than as euclidian\n%                     distances, the distance from each vector\n%                     to each other vector can be given here,\n%                     size dlen x dlen. For example PDIST\n%                     function can be used to calculate the\n%                     distances: Dist = squareform(pdist(D,'mahal'));\n%\n%   P        (matrix) size dlen x odim, the projections\n%\n% The output dimension must be 2 or higher but (naturally) lower \n% than data set dimension.\n%\n% The mode argument determines the end condition for iteration. If \n% the mode argument is used, also the value argument has to be \n% specified. Different mode possibilities are:\n% 'steps'      the iteration is terminated when it is run <value> \n% 'errlimit'   steps, the iteration is terminated when projection error \n%              is lower than <value>,\n% 'errchange'  the iteration is terminated when change between \n%              projection error on two successive iteration rounds\n%\t       is less than <value> percent of total error, and\n% 'seconds'    the iteration is terminated after <value> seconds \n%              of iteration.\n%\n% See also CCA, PCAPROJ, SOM_GRID.\n\n% Reference: Sammon, J.W. Jr., \"A nonlinear mapping for data\n%   structure analysis\", IEEE Transactions on Computers, vol. C-18,\n%   no. 5, 1969, pp. 401-409.\n\n% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Vesanto\n% Copyright (c) by Juha Vesanto\n% http://www.cis.hut.fi/projects/somtoolbox/\n\n% juuso 040100 \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% check arguments\n\nerror(nargchk(2, 6, nargin));  % check no. of input arguments is correct\n\n% input data\nif isstruct(D),\n  if isfield(D, 'data'),         D = D.data; % data struct\n  elseif isfield(D, 'codebook'), D = D.codebook; % map struct\n  else error('Invalid structure');\n  end\nend\nif any(isnan(D(:))), \n  error('Cannot make Sammon''s projection for data with unknown components')\nend \n\n% compute data dimensions\norig_si = size(D); \ndim = orig_si(end); \nnoc = prod(orig_si)/dim;\nif length(orig_si)>2, D = reshape(D,[noc dim]); end\n\n% output dimension / initial projection matrix\nif prod(size(P))==1, \n  odim = P; \n  P = rand(noc,odim)-0.5; \nelse \n  si = size(P);\n  odim = si(end);\n  if prod(si) ~= noc*odim, \n    error('Initial projection matrix size does not match data size');\n  end\n  if length(si)>2, P = reshape(P,[noc odim]); end\n  inds = find(isnan(P)); \n  if length(inds), P(inds) = rand(size(inds)); end\nend\nif odim > dim | odim < 2, \n  error('Output dimension must be within [2, dimension of data]');\nend\n\n% determine operating mode\nif nargin < 3 | isempty(varargin{1}) | isnan(varargin{1}), value=100;\nelse value = varargin{1}; \nend\n  \nif nargin < 4 | isempty(varargin{2}) | isnan(varargin{2}), mode='steps';\nelse mode = varargin{2}; \nend  \nswitch mode,\ncase 'steps',     runlen = value;\ncase 'errlimit',  errlimit = value;\ncase 'errchange', errchange = value; e_prev = 0;\ncase 'seconds',   endtime = value;\notherwise, error(['Illegal mode: ' mode]);\nend\n\n% iteration step size\nif nargin > 4, alpha = varargin{3}; else alpha = NaN; end\nif isempty(alpha) | isnan(alpha), alpha = 0.2; end\n\n% mutual distances\nif nargin > 5, Mdist = varargin{4}; else Mdist = []; end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% initialization\n\n% these are used quite frequently\nnoc_x_1  = ones(noc, 1); \nodim_x_1 = ones(odim,1); \n\n% compute mutual distances between vectors\nif isempty(Mdist) | all(isnan(Mdist(:))),  \n  fprintf(2, 'computing mutual distances\\r');\n  dim_x_1 = ones(dim,1);\n  for i = 1:noc,\n    x = D(i,:); \n    Diff = D - x(noc_x_1,:);\n    N = isnan(Diff);\n    Diff(find(N)) = 0; \n    Mdist(:,i) = sqrt((Diff.^2)*dim_x_1);\n    N = find(sum(N')==dim); %mutual distance unknown\n    if ~isempty(N), Mdist(N,i) = NaN; end\n  end\nelse\n  % if the distance matrix is output from PDIST function\n  if size(Mdist,1)==1, Mdist = squareform(Mdist); end\n  if size(Mdist,1)~=noc, \n    error('Mutual distance matrix size and data set size do not match'); \n  end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% action\n\nif strcmp(mode, 'seconds'), tic; end;\nfprintf(2, 'iterating                    \\r');\n\n% sammon iteration   \n\nx  = P ;\nxu = zeros(noc, odim);\nxd = zeros(noc, odim);\ndq = zeros(noc, 1);\ndr = zeros(noc, 1);\n\ni = 0;\nready = 0;\nwhile ~ready\n  for j = 1:noc,\n    xd      = -x + x(j*noc_x_1,:);\n    xd2     = xd.^2;\n    dpj     = sqrt(sum(xd2'))';\n    dq      = Mdist(:,j) - dpj;\n    dr      = Mdist(:,j) .* dpj;\n    ind     = find(dr ~= 0);\n    term    = dq(ind) ./ dr(ind);\n    e1      = sum(xd(ind,:) .* term(:,odim_x_1));\n    term2   = ((1.0 + dq(ind) ./ dpj(ind)) ./ dpj(ind)) ./ dr(ind);\n    e2      = sum(term) - sum(xd2(ind,:) .* term2(:,odim_x_1));\n    xu(j,:) = x(j,:) + alpha * e1 ./ abs(e2);\n  end\n\n  % move the center of mass to the center \n\n  c = sum(xu) / noc;\n  x = xu - c(noc_x_1, :);\n\n  i = i + 1;\n\n  % compute mapping error\n  % doing this adds about 25% to computing time  \n  if 0,\n    e = 0; tot = 0;\n    for j = 2:noc, \n      d   = Mdist(1:(j - 1), j);\n      tot = tot + sum(d);\n      ind = find(d ~= 0);\n      xd  = -x(1:(j - 1), :) + x(j * ones(j - 1, 1), :);\n      ee  = d - sqrt(sum(xd'.^2))';\n      e   = e + sum(ee(ind).^2 ./ d(ind));\n    end\n    e = e/tot; \n    fprintf(2, '\\r%d iterations, error %f', i, e);\n  else\n    fprintf(2, '\\r%d iterations', i);\n  end\n  \n  % determine is the iteration ready\n  \n  switch mode\n    case 'steps', \n      if i == runlen, ready = 1; end;\n    case 'errlimit',\n      if e < errlimit, ready = 1; end;\n    case 'errchange',\n      if i > 1\n\tchange = 100 * abs(e - e_prev) / e_prev;\n\tif change < errchange, ready = 1; end;\n\tfprintf(2, ', change of error %f %%    ', change);\n      end\n      e_prev = e;\n    case 'seconds'\n      if toc > endtime, ready = 1; end;\n      fprintf(2, ', elapsed time %f seconds  ', toc);\n  end\n  fprintf(2, '        ');\n  \n  % If you want to see the Sammon's projection plotted (in 2-D and 3-D case),\n  % execute the code below; it is not in use by default to speed up \n  % computation.  \n  if 0, \n    clf\n    if odim == 1,     plot(x(:,1), noc_x_1, 'o');\n    elseif odim == 2, plot(x(:,1), x(:,2), 'o');\n    else              plot3(x(:,1), x(:,2), x(:,3), 'o')\n    end\n    drawnow\n  end\nend\n\nfprintf(2, '\\n');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% clean up\n\n% reshape\norig_si(end) = odim; \nP = reshape(x, orig_si);\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/sammon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5501761683238865}}
{"text": "function show_reg_warp(I,U,V,grid_size)\n%SHOW_REG_WARP Summary of this function goes here\n%   Detailed explanation goes here\n% Input:\n%   I - image matrix or handle to the axes\n%   (U,V) - translation field v(x) = (U(x),V(x)), s.t. T(x) = x + v(x)\n%   grid_size - number of points per dimension\n\nif nargin < 1\n    I = imread('pout.tif');\nend\n\nif nargin < 3\n    [rows,cols,b] = size(I);\n    U = zeros(rows,cols);\n    V = zeros(rows,cols);\nend\n\nif nargin < 4\n    grid_size = 20;\nend\n\n[rows,cols] = size(U);\n\n\nx1 = linspace(1, cols, grid_size);\ny1 = linspace(1, rows, grid_size);\n[X,Y] = meshgrid(x1,y1);\nU1 = interp2((1:cols),(1:rows),U,X,Y);\nV1 = interp2((1:cols),(1:rows),V,X,Y);\nX_target = X - U1; % X_target + U1 = X;\nY_target = Y - V1; % Y_target + V1 = Y;\nx = X_target(:);\ny = Y_target(:);\n\n[W,M] = image2graph(ones(length(y1),length(x1)),0.05,1e-9);\n\n% [A,J2,A2] = create_adjacency_graph(X,'epsball',1.01,1);\n\nif ishandle(I)\n    ax_h = I;\nelseif ~isempty(I)\n    figure,imshow(I);\n    ax_h = gca;\nend\nhold(ax_h, 'on');\n\nfor i = 1:length(x)\n    neighbor_inds = find(M(i,:));\n    for j = 1:length(neighbor_inds)\n        plot(ax_h,[x(i),x(neighbor_inds(j))],[y(i),y(neighbor_inds(j))],'-b',...\n            'linewidth', 1);\n    end\nend\n\nend\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/common/show_reg_warp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5501761633386589}}
{"text": "function [TET,Vtet,C]=hex2tet(varargin)\n\n% function [TET,Vtet,C]=hex2tet(HEX,V,C,tetOpt)\n\n%%\n\nswitch nargin\n    case 2\n        HEX=varargin{1};\n        V=varargin{2};\n        C=[];\n        tetOpt=1;\n    case 3\n        HEX=varargin{1};\n        V=varargin{2};\n        C=varargin{3};\n        tetOpt=1;\n    case 4\n        HEX=varargin{1};\n        V=varargin{2};\n        C=varargin{3};\n        tetOpt=varargin{4};\n    otherwise\n        error('Wrong number of input arguments');\nend\n\n%%\n\nC=C(:);\nswitch tetOpt\n    case 1 %Add central node and cross side faces\n        \n        [F,~]=element2patch(HEX,C,'hex8');\n        \n        numV=size(V,1);\n        numE=size(HEX,1);\n        \n        %The original vertices\n        X=V(:,1); Y=V(:,2); Z=V(:,3);\n        \n        %The mid-element points\n        if numE==1\n            Vm=[mean(X(HEX),1) mean(Y(HEX),1) mean(Z(HEX),1)];\n        else\n            Vm=[mean(X(HEX),2) mean(Y(HEX),2) mean(Z(HEX),2)];\n        end\n        \n        %The mid-face points\n        Vf=[mean(X(F),2) mean(Y(F),2) mean(Z(F),2)];\n        \n        %TET point collection\n        Vtet=[V; Vm; Vf];\n        \n        %Defining tetrahedral node list per hex element\n        numV2=numV+numE+1;\n        indAdd=reshape(numV2:(numV2+6*numE)-1,numE,6);        \n        TET_set=[HEX (numV+1:numV+numE)' indAdd];\n\n        TET_format=[14 13 9 10;...\n                    12 14 9 10;...\n                    15 12 9 10;...\n                    13 15 9 10;...\n                    %\n                    13 14 9 11;...\n                    14 12 9 11;...\n                    12 15 9 11;...\n                    15 13 9 11;...\n                    %\n                    1 10 12 15;...\n                    2 10 14 12;...\n                    3 10 13 14;...\n                    4 10 15 13;...\n                    %\n                    5 11 15 12;...\n                    6 11 12 14;...\n                    7 11 14 13;...\n                    8 11 13 15;...\n                    %\n                    1 2 12 10;...\n                    2 3 14 10;...\n                    3 4 13 10;...\n                    4 1 15 10;...\n                    %\n                    5 6 11 12;...\n                    6 7 11 14;...\n                    7 8 11 13;...\n                    8 5 11 15;...\n                    %\n                    1 5 15 12;...\n                    2 6 12 14;...\n                    3 7 14 13;...\n                    4 8 13 15;...\n                    ];\n                \n        %Reform TET_set as an nx4\n        TET_set_reform1=TET_set(:,TET_format(:))';        \n        TET_set_reform2=reshape(TET_set_reform1,size(TET_format,1),numel(TET_set_reform1)/size(TET_format,1))';\n        TET=reshape(TET_set_reform2,4,numel(TET_set_reform2)/4)';\n        \n        %Fix color information\n        C=repmat(C,size(TET_format,1),1);        \n        \n        %Removing double vertices\n        [TET,Vtet]=mergeVertices(TET,Vtet);\n\n    case 2 %Delaunay based 6 tetrahedron decomposition of cube applied to all\n        HEX=HEX(:,[1 2 4 3 5 6 8 7]);\n        tetInd =[5     1     2     3;...\n            6     5     2     3;...\n            6     7     5     3;...\n            6     4     7     3;...\n            6     2     4     3;...\n            6     8     7     4];\n        a=tetInd';\n        a=a(:)';\n        A=HEX(:,a);\n        TET=reshape(A',4,6.*size(HEX,1))';\n        if ~isempty(C)\n            C=(ones(6,1)*C');\n            C=C(:);\n        end\n        Vtet=V;\n    case 3 %Same as 2 but flipped top to bottom\n        \n        %Switch top and bottom\n        HEX=HEX(:,[8 7 5 6 4 3 1 2]);\n\n        tetInd =[5     1     2     3;...\n            6     5     2     3;...\n            6     7     5     3;...\n            6     4     7     3;...\n            6     2     4     3;...\n            6     8     7     4];\n        a=tetInd';\n        a=a(:)';\n        A=HEX(:,a);\n        TET=reshape(A',4,6.*size(HEX,1))';\n        if ~isempty(C)\n            C=(ones(6,1)*C');\n            C=C(:);\n        end\n        Vtet=V;\n    case 4 % 5 tetrahedron decomposition of cube\n        tetInd=[1 8 6 5; 7 8 6 3; 2 1 3 6; 4 8 3 1; 6 3 8 1];      \n        a=tetInd';\n        a=a(:)';\n        A=HEX(:,a);\n        TET=reshape(A',4,5.*size(HEX,1))';\n        if ~isempty(C)\n            C=(ones(5,1)*C');\n            C=C(:);\n        end\n        Vtet=V;\n    case 5 %Same as 4 but flipped top to bottom\n        %Switch top and bottom\n        HEX=(HEX(:,[4 3 7 8 1 2 6 5 ]));\n\n        tetInd=[1 8 6 5; 7 8 6 3; 2 1 3 6; 4 8 3 1; 6 3 8 1];\n        a=tetInd';\n        a=a(:)';\n        A=HEX(:,a);\n        TET=reshape(A',4,5.*size(HEX,1))';\n        if ~isempty(C)\n            C=(ones(5,1)*C');\n            C=C(:);\n        end\n        Vtet=V;\n    case 6 % tets for octet-truss lattice\n         [F,~]=element2patch(HEX,C,'hex8');\n        \n        numV=size(V,1);\n        numE=size(HEX,1);\n        \n        %The original vertices\n        X=V(:,1); Y=V(:,2); Z=V(:,3);\n        \n        %The mid-element points\n        if numE==1\n            Vm=[mean(X(HEX),1) mean(Y(HEX),1) mean(Z(HEX),1)];\n        else\n            Vm=[mean(X(HEX),2) mean(Y(HEX),2) mean(Z(HEX),2)];\n        end\n        \n        %The mid-face points\n        Vf=[mean(X(F),2) mean(Y(F),2) mean(Z(F),2)];\n        \n        %TET point collection\n        Vtet=[V; Vm; Vf];\n        \n        %Defining tetrahedral node list per hex element\n        numV2=numV+numE+1;\n        indAdd=reshape(numV2:(numV2+6*numE)-1,numE,6);        \n        TET_set=[HEX (numV+1:numV+numE)' indAdd];\n\n        TET_format=[...\n%                     %\n%                     14 13 9 10;...\n%                     12 14 9 10;...\n%                     15 12 9 10;...\n%                     13 15 9 10;...\n%                     %\n%                     13 14 9 11;...\n%                     14 12 9 11;...\n%                     12 15 9 11;...\n%                     15 13 9 11;...\n                    %\n                    1 10 12 15;...\n                    2 10 14 12;...\n                    3 10 13 14;...\n                    4 10 15 13;...\n                    %\n                    5 11 15 12;...\n                    6 11 12 14;...\n                    7 11 14 13;...\n                    8 11 13 15;...\n\n                    %\n                    1 5 15 12;...\n                    2 6 12 14;...\n                    3 7 14 13;...\n                    4 8 13 15;...\n                    ];\n                \n        %Reform TET_set as an nx4\n        TET_set_reform1=TET_set(:,TET_format(:))';        \n        TET_set_reform2=reshape(TET_set_reform1,size(TET_format,1),numel(TET_set_reform1)/size(TET_format,1))';\n        TET=reshape(TET_set_reform2,4,numel(TET_set_reform2)/4)';\n        \n        %Fix color information\n        C=repmat(C,size(TET_format,1),1);        \n        \n        %Removing double vertices\n        [TET,Vtet]=mergeVertices(TET,Vtet);\nend\n\nTET=TET(:,[1 2 4 3]); %Invert\n\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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) 2019  Kevin Mattheus Moerman\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program.  If not, see <http://www.gnu.org/licenses/>.\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/gibbon/hex2tet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5501761614547359}}
{"text": "function IN = inpolyhedron(varargin)\n%INPOLYHEDRON  Tests if points are inside a 3D triangulated (faces/vertices) surface\n%   BY CONVENTION, SURFACE NORMALS SHOULD POINT OUT from the object. (see\n%   FLIPNORMALS option below for details)\n%\n%   IN = INPOLYHEDRON(FV,QPTS) tests if the query points (QPTS) are inside the\n%   patch/surface/polyhedron defined by FV (a structure with fields 'vertices' and\n%   'faces'). QPTS is an N-by-3 set of XYZ coordinates. IN is an N-by-1 logical\n%   vector which will be TRUE for each query point inside the surface.\n%\n%   INPOLYHEDRON(FACES,VERTICES,...) takes faces/vertices separately, rather than in\n%   an FV structure.\n%\n%   IN = INPOLYHEDRON(..., X, Y, Z) voxelises a mask of 3D gridded query points\n%   rather than an N-by-3 array of points. X, Y, and Z coordinates of the grid\n%   supplied in XVEC, YVEC, and ZVEC respectively. IN will return as a 3D logical\n%   volume with SIZE(IN) = [LENGTH(YVEC) LENGTH(XVEC) LENGTH(ZVEC)], equivalent to\n%   syntax used by MESHGRID. INPOLYHEDRON handles this input faster and with a lower \n%   memory footprint than using MESHGRID to make full X, Y, Z query points matrices.\n%\n%   INPOLYHEDRON(...,'PropertyName',VALUE,'PropertyName',VALUE,...) tests query\n%   points using the following optional property values:\n%\n%   TOL           - Tolerance on the tests for \"inside\" the surface. You can think of\n%   tol as the distance a point may possibly lie above/below the surface, and still\n%   be perceived as on the surface. Due to numerical rounding nothing can ever be\n%   done exactly here. Defaults to ZERO. Note that in the current implementation TOL\n%   only affects points lying above/below a surface triangle (in the Z-direction).\n%   Points coincident with a vertex in the XY plane are considered INside the surface.\n%   More formal rules can be implemented with input/feedback from users.\n%\n%   GRIDSIZE      - Internally, INPOLYHEDRON uses a divide-and-conquer algorithm to\n%   split all faces into a chessboard-like grid of GRIDSIZE-by-GRIDSIZE regions.\n%   Performance will be a tradeoff between a small GRIDSIZE (few iterations, more\n%   data per iteration) and a large GRIDSIZE (many iterations of small data\n%   calculations). The sweet-spot has been experimentally determined (on a win64\n%   system) to be correlated with the number of faces/vertices. You can overwrite\n%   this automatically computed choice by specifying a GRIDSIZE parameter.\n%\n%   FACENORMALS   - By default, the normals to the FACE triangles are computed as the\n%   cross-product of the first two triangle edges. You may optionally specify face\n%   normals here if they have been pre-computed.\n%\n%   FLIPNORMALS   - (Defaults FALSE). To match a wider convention, triangle\n%   face normals are presumed to point OUT from the object's surface. If\n%   your surface normals are defined pointing IN, then you should set the\n%   FLIPNORMALS option to TRUE to use the reverse of this convention.\n%\n%   Example:\n%       tmpvol = zeros(20,20,20);       % Empty voxel volume\n%       tmpvol(5:15,8:12,8:12) = 1;     % Turn some voxels on\n%       tmpvol(8:12,5:15,8:12) = 1;\n%       tmpvol(8:12,8:12,5:15) = 1;\n%       fv = isosurface(tmpvol, 0.99);  % Create the patch object\n%       fv.faces = fliplr(fv.faces);    % Ensure normals point OUT\n%       % Test SCATTERED query points\n%       pts = rand(200,3)*12 + 4;       % Make some query points\n%       in = inpolyhedron(fv, pts);     % Test which are inside the patch\n%       figure, hold on, view(3)        % Display the result\n%       patch(fv,'FaceColor','g','FaceAlpha',0.2)\n%       plot3(pts(in,1),pts(in,2),pts(in,3),'bo','MarkerFaceColor','b')\n%       plot3(pts(~in,1),pts(~in,2),pts(~in,3),'ro'), axis image\n%       % Test STRUCTURED GRID of query points\n%       gridLocs = 3:2.1:19;\n%       [x,y,z] = meshgrid(gridLocs,gridLocs,gridLocs);\n%       in = inpolyhedron(fv, gridLocs,gridLocs,gridLocs);\n%       figure, hold on, view(3)        % Display the result\n%       patch(fv,'FaceColor','g','FaceAlpha',0.2)\n%       plot3(x(in), y(in), z(in),'bo','MarkerFaceColor','b')\n%       plot3(x(~in),y(~in),z(~in),'ro'), axis image\n%\n% See also: UNIFYMESHNORMALS (on the <a href=\"http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=43013\">file exchange</a>)\n\n% TODO-list\n% - Optmise overall memory footprint. (need examples with MEM errors)\n% - Implement an \"ignore these\" step to speed up calculations for:\n%     * Query points outside the convex hull of the faces/vertices input\n% - Get a better/best gridSize calculation. User feedback?\n% - Detect cases where X-rays or Y-rays would be better than Z-rays?\n\n%\n%   Author: Sven Holcombe\n% - 10 Jun 2012: Version 1.0\n% - 28 Aug 2012: Version 1.1 - Speedup using accumarray\n% - 07 Nov 2012: Version 2.0 - BEHAVIOUR CHANGE\n%                Query points coincident with a VERTEX are now IN an XY triangle\n% - 18 Aug 2013: Version 2.1 - Gridded query point handling with low memory footprint.\n% - 10 Sep 2013: Version 3.0 - BEHAVIOUR CHANGE \n%                NEW CONVENTION ADOPTED to expect face normals pointing IN\n%                Vertically oriented faces are now ignored. Speeds up\n%                computation and fixes bug where presence of vertical faces\n%                produced NaN distance from a query pt to facet, making all\n%                query points under facet erroneously NOT IN polyhedron.\n% - 25 Sep 2013: Version 3.1 - Dropped nested unique call which was made\n%                mostly redundant via v2.1 gridded point handling. Also\n%                refreshed grid size selection via optimisation.\n% - 25 Feb 2014: Version 3.2 - Fixed indeterminate behaviour for query \n%                points *exactly* in line with an \"overhanging\" vertex.\n%%\n\n% FACETS is an unpacked arrangement of faces/vertices. It is [3-by-3-by-N],\n% with 3 1-by-3 XYZ coordinates of N faces.\n[facets, qPts, options] = parseInputs(varargin{:});\nnumFaces = size(facets,3);\nif ~options.griddedInput            % SCATTERED QUERY POINTS\n    numQPoints = size(qPts,1);\nelse                                % STRUCTURED QUERY POINTS\n    numQPoints = prod(cellfun(@numel,qPts(1:2)));\nend\n\n% Precompute 3d normals to all facets (triangles). Do this via the cross\n% product of the first edge vector with the second. Normalise the result.\nallEdgeVecs = facets([2 3 1],:,:) - facets(:,:,:);\nif isempty(options.facenormals)\n    allFacetNormals =  bsxfun(@times, allEdgeVecs(1,[2 3 1],:), allEdgeVecs(2,[3 1 2],:)) - ...\n        bsxfun(@times, allEdgeVecs(2,[2 3 1],:), allEdgeVecs(1,[3 1 2],:));\n    allFacetNormals = bsxfun(@rdivide, allFacetNormals, sqrt(sum(allFacetNormals.^2,2)));\nelse\n    allFacetNormals = permute(options.facenormals,[3 2 1]);\nend\nif options.flipnormals\n    allFacetNormals = -allFacetNormals;\nend\n% We use a Z-ray intersection so we don't even need to consider facets that\n% are purely vertically oriented (have zero Z-component).\nisFacetUseful = allFacetNormals(:,3,:) ~= 0;\n\n%% Setup grid referencing system\n% Function speed can be thought of as a function of grid size. A small number of grid\n% squares means iterating over fewer regions (good) but with more faces/qPts to\n% consider each time (bad). For any given mesh/queryPt configuration, there will be a\n% sweet spot that minimises computation time. There will also be a constraint from\n% memory available - low grid sizes means considering many queryPt/faces at once,\n% which will require a larger memory footprint. Here we will let the user specify\n% gridsize directly, or we will estimate the optimum size based on prior testing.\nif ~isempty(options.gridsize)\n    gridSize = options.gridsize;\nelse\n    % Coefficients (with 95% confidence bounds):\n    p00 =         -47;    p10 =       12.83;    p01 =       20.89;\n    p20 =      0.7578;    p11 =      -6.511;    p02 =      -2.586;\n    p30 =     -0.1802;    p21 =      0.2085;    p12 =      0.7521;\n    p03 =     0.09984;    p40 =    0.005815;    p31 =    0.007775;\n    p22 =    -0.02129;    p13 =    -0.02309;\n    GSfit = @(x,y)p00 + p10*x + p01*y + p20*x^2 + p11*x*y + p02*y^2 + p30*x^3 + p21*x^2*y + p12*x*y^2 + p03*y^3 + p40*x^4 + p31*x^3*y + p22*x^2*y^2 + p13*x*y^3;\n    gridSize = min(150 ,max(1, ceil(GSfit(log(numQPoints),log(numFaces)))));\n    if isnan(gridSize), gridSize = 1; end\nend\n\n%% Find candidate qPts -> triangles pairs\n% We have a large set of query points. For each query point, find potential\n% triangles that would be pierced by vertical rays through the qPt. First,\n% a simple filter by XY bounding box\n\n% Calculate the bounding box of each facet\nminFacetCoords = permute(min(facets(:,1:2,:),[],1),[3 2 1]);\nmaxFacetCoords = permute(max(facets(:,1:2,:),[],1),[3 2 1]);\n\n% Set rescale values to rescale all vertices between 0(-eps) and 1(+eps)\nscalingOffsetsXY = min(minFacetCoords,[],1) - eps;\nscalingRangeXY = max(maxFacetCoords,[],1) - scalingOffsetsXY + 2*eps;\n\n% Based on scaled min/max facet coords, get the [lowX lowY highX highY] \"grid\" index\n% of all faces\nlowToHighGridIdxs = floor(bsxfun(@rdivide, ...\n    bsxfun(@minus, ... % Use min/max coordinates of each facet (+/- the tolerance)\n    [minFacetCoords-options.tol maxFacetCoords+options.tol],...\n    [scalingOffsetsXY scalingOffsetsXY]),...\n    [scalingRangeXY scalingRangeXY]) * gridSize) + 1;\n\n% Build a grid of cells. In each cell, place the facet indices that encroach into\n% that grid region. Similarly, each query point will be assigned to a grid region.\n% Note that query points will be assigned only one grid region, facets can cover many\n% regions. Furthermore, we will add a tolerance to facet region assignment to ensure\n% a query point will be compared to facets even if it falls only on the edge of a\n% facet's bounding box, rather than inside it.\ncells = cell(gridSize);\n[unqLHgrids,~,facetInds] = unique(lowToHighGridIdxs,'rows');\ntmpInds = accumarray(facetInds(isFacetUseful),find(isFacetUseful),[size(unqLHgrids,1),1],@(x){x});\nfor xi = 1:gridSize\n    xyMinMask = xi >= unqLHgrids(:,1) & xi <= unqLHgrids(:,3);\n    for yi = 1:gridSize\n        cells{yi,xi} = cat(1,tmpInds{xyMinMask & yi >= unqLHgrids(:,2) & yi <= unqLHgrids(:,4)});\n        % The above line (with accumarray) is faster with equiv results than:\n        % % cells{yi,xi} = find(ismember(facetInds, xyInds));\n    end\nend\n% With large number of facets, memory may be important:\nclear lowToHightGridIdxs LHgrids facetInds tmpInds xyMinMask minFacetCoords maxFacetCoords\n\n%% Compute edge unit vectors and dot products\n\n% Precompute the 2d unit vectors making up each facet's edges in the XY plane.\nallEdgeUVecs = bsxfun(@rdivide, allEdgeVecs(:,1:2,:), sqrt(sum(allEdgeVecs(:,1:2,:).^2,2)));\n\n% Precompute the inner product between edgeA.edgeC, edgeB.edgeA, edgeC.edgeB\nallEdgeEdgeDotPs = sum(allEdgeUVecs .* -allEdgeUVecs([3 1 2],:,:),2) - 1e-9;\n\n%% Gather XY query locations\n% Since query points are most likely given as a (3D) grid of query locations, we only\n% need to consider the unique XY locations when asking which facets a vertical ray\n% through an XY location would pierce.\nif ~options.griddedInput            % SCATTERED QUERY POINTS\n    qPtsXY = @(varargin)qPts(:,1:2);\n    qPtsXYZViaUnqIndice = @(ind)qPts(ind,:);\n    outPxIndsViaUnqIndiceMask = @(ind,mask)ind(mask);\n    outputSize = [size(qPts,1),1];\n    reshapeINfcn = @(INMASK)INMASK;\n    minFacetDistanceFcn = @minFacetToQptDistance;\nelse                                % STRUCTURED QUERY POINTS\n    [xmat,ymat] = meshgrid(qPts{1:2});\n    qPtsXY = [xmat(:) ymat(:)];\n    % A standard set of Z locations will be shifted around by different\n    % unqQpts XY coordinates.\n    zCoords = qPts{3}(:) * [0 0 1];\n    qPtsXYZViaUnqIndice = @(ind)bsxfun(@plus, zCoords, [qPtsXY(ind,:) 0]);\n    % From a given indice and mask, we will turn on/off the IN points under\n    % that indice based on the mask. The easiest calculation is to setup\n    % the IN matrix as a numZpts-by-numUnqPts mask. At the end, we must\n    % unpack/reshape this 2D mask to a full 3D logical mask\n    numZpts = size(zCoords,1);\n    baseZinds = 1:numZpts;\n    outPxIndsViaUnqIndiceMask = @(ind,mask)(ind-1)*numZpts + baseZinds(mask);\n    outputSize = [numZpts, size(qPtsXY,1)];\n    reshapeINfcn = @(INMASK)reshape(INMASK', cellfun(@numel, qPts([2 1 3])));\n    minFacetDistanceFcn = @minFacetToQptsDistance;\nend\n\n% Start with every query point NOT inside the polyhedron. We will\n% iteratively find those query points that ARE inside.\nIN = false(outputSize);\n% Determine with grids each query point falls into.\nqPtGridXY = floor(bsxfun(@rdivide, bsxfun(@minus, qPtsXY(:,:), scalingOffsetsXY),...\n    scalingRangeXY) * gridSize) + 1;\n[unqQgridXY,~,qPtGridInds] = unique(qPtGridXY,'rows');\n% We need only consider grid indices within those already set up\nptsToConsidMask = ~any(qPtGridXY<1 | qPtGridXY>gridSize, 2);\nif ~any(ptsToConsidMask)\n    IN = reshapeINfcn(IN);\n    return;\nend\n% Build the reference list\ncellQptContents = accumarray(qPtGridInds(ptsToConsidMask),find(ptsToConsidMask), [],@(x){x});\ngridsToCheck = unqQgridXY(~any(unqQgridXY<1 | unqQgridXY>gridSize, 2),:);\ncellQptContents(cellfun('isempty',cellQptContents)) = [];\ngridIndsToCheck = sub2ind(size(cells), gridsToCheck(:,2), gridsToCheck(:,1));\n\n% For ease of multiplication, reshape qPt XY coords to [1-by-2-by-1-by-N]\nqPtsXY = permute(qPtsXY(:,:),[4 2 3 1]);\n\n% There will be some grid indices with query points but without facets.\nemptyMask = cellfun('isempty',cells(gridIndsToCheck))';\nfor i = find(~emptyMask)\n    % We get all the facet coordinates (ie, triangle vertices) of triangles\n    % that intrude into this grid location. The size is [3-by-2-by-N], for\n    % the [3vertices-by-XY-by-Ntriangles]\n    allFacetInds = cells{gridIndsToCheck(i)};\n    candVerts = facets(:,1:2,allFacetInds);\n    % We need the XY coordinates of query points falling into this grid.\n    allqPtInds = cellQptContents{i};\n    queryPtsXY = qPtsXY(:,:,:,allqPtInds);\n\n    % Get unit vectors pointing from each triangle vertex to my query point(s)\n    vert2ptVecs = bsxfun(@minus, queryPtsXY, candVerts);\n    vert2ptUVecs = bsxfun(@rdivide, vert2ptVecs, sqrt(sum(vert2ptVecs.^2,2)));\n    % Get unit vectors pointing around each triangle (along edge A, edge B, edge C)\n    edgeUVecs = allEdgeUVecs(:,:,allFacetInds);\n    % Get the inner product between edgeA.edgeC, edgeB.edgeA, edgeC.edgeB\n    edgeEdgeDotPs = allEdgeEdgeDotPs(:,:,allFacetInds);\n    % Get inner products between each edge unit vec and the UVs from qPt to vertex\n    edgeQPntDotPs = sum(bsxfun(@times, edgeUVecs, vert2ptUVecs),2);\n    qPntEdgeDotPs = sum(bsxfun(@times,vert2ptUVecs, -edgeUVecs([3 1 2],:,:)),2);\n    % If both inner products 2 edges to the query point are greater than the inner\n    % product between the two edges themselves, the query point is between the V\n    % shape made by the two edges. If this is true for all 3 edge pair, the query\n    % point is inside the triangle.\n    resultIN = all(bsxfun(@gt, edgeQPntDotPs, edgeEdgeDotPs) & bsxfun(@gt, qPntEdgeDotPs, edgeEdgeDotPs),1);\n    resultONVERTEX = any(any(isnan(vert2ptUVecs),2),1);\n    result = resultIN | resultONVERTEX;\n    qPtHitsTriangles = any(result,3);\n    % If NONE of the query points pierce ANY triangles, we can skip forward\n    if ~any(qPtHitsTriangles), continue, end\n\n    % In the next step, we'll need to know the indices of ALL the query points at\n    % each of the distinct XY coordinates. Let's get their indices into \"qPts\" as a\n    % cell of length M, where M is the number of unique XY points we had found.\n    for ptNo = find(qPtHitsTriangles(:))'\n        % Which facets does it pierce?\n        piercedFacetInds = allFacetInds(result(1,1,:,ptNo));\n        \n        % Get the 1-by-3-by-N set of triangle normals that this qPt pierces       \n        piercedTriNorms = allFacetNormals(:,:,piercedFacetInds);\n        \n        % Pick the first vertex as the \"origin\" of a plane through the facet. Get the\n        % vectors from each query point to each facet origin\n        facetToQptVectors = bsxfun(@minus, ...\n            qPtsXYZViaUnqIndice(allqPtInds(ptNo)),...\n            facets(1,:,piercedFacetInds));\n        \n        % Calculate how far you need to go up/down to pierce the facet's plane.\n        % Positive direction means \"inside\" the facet, negative direction means\n        % outside.\n        facetToQptDists = bsxfun(@rdivide, ...\n            sum(bsxfun(@times,piercedTriNorms,facetToQptVectors),2), ...\n            abs(piercedTriNorms(:,3,:)));\n        \n        % Since it's possible for two triangles sharing the same vertex to\n        % be the same distance away, I want to sum up all the distances of\n        % triangles that are closest to the query point. Simple case: The\n        % closest triangle is unique Edge case: The closest triangle is one\n        % of many the same distance and direction away. Tricky case: The\n        % closes triangle has another triangle the equivalent distance\n        % but facing the opposite direction\n        IN( outPxIndsViaUnqIndiceMask(allqPtInds(ptNo), ...\n            minFacetDistanceFcn(facetToQptDists)<options.tol...\n            )) = true;\n    end\nend\n\n% If they provided X,Y,Z vectors of query points, our output is currently a\n% 2D mask and must be reshaped to [LEN(Y) LEN(X) LEN(Z)].\nIN = reshapeINfcn(IN);\n\n%% Called subfunctions\n\n% vertices = [\n%     0.9046    0.1355   -0.0900\n%     0.8999    0.3836   -0.0914\n%     1.0572    0.2964   -0.0907\n%     0.8735    0.1423   -0.1166\n%     0.8685    0.4027   -0.1180\n%     1.0337    0.3112   -0.1173\n%     0.9358    0.1287   -0.0634\n%     0.9313    0.3644   -0.0647\n%     1.0808    0.2816   -0.0641\n% ];\n% faces = [\n%      1     2     5\n%      1     5     4\n%      2     3     6\n%      2     6     5\n%      3     1     4\n%      3     4     6\n%      6     4     5\n%      2     1     8\n%      8     1     7\n%      3     2     9\n%      9     2     8\n%      1     3     7\n%      7     3     9\n%      7     9     8\n% ];\n% point = [vertices(3,1),vertices(3,2),1.5];\n\n\nfunction closestTriDistance = minFacetToQptDistance(facetToQptDists)\n% FacetToQptDists is a 1pt-by-1-by-Nfacets array of how far you need to go\n% up/down to pierce each facet's plane. If the Qpt was directly over an\n% \"overhang\" vertex, then two facets with opposite orientation will be\n% equally distant from the Qpt, with one distance positive and one\n% negative. In such cases, it is impossible for the Qpt to actually be\n% \"inside\" this pair of facets, so their distance is updated to Inf.\n\n[~,minInd] = min(abs(facetToQptDists),[],3);\nwhile any( abs(facetToQptDists + facetToQptDists(minInd)) < 1e-15 )\n    % Since the above comparison is made every time, but the below variable\n    % setting is done only in the rare case that a query point coincides\n    % with an overhang vertex, it is more efficient to re-compute the\n    % equality when it's true, rather than store the result every time.\n    facetToQptDists( abs(facetToQptDists) - abs(facetToQptDists(minInd)) < 1e-15) = inf;\n    if ~any(isfinite(facetToQptDists))\n        break;\n    end\n    [~,minInd] = min(abs(facetToQptDists),[],3);\nend\nclosestTriDistance = facetToQptDists(minInd);\n\nfunction closestTriDistance = minFacetToQptsDistance(facetToQptDists)\n% As above, but facetToQptDists is an Mpts-by-1-by-Nfacets array.\n\n% The multi-point version is a little more tricky. While below is quite a\n% bit slower when the while loop is entered, it is very rarely entered and\n% very fast to make just the initial comparison.\n[minVals,minInds] = min(abs(facetToQptDists),[],3);\nwhile any(...\n        any(abs(bsxfun(@plus,minVals,facetToQptDists))<1e-15,3) & ...\n        any(abs(bsxfun(@minus,minVals,facetToQptDists))<1e-15,3))\n    maskP = abs(bsxfun(@plus,minVals,facetToQptDists))<1e-15;\n    maskN = abs(bsxfun(@minus,minVals,facetToQptDists))<1e-15;\n    mustAlterMask = any(maskP,3) & any(maskN,3);\n    for i = find(mustAlterMask)'\n        facetToQptDists(i,:,maskP(i,:,:) | maskN(i,:,:)) = inf;\n    end\n    [newMv,newMinInds] = min(abs(facetToQptDists(mustAlterMask,:,:)),[],3);\n    minInds(mustAlterMask) = newMinInds(:);\n    minVals(mustAlterMask) = newMv(:);\nend\n% Below is a tiny speedup on basically a sub2ind call.\nclosestTriDistance = facetToQptDists((minInds-1)*size(facetToQptDists,1) + (1:size(facetToQptDists,1))');\n\n%% Input handling subfunctions\nfunction [facets, qPts, options] = parseInputs(varargin)\n    \n% Gather FACES and VERTICES\nif isstruct(varargin{1})                        % inpolyhedron(FVstruct, ...)\n    if ~all(isfield(varargin{1},{'vertices','faces'}))\n        error( 'Structure FV must have \"faces\" and \"vertices\" fields' );\n    end\n    faces = varargin{1}.faces;\n    vertices = varargin{1}.vertices;\n    varargin(1) = []; % Chomp off the faces/vertices\n    \nelse                                            % inpolyhedron(FACES, VERTICES, ...)\n    faces = varargin{1};\n    vertices = varargin{2};\n    varargin(1:2) = []; % Chomp off the faces/vertices\nend\n\n% Unpack the faces/vertices into [3-by-3-by-N] facets. It's better to\n% perform this now and have FACETS only in memory in the main program,\n% rather than FACETS, FACES and VERTICES\nfacets = vertices';\nfacets = permute(reshape(facets(:,faces'), 3, 3, []),[2 1 3]);\n\n% Extract query points\nif length(varargin)<2 || ischar(varargin{2})    % inpolyhedron(F, V, [x(:) y(:) z(:)], ...)\n    qPts = varargin{1};\n    varargin(1) = []; % Chomp off the query points\nelse                                            % inpolyhedron(F, V, xVec, yVec, zVec, ...)\n    qPts = varargin(1:3);\n    % Chomp off the query points and tell the world that it's gridded input.\n    varargin(1:3) = [];\n    varargin = [varargin {'griddedInput',true}];\nend\n    \n% Extract configurable options\noptions = parseOptions(varargin{:});\n\n% Check if face normals are unified\nif options.testNormals\n    options.normalsAreUnified = checkNormalUnification(faces);\nend\n\nfunction options = parseOptions(varargin)\nIP = inputParser;\nIP.addParamValue('gridsize',[], @(x)isscalar(x) && isnumeric(x))\nIP.addParamValue('tol', 0, @(x)isscalar(x) && isnumeric(x))\nIP.addParamValue('tol_ang', 1e-5, @(x)isscalar(x) && isnumeric(x))\nIP.addParamValue('facenormals',[]);\nIP.addParamValue('flipnormals',false);\nIP.addParamValue('griddedInput',false);\nIP.addParamValue('testNormals',false);\nIP.parse(varargin{:});\noptions = IP.Results;", "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/toolbox/inpolyhedron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5501761614547359}}
{"text": "function init_params = init_coeffs(x,y)\n% INIT_COEFFS Function to generate the initial parameters for the 4\n% parameter dose response curve.\n% Requires an array of doses and an array of responses\n% This function is used by sigmoid.m and ec50.m\n%\n% Copyright 2004 Carlos Evangelista \n% send comments to CCEvangelista@aol.com\n% Version 1.0    01/07/2004\n\nparms=ones(1,4);\nparms(1)=min(y);\nparms(2)=max(y);\nparms(3)=(min(x)+max(x))/2;\nsizey=size(y);\nsizex=size(x);\nif (y(1)-y(sizey))./(x(2)-x(sizex))>0\n    parms(4)=(y(1)-y(sizey))./(x(2)-x(sizex));\nelse\n    parms(4)=1;\nend\ninit_params=parms;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4363-doseresponse/init_coeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5501761583534311}}
{"text": "%% patchThick\n% Below is a demonstration of the features of the |patchThick| function\n\n%% Syntax\n% |[E,VE,Fq1,Fq2]=patchThick(F,V,dirSet,layerThickness,numSteps);|\n\n%% Description\n% Use |patchThick| to thicken a quadrilateral mesh to create hexahedral\n% elements.  \n\n%%\n\nclear; close all; clc;\n\n%% Examples\n\n%%\n% PLOT SETTINGS\nfontSize=20;\n\n%% Example: Using |patchThick| to thicken quads into hexahedra\n\n%%\n% Creating an example polygon\nns=15;\nt=linspace(0,pi,ns);\nx=cos(t);\ny=sin(t);\nz=zeros(size(x));\nVc=flipud([x(:) y(:) z(:)]);\n\n%%\n% Extruding polygon to a quadrilateral surface\ncPar.depth=2; \ncPar.patchType='quad'; \ncPar.dir=0;\ncPar.closeLoopOpt=0; \ncPar.numSteps=8;\n[F,V]=polyExtrude(Vc,cPar);\n\n%% \n% Thickening quadrilaterial elements to hexahedral elements\nlayerThickness=0.5; \nnumSteps=3; \n[E,VE]=patchThick(F,V,1,layerThickness,numSteps);\n\n%Use element2patch to get patch data \nFE=element2patch(E);\n\n%%\n% Visualize mesh\n\ncFigure; hold on;\ntitle('Hexahedral mesh');\ngpatch(FE,VE,'bw','k',1);\naxisGeom;\ncamlight headlight;\ndrawnow;\n\n%% Example: Using |patchThick| to thicken triangles into pentahedra\n\n%%\n% Create test data set\n[F,V,C]=hemiSphereMesh(1,1,0);\nV(:,3)=-V(:,3);\nF=fliplr(F);\n\n\n%% \n% Thickening quadrilaterial surface to hexahedral elements\nlayerThickness=0.4; \nnumSteps=2; \n[E,VE,Fq1,Fq2]=patchThick(F,V,1,layerThickness,numSteps);\n\n%Use element2patch to get patch data \nFE=element2patch(E,[],'penta6');\n\n%%\n% Visualize mesh\n\ncFigure; hold on;\ntitle('Pentahedral mesh');\ngpatch(FE,VE,'bw','k',1);\n% patchNormPlot(FE,VE);\naxisGeom;\ncamlight headlight;\ndrawnow;\n\n%% Example: Using |patchThick| to thicken a mixed mesh of quads and triangles\n\n%%\n% Create test data set\n[F,V,C]=hemiSphereMesh(1,1,0);\nV(:,3)=-V(:,3);\nF=fliplr(F);\n\n%% \n% Convert to mixed mesh\noptionStruct.maxAngleDeviation=90*(pi/180);\noptionStruct.selectionMethod='best';\noptionStruct.triangleConvert=0;\noptionStruct.fourConnectConvert=0;\n[F,V]=tri2quadGroupSplit(F,V,optionStruct);\n\n%% \n% Thickening quadrilaterial surface to hexahedral elements\nlayerThickness=0.4; \nnumSteps=2; \n[E,VE,Fq1,Fq2]=patchThick(F,V,1,layerThickness,numSteps);\n\n%Use element2patch to get patch data \nFE=E;\nfor q=1:1:numel(E)\n    if size(E{q},2)==6\n        elementType='penta6';\n    elseif size(E{q},2)==8\n        elementType='hex8';\n    end\n    FE{q}=element2patch(E{q},[],elementType);\nend\n\n%%\n% Visualize mesh\n\ncFigure; hold on;\ntitle('Mixed hexahedral-pentahedral mesh');\nfor q=1:1:numel(FE)\n    gpatch(FE{q},VE,'bw','k',1);\nend\n% patchNormPlot(FE,VE);\naxisGeom;\ncamlight headlight;\ndrawnow;\n\n\n%% \n%\n% <<gibbVerySmall.gif>>\n% \n% _*GIBBON*_ \n% <www.gibboncode.org>\n% \n% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: <https://github.com/gibbonCode/GIBBON/blob/master/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 <http://www.gnu.org/licenses/>.\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_patchThick.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5501761545855851}}
{"text": "function [varargout]=tricontf(varargin);\n% TRICONT  Filled contours data on a triangular mesh\n%     [CS,h]=TRICONTF(X,Y,M,Z) takes the mesh specified by points\n%     (X,Y), with heights Z, and the  Nx3 triangulation M (where\n%     each row gives the indexes into X/Y vectors of the triangle\n%     corners), and make filled contours.    \n%\n%     TRICONTF(...,LEVELS) fills contours at the specified levels.\n%     \n%   \n%     TRICONTF(...,LINESPEC) takes line style and colour\n%     parameters for the lines.\n%\n%     [CS,h] are the inputs needed by CLABEL, but if you want\n%     labelled contours you are better off doing something like\n%     \n%\n%     [CS,h]=TRICONTF(...);\n%     set(h,'edgecolor','none');\n%     hold on;\n%     [CS,h]=TRICONT(...);\n%     hold off\n%     clabel(CS,h)\n%\n%     since the CS and h returned by TRICONTF contain boundary \n%     information which is not usually required for labelling.\n%     \n%     The advantage of using TRICONTF over the GRIDDATA method is the\n%     the triangulation is already specified (and may be non-convex\n%     as well as containing holes), and the contours are also exact\n%     on the triangulation (no weird boundary jaggies). However,\n%     LINEAR finite elements are assumed.\n%     \n%     Note - unlike contourf, TRICONTF will not\n%     work 'properly' with NaN values in Z - if you\n%     have bad data remove those triangles from M!\n%\n%     See also TRICONT\n%\n%     Rich Pawlowicz (rpawlowicz@eos.ubc.ca)  March/2013\n%\n\n\n% Copy a bunch of lines from contourf\nerror(nargchk(4,9,nargin,'struct'));\n[cax,args,nargs] = axescheck(varargin{:});\n\n\ncax = newplot(cax);\n \n% Check for empty arguments.\nfor i = 1:nargs\n  if isempty(args{i})\n    error('MATLAB:contourf:EmptyInput','Input argument is empty');\n  end\nend\n\n\n% Trim off the last arg if it's a string (line_spec).\nnin = nargs;\nif ischar(args{end})\n  [lin,col,mark,msg] = colstyle(args{end}); %#ok\n  if ~isempty(msg), error(msg); end %#ok\n  nin = nin - 1;\nelse\n  lin = '';\n  col = '';\nend\n\n\n% Closed contours are made up of a) contours through the\n% interior, and b) curves around the grid boundaries (there\n% can be interior \"islands\" in an FEM mesh too).  The\n% general strategy is to get a bunch of line segments, and\n% then join them into continuous curves.\n\n% First, get all the interior contours (this is pretty fast)\n% but don't draw anything yet; this also does some checking\n% on M to make sure triangles are oriented.\n\n[Xp,Yp,M,Zp,nv,CS,xx,yy,zz]=tricont(args{1:nin});\nnCS=[find(isnan(CS(2,:))) size(CS,2)+1];\nlCS=CS(1,nCS(1:end-1));\n\n% Don't fill contours below the lowest level specified in nv.\n% To fill all contours, specify a value of nv lower than the\n% minimum of the surface. \ni = find(isfinite(Zp));\nminz = min(Zp(i));\nmaxz = max(Zp(i));\ndraw_min=0;\nif any(nv <= minz),\n  draw_min=1;\nend\n\n\n% Second step - get all the boundary curves. \n\nBS=findboundary(M);\niBS=find(isnan(BS));\n\n  \n% Third step:\n% Once we have interior and boundary curves, join *them* together.\n% However, we have to have separate boundary curves for every\n% level, because we need only the parts of the boundary where the\n% interior is higher than that level.\n\n\nfCS=NaN(2,size(CS,2)+size(BS,2));iCS=1;\nncurves = 0;\nI = [];\nArea=[];levs=[];\n\nfor l=1:length(nv),   % For each level\n\n  \n  lvlBS=NaN(2,length(CS)+length(BS)+50);jBS=1;\n\n  iCSlvl=find(lCS==nv(l));\n  if any(iCSlvl),\n  \n     % Create a structure with all the lines at level\n     % nv(k). First add the interior contours\n     \n\n     for k=1:length(iCSlvl),\n       nseg=nCS(iCSlvl(k)+1)-nCS(iCSlvl(k))-1;\n       level=CS(1,nCS(iCSlvl(k)));\n       xseg=CS(1,nCS(iCSlvl(k))+[1:nseg]);\n       yseg=CS(2,nCS(iCSlvl(k))+[1:nseg]);\n       lvlBS(:,jBS+[0:nseg])=[ nv(l) xseg ; NaN yseg ];\n       jBS=jBS+1+nseg;\n     end;   \n  end;\n  \n     % Now look through all the boundaries, and for each boundary segment\n     % take only the parts that are higher than nv(l). In general we will\n     % have to interpolate to get the first and last position of the curve,\n     % except when it it as the beginning or end of a boundary curve.\n     \n     for k=1:length(iBS)-1,\n       Bseg=BS(iBS(k)+1:iBS(k+1)-1);\n       id=Zp(Bseg)>nv(l);\n             \n       segstart=find(diff(id)== 1)+1;\n       if id(1)==1,segstart=[1;segstart]; end;\n       segend=  find(diff(id)==-1);\n       if id(end)==1,segend=[segend;length(Bseg)]; end;\n\n       for m=1:length(segstart),\n\t if segstart(m)==1,  % First point is above...\n\t   xstart=[];\n\t   ystart=[];\n\t else                % ...otherwise interpolate it\n\t   xstart=(Xp(Bseg(segstart(m)))*(nv(l)-Zp(Bseg(segstart(m)-1))) + Xp(Bseg(segstart(m)-1))*(Zp(Bseg(segstart(m)))-nv(l)) )./(Zp(Bseg(segstart(m)))-Zp(Bseg(segstart(m)-1)));\n\t   ystart=(Yp(Bseg(segstart(m)))*(nv(l)-Zp(Bseg(segstart(m)-1))) + Yp(Bseg(segstart(m)-1))*(Zp(Bseg(segstart(m)))-nv(l)) )./(Zp(Bseg(segstart(m)))-Zp(Bseg(segstart(m)-1)));\n\t end;\n\t if segend(m)==length(Bseg),  % Last point is above....\n\t   xend=[];\n\t   yend=[];\n\t else;               % ...otherwise interpolate it.\n\t   xend=(Xp(Bseg(segend(m)+1))*(nv(l)-Zp(Bseg(segend(m)    ))) + Xp(Bseg(segend(m)    ))*(Zp(Bseg(segend(m)+1))-nv(l)) )./(Zp(Bseg(segend(m)+1))-Zp(Bseg(segend(m)    ))) ;\n\t   yend=(Yp(Bseg(segend(m)+1))*(nv(l)-Zp(Bseg(segend(m)    ))) + Yp(Bseg(segend(m)    ))*(Zp(Bseg(segend(m)+1))-nv(l)) )./(Zp(Bseg(segend(m)+1))-Zp(Bseg(segend(m)    )));\n\t end; \n         xseg=[ xstart , Xp(Bseg(segstart(m):segend(m)))' , xend ];\n         yseg=[ ystart , Yp(Bseg(segstart(m):segend(m)))' , yend ];\n\t lvlBS(:,jBS+[0:length(xseg)])=[ nv(l) xseg ; NaN yseg ];\n         jBS=jBS+1+length(xseg);\n        end;\n      end;\n      lvlBS(:,jBS+1:end)=[];\n          \n      ii=find(isnan(lvlBS(2,:)));\n \n \n      % Now, apply the line joing algorithm *again* to put the different curves together\n      % into a bunch of closed curves.\n\n      % Begin and end of all line segments\n      x2=[lvlBS(1,ii(1:end-1)+1) ; lvlBS(1,ii(2:end)-1) ];\n      y2=[lvlBS(2,ii(1:end-1)+1) ; lvlBS(2,ii(2:end)-1) ];\n    \n      iZ=ones(1,size(x2,2));\n      iN=1;\n      iZ(iN)=0;\n      seg=iN;\n      rev1=1;rev2=2;  % keeps track of which direction to add points\n       while any(iN),\n\n\t% Any line segments with the same endpoint that aren't used?\n\t% Use == for real numbers because the end points are calculated using\n\t% the same formula and hence should be exactly the same\n\tiN=find( x2(rev1,:)==x2(rev2,iN) & y2(rev1,:)==y2(rev2,iN) & iZ,1);\n\n\tif any(iN),  % If yes...\n\t  seg=[seg iN];  % Add it to the segment list...\n\t  iZ(iN)=0;      % ...and mark it used\n\telse         % If none...\n\t  if rev1==1;  % If we haven't searched backwards yet\n            iN=seg(1);  % Take the other end of the lines\n            seg=seg(end:-1:1); % Reverse the segment list\n            rev1=2;rev2=1;\n\t  else         % we *have* searched backwards, and it really is the end\n\t    xseg=[];yseg=[];\n\t    for k=1:length(seg),\n\t      xseg=[lvlBS(1,ii(seg(k))+1:ii(seg(k)+1)-1) xseg];\n\t      yseg=[lvlBS(2,ii(seg(k))+1:ii(seg(k)+1)-1) yseg];\n\t    end;\n\n\t    fCS(:,iCS)=[nv(l);length(xseg)];\n\t    fCS(:,iCS+[1:length(xseg)])=[xseg ;yseg];\n\n            % need these stats later\n\t    ncurves = ncurves + 1;\n            levs(ncurves)=nv(l);\n            I(ncurves) = iCS;\n            Area(ncurves)=sum( diff(xseg).*(yseg(1:end-1)+yseg(2:end))/2 );\n\n\t    iCS=iCS+1+length(xseg);\n\n            iN=find(iZ,1); % ...and go find the next unused segment\n\t    seg=iN;\n            iZ(iN)=0;\n            rev1=1;rev2=2;   % ...and search forward.\n\t  end;\t\t\n\tend;\n      end; \n\n   \nend;\nfCS(:,iCS:end)=[];\n\n\n% OK, now we have all the closed curves formed.\n\n\n% Plot patches in order of decreasing size. This makes sure that\n% all the levels get drawn, not matter if we are going up a hill or\n% down into a hole. When going down we shift levels though, you can\n% tell whether we are going up or down by checking the sign of the\n% area (since curves are oriented so that the high side is always\n% the same side). Lowest curve is largest and encloses higher data\n% always.\n\n% The areas of 'interior holes' will be the same at all\n% levels, as will any levels that go all around the outside (which will\n% happen if there are interior valleys, which causes a problem (this \n% didn't happen in contourf because boundary-finding was\n% done differently) so we use sortrows to make sure the highest level\n% gets drawn on top for positive areas (i.e. hills), but the lowest\n% level gets drawn on top for NEGATIVE areas (holes).\n\n%[FA,IA]=sort(-abs(Area));  \n[FA,IA]=sortrows([-abs(Area)' (sign(Area).*levs)']);\n\n% below here code is basically identical to contourf\n\n\nif ~ishold(cax),\n    view(cax,2);\n    set(cax,'Box','on','Layer','top');\n    grid(cax,'off')\nend\n\nfig = ancestor(cax,'figure');\nH=[];\n\n% This is the colour for holes\nif ~ischar(get(cax,'color'))\n  bg = get(cax,'color');\nelse\n  bg = get(fig,'color');\nend\n\nif isempty(col)\n  edgec = get(fig,'defaultsurfaceedgecolor');\nelse\n  edgec = col;\nend\nif isempty(lin)\n  edgestyle = get(fig,'defaultpatchlinestyle');\nelse\n  edgestyle = lin;\nend\n\n \nfor jj=IA',\n  nl=fCS(2,I(jj));\n  lev=fCS(1,I(jj));\n  if (lev ~= minz || draw_min ),\n    xp=fCS(1,I(jj)+(1:nl));  \n    yp=fCS(2,I(jj)+(1:nl));\n    clev = lev;           % color for filled region above this level\n    if (sign(Area(jj)) ~=sign(Area(IA(1))) ),\n      kk=find(nv==lev);\n      kk0 = 1 + sum(nv<=minz) * (~draw_min);\n      if (kk > kk0)\n        clev=nv(kk-1);    % in valley, use color for lower level\n      elseif (kk == kk0)\n        clev=NaN;\n      else \n        clev=NaN;         % missing data section\n        lev=NaN;\n      end\n    end\n\n    if (isfinite(clev)),\n      H=[H;patch(xp,yp,clev,'facecolor','flat','edgecolor',edgec, ...\n              'linestyle',edgestyle,'userdata',lev,'parent',cax)];\n    else\n      H=[H;patch(xp,yp,clev,'facecolor',bg,'edgecolor',edgec, ...\n              'linestyle',edgestyle,'userdata',fCS(1,I(jj)),'parent',cax)];\n    end\n  end;\nend;\n\n% Contourf strips out bnoundary points but I can't be bothered - if you\n% want labelled contours you should really follow a tricontf call with\n% a tricont call.\n  \nvarargout={fCS,H};\n\n%-----------------------------------------------------------------\nfunction BS=findboundary(M);\n% Finds the curves that make up the\n% boundary of a triangulation\n%\n% First, examining ALL 2 point line segments in M \n% to see if they are contained in one or\n% two triangles in the mesh! This is slow.\n%\nlenM=size(M,1);\n\n \n%Bseg=NaN(2,lenM);iB=1;\n%\n%pat=[1 2;  % Edge indices in order when triangles \n%     2 3;  % are arranged CW\n%     3 1];\n%for k=1:lenM,\n% for l=1:3,\n%    [id,jid]  =find( (      M==M(k,pat(l,1))) );\n%    [id2,jid2]=find( (M(id,:)==M(k,pat(l,2))) );\n%    if length(id2)==1,\n%      Bseg(:,iB)=M(k,pat(l,:))';\n%      iB=iB+1;\n%    end;\n% end;\n%end;\n%Bseg(:,iB:end)=[];\n\n \n% Try another way - this works MUCH MUCH faster\n% (can be many orders of magnitude faster for large\n% problems!), but will fail if the mesh is screwy\n% (i.e. edges do not appear ONLY one or two times\n% in the whole list of triangles()\n\n% Put all the triangle edges in a list\nalledge=[ M(:,[1 2]) ; M(:,[2 3]) ; M(:,[3 1]) ];\n\n% put rows in increasing numerical order, then sort\n% so the rows will either be unique edges, or pairs\n% of edges\n[sortedge,I]=sortrows(sort(alledge,2));\n% Now identify the boundaries between pairs and\n% unique edges - the diff will == 0 between \n% pairs of identical edges\nchges=[1;any(diff(sortedge)~=0,2);1];\n% so find places where we have 1s one after another,\n% since this marks a transition through a unique\n% edge\nibdy=find(diff(chges)==0);\n% ...and now get the original rows, before the\n% numerical sorting\nBseg=alledge(I(ibdy),:)'; % back to original list\n \n% Now I join all the individual boundary segments\n% into a smaller number of actual curves using the\n% follow foward/follow backward algorithm, all curves\n% should traverse with the interior to their right.\n\nBS=NaN(1,length(Bseg)+50);iBS=1;  % preallocate\niZ=ones(1,size(Bseg,2));  % flag to tell me if a line segment has not been added\n                        % to a line\niN=1;\niZ(iN)=0;\nseg=iN;\nrev1=1;rev2=2;  % keeps track of which direction to add points\n                % (differs if I am going forward or backward from a point)\nwhile any(iN),\n\n  % Any line segments with the same endpoint that aren't used?\n  iN=find( Bseg(rev1,:)==Bseg(rev2,iN) & iZ ,1);\n\n  if any(iN),  % If yes...\n    seg=[seg iN];  % Add it to the segment list...\n    iZ(iN)=0;      % ...and mark it used\n  else         % If none...\n    if rev1==1;  % If we haven't searched backwards yet\n      iN=seg(1);  % Take the other end of the lines\n    %  iZ(iN)=0;\n      seg=seg(end:-1:1); % Reverse the segment list\n      rev1=2;rev2=1;\n    else         % we *have* searched backwards, and it really is the end\n      xseg=[Bseg(2,seg),Bseg(1,seg(end))];  % make up the line\n\n      BS(iBS+[0:length(xseg)])=[NaN xseg(end:-1:1) ];\n      iBS=iBS+1+length(xseg);\n\n      iN=find(iZ,1); % ...and go find the next unused segment\n      seg=iN;\n      iZ(iN)=0;\n      rev1=1;rev2=2;   % ...and search forward.\n    end;\t\t\n  end;\nend; \nBS(iBS+1:end)=[];\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/40847-tricontf/tricontf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5501761396299024}}
{"text": "function volr = volresize(vol, newsz, varargin)\n    % volresize(vol, newsz, {interp_type}, {offset_type}\n    interp_type = 1;\n    if nargin >= 3\n        interp_type = varargin{1};\n    end\n    \n    use_offset = 'sample_std';\n    if nargin >= 4\n        use_offset = varargin{2};\n    end\n    \n    tmp = zeros(max(newsz, size(vol))); \n    tmp(1:size(vol,1), 1:size(vol,2), 1:size(vol,3)) = vol;\n    [n1, n2, n3] = ndgrid(1:size(tmp,1), 1:size(tmp,2), 1:size(tmp,3));\n    k = size(vol) ./ newsz;\n%     k = (size(vol)-1) ./ (newsz - 1);\n    \n    %yeah\n    k = size(vol) ./ newsz;\n    if strcmp(use_offset, 'matlab')\n        d = 0.5*(1-k);\n    elseif strcmp(use_offset, 'for_upsampling')\n        d = 0.5 * [1,1,1];\n%         d = [0,0,0];\n    elseif strcmp(use_offset, 'for_upsampling_2')\n        k = (size(vol) - 1) ./ (newsz - 1);\n        k = size(vol)./ newsz;\n        d = 1 - k;\n    elseif strcmp(use_offset, 'sample_std')\n        k = (newsz - 2) ./ (size(vol) - 2);\n        k = (size(vol) - 1) ./ (newsz - 1);\n        d = (1 - k);\n     end\n    \n    \n    T = cat(4, k(1) * n1 - n1 + d(1), k(2) * n2 - n2 + d(2), k(3) * n3 - n3  + d(3));\n    \n%         if any(k < 1)\n%             sgm = 0.00001 + max(k - 1, 0)*1.1;\n%             tmp = imgaussfilt3(tmp, sgm);\n%         end\n   \n%     T = cat(4, (k(1)-1) * n1, (k(2)-1) * n2, (k(3)-1) * n3);\n    \n\n    volr = imdeform3(tmp, T, interp_type);\n    \n    volr = volr(1:newsz(1), 1:newsz(2), 1:newsz(3));\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/volresize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430604060731, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.5501526158728601}}
{"text": "function [lambda] = spm_mci_adjoint_int (U,P,M,V,djdx,tol)\n% Integrate adjoint equation\n% FORMAT [lambda] = spm_mci_adjoint_int (U,P,M,V,djdx,tol)\n%\n% U         Inputs\n% P         Parameters\n% M         Model structure\n% V         states\n% djdx      derivative of log likelihood wrt states\n% tol       tolerances\n%\n% lambda    adjoint parameters, at times M.t\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny and Biswa Sengupta\n% $Id: spm_mci_adjoint_int.m 6548 2015-09-11 12:39:47Z will $\n\ninit_t=M.t(1);\nfinal_t=M.T;\n\ntol.abs=1e-3;\ntol.rel=1e-5;\n\n% parameters for the intergrator\noptions = odeset('AbsTol',tol.abs,'RelTol',tol.rel);\n\n% integrate adjoint equation backwards\nlam_init=zeros(M.n,1);\n[TT, ld] = ode15s(@(t,lam) integrate_adjoints(t,lam,djdx,V,U,P,M),[final_t init_t], lam_init, options);\n\n% interpolate to M.t \n% (Note, interp1q is not accurate enough here\n% as TT typically has less resolution than M.t)\nlambda = interp1(TT,ld,M.t,'spline');\n\nend\n\n%--------------------------------------------------------------------------\nfunction DlDt = integrate_adjoints(t,lam,djdx,V,U,P,M)\n\nNx=M.n;\nDlDt = zeros(Nx,1);\n\n% Interpolate state and dj/dx to current time point\nfor d=1:Nx,\n    local_djdx(d)=interp1q(M.t,djdx(:,d),t);\n    v(d)=interp1q(M.t,V(:,d),t);\nend\n\n% Find nearest time point for which we have pre-computed input\nif isempty(U)\n    ut=[];\nelse\n    [tmp,ind]=min(abs(t-M.t));\n    ut=U(:,ind);\nend\n\n% Evaluate state Jacobian\nif isfield(M,'dfdx')\n    Fx = feval(M.dfdx,v(:),ut,P,M);\nelse\n    Fx = spm_diff(M.f,v(:),ut,P,M,1);\nend\n\nDlDt=local_djdx-lam'*Fx;\nDlDt=DlDt';\n\nend", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/gradients/spm_mci_adjoint_int.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5501525937185123}}
{"text": "function dat= prep_powerspectrum (data, band, varargin)\n%PROC_SPECTRUM -  calculate the power spectrum\n%\n%dat= proc_spectrum(dat, band, <win/N, step>)\n%dat= proc_spectrum(dat, band, <opts>)\n% IN   dat  - data structure of continuous or epoched data\n%      band - frequency band\n%      win  - window for FFT\n%      N    - window width for FFT -> square window, default dat.fs\n%      step - step for window (= # of overlapping samples), default N/2\n%      opt  - struct of options:\n%       .win       - window for FFT, default ones(dat.fs, 1)\n%       .step      - step for window, default N/2\n%       .db_scaled - boolean, if true values are db scaled (10*log10),\n%                    default true\n\n%%\n% data\ndat=data;\nban=band;\nopt=opt_cellToStruct(varargin{:});\nepo=struct('win',[],'N',[],'step',[],'scale',[]);\n\nif isempty(dat)\n    warning('Warning! data is empty');\nend\nif isempty(ban)\n    warning('Band is not exist.');\nend\n\nif ~isfield(opt,'win') \n   epo.win=dat.fs;\nelse\n    epo.win=opt.win;\nend\n\nif ~isfield(opt,'N')\n   epo.N=dat.fs;\nelse\n    epo.N=opt.N;\nend\n\nif ~isfield(opt,'step')\n   epo.step=dat.fs/2;\nelse\n   epo.N=opt.N;\nend\n\nif ~isfield(opt,'scale')\n   epo.scale='db';\nelse\n    epo.scale=opt.scale;\nend\n\n[T, nEvents , nChans]= size(dat.x);\n\nif length(epo.win)==1\n    if epo.win>T\n        warning('window legth is higher than signal')\n    end\n    epo.win=ones(epo.win,1);\nend\nN=length(epo.win);\nnormwin=norm(epo.win);\nFreq=(0:N)/2*dat.fs/N;\n\n%%\nXX= zeros(N, nChans*nEvents);\nnWindows= 1 + max(0, floor((T-N)/epo.step));\niv= 1:min(N, T);\nWin= repmat(epo.win(:), [1 nChans*nEvents]);\nbInd= band(1): ban(2);\n\n%%calculate file\n\nswitch(lower(epo.scale)),\n    case 'db',\n        for iw= 1:nWindows,\n            XX= XX + abs(fft(dat.x(iv,:).*Win, N)).^2;\n            iv= iv + epo.step;\n        end\n        XX = XX/(nWindows*normwin^2);\n        dat.x= reshape( 10*log10( XX(bInd,:)+eps ), [length(bInd), nChans, nEvents]);\n        dat.yUnit= 'dB';\n    case 'power',\n        for iw= 1:nWindows,\n            XX= XX + abs(fft(dat.x(iv,:).*Win, N).^2);\n            iv= iv + epo.step;\n        end\n        dat.x= reshape(XX(bInd,:)/(nWindows*normwin^2), [length(bInd), nChans, nEvents]);\n        dat.yUnit= 'power';\nend\n\n\n\nend\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/BMI_modules/_Developing/func_powerspectrum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.550152590949963}}
{"text": "function [Y, G, A] = mlpOut(model, X);\n\n% MLPOUT Output of an MLP model.\n% FORMAT \n% DESC gives the output of a multi-layer perceptron model, for\n% single hidden layer models the function is a wrapper for mlpfwd.\n% ARG model : the model for which the output is required.\n% ARG X : the input data for which the output is required.\n% RETURN Y : the output.\n%\n% FORMAT \n% DESC gives the output of a multi-layer perceptron model.\n% ARG model : the model for which the output is required.\n% ARG X : the input data for which the output is required.\n% RETURN Y : the output.\n% RETURN G : the hidden layer activations.\n%\n% SEEALSO : mlpfwd, mlp, modelOut\n%\n% COPYRIGHT : Neil D. Lawrence, 2006, 2007\n\n% MLTOOLS\n\nif length(model.hiddenDim)==1\n  if nargout > 1\n    if nargout > 2\n      [Y, G, A] = mlpfwd(model, X);\n    else\n      [Y, G] = mlpfwd(model, X);\n    end\n  else\n    Y = mlpfwd(model, X);\n  end\nelse\n  ndata = size(x, 1);\n  G{1} = tanh(X*model.w{1} + repmat(model.b{1}, numData, 1));\n  A{1} = G{1}*model.w{2} + repmat(model.b{2}, numData, 1);\n  for i = 2:length(model.numHidden)\n    G{i} = tanh(A{i-1});\n    A{i} = G{i}*model.w{i+1} + repmat(model.b{i+1}, numData, 1);\n  end\n  switch model.outfn\n    \n   case 'linear' \n    y = A{end};\n    \n   otherwise \n    error('Output function not implemented in multiple hidden layer model.')\n    \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/mltools/mlpOut.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5501120389904695}}
{"text": "function [C, d] = spot_ellipsoid(A, b)\n\nn = size(A, 2);\n\n% tic\npr = spotsosprog;\n[pr, t] = pr.newFree(1);\n[pr, Z] = pr.newFree(n, n);\n[pr, C] = pr.newSym(n);\n[pr, d] = pr.newFree(n);\nz = diag(Z);\npr = pr.withPSD([C, Z'; Z, diag(z)]);\nlor = [b - A * d, A * C']';\npr = pr.withLor(lor); \n\nl = ceil(log2(n));\nm = 2^l - n;\nif m > 0\n  x = [z; repmat(t, m, 1)];\nelse\n  x = z;\nend\n[pr, g] = geo_mean_recursive(pr, x);\npr = pr.withEqs(2^(l/2) * t - g);\n\n% fprintf(1, 'setup: %f\\n', toc);\n\n% tic\n% disp('mosek')\n% solver = @spot_mosek;\n% sol = pr.minimize(-t, solver);\n% sol.eval(lor)\n% double(sol.eval(C))\n% double(sol.eval(d))\n% fprintf(1, 'mosek: %f\\n', toc);\n\n% tic\nsolver = @spot_sedumi;\nsol = pr.minimize(-t, solver);\n% sol.eval(lor)\n% fprintf(1, 'sedumi: %f\\n', toc);\n\n% tic\nC = double(sol.eval(C));\nd = double(sol.eval(d));\n% fprintf(1, 'extract: %f\\n', toc);\n\nend\n\nfunction [pr, g] = geo_mean_recursive(pr, x)\n  n = length(x);\n  if n > 1\n    [pr, y] = pr.newFree(n/2);\n    pr = pr.withRLor([reshape(x, 2, n/2); reshape(y, 1, n/2)]);\n    [pr, g] = geo_mean_recursive(pr, y);\n  else\n    g = x;\n  end\nend", "meta": {"author": "rdeits", "repo": "iris-distro", "sha": "ff624610a82a858862d55732136dbc2cc9ab16fc", "save_path": "github-repos/MATLAB/rdeits-iris-distro", "path": "github-repos/MATLAB/rdeits-iris-distro/iris-distro-ff624610a82a858862d55732136dbc2cc9ab16fc/src/matlab/+iris/+inner_ellipsoid/spot_ellipsoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.5501120246202029}}
{"text": "classdef MOEADM2M < ALGORITHM\n% <multi> <real/integer>\n% MOEA/D based on MOP to MOP\n% K --- 10 --- Number of reference vectors\n\n%------------------------------- Reference --------------------------------\n% H. Liu, F. Gu, and Q. Zhang, Decomposition of a multiobjective\n% optimization problem into a number of simple multiobjective subproblems,\n% IEEE Transactions on Evolutionary Computation, 2014, 18(3): 450-455.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Parameter setting\n            K = Algorithm.ParameterSet(10);\n\n            %% Generate random population\n            [W,K]      = UniformPoint(K,Problem.M);\n            Problem.N  = ceil(Problem.N/K)*K;\n            S          = Problem.N/K;\n            Population = Problem.Initialization();\n            Population = Associate(Population,W,S);\n\n            %% Optimization\n            while Algorithm.NotTerminated(Population)\n                MatingPoolLocal      = randi(S,S,K) + repmat(0:S:S*(K-1),S,1);\n                MatingPoolGlobal     = randi(Problem.N,1,Problem.N);\n                rnd                  = rand(S,K) < 0.7;\n                MatingPoolLocal(rnd) = MatingPoolGlobal(rnd);\n                Offspring  = Operator(Problem,Population,Population(MatingPoolLocal(:)));\n                Population = Associate([Population,Offspring],W,S);\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/Algorithms/Multi-objective optimization/MOEA-D-M2M/MOEADM2M.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6442250928250376, "lm_q1q2_score": 0.5501120225347951}}
{"text": "function [TB] = GB2TB(GB)\n% Convert computery things from gigabytes to terabytes.\n% Chad A. Greene 2012\nTB = GB*2^-10 ;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/GB2TB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5501027679824122}}
{"text": "function domOrient3M = calcDominantOrientation(scanArray3M, mask3M, patchSizeV, dim2d3dFlag, hWait)\n% function domOrient3M = calcDominantOrientation(scanArray3M, mask3M, patchSizeV, dim2d3dFlag, hWait)\n%\n% Dominant orientation calculation.\n%\n% APA, 10/14/2016\n\n% Flag to draw waitbar\nwaitbarFlag = 0;\nif exist('hWait','var') & ishandle(hWait)\n    waitbarFlag = 1;\nend\n\n% Get indices of non-NaN voxels\ncalcIndM = ~isnan(scanArray3M) & mask3M;\n\n% % Grid resolution\nslcWindow = 2 * patchSizeV(3) + 1;\nrowWindow = 2 * patchSizeV(1) + 1;\ncolWindow = 2 * patchSizeV(2) + 1;\n\n% Build distance matrices\nnumColsPad = floor(colWindow/2);\nnumRowsPad = floor(rowWindow/2);\nnumSlcsPad = floor(slcWindow/2);\n\n% Get number of voxels per slice\n[numRows, numCols, numSlices] = size(scanArray3M);\nnumVoxels = numRows*numCols;\n\n% Pad q, so that sliding window works also for the edge voxels\nif exist('padarray.m','file')\n    %scanArrayTmp3M = padarray(scanArray3M,[numRowsPad numColsPad\n    %numSlcsPad],NaN,'both'); % aa commented\n    q = padarray(scanArray3M,[numRowsPad numColsPad numSlcsPad],NaN,'both');\nelse\n    q = padarray_oct(scanArray3M,[numRowsPad numColsPad numSlcsPad],NaN,'both');\nend\n\n% Create indices for 2D blocks\n[m,n,~] = size(q);\nm = uint32(m);\nn = uint32(n);\ncolWindow = uint32(colWindow);\nrowWindow = uint32(rowWindow);\nslcWindow = uint32(slcWindow);\n\n% Index calculation adapted from \n% http://stackoverflow.com/questions/25449279/efficient-implementation-of-im2col-and-col2im\n\n%// Start indices for each block\nstart_ind = reshape(bsxfun(@plus,[1:m-rowWindow+1]',[0:n-colWindow]*m),[],1); %//'\n\n%// Row indices\nlin_row = permute(bsxfun(@plus,start_ind,[0:rowWindow-1])',[1 3 2]);  %//'\n\n%// Get linear indices based on row and col indices and get desired output\n% imTmpM = A(reshape(bsxfun(@plus,lin_row,[0:ncols-1]*m),nrows*ncols,[]));\nindM = reshape(bsxfun(@plus,lin_row,(0:colWindow-1)*m),rowWindow*colWindow,[]);\n\n[Fx,Fy] = gradient(q);\n%Fx = abs(Fx);\n%Fy = abs(Fy);\n\ndomOrient3M = zeros(size(scanArray3M));\ndomOrient2M = zeros(size(scanArray3M(:,:,1)));\n\ntic\n% Iterate over slices. compute cooccurance for all patches per slice\nfor slcNum = 1:numSlices %(1+numSlcsPad):(numSlices+numSlcsPad)\n    \n    disp(['--- Orientation Calculation for Slice # ', num2str(slcNum), ' ----']) \n    \n    calcSlcIndV = calcIndM(:,:,slcNum);\n    calcSlcIndV = calcSlcIndV(:);\n    numCalcVoxs = sum(calcSlcIndV);\n    \n    indSlcM = indM(:,calcSlcIndV);\n    \n    FxSlc = Fx(:,:,slcNum+numSlcsPad);\n    FySlc = Fy(:,:,slcNum+numSlcsPad);\n\n    domOrientM = zeros(2,numCalcVoxs);\n    for i = 1:numCalcVoxs % size(indSlcM,2)\n        Y = [FxSlc(indSlcM(:,i)) FySlc(indSlcM(:,i))];\n        Y(sum(isnan(Y),2)>0,:) = [];\n        %pp = pca(Y);\n        %pp1M(:,i) = pp(1,:)';\n        if ~isempty(Y)\n            [Usvd, S, Vsvd] = svd(Y);\n            domOrientM(:,i) = Vsvd(:,1);\n        end\n    end\n    domOrientSlc2M = domOrient2M;\n    domOrientSlc2M(calcSlcIndV) = atan2(domOrientM(2,:),domOrientM(1,:));\n    domOrient3M(:,:,slcNum) = domOrientSlc2M;\n    \n    if waitbarFlag\n        set(hWait, 'Vertices', [[0 0 slcNum/numSlices slcNum/numSlices]' [0 1 1 0]']);\n        drawnow;\n    end \n    \nend\ntoc\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/heterogenity_metrics/calcDominantOrientation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5501027454513645}}
{"text": "classdef EAGMOEAD < ALGORITHM\n% <multi> <real/integer/label/binary/permutation>\n% External archive guided MOEA/D\n% LGs --- 8 --- The number of learning generations\n\n%------------------------------- Reference --------------------------------\n% X. Cai, Y. Li, Z. Fan, and Q. Zhang, An external archive guided\n% multiobjective evolutionary algorithm based on decomposition for\n% combinatorial optimization, IEEE Transactions on Evolutionary\n% Computation, 2015, 19(4): 508-523.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n    methods\n        function main(Algorithm,Problem)\n            %% Parameter setting\n            LGs = Algorithm.ParameterSet(8);\n\n            %% Generate the weight vectors\n            [W,Problem.N] = UniformPoint(Problem.N,Problem.M);\n            T = ceil(Problem.N/10);\n\n            %% Detect the neighbours of each solution\n            B = pdist2(W,W);\n            [~,B] = sort(B,2);\n            B = B(:,1:T);\n\n            %% Generate random population\n            Population = Problem.Initialization();\n            Archive    = Population;            % External archive\n            s          = zeros(Problem.N,LGs);\t% Number of successful solutions in last several generations\n\n            %% Optimization\n            while Algorithm.NotTerminated(Archive)\n                [MatingPool,offspringLoc] = MatingSelection(B,s);\n                Offspring  = OperatorGAhalf(Problem,Population(MatingPool));\n                Population = UpdatePopulation(Population,Offspring,offspringLoc,W,B);\n                [Archive,sucessful] = UpdateArchive(Archive,Offspring);\n                % Update the number of successful solutions generated by\n                % each subproblem in the last LGs generations\n                if any(sucessful)\n                    s(:,mod(ceil(Problem.FE/Problem.N),LGs)+1) = hist(offspringLoc(sucessful),1:Problem.N)';\n                end\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/Algorithms/Multi-objective optimization/EAG-MOEA-D/EAGMOEAD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5500970015513318}}
{"text": "function [err,tree] = l2boost(train_feats, train_y, val_feats, val_y, depth, max_iter, alpha)\n% Run L2-Boosting and test parameters\n    DefaultVal('max_iter',100);\n    residual = train_y;\n    err_increase = 1;\n    pred_train = zeros(numel(train_y),1);\n    pred_val = zeros(numel(val_y),1);\n    for i=1:max_iter\n        tree{i} = classregtree_fuxin(train_feats, residual, 'minleaf',numel(train_y) / 2^(depth-1));\n        if exist('alpha','var')\n            tree{i} = tree{i}.prune('alpha',alpha);\n        end\n        pred_train = pred_train + tree{i}.eval(train_feats);\n        residual = train_y - pred_train;\n        pred_val = pred_val + tree{i}.eval(val_feats);\n        residual_val = val_y - pred_val;\n        err(i) = mean(abs(residual_val))\n        if i > 1 && err(i) >= err(i-1)\n            err_increase = err_increase + 1;\n        else\n            err_increase = 0;\n        end\n        if err_increase > 3\n            break;\n        end\n    end\n    [a,b] = min(err(1:i));\n    tree = tree(1:b);\nend", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/rigor/rigor_src/extern_src/fuxin_lib_src/boosting/l2boost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.5500969876542998}}
{"text": "%   TTeMPS Toolbox. \n%   Michael Steinlechner, 2013-2016\n%   Questions and contact: michael.steinlechner@epfl.ch\n%   BSD 2-clause license, see LICENSE.txt\nfunction [X, residuum, cost, times] = alsLinsolve_fast( L, F, X, opts )\n\nt_start = tic();\n% set default opts\nif ~exist( 'opts', 'var');       opts = struct();       end\nif ~isfield( opts, 'nSweeps');   opts.nSweeps = 4;      end\nif ~isfield( opts, 'solver');    opts.solver = 'pcg';   end\n\nd = X.order;\nn = X.size;\n\n\nnormF = norm(F);\ng = apply(L, X) - F;\ncost = cost_function_res( X, g );\nresiduum = norm( g ) / normF;\ntimes = toc(t_start);\n\nX = orthogonalize(X, 1);\nfor sweep = 1:opts.nSweeps\n    % ====================================================================\n    % LEFT-TO-RIGHT SWEEP\n    % ====================================================================\n    disp( ['STARTING SWEEP ', num2str(sweep), ' from left to right'] )\n    disp( '===========================================================')\n    for idx = 1:d-1\n        disp( ['Current core: ', num2str(idx)] )\n\n        Fi = contract( X, F, idx );\n        sz = [X.rank(idx), X.size(idx), X.rank(idx+1)];\n        \n        if strcmpi( opts.solver, 'direct' )\n            % if system very small\n            Li = contract( L, X, idx );\n            Ui = Li \\ Fi(:);\n            X.U{idx} = reshape( Ui, sz );\n\n        elseif strcmpi( opts.solver, 'pcg' )\n\n            [left, right] = Afun_prepare( L, X, idx );\n            [B2, V, E] =  prepare_precond( L.L0, X, idx );\n\n            Ui = pcg( @(y) Afun( L, y, idx, sz, left, right), ...\n                     Fi(:), ...\n                     1e-10, 1000, ...\n                     @(y) apply_precond( B2, V, E, y, sz ), [],...\n                     X.U{idx}(:) ); \n\n            X.U{idx} = reshape( Ui, sz );\n\n        elseif strcmpi( opts.solver, 'diag' )\n            X.U{idx} = solve_inner( L.L0, X, Fi, idx );\n\n        else\n            error( 'Unknown opts.solver type. Use either ''direct'', ''pcg'' (default) or ''diag''.' )\n        end\n\n        X = orth_at( X, idx, 'left', true );\n        \n        g = apply(L, X) - F;\n        residuum = [residuum; norm( g ) / normF];\n        cost = [cost; cost_function_res( X, g )];\n        times = [times; toc(t_start)];\n    end\n\n    % ====================================================================\n    % RIGHT-TO-LEFT\n    % ====================================================================\n    disp( 'Starting right-to-left half-sweep:')\n    for idx = d:-1:2\n        disp( ['Current core: ', num2str(idx)] )\n\n        Fi = contract( X, F, idx );\n        sz = [X.rank(idx), X.size(idx), X.rank(idx+1)];\n        \n        if strcmpi( opts.solver, 'direct' )\n            % if system very small\n            Li = contract( L, X, idx );\n            Ui = Li \\ Fi(:);\n            X.U{idx} = reshape( Ui, sz );\n\n        elseif strcmpi( opts.solver, 'pcg' )\n\n            [left, right] = Afun_prepare( L, X, idx );\n            [B2, V, E] =  prepare_precond( L.L0, X, idx );\n\n            Ui = pcg( @(y) Afun( L, y, idx, sz, left, right), ...\n                     Fi(:), ...\n                     1e-10, 1000, ...\n                     @(y) apply_precond( B2, V, E, y, sz ), [],...\n                     X.U{idx}(:) ); \n\n\n\n            X.U{idx} = reshape( Ui, sz );\n\n        elseif strcmpi( opts.solver, 'diag' )\n            X.U{idx} = solve_inner( L.L0, X, Fi, idx );\n\n        else\n            error( 'Unknown opts.solver type. Use either ''direct'', ''pcg'' (default) or ''diag''.' )\n        end\n\n\n        X = orth_at( X, idx, 'right', true );\n        \n        g = apply(L, X) - F;\n        residuum = [residuum; norm( g ) / normF];\n        cost = [cost; cost_function_res( X, g )];\n        times = [times; toc(t_start)];\n    end\n    \nend\n\n\nend\n\nfunction res = cost_function( L, X, F )\nres = 0.5*innerprod( X, apply(L, X) ) - innerprod( X, F );\nend\n\nfunction res = cost_function_res( X, res )\nres = 0.5*innerprod( X, res );\nend\n\n\nfunction [left, right] = Afun_prepare( A, x, idx )\n    y = A.apply(x); \n    if idx == 1\n        right = innerprod( x, y, 'RL', idx+1 );\n        left = [];\n    elseif idx == x.order\n        left = innerprod( x, y, 'LR', idx-1 );\n        right = [];\n    else\n        left = innerprod( x, y, 'LR', idx-1 );\n        right = innerprod( x, y, 'RL', idx+1 ); \n    end\nend\n\nfunction res = Afun( A, U, idx, sz, left, right )\n\n    V = reshape( U, sz );\n    V = A.apply( V, idx );\n    \n    if idx == 1\n        tmp = tensorprod_ttemps( V, right, 3 );\n    elseif idx == A.order\n        tmp = tensorprod_ttemps( V, left, 1 );\n    else\n        tmp = tensorprod_ttemps( V, right, 3);\n        tmp = tensorprod_ttemps( tmp, left, 1);\n    end\n\n    res = tmp(:);\nend\n\n%function res = apply_local_precond( A, U, sz, expB)\n%\n%    p = size(U, 2);\n%\n%    x = reshape( U, [sz, p] );\n%    res = zeros( [sz, p] );\n%\n%    for i = 1:size( expB, 1)\n%        tmp = reshape( x, [sz(1), sz(2)*sz(3)*p] );\n%        tmp = reshape( expB{1,i}*tmp, [sz(1), sz(2), sz(3), p] );\n%\n%        tmp = reshape( permute( tmp, [2 1 3 4] ), [sz(2), sz(1)*sz(3)*p] );\n%        tmp = ipermute( reshape( expB{2,i}*tmp, [sz(2), sz(1), sz(3), p] ), [2 1 3 4] );\n%\n%        tmp = reshape( permute( tmp, [3 1 2 4] ), [sz(3), sz(1)*sz(2)*p] );\n%        tmp = ipermute( reshape( expB{3,i}*tmp, [sz(3), sz(1), sz(2), p] ), [3 1 2 4] );\n%\n%        res = res + tmp;\n%    end\n%    res = reshape( res, [prod(sz), p] );\n%    \n%end\n\nfunction res = solve_inner( L0, X, Fi, idx )\n    n = size(L0, 1);\n    rl = X.rank(idx);\n    rr = X.rank(idx+1);\n\n    B1 = zeros( rl );\n    % calculate B1 part:\n    for i = 1:idx-1\n        % apply L to the i'th core\n        tmp = X;\n        tmp.U{i} = tensorprod_ttemps( tmp.U{i}, L0, 2 );\n        B1 = B1 + innerprod( X, tmp, 'LR', idx-1);\n    end\n\n    % calculate B2 part:\n    B2 = L0;\n\n    B3 = zeros( rr );\n    % calculate B3 part:\n    for i = idx+1:X.order\n        tmp = X;\n        tmp.U{i} = tensorprod_ttemps( tmp.U{i}, L0, 2 );\n        B3 = B3 + innerprod( X, tmp, 'RL', idx+1);\n    end\n\n    [V,E] = eig( kron( eye(rr), B1 ) + kron( B3, eye(rl) ) );\n    E = diag(E);\n\n    rhs = matricize( Fi, 2 ) * V;\n    Y = zeros(size(rhs));\n    for i=1:length(E)\n        Y(:,i) = (B2 + E(i)*speye(n)) \\ rhs(:,i);\n    end\n    res = tensorize( Y*V', 2, [rl, n, rr] );\nend\n\nfunction [B2, V, E] = prepare_precond( L0, X, idx )\n    n = size(L0, 1);\n    rl = X.rank(idx);\n    rr = X.rank(idx+1);\n\n    B1 = zeros( rl );\n    % calculate B1 part:\n    for i = 1:idx-1\n        % apply L to the i'th core\n        tmp = X;\n        tmp.U{i} = tensorprod_ttemps( tmp.U{i}, L0, 2 );\n        B1 = B1 + innerprod( X, tmp, 'LR', idx-1);\n    end\n\n    % calculate B2 part:\n    B2 = L0;\n\n    B3 = zeros( rr );\n    % calculate B3 part:\n    for i = idx+1:X.order\n        tmp = X;\n        tmp.U{i} = tensorprod_ttemps( tmp.U{i}, L0, 2 );\n        B3 = B3 + innerprod( X, tmp, 'RL', idx+1);\n    end\n\n    [V,E] = eig( kron( eye(rr), B1 ) + kron( B3, eye(rl) ) );\n    E = diag(E);\nend\n\nfunction res = apply_precond( B2, V, E, rhs, sz )\n    n = size(B2, 1);\n    rhs = reshape( rhs, sz );\n    rhs = matricize( rhs, 2 ) * V;\n    Y = zeros(size(rhs));\n    for i=1:length(E)\n        Y(:,i) = (B2 + E(i)*speye(n)) \\ rhs(:,i);\n    end\n    res = tensorize( Y*V', 2, sz );\n    res = res(:);\nend\n\n\n\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/algorithms/linearsystem/alsLinsolve_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.550096979768708}}
{"text": "function y = acoth(x)\n%ACOTH        Implements  acoth(x)  for intervals\n%\n%   y = acoth(x)\n%\n%interval standard function implementation\n%\n\n% written  10/16/98     S.M. Rump\n% modified 12/30/98     S.M. Rump  improved speed and use atanh\n% modified 08/31/99     S.M. Rump  complex allowed, sparse input,\n%                                  major revision, improved accuracy near 1\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% modified 04/06/05     S.M. Rump  rounding unchanged\n% modified 12/04/05     S.M. Rump  'realstdfctsexcptnignore' added and\n%                                     some improvements, extreme values \n%                                     for approximate part\n% modified 09/06/07     S.M. Rump  approximate std fcts removed, exceptional arguments\n% modified 09/28/08     S.M. Rump  check for rounding to nearest improved\n% modified 10/20/08     S.M. Rump  check for zero omitted\n% modified 10/18/08     S.M. Rump  StdFctsException ignore/NaN\n% modified 08/26/12     S.M. Rump  global variables removed\n% modified 10/13/12     S.M. Rump  INTLAB_INTVAL_STDFCTS\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 x.complex\n    if issparse(x.mid)\n      x.mid = full(x.mid);\n      x.rad = full(x.rad);\n    end\n    y = atanh( 1./x );\n    if rndold\n      setround(rndold)\n    end\n    return\n  end\n  \n  if issparse(x.inf)\n    x.inf = full(x.inf);\n    x.sup = full(x.sup);\n  end\n  % input x real and full\n  % real range of definition:  [-inf,-1] and [1,inf]\n  % take care for intersection( x , (-1,1) ) nonempty\n  INTLAB_STDFCTS_EXCPTN = getappdata(0,'INTLAB_STDFCTS_EXCPTN');\n  Index1 = ( abs(x.inf)<1 );           % (partially) exceptional indices\n  Index2 = ( abs(x.sup)<1 ); \n  if ~isempty(find(Index1)) | ~isempty(find(Index2))   % handle input out-of-range\n    if INTLAB_STDFCTS_EXCPTN<=1 % out-of-range input handled as complex\n      if INTLAB_STDFCTS_EXCPTN==1\n        warning('ACOTH: Real interval input out of range changed to be complex')\n      end\n      y = x;\n      index = Index1 | Index2;\n      %VVVV  y(index) = atanh(cintval(1./x(index)));\n      s.type = '()'; s.subs = {index}; y = subsasgn(y,s,atanh(cintval(1./subsref(x,s))));\n      %AAAA  Matlab bug fix\n      index = ~index;\n      if any(index(:))\n        %VVVV  y(index) = atanh(1./x(index));\n        s.type = '()'; s.subs = {index}; y = subsasgn(y,s,atanh(1./subsref(x,s)));\n        %AAAA  Matlab bug fix\n      end\n      index = ( x==0 );\n      if any(index(:))\n        INTLAB_STDFCTS_PI = getappdata(0,'INTLAB_STDFCTS_PI');\n        iPI2 = intval(j*INTLAB_STDFCTS_PI.PI2MID,INTLAB_STDFCTS_PI.PI2RAD,'midrad');\n        %VVVV  y(index) = iPI2;\n        s.type = '()'; s.subs = {index}; y = subsasgn(y,s,iPI2);\n        %AAAA  Matlab bug fix\n      end\n      if rndold\n        setround(rndold)\n      end\n      return\n    end\n    setappdata(0,'INTLAB_STDFCTS_EXCPTN_',1);\n    if INTLAB_STDFCTS_EXCPTN==3    % ignore input out of range (ignore-mode)\n      x.inf(Index1) = 1;                  % completely exceptional indices treated below\n      x.sup(Index2) = -1;\n      Index = ( Index1 & Index2 );        % completely exceptional indices\n    end\n  else\n    Index = [];                           % make sure Index is not undefined\n  end\n  \n  % input x real and full\n  y = x;\n  wng = warning;                         % get current warning mode\n  warning off\n  \n  % treat positive intervals\n  index1 = ( x.inf>0 );\n  if any(index1(:))\n    y.inf(index1) = acoth_pos(x.sup(index1),-1);\n    y.sup(index1) = acoth_pos(x.inf(index1),1);\n  end\n\n  % treat negative intervals\n  index1 = ( x.sup<0 );\n  if any(index1(:))\n    y.inf(index1) = - acoth_pos(-x.sup(index1),1);\n    y.sup(index1) = - acoth_pos(-x.inf(index1),-1);\n  end\n    \n  if INTLAB_STDFCTS_EXCPTN==3      % ignore input out of range (ignore-mode)\n    if ~isempty(find(Index))              % completely exceptional arguments to NaN\n      y.inf(Index) = NaN;\n      y.sup(Index) = NaN;\n    end\n  else                                    % any input out of range to NaN (NaN-mode)\n    Index = Index1 | Index2;\n    if ~isempty(find(Index))              % exceptional arguments to NaN\n      y.inf(Index) = NaN;\n      y.sup(Index) = NaN;\n    end\n  end\n    \n  setround(rndold)\n  warning(wng)                           % restore warning mode\n\n  \n\nfunction y = acoth_pos(x,rnd)\n% local acoth for double vector x>=1 with rounding corresponding to rnd\n%\n\n  y = x;\n\n  index = ( x<4 );\n  if any(index(:))             % 1 <= x <= 4\n    setround(rnd)              % acoth(x) = log( 1 + 2/(x-1) )\n    e = x(index) - 1;          % e w/o rounding error\n    e = 1 + 2./e;\n    y(index) = log_rnd( e , rnd ) / 2;\n    y(x==1) = inf;\n  end\n\n  index = ~index;              % x >= 4, difference x-1 not necessarily exact\n  if any(index(:))             % acoth(x) = atanh(1/x)\n    setround(rnd)\n    e = 1./x(index);\n    y(index) = atanh_pos( e , rnd );\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/acoth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5500969656659365}}
{"text": "function [insideNodes,insideNodeStruct] = floodFillFindPerim2(mesh,perimDist,startNode)\n% A flood-fill method to find the mesh perimeter\n%\n% [insideNodes,insideNodeStruct]=floodFillFindPerim2(mesh,perimDist,startNode,busyHandle)\n%\n% Find expanding rings connected to the start node. \n% Stop when all the members of the ring exceed perimDist from the startNode\n% But cleverer than this :)\n%\n% Also stores the average distance of each new set and its offset - May be\n% useful for tacking down points later This can break quite easily - for\n% example when the floodfill runs around all sides of a bump. But we can\n% fix this later  ...\n%\n% AUTHOR:  Wade\n% DATE : 020701 last modified\n \n\nallWithinDist = 1;\ninsideNodes   = startNode;\ncurrentNodes  = startNode;\ncounter       = 0;\ninsideNodeStruct.offset = 0;\ninsideNodeStruct.avDist = 0;\nnVerts = length(mesh.connectionMatrix);\n\n% Limit to generate no more that 10000 rings....\nwhile ((allWithinDist) && (counter<10000)) \n   \n   % What nodes are connected to the current ones?\n   [newRows connected]=find(mesh.connectionMatrix(currentNodes,:));\n \n   if (~isempty(connected))\n\n      connected=unique(connected(:));   \n      insideNodes=[insideNodes;connected];\n      \n      currentNodes=connected;\n\t  notCnodes=setdiff(1:nVerts,currentNodes);\n\t  \n\t  % This is a cute way of zeroing columns in a sparse matrix. Much\n\t  % faster than foo(:,currentNodes)=0;  \n\t  diagMat=sparse(notCnodes,notCnodes,ones(length(notCnodes),1),nVerts,nVerts);\n\t  mesh.connectionMatrix=(mesh.connectionMatrix)*(diagMat);\n   \n\t  nodeDists=mesh.dist(currentNodes);\n      f=find(nodeDists<perimDist);     \n      allWithinDist=(sum(f(:)));\n      \n      % Average distance\n      insideNodeStruct.avDist=[insideNodeStruct.avDist;mean(nodeDists(:))];\n      \n      % Offset to the list of current rings\n      insideNodeStruct.offset=[insideNodeStruct.offset;length(connected)];\n          \n   else\n         allWithinDist=0;\n   end   \n   \n   counter=counter+1; \n   \nend\n\ninsideNodes=unique(insideNodes);\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/mrAnatomy/mrFlatMesh/mrFlatMeshNifti/floodFillFindPerim2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5500969602717154}}
{"text": "function eframes = vl_frame2oell(frames)\n% FRAMES2OELL   Convert generic feature frames to oriented ellipses\n%   EFRAMES = VL_FRAME2OELL(FRAMES) converts the specified FRAMES to\n%   the oriented ellipses EFRAMES.\n%\n%   A frame is either a point, disc, oriented disc, ellipse, or\n%   oriented ellipse. These are represened respecively by\n%   2, 3, 4, 5 and 6 parameters each, as described in VL_PLOTFRAME().\n%\n%   An oriented ellipse is the most general frame. When an unoriented\n%   frame is converted to an oriented ellipse, the rotation is selected\n%   so that the positive Y direction is unchanged.\n%\n%   See: VL_PLOTFRAME(), VL_HELP().\n\n% Author: Andrea Vedaldi\n\n% Copyright (C) 2013 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n[D,K] = size(frames) ;\neframes = zeros(6,K) ;\n\nswitch D\n  case 2\n    eframes(1:2,:) = frames(1:2,:) ;\n\n  case 3\n    eframes(1:2,:) = frames(1:2,:) ;\n    eframes(3,:)   = frames(3,:) ;\n    eframes(6,:)   = frames(3,:) ;\n\n  case 4\n    r = frames(3,:) ;\n    c = r.*cos(frames(4,:)) ;\n    s = r.*sin(frames(4,:)) ;\n\n    eframes(1:2,:) = frames(1:2,:) ;\n    eframes(3:6,:) = [c ; s ; -s ; c] ;\n\n  case 5\n    eframes(1:2,:) = frames(1:2,:) ;\n    eframes(3:6,:) = mapFromS(frames(3:5,:)) ;\n\n  case 6\n    eframes = frames ;\n\n  otherwise\n     error('FRAMES format is unknown.') ;\nend\n\n% --------------------------------------------------------------------\nfunction A = mapFromS(S)\n% --------------------------------------------------------------------\n% Returns the (stacking of the) 2x2 matrix A that maps the unit circle\n% into the ellipses satisfying the equation x' inv(S) x = 1. Here S\n% is a stacked covariance matrix, with elements S11, S12 and S22.\n%\n% The goal is to find A such that AA' = S. In order to let the Y\n% direction unaffected (upright feature), the assumption is taht\n% A = [a b ; 0 c]. Hence\n%\n%  AA' = [a^2, ab ; ab, b^2+c^2] = S.\n\nA = zeros(4,size(S,2)) ;\na = sqrt(S(1,:));\nb = S(2,:) ./ max(a, 1e-18) ;\n\nA(1,:) = a ;\nA(2,:) = b ;\nA(4,:) = sqrt(max(S(3,:) - b.*b, 0)) ;\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/vlfeat/toolbox/sift/vl_frame2oell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.5500739236021823}}
{"text": "function B = colFirstNonZero(A)\n    % Get first non zero element of each column of a matrix\n    % SYNTAX:\n    % B = colFirstNonZero(A)\n    [~, c] = max( A ~=0, [], 1 );\n    d = (0 : (size(A, 2) - 1)) * size(A, 1) + c;\n    B = A(d);\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/colFirstNonZero.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5500739024521792}}
{"text": "%**************************************************************************\n% Q Learning applied to Cart-Pole balancing problem.\n% The environment of the learning system is a black box, from which it has\n% several lines and a reinforcement line. Its task is to learn to give\n% responses which maximize the scalar signals on its reinforcement line.\n% The Q-value update is the following, if the system takes action a from     \n%   state s at time t, and arrives at state ss with feedback r at time t+1:  \n%                                                                              \n%   Q(t+1, s, a) = Q(t, s, a)                                                  \n%                  + alpha (r + gamma max_{b}Q(t,ss, b) - Q(t, s, a)) \n\n\n% get_box:  Given the current state, returns a number from 1 to 162\n%           designating the region of the state space encompassing the current \n%           state.\n%           Returns a value of -1 if a failure state is encountered.\n\n% cart_pole: The cart and pole dynamics; given the Force and\n%            current state, estimates next state\n\n%Code written by: Savinay Nagendra\n%email id:        nagsavi17@gmail.com \n%**************************************************************************\nclc;\nclear all;\nclose all;\n% Initialization\n\nNUM_BOXES = 163;\nALPHA = 0.4;             % Learning rate parameter\nGAMMA = 0.999;           % Discount factor for future reinf\nQ = zeros(NUM_BOXES,2);  % State-Action Values\naction = [30 -30];\nMAX_FAILURES = 1000;\nMAX_STEPS = 150000;\nepsilon = 0;\nsteps = 0;\nfailures = 0;\nthetaPlot = 0;\nxPlot = 0;\n%Pendulum state initialization\ntheta = 0;\nthetaDot = 0;\nx = 0;\nxDot = 0;\nbox = getBox4(theta,thetaDot,x,xDot);\n\nwhile(steps<=MAX_STEPS && failures<+MAX_FAILURES)\n    steps = steps + 1;\n    \n    % choose either explore or exploit\n    if(rand>epsilon)       % exploit\n        [~,actionMax] = max(Q(box,:));\n        currentAction = action(actionMax);\n    else                   % explore\n        currentAction = datasample(action,1);\n    end\n    \n    actionIndex = find(action == currentAction); % index of chosen action\n    %Apply action to the simulated cart pole\n    [thetaNext,thetaDotNext,thetaacc,xNext,xDotNext] = cart_pole2(currentAction,theta,thetaDot,x,xDot);\n    %Get box of state space containing the resulting state\n    thetaPlot(end + 1) = thetaNext;\n    xPlot(end + 1) = xNext;\n    newBox = getBox4(thetaNext,thetaDotNext,xNext,xDotNext);\n    theta = thetaNext;\n    thetaDot = thetaDotNext;\n    x = xNext;\n    xDot = xDotNext;\n    if(newBox==163)\n        r = -1;\n        Q(newBox,:) = 0;\n        figure(2);\n        plot((1:length(thetaPlot)),thetaPlot,'-ob');\n        figure(3);\n        plot((1:length(xPlot)),xPlot,'-og');\n\n        thetaPlot = 0;\n        xPlot = 0;\n        theta = 0;\n        thetaDot = 0;\n        x = 0;\n        xDot = 0;\n        newBox = getBox4(theta,thetaDot,x,xDot);\n        failures = failures + 1;\n        fprintf('Trial %d was %d steps. \\n',failures,steps);\n        figure(1);\n        plot(failures,steps,'-or');\n        hold on;\n        steps = 0;\n    else\n        r = 0;\n    end\n    Q(box,actionIndex) = Q(box,actionIndex) + ALPHA*(r + GAMMA*max(Q(newBox,:)) - Q(box,actionIndex));\n    box = newBox;\nend\nif(failures == MAX_FAILURES)\n    fprintf('Pole not balanced. Stopping after %d failures.',failures);\nelse\n    fprintf('Pole balanced successfully for at least %d steps\\n', steps);\n    figure(1);\n    plot(failures+1,steps,'-or');\n    hold on;\n    figure(2);\n    plot((1:length(thetaPlot)),thetaPlot,'-ob');\n    figure(3);\n    plot((1:length(xPlot)),xPlot,'-og');\n    figure(4);\n    plot((1:301),thetaPlot(1:301),'-ob');\n    hold on;\n    figure(5);\n    plot((1:301),xPlot(1:301),'-og');\n    hold on;\nend\n\n    \n    \n        \n    \n    \n\n    \n    \n    \n\n\n\n\n", "meta": {"author": "savinay95n", "repo": "Reinforcement-learning-Algorithms-and-Dynamic-Programming", "sha": "ab531f4c5856e20800c64932a06d246c91c7f62c", "save_path": "github-repos/MATLAB/savinay95n-Reinforcement-learning-Algorithms-and-Dynamic-Programming", "path": "github-repos/MATLAB/savinay95n-Reinforcement-learning-Algorithms-and-Dynamic-Programming/Reinforcement-learning-Algorithms-and-Dynamic-Programming-ab531f4c5856e20800c64932a06d246c91c7f62c/QLearningCartPoleLeastTrials.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5500070491988996}}
{"text": "clear classes\n\nW = diag([0.1, 1*pi/180].^2);\nP0 = diag([0.005, 0.005, 0.001].^2);\nV = diag([0.005, 0.5*pi/180].^2);\n\nrandinit\nmap = Map(20, 10);\nveh = Vehicle(V);\nRandomPath(veh, map.dim);\nsensor = RangeBearingSensor(veh, map, W);\nsensor.interval = 5;\nekf = EKF(veh, W, P0, sensor, W);\n\nrandinit\nekf.run(1000);\n\n\n\nf1\nclf\nmap.visualize()\nveh.plot_xy('b');\nekf.plot_xy('r');\nekf.plot_ellipse([], 'k')\ngrid on\nxyzlabel\n\nf2\nclf\nekf.plot_P()\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/unit_test/old/loc_map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5500070358285135}}
